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 [-m <method> -p <path>] [<options>]\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 (the default for virtio-serial is:\n"
127 " -l, --logfile set logfile path, logs to stderr by default\n"
128 " -f, --pidfile specify pidfile (default is %s)\n"
129 " -v, --verbose log extra debugging information\n"
130 " -V, --version print version information and exit\n"
131 " -d, --daemonize become a daemon\n"
133 " -s, --service service commands: install, uninstall\n"
135 " -b, --blacklist comma-separated list of RPCs to disable (no spaces, \"?\"\n"
136 " to list available RPCs)\n"
137 " -h, --help display this help and exit\n"
139 "Report bugs to <mdroth@linux.vnet.ibm.com>\n"
140 , cmd
, QGA_VERSION
, QGA_VIRTIO_PATH_DEFAULT
, QGA_PIDFILE_DEFAULT
);
143 static const char *ga_log_level_str(GLogLevelFlags level
)
145 switch (level
& G_LOG_LEVEL_MASK
) {
146 case G_LOG_LEVEL_ERROR
:
148 case G_LOG_LEVEL_CRITICAL
:
150 case G_LOG_LEVEL_WARNING
:
152 case G_LOG_LEVEL_MESSAGE
:
154 case G_LOG_LEVEL_INFO
:
156 case G_LOG_LEVEL_DEBUG
:
163 bool ga_logging_enabled(GAState
*s
)
165 return s
->logging_enabled
;
168 void ga_disable_logging(GAState
*s
)
170 s
->logging_enabled
= false;
173 void ga_enable_logging(GAState
*s
)
175 s
->logging_enabled
= true;
178 static void ga_log(const gchar
*domain
, GLogLevelFlags level
,
179 const gchar
*msg
, gpointer opaque
)
183 const char *level_str
= ga_log_level_str(level
);
185 if (!ga_logging_enabled(s
)) {
189 level
&= G_LOG_LEVEL_MASK
;
191 if (domain
&& strcmp(domain
, "syslog") == 0) {
192 syslog(LOG_INFO
, "%s: %s", level_str
, msg
);
193 } else if (level
& s
->log_level
) {
195 if (level
& s
->log_level
) {
197 g_get_current_time(&time
);
199 "%lu.%lu: %s: %s\n", time
.tv_sec
, time
.tv_usec
, level_str
, msg
);
204 void ga_set_response_delimited(GAState
*s
)
206 s
->delimit_response
= true;
210 static void become_daemon(const char *pidfile
)
224 pidfd
= open(pidfile
, O_CREAT
|O_WRONLY
|O_EXCL
, S_IRUSR
|S_IWUSR
);
226 g_critical("Cannot create pid file, %s", strerror(errno
));
230 if (asprintf(&pidstr
, "%d", getpid()) == -1) {
231 g_critical("Cannot allocate memory");
234 if (write(pidfd
, pidstr
, strlen(pidstr
)) != strlen(pidstr
)) {
236 g_critical("Failed to write pid file");
245 if ((chdir("/")) < 0) {
250 close(STDOUT_FILENO
);
251 close(STDERR_FILENO
);
257 g_critical("failed to daemonize");
262 static int send_response(GAState
*s
, QObject
*payload
)
265 QString
*payload_qstr
, *response_qstr
;
268 g_assert(payload
&& s
->channel
);
270 payload_qstr
= qobject_to_json(payload
);
275 if (s
->delimit_response
) {
276 s
->delimit_response
= false;
277 response_qstr
= qstring_new();
278 qstring_append_chr(response_qstr
, QGA_SENTINEL_BYTE
);
279 qstring_append(response_qstr
, qstring_get_str(payload_qstr
));
280 QDECREF(payload_qstr
);
282 response_qstr
= payload_qstr
;
285 qstring_append_chr(response_qstr
, '\n');
286 buf
= qstring_get_str(response_qstr
);
287 status
= ga_channel_write_all(s
->channel
, buf
, strlen(buf
));
288 QDECREF(response_qstr
);
289 if (status
!= G_IO_STATUS_NORMAL
) {
296 static void process_command(GAState
*s
, QDict
*req
)
302 g_debug("processing command");
303 rsp
= qmp_dispatch(QOBJECT(req
));
305 ret
= send_response(s
, rsp
);
307 g_warning("error sending response: %s", strerror(ret
));
311 g_warning("error getting response");
315 /* handle requests/control events coming in over the channel */
316 static void process_event(JSONMessageParser
*parser
, QList
*tokens
)
318 GAState
*s
= container_of(parser
, GAState
, parser
);
324 g_assert(s
&& parser
);
326 g_debug("process_event: called");
327 obj
= json_parser_parse_err(tokens
, NULL
, &err
);
328 if (err
|| !obj
|| qobject_type(obj
) != QTYPE_QDICT
) {
332 g_warning("failed to parse event: unknown error");
333 error_set(&err
, QERR_JSON_PARSING
);
335 g_warning("failed to parse event: %s", error_get_pretty(err
));
337 qdict_put_obj(qdict
, "error", error_get_qobject(err
));
340 qdict
= qobject_to_qdict(obj
);
345 /* handle host->guest commands */
346 if (qdict_haskey(qdict
, "execute")) {
347 process_command(s
, qdict
);
349 if (!qdict_haskey(qdict
, "error")) {
352 g_warning("unrecognized payload format");
353 error_set(&err
, QERR_UNSUPPORTED
);
354 qdict_put_obj(qdict
, "error", error_get_qobject(err
));
357 ret
= send_response(s
, QOBJECT(qdict
));
359 g_warning("error sending error response: %s", strerror(ret
));
366 /* false return signals GAChannel to close the current client connection */
367 static gboolean
channel_event_cb(GIOCondition condition
, gpointer data
)
370 gchar buf
[QGA_READ_COUNT_DEFAULT
+1];
373 GIOStatus status
= ga_channel_read(s
->channel
, buf
, QGA_READ_COUNT_DEFAULT
, &count
);
375 g_warning("error reading channel: %s", err
->message
);
380 case G_IO_STATUS_ERROR
:
381 g_warning("error reading channel");
383 case G_IO_STATUS_NORMAL
:
385 g_debug("read data, count: %d, data: %s", (int)count
, buf
);
386 json_message_parser_feed(&s
->parser
, (char *)buf
, (int)count
);
388 case G_IO_STATUS_EOF
:
389 g_debug("received EOF");
393 case G_IO_STATUS_AGAIN
:
394 /* virtio causes us to spin here when no process is attached to
395 * host-side chardev. sleep a bit to mitigate this
402 g_warning("unknown channel read status, closing");
408 static gboolean
channel_init(GAState
*s
, const gchar
*method
, const gchar
*path
)
410 GAChannelMethod channel_method
;
412 if (method
== NULL
) {
413 method
= "virtio-serial";
417 if (strcmp(method
, "virtio-serial") != 0) {
418 g_critical("must specify a path for this channel");
421 /* try the default path for the virtio-serial port */
422 path
= QGA_VIRTIO_PATH_DEFAULT
;
425 if (strcmp(method
, "virtio-serial") == 0) {
426 s
->virtio
= true; /* virtio requires special handling in some cases */
427 channel_method
= GA_CHANNEL_VIRTIO_SERIAL
;
428 } else if (strcmp(method
, "isa-serial") == 0) {
429 channel_method
= GA_CHANNEL_ISA_SERIAL
;
430 } else if (strcmp(method
, "unix-listen") == 0) {
431 channel_method
= GA_CHANNEL_UNIX_LISTEN
;
433 g_critical("unsupported channel method/type: %s", method
);
437 s
->channel
= ga_channel_new(channel_method
, path
, channel_event_cb
, s
);
439 g_critical("failed to create guest agent channel");
447 DWORD WINAPI
service_ctrl_handler(DWORD ctrl
, DWORD type
, LPVOID data
,
450 DWORD ret
= NO_ERROR
;
451 GAService
*service
= &ga_state
->service
;
455 case SERVICE_CONTROL_STOP
:
456 case SERVICE_CONTROL_SHUTDOWN
:
457 quit_handler(SIGTERM
);
458 service
->status
.dwCurrentState
= SERVICE_STOP_PENDING
;
459 SetServiceStatus(service
->status_handle
, &service
->status
);
463 ret
= ERROR_CALL_NOT_IMPLEMENTED
;
468 VOID WINAPI
service_main(DWORD argc
, TCHAR
*argv
[])
470 GAService
*service
= &ga_state
->service
;
472 service
->status_handle
= RegisterServiceCtrlHandlerEx(QGA_SERVICE_NAME
,
473 service_ctrl_handler
, NULL
);
475 if (service
->status_handle
== 0) {
476 g_critical("Failed to register extended requests function!\n");
480 service
->status
.dwServiceType
= SERVICE_WIN32
;
481 service
->status
.dwCurrentState
= SERVICE_RUNNING
;
482 service
->status
.dwControlsAccepted
= SERVICE_ACCEPT_STOP
| SERVICE_ACCEPT_SHUTDOWN
;
483 service
->status
.dwWin32ExitCode
= NO_ERROR
;
484 service
->status
.dwServiceSpecificExitCode
= NO_ERROR
;
485 service
->status
.dwCheckPoint
= 0;
486 service
->status
.dwWaitHint
= 0;
487 SetServiceStatus(service
->status_handle
, &service
->status
);
489 g_main_loop_run(ga_state
->main_loop
);
491 service
->status
.dwCurrentState
= SERVICE_STOPPED
;
492 SetServiceStatus(service
->status_handle
, &service
->status
);
496 int main(int argc
, char **argv
)
498 const char *sopt
= "hVvdm:p:l:f:b:s:";
499 const char *method
= NULL
, *path
= NULL
, *pidfile
= QGA_PIDFILE_DEFAULT
;
500 const char *log_file_name
= NULL
;
502 const char *service
= NULL
;
504 const struct option lopt
[] = {
505 { "help", 0, NULL
, 'h' },
506 { "version", 0, NULL
, 'V' },
507 { "logfile", 1, NULL
, 'l' },
508 { "pidfile", 1, NULL
, 'f' },
509 { "verbose", 0, NULL
, 'v' },
510 { "method", 1, NULL
, 'm' },
511 { "path", 1, NULL
, 'p' },
512 { "daemonize", 0, NULL
, 'd' },
513 { "blacklist", 1, NULL
, 'b' },
515 { "service", 1, NULL
, 's' },
519 int opt_ind
= 0, ch
, daemonize
= 0, i
, j
, len
;
520 GLogLevelFlags log_level
= G_LOG_LEVEL_ERROR
| G_LOG_LEVEL_CRITICAL
;
521 FILE *log_file
= stderr
;
524 module_call_init(MODULE_INIT_QAPI
);
526 while ((ch
= getopt_long(argc
, argv
, sopt
, lopt
, &opt_ind
)) != -1) {
535 log_file_name
= optarg
;
536 log_file
= fopen(log_file_name
, "a");
538 g_critical("unable to open specified log file: %s",
547 /* enable all log levels */
548 log_level
= G_LOG_LEVEL_MASK
;
551 printf("QEMU Guest Agent %s\n", QGA_VERSION
);
557 char **list_head
, **list
;
558 if (*optarg
== '?') {
559 list_head
= list
= qmp_get_command_list();
560 while (*list
!= NULL
) {
561 printf("%s\n", *list
);
568 for (j
= 0, i
= 0, len
= strlen(optarg
); i
< len
; i
++) {
569 if (optarg
[i
] == ',') {
571 qmp_disable_command(&optarg
[j
]);
572 g_debug("disabling command: %s", &optarg
[j
]);
577 qmp_disable_command(&optarg
[j
]);
578 g_debug("disabling command: %s", &optarg
[j
]);
585 if (strcmp(service
, "install") == 0) {
586 return ga_install_service(path
, log_file_name
);
587 } else if (strcmp(service
, "uninstall") == 0) {
588 return ga_uninstall_service();
590 printf("Unknown service command.\n");
599 g_print("Unknown option, try '%s --help' for more information.\n",
607 g_debug("starting daemon");
608 become_daemon(pidfile
);
612 s
= g_malloc0(sizeof(GAState
));
613 s
->log_file
= log_file
;
614 s
->log_level
= log_level
;
615 g_log_set_default_handler(ga_log
, s
);
616 g_log_set_fatal_mask(NULL
, G_LOG_LEVEL_ERROR
);
617 s
->logging_enabled
= true;
618 s
->command_state
= ga_command_state_new();
619 ga_command_state_init(s
, s
->command_state
);
620 ga_command_state_init_all(s
->command_state
);
621 json_message_parser_init(&s
->parser
, process_event
);
624 if (!register_signal_handlers()) {
625 g_critical("failed to register signal handlers");
630 s
->main_loop
= g_main_loop_new(NULL
, false);
631 if (!channel_init(ga_state
, method
, path
)) {
632 g_critical("failed to initialize guest agent channel");
636 g_main_loop_run(ga_state
->main_loop
);
639 SERVICE_TABLE_ENTRY service_table
[] = {
640 { (char *)QGA_SERVICE_NAME
, service_main
}, { NULL
, NULL
} };
641 StartServiceCtrlDispatcher(service_table
);
643 g_main_loop_run(ga_state
->main_loop
);
647 ga_command_state_cleanup_all(ga_state
->command_state
);
648 ga_channel_free(ga_state
->channel
);