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