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