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