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