]> git.proxmox.com Git - mirror_frr.git/blob - lib/command.c
zebra: Unlock the route node when sending route notifications
[mirror_frr.git] / lib / command.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * CLI backend interface.
4 *
5 * --
6 * Copyright (C) 2016 Cumulus Networks, Inc.
7 * Copyright (C) 1997, 98, 99 Kunihiro Ishiguro
8 * Copyright (C) 2013 by Open Source Routing.
9 * Copyright (C) 2013 by Internet Systems Consortium, Inc. ("ISC")
10 */
11
12 #include <zebra.h>
13 #include <lib/version.h>
14
15 #include "command.h"
16 #include "frrstr.h"
17 #include "memory.h"
18 #include "log.h"
19 #include "log_vty.h"
20 #include "frrevent.h"
21 #include "vector.h"
22 #include "linklist.h"
23 #include "vty.h"
24 #include "workqueue.h"
25 #include "vrf.h"
26 #include "command_match.h"
27 #include "command_graph.h"
28 #include "qobj.h"
29 #include "defaults.h"
30 #include "libfrr.h"
31 #include "jhash.h"
32 #include "hook.h"
33 #include "lib_errors.h"
34 #include "mgmt_be_client.h"
35 #include "mgmt_fe_client.h"
36 #include "northbound_cli.h"
37 #include "network.h"
38 #include "routemap.h"
39
40 #include "frrscript.h"
41
42 DEFINE_MTYPE_STATIC(LIB, HOST, "Host config");
43 DEFINE_MTYPE(LIB, COMPLETION, "Completion item");
44
45 #define item(x) \
46 { \
47 x, #x \
48 }
49
50 /* clang-format off */
51 const struct message tokennames[] = {
52 item(WORD_TKN),
53 item(VARIABLE_TKN),
54 item(RANGE_TKN),
55 item(IPV4_TKN),
56 item(IPV4_PREFIX_TKN),
57 item(IPV6_TKN),
58 item(IPV6_PREFIX_TKN),
59 item(MAC_TKN),
60 item(MAC_PREFIX_TKN),
61 item(ASNUM_TKN),
62 item(FORK_TKN),
63 item(JOIN_TKN),
64 item(START_TKN),
65 item(END_TKN),
66 item(NEG_ONLY_TKN),
67 {0},
68 };
69 /* clang-format on */
70
71 /* Command vector which includes some level of command lists. Normally
72 each daemon maintains each own cmdvec. */
73 vector cmdvec = NULL;
74
75 /* Host information structure. */
76 struct host host;
77
78 /* for vtysh, put together CLI trees only when switching into node */
79 static bool defer_cli_tree;
80
81 /*
82 * Returns host.name if any, otherwise
83 * it returns the system hostname.
84 */
85 const char *cmd_hostname_get(void)
86 {
87 return host.name;
88 }
89
90 /*
91 * Returns unix domainname
92 */
93 const char *cmd_domainname_get(void)
94 {
95 return host.domainname;
96 }
97
98 const char *cmd_system_get(void)
99 {
100 return host.system;
101 }
102
103 const char *cmd_release_get(void)
104 {
105 return host.release;
106 }
107
108 const char *cmd_version_get(void)
109 {
110 return host.version;
111 }
112
113 bool cmd_allow_reserved_ranges_get(void)
114 {
115 return host.allow_reserved_ranges;
116 }
117
118 const char *cmd_software_version_get(void)
119 {
120 return FRR_FULL_NAME "/" FRR_VERSION;
121 }
122
123 static int root_on_exit(struct vty *vty);
124
125 /* Standard command node structures. */
126 static struct cmd_node auth_node = {
127 .name = "auth",
128 .node = AUTH_NODE,
129 .prompt = "Password: ",
130 };
131
132 static struct cmd_node view_node = {
133 .name = "view",
134 .node = VIEW_NODE,
135 .prompt = "%s> ",
136 .node_exit = root_on_exit,
137 };
138
139 static struct cmd_node auth_enable_node = {
140 .name = "auth enable",
141 .node = AUTH_ENABLE_NODE,
142 .prompt = "Password: ",
143 };
144
145 static struct cmd_node enable_node = {
146 .name = "enable",
147 .node = ENABLE_NODE,
148 .prompt = "%s# ",
149 .node_exit = root_on_exit,
150 };
151
152 static int config_write_host(struct vty *vty);
153 static struct cmd_node config_node = {
154 .name = "config",
155 .node = CONFIG_NODE,
156 .parent_node = ENABLE_NODE,
157 .prompt = "%s(config)# ",
158 .config_write = config_write_host,
159 .node_exit = vty_config_node_exit,
160 };
161
162 /* This is called from main when a daemon is invoked with -v or --version. */
163 void print_version(const char *progname)
164 {
165 printf("%s version %s\n", progname, FRR_VERSION);
166 printf("%s\n", FRR_COPYRIGHT);
167 #ifdef ENABLE_VERSION_BUILD_CONFIG
168 printf("configured with:\n\t%s\n", FRR_CONFIG_ARGS);
169 #endif
170 }
171
172 char *argv_concat(struct cmd_token **argv, int argc, int shift)
173 {
174 int cnt = MAX(argc - shift, 0);
175 const char *argstr[cnt + 1];
176
177 if (!cnt)
178 return NULL;
179
180 for (int i = 0; i < cnt; i++)
181 argstr[i] = argv[i + shift]->arg;
182
183 return frrstr_join(argstr, cnt, " ");
184 }
185
186 vector cmd_make_strvec(const char *string)
187 {
188 if (!string)
189 return NULL;
190
191 const char *copy = string;
192
193 /* skip leading whitespace */
194 while (isspace((unsigned char)*copy) && *copy != '\0')
195 copy++;
196
197 /* if the entire string was whitespace or a comment, return */
198 if (*copy == '\0' || *copy == '!' || *copy == '#')
199 return NULL;
200
201 vector result = frrstr_split_vec(copy, "\n\r\t ");
202
203 for (unsigned int i = 0; i < vector_active(result); i++) {
204 if (strlen(vector_slot(result, i)) == 0) {
205 XFREE(MTYPE_TMP, vector_slot(result, i));
206 vector_unset(result, i);
207 }
208 }
209
210 vector_compact(result);
211
212 return result;
213 }
214
215 void cmd_free_strvec(vector v)
216 {
217 frrstr_strvec_free(v);
218 }
219
220 /**
221 * Convenience function for accessing argv data.
222 *
223 * @param argc
224 * @param argv
225 * @param text definition snippet of the desired token
226 * @param index the starting index, and where to store the
227 * index of the found token if it exists
228 * @return 1 if found, 0 otherwise
229 */
230 int argv_find(struct cmd_token **argv, int argc, const char *text, int *index)
231 {
232 int found = 0;
233 for (int i = *index; i < argc && found == 0; i++)
234 if ((found = strmatch(text, argv[i]->text)))
235 *index = i;
236 return found;
237 }
238
239 static unsigned int cmd_hash_key(const void *p)
240 {
241 int size = sizeof(p);
242
243 return jhash(p, size, 0);
244 }
245
246 static bool cmd_hash_cmp(const void *a, const void *b)
247 {
248 return a == b;
249 }
250
251 /* Install top node of command vector. */
252 void install_node(struct cmd_node *node)
253 {
254 #define CMD_HASH_STR_SIZE 256
255 char hash_name[CMD_HASH_STR_SIZE];
256
257 vector_set_index(cmdvec, node->node, node);
258 node->cmdgraph = graph_new();
259 node->cmd_vector = vector_init(VECTOR_MIN_SIZE);
260 // add start node
261 struct cmd_token *token = cmd_token_new(START_TKN, 0, NULL, NULL);
262 graph_new_node(node->cmdgraph, token,
263 (void (*)(void *)) & cmd_token_del);
264
265 snprintf(hash_name, sizeof(hash_name), "Command Hash: %s", node->name);
266 node->cmd_hash =
267 hash_create_size(16, cmd_hash_key, cmd_hash_cmp, hash_name);
268 }
269
270 /* Return prompt character of specified node. */
271 const char *cmd_prompt(enum node_type node)
272 {
273 struct cmd_node *cnode;
274
275 cnode = vector_slot(cmdvec, node);
276 return cnode->prompt;
277 }
278
279 void cmd_defer_tree(bool val)
280 {
281 defer_cli_tree = val;
282 }
283
284 /* Install a command into a node. */
285 void _install_element(enum node_type ntype, const struct cmd_element *cmd)
286 {
287 struct cmd_node *cnode;
288
289 /* cmd_init hasn't been called */
290 if (!cmdvec) {
291 fprintf(stderr, "%s called before cmd_init, breakage likely\n",
292 __func__);
293 return;
294 }
295
296 cnode = vector_lookup(cmdvec, ntype);
297
298 if (cnode == NULL) {
299 fprintf(stderr,
300 "%s[%s]:\n"
301 "\tnode %d does not exist.\n"
302 "\tplease call install_node() before install_element()\n",
303 cmd->name, cmd->string, ntype);
304 exit(EXIT_FAILURE);
305 }
306
307 if (hash_lookup(cnode->cmd_hash, (void *)cmd) != NULL) {
308 fprintf(stderr,
309 "%s[%s]:\n"
310 "\tnode %d (%s) already has this command installed.\n"
311 "\tduplicate install_element call?\n",
312 cmd->name, cmd->string, ntype, cnode->name);
313 return;
314 }
315
316 (void)hash_get(cnode->cmd_hash, (void *)cmd, hash_alloc_intern);
317
318 if (cnode->graph_built || !defer_cli_tree) {
319 struct graph *graph = graph_new();
320 struct cmd_token *token =
321 cmd_token_new(START_TKN, 0, NULL, NULL);
322 graph_new_node(graph, token,
323 (void (*)(void *)) & cmd_token_del);
324
325 cmd_graph_parse(graph, cmd);
326 cmd_graph_names(graph);
327 cmd_graph_merge(cnode->cmdgraph, graph, +1);
328 graph_delete_graph(graph);
329
330 cnode->graph_built = true;
331 }
332
333 vector_set(cnode->cmd_vector, (void *)cmd);
334
335 if (ntype == VIEW_NODE)
336 _install_element(ENABLE_NODE, cmd);
337 }
338
339 static void cmd_finalize_iter(struct hash_bucket *hb, void *arg)
340 {
341 struct cmd_node *cnode = arg;
342 const struct cmd_element *cmd = hb->data;
343 struct graph *graph = graph_new();
344 struct cmd_token *token = cmd_token_new(START_TKN, 0, NULL, NULL);
345
346 graph_new_node(graph, token, (void (*)(void *)) & cmd_token_del);
347
348 cmd_graph_parse(graph, cmd);
349 cmd_graph_names(graph);
350 cmd_graph_merge(cnode->cmdgraph, graph, +1);
351 graph_delete_graph(graph);
352 }
353
354 void cmd_finalize_node(struct cmd_node *cnode)
355 {
356 if (cnode->graph_built)
357 return;
358
359 hash_iterate(cnode->cmd_hash, cmd_finalize_iter, cnode);
360 cnode->graph_built = true;
361 }
362
363 void uninstall_element(enum node_type ntype, const struct cmd_element *cmd)
364 {
365 struct cmd_node *cnode;
366
367 /* cmd_init hasn't been called */
368 if (!cmdvec) {
369 fprintf(stderr, "%s called before cmd_init, breakage likely\n",
370 __func__);
371 return;
372 }
373
374 cnode = vector_lookup(cmdvec, ntype);
375
376 if (cnode == NULL) {
377 fprintf(stderr,
378 "%s[%s]:\n"
379 "\tnode %d does not exist.\n"
380 "\tplease call install_node() before uninstall_element()\n",
381 cmd->name, cmd->string, ntype);
382 exit(EXIT_FAILURE);
383 }
384
385 if (hash_release(cnode->cmd_hash, (void *)cmd) == NULL) {
386 fprintf(stderr,
387 "%s[%s]:\n"
388 "\tnode %d (%s) does not have this command installed.\n"
389 "\tduplicate uninstall_element call?\n",
390 cmd->name, cmd->string, ntype, cnode->name);
391 return;
392 }
393
394 vector_unset_value(cnode->cmd_vector, (void *)cmd);
395
396 if (cnode->graph_built) {
397 struct graph *graph = graph_new();
398 struct cmd_token *token =
399 cmd_token_new(START_TKN, 0, NULL, NULL);
400 graph_new_node(graph, token,
401 (void (*)(void *)) & cmd_token_del);
402
403 cmd_graph_parse(graph, cmd);
404 cmd_graph_names(graph);
405 cmd_graph_merge(cnode->cmdgraph, graph, -1);
406 graph_delete_graph(graph);
407 }
408
409 if (ntype == VIEW_NODE)
410 uninstall_element(ENABLE_NODE, cmd);
411 }
412
413
414 static const unsigned char itoa64[] =
415 "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
416
417 static void to64(char *s, long v, int n)
418 {
419 while (--n >= 0) {
420 *s++ = itoa64[v & 0x3f];
421 v >>= 6;
422 }
423 }
424
425 static char *zencrypt(const char *passwd)
426 {
427 char salt[6];
428 struct timeval tv;
429
430 gettimeofday(&tv, 0);
431
432 to64(&salt[0], frr_weak_random(), 3);
433 to64(&salt[3], tv.tv_usec, 3);
434 salt[5] = '\0';
435
436 return crypt(passwd, salt);
437 }
438
439 static bool full_cli;
440
441 /* This function write configuration of this host. */
442 static int config_write_host(struct vty *vty)
443 {
444 const char *name;
445
446 name = cmd_hostname_get();
447 if (name && name[0] != '\0')
448 vty_out(vty, "hostname %s\n", name);
449
450 name = cmd_domainname_get();
451 if (name && name[0] != '\0')
452 vty_out(vty, "domainname %s\n", name);
453
454 if (cmd_allow_reserved_ranges_get())
455 vty_out(vty, "allow-reserved-ranges\n");
456
457 /* The following are all configuration commands that are not sent to
458 * watchfrr. For instance watchfrr is hardcoded to log to syslog so
459 * we would always display 'log syslog informational' in the config
460 * which would cause other daemons to then switch to syslog when they
461 * parse frr.conf.
462 */
463 if (full_cli) {
464 if (host.encrypt) {
465 if (host.password_encrypt)
466 vty_out(vty, "password 8 %s\n",
467 host.password_encrypt);
468 if (host.enable_encrypt)
469 vty_out(vty, "enable password 8 %s\n",
470 host.enable_encrypt);
471 } else {
472 if (host.password)
473 vty_out(vty, "password %s\n", host.password);
474 if (host.enable)
475 vty_out(vty, "enable password %s\n",
476 host.enable);
477 }
478 log_config_write(vty);
479
480 /* print disable always, but enable only if default is flipped
481 * => prep for future removal of compile-time knob
482 */
483 if (!cputime_enabled)
484 vty_out(vty, "no service cputime-stats\n");
485 #ifdef EXCLUDE_CPU_TIME
486 else
487 vty_out(vty, "service cputime-stats\n");
488 #endif
489
490 if (!cputime_threshold)
491 vty_out(vty, "no service cputime-warning\n");
492 #if defined(CONSUMED_TIME_CHECK) && CONSUMED_TIME_CHECK != 5000000
493 else /* again, always print non-default */
494 #else
495 else if (cputime_threshold != 5000000)
496 #endif
497 vty_out(vty, "service cputime-warning %lu\n",
498 cputime_threshold / 1000);
499
500 if (!walltime_threshold)
501 vty_out(vty, "no service walltime-warning\n");
502 #if defined(CONSUMED_TIME_CHECK) && CONSUMED_TIME_CHECK != 5000000
503 else /* again, always print non-default */
504 #else
505 else if (walltime_threshold != 5000000)
506 #endif
507 vty_out(vty, "service walltime-warning %lu\n",
508 walltime_threshold / 1000);
509
510 if (host.advanced)
511 vty_out(vty, "service advanced-vty\n");
512
513 if (host.encrypt)
514 vty_out(vty, "service password-encryption\n");
515
516 if (host.lines >= 0)
517 vty_out(vty, "service terminal-length %d\n",
518 host.lines);
519
520 if (host.motdfile)
521 vty_out(vty, "banner motd file %s\n", host.motdfile);
522 else if (host.motd
523 && strncmp(host.motd, FRR_DEFAULT_MOTD,
524 strlen(host.motd)))
525 vty_out(vty, "banner motd line %s\n", host.motd);
526 else if (!host.motd)
527 vty_out(vty, "no banner motd\n");
528 }
529
530 if (debug_memstats_at_exit)
531 vty_out(vty, "!\ndebug memstats-at-exit\n");
532
533 return 1;
534 }
535
536 /* Utility function for getting command graph. */
537 static struct graph *cmd_node_graph(vector v, enum node_type ntype)
538 {
539 struct cmd_node *cnode = vector_slot(v, ntype);
540
541 cmd_finalize_node(cnode);
542 return cnode->cmdgraph;
543 }
544
545 static int cmd_try_do_shortcut(enum node_type node, char *first_word)
546 {
547 if (first_word != NULL && node != AUTH_NODE && node != VIEW_NODE
548 && node != AUTH_ENABLE_NODE && 0 == strcmp("do", first_word))
549 return 1;
550 return 0;
551 }
552
553 /**
554 * Compare function for cmd_token.
555 * Used with qsort to sort command completions.
556 */
557 static int compare_completions(const void *fst, const void *snd)
558 {
559 const struct cmd_token *first = *(const struct cmd_token * const *)fst,
560 *secnd = *(const struct cmd_token * const *)snd;
561 return strcmp(first->text, secnd->text);
562 }
563
564 /**
565 * Takes a list of completions returned by command_complete,
566 * dedeuplicates them based on both text and description,
567 * sorts them, and returns them as a vector.
568 *
569 * @param completions linked list of cmd_token
570 * @return deduplicated and sorted vector with
571 */
572 vector completions_to_vec(struct list *completions)
573 {
574 vector comps = vector_init(VECTOR_MIN_SIZE);
575
576 struct listnode *ln;
577 struct cmd_token *token, *cr = NULL;
578 unsigned int i, exists;
579 for (ALL_LIST_ELEMENTS_RO(completions, ln, token)) {
580 if (token->type == END_TKN && (cr = token))
581 continue;
582
583 // linear search for token in completions vector
584 exists = 0;
585 for (i = 0; i < vector_active(comps) && !exists; i++) {
586 struct cmd_token *curr = vector_slot(comps, i);
587 #ifdef VTYSH_DEBUG
588 exists = !strcmp(curr->text, token->text)
589 && !strcmp(curr->desc, token->desc);
590 #else
591 exists = !strcmp(curr->text, token->text);
592 #endif /* VTYSH_DEBUG */
593 }
594
595 if (!exists)
596 vector_set(comps, token);
597 }
598
599 // sort completions
600 qsort(comps->index, vector_active(comps), sizeof(void *),
601 &compare_completions);
602
603 // make <cr> the first element, if it is present
604 if (cr) {
605 vector_set_index(comps, vector_active(comps), NULL);
606 memmove(comps->index + 1, comps->index,
607 (comps->alloced - 1) * sizeof(void *));
608 vector_set_index(comps, 0, cr);
609 }
610
611 return comps;
612 }
613 /**
614 * Generates a vector of cmd_token representing possible completions
615 * on the current input.
616 *
617 * @param vline the vectorized input line
618 * @param vty the vty with the node to match on
619 * @param status pointer to matcher status code
620 * @return vector of struct cmd_token * with possible completions
621 */
622 static vector cmd_complete_command_real(vector vline, struct vty *vty,
623 int *status)
624 {
625 struct list *completions;
626 struct graph *cmdgraph = cmd_node_graph(cmdvec, vty->node);
627
628 enum matcher_rv rv = command_complete(cmdgraph, vline, &completions);
629
630 if (MATCHER_ERROR(rv)) {
631 *status = CMD_ERR_NO_MATCH;
632 return NULL;
633 }
634
635 vector comps = completions_to_vec(completions);
636 list_delete(&completions);
637
638 // set status code appropriately
639 switch (vector_active(comps)) {
640 case 0:
641 *status = CMD_ERR_NO_MATCH;
642 break;
643 case 1:
644 *status = CMD_COMPLETE_FULL_MATCH;
645 break;
646 default:
647 *status = CMD_COMPLETE_LIST_MATCH;
648 }
649
650 return comps;
651 }
652
653 vector cmd_describe_command(vector vline, struct vty *vty, int *status)
654 {
655 vector ret;
656
657 if (cmd_try_do_shortcut(vty->node, vector_slot(vline, 0))) {
658 enum node_type onode;
659 int orig_xpath_index;
660 vector shifted_vline;
661 unsigned int index;
662
663 onode = vty->node;
664 orig_xpath_index = vty->xpath_index;
665 vty->node = ENABLE_NODE;
666 vty->xpath_index = 0;
667 /* We can try it on enable node, cos' the vty is authenticated
668 */
669
670 shifted_vline = vector_init(vector_count(vline));
671 /* use memcpy? */
672 for (index = 1; index < vector_active(vline); index++) {
673 vector_set_index(shifted_vline, index - 1,
674 vector_lookup(vline, index));
675 }
676
677 ret = cmd_complete_command_real(shifted_vline, vty, status);
678
679 vector_free(shifted_vline);
680 vty->node = onode;
681 vty->xpath_index = orig_xpath_index;
682 return ret;
683 }
684
685 return cmd_complete_command_real(vline, vty, status);
686 }
687
688 static struct list *varhandlers = NULL;
689
690 void cmd_variable_complete(struct cmd_token *token, const char *arg,
691 vector comps)
692 {
693 struct listnode *ln;
694 const struct cmd_variable_handler *cvh;
695 size_t i, argsz;
696 vector tmpcomps;
697
698 tmpcomps = arg ? vector_init(VECTOR_MIN_SIZE) : comps;
699
700 for (ALL_LIST_ELEMENTS_RO(varhandlers, ln, cvh)) {
701 if (cvh->tokenname && strcmp(cvh->tokenname, token->text))
702 continue;
703 if (cvh->varname && (!token->varname
704 || strcmp(cvh->varname, token->varname)))
705 continue;
706 cvh->completions(tmpcomps, token);
707 break;
708 }
709
710 if (!arg)
711 return;
712
713 argsz = strlen(arg);
714 for (i = vector_active(tmpcomps); i; i--) {
715 char *item = vector_slot(tmpcomps, i - 1);
716 if (strlen(item) >= argsz && !strncmp(item, arg, argsz))
717 vector_set(comps, item);
718 else
719 XFREE(MTYPE_COMPLETION, item);
720 }
721 vector_free(tmpcomps);
722 }
723
724 #define AUTOCOMP_INDENT 5
725
726 char *cmd_variable_comp2str(vector comps, unsigned short cols)
727 {
728 size_t bsz = 16;
729 char *buf = XCALLOC(MTYPE_TMP, bsz);
730 int lc = AUTOCOMP_INDENT;
731 size_t cs = AUTOCOMP_INDENT;
732 size_t itemlen;
733 snprintf(buf, bsz, "%*s", AUTOCOMP_INDENT, "");
734 for (size_t j = 0; j < vector_active(comps); j++) {
735 char *item = vector_slot(comps, j);
736 itemlen = strlen(item);
737
738 if (cs + itemlen + AUTOCOMP_INDENT + 3 >= bsz)
739 buf = XREALLOC(MTYPE_TMP, buf, (bsz *= 2));
740
741 if (lc + itemlen + 1 >= cols) {
742 cs += snprintf(&buf[cs], bsz - cs, "\n%*s",
743 AUTOCOMP_INDENT, "");
744 lc = AUTOCOMP_INDENT;
745 }
746
747 size_t written = snprintf(&buf[cs], bsz - cs, "%s ", item);
748 lc += written;
749 cs += written;
750 XFREE(MTYPE_COMPLETION, item);
751 vector_set_index(comps, j, NULL);
752 }
753 return buf;
754 }
755
756 void cmd_variable_handler_register(const struct cmd_variable_handler *cvh)
757 {
758 if (!varhandlers)
759 return;
760
761 for (; cvh->completions; cvh++)
762 listnode_add(varhandlers, (void *)cvh);
763 }
764
765 DEFUN_HIDDEN (autocomplete,
766 autocomplete_cmd,
767 "autocomplete TYPE TEXT VARNAME",
768 "Autocompletion handler (internal, for vtysh)\n"
769 "cmd_token->type\n"
770 "cmd_token->text\n"
771 "cmd_token->varname\n")
772 {
773 struct cmd_token tok;
774 vector comps = vector_init(32);
775 size_t i;
776
777 memset(&tok, 0, sizeof(tok));
778 tok.type = atoi(argv[1]->arg);
779 tok.text = argv[2]->arg;
780 tok.varname = argv[3]->arg;
781 if (!strcmp(tok.varname, "-"))
782 tok.varname = NULL;
783
784 cmd_variable_complete(&tok, NULL, comps);
785
786 for (i = 0; i < vector_active(comps); i++) {
787 char *text = vector_slot(comps, i);
788 vty_out(vty, "%s\n", text);
789 XFREE(MTYPE_COMPLETION, text);
790 }
791
792 vector_free(comps);
793 return CMD_SUCCESS;
794 }
795
796 /**
797 * Generate possible tab-completions for the given input. This function only
798 * returns results that would result in a valid command if used as Readline
799 * completions (as is the case in vtysh). For instance, if the passed vline ends
800 * with '4.3.2', the strings 'A.B.C.D' and 'A.B.C.D/M' will _not_ be returned.
801 *
802 * @param vline vectorized input line
803 * @param vty the vty
804 * @param status location to store matcher status code in
805 * @return set of valid strings for use with Readline as tab-completions.
806 */
807
808 char **cmd_complete_command(vector vline, struct vty *vty, int *status)
809 {
810 char **ret = NULL;
811 int original_node = vty->node;
812 vector input_line = vector_init(vector_count(vline));
813
814 // if the first token is 'do' we'll want to execute the command in the
815 // enable node
816 int do_shortcut = cmd_try_do_shortcut(vty->node, vector_slot(vline, 0));
817 vty->node = do_shortcut ? ENABLE_NODE : original_node;
818
819 // construct the input line we'll be matching on
820 unsigned int offset = (do_shortcut) ? 1 : 0;
821 for (unsigned index = 0; index + offset < vector_active(vline); index++)
822 vector_set_index(input_line, index,
823 vector_lookup(vline, index + offset));
824
825 // get token completions -- this is a copying operation
826 vector comps = NULL, initial_comps;
827 initial_comps = cmd_complete_command_real(input_line, vty, status);
828
829 if (!MATCHER_ERROR(*status)) {
830 assert(initial_comps);
831 // filter out everything that is not suitable for a
832 // tab-completion
833 comps = vector_init(VECTOR_MIN_SIZE);
834 for (unsigned int i = 0; i < vector_active(initial_comps);
835 i++) {
836 struct cmd_token *token = vector_slot(initial_comps, i);
837 if (token->type == WORD_TKN)
838 vector_set(comps, XSTRDUP(MTYPE_COMPLETION,
839 token->text));
840 else if (IS_VARYING_TOKEN(token->type)) {
841 const char *ref = vector_lookup(
842 vline, vector_active(vline) - 1);
843 cmd_variable_complete(token, ref, comps);
844 }
845 }
846 vector_free(initial_comps);
847
848 // since we filtered results, we need to re-set status code
849 switch (vector_active(comps)) {
850 case 0:
851 *status = CMD_ERR_NO_MATCH;
852 break;
853 case 1:
854 *status = CMD_COMPLETE_FULL_MATCH;
855 break;
856 default:
857 *status = CMD_COMPLETE_LIST_MATCH;
858 }
859
860 // copy completions text into an array of char*
861 ret = XMALLOC(MTYPE_TMP,
862 (vector_active(comps) + 1) * sizeof(char *));
863 unsigned int i;
864 for (i = 0; i < vector_active(comps); i++) {
865 ret[i] = vector_slot(comps, i);
866 }
867 // set the last element to NULL, because this array is used in
868 // a Readline completion_generator function which expects NULL
869 // as a sentinel value
870 ret[i] = NULL;
871 vector_free(comps);
872 comps = NULL;
873 } else if (initial_comps)
874 vector_free(initial_comps);
875
876 // comps should always be null here
877 assert(!comps);
878
879 // free the adjusted input line
880 vector_free(input_line);
881
882 // reset vty->node to its original value
883 vty->node = original_node;
884
885 return ret;
886 }
887
888 /* return parent node */
889 /* MUST eventually converge on CONFIG_NODE */
890 enum node_type node_parent(enum node_type node)
891 {
892 struct cmd_node *cnode;
893
894 assert(node > CONFIG_NODE);
895
896 cnode = vector_lookup(cmdvec, node);
897
898 return cnode->parent_node;
899 }
900
901 /* Execute command by argument vline vector. */
902 static int cmd_execute_command_real(vector vline, enum cmd_filter_type filter,
903 struct vty *vty,
904 const struct cmd_element **cmd,
905 unsigned int up_level)
906 {
907 struct list *argv_list;
908 enum matcher_rv status;
909 const struct cmd_element *matched_element = NULL;
910 unsigned int i;
911 int xpath_index = vty->xpath_index;
912 int node = vty->node;
913
914 /* only happens for legacy split config file load; need to check for
915 * a match before calling node_exit handlers below
916 */
917 for (i = 0; i < up_level; i++) {
918 struct cmd_node *cnode;
919
920 if (node <= CONFIG_NODE)
921 return CMD_NO_LEVEL_UP;
922
923 cnode = vector_slot(cmdvec, node);
924 node = node_parent(node);
925
926 if (xpath_index > 0 && !cnode->no_xpath)
927 xpath_index--;
928 }
929
930 struct graph *cmdgraph = cmd_node_graph(cmdvec, node);
931 status = command_match(cmdgraph, vline, &argv_list, &matched_element);
932
933 if (cmd)
934 *cmd = matched_element;
935
936 // if matcher error, return corresponding CMD_ERR
937 if (MATCHER_ERROR(status)) {
938 if (argv_list)
939 list_delete(&argv_list);
940 switch (status) {
941 case MATCHER_INCOMPLETE:
942 return CMD_ERR_INCOMPLETE;
943 case MATCHER_AMBIGUOUS:
944 return CMD_ERR_AMBIGUOUS;
945 case MATCHER_NO_MATCH:
946 case MATCHER_OK:
947 return CMD_ERR_NO_MATCH;
948 }
949 }
950
951 for (i = 0; i < up_level; i++)
952 cmd_exit(vty);
953
954 // build argv array from argv list
955 struct cmd_token **argv = XMALLOC(
956 MTYPE_TMP, argv_list->count * sizeof(struct cmd_token *));
957 struct listnode *ln;
958 struct cmd_token *token;
959
960 i = 0;
961 for (ALL_LIST_ELEMENTS_RO(argv_list, ln, token))
962 argv[i++] = token;
963
964 int argc = argv_list->count;
965
966 int ret;
967 if (matched_element->daemon)
968 ret = CMD_SUCCESS_DAEMON;
969 else {
970 if (vty->config) {
971 /* Clear array of enqueued configuration changes. */
972 vty->num_cfg_changes = 0;
973 memset(&vty->cfg_changes, 0, sizeof(vty->cfg_changes));
974
975 /* Regenerate candidate configuration if necessary. */
976 if (frr_get_cli_mode() == FRR_CLI_CLASSIC
977 && running_config->version
978 > vty->candidate_config->version)
979 nb_config_replace(vty->candidate_config,
980 running_config, true);
981
982 /*
983 * Perform pending commit (if any) before executing
984 * non-YANG command.
985 */
986 if (!(matched_element->attr & CMD_ATTR_YANG))
987 (void)nb_cli_pending_commit_check(vty);
988 }
989
990 ret = matched_element->func(matched_element, vty, argc, argv);
991 }
992
993 // delete list and cmd_token's in it
994 list_delete(&argv_list);
995 XFREE(MTYPE_TMP, argv);
996
997 return ret;
998 }
999
1000 /**
1001 * Execute a given command, handling things like "do ..." and checking
1002 * whether the given command might apply at a parent node if doesn't
1003 * apply for the current node.
1004 *
1005 * @param vline Command line input, vector of char* where each element is
1006 * one input token.
1007 * @param vty The vty context in which the command should be executed.
1008 * @param cmd Pointer where the struct cmd_element of the matched command
1009 * will be stored, if any. May be set to NULL if this info is
1010 * not needed.
1011 * @param vtysh If set != 0, don't lookup the command at parent nodes.
1012 * @return The status of the command that has been executed or an error code
1013 * as to why no command could be executed.
1014 */
1015 int cmd_execute_command(vector vline, struct vty *vty,
1016 const struct cmd_element **cmd, int vtysh)
1017 {
1018 int ret, saved_ret = 0;
1019 enum node_type onode, try_node;
1020 int orig_xpath_index;
1021
1022 onode = try_node = vty->node;
1023 orig_xpath_index = vty->xpath_index;
1024
1025 if (cmd_try_do_shortcut(vty->node, vector_slot(vline, 0))) {
1026 vector shifted_vline;
1027 unsigned int index;
1028
1029 vty->node = ENABLE_NODE;
1030 vty->xpath_index = 0;
1031 /* We can try it on enable node, cos' the vty is authenticated
1032 */
1033
1034 shifted_vline = vector_init(vector_count(vline));
1035 /* use memcpy? */
1036 for (index = 1; index < vector_active(vline); index++)
1037 vector_set_index(shifted_vline, index - 1,
1038 vector_lookup(vline, index));
1039
1040 ret = cmd_execute_command_real(shifted_vline, FILTER_RELAXED,
1041 vty, cmd, 0);
1042
1043 vector_free(shifted_vline);
1044 vty->node = onode;
1045 vty->xpath_index = orig_xpath_index;
1046 return ret;
1047 }
1048
1049 saved_ret = ret =
1050 cmd_execute_command_real(vline, FILTER_RELAXED, vty, cmd, 0);
1051
1052 if (vtysh)
1053 return saved_ret;
1054
1055 if (ret != CMD_SUCCESS && ret != CMD_WARNING
1056 && ret != CMD_ERR_AMBIGUOUS && ret != CMD_ERR_INCOMPLETE
1057 && ret != CMD_NOT_MY_INSTANCE && ret != CMD_WARNING_CONFIG_FAILED) {
1058 /* This assumes all nodes above CONFIG_NODE are childs of
1059 * CONFIG_NODE */
1060 while (vty->node > CONFIG_NODE) {
1061 struct cmd_node *cnode = vector_slot(cmdvec, try_node);
1062
1063 try_node = node_parent(try_node);
1064 vty->node = try_node;
1065 if (vty->xpath_index > 0 && !cnode->no_xpath)
1066 vty->xpath_index--;
1067
1068 ret = cmd_execute_command_real(vline, FILTER_RELAXED,
1069 vty, cmd, 0);
1070 if (ret == CMD_SUCCESS || ret == CMD_WARNING
1071 || ret == CMD_ERR_AMBIGUOUS || ret == CMD_ERR_INCOMPLETE
1072 || ret == CMD_NOT_MY_INSTANCE
1073 || ret == CMD_WARNING_CONFIG_FAILED)
1074 return ret;
1075 }
1076 /* no command succeeded, reset the vty to the original node */
1077 vty->node = onode;
1078 vty->xpath_index = orig_xpath_index;
1079 }
1080
1081 /* return command status for original node */
1082 return saved_ret;
1083 }
1084
1085 /**
1086 * Execute a given command, matching it strictly against the current node.
1087 * This mode is used when reading config files.
1088 *
1089 * @param vline Command line input, vector of char* where each element is
1090 * one input token.
1091 * @param vty The vty context in which the command should be executed.
1092 * @param cmd Pointer where the struct cmd_element* of the matched command
1093 * will be stored, if any. May be set to NULL if this info is
1094 * not needed.
1095 * @return The status of the command that has been executed or an error code
1096 * as to why no command could be executed.
1097 */
1098 int cmd_execute_command_strict(vector vline, struct vty *vty,
1099 const struct cmd_element **cmd)
1100 {
1101 return cmd_execute_command_real(vline, FILTER_STRICT, vty, cmd, 0);
1102 }
1103
1104 /*
1105 * Hook for preprocessing command string before executing.
1106 *
1107 * All subscribers are called with the raw command string that is to be
1108 * executed. If any changes are to be made, a new string should be allocated
1109 * with MTYPE_TMP and *cmd_out updated to point to this new string. The caller
1110 * is then responsible for freeing this string.
1111 *
1112 * All processing functions must be mutually exclusive in their action, i.e. if
1113 * one subscriber decides to modify the command, all others must not modify it
1114 * when called. Feeding the output of one processing command into a subsequent
1115 * one is not supported.
1116 *
1117 * This hook is intentionally internal to the command processing system.
1118 *
1119 * cmd_in
1120 * The raw command string.
1121 *
1122 * cmd_out
1123 * The result of any processing.
1124 */
1125 DECLARE_HOOK(cmd_execute,
1126 (struct vty *vty, const char *cmd_in, char **cmd_out),
1127 (vty, cmd_in, cmd_out));
1128 DEFINE_HOOK(cmd_execute, (struct vty *vty, const char *cmd_in, char **cmd_out),
1129 (vty, cmd_in, cmd_out));
1130
1131 /* Hook executed after a CLI command. */
1132 DECLARE_KOOH(cmd_execute_done, (struct vty *vty, const char *cmd_exec),
1133 (vty, cmd_exec));
1134 DEFINE_KOOH(cmd_execute_done, (struct vty *vty, const char *cmd_exec),
1135 (vty, cmd_exec));
1136
1137 /*
1138 * cmd_execute hook subscriber to handle `|` actions.
1139 */
1140 static int handle_pipe_action(struct vty *vty, const char *cmd_in,
1141 char **cmd_out)
1142 {
1143 /* look for `|` */
1144 char *orig, *working, *token, *u;
1145 char *pipe = strstr(cmd_in, "| ");
1146 int ret = 0;
1147
1148 if (!pipe)
1149 return 0;
1150
1151 /* duplicate string for processing purposes, not including pipe */
1152 orig = working = XSTRDUP(MTYPE_TMP, pipe + 2);
1153
1154 /* retrieve action */
1155 token = strsep(&working, " ");
1156 assert(token);
1157
1158 /* match result to known actions */
1159 if (strmatch(token, "include")) {
1160 /* the remaining text should be a regexp */
1161 char *regexp = working;
1162
1163 if (!regexp) {
1164 vty_out(vty, "%% Need a regexp to filter with\n");
1165 ret = 1;
1166 goto fail;
1167 }
1168
1169 bool succ = vty_set_include(vty, regexp);
1170
1171 if (!succ) {
1172 vty_out(vty, "%% Bad regexp '%s'\n", regexp);
1173 ret = 1;
1174 goto fail;
1175 }
1176 *cmd_out = XSTRDUP(MTYPE_TMP, cmd_in);
1177 u = *cmd_out;
1178 strsep(&u, "|");
1179 } else {
1180 vty_out(vty, "%% Unknown action '%s'\n", token);
1181 ret = 1;
1182 goto fail;
1183 }
1184
1185 fail:
1186 XFREE(MTYPE_TMP, orig);
1187 return ret;
1188 }
1189
1190 static int handle_pipe_action_done(struct vty *vty, const char *cmd_exec)
1191 {
1192 if (vty->filter)
1193 vty_set_include(vty, NULL);
1194
1195 return 0;
1196 }
1197
1198 int cmd_execute(struct vty *vty, const char *cmd,
1199 const struct cmd_element **matched, int vtysh)
1200 {
1201 int ret;
1202 char *cmd_out = NULL;
1203 const char *cmd_exec = NULL;
1204 vector vline;
1205
1206 ret = hook_call(cmd_execute, vty, cmd, &cmd_out);
1207 if (ret) {
1208 ret = CMD_WARNING;
1209 goto free;
1210 }
1211
1212 cmd_exec = cmd_out ? (const char *)cmd_out : cmd;
1213
1214 vline = cmd_make_strvec(cmd_exec);
1215
1216 if (vline) {
1217 ret = cmd_execute_command(vline, vty, matched, vtysh);
1218 cmd_free_strvec(vline);
1219 } else {
1220 ret = CMD_SUCCESS;
1221 }
1222
1223 free:
1224 hook_call(cmd_execute_done, vty, cmd_exec);
1225
1226 XFREE(MTYPE_TMP, cmd_out);
1227
1228 return ret;
1229 }
1230
1231
1232 /**
1233 * Parse one line of config, walking up the parse tree attempting to find a
1234 * match
1235 *
1236 * @param vty The vty context in which the command should be executed.
1237 * @param cmd Pointer where the struct cmd_element* of the match command
1238 * will be stored, if any. May be set to NULL if this info is
1239 * not needed.
1240 * @param use_daemon Boolean to control whether or not we match on
1241 * CMD_SUCCESS_DAEMON
1242 * or not.
1243 * @return The status of the command that has been executed or an error code
1244 * as to why no command could be executed.
1245 */
1246 int command_config_read_one_line(struct vty *vty,
1247 const struct cmd_element **cmd,
1248 uint32_t line_num, int use_daemon)
1249 {
1250 vector vline;
1251 int ret;
1252 unsigned up_level = 0;
1253
1254 vline = cmd_make_strvec(vty->buf);
1255
1256 /* In case of comment line */
1257 if (vline == NULL)
1258 return CMD_SUCCESS;
1259
1260 /* Execute configuration command : this is strict match */
1261 ret = cmd_execute_command_strict(vline, vty, cmd);
1262
1263 /* The logic for trying parent nodes is in cmd_execute_command_real()
1264 * since calling ->node_exit() correctly is a bit involved. This is
1265 * also the only reason CMD_NO_LEVEL_UP exists.
1266 */
1267 while (!(use_daemon && ret == CMD_SUCCESS_DAEMON)
1268 && !(!use_daemon && ret == CMD_ERR_NOTHING_TODO)
1269 && ret != CMD_SUCCESS && ret != CMD_WARNING
1270 && ret != CMD_ERR_AMBIGUOUS && ret != CMD_ERR_INCOMPLETE
1271 && ret != CMD_NOT_MY_INSTANCE && ret != CMD_WARNING_CONFIG_FAILED
1272 && ret != CMD_NO_LEVEL_UP)
1273 ret = cmd_execute_command_real(vline, FILTER_STRICT, vty, cmd,
1274 ++up_level);
1275
1276 if (ret == CMD_NO_LEVEL_UP)
1277 ret = CMD_ERR_NO_MATCH;
1278
1279 if (ret != CMD_SUCCESS &&
1280 ret != CMD_WARNING &&
1281 ret != CMD_SUCCESS_DAEMON) {
1282 struct vty_error *ve = XCALLOC(MTYPE_TMP, sizeof(*ve));
1283
1284 memcpy(ve->error_buf, vty->buf, VTY_BUFSIZ);
1285 ve->line_num = line_num;
1286 ve->cmd_ret = ret;
1287 if (!vty->error)
1288 vty->error = list_new();
1289
1290 listnode_add(vty->error, ve);
1291 }
1292
1293 cmd_free_strvec(vline);
1294
1295 return ret;
1296 }
1297
1298 /* Configuration make from file. */
1299 int config_from_file(struct vty *vty, FILE *fp, unsigned int *line_num)
1300 {
1301 int ret, error_ret = 0;
1302 *line_num = 0;
1303
1304 while (fgets(vty->buf, VTY_BUFSIZ, fp)) {
1305 ++(*line_num);
1306
1307 if (vty_log_commands) {
1308 int len = strlen(vty->buf);
1309
1310 /* now log the command */
1311 zlog_notice("config-from-file# %.*s", len ? len - 1 : 0,
1312 vty->buf);
1313 }
1314
1315 ret = command_config_read_one_line(vty, NULL, *line_num, 0);
1316
1317 if (ret != CMD_SUCCESS && ret != CMD_WARNING
1318 && ret != CMD_ERR_NOTHING_TODO)
1319 error_ret = ret;
1320 }
1321
1322 if (error_ret) {
1323 return error_ret;
1324 }
1325
1326 return CMD_SUCCESS;
1327 }
1328
1329 /* Configuration from terminal */
1330 DEFUN (config_terminal,
1331 config_terminal_cmd,
1332 "configure [terminal]",
1333 "Configuration from vty interface\n"
1334 "Configuration terminal\n")
1335 {
1336 return vty_config_enter(vty, false, false);
1337 }
1338
1339 /* Enable command */
1340 DEFUN (enable,
1341 config_enable_cmd,
1342 "enable",
1343 "Turn on privileged mode command\n")
1344 {
1345 /* If enable password is NULL, change to ENABLE_NODE */
1346 if ((host.enable == NULL && host.enable_encrypt == NULL)
1347 || vty->type == VTY_SHELL_SERV)
1348 vty->node = ENABLE_NODE;
1349 else
1350 vty->node = AUTH_ENABLE_NODE;
1351
1352 return CMD_SUCCESS;
1353 }
1354
1355 /* Disable command */
1356 DEFUN (disable,
1357 config_disable_cmd,
1358 "disable",
1359 "Turn off privileged mode command\n")
1360 {
1361 if (vty->node == ENABLE_NODE)
1362 vty->node = VIEW_NODE;
1363 return CMD_SUCCESS;
1364 }
1365
1366 /* Down vty node level. */
1367 DEFUN (config_exit,
1368 config_exit_cmd,
1369 "exit",
1370 "Exit current mode and down to previous mode\n")
1371 {
1372 cmd_exit(vty);
1373 return CMD_SUCCESS;
1374 }
1375
1376 static int root_on_exit(struct vty *vty)
1377 {
1378 if (vty_shell(vty))
1379 exit(0);
1380 else
1381 vty->status = VTY_CLOSE;
1382 return 0;
1383 }
1384
1385 void cmd_exit(struct vty *vty)
1386 {
1387 struct cmd_node *cnode = vector_lookup(cmdvec, vty->node);
1388
1389 if (cnode->node_exit) {
1390 if (!cnode->node_exit(vty))
1391 return;
1392 }
1393 if (cnode->parent_node)
1394 vty->node = cnode->parent_node;
1395 if (vty->xpath_index > 0 && !cnode->no_xpath)
1396 vty->xpath_index--;
1397 }
1398
1399 /* ALIAS_FIXME */
1400 DEFUN (config_quit,
1401 config_quit_cmd,
1402 "quit",
1403 "Exit current mode and down to previous mode\n")
1404 {
1405 return config_exit(self, vty, argc, argv);
1406 }
1407
1408
1409 /* End of configuration. */
1410 DEFUN (config_end,
1411 config_end_cmd,
1412 "end",
1413 "End current mode and change to enable mode.\n")
1414 {
1415 if (vty->config) {
1416 vty_config_exit(vty);
1417 vty->node = ENABLE_NODE;
1418 }
1419 return CMD_SUCCESS;
1420 }
1421
1422 /* Show version. */
1423 DEFUN (show_version,
1424 show_version_cmd,
1425 "show version",
1426 SHOW_STR
1427 "Displays zebra version\n")
1428 {
1429 vty_out(vty, "%s %s (%s) on %s(%s).\n", FRR_FULL_NAME, FRR_VERSION,
1430 cmd_hostname_get() ? cmd_hostname_get() : "", cmd_system_get(),
1431 cmd_release_get());
1432 vty_out(vty, "%s%s\n", FRR_COPYRIGHT, GIT_INFO);
1433 #ifdef ENABLE_VERSION_BUILD_CONFIG
1434 vty_out(vty, "configured with:\n %s\n", FRR_CONFIG_ARGS);
1435 #endif
1436 return CMD_SUCCESS;
1437 }
1438
1439 /* Help display function for all node. */
1440 DEFUN (config_help,
1441 config_help_cmd,
1442 "help",
1443 "Description of the interactive help system\n")
1444 {
1445 vty_out(vty,
1446 "Quagga VTY provides advanced help feature. When you need help,\n\
1447 anytime at the command line please press '?'.\n\
1448 \n\
1449 If nothing matches, the help list will be empty and you must backup\n\
1450 until entering a '?' shows the available options.\n\
1451 Two styles of help are provided:\n\
1452 1. Full help is available when you are ready to enter a\n\
1453 command argument (e.g. 'show ?') and describes each possible\n\
1454 argument.\n\
1455 2. Partial help is provided when an abbreviated argument is entered\n\
1456 and you want to know what arguments match the input\n\
1457 (e.g. 'show me?'.)\n\n");
1458 return CMD_SUCCESS;
1459 }
1460
1461 static void permute(struct graph_node *start, struct vty *vty)
1462 {
1463 static struct list *position = NULL;
1464 if (!position)
1465 position = list_new();
1466
1467 struct cmd_token *stok = start->data;
1468 struct graph_node *gnn;
1469 struct listnode *ln;
1470
1471 // recursive dfs
1472 listnode_add(position, start);
1473 for (unsigned int i = 0; i < vector_active(start->to); i++) {
1474 struct graph_node *gn = vector_slot(start->to, i);
1475 struct cmd_token *tok = gn->data;
1476 if (tok->attr & CMD_ATTR_HIDDEN)
1477 continue;
1478 else if (tok->type == END_TKN || gn == start) {
1479 vty_out(vty, " ");
1480 for (ALL_LIST_ELEMENTS_RO(position, ln, gnn)) {
1481 struct cmd_token *tt = gnn->data;
1482 if (tt->type < SPECIAL_TKN)
1483 vty_out(vty, " %s", tt->text);
1484 }
1485 if (gn == start)
1486 vty_out(vty, "...");
1487 vty_out(vty, "\n");
1488 } else {
1489 bool skip = false;
1490 if (stok->type == FORK_TKN && tok->type != FORK_TKN)
1491 for (ALL_LIST_ELEMENTS_RO(position, ln, gnn))
1492 if (gnn == gn) {
1493 skip = true;
1494 break;
1495 }
1496 if (!skip)
1497 permute(gn, vty);
1498 }
1499 }
1500 list_delete_node(position, listtail(position));
1501 }
1502
1503 static void print_cmd(struct vty *vty, const char *cmd)
1504 {
1505 int i, j, len = strlen(cmd);
1506 char buf[len + 1];
1507 bool skip = false;
1508
1509 j = 0;
1510 for (i = 0; i < len; i++) {
1511 /* skip varname */
1512 if (cmd[i] == '$')
1513 skip = true;
1514 else if (strchr(" ()<>[]{}|", cmd[i]))
1515 skip = false;
1516
1517 if (skip)
1518 continue;
1519
1520 if (isspace(cmd[i])) {
1521 /* skip leading whitespace */
1522 if (i == 0)
1523 continue;
1524 /* skip trailing whitespace */
1525 if (i == len - 1)
1526 continue;
1527 /* skip all whitespace after opening brackets or pipe */
1528 if (strchr("(<[{|", cmd[i - 1])) {
1529 while (isspace(cmd[i + 1]))
1530 i++;
1531 continue;
1532 }
1533 /* skip repeated whitespace */
1534 if (isspace(cmd[i + 1]))
1535 continue;
1536 /* skip whitespace before closing brackets or pipe */
1537 if (strchr(")>]}|", cmd[i + 1]))
1538 continue;
1539 /* convert tabs to spaces */
1540 if (cmd[i] == '\t') {
1541 buf[j++] = ' ';
1542 continue;
1543 }
1544 }
1545
1546 buf[j++] = cmd[i];
1547 }
1548 buf[j] = 0;
1549
1550 vty_out(vty, "%s\n", buf);
1551 }
1552
1553 int cmd_list_cmds(struct vty *vty, int do_permute)
1554 {
1555 struct cmd_node *node = vector_slot(cmdvec, vty->node);
1556
1557 if (do_permute) {
1558 cmd_finalize_node(node);
1559 permute(vector_slot(node->cmdgraph->nodes, 0), vty);
1560 } else {
1561 /* loop over all commands at this node */
1562 const struct cmd_element *element = NULL;
1563 for (unsigned int i = 0; i < vector_active(node->cmd_vector);
1564 i++)
1565 if ((element = vector_slot(node->cmd_vector, i)) &&
1566 !(element->attr & CMD_ATTR_HIDDEN)) {
1567 vty_out(vty, " ");
1568 print_cmd(vty, element->string);
1569 }
1570 }
1571 return CMD_SUCCESS;
1572 }
1573
1574 /* Help display function for all node. */
1575 DEFUN (config_list,
1576 config_list_cmd,
1577 "list [permutations]",
1578 "Print command list\n"
1579 "Print all possible command permutations\n")
1580 {
1581 return cmd_list_cmds(vty, argc == 2);
1582 }
1583
1584 DEFUN (show_commandtree,
1585 show_commandtree_cmd,
1586 "show commandtree [permutations]",
1587 SHOW_STR
1588 "Show command tree\n"
1589 "Permutations that we are interested in\n")
1590 {
1591 return cmd_list_cmds(vty, argc == 3);
1592 }
1593
1594 DEFUN_HIDDEN(show_cli_graph,
1595 show_cli_graph_cmd,
1596 "show cli graph",
1597 SHOW_STR
1598 "CLI reflection\n"
1599 "Dump current command space as DOT graph\n")
1600 {
1601 struct cmd_node *cn = vector_slot(cmdvec, vty->node);
1602 char *dot;
1603
1604 cmd_finalize_node(cn);
1605 dot = cmd_graph_dump_dot(cn->cmdgraph);
1606
1607 vty_out(vty, "%s\n", dot);
1608 XFREE(MTYPE_TMP, dot);
1609 return CMD_SUCCESS;
1610 }
1611
1612 static int vty_write_config(struct vty *vty)
1613 {
1614 size_t i;
1615 struct cmd_node *node;
1616
1617 if (host.noconfig)
1618 return CMD_SUCCESS;
1619
1620 nb_cli_show_config_prepare(running_config, false);
1621
1622 if (vty->type == VTY_TERM) {
1623 vty_out(vty, "\nCurrent configuration:\n");
1624 vty_out(vty, "!\n");
1625 }
1626
1627 if (strcmp(frr_defaults_version(), FRR_VER_SHORT))
1628 vty_out(vty, "! loaded from %s\n", frr_defaults_version());
1629 vty_out(vty, "frr version %s\n", FRR_VER_SHORT);
1630 vty_out(vty, "frr defaults %s\n", frr_defaults_profile());
1631 vty_out(vty, "!\n");
1632
1633 for (i = 0; i < vector_active(cmdvec); i++)
1634 if ((node = vector_slot(cmdvec, i)) && node->config_write) {
1635 if ((*node->config_write)(vty))
1636 vty_out(vty, "!\n");
1637 }
1638
1639 if (vty->type == VTY_TERM) {
1640 vty_out(vty, "end\n");
1641 }
1642
1643 return CMD_SUCCESS;
1644 }
1645
1646 static int file_write_config(struct vty *vty)
1647 {
1648 int fd, dirfd;
1649 char *config_file, *slash;
1650 char *config_file_tmp = NULL;
1651 char *config_file_sav = NULL;
1652 int ret = CMD_WARNING;
1653 struct vty *file_vty;
1654 struct stat conf_stat;
1655
1656 if (host.noconfig)
1657 return CMD_SUCCESS;
1658
1659 /* Check and see if we are operating under vtysh configuration */
1660 if (host.config == NULL) {
1661 vty_out(vty,
1662 "Can't save to configuration file, using vtysh.\n");
1663 return CMD_WARNING;
1664 }
1665
1666 /* Get filename. */
1667 config_file = host.config;
1668
1669 #ifndef O_DIRECTORY
1670 #define O_DIRECTORY 0
1671 #endif
1672 slash = strrchr(config_file, '/');
1673 if (slash) {
1674 char *config_dir = XSTRDUP(MTYPE_TMP, config_file);
1675 config_dir[slash - config_file] = '\0';
1676 dirfd = open(config_dir, O_DIRECTORY | O_RDONLY);
1677 XFREE(MTYPE_TMP, config_dir);
1678 } else
1679 dirfd = open(".", O_DIRECTORY | O_RDONLY);
1680 /* if dirfd is invalid, directory sync fails, but we're still OK */
1681
1682 size_t config_file_sav_sz = strlen(config_file) + strlen(CONF_BACKUP_EXT) + 1;
1683 config_file_sav = XMALLOC(MTYPE_TMP, config_file_sav_sz);
1684 strlcpy(config_file_sav, config_file, config_file_sav_sz);
1685 strlcat(config_file_sav, CONF_BACKUP_EXT, config_file_sav_sz);
1686
1687
1688 config_file_tmp = XMALLOC(MTYPE_TMP, strlen(config_file) + 8);
1689 snprintf(config_file_tmp, strlen(config_file) + 8, "%s.XXXXXX",
1690 config_file);
1691
1692 /* Open file to configuration write. */
1693 fd = mkstemp(config_file_tmp);
1694 if (fd < 0) {
1695 vty_out(vty, "Can't open configuration file %s.\n",
1696 config_file_tmp);
1697 goto finished;
1698 }
1699 if (fchmod(fd, CONFIGFILE_MASK) != 0) {
1700 vty_out(vty, "Can't chmod configuration file %s: %s (%d).\n",
1701 config_file_tmp, safe_strerror(errno), errno);
1702 goto finished;
1703 }
1704
1705 /* Make vty for configuration file. */
1706 file_vty = vty_new();
1707 file_vty->wfd = fd;
1708 file_vty->type = VTY_FILE;
1709
1710 /* Config file header print. */
1711 vty_out(file_vty, "!\n! Zebra configuration saved from vty\n! ");
1712 vty_time_print(file_vty, 1);
1713 vty_out(file_vty, "!\n");
1714 vty_write_config(file_vty);
1715 vty_close(file_vty);
1716
1717 if (stat(config_file, &conf_stat) >= 0) {
1718 if (unlink(config_file_sav) != 0)
1719 if (errno != ENOENT) {
1720 vty_out(vty,
1721 "Can't unlink backup configuration file %s.\n",
1722 config_file_sav);
1723 goto finished;
1724 }
1725 if (link(config_file, config_file_sav) != 0) {
1726 vty_out(vty,
1727 "Can't backup old configuration file %s.\n",
1728 config_file_sav);
1729 goto finished;
1730 }
1731 if (dirfd >= 0)
1732 fsync(dirfd);
1733 }
1734 if (rename(config_file_tmp, config_file) != 0) {
1735 vty_out(vty, "Can't save configuration file %s.\n",
1736 config_file);
1737 goto finished;
1738 }
1739 if (dirfd >= 0)
1740 fsync(dirfd);
1741
1742 vty_out(vty, "Configuration saved to %s\n", config_file);
1743 ret = CMD_SUCCESS;
1744
1745 finished:
1746 if (ret != CMD_SUCCESS)
1747 unlink(config_file_tmp);
1748 if (dirfd >= 0)
1749 close(dirfd);
1750 XFREE(MTYPE_TMP, config_file_tmp);
1751 XFREE(MTYPE_TMP, config_file_sav);
1752 return ret;
1753 }
1754
1755 /* Write current configuration into file. */
1756
1757 DEFUN (config_write,
1758 config_write_cmd,
1759 "write [<file|memory|terminal>]",
1760 "Write running configuration to memory, network, or terminal\n"
1761 "Write to configuration file\n"
1762 "Write configuration currently in memory\n"
1763 "Write configuration to terminal\n")
1764 {
1765 const int idx_type = 1;
1766
1767 // if command was 'write terminal' or 'write memory'
1768 if (argc == 2 && (!strcmp(argv[idx_type]->text, "terminal"))) {
1769 return vty_write_config(vty);
1770 }
1771
1772 return file_write_config(vty);
1773 }
1774
1775 /* ALIAS_FIXME for 'write <terminal|memory>' */
1776 DEFUN (show_running_config,
1777 show_running_config_cmd,
1778 "show running-config",
1779 SHOW_STR
1780 "running configuration (same as write terminal)\n")
1781 {
1782 return vty_write_config(vty);
1783 }
1784
1785 /* ALIAS_FIXME for 'write file' */
1786 DEFUN (copy_runningconf_startupconf,
1787 copy_runningconf_startupconf_cmd,
1788 "copy running-config startup-config",
1789 "Copy configuration\n"
1790 "Copy running config to... \n"
1791 "Copy running config to startup config (same as write file/memory)\n")
1792 {
1793 return file_write_config(vty);
1794 }
1795 /** -- **/
1796
1797 /* Write startup configuration into the terminal. */
1798 DEFUN (show_startup_config,
1799 show_startup_config_cmd,
1800 "show startup-config",
1801 SHOW_STR
1802 "Contents of startup configuration\n")
1803 {
1804 char buf[BUFSIZ];
1805 FILE *confp;
1806
1807 if (host.noconfig)
1808 return CMD_SUCCESS;
1809 if (host.config == NULL)
1810 return CMD_WARNING;
1811
1812 confp = fopen(host.config, "r");
1813 if (confp == NULL) {
1814 vty_out(vty, "Can't open configuration file [%s] due to '%s'\n",
1815 host.config, safe_strerror(errno));
1816 return CMD_WARNING;
1817 }
1818
1819 while (fgets(buf, BUFSIZ, confp)) {
1820 char *cp = buf;
1821
1822 while (*cp != '\r' && *cp != '\n' && *cp != '\0')
1823 cp++;
1824 *cp = '\0';
1825
1826 vty_out(vty, "%s\n", buf);
1827 }
1828
1829 fclose(confp);
1830
1831 return CMD_SUCCESS;
1832 }
1833
1834 int cmd_domainname_set(const char *domainname)
1835 {
1836 XFREE(MTYPE_HOST, host.domainname);
1837 host.domainname = domainname ? XSTRDUP(MTYPE_HOST, domainname) : NULL;
1838 return CMD_SUCCESS;
1839 }
1840
1841 /* Hostname configuration */
1842 DEFUN(config_domainname,
1843 domainname_cmd,
1844 "domainname WORD",
1845 "Set system's domain name\n"
1846 "This system's domain name\n")
1847 {
1848 struct cmd_token *word = argv[1];
1849
1850 if (!isalpha((unsigned char)word->arg[0])) {
1851 vty_out(vty, "Please specify string starting with alphabet\n");
1852 return CMD_WARNING_CONFIG_FAILED;
1853 }
1854
1855 return cmd_domainname_set(word->arg);
1856 }
1857
1858 DEFUN(config_no_domainname,
1859 no_domainname_cmd,
1860 "no domainname [DOMAINNAME]",
1861 NO_STR
1862 "Reset system's domain name\n"
1863 "domain name of this router\n")
1864 {
1865 return cmd_domainname_set(NULL);
1866 }
1867
1868 int cmd_hostname_set(const char *hostname)
1869 {
1870 XFREE(MTYPE_HOST, host.name);
1871 host.name = hostname ? XSTRDUP(MTYPE_HOST, hostname) : NULL;
1872 return CMD_SUCCESS;
1873 }
1874
1875 /* Hostname configuration */
1876 DEFUN (config_hostname,
1877 hostname_cmd,
1878 "hostname WORD",
1879 "Set system's network name\n"
1880 "This system's network name\n")
1881 {
1882 struct cmd_token *word = argv[1];
1883
1884 if (!isalnum((unsigned char)word->arg[0])) {
1885 vty_out(vty,
1886 "Please specify string starting with alphabet or number\n");
1887 return CMD_WARNING_CONFIG_FAILED;
1888 }
1889
1890 /* With reference to RFC 1123 Section 2.1 */
1891 if (strlen(word->arg) > HOSTNAME_LEN) {
1892 vty_out(vty, "Hostname length should be less than %d chars\n",
1893 HOSTNAME_LEN);
1894 return CMD_WARNING_CONFIG_FAILED;
1895 }
1896
1897 return cmd_hostname_set(word->arg);
1898 }
1899
1900 DEFUN (config_no_hostname,
1901 no_hostname_cmd,
1902 "no hostname [HOSTNAME]",
1903 NO_STR
1904 "Reset system's network name\n"
1905 "Host name of this router\n")
1906 {
1907 return cmd_hostname_set(NULL);
1908 }
1909
1910 /* VTY interface password set. */
1911 DEFUN (config_password,
1912 password_cmd,
1913 "password [(8-8)] WORD",
1914 "Modify the terminal connection password\n"
1915 "Specifies a HIDDEN password will follow\n"
1916 "The password string\n")
1917 {
1918 int idx_8 = 1;
1919 int idx_word = 2;
1920 if (argc == 3) // '8' was specified
1921 {
1922 if (host.password)
1923 XFREE(MTYPE_HOST, host.password);
1924 host.password = NULL;
1925 if (host.password_encrypt)
1926 XFREE(MTYPE_HOST, host.password_encrypt);
1927 host.password_encrypt =
1928 XSTRDUP(MTYPE_HOST, argv[idx_word]->arg);
1929 return CMD_SUCCESS;
1930 }
1931
1932 if (!isalnum((unsigned char)argv[idx_8]->arg[0])) {
1933 vty_out(vty,
1934 "Please specify string starting with alphanumeric\n");
1935 return CMD_WARNING_CONFIG_FAILED;
1936 }
1937
1938 if (host.password)
1939 XFREE(MTYPE_HOST, host.password);
1940 host.password = NULL;
1941
1942 if (host.encrypt) {
1943 if (host.password_encrypt)
1944 XFREE(MTYPE_HOST, host.password_encrypt);
1945 host.password_encrypt =
1946 XSTRDUP(MTYPE_HOST, zencrypt(argv[idx_8]->arg));
1947 } else
1948 host.password = XSTRDUP(MTYPE_HOST, argv[idx_8]->arg);
1949
1950 return CMD_SUCCESS;
1951 }
1952
1953 /* VTY interface password delete. */
1954 DEFUN (no_config_password,
1955 no_password_cmd,
1956 "no password",
1957 NO_STR
1958 "Modify the terminal connection password\n")
1959 {
1960 bool warned = false;
1961
1962 if (host.password) {
1963 if (!vty_shell_serv(vty)) {
1964 vty_out(vty, NO_PASSWD_CMD_WARNING);
1965 warned = true;
1966 }
1967 XFREE(MTYPE_HOST, host.password);
1968 }
1969 host.password = NULL;
1970
1971 if (host.password_encrypt) {
1972 if (!warned && !vty_shell_serv(vty))
1973 vty_out(vty, NO_PASSWD_CMD_WARNING);
1974 XFREE(MTYPE_HOST, host.password_encrypt);
1975 }
1976 host.password_encrypt = NULL;
1977
1978 return CMD_SUCCESS;
1979 }
1980
1981 /* VTY enable password set. */
1982 DEFUN (config_enable_password,
1983 enable_password_cmd,
1984 "enable password [(8-8)] WORD",
1985 "Modify enable password parameters\n"
1986 "Assign the privileged level password\n"
1987 "Specifies a HIDDEN password will follow\n"
1988 "The HIDDEN 'enable' password string\n")
1989 {
1990 int idx_8 = 2;
1991 int idx_word = 3;
1992
1993 /* Crypt type is specified. */
1994 if (argc == 4) {
1995 if (argv[idx_8]->arg[0] == '8') {
1996 if (host.enable)
1997 XFREE(MTYPE_HOST, host.enable);
1998 host.enable = NULL;
1999
2000 if (host.enable_encrypt)
2001 XFREE(MTYPE_HOST, host.enable_encrypt);
2002 host.enable_encrypt =
2003 XSTRDUP(MTYPE_HOST, argv[idx_word]->arg);
2004
2005 return CMD_SUCCESS;
2006 } else {
2007 vty_out(vty, "Unknown encryption type.\n");
2008 return CMD_WARNING_CONFIG_FAILED;
2009 }
2010 }
2011
2012 if (!isalnum((unsigned char)argv[idx_8]->arg[0])) {
2013 vty_out(vty,
2014 "Please specify string starting with alphanumeric\n");
2015 return CMD_WARNING_CONFIG_FAILED;
2016 }
2017
2018 if (host.enable)
2019 XFREE(MTYPE_HOST, host.enable);
2020 host.enable = NULL;
2021
2022 /* Plain password input. */
2023 if (host.encrypt) {
2024 if (host.enable_encrypt)
2025 XFREE(MTYPE_HOST, host.enable_encrypt);
2026 host.enable_encrypt =
2027 XSTRDUP(MTYPE_HOST, zencrypt(argv[idx_8]->arg));
2028 } else
2029 host.enable = XSTRDUP(MTYPE_HOST, argv[idx_8]->arg);
2030
2031 return CMD_SUCCESS;
2032 }
2033
2034 /* VTY enable password delete. */
2035 DEFUN (no_config_enable_password,
2036 no_enable_password_cmd,
2037 "no enable password",
2038 NO_STR
2039 "Modify enable password parameters\n"
2040 "Assign the privileged level password\n")
2041 {
2042 bool warned = false;
2043
2044 if (host.enable) {
2045 if (!vty_shell_serv(vty)) {
2046 vty_out(vty, NO_PASSWD_CMD_WARNING);
2047 warned = true;
2048 }
2049 XFREE(MTYPE_HOST, host.enable);
2050 }
2051 host.enable = NULL;
2052
2053 if (host.enable_encrypt) {
2054 if (!warned && !vty_shell_serv(vty))
2055 vty_out(vty, NO_PASSWD_CMD_WARNING);
2056 XFREE(MTYPE_HOST, host.enable_encrypt);
2057 }
2058 host.enable_encrypt = NULL;
2059
2060 return CMD_SUCCESS;
2061 }
2062
2063 DEFUN (service_password_encrypt,
2064 service_password_encrypt_cmd,
2065 "service password-encryption",
2066 "Set up miscellaneous service\n"
2067 "Enable encrypted passwords\n")
2068 {
2069 if (host.encrypt)
2070 return CMD_SUCCESS;
2071
2072 host.encrypt = 1;
2073
2074 if (host.password) {
2075 if (host.password_encrypt)
2076 XFREE(MTYPE_HOST, host.password_encrypt);
2077 host.password_encrypt =
2078 XSTRDUP(MTYPE_HOST, zencrypt(host.password));
2079 }
2080 if (host.enable) {
2081 if (host.enable_encrypt)
2082 XFREE(MTYPE_HOST, host.enable_encrypt);
2083 host.enable_encrypt =
2084 XSTRDUP(MTYPE_HOST, zencrypt(host.enable));
2085 }
2086
2087 return CMD_SUCCESS;
2088 }
2089
2090 DEFUN (no_service_password_encrypt,
2091 no_service_password_encrypt_cmd,
2092 "no service password-encryption",
2093 NO_STR
2094 "Set up miscellaneous service\n"
2095 "Enable encrypted passwords\n")
2096 {
2097 if (!host.encrypt)
2098 return CMD_SUCCESS;
2099
2100 host.encrypt = 0;
2101
2102 if (host.password_encrypt)
2103 XFREE(MTYPE_HOST, host.password_encrypt);
2104 host.password_encrypt = NULL;
2105
2106 if (host.enable_encrypt)
2107 XFREE(MTYPE_HOST, host.enable_encrypt);
2108 host.enable_encrypt = NULL;
2109
2110 return CMD_SUCCESS;
2111 }
2112
2113 DEFUN (config_terminal_length,
2114 config_terminal_length_cmd,
2115 "terminal length (0-512)",
2116 "Set terminal line parameters\n"
2117 "Set number of lines on a screen\n"
2118 "Number of lines on screen (0 for no pausing)\n")
2119 {
2120 int idx_number = 2;
2121
2122 vty->lines = atoi(argv[idx_number]->arg);
2123
2124 return CMD_SUCCESS;
2125 }
2126
2127 DEFUN (config_terminal_no_length,
2128 config_terminal_no_length_cmd,
2129 "terminal no length",
2130 "Set terminal line parameters\n"
2131 NO_STR
2132 "Set number of lines on a screen\n")
2133 {
2134 vty->lines = -1;
2135 return CMD_SUCCESS;
2136 }
2137
2138 DEFUN (service_terminal_length,
2139 service_terminal_length_cmd,
2140 "service terminal-length (0-512)",
2141 "Set up miscellaneous service\n"
2142 "System wide terminal length configuration\n"
2143 "Number of lines of VTY (0 means no line control)\n")
2144 {
2145 int idx_number = 2;
2146
2147 host.lines = atoi(argv[idx_number]->arg);
2148
2149 return CMD_SUCCESS;
2150 }
2151
2152 DEFUN (no_service_terminal_length,
2153 no_service_terminal_length_cmd,
2154 "no service terminal-length [(0-512)]",
2155 NO_STR
2156 "Set up miscellaneous service\n"
2157 "System wide terminal length configuration\n"
2158 "Number of lines of VTY (0 means no line control)\n")
2159 {
2160 host.lines = -1;
2161 return CMD_SUCCESS;
2162 }
2163
2164 DEFUN_HIDDEN (do_echo,
2165 echo_cmd,
2166 "echo MESSAGE...",
2167 "Echo a message back to the vty\n"
2168 "The message to echo\n")
2169 {
2170 char *message;
2171
2172 vty_out(vty, "%s\n",
2173 ((message = argv_concat(argv, argc, 1)) ? message : ""));
2174 if (message)
2175 XFREE(MTYPE_TMP, message);
2176 return CMD_SUCCESS;
2177 }
2178
2179 DEFUN (config_logmsg,
2180 config_logmsg_cmd,
2181 "logmsg <emergencies|alerts|critical|errors|warnings|notifications|informational|debugging> MESSAGE...",
2182 "Send a message to enabled logging destinations\n"
2183 LOG_LEVEL_DESC
2184 "The message to send\n")
2185 {
2186 int idx_log_level = 1;
2187 int idx_message = 2;
2188 int level;
2189 char *message;
2190
2191 level = log_level_match(argv[idx_log_level]->arg);
2192 if (level == ZLOG_DISABLED)
2193 return CMD_ERR_NO_MATCH;
2194
2195 zlog(level, "%s",
2196 ((message = argv_concat(argv, argc, idx_message)) ? message : ""));
2197 if (message)
2198 XFREE(MTYPE_TMP, message);
2199
2200 return CMD_SUCCESS;
2201 }
2202
2203 DEFUN (debug_memstats,
2204 debug_memstats_cmd,
2205 "[no] debug memstats-at-exit",
2206 NO_STR
2207 DEBUG_STR
2208 "Print memory type statistics at exit\n")
2209 {
2210 debug_memstats_at_exit = !!strcmp(argv[0]->text, "no");
2211 return CMD_SUCCESS;
2212 }
2213
2214 int cmd_banner_motd_file(const char *file)
2215 {
2216 int success = CMD_SUCCESS;
2217 char p[PATH_MAX];
2218 char *rpath;
2219 char *in;
2220
2221 rpath = realpath(file, p);
2222 if (!rpath)
2223 return CMD_ERR_NO_FILE;
2224 in = strstr(rpath, SYSCONFDIR);
2225 if (in == rpath) {
2226 XFREE(MTYPE_HOST, host.motdfile);
2227 host.motdfile = XSTRDUP(MTYPE_HOST, file);
2228 } else
2229 success = CMD_WARNING_CONFIG_FAILED;
2230
2231 return success;
2232 }
2233
2234 void cmd_banner_motd_line(const char *line)
2235 {
2236 XFREE(MTYPE_HOST, host.motd);
2237 host.motd = XSTRDUP(MTYPE_HOST, line);
2238 }
2239
2240 DEFUN (banner_motd_file,
2241 banner_motd_file_cmd,
2242 "banner motd file FILE",
2243 "Set banner\n"
2244 "Banner for motd\n"
2245 "Banner from a file\n"
2246 "Filename\n")
2247 {
2248 int idx_file = 3;
2249 const char *filename = argv[idx_file]->arg;
2250 int cmd = cmd_banner_motd_file(filename);
2251
2252 if (cmd == CMD_ERR_NO_FILE)
2253 vty_out(vty, "%s does not exist\n", filename);
2254 else if (cmd == CMD_WARNING_CONFIG_FAILED)
2255 vty_out(vty, "%s must be in %s\n", filename, SYSCONFDIR);
2256
2257 return cmd;
2258 }
2259
2260 DEFUN (banner_motd_line,
2261 banner_motd_line_cmd,
2262 "banner motd line LINE...",
2263 "Set banner\n"
2264 "Banner for motd\n"
2265 "Banner from an input\n"
2266 "Text\n")
2267 {
2268 int idx = 0;
2269 char *motd;
2270
2271 argv_find(argv, argc, "LINE", &idx);
2272 motd = argv_concat(argv, argc, idx);
2273
2274 cmd_banner_motd_line(motd);
2275 XFREE(MTYPE_TMP, motd);
2276
2277 return CMD_SUCCESS;
2278 }
2279
2280 DEFUN (banner_motd_default,
2281 banner_motd_default_cmd,
2282 "banner motd default",
2283 "Set banner string\n"
2284 "Strings for motd\n"
2285 "Default string\n")
2286 {
2287 cmd_banner_motd_line(FRR_DEFAULT_MOTD);
2288 return CMD_SUCCESS;
2289 }
2290
2291 DEFUN (no_banner_motd,
2292 no_banner_motd_cmd,
2293 "no banner motd",
2294 NO_STR
2295 "Set banner string\n"
2296 "Strings for motd\n")
2297 {
2298 host.motd = NULL;
2299 if (host.motdfile)
2300 XFREE(MTYPE_HOST, host.motdfile);
2301 host.motdfile = NULL;
2302 return CMD_SUCCESS;
2303 }
2304
2305 DEFUN(allow_reserved_ranges, allow_reserved_ranges_cmd, "allow-reserved-ranges",
2306 "Allow using IPv4 (Class E) reserved IP space\n")
2307 {
2308 host.allow_reserved_ranges = true;
2309 return CMD_SUCCESS;
2310 }
2311
2312 DEFUN(no_allow_reserved_ranges, no_allow_reserved_ranges_cmd,
2313 "no allow-reserved-ranges",
2314 NO_STR "Allow using IPv4 (Class E) reserved IP space\n")
2315 {
2316 host.allow_reserved_ranges = false;
2317 return CMD_SUCCESS;
2318 }
2319
2320 int cmd_find_cmds(struct vty *vty, struct cmd_token **argv, int argc)
2321 {
2322 const struct cmd_node *node;
2323 const struct cmd_element *cli;
2324 vector clis;
2325
2326 regex_t exp = {};
2327
2328 char *pattern = argv_concat(argv, argc, 1);
2329 int cr = regcomp(&exp, pattern, REG_NOSUB | REG_EXTENDED);
2330 XFREE(MTYPE_TMP, pattern);
2331
2332 if (cr != 0) {
2333 switch (cr) {
2334 case REG_BADBR:
2335 vty_out(vty, "%% Invalid {...} expression\n");
2336 break;
2337 case REG_BADRPT:
2338 vty_out(vty, "%% Bad repetition operator\n");
2339 break;
2340 case REG_BADPAT:
2341 vty_out(vty, "%% Regex syntax error\n");
2342 break;
2343 case REG_ECOLLATE:
2344 vty_out(vty, "%% Invalid collating element\n");
2345 break;
2346 case REG_ECTYPE:
2347 vty_out(vty, "%% Invalid character class name\n");
2348 break;
2349 case REG_EESCAPE:
2350 vty_out(vty,
2351 "%% Regex ended with escape character (\\)\n");
2352 break;
2353 case REG_ESUBREG:
2354 vty_out(vty,
2355 "%% Invalid number in \\digit construction\n");
2356 break;
2357 case REG_EBRACK:
2358 vty_out(vty, "%% Unbalanced square brackets\n");
2359 break;
2360 case REG_EPAREN:
2361 vty_out(vty, "%% Unbalanced parentheses\n");
2362 break;
2363 case REG_EBRACE:
2364 vty_out(vty, "%% Unbalanced braces\n");
2365 break;
2366 case REG_ERANGE:
2367 vty_out(vty,
2368 "%% Invalid endpoint in range expression\n");
2369 break;
2370 case REG_ESPACE:
2371 vty_out(vty, "%% Failed to compile (out of memory)\n");
2372 break;
2373 }
2374
2375 goto done;
2376 }
2377
2378
2379 for (unsigned int i = 0; i < vector_active(cmdvec); i++) {
2380 node = vector_slot(cmdvec, i);
2381 if (!node)
2382 continue;
2383 clis = node->cmd_vector;
2384 for (unsigned int j = 0; j < vector_active(clis); j++) {
2385 cli = vector_slot(clis, j);
2386
2387 if (regexec(&exp, cli->string, 0, NULL, 0) == 0) {
2388 vty_out(vty, " (%s) ", node->name);
2389 print_cmd(vty, cli->string);
2390 }
2391 }
2392 }
2393
2394 done:
2395 regfree(&exp);
2396 return CMD_SUCCESS;
2397 }
2398
2399 DEFUN(find,
2400 find_cmd,
2401 "find REGEX...",
2402 "Find CLI command matching a regular expression\n"
2403 "Search pattern (POSIX regex)\n")
2404 {
2405 return cmd_find_cmds(vty, argv, argc);
2406 }
2407
2408 #if defined(DEV_BUILD) && defined(HAVE_SCRIPTING)
2409 DEFUN(script, script_cmd, "script SCRIPT FUNCTION",
2410 "Test command - execute a function in a script\n"
2411 "Script name (same as filename in /etc/frr/scripts/)\n"
2412 "Function name (in the script)\n")
2413 {
2414 struct prefix p;
2415
2416 (void)str2prefix("1.2.3.4/24", &p);
2417 struct frrscript *fs = frrscript_new(argv[1]->arg);
2418
2419 if (frrscript_load(fs, argv[2]->arg, NULL)) {
2420 vty_out(vty,
2421 "/etc/frr/scripts/%s.lua or function '%s' not found\n",
2422 argv[1]->arg, argv[2]->arg);
2423 }
2424
2425 int ret = frrscript_call(fs, argv[2]->arg, ("p", &p));
2426 char buf[40];
2427 prefix2str(&p, buf, sizeof(buf));
2428 vty_out(vty, "p: %s\n", buf);
2429 vty_out(vty, "Script result: %d\n", ret);
2430
2431 frrscript_delete(fs);
2432
2433 return CMD_SUCCESS;
2434 }
2435 #endif
2436
2437 /* Set config filename. Called from vty.c */
2438 void host_config_set(const char *filename)
2439 {
2440 XFREE(MTYPE_HOST, host.config);
2441 host.config = XSTRDUP(MTYPE_HOST, filename);
2442 }
2443
2444 const char *host_config_get(void)
2445 {
2446 return host.config;
2447 }
2448
2449 void cmd_show_lib_debugs(struct vty *vty)
2450 {
2451 route_map_show_debug(vty);
2452 mgmt_debug_be_client_show_debug(vty);
2453 mgmt_debug_fe_client_show_debug(vty);
2454 }
2455
2456 void install_default(enum node_type node)
2457 {
2458 _install_element(node, &config_exit_cmd);
2459 _install_element(node, &config_quit_cmd);
2460 _install_element(node, &config_end_cmd);
2461 _install_element(node, &config_help_cmd);
2462 _install_element(node, &config_list_cmd);
2463 _install_element(node, &show_cli_graph_cmd);
2464 _install_element(node, &find_cmd);
2465
2466 _install_element(node, &config_write_cmd);
2467 _install_element(node, &show_running_config_cmd);
2468
2469 _install_element(node, &autocomplete_cmd);
2470
2471 nb_cli_install_default(node);
2472 }
2473
2474 /* Initialize command interface. Install basic nodes and commands.
2475 *
2476 * terminal = 0 -- vtysh / no logging, no config control
2477 * terminal = 1 -- normal daemon
2478 * terminal = -1 -- watchfrr / no logging, but minimal config control */
2479 void cmd_init(int terminal)
2480 {
2481 struct utsname names;
2482
2483 uname(&names);
2484 qobj_init();
2485
2486 /* register command preprocessors */
2487 hook_register(cmd_execute, handle_pipe_action);
2488 hook_register(cmd_execute_done, handle_pipe_action_done);
2489
2490 varhandlers = list_new();
2491
2492 /* Allocate initial top vector of commands. */
2493 cmdvec = vector_init(VECTOR_MIN_SIZE);
2494
2495 /* Default host value settings. */
2496 host.name = XSTRDUP(MTYPE_HOST, names.nodename);
2497 host.system = XSTRDUP(MTYPE_HOST, names.sysname);
2498 host.release = XSTRDUP(MTYPE_HOST, names.release);
2499 host.version = XSTRDUP(MTYPE_HOST, names.version);
2500
2501 #ifdef HAVE_STRUCT_UTSNAME_DOMAINNAME
2502 if ((strcmp(names.domainname, "(none)") == 0))
2503 host.domainname = NULL;
2504 else
2505 host.domainname = XSTRDUP(MTYPE_HOST, names.domainname);
2506 #else
2507 host.domainname = NULL;
2508 #endif
2509 host.password = NULL;
2510 host.enable = NULL;
2511 host.config = NULL;
2512 host.noconfig = (terminal < 0);
2513 host.lines = -1;
2514 cmd_banner_motd_line(FRR_DEFAULT_MOTD);
2515 host.motdfile = NULL;
2516 host.allow_reserved_ranges = false;
2517
2518 /* Install top nodes. */
2519 install_node(&view_node);
2520 install_node(&enable_node);
2521 install_node(&auth_node);
2522 install_node(&auth_enable_node);
2523 install_node(&config_node);
2524
2525 /* Each node's basic commands. */
2526 install_element(VIEW_NODE, &show_version_cmd);
2527 install_element(ENABLE_NODE, &show_startup_config_cmd);
2528
2529 if (terminal) {
2530 install_element(ENABLE_NODE, &debug_memstats_cmd);
2531
2532 install_element(VIEW_NODE, &config_list_cmd);
2533 install_element(VIEW_NODE, &config_exit_cmd);
2534 install_element(VIEW_NODE, &config_quit_cmd);
2535 install_element(VIEW_NODE, &config_help_cmd);
2536 install_element(VIEW_NODE, &config_enable_cmd);
2537 install_element(VIEW_NODE, &config_terminal_length_cmd);
2538 install_element(VIEW_NODE, &config_terminal_no_length_cmd);
2539 install_element(VIEW_NODE, &show_commandtree_cmd);
2540 install_element(VIEW_NODE, &echo_cmd);
2541 install_element(VIEW_NODE, &autocomplete_cmd);
2542 install_element(VIEW_NODE, &find_cmd);
2543 #if defined(DEV_BUILD) && defined(HAVE_SCRIPTING)
2544 install_element(VIEW_NODE, &script_cmd);
2545 #endif
2546
2547
2548 install_element(ENABLE_NODE, &config_end_cmd);
2549 install_element(ENABLE_NODE, &config_disable_cmd);
2550 install_element(ENABLE_NODE, &config_terminal_cmd);
2551 install_element(ENABLE_NODE, &copy_runningconf_startupconf_cmd);
2552 install_element(ENABLE_NODE, &config_write_cmd);
2553 install_element(ENABLE_NODE, &show_running_config_cmd);
2554 install_element(ENABLE_NODE, &config_logmsg_cmd);
2555
2556 install_default(CONFIG_NODE);
2557
2558 event_cmd_init();
2559 workqueue_cmd_init();
2560 hash_cmd_init();
2561 }
2562
2563 install_element(CONFIG_NODE, &hostname_cmd);
2564 install_element(CONFIG_NODE, &no_hostname_cmd);
2565 install_element(CONFIG_NODE, &domainname_cmd);
2566 install_element(CONFIG_NODE, &no_domainname_cmd);
2567
2568 if (terminal > 0) {
2569 full_cli = true;
2570
2571 install_element(CONFIG_NODE, &debug_memstats_cmd);
2572
2573 install_element(CONFIG_NODE, &password_cmd);
2574 install_element(CONFIG_NODE, &no_password_cmd);
2575 install_element(CONFIG_NODE, &enable_password_cmd);
2576 install_element(CONFIG_NODE, &no_enable_password_cmd);
2577
2578 install_element(CONFIG_NODE, &service_password_encrypt_cmd);
2579 install_element(CONFIG_NODE, &no_service_password_encrypt_cmd);
2580 install_element(CONFIG_NODE, &banner_motd_default_cmd);
2581 install_element(CONFIG_NODE, &banner_motd_file_cmd);
2582 install_element(CONFIG_NODE, &banner_motd_line_cmd);
2583 install_element(CONFIG_NODE, &no_banner_motd_cmd);
2584 install_element(CONFIG_NODE, &service_terminal_length_cmd);
2585 install_element(CONFIG_NODE, &no_service_terminal_length_cmd);
2586 install_element(CONFIG_NODE, &allow_reserved_ranges_cmd);
2587 install_element(CONFIG_NODE, &no_allow_reserved_ranges_cmd);
2588
2589 log_cmd_init();
2590 vrf_install_commands();
2591 }
2592
2593 #ifdef DEV_BUILD
2594 grammar_sandbox_init();
2595 #endif
2596 }
2597
2598 void cmd_terminate(void)
2599 {
2600 struct cmd_node *cmd_node;
2601
2602 hook_unregister(cmd_execute, handle_pipe_action);
2603 hook_unregister(cmd_execute_done, handle_pipe_action_done);
2604
2605 if (cmdvec) {
2606 for (unsigned int i = 0; i < vector_active(cmdvec); i++)
2607 if ((cmd_node = vector_slot(cmdvec, i)) != NULL) {
2608 // deleting the graph delets the cmd_element as
2609 // well
2610 graph_delete_graph(cmd_node->cmdgraph);
2611 vector_free(cmd_node->cmd_vector);
2612 hash_clean_and_free(&cmd_node->cmd_hash, NULL);
2613 }
2614
2615 vector_free(cmdvec);
2616 cmdvec = NULL;
2617 }
2618
2619 XFREE(MTYPE_HOST, host.name);
2620 XFREE(MTYPE_HOST, host.system);
2621 XFREE(MTYPE_HOST, host.release);
2622 XFREE(MTYPE_HOST, host.version);
2623 XFREE(MTYPE_HOST, host.domainname);
2624 XFREE(MTYPE_HOST, host.password);
2625 XFREE(MTYPE_HOST, host.password_encrypt);
2626 XFREE(MTYPE_HOST, host.enable);
2627 XFREE(MTYPE_HOST, host.enable_encrypt);
2628 XFREE(MTYPE_HOST, host.motdfile);
2629 XFREE(MTYPE_HOST, host.config);
2630 XFREE(MTYPE_HOST, host.motd);
2631
2632 list_delete(&varhandlers);
2633 qobj_finish();
2634 }