d5f5988437dcec6ce936d333be622ace0402a19c
[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
67 #include <netinet/in.h>
68
69 #include "cmdline_parse.h"
70 #include "cmdline.h"
71
72 //#define CMDLINE_DEBUG
73 //#define debug_printf printf
74 #define debug_printf(args...) do {} while(0)
75
76 /* isblank() needs _XOPEN_SOURCE >= 600 || _ISOC99_SOURCE, so use our
77  * own. */
78 static int
79 isblank2(char c)
80 {
81         if (c == ' ' ||
82             c == '\t' )
83                 return 1;
84         return 0;
85 }
86
87 static int
88 isendofline(char c)
89 {
90         if (c == '\n' ||
91             c == '\r' )
92                 return 1;
93         return 0;
94 }
95
96 static int
97 iscomment(char c)
98 {
99         if (c == '#')
100                 return 1;
101         return 0;
102 }
103
104 int
105 cmdline_isendoftoken(char c)
106 {
107         if (!c || iscomment(c) || isblank2(c) || isendofline(c))
108                 return 1;
109         return 0;
110 }
111
112 static unsigned int
113 nb_common_chars(const char * s1, const char * s2)
114 {
115         unsigned int i=0;
116
117         while (*s1==*s2 && *s1 && *s2) {
118                 s1++;
119                 s2++;
120                 i++;
121         }
122         return i;
123 }
124
125 /**
126  * try to match the buffer with an instruction (only the first
127  * nb_match_token tokens if != 0). Return 0 if we match all the
128  * tokens, else the number of matched tokens, else -1.
129  */
130 static int
131 match_inst(cmdline_parse_inst_t *inst, const char *buf, unsigned int nb_match_token,
132            void * result_buf)
133 {
134         unsigned int token_num=0;
135         cmdline_parse_token_hdr_t * token_p;
136         unsigned int i=0;
137         int n = 0;
138         struct cmdline_token_hdr token_hdr;
139
140         token_p = inst->tokens[token_num];
141         if (token_p)
142                 memcpy(&token_hdr, token_p, sizeof(token_hdr));
143
144         /* check if we match all tokens of inst */
145         while (token_p && (!nb_match_token || i<nb_match_token)) {
146                 debug_printf("TK\n");
147                 /* skip spaces */
148                 while (isblank2(*buf)) {
149                         buf++;
150                 }
151
152                 /* end of buf */
153                 if ( isendofline(*buf) || iscomment(*buf) )
154                         break;
155
156                 n = token_hdr.ops->parse(token_p, buf, (result_buf ? result_buf+token_hdr.offset : NULL));
157                 if ( n < 0 )
158                         break;
159                 debug_printf("TK parsed (len=%d)\n", n);
160                 i++;
161                 buf += n;
162
163                 token_num ++;
164                 token_p = inst->tokens[token_num];
165                 if (token_p)
166                         memcpy(&token_hdr, token_p, sizeof(token_hdr));
167         }
168
169         /* does not match */
170         if (i==0)
171                 return -1;
172
173         /* in case we want to match a specific num of token */
174         if (nb_match_token) {
175                 if (i == nb_match_token) {
176                         return 0;
177                 }
178                 return i;
179         }
180
181         /* we don't match all the tokens */
182         if (token_p) {
183                 return i;
184         }
185
186         /* are there are some tokens more */
187         while (isblank2(*buf)) {
188                 buf++;
189         }
190
191         /* end of buf */
192         if ( isendofline(*buf) || iscomment(*buf) )
193                 return 0;
194
195         /* garbage after inst */
196         return i;
197 }
198
199
200 int
201 cmdline_parse(struct cmdline *cl, const char * buf)
202 {
203         unsigned int inst_num=0;
204         cmdline_parse_inst_t *inst;
205         const char *curbuf;
206         char result_buf[BUFSIZ]; /* XXX align, size zé in broblém */
207         void (*f)(void *, struct cmdline *, void *) = NULL;
208         void *data = NULL;
209         int comment = 0;
210         int linelen = 0;
211         int parse_it = 0;
212         int err = CMDLINE_PARSE_NOMATCH;
213         int tok;
214         cmdline_parse_ctx_t *ctx = cl->ctx;
215 #ifdef CMDLINE_DEBUG
216         char debug_buf[BUFSIZ];
217 #endif
218
219         /*
220          * - look if the buffer contains at least one line
221          * - look if line contains only spaces or comments
222          * - count line length
223          */
224         curbuf = buf;
225         while (! isendofline(*curbuf)) {
226                 if ( *curbuf == '\0' ) {
227                         debug_printf("Incomplete buf (len=%d)\n", linelen);
228                         return 0;
229                 }
230                 if ( iscomment(*curbuf) ) {
231                         comment = 1;
232                 }
233                 if ( ! isblank2(*curbuf) && ! comment) {
234                         parse_it = 1;
235                 }
236                 curbuf++;
237                 linelen++;
238         }
239
240         /* skip all endofline chars */
241         while (isendofline(buf[linelen])) {
242                 linelen++;
243         }
244
245         /* empty line */
246         if ( parse_it == 0 ) {
247                 debug_printf("Empty line (len=%d)\n", linelen);
248                 return linelen;
249         }
250
251 #ifdef CMDLINE_DEBUG
252         snprintf(debug_buf, (linelen>64 ? 64 : linelen), "%s", buf);
253         debug_printf("Parse line : len=%d, <%s>\n", linelen, debug_buf);
254 #endif
255
256         /* parse it !! */
257         inst = ctx[inst_num];
258         while (inst) {
259                 debug_printf("INST %d\n", inst_num);
260
261                 /* fully parsed */
262                 tok = match_inst(inst, buf, 0, result_buf);
263
264                 if (tok > 0) /* we matched at least one token */
265                         err = CMDLINE_PARSE_BAD_ARGS;
266
267                 else if (!tok) {
268                         debug_printf("INST fully parsed\n");
269                         /* skip spaces */
270                         while (isblank2(*curbuf)) {
271                                 curbuf++;
272                         }
273
274                         /* if end of buf -> there is no garbage after inst */
275                         if (isendofline(*curbuf) || iscomment(*curbuf)) {
276                                 if (!f) {
277                                         memcpy(&f, &inst->f, sizeof(f));
278                                         memcpy(&data, &inst->data, sizeof(data));
279                                 }
280                                 else {
281                                         /* more than 1 inst matches */
282                                         err = CMDLINE_PARSE_AMBIGUOUS;
283                                         f=NULL;
284                                         debug_printf("Ambiguous cmd\n");
285                                         break;
286                                 }
287                         }
288                 }
289
290                 inst_num ++;
291                 inst = ctx[inst_num];
292         }
293
294         /* call func */
295         if (f) {
296                 f(result_buf, cl, data);
297         }
298
299         /* no match */
300         else {
301                 debug_printf("No match err=%d\n", err);
302                 return err;
303         }
304
305         return linelen;
306 }
307
308 int
309 cmdline_complete(struct cmdline *cl, const char *buf, int *state,
310                  char *dst, unsigned int size)
311 {
312         const char *incomplete_token = buf;
313         unsigned int inst_num = 0;
314         cmdline_parse_inst_t *inst;
315         cmdline_parse_token_hdr_t *token_p;
316         struct cmdline_token_hdr token_hdr;
317         char tmpbuf[64], completion_buf[64];
318         unsigned int incomplete_token_len;
319         int completion_len = -1;
320         int nb_token = 0;
321         unsigned int i, n;
322         int l;
323         unsigned int nb_completable;
324         unsigned int nb_non_completable;
325         int local_state = 0;
326         char *help_str;
327         cmdline_parse_ctx_t *ctx = cl->ctx;
328
329         debug_printf("%s called\n", __FUNCTION__);
330         memset(&token_hdr, 0, sizeof(token_hdr));
331
332         /* count the number of complete token to parse */
333         for (i=0 ; buf[i] ; i++) {
334                 if (!isblank2(buf[i]) && isblank2(buf[i+1]))
335                         nb_token++;
336                 if (isblank2(buf[i]) && !isblank2(buf[i+1]))
337                         incomplete_token = buf+i+1;
338         }
339         incomplete_token_len = strlen(incomplete_token);
340
341         /* first call -> do a first pass */
342         if (*state <= 0) {
343                 debug_printf("try complete <%s>\n", buf);
344                 debug_printf("there is %d complete tokens, <%s> is incomplete\n", nb_token, incomplete_token);
345
346                 nb_completable = 0;
347                 nb_non_completable = 0;
348
349                 inst = ctx[inst_num];
350                 while (inst) {
351                         /* parse the first tokens of the inst */
352                         if (nb_token && match_inst(inst, buf, nb_token, NULL))
353                                 goto next;
354
355                         debug_printf("instruction match \n");
356                         token_p = inst->tokens[nb_token];
357                         if (token_p)
358                                 memcpy(&token_hdr, token_p, sizeof(token_hdr));
359
360                         /* non completable */
361                         if (!token_p ||
362                             !token_hdr.ops->complete_get_nb ||
363                             !token_hdr.ops->complete_get_elt ||
364                             (n = token_hdr.ops->complete_get_nb(token_p)) == 0) {
365                                 nb_non_completable++;
366                                 goto next;
367                         }
368
369                         debug_printf("%d choices for this token\n", n);
370                         for (i=0 ; i<n ; i++) {
371                                 if (token_hdr.ops->complete_get_elt(token_p, i, tmpbuf, sizeof(tmpbuf)) < 0)
372                                         continue;
373                                 strcat(tmpbuf, " "); /* we have at least room for one char */
374                                 debug_printf("   choice <%s>\n", tmpbuf);
375                                 /* does the completion match the beginning of the word ? */
376                                 if (!strncmp(incomplete_token, tmpbuf, incomplete_token_len)) {
377                                         if (completion_len == -1) {
378                                                 strcpy(completion_buf, tmpbuf+incomplete_token_len);
379                                                 completion_len = strlen(tmpbuf+incomplete_token_len);
380
381                                         }
382                                         else {
383                                                 completion_len = nb_common_chars(completion_buf,
384                                                                                  tmpbuf+incomplete_token_len);
385                                                 completion_buf[completion_len] = 0;
386                                         }
387                                         nb_completable++;
388                                 }
389                         }
390                 next:
391                         inst_num ++;
392                         inst = ctx[inst_num];
393                 }
394
395                 debug_printf("total choices %d for this completion\n", nb_completable);
396
397                 /* no possible completion */
398                 if (nb_completable == 0 && nb_non_completable == 0)
399                         return 0;
400
401                 /* if multichoice is not required */
402                 if (*state == 0 && incomplete_token_len > 0) {
403                         /* one or several choices starting with the
404                            same chars */
405                         if (completion_len > 0) {
406                                 if ((unsigned)(completion_len + 1) > size)
407                                         return 0;
408
409                                 strcpy(dst, completion_buf);
410                                 return 2;
411                         }
412                 }
413         }
414
415         /* init state correctly */
416         if (*state == -1)
417                 *state = 0;
418
419         debug_printf("Multiple choice STATE=%d\n", *state);
420
421         inst_num = 0;
422         inst = ctx[inst_num];
423         while (inst) {
424                 /* we need to redo it */
425                 inst = ctx[inst_num];
426
427                 if (nb_token && match_inst(inst, buf, nb_token, NULL))
428                         goto next2;
429
430                 token_p = inst->tokens[nb_token];
431                 if (token_p)
432                         memcpy(&token_hdr, token_p, sizeof(token_hdr));
433
434                 /* one choice for this token */
435                 if (!token_p ||
436                     !token_hdr.ops->complete_get_nb ||
437                     !token_hdr.ops->complete_get_elt ||
438                     (n = token_hdr.ops->complete_get_nb(token_p)) == 0) {
439                         if (local_state < *state) {
440                                 local_state++;
441                                 goto next2;
442                         }
443                         (*state)++;
444                         if (token_p && token_hdr.ops->get_help) {
445                                 token_hdr.ops->get_help(token_p, tmpbuf, sizeof(tmpbuf));
446                                 help_str = inst->help_str;
447                                 if (help_str)
448                                         snprintf(dst, size, "[%s]: %s", tmpbuf, help_str);
449                                 else
450                                         snprintf(dst, size, "[%s]: No help", tmpbuf);
451                         }
452                         else {
453                                 snprintf(dst, size, "[RETURN]");
454                         }
455                         return 1;
456                 }
457
458                 /* several choices */
459                 for (i=0 ; i<n ; i++) {
460                         if (token_hdr.ops->complete_get_elt(token_p, i, tmpbuf, sizeof(tmpbuf)) < 0)
461                                 continue;
462                         strcat(tmpbuf, " "); /* we have at least room for one char */
463                         debug_printf("   choice <%s>\n", tmpbuf);
464                         /* does the completion match the beginning of the word ? */
465                         if (!strncmp(incomplete_token, tmpbuf, incomplete_token_len)) {
466                                 if (local_state < *state) {
467                                         local_state++;
468                                         continue;
469                                 }
470                                 (*state)++;
471                                 l=snprintf(dst, size, "%s", tmpbuf);
472                                 if (l>=0 && token_hdr.ops->get_help) {
473                                         token_hdr.ops->get_help(token_p, tmpbuf, sizeof(tmpbuf));
474                                         help_str = inst->help_str;
475                                         if (help_str)
476                                                 snprintf(dst+l, size-l, "[%s]: %s", tmpbuf, help_str);
477                                         else
478                                                 snprintf(dst+l, size-l, "[%s]: No help", tmpbuf);
479                                 }
480
481                                 return 1;
482                         }
483                 }
484         next2:
485                 inst_num ++;
486                 inst = ctx[inst_num];
487         }
488         return 0;
489 }
490