]>
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(...) \
40 do { if (TM) fprintf (stderr, __VA_ARGS__); } while (0);
42 /* matcher helper prototypes */
44 add_nexthops (struct list
*, struct graph_node
*,
45 struct graph_node
**, size_t);
48 command_match_r (struct graph_node
*, vector
, unsigned int,
49 struct graph_node
**);
52 score_precedence (enum cmd_token_type
);
54 static enum match_type
55 min_match_level (enum cmd_token_type
);
58 del_arglist (struct list
*);
60 static struct cmd_token
*
61 disambiguate_tokens (struct cmd_token
*, struct cmd_token
*, char *);
64 disambiguate (struct list
*, struct list
*, vector
, unsigned int);
67 compare_completions (const void *, const void *);
69 /* token matcher prototypes */
70 static enum match_type
71 match_token (struct cmd_token
*, char *);
73 static enum match_type
74 match_ipv4 (const char *);
76 static enum match_type
77 match_ipv4_prefix (const char *);
79 static enum match_type
80 match_ipv6_prefix (const char *, bool);
82 static enum match_type
83 match_range (struct cmd_token
*, const char *);
85 static enum match_type
86 match_word (struct cmd_token
*, const char *);
88 static enum match_type
89 match_variable (struct cmd_token
*, const char *);
91 /* matching functions */
92 static enum matcher_rv matcher_rv
;
95 command_match (struct graph
*cmdgraph
,
98 const struct cmd_element
**el
)
100 struct graph_node
*stack
[MAXDEPTH
];
101 matcher_rv
= MATCHER_NO_MATCH
;
103 // prepend a dummy token to match that pesky start node
104 vector vvline
= vector_init (vline
->alloced
+ 1);
105 vector_set_index (vvline
, 0, (void *) XSTRDUP (MTYPE_TMP
, "dummy"));
106 memcpy (vvline
->index
+ 1, vline
->index
, sizeof (void *) * vline
->alloced
);
107 vvline
->active
= vline
->active
+ 1;
109 struct graph_node
*start
= vector_slot (cmdgraph
->nodes
, 0);
110 if ((*argv
= command_match_r (start
, vvline
, 0, stack
))) // successful match
112 struct listnode
*head
= listhead (*argv
);
113 struct listnode
*tail
= listtail (*argv
);
115 // delete dummy start node
116 cmd_token_del ((struct cmd_token
*) head
->data
);
117 list_delete_node (*argv
, head
);
119 // get cmd_element out of list tail
120 *el
= listgetdata (tail
);
121 list_delete_node (*argv
, tail
);
123 // now argv is an ordered list of cmd_token matching the user
124 // input, with each cmd_token->arg holding the corresponding input
129 trace_matcher ("No match\n");
132 trace_matcher ("Matched command\n->string %s\n->desc %s\n", (*el
)->string
, (*el
)->doc
);
135 // free the leader token we alloc'd
136 XFREE (MTYPE_TMP
, vector_slot (vvline
, 0));
138 vector_free (vvline
);
144 * Builds an argument list given a DFA and a matching input line.
146 * First the function determines if the node it is passed matches the first
147 * token of input. If it does not, it returns NULL (MATCHER_NO_MATCH). If it
148 * does match, then it saves the input token as the head of an argument list.
150 * The next step is to see if there is further input in the input line. If
151 * there is not, the current node's children are searched to see if any of them
152 * are leaves (type END_TKN). If this is the case, then the bottom of the
153 * recursion stack has been reached, the leaf is pushed onto the argument list,
154 * the current node is pushed, and the resulting argument list is
155 * returned (MATCHER_OK). If it is not the case, NULL is returned, indicating
156 * that there is no match for the input along this path (MATCHER_INCOMPLETE).
158 * If there is further input, then the function recurses on each of the current
159 * node's children, passing them the input line minus the token that was just
160 * matched. For each child, the return value of the recursive call is
161 * inspected. If it is null, then there is no match for the input along the
162 * subgraph headed by that child. If it is not null, then there is at least one
163 * input match in that subgraph (more on this in a moment).
165 * If a recursive call on a child returns a non-null value, then it has matched
166 * the input given it on the subgraph that starts with that child. However, due
167 * to the flexibility of the grammar, it is sometimes the case that two or more
168 * child graphs match the same input (two or more of the recursive calls have
169 * non-NULL return values). This is not a valid state, since only one true
170 * match is possible. In order to resolve this conflict, the function keeps a
171 * reference to the child node that most specifically matches the input. This
172 * is done by assigning each node type a precedence. If a child is found to
173 * match the remaining input, then the precedence values of the current
174 * best-matching child and this new match are compared. The node with higher
175 * precedence is kept, and the other match is discarded. Due to the recursive
176 * nature of this function, it is only necessary to compare the precedence of
177 * immediate children, since all subsequent children will already have been
178 * disambiguated in this way.
180 * In the event that two children are found to match with the same precedence,
181 * then the input is ambiguous for the passed cmd_element and NULL is returned.
183 * @param[in] start the start node.
184 * @param[in] vline the vectorized input line.
185 * @param[in] n the index of the first input token.
186 * @return A linked list of n elements. The first n-1 elements are pointers to
187 * struct cmd_token and represent the sequence of tokens matched by the input.
188 * The ->arg field of each token points to a copy of the input matched on it.
189 * The final nth element is a pointer to struct cmd_element, which is the
190 * command that was matched.
192 * If no match was found, the return value is NULL.
195 command_match_r (struct graph_node
*start
, vector vline
, unsigned int n
,
196 struct graph_node
**stack
)
198 assert (n
< vector_active (vline
));
200 // get the minimum match level that can count as a full match
201 struct cmd_token
*token
= start
->data
;
202 enum match_type minmatch
= min_match_level (token
->type
);
204 /* check history/stack of tokens
205 * this disallows matching the same one more than once if there is a
206 * circle in the graph (used for keyword arguments) */
209 if (!token
->allowrepeat
)
210 for (size_t s
= 0; s
< n
; s
++)
211 if (stack
[s
] == start
)
214 // get the current operating input token
215 char *input_token
= vector_slot (vline
, n
);
218 fprintf (stdout
, "\"%-20s\" matches \"%-30s\" ? ", input_token
, token
->text
);
219 enum match_type mt
= match_token (token
, input_token
);
220 fprintf (stdout
, "min: %d - ", minmatch
);
224 fprintf (stdout
, "trivial_match ");
227 fprintf (stdout
, "no_match ");
230 fprintf (stdout
, "partly_match ");
233 fprintf (stdout
, "exact_match ");
236 if (mt
>= minmatch
) fprintf (stdout
, " MATCH");
237 fprintf (stdout
, "\n");
240 // if we don't match this node, die
241 if (match_token (token
, input_token
) < minmatch
)
246 // pointers for iterating linklist
248 struct graph_node
*gn
;
250 // get all possible nexthops
251 struct list
*next
= list_new();
252 add_nexthops (next
, start
, NULL
, 0);
254 // determine the best match
256 struct list
*currbest
= NULL
;
257 for (ALL_LIST_ELEMENTS_RO (next
,ln
,gn
))
259 // if we've matched all input we're looking for END_TKN
260 if (n
+1 == vector_active (vline
))
262 struct cmd_token
*tok
= gn
->data
;
263 if (tok
->type
== END_TKN
)
265 if (currbest
) // there is more than one END_TKN in the follow set
270 currbest
= list_new();
271 // node should have one child node with the element
272 struct graph_node
*leaf
= vector_slot (gn
->to
, 0);
273 // last node in the list will hold the cmd_element;
274 // this is important because list_delete() expects
275 // that all nodes have the same data type, so when
276 // deleting this list the last node must be
278 struct cmd_element
*el
= leaf
->data
;
279 listnode_add (currbest
, el
);
280 currbest
->del
= (void (*)(void *)) &cmd_token_del
;
281 // do not break immediately; continue walking through the follow set
282 // to ensure that there is exactly one END_TKN
287 // else recurse on candidate child node
288 struct list
*result
= command_match_r (gn
, vline
, n
+1, stack
);
290 // save the best match
291 if (result
&& currbest
)
293 // pick the best of two matches
294 struct list
*newbest
= disambiguate (currbest
, result
, vline
, n
+1);
295 // set ambiguity flag
296 ambiguous
= !newbest
|| (ambiguous
&& newbest
== currbest
);
297 // delete the unnecessary result
298 struct list
*todelete
= ((newbest
&& newbest
== result
) ? currbest
: result
);
299 del_arglist (todelete
);
301 currbest
= newbest
? newbest
: currbest
;
311 del_arglist (currbest
);
313 matcher_rv
= MATCHER_AMBIGUOUS
;
317 // copy token, set arg and prepend to currbest
318 struct cmd_token
*token
= start
->data
;
319 struct cmd_token
*copy
= cmd_token_dup (token
);
320 copy
->arg
= XSTRDUP (MTYPE_CMD_ARG
, input_token
);
321 listnode_add_before (currbest
, currbest
->head
, copy
);
322 matcher_rv
= MATCHER_OK
;
325 else if (n
+1 == vector_active (vline
) && matcher_rv
== MATCHER_NO_MATCH
)
326 matcher_rv
= MATCHER_INCOMPLETE
;
335 stack_del (void *val
)
337 XFREE (MTYPE_CMD_MATCHSTACK
, val
);
341 command_complete (struct graph
*graph
,
343 struct list
**completions
)
345 // pointer to next input token to match
348 struct list
*current
= list_new(), // current nodes to match input token against
349 *next
= list_new(); // possible next hops after current input token
350 current
->del
= next
->del
= stack_del
;
352 // pointers used for iterating lists
353 struct graph_node
**gstack
, **newstack
;
354 struct listnode
*node
;
356 // add all children of start node to list
357 struct graph_node
*start
= vector_slot (graph
->nodes
, 0);
358 add_nexthops (next
, start
, &start
, 0);
361 for (idx
= 0; idx
< vector_active (vline
) && next
->count
> 0; idx
++)
363 list_delete (current
);
366 next
->del
= stack_del
;
368 input_token
= vector_slot (vline
, idx
);
370 int exact_match_exists
= 0;
371 for (ALL_LIST_ELEMENTS_RO (current
,node
,gstack
))
372 if (!exact_match_exists
)
373 exact_match_exists
= (match_token (gstack
[0]->data
, input_token
) == exact_match
);
377 for (ALL_LIST_ELEMENTS_RO (current
,node
,gstack
))
379 struct cmd_token
*token
= gstack
[0]->data
;
381 if (token
->attr
== CMD_ATTR_HIDDEN
|| token
->attr
== CMD_ATTR_DEPRECATED
)
384 enum match_type minmatch
= min_match_level (token
->type
);
385 trace_matcher ("\"%s\" matches \"%s\" (%d) ? ",
386 input_token
, token
->text
, token
->type
);
388 unsigned int last_token
= (vector_active (vline
) - 1 == idx
);
389 enum match_type matchtype
= match_token (token
, input_token
);
392 // occurs when last token is whitespace
394 trace_matcher ("trivial_match\n");
396 newstack
= XMALLOC (MTYPE_CMD_MATCHSTACK
,
397 sizeof(struct graph_node
*));
398 /* we're not recursing here, just the first element is OK */
399 newstack
[0] = gstack
[0];
400 listnode_add (next
, newstack
);
403 trace_matcher ("trivial_match\n");
404 if (exact_match_exists
&& !last_token
)
407 trace_matcher ("exact_match\n");
410 newstack
= XMALLOC (MTYPE_CMD_MATCHSTACK
,
411 sizeof(struct graph_node
*));
412 /* same as above, not recursing on this */
413 newstack
[0] = gstack
[0];
414 listnode_add (next
, newstack
);
416 else if (matchtype
>= minmatch
)
417 add_nexthops (next
, gstack
[0], gstack
, idx
+ 1);
420 trace_matcher ("no_match\n");
427 * -----------------------------------------------------------------
428 * token = last input token processed
429 * idx = index in `command` of last token processed
430 * current = set of all transitions from the previous input token
431 * next = set of all nodes reachable from all nodes in `matched`
435 idx
== vector_active(vline
) && next
->count
?
440 if (!MATCHER_ERROR(matcher_rv
))
442 // extract cmd_token into list
443 *completions
= list_new ();
444 for (ALL_LIST_ELEMENTS_RO (next
,node
,gstack
)) {
445 listnode_add (*completions
, gstack
[0]->data
);
449 list_delete (current
);
456 * Adds all children that are reachable by one parser hop to the given list.
457 * special tokens except END_TKN are treated as transparent.
459 * @param[in] list to add the nexthops to
460 * @param[in] node to start calculating nexthops from
461 * @param[in] stack listing previously visited nodes, if non-NULL.
462 * @param[in] stackpos how many valid entries are in stack
463 * @return the number of children added to the list
465 * NB: non-null "stack" means that new stacks will be added to "list" as
466 * output, instead of direct node pointers!
469 add_nexthops (struct list
*list
, struct graph_node
*node
,
470 struct graph_node
**stack
, size_t stackpos
)
473 struct graph_node
*child
;
474 struct graph_node
**nextstack
;
475 for (unsigned int i
= 0; i
< vector_active (node
->to
); i
++)
477 child
= vector_slot (node
->to
, i
);
479 struct cmd_token
*token
= child
->data
;
480 if (!token
->allowrepeat
&& stack
)
482 for (j
= 0; j
< stackpos
; j
++)
483 if (child
== stack
[j
])
488 if (token
->type
>= SPECIAL_TKN
&& token
->type
!= END_TKN
)
490 added
+= add_nexthops (list
, child
, stack
, stackpos
);
496 nextstack
= XMALLOC (MTYPE_CMD_MATCHSTACK
,
497 (stackpos
+ 1) * sizeof(struct graph_node
*));
498 nextstack
[0] = child
;
499 memcpy(nextstack
+ 1, stack
, stackpos
* sizeof(struct graph_node
*));
501 listnode_add (list
, nextstack
);
504 listnode_add (list
, child
);
513 * Determines the node types for which a partial match may count as a full
514 * match. Enables command abbrevations.
516 * @param[in] type node type
517 * @return minimum match level needed to for a token to fully match
519 static enum match_type
520 min_match_level (enum cmd_token_type type
)
524 // anything matches a start node, for the sake of recursion
527 // allowing words to partly match enables command abbreviation
536 * Assigns precedence scores to node types.
538 * @param[in] type node type to score
539 * @return precedence score
542 score_precedence (enum cmd_token_type type
)
546 // some of these are mutually exclusive, so they share
547 // the same precedence value
549 case IPV4_PREFIX_TKN
:
551 case IPV6_PREFIX_TKN
:
564 * Picks the better of two possible matches for a token.
566 * @param[in] first candidate node matching token
567 * @param[in] second candidate node matching token
568 * @param[in] token the token being matched
569 * @return the best-matching node, or NULL if the two are entirely ambiguous
571 static struct cmd_token
*
572 disambiguate_tokens (struct cmd_token
*first
,
573 struct cmd_token
*second
,
576 // if the types are different, simply go off of type precedence
577 if (first
->type
!= second
->type
)
579 int firstprec
= score_precedence (first
->type
);
580 int secndprec
= score_precedence (second
->type
);
581 if (firstprec
!= secndprec
)
582 return firstprec
< secndprec
? first
: second
;
587 // if they're the same, return the more exact match
588 enum match_type fmtype
= match_token (first
, input_token
);
589 enum match_type smtype
= match_token (second
, input_token
);
590 if (fmtype
!= smtype
)
591 return fmtype
> smtype
? first
: second
;
597 * Picks the better of two possible matches for an input line.
599 * @param[in] first candidate list of cmd_token matching vline
600 * @param[in] second candidate list of cmd_token matching vline
601 * @param[in] vline the input line being matched
602 * @param[in] n index into vline to start comparing at
603 * @return the best-matching list, or NULL if the two are entirely ambiguous
606 disambiguate (struct list
*first
,
611 // doesn't make sense for these to be inequal length
612 assert (first
->count
== second
->count
);
613 assert (first
->count
== vector_active (vline
) - n
+1);
615 struct listnode
*fnode
= listhead (first
),
616 *snode
= listhead (second
);
617 struct cmd_token
*ftok
= listgetdata (fnode
),
618 *stok
= listgetdata (snode
),
621 // compare each token, if one matches better use that one
622 for (unsigned int i
= n
; i
< vector_active (vline
); i
++)
624 char *token
= vector_slot(vline
, i
);
625 if ((best
= disambiguate_tokens (ftok
, stok
, token
)))
626 return best
== ftok
? first
: second
;
627 fnode
= listnextnode (fnode
);
628 snode
= listnextnode (snode
);
629 ftok
= listgetdata (fnode
);
630 stok
= listgetdata (snode
);
637 * Deletion function for arglist.
639 * Since list->del for arglists expects all listnode->data to hold cmd_token,
640 * but arglists have cmd_element as the data for the tail, this function
641 * manually deletes the tail before deleting the rest of the list as usual.
643 * The cmd_element at the end is *not* a copy. It is the one and only.
645 * @param list the arglist to delete
648 del_arglist (struct list
*list
)
650 // manually delete last node
651 struct listnode
*tail
= listtail (list
);
653 list_delete_node (list
, tail
);
655 // delete the rest of the list as usual
659 /*---------- token level matching functions ----------*/
661 static enum match_type
662 match_token (struct cmd_token
*token
, char *input_token
)
664 // nothing trivially matches everything
666 return trivial_match
;
668 switch (token
->type
) {
670 return match_word (token
, input_token
);
672 return match_ipv4 (input_token
);
673 case IPV4_PREFIX_TKN
:
674 return match_ipv4_prefix (input_token
);
676 return match_ipv6_prefix (input_token
, false);
677 case IPV6_PREFIX_TKN
:
678 return match_ipv6_prefix (input_token
, true);
680 return match_range (token
, input_token
);
682 return match_variable (token
, input_token
);
689 #define IPV4_ADDR_STR "0123456789."
690 #define IPV4_PREFIX_STR "0123456789./"
692 static enum match_type
693 match_ipv4 (const char *str
)
696 int dots
= 0, nums
= 0;
701 memset (buf
, 0, sizeof (buf
));
710 if (*(str
+ 1) == '.')
713 if (*(str
+ 1) == '\0')
719 if (!isdigit ((int) *str
))
728 strncpy (buf
, sp
, str
- sp
);
729 if (atoi (buf
) > 255)
746 static enum match_type
747 match_ipv4_prefix (const char *str
)
755 memset (buf
, 0, sizeof (buf
));
757 while (*str
!= '\0' && *str
!= '/')
764 if (*(str
+ 1) == '.' || *(str
+ 1) == '/')
767 if (*(str
+ 1) == '\0')
774 if (!isdigit ((int) *str
))
783 strncpy (buf
, sp
, str
- sp
);
784 if (atoi (buf
) > 255)
791 if (*(str
+ 1) == '\0')
797 else if (*str
== '\0')
810 if (!isdigit ((int) *str
))
823 #define IPV6_ADDR_STR "0123456789abcdefABCDEF:."
824 #define IPV6_PREFIX_STR "0123456789abcdefABCDEF:./"
825 #define STATE_START 1
826 #define STATE_COLON 2
827 #define STATE_DOUBLE 3
830 #define STATE_SLASH 6
833 static enum match_type
834 match_ipv6_prefix (const char *str
, bool prefix
)
836 int state
= STATE_START
;
837 int colons
= 0, nums
= 0, double_colon
= 0;
839 const char *sp
= NULL
, *start
= str
;
845 if (strspn (str
, prefix
? IPV6_PREFIX_STR
: IPV6_ADDR_STR
) != strlen (str
))
848 while (*str
!= '\0' && state
!= STATE_MASK
)
855 if (*(str
+ 1) != ':' && *(str
+ 1) != '\0')
869 if (*(str
+ 1) == '/')
871 else if (*(str
+ 1) == ':')
872 state
= STATE_DOUBLE
;
883 if (*(str
+ 1) == ':')
887 if (*(str
+ 1) != '\0' && *(str
+ 1) != '/')
891 if (*(str
+ 1) == '/')
901 if (*(str
+ 1) == ':' || *(str
+ 1) == '.'
902 || *(str
+ 1) == '\0' || *(str
+ 1) == '/')
907 for (; sp
<= str
; sp
++)
913 if (*(str
+ 1) == ':')
915 else if (*(str
+ 1) == '.')
917 if (colons
|| double_colon
)
922 else if (*(str
+ 1) == '/')
930 if (*(str
+ 1) == '\0')
950 struct sockaddr_in6 sin6_dummy
;
951 int ret
= inet_pton(AF_INET6
, start
, &sin6_dummy
.sin6_addr
);
952 return ret
== 1 ? exact_match
: partly_match
;
955 if (state
< STATE_MASK
)
958 mask
= strtol (str
, &endptr
, 10);
962 if (mask
< 0 || mask
> 128)
968 static enum match_type
969 match_range (struct cmd_token
*token
, const char *str
)
971 assert (token
->type
== RANGE_TKN
);
976 val
= strtoll (str
, &endptr
, 10);
980 if (val
< token
->min
|| val
> token
->max
)
986 static enum match_type
987 match_word (struct cmd_token
*token
, const char *word
)
989 assert (token
->type
== WORD_TKN
);
991 // if the passed token is 0 length, partly match
995 // if the passed token is strictly a prefix of the full word, partly match
996 if (strlen (word
) < strlen (token
->text
))
997 return !strncmp (token
->text
, word
, strlen (word
)) ?
1001 // if they are the same length and exactly equal, exact match
1002 else if (strlen (word
) == strlen (token
->text
))
1003 return !strncmp (token
->text
, word
, strlen (word
)) ? exact_match
: no_match
;
1008 static enum match_type
1009 match_variable (struct cmd_token
*token
, const char *word
)
1011 assert (token
->type
== VARIABLE_TKN
);