xref: /kvmtool/kvm-cmd.c (revision e81c0199f8cc2dbe25f0d1234bea796a0c64220c)
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 	{ "stop",	kvm_cmd_stop,		NULL,         0 },
28 	{ "help",	kvm_cmd_help,		NULL,         0 },
29 	{ "run",	kvm_cmd_run,		kvm_run_help, 0 },
30 	{ NULL,		NULL,			NULL,         0 },
31 };
32 
33 /*
34  * kvm_get_command: Searches the command in an array of the commands and
35  * returns a pointer to cmd_struct if a match is found.
36  *
37  * Input parameters:
38  * command: Array of possible commands. The last entry in the array must be
39  *          NULL.
40  * cmd: A string command to search in the array
41  *
42  * Return Value:
43  * NULL: If the cmd is not matched with any of the command in the command array
44  * p: Pointer to cmd_struct of the matching command
45  */
46 struct cmd_struct *kvm_get_command(struct cmd_struct *command,
47 		const char *cmd)
48 {
49 	struct cmd_struct *p = command;
50 
51 	while (p->cmd) {
52 		if (!strcmp(p->cmd, cmd))
53 			return p;
54 		p++;
55 	}
56 	return NULL;
57 }
58 
59 int handle_command(struct cmd_struct *command, int argc, const char **argv)
60 {
61 	struct cmd_struct *p;
62 	const char *prefix = NULL;
63 	int ret = 0;
64 
65 	if (!argv || !*argv) {
66 		p = kvm_get_command(command, "help");
67 		assert(p);
68 		return p->fn(argc, argv, prefix);
69 	}
70 
71 	p = kvm_get_command(command, argv[0]);
72 	if (!p) {
73 		p = kvm_get_command(command, "help");
74 		assert(p);
75 		p->fn(0, NULL, prefix);
76 		return EINVAL;
77 	}
78 
79 	ret = p->fn(argc - 1, &argv[1], prefix);
80 	if (ret < 0) {
81 		if (errno == EPERM)
82 			die("Permission error - are you root?");
83 	}
84 
85 	return ret;
86 }
87