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 "json-streamer.h"
24 #include "json-parser.h"
27 #include "qga/guest-agent-core.h"
31 #include "error_int.h"
32 #include "qapi/qmp-core.h"
33 #include "qga/channel.h"
35 #include "qga/service-win32.h"
40 #define QGA_VIRTIO_PATH_DEFAULT "/dev/virtio-ports/org.qemu.guest_agent.0"
42 #define QGA_VIRTIO_PATH_DEFAULT "\\\\.\\Global\\org.qemu.guest_agent.0"
44 #define QGA_PIDFILE_DEFAULT "/var/run/qemu-ga.pid"
45 #define QGA_STATEDIR_DEFAULT "/tmp"
46 #define QGA_SENTINEL_BYTE 0xFF
49 JSONMessageParser parser
;
52 bool virtio
; /* fastpath to check for virtio to deal with poll() quirks */
53 GACommandState
*command_state
;
54 GLogLevelFlags log_level
;
60 bool delimit_response
;
63 const char *state_filepath_isfrozen
;
65 const char *log_filepath
;
66 const char *pid_filepath
;
70 struct GAState
*ga_state
;
72 /* commands that are safe to issue while filesystems are frozen */
73 static const char *ga_freeze_whitelist
[] = {
77 "guest-fsfreeze-status",
78 "guest-fsfreeze-thaw",
83 DWORD WINAPI
service_ctrl_handler(DWORD ctrl
, DWORD type
, LPVOID data
,
85 VOID WINAPI
service_main(DWORD argc
, TCHAR
*argv
[]);
88 static void quit_handler(int sig
)
90 /* if we're frozen, don't exit unless we're absolutely forced to,
91 * because it's basically impossible for graceful exit to complete
92 * unless all log/pid files are on unfreezable filesystems. there's
93 * also a very likely chance killing the agent before unfreezing
94 * the filesystems is a mistake (or will be viewed as one later).
96 if (ga_is_frozen(ga_state
)) {
99 g_debug("received signal num %d, quitting", sig
);
101 if (g_main_loop_is_running(ga_state
->main_loop
)) {
102 g_main_loop_quit(ga_state
->main_loop
);
107 /* reap _all_ terminated children */
108 static void child_handler(int sig
)
111 while (waitpid(-1, &status
, WNOHANG
) > 0) /* NOTHING */;
114 static gboolean
register_signal_handlers(void)
116 struct sigaction sigact
, sigact_chld
;
119 memset(&sigact
, 0, sizeof(struct sigaction
));
120 sigact
.sa_handler
= quit_handler
;
122 ret
= sigaction(SIGINT
, &sigact
, NULL
);
124 g_error("error configuring signal handler: %s", strerror(errno
));
127 ret
= sigaction(SIGTERM
, &sigact
, NULL
);
129 g_error("error configuring signal handler: %s", strerror(errno
));
133 memset(&sigact_chld
, 0, sizeof(struct sigaction
));
134 sigact_chld
.sa_handler
= child_handler
;
135 sigact_chld
.sa_flags
= SA_NOCLDSTOP
;
136 ret
= sigaction(SIGCHLD
, &sigact_chld
, NULL
);
138 g_error("error configuring signal handler: %s", strerror(errno
));
145 static void usage(const char *cmd
)
148 "Usage: %s [-m <method> -p <path>] [<options>]\n"
149 "QEMU Guest Agent %s\n"
151 " -m, --method transport method: one of unix-listen, virtio-serial, or\n"
152 " isa-serial (virtio-serial is the default)\n"
153 " -p, --path device/socket path (the default for virtio-serial is:\n"
155 " -l, --logfile set logfile path, logs to stderr by default\n"
156 " -f, --pidfile specify pidfile (default is %s)\n"
157 " -t, --statedir specify dir to store state information (absolute paths\n"
158 " only, default is %s)\n"
159 " -v, --verbose log extra debugging information\n"
160 " -V, --version print version information and exit\n"
161 " -d, --daemonize become a daemon\n"
163 " -s, --service service commands: install, uninstall\n"
165 " -b, --blacklist comma-separated list of RPCs to disable (no spaces, \"?\"\n"
166 " to list available RPCs)\n"
167 " -h, --help display this help and exit\n"
169 "Report bugs to <mdroth@linux.vnet.ibm.com>\n"
170 , cmd
, QGA_VERSION
, QGA_VIRTIO_PATH_DEFAULT
, QGA_PIDFILE_DEFAULT
,
171 QGA_STATEDIR_DEFAULT
);
174 static const char *ga_log_level_str(GLogLevelFlags level
)
176 switch (level
& G_LOG_LEVEL_MASK
) {
177 case G_LOG_LEVEL_ERROR
:
179 case G_LOG_LEVEL_CRITICAL
:
181 case G_LOG_LEVEL_WARNING
:
183 case G_LOG_LEVEL_MESSAGE
:
185 case G_LOG_LEVEL_INFO
:
187 case G_LOG_LEVEL_DEBUG
:
194 bool ga_logging_enabled(GAState
*s
)
196 return s
->logging_enabled
;
199 void ga_disable_logging(GAState
*s
)
201 s
->logging_enabled
= false;
204 void ga_enable_logging(GAState
*s
)
206 s
->logging_enabled
= true;
209 static void ga_log(const gchar
*domain
, GLogLevelFlags level
,
210 const gchar
*msg
, gpointer opaque
)
214 const char *level_str
= ga_log_level_str(level
);
216 if (!ga_logging_enabled(s
)) {
220 level
&= G_LOG_LEVEL_MASK
;
222 if (domain
&& strcmp(domain
, "syslog") == 0) {
223 syslog(LOG_INFO
, "%s: %s", level_str
, msg
);
224 } else if (level
& s
->log_level
) {
226 if (level
& s
->log_level
) {
228 g_get_current_time(&time
);
230 "%lu.%lu: %s: %s\n", time
.tv_sec
, time
.tv_usec
, level_str
, msg
);
235 void ga_set_response_delimited(GAState
*s
)
237 s
->delimit_response
= true;
241 static bool ga_open_pidfile(const char *pidfile
)
246 pidfd
= open(pidfile
, O_CREAT
|O_WRONLY
, S_IRUSR
|S_IWUSR
);
247 if (pidfd
== -1 || lockf(pidfd
, F_TLOCK
, 0)) {
248 g_critical("Cannot lock pid file, %s", strerror(errno
));
252 if (ftruncate(pidfd
, 0) || lseek(pidfd
, 0, SEEK_SET
)) {
253 g_critical("Failed to truncate pid file");
256 sprintf(pidstr
, "%d", getpid());
257 if (write(pidfd
, pidstr
, strlen(pidstr
)) != strlen(pidstr
)) {
258 g_critical("Failed to write pid file");
269 static bool ga_open_pidfile(const char *pidfile
)
275 static gint
ga_strcmp(gconstpointer str1
, gconstpointer str2
)
277 return strcmp(str1
, str2
);
280 /* disable commands that aren't safe for fsfreeze */
281 static void ga_disable_non_whitelisted(void)
283 char **list_head
, **list
;
287 list_head
= list
= qmp_get_command_list();
288 while (*list
!= NULL
) {
291 while (ga_freeze_whitelist
[i
] != NULL
) {
292 if (strcmp(*list
, ga_freeze_whitelist
[i
]) == 0) {
298 g_debug("disabling command: %s", *list
);
299 qmp_disable_command(*list
);
307 /* [re-]enable all commands, except those explicitly blacklisted by user */
308 static void ga_enable_non_blacklisted(GList
*blacklist
)
310 char **list_head
, **list
;
312 list_head
= list
= qmp_get_command_list();
313 while (*list
!= NULL
) {
314 if (g_list_find_custom(blacklist
, *list
, ga_strcmp
) == NULL
&&
315 !qmp_command_is_enabled(*list
)) {
316 g_debug("enabling command: %s", *list
);
317 qmp_enable_command(*list
);
325 static bool ga_create_file(const char *path
)
327 int fd
= open(path
, O_CREAT
| O_WRONLY
, S_IWUSR
| S_IRUSR
);
329 g_warning("unable to open/create file %s: %s", path
, strerror(errno
));
336 static bool ga_delete_file(const char *path
)
338 int ret
= unlink(path
);
340 g_warning("unable to delete file: %s: %s", path
, strerror(errno
));
347 bool ga_is_frozen(GAState
*s
)
352 void ga_set_frozen(GAState
*s
)
354 if (ga_is_frozen(s
)) {
357 /* disable all non-whitelisted (for frozen state) commands */
358 ga_disable_non_whitelisted();
359 g_warning("disabling logging due to filesystem freeze");
360 ga_disable_logging(s
);
362 if (!ga_create_file(s
->state_filepath_isfrozen
)) {
363 g_warning("unable to create %s, fsfreeze may not function properly",
364 s
->state_filepath_isfrozen
);
368 void ga_unset_frozen(GAState
*s
)
370 if (!ga_is_frozen(s
)) {
374 /* if we delayed creation/opening of pid/log files due to being
375 * in a frozen state at start up, do it now
377 if (s
->deferred_options
.log_filepath
) {
378 s
->log_file
= fopen(s
->deferred_options
.log_filepath
, "a");
380 s
->log_file
= stderr
;
382 s
->deferred_options
.log_filepath
= NULL
;
384 ga_enable_logging(s
);
385 g_warning("logging re-enabled due to filesystem unfreeze");
386 if (s
->deferred_options
.pid_filepath
) {
387 if (!ga_open_pidfile(s
->deferred_options
.pid_filepath
)) {
388 g_warning("failed to create/open pid file");
390 s
->deferred_options
.pid_filepath
= NULL
;
393 /* enable all disabled, non-blacklisted commands */
394 ga_enable_non_blacklisted(s
->blacklist
);
396 if (!ga_delete_file(s
->state_filepath_isfrozen
)) {
397 g_warning("unable to delete %s, fsfreeze may not function properly",
398 s
->state_filepath_isfrozen
);
402 static void become_daemon(const char *pidfile
)
416 if (!ga_open_pidfile(pidfile
)) {
417 g_critical("failed to create pidfile");
427 if ((chdir("/")) < 0) {
432 close(STDOUT_FILENO
);
433 close(STDERR_FILENO
);
438 g_critical("failed to daemonize");
443 static int send_response(GAState
*s
, QObject
*payload
)
446 QString
*payload_qstr
, *response_qstr
;
449 g_assert(payload
&& s
->channel
);
451 payload_qstr
= qobject_to_json(payload
);
456 if (s
->delimit_response
) {
457 s
->delimit_response
= false;
458 response_qstr
= qstring_new();
459 qstring_append_chr(response_qstr
, QGA_SENTINEL_BYTE
);
460 qstring_append(response_qstr
, qstring_get_str(payload_qstr
));
461 QDECREF(payload_qstr
);
463 response_qstr
= payload_qstr
;
466 qstring_append_chr(response_qstr
, '\n');
467 buf
= qstring_get_str(response_qstr
);
468 status
= ga_channel_write_all(s
->channel
, buf
, strlen(buf
));
469 QDECREF(response_qstr
);
470 if (status
!= G_IO_STATUS_NORMAL
) {
477 static void process_command(GAState
*s
, QDict
*req
)
483 g_debug("processing command");
484 rsp
= qmp_dispatch(QOBJECT(req
));
486 ret
= send_response(s
, rsp
);
488 g_warning("error sending response: %s", strerror(ret
));
492 g_warning("error getting response");
496 /* handle requests/control events coming in over the channel */
497 static void process_event(JSONMessageParser
*parser
, QList
*tokens
)
499 GAState
*s
= container_of(parser
, GAState
, parser
);
505 g_assert(s
&& parser
);
507 g_debug("process_event: called");
508 obj
= json_parser_parse_err(tokens
, NULL
, &err
);
509 if (err
|| !obj
|| qobject_type(obj
) != QTYPE_QDICT
) {
513 g_warning("failed to parse event: unknown error");
514 error_set(&err
, QERR_JSON_PARSING
);
516 g_warning("failed to parse event: %s", error_get_pretty(err
));
518 qdict_put_obj(qdict
, "error", error_get_qobject(err
));
521 qdict
= qobject_to_qdict(obj
);
526 /* handle host->guest commands */
527 if (qdict_haskey(qdict
, "execute")) {
528 process_command(s
, qdict
);
530 if (!qdict_haskey(qdict
, "error")) {
533 g_warning("unrecognized payload format");
534 error_set(&err
, QERR_UNSUPPORTED
);
535 qdict_put_obj(qdict
, "error", error_get_qobject(err
));
538 ret
= send_response(s
, QOBJECT(qdict
));
540 g_warning("error sending error response: %s", strerror(ret
));
547 /* false return signals GAChannel to close the current client connection */
548 static gboolean
channel_event_cb(GIOCondition condition
, gpointer data
)
551 gchar buf
[QGA_READ_COUNT_DEFAULT
+1];
554 GIOStatus status
= ga_channel_read(s
->channel
, buf
, QGA_READ_COUNT_DEFAULT
, &count
);
556 g_warning("error reading channel: %s", err
->message
);
561 case G_IO_STATUS_ERROR
:
562 g_warning("error reading channel");
564 case G_IO_STATUS_NORMAL
:
566 g_debug("read data, count: %d, data: %s", (int)count
, buf
);
567 json_message_parser_feed(&s
->parser
, (char *)buf
, (int)count
);
569 case G_IO_STATUS_EOF
:
570 g_debug("received EOF");
574 case G_IO_STATUS_AGAIN
:
575 /* virtio causes us to spin here when no process is attached to
576 * host-side chardev. sleep a bit to mitigate this
583 g_warning("unknown channel read status, closing");
589 static gboolean
channel_init(GAState
*s
, const gchar
*method
, const gchar
*path
)
591 GAChannelMethod channel_method
;
593 if (method
== NULL
) {
594 method
= "virtio-serial";
598 if (strcmp(method
, "virtio-serial") != 0) {
599 g_critical("must specify a path for this channel");
602 /* try the default path for the virtio-serial port */
603 path
= QGA_VIRTIO_PATH_DEFAULT
;
606 if (strcmp(method
, "virtio-serial") == 0) {
607 s
->virtio
= true; /* virtio requires special handling in some cases */
608 channel_method
= GA_CHANNEL_VIRTIO_SERIAL
;
609 } else if (strcmp(method
, "isa-serial") == 0) {
610 channel_method
= GA_CHANNEL_ISA_SERIAL
;
611 } else if (strcmp(method
, "unix-listen") == 0) {
612 channel_method
= GA_CHANNEL_UNIX_LISTEN
;
614 g_critical("unsupported channel method/type: %s", method
);
618 s
->channel
= ga_channel_new(channel_method
, path
, channel_event_cb
, s
);
620 g_critical("failed to create guest agent channel");
628 DWORD WINAPI
service_ctrl_handler(DWORD ctrl
, DWORD type
, LPVOID data
,
631 DWORD ret
= NO_ERROR
;
632 GAService
*service
= &ga_state
->service
;
636 case SERVICE_CONTROL_STOP
:
637 case SERVICE_CONTROL_SHUTDOWN
:
638 quit_handler(SIGTERM
);
639 service
->status
.dwCurrentState
= SERVICE_STOP_PENDING
;
640 SetServiceStatus(service
->status_handle
, &service
->status
);
644 ret
= ERROR_CALL_NOT_IMPLEMENTED
;
649 VOID WINAPI
service_main(DWORD argc
, TCHAR
*argv
[])
651 GAService
*service
= &ga_state
->service
;
653 service
->status_handle
= RegisterServiceCtrlHandlerEx(QGA_SERVICE_NAME
,
654 service_ctrl_handler
, NULL
);
656 if (service
->status_handle
== 0) {
657 g_critical("Failed to register extended requests function!\n");
661 service
->status
.dwServiceType
= SERVICE_WIN32
;
662 service
->status
.dwCurrentState
= SERVICE_RUNNING
;
663 service
->status
.dwControlsAccepted
= SERVICE_ACCEPT_STOP
| SERVICE_ACCEPT_SHUTDOWN
;
664 service
->status
.dwWin32ExitCode
= NO_ERROR
;
665 service
->status
.dwServiceSpecificExitCode
= NO_ERROR
;
666 service
->status
.dwCheckPoint
= 0;
667 service
->status
.dwWaitHint
= 0;
668 SetServiceStatus(service
->status_handle
, &service
->status
);
670 g_main_loop_run(ga_state
->main_loop
);
672 service
->status
.dwCurrentState
= SERVICE_STOPPED
;
673 SetServiceStatus(service
->status_handle
, &service
->status
);
677 int main(int argc
, char **argv
)
679 const char *sopt
= "hVvdm:p:l:f:b:s:t:";
680 const char *method
= NULL
, *path
= NULL
;
681 const char *log_filepath
= NULL
;
682 const char *pid_filepath
= QGA_PIDFILE_DEFAULT
;
683 const char *state_dir
= QGA_STATEDIR_DEFAULT
;
685 const char *service
= NULL
;
687 const struct option lopt
[] = {
688 { "help", 0, NULL
, 'h' },
689 { "version", 0, NULL
, 'V' },
690 { "logfile", 1, NULL
, 'l' },
691 { "pidfile", 1, NULL
, 'f' },
692 { "verbose", 0, NULL
, 'v' },
693 { "method", 1, NULL
, 'm' },
694 { "path", 1, NULL
, 'p' },
695 { "daemonize", 0, NULL
, 'd' },
696 { "blacklist", 1, NULL
, 'b' },
698 { "service", 1, NULL
, 's' },
700 { "statedir", 1, NULL
, 't' },
703 int opt_ind
= 0, ch
, daemonize
= 0, i
, j
, len
;
704 GLogLevelFlags log_level
= G_LOG_LEVEL_ERROR
| G_LOG_LEVEL_CRITICAL
;
705 GList
*blacklist
= NULL
;
708 module_call_init(MODULE_INIT_QAPI
);
710 while ((ch
= getopt_long(argc
, argv
, sopt
, lopt
, &opt_ind
)) != -1) {
719 log_filepath
= optarg
;
722 pid_filepath
= optarg
;
728 /* enable all log levels */
729 log_level
= G_LOG_LEVEL_MASK
;
732 printf("QEMU Guest Agent %s\n", QGA_VERSION
);
738 char **list_head
, **list
;
739 if (*optarg
== '?') {
740 list_head
= list
= qmp_get_command_list();
741 while (*list
!= NULL
) {
742 printf("%s\n", *list
);
749 for (j
= 0, i
= 0, len
= strlen(optarg
); i
< len
; i
++) {
750 if (optarg
[i
] == ',') {
752 blacklist
= g_list_append(blacklist
, &optarg
[j
]);
757 blacklist
= g_list_append(blacklist
, &optarg
[j
]);
764 if (strcmp(service
, "install") == 0) {
765 return ga_install_service(path
, log_filepath
);
766 } else if (strcmp(service
, "uninstall") == 0) {
767 return ga_uninstall_service();
769 printf("Unknown service command.\n");
778 g_print("Unknown option, try '%s --help' for more information.\n",
784 s
= g_malloc0(sizeof(GAState
));
785 s
->log_level
= log_level
;
786 s
->log_file
= stderr
;
787 g_log_set_default_handler(ga_log
, s
);
788 g_log_set_fatal_mask(NULL
, G_LOG_LEVEL_ERROR
);
789 ga_enable_logging(s
);
790 s
->state_filepath_isfrozen
= g_strdup_printf("%s/qga.state.isfrozen",
794 /* check if a previous instance of qemu-ga exited with filesystems' state
795 * marked as frozen. this could be a stale value (a non-qemu-ga process
796 * or reboot may have since unfrozen them), but better to require an
797 * uneeded unfreeze than to risk hanging on start-up
800 if (stat(s
->state_filepath_isfrozen
, &st
) == -1) {
801 /* it's okay if the file doesn't exist, but if we can't access for
802 * some other reason, such as permissions, there's a configuration
803 * that needs to be addressed. so just bail now before we get into
806 if (errno
!= ENOENT
) {
807 g_critical("unable to access state file at path %s: %s",
808 s
->state_filepath_isfrozen
, strerror(errno
));
812 g_warning("previous instance appears to have exited with frozen"
813 " filesystems. deferring logging/pidfile creation and"
814 " disabling non-fsfreeze-safe commands until"
815 " guest-fsfreeze-thaw is issued, or filesystems are"
816 " manually unfrozen and the file %s is removed",
817 s
->state_filepath_isfrozen
);
822 if (ga_is_frozen(s
)) {
824 /* delay opening/locking of pidfile till filesystem are unfrozen */
825 s
->deferred_options
.pid_filepath
= pid_filepath
;
829 /* delay opening the log file till filesystems are unfrozen */
830 s
->deferred_options
.log_filepath
= log_filepath
;
832 ga_disable_logging(s
);
833 ga_disable_non_whitelisted();
836 become_daemon(pid_filepath
);
839 s
->log_file
= fopen(log_filepath
, "a");
841 g_critical("unable to open specified log file: %s",
849 s
->blacklist
= blacklist
;
851 g_debug("disabling command: %s", (char *)blacklist
->data
);
852 qmp_disable_command(blacklist
->data
);
853 blacklist
= g_list_next(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
);
862 if (!register_signal_handlers()) {
863 g_critical("failed to register signal handlers");
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");
874 g_main_loop_run(ga_state
->main_loop
);
877 SERVICE_TABLE_ENTRY service_table
[] = {
878 { (char *)QGA_SERVICE_NAME
, service_main
}, { NULL
, NULL
} };
879 StartServiceCtrlDispatcher(service_table
);
881 g_main_loop_run(ga_state
->main_loop
);
885 ga_command_state_cleanup_all(ga_state
->command_state
);
886 ga_channel_free(ga_state
->channel
);
889 unlink(pid_filepath
);
895 unlink(pid_filepath
);