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);
120 if (rc == CMD_HELP) {
121 fprintf(stdout, "%s\n", cmd->pc_help);
127 "%s: '%s' is not a valid command. See '%s --list-commands'.\n",
128 program_invocation_short_name, argv[0],
129 program_invocation_short_name);
135 * Returns the command_t * (NULL if not found) corresponding to a
136 * _partial_ match with the first token in name. It sets *next to
137 * point to the following token. Does not modify *name.
139 static command_t *find_cmd(char *name, command_t cmds[], char **next)
147 * This sets name to point to the first non-white space character,
148 * and next to the first whitespace after name, len to the length: do
151 name = skipwhitespace(name);
152 *next = skiptowhitespace(name);
153 len = (int)(*next - name);
157 for (i = 0; cmds[i].pc_name; i++) {
158 if (strncasecmp(name, cmds[i].pc_name, len) == 0) {
159 *next = skipwhitespace(*next);
167 * Recursively process a command line string s and find the command
168 * corresponding to it. This can be ambiguous, full, incomplete,
171 static int process(char *s, char **next, command_t *lookup,
172 command_t **result, char **prev)
174 *result = find_cmd(s, lookup, next);
182 * found entry: is it ambigous, i.e. not exact command name and
183 * more than one command in the list matches. Note that find_cmd
184 * points to the first ambiguous entry
186 if (strncasecmp(s, (*result)->pc_name, strlen((*result)->pc_name))) {
188 int found_another = 0;
190 command_t *another_result = find_cmd(s, (*result) + 1,
192 while (another_result) {
193 if (strncasecmp(s, another_result->pc_name,
194 strlen(another_result->pc_name)) == 0) {
195 *result = another_result;
196 *next = another_next;
199 another_result = find_cmd(s, another_result + 1,
208 /* found a unique command: component or full? */
209 if ((*result)->pc_func)
213 return CMD_INCOMPLETE;
214 return process(*next, next, (*result)->pc_sub_cmd,
218 #ifdef HAVE_LIBREADLINE
219 static command_t *match_tbl; /* Command completion against this table */
220 static char *command_generator(const char *text, int state)
222 static int index, len;
225 /* Do we have a match table? */
229 /* If this is the first time called on this word, state is 0 */
232 len = (int)strlen(text);
235 /* Return next name in the command list that paritally matches test */
236 while ((name = (match_tbl + index)->pc_name)) {
239 if (strncasecmp(name, text, len) == 0)
243 /* No more matches */
247 /* probably called by readline */
248 static char **command_completion(const char *text, int start, int end)
253 match_tbl = top_level;
255 for (table = find_cmd(rl_line_buffer, match_tbl, &pos);
256 table; table = find_cmd(pos, match_tbl, &pos)) {
257 if (*(pos - 1) == ' ')
258 match_tbl = table->pc_sub_cmd;
261 return rl_completion_matches(text, command_generator);
265 /* take a string and execute the function or print help */
266 static int execute_line(char *line)
268 command_t *cmd, *ambig;
275 switch (process(line, &next, top_level, &cmd, &prev)) {
277 fprintf(stderr, "Ambiguous command \'%s\'\nOptions: ", line);
278 while ((ambig = find_cmd(prev, cmd, &tmp))) {
279 fprintf(stderr, "%s ", ambig->pc_name);
282 fprintf(stderr, "\n");
285 fprintf(stderr, "No such command, type help\n");
289 "'%s' incomplete command. Use '%s x' where x is one of:\n",
291 fprintf(stderr, "\t");
292 for (i = 0; cmd->pc_sub_cmd[i].pc_name; i++)
293 fprintf(stderr, "%s ", cmd->pc_sub_cmd[i].pc_name);
294 fprintf(stderr, "\n");
298 i = line2args(line, argv, MAXARGS);
299 rc = cmd->pc_func(i, argv);
301 if (rc == CMD_HELP) {
302 fprintf(stdout, "%s\n", cmd->pc_help);
312 #ifdef HAVE_LIBREADLINE
313 static void noop_int_fn(int unused) { }
314 static void noop_void_fn(void) { }
318 * just in case you're ever in an airplane and discover you
319 * forgot to install readline-dev. :)
321 static int init_input(void)
323 int interactive = isatty(fileno(stdin));
325 #ifdef HAVE_LIBREADLINE
327 stifle_history(HISTORY);
330 rl_prep_term_function = noop_int_fn;
331 rl_deprep_term_function = noop_void_fn;
334 rl_attempted_completion_function = command_completion;
335 rl_completion_entry_function = command_generator;
340 #ifndef HAVE_LIBREADLINE
341 #define add_history(s)
342 static char *readline(char *prompt)
345 char *line = malloc(size);
353 printf("%s", prompt);
356 if ((c = fgetc(stdin)) != EOF) {
361 if (ptr - line >= size - 1) {
368 memcpy(tmp, line, ptr - line);
369 ptr = tmp + (ptr - line);
375 if (ferror(stdin) || feof(stdin))
382 if (eof && (strlen(line) == 0)) {
393 /* this is the command execution machine */
394 int Parser_commands(void)
397 int rc = 0, save_error = 0;
400 interactive = init_input();
403 line = readline(interactive ? parser_prompt : NULL);
408 s = skipwhitespace(line);
412 rc = execute_line(s);
414 /* stop on error if not-interactive */
415 if (rc != 0 && !interactive) {
430 /* sets the parser prompt */
431 void Parser_init(char *prompt, command_t *cmds)
437 parser_prompt = strdup(prompt);
440 /* frees the parser prompt */
441 void Parser_exit(int argc, char *argv[])
445 parser_prompt = NULL;
448 /* convert a string to an integer */
449 int Parser_int(char *s, int *val)
454 ret = sscanf(s, "%d", val);
455 } else if (*(s + 1) != 'x') {
456 ret = sscanf(s, "%o", val);
459 ret = sscanf(++s, "%x", val);
465 void Parser_qhelp(int argc, char *argv[])
467 printf("usage: %s [COMMAND] [OPTIONS]... [ARGS]\n",
468 program_invocation_short_name);
469 printf("Without any parameters, interactive mode is invoked\n");
471 printf("Try '%s help <COMMAND>', or '%s --list-commands' for a list of commands.\n",
472 program_invocation_short_name, program_invocation_short_name);
475 int Parser_help(int argc, char **argv)
478 char *next, *prev, *tmp;
479 command_t *result, *ambig;
483 Parser_qhelp(argc, argv);
488 * Joining command line arguments without space is not critical here
489 * because of this string is used for search a help topic and assume
490 * that only one argument will be (the name of topic). For example:
491 * lst > help ping run
492 * pingrun: Unknown command.
495 for (i = 1; i < argc; i++) {
496 if (strlen(argv[i]) >= sizeof(line) - strlen(line))
499 * The function strlcat() cannot be used here because of
500 * this function is used in LNet utils that is not linked
503 strncat(line, argv[i], sizeof(line) - strlen(line));
506 switch (process(line, &next, top_level, &result, &prev)) {
508 fprintf(stderr, "%s: %s\n", line, result->pc_help);
511 fprintf(stderr, "%s: Unknown command.\n", line);
515 "'%s' incomplete command. Use '%s x' where x is one of:\n",
517 fprintf(stderr, "\t");
518 for (i = 0; result->pc_sub_cmd[i].pc_name; i++)
519 fprintf(stderr, "%s ", result->pc_sub_cmd[i].pc_name);
520 fprintf(stderr, "\n");
523 fprintf(stderr, "Ambiguous command \'%s\'\nOptions: ", line);
524 while ((ambig = find_cmd(prev, result, &tmp))) {
525 fprintf(stderr, "%s ", ambig->pc_name);
528 fprintf(stderr, "\n");
534 void Parser_printhelp(char *cmd)
536 char *argv[] = { "help", cmd };
538 Parser_help(2, argv);
544 * Parser_list_commands() - Output a list of the supported commands.
545 * @cmdlist: Array of structures describing the commands.
546 * @buffer: String buffer used to temporarily store the output text.
547 * @buf_size: Length of the string buffer.
548 * @parent_cmd: When called recursively, contains the name of the parent cmd.
549 * @col_start: Column where printing should begin.
550 * @col_num: The number of commands printed in a single row.
552 * The commands and subcommands supported by the utility are printed, arranged
553 * into several columns for readability. If a command supports subcommands, the
554 * function is called recursively, and the name of the parent command is
555 * supplied so that it can be prepended to the names of the subcommands.
557 * Return: The number of items that were printed.
559 int Parser_list_commands(const command_t *cmdlist, char *buffer,
560 size_t buf_size, const char *parent_cmd,
561 int col_start, int col_num)
569 if (col_start >= col_num)
572 char_max = (buf_size - 1) / col_num; /* Reserve 1 char for NUL */
574 for (; cmdlist->pc_name; cmdlist++) {
575 if (!cmdlist->pc_func && !cmdlist->pc_sub_cmd)
579 len = snprintf(&buffer[col * char_max],
580 char_max + 1, "%s %s", parent_cmd,
583 len = snprintf(&buffer[col * char_max],
584 char_max + 1, "%s", cmdlist->pc_name);
586 /* Add trailing spaces to pad the entry to the column size */
587 if (len < char_max) {
588 snprintf(&buffer[col * char_max] + len,
589 char_max - len + 1, "%*s", char_max - len,
592 buffer[(col + 1) * char_max - 1] = ' ';
596 if (col >= col_num) {
597 fprintf(stdout, "%s\n", buffer);
602 if (cmdlist->pc_sub_cmd) {
603 rc = Parser_list_commands(cmdlist->pc_sub_cmd, buffer,
604 buf_size, cmdlist->pc_name,
606 col = (col + rc) % col_num;
610 if (!parent_cmd && col != 0)
611 fprintf(stdout, "%s\n", buffer);
615 char *Parser_getstr(const char *prompt, const char *deft, char *res,
619 int size = strlen(prompt) + strlen(deft) + 8;
622 theprompt = malloc(size);
625 snprintf(theprompt, size, "%s [%s]: ", prompt, deft);
627 line = readline(theprompt);
631 * The function strlcpy() cannot be used here because of
632 * this function is used in LNet utils that is not linked
635 if (!line || *line == '\0')
636 strncpy(res, deft, len);
638 strncpy(res, line, len);
648 /* get integer from prompt, loop forever to get it */
649 int Parser_getint(const char *prompt, long min, long max, long deft, int base)
654 int size = strlen(prompt) + 40;
655 char *theprompt = malloc(size);
658 snprintf(theprompt, size, "%s [%ld, (0x%lx)]: ", prompt, deft, deft);
663 line = readline(theprompt);
665 fprintf(stdout, "Please enter an integer.\n");
674 rc = Parser_arg2int(line, &result, base);
677 fprintf(stdout, "Invalid string.\n");
679 } else if (result > max || result < min) {
681 "Error: response must lie between %ld and %ld.\n",
694 /* get boolean (starting with YyNn; loop forever */
695 int Parser_getbool(const char *prompt, int deft)
699 int size = strlen(prompt) + 8;
700 char *theprompt = malloc(size);
705 if (deft != 0 && deft != 1) {
706 fprintf(stderr, "Error: Parser_getbool given bad default %d\n",
710 snprintf(theprompt, size, "%s [%s]: ", prompt, (deft == 0) ? "N" : "Y");
714 line = readline(theprompt);
723 if (*line == 'y' || *line == 'Y') {
727 if (*line == 'n' || *line == 'N') {
733 fprintf(stdout, "Invalid string. Must start with yY or nN\n");
745 /* parse int out of a string or prompt for it */
746 long Parser_intarg(const char *inp, const char *prompt, int deft,
747 int min, int max, int base)
752 rc = Parser_arg2int(inp, &result, base);
756 return Parser_getint(prompt, deft, min, max, base);
759 /* parse int out of a string or prompt for it */
760 char *Parser_strarg(char *inp, const char *prompt, const char *deft,
761 char *answer, int len)
763 if (!inp || *inp == '\0')
764 return Parser_getstr(prompt, deft, answer, len);
770 * change a string into a number: return 0 on success. No invalid characters
771 * allowed. The processing of base and validity follows strtol(3)
773 int Parser_arg2int(const char *inp, long *result, int base)
777 if ((base != 0) && (base < 2 || base > 36))
780 *result = strtol(inp, &endptr, base);
782 if (*inp != '\0' && *endptr == '\0')
788 /* Convert human readable size string to and int; "1k" -> 1000 */
789 int Parser_size(unsigned long *sizep, char *str)
794 switch (sscanf(str, "%lu%1[gGmMkK]", &size, mod)) {
821 /* Convert a string boolean to an int; "enable" -> 1 */
822 int Parser_bool(int *b, char *str)
824 if (!strcasecmp(str, "no") || !strcasecmp(str, "n") ||
825 !strcasecmp(str, "off") || !strcasecmp(str, "down") ||
826 !strcasecmp(str, "disable")) {
831 if (!strcasecmp(str, "yes") || !strcasecmp(str, "y") ||
832 !strcasecmp(str, "on") || !strcasecmp(str, "up") ||
833 !strcasecmp(str, "enable")) {
841 int Parser_quit(int argc, char **argv)
849 int Parser_version(int argc, char **argv)
851 fprintf(stdout, "%s %s\n", program_invocation_short_name,
852 LUSTRE_VERSION_STRING);