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