Whamcloud - gitweb
LU-6068 misc: update Intel copyright messages 2014
[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 <lustre_ver.h>
24 #include <libcfs/libcfsutil.h>
25
26 static command_t * top_level;           /* Top level of commands, initialized by
27                                     * InitParser                              */
28 static char * parser_prompt = NULL;/* Parser prompt, set by InitParser      */
29 static int done;                   /* Set to 1 if user types exit or quit   */
30 static int ignore_errors;       /* Normally, the parser will quit when
31                                    an error occurs in non-interacive
32                                    mode. Setting this to non-zero will
33                                    force it to keep buggering on. */
34
35
36 /* static functions */
37 static char *skipwhitespace(char *s);
38 static char *skiptowhitespace(char *s);
39 static command_t *find_cmd(char *name, command_t cmds[], char **next);
40 static int process(char *s, char **next, command_t *lookup, command_t **result,
41                    char **prev);
42 static void print_commands(char *str, command_t *table);
43
44 static char * skipwhitespace(char * s)
45 {
46         char * t;
47         int    len;
48
49         len = (int)strlen(s);
50         for (t = s; t <= s + len && isspace(*t); t++);
51         return(t);
52 }
53
54
55 static char * skiptowhitespace(char * s)
56 {
57         char * t;
58
59         for (t = s; *t && !isspace(*t); t++);
60         return(t);
61 }
62
63 static int line2args(char *line, char **argv, int maxargs)
64 {
65         char *arg;
66         int i = 0;
67
68         arg = strtok(line, " \t");
69         if (arg == NULL || maxargs < 1)
70                 return 0;
71
72         argv[i++] = arg;
73         while ((arg = strtok(NULL, " \t")) != NULL && i < maxargs)
74                 argv[i++] = arg;
75         return i;
76 }
77
78 /* find a command -- return it if unique otherwise print alternatives */
79 static command_t *Parser_findargcmd(char *name, command_t cmds[])
80 {
81         command_t *cmd;
82
83         for (cmd = cmds; cmd->pc_name; cmd++) {
84                 if (strcmp(name, cmd->pc_name) == 0)
85                         return cmd;
86         }
87         return NULL;
88 }
89
90 void Parser_ignore_errors(int ignore)
91 {
92         ignore_errors = ignore;
93 }
94
95 int Parser_execarg(int argc, char **argv, command_t cmds[])
96 {
97         command_t *cmd;
98
99         cmd = Parser_findargcmd(argv[0], cmds);
100         if ( cmd ) {
101                 int rc = (cmd->pc_func)(argc, argv);
102                 if (rc == CMD_HELP)
103                         fprintf(stderr, "%s\n", cmd->pc_help);
104                 return rc;
105         } else {
106                 printf("Try interactive use without arguments or use one of:\n");
107                 for (cmd = cmds; cmd->pc_name; cmd++)
108                         printf("\"%s\"\n", cmd->pc_name);
109                 printf("as argument.\n");
110         }
111         return -1;
112 }
113
114 /* returns the command_t * (NULL if not found) corresponding to a
115    _partial_ match with the first token in name.  It sets *next to
116    point to the following token. Does not modify *name. */
117 static command_t * find_cmd(char * name, command_t cmds[], char ** next)
118 {
119         int    i, len;
120
121         if (!cmds || !name )
122                 return NULL;
123
124         /* This sets name to point to the first non-white space character,
125            and next to the first whitespace after name, len to the length: do
126            this with strtok*/
127         name = skipwhitespace(name);
128         *next = skiptowhitespace(name);
129         len = (int)(*next - name);
130         if (len == 0)
131                 return NULL;
132
133         for (i = 0; cmds[i].pc_name; i++) {
134                 if (strncasecmp(name, cmds[i].pc_name, len) == 0) {
135                         *next = skipwhitespace(*next);
136                         return(&cmds[i]);
137                 }
138         }
139         return NULL;
140 }
141
142 /* Recursively process a command line string s and find the command
143    corresponding to it. This can be ambiguous, full, incomplete,
144    non-existent. */
145 static int process(char *s, char ** next, command_t *lookup,
146                    command_t **result, char **prev)
147 {
148         *result = find_cmd(s, lookup, next);
149         *prev = s;
150
151         /* non existent */
152         if (!*result)
153                 return CMD_NONE;
154
155         /* found entry: is it ambigous, i.e. not exact command name and
156            more than one command in the list matches.  Note that find_cmd
157            points to the first ambiguous entry */
158         if (strncasecmp(s, (*result)->pc_name, strlen((*result)->pc_name))) {
159                 char *another_next;
160                 command_t *another_result = find_cmd(s, (*result) + 1,
161                                                      &another_next);
162                 int found_another = 0;
163
164                 while (another_result) {
165                         if (strncasecmp(s, another_result->pc_name,
166                                         strlen(another_result->pc_name)) == 0){
167                                 *result = another_result;
168                                 *next = another_next;
169                                 goto got_it;
170                         }
171                         another_result = find_cmd(s, another_result + 1,
172                                                   &another_next);
173                         found_another = 1;
174                 }
175                 if (found_another)
176                         return CMD_AMBIG;
177         }
178
179 got_it:
180         /* found a unique command: component or full? */
181         if ( (*result)->pc_func ) {
182                 return CMD_COMPLETE;
183         } else {
184                 if ( *next == '\0' ) {
185                         return CMD_INCOMPLETE;
186                 } else {
187                         return process(*next, next, (*result)->pc_sub_cmd,
188                                        result, prev);
189                 }
190         }
191 }
192
193 #ifdef HAVE_LIBREADLINE
194 static command_t * match_tbl;   /* Command completion against this table */
195 static char * command_generator(const char * text, int state)
196 {
197         static int index,
198                 len;
199         char       *name;
200
201         /* Do we have a match table? */
202         if (!match_tbl)
203                 return NULL;
204
205         /* If this is the first time called on this word, state is 0 */
206         if (!state) {
207                 index = 0;
208                 len = (int)strlen(text);
209         }
210
211         /* Return next name in the command list that paritally matches test */
212         while ( (name = (match_tbl + index)->pc_name) ) {
213                 index++;
214
215                 if (strncasecmp(name, text, len) == 0) {
216                         return(strdup(name));
217                 }
218         }
219
220         /* No more matches */
221         return NULL;
222 }
223
224 /* probably called by readline */
225 static char **command_completion(const char *text, int start, int end)
226 {
227         command_t   * table;
228         char        * pos;
229
230         match_tbl = top_level;
231         
232         for (table = find_cmd(rl_line_buffer, match_tbl, &pos);
233              table; table = find_cmd(pos, match_tbl, &pos)) 
234         {
235
236                 if (*(pos - 1) == ' ') match_tbl = table->pc_sub_cmd;
237         }
238
239         return completion_matches(text, command_generator);
240 }
241 #endif
242
243 /* take a string and execute the function or print help */
244 int execute_line(char * line)
245 {
246         command_t         *cmd, *ambig;
247         char *prev;
248         char *next, *tmp;
249         char *argv[MAXARGS];
250         int         i;
251         int rc = 0;
252
253         switch (process(line, &next, top_level, &cmd, &prev)) {
254         case CMD_AMBIG:
255                 fprintf(stderr, "Ambiguous command \'%s\'\nOptions: ", line);
256                 while( (ambig = find_cmd(prev, cmd, &tmp)) ) {
257                         fprintf(stderr, "%s ", ambig->pc_name);
258                         cmd = ambig + 1;
259                 }
260                 fprintf(stderr, "\n");
261                 break;
262         case CMD_NONE:
263                 fprintf(stderr, "No such command, type help\n");
264                 break;
265         case CMD_INCOMPLETE:
266                 fprintf(stderr,
267                         "'%s' incomplete command.  Use '%s x' where x is one of:\n",
268                         line, line);
269                 fprintf(stderr, "\t");
270                 for (i = 0; cmd->pc_sub_cmd[i].pc_name; i++) {
271                         fprintf(stderr, "%s ", cmd->pc_sub_cmd[i].pc_name);
272                 }
273                 fprintf(stderr, "\n");
274                 break;
275         case CMD_COMPLETE:
276                 i = line2args(line, argv, MAXARGS);
277                 rc = (cmd->pc_func)(i, argv);
278
279                 if (rc == CMD_HELP)
280                         fprintf(stderr, "%s\n", cmd->pc_help);
281
282                 break;
283         }
284
285         return rc;
286 }
287
288 #ifdef HAVE_LIBREADLINE
289 static void noop_int_fn(int unused) { }
290 static void noop_void_fn(void) { }
291 #endif
292
293 /* just in case you're ever in an airplane and discover you
294  * forgot to install readline-dev. :) */
295 static int init_input(void)
296 {
297         int interactive = isatty(fileno(stdin));
298
299 #ifdef HAVE_LIBREADLINE
300         using_history();
301         stifle_history(HISTORY);
302
303         if (!interactive) {
304                 rl_prep_term_function = noop_int_fn;
305                 rl_deprep_term_function = noop_void_fn;
306         }
307
308         rl_attempted_completion_function = command_completion;
309         rl_completion_entry_function = 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 }