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