Whamcloud - gitweb
b40250ba9aafc5ab998be8f3b529f5e4637649d6
[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         line[0]='\0';
458         for ( i = 1 ;  i < argc ; i++ ) {
459                 if (strlen(argv[i]) > sizeof(line)-strlen(line)-1)
460                         return -E2BIG;
461                 strncat(line, argv[i], sizeof(line)-strlen(line)-1);
462         }
463
464         switch ( process(line, &next, top_level, &result, &prev) ) {
465         case CMD_COMPLETE:
466                 fprintf(stderr, "%s: %s\n",line, result->pc_help);
467                 break;
468         case CMD_NONE:
469                 fprintf(stderr, "%s: Unknown command.\n", line);
470                 break;
471         case CMD_INCOMPLETE:
472                 fprintf(stderr,
473                         "'%s' incomplete command.  Use '%s x' where x is one of:\n",
474                         line, line);
475                 fprintf(stderr, "\t");
476                 for (i = 0; result->pc_sub_cmd[i].pc_name; i++) {
477                         fprintf(stderr, "%s ", result->pc_sub_cmd[i].pc_name);
478                 }
479                 fprintf(stderr, "\n");
480                 break;
481         case CMD_AMBIG:
482                 fprintf(stderr, "Ambiguous command \'%s\'\nOptions: ", line);
483                 while( (ambig = find_cmd(prev, result, &tmp)) ) {
484                         fprintf(stderr, "%s ", ambig->pc_name);
485                         result = ambig + 1;
486                 }
487                 fprintf(stderr, "\n");
488                 break;
489         }
490         return 0;
491 }
492
493
494 void Parser_printhelp(char *cmd)
495 {
496         char *argv[] = { "help", cmd };
497         Parser_help(2, argv);
498 }
499
500
501 /*************************************************************************
502  * COMMANDS                                                              *
503  *************************************************************************/
504 static void print_commands(char * str, command_t * table) {
505         command_t * cmds;
506         char         buf[80];
507
508         for (cmds = table; cmds->pc_name; cmds++) {
509                 if (cmds->pc_func) {
510                         if (str) printf("\t%s %s\n", str, cmds->pc_name);
511                         else printf("\t%s\n", cmds->pc_name);
512                 }
513                 if (cmds->pc_sub_cmd) {
514                         if (str) {
515                                 sprintf(buf, "%s %s", str, cmds->pc_name);
516                                 print_commands(buf, cmds->pc_sub_cmd);
517                         } else {
518                                 print_commands(cmds->pc_name, cmds->pc_sub_cmd);
519                         }
520                 }
521         }
522 }
523
524 char *Parser_getstr(const char *prompt, const char *deft, char *res,
525                     size_t len)
526 {
527         char *line = NULL;
528         int size = strlen(prompt) + strlen(deft) + 8;
529         char *theprompt;
530         theprompt = malloc(size);
531         assert(theprompt);
532
533         sprintf(theprompt, "%s [%s]: ", prompt, deft);
534
535         line  = readline(theprompt);
536         free(theprompt);
537
538         if ( line == NULL || *line == '\0' ) {
539                 strncpy(res, deft, len);
540         } else {
541                 strncpy(res, line, len);
542         }
543
544         if ( line ) {
545                 free(line);
546                 return res;
547         } else {
548                 return NULL;
549         }
550 }
551
552 /* get integer from prompt, loop forever to get it */
553 int Parser_getint(const char *prompt, long min, long max, long deft, int base)
554 {
555         int rc;
556         long result;
557         char *line;
558         int size = strlen(prompt) + 40;
559         char *theprompt = malloc(size);
560         assert(theprompt);
561         sprintf(theprompt,"%s [%ld, (0x%lx)]: ", prompt, deft, deft);
562
563         fflush(stdout);
564
565         do {
566                 line = NULL;
567                 line = readline(theprompt);
568                 if ( !line ) {
569                         fprintf(stdout, "Please enter an integer.\n");
570                         fflush(stdout);
571                         continue;
572                 }
573                 if ( *line == '\0' ) {
574                         free(line);
575                         result =  deft;
576                         break;
577                 }
578                 rc = Parser_arg2int(line, &result, base);
579                 free(line);
580                 if ( rc != 0 ) {
581                         fprintf(stdout, "Invalid string.\n");
582                         fflush(stdout);
583                 } else if ( result > max || result < min ) {
584                         fprintf(stdout, "Error: response must lie between %ld and %ld.\n",
585                                 min, max);
586                         fflush(stdout);
587                 } else {
588                         break;
589                 }
590         } while ( 1 ) ;
591
592         if (theprompt)
593                 free(theprompt);
594         return result;
595
596 }
597
598 /* get boolean (starting with YyNn; loop forever */
599 int Parser_getbool(const char *prompt, int deft)
600 {
601         int result = 0;
602         char *line;
603         int size = strlen(prompt) + 8;
604         char *theprompt = malloc(size);
605         assert(theprompt);
606
607         fflush(stdout);
608
609         if ( deft != 0 && deft != 1 ) {
610                 fprintf(stderr, "Error: Parser_getbool given bad default %d\n",
611                         deft);
612                 assert ( 0 );
613         }
614         sprintf(theprompt, "%s [%s]: ", prompt, (deft==0)? "N" : "Y");
615
616         do {
617                 line = NULL;
618                 line = readline(theprompt);
619                 if ( line == NULL ) {
620                         result = deft;
621                         break;
622                 }
623                 if ( *line == '\0' ) {
624                         result = deft;
625                         break;
626                 }
627                 if ( *line == 'y' || *line == 'Y' ) {
628                         result = 1;
629                         break;
630                 }
631                 if ( *line == 'n' || *line == 'N' ) {
632                         result = 0;
633                         break;
634                 }
635                 if ( line )
636                         free(line);
637                 fprintf(stdout, "Invalid string. Must start with yY or nN\n");
638                 fflush(stdout);
639         } while ( 1 );
640
641         if ( line )
642                 free(line);
643         if ( theprompt )
644                 free(theprompt);
645         return result;
646 }
647
648 /* parse int out of a string or prompt for it */
649 long Parser_intarg(const char *inp, const char *prompt, int deft,
650                    int min, int max, int base)
651 {
652         long result;
653         int rc;
654
655         rc = Parser_arg2int(inp, &result, base);
656
657         if ( rc == 0 ) {
658                 return result;
659         } else {
660                 return Parser_getint(prompt, deft, min, max, base);
661         }
662 }
663
664 /* parse int out of a string or prompt for it */
665 char *Parser_strarg(char *inp, const char *prompt, const char *deft,
666                     char *answer, int len)
667 {
668         if ( inp == NULL || *inp == '\0' ) {
669                 return Parser_getstr(prompt, deft, answer, len);
670         } else
671                 return inp;
672 }
673
674 /* change a string into a number: return 0 on success. No invalid characters
675    allowed. The processing of base and validity follows strtol(3)*/
676 int Parser_arg2int(const char *inp, long *result, int base)
677 {
678         char *endptr;
679
680         if ( (base !=0) && (base < 2 || base > 36) )
681                 return 1;
682
683         *result = strtol(inp, &endptr, base);
684
685         if ( *inp != '\0' && *endptr == '\0' )
686                 return 0;
687         else
688                 return 1;
689 }
690
691 /* Convert human readable size string to and int; "1k" -> 1000 */
692 int Parser_size (int *sizep, char *str) {
693         int size;
694         char mod[32];
695
696         switch (sscanf (str, "%d%1[gGmMkK]", &size, mod)) {
697         default:
698                 return (-1);
699
700         case 1:
701                 *sizep = size;
702                 return (0);
703
704         case 2:
705                 switch (*mod) {
706                 case 'g':
707                 case 'G':
708                         *sizep = size << 30;
709                         return (0);
710
711                 case 'm':
712                 case 'M':
713                         *sizep = size << 20;
714                         return (0);
715
716                 case 'k':
717                 case 'K':
718                         *sizep = size << 10;
719                         return (0);
720
721                 default:
722                         *sizep = size;
723                         return (0);
724                 }
725         }
726 }
727
728 /* Convert a string boolean to an int; "enable" -> 1 */
729 int Parser_bool (int *b, char *str) {
730         if (!strcasecmp (str, "no") ||
731             !strcasecmp (str, "n") ||
732             !strcasecmp (str, "off") ||
733             !strcasecmp (str, "down") ||
734             !strcasecmp (str, "disable"))
735         {
736                 *b = 0;
737                 return (0);
738         }
739
740         if (!strcasecmp (str, "yes") ||
741             !strcasecmp (str, "y") ||
742             !strcasecmp (str, "on") ||
743             !strcasecmp (str, "up") ||
744             !strcasecmp (str, "enable"))
745         {
746                 *b = 1;
747                 return (0);
748         }
749
750         return (-1);
751 }
752
753 int Parser_quit(int argc, char **argv)
754 {
755         argc = argc;
756         argv = argv;
757         done = 1;
758         return 0;
759 }