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