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