block/curl: Replace usleep by g_usleep
[qemu-kvm.git] / qemu-ga.c
blobd6f786e50d7e2b4bec864feebbd63a20514ea650
1 /*
2 * QEMU Guest Agent
4 * Copyright IBM Corp. 2011
6 * Authors:
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.
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
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 #define QGA_SENTINEL_BYTE 0xFF
46 struct GAState {
47 JSONMessageParser parser;
48 GMainLoop *main_loop;
49 GAChannel *channel;
50 bool virtio; /* fastpath to check for virtio to deal with poll() quirks */
51 GACommandState *command_state;
52 GLogLevelFlags log_level;
53 FILE *log_file;
54 bool logging_enabled;
55 #ifdef _WIN32
56 GAService service;
57 #endif
58 bool delimit_response;
61 struct GAState *ga_state;
63 #ifdef _WIN32
64 DWORD WINAPI service_ctrl_handler(DWORD ctrl, DWORD type, LPVOID data,
65 LPVOID ctx);
66 VOID WINAPI service_main(DWORD argc, TCHAR *argv[]);
67 #endif
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);
78 #ifndef _WIN32
79 /* reap _all_ terminated children */
80 static void child_handler(int sig)
82 int status;
83 while (waitpid(-1, &status, WNOHANG) > 0) /* NOTHING */;
86 static gboolean register_signal_handlers(void)
88 struct sigaction sigact, sigact_chld;
89 int ret;
91 memset(&sigact, 0, sizeof(struct sigaction));
92 sigact.sa_handler = quit_handler;
94 ret = sigaction(SIGINT, &sigact, NULL);
95 if (ret == -1) {
96 g_error("error configuring signal handler: %s", strerror(errno));
97 return false;
99 ret = sigaction(SIGTERM, &sigact, NULL);
100 if (ret == -1) {
101 g_error("error configuring signal handler: %s", strerror(errno));
102 return false;
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);
109 if (ret == -1) {
110 g_error("error configuring signal handler: %s", strerror(errno));
113 return true;
115 #endif
117 static void usage(const char *cmd)
119 printf(
120 "Usage: %s -c <channel_opts>\n"
121 "QEMU Guest Agent %s\n"
122 "\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"
131 #ifdef _WIN32
132 " -s, --service service commands: install, uninstall\n"
133 #endif
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"
137 "\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:
146 return "error";
147 case G_LOG_LEVEL_CRITICAL:
148 return "critical";
149 case G_LOG_LEVEL_WARNING:
150 return "warning";
151 case G_LOG_LEVEL_MESSAGE:
152 return "message";
153 case G_LOG_LEVEL_INFO:
154 return "info";
155 case G_LOG_LEVEL_DEBUG:
156 return "debug";
157 default:
158 return "user";
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)
180 GAState *s = opaque;
181 GTimeVal time;
182 const char *level_str = ga_log_level_str(level);
184 if (!ga_logging_enabled(s)) {
185 return;
188 level &= G_LOG_LEVEL_MASK;
189 #ifndef _WIN32
190 if (domain && strcmp(domain, "syslog") == 0) {
191 syslog(LOG_INFO, "%s: %s", level_str, msg);
192 } else if (level & s->log_level) {
193 #else
194 if (level & s->log_level) {
195 #endif
196 g_get_current_time(&time);
197 fprintf(s->log_file,
198 "%lu.%lu: %s: %s\n", time.tv_sec, time.tv_usec, level_str, msg);
199 fflush(s->log_file);
203 void ga_set_response_delimited(GAState *s)
205 s->delimit_response = true;
208 #ifndef _WIN32
209 static void become_daemon(const char *pidfile)
211 pid_t pid, sid;
212 int pidfd;
213 char *pidstr = NULL;
215 pid = fork();
216 if (pid < 0) {
217 exit(EXIT_FAILURE);
219 if (pid > 0) {
220 exit(EXIT_SUCCESS);
223 pidfd = open(pidfile, O_CREAT|O_WRONLY|O_EXCL, S_IRUSR|S_IWUSR);
224 if (pidfd == -1) {
225 g_critical("Cannot create pid file, %s", strerror(errno));
226 exit(EXIT_FAILURE);
229 if (asprintf(&pidstr, "%d", getpid()) == -1) {
230 g_critical("Cannot allocate memory");
231 goto fail;
233 if (write(pidfd, pidstr, strlen(pidstr)) != strlen(pidstr)) {
234 free(pidstr);
235 g_critical("Failed to write pid file");
236 goto fail;
239 umask(0);
240 sid = setsid();
241 if (sid < 0) {
242 goto fail;
244 if ((chdir("/")) < 0) {
245 goto fail;
248 close(STDIN_FILENO);
249 close(STDOUT_FILENO);
250 close(STDERR_FILENO);
251 free(pidstr);
252 return;
254 fail:
255 unlink(pidfile);
256 g_critical("failed to daemonize");
257 exit(EXIT_FAILURE);
259 #endif
261 static int send_response(GAState *s, QObject *payload)
263 const char *buf;
264 QString *payload_qstr, *response_qstr;
265 GIOStatus status;
267 g_assert(payload && s->channel);
269 payload_qstr = qobject_to_json(payload);
270 if (!payload_qstr) {
271 return -EINVAL;
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);
280 } else {
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) {
289 return -EIO;
292 return 0;
295 static void process_command(GAState *s, QDict *req)
297 QObject *rsp = NULL;
298 int ret;
300 g_assert(req);
301 g_debug("processing command");
302 rsp = qmp_dispatch(QOBJECT(req));
303 if (rsp) {
304 ret = send_response(s, rsp);
305 if (ret) {
306 g_warning("error sending response: %s", strerror(ret));
308 qobject_decref(rsp);
309 } else {
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);
318 QObject *obj;
319 QDict *qdict;
320 Error *err = NULL;
321 int ret;
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) {
328 qobject_decref(obj);
329 qdict = qdict_new();
330 if (!err) {
331 g_warning("failed to parse event: unknown error");
332 error_set(&err, QERR_JSON_PARSING);
333 } else {
334 g_warning("failed to parse event: %s", error_get_pretty(err));
336 qdict_put_obj(qdict, "error", error_get_qobject(err));
337 error_free(err);
338 } else {
339 qdict = qobject_to_qdict(obj);
342 g_assert(qdict);
344 /* handle host->guest commands */
345 if (qdict_haskey(qdict, "execute")) {
346 process_command(s, qdict);
347 } else {
348 if (!qdict_haskey(qdict, "error")) {
349 QDECREF(qdict);
350 qdict = qdict_new();
351 g_warning("unrecognized payload format");
352 error_set(&err, QERR_UNSUPPORTED);
353 qdict_put_obj(qdict, "error", error_get_qobject(err));
354 error_free(err);
356 ret = send_response(s, QOBJECT(qdict));
357 if (ret) {
358 g_warning("error sending error response: %s", strerror(ret));
362 QDECREF(qdict);
365 /* false return signals GAChannel to close the current client connection */
366 static gboolean channel_event_cb(GIOCondition condition, gpointer data)
368 GAState *s = data;
369 gchar buf[QGA_READ_COUNT_DEFAULT+1];
370 gsize count;
371 GError *err = NULL;
372 GIOStatus status = ga_channel_read(s->channel, buf, QGA_READ_COUNT_DEFAULT, &count);
373 if (err != NULL) {
374 g_warning("error reading channel: %s", err->message);
375 g_error_free(err);
376 return false;
378 switch (status) {
379 case G_IO_STATUS_ERROR:
380 g_warning("error reading channel");
381 return false;
382 case G_IO_STATUS_NORMAL:
383 buf[count] = 0;
384 g_debug("read data, count: %d, data: %s", (int)count, buf);
385 json_message_parser_feed(&s->parser, (char *)buf, (int)count);
386 break;
387 case G_IO_STATUS_EOF:
388 g_debug("received EOF");
389 if (!s->virtio) {
390 return false;
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
396 if (s->virtio) {
397 usleep(100*1000);
399 return true;
400 default:
401 g_warning("unknown channel read status, closing");
402 return false;
404 return true;
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";
415 if (path == NULL) {
416 if (strcmp(method, "virtio-serial") != 0) {
417 g_critical("must specify a path for this channel");
418 return false;
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;
431 } else {
432 g_critical("unsupported channel method/type: %s", method);
433 return false;
436 s->channel = ga_channel_new(channel_method, path, channel_event_cb, s);
437 if (!s->channel) {
438 g_critical("failed to create guest agent channel");
439 return false;
442 return true;
445 #ifdef _WIN32
446 DWORD WINAPI service_ctrl_handler(DWORD ctrl, DWORD type, LPVOID data,
447 LPVOID ctx)
449 DWORD ret = NO_ERROR;
450 GAService *service = &ga_state->service;
452 switch (ctrl)
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);
459 break;
461 default:
462 ret = ERROR_CALL_NOT_IMPLEMENTED;
464 return ret;
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");
476 return;
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);
493 #endif
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;
500 #ifdef _WIN32
501 const char *service = NULL;
502 #endif
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' },
513 #ifdef _WIN32
514 { "service", 1, NULL, 's' },
515 #endif
516 { NULL, 0, NULL, 0 }
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;
521 GAState *s;
523 module_call_init(MODULE_INIT_QAPI);
525 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
526 switch (ch) {
527 case 'm':
528 method = optarg;
529 break;
530 case 'p':
531 path = optarg;
532 break;
533 case 'l':
534 log_file_name = optarg;
535 log_file = fopen(log_file_name, "a");
536 if (!log_file) {
537 g_critical("unable to open specified log file: %s",
538 strerror(errno));
539 return EXIT_FAILURE;
541 break;
542 case 'f':
543 pidfile = optarg;
544 break;
545 case 'v':
546 /* enable all log levels */
547 log_level = G_LOG_LEVEL_MASK;
548 break;
549 case 'V':
550 printf("QEMU Guest Agent %s\n", QGA_VERSION);
551 return 0;
552 case 'd':
553 daemonize = 1;
554 break;
555 case 'b': {
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);
561 g_free(*list);
562 list++;
564 g_free(list_head);
565 return 0;
567 for (j = 0, i = 0, len = strlen(optarg); i < len; i++) {
568 if (optarg[i] == ',') {
569 optarg[i] = 0;
570 qmp_disable_command(&optarg[j]);
571 g_debug("disabling command: %s", &optarg[j]);
572 j = i + 1;
575 if (j < i) {
576 qmp_disable_command(&optarg[j]);
577 g_debug("disabling command: %s", &optarg[j]);
579 break;
581 #ifdef _WIN32
582 case 's':
583 service = optarg;
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();
588 } else {
589 printf("Unknown service command.\n");
590 return EXIT_FAILURE;
592 break;
593 #endif
594 case 'h':
595 usage(argv[0]);
596 return 0;
597 case '?':
598 g_print("Unknown option, try '%s --help' for more information.\n",
599 argv[0]);
600 return EXIT_FAILURE;
604 #ifndef _WIN32
605 if (daemonize) {
606 g_debug("starting daemon");
607 become_daemon(pidfile);
609 #endif
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);
621 ga_state = s;
622 #ifndef _WIN32
623 if (!register_signal_handlers()) {
624 g_critical("failed to register signal handlers");
625 goto out_bad;
627 #endif
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");
632 goto out_bad;
634 #ifndef _WIN32
635 g_main_loop_run(ga_state->main_loop);
636 #else
637 if (daemonize) {
638 SERVICE_TABLE_ENTRY service_table[] = {
639 { (char *)QGA_SERVICE_NAME, service_main }, { NULL, NULL } };
640 StartServiceCtrlDispatcher(service_table);
641 } else {
642 g_main_loop_run(ga_state->main_loop);
644 #endif
646 ga_command_state_cleanup_all(ga_state->command_state);
647 ga_channel_free(ga_state->channel);
649 if (daemonize) {
650 unlink(pidfile);
652 return 0;
654 out_bad:
655 if (daemonize) {
656 unlink(pidfile);
658 return EXIT_FAILURE;