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.
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"
30 #include "qapi/qmp/qerror.h"
31 #include "qapi/qmp/dispatch.h"
32 #include "qga/channel.h"
34 #include "qga/service-win32.h"
40 #define CONFIG_FSFREEZE
45 #define QGA_VIRTIO_PATH_DEFAULT "/dev/virtio-ports/org.qemu.guest_agent.0"
47 #define QGA_VIRTIO_PATH_DEFAULT "\\\\.\\Global\\org.qemu.guest_agent.0"
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"
54 #define QGA_SENTINEL_BYTE 0xFF
57 JSONMessageParser parser
;
60 bool virtio
; /* fastpath to check for virtio to deal with poll() quirks */
61 GACommandState
*command_state
;
62 GLogLevelFlags log_level
;
68 bool delimit_response
;
71 const char *state_filepath_isfrozen
;
73 const char *log_filepath
;
74 const char *pid_filepath
;
76 #ifdef CONFIG_FSFREEZE
77 const char *fsfreeze_hook
;
81 struct GAState
*ga_state
;
83 /* commands that are safe to issue while filesystems are frozen */
84 static const char *ga_freeze_whitelist
[] = {
88 "guest-fsfreeze-status",
89 "guest-fsfreeze-thaw",
94 DWORD WINAPI
service_ctrl_handler(DWORD ctrl
, DWORD type
, LPVOID data
,
96 VOID WINAPI
service_main(DWORD argc
, TCHAR
*argv
[]);
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
)) {
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
);
118 static gboolean
register_signal_handlers(void)
120 struct sigaction sigact
;
123 memset(&sigact
, 0, sizeof(struct sigaction
));
124 sigact
.sa_handler
= quit_handler
;
126 ret
= sigaction(SIGINT
, &sigact
, NULL
);
128 g_error("error configuring signal handler: %s", strerror(errno
));
130 ret
= sigaction(SIGTERM
, &sigact
, NULL
);
132 g_error("error configuring signal handler: %s", strerror(errno
));
138 /* TODO: use this in place of all post-fork() fclose(std*) callers */
139 void reopen_fd_to_null(int fd
)
143 nullfd
= open("/dev/null", O_RDWR
);
156 static void usage(const char *cmd
)
159 "Usage: %s [-m <method> -p <path>] [<options>]\n"
160 "QEMU Guest Agent %s\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"
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"
174 " If using -F with an argument, do not follow -F with a\n"
176 " (for example: -F/var/run/fsfreezehook.sh)\n"
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"
184 " -s, --service service commands: install, uninstall\n"
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"
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
,
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
:
203 case G_LOG_LEVEL_CRITICAL
:
205 case G_LOG_LEVEL_WARNING
:
207 case G_LOG_LEVEL_MESSAGE
:
209 case G_LOG_LEVEL_INFO
:
211 case G_LOG_LEVEL_DEBUG
:
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
)
238 const char *level_str
= ga_log_level_str(level
);
240 if (!ga_logging_enabled(s
)) {
244 level
&= G_LOG_LEVEL_MASK
;
246 if (domain
&& strcmp(domain
, "syslog") == 0) {
247 syslog(LOG_INFO
, "%s: %s", level_str
, msg
);
248 } else if (level
& s
->log_level
) {
250 if (level
& s
->log_level
) {
252 g_get_current_time(&time
);
254 "%lu.%lu: %s: %s\n", time
.tv_sec
, time
.tv_usec
, level_str
, msg
);
259 void ga_set_response_delimited(GAState
*s
)
261 s
->delimit_response
= true;
264 static FILE *ga_open_logfile(const char *logfile
)
268 f
= fopen(logfile
, "a");
273 qemu_set_cloexec(fileno(f
));
278 static bool ga_open_pidfile(const char *pidfile
)
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
));
292 if (ftruncate(pidfd
, 0)) {
293 g_critical("Failed to truncate pid file");
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");
302 /* keep pidfile open & locked forever */
311 static bool ga_open_pidfile(const char *pidfile
)
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
;
329 list_head
= list
= qmp_get_command_list();
330 while (*list
!= NULL
) {
333 while (ga_freeze_whitelist
[i
] != NULL
) {
334 if (strcmp(*list
, ga_freeze_whitelist
[i
]) == 0) {
340 g_debug("disabling command: %s", *list
);
341 qmp_disable_command(*list
);
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
);
367 static bool ga_create_file(const char *path
)
369 int fd
= open(path
, O_CREAT
| O_WRONLY
, S_IWUSR
| S_IRUSR
);
371 g_warning("unable to open/create file %s: %s", path
, strerror(errno
));
378 static bool ga_delete_file(const char *path
)
380 int ret
= unlink(path
);
382 g_warning("unable to delete file: %s: %s", path
, strerror(errno
));
389 bool ga_is_frozen(GAState
*s
)
394 void ga_set_frozen(GAState
*s
)
396 if (ga_is_frozen(s
)) {
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
);
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
)) {
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
);
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
);
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
;
451 static void become_daemon(const char *pidfile
)
465 if (!ga_open_pidfile(pidfile
)) {
466 g_critical("failed to create pidfile");
476 if ((chdir("/")) < 0) {
480 reopen_fd_to_null(STDIN_FILENO
);
481 reopen_fd_to_null(STDOUT_FILENO
);
482 reopen_fd_to_null(STDERR_FILENO
);
489 g_critical("failed to daemonize");
494 static int send_response(GAState
*s
, QObject
*payload
)
497 QString
*payload_qstr
, *response_qstr
;
500 g_assert(payload
&& s
->channel
);
502 payload_qstr
= qobject_to_json(payload
);
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
);
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
) {
528 static void process_command(GAState
*s
, QDict
*req
)
534 g_debug("processing command");
535 rsp
= qmp_dispatch(QOBJECT(req
));
537 ret
= send_response(s
, rsp
);
539 g_warning("error sending response: %s", strerror(ret
));
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
);
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
) {
562 g_warning("failed to parse event: unknown error");
563 error_set(&err
, QERR_JSON_PARSING
);
565 g_warning("failed to parse event: %s", error_get_pretty(err
));
567 qdict_put_obj(qdict
, "error", qmp_build_error_object(err
));
570 qdict
= qobject_to_qdict(obj
);
575 /* handle host->guest commands */
576 if (qdict_haskey(qdict
, "execute")) {
577 process_command(s
, qdict
);
579 if (!qdict_haskey(qdict
, "error")) {
582 g_warning("unrecognized payload format");
583 error_set(&err
, QERR_UNSUPPORTED
);
584 qdict_put_obj(qdict
, "error", qmp_build_error_object(err
));
587 ret
= send_response(s
, QOBJECT(qdict
));
589 g_warning("error sending error response: %s", strerror(ret
));
596 /* false return signals GAChannel to close the current client connection */
597 static gboolean
channel_event_cb(GIOCondition condition
, gpointer data
)
600 gchar buf
[QGA_READ_COUNT_DEFAULT
+1];
603 GIOStatus status
= ga_channel_read(s
->channel
, buf
, QGA_READ_COUNT_DEFAULT
, &count
);
605 g_warning("error reading channel: %s", err
->message
);
610 case G_IO_STATUS_ERROR
:
611 g_warning("error reading channel");
613 case G_IO_STATUS_NORMAL
:
615 g_debug("read data, count: %d, data: %s", (int)count
, buf
);
616 json_message_parser_feed(&s
->parser
, (char *)buf
, (int)count
);
618 case G_IO_STATUS_EOF
:
619 g_debug("received EOF");
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
633 g_warning("unknown channel read status, closing");
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";
648 if (strcmp(method
, "virtio-serial") != 0) {
649 g_critical("must specify a path for this channel");
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
;
664 g_critical("unsupported channel method/type: %s", method
);
668 s
->channel
= ga_channel_new(channel_method
, path
, channel_event_cb
, s
);
670 g_critical("failed to create guest agent channel");
678 DWORD WINAPI
service_ctrl_handler(DWORD ctrl
, DWORD type
, LPVOID data
,
681 DWORD ret
= NO_ERROR
;
682 GAService
*service
= &ga_state
->service
;
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
);
694 ret
= ERROR_CALL_NOT_IMPLEMENTED
;
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");
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
);
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
;
736 const char *state_dir
= QGA_STATEDIR_DEFAULT
;
738 const char *service
= NULL
;
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' },
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' },
754 { "service", 1, NULL
, 's' },
756 { "statedir", 1, NULL
, 't' },
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
;
764 module_call_init(MODULE_INIT_QAPI
);
766 while ((ch
= getopt_long(argc
, argv
, sopt
, lopt
, &opt_ind
)) != -1) {
775 log_filepath
= optarg
;
778 pid_filepath
= optarg
;
780 #ifdef CONFIG_FSFREEZE
782 fsfreeze_hook
= optarg
? optarg
: QGA_FSFREEZE_HOOK_DEFAULT
;
789 /* enable all log levels */
790 log_level
= G_LOG_LEVEL_MASK
;
793 printf("QEMU Guest Agent %s\n", QEMU_VERSION
);
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
);
810 for (j
= 0, i
= 0, len
= strlen(optarg
); i
< len
; i
++) {
811 if (optarg
[i
] == ',') {
813 blacklist
= g_list_append(blacklist
, &optarg
[j
]);
818 blacklist
= g_list_append(blacklist
, &optarg
[j
]);
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();
830 printf("Unknown service command.\n");
839 g_print("Unknown option, try '%s --help' for more information.\n",
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
;
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",
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
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
870 if (errno
!= ENOENT
) {
871 g_critical("unable to access state file at path %s: %s",
872 s
->state_filepath_isfrozen
, strerror(errno
));
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
);
886 if (ga_is_frozen(s
)) {
888 /* delay opening/locking of pidfile till filesystem are unfrozen */
889 s
->deferred_options
.pid_filepath
= pid_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();
900 become_daemon(pid_filepath
);
903 FILE *log_file
= ga_open_logfile(log_filepath
);
905 g_critical("unable to open specified log file: %s",
909 s
->log_file
= log_file
;
914 s
->blacklist
= blacklist
;
916 g_debug("disabling command: %s", (char *)blacklist
->data
);
917 qmp_disable_command(blacklist
->data
);
918 blacklist
= g_list_next(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
);
927 if (!register_signal_handlers()) {
928 g_critical("failed to register signal handlers");
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");
939 g_main_loop_run(ga_state
->main_loop
);
942 SERVICE_TABLE_ENTRY service_table
[] = {
943 { (char *)QGA_SERVICE_NAME
, service_main
}, { NULL
, NULL
} };
944 StartServiceCtrlDispatcher(service_table
);
946 g_main_loop_run(ga_state
->main_loop
);
950 ga_command_state_cleanup_all(ga_state
->command_state
);
951 ga_channel_free(ga_state
->channel
);
954 unlink(pid_filepath
);
960 unlink(pid_filepath
);