]> git.proxmox.com Git - mirror_qemu.git/blame - qemu-ga.c
qemu-ga: move channel/transport functionality into wrapper class
[mirror_qemu.git] / qemu-ga.c
CommitLineData
48ff7a62
MR
1/*
2 * QEMU Guest Agent
3 *
4 * Copyright IBM Corp. 2011
5 *
6 * Authors:
7 * Adam Litke <aglitke@linux.vnet.ibm.com>
8 * Michael Roth <mdroth@linux.vnet.ibm.com>
9 *
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.
12 */
13#include <stdlib.h>
14#include <stdio.h>
15#include <stdbool.h>
16#include <glib.h>
48ff7a62 17#include <getopt.h>
48ff7a62 18#include <syslog.h>
48ff7a62
MR
19#include "json-streamer.h"
20#include "json-parser.h"
21#include "qint.h"
22#include "qjson.h"
23#include "qga/guest-agent-core.h"
24#include "module.h"
25#include "signal.h"
26#include "qerror.h"
27#include "error_int.h"
abd6cf6d 28#include "qapi/qmp-core.h"
125b310e 29#include "qga/channel.h"
48ff7a62
MR
30
31#define QGA_VIRTIO_PATH_DEFAULT "/dev/virtio-ports/org.qemu.guest_agent.0"
32#define QGA_PIDFILE_DEFAULT "/var/run/qemu-ga.pid"
48ff7a62
MR
33
34struct GAState {
35 JSONMessageParser parser;
36 GMainLoop *main_loop;
125b310e 37 GAChannel *channel;
48ff7a62
MR
38 bool virtio; /* fastpath to check for virtio to deal with poll() quirks */
39 GACommandState *command_state;
40 GLogLevelFlags log_level;
41 FILE *log_file;
42 bool logging_enabled;
43};
44
45static struct GAState *ga_state;
46
47static void quit_handler(int sig)
48{
2542bfd5 49 g_debug("received signal num %d, quitting", sig);
48ff7a62
MR
50
51 if (g_main_loop_is_running(ga_state->main_loop)) {
52 g_main_loop_quit(ga_state->main_loop);
53 }
54}
55
125b310e 56static gboolean register_signal_handlers(void)
48ff7a62
MR
57{
58 struct sigaction sigact;
59 int ret;
60
61 memset(&sigact, 0, sizeof(struct sigaction));
62 sigact.sa_handler = quit_handler;
63
64 ret = sigaction(SIGINT, &sigact, NULL);
65 if (ret == -1) {
66 g_error("error configuring signal handler: %s", strerror(errno));
125b310e 67 return false;
48ff7a62
MR
68 }
69 ret = sigaction(SIGTERM, &sigact, NULL);
70 if (ret == -1) {
71 g_error("error configuring signal handler: %s", strerror(errno));
125b310e 72 return false;
48ff7a62 73 }
125b310e 74 return true;
48ff7a62
MR
75}
76
77static void usage(const char *cmd)
78{
79 printf(
80"Usage: %s -c <channel_opts>\n"
81"QEMU Guest Agent %s\n"
82"\n"
83" -m, --method transport method: one of unix-listen, virtio-serial, or\n"
84" isa-serial (virtio-serial is the default)\n"
85" -p, --path device/socket path (%s is the default for virtio-serial)\n"
86" -l, --logfile set logfile path, logs to stderr by default\n"
87" -f, --pidfile specify pidfile (default is %s)\n"
88" -v, --verbose log extra debugging information\n"
89" -V, --version print version information and exit\n"
90" -d, --daemonize become a daemon\n"
dabdf394 91" -b, --blacklist comma-separated list of RPCs to disable (no spaces, \"?\""
abd6cf6d 92" to list available RPCs)\n"
48ff7a62
MR
93" -h, --help display this help and exit\n"
94"\n"
95"Report bugs to <mdroth@linux.vnet.ibm.com>\n"
96 , cmd, QGA_VERSION, QGA_VIRTIO_PATH_DEFAULT, QGA_PIDFILE_DEFAULT);
97}
98
48ff7a62
MR
99static const char *ga_log_level_str(GLogLevelFlags level)
100{
101 switch (level & G_LOG_LEVEL_MASK) {
102 case G_LOG_LEVEL_ERROR:
103 return "error";
104 case G_LOG_LEVEL_CRITICAL:
105 return "critical";
106 case G_LOG_LEVEL_WARNING:
107 return "warning";
108 case G_LOG_LEVEL_MESSAGE:
109 return "message";
110 case G_LOG_LEVEL_INFO:
111 return "info";
112 case G_LOG_LEVEL_DEBUG:
113 return "debug";
114 default:
115 return "user";
116 }
117}
118
119bool ga_logging_enabled(GAState *s)
120{
121 return s->logging_enabled;
122}
123
124void ga_disable_logging(GAState *s)
125{
126 s->logging_enabled = false;
127}
128
129void ga_enable_logging(GAState *s)
130{
131 s->logging_enabled = true;
132}
133
134static void ga_log(const gchar *domain, GLogLevelFlags level,
135 const gchar *msg, gpointer opaque)
136{
137 GAState *s = opaque;
138 GTimeVal time;
139 const char *level_str = ga_log_level_str(level);
140
141 if (!ga_logging_enabled(s)) {
142 return;
143 }
144
145 level &= G_LOG_LEVEL_MASK;
8f477478 146 if (domain && strcmp(domain, "syslog") == 0) {
48ff7a62
MR
147 syslog(LOG_INFO, "%s: %s", level_str, msg);
148 } else if (level & s->log_level) {
149 g_get_current_time(&time);
150 fprintf(s->log_file,
151 "%lu.%lu: %s: %s\n", time.tv_sec, time.tv_usec, level_str, msg);
152 fflush(s->log_file);
153 }
154}
155
156static void become_daemon(const char *pidfile)
157{
158 pid_t pid, sid;
159 int pidfd;
160 char *pidstr = NULL;
161
162 pid = fork();
163 if (pid < 0) {
164 exit(EXIT_FAILURE);
165 }
166 if (pid > 0) {
167 exit(EXIT_SUCCESS);
168 }
169
170 pidfd = open(pidfile, O_CREAT|O_WRONLY|O_EXCL, S_IRUSR|S_IWUSR);
171 if (pidfd == -1) {
172 g_critical("Cannot create pid file, %s", strerror(errno));
173 exit(EXIT_FAILURE);
174 }
175
176 if (asprintf(&pidstr, "%d", getpid()) == -1) {
177 g_critical("Cannot allocate memory");
178 goto fail;
179 }
180 if (write(pidfd, pidstr, strlen(pidstr)) != strlen(pidstr)) {
181 free(pidstr);
182 g_critical("Failed to write pid file");
183 goto fail;
184 }
185
186 umask(0);
187 sid = setsid();
188 if (sid < 0) {
189 goto fail;
190 }
191 if ((chdir("/")) < 0) {
192 goto fail;
193 }
194
195 close(STDIN_FILENO);
196 close(STDOUT_FILENO);
197 close(STDERR_FILENO);
198 free(pidstr);
199 return;
200
201fail:
202 unlink(pidfile);
203 g_critical("failed to daemonize");
204 exit(EXIT_FAILURE);
205}
206
125b310e 207static int send_response(GAState *s, QObject *payload)
48ff7a62 208{
48ff7a62
MR
209 const char *buf;
210 QString *payload_qstr;
125b310e 211 GIOStatus status;
48ff7a62 212
125b310e 213 g_assert(payload && s->channel);
48ff7a62
MR
214
215 payload_qstr = qobject_to_json(payload);
216 if (!payload_qstr) {
217 return -EINVAL;
218 }
219
220 qstring_append_chr(payload_qstr, '\n');
221 buf = qstring_get_str(payload_qstr);
125b310e 222 status = ga_channel_write_all(s->channel, buf, strlen(buf));
48ff7a62 223 QDECREF(payload_qstr);
125b310e
MR
224 if (status != G_IO_STATUS_NORMAL) {
225 return -EIO;
48ff7a62 226 }
125b310e
MR
227
228 return 0;
48ff7a62
MR
229}
230
231static void process_command(GAState *s, QDict *req)
232{
233 QObject *rsp = NULL;
234 int ret;
235
236 g_assert(req);
237 g_debug("processing command");
238 rsp = qmp_dispatch(QOBJECT(req));
239 if (rsp) {
125b310e 240 ret = send_response(s, rsp);
48ff7a62 241 if (ret) {
125b310e 242 g_warning("error sending response: %s", strerror(ret));
48ff7a62
MR
243 }
244 qobject_decref(rsp);
245 } else {
246 g_warning("error getting response");
247 }
248}
249
250/* handle requests/control events coming in over the channel */
251static void process_event(JSONMessageParser *parser, QList *tokens)
252{
253 GAState *s = container_of(parser, GAState, parser);
254 QObject *obj;
255 QDict *qdict;
256 Error *err = NULL;
257 int ret;
258
259 g_assert(s && parser);
260
261 g_debug("process_event: called");
262 obj = json_parser_parse_err(tokens, NULL, &err);
263 if (err || !obj || qobject_type(obj) != QTYPE_QDICT) {
264 qobject_decref(obj);
265 qdict = qdict_new();
266 if (!err) {
267 g_warning("failed to parse event: unknown error");
268 error_set(&err, QERR_JSON_PARSING);
269 } else {
270 g_warning("failed to parse event: %s", error_get_pretty(err));
271 }
272 qdict_put_obj(qdict, "error", error_get_qobject(err));
273 error_free(err);
274 } else {
275 qdict = qobject_to_qdict(obj);
276 }
277
278 g_assert(qdict);
279
280 /* handle host->guest commands */
281 if (qdict_haskey(qdict, "execute")) {
282 process_command(s, qdict);
283 } else {
284 if (!qdict_haskey(qdict, "error")) {
285 QDECREF(qdict);
286 qdict = qdict_new();
287 g_warning("unrecognized payload format");
288 error_set(&err, QERR_UNSUPPORTED);
289 qdict_put_obj(qdict, "error", error_get_qobject(err));
290 error_free(err);
291 }
125b310e 292 ret = send_response(s, QOBJECT(qdict));
48ff7a62 293 if (ret) {
125b310e 294 g_warning("error sending error response: %s", strerror(ret));
48ff7a62
MR
295 }
296 }
297
298 QDECREF(qdict);
299}
300
125b310e
MR
301/* false return signals GAChannel to close the current client connection */
302static gboolean channel_event_cb(GIOCondition condition, gpointer data)
48ff7a62
MR
303{
304 GAState *s = data;
125b310e 305 gchar buf[QGA_READ_COUNT_DEFAULT+1];
48ff7a62
MR
306 gsize count;
307 GError *err = NULL;
125b310e 308 GIOStatus status = ga_channel_read(s->channel, buf, QGA_READ_COUNT_DEFAULT, &count);
48ff7a62
MR
309 if (err != NULL) {
310 g_warning("error reading channel: %s", err->message);
48ff7a62
MR
311 g_error_free(err);
312 return false;
313 }
314 switch (status) {
315 case G_IO_STATUS_ERROR:
125b310e 316 g_warning("error reading channel");
48ff7a62
MR
317 return false;
318 case G_IO_STATUS_NORMAL:
125b310e 319 buf[count] = 0;
48ff7a62
MR
320 g_debug("read data, count: %d, data: %s", (int)count, buf);
321 json_message_parser_feed(&s->parser, (char *)buf, (int)count);
125b310e
MR
322 break;
323 case G_IO_STATUS_EOF:
324 g_debug("received EOF");
325 if (!s->virtio) {
326 return false;
327 }
48ff7a62
MR
328 case G_IO_STATUS_AGAIN:
329 /* virtio causes us to spin here when no process is attached to
330 * host-side chardev. sleep a bit to mitigate this
331 */
332 if (s->virtio) {
333 usleep(100*1000);
334 }
335 return true;
48ff7a62
MR
336 default:
337 g_warning("unknown channel read status, closing");
48ff7a62
MR
338 return false;
339 }
340 return true;
341}
342
125b310e 343static gboolean channel_init(GAState *s, const gchar *method, const gchar *path)
48ff7a62 344{
125b310e 345 GAChannelMethod channel_method;
48ff7a62 346
125b310e
MR
347 if (method == NULL) {
348 method = "virtio-serial";
48ff7a62
MR
349 }
350
125b310e
MR
351 if (path == NULL) {
352 if (strcmp(method, "virtio-serial") != 0) {
48ff7a62 353 g_critical("must specify a path for this channel");
125b310e 354 return false;
48ff7a62
MR
355 }
356 /* try the default path for the virtio-serial port */
125b310e 357 path = QGA_VIRTIO_PATH_DEFAULT;
48ff7a62
MR
358 }
359
125b310e
MR
360 if (strcmp(method, "virtio-serial") == 0) {
361 s->virtio = true; /* virtio requires special handling in some cases */
362 channel_method = GA_CHANNEL_VIRTIO_SERIAL;
363 } else if (strcmp(method, "isa-serial") == 0) {
364 channel_method = GA_CHANNEL_ISA_SERIAL;
365 } else if (strcmp(method, "unix-listen") == 0) {
366 channel_method = GA_CHANNEL_UNIX_LISTEN;
48ff7a62 367 } else {
125b310e
MR
368 g_critical("unsupported channel method/type: %s", method);
369 return false;
48ff7a62
MR
370 }
371
125b310e
MR
372 s->channel = ga_channel_new(channel_method, path, channel_event_cb, s);
373 if (!s->channel) {
374 g_critical("failed to create guest agent channel");
375 return false;
376 }
377
378 return true;
48ff7a62
MR
379}
380
381int main(int argc, char **argv)
382{
abd6cf6d 383 const char *sopt = "hVvdm:p:l:f:b:";
48ff7a62
MR
384 const char *method = NULL, *path = NULL, *pidfile = QGA_PIDFILE_DEFAULT;
385 const struct option lopt[] = {
386 { "help", 0, NULL, 'h' },
387 { "version", 0, NULL, 'V' },
388 { "logfile", 0, NULL, 'l' },
389 { "pidfile", 0, NULL, 'f' },
390 { "verbose", 0, NULL, 'v' },
391 { "method", 0, NULL, 'm' },
392 { "path", 0, NULL, 'p' },
393 { "daemonize", 0, NULL, 'd' },
abd6cf6d 394 { "blacklist", 0, NULL, 'b' },
48ff7a62
MR
395 { NULL, 0, NULL, 0 }
396 };
abd6cf6d 397 int opt_ind = 0, ch, daemonize = 0, i, j, len;
48ff7a62
MR
398 GLogLevelFlags log_level = G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL;
399 FILE *log_file = stderr;
400 GAState *s;
401
abd6cf6d
MR
402 module_call_init(MODULE_INIT_QAPI);
403
48ff7a62
MR
404 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
405 switch (ch) {
406 case 'm':
407 method = optarg;
408 break;
409 case 'p':
410 path = optarg;
411 break;
412 case 'l':
413 log_file = fopen(optarg, "a");
414 if (!log_file) {
415 g_critical("unable to open specified log file: %s",
416 strerror(errno));
417 return EXIT_FAILURE;
418 }
419 break;
420 case 'f':
421 pidfile = optarg;
422 break;
423 case 'v':
424 /* enable all log levels */
425 log_level = G_LOG_LEVEL_MASK;
426 break;
427 case 'V':
428 printf("QEMU Guest Agent %s\n", QGA_VERSION);
429 return 0;
430 case 'd':
431 daemonize = 1;
432 break;
abd6cf6d
MR
433 case 'b': {
434 char **list_head, **list;
435 if (*optarg == '?') {
436 list_head = list = qmp_get_command_list();
437 while (*list != NULL) {
438 printf("%s\n", *list);
439 g_free(*list);
440 list++;
441 }
442 g_free(list_head);
443 return 0;
444 }
445 for (j = 0, i = 0, len = strlen(optarg); i < len; i++) {
446 if (optarg[i] == ',') {
447 optarg[i] = 0;
448 qmp_disable_command(&optarg[j]);
449 g_debug("disabling command: %s", &optarg[j]);
450 j = i + 1;
451 }
452 }
453 if (j < i) {
454 qmp_disable_command(&optarg[j]);
455 g_debug("disabling command: %s", &optarg[j]);
456 }
457 break;
458 }
48ff7a62
MR
459 case 'h':
460 usage(argv[0]);
461 return 0;
462 case '?':
463 g_print("Unknown option, try '%s --help' for more information.\n",
464 argv[0]);
465 return EXIT_FAILURE;
466 }
467 }
468
469 if (daemonize) {
470 g_debug("starting daemon");
471 become_daemon(pidfile);
472 }
473
7267c094 474 s = g_malloc0(sizeof(GAState));
48ff7a62
MR
475 s->log_file = log_file;
476 s->log_level = log_level;
477 g_log_set_default_handler(ga_log, s);
478 g_log_set_fatal_mask(NULL, G_LOG_LEVEL_ERROR);
479 s->logging_enabled = true;
e3d4d252
MR
480 s->command_state = ga_command_state_new();
481 ga_command_state_init(s, s->command_state);
482 ga_command_state_init_all(s->command_state);
125b310e 483 json_message_parser_init(&s->parser, process_event);
48ff7a62 484 ga_state = s;
125b310e
MR
485 if (!register_signal_handlers()) {
486 g_critical("failed to register signal handlers");
487 goto out_bad;
488 }
48ff7a62 489
125b310e
MR
490 s->main_loop = g_main_loop_new(NULL, false);
491 if (!channel_init(ga_state, method, path)) {
492 g_critical("failed to initialize guest agent channel");
493 goto out_bad;
494 }
48ff7a62
MR
495 g_main_loop_run(ga_state->main_loop);
496
e3d4d252 497 ga_command_state_cleanup_all(ga_state->command_state);
125b310e 498 ga_channel_free(ga_state->channel);
48ff7a62 499
125b310e
MR
500 if (daemonize) {
501 unlink(pidfile);
502 }
48ff7a62 503 return 0;
125b310e
MR
504
505out_bad:
506 if (daemonize) {
507 unlink(pidfile);
508 }
509 return EXIT_FAILURE;
48ff7a62 510}