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