]> git.proxmox.com Git - qemu.git/blob - qemu-ga.c
qemu-ga: add guest-suspend-disk
[qemu.git] / qemu-ga.c
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>
17 #include <getopt.h>
18 #ifndef _WIN32
19 #include <syslog.h>
20 #include <sys/wait.h>
21 #endif
22 #include "json-streamer.h"
23 #include "json-parser.h"
24 #include "qint.h"
25 #include "qjson.h"
26 #include "qga/guest-agent-core.h"
27 #include "module.h"
28 #include "signal.h"
29 #include "qerror.h"
30 #include "error_int.h"
31 #include "qapi/qmp-core.h"
32 #include "qga/channel.h"
33 #ifdef _WIN32
34 #include "qga/service-win32.h"
35 #include <windows.h>
36 #endif
37
38 #ifndef _WIN32
39 #define QGA_VIRTIO_PATH_DEFAULT "/dev/virtio-ports/org.qemu.guest_agent.0"
40 #else
41 #define QGA_VIRTIO_PATH_DEFAULT "\\\\.\\Global\\org.qemu.guest_agent.0"
42 #endif
43 #define QGA_PIDFILE_DEFAULT "/var/run/qemu-ga.pid"
44
45 struct GAState {
46 JSONMessageParser parser;
47 GMainLoop *main_loop;
48 GAChannel *channel;
49 bool virtio; /* fastpath to check for virtio to deal with poll() quirks */
50 GACommandState *command_state;
51 GLogLevelFlags log_level;
52 FILE *log_file;
53 bool logging_enabled;
54 #ifdef _WIN32
55 GAService service;
56 #endif
57 };
58
59 static struct GAState *ga_state;
60
61 #ifdef _WIN32
62 DWORD WINAPI service_ctrl_handler(DWORD ctrl, DWORD type, LPVOID data,
63 LPVOID ctx);
64 VOID WINAPI service_main(DWORD argc, TCHAR *argv[]);
65 #endif
66
67 static void quit_handler(int sig)
68 {
69 g_debug("received signal num %d, quitting", sig);
70
71 if (g_main_loop_is_running(ga_state->main_loop)) {
72 g_main_loop_quit(ga_state->main_loop);
73 }
74 }
75
76 #ifndef _WIN32
77 /* reap _all_ terminated children */
78 static void child_handler(int sig)
79 {
80 int status;
81 while (waitpid(-1, &status, WNOHANG) > 0) /* NOTHING */;
82 }
83
84 static gboolean register_signal_handlers(void)
85 {
86 struct sigaction sigact, sigact_chld;
87 int ret;
88
89 memset(&sigact, 0, sizeof(struct sigaction));
90 sigact.sa_handler = quit_handler;
91
92 ret = sigaction(SIGINT, &sigact, NULL);
93 if (ret == -1) {
94 g_error("error configuring signal handler: %s", strerror(errno));
95 return false;
96 }
97 ret = sigaction(SIGTERM, &sigact, NULL);
98 if (ret == -1) {
99 g_error("error configuring signal handler: %s", strerror(errno));
100 return false;
101 }
102
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);
107 if (ret == -1) {
108 g_error("error configuring signal handler: %s", strerror(errno));
109 }
110
111 return true;
112 }
113 #endif
114
115 static void usage(const char *cmd)
116 {
117 printf(
118 "Usage: %s -c <channel_opts>\n"
119 "QEMU Guest Agent %s\n"
120 "\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"
129 #ifdef _WIN32
130 " -s, --service service commands: install, uninstall\n"
131 #endif
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"
135 "\n"
136 "Report bugs to <mdroth@linux.vnet.ibm.com>\n"
137 , cmd, QGA_VERSION, QGA_VIRTIO_PATH_DEFAULT, QGA_PIDFILE_DEFAULT);
138 }
139
140 static const char *ga_log_level_str(GLogLevelFlags level)
141 {
142 switch (level & G_LOG_LEVEL_MASK) {
143 case G_LOG_LEVEL_ERROR:
144 return "error";
145 case G_LOG_LEVEL_CRITICAL:
146 return "critical";
147 case G_LOG_LEVEL_WARNING:
148 return "warning";
149 case G_LOG_LEVEL_MESSAGE:
150 return "message";
151 case G_LOG_LEVEL_INFO:
152 return "info";
153 case G_LOG_LEVEL_DEBUG:
154 return "debug";
155 default:
156 return "user";
157 }
158 }
159
160 bool ga_logging_enabled(GAState *s)
161 {
162 return s->logging_enabled;
163 }
164
165 void ga_disable_logging(GAState *s)
166 {
167 s->logging_enabled = false;
168 }
169
170 void ga_enable_logging(GAState *s)
171 {
172 s->logging_enabled = true;
173 }
174
175 static void ga_log(const gchar *domain, GLogLevelFlags level,
176 const gchar *msg, gpointer opaque)
177 {
178 GAState *s = opaque;
179 GTimeVal time;
180 const char *level_str = ga_log_level_str(level);
181
182 if (!ga_logging_enabled(s)) {
183 return;
184 }
185
186 level &= G_LOG_LEVEL_MASK;
187 #ifndef _WIN32
188 if (domain && strcmp(domain, "syslog") == 0) {
189 syslog(LOG_INFO, "%s: %s", level_str, msg);
190 } else if (level & s->log_level) {
191 #else
192 if (level & s->log_level) {
193 #endif
194 g_get_current_time(&time);
195 fprintf(s->log_file,
196 "%lu.%lu: %s: %s\n", time.tv_sec, time.tv_usec, level_str, msg);
197 fflush(s->log_file);
198 }
199 }
200
201 #ifndef _WIN32
202 static void become_daemon(const char *pidfile)
203 {
204 pid_t pid, sid;
205 int pidfd;
206 char *pidstr = NULL;
207
208 pid = fork();
209 if (pid < 0) {
210 exit(EXIT_FAILURE);
211 }
212 if (pid > 0) {
213 exit(EXIT_SUCCESS);
214 }
215
216 pidfd = open(pidfile, O_CREAT|O_WRONLY|O_EXCL, S_IRUSR|S_IWUSR);
217 if (pidfd == -1) {
218 g_critical("Cannot create pid file, %s", strerror(errno));
219 exit(EXIT_FAILURE);
220 }
221
222 if (asprintf(&pidstr, "%d", getpid()) == -1) {
223 g_critical("Cannot allocate memory");
224 goto fail;
225 }
226 if (write(pidfd, pidstr, strlen(pidstr)) != strlen(pidstr)) {
227 free(pidstr);
228 g_critical("Failed to write pid file");
229 goto fail;
230 }
231
232 umask(0);
233 sid = setsid();
234 if (sid < 0) {
235 goto fail;
236 }
237 if ((chdir("/")) < 0) {
238 goto fail;
239 }
240
241 close(STDIN_FILENO);
242 close(STDOUT_FILENO);
243 close(STDERR_FILENO);
244 free(pidstr);
245 return;
246
247 fail:
248 unlink(pidfile);
249 g_critical("failed to daemonize");
250 exit(EXIT_FAILURE);
251 }
252 #endif
253
254 static int send_response(GAState *s, QObject *payload)
255 {
256 const char *buf;
257 QString *payload_qstr;
258 GIOStatus status;
259
260 g_assert(payload && s->channel);
261
262 payload_qstr = qobject_to_json(payload);
263 if (!payload_qstr) {
264 return -EINVAL;
265 }
266
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) {
272 return -EIO;
273 }
274
275 return 0;
276 }
277
278 static void process_command(GAState *s, QDict *req)
279 {
280 QObject *rsp = NULL;
281 int ret;
282
283 g_assert(req);
284 g_debug("processing command");
285 rsp = qmp_dispatch(QOBJECT(req));
286 if (rsp) {
287 ret = send_response(s, rsp);
288 if (ret) {
289 g_warning("error sending response: %s", strerror(ret));
290 }
291 qobject_decref(rsp);
292 } else {
293 g_warning("error getting response");
294 }
295 }
296
297 /* handle requests/control events coming in over the channel */
298 static void process_event(JSONMessageParser *parser, QList *tokens)
299 {
300 GAState *s = container_of(parser, GAState, parser);
301 QObject *obj;
302 QDict *qdict;
303 Error *err = NULL;
304 int ret;
305
306 g_assert(s && parser);
307
308 g_debug("process_event: called");
309 obj = json_parser_parse_err(tokens, NULL, &err);
310 if (err || !obj || qobject_type(obj) != QTYPE_QDICT) {
311 qobject_decref(obj);
312 qdict = qdict_new();
313 if (!err) {
314 g_warning("failed to parse event: unknown error");
315 error_set(&err, QERR_JSON_PARSING);
316 } else {
317 g_warning("failed to parse event: %s", error_get_pretty(err));
318 }
319 qdict_put_obj(qdict, "error", error_get_qobject(err));
320 error_free(err);
321 } else {
322 qdict = qobject_to_qdict(obj);
323 }
324
325 g_assert(qdict);
326
327 /* handle host->guest commands */
328 if (qdict_haskey(qdict, "execute")) {
329 process_command(s, qdict);
330 } else {
331 if (!qdict_haskey(qdict, "error")) {
332 QDECREF(qdict);
333 qdict = qdict_new();
334 g_warning("unrecognized payload format");
335 error_set(&err, QERR_UNSUPPORTED);
336 qdict_put_obj(qdict, "error", error_get_qobject(err));
337 error_free(err);
338 }
339 ret = send_response(s, QOBJECT(qdict));
340 if (ret) {
341 g_warning("error sending error response: %s", strerror(ret));
342 }
343 }
344
345 QDECREF(qdict);
346 }
347
348 /* false return signals GAChannel to close the current client connection */
349 static gboolean channel_event_cb(GIOCondition condition, gpointer data)
350 {
351 GAState *s = data;
352 gchar buf[QGA_READ_COUNT_DEFAULT+1];
353 gsize count;
354 GError *err = NULL;
355 GIOStatus status = ga_channel_read(s->channel, buf, QGA_READ_COUNT_DEFAULT, &count);
356 if (err != NULL) {
357 g_warning("error reading channel: %s", err->message);
358 g_error_free(err);
359 return false;
360 }
361 switch (status) {
362 case G_IO_STATUS_ERROR:
363 g_warning("error reading channel");
364 return false;
365 case G_IO_STATUS_NORMAL:
366 buf[count] = 0;
367 g_debug("read data, count: %d, data: %s", (int)count, buf);
368 json_message_parser_feed(&s->parser, (char *)buf, (int)count);
369 break;
370 case G_IO_STATUS_EOF:
371 g_debug("received EOF");
372 if (!s->virtio) {
373 return false;
374 }
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
378 */
379 if (s->virtio) {
380 usleep(100*1000);
381 }
382 return true;
383 default:
384 g_warning("unknown channel read status, closing");
385 return false;
386 }
387 return true;
388 }
389
390 static gboolean channel_init(GAState *s, const gchar *method, const gchar *path)
391 {
392 GAChannelMethod channel_method;
393
394 if (method == NULL) {
395 method = "virtio-serial";
396 }
397
398 if (path == NULL) {
399 if (strcmp(method, "virtio-serial") != 0) {
400 g_critical("must specify a path for this channel");
401 return false;
402 }
403 /* try the default path for the virtio-serial port */
404 path = QGA_VIRTIO_PATH_DEFAULT;
405 }
406
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;
414 } else {
415 g_critical("unsupported channel method/type: %s", method);
416 return false;
417 }
418
419 s->channel = ga_channel_new(channel_method, path, channel_event_cb, s);
420 if (!s->channel) {
421 g_critical("failed to create guest agent channel");
422 return false;
423 }
424
425 return true;
426 }
427
428 #ifdef _WIN32
429 DWORD WINAPI service_ctrl_handler(DWORD ctrl, DWORD type, LPVOID data,
430 LPVOID ctx)
431 {
432 DWORD ret = NO_ERROR;
433 GAService *service = &ga_state->service;
434
435 switch (ctrl)
436 {
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);
442 break;
443
444 default:
445 ret = ERROR_CALL_NOT_IMPLEMENTED;
446 }
447 return ret;
448 }
449
450 VOID WINAPI service_main(DWORD argc, TCHAR *argv[])
451 {
452 GAService *service = &ga_state->service;
453
454 service->status_handle = RegisterServiceCtrlHandlerEx(QGA_SERVICE_NAME,
455 service_ctrl_handler, NULL);
456
457 if (service->status_handle == 0) {
458 g_critical("Failed to register extended requests function!\n");
459 return;
460 }
461
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);
470
471 g_main_loop_run(ga_state->main_loop);
472
473 service->status.dwCurrentState = SERVICE_STOPPED;
474 SetServiceStatus(service->status_handle, &service->status);
475 }
476 #endif
477
478 int main(int argc, char **argv)
479 {
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;
483 #ifdef _WIN32
484 const char *service = NULL;
485 #endif
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' },
496 #ifdef _WIN32
497 { "service", 1, NULL, 's' },
498 #endif
499 { NULL, 0, NULL, 0 }
500 };
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;
504 GAState *s;
505
506 module_call_init(MODULE_INIT_QAPI);
507
508 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
509 switch (ch) {
510 case 'm':
511 method = optarg;
512 break;
513 case 'p':
514 path = optarg;
515 break;
516 case 'l':
517 log_file_name = optarg;
518 log_file = fopen(log_file_name, "a");
519 if (!log_file) {
520 g_critical("unable to open specified log file: %s",
521 strerror(errno));
522 return EXIT_FAILURE;
523 }
524 break;
525 case 'f':
526 pidfile = optarg;
527 break;
528 case 'v':
529 /* enable all log levels */
530 log_level = G_LOG_LEVEL_MASK;
531 break;
532 case 'V':
533 printf("QEMU Guest Agent %s\n", QGA_VERSION);
534 return 0;
535 case 'd':
536 daemonize = 1;
537 break;
538 case 'b': {
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);
544 g_free(*list);
545 list++;
546 }
547 g_free(list_head);
548 return 0;
549 }
550 for (j = 0, i = 0, len = strlen(optarg); i < len; i++) {
551 if (optarg[i] == ',') {
552 optarg[i] = 0;
553 qmp_disable_command(&optarg[j]);
554 g_debug("disabling command: %s", &optarg[j]);
555 j = i + 1;
556 }
557 }
558 if (j < i) {
559 qmp_disable_command(&optarg[j]);
560 g_debug("disabling command: %s", &optarg[j]);
561 }
562 break;
563 }
564 #ifdef _WIN32
565 case 's':
566 service = optarg;
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();
571 } else {
572 printf("Unknown service command.\n");
573 return EXIT_FAILURE;
574 }
575 break;
576 #endif
577 case 'h':
578 usage(argv[0]);
579 return 0;
580 case '?':
581 g_print("Unknown option, try '%s --help' for more information.\n",
582 argv[0]);
583 return EXIT_FAILURE;
584 }
585 }
586
587 #ifndef _WIN32
588 if (daemonize) {
589 g_debug("starting daemon");
590 become_daemon(pidfile);
591 }
592 #endif
593
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);
604 ga_state = s;
605 #ifndef _WIN32
606 if (!register_signal_handlers()) {
607 g_critical("failed to register signal handlers");
608 goto out_bad;
609 }
610 #endif
611
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");
615 goto out_bad;
616 }
617 #ifndef _WIN32
618 g_main_loop_run(ga_state->main_loop);
619 #else
620 if (daemonize) {
621 SERVICE_TABLE_ENTRY service_table[] = {
622 { (char *)QGA_SERVICE_NAME, service_main }, { NULL, NULL } };
623 StartServiceCtrlDispatcher(service_table);
624 } else {
625 g_main_loop_run(ga_state->main_loop);
626 }
627 #endif
628
629 ga_command_state_cleanup_all(ga_state->command_state);
630 ga_channel_free(ga_state->channel);
631
632 if (daemonize) {
633 unlink(pidfile);
634 }
635 return 0;
636
637 out_bad:
638 if (daemonize) {
639 unlink(pidfile);
640 }
641 return EXIT_FAILURE;
642 }