cmdline: check size of result buffer to avoid overflow
[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 *resbuf, unsigned resbuf_size)
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 (resbuf == NULL)
235                         res = token_hdr.ops->parse(token_p, token_str, NULL, 0);
236                 else {
237                         unsigned rb_sz;
238                         void *rb = (char *)resbuf + token_hdr.offset;
239                         if (token_hdr.offset > resbuf_size)
240                                 return -ENOBUFS;
241                         rb_sz = resbuf_size - token_hdr.offset;
242                         res = token_hdr.ops->parse(token_p, token_str,
243                                                    rb, rb_sz);
244                 }
245
246                 if (res < 0)
247                         break;
248
249                 debug_printf("TK parsed (len=%d)\n", n);
250                 i++;
251                 buf += n;
252
253                 token_num ++;
254                 token_p = inst->tokens[token_num];
255                 if (token_p)
256                         memcpy(&token_hdr, token_p, sizeof(token_hdr));
257         }
258
259         /* does not match */
260         if (i==0)
261                 return -ENOENT;
262
263         /* in case we want to match a specific num of token */
264         if (nb_match_token) {
265                 if (i == nb_match_token) {
266                         return 0;
267                 }
268                 return i;
269         }
270
271         /* we don't match all the tokens */
272         if (token_p) {
273                 return i;
274         }
275
276         /* are there are some tokens more */
277         while (isblank2(*buf)) {
278                 buf++;
279         }
280
281         /* end of buf */
282         if ( isendofline(*buf) || iscomment(*buf) )
283                 return 0;
284
285         /* garbage after inst */
286         return i;
287 }
288
289
290 int
291 cmdline_parse(struct cmdline *cl, const char * buf)
292 {
293         unsigned int inst_num=0;
294         cmdline_parse_inst_t *inst;
295         const char *curbuf;
296         char result_buf[CMDLINE_MAX_DSTBUF_SIZE];
297         void (*f)(void *, struct cmdline *, void *) = NULL;
298         void *data = NULL;
299         int comment = 0;
300         int linelen = 0;
301         int parse_it = 0;
302         int err = CMDLINE_PARSE_NOMATCH;
303         int tok;
304         cmdline_parse_ctx_t *ctx = cl->ctx;
305 #ifdef CMDLINE_DEBUG
306         char debug_buf[BUFSIZ];
307 #endif
308
309         /*
310          * - look if the buffer contains at least one line
311          * - look if line contains only spaces or comments
312          * - count line length
313          */
314         curbuf = buf;
315         while (! isendofline(*curbuf)) {
316                 if ( *curbuf == '\0' ) {
317                         debug_printf("Incomplete buf (len=%d)\n", linelen);
318                         return 0;
319                 }
320                 if ( iscomment(*curbuf) ) {
321                         comment = 1;
322                 }
323                 if ( ! isblank2(*curbuf) && ! comment) {
324                         parse_it = 1;
325                 }
326                 curbuf++;
327                 linelen++;
328         }
329
330         /* skip all endofline chars */
331         while (isendofline(buf[linelen])) {
332                 linelen++;
333         }
334
335         /* empty line */
336         if ( parse_it == 0 ) {
337                 debug_printf("Empty line (len=%d)\n", linelen);
338                 return linelen;
339         }
340
341 #ifdef CMDLINE_DEBUG
342         snprintf(debug_buf, (linelen>64 ? 64 : linelen), "%s", buf);
343         debug_printf("Parse line : len=%d, <%s>\n", linelen, debug_buf);
344 #endif
345
346         /* parse it !! */
347         inst = ctx[inst_num];
348         while (inst) {
349                 debug_printf("INST %d\n", inst_num);
350
351                 /* fully parsed */
352                 tok = match_inst(inst, buf, 0, result_buf, sizeof(result_buf));
353
354                 if (tok > 0) /* we matched at least one token */
355                         err = CMDLINE_PARSE_BAD_ARGS;
356
357                 else if (!tok) {
358                         debug_printf("INST fully parsed\n");
359                         /* skip spaces */
360                         while (isblank2(*curbuf)) {
361                                 curbuf++;
362                         }
363
364                         /* if end of buf -> there is no garbage after inst */
365                         if (isendofline(*curbuf) || iscomment(*curbuf)) {
366                                 if (!f) {
367                                         memcpy(&f, &inst->f, sizeof(f));
368                                         memcpy(&data, &inst->data, sizeof(data));
369                                 }
370                                 else {
371                                         /* more than 1 inst matches */
372                                         err = CMDLINE_PARSE_AMBIGUOUS;
373                                         f=NULL;
374                                         debug_printf("Ambiguous cmd\n");
375                                         break;
376                                 }
377                         }
378                 }
379                 else if (tok == -EINVAL) {
380                         err = CMDLINE_PARSE_UNTERMINATED_QUOTE;
381                         f = NULL;
382                         debug_printf("Unterminated quote\n");
383                         break;
384                 }
385
386                 inst_num ++;
387                 inst = ctx[inst_num];
388         }
389
390         /* call func */
391         if (f) {
392                 f(result_buf, cl, data);
393         }
394
395         /* no match */
396         else {
397                 debug_printf("No match err=%d\n", err);
398                 return err;
399         }
400
401         return linelen;
402 }
403
404 int
405 cmdline_complete(struct cmdline *cl, const char *buf, int *state,
406                  char *dst, unsigned int size)
407 {
408         const char *partial_tok = buf;
409         unsigned int inst_num = 0;
410         cmdline_parse_inst_t *inst;
411         cmdline_parse_token_hdr_t *token_p;
412         struct cmdline_token_hdr token_hdr;
413         char tmpbuf[64], comp_buf[64];
414         unsigned int partial_tok_len;
415         int comp_len = -1;
416         int nb_token = 0;
417         unsigned int i, n;
418         int l;
419         unsigned int nb_completable;
420         unsigned int nb_non_completable;
421         int local_state = 0;
422         char *help_str;
423         cmdline_parse_ctx_t *ctx = cl->ctx;
424
425         debug_printf("%s called\n", __FUNCTION__);
426         memset(&token_hdr, 0, sizeof(token_hdr));
427
428         /* count the number of complete token to parse */
429         for (i=0 ; buf[i] ; i++) {
430                 if (!isblank2(buf[i]) && isblank2(buf[i+1]))
431                         nb_token++;
432                 if (isblank2(buf[i]) && !isblank2(buf[i+1]))
433                         partial_tok = buf+i+1;
434         }
435         partial_tok_len = strlen(partial_tok);
436
437         /* first call -> do a first pass */
438         if (*state <= 0) {
439                 debug_printf("try complete <%s>\n", buf);
440                 debug_printf("there is %d complete tokens, <%s> is incomplete\n",
441                              nb_token, partial_tok);
442
443                 nb_completable = 0;
444                 nb_non_completable = 0;
445
446                 inst = ctx[inst_num];
447                 while (inst) {
448                         /* parse the first tokens of the inst */
449                         if (nb_token && match_inst(inst, buf, nb_token, NULL, 0))
450                                 goto next;
451
452                         debug_printf("instruction match \n");
453                         token_p = inst->tokens[nb_token];
454                         if (token_p)
455                                 memcpy(&token_hdr, token_p, sizeof(token_hdr));
456
457                         /* non completable */
458                         if (!token_p ||
459                             !token_hdr.ops->complete_get_nb ||
460                             !token_hdr.ops->complete_get_elt ||
461                             (n = token_hdr.ops->complete_get_nb(token_p)) == 0) {
462                                 nb_non_completable++;
463                                 goto next;
464                         }
465
466                         debug_printf("%d choices for this token\n", n);
467                         for (i=0 ; i<n ; i++) {
468                                 if (token_hdr.ops->complete_get_elt(token_p, i,
469                                                                     tmpbuf,
470                                                                     sizeof(tmpbuf)) < 0)
471                                         continue;
472
473                                 /* we have at least room for one char */
474                                 strcat(tmpbuf, " ");
475
476                                 debug_printf("   choice <%s>\n", tmpbuf);
477
478                                 /* does the completion match the
479                                  * beginning of the word ? */
480                                 if (!strncmp(partial_tok, tmpbuf,
481                                              partial_tok_len)) {
482                                         if (comp_len == -1) {
483                                                 strcpy(comp_buf,
484                                                        tmpbuf + partial_tok_len);
485                                                 comp_len =
486                                                         strlen(tmpbuf +
487                                                                partial_tok_len);
488
489                                         }
490                                         else {
491                                                 comp_len =
492                                                         nb_common_chars(comp_buf,
493                                                                         tmpbuf+partial_tok_len);
494                                                 comp_buf[comp_len] = 0;
495                                         }
496                                         nb_completable++;
497                                 }
498                         }
499                 next:
500                         inst_num ++;
501                         inst = ctx[inst_num];
502                 }
503
504                 debug_printf("total choices %d for this completion\n",
505                              nb_completable);
506
507                 /* no possible completion */
508                 if (nb_completable == 0 && nb_non_completable == 0)
509                         return 0;
510
511                 /* if multichoice is not required */
512                 if (*state == 0 && partial_tok_len > 0) {
513                         /* one or several choices starting with the
514                            same chars */
515                         if (comp_len > 0) {
516                                 if ((unsigned)(comp_len + 1) > size)
517                                         return 0;
518
519                                 strcpy(dst, comp_buf);
520                                 return 2;
521                         }
522                 }
523         }
524
525         /* init state correctly */
526         if (*state == -1)
527                 *state = 0;
528
529         debug_printf("Multiple choice STATE=%d\n", *state);
530
531         inst_num = 0;
532         inst = ctx[inst_num];
533         while (inst) {
534                 /* we need to redo it */
535                 inst = ctx[inst_num];
536
537                 if (nb_token && match_inst(inst, buf, nb_token, NULL, 0))
538                         goto next2;
539
540                 token_p = inst->tokens[nb_token];
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                         strcat(tmpbuf, " ");
578
579                         debug_printf("   choice <%s>\n", tmpbuf);
580
581                         /* does the completion match the beginning of
582                          * the word ? */
583                         if (!strncmp(partial_tok, tmpbuf,
584                                      partial_tok_len)) {
585                                 if (local_state < *state) {
586                                         local_state++;
587                                         continue;
588                                 }
589                                 (*state)++;
590                                 l=snprintf(dst, size, "%s", tmpbuf);
591                                 if (l>=0 && token_hdr.ops->get_help) {
592                                         token_hdr.ops->get_help(token_p, tmpbuf,
593                                                                 sizeof(tmpbuf));
594                                         help_str = inst->help_str;
595                                         if (help_str)
596                                                 snprintf(dst+l, size-l, "[%s]: %s",
597                                                          tmpbuf, help_str);
598                                         else
599                                                 snprintf(dst+l, size-l,
600                                                          "[%s]: No help", tmpbuf);
601                                 }
602
603                                 return 1;
604                         }
605                 }
606         next2:
607                 inst_num ++;
608                 inst = ctx[inst_num];
609         }
610         return 0;
611 }
612