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
;
61 struct GAState
*ga_state
;
64 DWORD WINAPI
service_ctrl_handler(DWORD ctrl
, DWORD type
, LPVOID data
,
66 VOID WINAPI
service_main(DWORD argc
, TCHAR
*argv
[]);
69 static void quit_handler(int sig
)
71 g_debug("received signal num %d, quitting", sig
);
73 if (g_main_loop_is_running(ga_state
->main_loop
)) {
74 g_main_loop_quit(ga_state
->main_loop
);
79 /* reap _all_ terminated children */
80 static void child_handler(int sig
)
83 while (waitpid(-1, &status
, WNOHANG
) > 0) /* NOTHING */;
86 static gboolean
register_signal_handlers(void)
88 struct sigaction sigact
, sigact_chld
;
91 memset(&sigact
, 0, sizeof(struct sigaction
));
92 sigact
.sa_handler
= quit_handler
;
94 ret
= sigaction(SIGINT
, &sigact
, NULL
);
96 g_error("error configuring signal handler: %s", strerror(errno
));
99 ret
= sigaction(SIGTERM
, &sigact
, NULL
);
101 g_error("error configuring signal handler: %s", strerror(errno
));
105 memset(&sigact_chld
, 0, sizeof(struct sigaction
));
106 sigact_chld
.sa_handler
= child_handler
;
107 sigact_chld
.sa_flags
= SA_NOCLDSTOP
;
108 ret
= sigaction(SIGCHLD
, &sigact_chld
, NULL
);
110 g_error("error configuring signal handler: %s", strerror(errno
));
117 static void usage(const char *cmd
)
120 "Usage: %s -c <channel_opts>\n"
121 "QEMU Guest Agent %s\n"
123 " -m, --method transport method: one of unix-listen, virtio-serial, or\n"
124 " isa-serial (virtio-serial is the default)\n"
125 " -p, --path device/socket path (%s is the default for virtio-serial)\n"
126 " -l, --logfile set logfile path, logs to stderr by default\n"
127 " -f, --pidfile specify pidfile (default is %s)\n"
128 " -v, --verbose log extra debugging information\n"
129 " -V, --version print version information and exit\n"
130 " -d, --daemonize become a daemon\n"
132 " -s, --service service commands: install, uninstall\n"
134 " -b, --blacklist comma-separated list of RPCs to disable (no spaces, \"?\""
135 " to list available RPCs)\n"
136 " -h, --help display this help and exit\n"
138 "Report bugs to <mdroth@linux.vnet.ibm.com>\n"
139 , cmd
, QGA_VERSION
, QGA_VIRTIO_PATH_DEFAULT
, QGA_PIDFILE_DEFAULT
);
142 static const char *ga_log_level_str(GLogLevelFlags level
)
144 switch (level
& G_LOG_LEVEL_MASK
) {
145 case G_LOG_LEVEL_ERROR
:
147 case G_LOG_LEVEL_CRITICAL
:
149 case G_LOG_LEVEL_WARNING
:
151 case G_LOG_LEVEL_MESSAGE
:
153 case G_LOG_LEVEL_INFO
:
155 case G_LOG_LEVEL_DEBUG
:
162 bool ga_logging_enabled(GAState
*s
)
164 return s
->logging_enabled
;
167 void ga_disable_logging(GAState
*s
)
169 s
->logging_enabled
= false;
172 void ga_enable_logging(GAState
*s
)
174 s
->logging_enabled
= true;
177 static void ga_log(const gchar
*domain
, GLogLevelFlags level
,
178 const gchar
*msg
, gpointer opaque
)
182 const char *level_str
= ga_log_level_str(level
);
184 if (!ga_logging_enabled(s
)) {
188 level
&= G_LOG_LEVEL_MASK
;
190 if (domain
&& strcmp(domain
, "syslog") == 0) {
191 syslog(LOG_INFO
, "%s: %s", level_str
, msg
);
192 } else if (level
& s
->log_level
) {
194 if (level
& s
->log_level
) {
196 g_get_current_time(&time
);
198 "%lu.%lu: %s: %s\n", time
.tv_sec
, time
.tv_usec
, level_str
, msg
);
203 void ga_set_response_delimited(GAState
*s
)
205 s
->delimit_response
= true;
209 static void become_daemon(const char *pidfile
)
223 pidfd
= open(pidfile
, O_CREAT
|O_WRONLY
|O_EXCL
, S_IRUSR
|S_IWUSR
);
225 g_critical("Cannot create pid file, %s", strerror(errno
));
229 if (asprintf(&pidstr
, "%d", getpid()) == -1) {
230 g_critical("Cannot allocate memory");
233 if (write(pidfd
, pidstr
, strlen(pidstr
)) != strlen(pidstr
)) {
235 g_critical("Failed to write pid file");
244 if ((chdir("/")) < 0) {
249 close(STDOUT_FILENO
);
250 close(STDERR_FILENO
);
256 g_critical("failed to daemonize");
261 static int send_response(GAState
*s
, QObject
*payload
)
264 QString
*payload_qstr
, *response_qstr
;
267 g_assert(payload
&& s
->channel
);
269 payload_qstr
= qobject_to_json(payload
);
274 if (s
->delimit_response
) {
275 s
->delimit_response
= false;
276 response_qstr
= qstring_new();
277 qstring_append_chr(response_qstr
, QGA_SENTINEL_BYTE
);
278 qstring_append(response_qstr
, qstring_get_str(payload_qstr
));
279 QDECREF(payload_qstr
);
281 response_qstr
= payload_qstr
;
284 qstring_append_chr(response_qstr
, '\n');
285 buf
= qstring_get_str(response_qstr
);
286 status
= ga_channel_write_all(s
->channel
, buf
, strlen(buf
));
287 QDECREF(response_qstr
);
288 if (status
!= G_IO_STATUS_NORMAL
) {
295 static void process_command(GAState
*s
, QDict
*req
)
301 g_debug("processing command");
302 rsp
= qmp_dispatch(QOBJECT(req
));
304 ret
= send_response(s
, rsp
);
306 g_warning("error sending response: %s", strerror(ret
));
310 g_warning("error getting response");
314 /* handle requests/control events coming in over the channel */
315 static void process_event(JSONMessageParser
*parser
, QList
*tokens
)
317 GAState
*s
= container_of(parser
, GAState
, parser
);
323 g_assert(s
&& parser
);
325 g_debug("process_event: called");
326 obj
= json_parser_parse_err(tokens
, NULL
, &err
);
327 if (err
|| !obj
|| qobject_type(obj
) != QTYPE_QDICT
) {
331 g_warning("failed to parse event: unknown error");
332 error_set(&err
, QERR_JSON_PARSING
);
334 g_warning("failed to parse event: %s", error_get_pretty(err
));
336 qdict_put_obj(qdict
, "error", error_get_qobject(err
));
339 qdict
= qobject_to_qdict(obj
);
344 /* handle host->guest commands */
345 if (qdict_haskey(qdict
, "execute")) {
346 process_command(s
, qdict
);
348 if (!qdict_haskey(qdict
, "error")) {
351 g_warning("unrecognized payload format");
352 error_set(&err
, QERR_UNSUPPORTED
);
353 qdict_put_obj(qdict
, "error", error_get_qobject(err
));
356 ret
= send_response(s
, QOBJECT(qdict
));
358 g_warning("error sending error response: %s", strerror(ret
));
365 /* false return signals GAChannel to close the current client connection */
366 static gboolean
channel_event_cb(GIOCondition condition
, gpointer data
)
369 gchar buf
[QGA_READ_COUNT_DEFAULT
+1];
372 GIOStatus status
= ga_channel_read(s
->channel
, buf
, QGA_READ_COUNT_DEFAULT
, &count
);
374 g_warning("error reading channel: %s", err
->message
);
379 case G_IO_STATUS_ERROR
:
380 g_warning("error reading channel");
382 case G_IO_STATUS_NORMAL
:
384 g_debug("read data, count: %d, data: %s", (int)count
, buf
);
385 json_message_parser_feed(&s
->parser
, (char *)buf
, (int)count
);
387 case G_IO_STATUS_EOF
:
388 g_debug("received EOF");
392 case G_IO_STATUS_AGAIN
:
393 /* virtio causes us to spin here when no process is attached to
394 * host-side chardev. sleep a bit to mitigate this
401 g_warning("unknown channel read status, closing");
407 static gboolean
channel_init(GAState
*s
, const gchar
*method
, const gchar
*path
)
409 GAChannelMethod channel_method
;
411 if (method
== NULL
) {
412 method
= "virtio-serial";
416 if (strcmp(method
, "virtio-serial") != 0) {
417 g_critical("must specify a path for this channel");
420 /* try the default path for the virtio-serial port */
421 path
= QGA_VIRTIO_PATH_DEFAULT
;
424 if (strcmp(method
, "virtio-serial") == 0) {
425 s
->virtio
= true; /* virtio requires special handling in some cases */
426 channel_method
= GA_CHANNEL_VIRTIO_SERIAL
;
427 } else if (strcmp(method
, "isa-serial") == 0) {
428 channel_method
= GA_CHANNEL_ISA_SERIAL
;
429 } else if (strcmp(method
, "unix-listen") == 0) {
430 channel_method
= GA_CHANNEL_UNIX_LISTEN
;
432 g_critical("unsupported channel method/type: %s", method
);
436 s
->channel
= ga_channel_new(channel_method
, path
, channel_event_cb
, s
);
438 g_critical("failed to create guest agent channel");
446 DWORD WINAPI
service_ctrl_handler(DWORD ctrl
, DWORD type
, LPVOID data
,
449 DWORD ret
= NO_ERROR
;
450 GAService
*service
= &ga_state
->service
;
454 case SERVICE_CONTROL_STOP
:
455 case SERVICE_CONTROL_SHUTDOWN
:
456 quit_handler(SIGTERM
);
457 service
->status
.dwCurrentState
= SERVICE_STOP_PENDING
;
458 SetServiceStatus(service
->status_handle
, &service
->status
);
462 ret
= ERROR_CALL_NOT_IMPLEMENTED
;
467 VOID WINAPI
service_main(DWORD argc
, TCHAR
*argv
[])
469 GAService
*service
= &ga_state
->service
;
471 service
->status_handle
= RegisterServiceCtrlHandlerEx(QGA_SERVICE_NAME
,
472 service_ctrl_handler
, NULL
);
474 if (service
->status_handle
== 0) {
475 g_critical("Failed to register extended requests function!\n");
479 service
->status
.dwServiceType
= SERVICE_WIN32
;
480 service
->status
.dwCurrentState
= SERVICE_RUNNING
;
481 service
->status
.dwControlsAccepted
= SERVICE_ACCEPT_STOP
| SERVICE_ACCEPT_SHUTDOWN
;
482 service
->status
.dwWin32ExitCode
= NO_ERROR
;
483 service
->status
.dwServiceSpecificExitCode
= NO_ERROR
;
484 service
->status
.dwCheckPoint
= 0;
485 service
->status
.dwWaitHint
= 0;
486 SetServiceStatus(service
->status_handle
, &service
->status
);
488 g_main_loop_run(ga_state
->main_loop
);
490 service
->status
.dwCurrentState
= SERVICE_STOPPED
;
491 SetServiceStatus(service
->status_handle
, &service
->status
);
495 int main(int argc
, char **argv
)
497 const char *sopt
= "hVvdm:p:l:f:b:s:";
498 const char *method
= NULL
, *path
= NULL
, *pidfile
= QGA_PIDFILE_DEFAULT
;
499 const char *log_file_name
= NULL
;
501 const char *service
= NULL
;
503 const struct option lopt
[] = {
504 { "help", 0, NULL
, 'h' },
505 { "version", 0, NULL
, 'V' },
506 { "logfile", 1, NULL
, 'l' },
507 { "pidfile", 1, NULL
, 'f' },
508 { "verbose", 0, NULL
, 'v' },
509 { "method", 1, NULL
, 'm' },
510 { "path", 1, NULL
, 'p' },
511 { "daemonize", 0, NULL
, 'd' },
512 { "blacklist", 1, NULL
, 'b' },
514 { "service", 1, NULL
, 's' },
518 int opt_ind
= 0, ch
, daemonize
= 0, i
, j
, len
;
519 GLogLevelFlags log_level
= G_LOG_LEVEL_ERROR
| G_LOG_LEVEL_CRITICAL
;
520 FILE *log_file
= stderr
;
523 module_call_init(MODULE_INIT_QAPI
);
525 while ((ch
= getopt_long(argc
, argv
, sopt
, lopt
, &opt_ind
)) != -1) {
534 log_file_name
= optarg
;
535 log_file
= fopen(log_file_name
, "a");
537 g_critical("unable to open specified log file: %s",
546 /* enable all log levels */
547 log_level
= G_LOG_LEVEL_MASK
;
550 printf("QEMU Guest Agent %s\n", QGA_VERSION
);
556 char **list_head
, **list
;
557 if (*optarg
== '?') {
558 list_head
= list
= qmp_get_command_list();
559 while (*list
!= NULL
) {
560 printf("%s\n", *list
);
567 for (j
= 0, i
= 0, len
= strlen(optarg
); i
< len
; i
++) {
568 if (optarg
[i
] == ',') {
570 qmp_disable_command(&optarg
[j
]);
571 g_debug("disabling command: %s", &optarg
[j
]);
576 qmp_disable_command(&optarg
[j
]);
577 g_debug("disabling command: %s", &optarg
[j
]);
584 if (strcmp(service
, "install") == 0) {
585 return ga_install_service(path
, log_file_name
);
586 } else if (strcmp(service
, "uninstall") == 0) {
587 return ga_uninstall_service();
589 printf("Unknown service command.\n");
598 g_print("Unknown option, try '%s --help' for more information.\n",
606 g_debug("starting daemon");
607 become_daemon(pidfile
);
611 s
= g_malloc0(sizeof(GAState
));
612 s
->log_file
= log_file
;
613 s
->log_level
= log_level
;
614 g_log_set_default_handler(ga_log
, s
);
615 g_log_set_fatal_mask(NULL
, G_LOG_LEVEL_ERROR
);
616 s
->logging_enabled
= true;
617 s
->command_state
= ga_command_state_new();
618 ga_command_state_init(s
, s
->command_state
);
619 ga_command_state_init_all(s
->command_state
);
620 json_message_parser_init(&s
->parser
, process_event
);
623 if (!register_signal_handlers()) {
624 g_critical("failed to register signal handlers");
629 s
->main_loop
= g_main_loop_new(NULL
, false);
630 if (!channel_init(ga_state
, method
, path
)) {
631 g_critical("failed to initialize guest agent channel");
635 g_main_loop_run(ga_state
->main_loop
);
638 SERVICE_TABLE_ENTRY service_table
[] = {
639 { (char *)QGA_SERVICE_NAME
, service_main
}, { NULL
, NULL
} };
640 StartServiceCtrlDispatcher(service_table
);
642 g_main_loop_run(ga_state
->main_loop
);
646 ga_command_state_cleanup_all(ga_state
->command_state
);
647 ga_channel_free(ga_state
->channel
);