Whamcloud - gitweb
LU-6025 utils: reset optind before calls to getopt_long()
[fs/lustre-release.git] / libcfs / libcfs / util / parser.c
1 /*
2  * Copyright (C) 2001 Cluster File Systems, Inc.
3  *
4  * Copyright (c) 2014, Intel Corporation.
5  *
6  *   This file is part of Lustre, http://www.sf.net/projects/lustre/
7  *
8  *   Lustre is free software; you can redistribute it and/or
9  *   modify it under the terms of version 2 of the GNU General Public
10  *   License as published by the Free Software Foundation.
11  *
12  *   Lustre is distributed in the hope that it will be useful,
13  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  *   GNU General Public License for more details.
16  *
17  *   You should have received a copy of the GNU General Public License
18  *   along with Lustre; if not, write to the Free Software
19  *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20  *
21  */
22
23 #include <lustre_ver.h>
24 #include <libcfs/libcfsutil.h>
25
26 static command_t * top_level;           /* Top level of commands, initialized by
27                                     * InitParser                              */
28 static char * parser_prompt = NULL;/* Parser prompt, set by InitParser      */
29 static int done;                   /* Set to 1 if user types exit or quit   */
30 static int ignore_errors;       /* Normally, the parser will quit when
31                                    an error occurs in non-interacive
32                                    mode. Setting this to non-zero will
33                                    force it to keep buggering on. */
34
35
36 /* static functions */
37 static char *skipwhitespace(char *s);
38 static char *skiptowhitespace(char *s);
39 static command_t *find_cmd(char *name, command_t cmds[], char **next);
40 static int process(char *s, char **next, command_t *lookup, command_t **result,
41                    char **prev);
42 static void print_commands(char *str, command_t *table);
43
44 static char * skipwhitespace(char * s)
45 {
46         char * t;
47         int    len;
48
49         len = (int)strlen(s);
50         for (t = s; t <= s + len && isspace(*t); t++);
51         return(t);
52 }
53
54
55 static char * skiptowhitespace(char * s)
56 {
57         char * t;
58
59         for (t = s; *t && !isspace(*t); t++);
60         return(t);
61 }
62
63 static int line2args(char *line, char **argv, int maxargs)
64 {
65         char *arg;
66         int i = 0;
67
68         arg = strtok(line, " \t");
69         if (arg == NULL || maxargs < 1)
70                 return 0;
71
72         argv[i++] = arg;
73         while ((arg = strtok(NULL, " \t")) != NULL && i < maxargs)
74                 argv[i++] = arg;
75         return i;
76 }
77
78 /* find a command -- return it if unique otherwise print alternatives */
79 static command_t *Parser_findargcmd(char *name, command_t cmds[])
80 {
81         command_t *cmd;
82
83         for (cmd = cmds; cmd->pc_name; cmd++) {
84                 if (strcmp(name, cmd->pc_name) == 0)
85                         return cmd;
86         }
87         return NULL;
88 }
89
90 void Parser_ignore_errors(int ignore)
91 {
92         ignore_errors = ignore;
93 }
94
95 int Parser_execarg(int argc, char **argv, command_t cmds[])
96 {
97         command_t *cmd;
98
99         cmd = Parser_findargcmd(argv[0], cmds);
100         if ( cmd ) {
101                 int rc = (cmd->pc_func)(argc, argv);
102                 if (rc == CMD_HELP)
103                         fprintf(stderr, "%s\n", cmd->pc_help);
104                 return rc;
105         } else {
106                 printf("Try interactive use without arguments or use one of:\n");
107                 for (cmd = cmds; cmd->pc_name; cmd++)
108                         printf("\"%s\"\n", cmd->pc_name);
109                 printf("as argument.\n");
110         }
111         return -1;
112 }
113
114 /* returns the command_t * (NULL if not found) corresponding to a
115    _partial_ match with the first token in name.  It sets *next to
116    point to the following token. Does not modify *name. */
117 static command_t * find_cmd(char * name, command_t cmds[], char ** next)
118 {
119         int    i, len;
120
121         if (!cmds || !name )
122                 return NULL;
123
124         /* This sets name to point to the first non-white space character,
125            and next to the first whitespace after name, len to the length: do
126            this with strtok*/
127         name = skipwhitespace(name);
128         *next = skiptowhitespace(name);
129         len = (int)(*next - name);
130         if (len == 0)
131                 return NULL;
132
133         for (i = 0; cmds[i].pc_name; i++) {
134                 if (strncasecmp(name, cmds[i].pc_name, len) == 0) {
135                         *next = skipwhitespace(*next);
136                         return(&cmds[i]);
137                 }
138         }
139         return NULL;
140 }
141
142 /* Recursively process a command line string s and find the command
143    corresponding to it. This can be ambiguous, full, incomplete,
144    non-existent. */
145 static int process(char *s, char ** next, command_t *lookup,
146                    command_t **result, char **prev)
147 {
148         *result = find_cmd(s, lookup, next);
149         *prev = s;
150
151         /* non existent */
152         if (!*result)
153                 return CMD_NONE;
154
155         /* found entry: is it ambigous, i.e. not exact command name and
156            more than one command in the list matches.  Note that find_cmd
157            points to the first ambiguous entry */
158         if (strncasecmp(s, (*result)->pc_name, strlen((*result)->pc_name))) {
159                 char *another_next;
160                 command_t *another_result = find_cmd(s, (*result) + 1,
161                                                      &another_next);
162                 int found_another = 0;
163
164                 while (another_result) {
165                         if (strncasecmp(s, another_result->pc_name,
166                                         strlen(another_result->pc_name)) == 0){
167                                 *result = another_result;
168                                 *next = another_next;
169                                 goto got_it;
170                         }
171                         another_result = find_cmd(s, another_result + 1,
172                                                   &another_next);
173                         found_another = 1;
174                 }
175                 if (found_another)
176                         return CMD_AMBIG;
177         }
178
179 got_it:
180         /* found a unique command: component or full? */
181         if ( (*result)->pc_func ) {
182                 return CMD_COMPLETE;
183         } else {
184                 if ( *next == '\0' ) {
185                         return CMD_INCOMPLETE;
186                 } else {
187                         return process(*next, next, (*result)->pc_sub_cmd,
188                                        result, prev);
189                 }
190         }
191 }
192
193 #ifdef HAVE_LIBREADLINE
194 static command_t * match_tbl;   /* Command completion against this table */
195 static char * command_generator(const char * text, int state)
196 {
197         static int index,
198                 len;
199         char       *name;
200
201         /* Do we have a match table? */
202         if (!match_tbl)
203                 return NULL;
204
205         /* If this is the first time called on this word, state is 0 */
206         if (!state) {
207                 index = 0;
208                 len = (int)strlen(text);
209         }
210
211         /* Return next name in the command list that paritally matches test */
212         while ( (name = (match_tbl + index)->pc_name) ) {
213                 index++;
214
215                 if (strncasecmp(name, text, len) == 0) {
216                         return(strdup(name));
217                 }
218         }
219
220         /* No more matches */
221         return NULL;
222 }
223
224 /* probably called by readline */
225 static char **command_completion(const char *text, int start, int end)
226 {
227         command_t   * table;
228         char        * pos;
229
230         match_tbl = top_level;
231         
232         for (table = find_cmd(rl_line_buffer, match_tbl, &pos);
233              table; table = find_cmd(pos, match_tbl, &pos)) 
234         {
235
236                 if (*(pos - 1) == ' ') match_tbl = table->pc_sub_cmd;
237         }
238
239         return completion_matches(text, command_generator);
240 }
241 #endif
242
243 /* take a string and execute the function or print help */
244 int execute_line(char * line)
245 {
246         command_t       *cmd, *ambig;
247         char            *prev;
248         char            *next, *tmp;
249         char            *argv[MAXARGS];
250         int             i;
251         int             rc = 0;
252
253         switch (process(line, &next, top_level, &cmd, &prev)) {
254         case CMD_AMBIG:
255                 fprintf(stderr, "Ambiguous command \'%s\'\nOptions: ", line);
256                 while ((ambig = find_cmd(prev, cmd, &tmp))) {
257                         fprintf(stderr, "%s ", ambig->pc_name);
258                         cmd = ambig + 1;
259                 }
260                 fprintf(stderr, "\n");
261                 break;
262         case CMD_NONE:
263                 fprintf(stderr, "No such command, type help\n");
264                 break;
265         case CMD_INCOMPLETE:
266                 fprintf(stderr, "'%s' incomplete command.  Use '%s x' where "
267                         "x is one of:\n", line, line);
268                 fprintf(stderr, "\t");
269                 for (i = 0; cmd->pc_sub_cmd[i].pc_name; i++)
270                         fprintf(stderr, "%s ", cmd->pc_sub_cmd[i].pc_name);
271                 fprintf(stderr, "\n");
272                 break;
273         case CMD_COMPLETE:
274                 optind = 0;
275                 i = line2args(line, argv, MAXARGS);
276                 rc = (cmd->pc_func)(i, argv);
277
278                 if (rc == CMD_HELP)
279                         fprintf(stderr, "%s\n", cmd->pc_help);
280
281                 break;
282         }
283
284         return rc;
285 }
286
287 #ifdef HAVE_LIBREADLINE
288 static void noop_int_fn(int unused) { }
289 static void noop_void_fn(void) { }
290 #endif
291
292 /* just in case you're ever in an airplane and discover you
293  * forgot to install readline-dev. :) */
294 static int init_input(void)
295 {
296         int interactive = isatty(fileno(stdin));
297
298 #ifdef HAVE_LIBREADLINE
299         using_history();
300         stifle_history(HISTORY);
301
302         if (!interactive) {
303                 rl_prep_term_function = noop_int_fn;
304                 rl_deprep_term_function = noop_void_fn;
305         }
306
307         rl_attempted_completion_function = command_completion;
308         rl_completion_entry_function = command_generator;
309 #endif
310         return interactive;
311 }
312
313 #ifndef HAVE_LIBREADLINE
314 #define add_history(s)
315 char * readline(char * prompt)
316 {
317         int size = 2048;
318         char *line = malloc(size);
319         char *ptr = line;
320         int c;
321         int eof = 0;
322
323         if (line == NULL)
324                 return NULL;
325         if (prompt)
326                 printf ("%s", prompt);
327
328         while (1) {
329                 if ((c = fgetc(stdin)) != EOF) {
330                         if (c == '\n')
331                                 goto out;
332                         *ptr++ = (char)c;
333
334                         if (ptr - line >= size - 1) {
335                                 char *tmp;
336
337                                 size *= 2;
338                                 tmp = malloc(size);
339                                 if (tmp == NULL)
340                                         goto outfree;
341                                 memcpy(tmp, line, ptr - line);
342                                 ptr = tmp + (ptr - line);
343                                 free(line);
344                                 line = tmp;
345                         }
346                 } else {
347                         eof = 1;
348                         if (ferror(stdin) || feof(stdin))
349                                 goto outfree;
350                         goto out;
351                 }
352         }
353 out:
354         *ptr = 0;
355         if (eof && (strlen(line) == 0)) {
356                 free(line);
357                 line = NULL;
358         }
359         return line;
360 outfree:
361         free(line);
362         return NULL;
363 }
364 #endif
365
366 /* this is the command execution machine */
367 int Parser_commands(void)
368 {
369         char *line, *s;
370         int rc = 0, save_error = 0;
371         int interactive;
372
373         interactive = init_input();
374
375         while(!done) {
376                 line = readline(interactive ? parser_prompt : NULL);
377
378                 if (!line) break;
379
380                 s = skipwhitespace(line);
381
382                 if (*s) {
383                         add_history(s);
384                         rc = execute_line(s);
385                 }
386                 /* stop on error if not-interactive */
387                 if (rc != 0 && !interactive) {
388                         if (save_error == 0)
389                                 save_error = rc;
390                         if (!ignore_errors)
391                                 done = 1;
392                 }
393
394                 free(line);
395         }
396         if (save_error)
397                 rc = save_error;
398         return rc;
399 }
400
401
402 /* sets the parser prompt */
403 void Parser_init(char * prompt, command_t * cmds)
404 {
405         done = 0;
406         top_level = cmds;
407         if (parser_prompt) free(parser_prompt);
408         parser_prompt = strdup(prompt);
409 }
410
411 /* frees the parser prompt */
412 void Parser_exit(int argc, char *argv[])
413 {
414         done = 1;
415         free(parser_prompt);
416         parser_prompt = NULL;
417 }
418
419 /* convert a string to an integer */
420 int Parser_int(char *s, int *val)
421 {
422         int ret;
423
424         if (*s != '0')
425                 ret = sscanf(s, "%d", val);
426         else if (*(s+1) != 'x')
427                 ret = sscanf(s, "%o", val);
428         else {
429                 s++;
430                 ret = sscanf(++s, "%x", val);
431         }
432
433         return(ret);
434 }
435
436
437 void Parser_qhelp(int argc, char *argv[]) {
438
439         printf("Available commands are:\n");
440
441         print_commands(NULL, top_level);
442         printf("For more help type: help command-name\n");
443 }
444
445 int Parser_help(int argc, char **argv)
446 {
447         char line[1024];
448         char *next, *prev, *tmp;
449         command_t *result, *ambig;
450         int i;
451
452         if ( argc == 1 ) {
453                 Parser_qhelp(argc, argv);
454                 return 0;
455         }
456
457         /* Joining command line arguments without space is not critical here
458          * because of this string is used for search a help topic and assume
459          * that only one argument will be (the name of topic). For example:
460          * lst > help ping run
461          * pingrun: Unknown command. */
462         line[0] = '\0';
463         for (i = 1;  i < argc; i++) {
464                 if (strlen(argv[i]) >= sizeof(line) - strlen(line))
465                         return -E2BIG;
466                 /* The function strlcat() cannot be used here because of
467                  * this function is used in LNet utils that is not linked
468                  * with libcfs.a. */
469                 strncat(line, argv[i], sizeof(line) - strlen(line));
470         }
471
472         switch ( process(line, &next, top_level, &result, &prev) ) {
473         case CMD_COMPLETE:
474                 fprintf(stderr, "%s: %s\n",line, result->pc_help);
475                 break;
476         case CMD_NONE:
477                 fprintf(stderr, "%s: Unknown command.\n", line);
478                 break;
479         case CMD_INCOMPLETE:
480                 fprintf(stderr,
481                         "'%s' incomplete command.  Use '%s x' where x is one of:\n",
482                         line, line);
483                 fprintf(stderr, "\t");
484                 for (i = 0; result->pc_sub_cmd[i].pc_name; i++) {
485                         fprintf(stderr, "%s ", result->pc_sub_cmd[i].pc_name);
486                 }
487                 fprintf(stderr, "\n");
488                 break;
489         case CMD_AMBIG:
490                 fprintf(stderr, "Ambiguous command \'%s\'\nOptions: ", line);
491                 while( (ambig = find_cmd(prev, result, &tmp)) ) {
492                         fprintf(stderr, "%s ", ambig->pc_name);
493                         result = ambig + 1;
494                 }
495                 fprintf(stderr, "\n");
496                 break;
497         }
498         return 0;
499 }
500
501
502 void Parser_printhelp(char *cmd)
503 {
504         char *argv[] = { "help", cmd };
505         Parser_help(2, argv);
506 }
507
508
509 /*************************************************************************
510  * COMMANDS                                                              *
511  *************************************************************************/
512 static void print_commands(char * str, command_t * table) {
513         command_t * cmds;
514         char         buf[80];
515
516         for (cmds = table; cmds->pc_name; cmds++) {
517                 if (cmds->pc_func) {
518                         if (str) printf("\t%s %s\n", str, cmds->pc_name);
519                         else printf("\t%s\n", cmds->pc_name);
520                 }
521                 if (cmds->pc_sub_cmd) {
522                         if (str) {
523                                 sprintf(buf, "%s %s", str, cmds->pc_name);
524                                 print_commands(buf, cmds->pc_sub_cmd);
525                         } else {
526                                 print_commands(cmds->pc_name, cmds->pc_sub_cmd);
527                         }
528                 }
529         }
530 }
531
532 char *Parser_getstr(const char *prompt, const char *deft, char *res,
533                     size_t len)
534 {
535         char *line = NULL;
536         int size = strlen(prompt) + strlen(deft) + 8;
537         char *theprompt;
538         theprompt = malloc(size);
539         assert(theprompt);
540
541         sprintf(theprompt, "%s [%s]: ", prompt, deft);
542
543         line  = readline(theprompt);
544         free(theprompt);
545
546         /* The function strlcpy() cannot be used here because of
547          * this function is used in LNet utils that is not linked
548          * with libcfs.a. */
549         if (line == NULL || *line == '\0')
550                 strncpy(res, deft, len);
551         else
552                 strncpy(res, line, len);
553         res[len - 1] = '\0';
554
555         if (line != NULL) {
556                 free(line);
557                 return res;
558         }
559         return NULL;
560 }
561
562 /* get integer from prompt, loop forever to get it */
563 int Parser_getint(const char *prompt, long min, long max, long deft, int base)
564 {
565         int rc;
566         long result;
567         char *line;
568         int size = strlen(prompt) + 40;
569         char *theprompt = malloc(size);
570         assert(theprompt);
571         sprintf(theprompt,"%s [%ld, (0x%lx)]: ", prompt, deft, deft);
572
573         fflush(stdout);
574
575         do {
576                 line = NULL;
577                 line = readline(theprompt);
578                 if ( !line ) {
579                         fprintf(stdout, "Please enter an integer.\n");
580                         fflush(stdout);
581                         continue;
582                 }
583                 if ( *line == '\0' ) {
584                         free(line);
585                         result =  deft;
586                         break;
587                 }
588                 rc = Parser_arg2int(line, &result, base);
589                 free(line);
590                 if ( rc != 0 ) {
591                         fprintf(stdout, "Invalid string.\n");
592                         fflush(stdout);
593                 } else if ( result > max || result < min ) {
594                         fprintf(stdout, "Error: response must lie between %ld and %ld.\n",
595                                 min, max);
596                         fflush(stdout);
597                 } else {
598                         break;
599                 }
600         } while ( 1 ) ;
601
602         if (theprompt)
603                 free(theprompt);
604         return result;
605
606 }
607
608 /* get boolean (starting with YyNn; loop forever */
609 int Parser_getbool(const char *prompt, int deft)
610 {
611         int result = 0;
612         char *line;
613         int size = strlen(prompt) + 8;
614         char *theprompt = malloc(size);
615         assert(theprompt);
616
617         fflush(stdout);
618
619         if ( deft != 0 && deft != 1 ) {
620                 fprintf(stderr, "Error: Parser_getbool given bad default %d\n",
621                         deft);
622                 assert ( 0 );
623         }
624         sprintf(theprompt, "%s [%s]: ", prompt, (deft==0)? "N" : "Y");
625
626         do {
627                 line = NULL;
628                 line = readline(theprompt);
629                 if ( line == NULL ) {
630                         result = deft;
631                         break;
632                 }
633                 if ( *line == '\0' ) {
634                         result = deft;
635                         break;
636                 }
637                 if ( *line == 'y' || *line == 'Y' ) {
638                         result = 1;
639                         break;
640                 }
641                 if ( *line == 'n' || *line == 'N' ) {
642                         result = 0;
643                         break;
644                 }
645                 if ( line )
646                         free(line);
647                 fprintf(stdout, "Invalid string. Must start with yY or nN\n");
648                 fflush(stdout);
649         } while ( 1 );
650
651         if ( line )
652                 free(line);
653         if ( theprompt )
654                 free(theprompt);
655         return result;
656 }
657
658 /* parse int out of a string or prompt for it */
659 long Parser_intarg(const char *inp, const char *prompt, int deft,
660                    int min, int max, int base)
661 {
662         long result;
663         int rc;
664
665         rc = Parser_arg2int(inp, &result, base);
666
667         if ( rc == 0 ) {
668                 return result;
669         } else {
670                 return Parser_getint(prompt, deft, min, max, base);
671         }
672 }
673
674 /* parse int out of a string or prompt for it */
675 char *Parser_strarg(char *inp, const char *prompt, const char *deft,
676                     char *answer, int len)
677 {
678         if ( inp == NULL || *inp == '\0' ) {
679                 return Parser_getstr(prompt, deft, answer, len);
680         } else
681                 return inp;
682 }
683
684 /* change a string into a number: return 0 on success. No invalid characters
685    allowed. The processing of base and validity follows strtol(3)*/
686 int Parser_arg2int(const char *inp, long *result, int base)
687 {
688         char *endptr;
689
690         if ( (base !=0) && (base < 2 || base > 36) )
691                 return 1;
692
693         *result = strtol(inp, &endptr, base);
694
695         if ( *inp != '\0' && *endptr == '\0' )
696                 return 0;
697         else
698                 return 1;
699 }
700
701 /* Convert human readable size string to and int; "1k" -> 1000 */
702 int Parser_size (int *sizep, char *str) {
703         int size;
704         char mod[32];
705
706         switch (sscanf (str, "%d%1[gGmMkK]", &size, mod)) {
707         default:
708                 return (-1);
709
710         case 1:
711                 *sizep = size;
712                 return (0);
713
714         case 2:
715                 switch (*mod) {
716                 case 'g':
717                 case 'G':
718                         *sizep = size << 30;
719                         return (0);
720
721                 case 'm':
722                 case 'M':
723                         *sizep = size << 20;
724                         return (0);
725
726                 case 'k':
727                 case 'K':
728                         *sizep = size << 10;
729                         return (0);
730
731                 default:
732                         *sizep = size;
733                         return (0);
734                 }
735         }
736 }
737
738 /* Convert a string boolean to an int; "enable" -> 1 */
739 int Parser_bool (int *b, char *str) {
740         if (!strcasecmp (str, "no") ||
741             !strcasecmp (str, "n") ||
742             !strcasecmp (str, "off") ||
743             !strcasecmp (str, "down") ||
744             !strcasecmp (str, "disable"))
745         {
746                 *b = 0;
747                 return (0);
748         }
749
750         if (!strcasecmp (str, "yes") ||
751             !strcasecmp (str, "y") ||
752             !strcasecmp (str, "on") ||
753             !strcasecmp (str, "up") ||
754             !strcasecmp (str, "enable"))
755         {
756                 *b = 1;
757                 return (0);
758         }
759
760         return (-1);
761 }
762
763 int Parser_quit(int argc, char **argv)
764 {
765         argc = argc;
766         argv = argv;
767         done = 1;
768         return 0;
769 }
770
771 int Parser_version(int argc, char **argv)
772 {
773         fprintf(stdout, "%s %s\n", program_invocation_short_name,
774                 LUSTRE_VERSION_STRING);
775         return 0;
776 }