Fix mismatching allocation and deallocation
[qemu/ar7.git] / qemu-ga.c
blob49320133c6edbe72817aaa1f63f44b9fb6b488db
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 <termios.h>
19 #include <syslog.h>
20 #include "qemu_socket.h"
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"
31 #define QGA_VIRTIO_PATH_DEFAULT "/dev/virtio-ports/org.qemu.guest_agent.0"
32 #define QGA_PIDFILE_DEFAULT "/var/run/qemu-ga.pid"
33 #define QGA_BAUDRATE_DEFAULT B38400 /* for isa-serial channels */
34 #define QGA_TIMEOUT_DEFAULT 30*1000 /* ms */
36 struct GAState {
37 JSONMessageParser parser;
38 GMainLoop *main_loop;
39 GIOChannel *conn_channel;
40 GIOChannel *listen_channel;
41 const char *path;
42 const char *method;
43 bool virtio; /* fastpath to check for virtio to deal with poll() quirks */
44 GACommandState *command_state;
45 GLogLevelFlags log_level;
46 FILE *log_file;
47 bool logging_enabled;
50 static struct GAState *ga_state;
52 static void quit_handler(int sig)
54 g_debug("received signal num %d, quitting", sig);
56 if (g_main_loop_is_running(ga_state->main_loop)) {
57 g_main_loop_quit(ga_state->main_loop);
61 static void register_signal_handlers(void)
63 struct sigaction sigact;
64 int ret;
66 memset(&sigact, 0, sizeof(struct sigaction));
67 sigact.sa_handler = quit_handler;
69 ret = sigaction(SIGINT, &sigact, NULL);
70 if (ret == -1) {
71 g_error("error configuring signal handler: %s", strerror(errno));
72 exit(EXIT_FAILURE);
74 ret = sigaction(SIGTERM, &sigact, NULL);
75 if (ret == -1) {
76 g_error("error configuring signal handler: %s", strerror(errno));
80 static void usage(const char *cmd)
82 printf(
83 "Usage: %s -c <channel_opts>\n"
84 "QEMU Guest Agent %s\n"
85 "\n"
86 " -m, --method transport method: one of unix-listen, virtio-serial, or\n"
87 " isa-serial (virtio-serial is the default)\n"
88 " -p, --path device/socket path (%s is the default for virtio-serial)\n"
89 " -l, --logfile set logfile path, logs to stderr by default\n"
90 " -f, --pidfile specify pidfile (default is %s)\n"
91 " -v, --verbose log extra debugging information\n"
92 " -V, --version print version information and exit\n"
93 " -d, --daemonize become a daemon\n"
94 " -h, --help display this help and exit\n"
95 "\n"
96 "Report bugs to <mdroth@linux.vnet.ibm.com>\n"
97 , cmd, QGA_VERSION, QGA_VIRTIO_PATH_DEFAULT, QGA_PIDFILE_DEFAULT);
100 static void conn_channel_close(GAState *s);
102 static const char *ga_log_level_str(GLogLevelFlags level)
104 switch (level & G_LOG_LEVEL_MASK) {
105 case G_LOG_LEVEL_ERROR:
106 return "error";
107 case G_LOG_LEVEL_CRITICAL:
108 return "critical";
109 case G_LOG_LEVEL_WARNING:
110 return "warning";
111 case G_LOG_LEVEL_MESSAGE:
112 return "message";
113 case G_LOG_LEVEL_INFO:
114 return "info";
115 case G_LOG_LEVEL_DEBUG:
116 return "debug";
117 default:
118 return "user";
122 bool ga_logging_enabled(GAState *s)
124 return s->logging_enabled;
127 void ga_disable_logging(GAState *s)
129 s->logging_enabled = false;
132 void ga_enable_logging(GAState *s)
134 s->logging_enabled = true;
137 static void ga_log(const gchar *domain, GLogLevelFlags level,
138 const gchar *msg, gpointer opaque)
140 GAState *s = opaque;
141 GTimeVal time;
142 const char *level_str = ga_log_level_str(level);
144 if (!ga_logging_enabled(s)) {
145 return;
148 level &= G_LOG_LEVEL_MASK;
149 if (domain && strcmp(domain, "syslog") == 0) {
150 syslog(LOG_INFO, "%s: %s", level_str, msg);
151 } else if (level & s->log_level) {
152 g_get_current_time(&time);
153 fprintf(s->log_file,
154 "%lu.%lu: %s: %s\n", time.tv_sec, time.tv_usec, level_str, msg);
155 fflush(s->log_file);
159 static void become_daemon(const char *pidfile)
161 pid_t pid, sid;
162 int pidfd;
163 char *pidstr = NULL;
165 pid = fork();
166 if (pid < 0) {
167 exit(EXIT_FAILURE);
169 if (pid > 0) {
170 exit(EXIT_SUCCESS);
173 pidfd = open(pidfile, O_CREAT|O_WRONLY|O_EXCL, S_IRUSR|S_IWUSR);
174 if (pidfd == -1) {
175 g_critical("Cannot create pid file, %s", strerror(errno));
176 exit(EXIT_FAILURE);
179 if (asprintf(&pidstr, "%d", getpid()) == -1) {
180 g_critical("Cannot allocate memory");
181 goto fail;
183 if (write(pidfd, pidstr, strlen(pidstr)) != strlen(pidstr)) {
184 free(pidstr);
185 g_critical("Failed to write pid file");
186 goto fail;
189 umask(0);
190 sid = setsid();
191 if (sid < 0) {
192 goto fail;
194 if ((chdir("/")) < 0) {
195 goto fail;
198 close(STDIN_FILENO);
199 close(STDOUT_FILENO);
200 close(STDERR_FILENO);
201 free(pidstr);
202 return;
204 fail:
205 unlink(pidfile);
206 g_critical("failed to daemonize");
207 exit(EXIT_FAILURE);
210 static int conn_channel_send_buf(GIOChannel *channel, const char *buf,
211 gsize count)
213 GError *err = NULL;
214 gsize written = 0;
215 GIOStatus status;
217 while (count) {
218 status = g_io_channel_write_chars(channel, buf, count, &written, &err);
219 g_debug("sending data, count: %d", (int)count);
220 if (err != NULL) {
221 g_warning("error sending newline: %s", err->message);
222 return err->code;
224 if (status == G_IO_STATUS_ERROR || status == G_IO_STATUS_EOF) {
225 return -EPIPE;
228 if (status == G_IO_STATUS_NORMAL) {
229 count -= written;
233 return 0;
236 static int conn_channel_send_payload(GIOChannel *channel, QObject *payload)
238 int ret = 0;
239 const char *buf;
240 QString *payload_qstr;
241 GError *err = NULL;
243 g_assert(payload && channel);
245 payload_qstr = qobject_to_json(payload);
246 if (!payload_qstr) {
247 return -EINVAL;
250 qstring_append_chr(payload_qstr, '\n');
251 buf = qstring_get_str(payload_qstr);
252 ret = conn_channel_send_buf(channel, buf, strlen(buf));
253 if (ret) {
254 goto out_free;
257 g_io_channel_flush(channel, &err);
258 if (err != NULL) {
259 g_warning("error flushing payload: %s", err->message);
260 ret = err->code;
261 goto out_free;
264 out_free:
265 QDECREF(payload_qstr);
266 if (err) {
267 g_error_free(err);
269 return ret;
272 static void process_command(GAState *s, QDict *req)
274 QObject *rsp = NULL;
275 int ret;
277 g_assert(req);
278 g_debug("processing command");
279 rsp = qmp_dispatch(QOBJECT(req));
280 if (rsp) {
281 ret = conn_channel_send_payload(s->conn_channel, rsp);
282 if (ret) {
283 g_warning("error sending payload: %s", strerror(ret));
285 qobject_decref(rsp);
286 } else {
287 g_warning("error getting response");
291 /* handle requests/control events coming in over the channel */
292 static void process_event(JSONMessageParser *parser, QList *tokens)
294 GAState *s = container_of(parser, GAState, parser);
295 QObject *obj;
296 QDict *qdict;
297 Error *err = NULL;
298 int ret;
300 g_assert(s && parser);
302 g_debug("process_event: called");
303 obj = json_parser_parse_err(tokens, NULL, &err);
304 if (err || !obj || qobject_type(obj) != QTYPE_QDICT) {
305 qobject_decref(obj);
306 qdict = qdict_new();
307 if (!err) {
308 g_warning("failed to parse event: unknown error");
309 error_set(&err, QERR_JSON_PARSING);
310 } else {
311 g_warning("failed to parse event: %s", error_get_pretty(err));
313 qdict_put_obj(qdict, "error", error_get_qobject(err));
314 error_free(err);
315 } else {
316 qdict = qobject_to_qdict(obj);
319 g_assert(qdict);
321 /* handle host->guest commands */
322 if (qdict_haskey(qdict, "execute")) {
323 process_command(s, qdict);
324 } else {
325 if (!qdict_haskey(qdict, "error")) {
326 QDECREF(qdict);
327 qdict = qdict_new();
328 g_warning("unrecognized payload format");
329 error_set(&err, QERR_UNSUPPORTED);
330 qdict_put_obj(qdict, "error", error_get_qobject(err));
331 error_free(err);
333 ret = conn_channel_send_payload(s->conn_channel, QOBJECT(qdict));
334 if (ret) {
335 g_warning("error sending payload: %s", strerror(ret));
339 QDECREF(qdict);
342 static gboolean conn_channel_read(GIOChannel *channel, GIOCondition condition,
343 gpointer data)
345 GAState *s = data;
346 gchar buf[1024];
347 gsize count;
348 GError *err = NULL;
349 memset(buf, 0, 1024);
350 GIOStatus status = g_io_channel_read_chars(channel, buf, 1024,
351 &count, &err);
352 if (err != NULL) {
353 g_warning("error reading channel: %s", err->message);
354 conn_channel_close(s);
355 g_error_free(err);
356 return false;
358 switch (status) {
359 case G_IO_STATUS_ERROR:
360 g_warning("problem");
361 return false;
362 case G_IO_STATUS_NORMAL:
363 g_debug("read data, count: %d, data: %s", (int)count, buf);
364 json_message_parser_feed(&s->parser, (char *)buf, (int)count);
365 case G_IO_STATUS_AGAIN:
366 /* virtio causes us to spin here when no process is attached to
367 * host-side chardev. sleep a bit to mitigate this
369 if (s->virtio) {
370 usleep(100*1000);
372 return true;
373 case G_IO_STATUS_EOF:
374 g_debug("received EOF");
375 conn_channel_close(s);
376 if (s->virtio) {
377 return true;
379 return false;
380 default:
381 g_warning("unknown channel read status, closing");
382 conn_channel_close(s);
383 return false;
385 return true;
388 static int conn_channel_add(GAState *s, int fd)
390 GIOChannel *conn_channel;
391 GError *err = NULL;
393 g_assert(s && !s->conn_channel);
394 conn_channel = g_io_channel_unix_new(fd);
395 g_assert(conn_channel);
396 g_io_channel_set_encoding(conn_channel, NULL, &err);
397 if (err != NULL) {
398 g_warning("error setting channel encoding to binary");
399 g_error_free(err);
400 return -1;
402 g_io_add_watch(conn_channel, G_IO_IN | G_IO_HUP,
403 conn_channel_read, s);
404 s->conn_channel = conn_channel;
405 return 0;
408 static gboolean listen_channel_accept(GIOChannel *channel,
409 GIOCondition condition, gpointer data)
411 GAState *s = data;
412 g_assert(channel != NULL);
413 int ret, conn_fd;
414 bool accepted = false;
415 struct sockaddr_un addr;
416 socklen_t addrlen = sizeof(addr);
418 conn_fd = qemu_accept(g_io_channel_unix_get_fd(s->listen_channel),
419 (struct sockaddr *)&addr, &addrlen);
420 if (conn_fd == -1) {
421 g_warning("error converting fd to gsocket: %s", strerror(errno));
422 goto out;
424 fcntl(conn_fd, F_SETFL, O_NONBLOCK);
425 ret = conn_channel_add(s, conn_fd);
426 if (ret) {
427 g_warning("error setting up connection");
428 goto out;
430 accepted = true;
432 out:
433 /* only accept 1 connection at a time */
434 return !accepted;
437 /* start polling for readable events on listen fd, new==true
438 * indicates we should use the existing s->listen_channel
440 static int listen_channel_add(GAState *s, int listen_fd, bool new)
442 if (new) {
443 s->listen_channel = g_io_channel_unix_new(listen_fd);
445 g_io_add_watch(s->listen_channel, G_IO_IN,
446 listen_channel_accept, s);
447 return 0;
450 /* cleanup state for closed connection/session, start accepting new
451 * connections if we're in listening mode
453 static void conn_channel_close(GAState *s)
455 if (strcmp(s->method, "unix-listen") == 0) {
456 g_io_channel_shutdown(s->conn_channel, true, NULL);
457 listen_channel_add(s, 0, false);
458 } else if (strcmp(s->method, "virtio-serial") == 0) {
459 /* we spin on EOF for virtio-serial, so back off a bit. also,
460 * dont close the connection in this case, it'll resume normal
461 * operation when another process connects to host chardev
463 usleep(100*1000);
464 goto out_noclose;
466 g_io_channel_unref(s->conn_channel);
467 s->conn_channel = NULL;
468 out_noclose:
469 return;
472 static void init_guest_agent(GAState *s)
474 struct termios tio;
475 int ret, fd;
477 if (s->method == NULL) {
478 /* try virtio-serial as our default */
479 s->method = "virtio-serial";
482 if (s->path == NULL) {
483 if (strcmp(s->method, "virtio-serial") != 0) {
484 g_critical("must specify a path for this channel");
485 exit(EXIT_FAILURE);
487 /* try the default path for the virtio-serial port */
488 s->path = QGA_VIRTIO_PATH_DEFAULT;
491 if (strcmp(s->method, "virtio-serial") == 0) {
492 s->virtio = true;
493 fd = qemu_open(s->path, O_RDWR | O_NONBLOCK | O_ASYNC);
494 if (fd == -1) {
495 g_critical("error opening channel: %s", strerror(errno));
496 exit(EXIT_FAILURE);
498 ret = conn_channel_add(s, fd);
499 if (ret) {
500 g_critical("error adding channel to main loop");
501 exit(EXIT_FAILURE);
503 } else if (strcmp(s->method, "isa-serial") == 0) {
504 fd = qemu_open(s->path, O_RDWR | O_NOCTTY);
505 if (fd == -1) {
506 g_critical("error opening channel: %s", strerror(errno));
507 exit(EXIT_FAILURE);
509 tcgetattr(fd, &tio);
510 /* set up serial port for non-canonical, dumb byte streaming */
511 tio.c_iflag &= ~(IGNBRK | BRKINT | IGNPAR | PARMRK | INPCK | ISTRIP |
512 INLCR | IGNCR | ICRNL | IXON | IXOFF | IXANY |
513 IMAXBEL);
514 tio.c_oflag = 0;
515 tio.c_lflag = 0;
516 tio.c_cflag |= QGA_BAUDRATE_DEFAULT;
517 /* 1 available byte min or reads will block (we'll set non-blocking
518 * elsewhere, else we have to deal with read()=0 instead)
520 tio.c_cc[VMIN] = 1;
521 tio.c_cc[VTIME] = 0;
522 /* flush everything waiting for read/xmit, it's garbage at this point */
523 tcflush(fd, TCIFLUSH);
524 tcsetattr(fd, TCSANOW, &tio);
525 ret = conn_channel_add(s, fd);
526 if (ret) {
527 g_error("error adding channel to main loop");
529 } else if (strcmp(s->method, "unix-listen") == 0) {
530 fd = unix_listen(s->path, NULL, strlen(s->path));
531 if (fd == -1) {
532 g_critical("error opening path: %s", strerror(errno));
533 exit(EXIT_FAILURE);
535 ret = listen_channel_add(s, fd, true);
536 if (ret) {
537 g_critical("error binding/listening to specified socket");
538 exit(EXIT_FAILURE);
540 } else {
541 g_critical("unsupported channel method/type: %s", s->method);
542 exit(EXIT_FAILURE);
545 json_message_parser_init(&s->parser, process_event);
546 s->main_loop = g_main_loop_new(NULL, false);
549 int main(int argc, char **argv)
551 const char *sopt = "hVvdm:p:l:f:";
552 const char *method = NULL, *path = NULL, *pidfile = QGA_PIDFILE_DEFAULT;
553 const struct option lopt[] = {
554 { "help", 0, NULL, 'h' },
555 { "version", 0, NULL, 'V' },
556 { "logfile", 0, NULL, 'l' },
557 { "pidfile", 0, NULL, 'f' },
558 { "verbose", 0, NULL, 'v' },
559 { "method", 0, NULL, 'm' },
560 { "path", 0, NULL, 'p' },
561 { "daemonize", 0, NULL, 'd' },
562 { NULL, 0, NULL, 0 }
564 int opt_ind = 0, ch, daemonize = 0;
565 GLogLevelFlags log_level = G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL;
566 FILE *log_file = stderr;
567 GAState *s;
569 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
570 switch (ch) {
571 case 'm':
572 method = optarg;
573 break;
574 case 'p':
575 path = optarg;
576 break;
577 case 'l':
578 log_file = fopen(optarg, "a");
579 if (!log_file) {
580 g_critical("unable to open specified log file: %s",
581 strerror(errno));
582 return EXIT_FAILURE;
584 break;
585 case 'f':
586 pidfile = optarg;
587 break;
588 case 'v':
589 /* enable all log levels */
590 log_level = G_LOG_LEVEL_MASK;
591 break;
592 case 'V':
593 printf("QEMU Guest Agent %s\n", QGA_VERSION);
594 return 0;
595 case 'd':
596 daemonize = 1;
597 break;
598 case 'h':
599 usage(argv[0]);
600 return 0;
601 case '?':
602 g_print("Unknown option, try '%s --help' for more information.\n",
603 argv[0]);
604 return EXIT_FAILURE;
608 if (daemonize) {
609 g_debug("starting daemon");
610 become_daemon(pidfile);
613 s = g_malloc0(sizeof(GAState));
614 s->conn_channel = NULL;
615 s->path = path;
616 s->method = method;
617 s->log_file = log_file;
618 s->log_level = log_level;
619 g_log_set_default_handler(ga_log, s);
620 g_log_set_fatal_mask(NULL, G_LOG_LEVEL_ERROR);
621 s->logging_enabled = true;
622 s->command_state = ga_command_state_new();
623 ga_command_state_init(s, s->command_state);
624 ga_command_state_init_all(s->command_state);
625 ga_state = s;
627 module_call_init(MODULE_INIT_QAPI);
628 init_guest_agent(ga_state);
629 register_signal_handlers();
631 g_main_loop_run(ga_state->main_loop);
633 ga_command_state_cleanup_all(ga_state->command_state);
634 unlink(pidfile);
636 return 0;