Whamcloud - gitweb
smash the HEAD with the contents of b_cmd. HEAD_PRE_CMD_SMASH and
[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 //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
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                 int rc = (cmd->pc_func)(argc, argv);
114                 if (rc == CMD_HELP)
115                         fprintf(stderr, "%s\n", cmd->pc_help);
116                 return rc;
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 command_t * match_tbl;   /* Command completion against this table */
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 = 0;
314         if (prompt)
315                 printf ("%s", prompt);
316         if (fgets(line, sizeof(line), stdin) == NULL)
317                 return (NULL);
318         n = strlen(line);
319         if (n && line[n-1] == '\n')
320                 line[n-1] = '\0';
321         return strdup(line);
322 }
323 #endif
324
325 /* this is the command execution machine */
326 int Parser_commands(void)
327 {
328         char *line, *s;
329         int rc = 0;
330         int interactive;
331         
332         interactive = init_input();
333
334         while(!done) {
335                 line = readline(interactive ? parser_prompt : NULL);
336
337                 if (!line) break;
338
339                 s = skipwhitespace(line);
340
341                 if (*s) {
342                         add_history(s);
343                         rc = execute_line(s);
344                 }
345                 
346                 free(line);
347         }
348         return rc;
349 }
350
351
352 /* sets the parser prompt */
353 void Parser_init(char * prompt, command_t * cmds)
354 {
355     done = 0;
356     top_level = cmds;
357     if (parser_prompt) free(parser_prompt);
358     parser_prompt = strdup(prompt);
359 }
360
361 /* frees the parser prompt */
362 void Parser_exit(int argc, char *argv[])
363 {
364     done = 1;
365     free(parser_prompt);
366     parser_prompt = NULL;
367 }
368
369 /* convert a string to an integer */
370 int Parser_int(char *s, int *val)
371 {
372     int ret;
373
374     if (*s != '0')
375         ret = sscanf(s, "%d", val);
376     else if (*(s+1) != 'x')
377         ret = sscanf(s, "%o", val);
378     else {
379         s++;
380         ret = sscanf(++s, "%x", val);
381     }
382
383     return(ret);
384 }
385
386
387 void Parser_qhelp(int argc, char *argv[]) {
388
389     printf("Available commands are:\n");
390
391     print_commands(NULL, top_level);
392     printf("For more help type: help command-name\n");
393 }
394
395 int Parser_help(int argc, char **argv) 
396 {
397         char line[1024];
398         char *next, *prev, *tmp;
399         command_t *result, *ambig;
400         int i;
401
402         if ( argc == 1 ) {
403                 Parser_qhelp(argc, argv);
404                 return 0;
405         }
406
407         line[0]='\0';
408         for ( i = 1 ;  i < argc ; i++ ) {
409                 strcat(line, argv[i]);
410         }
411
412         switch ( process(line, &next, top_level, &result, &prev) ) {
413         case CMD_COMPLETE:
414                 fprintf(stderr, "%s: %s\n",line, result->pc_help);
415                 break;
416         case CMD_NONE:
417                 fprintf(stderr, "%s: Unknown command.\n", line);
418                 break;
419         case CMD_INCOMPLETE:
420                 fprintf(stderr,
421                         "'%s' incomplete command.  Use '%s x' where x is one of:\n",
422                         line, line);
423                 fprintf(stderr, "\t");
424                 for (i = 0; result->pc_sub_cmd[i].pc_name; i++) {
425                         fprintf(stderr, "%s ", result->pc_sub_cmd[i].pc_name);
426                 }
427                 fprintf(stderr, "\n");
428                 break;
429         case CMD_AMBIG:
430                 fprintf(stderr, "Ambiguous command \'%s\'\nOptions: ", line);
431                 while( (ambig = find_cmd(prev, result, &tmp)) ) {
432                         fprintf(stderr, "%s ", ambig->pc_name);
433                         result = ambig + 1;
434                 }
435                 fprintf(stderr, "\n");
436                 break;
437         }
438         return 0;
439 }  
440
441
442 void Parser_printhelp(char *cmd)
443 {
444         char *argv[] = { "help", cmd }; 
445         Parser_help(2, argv);
446 }
447
448 /*************************************************************************
449  * COMMANDS                                                              *
450  *************************************************************************/
451
452
453 static void print_commands(char * str, command_t * table) {
454     command_t * cmds;
455     char        buf[80];
456
457     for (cmds = table; cmds->pc_name; cmds++) {
458         if (cmds->pc_func) {
459             if (str) printf("\t%s %s\n", str, cmds->pc_name);
460             else printf("\t%s\n", cmds->pc_name);
461         }
462         if (cmds->pc_sub_cmd) {
463             if (str) {
464                 sprintf(buf, "%s %s", str, cmds->pc_name);
465                 print_commands(buf, cmds->pc_sub_cmd);
466             } else {
467                 print_commands(cmds->pc_name, cmds->pc_sub_cmd);
468             }
469         }
470     }
471 }
472
473 char *Parser_getstr(const char *prompt, const char *deft, char *res,
474                     size_t len)
475 {
476     char *line = NULL;
477     int size = strlen(prompt) + strlen(deft) + 8;
478     char *theprompt;
479     theprompt = malloc(size);
480     assert(theprompt);
481
482     sprintf(theprompt, "%s [%s]: ", prompt, deft);
483
484     line  = readline(theprompt);
485     free(theprompt);
486
487     if ( line == NULL || *line == '\0' ) {
488         strncpy(res, deft, len);
489     } else {
490         strncpy(res, line, len);
491     }
492
493     if ( line ) {
494         free(line);
495         return res;
496     } else {
497         return NULL;
498     }
499 }
500
501 /* get integer from prompt, loop forever to get it */
502 int Parser_getint(const char *prompt, long min, long max, long deft, int base)
503 {
504     int rc;
505     long result;
506     char *line;
507     int size = strlen(prompt) + 40;
508     char *theprompt = malloc(size);
509     assert(theprompt);
510     sprintf(theprompt,"%s [%ld, (0x%lx)]: ", prompt, deft, deft);
511
512     fflush(stdout);
513
514     do {
515         line = NULL;
516         line = readline(theprompt);
517         if ( !line ) {
518             fprintf(stdout, "Please enter an integer.\n");
519             fflush(stdout);
520             continue;
521         }
522         if ( *line == '\0' ) {
523             free(line);
524             result =  deft;
525             break;
526         }
527         rc = Parser_arg2int(line, &result, base);
528         free(line);
529         if ( rc != 0 ) {
530             fprintf(stdout, "Invalid string.\n");
531             fflush(stdout);
532         } else if ( result > max || result < min ) {
533             fprintf(stdout, "Error: response must lie between %ld and %ld.\n",
534                     min, max);
535             fflush(stdout);
536         } else {
537             break;
538         }
539     } while ( 1 ) ;
540
541     if (theprompt)
542         free(theprompt);
543     return result;
544
545 }
546
547 /* get boolean (starting with YyNn; loop forever */
548 int Parser_getbool(const char *prompt, int deft)
549 {
550     int result = 0;
551     char *line;
552     int size = strlen(prompt) + 8;
553     char *theprompt = malloc(size);
554     assert(theprompt);
555
556     fflush(stdout);
557
558     if ( deft != 0 && deft != 1 ) {
559         fprintf(stderr, "Error: Parser_getbool given bad default (%d).\n",
560                 deft);
561         assert ( 0 );
562     }
563     sprintf(theprompt, "%s [%s]: ", prompt, (deft==0)? "N" : "Y");
564
565     do {
566         line = NULL;
567         line = readline(theprompt);
568         if ( line == NULL ) {
569             result = deft;
570             break;
571         }
572         if ( *line == '\0' ) {
573             result = deft;
574             break;
575         }
576         if ( *line == 'y' || *line == 'Y' ) {
577             result = 1;
578             break;
579         }
580         if ( *line == 'n' || *line == 'N' ) {
581             result = 0;
582             break;
583         }
584         if ( line )
585             free(line);
586         fprintf(stdout, "Invalid string. Must start with yY or nN\n");
587         fflush(stdout);
588     } while ( 1 );
589
590     if ( line )
591         free(line);
592     if ( theprompt )
593         free(theprompt);
594     return result;
595 }
596
597 /* parse int out of a string or prompt for it */
598 long Parser_intarg(const char *inp, const char *prompt, int deft,
599                   int min, int max, int base)
600 {
601     long result;
602     int rc;
603
604     rc = Parser_arg2int(inp, &result, base);
605
606     if ( rc == 0 ) {
607         return result;
608     } else {
609         return Parser_getint(prompt, deft, min, max, base);
610     }
611 }
612
613 /* parse int out of a string or prompt for it */
614 char *Parser_strarg(char *inp, const char *prompt, const char *deft,
615                     char *answer, int len)
616 {
617     if ( inp == NULL || *inp == '\0' ) {
618         return Parser_getstr(prompt, deft, answer, len);
619     } else
620         return inp;
621 }
622
623 /* change a string into a number: return 0 on success. No invalid characters
624    allowed. The processing of base and validity follows strtol(3)*/
625 int Parser_arg2int(const char *inp, long *result, int base)
626 {
627     char *endptr;
628
629     if ( (base !=0) && (base < 2 || base > 36) )
630         return 1;
631
632     *result = strtol(inp, &endptr, base);
633
634         if ( *inp != '\0' && *endptr == '\0' )
635                 return 0;
636         else 
637                 return 1;
638 }
639
640 /* Convert human readable size string to and int; "1k" -> 1000 */
641 int Parser_size (int *sizep, char *str) {
642         int size;
643         char mod[32];
644
645         switch (sscanf (str, "%d%1[gGmMkK]", &size, mod)) {
646         default:
647                 return (-1);
648
649         case 1:
650                 *sizep = size;
651                 return (0);
652
653         case 2:
654                 switch (*mod) {
655                 case 'g':
656                 case 'G':
657                         *sizep = size << 30;
658                         return (0);
659
660                 case 'm':
661                 case 'M':
662                         *sizep = size << 20;
663                         return (0);
664
665                 case 'k':
666                 case 'K':
667                         *sizep = size << 10;
668                         return (0);
669
670                 default:
671                         *sizep = size;
672                         return (0);
673                 }
674         }
675 }
676
677 /* Convert a string boolean to an int; "enable" -> 1 */
678 int Parser_bool (int *b, char *str) {
679         if (!strcasecmp (str, "no") ||
680             !strcasecmp (str, "n") ||
681             !strcasecmp (str, "off") ||
682             !strcasecmp (str, "down") ||
683             !strcasecmp (str, "disable"))
684         {
685                 *b = 0;
686                 return (0);
687         }
688         
689         if (!strcasecmp (str, "yes") ||
690             !strcasecmp (str, "y") ||
691             !strcasecmp (str, "on") ||
692             !strcasecmp (str, "up") ||
693             !strcasecmp (str, "enable"))
694         {
695                 *b = 1;
696                 return (0);
697         }
698         
699         return (-1);
700 }
701
702 int Parser_quit(int argc, char **argv)
703 {
704         argc = argc;
705         argv = argv;
706         done = 1;
707         return 0;
708 }