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