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