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