4 * Copyright IBM Corp. 2011
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.
20 #include "qemu_socket.h"
21 #include "json-streamer.h"
22 #include "json-parser.h"
25 #include "qga/guest-agent-core.h"
29 #include "error_int.h"
30 #include "qapi/qmp-core.h"
32 #define QGA_VIRTIO_PATH_DEFAULT "/dev/virtio-ports/org.qemu.guest_agent.0"
33 #define QGA_PIDFILE_DEFAULT "/var/run/qemu-ga.pid"
34 #define QGA_BAUDRATE_DEFAULT B38400 /* for isa-serial channels */
35 #define QGA_TIMEOUT_DEFAULT 30*1000 /* ms */
38 JSONMessageParser parser;
40 GIOChannel *conn_channel;
41 GIOChannel *listen_channel;
44 bool virtio; /* fastpath to check for virtio to deal with poll() quirks */
45 GACommandState *command_state;
46 GLogLevelFlags log_level;
51 static struct GAState *ga_state;
53 static void quit_handler(int sig)
55 g_debug("received signal num %d, quitting", sig);
57 if (g_main_loop_is_running(ga_state->main_loop)) {
58 g_main_loop_quit(ga_state->main_loop);
62 static void register_signal_handlers(void)
64 struct sigaction sigact;
67 memset(&sigact, 0, sizeof(struct sigaction));
68 sigact.sa_handler = quit_handler;
70 ret = sigaction(SIGINT, &sigact, NULL);
72 g_error("error configuring signal handler: %s", strerror(errno));
75 ret = sigaction(SIGTERM, &sigact, NULL);
77 g_error("error configuring signal handler: %s", strerror(errno));
81 static void usage(const char *cmd)
84 "Usage: %s -c <channel_opts>\n"
85 "QEMU Guest Agent %s\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 " -d, --daemonize become a daemon\n"
95 " -b, --blacklist comma-separated list of RPCs to disable (no spaces, \"?\""
96 " to list available RPCs)\n"
97 " -h, --help display this help and exit\n"
100 , cmd, QGA_VERSION, QGA_VIRTIO_PATH_DEFAULT, QGA_PIDFILE_DEFAULT);
103 static void conn_channel_close(GAState *s);
105 static const char *ga_log_level_str(GLogLevelFlags level)
107 switch (level & G_LOG_LEVEL_MASK) {
108 case G_LOG_LEVEL_ERROR:
110 case G_LOG_LEVEL_CRITICAL:
112 case G_LOG_LEVEL_WARNING:
114 case G_LOG_LEVEL_MESSAGE:
116 case G_LOG_LEVEL_INFO:
118 case G_LOG_LEVEL_DEBUG:
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)
145 const char *level_str = ga_log_level_str(level);
147 if (!ga_logging_enabled(s)) {
151 level &= G_LOG_LEVEL_MASK;
152 if (domain && strcmp(domain, "syslog") == 0) {
153 syslog(LOG_INFO, "%s: %s", level_str, msg);
154 } else if (level & s->log_level) {
155 g_get_current_time(&time);
157 "%lu.%lu: %s: %s\n", time.tv_sec, time.tv_usec, level_str, msg);
162 static void become_daemon(const char *pidfile)
176 pidfd = open(pidfile, O_CREAT|O_WRONLY|O_EXCL, S_IRUSR|S_IWUSR);
178 g_critical("Cannot create pid file, %s", strerror(errno));
182 if (asprintf(&pidstr, "%d", getpid()) == -1) {
183 g_critical("Cannot allocate memory");
186 if (write(pidfd, pidstr, strlen(pidstr)) != strlen(pidstr)) {
188 g_critical("Failed to write pid file");
197 if ((chdir("/")) < 0) {
202 close(STDOUT_FILENO);
203 close(STDERR_FILENO);
209 g_critical("failed to daemonize");
213 static int conn_channel_send_buf(GIOChannel *channel, const char *buf,
221 status = g_io_channel_write_chars(channel, buf, count, &written, &err);
222 g_debug("sending data, count: %d", (int)count);
224 g_warning("error sending newline: %s", err->message);
227 if (status == G_IO_STATUS_ERROR || status == G_IO_STATUS_EOF) {
231 if (status == G_IO_STATUS_NORMAL) {
239 static int conn_channel_send_payload(GIOChannel *channel, QObject *payload)
243 QString *payload_qstr;
246 g_assert(payload && channel);
248 payload_qstr = qobject_to_json(payload);
253 qstring_append_chr(payload_qstr, '\n');
254 buf = qstring_get_str(payload_qstr);
255 ret = conn_channel_send_buf(channel, buf, strlen(buf));
260 g_io_channel_flush(channel, &err);
262 g_warning("error flushing payload: %s", err->message);
268 QDECREF(payload_qstr);
275 static void process_command(GAState *s, QDict *req)
281 g_debug("processing command");
282 rsp = qmp_dispatch(QOBJECT(req));
284 ret = conn_channel_send_payload(s->conn_channel, rsp);
286 g_warning("error sending payload: %s", strerror(ret));
290 g_warning("error getting response");
294 /* handle requests/control events coming in over the channel */
295 static void process_event(JSONMessageParser *parser, QList *tokens)
297 GAState *s = container_of(parser, GAState, parser);
303 g_assert(s && parser);
305 g_debug("process_event: called");
306 obj = json_parser_parse_err(tokens, NULL, &err);
307 if (err || !obj || qobject_type(obj) != QTYPE_QDICT) {
311 g_warning("failed to parse event: unknown error");
312 error_set(&err, QERR_JSON_PARSING);
314 g_warning("failed to parse event: %s", error_get_pretty(err));
316 qdict_put_obj(qdict, "error", error_get_qobject(err));
319 qdict = qobject_to_qdict(obj);
324 /* handle host->guest commands */
325 if (qdict_haskey(qdict, "execute")) {
326 process_command(s, qdict);
328 if (!qdict_haskey(qdict, "error")) {
331 g_warning("unrecognized payload format");
332 error_set(&err, QERR_UNSUPPORTED);
333 qdict_put_obj(qdict, "error", error_get_qobject(err));
336 ret = conn_channel_send_payload(s->conn_channel, QOBJECT(qdict));
338 g_warning("error sending payload: %s", strerror(ret));
345 static gboolean conn_channel_read(GIOChannel *channel, GIOCondition condition,
352 memset(buf, 0, 1024);
353 GIOStatus status = g_io_channel_read_chars(channel, buf, 1024,
356 g_warning("error reading channel: %s", err->message);
357 conn_channel_close(s);
362 case G_IO_STATUS_ERROR:
363 g_warning("problem");
365 case G_IO_STATUS_NORMAL:
366 g_debug("read data, count: %d, data: %s", (int)count, buf);
367 json_message_parser_feed(&s->parser, (char *)buf, (int)count);
368 case G_IO_STATUS_AGAIN:
369 /* virtio causes us to spin here when no process is attached to
370 * host-side chardev. sleep a bit to mitigate this
376 case G_IO_STATUS_EOF:
377 g_debug("received EOF");
378 conn_channel_close(s);
384 g_warning("unknown channel read status, closing");
385 conn_channel_close(s);
391 static int conn_channel_add(GAState *s, int fd)
393 GIOChannel *conn_channel;
396 g_assert(s && !s->conn_channel);
397 conn_channel = g_io_channel_unix_new(fd);
398 g_assert(conn_channel);
399 g_io_channel_set_encoding(conn_channel, NULL, &err);
401 g_warning("error setting channel encoding to binary");
405 g_io_add_watch(conn_channel, G_IO_IN | G_IO_HUP,
406 conn_channel_read, s);
407 s->conn_channel = conn_channel;
411 static gboolean listen_channel_accept(GIOChannel *channel,
412 GIOCondition condition, gpointer data)
415 g_assert(channel != NULL);
417 bool accepted = false;
418 struct sockaddr_un addr;
419 socklen_t addrlen = sizeof(addr);
421 conn_fd = qemu_accept(g_io_channel_unix_get_fd(s->listen_channel),
422 (struct sockaddr *)&addr, &addrlen);
424 g_warning("error converting fd to gsocket: %s", strerror(errno));
427 fcntl(conn_fd, F_SETFL, O_NONBLOCK);
428 ret = conn_channel_add(s, conn_fd);
430 g_warning("error setting up connection");
436 /* only accept 1 connection at a time */
440 /* start polling for readable events on listen fd, new==true
441 * indicates we should use the existing s->listen_channel
443 static int listen_channel_add(GAState *s, int listen_fd, bool new)
446 s->listen_channel = g_io_channel_unix_new(listen_fd);
448 g_io_add_watch(s->listen_channel, G_IO_IN,
449 listen_channel_accept, s);
453 /* cleanup state for closed connection/session, start accepting new
454 * connections if we're in listening mode
456 static void conn_channel_close(GAState *s)
458 if (strcmp(s->method, "unix-listen") == 0) {
459 g_io_channel_shutdown(s->conn_channel, true, NULL);
460 listen_channel_add(s, 0, false);
461 } else if (strcmp(s->method, "virtio-serial") == 0) {
462 /* we spin on EOF for virtio-serial, so back off a bit. also,
463 * dont close the connection in this case, it'll resume normal
464 * operation when another process connects to host chardev
469 g_io_channel_unref(s->conn_channel);
470 s->conn_channel = NULL;
475 static void init_guest_agent(GAState *s)
480 if (s->method == NULL) {
481 /* try virtio-serial as our default */
482 s->method = "virtio-serial";
485 if (s->path == NULL) {
486 if (strcmp(s->method, "virtio-serial") != 0) {
487 g_critical("must specify a path for this channel");
490 /* try the default path for the virtio-serial port */
491 s->path = QGA_VIRTIO_PATH_DEFAULT;
494 if (strcmp(s->method, "virtio-serial") == 0) {
496 fd = qemu_open(s->path, O_RDWR | O_NONBLOCK | O_ASYNC);
498 g_critical("error opening channel: %s", strerror(errno));
501 ret = conn_channel_add(s, fd);
503 g_critical("error adding channel to main loop");
506 } else if (strcmp(s->method, "isa-serial") == 0) {
507 fd = qemu_open(s->path, O_RDWR | O_NOCTTY);
509 g_critical("error opening channel: %s", strerror(errno));
513 /* set up serial port for non-canonical, dumb byte streaming */
514 tio.c_iflag &= ~(IGNBRK | BRKINT | IGNPAR | PARMRK | INPCK | ISTRIP |
515 INLCR | IGNCR | ICRNL | IXON | IXOFF | IXANY |
519 tio.c_cflag |= QGA_BAUDRATE_DEFAULT;
520 /* 1 available byte min or reads will block (we'll set non-blocking
521 * elsewhere, else we have to deal with read()=0 instead)
525 /* flush everything waiting for read/xmit, it's garbage at this point */
526 tcflush(fd, TCIFLUSH);
527 tcsetattr(fd, TCSANOW, &tio);
528 ret = conn_channel_add(s, fd);
530 g_error("error adding channel to main loop");
532 } else if (strcmp(s->method, "unix-listen") == 0) {
533 fd = unix_listen(s->path, NULL, strlen(s->path));
535 g_critical("error opening path: %s", strerror(errno));
538 ret = listen_channel_add(s, fd, true);
540 g_critical("error binding/listening to specified socket");
544 g_critical("unsupported channel method/type: %s", s->method);
548 json_message_parser_init(&s->parser, process_event);
549 s->main_loop = g_main_loop_new(NULL, false);
552 int main(int argc, char **argv)
554 const char *sopt = "hVvdm:p:l:f:b:";
555 const char *method = NULL, *path = NULL, *pidfile = QGA_PIDFILE_DEFAULT;
556 const struct option lopt[] = {
557 { "help", 0, NULL, 'h' },
558 { "version", 0, NULL, 'V' },
559 { "logfile", 0, NULL, 'l' },
560 { "pidfile", 0, NULL, 'f' },
561 { "verbose", 0, NULL, 'v' },
562 { "method", 0, NULL, 'm' },
563 { "path", 0, NULL, 'p' },
564 { "daemonize", 0, NULL, 'd' },
565 { "blacklist", 0, NULL, 'b' },
568 int opt_ind = 0, ch, daemonize = 0, i, j, len;
569 GLogLevelFlags log_level = G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL;
570 FILE *log_file = stderr;
573 module_call_init(MODULE_INIT_QAPI);
575 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
584 log_file = fopen(optarg, "a");
586 g_critical("unable to open specified log file: %s",
595 /* enable all log levels */
596 log_level = G_LOG_LEVEL_MASK;
599 printf("QEMU Guest Agent %s\n", QGA_VERSION);
605 char **list_head, **list;
606 if (*optarg == '?') {
607 list_head = list = qmp_get_command_list();
608 while (*list != NULL) {
609 printf("%s\n", *list);
616 for (j = 0, i = 0, len = strlen(optarg); i < len; i++) {
617 if (optarg[i] == ',') {
619 qmp_disable_command(&optarg[j]);
620 g_debug("disabling command: %s", &optarg[j]);
625 qmp_disable_command(&optarg[j]);
626 g_debug("disabling command: %s", &optarg[j]);
634 g_print("Unknown option, try '%s --help' for more information.\n",
641 g_debug("starting daemon");
642 become_daemon(pidfile);
645 s = g_malloc0(sizeof(GAState));
646 s->conn_channel = NULL;
649 s->log_file = log_file;
650 s->log_level = log_level;
651 g_log_set_default_handler(ga_log, s);
652 g_log_set_fatal_mask(NULL, G_LOG_LEVEL_ERROR);
653 s->logging_enabled = true;
654 s->command_state = ga_command_state_new();
655 ga_command_state_init(s, s->command_state);
656 ga_command_state_init_all(s->command_state);
659 init_guest_agent(ga_state);
660 register_signal_handlers();
662 g_main_loop_run(ga_state->main_loop);
664 ga_command_state_cleanup_all(ga_state->command_state);