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