xref: /kvmtool/kvm-cmd.c (revision 9abc695d9116baae92a62757d85b1262d76bdf15)
1 #include <stdio.h>
2 #include <string.h>
3 #include <errno.h>
4 
5 #include <assert.h>
6 
7 /* user defined header files */
8 #include "kvm/builtin-debug.h"
9 #include "kvm/builtin-pause.h"
10 #include "kvm/builtin-resume.h"
11 #include "kvm/builtin-balloon.h"
12 #include "kvm/builtin-list.h"
13 #include "kvm/builtin-version.h"
14 #include "kvm/builtin-stop.h"
15 #include "kvm/builtin-help.h"
16 #include "kvm/kvm-cmd.h"
17 #include "kvm/builtin-run.h"
18 #include "kvm/util.h"
19 
20 struct cmd_struct kvm_commands[] = {
21 	{ "pause",	kvm_cmd_pause,		NULL,         0 },
22 	{ "resume",	kvm_cmd_resume,		NULL,         0 },
23 	{ "debug",	kvm_cmd_debug,		NULL,         0 },
24 	{ "balloon",	kvm_cmd_balloon,	NULL,         0 },
25 	{ "list",	kvm_cmd_list,		NULL,         0 },
26 	{ "version",	kvm_cmd_version,	NULL,         0 },
27 	{ "--version",	kvm_cmd_version,	NULL,         0 },
28 	{ "stop",	kvm_cmd_stop,		NULL,         0 },
29 	{ "help",	kvm_cmd_help,		NULL,         0 },
30 	{ "run",	kvm_cmd_run,		kvm_run_help, 0 },
31 	{ NULL,		NULL,			NULL,         0 },
32 };
33 
34 /*
35  * kvm_get_command: Searches the command in an array of the commands and
36  * returns a pointer to cmd_struct if a match is found.
37  *
38  * Input parameters:
39  * command: Array of possible commands. The last entry in the array must be
40  *          NULL.
41  * cmd: A string command to search in the array
42  *
43  * Return Value:
44  * NULL: If the cmd is not matched with any of the command in the command array
45  * p: Pointer to cmd_struct of the matching command
46  */
47 struct cmd_struct *kvm_get_command(struct cmd_struct *command,
48 		const char *cmd)
49 {
50 	struct cmd_struct *p = command;
51 
52 	while (p->cmd) {
53 		if (!strcmp(p->cmd, cmd))
54 			return p;
55 		p++;
56 	}
57 	return NULL;
58 }
59 
60 int handle_command(struct cmd_struct *command, int argc, const char **argv)
61 {
62 	struct cmd_struct *p;
63 	const char *prefix = NULL;
64 	int ret = 0;
65 
66 	if (!argv || !*argv) {
67 		p = kvm_get_command(command, "help");
68 		assert(p);
69 		return p->fn(argc, argv, prefix);
70 	}
71 
72 	p = kvm_get_command(command, argv[0]);
73 	if (!p) {
74 		p = kvm_get_command(command, "help");
75 		assert(p);
76 		p->fn(0, NULL, prefix);
77 		return EINVAL;
78 	}
79 
80 	ret = p->fn(argc - 1, &argv[1], prefix);
81 	if (ret < 0) {
82 		if (errno == EPERM)
83 			die("Permission error - are you root?");
84 	}
85 
86 	return ret;
87 }
88