Coverage Report

Created: 2026-07-16 06:42

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/frr/lib/grammar_sandbox.c
Line
Count
Source
1
// SPDX-License-Identifier: GPL-2.0-or-later
2
/*
3
 * Testing shim and API examples for the new CLI backend.
4
 *
5
 * This unit defines a number of commands in the old engine that can
6
 * be used to test and interact with the new engine.
7
 * --
8
 * Copyright (C) 2016 Cumulus Networks, Inc.
9
 */
10
11
#ifdef HAVE_CONFIG_H
12
#include "config.h"
13
#endif
14
15
#include "command.h"
16
#include "graph.h"
17
#include "linklist.h"
18
#include "command_match.h"
19
20
#define GRAMMAR_STR "CLI grammar sandbox\n"
21
22
8
DEFINE_MTYPE_STATIC(LIB, CMD_DESCRIPTIONS, "Command desc");
23
8
24
8
/** headers **/
25
8
void grammar_sandbox_init(void);
26
8
static void pretty_print_graph(struct vty *vty, struct graph_node *, int, int,
27
8
             struct graph_node **, size_t);
28
8
static void init_cmdgraph(struct vty *, struct graph **);
29
8
30
8
/** shim interface commands **/
31
8
static struct graph *nodegraph = NULL, *nodegraph_free = NULL;
32
8
33
8
#define check_nodegraph()                                                      \
34
8
  do {                                                                   \
35
0
    if (!nodegraph) {                                              \
36
0
      vty_out(vty, "nodegraph not initialized\n");           \
37
0
      return CMD_WARNING;                                    \
38
0
    }                                                              \
39
0
  } while (0)
40
41
DEFUN (grammar_test,
42
       grammar_test_cmd,
43
       "grammar parse LINE...",
44
       GRAMMAR_STR
45
       "parse a command\n"
46
       "command to pass to new parser\n")
47
0
{
48
0
  check_nodegraph();
49
50
0
  int idx_command = 2;
51
  // make a string from tokenized command line
52
0
  char *command = argv_concat(argv, argc, idx_command);
53
54
  // create cmd_element for parser
55
0
  struct cmd_element *cmd =
56
0
    XCALLOC(MTYPE_CMD_DESCRIPTIONS, sizeof(struct cmd_element));
57
0
  cmd->string = command;
58
0
  cmd->doc =
59
0
    "0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n";
60
0
  cmd->func = NULL;
61
62
  // parse the command and install it into the command graph
63
0
  struct graph *graph = graph_new();
64
0
  struct cmd_token *token = cmd_token_new(START_TKN, 0, NULL, NULL);
65
0
  graph_new_node(graph, token, (void (*)(void *)) & cmd_token_del);
66
67
0
  cmd_graph_parse(graph, cmd);
68
0
  cmd_graph_merge(nodegraph, graph, +1);
69
70
0
  return CMD_SUCCESS;
71
0
}
72
73
DEFUN (grammar_test_complete,
74
       grammar_test_complete_cmd,
75
       "grammar complete COMMAND...",
76
       GRAMMAR_STR
77
       "attempt to complete input on DFA\n"
78
       "command to complete\n")
79
0
{
80
0
  check_nodegraph();
81
82
0
  int idx_command = 2;
83
0
  char *cmdstr = argv_concat(argv, argc, idx_command);
84
0
  if (!cmdstr)
85
0
    return CMD_SUCCESS;
86
87
0
  vector command = cmd_make_strvec(cmdstr);
88
0
  if (!command) {
89
0
    XFREE(MTYPE_TMP, cmdstr);
90
0
    return CMD_SUCCESS;
91
0
  }
92
93
  // generate completions of user input
94
0
  struct list *completions;
95
0
  enum matcher_rv result =
96
0
    command_complete(nodegraph, command, &completions);
97
98
  // print completions or relevant error message
99
0
  if (!MATCHER_ERROR(result)) {
100
0
    vector comps = completions_to_vec(completions);
101
0
    struct cmd_token *tkn;
102
103
    // calculate length of longest tkn->text in completions
104
0
    unsigned int width = 0, i = 0;
105
0
    for (i = 0; i < vector_active(comps); i++) {
106
0
      tkn = vector_slot(comps, i);
107
0
      unsigned int len = strlen(tkn->text);
108
0
      width = len > width ? len : width;
109
0
    }
110
111
    // print completions
112
0
    for (i = 0; i < vector_active(comps); i++) {
113
0
      tkn = vector_slot(comps, i);
114
0
      vty_out(vty, "  %-*s  %s\n", width, tkn->text,
115
0
        tkn->desc);
116
0
    }
117
118
0
    for (i = 0; i < vector_active(comps); i++)
119
0
      cmd_token_del(
120
0
        (struct cmd_token *)vector_slot(comps, i));
121
0
    vector_free(comps);
122
0
  } else
123
0
    vty_out(vty, "%% No match\n");
124
125
  // free resources
126
0
  list_delete(&completions);
127
0
  cmd_free_strvec(command);
128
0
  XFREE(MTYPE_TMP, cmdstr);
129
130
0
  return CMD_SUCCESS;
131
0
}
132
133
DEFUN (grammar_test_match,
134
       grammar_test_match_cmd,
135
       "grammar match COMMAND...",
136
       GRAMMAR_STR
137
       "attempt to match input on DFA\n"
138
       "command to match\n")
