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