cmdline: fix dynamic tokens initialization
[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 /** Retrieve either static or dynamic token at a given index. */
143 static cmdline_parse_token_hdr_t *
144 get_token(cmdline_parse_inst_t *inst,
145           unsigned int index,
146           cmdline_parse_token_hdr_t
147                 *(*dyn_tokens)[CMDLINE_PARSE_DYNAMIC_TOKENS])
148 {
149         /* check presence of static tokens first */
150         if (inst->tokens[0] || !inst->f)
151                 return inst->tokens[index];
152         /* for dynamic tokens, make sure index does not overflow */
153         if (index >= CMDLINE_PARSE_DYNAMIC_TOKENS - 1)
154                 return NULL;
155         /* in case token is already generated, return it */
156         if ((*dyn_tokens)[index])
157                 return (*dyn_tokens)[index];
158         /* generate token */
159         inst->f(&(*dyn_tokens)[index], NULL, dyn_tokens);
160         /* return immediately if there are no more tokens to expect */
161         if (!(*dyn_tokens)[index])
162                 return NULL;
163         /* terminate list with a NULL entry */
164         (*dyn_tokens)[index + 1] = NULL;
165         return (*dyn_tokens)[index];
166 }
167
168 /**
169  * try to match the buffer with an instruction (only the first
170  * nb_match_token tokens if != 0). Return 0 if we match all the
171  * tokens, else the number of matched tokens, else -1.
172  */
173 static int
174 match_inst(cmdline_parse_inst_t *inst, const char *buf,
175            unsigned int nb_match_token, void *resbuf, unsigned resbuf_size,
176            cmdline_parse_token_hdr_t
177                 *(*dyn_tokens)[CMDLINE_PARSE_DYNAMIC_TOKENS])
178 {
179         unsigned int token_num=0;
180         cmdline_parse_token_hdr_t * token_p;
181         unsigned int i=0;
182         int n = 0;
183         struct cmdline_token_hdr token_hdr;
184
185         token_p = get_token(inst, token_num, dyn_tokens);
186         if (token_p)
187                 memcpy(&token_hdr, token_p, sizeof(token_hdr));
188
189         /* check if we match all tokens of inst */
190         while (token_p && (!nb_match_token || i<nb_match_token)) {
191                 debug_printf("TK\n");
192                 /* skip spaces */
193                 while (isblank2(*buf)) {
194                         buf++;
195                 }
196
197                 /* end of buf */
198                 if ( isendofline(*buf) || iscomment(*buf) )
199                         break;
200
201                 if (resbuf == NULL) {
202                         n = token_hdr.ops->parse(token_p, buf, NULL, 0);
203                 } else {
204                         unsigned rb_sz;
205
206                         if (token_hdr.offset > resbuf_size) {
207                                 printf("Parse error(%s:%d): Token offset(%u) "
208                                         "exceeds maximum size(%u)\n",
209                                         __FILE__, __LINE__,
210                                         token_hdr.offset, resbuf_size);
211                                 return -ENOBUFS;
212                         }
213                         rb_sz = resbuf_size - token_hdr.offset;
214
215                         n = token_hdr.ops->parse(token_p, buf, (char *)resbuf +
216                                 token_hdr.offset, rb_sz);
217                 }
218
219                 if (n < 0)
220                         break;
221
222                 debug_printf("TK parsed (len=%d)\n", n);
223                 i++;
224                 buf += n;
225
226                 token_num ++;
227                 token_p = get_token(inst, token_num, dyn_tokens);
228                 if (token_p)
229                         memcpy(&token_hdr, token_p, sizeof(token_hdr));
230         }
231
232         /* does not match */
233         if (i==0)
234                 return -1;
235
236         /* in case we want to match a specific num of token */
237         if (nb_match_token) {
238                 if (i == nb_match_token) {
239                         return 0;
240                 }
241                 return i;
242         }
243
244         /* we don't match all the tokens */
245         if (token_p) {
246                 return i;
247         }
248
249         /* are there are some tokens more */
250         while (isblank2(*buf)) {
251                 buf++;
252         }
253
254         /* end of buf */
255         if ( isendofline(*buf) || iscomment(*buf) )
256                 return 0;
257
258         /* garbage after inst */
259         return i;
260 }
261
262
263 int
264 cmdline_parse(struct cmdline *cl, const char * buf)
265 {
266         unsigned int inst_num=0;
267         cmdline_parse_inst_t *inst;
268         const char *curbuf;
269         union {
270                 char buf[CMDLINE_PARSE_RESULT_BUFSIZE];
271                 long double align; /* strong alignment constraint for buf */
272         } result, tmp_result;
273         cmdline_parse_token_hdr_t *dyn_tokens[CMDLINE_PARSE_DYNAMIC_TOKENS];
274         void (*f)(void *, struct cmdline *, void *) = NULL;
275         void *data = NULL;
276         int comment = 0;
277         int linelen = 0;
278         int parse_it = 0;
279         int err = CMDLINE_PARSE_NOMATCH;
280         int tok;
281         cmdline_parse_ctx_t *ctx;
282 #ifdef RTE_LIBRTE_CMDLINE_DEBUG
283         char debug_buf[BUFSIZ];
284 #endif
285
286         if (!cl || !buf)
287                 return CMDLINE_PARSE_BAD_ARGS;
288
289         ctx = cl->ctx;
290
291         /*
292          * - look if the buffer contains at least one line
293          * - look if line contains only spaces or comments
294          * - count line length
295          */
296         curbuf = buf;
297         while (! isendofline(*curbuf)) {
298                 if ( *curbuf == '\0' ) {
299                         debug_printf("Incomplete buf (len=%d)\n", linelen);
300                         return 0;
301                 }
302                 if ( iscomment(*curbuf) ) {
303                         comment = 1;
304                 }
305                 if ( ! isblank2(*curbuf) && ! comment) {
306                         parse_it = 1;
307                 }
308                 curbuf++;
309                 linelen++;
310         }
311
312         /* skip all endofline chars */
313         while (isendofline(buf[linelen])) {
314                 linelen++;
315         }
316
317         /* empty line */
318         if ( parse_it == 0 ) {
319                 debug_printf("Empty line (len=%d)\n", linelen);
320                 return linelen;
321         }
322
323 #ifdef RTE_LIBRTE_CMDLINE_DEBUG
324         snprintf(debug_buf, (linelen>64 ? 64 : linelen), "%s", buf);
325         debug_printf("Parse line : len=%d, <%s>\n", linelen, debug_buf);
326 #endif
327
328         /* parse it !! */
329         inst = ctx[inst_num];
330         dyn_tokens[0] = NULL;
331         while (inst) {
332                 debug_printf("INST %d\n", inst_num);
333
334                 /* fully parsed */
335                 tok = match_inst(inst, buf, 0, tmp_result.buf,
336                                  sizeof(tmp_result.buf), &dyn_tokens);
337
338                 if (tok > 0) /* we matched at least one token */
339                         err = CMDLINE_PARSE_BAD_ARGS;
340
341                 else if (!tok) {
342                         debug_printf("INST fully parsed\n");
343                         memcpy(&result, &tmp_result,
344                                sizeof(result));
345                         /* skip spaces */
346                         while (isblank2(*curbuf)) {
347                                 curbuf++;
348                         }
349
350                         /* if end of buf -> there is no garbage after inst */
351                         if (isendofline(*curbuf) || iscomment(*curbuf)) {
352                                 if (!f) {
353                                         memcpy(&f, &inst->f, sizeof(f));
354                                         memcpy(&data, &inst->data, sizeof(data));
355                                 }
356                                 else {
357                                         /* more than 1 inst matches */
358                                         err = CMDLINE_PARSE_AMBIGUOUS;
359                                         f=NULL;
360                                         debug_printf("Ambiguous cmd\n");
361                                         break;
362                                 }
363                         }
364                 }
365
366                 inst_num ++;
367                 inst = ctx[inst_num];
368                 dyn_tokens[0] = NULL;
369         }
370
371         /* call func */
372         if (f) {
373                 f(result.buf, cl, data);
374         }
375
376         /* no match */
377         else {
378                 debug_printf("No match err=%d\n", err);
379                 return err;
380         }
381
382         return linelen;
383 }
384
385 int
386 cmdline_complete(struct cmdline *cl, const char *buf, int *state,
387                  char *dst, unsigned int size)
388 {
389         const char *partial_tok = buf;
390         unsigned int inst_num = 0;
391         cmdline_parse_inst_t *inst;
392         cmdline_parse_token_hdr_t *token_p;
393         struct cmdline_token_hdr token_hdr;
394         char tmpbuf[CMDLINE_BUFFER_SIZE], comp_buf[CMDLINE_BUFFER_SIZE];
395         cmdline_parse_token_hdr_t *dyn_tokens[CMDLINE_PARSE_DYNAMIC_TOKENS];
396         unsigned int partial_tok_len;
397         int comp_len = -1;
398         int tmp_len = -1;
399         int nb_token = 0;
400         unsigned int i, n;
401         int l;
402         unsigned int nb_completable;
403         unsigned int nb_non_completable;
404         int local_state = 0;
405         const char *help_str;
406         cmdline_parse_ctx_t *ctx;
407
408         if (!cl || !buf || !state || !dst)
409                 return -1;
410
411         ctx = cl->ctx;
412
413         debug_printf("%s called\n", __func__);
414         memset(&token_hdr, 0, sizeof(token_hdr));
415
416         /* count the number of complete token to parse */
417         for (i=0 ; buf[i] ; i++) {
418                 if (!isblank2(buf[i]) && isblank2(buf[i+1]))
419                         nb_token++;
420                 if (isblank2(buf[i]) && !isblank2(buf[i+1]))
421                         partial_tok = buf+i+1;
422         }
423         partial_tok_len = strnlen(partial_tok, RDLINE_BUF_SIZE);
424
425         /* first call -> do a first pass */
426         if (*state <= 0) {
427                 debug_printf("try complete <%s>\n", buf);
428                 debug_printf("there is %d complete tokens, <%s> is incomplete\n",
429                              nb_token, partial_tok);
430
431                 nb_completable = 0;
432                 nb_non_completable = 0;
433
434                 inst = ctx[inst_num];
435                 dyn_tokens[0] = NULL;
436                 while (inst) {
437                         /* parse the first tokens of the inst */
438                         if (nb_token &&
439                             match_inst(inst, buf, nb_token, NULL, 0,
440                                        &dyn_tokens))
441                                 goto next;
442
443                         debug_printf("instruction match\n");
444                         token_p = get_token(inst, nb_token, &dyn_tokens);
445                         if (token_p)
446                                 memcpy(&token_hdr, token_p, sizeof(token_hdr));
447
448                         /* non completable */
449                         if (!token_p ||
450                             !token_hdr.ops->complete_get_nb ||
451                             !token_hdr.ops->complete_get_elt ||
452                             (n = token_hdr.ops->complete_get_nb(token_p)) == 0) {
453                                 nb_non_completable++;
454                                 goto next;
455                         }
456
457                         debug_printf("%d choices for this token\n", n);
458                         for (i=0 ; i<n ; i++) {
459                                 if (token_hdr.ops->complete_get_elt(token_p, i,
460                                                                     tmpbuf,
461                                                                     sizeof(tmpbuf)) < 0)
462                                         continue;
463
464                                 /* we have at least room for one char */
465                                 tmp_len = strnlen(tmpbuf, sizeof(tmpbuf));
466                                 if (tmp_len < CMDLINE_BUFFER_SIZE - 1) {
467                                         tmpbuf[tmp_len] = ' ';
468                                         tmpbuf[tmp_len+1] = 0;
469                                 }
470
471                                 debug_printf("   choice <%s>\n", tmpbuf);
472
473                                 /* does the completion match the
474                                  * beginning of the word ? */
475                                 if (!strncmp(partial_tok, tmpbuf,
476                                              partial_tok_len)) {
477                                         if (comp_len == -1) {
478                                                 snprintf(comp_buf, sizeof(comp_buf),
479                                                          "%s", tmpbuf + partial_tok_len);
480                                                 comp_len =
481                                                         strnlen(tmpbuf + partial_tok_len,
482                                                                         sizeof(tmpbuf) - partial_tok_len);
483
484                                         }
485                                         else {
486                                                 comp_len =
487                                                         nb_common_chars(comp_buf,
488                                                                         tmpbuf+partial_tok_len);
489                                                 comp_buf[comp_len] = 0;
490                                         }
491                                         nb_completable++;
492                                 }
493                         }
494                 next:
495                         debug_printf("next\n");
496                         inst_num ++;
497                         inst = ctx[inst_num];
498                         dyn_tokens[0] = NULL;
499                 }
500
501                 debug_printf("total choices %d for this completion\n",
502                              nb_completable);
503
504                 /* no possible completion */
505                 if (nb_completable == 0 && nb_non_completable == 0)
506                         return 0;
507
508                 /* if multichoice is not required */
509                 if (*state == 0 && partial_tok_len > 0) {
510                         /* one or several choices starting with the
511                            same chars */
512                         if (comp_len > 0) {
513                                 if ((unsigned)(comp_len + 1) > size)
514                                         return 0;
515
516                                 snprintf(dst, size, "%s", comp_buf);
517                                 dst[comp_len] = 0;
518                                 return 2;
519                         }
520                 }
521         }
522
523         /* init state correctly */
524         if (*state == -1)
525                 *state = 0;
526
527         debug_printf("Multiple choice STATE=%d\n", *state);
528
529         inst_num = 0;
530         inst = ctx[inst_num];
531         dyn_tokens[0] = NULL;
532         while (inst) {
533                 /* we need to redo it */
534                 inst = ctx[inst_num];
535
536                 if (nb_token &&
537                     match_inst(inst, buf, nb_token, NULL, 0, &dyn_tokens))
538                         goto next2;
539
540                 token_p = get_token(inst, nb_token, &dyn_tokens);
541                 if (token_p)
542                         memcpy(&token_hdr, token_p, sizeof(token_hdr));
543
544                 /* one choice for this token */
545                 if (!token_p ||
546                     !token_hdr.ops->complete_get_nb ||
547                     !token_hdr.ops->complete_get_elt ||
548                     (n = token_hdr.ops->complete_get_nb(token_p)) == 0) {
549                         if (local_state < *state) {
550                                 local_state++;
551                                 goto next2;
552                         }
553                         (*state)++;
554                         if (token_p && token_hdr.ops->get_help) {
555                                 token_hdr.ops->get_help(token_p, tmpbuf,
556                                                         sizeof(tmpbuf));
557                                 help_str = inst->help_str;
558                                 if (help_str)
559                                         snprintf(dst, size, "[%s]: %s", tmpbuf,
560                                                  help_str);
561                                 else
562                                         snprintf(dst, size, "[%s]: No help",
563                                                  tmpbuf);
564                         }
565                         else {
566                                 snprintf(dst, size, "[RETURN]");
567                         }
568                         return 1;
569                 }
570
571                 /* several choices */
572                 for (i=0 ; i<n ; i++) {
573                         if (token_hdr.ops->complete_get_elt(token_p, i, tmpbuf,
574                                                             sizeof(tmpbuf)) < 0)
575                                 continue;
576                         /* we have at least room for one char */
577                         tmp_len = strnlen(tmpbuf, sizeof(tmpbuf));
578                         if (tmp_len < CMDLINE_BUFFER_SIZE - 1) {
579                                 tmpbuf[tmp_len] = ' ';
580                                 tmpbuf[tmp_len + 1] = 0;
581                         }
582
583                         debug_printf("   choice <%s>\n", tmpbuf);
584
585                         /* does the completion match the beginning of
586                          * the word ? */
587                         if (!strncmp(partial_tok, tmpbuf,
588                                      partial_tok_len)) {
589                                 if (local_state < *state) {
590                                         local_state++;
591                                         continue;
592                                 }
593                                 (*state)++;
594                                 l=snprintf(dst, size, "%s", tmpbuf);
595                                 if (l>=0 && token_hdr.ops->get_help) {
596                                         token_hdr.ops->get_help(token_p, tmpbuf,
597                                                                 sizeof(tmpbuf));
598                                         help_str = inst->help_str;
599                                         if (help_str)
600                                                 snprintf(dst+l, size-l, "[%s]: %s",
601                                                          tmpbuf, help_str);
602                                         else
603                                                 snprintf(dst+l, size-l,
604                                                          "[%s]: No help", tmpbuf);
605                                 }
606
607                                 return 1;
608                         }
609                 }
610         next2:
611                 inst_num ++;
612                 inst = ctx[inst_num];
613                 dyn_tokens[0] = NULL;
614         }
615         return 0;
616 }