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