]> git.proxmox.com Git - qemu.git/blame - qemu-ga.c
rtl8139: remove unused marco
[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>
d8ca685a 18#ifndef _WIN32
48ff7a62 19#include <syslog.h>
11d0f125 20#include <sys/wait.h>
d8ca685a 21#endif
48ff7a62
MR
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"
abd6cf6d 31#include "qapi/qmp-core.h"
125b310e 32#include "qga/channel.h"
bc62fa03
MR
33#ifdef _WIN32
34#include "qga/service-win32.h"
35#include <windows.h>
36#endif
48ff7a62 37
7868e26e 38#ifndef _WIN32
48ff7a62 39#define QGA_VIRTIO_PATH_DEFAULT "/dev/virtio-ports/org.qemu.guest_agent.0"
7868e26e
MR
40#else
41#define QGA_VIRTIO_PATH_DEFAULT "\\\\.\\Global\\org.qemu.guest_agent.0"
42#endif
48ff7a62 43#define QGA_PIDFILE_DEFAULT "/var/run/qemu-ga.pid"
3cf0bed8 44#define QGA_SENTINEL_BYTE 0xFF
48ff7a62
MR
45
46struct GAState {
47 JSONMessageParser parser;
48 GMainLoop *main_loop;
125b310e 49 GAChannel *channel;
48ff7a62
MR
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;
bc62fa03
MR
55#ifdef _WIN32
56 GAService service;
57#endif
3cf0bed8 58 bool delimit_response;
48ff7a62
MR
59};
60
3cf0bed8 61struct GAState *ga_state;
48ff7a62 62
bc62fa03
MR
63#ifdef _WIN32
64DWORD WINAPI service_ctrl_handler(DWORD ctrl, DWORD type, LPVOID data,
65 LPVOID ctx);
66VOID WINAPI service_main(DWORD argc, TCHAR *argv[]);
67#endif
68
48ff7a62
MR
69static void quit_handler(int sig)
70{
2542bfd5 71 g_debug("received signal num %d, quitting", sig);
48ff7a62
MR
72
73 if (g_main_loop_is_running(ga_state->main_loop)) {
74 g_main_loop_quit(ga_state->main_loop);
75 }
76}
77
bc62fa03 78#ifndef _WIN32
11d0f125
LC
79/* reap _all_ terminated children */
80static void child_handler(int sig)
81{
82 int status;
83 while (waitpid(-1, &status, WNOHANG) > 0) /* NOTHING */;
84}
85
125b310e 86static gboolean register_signal_handlers(void)
48ff7a62 87{
11d0f125 88 struct sigaction sigact, sigact_chld;
48ff7a62
MR
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));
125b310e 97 return false;
48ff7a62
MR
98 }
99 ret = sigaction(SIGTERM, &sigact, NULL);
100 if (ret == -1) {
101 g_error("error configuring signal handler: %s", strerror(errno));
125b310e 102 return false;
48ff7a62 103 }
11d0f125
LC
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
125b310e 113 return true;
48ff7a62 114}
d8ca685a 115#endif
48ff7a62
MR
116
117static void usage(const char *cmd)
118{
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"
bc62fa03
MR
131#ifdef _WIN32
132" -s, --service service commands: install, uninstall\n"
d8ca685a 133#endif
dabdf394 134" -b, --blacklist comma-separated list of RPCs to disable (no spaces, \"?\""
abd6cf6d 135" to list available RPCs)\n"
48ff7a62
MR
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);
140}
141
48ff7a62
MR
142static const char *ga_log_level_str(GLogLevelFlags level)
143{
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";
159 }
160}
161
162bool ga_logging_enabled(GAState *s)
163{
164 return s->logging_enabled;
165}
166
167void ga_disable_logging(GAState *s)
168{
169 s->logging_enabled = false;
170}
171
172void ga_enable_logging(GAState *s)
173{
174 s->logging_enabled = true;
175}
176
177static void ga_log(const gchar *domain, GLogLevelFlags level,
178 const gchar *msg, gpointer opaque)
179{
180 GAState *s = opaque;
181 GTimeVal time;
182 const char *level_str = ga_log_level_str(level);
183
184 if (!ga_logging_enabled(s)) {
185 return;
186 }
187
188 level &= G_LOG_LEVEL_MASK;
d8ca685a 189#ifndef _WIN32
8f477478 190 if (domain && strcmp(domain, "syslog") == 0) {
48ff7a62
MR
191 syslog(LOG_INFO, "%s: %s", level_str, msg);
192 } else if (level & s->log_level) {
d8ca685a
MR
193#else
194 if (level & s->log_level) {
195#endif
48ff7a62
MR
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);
200 }
201}
202
3cf0bed8
MR
203void ga_set_response_delimited(GAState *s)
204{
205 s->delimit_response = true;
206}
207
d8ca685a 208#ifndef _WIN32
48ff7a62
MR
209static void become_daemon(const char *pidfile)
210{
211 pid_t pid, sid;
212 int pidfd;
213 char *pidstr = NULL;
214
215 pid = fork();
216 if (pid < 0) {
217 exit(EXIT_FAILURE);
218 }
219 if (pid > 0) {
220 exit(EXIT_SUCCESS);
221 }
222
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);
227 }
228
229 if (asprintf(&pidstr, "%d", getpid()) == -1) {
230 g_critical("Cannot allocate memory");
231 goto fail;
232 }
233 if (write(pidfd, pidstr, strlen(pidstr)) != strlen(pidstr)) {
234 free(pidstr);
235 g_critical("Failed to write pid file");
236 goto fail;
237 }
238
239 umask(0);
240 sid = setsid();
241 if (sid < 0) {
242 goto fail;
243 }
244 if ((chdir("/")) < 0) {
245 goto fail;
246 }
247
248 close(STDIN_FILENO);
249 close(STDOUT_FILENO);
250 close(STDERR_FILENO);
251 free(pidstr);
252 return;
253
254fail:
255 unlink(pidfile);
256 g_critical("failed to daemonize");
257 exit(EXIT_FAILURE);
258}
d8ca685a 259#endif
48ff7a62 260
125b310e 261static int send_response(GAState *s, QObject *payload)
48ff7a62 262{
48ff7a62 263 const char *buf;
3cf0bed8 264 QString *payload_qstr, *response_qstr;
125b310e 265 GIOStatus status;
48ff7a62 266
125b310e 267 g_assert(payload && s->channel);
48ff7a62
MR
268
269 payload_qstr = qobject_to_json(payload);
270 if (!payload_qstr) {
271 return -EINVAL;
272 }
273
3cf0bed8
MR
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;
282 }
283
284 qstring_append_chr(response_qstr, '\n');
285 buf = qstring_get_str(response_qstr);
125b310e 286 status = ga_channel_write_all(s->channel, buf, strlen(buf));
3cf0bed8 287 QDECREF(response_qstr);
125b310e
MR
288 if (status != G_IO_STATUS_NORMAL) {
289 return -EIO;
48ff7a62 290 }
125b310e
MR
291
292 return 0;
48ff7a62
MR
293}
294
295static void process_command(GAState *s, QDict *req)
296{
297 QObject *rsp = NULL;
298 int ret;
299
300 g_assert(req);
301 g_debug("processing command");
302 rsp = qmp_dispatch(QOBJECT(req));
303 if (rsp) {
125b310e 304 ret = send_response(s, rsp);
48ff7a62 305 if (ret) {
125b310e 306 g_warning("error sending response: %s", strerror(ret));
48ff7a62
MR
307 }
308 qobject_decref(rsp);
309 } else {
310 g_warning("error getting response");
311 }
312}
313
314/* handle requests/control events coming in over the channel */
315static void process_event(JSONMessageParser *parser, QList *tokens)
316{
317 GAState *s = container_of(parser, GAState, parser);
318 QObject *obj;
319 QDict *qdict;
320 Error *err = NULL;
321 int ret;
322
323 g_assert(s && parser);
324
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));
335 }
336 qdict_put_obj(qdict, "error", error_get_qobject(err));
337 error_free(err);
338 } else {
339 qdict = qobject_to_qdict(obj);
340 }
341
342 g_assert(qdict);
343
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);
355 }
125b310e 356 ret = send_response(s, QOBJECT(qdict));
48ff7a62 357 if (ret) {
125b310e 358 g_warning("error sending error response: %s", strerror(ret));
48ff7a62
MR
359 }
360 }
361
362 QDECREF(qdict);
363}
364
125b310e
MR
365/* false return signals GAChannel to close the current client connection */
366static gboolean channel_event_cb(GIOCondition condition, gpointer data)
48ff7a62
MR
367{
368 GAState *s = data;
125b310e 369 gchar buf[QGA_READ_COUNT_DEFAULT+1];
48ff7a62
MR
370 gsize count;
371 GError *err = NULL;
125b310e 372 GIOStatus status = ga_channel_read(s->channel, buf, QGA_READ_COUNT_DEFAULT, &count);
48ff7a62
MR
373 if (err != NULL) {
374 g_warning("error reading channel: %s", err->message);
48ff7a62
MR
375 g_error_free(err);
376 return false;
377 }
378 switch (status) {
379 case G_IO_STATUS_ERROR:
125b310e 380 g_warning("error reading channel");
48ff7a62
MR
381 return false;
382 case G_IO_STATUS_NORMAL:
125b310e 383 buf[count] = 0;
48ff7a62
MR
384 g_debug("read data, count: %d, data: %s", (int)count, buf);
385 json_message_parser_feed(&s->parser, (char *)buf, (int)count);
125b310e
MR
386 break;
387 case G_IO_STATUS_EOF:
388 g_debug("received EOF");
389 if (!s->virtio) {
390 return false;
391 }
48ff7a62
MR
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
395 */
396 if (s->virtio) {
397 usleep(100*1000);
398 }
399 return true;
48ff7a62
MR
400 default:
401 g_warning("unknown channel read status, closing");
48ff7a62
MR
402 return false;
403 }
404 return true;
405}
406
125b310e 407static gboolean channel_init(GAState *s, const gchar *method, const gchar *path)
48ff7a62 408{
125b310e 409 GAChannelMethod channel_method;
48ff7a62 410
125b310e
MR
411 if (method == NULL) {
412 method = "virtio-serial";
48ff7a62
MR
413 }
414
125b310e
MR
415 if (path == NULL) {
416 if (strcmp(method, "virtio-serial") != 0) {
48ff7a62 417 g_critical("must specify a path for this channel");
125b310e 418 return false;
48ff7a62
MR
419 }
420 /* try the default path for the virtio-serial port */
125b310e 421 path = QGA_VIRTIO_PATH_DEFAULT;
48ff7a62
MR
422 }
423
125b310e
MR
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;
48ff7a62 431 } else {
125b310e
MR
432 g_critical("unsupported channel method/type: %s", method);
433 return false;
48ff7a62
MR
434 }
435
125b310e
MR
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;
440 }
441
442 return true;
48ff7a62
MR
443}
444
bc62fa03
MR
445#ifdef _WIN32
446DWORD WINAPI service_ctrl_handler(DWORD ctrl, DWORD type, LPVOID data,
447 LPVOID ctx)
448{
449 DWORD ret = NO_ERROR;
450 GAService *service = &ga_state->service;
451
452 switch (ctrl)
453 {
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;
460
461 default:
462 ret = ERROR_CALL_NOT_IMPLEMENTED;
463 }
464 return ret;
465}
466
467VOID WINAPI service_main(DWORD argc, TCHAR *argv[])
468{
469 GAService *service = &ga_state->service;
470
471 service->status_handle = RegisterServiceCtrlHandlerEx(QGA_SERVICE_NAME,
472 service_ctrl_handler, NULL);
473
474 if (service->status_handle == 0) {
475 g_critical("Failed to register extended requests function!\n");
476 return;
477 }
478
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);
487
488 g_main_loop_run(ga_state->main_loop);
489
490 service->status.dwCurrentState = SERVICE_STOPPED;
491 SetServiceStatus(service->status_handle, &service->status);
492}
493#endif
494
48ff7a62
MR
495int main(int argc, char **argv)
496{
bc62fa03 497 const char *sopt = "hVvdm:p:l:f:b:s:";
48ff7a62 498 const char *method = NULL, *path = NULL, *pidfile = QGA_PIDFILE_DEFAULT;
bc62fa03
MR
499 const char *log_file_name = NULL;
500#ifdef _WIN32
501 const char *service = NULL;
502#endif
48ff7a62
MR
503 const struct option lopt[] = {
504 { "help", 0, NULL, 'h' },
505 { "version", 0, NULL, 'V' },
bc62fa03
MR
506 { "logfile", 1, NULL, 'l' },
507 { "pidfile", 1, NULL, 'f' },
48ff7a62 508 { "verbose", 0, NULL, 'v' },
bc62fa03
MR
509 { "method", 1, NULL, 'm' },
510 { "path", 1, NULL, 'p' },
48ff7a62 511 { "daemonize", 0, NULL, 'd' },
bc62fa03
MR
512 { "blacklist", 1, NULL, 'b' },
513#ifdef _WIN32
514 { "service", 1, NULL, 's' },
515#endif
48ff7a62
MR
516 { NULL, 0, NULL, 0 }
517 };
abd6cf6d 518 int opt_ind = 0, ch, daemonize = 0, i, j, len;
48ff7a62
MR
519 GLogLevelFlags log_level = G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL;
520 FILE *log_file = stderr;
521 GAState *s;
522
abd6cf6d
MR
523 module_call_init(MODULE_INIT_QAPI);
524
48ff7a62
MR
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':
bc62fa03
MR
534 log_file_name = optarg;
535 log_file = fopen(log_file_name, "a");
48ff7a62
MR
536 if (!log_file) {
537 g_critical("unable to open specified log file: %s",
538 strerror(errno));
539 return EXIT_FAILURE;
540 }
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;
abd6cf6d
MR
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++;
563 }
564 g_free(list_head);
565 return 0;
566 }
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;
573 }
574 }
575 if (j < i) {
576 qmp_disable_command(&optarg[j]);
577 g_debug("disabling command: %s", &optarg[j]);
578 }
579 break;
580 }
bc62fa03
MR
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;
591 }
592 break;
593#endif
48ff7a62
MR
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;
601 }
602 }
603
d8ca685a 604#ifndef _WIN32
48ff7a62
MR
605 if (daemonize) {
606 g_debug("starting daemon");
607 become_daemon(pidfile);
608 }
d8ca685a 609#endif
48ff7a62 610
7267c094 611 s = g_malloc0(sizeof(GAState));
48ff7a62
MR
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;
e3d4d252
MR
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);
125b310e 620 json_message_parser_init(&s->parser, process_event);
48ff7a62 621 ga_state = s;
d8ca685a 622#ifndef _WIN32
125b310e
MR
623 if (!register_signal_handlers()) {
624 g_critical("failed to register signal handlers");
625 goto out_bad;
626 }
d8ca685a 627#endif
48ff7a62 628
125b310e
MR
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;
633 }
bc62fa03 634#ifndef _WIN32
48ff7a62 635 g_main_loop_run(ga_state->main_loop);
bc62fa03
MR
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);
643 }
644#endif
48ff7a62 645
e3d4d252 646 ga_command_state_cleanup_all(ga_state->command_state);
125b310e 647 ga_channel_free(ga_state->channel);
48ff7a62 648
125b310e
MR
649 if (daemonize) {
650 unlink(pidfile);
651 }
48ff7a62 652 return 0;
125b310e
MR
653
654out_bad:
655 if (daemonize) {
656 unlink(pidfile);
657 }
658 return EXIT_FAILURE;
48ff7a62 659}