blob: 762307988783256aa0361c1ad71da1af8133d9e3 [file] [log] [blame]
Michael Roth48ff7a62011-07-20 15:19:37 -05001/*
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>
Michael Roth48ff7a62011-07-20 15:19:37 -050017#include <getopt.h>
Michael Rothd8ca6852012-01-19 22:04:34 -060018#ifndef _WIN32
Michael Roth48ff7a62011-07-20 15:19:37 -050019#include <syslog.h>
Luiz Capitulino11d0f122012-02-28 11:03:03 -030020#include <sys/wait.h>
Michael Rothf789aa72012-04-18 16:28:01 -050021#include <sys/stat.h>
Michael Rothd8ca6852012-01-19 22:04:34 -060022#endif
Michael Roth48ff7a62011-07-20 15:19:37 -050023#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"
Michael Rothabd6cf62011-12-06 22:03:42 -060031#include "qapi/qmp-core.h"
Michael Roth125b3102012-01-19 00:18:20 -060032#include "qga/channel.h"
Michael Rothbc62fa02012-01-21 16:42:27 -060033#ifdef _WIN32
34#include "qga/service-win32.h"
35#include <windows.h>
36#endif
Michael Roth48ff7a62011-07-20 15:19:37 -050037
Michael Roth7868e262012-01-20 19:01:30 -060038#ifndef _WIN32
Michael Roth48ff7a62011-07-20 15:19:37 -050039#define QGA_VIRTIO_PATH_DEFAULT "/dev/virtio-ports/org.qemu.guest_agent.0"
Michael Roth7868e262012-01-20 19:01:30 -060040#else
41#define QGA_VIRTIO_PATH_DEFAULT "\\\\.\\Global\\org.qemu.guest_agent.0"
42#endif
Michael Roth48ff7a62011-07-20 15:19:37 -050043#define QGA_PIDFILE_DEFAULT "/var/run/qemu-ga.pid"
Michael Rothf789aa72012-04-18 16:28:01 -050044#define QGA_STATEDIR_DEFAULT "/tmp"
Michael Roth3cf0bed2012-02-07 13:56:48 -060045#define QGA_SENTINEL_BYTE 0xFF
Michael Roth48ff7a62011-07-20 15:19:37 -050046
47struct GAState {
48 JSONMessageParser parser;
49 GMainLoop *main_loop;
Michael Roth125b3102012-01-19 00:18:20 -060050 GAChannel *channel;
Michael Roth48ff7a62011-07-20 15:19:37 -050051 bool virtio; /* fastpath to check for virtio to deal with poll() quirks */
52 GACommandState *command_state;
53 GLogLevelFlags log_level;
54 FILE *log_file;
55 bool logging_enabled;
Michael Rothbc62fa02012-01-21 16:42:27 -060056#ifdef _WIN32
57 GAService service;
58#endif
Michael Roth3cf0bed2012-02-07 13:56:48 -060059 bool delimit_response;
Michael Rothf22d85e2012-04-17 19:01:45 -050060 bool frozen;
61 GList *blacklist;
Michael Rothf789aa72012-04-18 16:28:01 -050062 const char *state_filepath_isfrozen;
63 struct {
64 const char *log_filepath;
65 const char *pid_filepath;
66 } deferred_options;
Michael Roth48ff7a62011-07-20 15:19:37 -050067};
68
Michael Roth3cf0bed2012-02-07 13:56:48 -060069struct GAState *ga_state;
Michael Roth48ff7a62011-07-20 15:19:37 -050070
Michael Rothf22d85e2012-04-17 19:01:45 -050071/* commands that are safe to issue while filesystems are frozen */
72static const char *ga_freeze_whitelist[] = {
73 "guest-ping",
74 "guest-info",
75 "guest-sync",
76 "guest-fsfreeze-status",
77 "guest-fsfreeze-thaw",
78 NULL
79};
80
Michael Rothbc62fa02012-01-21 16:42:27 -060081#ifdef _WIN32
82DWORD WINAPI service_ctrl_handler(DWORD ctrl, DWORD type, LPVOID data,
83 LPVOID ctx);
84VOID WINAPI service_main(DWORD argc, TCHAR *argv[]);
85#endif
86
Michael Roth48ff7a62011-07-20 15:19:37 -050087static void quit_handler(int sig)
88{
Michael Rothf22d85e2012-04-17 19:01:45 -050089 /* if we're frozen, don't exit unless we're absolutely forced to,
90 * because it's basically impossible for graceful exit to complete
91 * unless all log/pid files are on unfreezable filesystems. there's
92 * also a very likely chance killing the agent before unfreezing
93 * the filesystems is a mistake (or will be viewed as one later).
94 */
95 if (ga_is_frozen(ga_state)) {
96 return;
97 }
Stefan Weil2542bfd2011-08-28 21:45:40 +020098 g_debug("received signal num %d, quitting", sig);
Michael Roth48ff7a62011-07-20 15:19:37 -050099
100 if (g_main_loop_is_running(ga_state->main_loop)) {
101 g_main_loop_quit(ga_state->main_loop);
102 }
103}
104
Michael Rothbc62fa02012-01-21 16:42:27 -0600105#ifndef _WIN32
Michael Roth125b3102012-01-19 00:18:20 -0600106static gboolean register_signal_handlers(void)
Michael Roth48ff7a62011-07-20 15:19:37 -0500107{
Luiz Capitulinodc8764f2012-05-11 16:19:46 -0300108 struct sigaction sigact;
Michael Roth48ff7a62011-07-20 15:19:37 -0500109 int ret;
110
111 memset(&sigact, 0, sizeof(struct sigaction));
112 sigact.sa_handler = quit_handler;
113
114 ret = sigaction(SIGINT, &sigact, NULL);
115 if (ret == -1) {
116 g_error("error configuring signal handler: %s", strerror(errno));
Michael Roth125b3102012-01-19 00:18:20 -0600117 return false;
Michael Roth48ff7a62011-07-20 15:19:37 -0500118 }
119 ret = sigaction(SIGTERM, &sigact, NULL);
120 if (ret == -1) {
121 g_error("error configuring signal handler: %s", strerror(errno));
Michael Roth125b3102012-01-19 00:18:20 -0600122 return false;
Michael Roth48ff7a62011-07-20 15:19:37 -0500123 }
Luiz Capitulino11d0f122012-02-28 11:03:03 -0300124
Michael Roth125b3102012-01-19 00:18:20 -0600125 return true;
Michael Roth48ff7a62011-07-20 15:19:37 -0500126}
Luiz Capitulino04b4e752012-05-10 16:50:41 -0300127
128/* TODO: use this in place of all post-fork() fclose(std*) callers */
129void reopen_fd_to_null(int fd)
130{
131 int nullfd;
132
133 nullfd = open("/dev/null", O_RDWR);
134 if (nullfd < 0) {
135 return;
136 }
137
138 dup2(nullfd, fd);
139
140 if (nullfd != fd) {
141 close(nullfd);
142 }
143}
Michael Rothd8ca6852012-01-19 22:04:34 -0600144#endif
Michael Roth48ff7a62011-07-20 15:19:37 -0500145
146static void usage(const char *cmd)
147{
148 printf(
Michael Roth4bdd0412012-04-17 11:28:27 -0500149"Usage: %s [-m <method> -p <path>] [<options>]\n"
Michael Roth48ff7a62011-07-20 15:19:37 -0500150"QEMU Guest Agent %s\n"
151"\n"
152" -m, --method transport method: one of unix-listen, virtio-serial, or\n"
153" isa-serial (virtio-serial is the default)\n"
Michael Roth4bdd0412012-04-17 11:28:27 -0500154" -p, --path device/socket path (the default for virtio-serial is:\n"
155" %s)\n"
Michael Roth48ff7a62011-07-20 15:19:37 -0500156" -l, --logfile set logfile path, logs to stderr by default\n"
157" -f, --pidfile specify pidfile (default is %s)\n"
Michael Rothf789aa72012-04-18 16:28:01 -0500158" -t, --statedir specify dir to store state information (absolute paths\n"
159" only, default is %s)\n"
Michael Roth48ff7a62011-07-20 15:19:37 -0500160" -v, --verbose log extra debugging information\n"
161" -V, --version print version information and exit\n"
162" -d, --daemonize become a daemon\n"
Michael Rothbc62fa02012-01-21 16:42:27 -0600163#ifdef _WIN32
164" -s, --service service commands: install, uninstall\n"
Michael Rothd8ca6852012-01-19 22:04:34 -0600165#endif
Michael Roth4bdd0412012-04-17 11:28:27 -0500166" -b, --blacklist comma-separated list of RPCs to disable (no spaces, \"?\"\n"
Michael Rothabd6cf62011-12-06 22:03:42 -0600167" to list available RPCs)\n"
Michael Roth48ff7a62011-07-20 15:19:37 -0500168" -h, --help display this help and exit\n"
169"\n"
170"Report bugs to <mdroth@linux.vnet.ibm.com>\n"
Michael Roth8efacc42012-05-14 09:33:48 -0500171 , cmd, QEMU_VERSION, QGA_VIRTIO_PATH_DEFAULT, QGA_PIDFILE_DEFAULT,
Michael Rothf789aa72012-04-18 16:28:01 -0500172 QGA_STATEDIR_DEFAULT);
Michael Roth48ff7a62011-07-20 15:19:37 -0500173}
174
Michael Roth48ff7a62011-07-20 15:19:37 -0500175static const char *ga_log_level_str(GLogLevelFlags level)
176{
177 switch (level & G_LOG_LEVEL_MASK) {
178 case G_LOG_LEVEL_ERROR:
179 return "error";
180 case G_LOG_LEVEL_CRITICAL:
181 return "critical";
182 case G_LOG_LEVEL_WARNING:
183 return "warning";
184 case G_LOG_LEVEL_MESSAGE:
185 return "message";
186 case G_LOG_LEVEL_INFO:
187 return "info";
188 case G_LOG_LEVEL_DEBUG:
189 return "debug";
190 default:
191 return "user";
192 }
193}
194
195bool ga_logging_enabled(GAState *s)
196{
197 return s->logging_enabled;
198}
199
200void ga_disable_logging(GAState *s)
201{
202 s->logging_enabled = false;
203}
204
205void ga_enable_logging(GAState *s)
206{
207 s->logging_enabled = true;
208}
209
210static void ga_log(const gchar *domain, GLogLevelFlags level,
211 const gchar *msg, gpointer opaque)
212{
213 GAState *s = opaque;
214 GTimeVal time;
215 const char *level_str = ga_log_level_str(level);
216
217 if (!ga_logging_enabled(s)) {
218 return;
219 }
220
221 level &= G_LOG_LEVEL_MASK;
Michael Rothd8ca6852012-01-19 22:04:34 -0600222#ifndef _WIN32
Michael Roth8f477472011-08-11 15:38:11 -0500223 if (domain && strcmp(domain, "syslog") == 0) {
Michael Roth48ff7a62011-07-20 15:19:37 -0500224 syslog(LOG_INFO, "%s: %s", level_str, msg);
225 } else if (level & s->log_level) {
Michael Rothd8ca6852012-01-19 22:04:34 -0600226#else
227 if (level & s->log_level) {
228#endif
Michael Roth48ff7a62011-07-20 15:19:37 -0500229 g_get_current_time(&time);
230 fprintf(s->log_file,
231 "%lu.%lu: %s: %s\n", time.tv_sec, time.tv_usec, level_str, msg);
232 fflush(s->log_file);
233 }
234}
235
Michael Roth3cf0bed2012-02-07 13:56:48 -0600236void ga_set_response_delimited(GAState *s)
237{
238 s->delimit_response = true;
239}
240
Michael Rothf789aa72012-04-18 16:28:01 -0500241#ifndef _WIN32
242static bool ga_open_pidfile(const char *pidfile)
243{
244 int pidfd;
245 char pidstr[32];
246
247 pidfd = open(pidfile, O_CREAT|O_WRONLY, S_IRUSR|S_IWUSR);
248 if (pidfd == -1 || lockf(pidfd, F_TLOCK, 0)) {
249 g_critical("Cannot lock pid file, %s", strerror(errno));
Jim Meyering4144f122012-08-22 13:55:52 +0200250 if (pidfd != -1) {
251 close(pidfd);
252 }
Michael Rothf789aa72012-04-18 16:28:01 -0500253 return false;
254 }
255
256 if (ftruncate(pidfd, 0) || lseek(pidfd, 0, SEEK_SET)) {
257 g_critical("Failed to truncate pid file");
258 goto fail;
259 }
260 sprintf(pidstr, "%d", getpid());
261 if (write(pidfd, pidstr, strlen(pidstr)) != strlen(pidstr)) {
262 g_critical("Failed to write pid file");
263 goto fail;
264 }
265
266 return true;
267
268fail:
269 unlink(pidfile);
270 return false;
271}
272#else /* _WIN32 */
273static bool ga_open_pidfile(const char *pidfile)
274{
275 return true;
276}
277#endif
278
Michael Rothf22d85e2012-04-17 19:01:45 -0500279static gint ga_strcmp(gconstpointer str1, gconstpointer str2)
280{
281 return strcmp(str1, str2);
282}
283
284/* disable commands that aren't safe for fsfreeze */
285static void ga_disable_non_whitelisted(void)
286{
287 char **list_head, **list;
288 bool whitelisted;
289 int i;
290
291 list_head = list = qmp_get_command_list();
292 while (*list != NULL) {
293 whitelisted = false;
294 i = 0;
295 while (ga_freeze_whitelist[i] != NULL) {
296 if (strcmp(*list, ga_freeze_whitelist[i]) == 0) {
297 whitelisted = true;
298 }
299 i++;
300 }
301 if (!whitelisted) {
302 g_debug("disabling command: %s", *list);
303 qmp_disable_command(*list);
304 }
305 g_free(*list);
306 list++;
307 }
308 g_free(list_head);
309}
310
Jim Meyeringa31f0532012-05-09 05:12:04 +0000311/* [re-]enable all commands, except those explicitly blacklisted by user */
Michael Rothf22d85e2012-04-17 19:01:45 -0500312static void ga_enable_non_blacklisted(GList *blacklist)
313{
314 char **list_head, **list;
315
316 list_head = list = qmp_get_command_list();
317 while (*list != NULL) {
318 if (g_list_find_custom(blacklist, *list, ga_strcmp) == NULL &&
319 !qmp_command_is_enabled(*list)) {
320 g_debug("enabling command: %s", *list);
321 qmp_enable_command(*list);
322 }
323 g_free(*list);
324 list++;
325 }
326 g_free(list_head);
327}
328
Michael Rothf789aa72012-04-18 16:28:01 -0500329static bool ga_create_file(const char *path)
330{
331 int fd = open(path, O_CREAT | O_WRONLY, S_IWUSR | S_IRUSR);
332 if (fd == -1) {
333 g_warning("unable to open/create file %s: %s", path, strerror(errno));
334 return false;
335 }
336 close(fd);
337 return true;
338}
339
340static bool ga_delete_file(const char *path)
341{
342 int ret = unlink(path);
343 if (ret == -1) {
344 g_warning("unable to delete file: %s: %s", path, strerror(errno));
345 return false;
346 }
347
348 return true;
349}
350
Michael Rothf22d85e2012-04-17 19:01:45 -0500351bool ga_is_frozen(GAState *s)
352{
353 return s->frozen;
354}
355
356void ga_set_frozen(GAState *s)
357{
358 if (ga_is_frozen(s)) {
359 return;
360 }
361 /* disable all non-whitelisted (for frozen state) commands */
362 ga_disable_non_whitelisted();
363 g_warning("disabling logging due to filesystem freeze");
364 ga_disable_logging(s);
365 s->frozen = true;
Michael Rothf789aa72012-04-18 16:28:01 -0500366 if (!ga_create_file(s->state_filepath_isfrozen)) {
367 g_warning("unable to create %s, fsfreeze may not function properly",
368 s->state_filepath_isfrozen);
369 }
Michael Rothf22d85e2012-04-17 19:01:45 -0500370}
371
372void ga_unset_frozen(GAState *s)
373{
374 if (!ga_is_frozen(s)) {
375 return;
376 }
377
Michael Rothf789aa72012-04-18 16:28:01 -0500378 /* if we delayed creation/opening of pid/log files due to being
379 * in a frozen state at start up, do it now
380 */
381 if (s->deferred_options.log_filepath) {
382 s->log_file = fopen(s->deferred_options.log_filepath, "a");
383 if (!s->log_file) {
384 s->log_file = stderr;
385 }
386 s->deferred_options.log_filepath = NULL;
387 }
Michael Rothf22d85e2012-04-17 19:01:45 -0500388 ga_enable_logging(s);
Michael Rothf789aa72012-04-18 16:28:01 -0500389 g_warning("logging re-enabled due to filesystem unfreeze");
390 if (s->deferred_options.pid_filepath) {
391 if (!ga_open_pidfile(s->deferred_options.pid_filepath)) {
392 g_warning("failed to create/open pid file");
393 }
394 s->deferred_options.pid_filepath = NULL;
395 }
Michael Rothf22d85e2012-04-17 19:01:45 -0500396
397 /* enable all disabled, non-blacklisted commands */
398 ga_enable_non_blacklisted(s->blacklist);
399 s->frozen = false;
Michael Rothf789aa72012-04-18 16:28:01 -0500400 if (!ga_delete_file(s->state_filepath_isfrozen)) {
401 g_warning("unable to delete %s, fsfreeze may not function properly",
402 s->state_filepath_isfrozen);
403 }
Michael Rothf22d85e2012-04-17 19:01:45 -0500404}
405
Michael Roth48ff7a62011-07-20 15:19:37 -0500406static void become_daemon(const char *pidfile)
407{
Michael Rothf789aa72012-04-18 16:28:01 -0500408#ifndef _WIN32
Michael Roth48ff7a62011-07-20 15:19:37 -0500409 pid_t pid, sid;
Michael Roth48ff7a62011-07-20 15:19:37 -0500410
411 pid = fork();
412 if (pid < 0) {
413 exit(EXIT_FAILURE);
414 }
415 if (pid > 0) {
416 exit(EXIT_SUCCESS);
417 }
418
Michael Rothf789aa72012-04-18 16:28:01 -0500419 if (pidfile) {
420 if (!ga_open_pidfile(pidfile)) {
421 g_critical("failed to create pidfile");
422 exit(EXIT_FAILURE);
423 }
Michael Roth48ff7a62011-07-20 15:19:37 -0500424 }
425
426 umask(0);
427 sid = setsid();
428 if (sid < 0) {
429 goto fail;
430 }
431 if ((chdir("/")) < 0) {
432 goto fail;
433 }
434
Luiz Capitulino226a4892012-05-10 16:50:42 -0300435 reopen_fd_to_null(STDIN_FILENO);
436 reopen_fd_to_null(STDOUT_FILENO);
437 reopen_fd_to_null(STDERR_FILENO);
Michael Roth48ff7a62011-07-20 15:19:37 -0500438 return;
439
440fail:
Stefan Weil4bdb1a32012-08-24 07:03:03 +0200441 if (pidfile) {
442 unlink(pidfile);
443 }
Michael Roth48ff7a62011-07-20 15:19:37 -0500444 g_critical("failed to daemonize");
445 exit(EXIT_FAILURE);
Michael Rothd8ca6852012-01-19 22:04:34 -0600446#endif
Michael Rothf789aa72012-04-18 16:28:01 -0500447}
Michael Roth48ff7a62011-07-20 15:19:37 -0500448
Michael Roth125b3102012-01-19 00:18:20 -0600449static int send_response(GAState *s, QObject *payload)
Michael Roth48ff7a62011-07-20 15:19:37 -0500450{
Michael Roth48ff7a62011-07-20 15:19:37 -0500451 const char *buf;
Michael Roth3cf0bed2012-02-07 13:56:48 -0600452 QString *payload_qstr, *response_qstr;
Michael Roth125b3102012-01-19 00:18:20 -0600453 GIOStatus status;
Michael Roth48ff7a62011-07-20 15:19:37 -0500454
Michael Roth125b3102012-01-19 00:18:20 -0600455 g_assert(payload && s->channel);
Michael Roth48ff7a62011-07-20 15:19:37 -0500456
457 payload_qstr = qobject_to_json(payload);
458 if (!payload_qstr) {
459 return -EINVAL;
460 }
461
Michael Roth3cf0bed2012-02-07 13:56:48 -0600462 if (s->delimit_response) {
463 s->delimit_response = false;
464 response_qstr = qstring_new();
465 qstring_append_chr(response_qstr, QGA_SENTINEL_BYTE);
466 qstring_append(response_qstr, qstring_get_str(payload_qstr));
467 QDECREF(payload_qstr);
468 } else {
469 response_qstr = payload_qstr;
470 }
471
472 qstring_append_chr(response_qstr, '\n');
473 buf = qstring_get_str(response_qstr);
Michael Roth125b3102012-01-19 00:18:20 -0600474 status = ga_channel_write_all(s->channel, buf, strlen(buf));
Michael Roth3cf0bed2012-02-07 13:56:48 -0600475 QDECREF(response_qstr);
Michael Roth125b3102012-01-19 00:18:20 -0600476 if (status != G_IO_STATUS_NORMAL) {
477 return -EIO;
Michael Roth48ff7a62011-07-20 15:19:37 -0500478 }
Michael Roth125b3102012-01-19 00:18:20 -0600479
480 return 0;
Michael Roth48ff7a62011-07-20 15:19:37 -0500481}
482
483static void process_command(GAState *s, QDict *req)
484{
485 QObject *rsp = NULL;
486 int ret;
487
488 g_assert(req);
489 g_debug("processing command");
490 rsp = qmp_dispatch(QOBJECT(req));
491 if (rsp) {
Michael Roth125b3102012-01-19 00:18:20 -0600492 ret = send_response(s, rsp);
Michael Roth48ff7a62011-07-20 15:19:37 -0500493 if (ret) {
Michael Roth125b3102012-01-19 00:18:20 -0600494 g_warning("error sending response: %s", strerror(ret));
Michael Roth48ff7a62011-07-20 15:19:37 -0500495 }
496 qobject_decref(rsp);
Michael Roth48ff7a62011-07-20 15:19:37 -0500497 }
498}
499
500/* handle requests/control events coming in over the channel */
501static void process_event(JSONMessageParser *parser, QList *tokens)
502{
503 GAState *s = container_of(parser, GAState, parser);
504 QObject *obj;
505 QDict *qdict;
506 Error *err = NULL;
507 int ret;
508
509 g_assert(s && parser);
510
511 g_debug("process_event: called");
512 obj = json_parser_parse_err(tokens, NULL, &err);
513 if (err || !obj || qobject_type(obj) != QTYPE_QDICT) {
514 qobject_decref(obj);
515 qdict = qdict_new();
516 if (!err) {
517 g_warning("failed to parse event: unknown error");
518 error_set(&err, QERR_JSON_PARSING);
519 } else {
520 g_warning("failed to parse event: %s", error_get_pretty(err));
521 }
Luiz Capitulino93b91c52012-08-01 16:30:13 -0300522 qdict_put_obj(qdict, "error", qmp_build_error_object(err));
Michael Roth48ff7a62011-07-20 15:19:37 -0500523 error_free(err);
524 } else {
525 qdict = qobject_to_qdict(obj);
526 }
527
528 g_assert(qdict);
529
530 /* handle host->guest commands */
531 if (qdict_haskey(qdict, "execute")) {
532 process_command(s, qdict);
533 } else {
534 if (!qdict_haskey(qdict, "error")) {
535 QDECREF(qdict);
536 qdict = qdict_new();
537 g_warning("unrecognized payload format");
538 error_set(&err, QERR_UNSUPPORTED);
Luiz Capitulino93b91c52012-08-01 16:30:13 -0300539 qdict_put_obj(qdict, "error", qmp_build_error_object(err));
Michael Roth48ff7a62011-07-20 15:19:37 -0500540 error_free(err);
541 }
Michael Roth125b3102012-01-19 00:18:20 -0600542 ret = send_response(s, QOBJECT(qdict));
Michael Roth48ff7a62011-07-20 15:19:37 -0500543 if (ret) {
Michael Roth125b3102012-01-19 00:18:20 -0600544 g_warning("error sending error response: %s", strerror(ret));
Michael Roth48ff7a62011-07-20 15:19:37 -0500545 }
546 }
547
548 QDECREF(qdict);
549}
550
Michael Roth125b3102012-01-19 00:18:20 -0600551/* false return signals GAChannel to close the current client connection */
552static gboolean channel_event_cb(GIOCondition condition, gpointer data)
Michael Roth48ff7a62011-07-20 15:19:37 -0500553{
554 GAState *s = data;
Michael Roth125b3102012-01-19 00:18:20 -0600555 gchar buf[QGA_READ_COUNT_DEFAULT+1];
Michael Roth48ff7a62011-07-20 15:19:37 -0500556 gsize count;
557 GError *err = NULL;
Michael Roth125b3102012-01-19 00:18:20 -0600558 GIOStatus status = ga_channel_read(s->channel, buf, QGA_READ_COUNT_DEFAULT, &count);
Michael Roth48ff7a62011-07-20 15:19:37 -0500559 if (err != NULL) {
560 g_warning("error reading channel: %s", err->message);
Michael Roth48ff7a62011-07-20 15:19:37 -0500561 g_error_free(err);
562 return false;
563 }
564 switch (status) {
565 case G_IO_STATUS_ERROR:
Michael Roth125b3102012-01-19 00:18:20 -0600566 g_warning("error reading channel");
Michael Roth48ff7a62011-07-20 15:19:37 -0500567 return false;
568 case G_IO_STATUS_NORMAL:
Michael Roth125b3102012-01-19 00:18:20 -0600569 buf[count] = 0;
Michael Roth48ff7a62011-07-20 15:19:37 -0500570 g_debug("read data, count: %d, data: %s", (int)count, buf);
571 json_message_parser_feed(&s->parser, (char *)buf, (int)count);
Michael Roth125b3102012-01-19 00:18:20 -0600572 break;
573 case G_IO_STATUS_EOF:
574 g_debug("received EOF");
575 if (!s->virtio) {
576 return false;
577 }
Michael Roth48ff7a62011-07-20 15:19:37 -0500578 case G_IO_STATUS_AGAIN:
579 /* virtio causes us to spin here when no process is attached to
580 * host-side chardev. sleep a bit to mitigate this
581 */
582 if (s->virtio) {
583 usleep(100*1000);
584 }
585 return true;
Michael Roth48ff7a62011-07-20 15:19:37 -0500586 default:
587 g_warning("unknown channel read status, closing");
Michael Roth48ff7a62011-07-20 15:19:37 -0500588 return false;
589 }
590 return true;
591}
592
Michael Roth125b3102012-01-19 00:18:20 -0600593static gboolean channel_init(GAState *s, const gchar *method, const gchar *path)
Michael Roth48ff7a62011-07-20 15:19:37 -0500594{
Michael Roth125b3102012-01-19 00:18:20 -0600595 GAChannelMethod channel_method;
Michael Roth48ff7a62011-07-20 15:19:37 -0500596
Michael Roth125b3102012-01-19 00:18:20 -0600597 if (method == NULL) {
598 method = "virtio-serial";
Michael Roth48ff7a62011-07-20 15:19:37 -0500599 }
600
Michael Roth125b3102012-01-19 00:18:20 -0600601 if (path == NULL) {
602 if (strcmp(method, "virtio-serial") != 0) {
Michael Roth48ff7a62011-07-20 15:19:37 -0500603 g_critical("must specify a path for this channel");
Michael Roth125b3102012-01-19 00:18:20 -0600604 return false;
Michael Roth48ff7a62011-07-20 15:19:37 -0500605 }
606 /* try the default path for the virtio-serial port */
Michael Roth125b3102012-01-19 00:18:20 -0600607 path = QGA_VIRTIO_PATH_DEFAULT;
Michael Roth48ff7a62011-07-20 15:19:37 -0500608 }
609
Michael Roth125b3102012-01-19 00:18:20 -0600610 if (strcmp(method, "virtio-serial") == 0) {
611 s->virtio = true; /* virtio requires special handling in some cases */
612 channel_method = GA_CHANNEL_VIRTIO_SERIAL;
613 } else if (strcmp(method, "isa-serial") == 0) {
614 channel_method = GA_CHANNEL_ISA_SERIAL;
615 } else if (strcmp(method, "unix-listen") == 0) {
616 channel_method = GA_CHANNEL_UNIX_LISTEN;
Michael Roth48ff7a62011-07-20 15:19:37 -0500617 } else {
Michael Roth125b3102012-01-19 00:18:20 -0600618 g_critical("unsupported channel method/type: %s", method);
619 return false;
Michael Roth48ff7a62011-07-20 15:19:37 -0500620 }
621
Michael Roth125b3102012-01-19 00:18:20 -0600622 s->channel = ga_channel_new(channel_method, path, channel_event_cb, s);
623 if (!s->channel) {
624 g_critical("failed to create guest agent channel");
625 return false;
626 }
627
628 return true;
Michael Roth48ff7a62011-07-20 15:19:37 -0500629}
630
Michael Rothbc62fa02012-01-21 16:42:27 -0600631#ifdef _WIN32
632DWORD WINAPI service_ctrl_handler(DWORD ctrl, DWORD type, LPVOID data,
633 LPVOID ctx)
634{
635 DWORD ret = NO_ERROR;
636 GAService *service = &ga_state->service;
637
638 switch (ctrl)
639 {
640 case SERVICE_CONTROL_STOP:
641 case SERVICE_CONTROL_SHUTDOWN:
642 quit_handler(SIGTERM);
643 service->status.dwCurrentState = SERVICE_STOP_PENDING;
644 SetServiceStatus(service->status_handle, &service->status);
645 break;
646
647 default:
648 ret = ERROR_CALL_NOT_IMPLEMENTED;
649 }
650 return ret;
651}
652
653VOID WINAPI service_main(DWORD argc, TCHAR *argv[])
654{
655 GAService *service = &ga_state->service;
656
657 service->status_handle = RegisterServiceCtrlHandlerEx(QGA_SERVICE_NAME,
658 service_ctrl_handler, NULL);
659
660 if (service->status_handle == 0) {
661 g_critical("Failed to register extended requests function!\n");
662 return;
663 }
664
665 service->status.dwServiceType = SERVICE_WIN32;
666 service->status.dwCurrentState = SERVICE_RUNNING;
667 service->status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
668 service->status.dwWin32ExitCode = NO_ERROR;
669 service->status.dwServiceSpecificExitCode = NO_ERROR;
670 service->status.dwCheckPoint = 0;
671 service->status.dwWaitHint = 0;
672 SetServiceStatus(service->status_handle, &service->status);
673
674 g_main_loop_run(ga_state->main_loop);
675
676 service->status.dwCurrentState = SERVICE_STOPPED;
677 SetServiceStatus(service->status_handle, &service->status);
678}
679#endif
680
Michael Roth48ff7a62011-07-20 15:19:37 -0500681int main(int argc, char **argv)
682{
Michael Rothf789aa72012-04-18 16:28:01 -0500683 const char *sopt = "hVvdm:p:l:f:b:s:t:";
684 const char *method = NULL, *path = NULL;
685 const char *log_filepath = NULL;
686 const char *pid_filepath = QGA_PIDFILE_DEFAULT;
687 const char *state_dir = QGA_STATEDIR_DEFAULT;
Michael Rothbc62fa02012-01-21 16:42:27 -0600688#ifdef _WIN32
689 const char *service = NULL;
690#endif
Michael Roth48ff7a62011-07-20 15:19:37 -0500691 const struct option lopt[] = {
692 { "help", 0, NULL, 'h' },
693 { "version", 0, NULL, 'V' },
Michael Rothbc62fa02012-01-21 16:42:27 -0600694 { "logfile", 1, NULL, 'l' },
695 { "pidfile", 1, NULL, 'f' },
Michael Roth48ff7a62011-07-20 15:19:37 -0500696 { "verbose", 0, NULL, 'v' },
Michael Rothbc62fa02012-01-21 16:42:27 -0600697 { "method", 1, NULL, 'm' },
698 { "path", 1, NULL, 'p' },
Michael Roth48ff7a62011-07-20 15:19:37 -0500699 { "daemonize", 0, NULL, 'd' },
Michael Rothbc62fa02012-01-21 16:42:27 -0600700 { "blacklist", 1, NULL, 'b' },
701#ifdef _WIN32
702 { "service", 1, NULL, 's' },
Michael Rothf22d85e2012-04-17 19:01:45 -0500703#endif
Michael Rothf789aa72012-04-18 16:28:01 -0500704 { "statedir", 1, NULL, 't' },
Michael Roth48ff7a62011-07-20 15:19:37 -0500705 { NULL, 0, NULL, 0 }
706 };
Michael Rothabd6cf62011-12-06 22:03:42 -0600707 int opt_ind = 0, ch, daemonize = 0, i, j, len;
Michael Roth48ff7a62011-07-20 15:19:37 -0500708 GLogLevelFlags log_level = G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL;
Michael Rothf22d85e2012-04-17 19:01:45 -0500709 GList *blacklist = NULL;
Michael Roth48ff7a62011-07-20 15:19:37 -0500710 GAState *s;
711
Michael Rothabd6cf62011-12-06 22:03:42 -0600712 module_call_init(MODULE_INIT_QAPI);
713
Michael Roth48ff7a62011-07-20 15:19:37 -0500714 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
715 switch (ch) {
716 case 'm':
717 method = optarg;
718 break;
719 case 'p':
720 path = optarg;
721 break;
722 case 'l':
Michael Rothf789aa72012-04-18 16:28:01 -0500723 log_filepath = optarg;
Michael Roth48ff7a62011-07-20 15:19:37 -0500724 break;
725 case 'f':
Michael Rothf789aa72012-04-18 16:28:01 -0500726 pid_filepath = optarg;
Michael Roth48ff7a62011-07-20 15:19:37 -0500727 break;
Michael Rothf789aa72012-04-18 16:28:01 -0500728 case 't':
729 state_dir = optarg;
730 break;
Michael Roth48ff7a62011-07-20 15:19:37 -0500731 case 'v':
732 /* enable all log levels */
733 log_level = G_LOG_LEVEL_MASK;
734 break;
735 case 'V':
Michael Roth8efacc42012-05-14 09:33:48 -0500736 printf("QEMU Guest Agent %s\n", QEMU_VERSION);
Michael Roth48ff7a62011-07-20 15:19:37 -0500737 return 0;
738 case 'd':
739 daemonize = 1;
740 break;
Michael Rothabd6cf62011-12-06 22:03:42 -0600741 case 'b': {
742 char **list_head, **list;
Peter Maydellc8057f92012-08-02 13:45:54 +0100743 if (is_help_option(optarg)) {
Michael Rothabd6cf62011-12-06 22:03:42 -0600744 list_head = list = qmp_get_command_list();
745 while (*list != NULL) {
746 printf("%s\n", *list);
747 g_free(*list);
748 list++;
749 }
750 g_free(list_head);
751 return 0;
752 }
753 for (j = 0, i = 0, len = strlen(optarg); i < len; i++) {
754 if (optarg[i] == ',') {
755 optarg[i] = 0;
Michael Rothf22d85e2012-04-17 19:01:45 -0500756 blacklist = g_list_append(blacklist, &optarg[j]);
Michael Rothabd6cf62011-12-06 22:03:42 -0600757 j = i + 1;
758 }
759 }
760 if (j < i) {
Michael Rothf22d85e2012-04-17 19:01:45 -0500761 blacklist = g_list_append(blacklist, &optarg[j]);
Michael Rothabd6cf62011-12-06 22:03:42 -0600762 }
763 break;
764 }
Michael Rothbc62fa02012-01-21 16:42:27 -0600765#ifdef _WIN32
766 case 's':
767 service = optarg;
768 if (strcmp(service, "install") == 0) {
Michael Rothf789aa72012-04-18 16:28:01 -0500769 return ga_install_service(path, log_filepath);
Michael Rothbc62fa02012-01-21 16:42:27 -0600770 } else if (strcmp(service, "uninstall") == 0) {
771 return ga_uninstall_service();
772 } else {
773 printf("Unknown service command.\n");
774 return EXIT_FAILURE;
775 }
776 break;
777#endif
Michael Roth48ff7a62011-07-20 15:19:37 -0500778 case 'h':
779 usage(argv[0]);
780 return 0;
781 case '?':
782 g_print("Unknown option, try '%s --help' for more information.\n",
783 argv[0]);
784 return EXIT_FAILURE;
785 }
786 }
787
Michael Rothf789aa72012-04-18 16:28:01 -0500788 s = g_malloc0(sizeof(GAState));
789 s->log_level = log_level;
790 s->log_file = stderr;
791 g_log_set_default_handler(ga_log, s);
792 g_log_set_fatal_mask(NULL, G_LOG_LEVEL_ERROR);
793 ga_enable_logging(s);
794 s->state_filepath_isfrozen = g_strdup_printf("%s/qga.state.isfrozen",
795 state_dir);
796 s->frozen = false;
Michael Rothd8ca6852012-01-19 22:04:34 -0600797#ifndef _WIN32
Michael Rothf789aa72012-04-18 16:28:01 -0500798 /* check if a previous instance of qemu-ga exited with filesystems' state
799 * marked as frozen. this could be a stale value (a non-qemu-ga process
800 * or reboot may have since unfrozen them), but better to require an
801 * uneeded unfreeze than to risk hanging on start-up
802 */
803 struct stat st;
804 if (stat(s->state_filepath_isfrozen, &st) == -1) {
805 /* it's okay if the file doesn't exist, but if we can't access for
806 * some other reason, such as permissions, there's a configuration
807 * that needs to be addressed. so just bail now before we get into
808 * more trouble later
809 */
810 if (errno != ENOENT) {
811 g_critical("unable to access state file at path %s: %s",
812 s->state_filepath_isfrozen, strerror(errno));
813 return EXIT_FAILURE;
814 }
815 } else {
816 g_warning("previous instance appears to have exited with frozen"
817 " filesystems. deferring logging/pidfile creation and"
818 " disabling non-fsfreeze-safe commands until"
819 " guest-fsfreeze-thaw is issued, or filesystems are"
820 " manually unfrozen and the file %s is removed",
821 s->state_filepath_isfrozen);
822 s->frozen = true;
Michael Roth48ff7a62011-07-20 15:19:37 -0500823 }
Michael Rothd8ca6852012-01-19 22:04:34 -0600824#endif
Michael Roth48ff7a62011-07-20 15:19:37 -0500825
Michael Rothf789aa72012-04-18 16:28:01 -0500826 if (ga_is_frozen(s)) {
827 if (daemonize) {
828 /* delay opening/locking of pidfile till filesystem are unfrozen */
829 s->deferred_options.pid_filepath = pid_filepath;
830 become_daemon(NULL);
831 }
832 if (log_filepath) {
833 /* delay opening the log file till filesystems are unfrozen */
834 s->deferred_options.log_filepath = log_filepath;
835 }
836 ga_disable_logging(s);
837 ga_disable_non_whitelisted();
838 } else {
839 if (daemonize) {
840 become_daemon(pid_filepath);
841 }
842 if (log_filepath) {
Michael Roth6c615ec2012-05-14 16:42:35 -0500843 FILE *log_file = fopen(log_filepath, "a");
844 if (!log_file) {
Michael Rothf789aa72012-04-18 16:28:01 -0500845 g_critical("unable to open specified log file: %s",
846 strerror(errno));
847 goto out_bad;
848 }
Michael Roth6c615ec2012-05-14 16:42:35 -0500849 s->log_file = log_file;
Michael Rothf789aa72012-04-18 16:28:01 -0500850 }
851 }
852
Michael Rothf22d85e2012-04-17 19:01:45 -0500853 if (blacklist) {
854 s->blacklist = blacklist;
855 do {
856 g_debug("disabling command: %s", (char *)blacklist->data);
857 qmp_disable_command(blacklist->data);
858 blacklist = g_list_next(blacklist);
859 } while (blacklist);
860 }
Michael Rothe3d4d252011-07-19 15:41:55 -0500861 s->command_state = ga_command_state_new();
862 ga_command_state_init(s, s->command_state);
863 ga_command_state_init_all(s->command_state);
Michael Roth125b3102012-01-19 00:18:20 -0600864 json_message_parser_init(&s->parser, process_event);
Michael Roth48ff7a62011-07-20 15:19:37 -0500865 ga_state = s;
Michael Rothd8ca6852012-01-19 22:04:34 -0600866#ifndef _WIN32
Michael Roth125b3102012-01-19 00:18:20 -0600867 if (!register_signal_handlers()) {
868 g_critical("failed to register signal handlers");
869 goto out_bad;
870 }
Michael Rothd8ca6852012-01-19 22:04:34 -0600871#endif
Michael Roth48ff7a62011-07-20 15:19:37 -0500872
Michael Roth125b3102012-01-19 00:18:20 -0600873 s->main_loop = g_main_loop_new(NULL, false);
874 if (!channel_init(ga_state, method, path)) {
875 g_critical("failed to initialize guest agent channel");
876 goto out_bad;
877 }
Michael Rothbc62fa02012-01-21 16:42:27 -0600878#ifndef _WIN32
Michael Roth48ff7a62011-07-20 15:19:37 -0500879 g_main_loop_run(ga_state->main_loop);
Michael Rothbc62fa02012-01-21 16:42:27 -0600880#else
881 if (daemonize) {
882 SERVICE_TABLE_ENTRY service_table[] = {
883 { (char *)QGA_SERVICE_NAME, service_main }, { NULL, NULL } };
884 StartServiceCtrlDispatcher(service_table);
885 } else {
886 g_main_loop_run(ga_state->main_loop);
887 }
888#endif
Michael Roth48ff7a62011-07-20 15:19:37 -0500889
Michael Rothe3d4d252011-07-19 15:41:55 -0500890 ga_command_state_cleanup_all(ga_state->command_state);
Michael Roth125b3102012-01-19 00:18:20 -0600891 ga_channel_free(ga_state->channel);
Michael Roth48ff7a62011-07-20 15:19:37 -0500892
Michael Roth125b3102012-01-19 00:18:20 -0600893 if (daemonize) {
Michael Rothf789aa72012-04-18 16:28:01 -0500894 unlink(pid_filepath);
Michael Roth125b3102012-01-19 00:18:20 -0600895 }
Michael Roth48ff7a62011-07-20 15:19:37 -0500896 return 0;
Michael Roth125b3102012-01-19 00:18:20 -0600897
898out_bad:
899 if (daemonize) {
Michael Rothf789aa72012-04-18 16:28:01 -0500900 unlink(pid_filepath);
Michael Roth125b3102012-01-19 00:18:20 -0600901 }
902 return EXIT_FAILURE;
Michael Roth48ff7a62011-07-20 15:19:37 -0500903}