blob: 216be39072b926c90d57eb324118c08a8dfdbba4 [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"
31#include "error_int.h"
Michael Rothabd6cf62011-12-06 22:03:42 -060032#include "qapi/qmp-core.h"
Michael Roth125b3102012-01-19 00:18:20 -060033#include "qga/channel.h"
Michael Rothbc62fa02012-01-21 16:42:27 -060034#ifdef _WIN32
35#include "qga/service-win32.h"
36#include <windows.h>
37#endif
Michael Roth48ff7a62011-07-20 15:19:37 -050038
Michael Roth7868e262012-01-20 19:01:30 -060039#ifndef _WIN32
Michael Roth48ff7a62011-07-20 15:19:37 -050040#define QGA_VIRTIO_PATH_DEFAULT "/dev/virtio-ports/org.qemu.guest_agent.0"
Michael Roth7868e262012-01-20 19:01:30 -060041#else
42#define QGA_VIRTIO_PATH_DEFAULT "\\\\.\\Global\\org.qemu.guest_agent.0"
43#endif
Michael Roth48ff7a62011-07-20 15:19:37 -050044#define QGA_PIDFILE_DEFAULT "/var/run/qemu-ga.pid"
Michael Rothf789aa72012-04-18 16:28:01 -050045#define QGA_STATEDIR_DEFAULT "/tmp"
Michael Roth3cf0bed2012-02-07 13:56:48 -060046#define QGA_SENTINEL_BYTE 0xFF
Michael Roth48ff7a62011-07-20 15:19:37 -050047
48struct GAState {
49 JSONMessageParser parser;
50 GMainLoop *main_loop;
Michael Roth125b3102012-01-19 00:18:20 -060051 GAChannel *channel;
Michael Roth48ff7a62011-07-20 15:19:37 -050052 bool virtio; /* fastpath to check for virtio to deal with poll() quirks */
53 GACommandState *command_state;
54 GLogLevelFlags log_level;
55 FILE *log_file;
56 bool logging_enabled;
Michael Rothbc62fa02012-01-21 16:42:27 -060057#ifdef _WIN32
58 GAService service;
59#endif
Michael Roth3cf0bed2012-02-07 13:56:48 -060060 bool delimit_response;
Michael Rothf22d85e2012-04-17 19:01:45 -050061 bool frozen;
62 GList *blacklist;
Michael Rothf789aa72012-04-18 16:28:01 -050063 const char *state_filepath_isfrozen;
64 struct {
65 const char *log_filepath;
66 const char *pid_filepath;
67 } deferred_options;
Michael Roth48ff7a62011-07-20 15:19:37 -050068};
69
Michael Roth3cf0bed2012-02-07 13:56:48 -060070struct GAState *ga_state;
Michael Roth48ff7a62011-07-20 15:19:37 -050071
Michael Rothf22d85e2012-04-17 19:01:45 -050072/* commands that are safe to issue while filesystems are frozen */
73static const char *ga_freeze_whitelist[] = {
74 "guest-ping",
75 "guest-info",
76 "guest-sync",
77 "guest-fsfreeze-status",
78 "guest-fsfreeze-thaw",
79 NULL
80};
81
Michael Rothbc62fa02012-01-21 16:42:27 -060082#ifdef _WIN32
83DWORD WINAPI service_ctrl_handler(DWORD ctrl, DWORD type, LPVOID data,
84 LPVOID ctx);
85VOID WINAPI service_main(DWORD argc, TCHAR *argv[]);
86#endif
87
Michael Roth48ff7a62011-07-20 15:19:37 -050088static void quit_handler(int sig)
89{
Michael Rothf22d85e2012-04-17 19:01:45 -050090 /* if we're frozen, don't exit unless we're absolutely forced to,
91 * because it's basically impossible for graceful exit to complete
92 * unless all log/pid files are on unfreezable filesystems. there's
93 * also a very likely chance killing the agent before unfreezing
94 * the filesystems is a mistake (or will be viewed as one later).
95 */
96 if (ga_is_frozen(ga_state)) {
97 return;
98 }
Stefan Weil2542bfd2011-08-28 21:45:40 +020099 g_debug("received signal num %d, quitting", sig);
Michael Roth48ff7a62011-07-20 15:19:37 -0500100
101 if (g_main_loop_is_running(ga_state->main_loop)) {
102 g_main_loop_quit(ga_state->main_loop);
103 }
104}
105
Michael Rothbc62fa02012-01-21 16:42:27 -0600106#ifndef _WIN32
Luiz Capitulino11d0f122012-02-28 11:03:03 -0300107/* reap _all_ terminated children */
108static void child_handler(int sig)
109{
110 int status;
111 while (waitpid(-1, &status, WNOHANG) > 0) /* NOTHING */;
112}
113
Michael Roth125b3102012-01-19 00:18:20 -0600114static gboolean register_signal_handlers(void)
Michael Roth48ff7a62011-07-20 15:19:37 -0500115{
Luiz Capitulino11d0f122012-02-28 11:03:03 -0300116 struct sigaction sigact, sigact_chld;
Michael Roth48ff7a62011-07-20 15:19:37 -0500117 int ret;
118
119 memset(&sigact, 0, sizeof(struct sigaction));
120 sigact.sa_handler = quit_handler;
121
122 ret = sigaction(SIGINT, &sigact, NULL);
123 if (ret == -1) {
124 g_error("error configuring signal handler: %s", strerror(errno));
Michael Roth125b3102012-01-19 00:18:20 -0600125 return false;
Michael Roth48ff7a62011-07-20 15:19:37 -0500126 }
127 ret = sigaction(SIGTERM, &sigact, NULL);
128 if (ret == -1) {
129 g_error("error configuring signal handler: %s", strerror(errno));
Michael Roth125b3102012-01-19 00:18:20 -0600130 return false;
Michael Roth48ff7a62011-07-20 15:19:37 -0500131 }
Luiz Capitulino11d0f122012-02-28 11:03:03 -0300132
133 memset(&sigact_chld, 0, sizeof(struct sigaction));
134 sigact_chld.sa_handler = child_handler;
135 sigact_chld.sa_flags = SA_NOCLDSTOP;
136 ret = sigaction(SIGCHLD, &sigact_chld, NULL);
137 if (ret == -1) {
138 g_error("error configuring signal handler: %s", strerror(errno));
139 }
140
Michael Roth125b3102012-01-19 00:18:20 -0600141 return true;
Michael Roth48ff7a62011-07-20 15:19:37 -0500142}
Michael Rothd8ca6852012-01-19 22:04:34 -0600143#endif
Michael Roth48ff7a62011-07-20 15:19:37 -0500144
145static void usage(const char *cmd)
146{
147 printf(
Michael Roth4bdd0412012-04-17 11:28:27 -0500148"Usage: %s [-m <method> -p <path>] [<options>]\n"
Michael Roth48ff7a62011-07-20 15:19:37 -0500149"QEMU Guest Agent %s\n"
150"\n"
151" -m, --method transport method: one of unix-listen, virtio-serial, or\n"
152" isa-serial (virtio-serial is the default)\n"
Michael Roth4bdd0412012-04-17 11:28:27 -0500153" -p, --path device/socket path (the default for virtio-serial is:\n"
154" %s)\n"
Michael Roth48ff7a62011-07-20 15:19:37 -0500155" -l, --logfile set logfile path, logs to stderr by default\n"
156" -f, --pidfile specify pidfile (default is %s)\n"
Michael Rothf789aa72012-04-18 16:28:01 -0500157" -t, --statedir specify dir to store state information (absolute paths\n"
158" only, default is %s)\n"
Michael Roth48ff7a62011-07-20 15:19:37 -0500159" -v, --verbose log extra debugging information\n"
160" -V, --version print version information and exit\n"
161" -d, --daemonize become a daemon\n"
Michael Rothbc62fa02012-01-21 16:42:27 -0600162#ifdef _WIN32
163" -s, --service service commands: install, uninstall\n"
Michael Rothd8ca6852012-01-19 22:04:34 -0600164#endif
Michael Roth4bdd0412012-04-17 11:28:27 -0500165" -b, --blacklist comma-separated list of RPCs to disable (no spaces, \"?\"\n"
Michael Rothabd6cf62011-12-06 22:03:42 -0600166" to list available RPCs)\n"
Michael Roth48ff7a62011-07-20 15:19:37 -0500167" -h, --help display this help and exit\n"
168"\n"
169"Report bugs to <mdroth@linux.vnet.ibm.com>\n"
Michael Rothf789aa72012-04-18 16:28:01 -0500170 , cmd, QGA_VERSION, QGA_VIRTIO_PATH_DEFAULT, QGA_PIDFILE_DEFAULT,
171 QGA_STATEDIR_DEFAULT);
Michael Roth48ff7a62011-07-20 15:19:37 -0500172}
173
Michael Roth48ff7a62011-07-20 15:19:37 -0500174static const char *ga_log_level_str(GLogLevelFlags level)
175{
176 switch (level & G_LOG_LEVEL_MASK) {
177 case G_LOG_LEVEL_ERROR:
178 return "error";
179 case G_LOG_LEVEL_CRITICAL:
180 return "critical";
181 case G_LOG_LEVEL_WARNING:
182 return "warning";
183 case G_LOG_LEVEL_MESSAGE:
184 return "message";
185 case G_LOG_LEVEL_INFO:
186 return "info";
187 case G_LOG_LEVEL_DEBUG:
188 return "debug";
189 default:
190 return "user";
191 }
192}
193
194bool ga_logging_enabled(GAState *s)
195{
196 return s->logging_enabled;
197}
198
199void ga_disable_logging(GAState *s)
200{
201 s->logging_enabled = false;
202}
203
204void ga_enable_logging(GAState *s)
205{
206 s->logging_enabled = true;
207}
208
209static void ga_log(const gchar *domain, GLogLevelFlags level,
210 const gchar *msg, gpointer opaque)
211{
212 GAState *s = opaque;
213 GTimeVal time;
214 const char *level_str = ga_log_level_str(level);
215
216 if (!ga_logging_enabled(s)) {
217 return;
218 }
219
220 level &= G_LOG_LEVEL_MASK;
Michael Rothd8ca6852012-01-19 22:04:34 -0600221#ifndef _WIN32
Michael Roth8f477472011-08-11 15:38:11 -0500222 if (domain && strcmp(domain, "syslog") == 0) {
Michael Roth48ff7a62011-07-20 15:19:37 -0500223 syslog(LOG_INFO, "%s: %s", level_str, msg);
224 } else if (level & s->log_level) {
Michael Rothd8ca6852012-01-19 22:04:34 -0600225#else
226 if (level & s->log_level) {
227#endif
Michael Roth48ff7a62011-07-20 15:19:37 -0500228 g_get_current_time(&time);
229 fprintf(s->log_file,
230 "%lu.%lu: %s: %s\n", time.tv_sec, time.tv_usec, level_str, msg);
231 fflush(s->log_file);
232 }
233}
234
Michael Roth3cf0bed2012-02-07 13:56:48 -0600235void ga_set_response_delimited(GAState *s)
236{
237 s->delimit_response = true;
238}
239
Michael Rothf789aa72012-04-18 16:28:01 -0500240#ifndef _WIN32
241static bool ga_open_pidfile(const char *pidfile)
242{
243 int pidfd;
244 char pidstr[32];
245
246 pidfd = open(pidfile, O_CREAT|O_WRONLY, S_IRUSR|S_IWUSR);
247 if (pidfd == -1 || lockf(pidfd, F_TLOCK, 0)) {
248 g_critical("Cannot lock pid file, %s", strerror(errno));
249 return false;
250 }
251
252 if (ftruncate(pidfd, 0) || lseek(pidfd, 0, SEEK_SET)) {
253 g_critical("Failed to truncate pid file");
254 goto fail;
255 }
256 sprintf(pidstr, "%d", getpid());
257 if (write(pidfd, pidstr, strlen(pidstr)) != strlen(pidstr)) {
258 g_critical("Failed to write pid file");
259 goto fail;
260 }
261
262 return true;
263
264fail:
265 unlink(pidfile);
266 return false;
267}
268#else /* _WIN32 */
269static bool ga_open_pidfile(const char *pidfile)
270{
271 return true;
272}
273#endif
274
Michael Rothf22d85e2012-04-17 19:01:45 -0500275static gint ga_strcmp(gconstpointer str1, gconstpointer str2)
276{
277 return strcmp(str1, str2);
278}
279
280/* disable commands that aren't safe for fsfreeze */
281static void ga_disable_non_whitelisted(void)
282{
283 char **list_head, **list;
284 bool whitelisted;
285 int i;
286
287 list_head = list = qmp_get_command_list();
288 while (*list != NULL) {
289 whitelisted = false;
290 i = 0;
291 while (ga_freeze_whitelist[i] != NULL) {
292 if (strcmp(*list, ga_freeze_whitelist[i]) == 0) {
293 whitelisted = true;
294 }
295 i++;
296 }
297 if (!whitelisted) {
298 g_debug("disabling command: %s", *list);
299 qmp_disable_command(*list);
300 }
301 g_free(*list);
302 list++;
303 }
304 g_free(list_head);
305}
306
307/* [re-]enable all commands, except those explictly blacklisted by user */
308static void ga_enable_non_blacklisted(GList *blacklist)
309{
310 char **list_head, **list;
311
312 list_head = list = qmp_get_command_list();
313 while (*list != NULL) {
314 if (g_list_find_custom(blacklist, *list, ga_strcmp) == NULL &&
315 !qmp_command_is_enabled(*list)) {
316 g_debug("enabling command: %s", *list);
317 qmp_enable_command(*list);
318 }
319 g_free(*list);
320 list++;
321 }
322 g_free(list_head);
323}
324
Michael Rothf789aa72012-04-18 16:28:01 -0500325static bool ga_create_file(const char *path)
326{
327 int fd = open(path, O_CREAT | O_WRONLY, S_IWUSR | S_IRUSR);
328 if (fd == -1) {
329 g_warning("unable to open/create file %s: %s", path, strerror(errno));
330 return false;
331 }
332 close(fd);
333 return true;
334}
335
336static bool ga_delete_file(const char *path)
337{
338 int ret = unlink(path);
339 if (ret == -1) {
340 g_warning("unable to delete file: %s: %s", path, strerror(errno));
341 return false;
342 }
343
344 return true;
345}
346
Michael Rothf22d85e2012-04-17 19:01:45 -0500347bool ga_is_frozen(GAState *s)
348{
349 return s->frozen;
350}
351
352void ga_set_frozen(GAState *s)
353{
354 if (ga_is_frozen(s)) {
355 return;
356 }
357 /* disable all non-whitelisted (for frozen state) commands */
358 ga_disable_non_whitelisted();
359 g_warning("disabling logging due to filesystem freeze");
360 ga_disable_logging(s);
361 s->frozen = true;
Michael Rothf789aa72012-04-18 16:28:01 -0500362 if (!ga_create_file(s->state_filepath_isfrozen)) {
363 g_warning("unable to create %s, fsfreeze may not function properly",
364 s->state_filepath_isfrozen);
365 }
Michael Rothf22d85e2012-04-17 19:01:45 -0500366}
367
368void ga_unset_frozen(GAState *s)
369{
370 if (!ga_is_frozen(s)) {
371 return;
372 }
373
Michael Rothf789aa72012-04-18 16:28:01 -0500374 /* if we delayed creation/opening of pid/log files due to being
375 * in a frozen state at start up, do it now
376 */
377 if (s->deferred_options.log_filepath) {
378 s->log_file = fopen(s->deferred_options.log_filepath, "a");
379 if (!s->log_file) {
380 s->log_file = stderr;
381 }
382 s->deferred_options.log_filepath = NULL;
383 }
Michael Rothf22d85e2012-04-17 19:01:45 -0500384 ga_enable_logging(s);
Michael Rothf789aa72012-04-18 16:28:01 -0500385 g_warning("logging re-enabled due to filesystem unfreeze");
386 if (s->deferred_options.pid_filepath) {
387 if (!ga_open_pidfile(s->deferred_options.pid_filepath)) {
388 g_warning("failed to create/open pid file");
389 }
390 s->deferred_options.pid_filepath = NULL;
391 }
Michael Rothf22d85e2012-04-17 19:01:45 -0500392
393 /* enable all disabled, non-blacklisted commands */
394 ga_enable_non_blacklisted(s->blacklist);
395 s->frozen = false;
Michael Rothf789aa72012-04-18 16:28:01 -0500396 if (!ga_delete_file(s->state_filepath_isfrozen)) {
397 g_warning("unable to delete %s, fsfreeze may not function properly",
398 s->state_filepath_isfrozen);
399 }
Michael Rothf22d85e2012-04-17 19:01:45 -0500400}
401
Michael Roth48ff7a62011-07-20 15:19:37 -0500402static void become_daemon(const char *pidfile)
403{
Michael Rothf789aa72012-04-18 16:28:01 -0500404#ifndef _WIN32
Michael Roth48ff7a62011-07-20 15:19:37 -0500405 pid_t pid, sid;
Michael Roth48ff7a62011-07-20 15:19:37 -0500406
407 pid = fork();
408 if (pid < 0) {
409 exit(EXIT_FAILURE);
410 }
411 if (pid > 0) {
412 exit(EXIT_SUCCESS);
413 }
414
Michael Rothf789aa72012-04-18 16:28:01 -0500415 if (pidfile) {
416 if (!ga_open_pidfile(pidfile)) {
417 g_critical("failed to create pidfile");
418 exit(EXIT_FAILURE);
419 }
Michael Roth48ff7a62011-07-20 15:19:37 -0500420 }
421
422 umask(0);
423 sid = setsid();
424 if (sid < 0) {
425 goto fail;
426 }
427 if ((chdir("/")) < 0) {
428 goto fail;
429 }
430
431 close(STDIN_FILENO);
432 close(STDOUT_FILENO);
433 close(STDERR_FILENO);
Michael Roth48ff7a62011-07-20 15:19:37 -0500434 return;
435
436fail:
437 unlink(pidfile);
438 g_critical("failed to daemonize");
439 exit(EXIT_FAILURE);
Michael Rothd8ca6852012-01-19 22:04:34 -0600440#endif
Michael Rothf789aa72012-04-18 16:28:01 -0500441}
Michael Roth48ff7a62011-07-20 15:19:37 -0500442
Michael Roth125b3102012-01-19 00:18:20 -0600443static int send_response(GAState *s, QObject *payload)
Michael Roth48ff7a62011-07-20 15:19:37 -0500444{
Michael Roth48ff7a62011-07-20 15:19:37 -0500445 const char *buf;
Michael Roth3cf0bed2012-02-07 13:56:48 -0600446 QString *payload_qstr, *response_qstr;
Michael Roth125b3102012-01-19 00:18:20 -0600447 GIOStatus status;
Michael Roth48ff7a62011-07-20 15:19:37 -0500448
Michael Roth125b3102012-01-19 00:18:20 -0600449 g_assert(payload && s->channel);
Michael Roth48ff7a62011-07-20 15:19:37 -0500450
451 payload_qstr = qobject_to_json(payload);
452 if (!payload_qstr) {
453 return -EINVAL;
454 }
455
Michael Roth3cf0bed2012-02-07 13:56:48 -0600456 if (s->delimit_response) {
457 s->delimit_response = false;
458 response_qstr = qstring_new();
459 qstring_append_chr(response_qstr, QGA_SENTINEL_BYTE);
460 qstring_append(response_qstr, qstring_get_str(payload_qstr));
461 QDECREF(payload_qstr);
462 } else {
463 response_qstr = payload_qstr;
464 }
465
466 qstring_append_chr(response_qstr, '\n');
467 buf = qstring_get_str(response_qstr);
Michael Roth125b3102012-01-19 00:18:20 -0600468 status = ga_channel_write_all(s->channel, buf, strlen(buf));
Michael Roth3cf0bed2012-02-07 13:56:48 -0600469 QDECREF(response_qstr);
Michael Roth125b3102012-01-19 00:18:20 -0600470 if (status != G_IO_STATUS_NORMAL) {
471 return -EIO;
Michael Roth48ff7a62011-07-20 15:19:37 -0500472 }
Michael Roth125b3102012-01-19 00:18:20 -0600473
474 return 0;
Michael Roth48ff7a62011-07-20 15:19:37 -0500475}
476
477static void process_command(GAState *s, QDict *req)
478{
479 QObject *rsp = NULL;
480 int ret;
481
482 g_assert(req);
483 g_debug("processing command");
484 rsp = qmp_dispatch(QOBJECT(req));
485 if (rsp) {
Michael Roth125b3102012-01-19 00:18:20 -0600486 ret = send_response(s, rsp);
Michael Roth48ff7a62011-07-20 15:19:37 -0500487 if (ret) {
Michael Roth125b3102012-01-19 00:18:20 -0600488 g_warning("error sending response: %s", strerror(ret));
Michael Roth48ff7a62011-07-20 15:19:37 -0500489 }
490 qobject_decref(rsp);
491 } else {
492 g_warning("error getting response");
493 }
494}
495
496/* handle requests/control events coming in over the channel */
497static void process_event(JSONMessageParser *parser, QList *tokens)
498{
499 GAState *s = container_of(parser, GAState, parser);
500 QObject *obj;
501 QDict *qdict;
502 Error *err = NULL;
503 int ret;
504
505 g_assert(s && parser);
506
507 g_debug("process_event: called");
508 obj = json_parser_parse_err(tokens, NULL, &err);
509 if (err || !obj || qobject_type(obj) != QTYPE_QDICT) {
510 qobject_decref(obj);
511 qdict = qdict_new();
512 if (!err) {
513 g_warning("failed to parse event: unknown error");
514 error_set(&err, QERR_JSON_PARSING);
515 } else {
516 g_warning("failed to parse event: %s", error_get_pretty(err));
517 }
518 qdict_put_obj(qdict, "error", error_get_qobject(err));
519 error_free(err);
520 } else {
521 qdict = qobject_to_qdict(obj);
522 }
523
524 g_assert(qdict);
525
526 /* handle host->guest commands */
527 if (qdict_haskey(qdict, "execute")) {
528 process_command(s, qdict);
529 } else {
530 if (!qdict_haskey(qdict, "error")) {
531 QDECREF(qdict);
532 qdict = qdict_new();
533 g_warning("unrecognized payload format");
534 error_set(&err, QERR_UNSUPPORTED);
535 qdict_put_obj(qdict, "error", error_get_qobject(err));
536 error_free(err);
537 }
Michael Roth125b3102012-01-19 00:18:20 -0600538 ret = send_response(s, QOBJECT(qdict));
Michael Roth48ff7a62011-07-20 15:19:37 -0500539 if (ret) {
Michael Roth125b3102012-01-19 00:18:20 -0600540 g_warning("error sending error response: %s", strerror(ret));
Michael Roth48ff7a62011-07-20 15:19:37 -0500541 }
542 }
543
544 QDECREF(qdict);
545}
546
Michael Roth125b3102012-01-19 00:18:20 -0600547/* false return signals GAChannel to close the current client connection */
548static gboolean channel_event_cb(GIOCondition condition, gpointer data)
Michael Roth48ff7a62011-07-20 15:19:37 -0500549{
550 GAState *s = data;
Michael Roth125b3102012-01-19 00:18:20 -0600551 gchar buf[QGA_READ_COUNT_DEFAULT+1];
Michael Roth48ff7a62011-07-20 15:19:37 -0500552 gsize count;
553 GError *err = NULL;
Michael Roth125b3102012-01-19 00:18:20 -0600554 GIOStatus status = ga_channel_read(s->channel, buf, QGA_READ_COUNT_DEFAULT, &count);
Michael Roth48ff7a62011-07-20 15:19:37 -0500555 if (err != NULL) {
556 g_warning("error reading channel: %s", err->message);
Michael Roth48ff7a62011-07-20 15:19:37 -0500557 g_error_free(err);
558 return false;
559 }
560 switch (status) {
561 case G_IO_STATUS_ERROR:
Michael Roth125b3102012-01-19 00:18:20 -0600562 g_warning("error reading channel");
Michael Roth48ff7a62011-07-20 15:19:37 -0500563 return false;
564 case G_IO_STATUS_NORMAL:
Michael Roth125b3102012-01-19 00:18:20 -0600565 buf[count] = 0;
Michael Roth48ff7a62011-07-20 15:19:37 -0500566 g_debug("read data, count: %d, data: %s", (int)count, buf);
567 json_message_parser_feed(&s->parser, (char *)buf, (int)count);
Michael Roth125b3102012-01-19 00:18:20 -0600568 break;
569 case G_IO_STATUS_EOF:
570 g_debug("received EOF");
571 if (!s->virtio) {
572 return false;
573 }
Michael Roth48ff7a62011-07-20 15:19:37 -0500574 case G_IO_STATUS_AGAIN:
575 /* virtio causes us to spin here when no process is attached to
576 * host-side chardev. sleep a bit to mitigate this
577 */
578 if (s->virtio) {
579 usleep(100*1000);
580 }
581 return true;
Michael Roth48ff7a62011-07-20 15:19:37 -0500582 default:
583 g_warning("unknown channel read status, closing");
Michael Roth48ff7a62011-07-20 15:19:37 -0500584 return false;
585 }
586 return true;
587}
588
Michael Roth125b3102012-01-19 00:18:20 -0600589static gboolean channel_init(GAState *s, const gchar *method, const gchar *path)
Michael Roth48ff7a62011-07-20 15:19:37 -0500590{
Michael Roth125b3102012-01-19 00:18:20 -0600591 GAChannelMethod channel_method;
Michael Roth48ff7a62011-07-20 15:19:37 -0500592
Michael Roth125b3102012-01-19 00:18:20 -0600593 if (method == NULL) {
594 method = "virtio-serial";
Michael Roth48ff7a62011-07-20 15:19:37 -0500595 }
596
Michael Roth125b3102012-01-19 00:18:20 -0600597 if (path == NULL) {
598 if (strcmp(method, "virtio-serial") != 0) {
Michael Roth48ff7a62011-07-20 15:19:37 -0500599 g_critical("must specify a path for this channel");
Michael Roth125b3102012-01-19 00:18:20 -0600600 return false;
Michael Roth48ff7a62011-07-20 15:19:37 -0500601 }
602 /* try the default path for the virtio-serial port */
Michael Roth125b3102012-01-19 00:18:20 -0600603 path = QGA_VIRTIO_PATH_DEFAULT;
Michael Roth48ff7a62011-07-20 15:19:37 -0500604 }
605
Michael Roth125b3102012-01-19 00:18:20 -0600606 if (strcmp(method, "virtio-serial") == 0) {
607 s->virtio = true; /* virtio requires special handling in some cases */
608 channel_method = GA_CHANNEL_VIRTIO_SERIAL;
609 } else if (strcmp(method, "isa-serial") == 0) {
610 channel_method = GA_CHANNEL_ISA_SERIAL;
611 } else if (strcmp(method, "unix-listen") == 0) {
612 channel_method = GA_CHANNEL_UNIX_LISTEN;
Michael Roth48ff7a62011-07-20 15:19:37 -0500613 } else {
Michael Roth125b3102012-01-19 00:18:20 -0600614 g_critical("unsupported channel method/type: %s", method);
615 return false;
Michael Roth48ff7a62011-07-20 15:19:37 -0500616 }
617
Michael Roth125b3102012-01-19 00:18:20 -0600618 s->channel = ga_channel_new(channel_method, path, channel_event_cb, s);
619 if (!s->channel) {
620 g_critical("failed to create guest agent channel");
621 return false;
622 }
623
624 return true;
Michael Roth48ff7a62011-07-20 15:19:37 -0500625}
626
Michael Rothbc62fa02012-01-21 16:42:27 -0600627#ifdef _WIN32
628DWORD WINAPI service_ctrl_handler(DWORD ctrl, DWORD type, LPVOID data,
629 LPVOID ctx)
630{
631 DWORD ret = NO_ERROR;
632 GAService *service = &ga_state->service;
633
634 switch (ctrl)
635 {
636 case SERVICE_CONTROL_STOP:
637 case SERVICE_CONTROL_SHUTDOWN:
638 quit_handler(SIGTERM);
639 service->status.dwCurrentState = SERVICE_STOP_PENDING;
640 SetServiceStatus(service->status_handle, &service->status);
641 break;
642
643 default:
644 ret = ERROR_CALL_NOT_IMPLEMENTED;
645 }
646 return ret;
647}
648
649VOID WINAPI service_main(DWORD argc, TCHAR *argv[])
650{
651 GAService *service = &ga_state->service;
652
653 service->status_handle = RegisterServiceCtrlHandlerEx(QGA_SERVICE_NAME,
654 service_ctrl_handler, NULL);
655
656 if (service->status_handle == 0) {
657 g_critical("Failed to register extended requests function!\n");
658 return;
659 }
660
661 service->status.dwServiceType = SERVICE_WIN32;
662 service->status.dwCurrentState = SERVICE_RUNNING;
663 service->status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
664 service->status.dwWin32ExitCode = NO_ERROR;
665 service->status.dwServiceSpecificExitCode = NO_ERROR;
666 service->status.dwCheckPoint = 0;
667 service->status.dwWaitHint = 0;
668 SetServiceStatus(service->status_handle, &service->status);
669
670 g_main_loop_run(ga_state->main_loop);
671
672 service->status.dwCurrentState = SERVICE_STOPPED;
673 SetServiceStatus(service->status_handle, &service->status);
674}
675#endif
676
Michael Roth48ff7a62011-07-20 15:19:37 -0500677int main(int argc, char **argv)
678{
Michael Rothf789aa72012-04-18 16:28:01 -0500679 const char *sopt = "hVvdm:p:l:f:b:s:t:";
680 const char *method = NULL, *path = NULL;
681 const char *log_filepath = NULL;
682 const char *pid_filepath = QGA_PIDFILE_DEFAULT;
683 const char *state_dir = QGA_STATEDIR_DEFAULT;
Michael Rothbc62fa02012-01-21 16:42:27 -0600684#ifdef _WIN32
685 const char *service = NULL;
686#endif
Michael Roth48ff7a62011-07-20 15:19:37 -0500687 const struct option lopt[] = {
688 { "help", 0, NULL, 'h' },
689 { "version", 0, NULL, 'V' },
Michael Rothbc62fa02012-01-21 16:42:27 -0600690 { "logfile", 1, NULL, 'l' },
691 { "pidfile", 1, NULL, 'f' },
Michael Roth48ff7a62011-07-20 15:19:37 -0500692 { "verbose", 0, NULL, 'v' },
Michael Rothbc62fa02012-01-21 16:42:27 -0600693 { "method", 1, NULL, 'm' },
694 { "path", 1, NULL, 'p' },
Michael Roth48ff7a62011-07-20 15:19:37 -0500695 { "daemonize", 0, NULL, 'd' },
Michael Rothbc62fa02012-01-21 16:42:27 -0600696 { "blacklist", 1, NULL, 'b' },
697#ifdef _WIN32
698 { "service", 1, NULL, 's' },
Michael Rothf22d85e2012-04-17 19:01:45 -0500699#endif
Michael Rothf789aa72012-04-18 16:28:01 -0500700 { "statedir", 1, NULL, 't' },
Michael Roth48ff7a62011-07-20 15:19:37 -0500701 { NULL, 0, NULL, 0 }
702 };
Michael Rothabd6cf62011-12-06 22:03:42 -0600703 int opt_ind = 0, ch, daemonize = 0, i, j, len;
Michael Roth48ff7a62011-07-20 15:19:37 -0500704 GLogLevelFlags log_level = G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL;
Michael Rothf22d85e2012-04-17 19:01:45 -0500705 GList *blacklist = NULL;
Michael Roth48ff7a62011-07-20 15:19:37 -0500706 GAState *s;
707
Michael Rothabd6cf62011-12-06 22:03:42 -0600708 module_call_init(MODULE_INIT_QAPI);
709
Michael Roth48ff7a62011-07-20 15:19:37 -0500710 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
711 switch (ch) {
712 case 'm':
713 method = optarg;
714 break;
715 case 'p':
716 path = optarg;
717 break;
718 case 'l':
Michael Rothf789aa72012-04-18 16:28:01 -0500719 log_filepath = optarg;
Michael Roth48ff7a62011-07-20 15:19:37 -0500720 break;
721 case 'f':
Michael Rothf789aa72012-04-18 16:28:01 -0500722 pid_filepath = optarg;
Michael Roth48ff7a62011-07-20 15:19:37 -0500723 break;
Michael Rothf789aa72012-04-18 16:28:01 -0500724 case 't':
725 state_dir = optarg;
726 break;
Michael Roth48ff7a62011-07-20 15:19:37 -0500727 case 'v':
728 /* enable all log levels */
729 log_level = G_LOG_LEVEL_MASK;
730 break;
731 case 'V':
732 printf("QEMU Guest Agent %s\n", QGA_VERSION);
733 return 0;
734 case 'd':
735 daemonize = 1;
736 break;
Michael Rothabd6cf62011-12-06 22:03:42 -0600737 case 'b': {
738 char **list_head, **list;
739 if (*optarg == '?') {
740 list_head = list = qmp_get_command_list();
741 while (*list != NULL) {
742 printf("%s\n", *list);
743 g_free(*list);
744 list++;
745 }
746 g_free(list_head);
747 return 0;
748 }
749 for (j = 0, i = 0, len = strlen(optarg); i < len; i++) {
750 if (optarg[i] == ',') {
751 optarg[i] = 0;
Michael Rothf22d85e2012-04-17 19:01:45 -0500752 blacklist = g_list_append(blacklist, &optarg[j]);
Michael Rothabd6cf62011-12-06 22:03:42 -0600753 j = i + 1;
754 }
755 }
756 if (j < i) {
Michael Rothf22d85e2012-04-17 19:01:45 -0500757 blacklist = g_list_append(blacklist, &optarg[j]);
Michael Rothabd6cf62011-12-06 22:03:42 -0600758 }
759 break;
760 }
Michael Rothbc62fa02012-01-21 16:42:27 -0600761#ifdef _WIN32
762 case 's':
763 service = optarg;
764 if (strcmp(service, "install") == 0) {
Michael Rothf789aa72012-04-18 16:28:01 -0500765 return ga_install_service(path, log_filepath);
Michael Rothbc62fa02012-01-21 16:42:27 -0600766 } else if (strcmp(service, "uninstall") == 0) {
767 return ga_uninstall_service();
768 } else {
769 printf("Unknown service command.\n");
770 return EXIT_FAILURE;
771 }
772 break;
773#endif
Michael Roth48ff7a62011-07-20 15:19:37 -0500774 case 'h':
775 usage(argv[0]);
776 return 0;
777 case '?':
778 g_print("Unknown option, try '%s --help' for more information.\n",
779 argv[0]);
780 return EXIT_FAILURE;
781 }
782 }
783
Michael Rothf789aa72012-04-18 16:28:01 -0500784 s = g_malloc0(sizeof(GAState));
785 s->log_level = log_level;
786 s->log_file = stderr;
787 g_log_set_default_handler(ga_log, s);
788 g_log_set_fatal_mask(NULL, G_LOG_LEVEL_ERROR);
789 ga_enable_logging(s);
790 s->state_filepath_isfrozen = g_strdup_printf("%s/qga.state.isfrozen",
791 state_dir);
792 s->frozen = false;
Michael Rothd8ca6852012-01-19 22:04:34 -0600793#ifndef _WIN32
Michael Rothf789aa72012-04-18 16:28:01 -0500794 /* check if a previous instance of qemu-ga exited with filesystems' state
795 * marked as frozen. this could be a stale value (a non-qemu-ga process
796 * or reboot may have since unfrozen them), but better to require an
797 * uneeded unfreeze than to risk hanging on start-up
798 */
799 struct stat st;
800 if (stat(s->state_filepath_isfrozen, &st) == -1) {
801 /* it's okay if the file doesn't exist, but if we can't access for
802 * some other reason, such as permissions, there's a configuration
803 * that needs to be addressed. so just bail now before we get into
804 * more trouble later
805 */
806 if (errno != ENOENT) {
807 g_critical("unable to access state file at path %s: %s",
808 s->state_filepath_isfrozen, strerror(errno));
809 return EXIT_FAILURE;
810 }
811 } else {
812 g_warning("previous instance appears to have exited with frozen"
813 " filesystems. deferring logging/pidfile creation and"
814 " disabling non-fsfreeze-safe commands until"
815 " guest-fsfreeze-thaw is issued, or filesystems are"
816 " manually unfrozen and the file %s is removed",
817 s->state_filepath_isfrozen);
818 s->frozen = true;
Michael Roth48ff7a62011-07-20 15:19:37 -0500819 }
Michael Rothd8ca6852012-01-19 22:04:34 -0600820#endif
Michael Roth48ff7a62011-07-20 15:19:37 -0500821
Michael Rothf789aa72012-04-18 16:28:01 -0500822 if (ga_is_frozen(s)) {
823 if (daemonize) {
824 /* delay opening/locking of pidfile till filesystem are unfrozen */
825 s->deferred_options.pid_filepath = pid_filepath;
826 become_daemon(NULL);
827 }
828 if (log_filepath) {
829 /* delay opening the log file till filesystems are unfrozen */
830 s->deferred_options.log_filepath = log_filepath;
831 }
832 ga_disable_logging(s);
833 ga_disable_non_whitelisted();
834 } else {
835 if (daemonize) {
836 become_daemon(pid_filepath);
837 }
838 if (log_filepath) {
839 s->log_file = fopen(log_filepath, "a");
840 if (!s->log_file) {
841 g_critical("unable to open specified log file: %s",
842 strerror(errno));
843 goto out_bad;
844 }
845 }
846 }
847
Michael Rothf22d85e2012-04-17 19:01:45 -0500848 if (blacklist) {
849 s->blacklist = blacklist;
850 do {
851 g_debug("disabling command: %s", (char *)blacklist->data);
852 qmp_disable_command(blacklist->data);
853 blacklist = g_list_next(blacklist);
854 } while (blacklist);
855 }
Michael Rothe3d4d252011-07-19 15:41:55 -0500856 s->command_state = ga_command_state_new();
857 ga_command_state_init(s, s->command_state);
858 ga_command_state_init_all(s->command_state);
Michael Roth125b3102012-01-19 00:18:20 -0600859 json_message_parser_init(&s->parser, process_event);
Michael Roth48ff7a62011-07-20 15:19:37 -0500860 ga_state = s;
Michael Rothd8ca6852012-01-19 22:04:34 -0600861#ifndef _WIN32
Michael Roth125b3102012-01-19 00:18:20 -0600862 if (!register_signal_handlers()) {
863 g_critical("failed to register signal handlers");
864 goto out_bad;
865 }
Michael Rothd8ca6852012-01-19 22:04:34 -0600866#endif
Michael Roth48ff7a62011-07-20 15:19:37 -0500867
Michael Roth125b3102012-01-19 00:18:20 -0600868 s->main_loop = g_main_loop_new(NULL, false);
869 if (!channel_init(ga_state, method, path)) {
870 g_critical("failed to initialize guest agent channel");
871 goto out_bad;
872 }
Michael Rothbc62fa02012-01-21 16:42:27 -0600873#ifndef _WIN32
Michael Roth48ff7a62011-07-20 15:19:37 -0500874 g_main_loop_run(ga_state->main_loop);
Michael Rothbc62fa02012-01-21 16:42:27 -0600875#else
876 if (daemonize) {
877 SERVICE_TABLE_ENTRY service_table[] = {
878 { (char *)QGA_SERVICE_NAME, service_main }, { NULL, NULL } };
879 StartServiceCtrlDispatcher(service_table);
880 } else {
881 g_main_loop_run(ga_state->main_loop);
882 }
883#endif
Michael Roth48ff7a62011-07-20 15:19:37 -0500884
Michael Rothe3d4d252011-07-19 15:41:55 -0500885 ga_command_state_cleanup_all(ga_state->command_state);
Michael Roth125b3102012-01-19 00:18:20 -0600886 ga_channel_free(ga_state->channel);
Michael Roth48ff7a62011-07-20 15:19:37 -0500887
Michael Roth125b3102012-01-19 00:18:20 -0600888 if (daemonize) {
Michael Rothf789aa72012-04-18 16:28:01 -0500889 unlink(pid_filepath);
Michael Roth125b3102012-01-19 00:18:20 -0600890 }
Michael Roth48ff7a62011-07-20 15:19:37 -0500891 return 0;
Michael Roth125b3102012-01-19 00:18:20 -0600892
893out_bad:
894 if (daemonize) {
Michael Rothf789aa72012-04-18 16:28:01 -0500895 unlink(pid_filepath);
Michael Roth125b3102012-01-19 00:18:20 -0600896 }
897 return EXIT_FAILURE;
Michael Roth48ff7a62011-07-20 15:19:37 -0500898}