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