Merge remote-tracking branch 'qmp/queue/qmp' into staging
[qemu-kvm.git] / qemu-ga.c
blob8f87621ae4ace3736604277ae31710db09c48d4d
1 /*
2 * QEMU Guest Agent
4 * Copyright IBM Corp. 2011
6 * Authors:
7 * Adam Litke <aglitke@linux.vnet.ibm.com>
8 * Michael Roth <mdroth@linux.vnet.ibm.com>
10 * This work is licensed under the terms of the GNU GPL, version 2 or later.
11 * See the COPYING file in the top-level directory.
13 #include <stdlib.h>
14 #include <stdio.h>
15 #include <stdbool.h>
16 #include <glib.h>
17 #include <getopt.h>
18 #ifndef _WIN32
19 #include <syslog.h>
20 #include <sys/wait.h>
21 #include <sys/stat.h>
22 #endif
23 #include "json-streamer.h"
24 #include "json-parser.h"
25 #include "qint.h"
26 #include "qjson.h"
27 #include "qga/guest-agent-core.h"
28 #include "module.h"
29 #include "signal.h"
30 #include "qerror.h"
31 #include "qapi/qmp-core.h"
32 #include "qga/channel.h"
33 #ifdef _WIN32
34 #include "qga/service-win32.h"
35 #include <windows.h>
36 #endif
38 #ifndef _WIN32
39 #define QGA_VIRTIO_PATH_DEFAULT "/dev/virtio-ports/org.qemu.guest_agent.0"
40 #else
41 #define QGA_VIRTIO_PATH_DEFAULT "\\\\.\\Global\\org.qemu.guest_agent.0"
42 #endif
43 #define QGA_PIDFILE_DEFAULT "/var/run/qemu-ga.pid"
44 #define QGA_STATEDIR_DEFAULT "/tmp"
45 #define QGA_SENTINEL_BYTE 0xFF
47 struct GAState {
48 JSONMessageParser parser;
49 GMainLoop *main_loop;
50 GAChannel *channel;
51 bool virtio; /* fastpath to check for virtio to deal with poll() quirks */
52 GACommandState *command_state;
53 GLogLevelFlags log_level;
54 FILE *log_file;
55 bool logging_enabled;
56 #ifdef _WIN32
57 GAService service;
58 #endif
59 bool delimit_response;
60 bool frozen;
61 GList *blacklist;
62 const char *state_filepath_isfrozen;
63 struct {
64 const char *log_filepath;
65 const char *pid_filepath;
66 } deferred_options;
69 struct GAState *ga_state;
71 /* commands that are safe to issue while filesystems are frozen */
72 static const char *ga_freeze_whitelist[] = {
73 "guest-ping",
74 "guest-info",
75 "guest-sync",
76 "guest-fsfreeze-status",
77 "guest-fsfreeze-thaw",
78 NULL
81 #ifdef _WIN32
82 DWORD WINAPI service_ctrl_handler(DWORD ctrl, DWORD type, LPVOID data,
83 LPVOID ctx);
84 VOID WINAPI service_main(DWORD argc, TCHAR *argv[]);
85 #endif
87 static void quit_handler(int sig)
89 /* if we're frozen, don't exit unless we're absolutely forced to,
90 * because it's basically impossible for graceful exit to complete
91 * unless all log/pid files are on unfreezable filesystems. there's
92 * also a very likely chance killing the agent before unfreezing
93 * the filesystems is a mistake (or will be viewed as one later).
95 if (ga_is_frozen(ga_state)) {
96 return;
98 g_debug("received signal num %d, quitting", sig);
100 if (g_main_loop_is_running(ga_state->main_loop)) {
101 g_main_loop_quit(ga_state->main_loop);
105 #ifndef _WIN32
106 static gboolean register_signal_handlers(void)
108 struct sigaction sigact;
109 int ret;
111 memset(&sigact, 0, sizeof(struct sigaction));
112 sigact.sa_handler = quit_handler;
114 ret = sigaction(SIGINT, &sigact, NULL);
115 if (ret == -1) {
116 g_error("error configuring signal handler: %s", strerror(errno));
117 return false;
119 ret = sigaction(SIGTERM, &sigact, NULL);
120 if (ret == -1) {
121 g_error("error configuring signal handler: %s", strerror(errno));
122 return false;
125 return true;
128 /* TODO: use this in place of all post-fork() fclose(std*) callers */
129 void reopen_fd_to_null(int fd)
131 int nullfd;
133 nullfd = open("/dev/null", O_RDWR);
134 if (nullfd < 0) {
135 return;
138 dup2(nullfd, fd);
140 if (nullfd != fd) {
141 close(nullfd);
144 #endif
146 static void usage(const char *cmd)
148 printf(
149 "Usage: %s [-m <method> -p <path>] [<options>]\n"
150 "QEMU Guest Agent %s\n"
151 "\n"
152 " -m, --method transport method: one of unix-listen, virtio-serial, or\n"
153 " isa-serial (virtio-serial is the default)\n"
154 " -p, --path device/socket path (the default for virtio-serial is:\n"
155 " %s)\n"
156 " -l, --logfile set logfile path, logs to stderr by default\n"
157 " -f, --pidfile specify pidfile (default is %s)\n"
158 " -t, --statedir specify dir to store state information (absolute paths\n"
159 " only, default is %s)\n"
160 " -v, --verbose log extra debugging information\n"
161 " -V, --version print version information and exit\n"
162 " -d, --daemonize become a daemon\n"
163 #ifdef _WIN32
164 " -s, --service service commands: install, uninstall\n"
165 #endif
166 " -b, --blacklist comma-separated list of RPCs to disable (no spaces, \"?\"\n"
167 " to list available RPCs)\n"
168 " -h, --help display this help and exit\n"
169 "\n"
170 "Report bugs to <mdroth@linux.vnet.ibm.com>\n"
171 , cmd, QEMU_VERSION, QGA_VIRTIO_PATH_DEFAULT, QGA_PIDFILE_DEFAULT,
172 QGA_STATEDIR_DEFAULT);
175 static const char *ga_log_level_str(GLogLevelFlags level)
177 switch (level & G_LOG_LEVEL_MASK) {
178 case G_LOG_LEVEL_ERROR:
179 return "error";
180 case G_LOG_LEVEL_CRITICAL:
181 return "critical";
182 case G_LOG_LEVEL_WARNING:
183 return "warning";
184 case G_LOG_LEVEL_MESSAGE:
185 return "message";
186 case G_LOG_LEVEL_INFO:
187 return "info";
188 case G_LOG_LEVEL_DEBUG:
189 return "debug";
190 default:
191 return "user";
195 bool ga_logging_enabled(GAState *s)
197 return s->logging_enabled;
200 void ga_disable_logging(GAState *s)
202 s->logging_enabled = false;
205 void ga_enable_logging(GAState *s)
207 s->logging_enabled = true;
210 static void ga_log(const gchar *domain, GLogLevelFlags level,
211 const gchar *msg, gpointer opaque)
213 GAState *s = opaque;
214 GTimeVal time;
215 const char *level_str = ga_log_level_str(level);
217 if (!ga_logging_enabled(s)) {
218 return;
221 level &= G_LOG_LEVEL_MASK;
222 #ifndef _WIN32
223 if (domain && strcmp(domain, "syslog") == 0) {
224 syslog(LOG_INFO, "%s: %s", level_str, msg);
225 } else if (level & s->log_level) {
226 #else
227 if (level & s->log_level) {
228 #endif
229 g_get_current_time(&time);
230 fprintf(s->log_file,
231 "%lu.%lu: %s: %s\n", time.tv_sec, time.tv_usec, level_str, msg);
232 fflush(s->log_file);
236 void ga_set_response_delimited(GAState *s)
238 s->delimit_response = true;
241 #ifndef _WIN32
242 static bool ga_open_pidfile(const char *pidfile)
244 int pidfd;
245 char pidstr[32];
247 pidfd = open(pidfile, O_CREAT|O_WRONLY, S_IRUSR|S_IWUSR);
248 if (pidfd == -1 || lockf(pidfd, F_TLOCK, 0)) {
249 g_critical("Cannot lock pid file, %s", strerror(errno));
250 return false;
253 if (ftruncate(pidfd, 0) || lseek(pidfd, 0, SEEK_SET)) {
254 g_critical("Failed to truncate pid file");
255 goto fail;
257 sprintf(pidstr, "%d", getpid());
258 if (write(pidfd, pidstr, strlen(pidstr)) != strlen(pidstr)) {
259 g_critical("Failed to write pid file");
260 goto fail;
263 return true;
265 fail:
266 unlink(pidfile);
267 return false;
269 #else /* _WIN32 */
270 static bool ga_open_pidfile(const char *pidfile)
272 return true;
274 #endif
276 static gint ga_strcmp(gconstpointer str1, gconstpointer str2)
278 return strcmp(str1, str2);
281 /* disable commands that aren't safe for fsfreeze */
282 static void ga_disable_non_whitelisted(void)
284 char **list_head, **list;
285 bool whitelisted;
286 int i;
288 list_head = list = qmp_get_command_list();
289 while (*list != NULL) {
290 whitelisted = false;
291 i = 0;
292 while (ga_freeze_whitelist[i] != NULL) {
293 if (strcmp(*list, ga_freeze_whitelist[i]) == 0) {
294 whitelisted = true;
296 i++;
298 if (!whitelisted) {
299 g_debug("disabling command: %s", *list);
300 qmp_disable_command(*list);
302 g_free(*list);
303 list++;
305 g_free(list_head);
308 /* [re-]enable all commands, except those explicitly blacklisted by user */
309 static void ga_enable_non_blacklisted(GList *blacklist)
311 char **list_head, **list;
313 list_head = list = qmp_get_command_list();
314 while (*list != NULL) {
315 if (g_list_find_custom(blacklist, *list, ga_strcmp) == NULL &&
316 !qmp_command_is_enabled(*list)) {
317 g_debug("enabling command: %s", *list);
318 qmp_enable_command(*list);
320 g_free(*list);
321 list++;
323 g_free(list_head);
326 static bool ga_create_file(const char *path)
328 int fd = open(path, O_CREAT | O_WRONLY, S_IWUSR | S_IRUSR);
329 if (fd == -1) {
330 g_warning("unable to open/create file %s: %s", path, strerror(errno));
331 return false;
333 close(fd);
334 return true;
337 static bool ga_delete_file(const char *path)
339 int ret = unlink(path);
340 if (ret == -1) {
341 g_warning("unable to delete file: %s: %s", path, strerror(errno));
342 return false;
345 return true;
348 bool ga_is_frozen(GAState *s)
350 return s->frozen;
353 void ga_set_frozen(GAState *s)
355 if (ga_is_frozen(s)) {
356 return;
358 /* disable all non-whitelisted (for frozen state) commands */
359 ga_disable_non_whitelisted();
360 g_warning("disabling logging due to filesystem freeze");
361 ga_disable_logging(s);
362 s->frozen = true;
363 if (!ga_create_file(s->state_filepath_isfrozen)) {
364 g_warning("unable to create %s, fsfreeze may not function properly",
365 s->state_filepath_isfrozen);
369 void ga_unset_frozen(GAState *s)
371 if (!ga_is_frozen(s)) {
372 return;
375 /* if we delayed creation/opening of pid/log files due to being
376 * in a frozen state at start up, do it now
378 if (s->deferred_options.log_filepath) {
379 s->log_file = fopen(s->deferred_options.log_filepath, "a");
380 if (!s->log_file) {
381 s->log_file = stderr;
383 s->deferred_options.log_filepath = NULL;
385 ga_enable_logging(s);
386 g_warning("logging re-enabled due to filesystem unfreeze");
387 if (s->deferred_options.pid_filepath) {
388 if (!ga_open_pidfile(s->deferred_options.pid_filepath)) {
389 g_warning("failed to create/open pid file");
391 s->deferred_options.pid_filepath = NULL;
394 /* enable all disabled, non-blacklisted commands */
395 ga_enable_non_blacklisted(s->blacklist);
396 s->frozen = false;
397 if (!ga_delete_file(s->state_filepath_isfrozen)) {
398 g_warning("unable to delete %s, fsfreeze may not function properly",
399 s->state_filepath_isfrozen);
403 static void become_daemon(const char *pidfile)
405 #ifndef _WIN32
406 pid_t pid, sid;
408 pid = fork();
409 if (pid < 0) {
410 exit(EXIT_FAILURE);
412 if (pid > 0) {
413 exit(EXIT_SUCCESS);
416 if (pidfile) {
417 if (!ga_open_pidfile(pidfile)) {
418 g_critical("failed to create pidfile");
419 exit(EXIT_FAILURE);
423 umask(0);
424 sid = setsid();
425 if (sid < 0) {
426 goto fail;
428 if ((chdir("/")) < 0) {
429 goto fail;
432 reopen_fd_to_null(STDIN_FILENO);
433 reopen_fd_to_null(STDOUT_FILENO);
434 reopen_fd_to_null(STDERR_FILENO);
435 return;
437 fail:
438 unlink(pidfile);
439 g_critical("failed to daemonize");
440 exit(EXIT_FAILURE);
441 #endif
444 static int send_response(GAState *s, QObject *payload)
446 const char *buf;
447 QString *payload_qstr, *response_qstr;
448 GIOStatus status;
450 g_assert(payload && s->channel);
452 payload_qstr = qobject_to_json(payload);
453 if (!payload_qstr) {
454 return -EINVAL;
457 if (s->delimit_response) {
458 s->delimit_response = false;
459 response_qstr = qstring_new();
460 qstring_append_chr(response_qstr, QGA_SENTINEL_BYTE);
461 qstring_append(response_qstr, qstring_get_str(payload_qstr));
462 QDECREF(payload_qstr);
463 } else {
464 response_qstr = payload_qstr;
467 qstring_append_chr(response_qstr, '\n');
468 buf = qstring_get_str(response_qstr);
469 status = ga_channel_write_all(s->channel, buf, strlen(buf));
470 QDECREF(response_qstr);
471 if (status != G_IO_STATUS_NORMAL) {
472 return -EIO;
475 return 0;
478 static void process_command(GAState *s, QDict *req)
480 QObject *rsp = NULL;
481 int ret;
483 g_assert(req);
484 g_debug("processing command");
485 rsp = qmp_dispatch(QOBJECT(req));
486 if (rsp) {
487 ret = send_response(s, rsp);
488 if (ret) {
489 g_warning("error sending response: %s", strerror(ret));
491 qobject_decref(rsp);
495 /* handle requests/control events coming in over the channel */
496 static void process_event(JSONMessageParser *parser, QList *tokens)
498 GAState *s = container_of(parser, GAState, parser);
499 QObject *obj;
500 QDict *qdict;
501 Error *err = NULL;
502 int ret;
504 g_assert(s && parser);
506 g_debug("process_event: called");
507 obj = json_parser_parse_err(tokens, NULL, &err);
508 if (err || !obj || qobject_type(obj) != QTYPE_QDICT) {
509 qobject_decref(obj);
510 qdict = qdict_new();
511 if (!err) {
512 g_warning("failed to parse event: unknown error");
513 error_set(&err, QERR_JSON_PARSING);
514 } else {
515 g_warning("failed to parse event: %s", error_get_pretty(err));
517 qdict_put_obj(qdict, "error", qmp_build_error_object(err));
518 error_free(err);
519 } else {
520 qdict = qobject_to_qdict(obj);
523 g_assert(qdict);
525 /* handle host->guest commands */
526 if (qdict_haskey(qdict, "execute")) {
527 process_command(s, qdict);
528 } else {
529 if (!qdict_haskey(qdict, "error")) {
530 QDECREF(qdict);
531 qdict = qdict_new();
532 g_warning("unrecognized payload format");
533 error_set(&err, QERR_UNSUPPORTED);
534 qdict_put_obj(qdict, "error", qmp_build_error_object(err));
535 error_free(err);
537 ret = send_response(s, QOBJECT(qdict));
538 if (ret) {
539 g_warning("error sending error response: %s", strerror(ret));
543 QDECREF(qdict);
546 /* false return signals GAChannel to close the current client connection */
547 static gboolean channel_event_cb(GIOCondition condition, gpointer data)
549 GAState *s = data;
550 gchar buf[QGA_READ_COUNT_DEFAULT+1];
551 gsize count;
552 GError *err = NULL;
553 GIOStatus status = ga_channel_read(s->channel, buf, QGA_READ_COUNT_DEFAULT, &count);
554 if (err != NULL) {
555 g_warning("error reading channel: %s", err->message);
556 g_error_free(err);
557 return false;
559 switch (status) {
560 case G_IO_STATUS_ERROR:
561 g_warning("error reading channel");
562 return false;
563 case G_IO_STATUS_NORMAL:
564 buf[count] = 0;
565 g_debug("read data, count: %d, data: %s", (int)count, buf);
566 json_message_parser_feed(&s->parser, (char *)buf, (int)count);
567 break;
568 case G_IO_STATUS_EOF:
569 g_debug("received EOF");
570 if (!s->virtio) {
571 return false;
573 case G_IO_STATUS_AGAIN:
574 /* virtio causes us to spin here when no process is attached to
575 * host-side chardev. sleep a bit to mitigate this
577 if (s->virtio) {
578 usleep(100*1000);
580 return true;
581 default:
582 g_warning("unknown channel read status, closing");
583 return false;
585 return true;
588 static gboolean channel_init(GAState *s, const gchar *method, const gchar *path)
590 GAChannelMethod channel_method;
592 if (method == NULL) {
593 method = "virtio-serial";
596 if (path == NULL) {
597 if (strcmp(method, "virtio-serial") != 0) {
598 g_critical("must specify a path for this channel");
599 return false;
601 /* try the default path for the virtio-serial port */
602 path = QGA_VIRTIO_PATH_DEFAULT;
605 if (strcmp(method, "virtio-serial") == 0) {
606 s->virtio = true; /* virtio requires special handling in some cases */
607 channel_method = GA_CHANNEL_VIRTIO_SERIAL;
608 } else if (strcmp(method, "isa-serial") == 0) {
609 channel_method = GA_CHANNEL_ISA_SERIAL;
610 } else if (strcmp(method, "unix-listen") == 0) {
611 channel_method = GA_CHANNEL_UNIX_LISTEN;
612 } else {
613 g_critical("unsupported channel method/type: %s", method);
614 return false;
617 s->channel = ga_channel_new(channel_method, path, channel_event_cb, s);
618 if (!s->channel) {
619 g_critical("failed to create guest agent channel");
620 return false;
623 return true;
626 #ifdef _WIN32
627 DWORD WINAPI service_ctrl_handler(DWORD ctrl, DWORD type, LPVOID data,
628 LPVOID ctx)
630 DWORD ret = NO_ERROR;
631 GAService *service = &ga_state->service;
633 switch (ctrl)
635 case SERVICE_CONTROL_STOP:
636 case SERVICE_CONTROL_SHUTDOWN:
637 quit_handler(SIGTERM);
638 service->status.dwCurrentState = SERVICE_STOP_PENDING;
639 SetServiceStatus(service->status_handle, &service->status);
640 break;
642 default:
643 ret = ERROR_CALL_NOT_IMPLEMENTED;
645 return ret;
648 VOID WINAPI service_main(DWORD argc, TCHAR *argv[])
650 GAService *service = &ga_state->service;
652 service->status_handle = RegisterServiceCtrlHandlerEx(QGA_SERVICE_NAME,
653 service_ctrl_handler, NULL);
655 if (service->status_handle == 0) {
656 g_critical("Failed to register extended requests function!\n");
657 return;
660 service->status.dwServiceType = SERVICE_WIN32;
661 service->status.dwCurrentState = SERVICE_RUNNING;
662 service->status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
663 service->status.dwWin32ExitCode = NO_ERROR;
664 service->status.dwServiceSpecificExitCode = NO_ERROR;
665 service->status.dwCheckPoint = 0;
666 service->status.dwWaitHint = 0;
667 SetServiceStatus(service->status_handle, &service->status);
669 g_main_loop_run(ga_state->main_loop);
671 service->status.dwCurrentState = SERVICE_STOPPED;
672 SetServiceStatus(service->status_handle, &service->status);
674 #endif
676 int main(int argc, char **argv)
678 const char *sopt = "hVvdm:p:l:f:b:s:t:";
679 const char *method = NULL, *path = NULL;
680 const char *log_filepath = NULL;
681 const char *pid_filepath = QGA_PIDFILE_DEFAULT;
682 const char *state_dir = QGA_STATEDIR_DEFAULT;
683 #ifdef _WIN32
684 const char *service = NULL;
685 #endif
686 const struct option lopt[] = {
687 { "help", 0, NULL, 'h' },
688 { "version", 0, NULL, 'V' },
689 { "logfile", 1, NULL, 'l' },
690 { "pidfile", 1, NULL, 'f' },
691 { "verbose", 0, NULL, 'v' },
692 { "method", 1, NULL, 'm' },
693 { "path", 1, NULL, 'p' },
694 { "daemonize", 0, NULL, 'd' },
695 { "blacklist", 1, NULL, 'b' },
696 #ifdef _WIN32
697 { "service", 1, NULL, 's' },
698 #endif
699 { "statedir", 1, NULL, 't' },
700 { NULL, 0, NULL, 0 }
702 int opt_ind = 0, ch, daemonize = 0, i, j, len;
703 GLogLevelFlags log_level = G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL;
704 GList *blacklist = NULL;
705 GAState *s;
707 module_call_init(MODULE_INIT_QAPI);
709 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
710 switch (ch) {
711 case 'm':
712 method = optarg;
713 break;
714 case 'p':
715 path = optarg;
716 break;
717 case 'l':
718 log_filepath = optarg;
719 break;
720 case 'f':
721 pid_filepath = optarg;
722 break;
723 case 't':
724 state_dir = optarg;
725 break;
726 case 'v':
727 /* enable all log levels */
728 log_level = G_LOG_LEVEL_MASK;
729 break;
730 case 'V':
731 printf("QEMU Guest Agent %s\n", QEMU_VERSION);
732 return 0;
733 case 'd':
734 daemonize = 1;
735 break;
736 case 'b': {
737 char **list_head, **list;
738 if (is_help_option(optarg)) {
739 list_head = list = qmp_get_command_list();
740 while (*list != NULL) {
741 printf("%s\n", *list);
742 g_free(*list);
743 list++;
745 g_free(list_head);
746 return 0;
748 for (j = 0, i = 0, len = strlen(optarg); i < len; i++) {
749 if (optarg[i] == ',') {
750 optarg[i] = 0;
751 blacklist = g_list_append(blacklist, &optarg[j]);
752 j = i + 1;
755 if (j < i) {
756 blacklist = g_list_append(blacklist, &optarg[j]);
758 break;
760 #ifdef _WIN32
761 case 's':
762 service = optarg;
763 if (strcmp(service, "install") == 0) {
764 return ga_install_service(path, log_filepath);
765 } else if (strcmp(service, "uninstall") == 0) {
766 return ga_uninstall_service();
767 } else {
768 printf("Unknown service command.\n");
769 return EXIT_FAILURE;
771 break;
772 #endif
773 case 'h':
774 usage(argv[0]);
775 return 0;
776 case '?':
777 g_print("Unknown option, try '%s --help' for more information.\n",
778 argv[0]);
779 return EXIT_FAILURE;
783 s = g_malloc0(sizeof(GAState));
784 s->log_level = log_level;
785 s->log_file = stderr;
786 g_log_set_default_handler(ga_log, s);
787 g_log_set_fatal_mask(NULL, G_LOG_LEVEL_ERROR);
788 ga_enable_logging(s);
789 s->state_filepath_isfrozen = g_strdup_printf("%s/qga.state.isfrozen",
790 state_dir);
791 s->frozen = false;
792 #ifndef _WIN32
793 /* check if a previous instance of qemu-ga exited with filesystems' state
794 * marked as frozen. this could be a stale value (a non-qemu-ga process
795 * or reboot may have since unfrozen them), but better to require an
796 * uneeded unfreeze than to risk hanging on start-up
798 struct stat st;
799 if (stat(s->state_filepath_isfrozen, &st) == -1) {
800 /* it's okay if the file doesn't exist, but if we can't access for
801 * some other reason, such as permissions, there's a configuration
802 * that needs to be addressed. so just bail now before we get into
803 * more trouble later
805 if (errno != ENOENT) {
806 g_critical("unable to access state file at path %s: %s",
807 s->state_filepath_isfrozen, strerror(errno));
808 return EXIT_FAILURE;
810 } else {
811 g_warning("previous instance appears to have exited with frozen"
812 " filesystems. deferring logging/pidfile creation and"
813 " disabling non-fsfreeze-safe commands until"
814 " guest-fsfreeze-thaw is issued, or filesystems are"
815 " manually unfrozen and the file %s is removed",
816 s->state_filepath_isfrozen);
817 s->frozen = true;
819 #endif
821 if (ga_is_frozen(s)) {
822 if (daemonize) {
823 /* delay opening/locking of pidfile till filesystem are unfrozen */
824 s->deferred_options.pid_filepath = pid_filepath;
825 become_daemon(NULL);
827 if (log_filepath) {
828 /* delay opening the log file till filesystems are unfrozen */
829 s->deferred_options.log_filepath = log_filepath;
831 ga_disable_logging(s);
832 ga_disable_non_whitelisted();
833 } else {
834 if (daemonize) {
835 become_daemon(pid_filepath);
837 if (log_filepath) {
838 FILE *log_file = fopen(log_filepath, "a");
839 if (!log_file) {
840 g_critical("unable to open specified log file: %s",
841 strerror(errno));
842 goto out_bad;
844 s->log_file = log_file;
848 if (blacklist) {
849 s->blacklist = blacklist;
850 do {
851 g_debug("disabling command: %s", (char *)blacklist->data);
852 qmp_disable_command(blacklist->data);
853 blacklist = g_list_next(blacklist);
854 } while (blacklist);
856 s->command_state = ga_command_state_new();
857 ga_command_state_init(s, s->command_state);
858 ga_command_state_init_all(s->command_state);
859 json_message_parser_init(&s->parser, process_event);
860 ga_state = s;
861 #ifndef _WIN32
862 if (!register_signal_handlers()) {
863 g_critical("failed to register signal handlers");
864 goto out_bad;
866 #endif
868 s->main_loop = g_main_loop_new(NULL, false);
869 if (!channel_init(ga_state, method, path)) {
870 g_critical("failed to initialize guest agent channel");
871 goto out_bad;
873 #ifndef _WIN32
874 g_main_loop_run(ga_state->main_loop);
875 #else
876 if (daemonize) {
877 SERVICE_TABLE_ENTRY service_table[] = {
878 { (char *)QGA_SERVICE_NAME, service_main }, { NULL, NULL } };
879 StartServiceCtrlDispatcher(service_table);
880 } else {
881 g_main_loop_run(ga_state->main_loop);
883 #endif
885 ga_command_state_cleanup_all(ga_state->command_state);
886 ga_channel_free(ga_state->channel);
888 if (daemonize) {
889 unlink(pid_filepath);
891 return 0;
893 out_bad:
894 if (daemonize) {
895 unlink(pid_filepath);
897 return EXIT_FAILURE;