Whamcloud - gitweb
- tagging RC_CURRENT
[fs/lustre-release.git] / lustre / portals / 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 #endif
36
37 /* completion_matches() is #if 0-ed out in modern glibc */
38 #ifndef completion_matches
39 #define completion_matches rl_completion_matches
40 #endif
41 extern void using_history(void);
42 extern void stifle_history(int);
43 extern void add_history(char *);
44
45 #include "parser.h"
46
47 static command_t * top_level;      /* Top level of commands, initialized by
48                                     * InitParser                            */
49 static char * parser_prompt = NULL;/* Parser prompt, set by InitParser      */
50 static int done;                   /* Set to 1 if user types exit or quit   */
51
52
53 /* static functions */
54 static char *skipwhitespace(char *s);
55 static char *skiptowhitespace(char *s);
56 static command_t *find_cmd(char *name, command_t cmds[], char **next);
57 static int process(char *s, char **next, command_t *lookup, command_t **result,
58                    char **prev);
59 static void print_commands(char *str, command_t *table);
60
61 static char * skipwhitespace(char * s)
62 {
63     char * t;
64     int    len;
65
66     len = (int)strlen(s);
67     for (t = s; t <= s + len && isspace(*t); t++);
68     return(t);
69 }
70
71
72 static char * skiptowhitespace(char * s)
73 {
74     char * t;
75
76     for (t = s; *t && !isspace(*t); t++);
77     return(t);
78 }
79
80 static int line2args(char *line, char **argv, int maxargs)
81 {
82     char *arg;
83     int i = 0;
84
85     arg = strtok(line, " \t");
86     if ( arg ) {
87             argv[i] = arg;
88         i++;
89     } else
90         return 0;
91
92     while( (arg = strtok(NULL, " \t")) && (i <= maxargs)) {
93         argv[i] = arg;
94         i++;
95     }
96     return i;
97 }
98
99 /* find a command -- return it if unique otherwise print alternatives */
100 static command_t *Parser_findargcmd(char *name, command_t cmds[])
101 {
102         command_t *cmd;
103
104         for (cmd = cmds; cmd->pc_name; cmd++) {
105                 if (strcmp(name, cmd->pc_name) == 0)
106                         return cmd;
107         }
108         return NULL;
109 }
110
111 int Parser_execarg(int argc, char **argv, command_t cmds[])
112 {
113         command_t *cmd;
114
115         cmd = Parser_findargcmd(argv[0], cmds);
116         if ( cmd ) {
117                 int rc = (cmd->pc_func)(argc, argv);
118                 if (rc == CMD_HELP)
119                         fprintf(stderr, "%s\n", cmd->pc_help);
120                 return rc;
121         } else {
122                 printf("Try interactive use without arguments or use one of:\n");
123                 for (cmd = cmds; cmd->pc_name; cmd++)
124                         printf("\"%s\" ", cmd->pc_name);
125                 printf("\nas argument.\n");
126         }
127         return -1;
128 }
129
130 /* returns the command_t * (NULL if not found) corresponding to a
131    _partial_ match with the first token in name.  It sets *next to
132    point to the following token. Does not modify *name. */
133 static command_t * find_cmd(char * name, command_t cmds[], char ** next)
134 {
135         int    i, len;
136     
137         if (!cmds || !name ) 
138                 return NULL;
139     
140         /* This sets name to point to the first non-white space character,
141            and next to the first whitespace after name, len to the length: do
142            this with strtok*/
143         name = skipwhitespace(name);
144         *next = skiptowhitespace(name);
145         len = *next - name;
146         if (len == 0) 
147                 return NULL;
148
149         for (i = 0; cmds[i].pc_name; i++) {
150                 if (strncasecmp(name, cmds[i].pc_name, len) == 0) {
151                         *next = skipwhitespace(*next);
152                         return(&cmds[i]);
153                 }
154         }
155         return NULL;
156 }
157
158 /* Recursively process a command line string s and find the command
159    corresponding to it. This can be ambiguous, full, incomplete,
160    non-existent. */
161 static int process(char *s, char ** next, command_t *lookup,
162                    command_t **result, char **prev)
163 {
164     *result = find_cmd(s, lookup, next);
165     *prev = s;
166
167         /* non existent */
168         if ( ! *result ) 
169                 return CMD_NONE;
170
171         /* found entry: is it ambigous, i.e. not exact command name and
172            more than one command in the list matches.  Note that find_cmd
173            points to the first ambiguous entry */
174         if ( strncasecmp(s, (*result)->pc_name, strlen((*result)->pc_name)) &&
175              find_cmd(s, (*result) + 1, next)) 
176                 return CMD_AMBIG;
177
178         /* found a unique command: component or full? */
179         if ( (*result)->pc_func ) {
180                 return CMD_COMPLETE;
181         } else {
182                 if ( *next == '\0' ) {
183                         return CMD_INCOMPLETE;
184                 } else {
185                         return process(*next, next, (*result)->pc_sub_cmd, result, prev);
186                 }
187         }
188 }
189
190 #ifdef HAVE_LIBREADLINE
191 static command_t * match_tbl;   /* Command completion against this table */
192 static char * command_generator(const char * text, int state)
193 {
194         static int index,
195                 len;
196         char       *name;
197
198         /* Do we have a match table? */
199         if (!match_tbl)
200                 return NULL;
201
202         /* If this is the first time called on this word, state is 0 */
203         if (!state) {
204                 index = 0;
205                 len = (int)strlen(text);
206         }
207
208         /* Return next name in the command list that paritally matches test */
209         while ( (name = (match_tbl + index)->pc_name) ) {
210                 index++;
211
212                 if (strncasecmp(name, text, len) == 0) {
213                         return(strdup(name));
214                 }
215         }
216
217     /* No more matches */
218     return NULL;
219 }
220
221 /* probably called by readline */
222 static char **command_completion(char * text, int start, int end)
223 {
224     command_t   * table;
225     char        * pos;
226
227     match_tbl = top_level;
228     for (table = find_cmd(rl_line_buffer, match_tbl, &pos);
229          table;
230          table = find_cmd(pos, match_tbl, &pos)) {
231
232         if (*(pos - 1) == ' ') match_tbl = table->pc_sub_cmd;
233     }
234
235     return(completion_matches(text, command_generator));
236 }
237 #endif
238
239 /* take a string and execute the function or print help */
240 int execute_line(char * line)
241 {
242         command_t         *cmd, *ambig;
243         char *prev;
244         char *next, *tmp;
245         char *argv[MAXARGS];
246         int         i;
247         int rc = 0;
248
249         switch( process(line, &next, top_level, &cmd, &prev) ) {
250         case CMD_AMBIG:
251                 fprintf(stderr, "Ambiguous command \'%s\'\nOptions: ", line);
252                 while( (ambig = find_cmd(prev, cmd, &tmp)) ) {
253                         fprintf(stderr, "%s ", ambig->pc_name);
254                         cmd = ambig + 1;
255                 }
256                 fprintf(stderr, "\n");
257                 break;
258         case CMD_NONE:
259                 fprintf(stderr, "No such command, type help\n");
260                 break;
261         case CMD_INCOMPLETE:
262                 fprintf(stderr,
263                         "'%s' incomplete command.  Use '%s x' where x is one of:\n",
264                         line, line);
265                 fprintf(stderr, "\t");
266                 for (i = 0; cmd->pc_sub_cmd[i].pc_name; i++) {
267                         fprintf(stderr, "%s ", cmd->pc_sub_cmd[i].pc_name);
268                 }
269                 fprintf(stderr, "\n");
270                 break;
271         case CMD_COMPLETE:
272                 i = line2args(line, argv, MAXARGS);
273                 rc = (cmd->pc_func)(i, argv);
274
275                 if (rc == CMD_HELP)
276                         fprintf(stderr, "%s\n", cmd->pc_help);
277
278                 break;
279         }
280
281         return rc;
282 }
283
284 int
285 noop_fn ()
286 {
287         return (0);
288 }
289
290 /* just in case you're ever in an airplane and discover you 
291    forgot to install readline-dev. :) */
292 int init_input() 
293 {
294         int   interactive = isatty (fileno (stdin));
295
296 #ifdef HAVE_LIBREADLINE
297         using_history();
298         stifle_history(HISTORY);
299
300         if (!interactive)
301         {
302                 rl_prep_term_function = (rl_vintfunc_t *)noop_fn;
303                 rl_deprep_term_function = (rl_voidfunc_t *)noop_fn;
304         }
305
306         rl_attempted_completion_function = (CPPFunction *)command_completion;
307         rl_completion_entry_function = (void *)command_generator;
308 #endif 
309         return interactive;
310 }
311
312 #ifndef HAVE_LIBREADLINE
313 #define add_history(s)
314 char * readline(char * prompt) 
315 {
316         char line[2048];
317         int n = 0;
318         if (prompt)
319                 printf ("%s", prompt);
320         if (fgets(line, sizeof(line), stdin) == NULL)
321                 return (NULL);
322         n = strlen(line);
323         if (n && line[n-1] == '\n')
324                 line[n-1] = '\0';
325         return strdup(line);
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  * 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, "down") ||
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, "up") ||
697             !strcasecmp (str, "enable"))
698         {
699                 *b = 1;
700                 return (0);
701         }
702         
703         return (-1);
704 }
705
706 int Parser_quit(int argc, char **argv)
707 {
708         argc = argc;
709         argv = argv;
710         done = 1;
711         return 0;
712 }