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