]>
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
, "type: %d ", token
->type
);
218 fprintf(stdout
, "min: %d - ", minmatch
);
221 fprintf(stdout
, "trivial_match ");
224 fprintf(stdout
, "no_match ");
227 fprintf(stdout
, "partly_match ");
230 fprintf(stdout
, "exact_match ");
234 fprintf(stdout
, " MATCH");
235 fprintf(stdout
, "\n");
238 // if we don't match this node, die
239 if (match_token(token
, input_token
) < minmatch
)
240 return MATCHER_NO_MATCH
;
244 // pointers for iterating linklist
246 struct graph_node
*gn
;
248 // get all possible nexthops
249 struct list
*next
= list_new();
250 add_nexthops(next
, start
, NULL
, 0);
252 // determine the best match
253 for (ALL_LIST_ELEMENTS_RO(next
, ln
, gn
)) {
254 // if we've matched all input we're looking for END_TKN
255 if (n
+ 1 == vector_active(vline
)) {
256 struct cmd_token
*tok
= gn
->data
;
257 if (tok
->type
== END_TKN
) {
258 // if more than one END_TKN in the follow set
260 status
= MATCHER_AMBIGUOUS
;
265 *currbest
= list_new();
266 // node should have one child node with the
268 struct graph_node
*leaf
=
269 vector_slot(gn
->to
, 0);
270 // last node in the list will hold the
271 // cmd_element; this is important because
272 // list_delete() expects that all nodes have
273 // the same data type, so when deleting this
274 // list the last node must be manually deleted
275 struct cmd_element
*el
= leaf
->data
;
276 listnode_add(*currbest
, el
);
278 (void (*)(void *)) & cmd_token_del
;
279 // do not break immediately; continue walking
280 // through the follow set to ensure that there
281 // is exactly one END_TKN
286 // else recurse on candidate child node
287 struct list
*result
= NULL
;
288 enum matcher_rv rstat
=
289 command_match_r(gn
, vline
, n
+ 1, stack
, &result
);
291 // save the best match
292 if (result
&& *currbest
) {
293 // pick the best of two matches
294 struct list
*newbest
=
295 disambiguate(*currbest
, result
, vline
, n
+ 1);
297 // current best and result are ambiguous
299 status
= MATCHER_AMBIGUOUS
;
300 // current best is still the best, but ambiguous
301 else if (newbest
== *currbest
302 && status
== MATCHER_AMBIGUOUS
)
303 status
= MATCHER_AMBIGUOUS
;
304 // result is better, but also ambiguous
305 else if (newbest
== result
306 && rstat
== MATCHER_AMBIGUOUS
)
307 status
= MATCHER_AMBIGUOUS
;
308 // one or the other is superior and not ambiguous
312 // delete the unnecessary result
313 struct list
*todelete
=
314 ((newbest
&& newbest
== result
) ? *currbest
316 del_arglist(todelete
);
318 *currbest
= newbest
? newbest
: *currbest
;
322 } else if (!*currbest
) {
323 status
= MAX(rstat
, status
);
327 // copy token, set arg and prepend to currbest
328 struct cmd_token
*token
= start
->data
;
329 struct cmd_token
*copy
= cmd_token_dup(token
);
330 copy
->arg
= XSTRDUP(MTYPE_CMD_ARG
, input_token
);
331 listnode_add_before(*currbest
, (*currbest
)->head
, copy
);
332 } else if (n
+ 1 == vector_active(vline
) && status
== MATCHER_NO_MATCH
)
333 status
= MATCHER_INCOMPLETE
;
336 list_delete_and_null(&next
);
341 static void stack_del(void *val
)
343 XFREE(MTYPE_CMD_MATCHSTACK
, val
);
346 enum matcher_rv
command_complete(struct graph
*graph
, vector vline
,
347 struct list
**completions
)
349 // pointer to next input token to match
354 list_new(), // current nodes to match input token against
355 *next
= list_new(); // possible next hops after current input
357 current
->del
= next
->del
= stack_del
;
359 // pointers used for iterating lists
360 struct graph_node
**gstack
, **newstack
;
361 struct listnode
*node
;
363 // add all children of start node to list
364 struct graph_node
*start
= vector_slot(graph
->nodes
, 0);
365 add_nexthops(next
, start
, &start
, 0);
368 for (idx
= 0; idx
< vector_active(vline
) && next
->count
> 0; idx
++) {
369 list_delete_and_null(¤t
);
372 next
->del
= stack_del
;
374 input_token
= vector_slot(vline
, idx
);
376 int exact_match_exists
= 0;
377 for (ALL_LIST_ELEMENTS_RO(current
, node
, gstack
))
378 if (!exact_match_exists
)
380 (match_token(gstack
[0]->data
,
386 for (ALL_LIST_ELEMENTS_RO(current
, node
, gstack
)) {
387 struct cmd_token
*token
= gstack
[0]->data
;
389 if (token
->attr
== CMD_ATTR_HIDDEN
390 || token
->attr
== CMD_ATTR_DEPRECATED
)
393 enum match_type minmatch
= min_match_level(token
->type
);
394 trace_matcher("\"%s\" matches \"%s\" (%d) ? ",
395 input_token
, token
->text
, token
->type
);
397 unsigned int last_token
=
398 (vector_active(vline
) - 1 == idx
);
399 enum match_type matchtype
=
400 match_token(token
, input_token
);
402 // occurs when last token is whitespace
404 trace_matcher("trivial_match\n");
406 newstack
= XMALLOC(MTYPE_CMD_MATCHSTACK
,
407 sizeof(struct graph_node
*));
408 /* we're not recursing here, just the first
410 newstack
[0] = gstack
[0];
411 listnode_add(next
, newstack
);
414 trace_matcher("trivial_match\n");
415 if (exact_match_exists
&& !last_token
)
419 trace_matcher("exact_match\n");
422 MTYPE_CMD_MATCHSTACK
,
423 sizeof(struct graph_node
*));
424 /* same as above, not recursing on this
426 newstack
[0] = gstack
[0];
427 listnode_add(next
, newstack
);
428 } else if (matchtype
>= minmatch
)
429 add_nexthops(next
, gstack
[0], gstack
,
433 trace_matcher("no_match\n");
440 * -----------------------------------------------------------------
441 * token = last input token processed
442 * idx = index in `command` of last token processed
443 * current = set of all transitions from the previous input token
444 * next = set of all nodes reachable from all nodes in `matched`
447 enum matcher_rv mrv
= idx
== vector_active(vline
) && next
->count
452 if (!MATCHER_ERROR(mrv
)) {
453 // extract cmd_token into list
454 *completions
= list_new();
455 for (ALL_LIST_ELEMENTS_RO(next
, node
, gstack
)) {
456 listnode_add(*completions
, gstack
[0]->data
);
460 list_delete_and_null(¤t
);
461 list_delete_and_null(&next
);
467 * Adds all children that are reachable by one parser hop to the given list.
468 * special tokens except END_TKN are treated as transparent.
470 * @param[in] list to add the nexthops to
471 * @param[in] node to start calculating nexthops from
472 * @param[in] stack listing previously visited nodes, if non-NULL.
473 * @param[in] stackpos how many valid entries are in stack
474 * @return the number of children added to the list
476 * NB: non-null "stack" means that new stacks will be added to "list" as
477 * output, instead of direct node pointers!
479 static int add_nexthops(struct list
*list
, struct graph_node
*node
,
480 struct graph_node
**stack
, size_t stackpos
)
483 struct graph_node
*child
;
484 struct graph_node
**nextstack
;
485 for (unsigned int i
= 0; i
< vector_active(node
->to
); i
++) {
486 child
= vector_slot(node
->to
, i
);
488 struct cmd_token
*token
= child
->data
;
489 if (!token
->allowrepeat
&& stack
) {
490 for (j
= 0; j
< stackpos
; j
++)
491 if (child
== stack
[j
])
496 if (token
->type
>= SPECIAL_TKN
&& token
->type
!= END_TKN
) {
497 added
+= add_nexthops(list
, child
, stack
, stackpos
);
501 MTYPE_CMD_MATCHSTACK
,
503 * sizeof(struct graph_node
*));
504 nextstack
[0] = child
;
505 memcpy(nextstack
+ 1, stack
,
506 stackpos
* sizeof(struct graph_node
*));
508 listnode_add(list
, nextstack
);
510 listnode_add(list
, child
);
519 * Determines the node types for which a partial match may count as a full
520 * match. Enables command abbrevations.
522 * @param[in] type node type
523 * @return minimum match level needed to for a token to fully match
525 static enum match_type
min_match_level(enum cmd_token_type type
)
528 // anything matches a start node, for the sake of recursion
531 // allowing words to partly match enables command abbreviation
540 * Assigns precedence scores to node types.
542 * @param[in] type node type to score
543 * @return precedence score
545 static int score_precedence(enum cmd_token_type type
)
548 // some of these are mutually exclusive, so they share
549 // the same precedence value
551 case IPV4_PREFIX_TKN
:
553 case IPV6_PREFIX_TKN
:
568 * Picks the better of two possible matches for a token.
570 * @param[in] first candidate node matching token
571 * @param[in] second candidate node matching token
572 * @param[in] token the token being matched
573 * @return the best-matching node, or NULL if the two are entirely ambiguous
575 static struct cmd_token
*disambiguate_tokens(struct cmd_token
*first
,
576 struct cmd_token
*second
,
579 // if the types are different, simply go off of type precedence
580 if (first
->type
!= second
->type
) {
581 int firstprec
= score_precedence(first
->type
);
582 int secndprec
= score_precedence(second
->type
);
583 if (firstprec
!= secndprec
)
584 return firstprec
< secndprec
? first
: second
;
589 // if they're the same, return the more exact match
590 enum match_type fmtype
= match_token(first
, input_token
);
591 enum match_type smtype
= match_token(second
, input_token
);
592 if (fmtype
!= smtype
)
593 return fmtype
> smtype
? first
: second
;
599 * Picks the better of two possible matches for an input line.
601 * @param[in] first candidate list of cmd_token matching vline
602 * @param[in] second candidate list of cmd_token matching vline
603 * @param[in] vline the input line being matched
604 * @param[in] n index into vline to start comparing at
605 * @return the best-matching list, or NULL if the two are entirely ambiguous
607 static struct list
*disambiguate(struct list
*first
, struct list
*second
,
608 vector vline
, unsigned int n
)
610 // doesn't make sense for these to be inequal length
611 assert(first
->count
== second
->count
);
612 assert(first
->count
== vector_active(vline
) - n
+ 1);
614 struct listnode
*fnode
= listhead(first
), *snode
= listhead(second
);
615 struct cmd_token
*ftok
= listgetdata(fnode
), *stok
= listgetdata(snode
),
618 // compare each token, if one matches better use that one
619 for (unsigned int i
= n
; i
< vector_active(vline
); i
++) {
620 char *token
= vector_slot(vline
, i
);
621 if ((best
= disambiguate_tokens(ftok
, stok
, token
)))
622 return best
== ftok
? first
: second
;
623 fnode
= listnextnode(fnode
);
624 snode
= listnextnode(snode
);
625 ftok
= listgetdata(fnode
);
626 stok
= listgetdata(snode
);
633 * Deletion function for arglist.
635 * Since list->del for arglists expects all listnode->data to hold cmd_token,
636 * but arglists have cmd_element as the data for the tail, this function
637 * manually deletes the tail before deleting the rest of the list as usual.
639 * The cmd_element at the end is *not* a copy. It is the one and only.
641 * @param list the arglist to delete
643 static void del_arglist(struct list
*list
)
645 // manually delete last node
646 struct listnode
*tail
= listtail(list
);
648 list_delete_node(list
, tail
);
650 // delete the rest of the list as usual
651 list_delete_and_null(&list
);
654 /*---------- token level matching functions ----------*/
656 static enum match_type
match_token(struct cmd_token
*token
, char *input_token
)
658 // nothing trivially matches everything
660 return trivial_match
;
662 switch (token
->type
) {
664 return match_word(token
, input_token
);
666 return match_ipv4(input_token
);
667 case IPV4_PREFIX_TKN
:
668 return match_ipv4_prefix(input_token
);
670 return match_ipv6_prefix(input_token
, false);
671 case IPV6_PREFIX_TKN
:
672 return match_ipv6_prefix(input_token
, true);
674 return match_range(token
, input_token
);
676 return match_variable(token
, input_token
);
678 return match_mac(input_token
, false);
680 return match_mac(input_token
, true);
687 #define IPV4_ADDR_STR "0123456789."
688 #define IPV4_PREFIX_STR "0123456789./"
690 static enum match_type
match_ipv4(const char *str
)
693 int dots
= 0, nums
= 0;
697 memset(buf
, 0, sizeof(buf
));
699 while (*str
!= '\0') {
704 if (*(str
+ 1) == '.')
707 if (*(str
+ 1) == '\0')
713 if (!isdigit((int)*str
))
722 strncpy(buf
, sp
, str
- sp
);
740 static enum match_type
match_ipv4_prefix(const char *str
)
747 memset(buf
, 0, sizeof(buf
));
749 while (*str
!= '\0' && *str
!= '/') {
754 if (*(str
+ 1) == '.' || *(str
+ 1) == '/')
757 if (*(str
+ 1) == '\0')
764 if (!isdigit((int)*str
))
773 strncpy(buf
, sp
, str
- sp
);
779 if (*(str
+ 1) == '\0')
784 } else if (*str
== '\0')
795 while (*str
!= '\0') {
796 if (!isdigit((int)*str
))
809 #define IPV6_ADDR_STR "0123456789abcdefABCDEF:."
810 #define IPV6_PREFIX_STR "0123456789abcdefABCDEF:./"
811 #define STATE_START 1
812 #define STATE_COLON 2
813 #define STATE_DOUBLE 3
816 #define STATE_SLASH 6
819 static enum match_type
match_ipv6_prefix(const char *str
, bool prefix
)
821 int state
= STATE_START
;
822 int colons
= 0, nums
= 0, double_colon
= 0;
824 const char *sp
= NULL
, *start
= str
;
830 if (strspn(str
, prefix
? IPV6_PREFIX_STR
: IPV6_ADDR_STR
)
834 while (*str
!= '\0' && state
!= STATE_MASK
) {
838 if (*(str
+ 1) != ':' && *(str
+ 1) != '\0')
850 if (*(str
+ 1) == '/')
852 else if (*(str
+ 1) == ':')
853 state
= STATE_DOUBLE
;
863 if (*(str
+ 1) == ':')
866 if (*(str
+ 1) != '\0' && *(str
+ 1) != '/')
870 if (*(str
+ 1) == '/')
880 if (*(str
+ 1) == ':' || *(str
+ 1) == '.'
881 || *(str
+ 1) == '\0' || *(str
+ 1) == '/') {
885 for (; sp
<= str
; sp
++)
891 if (*(str
+ 1) == ':')
893 else if (*(str
+ 1) == '.') {
894 if (colons
|| double_colon
)
898 } else if (*(str
+ 1) == '/')
906 if (*(str
+ 1) == '\0')
925 struct sockaddr_in6 sin6_dummy
;
926 int ret
= inet_pton(AF_INET6
, start
, &sin6_dummy
.sin6_addr
);
927 return ret
== 1 ? exact_match
: partly_match
;
930 if (state
< STATE_MASK
)
933 mask
= strtol(str
, &endptr
, 10);
937 if (mask
< 0 || mask
> 128)
943 static enum match_type
match_range(struct cmd_token
*token
, const char *str
)
945 assert(token
->type
== RANGE_TKN
);
950 val
= strtoll(str
, &endptr
, 10);
954 if (val
< token
->min
|| val
> token
->max
)
960 static enum match_type
match_word(struct cmd_token
*token
, const char *word
)
962 assert(token
->type
== WORD_TKN
);
964 // if the passed token is 0 length, partly match
968 // if the passed token is strictly a prefix of the full word, partly
970 if (strlen(word
) < strlen(token
->text
))
971 return !strncmp(token
->text
, word
, strlen(word
)) ? partly_match
974 // if they are the same length and exactly equal, exact match
975 else if (strlen(word
) == strlen(token
->text
))
976 return !strncmp(token
->text
, word
, strlen(word
)) ? exact_match
982 static enum match_type
match_variable(struct cmd_token
*token
, const char *word
)
984 assert(token
->type
== VARIABLE_TKN
);
988 #define MAC_CHARS "ABCDEFabcdef0123456789:"
990 static enum match_type
match_mac(const char *word
, bool prefix
)
992 /* 6 2-digit hex numbers separated by 5 colons */
993 size_t mac_explen
= 6 * 2 + 5;
994 /* '/' + 2-digit integer */
995 size_t mask_len
= 1 + 2;
998 unsigned int maskval
;
1001 if (strlen(word
) > mac_explen
+ (prefix
? mask_len
: 0))
1005 for (i
= 0; i
< mac_explen
; i
++) {
1006 if (word
[i
] == '\0' || !strchr(MAC_CHARS
, word
[i
]))
1008 if (((i
+ 1) % 3 == 0) != (word
[i
] == ':'))
1012 /* incomplete address */
1013 if (i
< mac_explen
&& word
[i
] == '\0')
1014 return partly_match
;
1015 else if (i
< mac_explen
)
1019 if (prefix
&& word
[i
] == '/') {
1020 if (word
[++i
] == '\0')
1021 return partly_match
;
1023 maskval
= strtoul(&word
[i
], &eptr
, 10);
1024 if (*eptr
!= '\0' || maskval
> 48)
1026 } else if (prefix
&& word
[i
] == '\0') {
1027 return partly_match
;
1028 } else if (prefix
) {