]> git.proxmox.com Git - mirror_frr.git/blame - lib/vty.c
Merge pull request #6851 from kuldeepkash/bgp_graceful_restart
[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
d62a17ae 59DEFINE_MTYPE_STATIC(LIB, VTY, "VTY")
4a1ab8e4 60DEFINE_MTYPE_STATIC(LIB, VTY_OUT_BUF, "VTY output buffer")
d62a17ae 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
d62a17ae 76static void vty_event(enum event, int, struct vty *);
718e3744 77
78/* Extern host structure from command.c */
79extern struct host host;
6b0655a2 80
718e3744 81/* Vector which store each vty structure. */
82static vector vtyvec;
83
84/* Vty timeout value. */
85static unsigned long vty_timeout_val = VTY_TIMEOUT_DEFAULT;
86
87/* Vty access-class command */
88static char *vty_accesslist_name = NULL;
89
90/* Vty access-calss for IPv6. */
91static char *vty_ipv6_accesslist_name = NULL;
92
93/* VTY server thread. */
677bcbbf 94static vector Vvty_serv_thread;
718e3744 95
96/* Current directory. */
1b3e9a21 97static char vty_cwd[MAXPATHLEN];
718e3744 98
718e3744 99/* Login password check. */
100static int no_password_check = 0;
101
102/* Integrated configuration file path */
c17faa4b 103static char integrate_default[] = SYSCONFDIR INTEGRATE_DEFAULT_CONFIG;
718e3744 104
2950f5da
DS
105static bool do_log_commands;
106static bool do_log_commands_perm;
6b0655a2 107
2071aa0e
DL
108void vty_frame(struct vty *vty, const char *format, ...)
109{
110 va_list args;
111
112 va_start(args, format);
c7179009
DL
113 vsnprintfrr(vty->frame + vty->frame_pos,
114 sizeof(vty->frame) - vty->frame_pos, format, args);
2071aa0e
DL
115 vty->frame_pos = strlen(vty->frame);
116 va_end(args);
117}
118
119void 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
fe6b47b9
QY
126bool vty_set_include(struct vty *vty, const char *regexp)
127{
128 int errcode;
129 bool ret = true;
130 char errbuf[256];
131
8224c6cf 132 if (!regexp) {
133 if (vty->filter) {
134 regfree(&vty->include);
135 vty->filter = false;
136 }
fe6b47b9
QY
137 return true;
138 }
139
140 errcode = regcomp(&vty->include, regexp,
141 REG_EXTENDED | REG_NEWLINE | REG_NOSUB);
142 if (errcode) {
143 ret = false;
511942ba
IR
144 regerror(errcode, &vty->include, errbuf, sizeof(errbuf));
145 vty_out(vty, "%% Regex compilation error: %s\n", errbuf);
fe6b47b9
QY
146 } else {
147 vty->filter = true;
148 }
149
150 return ret;
151}
152
83eba583 153/* VTY standard output function. */
d62a17ae 154int vty_out(struct vty *vty, const char *format, ...)
155{
156 va_list args;
807f5b98 157 ssize_t len;
d62a17ae 158 char buf[1024];
fa3bf3a2 159 char *p = NULL;
fe6b47b9 160 char *filtered;
d62a17ae 161
2071aa0e
DL
162 if (vty->frame_pos) {
163 vty->frame_pos = 0;
164 vty_out(vty, "%s", vty->frame);
165 }
166
2cddf2ff 167 va_start(args, format);
807f5b98 168 p = vasnprintfrr(MTYPE_VTY_OUT_BUF, buf, sizeof(buf), format, args);
2cddf2ff 169 va_end(args);
d62a17ae 170
807f5b98 171 len = strlen(p);
2cddf2ff
QY
172
173 /* filter buffer */
174 if (vty->filter) {
0b42d81a
QY
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 }
5d806ec6 217
2cddf2ff 218 frrstr_strvec_free(lines);
0b42d81a 219
2cddf2ff
QY
220 } else {
221 filtered = p;
222 }
d62a17ae 223
0b42d81a
QY
224 if (!filtered)
225 goto done;
226
2cddf2ff
QY
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:
9934e1c9 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 }
2cddf2ff
QY
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;
d62a17ae 248 }
249
0b42d81a
QY
250done:
251
252 if (vty->filter && filtered)
2cddf2ff
QY
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
d62a17ae 259 return len;
260}
261
262static int vty_log_out(struct vty *vty, const char *level,
807f5b98
DL
263 const char *proto_str, const char *msg,
264 struct timestamp_control *ctl)
d62a17ae 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
807f5b98 289 if (((ret = snprintf(buf + len, sizeof(buf) - len, "%s", msg)) < 0)
d62a17ae 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 */
450971aa 305 flog_err(EC_LIB_SOCKET,
34699016
DS
306 "%s: write failed to vty client fd %d, closing: %s",
307 __func__, vty->fd, safe_strerror(errno));
d62a17ae 308 buffer_reset(vty->obuf);
0b42d81a 309 buffer_reset(vty->lbuf);
d62a17ae 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;
718e3744 317}
318
319/* Output current time to the vty. */
d62a17ae 320void vty_time_print(struct vty *vty, int cr)
718e3744 321{
d62a17ae 322 char buf[QUAGGA_TIMESTAMP_LEN];
d0bfb22c 323
d62a17ae 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);
718e3744 332
d62a17ae 333 return;
718e3744 334}
335
336/* Say hello to vty interface. */
d62a17ae 337void 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);
fefa5e0f
DL
350 (s > buf) && isspace((unsigned char)s[-1]);
351 s--)
d62a17ae 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);
718e3744 361}
362
363/* Put out prompt and wait input from user. */
d62a17ae 364static void vty_prompt(struct vty *vty)
718e3744 365{
d62a17ae 366 if (vty->type == VTY_TERM) {
60466a63 367 vty_out(vty, cmd_prompt(vty->node), cmd_hostname_get());
d62a17ae 368 }
718e3744 369}
370
371/* Send WILL TELOPT_ECHO to remote server. */
d62a17ae 372static void vty_will_echo(struct vty *vty)
718e3744 373{
d62a17ae 374 unsigned char cmd[] = {IAC, WILL, TELOPT_ECHO, '\0'};
375 vty_out(vty, "%s", cmd);
718e3744 376}
377
378/* Make suppress Go-Ahead telnet option. */
d62a17ae 379static void vty_will_suppress_go_ahead(struct vty *vty)
718e3744 380{
d62a17ae 381 unsigned char cmd[] = {IAC, WILL, TELOPT_SGA, '\0'};
382 vty_out(vty, "%s", cmd);
718e3744 383}
384
385/* Make don't use linemode over telnet. */
d62a17ae 386static void vty_dont_linemode(struct vty *vty)
718e3744 387{
d62a17ae 388 unsigned char cmd[] = {IAC, DONT, TELOPT_LINEMODE, '\0'};
389 vty_out(vty, "%s", cmd);
718e3744 390}
391
392/* Use window size. */
d62a17ae 393static void vty_do_window_size(struct vty *vty)
718e3744 394{
d62a17ae 395 unsigned char cmd[] = {IAC, DO, TELOPT_NAWS, '\0'};
396 vty_out(vty, "%s", cmd);
718e3744 397}
398
d62a17ae 399#if 0 /* Currently not used. */
718e3744 400/* Make don't use lflow vty interface. */
401static void
402vty_dont_lflow_ahead (struct vty *vty)
403{
02ff83c5 404 unsigned char cmd[] = { IAC, DONT, TELOPT_LFLOW, '\0' };
718e3744 405 vty_out (vty, "%s", cmd);
406}
407#endif /* 0 */
408
718e3744 409/* Authentication of vty */
d62a17ae 410static void vty_auth(struct vty *vty, char *buf)
411{
412 char *passwd = NULL;
413 enum node_type next_node = 0;
414 int fail;
415 char *crypt(const char *, const char *);
416
417 switch (vty->node) {
418 case AUTH_NODE:
419 if (host.encrypt)
420 passwd = host.password_encrypt;
421 else
422 passwd = host.password;
423 if (host.advanced)
424 next_node = host.enable ? VIEW_NODE : ENABLE_NODE;
425 else
426 next_node = VIEW_NODE;
427 break;
428 case AUTH_ENABLE_NODE:
429 if (host.encrypt)
430 passwd = host.enable_encrypt;
431 else
432 passwd = host.enable;
433 next_node = ENABLE_NODE;
434 break;
435 }
436
437 if (passwd) {
438 if (host.encrypt)
439 fail = strcmp(crypt(buf, passwd), passwd);
440 else
441 fail = strcmp(buf, passwd);
442 } else
443 fail = 1;
444
445 if (!fail) {
446 vty->fail = 0;
447 vty->node = next_node; /* Success ! */
448 } else {
449 vty->fail++;
450 if (vty->fail >= 3) {
451 if (vty->node == AUTH_NODE) {
452 vty_out(vty,
453 "%% Bad passwords, too many failures!\n");
454 vty->status = VTY_CLOSE;
455 } else {
456 /* AUTH_ENABLE_NODE */
457 vty->fail = 0;
458 vty_out(vty,
459 "%% Bad enable passwords, too many failures!\n");
460 vty->status = VTY_CLOSE;
461 }
462 }
463 }
718e3744 464}
465
466/* Command execution over the vty interface. */
d62a17ae 467static int vty_command(struct vty *vty, char *buf)
468{
469 int ret;
d62a17ae 470 const char *protocolname;
471 char *cp = NULL;
472
b575a12c
A
473 assert(vty);
474
d62a17ae 475 /*
476 * Log non empty command lines
477 */
478 if (do_log_commands)
479 cp = buf;
480 if (cp != NULL) {
481 /* Skip white spaces. */
fefa5e0f 482 while (isspace((unsigned char)*cp) && *cp != '\0')
d62a17ae 483 cp++;
484 }
485 if (cp != NULL && *cp != '\0') {
486 unsigned i;
487 char vty_str[VTY_BUFSIZ];
488 char prompt_str[VTY_BUFSIZ];
489
490 /* format the base vty info */
491 snprintf(vty_str, sizeof(vty_str), "vty[??]@%s", vty->address);
b575a12c
A
492
493 for (i = 0; i < vector_active(vtyvec); i++)
494 if (vty == vector_slot(vtyvec, i)) {
495 snprintf(vty_str, sizeof(vty_str), "vty[%d]@%s",
496 i, vty->address);
497 break;
498 }
d62a17ae 499
500 /* format the prompt */
501 snprintf(prompt_str, sizeof(prompt_str), cmd_prompt(vty->node),
502 vty_str);
503
504 /* now log the command */
3ec8b5b8 505 zlog_notice("%s%s", prompt_str, buf);
d62a17ae 506 }
718e3744 507
924b9229 508#ifdef CONSUMED_TIME_CHECK
d62a17ae 509 {
510 RUSAGE_T before;
511 RUSAGE_T after;
512 unsigned long realtime, cputime;
924b9229 513
d62a17ae 514 GETRUSAGE(&before);
924b9229 515#endif /* CONSUMED_TIME_CHECK */
516
fe6b47b9 517 ret = cmd_execute(vty, buf, NULL, 0);
718e3744 518
d62a17ae 519 /* Get the name of the protocol if any */
520 protocolname = frr_protoname;
d0bfb22c 521
924b9229 522#ifdef CONSUMED_TIME_CHECK
d62a17ae 523 GETRUSAGE(&after);
524 if ((realtime = thread_consumed_time(&after, &before, &cputime))
525 > CONSUMED_TIME_CHECK)
526 /* Warn about CPU hog that must be fixed. */
34699016 527 flog_warn(
450971aa 528 EC_LIB_SLOW_THREAD,
d62a17ae 529 "SLOW COMMAND: command took %lums (cpu time %lums): %s",
530 realtime / 1000, cputime / 1000, buf);
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 }
718e3744 1093#if 0
55f70b67 1094 vty_out (vty, " %-*s %s\n", width
d0bfb22c 1095 desc->cmd[0] == '.' ? desc->cmd + 1 : desc->cmd,
55f70b67 1096 desc->str ? desc->str : "");
718e3744 1097#endif /* 0 */
d62a17ae 1098 }
1099
1100 if ((token = token_cr)) {
1101 if (!token->desc)
1102 vty_out(vty, " %-s\n", token->text);
1103 else if (desc_width >= strlen(token->desc))
1104 vty_out(vty, " %-*s %s\n", width, token->text,
1105 token->desc);
1106 else
1107 vty_describe_fold(vty, width, desc_width, token);
1108 }
718e3744 1109
2fe8aba3 1110out:
d62a17ae 1111 cmd_free_strvec(vline);
1112 if (describe)
1113 vector_free(describe);
718e3744 1114
d62a17ae 1115 vty_prompt(vty);
1116 vty_redraw_line(vty);
718e3744 1117}
1118
d62a17ae 1119static void vty_clear_buf(struct vty *vty)
718e3744 1120{
d62a17ae 1121 memset(vty->buf, 0, vty->max);
718e3744 1122}
1123
1124/* ^C stop current input and do not add command line to the history. */
d62a17ae 1125static void vty_stop_input(struct vty *vty)
1126{
1127 vty->cp = vty->length = 0;
1128 vty_clear_buf(vty);
1129 vty_out(vty, "\n");
1130
cf09d3ca 1131 if (vty->config) {
f344c66e 1132 vty_config_exit(vty);
d62a17ae 1133 vty->node = ENABLE_NODE;
d62a17ae 1134 }
cf09d3ca 1135
d62a17ae 1136 vty_prompt(vty);
1137
1138 /* Set history pointer to the latest one. */
1139 vty->hp = vty->hindex;
718e3744 1140}
1141
1142/* Add current command line to the history buffer. */
d62a17ae 1143static void vty_hist_add(struct vty *vty)
718e3744 1144{
d62a17ae 1145 int index;
718e3744 1146
d62a17ae 1147 if (vty->length == 0)
1148 return;
718e3744 1149
d62a17ae 1150 index = vty->hindex ? vty->hindex - 1 : VTY_MAXHIST - 1;
718e3744 1151
d62a17ae 1152 /* Ignore the same string as previous one. */
1153 if (vty->hist[index])
1154 if (strcmp(vty->buf, vty->hist[index]) == 0) {
1155 vty->hp = vty->hindex;
1156 return;
1157 }
718e3744 1158
d62a17ae 1159 /* Insert history entry. */
0a22ddfb 1160 XFREE(MTYPE_VTY_HIST, vty->hist[vty->hindex]);
d62a17ae 1161 vty->hist[vty->hindex] = XSTRDUP(MTYPE_VTY_HIST, vty->buf);
718e3744 1162
d62a17ae 1163 /* History index rotation. */
1164 vty->hindex++;
1165 if (vty->hindex == VTY_MAXHIST)
1166 vty->hindex = 0;
718e3744 1167
d62a17ae 1168 vty->hp = vty->hindex;
718e3744 1169}
1170
1171/* #define TELNET_OPTION_DEBUG */
1172
1173/* Get telnet window size. */
d62a17ae 1174static int vty_telnet_option(struct vty *vty, unsigned char *buf, int nbytes)
718e3744 1175{
1176#ifdef TELNET_OPTION_DEBUG
d62a17ae 1177 int i;
1178
1179 for (i = 0; i < nbytes; i++) {
1180 switch (buf[i]) {
1181 case IAC:
1182 vty_out(vty, "IAC ");
1183 break;
1184 case WILL:
1185 vty_out(vty, "WILL ");
1186 break;
1187 case WONT:
1188 vty_out(vty, "WONT ");
1189 break;
1190 case DO:
1191 vty_out(vty, "DO ");
1192 break;
1193 case DONT:
1194 vty_out(vty, "DONT ");
1195 break;
1196 case SB:
1197 vty_out(vty, "SB ");
1198 break;
1199 case SE:
1200 vty_out(vty, "SE ");
1201 break;
1202 case TELOPT_ECHO:
1203 vty_out(vty, "TELOPT_ECHO \n");
1204 break;
1205 case TELOPT_SGA:
1206 vty_out(vty, "TELOPT_SGA \n");
1207 break;
1208 case TELOPT_NAWS:
1209 vty_out(vty, "TELOPT_NAWS \n");
1210 break;
1211 default:
1212 vty_out(vty, "%x ", buf[i]);
1213 break;
1214 }
1215 }
1216 vty_out(vty, "\n");
718e3744 1217
1218#endif /* TELNET_OPTION_DEBUG */
1219
d62a17ae 1220 switch (buf[0]) {
1221 case SB:
1222 vty->sb_len = 0;
1223 vty->iac_sb_in_progress = 1;
1224 return 0;
d62a17ae 1225 case SE: {
1226 if (!vty->iac_sb_in_progress)
1227 return 0;
1228
1229 if ((vty->sb_len == 0) || (vty->sb_buf[0] == '\0')) {
1230 vty->iac_sb_in_progress = 0;
1231 return 0;
1232 }
1233 switch (vty->sb_buf[0]) {
1234 case TELOPT_NAWS:
1235 if (vty->sb_len != TELNET_NAWS_SB_LEN)
34699016 1236 flog_err(
450971aa 1237 EC_LIB_SYSTEM_CALL,
3efd0893 1238 "RFC 1073 violation detected: telnet NAWS option should send %d characters, but we received %lu",
d62a17ae 1239 TELNET_NAWS_SB_LEN,
d7c0a89a 1240 (unsigned long)vty->sb_len);
d62a17ae 1241 else if (sizeof(vty->sb_buf) < TELNET_NAWS_SB_LEN)
af4c2728 1242 flog_err(
450971aa 1243 EC_LIB_DEVELOPMENT,
472878dc 1244 "Bug detected: sizeof(vty->sb_buf) %lu < %d, too small to handle the telnet NAWS option",
d7c0a89a 1245 (unsigned long)sizeof(vty->sb_buf),
d62a17ae 1246 TELNET_NAWS_SB_LEN);
1247 else {
1248 vty->width = ((vty->sb_buf[1] << 8)
1249 | vty->sb_buf[2]);
1250 vty->height = ((vty->sb_buf[3] << 8)
1251 | vty->sb_buf[4]);
9fc7ebf1 1252#ifdef TELNET_OPTION_DEBUG
d62a17ae 1253 vty_out(vty,
3efd0893 1254 "TELNET NAWS window size negotiation completed: width %d, height %d\n",
d62a17ae 1255 vty->width, vty->height);
9fc7ebf1 1256#endif
d62a17ae 1257 }
1258 break;
1259 }
1260 vty->iac_sb_in_progress = 0;
1261 return 0;
d62a17ae 1262 }
1263 default:
1264 break;
1265 }
1266 return 1;
718e3744 1267}
1268
1269/* Execute current command line. */
d62a17ae 1270static int vty_execute(struct vty *vty)
718e3744 1271{
d62a17ae 1272 int ret;
718e3744 1273
d62a17ae 1274 ret = CMD_SUCCESS;
718e3744 1275
d62a17ae 1276 switch (vty->node) {
1277 case AUTH_NODE:
1278 case AUTH_ENABLE_NODE:
1279 vty_auth(vty, vty->buf);
1280 break;
1281 default:
1282 ret = vty_command(vty, vty->buf);
1283 if (vty->type == VTY_TERM)
1284 vty_hist_add(vty);
1285 break;
1286 }
718e3744 1287
d62a17ae 1288 /* Clear command line buffer. */
1289 vty->cp = vty->length = 0;
1290 vty_clear_buf(vty);
718e3744 1291
d62a17ae 1292 if (vty->status != VTY_CLOSE)
1293 vty_prompt(vty);
718e3744 1294
d62a17ae 1295 return ret;
718e3744 1296}
1297
1298#define CONTROL(X) ((X) - '@')
1299#define VTY_NORMAL 0
1300#define VTY_PRE_ESCAPE 1
1301#define VTY_ESCAPE 2
1302
1303/* Escape character command map. */
d62a17ae 1304static void vty_escape_map(unsigned char c, struct vty *vty)
1305{
1306 switch (c) {
1307 case ('A'):
1308 vty_previous_line(vty);
1309 break;
1310 case ('B'):
1311 vty_next_line(vty);
1312 break;
1313 case ('C'):
1314 vty_forward_char(vty);
1315 break;
1316 case ('D'):
1317 vty_backward_char(vty);
1318 break;
1319 default:
1320 break;
1321 }
1322
1323 /* Go back to normal mode. */
1324 vty->escape = VTY_NORMAL;
718e3744 1325}
1326
1327/* Quit print out to the buffer. */
d62a17ae 1328static void vty_buffer_reset(struct vty *vty)
718e3744 1329{
d62a17ae 1330 buffer_reset(vty->obuf);
0b42d81a 1331 buffer_reset(vty->lbuf);
d62a17ae 1332 vty_prompt(vty);
1333 vty_redraw_line(vty);
718e3744 1334}
1335
1336/* Read data via vty socket. */
d62a17ae 1337static int vty_read(struct thread *thread)
1338{
1339 int i;
1340 int nbytes;
1341 unsigned char buf[VTY_READ_BUFSIZ];
1342
1343 int vty_sock = THREAD_FD(thread);
1344 struct vty *vty = THREAD_ARG(thread);
d62a17ae 1345
1346 /* Read raw data from socket */
1347 if ((nbytes = read(vty->fd, buf, VTY_READ_BUFSIZ)) <= 0) {
1348 if (nbytes < 0) {
1349 if (ERRNO_IO_RETRY(errno)) {
1350 vty_event(VTY_READ, vty_sock, vty);
1351 return 0;
1352 }
1353 vty->monitor = 0; /* disable monitoring to avoid
1354 infinite recursion */
34699016 1355 flog_err(
450971aa 1356 EC_LIB_SOCKET,
d62a17ae 1357 "%s: read error on vty client fd %d, closing: %s",
1358 __func__, vty->fd, safe_strerror(errno));
1359 buffer_reset(vty->obuf);
0b42d81a 1360 buffer_reset(vty->lbuf);
d62a17ae 1361 }
1362 vty->status = VTY_CLOSE;
1363 }
1364
1365 for (i = 0; i < nbytes; i++) {
1366 if (buf[i] == IAC) {
1367 if (!vty->iac) {
1368 vty->iac = 1;
1369 continue;
1370 } else {
1371 vty->iac = 0;
1372 }
1373 }
1374
1375 if (vty->iac_sb_in_progress && !vty->iac) {
1376 if (vty->sb_len < sizeof(vty->sb_buf))
1377 vty->sb_buf[vty->sb_len] = buf[i];
1378 vty->sb_len++;
1379 continue;
1380 }
1381
1382 if (vty->iac) {
1383 /* In case of telnet command */
1384 int ret = 0;
1385 ret = vty_telnet_option(vty, buf + i, nbytes - i);
1386 vty->iac = 0;
1387 i += ret;
1388 continue;
1389 }
1390
1391
1392 if (vty->status == VTY_MORE) {
1393 switch (buf[i]) {
1394 case CONTROL('C'):
1395 case 'q':
1396 case 'Q':
1397 vty_buffer_reset(vty);
1398 break;
718e3744 1399#if 0 /* More line does not work for "show ip bgp". */
d0bfb22c
QY
1400 case '\n':
1401 case '\r':
1402 vty->status = VTY_MORELINE;
1403 break;
718e3744 1404#endif
d62a17ae 1405 default:
1406 break;
1407 }
1408 continue;
1409 }
1410
1411 /* Escape character. */
1412 if (vty->escape == VTY_ESCAPE) {
1413 vty_escape_map(buf[i], vty);
1414 continue;
1415 }
1416
1417 /* Pre-escape status. */
1418 if (vty->escape == VTY_PRE_ESCAPE) {
1419 switch (buf[i]) {
1420 case '[':
1421 vty->escape = VTY_ESCAPE;
1422 break;
1423 case 'b':
1424 vty_backward_word(vty);
1425 vty->escape = VTY_NORMAL;
1426 break;
1427 case 'f':
1428 vty_forward_word(vty);
1429 vty->escape = VTY_NORMAL;
1430 break;
1431 case 'd':
1432 vty_forward_kill_word(vty);
1433 vty->escape = VTY_NORMAL;
1434 break;
1435 case CONTROL('H'):
1436 case 0x7f:
1437 vty_backward_kill_word(vty);
1438 vty->escape = VTY_NORMAL;
1439 break;
1440 default:
1441 vty->escape = VTY_NORMAL;
1442 break;
1443 }
1444 continue;
1445 }
1446
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;
1491 case '\n':
1492 case '\r':
1493 vty_out(vty, "\n");
1494 vty_execute(vty);
1495 break;
1496 case '\t':
1497 vty_complete_command(vty);
1498 break;
1499 case '?':
1500 if (vty->node == AUTH_NODE
1501 || vty->node == AUTH_ENABLE_NODE)
1502 vty_self_insert(vty, buf[i]);
1503 else
1504 vty_describe_command(vty);
1505 break;
1506 case '\033':
1507 if (i + 1 < nbytes && buf[i + 1] == '[') {
1508 vty->escape = VTY_ESCAPE;
1509 i++;
1510 } else
1511 vty->escape = VTY_PRE_ESCAPE;
1512 break;
1513 default:
1514 if (buf[i] > 31 && buf[i] < 127)
1515 vty_self_insert(vty, buf[i]);
1516 break;
1517 }
1518 }
1519
1520 /* Check status. */
1521 if (vty->status == VTY_CLOSE)
1522 vty_close(vty);
1523 else {
1524 vty_event(VTY_WRITE, vty->wfd, vty);
1525 vty_event(VTY_READ, vty_sock, vty);
1526 }
1527 return 0;
718e3744 1528}
1529
1530/* Flush buffer to the vty. */
d62a17ae 1531static int vty_flush(struct thread *thread)
1532{
1533 int erase;
1534 buffer_status_t flushrc;
1535 int vty_sock = THREAD_FD(thread);
1536 struct vty *vty = THREAD_ARG(thread);
1537
d62a17ae 1538 /* Tempolary disable read thread. */
43b8ca99
DS
1539 if (vty->lines == 0)
1540 THREAD_OFF(vty->t_read);
d62a17ae 1541
1542 /* Function execution continue. */
1543 erase = ((vty->status == VTY_MORE || vty->status == VTY_MORELINE));
1544
1545 /* N.B. if width is 0, that means we don't know the window size. */
1546 if ((vty->lines == 0) || (vty->width == 0) || (vty->height == 0))
1547 flushrc = buffer_flush_available(vty->obuf, vty_sock);
1548 else if (vty->status == VTY_MORELINE)
1549 flushrc = buffer_flush_window(vty->obuf, vty_sock, vty->width,
1550 1, erase, 0);
1551 else
1552 flushrc = buffer_flush_window(
1553 vty->obuf, vty_sock, vty->width,
1554 vty->lines >= 0 ? vty->lines : vty->height, erase, 0);
1555 switch (flushrc) {
1556 case BUFFER_ERROR:
1557 vty->monitor =
1558 0; /* disable monitoring to avoid infinite recursion */
34699016 1559 zlog_info("buffer_flush failed on vty client fd %d, closing",
d62a17ae 1560 vty->fd);
0b42d81a 1561 buffer_reset(vty->lbuf);
d62a17ae 1562 buffer_reset(vty->obuf);
1563 vty_close(vty);
1564 return 0;
1565 case BUFFER_EMPTY:
1566 if (vty->status == VTY_CLOSE)
1567 vty_close(vty);
1568 else {
1569 vty->status = VTY_NORMAL;
1570 if (vty->lines == 0)
1571 vty_event(VTY_READ, vty_sock, vty);
1572 }
1573 break;
1574 case BUFFER_PENDING:
1575 /* There is more data waiting to be written. */
1576 vty->status = VTY_MORE;
1577 if (vty->lines == 0)
1578 vty_event(VTY_WRITE, vty_sock, vty);
1579 break;
1580 }
1581
1582 return 0;
718e3744 1583}
1584
2cddf2ff 1585/* Allocate new vty struct. */
4d762f26 1586struct vty *vty_new(void)
2cddf2ff
QY
1587{
1588 struct vty *new = XCALLOC(MTYPE_VTY, sizeof(struct vty));
1589
1590 new->fd = new->wfd = -1;
6ef6e4f0 1591 new->of = stdout;
0b42d81a 1592 new->lbuf = buffer_new(0);
2cddf2ff
QY
1593 new->obuf = buffer_new(0); /* Use default buffer size. */
1594 new->buf = XCALLOC(MTYPE_VTY, VTY_BUFSIZ);
2cddf2ff
QY
1595 new->max = VTY_BUFSIZ;
1596
1597 return new;
1598}
1599
1600
b7642925 1601/* allocate and initialise vty */
d62a17ae 1602static struct vty *vty_new_init(int vty_sock)
1603{
1604 struct vty *vty;
1605
1606 vty = vty_new();
1607 vty->fd = vty_sock;
1608 vty->wfd = vty_sock;
1609 vty->type = VTY_TERM;
1610 vty->node = AUTH_NODE;
1611 vty->fail = 0;
1612 vty->cp = 0;
1613 vty_clear_buf(vty);
1614 vty->length = 0;
1615 memset(vty->hist, 0, sizeof(vty->hist));
1616 vty->hp = 0;
1617 vty->hindex = 0;
1c2facd1
RW
1618 vty->xpath_index = 0;
1619 memset(vty->xpath, 0, sizeof(vty->xpath));
1620 vty->private_config = false;
1621 vty->candidate_config = vty_shared_candidate_config;
d62a17ae 1622 vector_set_index(vtyvec, vty_sock, vty);
1623 vty->status = VTY_NORMAL;
1624 vty->lines = -1;
1625 vty->iac = 0;
1626 vty->iac_sb_in_progress = 0;
1627 vty->sb_len = 0;
1628
1629 return vty;
b7642925
DL
1630}
1631
718e3744 1632/* Create new vty structure. */
d62a17ae 1633static struct vty *vty_create(int vty_sock, union sockunion *su)
1634{
1635 char buf[SU_ADDRSTRLEN];
1636 struct vty *vty;
1637
1638 sockunion2str(su, buf, SU_ADDRSTRLEN);
1639
1640 /* Allocate new vty structure and set up default values. */
1641 vty = vty_new_init(vty_sock);
1642
1643 /* configurable parameters not part of basic init */
1644 vty->v_timeout = vty_timeout_val;
9f73d2c9 1645 strlcpy(vty->address, buf, sizeof(vty->address));
d62a17ae 1646 if (no_password_check) {
1647 if (host.advanced)
1648 vty->node = ENABLE_NODE;
1649 else
1650 vty->node = VIEW_NODE;
1651 }
1652 if (host.lines >= 0)
1653 vty->lines = host.lines;
1654
1655 if (!no_password_check) {
1656 /* Vty is not available if password isn't set. */
1657 if (host.password == NULL && host.password_encrypt == NULL) {
1658 vty_out(vty, "Vty password is not set.\n");
1659 vty->status = VTY_CLOSE;
1660 vty_close(vty);
1661 return NULL;
1662 }
1663 }
1664
1665 /* Say hello to the world. */
1666 vty_hello(vty);
1667 if (!no_password_check)
1668 vty_out(vty, "\nUser Access Verification\n\n");
1669
1670 /* Setting up terminal. */
1671 vty_will_echo(vty);
1672 vty_will_suppress_go_ahead(vty);
1673
1674 vty_dont_linemode(vty);
1675 vty_do_window_size(vty);
1676 /* vty_dont_lflow_ahead (vty); */
1677
1678 vty_prompt(vty);
1679
1680 /* Add read/write thread. */
1681 vty_event(VTY_WRITE, vty_sock, vty);
1682 vty_event(VTY_READ, vty_sock, vty);
1683
1684 return vty;
718e3744 1685}
1686
b7642925 1687/* create vty for stdio */
b510a06e
DL
1688static struct termios stdio_orig_termios;
1689static struct vty *stdio_vty = NULL;
154b9e8f
DL
1690static bool stdio_termios = false;
1691static void (*stdio_vty_atclose)(int isexit);
b510a06e 1692
154b9e8f 1693static void vty_stdio_reset(int isexit)
b510a06e 1694{
d62a17ae 1695 if (stdio_vty) {
154b9e8f
DL
1696 if (stdio_termios)
1697 tcsetattr(0, TCSANOW, &stdio_orig_termios);
1698 stdio_termios = false;
1699
d62a17ae 1700 stdio_vty = NULL;
dbf78092 1701
d62a17ae 1702 if (stdio_vty_atclose)
154b9e8f 1703 stdio_vty_atclose(isexit);
d62a17ae 1704 stdio_vty_atclose = NULL;
1705 }
b510a06e
DL
1706}
1707
154b9e8f
DL
1708static void vty_stdio_atexit(void)
1709{
1710 vty_stdio_reset(1);
1711}
1712
1713void vty_stdio_suspend(void)
1714{
1715 if (!stdio_vty)
1716 return;
1717
43b8ca99
DS
1718 THREAD_OFF(stdio_vty->t_write);
1719 THREAD_OFF(stdio_vty->t_read);
1720 THREAD_OFF(stdio_vty->t_timeout);
154b9e8f
DL
1721
1722 if (stdio_termios)
1723 tcsetattr(0, TCSANOW, &stdio_orig_termios);
1724 stdio_termios = false;
1725}
1726
1727void vty_stdio_resume(void)
1728{
1729 if (!stdio_vty)
1730 return;
1731
1732 if (!tcgetattr(0, &stdio_orig_termios)) {
1733 struct termios termios;
1734
1735 termios = stdio_orig_termios;
1736 termios.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR
1737 | IGNCR | ICRNL | IXON);
1738 termios.c_oflag &= ~OPOST;
1739 termios.c_lflag &= ~(ECHO | ECHONL | ICANON | IEXTEN);
1740 termios.c_cflag &= ~(CSIZE | PARENB);
1741 termios.c_cflag |= CS8;
1742 tcsetattr(0, TCSANOW, &termios);
1743 stdio_termios = true;
1744 }
1745
1746 vty_prompt(stdio_vty);
1747
1748 /* Add read/write thread. */
1749 vty_event(VTY_WRITE, 1, stdio_vty);
1750 vty_event(VTY_READ, 0, stdio_vty);
1751}
1752
1753void vty_stdio_close(void)
1754{
1755 if (!stdio_vty)
1756 return;
1757 vty_close(stdio_vty);
1758}
1759
1760struct vty *vty_stdio(void (*atclose)(int isexit))
b7642925 1761{
d62a17ae 1762 struct vty *vty;
b7642925 1763
d62a17ae 1764 /* refuse creating two vtys on stdio */
1765 if (stdio_vty)
1766 return NULL;
b510a06e 1767
d62a17ae 1768 vty = stdio_vty = vty_new_init(0);
1769 stdio_vty_atclose = atclose;
1770 vty->wfd = 1;
b7642925 1771
d62a17ae 1772 /* always have stdio vty in a known _unchangeable_ state, don't want
1773 * config
1774 * to have any effect here to make sure scripting this works as intended
1775 */
1776 vty->node = ENABLE_NODE;
1777 vty->v_timeout = 0;
9f73d2c9 1778 strlcpy(vty->address, "console", sizeof(vty->address));
b7642925 1779
154b9e8f 1780 vty_stdio_resume();
d62a17ae 1781 return vty;
b7642925
DL
1782}
1783
718e3744 1784/* Accept connection from the network. */
d62a17ae 1785static int vty_accept(struct thread *thread)
1786{
1787 int vty_sock;
1788 union sockunion su;
1789 int ret;
1790 unsigned int on;
1791 int accept_sock;
1792 struct prefix p;
1793 struct access_list *acl = NULL;
1794 char buf[SU_ADDRSTRLEN];
1795
1796 accept_sock = THREAD_FD(thread);
1797
1798 /* We continue hearing vty socket. */
1799 vty_event(VTY_SERV, accept_sock, NULL);
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
1813 sockunion2hostprefix(&su, &p);
1814
1815 /* VTY's accesslist apply. */
1816 if (p.family == AF_INET && vty_accesslist_name) {
1817 if ((acl = access_list_lookup(AFI_IP, vty_accesslist_name))
1818 && (access_list_apply(acl, &p) == FILTER_DENY)) {
1819 zlog_info("Vty connection refused from %s",
1820 sockunion2str(&su, buf, SU_ADDRSTRLEN));
1821 close(vty_sock);
1822
1823 /* continue accepting connections */
1824 vty_event(VTY_SERV, accept_sock, NULL);
1825
1826 return 0;
1827 }
1828 }
1829
1830 /* VTY's ipv6 accesslist apply. */
1831 if (p.family == AF_INET6 && vty_ipv6_accesslist_name) {
1832 if ((acl = access_list_lookup(AFI_IP6,
1833 vty_ipv6_accesslist_name))
1834 && (access_list_apply(acl, &p) == FILTER_DENY)) {
1835 zlog_info("Vty connection refused from %s",
1836 sockunion2str(&su, buf, SU_ADDRSTRLEN));
1837 close(vty_sock);
1838
1839 /* continue accepting connections */
1840 vty_event(VTY_SERV, accept_sock, NULL);
1841
1842 return 0;
1843 }
1844 }
1845
1846 on = 1;
1847 ret = setsockopt(vty_sock, IPPROTO_TCP, TCP_NODELAY, (char *)&on,
1848 sizeof(on));
1849 if (ret < 0)
1850 zlog_info("can't set sockopt to vty_sock : %s",
1851 safe_strerror(errno));
1852
1853 zlog_info("Vty connection from %s",
1854 sockunion2str(&su, buf, SU_ADDRSTRLEN));
1855
1856 vty_create(vty_sock, &su);
1857
1858 return 0;
1859}
1860
1861static void vty_serv_sock_addrinfo(const char *hostname, unsigned short port)
1862{
1863 int ret;
1864 struct addrinfo req;
1865 struct addrinfo *ainfo;
1866 struct addrinfo *ainfo_save;
1867 int sock;
1868 char port_str[BUFSIZ];
1869
1870 memset(&req, 0, sizeof(struct addrinfo));
1871 req.ai_flags = AI_PASSIVE;
1872 req.ai_family = AF_UNSPEC;
1873 req.ai_socktype = SOCK_STREAM;
772270f3 1874 snprintf(port_str, sizeof(port_str), "%d", port);
d62a17ae 1875 port_str[sizeof(port_str) - 1] = '\0';
1876
1877 ret = getaddrinfo(hostname, port_str, &req, &ainfo);
1878
1879 if (ret != 0) {
450971aa 1880 flog_err_sys(EC_LIB_SYSTEM_CALL, "getaddrinfo failed: %s",
09c866e3 1881 gai_strerror(ret));
d62a17ae 1882 exit(1);
1883 }
1884
1885 ainfo_save = ainfo;
1886
1887 do {
1888 if (ainfo->ai_family != AF_INET && ainfo->ai_family != AF_INET6)
1889 continue;
1890
1891 sock = socket(ainfo->ai_family, ainfo->ai_socktype,
1892 ainfo->ai_protocol);
1893 if (sock < 0)
1894 continue;
718e3744 1895
d62a17ae 1896 sockopt_v6only(ainfo->ai_family, sock);
1897 sockopt_reuseaddr(sock);
1898 sockopt_reuseport(sock);
1899 set_cloexec(sock);
1900
1901 ret = bind(sock, ainfo->ai_addr, ainfo->ai_addrlen);
1902 if (ret < 0) {
1903 close(sock); /* Avoid sd leak. */
1904 continue;
1905 }
1906
1907 ret = listen(sock, 3);
1908 if (ret < 0) {
1909 close(sock); /* Avoid sd leak. */
1910 continue;
1911 }
1912
1913 vty_event(VTY_SERV, sock, NULL);
1914 } while ((ainfo = ainfo->ai_next) != NULL);
1915
1916 freeaddrinfo(ainfo_save);
718e3744 1917}
718e3744 1918
1919#ifdef VTYSH
1920/* For sockaddr_un. */
1921#include <sys/un.h>
1922
1923/* VTY shell UNIX domain socket. */
d62a17ae 1924static void vty_serv_un(const char *path)
1925{
1926 int ret;
1927 int sock, len;
1928 struct sockaddr_un serv;
1929 mode_t old_mask;
1930 struct zprivs_ids_t ids;
1931
1932 /* First of all, unlink existing socket */
1933 unlink(path);
1934
1935 /* Set umask */
1936 old_mask = umask(0007);
1937
1938 /* Make UNIX domain socket. */
1939 sock = socket(AF_UNIX, SOCK_STREAM, 0);
1940 if (sock < 0) {
450971aa 1941 flog_err_sys(EC_LIB_SOCKET,
09c866e3
QY
1942 "Cannot create unix stream socket: %s",
1943 safe_strerror(errno));
d62a17ae 1944 return;
1945 }
1946
1947 /* Make server socket. */
1948 memset(&serv, 0, sizeof(struct sockaddr_un));
1949 serv.sun_family = AF_UNIX;
1950 strlcpy(serv.sun_path, path, sizeof(serv.sun_path));
6f0e3f6e 1951#ifdef HAVE_STRUCT_SOCKADDR_UN_SUN_LEN
d62a17ae 1952 len = serv.sun_len = SUN_LEN(&serv);
718e3744 1953#else
d62a17ae 1954 len = sizeof(serv.sun_family) + strlen(serv.sun_path);
6f0e3f6e 1955#endif /* HAVE_STRUCT_SOCKADDR_UN_SUN_LEN */
718e3744 1956
d62a17ae 1957 set_cloexec(sock);
2da59394 1958
d62a17ae 1959 ret = bind(sock, (struct sockaddr *)&serv, len);
1960 if (ret < 0) {
450971aa 1961 flog_err_sys(EC_LIB_SOCKET, "Cannot bind path %s: %s", path,
09c866e3 1962 safe_strerror(errno));
d62a17ae 1963 close(sock); /* Avoid sd leak. */
1964 return;
1965 }
718e3744 1966
d62a17ae 1967 ret = listen(sock, 5);
1968 if (ret < 0) {
450971aa 1969 flog_err_sys(EC_LIB_SOCKET, "listen(fd %d) failed: %s", sock,
09c866e3 1970 safe_strerror(errno));
d62a17ae 1971 close(sock); /* Avoid sd leak. */
1972 return;
1973 }
718e3744 1974
d62a17ae 1975 umask(old_mask);
718e3744 1976
d62a17ae 1977 zprivs_get_ids(&ids);
d0bfb22c 1978
d62a17ae 1979 /* Hack: ids.gid_vty is actually a uint, but we stored -1 in it
1980 earlier for the case when we don't need to chown the file
1981 type casting it here to make a compare */
1982 if ((int)ids.gid_vty > 0) {
1983 /* set group of socket */
1984 if (chown(path, -1, ids.gid_vty)) {
450971aa 1985 flog_err_sys(EC_LIB_SYSTEM_CALL,
09c866e3
QY
1986 "vty_serv_un: could chown socket, %s",
1987 safe_strerror(errno));
d62a17ae 1988 }
1989 }
edd7c245 1990
d62a17ae 1991 vty_event(VTYSH_SERV, sock, NULL);
718e3744 1992}
1993
1994/* #define VTYSH_DEBUG 1 */
1995
d62a17ae 1996static int vtysh_accept(struct thread *thread)
718e3744 1997{
d62a17ae 1998 int accept_sock;
1999 int sock;
2000 int client_len;
2001 struct sockaddr_un client;
2002 struct vty *vty;
d0bfb22c 2003
d62a17ae 2004 accept_sock = THREAD_FD(thread);
718e3744 2005
d62a17ae 2006 vty_event(VTYSH_SERV, accept_sock, NULL);
718e3744 2007
d62a17ae 2008 memset(&client, 0, sizeof(struct sockaddr_un));
2009 client_len = sizeof(struct sockaddr_un);
718e3744 2010
d62a17ae 2011 sock = accept(accept_sock, (struct sockaddr *)&client,
2012 (socklen_t *)&client_len);
718e3744 2013
d62a17ae 2014 if (sock < 0) {
450971aa 2015 flog_err(EC_LIB_SOCKET, "can't accept vty socket : %s",
34699016 2016 safe_strerror(errno));
d62a17ae 2017 return -1;
2018 }
718e3744 2019
d62a17ae 2020 if (set_nonblocking(sock) < 0) {
34699016 2021 flog_err(
450971aa 2022 EC_LIB_SOCKET,
34699016 2023 "vtysh_accept: could not set vty socket %d to non-blocking, %s, closing",
d62a17ae 2024 sock, safe_strerror(errno));
2025 close(sock);
2026 return -1;
2027 }
2028 set_cloexec(sock);
2da59394 2029
718e3744 2030#ifdef VTYSH_DEBUG
d62a17ae 2031 printf("VTY shell accept\n");
718e3744 2032#endif /* VTYSH_DEBUG */
2033
d62a17ae 2034 vty = vty_new();
2035 vty->fd = sock;
2036 vty->wfd = sock;
2037 vty->type = VTY_SHELL_SERV;
2038 vty->node = VIEW_NODE;
2039
2040 vty_event(VTYSH_READ, sock, vty);
2041
2042 return 0;
2043}
2044
2045static int vtysh_flush(struct vty *vty)
2046{
2047 switch (buffer_flush_available(vty->obuf, vty->wfd)) {
2048 case BUFFER_PENDING:
2049 vty_event(VTYSH_WRITE, vty->wfd, vty);
2050 break;
2051 case BUFFER_ERROR:
2052 vty->monitor =
2053 0; /* disable monitoring to avoid infinite recursion */
450971aa 2054 flog_err(EC_LIB_SOCKET, "%s: write error to fd %d, closing",
34699016 2055 __func__, vty->fd);
0b42d81a 2056 buffer_reset(vty->lbuf);
d62a17ae 2057 buffer_reset(vty->obuf);
2058 vty_close(vty);
2059 return -1;
d62a17ae 2060 case BUFFER_EMPTY:
2061 break;
2062 }
2063 return 0;
2064}
2065
2066static int vtysh_read(struct thread *thread)
2067{
2068 int ret;
2069 int sock;
2070 int nbytes;
2071 struct vty *vty;
2072 unsigned char buf[VTY_READ_BUFSIZ];
2073 unsigned char *p;
d7c0a89a 2074 uint8_t header[4] = {0, 0, 0, 0};
d62a17ae 2075
2076 sock = THREAD_FD(thread);
2077 vty = THREAD_ARG(thread);
d62a17ae 2078
2079 if ((nbytes = read(sock, buf, VTY_READ_BUFSIZ)) <= 0) {
2080 if (nbytes < 0) {
2081 if (ERRNO_IO_RETRY(errno)) {
2082 vty_event(VTYSH_READ, sock, vty);
2083 return 0;
2084 }
2085 vty->monitor = 0; /* disable monitoring to avoid
2086 infinite recursion */
34699016 2087 flog_err(
450971aa 2088 EC_LIB_SOCKET,
d62a17ae 2089 "%s: read failed on vtysh client fd %d, closing: %s",
2090 __func__, sock, safe_strerror(errno));
2091 }
0b42d81a 2092 buffer_reset(vty->lbuf);
d62a17ae 2093 buffer_reset(vty->obuf);
2094 vty_close(vty);
718e3744 2095#ifdef VTYSH_DEBUG
d62a17ae 2096 printf("close vtysh\n");
718e3744 2097#endif /* VTYSH_DEBUG */
d62a17ae 2098 return 0;
2099 }
718e3744 2100
2101#ifdef VTYSH_DEBUG
d62a17ae 2102 printf("line: %.*s\n", nbytes, buf);
718e3744 2103#endif /* VTYSH_DEBUG */
2104
d62a17ae 2105 if (vty->length + nbytes >= VTY_BUFSIZ) {
2106 /* Clear command line buffer. */
2107 vty->cp = vty->length = 0;
2108 vty_clear_buf(vty);
2109 vty_out(vty, "%% Command is too long.\n");
2110 } else {
2111 for (p = buf; p < buf + nbytes; p++) {
2112 vty->buf[vty->length++] = *p;
2113 if (*p == '\0') {
2114 /* Pass this line to parser. */
2115 ret = vty_execute(vty);
2116/* Note that vty_execute clears the command buffer and resets
2117 vty->length to 0. */
2118
2119/* Return result. */
718e3744 2120#ifdef VTYSH_DEBUG
d62a17ae 2121 printf("result: %d\n", ret);
2122 printf("vtysh node: %d\n", vty->node);
718e3744 2123#endif /* VTYSH_DEBUG */
2124
d62a17ae 2125 /* hack for asynchronous "write integrated"
2126 * - other commands in "buf" will be ditched
2127 * - input during pending config-write is
2128 * "unsupported" */
2129 if (ret == CMD_SUSPEND)
2130 break;
95c4aff2 2131
d62a17ae 2132 /* warning: watchfrr hardcodes this result write
2133 */
2134 header[3] = ret;
2135 buffer_put(vty->obuf, header, 4);
9fc7ebf1 2136
d62a17ae 2137 if (!vty->t_write && (vtysh_flush(vty) < 0))
2138 /* Try to flush results; exit if a write
2139 * error occurs. */
2140 return 0;
2141 }
2142 }
2143 }
718e3744 2144
d62a17ae 2145 if (vty->status == VTY_CLOSE)
2146 vty_close(vty);
2147 else
2148 vty_event(VTYSH_READ, sock, vty);
718e3744 2149
d62a17ae 2150 return 0;
718e3744 2151}
49ff6d9d 2152
d62a17ae 2153static int vtysh_write(struct thread *thread)
49ff6d9d 2154{
d62a17ae 2155 struct vty *vty = THREAD_ARG(thread);
49ff6d9d 2156
d62a17ae 2157 vtysh_flush(vty);
2158 return 0;
49ff6d9d 2159}
2160
718e3744 2161#endif /* VTYSH */
2162
2163/* Determine address family to bind. */
d62a17ae 2164void vty_serv_sock(const char *addr, unsigned short port, const char *path)
718e3744 2165{
d62a17ae 2166 /* If port is set to 0, do not listen on TCP/IP at all! */
2167 if (port)
2168 vty_serv_sock_addrinfo(addr, port);
718e3744 2169
2170#ifdef VTYSH
d62a17ae 2171 vty_serv_un(path);
718e3744 2172#endif /* VTYSH */
2173}
2174
7ab57d19
DS
2175static void vty_error_delete(void *arg)
2176{
2177 struct vty_error *ve = arg;
2178
2179 XFREE(MTYPE_TMP, ve);
2180}
2181
9d0a3260
AS
2182/* Close vty interface. Warning: call this only from functions that
2183 will be careful not to access the vty afterwards (since it has
2184 now been freed). This is safest from top-level functions (called
2185 directly by the thread dispatcher). */
d62a17ae 2186void vty_close(struct vty *vty)
718e3744 2187{
d62a17ae 2188 int i;
2189 bool was_stdio = false;
718e3744 2190
791ded4a
DL
2191 /* Drop out of configure / transaction if needed. */
2192 vty_config_exit(vty);
2193
d62a17ae 2194 /* Cancel threads.*/
43b8ca99
DS
2195 THREAD_OFF(vty->t_read);
2196 THREAD_OFF(vty->t_write);
2197 THREAD_OFF(vty->t_timeout);
718e3744 2198
d62a17ae 2199 /* Flush buffer. */
2200 buffer_flush_all(vty->obuf, vty->wfd);
718e3744 2201
d62a17ae 2202 /* Free input buffer. */
2203 buffer_free(vty->obuf);
0b42d81a 2204 buffer_free(vty->lbuf);
718e3744 2205
d62a17ae 2206 /* Free command history. */
0a22ddfb
QY
2207 for (i = 0; i < VTY_MAXHIST; i++) {
2208 XFREE(MTYPE_VTY_HIST, vty->hist[i]);
2209 }
718e3744 2210
d62a17ae 2211 /* Unset vector. */
10b8a9c0
DL
2212 if (vty->fd != -1)
2213 vector_unset(vtyvec, vty->fd);
718e3744 2214
d62a17ae 2215 if (vty->wfd > 0 && vty->type == VTY_FILE)
2216 fsync(vty->wfd);
056cfe49 2217
10b8a9c0
DL
2218 /* Close socket.
2219 * note check is for fd > STDERR_FILENO, not fd != -1.
2220 * We never close stdin/stdout/stderr here, because we may be
2221 * running in foreground mode with logging to stdout. Also,
2222 * additionally, we'd need to replace these fds with /dev/null. */
2223 if (vty->wfd > STDERR_FILENO && vty->wfd != vty->fd)
2224 close(vty->wfd);
572e2644 2225 if (vty->fd > STDERR_FILENO)
d62a17ae 2226 close(vty->fd);
572e2644 2227 if (vty->fd == STDIN_FILENO)
d62a17ae 2228 was_stdio = true;
718e3744 2229
0a22ddfb 2230 XFREE(MTYPE_VTY, vty->buf);
718e3744 2231
7ab57d19
DS
2232 if (vty->error) {
2233 vty->error->del = vty_error_delete;
2234 list_delete(&vty->error);
2235 }
5689fe5f 2236
d62a17ae 2237 /* OK free vty. */
2238 XFREE(MTYPE_VTY, vty);
dd03f8ca 2239
d62a17ae 2240 if (was_stdio)
154b9e8f 2241 vty_stdio_reset(0);
718e3744 2242}
2243
2244/* When time out occur output message then close connection. */
d62a17ae 2245static int vty_timeout(struct thread *thread)
718e3744 2246{
d62a17ae 2247 struct vty *vty;
718e3744 2248
d62a17ae 2249 vty = THREAD_ARG(thread);
d62a17ae 2250 vty->v_timeout = 0;
718e3744 2251
d62a17ae 2252 /* Clear buffer*/
0b42d81a 2253 buffer_reset(vty->lbuf);
d62a17ae 2254 buffer_reset(vty->obuf);
2255 vty_out(vty, "\nVty connection is timed out.\n");
718e3744 2256
d62a17ae 2257 /* Close connection. */
2258 vty->status = VTY_CLOSE;
2259 vty_close(vty);
718e3744 2260
d62a17ae 2261 return 0;
718e3744 2262}
2263
2264/* Read up configuration file from file_name. */
1c2facd1 2265static void vty_read_file(struct nb_config *config, FILE *confp)
d62a17ae 2266{
2267 int ret;
2268 struct vty *vty;
7ab57d19
DS
2269 struct vty_error *ve;
2270 struct listnode *node;
d62a17ae 2271 unsigned int line_num = 0;
2272
2273 vty = vty_new();
10b8a9c0
DL
2274 /* vty_close won't close stderr; if some config command prints
2275 * something it'll end up there. (not ideal; it'd be beter if output
2276 * from a file-load went to logging instead. Also note that if this
2277 * function is called after daemonizing, stderr will be /dev/null.)
2278 *
2279 * vty->fd will be -1 from vty_new()
2280 */
2281 vty->wfd = STDERR_FILENO;
d62a17ae 2282 vty->type = VTY_FILE;
2283 vty->node = CONFIG_NODE;
eaf6705d 2284 vty->config = true;
1c2facd1
RW
2285 if (config)
2286 vty->candidate_config = config;
2287 else {
2288 vty->private_config = true;
2289 vty->candidate_config = nb_config_new(NULL);
2290 }
d62a17ae 2291
2292 /* Execute configuration file */
2293 ret = config_from_file(vty, confp, &line_num);
2294
2295 /* Flush any previous errors before printing messages below */
10b8a9c0 2296 buffer_flush_all(vty->obuf, vty->wfd);
d62a17ae 2297
2298 if (!((ret == CMD_SUCCESS) || (ret == CMD_ERR_NOTHING_TODO))) {
2299 const char *message = NULL;
b4fa7c95
DL
2300 char *nl;
2301
d62a17ae 2302 switch (ret) {
2303 case CMD_ERR_AMBIGUOUS:
b4fa7c95 2304 message = "Ambiguous command";
d62a17ae 2305 break;
2306 case CMD_ERR_NO_MATCH:
b4fa7c95 2307 message = "No such command";
d62a17ae 2308 break;
c539c389
DS
2309 case CMD_WARNING:
2310 message = "Command returned Warning";
2311 break;
2312 case CMD_WARNING_CONFIG_FAILED:
2313 message = "Command returned Warning Config Failed";
2314 break;
2315 case CMD_ERR_INCOMPLETE:
2316 message = "Command returned Incomplete";
2317 break;
2318 case CMD_ERR_EXEED_ARGC_MAX:
996c9314
LB
2319 message =
2320 "Command exceeded maximum number of Arguments";
c539c389
DS
2321 break;
2322 default:
2323 message = "Command returned unhandled error message";
2324 break;
d62a17ae 2325 }
b4fa7c95 2326
7ab57d19
DS
2327 for (ALL_LIST_ELEMENTS_RO(vty->error, node, ve)) {
2328 nl = strchr(ve->error_buf, '\n');
2329 if (nl)
2330 *nl = '\0';
2331 flog_err(EC_LIB_VTY, "ERROR: %s on config line %u: %s",
2332 message, ve->line_num, ve->error_buf);
2333 }
d62a17ae 2334 }
2335
1c2facd1
RW
2336 /*
2337 * Automatically commit the candidate configuration after
2338 * reading the configuration file.
2339 */
91f9fd78 2340 if (config == NULL) {
13d6b9c1 2341 struct nb_context context = {};
df5eda3d 2342 char errmsg[BUFSIZ] = {0};
13d6b9c1
RW
2343
2344 context.client = NB_CLIENT_CLI;
2345 context.user = vty;
2346 ret = nb_candidate_commit(&context, vty->candidate_config, true,
df5eda3d
RW
2347 "Read configuration file", NULL,
2348 errmsg, sizeof(errmsg));
1c2facd1 2349 if (ret != NB_OK && ret != NB_ERR_NO_CHANGES)
df5eda3d
RW
2350 zlog_err(
2351 "%s: failed to read configuration file: %s (%s)",
2352 __func__, nb_err_name(ret), errmsg);
1c2facd1
RW
2353 }
2354
d62a17ae 2355 vty_close(vty);
2356}
2357
2358static FILE *vty_use_backup_config(const char *fullpath)
2359{
2360 char *fullpath_sav, *fullpath_tmp;
2361 FILE *ret = NULL;
2362 int tmp, sav;
2363 int c;
2364 char buffer[512];
2365
9f73d2c9
QY
2366 size_t fullpath_sav_sz = strlen(fullpath) + strlen(CONF_BACKUP_EXT) + 1;
2367 fullpath_sav = malloc(fullpath_sav_sz);
2368 strlcpy(fullpath_sav, fullpath, fullpath_sav_sz);
2369 strlcat(fullpath_sav, CONF_BACKUP_EXT, fullpath_sav_sz);
d62a17ae 2370
2371 sav = open(fullpath_sav, O_RDONLY);
2372 if (sav < 0) {
2373 free(fullpath_sav);
2374 return NULL;
2375 }
2376
2377 fullpath_tmp = malloc(strlen(fullpath) + 8);
fc746f1c 2378 snprintf(fullpath_tmp, strlen(fullpath) + 8, "%s.XXXXXX", fullpath);
d62a17ae 2379
2380 /* Open file to configuration write. */
2381 tmp = mkstemp(fullpath_tmp);
2382 if (tmp < 0)
2383 goto out_close_sav;
2384
2385 if (fchmod(tmp, CONFIGFILE_MASK) != 0)
2386 goto out_close;
2387
2388 while ((c = read(sav, buffer, 512)) > 0) {
2389 if (write(tmp, buffer, c) <= 0)
2390 goto out_close;
2391 }
2392 close(sav);
2393 close(tmp);
2394
2395 if (rename(fullpath_tmp, fullpath) == 0)
2396 ret = fopen(fullpath, "r");
2397 else
2398 unlink(fullpath_tmp);
2399
2400 if (0) {
2401 out_close:
2402 close(tmp);
2403 unlink(fullpath_tmp);
2404 out_close_sav:
2405 close(sav);
2406 }
2407
2408 free(fullpath_sav);
2409 free(fullpath_tmp);
2410 return ret;
718e3744 2411}
2412
2413/* Read up configuration file from file_name. */
1c2facd1
RW
2414bool vty_read_config(struct nb_config *config, const char *config_file,
2415 char *config_default_dir)
d62a17ae 2416{
2417 char cwd[MAXPATHLEN];
2418 FILE *confp = NULL;
2419 const char *fullpath;
2420 char *tmp = NULL;
5ede5e4e 2421 bool read_success = false;
d62a17ae 2422
2423 /* If -f flag specified. */
2424 if (config_file != NULL) {
2425 if (!IS_DIRECTORY_SEP(config_file[0])) {
2426 if (getcwd(cwd, MAXPATHLEN) == NULL) {
09c866e3 2427 flog_err_sys(
450971aa 2428 EC_LIB_SYSTEM_CALL,
1c2facd1
RW
2429 "%s: failure to determine Current Working Directory %d!",
2430 __func__, errno);
2431 goto tmp_free_and_out;
d62a17ae 2432 }
2433 tmp = XMALLOC(MTYPE_TMP,
2434 strlen(cwd) + strlen(config_file) + 2);
2435 sprintf(tmp, "%s/%s", cwd, config_file);
2436 fullpath = tmp;
2437 } else
2438 fullpath = config_file;
2439
2440 confp = fopen(fullpath, "r");
2441
2442 if (confp == NULL) {
34699016 2443 flog_warn(
450971aa 2444 EC_LIB_BACKUP_CONFIG,
34699016
DS
2445 "%s: failed to open configuration file %s: %s, checking backup",
2446 __func__, fullpath, safe_strerror(errno));
d62a17ae 2447
2448 confp = vty_use_backup_config(fullpath);
2449 if (confp)
34699016 2450 flog_warn(
450971aa 2451 EC_LIB_BACKUP_CONFIG,
996c9314 2452 "WARNING: using backup configuration file!");
d62a17ae 2453 else {
1c2facd1
RW
2454 flog_err(
2455 EC_LIB_VTY,
2456 "%s: can't open configuration file [%s]",
2457 __func__, config_file);
2458 goto tmp_free_and_out;
d62a17ae 2459 }
2460 }
2461 } else {
2462
2463 host_config_set(config_default_dir);
a7222276 2464
718e3744 2465#ifdef VTYSH
d62a17ae 2466 int ret;
2467 struct stat conf_stat;
2468
2469 /* !!!!PLEASE LEAVE!!!!
2470 * This is NEEDED for use with vtysh -b, or else you can get
2471 * a real configuration food fight with a lot garbage in the
2472 * merged configuration file it creates coming from the per
2473 * daemon configuration files. This also allows the daemons
2474 * to start if there default configuration file is not
2475 * present or ignore them, as needed when using vtysh -b to
2476 * configure the daemons at boot - MAG
2477 */
2478
2479 /* Stat for vtysh Zebra.conf, if found startup and wait for
2480 * boot configuration
2481 */
2482
2483 if (strstr(config_default_dir, "vtysh") == NULL) {
2484 ret = stat(integrate_default, &conf_stat);
5ede5e4e
DS
2485 if (ret >= 0) {
2486 read_success = true;
d62a17ae 2487 goto tmp_free_and_out;
5ede5e4e 2488 }
d62a17ae 2489 }
a7222276 2490#endif /* VTYSH */
d62a17ae 2491 confp = fopen(config_default_dir, "r");
2492 if (confp == NULL) {
34699016 2493 flog_err(
450971aa 2494 EC_LIB_SYSTEM_CALL,
34699016
DS
2495 "%s: failed to open configuration file %s: %s, checking backup",
2496 __func__, config_default_dir,
2497 safe_strerror(errno));
d62a17ae 2498
2499 confp = vty_use_backup_config(config_default_dir);
2500 if (confp) {
34699016 2501 flog_warn(
450971aa 2502 EC_LIB_BACKUP_CONFIG,
996c9314 2503 "WARNING: 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,
2631 "WARNING: exiting with a pending confirmed commit. Rolling back to previous configuration.\n\n");
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
d62a17ae 2655static void vty_event(enum event event, int sock, struct vty *vty)
718e3744 2656{
d62a17ae 2657 struct thread *vty_serv_thread = NULL;
d8182598 2658
d62a17ae 2659 switch (event) {
2660 case VTY_SERV:
2661 vty_serv_thread = thread_add_read(vty_master, vty_accept, vty,
2662 sock, NULL);
2663 vector_set_index(Vvty_serv_thread, sock, vty_serv_thread);
2664 break;
718e3744 2665#ifdef VTYSH
d62a17ae 2666 case VTYSH_SERV:
2667 vty_serv_thread = thread_add_read(vty_master, vtysh_accept, vty,
2668 sock, NULL);
2669 vector_set_index(Vvty_serv_thread, sock, vty_serv_thread);
2670 break;
2671 case VTYSH_READ:
d62a17ae 2672 thread_add_read(vty_master, vtysh_read, vty, sock,
2673 &vty->t_read);
2674 break;
2675 case VTYSH_WRITE:
d62a17ae 2676 thread_add_write(vty_master, vtysh_write, vty, sock,
2677 &vty->t_write);
2678 break;
718e3744 2679#endif /* VTYSH */
d62a17ae 2680 case VTY_READ:
d62a17ae 2681 thread_add_read(vty_master, vty_read, vty, sock, &vty->t_read);
2682
2683 /* Time out treatment. */
2684 if (vty->v_timeout) {
43b8ca99 2685 THREAD_OFF(vty->t_timeout);
d62a17ae 2686 thread_add_timer(vty_master, vty_timeout, vty,
2687 vty->v_timeout, &vty->t_timeout);
2688 }
2689 break;
2690 case VTY_WRITE:
2691 thread_add_write(vty_master, vty_flush, vty, sock,
2692 &vty->t_write);
2693 break;
2694 case VTY_TIMEOUT_RESET:
43b8ca99
DS
2695 THREAD_OFF(vty->t_timeout);
2696 if (vty->v_timeout)
d62a17ae 2697 thread_add_timer(vty_master, vty_timeout, vty,
2698 vty->v_timeout, &vty->t_timeout);
d62a17ae 2699 break;
2700 }
718e3744 2701}
6b0655a2 2702
505e5056 2703DEFUN_NOSH (config_who,
718e3744 2704 config_who_cmd,
2705 "who",
2706 "Display who is on vty\n")
2707{
d62a17ae 2708 unsigned int i;
2709 struct vty *v;
718e3744 2710
d62a17ae 2711 for (i = 0; i < vector_active(vtyvec); i++)
2712 if ((v = vector_slot(vtyvec, i)) != NULL)
2713 vty_out(vty, "%svty[%d] connected from %s.\n",
2714 v->config ? "*" : " ", i, v->address);
2715 return CMD_SUCCESS;
718e3744 2716}
2717
2718/* Move to vty configuration mode. */
505e5056 2719DEFUN_NOSH (line_vty,
718e3744 2720 line_vty_cmd,
2721 "line vty",
2722 "Configure a terminal line\n"
2723 "Virtual terminal\n")
2724{
d62a17ae 2725 vty->node = VTY_NODE;
2726 return CMD_SUCCESS;
718e3744 2727}
2728
2729/* Set time out value. */
d62a17ae 2730static int exec_timeout(struct vty *vty, const char *min_str,
2731 const char *sec_str)
718e3744 2732{
d62a17ae 2733 unsigned long timeout = 0;
718e3744 2734
d62a17ae 2735 /* min_str and sec_str are already checked by parser. So it must be
2736 all digit string. */
2737 if (min_str) {
2738 timeout = strtol(min_str, NULL, 10);
2739 timeout *= 60;
2740 }
2741 if (sec_str)
2742 timeout += strtol(sec_str, NULL, 10);
718e3744 2743
d62a17ae 2744 vty_timeout_val = timeout;
2745 vty->v_timeout = timeout;
2746 vty_event(VTY_TIMEOUT_RESET, 0, vty);
718e3744 2747
2748
d62a17ae 2749 return CMD_SUCCESS;
718e3744 2750}
2751
2752DEFUN (exec_timeout_min,
2753 exec_timeout_min_cmd,
aa1c90a4 2754 "exec-timeout (0-35791)",
718e3744 2755 "Set timeout value\n"
2756 "Timeout value in minutes\n")
2757{
d62a17ae 2758 int idx_number = 1;
2759 return exec_timeout(vty, argv[idx_number]->arg, NULL);
718e3744 2760}
2761
2762DEFUN (exec_timeout_sec,
2763 exec_timeout_sec_cmd,
aa1c90a4 2764 "exec-timeout (0-35791) (0-2147483)",
718e3744 2765 "Set the EXEC timeout\n"
2766 "Timeout in minutes\n"
2767 "Timeout in seconds\n")
2768{
d62a17ae 2769 int idx_number = 1;
2770 int idx_number_2 = 2;
2771 return exec_timeout(vty, argv[idx_number]->arg,
2772 argv[idx_number_2]->arg);
718e3744 2773}
2774
2775DEFUN (no_exec_timeout,
2776 no_exec_timeout_cmd,
2777 "no exec-timeout",
2778 NO_STR
2779 "Set the EXEC timeout\n")
2780{
d62a17ae 2781 return exec_timeout(vty, NULL, NULL);
718e3744 2782}
2783
2784/* Set vty access class. */
2785DEFUN (vty_access_class,
2786 vty_access_class_cmd,
2787 "access-class WORD",
2788 "Filter connections based on an IP access list\n"
2789 "IP access list\n")
2790{
d62a17ae 2791 int idx_word = 1;
2792 if (vty_accesslist_name)
2793 XFREE(MTYPE_VTY, vty_accesslist_name);
718e3744 2794
d62a17ae 2795 vty_accesslist_name = XSTRDUP(MTYPE_VTY, argv[idx_word]->arg);
718e3744 2796
d62a17ae 2797 return CMD_SUCCESS;
718e3744 2798}
2799
2800/* Clear vty access class. */
2801DEFUN (no_vty_access_class,
2802 no_vty_access_class_cmd,
2803 "no access-class [WORD]",
2804 NO_STR
2805 "Filter connections based on an IP access list\n"
2806 "IP access list\n")
2807{
d62a17ae 2808 int idx_word = 2;
2809 const char *accesslist = (argc == 3) ? argv[idx_word]->arg : NULL;
2810 if (!vty_accesslist_name
2811 || (argc == 3 && strcmp(vty_accesslist_name, accesslist))) {
2812 vty_out(vty, "Access-class is not currently applied to vty\n");
2813 return CMD_WARNING_CONFIG_FAILED;
2814 }
718e3744 2815
d62a17ae 2816 XFREE(MTYPE_VTY, vty_accesslist_name);
718e3744 2817
d62a17ae 2818 vty_accesslist_name = NULL;
718e3744 2819
d62a17ae 2820 return CMD_SUCCESS;
718e3744 2821}
2822
718e3744 2823/* Set vty access class. */
2824DEFUN (vty_ipv6_access_class,
2825 vty_ipv6_access_class_cmd,
2826 "ipv6 access-class WORD",
2827 IPV6_STR
2828 "Filter connections based on an IP access list\n"
2829 "IPv6 access list\n")
2830{
d62a17ae 2831 int idx_word = 2;
2832 if (vty_ipv6_accesslist_name)
2833 XFREE(MTYPE_VTY, vty_ipv6_accesslist_name);
718e3744 2834
d62a17ae 2835 vty_ipv6_accesslist_name = XSTRDUP(MTYPE_VTY, argv[idx_word]->arg);
718e3744 2836
d62a17ae 2837 return CMD_SUCCESS;
718e3744 2838}
2839
2840/* Clear vty access class. */
2841DEFUN (no_vty_ipv6_access_class,
2842 no_vty_ipv6_access_class_cmd,
2843 "no ipv6 access-class [WORD]",
2844 NO_STR
2845 IPV6_STR
2846 "Filter connections based on an IP access list\n"
2847 "IPv6 access list\n")
2848{
d62a17ae 2849 int idx_word = 3;
2850 const char *accesslist = (argc == 4) ? argv[idx_word]->arg : NULL;
aa1c90a4 2851
d62a17ae 2852 if (!vty_ipv6_accesslist_name
2853 || (argc == 4 && strcmp(vty_ipv6_accesslist_name, accesslist))) {
2854 vty_out(vty,
2855 "IPv6 access-class is not currently applied to vty\n");
2856 return CMD_WARNING_CONFIG_FAILED;
2857 }
718e3744 2858
d62a17ae 2859 XFREE(MTYPE_VTY, vty_ipv6_accesslist_name);
718e3744 2860
d62a17ae 2861 vty_ipv6_accesslist_name = NULL;
718e3744 2862
d62a17ae 2863 return CMD_SUCCESS;
718e3744 2864}
718e3744 2865
2866/* vty login. */
2867DEFUN (vty_login,
2868 vty_login_cmd,
2869 "login",
2870 "Enable password checking\n")
2871{
d62a17ae 2872 no_password_check = 0;
2873 return CMD_SUCCESS;
718e3744 2874}
2875
2876DEFUN (no_vty_login,
2877 no_vty_login_cmd,
2878 "no login",
2879 NO_STR
2880 "Enable password checking\n")
2881{
d62a17ae 2882 no_password_check = 1;
2883 return CMD_SUCCESS;
718e3744 2884}
2885
2886DEFUN (service_advanced_vty,
2887 service_advanced_vty_cmd,
2888 "service advanced-vty",
2889 "Set up miscellaneous service\n"
2890 "Enable advanced mode vty interface\n")
2891{
d62a17ae 2892 host.advanced = 1;
2893 return CMD_SUCCESS;
718e3744 2894}
2895
2896DEFUN (no_service_advanced_vty,
2897 no_service_advanced_vty_cmd,
2898 "no service advanced-vty",
2899 NO_STR
2900 "Set up miscellaneous service\n"
2901 "Enable advanced mode vty interface\n")
2902{
d62a17ae 2903 host.advanced = 0;
2904 return CMD_SUCCESS;
718e3744 2905}
2906
505e5056 2907DEFUN_NOSH (terminal_monitor,
718e3744 2908 terminal_monitor_cmd,
2909 "terminal monitor",
2910 "Set terminal line parameters\n"
2911 "Copy debug output to the current terminal line\n")
2912{
d62a17ae 2913 vty->monitor = 1;
2914 return CMD_SUCCESS;
718e3744 2915}
2916
505e5056 2917DEFUN_NOSH (terminal_no_monitor,
718e3744 2918 terminal_no_monitor_cmd,
2919 "terminal no monitor",
2920 "Set terminal line parameters\n"
2921 NO_STR
2922 "Copy debug output to the current terminal line\n")
2923{
d62a17ae 2924 vty->monitor = 0;
2925 return CMD_SUCCESS;
718e3744 2926}
2927
505e5056 2928DEFUN_NOSH (no_terminal_monitor,
789f78ac 2929 no_terminal_monitor_cmd,
2930 "no terminal monitor",
2931 NO_STR
2932 "Set terminal line parameters\n"
2933 "Copy debug output to the current terminal line\n")
f667a580 2934{
d62a17ae 2935 return terminal_no_monitor(self, vty, argc, argv);
f667a580
QY
2936}
2937
789f78ac 2938
505e5056 2939DEFUN_NOSH (show_history,
718e3744 2940 show_history_cmd,
2941 "show history",
2942 SHOW_STR
2943 "Display the session command history\n")
2944{
d62a17ae 2945 int index;
718e3744 2946
d62a17ae 2947 for (index = vty->hindex + 1; index != vty->hindex;) {
2948 if (index == VTY_MAXHIST) {
2949 index = 0;
2950 continue;
2951 }
718e3744 2952
d62a17ae 2953 if (vty->hist[index] != NULL)
2954 vty_out(vty, " %s\n", vty->hist[index]);
718e3744 2955
d62a17ae 2956 index++;
2957 }
718e3744 2958
d62a17ae 2959 return CMD_SUCCESS;
718e3744 2960}
2961
da688ecd 2962/* vty login. */
2950f5da 2963DEFPY (log_commands,
da688ecd 2964 log_commands_cmd,
2950f5da
DS
2965 "[no] log commands",
2966 NO_STR
da688ecd 2967 "Logging control\n"
2950f5da 2968 "Log all commands\n")
da688ecd 2969{
2950f5da
DS
2970 if (no) {
2971 if (do_log_commands_perm) {
2972 vty_out(vty,
2973 "Daemon started with permanent logging turned on for commands, ignoring\n");
2974 return CMD_WARNING;
2975 }
2976
2977 do_log_commands = false;
2978 } else
2979 do_log_commands = true;
2980
d62a17ae 2981 return CMD_SUCCESS;
da688ecd
LB
2982}
2983
718e3744 2984/* Display current configuration. */
d62a17ae 2985static int vty_config_write(struct vty *vty)
718e3744 2986{
d62a17ae 2987 vty_out(vty, "line vty\n");
718e3744 2988
d62a17ae 2989 if (vty_accesslist_name)
2990 vty_out(vty, " access-class %s\n", vty_accesslist_name);
718e3744 2991
d62a17ae 2992 if (vty_ipv6_accesslist_name)
2993 vty_out(vty, " ipv6 access-class %s\n",
2994 vty_ipv6_accesslist_name);
718e3744 2995
d62a17ae 2996 /* exec-timeout */
2997 if (vty_timeout_val != VTY_TIMEOUT_DEFAULT)
2998 vty_out(vty, " exec-timeout %ld %ld\n", vty_timeout_val / 60,
2999 vty_timeout_val % 60);
718e3744 3000
d62a17ae 3001 /* login */
3002 if (no_password_check)
3003 vty_out(vty, " no login\n");
da688ecd 3004
d62a17ae 3005 if (do_log_commands)
3006 vty_out(vty, "log commands\n");
d0bfb22c 3007
d62a17ae 3008 vty_out(vty, "!\n");
718e3744 3009
d62a17ae 3010 return CMD_SUCCESS;
718e3744 3011}
3012
612c2c15 3013static int vty_config_write(struct vty *vty);
d62a17ae 3014struct cmd_node vty_node = {
f4b8291f 3015 .name = "vty",
62b346ee 3016 .node = VTY_NODE,
24389580 3017 .parent_node = CONFIG_NODE,
62b346ee 3018 .prompt = "%s(config-line)# ",
612c2c15 3019 .config_write = vty_config_write,
718e3744 3020};
3021
3022/* Reset all VTY status. */
4d762f26 3023void vty_reset(void)
d62a17ae 3024{
3025 unsigned int i;
3026 struct vty *vty;
3027 struct thread *vty_serv_thread;
3028
3029 for (i = 0; i < vector_active(vtyvec); i++)
3030 if ((vty = vector_slot(vtyvec, i)) != NULL) {
0b42d81a 3031 buffer_reset(vty->lbuf);
d62a17ae 3032 buffer_reset(vty->obuf);
3033 vty->status = VTY_CLOSE;
3034 vty_close(vty);
3035 }
3036
3037 for (i = 0; i < vector_active(Vvty_serv_thread); i++)
3038 if ((vty_serv_thread = vector_slot(Vvty_serv_thread, i))
3039 != NULL) {
43b8ca99 3040 THREAD_OFF(vty_serv_thread);
d62a17ae 3041 vector_slot(Vvty_serv_thread, i) = NULL;
3042 close(i);
3043 }
3044
3045 vty_timeout_val = VTY_TIMEOUT_DEFAULT;
3046
e1b36e13
QY
3047 XFREE(MTYPE_VTY, vty_accesslist_name);
3048 XFREE(MTYPE_VTY, vty_ipv6_accesslist_name);
718e3744 3049}
3050
d62a17ae 3051static void vty_save_cwd(void)
718e3744 3052{
d62a17ae 3053 char *c;
79ad2798 3054
daeb97e9 3055 c = getcwd(vty_cwd, sizeof(vty_cwd));
718e3744 3056
d62a17ae 3057 if (!c) {
3058 /*
3059 * At this point if these go wrong, more than likely
3060 * the whole world is coming down around us
3061 * Hence not worrying about it too much.
3062 */
3063 if (!chdir(SYSCONFDIR)) {
450971aa 3064 flog_err_sys(EC_LIB_SYSTEM_CALL,
09c866e3
QY
3065 "Failure to chdir to %s, errno: %d",
3066 SYSCONFDIR, errno);
d62a17ae 3067 exit(-1);
3068 }
daeb97e9 3069 if (getcwd(vty_cwd, sizeof(vty_cwd)) == NULL) {
450971aa 3070 flog_err_sys(EC_LIB_SYSTEM_CALL,
09c866e3 3071 "Failure to getcwd, errno: %d", errno);
d62a17ae 3072 exit(-1);
3073 }
3074 }
718e3744 3075}
3076
4d762f26 3077char *vty_get_cwd(void)
718e3744 3078{
d62a17ae 3079 return vty_cwd;
718e3744 3080}
3081
d62a17ae 3082int vty_shell(struct vty *vty)
718e3744 3083{
d62a17ae 3084 return vty->type == VTY_SHELL ? 1 : 0;
718e3744 3085}
3086
d62a17ae 3087int vty_shell_serv(struct vty *vty)
718e3744 3088{
d62a17ae 3089 return vty->type == VTY_SHELL_SERV ? 1 : 0;
718e3744 3090}
3091
4d762f26 3092void vty_init_vtysh(void)
718e3744 3093{
d62a17ae 3094 vtyvec = vector_init(VECTOR_MIN_SIZE);
718e3744 3095}
3096
3097/* Install vty's own commands like `who' command. */
2950f5da 3098void vty_init(struct thread_master *master_thread, bool do_command_logging)
d62a17ae 3099{
3100 /* For further configuration read, preserve current directory. */
3101 vty_save_cwd();
3102
3103 vtyvec = vector_init(VECTOR_MIN_SIZE);
3104
3105 vty_master = master_thread;
3106
154b9e8f 3107 atexit(vty_stdio_atexit);
d62a17ae 3108
3109 /* Initilize server thread vector. */
3110 Vvty_serv_thread = vector_init(VECTOR_MIN_SIZE);
3111
3112 /* Install bgp top node. */
612c2c15 3113 install_node(&vty_node);
d62a17ae 3114
3115 install_element(VIEW_NODE, &config_who_cmd);
3116 install_element(VIEW_NODE, &show_history_cmd);
3117 install_element(CONFIG_NODE, &line_vty_cmd);
3118 install_element(CONFIG_NODE, &service_advanced_vty_cmd);
3119 install_element(CONFIG_NODE, &no_service_advanced_vty_cmd);
3120 install_element(CONFIG_NODE, &show_history_cmd);
3121 install_element(CONFIG_NODE, &log_commands_cmd);
2950f5da
DS
3122
3123 if (do_command_logging) {
3124 do_log_commands = true;
3125 do_log_commands_perm = true;
3126 }
3127
d62a17ae 3128 install_element(ENABLE_NODE, &terminal_monitor_cmd);
3129 install_element(ENABLE_NODE, &terminal_no_monitor_cmd);
3130 install_element(ENABLE_NODE, &no_terminal_monitor_cmd);
3131
3132 install_default(VTY_NODE);
3133 install_element(VTY_NODE, &exec_timeout_min_cmd);
3134 install_element(VTY_NODE, &exec_timeout_sec_cmd);
3135 install_element(VTY_NODE, &no_exec_timeout_cmd);
3136 install_element(VTY_NODE, &vty_access_class_cmd);
3137 install_element(VTY_NODE, &no_vty_access_class_cmd);
3138 install_element(VTY_NODE, &vty_login_cmd);
3139 install_element(VTY_NODE, &no_vty_login_cmd);
3140 install_element(VTY_NODE, &vty_ipv6_access_class_cmd);
3141 install_element(VTY_NODE, &no_vty_ipv6_access_class_cmd);
3142}
3143
3144void vty_terminate(void)
3145{
daeb97e9 3146 memset(vty_cwd, 0x00, sizeof(vty_cwd));
d62a17ae 3147
3148 if (vtyvec && Vvty_serv_thread) {
3149 vty_reset();
3150 vector_free(vtyvec);
3151 vector_free(Vvty_serv_thread);
3152 vtyvec = NULL;
3153 Vvty_serv_thread = NULL;
3154 }
228da428 3155}