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