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