139
0
{
140
0
  check_nodegraph();
141
142
0
  int idx_command = 2;
143
0
  if (argv[2]->arg[0] == '#')
144
0
    return CMD_SUCCESS;
145
146
0
  char *cmdstr = argv_concat(argv, argc, idx_command);
147
0
  if (!cmdstr)
148
0
    return CMD_SUCCESS;
149
0
  vector command = cmd_make_strvec(cmdstr);
150
0
  if (!command) {
151
0
    XFREE(MTYPE_TMP, cmdstr);
152
0
    return CMD_SUCCESS;
153
0
  }
154
155
0
  struct list *argvv = NULL;
156
0
  const struct cmd_element *element = NULL;
157
0
  enum matcher_rv result =
158
0
    command_match(nodegraph, command, &argvv, &element);
159
160
  // print completions or relevant error message
161
0
  if (element) {
162
0
    vty_out(vty, "Matched: %s\n", element->string);
163
0
    struct listnode *ln;
164
0
    struct cmd_token *token;
165
0
    for (ALL_LIST_ELEMENTS_RO(argvv, ln, token))
166
0
      vty_out(vty, "%s -- %s\n", token->text, token->arg);
167
168
0
    vty_out(vty, "func: %p\n", element->func);
169
170
0
    list_delete(&argvv);
171
0
  } else {
172
0
    assert(MATCHER_ERROR(result));
173
0
    switch (result) {
174
0
    case MATCHER_NO_MATCH:
175
0
      vty_out(vty, "%% Unknown command\n");
176
0
      break;
177
0
    case MATCHER_INCOMPLETE:
178
0
      vty_out(vty, "%% Incomplete command\n");
179
0
      break;
180
0
    case MATCHER_AMBIGUOUS:
181
0
      vty_out(vty, "%% Ambiguous command\n");
182
0
      break;
183
0
    case MATCHER_OK:
184
0
      vty_out(vty, "%% Unknown error\n");
185
0
      break;
186
0
    }
187
0
  }
188
189
  // free resources
190
0
  cmd_free_strvec(command);
191
0
  XFREE(MTYPE_TMP, cmdstr);
192
193
0
  return CMD_SUCCESS;
194
0
}
195
196
/**
197
 * Testing shim to test docstrings
198
 */
199
DEFUN (grammar_test_doc,
200
       grammar_test_doc_cmd,
201
       "grammar test docstring",
202
       GRAMMAR_STR
203
       "Test function for docstring\n"
204
       "Command end\n")
205
0
{
206
0
  check_nodegraph();
207
208
  // create cmd_element with docstring
209
0
  struct cmd_element *cmd =
210
0
    XCALLOC(MTYPE_CMD_DESCRIPTIONS, sizeof(struct cmd_element));
211
0
  cmd->string = XSTRDUP(
212
0
    MTYPE_CMD_DESCRIPTIONS,
213
0
    "test docstring <example|selector follow> (1-255) end VARIABLE [OPTION|set lol] . VARARG");
214
0
  cmd->doc = XSTRDUP(MTYPE_CMD_DESCRIPTIONS,
215
0
         "Test stuff\n"
216
0
         "docstring thing\n"
217
0
         "first example\n"
218
0
         "second example\n"
219
0
         "follow\n"
220
0
         "random range\n"
221
0
         "end thingy\n"
222
0
         "variable\n"
223
0
         "optional variable\n"
224
0
         "optional set\n"
225
0
         "optional lol\n"
226
0
         "vararg!\n");
227
0
  cmd->func = NULL;
228
229
  // parse element
230
0
  cmd_graph_parse(nodegraph, cmd);
231
232
0
  return CMD_SUCCESS;
233
0
}
234
235
/**
236
 * Debugging command to print command graph
237
 */
