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;
264 static FILE *ga_open_logfile(const char *logfile)
268 f = fopen(logfile, "a");
273 qemu_set_cloexec(fileno(f));
278 static bool ga_open_pidfile(const char *pidfile)
283 pidfd = qemu_open(pidfile, O_CREAT|O_WRONLY, S_IRUSR|S_IWUSR);
284 if (pidfd == -1 || lockf(pidfd, F_TLOCK, 0)) {
285 g_critical("Cannot lock pid file, %s", strerror(errno));
292 if (ftruncate(pidfd, 0) || lseek(pidfd, 0, SEEK_SET)) {
293 g_critical("Failed to truncate pid file");
296 snprintf(pidstr, sizeof(pidstr), "%d\n", getpid());
297 if (write(pidfd, pidstr, strlen(pidstr)) != strlen(pidstr)) {
298 g_critical("Failed to write pid file");
309 static bool ga_open_pidfile(const char *pidfile)
315 static gint ga_strcmp(gconstpointer str1, gconstpointer str2)
317 return strcmp(str1, str2);
320 /* disable commands that aren't safe for fsfreeze */
321 static void ga_disable_non_whitelisted(void)
323 char **list_head, **list;
327 list_head = list = qmp_get_command_list();
328 while (*list != NULL) {
331 while (ga_freeze_whitelist[i] != NULL) {
332 if (strcmp(*list, ga_freeze_whitelist[i]) == 0) {
338 g_debug("disabling command: %s", *list);
339 qmp_disable_command(*list);
347 /* [re-]enable all commands, except those explicitly blacklisted by user */
348 static void ga_enable_non_blacklisted(GList *blacklist)
350 char **list_head, **list;
352 list_head = list = qmp_get_command_list();
353 while (*list != NULL) {
354 if (g_list_find_custom(blacklist, *list, ga_strcmp) == NULL &&
355 !qmp_command_is_enabled(*list)) {
356 g_debug("enabling command: %s", *list);
357 qmp_enable_command(*list);
365 static bool ga_create_file(const char *path)
367 int fd = open(path, O_CREAT | O_WRONLY, S_IWUSR | S_IRUSR);
369 g_warning("unable to open/create file %s: %s", path, strerror(errno));
376 static bool ga_delete_file(const char *path)
378 int ret = unlink(path);
380 g_warning("unable to delete file: %s: %s", path, strerror(errno));
387 bool ga_is_frozen(GAState *s)
392 void ga_set_frozen(GAState *s)
394 if (ga_is_frozen(s)) {
397 /* disable all non-whitelisted (for frozen state) commands */
398 ga_disable_non_whitelisted();
399 g_warning("disabling logging due to filesystem freeze");
400 ga_disable_logging(s);
402 if (!ga_create_file(s->state_filepath_isfrozen)) {
403 g_warning("unable to create %s, fsfreeze may not function properly",
404 s->state_filepath_isfrozen);
408 void ga_unset_frozen(GAState *s)
410 if (!ga_is_frozen(s)) {
414 /* if we delayed creation/opening of pid/log files due to being
415 * in a frozen state at start up, do it now
417 if (s->deferred_options.log_filepath) {
418 s->log_file = ga_open_logfile(s->deferred_options.log_filepath);
420 s->log_file = stderr;
422 s->deferred_options.log_filepath = NULL;
424 ga_enable_logging(s);
425 g_warning("logging re-enabled due to filesystem unfreeze");
426 if (s->deferred_options.pid_filepath) {
427 if (!ga_open_pidfile(s->deferred_options.pid_filepath)) {
428 g_warning("failed to create/open pid file");
430 s->deferred_options.pid_filepath = NULL;
433 /* enable all disabled, non-blacklisted commands */
434 ga_enable_non_blacklisted(s->blacklist);
436 if (!ga_delete_file(s->state_filepath_isfrozen)) {
437 g_warning("unable to delete %s, fsfreeze may not function properly",
438 s->state_filepath_isfrozen);
442 #ifdef CONFIG_FSFREEZE
443 const char *ga_fsfreeze_hook(GAState *s)
445 return s->fsfreeze_hook;
449 static void become_daemon(const char *pidfile)
463 if (!ga_open_pidfile(pidfile)) {
464 g_critical("failed to create pidfile");
474 if ((chdir("/")) < 0) {
478 reopen_fd_to_null(STDIN_FILENO);
479 reopen_fd_to_null(STDOUT_FILENO);
480 reopen_fd_to_null(STDERR_FILENO);
487 g_critical("failed to daemonize");
492 static int send_response(GAState *s, QObject *payload)
495 QString *payload_qstr, *response_qstr;
498 g_assert(payload && s->channel);
500 payload_qstr = qobject_to_json(payload);
505 if (s->delimit_response) {
506 s->delimit_response = false;
507 response_qstr = qstring_new();
508 qstring_append_chr(response_qstr, QGA_SENTINEL_BYTE);
509 qstring_append(response_qstr, qstring_get_str(payload_qstr));
510 QDECREF(payload_qstr);
512 response_qstr = payload_qstr;
515 qstring_append_chr(response_qstr, '\n');
516 buf = qstring_get_str(response_qstr);
517 status = ga_channel_write_all(s->channel, buf, strlen(buf));
518 QDECREF(response_qstr);
519 if (status != G_IO_STATUS_NORMAL) {
526 static void process_command(GAState *s, QDict *req)
532 g_debug("processing command");
533 rsp = qmp_dispatch(QOBJECT(req));
535 ret = send_response(s, rsp);
537 g_warning("error sending response: %s", strerror(ret));
543 /* handle requests/control events coming in over the channel */
544 static void process_event(JSONMessageParser *parser, QList *tokens)
546 GAState *s = container_of(parser, GAState, parser);
552 g_assert(s && parser);
554 g_debug("process_event: called");
555 obj = json_parser_parse_err(tokens, NULL, &err);
556 if (err || !obj || qobject_type(obj) != QTYPE_QDICT) {
560 g_warning("failed to parse event: unknown error");
561 error_set(&err, QERR_JSON_PARSING);
563 g_warning("failed to parse event: %s", error_get_pretty(err));
565 qdict_put_obj(qdict, "error", qmp_build_error_object(err));
568 qdict = qobject_to_qdict(obj);
573 /* handle host->guest commands */
574 if (qdict_haskey(qdict, "execute")) {
575 process_command(s, qdict);
577 if (!qdict_haskey(qdict, "error")) {
580 g_warning("unrecognized payload format");
581 error_set(&err, QERR_UNSUPPORTED);
582 qdict_put_obj(qdict, "error", qmp_build_error_object(err));
585 ret = send_response(s, QOBJECT(qdict));
587 g_warning("error sending error response: %s", strerror(ret));
594 /* false return signals GAChannel to close the current client connection */
595 static gboolean channel_event_cb(GIOCondition condition, gpointer data)
598 gchar buf[QGA_READ_COUNT_DEFAULT+1];
601 GIOStatus status = ga_channel_read(s->channel, buf, QGA_READ_COUNT_DEFAULT, &count);
603 g_warning("error reading channel: %s", err->message);
608 case G_IO_STATUS_ERROR:
609 g_warning("error reading channel");
611 case G_IO_STATUS_NORMAL:
613 g_debug("read data, count: %d, data: %s", (int)count, buf);
614 json_message_parser_feed(&s->parser, (char *)buf, (int)count);
616 case G_IO_STATUS_EOF:
617 g_debug("received EOF");
621 case G_IO_STATUS_AGAIN:
622 /* virtio causes us to spin here when no process is attached to
623 * host-side chardev. sleep a bit to mitigate this
630 g_warning("unknown channel read status, closing");
636 static gboolean channel_init(GAState *s, const gchar *method, const gchar *path)
638 GAChannelMethod channel_method;
640 if (method == NULL) {
641 method = "virtio-serial";
645 if (strcmp(method, "virtio-serial") != 0) {
646 g_critical("must specify a path for this channel");
649 /* try the default path for the virtio-serial port */
650 path = QGA_VIRTIO_PATH_DEFAULT;
653 if (strcmp(method, "virtio-serial") == 0) {
654 s->virtio = true; /* virtio requires special handling in some cases */
655 channel_method = GA_CHANNEL_VIRTIO_SERIAL;
656 } else if (strcmp(method, "isa-serial") == 0) {
657 channel_method = GA_CHANNEL_ISA_SERIAL;
658 } else if (strcmp(method, "unix-listen") == 0) {
659 channel_method = GA_CHANNEL_UNIX_LISTEN;
661 g_critical("unsupported channel method/type: %s", method);
665 s->channel = ga_channel_new(channel_method, path, channel_event_cb, s);
667 g_critical("failed to create guest agent channel");
675 DWORD WINAPI service_ctrl_handler(DWORD ctrl, DWORD type, LPVOID data,
678 DWORD ret = NO_ERROR;
679 GAService *service = &ga_state->service;
683 case SERVICE_CONTROL_STOP:
684 case SERVICE_CONTROL_SHUTDOWN:
685 quit_handler(SIGTERM);
686 service->status.dwCurrentState = SERVICE_STOP_PENDING;
687 SetServiceStatus(service->status_handle, &service->status);
691 ret = ERROR_CALL_NOT_IMPLEMENTED;
696 VOID WINAPI service_main(DWORD argc, TCHAR *argv[])
698 GAService *service = &ga_state->service;
700 service->status_handle = RegisterServiceCtrlHandlerEx(QGA_SERVICE_NAME,
701 service_ctrl_handler, NULL);
703 if (service->status_handle == 0) {
704 g_critical("Failed to register extended requests function!\n");
708 service->status.dwServiceType = SERVICE_WIN32;
709 service->status.dwCurrentState = SERVICE_RUNNING;
710 service->status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
711 service->status.dwWin32ExitCode = NO_ERROR;
712 service->status.dwServiceSpecificExitCode = NO_ERROR;
713 service->status.dwCheckPoint = 0;
714 service->status.dwWaitHint = 0;
715 SetServiceStatus(service->status_handle, &service->status);
717 g_main_loop_run(ga_state->main_loop);
719 service->status.dwCurrentState = SERVICE_STOPPED;
720 SetServiceStatus(service->status_handle, &service->status);
724 int main(int argc, char **argv)
726 const char *sopt = "hVvdm:p:l:f:F::b:s:t:";
727 const char *method = NULL, *path = NULL;
728 const char *log_filepath = NULL;
729 const char *pid_filepath = QGA_PIDFILE_DEFAULT;
730 #ifdef CONFIG_FSFREEZE
731 const char *fsfreeze_hook = NULL;
733 const char *state_dir = QGA_STATEDIR_DEFAULT;
735 const char *service = NULL;
737 const struct option lopt[] = {
738 { "help", 0, NULL, 'h' },
739 { "version", 0, NULL, 'V' },
740 { "logfile", 1, NULL, 'l' },
741 { "pidfile", 1, NULL, 'f' },
742 #ifdef CONFIG_FSFREEZE
743 { "fsfreeze-hook", 2, NULL, 'F' },
745 { "verbose", 0, NULL, 'v' },
746 { "method", 1, NULL, 'm' },
747 { "path", 1, NULL, 'p' },
748 { "daemonize", 0, NULL, 'd' },
749 { "blacklist", 1, NULL, 'b' },
751 { "service", 1, NULL, 's' },
753 { "statedir", 1, NULL, 't' },
756 int opt_ind = 0, ch, daemonize = 0, i, j, len;
757 GLogLevelFlags log_level = G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL;
758 GList *blacklist = NULL;
761 module_call_init(MODULE_INIT_QAPI);
763 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
772 log_filepath = optarg;
775 pid_filepath = optarg;
777 #ifdef CONFIG_FSFREEZE
779 fsfreeze_hook = optarg ? optarg : QGA_FSFREEZE_HOOK_DEFAULT;
786 /* enable all log levels */
787 log_level = G_LOG_LEVEL_MASK;
790 printf("QEMU Guest Agent %s\n", QEMU_VERSION);
796 char **list_head, **list;
797 if (is_help_option(optarg)) {
798 list_head = list = qmp_get_command_list();
799 while (*list != NULL) {
800 printf("%s\n", *list);
807 for (j = 0, i = 0, len = strlen(optarg); i < len; i++) {
808 if (optarg[i] == ',') {
810 blacklist = g_list_append(blacklist, &optarg[j]);
815 blacklist = g_list_append(blacklist, &optarg[j]);
822 if (strcmp(service, "install") == 0) {
823 return ga_install_service(path, log_filepath);
824 } else if (strcmp(service, "uninstall") == 0) {
825 return ga_uninstall_service();
827 printf("Unknown service command.\n");
836 g_print("Unknown option, try '%s --help' for more information.\n",
842 s = g_malloc0(sizeof(GAState));
843 s->log_level = log_level;
844 s->log_file = stderr;
845 #ifdef CONFIG_FSFREEZE
846 s->fsfreeze_hook = fsfreeze_hook;
848 g_log_set_default_handler(ga_log, s);
849 g_log_set_fatal_mask(NULL, G_LOG_LEVEL_ERROR);
850 ga_enable_logging(s);
851 s->state_filepath_isfrozen = g_strdup_printf("%s/qga.state.isfrozen",
855 /* check if a previous instance of qemu-ga exited with filesystems' state
856 * marked as frozen. this could be a stale value (a non-qemu-ga process
857 * or reboot may have since unfrozen them), but better to require an
858 * uneeded unfreeze than to risk hanging on start-up
861 if (stat(s->state_filepath_isfrozen, &st) == -1) {
862 /* it's okay if the file doesn't exist, but if we can't access for
863 * some other reason, such as permissions, there's a configuration
864 * that needs to be addressed. so just bail now before we get into
867 if (errno != ENOENT) {
868 g_critical("unable to access state file at path %s: %s",
869 s->state_filepath_isfrozen, strerror(errno));
873 g_warning("previous instance appears to have exited with frozen"
874 " filesystems. deferring logging/pidfile creation and"
875 " disabling non-fsfreeze-safe commands until"
876 " guest-fsfreeze-thaw is issued, or filesystems are"
877 " manually unfrozen and the file %s is removed",
878 s->state_filepath_isfrozen);
883 if (ga_is_frozen(s)) {
885 /* delay opening/locking of pidfile till filesystem are unfrozen */
886 s->deferred_options.pid_filepath = pid_filepath;
890 /* delay opening the log file till filesystems are unfrozen */
891 s->deferred_options.log_filepath = log_filepath;
893 ga_disable_logging(s);
894 ga_disable_non_whitelisted();
897 become_daemon(pid_filepath);
900 FILE *log_file = ga_open_logfile(log_filepath);
902 g_critical("unable to open specified log file: %s",
906 s->log_file = log_file;
911 s->blacklist = blacklist;
913 g_debug("disabling command: %s", (char *)blacklist->data);
914 qmp_disable_command(blacklist->data);
915 blacklist = g_list_next(blacklist);
918 s->command_state = ga_command_state_new();
919 ga_command_state_init(s, s->command_state);
920 ga_command_state_init_all(s->command_state);
921 json_message_parser_init(&s->parser, process_event);
924 if (!register_signal_handlers()) {
925 g_critical("failed to register signal handlers");
930 s->main_loop = g_main_loop_new(NULL, false);
931 if (!channel_init(ga_state, method, path)) {
932 g_critical("failed to initialize guest agent channel");
936 g_main_loop_run(ga_state->main_loop);
939 SERVICE_TABLE_ENTRY service_table[] = {
940 { (char *)QGA_SERVICE_NAME, service_main }, { NULL, NULL } };
941 StartServiceCtrlDispatcher(service_table);
943 g_main_loop_run(ga_state->main_loop);
947 ga_command_state_cleanup_all(ga_state->command_state);
948 ga_channel_free(ga_state->channel);
951 unlink(pid_filepath);
957 unlink(pid_filepath);