Whamcloud - gitweb
cca8e970e545348b76ead7a0512690aeba4ddce1
[fs/lustre-release.git] / libcfs / libcfs / util / parser.c
1 /*
2  * Copyright (C) 2001 Cluster File Systems, Inc.
3  *
4  *   This file is part of Lustre, http://www.sf.net/projects/lustre/
5  *
6  *   Lustre is free software; you can redistribute it and/or
7  *   modify it under the terms of version 2 of the GNU General Public
8  *   License as published by the Free Software Foundation.
9  *
10  *   Lustre is distributed in the hope that it will be useful,
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  *   GNU General Public License for more details.
14  *
15  *   You should have received a copy of the GNU General Public License
16  *   along with Lustre; if not, write to the Free Software
17  *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  *
19  */
20
21 #include <libcfs/libcfsutil.h>
22
23 static command_t * top_level;           /* Top level of commands, initialized by
24                                     * InitParser                              */
25 static char * parser_prompt = NULL;/* Parser prompt, set by InitParser      */
26 static int done;                   /* Set to 1 if user types exit or quit   */
27 static int ignore_errors;       /* Normally, the parser will quit when
28                                    an error occurs in non-interacive
29                                    mode. Setting this to non-zero will
30                                    force it to keep buggering on. */
31
32
33 /* static functions */
34 static char *skipwhitespace(char *s);
35 static char *skiptowhitespace(char *s);
36 static command_t *find_cmd(char *name, command_t cmds[], char **next);
37 static int process(char *s, char **next, command_t *lookup, command_t **result,
38                    char **prev);
39 static void print_commands(char *str, command_t *table);
40
41 static char * skipwhitespace(char * s)
42 {
43         char * t;
44         int    len;
45
46         len = (int)strlen(s);
47         for (t = s; t <= s + len && isspace(*t); t++);
48         return(t);
49 }
50
51
52 static char * skiptowhitespace(char * s)
53 {
54         char * t;
55
56         for (t = s; *t && !isspace(*t); t++);
57         return(t);
58 }
59
60 static int line2args(char *line, char **argv, int maxargs)
61 {
62         char *arg;
63         int i = 0;
64
65         arg = strtok(line, " \t");
66         if (arg == NULL || maxargs < 1)
67                 return 0;
68
69         argv[i++] = arg;
70         while ((arg = strtok(NULL, " \t")) != NULL && i < maxargs)
71                 argv[i++] = arg;
72         return i;
73 }
74
75 /* find a command -- return it if unique otherwise print alternatives */
76 static command_t *Parser_findargcmd(char *name, command_t cmds[])
77 {
78         command_t *cmd;
79
80         for (cmd = cmds; cmd->pc_name; cmd++) {
81                 if (strcmp(name, cmd->pc_name) == 0)
82                         return cmd;
83         }
84         return NULL;
85 }
86
87 void Parser_ignore_errors(int ignore)
88 {
89         ignore_errors = ignore;
90 }
91
92 int Parser_execarg(int argc, char **argv, command_t cmds[])
93 {
94         command_t *cmd;
95
96         cmd = Parser_findargcmd(argv[0], cmds);
97         if ( cmd ) {
98                 int rc = (cmd->pc_func)(argc, argv);
99                 if (rc == CMD_HELP)
100                         fprintf(stderr, "%s\n", cmd->pc_help);
101                 return rc;
102         } else {
103                 printf("Try interactive use without arguments or use one of:\n");
104                 for (cmd = cmds; cmd->pc_name; cmd++)
105                         printf("\"%s\"\n", cmd->pc_name);
106                 printf("as argument.\n");
107         }
108         return -1;
109 }
110
111 /* returns the command_t * (NULL if not found) corresponding to a
112    _partial_ match with the first token in name.  It sets *next to
113    point to the following token. Does not modify *name. */
114 static command_t * find_cmd(char * name, command_t cmds[], char ** next)
115 {
116         int    i, len;
117
118         if (!cmds || !name )
119                 return NULL;
120
121         /* This sets name to point to the first non-white space character,
122            and next to the first whitespace after name, len to the length: do
123            this with strtok*/
124         name = skipwhitespace(name);
125         *next = skiptowhitespace(name);
126         len = (int)(*next - name);
127         if (len == 0)
128                 return NULL;
129
130         for (i = 0; cmds[i].pc_name; i++) {
131                 if (strncasecmp(name, cmds[i].pc_name, len) == 0) {
132                         *next = skipwhitespace(*next);
133                         return(&cmds[i]);
134                 }
135         }
136         return NULL;
137 }
138
139 /* Recursively process a command line string s and find the command
140    corresponding to it. This can be ambiguous, full, incomplete,
141    non-existent. */
142 static int process(char *s, char ** next, command_t *lookup,
143                    command_t **result, char **prev)
144 {
145         *result = find_cmd(s, lookup, next);
146         *prev = s;
147
148         /* non existent */
149         if (!*result)
150                 return CMD_NONE;
151
152         /* found entry: is it ambigous, i.e. not exact command name and
153            more than one command in the list matches.  Note that find_cmd
154            points to the first ambiguous entry */
155         if (strncasecmp(s, (*result)->pc_name, strlen((*result)->pc_name))) {
156                 char *another_next;
157                 command_t *another_result = find_cmd(s, (*result) + 1,
158                                                      &another_next);
159                 int found_another = 0;
160
161                 while (another_result) {
162                         if (strncasecmp(s, another_result->pc_name,
163                                         strlen(another_result->pc_name)) == 0){
164                                 *result = another_result;
165                                 *next = another_next;
166                                 goto got_it;
167                         }
168                         another_result = find_cmd(s, another_result + 1,
169                                                   &another_next);
170                         found_another = 1;
171                 }
172                 if (found_another)
173                         return CMD_AMBIG;
174         }
175
176 got_it:
177         /* found a unique command: component or full? */
178         if ( (*result)->pc_func ) {
179                 return CMD_COMPLETE;
180         } else {
181                 if ( *next == '\0' ) {
182                         return CMD_INCOMPLETE;
183                 } else {
184                         return process(*next, next, (*result)->pc_sub_cmd,
185                                        result, prev);
186                 }
187         }
188 }
189
190 #ifdef HAVE_LIBREADLINE
191 static command_t * match_tbl;   /* Command completion against this table */
192 static char * command_generator(const char * text, int state)
193 {
194         static int index,
195                 len;
196         char       *name;
197
198         /* Do we have a match table? */
199         if (!match_tbl)
200                 return NULL;
201
202         /* If this is the first time called on this word, state is 0 */
203         if (!state) {
204                 index = 0;
205                 len = (int)strlen(text);
206         }
207
208         /* Return next name in the command list that paritally matches test */
209         while ( (name = (match_tbl + index)->pc_name) ) {
210                 index++;
211
212                 if (strncasecmp(name, text, len) == 0) {
213                         return(strdup(name));
214                 }
215         }
216
217         /* No more matches */
218         return NULL;
219 }
220
221 /* probably called by readline */
222 static char **command_completion(char * text, int start, int end)
223 {
224         command_t   * table;
225         char        * pos;
226
227         match_tbl = top_level;
228         
229         for (table = find_cmd(rl_line_buffer, match_tbl, &pos);
230              table; table = find_cmd(pos, match_tbl, &pos)) 
231         {
232
233                 if (*(pos - 1) == ' ') match_tbl = table->pc_sub_cmd;
234         }
235
236         return completion_matches(text, command_generator);
237 }
238 #endif
239
240 /* take a string and execute the function or print help */
241 int execute_line(char * line)
242 {
243         command_t         *cmd, *ambig;
244         char *prev;
245         char *next, *tmp;
246         char *argv[MAXARGS];
247         int         i;
248         int rc = 0;
249
250         switch (process(line, &next, top_level, &cmd, &prev)) {
251         case CMD_AMBIG:
252                 fprintf(stderr, "Ambiguous command \'%s\'\nOptions: ", line);
253                 while( (ambig = find_cmd(prev, cmd, &tmp)) ) {
254                         fprintf(stderr, "%s ", ambig->pc_name);
255                         cmd = ambig + 1;
256                 }
257                 fprintf(stderr, "\n");
258                 break;
259         case CMD_NONE:
260                 fprintf(stderr, "No such command, type help\n");
261                 break;
262         case CMD_INCOMPLETE:
263                 fprintf(stderr,
264                         "'%s' incomplete command.  Use '%s x' where x is one of:\n",
265                         line, line);
266                 fprintf(stderr, "\t");
267                 for (i = 0; cmd->pc_sub_cmd[i].pc_name; i++) {
268                         fprintf(stderr, "%s ", cmd->pc_sub_cmd[i].pc_name);
269                 }
270                 fprintf(stderr, "\n");
271                 break;
272         case CMD_COMPLETE:
273                 i = line2args(line, argv, MAXARGS);
274                 rc = (cmd->pc_func)(i, argv);
275
276                 if (rc == CMD_HELP)
277                         fprintf(stderr, "%s\n", cmd->pc_help);
278
279                 break;
280         }
281
282         return rc;
283 }
284
285 int
286 noop_fn ()
287 {
288         return (0);
289 }
290
291 /* just in case you're ever in an airplane and discover you
292    forgot to install readline-dev. :) */
293 int init_input()
294 {
295         int   interactive = isatty (fileno (stdin));
296
297 #ifdef HAVE_LIBREADLINE
298         using_history();
299         stifle_history(HISTORY);
300
301         if (!interactive)
302         {
303                 rl_prep_term_function = (rl_vintfunc_t *)noop_fn;
304                 rl_deprep_term_function = (rl_voidfunc_t *)noop_fn;
305         }
306
307         rl_attempted_completion_function = (CPPFunction *)command_completion;
308         rl_completion_entry_function = (void *)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 }