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