238
DEFUN (grammar_test_show,
239
       grammar_test_show_cmd,
240
       "grammar show [doc]",
241
       GRAMMAR_STR
242
       "print current accumulated DFA\n"
243
       "include docstrings\n")
244
0
{
245
0
  check_nodegraph();
246
247
0
  struct graph_node *stack[CMD_ARGC_MAX];
248
0
  pretty_print_graph(vty, vector_slot(nodegraph->nodes, 0), 0, argc >= 3,
249
0
         stack, 0);
250
0
  return CMD_SUCCESS;
251
0
}
252
253
DEFUN (grammar_test_dot,
254
       grammar_test_dot_cmd,
255
       "grammar dotfile OUTNAME",
256
       GRAMMAR_STR
257
       "print current graph for dot\n"
258
       ".dot filename\n")
259
0
{
260
0
  check_nodegraph();
261
0
  FILE *ofd = fopen(argv[2]->arg, "w");
262
263
0
  if (!ofd) {
264
0
    vty_out(vty, "%s: %s\r\n", argv[2]->arg, strerror(errno));
265
0
    return CMD_SUCCESS;
266
0
  }
267
268
0
  char *dot = cmd_graph_dump_dot(nodegraph);
269
270
0
  fprintf(ofd, "%s", dot);
271
0
  fclose(ofd);
272
0
  XFREE(MTYPE_TMP, dot);
273
274
0
  return CMD_SUCCESS;
275
0
}
276
277
struct cmd_permute_item {
278
  char *cmd;
279
  struct cmd_element *el;
280
};
281
282
static void cmd_permute_free(void *arg)
283
0
{
284
0
  struct cmd_permute_item *i = arg;
285
0
  XFREE(MTYPE_TMP, i->cmd);
286
0
  XFREE(MTYPE_TMP, i);
287
0
}
288
289
static int cmd_permute_cmp(void *a, void *b)
290
0
{
291
0
  struct cmd_permute_item *aa = a, *bb = b;
292
0
  return strcmp(aa->cmd, bb->cmd);
293
0
}
294
295
static void cmd_graph_permute(struct list *out, struct graph_node **stack,
296
            size_t stackpos, char *cmd)
297
0
{
298
0
  struct graph_node *gn = stack[stackpos];
299
0
  struct cmd_token *tok = gn->data;
300
0
  char *appendp = cmd + strlen(cmd);
301
0
  size_t j;
302
303
0
  if (tok->type < SPECIAL_TKN) {
304
0
    sprintf(appendp, "%s ", tok->text);
305
0
    appendp += strlen(appendp);
306
0
  } else if (tok->type == END_TKN) {
307
0
    struct cmd_permute_item *i = XMALLOC(MTYPE_TMP, sizeof(*i));
308
0
    i->el = ((struct graph_node *)vector_slot(gn->to, 0))->data;
309
0
    i->cmd = XSTRDUP(MTYPE_TMP, cmd);
310
0
    i->cmd[strlen(cmd) - 1] = '\0';
311
0
    listnode_add_sort(out, i);
312
0
    return;
313
0
  }
314
315
0
  if (++stackpos == CMD_ARGC_MAX)
316
0
    return;
317
318
0
  for (size_t i = 0; i < vector_active(gn->to); i++) {
319
0
    struct graph_node *gnext = vector_slot(gn->to, i);
320
0
    for (j = 0; j < stackpos; j++)
321
0
      if (stack[j] == gnext)
322
0
        break;
323
0
    if (j != stackpos)
324
0
      continue;
325
326
0
    stack[stackpos] = gnext;
327
0
    *appendp = '\0';
328
0
    cmd_graph_permute(out, stack, stackpos, cmd);
329
0
  }
330
0
}
331
332
static struct list *cmd_graph_permutations(struct graph *graph)
333
0
{
334
0
  char accumulate[2048] = "";
335
0
  struct graph_node *stack[CMD_ARGC_MAX];
336
337
0
  struct list *rv = list_new();
338
0
  rv->cmp = cmd_permute_cmp;
339
0
  rv->del = cmd_permute_free;
340
0
  stack[0] = vector_slot(graph->nodes, 0);
341
0
  cmd_graph_permute(rv, stack, 0, accumulate);
342
0
  return rv;
343
0
}
344
345
extern vector cmdvec;
346
347
DEFUN (grammar_findambig,
348
       grammar_findambig_cmd,
349
       "grammar find-ambiguous [{printall|nodescan}]",
350
       GRAMMAR_STR
351
       "Find ambiguous commands\n"
352
       "Print all permutations\n"
353
       "Scan all nodes\n")
