xref: /openbmc/qemu/qga/main.c (revision 764a6ee9)
1 /*
2  * QEMU Guest Agent
3  *
4  * Copyright IBM Corp. 2011
5  *
6  * Authors:
7  *  Adam Litke        <aglitke@linux.vnet.ibm.com>
8  *  Michael Roth      <mdroth@linux.vnet.ibm.com>
9  *
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.
12  */
13 
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/help-texts.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/error.h"
28 #include "channel.h"
29 #include "qemu/cutils.h"
30 #include "qemu/help_option.h"
31 #include "qemu/sockets.h"
32 #include "qemu/systemd.h"
33 #include "qemu-version.h"
34 #ifdef _WIN32
35 #include <dbt.h>
36 #include "qga/service-win32.h"
37 #include "qga/vss-win32.h"
38 #endif
39 #include "commands-common.h"
40 
41 #ifndef _WIN32
42 #ifdef CONFIG_BSD
43 #define QGA_VIRTIO_PATH_DEFAULT "/dev/vtcon/org.qemu.guest_agent.0"
44 #else /* CONFIG_BSD */
45 #define QGA_VIRTIO_PATH_DEFAULT "/dev/virtio-ports/org.qemu.guest_agent.0"
46 #endif /* CONFIG_BSD */
47 #define QGA_SERIAL_PATH_DEFAULT "/dev/ttyS0"
48 #define QGA_STATE_RELATIVE_DIR  "run"
49 #else
50 #define QGA_VIRTIO_PATH_DEFAULT "\\\\.\\Global\\org.qemu.guest_agent.0"
51 #define QGA_STATE_RELATIVE_DIR  "qemu-ga"
52 #define QGA_SERIAL_PATH_DEFAULT "COM1"
53 #endif
54 #ifdef CONFIG_FSFREEZE
55 #define QGA_FSFREEZE_HOOK_DEFAULT CONFIG_QEMU_CONFDIR "/fsfreeze-hook"
56 #endif
57 #define QGA_SENTINEL_BYTE 0xFF
58 #define QGA_CONF_DEFAULT CONFIG_QEMU_CONFDIR G_DIR_SEPARATOR_S "qemu-ga.conf"
59 #define QGA_RETRY_INTERVAL 5
60 
61 static struct {
62     const char *state_dir;
63     const char *pidfile;
64 } dfl_pathnames;
65 
66 typedef struct GAPersistentState {
67 #define QGA_PSTATE_DEFAULT_FD_COUNTER 1000
68     int64_t fd_counter;
69 } GAPersistentState;
70 
71 typedef struct GAConfig GAConfig;
72 
73 struct GAConfig {
74     char *channel_path;
75     char *method;
76     char *log_filepath;
77     char *pid_filepath;
78 #ifdef CONFIG_FSFREEZE
79     char *fsfreeze_hook;
80 #endif
81     char *state_dir;
82 #ifdef _WIN32
83     const char *service;
84 #endif
85     gchar *bliststr; /* blockedrpcs may point to this string */
86     gchar *aliststr; /* allowedrpcs may point to this string */
87     GList *blockedrpcs;
88     GList *allowedrpcs;
89     int daemonize;
90     GLogLevelFlags log_level;
91     int dumpconf;
92     bool retry_path;
93 };
94 
95 struct GAState {
96     JSONMessageParser parser;
97     GMainLoop *main_loop;
98     GAChannel *channel;
99     bool virtio; /* fastpath to check for virtio to deal with poll() quirks */
100     GACommandState *command_state;
101     GLogLevelFlags log_level;
102     FILE *log_file;
103     bool logging_enabled;
104 #ifdef _WIN32
105     GAService service;
106     HANDLE wakeup_event;
107     HANDLE event_log;
108 #endif
109     bool delimit_response;
110     bool frozen;
111     GList *blockedrpcs;
112     GList *allowedrpcs;
113     char *state_filepath_isfrozen;
114     struct {
115         const char *log_filepath;
116         const char *pid_filepath;
117     } deferred_options;
118 #ifdef CONFIG_FSFREEZE
119     const char *fsfreeze_hook;
120 #endif
121     gchar *pstate_filepath;
122     GAPersistentState pstate;
123     GAConfig *config;
124     int socket_activation;
125     bool force_exit;
126 };
127 
128 struct GAState *ga_state;
129 QmpCommandList ga_commands;
130 
131 /* commands that are safe to issue while filesystems are frozen */
132 static const char *ga_freeze_allowlist[] = {
133     "guest-ping",
134     "guest-info",
135     "guest-sync",
136     "guest-sync-delimited",
137     "guest-fsfreeze-status",
138     "guest-fsfreeze-thaw",
139     NULL
140 };
141 
142 #ifdef _WIN32
143 DWORD WINAPI service_ctrl_handler(DWORD ctrl, DWORD type, LPVOID data,
144                                   LPVOID ctx);
145 DWORD WINAPI handle_serial_device_events(DWORD type, LPVOID data);
146 VOID WINAPI service_main(DWORD argc, TCHAR *argv[]);
147 #endif
148 static int run_agent(GAState *s);
149 static void stop_agent(GAState *s, bool requested);
150 
151 static void
152 init_dfl_pathnames(void)
153 {
154     g_autofree char *state = qemu_get_local_state_dir();
155 
156     g_assert(dfl_pathnames.state_dir == NULL);
157     g_assert(dfl_pathnames.pidfile == NULL);
158     dfl_pathnames.state_dir = g_build_filename(state, QGA_STATE_RELATIVE_DIR, NULL);
159     dfl_pathnames.pidfile = g_build_filename(state, QGA_STATE_RELATIVE_DIR, "qemu-ga.pid", NULL);
160 }
161 
162 static void quit_handler(int sig)
163 {
164     /* if we're frozen, don't exit unless we're absolutely forced to,
165      * because it's basically impossible for graceful exit to complete
166      * unless all log/pid files are on unfreezable filesystems. there's
167      * also a very likely chance killing the agent before unfreezing
168      * the filesystems is a mistake (or will be viewed as one later).
169      * On Windows the freeze interval is limited to 10 seconds, so
170      * we should quit, but first we should wait for the timeout, thaw
171      * the filesystem and quit.
172      */
173     if (ga_is_frozen(ga_state)) {
174 #ifdef _WIN32
175         int i = 0;
176         Error *err = NULL;
177         HANDLE hEventTimeout;
178 
179         g_debug("Thawing filesystems before exiting");
180 
181         hEventTimeout = OpenEvent(EVENT_ALL_ACCESS, FALSE, EVENT_NAME_TIMEOUT);
182         if (hEventTimeout) {
183             WaitForSingleObject(hEventTimeout, 0);
184             CloseHandle(hEventTimeout);
185         }
186         qga_vss_fsfreeze(&i, false, NULL, &err);
187         if (err) {
188             g_debug("Error unfreezing filesystems prior to exiting: %s",
189                 error_get_pretty(err));
190             error_free(err);
191         }
192 #else
193         return;
194 #endif
195     }
196     g_debug("received signal num %d, quitting", sig);
197 
198     stop_agent(ga_state, true);
199 }
200 
201 #ifndef _WIN32
202 static gboolean register_signal_handlers(void)
203 {
204     struct sigaction sigact;
205     int ret;
206 
207     memset(&sigact, 0, sizeof(struct sigaction));
208     sigact.sa_handler = quit_handler;
209 
210     ret = sigaction(SIGINT, &sigact, NULL);
211     if (ret == -1) {
212         g_error("error configuring signal handler: %s", strerror(errno));
213     }
214     ret = sigaction(SIGTERM, &sigact, NULL);
215     if (ret == -1) {
216         g_error("error configuring signal handler: %s", strerror(errno));
217     }
218 
219     sigact.sa_handler = SIG_IGN;
220     if (sigaction(SIGPIPE, &sigact, NULL) != 0) {
221         g_error("error configuring SIGPIPE signal handler: %s",
222                 strerror(errno));
223     }
224 
225     return true;
226 }
227 
228 /* TODO: use this in place of all post-fork() fclose(std*) callers */
229 void reopen_fd_to_null(int fd)
230 {
231     int nullfd;
232 
233     nullfd = open("/dev/null", O_RDWR);
234     if (nullfd < 0) {
235         return;
236     }
237 
238     dup2(nullfd, fd);
239 
240     if (nullfd != fd) {
241         close(nullfd);
242     }
243 }
244 #endif
245 
246 static void usage(const char *cmd)
247 {
248 #ifdef CONFIG_FSFREEZE
249     g_autofree char *fsfreeze_hook = get_relocated_path(QGA_FSFREEZE_HOOK_DEFAULT);
250 #endif
251     g_autofree char *conf_path = get_relocated_path(QGA_CONF_DEFAULT);
252 
253     printf(
254 "Usage: %s [-m <method> -p <path>] [<options>]\n"
255 "QEMU Guest Agent " QEMU_FULL_VERSION "\n"
256 QEMU_COPYRIGHT "\n"
257 "\n"
258 "  -c, --config=PATH configuration file path (default is\n"
259 "                    %s/qemu-ga.conf\n"
260 "                    unless overridden by the QGA_CONF environment variable)\n"
261 "  -m, --method      transport method: one of unix-listen, virtio-serial,\n"
262 "                    isa-serial, or vsock-listen (virtio-serial is the default)\n"
263 "  -p, --path        device/socket path (the default for virtio-serial is:\n"
264 "                    %s,\n"
265 "                    the default for isa-serial is:\n"
266 "                    %s).\n"
267 "                    Socket addresses for vsock-listen are written as\n"
268 "                    <cid>:<port>.\n"
269 "  -l, --logfile     set logfile path, logs to stderr by default\n"
270 "  -f, --pidfile     specify pidfile (default is %s)\n"
271 #ifdef CONFIG_FSFREEZE
272 "  -F, --fsfreeze-hook\n"
273 "                    enable fsfreeze hook. Accepts an optional argument that\n"
274 "                    specifies script to run on freeze/thaw. Script will be\n"
275 "                    called with 'freeze'/'thaw' arguments accordingly.\n"
276 "                    (default is %s)\n"
277 "                    If using -F with an argument, do not follow -F with a\n"
278 "                    space.\n"
279 "                    (for example: -F/var/run/fsfreezehook.sh)\n"
280 #endif
281 "  -t, --statedir    specify dir to store state information (absolute paths\n"
282 "                    only, default is %s)\n"
283 "  -v, --verbose     log extra debugging information\n"
284 "  -V, --version     print version information and exit\n"
285 "  -d, --daemonize   become a daemon\n"
286 #ifdef _WIN32
287 "  -s, --service     service commands: install, uninstall, vss-install, vss-uninstall\n"
288 #endif
289 "  -b, --block-rpcs  comma-separated list of RPCs to disable (no spaces,\n"
290 "                    use \"--block-rpcs=help\" to list available RPCs)\n"
291 "  -a, --allow-rpcs  comma-separated list of RPCs to enable (no spaces,\n"
292 "                    use \"--allow-rpcs=help\" to list available RPCs)\n"
293 "  -D, --dump-conf   dump a qemu-ga config file based on current config\n"
294 "                    options / command-line parameters to stdout\n"
295 "  -r, --retry-path  attempt re-opening path if it's unavailable or closed\n"
296 "                    due to an error which may be recoverable in the future\n"
297 "                    (virtio-serial driver re-install, serial device hot\n"
298 "                    plug/unplug, etc.)\n"
299 "  -h, --help        display this help and exit\n"
300 "\n"
301 QEMU_HELP_BOTTOM "\n",
302     cmd, conf_path, QGA_VIRTIO_PATH_DEFAULT, QGA_SERIAL_PATH_DEFAULT,
303     dfl_pathnames.pidfile,
304 #ifdef CONFIG_FSFREEZE
305     fsfreeze_hook,
306 #endif
307     dfl_pathnames.state_dir);
308 }
309 
310 static const char *ga_log_level_str(GLogLevelFlags level)
311 {
312     switch (level & G_LOG_LEVEL_MASK) {
313     case G_LOG_LEVEL_ERROR:
314         return "error";
315     case G_LOG_LEVEL_CRITICAL:
316         return "critical";
317     case G_LOG_LEVEL_WARNING:
318         return "warning";
319     case G_LOG_LEVEL_MESSAGE:
320         return "message";
321     case G_LOG_LEVEL_INFO:
322         return "info";
323     case G_LOG_LEVEL_DEBUG:
324         return "debug";
325     default:
326         return "user";
327     }
328 }
329 
330 bool ga_logging_enabled(GAState *s)
331 {
332     return s->logging_enabled;
333 }
334 
335 void ga_disable_logging(GAState *s)
336 {
337     s->logging_enabled = false;
338 }
339 
340 void ga_enable_logging(GAState *s)
341 {
342     s->logging_enabled = true;
343 }
344 
345 static int glib_log_level_to_system(int level)
346 {
347     switch (level) {
348 #ifndef _WIN32
349     case G_LOG_LEVEL_ERROR:
350         return LOG_ERR;
351     case G_LOG_LEVEL_CRITICAL:
352         return LOG_CRIT;
353     case G_LOG_LEVEL_WARNING:
354         return LOG_WARNING;
355     case G_LOG_LEVEL_MESSAGE:
356         return LOG_NOTICE;
357     case G_LOG_LEVEL_DEBUG:
358         return LOG_DEBUG;
359     case G_LOG_LEVEL_INFO:
360     default:
361         return LOG_INFO;
362 #else
363     case G_LOG_LEVEL_ERROR:
364     case G_LOG_LEVEL_CRITICAL:
365         return EVENTLOG_ERROR_TYPE;
366     case G_LOG_LEVEL_WARNING:
367         return EVENTLOG_WARNING_TYPE;
368     case G_LOG_LEVEL_MESSAGE:
369     case G_LOG_LEVEL_INFO:
370     case G_LOG_LEVEL_DEBUG:
371     default:
372         return EVENTLOG_INFORMATION_TYPE;
373 #endif
374     }
375 }
376 
377 static void ga_log(const gchar *domain, GLogLevelFlags level,
378                    const gchar *msg, gpointer opaque)
379 {
380     GAState *s = opaque;
381     const char *level_str = ga_log_level_str(level);
382 
383     if (!ga_logging_enabled(s)) {
384         return;
385     }
386 
387     level &= G_LOG_LEVEL_MASK;
388     if (g_strcmp0(domain, "syslog") == 0) {
389 #ifndef _WIN32
390         syslog(glib_log_level_to_system(level), "%s: %s", level_str, msg);
391 #else
392         ReportEvent(s->event_log, glib_log_level_to_system(level),
393                     0, 1, NULL, 1, 0, &msg, NULL);
394 #endif
395     } else if (level & s->log_level) {
396         g_autoptr(GDateTime) now = g_date_time_new_now_utc();
397         g_autofree char *nowstr = g_date_time_format(now, "%s.%f");
398         fprintf(s->log_file, "%s: %s: %s\n", nowstr, level_str, msg);
399         fflush(s->log_file);
400     }
401 }
402 
403 void ga_set_response_delimited(GAState *s)
404 {
405     s->delimit_response = true;
406 }
407 
408 static FILE *ga_open_logfile(const char *logfile)
409 {
410     FILE *f;
411 
412     f = fopen(logfile, "a");
413     if (!f) {
414         return NULL;
415     }
416 
417     qemu_set_cloexec(fileno(f));
418     return f;
419 }
420 
421 static gint ga_strcmp(gconstpointer str1, gconstpointer str2)
422 {
423     return strcmp(str1, str2);
424 }
425 
426 static bool ga_command_is_allowed(const QmpCommand *cmd, GAState *state)
427 {
428     int i = 0;
429     GAConfig *config = state->config;
430     const char *name = qmp_command_name(cmd);
431     /* Fallback policy is allow everything */
432     bool allowed = true;
433 
434     if (config->allowedrpcs) {
435         /*
436          * If an allow-list is given, this changes the fallback
437          * policy to deny everything
438          */
439         allowed = false;
440 
441         if (g_list_find_custom(config->allowedrpcs, name, ga_strcmp) != NULL) {
442             allowed = true;
443         }
444     }
445 
446     /*
447      * If both allowedrpcs and blockedrpcs are set, the blocked
448      * list will take priority
449      */
450     if (config->blockedrpcs) {
451         if (g_list_find_custom(config->blockedrpcs, name, ga_strcmp) != NULL) {
452             allowed = false;
453         }
454     }
455 
456     /*
457      * If frozen, this filtering must take priority over
458      * absolutely everything
459      */
460     if (state->frozen) {
461         allowed = false;
462 
463         while (ga_freeze_allowlist[i] != NULL) {
464             if (strcmp(name, ga_freeze_allowlist[i]) == 0) {
465                 allowed = true;
466             }
467             i++;
468         }
469     }
470 
471     return allowed;
472 }
473 
474 static void ga_apply_command_filters_iter(const QmpCommand *cmd, void *opaque)
475 {
476     GAState *state = opaque;
477     bool want = ga_command_is_allowed(cmd, state);
478     bool have = qmp_command_is_enabled(cmd);
479     const char *name = qmp_command_name(cmd);
480 
481     if (want == have) {
482         return;
483     }
484 
485     if (have) {
486         g_debug("disabling command: %s", name);
487         qmp_disable_command(&ga_commands, name, "the command is not allowed");
488     } else {
489         g_debug("enabling command: %s", name);
490         qmp_enable_command(&ga_commands, name);
491     }
492 }
493 
494 static void ga_apply_command_filters(GAState *state)
495 {
496     qmp_for_each_command(&ga_commands, ga_apply_command_filters_iter, state);
497 }
498 
499 static bool ga_create_file(const char *path)
500 {
501     int fd = open(path, O_CREAT | O_WRONLY, S_IWUSR | S_IRUSR);
502     if (fd == -1) {
503         g_warning("unable to open/create file %s: %s", path, strerror(errno));
504         return false;
505     }
506     close(fd);
507     return true;
508 }
509 
510 static bool ga_delete_file(const char *path)
511 {
512     int ret = unlink(path);
513     if (ret == -1) {
514         g_warning("unable to delete file: %s: %s", path, strerror(errno));
515         return false;
516     }
517 
518     return true;
519 }
520 
521 bool ga_is_frozen(GAState *s)
522 {
523     return s->frozen;
524 }
525 
526 void ga_set_frozen(GAState *s)
527 {
528     if (ga_is_frozen(s)) {
529         return;
530     }
531     g_warning("disabling logging due to filesystem freeze");
532     s->frozen = true;
533     if (!ga_create_file(s->state_filepath_isfrozen)) {
534         g_warning("unable to create %s, fsfreeze may not function properly",
535                   s->state_filepath_isfrozen);
536     }
537     ga_apply_command_filters(s);
538     ga_disable_logging(s);
539 }
540 
541 void ga_unset_frozen(GAState *s)
542 {
543     if (!ga_is_frozen(s)) {
544         return;
545     }
546 
547     /* if we delayed creation/opening of pid/log files due to being
548      * in a frozen state at start up, do it now
549      */
550     if (s->deferred_options.log_filepath) {
551         s->log_file = ga_open_logfile(s->deferred_options.log_filepath);
552         if (!s->log_file) {
553             s->log_file = stderr;
554         }
555         s->deferred_options.log_filepath = NULL;
556     }
557     ga_enable_logging(s);
558     g_warning("logging re-enabled due to filesystem unfreeze");
559     if (s->deferred_options.pid_filepath) {
560         Error *err = NULL;
561 
562         if (!qemu_write_pidfile(s->deferred_options.pid_filepath, &err)) {
563             g_warning("%s", error_get_pretty(err));
564             error_free(err);
565         }
566         s->deferred_options.pid_filepath = NULL;
567     }
568 
569     /* enable all disabled, non-blocked and allowed commands */
570     s->frozen = false;
571     if (!ga_delete_file(s->state_filepath_isfrozen)) {
572         g_warning("unable to delete %s, fsfreeze may not function properly",
573                   s->state_filepath_isfrozen);
574     }
575     ga_apply_command_filters(s);
576 }
577 
578 #ifdef CONFIG_FSFREEZE
579 const char *ga_fsfreeze_hook(GAState *s)
580 {
581     return s->fsfreeze_hook;
582 }
583 #endif
584 
585 static void become_daemon(const char *pidfile)
586 {
587 #ifndef _WIN32
588     pid_t pid, sid;
589 
590     pid = fork();
591     if (pid < 0) {
592         exit(EXIT_FAILURE);
593     }
594     if (pid > 0) {
595         exit(EXIT_SUCCESS);
596     }
597 
598     if (pidfile) {
599         Error *err = NULL;
600 
601         if (!qemu_write_pidfile(pidfile, &err)) {
602             g_critical("%s", error_get_pretty(err));
603             error_free(err);
604             exit(EXIT_FAILURE);
605         }
606     }
607 
608     umask(S_IRWXG | S_IRWXO);
609     sid = setsid();
610     if (sid < 0) {
611         goto fail;
612     }
613     if ((chdir("/")) < 0) {
614         goto fail;
615     }
616 
617     reopen_fd_to_null(STDIN_FILENO);
618     reopen_fd_to_null(STDOUT_FILENO);
619     reopen_fd_to_null(STDERR_FILENO);
620     return;
621 
622 fail:
623     if (pidfile) {
624         unlink(pidfile);
625     }
626     g_critical("failed to daemonize");
627     exit(EXIT_FAILURE);
628 #endif
629 }
630 
631 static int send_response(GAState *s, const QDict *rsp)
632 {
633     GString *response;
634     GIOStatus status;
635 
636     g_assert(s->channel);
637 
638     if (!rsp) {
639         return 0;
640     }
641 
642     response = qobject_to_json(QOBJECT(rsp));
643     if (!response) {
644         return -EINVAL;
645     }
646 
647     if (s->delimit_response) {
648         s->delimit_response = false;
649         g_string_prepend_c(response, QGA_SENTINEL_BYTE);
650     }
651 
652     g_string_append_c(response, '\n');
653     status = ga_channel_write_all(s->channel, response->str, response->len);
654     g_string_free(response, true);
655     if (status != G_IO_STATUS_NORMAL) {
656         return -EIO;
657     }
658 
659     return 0;
660 }
661 
662 /* handle requests/control events coming in over the channel */
663 static void process_event(void *opaque, QObject *obj, Error *err)
664 {
665     GAState *s = opaque;
666     QDict *rsp;
667     int ret;
668 
669     g_debug("process_event: called");
670     assert(!obj != !err);
671     if (err) {
672         rsp = qmp_error_response(err);
673         goto end;
674     }
675 
676     g_debug("processing command");
677     rsp = qmp_dispatch(&ga_commands, obj, false, NULL);
678 
679 end:
680     ret = send_response(s, rsp);
681     if (ret < 0) {
682         g_warning("error sending error response: %s", strerror(-ret));
683     }
684     qobject_unref(rsp);
685     qobject_unref(obj);
686 }
687 
688 /* false return signals GAChannel to close the current client connection */
689 static gboolean channel_event_cb(GIOCondition condition, gpointer data)
690 {
691     GAState *s = data;
692     gchar buf[QGA_READ_COUNT_DEFAULT + 1];
693     gsize count;
694     GIOStatus status = ga_channel_read(s->channel, buf, QGA_READ_COUNT_DEFAULT, &count);
695     switch (status) {
696     case G_IO_STATUS_ERROR:
697         g_warning("error reading channel");
698         stop_agent(s, false);
699         return false;
700     case G_IO_STATUS_NORMAL:
701         buf[count] = 0;
702         g_debug("read data, count: %d, data: %s", (int)count, buf);
703         json_message_parser_feed(&s->parser, (char *)buf, (int)count);
704         break;
705     case G_IO_STATUS_EOF:
706         g_debug("received EOF");
707         if (!s->virtio) {
708             return false;
709         }
710         /* fall through */
711     case G_IO_STATUS_AGAIN:
712         /* virtio causes us to spin here when no process is attached to
713          * host-side chardev. sleep a bit to mitigate this
714          */
715         if (s->virtio) {
716             g_usleep(G_USEC_PER_SEC / 10);
717         }
718         return true;
719     default:
720         g_warning("unknown channel read status, closing");
721         return false;
722     }
723     return true;
724 }
725 
726 static gboolean channel_init(GAState *s, const gchar *method, const gchar *path,
727                              int listen_fd)
728 {
729     GAChannelMethod channel_method;
730 
731     if (strcmp(method, "virtio-serial") == 0) {
732         s->virtio = true; /* virtio requires special handling in some cases */
733         channel_method = GA_CHANNEL_VIRTIO_SERIAL;
734     } else if (strcmp(method, "isa-serial") == 0) {
735         channel_method = GA_CHANNEL_ISA_SERIAL;
736     } else if (strcmp(method, "unix-listen") == 0) {
737         channel_method = GA_CHANNEL_UNIX_LISTEN;
738     } else if (strcmp(method, "vsock-listen") == 0) {
739         channel_method = GA_CHANNEL_VSOCK_LISTEN;
740     } else {
741         g_critical("unsupported channel method/type: %s", method);
742         return false;
743     }
744 
745     s->channel = ga_channel_new(channel_method, path, listen_fd,
746                                 channel_event_cb, s);
747     if (!s->channel) {
748         g_critical("failed to create guest agent channel");
749         return false;
750     }
751 
752     return true;
753 }
754 
755 #ifdef _WIN32
756 DWORD WINAPI handle_serial_device_events(DWORD type, LPVOID data)
757 {
758     DWORD ret = NO_ERROR;
759     PDEV_BROADCAST_HDR broadcast_header = (PDEV_BROADCAST_HDR)data;
760 
761     if (broadcast_header->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE) {
762         switch (type) {
763             /* Device inserted */
764         case DBT_DEVICEARRIVAL:
765             /* Start QEMU-ga's service */
766             if (!SetEvent(ga_state->wakeup_event)) {
767                 ret = GetLastError();
768             }
769             break;
770             /* Device removed */
771         case DBT_DEVICEQUERYREMOVE:
772         case DBT_DEVICEREMOVEPENDING:
773         case DBT_DEVICEREMOVECOMPLETE:
774             /* Stop QEMU-ga's service */
775             if (!ResetEvent(ga_state->wakeup_event)) {
776                 ret = GetLastError();
777             }
778             break;
779         default:
780             ret = ERROR_CALL_NOT_IMPLEMENTED;
781         }
782     }
783     return ret;
784 }
785 
786 DWORD WINAPI service_ctrl_handler(DWORD ctrl, DWORD type, LPVOID data,
787                                   LPVOID ctx)
788 {
789     DWORD ret = NO_ERROR;
790     GAService *service = &ga_state->service;
791 
792     switch (ctrl) {
793     case SERVICE_CONTROL_STOP:
794     case SERVICE_CONTROL_SHUTDOWN:
795         quit_handler(SIGTERM);
796         SetEvent(ga_state->wakeup_event);
797         service->status.dwCurrentState = SERVICE_STOP_PENDING;
798         SetServiceStatus(service->status_handle, &service->status);
799         break;
800     case SERVICE_CONTROL_DEVICEEVENT:
801         handle_serial_device_events(type, data);
802         break;
803 
804     default:
805         ret = ERROR_CALL_NOT_IMPLEMENTED;
806     }
807     return ret;
808 }
809 
810 VOID WINAPI service_main(DWORD argc, TCHAR *argv[])
811 {
812     GAService *service = &ga_state->service;
813 
814     service->status_handle = RegisterServiceCtrlHandlerEx(QGA_SERVICE_NAME,
815         service_ctrl_handler, NULL);
816 
817     if (service->status_handle == 0) {
818         g_critical("Failed to register extended requests function!\n");
819         return;
820     }
821 
822     service->status.dwServiceType = SERVICE_WIN32;
823     service->status.dwCurrentState = SERVICE_RUNNING;
824     service->status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
825     service->status.dwWin32ExitCode = NO_ERROR;
826     service->status.dwServiceSpecificExitCode = NO_ERROR;
827     service->status.dwCheckPoint = 0;
828     service->status.dwWaitHint = 0;
829     DEV_BROADCAST_DEVICEINTERFACE notification_filter;
830     ZeroMemory(&notification_filter, sizeof(notification_filter));
831     notification_filter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
832     notification_filter.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE);
833     notification_filter.dbcc_classguid = GUID_VIOSERIAL_PORT;
834 
835     service->device_notification_handle =
836         RegisterDeviceNotification(service->status_handle,
837             &notification_filter, DEVICE_NOTIFY_SERVICE_HANDLE);
838     if (!service->device_notification_handle) {
839         g_critical("Failed to register device notification handle!\n");
840         return;
841     }
842     SetServiceStatus(service->status_handle, &service->status);
843 
844     run_agent(ga_state);
845 
846     UnregisterDeviceNotification(service->device_notification_handle);
847     service->status.dwCurrentState = SERVICE_STOPPED;
848     SetServiceStatus(service->status_handle, &service->status);
849 }
850 #endif
851 
852 static void set_persistent_state_defaults(GAPersistentState *pstate)
853 {
854     g_assert(pstate);
855     pstate->fd_counter = QGA_PSTATE_DEFAULT_FD_COUNTER;
856 }
857 
858 static void persistent_state_from_keyfile(GAPersistentState *pstate,
859                                           GKeyFile *keyfile)
860 {
861     g_assert(pstate);
862     g_assert(keyfile);
863     /* if any fields are missing, either because the file was tampered with
864      * by agents of chaos, or because the field wasn't present at the time the
865      * file was created, the best we can ever do is start over with the default
866      * values. so load them now, and ignore any errors in accessing key-value
867      * pairs
868      */
869     set_persistent_state_defaults(pstate);
870 
871     if (g_key_file_has_key(keyfile, "global", "fd_counter", NULL)) {
872         pstate->fd_counter =
873             g_key_file_get_integer(keyfile, "global", "fd_counter", NULL);
874     }
875 }
876 
877 static void persistent_state_to_keyfile(const GAPersistentState *pstate,
878                                         GKeyFile *keyfile)
879 {
880     g_assert(pstate);
881     g_assert(keyfile);
882 
883     g_key_file_set_integer(keyfile, "global", "fd_counter", pstate->fd_counter);
884 }
885 
886 static gboolean write_persistent_state(const GAPersistentState *pstate,
887                                        const gchar *path)
888 {
889     GKeyFile *keyfile = g_key_file_new();
890     GError *gerr = NULL;
891     gboolean ret = true;
892     gchar *data = NULL;
893     gsize data_len;
894 
895     g_assert(pstate);
896 
897     persistent_state_to_keyfile(pstate, keyfile);
898     data = g_key_file_to_data(keyfile, &data_len, &gerr);
899     if (gerr) {
900         g_critical("failed to convert persistent state to string: %s",
901                    gerr->message);
902         ret = false;
903         goto out;
904     }
905 
906     g_file_set_contents(path, data, data_len, &gerr);
907     if (gerr) {
908         g_critical("failed to write persistent state to %s: %s",
909                     path, gerr->message);
910         ret = false;
911         goto out;
912     }
913 
914 out:
915     if (gerr) {
916         g_error_free(gerr);
917     }
918     if (keyfile) {
919         g_key_file_free(keyfile);
920     }
921     g_free(data);
922     return ret;
923 }
924 
925 static gboolean read_persistent_state(GAPersistentState *pstate,
926                                       const gchar *path, gboolean frozen)
927 {
928     GKeyFile *keyfile = NULL;
929     GError *gerr = NULL;
930     struct stat st;
931     gboolean ret = true;
932 
933     g_assert(pstate);
934 
935     if (stat(path, &st) == -1) {
936         /* it's okay if state file doesn't exist, but any other error
937          * indicates a permissions issue or some other misconfiguration
938          * that we likely won't be able to recover from.
939          */
940         if (errno != ENOENT) {
941             g_critical("unable to access state file at path %s: %s",
942                        path, strerror(errno));
943             ret = false;
944             goto out;
945         }
946 
947         /* file doesn't exist. initialize state to default values and
948          * attempt to save now. (we could wait till later when we have
949          * modified state we need to commit, but if there's a problem,
950          * such as a missing parent directory, we want to catch it now)
951          *
952          * there is a potential scenario where someone either managed to
953          * update the agent from a version that didn't use a key store
954          * while qemu-ga thought the filesystem was frozen, or
955          * deleted the key store prior to issuing a fsfreeze, prior
956          * to restarting the agent. in this case we go ahead and defer
957          * initial creation till we actually have modified state to
958          * write, otherwise fail to recover from freeze.
959          */
960         set_persistent_state_defaults(pstate);
961         if (!frozen) {
962             ret = write_persistent_state(pstate, path);
963             if (!ret) {
964                 g_critical("unable to create state file at path %s", path);
965                 ret = false;
966                 goto out;
967             }
968         }
969         ret = true;
970         goto out;
971     }
972 
973     keyfile = g_key_file_new();
974     g_key_file_load_from_file(keyfile, path, 0, &gerr);
975     if (gerr) {
976         g_critical("error loading persistent state from path: %s, %s",
977                    path, gerr->message);
978         ret = false;
979         goto out;
980     }
981 
982     persistent_state_from_keyfile(pstate, keyfile);
983 
984 out:
985     if (keyfile) {
986         g_key_file_free(keyfile);
987     }
988     if (gerr) {
989         g_error_free(gerr);
990     }
991 
992     return ret;
993 }
994 
995 int64_t ga_get_fd_handle(GAState *s, Error **errp)
996 {
997     int64_t handle;
998 
999     g_assert(s->pstate_filepath);
1000     /*
1001      * We block commands and avoid operations that potentially require
1002      * writing to disk when we're in a frozen state. this includes opening
1003      * new files, so we should never get here in that situation
1004      */
1005     g_assert(!ga_is_frozen(s));
1006 
1007     handle = s->pstate.fd_counter++;
1008 
1009     /* This should never happen on a reasonable timeframe, as guest-file-open
1010      * would have to be issued 2^63 times */
1011     if (s->pstate.fd_counter == INT64_MAX) {
1012         abort();
1013     }
1014 
1015     if (!write_persistent_state(&s->pstate, s->pstate_filepath)) {
1016         error_setg(errp, "failed to commit persistent state to disk");
1017         return -1;
1018     }
1019 
1020     return handle;
1021 }
1022 
1023 static void ga_print_cmd(const QmpCommand *cmd, void *opaque)
1024 {
1025     printf("%s\n", qmp_command_name(cmd));
1026 }
1027 
1028 static GList *split_list(const gchar *str, const gchar *delim)
1029 {
1030     GList *list = NULL;
1031     int i;
1032     gchar **strv;
1033 
1034     strv = g_strsplit(str, delim, -1);
1035     for (i = 0; strv[i]; i++) {
1036         list = g_list_prepend(list, strv[i]);
1037     }
1038     g_free(strv);
1039 
1040     return list;
1041 }
1042 
1043 static void config_load(GAConfig *config, const char *confpath, bool required)
1044 {
1045     GError *gerr = NULL;
1046     GKeyFile *keyfile;
1047 
1048     /* read system config */
1049     keyfile = g_key_file_new();
1050     if (!g_key_file_load_from_file(keyfile, confpath, 0, &gerr)) {
1051         goto end;
1052     }
1053     if (g_key_file_has_key(keyfile, "general", "daemon", NULL)) {
1054         config->daemonize =
1055             g_key_file_get_boolean(keyfile, "general", "daemon", &gerr);
1056     }
1057     if (g_key_file_has_key(keyfile, "general", "method", NULL)) {
1058         config->method =
1059             g_key_file_get_string(keyfile, "general", "method", &gerr);
1060     }
1061     if (g_key_file_has_key(keyfile, "general", "path", NULL)) {
1062         config->channel_path =
1063             g_key_file_get_string(keyfile, "general", "path", &gerr);
1064     }
1065     if (g_key_file_has_key(keyfile, "general", "logfile", NULL)) {
1066         config->log_filepath =
1067             g_key_file_get_string(keyfile, "general", "logfile", &gerr);
1068     }
1069     if (g_key_file_has_key(keyfile, "general", "pidfile", NULL)) {
1070         config->pid_filepath =
1071             g_key_file_get_string(keyfile, "general", "pidfile", &gerr);
1072     }
1073 #ifdef CONFIG_FSFREEZE
1074     if (g_key_file_has_key(keyfile, "general", "fsfreeze-hook", NULL)) {
1075         config->fsfreeze_hook =
1076             g_key_file_get_string(keyfile,
1077                                   "general", "fsfreeze-hook", &gerr);
1078     }
1079 #endif
1080     if (g_key_file_has_key(keyfile, "general", "statedir", NULL)) {
1081         config->state_dir =
1082             g_key_file_get_string(keyfile, "general", "statedir", &gerr);
1083     }
1084     if (g_key_file_has_key(keyfile, "general", "verbose", NULL) &&
1085         g_key_file_get_boolean(keyfile, "general", "verbose", &gerr)) {
1086         /* enable all log levels */
1087         config->log_level = G_LOG_LEVEL_MASK;
1088     }
1089     if (g_key_file_has_key(keyfile, "general", "retry-path", NULL)) {
1090         config->retry_path =
1091             g_key_file_get_boolean(keyfile, "general", "retry-path", &gerr);
1092     }
1093 
1094     if (g_key_file_has_key(keyfile, "general", "block-rpcs", NULL)) {
1095         config->bliststr =
1096             g_key_file_get_string(keyfile, "general", "block-rpcs", &gerr);
1097         config->blockedrpcs = g_list_concat(config->blockedrpcs,
1098                                           split_list(config->bliststr, ","));
1099     }
1100     if (g_key_file_has_key(keyfile, "general", "allow-rpcs", NULL)) {
1101         config->aliststr =
1102             g_key_file_get_string(keyfile, "general", "allow-rpcs", &gerr);
1103         config->allowedrpcs = g_list_concat(config->allowedrpcs,
1104                                           split_list(config->aliststr, ","));
1105     }
1106 
1107 end:
1108     g_key_file_free(keyfile);
1109     if (gerr && (required ||
1110                  !(gerr->domain == G_FILE_ERROR && gerr->code == G_FILE_ERROR_NOENT))) {
1111         g_critical("error loading configuration from path: %s, %s",
1112                    confpath, gerr->message);
1113         exit(EXIT_FAILURE);
1114     }
1115     g_clear_error(&gerr);
1116 }
1117 
1118 static gchar *list_join(GList *list, const gchar separator)
1119 {
1120     GString *str = g_string_new("");
1121 
1122     while (list) {
1123         str = g_string_append(str, (gchar *)list->data);
1124         list = g_list_next(list);
1125         if (list) {
1126             str = g_string_append_c(str, separator);
1127         }
1128     }
1129 
1130     return g_string_free(str, FALSE);
1131 }
1132 
1133 static void config_dump(GAConfig *config)
1134 {
1135     GError *error = NULL;
1136     GKeyFile *keyfile;
1137     gchar *tmp;
1138 
1139     keyfile = g_key_file_new();
1140     g_assert(keyfile);
1141 
1142     g_key_file_set_boolean(keyfile, "general", "daemon", config->daemonize);
1143     g_key_file_set_string(keyfile, "general", "method", config->method);
1144     if (config->channel_path) {
1145         g_key_file_set_string(keyfile, "general", "path", config->channel_path);
1146     }
1147     if (config->log_filepath) {
1148         g_key_file_set_string(keyfile, "general", "logfile",
1149                               config->log_filepath);
1150     }
1151     g_key_file_set_string(keyfile, "general", "pidfile", config->pid_filepath);
1152 #ifdef CONFIG_FSFREEZE
1153     if (config->fsfreeze_hook) {
1154         g_key_file_set_string(keyfile, "general", "fsfreeze-hook",
1155                               config->fsfreeze_hook);
1156     }
1157 #endif
1158     g_key_file_set_string(keyfile, "general", "statedir", config->state_dir);
1159     g_key_file_set_boolean(keyfile, "general", "verbose",
1160                            config->log_level == G_LOG_LEVEL_MASK);
1161     g_key_file_set_boolean(keyfile, "general", "retry-path",
1162                            config->retry_path);
1163     tmp = list_join(config->blockedrpcs, ',');
1164     g_key_file_set_string(keyfile, "general", "block-rpcs", tmp);
1165     g_free(tmp);
1166     tmp = list_join(config->allowedrpcs, ',');
1167     g_key_file_set_string(keyfile, "general", "allow-rpcs", tmp);
1168     g_free(tmp);
1169 
1170     tmp = g_key_file_to_data(keyfile, NULL, &error);
1171     if (error) {
1172         g_critical("Failed to dump keyfile: %s", error->message);
1173         g_clear_error(&error);
1174     } else {
1175         printf("%s", tmp);
1176     }
1177 
1178     g_free(tmp);
1179     g_key_file_free(keyfile);
1180 }
1181 
1182 static void config_parse(GAConfig *config, int argc, char **argv)
1183 {
1184     const char *sopt = "hVvdc:m:p:l:f:F::b:a:s:t:Dr";
1185     int opt_ind = 0, ch;
1186     const struct option lopt[] = {
1187         { "help", 0, NULL, 'h' },
1188         { "version", 0, NULL, 'V' },
1189         { "config", 1, NULL, 'c' },
1190         { "dump-conf", 0, NULL, 'D' },
1191         { "logfile", 1, NULL, 'l' },
1192         { "pidfile", 1, NULL, 'f' },
1193 #ifdef CONFIG_FSFREEZE
1194         { "fsfreeze-hook", 2, NULL, 'F' },
1195 #endif
1196         { "verbose", 0, NULL, 'v' },
1197         { "method", 1, NULL, 'm' },
1198         { "path", 1, NULL, 'p' },
1199         { "daemonize", 0, NULL, 'd' },
1200         { "block-rpcs", 1, NULL, 'b' },
1201         { "allow-rpcs", 1, NULL, 'a' },
1202 #ifdef _WIN32
1203         { "service", 1, NULL, 's' },
1204 #endif
1205         { "statedir", 1, NULL, 't' },
1206         { "retry-path", 0, NULL, 'r' },
1207         { NULL, 0, NULL, 0 }
1208     };
1209     g_autofree char *confpath = g_strdup(g_getenv("QGA_CONF")) ?:
1210         get_relocated_path(QGA_CONF_DEFAULT);
1211     bool confrequired = false;
1212 
1213     while ((ch = getopt_long(argc, argv, sopt, lopt, NULL)) != -1) {
1214         switch (ch) {
1215         case 'c':
1216             g_free(confpath);
1217             confpath = g_strdup(optarg);
1218             confrequired = true;
1219             break;
1220         default:
1221             break;
1222         }
1223     }
1224 
1225     config_load(config, confpath, confrequired);
1226 
1227     /* Reset for second pass */
1228     optind = 1;
1229 
1230     while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
1231         switch (ch) {
1232         case 'm':
1233             g_free(config->method);
1234             config->method = g_strdup(optarg);
1235             break;
1236         case 'p':
1237             g_free(config->channel_path);
1238             config->channel_path = g_strdup(optarg);
1239             break;
1240         case 'l':
1241             g_free(config->log_filepath);
1242             config->log_filepath = g_strdup(optarg);
1243             break;
1244         case 'f':
1245             g_free(config->pid_filepath);
1246             config->pid_filepath = g_strdup(optarg);
1247             break;
1248 #ifdef CONFIG_FSFREEZE
1249         case 'F':
1250             g_free(config->fsfreeze_hook);
1251             config->fsfreeze_hook = optarg ? g_strdup(optarg) : get_relocated_path(QGA_FSFREEZE_HOOK_DEFAULT);
1252             break;
1253 #endif
1254         case 't':
1255             g_free(config->state_dir);
1256             config->state_dir = g_strdup(optarg);
1257             break;
1258         case 'v':
1259             /* enable all log levels */
1260             config->log_level = G_LOG_LEVEL_MASK;
1261             break;
1262         case 'V':
1263             printf("QEMU Guest Agent %s\n", QEMU_VERSION);
1264             exit(EXIT_SUCCESS);
1265         case 'd':
1266             config->daemonize = 1;
1267             break;
1268         case 'D':
1269             config->dumpconf = 1;
1270             break;
1271         case 'r':
1272             config->retry_path = true;
1273             break;
1274         case 'b': {
1275             if (is_help_option(optarg)) {
1276                 qmp_for_each_command(&ga_commands, ga_print_cmd, NULL);
1277                 exit(EXIT_SUCCESS);
1278             }
1279             config->blockedrpcs = g_list_concat(config->blockedrpcs,
1280                                                 split_list(optarg, ","));
1281             break;
1282         }
1283         case 'a': {
1284             if (is_help_option(optarg)) {
1285                 qmp_for_each_command(&ga_commands, ga_print_cmd, NULL);
1286                 exit(EXIT_SUCCESS);
1287             }
1288             config->allowedrpcs = g_list_concat(config->allowedrpcs,
1289                                                 split_list(optarg, ","));
1290             break;
1291         }
1292 #ifdef _WIN32
1293         case 's':
1294             config->service = optarg;
1295             if (strcmp(config->service, "install") == 0) {
1296                 if (ga_install_vss_provider()) {
1297                     exit(EXIT_FAILURE);
1298                 }
1299                 if (ga_install_service(config->channel_path,
1300                                        config->log_filepath, config->state_dir)) {
1301                     exit(EXIT_FAILURE);
1302                 }
1303                 exit(EXIT_SUCCESS);
1304             } else if (strcmp(config->service, "uninstall") == 0) {
1305                 ga_uninstall_vss_provider();
1306                 exit(ga_uninstall_service());
1307             } else if (strcmp(config->service, "vss-install") == 0) {
1308                 if (ga_install_vss_provider()) {
1309                     exit(EXIT_FAILURE);
1310                 }
1311                 exit(EXIT_SUCCESS);
1312             } else if (strcmp(config->service, "vss-uninstall") == 0) {
1313                 ga_uninstall_vss_provider();
1314                 exit(EXIT_SUCCESS);
1315             } else {
1316                 printf("Unknown service command.\n");
1317                 exit(EXIT_FAILURE);
1318             }
1319             break;
1320 #endif
1321         case 'h':
1322             usage(argv[0]);
1323             exit(EXIT_SUCCESS);
1324         case '?':
1325             g_print("Unknown option, try '%s --help' for more information.\n",
1326                     argv[0]);
1327             exit(EXIT_FAILURE);
1328         }
1329     }
1330 }
1331 
1332 static void config_free(GAConfig *config)
1333 {
1334     g_free(config->method);
1335     g_free(config->log_filepath);
1336     g_free(config->pid_filepath);
1337     g_free(config->state_dir);
1338     g_free(config->channel_path);
1339     g_free(config->bliststr);
1340     g_free(config->aliststr);
1341 #ifdef CONFIG_FSFREEZE
1342     g_free(config->fsfreeze_hook);
1343 #endif
1344     g_list_free_full(config->blockedrpcs, g_free);
1345     g_list_free_full(config->allowedrpcs, g_free);
1346     g_free(config);
1347 }
1348 
1349 static bool check_is_frozen(GAState *s)
1350 {
1351 #ifndef _WIN32
1352     /* check if a previous instance of qemu-ga exited with filesystems' state
1353      * marked as frozen. this could be a stale value (a non-qemu-ga process
1354      * or reboot may have since unfrozen them), but better to require an
1355      * unneeded unfreeze than to risk hanging on start-up
1356      */
1357     struct stat st;
1358     if (stat(s->state_filepath_isfrozen, &st) == -1) {
1359         /* it's okay if the file doesn't exist, but if we can't access for
1360          * some other reason, such as permissions, there's a configuration
1361          * that needs to be addressed. so just bail now before we get into
1362          * more trouble later
1363          */
1364         if (errno != ENOENT) {
1365             g_critical("unable to access state file at path %s: %s",
1366                        s->state_filepath_isfrozen, strerror(errno));
1367             return EXIT_FAILURE;
1368         }
1369     } else {
1370         g_warning("previous instance appears to have exited with frozen"
1371                   " filesystems. deferring logging/pidfile creation and"
1372                   " disabling non-fsfreeze-safe commands until"
1373                   " guest-fsfreeze-thaw is issued, or filesystems are"
1374                   " manually unfrozen and the file %s is removed",
1375                   s->state_filepath_isfrozen);
1376         return true;
1377     }
1378 #endif
1379     return false;
1380 }
1381 
1382 static GAState *initialize_agent(GAConfig *config, int socket_activation)
1383 {
1384     GAState *s = g_new0(GAState, 1);
1385 
1386     g_assert(ga_state == NULL);
1387 
1388     s->log_level = config->log_level;
1389     s->log_file = stderr;
1390 #ifdef CONFIG_FSFREEZE
1391     s->fsfreeze_hook = config->fsfreeze_hook;
1392 #endif
1393     s->pstate_filepath = g_strdup_printf("%s/qga.state", config->state_dir);
1394     s->state_filepath_isfrozen = g_strdup_printf("%s/qga.state.isfrozen",
1395                                                  config->state_dir);
1396     s->frozen = check_is_frozen(s);
1397 
1398     g_log_set_default_handler(ga_log, s);
1399     g_log_set_fatal_mask(NULL, G_LOG_LEVEL_ERROR);
1400     ga_enable_logging(s);
1401 
1402     g_debug("Guest agent version %s started", QEMU_FULL_VERSION);
1403 
1404 #ifdef _WIN32
1405     s->event_log = RegisterEventSource(NULL, "qemu-ga");
1406     if (!s->event_log) {
1407         g_autofree gchar *errmsg = g_win32_error_message(GetLastError());
1408         g_critical("unable to register event source: %s", errmsg);
1409         return NULL;
1410     }
1411 
1412     /* On win32 the state directory is application specific (be it the default
1413      * or a user override). We got past the command line parsing; let's create
1414      * the directory (with any intermediate directories). If we run into an
1415      * error later on, we won't try to clean up the directory, it is considered
1416      * persistent.
1417      */
1418     if (g_mkdir_with_parents(config->state_dir, S_IRWXU) == -1) {
1419         g_critical("unable to create (an ancestor of) the state directory"
1420                    " '%s': %s", config->state_dir, strerror(errno));
1421         return NULL;
1422     }
1423 
1424     if (!vss_init(true)) {
1425         g_debug("vss_init failed, vss commands will not function");
1426     }
1427 #endif
1428 
1429     if (ga_is_frozen(s)) {
1430         if (config->daemonize) {
1431             /* delay opening/locking of pidfile till filesystems are unfrozen */
1432             s->deferred_options.pid_filepath = config->pid_filepath;
1433             become_daemon(NULL);
1434         }
1435         if (config->log_filepath) {
1436             /* delay opening the log file till filesystems are unfrozen */
1437             s->deferred_options.log_filepath = config->log_filepath;
1438         }
1439         ga_disable_logging(s);
1440     } else {
1441         if (config->daemonize) {
1442             become_daemon(config->pid_filepath);
1443         }
1444         if (config->log_filepath) {
1445             FILE *log_file = ga_open_logfile(config->log_filepath);
1446             if (!log_file) {
1447                 g_critical("unable to open specified log file: %s",
1448                            strerror(errno));
1449                 return NULL;
1450             }
1451             s->log_file = log_file;
1452         }
1453     }
1454 
1455     /* load persistent state from disk */
1456     if (!read_persistent_state(&s->pstate,
1457                                s->pstate_filepath,
1458                                ga_is_frozen(s))) {
1459         g_critical("failed to load persistent state");
1460         return NULL;
1461     }
1462 
1463     s->command_state = ga_command_state_new();
1464     ga_command_state_init(s, s->command_state);
1465     ga_command_state_init_all(s->command_state);
1466     json_message_parser_init(&s->parser, process_event, s, NULL);
1467 
1468 #ifndef _WIN32
1469     if (!register_signal_handlers()) {
1470         g_critical("failed to register signal handlers");
1471         return NULL;
1472     }
1473 #endif
1474 
1475     s->main_loop = g_main_loop_new(NULL, false);
1476 
1477     s->config = config;
1478     s->socket_activation = socket_activation;
1479 
1480 #ifdef _WIN32
1481     s->wakeup_event = CreateEvent(NULL, TRUE, FALSE, TEXT("WakeUp"));
1482     if (s->wakeup_event == NULL) {
1483         g_critical("CreateEvent failed");
1484         return NULL;
1485     }
1486 #endif
1487 
1488     ga_apply_command_filters(s);
1489 
1490     ga_state = s;
1491     return s;
1492 }
1493 
1494 static void cleanup_agent(GAState *s)
1495 {
1496 #ifdef _WIN32
1497     CloseHandle(s->wakeup_event);
1498     CloseHandle(s->event_log);
1499 #endif
1500     if (s->command_state) {
1501         ga_command_state_cleanup_all(s->command_state);
1502         ga_command_state_free(s->command_state);
1503         json_message_parser_destroy(&s->parser);
1504     }
1505     g_free(s->pstate_filepath);
1506     g_free(s->state_filepath_isfrozen);
1507     if (s->main_loop) {
1508         g_main_loop_unref(s->main_loop);
1509     }
1510     g_free(s);
1511     ga_state = NULL;
1512 }
1513 
1514 static int run_agent_once(GAState *s)
1515 {
1516     if (!channel_init(s, s->config->method, s->config->channel_path,
1517                       s->socket_activation ? FIRST_SOCKET_ACTIVATION_FD : -1)) {
1518         g_critical("failed to initialize guest agent channel");
1519         return EXIT_FAILURE;
1520     }
1521 
1522     g_main_loop_run(ga_state->main_loop);
1523 
1524     if (s->channel) {
1525         ga_channel_free(s->channel);
1526     }
1527 
1528     return EXIT_SUCCESS;
1529 }
1530 
1531 static void wait_for_channel_availability(GAState *s)
1532 {
1533     g_warning("waiting for channel path...");
1534 #ifndef _WIN32
1535     sleep(QGA_RETRY_INTERVAL);
1536 #else
1537     DWORD dwWaitResult;
1538 
1539     dwWaitResult = WaitForSingleObject(s->wakeup_event, INFINITE);
1540 
1541     switch (dwWaitResult) {
1542     case WAIT_OBJECT_0:
1543         break;
1544     case WAIT_TIMEOUT:
1545         break;
1546     default:
1547         g_critical("WaitForSingleObject failed");
1548     }
1549 #endif
1550 }
1551 
1552 static int run_agent(GAState *s)
1553 {
1554     int ret = EXIT_SUCCESS;
1555 
1556     s->force_exit = false;
1557 
1558     do {
1559         ret = run_agent_once(s);
1560         if (s->config->retry_path && !s->force_exit) {
1561             g_warning("agent stopped unexpectedly, restarting...");
1562             wait_for_channel_availability(s);
1563         }
1564     } while (s->config->retry_path && !s->force_exit);
1565 
1566     return ret;
1567 }
1568 
1569 static void stop_agent(GAState *s, bool requested)
1570 {
1571     if (!s->force_exit) {
1572         s->force_exit = requested;
1573     }
1574 
1575     if (g_main_loop_is_running(s->main_loop)) {
1576         g_main_loop_quit(s->main_loop);
1577     }
1578 }
1579 
1580 int main(int argc, char **argv)
1581 {
1582     int ret = EXIT_SUCCESS;
1583     GAState *s;
1584     GAConfig *config = g_new0(GAConfig, 1);
1585     int socket_activation;
1586 
1587     config->log_level = G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL;
1588 
1589     qemu_init_exec_dir(argv[0]);
1590     qga_qmp_init_marshal(&ga_commands);
1591 
1592     init_dfl_pathnames();
1593     config_parse(config, argc, argv);
1594 
1595     if (config->pid_filepath == NULL) {
1596         config->pid_filepath = g_strdup(dfl_pathnames.pidfile);
1597     }
1598 
1599     if (config->state_dir == NULL) {
1600         config->state_dir = g_strdup(dfl_pathnames.state_dir);
1601     }
1602 
1603     if (config->method == NULL) {
1604         config->method = g_strdup("virtio-serial");
1605     }
1606 
1607     socket_activation = check_socket_activation();
1608     if (socket_activation > 1) {
1609         g_critical("qemu-ga only supports listening on one socket");
1610         ret = EXIT_FAILURE;
1611         goto end;
1612     }
1613     if (socket_activation) {
1614         SocketAddress *addr;
1615 
1616         g_free(config->method);
1617         g_free(config->channel_path);
1618         config->method = NULL;
1619         config->channel_path = NULL;
1620 
1621         addr = socket_local_address(FIRST_SOCKET_ACTIVATION_FD, NULL);
1622         if (addr) {
1623             if (addr->type == SOCKET_ADDRESS_TYPE_UNIX) {
1624                 config->method = g_strdup("unix-listen");
1625             } else if (addr->type == SOCKET_ADDRESS_TYPE_VSOCK) {
1626                 config->method = g_strdup("vsock-listen");
1627             }
1628 
1629             qapi_free_SocketAddress(addr);
1630         }
1631 
1632         if (!config->method) {
1633             g_critical("unsupported listen fd type");
1634             ret = EXIT_FAILURE;
1635             goto end;
1636         }
1637     } else if (config->channel_path == NULL) {
1638         if (strcmp(config->method, "virtio-serial") == 0) {
1639             /* try the default path for the virtio-serial port */
1640             config->channel_path = g_strdup(QGA_VIRTIO_PATH_DEFAULT);
1641         } else if (strcmp(config->method, "isa-serial") == 0) {
1642             /* try the default path for the serial port - COM1 */
1643             config->channel_path = g_strdup(QGA_SERIAL_PATH_DEFAULT);
1644         } else {
1645             g_critical("must specify a path for this channel");
1646             ret = EXIT_FAILURE;
1647             goto end;
1648         }
1649     }
1650 
1651     if (config->dumpconf) {
1652         config_dump(config);
1653         goto end;
1654     }
1655 
1656     s = initialize_agent(config, socket_activation);
1657     if (!s) {
1658         g_critical("error initializing guest agent");
1659         goto end;
1660     }
1661 
1662 #ifdef _WIN32
1663     if (config->daemonize) {
1664         SERVICE_TABLE_ENTRY service_table[] = {
1665             { (char *)QGA_SERVICE_NAME, service_main }, { NULL, NULL } };
1666         StartServiceCtrlDispatcher(service_table);
1667     } else {
1668         ret = run_agent(s);
1669     }
1670 #else
1671     ret = run_agent(s);
1672 #endif
1673 
1674     cleanup_agent(s);
1675 
1676 end:
1677     if (config->daemonize) {
1678         unlink(config->pid_filepath);
1679     }
1680 
1681     config_free(config);
1682 
1683     return ret;
1684 }
1685