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