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