]>
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
20 * along with GNU Zebra; see the file COPYING. If not, write to the Free
21 * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
27 #include "command_match.h"
30 DEFINE_MTYPE_STATIC(LIB
, CMD_MATCHSTACK
, "Command Match Stack")
40 #define trace_matcher(...) \
41 do { if (TM) fprintf (stderr, __VA_ARGS__); } while (0);
43 /* matcher helper prototypes */
45 add_nexthops (struct list
*, struct graph_node
*,
46 struct graph_node
**, size_t);
49 command_match_r (struct graph_node
*, vector
, unsigned int,
50 struct graph_node
**);
53 score_precedence (enum cmd_token_type
);
55 static enum match_type
56 min_match_level (enum cmd_token_type
);
59 del_arglist (struct list
*);
61 static struct cmd_token
*
62 disambiguate_tokens (struct cmd_token
*, struct cmd_token
*, char *);
65 disambiguate (struct list
*, struct list
*, vector
, unsigned int);
68 compare_completions (const void *, const void *);
70 /* token matcher prototypes */
71 static enum match_type
72 match_token (struct cmd_token
*, char *);
74 static enum match_type
75 match_ipv4 (const char *);
77 static enum match_type
78 match_ipv4_prefix (const char *);
80 static enum match_type
81 match_ipv6 (const char *);
83 static enum match_type
84 match_ipv6_prefix (const char *);
86 static enum match_type
87 match_range (struct cmd_token
*, const char *);
89 static enum match_type
90 match_word (struct cmd_token
*, const char *);
92 static enum match_type
93 match_variable (struct cmd_token
*, const char *);
95 /* matching functions */
96 static enum matcher_rv matcher_rv
;
99 command_match (struct graph
*cmdgraph
,
102 const struct cmd_element
**el
)
104 struct graph_node
*stack
[MAXDEPTH
];
105 matcher_rv
= MATCHER_NO_MATCH
;
107 // prepend a dummy token to match that pesky start node
108 vector vvline
= vector_init (vline
->alloced
+ 1);
109 vector_set_index (vvline
, 0, (void *) XSTRDUP (MTYPE_TMP
, "dummy"));
110 memcpy (vvline
->index
+ 1, vline
->index
, sizeof (void *) * vline
->alloced
);
111 vvline
->active
= vline
->active
+ 1;
113 struct graph_node
*start
= vector_slot (cmdgraph
->nodes
, 0);
114 if ((*argv
= command_match_r (start
, vvline
, 0, stack
))) // successful match
116 struct listnode
*head
= listhead (*argv
);
117 struct listnode
*tail
= listtail (*argv
);
119 // delete dummy start node
120 del_cmd_token ((struct cmd_token
*) head
->data
);
121 list_delete_node (*argv
, head
);
123 // get cmd_element out of list tail
124 *el
= listgetdata (tail
);
125 list_delete_node (*argv
, tail
);
127 // now argv is an ordered list of cmd_token matching the user
128 // input, with each cmd_token->arg holding the corresponding input
133 trace_matcher ("No match\n");
136 trace_matcher ("Matched command\n->string %s\n->desc %s\n", (*el
)->string
, (*el
)->doc
);
139 // free the leader token we alloc'd
140 XFREE (MTYPE_TMP
, vector_slot (vvline
, 0));
142 vector_free (vvline
);
148 * Builds an argument list given a DFA and a matching input line.
150 * First the function determines if the node it is passed matches the first
151 * token of input. If it does not, it returns NULL (MATCHER_NO_MATCH). If it
152 * does match, then it saves the input token as the head of an argument list.
154 * The next step is to see if there is further input in the input line. If
155 * there is not, the current node's children are searched to see if any of them
156 * are leaves (type END_TKN). If this is the case, then the bottom of the
157 * recursion stack has been reached, the leaf is pushed onto the argument list,
158 * the current node is pushed, and the resulting argument list is
159 * returned (MATCHER_OK). If it is not the case, NULL is returned, indicating
160 * that there is no match for the input along this path (MATCHER_INCOMPLETE).
162 * If there is further input, then the function recurses on each of the current
163 * node's children, passing them the input line minus the token that was just
164 * matched. For each child, the return value of the recursive call is
165 * inspected. If it is null, then there is no match for the input along the
166 * subgraph headed by that child. If it is not null, then there is at least one
167 * input match in that subgraph (more on this in a moment).
169 * If a recursive call on a child returns a non-null value, then it has matched
170 * the input given it on the subgraph that starts with that child. However, due
171 * to the flexibility of the grammar, it is sometimes the case that two or more
172 * child graphs match the same input (two or more of the recursive calls have
173 * non-NULL return values). This is not a valid state, since only one true
174 * match is possible. In order to resolve this conflict, the function keeps a
175 * reference to the child node that most specifically matches the input. This
176 * is done by assigning each node type a precedence. If a child is found to
177 * match the remaining input, then the precedence values of the current
178 * best-matching child and this new match are compared. The node with higher
179 * precedence is kept, and the other match is discarded. Due to the recursive
180 * nature of this function, it is only necessary to compare the precedence of
181 * immediate children, since all subsequent children will already have been
182 * disambiguated in this way.
184 * In the event that two children are found to match with the same precedence,
185 * then the input is ambiguous for the passed cmd_element and NULL is returned.
187 * @param[in] start the start node.
188 * @param[in] vline the vectorized input line.
189 * @param[in] n the index of the first input token.
190 * @return A linked list of n elements. The first n-1 elements are pointers to
191 * struct cmd_token and represent the sequence of tokens matched by the input.
192 * The ->arg field of each token points to a copy of the input matched on it.
193 * The final nth element is a pointer to struct cmd_element, which is the
194 * command that was matched.
196 * If no match was found, the return value is NULL.
199 command_match_r (struct graph_node
*start
, vector vline
, unsigned int n
,
200 struct graph_node
**stack
)
202 assert (n
< vector_active (vline
));
204 // get the minimum match level that can count as a full match
205 struct cmd_token
*token
= start
->data
;
206 enum match_type minmatch
= min_match_level (token
->type
);
208 /* check history/stack of tokens
209 * this disallows matching the same one more than once if there is a
210 * circle in the graph (used for keyword arguments) */
213 if (!token
->allowrepeat
)
214 for (size_t s
= 0; s
< n
; s
++)
215 if (stack
[s
] == start
)
218 // get the current operating input token
219 char *input_token
= vector_slot (vline
, n
);
222 fprintf (stdout
, "\"%-20s\" matches \"%-30s\" ? ", input_token
, token
->text
);
223 enum match_type mt
= match_token (token
, input_token
);
224 fprintf (stdout
, "min: %d - ", minmatch
);
228 fprintf (stdout
, "trivial_match ");
231 fprintf (stdout
, "no_match ");
234 fprintf (stdout
, "partly_match ");
237 fprintf (stdout
, "exact_match ");
240 if (mt
>= minmatch
) fprintf (stdout
, " MATCH");
241 fprintf (stdout
, "\n");
244 // if we don't match this node, die
245 if (match_token (token
, input_token
) < minmatch
)
250 // pointers for iterating linklist
252 struct graph_node
*gn
;
254 // get all possible nexthops
255 struct list
*next
= list_new();
256 add_nexthops (next
, start
, NULL
, 0);
258 // determine the best match
260 struct list
*currbest
= NULL
;
261 for (ALL_LIST_ELEMENTS_RO (next
,ln
,gn
))
263 // if we've matched all input we're looking for END_TKN
264 if (n
+1 == vector_active (vline
))
266 struct cmd_token
*tok
= gn
->data
;
267 if (tok
->type
== END_TKN
)
269 if (currbest
) // there is more than one END_TKN in the follow set
274 currbest
= list_new();
275 // node should have one child node with the element
276 struct graph_node
*leaf
= vector_slot (gn
->to
, 0);
277 // last node in the list will hold the cmd_element;
278 // this is important because list_delete() expects
279 // that all nodes have the same data type, so when
280 // deleting this list the last node must be
282 struct cmd_element
*el
= leaf
->data
;
283 listnode_add (currbest
, el
);
284 currbest
->del
= (void (*)(void *)) &del_cmd_token
;
285 // do not break immediately; continue walking through the follow set
286 // to ensure that there is exactly one END_TKN
291 // else recurse on candidate child node
292 struct list
*result
= command_match_r (gn
, vline
, n
+1, stack
);
294 // save the best match
295 if (result
&& currbest
)
297 // pick the best of two matches
298 struct list
*newbest
= disambiguate (currbest
, result
, vline
, n
+1);
299 // set ambiguity flag
300 ambiguous
= !newbest
|| (ambiguous
&& newbest
== currbest
);
301 // delete the unnecessary result
302 struct list
*todelete
= ((newbest
&& newbest
== result
) ? currbest
: result
);
303 del_arglist (todelete
);
305 currbest
= newbest
? newbest
: currbest
;
315 del_arglist (currbest
);
317 matcher_rv
= MATCHER_AMBIGUOUS
;
321 // copy token, set arg and prepend to currbest
322 struct cmd_token
*token
= start
->data
;
323 struct cmd_token
*copy
= copy_cmd_token (token
);
324 copy
->arg
= XSTRDUP (MTYPE_CMD_ARG
, input_token
);
325 listnode_add_before (currbest
, currbest
->head
, copy
);
326 matcher_rv
= MATCHER_OK
;
329 else if (n
+1 == vector_active (vline
) && matcher_rv
== MATCHER_NO_MATCH
)
330 matcher_rv
= MATCHER_INCOMPLETE
;
339 stack_del (void *val
)
341 XFREE (MTYPE_CMD_MATCHSTACK
, val
);
345 command_complete (struct graph
*graph
,
347 struct list
**completions
)
349 // pointer to next input token to match
352 struct list
*current
= list_new(), // current nodes to match input token against
353 *next
= list_new(); // possible next hops after current input token
354 current
->del
= next
->del
= stack_del
;
356 // pointers used for iterating lists
357 struct graph_node
**gstack
, **newstack
;
358 struct listnode
*node
;
360 // add all children of start node to list
361 struct graph_node
*start
= vector_slot (graph
->nodes
, 0);
362 add_nexthops (next
, start
, &start
, 0);
365 for (idx
= 0; idx
< vector_active (vline
) && next
->count
> 0; idx
++)
367 list_delete (current
);
370 next
->del
= stack_del
;
372 input_token
= vector_slot (vline
, idx
);
374 int exact_match_exists
= 0;
375 for (ALL_LIST_ELEMENTS_RO (current
,node
,gstack
))
376 if (!exact_match_exists
)
377 exact_match_exists
= (match_token (gstack
[0]->data
, input_token
) == exact_match
);
381 for (ALL_LIST_ELEMENTS_RO (current
,node
,gstack
))
383 struct cmd_token
*token
= gstack
[0]->data
;
385 if (token
->attr
== CMD_ATTR_HIDDEN
|| token
->attr
== CMD_ATTR_DEPRECATED
)
388 enum match_type minmatch
= min_match_level (token
->type
);
389 trace_matcher ("\"%s\" matches \"%s\" (%d) ? ",
390 input_token
, token
->text
, token
->type
);
392 unsigned int last_token
= (vector_active (vline
) - 1 == idx
);
393 enum match_type matchtype
= match_token (token
, input_token
);
396 // occurs when last token is whitespace
398 trace_matcher ("trivial_match\n");
400 newstack
= XMALLOC (MTYPE_CMD_MATCHSTACK
,
401 sizeof(struct graph_node
*));
402 /* we're not recursing here, just the first element is OK */
403 newstack
[0] = gstack
[0];
404 listnode_add (next
, newstack
);
407 trace_matcher ("trivial_match\n");
408 if (exact_match_exists
&& !last_token
)
411 trace_matcher ("exact_match\n");
414 newstack
= XMALLOC (MTYPE_CMD_MATCHSTACK
,
415 sizeof(struct graph_node
*));
416 /* same as above, not recursing on this */
417 newstack
[0] = gstack
[0];
418 listnode_add (next
, newstack
);
420 else if (matchtype
>= minmatch
)
421 add_nexthops (next
, gstack
[0], gstack
, idx
+ 1);
424 trace_matcher ("no_match\n");
431 * -----------------------------------------------------------------
432 * token = last input token processed
433 * idx = index in `command` of last token processed
434 * current = set of all transitions from the previous input token
435 * next = set of all nodes reachable from all nodes in `matched`
439 idx
== vector_active(vline
) && next
->count
?
444 if (!MATCHER_ERROR(matcher_rv
))
446 // extract cmd_token into list
447 *completions
= list_new ();
448 for (ALL_LIST_ELEMENTS_RO (next
,node
,gstack
)) {
449 listnode_add (*completions
, gstack
[0]->data
);
453 list_delete (current
);
460 * Adds all children that are reachable by one parser hop to the given list.
461 * special tokens except END_TKN are treated as transparent.
463 * @param[in] list to add the nexthops to
464 * @param[in] node to start calculating nexthops from
465 * @param[in] stack listing previously visited nodes, if non-NULL.
466 * @param[in] stackpos how many valid entries are in stack
467 * @return the number of children added to the list
469 * NB: non-null "stack" means that new stacks will be added to "list" as
470 * output, instead of direct node pointers!
473 add_nexthops (struct list
*list
, struct graph_node
*node
,
474 struct graph_node
**stack
, size_t stackpos
)
477 struct graph_node
*child
;
478 struct graph_node
**nextstack
;
479 for (unsigned int i
= 0; i
< vector_active (node
->to
); i
++)
481 child
= vector_slot (node
->to
, i
);
483 struct cmd_token
*token
= child
->data
;
484 if (!token
->allowrepeat
&& stack
)
486 for (j
= 0; j
< stackpos
; j
++)
487 if (child
== stack
[j
])
492 if (token
->type
>= SPECIAL_TKN
&& token
->type
!= END_TKN
)
494 added
+= add_nexthops (list
, child
, stack
, stackpos
);
500 nextstack
= XMALLOC (MTYPE_CMD_MATCHSTACK
,
501 (stackpos
+ 1) * sizeof(struct graph_node
*));
502 nextstack
[0] = child
;
503 memcpy(nextstack
+ 1, stack
, stackpos
* sizeof(struct graph_node
*));
505 listnode_add (list
, nextstack
);
508 listnode_add (list
, child
);
517 * Determines the node types for which a partial match may count as a full
518 * match. Enables command abbrevations.
520 * @param[in] type node type
521 * @return minimum match level needed to for a token to fully match
523 static enum match_type
524 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
546 score_precedence (enum cmd_token_type type
)
550 // some of these are mutually exclusive, so they share
551 // the same precedence value
553 case IPV4_PREFIX_TKN
:
555 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
*
576 disambiguate_tokens (struct cmd_token
*first
,
577 struct cmd_token
*second
,
580 // if the types are different, simply go off of type precedence
581 if (first
->type
!= second
->type
)
583 int firstprec
= score_precedence (first
->type
);
584 int secndprec
= score_precedence (second
->type
);
585 if (firstprec
!= secndprec
)
586 return firstprec
< secndprec
? first
: second
;
591 // if they're the same, return the more exact match
592 enum match_type fmtype
= match_token (first
, input_token
);
593 enum match_type smtype
= match_token (second
, input_token
);
594 if (fmtype
!= smtype
)
595 return fmtype
> smtype
? first
: second
;
601 * Picks the better of two possible matches for an input line.
603 * @param[in] first candidate list of cmd_token matching vline
604 * @param[in] second candidate list of cmd_token matching vline
605 * @param[in] vline the input line being matched
606 * @param[in] n index into vline to start comparing at
607 * @return the best-matching list, or NULL if the two are entirely ambiguous
610 disambiguate (struct list
*first
,
615 // doesn't make sense for these to be inequal length
616 assert (first
->count
== second
->count
);
617 assert (first
->count
== vector_active (vline
) - n
+1);
619 struct listnode
*fnode
= listhead (first
),
620 *snode
= listhead (second
);
621 struct cmd_token
*ftok
= listgetdata (fnode
),
622 *stok
= listgetdata (snode
),
625 // compare each token, if one matches better use that one
626 for (unsigned int i
= n
; i
< vector_active (vline
); i
++)
628 char *token
= vector_slot(vline
, i
);
629 if ((best
= disambiguate_tokens (ftok
, stok
, token
)))
630 return best
== ftok
? first
: second
;
631 fnode
= listnextnode (fnode
);
632 snode
= listnextnode (snode
);
633 ftok
= listgetdata (fnode
);
634 stok
= listgetdata (snode
);
641 * Deletion function for arglist.
643 * Since list->del for arglists expects all listnode->data to hold cmd_token,
644 * but arglists have cmd_element as the data for the tail, this function
645 * manually deletes the tail before deleting the rest of the list as usual.
647 * The cmd_element at the end is *not* a copy. It is the one and only.
649 * @param list the arglist to delete
652 del_arglist (struct list
*list
)
654 // manually delete last node
655 struct listnode
*tail
= listtail (list
);
657 list_delete_node (list
, tail
);
659 // delete the rest of the list as usual
663 /*---------- token level matching functions ----------*/
665 static enum match_type
666 match_token (struct cmd_token
*token
, char *input_token
)
668 // nothing trivially matches everything
670 return trivial_match
;
672 switch (token
->type
) {
674 return match_word (token
, input_token
);
676 return match_ipv4 (input_token
);
677 case IPV4_PREFIX_TKN
:
678 return match_ipv4_prefix (input_token
);
680 return match_ipv6 (input_token
);
681 case IPV6_PREFIX_TKN
:
682 return match_ipv6_prefix (input_token
);
684 return match_range (token
, input_token
);
686 return match_variable (token
, input_token
);
693 #define IPV4_ADDR_STR "0123456789."
694 #define IPV4_PREFIX_STR "0123456789./"
696 static enum match_type
697 match_ipv4 (const char *str
)
700 int dots
= 0, nums
= 0;
705 memset (buf
, 0, sizeof (buf
));
714 if (*(str
+ 1) == '.')
717 if (*(str
+ 1) == '\0')
723 if (!isdigit ((int) *str
))
732 strncpy (buf
, sp
, str
- sp
);
733 if (atoi (buf
) > 255)
750 static enum match_type
751 match_ipv4_prefix (const char *str
)
759 memset (buf
, 0, sizeof (buf
));
761 while (*str
!= '\0' && *str
!= '/')
768 if (*(str
+ 1) == '.' || *(str
+ 1) == '/')
771 if (*(str
+ 1) == '\0')
778 if (!isdigit ((int) *str
))
787 strncpy (buf
, sp
, str
- sp
);
788 if (atoi (buf
) > 255)
795 if (*(str
+ 1) == '\0')
801 else if (*str
== '\0')
814 if (!isdigit ((int) *str
))
827 #define IPV6_ADDR_STR "0123456789abcdefABCDEF:."
828 #define IPV6_PREFIX_STR "0123456789abcdefABCDEF:./"
829 #define STATE_START 1
830 #define STATE_COLON 2
831 #define STATE_DOUBLE 3
834 #define STATE_SLASH 6
837 static enum match_type
838 match_ipv6 (const char *str
)
840 struct sockaddr_in6 sin6_dummy
;
843 if (strspn (str
, IPV6_ADDR_STR
) != strlen (str
))
846 ret
= inet_pton(AF_INET6
, str
, &sin6_dummy
.sin6_addr
);
854 static enum match_type
855 match_ipv6_prefix (const char *str
)
857 int state
= STATE_START
;
858 int colons
= 0, nums
= 0, double_colon
= 0;
860 const char *sp
= NULL
;
866 if (strspn (str
, IPV6_PREFIX_STR
) != strlen (str
))
869 while (*str
!= '\0' && state
!= STATE_MASK
)
876 if (*(str
+ 1) != ':' && *(str
+ 1) != '\0')
890 if (*(str
+ 1) == '/')
892 else if (*(str
+ 1) == ':')
893 state
= STATE_DOUBLE
;
904 if (*(str
+ 1) == ':')
908 if (*(str
+ 1) != '\0' && *(str
+ 1) != '/')
912 if (*(str
+ 1) == '/')
922 if (*(str
+ 1) == ':' || *(str
+ 1) == '.'
923 || *(str
+ 1) == '\0' || *(str
+ 1) == '/')
928 for (; sp
<= str
; sp
++)
934 if (*(str
+ 1) == ':')
936 else if (*(str
+ 1) == '.')
938 if (colons
|| double_colon
)
943 else if (*(str
+ 1) == '/')
951 if (*(str
+ 1) == '\0')
969 if (state
< STATE_MASK
)
972 mask
= strtol (str
, &endptr
, 10);
976 if (mask
< 0 || mask
> 128)
982 static enum match_type
983 match_range (struct cmd_token
*token
, const char *str
)
985 assert (token
->type
== RANGE_TKN
);
990 val
= strtoll (str
, &endptr
, 10);
994 if (val
< token
->min
|| val
> token
->max
)
1000 static enum match_type
1001 match_word (struct cmd_token
*token
, const char *word
)
1003 assert (token
->type
== WORD_TKN
);
1005 // if the passed token is 0 length, partly match
1007 return partly_match
;
1009 // if the passed token is strictly a prefix of the full word, partly match
1010 if (strlen (word
) < strlen (token
->text
))
1011 return !strncmp (token
->text
, word
, strlen (word
)) ?
1015 // if they are the same length and exactly equal, exact match
1016 else if (strlen (word
) == strlen (token
->text
))
1017 return !strncmp (token
->text
, word
, strlen (word
)) ? exact_match
: no_match
;
1022 static enum match_type
1023 match_variable (struct cmd_token
*token
, const char *word
)
1025 assert (token
->type
== VARIABLE_TKN
);