]>
git.proxmox.com Git - mirror_frr.git/blob - lib/command_match.c
2 * Input matching routines for CLI backend.
5 * Copyright (C) 2016 Cumulus Networks, Inc.
7 * This file is part of GNU Zebra.
9 * GNU Zebra is free software; you can redistribute it and/or modify it
10 * under the terms of the GNU General Public License as published by the
11 * Free Software Foundation; either version 2, or (at your option) any
14 * GNU Zebra is distributed in the hope that it will be useful, but
15 * WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; see the file COPYING; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
26 #include "command_match.h"
29 DEFINE_MTYPE_STATIC(LIB
, CMD_MATCHSTACK
, "Command Match Stack")
39 #define trace_matcher(...) \
42 fprintf(stderr, __VA_ARGS__); \
45 /* matcher helper prototypes */
46 static int add_nexthops(struct list
*, struct graph_node
*,
47 struct graph_node
**, size_t);
49 static enum matcher_rv
command_match_r(struct graph_node
*, vector
,
50 unsigned int, struct graph_node
**,
53 static int score_precedence(enum cmd_token_type
);
55 static enum match_type
min_match_level(enum cmd_token_type
);
57 static void del_arglist(struct list
*);
59 static struct cmd_token
*disambiguate_tokens(struct cmd_token
*,
60 struct cmd_token
*, char *);
62 static struct list
*disambiguate(struct list
*, struct list
*, vector
,
65 int compare_completions(const void *, const void *);
67 /* token matcher prototypes */
68 static enum match_type
match_token(struct cmd_token
*, char *);
70 static enum match_type
match_ipv4(const char *);
72 static enum match_type
match_ipv4_prefix(const char *);
74 static enum match_type
match_ipv6_prefix(const char *, bool);
76 static enum match_type
match_range(struct cmd_token
*, const char *);
78 static enum match_type
match_word(struct cmd_token
*, const char *);
80 static enum match_type
match_variable(struct cmd_token
*, const char *);
82 static enum match_type
match_mac(const char *, bool);
84 enum matcher_rv
command_match(struct graph
*cmdgraph
, vector vline
,
85 struct list
**argv
, const struct cmd_element
**el
)
87 struct graph_node
*stack
[MAXDEPTH
];
88 enum matcher_rv status
;
91 // prepend a dummy token to match that pesky start node
92 vector vvline
= vector_init(vline
->alloced
+ 1);
93 vector_set_index(vvline
, 0, (void *)XSTRDUP(MTYPE_TMP
, "dummy"));
94 memcpy(vvline
->index
+ 1, vline
->index
,
95 sizeof(void *) * vline
->alloced
);
96 vvline
->active
= vline
->active
+ 1;
98 struct graph_node
*start
= vector_slot(cmdgraph
->nodes
, 0);
99 status
= command_match_r(start
, vvline
, 0, stack
, argv
);
100 if (status
== MATCHER_OK
) { // successful match
101 struct listnode
*head
= listhead(*argv
);
102 struct listnode
*tail
= listtail(*argv
);
104 // delete dummy start node
105 cmd_token_del((struct cmd_token
*)head
->data
);
106 list_delete_node(*argv
, head
);
108 // get cmd_element out of list tail
109 *el
= listgetdata(tail
);
110 list_delete_node(*argv
, tail
);
112 // now argv is an ordered list of cmd_token matching the user
113 // input, with each cmd_token->arg holding the corresponding
122 trace_matcher("No match\n");
124 trace_matcher("Matched command\n->string %s\n->desc %s\n",
125 (*el
)->string
, (*el
)->doc
);
128 // free the leader token we alloc'd
129 XFREE(MTYPE_TMP
, vector_slot(vvline
, 0));
137 * Builds an argument list given a DFA and a matching input line.
139 * First the function determines if the node it is passed matches the first
140 * token of input. If it does not, it returns NULL (MATCHER_NO_MATCH). If it
141 * does match, then it saves the input token as the head of an argument list.
143 * The next step is to see if there is further input in the input line. If
144 * there is not, the current node's children are searched to see if any of them
145 * are leaves (type END_TKN). If this is the case, then the bottom of the
146 * recursion stack has been reached, the leaf is pushed onto the argument list,
147 * the current node is pushed, and the resulting argument list is
148 * returned (MATCHER_OK). If it is not the case, NULL is returned, indicating
149 * that there is no match for the input along this path (MATCHER_INCOMPLETE).
151 * If there is further input, then the function recurses on each of the current
152 * node's children, passing them the input line minus the token that was just
153 * matched. For each child, the return value of the recursive call is
154 * inspected. If it is null, then there is no match for the input along the
155 * subgraph headed by that child. If it is not null, then there is at least one
156 * input match in that subgraph (more on this in a moment).
158 * If a recursive call on a child returns a non-null value, then it has matched
159 * the input given it on the subgraph that starts with that child. However, due
160 * to the flexibility of the grammar, it is sometimes the case that two or more
161 * child graphs match the same input (two or more of the recursive calls have
162 * non-NULL return values). This is not a valid state, since only one true
163 * match is possible. In order to resolve this conflict, the function keeps a
164 * reference to the child node that most specifically matches the input. This
165 * is done by assigning each node type a precedence. If a child is found to
166 * match the remaining input, then the precedence values of the current
167 * best-matching child and this new match are compared. The node with higher
168 * precedence is kept, and the other match is discarded. Due to the recursive
169 * nature of this function, it is only necessary to compare the precedence of
170 * immediate children, since all subsequent children will already have been
171 * disambiguated in this way.
173 * In the event that two children are found to match with the same precedence,
174 * then the input is ambiguous for the passed cmd_element and NULL is returned.
176 * @param[in] start the start node.
177 * @param[in] vline the vectorized input line.
178 * @param[in] n the index of the first input token.
179 * @return A linked list of n elements. The first n-1 elements are pointers to
180 * struct cmd_token and represent the sequence of tokens matched by the input.
181 * The ->arg field of each token points to a copy of the input matched on it.
182 * The final nth element is a pointer to struct cmd_element, which is the
183 * command that was matched.
185 * If no match was found, the return value is NULL.
187 static enum matcher_rv
command_match_r(struct graph_node
*start
, vector vline
,
189 struct graph_node
**stack
,
190 struct list
**currbest
)
192 assert(n
< vector_active(vline
));
194 enum matcher_rv status
= MATCHER_NO_MATCH
;
196 // get the minimum match level that can count as a full match
197 struct cmd_token
*token
= start
->data
;
198 enum match_type minmatch
= min_match_level(token
->type
);
200 /* check history/stack of tokens
201 * this disallows matching the same one more than once if there is a
202 * circle in the graph (used for keyword arguments) */
204 return MATCHER_NO_MATCH
;
205 if (!token
->allowrepeat
)
206 for (size_t s
= 0; s
< n
; s
++)
207 if (stack
[s
] == start
)
208 return MATCHER_NO_MATCH
;
210 // get the current operating input token
211 char *input_token
= vector_slot(vline
, n
);
214 fprintf(stdout
, "\"%-20s\" matches \"%-30s\" ? ", input_token
,
216 enum match_type mt
= match_token(token
, input_token
);
217 fprintf(stdout
, "min: %d - ", minmatch
);
220 fprintf(stdout
, "trivial_match ");
223 fprintf(stdout
, "no_match ");
226 fprintf(stdout
, "partly_match ");
229 fprintf(stdout
, "exact_match ");
233 fprintf(stdout
, " MATCH");
234 fprintf(stdout
, "\n");
237 // if we don't match this node, die
238 if (match_token(token
, input_token
) < minmatch
)
239 return MATCHER_NO_MATCH
;
243 // pointers for iterating linklist
245 struct graph_node
*gn
;
247 // get all possible nexthops
248 struct list
*next
= list_new();
249 add_nexthops(next
, start
, NULL
, 0);
251 // determine the best match
252 for (ALL_LIST_ELEMENTS_RO(next
, ln
, gn
)) {
253 // if we've matched all input we're looking for END_TKN
254 if (n
+ 1 == vector_active(vline
)) {
255 struct cmd_token
*tok
= gn
->data
;
256 if (tok
->type
== END_TKN
) {
257 // if more than one END_TKN in the follow set
259 status
= MATCHER_AMBIGUOUS
;
264 *currbest
= list_new();
265 // node should have one child node with the
267 struct graph_node
*leaf
=
268 vector_slot(gn
->to
, 0);
269 // last node in the list will hold the
270 // cmd_element; this is important because
271 // list_delete() expects that all nodes have
272 // the same data type, so when deleting this
273 // list the last node must be manually deleted
274 struct cmd_element
*el
= leaf
->data
;
275 listnode_add(*currbest
, el
);
277 (void (*)(void *)) & cmd_token_del
;
278 // do not break immediately; continue walking
279 // through the follow set to ensure that there
280 // is exactly one END_TKN
285 // else recurse on candidate child node
286 struct list
*result
= NULL
;
287 enum matcher_rv rstat
=
288 command_match_r(gn
, vline
, n
+ 1, stack
, &result
);
290 // save the best match
291 if (result
&& *currbest
) {
292 // pick the best of two matches
293 struct list
*newbest
=
294 disambiguate(*currbest
, result
, vline
, n
+ 1);
296 // current best and result are ambiguous
298 status
= MATCHER_AMBIGUOUS
;
299 // current best is still the best, but ambiguous
300 else if (newbest
== *currbest
301 && status
== MATCHER_AMBIGUOUS
)
302 status
= MATCHER_AMBIGUOUS
;
303 // result is better, but also ambiguous
304 else if (newbest
== result
305 && rstat
== MATCHER_AMBIGUOUS
)
306 status
= MATCHER_AMBIGUOUS
;
307 // one or the other is superior and not ambiguous
311 // delete the unnecessary result
312 struct list
*todelete
=
313 ((newbest
&& newbest
== result
) ? *currbest
315 del_arglist(todelete
);
317 *currbest
= newbest
? newbest
: *currbest
;
321 } else if (!*currbest
) {
322 status
= MAX(rstat
, status
);
326 // copy token, set arg and prepend to currbest
327 struct cmd_token
*token
= start
->data
;
328 struct cmd_token
*copy
= cmd_token_dup(token
);
329 copy
->arg
= XSTRDUP(MTYPE_CMD_ARG
, input_token
);
330 listnode_add_before(*currbest
, (*currbest
)->head
, copy
);
331 } else if (n
+ 1 == vector_active(vline
) && status
== MATCHER_NO_MATCH
)
332 status
= MATCHER_INCOMPLETE
;
340 static void stack_del(void *val
)
342 XFREE(MTYPE_CMD_MATCHSTACK
, val
);
345 enum matcher_rv
command_complete(struct graph
*graph
, vector vline
,
346 struct list
**completions
)
348 // pointer to next input token to match
353 list_new(), // current nodes to match input token against
354 *next
= list_new(); // possible next hops after current input
356 current
->del
= next
->del
= stack_del
;
358 // pointers used for iterating lists
359 struct graph_node
**gstack
, **newstack
;
360 struct listnode
*node
;
362 // add all children of start node to list
363 struct graph_node
*start
= vector_slot(graph
->nodes
, 0);
364 add_nexthops(next
, start
, &start
, 0);
367 for (idx
= 0; idx
< vector_active(vline
) && next
->count
> 0; idx
++) {
368 list_delete(current
);
371 next
->del
= stack_del
;
373 input_token
= vector_slot(vline
, idx
);
375 int exact_match_exists
= 0;
376 for (ALL_LIST_ELEMENTS_RO(current
, node
, gstack
))
377 if (!exact_match_exists
)
379 (match_token(gstack
[0]->data
,
385 for (ALL_LIST_ELEMENTS_RO(current
, node
, gstack
)) {
386 struct cmd_token
*token
= gstack
[0]->data
;
388 if (token
->attr
== CMD_ATTR_HIDDEN
389 || token
->attr
== CMD_ATTR_DEPRECATED
)
392 enum match_type minmatch
= min_match_level(token
->type
);
393 trace_matcher("\"%s\" matches \"%s\" (%d) ? ",
394 input_token
, token
->text
, token
->type
);
396 unsigned int last_token
=
397 (vector_active(vline
) - 1 == idx
);
398 enum match_type matchtype
=
399 match_token(token
, input_token
);
401 // occurs when last token is whitespace
403 trace_matcher("trivial_match\n");
405 newstack
= XMALLOC(MTYPE_CMD_MATCHSTACK
,
406 sizeof(struct graph_node
*));
407 /* we're not recursing here, just the first
409 newstack
[0] = gstack
[0];
410 listnode_add(next
, newstack
);
413 trace_matcher("trivial_match\n");
414 if (exact_match_exists
&& !last_token
)
418 trace_matcher("exact_match\n");
421 MTYPE_CMD_MATCHSTACK
,
422 sizeof(struct graph_node
*));
423 /* same as above, not recursing on this
425 newstack
[0] = gstack
[0];
426 listnode_add(next
, newstack
);
427 } else if (matchtype
>= minmatch
)
428 add_nexthops(next
, gstack
[0], gstack
,
432 trace_matcher("no_match\n");
439 * -----------------------------------------------------------------
440 * token = last input token processed
441 * idx = index in `command` of last token processed
442 * current = set of all transitions from the previous input token
443 * next = set of all nodes reachable from all nodes in `matched`
446 enum matcher_rv mrv
= idx
== vector_active(vline
) && next
->count
451 if (!MATCHER_ERROR(mrv
)) {
452 // extract cmd_token into list
453 *completions
= list_new();
454 for (ALL_LIST_ELEMENTS_RO(next
, node
, gstack
)) {
455 listnode_add(*completions
, gstack
[0]->data
);
459 list_delete(current
);
466 * Adds all children that are reachable by one parser hop to the given list.
467 * special tokens except END_TKN are treated as transparent.
469 * @param[in] list to add the nexthops to
470 * @param[in] node to start calculating nexthops from
471 * @param[in] stack listing previously visited nodes, if non-NULL.
472 * @param[in] stackpos how many valid entries are in stack
473 * @return the number of children added to the list
475 * NB: non-null "stack" means that new stacks will be added to "list" as
476 * output, instead of direct node pointers!
478 static int add_nexthops(struct list
*list
, struct graph_node
*node
,
479 struct graph_node
**stack
, size_t stackpos
)
482 struct graph_node
*child
;
483 struct graph_node
**nextstack
;
484 for (unsigned int i
= 0; i
< vector_active(node
->to
); i
++) {
485 child
= vector_slot(node
->to
, i
);
487 struct cmd_token
*token
= child
->data
;
488 if (!token
->allowrepeat
&& stack
) {
489 for (j
= 0; j
< stackpos
; j
++)
490 if (child
== stack
[j
])
495 if (token
->type
>= SPECIAL_TKN
&& token
->type
!= END_TKN
) {
496 added
+= add_nexthops(list
, child
, stack
, stackpos
);
500 MTYPE_CMD_MATCHSTACK
,
502 * sizeof(struct graph_node
*));
503 nextstack
[0] = child
;
504 memcpy(nextstack
+ 1, stack
,
505 stackpos
* sizeof(struct graph_node
*));
507 listnode_add(list
, nextstack
);
509 listnode_add(list
, child
);
518 * Determines the node types for which a partial match may count as a full
519 * match. Enables command abbrevations.
521 * @param[in] type node type
522 * @return minimum match level needed to for a token to fully match
524 static enum match_type
min_match_level(enum cmd_token_type type
)
527 // anything matches a start node, for the sake of recursion
530 // allowing words to partly match enables command abbreviation
539 * Assigns precedence scores to node types.
541 * @param[in] type node type to score
542 * @return precedence score
544 static int score_precedence(enum cmd_token_type type
)
547 // some of these are mutually exclusive, so they share
548 // the same precedence value
550 case IPV4_PREFIX_TKN
:
552 case IPV6_PREFIX_TKN
:
567 * Picks the better of two possible matches for a token.
569 * @param[in] first candidate node matching token
570 * @param[in] second candidate node matching token
571 * @param[in] token the token being matched
572 * @return the best-matching node, or NULL if the two are entirely ambiguous
574 static struct cmd_token
*disambiguate_tokens(struct cmd_token
*first
,
575 struct cmd_token
*second
,
578 // if the types are different, simply go off of type precedence
579 if (first
->type
!= second
->type
) {
580 int firstprec
= score_precedence(first
->type
);
581 int secndprec
= score_precedence(second
->type
);
582 if (firstprec
!= secndprec
)
583 return firstprec
< secndprec
? first
: second
;
588 // if they're the same, return the more exact match
589 enum match_type fmtype
= match_token(first
, input_token
);
590 enum match_type smtype
= match_token(second
, input_token
);
591 if (fmtype
!= smtype
)
592 return fmtype
> smtype
? first
: second
;
598 * Picks the better of two possible matches for an input line.
600 * @param[in] first candidate list of cmd_token matching vline
601 * @param[in] second candidate list of cmd_token matching vline
602 * @param[in] vline the input line being matched
603 * @param[in] n index into vline to start comparing at
604 * @return the best-matching list, or NULL if the two are entirely ambiguous
606 static struct list
*disambiguate(struct list
*first
, struct list
*second
,
607 vector vline
, unsigned int n
)
609 // doesn't make sense for these to be inequal length
610 assert(first
->count
== second
->count
);
611 assert(first
->count
== vector_active(vline
) - n
+ 1);
613 struct listnode
*fnode
= listhead(first
), *snode
= listhead(second
);
614 struct cmd_token
*ftok
= listgetdata(fnode
), *stok
= listgetdata(snode
),
617 // compare each token, if one matches better use that one
618 for (unsigned int i
= n
; i
< vector_active(vline
); i
++) {
619 char *token
= vector_slot(vline
, i
);
620 if ((best
= disambiguate_tokens(ftok
, stok
, token
)))
621 return best
== ftok
? first
: second
;
622 fnode
= listnextnode(fnode
);
623 snode
= listnextnode(snode
);
624 ftok
= listgetdata(fnode
);
625 stok
= listgetdata(snode
);
632 * Deletion function for arglist.
634 * Since list->del for arglists expects all listnode->data to hold cmd_token,
635 * but arglists have cmd_element as the data for the tail, this function
636 * manually deletes the tail before deleting the rest of the list as usual.
638 * The cmd_element at the end is *not* a copy. It is the one and only.
640 * @param list the arglist to delete
642 static void del_arglist(struct list
*list
)
644 // manually delete last node
645 struct listnode
*tail
= listtail(list
);
647 list_delete_node(list
, tail
);
649 // delete the rest of the list as usual
653 /*---------- token level matching functions ----------*/
655 static enum match_type
match_token(struct cmd_token
*token
, char *input_token
)
657 // nothing trivially matches everything
659 return trivial_match
;
661 switch (token
->type
) {
663 return match_word(token
, input_token
);
665 return match_ipv4(input_token
);
666 case IPV4_PREFIX_TKN
:
667 return match_ipv4_prefix(input_token
);
669 return match_ipv6_prefix(input_token
, false);
670 case IPV6_PREFIX_TKN
:
671 return match_ipv6_prefix(input_token
, true);
673 return match_range(token
, input_token
);
675 return match_variable(token
, input_token
);
677 return match_mac(input_token
, false);
679 return match_mac(input_token
, true);
686 #define IPV4_ADDR_STR "0123456789."
687 #define IPV4_PREFIX_STR "0123456789./"
689 static enum match_type
match_ipv4(const char *str
)
692 int dots
= 0, nums
= 0;
696 memset(buf
, 0, sizeof(buf
));
698 while (*str
!= '\0') {
703 if (*(str
+ 1) == '.')
706 if (*(str
+ 1) == '\0')
712 if (!isdigit((int)*str
))
721 strncpy(buf
, sp
, str
- sp
);
739 static enum match_type
match_ipv4_prefix(const char *str
)
746 memset(buf
, 0, sizeof(buf
));
748 while (*str
!= '\0' && *str
!= '/') {
753 if (*(str
+ 1) == '.' || *(str
+ 1) == '/')
756 if (*(str
+ 1) == '\0')
763 if (!isdigit((int)*str
))
772 strncpy(buf
, sp
, str
- sp
);
778 if (*(str
+ 1) == '\0')
783 } else if (*str
== '\0')
794 while (*str
!= '\0') {
795 if (!isdigit((int)*str
))
808 #define IPV6_ADDR_STR "0123456789abcdefABCDEF:."
809 #define IPV6_PREFIX_STR "0123456789abcdefABCDEF:./"
810 #define STATE_START 1
811 #define STATE_COLON 2
812 #define STATE_DOUBLE 3
815 #define STATE_SLASH 6
818 static enum match_type
match_ipv6_prefix(const char *str
, bool prefix
)
820 int state
= STATE_START
;
821 int colons
= 0, nums
= 0, double_colon
= 0;
823 const char *sp
= NULL
, *start
= str
;
829 if (strspn(str
, prefix
? IPV6_PREFIX_STR
: IPV6_ADDR_STR
)
833 while (*str
!= '\0' && state
!= STATE_MASK
) {
837 if (*(str
+ 1) != ':' && *(str
+ 1) != '\0')
849 if (*(str
+ 1) == '/')
851 else if (*(str
+ 1) == ':')
852 state
= STATE_DOUBLE
;
862 if (*(str
+ 1) == ':')
865 if (*(str
+ 1) != '\0' && *(str
+ 1) != '/')
869 if (*(str
+ 1) == '/')
879 if (*(str
+ 1) == ':' || *(str
+ 1) == '.'
880 || *(str
+ 1) == '\0' || *(str
+ 1) == '/') {
884 for (; sp
<= str
; sp
++)
890 if (*(str
+ 1) == ':')
892 else if (*(str
+ 1) == '.') {
893 if (colons
|| double_colon
)
897 } else if (*(str
+ 1) == '/')
905 if (*(str
+ 1) == '\0')
924 struct sockaddr_in6 sin6_dummy
;
925 int ret
= inet_pton(AF_INET6
, start
, &sin6_dummy
.sin6_addr
);
926 return ret
== 1 ? exact_match
: partly_match
;
929 if (state
< STATE_MASK
)
932 mask
= strtol(str
, &endptr
, 10);
936 if (mask
< 0 || mask
> 128)
942 static enum match_type
match_range(struct cmd_token
*token
, const char *str
)
944 assert(token
->type
== RANGE_TKN
);
949 val
= strtoll(str
, &endptr
, 10);
953 if (val
< token
->min
|| val
> token
->max
)
959 static enum match_type
match_word(struct cmd_token
*token
, const char *word
)
961 assert(token
->type
== WORD_TKN
);
963 // if the passed token is 0 length, partly match
967 // if the passed token is strictly a prefix of the full word, partly
969 if (strlen(word
) < strlen(token
->text
))
970 return !strncmp(token
->text
, word
, strlen(word
)) ? partly_match
973 // if they are the same length and exactly equal, exact match
974 else if (strlen(word
) == strlen(token
->text
))
975 return !strncmp(token
->text
, word
, strlen(word
)) ? exact_match
981 static enum match_type
match_variable(struct cmd_token
*token
, const char *word
)
983 assert(token
->type
== VARIABLE_TKN
);
987 #define MAC_CHARS "ABCDEFabcdef0123456789:"
989 static enum match_type
match_mac(const char *word
, bool prefix
)
991 /* 6 2-digit hex numbers separated by 5 colons */
992 size_t mac_explen
= 6 * 2 + 5;
993 /* '/' + 2-digit integer */
994 size_t mask_len
= 1 + 2;
997 unsigned int maskval
;
1000 if (strlen(word
) > mac_explen
+ (prefix
? mask_len
: 0))
1004 for (i
= 0; i
< mac_explen
; i
++) {
1005 if (word
[i
] == '\0' || !strchr(MAC_CHARS
, word
[i
]))
1007 if (((i
+ 1) % 3 == 0) != (word
[i
] == ':'))
1011 /* incomplete address */
1012 if (i
< mac_explen
&& word
[i
] == '\0')
1013 return partly_match
;
1014 else if (i
< mac_explen
)
1018 if (prefix
&& word
[i
] == '/') {
1019 if (word
[++i
] == '\0')
1020 return partly_match
;
1022 maskval
= strtoul(&word
[i
], &eptr
, 10);
1023 if (*eptr
!= '\0' || maskval
> 48)
1025 } else if (prefix
&& word
[i
] == '\0') {
1026 return partly_match
;
1027 } else if (prefix
) {