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.
21 #include "json-streamer.h"
22 #include "json-parser.h"
25 #include "qga/guest-agent-core.h"
29 #include "error_int.h"
30 #include "qapi/qmp-core.h"
31 #include "qga/channel.h"
33 #define QGA_VIRTIO_PATH_DEFAULT "/dev/virtio-ports/org.qemu.guest_agent.0"
34 #define QGA_PIDFILE_DEFAULT "/var/run/qemu-ga.pid"
37 JSONMessageParser parser
;
40 bool virtio
; /* fastpath to check for virtio to deal with poll() quirks */
41 GACommandState
*command_state
;
42 GLogLevelFlags log_level
;
47 static struct GAState
*ga_state
;
50 static void quit_handler(int sig
)
52 g_debug("received signal num %d, quitting", sig
);
54 if (g_main_loop_is_running(ga_state
->main_loop
)) {
55 g_main_loop_quit(ga_state
->main_loop
);
59 static gboolean
register_signal_handlers(void)
61 struct sigaction sigact
;
64 memset(&sigact
, 0, sizeof(struct sigaction
));
65 sigact
.sa_handler
= quit_handler
;
67 ret
= sigaction(SIGINT
, &sigact
, NULL
);
69 g_error("error configuring signal handler: %s", strerror(errno
));
72 ret
= sigaction(SIGTERM
, &sigact
, NULL
);
74 g_error("error configuring signal handler: %s", strerror(errno
));
81 static void usage(const char *cmd
)
84 "Usage: %s -c <channel_opts>\n"
85 "QEMU Guest Agent %s\n"
87 " -m, --method transport method: one of unix-listen, virtio-serial, or\n"
88 " isa-serial (virtio-serial is the default)\n"
89 " -p, --path device/socket path (%s is the default for virtio-serial)\n"
90 " -l, --logfile set logfile path, logs to stderr by default\n"
91 " -f, --pidfile specify pidfile (default is %s)\n"
92 " -v, --verbose log extra debugging information\n"
93 " -V, --version print version information and exit\n"
95 " -d, --daemonize become a daemon\n"
97 " -b, --blacklist comma-separated list of RPCs to disable (no spaces, \"?\""
98 " to list available RPCs)\n"
99 " -h, --help display this help and exit\n"
101 "Report bugs to <mdroth@linux.vnet.ibm.com>\n"
102 , cmd
, QGA_VERSION
, QGA_VIRTIO_PATH_DEFAULT
, QGA_PIDFILE_DEFAULT
);
105 static const char *ga_log_level_str(GLogLevelFlags level
)
107 switch (level
& G_LOG_LEVEL_MASK
) {
108 case G_LOG_LEVEL_ERROR
:
110 case G_LOG_LEVEL_CRITICAL
:
112 case G_LOG_LEVEL_WARNING
:
114 case G_LOG_LEVEL_MESSAGE
:
116 case G_LOG_LEVEL_INFO
:
118 case G_LOG_LEVEL_DEBUG
:
125 bool ga_logging_enabled(GAState
*s
)
127 return s
->logging_enabled
;
130 void ga_disable_logging(GAState
*s
)
132 s
->logging_enabled
= false;
135 void ga_enable_logging(GAState
*s
)
137 s
->logging_enabled
= true;
140 static void ga_log(const gchar
*domain
, GLogLevelFlags level
,
141 const gchar
*msg
, gpointer opaque
)
145 const char *level_str
= ga_log_level_str(level
);
147 if (!ga_logging_enabled(s
)) {
151 level
&= G_LOG_LEVEL_MASK
;
153 if (domain
&& strcmp(domain
, "syslog") == 0) {
154 syslog(LOG_INFO
, "%s: %s", level_str
, msg
);
155 } else if (level
& s
->log_level
) {
157 if (level
& s
->log_level
) {
159 g_get_current_time(&time
);
161 "%lu.%lu: %s: %s\n", time
.tv_sec
, time
.tv_usec
, level_str
, msg
);
167 static void become_daemon(const char *pidfile
)
181 pidfd
= open(pidfile
, O_CREAT
|O_WRONLY
|O_EXCL
, S_IRUSR
|S_IWUSR
);
183 g_critical("Cannot create pid file, %s", strerror(errno
));
187 if (asprintf(&pidstr
, "%d", getpid()) == -1) {
188 g_critical("Cannot allocate memory");
191 if (write(pidfd
, pidstr
, strlen(pidstr
)) != strlen(pidstr
)) {
193 g_critical("Failed to write pid file");
202 if ((chdir("/")) < 0) {
207 close(STDOUT_FILENO
);
208 close(STDERR_FILENO
);
214 g_critical("failed to daemonize");
219 static int send_response(GAState
*s
, QObject
*payload
)
222 QString
*payload_qstr
;
225 g_assert(payload
&& s
->channel
);
227 payload_qstr
= qobject_to_json(payload
);
232 qstring_append_chr(payload_qstr
, '\n');
233 buf
= qstring_get_str(payload_qstr
);
234 status
= ga_channel_write_all(s
->channel
, buf
, strlen(buf
));
235 QDECREF(payload_qstr
);
236 if (status
!= G_IO_STATUS_NORMAL
) {
243 static void process_command(GAState
*s
, QDict
*req
)
249 g_debug("processing command");
250 rsp
= qmp_dispatch(QOBJECT(req
));
252 ret
= send_response(s
, rsp
);
254 g_warning("error sending response: %s", strerror(ret
));
258 g_warning("error getting response");
262 /* handle requests/control events coming in over the channel */
263 static void process_event(JSONMessageParser
*parser
, QList
*tokens
)
265 GAState
*s
= container_of(parser
, GAState
, parser
);
271 g_assert(s
&& parser
);
273 g_debug("process_event: called");
274 obj
= json_parser_parse_err(tokens
, NULL
, &err
);
275 if (err
|| !obj
|| qobject_type(obj
) != QTYPE_QDICT
) {
279 g_warning("failed to parse event: unknown error");
280 error_set(&err
, QERR_JSON_PARSING
);
282 g_warning("failed to parse event: %s", error_get_pretty(err
));
284 qdict_put_obj(qdict
, "error", error_get_qobject(err
));
287 qdict
= qobject_to_qdict(obj
);
292 /* handle host->guest commands */
293 if (qdict_haskey(qdict
, "execute")) {
294 process_command(s
, qdict
);
296 if (!qdict_haskey(qdict
, "error")) {
299 g_warning("unrecognized payload format");
300 error_set(&err
, QERR_UNSUPPORTED
);
301 qdict_put_obj(qdict
, "error", error_get_qobject(err
));
304 ret
= send_response(s
, QOBJECT(qdict
));
306 g_warning("error sending error response: %s", strerror(ret
));
313 /* false return signals GAChannel to close the current client connection */
314 static gboolean
channel_event_cb(GIOCondition condition
, gpointer data
)
317 gchar buf
[QGA_READ_COUNT_DEFAULT
+1];
320 GIOStatus status
= ga_channel_read(s
->channel
, buf
, QGA_READ_COUNT_DEFAULT
, &count
);
322 g_warning("error reading channel: %s", err
->message
);
327 case G_IO_STATUS_ERROR
:
328 g_warning("error reading channel");
330 case G_IO_STATUS_NORMAL
:
332 g_debug("read data, count: %d, data: %s", (int)count
, buf
);
333 json_message_parser_feed(&s
->parser
, (char *)buf
, (int)count
);
335 case G_IO_STATUS_EOF
:
336 g_debug("received EOF");
340 case G_IO_STATUS_AGAIN
:
341 /* virtio causes us to spin here when no process is attached to
342 * host-side chardev. sleep a bit to mitigate this
349 g_warning("unknown channel read status, closing");
355 static gboolean
channel_init(GAState
*s
, const gchar
*method
, const gchar
*path
)
357 GAChannelMethod channel_method
;
359 if (method
== NULL
) {
360 method
= "virtio-serial";
364 if (strcmp(method
, "virtio-serial") != 0) {
365 g_critical("must specify a path for this channel");
368 /* try the default path for the virtio-serial port */
369 path
= QGA_VIRTIO_PATH_DEFAULT
;
372 if (strcmp(method
, "virtio-serial") == 0) {
373 s
->virtio
= true; /* virtio requires special handling in some cases */
374 channel_method
= GA_CHANNEL_VIRTIO_SERIAL
;
375 } else if (strcmp(method
, "isa-serial") == 0) {
376 channel_method
= GA_CHANNEL_ISA_SERIAL
;
377 } else if (strcmp(method
, "unix-listen") == 0) {
378 channel_method
= GA_CHANNEL_UNIX_LISTEN
;
380 g_critical("unsupported channel method/type: %s", method
);
384 s
->channel
= ga_channel_new(channel_method
, path
, channel_event_cb
, s
);
386 g_critical("failed to create guest agent channel");
393 int main(int argc
, char **argv
)
395 const char *sopt
= "hVvdm:p:l:f:b:";
396 const char *method
= NULL
, *path
= NULL
, *pidfile
= QGA_PIDFILE_DEFAULT
;
397 const struct option lopt
[] = {
398 { "help", 0, NULL
, 'h' },
399 { "version", 0, NULL
, 'V' },
400 { "logfile", 0, NULL
, 'l' },
401 { "pidfile", 0, NULL
, 'f' },
402 { "verbose", 0, NULL
, 'v' },
403 { "method", 0, NULL
, 'm' },
404 { "path", 0, NULL
, 'p' },
405 { "daemonize", 0, NULL
, 'd' },
406 { "blacklist", 0, NULL
, 'b' },
409 int opt_ind
= 0, ch
, daemonize
= 0, i
, j
, len
;
410 GLogLevelFlags log_level
= G_LOG_LEVEL_ERROR
| G_LOG_LEVEL_CRITICAL
;
411 FILE *log_file
= stderr
;
414 module_call_init(MODULE_INIT_QAPI
);
416 while ((ch
= getopt_long(argc
, argv
, sopt
, lopt
, &opt_ind
)) != -1) {
425 log_file
= fopen(optarg
, "a");
427 g_critical("unable to open specified log file: %s",
436 /* enable all log levels */
437 log_level
= G_LOG_LEVEL_MASK
;
440 printf("QEMU Guest Agent %s\n", QGA_VERSION
);
446 char **list_head
, **list
;
447 if (*optarg
== '?') {
448 list_head
= list
= qmp_get_command_list();
449 while (*list
!= NULL
) {
450 printf("%s\n", *list
);
457 for (j
= 0, i
= 0, len
= strlen(optarg
); i
< len
; i
++) {
458 if (optarg
[i
] == ',') {
460 qmp_disable_command(&optarg
[j
]);
461 g_debug("disabling command: %s", &optarg
[j
]);
466 qmp_disable_command(&optarg
[j
]);
467 g_debug("disabling command: %s", &optarg
[j
]);
475 g_print("Unknown option, try '%s --help' for more information.\n",
483 g_debug("starting daemon");
484 become_daemon(pidfile
);
488 s
= g_malloc0(sizeof(GAState
));
489 s
->log_file
= log_file
;
490 s
->log_level
= log_level
;
491 g_log_set_default_handler(ga_log
, s
);
492 g_log_set_fatal_mask(NULL
, G_LOG_LEVEL_ERROR
);
493 s
->logging_enabled
= true;
494 s
->command_state
= ga_command_state_new();
495 ga_command_state_init(s
, s
->command_state
);
496 ga_command_state_init_all(s
->command_state
);
497 json_message_parser_init(&s
->parser
, process_event
);
500 if (!register_signal_handlers()) {
501 g_critical("failed to register signal handlers");
506 s
->main_loop
= g_main_loop_new(NULL
, false);
507 if (!channel_init(ga_state
, method
, path
)) {
508 g_critical("failed to initialize guest agent channel");
511 g_main_loop_run(ga_state
->main_loop
);
513 ga_command_state_cleanup_all(ga_state
->command_state
);
514 ga_channel_free(ga_state
->channel
);