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 /* Top level of commands, initialized by InitParser */
42 static command_t *top_level;
43 /* Parser prompt, set by InitParser */
44 static char *parser_prompt;
45 /* Set to 1 if user types exit or quit */
48 * Normally, the parser will quit when an error occurs in non-interacive
49 * mode. Setting this to non-zero will force it to keep buggering on.
51 static int ignore_errors;
53 /* static functions */
54 static char *skipwhitespace(char *s);
55 static char *skiptowhitespace(char *s);
56 static command_t *find_cmd(char *name, command_t cmds[], char **next);
57 static int process(char *s, char **next, command_t *lookup, command_t **result,
60 static char *skipwhitespace(char *s)
66 for (t = s; t <= s + len && isspace(*t); t++)
71 static char *skiptowhitespace(char *s)
75 for (t = s; *t && !isspace(*t); t++)
80 static int line2args(char *line, char **argv, int maxargs)
85 arg = strtok(line, " \t");
86 if (!arg || maxargs < 1)
90 while ((arg = strtok(NULL, " \t")) != NULL && i < maxargs)
95 /* find a command -- return it if unique otherwise print alternatives */
96 static command_t *Parser_findargcmd(char *name, command_t cmds[])
100 for (cmd = cmds; cmd->pc_name; cmd++) {
101 if (strcmp(name, cmd->pc_name) == 0)
107 void Parser_ignore_errors(int ignore)
109 ignore_errors = ignore;
112 int Parser_execarg(int argc, char **argv, command_t cmds[])
116 cmd = Parser_findargcmd(argv[0], cmds);
117 if (cmd && cmd->pc_func) {
118 int rc = cmd->pc_func(argc, argv);
121 fprintf(stderr, "%s\n", cmd->pc_help);
124 printf("Try interactive use without arguments or use one of:\n");
125 for (cmd = cmds; cmd->pc_name; cmd++)
126 printf("\"%s\"\n", cmd->pc_name);
127 printf("as argument.\n");
133 * Returns the command_t * (NULL if not found) corresponding to a
134 * _partial_ match with the first token in name. It sets *next to
135 * point to the following token. Does not modify *name.
137 static command_t *find_cmd(char *name, command_t cmds[], char **next)
145 * This sets name to point to the first non-white space character,
146 * and next to the first whitespace after name, len to the length: do
149 name = skipwhitespace(name);
150 *next = skiptowhitespace(name);
151 len = (int)(*next - name);
155 for (i = 0; cmds[i].pc_name; i++) {
156 if (strncasecmp(name, cmds[i].pc_name, len) == 0) {
157 *next = skipwhitespace(*next);
165 * Recursively process a command line string s and find the command
166 * corresponding to it. This can be ambiguous, full, incomplete,
169 static int process(char *s, char **next, command_t *lookup,
170 command_t **result, char **prev)
172 *result = find_cmd(s, lookup, next);
180 * found entry: is it ambigous, i.e. not exact command name and
181 * more than one command in the list matches. Note that find_cmd
182 * points to the first ambiguous entry
184 if (strncasecmp(s, (*result)->pc_name, strlen((*result)->pc_name))) {
186 int found_another = 0;
188 command_t *another_result = find_cmd(s, (*result) + 1,
190 while (another_result) {
191 if (strncasecmp(s, another_result->pc_name,
192 strlen(another_result->pc_name)) == 0) {
193 *result = another_result;
194 *next = another_next;
197 another_result = find_cmd(s, another_result + 1,
206 /* found a unique command: component or full? */
207 if ((*result)->pc_func)
211 return CMD_INCOMPLETE;
212 return process(*next, next, (*result)->pc_sub_cmd,
216 #ifdef HAVE_LIBREADLINE
217 static command_t *match_tbl; /* Command completion against this table */
218 static char *command_generator(const char *text, int state)
220 static int index, len;
223 /* Do we have a match table? */
227 /* If this is the first time called on this word, state is 0 */
230 len = (int)strlen(text);
233 /* Return next name in the command list that paritally matches test */
234 while ((name = (match_tbl + index)->pc_name)) {
237 if (strncasecmp(name, text, len) == 0)
241 /* No more matches */
245 /* probably called by readline */
246 static char **command_completion(const char *text, int start, int end)
251 match_tbl = top_level;
253 for (table = find_cmd(rl_line_buffer, match_tbl, &pos);
254 table; table = find_cmd(pos, match_tbl, &pos)) {
255 if (*(pos - 1) == ' ')
256 match_tbl = table->pc_sub_cmd;
259 return rl_completion_matches(text, command_generator);
263 /* take a string and execute the function or print help */
264 int execute_line(char *line)
266 command_t *cmd, *ambig;
273 switch (process(line, &next, top_level, &cmd, &prev)) {
275 fprintf(stderr, "Ambiguous command \'%s\'\nOptions: ", line);
276 while ((ambig = find_cmd(prev, cmd, &tmp))) {
277 fprintf(stderr, "%s ", ambig->pc_name);
280 fprintf(stderr, "\n");
283 fprintf(stderr, "No such command, type help\n");
287 "'%s' incomplete command. Use '%s x' where x is one of:\n",
289 fprintf(stderr, "\t");
290 for (i = 0; cmd->pc_sub_cmd[i].pc_name; i++)
291 fprintf(stderr, "%s ", cmd->pc_sub_cmd[i].pc_name);
292 fprintf(stderr, "\n");
296 i = line2args(line, argv, MAXARGS);
297 rc = cmd->pc_func(i, argv);
300 fprintf(stderr, "%s\n", cmd->pc_help);
308 #ifdef HAVE_LIBREADLINE
309 static void noop_int_fn(int unused) { }
310 static void noop_void_fn(void) { }
314 * just in case you're ever in an airplane and discover you
315 * forgot to install readline-dev. :)
317 static int init_input(void)
319 int interactive = isatty(fileno(stdin));
321 #ifdef HAVE_LIBREADLINE
323 stifle_history(HISTORY);
326 rl_prep_term_function = noop_int_fn;
327 rl_deprep_term_function = noop_void_fn;
330 rl_attempted_completion_function = command_completion;
331 rl_completion_entry_function = command_generator;
336 #ifndef HAVE_LIBREADLINE
337 #define add_history(s)
338 char *readline(char *prompt)
341 char *line = malloc(size);
349 printf("%s", prompt);
352 if ((c = fgetc(stdin)) != EOF) {
357 if (ptr - line >= size - 1) {
364 memcpy(tmp, line, ptr - line);
365 ptr = tmp + (ptr - line);
371 if (ferror(stdin) || feof(stdin))
378 if (eof && (strlen(line) == 0)) {
389 /* this is the command execution machine */
390 int Parser_commands(void)
393 int rc = 0, save_error = 0;
396 interactive = init_input();
399 line = readline(interactive ? parser_prompt : NULL);
404 s = skipwhitespace(line);
408 rc = execute_line(s);
410 /* stop on error if not-interactive */
411 if (rc != 0 && !interactive) {
426 /* sets the parser prompt */
427 void Parser_init(char *prompt, command_t *cmds)
433 parser_prompt = strdup(prompt);
436 /* frees the parser prompt */
437 void Parser_exit(int argc, char *argv[])
441 parser_prompt = NULL;
444 /* convert a string to an integer */
445 int Parser_int(char *s, int *val)
450 ret = sscanf(s, "%d", val);
451 } else if (*(s + 1) != 'x') {
452 ret = sscanf(s, "%o", val);
455 ret = sscanf(++s, "%x", val);
461 void Parser_qhelp(int argc, char *argv[])
463 printf("usage: %s [COMMAND] [OPTIONS]... [ARGS]\n",
464 program_invocation_short_name);
465 printf("Without any parameters, interactive mode is invoked\n");
467 printf("Try '%s help <COMMAND>' or '%s --list-commands' for more information\n",
468 program_invocation_short_name, program_invocation_short_name);
471 int Parser_help(int argc, char **argv)
474 char *next, *prev, *tmp;
475 command_t *result, *ambig;
479 Parser_qhelp(argc, argv);
484 * Joining command line arguments without space is not critical here
485 * because of this string is used for search a help topic and assume
486 * that only one argument will be (the name of topic). For example:
487 * lst > help ping run
488 * pingrun: Unknown command.
491 for (i = 1; i < argc; i++) {
492 if (strlen(argv[i]) >= sizeof(line) - strlen(line))
495 * The function strlcat() cannot be used here because of
496 * this function is used in LNet utils that is not linked
499 strncat(line, argv[i], sizeof(line) - strlen(line));
502 switch (process(line, &next, top_level, &result, &prev)) {
504 fprintf(stderr, "%s: %s\n", line, result->pc_help);
507 fprintf(stderr, "%s: Unknown command.\n", line);
511 "'%s' incomplete command. Use '%s x' where x is one of:\n",
513 fprintf(stderr, "\t");
514 for (i = 0; result->pc_sub_cmd[i].pc_name; i++)
515 fprintf(stderr, "%s ", result->pc_sub_cmd[i].pc_name);
516 fprintf(stderr, "\n");
519 fprintf(stderr, "Ambiguous command \'%s\'\nOptions: ", line);
520 while ((ambig = find_cmd(prev, result, &tmp))) {
521 fprintf(stderr, "%s ", ambig->pc_name);
524 fprintf(stderr, "\n");
530 void Parser_printhelp(char *cmd)
532 char *argv[] = { "help", cmd };
534 Parser_help(2, argv);
540 * Parser_list_commands() - Output a list of the supported commands.
541 * @cmdlist: Array of structures describing the commands.
542 * @buffer: String buffer used to temporarily store the output text.
543 * @buf_size: Length of the string buffer.
544 * @parent_cmd: When called recursively, contains the name of the parent cmd.
545 * @col_start: Column where printing should begin.
546 * @col_num: The number of commands printed in a single row.
548 * The commands and subcommands supported by the utility are printed, arranged
549 * into several columns for readability. If a command supports subcommands, the
550 * function is called recursively, and the name of the parent command is
551 * supplied so that it can be prepended to the names of the subcommands.
553 * Return: The number of items that were printed.
555 int Parser_list_commands(const command_t *cmdlist, char *buffer,
556 size_t buf_size, const char *parent_cmd,
557 int col_start, int col_num)
565 if (col_start >= col_num)
568 char_max = (buf_size - 1) / col_num; /* Reserve 1 char for NUL */
570 for (; cmdlist->pc_name; cmdlist++) {
571 if (!cmdlist->pc_func && !cmdlist->pc_sub_cmd)
575 len = snprintf(&buffer[col * char_max],
576 char_max + 1, "%s %s", parent_cmd,
579 len = snprintf(&buffer[col * char_max],
580 char_max + 1, "%s", cmdlist->pc_name);
582 /* Add trailing spaces to pad the entry to the column size */
583 if (len < char_max) {
584 snprintf(&buffer[col * char_max] + len,
585 char_max - len + 1, "%*s", char_max - len,
588 buffer[(col + 1) * char_max - 1] = ' ';
592 if (col >= col_num) {
593 fprintf(stdout, "%s\n", buffer);
598 if (cmdlist->pc_sub_cmd) {
599 rc = Parser_list_commands(cmdlist->pc_sub_cmd, buffer,
600 buf_size, cmdlist->pc_name,
602 col = (col + rc) % col_num;
606 if (!parent_cmd && col != 0)
607 fprintf(stdout, "%s\n", buffer);
611 char *Parser_getstr(const char *prompt, const char *deft, char *res,
615 int size = strlen(prompt) + strlen(deft) + 8;
618 theprompt = malloc(size);
621 snprintf(theprompt, size, "%s [%s]: ", prompt, deft);
623 line = readline(theprompt);
627 * The function strlcpy() cannot be used here because of
628 * this function is used in LNet utils that is not linked
631 if (!line || *line == '\0')
632 strncpy(res, deft, len);
634 strncpy(res, line, len);
644 /* get integer from prompt, loop forever to get it */
645 int Parser_getint(const char *prompt, long min, long max, long deft, int base)
650 int size = strlen(prompt) + 40;
651 char *theprompt = malloc(size);
654 snprintf(theprompt, size, "%s [%ld, (0x%lx)]: ", prompt, deft, deft);
659 line = readline(theprompt);
661 fprintf(stdout, "Please enter an integer.\n");
670 rc = Parser_arg2int(line, &result, base);
673 fprintf(stdout, "Invalid string.\n");
675 } else if (result > max || result < min) {
677 "Error: response must lie between %ld and %ld.\n",
690 /* get boolean (starting with YyNn; loop forever */
691 int Parser_getbool(const char *prompt, int deft)
695 int size = strlen(prompt) + 8;
696 char *theprompt = malloc(size);
701 if (deft != 0 && deft != 1) {
702 fprintf(stderr, "Error: Parser_getbool given bad default %d\n",
706 snprintf(theprompt, size, "%s [%s]: ", prompt, (deft == 0) ? "N" : "Y");
710 line = readline(theprompt);
719 if (*line == 'y' || *line == 'Y') {
723 if (*line == 'n' || *line == 'N') {
729 fprintf(stdout, "Invalid string. Must start with yY or nN\n");
741 /* parse int out of a string or prompt for it */
742 long Parser_intarg(const char *inp, const char *prompt, int deft,
743 int min, int max, int base)
748 rc = Parser_arg2int(inp, &result, base);
752 return Parser_getint(prompt, deft, min, max, base);
755 /* parse int out of a string or prompt for it */
756 char *Parser_strarg(char *inp, const char *prompt, const char *deft,
757 char *answer, int len)
759 if (!inp || *inp == '\0')
760 return Parser_getstr(prompt, deft, answer, len);
766 * change a string into a number: return 0 on success. No invalid characters
767 * allowed. The processing of base and validity follows strtol(3)
769 int Parser_arg2int(const char *inp, long *result, int base)
773 if ((base != 0) && (base < 2 || base > 36))
776 *result = strtol(inp, &endptr, base);
778 if (*inp != '\0' && *endptr == '\0')
784 /* Convert human readable size string to and int; "1k" -> 1000 */
785 int Parser_size(unsigned long *sizep, char *str)
790 switch (sscanf(str, "%lu%1[gGmMkK]", &size, mod)) {
817 /* Convert a string boolean to an int; "enable" -> 1 */
818 int Parser_bool(int *b, char *str)
820 if (!strcasecmp(str, "no") || !strcasecmp(str, "n") ||
821 !strcasecmp(str, "off") || !strcasecmp(str, "down") ||
822 !strcasecmp(str, "disable")) {
827 if (!strcasecmp(str, "yes") || !strcasecmp(str, "y") ||
828 !strcasecmp(str, "on") || !strcasecmp(str, "up") ||
829 !strcasecmp(str, "enable")) {
837 int Parser_quit(int argc, char **argv)
845 int Parser_version(int argc, char **argv)
847 fprintf(stdout, "%s %s\n", program_invocation_short_name,
848 LUSTRE_VERSION_STRING);