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
14 #include "qemu/osdep.h"
15 #include <getopt.h>
16 #include <glib/gstdio.h>
17 #ifndef _WIN32
18 #include <syslog.h>
19 #include <sys/wait.h>
20 #endif
21 #include "qemu/help-texts.h"
22 #include "qobject/json-parser.h"
23 #include "qobject/qdict.h"
24 #include "qobject/qjson.h"
25 #include "guest-agent-core.h"
26 #include "qga-qapi-init-commands.h"
27 #include "qapi/error.h"
28 #include "channel.h"
29 #include "qemu/cutils.h"
30 #include "qemu/help_option.h"
31 #include "qemu/sockets.h"
32 #include "qemu/systemd.h"
33 #include "qemu-version.h"
34 #ifdef _WIN32
35 #include <dbt.h>
36 #include <pdh.h>
37 #include "qga/service-win32.h"
38 #include "qga/vss-win32.h"
39 #endif
40 #include "commands-common.h"
41
42 #ifndef _WIN32
43 #ifdef CONFIG_BSD
44 #define QGA_VIRTIO_PATH_DEFAULT "/dev/vtcon/org.qemu.guest_agent.0"
45 #else /* CONFIG_BSD */
46 #define QGA_VIRTIO_PATH_DEFAULT "/dev/virtio-ports/org.qemu.guest_agent.0"
47 #endif /* CONFIG_BSD */
48 #define QGA_SERIAL_PATH_DEFAULT "/dev/ttyS0"
49 #define QGA_STATE_RELATIVE_DIR "run"
50 #else
51 #define QGA_VIRTIO_PATH_DEFAULT "\\\\.\\Global\\org.qemu.guest_agent.0"
52 #define QGA_STATE_RELATIVE_DIR "qemu-ga"
53 #define QGA_SERIAL_PATH_DEFAULT "COM1"
54 #endif
55 #ifdef CONFIG_FSFREEZE
56 #define QGA_FSFREEZE_HOOK_DEFAULT CONFIG_QEMU_CONFDIR "/fsfreeze-hook"
57 #endif
58 #define QGA_SENTINEL_BYTE 0xFF
59 #define QGA_CONF_DEFAULT CONFIG_QEMU_CONFDIR G_DIR_SEPARATOR_S "qemu-ga.conf"
60 #define QGA_RETRY_INTERVAL 5
61
62 static struct {
63 const char *state_dir;
64 const char *pidfile;
65 } dfl_pathnames;
66
67 typedef struct GAPersistentState {
68 #define QGA_PSTATE_DEFAULT_FD_COUNTER 1000
69 int64_t fd_counter;
70 } GAPersistentState;
71
72 typedef struct GAConfig GAConfig;
73
74 struct GAConfig {
75 char *channel_path;
76 char *method;
77 char *log_filepath;
78 char *pid_filepath;
79 #ifdef CONFIG_FSFREEZE
80 char *fsfreeze_hook;
81 #endif
82 char *state_dir;
83 #ifdef _WIN32
84 const char *service;
85 #endif
86 gchar *bliststr; /* blockedrpcs may point to this string */
87 gchar *aliststr; /* allowedrpcs may point to this string */
88 GList *blockedrpcs;
89 GList *allowedrpcs;
90 int daemonize;
91 GLogLevelFlags log_level;
92 int dumpconf;
93 bool retry_path;
94 };
95
96 struct GAState {
97 JSONMessageParser parser;
98 GMainLoop *main_loop;
99 GAChannel *channel;
100 bool virtio; /* fastpath to check for virtio to deal with poll() quirks */
101 GACommandState *command_state;
102 GLogLevelFlags log_level;
103 FILE *log_file;
104 bool logging_enabled;
105 #ifdef _WIN32
106 GAService service;
107 HANDLE wakeup_event;
108 HANDLE event_log;
109 HANDLE load_avg_wait_handle;
110 HANDLE load_avg_event;
111 HQUERY load_avg_pdh_query;
112 #endif
113 bool delimit_response;
114 bool frozen;
115 GList *blockedrpcs;
116 GList *allowedrpcs;
117 char *state_filepath_isfrozen;
118 struct {
119 const char *log_filepath;
120 const char *pid_filepath;
121 } deferred_options;
122 #ifdef CONFIG_FSFREEZE
123 const char *fsfreeze_hook;
124 #endif
125 gchar *pstate_filepath;
126 GAPersistentState pstate;
127 GAConfig *config;
128 int socket_activation;
129 bool force_exit;
130 };
131
132 struct GAState *ga_state;
133 QmpCommandList ga_commands;
134
135 /* commands that are safe to issue while filesystems are frozen */
136 static const char *ga_freeze_allowlist[] = {
137 "guest-ping",
138 "guest-info",
139 "guest-sync",
140 "guest-sync-delimited",
141 "guest-fsfreeze-status",
142 "guest-fsfreeze-thaw",
143 NULL
144 };
145
146 #ifdef _WIN32
147 DWORD WINAPI service_ctrl_handler(DWORD ctrl, DWORD type, LPVOID data,
148 LPVOID ctx);
149 DWORD WINAPI handle_serial_device_events(DWORD type, LPVOID data);
150 VOID WINAPI service_main(DWORD argc, TCHAR *argv[]);
151 #endif
152 static int run_agent(GAState *s);
153 static void stop_agent(GAState *s, bool requested);
154
155 static void
init_dfl_pathnames(void)156 init_dfl_pathnames(void)
157 {
158 g_autofree char *state = qemu_get_local_state_dir();
159
160 g_assert(dfl_pathnames.state_dir == NULL);
161 g_assert(dfl_pathnames.pidfile == NULL);
162 dfl_pathnames.state_dir = g_build_filename(state, QGA_STATE_RELATIVE_DIR, NULL);
163 dfl_pathnames.pidfile = g_build_filename(state, QGA_STATE_RELATIVE_DIR, "qemu-ga.pid", NULL);
164 }
165
quit_handler(int sig)166 static void quit_handler(int sig)
167 {
168 /* if we're frozen, don't exit unless we're absolutely forced to,
169 * because it's basically impossible for graceful exit to complete
170 * unless all log/pid files are on unfreezable filesystems. there's
171 * also a very likely chance killing the agent before unfreezing
172 * the filesystems is a mistake (or will be viewed as one later).
173 * On Windows the freeze interval is limited to 10 seconds, so
174 * we should quit, but first we should wait for the timeout, thaw
175 * the filesystem and quit.
176 */
177 if (ga_is_frozen(ga_state)) {
178 #ifdef _WIN32
179 int i = 0;
180 Error *err = NULL;
181 HANDLE hEventTimeout;
182
183 g_debug("Thawing filesystems before exiting");
184
185 hEventTimeout = OpenEvent(EVENT_ALL_ACCESS, FALSE, EVENT_NAME_TIMEOUT);
186 if (hEventTimeout) {
187 WaitForSingleObject(hEventTimeout, 0);
188 CloseHandle(hEventTimeout);
189 }
190 qga_vss_fsfreeze(&i, false, NULL, &err);
191 if (err) {
192 g_debug("Error unfreezing filesystems prior to exiting: %s",
193 error_get_pretty(err));
194 error_free(err);
195 }
196 #else
197 return;
198 #endif
199 }
200 g_debug("received signal num %d, quitting", sig);
201
202 stop_agent(ga_state, true);
203 }
204
205 #ifndef _WIN32
register_signal_handlers(void)206 static gboolean register_signal_handlers(void)
207 {
208 struct sigaction sigact;
209 int ret;
210
211 memset(&sigact, 0, sizeof(struct sigaction));
212 sigact.sa_handler = quit_handler;
213
214 ret = sigaction(SIGINT, &sigact, NULL);
215 if (ret == -1) {
216 g_error("error configuring signal handler: %s", strerror(errno));
217 }
218 ret = sigaction(SIGTERM, &sigact, NULL);
219 if (ret == -1) {
220 g_error("error configuring signal handler: %s", strerror(errno));
221 }
222
223 sigact.sa_handler = SIG_IGN;
224 if (sigaction(SIGPIPE, &sigact, NULL) != 0) {
225 g_error("error configuring SIGPIPE signal handler: %s",
226 strerror(errno));
227 }
228
229 return true;
230 }
231
232 /* TODO: use this in place of all post-fork() fclose(std*) callers */
reopen_fd_to_null(int fd)233 void reopen_fd_to_null(int fd)
234 {
235 int nullfd;
236
237 nullfd = open("/dev/null", O_RDWR);
238 if (nullfd < 0) {
239 return;
240 }
241
242 dup2(nullfd, fd);
243
244 if (nullfd != fd) {
245 close(nullfd);
246 }
247 }
248 #endif
249
usage(const char * cmd)250 static void usage(const char *cmd)
251 {
252 #ifdef CONFIG_FSFREEZE
253 g_autofree char *fsfreeze_hook = get_relocated_path(QGA_FSFREEZE_HOOK_DEFAULT);
254 #endif
255 g_autofree char *conf_path = get_relocated_path(QGA_CONF_DEFAULT);
256
257 printf(
258 "Usage: %s [-m <method> -p <path>] [<options>]\n"
259 "QEMU Guest Agent " QEMU_FULL_VERSION "\n"
260 QEMU_COPYRIGHT "\n"
261 "\n"
262 " -c, --config=PATH configuration file path (default is\n"
263 " %s/qemu-ga.conf\n"
264 " unless overridden by the QGA_CONF environment variable)\n"
265 " -m, --method transport method: one of unix-listen, virtio-serial,\n"
266 " isa-serial, or vsock-listen (virtio-serial is the default)\n"
267 " -p, --path device/socket path (the default for virtio-serial is:\n"
268 " %s,\n"
269 " the default for isa-serial is:\n"
270 " %s).\n"
271 " Socket addresses for vsock-listen are written as\n"
272 " <cid>:<port>.\n"
273 " -l, --logfile set logfile path, logs to stderr by default\n"
274 " -f, --pidfile specify pidfile (default is %s)\n"
275 #ifdef CONFIG_FSFREEZE
276 " -F, --fsfreeze-hook\n"
277 " enable fsfreeze hook. Accepts an optional argument that\n"
278 " specifies script to run on freeze/thaw. Script will be\n"
279 " called with 'freeze'/'thaw' arguments accordingly.\n"
280 " (default is %s)\n"
281 " If using -F with an argument, do not follow -F with a\n"
282 " space.\n"
283 " (for example: -F/var/run/fsfreezehook.sh)\n"
284 #endif
285 " -t, --statedir specify dir to store state information (absolute paths\n"
286 " only, default is %s)\n"
287 " -v, --verbose log extra debugging information\n"
288 " -V, --version print version information and exit\n"
289 " -d, --daemonize become a daemon\n"
290 #ifdef _WIN32
291 " -s, --service service commands: install, uninstall, vss-install, vss-uninstall\n"
292 #endif
293 " -b, --block-rpcs comma-separated list of RPCs to disable (no spaces,\n"
294 " use \"--block-rpcs=help\" to list available RPCs)\n"
295 " -a, --allow-rpcs comma-separated list of RPCs to enable (no spaces,\n"
296 " use \"--allow-rpcs=help\" to list available RPCs)\n"
297 " -D, --dump-conf dump a qemu-ga config file based on current config\n"
298 " options / command-line parameters to stdout\n"
299 " -r, --retry-path attempt re-opening path if it's unavailable or closed\n"
300 " due to an error which may be recoverable in the future\n"
301 " (virtio-serial driver re-install, serial device hot\n"
302 " plug/unplug, etc.)\n"
303 " -h, --help display this help and exit\n"
304 "\n"
305 QEMU_HELP_BOTTOM "\n",
306 cmd, conf_path, QGA_VIRTIO_PATH_DEFAULT, QGA_SERIAL_PATH_DEFAULT,
307 dfl_pathnames.pidfile,
308 #ifdef CONFIG_FSFREEZE
309 fsfreeze_hook,
310 #endif
311 dfl_pathnames.state_dir);
312 }
313
ga_log_level_str(GLogLevelFlags level)314 static const char *ga_log_level_str(GLogLevelFlags level)
315 {
316 switch (level & G_LOG_LEVEL_MASK) {
317 case G_LOG_LEVEL_ERROR:
318 return "error";
319 case G_LOG_LEVEL_CRITICAL:
320 return "critical";
321 case G_LOG_LEVEL_WARNING:
322 return "warning";
323 case G_LOG_LEVEL_MESSAGE:
324 return "message";
325 case G_LOG_LEVEL_INFO:
326 return "info";
327 case G_LOG_LEVEL_DEBUG:
328 return "debug";
329 default:
330 return "user";
331 }
332 }
333
ga_logging_enabled(GAState * s)334 bool ga_logging_enabled(GAState *s)
335 {
336 return s->logging_enabled;
337 }
338
ga_disable_logging(GAState * s)339 void ga_disable_logging(GAState *s)
340 {
341 s->logging_enabled = false;
342 }
343
ga_enable_logging(GAState * s)344 void ga_enable_logging(GAState *s)
345 {
346 s->logging_enabled = true;
347 }
348
glib_log_level_to_system(int level)349 static int glib_log_level_to_system(int level)
350 {
351 switch (level) {
352 #ifndef _WIN32
353 case G_LOG_LEVEL_ERROR:
354 return LOG_ERR;
355 case G_LOG_LEVEL_CRITICAL:
356 return LOG_CRIT;
357 case G_LOG_LEVEL_WARNING:
358 return LOG_WARNING;
359 case G_LOG_LEVEL_MESSAGE:
360 return LOG_NOTICE;
361 case G_LOG_LEVEL_DEBUG:
362 return LOG_DEBUG;
363 case G_LOG_LEVEL_INFO:
364 default:
365 return LOG_INFO;
366 #else
367 case G_LOG_LEVEL_ERROR:
368 case G_LOG_LEVEL_CRITICAL:
369 return EVENTLOG_ERROR_TYPE;
370 case G_LOG_LEVEL_WARNING:
371 return EVENTLOG_WARNING_TYPE;
372 case G_LOG_LEVEL_MESSAGE:
373 case G_LOG_LEVEL_INFO:
374 case G_LOG_LEVEL_DEBUG:
375 default:
376 return EVENTLOG_INFORMATION_TYPE;
377 #endif
378 }
379 }
380
ga_log(const gchar * domain,GLogLevelFlags level,const gchar * msg,gpointer opaque)381 static void ga_log(const gchar *domain, GLogLevelFlags level,
382 const gchar *msg, gpointer opaque)
383 {
384 GAState *s = opaque;
385 const char *level_str = ga_log_level_str(level);
386
387 if (!ga_logging_enabled(s)) {
388 return;
389 }
390
391 level &= G_LOG_LEVEL_MASK;
392 if (g_strcmp0(domain, "syslog") == 0) {
393 #ifndef _WIN32
394 syslog(glib_log_level_to_system(level), "%s: %s", level_str, msg);
395 #else
396 ReportEvent(s->event_log, glib_log_level_to_system(level),
397 0, 1, NULL, 1, 0, &msg, NULL);
398 #endif
399 } else if (level & s->log_level) {
400 g_autoptr(GDateTime) now = g_date_time_new_now_utc();
401 g_autofree char *nowstr = g_date_time_format(now, "%s.%f");
402 fprintf(s->log_file, "%s: %s: %s\n", nowstr, level_str, msg);
403 fflush(s->log_file);
404 }
405 }
406
ga_set_response_delimited(GAState * s)407 void ga_set_response_delimited(GAState *s)
408 {
409 s->delimit_response = true;
410 }
411
ga_open_logfile(const char * logfile)412 static FILE *ga_open_logfile(const char *logfile)
413 {
414 FILE *f;
415
416 f = fopen(logfile, "a");
417 if (!f) {
418 return NULL;
419 }
420
421 qemu_set_cloexec(fileno(f));
422 return f;
423 }
424
ga_strcmp(gconstpointer str1,gconstpointer str2)425 static gint ga_strcmp(gconstpointer str1, gconstpointer str2)
426 {
427 return strcmp(str1, str2);
428 }
429
ga_command_is_allowed(const QmpCommand * cmd,GAState * state)430 static bool ga_command_is_allowed(const QmpCommand *cmd, GAState *state)
431 {
432 int i = 0;
433 GAConfig *config = state->config;
434 const char *name = qmp_command_name(cmd);
435 /* Fallback policy is allow everything */
436 bool allowed = true;
437
438 if (config->allowedrpcs) {
439 /*
440 * If an allow-list is given, this changes the fallback
441 * policy to deny everything
442 */
443 allowed = false;
444
445 if (g_list_find_custom(config->allowedrpcs, name, ga_strcmp) != NULL) {
446 allowed = true;
447 }
448 }
449
450 /*
451 * If both allowedrpcs and blockedrpcs are set, the blocked
452 * list will take priority
453 */
454 if (config->blockedrpcs) {
455 if (g_list_find_custom(config->blockedrpcs, name, ga_strcmp) != NULL) {
456 allowed = false;
457 }
458 }
459
460 /*
461 * If frozen, this filtering must take priority over
462 * absolutely everything
463 */
464 if (state->frozen) {
465 allowed = false;
466
467 while (ga_freeze_allowlist[i] != NULL) {
468 if (strcmp(name, ga_freeze_allowlist[i]) == 0) {
469 allowed = true;
470 }
471 i++;
472 }
473 }
474
475 return allowed;
476 }
477
ga_apply_command_filters_iter(const QmpCommand * cmd,void * opaque)478 static void ga_apply_command_filters_iter(const QmpCommand *cmd, void *opaque)
479 {
480 GAState *state = opaque;
481 bool want = ga_command_is_allowed(cmd, state);
482 bool have = qmp_command_is_enabled(cmd);
483 const char *name = qmp_command_name(cmd);
484
485 if (want == have) {
486 return;
487 }
488
489 if (have) {
490 g_debug("disabling command: %s", name);
491 qmp_disable_command(&ga_commands, name, "the command is not allowed");
492 } else {
493 g_debug("enabling command: %s", name);
494 qmp_enable_command(&ga_commands, name);
495 }
496 }
497
ga_apply_command_filters(GAState * state)498 static void ga_apply_command_filters(GAState *state)
499 {
500 qmp_for_each_command(&ga_commands, ga_apply_command_filters_iter, state);
501 }
502
ga_create_file(const char * path)503 static bool ga_create_file(const char *path)
504 {
505 int fd = open(path, O_CREAT | O_WRONLY, S_IWUSR | S_IRUSR);
506 if (fd == -1) {
507 g_warning("unable to open/create file %s: %s", path, strerror(errno));
508 return false;
509 }
510 close(fd);
511 return true;
512 }
513
ga_delete_file(const char * path)514 static bool ga_delete_file(const char *path)
515 {
516 int ret = unlink(path);
517 if (ret == -1) {
518 g_warning("unable to delete file: %s: %s", path, strerror(errno));
519 return false;
520 }
521
522 return true;
523 }
524
ga_is_frozen(GAState * s)525 bool ga_is_frozen(GAState *s)
526 {
527 return s->frozen;
528 }
529
ga_set_frozen(GAState * s)530 void ga_set_frozen(GAState *s)
531 {
532 if (ga_is_frozen(s)) {
533 return;
534 }
535 g_warning("disabling logging due to filesystem freeze");
536 s->frozen = true;
537 if (!ga_create_file(s->state_filepath_isfrozen)) {
538 g_warning("unable to create %s, fsfreeze may not function properly",
539 s->state_filepath_isfrozen);
540 }
541 ga_apply_command_filters(s);
542 ga_disable_logging(s);
543 }
544
ga_unset_frozen(GAState * s)545 void ga_unset_frozen(GAState *s)
546 {
547 if (!ga_is_frozen(s)) {
548 return;
549 }
550
551 /* if we delayed creation/opening of pid/log files due to being
552 * in a frozen state at start up, do it now
553 */
554 if (s->deferred_options.log_filepath) {
555 s->log_file = ga_open_logfile(s->deferred_options.log_filepath);
556 if (!s->log_file) {
557 s->log_file = stderr;
558 }
559 s->deferred_options.log_filepath = NULL;
560 }
561 ga_enable_logging(s);
562 g_warning("logging re-enabled due to filesystem unfreeze");
563 if (s->deferred_options.pid_filepath) {
564 Error *err = NULL;
565
566 if (!qemu_write_pidfile(s->deferred_options.pid_filepath, &err)) {
567 g_warning("%s", error_get_pretty(err));
568 error_free(err);
569 }
570 s->deferred_options.pid_filepath = NULL;
571 }
572
573 /* enable all disabled, non-blocked and allowed commands */
574 s->frozen = false;
575 if (!ga_delete_file(s->state_filepath_isfrozen)) {
576 g_warning("unable to delete %s, fsfreeze may not function properly",
577 s->state_filepath_isfrozen);
578 }
579 ga_apply_command_filters(s);
580 }
581
582 #ifdef CONFIG_FSFREEZE
ga_fsfreeze_hook(GAState * s)583 const char *ga_fsfreeze_hook(GAState *s)
584 {
585 return s->fsfreeze_hook;
586 }
587 #endif
588
589 #ifdef _WIN32
ga_set_load_avg_wait_handle(GAState * s,HANDLE wait_handle)590 void ga_set_load_avg_wait_handle(GAState *s, HANDLE wait_handle)
591 {
592 s->load_avg_wait_handle = wait_handle;
593 }
ga_set_load_avg_event(GAState * s,HANDLE event)594 void ga_set_load_avg_event(GAState *s, HANDLE event)
595 {
596 s->load_avg_event = event;
597 }
ga_set_load_avg_pdh_query(GAState * s,HQUERY query)598 void ga_set_load_avg_pdh_query(GAState *s, HQUERY query)
599 {
600 s->load_avg_pdh_query = query;
601 }
ga_get_load_avg_pdh_query(GAState * s)602 HQUERY ga_get_load_avg_pdh_query(GAState *s)
603 {
604 return s->load_avg_pdh_query;
605 }
606 #endif
607
become_daemon(const char * pidfile)608 static void become_daemon(const char *pidfile)
609 {
610 #ifndef _WIN32
611 pid_t pid, sid;
612
613 pid = fork();
614 if (pid < 0) {
615 exit(EXIT_FAILURE);
616 }
617 if (pid > 0) {
618 exit(EXIT_SUCCESS);
619 }
620
621 if (pidfile) {
622 Error *err = NULL;
623
624 if (!qemu_write_pidfile(pidfile, &err)) {
625 g_critical("%s", error_get_pretty(err));
626 error_free(err);
627 exit(EXIT_FAILURE);
628 }
629 }
630
631 umask(S_IRWXG | S_IRWXO);
632 sid = setsid();
633 if (sid < 0) {
634 goto fail;
635 }
636 if ((chdir("/")) < 0) {
637 goto fail;
638 }
639
640 reopen_fd_to_null(STDIN_FILENO);
641 reopen_fd_to_null(STDOUT_FILENO);
642 reopen_fd_to_null(STDERR_FILENO);
643 return;
644
645 fail:
646 if (pidfile) {
647 unlink(pidfile);
648 }
649 g_critical("failed to daemonize");
650 exit(EXIT_FAILURE);
651 #endif
652 }
653
send_response(GAState * s,const QDict * rsp)654 static int send_response(GAState *s, const QDict *rsp)
655 {
656 GString *response;
657 GIOStatus status;
658
659 g_assert(s->channel);
660
661 if (!rsp) {
662 return 0;
663 }
664
665 response = qobject_to_json(QOBJECT(rsp));
666 if (!response) {
667 return -EINVAL;
668 }
669
670 if (s->delimit_response) {
671 s->delimit_response = false;
672 g_string_prepend_c(response, QGA_SENTINEL_BYTE);
673 }
674
675 g_string_append_c(response, '\n');
676 status = ga_channel_write_all(s->channel, response->str, response->len);
677 g_string_free(response, true);
678 if (status != G_IO_STATUS_NORMAL) {
679 return -EIO;
680 }
681
682 return 0;
683 }
684
685 /* handle requests/control events coming in over the channel */
process_event(void * opaque,QObject * obj,Error * err)686 static void process_event(void *opaque, QObject *obj, Error *err)
687 {
688 GAState *s = opaque;
689 QDict *rsp;
690 int ret;
691
692 g_debug("process_event: called");
693 assert(!obj != !err);
694 if (err) {
695 rsp = qmp_error_response(err);
696 goto end;
697 }
698
699 g_debug("processing command");
700 rsp = qmp_dispatch(&ga_commands, obj, false, NULL);
701
702 end:
703 ret = send_response(s, rsp);
704 if (ret < 0) {
705 g_warning("error sending error response: %s", strerror(-ret));
706 }
707 qobject_unref(rsp);
708 qobject_unref(obj);
709 }
710
711 /* false return signals GAChannel to close the current client connection */
channel_event_cb(GIOCondition condition,gpointer data)712 static gboolean channel_event_cb(GIOCondition condition, gpointer data)
713 {
714 GAState *s = data;
715 gchar buf[QGA_READ_COUNT_DEFAULT + 1];
716 gsize count;
717 GIOStatus status = ga_channel_read(s->channel, buf, QGA_READ_COUNT_DEFAULT, &count);
718 switch (status) {
719 case G_IO_STATUS_ERROR:
720 g_warning("error reading channel");
721 stop_agent(s, false);
722 return false;
723 case G_IO_STATUS_NORMAL:
724 buf[count] = 0;
725 g_debug("read data, count: %d, data: %s", (int)count, buf);
726 json_message_parser_feed(&s->parser, (char *)buf, (int)count);
727 break;
728 case G_IO_STATUS_EOF:
729 g_debug("received EOF");
730 if (!s->virtio) {
731 return false;
732 }
733 /* fall through */
734 case G_IO_STATUS_AGAIN:
735 /* virtio causes us to spin here when no process is attached to
736 * host-side chardev. sleep a bit to mitigate this
737 */
738 if (s->virtio) {
739 g_usleep(G_USEC_PER_SEC / 10);
740 }
741 return true;
742 default:
743 g_warning("unknown channel read status, closing");
744 return false;
745 }
746 return true;
747 }
748
channel_init(GAState * s,const gchar * method,const gchar * path,int listen_fd)749 static gboolean channel_init(GAState *s, const gchar *method, const gchar *path,
750 int listen_fd)
751 {
752 GAChannelMethod channel_method;
753
754 if (strcmp(method, "virtio-serial") == 0) {
755 s->virtio = true; /* virtio requires special handling in some cases */
756 channel_method = GA_CHANNEL_VIRTIO_SERIAL;
757 } else if (strcmp(method, "isa-serial") == 0) {
758 channel_method = GA_CHANNEL_ISA_SERIAL;
759 } else if (strcmp(method, "unix-listen") == 0) {
760 channel_method = GA_CHANNEL_UNIX_LISTEN;
761 } else if (strcmp(method, "vsock-listen") == 0) {
762 channel_method = GA_CHANNEL_VSOCK_LISTEN;
763 } else {
764 g_critical("unsupported channel method/type: %s", method);
765 return false;
766 }
767
768 s->channel = ga_channel_new(channel_method, path, listen_fd,
769 channel_event_cb, s);
770 if (!s->channel) {
771 g_critical("failed to create guest agent channel");
772 return false;
773 }
774
775 return true;
776 }
777
778 #ifdef _WIN32
handle_serial_device_events(DWORD type,LPVOID data)779 DWORD WINAPI handle_serial_device_events(DWORD type, LPVOID data)
780 {
781 DWORD ret = NO_ERROR;
782 PDEV_BROADCAST_HDR broadcast_header = (PDEV_BROADCAST_HDR)data;
783
784 if (broadcast_header->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE) {
785 switch (type) {
786 /* Device inserted */
787 case DBT_DEVICEARRIVAL:
788 /* Start QEMU-ga's service */
789 if (!SetEvent(ga_state->wakeup_event)) {
790 ret = GetLastError();
791 }
792 break;
793 /* Device removed */
794 case DBT_DEVICEQUERYREMOVE:
795 case DBT_DEVICEREMOVEPENDING:
796 case DBT_DEVICEREMOVECOMPLETE:
797 /* Stop QEMU-ga's service */
798 if (!ResetEvent(ga_state->wakeup_event)) {
799 ret = GetLastError();
800 }
801 break;
802 default:
803 ret = ERROR_CALL_NOT_IMPLEMENTED;
804 }
805 }
806 return ret;
807 }
808
service_ctrl_handler(DWORD ctrl,DWORD type,LPVOID data,LPVOID ctx)809 DWORD WINAPI service_ctrl_handler(DWORD ctrl, DWORD type, LPVOID data,
810 LPVOID ctx)
811 {
812 DWORD ret = NO_ERROR;
813 GAService *service = &ga_state->service;
814
815 switch (ctrl) {
816 case SERVICE_CONTROL_STOP:
817 case SERVICE_CONTROL_SHUTDOWN:
818 quit_handler(SIGTERM);
819 SetEvent(ga_state->wakeup_event);
820 service->status.dwCurrentState = SERVICE_STOP_PENDING;
821 SetServiceStatus(service->status_handle, &service->status);
822 break;
823 case SERVICE_CONTROL_DEVICEEVENT:
824 handle_serial_device_events(type, data);
825 break;
826
827 default:
828 ret = ERROR_CALL_NOT_IMPLEMENTED;
829 }
830 return ret;
831 }
832
service_main(DWORD argc,TCHAR * argv[])833 VOID WINAPI service_main(DWORD argc, TCHAR *argv[])
834 {
835 GAService *service = &ga_state->service;
836
837 service->status_handle = RegisterServiceCtrlHandlerEx(QGA_SERVICE_NAME,
838 service_ctrl_handler, NULL);
839
840 if (service->status_handle == 0) {
841 g_critical("Failed to register extended requests function!\n");
842 return;
843 }
844
845 service->status.dwServiceType = SERVICE_WIN32;
846 service->status.dwCurrentState = SERVICE_RUNNING;
847 service->status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
848 service->status.dwWin32ExitCode = NO_ERROR;
849 service->status.dwServiceSpecificExitCode = NO_ERROR;
850 service->status.dwCheckPoint = 0;
851 service->status.dwWaitHint = 0;
852 DEV_BROADCAST_DEVICEINTERFACE notification_filter;
853 ZeroMemory(¬ification_filter, sizeof(notification_filter));
854 notification_filter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
855 notification_filter.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE);
856 notification_filter.dbcc_classguid = GUID_VIOSERIAL_PORT;
857
858 service->device_notification_handle =
859 RegisterDeviceNotification(service->status_handle,
860 ¬ification_filter, DEVICE_NOTIFY_SERVICE_HANDLE);
861 if (!service->device_notification_handle) {
862 g_critical("Failed to register device notification handle!\n");
863 return;
864 }
865 SetServiceStatus(service->status_handle, &service->status);
866
867 run_agent(ga_state);
868
869 UnregisterDeviceNotification(service->device_notification_handle);
870 service->status.dwCurrentState = SERVICE_STOPPED;
871 SetServiceStatus(service->status_handle, &service->status);
872 }
873 #endif
874
set_persistent_state_defaults(GAPersistentState * pstate)875 static void set_persistent_state_defaults(GAPersistentState *pstate)
876 {
877 g_assert(pstate);
878 pstate->fd_counter = QGA_PSTATE_DEFAULT_FD_COUNTER;
879 }
880
persistent_state_from_keyfile(GAPersistentState * pstate,GKeyFile * keyfile)881 static void persistent_state_from_keyfile(GAPersistentState *pstate,
882 GKeyFile *keyfile)
883 {
884 g_assert(pstate);
885 g_assert(keyfile);
886 /* if any fields are missing, either because the file was tampered with
887 * by agents of chaos, or because the field wasn't present at the time the
888 * file was created, the best we can ever do is start over with the default
889 * values. so load them now, and ignore any errors in accessing key-value
890 * pairs
891 */
892 set_persistent_state_defaults(pstate);
893
894 if (g_key_file_has_key(keyfile, "global", "fd_counter", NULL)) {
895 pstate->fd_counter =
896 g_key_file_get_integer(keyfile, "global", "fd_counter", NULL);
897 }
898 }
899
persistent_state_to_keyfile(const GAPersistentState * pstate,GKeyFile * keyfile)900 static void persistent_state_to_keyfile(const GAPersistentState *pstate,
901 GKeyFile *keyfile)
902 {
903 g_assert(pstate);
904 g_assert(keyfile);
905
906 g_key_file_set_integer(keyfile, "global", "fd_counter", pstate->fd_counter);
907 }
908
write_persistent_state(const GAPersistentState * pstate,const gchar * path)909 static gboolean write_persistent_state(const GAPersistentState *pstate,
910 const gchar *path)
911 {
912 GKeyFile *keyfile = g_key_file_new();
913 GError *gerr = NULL;
914 gboolean ret = true;
915 gchar *data = NULL;
916 gsize data_len;
917
918 g_assert(pstate);
919
920 persistent_state_to_keyfile(pstate, keyfile);
921 data = g_key_file_to_data(keyfile, &data_len, &gerr);
922 if (gerr) {
923 g_critical("failed to convert persistent state to string: %s",
924 gerr->message);
925 ret = false;
926 goto out;
927 }
928
929 g_file_set_contents(path, data, data_len, &gerr);
930 if (gerr) {
931 g_critical("failed to write persistent state to %s: %s",
932 path, gerr->message);
933 ret = false;
934 goto out;
935 }
936
937 out:
938 if (gerr) {
939 g_error_free(gerr);
940 }
941 if (keyfile) {
942 g_key_file_free(keyfile);
943 }
944 g_free(data);
945 return ret;
946 }
947
read_persistent_state(GAPersistentState * pstate,const gchar * path,gboolean frozen)948 static gboolean read_persistent_state(GAPersistentState *pstate,
949 const gchar *path, gboolean frozen)
950 {
951 GKeyFile *keyfile = NULL;
952 GError *gerr = NULL;
953 struct stat st;
954 gboolean ret = true;
955
956 g_assert(pstate);
957
958 if (stat(path, &st) == -1) {
959 /* it's okay if state file doesn't exist, but any other error
960 * indicates a permissions issue or some other misconfiguration
961 * that we likely won't be able to recover from.
962 */
963 if (errno != ENOENT) {
964 g_critical("unable to access state file at path %s: %s",
965 path, strerror(errno));
966 ret = false;
967 goto out;
968 }
969
970 /* file doesn't exist. initialize state to default values and
971 * attempt to save now. (we could wait till later when we have
972 * modified state we need to commit, but if there's a problem,
973 * such as a missing parent directory, we want to catch it now)
974 *
975 * there is a potential scenario where someone either managed to
976 * update the agent from a version that didn't use a key store
977 * while qemu-ga thought the filesystem was frozen, or
978 * deleted the key store prior to issuing a fsfreeze, prior
979 * to restarting the agent. in this case we go ahead and defer
980 * initial creation till we actually have modified state to
981 * write, otherwise fail to recover from freeze.
982 */
983 set_persistent_state_defaults(pstate);
984 if (!frozen) {
985 ret = write_persistent_state(pstate, path);
986 if (!ret) {
987 g_critical("unable to create state file at path %s", path);
988 ret = false;
989 goto out;
990 }
991 }
992 ret = true;
993 goto out;
994 }
995
996 keyfile = g_key_file_new();
997 g_key_file_load_from_file(keyfile, path, 0, &gerr);
998 if (gerr) {
999 g_critical("error loading persistent state from path: %s, %s",
1000 path, gerr->message);
1001 ret = false;
1002 goto out;
1003 }
1004
1005 persistent_state_from_keyfile(pstate, keyfile);
1006
1007 out:
1008 if (keyfile) {
1009 g_key_file_free(keyfile);
1010 }
1011 if (gerr) {
1012 g_error_free(gerr);
1013 }
1014
1015 return ret;
1016 }
1017
ga_get_fd_handle(GAState * s,Error ** errp)1018 int64_t ga_get_fd_handle(GAState *s, Error **errp)
1019 {
1020 int64_t handle;
1021
1022 g_assert(s->pstate_filepath);
1023 /*
1024 * We block commands and avoid operations that potentially require
1025 * writing to disk when we're in a frozen state. this includes opening
1026 * new files, so we should never get here in that situation
1027 */
1028 g_assert(!ga_is_frozen(s));
1029
1030 handle = s->pstate.fd_counter++;
1031
1032 /* This should never happen on a reasonable timeframe, as guest-file-open
1033 * would have to be issued 2^63 times */
1034 if (s->pstate.fd_counter == INT64_MAX) {
1035 abort();
1036 }
1037
1038 if (!write_persistent_state(&s->pstate, s->pstate_filepath)) {
1039 error_setg(errp, "failed to commit persistent state to disk");
1040 return -1;
1041 }
1042
1043 return handle;
1044 }
1045
ga_print_cmd(const QmpCommand * cmd,void * opaque)1046 static void ga_print_cmd(const QmpCommand *cmd, void *opaque)
1047 {
1048 printf("%s\n", qmp_command_name(cmd));
1049 }
1050
split_list(const gchar * str,const gchar * delim)1051 static GList *split_list(const gchar *str, const gchar *delim)
1052 {
1053 GList *list = NULL;
1054 int i;
1055 gchar **strv;
1056
1057 strv = g_strsplit(str, delim, -1);
1058 for (i = 0; strv[i]; i++) {
1059 list = g_list_prepend(list, strv[i]);
1060 }
1061 g_free(strv);
1062
1063 return list;
1064 }
1065
config_load(GAConfig * config,const char * confpath,bool required)1066 static void config_load(GAConfig *config, const char *confpath, bool required)
1067 {
1068 GError *gerr = NULL;
1069 GKeyFile *keyfile;
1070
1071 /* read system config */
1072 keyfile = g_key_file_new();
1073 if (!g_key_file_load_from_file(keyfile, confpath, 0, &gerr)) {
1074 goto end;
1075 }
1076 if (g_key_file_has_key(keyfile, "general", "daemon", NULL)) {
1077 config->daemonize =
1078 g_key_file_get_boolean(keyfile, "general", "daemon", &gerr);
1079 }
1080 if (g_key_file_has_key(keyfile, "general", "method", NULL)) {
1081 config->method =
1082 g_key_file_get_string(keyfile, "general", "method", &gerr);
1083 }
1084 if (g_key_file_has_key(keyfile, "general", "path", NULL)) {
1085 config->channel_path =
1086 g_key_file_get_string(keyfile, "general", "path", &gerr);
1087 }
1088 if (g_key_file_has_key(keyfile, "general", "logfile", NULL)) {
1089 config->log_filepath =
1090 g_key_file_get_string(keyfile, "general", "logfile", &gerr);
1091 }
1092 if (g_key_file_has_key(keyfile, "general", "pidfile", NULL)) {
1093 config->pid_filepath =
1094 g_key_file_get_string(keyfile, "general", "pidfile", &gerr);
1095 }
1096 #ifdef CONFIG_FSFREEZE
1097 if (g_key_file_has_key(keyfile, "general", "fsfreeze-hook", NULL)) {
1098 config->fsfreeze_hook =
1099 g_key_file_get_string(keyfile,
1100 "general", "fsfreeze-hook", &gerr);
1101 }
1102 #endif
1103 if (g_key_file_has_key(keyfile, "general", "statedir", NULL)) {
1104 config->state_dir =
1105 g_key_file_get_string(keyfile, "general", "statedir", &gerr);
1106 }
1107 if (g_key_file_has_key(keyfile, "general", "verbose", NULL) &&
1108 g_key_file_get_boolean(keyfile, "general", "verbose", &gerr)) {
1109 /* enable all log levels */
1110 config->log_level = G_LOG_LEVEL_MASK;
1111 }
1112 if (g_key_file_has_key(keyfile, "general", "retry-path", NULL)) {
1113 config->retry_path =
1114 g_key_file_get_boolean(keyfile, "general", "retry-path", &gerr);
1115 }
1116
1117 if (g_key_file_has_key(keyfile, "general", "block-rpcs", NULL)) {
1118 config->bliststr =
1119 g_key_file_get_string(keyfile, "general", "block-rpcs", &gerr);
1120 config->blockedrpcs = g_list_concat(config->blockedrpcs,
1121 split_list(config->bliststr, ","));
1122 }
1123 if (g_key_file_has_key(keyfile, "general", "allow-rpcs", NULL)) {
1124 config->aliststr =
1125 g_key_file_get_string(keyfile, "general", "allow-rpcs", &gerr);
1126 config->allowedrpcs = g_list_concat(config->allowedrpcs,
1127 split_list(config->aliststr, ","));
1128 }
1129
1130 end:
1131 g_key_file_free(keyfile);
1132 if (gerr && (required ||
1133 !(gerr->domain == G_FILE_ERROR && gerr->code == G_FILE_ERROR_NOENT))) {
1134 g_critical("error loading configuration from path: %s, %s",
1135 confpath, gerr->message);
1136 exit(EXIT_FAILURE);
1137 }
1138 g_clear_error(&gerr);
1139 }
1140
list_join(GList * list,const gchar separator)1141 static gchar *list_join(GList *list, const gchar separator)
1142 {
1143 GString *str = g_string_new("");
1144
1145 while (list) {
1146 str = g_string_append(str, (gchar *)list->data);
1147 list = g_list_next(list);
1148 if (list) {
1149 str = g_string_append_c(str, separator);
1150 }
1151 }
1152
1153 return g_string_free(str, FALSE);
1154 }
1155
config_dump(GAConfig * config)1156 static void config_dump(GAConfig *config)
1157 {
1158 GError *error = NULL;
1159 GKeyFile *keyfile;
1160 gchar *tmp;
1161
1162 keyfile = g_key_file_new();
1163 g_assert(keyfile);
1164
1165 g_key_file_set_boolean(keyfile, "general", "daemon", config->daemonize);
1166 g_key_file_set_string(keyfile, "general", "method", config->method);
1167 if (config->channel_path) {
1168 g_key_file_set_string(keyfile, "general", "path", config->channel_path);
1169 }
1170 if (config->log_filepath) {
1171 g_key_file_set_string(keyfile, "general", "logfile",
1172 config->log_filepath);
1173 }
1174 g_key_file_set_string(keyfile, "general", "pidfile", config->pid_filepath);
1175 #ifdef CONFIG_FSFREEZE
1176 if (config->fsfreeze_hook) {
1177 g_key_file_set_string(keyfile, "general", "fsfreeze-hook",
1178 config->fsfreeze_hook);
1179 }
1180 #endif
1181 g_key_file_set_string(keyfile, "general", "statedir", config->state_dir);
1182 g_key_file_set_boolean(keyfile, "general", "verbose",
1183 config->log_level == G_LOG_LEVEL_MASK);
1184 g_key_file_set_boolean(keyfile, "general", "retry-path",
1185 config->retry_path);
1186 tmp = list_join(config->blockedrpcs, ',');
1187 g_key_file_set_string(keyfile, "general", "block-rpcs", tmp);
1188 g_free(tmp);
1189 tmp = list_join(config->allowedrpcs, ',');
1190 g_key_file_set_string(keyfile, "general", "allow-rpcs", tmp);
1191 g_free(tmp);
1192
1193 tmp = g_key_file_to_data(keyfile, NULL, &error);
1194 if (error) {
1195 g_critical("Failed to dump keyfile: %s", error->message);
1196 g_clear_error(&error);
1197 } else {
1198 printf("%s", tmp);
1199 }
1200
1201 g_free(tmp);
1202 g_key_file_free(keyfile);
1203 }
1204
config_parse(GAConfig * config,int argc,char ** argv)1205 static void config_parse(GAConfig *config, int argc, char **argv)
1206 {
1207 const char *sopt = "hVvdc:m:p:l:f:F::b:a:s:t:Dr";
1208 int opt_ind = 0, ch;
1209 const struct option lopt[] = {
1210 { "help", 0, NULL, 'h' },
1211 { "version", 0, NULL, 'V' },
1212 { "config", 1, NULL, 'c' },
1213 { "dump-conf", 0, NULL, 'D' },
1214 { "logfile", 1, NULL, 'l' },
1215 { "pidfile", 1, NULL, 'f' },
1216 #ifdef CONFIG_FSFREEZE
1217 { "fsfreeze-hook", 2, NULL, 'F' },
1218 #endif
1219 { "verbose", 0, NULL, 'v' },
1220 { "method", 1, NULL, 'm' },
1221 { "path", 1, NULL, 'p' },
1222 { "daemonize", 0, NULL, 'd' },
1223 { "block-rpcs", 1, NULL, 'b' },
1224 { "allow-rpcs", 1, NULL, 'a' },
1225 #ifdef _WIN32
1226 { "service", 1, NULL, 's' },
1227 #endif
1228 { "statedir", 1, NULL, 't' },
1229 { "retry-path", 0, NULL, 'r' },
1230 { NULL, 0, NULL, 0 }
1231 };
1232 g_autofree char *confpath = g_strdup(g_getenv("QGA_CONF")) ?:
1233 get_relocated_path(QGA_CONF_DEFAULT);
1234 bool confrequired = false;
1235
1236 while ((ch = getopt_long(argc, argv, sopt, lopt, NULL)) != -1) {
1237 switch (ch) {
1238 case 'c':
1239 g_free(confpath);
1240 confpath = g_strdup(optarg);
1241 confrequired = true;
1242 break;
1243 default:
1244 break;
1245 }
1246 }
1247
1248 config_load(config, confpath, confrequired);
1249
1250 /* Reset for second pass */
1251 optind = 1;
1252
1253 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
1254 switch (ch) {
1255 case 'm':
1256 g_free(config->method);
1257 config->method = g_strdup(optarg);
1258 break;
1259 case 'p':
1260 g_free(config->channel_path);
1261 config->channel_path = g_strdup(optarg);
1262 break;
1263 case 'l':
1264 g_free(config->log_filepath);
1265 config->log_filepath = g_strdup(optarg);
1266 break;
1267 case 'f':
1268 g_free(config->pid_filepath);
1269 config->pid_filepath = g_strdup(optarg);
1270 break;
1271 #ifdef CONFIG_FSFREEZE
1272 case 'F':
1273 g_free(config->fsfreeze_hook);
1274 config->fsfreeze_hook = optarg ? g_strdup(optarg) : get_relocated_path(QGA_FSFREEZE_HOOK_DEFAULT);
1275 break;
1276 #endif
1277 case 't':
1278 g_free(config->state_dir);
1279 config->state_dir = g_strdup(optarg);
1280 break;
1281 case 'v':
1282 /* enable all log levels */
1283 config->log_level = G_LOG_LEVEL_MASK;
1284 break;
1285 case 'V':
1286 printf("QEMU Guest Agent %s\n", QEMU_VERSION);
1287 exit(EXIT_SUCCESS);
1288 case 'd':
1289 config->daemonize = 1;
1290 break;
1291 case 'D':
1292 config->dumpconf = 1;
1293 break;
1294 case 'r':
1295 config->retry_path = true;
1296 break;
1297 case 'b': {
1298 if (is_help_option(optarg)) {
1299 qmp_for_each_command(&ga_commands, ga_print_cmd, NULL);
1300 exit(EXIT_SUCCESS);
1301 }
1302 config->blockedrpcs = g_list_concat(config->blockedrpcs,
1303 split_list(optarg, ","));
1304 break;
1305 }
1306 case 'a': {
1307 if (is_help_option(optarg)) {
1308 qmp_for_each_command(&ga_commands, ga_print_cmd, NULL);
1309 exit(EXIT_SUCCESS);
1310 }
1311 config->allowedrpcs = g_list_concat(config->allowedrpcs,
1312 split_list(optarg, ","));
1313 break;
1314 }
1315 #ifdef _WIN32
1316 case 's':
1317 config->service = optarg;
1318 if (strcmp(config->service, "install") == 0) {
1319 if (ga_install_vss_provider()) {
1320 exit(EXIT_FAILURE);
1321 }
1322 if (ga_install_service(config->channel_path,
1323 config->log_filepath, config->state_dir)) {
1324 exit(EXIT_FAILURE);
1325 }
1326 exit(EXIT_SUCCESS);
1327 } else if (strcmp(config->service, "uninstall") == 0) {
1328 ga_uninstall_vss_provider();
1329 exit(ga_uninstall_service());
1330 } else if (strcmp(config->service, "vss-install") == 0) {
1331 if (ga_install_vss_provider()) {
1332 exit(EXIT_FAILURE);
1333 }
1334 exit(EXIT_SUCCESS);
1335 } else if (strcmp(config->service, "vss-uninstall") == 0) {
1336 ga_uninstall_vss_provider();
1337 exit(EXIT_SUCCESS);
1338 } else {
1339 printf("Unknown service command.\n");
1340 exit(EXIT_FAILURE);
1341 }
1342 break;
1343 #endif
1344 case 'h':
1345 usage(argv[0]);
1346 exit(EXIT_SUCCESS);
1347 case '?':
1348 g_print("Unknown option, try '%s --help' for more information.\n",
1349 argv[0]);
1350 exit(EXIT_FAILURE);
1351 }
1352 }
1353 }
1354
config_free(GAConfig * config)1355 static void config_free(GAConfig *config)
1356 {
1357 g_free(config->method);
1358 g_free(config->log_filepath);
1359 g_free(config->pid_filepath);
1360 g_free(config->state_dir);
1361 g_free(config->channel_path);
1362 g_free(config->bliststr);
1363 g_free(config->aliststr);
1364 #ifdef CONFIG_FSFREEZE
1365 g_free(config->fsfreeze_hook);
1366 #endif
1367 g_list_free_full(config->blockedrpcs, g_free);
1368 g_list_free_full(config->allowedrpcs, g_free);
1369 g_free(config);
1370 }
1371
check_is_frozen(GAState * s)1372 static bool check_is_frozen(GAState *s)
1373 {
1374 #ifndef _WIN32
1375 /* check if a previous instance of qemu-ga exited with filesystems' state
1376 * marked as frozen. this could be a stale value (a non-qemu-ga process
1377 * or reboot may have since unfrozen them), but better to require an
1378 * unneeded unfreeze than to risk hanging on start-up
1379 */
1380 struct stat st;
1381 if (stat(s->state_filepath_isfrozen, &st) == -1) {
1382 /* it's okay if the file doesn't exist, but if we can't access for
1383 * some other reason, such as permissions, there's a configuration
1384 * that needs to be addressed. so just bail now before we get into
1385 * more trouble later
1386 */
1387 if (errno != ENOENT) {
1388 g_critical("unable to access state file at path %s: %s",
1389 s->state_filepath_isfrozen, strerror(errno));
1390 return EXIT_FAILURE;
1391 }
1392 } else {
1393 g_warning("previous instance appears to have exited with frozen"
1394 " filesystems. deferring logging/pidfile creation and"
1395 " disabling non-fsfreeze-safe commands until"
1396 " guest-fsfreeze-thaw is issued, or filesystems are"
1397 " manually unfrozen and the file %s is removed",
1398 s->state_filepath_isfrozen);
1399 return true;
1400 }
1401 #endif
1402 return false;
1403 }
1404
initialize_agent(GAConfig * config,int socket_activation)1405 static GAState *initialize_agent(GAConfig *config, int socket_activation)
1406 {
1407 GAState *s = g_new0(GAState, 1);
1408
1409 g_assert(ga_state == NULL);
1410
1411 s->log_level = config->log_level;
1412 s->log_file = stderr;
1413 #ifdef CONFIG_FSFREEZE
1414 s->fsfreeze_hook = config->fsfreeze_hook;
1415 #endif
1416 s->pstate_filepath = g_strdup_printf("%s/qga.state", config->state_dir);
1417 s->state_filepath_isfrozen = g_strdup_printf("%s/qga.state.isfrozen",
1418 config->state_dir);
1419 s->frozen = check_is_frozen(s);
1420
1421 g_log_set_default_handler(ga_log, s);
1422 g_log_set_fatal_mask(NULL, G_LOG_LEVEL_ERROR);
1423 ga_enable_logging(s);
1424
1425 g_debug("Guest agent version %s started", QEMU_FULL_VERSION);
1426
1427 #ifdef _WIN32
1428 s->load_avg_wait_handle = INVALID_HANDLE_VALUE;
1429 s->load_avg_event = INVALID_HANDLE_VALUE;
1430 s->load_avg_pdh_query = NULL;
1431
1432 s->event_log = RegisterEventSource(NULL, "qemu-ga");
1433 if (!s->event_log) {
1434 g_autofree gchar *errmsg = g_win32_error_message(GetLastError());
1435 g_critical("unable to register event source: %s", errmsg);
1436 return NULL;
1437 }
1438
1439 /* On win32 the state directory is application specific (be it the default
1440 * or a user override). We got past the command line parsing; let's create
1441 * the directory (with any intermediate directories). If we run into an
1442 * error later on, we won't try to clean up the directory, it is considered
1443 * persistent.
1444 */
1445 if (g_mkdir_with_parents(config->state_dir, S_IRWXU) == -1) {
1446 g_critical("unable to create (an ancestor of) the state directory"
1447 " '%s': %s", config->state_dir, strerror(errno));
1448 return NULL;
1449 }
1450
1451 if (!vss_init(true)) {
1452 g_debug("vss_init failed, vss commands will not function");
1453 }
1454 #endif
1455
1456 if (ga_is_frozen(s)) {
1457 if (config->daemonize) {
1458 /* delay opening/locking of pidfile till filesystems are unfrozen */
1459 s->deferred_options.pid_filepath = config->pid_filepath;
1460 }
1461 if (config->log_filepath) {
1462 /* delay opening the log file till filesystems are unfrozen */
1463 s->deferred_options.log_filepath = config->log_filepath;
1464 }
1465 ga_disable_logging(s);
1466 } else {
1467 if (config->log_filepath) {
1468 FILE *log_file = ga_open_logfile(config->log_filepath);
1469 if (!log_file) {
1470 g_critical("unable to open specified log file: %s",
1471 strerror(errno));
1472 return NULL;
1473 }
1474 s->log_file = log_file;
1475 }
1476 }
1477
1478 /* load persistent state from disk */
1479 if (!read_persistent_state(&s->pstate,
1480 s->pstate_filepath,
1481 ga_is_frozen(s))) {
1482 g_critical("failed to load persistent state");
1483 return NULL;
1484 }
1485
1486 s->command_state = ga_command_state_new();
1487 ga_command_state_init(s, s->command_state);
1488 ga_command_state_init_all(s->command_state);
1489 json_message_parser_init(&s->parser, process_event, s, NULL);
1490
1491 #ifndef _WIN32
1492 if (!register_signal_handlers()) {
1493 g_critical("failed to register signal handlers");
1494 return NULL;
1495 }
1496 #endif
1497
1498 s->main_loop = g_main_loop_new(NULL, false);
1499
1500 s->config = config;
1501 s->socket_activation = socket_activation;
1502
1503 #ifdef _WIN32
1504 s->wakeup_event = CreateEvent(NULL, TRUE, FALSE, TEXT("WakeUp"));
1505 if (s->wakeup_event == NULL) {
1506 g_critical("CreateEvent failed");
1507 return NULL;
1508 }
1509 #endif
1510
1511 ga_apply_command_filters(s);
1512
1513 if (!channel_init(s, s->config->method, s->config->channel_path,
1514 s->socket_activation ? FIRST_SOCKET_ACTIVATION_FD : -1)) {
1515 g_critical("failed to initialize guest agent channel");
1516 return NULL;
1517 }
1518
1519 if (config->daemonize) {
1520 if (ga_is_frozen(s)) {
1521 become_daemon(NULL);
1522 } else {
1523 become_daemon(config->pid_filepath);
1524 }
1525 }
1526
1527 ga_state = s;
1528 return s;
1529 }
1530
cleanup_agent(GAState * s)1531 static void cleanup_agent(GAState *s)
1532 {
1533 #ifdef _WIN32
1534 CloseHandle(s->wakeup_event);
1535 CloseHandle(s->event_log);
1536
1537 if (s->load_avg_wait_handle != INVALID_HANDLE_VALUE) {
1538 UnregisterWait(s->load_avg_wait_handle);
1539 }
1540
1541 if (s->load_avg_event != INVALID_HANDLE_VALUE) {
1542 CloseHandle(s->load_avg_event);
1543 }
1544
1545 if (s->load_avg_pdh_query) {
1546 PdhCloseQuery(s->load_avg_pdh_query);
1547 }
1548 #endif
1549 if (s->command_state) {
1550 ga_command_state_cleanup_all(s->command_state);
1551 ga_command_state_free(s->command_state);
1552 json_message_parser_destroy(&s->parser);
1553 }
1554 g_free(s->pstate_filepath);
1555 g_free(s->state_filepath_isfrozen);
1556 if (s->main_loop) {
1557 g_main_loop_unref(s->main_loop);
1558 }
1559 g_free(s);
1560 ga_state = NULL;
1561 }
1562
run_agent_once(GAState * s)1563 static int run_agent_once(GAState *s)
1564 {
1565 if (!s->channel &&
1566 channel_init(s, s->config->method, s->config->channel_path,
1567 s->socket_activation ? FIRST_SOCKET_ACTIVATION_FD : -1)) {
1568 g_critical("failed to initialize guest agent channel");
1569 return EXIT_FAILURE;
1570 }
1571
1572 g_main_loop_run(s->main_loop);
1573
1574 if (s->channel) {
1575 ga_channel_free(s->channel);
1576 s->channel = NULL;
1577 }
1578
1579 return EXIT_SUCCESS;
1580 }
1581
wait_for_channel_availability(GAState * s)1582 static void wait_for_channel_availability(GAState *s)
1583 {
1584 g_warning("waiting for channel path...");
1585 #ifndef _WIN32
1586 sleep(QGA_RETRY_INTERVAL);
1587 #else
1588 DWORD dwWaitResult;
1589
1590 dwWaitResult = WaitForSingleObject(s->wakeup_event, INFINITE);
1591
1592 switch (dwWaitResult) {
1593 case WAIT_OBJECT_0:
1594 break;
1595 case WAIT_TIMEOUT:
1596 break;
1597 default:
1598 g_critical("WaitForSingleObject failed");
1599 }
1600 #endif
1601 }
1602
run_agent(GAState * s)1603 static int run_agent(GAState *s)
1604 {
1605 int ret = EXIT_SUCCESS;
1606
1607 s->force_exit = false;
1608
1609 do {
1610 ret = run_agent_once(s);
1611 if (s->config->retry_path && !s->force_exit) {
1612 g_warning("agent stopped unexpectedly, restarting...");
1613 wait_for_channel_availability(s);
1614 }
1615 } while (s->config->retry_path && !s->force_exit);
1616
1617 return ret;
1618 }
1619
stop_agent(GAState * s,bool requested)1620 static void stop_agent(GAState *s, bool requested)
1621 {
1622 if (!s->force_exit) {
1623 s->force_exit = requested;
1624 }
1625
1626 if (g_main_loop_is_running(s->main_loop)) {
1627 g_main_loop_quit(s->main_loop);
1628 }
1629 }
1630
main(int argc,char ** argv)1631 int main(int argc, char **argv)
1632 {
1633 int ret = EXIT_FAILURE;
1634 GAState *s;
1635 GAConfig *config = g_new0(GAConfig, 1);
1636 int socket_activation;
1637
1638 config->log_level = G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL;
1639
1640 qemu_init_exec_dir(argv[0]);
1641 qga_qmp_init_marshal(&ga_commands);
1642
1643 init_dfl_pathnames();
1644 config_parse(config, argc, argv);
1645
1646 if (config->pid_filepath == NULL) {
1647 config->pid_filepath = g_strdup(dfl_pathnames.pidfile);
1648 }
1649
1650 if (config->state_dir == NULL) {
1651 config->state_dir = g_strdup(dfl_pathnames.state_dir);
1652 }
1653
1654 if (config->method == NULL) {
1655 config->method = g_strdup("virtio-serial");
1656 }
1657
1658 socket_activation = check_socket_activation();
1659 if (socket_activation > 1) {
1660 g_critical("qemu-ga only supports listening on one socket");
1661 goto end;
1662 }
1663 if (socket_activation) {
1664 SocketAddress *addr;
1665
1666 g_free(config->method);
1667 g_free(config->channel_path);
1668 config->method = NULL;
1669 config->channel_path = NULL;
1670
1671 addr = socket_local_address(FIRST_SOCKET_ACTIVATION_FD, NULL);
1672 if (addr) {
1673 if (addr->type == SOCKET_ADDRESS_TYPE_UNIX) {
1674 config->method = g_strdup("unix-listen");
1675 } else if (addr->type == SOCKET_ADDRESS_TYPE_VSOCK) {
1676 config->method = g_strdup("vsock-listen");
1677 }
1678
1679 qapi_free_SocketAddress(addr);
1680 }
1681
1682 if (!config->method) {
1683 g_critical("unsupported listen fd type");
1684 goto end;
1685 }
1686 } else if (config->channel_path == NULL) {
1687 if (strcmp(config->method, "virtio-serial") == 0) {
1688 /* try the default path for the virtio-serial port */
1689 config->channel_path = g_strdup(QGA_VIRTIO_PATH_DEFAULT);
1690 } else if (strcmp(config->method, "isa-serial") == 0) {
1691 /* try the default path for the serial port - COM1 */
1692 config->channel_path = g_strdup(QGA_SERIAL_PATH_DEFAULT);
1693 } else {
1694 g_critical("must specify a path for this channel");
1695 goto end;
1696 }
1697 }
1698
1699 if (config->dumpconf) {
1700 config_dump(config);
1701 ret = EXIT_SUCCESS;
1702 goto end;
1703 }
1704
1705 s = initialize_agent(config, socket_activation);
1706 if (!s) {
1707 g_critical("error initializing guest agent");
1708 goto end;
1709 }
1710
1711 #ifdef _WIN32
1712 if (config->daemonize) {
1713 SERVICE_TABLE_ENTRY service_table[] = {
1714 { (char *)QGA_SERVICE_NAME, service_main }, { NULL, NULL } };
1715 StartServiceCtrlDispatcher(service_table);
1716 ret = EXIT_SUCCESS;
1717 } else {
1718 ret = run_agent(s);
1719 }
1720 #else
1721 ret = run_agent(s);
1722 #endif
1723
1724 cleanup_agent(s);
1725
1726 end:
1727 if (config->daemonize) {
1728 unlink(config->pid_filepath);
1729 }
1730
1731 config_free(config);
1732
1733 return ret;
1734 }
1735