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