Whamcloud - gitweb
LU-5418 libcfs: only define noop_*_fn when readline is used
[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(const 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 #ifdef HAVE_LIBREADLINE
287 static void noop_int_fn(int unused) { }
288 static void noop_void_fn(void) { }
289 #endif
290
291 /* just in case you're ever in an airplane and discover you
292  * forgot to install readline-dev. :) */
293 static int init_input(void)
294 {
295         int interactive = isatty(fileno(stdin));
296
297 #ifdef HAVE_LIBREADLINE
298         using_history();
299         stifle_history(HISTORY);
300
301         if (!interactive) {
302                 rl_prep_term_function = noop_int_fn;
303                 rl_deprep_term_function = noop_void_fn;
304         }
305
306         rl_attempted_completion_function = command_completion;
307         rl_completion_entry_function = 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         int size = 2048;
317         char *line = malloc(size);
318         char *ptr = line;
319         int c;
320         int eof = 0;
321
322         if (line == NULL)
323                 return NULL;
324         if (prompt)
325                 printf ("%s", prompt);
326
327         while (1) {
328                 if ((c = fgetc(stdin)) != EOF) {
329                         if (c == '\n')
330                                 goto out;
331                         *ptr++ = (char)c;
332
333                         if (ptr - line >= size - 1) {
334                                 char *tmp;
335
336                                 size *= 2;
337                                 tmp = malloc(size);
338                                 if (tmp == NULL)
339                                         goto outfree;
340                                 memcpy(tmp, line, ptr - line);
341                                 ptr = tmp + (ptr - line);
342                                 free(line);
343                                 line = tmp;
344                         }
345                 } else {
346                         eof = 1;
347                         if (ferror(stdin) || feof(stdin))
348                                 goto outfree;
349                         goto out;
350                 }
351         }
352 out:
353         *ptr = 0;
354         if (eof && (strlen(line) == 0)) {
355                 free(line);
356                 line = NULL;
357         }
358         return line;
359 outfree:
360         free(line);
361         return NULL;
362 }
363 #endif
364
365 /* this is the command execution machine */
366 int Parser_commands(void)
367 {
368         char *line, *s;
369         int rc = 0, save_error = 0;
370         int interactive;
371
372         interactive = init_input();
373
374         while(!done) {
375                 line = readline(interactive ? parser_prompt : NULL);
376
377                 if (!line) break;
378
379                 s = skipwhitespace(line);
380
381                 if (*s) {
382                         add_history(s);
383                         rc = execute_line(s);
384                 }
385                 /* stop on error if not-interactive */
386                 if (rc != 0 && !interactive) {
387                         if (save_error == 0)
388                                 save_error = rc;
389                         if (!ignore_errors)
390                                 done = 1;
391                 }
392
393                 free(line);
394         }
395         if (save_error)
396                 rc = save_error;
397         return rc;
398 }
399
400
401 /* sets the parser prompt */
402 void Parser_init(char * prompt, command_t * cmds)
403 {
404         done = 0;
405         top_level = cmds;
406         if (parser_prompt) free(parser_prompt);
407         parser_prompt = strdup(prompt);
408 }
409
410 /* frees the parser prompt */
411 void Parser_exit(int argc, char *argv[])
412 {
413         done = 1;
414         free(parser_prompt);
415         parser_prompt = NULL;
416 }
417
418 /* convert a string to an integer */
419 int Parser_int(char *s, int *val)
420 {
421         int ret;
422
423         if (*s != '0')
424                 ret = sscanf(s, "%d", val);
425         else if (*(s+1) != 'x')
426                 ret = sscanf(s, "%o", val);
427         else {
428                 s++;
429                 ret = sscanf(++s, "%x", val);
430         }
431
432         return(ret);
433 }
434
435
436 void Parser_qhelp(int argc, char *argv[]) {
437
438         printf("Available commands are:\n");
439
440         print_commands(NULL, top_level);
441         printf("For more help type: help command-name\n");
442 }
443
444 int Parser_help(int argc, char **argv)
445 {
446         char line[1024];
447         char *next, *prev, *tmp;
448         command_t *result, *ambig;
449         int i;
450
451         if ( argc == 1 ) {
452                 Parser_qhelp(argc, argv);
453                 return 0;
454         }
455
456         /* Joining command line arguments without space is not critical here
457          * because of this string is used for search a help topic and assume
458          * that only one argument will be (the name of topic). For example:
459          * lst > help ping run
460          * pingrun: Unknown command. */
461         line[0] = '\0';
462         for (i = 1;  i < argc; i++) {
463                 if (strlen(argv[i]) >= sizeof(line) - strlen(line))
464                         return -E2BIG;
465                 /* The function strlcat() cannot be used here because of
466                  * this function is used in LNet utils that is not linked
467                  * with libcfs.a. */
468                 strncat(line, argv[i], sizeof(line) - strlen(line));
469         }
470
471         switch ( process(line, &next, top_level, &result, &prev) ) {
472         case CMD_COMPLETE:
473                 fprintf(stderr, "%s: %s\n",line, result->pc_help);
474                 break;
475         case CMD_NONE:
476                 fprintf(stderr, "%s: Unknown command.\n", line);
477                 break;
478         case CMD_INCOMPLETE:
479                 fprintf(stderr,
480                         "'%s' incomplete command.  Use '%s x' where x is one of:\n",
481                         line, line);
482                 fprintf(stderr, "\t");
483                 for (i = 0; result->pc_sub_cmd[i].pc_name; i++) {
484                         fprintf(stderr, "%s ", result->pc_sub_cmd[i].pc_name);
485                 }
486                 fprintf(stderr, "\n");
487                 break;
488         case CMD_AMBIG:
489                 fprintf(stderr, "Ambiguous command \'%s\'\nOptions: ", line);
490                 while( (ambig = find_cmd(prev, result, &tmp)) ) {
491                         fprintf(stderr, "%s ", ambig->pc_name);
492                         result = ambig + 1;
493                 }
494                 fprintf(stderr, "\n");
495                 break;
496         }
497         return 0;
498 }
499
500
501 void Parser_printhelp(char *cmd)
502 {
503         char *argv[] = { "help", cmd };
504         Parser_help(2, argv);
505 }
506
507
508 /*************************************************************************
509  * COMMANDS                                                              *
510  *************************************************************************/
511 static void print_commands(char * str, command_t * table) {
512         command_t * cmds;
513         char         buf[80];
514
515         for (cmds = table; cmds->pc_name; cmds++) {
516                 if (cmds->pc_func) {
517                         if (str) printf("\t%s %s\n", str, cmds->pc_name);
518                         else printf("\t%s\n", cmds->pc_name);
519                 }
520                 if (cmds->pc_sub_cmd) {
521                         if (str) {
522                                 sprintf(buf, "%s %s", str, cmds->pc_name);
523                                 print_commands(buf, cmds->pc_sub_cmd);
524                         } else {
525                                 print_commands(cmds->pc_name, cmds->pc_sub_cmd);
526                         }
527                 }
528         }
529 }
530
531 char *Parser_getstr(const char *prompt, const char *deft, char *res,
532                     size_t len)
533 {
534         char *line = NULL;
535         int size = strlen(prompt) + strlen(deft) + 8;
536         char *theprompt;
537         theprompt = malloc(size);
538         assert(theprompt);
539
540         sprintf(theprompt, "%s [%s]: ", prompt, deft);
541
542         line  = readline(theprompt);
543         free(theprompt);
544
545         /* The function strlcpy() cannot be used here because of
546          * this function is used in LNet utils that is not linked
547          * with libcfs.a. */
548         if (line == NULL || *line == '\0')
549                 strncpy(res, deft, len);
550         else
551                 strncpy(res, line, len);
552         res[len - 1] = '\0';
553
554         if (line != NULL) {
555                 free(line);
556                 return res;
557         }
558         return NULL;
559 }
560
561 /* get integer from prompt, loop forever to get it */
562 int Parser_getint(const char *prompt, long min, long max, long deft, int base)
563 {
564         int rc;
565         long result;
566         char *line;
567         int size = strlen(prompt) + 40;
568         char *theprompt = malloc(size);
569         assert(theprompt);
570         sprintf(theprompt,"%s [%ld, (0x%lx)]: ", prompt, deft, deft);
571
572         fflush(stdout);
573
574         do {
575                 line = NULL;
576                 line = readline(theprompt);
577                 if ( !line ) {
578                         fprintf(stdout, "Please enter an integer.\n");
579                         fflush(stdout);
580                         continue;
581                 }
582                 if ( *line == '\0' ) {
583                         free(line);
584                         result =  deft;
585                         break;
586                 }
587                 rc = Parser_arg2int(line, &result, base);
588                 free(line);
589                 if ( rc != 0 ) {
590                         fprintf(stdout, "Invalid string.\n");
591                         fflush(stdout);
592                 } else if ( result > max || result < min ) {
593                         fprintf(stdout, "Error: response must lie between %ld and %ld.\n",
594                                 min, max);
595                         fflush(stdout);
596                 } else {
597                         break;
598                 }
599         } while ( 1 ) ;
600
601         if (theprompt)
602                 free(theprompt);
603         return result;
604
605 }
606
607 /* get boolean (starting with YyNn; loop forever */
608 int Parser_getbool(const char *prompt, int deft)
609 {
610         int result = 0;
611         char *line;
612         int size = strlen(prompt) + 8;
613         char *theprompt = malloc(size);
614         assert(theprompt);
615
616         fflush(stdout);
617
618         if ( deft != 0 && deft != 1 ) {
619                 fprintf(stderr, "Error: Parser_getbool given bad default %d\n",
620                         deft);
621                 assert ( 0 );
622         }
623         sprintf(theprompt, "%s [%s]: ", prompt, (deft==0)? "N" : "Y");
624
625         do {
626                 line = NULL;
627                 line = readline(theprompt);
628                 if ( line == NULL ) {
629                         result = deft;
630                         break;
631                 }
632                 if ( *line == '\0' ) {
633                         result = deft;
634                         break;
635                 }
636                 if ( *line == 'y' || *line == 'Y' ) {
637                         result = 1;
638                         break;
639                 }
640                 if ( *line == 'n' || *line == 'N' ) {
641                         result = 0;
642                         break;
643                 }
644                 if ( line )
645                         free(line);
646                 fprintf(stdout, "Invalid string. Must start with yY or nN\n");
647                 fflush(stdout);
648         } while ( 1 );
649
650         if ( line )
651                 free(line);
652         if ( theprompt )
653                 free(theprompt);
654         return result;
655 }
656
657 /* parse int out of a string or prompt for it */
658 long Parser_intarg(const char *inp, const char *prompt, int deft,
659                    int min, int max, int base)
660 {
661         long result;
662         int rc;
663
664         rc = Parser_arg2int(inp, &result, base);
665
666         if ( rc == 0 ) {
667                 return result;
668         } else {
669                 return Parser_getint(prompt, deft, min, max, base);
670         }
671 }
672
673 /* parse int out of a string or prompt for it */
674 char *Parser_strarg(char *inp, const char *prompt, const char *deft,
675                     char *answer, int len)
676 {
677         if ( inp == NULL || *inp == '\0' ) {
678                 return Parser_getstr(prompt, deft, answer, len);
679         } else
680                 return inp;
681 }
682
683 /* change a string into a number: return 0 on success. No invalid characters
684    allowed. The processing of base and validity follows strtol(3)*/
685 int Parser_arg2int(const char *inp, long *result, int base)
686 {
687         char *endptr;
688
689         if ( (base !=0) && (base < 2 || base > 36) )
690                 return 1;
691
692         *result = strtol(inp, &endptr, base);
693
694         if ( *inp != '\0' && *endptr == '\0' )
695                 return 0;
696         else
697                 return 1;
698 }
699
700 /* Convert human readable size string to and int; "1k" -> 1000 */
701 int Parser_size (int *sizep, char *str) {
702         int size;
703         char mod[32];
704
705         switch (sscanf (str, "%d%1[gGmMkK]", &size, mod)) {
706         default:
707                 return (-1);
708
709         case 1:
710                 *sizep = size;
711                 return (0);
712
713         case 2:
714                 switch (*mod) {
715                 case 'g':
716                 case 'G':
717                         *sizep = size << 30;
718                         return (0);
719
720                 case 'm':
721                 case 'M':
722                         *sizep = size << 20;
723                         return (0);
724
725                 case 'k':
726                 case 'K':
727                         *sizep = size << 10;
728                         return (0);
729
730                 default:
731                         *sizep = size;
732                         return (0);
733                 }
734         }
735 }
736
737 /* Convert a string boolean to an int; "enable" -> 1 */
738 int Parser_bool (int *b, char *str) {
739         if (!strcasecmp (str, "no") ||
740             !strcasecmp (str, "n") ||
741             !strcasecmp (str, "off") ||
742             !strcasecmp (str, "down") ||
743             !strcasecmp (str, "disable"))
744         {
745                 *b = 0;
746                 return (0);
747         }
748
749         if (!strcasecmp (str, "yes") ||
750             !strcasecmp (str, "y") ||
751             !strcasecmp (str, "on") ||
752             !strcasecmp (str, "up") ||
753             !strcasecmp (str, "enable"))
754         {
755                 *b = 1;
756                 return (0);
757         }
758
759         return (-1);
760 }
761
762 int Parser_quit(int argc, char **argv)
763 {
764         argc = argc;
765         argv = argv;
766         done = 1;
767         return 0;
768 }
769
770 int Parser_version(int argc, char **argv)
771 {
772         fprintf(stdout, "%s %s\n", program_invocation_short_name,
773                 LUSTRE_VERSION_STRING);
774         return 0;
775 }