blob: 8d53e04a0fcb1c0683e98110784f8043cd5f8165 [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}
Luiz Capitulino04b4e752012-05-10 16:50:41 -0300143
144/* TODO: use this in place of all post-fork() fclose(std*) callers */
145void reopen_fd_to_null(int fd)
146{
147 int nullfd;
148
149 nullfd = open("/dev/null", O_RDWR);
150 if (nullfd < 0) {
151 return;
152 }
153
154 dup2(nullfd, fd);
155
156 if (nullfd != fd) {
157 close(nullfd);
158 }
159}
Michael Rothd8ca6852012-01-19 22:04:34 -0600160#endif
Michael Roth48ff7a62011-07-20 15:19:37 -0500161
162static void usage(const char *cmd)
163{
164 printf(
Michael Roth4bdd0412012-04-17 11:28:27 -0500165"Usage: %s [-m <method> -p <path>] [<options>]\n"
Michael Roth48ff7a62011-07-20 15:19:37 -0500166"QEMU Guest Agent %s\n"
167"\n"
168" -m, --method transport method: one of unix-listen, virtio-serial, or\n"
169" isa-serial (virtio-serial is the default)\n"
Michael Roth4bdd0412012-04-17 11:28:27 -0500170" -p, --path device/socket path (the default for virtio-serial is:\n"
171" %s)\n"
Michael Roth48ff7a62011-07-20 15:19:37 -0500172" -l, --logfile set logfile path, logs to stderr by default\n"
173" -f, --pidfile specify pidfile (default is %s)\n"
Michael Rothf789aa72012-04-18 16:28:01 -0500174" -t, --statedir specify dir to store state information (absolute paths\n"
175" only, default is %s)\n"
Michael Roth48ff7a62011-07-20 15:19:37 -0500176" -v, --verbose log extra debugging information\n"
177" -V, --version print version information and exit\n"
178" -d, --daemonize become a daemon\n"
Michael Rothbc62fa02012-01-21 16:42:27 -0600179#ifdef _WIN32
180" -s, --service service commands: install, uninstall\n"
Michael Rothd8ca6852012-01-19 22:04:34 -0600181#endif
Michael Roth4bdd0412012-04-17 11:28:27 -0500182" -b, --blacklist comma-separated list of RPCs to disable (no spaces, \"?\"\n"
Michael Rothabd6cf62011-12-06 22:03:42 -0600183" to list available RPCs)\n"
Michael Roth48ff7a62011-07-20 15:19:37 -0500184" -h, --help display this help and exit\n"
185"\n"
186"Report bugs to <mdroth@linux.vnet.ibm.com>\n"
Michael Rothf789aa72012-04-18 16:28:01 -0500187 , cmd, QGA_VERSION, QGA_VIRTIO_PATH_DEFAULT, QGA_PIDFILE_DEFAULT,
188 QGA_STATEDIR_DEFAULT);
Michael Roth48ff7a62011-07-20 15:19:37 -0500189}
190
Michael Roth48ff7a62011-07-20 15:19:37 -0500191static const char *ga_log_level_str(GLogLevelFlags level)
192{
193 switch (level & G_LOG_LEVEL_MASK) {
194 case G_LOG_LEVEL_ERROR:
195 return "error";
196 case G_LOG_LEVEL_CRITICAL:
197 return "critical";
198 case G_LOG_LEVEL_WARNING:
199 return "warning";
200 case G_LOG_LEVEL_MESSAGE:
201 return "message";
202 case G_LOG_LEVEL_INFO:
203 return "info";
204 case G_LOG_LEVEL_DEBUG:
205 return "debug";
206 default:
207 return "user";
208 }
209}
210
211bool ga_logging_enabled(GAState *s)
212{
213 return s->logging_enabled;
214}
215
216void ga_disable_logging(GAState *s)
217{
218 s->logging_enabled = false;
219}
220
221void ga_enable_logging(GAState *s)
222{
223 s->logging_enabled = true;
224}
225
226static void ga_log(const gchar *domain, GLogLevelFlags level,
227 const gchar *msg, gpointer opaque)
228{
229 GAState *s = opaque;
230 GTimeVal time;
231 const char *level_str = ga_log_level_str(level);
232
233 if (!ga_logging_enabled(s)) {
234 return;
235 }
236
237 level &= G_LOG_LEVEL_MASK;
Michael Rothd8ca6852012-01-19 22:04:34 -0600238#ifndef _WIN32
Michael Roth8f477472011-08-11 15:38:11 -0500239 if (domain && strcmp(domain, "syslog") == 0) {
Michael Roth48ff7a62011-07-20 15:19:37 -0500240 syslog(LOG_INFO, "%s: %s", level_str, msg);
241 } else if (level & s->log_level) {
Michael Rothd8ca6852012-01-19 22:04:34 -0600242#else
243 if (level & s->log_level) {
244#endif
Michael Roth48ff7a62011-07-20 15:19:37 -0500245 g_get_current_time(&time);
246 fprintf(s->log_file,
247 "%lu.%lu: %s: %s\n", time.tv_sec, time.tv_usec, level_str, msg);
248 fflush(s->log_file);
249 }
250}
251
Michael Roth3cf0bed2012-02-07 13:56:48 -0600252void ga_set_response_delimited(GAState *s)
253{
254 s->delimit_response = true;
255}
256
Michael Rothf789aa72012-04-18 16:28:01 -0500257#ifndef _WIN32
258static bool ga_open_pidfile(const char *pidfile)
259{
260 int pidfd;
261 char pidstr[32];
262
263 pidfd = open(pidfile, O_CREAT|O_WRONLY, S_IRUSR|S_IWUSR);
264 if (pidfd == -1 || lockf(pidfd, F_TLOCK, 0)) {
265 g_critical("Cannot lock pid file, %s", strerror(errno));
266 return false;
267 }
268
269 if (ftruncate(pidfd, 0) || lseek(pidfd, 0, SEEK_SET)) {
270 g_critical("Failed to truncate pid file");
271 goto fail;
272 }
273 sprintf(pidstr, "%d", getpid());
274 if (write(pidfd, pidstr, strlen(pidstr)) != strlen(pidstr)) {
275 g_critical("Failed to write pid file");
276 goto fail;
277 }
278
279 return true;
280
281fail:
282 unlink(pidfile);
283 return false;
284}
285#else /* _WIN32 */
286static bool ga_open_pidfile(const char *pidfile)
287{
288 return true;
289}
290#endif
291
Michael Rothf22d85e2012-04-17 19:01:45 -0500292static gint ga_strcmp(gconstpointer str1, gconstpointer str2)
293{
294 return strcmp(str1, str2);
295}
296
297/* disable commands that aren't safe for fsfreeze */
298static void ga_disable_non_whitelisted(void)
299{
300 char **list_head, **list;
301 bool whitelisted;
302 int i;
303
304 list_head = list = qmp_get_command_list();
305 while (*list != NULL) {
306 whitelisted = false;
307 i = 0;
308 while (ga_freeze_whitelist[i] != NULL) {
309 if (strcmp(*list, ga_freeze_whitelist[i]) == 0) {
310 whitelisted = true;
311 }
312 i++;
313 }
314 if (!whitelisted) {
315 g_debug("disabling command: %s", *list);
316 qmp_disable_command(*list);
317 }
318 g_free(*list);
319 list++;
320 }
321 g_free(list_head);
322}
323
Jim Meyeringa31f0532012-05-09 05:12:04 +0000324/* [re-]enable all commands, except those explicitly blacklisted by user */
Michael Rothf22d85e2012-04-17 19:01:45 -0500325static void ga_enable_non_blacklisted(GList *blacklist)
326{
327 char **list_head, **list;
328
329 list_head = list = qmp_get_command_list();
330 while (*list != NULL) {
331 if (g_list_find_custom(blacklist, *list, ga_strcmp) == NULL &&
332 !qmp_command_is_enabled(*list)) {
333 g_debug("enabling command: %s", *list);
334 qmp_enable_command(*list);
335 }
336 g_free(*list);
337 list++;
338 }
339 g_free(list_head);
340}
341
Michael Rothf789aa72012-04-18 16:28:01 -0500342static bool ga_create_file(const char *path)
343{
344 int fd = open(path, O_CREAT | O_WRONLY, S_IWUSR | S_IRUSR);
345 if (fd == -1) {
346 g_warning("unable to open/create file %s: %s", path, strerror(errno));
347 return false;
348 }
349 close(fd);
350 return true;
351}
352
353static bool ga_delete_file(const char *path)
354{
355 int ret = unlink(path);
356 if (ret == -1) {
357 g_warning("unable to delete file: %s: %s", path, strerror(errno));
358 return false;
359 }
360
361 return true;
362}
363
Michael Rothf22d85e2012-04-17 19:01:45 -0500364bool ga_is_frozen(GAState *s)
365{
366 return s->frozen;
367}
368
369void ga_set_frozen(GAState *s)
370{
371 if (ga_is_frozen(s)) {
372 return;
373 }
374 /* disable all non-whitelisted (for frozen state) commands */
375 ga_disable_non_whitelisted();
376 g_warning("disabling logging due to filesystem freeze");
377 ga_disable_logging(s);
378 s->frozen = true;
Michael Rothf789aa72012-04-18 16:28:01 -0500379 if (!ga_create_file(s->state_filepath_isfrozen)) {
380 g_warning("unable to create %s, fsfreeze may not function properly",
381 s->state_filepath_isfrozen);
382 }
Michael Rothf22d85e2012-04-17 19:01:45 -0500383}
384
385void ga_unset_frozen(GAState *s)
386{
387 if (!ga_is_frozen(s)) {
388 return;
389 }
390
Michael Rothf789aa72012-04-18 16:28:01 -0500391 /* if we delayed creation/opening of pid/log files due to being
392 * in a frozen state at start up, do it now
393 */
394 if (s->deferred_options.log_filepath) {
395 s->log_file = fopen(s->deferred_options.log_filepath, "a");
396 if (!s->log_file) {
397 s->log_file = stderr;
398 }
399 s->deferred_options.log_filepath = NULL;
400 }
Michael Rothf22d85e2012-04-17 19:01:45 -0500401 ga_enable_logging(s);
Michael Rothf789aa72012-04-18 16:28:01 -0500402 g_warning("logging re-enabled due to filesystem unfreeze");
403 if (s->deferred_options.pid_filepath) {
404 if (!ga_open_pidfile(s->deferred_options.pid_filepath)) {
405 g_warning("failed to create/open pid file");
406 }
407 s->deferred_options.pid_filepath = NULL;
408 }
Michael Rothf22d85e2012-04-17 19:01:45 -0500409
410 /* enable all disabled, non-blacklisted commands */
411 ga_enable_non_blacklisted(s->blacklist);
412 s->frozen = false;
Michael Rothf789aa72012-04-18 16:28:01 -0500413 if (!ga_delete_file(s->state_filepath_isfrozen)) {
414 g_warning("unable to delete %s, fsfreeze may not function properly",
415 s->state_filepath_isfrozen);
416 }
Michael Rothf22d85e2012-04-17 19:01:45 -0500417}
418
Michael Roth48ff7a62011-07-20 15:19:37 -0500419static void become_daemon(const char *pidfile)
420{
Michael Rothf789aa72012-04-18 16:28:01 -0500421#ifndef _WIN32
Michael Roth48ff7a62011-07-20 15:19:37 -0500422 pid_t pid, sid;
Michael Roth48ff7a62011-07-20 15:19:37 -0500423
424 pid = fork();
425 if (pid < 0) {
426 exit(EXIT_FAILURE);
427 }
428 if (pid > 0) {
429 exit(EXIT_SUCCESS);
430 }
431
Michael Rothf789aa72012-04-18 16:28:01 -0500432 if (pidfile) {
433 if (!ga_open_pidfile(pidfile)) {
434 g_critical("failed to create pidfile");
435 exit(EXIT_FAILURE);
436 }
Michael Roth48ff7a62011-07-20 15:19:37 -0500437 }
438
439 umask(0);
440 sid = setsid();
441 if (sid < 0) {
442 goto fail;
443 }
444 if ((chdir("/")) < 0) {
445 goto fail;
446 }
447
448 close(STDIN_FILENO);
449 close(STDOUT_FILENO);
450 close(STDERR_FILENO);
Michael Roth48ff7a62011-07-20 15:19:37 -0500451 return;
452
453fail:
454 unlink(pidfile);
455 g_critical("failed to daemonize");
456 exit(EXIT_FAILURE);
Michael Rothd8ca6852012-01-19 22:04:34 -0600457#endif
Michael Rothf789aa72012-04-18 16:28:01 -0500458}
Michael Roth48ff7a62011-07-20 15:19:37 -0500459
Michael Roth125b3102012-01-19 00:18:20 -0600460static int send_response(GAState *s, QObject *payload)
Michael Roth48ff7a62011-07-20 15:19:37 -0500461{
Michael Roth48ff7a62011-07-20 15:19:37 -0500462 const char *buf;
Michael Roth3cf0bed2012-02-07 13:56:48 -0600463 QString *payload_qstr, *response_qstr;
Michael Roth125b3102012-01-19 00:18:20 -0600464 GIOStatus status;
Michael Roth48ff7a62011-07-20 15:19:37 -0500465
Michael Roth125b3102012-01-19 00:18:20 -0600466 g_assert(payload && s->channel);
Michael Roth48ff7a62011-07-20 15:19:37 -0500467
468 payload_qstr = qobject_to_json(payload);
469 if (!payload_qstr) {
470 return -EINVAL;
471 }
472
Michael Roth3cf0bed2012-02-07 13:56:48 -0600473 if (s->delimit_response) {
474 s->delimit_response = false;
475 response_qstr = qstring_new();
476 qstring_append_chr(response_qstr, QGA_SENTINEL_BYTE);
477 qstring_append(response_qstr, qstring_get_str(payload_qstr));
478 QDECREF(payload_qstr);
479 } else {
480 response_qstr = payload_qstr;
481 }
482
483 qstring_append_chr(response_qstr, '\n');
484 buf = qstring_get_str(response_qstr);
Michael Roth125b3102012-01-19 00:18:20 -0600485 status = ga_channel_write_all(s->channel, buf, strlen(buf));
Michael Roth3cf0bed2012-02-07 13:56:48 -0600486 QDECREF(response_qstr);
Michael Roth125b3102012-01-19 00:18:20 -0600487 if (status != G_IO_STATUS_NORMAL) {
488 return -EIO;
Michael Roth48ff7a62011-07-20 15:19:37 -0500489 }
Michael Roth125b3102012-01-19 00:18:20 -0600490
491 return 0;
Michael Roth48ff7a62011-07-20 15:19:37 -0500492}
493
494static void process_command(GAState *s, QDict *req)
495{
496 QObject *rsp = NULL;
497 int ret;
498
499 g_assert(req);
500 g_debug("processing command");
501 rsp = qmp_dispatch(QOBJECT(req));
502 if (rsp) {
Michael Roth125b3102012-01-19 00:18:20 -0600503 ret = send_response(s, rsp);
Michael Roth48ff7a62011-07-20 15:19:37 -0500504 if (ret) {
Michael Roth125b3102012-01-19 00:18:20 -0600505 g_warning("error sending response: %s", strerror(ret));
Michael Roth48ff7a62011-07-20 15:19:37 -0500506 }
507 qobject_decref(rsp);
Michael Roth48ff7a62011-07-20 15:19:37 -0500508 }
509}
510
511/* handle requests/control events coming in over the channel */
512static void process_event(JSONMessageParser *parser, QList *tokens)
513{
514 GAState *s = container_of(parser, GAState, parser);
515 QObject *obj;
516 QDict *qdict;
517 Error *err = NULL;
518 int ret;
519
520 g_assert(s && parser);
521
522 g_debug("process_event: called");
523 obj = json_parser_parse_err(tokens, NULL, &err);
524 if (err || !obj || qobject_type(obj) != QTYPE_QDICT) {
525 qobject_decref(obj);
526 qdict = qdict_new();
527 if (!err) {
528 g_warning("failed to parse event: unknown error");
529 error_set(&err, QERR_JSON_PARSING);
530 } else {
531 g_warning("failed to parse event: %s", error_get_pretty(err));
532 }
533 qdict_put_obj(qdict, "error", error_get_qobject(err));
534 error_free(err);
535 } else {
536 qdict = qobject_to_qdict(obj);
537 }
538
539 g_assert(qdict);
540
541 /* handle host->guest commands */
542 if (qdict_haskey(qdict, "execute")) {
543 process_command(s, qdict);
544 } else {
545 if (!qdict_haskey(qdict, "error")) {
546 QDECREF(qdict);
547 qdict = qdict_new();
548 g_warning("unrecognized payload format");
549 error_set(&err, QERR_UNSUPPORTED);
550 qdict_put_obj(qdict, "error", error_get_qobject(err));
551 error_free(err);
552 }
Michael Roth125b3102012-01-19 00:18:20 -0600553 ret = send_response(s, QOBJECT(qdict));
Michael Roth48ff7a62011-07-20 15:19:37 -0500554 if (ret) {
Michael Roth125b3102012-01-19 00:18:20 -0600555 g_warning("error sending error response: %s", strerror(ret));
Michael Roth48ff7a62011-07-20 15:19:37 -0500556 }
557 }
558
559 QDECREF(qdict);
560}
561
Michael Roth125b3102012-01-19 00:18:20 -0600562/* false return signals GAChannel to close the current client connection */
563static gboolean channel_event_cb(GIOCondition condition, gpointer data)
Michael Roth48ff7a62011-07-20 15:19:37 -0500564{
565 GAState *s = data;
Michael Roth125b3102012-01-19 00:18:20 -0600566 gchar buf[QGA_READ_COUNT_DEFAULT+1];
Michael Roth48ff7a62011-07-20 15:19:37 -0500567 gsize count;
568 GError *err = NULL;
Michael Roth125b3102012-01-19 00:18:20 -0600569 GIOStatus status = ga_channel_read(s->channel, buf, QGA_READ_COUNT_DEFAULT, &count);
Michael Roth48ff7a62011-07-20 15:19:37 -0500570 if (err != NULL) {
571 g_warning("error reading channel: %s", err->message);
Michael Roth48ff7a62011-07-20 15:19:37 -0500572 g_error_free(err);
573 return false;
574 }
575 switch (status) {
576 case G_IO_STATUS_ERROR:
Michael Roth125b3102012-01-19 00:18:20 -0600577 g_warning("error reading channel");
Michael Roth48ff7a62011-07-20 15:19:37 -0500578 return false;
579 case G_IO_STATUS_NORMAL:
Michael Roth125b3102012-01-19 00:18:20 -0600580 buf[count] = 0;
Michael Roth48ff7a62011-07-20 15:19:37 -0500581 g_debug("read data, count: %d, data: %s", (int)count, buf);
582 json_message_parser_feed(&s->parser, (char *)buf, (int)count);
Michael Roth125b3102012-01-19 00:18:20 -0600583 break;
584 case G_IO_STATUS_EOF:
585 g_debug("received EOF");
586 if (!s->virtio) {
587 return false;
588 }
Michael Roth48ff7a62011-07-20 15:19:37 -0500589 case G_IO_STATUS_AGAIN:
590 /* virtio causes us to spin here when no process is attached to
591 * host-side chardev. sleep a bit to mitigate this
592 */
593 if (s->virtio) {
594 usleep(100*1000);
595 }
596 return true;
Michael Roth48ff7a62011-07-20 15:19:37 -0500597 default:
598 g_warning("unknown channel read status, closing");
Michael Roth48ff7a62011-07-20 15:19:37 -0500599 return false;
600 }
601 return true;
602}
603
Michael Roth125b3102012-01-19 00:18:20 -0600604static gboolean channel_init(GAState *s, const gchar *method, const gchar *path)
Michael Roth48ff7a62011-07-20 15:19:37 -0500605{
Michael Roth125b3102012-01-19 00:18:20 -0600606 GAChannelMethod channel_method;
Michael Roth48ff7a62011-07-20 15:19:37 -0500607
Michael Roth125b3102012-01-19 00:18:20 -0600608 if (method == NULL) {
609 method = "virtio-serial";
Michael Roth48ff7a62011-07-20 15:19:37 -0500610 }
611
Michael Roth125b3102012-01-19 00:18:20 -0600612 if (path == NULL) {
613 if (strcmp(method, "virtio-serial") != 0) {
Michael Roth48ff7a62011-07-20 15:19:37 -0500614 g_critical("must specify a path for this channel");
Michael Roth125b3102012-01-19 00:18:20 -0600615 return false;
Michael Roth48ff7a62011-07-20 15:19:37 -0500616 }
617 /* try the default path for the virtio-serial port */
Michael Roth125b3102012-01-19 00:18:20 -0600618 path = QGA_VIRTIO_PATH_DEFAULT;
Michael Roth48ff7a62011-07-20 15:19:37 -0500619 }
620
Michael Roth125b3102012-01-19 00:18:20 -0600621 if (strcmp(method, "virtio-serial") == 0) {
622 s->virtio = true; /* virtio requires special handling in some cases */
623 channel_method = GA_CHANNEL_VIRTIO_SERIAL;
624 } else if (strcmp(method, "isa-serial") == 0) {
625 channel_method = GA_CHANNEL_ISA_SERIAL;
626 } else if (strcmp(method, "unix-listen") == 0) {
627 channel_method = GA_CHANNEL_UNIX_LISTEN;
Michael Roth48ff7a62011-07-20 15:19:37 -0500628 } else {
Michael Roth125b3102012-01-19 00:18:20 -0600629 g_critical("unsupported channel method/type: %s", method);
630 return false;
Michael Roth48ff7a62011-07-20 15:19:37 -0500631 }
632
Michael Roth125b3102012-01-19 00:18:20 -0600633 s->channel = ga_channel_new(channel_method, path, channel_event_cb, s);
634 if (!s->channel) {
635 g_critical("failed to create guest agent channel");
636 return false;
637 }
638
639 return true;
Michael Roth48ff7a62011-07-20 15:19:37 -0500640}
641
Michael Rothbc62fa02012-01-21 16:42:27 -0600642#ifdef _WIN32
643DWORD WINAPI service_ctrl_handler(DWORD ctrl, DWORD type, LPVOID data,
644 LPVOID ctx)
645{
646 DWORD ret = NO_ERROR;
647 GAService *service = &ga_state->service;
648
649 switch (ctrl)
650 {
651 case SERVICE_CONTROL_STOP:
652 case SERVICE_CONTROL_SHUTDOWN:
653 quit_handler(SIGTERM);
654 service->status.dwCurrentState = SERVICE_STOP_PENDING;
655 SetServiceStatus(service->status_handle, &service->status);
656 break;
657
658 default:
659 ret = ERROR_CALL_NOT_IMPLEMENTED;
660 }
661 return ret;
662}
663
664VOID WINAPI service_main(DWORD argc, TCHAR *argv[])
665{
666 GAService *service = &ga_state->service;
667
668 service->status_handle = RegisterServiceCtrlHandlerEx(QGA_SERVICE_NAME,
669 service_ctrl_handler, NULL);
670
671 if (service->status_handle == 0) {
672 g_critical("Failed to register extended requests function!\n");
673 return;
674 }
675
676 service->status.dwServiceType = SERVICE_WIN32;
677 service->status.dwCurrentState = SERVICE_RUNNING;
678 service->status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
679 service->status.dwWin32ExitCode = NO_ERROR;
680 service->status.dwServiceSpecificExitCode = NO_ERROR;
681 service->status.dwCheckPoint = 0;
682 service->status.dwWaitHint = 0;
683 SetServiceStatus(service->status_handle, &service->status);
684
685 g_main_loop_run(ga_state->main_loop);
686
687 service->status.dwCurrentState = SERVICE_STOPPED;
688 SetServiceStatus(service->status_handle, &service->status);
689}
690#endif
691
Michael Roth48ff7a62011-07-20 15:19:37 -0500692int main(int argc, char **argv)
693{
Michael Rothf789aa72012-04-18 16:28:01 -0500694 const char *sopt = "hVvdm:p:l:f:b:s:t:";
695 const char *method = NULL, *path = NULL;
696 const char *log_filepath = NULL;
697 const char *pid_filepath = QGA_PIDFILE_DEFAULT;
698 const char *state_dir = QGA_STATEDIR_DEFAULT;
Michael Rothbc62fa02012-01-21 16:42:27 -0600699#ifdef _WIN32
700 const char *service = NULL;
701#endif
Michael Roth48ff7a62011-07-20 15:19:37 -0500702 const struct option lopt[] = {
703 { "help", 0, NULL, 'h' },
704 { "version", 0, NULL, 'V' },
Michael Rothbc62fa02012-01-21 16:42:27 -0600705 { "logfile", 1, NULL, 'l' },
706 { "pidfile", 1, NULL, 'f' },
Michael Roth48ff7a62011-07-20 15:19:37 -0500707 { "verbose", 0, NULL, 'v' },
Michael Rothbc62fa02012-01-21 16:42:27 -0600708 { "method", 1, NULL, 'm' },
709 { "path", 1, NULL, 'p' },
Michael Roth48ff7a62011-07-20 15:19:37 -0500710 { "daemonize", 0, NULL, 'd' },
Michael Rothbc62fa02012-01-21 16:42:27 -0600711 { "blacklist", 1, NULL, 'b' },
712#ifdef _WIN32
713 { "service", 1, NULL, 's' },
Michael Rothf22d85e2012-04-17 19:01:45 -0500714#endif
Michael Rothf789aa72012-04-18 16:28:01 -0500715 { "statedir", 1, NULL, 't' },
Michael Roth48ff7a62011-07-20 15:19:37 -0500716 { NULL, 0, NULL, 0 }
717 };
Michael Rothabd6cf62011-12-06 22:03:42 -0600718 int opt_ind = 0, ch, daemonize = 0, i, j, len;
Michael Roth48ff7a62011-07-20 15:19:37 -0500719 GLogLevelFlags log_level = G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL;
Michael Rothf22d85e2012-04-17 19:01:45 -0500720 GList *blacklist = NULL;
Michael Roth48ff7a62011-07-20 15:19:37 -0500721 GAState *s;
722
Michael Rothabd6cf62011-12-06 22:03:42 -0600723 module_call_init(MODULE_INIT_QAPI);
724
Michael Roth48ff7a62011-07-20 15:19:37 -0500725 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
726 switch (ch) {
727 case 'm':
728 method = optarg;
729 break;
730 case 'p':
731 path = optarg;
732 break;
733 case 'l':
Michael Rothf789aa72012-04-18 16:28:01 -0500734 log_filepath = optarg;
Michael Roth48ff7a62011-07-20 15:19:37 -0500735 break;
736 case 'f':
Michael Rothf789aa72012-04-18 16:28:01 -0500737 pid_filepath = optarg;
Michael Roth48ff7a62011-07-20 15:19:37 -0500738 break;
Michael Rothf789aa72012-04-18 16:28:01 -0500739 case 't':
740 state_dir = optarg;
741 break;
Michael Roth48ff7a62011-07-20 15:19:37 -0500742 case 'v':
743 /* enable all log levels */
744 log_level = G_LOG_LEVEL_MASK;
745 break;
746 case 'V':
747 printf("QEMU Guest Agent %s\n", QGA_VERSION);
748 return 0;
749 case 'd':
750 daemonize = 1;
751 break;
Michael Rothabd6cf62011-12-06 22:03:42 -0600752 case 'b': {
753 char **list_head, **list;
754 if (*optarg == '?') {
755 list_head = list = qmp_get_command_list();
756 while (*list != NULL) {
757 printf("%s\n", *list);
758 g_free(*list);
759 list++;
760 }
761 g_free(list_head);
762 return 0;
763 }
764 for (j = 0, i = 0, len = strlen(optarg); i < len; i++) {
765 if (optarg[i] == ',') {
766 optarg[i] = 0;
Michael Rothf22d85e2012-04-17 19:01:45 -0500767 blacklist = g_list_append(blacklist, &optarg[j]);
Michael Rothabd6cf62011-12-06 22:03:42 -0600768 j = i + 1;
769 }
770 }
771 if (j < i) {
Michael Rothf22d85e2012-04-17 19:01:45 -0500772 blacklist = g_list_append(blacklist, &optarg[j]);
Michael Rothabd6cf62011-12-06 22:03:42 -0600773 }
774 break;
775 }
Michael Rothbc62fa02012-01-21 16:42:27 -0600776#ifdef _WIN32
777 case 's':
778 service = optarg;
779 if (strcmp(service, "install") == 0) {
Michael Rothf789aa72012-04-18 16:28:01 -0500780 return ga_install_service(path, log_filepath);
Michael Rothbc62fa02012-01-21 16:42:27 -0600781 } else if (strcmp(service, "uninstall") == 0) {
782 return ga_uninstall_service();
783 } else {
784 printf("Unknown service command.\n");
785 return EXIT_FAILURE;
786 }
787 break;
788#endif
Michael Roth48ff7a62011-07-20 15:19:37 -0500789 case 'h':
790 usage(argv[0]);
791 return 0;
792 case '?':
793 g_print("Unknown option, try '%s --help' for more information.\n",
794 argv[0]);
795 return EXIT_FAILURE;
796 }
797 }
798
Michael Rothf789aa72012-04-18 16:28:01 -0500799 s = g_malloc0(sizeof(GAState));
800 s->log_level = log_level;
801 s->log_file = stderr;
802 g_log_set_default_handler(ga_log, s);
803 g_log_set_fatal_mask(NULL, G_LOG_LEVEL_ERROR);
804 ga_enable_logging(s);
805 s->state_filepath_isfrozen = g_strdup_printf("%s/qga.state.isfrozen",
806 state_dir);
807 s->frozen = false;
Michael Rothd8ca6852012-01-19 22:04:34 -0600808#ifndef _WIN32
Michael Rothf789aa72012-04-18 16:28:01 -0500809 /* check if a previous instance of qemu-ga exited with filesystems' state
810 * marked as frozen. this could be a stale value (a non-qemu-ga process
811 * or reboot may have since unfrozen them), but better to require an
812 * uneeded unfreeze than to risk hanging on start-up
813 */
814 struct stat st;
815 if (stat(s->state_filepath_isfrozen, &st) == -1) {
816 /* it's okay if the file doesn't exist, but if we can't access for
817 * some other reason, such as permissions, there's a configuration
818 * that needs to be addressed. so just bail now before we get into
819 * more trouble later
820 */
821 if (errno != ENOENT) {
822 g_critical("unable to access state file at path %s: %s",
823 s->state_filepath_isfrozen, strerror(errno));
824 return EXIT_FAILURE;
825 }
826 } else {
827 g_warning("previous instance appears to have exited with frozen"
828 " filesystems. deferring logging/pidfile creation and"
829 " disabling non-fsfreeze-safe commands until"
830 " guest-fsfreeze-thaw is issued, or filesystems are"
831 " manually unfrozen and the file %s is removed",
832 s->state_filepath_isfrozen);
833 s->frozen = true;
Michael Roth48ff7a62011-07-20 15:19:37 -0500834 }
Michael Rothd8ca6852012-01-19 22:04:34 -0600835#endif
Michael Roth48ff7a62011-07-20 15:19:37 -0500836
Michael Rothf789aa72012-04-18 16:28:01 -0500837 if (ga_is_frozen(s)) {
838 if (daemonize) {
839 /* delay opening/locking of pidfile till filesystem are unfrozen */
840 s->deferred_options.pid_filepath = pid_filepath;
841 become_daemon(NULL);
842 }
843 if (log_filepath) {
844 /* delay opening the log file till filesystems are unfrozen */
845 s->deferred_options.log_filepath = log_filepath;
846 }
847 ga_disable_logging(s);
848 ga_disable_non_whitelisted();
849 } else {
850 if (daemonize) {
851 become_daemon(pid_filepath);
852 }
853 if (log_filepath) {
854 s->log_file = fopen(log_filepath, "a");
855 if (!s->log_file) {
856 g_critical("unable to open specified log file: %s",
857 strerror(errno));
858 goto out_bad;
859 }
860 }
861 }
862
Michael Rothf22d85e2012-04-17 19:01:45 -0500863 if (blacklist) {
864 s->blacklist = blacklist;
865 do {
866 g_debug("disabling command: %s", (char *)blacklist->data);
867 qmp_disable_command(blacklist->data);
868 blacklist = g_list_next(blacklist);
869 } while (blacklist);
870 }
Michael Rothe3d4d252011-07-19 15:41:55 -0500871 s->command_state = ga_command_state_new();
872 ga_command_state_init(s, s->command_state);
873 ga_command_state_init_all(s->command_state);
Michael Roth125b3102012-01-19 00:18:20 -0600874 json_message_parser_init(&s->parser, process_event);
Michael Roth48ff7a62011-07-20 15:19:37 -0500875 ga_state = s;
Michael Rothd8ca6852012-01-19 22:04:34 -0600876#ifndef _WIN32
Michael Roth125b3102012-01-19 00:18:20 -0600877 if (!register_signal_handlers()) {
878 g_critical("failed to register signal handlers");
879 goto out_bad;
880 }
Michael Rothd8ca6852012-01-19 22:04:34 -0600881#endif
Michael Roth48ff7a62011-07-20 15:19:37 -0500882
Michael Roth125b3102012-01-19 00:18:20 -0600883 s->main_loop = g_main_loop_new(NULL, false);
884 if (!channel_init(ga_state, method, path)) {
885 g_critical("failed to initialize guest agent channel");
886 goto out_bad;
887 }
Michael Rothbc62fa02012-01-21 16:42:27 -0600888#ifndef _WIN32
Michael Roth48ff7a62011-07-20 15:19:37 -0500889 g_main_loop_run(ga_state->main_loop);
Michael Rothbc62fa02012-01-21 16:42:27 -0600890#else
891 if (daemonize) {
892 SERVICE_TABLE_ENTRY service_table[] = {
893 { (char *)QGA_SERVICE_NAME, service_main }, { NULL, NULL } };
894 StartServiceCtrlDispatcher(service_table);
895 } else {
896 g_main_loop_run(ga_state->main_loop);
897 }
898#endif
Michael Roth48ff7a62011-07-20 15:19:37 -0500899
Michael Rothe3d4d252011-07-19 15:41:55 -0500900 ga_command_state_cleanup_all(ga_state->command_state);
Michael Roth125b3102012-01-19 00:18:20 -0600901 ga_channel_free(ga_state->channel);
Michael Roth48ff7a62011-07-20 15:19:37 -0500902
Michael Roth125b3102012-01-19 00:18:20 -0600903 if (daemonize) {
Michael Rothf789aa72012-04-18 16:28:01 -0500904 unlink(pid_filepath);
Michael Roth125b3102012-01-19 00:18:20 -0600905 }
Michael Roth48ff7a62011-07-20 15:19:37 -0500906 return 0;
Michael Roth125b3102012-01-19 00:18:20 -0600907
908out_bad:
909 if (daemonize) {
Michael Rothf789aa72012-04-18 16:28:01 -0500910 unlink(pid_filepath);
Michael Roth125b3102012-01-19 00:18:20 -0600911 }
912 return EXIT_FAILURE;
Michael Roth48ff7a62011-07-20 15:19:37 -0500913}