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