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