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.
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"
31 #include "qga/channel.h"
33 #include "qga/service-win32.h"
38 #define QGA_VIRTIO_PATH_DEFAULT "/dev/virtio-ports/org.qemu.guest_agent.0"
40 #define QGA_VIRTIO_PATH_DEFAULT "\\\\.\\Global\\org.qemu.guest_agent.0"
42 #define QGA_PIDFILE_DEFAULT "/var/run/qemu-ga.pid"
45 JSONMessageParser parser;
48 bool virtio; /* fastpath to check for virtio to deal with poll() quirks */
49 GACommandState *command_state;
50 GLogLevelFlags log_level;
58 static struct GAState *ga_state;
61 DWORD WINAPI service_ctrl_handler(DWORD ctrl, DWORD type, LPVOID data,
63 VOID WINAPI service_main(DWORD argc, TCHAR *argv[]);
66 static void quit_handler(int sig)
68 g_debug("received signal num %d, quitting", sig);
70 if (g_main_loop_is_running(ga_state->main_loop)) {
71 g_main_loop_quit(ga_state->main_loop);
76 static gboolean register_signal_handlers(void)
78 struct sigaction sigact;
81 memset(&sigact, 0, sizeof(struct sigaction));
82 sigact.sa_handler = quit_handler;
84 ret = sigaction(SIGINT, &sigact, NULL);
86 g_error("error configuring signal handler: %s", strerror(errno));
89 ret = sigaction(SIGTERM, &sigact, NULL);
91 g_error("error configuring signal handler: %s", strerror(errno));
98 static void usage(const char *cmd)
101 "Usage: %s -c <channel_opts>\n"
102 "QEMU Guest Agent %s\n"
104 " -m, --method transport method: one of unix-listen, virtio-serial, or\n"
105 " isa-serial (virtio-serial is the default)\n"
106 " -p, --path device/socket path (%s is the default for virtio-serial)\n"
107 " -l, --logfile set logfile path, logs to stderr by default\n"
108 " -f, --pidfile specify pidfile (default is %s)\n"
109 " -v, --verbose log extra debugging information\n"
110 " -V, --version print version information and exit\n"
111 " -d, --daemonize become a daemon\n"
113 " -s, --service service commands: install, uninstall\n"
115 " -b, --blacklist comma-separated list of RPCs to disable (no spaces, \"?\""
116 " to list available RPCs)\n"
117 " -h, --help display this help and exit\n"
120 , cmd, QGA_VERSION, QGA_VIRTIO_PATH_DEFAULT, QGA_PIDFILE_DEFAULT);
123 static const char *ga_log_level_str(GLogLevelFlags level)
125 switch (level & G_LOG_LEVEL_MASK) {
126 case G_LOG_LEVEL_ERROR:
128 case G_LOG_LEVEL_CRITICAL:
130 case G_LOG_LEVEL_WARNING:
132 case G_LOG_LEVEL_MESSAGE:
134 case G_LOG_LEVEL_INFO:
136 case G_LOG_LEVEL_DEBUG:
143 bool ga_logging_enabled(GAState *s)
145 return s->logging_enabled;
148 void ga_disable_logging(GAState *s)
150 s->logging_enabled = false;
153 void ga_enable_logging(GAState *s)
155 s->logging_enabled = true;
158 static void ga_log(const gchar *domain, GLogLevelFlags level,
159 const gchar *msg, gpointer opaque)
163 const char *level_str = ga_log_level_str(level);
165 if (!ga_logging_enabled(s)) {
169 level &= G_LOG_LEVEL_MASK;
171 if (domain && strcmp(domain, "syslog") == 0) {
172 syslog(LOG_INFO, "%s: %s", level_str, msg);
173 } else if (level & s->log_level) {
175 if (level & s->log_level) {
177 g_get_current_time(&time);
179 "%lu.%lu: %s: %s\n", time.tv_sec, time.tv_usec, level_str, msg);
185 static void become_daemon(const char *pidfile)
199 pidfd = open(pidfile, O_CREAT|O_WRONLY|O_EXCL, S_IRUSR|S_IWUSR);
201 g_critical("Cannot create pid file, %s", strerror(errno));
205 if (asprintf(&pidstr, "%d", getpid()) == -1) {
206 g_critical("Cannot allocate memory");
209 if (write(pidfd, pidstr, strlen(pidstr)) != strlen(pidstr)) {
211 g_critical("Failed to write pid file");
220 if ((chdir("/")) < 0) {
225 close(STDOUT_FILENO);
226 close(STDERR_FILENO);
232 g_critical("failed to daemonize");
237 static int send_response(GAState *s, QObject *payload)
240 QString *payload_qstr;
243 g_assert(payload && s->channel);
245 payload_qstr = qobject_to_json(payload);
250 qstring_append_chr(payload_qstr, '\n');
251 buf = qstring_get_str(payload_qstr);
252 status = ga_channel_write_all(s->channel, buf, strlen(buf));
253 QDECREF(payload_qstr);
254 if (status != G_IO_STATUS_NORMAL) {
261 static void process_command(GAState *s, QDict *req)
267 g_debug("processing command");
268 rsp = qmp_dispatch(QOBJECT(req));
270 ret = send_response(s, rsp);
272 g_warning("error sending response: %s", strerror(ret));
276 g_warning("error getting response");
280 /* handle requests/control events coming in over the channel */
281 static void process_event(JSONMessageParser *parser, QList *tokens)
283 GAState *s = container_of(parser, GAState, parser);
289 g_assert(s && parser);
291 g_debug("process_event: called");
292 obj = json_parser_parse_err(tokens, NULL, &err);
293 if (err || !obj || qobject_type(obj) != QTYPE_QDICT) {
297 g_warning("failed to parse event: unknown error");
298 error_set(&err, QERR_JSON_PARSING);
300 g_warning("failed to parse event: %s", error_get_pretty(err));
302 qdict_put_obj(qdict, "error", error_get_qobject(err));
305 qdict = qobject_to_qdict(obj);
310 /* handle host->guest commands */
311 if (qdict_haskey(qdict, "execute")) {
312 process_command(s, qdict);
314 if (!qdict_haskey(qdict, "error")) {
317 g_warning("unrecognized payload format");
318 error_set(&err, QERR_UNSUPPORTED);
319 qdict_put_obj(qdict, "error", error_get_qobject(err));
322 ret = send_response(s, QOBJECT(qdict));
324 g_warning("error sending error response: %s", strerror(ret));
331 /* false return signals GAChannel to close the current client connection */
332 static gboolean channel_event_cb(GIOCondition condition, gpointer data)
335 gchar buf[QGA_READ_COUNT_DEFAULT+1];
338 GIOStatus status = ga_channel_read(s->channel, buf, QGA_READ_COUNT_DEFAULT, &count);
340 g_warning("error reading channel: %s", err->message);
345 case G_IO_STATUS_ERROR:
346 g_warning("error reading channel");
348 case G_IO_STATUS_NORMAL:
350 g_debug("read data, count: %d, data: %s", (int)count, buf);
351 json_message_parser_feed(&s->parser, (char *)buf, (int)count);
353 case G_IO_STATUS_EOF:
354 g_debug("received EOF");
358 case G_IO_STATUS_AGAIN:
359 /* virtio causes us to spin here when no process is attached to
360 * host-side chardev. sleep a bit to mitigate this
367 g_warning("unknown channel read status, closing");
373 static gboolean channel_init(GAState *s, const gchar *method, const gchar *path)
375 GAChannelMethod channel_method;
377 if (method == NULL) {
378 method = "virtio-serial";
382 if (strcmp(method, "virtio-serial") != 0) {
383 g_critical("must specify a path for this channel");
386 /* try the default path for the virtio-serial port */
387 path = QGA_VIRTIO_PATH_DEFAULT;
390 if (strcmp(method, "virtio-serial") == 0) {
391 s->virtio = true; /* virtio requires special handling in some cases */
392 channel_method = GA_CHANNEL_VIRTIO_SERIAL;
393 } else if (strcmp(method, "isa-serial") == 0) {
394 channel_method = GA_CHANNEL_ISA_SERIAL;
395 } else if (strcmp(method, "unix-listen") == 0) {
396 channel_method = GA_CHANNEL_UNIX_LISTEN;
398 g_critical("unsupported channel method/type: %s", method);
402 s->channel = ga_channel_new(channel_method, path, channel_event_cb, s);
404 g_critical("failed to create guest agent channel");
412 DWORD WINAPI service_ctrl_handler(DWORD ctrl, DWORD type, LPVOID data,
415 DWORD ret = NO_ERROR;
416 GAService *service = &ga_state->service;
420 case SERVICE_CONTROL_STOP:
421 case SERVICE_CONTROL_SHUTDOWN:
422 quit_handler(SIGTERM);
423 service->status.dwCurrentState = SERVICE_STOP_PENDING;
424 SetServiceStatus(service->status_handle, &service->status);
428 ret = ERROR_CALL_NOT_IMPLEMENTED;
433 VOID WINAPI service_main(DWORD argc, TCHAR *argv[])
435 GAService *service = &ga_state->service;
437 service->status_handle = RegisterServiceCtrlHandlerEx(QGA_SERVICE_NAME,
438 service_ctrl_handler, NULL);
440 if (service->status_handle == 0) {
441 g_critical("Failed to register extended requests function!\n");
445 service->status.dwServiceType = SERVICE_WIN32;
446 service->status.dwCurrentState = SERVICE_RUNNING;
447 service->status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
448 service->status.dwWin32ExitCode = NO_ERROR;
449 service->status.dwServiceSpecificExitCode = NO_ERROR;
450 service->status.dwCheckPoint = 0;
451 service->status.dwWaitHint = 0;
452 SetServiceStatus(service->status_handle, &service->status);
454 g_main_loop_run(ga_state->main_loop);
456 service->status.dwCurrentState = SERVICE_STOPPED;
457 SetServiceStatus(service->status_handle, &service->status);
461 int main(int argc, char **argv)
463 const char *sopt = "hVvdm:p:l:f:b:s:";
464 const char *method = NULL, *path = NULL, *pidfile = QGA_PIDFILE_DEFAULT;
465 const char *log_file_name = NULL;
467 const char *service = NULL;
469 const struct option lopt[] = {
470 { "help", 0, NULL, 'h' },
471 { "version", 0, NULL, 'V' },
472 { "logfile", 1, NULL, 'l' },
473 { "pidfile", 1, NULL, 'f' },
474 { "verbose", 0, NULL, 'v' },
475 { "method", 1, NULL, 'm' },
476 { "path", 1, NULL, 'p' },
477 { "daemonize", 0, NULL, 'd' },
478 { "blacklist", 1, NULL, 'b' },
480 { "service", 1, NULL, 's' },
484 int opt_ind = 0, ch, daemonize = 0, i, j, len;
485 GLogLevelFlags log_level = G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL;
486 FILE *log_file = stderr;
489 module_call_init(MODULE_INIT_QAPI);
491 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
500 log_file_name = optarg;
501 log_file = fopen(log_file_name, "a");
503 g_critical("unable to open specified log file: %s",
512 /* enable all log levels */
513 log_level = G_LOG_LEVEL_MASK;
516 printf("QEMU Guest Agent %s\n", QGA_VERSION);
522 char **list_head, **list;
523 if (*optarg == '?') {
524 list_head = list = qmp_get_command_list();
525 while (*list != NULL) {
526 printf("%s\n", *list);
533 for (j = 0, i = 0, len = strlen(optarg); i < len; i++) {
534 if (optarg[i] == ',') {
536 qmp_disable_command(&optarg[j]);
537 g_debug("disabling command: %s", &optarg[j]);
542 qmp_disable_command(&optarg[j]);
543 g_debug("disabling command: %s", &optarg[j]);
550 if (strcmp(service, "install") == 0) {
551 return ga_install_service(path, log_file_name);
552 } else if (strcmp(service, "uninstall") == 0) {
553 return ga_uninstall_service();
555 printf("Unknown service command.\n");
564 g_print("Unknown option, try '%s --help' for more information.\n",
572 g_debug("starting daemon");
573 become_daemon(pidfile);
577 s = g_malloc0(sizeof(GAState));
578 s->log_file = log_file;
579 s->log_level = log_level;
580 g_log_set_default_handler(ga_log, s);
581 g_log_set_fatal_mask(NULL, G_LOG_LEVEL_ERROR);
582 s->logging_enabled = true;
583 s->command_state = ga_command_state_new();
584 ga_command_state_init(s, s->command_state);
585 ga_command_state_init_all(s->command_state);
586 json_message_parser_init(&s->parser, process_event);
589 if (!register_signal_handlers()) {
590 g_critical("failed to register signal handlers");
595 s->main_loop = g_main_loop_new(NULL, false);
596 if (!channel_init(ga_state, method, path)) {
597 g_critical("failed to initialize guest agent channel");
601 g_main_loop_run(ga_state->main_loop);
604 SERVICE_TABLE_ENTRY service_table[] = {
605 { (char *)QGA_SERVICE_NAME, service_main }, { NULL, NULL } };
606 StartServiceCtrlDispatcher(service_table);
608 g_main_loop_run(ga_state->main_loop);
612 ga_command_state_cleanup_all(ga_state->command_state);
613 ga_channel_free(ga_state->channel);