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