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