354
0
{
355
0
  struct list *commands;
356
0
  struct cmd_permute_item *prev = NULL, *cur = NULL;
357
0
  struct listnode *ln;
358
0
  int i, printall, scan, scannode = 0;
359
0
  int ambig = 0;
360
361
0
  i = 0;
362
0
  printall = argv_find(argv, argc, "printall", &i);
363
0
  i = 0;
364
0
  scan = argv_find(argv, argc, "nodescan", &i);
365
366
0
  if (scan && nodegraph_free) {
367
0
    graph_delete_graph(nodegraph_free);
368
0
    nodegraph_free = NULL;
369
0
  }
370
371
0
  if (!scan && !nodegraph) {
372
0
    vty_out(vty, "nodegraph uninitialized\r\n");
373
0
    return CMD_WARNING_CONFIG_FAILED;
374
0
  }
375
376
0
  do {
377
0
    if (scan) {
378
0
      struct cmd_node *cnode =
379
0
        vector_slot(cmdvec, scannode++);
380
0
      if (!cnode)
381
0
        continue;
382
0
      cmd_finalize_node(cnode);
383
0
      nodegraph = cnode->cmdgraph;
384
0
      if (!nodegraph)
385
0
        continue;
386
0
      vty_out(vty, "scanning node %d (%s)\n", scannode - 1,
387
0
        cnode->name);
388
0
    }
389
390
0
    commands = cmd_graph_permutations(nodegraph);
391
0
    prev = NULL;
392
0
    for (ALL_LIST_ELEMENTS_RO(commands, ln, cur)) {
393
0
      int same = prev && !strcmp(prev->cmd, cur->cmd);
394
0
      if (printall && !same)
395
0
        vty_out(vty, "'%s' [%x]\n", cur->cmd,
396
0
          cur->el->daemon);
397
0
      if (same) {
398
0
        vty_out(vty, "'%s' AMBIGUOUS:\n", cur->cmd);
399
0
        vty_out(vty, "  %s\n   '%s'\n", prev->el->name,
400
0
          prev->el->string);
401
0
        vty_out(vty, "  %s\n   '%s'\n", cur->el->name,
402
0
          cur->el->string);
403
0
        vty_out(vty, "\n");
404
0
        ambig++;
405
0
      }
406
0
      prev = cur;
407
0
    }
408
0
    list_delete(&commands);
409
410
0
    vty_out(vty, "\n");
411
0
  } while (scan && scannode < LINK_PARAMS_NODE);
412
413
0
  vty_out(vty, "%d ambiguous commands found.\n", ambig);
414
415
0
  if (scan)
416
0
    nodegraph = NULL;
417
0
  return ambig == 0 ? CMD_SUCCESS : CMD_WARNING_CONFIG_FAILED;
418
0
}
419
420
DEFUN (grammar_init_graph,
421
       grammar_init_graph_cmd,
422
       "grammar init",
423
       GRAMMAR_STR
424
       "(re)initialize graph\n")
425
0
{
426
0
  if (nodegraph_free)
427
0
    graph_delete_graph(nodegraph_free);
428
0
  nodegraph_free = NULL;
429
430
0
  init_cmdgraph(vty, &nodegraph);
431
0
  return CMD_SUCCESS;
432
0
}
433
434
DEFUN (grammar_access,
435
       grammar_access_cmd,
436
       "grammar access (0-65535)",
437
       GRAMMAR_STR
438
       "access node graph\n"
439
       "node number\n")
