2 * Copyright (C) 2001 Cluster File Systems, Inc.
4 * Copyright (c) 2014, 2017, Intel Corporation.
6 * This file is part of Lustre, http://www.sf.net/projects/lustre/
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.
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.
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.
31 #ifdef HAVE_LIBREADLINE
32 # include <readline/history.h>
33 # include <readline/readline.h>
34 #endif /* HAVE_LIBREADLINE */
38 #include <libcfs/util/parser.h>
39 #include <linux/lustre/lustre_ver.h>
41 static command_t * top_level; /* Top level of commands, initialized by
43 static char * parser_prompt = NULL;/* Parser prompt, set by InitParser */
44 static int done; /* Set to 1 if user types exit or quit */
45 static int ignore_errors; /* Normally, the parser will quit when
46 an error occurs in non-interacive
47 mode. Setting this to non-zero will
48 force it to keep buggering on. */
51 /* static functions */
52 static char *skipwhitespace(char *s);
53 static char *skiptowhitespace(char *s);
54 static command_t *find_cmd(char *name, command_t cmds[], char **next);
55 static int process(char *s, char **next, command_t *lookup, command_t **result,
58 static char * skipwhitespace(char * s)
64 for (t = s; t <= s + len && isspace(*t); t++);
69 static char * skiptowhitespace(char * s)
73 for (t = s; *t && !isspace(*t); t++);
77 static int line2args(char *line, char **argv, int maxargs)
82 arg = strtok(line, " \t");
83 if (arg == NULL || maxargs < 1)
87 while ((arg = strtok(NULL, " \t")) != NULL && i < maxargs)
92 /* find a command -- return it if unique otherwise print alternatives */
93 static command_t *Parser_findargcmd(char *name, command_t cmds[])
97 for (cmd = cmds; cmd->pc_name; cmd++) {
98 if (strcmp(name, cmd->pc_name) == 0)
104 void Parser_ignore_errors(int ignore)
106 ignore_errors = ignore;
109 int Parser_execarg(int argc, char **argv, command_t cmds[])
113 cmd = Parser_findargcmd(argv[0], cmds);
114 if (cmd != NULL && cmd->pc_func != NULL) {
115 int rc = (cmd->pc_func)(argc, argv);
117 fprintf(stderr, "%s\n", cmd->pc_help);
120 printf("Try interactive use without arguments or use one of:\n");
121 for (cmd = cmds; cmd->pc_name; cmd++)
122 printf("\"%s\"\n", cmd->pc_name);
123 printf("as argument.\n");
128 /* returns the command_t * (NULL if not found) corresponding to a
129 _partial_ match with the first token in name. It sets *next to
130 point to the following token. Does not modify *name. */
131 static command_t * find_cmd(char * name, command_t cmds[], char ** next)
138 /* This sets name to point to the first non-white space character,
139 and next to the first whitespace after name, len to the length: do
141 name = skipwhitespace(name);
142 *next = skiptowhitespace(name);
143 len = (int)(*next - name);
147 for (i = 0; cmds[i].pc_name; i++) {
148 if (strncasecmp(name, cmds[i].pc_name, len) == 0) {
149 *next = skipwhitespace(*next);
156 /* Recursively process a command line string s and find the command
157 corresponding to it. This can be ambiguous, full, incomplete,
159 static int process(char *s, char ** next, command_t *lookup,
160 command_t **result, char **prev)
162 *result = find_cmd(s, lookup, next);
169 /* found entry: is it ambigous, i.e. not exact command name and
170 more than one command in the list matches. Note that find_cmd
171 points to the first ambiguous entry */
172 if (strncasecmp(s, (*result)->pc_name, strlen((*result)->pc_name))) {
174 command_t *another_result = find_cmd(s, (*result) + 1,
176 int found_another = 0;
178 while (another_result) {
179 if (strncasecmp(s, another_result->pc_name,
180 strlen(another_result->pc_name)) == 0){
181 *result = another_result;
182 *next = another_next;
185 another_result = find_cmd(s, another_result + 1,
194 /* found a unique command: component or full? */
195 if ((*result)->pc_func != NULL) {
198 if (**next == '\0') {
199 return CMD_INCOMPLETE;
201 return process(*next, next, (*result)->pc_sub_cmd,
207 #ifdef HAVE_LIBREADLINE
208 static command_t * match_tbl; /* Command completion against this table */
209 static char * command_generator(const char * text, int state)
215 /* Do we have a match table? */
219 /* If this is the first time called on this word, state is 0 */
222 len = (int)strlen(text);
225 /* Return next name in the command list that paritally matches test */
226 while ( (name = (match_tbl + index)->pc_name) ) {
229 if (strncasecmp(name, text, len) == 0) {
230 return(strdup(name));
234 /* No more matches */
238 /* probably called by readline */
239 static char **command_completion(const char *text, int start, int end)
244 match_tbl = top_level;
246 for (table = find_cmd(rl_line_buffer, match_tbl, &pos);
247 table; table = find_cmd(pos, match_tbl, &pos))
250 if (*(pos - 1) == ' ') match_tbl = table->pc_sub_cmd;
253 return rl_completion_matches(text, command_generator);
257 /* take a string and execute the function or print help */
258 int execute_line(char * line)
260 command_t *cmd, *ambig;
267 switch (process(line, &next, top_level, &cmd, &prev)) {
269 fprintf(stderr, "Ambiguous command \'%s\'\nOptions: ", line);
270 while ((ambig = find_cmd(prev, cmd, &tmp))) {
271 fprintf(stderr, "%s ", ambig->pc_name);
274 fprintf(stderr, "\n");
277 fprintf(stderr, "No such command, type help\n");
280 fprintf(stderr, "'%s' incomplete command. Use '%s x' where "
281 "x is one of:\n", line, line);
282 fprintf(stderr, "\t");
283 for (i = 0; cmd->pc_sub_cmd[i].pc_name; i++)
284 fprintf(stderr, "%s ", cmd->pc_sub_cmd[i].pc_name);
285 fprintf(stderr, "\n");
289 i = line2args(line, argv, MAXARGS);
290 rc = (cmd->pc_func)(i, argv);
293 fprintf(stderr, "%s\n", cmd->pc_help);
301 #ifdef HAVE_LIBREADLINE
302 static void noop_int_fn(int unused) { }
303 static void noop_void_fn(void) { }
306 /* just in case you're ever in an airplane and discover you
307 * forgot to install readline-dev. :) */
308 static int init_input(void)
310 int interactive = isatty(fileno(stdin));
312 #ifdef HAVE_LIBREADLINE
314 stifle_history(HISTORY);
317 rl_prep_term_function = noop_int_fn;
318 rl_deprep_term_function = noop_void_fn;
321 rl_attempted_completion_function = command_completion;
322 rl_completion_entry_function = command_generator;
327 #ifndef HAVE_LIBREADLINE
328 #define add_history(s)
329 char * readline(char * prompt)
332 char *line = malloc(size);
340 printf ("%s", prompt);
343 if ((c = fgetc(stdin)) != EOF) {
348 if (ptr - line >= size - 1) {
355 memcpy(tmp, line, ptr - line);
356 ptr = tmp + (ptr - line);
362 if (ferror(stdin) || feof(stdin))
369 if (eof && (strlen(line) == 0)) {
380 /* this is the command execution machine */
381 int Parser_commands(void)
384 int rc = 0, save_error = 0;
387 interactive = init_input();
390 line = readline(interactive ? parser_prompt : NULL);
394 s = skipwhitespace(line);
398 rc = execute_line(s);
400 /* stop on error if not-interactive */
401 if (rc != 0 && !interactive) {
416 /* sets the parser prompt */
417 void Parser_init(char * prompt, command_t * cmds)
421 if (parser_prompt) free(parser_prompt);
422 parser_prompt = strdup(prompt);
425 /* frees the parser prompt */
426 void Parser_exit(int argc, char *argv[])
430 parser_prompt = NULL;
433 /* convert a string to an integer */
434 int Parser_int(char *s, int *val)
439 ret = sscanf(s, "%d", val);
440 else if (*(s+1) != 'x')
441 ret = sscanf(s, "%o", val);
444 ret = sscanf(++s, "%x", val);
451 void Parser_qhelp(int argc, char *argv[]) {
453 printf("usage: %s [COMMAND] [OPTIONS]... [ARGS]\n",
454 program_invocation_short_name);
455 printf("Without any parameters, interactive mode is invoked\n");
457 printf("Try '%s help <COMMAND>' or '%s --list-commands' for more information\n",
458 program_invocation_short_name, program_invocation_short_name);
461 int Parser_help(int argc, char **argv)
464 char *next, *prev, *tmp;
465 command_t *result, *ambig;
469 Parser_qhelp(argc, argv);
473 /* Joining command line arguments without space is not critical here
474 * because of this string is used for search a help topic and assume
475 * that only one argument will be (the name of topic). For example:
476 * lst > help ping run
477 * pingrun: Unknown command. */
479 for (i = 1; i < argc; i++) {
480 if (strlen(argv[i]) >= sizeof(line) - strlen(line))
482 /* The function strlcat() cannot be used here because of
483 * this function is used in LNet utils that is not linked
485 strncat(line, argv[i], sizeof(line) - strlen(line));
488 switch ( process(line, &next, top_level, &result, &prev) ) {
490 fprintf(stderr, "%s: %s\n",line, result->pc_help);
493 fprintf(stderr, "%s: Unknown command.\n", line);
497 "'%s' incomplete command. Use '%s x' where x is one of:\n",
499 fprintf(stderr, "\t");
500 for (i = 0; result->pc_sub_cmd[i].pc_name; i++) {
501 fprintf(stderr, "%s ", result->pc_sub_cmd[i].pc_name);
503 fprintf(stderr, "\n");
506 fprintf(stderr, "Ambiguous command \'%s\'\nOptions: ", line);
507 while( (ambig = find_cmd(prev, result, &tmp)) ) {
508 fprintf(stderr, "%s ", ambig->pc_name);
511 fprintf(stderr, "\n");
518 void Parser_printhelp(char *cmd)
520 char *argv[] = { "help", cmd };
521 Parser_help(2, argv);
525 /*************************************************************************
527 *************************************************************************/
530 * Parser_list_commands() - Output a list of the supported commands.
531 * @cmdlist: Array of structures describing the commands.
532 * @buffer: String buffer used to temporarily store the output text.
533 * @buf_size: Length of the string buffer.
534 * @parent_cmd: When called recursively, contains the name of the parent cmd.
535 * @col_start: Column where printing should begin.
536 * @col_num: The number of commands printed in a single row.
538 * The commands and subcommands supported by the utility are printed, arranged
539 * into several columns for readability. If a command supports subcommands, the
540 * function is called recursively, and the name of the parent command is
541 * supplied so that it can be prepended to the names of the subcommands.
543 * Return: The number of items that were printed.
545 int Parser_list_commands(const command_t *cmdlist, char *buffer,
546 size_t buf_size, const char *parent_cmd,
547 int col_start, int col_num)
555 if (col_start >= col_num)
558 char_max = (buf_size - 1) / col_num; /* Reserve 1 char for NUL */
560 for (; cmdlist->pc_name != NULL; cmdlist++) {
561 if (cmdlist->pc_func == NULL && cmdlist->pc_sub_cmd == NULL)
564 if (parent_cmd != NULL)
565 len = snprintf(&buffer[col * char_max],
566 char_max + 1, "%s %s", parent_cmd,
569 len = snprintf(&buffer[col * char_max],
570 char_max + 1, "%s", cmdlist->pc_name);
572 /* Add trailing spaces to pad the entry to the column size */
573 if (len < char_max) {
574 snprintf(&buffer[col * char_max] + len,
575 char_max - len + 1, "%*s", char_max - len,
578 buffer[(col + 1) * char_max - 1] = ' ';
582 if (col >= col_num) {
583 fprintf(stdout, "%s\n", buffer);
588 if (cmdlist->pc_sub_cmd != NULL) {
589 rc = Parser_list_commands(cmdlist->pc_sub_cmd, buffer,
590 buf_size, cmdlist->pc_name,
592 col = (col + rc) % col_num;
596 if (parent_cmd == NULL && col != 0)
597 fprintf(stdout, "%s\n", buffer);
601 char *Parser_getstr(const char *prompt, const char *deft, char *res,
605 int size = strlen(prompt) + strlen(deft) + 8;
607 theprompt = malloc(size);
610 sprintf(theprompt, "%s [%s]: ", prompt, deft);
612 line = readline(theprompt);
615 /* The function strlcpy() cannot be used here because of
616 * this function is used in LNet utils that is not linked
618 if (line == NULL || *line == '\0')
619 strncpy(res, deft, len);
621 strncpy(res, line, len);
631 /* get integer from prompt, loop forever to get it */
632 int Parser_getint(const char *prompt, long min, long max, long deft, int base)
637 int size = strlen(prompt) + 40;
638 char *theprompt = malloc(size);
640 sprintf(theprompt,"%s [%ld, (0x%lx)]: ", prompt, deft, deft);
646 line = readline(theprompt);
648 fprintf(stdout, "Please enter an integer.\n");
652 if ( *line == '\0' ) {
657 rc = Parser_arg2int(line, &result, base);
660 fprintf(stdout, "Invalid string.\n");
662 } else if ( result > max || result < min ) {
663 fprintf(stdout, "Error: response must lie between %ld and %ld.\n",
677 /* get boolean (starting with YyNn; loop forever */
678 int Parser_getbool(const char *prompt, int deft)
682 int size = strlen(prompt) + 8;
683 char *theprompt = malloc(size);
688 if ( deft != 0 && deft != 1 ) {
689 fprintf(stderr, "Error: Parser_getbool given bad default %d\n",
693 sprintf(theprompt, "%s [%s]: ", prompt, (deft==0)? "N" : "Y");
697 line = readline(theprompt);
698 if ( line == NULL ) {
702 if ( *line == '\0' ) {
706 if ( *line == 'y' || *line == 'Y' ) {
710 if ( *line == 'n' || *line == 'N' ) {
716 fprintf(stdout, "Invalid string. Must start with yY or nN\n");
727 /* parse int out of a string or prompt for it */
728 long Parser_intarg(const char *inp, const char *prompt, int deft,
729 int min, int max, int base)
734 rc = Parser_arg2int(inp, &result, base);
739 return Parser_getint(prompt, deft, min, max, base);
743 /* parse int out of a string or prompt for it */
744 char *Parser_strarg(char *inp, const char *prompt, const char *deft,
745 char *answer, int len)
747 if ( inp == NULL || *inp == '\0' ) {
748 return Parser_getstr(prompt, deft, answer, len);
753 /* change a string into a number: return 0 on success. No invalid characters
754 allowed. The processing of base and validity follows strtol(3)*/
755 int Parser_arg2int(const char *inp, long *result, int base)
759 if ( (base !=0) && (base < 2 || base > 36) )
762 *result = strtol(inp, &endptr, base);
764 if ( *inp != '\0' && *endptr == '\0' )
770 /* Convert human readable size string to and int; "1k" -> 1000 */
771 int Parser_size(unsigned long *sizep, char *str)
776 switch (sscanf(str, "%lu%1[gGmMkK]", &size, mod)) {
808 /* Convert a string boolean to an int; "enable" -> 1 */
809 int Parser_bool (int *b, char *str) {
810 if (!strcasecmp (str, "no") ||
811 !strcasecmp (str, "n") ||
812 !strcasecmp (str, "off") ||
813 !strcasecmp (str, "down") ||
814 !strcasecmp (str, "disable"))
820 if (!strcasecmp (str, "yes") ||
821 !strcasecmp (str, "y") ||
822 !strcasecmp (str, "on") ||
823 !strcasecmp (str, "up") ||
824 !strcasecmp (str, "enable"))
833 int Parser_quit(int argc, char **argv)
841 int Parser_version(int argc, char **argv)
843 fprintf(stdout, "%s %s\n", program_invocation_short_name,
844 LUSTRE_VERSION_STRING);