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