440
0
{
441
0
  if (nodegraph_free)
442
0
    graph_delete_graph(nodegraph_free);
443
0
  nodegraph_free = NULL;
444
445
0
  struct cmd_node *cnode;
446
447
0
  cnode = vector_slot(cmdvec, atoi(argv[2]->arg));
448
0
  if (!cnode) {
449
0
    vty_out(vty, "%% no such node\n");
450
0
    return CMD_WARNING_CONFIG_FAILED;
451
0
  }
452
453
0
  vty_out(vty, "node %d\n", (int)cnode->node);
454
0
  cmd_finalize_node(cnode);
455
0
  nodegraph = cnode->cmdgraph;
456
0
  return CMD_SUCCESS;
457
0
}
458
459
/* this is called in vtysh.c to set up the testing shim */
460
void grammar_sandbox_init(void)
461
0
{
462
  // install all enable elements
463
0
  install_element(ENABLE_NODE, &grammar_test_cmd);
464
0
  install_element(ENABLE_NODE, &grammar_test_show_cmd);
465
0
  install_element(ENABLE_NODE, &grammar_test_dot_cmd);
466
0
  install_element(ENABLE_NODE, &grammar_test_match_cmd);
467
0
  install_element(ENABLE_NODE, &grammar_test_complete_cmd);
468
0
  install_element(ENABLE_NODE, &grammar_test_doc_cmd);
469
0
  install_element(ENABLE_NODE, &grammar_findambig_cmd);
470
0
  install_element(ENABLE_NODE, &grammar_init_graph_cmd);
471
0
  install_element(ENABLE_NODE, &grammar_access_cmd);
472
0
}
473
474
/**
475
 * Pretty-prints a graph, assuming it is a tree.
476
 *
477
 * @param start the node to take as the root
478
 * @param level indent level for recursive calls, always pass 0
479
 */
480
static void pretty_print_graph(struct vty *vty, struct graph_node *start,
481
             int level, int desc, struct graph_node **stack,
482
             size_t stackpos)
483
0
{
484
  // print this node
485
0
  char tokennum[32];
486
0
  struct cmd_token *tok = start->data;
487
488
0
  snprintf(tokennum, sizeof(tokennum), "%d?", tok->type);
489
0
  vty_out(vty, "%s", lookup_msg(tokennames, tok->type, NULL));
490
0
  if (tok->text)
491
0
    vty_out(vty, ":\"%s\"", tok->text);
492
0
  if (tok->varname)
493
0
    vty_out(vty, " => %s", tok->varname);
494
0
  if (desc)
495
0
    vty_out(vty, " ?'%s'", tok->desc);
496
0
  vty_out(vty, " ");
497
498
0
  if (stackpos == CMD_ARGC_MAX) {
499
0
    vty_out(vty, " -aborting! (depth limit)\n");
500
0
    return;
501
0
  }
502
0
  stack[stackpos++] = start;
503
504
0
  int numto = desc ? 2 : vector_active(start->to);
505
0
  if (numto) {
506
0
    if (numto > 1)
507
0
      vty_out(vty, "\n");
508
0
    for (unsigned int i = 0; i < vector_active(start->to); i++) {
509
0
      struct graph_node *adj = vector_slot(start->to, i);
510
      // if we're listing multiple children, indent!
511
0
      if (numto > 1)
512
0
        for (int j = 0; j < level + 1; j++)
513
0
          vty_out(vty, "    ");
514
      // if this node is a vararg, just print *
515
0
      if (adj == start)
516
0
        vty_out(vty, "*");
517
0
      else if (((struct cmd_token *)adj->data)->type
518
0
         == END_TKN)
519
0
        vty_out(vty, "--END\n");
520
0
      else {
521
0
        size_t k;
522
0
        for (k = 0; k < stackpos; k++)
523
0
          if (stack[k] == adj) {
524
0
            vty_out(vty, "<<loop@%zu \n",
525
0
              k);
526
0
            break;
527
0
          }
528
0
        if (k == stackpos)
529
0
          pretty_print_graph(
530
0
            vty, adj,
531
0
            numto > 1 ? level + 1 : level,
532
0
            desc, stack, stackpos);
533
0
      }
534
0
    }
535
0
  } else
536
0
    vty_out(vty, "\n");
537
0
}
538
539
/** stuff that should go in command.c + command.h */
540
static void init_cmdgraph(struct vty *vty, struct graph **graph)
541
0
{
542
  // initialize graph, add start noe
543
0
  *graph = graph_new();
544
0
  nodegraph_free = *graph;
545
0
  struct cmd_token *token = cmd_token_new(START_TKN, 0, NULL, NULL);
546
0
  graph_new_node(*graph, token, (void (*)(void *)) & cmd_token_del);
547
0
  if (vty)
548
0
    vty_out(vty, "initialized graph\n");
549
0
}