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