qemu-ga: fixes for win32 build of qemu-ga
[qemu/ar7.git] / qemu-ga.c
blob93ebc3e4718fd5831802a3de71c4593dc915f193
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 #ifndef _WIN32
19 #include <syslog.h>
20 #endif
21 #include "json-streamer.h"
22 #include "json-parser.h"
23 #include "qint.h"
24 #include "qjson.h"
25 #include "qga/guest-agent-core.h"
26 #include "module.h"
27 #include "signal.h"
28 #include "qerror.h"
29 #include "error_int.h"
30 #include "qapi/qmp-core.h"
31 #include "qga/channel.h"
33 #define QGA_VIRTIO_PATH_DEFAULT "/dev/virtio-ports/org.qemu.guest_agent.0"
34 #define QGA_PIDFILE_DEFAULT "/var/run/qemu-ga.pid"
36 struct GAState {
37 JSONMessageParser parser;
38 GMainLoop *main_loop;
39 GAChannel *channel;
40 bool virtio; /* fastpath to check for virtio to deal with poll() quirks */
41 GACommandState *command_state;
42 GLogLevelFlags log_level;
43 FILE *log_file;
44 bool logging_enabled;
47 static struct GAState *ga_state;
49 #ifndef _WIN32
50 static void quit_handler(int sig)
52 g_debug("received signal num %d, quitting", sig);
54 if (g_main_loop_is_running(ga_state->main_loop)) {
55 g_main_loop_quit(ga_state->main_loop);
59 static gboolean register_signal_handlers(void)
61 struct sigaction sigact;
62 int ret;
64 memset(&sigact, 0, sizeof(struct sigaction));
65 sigact.sa_handler = quit_handler;
67 ret = sigaction(SIGINT, &sigact, NULL);
68 if (ret == -1) {
69 g_error("error configuring signal handler: %s", strerror(errno));
70 return false;
72 ret = sigaction(SIGTERM, &sigact, NULL);
73 if (ret == -1) {
74 g_error("error configuring signal handler: %s", strerror(errno));
75 return false;
77 return true;
79 #endif
81 static void usage(const char *cmd)
83 printf(
84 "Usage: %s -c <channel_opts>\n"
85 "QEMU Guest Agent %s\n"
86 "\n"
87 " -m, --method transport method: one of unix-listen, virtio-serial, or\n"
88 " isa-serial (virtio-serial is the default)\n"
89 " -p, --path device/socket path (%s is the default for virtio-serial)\n"
90 " -l, --logfile set logfile path, logs to stderr by default\n"
91 " -f, --pidfile specify pidfile (default is %s)\n"
92 " -v, --verbose log extra debugging information\n"
93 " -V, --version print version information and exit\n"
94 #ifndef _WIN32
95 " -d, --daemonize become a daemon\n"
96 #endif
97 " -b, --blacklist comma-separated list of RPCs to disable (no spaces, \"?\""
98 " to list available RPCs)\n"
99 " -h, --help display this help and exit\n"
100 "\n"
101 "Report bugs to <mdroth@linux.vnet.ibm.com>\n"
102 , cmd, QGA_VERSION, QGA_VIRTIO_PATH_DEFAULT, QGA_PIDFILE_DEFAULT);
105 static const char *ga_log_level_str(GLogLevelFlags level)
107 switch (level & G_LOG_LEVEL_MASK) {
108 case G_LOG_LEVEL_ERROR:
109 return "error";
110 case G_LOG_LEVEL_CRITICAL:
111 return "critical";
112 case G_LOG_LEVEL_WARNING:
113 return "warning";
114 case G_LOG_LEVEL_MESSAGE:
115 return "message";
116 case G_LOG_LEVEL_INFO:
117 return "info";
118 case G_LOG_LEVEL_DEBUG:
119 return "debug";
120 default:
121 return "user";
125 bool ga_logging_enabled(GAState *s)
127 return s->logging_enabled;
130 void ga_disable_logging(GAState *s)
132 s->logging_enabled = false;
135 void ga_enable_logging(GAState *s)
137 s->logging_enabled = true;
140 static void ga_log(const gchar *domain, GLogLevelFlags level,
141 const gchar *msg, gpointer opaque)
143 GAState *s = opaque;
144 GTimeVal time;
145 const char *level_str = ga_log_level_str(level);
147 if (!ga_logging_enabled(s)) {
148 return;
151 level &= G_LOG_LEVEL_MASK;
152 #ifndef _WIN32
153 if (domain && strcmp(domain, "syslog") == 0) {
154 syslog(LOG_INFO, "%s: %s", level_str, msg);
155 } else if (level & s->log_level) {
156 #else
157 if (level & s->log_level) {
158 #endif
159 g_get_current_time(&time);
160 fprintf(s->log_file,
161 "%lu.%lu: %s: %s\n", time.tv_sec, time.tv_usec, level_str, msg);
162 fflush(s->log_file);
166 #ifndef _WIN32
167 static void become_daemon(const char *pidfile)
169 pid_t pid, sid;
170 int pidfd;
171 char *pidstr = NULL;
173 pid = fork();
174 if (pid < 0) {
175 exit(EXIT_FAILURE);
177 if (pid > 0) {
178 exit(EXIT_SUCCESS);
181 pidfd = open(pidfile, O_CREAT|O_WRONLY|O_EXCL, S_IRUSR|S_IWUSR);
182 if (pidfd == -1) {
183 g_critical("Cannot create pid file, %s", strerror(errno));
184 exit(EXIT_FAILURE);
187 if (asprintf(&pidstr, "%d", getpid()) == -1) {
188 g_critical("Cannot allocate memory");
189 goto fail;
191 if (write(pidfd, pidstr, strlen(pidstr)) != strlen(pidstr)) {
192 free(pidstr);
193 g_critical("Failed to write pid file");
194 goto fail;
197 umask(0);
198 sid = setsid();
199 if (sid < 0) {
200 goto fail;
202 if ((chdir("/")) < 0) {
203 goto fail;
206 close(STDIN_FILENO);
207 close(STDOUT_FILENO);
208 close(STDERR_FILENO);
209 free(pidstr);
210 return;
212 fail:
213 unlink(pidfile);
214 g_critical("failed to daemonize");
215 exit(EXIT_FAILURE);
217 #endif
219 static int send_response(GAState *s, QObject *payload)
221 const char *buf;
222 QString *payload_qstr;
223 GIOStatus status;
225 g_assert(payload && s->channel);
227 payload_qstr = qobject_to_json(payload);
228 if (!payload_qstr) {
229 return -EINVAL;
232 qstring_append_chr(payload_qstr, '\n');
233 buf = qstring_get_str(payload_qstr);
234 status = ga_channel_write_all(s->channel, buf, strlen(buf));
235 QDECREF(payload_qstr);
236 if (status != G_IO_STATUS_NORMAL) {
237 return -EIO;
240 return 0;
243 static void process_command(GAState *s, QDict *req)
245 QObject *rsp = NULL;
246 int ret;
248 g_assert(req);
249 g_debug("processing command");
250 rsp = qmp_dispatch(QOBJECT(req));
251 if (rsp) {
252 ret = send_response(s, rsp);
253 if (ret) {
254 g_warning("error sending response: %s", strerror(ret));
256 qobject_decref(rsp);
257 } else {
258 g_warning("error getting response");
262 /* handle requests/control events coming in over the channel */
263 static void process_event(JSONMessageParser *parser, QList *tokens)
265 GAState *s = container_of(parser, GAState, parser);
266 QObject *obj;
267 QDict *qdict;
268 Error *err = NULL;
269 int ret;
271 g_assert(s && parser);
273 g_debug("process_event: called");
274 obj = json_parser_parse_err(tokens, NULL, &err);
275 if (err || !obj || qobject_type(obj) != QTYPE_QDICT) {
276 qobject_decref(obj);
277 qdict = qdict_new();
278 if (!err) {
279 g_warning("failed to parse event: unknown error");
280 error_set(&err, QERR_JSON_PARSING);
281 } else {
282 g_warning("failed to parse event: %s", error_get_pretty(err));
284 qdict_put_obj(qdict, "error", error_get_qobject(err));
285 error_free(err);
286 } else {
287 qdict = qobject_to_qdict(obj);
290 g_assert(qdict);
292 /* handle host->guest commands */
293 if (qdict_haskey(qdict, "execute")) {
294 process_command(s, qdict);
295 } else {
296 if (!qdict_haskey(qdict, "error")) {
297 QDECREF(qdict);
298 qdict = qdict_new();
299 g_warning("unrecognized payload format");
300 error_set(&err, QERR_UNSUPPORTED);
301 qdict_put_obj(qdict, "error", error_get_qobject(err));
302 error_free(err);
304 ret = send_response(s, QOBJECT(qdict));
305 if (ret) {
306 g_warning("error sending error response: %s", strerror(ret));
310 QDECREF(qdict);
313 /* false return signals GAChannel to close the current client connection */
314 static gboolean channel_event_cb(GIOCondition condition, gpointer data)
316 GAState *s = data;
317 gchar buf[QGA_READ_COUNT_DEFAULT+1];
318 gsize count;
319 GError *err = NULL;
320 GIOStatus status = ga_channel_read(s->channel, buf, QGA_READ_COUNT_DEFAULT, &count);
321 if (err != NULL) {
322 g_warning("error reading channel: %s", err->message);
323 g_error_free(err);
324 return false;
326 switch (status) {
327 case G_IO_STATUS_ERROR:
328 g_warning("error reading channel");
329 return false;
330 case G_IO_STATUS_NORMAL:
331 buf[count] = 0;
332 g_debug("read data, count: %d, data: %s", (int)count, buf);
333 json_message_parser_feed(&s->parser, (char *)buf, (int)count);
334 break;
335 case G_IO_STATUS_EOF:
336 g_debug("received EOF");
337 if (!s->virtio) {
338 return false;
340 case G_IO_STATUS_AGAIN:
341 /* virtio causes us to spin here when no process is attached to
342 * host-side chardev. sleep a bit to mitigate this
344 if (s->virtio) {
345 usleep(100*1000);
347 return true;
348 default:
349 g_warning("unknown channel read status, closing");
350 return false;
352 return true;
355 static gboolean channel_init(GAState *s, const gchar *method, const gchar *path)
357 GAChannelMethod channel_method;
359 if (method == NULL) {
360 method = "virtio-serial";
363 if (path == NULL) {
364 if (strcmp(method, "virtio-serial") != 0) {
365 g_critical("must specify a path for this channel");
366 return false;
368 /* try the default path for the virtio-serial port */
369 path = QGA_VIRTIO_PATH_DEFAULT;
372 if (strcmp(method, "virtio-serial") == 0) {
373 s->virtio = true; /* virtio requires special handling in some cases */
374 channel_method = GA_CHANNEL_VIRTIO_SERIAL;
375 } else if (strcmp(method, "isa-serial") == 0) {
376 channel_method = GA_CHANNEL_ISA_SERIAL;
377 } else if (strcmp(method, "unix-listen") == 0) {
378 channel_method = GA_CHANNEL_UNIX_LISTEN;
379 } else {
380 g_critical("unsupported channel method/type: %s", method);
381 return false;
384 s->channel = ga_channel_new(channel_method, path, channel_event_cb, s);
385 if (!s->channel) {
386 g_critical("failed to create guest agent channel");
387 return false;
390 return true;
393 int main(int argc, char **argv)
395 const char *sopt = "hVvdm:p:l:f:b:";
396 const char *method = NULL, *path = NULL, *pidfile = QGA_PIDFILE_DEFAULT;
397 const struct option lopt[] = {
398 { "help", 0, NULL, 'h' },
399 { "version", 0, NULL, 'V' },
400 { "logfile", 0, NULL, 'l' },
401 { "pidfile", 0, NULL, 'f' },
402 { "verbose", 0, NULL, 'v' },
403 { "method", 0, NULL, 'm' },
404 { "path", 0, NULL, 'p' },
405 { "daemonize", 0, NULL, 'd' },
406 { "blacklist", 0, NULL, 'b' },
407 { NULL, 0, NULL, 0 }
409 int opt_ind = 0, ch, daemonize = 0, i, j, len;
410 GLogLevelFlags log_level = G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL;
411 FILE *log_file = stderr;
412 GAState *s;
414 module_call_init(MODULE_INIT_QAPI);
416 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
417 switch (ch) {
418 case 'm':
419 method = optarg;
420 break;
421 case 'p':
422 path = optarg;
423 break;
424 case 'l':
425 log_file = fopen(optarg, "a");
426 if (!log_file) {
427 g_critical("unable to open specified log file: %s",
428 strerror(errno));
429 return EXIT_FAILURE;
431 break;
432 case 'f':
433 pidfile = optarg;
434 break;
435 case 'v':
436 /* enable all log levels */
437 log_level = G_LOG_LEVEL_MASK;
438 break;
439 case 'V':
440 printf("QEMU Guest Agent %s\n", QGA_VERSION);
441 return 0;
442 case 'd':
443 daemonize = 1;
444 break;
445 case 'b': {
446 char **list_head, **list;
447 if (*optarg == '?') {
448 list_head = list = qmp_get_command_list();
449 while (*list != NULL) {
450 printf("%s\n", *list);
451 g_free(*list);
452 list++;
454 g_free(list_head);
455 return 0;
457 for (j = 0, i = 0, len = strlen(optarg); i < len; i++) {
458 if (optarg[i] == ',') {
459 optarg[i] = 0;
460 qmp_disable_command(&optarg[j]);
461 g_debug("disabling command: %s", &optarg[j]);
462 j = i + 1;
465 if (j < i) {
466 qmp_disable_command(&optarg[j]);
467 g_debug("disabling command: %s", &optarg[j]);
469 break;
471 case 'h':
472 usage(argv[0]);
473 return 0;
474 case '?':
475 g_print("Unknown option, try '%s --help' for more information.\n",
476 argv[0]);
477 return EXIT_FAILURE;
481 #ifndef _WIN32
482 if (daemonize) {
483 g_debug("starting daemon");
484 become_daemon(pidfile);
486 #endif
488 s = g_malloc0(sizeof(GAState));
489 s->log_file = log_file;
490 s->log_level = log_level;
491 g_log_set_default_handler(ga_log, s);
492 g_log_set_fatal_mask(NULL, G_LOG_LEVEL_ERROR);
493 s->logging_enabled = true;
494 s->command_state = ga_command_state_new();
495 ga_command_state_init(s, s->command_state);
496 ga_command_state_init_all(s->command_state);
497 json_message_parser_init(&s->parser, process_event);
498 ga_state = s;
499 #ifndef _WIN32
500 if (!register_signal_handlers()) {
501 g_critical("failed to register signal handlers");
502 goto out_bad;
504 #endif
506 s->main_loop = g_main_loop_new(NULL, false);
507 if (!channel_init(ga_state, method, path)) {
508 g_critical("failed to initialize guest agent channel");
509 goto out_bad;
511 g_main_loop_run(ga_state->main_loop);
513 ga_command_state_cleanup_all(ga_state->command_state);
514 ga_channel_free(ga_state->channel);
516 if (daemonize) {
517 unlink(pidfile);
519 return 0;
521 out_bad:
522 if (daemonize) {
523 unlink(pidfile);
525 return EXIT_FAILURE;