cmdline: support dynamic tokens
[dpdk.git] / lib / librte_cmdline / cmdline_parse.c
1 /*-
2  *   BSD LICENSE
3  *
4  *   Copyright(c) 2010-2014 Intel Corporation. All rights reserved.
5  *   All rights reserved.
6  *
7  *   Redistribution and use in source and binary forms, with or without
8  *   modification, are permitted provided that the following conditions
9  *   are met:
10  *
11  *     * Redistributions of source code must retain the above copyright
12  *       notice, this list of conditions and the following disclaimer.
13  *     * Redistributions in binary form must reproduce the above copyright
14  *       notice, this list of conditions and the following disclaimer in
15  *       the documentation and/or other materials provided with the
16  *       distribution.
17  *     * Neither the name of Intel Corporation nor the names of its
18  *       contributors may be used to endorse or promote products derived
19  *       from this software without specific prior written permission.
20  *
21  *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24  *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25  *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26  *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27  *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28  *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29  *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31  *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  */
33
34 /*
35  * Copyright (c) 2009, Olivier MATZ <zer0@droids-corp.org>
36  * All rights reserved.
37  * Redistribution and use in source and binary forms, with or without
38  * modification, are permitted provided that the following conditions are met:
39  *
40  *     * Redistributions of source code must retain the above copyright
41  *       notice, this list of conditions and the following disclaimer.
42  *     * Redistributions in binary form must reproduce the above copyright
43  *       notice, this list of conditions and the following disclaimer in the
44  *       documentation and/or other materials provided with the distribution.
45  *     * Neither the name of the University of California, Berkeley nor the
46  *       names of its contributors may be used to endorse or promote products
47  *       derived from this software without specific prior written permission.
48  *
49  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
50  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
51  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
52  * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
53  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
54  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
55  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
56  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
57  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
58  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
59  */
60
61 #include <stdio.h>
62 #include <stdarg.h>
63 #include <errno.h>
64 #include <string.h>
65 #include <inttypes.h>
66 #include <ctype.h>
67 #include <termios.h>
68
69 #include <netinet/in.h>
70
71 #include <rte_string_fns.h>
72
73 #include "cmdline_rdline.h"
74 #include "cmdline_parse.h"
75 #include "cmdline.h"
76
77 #ifdef RTE_LIBRTE_CMDLINE_DEBUG
78 #define debug_printf printf
79 #else
80 #define debug_printf(args...) do {} while(0)
81 #endif
82
83 #define CMDLINE_BUFFER_SIZE 64
84
85 /* isblank() needs _XOPEN_SOURCE >= 600 || _ISOC99_SOURCE, so use our
86  * own. */
87 static int
88 isblank2(char c)
89 {
90         if (c == ' ' ||
91             c == '\t' )
92                 return 1;
93         return 0;
94 }
95
96 static int
97 isendofline(char c)
98 {
99         if (c == '\n' ||
100             c == '\r' )
101                 return 1;
102         return 0;
103 }
104
105 static int
106 iscomment(char c)
107 {
108         if (c == '#')
109                 return 1;
110         return 0;
111 }
112
113 int
114 cmdline_isendoftoken(char c)
115 {
116         if (!c || iscomment(c) || isblank2(c) || isendofline(c))
117                 return 1;
118         return 0;
119 }
120
121 int
122 cmdline_isendofcommand(char c)
123 {
124         if (!c || iscomment(c) || isendofline(c))
125                 return 1;
126         return 0;
127 }
128
129 static unsigned int
130 nb_common_chars(const char * s1, const char * s2)
131 {
132         unsigned int i=0;
133
134         while (*s1==*s2 && *s1) {
135                 s1++;
136                 s2++;
137                 i++;
138         }
139         return i;
140 }
141
142 /**
143  * try to match the buffer with an instruction (only the first
144  * nb_match_token tokens if != 0). Return 0 if we match all the
145  * tokens, else the number of matched tokens, else -1.
146  */
147 static int
148 match_inst(cmdline_parse_inst_t *inst, const char *buf,
149            unsigned int nb_match_token, void *resbuf, unsigned resbuf_size,
150            cmdline_parse_token_hdr_t
151                 *(*dyn_tokens)[CMDLINE_PARSE_DYNAMIC_TOKENS])
152 {
153         unsigned int token_num=0;
154         cmdline_parse_token_hdr_t * token_p;
155         unsigned int i=0;
156         int n = 0;
157         struct cmdline_token_hdr token_hdr;
158
159         token_p = inst->tokens[token_num];
160         if (!token_p && dyn_tokens && inst->f) {
161                 if (!(*dyn_tokens)[0])
162                         inst->f(&(*dyn_tokens)[0], NULL, dyn_tokens);
163                 token_p = (*dyn_tokens)[0];
164         }
165         if (token_p)
166                 memcpy(&token_hdr, token_p, sizeof(token_hdr));
167
168         /* check if we match all tokens of inst */
169         while (token_p && (!nb_match_token || i<nb_match_token)) {
170                 debug_printf("TK\n");
171                 /* skip spaces */
172                 while (isblank2(*buf)) {
173                         buf++;
174                 }
175
176                 /* end of buf */
177                 if ( isendofline(*buf) || iscomment(*buf) )
178                         break;
179
180                 if (resbuf == NULL) {
181                         n = token_hdr.ops->parse(token_p, buf, NULL, 0);
182                 } else {
183                         unsigned rb_sz;
184
185                         if (token_hdr.offset > resbuf_size) {
186                                 printf("Parse error(%s:%d): Token offset(%u) "
187                                         "exceeds maximum size(%u)\n",
188                                         __FILE__, __LINE__,
189                                         token_hdr.offset, resbuf_size);
190                                 return -ENOBUFS;
191                         }
192                         rb_sz = resbuf_size - token_hdr.offset;
193
194                         n = token_hdr.ops->parse(token_p, buf, (char *)resbuf +
195                                 token_hdr.offset, rb_sz);
196                 }
197
198                 if (n < 0)
199                         break;
200
201                 debug_printf("TK parsed (len=%d)\n", n);
202                 i++;
203                 buf += n;
204
205                 token_num ++;
206                 if (!inst->tokens[0]) {
207                         if (token_num < (CMDLINE_PARSE_DYNAMIC_TOKENS - 1)) {
208                                 if (!(*dyn_tokens)[token_num])
209                                         inst->f(&(*dyn_tokens)[token_num],
210                                                 NULL,
211                                                 dyn_tokens);
212                                 token_p = (*dyn_tokens)[token_num];
213                         } else
214                                 token_p = NULL;
215                 } else
216                         token_p = inst->tokens[token_num];
217                 if (token_p)
218                         memcpy(&token_hdr, token_p, sizeof(token_hdr));
219         }
220
221         /* does not match */
222         if (i==0)
223                 return -1;
224
225         /* in case we want to match a specific num of token */
226         if (nb_match_token) {
227                 if (i == nb_match_token) {
228                         return 0;
229                 }
230                 return i;
231         }
232
233         /* we don't match all the tokens */
234         if (token_p) {
235                 return i;
236         }
237
238         /* are there are some tokens more */
239         while (isblank2(*buf)) {
240                 buf++;
241         }
242
243         /* end of buf */
244         if ( isendofline(*buf) || iscomment(*buf) )
245                 return 0;
246
247         /* garbage after inst */
248         return i;
249 }
250
251
252 int
253 cmdline_parse(struct cmdline *cl, const char * buf)
254 {
255         unsigned int inst_num=0;
256         cmdline_parse_inst_t *inst;
257         const char *curbuf;
258         char result_buf[CMDLINE_PARSE_RESULT_BUFSIZE];
259         cmdline_parse_token_hdr_t *dyn_tokens[CMDLINE_PARSE_DYNAMIC_TOKENS];
260         void (*f)(void *, struct cmdline *, void *) = NULL;
261         void *data = NULL;
262         int comment = 0;
263         int linelen = 0;
264         int parse_it = 0;
265         int err = CMDLINE_PARSE_NOMATCH;
266         int tok;
267         cmdline_parse_ctx_t *ctx;
268 #ifdef RTE_LIBRTE_CMDLINE_DEBUG
269         char debug_buf[BUFSIZ];
270 #endif
271
272         if (!cl || !buf)
273                 return CMDLINE_PARSE_BAD_ARGS;
274
275         ctx = cl->ctx;
276         memset(&dyn_tokens, 0, sizeof(dyn_tokens));
277
278         /*
279          * - look if the buffer contains at least one line
280          * - look if line contains only spaces or comments
281          * - count line length
282          */
283         curbuf = buf;
284         while (! isendofline(*curbuf)) {
285                 if ( *curbuf == '\0' ) {
286                         debug_printf("Incomplete buf (len=%d)\n", linelen);
287                         return 0;
288                 }
289                 if ( iscomment(*curbuf) ) {
290                         comment = 1;
291                 }
292                 if ( ! isblank2(*curbuf) && ! comment) {
293                         parse_it = 1;
294                 }
295                 curbuf++;
296                 linelen++;
297         }
298
299         /* skip all endofline chars */
300         while (isendofline(buf[linelen])) {
301                 linelen++;
302         }
303
304         /* empty line */
305         if ( parse_it == 0 ) {
306                 debug_printf("Empty line (len=%d)\n", linelen);
307                 return linelen;
308         }
309
310 #ifdef RTE_LIBRTE_CMDLINE_DEBUG
311         snprintf(debug_buf, (linelen>64 ? 64 : linelen), "%s", buf);
312         debug_printf("Parse line : len=%d, <%s>\n", linelen, debug_buf);
313 #endif
314
315         /* parse it !! */
316         inst = ctx[inst_num];
317         while (inst) {
318                 debug_printf("INST %d\n", inst_num);
319
320                 /* fully parsed */
321                 tok = match_inst(inst, buf, 0, result_buf, sizeof(result_buf),
322                                  &dyn_tokens);
323
324                 if (tok > 0) /* we matched at least one token */
325                         err = CMDLINE_PARSE_BAD_ARGS;
326
327                 else if (!tok) {
328                         debug_printf("INST fully parsed\n");
329                         /* skip spaces */
330                         while (isblank2(*curbuf)) {
331                                 curbuf++;
332                         }
333
334                         /* if end of buf -> there is no garbage after inst */
335                         if (isendofline(*curbuf) || iscomment(*curbuf)) {
336                                 if (!f) {
337                                         memcpy(&f, &inst->f, sizeof(f));
338                                         memcpy(&data, &inst->data, sizeof(data));
339                                 }
340                                 else {
341                                         /* more than 1 inst matches */
342                                         err = CMDLINE_PARSE_AMBIGUOUS;
343                                         f=NULL;
344                                         debug_printf("Ambiguous cmd\n");
345                                         break;
346                                 }
347                         }
348                 }
349
350                 inst_num ++;
351                 inst = ctx[inst_num];
352         }
353
354         /* call func */
355         if (f) {
356                 f(result_buf, cl, data);
357         }
358
359         /* no match */
360         else {
361                 debug_printf("No match err=%d\n", err);
362                 return err;
363         }
364
365         return linelen;
366 }
367
368 int
369 cmdline_complete(struct cmdline *cl, const char *buf, int *state,
370                  char *dst, unsigned int size)
371 {
372         const char *partial_tok = buf;
373         unsigned int inst_num = 0;
374         cmdline_parse_inst_t *inst;
375         cmdline_parse_token_hdr_t *token_p;
376         struct cmdline_token_hdr token_hdr;
377         char tmpbuf[CMDLINE_BUFFER_SIZE], comp_buf[CMDLINE_BUFFER_SIZE];
378         cmdline_parse_token_hdr_t *dyn_tokens[CMDLINE_PARSE_DYNAMIC_TOKENS];
379         unsigned int partial_tok_len;
380         int comp_len = -1;
381         int tmp_len = -1;
382         int nb_token = 0;
383         unsigned int i, n;
384         int l;
385         unsigned int nb_completable;
386         unsigned int nb_non_completable;
387         int local_state = 0;
388         const char *help_str;
389         cmdline_parse_ctx_t *ctx;
390
391         if (!cl || !buf || !state || !dst)
392                 return -1;
393
394         ctx = cl->ctx;
395
396         debug_printf("%s called\n", __func__);
397         memset(&token_hdr, 0, sizeof(token_hdr));
398         memset(&dyn_tokens, 0, sizeof(dyn_tokens));
399
400         /* count the number of complete token to parse */
401         for (i=0 ; buf[i] ; i++) {
402                 if (!isblank2(buf[i]) && isblank2(buf[i+1]))
403                         nb_token++;
404                 if (isblank2(buf[i]) && !isblank2(buf[i+1]))
405                         partial_tok = buf+i+1;
406         }
407         partial_tok_len = strnlen(partial_tok, RDLINE_BUF_SIZE);
408
409         /* first call -> do a first pass */
410         if (*state <= 0) {
411                 debug_printf("try complete <%s>\n", buf);
412                 debug_printf("there is %d complete tokens, <%s> is incomplete\n",
413                              nb_token, partial_tok);
414
415                 nb_completable = 0;
416                 nb_non_completable = 0;
417
418                 inst = ctx[inst_num];
419                 while (inst) {
420                         /* parse the first tokens of the inst */
421                         if (nb_token &&
422                             match_inst(inst, buf, nb_token, NULL, 0,
423                                        &dyn_tokens))
424                                 goto next;
425
426                         debug_printf("instruction match\n");
427                         if (!inst->tokens[0]) {
428                                 if (nb_token <
429                                     (CMDLINE_PARSE_DYNAMIC_TOKENS - 1)) {
430                                         if (!dyn_tokens[nb_token])
431                                                 inst->f(&dyn_tokens[nb_token],
432                                                         NULL,
433                                                         &dyn_tokens);
434                                         token_p = dyn_tokens[nb_token];
435                                 } else
436                                         token_p = NULL;
437                         } else
438                                 token_p = inst->tokens[nb_token];
439                         if (token_p)
440                                 memcpy(&token_hdr, token_p, sizeof(token_hdr));
441
442                         /* non completable */
443                         if (!token_p ||
444                             !token_hdr.ops->complete_get_nb ||
445                             !token_hdr.ops->complete_get_elt ||
446                             (n = token_hdr.ops->complete_get_nb(token_p)) == 0) {
447                                 nb_non_completable++;
448                                 goto next;
449                         }
450
451                         debug_printf("%d choices for this token\n", n);
452                         for (i=0 ; i<n ; i++) {
453                                 if (token_hdr.ops->complete_get_elt(token_p, i,
454                                                                     tmpbuf,
455                                                                     sizeof(tmpbuf)) < 0)
456                                         continue;
457
458                                 /* we have at least room for one char */
459                                 tmp_len = strnlen(tmpbuf, sizeof(tmpbuf));
460                                 if (tmp_len < CMDLINE_BUFFER_SIZE - 1) {
461                                         tmpbuf[tmp_len] = ' ';
462                                         tmpbuf[tmp_len+1] = 0;
463                                 }
464
465                                 debug_printf("   choice <%s>\n", tmpbuf);
466
467                                 /* does the completion match the
468                                  * beginning of the word ? */
469                                 if (!strncmp(partial_tok, tmpbuf,
470                                              partial_tok_len)) {
471                                         if (comp_len == -1) {
472                                                 snprintf(comp_buf, sizeof(comp_buf),
473                                                          "%s", tmpbuf + partial_tok_len);
474                                                 comp_len =
475                                                         strnlen(tmpbuf + partial_tok_len,
476                                                                         sizeof(tmpbuf) - partial_tok_len);
477
478                                         }
479                                         else {
480                                                 comp_len =
481                                                         nb_common_chars(comp_buf,
482                                                                         tmpbuf+partial_tok_len);
483                                                 comp_buf[comp_len] = 0;
484                                         }
485                                         nb_completable++;
486                                 }
487                         }
488                 next:
489                         debug_printf("next\n");
490                         inst_num ++;
491                         inst = ctx[inst_num];
492                 }
493
494                 debug_printf("total choices %d for this completion\n",
495                              nb_completable);
496
497                 /* no possible completion */
498                 if (nb_completable == 0 && nb_non_completable == 0)
499                         return 0;
500
501                 /* if multichoice is not required */
502                 if (*state == 0 && partial_tok_len > 0) {
503                         /* one or several choices starting with the
504                            same chars */
505                         if (comp_len > 0) {
506                                 if ((unsigned)(comp_len + 1) > size)
507                                         return 0;
508
509                                 snprintf(dst, size, "%s", comp_buf);
510                                 dst[comp_len] = 0;
511                                 return 2;
512                         }
513                 }
514         }
515
516         /* init state correctly */
517         if (*state == -1)
518                 *state = 0;
519
520         debug_printf("Multiple choice STATE=%d\n", *state);
521
522         inst_num = 0;
523         inst = ctx[inst_num];
524         while (inst) {
525                 /* we need to redo it */
526                 inst = ctx[inst_num];
527
528                 if (nb_token &&
529                     match_inst(inst, buf, nb_token, NULL, 0, &dyn_tokens))
530                         goto next2;
531
532                 if (!inst->tokens[0]) {
533                         if (nb_token < (CMDLINE_PARSE_DYNAMIC_TOKENS - 1)) {
534                                 if (!dyn_tokens[nb_token])
535                                         inst->f(&dyn_tokens[nb_token],
536                                                 NULL,
537                                                 &dyn_tokens);
538                                 token_p = dyn_tokens[nb_token];
539                         } else
540                                 token_p = NULL;
541                 } else
542                         token_p = inst->tokens[nb_token];
543                 if (token_p)
544                         memcpy(&token_hdr, token_p, sizeof(token_hdr));
545
546                 /* one choice for this token */
547                 if (!token_p ||
548                     !token_hdr.ops->complete_get_nb ||
549                     !token_hdr.ops->complete_get_elt ||
550                     (n = token_hdr.ops->complete_get_nb(token_p)) == 0) {
551                         if (local_state < *state) {
552                                 local_state++;
553                                 goto next2;
554                         }
555                         (*state)++;
556                         if (token_p && token_hdr.ops->get_help) {
557                                 token_hdr.ops->get_help(token_p, tmpbuf,
558                                                         sizeof(tmpbuf));
559                                 help_str = inst->help_str;
560                                 if (help_str)
561                                         snprintf(dst, size, "[%s]: %s", tmpbuf,
562                                                  help_str);
563                                 else
564                                         snprintf(dst, size, "[%s]: No help",
565                                                  tmpbuf);
566                         }
567                         else {
568                                 snprintf(dst, size, "[RETURN]");
569                         }
570                         return 1;
571                 }
572
573                 /* several choices */
574                 for (i=0 ; i<n ; i++) {
575                         if (token_hdr.ops->complete_get_elt(token_p, i, tmpbuf,
576                                                             sizeof(tmpbuf)) < 0)
577                                 continue;
578                         /* we have at least room for one char */
579                         tmp_len = strnlen(tmpbuf, sizeof(tmpbuf));
580                         if (tmp_len < CMDLINE_BUFFER_SIZE - 1) {
581                                 tmpbuf[tmp_len] = ' ';
582                                 tmpbuf[tmp_len + 1] = 0;
583                         }
584
585                         debug_printf("   choice <%s>\n", tmpbuf);
586
587                         /* does the completion match the beginning of
588                          * the word ? */
589                         if (!strncmp(partial_tok, tmpbuf,
590                                      partial_tok_len)) {
591                                 if (local_state < *state) {
592                                         local_state++;
593                                         continue;
594                                 }
595                                 (*state)++;
596                                 l=snprintf(dst, size, "%s", tmpbuf);
597                                 if (l>=0 && token_hdr.ops->get_help) {
598                                         token_hdr.ops->get_help(token_p, tmpbuf,
599                                                                 sizeof(tmpbuf));
600                                         help_str = inst->help_str;
601                                         if (help_str)
602                                                 snprintf(dst+l, size-l, "[%s]: %s",
603                                                          tmpbuf, help_str);
604                                         else
605                                                 snprintf(dst+l, size-l,
606                                                          "[%s]: No help", tmpbuf);
607                                 }
608
609                                 return 1;
610                         }
611                 }
612         next2:
613                 inst_num ++;
614                 inst = ctx[inst_num];
615         }
616         return 0;
617 }