]> git.proxmox.com Git - mirror_frr.git/blob - lib/vty.c
lib: ZeroMQ read handler, v2
[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 bool stdio_termios = false;
1667 static void (*stdio_vty_atclose)(int isexit);
1668
1669 static void vty_stdio_reset(int isexit)
1670 {
1671 if (stdio_vty) {
1672 if (stdio_termios)
1673 tcsetattr(0, TCSANOW, &stdio_orig_termios);
1674 stdio_termios = false;
1675
1676 stdio_vty = NULL;
1677
1678 if (stdio_vty_atclose)
1679 stdio_vty_atclose(isexit);
1680 stdio_vty_atclose = NULL;
1681 }
1682 }
1683
1684 static void vty_stdio_atexit(void)
1685 {
1686 vty_stdio_reset(1);
1687 }
1688
1689 void vty_stdio_suspend(void)
1690 {
1691 if (!stdio_vty)
1692 return;
1693
1694 if (stdio_vty->t_write)
1695 thread_cancel(stdio_vty->t_write);
1696 if (stdio_vty->t_read)
1697 thread_cancel(stdio_vty->t_read);
1698 if (stdio_vty->t_timeout)
1699 thread_cancel(stdio_vty->t_timeout);
1700
1701 if (stdio_termios)
1702 tcsetattr(0, TCSANOW, &stdio_orig_termios);
1703 stdio_termios = false;
1704 }
1705
1706 void vty_stdio_resume(void)
1707 {
1708 if (!stdio_vty)
1709 return;
1710
1711 if (!tcgetattr(0, &stdio_orig_termios)) {
1712 struct termios termios;
1713
1714 termios = stdio_orig_termios;
1715 termios.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR
1716 | IGNCR | ICRNL | IXON);
1717 termios.c_oflag &= ~OPOST;
1718 termios.c_lflag &= ~(ECHO | ECHONL | ICANON | IEXTEN);
1719 termios.c_cflag &= ~(CSIZE | PARENB);
1720 termios.c_cflag |= CS8;
1721 tcsetattr(0, TCSANOW, &termios);
1722 stdio_termios = true;
1723 }
1724
1725 vty_prompt(stdio_vty);
1726
1727 /* Add read/write thread. */
1728 vty_event(VTY_WRITE, 1, stdio_vty);
1729 vty_event(VTY_READ, 0, stdio_vty);
1730 }
1731
1732 void vty_stdio_close(void)
1733 {
1734 if (!stdio_vty)
1735 return;
1736 vty_close(stdio_vty);
1737 }
1738
1739 struct vty *vty_stdio(void (*atclose)(int isexit))
1740 {
1741 struct vty *vty;
1742
1743 /* refuse creating two vtys on stdio */
1744 if (stdio_vty)
1745 return NULL;
1746
1747 vty = stdio_vty = vty_new_init(0);
1748 stdio_vty_atclose = atclose;
1749 vty->wfd = 1;
1750
1751 /* always have stdio vty in a known _unchangeable_ state, don't want
1752 * config
1753 * to have any effect here to make sure scripting this works as intended
1754 */
1755 vty->node = ENABLE_NODE;
1756 vty->v_timeout = 0;
1757 strcpy(vty->address, "console");
1758
1759 vty_stdio_resume();
1760 return vty;
1761 }
1762
1763 /* Accept connection from the network. */
1764 static int vty_accept(struct thread *thread)
1765 {
1766 int vty_sock;
1767 union sockunion su;
1768 int ret;
1769 unsigned int on;
1770 int accept_sock;
1771 struct prefix p;
1772 struct access_list *acl = NULL;
1773 char buf[SU_ADDRSTRLEN];
1774
1775 accept_sock = THREAD_FD(thread);
1776
1777 /* We continue hearing vty socket. */
1778 vty_event(VTY_SERV, accept_sock, NULL);
1779
1780 memset(&su, 0, sizeof(union sockunion));
1781
1782 /* We can handle IPv4 or IPv6 socket. */
1783 vty_sock = sockunion_accept(accept_sock, &su);
1784 if (vty_sock < 0) {
1785 zlog_warn("can't accept vty socket : %s", safe_strerror(errno));
1786 return -1;
1787 }
1788 set_nonblocking(vty_sock);
1789 set_cloexec(vty_sock);
1790
1791 sockunion2hostprefix(&su, &p);
1792
1793 /* VTY's accesslist apply. */
1794 if (p.family == AF_INET && vty_accesslist_name) {
1795 if ((acl = access_list_lookup(AFI_IP, vty_accesslist_name))
1796 && (access_list_apply(acl, &p) == FILTER_DENY)) {
1797 zlog_info("Vty connection refused from %s",
1798 sockunion2str(&su, buf, SU_ADDRSTRLEN));
1799 close(vty_sock);
1800
1801 /* continue accepting connections */
1802 vty_event(VTY_SERV, accept_sock, NULL);
1803
1804 return 0;
1805 }
1806 }
1807
1808 /* VTY's ipv6 accesslist apply. */
1809 if (p.family == AF_INET6 && vty_ipv6_accesslist_name) {
1810 if ((acl = access_list_lookup(AFI_IP6,
1811 vty_ipv6_accesslist_name))
1812 && (access_list_apply(acl, &p) == FILTER_DENY)) {
1813 zlog_info("Vty connection refused from %s",
1814 sockunion2str(&su, buf, SU_ADDRSTRLEN));
1815 close(vty_sock);
1816
1817 /* continue accepting connections */
1818 vty_event(VTY_SERV, accept_sock, NULL);
1819
1820 return 0;
1821 }
1822 }
1823
1824 on = 1;
1825 ret = setsockopt(vty_sock, IPPROTO_TCP, TCP_NODELAY, (char *)&on,
1826 sizeof(on));
1827 if (ret < 0)
1828 zlog_info("can't set sockopt to vty_sock : %s",
1829 safe_strerror(errno));
1830
1831 zlog_info("Vty connection from %s",
1832 sockunion2str(&su, buf, SU_ADDRSTRLEN));
1833
1834 vty_create(vty_sock, &su);
1835
1836 return 0;
1837 }
1838
1839 static void vty_serv_sock_addrinfo(const char *hostname, unsigned short port)
1840 {
1841 int ret;
1842 struct addrinfo req;
1843 struct addrinfo *ainfo;
1844 struct addrinfo *ainfo_save;
1845 int sock;
1846 char port_str[BUFSIZ];
1847
1848 memset(&req, 0, sizeof(struct addrinfo));
1849 req.ai_flags = AI_PASSIVE;
1850 req.ai_family = AF_UNSPEC;
1851 req.ai_socktype = SOCK_STREAM;
1852 sprintf(port_str, "%d", port);
1853 port_str[sizeof(port_str) - 1] = '\0';
1854
1855 ret = getaddrinfo(hostname, port_str, &req, &ainfo);
1856
1857 if (ret != 0) {
1858 zlog_err("getaddrinfo failed: %s", gai_strerror(ret));
1859 exit(1);
1860 }
1861
1862 ainfo_save = ainfo;
1863
1864 do {
1865 if (ainfo->ai_family != AF_INET && ainfo->ai_family != AF_INET6)
1866 continue;
1867
1868 sock = socket(ainfo->ai_family, ainfo->ai_socktype,
1869 ainfo->ai_protocol);
1870 if (sock < 0)
1871 continue;
1872
1873 sockopt_v6only(ainfo->ai_family, sock);
1874 sockopt_reuseaddr(sock);
1875 sockopt_reuseport(sock);
1876 set_cloexec(sock);
1877
1878 ret = bind(sock, ainfo->ai_addr, ainfo->ai_addrlen);
1879 if (ret < 0) {
1880 close(sock); /* Avoid sd leak. */
1881 continue;
1882 }
1883
1884 ret = listen(sock, 3);
1885 if (ret < 0) {
1886 close(sock); /* Avoid sd leak. */
1887 continue;
1888 }
1889
1890 vty_event(VTY_SERV, sock, NULL);
1891 } while ((ainfo = ainfo->ai_next) != NULL);
1892
1893 freeaddrinfo(ainfo_save);
1894 }
1895
1896 #ifdef VTYSH
1897 /* For sockaddr_un. */
1898 #include <sys/un.h>
1899
1900 /* VTY shell UNIX domain socket. */
1901 static void vty_serv_un(const char *path)
1902 {
1903 int ret;
1904 int sock, len;
1905 struct sockaddr_un serv;
1906 mode_t old_mask;
1907 struct zprivs_ids_t ids;
1908
1909 /* First of all, unlink existing socket */
1910 unlink(path);
1911
1912 /* Set umask */
1913 old_mask = umask(0007);
1914
1915 /* Make UNIX domain socket. */
1916 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1917 if (sock < 0) {
1918 zlog_err("Cannot create unix stream socket: %s",
1919 safe_strerror(errno));
1920 return;
1921 }
1922
1923 /* Make server socket. */
1924 memset(&serv, 0, sizeof(struct sockaddr_un));
1925 serv.sun_family = AF_UNIX;
1926 strlcpy(serv.sun_path, path, sizeof(serv.sun_path));
1927 #ifdef HAVE_STRUCT_SOCKADDR_UN_SUN_LEN
1928 len = serv.sun_len = SUN_LEN(&serv);
1929 #else
1930 len = sizeof(serv.sun_family) + strlen(serv.sun_path);
1931 #endif /* HAVE_STRUCT_SOCKADDR_UN_SUN_LEN */
1932
1933 set_cloexec(sock);
1934
1935 ret = bind(sock, (struct sockaddr *)&serv, len);
1936 if (ret < 0) {
1937 zlog_err("Cannot bind path %s: %s", path, safe_strerror(errno));
1938 close(sock); /* Avoid sd leak. */
1939 return;
1940 }
1941
1942 ret = listen(sock, 5);
1943 if (ret < 0) {
1944 zlog_err("listen(fd %d) failed: %s", sock,
1945 safe_strerror(errno));
1946 close(sock); /* Avoid sd leak. */
1947 return;
1948 }
1949
1950 umask(old_mask);
1951
1952 zprivs_get_ids(&ids);
1953
1954 /* Hack: ids.gid_vty is actually a uint, but we stored -1 in it
1955 earlier for the case when we don't need to chown the file
1956 type casting it here to make a compare */
1957 if ((int)ids.gid_vty > 0) {
1958 /* set group of socket */
1959 if (chown(path, -1, ids.gid_vty)) {
1960 zlog_err("vty_serv_un: could chown socket, %s",
1961 safe_strerror(errno));
1962 }
1963 }
1964
1965 vty_event(VTYSH_SERV, sock, NULL);
1966 }
1967
1968 /* #define VTYSH_DEBUG 1 */
1969
1970 static int vtysh_accept(struct thread *thread)
1971 {
1972 int accept_sock;
1973 int sock;
1974 int client_len;
1975 struct sockaddr_un client;
1976 struct vty *vty;
1977
1978 accept_sock = THREAD_FD(thread);
1979
1980 vty_event(VTYSH_SERV, accept_sock, NULL);
1981
1982 memset(&client, 0, sizeof(struct sockaddr_un));
1983 client_len = sizeof(struct sockaddr_un);
1984
1985 sock = accept(accept_sock, (struct sockaddr *)&client,
1986 (socklen_t *)&client_len);
1987
1988 if (sock < 0) {
1989 zlog_warn("can't accept vty socket : %s", safe_strerror(errno));
1990 return -1;
1991 }
1992
1993 if (set_nonblocking(sock) < 0) {
1994 zlog_warn(
1995 "vtysh_accept: could not set vty socket %d to non-blocking,"
1996 " %s, closing",
1997 sock, safe_strerror(errno));
1998 close(sock);
1999 return -1;
2000 }
2001 set_cloexec(sock);
2002
2003 #ifdef VTYSH_DEBUG
2004 printf("VTY shell accept\n");
2005 #endif /* VTYSH_DEBUG */
2006
2007 vty = vty_new();
2008 vty->fd = sock;
2009 vty->wfd = sock;
2010 vty->type = VTY_SHELL_SERV;
2011 vty->node = VIEW_NODE;
2012
2013 vty_event(VTYSH_READ, sock, vty);
2014
2015 return 0;
2016 }
2017
2018 static int vtysh_flush(struct vty *vty)
2019 {
2020 switch (buffer_flush_available(vty->obuf, vty->wfd)) {
2021 case BUFFER_PENDING:
2022 vty_event(VTYSH_WRITE, vty->wfd, vty);
2023 break;
2024 case BUFFER_ERROR:
2025 vty->monitor =
2026 0; /* disable monitoring to avoid infinite recursion */
2027 zlog_warn("%s: write error to fd %d, closing", __func__,
2028 vty->fd);
2029 buffer_reset(vty->obuf);
2030 vty_close(vty);
2031 return -1;
2032 break;
2033 case BUFFER_EMPTY:
2034 break;
2035 }
2036 return 0;
2037 }
2038
2039 static int vtysh_read(struct thread *thread)
2040 {
2041 int ret;
2042 int sock;
2043 int nbytes;
2044 struct vty *vty;
2045 unsigned char buf[VTY_READ_BUFSIZ];
2046 unsigned char *p;
2047 u_char header[4] = {0, 0, 0, 0};
2048
2049 sock = THREAD_FD(thread);
2050 vty = THREAD_ARG(thread);
2051 vty->t_read = NULL;
2052
2053 if ((nbytes = read(sock, buf, VTY_READ_BUFSIZ)) <= 0) {
2054 if (nbytes < 0) {
2055 if (ERRNO_IO_RETRY(errno)) {
2056 vty_event(VTYSH_READ, sock, vty);
2057 return 0;
2058 }
2059 vty->monitor = 0; /* disable monitoring to avoid
2060 infinite recursion */
2061 zlog_warn(
2062 "%s: read failed on vtysh client fd %d, closing: %s",
2063 __func__, sock, safe_strerror(errno));
2064 }
2065 buffer_reset(vty->obuf);
2066 vty_close(vty);
2067 #ifdef VTYSH_DEBUG
2068 printf("close vtysh\n");
2069 #endif /* VTYSH_DEBUG */
2070 return 0;
2071 }
2072
2073 #ifdef VTYSH_DEBUG
2074 printf("line: %.*s\n", nbytes, buf);
2075 #endif /* VTYSH_DEBUG */
2076
2077 if (vty->length + nbytes >= VTY_BUFSIZ) {
2078 /* Clear command line buffer. */
2079 vty->cp = vty->length = 0;
2080 vty_clear_buf(vty);
2081 vty_out(vty, "%% Command is too long.\n");
2082 } else {
2083 for (p = buf; p < buf + nbytes; p++) {
2084 vty->buf[vty->length++] = *p;
2085 if (*p == '\0') {
2086 /* Pass this line to parser. */
2087 ret = vty_execute(vty);
2088 /* Note that vty_execute clears the command buffer and resets
2089 vty->length to 0. */
2090
2091 /* Return result. */
2092 #ifdef VTYSH_DEBUG
2093 printf("result: %d\n", ret);
2094 printf("vtysh node: %d\n", vty->node);
2095 #endif /* VTYSH_DEBUG */
2096
2097 /* hack for asynchronous "write integrated"
2098 * - other commands in "buf" will be ditched
2099 * - input during pending config-write is
2100 * "unsupported" */
2101 if (ret == CMD_SUSPEND)
2102 break;
2103
2104 /* warning: watchfrr hardcodes this result write
2105 */
2106 header[3] = ret;
2107 buffer_put(vty->obuf, header, 4);
2108
2109 if (!vty->t_write && (vtysh_flush(vty) < 0))
2110 /* Try to flush results; exit if a write
2111 * error occurs. */
2112 return 0;
2113 }
2114 }
2115 }
2116
2117 if (vty->status == VTY_CLOSE)
2118 vty_close(vty);
2119 else
2120 vty_event(VTYSH_READ, sock, vty);
2121
2122 return 0;
2123 }
2124
2125 static int vtysh_write(struct thread *thread)
2126 {
2127 struct vty *vty = THREAD_ARG(thread);
2128
2129 vty->t_write = NULL;
2130 vtysh_flush(vty);
2131 return 0;
2132 }
2133
2134 #endif /* VTYSH */
2135
2136 /* Determine address family to bind. */
2137 void vty_serv_sock(const char *addr, unsigned short port, const char *path)
2138 {
2139 /* If port is set to 0, do not listen on TCP/IP at all! */
2140 if (port)
2141 vty_serv_sock_addrinfo(addr, port);
2142
2143 #ifdef VTYSH
2144 vty_serv_un(path);
2145 #endif /* VTYSH */
2146 }
2147
2148 /* Close vty interface. Warning: call this only from functions that
2149 will be careful not to access the vty afterwards (since it has
2150 now been freed). This is safest from top-level functions (called
2151 directly by the thread dispatcher). */
2152 void vty_close(struct vty *vty)
2153 {
2154 int i;
2155 bool was_stdio = false;
2156
2157 /* Cancel threads.*/
2158 if (vty->t_read)
2159 thread_cancel(vty->t_read);
2160 if (vty->t_write)
2161 thread_cancel(vty->t_write);
2162 if (vty->t_timeout)
2163 thread_cancel(vty->t_timeout);
2164
2165 /* Flush buffer. */
2166 buffer_flush_all(vty->obuf, vty->wfd);
2167
2168 /* Free input buffer. */
2169 buffer_free(vty->obuf);
2170
2171 /* Free command history. */
2172 for (i = 0; i < VTY_MAXHIST; i++)
2173 if (vty->hist[i])
2174 XFREE(MTYPE_VTY_HIST, vty->hist[i]);
2175
2176 /* Unset vector. */
2177 if (vty->fd != -1)
2178 vector_unset(vtyvec, vty->fd);
2179
2180 if (vty->wfd > 0 && vty->type == VTY_FILE)
2181 fsync(vty->wfd);
2182
2183 /* Close socket.
2184 * note check is for fd > STDERR_FILENO, not fd != -1.
2185 * We never close stdin/stdout/stderr here, because we may be
2186 * running in foreground mode with logging to stdout. Also,
2187 * additionally, we'd need to replace these fds with /dev/null. */
2188 if (vty->wfd > STDERR_FILENO && vty->wfd != vty->fd)
2189 close(vty->wfd);
2190 if (vty->fd > STDERR_FILENO) {
2191 close(vty->fd);
2192 } else
2193 was_stdio = true;
2194
2195 if (vty->buf)
2196 XFREE(MTYPE_VTY, vty->buf);
2197
2198 if (vty->error_buf)
2199 XFREE(MTYPE_VTY, vty->error_buf);
2200
2201 /* Check configure. */
2202 vty_config_unlock(vty);
2203
2204 /* OK free vty. */
2205 XFREE(MTYPE_VTY, vty);
2206
2207 if (was_stdio)
2208 vty_stdio_reset(0);
2209 }
2210
2211 /* When time out occur output message then close connection. */
2212 static int vty_timeout(struct thread *thread)
2213 {
2214 struct vty *vty;
2215
2216 vty = THREAD_ARG(thread);
2217 vty->t_timeout = NULL;
2218 vty->v_timeout = 0;
2219
2220 /* Clear buffer*/
2221 buffer_reset(vty->obuf);
2222 vty_out(vty, "\nVty connection is timed out.\n");
2223
2224 /* Close connection. */
2225 vty->status = VTY_CLOSE;
2226 vty_close(vty);
2227
2228 return 0;
2229 }
2230
2231 /* Read up configuration file from file_name. */
2232 static void vty_read_file(FILE *confp)
2233 {
2234 int ret;
2235 struct vty *vty;
2236 unsigned int line_num = 0;
2237
2238 vty = vty_new();
2239 /* vty_close won't close stderr; if some config command prints
2240 * something it'll end up there. (not ideal; it'd be beter if output
2241 * from a file-load went to logging instead. Also note that if this
2242 * function is called after daemonizing, stderr will be /dev/null.)
2243 *
2244 * vty->fd will be -1 from vty_new()
2245 */
2246 vty->wfd = STDERR_FILENO;
2247 vty->type = VTY_FILE;
2248 vty->node = CONFIG_NODE;
2249
2250 /* Execute configuration file */
2251 ret = config_from_file(vty, confp, &line_num);
2252
2253 /* Flush any previous errors before printing messages below */
2254 buffer_flush_all(vty->obuf, vty->wfd);
2255
2256 if (!((ret == CMD_SUCCESS) || (ret == CMD_ERR_NOTHING_TODO))) {
2257 const char *message = NULL;
2258 char *nl;
2259
2260 switch (ret) {
2261 case CMD_ERR_AMBIGUOUS:
2262 message = "Ambiguous command";
2263 break;
2264 case CMD_ERR_NO_MATCH:
2265 message = "No such command";
2266 break;
2267 }
2268
2269 nl = strchr(vty->error_buf, '\n');
2270 if (nl)
2271 *nl = '\0';
2272 zlog_err("ERROR: %s on config line %u: %s",
2273 message, line_num, vty->error_buf);
2274 }
2275
2276 vty_close(vty);
2277 }
2278
2279 static FILE *vty_use_backup_config(const char *fullpath)
2280 {
2281 char *fullpath_sav, *fullpath_tmp;
2282 FILE *ret = NULL;
2283 int tmp, sav;
2284 int c;
2285 char buffer[512];
2286
2287 fullpath_sav = malloc(strlen(fullpath) + strlen(CONF_BACKUP_EXT) + 1);
2288 strcpy(fullpath_sav, fullpath);
2289 strcat(fullpath_sav, CONF_BACKUP_EXT);
2290
2291 sav = open(fullpath_sav, O_RDONLY);
2292 if (sav < 0) {
2293 free(fullpath_sav);
2294 return NULL;
2295 }
2296
2297 fullpath_tmp = malloc(strlen(fullpath) + 8);
2298 sprintf(fullpath_tmp, "%s.XXXXXX", fullpath);
2299
2300 /* Open file to configuration write. */
2301 tmp = mkstemp(fullpath_tmp);
2302 if (tmp < 0)
2303 goto out_close_sav;
2304
2305 if (fchmod(tmp, CONFIGFILE_MASK) != 0)
2306 goto out_close;
2307
2308 while ((c = read(sav, buffer, 512)) > 0) {
2309 if (write(tmp, buffer, c) <= 0)
2310 goto out_close;
2311 }
2312 close(sav);
2313 close(tmp);
2314
2315 if (rename(fullpath_tmp, fullpath) == 0)
2316 ret = fopen(fullpath, "r");
2317 else
2318 unlink(fullpath_tmp);
2319
2320 if (0) {
2321 out_close:
2322 close(tmp);
2323 unlink(fullpath_tmp);
2324 out_close_sav:
2325 close(sav);
2326 }
2327
2328 free(fullpath_sav);
2329 free(fullpath_tmp);
2330 return ret;
2331 }
2332
2333 /* Read up configuration file from file_name. */
2334 void vty_read_config(const char *config_file, char *config_default_dir)
2335 {
2336 char cwd[MAXPATHLEN];
2337 FILE *confp = NULL;
2338 const char *fullpath;
2339 char *tmp = NULL;
2340
2341 /* If -f flag specified. */
2342 if (config_file != NULL) {
2343 if (!IS_DIRECTORY_SEP(config_file[0])) {
2344 if (getcwd(cwd, MAXPATHLEN) == NULL) {
2345 zlog_err("Failure to determine Current Working Directory %d!",
2346 errno);
2347 exit(1);
2348 }
2349 tmp = XMALLOC(MTYPE_TMP,
2350 strlen(cwd) + strlen(config_file) + 2);
2351 sprintf(tmp, "%s/%s", cwd, config_file);
2352 fullpath = tmp;
2353 } else
2354 fullpath = config_file;
2355
2356 confp = fopen(fullpath, "r");
2357
2358 if (confp == NULL) {
2359 zlog_err("%s: failed to open configuration file %s: %s",
2360 __func__, fullpath, safe_strerror(errno));
2361
2362 confp = vty_use_backup_config(fullpath);
2363 if (confp)
2364 zlog_warn("WARNING: using backup configuration file!");
2365 else {
2366 zlog_err("can't open configuration file [%s]",
2367 config_file);
2368 exit(1);
2369 }
2370 }
2371 } else {
2372
2373 host_config_set(config_default_dir);
2374
2375 #ifdef VTYSH
2376 int ret;
2377 struct stat conf_stat;
2378
2379 /* !!!!PLEASE LEAVE!!!!
2380 * This is NEEDED for use with vtysh -b, or else you can get
2381 * a real configuration food fight with a lot garbage in the
2382 * merged configuration file it creates coming from the per
2383 * daemon configuration files. This also allows the daemons
2384 * to start if there default configuration file is not
2385 * present or ignore them, as needed when using vtysh -b to
2386 * configure the daemons at boot - MAG
2387 */
2388
2389 /* Stat for vtysh Zebra.conf, if found startup and wait for
2390 * boot configuration
2391 */
2392
2393 if (strstr(config_default_dir, "vtysh") == NULL) {
2394 ret = stat(integrate_default, &conf_stat);
2395 if (ret >= 0)
2396 goto tmp_free_and_out;
2397 }
2398 #endif /* VTYSH */
2399 confp = fopen(config_default_dir, "r");
2400 if (confp == NULL) {
2401 zlog_err("%s: failed to open configuration file %s: %s",
2402 __func__, config_default_dir,
2403 safe_strerror(errno));
2404
2405 confp = vty_use_backup_config(config_default_dir);
2406 if (confp) {
2407 zlog_warn("WARNING: using backup configuration file!");
2408 fullpath = config_default_dir;
2409 } else {
2410 zlog_err("can't open configuration file [%s]",
2411 config_default_dir);
2412 goto tmp_free_and_out;
2413 }
2414 } else
2415 fullpath = config_default_dir;
2416 }
2417
2418 vty_read_file(confp);
2419
2420 fclose(confp);
2421
2422 host_config_set(fullpath);
2423
2424 tmp_free_and_out:
2425 if (tmp)
2426 XFREE(MTYPE_TMP, tmp);
2427 }
2428
2429 /* Small utility function which output log to the VTY. */
2430 void vty_log(const char *level, const char *proto_str, const char *format,
2431 struct timestamp_control *ctl, va_list va)
2432 {
2433 unsigned int i;
2434 struct vty *vty;
2435
2436 if (!vtyvec)
2437 return;
2438
2439 for (i = 0; i < vector_active(vtyvec); i++)
2440 if ((vty = vector_slot(vtyvec, i)) != NULL)
2441 if (vty->monitor) {
2442 va_list ac;
2443 va_copy(ac, va);
2444 vty_log_out(vty, level, proto_str, format, ctl,
2445 ac);
2446 va_end(ac);
2447 }
2448 }
2449
2450 /* Async-signal-safe version of vty_log for fixed strings. */
2451 void vty_log_fixed(char *buf, size_t len)
2452 {
2453 unsigned int i;
2454 struct iovec iov[2];
2455 char crlf[4] = "\r\n";
2456
2457 /* vty may not have been initialised */
2458 if (!vtyvec)
2459 return;
2460
2461 iov[0].iov_base = buf;
2462 iov[0].iov_len = len;
2463 iov[1].iov_base = crlf;
2464 iov[1].iov_len = 2;
2465
2466 for (i = 0; i < vector_active(vtyvec); i++) {
2467 struct vty *vty;
2468 if (((vty = vector_slot(vtyvec, i)) != NULL) && vty->monitor)
2469 /* N.B. We don't care about the return code, since
2470 process is
2471 most likely just about to die anyway. */
2472 if (writev(vty->wfd, iov, 2) == -1) {
2473 fprintf(stderr, "Failure to writev: %d\n",
2474 errno);
2475 exit(-1);
2476 }
2477 }
2478 }
2479
2480 int vty_config_lock(struct vty *vty)
2481 {
2482 if (vty_config_is_lockless)
2483 return 1;
2484 if (vty_config == 0) {
2485 vty->config = 1;
2486 vty_config = 1;
2487 }
2488 return vty->config;
2489 }
2490
2491 int vty_config_unlock(struct vty *vty)
2492 {
2493 if (vty_config_is_lockless)
2494 return 0;
2495 if (vty_config == 1 && vty->config == 1) {
2496 vty->config = 0;
2497 vty_config = 0;
2498 }
2499 return vty->config;
2500 }
2501
2502 void vty_config_lockless(void)
2503 {
2504 vty_config_is_lockless = 1;
2505 }
2506
2507 /* Master of the threads. */
2508 static struct thread_master *vty_master;
2509
2510 static void vty_event(enum event event, int sock, struct vty *vty)
2511 {
2512 struct thread *vty_serv_thread = NULL;
2513
2514 switch (event) {
2515 case VTY_SERV:
2516 vty_serv_thread = thread_add_read(vty_master, vty_accept, vty,
2517 sock, NULL);
2518 vector_set_index(Vvty_serv_thread, sock, vty_serv_thread);
2519 break;
2520 #ifdef VTYSH
2521 case VTYSH_SERV:
2522 vty_serv_thread = thread_add_read(vty_master, vtysh_accept, vty,
2523 sock, NULL);
2524 vector_set_index(Vvty_serv_thread, sock, vty_serv_thread);
2525 break;
2526 case VTYSH_READ:
2527 vty->t_read = NULL;
2528 thread_add_read(vty_master, vtysh_read, vty, sock,
2529 &vty->t_read);
2530 break;
2531 case VTYSH_WRITE:
2532 vty->t_write = NULL;
2533 thread_add_write(vty_master, vtysh_write, vty, sock,
2534 &vty->t_write);
2535 break;
2536 #endif /* VTYSH */
2537 case VTY_READ:
2538 vty->t_read = NULL;
2539 thread_add_read(vty_master, vty_read, vty, sock, &vty->t_read);
2540
2541 /* Time out treatment. */
2542 if (vty->v_timeout) {
2543 if (vty->t_timeout)
2544 thread_cancel(vty->t_timeout);
2545 vty->t_timeout = NULL;
2546 thread_add_timer(vty_master, vty_timeout, vty,
2547 vty->v_timeout, &vty->t_timeout);
2548 }
2549 break;
2550 case VTY_WRITE:
2551 thread_add_write(vty_master, vty_flush, vty, sock,
2552 &vty->t_write);
2553 break;
2554 case VTY_TIMEOUT_RESET:
2555 if (vty->t_timeout) {
2556 thread_cancel(vty->t_timeout);
2557 vty->t_timeout = NULL;
2558 }
2559 if (vty->v_timeout) {
2560 vty->t_timeout = NULL;
2561 thread_add_timer(vty_master, vty_timeout, vty,
2562 vty->v_timeout, &vty->t_timeout);
2563 }
2564 break;
2565 }
2566 }
2567
2568 DEFUN_NOSH (config_who,
2569 config_who_cmd,
2570 "who",
2571 "Display who is on vty\n")
2572 {
2573 unsigned int i;
2574 struct vty *v;
2575
2576 for (i = 0; i < vector_active(vtyvec); i++)
2577 if ((v = vector_slot(vtyvec, i)) != NULL)
2578 vty_out(vty, "%svty[%d] connected from %s.\n",
2579 v->config ? "*" : " ", i, v->address);
2580 return CMD_SUCCESS;
2581 }
2582
2583 /* Move to vty configuration mode. */
2584 DEFUN_NOSH (line_vty,
2585 line_vty_cmd,
2586 "line vty",
2587 "Configure a terminal line\n"
2588 "Virtual terminal\n")
2589 {
2590 vty->node = VTY_NODE;
2591 return CMD_SUCCESS;
2592 }
2593
2594 /* Set time out value. */
2595 static int exec_timeout(struct vty *vty, const char *min_str,
2596 const char *sec_str)
2597 {
2598 unsigned long timeout = 0;
2599
2600 /* min_str and sec_str are already checked by parser. So it must be
2601 all digit string. */
2602 if (min_str) {
2603 timeout = strtol(min_str, NULL, 10);
2604 timeout *= 60;
2605 }
2606 if (sec_str)
2607 timeout += strtol(sec_str, NULL, 10);
2608
2609 vty_timeout_val = timeout;
2610 vty->v_timeout = timeout;
2611 vty_event(VTY_TIMEOUT_RESET, 0, vty);
2612
2613
2614 return CMD_SUCCESS;
2615 }
2616
2617 DEFUN (exec_timeout_min,
2618 exec_timeout_min_cmd,
2619 "exec-timeout (0-35791)",
2620 "Set timeout value\n"
2621 "Timeout value in minutes\n")
2622 {
2623 int idx_number = 1;
2624 return exec_timeout(vty, argv[idx_number]->arg, NULL);
2625 }
2626
2627 DEFUN (exec_timeout_sec,
2628 exec_timeout_sec_cmd,
2629 "exec-timeout (0-35791) (0-2147483)",
2630 "Set the EXEC timeout\n"
2631 "Timeout in minutes\n"
2632 "Timeout in seconds\n")
2633 {
2634 int idx_number = 1;
2635 int idx_number_2 = 2;
2636 return exec_timeout(vty, argv[idx_number]->arg,
2637 argv[idx_number_2]->arg);
2638 }
2639
2640 DEFUN (no_exec_timeout,
2641 no_exec_timeout_cmd,
2642 "no exec-timeout",
2643 NO_STR
2644 "Set the EXEC timeout\n")
2645 {
2646 return exec_timeout(vty, NULL, NULL);
2647 }
2648
2649 /* Set vty access class. */
2650 DEFUN (vty_access_class,
2651 vty_access_class_cmd,
2652 "access-class WORD",
2653 "Filter connections based on an IP access list\n"
2654 "IP access list\n")
2655 {
2656 int idx_word = 1;
2657 if (vty_accesslist_name)
2658 XFREE(MTYPE_VTY, vty_accesslist_name);
2659
2660 vty_accesslist_name = XSTRDUP(MTYPE_VTY, argv[idx_word]->arg);
2661
2662 return CMD_SUCCESS;
2663 }
2664
2665 /* Clear vty access class. */
2666 DEFUN (no_vty_access_class,
2667 no_vty_access_class_cmd,
2668 "no access-class [WORD]",
2669 NO_STR
2670 "Filter connections based on an IP access list\n"
2671 "IP access list\n")
2672 {
2673 int idx_word = 2;
2674 const char *accesslist = (argc == 3) ? argv[idx_word]->arg : NULL;
2675 if (!vty_accesslist_name
2676 || (argc == 3 && strcmp(vty_accesslist_name, accesslist))) {
2677 vty_out(vty, "Access-class is not currently applied to vty\n");
2678 return CMD_WARNING_CONFIG_FAILED;
2679 }
2680
2681 XFREE(MTYPE_VTY, vty_accesslist_name);
2682
2683 vty_accesslist_name = NULL;
2684
2685 return CMD_SUCCESS;
2686 }
2687
2688 /* Set vty access class. */
2689 DEFUN (vty_ipv6_access_class,
2690 vty_ipv6_access_class_cmd,
2691 "ipv6 access-class WORD",
2692 IPV6_STR
2693 "Filter connections based on an IP access list\n"
2694 "IPv6 access list\n")
2695 {
2696 int idx_word = 2;
2697 if (vty_ipv6_accesslist_name)
2698 XFREE(MTYPE_VTY, vty_ipv6_accesslist_name);
2699
2700 vty_ipv6_accesslist_name = XSTRDUP(MTYPE_VTY, argv[idx_word]->arg);
2701
2702 return CMD_SUCCESS;
2703 }
2704
2705 /* Clear vty access class. */
2706 DEFUN (no_vty_ipv6_access_class,
2707 no_vty_ipv6_access_class_cmd,
2708 "no ipv6 access-class [WORD]",
2709 NO_STR
2710 IPV6_STR
2711 "Filter connections based on an IP access list\n"
2712 "IPv6 access list\n")
2713 {
2714 int idx_word = 3;
2715 const char *accesslist = (argc == 4) ? argv[idx_word]->arg : NULL;
2716
2717 if (!vty_ipv6_accesslist_name
2718 || (argc == 4 && strcmp(vty_ipv6_accesslist_name, accesslist))) {
2719 vty_out(vty,
2720 "IPv6 access-class is not currently applied to vty\n");
2721 return CMD_WARNING_CONFIG_FAILED;
2722 }
2723
2724 XFREE(MTYPE_VTY, vty_ipv6_accesslist_name);
2725
2726 vty_ipv6_accesslist_name = NULL;
2727
2728 return CMD_SUCCESS;
2729 }
2730
2731 /* vty login. */
2732 DEFUN (vty_login,
2733 vty_login_cmd,
2734 "login",
2735 "Enable password checking\n")
2736 {
2737 no_password_check = 0;
2738 return CMD_SUCCESS;
2739 }
2740
2741 DEFUN (no_vty_login,
2742 no_vty_login_cmd,
2743 "no login",
2744 NO_STR
2745 "Enable password checking\n")
2746 {
2747 no_password_check = 1;
2748 return CMD_SUCCESS;
2749 }
2750
2751 DEFUN (service_advanced_vty,
2752 service_advanced_vty_cmd,
2753 "service advanced-vty",
2754 "Set up miscellaneous service\n"
2755 "Enable advanced mode vty interface\n")
2756 {
2757 host.advanced = 1;
2758 return CMD_SUCCESS;
2759 }
2760
2761 DEFUN (no_service_advanced_vty,
2762 no_service_advanced_vty_cmd,
2763 "no service advanced-vty",
2764 NO_STR
2765 "Set up miscellaneous service\n"
2766 "Enable advanced mode vty interface\n")
2767 {
2768 host.advanced = 0;
2769 return CMD_SUCCESS;
2770 }
2771
2772 DEFUN_NOSH (terminal_monitor,
2773 terminal_monitor_cmd,
2774 "terminal monitor",
2775 "Set terminal line parameters\n"
2776 "Copy debug output to the current terminal line\n")
2777 {
2778 vty->monitor = 1;
2779 return CMD_SUCCESS;
2780 }
2781
2782 DEFUN_NOSH (terminal_no_monitor,
2783 terminal_no_monitor_cmd,
2784 "terminal no monitor",
2785 "Set terminal line parameters\n"
2786 NO_STR
2787 "Copy debug output to the current terminal line\n")
2788 {
2789 vty->monitor = 0;
2790 return CMD_SUCCESS;
2791 }
2792
2793 DEFUN_NOSH (no_terminal_monitor,
2794 no_terminal_monitor_cmd,
2795 "no terminal monitor",
2796 NO_STR
2797 "Set terminal line parameters\n"
2798 "Copy debug output to the current terminal line\n")
2799 {
2800 return terminal_no_monitor(self, vty, argc, argv);
2801 }
2802
2803
2804 DEFUN_NOSH (show_history,
2805 show_history_cmd,
2806 "show history",
2807 SHOW_STR
2808 "Display the session command history\n")
2809 {
2810 int index;
2811
2812 for (index = vty->hindex + 1; index != vty->hindex;) {
2813 if (index == VTY_MAXHIST) {
2814 index = 0;
2815 continue;
2816 }
2817
2818 if (vty->hist[index] != NULL)
2819 vty_out(vty, " %s\n", vty->hist[index]);
2820
2821 index++;
2822 }
2823
2824 return CMD_SUCCESS;
2825 }
2826
2827 /* vty login. */
2828 DEFUN (log_commands,
2829 log_commands_cmd,
2830 "log commands",
2831 "Logging control\n"
2832 "Log all commands (can't be unset without restart)\n")
2833 {
2834 do_log_commands = 1;
2835 return CMD_SUCCESS;
2836 }
2837
2838 /* Display current configuration. */
2839 static int vty_config_write(struct vty *vty)
2840 {
2841 vty_out(vty, "line vty\n");
2842
2843 if (vty_accesslist_name)
2844 vty_out(vty, " access-class %s\n", vty_accesslist_name);
2845
2846 if (vty_ipv6_accesslist_name)
2847 vty_out(vty, " ipv6 access-class %s\n",
2848 vty_ipv6_accesslist_name);
2849
2850 /* exec-timeout */
2851 if (vty_timeout_val != VTY_TIMEOUT_DEFAULT)
2852 vty_out(vty, " exec-timeout %ld %ld\n", vty_timeout_val / 60,
2853 vty_timeout_val % 60);
2854
2855 /* login */
2856 if (no_password_check)
2857 vty_out(vty, " no login\n");
2858
2859 if (do_log_commands)
2860 vty_out(vty, "log commands\n");
2861
2862 vty_out(vty, "!\n");
2863
2864 return CMD_SUCCESS;
2865 }
2866
2867 struct cmd_node vty_node = {
2868 VTY_NODE, "%s(config-line)# ", 1,
2869 };
2870
2871 /* Reset all VTY status. */
2872 void vty_reset()
2873 {
2874 unsigned int i;
2875 struct vty *vty;
2876 struct thread *vty_serv_thread;
2877
2878 for (i = 0; i < vector_active(vtyvec); i++)
2879 if ((vty = vector_slot(vtyvec, i)) != NULL) {
2880 buffer_reset(vty->obuf);
2881 vty->status = VTY_CLOSE;
2882 vty_close(vty);
2883 }
2884
2885 for (i = 0; i < vector_active(Vvty_serv_thread); i++)
2886 if ((vty_serv_thread = vector_slot(Vvty_serv_thread, i))
2887 != NULL) {
2888 thread_cancel(vty_serv_thread);
2889 vector_slot(Vvty_serv_thread, i) = NULL;
2890 close(i);
2891 }
2892
2893 vty_timeout_val = VTY_TIMEOUT_DEFAULT;
2894
2895 if (vty_accesslist_name) {
2896 XFREE(MTYPE_VTY, vty_accesslist_name);
2897 vty_accesslist_name = NULL;
2898 }
2899
2900 if (vty_ipv6_accesslist_name) {
2901 XFREE(MTYPE_VTY, vty_ipv6_accesslist_name);
2902 vty_ipv6_accesslist_name = NULL;
2903 }
2904 }
2905
2906 static void vty_save_cwd(void)
2907 {
2908 char cwd[MAXPATHLEN];
2909 char *c;
2910
2911 c = getcwd(cwd, MAXPATHLEN);
2912
2913 if (!c) {
2914 /*
2915 * At this point if these go wrong, more than likely
2916 * the whole world is coming down around us
2917 * Hence not worrying about it too much.
2918 */
2919 if (!chdir(SYSCONFDIR)) {
2920 zlog_err("Failure to chdir to %s, errno: %d",
2921 SYSCONFDIR, errno);
2922 exit(-1);
2923 }
2924 if (getcwd(cwd, MAXPATHLEN) == NULL) {
2925 zlog_err("Failure to getcwd, errno: %d",
2926 errno);
2927 exit(-1);
2928 }
2929 }
2930
2931 vty_cwd = XMALLOC(MTYPE_TMP, strlen(cwd) + 1);
2932 strcpy(vty_cwd, cwd);
2933 }
2934
2935 char *vty_get_cwd()
2936 {
2937 return vty_cwd;
2938 }
2939
2940 int vty_shell(struct vty *vty)
2941 {
2942 return vty->type == VTY_SHELL ? 1 : 0;
2943 }
2944
2945 int vty_shell_serv(struct vty *vty)
2946 {
2947 return vty->type == VTY_SHELL_SERV ? 1 : 0;
2948 }
2949
2950 void vty_init_vtysh()
2951 {
2952 vtyvec = vector_init(VECTOR_MIN_SIZE);
2953 }
2954
2955 /* Install vty's own commands like `who' command. */
2956 void vty_init(struct thread_master *master_thread)
2957 {
2958 /* For further configuration read, preserve current directory. */
2959 vty_save_cwd();
2960
2961 vtyvec = vector_init(VECTOR_MIN_SIZE);
2962
2963 vty_master = master_thread;
2964
2965 atexit(vty_stdio_atexit);
2966
2967 /* Initilize server thread vector. */
2968 Vvty_serv_thread = vector_init(VECTOR_MIN_SIZE);
2969
2970 /* Install bgp top node. */
2971 install_node(&vty_node, vty_config_write);
2972
2973 install_element(VIEW_NODE, &config_who_cmd);
2974 install_element(VIEW_NODE, &show_history_cmd);
2975 install_element(CONFIG_NODE, &line_vty_cmd);
2976 install_element(CONFIG_NODE, &service_advanced_vty_cmd);
2977 install_element(CONFIG_NODE, &no_service_advanced_vty_cmd);
2978 install_element(CONFIG_NODE, &show_history_cmd);
2979 install_element(CONFIG_NODE, &log_commands_cmd);
2980 install_element(ENABLE_NODE, &terminal_monitor_cmd);
2981 install_element(ENABLE_NODE, &terminal_no_monitor_cmd);
2982 install_element(ENABLE_NODE, &no_terminal_monitor_cmd);
2983
2984 install_default(VTY_NODE);
2985 install_element(VTY_NODE, &exec_timeout_min_cmd);
2986 install_element(VTY_NODE, &exec_timeout_sec_cmd);
2987 install_element(VTY_NODE, &no_exec_timeout_cmd);
2988 install_element(VTY_NODE, &vty_access_class_cmd);
2989 install_element(VTY_NODE, &no_vty_access_class_cmd);
2990 install_element(VTY_NODE, &vty_login_cmd);
2991 install_element(VTY_NODE, &no_vty_login_cmd);
2992 install_element(VTY_NODE, &vty_ipv6_access_class_cmd);
2993 install_element(VTY_NODE, &no_vty_ipv6_access_class_cmd);
2994 }
2995
2996 void vty_terminate(void)
2997 {
2998 if (vty_cwd)
2999 XFREE(MTYPE_TMP, vty_cwd);
3000
3001 if (vtyvec && Vvty_serv_thread) {
3002 vty_reset();
3003 vector_free(vtyvec);
3004 vector_free(Vvty_serv_thread);
3005 vtyvec = NULL;
3006 Vvty_serv_thread = NULL;
3007 }
3008 }