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