Update version for v7.0.0-rc3 release
[qemu.git] / qga / main.c
blobb9dd19918e47934480b42903725723afc9229621
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.
14 #include "qemu/osdep.h"
15 #include <getopt.h>
16 #include <glib/gstdio.h>
17 #ifndef _WIN32
18 #include <syslog.h>
19 #include <sys/wait.h>
20 #endif
21 #include "qemu-common.h"
22 #include "qapi/qmp/json-parser.h"
23 #include "qapi/qmp/qdict.h"
24 #include "qapi/qmp/qjson.h"
25 #include "guest-agent-core.h"
26 #include "qga-qapi-init-commands.h"
27 #include "qapi/qmp/qerror.h"
28 #include "qapi/error.h"
29 #include "channel.h"
30 #include "qemu/cutils.h"
31 #include "qemu/help_option.h"
32 #include "qemu/sockets.h"
33 #include "qemu/systemd.h"
34 #include "qemu-version.h"
35 #ifdef _WIN32
36 #include <dbt.h>
37 #include "qga/service-win32.h"
38 #include "qga/vss-win32.h"
39 #endif
40 #ifdef __linux__
41 #include <linux/fs.h>
42 #ifdef FIFREEZE
43 #define CONFIG_FSFREEZE
44 #endif
45 #endif
47 #ifndef _WIN32
48 #define QGA_VIRTIO_PATH_DEFAULT "/dev/virtio-ports/org.qemu.guest_agent.0"
49 #define QGA_STATE_RELATIVE_DIR "run"
50 #define QGA_SERIAL_PATH_DEFAULT "/dev/ttyS0"
51 #else
52 #define QGA_VIRTIO_PATH_DEFAULT "\\\\.\\Global\\org.qemu.guest_agent.0"
53 #define QGA_STATE_RELATIVE_DIR "qemu-ga"
54 #define QGA_SERIAL_PATH_DEFAULT "COM1"
55 #endif
56 #ifdef CONFIG_FSFREEZE
57 #define QGA_FSFREEZE_HOOK_DEFAULT CONFIG_QEMU_CONFDIR "/fsfreeze-hook"
58 #endif
59 #define QGA_SENTINEL_BYTE 0xFF
60 #define QGA_CONF_DEFAULT CONFIG_QEMU_CONFDIR G_DIR_SEPARATOR_S "qemu-ga.conf"
61 #define QGA_RETRY_INTERVAL 5
63 static struct {
64 const char *state_dir;
65 const char *pidfile;
66 } dfl_pathnames;
68 typedef struct GAPersistentState {
69 #define QGA_PSTATE_DEFAULT_FD_COUNTER 1000
70 int64_t fd_counter;
71 } GAPersistentState;
73 typedef struct GAConfig GAConfig;
75 struct GAState {
76 JSONMessageParser parser;
77 GMainLoop *main_loop;
78 GAChannel *channel;
79 bool virtio; /* fastpath to check for virtio to deal with poll() quirks */
80 GACommandState *command_state;
81 GLogLevelFlags log_level;
82 FILE *log_file;
83 bool logging_enabled;
84 #ifdef _WIN32
85 GAService service;
86 HANDLE wakeup_event;
87 #endif
88 bool delimit_response;
89 bool frozen;
90 GList *blacklist;
91 char *state_filepath_isfrozen;
92 struct {
93 const char *log_filepath;
94 const char *pid_filepath;
95 } deferred_options;
96 #ifdef CONFIG_FSFREEZE
97 const char *fsfreeze_hook;
98 #endif
99 gchar *pstate_filepath;
100 GAPersistentState pstate;
101 GAConfig *config;
102 int socket_activation;
103 bool force_exit;
106 struct GAState *ga_state;
107 QmpCommandList ga_commands;
109 /* commands that are safe to issue while filesystems are frozen */
110 static const char *ga_freeze_whitelist[] = {
111 "guest-ping",
112 "guest-info",
113 "guest-sync",
114 "guest-sync-delimited",
115 "guest-fsfreeze-status",
116 "guest-fsfreeze-thaw",
117 NULL
120 #ifdef _WIN32
121 DWORD WINAPI service_ctrl_handler(DWORD ctrl, DWORD type, LPVOID data,
122 LPVOID ctx);
123 DWORD WINAPI handle_serial_device_events(DWORD type, LPVOID data);
124 VOID WINAPI service_main(DWORD argc, TCHAR *argv[]);
125 #endif
126 static int run_agent(GAState *s);
127 static void stop_agent(GAState *s, bool requested);
129 static void
130 init_dfl_pathnames(void)
132 g_assert(dfl_pathnames.state_dir == NULL);
133 g_assert(dfl_pathnames.pidfile == NULL);
134 dfl_pathnames.state_dir = qemu_get_local_state_pathname(
135 QGA_STATE_RELATIVE_DIR);
136 dfl_pathnames.pidfile = qemu_get_local_state_pathname(
137 QGA_STATE_RELATIVE_DIR G_DIR_SEPARATOR_S "qemu-ga.pid");
140 static void quit_handler(int sig)
142 /* if we're frozen, don't exit unless we're absolutely forced to,
143 * because it's basically impossible for graceful exit to complete
144 * unless all log/pid files are on unfreezable filesystems. there's
145 * also a very likely chance killing the agent before unfreezing
146 * the filesystems is a mistake (or will be viewed as one later).
147 * On Windows the freeze interval is limited to 10 seconds, so
148 * we should quit, but first we should wait for the timeout, thaw
149 * the filesystem and quit.
151 if (ga_is_frozen(ga_state)) {
152 #ifdef _WIN32
153 int i = 0;
154 Error *err = NULL;
155 HANDLE hEventTimeout;
157 g_debug("Thawing filesystems before exiting");
159 hEventTimeout = OpenEvent(EVENT_ALL_ACCESS, FALSE, EVENT_NAME_TIMEOUT);
160 if (hEventTimeout) {
161 WaitForSingleObject(hEventTimeout, 0);
162 CloseHandle(hEventTimeout);
164 qga_vss_fsfreeze(&i, false, NULL, &err);
165 if (err) {
166 g_debug("Error unfreezing filesystems prior to exiting: %s",
167 error_get_pretty(err));
168 error_free(err);
170 #else
171 return;
172 #endif
174 g_debug("received signal num %d, quitting", sig);
176 stop_agent(ga_state, true);
179 #ifndef _WIN32
180 static gboolean register_signal_handlers(void)
182 struct sigaction sigact;
183 int ret;
185 memset(&sigact, 0, sizeof(struct sigaction));
186 sigact.sa_handler = quit_handler;
188 ret = sigaction(SIGINT, &sigact, NULL);
189 if (ret == -1) {
190 g_error("error configuring signal handler: %s", strerror(errno));
192 ret = sigaction(SIGTERM, &sigact, NULL);
193 if (ret == -1) {
194 g_error("error configuring signal handler: %s", strerror(errno));
197 sigact.sa_handler = SIG_IGN;
198 if (sigaction(SIGPIPE, &sigact, NULL) != 0) {
199 g_error("error configuring SIGPIPE signal handler: %s",
200 strerror(errno));
203 return true;
206 /* TODO: use this in place of all post-fork() fclose(std*) callers */
207 void reopen_fd_to_null(int fd)
209 int nullfd;
211 nullfd = open("/dev/null", O_RDWR);
212 if (nullfd < 0) {
213 return;
216 dup2(nullfd, fd);
218 if (nullfd != fd) {
219 close(nullfd);
222 #endif
224 static void usage(const char *cmd)
226 printf(
227 "Usage: %s [-m <method> -p <path>] [<options>]\n"
228 "QEMU Guest Agent " QEMU_FULL_VERSION "\n"
229 QEMU_COPYRIGHT "\n"
230 "\n"
231 " -m, --method transport method: one of unix-listen, virtio-serial,\n"
232 " isa-serial, or vsock-listen (virtio-serial is the default)\n"
233 " -p, --path device/socket path (the default for virtio-serial is:\n"
234 " %s,\n"
235 " the default for isa-serial is:\n"
236 " %s).\n"
237 " Socket addresses for vsock-listen are written as\n"
238 " <cid>:<port>.\n"
239 " -l, --logfile set logfile path, logs to stderr by default\n"
240 " -f, --pidfile specify pidfile (default is %s)\n"
241 #ifdef CONFIG_FSFREEZE
242 " -F, --fsfreeze-hook\n"
243 " enable fsfreeze hook. Accepts an optional argument that\n"
244 " specifies script to run on freeze/thaw. Script will be\n"
245 " called with 'freeze'/'thaw' arguments accordingly.\n"
246 " (default is %s)\n"
247 " If using -F with an argument, do not follow -F with a\n"
248 " space.\n"
249 " (for example: -F/var/run/fsfreezehook.sh)\n"
250 #endif
251 " -t, --statedir specify dir to store state information (absolute paths\n"
252 " only, default is %s)\n"
253 " -v, --verbose log extra debugging information\n"
254 " -V, --version print version information and exit\n"
255 " -d, --daemonize become a daemon\n"
256 #ifdef _WIN32
257 " -s, --service service commands: install, uninstall, vss-install, vss-uninstall\n"
258 #endif
259 " -b, --blacklist comma-separated list of RPCs to disable (no spaces, \"?\"\n"
260 " to list available RPCs)\n"
261 " -D, --dump-conf dump a qemu-ga config file based on current config\n"
262 " options / command-line parameters to stdout\n"
263 " -r, --retry-path attempt re-opening path if it's unavailable or closed\n"
264 " due to an error which may be recoverable in the future\n"
265 " (virtio-serial driver re-install, serial device hot\n"
266 " plug/unplug, etc.)\n"
267 " -h, --help display this help and exit\n"
268 "\n"
269 QEMU_HELP_BOTTOM "\n"
270 , cmd, QGA_VIRTIO_PATH_DEFAULT, QGA_SERIAL_PATH_DEFAULT,
271 dfl_pathnames.pidfile,
272 #ifdef CONFIG_FSFREEZE
273 QGA_FSFREEZE_HOOK_DEFAULT,
274 #endif
275 dfl_pathnames.state_dir);
278 static const char *ga_log_level_str(GLogLevelFlags level)
280 switch (level & G_LOG_LEVEL_MASK) {
281 case G_LOG_LEVEL_ERROR:
282 return "error";
283 case G_LOG_LEVEL_CRITICAL:
284 return "critical";
285 case G_LOG_LEVEL_WARNING:
286 return "warning";
287 case G_LOG_LEVEL_MESSAGE:
288 return "message";
289 case G_LOG_LEVEL_INFO:
290 return "info";
291 case G_LOG_LEVEL_DEBUG:
292 return "debug";
293 default:
294 return "user";
298 bool ga_logging_enabled(GAState *s)
300 return s->logging_enabled;
303 void ga_disable_logging(GAState *s)
305 s->logging_enabled = false;
308 void ga_enable_logging(GAState *s)
310 s->logging_enabled = true;
313 static void ga_log(const gchar *domain, GLogLevelFlags level,
314 const gchar *msg, gpointer opaque)
316 GAState *s = opaque;
317 GTimeVal time;
318 const char *level_str = ga_log_level_str(level);
320 if (!ga_logging_enabled(s)) {
321 return;
324 level &= G_LOG_LEVEL_MASK;
325 #ifndef _WIN32
326 if (g_strcmp0(domain, "syslog") == 0) {
327 syslog(LOG_INFO, "%s: %s", level_str, msg);
328 } else if (level & s->log_level) {
329 #else
330 if (level & s->log_level) {
331 #endif
332 g_get_current_time(&time);
333 fprintf(s->log_file,
334 "%lu.%lu: %s: %s\n", time.tv_sec, time.tv_usec, level_str, msg);
335 fflush(s->log_file);
339 void ga_set_response_delimited(GAState *s)
341 s->delimit_response = true;
344 static FILE *ga_open_logfile(const char *logfile)
346 FILE *f;
348 f = fopen(logfile, "a");
349 if (!f) {
350 return NULL;
353 qemu_set_cloexec(fileno(f));
354 return f;
357 static gint ga_strcmp(gconstpointer str1, gconstpointer str2)
359 return strcmp(str1, str2);
362 /* disable commands that aren't safe for fsfreeze */
363 static void ga_disable_non_whitelisted(const QmpCommand *cmd, void *opaque)
365 bool whitelisted = false;
366 int i = 0;
367 const char *name = qmp_command_name(cmd);
369 while (ga_freeze_whitelist[i] != NULL) {
370 if (strcmp(name, ga_freeze_whitelist[i]) == 0) {
371 whitelisted = true;
373 i++;
375 if (!whitelisted) {
376 g_debug("disabling command: %s", name);
377 qmp_disable_command(&ga_commands, name, "the agent is in frozen state");
381 /* [re-]enable all commands, except those explicitly blacklisted by user */
382 static void ga_enable_non_blacklisted(const QmpCommand *cmd, void *opaque)
384 GList *blacklist = opaque;
385 const char *name = qmp_command_name(cmd);
387 if (g_list_find_custom(blacklist, name, ga_strcmp) == NULL &&
388 !qmp_command_is_enabled(cmd)) {
389 g_debug("enabling command: %s", name);
390 qmp_enable_command(&ga_commands, name);
394 static bool ga_create_file(const char *path)
396 int fd = open(path, O_CREAT | O_WRONLY, S_IWUSR | S_IRUSR);
397 if (fd == -1) {
398 g_warning("unable to open/create file %s: %s", path, strerror(errno));
399 return false;
401 close(fd);
402 return true;
405 static bool ga_delete_file(const char *path)
407 int ret = unlink(path);
408 if (ret == -1) {
409 g_warning("unable to delete file: %s: %s", path, strerror(errno));
410 return false;
413 return true;
416 bool ga_is_frozen(GAState *s)
418 return s->frozen;
421 void ga_set_frozen(GAState *s)
423 if (ga_is_frozen(s)) {
424 return;
426 /* disable all non-whitelisted (for frozen state) commands */
427 qmp_for_each_command(&ga_commands, ga_disable_non_whitelisted, NULL);
428 g_warning("disabling logging due to filesystem freeze");
429 ga_disable_logging(s);
430 s->frozen = true;
431 if (!ga_create_file(s->state_filepath_isfrozen)) {
432 g_warning("unable to create %s, fsfreeze may not function properly",
433 s->state_filepath_isfrozen);
437 void ga_unset_frozen(GAState *s)
439 if (!ga_is_frozen(s)) {
440 return;
443 /* if we delayed creation/opening of pid/log files due to being
444 * in a frozen state at start up, do it now
446 if (s->deferred_options.log_filepath) {
447 s->log_file = ga_open_logfile(s->deferred_options.log_filepath);
448 if (!s->log_file) {
449 s->log_file = stderr;
451 s->deferred_options.log_filepath = NULL;
453 ga_enable_logging(s);
454 g_warning("logging re-enabled due to filesystem unfreeze");
455 if (s->deferred_options.pid_filepath) {
456 Error *err = NULL;
458 if (!qemu_write_pidfile(s->deferred_options.pid_filepath, &err)) {
459 g_warning("%s", error_get_pretty(err));
460 error_free(err);
462 s->deferred_options.pid_filepath = NULL;
465 /* enable all disabled, non-blacklisted commands */
466 qmp_for_each_command(&ga_commands, ga_enable_non_blacklisted, s->blacklist);
467 s->frozen = false;
468 if (!ga_delete_file(s->state_filepath_isfrozen)) {
469 g_warning("unable to delete %s, fsfreeze may not function properly",
470 s->state_filepath_isfrozen);
474 #ifdef CONFIG_FSFREEZE
475 const char *ga_fsfreeze_hook(GAState *s)
477 return s->fsfreeze_hook;
479 #endif
481 static void become_daemon(const char *pidfile)
483 #ifndef _WIN32
484 pid_t pid, sid;
486 pid = fork();
487 if (pid < 0) {
488 exit(EXIT_FAILURE);
490 if (pid > 0) {
491 exit(EXIT_SUCCESS);
494 if (pidfile) {
495 Error *err = NULL;
497 if (!qemu_write_pidfile(pidfile, &err)) {
498 g_critical("%s", error_get_pretty(err));
499 error_free(err);
500 exit(EXIT_FAILURE);
504 umask(S_IRWXG | S_IRWXO);
505 sid = setsid();
506 if (sid < 0) {
507 goto fail;
509 if ((chdir("/")) < 0) {
510 goto fail;
513 reopen_fd_to_null(STDIN_FILENO);
514 reopen_fd_to_null(STDOUT_FILENO);
515 reopen_fd_to_null(STDERR_FILENO);
516 return;
518 fail:
519 if (pidfile) {
520 unlink(pidfile);
522 g_critical("failed to daemonize");
523 exit(EXIT_FAILURE);
524 #endif
527 static int send_response(GAState *s, const QDict *rsp)
529 GString *response;
530 GIOStatus status;
532 g_assert(s->channel);
534 if (!rsp) {
535 return 0;
538 response = qobject_to_json(QOBJECT(rsp));
539 if (!response) {
540 return -EINVAL;
543 if (s->delimit_response) {
544 s->delimit_response = false;
545 g_string_prepend_c(response, QGA_SENTINEL_BYTE);
548 g_string_append_c(response, '\n');
549 status = ga_channel_write_all(s->channel, response->str, response->len);
550 g_string_free(response, true);
551 if (status != G_IO_STATUS_NORMAL) {
552 return -EIO;
555 return 0;
558 /* handle requests/control events coming in over the channel */
559 static void process_event(void *opaque, QObject *obj, Error *err)
561 GAState *s = opaque;
562 QDict *rsp;
563 int ret;
565 g_debug("process_event: called");
566 assert(!obj != !err);
567 if (err) {
568 rsp = qmp_error_response(err);
569 goto end;
572 g_debug("processing command");
573 rsp = qmp_dispatch(&ga_commands, obj, false, NULL);
575 end:
576 ret = send_response(s, rsp);
577 if (ret < 0) {
578 g_warning("error sending error response: %s", strerror(-ret));
580 qobject_unref(rsp);
581 qobject_unref(obj);
584 /* false return signals GAChannel to close the current client connection */
585 static gboolean channel_event_cb(GIOCondition condition, gpointer data)
587 GAState *s = data;
588 gchar buf[QGA_READ_COUNT_DEFAULT + 1];
589 gsize count;
590 GIOStatus status = ga_channel_read(s->channel, buf, QGA_READ_COUNT_DEFAULT, &count);
591 switch (status) {
592 case G_IO_STATUS_ERROR:
593 g_warning("error reading channel");
594 stop_agent(s, false);
595 return false;
596 case G_IO_STATUS_NORMAL:
597 buf[count] = 0;
598 g_debug("read data, count: %d, data: %s", (int)count, buf);
599 json_message_parser_feed(&s->parser, (char *)buf, (int)count);
600 break;
601 case G_IO_STATUS_EOF:
602 g_debug("received EOF");
603 if (!s->virtio) {
604 return false;
606 /* fall through */
607 case G_IO_STATUS_AGAIN:
608 /* virtio causes us to spin here when no process is attached to
609 * host-side chardev. sleep a bit to mitigate this
611 if (s->virtio) {
612 usleep(100 * 1000);
614 return true;
615 default:
616 g_warning("unknown channel read status, closing");
617 return false;
619 return true;
622 static gboolean channel_init(GAState *s, const gchar *method, const gchar *path,
623 int listen_fd)
625 GAChannelMethod channel_method;
627 if (strcmp(method, "virtio-serial") == 0) {
628 s->virtio = true; /* virtio requires special handling in some cases */
629 channel_method = GA_CHANNEL_VIRTIO_SERIAL;
630 } else if (strcmp(method, "isa-serial") == 0) {
631 channel_method = GA_CHANNEL_ISA_SERIAL;
632 } else if (strcmp(method, "unix-listen") == 0) {
633 channel_method = GA_CHANNEL_UNIX_LISTEN;
634 } else if (strcmp(method, "vsock-listen") == 0) {
635 channel_method = GA_CHANNEL_VSOCK_LISTEN;
636 } else {
637 g_critical("unsupported channel method/type: %s", method);
638 return false;
641 s->channel = ga_channel_new(channel_method, path, listen_fd,
642 channel_event_cb, s);
643 if (!s->channel) {
644 g_critical("failed to create guest agent channel");
645 return false;
648 return true;
651 #ifdef _WIN32
652 DWORD WINAPI handle_serial_device_events(DWORD type, LPVOID data)
654 DWORD ret = NO_ERROR;
655 PDEV_BROADCAST_HDR broadcast_header = (PDEV_BROADCAST_HDR)data;
657 if (broadcast_header->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE) {
658 switch (type) {
659 /* Device inserted */
660 case DBT_DEVICEARRIVAL:
661 /* Start QEMU-ga's service */
662 if (!SetEvent(ga_state->wakeup_event)) {
663 ret = GetLastError();
665 break;
666 /* Device removed */
667 case DBT_DEVICEQUERYREMOVE:
668 case DBT_DEVICEREMOVEPENDING:
669 case DBT_DEVICEREMOVECOMPLETE:
670 /* Stop QEMU-ga's service */
671 if (!ResetEvent(ga_state->wakeup_event)) {
672 ret = GetLastError();
674 break;
675 default:
676 ret = ERROR_CALL_NOT_IMPLEMENTED;
679 return ret;
682 DWORD WINAPI service_ctrl_handler(DWORD ctrl, DWORD type, LPVOID data,
683 LPVOID ctx)
685 DWORD ret = NO_ERROR;
686 GAService *service = &ga_state->service;
688 switch (ctrl) {
689 case SERVICE_CONTROL_STOP:
690 case SERVICE_CONTROL_SHUTDOWN:
691 quit_handler(SIGTERM);
692 SetEvent(ga_state->wakeup_event);
693 service->status.dwCurrentState = SERVICE_STOP_PENDING;
694 SetServiceStatus(service->status_handle, &service->status);
695 break;
696 case SERVICE_CONTROL_DEVICEEVENT:
697 handle_serial_device_events(type, data);
698 break;
700 default:
701 ret = ERROR_CALL_NOT_IMPLEMENTED;
703 return ret;
706 VOID WINAPI service_main(DWORD argc, TCHAR *argv[])
708 GAService *service = &ga_state->service;
710 service->status_handle = RegisterServiceCtrlHandlerEx(QGA_SERVICE_NAME,
711 service_ctrl_handler, NULL);
713 if (service->status_handle == 0) {
714 g_critical("Failed to register extended requests function!\n");
715 return;
718 service->status.dwServiceType = SERVICE_WIN32;
719 service->status.dwCurrentState = SERVICE_RUNNING;
720 service->status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
721 service->status.dwWin32ExitCode = NO_ERROR;
722 service->status.dwServiceSpecificExitCode = NO_ERROR;
723 service->status.dwCheckPoint = 0;
724 service->status.dwWaitHint = 0;
725 DEV_BROADCAST_DEVICEINTERFACE notification_filter;
726 ZeroMemory(&notification_filter, sizeof(notification_filter));
727 notification_filter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
728 notification_filter.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE);
729 notification_filter.dbcc_classguid = GUID_VIOSERIAL_PORT;
731 service->device_notification_handle =
732 RegisterDeviceNotification(service->status_handle,
733 &notification_filter, DEVICE_NOTIFY_SERVICE_HANDLE);
734 if (!service->device_notification_handle) {
735 g_critical("Failed to register device notification handle!\n");
736 return;
738 SetServiceStatus(service->status_handle, &service->status);
740 run_agent(ga_state);
742 UnregisterDeviceNotification(service->device_notification_handle);
743 service->status.dwCurrentState = SERVICE_STOPPED;
744 SetServiceStatus(service->status_handle, &service->status);
746 #endif
748 static void set_persistent_state_defaults(GAPersistentState *pstate)
750 g_assert(pstate);
751 pstate->fd_counter = QGA_PSTATE_DEFAULT_FD_COUNTER;
754 static void persistent_state_from_keyfile(GAPersistentState *pstate,
755 GKeyFile *keyfile)
757 g_assert(pstate);
758 g_assert(keyfile);
759 /* if any fields are missing, either because the file was tampered with
760 * by agents of chaos, or because the field wasn't present at the time the
761 * file was created, the best we can ever do is start over with the default
762 * values. so load them now, and ignore any errors in accessing key-value
763 * pairs
765 set_persistent_state_defaults(pstate);
767 if (g_key_file_has_key(keyfile, "global", "fd_counter", NULL)) {
768 pstate->fd_counter =
769 g_key_file_get_integer(keyfile, "global", "fd_counter", NULL);
773 static void persistent_state_to_keyfile(const GAPersistentState *pstate,
774 GKeyFile *keyfile)
776 g_assert(pstate);
777 g_assert(keyfile);
779 g_key_file_set_integer(keyfile, "global", "fd_counter", pstate->fd_counter);
782 static gboolean write_persistent_state(const GAPersistentState *pstate,
783 const gchar *path)
785 GKeyFile *keyfile = g_key_file_new();
786 GError *gerr = NULL;
787 gboolean ret = true;
788 gchar *data = NULL;
789 gsize data_len;
791 g_assert(pstate);
793 persistent_state_to_keyfile(pstate, keyfile);
794 data = g_key_file_to_data(keyfile, &data_len, &gerr);
795 if (gerr) {
796 g_critical("failed to convert persistent state to string: %s",
797 gerr->message);
798 ret = false;
799 goto out;
802 g_file_set_contents(path, data, data_len, &gerr);
803 if (gerr) {
804 g_critical("failed to write persistent state to %s: %s",
805 path, gerr->message);
806 ret = false;
807 goto out;
810 out:
811 if (gerr) {
812 g_error_free(gerr);
814 if (keyfile) {
815 g_key_file_free(keyfile);
817 g_free(data);
818 return ret;
821 static gboolean read_persistent_state(GAPersistentState *pstate,
822 const gchar *path, gboolean frozen)
824 GKeyFile *keyfile = NULL;
825 GError *gerr = NULL;
826 struct stat st;
827 gboolean ret = true;
829 g_assert(pstate);
831 if (stat(path, &st) == -1) {
832 /* it's okay if state file doesn't exist, but any other error
833 * indicates a permissions issue or some other misconfiguration
834 * that we likely won't be able to recover from.
836 if (errno != ENOENT) {
837 g_critical("unable to access state file at path %s: %s",
838 path, strerror(errno));
839 ret = false;
840 goto out;
843 /* file doesn't exist. initialize state to default values and
844 * attempt to save now. (we could wait till later when we have
845 * modified state we need to commit, but if there's a problem,
846 * such as a missing parent directory, we want to catch it now)
848 * there is a potential scenario where someone either managed to
849 * update the agent from a version that didn't use a key store
850 * while qemu-ga thought the filesystem was frozen, or
851 * deleted the key store prior to issuing a fsfreeze, prior
852 * to restarting the agent. in this case we go ahead and defer
853 * initial creation till we actually have modified state to
854 * write, otherwise fail to recover from freeze.
856 set_persistent_state_defaults(pstate);
857 if (!frozen) {
858 ret = write_persistent_state(pstate, path);
859 if (!ret) {
860 g_critical("unable to create state file at path %s", path);
861 ret = false;
862 goto out;
865 ret = true;
866 goto out;
869 keyfile = g_key_file_new();
870 g_key_file_load_from_file(keyfile, path, 0, &gerr);
871 if (gerr) {
872 g_critical("error loading persistent state from path: %s, %s",
873 path, gerr->message);
874 ret = false;
875 goto out;
878 persistent_state_from_keyfile(pstate, keyfile);
880 out:
881 if (keyfile) {
882 g_key_file_free(keyfile);
884 if (gerr) {
885 g_error_free(gerr);
888 return ret;
891 int64_t ga_get_fd_handle(GAState *s, Error **errp)
893 int64_t handle;
895 g_assert(s->pstate_filepath);
896 /* we blacklist commands and avoid operations that potentially require
897 * writing to disk when we're in a frozen state. this includes opening
898 * new files, so we should never get here in that situation
900 g_assert(!ga_is_frozen(s));
902 handle = s->pstate.fd_counter++;
904 /* This should never happen on a reasonable timeframe, as guest-file-open
905 * would have to be issued 2^63 times */
906 if (s->pstate.fd_counter == INT64_MAX) {
907 abort();
910 if (!write_persistent_state(&s->pstate, s->pstate_filepath)) {
911 error_setg(errp, "failed to commit persistent state to disk");
912 return -1;
915 return handle;
918 static void ga_print_cmd(const QmpCommand *cmd, void *opaque)
920 printf("%s\n", qmp_command_name(cmd));
923 static GList *split_list(const gchar *str, const gchar *delim)
925 GList *list = NULL;
926 int i;
927 gchar **strv;
929 strv = g_strsplit(str, delim, -1);
930 for (i = 0; strv[i]; i++) {
931 list = g_list_prepend(list, strv[i]);
933 g_free(strv);
935 return list;
938 struct GAConfig {
939 char *channel_path;
940 char *method;
941 char *log_filepath;
942 char *pid_filepath;
943 #ifdef CONFIG_FSFREEZE
944 char *fsfreeze_hook;
945 #endif
946 char *state_dir;
947 #ifdef _WIN32
948 const char *service;
949 #endif
950 gchar *bliststr; /* blacklist may point to this string */
951 GList *blacklist;
952 int daemonize;
953 GLogLevelFlags log_level;
954 int dumpconf;
955 bool retry_path;
958 static void config_load(GAConfig *config)
960 GError *gerr = NULL;
961 GKeyFile *keyfile;
962 g_autofree char *conf = g_strdup(g_getenv("QGA_CONF")) ?: get_relocated_path(QGA_CONF_DEFAULT);
964 /* read system config */
965 keyfile = g_key_file_new();
966 if (!g_key_file_load_from_file(keyfile, conf, 0, &gerr)) {
967 goto end;
969 if (g_key_file_has_key(keyfile, "general", "daemon", NULL)) {
970 config->daemonize =
971 g_key_file_get_boolean(keyfile, "general", "daemon", &gerr);
973 if (g_key_file_has_key(keyfile, "general", "method", NULL)) {
974 config->method =
975 g_key_file_get_string(keyfile, "general", "method", &gerr);
977 if (g_key_file_has_key(keyfile, "general", "path", NULL)) {
978 config->channel_path =
979 g_key_file_get_string(keyfile, "general", "path", &gerr);
981 if (g_key_file_has_key(keyfile, "general", "logfile", NULL)) {
982 config->log_filepath =
983 g_key_file_get_string(keyfile, "general", "logfile", &gerr);
985 if (g_key_file_has_key(keyfile, "general", "pidfile", NULL)) {
986 config->pid_filepath =
987 g_key_file_get_string(keyfile, "general", "pidfile", &gerr);
989 #ifdef CONFIG_FSFREEZE
990 if (g_key_file_has_key(keyfile, "general", "fsfreeze-hook", NULL)) {
991 config->fsfreeze_hook =
992 g_key_file_get_string(keyfile,
993 "general", "fsfreeze-hook", &gerr);
995 #endif
996 if (g_key_file_has_key(keyfile, "general", "statedir", NULL)) {
997 config->state_dir =
998 g_key_file_get_string(keyfile, "general", "statedir", &gerr);
1000 if (g_key_file_has_key(keyfile, "general", "verbose", NULL) &&
1001 g_key_file_get_boolean(keyfile, "general", "verbose", &gerr)) {
1002 /* enable all log levels */
1003 config->log_level = G_LOG_LEVEL_MASK;
1005 if (g_key_file_has_key(keyfile, "general", "retry-path", NULL)) {
1006 config->retry_path =
1007 g_key_file_get_boolean(keyfile, "general", "retry-path", &gerr);
1009 if (g_key_file_has_key(keyfile, "general", "blacklist", NULL)) {
1010 config->bliststr =
1011 g_key_file_get_string(keyfile, "general", "blacklist", &gerr);
1012 config->blacklist = g_list_concat(config->blacklist,
1013 split_list(config->bliststr, ","));
1016 end:
1017 g_key_file_free(keyfile);
1018 if (gerr &&
1019 !(gerr->domain == G_FILE_ERROR && gerr->code == G_FILE_ERROR_NOENT)) {
1020 g_critical("error loading configuration from path: %s, %s",
1021 conf, gerr->message);
1022 exit(EXIT_FAILURE);
1024 g_clear_error(&gerr);
1027 static gchar *list_join(GList *list, const gchar separator)
1029 GString *str = g_string_new("");
1031 while (list) {
1032 str = g_string_append(str, (gchar *)list->data);
1033 list = g_list_next(list);
1034 if (list) {
1035 str = g_string_append_c(str, separator);
1039 return g_string_free(str, FALSE);
1042 static void config_dump(GAConfig *config)
1044 GError *error = NULL;
1045 GKeyFile *keyfile;
1046 gchar *tmp;
1048 keyfile = g_key_file_new();
1049 g_assert(keyfile);
1051 g_key_file_set_boolean(keyfile, "general", "daemon", config->daemonize);
1052 g_key_file_set_string(keyfile, "general", "method", config->method);
1053 if (config->channel_path) {
1054 g_key_file_set_string(keyfile, "general", "path", config->channel_path);
1056 if (config->log_filepath) {
1057 g_key_file_set_string(keyfile, "general", "logfile",
1058 config->log_filepath);
1060 g_key_file_set_string(keyfile, "general", "pidfile", config->pid_filepath);
1061 #ifdef CONFIG_FSFREEZE
1062 if (config->fsfreeze_hook) {
1063 g_key_file_set_string(keyfile, "general", "fsfreeze-hook",
1064 config->fsfreeze_hook);
1066 #endif
1067 g_key_file_set_string(keyfile, "general", "statedir", config->state_dir);
1068 g_key_file_set_boolean(keyfile, "general", "verbose",
1069 config->log_level == G_LOG_LEVEL_MASK);
1070 g_key_file_set_boolean(keyfile, "general", "retry-path",
1071 config->retry_path);
1072 tmp = list_join(config->blacklist, ',');
1073 g_key_file_set_string(keyfile, "general", "blacklist", tmp);
1074 g_free(tmp);
1076 tmp = g_key_file_to_data(keyfile, NULL, &error);
1077 if (error) {
1078 g_critical("Failed to dump keyfile: %s", error->message);
1079 g_clear_error(&error);
1080 } else {
1081 printf("%s", tmp);
1084 g_free(tmp);
1085 g_key_file_free(keyfile);
1088 static void config_parse(GAConfig *config, int argc, char **argv)
1090 const char *sopt = "hVvdm:p:l:f:F::b:s:t:Dr";
1091 int opt_ind = 0, ch;
1092 const struct option lopt[] = {
1093 { "help", 0, NULL, 'h' },
1094 { "version", 0, NULL, 'V' },
1095 { "dump-conf", 0, NULL, 'D' },
1096 { "logfile", 1, NULL, 'l' },
1097 { "pidfile", 1, NULL, 'f' },
1098 #ifdef CONFIG_FSFREEZE
1099 { "fsfreeze-hook", 2, NULL, 'F' },
1100 #endif
1101 { "verbose", 0, NULL, 'v' },
1102 { "method", 1, NULL, 'm' },
1103 { "path", 1, NULL, 'p' },
1104 { "daemonize", 0, NULL, 'd' },
1105 { "blacklist", 1, NULL, 'b' },
1106 #ifdef _WIN32
1107 { "service", 1, NULL, 's' },
1108 #endif
1109 { "statedir", 1, NULL, 't' },
1110 { "retry-path", 0, NULL, 'r' },
1111 { NULL, 0, NULL, 0 }
1114 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
1115 switch (ch) {
1116 case 'm':
1117 g_free(config->method);
1118 config->method = g_strdup(optarg);
1119 break;
1120 case 'p':
1121 g_free(config->channel_path);
1122 config->channel_path = g_strdup(optarg);
1123 break;
1124 case 'l':
1125 g_free(config->log_filepath);
1126 config->log_filepath = g_strdup(optarg);
1127 break;
1128 case 'f':
1129 g_free(config->pid_filepath);
1130 config->pid_filepath = g_strdup(optarg);
1131 break;
1132 #ifdef CONFIG_FSFREEZE
1133 case 'F':
1134 g_free(config->fsfreeze_hook);
1135 config->fsfreeze_hook = optarg ? g_strdup(optarg) : get_relocated_path(QGA_FSFREEZE_HOOK_DEFAULT);
1136 break;
1137 #endif
1138 case 't':
1139 g_free(config->state_dir);
1140 config->state_dir = g_strdup(optarg);
1141 break;
1142 case 'v':
1143 /* enable all log levels */
1144 config->log_level = G_LOG_LEVEL_MASK;
1145 break;
1146 case 'V':
1147 printf("QEMU Guest Agent %s\n", QEMU_VERSION);
1148 exit(EXIT_SUCCESS);
1149 case 'd':
1150 config->daemonize = 1;
1151 break;
1152 case 'D':
1153 config->dumpconf = 1;
1154 break;
1155 case 'r':
1156 config->retry_path = true;
1157 break;
1158 case 'b': {
1159 if (is_help_option(optarg)) {
1160 qmp_for_each_command(&ga_commands, ga_print_cmd, NULL);
1161 exit(EXIT_SUCCESS);
1163 config->blacklist = g_list_concat(config->blacklist,
1164 split_list(optarg, ","));
1165 break;
1167 #ifdef _WIN32
1168 case 's':
1169 config->service = optarg;
1170 if (strcmp(config->service, "install") == 0) {
1171 if (ga_install_vss_provider()) {
1172 exit(EXIT_FAILURE);
1174 if (ga_install_service(config->channel_path,
1175 config->log_filepath, config->state_dir)) {
1176 exit(EXIT_FAILURE);
1178 exit(EXIT_SUCCESS);
1179 } else if (strcmp(config->service, "uninstall") == 0) {
1180 ga_uninstall_vss_provider();
1181 exit(ga_uninstall_service());
1182 } else if (strcmp(config->service, "vss-install") == 0) {
1183 if (ga_install_vss_provider()) {
1184 exit(EXIT_FAILURE);
1186 exit(EXIT_SUCCESS);
1187 } else if (strcmp(config->service, "vss-uninstall") == 0) {
1188 ga_uninstall_vss_provider();
1189 exit(EXIT_SUCCESS);
1190 } else {
1191 printf("Unknown service command.\n");
1192 exit(EXIT_FAILURE);
1194 break;
1195 #endif
1196 case 'h':
1197 usage(argv[0]);
1198 exit(EXIT_SUCCESS);
1199 case '?':
1200 g_print("Unknown option, try '%s --help' for more information.\n",
1201 argv[0]);
1202 exit(EXIT_FAILURE);
1207 static void config_free(GAConfig *config)
1209 g_free(config->method);
1210 g_free(config->log_filepath);
1211 g_free(config->pid_filepath);
1212 g_free(config->state_dir);
1213 g_free(config->channel_path);
1214 g_free(config->bliststr);
1215 #ifdef CONFIG_FSFREEZE
1216 g_free(config->fsfreeze_hook);
1217 #endif
1218 g_list_free_full(config->blacklist, g_free);
1219 g_free(config);
1222 static bool check_is_frozen(GAState *s)
1224 #ifndef _WIN32
1225 /* check if a previous instance of qemu-ga exited with filesystems' state
1226 * marked as frozen. this could be a stale value (a non-qemu-ga process
1227 * or reboot may have since unfrozen them), but better to require an
1228 * uneeded unfreeze than to risk hanging on start-up
1230 struct stat st;
1231 if (stat(s->state_filepath_isfrozen, &st) == -1) {
1232 /* it's okay if the file doesn't exist, but if we can't access for
1233 * some other reason, such as permissions, there's a configuration
1234 * that needs to be addressed. so just bail now before we get into
1235 * more trouble later
1237 if (errno != ENOENT) {
1238 g_critical("unable to access state file at path %s: %s",
1239 s->state_filepath_isfrozen, strerror(errno));
1240 return EXIT_FAILURE;
1242 } else {
1243 g_warning("previous instance appears to have exited with frozen"
1244 " filesystems. deferring logging/pidfile creation and"
1245 " disabling non-fsfreeze-safe commands until"
1246 " guest-fsfreeze-thaw is issued, or filesystems are"
1247 " manually unfrozen and the file %s is removed",
1248 s->state_filepath_isfrozen);
1249 return true;
1251 #endif
1252 return false;
1255 static GAState *initialize_agent(GAConfig *config, int socket_activation)
1257 GAState *s = g_new0(GAState, 1);
1259 g_assert(ga_state == NULL);
1261 s->log_level = config->log_level;
1262 s->log_file = stderr;
1263 #ifdef CONFIG_FSFREEZE
1264 s->fsfreeze_hook = config->fsfreeze_hook;
1265 #endif
1266 s->pstate_filepath = g_strdup_printf("%s/qga.state", config->state_dir);
1267 s->state_filepath_isfrozen = g_strdup_printf("%s/qga.state.isfrozen",
1268 config->state_dir);
1269 s->frozen = check_is_frozen(s);
1271 g_log_set_default_handler(ga_log, s);
1272 g_log_set_fatal_mask(NULL, G_LOG_LEVEL_ERROR);
1273 ga_enable_logging(s);
1275 #ifdef _WIN32
1276 /* On win32 the state directory is application specific (be it the default
1277 * or a user override). We got past the command line parsing; let's create
1278 * the directory (with any intermediate directories). If we run into an
1279 * error later on, we won't try to clean up the directory, it is considered
1280 * persistent.
1282 if (g_mkdir_with_parents(config->state_dir, S_IRWXU) == -1) {
1283 g_critical("unable to create (an ancestor of) the state directory"
1284 " '%s': %s", config->state_dir, strerror(errno));
1285 return NULL;
1287 #endif
1289 if (ga_is_frozen(s)) {
1290 if (config->daemonize) {
1291 /* delay opening/locking of pidfile till filesystems are unfrozen */
1292 s->deferred_options.pid_filepath = config->pid_filepath;
1293 become_daemon(NULL);
1295 if (config->log_filepath) {
1296 /* delay opening the log file till filesystems are unfrozen */
1297 s->deferred_options.log_filepath = config->log_filepath;
1299 ga_disable_logging(s);
1300 qmp_for_each_command(&ga_commands, ga_disable_non_whitelisted, NULL);
1301 } else {
1302 if (config->daemonize) {
1303 become_daemon(config->pid_filepath);
1305 if (config->log_filepath) {
1306 FILE *log_file = ga_open_logfile(config->log_filepath);
1307 if (!log_file) {
1308 g_critical("unable to open specified log file: %s",
1309 strerror(errno));
1310 return NULL;
1312 s->log_file = log_file;
1316 /* load persistent state from disk */
1317 if (!read_persistent_state(&s->pstate,
1318 s->pstate_filepath,
1319 ga_is_frozen(s))) {
1320 g_critical("failed to load persistent state");
1321 return NULL;
1324 config->blacklist = ga_command_blacklist_init(config->blacklist);
1325 if (config->blacklist) {
1326 GList *l = config->blacklist;
1327 s->blacklist = config->blacklist;
1328 do {
1329 g_debug("disabling command: %s", (char *)l->data);
1330 qmp_disable_command(&ga_commands, l->data, NULL);
1331 l = g_list_next(l);
1332 } while (l);
1334 s->command_state = ga_command_state_new();
1335 ga_command_state_init(s, s->command_state);
1336 ga_command_state_init_all(s->command_state);
1337 json_message_parser_init(&s->parser, process_event, s, NULL);
1339 #ifndef _WIN32
1340 if (!register_signal_handlers()) {
1341 g_critical("failed to register signal handlers");
1342 return NULL;
1344 #endif
1346 s->main_loop = g_main_loop_new(NULL, false);
1348 s->config = config;
1349 s->socket_activation = socket_activation;
1351 #ifdef _WIN32
1352 s->wakeup_event = CreateEvent(NULL, TRUE, FALSE, TEXT("WakeUp"));
1353 if (s->wakeup_event == NULL) {
1354 g_critical("CreateEvent failed");
1355 return NULL;
1357 #endif
1359 ga_state = s;
1360 return s;
1363 static void cleanup_agent(GAState *s)
1365 #ifdef _WIN32
1366 CloseHandle(s->wakeup_event);
1367 #endif
1368 if (s->command_state) {
1369 ga_command_state_cleanup_all(s->command_state);
1370 ga_command_state_free(s->command_state);
1371 json_message_parser_destroy(&s->parser);
1373 g_free(s->pstate_filepath);
1374 g_free(s->state_filepath_isfrozen);
1375 if (s->main_loop) {
1376 g_main_loop_unref(s->main_loop);
1378 g_free(s);
1379 ga_state = NULL;
1382 static int run_agent_once(GAState *s)
1384 if (!channel_init(s, s->config->method, s->config->channel_path,
1385 s->socket_activation ? FIRST_SOCKET_ACTIVATION_FD : -1)) {
1386 g_critical("failed to initialize guest agent channel");
1387 return EXIT_FAILURE;
1390 g_main_loop_run(ga_state->main_loop);
1392 if (s->channel) {
1393 ga_channel_free(s->channel);
1396 return EXIT_SUCCESS;
1399 static void wait_for_channel_availability(GAState *s)
1401 g_warning("waiting for channel path...");
1402 #ifndef _WIN32
1403 sleep(QGA_RETRY_INTERVAL);
1404 #else
1405 DWORD dwWaitResult;
1407 dwWaitResult = WaitForSingleObject(s->wakeup_event, INFINITE);
1409 switch (dwWaitResult) {
1410 case WAIT_OBJECT_0:
1411 break;
1412 case WAIT_TIMEOUT:
1413 break;
1414 default:
1415 g_critical("WaitForSingleObject failed");
1417 #endif
1420 static int run_agent(GAState *s)
1422 int ret = EXIT_SUCCESS;
1424 s->force_exit = false;
1426 do {
1427 ret = run_agent_once(s);
1428 if (s->config->retry_path && !s->force_exit) {
1429 g_warning("agent stopped unexpectedly, restarting...");
1430 wait_for_channel_availability(s);
1432 } while (s->config->retry_path && !s->force_exit);
1434 return ret;
1437 static void stop_agent(GAState *s, bool requested)
1439 if (!s->force_exit) {
1440 s->force_exit = requested;
1443 if (g_main_loop_is_running(s->main_loop)) {
1444 g_main_loop_quit(s->main_loop);
1448 int main(int argc, char **argv)
1450 int ret = EXIT_SUCCESS;
1451 GAState *s;
1452 GAConfig *config = g_new0(GAConfig, 1);
1453 int socket_activation;
1455 config->log_level = G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL;
1457 qemu_init_exec_dir(argv[0]);
1458 qga_qmp_init_marshal(&ga_commands);
1460 init_dfl_pathnames();
1461 config_load(config);
1462 config_parse(config, argc, argv);
1464 if (config->pid_filepath == NULL) {
1465 config->pid_filepath = g_strdup(dfl_pathnames.pidfile);
1468 if (config->state_dir == NULL) {
1469 config->state_dir = g_strdup(dfl_pathnames.state_dir);
1472 if (config->method == NULL) {
1473 config->method = g_strdup("virtio-serial");
1476 socket_activation = check_socket_activation();
1477 if (socket_activation > 1) {
1478 g_critical("qemu-ga only supports listening on one socket");
1479 ret = EXIT_FAILURE;
1480 goto end;
1482 if (socket_activation) {
1483 SocketAddress *addr;
1485 g_free(config->method);
1486 g_free(config->channel_path);
1487 config->method = NULL;
1488 config->channel_path = NULL;
1490 addr = socket_local_address(FIRST_SOCKET_ACTIVATION_FD, NULL);
1491 if (addr) {
1492 if (addr->type == SOCKET_ADDRESS_TYPE_UNIX) {
1493 config->method = g_strdup("unix-listen");
1494 } else if (addr->type == SOCKET_ADDRESS_TYPE_VSOCK) {
1495 config->method = g_strdup("vsock-listen");
1498 qapi_free_SocketAddress(addr);
1501 if (!config->method) {
1502 g_critical("unsupported listen fd type");
1503 ret = EXIT_FAILURE;
1504 goto end;
1506 } else if (config->channel_path == NULL) {
1507 if (strcmp(config->method, "virtio-serial") == 0) {
1508 /* try the default path for the virtio-serial port */
1509 config->channel_path = g_strdup(QGA_VIRTIO_PATH_DEFAULT);
1510 } else if (strcmp(config->method, "isa-serial") == 0) {
1511 /* try the default path for the serial port - COM1 */
1512 config->channel_path = g_strdup(QGA_SERIAL_PATH_DEFAULT);
1513 } else {
1514 g_critical("must specify a path for this channel");
1515 ret = EXIT_FAILURE;
1516 goto end;
1520 if (config->dumpconf) {
1521 config_dump(config);
1522 goto end;
1525 s = initialize_agent(config, socket_activation);
1526 if (!s) {
1527 g_critical("error initializing guest agent");
1528 goto end;
1531 #ifdef _WIN32
1532 if (config->daemonize) {
1533 SERVICE_TABLE_ENTRY service_table[] = {
1534 { (char *)QGA_SERVICE_NAME, service_main }, { NULL, NULL } };
1535 StartServiceCtrlDispatcher(service_table);
1536 } else {
1537 ret = run_agent(s);
1539 #else
1540 ret = run_agent(s);
1541 #endif
1543 cleanup_agent(s);
1545 end:
1546 if (config->daemonize) {
1547 unlink(config->pid_filepath);
1550 config_free(config);
1552 return ret;