-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
command.c
2835 lines (2459 loc) · 71.7 KB
/
command.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* CLI backend interface.
*
* --
* Copyright (C) 2016 Cumulus Networks, Inc.
* Copyright (C) 1997, 98, 99 Kunihiro Ishiguro
* Copyright (C) 2013 by Open Source Routing.
* Copyright (C) 2013 by Internet Systems Consortium, Inc. ("ISC")
*
* This file is part of GNU Zebra.
*
* GNU Zebra is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2, or (at your option) any
* later version.
*
* GNU Zebra is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; see the file COPYING; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <zebra.h>
#include "memory.h"
#include "log.h"
#include "log_int.h"
#include <lib/version.h>
#include "thread.h"
#include "vector.h"
#include "linklist.h"
#include "vty.h"
#include "command.h"
#include "workqueue.h"
#include "vrf.h"
#include "command_match.h"
#include "command_graph.h"
#include "qobj.h"
#include "defaults.h"
#include "libfrr.h"
#include "jhash.h"
DEFINE_MTYPE(LIB, HOST, "Host config")
DEFINE_MTYPE(LIB, STRVEC, "String vector")
DEFINE_MTYPE(LIB, COMPLETION, "Completion item")
#define item(x) \
{ \
x, #x \
}
/* clang-format off */
const struct message tokennames[] = {
item(WORD_TKN),
item(VARIABLE_TKN),
item(RANGE_TKN),
item(IPV4_TKN),
item(IPV4_PREFIX_TKN),
item(IPV6_TKN),
item(IPV6_PREFIX_TKN),
item(MAC_TKN),
item(MAC_PREFIX_TKN),
item(FORK_TKN),
item(JOIN_TKN),
item(START_TKN),
item(END_TKN),
{0},
};
const char *node_names[] = {
"auth", // AUTH_NODE,
"view", // VIEW_NODE,
"auth enable", // AUTH_ENABLE_NODE,
"enable", // ENABLE_NODE,
"config", // CONFIG_NODE,
"debug", // DEBUG_NODE,
"vrf debug", // VRF_DEBUG_NODE,
"vnc debug", // DEBUG_VNC_NODE,
"aaa", // AAA_NODE,
"keychain", // KEYCHAIN_NODE,
"keychain key", // KEYCHAIN_KEY_NODE,
"logical-router", // LOGICALROUTER_NODE,
"vrf", // VRF_NODE,
"interface", // INTERFACE_NODE,
"nexthop-group", // NH_GROUP_NODE,
"zebra", // ZEBRA_NODE,
"table", // TABLE_NODE,
"rip", // RIP_NODE,
"ripng", // RIPNG_NODE,
"babel", // BABEL_NODE,
"eigrp", // EIGRP_NODE,
"bgp", // BGP_NODE,
"bgp vpnv4", // BGP_VPNV4_NODE,
"bgp vpnv6", // BGP_VPNV6_NODE,
"bgp ipv4 unicast", // BGP_IPV4_NODE,
"bgp ipv4 multicast", // BGP_IPV4M_NODE,
"bgp ipv4 labeled unicast", // BGP_IPV4L_NODE,
"bgp ipv6", // BGP_IPV6_NODE,
"bgp ipv6 multicast", // BGP_IPV6M_NODE,
"bgp ipv6 labeled unicast", // BGP_IPV6L_NODE,
"bgp vrf policy", // BGP_VRF_POLICY_NODE,
"bgp vnc defaults", // BGP_VNC_DEFAULTS_NODE,
"bgp vnc nve", // BGP_VNC_NVE_GROUP_NODE,
"bgp vnc l2", // BGP_VNC_L2_GROUP_NODE,
"rfp defaults", // RFP_DEFAULTS_NODE,
"bgp evpn", // BGP_EVPN_NODE,
"ospf", // OSPF_NODE,
"ospf6", // OSPF6_NODE,
"ldp", // LDP_NODE,
"ldp ipv4", // LDP_IPV4_NODE,
"ldp ipv6", // LDP_IPV6_NODE,
"ldp ipv4 interface", // LDP_IPV4_IFACE_NODE,
"ldp ipv6 interface", // LDP_IPV6_IFACE_NODE,
"ldp l2vpn", // LDP_L2VPN_NODE,
"ldp", // LDP_PSEUDOWIRE_NODE,
"isis", // ISIS_NODE,
"static ip", // IP_NODE,
"ipv4 access list", // ACCESS_NODE,
"ipv4 prefix list", // PREFIX_NODE,
"ipv6 access list", // ACCESS_IPV6_NODE,
"MAC access list", // ACCESS_MAC_NODE,
"ipv6 prefix list", // PREFIX_IPV6_NODE,
"as list", // AS_LIST_NODE,
"community list", // COMMUNITY_LIST_NODE,
"routemap", // RMAP_NODE,
"pbr-map", // PBRMAP_NODE,
"smux", // SMUX_NODE,
"dump", // DUMP_NODE,
"forwarding", // FORWARDING_NODE,
"protocol", // PROTOCOL_NODE,
"mpls", // MPLS_NODE,
"pw", // PW_NODE,
"vty", // VTY_NODE,
"link-params", // LINK_PARAMS_NODE,
"bgp evpn vni", // BGP_EVPN_VNI_NODE,
"rpki", // RPKI_NODE
"bgp ipv4 flowspec", /* BGP_FLOWSPECV4_NODE
*/
"bgp ipv6 flowspec", /* BGP_FLOWSPECV6_NODE
*/
};
/* clang-format on */
/* Command vector which includes some level of command lists. Normally
each daemon maintains each own cmdvec. */
vector cmdvec = NULL;
/* Host information structure. */
struct host host;
/*
* Returns host.name if any, otherwise
* it returns the system hostname.
*/
const char *cmd_hostname_get(void)
{
return host.name;
}
/*
* Returns unix domainname
*/
const char *cmd_domainname_get(void)
{
return host.domainname;
}
/* Standard command node structures. */
static struct cmd_node auth_node = {
AUTH_NODE, "Password: ",
};
static struct cmd_node view_node = {
VIEW_NODE, "%s> ",
};
static struct cmd_node auth_enable_node = {
AUTH_ENABLE_NODE, "Password: ",
};
static struct cmd_node enable_node = {
ENABLE_NODE, "%s# ",
};
static struct cmd_node config_node = {CONFIG_NODE, "%s(config)# ", 1};
/* Default motd string. */
static const char *default_motd = FRR_DEFAULT_MOTD;
static const struct facility_map {
int facility;
const char *name;
size_t match;
} syslog_facilities[] = {
{LOG_KERN, "kern", 1},
{LOG_USER, "user", 2},
{LOG_MAIL, "mail", 1},
{LOG_DAEMON, "daemon", 1},
{LOG_AUTH, "auth", 1},
{LOG_SYSLOG, "syslog", 1},
{LOG_LPR, "lpr", 2},
{LOG_NEWS, "news", 1},
{LOG_UUCP, "uucp", 2},
{LOG_CRON, "cron", 1},
#ifdef LOG_FTP
{LOG_FTP, "ftp", 1},
#endif
{LOG_LOCAL0, "local0", 6},
{LOG_LOCAL1, "local1", 6},
{LOG_LOCAL2, "local2", 6},
{LOG_LOCAL3, "local3", 6},
{LOG_LOCAL4, "local4", 6},
{LOG_LOCAL5, "local5", 6},
{LOG_LOCAL6, "local6", 6},
{LOG_LOCAL7, "local7", 6},
{0, NULL, 0},
};
static const char *facility_name(int facility)
{
const struct facility_map *fm;
for (fm = syslog_facilities; fm->name; fm++)
if (fm->facility == facility)
return fm->name;
return "";
}
static int facility_match(const char *str)
{
const struct facility_map *fm;
for (fm = syslog_facilities; fm->name; fm++)
if (!strncmp(str, fm->name, fm->match))
return fm->facility;
return -1;
}
static int level_match(const char *s)
{
int level;
for (level = 0; zlog_priority[level] != NULL; level++)
if (!strncmp(s, zlog_priority[level], 2))
return level;
return ZLOG_DISABLED;
}
/* This is called from main when a daemon is invoked with -v or --version. */
void print_version(const char *progname)
{
printf("%s version %s\n", progname, FRR_VERSION);
printf("%s\n", FRR_COPYRIGHT);
printf("configured with:\n\t%s\n", FRR_CONFIG_ARGS);
}
/* Utility function to concatenate argv argument into a single string
with inserting ' ' character between each argument. */
char *argv_concat(struct cmd_token **argv, int argc, int shift)
{
int i;
size_t len;
char *str;
char *p;
len = 0;
for (i = shift; i < argc; i++)
len += strlen(argv[i]->arg) + 1;
if (!len)
return NULL;
p = str = XMALLOC(MTYPE_TMP, len);
for (i = shift; i < argc; i++) {
size_t arglen;
memcpy(p, argv[i]->arg, (arglen = strlen(argv[i]->arg)));
p += arglen;
*p++ = ' ';
}
*(p - 1) = '\0';
return str;
}
/**
* Convenience function for accessing argv data.
*
* @param argc
* @param argv
* @param text definition snippet of the desired token
* @param index the starting index, and where to store the
* index of the found token if it exists
* @return 1 if found, 0 otherwise
*/
int argv_find(struct cmd_token **argv, int argc, const char *text, int *index)
{
int found = 0;
for (int i = *index; i < argc && found == 0; i++)
if ((found = strmatch(text, argv[i]->text)))
*index = i;
return found;
}
static unsigned int cmd_hash_key(void *p)
{
int size = sizeof(p);
return jhash(p, size, 0);
}
static int cmd_hash_cmp(const void *a, const void *b)
{
return a == b;
}
/* Install top node of command vector. */
void install_node(struct cmd_node *node, int (*func)(struct vty *))
{
vector_set_index(cmdvec, node->node, node);
node->func = func;
node->cmdgraph = graph_new();
node->cmd_vector = vector_init(VECTOR_MIN_SIZE);
// add start node
struct cmd_token *token =
cmd_token_new(START_TKN, CMD_ATTR_NORMAL, NULL, NULL);
graph_new_node(node->cmdgraph, token,
(void (*)(void *)) & cmd_token_del);
node->cmd_hash = hash_create_size(16, cmd_hash_key, cmd_hash_cmp,
"Command Hash");
}
/**
* Tokenizes a string, storing tokens in a vector.
* Whitespace is ignored.
*
* Delimiter string = " \n\r\t".
*
* @param string to tokenize
* @return tokenized string
*/
vector cmd_make_strvec(const char *string)
{
if (!string)
return NULL;
char *copy, *copystart;
copystart = copy = XSTRDUP(MTYPE_TMP, string);
// skip leading whitespace
while (isspace((int)*copy) && *copy != '\0')
copy++;
// if the entire string was whitespace or a comment, return
if (*copy == '\0' || *copy == '!' || *copy == '#') {
XFREE(MTYPE_TMP, copystart);
return NULL;
}
vector strvec = vector_init(VECTOR_MIN_SIZE);
const char *delim = " \n\r\t", *tok = NULL;
while (copy) {
tok = strsep(©, delim);
if (*tok != '\0')
vector_set(strvec, XSTRDUP(MTYPE_STRVEC, tok));
}
XFREE(MTYPE_TMP, copystart);
return strvec;
}
/* Free allocated string vector. */
void cmd_free_strvec(vector v)
{
unsigned int i;
char *cp;
if (!v)
return;
for (i = 0; i < vector_active(v); i++)
if ((cp = vector_slot(v, i)) != NULL)
XFREE(MTYPE_STRVEC, cp);
vector_free(v);
}
/* Return prompt character of specified node. */
const char *cmd_prompt(enum node_type node)
{
struct cmd_node *cnode;
cnode = vector_slot(cmdvec, node);
return cnode->prompt;
}
/* Install a command into a node. */
void install_element(enum node_type ntype, struct cmd_element *cmd)
{
struct cmd_node *cnode;
/* cmd_init hasn't been called */
if (!cmdvec) {
fprintf(stderr, "%s called before cmd_init, breakage likely\n",
__func__);
return;
}
cnode = vector_lookup(cmdvec, ntype);
if (cnode == NULL) {
fprintf(stderr,
"%s[%s]:\n"
"\tnode %d (%s) does not exist.\n"
"\tplease call install_node() before install_element()\n",
cmd->name, cmd->string, ntype, node_names[ntype]);
exit(EXIT_FAILURE);
}
if (hash_lookup(cnode->cmd_hash, cmd) != NULL) {
fprintf(stderr,
"%s[%s]:\n"
"\tnode %d (%s) already has this command installed.\n"
"\tduplicate install_element call?\n",
cmd->name, cmd->string, ntype, node_names[ntype]);
return;
}
assert(hash_get(cnode->cmd_hash, cmd, hash_alloc_intern));
struct graph *graph = graph_new();
struct cmd_token *token =
cmd_token_new(START_TKN, CMD_ATTR_NORMAL, NULL, NULL);
graph_new_node(graph, token, (void (*)(void *)) & cmd_token_del);
cmd_graph_parse(graph, cmd);
cmd_graph_names(graph);
cmd_graph_merge(cnode->cmdgraph, graph, +1);
graph_delete_graph(graph);
vector_set(cnode->cmd_vector, cmd);
if (ntype == VIEW_NODE)
install_element(ENABLE_NODE, cmd);
}
void uninstall_element(enum node_type ntype, struct cmd_element *cmd)
{
struct cmd_node *cnode;
/* cmd_init hasn't been called */
if (!cmdvec) {
fprintf(stderr, "%s called before cmd_init, breakage likely\n",
__func__);
return;
}
cnode = vector_lookup(cmdvec, ntype);
if (cnode == NULL) {
fprintf(stderr,
"%s[%s]:\n"
"\tnode %d (%s) does not exist.\n"
"\tplease call install_node() before uninstall_element()\n",
cmd->name, cmd->string, ntype, node_names[ntype]);
exit(EXIT_FAILURE);
}
if (hash_release(cnode->cmd_hash, cmd) == NULL) {
fprintf(stderr,
"%s[%s]:\n"
"\tnode %d (%s) does not have this command installed.\n"
"\tduplicate uninstall_element call?\n",
cmd->name, cmd->string, ntype, node_names[ntype]);
return;
}
vector_unset_value(cnode->cmd_vector, cmd);
struct graph *graph = graph_new();
struct cmd_token *token =
cmd_token_new(START_TKN, CMD_ATTR_NORMAL, NULL, NULL);
graph_new_node(graph, token, (void (*)(void *)) & cmd_token_del);
cmd_graph_parse(graph, cmd);
cmd_graph_names(graph);
cmd_graph_merge(cnode->cmdgraph, graph, -1);
graph_delete_graph(graph);
if (ntype == VIEW_NODE)
uninstall_element(ENABLE_NODE, cmd);
}
static const unsigned char itoa64[] =
"./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
static void to64(char *s, long v, int n)
{
while (--n >= 0) {
*s++ = itoa64[v & 0x3f];
v >>= 6;
}
}
static char *zencrypt(const char *passwd)
{
char salt[6];
struct timeval tv;
char *crypt(const char *, const char *);
gettimeofday(&tv, 0);
to64(&salt[0], random(), 3);
to64(&salt[3], tv.tv_usec, 3);
salt[5] = '\0';
return crypt(passwd, salt);
}
/* This function write configuration of this host. */
static int config_write_host(struct vty *vty)
{
if (cmd_hostname_get())
vty_out(vty, "hostname %s\n", cmd_hostname_get());
if (cmd_domainname_get())
vty_out(vty, "domainname %s\n", cmd_domainname_get());
if (host.encrypt) {
if (host.password_encrypt)
vty_out(vty, "password 8 %s\n", host.password_encrypt);
if (host.enable_encrypt)
vty_out(vty, "enable password 8 %s\n",
host.enable_encrypt);
} else {
if (host.password)
vty_out(vty, "password %s\n", host.password);
if (host.enable)
vty_out(vty, "enable password %s\n", host.enable);
}
if (zlog_default->default_lvl != LOG_DEBUG) {
vty_out(vty, "! N.B. The 'log trap' command is deprecated.\n");
vty_out(vty, "log trap %s\n",
zlog_priority[zlog_default->default_lvl]);
}
if (host.logfile
&& (zlog_default->maxlvl[ZLOG_DEST_FILE] != ZLOG_DISABLED)) {
vty_out(vty, "log file %s", host.logfile);
if (zlog_default->maxlvl[ZLOG_DEST_FILE]
!= zlog_default->default_lvl)
vty_out(vty, " %s",
zlog_priority
[zlog_default->maxlvl[ZLOG_DEST_FILE]]);
vty_out(vty, "\n");
}
if (zlog_default->maxlvl[ZLOG_DEST_STDOUT] != ZLOG_DISABLED) {
vty_out(vty, "log stdout");
if (zlog_default->maxlvl[ZLOG_DEST_STDOUT]
!= zlog_default->default_lvl)
vty_out(vty, " %s",
zlog_priority[zlog_default->maxlvl
[ZLOG_DEST_STDOUT]]);
vty_out(vty, "\n");
}
if (zlog_default->maxlvl[ZLOG_DEST_MONITOR] == ZLOG_DISABLED)
vty_out(vty, "no log monitor\n");
else if (zlog_default->maxlvl[ZLOG_DEST_MONITOR]
!= zlog_default->default_lvl)
vty_out(vty, "log monitor %s\n",
zlog_priority[zlog_default->maxlvl[ZLOG_DEST_MONITOR]]);
if (zlog_default->maxlvl[ZLOG_DEST_SYSLOG] != ZLOG_DISABLED) {
vty_out(vty, "log syslog");
if (zlog_default->maxlvl[ZLOG_DEST_SYSLOG]
!= zlog_default->default_lvl)
vty_out(vty, " %s",
zlog_priority[zlog_default->maxlvl
[ZLOG_DEST_SYSLOG]]);
vty_out(vty, "\n");
}
if (zlog_default->facility != LOG_DAEMON)
vty_out(vty, "log facility %s\n",
facility_name(zlog_default->facility));
if (zlog_default->record_priority == 1)
vty_out(vty, "log record-priority\n");
if (zlog_default->timestamp_precision > 0)
vty_out(vty, "log timestamp precision %d\n",
zlog_default->timestamp_precision);
if (host.advanced)
vty_out(vty, "service advanced-vty\n");
if (host.encrypt)
vty_out(vty, "service password-encryption\n");
if (host.lines >= 0)
vty_out(vty, "service terminal-length %d\n", host.lines);
if (host.motdfile)
vty_out(vty, "banner motd file %s\n", host.motdfile);
else if (!host.motd)
vty_out(vty, "no banner motd\n");
if (debug_memstats_at_exit)
vty_out(vty, "!\ndebug memstats-at-exit\n");
return 1;
}
/* Utility function for getting command graph. */
static struct graph *cmd_node_graph(vector v, enum node_type ntype)
{
struct cmd_node *cnode = vector_slot(v, ntype);
return cnode->cmdgraph;
}
static int cmd_try_do_shortcut(enum node_type node, char *first_word)
{
if (first_word != NULL && node != AUTH_NODE && node != VIEW_NODE
&& node != AUTH_ENABLE_NODE && 0 == strcmp("do", first_word))
return 1;
return 0;
}
/**
* Compare function for cmd_token.
* Used with qsort to sort command completions.
*/
static int compare_completions(const void *fst, const void *snd)
{
struct cmd_token *first = *(struct cmd_token **)fst,
*secnd = *(struct cmd_token **)snd;
return strcmp(first->text, secnd->text);
}
/**
* Takes a list of completions returned by command_complete,
* dedeuplicates them based on both text and description,
* sorts them, and returns them as a vector.
*
* @param completions linked list of cmd_token
* @return deduplicated and sorted vector with
*/
vector completions_to_vec(struct list *completions)
{
vector comps = vector_init(VECTOR_MIN_SIZE);
struct listnode *ln;
struct cmd_token *token, *cr = NULL;
unsigned int i, exists;
for (ALL_LIST_ELEMENTS_RO(completions, ln, token)) {
if (token->type == END_TKN && (cr = token))
continue;
// linear search for token in completions vector
exists = 0;
for (i = 0; i < vector_active(comps) && !exists; i++) {
struct cmd_token *curr = vector_slot(comps, i);
#ifdef VTYSH_DEBUG
exists = !strcmp(curr->text, token->text)
&& !strcmp(curr->desc, token->desc);
#else
exists = !strcmp(curr->text, token->text);
#endif /* VTYSH_DEBUG */
}
if (!exists)
vector_set(comps, token);
}
// sort completions
qsort(comps->index, vector_active(comps), sizeof(void *),
&compare_completions);
// make <cr> the first element, if it is present
if (cr) {
vector_set_index(comps, vector_active(comps), NULL);
memmove(comps->index + 1, comps->index,
(comps->alloced - 1) * sizeof(void *));
vector_set_index(comps, 0, cr);
}
return comps;
}
/**
* Generates a vector of cmd_token representing possible completions
* on the current input.
*
* @param vline the vectorized input line
* @param vty the vty with the node to match on
* @param status pointer to matcher status code
* @return vector of struct cmd_token * with possible completions
*/
static vector cmd_complete_command_real(vector vline, struct vty *vty,
int *status)
{
struct list *completions;
struct graph *cmdgraph = cmd_node_graph(cmdvec, vty->node);
enum matcher_rv rv = command_complete(cmdgraph, vline, &completions);
if (MATCHER_ERROR(rv)) {
*status = CMD_ERR_NO_MATCH;
return NULL;
}
vector comps = completions_to_vec(completions);
list_delete_and_null(&completions);
// set status code appropriately
switch (vector_active(comps)) {
case 0:
*status = CMD_ERR_NO_MATCH;
break;
case 1:
*status = CMD_COMPLETE_FULL_MATCH;
break;
default:
*status = CMD_COMPLETE_LIST_MATCH;
}
return comps;
}
vector cmd_describe_command(vector vline, struct vty *vty, int *status)
{
vector ret;
if (cmd_try_do_shortcut(vty->node, vector_slot(vline, 0))) {
enum node_type onode;
vector shifted_vline;
unsigned int index;
onode = vty->node;
vty->node = ENABLE_NODE;
/* We can try it on enable node, cos' the vty is authenticated
*/
shifted_vline = vector_init(vector_count(vline));
/* use memcpy? */
for (index = 1; index < vector_active(vline); index++) {
vector_set_index(shifted_vline, index - 1,
vector_lookup(vline, index));
}
ret = cmd_complete_command_real(shifted_vline, vty, status);
vector_free(shifted_vline);
vty->node = onode;
return ret;
}
return cmd_complete_command_real(vline, vty, status);
}
static struct list *varhandlers = NULL;
void cmd_variable_complete(struct cmd_token *token, const char *arg,
vector comps)
{
struct listnode *ln;
const struct cmd_variable_handler *cvh;
size_t i, argsz;
vector tmpcomps;
tmpcomps = arg ? vector_init(VECTOR_MIN_SIZE) : comps;
for (ALL_LIST_ELEMENTS_RO(varhandlers, ln, cvh)) {
if (cvh->tokenname && strcmp(cvh->tokenname, token->text))
continue;
if (cvh->varname && (!token->varname
|| strcmp(cvh->varname, token->varname)))
continue;
cvh->completions(tmpcomps, token);
break;
}
if (!arg)
return;
argsz = strlen(arg);
for (i = vector_active(tmpcomps); i; i--) {
char *item = vector_slot(tmpcomps, i - 1);
if (strlen(item) >= argsz && !strncmp(item, arg, argsz))
vector_set(comps, item);
else
XFREE(MTYPE_COMPLETION, item);
}
vector_free(tmpcomps);
}
#define AUTOCOMP_INDENT 5
char *cmd_variable_comp2str(vector comps, unsigned short cols)
{
size_t bsz = 16;
char *buf = XCALLOC(MTYPE_TMP, bsz);
int lc = AUTOCOMP_INDENT;
size_t cs = AUTOCOMP_INDENT;
size_t itemlen;
snprintf(buf, bsz, "%*s", AUTOCOMP_INDENT, "");
for (size_t j = 0; j < vector_active(comps); j++) {
char *item = vector_slot(comps, j);
itemlen = strlen(item);
if (cs + itemlen + AUTOCOMP_INDENT + 3 >= bsz)
buf = XREALLOC(MTYPE_TMP, buf, (bsz *= 2));
if (lc + itemlen + 1 >= cols) {
cs += snprintf(&buf[cs], bsz - cs, "\n%*s",
AUTOCOMP_INDENT, "");
lc = AUTOCOMP_INDENT;
}
size_t written = snprintf(&buf[cs], bsz - cs, "%s ", item);
lc += written;
cs += written;
XFREE(MTYPE_COMPLETION, item);
vector_set_index(comps, j, NULL);
}
return buf;
}
void cmd_variable_handler_register(const struct cmd_variable_handler *cvh)
{
if (!varhandlers)
return;
for (; cvh->completions; cvh++)
listnode_add(varhandlers, (void *)cvh);
}
DEFUN_HIDDEN (autocomplete,
autocomplete_cmd,
"autocomplete TYPE TEXT VARNAME",
"Autocompletion handler (internal, for vtysh)\n"
"cmd_token->type\n"
"cmd_token->text\n"
"cmd_token->varname\n")
{
struct cmd_token tok;
vector comps = vector_init(32);
size_t i;
memset(&tok, 0, sizeof(tok));
tok.type = atoi(argv[1]->arg);
tok.text = argv[2]->arg;
tok.varname = argv[3]->arg;
if (!strcmp(tok.varname, "-"))
tok.varname = NULL;
cmd_variable_complete(&tok, NULL, comps);
for (i = 0; i < vector_active(comps); i++) {
char *text = vector_slot(comps, i);
vty_out(vty, "%s\n", text);
XFREE(MTYPE_COMPLETION, text);
}
vector_free(comps);
return CMD_SUCCESS;
}
/**
* Generate possible tab-completions for the given input. This function only
* returns results that would result in a valid command if used as Readline
* completions (as is the case in vtysh). For instance, if the passed vline ends
* with '4.3.2', the strings 'A.B.C.D' and 'A.B.C.D/M' will _not_ be returned.
*
* @param vline vectorized input line
* @param vty the vty
* @param status location to store matcher status code in
* @return set of valid strings for use with Readline as tab-completions.
*/
char **cmd_complete_command(vector vline, struct vty *vty, int *status)
{
char **ret = NULL;
int original_node = vty->node;
vector input_line = vector_init(vector_count(vline));
// if the first token is 'do' we'll want to execute the command in the
// enable node
int do_shortcut = cmd_try_do_shortcut(vty->node, vector_slot(vline, 0));
vty->node = do_shortcut ? ENABLE_NODE : original_node;
// construct the input line we'll be matching on
unsigned int offset = (do_shortcut) ? 1 : 0;
for (unsigned index = 0; index + offset < vector_active(vline); index++)
vector_set_index(input_line, index,
vector_lookup(vline, index + offset));
// get token completions -- this is a copying operation
vector comps = NULL, initial_comps;
initial_comps = cmd_complete_command_real(input_line, vty, status);
if (!MATCHER_ERROR(*status)) {
assert(initial_comps);
// filter out everything that is not suitable for a
// tab-completion
comps = vector_init(VECTOR_MIN_SIZE);
for (unsigned int i = 0; i < vector_active(initial_comps);
i++) {
struct cmd_token *token = vector_slot(initial_comps, i);
if (token->type == WORD_TKN)
vector_set(comps, XSTRDUP(MTYPE_COMPLETION,
token->text));
else if (IS_VARYING_TOKEN(token->type)) {
const char *ref = vector_lookup(
vline, vector_active(vline) - 1);
cmd_variable_complete(token, ref, comps);
}
}
vector_free(initial_comps);
// since we filtered results, we need to re-set status code
switch (vector_active(comps)) {
case 0:
*status = CMD_ERR_NO_MATCH;
break;
case 1:
*status = CMD_COMPLETE_FULL_MATCH;
break;
default:
*status = CMD_COMPLETE_LIST_MATCH;
}
// copy completions text into an array of char*
ret = XMALLOC(MTYPE_TMP,
(vector_active(comps) + 1) * sizeof(char *));
unsigned int i;
for (i = 0; i < vector_active(comps); i++) {
ret[i] = vector_slot(comps, i);
}
// set the last element to NULL, because this array is used in
// a Readline completion_generator function which expects NULL
// as a sentinel value
ret[i] = NULL;
vector_free(comps);
comps = NULL;
} else if (initial_comps)
vector_free(initial_comps);
// comps should always be null here
assert(!comps);
// free the adjusted input line
vector_free(input_line);
// reset vty->node to its original value
vty->node = original_node;
return ret;
}
/* return parent node */
/* MUST eventually converge on CONFIG_NODE */
enum node_type node_parent(enum node_type node)
{
enum node_type ret;
assert(node > CONFIG_NODE);
switch (node) {
case BGP_VPNV4_NODE:
case BGP_VPNV6_NODE:
case BGP_FLOWSPECV4_NODE:
case BGP_FLOWSPECV6_NODE:
case BGP_VRF_POLICY_NODE:
case BGP_VNC_DEFAULTS_NODE:
case BGP_VNC_NVE_GROUP_NODE:
case BGP_VNC_L2_GROUP_NODE:
case BGP_IPV4_NODE:
case BGP_IPV4M_NODE:
case BGP_IPV4L_NODE:
case BGP_IPV6_NODE:
case BGP_IPV6M_NODE:
case BGP_EVPN_NODE:
case BGP_IPV6L_NODE:
ret = BGP_NODE;
break;
case BGP_EVPN_VNI_NODE:
ret = BGP_EVPN_NODE;
break;
case KEYCHAIN_KEY_NODE:
ret = KEYCHAIN_NODE;
break;
case LINK_PARAMS_NODE:
ret = INTERFACE_NODE;
break;