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