4 * Copyright IBM Corp. 2011
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.
14 #include "qemu/osdep.h"
16 #include <glib/gstdio.h>
21 #include "qemu/help-texts.h"
22 #include "qapi/qmp/json-parser.h"
23 #include "qapi/qmp/qdict.h"
24 #include "qapi/qmp/qjson.h"
25 #include "guest-agent-core.h"
26 #include "qga-qapi-init-commands.h"
27 #include "qapi/qmp/qerror.h"
28 #include "qapi/error.h"
30 #include "qemu/cutils.h"
31 #include "qemu/help_option.h"
32 #include "qemu/sockets.h"
33 #include "qemu/systemd.h"
34 #include "qemu-version.h"
37 #include "qga/service-win32.h"
38 #include "qga/vss-win32.h"
40 #include "commands-common.h"
44 #define QGA_VIRTIO_PATH_DEFAULT "/dev/vtcon/org.qemu.guest_agent.0"
45 #else /* CONFIG_BSD */
46 #define QGA_VIRTIO_PATH_DEFAULT "/dev/virtio-ports/org.qemu.guest_agent.0"
47 #endif /* CONFIG_BSD */
48 #define QGA_SERIAL_PATH_DEFAULT "/dev/ttyS0"
49 #define QGA_STATE_RELATIVE_DIR "run"
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"
55 #ifdef CONFIG_FSFREEZE
56 #define QGA_FSFREEZE_HOOK_DEFAULT CONFIG_QEMU_CONFDIR "/fsfreeze-hook"
58 #define QGA_SENTINEL_BYTE 0xFF
59 #define QGA_CONF_DEFAULT CONFIG_QEMU_CONFDIR G_DIR_SEPARATOR_S "qemu-ga.conf"
60 #define QGA_RETRY_INTERVAL 5
63 const char *state_dir
;
67 typedef struct GAPersistentState
{
68 #define QGA_PSTATE_DEFAULT_FD_COUNTER 1000
72 typedef struct GAConfig GAConfig
;
75 JSONMessageParser parser
;
78 bool virtio
; /* fastpath to check for virtio to deal with poll() quirks */
79 GACommandState
*command_state
;
80 GLogLevelFlags log_level
;
88 bool delimit_response
;
91 char *state_filepath_isfrozen
;
93 const char *log_filepath
;
94 const char *pid_filepath
;
96 #ifdef CONFIG_FSFREEZE
97 const char *fsfreeze_hook
;
99 gchar
*pstate_filepath
;
100 GAPersistentState pstate
;
102 int socket_activation
;
106 struct GAState
*ga_state
;
107 QmpCommandList ga_commands
;
109 /* commands that are safe to issue while filesystems are frozen */
110 static const char *ga_freeze_allowlist
[] = {
114 "guest-sync-delimited",
115 "guest-fsfreeze-status",
116 "guest-fsfreeze-thaw",
121 DWORD WINAPI
service_ctrl_handler(DWORD ctrl
, DWORD type
, LPVOID data
,
123 DWORD WINAPI
handle_serial_device_events(DWORD type
, LPVOID data
);
124 VOID WINAPI
service_main(DWORD argc
, TCHAR
*argv
[]);
126 static int run_agent(GAState
*s
);
127 static void stop_agent(GAState
*s
, bool requested
);
130 init_dfl_pathnames(void)
132 g_autofree
char *state
= qemu_get_local_state_dir();
134 g_assert(dfl_pathnames
.state_dir
== NULL
);
135 g_assert(dfl_pathnames
.pidfile
== NULL
);
136 dfl_pathnames
.state_dir
= g_build_filename(state
, QGA_STATE_RELATIVE_DIR
, NULL
);
137 dfl_pathnames
.pidfile
= g_build_filename(state
, QGA_STATE_RELATIVE_DIR
, "qemu-ga.pid", NULL
);
140 static void quit_handler(int sig
)
142 /* if we're frozen, don't exit unless we're absolutely forced to,
143 * because it's basically impossible for graceful exit to complete
144 * unless all log/pid files are on unfreezable filesystems. there's
145 * also a very likely chance killing the agent before unfreezing
146 * the filesystems is a mistake (or will be viewed as one later).
147 * On Windows the freeze interval is limited to 10 seconds, so
148 * we should quit, but first we should wait for the timeout, thaw
149 * the filesystem and quit.
151 if (ga_is_frozen(ga_state
)) {
155 HANDLE hEventTimeout
;
157 g_debug("Thawing filesystems before exiting");
159 hEventTimeout
= OpenEvent(EVENT_ALL_ACCESS
, FALSE
, EVENT_NAME_TIMEOUT
);
161 WaitForSingleObject(hEventTimeout
, 0);
162 CloseHandle(hEventTimeout
);
164 qga_vss_fsfreeze(&i
, false, NULL
, &err
);
166 g_debug("Error unfreezing filesystems prior to exiting: %s",
167 error_get_pretty(err
));
174 g_debug("received signal num %d, quitting", sig
);
176 stop_agent(ga_state
, true);
180 static gboolean
register_signal_handlers(void)
182 struct sigaction sigact
;
185 memset(&sigact
, 0, sizeof(struct sigaction
));
186 sigact
.sa_handler
= quit_handler
;
188 ret
= sigaction(SIGINT
, &sigact
, NULL
);
190 g_error("error configuring signal handler: %s", strerror(errno
));
192 ret
= sigaction(SIGTERM
, &sigact
, NULL
);
194 g_error("error configuring signal handler: %s", strerror(errno
));
197 sigact
.sa_handler
= SIG_IGN
;
198 if (sigaction(SIGPIPE
, &sigact
, NULL
) != 0) {
199 g_error("error configuring SIGPIPE signal handler: %s",
206 /* TODO: use this in place of all post-fork() fclose(std*) callers */
207 void reopen_fd_to_null(int fd
)
211 nullfd
= open("/dev/null", O_RDWR
);
224 static void usage(const char *cmd
)
226 #ifdef CONFIG_FSFREEZE
227 g_autofree
char *fsfreeze_hook
= get_relocated_path(QGA_FSFREEZE_HOOK_DEFAULT
);
231 "Usage: %s [-m <method> -p <path>] [<options>]\n"
232 "QEMU Guest Agent " QEMU_FULL_VERSION
"\n"
235 " -m, --method transport method: one of unix-listen, virtio-serial,\n"
236 " isa-serial, or vsock-listen (virtio-serial is the default)\n"
237 " -p, --path device/socket path (the default for virtio-serial is:\n"
239 " the default for isa-serial is:\n"
241 " Socket addresses for vsock-listen are written as\n"
243 " -l, --logfile set logfile path, logs to stderr by default\n"
244 " -f, --pidfile specify pidfile (default is %s)\n"
245 #ifdef CONFIG_FSFREEZE
246 " -F, --fsfreeze-hook\n"
247 " enable fsfreeze hook. Accepts an optional argument that\n"
248 " specifies script to run on freeze/thaw. Script will be\n"
249 " called with 'freeze'/'thaw' arguments accordingly.\n"
251 " If using -F with an argument, do not follow -F with a\n"
253 " (for example: -F/var/run/fsfreezehook.sh)\n"
255 " -t, --statedir specify dir to store state information (absolute paths\n"
256 " only, default is %s)\n"
257 " -v, --verbose log extra debugging information\n"
258 " -V, --version print version information and exit\n"
259 " -d, --daemonize become a daemon\n"
261 " -s, --service service commands: install, uninstall, vss-install, vss-uninstall\n"
263 " -b, --block-rpcs comma-separated list of RPCs to disable (no spaces,\n"
264 " use \"help\" to list available RPCs)\n"
265 " -D, --dump-conf dump a qemu-ga config file based on current config\n"
266 " options / command-line parameters to stdout\n"
267 " -r, --retry-path attempt re-opening path if it's unavailable or closed\n"
268 " due to an error which may be recoverable in the future\n"
269 " (virtio-serial driver re-install, serial device hot\n"
270 " plug/unplug, etc.)\n"
271 " -h, --help display this help and exit\n"
273 QEMU_HELP_BOTTOM
"\n"
274 , cmd
, QGA_VIRTIO_PATH_DEFAULT
, QGA_SERIAL_PATH_DEFAULT
,
275 dfl_pathnames
.pidfile
,
276 #ifdef CONFIG_FSFREEZE
279 dfl_pathnames
.state_dir
);
282 static const char *ga_log_level_str(GLogLevelFlags level
)
284 switch (level
& G_LOG_LEVEL_MASK
) {
285 case G_LOG_LEVEL_ERROR
:
287 case G_LOG_LEVEL_CRITICAL
:
289 case G_LOG_LEVEL_WARNING
:
291 case G_LOG_LEVEL_MESSAGE
:
293 case G_LOG_LEVEL_INFO
:
295 case G_LOG_LEVEL_DEBUG
:
302 bool ga_logging_enabled(GAState
*s
)
304 return s
->logging_enabled
;
307 void ga_disable_logging(GAState
*s
)
309 s
->logging_enabled
= false;
312 void ga_enable_logging(GAState
*s
)
314 s
->logging_enabled
= true;
317 static int glib_log_level_to_system(int level
)
321 case G_LOG_LEVEL_ERROR
:
323 case G_LOG_LEVEL_CRITICAL
:
325 case G_LOG_LEVEL_WARNING
:
327 case G_LOG_LEVEL_MESSAGE
:
329 case G_LOG_LEVEL_DEBUG
:
331 case G_LOG_LEVEL_INFO
:
335 case G_LOG_LEVEL_ERROR
:
336 case G_LOG_LEVEL_CRITICAL
:
337 return EVENTLOG_ERROR_TYPE
;
338 case G_LOG_LEVEL_WARNING
:
339 return EVENTLOG_WARNING_TYPE
;
340 case G_LOG_LEVEL_MESSAGE
:
341 case G_LOG_LEVEL_INFO
:
342 case G_LOG_LEVEL_DEBUG
:
344 return EVENTLOG_INFORMATION_TYPE
;
349 static void ga_log(const gchar
*domain
, GLogLevelFlags level
,
350 const gchar
*msg
, gpointer opaque
)
353 const char *level_str
= ga_log_level_str(level
);
355 if (!ga_logging_enabled(s
)) {
359 level
&= G_LOG_LEVEL_MASK
;
360 if (g_strcmp0(domain
, "syslog") == 0) {
362 syslog(glib_log_level_to_system(level
), "%s: %s", level_str
, msg
);
364 ReportEvent(s
->event_log
, glib_log_level_to_system(level
),
365 0, 1, NULL
, 1, 0, &msg
, NULL
);
367 } else if (level
& s
->log_level
) {
368 g_autoptr(GDateTime
) now
= g_date_time_new_now_utc();
369 g_autofree
char *nowstr
= g_date_time_format(now
, "%s.%f");
370 fprintf(s
->log_file
, "%s: %s: %s\n", nowstr
, level_str
, msg
);
375 void ga_set_response_delimited(GAState
*s
)
377 s
->delimit_response
= true;
380 static FILE *ga_open_logfile(const char *logfile
)
384 f
= fopen(logfile
, "a");
389 qemu_set_cloexec(fileno(f
));
393 static gint
ga_strcmp(gconstpointer str1
, gconstpointer str2
)
395 return strcmp(str1
, str2
);
398 /* disable commands that aren't safe for fsfreeze */
399 static void ga_disable_not_allowed(const QmpCommand
*cmd
, void *opaque
)
401 bool allowed
= false;
403 const char *name
= qmp_command_name(cmd
);
405 while (ga_freeze_allowlist
[i
] != NULL
) {
406 if (strcmp(name
, ga_freeze_allowlist
[i
]) == 0) {
412 g_debug("disabling command: %s", name
);
413 qmp_disable_command(&ga_commands
, name
, "the agent is in frozen state");
417 /* [re-]enable all commands, except those explicitly blocked by user */
418 static void ga_enable_non_blocked(const QmpCommand
*cmd
, void *opaque
)
420 GList
*blockedrpcs
= opaque
;
421 const char *name
= qmp_command_name(cmd
);
423 if (g_list_find_custom(blockedrpcs
, name
, ga_strcmp
) == NULL
&&
424 !qmp_command_is_enabled(cmd
)) {
425 g_debug("enabling command: %s", name
);
426 qmp_enable_command(&ga_commands
, name
);
430 static bool ga_create_file(const char *path
)
432 int fd
= open(path
, O_CREAT
| O_WRONLY
, S_IWUSR
| S_IRUSR
);
434 g_warning("unable to open/create file %s: %s", path
, strerror(errno
));
441 static bool ga_delete_file(const char *path
)
443 int ret
= unlink(path
);
445 g_warning("unable to delete file: %s: %s", path
, strerror(errno
));
452 bool ga_is_frozen(GAState
*s
)
457 void ga_set_frozen(GAState
*s
)
459 if (ga_is_frozen(s
)) {
462 /* disable all forbidden (for frozen state) commands */
463 qmp_for_each_command(&ga_commands
, ga_disable_not_allowed
, NULL
);
464 g_warning("disabling logging due to filesystem freeze");
465 ga_disable_logging(s
);
467 if (!ga_create_file(s
->state_filepath_isfrozen
)) {
468 g_warning("unable to create %s, fsfreeze may not function properly",
469 s
->state_filepath_isfrozen
);
473 void ga_unset_frozen(GAState
*s
)
475 if (!ga_is_frozen(s
)) {
479 /* if we delayed creation/opening of pid/log files due to being
480 * in a frozen state at start up, do it now
482 if (s
->deferred_options
.log_filepath
) {
483 s
->log_file
= ga_open_logfile(s
->deferred_options
.log_filepath
);
485 s
->log_file
= stderr
;
487 s
->deferred_options
.log_filepath
= NULL
;
489 ga_enable_logging(s
);
490 g_warning("logging re-enabled due to filesystem unfreeze");
491 if (s
->deferred_options
.pid_filepath
) {
494 if (!qemu_write_pidfile(s
->deferred_options
.pid_filepath
, &err
)) {
495 g_warning("%s", error_get_pretty(err
));
498 s
->deferred_options
.pid_filepath
= NULL
;
501 /* enable all disabled, non-blocked commands */
502 qmp_for_each_command(&ga_commands
, ga_enable_non_blocked
, s
->blockedrpcs
);
504 if (!ga_delete_file(s
->state_filepath_isfrozen
)) {
505 g_warning("unable to delete %s, fsfreeze may not function properly",
506 s
->state_filepath_isfrozen
);
510 #ifdef CONFIG_FSFREEZE
511 const char *ga_fsfreeze_hook(GAState
*s
)
513 return s
->fsfreeze_hook
;
517 static void become_daemon(const char *pidfile
)
533 if (!qemu_write_pidfile(pidfile
, &err
)) {
534 g_critical("%s", error_get_pretty(err
));
540 umask(S_IRWXG
| S_IRWXO
);
545 if ((chdir("/")) < 0) {
549 reopen_fd_to_null(STDIN_FILENO
);
550 reopen_fd_to_null(STDOUT_FILENO
);
551 reopen_fd_to_null(STDERR_FILENO
);
558 g_critical("failed to daemonize");
563 static int send_response(GAState
*s
, const QDict
*rsp
)
568 g_assert(s
->channel
);
574 response
= qobject_to_json(QOBJECT(rsp
));
579 if (s
->delimit_response
) {
580 s
->delimit_response
= false;
581 g_string_prepend_c(response
, QGA_SENTINEL_BYTE
);
584 g_string_append_c(response
, '\n');
585 status
= ga_channel_write_all(s
->channel
, response
->str
, response
->len
);
586 g_string_free(response
, true);
587 if (status
!= G_IO_STATUS_NORMAL
) {
594 /* handle requests/control events coming in over the channel */
595 static void process_event(void *opaque
, QObject
*obj
, Error
*err
)
601 g_debug("process_event: called");
602 assert(!obj
!= !err
);
604 rsp
= qmp_error_response(err
);
608 g_debug("processing command");
609 rsp
= qmp_dispatch(&ga_commands
, obj
, false, NULL
);
612 ret
= send_response(s
, rsp
);
614 g_warning("error sending error response: %s", strerror(-ret
));
620 /* false return signals GAChannel to close the current client connection */
621 static gboolean
channel_event_cb(GIOCondition condition
, gpointer data
)
624 gchar buf
[QGA_READ_COUNT_DEFAULT
+ 1];
626 GIOStatus status
= ga_channel_read(s
->channel
, buf
, QGA_READ_COUNT_DEFAULT
, &count
);
628 case G_IO_STATUS_ERROR
:
629 g_warning("error reading channel");
630 stop_agent(s
, false);
632 case G_IO_STATUS_NORMAL
:
634 g_debug("read data, count: %d, data: %s", (int)count
, buf
);
635 json_message_parser_feed(&s
->parser
, (char *)buf
, (int)count
);
637 case G_IO_STATUS_EOF
:
638 g_debug("received EOF");
643 case G_IO_STATUS_AGAIN
:
644 /* virtio causes us to spin here when no process is attached to
645 * host-side chardev. sleep a bit to mitigate this
648 g_usleep(G_USEC_PER_SEC
/ 10);
652 g_warning("unknown channel read status, closing");
658 static gboolean
channel_init(GAState
*s
, const gchar
*method
, const gchar
*path
,
661 GAChannelMethod channel_method
;
663 if (strcmp(method
, "virtio-serial") == 0) {
664 s
->virtio
= true; /* virtio requires special handling in some cases */
665 channel_method
= GA_CHANNEL_VIRTIO_SERIAL
;
666 } else if (strcmp(method
, "isa-serial") == 0) {
667 channel_method
= GA_CHANNEL_ISA_SERIAL
;
668 } else if (strcmp(method
, "unix-listen") == 0) {
669 channel_method
= GA_CHANNEL_UNIX_LISTEN
;
670 } else if (strcmp(method
, "vsock-listen") == 0) {
671 channel_method
= GA_CHANNEL_VSOCK_LISTEN
;
673 g_critical("unsupported channel method/type: %s", method
);
677 s
->channel
= ga_channel_new(channel_method
, path
, listen_fd
,
678 channel_event_cb
, s
);
680 g_critical("failed to create guest agent channel");
688 DWORD WINAPI
handle_serial_device_events(DWORD type
, LPVOID data
)
690 DWORD ret
= NO_ERROR
;
691 PDEV_BROADCAST_HDR broadcast_header
= (PDEV_BROADCAST_HDR
)data
;
693 if (broadcast_header
->dbch_devicetype
== DBT_DEVTYP_DEVICEINTERFACE
) {
695 /* Device inserted */
696 case DBT_DEVICEARRIVAL
:
697 /* Start QEMU-ga's service */
698 if (!SetEvent(ga_state
->wakeup_event
)) {
699 ret
= GetLastError();
703 case DBT_DEVICEQUERYREMOVE
:
704 case DBT_DEVICEREMOVEPENDING
:
705 case DBT_DEVICEREMOVECOMPLETE
:
706 /* Stop QEMU-ga's service */
707 if (!ResetEvent(ga_state
->wakeup_event
)) {
708 ret
= GetLastError();
712 ret
= ERROR_CALL_NOT_IMPLEMENTED
;
718 DWORD WINAPI
service_ctrl_handler(DWORD ctrl
, DWORD type
, LPVOID data
,
721 DWORD ret
= NO_ERROR
;
722 GAService
*service
= &ga_state
->service
;
725 case SERVICE_CONTROL_STOP
:
726 case SERVICE_CONTROL_SHUTDOWN
:
727 quit_handler(SIGTERM
);
728 SetEvent(ga_state
->wakeup_event
);
729 service
->status
.dwCurrentState
= SERVICE_STOP_PENDING
;
730 SetServiceStatus(service
->status_handle
, &service
->status
);
732 case SERVICE_CONTROL_DEVICEEVENT
:
733 handle_serial_device_events(type
, data
);
737 ret
= ERROR_CALL_NOT_IMPLEMENTED
;
742 VOID WINAPI
service_main(DWORD argc
, TCHAR
*argv
[])
744 GAService
*service
= &ga_state
->service
;
746 service
->status_handle
= RegisterServiceCtrlHandlerEx(QGA_SERVICE_NAME
,
747 service_ctrl_handler
, NULL
);
749 if (service
->status_handle
== 0) {
750 g_critical("Failed to register extended requests function!\n");
754 service
->status
.dwServiceType
= SERVICE_WIN32
;
755 service
->status
.dwCurrentState
= SERVICE_RUNNING
;
756 service
->status
.dwControlsAccepted
= SERVICE_ACCEPT_STOP
| SERVICE_ACCEPT_SHUTDOWN
;
757 service
->status
.dwWin32ExitCode
= NO_ERROR
;
758 service
->status
.dwServiceSpecificExitCode
= NO_ERROR
;
759 service
->status
.dwCheckPoint
= 0;
760 service
->status
.dwWaitHint
= 0;
761 DEV_BROADCAST_DEVICEINTERFACE notification_filter
;
762 ZeroMemory(¬ification_filter
, sizeof(notification_filter
));
763 notification_filter
.dbcc_devicetype
= DBT_DEVTYP_DEVICEINTERFACE
;
764 notification_filter
.dbcc_size
= sizeof(DEV_BROADCAST_DEVICEINTERFACE
);
765 notification_filter
.dbcc_classguid
= GUID_VIOSERIAL_PORT
;
767 service
->device_notification_handle
=
768 RegisterDeviceNotification(service
->status_handle
,
769 ¬ification_filter
, DEVICE_NOTIFY_SERVICE_HANDLE
);
770 if (!service
->device_notification_handle
) {
771 g_critical("Failed to register device notification handle!\n");
774 SetServiceStatus(service
->status_handle
, &service
->status
);
778 UnregisterDeviceNotification(service
->device_notification_handle
);
779 service
->status
.dwCurrentState
= SERVICE_STOPPED
;
780 SetServiceStatus(service
->status_handle
, &service
->status
);
784 static void set_persistent_state_defaults(GAPersistentState
*pstate
)
787 pstate
->fd_counter
= QGA_PSTATE_DEFAULT_FD_COUNTER
;
790 static void persistent_state_from_keyfile(GAPersistentState
*pstate
,
795 /* if any fields are missing, either because the file was tampered with
796 * by agents of chaos, or because the field wasn't present at the time the
797 * file was created, the best we can ever do is start over with the default
798 * values. so load them now, and ignore any errors in accessing key-value
801 set_persistent_state_defaults(pstate
);
803 if (g_key_file_has_key(keyfile
, "global", "fd_counter", NULL
)) {
805 g_key_file_get_integer(keyfile
, "global", "fd_counter", NULL
);
809 static void persistent_state_to_keyfile(const GAPersistentState
*pstate
,
815 g_key_file_set_integer(keyfile
, "global", "fd_counter", pstate
->fd_counter
);
818 static gboolean
write_persistent_state(const GAPersistentState
*pstate
,
821 GKeyFile
*keyfile
= g_key_file_new();
829 persistent_state_to_keyfile(pstate
, keyfile
);
830 data
= g_key_file_to_data(keyfile
, &data_len
, &gerr
);
832 g_critical("failed to convert persistent state to string: %s",
838 g_file_set_contents(path
, data
, data_len
, &gerr
);
840 g_critical("failed to write persistent state to %s: %s",
841 path
, gerr
->message
);
851 g_key_file_free(keyfile
);
857 static gboolean
read_persistent_state(GAPersistentState
*pstate
,
858 const gchar
*path
, gboolean frozen
)
860 GKeyFile
*keyfile
= NULL
;
867 if (stat(path
, &st
) == -1) {
868 /* it's okay if state file doesn't exist, but any other error
869 * indicates a permissions issue or some other misconfiguration
870 * that we likely won't be able to recover from.
872 if (errno
!= ENOENT
) {
873 g_critical("unable to access state file at path %s: %s",
874 path
, strerror(errno
));
879 /* file doesn't exist. initialize state to default values and
880 * attempt to save now. (we could wait till later when we have
881 * modified state we need to commit, but if there's a problem,
882 * such as a missing parent directory, we want to catch it now)
884 * there is a potential scenario where someone either managed to
885 * update the agent from a version that didn't use a key store
886 * while qemu-ga thought the filesystem was frozen, or
887 * deleted the key store prior to issuing a fsfreeze, prior
888 * to restarting the agent. in this case we go ahead and defer
889 * initial creation till we actually have modified state to
890 * write, otherwise fail to recover from freeze.
892 set_persistent_state_defaults(pstate
);
894 ret
= write_persistent_state(pstate
, path
);
896 g_critical("unable to create state file at path %s", path
);
905 keyfile
= g_key_file_new();
906 g_key_file_load_from_file(keyfile
, path
, 0, &gerr
);
908 g_critical("error loading persistent state from path: %s, %s",
909 path
, gerr
->message
);
914 persistent_state_from_keyfile(pstate
, keyfile
);
918 g_key_file_free(keyfile
);
927 int64_t ga_get_fd_handle(GAState
*s
, Error
**errp
)
931 g_assert(s
->pstate_filepath
);
933 * We block commands and avoid operations that potentially require
934 * writing to disk when we're in a frozen state. this includes opening
935 * new files, so we should never get here in that situation
937 g_assert(!ga_is_frozen(s
));
939 handle
= s
->pstate
.fd_counter
++;
941 /* This should never happen on a reasonable timeframe, as guest-file-open
942 * would have to be issued 2^63 times */
943 if (s
->pstate
.fd_counter
== INT64_MAX
) {
947 if (!write_persistent_state(&s
->pstate
, s
->pstate_filepath
)) {
948 error_setg(errp
, "failed to commit persistent state to disk");
955 static void ga_print_cmd(const QmpCommand
*cmd
, void *opaque
)
957 printf("%s\n", qmp_command_name(cmd
));
960 static GList
*split_list(const gchar
*str
, const gchar
*delim
)
966 strv
= g_strsplit(str
, delim
, -1);
967 for (i
= 0; strv
[i
]; i
++) {
968 list
= g_list_prepend(list
, strv
[i
]);
980 #ifdef CONFIG_FSFREEZE
987 gchar
*bliststr
; /* blockedrpcs may point to this string */
990 GLogLevelFlags log_level
;
995 static void config_load(GAConfig
*config
)
999 g_autofree
char *conf
= g_strdup(g_getenv("QGA_CONF")) ?: get_relocated_path(QGA_CONF_DEFAULT
);
1000 const gchar
*blockrpcs_key
= "block-rpcs";
1002 /* read system config */
1003 keyfile
= g_key_file_new();
1004 if (!g_key_file_load_from_file(keyfile
, conf
, 0, &gerr
)) {
1007 if (g_key_file_has_key(keyfile
, "general", "daemon", NULL
)) {
1009 g_key_file_get_boolean(keyfile
, "general", "daemon", &gerr
);
1011 if (g_key_file_has_key(keyfile
, "general", "method", NULL
)) {
1013 g_key_file_get_string(keyfile
, "general", "method", &gerr
);
1015 if (g_key_file_has_key(keyfile
, "general", "path", NULL
)) {
1016 config
->channel_path
=
1017 g_key_file_get_string(keyfile
, "general", "path", &gerr
);
1019 if (g_key_file_has_key(keyfile
, "general", "logfile", NULL
)) {
1020 config
->log_filepath
=
1021 g_key_file_get_string(keyfile
, "general", "logfile", &gerr
);
1023 if (g_key_file_has_key(keyfile
, "general", "pidfile", NULL
)) {
1024 config
->pid_filepath
=
1025 g_key_file_get_string(keyfile
, "general", "pidfile", &gerr
);
1027 #ifdef CONFIG_FSFREEZE
1028 if (g_key_file_has_key(keyfile
, "general", "fsfreeze-hook", NULL
)) {
1029 config
->fsfreeze_hook
=
1030 g_key_file_get_string(keyfile
,
1031 "general", "fsfreeze-hook", &gerr
);
1034 if (g_key_file_has_key(keyfile
, "general", "statedir", NULL
)) {
1036 g_key_file_get_string(keyfile
, "general", "statedir", &gerr
);
1038 if (g_key_file_has_key(keyfile
, "general", "verbose", NULL
) &&
1039 g_key_file_get_boolean(keyfile
, "general", "verbose", &gerr
)) {
1040 /* enable all log levels */
1041 config
->log_level
= G_LOG_LEVEL_MASK
;
1043 if (g_key_file_has_key(keyfile
, "general", "retry-path", NULL
)) {
1044 config
->retry_path
=
1045 g_key_file_get_boolean(keyfile
, "general", "retry-path", &gerr
);
1048 if (g_key_file_has_key(keyfile
, "general", "blacklist", NULL
)) {
1049 g_warning("config using deprecated 'blacklist' key, should be replaced"
1050 " with the 'block-rpcs' key.");
1051 blockrpcs_key
= "blacklist";
1053 if (g_key_file_has_key(keyfile
, "general", blockrpcs_key
, NULL
)) {
1055 g_key_file_get_string(keyfile
, "general", blockrpcs_key
, &gerr
);
1056 config
->blockedrpcs
= g_list_concat(config
->blockedrpcs
,
1057 split_list(config
->bliststr
, ","));
1061 g_key_file_free(keyfile
);
1063 !(gerr
->domain
== G_FILE_ERROR
&& gerr
->code
== G_FILE_ERROR_NOENT
)) {
1064 g_critical("error loading configuration from path: %s, %s",
1065 conf
, gerr
->message
);
1068 g_clear_error(&gerr
);
1071 static gchar
*list_join(GList
*list
, const gchar separator
)
1073 GString
*str
= g_string_new("");
1076 str
= g_string_append(str
, (gchar
*)list
->data
);
1077 list
= g_list_next(list
);
1079 str
= g_string_append_c(str
, separator
);
1083 return g_string_free(str
, FALSE
);
1086 static void config_dump(GAConfig
*config
)
1088 GError
*error
= NULL
;
1092 keyfile
= g_key_file_new();
1095 g_key_file_set_boolean(keyfile
, "general", "daemon", config
->daemonize
);
1096 g_key_file_set_string(keyfile
, "general", "method", config
->method
);
1097 if (config
->channel_path
) {
1098 g_key_file_set_string(keyfile
, "general", "path", config
->channel_path
);
1100 if (config
->log_filepath
) {
1101 g_key_file_set_string(keyfile
, "general", "logfile",
1102 config
->log_filepath
);
1104 g_key_file_set_string(keyfile
, "general", "pidfile", config
->pid_filepath
);
1105 #ifdef CONFIG_FSFREEZE
1106 if (config
->fsfreeze_hook
) {
1107 g_key_file_set_string(keyfile
, "general", "fsfreeze-hook",
1108 config
->fsfreeze_hook
);
1111 g_key_file_set_string(keyfile
, "general", "statedir", config
->state_dir
);
1112 g_key_file_set_boolean(keyfile
, "general", "verbose",
1113 config
->log_level
== G_LOG_LEVEL_MASK
);
1114 g_key_file_set_boolean(keyfile
, "general", "retry-path",
1115 config
->retry_path
);
1116 tmp
= list_join(config
->blockedrpcs
, ',');
1117 g_key_file_set_string(keyfile
, "general", "block-rpcs", tmp
);
1120 tmp
= g_key_file_to_data(keyfile
, NULL
, &error
);
1122 g_critical("Failed to dump keyfile: %s", error
->message
);
1123 g_clear_error(&error
);
1129 g_key_file_free(keyfile
);
1132 static void config_parse(GAConfig
*config
, int argc
, char **argv
)
1134 const char *sopt
= "hVvdm:p:l:f:F::b:s:t:Dr";
1135 int opt_ind
= 0, ch
;
1136 const struct option lopt
[] = {
1137 { "help", 0, NULL
, 'h' },
1138 { "version", 0, NULL
, 'V' },
1139 { "dump-conf", 0, NULL
, 'D' },
1140 { "logfile", 1, NULL
, 'l' },
1141 { "pidfile", 1, NULL
, 'f' },
1142 #ifdef CONFIG_FSFREEZE
1143 { "fsfreeze-hook", 2, NULL
, 'F' },
1145 { "verbose", 0, NULL
, 'v' },
1146 { "method", 1, NULL
, 'm' },
1147 { "path", 1, NULL
, 'p' },
1148 { "daemonize", 0, NULL
, 'd' },
1149 { "block-rpcs", 1, NULL
, 'b' },
1150 { "blacklist", 1, NULL
, 'b' }, /* deprecated alias for 'block-rpcs' */
1152 { "service", 1, NULL
, 's' },
1154 { "statedir", 1, NULL
, 't' },
1155 { "retry-path", 0, NULL
, 'r' },
1156 { NULL
, 0, NULL
, 0 }
1159 while ((ch
= getopt_long(argc
, argv
, sopt
, lopt
, &opt_ind
)) != -1) {
1162 g_free(config
->method
);
1163 config
->method
= g_strdup(optarg
);
1166 g_free(config
->channel_path
);
1167 config
->channel_path
= g_strdup(optarg
);
1170 g_free(config
->log_filepath
);
1171 config
->log_filepath
= g_strdup(optarg
);
1174 g_free(config
->pid_filepath
);
1175 config
->pid_filepath
= g_strdup(optarg
);
1177 #ifdef CONFIG_FSFREEZE
1179 g_free(config
->fsfreeze_hook
);
1180 config
->fsfreeze_hook
= optarg
? g_strdup(optarg
) : get_relocated_path(QGA_FSFREEZE_HOOK_DEFAULT
);
1184 g_free(config
->state_dir
);
1185 config
->state_dir
= g_strdup(optarg
);
1188 /* enable all log levels */
1189 config
->log_level
= G_LOG_LEVEL_MASK
;
1192 printf("QEMU Guest Agent %s\n", QEMU_VERSION
);
1195 config
->daemonize
= 1;
1198 config
->dumpconf
= 1;
1201 config
->retry_path
= true;
1204 if (is_help_option(optarg
)) {
1205 qmp_for_each_command(&ga_commands
, ga_print_cmd
, NULL
);
1208 config
->blockedrpcs
= g_list_concat(config
->blockedrpcs
,
1209 split_list(optarg
, ","));
1214 config
->service
= optarg
;
1215 if (strcmp(config
->service
, "install") == 0) {
1216 if (ga_install_vss_provider()) {
1219 if (ga_install_service(config
->channel_path
,
1220 config
->log_filepath
, config
->state_dir
)) {
1224 } else if (strcmp(config
->service
, "uninstall") == 0) {
1225 ga_uninstall_vss_provider();
1226 exit(ga_uninstall_service());
1227 } else if (strcmp(config
->service
, "vss-install") == 0) {
1228 if (ga_install_vss_provider()) {
1232 } else if (strcmp(config
->service
, "vss-uninstall") == 0) {
1233 ga_uninstall_vss_provider();
1236 printf("Unknown service command.\n");
1245 g_print("Unknown option, try '%s --help' for more information.\n",
1252 static void config_free(GAConfig
*config
)
1254 g_free(config
->method
);
1255 g_free(config
->log_filepath
);
1256 g_free(config
->pid_filepath
);
1257 g_free(config
->state_dir
);
1258 g_free(config
->channel_path
);
1259 g_free(config
->bliststr
);
1260 #ifdef CONFIG_FSFREEZE
1261 g_free(config
->fsfreeze_hook
);
1263 g_list_free_full(config
->blockedrpcs
, g_free
);
1267 static bool check_is_frozen(GAState
*s
)
1270 /* check if a previous instance of qemu-ga exited with filesystems' state
1271 * marked as frozen. this could be a stale value (a non-qemu-ga process
1272 * or reboot may have since unfrozen them), but better to require an
1273 * uneeded unfreeze than to risk hanging on start-up
1276 if (stat(s
->state_filepath_isfrozen
, &st
) == -1) {
1277 /* it's okay if the file doesn't exist, but if we can't access for
1278 * some other reason, such as permissions, there's a configuration
1279 * that needs to be addressed. so just bail now before we get into
1280 * more trouble later
1282 if (errno
!= ENOENT
) {
1283 g_critical("unable to access state file at path %s: %s",
1284 s
->state_filepath_isfrozen
, strerror(errno
));
1285 return EXIT_FAILURE
;
1288 g_warning("previous instance appears to have exited with frozen"
1289 " filesystems. deferring logging/pidfile creation and"
1290 " disabling non-fsfreeze-safe commands until"
1291 " guest-fsfreeze-thaw is issued, or filesystems are"
1292 " manually unfrozen and the file %s is removed",
1293 s
->state_filepath_isfrozen
);
1300 static GAState
*initialize_agent(GAConfig
*config
, int socket_activation
)
1302 GAState
*s
= g_new0(GAState
, 1);
1304 g_assert(ga_state
== NULL
);
1306 s
->log_level
= config
->log_level
;
1307 s
->log_file
= stderr
;
1308 #ifdef CONFIG_FSFREEZE
1309 s
->fsfreeze_hook
= config
->fsfreeze_hook
;
1311 s
->pstate_filepath
= g_strdup_printf("%s/qga.state", config
->state_dir
);
1312 s
->state_filepath_isfrozen
= g_strdup_printf("%s/qga.state.isfrozen",
1314 s
->frozen
= check_is_frozen(s
);
1316 g_log_set_default_handler(ga_log
, s
);
1317 g_log_set_fatal_mask(NULL
, G_LOG_LEVEL_ERROR
);
1318 ga_enable_logging(s
);
1320 g_debug("Guest agent version %s started", QEMU_FULL_VERSION
);
1323 s
->event_log
= RegisterEventSource(NULL
, "qemu-ga");
1324 if (!s
->event_log
) {
1325 g_autofree gchar
*errmsg
= g_win32_error_message(GetLastError());
1326 g_critical("unable to register event source: %s", errmsg
);
1330 /* On win32 the state directory is application specific (be it the default
1331 * or a user override). We got past the command line parsing; let's create
1332 * the directory (with any intermediate directories). If we run into an
1333 * error later on, we won't try to clean up the directory, it is considered
1336 if (g_mkdir_with_parents(config
->state_dir
, S_IRWXU
) == -1) {
1337 g_critical("unable to create (an ancestor of) the state directory"
1338 " '%s': %s", config
->state_dir
, strerror(errno
));
1343 if (ga_is_frozen(s
)) {
1344 if (config
->daemonize
) {
1345 /* delay opening/locking of pidfile till filesystems are unfrozen */
1346 s
->deferred_options
.pid_filepath
= config
->pid_filepath
;
1347 become_daemon(NULL
);
1349 if (config
->log_filepath
) {
1350 /* delay opening the log file till filesystems are unfrozen */
1351 s
->deferred_options
.log_filepath
= config
->log_filepath
;
1353 ga_disable_logging(s
);
1354 qmp_for_each_command(&ga_commands
, ga_disable_not_allowed
, NULL
);
1356 if (config
->daemonize
) {
1357 become_daemon(config
->pid_filepath
);
1359 if (config
->log_filepath
) {
1360 FILE *log_file
= ga_open_logfile(config
->log_filepath
);
1362 g_critical("unable to open specified log file: %s",
1366 s
->log_file
= log_file
;
1370 /* load persistent state from disk */
1371 if (!read_persistent_state(&s
->pstate
,
1374 g_critical("failed to load persistent state");
1378 config
->blockedrpcs
= ga_command_init_blockedrpcs(config
->blockedrpcs
);
1379 if (config
->blockedrpcs
) {
1380 GList
*l
= config
->blockedrpcs
;
1381 s
->blockedrpcs
= config
->blockedrpcs
;
1383 g_debug("disabling command: %s", (char *)l
->data
);
1384 qmp_disable_command(&ga_commands
, l
->data
, NULL
);
1388 s
->command_state
= ga_command_state_new();
1389 ga_command_state_init(s
, s
->command_state
);
1390 ga_command_state_init_all(s
->command_state
);
1391 json_message_parser_init(&s
->parser
, process_event
, s
, NULL
);
1394 if (!register_signal_handlers()) {
1395 g_critical("failed to register signal handlers");
1400 s
->main_loop
= g_main_loop_new(NULL
, false);
1403 s
->socket_activation
= socket_activation
;
1406 s
->wakeup_event
= CreateEvent(NULL
, TRUE
, FALSE
, TEXT("WakeUp"));
1407 if (s
->wakeup_event
== NULL
) {
1408 g_critical("CreateEvent failed");
1417 static void cleanup_agent(GAState
*s
)
1420 CloseHandle(s
->wakeup_event
);
1421 CloseHandle(s
->event_log
);
1423 if (s
->command_state
) {
1424 ga_command_state_cleanup_all(s
->command_state
);
1425 ga_command_state_free(s
->command_state
);
1426 json_message_parser_destroy(&s
->parser
);
1428 g_free(s
->pstate_filepath
);
1429 g_free(s
->state_filepath_isfrozen
);
1431 g_main_loop_unref(s
->main_loop
);
1437 static int run_agent_once(GAState
*s
)
1439 if (!channel_init(s
, s
->config
->method
, s
->config
->channel_path
,
1440 s
->socket_activation
? FIRST_SOCKET_ACTIVATION_FD
: -1)) {
1441 g_critical("failed to initialize guest agent channel");
1442 return EXIT_FAILURE
;
1445 g_main_loop_run(ga_state
->main_loop
);
1448 ga_channel_free(s
->channel
);
1451 return EXIT_SUCCESS
;
1454 static void wait_for_channel_availability(GAState
*s
)
1456 g_warning("waiting for channel path...");
1458 sleep(QGA_RETRY_INTERVAL
);
1462 dwWaitResult
= WaitForSingleObject(s
->wakeup_event
, INFINITE
);
1464 switch (dwWaitResult
) {
1470 g_critical("WaitForSingleObject failed");
1475 static int run_agent(GAState
*s
)
1477 int ret
= EXIT_SUCCESS
;
1479 s
->force_exit
= false;
1482 ret
= run_agent_once(s
);
1483 if (s
->config
->retry_path
&& !s
->force_exit
) {
1484 g_warning("agent stopped unexpectedly, restarting...");
1485 wait_for_channel_availability(s
);
1487 } while (s
->config
->retry_path
&& !s
->force_exit
);
1492 static void stop_agent(GAState
*s
, bool requested
)
1494 if (!s
->force_exit
) {
1495 s
->force_exit
= requested
;
1498 if (g_main_loop_is_running(s
->main_loop
)) {
1499 g_main_loop_quit(s
->main_loop
);
1503 int main(int argc
, char **argv
)
1505 int ret
= EXIT_SUCCESS
;
1507 GAConfig
*config
= g_new0(GAConfig
, 1);
1508 int socket_activation
;
1510 config
->log_level
= G_LOG_LEVEL_ERROR
| G_LOG_LEVEL_CRITICAL
;
1512 qemu_init_exec_dir(argv
[0]);
1513 qga_qmp_init_marshal(&ga_commands
);
1515 init_dfl_pathnames();
1516 config_load(config
);
1517 config_parse(config
, argc
, argv
);
1519 if (config
->pid_filepath
== NULL
) {
1520 config
->pid_filepath
= g_strdup(dfl_pathnames
.pidfile
);
1523 if (config
->state_dir
== NULL
) {
1524 config
->state_dir
= g_strdup(dfl_pathnames
.state_dir
);
1527 if (config
->method
== NULL
) {
1528 config
->method
= g_strdup("virtio-serial");
1531 socket_activation
= check_socket_activation();
1532 if (socket_activation
> 1) {
1533 g_critical("qemu-ga only supports listening on one socket");
1537 if (socket_activation
) {
1538 SocketAddress
*addr
;
1540 g_free(config
->method
);
1541 g_free(config
->channel_path
);
1542 config
->method
= NULL
;
1543 config
->channel_path
= NULL
;
1545 addr
= socket_local_address(FIRST_SOCKET_ACTIVATION_FD
, NULL
);
1547 if (addr
->type
== SOCKET_ADDRESS_TYPE_UNIX
) {
1548 config
->method
= g_strdup("unix-listen");
1549 } else if (addr
->type
== SOCKET_ADDRESS_TYPE_VSOCK
) {
1550 config
->method
= g_strdup("vsock-listen");
1553 qapi_free_SocketAddress(addr
);
1556 if (!config
->method
) {
1557 g_critical("unsupported listen fd type");
1561 } else if (config
->channel_path
== NULL
) {
1562 if (strcmp(config
->method
, "virtio-serial") == 0) {
1563 /* try the default path for the virtio-serial port */
1564 config
->channel_path
= g_strdup(QGA_VIRTIO_PATH_DEFAULT
);
1565 } else if (strcmp(config
->method
, "isa-serial") == 0) {
1566 /* try the default path for the serial port - COM1 */
1567 config
->channel_path
= g_strdup(QGA_SERIAL_PATH_DEFAULT
);
1569 g_critical("must specify a path for this channel");
1575 if (config
->dumpconf
) {
1576 config_dump(config
);
1580 s
= initialize_agent(config
, socket_activation
);
1582 g_critical("error initializing guest agent");
1587 if (config
->daemonize
) {
1588 SERVICE_TABLE_ENTRY service_table
[] = {
1589 { (char *)QGA_SERVICE_NAME
, service_main
}, { NULL
, NULL
} };
1590 StartServiceCtrlDispatcher(service_table
);
1601 if (config
->daemonize
) {
1602 unlink(config
->pid_filepath
);
1605 config_free(config
);