]> git.proxmox.com Git - mirror_frr.git/blob - lib/vty.c
Merge pull request #3720 from donaldsharp/bgp_vrf_peering
[mirror_frr.git] / lib / vty.c
1 /*
2 * Virtual terminal [aka TeletYpe] interface routine.
3 * Copyright (C) 1997, 98 Kunihiro Ishiguro
4 *
5 * This file is part of GNU Zebra.
6 *
7 * GNU Zebra is free software; you can redistribute it and/or modify it
8 * under the terms of the GNU General Public License as published by the
9 * Free Software Foundation; either version 2, or (at your option) any
10 * later version.
11 *
12 * GNU Zebra is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License along
18 * with this program; see the file COPYING; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22 #include <zebra.h>
23
24 #include <lib/version.h>
25 #include <sys/types.h>
26 #include <regex.h>
27 #include <stdio.h>
28
29 #include "linklist.h"
30 #include "thread.h"
31 #include "buffer.h"
32 #include "command.h"
33 #include "sockunion.h"
34 #include "memory.h"
35 #include "log.h"
36 #include "prefix.h"
37 #include "filter.h"
38 #include "vty.h"
39 #include "privs.h"
40 #include "network.h"
41 #include "libfrr.h"
42 #include "frrstr.h"
43 #include "lib_errors.h"
44 #include "northbound_cli.h"
45
46 #include <arpa/telnet.h>
47 #include <termios.h>
48
49 DEFINE_MTYPE_STATIC(LIB, VTY, "VTY")
50 DEFINE_MTYPE_STATIC(LIB, VTY_OUT_BUF, "VTY output buffer")
51 DEFINE_MTYPE_STATIC(LIB, VTY_HIST, "VTY history")
52
53 /* Vty events */
54 enum event {
55 VTY_SERV,
56 VTY_READ,
57 VTY_WRITE,
58 VTY_TIMEOUT_RESET,
59 #ifdef VTYSH
60 VTYSH_SERV,
61 VTYSH_READ,
62 VTYSH_WRITE
63 #endif /* VTYSH */
64 };
65
66 static void vty_event(enum event, int, struct vty *);
67
68 /* Extern host structure from command.c */
69 extern struct host host;
70
71 /* Vector which store each vty structure. */
72 static vector vtyvec;
73
74 /* Vty timeout value. */
75 static unsigned long vty_timeout_val = VTY_TIMEOUT_DEFAULT;
76
77 /* Vty access-class command */
78 static char *vty_accesslist_name = NULL;
79
80 /* Vty access-calss for IPv6. */
81 static char *vty_ipv6_accesslist_name = NULL;
82
83 /* VTY server thread. */
84 static vector Vvty_serv_thread;
85
86 /* Current directory. */
87 char *vty_cwd = NULL;
88
89 /* Exclusive configuration lock. */
90 struct vty *vty_exclusive_lock;
91
92 /* Login password check. */
93 static int no_password_check = 0;
94
95 /* Integrated configuration file path */
96 static char integrate_default[] = SYSCONFDIR INTEGRATE_DEFAULT_CONFIG;
97
98 static int do_log_commands = 0;
99
100 void vty_frame(struct vty *vty, const char *format, ...)
101 {
102 va_list args;
103
104 va_start(args, format);
105 vsnprintf(vty->frame + vty->frame_pos,
106 sizeof(vty->frame) - vty->frame_pos, format, args);
107 vty->frame_pos = strlen(vty->frame);
108 va_end(args);
109 }
110
111 void vty_endframe(struct vty *vty, const char *endtext)
112 {
113 if (vty->frame_pos == 0 && endtext)
114 vty_out(vty, "%s", endtext);
115 vty->frame_pos = 0;
116 }
117
118 bool vty_set_include(struct vty *vty, const char *regexp)
119 {
120 int errcode;
121 bool ret = true;
122 char errbuf[256];
123
124 if (!regexp) {
125 if (vty->filter) {
126 regfree(&vty->include);
127 vty->filter = false;
128 }
129 return true;
130 }
131
132 errcode = regcomp(&vty->include, regexp,
133 REG_EXTENDED | REG_NEWLINE | REG_NOSUB);
134 if (errcode) {
135 ret = false;
136 regerror(ret, &vty->include, errbuf, sizeof(errbuf));
137 vty_out(vty, "%% Regex compilation error: %s", errbuf);
138 } else {
139 vty->filter = true;
140 }
141
142 return ret;
143 }
144
145 /* VTY standard output function. */
146 int vty_out(struct vty *vty, const char *format, ...)
147 {
148 va_list args;
149 int len = 0;
150 int size = 1024;
151 char buf[1024];
152 char *p = NULL;
153 char *filtered;
154
155 if (vty->frame_pos) {
156 vty->frame_pos = 0;
157 vty_out(vty, "%s", vty->frame);
158 }
159
160 /* Try to write to initial buffer. */
161 va_start(args, format);
162 len = vsnprintf(buf, sizeof(buf), format, args);
163 va_end(args);
164
165 /* Initial buffer is not enough. */
166 if (len < 0 || len >= size) {
167 while (1) {
168 if (len > -1)
169 size = len + 1;
170 else
171 size = size * 2;
172
173 p = XREALLOC(MTYPE_VTY_OUT_BUF, p, size);
174 if (!p)
175 return -1;
176
177 va_start(args, format);
178 len = vsnprintf(p, size, format, args);
179 va_end(args);
180
181 if (len > -1 && len < size)
182 break;
183 }
184 }
185
186 /* When initial buffer is enough to store all output. */
187 if (!p)
188 p = buf;
189
190 /* filter buffer */
191 if (vty->filter) {
192 vector lines = frrstr_split_vec(p, "\n");
193
194 /* Place first value in the cache */
195 char *firstline = vector_slot(lines, 0);
196 buffer_put(vty->lbuf, (uint8_t *) firstline, strlen(firstline));
197
198 /* If our split returned more than one entry, time to filter */
199 if (vector_active(lines) > 1) {
200 /*
201 * returned string is MTYPE_TMP so it matches the MTYPE
202 * of everything else in the vector
203 */
204 char *bstr = buffer_getstr(vty->lbuf);
205 buffer_reset(vty->lbuf);
206 XFREE(MTYPE_TMP, lines->index[0]);
207 vector_set_index(lines, 0, bstr);
208 frrstr_filter_vec(lines, &vty->include);
209 vector_compact(lines);
210 /*
211 * Consider the string "foo\n". If the regex is an empty string
212 * and the line ended with a newline, then the vector will look
213 * like:
214 *
215 * [0]: 'foo'
216 * [1]: ''
217 *
218 * If the regex isn't empty, the vector will look like:
219 *
220 * [0]: 'foo'
221 *
222 * In this case we'd like to preserve the newline, so we add
223 * the empty string [1] as in the first example.
224 */
225 if (p[strlen(p) - 1] == '\n' && vector_active(lines) > 0
226 && strlen(vector_slot(lines, vector_active(lines) - 1)))
227 vector_set(lines, XSTRDUP(MTYPE_TMP, ""));
228
229 filtered = frrstr_join_vec(lines, "\n");
230 }
231 else {
232 filtered = NULL;
233 }
234
235 frrstr_strvec_free(lines);
236
237 } else {
238 filtered = p;
239 }
240
241 if (!filtered)
242 goto done;
243
244 switch (vty->type) {
245 case VTY_TERM:
246 /* print with crlf replacement */
247 buffer_put_crlf(vty->obuf, (uint8_t *)filtered,
248 strlen(filtered));
249 break;
250 case VTY_SHELL:
251 fprintf(vty->of, "%s", filtered);
252 fflush(vty->of);
253 break;
254 case VTY_SHELL_SERV:
255 case VTY_FILE:
256 default:
257 /* print without crlf replacement */
258 buffer_put(vty->obuf, (uint8_t *)filtered, strlen(filtered));
259 break;
260 }
261
262 done:
263
264 if (vty->filter && filtered)
265 XFREE(MTYPE_TMP, filtered);
266
267 /* If p is not different with buf, it is allocated buffer. */
268 if (p != buf)
269 XFREE(MTYPE_VTY_OUT_BUF, p);
270
271 return len;
272 }
273
274 static int vty_log_out(struct vty *vty, const char *level,
275 const char *proto_str, const char *format,
276 struct timestamp_control *ctl, va_list va)
277 {
278 int ret;
279 int len;
280 char buf[1024];
281
282 if (!ctl->already_rendered) {
283 ctl->len = quagga_timestamp(ctl->precision, ctl->buf,
284 sizeof(ctl->buf));
285 ctl->already_rendered = 1;
286 }
287 if (ctl->len + 1 >= sizeof(buf))
288 return -1;
289 memcpy(buf, ctl->buf, len = ctl->len);
290 buf[len++] = ' ';
291 buf[len] = '\0';
292
293 if (level)
294 ret = snprintf(buf + len, sizeof(buf) - len, "%s: %s: ", level,
295 proto_str);
296 else
297 ret = snprintf(buf + len, sizeof(buf) - len, "%s: ", proto_str);
298 if ((ret < 0) || ((size_t)(len += ret) >= sizeof(buf)))
299 return -1;
300
301 if (((ret = vsnprintf(buf + len, sizeof(buf) - len, format, va)) < 0)
302 || ((size_t)((len += ret) + 2) > sizeof(buf)))
303 return -1;
304
305 buf[len++] = '\r';
306 buf[len++] = '\n';
307
308 if (write(vty->wfd, buf, len) < 0) {
309 if (ERRNO_IO_RETRY(errno))
310 /* Kernel buffer is full, probably too much debugging
311 output, so just
312 drop the data and ignore. */
313 return -1;
314 /* Fatal I/O error. */
315 vty->monitor =
316 0; /* disable monitoring to avoid infinite recursion */
317 flog_err(EC_LIB_SOCKET,
318 "%s: write failed to vty client fd %d, closing: %s",
319 __func__, vty->fd, safe_strerror(errno));
320 buffer_reset(vty->obuf);
321 buffer_reset(vty->lbuf);
322 /* cannot call vty_close, because a parent routine may still try
323 to access the vty struct */
324 vty->status = VTY_CLOSE;
325 shutdown(vty->fd, SHUT_RDWR);
326 return -1;
327 }
328 return 0;
329 }
330
331 /* Output current time to the vty. */
332 void vty_time_print(struct vty *vty, int cr)
333 {
334 char buf[QUAGGA_TIMESTAMP_LEN];
335
336 if (quagga_timestamp(0, buf, sizeof(buf)) == 0) {
337 zlog_info("quagga_timestamp error");
338 return;
339 }
340 if (cr)
341 vty_out(vty, "%s\n", buf);
342 else
343 vty_out(vty, "%s ", buf);
344
345 return;
346 }
347
348 /* Say hello to vty interface. */
349 void vty_hello(struct vty *vty)
350 {
351 if (host.motdfile) {
352 FILE *f;
353 char buf[4096];
354
355 f = fopen(host.motdfile, "r");
356 if (f) {
357 while (fgets(buf, sizeof(buf), f)) {
358 char *s;
359 /* work backwards to ignore trailling isspace()
360 */
361 for (s = buf + strlen(buf);
362 (s > buf) && isspace((int)*(s - 1)); s--)
363 ;
364 *s = '\0';
365 vty_out(vty, "%s\n", buf);
366 }
367 fclose(f);
368 } else
369 vty_out(vty, "MOTD file not found\n");
370 } else if (host.motd)
371 vty_out(vty, "%s", host.motd);
372 }
373
374 /* Put out prompt and wait input from user. */
375 static void vty_prompt(struct vty *vty)
376 {
377 if (vty->type == VTY_TERM) {
378 vty_out(vty, cmd_prompt(vty->node), cmd_hostname_get());
379 }
380 }
381
382 /* Send WILL TELOPT_ECHO to remote server. */
383 static void vty_will_echo(struct vty *vty)
384 {
385 unsigned char cmd[] = {IAC, WILL, TELOPT_ECHO, '\0'};
386 vty_out(vty, "%s", cmd);
387 }
388
389 /* Make suppress Go-Ahead telnet option. */
390 static void vty_will_suppress_go_ahead(struct vty *vty)
391 {
392 unsigned char cmd[] = {IAC, WILL, TELOPT_SGA, '\0'};
393 vty_out(vty, "%s", cmd);
394 }
395
396 /* Make don't use linemode over telnet. */
397 static void vty_dont_linemode(struct vty *vty)
398 {
399 unsigned char cmd[] = {IAC, DONT, TELOPT_LINEMODE, '\0'};
400 vty_out(vty, "%s", cmd);
401 }
402
403 /* Use window size. */
404 static void vty_do_window_size(struct vty *vty)
405 {
406 unsigned char cmd[] = {IAC, DO, TELOPT_NAWS, '\0'};
407 vty_out(vty, "%s", cmd);
408 }
409
410 #if 0 /* Currently not used. */
411 /* Make don't use lflow vty interface. */
412 static void
413 vty_dont_lflow_ahead (struct vty *vty)
414 {
415 unsigned char cmd[] = { IAC, DONT, TELOPT_LFLOW, '\0' };
416 vty_out (vty, "%s", cmd);
417 }
418 #endif /* 0 */
419
420 /* Authentication of vty */
421 static void vty_auth(struct vty *vty, char *buf)
422 {
423 char *passwd = NULL;
424 enum node_type next_node = 0;
425 int fail;
426 char *crypt(const char *, const char *);
427
428 switch (vty->node) {
429 case AUTH_NODE:
430 if (host.encrypt)
431 passwd = host.password_encrypt;
432 else
433 passwd = host.password;
434 if (host.advanced)
435 next_node = host.enable ? VIEW_NODE : ENABLE_NODE;
436 else
437 next_node = VIEW_NODE;
438 break;
439 case AUTH_ENABLE_NODE:
440 if (host.encrypt)
441 passwd = host.enable_encrypt;
442 else
443 passwd = host.enable;
444 next_node = ENABLE_NODE;
445 break;
446 }
447
448 if (passwd) {
449 if (host.encrypt)
450 fail = strcmp(crypt(buf, passwd), passwd);
451 else
452 fail = strcmp(buf, passwd);
453 } else
454 fail = 1;
455
456 if (!fail) {
457 vty->fail = 0;
458 vty->node = next_node; /* Success ! */
459 } else {
460 vty->fail++;
461 if (vty->fail >= 3) {
462 if (vty->node == AUTH_NODE) {
463 vty_out(vty,
464 "%% Bad passwords, too many failures!\n");
465 vty->status = VTY_CLOSE;
466 } else {
467 /* AUTH_ENABLE_NODE */
468 vty->fail = 0;
469 vty_out(vty,
470 "%% Bad enable passwords, too many failures!\n");
471 vty->status = VTY_CLOSE;
472 }
473 }
474 }
475 }
476
477 /* Command execution over the vty interface. */
478 static int vty_command(struct vty *vty, char *buf)
479 {
480 int ret;
481 const char *protocolname;
482 char *cp = NULL;
483
484 assert(vty);
485
486 /*
487 * Log non empty command lines
488 */
489 if (do_log_commands)
490 cp = buf;
491 if (cp != NULL) {
492 /* Skip white spaces. */
493 while (isspace((int)*cp) && *cp != '\0')
494 cp++;
495 }
496 if (cp != NULL && *cp != '\0') {
497 unsigned i;
498 char vty_str[VTY_BUFSIZ];
499 char prompt_str[VTY_BUFSIZ];
500
501 /* format the base vty info */
502 snprintf(vty_str, sizeof(vty_str), "vty[??]@%s", vty->address);
503
504 for (i = 0; i < vector_active(vtyvec); i++)
505 if (vty == vector_slot(vtyvec, i)) {
506 snprintf(vty_str, sizeof(vty_str), "vty[%d]@%s",
507 i, vty->address);
508 break;
509 }
510
511 /* format the prompt */
512 snprintf(prompt_str, sizeof(prompt_str), cmd_prompt(vty->node),
513 vty_str);
514
515 /* now log the command */
516 zlog_notice("%s%s", prompt_str, buf);
517 }
518
519 #ifdef CONSUMED_TIME_CHECK
520 {
521 RUSAGE_T before;
522 RUSAGE_T after;
523 unsigned long realtime, cputime;
524
525 GETRUSAGE(&before);
526 #endif /* CONSUMED_TIME_CHECK */
527
528 ret = cmd_execute(vty, buf, NULL, 0);
529
530 /* Get the name of the protocol if any */
531 protocolname = frr_protoname;
532
533 #ifdef CONSUMED_TIME_CHECK
534 GETRUSAGE(&after);
535 if ((realtime = thread_consumed_time(&after, &before, &cputime))
536 > CONSUMED_TIME_CHECK)
537 /* Warn about CPU hog that must be fixed. */
538 flog_warn(
539 EC_LIB_SLOW_THREAD,
540 "SLOW COMMAND: command took %lums (cpu time %lums): %s",
541 realtime / 1000, cputime / 1000, buf);
542 }
543 #endif /* CONSUMED_TIME_CHECK */
544
545 if (ret != CMD_SUCCESS)
546 switch (ret) {
547 case CMD_WARNING:
548 if (vty->type == VTY_FILE)
549 vty_out(vty, "Warning...\n");
550 break;
551 case CMD_ERR_AMBIGUOUS:
552 vty_out(vty, "%% Ambiguous command.\n");
553 break;
554 case CMD_ERR_NO_MATCH:
555 vty_out(vty, "%% [%s] Unknown command: %s\n",
556 protocolname, buf);
557 break;
558 case CMD_ERR_INCOMPLETE:
559 vty_out(vty, "%% Command incomplete.\n");
560 break;
561 }
562
563 return ret;
564 }
565
566 static const char telnet_backward_char = 0x08;
567 static const char telnet_space_char = ' ';
568
569 /* Basic function to write buffer to vty. */
570 static void vty_write(struct vty *vty, const char *buf, size_t nbytes)
571 {
572 if ((vty->node == AUTH_NODE) || (vty->node == AUTH_ENABLE_NODE))
573 return;
574
575 /* Should we do buffering here ? And make vty_flush (vty) ? */
576 buffer_put(vty->obuf, buf, nbytes);
577 }
578
579 /* Basic function to insert character into vty. */
580 static void vty_self_insert(struct vty *vty, char c)
581 {
582 int i;
583 int length;
584
585 if (vty->length + 1 >= VTY_BUFSIZ)
586 return;
587
588 length = vty->length - vty->cp;
589 memmove(&vty->buf[vty->cp + 1], &vty->buf[vty->cp], length);
590 vty->buf[vty->cp] = c;
591
592 vty_write(vty, &vty->buf[vty->cp], length + 1);
593 for (i = 0; i < length; i++)
594 vty_write(vty, &telnet_backward_char, 1);
595
596 vty->cp++;
597 vty->length++;
598
599 vty->buf[vty->length] = '\0';
600 }
601
602 /* Self insert character 'c' in overwrite mode. */
603 static void vty_self_insert_overwrite(struct vty *vty, char c)
604 {
605 if (vty->cp == vty->length) {
606 vty_self_insert(vty, c);
607 return;
608 }
609
610 vty->buf[vty->cp++] = c;
611 vty_write(vty, &c, 1);
612 }
613
614 /**
615 * Insert a string into vty->buf at the current cursor position.
616 *
617 * If the resultant string would be larger than VTY_BUFSIZ it is
618 * truncated to fit.
619 */
620 static void vty_insert_word_overwrite(struct vty *vty, char *str)
621 {
622 if (vty->cp == VTY_BUFSIZ)
623 return;
624
625 size_t nwrite = MIN((int)strlen(str), VTY_BUFSIZ - vty->cp - 1);
626 memcpy(&vty->buf[vty->cp], str, nwrite);
627 vty->cp += nwrite;
628 vty->length = MAX(vty->cp, vty->length);
629 vty->buf[vty->length] = '\0';
630 vty_write(vty, str, nwrite);
631 }
632
633 /* Forward character. */
634 static void vty_forward_char(struct vty *vty)
635 {
636 if (vty->cp < vty->length) {
637 vty_write(vty, &vty->buf[vty->cp], 1);
638 vty->cp++;
639 }
640 }
641
642 /* Backward character. */
643 static void vty_backward_char(struct vty *vty)
644 {
645 if (vty->cp > 0) {
646 vty->cp--;
647 vty_write(vty, &telnet_backward_char, 1);
648 }
649 }
650
651 /* Move to the beginning of the line. */
652 static void vty_beginning_of_line(struct vty *vty)
653 {
654 while (vty->cp)
655 vty_backward_char(vty);
656 }
657
658 /* Move to the end of the line. */
659 static void vty_end_of_line(struct vty *vty)
660 {
661 while (vty->cp < vty->length)
662 vty_forward_char(vty);
663 }
664
665 static void vty_kill_line_from_beginning(struct vty *);
666 static void vty_redraw_line(struct vty *);
667
668 /* Print command line history. This function is called from
669 vty_next_line and vty_previous_line. */
670 static void vty_history_print(struct vty *vty)
671 {
672 int length;
673
674 vty_kill_line_from_beginning(vty);
675
676 /* Get previous line from history buffer */
677 length = strlen(vty->hist[vty->hp]);
678 memcpy(vty->buf, vty->hist[vty->hp], length);
679 vty->cp = vty->length = length;
680 vty->buf[vty->length] = '\0';
681
682 /* Redraw current line */
683 vty_redraw_line(vty);
684 }
685
686 /* Show next command line history. */
687 static void vty_next_line(struct vty *vty)
688 {
689 int try_index;
690
691 if (vty->hp == vty->hindex)
692 return;
693
694 /* Try is there history exist or not. */
695 try_index = vty->hp;
696 if (try_index == (VTY_MAXHIST - 1))
697 try_index = 0;
698 else
699 try_index++;
700
701 /* If there is not history return. */
702 if (vty->hist[try_index] == NULL)
703 return;
704 else
705 vty->hp = try_index;
706
707 vty_history_print(vty);
708 }
709
710 /* Show previous command line history. */
711 static void vty_previous_line(struct vty *vty)
712 {
713 int try_index;
714
715 try_index = vty->hp;
716 if (try_index == 0)
717 try_index = VTY_MAXHIST - 1;
718 else
719 try_index--;
720
721 if (vty->hist[try_index] == NULL)
722 return;
723 else
724 vty->hp = try_index;
725
726 vty_history_print(vty);
727 }
728
729 /* This function redraw all of the command line character. */
730 static void vty_redraw_line(struct vty *vty)
731 {
732 vty_write(vty, vty->buf, vty->length);
733 vty->cp = vty->length;
734 }
735
736 /* Forward word. */
737 static void vty_forward_word(struct vty *vty)
738 {
739 while (vty->cp != vty->length && vty->buf[vty->cp] != ' ')
740 vty_forward_char(vty);
741
742 while (vty->cp != vty->length && vty->buf[vty->cp] == ' ')
743 vty_forward_char(vty);
744 }
745
746 /* Backward word without skipping training space. */
747 static void vty_backward_pure_word(struct vty *vty)
748 {
749 while (vty->cp > 0 && vty->buf[vty->cp - 1] != ' ')
750 vty_backward_char(vty);
751 }
752
753 /* Backward word. */
754 static void vty_backward_word(struct vty *vty)
755 {
756 while (vty->cp > 0 && vty->buf[vty->cp - 1] == ' ')
757 vty_backward_char(vty);
758
759 while (vty->cp > 0 && vty->buf[vty->cp - 1] != ' ')
760 vty_backward_char(vty);
761 }
762
763 /* When '^D' is typed at the beginning of the line we move to the down
764 level. */
765 static void vty_down_level(struct vty *vty)
766 {
767 vty_out(vty, "\n");
768 cmd_exit(vty);
769 vty_prompt(vty);
770 vty->cp = 0;
771 }
772
773 /* When '^Z' is received from vty, move down to the enable mode. */
774 static void vty_end_config(struct vty *vty)
775 {
776 vty_out(vty, "\n");
777
778 if (vty->config) {
779 vty_config_exit(vty);
780 vty->node = ENABLE_NODE;
781 }
782
783 vty_prompt(vty);
784 vty->cp = 0;
785 }
786
787 /* Delete a charcter at the current point. */
788 static void vty_delete_char(struct vty *vty)
789 {
790 int i;
791 int size;
792
793 if (vty->length == 0) {
794 vty_down_level(vty);
795 return;
796 }
797
798 if (vty->cp == vty->length)
799 return; /* completion need here? */
800
801 size = vty->length - vty->cp;
802
803 vty->length--;
804 memmove(&vty->buf[vty->cp], &vty->buf[vty->cp + 1], size - 1);
805 vty->buf[vty->length] = '\0';
806
807 if (vty->node == AUTH_NODE || vty->node == AUTH_ENABLE_NODE)
808 return;
809
810 vty_write(vty, &vty->buf[vty->cp], size - 1);
811 vty_write(vty, &telnet_space_char, 1);
812
813 for (i = 0; i < size; i++)
814 vty_write(vty, &telnet_backward_char, 1);
815 }
816
817 /* Delete a character before the point. */
818 static void vty_delete_backward_char(struct vty *vty)
819 {
820 if (vty->cp == 0)
821 return;
822
823 vty_backward_char(vty);
824 vty_delete_char(vty);
825 }
826
827 /* Kill rest of line from current point. */
828 static void vty_kill_line(struct vty *vty)
829 {
830 int i;
831 int size;
832
833 size = vty->length - vty->cp;
834
835 if (size == 0)
836 return;
837
838 for (i = 0; i < size; i++)
839 vty_write(vty, &telnet_space_char, 1);
840 for (i = 0; i < size; i++)
841 vty_write(vty, &telnet_backward_char, 1);
842
843 memset(&vty->buf[vty->cp], 0, size);
844 vty->length = vty->cp;
845 }
846
847 /* Kill line from the beginning. */
848 static void vty_kill_line_from_beginning(struct vty *vty)
849 {
850 vty_beginning_of_line(vty);
851 vty_kill_line(vty);
852 }
853
854 /* Delete a word before the point. */
855 static void vty_forward_kill_word(struct vty *vty)
856 {
857 while (vty->cp != vty->length && vty->buf[vty->cp] == ' ')
858 vty_delete_char(vty);
859 while (vty->cp != vty->length && vty->buf[vty->cp] != ' ')
860 vty_delete_char(vty);
861 }
862
863 /* Delete a word before the point. */
864 static void vty_backward_kill_word(struct vty *vty)
865 {
866 while (vty->cp > 0 && vty->buf[vty->cp - 1] == ' ')
867 vty_delete_backward_char(vty);
868 while (vty->cp > 0 && vty->buf[vty->cp - 1] != ' ')
869 vty_delete_backward_char(vty);
870 }
871
872 /* Transpose chars before or at the point. */
873 static void vty_transpose_chars(struct vty *vty)
874 {
875 char c1, c2;
876
877 /* If length is short or point is near by the beginning of line then
878 return. */
879 if (vty->length < 2 || vty->cp < 1)
880 return;
881
882 /* In case of point is located at the end of the line. */
883 if (vty->cp == vty->length) {
884 c1 = vty->buf[vty->cp - 1];
885 c2 = vty->buf[vty->cp - 2];
886
887 vty_backward_char(vty);
888 vty_backward_char(vty);
889 vty_self_insert_overwrite(vty, c1);
890 vty_self_insert_overwrite(vty, c2);
891 } else {
892 c1 = vty->buf[vty->cp];
893 c2 = vty->buf[vty->cp - 1];
894
895 vty_backward_char(vty);
896 vty_self_insert_overwrite(vty, c1);
897 vty_self_insert_overwrite(vty, c2);
898 }
899 }
900
901 /* Do completion at vty interface. */
902 static void vty_complete_command(struct vty *vty)
903 {
904 int i;
905 int ret;
906 char **matched = NULL;
907 vector vline;
908
909 if (vty->node == AUTH_NODE || vty->node == AUTH_ENABLE_NODE)
910 return;
911
912 vline = cmd_make_strvec(vty->buf);
913 if (vline == NULL)
914 return;
915
916 /* In case of 'help \t'. */
917 if (isspace((int)vty->buf[vty->length - 1]))
918 vector_set(vline, NULL);
919
920 matched = cmd_complete_command(vline, vty, &ret);
921
922 cmd_free_strvec(vline);
923
924 vty_out(vty, "\n");
925 switch (ret) {
926 case CMD_ERR_AMBIGUOUS:
927 vty_out(vty, "%% Ambiguous command.\n");
928 vty_prompt(vty);
929 vty_redraw_line(vty);
930 break;
931 case CMD_ERR_NO_MATCH:
932 /* vty_out (vty, "%% There is no matched command.\n"); */
933 vty_prompt(vty);
934 vty_redraw_line(vty);
935 break;
936 case CMD_COMPLETE_FULL_MATCH:
937 if (!matched[0]) {
938 /* 2016-11-28 equinox -- need to debug, SEGV here */
939 vty_out(vty, "%% CLI BUG: FULL_MATCH with NULL str\n");
940 vty_prompt(vty);
941 vty_redraw_line(vty);
942 break;
943 }
944 vty_prompt(vty);
945 vty_redraw_line(vty);
946 vty_backward_pure_word(vty);
947 vty_insert_word_overwrite(vty, matched[0]);
948 vty_self_insert(vty, ' ');
949 XFREE(MTYPE_COMPLETION, matched[0]);
950 break;
951 case CMD_COMPLETE_MATCH:
952 vty_prompt(vty);
953 vty_redraw_line(vty);
954 vty_backward_pure_word(vty);
955 vty_insert_word_overwrite(vty, matched[0]);
956 XFREE(MTYPE_COMPLETION, matched[0]);
957 break;
958 case CMD_COMPLETE_LIST_MATCH:
959 for (i = 0; matched[i] != NULL; i++) {
960 if (i != 0 && ((i % 6) == 0))
961 vty_out(vty, "\n");
962 vty_out(vty, "%-10s ", matched[i]);
963 XFREE(MTYPE_COMPLETION, matched[i]);
964 }
965 vty_out(vty, "\n");
966
967 vty_prompt(vty);
968 vty_redraw_line(vty);
969 break;
970 case CMD_ERR_NOTHING_TODO:
971 vty_prompt(vty);
972 vty_redraw_line(vty);
973 break;
974 default:
975 break;
976 }
977 XFREE(MTYPE_TMP, matched);
978 }
979
980 static void vty_describe_fold(struct vty *vty, int cmd_width,
981 unsigned int desc_width, struct cmd_token *token)
982 {
983 char *buf;
984 const char *cmd, *p;
985 int pos;
986
987 cmd = token->text;
988
989 if (desc_width <= 0) {
990 vty_out(vty, " %-*s %s\n", cmd_width, cmd, token->desc);
991 return;
992 }
993
994 buf = XCALLOC(MTYPE_TMP, strlen(token->desc) + 1);
995
996 for (p = token->desc; strlen(p) > desc_width; p += pos + 1) {
997 for (pos = desc_width; pos > 0; pos--)
998 if (*(p + pos) == ' ')
999 break;
1000
1001 if (pos == 0)
1002 break;
1003
1004 strncpy(buf, p, pos);
1005 buf[pos] = '\0';
1006 vty_out(vty, " %-*s %s\n", cmd_width, cmd, buf);
1007
1008 cmd = "";
1009 }
1010
1011 vty_out(vty, " %-*s %s\n", cmd_width, cmd, p);
1012
1013 XFREE(MTYPE_TMP, buf);
1014 }
1015
1016 /* Describe matched command function. */
1017 static void vty_describe_command(struct vty *vty)
1018 {
1019 int ret;
1020 vector vline;
1021 vector describe;
1022 unsigned int i, width, desc_width;
1023 struct cmd_token *token, *token_cr = NULL;
1024
1025 vline = cmd_make_strvec(vty->buf);
1026
1027 /* In case of '> ?'. */
1028 if (vline == NULL) {
1029 vline = vector_init(1);
1030 vector_set(vline, NULL);
1031 } else if (isspace((int)vty->buf[vty->length - 1]))
1032 vector_set(vline, NULL);
1033
1034 describe = cmd_describe_command(vline, vty, &ret);
1035
1036 vty_out(vty, "\n");
1037
1038 /* Ambiguous error. */
1039 switch (ret) {
1040 case CMD_ERR_AMBIGUOUS:
1041 vty_out(vty, "%% Ambiguous command.\n");
1042 goto out;
1043 break;
1044 case CMD_ERR_NO_MATCH:
1045 vty_out(vty, "%% There is no matched command.\n");
1046 goto out;
1047 break;
1048 }
1049
1050 /* Get width of command string. */
1051 width = 0;
1052 for (i = 0; i < vector_active(describe); i++)
1053 if ((token = vector_slot(describe, i)) != NULL) {
1054 unsigned int len;
1055
1056 if (token->text[0] == '\0')
1057 continue;
1058
1059 len = strlen(token->text);
1060
1061 if (width < len)
1062 width = len;
1063 }
1064
1065 /* Get width of description string. */
1066 desc_width = vty->width - (width + 6);
1067
1068 /* Print out description. */
1069 for (i = 0; i < vector_active(describe); i++)
1070 if ((token = vector_slot(describe, i)) != NULL) {
1071 if (token->text[0] == '\0')
1072 continue;
1073
1074 if (strcmp(token->text, CMD_CR_TEXT) == 0) {
1075 token_cr = token;
1076 continue;
1077 }
1078
1079 if (!token->desc)
1080 vty_out(vty, " %-s\n", token->text);
1081 else if (desc_width >= strlen(token->desc))
1082 vty_out(vty, " %-*s %s\n", width, token->text,
1083 token->desc);
1084 else
1085 vty_describe_fold(vty, width, desc_width,
1086 token);
1087
1088 if (IS_VARYING_TOKEN(token->type)) {
1089 const char *ref = vector_slot(
1090 vline, vector_active(vline) - 1);
1091
1092 vector varcomps = vector_init(VECTOR_MIN_SIZE);
1093 cmd_variable_complete(token, ref, varcomps);
1094
1095 if (vector_active(varcomps) > 0) {
1096 char *ac = cmd_variable_comp2str(
1097 varcomps, vty->width);
1098 vty_out(vty, "%s\n", ac);
1099 XFREE(MTYPE_TMP, ac);
1100 }
1101
1102 vector_free(varcomps);
1103 }
1104 #if 0
1105 vty_out (vty, " %-*s %s\n", width
1106 desc->cmd[0] == '.' ? desc->cmd + 1 : desc->cmd,
1107 desc->str ? desc->str : "");
1108 #endif /* 0 */
1109 }
1110
1111 if ((token = token_cr)) {
1112 if (!token->desc)
1113 vty_out(vty, " %-s\n", token->text);
1114 else if (desc_width >= strlen(token->desc))
1115 vty_out(vty, " %-*s %s\n", width, token->text,
1116 token->desc);
1117 else
1118 vty_describe_fold(vty, width, desc_width, token);
1119 }
1120
1121 out:
1122 cmd_free_strvec(vline);
1123 if (describe)
1124 vector_free(describe);
1125
1126 vty_prompt(vty);
1127 vty_redraw_line(vty);
1128 }
1129
1130 static void vty_clear_buf(struct vty *vty)
1131 {
1132 memset(vty->buf, 0, vty->max);
1133 }
1134
1135 /* ^C stop current input and do not add command line to the history. */
1136 static void vty_stop_input(struct vty *vty)
1137 {
1138 vty->cp = vty->length = 0;
1139 vty_clear_buf(vty);
1140 vty_out(vty, "\n");
1141
1142 if (vty->config) {
1143 vty_config_exit(vty);
1144 vty->node = ENABLE_NODE;
1145 }
1146
1147 vty_prompt(vty);
1148
1149 /* Set history pointer to the latest one. */
1150 vty->hp = vty->hindex;
1151 }
1152
1153 /* Add current command line to the history buffer. */
1154 static void vty_hist_add(struct vty *vty)
1155 {
1156 int index;
1157
1158 if (vty->length == 0)
1159 return;
1160
1161 index = vty->hindex ? vty->hindex - 1 : VTY_MAXHIST - 1;
1162
1163 /* Ignore the same string as previous one. */
1164 if (vty->hist[index])
1165 if (strcmp(vty->buf, vty->hist[index]) == 0) {
1166 vty->hp = vty->hindex;
1167 return;
1168 }
1169
1170 /* Insert history entry. */
1171 XFREE(MTYPE_VTY_HIST, vty->hist[vty->hindex]);
1172 vty->hist[vty->hindex] = XSTRDUP(MTYPE_VTY_HIST, vty->buf);
1173
1174 /* History index rotation. */
1175 vty->hindex++;
1176 if (vty->hindex == VTY_MAXHIST)
1177 vty->hindex = 0;
1178
1179 vty->hp = vty->hindex;
1180 }
1181
1182 /* #define TELNET_OPTION_DEBUG */
1183
1184 /* Get telnet window size. */
1185 static int vty_telnet_option(struct vty *vty, unsigned char *buf, int nbytes)
1186 {
1187 #ifdef TELNET_OPTION_DEBUG
1188 int i;
1189
1190 for (i = 0; i < nbytes; i++) {
1191 switch (buf[i]) {
1192 case IAC:
1193 vty_out(vty, "IAC ");
1194 break;
1195 case WILL:
1196 vty_out(vty, "WILL ");
1197 break;
1198 case WONT:
1199 vty_out(vty, "WONT ");
1200 break;
1201 case DO:
1202 vty_out(vty, "DO ");
1203 break;
1204 case DONT:
1205 vty_out(vty, "DONT ");
1206 break;
1207 case SB:
1208 vty_out(vty, "SB ");
1209 break;
1210 case SE:
1211 vty_out(vty, "SE ");
1212 break;
1213 case TELOPT_ECHO:
1214 vty_out(vty, "TELOPT_ECHO \n");
1215 break;
1216 case TELOPT_SGA:
1217 vty_out(vty, "TELOPT_SGA \n");
1218 break;
1219 case TELOPT_NAWS:
1220 vty_out(vty, "TELOPT_NAWS \n");
1221 break;
1222 default:
1223 vty_out(vty, "%x ", buf[i]);
1224 break;
1225 }
1226 }
1227 vty_out(vty, "\n");
1228
1229 #endif /* TELNET_OPTION_DEBUG */
1230
1231 switch (buf[0]) {
1232 case SB:
1233 vty->sb_len = 0;
1234 vty->iac_sb_in_progress = 1;
1235 return 0;
1236 break;
1237 case SE: {
1238 if (!vty->iac_sb_in_progress)
1239 return 0;
1240
1241 if ((vty->sb_len == 0) || (vty->sb_buf[0] == '\0')) {
1242 vty->iac_sb_in_progress = 0;
1243 return 0;
1244 }
1245 switch (vty->sb_buf[0]) {
1246 case TELOPT_NAWS:
1247 if (vty->sb_len != TELNET_NAWS_SB_LEN)
1248 flog_err(
1249 EC_LIB_SYSTEM_CALL,
1250 "RFC 1073 violation detected: telnet NAWS option "
1251 "should send %d characters, but we received %lu",
1252 TELNET_NAWS_SB_LEN,
1253 (unsigned long)vty->sb_len);
1254 else if (sizeof(vty->sb_buf) < TELNET_NAWS_SB_LEN)
1255 flog_err(
1256 EC_LIB_DEVELOPMENT,
1257 "Bug detected: sizeof(vty->sb_buf) %lu < %d, too small to handle the telnet NAWS option",
1258 (unsigned long)sizeof(vty->sb_buf),
1259 TELNET_NAWS_SB_LEN);
1260 else {
1261 vty->width = ((vty->sb_buf[1] << 8)
1262 | vty->sb_buf[2]);
1263 vty->height = ((vty->sb_buf[3] << 8)
1264 | vty->sb_buf[4]);
1265 #ifdef TELNET_OPTION_DEBUG
1266 vty_out(vty,
1267 "TELNET NAWS window size negotiation completed: "
1268 "width %d, height %d\n",
1269 vty->width, vty->height);
1270 #endif
1271 }
1272 break;
1273 }
1274 vty->iac_sb_in_progress = 0;
1275 return 0;
1276 break;
1277 }
1278 default:
1279 break;
1280 }
1281 return 1;
1282 }
1283
1284 /* Execute current command line. */
1285 static int vty_execute(struct vty *vty)
1286 {
1287 int ret;
1288
1289 ret = CMD_SUCCESS;
1290
1291 switch (vty->node) {
1292 case AUTH_NODE:
1293 case AUTH_ENABLE_NODE:
1294 vty_auth(vty, vty->buf);
1295 break;
1296 default:
1297 ret = vty_command(vty, vty->buf);
1298 if (vty->type == VTY_TERM)
1299 vty_hist_add(vty);
1300 break;
1301 }
1302
1303 /* Clear command line buffer. */
1304 vty->cp = vty->length = 0;
1305 vty_clear_buf(vty);
1306
1307 if (vty->status != VTY_CLOSE)
1308 vty_prompt(vty);
1309
1310 return ret;
1311 }
1312
1313 #define CONTROL(X) ((X) - '@')
1314 #define VTY_NORMAL 0
1315 #define VTY_PRE_ESCAPE 1
1316 #define VTY_ESCAPE 2
1317
1318 /* Escape character command map. */
1319 static void vty_escape_map(unsigned char c, struct vty *vty)
1320 {
1321 switch (c) {
1322 case ('A'):
1323 vty_previous_line(vty);
1324 break;
1325 case ('B'):
1326 vty_next_line(vty);
1327 break;
1328 case ('C'):
1329 vty_forward_char(vty);
1330 break;
1331 case ('D'):
1332 vty_backward_char(vty);
1333 break;
1334 default:
1335 break;
1336 }
1337
1338 /* Go back to normal mode. */
1339 vty->escape = VTY_NORMAL;
1340 }
1341
1342 /* Quit print out to the buffer. */
1343 static void vty_buffer_reset(struct vty *vty)
1344 {
1345 buffer_reset(vty->obuf);
1346 buffer_reset(vty->lbuf);
1347 vty_prompt(vty);
1348 vty_redraw_line(vty);
1349 }
1350
1351 /* Read data via vty socket. */
1352 static int vty_read(struct thread *thread)
1353 {
1354 int i;
1355 int nbytes;
1356 unsigned char buf[VTY_READ_BUFSIZ];
1357
1358 int vty_sock = THREAD_FD(thread);
1359 struct vty *vty = THREAD_ARG(thread);
1360 vty->t_read = NULL;
1361
1362 /* Read raw data from socket */
1363 if ((nbytes = read(vty->fd, buf, VTY_READ_BUFSIZ)) <= 0) {
1364 if (nbytes < 0) {
1365 if (ERRNO_IO_RETRY(errno)) {
1366 vty_event(VTY_READ, vty_sock, vty);
1367 return 0;
1368 }
1369 vty->monitor = 0; /* disable monitoring to avoid
1370 infinite recursion */
1371 flog_err(
1372 EC_LIB_SOCKET,
1373 "%s: read error on vty client fd %d, closing: %s",
1374 __func__, vty->fd, safe_strerror(errno));
1375 buffer_reset(vty->obuf);
1376 buffer_reset(vty->lbuf);
1377 }
1378 vty->status = VTY_CLOSE;
1379 }
1380
1381 for (i = 0; i < nbytes; i++) {
1382 if (buf[i] == IAC) {
1383 if (!vty->iac) {
1384 vty->iac = 1;
1385 continue;
1386 } else {
1387 vty->iac = 0;
1388 }
1389 }
1390
1391 if (vty->iac_sb_in_progress && !vty->iac) {
1392 if (vty->sb_len < sizeof(vty->sb_buf))
1393 vty->sb_buf[vty->sb_len] = buf[i];
1394 vty->sb_len++;
1395 continue;
1396 }
1397
1398 if (vty->iac) {
1399 /* In case of telnet command */
1400 int ret = 0;
1401 ret = vty_telnet_option(vty, buf + i, nbytes - i);
1402 vty->iac = 0;
1403 i += ret;
1404 continue;
1405 }
1406
1407
1408 if (vty->status == VTY_MORE) {
1409 switch (buf[i]) {
1410 case CONTROL('C'):
1411 case 'q':
1412 case 'Q':
1413 vty_buffer_reset(vty);
1414 break;
1415 #if 0 /* More line does not work for "show ip bgp". */
1416 case '\n':
1417 case '\r':
1418 vty->status = VTY_MORELINE;
1419 break;
1420 #endif
1421 default:
1422 break;
1423 }
1424 continue;
1425 }
1426
1427 /* Escape character. */
1428 if (vty->escape == VTY_ESCAPE) {
1429 vty_escape_map(buf[i], vty);
1430 continue;
1431 }
1432
1433 /* Pre-escape status. */
1434 if (vty->escape == VTY_PRE_ESCAPE) {
1435 switch (buf[i]) {
1436 case '[':
1437 vty->escape = VTY_ESCAPE;
1438 break;
1439 case 'b':
1440 vty_backward_word(vty);
1441 vty->escape = VTY_NORMAL;
1442 break;
1443 case 'f':
1444 vty_forward_word(vty);
1445 vty->escape = VTY_NORMAL;
1446 break;
1447 case 'd':
1448 vty_forward_kill_word(vty);
1449 vty->escape = VTY_NORMAL;
1450 break;
1451 case CONTROL('H'):
1452 case 0x7f:
1453 vty_backward_kill_word(vty);
1454 vty->escape = VTY_NORMAL;
1455 break;
1456 default:
1457 vty->escape = VTY_NORMAL;
1458 break;
1459 }
1460 continue;
1461 }
1462
1463 switch (buf[i]) {
1464 case CONTROL('A'):
1465 vty_beginning_of_line(vty);
1466 break;
1467 case CONTROL('B'):
1468 vty_backward_char(vty);
1469 break;
1470 case CONTROL('C'):
1471 vty_stop_input(vty);
1472 break;
1473 case CONTROL('D'):
1474 vty_delete_char(vty);
1475 break;
1476 case CONTROL('E'):
1477 vty_end_of_line(vty);
1478 break;
1479 case CONTROL('F'):
1480 vty_forward_char(vty);
1481 break;
1482 case CONTROL('H'):
1483 case 0x7f:
1484 vty_delete_backward_char(vty);
1485 break;
1486 case CONTROL('K'):
1487 vty_kill_line(vty);
1488 break;
1489 case CONTROL('N'):
1490 vty_next_line(vty);
1491 break;
1492 case CONTROL('P'):
1493 vty_previous_line(vty);
1494 break;
1495 case CONTROL('T'):
1496 vty_transpose_chars(vty);
1497 break;
1498 case CONTROL('U'):
1499 vty_kill_line_from_beginning(vty);
1500 break;
1501 case CONTROL('W'):
1502 vty_backward_kill_word(vty);
1503 break;
1504 case CONTROL('Z'):
1505 vty_end_config(vty);
1506 break;
1507 case '\n':
1508 case '\r':
1509 vty_out(vty, "\n");
1510 vty_execute(vty);
1511 break;
1512 case '\t':
1513 vty_complete_command(vty);
1514 break;
1515 case '?':
1516 if (vty->node == AUTH_NODE
1517 || vty->node == AUTH_ENABLE_NODE)
1518 vty_self_insert(vty, buf[i]);
1519 else
1520 vty_describe_command(vty);
1521 break;
1522 case '\033':
1523 if (i + 1 < nbytes && buf[i + 1] == '[') {
1524 vty->escape = VTY_ESCAPE;
1525 i++;
1526 } else
1527 vty->escape = VTY_PRE_ESCAPE;
1528 break;
1529 default:
1530 if (buf[i] > 31 && buf[i] < 127)
1531 vty_self_insert(vty, buf[i]);
1532 break;
1533 }
1534 }
1535
1536 /* Check status. */
1537 if (vty->status == VTY_CLOSE)
1538 vty_close(vty);
1539 else {
1540 vty_event(VTY_WRITE, vty->wfd, vty);
1541 vty_event(VTY_READ, vty_sock, vty);
1542 }
1543 return 0;
1544 }
1545
1546 /* Flush buffer to the vty. */
1547 static int vty_flush(struct thread *thread)
1548 {
1549 int erase;
1550 buffer_status_t flushrc;
1551 int vty_sock = THREAD_FD(thread);
1552 struct vty *vty = THREAD_ARG(thread);
1553
1554 vty->t_write = NULL;
1555
1556 /* Tempolary disable read thread. */
1557 if ((vty->lines == 0) && vty->t_read) {
1558 thread_cancel(vty->t_read);
1559 vty->t_read = NULL;
1560 }
1561
1562 /* Function execution continue. */
1563 erase = ((vty->status == VTY_MORE || vty->status == VTY_MORELINE));
1564
1565 /* N.B. if width is 0, that means we don't know the window size. */
1566 if ((vty->lines == 0) || (vty->width == 0) || (vty->height == 0))
1567 flushrc = buffer_flush_available(vty->obuf, vty_sock);
1568 else if (vty->status == VTY_MORELINE)
1569 flushrc = buffer_flush_window(vty->obuf, vty_sock, vty->width,
1570 1, erase, 0);
1571 else
1572 flushrc = buffer_flush_window(
1573 vty->obuf, vty_sock, vty->width,
1574 vty->lines >= 0 ? vty->lines : vty->height, erase, 0);
1575 switch (flushrc) {
1576 case BUFFER_ERROR:
1577 vty->monitor =
1578 0; /* disable monitoring to avoid infinite recursion */
1579 zlog_info("buffer_flush failed on vty client fd %d, closing",
1580 vty->fd);
1581 buffer_reset(vty->lbuf);
1582 buffer_reset(vty->obuf);
1583 vty_close(vty);
1584 return 0;
1585 case BUFFER_EMPTY:
1586 if (vty->status == VTY_CLOSE)
1587 vty_close(vty);
1588 else {
1589 vty->status = VTY_NORMAL;
1590 if (vty->lines == 0)
1591 vty_event(VTY_READ, vty_sock, vty);
1592 }
1593 break;
1594 case BUFFER_PENDING:
1595 /* There is more data waiting to be written. */
1596 vty->status = VTY_MORE;
1597 if (vty->lines == 0)
1598 vty_event(VTY_WRITE, vty_sock, vty);
1599 break;
1600 }
1601
1602 return 0;
1603 }
1604
1605 /* Allocate new vty struct. */
1606 struct vty *vty_new(void)
1607 {
1608 struct vty *new = XCALLOC(MTYPE_VTY, sizeof(struct vty));
1609
1610 new->fd = new->wfd = -1;
1611 new->of = stdout;
1612 new->lbuf = buffer_new(0);
1613 new->obuf = buffer_new(0); /* Use default buffer size. */
1614 new->buf = XCALLOC(MTYPE_VTY, VTY_BUFSIZ);
1615 new->max = VTY_BUFSIZ;
1616
1617 return new;
1618 }
1619
1620
1621 /* allocate and initialise vty */
1622 static struct vty *vty_new_init(int vty_sock)
1623 {
1624 struct vty *vty;
1625
1626 vty = vty_new();
1627 vty->fd = vty_sock;
1628 vty->wfd = vty_sock;
1629 vty->type = VTY_TERM;
1630 vty->node = AUTH_NODE;
1631 vty->fail = 0;
1632 vty->cp = 0;
1633 vty_clear_buf(vty);
1634 vty->length = 0;
1635 memset(vty->hist, 0, sizeof(vty->hist));
1636 vty->hp = 0;
1637 vty->hindex = 0;
1638 vty->xpath_index = 0;
1639 memset(vty->xpath, 0, sizeof(vty->xpath));
1640 vty->private_config = false;
1641 vty->candidate_config = vty_shared_candidate_config;
1642 vector_set_index(vtyvec, vty_sock, vty);
1643 vty->status = VTY_NORMAL;
1644 vty->lines = -1;
1645 vty->iac = 0;
1646 vty->iac_sb_in_progress = 0;
1647 vty->sb_len = 0;
1648
1649 return vty;
1650 }
1651
1652 /* Create new vty structure. */
1653 static struct vty *vty_create(int vty_sock, union sockunion *su)
1654 {
1655 char buf[SU_ADDRSTRLEN];
1656 struct vty *vty;
1657
1658 sockunion2str(su, buf, SU_ADDRSTRLEN);
1659
1660 /* Allocate new vty structure and set up default values. */
1661 vty = vty_new_init(vty_sock);
1662
1663 /* configurable parameters not part of basic init */
1664 vty->v_timeout = vty_timeout_val;
1665 strcpy(vty->address, buf);
1666 if (no_password_check) {
1667 if (host.advanced)
1668 vty->node = ENABLE_NODE;
1669 else
1670 vty->node = VIEW_NODE;
1671 }
1672 if (host.lines >= 0)
1673 vty->lines = host.lines;
1674
1675 if (!no_password_check) {
1676 /* Vty is not available if password isn't set. */
1677 if (host.password == NULL && host.password_encrypt == NULL) {
1678 vty_out(vty, "Vty password is not set.\n");
1679 vty->status = VTY_CLOSE;
1680 vty_close(vty);
1681 return NULL;
1682 }
1683 }
1684
1685 /* Say hello to the world. */
1686 vty_hello(vty);
1687 if (!no_password_check)
1688 vty_out(vty, "\nUser Access Verification\n\n");
1689
1690 /* Setting up terminal. */
1691 vty_will_echo(vty);
1692 vty_will_suppress_go_ahead(vty);
1693
1694 vty_dont_linemode(vty);
1695 vty_do_window_size(vty);
1696 /* vty_dont_lflow_ahead (vty); */
1697
1698 vty_prompt(vty);
1699
1700 /* Add read/write thread. */
1701 vty_event(VTY_WRITE, vty_sock, vty);
1702 vty_event(VTY_READ, vty_sock, vty);
1703
1704 return vty;
1705 }
1706
1707 /* create vty for stdio */
1708 static struct termios stdio_orig_termios;
1709 static struct vty *stdio_vty = NULL;
1710 static bool stdio_termios = false;
1711 static void (*stdio_vty_atclose)(int isexit);
1712
1713 static void vty_stdio_reset(int isexit)
1714 {
1715 if (stdio_vty) {
1716 if (stdio_termios)
1717 tcsetattr(0, TCSANOW, &stdio_orig_termios);
1718 stdio_termios = false;
1719
1720 stdio_vty = NULL;
1721
1722 if (stdio_vty_atclose)
1723 stdio_vty_atclose(isexit);
1724 stdio_vty_atclose = NULL;
1725 }
1726 }
1727
1728 static void vty_stdio_atexit(void)
1729 {
1730 vty_stdio_reset(1);
1731 }
1732
1733 void vty_stdio_suspend(void)
1734 {
1735 if (!stdio_vty)
1736 return;
1737
1738 if (stdio_vty->t_write)
1739 thread_cancel(stdio_vty->t_write);
1740 if (stdio_vty->t_read)
1741 thread_cancel(stdio_vty->t_read);
1742 if (stdio_vty->t_timeout)
1743 thread_cancel(stdio_vty->t_timeout);
1744
1745 if (stdio_termios)
1746 tcsetattr(0, TCSANOW, &stdio_orig_termios);
1747 stdio_termios = false;
1748 }
1749
1750 void vty_stdio_resume(void)
1751 {
1752 if (!stdio_vty)
1753 return;
1754
1755 if (!tcgetattr(0, &stdio_orig_termios)) {
1756 struct termios termios;
1757
1758 termios = stdio_orig_termios;
1759 termios.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR
1760 | IGNCR | ICRNL | IXON);
1761 termios.c_oflag &= ~OPOST;
1762 termios.c_lflag &= ~(ECHO | ECHONL | ICANON | IEXTEN);
1763 termios.c_cflag &= ~(CSIZE | PARENB);
1764 termios.c_cflag |= CS8;
1765 tcsetattr(0, TCSANOW, &termios);
1766 stdio_termios = true;
1767 }
1768
1769 vty_prompt(stdio_vty);
1770
1771 /* Add read/write thread. */
1772 vty_event(VTY_WRITE, 1, stdio_vty);
1773 vty_event(VTY_READ, 0, stdio_vty);
1774 }
1775
1776 void vty_stdio_close(void)
1777 {
1778 if (!stdio_vty)
1779 return;
1780 vty_close(stdio_vty);
1781 }
1782
1783 struct vty *vty_stdio(void (*atclose)(int isexit))
1784 {
1785 struct vty *vty;
1786
1787 /* refuse creating two vtys on stdio */
1788 if (stdio_vty)
1789 return NULL;
1790
1791 vty = stdio_vty = vty_new_init(0);
1792 stdio_vty_atclose = atclose;
1793 vty->wfd = 1;
1794
1795 /* always have stdio vty in a known _unchangeable_ state, don't want
1796 * config
1797 * to have any effect here to make sure scripting this works as intended
1798 */
1799 vty->node = ENABLE_NODE;
1800 vty->v_timeout = 0;
1801 strcpy(vty->address, "console");
1802
1803 vty_stdio_resume();
1804 return vty;
1805 }
1806
1807 /* Accept connection from the network. */
1808 static int vty_accept(struct thread *thread)
1809 {
1810 int vty_sock;
1811 union sockunion su;
1812 int ret;
1813 unsigned int on;
1814 int accept_sock;
1815 struct prefix p;
1816 struct access_list *acl = NULL;
1817 char buf[SU_ADDRSTRLEN];
1818
1819 accept_sock = THREAD_FD(thread);
1820
1821 /* We continue hearing vty socket. */
1822 vty_event(VTY_SERV, accept_sock, NULL);
1823
1824 memset(&su, 0, sizeof(union sockunion));
1825
1826 /* We can handle IPv4 or IPv6 socket. */
1827 vty_sock = sockunion_accept(accept_sock, &su);
1828 if (vty_sock < 0) {
1829 flog_err(EC_LIB_SOCKET, "can't accept vty socket : %s",
1830 safe_strerror(errno));
1831 return -1;
1832 }
1833 set_nonblocking(vty_sock);
1834 set_cloexec(vty_sock);
1835
1836 sockunion2hostprefix(&su, &p);
1837
1838 /* VTY's accesslist apply. */
1839 if (p.family == AF_INET && vty_accesslist_name) {
1840 if ((acl = access_list_lookup(AFI_IP, vty_accesslist_name))
1841 && (access_list_apply(acl, &p) == FILTER_DENY)) {
1842 zlog_info("Vty connection refused from %s",
1843 sockunion2str(&su, buf, SU_ADDRSTRLEN));
1844 close(vty_sock);
1845
1846 /* continue accepting connections */
1847 vty_event(VTY_SERV, accept_sock, NULL);
1848
1849 return 0;
1850 }
1851 }
1852
1853 /* VTY's ipv6 accesslist apply. */
1854 if (p.family == AF_INET6 && vty_ipv6_accesslist_name) {
1855 if ((acl = access_list_lookup(AFI_IP6,
1856 vty_ipv6_accesslist_name))
1857 && (access_list_apply(acl, &p) == FILTER_DENY)) {
1858 zlog_info("Vty connection refused from %s",
1859 sockunion2str(&su, buf, SU_ADDRSTRLEN));
1860 close(vty_sock);
1861
1862 /* continue accepting connections */
1863 vty_event(VTY_SERV, accept_sock, NULL);
1864
1865 return 0;
1866 }
1867 }
1868
1869 on = 1;
1870 ret = setsockopt(vty_sock, IPPROTO_TCP, TCP_NODELAY, (char *)&on,
1871 sizeof(on));
1872 if (ret < 0)
1873 zlog_info("can't set sockopt to vty_sock : %s",
1874 safe_strerror(errno));
1875
1876 zlog_info("Vty connection from %s",
1877 sockunion2str(&su, buf, SU_ADDRSTRLEN));
1878
1879 vty_create(vty_sock, &su);
1880
1881 return 0;
1882 }
1883
1884 static void vty_serv_sock_addrinfo(const char *hostname, unsigned short port)
1885 {
1886 int ret;
1887 struct addrinfo req;
1888 struct addrinfo *ainfo;
1889 struct addrinfo *ainfo_save;
1890 int sock;
1891 char port_str[BUFSIZ];
1892
1893 memset(&req, 0, sizeof(struct addrinfo));
1894 req.ai_flags = AI_PASSIVE;
1895 req.ai_family = AF_UNSPEC;
1896 req.ai_socktype = SOCK_STREAM;
1897 sprintf(port_str, "%d", port);
1898 port_str[sizeof(port_str) - 1] = '\0';
1899
1900 ret = getaddrinfo(hostname, port_str, &req, &ainfo);
1901
1902 if (ret != 0) {
1903 flog_err_sys(EC_LIB_SYSTEM_CALL, "getaddrinfo failed: %s",
1904 gai_strerror(ret));
1905 exit(1);
1906 }
1907
1908 ainfo_save = ainfo;
1909
1910 do {
1911 if (ainfo->ai_family != AF_INET && ainfo->ai_family != AF_INET6)
1912 continue;
1913
1914 sock = socket(ainfo->ai_family, ainfo->ai_socktype,
1915 ainfo->ai_protocol);
1916 if (sock < 0)
1917 continue;
1918
1919 sockopt_v6only(ainfo->ai_family, sock);
1920 sockopt_reuseaddr(sock);
1921 sockopt_reuseport(sock);
1922 set_cloexec(sock);
1923
1924 ret = bind(sock, ainfo->ai_addr, ainfo->ai_addrlen);
1925 if (ret < 0) {
1926 close(sock); /* Avoid sd leak. */
1927 continue;
1928 }
1929
1930 ret = listen(sock, 3);
1931 if (ret < 0) {
1932 close(sock); /* Avoid sd leak. */
1933 continue;
1934 }
1935
1936 vty_event(VTY_SERV, sock, NULL);
1937 } while ((ainfo = ainfo->ai_next) != NULL);
1938
1939 freeaddrinfo(ainfo_save);
1940 }
1941
1942 #ifdef VTYSH
1943 /* For sockaddr_un. */
1944 #include <sys/un.h>
1945
1946 /* VTY shell UNIX domain socket. */
1947 static void vty_serv_un(const char *path)
1948 {
1949 int ret;
1950 int sock, len;
1951 struct sockaddr_un serv;
1952 mode_t old_mask;
1953 struct zprivs_ids_t ids;
1954
1955 /* First of all, unlink existing socket */
1956 unlink(path);
1957
1958 /* Set umask */
1959 old_mask = umask(0007);
1960
1961 /* Make UNIX domain socket. */
1962 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1963 if (sock < 0) {
1964 flog_err_sys(EC_LIB_SOCKET,
1965 "Cannot create unix stream socket: %s",
1966 safe_strerror(errno));
1967 return;
1968 }
1969
1970 /* Make server socket. */
1971 memset(&serv, 0, sizeof(struct sockaddr_un));
1972 serv.sun_family = AF_UNIX;
1973 strlcpy(serv.sun_path, path, sizeof(serv.sun_path));
1974 #ifdef HAVE_STRUCT_SOCKADDR_UN_SUN_LEN
1975 len = serv.sun_len = SUN_LEN(&serv);
1976 #else
1977 len = sizeof(serv.sun_family) + strlen(serv.sun_path);
1978 #endif /* HAVE_STRUCT_SOCKADDR_UN_SUN_LEN */
1979
1980 set_cloexec(sock);
1981
1982 ret = bind(sock, (struct sockaddr *)&serv, len);
1983 if (ret < 0) {
1984 flog_err_sys(EC_LIB_SOCKET, "Cannot bind path %s: %s", path,
1985 safe_strerror(errno));
1986 close(sock); /* Avoid sd leak. */
1987 return;
1988 }
1989
1990 ret = listen(sock, 5);
1991 if (ret < 0) {
1992 flog_err_sys(EC_LIB_SOCKET, "listen(fd %d) failed: %s", sock,
1993 safe_strerror(errno));
1994 close(sock); /* Avoid sd leak. */
1995 return;
1996 }
1997
1998 umask(old_mask);
1999
2000 zprivs_get_ids(&ids);
2001
2002 /* Hack: ids.gid_vty is actually a uint, but we stored -1 in it
2003 earlier for the case when we don't need to chown the file
2004 type casting it here to make a compare */
2005 if ((int)ids.gid_vty > 0) {
2006 /* set group of socket */
2007 if (chown(path, -1, ids.gid_vty)) {
2008 flog_err_sys(EC_LIB_SYSTEM_CALL,
2009 "vty_serv_un: could chown socket, %s",
2010 safe_strerror(errno));
2011 }
2012 }
2013
2014 vty_event(VTYSH_SERV, sock, NULL);
2015 }
2016
2017 /* #define VTYSH_DEBUG 1 */
2018
2019 static int vtysh_accept(struct thread *thread)
2020 {
2021 int accept_sock;
2022 int sock;
2023 int client_len;
2024 struct sockaddr_un client;
2025 struct vty *vty;
2026
2027 accept_sock = THREAD_FD(thread);
2028
2029 vty_event(VTYSH_SERV, accept_sock, NULL);
2030
2031 memset(&client, 0, sizeof(struct sockaddr_un));
2032 client_len = sizeof(struct sockaddr_un);
2033
2034 sock = accept(accept_sock, (struct sockaddr *)&client,
2035 (socklen_t *)&client_len);
2036
2037 if (sock < 0) {
2038 flog_err(EC_LIB_SOCKET, "can't accept vty socket : %s",
2039 safe_strerror(errno));
2040 return -1;
2041 }
2042
2043 if (set_nonblocking(sock) < 0) {
2044 flog_err(
2045 EC_LIB_SOCKET,
2046 "vtysh_accept: could not set vty socket %d to non-blocking, %s, closing",
2047 sock, safe_strerror(errno));
2048 close(sock);
2049 return -1;
2050 }
2051 set_cloexec(sock);
2052
2053 #ifdef VTYSH_DEBUG
2054 printf("VTY shell accept\n");
2055 #endif /* VTYSH_DEBUG */
2056
2057 vty = vty_new();
2058 vty->fd = sock;
2059 vty->wfd = sock;
2060 vty->type = VTY_SHELL_SERV;
2061 vty->node = VIEW_NODE;
2062
2063 vty_event(VTYSH_READ, sock, vty);
2064
2065 return 0;
2066 }
2067
2068 static int vtysh_flush(struct vty *vty)
2069 {
2070 switch (buffer_flush_available(vty->obuf, vty->wfd)) {
2071 case BUFFER_PENDING:
2072 vty_event(VTYSH_WRITE, vty->wfd, vty);
2073 break;
2074 case BUFFER_ERROR:
2075 vty->monitor =
2076 0; /* disable monitoring to avoid infinite recursion */
2077 flog_err(EC_LIB_SOCKET, "%s: write error to fd %d, closing",
2078 __func__, vty->fd);
2079 buffer_reset(vty->lbuf);
2080 buffer_reset(vty->obuf);
2081 vty_close(vty);
2082 return -1;
2083 break;
2084 case BUFFER_EMPTY:
2085 break;
2086 }
2087 return 0;
2088 }
2089
2090 static int vtysh_read(struct thread *thread)
2091 {
2092 int ret;
2093 int sock;
2094 int nbytes;
2095 struct vty *vty;
2096 unsigned char buf[VTY_READ_BUFSIZ];
2097 unsigned char *p;
2098 uint8_t header[4] = {0, 0, 0, 0};
2099
2100 sock = THREAD_FD(thread);
2101 vty = THREAD_ARG(thread);
2102 vty->t_read = NULL;
2103
2104 if ((nbytes = read(sock, buf, VTY_READ_BUFSIZ)) <= 0) {
2105 if (nbytes < 0) {
2106 if (ERRNO_IO_RETRY(errno)) {
2107 vty_event(VTYSH_READ, sock, vty);
2108 return 0;
2109 }
2110 vty->monitor = 0; /* disable monitoring to avoid
2111 infinite recursion */
2112 flog_err(
2113 EC_LIB_SOCKET,
2114 "%s: read failed on vtysh client fd %d, closing: %s",
2115 __func__, sock, safe_strerror(errno));
2116 }
2117 buffer_reset(vty->lbuf);
2118 buffer_reset(vty->obuf);
2119 vty_close(vty);
2120 #ifdef VTYSH_DEBUG
2121 printf("close vtysh\n");
2122 #endif /* VTYSH_DEBUG */
2123 return 0;
2124 }
2125
2126 #ifdef VTYSH_DEBUG
2127 printf("line: %.*s\n", nbytes, buf);
2128 #endif /* VTYSH_DEBUG */
2129
2130 if (vty->length + nbytes >= VTY_BUFSIZ) {
2131 /* Clear command line buffer. */
2132 vty->cp = vty->length = 0;
2133 vty_clear_buf(vty);
2134 vty_out(vty, "%% Command is too long.\n");
2135 } else {
2136 for (p = buf; p < buf + nbytes; p++) {
2137 vty->buf[vty->length++] = *p;
2138 if (*p == '\0') {
2139 /* Pass this line to parser. */
2140 ret = vty_execute(vty);
2141 /* Note that vty_execute clears the command buffer and resets
2142 vty->length to 0. */
2143
2144 /* Return result. */
2145 #ifdef VTYSH_DEBUG
2146 printf("result: %d\n", ret);
2147 printf("vtysh node: %d\n", vty->node);
2148 #endif /* VTYSH_DEBUG */
2149
2150 /* hack for asynchronous "write integrated"
2151 * - other commands in "buf" will be ditched
2152 * - input during pending config-write is
2153 * "unsupported" */
2154 if (ret == CMD_SUSPEND)
2155 break;
2156
2157 /* warning: watchfrr hardcodes this result write
2158 */
2159 header[3] = ret;
2160 buffer_put(vty->obuf, header, 4);
2161
2162 if (!vty->t_write && (vtysh_flush(vty) < 0))
2163 /* Try to flush results; exit if a write
2164 * error occurs. */
2165 return 0;
2166 }
2167 }
2168 }
2169
2170 if (vty->status == VTY_CLOSE)
2171 vty_close(vty);
2172 else
2173 vty_event(VTYSH_READ, sock, vty);
2174
2175 return 0;
2176 }
2177
2178 static int vtysh_write(struct thread *thread)
2179 {
2180 struct vty *vty = THREAD_ARG(thread);
2181
2182 vty->t_write = NULL;
2183 vtysh_flush(vty);
2184 return 0;
2185 }
2186
2187 #endif /* VTYSH */
2188
2189 /* Determine address family to bind. */
2190 void vty_serv_sock(const char *addr, unsigned short port, const char *path)
2191 {
2192 /* If port is set to 0, do not listen on TCP/IP at all! */
2193 if (port)
2194 vty_serv_sock_addrinfo(addr, port);
2195
2196 #ifdef VTYSH
2197 vty_serv_un(path);
2198 #endif /* VTYSH */
2199 }
2200
2201 static void vty_error_delete(void *arg)
2202 {
2203 struct vty_error *ve = arg;
2204
2205 XFREE(MTYPE_TMP, ve);
2206 }
2207
2208 /* Close vty interface. Warning: call this only from functions that
2209 will be careful not to access the vty afterwards (since it has
2210 now been freed). This is safest from top-level functions (called
2211 directly by the thread dispatcher). */
2212 void vty_close(struct vty *vty)
2213 {
2214 int i;
2215 bool was_stdio = false;
2216
2217 /* Cancel threads.*/
2218 if (vty->t_read)
2219 thread_cancel(vty->t_read);
2220 if (vty->t_write)
2221 thread_cancel(vty->t_write);
2222 if (vty->t_timeout)
2223 thread_cancel(vty->t_timeout);
2224
2225 /* Flush buffer. */
2226 buffer_flush_all(vty->obuf, vty->wfd);
2227
2228 /* Free input buffer. */
2229 buffer_free(vty->obuf);
2230 buffer_free(vty->lbuf);
2231
2232 /* Free command history. */
2233 for (i = 0; i < VTY_MAXHIST; i++) {
2234 XFREE(MTYPE_VTY_HIST, vty->hist[i]);
2235 }
2236
2237 /* Unset vector. */
2238 if (vty->fd != -1)
2239 vector_unset(vtyvec, vty->fd);
2240
2241 if (vty->wfd > 0 && vty->type == VTY_FILE)
2242 fsync(vty->wfd);
2243
2244 /* Close socket.
2245 * note check is for fd > STDERR_FILENO, not fd != -1.
2246 * We never close stdin/stdout/stderr here, because we may be
2247 * running in foreground mode with logging to stdout. Also,
2248 * additionally, we'd need to replace these fds with /dev/null. */
2249 if (vty->wfd > STDERR_FILENO && vty->wfd != vty->fd)
2250 close(vty->wfd);
2251 if (vty->fd > STDERR_FILENO)
2252 close(vty->fd);
2253 if (vty->fd == STDIN_FILENO)
2254 was_stdio = true;
2255
2256 XFREE(MTYPE_VTY, vty->buf);
2257
2258 if (vty->error) {
2259 vty->error->del = vty_error_delete;
2260 list_delete(&vty->error);
2261 }
2262
2263 /* Check configure. */
2264 vty_config_exit(vty);
2265
2266 /* OK free vty. */
2267 XFREE(MTYPE_VTY, vty);
2268
2269 if (was_stdio)
2270 vty_stdio_reset(0);
2271 }
2272
2273 /* When time out occur output message then close connection. */
2274 static int vty_timeout(struct thread *thread)
2275 {
2276 struct vty *vty;
2277
2278 vty = THREAD_ARG(thread);
2279 vty->t_timeout = NULL;
2280 vty->v_timeout = 0;
2281
2282 /* Clear buffer*/
2283 buffer_reset(vty->lbuf);
2284 buffer_reset(vty->obuf);
2285 vty_out(vty, "\nVty connection is timed out.\n");
2286
2287 /* Close connection. */
2288 vty->status = VTY_CLOSE;
2289 vty_close(vty);
2290
2291 return 0;
2292 }
2293
2294 /* Read up configuration file from file_name. */
2295 static void vty_read_file(struct nb_config *config, FILE *confp)
2296 {
2297 int ret;
2298 struct vty *vty;
2299 struct vty_error *ve;
2300 struct listnode *node;
2301 unsigned int line_num = 0;
2302
2303 vty = vty_new();
2304 /* vty_close won't close stderr; if some config command prints
2305 * something it'll end up there. (not ideal; it'd be beter if output
2306 * from a file-load went to logging instead. Also note that if this
2307 * function is called after daemonizing, stderr will be /dev/null.)
2308 *
2309 * vty->fd will be -1 from vty_new()
2310 */
2311 vty->wfd = STDERR_FILENO;
2312 vty->type = VTY_FILE;
2313 vty->node = CONFIG_NODE;
2314 if (config)
2315 vty->candidate_config = config;
2316 else {
2317 vty->private_config = true;
2318 vty->candidate_config = nb_config_new(NULL);
2319 }
2320
2321 /* Execute configuration file */
2322 ret = config_from_file(vty, confp, &line_num);
2323
2324 /* Flush any previous errors before printing messages below */
2325 buffer_flush_all(vty->obuf, vty->wfd);
2326
2327 if (!((ret == CMD_SUCCESS) || (ret == CMD_ERR_NOTHING_TODO))) {
2328 const char *message = NULL;
2329 char *nl;
2330
2331 switch (ret) {
2332 case CMD_ERR_AMBIGUOUS:
2333 message = "Ambiguous command";
2334 break;
2335 case CMD_ERR_NO_MATCH:
2336 message = "No such command";
2337 break;
2338 case CMD_WARNING:
2339 message = "Command returned Warning";
2340 break;
2341 case CMD_WARNING_CONFIG_FAILED:
2342 message = "Command returned Warning Config Failed";
2343 break;
2344 case CMD_ERR_INCOMPLETE:
2345 message = "Command returned Incomplete";
2346 break;
2347 case CMD_ERR_EXEED_ARGC_MAX:
2348 message =
2349 "Command exceeded maximum number of Arguments";
2350 break;
2351 default:
2352 message = "Command returned unhandled error message";
2353 break;
2354 }
2355
2356 for (ALL_LIST_ELEMENTS_RO(vty->error, node, ve)) {
2357 nl = strchr(ve->error_buf, '\n');
2358 if (nl)
2359 *nl = '\0';
2360 flog_err(EC_LIB_VTY, "ERROR: %s on config line %u: %s",
2361 message, ve->line_num, ve->error_buf);
2362 }
2363 }
2364
2365 /*
2366 * Automatically commit the candidate configuration after
2367 * reading the configuration file.
2368 */
2369 if (config == NULL && vty->candidate_config
2370 && frr_get_cli_mode() == FRR_CLI_TRANSACTIONAL) {
2371 ret = nb_candidate_commit(vty->candidate_config, NB_CLIENT_CLI,
2372 true, "Read configuration file",
2373 NULL);
2374 if (ret != NB_OK && ret != NB_ERR_NO_CHANGES)
2375 zlog_err("%s: failed to read configuration file.",
2376 __func__);
2377 }
2378
2379 vty_close(vty);
2380 }
2381
2382 static FILE *vty_use_backup_config(const char *fullpath)
2383 {
2384 char *fullpath_sav, *fullpath_tmp;
2385 FILE *ret = NULL;
2386 int tmp, sav;
2387 int c;
2388 char buffer[512];
2389
2390 fullpath_sav = malloc(strlen(fullpath) + strlen(CONF_BACKUP_EXT) + 1);
2391 strcpy(fullpath_sav, fullpath);
2392 strcat(fullpath_sav, CONF_BACKUP_EXT);
2393
2394 sav = open(fullpath_sav, O_RDONLY);
2395 if (sav < 0) {
2396 free(fullpath_sav);
2397 return NULL;
2398 }
2399
2400 fullpath_tmp = malloc(strlen(fullpath) + 8);
2401 sprintf(fullpath_tmp, "%s.XXXXXX", fullpath);
2402
2403 /* Open file to configuration write. */
2404 tmp = mkstemp(fullpath_tmp);
2405 if (tmp < 0)
2406 goto out_close_sav;
2407
2408 if (fchmod(tmp, CONFIGFILE_MASK) != 0)
2409 goto out_close;
2410
2411 while ((c = read(sav, buffer, 512)) > 0) {
2412 if (write(tmp, buffer, c) <= 0)
2413 goto out_close;
2414 }
2415 close(sav);
2416 close(tmp);
2417
2418 if (rename(fullpath_tmp, fullpath) == 0)
2419 ret = fopen(fullpath, "r");
2420 else
2421 unlink(fullpath_tmp);
2422
2423 if (0) {
2424 out_close:
2425 close(tmp);
2426 unlink(fullpath_tmp);
2427 out_close_sav:
2428 close(sav);
2429 }
2430
2431 free(fullpath_sav);
2432 free(fullpath_tmp);
2433 return ret;
2434 }
2435
2436 /* Read up configuration file from file_name. */
2437 bool vty_read_config(struct nb_config *config, const char *config_file,
2438 char *config_default_dir)
2439 {
2440 char cwd[MAXPATHLEN];
2441 FILE *confp = NULL;
2442 const char *fullpath;
2443 char *tmp = NULL;
2444 bool read_success = false;
2445
2446 /* If -f flag specified. */
2447 if (config_file != NULL) {
2448 if (!IS_DIRECTORY_SEP(config_file[0])) {
2449 if (getcwd(cwd, MAXPATHLEN) == NULL) {
2450 flog_err_sys(
2451 EC_LIB_SYSTEM_CALL,
2452 "%s: failure to determine Current Working Directory %d!",
2453 __func__, errno);
2454 goto tmp_free_and_out;
2455 }
2456 tmp = XMALLOC(MTYPE_TMP,
2457 strlen(cwd) + strlen(config_file) + 2);
2458 sprintf(tmp, "%s/%s", cwd, config_file);
2459 fullpath = tmp;
2460 } else
2461 fullpath = config_file;
2462
2463 confp = fopen(fullpath, "r");
2464
2465 if (confp == NULL) {
2466 flog_warn(
2467 EC_LIB_BACKUP_CONFIG,
2468 "%s: failed to open configuration file %s: %s, checking backup",
2469 __func__, fullpath, safe_strerror(errno));
2470
2471 confp = vty_use_backup_config(fullpath);
2472 if (confp)
2473 flog_warn(
2474 EC_LIB_BACKUP_CONFIG,
2475 "WARNING: using backup configuration file!");
2476 else {
2477 flog_err(
2478 EC_LIB_VTY,
2479 "%s: can't open configuration file [%s]",
2480 __func__, config_file);
2481 goto tmp_free_and_out;
2482 }
2483 }
2484 } else {
2485
2486 host_config_set(config_default_dir);
2487
2488 #ifdef VTYSH
2489 int ret;
2490 struct stat conf_stat;
2491
2492 /* !!!!PLEASE LEAVE!!!!
2493 * This is NEEDED for use with vtysh -b, or else you can get
2494 * a real configuration food fight with a lot garbage in the
2495 * merged configuration file it creates coming from the per
2496 * daemon configuration files. This also allows the daemons
2497 * to start if there default configuration file is not
2498 * present or ignore them, as needed when using vtysh -b to
2499 * configure the daemons at boot - MAG
2500 */
2501
2502 /* Stat for vtysh Zebra.conf, if found startup and wait for
2503 * boot configuration
2504 */
2505
2506 if (strstr(config_default_dir, "vtysh") == NULL) {
2507 ret = stat(integrate_default, &conf_stat);
2508 if (ret >= 0) {
2509 read_success = true;
2510 goto tmp_free_and_out;
2511 }
2512 }
2513 #endif /* VTYSH */
2514 confp = fopen(config_default_dir, "r");
2515 if (confp == NULL) {
2516 flog_err(
2517 EC_LIB_SYSTEM_CALL,
2518 "%s: failed to open configuration file %s: %s, checking backup",
2519 __func__, config_default_dir,
2520 safe_strerror(errno));
2521
2522 confp = vty_use_backup_config(config_default_dir);
2523 if (confp) {
2524 flog_warn(
2525 EC_LIB_BACKUP_CONFIG,
2526 "WARNING: using backup configuration file!");
2527 fullpath = config_default_dir;
2528 } else {
2529 flog_err(EC_LIB_VTY,
2530 "can't open configuration file [%s]",
2531 config_default_dir);
2532 goto tmp_free_and_out;
2533 }
2534 } else
2535 fullpath = config_default_dir;
2536 }
2537
2538 vty_read_file(config, confp);
2539 read_success = true;
2540
2541 fclose(confp);
2542
2543 host_config_set(fullpath);
2544
2545 tmp_free_and_out:
2546 XFREE(MTYPE_TMP, tmp);
2547
2548 return read_success;
2549 }
2550
2551 /* Small utility function which output log to the VTY. */
2552 void vty_log(const char *level, const char *proto_str, const char *format,
2553 struct timestamp_control *ctl, va_list va)
2554 {
2555 unsigned int i;
2556 struct vty *vty;
2557
2558 if (!vtyvec)
2559 return;
2560
2561 for (i = 0; i < vector_active(vtyvec); i++)
2562 if ((vty = vector_slot(vtyvec, i)) != NULL)
2563 if (vty->monitor) {
2564 va_list ac;
2565 va_copy(ac, va);
2566 vty_log_out(vty, level, proto_str, format, ctl,
2567 ac);
2568 va_end(ac);
2569 }
2570 }
2571
2572 /* Async-signal-safe version of vty_log for fixed strings. */
2573 void vty_log_fixed(char *buf, size_t len)
2574 {
2575 unsigned int i;
2576 struct iovec iov[2];
2577 char crlf[4] = "\r\n";
2578
2579 /* vty may not have been initialised */
2580 if (!vtyvec)
2581 return;
2582
2583 iov[0].iov_base = buf;
2584 iov[0].iov_len = len;
2585 iov[1].iov_base = crlf;
2586 iov[1].iov_len = 2;
2587
2588 for (i = 0; i < vector_active(vtyvec); i++) {
2589 struct vty *vty;
2590 if (((vty = vector_slot(vtyvec, i)) != NULL) && vty->monitor)
2591 /* N.B. We don't care about the return code, since
2592 process is
2593 most likely just about to die anyway. */
2594 if (writev(vty->wfd, iov, 2) == -1) {
2595 fprintf(stderr, "Failure to writev: %d\n",
2596 errno);
2597 exit(-1);
2598 }
2599 }
2600 }
2601
2602 int vty_config_enter(struct vty *vty, bool private_config, bool exclusive)
2603 {
2604 if (exclusive && !vty_config_exclusive_lock(vty)) {
2605 vty_out(vty, "VTY configuration is locked by other VTY\n");
2606 return CMD_WARNING;
2607 }
2608
2609 vty->node = CONFIG_NODE;
2610 vty->config = true;
2611 vty->private_config = private_config;
2612 vty->xpath_index = 0;
2613
2614 if (private_config) {
2615 vty->candidate_config = nb_config_dup(running_config);
2616 vty->candidate_config_base = nb_config_dup(running_config);
2617 vty_out(vty,
2618 "Warning: uncommitted changes will be discarded on exit.\n\n");
2619 } else {
2620 vty->candidate_config = vty_shared_candidate_config;
2621 if (frr_get_cli_mode() == FRR_CLI_TRANSACTIONAL)
2622 vty->candidate_config_base =
2623 nb_config_dup(running_config);
2624 }
2625
2626 return CMD_SUCCESS;
2627 }
2628
2629 void vty_config_exit(struct vty *vty)
2630 {
2631 /* Check if there's a pending confirmed commit. */
2632 if (vty->t_confirmed_commit_timeout) {
2633 vty_out(vty,
2634 "WARNING: exiting with a pending confirmed commit. Rolling back to previous configuration.\n\n");
2635 nb_cli_confirmed_commit_rollback(vty);
2636 nb_cli_confirmed_commit_clean(vty);
2637 }
2638
2639 vty_config_exclusive_unlock(vty);
2640
2641 if (vty->candidate_config) {
2642 if (vty->private_config)
2643 nb_config_free(vty->candidate_config);
2644 vty->candidate_config = NULL;
2645 }
2646 if (vty->candidate_config_base) {
2647 nb_config_free(vty->candidate_config_base);
2648 vty->candidate_config_base = NULL;
2649 }
2650
2651 vty->config = false;
2652 }
2653
2654 int vty_config_exclusive_lock(struct vty *vty)
2655 {
2656 if (vty_exclusive_lock == NULL) {
2657 vty_exclusive_lock = vty;
2658 return 1;
2659 }
2660 return 0;
2661 }
2662
2663 void vty_config_exclusive_unlock(struct vty *vty)
2664 {
2665 if (vty_exclusive_lock == vty)
2666 vty_exclusive_lock = NULL;
2667 }
2668
2669 /* Master of the threads. */
2670 static struct thread_master *vty_master;
2671
2672 static void vty_event(enum event event, int sock, struct vty *vty)
2673 {
2674 struct thread *vty_serv_thread = NULL;
2675
2676 switch (event) {
2677 case VTY_SERV:
2678 vty_serv_thread = thread_add_read(vty_master, vty_accept, vty,
2679 sock, NULL);
2680 vector_set_index(Vvty_serv_thread, sock, vty_serv_thread);
2681 break;
2682 #ifdef VTYSH
2683 case VTYSH_SERV:
2684 vty_serv_thread = thread_add_read(vty_master, vtysh_accept, vty,
2685 sock, NULL);
2686 vector_set_index(Vvty_serv_thread, sock, vty_serv_thread);
2687 break;
2688 case VTYSH_READ:
2689 vty->t_read = NULL;
2690 thread_add_read(vty_master, vtysh_read, vty, sock,
2691 &vty->t_read);
2692 break;
2693 case VTYSH_WRITE:
2694 vty->t_write = NULL;
2695 thread_add_write(vty_master, vtysh_write, vty, sock,
2696 &vty->t_write);
2697 break;
2698 #endif /* VTYSH */
2699 case VTY_READ:
2700 vty->t_read = NULL;
2701 thread_add_read(vty_master, vty_read, vty, sock, &vty->t_read);
2702
2703 /* Time out treatment. */
2704 if (vty->v_timeout) {
2705 if (vty->t_timeout)
2706 thread_cancel(vty->t_timeout);
2707 vty->t_timeout = NULL;
2708 thread_add_timer(vty_master, vty_timeout, vty,
2709 vty->v_timeout, &vty->t_timeout);
2710 }
2711 break;
2712 case VTY_WRITE:
2713 thread_add_write(vty_master, vty_flush, vty, sock,
2714 &vty->t_write);
2715 break;
2716 case VTY_TIMEOUT_RESET:
2717 if (vty->t_timeout) {
2718 thread_cancel(vty->t_timeout);
2719 vty->t_timeout = NULL;
2720 }
2721 if (vty->v_timeout) {
2722 vty->t_timeout = NULL;
2723 thread_add_timer(vty_master, vty_timeout, vty,
2724 vty->v_timeout, &vty->t_timeout);
2725 }
2726 break;
2727 }
2728 }
2729
2730 DEFUN_NOSH (config_who,
2731 config_who_cmd,
2732 "who",
2733 "Display who is on vty\n")
2734 {
2735 unsigned int i;
2736 struct vty *v;
2737
2738 for (i = 0; i < vector_active(vtyvec); i++)
2739 if ((v = vector_slot(vtyvec, i)) != NULL)
2740 vty_out(vty, "%svty[%d] connected from %s.\n",
2741 v->config ? "*" : " ", i, v->address);
2742 return CMD_SUCCESS;
2743 }
2744
2745 /* Move to vty configuration mode. */
2746 DEFUN_NOSH (line_vty,
2747 line_vty_cmd,
2748 "line vty",
2749 "Configure a terminal line\n"
2750 "Virtual terminal\n")
2751 {
2752 vty->node = VTY_NODE;
2753 return CMD_SUCCESS;
2754 }
2755
2756 /* Set time out value. */
2757 static int exec_timeout(struct vty *vty, const char *min_str,
2758 const char *sec_str)
2759 {
2760 unsigned long timeout = 0;
2761
2762 /* min_str and sec_str are already checked by parser. So it must be
2763 all digit string. */
2764 if (min_str) {
2765 timeout = strtol(min_str, NULL, 10);
2766 timeout *= 60;
2767 }
2768 if (sec_str)
2769 timeout += strtol(sec_str, NULL, 10);
2770
2771 vty_timeout_val = timeout;
2772 vty->v_timeout = timeout;
2773 vty_event(VTY_TIMEOUT_RESET, 0, vty);
2774
2775
2776 return CMD_SUCCESS;
2777 }
2778
2779 DEFUN (exec_timeout_min,
2780 exec_timeout_min_cmd,
2781 "exec-timeout (0-35791)",
2782 "Set timeout value\n"
2783 "Timeout value in minutes\n")
2784 {
2785 int idx_number = 1;
2786 return exec_timeout(vty, argv[idx_number]->arg, NULL);
2787 }
2788
2789 DEFUN (exec_timeout_sec,
2790 exec_timeout_sec_cmd,
2791 "exec-timeout (0-35791) (0-2147483)",
2792 "Set the EXEC timeout\n"
2793 "Timeout in minutes\n"
2794 "Timeout in seconds\n")
2795 {
2796 int idx_number = 1;
2797 int idx_number_2 = 2;
2798 return exec_timeout(vty, argv[idx_number]->arg,
2799 argv[idx_number_2]->arg);
2800 }
2801
2802 DEFUN (no_exec_timeout,
2803 no_exec_timeout_cmd,
2804 "no exec-timeout",
2805 NO_STR
2806 "Set the EXEC timeout\n")
2807 {
2808 return exec_timeout(vty, NULL, NULL);
2809 }
2810
2811 /* Set vty access class. */
2812 DEFUN (vty_access_class,
2813 vty_access_class_cmd,
2814 "access-class WORD",
2815 "Filter connections based on an IP access list\n"
2816 "IP access list\n")
2817 {
2818 int idx_word = 1;
2819 if (vty_accesslist_name)
2820 XFREE(MTYPE_VTY, vty_accesslist_name);
2821
2822 vty_accesslist_name = XSTRDUP(MTYPE_VTY, argv[idx_word]->arg);
2823
2824 return CMD_SUCCESS;
2825 }
2826
2827 /* Clear vty access class. */
2828 DEFUN (no_vty_access_class,
2829 no_vty_access_class_cmd,
2830 "no access-class [WORD]",
2831 NO_STR
2832 "Filter connections based on an IP access list\n"
2833 "IP access list\n")
2834 {
2835 int idx_word = 2;
2836 const char *accesslist = (argc == 3) ? argv[idx_word]->arg : NULL;
2837 if (!vty_accesslist_name
2838 || (argc == 3 && strcmp(vty_accesslist_name, accesslist))) {
2839 vty_out(vty, "Access-class is not currently applied to vty\n");
2840 return CMD_WARNING_CONFIG_FAILED;
2841 }
2842
2843 XFREE(MTYPE_VTY, vty_accesslist_name);
2844
2845 vty_accesslist_name = NULL;
2846
2847 return CMD_SUCCESS;
2848 }
2849
2850 /* Set vty access class. */
2851 DEFUN (vty_ipv6_access_class,
2852 vty_ipv6_access_class_cmd,
2853 "ipv6 access-class WORD",
2854 IPV6_STR
2855 "Filter connections based on an IP access list\n"
2856 "IPv6 access list\n")
2857 {
2858 int idx_word = 2;
2859 if (vty_ipv6_accesslist_name)
2860 XFREE(MTYPE_VTY, vty_ipv6_accesslist_name);
2861
2862 vty_ipv6_accesslist_name = XSTRDUP(MTYPE_VTY, argv[idx_word]->arg);
2863
2864 return CMD_SUCCESS;
2865 }
2866
2867 /* Clear vty access class. */
2868 DEFUN (no_vty_ipv6_access_class,
2869 no_vty_ipv6_access_class_cmd,
2870 "no ipv6 access-class [WORD]",
2871 NO_STR
2872 IPV6_STR
2873 "Filter connections based on an IP access list\n"
2874 "IPv6 access list\n")
2875 {
2876 int idx_word = 3;
2877 const char *accesslist = (argc == 4) ? argv[idx_word]->arg : NULL;
2878
2879 if (!vty_ipv6_accesslist_name
2880 || (argc == 4 && strcmp(vty_ipv6_accesslist_name, accesslist))) {
2881 vty_out(vty,
2882 "IPv6 access-class is not currently applied to vty\n");
2883 return CMD_WARNING_CONFIG_FAILED;
2884 }
2885
2886 XFREE(MTYPE_VTY, vty_ipv6_accesslist_name);
2887
2888 vty_ipv6_accesslist_name = NULL;
2889
2890 return CMD_SUCCESS;
2891 }
2892
2893 /* vty login. */
2894 DEFUN (vty_login,
2895 vty_login_cmd,
2896 "login",
2897 "Enable password checking\n")
2898 {
2899 no_password_check = 0;
2900 return CMD_SUCCESS;
2901 }
2902
2903 DEFUN (no_vty_login,
2904 no_vty_login_cmd,
2905 "no login",
2906 NO_STR
2907 "Enable password checking\n")
2908 {
2909 no_password_check = 1;
2910 return CMD_SUCCESS;
2911 }
2912
2913 DEFUN (service_advanced_vty,
2914 service_advanced_vty_cmd,
2915 "service advanced-vty",
2916 "Set up miscellaneous service\n"
2917 "Enable advanced mode vty interface\n")
2918 {
2919 host.advanced = 1;
2920 return CMD_SUCCESS;
2921 }
2922
2923 DEFUN (no_service_advanced_vty,
2924 no_service_advanced_vty_cmd,
2925 "no service advanced-vty",
2926 NO_STR
2927 "Set up miscellaneous service\n"
2928 "Enable advanced mode vty interface\n")
2929 {
2930 host.advanced = 0;
2931 return CMD_SUCCESS;
2932 }
2933
2934 DEFUN_NOSH (terminal_monitor,
2935 terminal_monitor_cmd,
2936 "terminal monitor",
2937 "Set terminal line parameters\n"
2938 "Copy debug output to the current terminal line\n")
2939 {
2940 vty->monitor = 1;
2941 return CMD_SUCCESS;
2942 }
2943
2944 DEFUN_NOSH (terminal_no_monitor,
2945 terminal_no_monitor_cmd,
2946 "terminal no monitor",
2947 "Set terminal line parameters\n"
2948 NO_STR
2949 "Copy debug output to the current terminal line\n")
2950 {
2951 vty->monitor = 0;
2952 return CMD_SUCCESS;
2953 }
2954
2955 DEFUN_NOSH (no_terminal_monitor,
2956 no_terminal_monitor_cmd,
2957 "no terminal monitor",
2958 NO_STR
2959 "Set terminal line parameters\n"
2960 "Copy debug output to the current terminal line\n")
2961 {
2962 return terminal_no_monitor(self, vty, argc, argv);
2963 }
2964
2965
2966 DEFUN_NOSH (show_history,
2967 show_history_cmd,
2968 "show history",
2969 SHOW_STR
2970 "Display the session command history\n")
2971 {
2972 int index;
2973
2974 for (index = vty->hindex + 1; index != vty->hindex;) {
2975 if (index == VTY_MAXHIST) {
2976 index = 0;
2977 continue;
2978 }
2979
2980 if (vty->hist[index] != NULL)
2981 vty_out(vty, " %s\n", vty->hist[index]);
2982
2983 index++;
2984 }
2985
2986 return CMD_SUCCESS;
2987 }
2988
2989 /* vty login. */
2990 DEFUN (log_commands,
2991 log_commands_cmd,
2992 "log commands",
2993 "Logging control\n"
2994 "Log all commands (can't be unset without restart)\n")
2995 {
2996 do_log_commands = 1;
2997 return CMD_SUCCESS;
2998 }
2999
3000 /* Display current configuration. */
3001 static int vty_config_write(struct vty *vty)
3002 {
3003 vty_out(vty, "line vty\n");
3004
3005 if (vty_accesslist_name)
3006 vty_out(vty, " access-class %s\n", vty_accesslist_name);
3007
3008 if (vty_ipv6_accesslist_name)
3009 vty_out(vty, " ipv6 access-class %s\n",
3010 vty_ipv6_accesslist_name);
3011
3012 /* exec-timeout */
3013 if (vty_timeout_val != VTY_TIMEOUT_DEFAULT)
3014 vty_out(vty, " exec-timeout %ld %ld\n", vty_timeout_val / 60,
3015 vty_timeout_val % 60);
3016
3017 /* login */
3018 if (no_password_check)
3019 vty_out(vty, " no login\n");
3020
3021 if (do_log_commands)
3022 vty_out(vty, "log commands\n");
3023
3024 vty_out(vty, "!\n");
3025
3026 return CMD_SUCCESS;
3027 }
3028
3029 struct cmd_node vty_node = {
3030 VTY_NODE, "%s(config-line)# ", 1,
3031 };
3032
3033 /* Reset all VTY status. */
3034 void vty_reset(void)
3035 {
3036 unsigned int i;
3037 struct vty *vty;
3038 struct thread *vty_serv_thread;
3039
3040 for (i = 0; i < vector_active(vtyvec); i++)
3041 if ((vty = vector_slot(vtyvec, i)) != NULL) {
3042 buffer_reset(vty->lbuf);
3043 buffer_reset(vty->obuf);
3044 vty->status = VTY_CLOSE;
3045 vty_close(vty);
3046 }
3047
3048 for (i = 0; i < vector_active(Vvty_serv_thread); i++)
3049 if ((vty_serv_thread = vector_slot(Vvty_serv_thread, i))
3050 != NULL) {
3051 thread_cancel(vty_serv_thread);
3052 vector_slot(Vvty_serv_thread, i) = NULL;
3053 close(i);
3054 }
3055
3056 vty_timeout_val = VTY_TIMEOUT_DEFAULT;
3057
3058 if (vty_accesslist_name) {
3059 XFREE(MTYPE_VTY, vty_accesslist_name);
3060 vty_accesslist_name = NULL;
3061 }
3062
3063 if (vty_ipv6_accesslist_name) {
3064 XFREE(MTYPE_VTY, vty_ipv6_accesslist_name);
3065 vty_ipv6_accesslist_name = NULL;
3066 }
3067 }
3068
3069 static void vty_save_cwd(void)
3070 {
3071 char cwd[MAXPATHLEN];
3072 char *c;
3073
3074 c = getcwd(cwd, MAXPATHLEN);
3075
3076 if (!c) {
3077 /*
3078 * At this point if these go wrong, more than likely
3079 * the whole world is coming down around us
3080 * Hence not worrying about it too much.
3081 */
3082 if (!chdir(SYSCONFDIR)) {
3083 flog_err_sys(EC_LIB_SYSTEM_CALL,
3084 "Failure to chdir to %s, errno: %d",
3085 SYSCONFDIR, errno);
3086 exit(-1);
3087 }
3088 if (getcwd(cwd, MAXPATHLEN) == NULL) {
3089 flog_err_sys(EC_LIB_SYSTEM_CALL,
3090 "Failure to getcwd, errno: %d", errno);
3091 exit(-1);
3092 }
3093 }
3094
3095 vty_cwd = XMALLOC(MTYPE_TMP, strlen(cwd) + 1);
3096 strcpy(vty_cwd, cwd);
3097 }
3098
3099 char *vty_get_cwd(void)
3100 {
3101 return vty_cwd;
3102 }
3103
3104 int vty_shell(struct vty *vty)
3105 {
3106 return vty->type == VTY_SHELL ? 1 : 0;
3107 }
3108
3109 int vty_shell_serv(struct vty *vty)
3110 {
3111 return vty->type == VTY_SHELL_SERV ? 1 : 0;
3112 }
3113
3114 void vty_init_vtysh(void)
3115 {
3116 vtyvec = vector_init(VECTOR_MIN_SIZE);
3117 }
3118
3119 /* Install vty's own commands like `who' command. */
3120 void vty_init(struct thread_master *master_thread)
3121 {
3122 /* For further configuration read, preserve current directory. */
3123 vty_save_cwd();
3124
3125 vtyvec = vector_init(VECTOR_MIN_SIZE);
3126
3127 vty_master = master_thread;
3128
3129 atexit(vty_stdio_atexit);
3130
3131 /* Initilize server thread vector. */
3132 Vvty_serv_thread = vector_init(VECTOR_MIN_SIZE);
3133
3134 /* Install bgp top node. */
3135 install_node(&vty_node, vty_config_write);
3136
3137 install_element(VIEW_NODE, &config_who_cmd);
3138 install_element(VIEW_NODE, &show_history_cmd);
3139 install_element(CONFIG_NODE, &line_vty_cmd);
3140 install_element(CONFIG_NODE, &service_advanced_vty_cmd);
3141 install_element(CONFIG_NODE, &no_service_advanced_vty_cmd);
3142 install_element(CONFIG_NODE, &show_history_cmd);
3143 install_element(CONFIG_NODE, &log_commands_cmd);
3144 install_element(ENABLE_NODE, &terminal_monitor_cmd);
3145 install_element(ENABLE_NODE, &terminal_no_monitor_cmd);
3146 install_element(ENABLE_NODE, &no_terminal_monitor_cmd);
3147
3148 install_default(VTY_NODE);
3149 install_element(VTY_NODE, &exec_timeout_min_cmd);
3150 install_element(VTY_NODE, &exec_timeout_sec_cmd);
3151 install_element(VTY_NODE, &no_exec_timeout_cmd);
3152 install_element(VTY_NODE, &vty_access_class_cmd);
3153 install_element(VTY_NODE, &no_vty_access_class_cmd);
3154 install_element(VTY_NODE, &vty_login_cmd);
3155 install_element(VTY_NODE, &no_vty_login_cmd);
3156 install_element(VTY_NODE, &vty_ipv6_access_class_cmd);
3157 install_element(VTY_NODE, &no_vty_ipv6_access_class_cmd);
3158 }
3159
3160 void vty_terminate(void)
3161 {
3162 XFREE(MTYPE_TMP, vty_cwd);
3163
3164 if (vtyvec && Vvty_serv_thread) {
3165 vty_reset();
3166 vector_free(vtyvec);
3167 vector_free(Vvty_serv_thread);
3168 vtyvec = NULL;
3169 Vvty_serv_thread = NULL;
3170 }
3171 }