xref: /openbmc/qemu/qga/main.c (revision acb0ef58)
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 #include <stdlib.h>
14 #include <stdio.h>
15 #include <stdbool.h>
16 #include <glib.h>
17 #include <getopt.h>
18 #include <glib/gstdio.h>
19 #ifndef _WIN32
20 #include <syslog.h>
21 #include <sys/wait.h>
22 #include <sys/stat.h>
23 #endif
24 #include "qapi/qmp/json-streamer.h"
25 #include "qapi/qmp/json-parser.h"
26 #include "qapi/qmp/qint.h"
27 #include "qapi/qmp/qjson.h"
28 #include "qga/guest-agent-core.h"
29 #include "qemu/module.h"
30 #include "signal.h"
31 #include "qapi/qmp/qerror.h"
32 #include "qapi/qmp/dispatch.h"
33 #include "qga/channel.h"
34 #include "qemu/bswap.h"
35 #ifdef _WIN32
36 #include "qga/service-win32.h"
37 #include "qga/vss-win32.h"
38 #endif
39 #ifdef __linux__
40 #include <linux/fs.h>
41 #ifdef FIFREEZE
42 #define CONFIG_FSFREEZE
43 #endif
44 #endif
45 
46 #ifndef _WIN32
47 #define QGA_VIRTIO_PATH_DEFAULT "/dev/virtio-ports/org.qemu.guest_agent.0"
48 #define QGA_STATE_RELATIVE_DIR  "run"
49 #define QGA_SERIAL_PATH_DEFAULT "/dev/ttyS0"
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 
60 static struct {
61     const char *state_dir;
62     const char *pidfile;
63 } dfl_pathnames;
64 
65 typedef struct GAPersistentState {
66 #define QGA_PSTATE_DEFAULT_FD_COUNTER 1000
67     int64_t fd_counter;
68 } GAPersistentState;
69 
70 struct GAState {
71     JSONMessageParser parser;
72     GMainLoop *main_loop;
73     GAChannel *channel;
74     bool virtio; /* fastpath to check for virtio to deal with poll() quirks */
75     GACommandState *command_state;
76     GLogLevelFlags log_level;
77     FILE *log_file;
78     bool logging_enabled;
79 #ifdef _WIN32
80     GAService service;
81 #endif
82     bool delimit_response;
83     bool frozen;
84     GList *blacklist;
85     const char *state_filepath_isfrozen;
86     struct {
87         const char *log_filepath;
88         const char *pid_filepath;
89     } deferred_options;
90 #ifdef CONFIG_FSFREEZE
91     const char *fsfreeze_hook;
92 #endif
93     const gchar *pstate_filepath;
94     GAPersistentState pstate;
95 };
96 
97 struct GAState *ga_state;
98 
99 /* commands that are safe to issue while filesystems are frozen */
100 static const char *ga_freeze_whitelist[] = {
101     "guest-ping",
102     "guest-info",
103     "guest-sync",
104     "guest-sync-delimited",
105     "guest-fsfreeze-status",
106     "guest-fsfreeze-thaw",
107     NULL
108 };
109 
110 #ifdef _WIN32
111 DWORD WINAPI service_ctrl_handler(DWORD ctrl, DWORD type, LPVOID data,
112                                   LPVOID ctx);
113 VOID WINAPI service_main(DWORD argc, TCHAR *argv[]);
114 #endif
115 
116 static void
117 init_dfl_pathnames(void)
118 {
119     g_assert(dfl_pathnames.state_dir == NULL);
120     g_assert(dfl_pathnames.pidfile == NULL);
121     dfl_pathnames.state_dir = qemu_get_local_state_pathname(
122       QGA_STATE_RELATIVE_DIR);
123     dfl_pathnames.pidfile   = qemu_get_local_state_pathname(
124       QGA_STATE_RELATIVE_DIR G_DIR_SEPARATOR_S "qemu-ga.pid");
125 }
126 
127 static void quit_handler(int sig)
128 {
129     /* if we're frozen, don't exit unless we're absolutely forced to,
130      * because it's basically impossible for graceful exit to complete
131      * unless all log/pid files are on unfreezable filesystems. there's
132      * also a very likely chance killing the agent before unfreezing
133      * the filesystems is a mistake (or will be viewed as one later).
134      */
135     if (ga_is_frozen(ga_state)) {
136         return;
137     }
138     g_debug("received signal num %d, quitting", sig);
139 
140     if (g_main_loop_is_running(ga_state->main_loop)) {
141         g_main_loop_quit(ga_state->main_loop);
142     }
143 }
144 
145 #ifndef _WIN32
146 static gboolean register_signal_handlers(void)
147 {
148     struct sigaction sigact;
149     int ret;
150 
151     memset(&sigact, 0, sizeof(struct sigaction));
152     sigact.sa_handler = quit_handler;
153 
154     ret = sigaction(SIGINT, &sigact, NULL);
155     if (ret == -1) {
156         g_error("error configuring signal handler: %s", strerror(errno));
157     }
158     ret = sigaction(SIGTERM, &sigact, NULL);
159     if (ret == -1) {
160         g_error("error configuring signal handler: %s", strerror(errno));
161     }
162 
163     return true;
164 }
165 
166 /* TODO: use this in place of all post-fork() fclose(std*) callers */
167 void reopen_fd_to_null(int fd)
168 {
169     int nullfd;
170 
171     nullfd = open("/dev/null", O_RDWR);
172     if (nullfd < 0) {
173         return;
174     }
175 
176     dup2(nullfd, fd);
177 
178     if (nullfd != fd) {
179         close(nullfd);
180     }
181 }
182 #endif
183 
184 static void usage(const char *cmd)
185 {
186     printf(
187 "Usage: %s [-m <method> -p <path>] [<options>]\n"
188 "QEMU Guest Agent %s\n"
189 "\n"
190 "  -m, --method      transport method: one of unix-listen, virtio-serial, or\n"
191 "                    isa-serial (virtio-serial is the default)\n"
192 "  -p, --path        device/socket path (the default for virtio-serial is:\n"
193 "                    %s,\n"
194 "                    the default for isa-serial is:\n"
195 "                    %s)\n"
196 "  -l, --logfile     set logfile path, logs to stderr by default\n"
197 "  -f, --pidfile     specify pidfile (default is %s)\n"
198 #ifdef CONFIG_FSFREEZE
199 "  -F, --fsfreeze-hook\n"
200 "                    enable fsfreeze hook. Accepts an optional argument that\n"
201 "                    specifies script to run on freeze/thaw. Script will be\n"
202 "                    called with 'freeze'/'thaw' arguments accordingly.\n"
203 "                    (default is %s)\n"
204 "                    If using -F with an argument, do not follow -F with a\n"
205 "                    space.\n"
206 "                    (for example: -F/var/run/fsfreezehook.sh)\n"
207 #endif
208 "  -t, --statedir    specify dir to store state information (absolute paths\n"
209 "                    only, default is %s)\n"
210 "  -v, --verbose     log extra debugging information\n"
211 "  -V, --version     print version information and exit\n"
212 "  -d, --daemonize   become a daemon\n"
213 #ifdef _WIN32
214 "  -s, --service     service commands: install, uninstall\n"
215 #endif
216 "  -b, --blacklist   comma-separated list of RPCs to disable (no spaces, \"?\"\n"
217 "                    to list available RPCs)\n"
218 "  -h, --help        display this help and exit\n"
219 "\n"
220 "Report bugs to <mdroth@linux.vnet.ibm.com>\n"
221     , cmd, QEMU_VERSION, QGA_VIRTIO_PATH_DEFAULT, QGA_SERIAL_PATH_DEFAULT,
222     dfl_pathnames.pidfile,
223 #ifdef CONFIG_FSFREEZE
224     QGA_FSFREEZE_HOOK_DEFAULT,
225 #endif
226     dfl_pathnames.state_dir);
227 }
228 
229 static const char *ga_log_level_str(GLogLevelFlags level)
230 {
231     switch (level & G_LOG_LEVEL_MASK) {
232         case G_LOG_LEVEL_ERROR:
233             return "error";
234         case G_LOG_LEVEL_CRITICAL:
235             return "critical";
236         case G_LOG_LEVEL_WARNING:
237             return "warning";
238         case G_LOG_LEVEL_MESSAGE:
239             return "message";
240         case G_LOG_LEVEL_INFO:
241             return "info";
242         case G_LOG_LEVEL_DEBUG:
243             return "debug";
244         default:
245             return "user";
246     }
247 }
248 
249 bool ga_logging_enabled(GAState *s)
250 {
251     return s->logging_enabled;
252 }
253 
254 void ga_disable_logging(GAState *s)
255 {
256     s->logging_enabled = false;
257 }
258 
259 void ga_enable_logging(GAState *s)
260 {
261     s->logging_enabled = true;
262 }
263 
264 static void ga_log(const gchar *domain, GLogLevelFlags level,
265                    const gchar *msg, gpointer opaque)
266 {
267     GAState *s = opaque;
268     GTimeVal time;
269     const char *level_str = ga_log_level_str(level);
270 
271     if (!ga_logging_enabled(s)) {
272         return;
273     }
274 
275     level &= G_LOG_LEVEL_MASK;
276 #ifndef _WIN32
277     if (domain && strcmp(domain, "syslog") == 0) {
278         syslog(LOG_INFO, "%s: %s", level_str, msg);
279     } else if (level & s->log_level) {
280 #else
281     if (level & s->log_level) {
282 #endif
283         g_get_current_time(&time);
284         fprintf(s->log_file,
285                 "%lu.%lu: %s: %s\n", time.tv_sec, time.tv_usec, level_str, msg);
286         fflush(s->log_file);
287     }
288 }
289 
290 void ga_set_response_delimited(GAState *s)
291 {
292     s->delimit_response = true;
293 }
294 
295 static FILE *ga_open_logfile(const char *logfile)
296 {
297     FILE *f;
298 
299     f = fopen(logfile, "a");
300     if (!f) {
301         return NULL;
302     }
303 
304     qemu_set_cloexec(fileno(f));
305     return f;
306 }
307 
308 #ifndef _WIN32
309 static bool ga_open_pidfile(const char *pidfile)
310 {
311     int pidfd;
312     char pidstr[32];
313 
314     pidfd = qemu_open(pidfile, O_CREAT|O_WRONLY, S_IRUSR|S_IWUSR);
315     if (pidfd == -1 || lockf(pidfd, F_TLOCK, 0)) {
316         g_critical("Cannot lock pid file, %s", strerror(errno));
317         if (pidfd != -1) {
318             close(pidfd);
319         }
320         return false;
321     }
322 
323     if (ftruncate(pidfd, 0)) {
324         g_critical("Failed to truncate pid file");
325         goto fail;
326     }
327     snprintf(pidstr, sizeof(pidstr), "%d\n", getpid());
328     if (write(pidfd, pidstr, strlen(pidstr)) != strlen(pidstr)) {
329         g_critical("Failed to write pid file");
330         goto fail;
331     }
332 
333     /* keep pidfile open & locked forever */
334     return true;
335 
336 fail:
337     unlink(pidfile);
338     close(pidfd);
339     return false;
340 }
341 #else /* _WIN32 */
342 static bool ga_open_pidfile(const char *pidfile)
343 {
344     return true;
345 }
346 #endif
347 
348 static gint ga_strcmp(gconstpointer str1, gconstpointer str2)
349 {
350     return strcmp(str1, str2);
351 }
352 
353 /* disable commands that aren't safe for fsfreeze */
354 static void ga_disable_non_whitelisted(QmpCommand *cmd, void *opaque)
355 {
356     bool whitelisted = false;
357     int i = 0;
358     const char *name = qmp_command_name(cmd);
359 
360     while (ga_freeze_whitelist[i] != NULL) {
361         if (strcmp(name, ga_freeze_whitelist[i]) == 0) {
362             whitelisted = true;
363         }
364         i++;
365     }
366     if (!whitelisted) {
367         g_debug("disabling command: %s", name);
368         qmp_disable_command(name);
369     }
370 }
371 
372 /* [re-]enable all commands, except those explicitly blacklisted by user */
373 static void ga_enable_non_blacklisted(QmpCommand *cmd, void *opaque)
374 {
375     GList *blacklist = opaque;
376     const char *name = qmp_command_name(cmd);
377 
378     if (g_list_find_custom(blacklist, name, ga_strcmp) == NULL &&
379         !qmp_command_is_enabled(cmd)) {
380         g_debug("enabling command: %s", name);
381         qmp_enable_command(name);
382     }
383 }
384 
385 static bool ga_create_file(const char *path)
386 {
387     int fd = open(path, O_CREAT | O_WRONLY, S_IWUSR | S_IRUSR);
388     if (fd == -1) {
389         g_warning("unable to open/create file %s: %s", path, strerror(errno));
390         return false;
391     }
392     close(fd);
393     return true;
394 }
395 
396 static bool ga_delete_file(const char *path)
397 {
398     int ret = unlink(path);
399     if (ret == -1) {
400         g_warning("unable to delete file: %s: %s", path, strerror(errno));
401         return false;
402     }
403 
404     return true;
405 }
406 
407 bool ga_is_frozen(GAState *s)
408 {
409     return s->frozen;
410 }
411 
412 void ga_set_frozen(GAState *s)
413 {
414     if (ga_is_frozen(s)) {
415         return;
416     }
417     /* disable all non-whitelisted (for frozen state) commands */
418     qmp_for_each_command(ga_disable_non_whitelisted, NULL);
419     g_warning("disabling logging due to filesystem freeze");
420     ga_disable_logging(s);
421     s->frozen = true;
422     if (!ga_create_file(s->state_filepath_isfrozen)) {
423         g_warning("unable to create %s, fsfreeze may not function properly",
424                   s->state_filepath_isfrozen);
425     }
426 }
427 
428 void ga_unset_frozen(GAState *s)
429 {
430     if (!ga_is_frozen(s)) {
431         return;
432     }
433 
434     /* if we delayed creation/opening of pid/log files due to being
435      * in a frozen state at start up, do it now
436      */
437     if (s->deferred_options.log_filepath) {
438         s->log_file = ga_open_logfile(s->deferred_options.log_filepath);
439         if (!s->log_file) {
440             s->log_file = stderr;
441         }
442         s->deferred_options.log_filepath = NULL;
443     }
444     ga_enable_logging(s);
445     g_warning("logging re-enabled due to filesystem unfreeze");
446     if (s->deferred_options.pid_filepath) {
447         if (!ga_open_pidfile(s->deferred_options.pid_filepath)) {
448             g_warning("failed to create/open pid file");
449         }
450         s->deferred_options.pid_filepath = NULL;
451     }
452 
453     /* enable all disabled, non-blacklisted commands */
454     qmp_for_each_command(ga_enable_non_blacklisted, s->blacklist);
455     s->frozen = false;
456     if (!ga_delete_file(s->state_filepath_isfrozen)) {
457         g_warning("unable to delete %s, fsfreeze may not function properly",
458                   s->state_filepath_isfrozen);
459     }
460 }
461 
462 #ifdef CONFIG_FSFREEZE
463 const char *ga_fsfreeze_hook(GAState *s)
464 {
465     return s->fsfreeze_hook;
466 }
467 #endif
468 
469 static void become_daemon(const char *pidfile)
470 {
471 #ifndef _WIN32
472     pid_t pid, sid;
473 
474     pid = fork();
475     if (pid < 0) {
476         exit(EXIT_FAILURE);
477     }
478     if (pid > 0) {
479         exit(EXIT_SUCCESS);
480     }
481 
482     if (pidfile) {
483         if (!ga_open_pidfile(pidfile)) {
484             g_critical("failed to create pidfile");
485             exit(EXIT_FAILURE);
486         }
487     }
488 
489     umask(S_IRWXG | S_IRWXO);
490     sid = setsid();
491     if (sid < 0) {
492         goto fail;
493     }
494     if ((chdir("/")) < 0) {
495         goto fail;
496     }
497 
498     reopen_fd_to_null(STDIN_FILENO);
499     reopen_fd_to_null(STDOUT_FILENO);
500     reopen_fd_to_null(STDERR_FILENO);
501     return;
502 
503 fail:
504     if (pidfile) {
505         unlink(pidfile);
506     }
507     g_critical("failed to daemonize");
508     exit(EXIT_FAILURE);
509 #endif
510 }
511 
512 static int send_response(GAState *s, QObject *payload)
513 {
514     const char *buf;
515     QString *payload_qstr, *response_qstr;
516     GIOStatus status;
517 
518     g_assert(payload && s->channel);
519 
520     payload_qstr = qobject_to_json(payload);
521     if (!payload_qstr) {
522         return -EINVAL;
523     }
524 
525     if (s->delimit_response) {
526         s->delimit_response = false;
527         response_qstr = qstring_new();
528         qstring_append_chr(response_qstr, QGA_SENTINEL_BYTE);
529         qstring_append(response_qstr, qstring_get_str(payload_qstr));
530         QDECREF(payload_qstr);
531     } else {
532         response_qstr = payload_qstr;
533     }
534 
535     qstring_append_chr(response_qstr, '\n');
536     buf = qstring_get_str(response_qstr);
537     status = ga_channel_write_all(s->channel, buf, strlen(buf));
538     QDECREF(response_qstr);
539     if (status != G_IO_STATUS_NORMAL) {
540         return -EIO;
541     }
542 
543     return 0;
544 }
545 
546 static void process_command(GAState *s, QDict *req)
547 {
548     QObject *rsp = NULL;
549     int ret;
550 
551     g_assert(req);
552     g_debug("processing command");
553     rsp = qmp_dispatch(QOBJECT(req));
554     if (rsp) {
555         ret = send_response(s, rsp);
556         if (ret) {
557             g_warning("error sending response: %s", strerror(ret));
558         }
559         qobject_decref(rsp);
560     }
561 }
562 
563 /* handle requests/control events coming in over the channel */
564 static void process_event(JSONMessageParser *parser, QList *tokens)
565 {
566     GAState *s = container_of(parser, GAState, parser);
567     QObject *obj;
568     QDict *qdict;
569     Error *err = NULL;
570     int ret;
571 
572     g_assert(s && parser);
573 
574     g_debug("process_event: called");
575     obj = json_parser_parse_err(tokens, NULL, &err);
576     if (err || !obj || qobject_type(obj) != QTYPE_QDICT) {
577         qobject_decref(obj);
578         qdict = qdict_new();
579         if (!err) {
580             g_warning("failed to parse event: unknown error");
581             error_set(&err, QERR_JSON_PARSING);
582         } else {
583             g_warning("failed to parse event: %s", error_get_pretty(err));
584         }
585         qdict_put_obj(qdict, "error", qmp_build_error_object(err));
586         error_free(err);
587     } else {
588         qdict = qobject_to_qdict(obj);
589     }
590 
591     g_assert(qdict);
592 
593     /* handle host->guest commands */
594     if (qdict_haskey(qdict, "execute")) {
595         process_command(s, qdict);
596     } else {
597         if (!qdict_haskey(qdict, "error")) {
598             QDECREF(qdict);
599             qdict = qdict_new();
600             g_warning("unrecognized payload format");
601             error_set(&err, QERR_UNSUPPORTED);
602             qdict_put_obj(qdict, "error", qmp_build_error_object(err));
603             error_free(err);
604         }
605         ret = send_response(s, QOBJECT(qdict));
606         if (ret) {
607             g_warning("error sending error response: %s", strerror(ret));
608         }
609     }
610 
611     QDECREF(qdict);
612 }
613 
614 /* false return signals GAChannel to close the current client connection */
615 static gboolean channel_event_cb(GIOCondition condition, gpointer data)
616 {
617     GAState *s = data;
618     gchar buf[QGA_READ_COUNT_DEFAULT+1];
619     gsize count;
620     GError *err = NULL;
621     GIOStatus status = ga_channel_read(s->channel, buf, QGA_READ_COUNT_DEFAULT, &count);
622     if (err != NULL) {
623         g_warning("error reading channel: %s", err->message);
624         g_error_free(err);
625         return false;
626     }
627     switch (status) {
628     case G_IO_STATUS_ERROR:
629         g_warning("error reading channel");
630         return false;
631     case G_IO_STATUS_NORMAL:
632         buf[count] = 0;
633         g_debug("read data, count: %d, data: %s", (int)count, buf);
634         json_message_parser_feed(&s->parser, (char *)buf, (int)count);
635         break;
636     case G_IO_STATUS_EOF:
637         g_debug("received EOF");
638         if (!s->virtio) {
639             return false;
640         }
641         /* fall through */
642     case G_IO_STATUS_AGAIN:
643         /* virtio causes us to spin here when no process is attached to
644          * host-side chardev. sleep a bit to mitigate this
645          */
646         if (s->virtio) {
647             usleep(100*1000);
648         }
649         return true;
650     default:
651         g_warning("unknown channel read status, closing");
652         return false;
653     }
654     return true;
655 }
656 
657 static gboolean channel_init(GAState *s, const gchar *method, const gchar *path)
658 {
659     GAChannelMethod channel_method;
660 
661     if (method == NULL) {
662         method = "virtio-serial";
663     }
664 
665     if (path == NULL) {
666         if (strcmp(method, "virtio-serial") == 0 ) {
667             /* try the default path for the virtio-serial port */
668             path = QGA_VIRTIO_PATH_DEFAULT;
669         } else if (strcmp(method, "isa-serial") == 0){
670             /* try the default path for the serial port - COM1 */
671             path = QGA_SERIAL_PATH_DEFAULT;
672         } else {
673             g_critical("must specify a path for this channel");
674             return false;
675         }
676     }
677 
678     if (strcmp(method, "virtio-serial") == 0) {
679         s->virtio = true; /* virtio requires special handling in some cases */
680         channel_method = GA_CHANNEL_VIRTIO_SERIAL;
681     } else if (strcmp(method, "isa-serial") == 0) {
682         channel_method = GA_CHANNEL_ISA_SERIAL;
683     } else if (strcmp(method, "unix-listen") == 0) {
684         channel_method = GA_CHANNEL_UNIX_LISTEN;
685     } else {
686         g_critical("unsupported channel method/type: %s", method);
687         return false;
688     }
689 
690     s->channel = ga_channel_new(channel_method, path, channel_event_cb, s);
691     if (!s->channel) {
692         g_critical("failed to create guest agent channel");
693         return false;
694     }
695 
696     return true;
697 }
698 
699 #ifdef _WIN32
700 DWORD WINAPI service_ctrl_handler(DWORD ctrl, DWORD type, LPVOID data,
701                                   LPVOID ctx)
702 {
703     DWORD ret = NO_ERROR;
704     GAService *service = &ga_state->service;
705 
706     switch (ctrl)
707     {
708         case SERVICE_CONTROL_STOP:
709         case SERVICE_CONTROL_SHUTDOWN:
710             quit_handler(SIGTERM);
711             service->status.dwCurrentState = SERVICE_STOP_PENDING;
712             SetServiceStatus(service->status_handle, &service->status);
713             break;
714 
715         default:
716             ret = ERROR_CALL_NOT_IMPLEMENTED;
717     }
718     return ret;
719 }
720 
721 VOID WINAPI service_main(DWORD argc, TCHAR *argv[])
722 {
723     GAService *service = &ga_state->service;
724 
725     service->status_handle = RegisterServiceCtrlHandlerEx(QGA_SERVICE_NAME,
726         service_ctrl_handler, NULL);
727 
728     if (service->status_handle == 0) {
729         g_critical("Failed to register extended requests function!\n");
730         return;
731     }
732 
733     service->status.dwServiceType = SERVICE_WIN32;
734     service->status.dwCurrentState = SERVICE_RUNNING;
735     service->status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
736     service->status.dwWin32ExitCode = NO_ERROR;
737     service->status.dwServiceSpecificExitCode = NO_ERROR;
738     service->status.dwCheckPoint = 0;
739     service->status.dwWaitHint = 0;
740     SetServiceStatus(service->status_handle, &service->status);
741 
742     g_main_loop_run(ga_state->main_loop);
743 
744     service->status.dwCurrentState = SERVICE_STOPPED;
745     SetServiceStatus(service->status_handle, &service->status);
746 }
747 #endif
748 
749 static void set_persistent_state_defaults(GAPersistentState *pstate)
750 {
751     g_assert(pstate);
752     pstate->fd_counter = QGA_PSTATE_DEFAULT_FD_COUNTER;
753 }
754 
755 static void persistent_state_from_keyfile(GAPersistentState *pstate,
756                                           GKeyFile *keyfile)
757 {
758     g_assert(pstate);
759     g_assert(keyfile);
760     /* if any fields are missing, either because the file was tampered with
761      * by agents of chaos, or because the field wasn't present at the time the
762      * file was created, the best we can ever do is start over with the default
763      * values. so load them now, and ignore any errors in accessing key-value
764      * pairs
765      */
766     set_persistent_state_defaults(pstate);
767 
768     if (g_key_file_has_key(keyfile, "global", "fd_counter", NULL)) {
769         pstate->fd_counter =
770             g_key_file_get_integer(keyfile, "global", "fd_counter", NULL);
771     }
772 }
773 
774 static void persistent_state_to_keyfile(const GAPersistentState *pstate,
775                                         GKeyFile *keyfile)
776 {
777     g_assert(pstate);
778     g_assert(keyfile);
779 
780     g_key_file_set_integer(keyfile, "global", "fd_counter", pstate->fd_counter);
781 }
782 
783 static gboolean write_persistent_state(const GAPersistentState *pstate,
784                                        const gchar *path)
785 {
786     GKeyFile *keyfile = g_key_file_new();
787     GError *gerr = NULL;
788     gboolean ret = true;
789     gchar *data = NULL;
790     gsize data_len;
791 
792     g_assert(pstate);
793 
794     persistent_state_to_keyfile(pstate, keyfile);
795     data = g_key_file_to_data(keyfile, &data_len, &gerr);
796     if (gerr) {
797         g_critical("failed to convert persistent state to string: %s",
798                    gerr->message);
799         ret = false;
800         goto out;
801     }
802 
803     g_file_set_contents(path, data, data_len, &gerr);
804     if (gerr) {
805         g_critical("failed to write persistent state to %s: %s",
806                     path, gerr->message);
807         ret = false;
808         goto out;
809     }
810 
811 out:
812     if (gerr) {
813         g_error_free(gerr);
814     }
815     if (keyfile) {
816         g_key_file_free(keyfile);
817     }
818     g_free(data);
819     return ret;
820 }
821 
822 static gboolean read_persistent_state(GAPersistentState *pstate,
823                                       const gchar *path, gboolean frozen)
824 {
825     GKeyFile *keyfile = NULL;
826     GError *gerr = NULL;
827     struct stat st;
828     gboolean ret = true;
829 
830     g_assert(pstate);
831 
832     if (stat(path, &st) == -1) {
833         /* it's okay if state file doesn't exist, but any other error
834          * indicates a permissions issue or some other misconfiguration
835          * that we likely won't be able to recover from.
836          */
837         if (errno != ENOENT) {
838             g_critical("unable to access state file at path %s: %s",
839                        path, strerror(errno));
840             ret = false;
841             goto out;
842         }
843 
844         /* file doesn't exist. initialize state to default values and
845          * attempt to save now. (we could wait till later when we have
846          * modified state we need to commit, but if there's a problem,
847          * such as a missing parent directory, we want to catch it now)
848          *
849          * there is a potential scenario where someone either managed to
850          * update the agent from a version that didn't use a key store
851          * while qemu-ga thought the filesystem was frozen, or
852          * deleted the key store prior to issuing a fsfreeze, prior
853          * to restarting the agent. in this case we go ahead and defer
854          * initial creation till we actually have modified state to
855          * write, otherwise fail to recover from freeze.
856          */
857         set_persistent_state_defaults(pstate);
858         if (!frozen) {
859             ret = write_persistent_state(pstate, path);
860             if (!ret) {
861                 g_critical("unable to create state file at path %s", path);
862                 ret = false;
863                 goto out;
864             }
865         }
866         ret = true;
867         goto out;
868     }
869 
870     keyfile = g_key_file_new();
871     g_key_file_load_from_file(keyfile, path, 0, &gerr);
872     if (gerr) {
873         g_critical("error loading persistent state from path: %s, %s",
874                    path, gerr->message);
875         ret = false;
876         goto out;
877     }
878 
879     persistent_state_from_keyfile(pstate, keyfile);
880 
881 out:
882     if (keyfile) {
883         g_key_file_free(keyfile);
884     }
885     if (gerr) {
886         g_error_free(gerr);
887     }
888 
889     return ret;
890 }
891 
892 int64_t ga_get_fd_handle(GAState *s, Error **errp)
893 {
894     int64_t handle;
895 
896     g_assert(s->pstate_filepath);
897     /* we blacklist commands and avoid operations that potentially require
898      * writing to disk when we're in a frozen state. this includes opening
899      * new files, so we should never get here in that situation
900      */
901     g_assert(!ga_is_frozen(s));
902 
903     handle = s->pstate.fd_counter++;
904 
905     /* This should never happen on a reasonable timeframe, as guest-file-open
906      * would have to be issued 2^63 times */
907     if (s->pstate.fd_counter == INT64_MAX) {
908         abort();
909     }
910 
911     if (!write_persistent_state(&s->pstate, s->pstate_filepath)) {
912         error_setg(errp, "failed to commit persistent state to disk");
913         return -1;
914     }
915 
916     return handle;
917 }
918 
919 static void ga_print_cmd(QmpCommand *cmd, void *opaque)
920 {
921     printf("%s\n", qmp_command_name(cmd));
922 }
923 
924 int main(int argc, char **argv)
925 {
926     const char *sopt = "hVvdm:p:l:f:F::b:s:t:";
927     const char *method = NULL, *path = NULL;
928     const char *log_filepath = NULL;
929     const char *pid_filepath;
930 #ifdef CONFIG_FSFREEZE
931     const char *fsfreeze_hook = NULL;
932 #endif
933     const char *state_dir;
934 #ifdef _WIN32
935     const char *service = NULL;
936 #endif
937     const struct option lopt[] = {
938         { "help", 0, NULL, 'h' },
939         { "version", 0, NULL, 'V' },
940         { "logfile", 1, NULL, 'l' },
941         { "pidfile", 1, NULL, 'f' },
942 #ifdef CONFIG_FSFREEZE
943         { "fsfreeze-hook", 2, NULL, 'F' },
944 #endif
945         { "verbose", 0, NULL, 'v' },
946         { "method", 1, NULL, 'm' },
947         { "path", 1, NULL, 'p' },
948         { "daemonize", 0, NULL, 'd' },
949         { "blacklist", 1, NULL, 'b' },
950 #ifdef _WIN32
951         { "service", 1, NULL, 's' },
952 #endif
953         { "statedir", 1, NULL, 't' },
954         { NULL, 0, NULL, 0 }
955     };
956     int opt_ind = 0, ch, daemonize = 0, i, j, len;
957     GLogLevelFlags log_level = G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL;
958     GList *blacklist = NULL;
959     GAState *s;
960 
961     module_call_init(MODULE_INIT_QAPI);
962 
963     init_dfl_pathnames();
964     pid_filepath = dfl_pathnames.pidfile;
965     state_dir = dfl_pathnames.state_dir;
966 
967     while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
968         switch (ch) {
969         case 'm':
970             method = optarg;
971             break;
972         case 'p':
973             path = optarg;
974             break;
975         case 'l':
976             log_filepath = optarg;
977             break;
978         case 'f':
979             pid_filepath = optarg;
980             break;
981 #ifdef CONFIG_FSFREEZE
982         case 'F':
983             fsfreeze_hook = optarg ? optarg : QGA_FSFREEZE_HOOK_DEFAULT;
984             break;
985 #endif
986         case 't':
987              state_dir = optarg;
988              break;
989         case 'v':
990             /* enable all log levels */
991             log_level = G_LOG_LEVEL_MASK;
992             break;
993         case 'V':
994             printf("QEMU Guest Agent %s\n", QEMU_VERSION);
995             return 0;
996         case 'd':
997             daemonize = 1;
998             break;
999         case 'b': {
1000             if (is_help_option(optarg)) {
1001                 qmp_for_each_command(ga_print_cmd, NULL);
1002                 return 0;
1003             }
1004             for (j = 0, i = 0, len = strlen(optarg); i < len; i++) {
1005                 if (optarg[i] == ',') {
1006                     optarg[i] = 0;
1007                     blacklist = g_list_append(blacklist, &optarg[j]);
1008                     j = i + 1;
1009                 }
1010             }
1011             if (j < i) {
1012                 blacklist = g_list_append(blacklist, &optarg[j]);
1013             }
1014             break;
1015         }
1016 #ifdef _WIN32
1017         case 's':
1018             service = optarg;
1019             if (strcmp(service, "install") == 0) {
1020                 const char *fixed_state_dir;
1021 
1022                 /* If the user passed the "-t" option, we save that state dir
1023                  * in the service. Otherwise we let the service fetch the state
1024                  * dir from the environment when it starts.
1025                  */
1026                 fixed_state_dir = (state_dir == dfl_pathnames.state_dir) ?
1027                                   NULL :
1028                                   state_dir;
1029                 if (ga_install_vss_provider()) {
1030                     return EXIT_FAILURE;
1031                 }
1032                 if (ga_install_service(path, log_filepath, fixed_state_dir)) {
1033                     return EXIT_FAILURE;
1034                 }
1035                 return 0;
1036             } else if (strcmp(service, "uninstall") == 0) {
1037                 ga_uninstall_vss_provider();
1038                 return ga_uninstall_service();
1039             } else {
1040                 printf("Unknown service command.\n");
1041                 return EXIT_FAILURE;
1042             }
1043             break;
1044 #endif
1045         case 'h':
1046             usage(argv[0]);
1047             return 0;
1048         case '?':
1049             g_print("Unknown option, try '%s --help' for more information.\n",
1050                     argv[0]);
1051             return EXIT_FAILURE;
1052         }
1053     }
1054 
1055 #ifdef _WIN32
1056     /* On win32 the state directory is application specific (be it the default
1057      * or a user override). We got past the command line parsing; let's create
1058      * the directory (with any intermediate directories). If we run into an
1059      * error later on, we won't try to clean up the directory, it is considered
1060      * persistent.
1061      */
1062     if (g_mkdir_with_parents(state_dir, S_IRWXU) == -1) {
1063         g_critical("unable to create (an ancestor of) the state directory"
1064                    " '%s': %s", state_dir, strerror(errno));
1065         return EXIT_FAILURE;
1066     }
1067 #endif
1068 
1069     s = g_malloc0(sizeof(GAState));
1070     s->log_level = log_level;
1071     s->log_file = stderr;
1072 #ifdef CONFIG_FSFREEZE
1073     s->fsfreeze_hook = fsfreeze_hook;
1074 #endif
1075     g_log_set_default_handler(ga_log, s);
1076     g_log_set_fatal_mask(NULL, G_LOG_LEVEL_ERROR);
1077     ga_enable_logging(s);
1078     s->state_filepath_isfrozen = g_strdup_printf("%s/qga.state.isfrozen",
1079                                                  state_dir);
1080     s->pstate_filepath = g_strdup_printf("%s/qga.state", state_dir);
1081     s->frozen = false;
1082 
1083 #ifndef _WIN32
1084     /* check if a previous instance of qemu-ga exited with filesystems' state
1085      * marked as frozen. this could be a stale value (a non-qemu-ga process
1086      * or reboot may have since unfrozen them), but better to require an
1087      * uneeded unfreeze than to risk hanging on start-up
1088      */
1089     struct stat st;
1090     if (stat(s->state_filepath_isfrozen, &st) == -1) {
1091         /* it's okay if the file doesn't exist, but if we can't access for
1092          * some other reason, such as permissions, there's a configuration
1093          * that needs to be addressed. so just bail now before we get into
1094          * more trouble later
1095          */
1096         if (errno != ENOENT) {
1097             g_critical("unable to access state file at path %s: %s",
1098                        s->state_filepath_isfrozen, strerror(errno));
1099             return EXIT_FAILURE;
1100         }
1101     } else {
1102         g_warning("previous instance appears to have exited with frozen"
1103                   " filesystems. deferring logging/pidfile creation and"
1104                   " disabling non-fsfreeze-safe commands until"
1105                   " guest-fsfreeze-thaw is issued, or filesystems are"
1106                   " manually unfrozen and the file %s is removed",
1107                   s->state_filepath_isfrozen);
1108         s->frozen = true;
1109     }
1110 #endif
1111 
1112     if (ga_is_frozen(s)) {
1113         if (daemonize) {
1114             /* delay opening/locking of pidfile till filesystems are unfrozen */
1115             s->deferred_options.pid_filepath = pid_filepath;
1116             become_daemon(NULL);
1117         }
1118         if (log_filepath) {
1119             /* delay opening the log file till filesystems are unfrozen */
1120             s->deferred_options.log_filepath = log_filepath;
1121         }
1122         ga_disable_logging(s);
1123         qmp_for_each_command(ga_disable_non_whitelisted, NULL);
1124     } else {
1125         if (daemonize) {
1126             become_daemon(pid_filepath);
1127         }
1128         if (log_filepath) {
1129             FILE *log_file = ga_open_logfile(log_filepath);
1130             if (!log_file) {
1131                 g_critical("unable to open specified log file: %s",
1132                            strerror(errno));
1133                 goto out_bad;
1134             }
1135             s->log_file = log_file;
1136         }
1137     }
1138 
1139     /* load persistent state from disk */
1140     if (!read_persistent_state(&s->pstate,
1141                                s->pstate_filepath,
1142                                ga_is_frozen(s))) {
1143         g_critical("failed to load persistent state");
1144         goto out_bad;
1145     }
1146 
1147     if (blacklist) {
1148         s->blacklist = blacklist;
1149         do {
1150             g_debug("disabling command: %s", (char *)blacklist->data);
1151             qmp_disable_command(blacklist->data);
1152             blacklist = g_list_next(blacklist);
1153         } while (blacklist);
1154     }
1155     s->command_state = ga_command_state_new();
1156     ga_command_state_init(s, s->command_state);
1157     ga_command_state_init_all(s->command_state);
1158     json_message_parser_init(&s->parser, process_event);
1159     ga_state = s;
1160 #ifndef _WIN32
1161     if (!register_signal_handlers()) {
1162         g_critical("failed to register signal handlers");
1163         goto out_bad;
1164     }
1165 #endif
1166 
1167     s->main_loop = g_main_loop_new(NULL, false);
1168     if (!channel_init(ga_state, method, path)) {
1169         g_critical("failed to initialize guest agent channel");
1170         goto out_bad;
1171     }
1172 #ifndef _WIN32
1173     g_main_loop_run(ga_state->main_loop);
1174 #else
1175     if (daemonize) {
1176         SERVICE_TABLE_ENTRY service_table[] = {
1177             { (char *)QGA_SERVICE_NAME, service_main }, { NULL, NULL } };
1178         StartServiceCtrlDispatcher(service_table);
1179     } else {
1180         g_main_loop_run(ga_state->main_loop);
1181     }
1182 #endif
1183 
1184     ga_command_state_cleanup_all(ga_state->command_state);
1185     ga_channel_free(ga_state->channel);
1186 
1187     if (daemonize) {
1188         unlink(pid_filepath);
1189     }
1190     return 0;
1191 
1192 out_bad:
1193     if (daemonize) {
1194         unlink(pid_filepath);
1195     }
1196     return EXIT_FAILURE;
1197 }
1198