]> git.proxmox.com Git - qemu.git/blob - qemu-ga.c
prep: Initialize PC speaker
[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 #define QGA_SENTINEL_BYTE 0xFF
45
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;
59 };
60
61 struct GAState *ga_state;
62
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
68
69 static void quit_handler(int sig)
70 {
71 g_debug("received signal num %d, quitting", sig);
72
73 if (g_main_loop_is_running(ga_state->main_loop)) {
74 g_main_loop_quit(ga_state->main_loop);
75 }
76 }
77
78 #ifndef _WIN32
79 /* reap _all_ terminated children */
80 static void child_handler(int sig)
81 {
82 int status;
83 while (waitpid(-1, &status, WNOHANG) > 0) /* NOTHING */;
84 }
85
86 static gboolean register_signal_handlers(void)
87 {
88 struct sigaction sigact, sigact_chld;
89 int ret;
90
91 memset(&sigact, 0, sizeof(struct sigaction));
92 sigact.sa_handler = quit_handler;
93
94 ret = sigaction(SIGINT, &sigact, NULL);
95 if (ret == -1) {
96 g_error("error configuring signal handler: %s", strerror(errno));
97 return false;
98 }
99 ret = sigaction(SIGTERM, &sigact, NULL);
100 if (ret == -1) {
101 g_error("error configuring signal handler: %s", strerror(errno));
102 return false;
103 }
104
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));
111 }
112
113 return true;
114 }
115 #endif
116
117 static void usage(const char *cmd)
118 {
119 printf(
120 "Usage: %s [-m <method> -p <path>] [<options>]\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 (the default for virtio-serial is:\n"
126 " %s)\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"
132 #ifdef _WIN32
133 " -s, --service service commands: install, uninstall\n"
134 #endif
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"
138 "\n"
139 "Report bugs to <mdroth@linux.vnet.ibm.com>\n"
140 , cmd, QGA_VERSION, QGA_VIRTIO_PATH_DEFAULT, QGA_PIDFILE_DEFAULT);
141 }
142
143 static const char *ga_log_level_str(GLogLevelFlags level)
144 {
145 switch (level & G_LOG_LEVEL_MASK) {
146 case G_LOG_LEVEL_ERROR:
147 return "error";
148 case G_LOG_LEVEL_CRITICAL:
149 return "critical";
150 case G_LOG_LEVEL_WARNING:
151 return "warning";
152 case G_LOG_LEVEL_MESSAGE:
153 return "message";
154 case G_LOG_LEVEL_INFO:
155 return "info";
156 case G_LOG_LEVEL_DEBUG:
157 return "debug";
158 default:
159 return "user";
160 }
161 }
162
163 bool ga_logging_enabled(GAState *s)
164 {
165 return s->logging_enabled;
166 }
167
168 void ga_disable_logging(GAState *s)
169 {
170 s->logging_enabled = false;
171 }
172
173 void ga_enable_logging(GAState *s)
174 {
175 s->logging_enabled = true;
176 }
177
178 static void ga_log(const gchar *domain, GLogLevelFlags level,
179 const gchar *msg, gpointer opaque)
180 {
181 GAState *s = opaque;
182 GTimeVal time;
183 const char *level_str = ga_log_level_str(level);
184
185 if (!ga_logging_enabled(s)) {
186 return;
187 }
188
189 level &= G_LOG_LEVEL_MASK;
190 #ifndef _WIN32
191 if (domain && strcmp(domain, "syslog") == 0) {
192 syslog(LOG_INFO, "%s: %s", level_str, msg);
193 } else if (level & s->log_level) {
194 #else
195 if (level & s->log_level) {
196 #endif
197 g_get_current_time(&time);
198 fprintf(s->log_file,
199 "%lu.%lu: %s: %s\n", time.tv_sec, time.tv_usec, level_str, msg);
200 fflush(s->log_file);
201 }
202 }
203
204 void ga_set_response_delimited(GAState *s)
205 {
206 s->delimit_response = true;
207 }
208
209 #ifndef _WIN32
210 static void become_daemon(const char *pidfile)
211 {
212 pid_t pid, sid;
213 int pidfd;
214 char *pidstr = NULL;
215
216 pid = fork();
217 if (pid < 0) {
218 exit(EXIT_FAILURE);
219 }
220 if (pid > 0) {
221 exit(EXIT_SUCCESS);
222 }
223
224 pidfd = open(pidfile, O_CREAT|O_WRONLY|O_EXCL, S_IRUSR|S_IWUSR);
225 if (pidfd == -1) {
226 g_critical("Cannot create pid file, %s", strerror(errno));
227 exit(EXIT_FAILURE);
228 }
229
230 if (asprintf(&pidstr, "%d", getpid()) == -1) {
231 g_critical("Cannot allocate memory");
232 goto fail;
233 }
234 if (write(pidfd, pidstr, strlen(pidstr)) != strlen(pidstr)) {
235 free(pidstr);
236 g_critical("Failed to write pid file");
237 goto fail;
238 }
239
240 umask(0);
241 sid = setsid();
242 if (sid < 0) {
243 goto fail;
244 }
245 if ((chdir("/")) < 0) {
246 goto fail;
247 }
248
249 close(STDIN_FILENO);
250 close(STDOUT_FILENO);
251 close(STDERR_FILENO);
252 free(pidstr);
253 return;
254
255 fail:
256 unlink(pidfile);
257 g_critical("failed to daemonize");
258 exit(EXIT_FAILURE);
259 }
260 #endif
261
262 static int send_response(GAState *s, QObject *payload)
263 {
264 const char *buf;
265 QString *payload_qstr, *response_qstr;
266 GIOStatus status;
267
268 g_assert(payload && s->channel);
269
270 payload_qstr = qobject_to_json(payload);
271 if (!payload_qstr) {
272 return -EINVAL;
273 }
274
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);
281 } else {
282 response_qstr = payload_qstr;
283 }
284
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) {
290 return -EIO;
291 }
292
293 return 0;
294 }
295
296 static void process_command(GAState *s, QDict *req)
297 {
298 QObject *rsp = NULL;
299 int ret;
300
301 g_assert(req);
302 g_debug("processing command");
303 rsp = qmp_dispatch(QOBJECT(req));
304 if (rsp) {
305 ret = send_response(s, rsp);
306 if (ret) {
307 g_warning("error sending response: %s", strerror(ret));
308 }
309 qobject_decref(rsp);
310 } else {
311 g_warning("error getting response");
312 }
313 }
314
315 /* handle requests/control events coming in over the channel */
316 static void process_event(JSONMessageParser *parser, QList *tokens)
317 {
318 GAState *s = container_of(parser, GAState, parser);
319 QObject *obj;
320 QDict *qdict;
321 Error *err = NULL;
322 int ret;
323
324 g_assert(s && parser);
325
326 g_debug("process_event: called");
327 obj = json_parser_parse_err(tokens, NULL, &err);
328 if (err || !obj || qobject_type(obj) != QTYPE_QDICT) {
329 qobject_decref(obj);
330 qdict = qdict_new();
331 if (!err) {
332 g_warning("failed to parse event: unknown error");
333 error_set(&err, QERR_JSON_PARSING);
334 } else {
335 g_warning("failed to parse event: %s", error_get_pretty(err));
336 }
337 qdict_put_obj(qdict, "error", error_get_qobject(err));
338 error_free(err);
339 } else {
340 qdict = qobject_to_qdict(obj);
341 }
342
343 g_assert(qdict);
344
345 /* handle host->guest commands */
346 if (qdict_haskey(qdict, "execute")) {
347 process_command(s, qdict);
348 } else {
349 if (!qdict_haskey(qdict, "error")) {
350 QDECREF(qdict);
351 qdict = qdict_new();
352 g_warning("unrecognized payload format");
353 error_set(&err, QERR_UNSUPPORTED);
354 qdict_put_obj(qdict, "error", error_get_qobject(err));
355 error_free(err);
356 }
357 ret = send_response(s, QOBJECT(qdict));
358 if (ret) {
359 g_warning("error sending error response: %s", strerror(ret));
360 }
361 }
362
363 QDECREF(qdict);
364 }
365
366 /* false return signals GAChannel to close the current client connection */
367 static gboolean channel_event_cb(GIOCondition condition, gpointer data)
368 {
369 GAState *s = data;
370 gchar buf[QGA_READ_COUNT_DEFAULT+1];
371 gsize count;
372 GError *err = NULL;
373 GIOStatus status = ga_channel_read(s->channel, buf, QGA_READ_COUNT_DEFAULT, &count);
374 if (err != NULL) {
375 g_warning("error reading channel: %s", err->message);
376 g_error_free(err);
377 return false;
378 }
379 switch (status) {
380 case G_IO_STATUS_ERROR:
381 g_warning("error reading channel");
382 return false;
383 case G_IO_STATUS_NORMAL:
384 buf[count] = 0;
385 g_debug("read data, count: %d, data: %s", (int)count, buf);
386 json_message_parser_feed(&s->parser, (char *)buf, (int)count);
387 break;
388 case G_IO_STATUS_EOF:
389 g_debug("received EOF");
390 if (!s->virtio) {
391 return false;
392 }
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
396 */
397 if (s->virtio) {
398 usleep(100*1000);
399 }
400 return true;
401 default:
402 g_warning("unknown channel read status, closing");
403 return false;
404 }
405 return true;
406 }
407
408 static gboolean channel_init(GAState *s, const gchar *method, const gchar *path)
409 {
410 GAChannelMethod channel_method;
411
412 if (method == NULL) {
413 method = "virtio-serial";
414 }
415
416 if (path == NULL) {
417 if (strcmp(method, "virtio-serial") != 0) {
418 g_critical("must specify a path for this channel");
419 return false;
420 }
421 /* try the default path for the virtio-serial port */
422 path = QGA_VIRTIO_PATH_DEFAULT;
423 }
424
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;
432 } else {
433 g_critical("unsupported channel method/type: %s", method);
434 return false;
435 }
436
437 s->channel = ga_channel_new(channel_method, path, channel_event_cb, s);
438 if (!s->channel) {
439 g_critical("failed to create guest agent channel");
440 return false;
441 }
442
443 return true;
444 }
445
446 #ifdef _WIN32
447 DWORD WINAPI service_ctrl_handler(DWORD ctrl, DWORD type, LPVOID data,
448 LPVOID ctx)
449 {
450 DWORD ret = NO_ERROR;
451 GAService *service = &ga_state->service;
452
453 switch (ctrl)
454 {
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);
460 break;
461
462 default:
463 ret = ERROR_CALL_NOT_IMPLEMENTED;
464 }
465 return ret;
466 }
467
468 VOID WINAPI service_main(DWORD argc, TCHAR *argv[])
469 {
470 GAService *service = &ga_state->service;
471
472 service->status_handle = RegisterServiceCtrlHandlerEx(QGA_SERVICE_NAME,
473 service_ctrl_handler, NULL);
474
475 if (service->status_handle == 0) {
476 g_critical("Failed to register extended requests function!\n");
477 return;
478 }
479
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);
488
489 g_main_loop_run(ga_state->main_loop);
490
491 service->status.dwCurrentState = SERVICE_STOPPED;
492 SetServiceStatus(service->status_handle, &service->status);
493 }
494 #endif
495
496 int main(int argc, char **argv)
497 {
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;
501 #ifdef _WIN32
502 const char *service = NULL;
503 #endif
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' },
514 #ifdef _WIN32
515 { "service", 1, NULL, 's' },
516 #endif
517 { NULL, 0, NULL, 0 }
518 };
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;
522 GAState *s;
523
524 module_call_init(MODULE_INIT_QAPI);
525
526 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
527 switch (ch) {
528 case 'm':
529 method = optarg;
530 break;
531 case 'p':
532 path = optarg;
533 break;
534 case 'l':
535 log_file_name = optarg;
536 log_file = fopen(log_file_name, "a");
537 if (!log_file) {
538 g_critical("unable to open specified log file: %s",
539 strerror(errno));
540 return EXIT_FAILURE;
541 }
542 break;
543 case 'f':
544 pidfile = optarg;
545 break;
546 case 'v':
547 /* enable all log levels */
548 log_level = G_LOG_LEVEL_MASK;
549 break;
550 case 'V':
551 printf("QEMU Guest Agent %s\n", QGA_VERSION);
552 return 0;
553 case 'd':
554 daemonize = 1;
555 break;
556 case 'b': {
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);
562 g_free(*list);
563 list++;
564 }
565 g_free(list_head);
566 return 0;
567 }
568 for (j = 0, i = 0, len = strlen(optarg); i < len; i++) {
569 if (optarg[i] == ',') {
570 optarg[i] = 0;
571 qmp_disable_command(&optarg[j]);
572 g_debug("disabling command: %s", &optarg[j]);
573 j = i + 1;
574 }
575 }
576 if (j < i) {
577 qmp_disable_command(&optarg[j]);
578 g_debug("disabling command: %s", &optarg[j]);
579 }
580 break;
581 }
582 #ifdef _WIN32
583 case 's':
584 service = optarg;
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();
589 } else {
590 printf("Unknown service command.\n");
591 return EXIT_FAILURE;
592 }
593 break;
594 #endif
595 case 'h':
596 usage(argv[0]);
597 return 0;
598 case '?':
599 g_print("Unknown option, try '%s --help' for more information.\n",
600 argv[0]);
601 return EXIT_FAILURE;
602 }
603 }
604
605 #ifndef _WIN32
606 if (daemonize) {
607 g_debug("starting daemon");
608 become_daemon(pidfile);
609 }
610 #endif
611
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);
622 ga_state = s;
623 #ifndef _WIN32
624 if (!register_signal_handlers()) {
625 g_critical("failed to register signal handlers");
626 goto out_bad;
627 }
628 #endif
629
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");
633 goto out_bad;
634 }
635 #ifndef _WIN32
636 g_main_loop_run(ga_state->main_loop);
637 #else
638 if (daemonize) {
639 SERVICE_TABLE_ENTRY service_table[] = {
640 { (char *)QGA_SERVICE_NAME, service_main }, { NULL, NULL } };
641 StartServiceCtrlDispatcher(service_table);
642 } else {
643 g_main_loop_run(ga_state->main_loop);
644 }
645 #endif
646
647 ga_command_state_cleanup_all(ga_state->command_state);
648 ga_channel_free(ga_state->channel);
649
650 if (daemonize) {
651 unlink(pidfile);
652 }
653 return 0;
654
655 out_bad:
656 if (daemonize) {
657 unlink(pidfile);
658 }
659 return EXIT_FAILURE;
660 }