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