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