]> git.proxmox.com Git - qemu.git/blame - qemu-ga.c
qemu-ga: don't warn on no command return
[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>
f789aa7b 21#include <sys/stat.h>
d8ca685a 22#endif
48ff7a62
MR
23#include "json-streamer.h"
24#include "json-parser.h"
25#include "qint.h"
26#include "qjson.h"
27#include "qga/guest-agent-core.h"
28#include "module.h"
29#include "signal.h"
30#include "qerror.h"
31#include "error_int.h"
abd6cf6d 32#include "qapi/qmp-core.h"
125b310e 33#include "qga/channel.h"
bc62fa03
MR
34#ifdef _WIN32
35#include "qga/service-win32.h"
36#include <windows.h>
37#endif
48ff7a62 38
7868e26e 39#ifndef _WIN32
48ff7a62 40#define QGA_VIRTIO_PATH_DEFAULT "/dev/virtio-ports/org.qemu.guest_agent.0"
7868e26e
MR
41#else
42#define QGA_VIRTIO_PATH_DEFAULT "\\\\.\\Global\\org.qemu.guest_agent.0"
43#endif
48ff7a62 44#define QGA_PIDFILE_DEFAULT "/var/run/qemu-ga.pid"
f789aa7b 45#define QGA_STATEDIR_DEFAULT "/tmp"
3cf0bed8 46#define QGA_SENTINEL_BYTE 0xFF
48ff7a62
MR
47
48struct GAState {
49 JSONMessageParser parser;
50 GMainLoop *main_loop;
125b310e 51 GAChannel *channel;
48ff7a62
MR
52 bool virtio; /* fastpath to check for virtio to deal with poll() quirks */
53 GACommandState *command_state;
54 GLogLevelFlags log_level;
55 FILE *log_file;
56 bool logging_enabled;
bc62fa03
MR
57#ifdef _WIN32
58 GAService service;
59#endif
3cf0bed8 60 bool delimit_response;
f22d85e9
MR
61 bool frozen;
62 GList *blacklist;
f789aa7b
MR
63 const char *state_filepath_isfrozen;
64 struct {
65 const char *log_filepath;
66 const char *pid_filepath;
67 } deferred_options;
48ff7a62
MR
68};
69
3cf0bed8 70struct GAState *ga_state;
48ff7a62 71
f22d85e9
MR
72/* commands that are safe to issue while filesystems are frozen */
73static const char *ga_freeze_whitelist[] = {
74 "guest-ping",
75 "guest-info",
76 "guest-sync",
77 "guest-fsfreeze-status",
78 "guest-fsfreeze-thaw",
79 NULL
80};
81
bc62fa03
MR
82#ifdef _WIN32
83DWORD WINAPI service_ctrl_handler(DWORD ctrl, DWORD type, LPVOID data,
84 LPVOID ctx);
85VOID WINAPI service_main(DWORD argc, TCHAR *argv[]);
86#endif
87
48ff7a62
MR
88static void quit_handler(int sig)
89{
f22d85e9
MR
90 /* if we're frozen, don't exit unless we're absolutely forced to,
91 * because it's basically impossible for graceful exit to complete
92 * unless all log/pid files are on unfreezable filesystems. there's
93 * also a very likely chance killing the agent before unfreezing
94 * the filesystems is a mistake (or will be viewed as one later).
95 */
96 if (ga_is_frozen(ga_state)) {
97 return;
98 }
2542bfd5 99 g_debug("received signal num %d, quitting", sig);
48ff7a62
MR
100
101 if (g_main_loop_is_running(ga_state->main_loop)) {
102 g_main_loop_quit(ga_state->main_loop);
103 }
104}
105
bc62fa03 106#ifndef _WIN32
11d0f125
LC
107/* reap _all_ terminated children */
108static void child_handler(int sig)
109{
110 int status;
111 while (waitpid(-1, &status, WNOHANG) > 0) /* NOTHING */;
112}
113
125b310e 114static gboolean register_signal_handlers(void)
48ff7a62 115{
11d0f125 116 struct sigaction sigact, sigact_chld;
48ff7a62
MR
117 int ret;
118
119 memset(&sigact, 0, sizeof(struct sigaction));
120 sigact.sa_handler = quit_handler;
121
122 ret = sigaction(SIGINT, &sigact, NULL);
123 if (ret == -1) {
124 g_error("error configuring signal handler: %s", strerror(errno));
125b310e 125 return false;
48ff7a62
MR
126 }
127 ret = sigaction(SIGTERM, &sigact, NULL);
128 if (ret == -1) {
129 g_error("error configuring signal handler: %s", strerror(errno));
125b310e 130 return false;
48ff7a62 131 }
11d0f125
LC
132
133 memset(&sigact_chld, 0, sizeof(struct sigaction));
134 sigact_chld.sa_handler = child_handler;
135 sigact_chld.sa_flags = SA_NOCLDSTOP;
136 ret = sigaction(SIGCHLD, &sigact_chld, NULL);
137 if (ret == -1) {
138 g_error("error configuring signal handler: %s", strerror(errno));
139 }
140
125b310e 141 return true;
48ff7a62 142}
d8ca685a 143#endif
48ff7a62
MR
144
145static void usage(const char *cmd)
146{
147 printf(
4bdd0416 148"Usage: %s [-m <method> -p <path>] [<options>]\n"
48ff7a62
MR
149"QEMU Guest Agent %s\n"
150"\n"
151" -m, --method transport method: one of unix-listen, virtio-serial, or\n"
152" isa-serial (virtio-serial is the default)\n"
4bdd0416
MR
153" -p, --path device/socket path (the default for virtio-serial is:\n"
154" %s)\n"
48ff7a62
MR
155" -l, --logfile set logfile path, logs to stderr by default\n"
156" -f, --pidfile specify pidfile (default is %s)\n"
f789aa7b
MR
157" -t, --statedir specify dir to store state information (absolute paths\n"
158" only, default is %s)\n"
48ff7a62
MR
159" -v, --verbose log extra debugging information\n"
160" -V, --version print version information and exit\n"
161" -d, --daemonize become a daemon\n"
bc62fa03
MR
162#ifdef _WIN32
163" -s, --service service commands: install, uninstall\n"
d8ca685a 164#endif
4bdd0416 165" -b, --blacklist comma-separated list of RPCs to disable (no spaces, \"?\"\n"
abd6cf6d 166" to list available RPCs)\n"
48ff7a62
MR
167" -h, --help display this help and exit\n"
168"\n"
169"Report bugs to <mdroth@linux.vnet.ibm.com>\n"
f789aa7b
MR
170 , cmd, QGA_VERSION, QGA_VIRTIO_PATH_DEFAULT, QGA_PIDFILE_DEFAULT,
171 QGA_STATEDIR_DEFAULT);
48ff7a62
MR
172}
173
48ff7a62
MR
174static const char *ga_log_level_str(GLogLevelFlags level)
175{
176 switch (level & G_LOG_LEVEL_MASK) {
177 case G_LOG_LEVEL_ERROR:
178 return "error";
179 case G_LOG_LEVEL_CRITICAL:
180 return "critical";
181 case G_LOG_LEVEL_WARNING:
182 return "warning";
183 case G_LOG_LEVEL_MESSAGE:
184 return "message";
185 case G_LOG_LEVEL_INFO:
186 return "info";
187 case G_LOG_LEVEL_DEBUG:
188 return "debug";
189 default:
190 return "user";
191 }
192}
193
194bool ga_logging_enabled(GAState *s)
195{
196 return s->logging_enabled;
197}
198
199void ga_disable_logging(GAState *s)
200{
201 s->logging_enabled = false;
202}
203
204void ga_enable_logging(GAState *s)
205{
206 s->logging_enabled = true;
207}
208
209static void ga_log(const gchar *domain, GLogLevelFlags level,
210 const gchar *msg, gpointer opaque)
211{
212 GAState *s = opaque;
213 GTimeVal time;
214 const char *level_str = ga_log_level_str(level);
215
216 if (!ga_logging_enabled(s)) {
217 return;
218 }
219
220 level &= G_LOG_LEVEL_MASK;
d8ca685a 221#ifndef _WIN32
8f477478 222 if (domain && strcmp(domain, "syslog") == 0) {
48ff7a62
MR
223 syslog(LOG_INFO, "%s: %s", level_str, msg);
224 } else if (level & s->log_level) {
d8ca685a
MR
225#else
226 if (level & s->log_level) {
227#endif
48ff7a62
MR
228 g_get_current_time(&time);
229 fprintf(s->log_file,
230 "%lu.%lu: %s: %s\n", time.tv_sec, time.tv_usec, level_str, msg);
231 fflush(s->log_file);
232 }
233}
234
3cf0bed8
MR
235void ga_set_response_delimited(GAState *s)
236{
237 s->delimit_response = true;
238}
239
f789aa7b
MR
240#ifndef _WIN32
241static bool ga_open_pidfile(const char *pidfile)
242{
243 int pidfd;
244 char pidstr[32];
245
246 pidfd = open(pidfile, O_CREAT|O_WRONLY, S_IRUSR|S_IWUSR);
247 if (pidfd == -1 || lockf(pidfd, F_TLOCK, 0)) {
248 g_critical("Cannot lock pid file, %s", strerror(errno));
249 return false;
250 }
251
252 if (ftruncate(pidfd, 0) || lseek(pidfd, 0, SEEK_SET)) {
253 g_critical("Failed to truncate pid file");
254 goto fail;
255 }
256 sprintf(pidstr, "%d", getpid());
257 if (write(pidfd, pidstr, strlen(pidstr)) != strlen(pidstr)) {
258 g_critical("Failed to write pid file");
259 goto fail;
260 }
261
262 return true;
263
264fail:
265 unlink(pidfile);
266 return false;
267}
268#else /* _WIN32 */
269static bool ga_open_pidfile(const char *pidfile)
270{
271 return true;
272}
273#endif
274
f22d85e9
MR
275static gint ga_strcmp(gconstpointer str1, gconstpointer str2)
276{
277 return strcmp(str1, str2);
278}
279
280/* disable commands that aren't safe for fsfreeze */
281static void ga_disable_non_whitelisted(void)
282{
283 char **list_head, **list;
284 bool whitelisted;
285 int i;
286
287 list_head = list = qmp_get_command_list();
288 while (*list != NULL) {
289 whitelisted = false;
290 i = 0;
291 while (ga_freeze_whitelist[i] != NULL) {
292 if (strcmp(*list, ga_freeze_whitelist[i]) == 0) {
293 whitelisted = true;
294 }
295 i++;
296 }
297 if (!whitelisted) {
298 g_debug("disabling command: %s", *list);
299 qmp_disable_command(*list);
300 }
301 g_free(*list);
302 list++;
303 }
304 g_free(list_head);
305}
306
a31f0531 307/* [re-]enable all commands, except those explicitly blacklisted by user */
f22d85e9
MR
308static void ga_enable_non_blacklisted(GList *blacklist)
309{
310 char **list_head, **list;
311
312 list_head = list = qmp_get_command_list();
313 while (*list != NULL) {
314 if (g_list_find_custom(blacklist, *list, ga_strcmp) == NULL &&
315 !qmp_command_is_enabled(*list)) {
316 g_debug("enabling command: %s", *list);
317 qmp_enable_command(*list);
318 }
319 g_free(*list);
320 list++;
321 }
322 g_free(list_head);
323}
324
f789aa7b
MR
325static bool ga_create_file(const char *path)
326{
327 int fd = open(path, O_CREAT | O_WRONLY, S_IWUSR | S_IRUSR);
328 if (fd == -1) {
329 g_warning("unable to open/create file %s: %s", path, strerror(errno));
330 return false;
331 }
332 close(fd);
333 return true;
334}
335
336static bool ga_delete_file(const char *path)
337{
338 int ret = unlink(path);
339 if (ret == -1) {
340 g_warning("unable to delete file: %s: %s", path, strerror(errno));
341 return false;
342 }
343
344 return true;
345}
346
f22d85e9
MR
347bool ga_is_frozen(GAState *s)
348{
349 return s->frozen;
350}
351
352void ga_set_frozen(GAState *s)
353{
354 if (ga_is_frozen(s)) {
355 return;
356 }
357 /* disable all non-whitelisted (for frozen state) commands */
358 ga_disable_non_whitelisted();
359 g_warning("disabling logging due to filesystem freeze");
360 ga_disable_logging(s);
361 s->frozen = true;
f789aa7b
MR
362 if (!ga_create_file(s->state_filepath_isfrozen)) {
363 g_warning("unable to create %s, fsfreeze may not function properly",
364 s->state_filepath_isfrozen);
365 }
f22d85e9
MR
366}
367
368void ga_unset_frozen(GAState *s)
369{
370 if (!ga_is_frozen(s)) {
371 return;
372 }
373
f789aa7b
MR
374 /* if we delayed creation/opening of pid/log files due to being
375 * in a frozen state at start up, do it now
376 */
377 if (s->deferred_options.log_filepath) {
378 s->log_file = fopen(s->deferred_options.log_filepath, "a");
379 if (!s->log_file) {
380 s->log_file = stderr;
381 }
382 s->deferred_options.log_filepath = NULL;
383 }
f22d85e9 384 ga_enable_logging(s);
f789aa7b
MR
385 g_warning("logging re-enabled due to filesystem unfreeze");
386 if (s->deferred_options.pid_filepath) {
387 if (!ga_open_pidfile(s->deferred_options.pid_filepath)) {
388 g_warning("failed to create/open pid file");
389 }
390 s->deferred_options.pid_filepath = NULL;
391 }
f22d85e9
MR
392
393 /* enable all disabled, non-blacklisted commands */
394 ga_enable_non_blacklisted(s->blacklist);
395 s->frozen = false;
f789aa7b
MR
396 if (!ga_delete_file(s->state_filepath_isfrozen)) {
397 g_warning("unable to delete %s, fsfreeze may not function properly",
398 s->state_filepath_isfrozen);
399 }
f22d85e9
MR
400}
401
48ff7a62
MR
402static void become_daemon(const char *pidfile)
403{
f789aa7b 404#ifndef _WIN32
48ff7a62 405 pid_t pid, sid;
48ff7a62
MR
406
407 pid = fork();
408 if (pid < 0) {
409 exit(EXIT_FAILURE);
410 }
411 if (pid > 0) {
412 exit(EXIT_SUCCESS);
413 }
414
f789aa7b
MR
415 if (pidfile) {
416 if (!ga_open_pidfile(pidfile)) {
417 g_critical("failed to create pidfile");
418 exit(EXIT_FAILURE);
419 }
48ff7a62
MR
420 }
421
422 umask(0);
423 sid = setsid();
424 if (sid < 0) {
425 goto fail;
426 }
427 if ((chdir("/")) < 0) {
428 goto fail;
429 }
430
431 close(STDIN_FILENO);
432 close(STDOUT_FILENO);
433 close(STDERR_FILENO);
48ff7a62
MR
434 return;
435
436fail:
437 unlink(pidfile);
438 g_critical("failed to daemonize");
439 exit(EXIT_FAILURE);
d8ca685a 440#endif
f789aa7b 441}
48ff7a62 442
125b310e 443static int send_response(GAState *s, QObject *payload)
48ff7a62 444{
48ff7a62 445 const char *buf;
3cf0bed8 446 QString *payload_qstr, *response_qstr;
125b310e 447 GIOStatus status;
48ff7a62 448
125b310e 449 g_assert(payload && s->channel);
48ff7a62
MR
450
451 payload_qstr = qobject_to_json(payload);
452 if (!payload_qstr) {
453 return -EINVAL;
454 }
455
3cf0bed8
MR
456 if (s->delimit_response) {
457 s->delimit_response = false;
458 response_qstr = qstring_new();
459 qstring_append_chr(response_qstr, QGA_SENTINEL_BYTE);
460 qstring_append(response_qstr, qstring_get_str(payload_qstr));
461 QDECREF(payload_qstr);
462 } else {
463 response_qstr = payload_qstr;
464 }
465
466 qstring_append_chr(response_qstr, '\n');
467 buf = qstring_get_str(response_qstr);
125b310e 468 status = ga_channel_write_all(s->channel, buf, strlen(buf));
3cf0bed8 469 QDECREF(response_qstr);
125b310e
MR
470 if (status != G_IO_STATUS_NORMAL) {
471 return -EIO;
48ff7a62 472 }
125b310e
MR
473
474 return 0;
48ff7a62
MR
475}
476
477static void process_command(GAState *s, QDict *req)
478{
479 QObject *rsp = NULL;
480 int ret;
481
482 g_assert(req);
483 g_debug("processing command");
484 rsp = qmp_dispatch(QOBJECT(req));
485 if (rsp) {
125b310e 486 ret = send_response(s, rsp);
48ff7a62 487 if (ret) {
125b310e 488 g_warning("error sending response: %s", strerror(ret));
48ff7a62
MR
489 }
490 qobject_decref(rsp);
48ff7a62
MR
491 }
492}
493
494/* handle requests/control events coming in over the channel */
495static void process_event(JSONMessageParser *parser, QList *tokens)
496{
497 GAState *s = container_of(parser, GAState, parser);
498 QObject *obj;
499 QDict *qdict;
500 Error *err = NULL;
501 int ret;
502
503 g_assert(s && parser);
504
505 g_debug("process_event: called");
506 obj = json_parser_parse_err(tokens, NULL, &err);
507 if (err || !obj || qobject_type(obj) != QTYPE_QDICT) {
508 qobject_decref(obj);
509 qdict = qdict_new();
510 if (!err) {
511 g_warning("failed to parse event: unknown error");
512 error_set(&err, QERR_JSON_PARSING);
513 } else {
514 g_warning("failed to parse event: %s", error_get_pretty(err));
515 }
516 qdict_put_obj(qdict, "error", error_get_qobject(err));
517 error_free(err);
518 } else {
519 qdict = qobject_to_qdict(obj);
520 }
521
522 g_assert(qdict);
523
524 /* handle host->guest commands */
525 if (qdict_haskey(qdict, "execute")) {
526 process_command(s, qdict);
527 } else {
528 if (!qdict_haskey(qdict, "error")) {
529 QDECREF(qdict);
530 qdict = qdict_new();
531 g_warning("unrecognized payload format");
532 error_set(&err, QERR_UNSUPPORTED);
533 qdict_put_obj(qdict, "error", error_get_qobject(err));
534 error_free(err);
535 }
125b310e 536 ret = send_response(s, QOBJECT(qdict));
48ff7a62 537 if (ret) {
125b310e 538 g_warning("error sending error response: %s", strerror(ret));
48ff7a62
MR
539 }
540 }
541
542 QDECREF(qdict);
543}
544
125b310e
MR
545/* false return signals GAChannel to close the current client connection */
546static gboolean channel_event_cb(GIOCondition condition, gpointer data)
48ff7a62
MR
547{
548 GAState *s = data;
125b310e 549 gchar buf[QGA_READ_COUNT_DEFAULT+1];
48ff7a62
MR
550 gsize count;
551 GError *err = NULL;
125b310e 552 GIOStatus status = ga_channel_read(s->channel, buf, QGA_READ_COUNT_DEFAULT, &count);
48ff7a62
MR
553 if (err != NULL) {
554 g_warning("error reading channel: %s", err->message);
48ff7a62
MR
555 g_error_free(err);
556 return false;
557 }
558 switch (status) {
559 case G_IO_STATUS_ERROR:
125b310e 560 g_warning("error reading channel");
48ff7a62
MR
561 return false;
562 case G_IO_STATUS_NORMAL:
125b310e 563 buf[count] = 0;
48ff7a62
MR
564 g_debug("read data, count: %d, data: %s", (int)count, buf);
565 json_message_parser_feed(&s->parser, (char *)buf, (int)count);
125b310e
MR
566 break;
567 case G_IO_STATUS_EOF:
568 g_debug("received EOF");
569 if (!s->virtio) {
570 return false;
571 }
48ff7a62
MR
572 case G_IO_STATUS_AGAIN:
573 /* virtio causes us to spin here when no process is attached to
574 * host-side chardev. sleep a bit to mitigate this
575 */
576 if (s->virtio) {
577 usleep(100*1000);
578 }
579 return true;
48ff7a62
MR
580 default:
581 g_warning("unknown channel read status, closing");
48ff7a62
MR
582 return false;
583 }
584 return true;
585}
586
125b310e 587static gboolean channel_init(GAState *s, const gchar *method, const gchar *path)
48ff7a62 588{
125b310e 589 GAChannelMethod channel_method;
48ff7a62 590
125b310e
MR
591 if (method == NULL) {
592 method = "virtio-serial";
48ff7a62
MR
593 }
594
125b310e
MR
595 if (path == NULL) {
596 if (strcmp(method, "virtio-serial") != 0) {
48ff7a62 597 g_critical("must specify a path for this channel");
125b310e 598 return false;
48ff7a62
MR
599 }
600 /* try the default path for the virtio-serial port */
125b310e 601 path = QGA_VIRTIO_PATH_DEFAULT;
48ff7a62
MR
602 }
603
125b310e
MR
604 if (strcmp(method, "virtio-serial") == 0) {
605 s->virtio = true; /* virtio requires special handling in some cases */
606 channel_method = GA_CHANNEL_VIRTIO_SERIAL;
607 } else if (strcmp(method, "isa-serial") == 0) {
608 channel_method = GA_CHANNEL_ISA_SERIAL;
609 } else if (strcmp(method, "unix-listen") == 0) {
610 channel_method = GA_CHANNEL_UNIX_LISTEN;
48ff7a62 611 } else {
125b310e
MR
612 g_critical("unsupported channel method/type: %s", method);
613 return false;
48ff7a62
MR
614 }
615
125b310e
MR
616 s->channel = ga_channel_new(channel_method, path, channel_event_cb, s);
617 if (!s->channel) {
618 g_critical("failed to create guest agent channel");
619 return false;
620 }
621
622 return true;
48ff7a62
MR
623}
624
bc62fa03
MR
625#ifdef _WIN32
626DWORD WINAPI service_ctrl_handler(DWORD ctrl, DWORD type, LPVOID data,
627 LPVOID ctx)
628{
629 DWORD ret = NO_ERROR;
630 GAService *service = &ga_state->service;
631
632 switch (ctrl)
633 {
634 case SERVICE_CONTROL_STOP:
635 case SERVICE_CONTROL_SHUTDOWN:
636 quit_handler(SIGTERM);
637 service->status.dwCurrentState = SERVICE_STOP_PENDING;
638 SetServiceStatus(service->status_handle, &service->status);
639 break;
640
641 default:
642 ret = ERROR_CALL_NOT_IMPLEMENTED;
643 }
644 return ret;
645}
646
647VOID WINAPI service_main(DWORD argc, TCHAR *argv[])
648{
649 GAService *service = &ga_state->service;
650
651 service->status_handle = RegisterServiceCtrlHandlerEx(QGA_SERVICE_NAME,
652 service_ctrl_handler, NULL);
653
654 if (service->status_handle == 0) {
655 g_critical("Failed to register extended requests function!\n");
656 return;
657 }
658
659 service->status.dwServiceType = SERVICE_WIN32;
660 service->status.dwCurrentState = SERVICE_RUNNING;
661 service->status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
662 service->status.dwWin32ExitCode = NO_ERROR;
663 service->status.dwServiceSpecificExitCode = NO_ERROR;
664 service->status.dwCheckPoint = 0;
665 service->status.dwWaitHint = 0;
666 SetServiceStatus(service->status_handle, &service->status);
667
668 g_main_loop_run(ga_state->main_loop);
669
670 service->status.dwCurrentState = SERVICE_STOPPED;
671 SetServiceStatus(service->status_handle, &service->status);
672}
673#endif
674
48ff7a62
MR
675int main(int argc, char **argv)
676{
f789aa7b
MR
677 const char *sopt = "hVvdm:p:l:f:b:s:t:";
678 const char *method = NULL, *path = NULL;
679 const char *log_filepath = NULL;
680 const char *pid_filepath = QGA_PIDFILE_DEFAULT;
681 const char *state_dir = QGA_STATEDIR_DEFAULT;
bc62fa03
MR
682#ifdef _WIN32
683 const char *service = NULL;
684#endif
48ff7a62
MR
685 const struct option lopt[] = {
686 { "help", 0, NULL, 'h' },
687 { "version", 0, NULL, 'V' },
bc62fa03
MR
688 { "logfile", 1, NULL, 'l' },
689 { "pidfile", 1, NULL, 'f' },
48ff7a62 690 { "verbose", 0, NULL, 'v' },
bc62fa03
MR
691 { "method", 1, NULL, 'm' },
692 { "path", 1, NULL, 'p' },
48ff7a62 693 { "daemonize", 0, NULL, 'd' },
bc62fa03
MR
694 { "blacklist", 1, NULL, 'b' },
695#ifdef _WIN32
696 { "service", 1, NULL, 's' },
f22d85e9 697#endif
f789aa7b 698 { "statedir", 1, NULL, 't' },
48ff7a62
MR
699 { NULL, 0, NULL, 0 }
700 };
abd6cf6d 701 int opt_ind = 0, ch, daemonize = 0, i, j, len;
48ff7a62 702 GLogLevelFlags log_level = G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL;
f22d85e9 703 GList *blacklist = NULL;
48ff7a62
MR
704 GAState *s;
705
abd6cf6d
MR
706 module_call_init(MODULE_INIT_QAPI);
707
48ff7a62
MR
708 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
709 switch (ch) {
710 case 'm':
711 method = optarg;
712 break;
713 case 'p':
714 path = optarg;
715 break;
716 case 'l':
f789aa7b 717 log_filepath = optarg;
48ff7a62
MR
718 break;
719 case 'f':
f789aa7b 720 pid_filepath = optarg;
48ff7a62 721 break;
f789aa7b
MR
722 case 't':
723 state_dir = optarg;
724 break;
48ff7a62
MR
725 case 'v':
726 /* enable all log levels */
727 log_level = G_LOG_LEVEL_MASK;
728 break;
729 case 'V':
730 printf("QEMU Guest Agent %s\n", QGA_VERSION);
731 return 0;
732 case 'd':
733 daemonize = 1;
734 break;
abd6cf6d
MR
735 case 'b': {
736 char **list_head, **list;
737 if (*optarg == '?') {
738 list_head = list = qmp_get_command_list();
739 while (*list != NULL) {
740 printf("%s\n", *list);
741 g_free(*list);
742 list++;
743 }
744 g_free(list_head);
745 return 0;
746 }
747 for (j = 0, i = 0, len = strlen(optarg); i < len; i++) {
748 if (optarg[i] == ',') {
749 optarg[i] = 0;
f22d85e9 750 blacklist = g_list_append(blacklist, &optarg[j]);
abd6cf6d
MR
751 j = i + 1;
752 }
753 }
754 if (j < i) {
f22d85e9 755 blacklist = g_list_append(blacklist, &optarg[j]);
abd6cf6d
MR
756 }
757 break;
758 }
bc62fa03
MR
759#ifdef _WIN32
760 case 's':
761 service = optarg;
762 if (strcmp(service, "install") == 0) {
f789aa7b 763 return ga_install_service(path, log_filepath);
bc62fa03
MR
764 } else if (strcmp(service, "uninstall") == 0) {
765 return ga_uninstall_service();
766 } else {
767 printf("Unknown service command.\n");
768 return EXIT_FAILURE;
769 }
770 break;
771#endif
48ff7a62
MR
772 case 'h':
773 usage(argv[0]);
774 return 0;
775 case '?':
776 g_print("Unknown option, try '%s --help' for more information.\n",
777 argv[0]);
778 return EXIT_FAILURE;
779 }
780 }
781
7267c094 782 s = g_malloc0(sizeof(GAState));
48ff7a62 783 s->log_level = log_level;
f789aa7b 784 s->log_file = stderr;
48ff7a62
MR
785 g_log_set_default_handler(ga_log, s);
786 g_log_set_fatal_mask(NULL, G_LOG_LEVEL_ERROR);
f789aa7b
MR
787 ga_enable_logging(s);
788 s->state_filepath_isfrozen = g_strdup_printf("%s/qga.state.isfrozen",
789 state_dir);
f22d85e9 790 s->frozen = false;
f789aa7b
MR
791#ifndef _WIN32
792 /* check if a previous instance of qemu-ga exited with filesystems' state
793 * marked as frozen. this could be a stale value (a non-qemu-ga process
794 * or reboot may have since unfrozen them), but better to require an
795 * uneeded unfreeze than to risk hanging on start-up
796 */
797 struct stat st;
798 if (stat(s->state_filepath_isfrozen, &st) == -1) {
799 /* it's okay if the file doesn't exist, but if we can't access for
800 * some other reason, such as permissions, there's a configuration
801 * that needs to be addressed. so just bail now before we get into
802 * more trouble later
803 */
804 if (errno != ENOENT) {
805 g_critical("unable to access state file at path %s: %s",
806 s->state_filepath_isfrozen, strerror(errno));
807 return EXIT_FAILURE;
808 }
809 } else {
810 g_warning("previous instance appears to have exited with frozen"
811 " filesystems. deferring logging/pidfile creation and"
812 " disabling non-fsfreeze-safe commands until"
813 " guest-fsfreeze-thaw is issued, or filesystems are"
814 " manually unfrozen and the file %s is removed",
815 s->state_filepath_isfrozen);
816 s->frozen = true;
817 }
818#endif
819
820 if (ga_is_frozen(s)) {
821 if (daemonize) {
822 /* delay opening/locking of pidfile till filesystem are unfrozen */
823 s->deferred_options.pid_filepath = pid_filepath;
824 become_daemon(NULL);
825 }
826 if (log_filepath) {
827 /* delay opening the log file till filesystems are unfrozen */
828 s->deferred_options.log_filepath = log_filepath;
829 }
830 ga_disable_logging(s);
831 ga_disable_non_whitelisted();
832 } else {
833 if (daemonize) {
834 become_daemon(pid_filepath);
835 }
836 if (log_filepath) {
837 s->log_file = fopen(log_filepath, "a");
838 if (!s->log_file) {
839 g_critical("unable to open specified log file: %s",
840 strerror(errno));
841 goto out_bad;
842 }
843 }
844 }
845
f22d85e9
MR
846 if (blacklist) {
847 s->blacklist = blacklist;
848 do {
849 g_debug("disabling command: %s", (char *)blacklist->data);
850 qmp_disable_command(blacklist->data);
851 blacklist = g_list_next(blacklist);
852 } while (blacklist);
853 }
e3d4d252
MR
854 s->command_state = ga_command_state_new();
855 ga_command_state_init(s, s->command_state);
856 ga_command_state_init_all(s->command_state);
125b310e 857 json_message_parser_init(&s->parser, process_event);
48ff7a62 858 ga_state = s;
d8ca685a 859#ifndef _WIN32
125b310e
MR
860 if (!register_signal_handlers()) {
861 g_critical("failed to register signal handlers");
862 goto out_bad;
863 }
d8ca685a 864#endif
48ff7a62 865
125b310e
MR
866 s->main_loop = g_main_loop_new(NULL, false);
867 if (!channel_init(ga_state, method, path)) {
868 g_critical("failed to initialize guest agent channel");
869 goto out_bad;
870 }
bc62fa03 871#ifndef _WIN32
48ff7a62 872 g_main_loop_run(ga_state->main_loop);
bc62fa03
MR
873#else
874 if (daemonize) {
875 SERVICE_TABLE_ENTRY service_table[] = {
876 { (char *)QGA_SERVICE_NAME, service_main }, { NULL, NULL } };
877 StartServiceCtrlDispatcher(service_table);
878 } else {
879 g_main_loop_run(ga_state->main_loop);
880 }
881#endif
48ff7a62 882
e3d4d252 883 ga_command_state_cleanup_all(ga_state->command_state);
125b310e 884 ga_channel_free(ga_state->channel);
48ff7a62 885
125b310e 886 if (daemonize) {
f789aa7b 887 unlink(pid_filepath);
125b310e 888 }
48ff7a62 889 return 0;
125b310e
MR
890
891out_bad:
892 if (daemonize) {
f789aa7b 893 unlink(pid_filepath);
125b310e
MR
894 }
895 return EXIT_FAILURE;
48ff7a62 896}