Merge remote-tracking branch 'bonzini/hw-dirs' into staging
[qemu/agraf.git] / qga / main.c
blobdb281a508be6d6adb3123a31574d4b4328e84604
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 "qapi/qmp/json-streamer.h"
24 #include "qapi/qmp/json-parser.h"
25 #include "qapi/qmp/qint.h"
26 #include "qapi/qmp/qjson.h"
27 #include "qga/guest-agent-core.h"
28 #include "qemu/module.h"
29 #include "signal.h"
30 #include "qapi/qmp/qerror.h"
31 #include "qapi/qmp/dispatch.h"
32 #include "qga/channel.h"
33 #ifdef _WIN32
34 #include "qga/service-win32.h"
35 #include <windows.h>
36 #endif
37 #ifdef __linux__
38 #include <linux/fs.h>
39 #ifdef FIFREEZE
40 #define CONFIG_FSFREEZE
41 #endif
42 #endif
44 #ifndef _WIN32
45 #define QGA_VIRTIO_PATH_DEFAULT "/dev/virtio-ports/org.qemu.guest_agent.0"
46 #else
47 #define QGA_VIRTIO_PATH_DEFAULT "\\\\.\\Global\\org.qemu.guest_agent.0"
48 #endif
49 #define QGA_STATEDIR_DEFAULT CONFIG_QEMU_LOCALSTATEDIR "/run"
50 #define QGA_PIDFILE_DEFAULT QGA_STATEDIR_DEFAULT "/qemu-ga.pid"
51 #ifdef CONFIG_FSFREEZE
52 #define QGA_FSFREEZE_HOOK_DEFAULT CONFIG_QEMU_CONFDIR "/fsfreeze-hook"
53 #endif
54 #define QGA_SENTINEL_BYTE 0xFF
56 struct GAState {
57 JSONMessageParser parser;
58 GMainLoop *main_loop;
59 GAChannel *channel;
60 bool virtio; /* fastpath to check for virtio to deal with poll() quirks */
61 GACommandState *command_state;
62 GLogLevelFlags log_level;
63 FILE *log_file;
64 bool logging_enabled;
65 #ifdef _WIN32
66 GAService service;
67 #endif
68 bool delimit_response;
69 bool frozen;
70 GList *blacklist;
71 const char *state_filepath_isfrozen;
72 struct {
73 const char *log_filepath;
74 const char *pid_filepath;
75 } deferred_options;
76 #ifdef CONFIG_FSFREEZE
77 const char *fsfreeze_hook;
78 #endif
81 struct GAState *ga_state;
83 /* commands that are safe to issue while filesystems are frozen */
84 static const char *ga_freeze_whitelist[] = {
85 "guest-ping",
86 "guest-info",
87 "guest-sync",
88 "guest-fsfreeze-status",
89 "guest-fsfreeze-thaw",
90 NULL
93 #ifdef _WIN32
94 DWORD WINAPI service_ctrl_handler(DWORD ctrl, DWORD type, LPVOID data,
95 LPVOID ctx);
96 VOID WINAPI service_main(DWORD argc, TCHAR *argv[]);
97 #endif
99 static void quit_handler(int sig)
101 /* if we're frozen, don't exit unless we're absolutely forced to,
102 * because it's basically impossible for graceful exit to complete
103 * unless all log/pid files are on unfreezable filesystems. there's
104 * also a very likely chance killing the agent before unfreezing
105 * the filesystems is a mistake (or will be viewed as one later).
107 if (ga_is_frozen(ga_state)) {
108 return;
110 g_debug("received signal num %d, quitting", sig);
112 if (g_main_loop_is_running(ga_state->main_loop)) {
113 g_main_loop_quit(ga_state->main_loop);
117 #ifndef _WIN32
118 static gboolean register_signal_handlers(void)
120 struct sigaction sigact;
121 int ret;
123 memset(&sigact, 0, sizeof(struct sigaction));
124 sigact.sa_handler = quit_handler;
126 ret = sigaction(SIGINT, &sigact, NULL);
127 if (ret == -1) {
128 g_error("error configuring signal handler: %s", strerror(errno));
130 ret = sigaction(SIGTERM, &sigact, NULL);
131 if (ret == -1) {
132 g_error("error configuring signal handler: %s", strerror(errno));
135 return true;
138 /* TODO: use this in place of all post-fork() fclose(std*) callers */
139 void reopen_fd_to_null(int fd)
141 int nullfd;
143 nullfd = open("/dev/null", O_RDWR);
144 if (nullfd < 0) {
145 return;
148 dup2(nullfd, fd);
150 if (nullfd != fd) {
151 close(nullfd);
154 #endif
156 static void usage(const char *cmd)
158 printf(
159 "Usage: %s [-m <method> -p <path>] [<options>]\n"
160 "QEMU Guest Agent %s\n"
161 "\n"
162 " -m, --method transport method: one of unix-listen, virtio-serial, or\n"
163 " isa-serial (virtio-serial is the default)\n"
164 " -p, --path device/socket path (the default for virtio-serial is:\n"
165 " %s)\n"
166 " -l, --logfile set logfile path, logs to stderr by default\n"
167 " -f, --pidfile specify pidfile (default is %s)\n"
168 #ifdef CONFIG_FSFREEZE
169 " -F, --fsfreeze-hook\n"
170 " enable fsfreeze hook. Accepts an optional argument that\n"
171 " specifies script to run on freeze/thaw. Script will be\n"
172 " called with 'freeze'/'thaw' arguments accordingly.\n"
173 " (default is %s)\n"
174 " If using -F with an argument, do not follow -F with a\n"
175 " space.\n"
176 " (for example: -F/var/run/fsfreezehook.sh)\n"
177 #endif
178 " -t, --statedir specify dir to store state information (absolute paths\n"
179 " only, default is %s)\n"
180 " -v, --verbose log extra debugging information\n"
181 " -V, --version print version information and exit\n"
182 " -d, --daemonize become a daemon\n"
183 #ifdef _WIN32
184 " -s, --service service commands: install, uninstall\n"
185 #endif
186 " -b, --blacklist comma-separated list of RPCs to disable (no spaces, \"?\"\n"
187 " to list available RPCs)\n"
188 " -h, --help display this help and exit\n"
189 "\n"
190 "Report bugs to <mdroth@linux.vnet.ibm.com>\n"
191 , cmd, QEMU_VERSION, QGA_VIRTIO_PATH_DEFAULT, QGA_PIDFILE_DEFAULT,
192 #ifdef CONFIG_FSFREEZE
193 QGA_FSFREEZE_HOOK_DEFAULT,
194 #endif
195 QGA_STATEDIR_DEFAULT);
198 static const char *ga_log_level_str(GLogLevelFlags level)
200 switch (level & G_LOG_LEVEL_MASK) {
201 case G_LOG_LEVEL_ERROR:
202 return "error";
203 case G_LOG_LEVEL_CRITICAL:
204 return "critical";
205 case G_LOG_LEVEL_WARNING:
206 return "warning";
207 case G_LOG_LEVEL_MESSAGE:
208 return "message";
209 case G_LOG_LEVEL_INFO:
210 return "info";
211 case G_LOG_LEVEL_DEBUG:
212 return "debug";
213 default:
214 return "user";
218 bool ga_logging_enabled(GAState *s)
220 return s->logging_enabled;
223 void ga_disable_logging(GAState *s)
225 s->logging_enabled = false;
228 void ga_enable_logging(GAState *s)
230 s->logging_enabled = true;
233 static void ga_log(const gchar *domain, GLogLevelFlags level,
234 const gchar *msg, gpointer opaque)
236 GAState *s = opaque;
237 GTimeVal time;
238 const char *level_str = ga_log_level_str(level);
240 if (!ga_logging_enabled(s)) {
241 return;
244 level &= G_LOG_LEVEL_MASK;
245 #ifndef _WIN32
246 if (domain && strcmp(domain, "syslog") == 0) {
247 syslog(LOG_INFO, "%s: %s", level_str, msg);
248 } else if (level & s->log_level) {
249 #else
250 if (level & s->log_level) {
251 #endif
252 g_get_current_time(&time);
253 fprintf(s->log_file,
254 "%lu.%lu: %s: %s\n", time.tv_sec, time.tv_usec, level_str, msg);
255 fflush(s->log_file);
259 void ga_set_response_delimited(GAState *s)
261 s->delimit_response = true;
264 static FILE *ga_open_logfile(const char *logfile)
266 FILE *f;
268 f = fopen(logfile, "a");
269 if (!f) {
270 return NULL;
273 qemu_set_cloexec(fileno(f));
274 return f;
277 #ifndef _WIN32
278 static bool ga_open_pidfile(const char *pidfile)
280 int pidfd;
281 char pidstr[32];
283 pidfd = qemu_open(pidfile, O_CREAT|O_WRONLY, S_IRUSR|S_IWUSR);
284 if (pidfd == -1 || lockf(pidfd, F_TLOCK, 0)) {
285 g_critical("Cannot lock pid file, %s", strerror(errno));
286 if (pidfd != -1) {
287 close(pidfd);
289 return false;
292 if (ftruncate(pidfd, 0)) {
293 g_critical("Failed to truncate pid file");
294 goto fail;
296 snprintf(pidstr, sizeof(pidstr), "%d\n", getpid());
297 if (write(pidfd, pidstr, strlen(pidstr)) != strlen(pidstr)) {
298 g_critical("Failed to write pid file");
299 goto fail;
302 /* keep pidfile open & locked forever */
303 return true;
305 fail:
306 unlink(pidfile);
307 close(pidfd);
308 return false;
310 #else /* _WIN32 */
311 static bool ga_open_pidfile(const char *pidfile)
313 return true;
315 #endif
317 static gint ga_strcmp(gconstpointer str1, gconstpointer str2)
319 return strcmp(str1, str2);
322 /* disable commands that aren't safe for fsfreeze */
323 static void ga_disable_non_whitelisted(void)
325 char **list_head, **list;
326 bool whitelisted;
327 int i;
329 list_head = list = qmp_get_command_list();
330 while (*list != NULL) {
331 whitelisted = false;
332 i = 0;
333 while (ga_freeze_whitelist[i] != NULL) {
334 if (strcmp(*list, ga_freeze_whitelist[i]) == 0) {
335 whitelisted = true;
337 i++;
339 if (!whitelisted) {
340 g_debug("disabling command: %s", *list);
341 qmp_disable_command(*list);
343 g_free(*list);
344 list++;
346 g_free(list_head);
349 /* [re-]enable all commands, except those explicitly blacklisted by user */
350 static void ga_enable_non_blacklisted(GList *blacklist)
352 char **list_head, **list;
354 list_head = list = qmp_get_command_list();
355 while (*list != NULL) {
356 if (g_list_find_custom(blacklist, *list, ga_strcmp) == NULL &&
357 !qmp_command_is_enabled(*list)) {
358 g_debug("enabling command: %s", *list);
359 qmp_enable_command(*list);
361 g_free(*list);
362 list++;
364 g_free(list_head);
367 static bool ga_create_file(const char *path)
369 int fd = open(path, O_CREAT | O_WRONLY, S_IWUSR | S_IRUSR);
370 if (fd == -1) {
371 g_warning("unable to open/create file %s: %s", path, strerror(errno));
372 return false;
374 close(fd);
375 return true;
378 static bool ga_delete_file(const char *path)
380 int ret = unlink(path);
381 if (ret == -1) {
382 g_warning("unable to delete file: %s: %s", path, strerror(errno));
383 return false;
386 return true;
389 bool ga_is_frozen(GAState *s)
391 return s->frozen;
394 void ga_set_frozen(GAState *s)
396 if (ga_is_frozen(s)) {
397 return;
399 /* disable all non-whitelisted (for frozen state) commands */
400 ga_disable_non_whitelisted();
401 g_warning("disabling logging due to filesystem freeze");
402 ga_disable_logging(s);
403 s->frozen = true;
404 if (!ga_create_file(s->state_filepath_isfrozen)) {
405 g_warning("unable to create %s, fsfreeze may not function properly",
406 s->state_filepath_isfrozen);
410 void ga_unset_frozen(GAState *s)
412 if (!ga_is_frozen(s)) {
413 return;
416 /* if we delayed creation/opening of pid/log files due to being
417 * in a frozen state at start up, do it now
419 if (s->deferred_options.log_filepath) {
420 s->log_file = ga_open_logfile(s->deferred_options.log_filepath);
421 if (!s->log_file) {
422 s->log_file = stderr;
424 s->deferred_options.log_filepath = NULL;
426 ga_enable_logging(s);
427 g_warning("logging re-enabled due to filesystem unfreeze");
428 if (s->deferred_options.pid_filepath) {
429 if (!ga_open_pidfile(s->deferred_options.pid_filepath)) {
430 g_warning("failed to create/open pid file");
432 s->deferred_options.pid_filepath = NULL;
435 /* enable all disabled, non-blacklisted commands */
436 ga_enable_non_blacklisted(s->blacklist);
437 s->frozen = false;
438 if (!ga_delete_file(s->state_filepath_isfrozen)) {
439 g_warning("unable to delete %s, fsfreeze may not function properly",
440 s->state_filepath_isfrozen);
444 #ifdef CONFIG_FSFREEZE
445 const char *ga_fsfreeze_hook(GAState *s)
447 return s->fsfreeze_hook;
449 #endif
451 static void become_daemon(const char *pidfile)
453 #ifndef _WIN32
454 pid_t pid, sid;
456 pid = fork();
457 if (pid < 0) {
458 exit(EXIT_FAILURE);
460 if (pid > 0) {
461 exit(EXIT_SUCCESS);
464 if (pidfile) {
465 if (!ga_open_pidfile(pidfile)) {
466 g_critical("failed to create pidfile");
467 exit(EXIT_FAILURE);
471 umask(0);
472 sid = setsid();
473 if (sid < 0) {
474 goto fail;
476 if ((chdir("/")) < 0) {
477 goto fail;
480 reopen_fd_to_null(STDIN_FILENO);
481 reopen_fd_to_null(STDOUT_FILENO);
482 reopen_fd_to_null(STDERR_FILENO);
483 return;
485 fail:
486 if (pidfile) {
487 unlink(pidfile);
489 g_critical("failed to daemonize");
490 exit(EXIT_FAILURE);
491 #endif
494 static int send_response(GAState *s, QObject *payload)
496 const char *buf;
497 QString *payload_qstr, *response_qstr;
498 GIOStatus status;
500 g_assert(payload && s->channel);
502 payload_qstr = qobject_to_json(payload);
503 if (!payload_qstr) {
504 return -EINVAL;
507 if (s->delimit_response) {
508 s->delimit_response = false;
509 response_qstr = qstring_new();
510 qstring_append_chr(response_qstr, QGA_SENTINEL_BYTE);
511 qstring_append(response_qstr, qstring_get_str(payload_qstr));
512 QDECREF(payload_qstr);
513 } else {
514 response_qstr = payload_qstr;
517 qstring_append_chr(response_qstr, '\n');
518 buf = qstring_get_str(response_qstr);
519 status = ga_channel_write_all(s->channel, buf, strlen(buf));
520 QDECREF(response_qstr);
521 if (status != G_IO_STATUS_NORMAL) {
522 return -EIO;
525 return 0;
528 static void process_command(GAState *s, QDict *req)
530 QObject *rsp = NULL;
531 int ret;
533 g_assert(req);
534 g_debug("processing command");
535 rsp = qmp_dispatch(QOBJECT(req));
536 if (rsp) {
537 ret = send_response(s, rsp);
538 if (ret) {
539 g_warning("error sending response: %s", strerror(ret));
541 qobject_decref(rsp);
545 /* handle requests/control events coming in over the channel */
546 static void process_event(JSONMessageParser *parser, QList *tokens)
548 GAState *s = container_of(parser, GAState, parser);
549 QObject *obj;
550 QDict *qdict;
551 Error *err = NULL;
552 int ret;
554 g_assert(s && parser);
556 g_debug("process_event: called");
557 obj = json_parser_parse_err(tokens, NULL, &err);
558 if (err || !obj || qobject_type(obj) != QTYPE_QDICT) {
559 qobject_decref(obj);
560 qdict = qdict_new();
561 if (!err) {
562 g_warning("failed to parse event: unknown error");
563 error_set(&err, QERR_JSON_PARSING);
564 } else {
565 g_warning("failed to parse event: %s", error_get_pretty(err));
567 qdict_put_obj(qdict, "error", qmp_build_error_object(err));
568 error_free(err);
569 } else {
570 qdict = qobject_to_qdict(obj);
573 g_assert(qdict);
575 /* handle host->guest commands */
576 if (qdict_haskey(qdict, "execute")) {
577 process_command(s, qdict);
578 } else {
579 if (!qdict_haskey(qdict, "error")) {
580 QDECREF(qdict);
581 qdict = qdict_new();
582 g_warning("unrecognized payload format");
583 error_set(&err, QERR_UNSUPPORTED);
584 qdict_put_obj(qdict, "error", qmp_build_error_object(err));
585 error_free(err);
587 ret = send_response(s, QOBJECT(qdict));
588 if (ret) {
589 g_warning("error sending error response: %s", strerror(ret));
593 QDECREF(qdict);
596 /* false return signals GAChannel to close the current client connection */
597 static gboolean channel_event_cb(GIOCondition condition, gpointer data)
599 GAState *s = data;
600 gchar buf[QGA_READ_COUNT_DEFAULT+1];
601 gsize count;
602 GError *err = NULL;
603 GIOStatus status = ga_channel_read(s->channel, buf, QGA_READ_COUNT_DEFAULT, &count);
604 if (err != NULL) {
605 g_warning("error reading channel: %s", err->message);
606 g_error_free(err);
607 return false;
609 switch (status) {
610 case G_IO_STATUS_ERROR:
611 g_warning("error reading channel");
612 return false;
613 case G_IO_STATUS_NORMAL:
614 buf[count] = 0;
615 g_debug("read data, count: %d, data: %s", (int)count, buf);
616 json_message_parser_feed(&s->parser, (char *)buf, (int)count);
617 break;
618 case G_IO_STATUS_EOF:
619 g_debug("received EOF");
620 if (!s->virtio) {
621 return false;
623 /* fall through */
624 case G_IO_STATUS_AGAIN:
625 /* virtio causes us to spin here when no process is attached to
626 * host-side chardev. sleep a bit to mitigate this
628 if (s->virtio) {
629 usleep(100*1000);
631 return true;
632 default:
633 g_warning("unknown channel read status, closing");
634 return false;
636 return true;
639 static gboolean channel_init(GAState *s, const gchar *method, const gchar *path)
641 GAChannelMethod channel_method;
643 if (method == NULL) {
644 method = "virtio-serial";
647 if (path == NULL) {
648 if (strcmp(method, "virtio-serial") != 0) {
649 g_critical("must specify a path for this channel");
650 return false;
652 /* try the default path for the virtio-serial port */
653 path = QGA_VIRTIO_PATH_DEFAULT;
656 if (strcmp(method, "virtio-serial") == 0) {
657 s->virtio = true; /* virtio requires special handling in some cases */
658 channel_method = GA_CHANNEL_VIRTIO_SERIAL;
659 } else if (strcmp(method, "isa-serial") == 0) {
660 channel_method = GA_CHANNEL_ISA_SERIAL;
661 } else if (strcmp(method, "unix-listen") == 0) {
662 channel_method = GA_CHANNEL_UNIX_LISTEN;
663 } else {
664 g_critical("unsupported channel method/type: %s", method);
665 return false;
668 s->channel = ga_channel_new(channel_method, path, channel_event_cb, s);
669 if (!s->channel) {
670 g_critical("failed to create guest agent channel");
671 return false;
674 return true;
677 #ifdef _WIN32
678 DWORD WINAPI service_ctrl_handler(DWORD ctrl, DWORD type, LPVOID data,
679 LPVOID ctx)
681 DWORD ret = NO_ERROR;
682 GAService *service = &ga_state->service;
684 switch (ctrl)
686 case SERVICE_CONTROL_STOP:
687 case SERVICE_CONTROL_SHUTDOWN:
688 quit_handler(SIGTERM);
689 service->status.dwCurrentState = SERVICE_STOP_PENDING;
690 SetServiceStatus(service->status_handle, &service->status);
691 break;
693 default:
694 ret = ERROR_CALL_NOT_IMPLEMENTED;
696 return ret;
699 VOID WINAPI service_main(DWORD argc, TCHAR *argv[])
701 GAService *service = &ga_state->service;
703 service->status_handle = RegisterServiceCtrlHandlerEx(QGA_SERVICE_NAME,
704 service_ctrl_handler, NULL);
706 if (service->status_handle == 0) {
707 g_critical("Failed to register extended requests function!\n");
708 return;
711 service->status.dwServiceType = SERVICE_WIN32;
712 service->status.dwCurrentState = SERVICE_RUNNING;
713 service->status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
714 service->status.dwWin32ExitCode = NO_ERROR;
715 service->status.dwServiceSpecificExitCode = NO_ERROR;
716 service->status.dwCheckPoint = 0;
717 service->status.dwWaitHint = 0;
718 SetServiceStatus(service->status_handle, &service->status);
720 g_main_loop_run(ga_state->main_loop);
722 service->status.dwCurrentState = SERVICE_STOPPED;
723 SetServiceStatus(service->status_handle, &service->status);
725 #endif
727 int main(int argc, char **argv)
729 const char *sopt = "hVvdm:p:l:f:F::b:s:t:";
730 const char *method = NULL, *path = NULL;
731 const char *log_filepath = NULL;
732 const char *pid_filepath = QGA_PIDFILE_DEFAULT;
733 #ifdef CONFIG_FSFREEZE
734 const char *fsfreeze_hook = NULL;
735 #endif
736 const char *state_dir = QGA_STATEDIR_DEFAULT;
737 #ifdef _WIN32
738 const char *service = NULL;
739 #endif
740 const struct option lopt[] = {
741 { "help", 0, NULL, 'h' },
742 { "version", 0, NULL, 'V' },
743 { "logfile", 1, NULL, 'l' },
744 { "pidfile", 1, NULL, 'f' },
745 #ifdef CONFIG_FSFREEZE
746 { "fsfreeze-hook", 2, NULL, 'F' },
747 #endif
748 { "verbose", 0, NULL, 'v' },
749 { "method", 1, NULL, 'm' },
750 { "path", 1, NULL, 'p' },
751 { "daemonize", 0, NULL, 'd' },
752 { "blacklist", 1, NULL, 'b' },
753 #ifdef _WIN32
754 { "service", 1, NULL, 's' },
755 #endif
756 { "statedir", 1, NULL, 't' },
757 { NULL, 0, NULL, 0 }
759 int opt_ind = 0, ch, daemonize = 0, i, j, len;
760 GLogLevelFlags log_level = G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL;
761 GList *blacklist = NULL;
762 GAState *s;
764 module_call_init(MODULE_INIT_QAPI);
766 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
767 switch (ch) {
768 case 'm':
769 method = optarg;
770 break;
771 case 'p':
772 path = optarg;
773 break;
774 case 'l':
775 log_filepath = optarg;
776 break;
777 case 'f':
778 pid_filepath = optarg;
779 break;
780 #ifdef CONFIG_FSFREEZE
781 case 'F':
782 fsfreeze_hook = optarg ? optarg : QGA_FSFREEZE_HOOK_DEFAULT;
783 break;
784 #endif
785 case 't':
786 state_dir = optarg;
787 break;
788 case 'v':
789 /* enable all log levels */
790 log_level = G_LOG_LEVEL_MASK;
791 break;
792 case 'V':
793 printf("QEMU Guest Agent %s\n", QEMU_VERSION);
794 return 0;
795 case 'd':
796 daemonize = 1;
797 break;
798 case 'b': {
799 char **list_head, **list;
800 if (is_help_option(optarg)) {
801 list_head = list = qmp_get_command_list();
802 while (*list != NULL) {
803 printf("%s\n", *list);
804 g_free(*list);
805 list++;
807 g_free(list_head);
808 return 0;
810 for (j = 0, i = 0, len = strlen(optarg); i < len; i++) {
811 if (optarg[i] == ',') {
812 optarg[i] = 0;
813 blacklist = g_list_append(blacklist, &optarg[j]);
814 j = i + 1;
817 if (j < i) {
818 blacklist = g_list_append(blacklist, &optarg[j]);
820 break;
822 #ifdef _WIN32
823 case 's':
824 service = optarg;
825 if (strcmp(service, "install") == 0) {
826 return ga_install_service(path, log_filepath);
827 } else if (strcmp(service, "uninstall") == 0) {
828 return ga_uninstall_service();
829 } else {
830 printf("Unknown service command.\n");
831 return EXIT_FAILURE;
833 break;
834 #endif
835 case 'h':
836 usage(argv[0]);
837 return 0;
838 case '?':
839 g_print("Unknown option, try '%s --help' for more information.\n",
840 argv[0]);
841 return EXIT_FAILURE;
845 s = g_malloc0(sizeof(GAState));
846 s->log_level = log_level;
847 s->log_file = stderr;
848 #ifdef CONFIG_FSFREEZE
849 s->fsfreeze_hook = fsfreeze_hook;
850 #endif
851 g_log_set_default_handler(ga_log, s);
852 g_log_set_fatal_mask(NULL, G_LOG_LEVEL_ERROR);
853 ga_enable_logging(s);
854 s->state_filepath_isfrozen = g_strdup_printf("%s/qga.state.isfrozen",
855 state_dir);
856 s->frozen = false;
857 #ifndef _WIN32
858 /* check if a previous instance of qemu-ga exited with filesystems' state
859 * marked as frozen. this could be a stale value (a non-qemu-ga process
860 * or reboot may have since unfrozen them), but better to require an
861 * uneeded unfreeze than to risk hanging on start-up
863 struct stat st;
864 if (stat(s->state_filepath_isfrozen, &st) == -1) {
865 /* it's okay if the file doesn't exist, but if we can't access for
866 * some other reason, such as permissions, there's a configuration
867 * that needs to be addressed. so just bail now before we get into
868 * more trouble later
870 if (errno != ENOENT) {
871 g_critical("unable to access state file at path %s: %s",
872 s->state_filepath_isfrozen, strerror(errno));
873 return EXIT_FAILURE;
875 } else {
876 g_warning("previous instance appears to have exited with frozen"
877 " filesystems. deferring logging/pidfile creation and"
878 " disabling non-fsfreeze-safe commands until"
879 " guest-fsfreeze-thaw is issued, or filesystems are"
880 " manually unfrozen and the file %s is removed",
881 s->state_filepath_isfrozen);
882 s->frozen = true;
884 #endif
886 if (ga_is_frozen(s)) {
887 if (daemonize) {
888 /* delay opening/locking of pidfile till filesystem are unfrozen */
889 s->deferred_options.pid_filepath = pid_filepath;
890 become_daemon(NULL);
892 if (log_filepath) {
893 /* delay opening the log file till filesystems are unfrozen */
894 s->deferred_options.log_filepath = log_filepath;
896 ga_disable_logging(s);
897 ga_disable_non_whitelisted();
898 } else {
899 if (daemonize) {
900 become_daemon(pid_filepath);
902 if (log_filepath) {
903 FILE *log_file = ga_open_logfile(log_filepath);
904 if (!log_file) {
905 g_critical("unable to open specified log file: %s",
906 strerror(errno));
907 goto out_bad;
909 s->log_file = log_file;
913 if (blacklist) {
914 s->blacklist = blacklist;
915 do {
916 g_debug("disabling command: %s", (char *)blacklist->data);
917 qmp_disable_command(blacklist->data);
918 blacklist = g_list_next(blacklist);
919 } while (blacklist);
921 s->command_state = ga_command_state_new();
922 ga_command_state_init(s, s->command_state);
923 ga_command_state_init_all(s->command_state);
924 json_message_parser_init(&s->parser, process_event);
925 ga_state = s;
926 #ifndef _WIN32
927 if (!register_signal_handlers()) {
928 g_critical("failed to register signal handlers");
929 goto out_bad;
931 #endif
933 s->main_loop = g_main_loop_new(NULL, false);
934 if (!channel_init(ga_state, method, path)) {
935 g_critical("failed to initialize guest agent channel");
936 goto out_bad;
938 #ifndef _WIN32
939 g_main_loop_run(ga_state->main_loop);
940 #else
941 if (daemonize) {
942 SERVICE_TABLE_ENTRY service_table[] = {
943 { (char *)QGA_SERVICE_NAME, service_main }, { NULL, NULL } };
944 StartServiceCtrlDispatcher(service_table);
945 } else {
946 g_main_loop_run(ga_state->main_loop);
948 #endif
950 ga_command_state_cleanup_all(ga_state->command_state);
951 ga_channel_free(ga_state->channel);
953 if (daemonize) {
954 unlink(pid_filepath);
956 return 0;
958 out_bad:
959 if (daemonize) {
960 unlink(pid_filepath);
962 return EXIT_FAILURE;