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.
23 #include "qapi/qmp/json-streamer.h"
24 #include "qapi/qmp/json-parser.h"
25 #include "qapi/qmp/qint.h"
26 #include "qapi/qmp/qjson.h"
27 #include "qga/guest-agent-core.h"
28 #include "qemu/module.h"
30 #include "qapi/qmp/qerror.h"
31 #include "qapi/qmp/dispatch.h"
32 #include "qga/channel.h"
34 #include "qga/service-win32.h"
40 #define CONFIG_FSFREEZE
45 #define QGA_VIRTIO_PATH_DEFAULT "/dev/virtio-ports/org.qemu.guest_agent.0"
47 #define QGA_VIRTIO_PATH_DEFAULT "\\\\.\\Global\\org.qemu.guest_agent.0"
49 #define QGA_STATEDIR_DEFAULT CONFIG_QEMU_LOCALSTATEDIR "/run"
50 #define QGA_PIDFILE_DEFAULT QGA_STATEDIR_DEFAULT "/qemu-ga.pid"
51 #ifdef CONFIG_FSFREEZE
52 #define QGA_FSFREEZE_HOOK_DEFAULT CONFIG_QEMU_CONFDIR "/fsfreeze-hook"
54 #define QGA_SENTINEL_BYTE 0xFF
57 JSONMessageParser parser;
60 bool virtio; /* fastpath to check for virtio to deal with poll() quirks */
61 GACommandState *command_state;
62 GLogLevelFlags log_level;
68 bool delimit_response;
71 const char *state_filepath_isfrozen;
73 const char *log_filepath;
74 const char *pid_filepath;
76 #ifdef CONFIG_FSFREEZE
77 const char *fsfreeze_hook;
81 struct GAState *ga_state;
83 /* commands that are safe to issue while filesystems are frozen */
84 static const char *ga_freeze_whitelist[] = {
88 "guest-fsfreeze-status",
89 "guest-fsfreeze-thaw",
94 DWORD WINAPI service_ctrl_handler(DWORD ctrl, DWORD type, LPVOID data,
96 VOID WINAPI service_main(DWORD argc, TCHAR *argv[]);
99 static void quit_handler(int sig)
101 /* if we're frozen, don't exit unless we're absolutely forced to,
102 * because it's basically impossible for graceful exit to complete
103 * unless all log/pid files are on unfreezable filesystems. there's
104 * also a very likely chance killing the agent before unfreezing
105 * the filesystems is a mistake (or will be viewed as one later).
107 if (ga_is_frozen(ga_state)) {
110 g_debug("received signal num %d, quitting", sig);
112 if (g_main_loop_is_running(ga_state->main_loop)) {
113 g_main_loop_quit(ga_state->main_loop);
118 static gboolean register_signal_handlers(void)
120 struct sigaction sigact;
123 memset(&sigact, 0, sizeof(struct sigaction));
124 sigact.sa_handler = quit_handler;
126 ret = sigaction(SIGINT, &sigact, NULL);
128 g_error("error configuring signal handler: %s", strerror(errno));
130 ret = sigaction(SIGTERM, &sigact, NULL);
132 g_error("error configuring signal handler: %s", strerror(errno));
138 /* TODO: use this in place of all post-fork() fclose(std*) callers */
139 void reopen_fd_to_null(int fd)
143 nullfd = open("/dev/null", O_RDWR);
156 static void usage(const char *cmd)
159 "Usage: %s [-m <method> -p <path>] [<options>]\n"
160 "QEMU Guest Agent %s\n"
162 " -m, --method transport method: one of unix-listen, virtio-serial, or\n"
163 " isa-serial (virtio-serial is the default)\n"
164 " -p, --path device/socket path (the default for virtio-serial is:\n"
166 " -l, --logfile set logfile path, logs to stderr by default\n"
167 " -f, --pidfile specify pidfile (default is %s)\n"
168 #ifdef CONFIG_FSFREEZE
169 " -F, --fsfreeze-hook\n"
170 " enable fsfreeze hook. Accepts an optional argument that\n"
171 " specifies script to run on freeze/thaw. Script will be\n"
172 " called with 'freeze'/'thaw' arguments accordingly.\n"
174 " If using -F with an argument, do not follow -F with a\n"
176 " (for example: -F/var/run/fsfreezehook.sh)\n"
178 " -t, --statedir specify dir to store state information (absolute paths\n"
179 " only, default is %s)\n"
180 " -v, --verbose log extra debugging information\n"
181 " -V, --version print version information and exit\n"
182 " -d, --daemonize become a daemon\n"
184 " -s, --service service commands: install, uninstall\n"
186 " -b, --blacklist comma-separated list of RPCs to disable (no spaces, \"?\"\n"
187 " to list available RPCs)\n"
188 " -h, --help display this help and exit\n"
191 , cmd, QEMU_VERSION, QGA_VIRTIO_PATH_DEFAULT, QGA_PIDFILE_DEFAULT,
192 #ifdef CONFIG_FSFREEZE
193 QGA_FSFREEZE_HOOK_DEFAULT,
195 QGA_STATEDIR_DEFAULT);
198 static const char *ga_log_level_str(GLogLevelFlags level)
200 switch (level & G_LOG_LEVEL_MASK) {
201 case G_LOG_LEVEL_ERROR:
203 case G_LOG_LEVEL_CRITICAL:
205 case G_LOG_LEVEL_WARNING:
207 case G_LOG_LEVEL_MESSAGE:
209 case G_LOG_LEVEL_INFO:
211 case G_LOG_LEVEL_DEBUG:
218 bool ga_logging_enabled(GAState *s)
220 return s->logging_enabled;
223 void ga_disable_logging(GAState *s)
225 s->logging_enabled = false;
228 void ga_enable_logging(GAState *s)
230 s->logging_enabled = true;
233 static void ga_log(const gchar *domain, GLogLevelFlags level,
234 const gchar *msg, gpointer opaque)
238 const char *level_str = ga_log_level_str(level);
240 if (!ga_logging_enabled(s)) {
244 level &= G_LOG_LEVEL_MASK;
246 if (domain && strcmp(domain, "syslog") == 0) {
247 syslog(LOG_INFO, "%s: %s", level_str, msg);
248 } else if (level & s->log_level) {
250 if (level & s->log_level) {
252 g_get_current_time(&time);
254 "%lu.%lu: %s: %s\n", time.tv_sec, time.tv_usec, level_str, msg);
259 void ga_set_response_delimited(GAState *s)
261 s->delimit_response = true;
265 static bool ga_open_pidfile(const char *pidfile)
270 pidfd = open(pidfile, O_CREAT|O_WRONLY, S_IRUSR|S_IWUSR);
271 if (pidfd == -1 || lockf(pidfd, F_TLOCK, 0)) {
272 g_critical("Cannot lock pid file, %s", strerror(errno));
279 if (ftruncate(pidfd, 0) || lseek(pidfd, 0, SEEK_SET)) {
280 g_critical("Failed to truncate pid file");
283 snprintf(pidstr, sizeof(pidstr), "%d\n", getpid());
284 if (write(pidfd, pidstr, strlen(pidstr)) != strlen(pidstr)) {
285 g_critical("Failed to write pid file");
296 static bool ga_open_pidfile(const char *pidfile)
302 static gint ga_strcmp(gconstpointer str1, gconstpointer str2)
304 return strcmp(str1, str2);
307 /* disable commands that aren't safe for fsfreeze */
308 static void ga_disable_non_whitelisted(void)
310 char **list_head, **list;
314 list_head = list = qmp_get_command_list();
315 while (*list != NULL) {
318 while (ga_freeze_whitelist[i] != NULL) {
319 if (strcmp(*list, ga_freeze_whitelist[i]) == 0) {
325 g_debug("disabling command: %s", *list);
326 qmp_disable_command(*list);
334 /* [re-]enable all commands, except those explicitly blacklisted by user */
335 static void ga_enable_non_blacklisted(GList *blacklist)
337 char **list_head, **list;
339 list_head = list = qmp_get_command_list();
340 while (*list != NULL) {
341 if (g_list_find_custom(blacklist, *list, ga_strcmp) == NULL &&
342 !qmp_command_is_enabled(*list)) {
343 g_debug("enabling command: %s", *list);
344 qmp_enable_command(*list);
352 static bool ga_create_file(const char *path)
354 int fd = open(path, O_CREAT | O_WRONLY, S_IWUSR | S_IRUSR);
356 g_warning("unable to open/create file %s: %s", path, strerror(errno));
363 static bool ga_delete_file(const char *path)
365 int ret = unlink(path);
367 g_warning("unable to delete file: %s: %s", path, strerror(errno));
374 bool ga_is_frozen(GAState *s)
379 void ga_set_frozen(GAState *s)
381 if (ga_is_frozen(s)) {
384 /* disable all non-whitelisted (for frozen state) commands */
385 ga_disable_non_whitelisted();
386 g_warning("disabling logging due to filesystem freeze");
387 ga_disable_logging(s);
389 if (!ga_create_file(s->state_filepath_isfrozen)) {
390 g_warning("unable to create %s, fsfreeze may not function properly",
391 s->state_filepath_isfrozen);
395 void ga_unset_frozen(GAState *s)
397 if (!ga_is_frozen(s)) {
401 /* if we delayed creation/opening of pid/log files due to being
402 * in a frozen state at start up, do it now
404 if (s->deferred_options.log_filepath) {
405 s->log_file = fopen(s->deferred_options.log_filepath, "a");
407 s->log_file = stderr;
409 s->deferred_options.log_filepath = NULL;
411 ga_enable_logging(s);
412 g_warning("logging re-enabled due to filesystem unfreeze");
413 if (s->deferred_options.pid_filepath) {
414 if (!ga_open_pidfile(s->deferred_options.pid_filepath)) {
415 g_warning("failed to create/open pid file");
417 s->deferred_options.pid_filepath = NULL;
420 /* enable all disabled, non-blacklisted commands */
421 ga_enable_non_blacklisted(s->blacklist);
423 if (!ga_delete_file(s->state_filepath_isfrozen)) {
424 g_warning("unable to delete %s, fsfreeze may not function properly",
425 s->state_filepath_isfrozen);
429 #ifdef CONFIG_FSFREEZE
430 const char *ga_fsfreeze_hook(GAState *s)
432 return s->fsfreeze_hook;
436 static void become_daemon(const char *pidfile)
450 if (!ga_open_pidfile(pidfile)) {
451 g_critical("failed to create pidfile");
461 if ((chdir("/")) < 0) {
465 reopen_fd_to_null(STDIN_FILENO);
466 reopen_fd_to_null(STDOUT_FILENO);
467 reopen_fd_to_null(STDERR_FILENO);
474 g_critical("failed to daemonize");
479 static int send_response(GAState *s, QObject *payload)
482 QString *payload_qstr, *response_qstr;
485 g_assert(payload && s->channel);
487 payload_qstr = qobject_to_json(payload);
492 if (s->delimit_response) {
493 s->delimit_response = false;
494 response_qstr = qstring_new();
495 qstring_append_chr(response_qstr, QGA_SENTINEL_BYTE);
496 qstring_append(response_qstr, qstring_get_str(payload_qstr));
497 QDECREF(payload_qstr);
499 response_qstr = payload_qstr;
502 qstring_append_chr(response_qstr, '\n');
503 buf = qstring_get_str(response_qstr);
504 status = ga_channel_write_all(s->channel, buf, strlen(buf));
505 QDECREF(response_qstr);
506 if (status != G_IO_STATUS_NORMAL) {
513 static void process_command(GAState *s, QDict *req)
519 g_debug("processing command");
520 rsp = qmp_dispatch(QOBJECT(req));
522 ret = send_response(s, rsp);
524 g_warning("error sending response: %s", strerror(ret));
530 /* handle requests/control events coming in over the channel */
531 static void process_event(JSONMessageParser *parser, QList *tokens)
533 GAState *s = container_of(parser, GAState, parser);
539 g_assert(s && parser);
541 g_debug("process_event: called");
542 obj = json_parser_parse_err(tokens, NULL, &err);
543 if (err || !obj || qobject_type(obj) != QTYPE_QDICT) {
547 g_warning("failed to parse event: unknown error");
548 error_set(&err, QERR_JSON_PARSING);
550 g_warning("failed to parse event: %s", error_get_pretty(err));
552 qdict_put_obj(qdict, "error", qmp_build_error_object(err));
555 qdict = qobject_to_qdict(obj);
560 /* handle host->guest commands */
561 if (qdict_haskey(qdict, "execute")) {
562 process_command(s, qdict);
564 if (!qdict_haskey(qdict, "error")) {
567 g_warning("unrecognized payload format");
568 error_set(&err, QERR_UNSUPPORTED);
569 qdict_put_obj(qdict, "error", qmp_build_error_object(err));
572 ret = send_response(s, QOBJECT(qdict));
574 g_warning("error sending error response: %s", strerror(ret));
581 /* false return signals GAChannel to close the current client connection */
582 static gboolean channel_event_cb(GIOCondition condition, gpointer data)
585 gchar buf[QGA_READ_COUNT_DEFAULT+1];
588 GIOStatus status = ga_channel_read(s->channel, buf, QGA_READ_COUNT_DEFAULT, &count);
590 g_warning("error reading channel: %s", err->message);
595 case G_IO_STATUS_ERROR:
596 g_warning("error reading channel");
598 case G_IO_STATUS_NORMAL:
600 g_debug("read data, count: %d, data: %s", (int)count, buf);
601 json_message_parser_feed(&s->parser, (char *)buf, (int)count);
603 case G_IO_STATUS_EOF:
604 g_debug("received EOF");
608 case G_IO_STATUS_AGAIN:
609 /* virtio causes us to spin here when no process is attached to
610 * host-side chardev. sleep a bit to mitigate this
617 g_warning("unknown channel read status, closing");
623 static gboolean channel_init(GAState *s, const gchar *method, const gchar *path)
625 GAChannelMethod channel_method;
627 if (method == NULL) {
628 method = "virtio-serial";
632 if (strcmp(method, "virtio-serial") != 0) {
633 g_critical("must specify a path for this channel");
636 /* try the default path for the virtio-serial port */
637 path = QGA_VIRTIO_PATH_DEFAULT;
640 if (strcmp(method, "virtio-serial") == 0) {
641 s->virtio = true; /* virtio requires special handling in some cases */
642 channel_method = GA_CHANNEL_VIRTIO_SERIAL;
643 } else if (strcmp(method, "isa-serial") == 0) {
644 channel_method = GA_CHANNEL_ISA_SERIAL;
645 } else if (strcmp(method, "unix-listen") == 0) {
646 channel_method = GA_CHANNEL_UNIX_LISTEN;
648 g_critical("unsupported channel method/type: %s", method);
652 s->channel = ga_channel_new(channel_method, path, channel_event_cb, s);
654 g_critical("failed to create guest agent channel");
662 DWORD WINAPI service_ctrl_handler(DWORD ctrl, DWORD type, LPVOID data,
665 DWORD ret = NO_ERROR;
666 GAService *service = &ga_state->service;
670 case SERVICE_CONTROL_STOP:
671 case SERVICE_CONTROL_SHUTDOWN:
672 quit_handler(SIGTERM);
673 service->status.dwCurrentState = SERVICE_STOP_PENDING;
674 SetServiceStatus(service->status_handle, &service->status);
678 ret = ERROR_CALL_NOT_IMPLEMENTED;
683 VOID WINAPI service_main(DWORD argc, TCHAR *argv[])
685 GAService *service = &ga_state->service;
687 service->status_handle = RegisterServiceCtrlHandlerEx(QGA_SERVICE_NAME,
688 service_ctrl_handler, NULL);
690 if (service->status_handle == 0) {
691 g_critical("Failed to register extended requests function!\n");
695 service->status.dwServiceType = SERVICE_WIN32;
696 service->status.dwCurrentState = SERVICE_RUNNING;
697 service->status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
698 service->status.dwWin32ExitCode = NO_ERROR;
699 service->status.dwServiceSpecificExitCode = NO_ERROR;
700 service->status.dwCheckPoint = 0;
701 service->status.dwWaitHint = 0;
702 SetServiceStatus(service->status_handle, &service->status);
704 g_main_loop_run(ga_state->main_loop);
706 service->status.dwCurrentState = SERVICE_STOPPED;
707 SetServiceStatus(service->status_handle, &service->status);
711 int main(int argc, char **argv)
713 const char *sopt = "hVvdm:p:l:f:F::b:s:t:";
714 const char *method = NULL, *path = NULL;
715 const char *log_filepath = NULL;
716 const char *pid_filepath = QGA_PIDFILE_DEFAULT;
717 #ifdef CONFIG_FSFREEZE
718 const char *fsfreeze_hook = NULL;
720 const char *state_dir = QGA_STATEDIR_DEFAULT;
722 const char *service = NULL;
724 const struct option lopt[] = {
725 { "help", 0, NULL, 'h' },
726 { "version", 0, NULL, 'V' },
727 { "logfile", 1, NULL, 'l' },
728 { "pidfile", 1, NULL, 'f' },
729 #ifdef CONFIG_FSFREEZE
730 { "fsfreeze-hook", 2, NULL, 'F' },
732 { "verbose", 0, NULL, 'v' },
733 { "method", 1, NULL, 'm' },
734 { "path", 1, NULL, 'p' },
735 { "daemonize", 0, NULL, 'd' },
736 { "blacklist", 1, NULL, 'b' },
738 { "service", 1, NULL, 's' },
740 { "statedir", 1, NULL, 't' },
743 int opt_ind = 0, ch, daemonize = 0, i, j, len;
744 GLogLevelFlags log_level = G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL;
745 GList *blacklist = NULL;
748 module_call_init(MODULE_INIT_QAPI);
750 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
759 log_filepath = optarg;
762 pid_filepath = optarg;
764 #ifdef CONFIG_FSFREEZE
766 fsfreeze_hook = optarg ? optarg : QGA_FSFREEZE_HOOK_DEFAULT;
773 /* enable all log levels */
774 log_level = G_LOG_LEVEL_MASK;
777 printf("QEMU Guest Agent %s\n", QEMU_VERSION);
783 char **list_head, **list;
784 if (is_help_option(optarg)) {
785 list_head = list = qmp_get_command_list();
786 while (*list != NULL) {
787 printf("%s\n", *list);
794 for (j = 0, i = 0, len = strlen(optarg); i < len; i++) {
795 if (optarg[i] == ',') {
797 blacklist = g_list_append(blacklist, &optarg[j]);
802 blacklist = g_list_append(blacklist, &optarg[j]);
809 if (strcmp(service, "install") == 0) {
810 return ga_install_service(path, log_filepath);
811 } else if (strcmp(service, "uninstall") == 0) {
812 return ga_uninstall_service();
814 printf("Unknown service command.\n");
823 g_print("Unknown option, try '%s --help' for more information.\n",
829 s = g_malloc0(sizeof(GAState));
830 s->log_level = log_level;
831 s->log_file = stderr;
832 #ifdef CONFIG_FSFREEZE
833 s->fsfreeze_hook = fsfreeze_hook;
835 g_log_set_default_handler(ga_log, s);
836 g_log_set_fatal_mask(NULL, G_LOG_LEVEL_ERROR);
837 ga_enable_logging(s);
838 s->state_filepath_isfrozen = g_strdup_printf("%s/qga.state.isfrozen",
842 /* check if a previous instance of qemu-ga exited with filesystems' state
843 * marked as frozen. this could be a stale value (a non-qemu-ga process
844 * or reboot may have since unfrozen them), but better to require an
845 * uneeded unfreeze than to risk hanging on start-up
848 if (stat(s->state_filepath_isfrozen, &st) == -1) {
849 /* it's okay if the file doesn't exist, but if we can't access for
850 * some other reason, such as permissions, there's a configuration
851 * that needs to be addressed. so just bail now before we get into
854 if (errno != ENOENT) {
855 g_critical("unable to access state file at path %s: %s",
856 s->state_filepath_isfrozen, strerror(errno));
860 g_warning("previous instance appears to have exited with frozen"
861 " filesystems. deferring logging/pidfile creation and"
862 " disabling non-fsfreeze-safe commands until"
863 " guest-fsfreeze-thaw is issued, or filesystems are"
864 " manually unfrozen and the file %s is removed",
865 s->state_filepath_isfrozen);
870 if (ga_is_frozen(s)) {
872 /* delay opening/locking of pidfile till filesystem are unfrozen */
873 s->deferred_options.pid_filepath = pid_filepath;
877 /* delay opening the log file till filesystems are unfrozen */
878 s->deferred_options.log_filepath = log_filepath;
880 ga_disable_logging(s);
881 ga_disable_non_whitelisted();
884 become_daemon(pid_filepath);
887 FILE *log_file = fopen(log_filepath, "a");
889 g_critical("unable to open specified log file: %s",
893 s->log_file = log_file;
898 s->blacklist = blacklist;
900 g_debug("disabling command: %s", (char *)blacklist->data);
901 qmp_disable_command(blacklist->data);
902 blacklist = g_list_next(blacklist);
905 s->command_state = ga_command_state_new();
906 ga_command_state_init(s, s->command_state);
907 ga_command_state_init_all(s->command_state);
908 json_message_parser_init(&s->parser, process_event);
911 if (!register_signal_handlers()) {
912 g_critical("failed to register signal handlers");
917 s->main_loop = g_main_loop_new(NULL, false);
918 if (!channel_init(ga_state, method, path)) {
919 g_critical("failed to initialize guest agent channel");
923 g_main_loop_run(ga_state->main_loop);
926 SERVICE_TABLE_ENTRY service_table[] = {
927 { (char *)QGA_SERVICE_NAME, service_main }, { NULL, NULL } };
928 StartServiceCtrlDispatcher(service_table);
930 g_main_loop_run(ga_state->main_loop);
934 ga_command_state_cleanup_all(ga_state->command_state);
935 ga_channel_free(ga_state->channel);
938 unlink(pid_filepath);
944 unlink(pid_filepath);