qemu-ga: move channel/transport functionality into wrapper class
[qemu/kevin.git] / qemu-ga.c
blob2e8af02f7ea2e633e115d6c15d2fba3faf9c36ec
1 /*
2 * QEMU Guest Agent
4 * Copyright IBM Corp. 2011
6 * Authors:
7 * Adam Litke <aglitke@linux.vnet.ibm.com>
8 * Michael Roth <mdroth@linux.vnet.ibm.com>
10 * This work is licensed under the terms of the GNU GPL, version 2 or later.
11 * See the COPYING file in the top-level directory.
13 #include <stdlib.h>
14 #include <stdio.h>
15 #include <stdbool.h>
16 #include <glib.h>
17 #include <getopt.h>
18 #include <syslog.h>
19 #include "json-streamer.h"
20 #include "json-parser.h"
21 #include "qint.h"
22 #include "qjson.h"
23 #include "qga/guest-agent-core.h"
24 #include "module.h"
25 #include "signal.h"
26 #include "qerror.h"
27 #include "error_int.h"
28 #include "qapi/qmp-core.h"
29 #include "qga/channel.h"
31 #define QGA_VIRTIO_PATH_DEFAULT "/dev/virtio-ports/org.qemu.guest_agent.0"
32 #define QGA_PIDFILE_DEFAULT "/var/run/qemu-ga.pid"
34 struct GAState {
35 JSONMessageParser parser;
36 GMainLoop *main_loop;
37 GAChannel *channel;
38 bool virtio; /* fastpath to check for virtio to deal with poll() quirks */
39 GACommandState *command_state;
40 GLogLevelFlags log_level;
41 FILE *log_file;
42 bool logging_enabled;
45 static struct GAState *ga_state;
47 static void quit_handler(int sig)
49 g_debug("received signal num %d, quitting", sig);
51 if (g_main_loop_is_running(ga_state->main_loop)) {
52 g_main_loop_quit(ga_state->main_loop);
56 static gboolean register_signal_handlers(void)
58 struct sigaction sigact;
59 int ret;
61 memset(&sigact, 0, sizeof(struct sigaction));
62 sigact.sa_handler = quit_handler;
64 ret = sigaction(SIGINT, &sigact, NULL);
65 if (ret == -1) {
66 g_error("error configuring signal handler: %s", strerror(errno));
67 return false;
69 ret = sigaction(SIGTERM, &sigact, NULL);
70 if (ret == -1) {
71 g_error("error configuring signal handler: %s", strerror(errno));
72 return false;
74 return true;
77 static void usage(const char *cmd)
79 printf(
80 "Usage: %s -c <channel_opts>\n"
81 "QEMU Guest Agent %s\n"
82 "\n"
83 " -m, --method transport method: one of unix-listen, virtio-serial, or\n"
84 " isa-serial (virtio-serial is the default)\n"
85 " -p, --path device/socket path (%s is the default for virtio-serial)\n"
86 " -l, --logfile set logfile path, logs to stderr by default\n"
87 " -f, --pidfile specify pidfile (default is %s)\n"
88 " -v, --verbose log extra debugging information\n"
89 " -V, --version print version information and exit\n"
90 " -d, --daemonize become a daemon\n"
91 " -b, --blacklist comma-separated list of RPCs to disable (no spaces, \"?\""
92 " to list available RPCs)\n"
93 " -h, --help display this help and exit\n"
94 "\n"
95 "Report bugs to <mdroth@linux.vnet.ibm.com>\n"
96 , cmd, QGA_VERSION, QGA_VIRTIO_PATH_DEFAULT, QGA_PIDFILE_DEFAULT);
99 static const char *ga_log_level_str(GLogLevelFlags level)
101 switch (level & G_LOG_LEVEL_MASK) {
102 case G_LOG_LEVEL_ERROR:
103 return "error";
104 case G_LOG_LEVEL_CRITICAL:
105 return "critical";
106 case G_LOG_LEVEL_WARNING:
107 return "warning";
108 case G_LOG_LEVEL_MESSAGE:
109 return "message";
110 case G_LOG_LEVEL_INFO:
111 return "info";
112 case G_LOG_LEVEL_DEBUG:
113 return "debug";
114 default:
115 return "user";
119 bool ga_logging_enabled(GAState *s)
121 return s->logging_enabled;
124 void ga_disable_logging(GAState *s)
126 s->logging_enabled = false;
129 void ga_enable_logging(GAState *s)
131 s->logging_enabled = true;
134 static void ga_log(const gchar *domain, GLogLevelFlags level,
135 const gchar *msg, gpointer opaque)
137 GAState *s = opaque;
138 GTimeVal time;
139 const char *level_str = ga_log_level_str(level);
141 if (!ga_logging_enabled(s)) {
142 return;
145 level &= G_LOG_LEVEL_MASK;
146 if (domain && strcmp(domain, "syslog") == 0) {
147 syslog(LOG_INFO, "%s: %s", level_str, msg);
148 } else if (level & s->log_level) {
149 g_get_current_time(&time);
150 fprintf(s->log_file,
151 "%lu.%lu: %s: %s\n", time.tv_sec, time.tv_usec, level_str, msg);
152 fflush(s->log_file);
156 static void become_daemon(const char *pidfile)
158 pid_t pid, sid;
159 int pidfd;
160 char *pidstr = NULL;
162 pid = fork();
163 if (pid < 0) {
164 exit(EXIT_FAILURE);
166 if (pid > 0) {
167 exit(EXIT_SUCCESS);
170 pidfd = open(pidfile, O_CREAT|O_WRONLY|O_EXCL, S_IRUSR|S_IWUSR);
171 if (pidfd == -1) {
172 g_critical("Cannot create pid file, %s", strerror(errno));
173 exit(EXIT_FAILURE);
176 if (asprintf(&pidstr, "%d", getpid()) == -1) {
177 g_critical("Cannot allocate memory");
178 goto fail;
180 if (write(pidfd, pidstr, strlen(pidstr)) != strlen(pidstr)) {
181 free(pidstr);
182 g_critical("Failed to write pid file");
183 goto fail;
186 umask(0);
187 sid = setsid();
188 if (sid < 0) {
189 goto fail;
191 if ((chdir("/")) < 0) {
192 goto fail;
195 close(STDIN_FILENO);
196 close(STDOUT_FILENO);
197 close(STDERR_FILENO);
198 free(pidstr);
199 return;
201 fail:
202 unlink(pidfile);
203 g_critical("failed to daemonize");
204 exit(EXIT_FAILURE);
207 static int send_response(GAState *s, QObject *payload)
209 const char *buf;
210 QString *payload_qstr;
211 GIOStatus status;
213 g_assert(payload && s->channel);
215 payload_qstr = qobject_to_json(payload);
216 if (!payload_qstr) {
217 return -EINVAL;
220 qstring_append_chr(payload_qstr, '\n');
221 buf = qstring_get_str(payload_qstr);
222 status = ga_channel_write_all(s->channel, buf, strlen(buf));
223 QDECREF(payload_qstr);
224 if (status != G_IO_STATUS_NORMAL) {
225 return -EIO;
228 return 0;
231 static void process_command(GAState *s, QDict *req)
233 QObject *rsp = NULL;
234 int ret;
236 g_assert(req);
237 g_debug("processing command");
238 rsp = qmp_dispatch(QOBJECT(req));
239 if (rsp) {
240 ret = send_response(s, rsp);
241 if (ret) {
242 g_warning("error sending response: %s", strerror(ret));
244 qobject_decref(rsp);
245 } else {
246 g_warning("error getting response");
250 /* handle requests/control events coming in over the channel */
251 static void process_event(JSONMessageParser *parser, QList *tokens)
253 GAState *s = container_of(parser, GAState, parser);
254 QObject *obj;
255 QDict *qdict;
256 Error *err = NULL;
257 int ret;
259 g_assert(s && parser);
261 g_debug("process_event: called");
262 obj = json_parser_parse_err(tokens, NULL, &err);
263 if (err || !obj || qobject_type(obj) != QTYPE_QDICT) {
264 qobject_decref(obj);
265 qdict = qdict_new();
266 if (!err) {
267 g_warning("failed to parse event: unknown error");
268 error_set(&err, QERR_JSON_PARSING);
269 } else {
270 g_warning("failed to parse event: %s", error_get_pretty(err));
272 qdict_put_obj(qdict, "error", error_get_qobject(err));
273 error_free(err);
274 } else {
275 qdict = qobject_to_qdict(obj);
278 g_assert(qdict);
280 /* handle host->guest commands */
281 if (qdict_haskey(qdict, "execute")) {
282 process_command(s, qdict);
283 } else {
284 if (!qdict_haskey(qdict, "error")) {
285 QDECREF(qdict);
286 qdict = qdict_new();
287 g_warning("unrecognized payload format");
288 error_set(&err, QERR_UNSUPPORTED);
289 qdict_put_obj(qdict, "error", error_get_qobject(err));
290 error_free(err);
292 ret = send_response(s, QOBJECT(qdict));
293 if (ret) {
294 g_warning("error sending error response: %s", strerror(ret));
298 QDECREF(qdict);
301 /* false return signals GAChannel to close the current client connection */
302 static gboolean channel_event_cb(GIOCondition condition, gpointer data)
304 GAState *s = data;
305 gchar buf[QGA_READ_COUNT_DEFAULT+1];
306 gsize count;
307 GError *err = NULL;
308 GIOStatus status = ga_channel_read(s->channel, buf, QGA_READ_COUNT_DEFAULT, &count);
309 if (err != NULL) {
310 g_warning("error reading channel: %s", err->message);
311 g_error_free(err);
312 return false;
314 switch (status) {
315 case G_IO_STATUS_ERROR:
316 g_warning("error reading channel");
317 return false;
318 case G_IO_STATUS_NORMAL:
319 buf[count] = 0;
320 g_debug("read data, count: %d, data: %s", (int)count, buf);
321 json_message_parser_feed(&s->parser, (char *)buf, (int)count);
322 break;
323 case G_IO_STATUS_EOF:
324 g_debug("received EOF");
325 if (!s->virtio) {
326 return false;
328 case G_IO_STATUS_AGAIN:
329 /* virtio causes us to spin here when no process is attached to
330 * host-side chardev. sleep a bit to mitigate this
332 if (s->virtio) {
333 usleep(100*1000);
335 return true;
336 default:
337 g_warning("unknown channel read status, closing");
338 return false;
340 return true;
343 static gboolean channel_init(GAState *s, const gchar *method, const gchar *path)
345 GAChannelMethod channel_method;
347 if (method == NULL) {
348 method = "virtio-serial";
351 if (path == NULL) {
352 if (strcmp(method, "virtio-serial") != 0) {
353 g_critical("must specify a path for this channel");
354 return false;
356 /* try the default path for the virtio-serial port */
357 path = QGA_VIRTIO_PATH_DEFAULT;
360 if (strcmp(method, "virtio-serial") == 0) {
361 s->virtio = true; /* virtio requires special handling in some cases */
362 channel_method = GA_CHANNEL_VIRTIO_SERIAL;
363 } else if (strcmp(method, "isa-serial") == 0) {
364 channel_method = GA_CHANNEL_ISA_SERIAL;
365 } else if (strcmp(method, "unix-listen") == 0) {
366 channel_method = GA_CHANNEL_UNIX_LISTEN;
367 } else {
368 g_critical("unsupported channel method/type: %s", method);
369 return false;
372 s->channel = ga_channel_new(channel_method, path, channel_event_cb, s);
373 if (!s->channel) {
374 g_critical("failed to create guest agent channel");
375 return false;
378 return true;
381 int main(int argc, char **argv)
383 const char *sopt = "hVvdm:p:l:f:b:";
384 const char *method = NULL, *path = NULL, *pidfile = QGA_PIDFILE_DEFAULT;
385 const struct option lopt[] = {
386 { "help", 0, NULL, 'h' },
387 { "version", 0, NULL, 'V' },
388 { "logfile", 0, NULL, 'l' },
389 { "pidfile", 0, NULL, 'f' },
390 { "verbose", 0, NULL, 'v' },
391 { "method", 0, NULL, 'm' },
392 { "path", 0, NULL, 'p' },
393 { "daemonize", 0, NULL, 'd' },
394 { "blacklist", 0, NULL, 'b' },
395 { NULL, 0, NULL, 0 }
397 int opt_ind = 0, ch, daemonize = 0, i, j, len;
398 GLogLevelFlags log_level = G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL;
399 FILE *log_file = stderr;
400 GAState *s;
402 module_call_init(MODULE_INIT_QAPI);
404 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
405 switch (ch) {
406 case 'm':
407 method = optarg;
408 break;
409 case 'p':
410 path = optarg;
411 break;
412 case 'l':
413 log_file = fopen(optarg, "a");
414 if (!log_file) {
415 g_critical("unable to open specified log file: %s",
416 strerror(errno));
417 return EXIT_FAILURE;
419 break;
420 case 'f':
421 pidfile = optarg;
422 break;
423 case 'v':
424 /* enable all log levels */
425 log_level = G_LOG_LEVEL_MASK;
426 break;
427 case 'V':
428 printf("QEMU Guest Agent %s\n", QGA_VERSION);
429 return 0;
430 case 'd':
431 daemonize = 1;
432 break;
433 case 'b': {
434 char **list_head, **list;
435 if (*optarg == '?') {
436 list_head = list = qmp_get_command_list();
437 while (*list != NULL) {
438 printf("%s\n", *list);
439 g_free(*list);
440 list++;
442 g_free(list_head);
443 return 0;
445 for (j = 0, i = 0, len = strlen(optarg); i < len; i++) {
446 if (optarg[i] == ',') {
447 optarg[i] = 0;
448 qmp_disable_command(&optarg[j]);
449 g_debug("disabling command: %s", &optarg[j]);
450 j = i + 1;
453 if (j < i) {
454 qmp_disable_command(&optarg[j]);
455 g_debug("disabling command: %s", &optarg[j]);
457 break;
459 case 'h':
460 usage(argv[0]);
461 return 0;
462 case '?':
463 g_print("Unknown option, try '%s --help' for more information.\n",
464 argv[0]);
465 return EXIT_FAILURE;
469 if (daemonize) {
470 g_debug("starting daemon");
471 become_daemon(pidfile);
474 s = g_malloc0(sizeof(GAState));
475 s->log_file = log_file;
476 s->log_level = log_level;
477 g_log_set_default_handler(ga_log, s);
478 g_log_set_fatal_mask(NULL, G_LOG_LEVEL_ERROR);
479 s->logging_enabled = true;
480 s->command_state = ga_command_state_new();
481 ga_command_state_init(s, s->command_state);
482 ga_command_state_init_all(s->command_state);
483 json_message_parser_init(&s->parser, process_event);
484 ga_state = s;
485 if (!register_signal_handlers()) {
486 g_critical("failed to register signal handlers");
487 goto out_bad;
490 s->main_loop = g_main_loop_new(NULL, false);
491 if (!channel_init(ga_state, method, path)) {
492 g_critical("failed to initialize guest agent channel");
493 goto out_bad;
495 g_main_loop_run(ga_state->main_loop);
497 ga_command_state_cleanup_all(ga_state->command_state);
498 ga_channel_free(ga_state->channel);
500 if (daemonize) {
501 unlink(pidfile);
503 return 0;
505 out_bad:
506 if (daemonize) {
507 unlink(pidfile);
509 return EXIT_FAILURE;