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.
22 #include "json-streamer.h"
23 #include "json-parser.h"
26 #include "qga/guest-agent-core.h"
30 #include "error_int.h"
31 #include "qapi/qmp-core.h"
32 #include "qga/channel.h"
34 #include "qga/service-win32.h"
39 #define QGA_VIRTIO_PATH_DEFAULT "/dev/virtio-ports/org.qemu.guest_agent.0"
41 #define QGA_VIRTIO_PATH_DEFAULT "\\\\.\\Global\\org.qemu.guest_agent.0"
43 #define QGA_PIDFILE_DEFAULT "/var/run/qemu-ga.pid"
44 #define QGA_SENTINEL_BYTE 0xFF
47 JSONMessageParser parser
;
50 bool virtio
; /* fastpath to check for virtio to deal with poll() quirks */
51 GACommandState
*command_state
;
52 GLogLevelFlags log_level
;
58 bool delimit_response
;
63 struct GAState
*ga_state
;
65 /* commands that are safe to issue while filesystems are frozen */
66 static const char *ga_freeze_whitelist
[] = {
70 "guest-fsfreeze-status",
71 "guest-fsfreeze-thaw",
76 DWORD WINAPI
service_ctrl_handler(DWORD ctrl
, DWORD type
, LPVOID data
,
78 VOID WINAPI
service_main(DWORD argc
, TCHAR
*argv
[]);
81 static void quit_handler(int sig
)
83 /* if we're frozen, don't exit unless we're absolutely forced to,
84 * because it's basically impossible for graceful exit to complete
85 * unless all log/pid files are on unfreezable filesystems. there's
86 * also a very likely chance killing the agent before unfreezing
87 * the filesystems is a mistake (or will be viewed as one later).
89 if (ga_is_frozen(ga_state
)) {
92 g_debug("received signal num %d, quitting", sig
);
94 if (g_main_loop_is_running(ga_state
->main_loop
)) {
95 g_main_loop_quit(ga_state
->main_loop
);
100 /* reap _all_ terminated children */
101 static void child_handler(int sig
)
104 while (waitpid(-1, &status
, WNOHANG
) > 0) /* NOTHING */;
107 static gboolean
register_signal_handlers(void)
109 struct sigaction sigact
, sigact_chld
;
112 memset(&sigact
, 0, sizeof(struct sigaction
));
113 sigact
.sa_handler
= quit_handler
;
115 ret
= sigaction(SIGINT
, &sigact
, NULL
);
117 g_error("error configuring signal handler: %s", strerror(errno
));
120 ret
= sigaction(SIGTERM
, &sigact
, NULL
);
122 g_error("error configuring signal handler: %s", strerror(errno
));
126 memset(&sigact_chld
, 0, sizeof(struct sigaction
));
127 sigact_chld
.sa_handler
= child_handler
;
128 sigact_chld
.sa_flags
= SA_NOCLDSTOP
;
129 ret
= sigaction(SIGCHLD
, &sigact_chld
, NULL
);
131 g_error("error configuring signal handler: %s", strerror(errno
));
138 static void usage(const char *cmd
)
141 "Usage: %s [-m <method> -p <path>] [<options>]\n"
142 "QEMU Guest Agent %s\n"
144 " -m, --method transport method: one of unix-listen, virtio-serial, or\n"
145 " isa-serial (virtio-serial is the default)\n"
146 " -p, --path device/socket path (the default for virtio-serial is:\n"
148 " -l, --logfile set logfile path, logs to stderr by default\n"
149 " -f, --pidfile specify pidfile (default is %s)\n"
150 " -v, --verbose log extra debugging information\n"
151 " -V, --version print version information and exit\n"
152 " -d, --daemonize become a daemon\n"
154 " -s, --service service commands: install, uninstall\n"
156 " -b, --blacklist comma-separated list of RPCs to disable (no spaces, \"?\"\n"
157 " to list available RPCs)\n"
158 " -h, --help display this help and exit\n"
160 "Report bugs to <mdroth@linux.vnet.ibm.com>\n"
161 , cmd
, QGA_VERSION
, QGA_VIRTIO_PATH_DEFAULT
, QGA_PIDFILE_DEFAULT
);
164 static const char *ga_log_level_str(GLogLevelFlags level
)
166 switch (level
& G_LOG_LEVEL_MASK
) {
167 case G_LOG_LEVEL_ERROR
:
169 case G_LOG_LEVEL_CRITICAL
:
171 case G_LOG_LEVEL_WARNING
:
173 case G_LOG_LEVEL_MESSAGE
:
175 case G_LOG_LEVEL_INFO
:
177 case G_LOG_LEVEL_DEBUG
:
184 bool ga_logging_enabled(GAState
*s
)
186 return s
->logging_enabled
;
189 void ga_disable_logging(GAState
*s
)
191 s
->logging_enabled
= false;
194 void ga_enable_logging(GAState
*s
)
196 s
->logging_enabled
= true;
199 static void ga_log(const gchar
*domain
, GLogLevelFlags level
,
200 const gchar
*msg
, gpointer opaque
)
204 const char *level_str
= ga_log_level_str(level
);
206 if (!ga_logging_enabled(s
)) {
210 level
&= G_LOG_LEVEL_MASK
;
212 if (domain
&& strcmp(domain
, "syslog") == 0) {
213 syslog(LOG_INFO
, "%s: %s", level_str
, msg
);
214 } else if (level
& s
->log_level
) {
216 if (level
& s
->log_level
) {
218 g_get_current_time(&time
);
220 "%lu.%lu: %s: %s\n", time
.tv_sec
, time
.tv_usec
, level_str
, msg
);
225 void ga_set_response_delimited(GAState
*s
)
227 s
->delimit_response
= true;
230 static gint
ga_strcmp(gconstpointer str1
, gconstpointer str2
)
232 return strcmp(str1
, str2
);
235 /* disable commands that aren't safe for fsfreeze */
236 static void ga_disable_non_whitelisted(void)
238 char **list_head
, **list
;
242 list_head
= list
= qmp_get_command_list();
243 while (*list
!= NULL
) {
246 while (ga_freeze_whitelist
[i
] != NULL
) {
247 if (strcmp(*list
, ga_freeze_whitelist
[i
]) == 0) {
253 g_debug("disabling command: %s", *list
);
254 qmp_disable_command(*list
);
262 /* [re-]enable all commands, except those explictly blacklisted by user */
263 static void ga_enable_non_blacklisted(GList
*blacklist
)
265 char **list_head
, **list
;
267 list_head
= list
= qmp_get_command_list();
268 while (*list
!= NULL
) {
269 if (g_list_find_custom(blacklist
, *list
, ga_strcmp
) == NULL
&&
270 !qmp_command_is_enabled(*list
)) {
271 g_debug("enabling command: %s", *list
);
272 qmp_enable_command(*list
);
280 bool ga_is_frozen(GAState
*s
)
285 void ga_set_frozen(GAState
*s
)
287 if (ga_is_frozen(s
)) {
290 /* disable all non-whitelisted (for frozen state) commands */
291 ga_disable_non_whitelisted();
292 g_warning("disabling logging due to filesystem freeze");
293 ga_disable_logging(s
);
297 void ga_unset_frozen(GAState
*s
)
299 if (!ga_is_frozen(s
)) {
303 ga_enable_logging(s
);
304 g_warning("logging re-enabled");
306 /* enable all disabled, non-blacklisted commands */
307 ga_enable_non_blacklisted(s
->blacklist
);
312 static void become_daemon(const char *pidfile
)
326 pidfd
= open(pidfile
, O_CREAT
|O_WRONLY
|O_EXCL
, S_IRUSR
|S_IWUSR
);
328 g_critical("Cannot create pid file, %s", strerror(errno
));
332 if (asprintf(&pidstr
, "%d", getpid()) == -1) {
333 g_critical("Cannot allocate memory");
336 if (write(pidfd
, pidstr
, strlen(pidstr
)) != strlen(pidstr
)) {
338 g_critical("Failed to write pid file");
347 if ((chdir("/")) < 0) {
352 close(STDOUT_FILENO
);
353 close(STDERR_FILENO
);
359 g_critical("failed to daemonize");
364 static int send_response(GAState
*s
, QObject
*payload
)
367 QString
*payload_qstr
, *response_qstr
;
370 g_assert(payload
&& s
->channel
);
372 payload_qstr
= qobject_to_json(payload
);
377 if (s
->delimit_response
) {
378 s
->delimit_response
= false;
379 response_qstr
= qstring_new();
380 qstring_append_chr(response_qstr
, QGA_SENTINEL_BYTE
);
381 qstring_append(response_qstr
, qstring_get_str(payload_qstr
));
382 QDECREF(payload_qstr
);
384 response_qstr
= payload_qstr
;
387 qstring_append_chr(response_qstr
, '\n');
388 buf
= qstring_get_str(response_qstr
);
389 status
= ga_channel_write_all(s
->channel
, buf
, strlen(buf
));
390 QDECREF(response_qstr
);
391 if (status
!= G_IO_STATUS_NORMAL
) {
398 static void process_command(GAState
*s
, QDict
*req
)
404 g_debug("processing command");
405 rsp
= qmp_dispatch(QOBJECT(req
));
407 ret
= send_response(s
, rsp
);
409 g_warning("error sending response: %s", strerror(ret
));
413 g_warning("error getting response");
417 /* handle requests/control events coming in over the channel */
418 static void process_event(JSONMessageParser
*parser
, QList
*tokens
)
420 GAState
*s
= container_of(parser
, GAState
, parser
);
426 g_assert(s
&& parser
);
428 g_debug("process_event: called");
429 obj
= json_parser_parse_err(tokens
, NULL
, &err
);
430 if (err
|| !obj
|| qobject_type(obj
) != QTYPE_QDICT
) {
434 g_warning("failed to parse event: unknown error");
435 error_set(&err
, QERR_JSON_PARSING
);
437 g_warning("failed to parse event: %s", error_get_pretty(err
));
439 qdict_put_obj(qdict
, "error", error_get_qobject(err
));
442 qdict
= qobject_to_qdict(obj
);
447 /* handle host->guest commands */
448 if (qdict_haskey(qdict
, "execute")) {
449 process_command(s
, qdict
);
451 if (!qdict_haskey(qdict
, "error")) {
454 g_warning("unrecognized payload format");
455 error_set(&err
, QERR_UNSUPPORTED
);
456 qdict_put_obj(qdict
, "error", error_get_qobject(err
));
459 ret
= send_response(s
, QOBJECT(qdict
));
461 g_warning("error sending error response: %s", strerror(ret
));
468 /* false return signals GAChannel to close the current client connection */
469 static gboolean
channel_event_cb(GIOCondition condition
, gpointer data
)
472 gchar buf
[QGA_READ_COUNT_DEFAULT
+1];
475 GIOStatus status
= ga_channel_read(s
->channel
, buf
, QGA_READ_COUNT_DEFAULT
, &count
);
477 g_warning("error reading channel: %s", err
->message
);
482 case G_IO_STATUS_ERROR
:
483 g_warning("error reading channel");
485 case G_IO_STATUS_NORMAL
:
487 g_debug("read data, count: %d, data: %s", (int)count
, buf
);
488 json_message_parser_feed(&s
->parser
, (char *)buf
, (int)count
);
490 case G_IO_STATUS_EOF
:
491 g_debug("received EOF");
495 case G_IO_STATUS_AGAIN
:
496 /* virtio causes us to spin here when no process is attached to
497 * host-side chardev. sleep a bit to mitigate this
504 g_warning("unknown channel read status, closing");
510 static gboolean
channel_init(GAState
*s
, const gchar
*method
, const gchar
*path
)
512 GAChannelMethod channel_method
;
514 if (method
== NULL
) {
515 method
= "virtio-serial";
519 if (strcmp(method
, "virtio-serial") != 0) {
520 g_critical("must specify a path for this channel");
523 /* try the default path for the virtio-serial port */
524 path
= QGA_VIRTIO_PATH_DEFAULT
;
527 if (strcmp(method
, "virtio-serial") == 0) {
528 s
->virtio
= true; /* virtio requires special handling in some cases */
529 channel_method
= GA_CHANNEL_VIRTIO_SERIAL
;
530 } else if (strcmp(method
, "isa-serial") == 0) {
531 channel_method
= GA_CHANNEL_ISA_SERIAL
;
532 } else if (strcmp(method
, "unix-listen") == 0) {
533 channel_method
= GA_CHANNEL_UNIX_LISTEN
;
535 g_critical("unsupported channel method/type: %s", method
);
539 s
->channel
= ga_channel_new(channel_method
, path
, channel_event_cb
, s
);
541 g_critical("failed to create guest agent channel");
549 DWORD WINAPI
service_ctrl_handler(DWORD ctrl
, DWORD type
, LPVOID data
,
552 DWORD ret
= NO_ERROR
;
553 GAService
*service
= &ga_state
->service
;
557 case SERVICE_CONTROL_STOP
:
558 case SERVICE_CONTROL_SHUTDOWN
:
559 quit_handler(SIGTERM
);
560 service
->status
.dwCurrentState
= SERVICE_STOP_PENDING
;
561 SetServiceStatus(service
->status_handle
, &service
->status
);
565 ret
= ERROR_CALL_NOT_IMPLEMENTED
;
570 VOID WINAPI
service_main(DWORD argc
, TCHAR
*argv
[])
572 GAService
*service
= &ga_state
->service
;
574 service
->status_handle
= RegisterServiceCtrlHandlerEx(QGA_SERVICE_NAME
,
575 service_ctrl_handler
, NULL
);
577 if (service
->status_handle
== 0) {
578 g_critical("Failed to register extended requests function!\n");
582 service
->status
.dwServiceType
= SERVICE_WIN32
;
583 service
->status
.dwCurrentState
= SERVICE_RUNNING
;
584 service
->status
.dwControlsAccepted
= SERVICE_ACCEPT_STOP
| SERVICE_ACCEPT_SHUTDOWN
;
585 service
->status
.dwWin32ExitCode
= NO_ERROR
;
586 service
->status
.dwServiceSpecificExitCode
= NO_ERROR
;
587 service
->status
.dwCheckPoint
= 0;
588 service
->status
.dwWaitHint
= 0;
589 SetServiceStatus(service
->status_handle
, &service
->status
);
591 g_main_loop_run(ga_state
->main_loop
);
593 service
->status
.dwCurrentState
= SERVICE_STOPPED
;
594 SetServiceStatus(service
->status_handle
, &service
->status
);
598 int main(int argc
, char **argv
)
600 const char *sopt
= "hVvdm:p:l:f:b:s:";
601 const char *method
= NULL
, *path
= NULL
, *pidfile
= QGA_PIDFILE_DEFAULT
;
602 const char *log_file_name
= NULL
;
604 const char *service
= NULL
;
606 const struct option lopt
[] = {
607 { "help", 0, NULL
, 'h' },
608 { "version", 0, NULL
, 'V' },
609 { "logfile", 1, NULL
, 'l' },
610 { "pidfile", 1, NULL
, 'f' },
611 { "verbose", 0, NULL
, 'v' },
612 { "method", 1, NULL
, 'm' },
613 { "path", 1, NULL
, 'p' },
614 { "daemonize", 0, NULL
, 'd' },
615 { "blacklist", 1, NULL
, 'b' },
617 { "service", 1, NULL
, 's' },
621 int opt_ind
= 0, ch
, daemonize
= 0, i
, j
, len
;
622 GLogLevelFlags log_level
= G_LOG_LEVEL_ERROR
| G_LOG_LEVEL_CRITICAL
;
623 FILE *log_file
= stderr
;
624 GList
*blacklist
= NULL
;
627 module_call_init(MODULE_INIT_QAPI
);
629 while ((ch
= getopt_long(argc
, argv
, sopt
, lopt
, &opt_ind
)) != -1) {
638 log_file_name
= optarg
;
639 log_file
= fopen(log_file_name
, "a");
641 g_critical("unable to open specified log file: %s",
650 /* enable all log levels */
651 log_level
= G_LOG_LEVEL_MASK
;
654 printf("QEMU Guest Agent %s\n", QGA_VERSION
);
660 char **list_head
, **list
;
661 if (*optarg
== '?') {
662 list_head
= list
= qmp_get_command_list();
663 while (*list
!= NULL
) {
664 printf("%s\n", *list
);
671 for (j
= 0, i
= 0, len
= strlen(optarg
); i
< len
; i
++) {
672 if (optarg
[i
] == ',') {
674 blacklist
= g_list_append(blacklist
, &optarg
[j
]);
679 blacklist
= g_list_append(blacklist
, &optarg
[j
]);
686 if (strcmp(service
, "install") == 0) {
687 return ga_install_service(path
, log_file_name
);
688 } else if (strcmp(service
, "uninstall") == 0) {
689 return ga_uninstall_service();
691 printf("Unknown service command.\n");
700 g_print("Unknown option, try '%s --help' for more information.\n",
708 g_debug("starting daemon");
709 become_daemon(pidfile
);
713 s
= g_malloc0(sizeof(GAState
));
714 s
->log_file
= log_file
;
715 s
->log_level
= log_level
;
716 g_log_set_default_handler(ga_log
, s
);
717 g_log_set_fatal_mask(NULL
, G_LOG_LEVEL_ERROR
);
718 s
->logging_enabled
= true;
721 s
->blacklist
= blacklist
;
723 g_debug("disabling command: %s", (char *)blacklist
->data
);
724 qmp_disable_command(blacklist
->data
);
725 blacklist
= g_list_next(blacklist
);
728 s
->command_state
= ga_command_state_new();
729 ga_command_state_init(s
, s
->command_state
);
730 ga_command_state_init_all(s
->command_state
);
731 json_message_parser_init(&s
->parser
, process_event
);
734 if (!register_signal_handlers()) {
735 g_critical("failed to register signal handlers");
740 s
->main_loop
= g_main_loop_new(NULL
, false);
741 if (!channel_init(ga_state
, method
, path
)) {
742 g_critical("failed to initialize guest agent channel");
746 g_main_loop_run(ga_state
->main_loop
);
749 SERVICE_TABLE_ENTRY service_table
[] = {
750 { (char *)QGA_SERVICE_NAME
, service_main
}, { NULL
, NULL
} };
751 StartServiceCtrlDispatcher(service_table
);
753 g_main_loop_run(ga_state
->main_loop
);
757 ga_command_state_cleanup_all(ga_state
->command_state
);
758 ga_channel_free(ga_state
->channel
);