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