]> git.proxmox.com Git - mirror_frr.git/blob - lib/command_match.c
Merge pull request #2053 from LabNConsulting/working/master/bvl-bug-degenerate-no...
[mirror_frr.git] / lib / command_match.c
1 /*
2 * Input matching routines for CLI backend.
3 *
4 * --
5 * Copyright (C) 2016 Cumulus Networks, Inc.
6 *
7 * This file is part of GNU Zebra.
8 *
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
12 * later version.
13 *
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.
18 *
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
22 */
23
24 #include <zebra.h>
25
26 #include "command_match.h"
27 #include "memory.h"
28
29 DEFINE_MTYPE_STATIC(LIB, CMD_MATCHSTACK, "Command Match Stack")
30
31 #ifdef TRACE_MATCHER
32 #define TM 1
33 #else
34 #define TM 0
35 #endif
36
37 #define trace_matcher(...) \
38 do { \
39 if (TM) \
40 fprintf(stderr, __VA_ARGS__); \
41 } while (0);
42
43 /* matcher helper prototypes */
44 static int add_nexthops(struct list *, struct graph_node *,
45 struct graph_node **, size_t);
46
47 static enum matcher_rv command_match_r(struct graph_node *, vector,
48 unsigned int, struct graph_node **,
49 struct list **);
50
51 static int score_precedence(enum cmd_token_type);
52
53 static enum match_type min_match_level(enum cmd_token_type);
54
55 static void del_arglist(struct list *);
56
57 static struct cmd_token *disambiguate_tokens(struct cmd_token *,
58 struct cmd_token *, char *);
59
60 static struct list *disambiguate(struct list *, struct list *, vector,
61 unsigned int);
62
63 int compare_completions(const void *, const void *);
64
65 /* token matcher prototypes */
66 static enum match_type match_token(struct cmd_token *, char *);
67
68 static enum match_type match_ipv4(const char *);
69
70 static enum match_type match_ipv4_prefix(const char *);
71
72 static enum match_type match_ipv6_prefix(const char *, bool);
73
74 static enum match_type match_range(struct cmd_token *, const char *);
75
76 static enum match_type match_word(struct cmd_token *, const char *);
77
78 static enum match_type match_variable(struct cmd_token *, const char *);
79
80 static enum match_type match_mac(const char *, bool);
81
82 enum matcher_rv command_match(struct graph *cmdgraph, vector vline,
83 struct list **argv, const struct cmd_element **el)
84 {
85 struct graph_node *stack[CMD_ARGC_MAX];
86 enum matcher_rv status;
87 *argv = NULL;
88
89 // prepend a dummy token to match that pesky start node
90 vector vvline = vector_init(vline->alloced + 1);
91 vector_set_index(vvline, 0, (void *)XSTRDUP(MTYPE_TMP, "dummy"));
92 memcpy(vvline->index + 1, vline->index,
93 sizeof(void *) * vline->alloced);
94 vvline->active = vline->active + 1;
95
96 struct graph_node *start = vector_slot(cmdgraph->nodes, 0);
97 status = command_match_r(start, vvline, 0, stack, argv);
98 if (status == MATCHER_OK) { // successful match
99 struct listnode *head = listhead(*argv);
100 struct listnode *tail = listtail(*argv);
101
102 assert(head);
103 assert(tail);
104
105 // delete dummy start node
106 cmd_token_del((struct cmd_token *)head->data);
107 list_delete_node(*argv, head);
108
109 // get cmd_element out of list tail
110 *el = listgetdata(tail);
111 list_delete_node(*argv, tail);
112
113 // now argv is an ordered list of cmd_token matching the user
114 // input, with each cmd_token->arg holding the corresponding
115 // input
116 assert(*el);
117 } else if (*argv) {
118 del_arglist(*argv);
119 *argv = NULL;
120 }
121
122 if (!*el) {
123 trace_matcher("No match\n");
124 } else {
125 trace_matcher("Matched command\n->string %s\n->desc %s\n",
126 (*el)->string, (*el)->doc);
127 }
128
129 // free the leader token we alloc'd
130 XFREE(MTYPE_TMP, vector_slot(vvline, 0));
131 // free vector
132 vector_free(vvline);
133
134 return status;
135 }
136
137 /**
138 * Builds an argument list given a DFA and a matching input line.
139 *
140 * First the function determines if the node it is passed matches the first
141 * token of input. If it does not, it returns NULL (MATCHER_NO_MATCH). If it
142 * does match, then it saves the input token as the head of an argument list.
143 *
144 * The next step is to see if there is further input in the input line. If
145 * there is not, the current node's children are searched to see if any of them
146 * are leaves (type END_TKN). If this is the case, then the bottom of the
147 * recursion stack has been reached, the leaf is pushed onto the argument list,
148 * the current node is pushed, and the resulting argument list is
149 * returned (MATCHER_OK). If it is not the case, NULL is returned, indicating
150 * that there is no match for the input along this path (MATCHER_INCOMPLETE).
151 *
152 * If there is further input, then the function recurses on each of the current
153 * node's children, passing them the input line minus the token that was just
154 * matched. For each child, the return value of the recursive call is
155 * inspected. If it is null, then there is no match for the input along the
156 * subgraph headed by that child. If it is not null, then there is at least one
157 * input match in that subgraph (more on this in a moment).
158 *
159 * If a recursive call on a child returns a non-null value, then it has matched
160 * the input given it on the subgraph that starts with that child. However, due
161 * to the flexibility of the grammar, it is sometimes the case that two or more
162 * child graphs match the same input (two or more of the recursive calls have
163 * non-NULL return values). This is not a valid state, since only one true
164 * match is possible. In order to resolve this conflict, the function keeps a
165 * reference to the child node that most specifically matches the input. This
166 * is done by assigning each node type a precedence. If a child is found to
167 * match the remaining input, then the precedence values of the current
168 * best-matching child and this new match are compared. The node with higher
169 * precedence is kept, and the other match is discarded. Due to the recursive
170 * nature of this function, it is only necessary to compare the precedence of
171 * immediate children, since all subsequent children will already have been
172 * disambiguated in this way.
173 *
174 * In the event that two children are found to match with the same precedence,
175 * then the input is ambiguous for the passed cmd_element and NULL is returned.
176 *
177 * @param[in] start the start node.
178 * @param[in] vline the vectorized input line.
179 * @param[in] n the index of the first input token.
180 * @return A linked list of n elements. The first n-1 elements are pointers to
181 * struct cmd_token and represent the sequence of tokens matched by the input.
182 * The ->arg field of each token points to a copy of the input matched on it.
183 * The final nth element is a pointer to struct cmd_element, which is the
184 * command that was matched.
185 *
186 * If no match was found, the return value is NULL.
187 */
188 static enum matcher_rv command_match_r(struct graph_node *start, vector vline,
189 unsigned int n,
190 struct graph_node **stack,
191 struct list **currbest)
192 {
193 assert(n < vector_active(vline));
194
195 enum matcher_rv status = MATCHER_NO_MATCH;
196
197 // get the minimum match level that can count as a full match
198 struct cmd_token *token = start->data;
199 enum match_type minmatch = min_match_level(token->type);
200
201 /* check history/stack of tokens
202 * this disallows matching the same one more than once if there is a
203 * circle in the graph (used for keyword arguments) */
204 if (n == CMD_ARGC_MAX)
205 return MATCHER_NO_MATCH;
206 if (!token->allowrepeat)
207 for (size_t s = 0; s < n; s++)
208 if (stack[s] == start)
209 return MATCHER_NO_MATCH;
210
211 // get the current operating input token
212 char *input_token = vector_slot(vline, n);
213
214 #ifdef TRACE_MATCHER
215 fprintf(stdout, "\"%-20s\" matches \"%-30s\" ? ", input_token,
216 token->text);
217 enum match_type mt = match_token(token, input_token);
218 fprintf(stdout, "type: %d ", token->type);
219 fprintf(stdout, "min: %d - ", minmatch);
220 switch (mt) {
221 case trivial_match:
222 fprintf(stdout, "trivial_match ");
223 break;
224 case no_match:
225 fprintf(stdout, "no_match ");
226 break;
227 case partly_match:
228 fprintf(stdout, "partly_match ");
229 break;
230 case exact_match:
231 fprintf(stdout, "exact_match ");
232 break;
233 }
234 if (mt >= minmatch)
235 fprintf(stdout, " MATCH");
236 fprintf(stdout, "\n");
237 #endif
238
239 // if we don't match this node, die
240 if (match_token(token, input_token) < minmatch)
241 return MATCHER_NO_MATCH;
242
243 stack[n] = start;
244
245 // pointers for iterating linklist
246 struct listnode *ln;
247 struct graph_node *gn;
248
249 // get all possible nexthops
250 struct list *next = list_new();
251 add_nexthops(next, start, NULL, 0);
252
253 // determine the best match
254 for (ALL_LIST_ELEMENTS_RO(next, ln, gn)) {
255 // if we've matched all input we're looking for END_TKN
256 if (n + 1 == vector_active(vline)) {
257 struct cmd_token *tok = gn->data;
258 if (tok->type == END_TKN) {
259 // if more than one END_TKN in the follow set
260 if (*currbest) {
261 status = MATCHER_AMBIGUOUS;
262 break;
263 } else {
264 status = MATCHER_OK;
265 }
266 *currbest = list_new();
267 // node should have one child node with the
268 // element
269 struct graph_node *leaf =
270 vector_slot(gn->to, 0);
271 // last node in the list will hold the
272 // cmd_element; this is important because
273 // list_delete() expects that all nodes have
274 // the same data type, so when deleting this
275 // list the last node must be manually deleted
276 struct cmd_element *el = leaf->data;
277 listnode_add(*currbest, el);
278 (*currbest)->del =
279 (void (*)(void *)) & cmd_token_del;
280 // do not break immediately; continue walking
281 // through the follow set to ensure that there
282 // is exactly one END_TKN
283 }
284 continue;
285 }
286
287 // else recurse on candidate child node
288 struct list *result = NULL;
289 enum matcher_rv rstat =
290 command_match_r(gn, vline, n + 1, stack, &result);
291
292 // save the best match
293 if (result && *currbest) {
294 // pick the best of two matches
295 struct list *newbest =
296 disambiguate(*currbest, result, vline, n + 1);
297
298 // current best and result are ambiguous
299 if (!newbest)
300 status = MATCHER_AMBIGUOUS;
301 // current best is still the best, but ambiguous
302 else if (newbest == *currbest
303 && status == MATCHER_AMBIGUOUS)
304 status = MATCHER_AMBIGUOUS;
305 // result is better, but also ambiguous
306 else if (newbest == result
307 && rstat == MATCHER_AMBIGUOUS)
308 status = MATCHER_AMBIGUOUS;
309 // one or the other is superior and not ambiguous
310 else
311 status = MATCHER_OK;
312
313 // delete the unnecessary result
314 struct list *todelete =
315 ((newbest && newbest == result) ? *currbest
316 : result);
317 del_arglist(todelete);
318
319 *currbest = newbest ? newbest : *currbest;
320 } else if (result) {
321 status = rstat;
322 *currbest = result;
323 } else if (!*currbest) {
324 status = MAX(rstat, status);
325 }
326 }
327 if (*currbest) {
328 // copy token, set arg and prepend to currbest
329 struct cmd_token *token = start->data;
330 struct cmd_token *copy = cmd_token_dup(token);
331 copy->arg = XSTRDUP(MTYPE_CMD_ARG, input_token);
332 listnode_add_before(*currbest, (*currbest)->head, copy);
333 } else if (n + 1 == vector_active(vline) && status == MATCHER_NO_MATCH)
334 status = MATCHER_INCOMPLETE;
335
336 // cleanup
337 list_delete_and_null(&next);
338
339 return status;
340 }
341
342 static void stack_del(void *val)
343 {
344 XFREE(MTYPE_CMD_MATCHSTACK, val);
345 }
346
347 enum matcher_rv command_complete(struct graph *graph, vector vline,
348 struct list **completions)
349 {
350 // pointer to next input token to match
351 char *input_token;
352
353 struct list *
354 current =
355 list_new(), // current nodes to match input token against
356 *next = list_new(); // possible next hops after current input
357 // token
358 current->del = next->del = stack_del;
359
360 // pointers used for iterating lists
361 struct graph_node **gstack, **newstack;
362 struct listnode *node;
363
364 // add all children of start node to list
365 struct graph_node *start = vector_slot(graph->nodes, 0);
366 add_nexthops(next, start, &start, 0);
367
368 unsigned int idx;
369 for (idx = 0; idx < vector_active(vline) && next->count > 0; idx++) {
370 list_delete_and_null(&current);
371 current = next;
372 next = list_new();
373 next->del = stack_del;
374
375 input_token = vector_slot(vline, idx);
376
377 int exact_match_exists = 0;
378 for (ALL_LIST_ELEMENTS_RO(current, node, gstack))
379 if (!exact_match_exists)
380 exact_match_exists =
381 (match_token(gstack[0]->data,
382 input_token)
383 == exact_match);
384 else
385 break;
386
387 for (ALL_LIST_ELEMENTS_RO(current, node, gstack)) {
388 struct cmd_token *token = gstack[0]->data;
389
390 if (token->attr == CMD_ATTR_HIDDEN
391 || token->attr == CMD_ATTR_DEPRECATED)
392 continue;
393
394 enum match_type minmatch = min_match_level(token->type);
395 trace_matcher("\"%s\" matches \"%s\" (%d) ? ",
396 input_token, token->text, token->type);
397
398 unsigned int last_token =
399 (vector_active(vline) - 1 == idx);
400 enum match_type matchtype =
401 match_token(token, input_token);
402 switch (matchtype) {
403 // occurs when last token is whitespace
404 case trivial_match:
405 trace_matcher("trivial_match\n");
406 assert(last_token);
407 newstack = XMALLOC(MTYPE_CMD_MATCHSTACK,
408 sizeof(struct graph_node *));
409 /* we're not recursing here, just the first
410 * element is OK */
411 newstack[0] = gstack[0];
412 listnode_add(next, newstack);
413 break;
414 case partly_match:
415 trace_matcher("trivial_match\n");
416 if (exact_match_exists && !last_token)
417 break;
418 /* fallthru */
419 case exact_match:
420 trace_matcher("exact_match\n");
421 if (last_token) {
422 newstack = XMALLOC(
423 MTYPE_CMD_MATCHSTACK,
424 sizeof(struct graph_node *));
425 /* same as above, not recursing on this
426 */
427 newstack[0] = gstack[0];
428 listnode_add(next, newstack);
429 } else if (matchtype >= minmatch)
430 add_nexthops(next, gstack[0], gstack,
431 idx + 1);
432 break;
433 default:
434 trace_matcher("no_match\n");
435 break;
436 }
437 }
438 }
439
440 /* Variable summary
441 * -----------------------------------------------------------------
442 * token = last input token processed
443 * idx = index in `command` of last token processed
444 * current = set of all transitions from the previous input token
445 * next = set of all nodes reachable from all nodes in `matched`
446 */
447
448 enum matcher_rv mrv = idx == vector_active(vline) && next->count
449 ? MATCHER_OK
450 : MATCHER_NO_MATCH;
451
452 *completions = NULL;
453 if (!MATCHER_ERROR(mrv)) {
454 // extract cmd_token into list
455 *completions = list_new();
456 for (ALL_LIST_ELEMENTS_RO(next, node, gstack)) {
457 listnode_add(*completions, gstack[0]->data);
458 }
459 }
460
461 list_delete_and_null(&current);
462 list_delete_and_null(&next);
463
464 return mrv;
465 }
466
467 /**
468 * Adds all children that are reachable by one parser hop to the given list.
469 * special tokens except END_TKN are treated as transparent.
470 *
471 * @param[in] list to add the nexthops to
472 * @param[in] node to start calculating nexthops from
473 * @param[in] stack listing previously visited nodes, if non-NULL.
474 * @param[in] stackpos how many valid entries are in stack
475 * @return the number of children added to the list
476 *
477 * NB: non-null "stack" means that new stacks will be added to "list" as
478 * output, instead of direct node pointers!
479 */
480 static int add_nexthops(struct list *list, struct graph_node *node,
481 struct graph_node **stack, size_t stackpos)
482 {
483 int added = 0;
484 struct graph_node *child;
485 struct graph_node **nextstack;
486 for (unsigned int i = 0; i < vector_active(node->to); i++) {
487 child = vector_slot(node->to, i);
488 size_t j;
489 struct cmd_token *token = child->data;
490 if (!token->allowrepeat && stack) {
491 for (j = 0; j < stackpos; j++)
492 if (child == stack[j])
493 break;
494 if (j != stackpos)
495 continue;
496 }
497 if (token->type >= SPECIAL_TKN && token->type != END_TKN) {
498 added += add_nexthops(list, child, stack, stackpos);
499 } else {
500 if (stack) {
501 nextstack = XMALLOC(
502 MTYPE_CMD_MATCHSTACK,
503 (stackpos + 1)
504 * sizeof(struct graph_node *));
505 nextstack[0] = child;
506 memcpy(nextstack + 1, stack,
507 stackpos * sizeof(struct graph_node *));
508
509 listnode_add(list, nextstack);
510 } else
511 listnode_add(list, child);
512 added++;
513 }
514 }
515
516 return added;
517 }
518
519 /**
520 * Determines the node types for which a partial match may count as a full
521 * match. Enables command abbrevations.
522 *
523 * @param[in] type node type
524 * @return minimum match level needed to for a token to fully match
525 */
526 static enum match_type min_match_level(enum cmd_token_type type)
527 {
528 switch (type) {
529 // anything matches a start node, for the sake of recursion
530 case START_TKN:
531 return no_match;
532 // allowing words to partly match enables command abbreviation
533 case WORD_TKN:
534 return partly_match;
535 default:
536 return exact_match;
537 }
538 }
539
540 /**
541 * Assigns precedence scores to node types.
542 *
543 * @param[in] type node type to score
544 * @return precedence score
545 */
546 static int score_precedence(enum cmd_token_type type)
547 {
548 switch (type) {
549 // some of these are mutually exclusive, so they share
550 // the same precedence value
551 case IPV4_TKN:
552 case IPV4_PREFIX_TKN:
553 case IPV6_TKN:
554 case IPV6_PREFIX_TKN:
555 case MAC_TKN:
556 case MAC_PREFIX_TKN:
557 case RANGE_TKN:
558 return 2;
559 case WORD_TKN:
560 return 3;
561 case VARIABLE_TKN:
562 return 4;
563 default:
564 return 10;
565 }
566 }
567
568 /**
569 * Picks the better of two possible matches for a token.
570 *
571 * @param[in] first candidate node matching token
572 * @param[in] second candidate node matching token
573 * @param[in] token the token being matched
574 * @return the best-matching node, or NULL if the two are entirely ambiguous
575 */
576 static struct cmd_token *disambiguate_tokens(struct cmd_token *first,
577 struct cmd_token *second,
578 char *input_token)
579 {
580 // if the types are different, simply go off of type precedence
581 if (first->type != second->type) {
582 int firstprec = score_precedence(first->type);
583 int secndprec = score_precedence(second->type);
584 if (firstprec != secndprec)
585 return firstprec < secndprec ? first : second;
586 else
587 return NULL;
588 }
589
590 // if they're the same, return the more exact match
591 enum match_type fmtype = match_token(first, input_token);
592 enum match_type smtype = match_token(second, input_token);
593 if (fmtype != smtype)
594 return fmtype > smtype ? first : second;
595
596 return NULL;
597 }
598
599 /**
600 * Picks the better of two possible matches for an input line.
601 *
602 * @param[in] first candidate list of cmd_token matching vline
603 * @param[in] second candidate list of cmd_token matching vline
604 * @param[in] vline the input line being matched
605 * @param[in] n index into vline to start comparing at
606 * @return the best-matching list, or NULL if the two are entirely ambiguous
607 */
608 static struct list *disambiguate(struct list *first, struct list *second,
609 vector vline, unsigned int n)
610 {
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);
614
615 struct listnode *fnode = listhead(first), *snode = listhead(second);
616 struct cmd_token *ftok = listgetdata(fnode), *stok = listgetdata(snode),
617 *best = NULL;
618
619 // compare each token, if one matches better use that one
620 for (unsigned int i = n; i < vector_active(vline); i++) {
621 char *token = vector_slot(vline, i);
622 if ((best = disambiguate_tokens(ftok, stok, token)))
623 return best == ftok ? first : second;
624 fnode = listnextnode(fnode);
625 snode = listnextnode(snode);
626 ftok = listgetdata(fnode);
627 stok = listgetdata(snode);
628 }
629
630 return NULL;
631 }
632
633 /*
634 * Deletion function for arglist.
635 *
636 * Since list->del for arglists expects all listnode->data to hold cmd_token,
637 * but arglists have cmd_element as the data for the tail, this function
638 * manually deletes the tail before deleting the rest of the list as usual.
639 *
640 * The cmd_element at the end is *not* a copy. It is the one and only.
641 *
642 * @param list the arglist to delete
643 */
644 static void del_arglist(struct list *list)
645 {
646 // manually delete last node
647 struct listnode *tail = listtail(list);
648 tail->data = NULL;
649 list_delete_node(list, tail);
650
651 // delete the rest of the list as usual
652 list_delete_and_null(&list);
653 }
654
655 /*---------- token level matching functions ----------*/
656
657 static enum match_type match_token(struct cmd_token *token, char *input_token)
658 {
659 // nothing trivially matches everything
660 if (!input_token)
661 return trivial_match;
662
663 switch (token->type) {
664 case WORD_TKN:
665 return match_word(token, input_token);
666 case IPV4_TKN:
667 return match_ipv4(input_token);
668 case IPV4_PREFIX_TKN:
669 return match_ipv4_prefix(input_token);
670 case IPV6_TKN:
671 return match_ipv6_prefix(input_token, false);
672 case IPV6_PREFIX_TKN:
673 return match_ipv6_prefix(input_token, true);
674 case RANGE_TKN:
675 return match_range(token, input_token);
676 case VARIABLE_TKN:
677 return match_variable(token, input_token);
678 case MAC_TKN:
679 return match_mac(input_token, false);
680 case MAC_PREFIX_TKN:
681 return match_mac(input_token, true);
682 case END_TKN:
683 default:
684 return no_match;
685 }
686 }
687
688 #define IPV4_ADDR_STR "0123456789."
689 #define IPV4_PREFIX_STR "0123456789./"
690
691 static enum match_type match_ipv4(const char *str)
692 {
693 const char *sp;
694 int dots = 0, nums = 0;
695 char buf[4];
696
697 for (;;) {
698 memset(buf, 0, sizeof(buf));
699 sp = str;
700 while (*str != '\0') {
701 if (*str == '.') {
702 if (dots >= 3)
703 return no_match;
704
705 if (*(str + 1) == '.')
706 return no_match;
707
708 if (*(str + 1) == '\0')
709 return partly_match;
710
711 dots++;
712 break;
713 }
714 if (!isdigit((int)*str))
715 return no_match;
716
717 str++;
718 }
719
720 if (str - sp > 3)
721 return no_match;
722
723 strncpy(buf, sp, str - sp);
724 if (atoi(buf) > 255)
725 return no_match;
726
727 nums++;
728
729 if (*str == '\0')
730 break;
731
732 str++;
733 }
734
735 if (nums < 4)
736 return partly_match;
737
738 return exact_match;
739 }
740
741 static enum match_type match_ipv4_prefix(const char *str)
742 {
743 const char *sp;
744 int dots = 0;
745 char buf[4];
746
747 for (;;) {
748 memset(buf, 0, sizeof(buf));
749 sp = str;
750 while (*str != '\0' && *str != '/') {
751 if (*str == '.') {
752 if (dots == 3)
753 return no_match;
754
755 if (*(str + 1) == '.' || *(str + 1) == '/')
756 return no_match;
757
758 if (*(str + 1) == '\0')
759 return partly_match;
760
761 dots++;
762 break;
763 }
764
765 if (!isdigit((int)*str))
766 return no_match;
767
768 str++;
769 }
770
771 if (str - sp > 3)
772 return no_match;
773
774 strncpy(buf, sp, str - sp);
775 if (atoi(buf) > 255)
776 return no_match;
777
778 if (dots == 3) {
779 if (*str == '/') {
780 if (*(str + 1) == '\0')
781 return partly_match;
782
783 str++;
784 break;
785 } else if (*str == '\0')
786 return partly_match;
787 }
788
789 if (*str == '\0')
790 return partly_match;
791
792 str++;
793 }
794
795 sp = str;
796 while (*str != '\0') {
797 if (!isdigit((int)*str))
798 return no_match;
799
800 str++;
801 }
802
803 if (atoi(sp) > 32)
804 return no_match;
805
806 return exact_match;
807 }
808
809
810 #define IPV6_ADDR_STR "0123456789abcdefABCDEF:."
811 #define IPV6_PREFIX_STR "0123456789abcdefABCDEF:./"
812 #define STATE_START 1
813 #define STATE_COLON 2
814 #define STATE_DOUBLE 3
815 #define STATE_ADDR 4
816 #define STATE_DOT 5
817 #define STATE_SLASH 6
818 #define STATE_MASK 7
819
820 static enum match_type match_ipv6_prefix(const char *str, bool prefix)
821 {
822 int state = STATE_START;
823 int colons = 0, nums = 0, double_colon = 0;
824 int mask;
825 const char *sp = NULL, *start = str;
826 char *endptr = NULL;
827
828 if (str == NULL)
829 return partly_match;
830
831 if (strspn(str, prefix ? IPV6_PREFIX_STR : IPV6_ADDR_STR)
832 != strlen(str))
833 return no_match;
834
835 while (*str != '\0' && state != STATE_MASK) {
836 switch (state) {
837 case STATE_START:
838 if (*str == ':') {
839 if (*(str + 1) != ':' && *(str + 1) != '\0')
840 return no_match;
841 colons--;
842 state = STATE_COLON;
843 } else {
844 sp = str;
845 state = STATE_ADDR;
846 }
847
848 continue;
849 case STATE_COLON:
850 colons++;
851 if (*(str + 1) == '/')
852 return no_match;
853 else if (*(str + 1) == ':')
854 state = STATE_DOUBLE;
855 else {
856 sp = str + 1;
857 state = STATE_ADDR;
858 }
859 break;
860 case STATE_DOUBLE:
861 if (double_colon)
862 return no_match;
863
864 if (*(str + 1) == ':')
865 return no_match;
866 else {
867 if (*(str + 1) != '\0' && *(str + 1) != '/')
868 colons++;
869 sp = str + 1;
870
871 if (*(str + 1) == '/')
872 state = STATE_SLASH;
873 else
874 state = STATE_ADDR;
875 }
876
877 double_colon++;
878 nums += 1;
879 break;
880 case STATE_ADDR:
881 if (*(str + 1) == ':' || *(str + 1) == '.'
882 || *(str + 1) == '\0' || *(str + 1) == '/') {
883 if (str - sp > 3)
884 return no_match;
885
886 for (; sp <= str; sp++)
887 if (*sp == '/')
888 return no_match;
889
890 nums++;
891
892 if (*(str + 1) == ':')
893 state = STATE_COLON;
894 else if (*(str + 1) == '.') {
895 if (colons || double_colon)
896 state = STATE_DOT;
897 else
898 return no_match;
899 } else if (*(str + 1) == '/')
900 state = STATE_SLASH;
901 }
902 break;
903 case STATE_DOT:
904 state = STATE_ADDR;
905 break;
906 case STATE_SLASH:
907 if (*(str + 1) == '\0')
908 return partly_match;
909
910 state = STATE_MASK;
911 break;
912 default:
913 break;
914 }
915
916 if (nums > 11)
917 return no_match;
918
919 if (colons > 7)
920 return no_match;
921
922 str++;
923 }
924
925 if (!prefix) {
926 struct sockaddr_in6 sin6_dummy;
927 int ret = inet_pton(AF_INET6, start, &sin6_dummy.sin6_addr);
928 return ret == 1 ? exact_match : partly_match;
929 }
930
931 if (state < STATE_MASK)
932 return partly_match;
933
934 mask = strtol(str, &endptr, 10);
935 if (*endptr != '\0')
936 return no_match;
937
938 if (mask < 0 || mask > 128)
939 return no_match;
940
941 return exact_match;
942 }
943
944 static enum match_type match_range(struct cmd_token *token, const char *str)
945 {
946 assert(token->type == RANGE_TKN);
947
948 char *endptr = NULL;
949 long long val;
950
951 val = strtoll(str, &endptr, 10);
952 if (*endptr != '\0')
953 return no_match;
954
955 if (val < token->min || val > token->max)
956 return no_match;
957 else
958 return exact_match;
959 }
960
961 static enum match_type match_word(struct cmd_token *token, const char *word)
962 {
963 assert(token->type == WORD_TKN);
964
965 // if the passed token is 0 length, partly match
966 if (!strlen(word))
967 return partly_match;
968
969 // if the passed token is strictly a prefix of the full word, partly
970 // match
971 if (strlen(word) < strlen(token->text))
972 return !strncmp(token->text, word, strlen(word)) ? partly_match
973 : no_match;
974
975 // if they are the same length and exactly equal, exact match
976 else if (strlen(word) == strlen(token->text))
977 return !strncmp(token->text, word, strlen(word)) ? exact_match
978 : no_match;
979
980 return no_match;
981 }
982
983 static enum match_type match_variable(struct cmd_token *token, const char *word)
984 {
985 assert(token->type == VARIABLE_TKN);
986 return exact_match;
987 }
988
989 #define MAC_CHARS "ABCDEFabcdef0123456789:"
990
991 static enum match_type match_mac(const char *word, bool prefix)
992 {
993 /* 6 2-digit hex numbers separated by 5 colons */
994 size_t mac_explen = 6 * 2 + 5;
995 /* '/' + 2-digit integer */
996 size_t mask_len = 1 + 2;
997 unsigned int i;
998 char *eptr;
999 unsigned int maskval;
1000
1001 /* length check */
1002 if (strlen(word) > mac_explen + (prefix ? mask_len : 0))
1003 return no_match;
1004
1005 /* address check */
1006 for (i = 0; i < mac_explen; i++) {
1007 if (word[i] == '\0' || !strchr(MAC_CHARS, word[i]))
1008 break;
1009 if (((i + 1) % 3 == 0) != (word[i] == ':'))
1010 return no_match;
1011 }
1012
1013 /* incomplete address */
1014 if (i < mac_explen && word[i] == '\0')
1015 return partly_match;
1016 else if (i < mac_explen)
1017 return no_match;
1018
1019 /* mask check */
1020 if (prefix && word[i] == '/') {
1021 if (word[++i] == '\0')
1022 return partly_match;
1023
1024 maskval = strtoul(&word[i], &eptr, 10);
1025 if (*eptr != '\0' || maskval > 48)
1026 return no_match;
1027 } else if (prefix && word[i] == '\0') {
1028 return partly_match;
1029 } else if (prefix) {
1030 return no_match;
1031 }
1032
1033 return exact_match;
1034 }