]> git.proxmox.com Git - mirror_frr.git/blob - lib/vty.c
*: rename zlog_fer -> flog_err
[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(LIB_ERR_SYSTEM_CALL,
1977 "getaddrinfo failed: %s", 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(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(LIB_ERR_SOCKET,
2058 "Cannot bind path %s: %s",
2059 path, safe_strerror(errno));
2060 close(sock); /* Avoid sd leak. */
2061 return;
2062 }
2063
2064 ret = listen(sock, 5);
2065 if (ret < 0) {
2066 flog_err(LIB_ERR_SOCKET,
2067 "listen(fd %d) failed: %s", sock,
2068 safe_strerror(errno));
2069 close(sock); /* Avoid sd leak. */
2070 return;
2071 }
2072
2073 umask(old_mask);
2074
2075 zprivs_get_ids(&ids);
2076
2077 /* Hack: ids.gid_vty is actually a uint, but we stored -1 in it
2078 earlier for the case when we don't need to chown the file
2079 type casting it here to make a compare */
2080 if ((int)ids.gid_vty > 0) {
2081 /* set group of socket */
2082 if (chown(path, -1, ids.gid_vty)) {
2083 flog_err(LIB_ERR_SYSTEM_CALL,
2084 "vty_serv_un: could chown socket, %s",
2085 safe_strerror(errno));
2086 }
2087 }
2088
2089 vty_event(VTYSH_SERV, sock, NULL);
2090 }
2091
2092 /* #define VTYSH_DEBUG 1 */
2093
2094 static int vtysh_accept(struct thread *thread)
2095 {
2096 int accept_sock;
2097 int sock;
2098 int client_len;
2099 struct sockaddr_un client;
2100 struct vty *vty;
2101
2102 accept_sock = THREAD_FD(thread);
2103
2104 vty_event(VTYSH_SERV, accept_sock, NULL);
2105
2106 memset(&client, 0, sizeof(struct sockaddr_un));
2107 client_len = sizeof(struct sockaddr_un);
2108
2109 sock = accept(accept_sock, (struct sockaddr *)&client,
2110 (socklen_t *)&client_len);
2111
2112 if (sock < 0) {
2113 zlog_warn("can't accept vty socket : %s", safe_strerror(errno));
2114 return -1;
2115 }
2116
2117 if (set_nonblocking(sock) < 0) {
2118 zlog_warn(
2119 "vtysh_accept: could not set vty socket %d to non-blocking,"
2120 " %s, closing",
2121 sock, safe_strerror(errno));
2122 close(sock);
2123 return -1;
2124 }
2125 set_cloexec(sock);
2126
2127 #ifdef VTYSH_DEBUG
2128 printf("VTY shell accept\n");
2129 #endif /* VTYSH_DEBUG */
2130
2131 vty = vty_new();
2132 vty->fd = sock;
2133 vty->wfd = sock;
2134 vty->type = VTY_SHELL_SERV;
2135 vty->node = VIEW_NODE;
2136
2137 vty_event(VTYSH_READ, sock, vty);
2138
2139 return 0;
2140 }
2141
2142 static int vtysh_flush(struct vty *vty)
2143 {
2144 switch (buffer_flush_available(vty->obuf, vty->wfd)) {
2145 case BUFFER_PENDING:
2146 vty_event(VTYSH_WRITE, vty->wfd, vty);
2147 break;
2148 case BUFFER_ERROR:
2149 vty->monitor =
2150 0; /* disable monitoring to avoid infinite recursion */
2151 zlog_warn("%s: write error to fd %d, closing", __func__,
2152 vty->fd);
2153 buffer_reset(vty->lbuf);
2154 buffer_reset(vty->obuf);
2155 vty_close(vty);
2156 return -1;
2157 break;
2158 case BUFFER_EMPTY:
2159 break;
2160 }
2161 return 0;
2162 }
2163
2164 static int vtysh_read(struct thread *thread)
2165 {
2166 int ret;
2167 int sock;
2168 int nbytes;
2169 struct vty *vty;
2170 unsigned char buf[VTY_READ_BUFSIZ];
2171 unsigned char *p;
2172 uint8_t header[4] = {0, 0, 0, 0};
2173
2174 sock = THREAD_FD(thread);
2175 vty = THREAD_ARG(thread);
2176 vty->t_read = NULL;
2177
2178 if ((nbytes = read(sock, buf, VTY_READ_BUFSIZ)) <= 0) {
2179 if (nbytes < 0) {
2180 if (ERRNO_IO_RETRY(errno)) {
2181 vty_event(VTYSH_READ, sock, vty);
2182 return 0;
2183 }
2184 vty->monitor = 0; /* disable monitoring to avoid
2185 infinite recursion */
2186 zlog_warn(
2187 "%s: read failed on vtysh client fd %d, closing: %s",
2188 __func__, sock, safe_strerror(errno));
2189 }
2190 buffer_reset(vty->lbuf);
2191 buffer_reset(vty->obuf);
2192 vty_close(vty);
2193 #ifdef VTYSH_DEBUG
2194 printf("close vtysh\n");
2195 #endif /* VTYSH_DEBUG */
2196 return 0;
2197 }
2198
2199 #ifdef VTYSH_DEBUG
2200 printf("line: %.*s\n", nbytes, buf);
2201 #endif /* VTYSH_DEBUG */
2202
2203 if (vty->length + nbytes >= VTY_BUFSIZ) {
2204 /* Clear command line buffer. */
2205 vty->cp = vty->length = 0;
2206 vty_clear_buf(vty);
2207 vty_out(vty, "%% Command is too long.\n");
2208 } else {
2209 for (p = buf; p < buf + nbytes; p++) {
2210 vty->buf[vty->length++] = *p;
2211 if (*p == '\0') {
2212 /* Pass this line to parser. */
2213 ret = vty_execute(vty);
2214 /* Note that vty_execute clears the command buffer and resets
2215 vty->length to 0. */
2216
2217 /* Return result. */
2218 #ifdef VTYSH_DEBUG
2219 printf("result: %d\n", ret);
2220 printf("vtysh node: %d\n", vty->node);
2221 #endif /* VTYSH_DEBUG */
2222
2223 /* hack for asynchronous "write integrated"
2224 * - other commands in "buf" will be ditched
2225 * - input during pending config-write is
2226 * "unsupported" */
2227 if (ret == CMD_SUSPEND)
2228 break;
2229
2230 /* warning: watchfrr hardcodes this result write
2231 */
2232 header[3] = ret;
2233 buffer_put(vty->obuf, header, 4);
2234
2235 if (!vty->t_write && (vtysh_flush(vty) < 0))
2236 /* Try to flush results; exit if a write
2237 * error occurs. */
2238 return 0;
2239 }
2240 }
2241 }
2242
2243 if (vty->status == VTY_CLOSE)
2244 vty_close(vty);
2245 else
2246 vty_event(VTYSH_READ, sock, vty);
2247
2248 return 0;
2249 }
2250
2251 static int vtysh_write(struct thread *thread)
2252 {
2253 struct vty *vty = THREAD_ARG(thread);
2254
2255 vty->t_write = NULL;
2256 vtysh_flush(vty);
2257 return 0;
2258 }
2259
2260 #endif /* VTYSH */
2261
2262 /* Determine address family to bind. */
2263 void vty_serv_sock(const char *addr, unsigned short port, const char *path)
2264 {
2265 /* If port is set to 0, do not listen on TCP/IP at all! */
2266 if (port)
2267 vty_serv_sock_addrinfo(addr, port);
2268
2269 #ifdef VTYSH
2270 vty_serv_un(path);
2271 #endif /* VTYSH */
2272 }
2273
2274 /* Close vty interface. Warning: call this only from functions that
2275 will be careful not to access the vty afterwards (since it has
2276 now been freed). This is safest from top-level functions (called
2277 directly by the thread dispatcher). */
2278 void vty_close(struct vty *vty)
2279 {
2280 int i;
2281 bool was_stdio = false;
2282
2283 /* Cancel threads.*/
2284 if (vty->t_read)
2285 thread_cancel(vty->t_read);
2286 if (vty->t_write)
2287 thread_cancel(vty->t_write);
2288 if (vty->t_timeout)
2289 thread_cancel(vty->t_timeout);
2290
2291 /* Flush buffer. */
2292 buffer_flush_all(vty->obuf, vty->wfd);
2293
2294 /* Free input buffer. */
2295 buffer_free(vty->obuf);
2296 buffer_free(vty->lbuf);
2297
2298 /* Free command history. */
2299 for (i = 0; i < VTY_MAXHIST; i++)
2300 if (vty->hist[i])
2301 XFREE(MTYPE_VTY_HIST, vty->hist[i]);
2302
2303 /* Unset vector. */
2304 if (vty->fd != -1)
2305 vector_unset(vtyvec, vty->fd);
2306
2307 if (vty->wfd > 0 && vty->type == VTY_FILE)
2308 fsync(vty->wfd);
2309
2310 /* Close socket.
2311 * note check is for fd > STDERR_FILENO, not fd != -1.
2312 * We never close stdin/stdout/stderr here, because we may be
2313 * running in foreground mode with logging to stdout. Also,
2314 * additionally, we'd need to replace these fds with /dev/null. */
2315 if (vty->wfd > STDERR_FILENO && vty->wfd != vty->fd)
2316 close(vty->wfd);
2317 if (vty->fd > STDERR_FILENO)
2318 close(vty->fd);
2319 if (vty->fd == STDIN_FILENO)
2320 was_stdio = true;
2321
2322 if (vty->buf)
2323 XFREE(MTYPE_VTY, vty->buf);
2324
2325 if (vty->error_buf)
2326 XFREE(MTYPE_VTY, vty->error_buf);
2327
2328 /* Check configure. */
2329 vty_config_unlock(vty);
2330
2331 /* OK free vty. */
2332 XFREE(MTYPE_VTY, vty);
2333
2334 if (was_stdio)
2335 vty_stdio_reset(0);
2336 }
2337
2338 /* When time out occur output message then close connection. */
2339 static int vty_timeout(struct thread *thread)
2340 {
2341 struct vty *vty;
2342
2343 vty = THREAD_ARG(thread);
2344 vty->t_timeout = NULL;
2345 vty->v_timeout = 0;
2346
2347 /* Clear buffer*/
2348 buffer_reset(vty->lbuf);
2349 buffer_reset(vty->obuf);
2350 vty_out(vty, "\nVty connection is timed out.\n");
2351
2352 /* Close connection. */
2353 vty->status = VTY_CLOSE;
2354 vty_close(vty);
2355
2356 return 0;
2357 }
2358
2359 /* Read up configuration file from file_name. */
2360 static void vty_read_file(FILE *confp)
2361 {
2362 int ret;
2363 struct vty *vty;
2364 unsigned int line_num = 0;
2365
2366 vty = vty_new();
2367 /* vty_close won't close stderr; if some config command prints
2368 * something it'll end up there. (not ideal; it'd be beter if output
2369 * from a file-load went to logging instead. Also note that if this
2370 * function is called after daemonizing, stderr will be /dev/null.)
2371 *
2372 * vty->fd will be -1 from vty_new()
2373 */
2374 vty->wfd = STDERR_FILENO;
2375 vty->type = VTY_FILE;
2376 vty->node = CONFIG_NODE;
2377
2378 /* Execute configuration file */
2379 ret = config_from_file(vty, confp, &line_num);
2380
2381 /* Flush any previous errors before printing messages below */
2382 buffer_flush_all(vty->obuf, vty->wfd);
2383
2384 if (!((ret == CMD_SUCCESS) || (ret == CMD_ERR_NOTHING_TODO))) {
2385 const char *message = NULL;
2386 char *nl;
2387
2388 switch (ret) {
2389 case CMD_ERR_AMBIGUOUS:
2390 message = "Ambiguous command";
2391 break;
2392 case CMD_ERR_NO_MATCH:
2393 message = "No such command";
2394 break;
2395 case CMD_WARNING:
2396 message = "Command returned Warning";
2397 break;
2398 case CMD_WARNING_CONFIG_FAILED:
2399 message = "Command returned Warning Config Failed";
2400 break;
2401 case CMD_ERR_INCOMPLETE:
2402 message = "Command returned Incomplete";
2403 break;
2404 case CMD_ERR_EXEED_ARGC_MAX:
2405 message =
2406 "Command exceeded maximum number of Arguments";
2407 break;
2408 default:
2409 message = "Command returned unhandled error message";
2410 break;
2411 }
2412
2413 nl = strchr(vty->error_buf, '\n');
2414 if (nl)
2415 *nl = '\0';
2416 flog_err(LIB_ERR_VTY,
2417 "ERROR: %s on config line %u: %s", message, line_num,
2418 vty->error_buf);
2419 }
2420
2421 vty_close(vty);
2422 }
2423
2424 static FILE *vty_use_backup_config(const char *fullpath)
2425 {
2426 char *fullpath_sav, *fullpath_tmp;
2427 FILE *ret = NULL;
2428 int tmp, sav;
2429 int c;
2430 char buffer[512];
2431
2432 fullpath_sav = malloc(strlen(fullpath) + strlen(CONF_BACKUP_EXT) + 1);
2433 strcpy(fullpath_sav, fullpath);
2434 strcat(fullpath_sav, CONF_BACKUP_EXT);
2435
2436 sav = open(fullpath_sav, O_RDONLY);
2437 if (sav < 0) {
2438 free(fullpath_sav);
2439 return NULL;
2440 }
2441
2442 fullpath_tmp = malloc(strlen(fullpath) + 8);
2443 sprintf(fullpath_tmp, "%s.XXXXXX", fullpath);
2444
2445 /* Open file to configuration write. */
2446 tmp = mkstemp(fullpath_tmp);
2447 if (tmp < 0)
2448 goto out_close_sav;
2449
2450 if (fchmod(tmp, CONFIGFILE_MASK) != 0)
2451 goto out_close;
2452
2453 while ((c = read(sav, buffer, 512)) > 0) {
2454 if (write(tmp, buffer, c) <= 0)
2455 goto out_close;
2456 }
2457 close(sav);
2458 close(tmp);
2459
2460 if (rename(fullpath_tmp, fullpath) == 0)
2461 ret = fopen(fullpath, "r");
2462 else
2463 unlink(fullpath_tmp);
2464
2465 if (0) {
2466 out_close:
2467 close(tmp);
2468 unlink(fullpath_tmp);
2469 out_close_sav:
2470 close(sav);
2471 }
2472
2473 free(fullpath_sav);
2474 free(fullpath_tmp);
2475 return ret;
2476 }
2477
2478 /* Read up configuration file from file_name. */
2479 bool vty_read_config(const char *config_file, char *config_default_dir)
2480 {
2481 char cwd[MAXPATHLEN];
2482 FILE *confp = NULL;
2483 const char *fullpath;
2484 char *tmp = NULL;
2485 bool read_success = false;
2486
2487 /* If -f flag specified. */
2488 if (config_file != NULL) {
2489 if (!IS_DIRECTORY_SEP(config_file[0])) {
2490 if (getcwd(cwd, MAXPATHLEN) == NULL) {
2491 flog_err(LIB_ERR_SYSTEM_CALL,
2492 "Failure to determine Current Working Directory %d!",
2493 errno);
2494 exit(1);
2495 }
2496 tmp = XMALLOC(MTYPE_TMP,
2497 strlen(cwd) + strlen(config_file) + 2);
2498 sprintf(tmp, "%s/%s", cwd, config_file);
2499 fullpath = tmp;
2500 } else
2501 fullpath = config_file;
2502
2503 confp = fopen(fullpath, "r");
2504
2505 if (confp == NULL) {
2506 zlog_warn("%s: failed to open configuration file %s: %s, checking backup",
2507 __func__, fullpath, safe_strerror(errno));
2508
2509 confp = vty_use_backup_config(fullpath);
2510 if (confp)
2511 zlog_warn(
2512 "WARNING: using backup configuration file!");
2513 else {
2514 flog_err(LIB_ERR_VTY,
2515 "can't open configuration file [%s]",
2516 config_file);
2517 exit(1);
2518 }
2519 }
2520 } else {
2521
2522 host_config_set(config_default_dir);
2523
2524 #ifdef VTYSH
2525 int ret;
2526 struct stat conf_stat;
2527
2528 /* !!!!PLEASE LEAVE!!!!
2529 * This is NEEDED for use with vtysh -b, or else you can get
2530 * a real configuration food fight with a lot garbage in the
2531 * merged configuration file it creates coming from the per
2532 * daemon configuration files. This also allows the daemons
2533 * to start if there default configuration file is not
2534 * present or ignore them, as needed when using vtysh -b to
2535 * configure the daemons at boot - MAG
2536 */
2537
2538 /* Stat for vtysh Zebra.conf, if found startup and wait for
2539 * boot configuration
2540 */
2541
2542 if (strstr(config_default_dir, "vtysh") == NULL) {
2543 ret = stat(integrate_default, &conf_stat);
2544 if (ret >= 0) {
2545 read_success = true;
2546 goto tmp_free_and_out;
2547 }
2548 }
2549 #endif /* VTYSH */
2550 confp = fopen(config_default_dir, "r");
2551 if (confp == NULL) {
2552 zlog_warn("%s: failed to open configuration file %s: %s, checking backup",
2553 __func__, config_default_dir,
2554 safe_strerror(errno));
2555
2556 confp = vty_use_backup_config(config_default_dir);
2557 if (confp) {
2558 zlog_warn(
2559 "WARNING: using backup configuration file!");
2560 fullpath = config_default_dir;
2561 } else {
2562 flog_err(LIB_ERR_VTY,
2563 "can't open configuration file [%s]",
2564 config_default_dir);
2565 goto tmp_free_and_out;
2566 }
2567 } else
2568 fullpath = config_default_dir;
2569 }
2570
2571 vty_read_file(confp);
2572 read_success = true;
2573
2574 fclose(confp);
2575
2576 host_config_set(fullpath);
2577
2578 tmp_free_and_out:
2579 if (tmp)
2580 XFREE(MTYPE_TMP, tmp);
2581
2582 return read_success;
2583 }
2584
2585 /* Small utility function which output log to the VTY. */
2586 void vty_log(const char *level, const char *proto_str, const char *format,
2587 struct timestamp_control *ctl, va_list va)
2588 {
2589 unsigned int i;
2590 struct vty *vty;
2591
2592 if (!vtyvec)
2593 return;
2594
2595 for (i = 0; i < vector_active(vtyvec); i++)
2596 if ((vty = vector_slot(vtyvec, i)) != NULL)
2597 if (vty->monitor) {
2598 va_list ac;
2599 va_copy(ac, va);
2600 vty_log_out(vty, level, proto_str, format, ctl,
2601 ac);
2602 va_end(ac);
2603 }
2604 }
2605
2606 /* Async-signal-safe version of vty_log for fixed strings. */
2607 void vty_log_fixed(char *buf, size_t len)
2608 {
2609 unsigned int i;
2610 struct iovec iov[2];
2611 char crlf[4] = "\r\n";
2612
2613 /* vty may not have been initialised */
2614 if (!vtyvec)
2615 return;
2616
2617 iov[0].iov_base = buf;
2618 iov[0].iov_len = len;
2619 iov[1].iov_base = crlf;
2620 iov[1].iov_len = 2;
2621
2622 for (i = 0; i < vector_active(vtyvec); i++) {
2623 struct vty *vty;
2624 if (((vty = vector_slot(vtyvec, i)) != NULL) && vty->monitor)
2625 /* N.B. We don't care about the return code, since
2626 process is
2627 most likely just about to die anyway. */
2628 if (writev(vty->wfd, iov, 2) == -1) {
2629 fprintf(stderr, "Failure to writev: %d\n",
2630 errno);
2631 exit(-1);
2632 }
2633 }
2634 }
2635
2636 int vty_config_lock(struct vty *vty)
2637 {
2638 if (vty_config_is_lockless)
2639 return 1;
2640 if (vty_config == 0) {
2641 vty->config = 1;
2642 vty_config = 1;
2643 }
2644 return vty->config;
2645 }
2646
2647 int vty_config_unlock(struct vty *vty)
2648 {
2649 if (vty_config_is_lockless)
2650 return 0;
2651 if (vty_config == 1 && vty->config == 1) {
2652 vty->config = 0;
2653 vty_config = 0;
2654 }
2655 return vty->config;
2656 }
2657
2658 void vty_config_lockless(void)
2659 {
2660 vty_config_is_lockless = 1;
2661 }
2662
2663 /* Master of the threads. */
2664 static struct thread_master *vty_master;
2665
2666 static void vty_event(enum event event, int sock, struct vty *vty)
2667 {
2668 struct thread *vty_serv_thread = NULL;
2669
2670 switch (event) {
2671 case VTY_SERV:
2672 vty_serv_thread = thread_add_read(vty_master, vty_accept, vty,
2673 sock, NULL);
2674 vector_set_index(Vvty_serv_thread, sock, vty_serv_thread);
2675 break;
2676 #ifdef VTYSH
2677 case VTYSH_SERV:
2678 vty_serv_thread = thread_add_read(vty_master, vtysh_accept, vty,
2679 sock, NULL);
2680 vector_set_index(Vvty_serv_thread, sock, vty_serv_thread);
2681 break;
2682 case VTYSH_READ:
2683 vty->t_read = NULL;
2684 thread_add_read(vty_master, vtysh_read, vty, sock,
2685 &vty->t_read);
2686 break;
2687 case VTYSH_WRITE:
2688 vty->t_write = NULL;
2689 thread_add_write(vty_master, vtysh_write, vty, sock,
2690 &vty->t_write);
2691 break;
2692 #endif /* VTYSH */
2693 case VTY_READ:
2694 vty->t_read = NULL;
2695 thread_add_read(vty_master, vty_read, vty, sock, &vty->t_read);
2696
2697 /* Time out treatment. */
2698 if (vty->v_timeout) {
2699 if (vty->t_timeout)
2700 thread_cancel(vty->t_timeout);
2701 vty->t_timeout = NULL;
2702 thread_add_timer(vty_master, vty_timeout, vty,
2703 vty->v_timeout, &vty->t_timeout);
2704 }
2705 break;
2706 case VTY_WRITE:
2707 thread_add_write(vty_master, vty_flush, vty, sock,
2708 &vty->t_write);
2709 break;
2710 case VTY_TIMEOUT_RESET:
2711 if (vty->t_timeout) {
2712 thread_cancel(vty->t_timeout);
2713 vty->t_timeout = NULL;
2714 }
2715 if (vty->v_timeout) {
2716 vty->t_timeout = NULL;
2717 thread_add_timer(vty_master, vty_timeout, vty,
2718 vty->v_timeout, &vty->t_timeout);
2719 }
2720 break;
2721 }
2722 }
2723
2724 DEFUN_NOSH (config_who,
2725 config_who_cmd,
2726 "who",
2727 "Display who is on vty\n")
2728 {
2729 unsigned int i;
2730 struct vty *v;
2731
2732 for (i = 0; i < vector_active(vtyvec); i++)
2733 if ((v = vector_slot(vtyvec, i)) != NULL)
2734 vty_out(vty, "%svty[%d] connected from %s.\n",
2735 v->config ? "*" : " ", i, v->address);
2736 return CMD_SUCCESS;
2737 }
2738
2739 /* Move to vty configuration mode. */
2740 DEFUN_NOSH (line_vty,
2741 line_vty_cmd,
2742 "line vty",
2743 "Configure a terminal line\n"
2744 "Virtual terminal\n")
2745 {
2746 vty->node = VTY_NODE;
2747 return CMD_SUCCESS;
2748 }
2749
2750 /* Set time out value. */
2751 static int exec_timeout(struct vty *vty, const char *min_str,
2752 const char *sec_str)
2753 {
2754 unsigned long timeout = 0;
2755
2756 /* min_str and sec_str are already checked by parser. So it must be
2757 all digit string. */
2758 if (min_str) {
2759 timeout = strtol(min_str, NULL, 10);
2760 timeout *= 60;
2761 }
2762 if (sec_str)
2763 timeout += strtol(sec_str, NULL, 10);
2764
2765 vty_timeout_val = timeout;
2766 vty->v_timeout = timeout;
2767 vty_event(VTY_TIMEOUT_RESET, 0, vty);
2768
2769
2770 return CMD_SUCCESS;
2771 }
2772
2773 DEFUN (exec_timeout_min,
2774 exec_timeout_min_cmd,
2775 "exec-timeout (0-35791)",
2776 "Set timeout value\n"
2777 "Timeout value in minutes\n")
2778 {
2779 int idx_number = 1;
2780 return exec_timeout(vty, argv[idx_number]->arg, NULL);
2781 }
2782
2783 DEFUN (exec_timeout_sec,
2784 exec_timeout_sec_cmd,
2785 "exec-timeout (0-35791) (0-2147483)",
2786 "Set the EXEC timeout\n"
2787 "Timeout in minutes\n"
2788 "Timeout in seconds\n")
2789 {
2790 int idx_number = 1;
2791 int idx_number_2 = 2;
2792 return exec_timeout(vty, argv[idx_number]->arg,
2793 argv[idx_number_2]->arg);
2794 }
2795
2796 DEFUN (no_exec_timeout,
2797 no_exec_timeout_cmd,
2798 "no exec-timeout",
2799 NO_STR
2800 "Set the EXEC timeout\n")
2801 {
2802 return exec_timeout(vty, NULL, NULL);
2803 }
2804
2805 /* Set vty access class. */
2806 DEFUN (vty_access_class,
2807 vty_access_class_cmd,
2808 "access-class WORD",
2809 "Filter connections based on an IP access list\n"
2810 "IP access list\n")
2811 {
2812 int idx_word = 1;
2813 if (vty_accesslist_name)
2814 XFREE(MTYPE_VTY, vty_accesslist_name);
2815
2816 vty_accesslist_name = XSTRDUP(MTYPE_VTY, argv[idx_word]->arg);
2817
2818 return CMD_SUCCESS;
2819 }
2820
2821 /* Clear vty access class. */
2822 DEFUN (no_vty_access_class,
2823 no_vty_access_class_cmd,
2824 "no access-class [WORD]",
2825 NO_STR
2826 "Filter connections based on an IP access list\n"
2827 "IP access list\n")
2828 {
2829 int idx_word = 2;
2830 const char *accesslist = (argc == 3) ? argv[idx_word]->arg : NULL;
2831 if (!vty_accesslist_name
2832 || (argc == 3 && strcmp(vty_accesslist_name, accesslist))) {
2833 vty_out(vty, "Access-class is not currently applied to vty\n");
2834 return CMD_WARNING_CONFIG_FAILED;
2835 }
2836
2837 XFREE(MTYPE_VTY, vty_accesslist_name);
2838
2839 vty_accesslist_name = NULL;
2840
2841 return CMD_SUCCESS;
2842 }
2843
2844 /* Set vty access class. */
2845 DEFUN (vty_ipv6_access_class,
2846 vty_ipv6_access_class_cmd,
2847 "ipv6 access-class WORD",
2848 IPV6_STR
2849 "Filter connections based on an IP access list\n"
2850 "IPv6 access list\n")
2851 {
2852 int idx_word = 2;
2853 if (vty_ipv6_accesslist_name)
2854 XFREE(MTYPE_VTY, vty_ipv6_accesslist_name);
2855
2856 vty_ipv6_accesslist_name = XSTRDUP(MTYPE_VTY, argv[idx_word]->arg);
2857
2858 return CMD_SUCCESS;
2859 }
2860
2861 /* Clear vty access class. */
2862 DEFUN (no_vty_ipv6_access_class,
2863 no_vty_ipv6_access_class_cmd,
2864 "no ipv6 access-class [WORD]",
2865 NO_STR
2866 IPV6_STR
2867 "Filter connections based on an IP access list\n"
2868 "IPv6 access list\n")
2869 {
2870 int idx_word = 3;
2871 const char *accesslist = (argc == 4) ? argv[idx_word]->arg : NULL;
2872
2873 if (!vty_ipv6_accesslist_name
2874 || (argc == 4 && strcmp(vty_ipv6_accesslist_name, accesslist))) {
2875 vty_out(vty,
2876 "IPv6 access-class is not currently applied to vty\n");
2877 return CMD_WARNING_CONFIG_FAILED;
2878 }
2879
2880 XFREE(MTYPE_VTY, vty_ipv6_accesslist_name);
2881
2882 vty_ipv6_accesslist_name = NULL;
2883
2884 return CMD_SUCCESS;
2885 }
2886
2887 /* vty login. */
2888 DEFUN (vty_login,
2889 vty_login_cmd,
2890 "login",
2891 "Enable password checking\n")
2892 {
2893 no_password_check = 0;
2894 return CMD_SUCCESS;
2895 }
2896
2897 DEFUN (no_vty_login,
2898 no_vty_login_cmd,
2899 "no login",
2900 NO_STR
2901 "Enable password checking\n")
2902 {
2903 no_password_check = 1;
2904 return CMD_SUCCESS;
2905 }
2906
2907 DEFUN (service_advanced_vty,
2908 service_advanced_vty_cmd,
2909 "service advanced-vty",
2910 "Set up miscellaneous service\n"
2911 "Enable advanced mode vty interface\n")
2912 {
2913 host.advanced = 1;
2914 return CMD_SUCCESS;
2915 }
2916
2917 DEFUN (no_service_advanced_vty,
2918 no_service_advanced_vty_cmd,
2919 "no service advanced-vty",
2920 NO_STR
2921 "Set up miscellaneous service\n"
2922 "Enable advanced mode vty interface\n")
2923 {
2924 host.advanced = 0;
2925 return CMD_SUCCESS;
2926 }
2927
2928 DEFUN_NOSH (terminal_monitor,
2929 terminal_monitor_cmd,
2930 "terminal monitor",
2931 "Set terminal line parameters\n"
2932 "Copy debug output to the current terminal line\n")
2933 {
2934 vty->monitor = 1;
2935 return CMD_SUCCESS;
2936 }
2937
2938 DEFUN_NOSH (terminal_no_monitor,
2939 terminal_no_monitor_cmd,
2940 "terminal no monitor",
2941 "Set terminal line parameters\n"
2942 NO_STR
2943 "Copy debug output to the current terminal line\n")
2944 {
2945 vty->monitor = 0;
2946 return CMD_SUCCESS;
2947 }
2948
2949 DEFUN_NOSH (no_terminal_monitor,
2950 no_terminal_monitor_cmd,
2951 "no terminal monitor",
2952 NO_STR
2953 "Set terminal line parameters\n"
2954 "Copy debug output to the current terminal line\n")
2955 {
2956 return terminal_no_monitor(self, vty, argc, argv);
2957 }
2958
2959
2960 DEFUN_NOSH (show_history,
2961 show_history_cmd,
2962 "show history",
2963 SHOW_STR
2964 "Display the session command history\n")
2965 {
2966 int index;
2967
2968 for (index = vty->hindex + 1; index != vty->hindex;) {
2969 if (index == VTY_MAXHIST) {
2970 index = 0;
2971 continue;
2972 }
2973
2974 if (vty->hist[index] != NULL)
2975 vty_out(vty, " %s\n", vty->hist[index]);
2976
2977 index++;
2978 }
2979
2980 return CMD_SUCCESS;
2981 }
2982
2983 /* vty login. */
2984 DEFUN (log_commands,
2985 log_commands_cmd,
2986 "log commands",
2987 "Logging control\n"
2988 "Log all commands (can't be unset without restart)\n")
2989 {
2990 do_log_commands = 1;
2991 return CMD_SUCCESS;
2992 }
2993
2994 /* Display current configuration. */
2995 static int vty_config_write(struct vty *vty)
2996 {
2997 vty_out(vty, "line vty\n");
2998
2999 if (vty_accesslist_name)
3000 vty_out(vty, " access-class %s\n", vty_accesslist_name);
3001
3002 if (vty_ipv6_accesslist_name)
3003 vty_out(vty, " ipv6 access-class %s\n",
3004 vty_ipv6_accesslist_name);
3005
3006 /* exec-timeout */
3007 if (vty_timeout_val != VTY_TIMEOUT_DEFAULT)
3008 vty_out(vty, " exec-timeout %ld %ld\n", vty_timeout_val / 60,
3009 vty_timeout_val % 60);
3010
3011 /* login */
3012 if (no_password_check)
3013 vty_out(vty, " no login\n");
3014
3015 if (do_log_commands)
3016 vty_out(vty, "log commands\n");
3017
3018 vty_out(vty, "!\n");
3019
3020 return CMD_SUCCESS;
3021 }
3022
3023 struct cmd_node vty_node = {
3024 VTY_NODE, "%s(config-line)# ", 1,
3025 };
3026
3027 /* Reset all VTY status. */
3028 void vty_reset()
3029 {
3030 unsigned int i;
3031 struct vty *vty;
3032 struct thread *vty_serv_thread;
3033
3034 for (i = 0; i < vector_active(vtyvec); i++)
3035 if ((vty = vector_slot(vtyvec, i)) != NULL) {
3036 buffer_reset(vty->lbuf);
3037 buffer_reset(vty->obuf);
3038 vty->status = VTY_CLOSE;
3039 vty_close(vty);
3040 }
3041
3042 for (i = 0; i < vector_active(Vvty_serv_thread); i++)
3043 if ((vty_serv_thread = vector_slot(Vvty_serv_thread, i))
3044 != NULL) {
3045 thread_cancel(vty_serv_thread);
3046 vector_slot(Vvty_serv_thread, i) = NULL;
3047 close(i);
3048 }
3049
3050 vty_timeout_val = VTY_TIMEOUT_DEFAULT;
3051
3052 if (vty_accesslist_name) {
3053 XFREE(MTYPE_VTY, vty_accesslist_name);
3054 vty_accesslist_name = NULL;
3055 }
3056
3057 if (vty_ipv6_accesslist_name) {
3058 XFREE(MTYPE_VTY, vty_ipv6_accesslist_name);
3059 vty_ipv6_accesslist_name = NULL;
3060 }
3061 }
3062
3063 static void vty_save_cwd(void)
3064 {
3065 char cwd[MAXPATHLEN];
3066 char *c;
3067
3068 c = getcwd(cwd, MAXPATHLEN);
3069
3070 if (!c) {
3071 /*
3072 * At this point if these go wrong, more than likely
3073 * the whole world is coming down around us
3074 * Hence not worrying about it too much.
3075 */
3076 if (!chdir(SYSCONFDIR)) {
3077 flog_err(LIB_ERR_SYSTEM_CALL,
3078 "Failure to chdir to %s, errno: %d",
3079 SYSCONFDIR, errno);
3080 exit(-1);
3081 }
3082 if (getcwd(cwd, MAXPATHLEN) == NULL) {
3083 flog_err(LIB_ERR_SYSTEM_CALL,
3084 "Failure to getcwd, errno: %d", errno);
3085 exit(-1);
3086 }
3087 }
3088
3089 vty_cwd = XMALLOC(MTYPE_TMP, strlen(cwd) + 1);
3090 strcpy(vty_cwd, cwd);
3091 }
3092
3093 char *vty_get_cwd()
3094 {
3095 return vty_cwd;
3096 }
3097
3098 int vty_shell(struct vty *vty)
3099 {
3100 return vty->type == VTY_SHELL ? 1 : 0;
3101 }
3102
3103 int vty_shell_serv(struct vty *vty)
3104 {
3105 return vty->type == VTY_SHELL_SERV ? 1 : 0;
3106 }
3107
3108 void vty_init_vtysh()
3109 {
3110 vtyvec = vector_init(VECTOR_MIN_SIZE);
3111 }
3112
3113 /* Install vty's own commands like `who' command. */
3114 void vty_init(struct thread_master *master_thread)
3115 {
3116 /* For further configuration read, preserve current directory. */
3117 vty_save_cwd();
3118
3119 vtyvec = vector_init(VECTOR_MIN_SIZE);
3120
3121 vty_master = master_thread;
3122
3123 atexit(vty_stdio_atexit);
3124
3125 /* Initilize server thread vector. */
3126 Vvty_serv_thread = vector_init(VECTOR_MIN_SIZE);
3127
3128 /* Install bgp top node. */
3129 install_node(&vty_node, vty_config_write);
3130
3131 install_element(VIEW_NODE, &config_who_cmd);
3132 install_element(VIEW_NODE, &show_history_cmd);
3133 install_element(CONFIG_NODE, &line_vty_cmd);
3134 install_element(CONFIG_NODE, &service_advanced_vty_cmd);
3135 install_element(CONFIG_NODE, &no_service_advanced_vty_cmd);
3136 install_element(CONFIG_NODE, &show_history_cmd);
3137 install_element(CONFIG_NODE, &log_commands_cmd);
3138 install_element(ENABLE_NODE, &terminal_monitor_cmd);
3139 install_element(ENABLE_NODE, &terminal_no_monitor_cmd);
3140 install_element(ENABLE_NODE, &no_terminal_monitor_cmd);
3141
3142 install_default(VTY_NODE);
3143 install_element(VTY_NODE, &exec_timeout_min_cmd);
3144 install_element(VTY_NODE, &exec_timeout_sec_cmd);
3145 install_element(VTY_NODE, &no_exec_timeout_cmd);
3146 install_element(VTY_NODE, &vty_access_class_cmd);
3147 install_element(VTY_NODE, &no_vty_access_class_cmd);
3148 install_element(VTY_NODE, &vty_login_cmd);
3149 install_element(VTY_NODE, &no_vty_login_cmd);
3150 install_element(VTY_NODE, &vty_ipv6_access_class_cmd);
3151 install_element(VTY_NODE, &no_vty_ipv6_access_class_cmd);
3152 }
3153
3154 void vty_terminate(void)
3155 {
3156 if (vty_cwd)
3157 XFREE(MTYPE_TMP, vty_cwd);
3158
3159 if (vtyvec && Vvty_serv_thread) {
3160 vty_reset();
3161 vector_free(vtyvec);
3162 vector_free(Vvty_serv_thread);
3163 vtyvec = NULL;
3164 Vvty_serv_thread = NULL;
3165 }
3166 }