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