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