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