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