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