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