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"
46 JSONMessageParser parser
;
49 bool virtio
; /* fastpath to check for virtio to deal with poll() quirks */
50 GACommandState
*command_state
;
51 GLogLevelFlags log_level
;
59 static struct GAState
*ga_state
;
62 DWORD WINAPI
service_ctrl_handler(DWORD ctrl
, DWORD type
, LPVOID data
,
64 VOID WINAPI
service_main(DWORD argc
, TCHAR
*argv
[]);
67 static void quit_handler(int sig
)
69 g_debug("received signal num %d, quitting", sig
);
71 if (g_main_loop_is_running(ga_state
->main_loop
)) {
72 g_main_loop_quit(ga_state
->main_loop
);
77 /* reap _all_ terminated children */
78 static void child_handler(int sig
)
81 while (waitpid(-1, &status
, WNOHANG
) > 0) /* NOTHING */;
84 static gboolean
register_signal_handlers(void)
86 struct sigaction sigact
, sigact_chld
;
89 memset(&sigact
, 0, sizeof(struct sigaction
));
90 sigact
.sa_handler
= quit_handler
;
92 ret
= sigaction(SIGINT
, &sigact
, NULL
);
94 g_error("error configuring signal handler: %s", strerror(errno
));
97 ret
= sigaction(SIGTERM
, &sigact
, NULL
);
99 g_error("error configuring signal handler: %s", strerror(errno
));
103 memset(&sigact_chld
, 0, sizeof(struct sigaction
));
104 sigact_chld
.sa_handler
= child_handler
;
105 sigact_chld
.sa_flags
= SA_NOCLDSTOP
;
106 ret
= sigaction(SIGCHLD
, &sigact_chld
, NULL
);
108 g_error("error configuring signal handler: %s", strerror(errno
));
115 static void usage(const char *cmd
)
118 "Usage: %s -c <channel_opts>\n"
119 "QEMU Guest Agent %s\n"
121 " -m, --method transport method: one of unix-listen, virtio-serial, or\n"
122 " isa-serial (virtio-serial is the default)\n"
123 " -p, --path device/socket path (%s is the default for virtio-serial)\n"
124 " -l, --logfile set logfile path, logs to stderr by default\n"
125 " -f, --pidfile specify pidfile (default is %s)\n"
126 " -v, --verbose log extra debugging information\n"
127 " -V, --version print version information and exit\n"
128 " -d, --daemonize become a daemon\n"
130 " -s, --service service commands: install, uninstall\n"
132 " -b, --blacklist comma-separated list of RPCs to disable (no spaces, \"?\""
133 " to list available RPCs)\n"
134 " -h, --help display this help and exit\n"
136 "Report bugs to <mdroth@linux.vnet.ibm.com>\n"
137 , cmd
, QGA_VERSION
, QGA_VIRTIO_PATH_DEFAULT
, QGA_PIDFILE_DEFAULT
);
140 static const char *ga_log_level_str(GLogLevelFlags level
)
142 switch (level
& G_LOG_LEVEL_MASK
) {
143 case G_LOG_LEVEL_ERROR
:
145 case G_LOG_LEVEL_CRITICAL
:
147 case G_LOG_LEVEL_WARNING
:
149 case G_LOG_LEVEL_MESSAGE
:
151 case G_LOG_LEVEL_INFO
:
153 case G_LOG_LEVEL_DEBUG
:
160 bool ga_logging_enabled(GAState
*s
)
162 return s
->logging_enabled
;
165 void ga_disable_logging(GAState
*s
)
167 s
->logging_enabled
= false;
170 void ga_enable_logging(GAState
*s
)
172 s
->logging_enabled
= true;
175 static void ga_log(const gchar
*domain
, GLogLevelFlags level
,
176 const gchar
*msg
, gpointer opaque
)
180 const char *level_str
= ga_log_level_str(level
);
182 if (!ga_logging_enabled(s
)) {
186 level
&= G_LOG_LEVEL_MASK
;
188 if (domain
&& strcmp(domain
, "syslog") == 0) {
189 syslog(LOG_INFO
, "%s: %s", level_str
, msg
);
190 } else if (level
& s
->log_level
) {
192 if (level
& s
->log_level
) {
194 g_get_current_time(&time
);
196 "%lu.%lu: %s: %s\n", time
.tv_sec
, time
.tv_usec
, level_str
, msg
);
202 static void become_daemon(const char *pidfile
)
216 pidfd
= open(pidfile
, O_CREAT
|O_WRONLY
|O_EXCL
, S_IRUSR
|S_IWUSR
);
218 g_critical("Cannot create pid file, %s", strerror(errno
));
222 if (asprintf(&pidstr
, "%d", getpid()) == -1) {
223 g_critical("Cannot allocate memory");
226 if (write(pidfd
, pidstr
, strlen(pidstr
)) != strlen(pidstr
)) {
228 g_critical("Failed to write pid file");
237 if ((chdir("/")) < 0) {
242 close(STDOUT_FILENO
);
243 close(STDERR_FILENO
);
249 g_critical("failed to daemonize");
254 static int send_response(GAState
*s
, QObject
*payload
)
257 QString
*payload_qstr
;
260 g_assert(payload
&& s
->channel
);
262 payload_qstr
= qobject_to_json(payload
);
267 qstring_append_chr(payload_qstr
, '\n');
268 buf
= qstring_get_str(payload_qstr
);
269 status
= ga_channel_write_all(s
->channel
, buf
, strlen(buf
));
270 QDECREF(payload_qstr
);
271 if (status
!= G_IO_STATUS_NORMAL
) {
278 static void process_command(GAState
*s
, QDict
*req
)
284 g_debug("processing command");
285 rsp
= qmp_dispatch(QOBJECT(req
));
287 ret
= send_response(s
, rsp
);
289 g_warning("error sending response: %s", strerror(ret
));
293 g_warning("error getting response");
297 /* handle requests/control events coming in over the channel */
298 static void process_event(JSONMessageParser
*parser
, QList
*tokens
)
300 GAState
*s
= container_of(parser
, GAState
, parser
);
306 g_assert(s
&& parser
);
308 g_debug("process_event: called");
309 obj
= json_parser_parse_err(tokens
, NULL
, &err
);
310 if (err
|| !obj
|| qobject_type(obj
) != QTYPE_QDICT
) {
314 g_warning("failed to parse event: unknown error");
315 error_set(&err
, QERR_JSON_PARSING
);
317 g_warning("failed to parse event: %s", error_get_pretty(err
));
319 qdict_put_obj(qdict
, "error", error_get_qobject(err
));
322 qdict
= qobject_to_qdict(obj
);
327 /* handle host->guest commands */
328 if (qdict_haskey(qdict
, "execute")) {
329 process_command(s
, qdict
);
331 if (!qdict_haskey(qdict
, "error")) {
334 g_warning("unrecognized payload format");
335 error_set(&err
, QERR_UNSUPPORTED
);
336 qdict_put_obj(qdict
, "error", error_get_qobject(err
));
339 ret
= send_response(s
, QOBJECT(qdict
));
341 g_warning("error sending error response: %s", strerror(ret
));
348 /* false return signals GAChannel to close the current client connection */
349 static gboolean
channel_event_cb(GIOCondition condition
, gpointer data
)
352 gchar buf
[QGA_READ_COUNT_DEFAULT
+1];
355 GIOStatus status
= ga_channel_read(s
->channel
, buf
, QGA_READ_COUNT_DEFAULT
, &count
);
357 g_warning("error reading channel: %s", err
->message
);
362 case G_IO_STATUS_ERROR
:
363 g_warning("error reading channel");
365 case G_IO_STATUS_NORMAL
:
367 g_debug("read data, count: %d, data: %s", (int)count
, buf
);
368 json_message_parser_feed(&s
->parser
, (char *)buf
, (int)count
);
370 case G_IO_STATUS_EOF
:
371 g_debug("received EOF");
375 case G_IO_STATUS_AGAIN
:
376 /* virtio causes us to spin here when no process is attached to
377 * host-side chardev. sleep a bit to mitigate this
384 g_warning("unknown channel read status, closing");
390 static gboolean
channel_init(GAState
*s
, const gchar
*method
, const gchar
*path
)
392 GAChannelMethod channel_method
;
394 if (method
== NULL
) {
395 method
= "virtio-serial";
399 if (strcmp(method
, "virtio-serial") != 0) {
400 g_critical("must specify a path for this channel");
403 /* try the default path for the virtio-serial port */
404 path
= QGA_VIRTIO_PATH_DEFAULT
;
407 if (strcmp(method
, "virtio-serial") == 0) {
408 s
->virtio
= true; /* virtio requires special handling in some cases */
409 channel_method
= GA_CHANNEL_VIRTIO_SERIAL
;
410 } else if (strcmp(method
, "isa-serial") == 0) {
411 channel_method
= GA_CHANNEL_ISA_SERIAL
;
412 } else if (strcmp(method
, "unix-listen") == 0) {
413 channel_method
= GA_CHANNEL_UNIX_LISTEN
;
415 g_critical("unsupported channel method/type: %s", method
);
419 s
->channel
= ga_channel_new(channel_method
, path
, channel_event_cb
, s
);
421 g_critical("failed to create guest agent channel");
429 DWORD WINAPI
service_ctrl_handler(DWORD ctrl
, DWORD type
, LPVOID data
,
432 DWORD ret
= NO_ERROR
;
433 GAService
*service
= &ga_state
->service
;
437 case SERVICE_CONTROL_STOP
:
438 case SERVICE_CONTROL_SHUTDOWN
:
439 quit_handler(SIGTERM
);
440 service
->status
.dwCurrentState
= SERVICE_STOP_PENDING
;
441 SetServiceStatus(service
->status_handle
, &service
->status
);
445 ret
= ERROR_CALL_NOT_IMPLEMENTED
;
450 VOID WINAPI
service_main(DWORD argc
, TCHAR
*argv
[])
452 GAService
*service
= &ga_state
->service
;
454 service
->status_handle
= RegisterServiceCtrlHandlerEx(QGA_SERVICE_NAME
,
455 service_ctrl_handler
, NULL
);
457 if (service
->status_handle
== 0) {
458 g_critical("Failed to register extended requests function!\n");
462 service
->status
.dwServiceType
= SERVICE_WIN32
;
463 service
->status
.dwCurrentState
= SERVICE_RUNNING
;
464 service
->status
.dwControlsAccepted
= SERVICE_ACCEPT_STOP
| SERVICE_ACCEPT_SHUTDOWN
;
465 service
->status
.dwWin32ExitCode
= NO_ERROR
;
466 service
->status
.dwServiceSpecificExitCode
= NO_ERROR
;
467 service
->status
.dwCheckPoint
= 0;
468 service
->status
.dwWaitHint
= 0;
469 SetServiceStatus(service
->status_handle
, &service
->status
);
471 g_main_loop_run(ga_state
->main_loop
);
473 service
->status
.dwCurrentState
= SERVICE_STOPPED
;
474 SetServiceStatus(service
->status_handle
, &service
->status
);
478 int main(int argc
, char **argv
)
480 const char *sopt
= "hVvdm:p:l:f:b:s:";
481 const char *method
= NULL
, *path
= NULL
, *pidfile
= QGA_PIDFILE_DEFAULT
;
482 const char *log_file_name
= NULL
;
484 const char *service
= NULL
;
486 const struct option lopt
[] = {
487 { "help", 0, NULL
, 'h' },
488 { "version", 0, NULL
, 'V' },
489 { "logfile", 1, NULL
, 'l' },
490 { "pidfile", 1, NULL
, 'f' },
491 { "verbose", 0, NULL
, 'v' },
492 { "method", 1, NULL
, 'm' },
493 { "path", 1, NULL
, 'p' },
494 { "daemonize", 0, NULL
, 'd' },
495 { "blacklist", 1, NULL
, 'b' },
497 { "service", 1, NULL
, 's' },
501 int opt_ind
= 0, ch
, daemonize
= 0, i
, j
, len
;
502 GLogLevelFlags log_level
= G_LOG_LEVEL_ERROR
| G_LOG_LEVEL_CRITICAL
;
503 FILE *log_file
= stderr
;
506 module_call_init(MODULE_INIT_QAPI
);
508 while ((ch
= getopt_long(argc
, argv
, sopt
, lopt
, &opt_ind
)) != -1) {
517 log_file_name
= optarg
;
518 log_file
= fopen(log_file_name
, "a");
520 g_critical("unable to open specified log file: %s",
529 /* enable all log levels */
530 log_level
= G_LOG_LEVEL_MASK
;
533 printf("QEMU Guest Agent %s\n", QGA_VERSION
);
539 char **list_head
, **list
;
540 if (*optarg
== '?') {
541 list_head
= list
= qmp_get_command_list();
542 while (*list
!= NULL
) {
543 printf("%s\n", *list
);
550 for (j
= 0, i
= 0, len
= strlen(optarg
); i
< len
; i
++) {
551 if (optarg
[i
] == ',') {
553 qmp_disable_command(&optarg
[j
]);
554 g_debug("disabling command: %s", &optarg
[j
]);
559 qmp_disable_command(&optarg
[j
]);
560 g_debug("disabling command: %s", &optarg
[j
]);
567 if (strcmp(service
, "install") == 0) {
568 return ga_install_service(path
, log_file_name
);
569 } else if (strcmp(service
, "uninstall") == 0) {
570 return ga_uninstall_service();
572 printf("Unknown service command.\n");
581 g_print("Unknown option, try '%s --help' for more information.\n",
589 g_debug("starting daemon");
590 become_daemon(pidfile
);
594 s
= g_malloc0(sizeof(GAState
));
595 s
->log_file
= log_file
;
596 s
->log_level
= log_level
;
597 g_log_set_default_handler(ga_log
, s
);
598 g_log_set_fatal_mask(NULL
, G_LOG_LEVEL_ERROR
);
599 s
->logging_enabled
= true;
600 s
->command_state
= ga_command_state_new();
601 ga_command_state_init(s
, s
->command_state
);
602 ga_command_state_init_all(s
->command_state
);
603 json_message_parser_init(&s
->parser
, process_event
);
606 if (!register_signal_handlers()) {
607 g_critical("failed to register signal handlers");
612 s
->main_loop
= g_main_loop_new(NULL
, false);
613 if (!channel_init(ga_state
, method
, path
)) {
614 g_critical("failed to initialize guest agent channel");
618 g_main_loop_run(ga_state
->main_loop
);
621 SERVICE_TABLE_ENTRY service_table
[] = {
622 { (char *)QGA_SERVICE_NAME
, service_main
}, { NULL
, NULL
} };
623 StartServiceCtrlDispatcher(service_table
);
625 g_main_loop_run(ga_state
->main_loop
);
629 ga_command_state_cleanup_all(ga_state
->command_state
);
630 ga_channel_free(ga_state
->channel
);