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