]> git.proxmox.com Git - mirror_frr.git/blob - lib/command.c
Merge pull request #11530 from ARShreenidhi/default_originate_testcase
[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 bool cmd_allow_reserved_ranges_get(void)
125 {
126 return host.allow_reserved_ranges;
127 }
128
129 static int root_on_exit(struct vty *vty);
130
131 /* Standard command node structures. */
132 static struct cmd_node auth_node = {
133 .name = "auth",
134 .node = AUTH_NODE,
135 .prompt = "Password: ",
136 };
137
138 static struct cmd_node view_node = {
139 .name = "view",
140 .node = VIEW_NODE,
141 .prompt = "%s> ",
142 .node_exit = root_on_exit,
143 };
144
145 static struct cmd_node auth_enable_node = {
146 .name = "auth enable",
147 .node = AUTH_ENABLE_NODE,
148 .prompt = "Password: ",
149 };
150
151 static struct cmd_node enable_node = {
152 .name = "enable",
153 .node = ENABLE_NODE,
154 .prompt = "%s# ",
155 .node_exit = root_on_exit,
156 };
157
158 static int config_write_host(struct vty *vty);
159 static struct cmd_node config_node = {
160 .name = "config",
161 .node = CONFIG_NODE,
162 .parent_node = ENABLE_NODE,
163 .prompt = "%s(config)# ",
164 .config_write = config_write_host,
165 .node_exit = vty_config_node_exit,
166 };
167
168 /* This is called from main when a daemon is invoked with -v or --version. */
169 void print_version(const char *progname)
170 {
171 printf("%s version %s\n", progname, FRR_VERSION);
172 printf("%s\n", FRR_COPYRIGHT);
173 #ifdef ENABLE_VERSION_BUILD_CONFIG
174 printf("configured with:\n\t%s\n", FRR_CONFIG_ARGS);
175 #endif
176 }
177
178 char *argv_concat(struct cmd_token **argv, int argc, int shift)
179 {
180 int cnt = MAX(argc - shift, 0);
181 const char *argstr[cnt + 1];
182
183 if (!cnt)
184 return NULL;
185
186 for (int i = 0; i < cnt; i++)
187 argstr[i] = argv[i + shift]->arg;
188
189 return frrstr_join(argstr, cnt, " ");
190 }
191
192 vector cmd_make_strvec(const char *string)
193 {
194 if (!string)
195 return NULL;
196
197 const char *copy = string;
198
199 /* skip leading whitespace */
200 while (isspace((unsigned char)*copy) && *copy != '\0')
201 copy++;
202
203 /* if the entire string was whitespace or a comment, return */
204 if (*copy == '\0' || *copy == '!' || *copy == '#')
205 return NULL;
206
207 vector result = frrstr_split_vec(copy, "\n\r\t ");
208
209 for (unsigned int i = 0; i < vector_active(result); i++) {
210 if (strlen(vector_slot(result, i)) == 0) {
211 XFREE(MTYPE_TMP, vector_slot(result, i));
212 vector_unset(result, i);
213 }
214 }
215
216 vector_compact(result);
217
218 return result;
219 }
220
221 void cmd_free_strvec(vector v)
222 {
223 frrstr_strvec_free(v);
224 }
225
226 /**
227 * Convenience function for accessing argv data.
228 *
229 * @param argc
230 * @param argv
231 * @param text definition snippet of the desired token
232 * @param index the starting index, and where to store the
233 * index of the found token if it exists
234 * @return 1 if found, 0 otherwise
235 */
236 int argv_find(struct cmd_token **argv, int argc, const char *text, int *index)
237 {
238 int found = 0;
239 for (int i = *index; i < argc && found == 0; i++)
240 if ((found = strmatch(text, argv[i]->text)))
241 *index = i;
242 return found;
243 }
244
245 static unsigned int cmd_hash_key(const void *p)
246 {
247 int size = sizeof(p);
248
249 return jhash(p, size, 0);
250 }
251
252 static bool cmd_hash_cmp(const void *a, const void *b)
253 {
254 return a == b;
255 }
256
257 /* Install top node of command vector. */
258 void install_node(struct cmd_node *node)
259 {
260 #define CMD_HASH_STR_SIZE 256
261 char hash_name[CMD_HASH_STR_SIZE];
262
263 vector_set_index(cmdvec, node->node, node);
264 node->cmdgraph = graph_new();
265 node->cmd_vector = vector_init(VECTOR_MIN_SIZE);
266 // add start node
267 struct cmd_token *token =
268 cmd_token_new(START_TKN, CMD_ATTR_NORMAL, NULL, NULL);
269 graph_new_node(node->cmdgraph, token,
270 (void (*)(void *)) & cmd_token_del);
271
272 snprintf(hash_name, sizeof(hash_name), "Command Hash: %s", node->name);
273 node->cmd_hash =
274 hash_create_size(16, cmd_hash_key, cmd_hash_cmp, hash_name);
275 }
276
277 /* Return prompt character of specified node. */
278 const char *cmd_prompt(enum node_type node)
279 {
280 struct cmd_node *cnode;
281
282 cnode = vector_slot(cmdvec, node);
283 return cnode->prompt;
284 }
285
286 void cmd_defer_tree(bool val)
287 {
288 defer_cli_tree = val;
289 }
290
291 /* Install a command into a node. */
292 void _install_element(enum node_type ntype, const struct cmd_element *cmd)
293 {
294 struct cmd_node *cnode;
295
296 /* cmd_init hasn't been called */
297 if (!cmdvec) {
298 fprintf(stderr, "%s called before cmd_init, breakage likely\n",
299 __func__);
300 return;
301 }
302
303 cnode = vector_lookup(cmdvec, ntype);
304
305 if (cnode == NULL) {
306 fprintf(stderr,
307 "%s[%s]:\n"
308 "\tnode %d does not exist.\n"
309 "\tplease call install_node() before install_element()\n",
310 cmd->name, cmd->string, ntype);
311 exit(EXIT_FAILURE);
312 }
313
314 if (hash_lookup(cnode->cmd_hash, (void *)cmd) != NULL) {
315 fprintf(stderr,
316 "%s[%s]:\n"
317 "\tnode %d (%s) already has this command installed.\n"
318 "\tduplicate install_element call?\n",
319 cmd->name, cmd->string, ntype, cnode->name);
320 return;
321 }
322
323 (void)hash_get(cnode->cmd_hash, (void *)cmd, hash_alloc_intern);
324
325 if (cnode->graph_built || !defer_cli_tree) {
326 struct graph *graph = graph_new();
327 struct cmd_token *token =
328 cmd_token_new(START_TKN, CMD_ATTR_NORMAL, NULL, NULL);
329 graph_new_node(graph, token,
330 (void (*)(void *)) & cmd_token_del);
331
332 cmd_graph_parse(graph, cmd);
333 cmd_graph_names(graph);
334 cmd_graph_merge(cnode->cmdgraph, graph, +1);
335 graph_delete_graph(graph);
336
337 cnode->graph_built = true;
338 }
339
340 vector_set(cnode->cmd_vector, (void *)cmd);
341
342 if (ntype == VIEW_NODE)
343 _install_element(ENABLE_NODE, cmd);
344 }
345
346 static void cmd_finalize_iter(struct hash_bucket *hb, void *arg)
347 {
348 struct cmd_node *cnode = arg;
349 const struct cmd_element *cmd = hb->data;
350 struct graph *graph = graph_new();
351 struct cmd_token *token =
352 cmd_token_new(START_TKN, CMD_ATTR_NORMAL, NULL, NULL);
353
354 graph_new_node(graph, token, (void (*)(void *)) & cmd_token_del);
355
356 cmd_graph_parse(graph, cmd);
357 cmd_graph_names(graph);
358 cmd_graph_merge(cnode->cmdgraph, graph, +1);
359 graph_delete_graph(graph);
360 }
361
362 void cmd_finalize_node(struct cmd_node *cnode)
363 {
364 if (cnode->graph_built)
365 return;
366
367 hash_iterate(cnode->cmd_hash, cmd_finalize_iter, cnode);
368 cnode->graph_built = true;
369 }
370
371 void uninstall_element(enum node_type ntype, const struct cmd_element *cmd)
372 {
373 struct cmd_node *cnode;
374
375 /* cmd_init hasn't been called */
376 if (!cmdvec) {
377 fprintf(stderr, "%s called before cmd_init, breakage likely\n",
378 __func__);
379 return;
380 }
381
382 cnode = vector_lookup(cmdvec, ntype);
383
384 if (cnode == NULL) {
385 fprintf(stderr,
386 "%s[%s]:\n"
387 "\tnode %d does not exist.\n"
388 "\tplease call install_node() before uninstall_element()\n",
389 cmd->name, cmd->string, ntype);
390 exit(EXIT_FAILURE);
391 }
392
393 if (hash_release(cnode->cmd_hash, (void *)cmd) == NULL) {
394 fprintf(stderr,
395 "%s[%s]:\n"
396 "\tnode %d (%s) does not have this command installed.\n"
397 "\tduplicate uninstall_element call?\n",
398 cmd->name, cmd->string, ntype, cnode->name);
399 return;
400 }
401
402 vector_unset_value(cnode->cmd_vector, (void *)cmd);
403
404 if (cnode->graph_built) {
405 struct graph *graph = graph_new();
406 struct cmd_token *token =
407 cmd_token_new(START_TKN, CMD_ATTR_NORMAL, NULL, NULL);
408 graph_new_node(graph, token,
409 (void (*)(void *)) & cmd_token_del);
410
411 cmd_graph_parse(graph, cmd);
412 cmd_graph_names(graph);
413 cmd_graph_merge(cnode->cmdgraph, graph, -1);
414 graph_delete_graph(graph);
415 }
416
417 if (ntype == VIEW_NODE)
418 uninstall_element(ENABLE_NODE, cmd);
419 }
420
421
422 static const unsigned char itoa64[] =
423 "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
424
425 static void to64(char *s, long v, int n)
426 {
427 while (--n >= 0) {
428 *s++ = itoa64[v & 0x3f];
429 v >>= 6;
430 }
431 }
432
433 static char *zencrypt(const char *passwd)
434 {
435 char salt[6];
436 struct timeval tv;
437
438 gettimeofday(&tv, 0);
439
440 to64(&salt[0], frr_weak_random(), 3);
441 to64(&salt[3], tv.tv_usec, 3);
442 salt[5] = '\0';
443
444 return crypt(passwd, salt);
445 }
446
447 static bool full_cli;
448
449 /* This function write configuration of this host. */
450 static int config_write_host(struct vty *vty)
451 {
452 const char *name;
453
454 name = cmd_hostname_get();
455 if (name && name[0] != '\0')
456 vty_out(vty, "hostname %s\n", name);
457
458 name = cmd_domainname_get();
459 if (name && name[0] != '\0')
460 vty_out(vty, "domainname %s\n", name);
461
462 if (cmd_allow_reserved_ranges_get())
463 vty_out(vty, "allow-reserved-ranges\n");
464
465 /* The following are all configuration commands that are not sent to
466 * watchfrr. For instance watchfrr is hardcoded to log to syslog so
467 * we would always display 'log syslog informational' in the config
468 * which would cause other daemons to then switch to syslog when they
469 * parse frr.conf.
470 */
471 if (full_cli) {
472 if (host.encrypt) {
473 if (host.password_encrypt)
474 vty_out(vty, "password 8 %s\n",
475 host.password_encrypt);
476 if (host.enable_encrypt)
477 vty_out(vty, "enable password 8 %s\n",
478 host.enable_encrypt);
479 } else {
480 if (host.password)
481 vty_out(vty, "password %s\n", host.password);
482 if (host.enable)
483 vty_out(vty, "enable password %s\n",
484 host.enable);
485 }
486 log_config_write(vty);
487
488 /* print disable always, but enable only if default is flipped
489 * => prep for future removal of compile-time knob
490 */
491 if (!cputime_enabled)
492 vty_out(vty, "no service cputime-stats\n");
493 #ifdef EXCLUDE_CPU_TIME
494 else
495 vty_out(vty, "service cputime-stats\n");
496 #endif
497
498 if (!cputime_threshold)
499 vty_out(vty, "no service cputime-warning\n");
500 #if defined(CONSUMED_TIME_CHECK) && CONSUMED_TIME_CHECK != 5000000
501 else /* again, always print non-default */
502 #else
503 else if (cputime_threshold != 5000000)
504 #endif
505 vty_out(vty, "service cputime-warning %lu\n",
506 cputime_threshold);
507
508 if (!walltime_threshold)
509 vty_out(vty, "no service walltime-warning\n");
510 #if defined(CONSUMED_TIME_CHECK) && CONSUMED_TIME_CHECK != 5000000
511 else /* again, always print non-default */
512 #else
513 else if (walltime_threshold != 5000000)
514 #endif
515 vty_out(vty, "service walltime-warning %lu\n",
516 walltime_threshold);
517
518 if (host.advanced)
519 vty_out(vty, "service advanced-vty\n");
520
521 if (host.encrypt)
522 vty_out(vty, "service password-encryption\n");
523
524 if (host.lines >= 0)
525 vty_out(vty, "service terminal-length %d\n",
526 host.lines);
527
528 if (host.motdfile)
529 vty_out(vty, "banner motd file %s\n", host.motdfile);
530 else if (host.motd
531 && strncmp(host.motd, FRR_DEFAULT_MOTD,
532 strlen(host.motd)))
533 vty_out(vty, "banner motd line %s\n", host.motd);
534 else if (!host.motd)
535 vty_out(vty, "no banner motd\n");
536 }
537
538 if (debug_memstats_at_exit)
539 vty_out(vty, "!\ndebug memstats-at-exit\n");
540
541 return 1;
542 }
543
544 /* Utility function for getting command graph. */
545 static struct graph *cmd_node_graph(vector v, enum node_type ntype)
546 {
547 struct cmd_node *cnode = vector_slot(v, ntype);
548
549 cmd_finalize_node(cnode);
550 return cnode->cmdgraph;
551 }
552
553 static int cmd_try_do_shortcut(enum node_type node, char *first_word)
554 {
555 if (first_word != NULL && node != AUTH_NODE && node != VIEW_NODE
556 && node != AUTH_ENABLE_NODE && 0 == strcmp("do", first_word))
557 return 1;
558 return 0;
559 }
560
561 /**
562 * Compare function for cmd_token.
563 * Used with qsort to sort command completions.
564 */
565 static int compare_completions(const void *fst, const void *snd)
566 {
567 const struct cmd_token *first = *(const struct cmd_token * const *)fst,
568 *secnd = *(const struct cmd_token * const *)snd;
569 return strcmp(first->text, secnd->text);
570 }
571
572 /**
573 * Takes a list of completions returned by command_complete,
574 * dedeuplicates them based on both text and description,
575 * sorts them, and returns them as a vector.
576 *
577 * @param completions linked list of cmd_token
578 * @return deduplicated and sorted vector with
579 */
580 vector completions_to_vec(struct list *completions)
581 {
582 vector comps = vector_init(VECTOR_MIN_SIZE);
583
584 struct listnode *ln;
585 struct cmd_token *token, *cr = NULL;
586 unsigned int i, exists;
587 for (ALL_LIST_ELEMENTS_RO(completions, ln, token)) {
588 if (token->type == END_TKN && (cr = token))
589 continue;
590
591 // linear search for token in completions vector
592 exists = 0;
593 for (i = 0; i < vector_active(comps) && !exists; i++) {
594 struct cmd_token *curr = vector_slot(comps, i);
595 #ifdef VTYSH_DEBUG
596 exists = !strcmp(curr->text, token->text)
597 && !strcmp(curr->desc, token->desc);
598 #else
599 exists = !strcmp(curr->text, token->text);
600 #endif /* VTYSH_DEBUG */
601 }
602
603 if (!exists)
604 vector_set(comps, token);
605 }
606
607 // sort completions
608 qsort(comps->index, vector_active(comps), sizeof(void *),
609 &compare_completions);
610
611 // make <cr> the first element, if it is present
612 if (cr) {
613 vector_set_index(comps, vector_active(comps), NULL);
614 memmove(comps->index + 1, comps->index,
615 (comps->alloced - 1) * sizeof(void *));
616 vector_set_index(comps, 0, cr);
617 }
618
619 return comps;
620 }
621 /**
622 * Generates a vector of cmd_token representing possible completions
623 * on the current input.
624 *
625 * @param vline the vectorized input line
626 * @param vty the vty with the node to match on
627 * @param status pointer to matcher status code
628 * @return vector of struct cmd_token * with possible completions
629 */
630 static vector cmd_complete_command_real(vector vline, struct vty *vty,
631 int *status)
632 {
633 struct list *completions;
634 struct graph *cmdgraph = cmd_node_graph(cmdvec, vty->node);
635
636 enum matcher_rv rv = command_complete(cmdgraph, vline, &completions);
637
638 if (MATCHER_ERROR(rv)) {
639 *status = CMD_ERR_NO_MATCH;
640 return NULL;
641 }
642
643 vector comps = completions_to_vec(completions);
644 list_delete(&completions);
645
646 // set status code appropriately
647 switch (vector_active(comps)) {
648 case 0:
649 *status = CMD_ERR_NO_MATCH;
650 break;
651 case 1:
652 *status = CMD_COMPLETE_FULL_MATCH;
653 break;
654 default:
655 *status = CMD_COMPLETE_LIST_MATCH;
656 }
657
658 return comps;
659 }
660
661 vector cmd_describe_command(vector vline, struct vty *vty, int *status)
662 {
663 vector ret;
664
665 if (cmd_try_do_shortcut(vty->node, vector_slot(vline, 0))) {
666 enum node_type onode;
667 int orig_xpath_index;
668 vector shifted_vline;
669 unsigned int index;
670
671 onode = vty->node;
672 orig_xpath_index = vty->xpath_index;
673 vty->node = ENABLE_NODE;
674 vty->xpath_index = 0;
675 /* We can try it on enable node, cos' the vty is authenticated
676 */
677
678 shifted_vline = vector_init(vector_count(vline));
679 /* use memcpy? */
680 for (index = 1; index < vector_active(vline); index++) {
681 vector_set_index(shifted_vline, index - 1,
682 vector_lookup(vline, index));
683 }
684
685 ret = cmd_complete_command_real(shifted_vline, vty, status);
686
687 vector_free(shifted_vline);
688 vty->node = onode;
689 vty->xpath_index = orig_xpath_index;
690 return ret;
691 }
692
693 return cmd_complete_command_real(vline, vty, status);
694 }
695
696 static struct list *varhandlers = NULL;
697
698 void cmd_variable_complete(struct cmd_token *token, const char *arg,
699 vector comps)
700 {
701 struct listnode *ln;
702 const struct cmd_variable_handler *cvh;
703 size_t i, argsz;
704 vector tmpcomps;
705
706 tmpcomps = arg ? vector_init(VECTOR_MIN_SIZE) : comps;
707
708 for (ALL_LIST_ELEMENTS_RO(varhandlers, ln, cvh)) {
709 if (cvh->tokenname && strcmp(cvh->tokenname, token->text))
710 continue;
711 if (cvh->varname && (!token->varname
712 || strcmp(cvh->varname, token->varname)))
713 continue;
714 cvh->completions(tmpcomps, token);
715 break;
716 }
717
718 if (!arg)
719 return;
720
721 argsz = strlen(arg);
722 for (i = vector_active(tmpcomps); i; i--) {
723 char *item = vector_slot(tmpcomps, i - 1);
724 if (strlen(item) >= argsz && !strncmp(item, arg, argsz))
725 vector_set(comps, item);
726 else
727 XFREE(MTYPE_COMPLETION, item);
728 }
729 vector_free(tmpcomps);
730 }
731
732 #define AUTOCOMP_INDENT 5
733
734 char *cmd_variable_comp2str(vector comps, unsigned short cols)
735 {
736 size_t bsz = 16;
737 char *buf = XCALLOC(MTYPE_TMP, bsz);
738 int lc = AUTOCOMP_INDENT;
739 size_t cs = AUTOCOMP_INDENT;
740 size_t itemlen;
741 snprintf(buf, bsz, "%*s", AUTOCOMP_INDENT, "");
742 for (size_t j = 0; j < vector_active(comps); j++) {
743 char *item = vector_slot(comps, j);
744 itemlen = strlen(item);
745
746 if (cs + itemlen + AUTOCOMP_INDENT + 3 >= bsz)
747 buf = XREALLOC(MTYPE_TMP, buf, (bsz *= 2));
748
749 if (lc + itemlen + 1 >= cols) {
750 cs += snprintf(&buf[cs], bsz - cs, "\n%*s",
751 AUTOCOMP_INDENT, "");
752 lc = AUTOCOMP_INDENT;
753 }
754
755 size_t written = snprintf(&buf[cs], bsz - cs, "%s ", item);
756 lc += written;
757 cs += written;
758 XFREE(MTYPE_COMPLETION, item);
759 vector_set_index(comps, j, NULL);
760 }
761 return buf;
762 }
763
764 void cmd_variable_handler_register(const struct cmd_variable_handler *cvh)
765 {
766 if (!varhandlers)
767 return;
768
769 for (; cvh->completions; cvh++)
770 listnode_add(varhandlers, (void *)cvh);
771 }
772
773 DEFUN_HIDDEN (autocomplete,
774 autocomplete_cmd,
775 "autocomplete TYPE TEXT VARNAME",
776 "Autocompletion handler (internal, for vtysh)\n"
777 "cmd_token->type\n"
778 "cmd_token->text\n"
779 "cmd_token->varname\n")
780 {
781 struct cmd_token tok;
782 vector comps = vector_init(32);
783 size_t i;
784
785 memset(&tok, 0, sizeof(tok));
786 tok.type = atoi(argv[1]->arg);
787 tok.text = argv[2]->arg;
788 tok.varname = argv[3]->arg;
789 if (!strcmp(tok.varname, "-"))
790 tok.varname = NULL;
791
792 cmd_variable_complete(&tok, NULL, comps);
793
794 for (i = 0; i < vector_active(comps); i++) {
795 char *text = vector_slot(comps, i);
796 vty_out(vty, "%s\n", text);
797 XFREE(MTYPE_COMPLETION, text);
798 }
799
800 vector_free(comps);
801 return CMD_SUCCESS;
802 }
803
804 /**
805 * Generate possible tab-completions for the given input. This function only
806 * returns results that would result in a valid command if used as Readline
807 * completions (as is the case in vtysh). For instance, if the passed vline ends
808 * with '4.3.2', the strings 'A.B.C.D' and 'A.B.C.D/M' will _not_ be returned.
809 *
810 * @param vline vectorized input line
811 * @param vty the vty
812 * @param status location to store matcher status code in
813 * @return set of valid strings for use with Readline as tab-completions.
814 */
815
816 char **cmd_complete_command(vector vline, struct vty *vty, int *status)
817 {
818 char **ret = NULL;
819 int original_node = vty->node;
820 vector input_line = vector_init(vector_count(vline));
821
822 // if the first token is 'do' we'll want to execute the command in the
823 // enable node
824 int do_shortcut = cmd_try_do_shortcut(vty->node, vector_slot(vline, 0));
825 vty->node = do_shortcut ? ENABLE_NODE : original_node;
826
827 // construct the input line we'll be matching on
828 unsigned int offset = (do_shortcut) ? 1 : 0;
829 for (unsigned index = 0; index + offset < vector_active(vline); index++)
830 vector_set_index(input_line, index,
831 vector_lookup(vline, index + offset));
832
833 // get token completions -- this is a copying operation
834 vector comps = NULL, initial_comps;
835 initial_comps = cmd_complete_command_real(input_line, vty, status);
836
837 if (!MATCHER_ERROR(*status)) {
838 assert(initial_comps);
839 // filter out everything that is not suitable for a
840 // tab-completion
841 comps = vector_init(VECTOR_MIN_SIZE);
842 for (unsigned int i = 0; i < vector_active(initial_comps);
843 i++) {
844 struct cmd_token *token = vector_slot(initial_comps, i);
845 if (token->type == WORD_TKN)
846 vector_set(comps, XSTRDUP(MTYPE_COMPLETION,
847 token->text));
848 else if (IS_VARYING_TOKEN(token->type)) {
849 const char *ref = vector_lookup(
850 vline, vector_active(vline) - 1);
851 cmd_variable_complete(token, ref, comps);
852 }
853 }
854 vector_free(initial_comps);
855
856 // since we filtered results, we need to re-set status code
857 switch (vector_active(comps)) {
858 case 0:
859 *status = CMD_ERR_NO_MATCH;
860 break;
861 case 1:
862 *status = CMD_COMPLETE_FULL_MATCH;
863 break;
864 default:
865 *status = CMD_COMPLETE_LIST_MATCH;
866 }
867
868 // copy completions text into an array of char*
869 ret = XMALLOC(MTYPE_TMP,
870 (vector_active(comps) + 1) * sizeof(char *));
871 unsigned int i;
872 for (i = 0; i < vector_active(comps); i++) {
873 ret[i] = vector_slot(comps, i);
874 }
875 // set the last element to NULL, because this array is used in
876 // a Readline completion_generator function which expects NULL
877 // as a sentinel value
878 ret[i] = NULL;
879 vector_free(comps);
880 comps = NULL;
881 } else if (initial_comps)
882 vector_free(initial_comps);
883
884 // comps should always be null here
885 assert(!comps);
886
887 // free the adjusted input line
888 vector_free(input_line);
889
890 // reset vty->node to its original value
891 vty->node = original_node;
892
893 return ret;
894 }
895
896 /* return parent node */
897 /* MUST eventually converge on CONFIG_NODE */
898 enum node_type node_parent(enum node_type node)
899 {
900 struct cmd_node *cnode;
901
902 assert(node > CONFIG_NODE);
903
904 cnode = vector_lookup(cmdvec, node);
905
906 return cnode->parent_node;
907 }
908
909 /* Execute command by argument vline vector. */
910 static int cmd_execute_command_real(vector vline, enum cmd_filter_type filter,
911 struct vty *vty,
912 const struct cmd_element **cmd,
913 unsigned int up_level)
914 {
915 struct list *argv_list;
916 enum matcher_rv status;
917 const struct cmd_element *matched_element = NULL;
918 unsigned int i;
919 int xpath_index = vty->xpath_index;
920 int node = vty->node;
921
922 /* only happens for legacy split config file load; need to check for
923 * a match before calling node_exit handlers below
924 */
925 for (i = 0; i < up_level; i++) {
926 struct cmd_node *cnode;
927
928 if (node <= CONFIG_NODE)
929 return CMD_NO_LEVEL_UP;
930
931 cnode = vector_slot(cmdvec, node);
932 node = node_parent(node);
933
934 if (xpath_index > 0 && !cnode->no_xpath)
935 xpath_index--;
936 }
937
938 struct graph *cmdgraph = cmd_node_graph(cmdvec, node);
939 status = command_match(cmdgraph, vline, &argv_list, &matched_element);
940
941 if (cmd)
942 *cmd = matched_element;
943
944 // if matcher error, return corresponding CMD_ERR
945 if (MATCHER_ERROR(status)) {
946 if (argv_list)
947 list_delete(&argv_list);
948 switch (status) {
949 case MATCHER_INCOMPLETE:
950 return CMD_ERR_INCOMPLETE;
951 case MATCHER_AMBIGUOUS:
952 return CMD_ERR_AMBIGUOUS;
953 default:
954 return CMD_ERR_NO_MATCH;
955 }
956 }
957
958 for (i = 0; i < up_level; i++)
959 cmd_exit(vty);
960
961 // build argv array from argv list
962 struct cmd_token **argv = XMALLOC(
963 MTYPE_TMP, argv_list->count * sizeof(struct cmd_token *));
964 struct listnode *ln;
965 struct cmd_token *token;
966
967 i = 0;
968 for (ALL_LIST_ELEMENTS_RO(argv_list, ln, token))
969 argv[i++] = token;
970
971 int argc = argv_list->count;
972
973 int ret;
974 if (matched_element->daemon)
975 ret = CMD_SUCCESS_DAEMON;
976 else {
977 if (vty->config) {
978 /* Clear array of enqueued configuration changes. */
979 vty->num_cfg_changes = 0;
980 memset(&vty->cfg_changes, 0, sizeof(vty->cfg_changes));
981
982 /* Regenerate candidate configuration if necessary. */
983 if (frr_get_cli_mode() == FRR_CLI_CLASSIC
984 && running_config->version
985 > vty->candidate_config->version)
986 nb_config_replace(vty->candidate_config,
987 running_config, true);
988
989 /*
990 * Perform pending commit (if any) before executing
991 * non-YANG command.
992 */
993 if (matched_element->attr != CMD_ATTR_YANG)
994 (void)nb_cli_pending_commit_check(vty);
995 }
996
997 ret = matched_element->func(matched_element, vty, argc, argv);
998 }
999
1000 // delete list and cmd_token's in it
1001 list_delete(&argv_list);
1002 XFREE(MTYPE_TMP, argv);
1003
1004 return ret;
1005 }
1006
1007 /**
1008 * Execute a given command, handling things like "do ..." and checking
1009 * whether the given command might apply at a parent node if doesn't
1010 * apply for the current node.
1011 *
1012 * @param vline Command line input, vector of char* where each element is
1013 * one input token.
1014 * @param vty The vty context in which the command should be executed.
1015 * @param cmd Pointer where the struct cmd_element of the matched command
1016 * will be stored, if any. May be set to NULL if this info is
1017 * not needed.
1018 * @param vtysh If set != 0, don't lookup the command at parent nodes.
1019 * @return The status of the command that has been executed or an error code
1020 * as to why no command could be executed.
1021 */
1022 int cmd_execute_command(vector vline, struct vty *vty,
1023 const struct cmd_element **cmd, int vtysh)
1024 {
1025 int ret, saved_ret = 0;
1026 enum node_type onode, try_node;
1027 int orig_xpath_index;
1028
1029 onode = try_node = vty->node;
1030 orig_xpath_index = vty->xpath_index;
1031
1032 if (cmd_try_do_shortcut(vty->node, vector_slot(vline, 0))) {
1033 vector shifted_vline;
1034 unsigned int index;
1035
1036 vty->node = ENABLE_NODE;
1037 vty->xpath_index = 0;
1038 /* We can try it on enable node, cos' the vty is authenticated
1039 */
1040
1041 shifted_vline = vector_init(vector_count(vline));
1042 /* use memcpy? */
1043 for (index = 1; index < vector_active(vline); index++)
1044 vector_set_index(shifted_vline, index - 1,
1045 vector_lookup(vline, index));
1046
1047 ret = cmd_execute_command_real(shifted_vline, FILTER_RELAXED,
1048 vty, cmd, 0);
1049
1050 vector_free(shifted_vline);
1051 vty->node = onode;
1052 vty->xpath_index = orig_xpath_index;
1053 return ret;
1054 }
1055
1056 saved_ret = ret =
1057 cmd_execute_command_real(vline, FILTER_RELAXED, vty, cmd, 0);
1058
1059 if (vtysh)
1060 return saved_ret;
1061
1062 if (ret != CMD_SUCCESS && ret != CMD_WARNING
1063 && ret != CMD_ERR_AMBIGUOUS && ret != CMD_ERR_INCOMPLETE
1064 && ret != CMD_NOT_MY_INSTANCE && ret != CMD_WARNING_CONFIG_FAILED) {
1065 /* This assumes all nodes above CONFIG_NODE are childs of
1066 * CONFIG_NODE */
1067 while (vty->node > CONFIG_NODE) {
1068 struct cmd_node *cnode = vector_slot(cmdvec, try_node);
1069
1070 try_node = node_parent(try_node);
1071 vty->node = try_node;
1072 if (vty->xpath_index > 0 && !cnode->no_xpath)
1073 vty->xpath_index--;
1074
1075 ret = cmd_execute_command_real(vline, FILTER_RELAXED,
1076 vty, cmd, 0);
1077 if (ret == CMD_SUCCESS || ret == CMD_WARNING
1078 || ret == CMD_ERR_AMBIGUOUS || ret == CMD_ERR_INCOMPLETE
1079 || ret == CMD_NOT_MY_INSTANCE
1080 || ret == CMD_WARNING_CONFIG_FAILED)
1081 return ret;
1082 }
1083 /* no command succeeded, reset the vty to the original node */
1084 vty->node = onode;
1085 vty->xpath_index = orig_xpath_index;
1086 }
1087
1088 /* return command status for original node */
1089 return saved_ret;
1090 }
1091
1092 /**
1093 * Execute a given command, matching it strictly against the current node.
1094 * This mode is used when reading config files.
1095 *
1096 * @param vline Command line input, vector of char* where each element is
1097 * one input token.
1098 * @param vty The vty context in which the command should be executed.
1099 * @param cmd Pointer where the struct cmd_element* of the matched command
1100 * will be stored, if any. May be set to NULL if this info is
1101 * not needed.
1102 * @return The status of the command that has been executed or an error code
1103 * as to why no command could be executed.
1104 */
1105 int cmd_execute_command_strict(vector vline, struct vty *vty,
1106 const struct cmd_element **cmd)
1107 {
1108 return cmd_execute_command_real(vline, FILTER_STRICT, vty, cmd, 0);
1109 }
1110
1111 /*
1112 * Hook for preprocessing command string before executing.
1113 *
1114 * All subscribers are called with the raw command string that is to be
1115 * executed. If any changes are to be made, a new string should be allocated
1116 * with MTYPE_TMP and *cmd_out updated to point to this new string. The caller
1117 * is then responsible for freeing this string.
1118 *
1119 * All processing functions must be mutually exclusive in their action, i.e. if
1120 * one subscriber decides to modify the command, all others must not modify it
1121 * when called. Feeding the output of one processing command into a subsequent
1122 * one is not supported.
1123 *
1124 * This hook is intentionally internal to the command processing system.
1125 *
1126 * cmd_in
1127 * The raw command string.
1128 *
1129 * cmd_out
1130 * The result of any processing.
1131 */
1132 DECLARE_HOOK(cmd_execute,
1133 (struct vty *vty, const char *cmd_in, char **cmd_out),
1134 (vty, cmd_in, cmd_out));
1135 DEFINE_HOOK(cmd_execute, (struct vty *vty, const char *cmd_in, char **cmd_out),
1136 (vty, cmd_in, cmd_out));
1137
1138 /* Hook executed after a CLI command. */
1139 DECLARE_KOOH(cmd_execute_done, (struct vty *vty, const char *cmd_exec),
1140 (vty, cmd_exec));
1141 DEFINE_KOOH(cmd_execute_done, (struct vty *vty, const char *cmd_exec),
1142 (vty, cmd_exec));
1143
1144 /*
1145 * cmd_execute hook subscriber to handle `|` actions.
1146 */
1147 static int handle_pipe_action(struct vty *vty, const char *cmd_in,
1148 char **cmd_out)
1149 {
1150 /* look for `|` */
1151 char *orig, *working, *token, *u;
1152 char *pipe = strstr(cmd_in, "| ");
1153 int ret = 0;
1154
1155 if (!pipe)
1156 return 0;
1157
1158 /* duplicate string for processing purposes, not including pipe */
1159 orig = working = XSTRDUP(MTYPE_TMP, pipe + 2);
1160
1161 /* retrieve action */
1162 token = strsep(&working, " ");
1163 assert(token);
1164
1165 /* match result to known actions */
1166 if (strmatch(token, "include")) {
1167 /* the remaining text should be a regexp */
1168 char *regexp = working;
1169
1170 if (!regexp) {
1171 vty_out(vty, "%% Need a regexp to filter with\n");
1172 ret = 1;
1173 goto fail;
1174 }
1175
1176 bool succ = vty_set_include(vty, regexp);
1177
1178 if (!succ) {
1179 vty_out(vty, "%% Bad regexp '%s'\n", regexp);
1180 ret = 1;
1181 goto fail;
1182 }
1183 *cmd_out = XSTRDUP(MTYPE_TMP, cmd_in);
1184 u = *cmd_out;
1185 strsep(&u, "|");
1186 } else {
1187 vty_out(vty, "%% Unknown action '%s'\n", token);
1188 ret = 1;
1189 goto fail;
1190 }
1191
1192 fail:
1193 XFREE(MTYPE_TMP, orig);
1194 return ret;
1195 }
1196
1197 static int handle_pipe_action_done(struct vty *vty, const char *cmd_exec)
1198 {
1199 if (vty->filter)
1200 vty_set_include(vty, NULL);
1201
1202 return 0;
1203 }
1204
1205 int cmd_execute(struct vty *vty, const char *cmd,
1206 const struct cmd_element **matched, int vtysh)
1207 {
1208 int ret;
1209 char *cmd_out = NULL;
1210 const char *cmd_exec = NULL;
1211 vector vline;
1212
1213 ret = hook_call(cmd_execute, vty, cmd, &cmd_out);
1214 if (ret) {
1215 ret = CMD_WARNING;
1216 goto free;
1217 }
1218
1219 cmd_exec = cmd_out ? (const char *)cmd_out : cmd;
1220
1221 vline = cmd_make_strvec(cmd_exec);
1222
1223 if (vline) {
1224 ret = cmd_execute_command(vline, vty, matched, vtysh);
1225 cmd_free_strvec(vline);
1226 } else {
1227 ret = CMD_SUCCESS;
1228 }
1229
1230 free:
1231 hook_call(cmd_execute_done, vty, cmd_exec);
1232
1233 XFREE(MTYPE_TMP, cmd_out);
1234
1235 return ret;
1236 }
1237
1238
1239 /**
1240 * Parse one line of config, walking up the parse tree attempting to find a
1241 * match
1242 *
1243 * @param vty The vty context in which the command should be executed.
1244 * @param cmd Pointer where the struct cmd_element* of the match command
1245 * will be stored, if any. May be set to NULL if this info is
1246 * not needed.
1247 * @param use_daemon Boolean to control whether or not we match on
1248 * CMD_SUCCESS_DAEMON
1249 * or not.
1250 * @return The status of the command that has been executed or an error code
1251 * as to why no command could be executed.
1252 */
1253 int command_config_read_one_line(struct vty *vty,
1254 const struct cmd_element **cmd,
1255 uint32_t line_num, int use_daemon)
1256 {
1257 vector vline;
1258 int ret;
1259 unsigned up_level = 0;
1260
1261 vline = cmd_make_strvec(vty->buf);
1262
1263 /* In case of comment line */
1264 if (vline == NULL)
1265 return CMD_SUCCESS;
1266
1267 /* Execute configuration command : this is strict match */
1268 ret = cmd_execute_command_strict(vline, vty, cmd);
1269
1270 /* The logic for trying parent nodes is in cmd_execute_command_real()
1271 * since calling ->node_exit() correctly is a bit involved. This is
1272 * also the only reason CMD_NO_LEVEL_UP exists.
1273 */
1274 while (!(use_daemon && ret == CMD_SUCCESS_DAEMON)
1275 && !(!use_daemon && ret == CMD_ERR_NOTHING_TODO)
1276 && ret != CMD_SUCCESS && ret != CMD_WARNING
1277 && ret != CMD_ERR_AMBIGUOUS && ret != CMD_ERR_INCOMPLETE
1278 && ret != CMD_NOT_MY_INSTANCE && ret != CMD_WARNING_CONFIG_FAILED
1279 && ret != CMD_NO_LEVEL_UP)
1280 ret = cmd_execute_command_real(vline, FILTER_STRICT, vty, cmd,
1281 ++up_level);
1282
1283 if (ret == CMD_NO_LEVEL_UP)
1284 ret = CMD_ERR_NO_MATCH;
1285
1286 if (ret != CMD_SUCCESS &&
1287 ret != CMD_WARNING &&
1288 ret != CMD_SUCCESS_DAEMON) {
1289 struct vty_error *ve = XCALLOC(MTYPE_TMP, sizeof(*ve));
1290
1291 memcpy(ve->error_buf, vty->buf, VTY_BUFSIZ);
1292 ve->line_num = line_num;
1293 if (!vty->error)
1294 vty->error = list_new();
1295
1296 listnode_add(vty->error, ve);
1297 }
1298
1299 cmd_free_strvec(vline);
1300
1301 return ret;
1302 }
1303
1304 /* Configuration make from file. */
1305 int config_from_file(struct vty *vty, FILE *fp, unsigned int *line_num)
1306 {
1307 int ret, error_ret = 0;
1308 *line_num = 0;
1309
1310 while (fgets(vty->buf, VTY_BUFSIZ, fp)) {
1311 ++(*line_num);
1312
1313 ret = command_config_read_one_line(vty, NULL, *line_num, 0);
1314
1315 if (ret != CMD_SUCCESS && ret != CMD_WARNING
1316 && ret != CMD_ERR_NOTHING_TODO)
1317 error_ret = ret;
1318 }
1319
1320 if (error_ret) {
1321 return error_ret;
1322 }
1323
1324 return CMD_SUCCESS;
1325 }
1326
1327 /* Configuration from terminal */
1328 DEFUN (config_terminal,
1329 config_terminal_cmd,
1330 "configure [terminal]",
1331 "Configuration from vty interface\n"
1332 "Configuration terminal\n")
1333 {
1334 return vty_config_enter(vty, false, false);
1335 }
1336
1337 /* Enable command */
1338 DEFUN (enable,
1339 config_enable_cmd,
1340 "enable",
1341 "Turn on privileged mode command\n")
1342 {
1343 /* If enable password is NULL, change to ENABLE_NODE */
1344 if ((host.enable == NULL && host.enable_encrypt == NULL)
1345 || vty->type == VTY_SHELL_SERV)
1346 vty->node = ENABLE_NODE;
1347 else
1348 vty->node = AUTH_ENABLE_NODE;
1349
1350 return CMD_SUCCESS;
1351 }
1352
1353 /* Disable command */
1354 DEFUN (disable,
1355 config_disable_cmd,
1356 "disable",
1357 "Turn off privileged mode command\n")
1358 {
1359 if (vty->node == ENABLE_NODE)
1360 vty->node = VIEW_NODE;
1361 return CMD_SUCCESS;
1362 }
1363
1364 /* Down vty node level. */
1365 DEFUN (config_exit,
1366 config_exit_cmd,
1367 "exit",
1368 "Exit current mode and down to previous mode\n")
1369 {
1370 cmd_exit(vty);
1371 return CMD_SUCCESS;
1372 }
1373
1374 static int root_on_exit(struct vty *vty)
1375 {
1376 if (vty_shell(vty))
1377 exit(0);
1378 else
1379 vty->status = VTY_CLOSE;
1380 return 0;
1381 }
1382
1383 void cmd_exit(struct vty *vty)
1384 {
1385 struct cmd_node *cnode = vector_lookup(cmdvec, vty->node);
1386
1387 if (cnode->node_exit) {
1388 if (!cnode->node_exit(vty))
1389 return;
1390 }
1391 if (cnode->parent_node)
1392 vty->node = cnode->parent_node;
1393 if (vty->xpath_index > 0 && !cnode->no_xpath)
1394 vty->xpath_index--;
1395 }
1396
1397 /* ALIAS_FIXME */
1398 DEFUN (config_quit,
1399 config_quit_cmd,
1400 "quit",
1401 "Exit current mode and down to previous mode\n")
1402 {
1403 return config_exit(self, vty, argc, argv);
1404 }
1405
1406
1407 /* End of configuration. */
1408 DEFUN (config_end,
1409 config_end_cmd,
1410 "end",
1411 "End current mode and change to enable mode.\n")
1412 {
1413 if (vty->config) {
1414 vty_config_exit(vty);
1415 vty->node = ENABLE_NODE;
1416 }
1417 return CMD_SUCCESS;
1418 }
1419
1420 /* Show version. */
1421 DEFUN (show_version,
1422 show_version_cmd,
1423 "show version",
1424 SHOW_STR
1425 "Displays zebra version\n")
1426 {
1427 vty_out(vty, "%s %s (%s) on %s(%s).\n", FRR_FULL_NAME, FRR_VERSION,
1428 cmd_hostname_get() ? cmd_hostname_get() : "", cmd_system_get(),
1429 cmd_release_get());
1430 vty_out(vty, "%s%s\n", FRR_COPYRIGHT, GIT_INFO);
1431 #ifdef ENABLE_VERSION_BUILD_CONFIG
1432 vty_out(vty, "configured with:\n %s\n", FRR_CONFIG_ARGS);
1433 #endif
1434 return CMD_SUCCESS;
1435 }
1436
1437 /* Help display function for all node. */
1438 DEFUN (config_help,
1439 config_help_cmd,
1440 "help",
1441 "Description of the interactive help system\n")
1442 {
1443 vty_out(vty,
1444 "Quagga VTY provides advanced help feature. When you need help,\n\
1445 anytime at the command line please press '?'.\n\
1446 \n\
1447 If nothing matches, the help list will be empty and you must backup\n\
1448 until entering a '?' shows the available options.\n\
1449 Two styles of help are provided:\n\
1450 1. Full help is available when you are ready to enter a\n\
1451 command argument (e.g. 'show ?') and describes each possible\n\
1452 argument.\n\
1453 2. Partial help is provided when an abbreviated argument is entered\n\
1454 and you want to know what arguments match the input\n\
1455 (e.g. 'show me?'.)\n\n");
1456 return CMD_SUCCESS;
1457 }
1458
1459 static void permute(struct graph_node *start, struct vty *vty)
1460 {
1461 static struct list *position = NULL;
1462 if (!position)
1463 position = list_new();
1464
1465 struct cmd_token *stok = start->data;
1466 struct graph_node *gnn;
1467 struct listnode *ln;
1468
1469 // recursive dfs
1470 listnode_add(position, start);
1471 for (unsigned int i = 0; i < vector_active(start->to); i++) {
1472 struct graph_node *gn = vector_slot(start->to, i);
1473 struct cmd_token *tok = gn->data;
1474 if (tok->attr == CMD_ATTR_HIDDEN
1475 || tok->attr == CMD_ATTR_DEPRECATED)
1476 continue;
1477 else if (tok->type == END_TKN || gn == start) {
1478 vty_out(vty, " ");
1479 for (ALL_LIST_ELEMENTS_RO(position, ln, gnn)) {
1480 struct cmd_token *tt = gnn->data;
1481 if (tt->type < SPECIAL_TKN)
1482 vty_out(vty, " %s", tt->text);
1483 }
1484 if (gn == start)
1485 vty_out(vty, "...");
1486 vty_out(vty, "\n");
1487 } else {
1488 bool skip = false;
1489 if (stok->type == FORK_TKN && tok->type != FORK_TKN)
1490 for (ALL_LIST_ELEMENTS_RO(position, ln, gnn))
1491 if (gnn == gn) {
1492 skip = true;
1493 break;
1494 }
1495 if (!skip)
1496 permute(gn, vty);
1497 }
1498 }
1499 list_delete_node(position, listtail(position));
1500 }
1501
1502 static void print_cmd(struct vty *vty, const char *cmd)
1503 {
1504 int i, j, len = strlen(cmd);
1505 char buf[len + 1];
1506 bool skip = false;
1507
1508 j = 0;
1509 for (i = 0; i < len; i++) {
1510 /* skip varname */
1511 if (cmd[i] == '$')
1512 skip = true;
1513 else if (strchr(" ()<>[]{}|", cmd[i]))
1514 skip = false;
1515
1516 if (skip)
1517 continue;
1518
1519 if (isspace(cmd[i])) {
1520 /* skip leading whitespace */
1521 if (i == 0)
1522 continue;
1523 /* skip trailing whitespace */
1524 if (i == len - 1)
1525 continue;
1526 /* skip all whitespace after opening brackets or pipe */
1527 if (strchr("(<[{|", cmd[i - 1])) {
1528 while (isspace(cmd[i + 1]))
1529 i++;
1530 continue;
1531 }
1532 /* skip repeated whitespace */
1533 if (isspace(cmd[i + 1]))
1534 continue;
1535 /* skip whitespace before closing brackets or pipe */
1536 if (strchr(")>]}|", cmd[i + 1]))
1537 continue;
1538 /* convert tabs to spaces */
1539 if (cmd[i] == '\t') {
1540 buf[j++] = ' ';
1541 continue;
1542 }
1543 }
1544
1545 buf[j++] = cmd[i];
1546 }
1547 buf[j] = 0;
1548
1549 vty_out(vty, "%s\n", buf);
1550 }
1551
1552 int cmd_list_cmds(struct vty *vty, int do_permute)
1553 {
1554 struct cmd_node *node = vector_slot(cmdvec, vty->node);
1555
1556 if (do_permute) {
1557 cmd_finalize_node(node);
1558 permute(vector_slot(node->cmdgraph->nodes, 0), vty);
1559 } else {
1560 /* loop over all commands at this node */
1561 const struct cmd_element *element = NULL;
1562 for (unsigned int i = 0; i < vector_active(node->cmd_vector);
1563 i++)
1564 if ((element = vector_slot(node->cmd_vector, i))
1565 && element->attr != CMD_ATTR_DEPRECATED
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 install_default(enum node_type node)
2450 {
2451 _install_element(node, &config_exit_cmd);
2452 _install_element(node, &config_quit_cmd);
2453 _install_element(node, &config_end_cmd);
2454 _install_element(node, &config_help_cmd);
2455 _install_element(node, &config_list_cmd);
2456 _install_element(node, &show_cli_graph_cmd);
2457 _install_element(node, &find_cmd);
2458
2459 _install_element(node, &config_write_cmd);
2460 _install_element(node, &show_running_config_cmd);
2461
2462 _install_element(node, &autocomplete_cmd);
2463
2464 nb_cli_install_default(node);
2465 }
2466
2467 /* Initialize command interface. Install basic nodes and commands.
2468 *
2469 * terminal = 0 -- vtysh / no logging, no config control
2470 * terminal = 1 -- normal daemon
2471 * terminal = -1 -- watchfrr / no logging, but minimal config control */
2472 void cmd_init(int terminal)
2473 {
2474 struct utsname names;
2475
2476 uname(&names);
2477 qobj_init();
2478
2479 /* register command preprocessors */
2480 hook_register(cmd_execute, handle_pipe_action);
2481 hook_register(cmd_execute_done, handle_pipe_action_done);
2482
2483 varhandlers = list_new();
2484
2485 /* Allocate initial top vector of commands. */
2486 cmdvec = vector_init(VECTOR_MIN_SIZE);
2487
2488 /* Default host value settings. */
2489 host.name = XSTRDUP(MTYPE_HOST, names.nodename);
2490 host.system = XSTRDUP(MTYPE_HOST, names.sysname);
2491 host.release = XSTRDUP(MTYPE_HOST, names.release);
2492 host.version = XSTRDUP(MTYPE_HOST, names.version);
2493
2494 #ifdef HAVE_STRUCT_UTSNAME_DOMAINNAME
2495 if ((strcmp(names.domainname, "(none)") == 0))
2496 host.domainname = NULL;
2497 else
2498 host.domainname = XSTRDUP(MTYPE_HOST, names.domainname);
2499 #else
2500 host.domainname = NULL;
2501 #endif
2502 host.password = NULL;
2503 host.enable = NULL;
2504 host.config = NULL;
2505 host.noconfig = (terminal < 0);
2506 host.lines = -1;
2507 cmd_banner_motd_line(FRR_DEFAULT_MOTD);
2508 host.motdfile = NULL;
2509 host.allow_reserved_ranges = false;
2510
2511 /* Install top nodes. */
2512 install_node(&view_node);
2513 install_node(&enable_node);
2514 install_node(&auth_node);
2515 install_node(&auth_enable_node);
2516 install_node(&config_node);
2517
2518 /* Each node's basic commands. */
2519 install_element(VIEW_NODE, &show_version_cmd);
2520 install_element(ENABLE_NODE, &show_startup_config_cmd);
2521
2522 if (terminal) {
2523 install_element(ENABLE_NODE, &debug_memstats_cmd);
2524
2525 install_element(VIEW_NODE, &config_list_cmd);
2526 install_element(VIEW_NODE, &config_exit_cmd);
2527 install_element(VIEW_NODE, &config_quit_cmd);
2528 install_element(VIEW_NODE, &config_help_cmd);
2529 install_element(VIEW_NODE, &config_enable_cmd);
2530 install_element(VIEW_NODE, &config_terminal_length_cmd);
2531 install_element(VIEW_NODE, &config_terminal_no_length_cmd);
2532 install_element(VIEW_NODE, &show_commandtree_cmd);
2533 install_element(VIEW_NODE, &echo_cmd);
2534 install_element(VIEW_NODE, &autocomplete_cmd);
2535 install_element(VIEW_NODE, &find_cmd);
2536 #if defined(DEV_BUILD) && defined(HAVE_SCRIPTING)
2537 install_element(VIEW_NODE, &script_cmd);
2538 #endif
2539
2540
2541 install_element(ENABLE_NODE, &config_end_cmd);
2542 install_element(ENABLE_NODE, &config_disable_cmd);
2543 install_element(ENABLE_NODE, &config_terminal_cmd);
2544 install_element(ENABLE_NODE, &copy_runningconf_startupconf_cmd);
2545 install_element(ENABLE_NODE, &config_write_cmd);
2546 install_element(ENABLE_NODE, &show_running_config_cmd);
2547 install_element(ENABLE_NODE, &config_logmsg_cmd);
2548
2549 install_default(CONFIG_NODE);
2550
2551 thread_cmd_init();
2552 workqueue_cmd_init();
2553 hash_cmd_init();
2554 }
2555
2556 install_element(CONFIG_NODE, &hostname_cmd);
2557 install_element(CONFIG_NODE, &no_hostname_cmd);
2558 install_element(CONFIG_NODE, &domainname_cmd);
2559 install_element(CONFIG_NODE, &no_domainname_cmd);
2560
2561 if (terminal > 0) {
2562 full_cli = true;
2563
2564 install_element(CONFIG_NODE, &debug_memstats_cmd);
2565
2566 install_element(CONFIG_NODE, &password_cmd);
2567 install_element(CONFIG_NODE, &no_password_cmd);
2568 install_element(CONFIG_NODE, &enable_password_cmd);
2569 install_element(CONFIG_NODE, &no_enable_password_cmd);
2570
2571 install_element(CONFIG_NODE, &service_password_encrypt_cmd);
2572 install_element(CONFIG_NODE, &no_service_password_encrypt_cmd);
2573 install_element(CONFIG_NODE, &banner_motd_default_cmd);
2574 install_element(CONFIG_NODE, &banner_motd_file_cmd);
2575 install_element(CONFIG_NODE, &banner_motd_line_cmd);
2576 install_element(CONFIG_NODE, &no_banner_motd_cmd);
2577 install_element(CONFIG_NODE, &service_terminal_length_cmd);
2578 install_element(CONFIG_NODE, &no_service_terminal_length_cmd);
2579 install_element(CONFIG_NODE, &allow_reserved_ranges_cmd);
2580 install_element(CONFIG_NODE, &no_allow_reserved_ranges_cmd);
2581
2582 log_cmd_init();
2583 vrf_install_commands();
2584 }
2585
2586 #ifdef DEV_BUILD
2587 grammar_sandbox_init();
2588 #endif
2589 }
2590
2591 void cmd_terminate(void)
2592 {
2593 struct cmd_node *cmd_node;
2594
2595 hook_unregister(cmd_execute, handle_pipe_action);
2596 hook_unregister(cmd_execute_done, handle_pipe_action_done);
2597
2598 if (cmdvec) {
2599 for (unsigned int i = 0; i < vector_active(cmdvec); i++)
2600 if ((cmd_node = vector_slot(cmdvec, i)) != NULL) {
2601 // deleting the graph delets the cmd_element as
2602 // well
2603 graph_delete_graph(cmd_node->cmdgraph);
2604 vector_free(cmd_node->cmd_vector);
2605 hash_clean(cmd_node->cmd_hash, NULL);
2606 hash_free(cmd_node->cmd_hash);
2607 cmd_node->cmd_hash = NULL;
2608 }
2609
2610 vector_free(cmdvec);
2611 cmdvec = NULL;
2612 }
2613
2614 XFREE(MTYPE_HOST, host.name);
2615 XFREE(MTYPE_HOST, host.system);
2616 XFREE(MTYPE_HOST, host.release);
2617 XFREE(MTYPE_HOST, host.version);
2618 XFREE(MTYPE_HOST, host.domainname);
2619 XFREE(MTYPE_HOST, host.password);
2620 XFREE(MTYPE_HOST, host.password_encrypt);
2621 XFREE(MTYPE_HOST, host.enable);
2622 XFREE(MTYPE_HOST, host.enable_encrypt);
2623 XFREE(MTYPE_HOST, host.motdfile);
2624 XFREE(MTYPE_HOST, host.config);
2625 XFREE(MTYPE_HOST, host.motd);
2626
2627 list_delete(&varhandlers);
2628 qobj_finish();
2629 }