main.c 40.1 KB
Newer Older
M
Michael Roth 已提交
1 2 3 4 5 6 7 8 9 10 11 12
/*
 * QEMU Guest Agent
 *
 * Copyright IBM Corp. 2011
 *
 * Authors:
 *  Adam Litke        <aglitke@linux.vnet.ibm.com>
 *  Michael Roth      <mdroth@linux.vnet.ibm.com>
 *
 * This work is licensed under the terms of the GNU GPL, version 2 or later.
 * See the COPYING file in the top-level directory.
 */
P
Peter Maydell 已提交
13
#include "qemu/osdep.h"
M
Michael Roth 已提交
14
#include <getopt.h>
15
#include <glib/gstdio.h>
16
#ifndef _WIN32
M
Michael Roth 已提交
17
#include <syslog.h>
18
#include <sys/wait.h>
19
#endif
20 21 22 23
#include "qapi/qmp/json-streamer.h"
#include "qapi/qmp/json-parser.h"
#include "qapi/qmp/qint.h"
#include "qapi/qmp/qjson.h"
M
Michael Roth 已提交
24
#include "qga/guest-agent-core.h"
25
#include "qemu/module.h"
26 27
#include "qapi/qmp/qerror.h"
#include "qapi/qmp/dispatch.h"
28
#include "qga/channel.h"
29
#include "qemu/bswap.h"
30
#include "qemu/help_option.h"
31 32
#ifdef _WIN32
#include "qga/service-win32.h"
33
#include "qga/vss-win32.h"
34
#endif
35 36 37 38 39 40
#ifdef __linux__
#include <linux/fs.h>
#ifdef FIFREEZE
#define CONFIG_FSFREEZE
#endif
#endif
M
Michael Roth 已提交
41

42
#ifndef _WIN32
M
Michael Roth 已提交
43
#define QGA_VIRTIO_PATH_DEFAULT "/dev/virtio-ports/org.qemu.guest_agent.0"
44
#define QGA_STATE_RELATIVE_DIR  "run"
45
#define QGA_SERIAL_PATH_DEFAULT "/dev/ttyS0"
46 47
#else
#define QGA_VIRTIO_PATH_DEFAULT "\\\\.\\Global\\org.qemu.guest_agent.0"
48
#define QGA_STATE_RELATIVE_DIR  "qemu-ga"
49
#define QGA_SERIAL_PATH_DEFAULT "COM1"
50
#endif
51 52 53
#ifdef CONFIG_FSFREEZE
#define QGA_FSFREEZE_HOOK_DEFAULT CONFIG_QEMU_CONFDIR "/fsfreeze-hook"
#endif
M
Michael Roth 已提交
54
#define QGA_SENTINEL_BYTE 0xFF
55
#define QGA_CONF_DEFAULT CONFIG_QEMU_CONFDIR G_DIR_SEPARATOR_S "qemu-ga.conf"
M
Michael Roth 已提交
56

57 58 59 60 61
static struct {
    const char *state_dir;
    const char *pidfile;
} dfl_pathnames;

62 63 64 65 66
typedef struct GAPersistentState {
#define QGA_PSTATE_DEFAULT_FD_COUNTER 1000
    int64_t fd_counter;
} GAPersistentState;

M
Michael Roth 已提交
67 68 69
struct GAState {
    JSONMessageParser parser;
    GMainLoop *main_loop;
70
    GAChannel *channel;
M
Michael Roth 已提交
71 72 73 74 75
    bool virtio; /* fastpath to check for virtio to deal with poll() quirks */
    GACommandState *command_state;
    GLogLevelFlags log_level;
    FILE *log_file;
    bool logging_enabled;
76 77 78
#ifdef _WIN32
    GAService service;
#endif
M
Michael Roth 已提交
79
    bool delimit_response;
80 81
    bool frozen;
    GList *blacklist;
M
Marc-André Lureau 已提交
82
    char *state_filepath_isfrozen;
83 84 85 86
    struct {
        const char *log_filepath;
        const char *pid_filepath;
    } deferred_options;
87 88 89
#ifdef CONFIG_FSFREEZE
    const char *fsfreeze_hook;
#endif
M
Marc-André Lureau 已提交
90
    gchar *pstate_filepath;
91
    GAPersistentState pstate;
M
Michael Roth 已提交
92 93
};

M
Michael Roth 已提交
94
struct GAState *ga_state;
M
Michael Roth 已提交
95

96 97 98 99 100
/* commands that are safe to issue while filesystems are frozen */
static const char *ga_freeze_whitelist[] = {
    "guest-ping",
    "guest-info",
    "guest-sync",
101
    "guest-sync-delimited",
102 103 104 105 106
    "guest-fsfreeze-status",
    "guest-fsfreeze-thaw",
    NULL
};

107 108 109 110 111 112
#ifdef _WIN32
DWORD WINAPI service_ctrl_handler(DWORD ctrl, DWORD type, LPVOID data,
                                  LPVOID ctx);
VOID WINAPI service_main(DWORD argc, TCHAR *argv[]);
#endif

113 114 115 116 117 118 119 120 121 122 123
static void
init_dfl_pathnames(void)
{
    g_assert(dfl_pathnames.state_dir == NULL);
    g_assert(dfl_pathnames.pidfile == NULL);
    dfl_pathnames.state_dir = qemu_get_local_state_pathname(
      QGA_STATE_RELATIVE_DIR);
    dfl_pathnames.pidfile   = qemu_get_local_state_pathname(
      QGA_STATE_RELATIVE_DIR G_DIR_SEPARATOR_S "qemu-ga.pid");
}

M
Michael Roth 已提交
124 125
static void quit_handler(int sig)
{
126 127 128 129 130 131 132 133 134
    /* if we're frozen, don't exit unless we're absolutely forced to,
     * because it's basically impossible for graceful exit to complete
     * unless all log/pid files are on unfreezable filesystems. there's
     * also a very likely chance killing the agent before unfreezing
     * the filesystems is a mistake (or will be viewed as one later).
     */
    if (ga_is_frozen(ga_state)) {
        return;
    }
135
    g_debug("received signal num %d, quitting", sig);
M
Michael Roth 已提交
136 137 138 139 140 141

    if (g_main_loop_is_running(ga_state->main_loop)) {
        g_main_loop_quit(ga_state->main_loop);
    }
}

142
#ifndef _WIN32
143
static gboolean register_signal_handlers(void)
M
Michael Roth 已提交
144
{
145
    struct sigaction sigact;
M
Michael Roth 已提交
146 147 148 149 150 151 152 153 154 155 156 157 158
    int ret;

    memset(&sigact, 0, sizeof(struct sigaction));
    sigact.sa_handler = quit_handler;

    ret = sigaction(SIGINT, &sigact, NULL);
    if (ret == -1) {
        g_error("error configuring signal handler: %s", strerror(errno));
    }
    ret = sigaction(SIGTERM, &sigact, NULL);
    if (ret == -1) {
        g_error("error configuring signal handler: %s", strerror(errno));
    }
159

160 161 162 163 164 165
    sigact.sa_handler = SIG_IGN;
    if (sigaction(SIGPIPE, &sigact, NULL) != 0) {
        g_error("error configuring SIGPIPE signal handler: %s",
                strerror(errno));
    }

166
    return true;
M
Michael Roth 已提交
167
}
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184

/* TODO: use this in place of all post-fork() fclose(std*) callers */
void reopen_fd_to_null(int fd)
{
    int nullfd;

    nullfd = open("/dev/null", O_RDWR);
    if (nullfd < 0) {
        return;
    }

    dup2(nullfd, fd);

    if (nullfd != fd) {
        close(nullfd);
    }
}
185
#endif
M
Michael Roth 已提交
186 187 188 189

static void usage(const char *cmd)
{
    printf(
M
Michael Roth 已提交
190
"Usage: %s [-m <method> -p <path>] [<options>]\n"
M
Michael Roth 已提交
191 192
"QEMU Guest Agent %s\n"
"\n"
S
Stefan Hajnoczi 已提交
193 194
"  -m, --method      transport method: one of unix-listen, virtio-serial,\n"
"                    isa-serial, or vsock-listen (virtio-serial is the default)\n"
M
Michael Roth 已提交
195
"  -p, --path        device/socket path (the default for virtio-serial is:\n"
196 197
"                    %s,\n"
"                    the default for isa-serial is:\n"
M
Michael Roth 已提交
198
"                    %s)\n"
M
Michael Roth 已提交
199 200
"  -l, --logfile     set logfile path, logs to stderr by default\n"
"  -f, --pidfile     specify pidfile (default is %s)\n"
201 202 203 204 205 206 207 208 209 210
#ifdef CONFIG_FSFREEZE
"  -F, --fsfreeze-hook\n"
"                    enable fsfreeze hook. Accepts an optional argument that\n"
"                    specifies script to run on freeze/thaw. Script will be\n"
"                    called with 'freeze'/'thaw' arguments accordingly.\n"
"                    (default is %s)\n"
"                    If using -F with an argument, do not follow -F with a\n"
"                    space.\n"
"                    (for example: -F/var/run/fsfreezehook.sh)\n"
#endif
211 212
"  -t, --statedir    specify dir to store state information (absolute paths\n"
"                    only, default is %s)\n"
M
Michael Roth 已提交
213 214 215
"  -v, --verbose     log extra debugging information\n"
"  -V, --version     print version information and exit\n"
"  -d, --daemonize   become a daemon\n"
216
#ifdef _WIN32
217
"  -s, --service     service commands: install, uninstall, vss-install, vss-uninstall\n"
218
#endif
M
Michael Roth 已提交
219
"  -b, --blacklist   comma-separated list of RPCs to disable (no spaces, \"?\"\n"
220
"                    to list available RPCs)\n"
M
Marc-André Lureau 已提交
221 222
"  -D, --dump-conf   dump a qemu-ga config file based on current config\n"
"                    options / command-line parameters to stdout\n"
M
Michael Roth 已提交
223 224 225
"  -h, --help        display this help and exit\n"
"\n"
"Report bugs to <mdroth@linux.vnet.ibm.com>\n"
226 227
    , cmd, QEMU_VERSION, QGA_VIRTIO_PATH_DEFAULT, QGA_SERIAL_PATH_DEFAULT,
    dfl_pathnames.pidfile,
228 229 230
#ifdef CONFIG_FSFREEZE
    QGA_FSFREEZE_HOOK_DEFAULT,
#endif
231
    dfl_pathnames.state_dir);
M
Michael Roth 已提交
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
}

static const char *ga_log_level_str(GLogLevelFlags level)
{
    switch (level & G_LOG_LEVEL_MASK) {
        case G_LOG_LEVEL_ERROR:
            return "error";
        case G_LOG_LEVEL_CRITICAL:
            return "critical";
        case G_LOG_LEVEL_WARNING:
            return "warning";
        case G_LOG_LEVEL_MESSAGE:
            return "message";
        case G_LOG_LEVEL_INFO:
            return "info";
        case G_LOG_LEVEL_DEBUG:
            return "debug";
        default:
            return "user";
    }
}

bool ga_logging_enabled(GAState *s)
{
    return s->logging_enabled;
}

void ga_disable_logging(GAState *s)
{
    s->logging_enabled = false;
}

void ga_enable_logging(GAState *s)
{
    s->logging_enabled = true;
}

static void ga_log(const gchar *domain, GLogLevelFlags level,
                   const gchar *msg, gpointer opaque)
{
    GAState *s = opaque;
    GTimeVal time;
    const char *level_str = ga_log_level_str(level);

    if (!ga_logging_enabled(s)) {
        return;
    }

    level &= G_LOG_LEVEL_MASK;
281
#ifndef _WIN32
282
    if (g_strcmp0(domain, "syslog") == 0) {
M
Michael Roth 已提交
283 284
        syslog(LOG_INFO, "%s: %s", level_str, msg);
    } else if (level & s->log_level) {
285 286 287
#else
    if (level & s->log_level) {
#endif
M
Michael Roth 已提交
288 289 290 291 292 293 294
        g_get_current_time(&time);
        fprintf(s->log_file,
                "%lu.%lu: %s: %s\n", time.tv_sec, time.tv_usec, level_str, msg);
        fflush(s->log_file);
    }
}

M
Michael Roth 已提交
295 296 297 298 299
void ga_set_response_delimited(GAState *s)
{
    s->delimit_response = true;
}

L
Luiz Capitulino 已提交
300 301 302 303 304 305 306 307 308 309 310 311 312
static FILE *ga_open_logfile(const char *logfile)
{
    FILE *f;

    f = fopen(logfile, "a");
    if (!f) {
        return NULL;
    }

    qemu_set_cloexec(fileno(f));
    return f;
}

313 314 315 316 317 318
#ifndef _WIN32
static bool ga_open_pidfile(const char *pidfile)
{
    int pidfd;
    char pidstr[32];

319
    pidfd = qemu_open(pidfile, O_CREAT|O_WRONLY, S_IRUSR|S_IWUSR);
320 321
    if (pidfd == -1 || lockf(pidfd, F_TLOCK, 0)) {
        g_critical("Cannot lock pid file, %s", strerror(errno));
322 323 324
        if (pidfd != -1) {
            close(pidfd);
        }
325 326 327
        return false;
    }

328
    if (ftruncate(pidfd, 0)) {
329 330 331
        g_critical("Failed to truncate pid file");
        goto fail;
    }
332
    snprintf(pidstr, sizeof(pidstr), "%d\n", getpid());
333 334 335 336 337
    if (write(pidfd, pidstr, strlen(pidstr)) != strlen(pidstr)) {
        g_critical("Failed to write pid file");
        goto fail;
    }

338
    /* keep pidfile open & locked forever */
339 340 341 342
    return true;

fail:
    unlink(pidfile);
343
    close(pidfd);
344 345 346 347 348 349 350 351 352
    return false;
}
#else /* _WIN32 */
static bool ga_open_pidfile(const char *pidfile)
{
    return true;
}
#endif

353 354 355 356 357 358
static gint ga_strcmp(gconstpointer str1, gconstpointer str2)
{
    return strcmp(str1, str2);
}

/* disable commands that aren't safe for fsfreeze */
359
static void ga_disable_non_whitelisted(QmpCommand *cmd, void *opaque)
360
{
361 362 363 364 365 366 367
    bool whitelisted = false;
    int i = 0;
    const char *name = qmp_command_name(cmd);

    while (ga_freeze_whitelist[i] != NULL) {
        if (strcmp(name, ga_freeze_whitelist[i]) == 0) {
            whitelisted = true;
368
        }
369 370 371 372 373
        i++;
    }
    if (!whitelisted) {
        g_debug("disabling command: %s", name);
        qmp_disable_command(name);
374 375 376
    }
}

J
Jim Meyering 已提交
377
/* [re-]enable all commands, except those explicitly blacklisted by user */
378
static void ga_enable_non_blacklisted(QmpCommand *cmd, void *opaque)
379
{
380 381 382 383 384 385 386
    GList *blacklist = opaque;
    const char *name = qmp_command_name(cmd);

    if (g_list_find_custom(blacklist, name, ga_strcmp) == NULL &&
        !qmp_command_is_enabled(cmd)) {
        g_debug("enabling command: %s", name);
        qmp_enable_command(name);
387 388 389
    }
}

390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
static bool ga_create_file(const char *path)
{
    int fd = open(path, O_CREAT | O_WRONLY, S_IWUSR | S_IRUSR);
    if (fd == -1) {
        g_warning("unable to open/create file %s: %s", path, strerror(errno));
        return false;
    }
    close(fd);
    return true;
}

static bool ga_delete_file(const char *path)
{
    int ret = unlink(path);
    if (ret == -1) {
        g_warning("unable to delete file: %s: %s", path, strerror(errno));
        return false;
    }

    return true;
}

412 413 414 415 416 417 418 419 420 421 422
bool ga_is_frozen(GAState *s)
{
    return s->frozen;
}

void ga_set_frozen(GAState *s)
{
    if (ga_is_frozen(s)) {
        return;
    }
    /* disable all non-whitelisted (for frozen state) commands */
423
    qmp_for_each_command(ga_disable_non_whitelisted, NULL);
424 425 426
    g_warning("disabling logging due to filesystem freeze");
    ga_disable_logging(s);
    s->frozen = true;
427 428 429 430
    if (!ga_create_file(s->state_filepath_isfrozen)) {
        g_warning("unable to create %s, fsfreeze may not function properly",
                  s->state_filepath_isfrozen);
    }
431 432 433 434 435 436 437 438
}

void ga_unset_frozen(GAState *s)
{
    if (!ga_is_frozen(s)) {
        return;
    }

439 440 441 442
    /* if we delayed creation/opening of pid/log files due to being
     * in a frozen state at start up, do it now
     */
    if (s->deferred_options.log_filepath) {
L
Luiz Capitulino 已提交
443
        s->log_file = ga_open_logfile(s->deferred_options.log_filepath);
444 445 446 447 448
        if (!s->log_file) {
            s->log_file = stderr;
        }
        s->deferred_options.log_filepath = NULL;
    }
449
    ga_enable_logging(s);
450 451 452 453 454 455 456
    g_warning("logging re-enabled due to filesystem unfreeze");
    if (s->deferred_options.pid_filepath) {
        if (!ga_open_pidfile(s->deferred_options.pid_filepath)) {
            g_warning("failed to create/open pid file");
        }
        s->deferred_options.pid_filepath = NULL;
    }
457 458

    /* enable all disabled, non-blacklisted commands */
459
    qmp_for_each_command(ga_enable_non_blacklisted, s->blacklist);
460
    s->frozen = false;
461 462 463 464
    if (!ga_delete_file(s->state_filepath_isfrozen)) {
        g_warning("unable to delete %s, fsfreeze may not function properly",
                  s->state_filepath_isfrozen);
    }
465 466
}

467 468 469 470 471 472 473
#ifdef CONFIG_FSFREEZE
const char *ga_fsfreeze_hook(GAState *s)
{
    return s->fsfreeze_hook;
}
#endif

M
Michael Roth 已提交
474 475
static void become_daemon(const char *pidfile)
{
476
#ifndef _WIN32
M
Michael Roth 已提交
477 478 479 480 481 482 483 484 485 486
    pid_t pid, sid;

    pid = fork();
    if (pid < 0) {
        exit(EXIT_FAILURE);
    }
    if (pid > 0) {
        exit(EXIT_SUCCESS);
    }

487 488 489 490 491
    if (pidfile) {
        if (!ga_open_pidfile(pidfile)) {
            g_critical("failed to create pidfile");
            exit(EXIT_FAILURE);
        }
M
Michael Roth 已提交
492 493
    }

494
    umask(S_IRWXG | S_IRWXO);
M
Michael Roth 已提交
495 496 497 498 499 500 501 502
    sid = setsid();
    if (sid < 0) {
        goto fail;
    }
    if ((chdir("/")) < 0) {
        goto fail;
    }

503 504 505
    reopen_fd_to_null(STDIN_FILENO);
    reopen_fd_to_null(STDOUT_FILENO);
    reopen_fd_to_null(STDERR_FILENO);
M
Michael Roth 已提交
506 507 508
    return;

fail:
509 510 511
    if (pidfile) {
        unlink(pidfile);
    }
M
Michael Roth 已提交
512 513
    g_critical("failed to daemonize");
    exit(EXIT_FAILURE);
514
#endif
515
}
M
Michael Roth 已提交
516

517
static int send_response(GAState *s, QObject *payload)
M
Michael Roth 已提交
518 519
{
    const char *buf;
M
Michael Roth 已提交
520
    QString *payload_qstr, *response_qstr;
521
    GIOStatus status;
M
Michael Roth 已提交
522

523
    g_assert(payload && s->channel);
M
Michael Roth 已提交
524 525 526 527 528 529

    payload_qstr = qobject_to_json(payload);
    if (!payload_qstr) {
        return -EINVAL;
    }

M
Michael Roth 已提交
530 531 532 533 534 535 536 537 538 539 540 541
    if (s->delimit_response) {
        s->delimit_response = false;
        response_qstr = qstring_new();
        qstring_append_chr(response_qstr, QGA_SENTINEL_BYTE);
        qstring_append(response_qstr, qstring_get_str(payload_qstr));
        QDECREF(payload_qstr);
    } else {
        response_qstr = payload_qstr;
    }

    qstring_append_chr(response_qstr, '\n');
    buf = qstring_get_str(response_qstr);
542
    status = ga_channel_write_all(s->channel, buf, strlen(buf));
M
Michael Roth 已提交
543
    QDECREF(response_qstr);
544 545
    if (status != G_IO_STATUS_NORMAL) {
        return -EIO;
M
Michael Roth 已提交
546
    }
547 548

    return 0;
M
Michael Roth 已提交
549 550 551 552 553 554 555 556 557 558 559
}

static void process_command(GAState *s, QDict *req)
{
    QObject *rsp = NULL;
    int ret;

    g_assert(req);
    g_debug("processing command");
    rsp = qmp_dispatch(QOBJECT(req));
    if (rsp) {
560
        ret = send_response(s, rsp);
561 562
        if (ret < 0) {
            g_warning("error sending response: %s", strerror(-ret));
M
Michael Roth 已提交
563 564 565 566 567 568
        }
        qobject_decref(rsp);
    }
}

/* handle requests/control events coming in over the channel */
P
Paolo Bonzini 已提交
569
static void process_event(JSONMessageParser *parser, GQueue *tokens)
M
Michael Roth 已提交
570 571 572 573 574 575 576 577 578
{
    GAState *s = container_of(parser, GAState, parser);
    QDict *qdict;
    Error *err = NULL;
    int ret;

    g_assert(s && parser);

    g_debug("process_event: called");
579 580 581
    qdict = qobject_to_qdict(json_parser_parse_err(tokens, NULL, &err));
    if (err || !qdict) {
        QDECREF(qdict);
M
Michael Roth 已提交
582 583 584
        qdict = qdict_new();
        if (!err) {
            g_warning("failed to parse event: unknown error");
585
            error_setg(&err, QERR_JSON_PARSING);
M
Michael Roth 已提交
586 587 588
        } else {
            g_warning("failed to parse event: %s", error_get_pretty(err));
        }
589
        qdict_put_obj(qdict, "error", qmp_build_error_object(err));
M
Michael Roth 已提交
590 591 592 593 594 595 596 597 598 599 600
        error_free(err);
    }

    /* handle host->guest commands */
    if (qdict_haskey(qdict, "execute")) {
        process_command(s, qdict);
    } else {
        if (!qdict_haskey(qdict, "error")) {
            QDECREF(qdict);
            qdict = qdict_new();
            g_warning("unrecognized payload format");
601
            error_setg(&err, QERR_UNSUPPORTED);
602
            qdict_put_obj(qdict, "error", qmp_build_error_object(err));
M
Michael Roth 已提交
603 604
            error_free(err);
        }
605
        ret = send_response(s, QOBJECT(qdict));
G
Gonglei 已提交
606 607
        if (ret < 0) {
            g_warning("error sending error response: %s", strerror(-ret));
M
Michael Roth 已提交
608 609 610 611 612 613
        }
    }

    QDECREF(qdict);
}

614 615
/* false return signals GAChannel to close the current client connection */
static gboolean channel_event_cb(GIOCondition condition, gpointer data)
M
Michael Roth 已提交
616 617
{
    GAState *s = data;
618
    gchar buf[QGA_READ_COUNT_DEFAULT+1];
M
Michael Roth 已提交
619
    gsize count;
620
    GIOStatus status = ga_channel_read(s->channel, buf, QGA_READ_COUNT_DEFAULT, &count);
M
Michael Roth 已提交
621 622
    switch (status) {
    case G_IO_STATUS_ERROR:
623
        g_warning("error reading channel");
M
Michael Roth 已提交
624 625
        return false;
    case G_IO_STATUS_NORMAL:
626
        buf[count] = 0;
M
Michael Roth 已提交
627 628
        g_debug("read data, count: %d, data: %s", (int)count, buf);
        json_message_parser_feed(&s->parser, (char *)buf, (int)count);
629 630 631 632 633 634
        break;
    case G_IO_STATUS_EOF:
        g_debug("received EOF");
        if (!s->virtio) {
            return false;
        }
635
        /* fall through */
M
Michael Roth 已提交
636 637 638 639 640 641 642 643 644 645 646 647 648 649 650
    case G_IO_STATUS_AGAIN:
        /* virtio causes us to spin here when no process is attached to
         * host-side chardev. sleep a bit to mitigate this
         */
        if (s->virtio) {
            usleep(100*1000);
        }
        return true;
    default:
        g_warning("unknown channel read status, closing");
        return false;
    }
    return true;
}

651
static gboolean channel_init(GAState *s, const gchar *method, const gchar *path)
M
Michael Roth 已提交
652
{
653
    GAChannelMethod channel_method;
M
Michael Roth 已提交
654

655 656 657 658 659 660 661
    if (strcmp(method, "virtio-serial") == 0) {
        s->virtio = true; /* virtio requires special handling in some cases */
        channel_method = GA_CHANNEL_VIRTIO_SERIAL;
    } else if (strcmp(method, "isa-serial") == 0) {
        channel_method = GA_CHANNEL_ISA_SERIAL;
    } else if (strcmp(method, "unix-listen") == 0) {
        channel_method = GA_CHANNEL_UNIX_LISTEN;
S
Stefan Hajnoczi 已提交
662 663
    } else if (strcmp(method, "vsock-listen") == 0) {
        channel_method = GA_CHANNEL_VSOCK_LISTEN;
M
Michael Roth 已提交
664
    } else {
665 666
        g_critical("unsupported channel method/type: %s", method);
        return false;
M
Michael Roth 已提交
667 668
    }

669 670 671 672 673 674 675
    s->channel = ga_channel_new(channel_method, path, channel_event_cb, s);
    if (!s->channel) {
        g_critical("failed to create guest agent channel");
        return false;
    }

    return true;
M
Michael Roth 已提交
676 677
}

678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
#ifdef _WIN32
DWORD WINAPI service_ctrl_handler(DWORD ctrl, DWORD type, LPVOID data,
                                  LPVOID ctx)
{
    DWORD ret = NO_ERROR;
    GAService *service = &ga_state->service;

    switch (ctrl)
    {
        case SERVICE_CONTROL_STOP:
        case SERVICE_CONTROL_SHUTDOWN:
            quit_handler(SIGTERM);
            service->status.dwCurrentState = SERVICE_STOP_PENDING;
            SetServiceStatus(service->status_handle, &service->status);
            break;

        default:
            ret = ERROR_CALL_NOT_IMPLEMENTED;
    }
    return ret;
}

VOID WINAPI service_main(DWORD argc, TCHAR *argv[])
{
    GAService *service = &ga_state->service;

    service->status_handle = RegisterServiceCtrlHandlerEx(QGA_SERVICE_NAME,
        service_ctrl_handler, NULL);

    if (service->status_handle == 0) {
        g_critical("Failed to register extended requests function!\n");
        return;
    }

    service->status.dwServiceType = SERVICE_WIN32;
    service->status.dwCurrentState = SERVICE_RUNNING;
    service->status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
    service->status.dwWin32ExitCode = NO_ERROR;
    service->status.dwServiceSpecificExitCode = NO_ERROR;
    service->status.dwCheckPoint = 0;
    service->status.dwWaitHint = 0;
    SetServiceStatus(service->status_handle, &service->status);

    g_main_loop_run(ga_state->main_loop);

    service->status.dwCurrentState = SERVICE_STOPPED;
    SetServiceStatus(service->status_handle, &service->status);
}
#endif

728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
static void set_persistent_state_defaults(GAPersistentState *pstate)
{
    g_assert(pstate);
    pstate->fd_counter = QGA_PSTATE_DEFAULT_FD_COUNTER;
}

static void persistent_state_from_keyfile(GAPersistentState *pstate,
                                          GKeyFile *keyfile)
{
    g_assert(pstate);
    g_assert(keyfile);
    /* if any fields are missing, either because the file was tampered with
     * by agents of chaos, or because the field wasn't present at the time the
     * file was created, the best we can ever do is start over with the default
     * values. so load them now, and ignore any errors in accessing key-value
     * pairs
     */
    set_persistent_state_defaults(pstate);

    if (g_key_file_has_key(keyfile, "global", "fd_counter", NULL)) {
        pstate->fd_counter =
749
            g_key_file_get_integer(keyfile, "global", "fd_counter", NULL);
750 751 752 753 754 755 756 757 758
    }
}

static void persistent_state_to_keyfile(const GAPersistentState *pstate,
                                        GKeyFile *keyfile)
{
    g_assert(pstate);
    g_assert(keyfile);

759
    g_key_file_set_integer(keyfile, "global", "fd_counter", pstate->fd_counter);
760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882
}

static gboolean write_persistent_state(const GAPersistentState *pstate,
                                       const gchar *path)
{
    GKeyFile *keyfile = g_key_file_new();
    GError *gerr = NULL;
    gboolean ret = true;
    gchar *data = NULL;
    gsize data_len;

    g_assert(pstate);

    persistent_state_to_keyfile(pstate, keyfile);
    data = g_key_file_to_data(keyfile, &data_len, &gerr);
    if (gerr) {
        g_critical("failed to convert persistent state to string: %s",
                   gerr->message);
        ret = false;
        goto out;
    }

    g_file_set_contents(path, data, data_len, &gerr);
    if (gerr) {
        g_critical("failed to write persistent state to %s: %s",
                    path, gerr->message);
        ret = false;
        goto out;
    }

out:
    if (gerr) {
        g_error_free(gerr);
    }
    if (keyfile) {
        g_key_file_free(keyfile);
    }
    g_free(data);
    return ret;
}

static gboolean read_persistent_state(GAPersistentState *pstate,
                                      const gchar *path, gboolean frozen)
{
    GKeyFile *keyfile = NULL;
    GError *gerr = NULL;
    struct stat st;
    gboolean ret = true;

    g_assert(pstate);

    if (stat(path, &st) == -1) {
        /* it's okay if state file doesn't exist, but any other error
         * indicates a permissions issue or some other misconfiguration
         * that we likely won't be able to recover from.
         */
        if (errno != ENOENT) {
            g_critical("unable to access state file at path %s: %s",
                       path, strerror(errno));
            ret = false;
            goto out;
        }

        /* file doesn't exist. initialize state to default values and
         * attempt to save now. (we could wait till later when we have
         * modified state we need to commit, but if there's a problem,
         * such as a missing parent directory, we want to catch it now)
         *
         * there is a potential scenario where someone either managed to
         * update the agent from a version that didn't use a key store
         * while qemu-ga thought the filesystem was frozen, or
         * deleted the key store prior to issuing a fsfreeze, prior
         * to restarting the agent. in this case we go ahead and defer
         * initial creation till we actually have modified state to
         * write, otherwise fail to recover from freeze.
         */
        set_persistent_state_defaults(pstate);
        if (!frozen) {
            ret = write_persistent_state(pstate, path);
            if (!ret) {
                g_critical("unable to create state file at path %s", path);
                ret = false;
                goto out;
            }
        }
        ret = true;
        goto out;
    }

    keyfile = g_key_file_new();
    g_key_file_load_from_file(keyfile, path, 0, &gerr);
    if (gerr) {
        g_critical("error loading persistent state from path: %s, %s",
                   path, gerr->message);
        ret = false;
        goto out;
    }

    persistent_state_from_keyfile(pstate, keyfile);

out:
    if (keyfile) {
        g_key_file_free(keyfile);
    }
    if (gerr) {
        g_error_free(gerr);
    }

    return ret;
}

int64_t ga_get_fd_handle(GAState *s, Error **errp)
{
    int64_t handle;

    g_assert(s->pstate_filepath);
    /* we blacklist commands and avoid operations that potentially require
     * writing to disk when we're in a frozen state. this includes opening
     * new files, so we should never get here in that situation
     */
    g_assert(!ga_is_frozen(s));

    handle = s->pstate.fd_counter++;
883 884 885 886 887

    /* This should never happen on a reasonable timeframe, as guest-file-open
     * would have to be issued 2^63 times */
    if (s->pstate.fd_counter == INT64_MAX) {
        abort();
888
    }
889

890 891
    if (!write_persistent_state(&s->pstate, s->pstate_filepath)) {
        error_setg(errp, "failed to commit persistent state to disk");
892
        return -1;
893 894 895 896 897
    }

    return handle;
}

898 899 900 901 902
static void ga_print_cmd(QmpCommand *cmd, void *opaque)
{
    printf("%s\n", qmp_command_name(cmd));
}

903
static GList *split_list(const gchar *str, const gchar *delim)
904 905
{
    GList *list = NULL;
906 907
    int i;
    gchar **strv;
908

909 910 911
    strv = g_strsplit(str, delim, -1);
    for (i = 0; strv[i]; i++) {
        list = g_list_prepend(list, strv[i]);
912
    }
913
    g_free(strv);
914 915 916 917

    return list;
}

918 919 920 921 922
typedef struct GAConfig {
    char *channel_path;
    char *method;
    char *log_filepath;
    char *pid_filepath;
923
#ifdef CONFIG_FSFREEZE
924
    char *fsfreeze_hook;
925
#endif
926
    char *state_dir;
927
#ifdef _WIN32
928
    const char *service;
929
#endif
930
    gchar *bliststr; /* blacklist may point to this string */
931 932 933
    GList *blacklist;
    int daemonize;
    GLogLevelFlags log_level;
M
Marc-André Lureau 已提交
934
    int dumpconf;
935 936
} GAConfig;

937 938 939 940
static void config_load(GAConfig *config)
{
    GError *gerr = NULL;
    GKeyFile *keyfile;
941
    const char *conf = g_getenv("QGA_CONF") ?: QGA_CONF_DEFAULT;
942 943 944

    /* read system config */
    keyfile = g_key_file_new();
945
    if (!g_key_file_load_from_file(keyfile, conf, 0, &gerr)) {
946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001
        goto end;
    }
    if (g_key_file_has_key(keyfile, "general", "daemon", NULL)) {
        config->daemonize =
            g_key_file_get_boolean(keyfile, "general", "daemon", &gerr);
    }
    if (g_key_file_has_key(keyfile, "general", "method", NULL)) {
        config->method =
            g_key_file_get_string(keyfile, "general", "method", &gerr);
    }
    if (g_key_file_has_key(keyfile, "general", "path", NULL)) {
        config->channel_path =
            g_key_file_get_string(keyfile, "general", "path", &gerr);
    }
    if (g_key_file_has_key(keyfile, "general", "logfile", NULL)) {
        config->log_filepath =
            g_key_file_get_string(keyfile, "general", "logfile", &gerr);
    }
    if (g_key_file_has_key(keyfile, "general", "pidfile", NULL)) {
        config->pid_filepath =
            g_key_file_get_string(keyfile, "general", "pidfile", &gerr);
    }
#ifdef CONFIG_FSFREEZE
    if (g_key_file_has_key(keyfile, "general", "fsfreeze-hook", NULL)) {
        config->fsfreeze_hook =
            g_key_file_get_string(keyfile,
                                  "general", "fsfreeze-hook", &gerr);
    }
#endif
    if (g_key_file_has_key(keyfile, "general", "statedir", NULL)) {
        config->state_dir =
            g_key_file_get_string(keyfile, "general", "statedir", &gerr);
    }
    if (g_key_file_has_key(keyfile, "general", "verbose", NULL) &&
        g_key_file_get_boolean(keyfile, "general", "verbose", &gerr)) {
        /* enable all log levels */
        config->log_level = G_LOG_LEVEL_MASK;
    }
    if (g_key_file_has_key(keyfile, "general", "blacklist", NULL)) {
        config->bliststr =
            g_key_file_get_string(keyfile, "general", "blacklist", &gerr);
        config->blacklist = g_list_concat(config->blacklist,
                                          split_list(config->bliststr, ","));
    }

end:
    g_key_file_free(keyfile);
    if (gerr &&
        !(gerr->domain == G_FILE_ERROR && gerr->code == G_FILE_ERROR_NOENT)) {
        g_critical("error loading configuration from path: %s, %s",
                   QGA_CONF_DEFAULT, gerr->message);
        exit(EXIT_FAILURE);
    }
    g_clear_error(&gerr);
}

M
Marc-André Lureau 已提交
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
static gchar *list_join(GList *list, const gchar separator)
{
    GString *str = g_string_new("");

    while (list) {
        str = g_string_append(str, (gchar *)list->data);
        list = g_list_next(list);
        if (list) {
            str = g_string_append_c(str, separator);
        }
    }

    return g_string_free(str, FALSE);
}

static void config_dump(GAConfig *config)
{
    GError *error = NULL;
    GKeyFile *keyfile;
    gchar *tmp;

    keyfile = g_key_file_new();
    g_assert(keyfile);

    g_key_file_set_boolean(keyfile, "general", "daemon", config->daemonize);
    g_key_file_set_string(keyfile, "general", "method", config->method);
    g_key_file_set_string(keyfile, "general", "path", config->channel_path);
    if (config->log_filepath) {
        g_key_file_set_string(keyfile, "general", "logfile",
                              config->log_filepath);
    }
    g_key_file_set_string(keyfile, "general", "pidfile", config->pid_filepath);
#ifdef CONFIG_FSFREEZE
    if (config->fsfreeze_hook) {
        g_key_file_set_string(keyfile, "general", "fsfreeze-hook",
                              config->fsfreeze_hook);
    }
#endif
    g_key_file_set_string(keyfile, "general", "statedir", config->state_dir);
    g_key_file_set_boolean(keyfile, "general", "verbose",
                           config->log_level == G_LOG_LEVEL_MASK);
    tmp = list_join(config->blacklist, ',');
    g_key_file_set_string(keyfile, "general", "blacklist", tmp);
    g_free(tmp);

    tmp = g_key_file_to_data(keyfile, NULL, &error);
    printf("%s", tmp);

    g_free(tmp);
    g_key_file_free(keyfile);
}

1054
static void config_parse(GAConfig *config, int argc, char **argv)
1055 1056 1057
{
    const char *sopt = "hVvdm:p:l:f:F::b:s:t:D";
    int opt_ind = 0, ch;
M
Michael Roth 已提交
1058 1059 1060
    const struct option lopt[] = {
        { "help", 0, NULL, 'h' },
        { "version", 0, NULL, 'V' },
M
Marc-André Lureau 已提交
1061
        { "dump-conf", 0, NULL, 'D' },
1062 1063
        { "logfile", 1, NULL, 'l' },
        { "pidfile", 1, NULL, 'f' },
1064 1065 1066
#ifdef CONFIG_FSFREEZE
        { "fsfreeze-hook", 2, NULL, 'F' },
#endif
M
Michael Roth 已提交
1067
        { "verbose", 0, NULL, 'v' },
1068 1069
        { "method", 1, NULL, 'm' },
        { "path", 1, NULL, 'p' },
M
Michael Roth 已提交
1070
        { "daemonize", 0, NULL, 'd' },
1071 1072 1073
        { "blacklist", 1, NULL, 'b' },
#ifdef _WIN32
        { "service", 1, NULL, 's' },
1074
#endif
1075
        { "statedir", 1, NULL, 't' },
M
Michael Roth 已提交
1076 1077 1078 1079 1080 1081
        { NULL, 0, NULL, 0 }
    };

    while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
        switch (ch) {
        case 'm':
1082
            g_free(config->method);
1083
            config->method = g_strdup(optarg);
M
Michael Roth 已提交
1084 1085
            break;
        case 'p':
1086
            g_free(config->channel_path);
1087
            config->channel_path = g_strdup(optarg);
M
Michael Roth 已提交
1088 1089
            break;
        case 'l':
1090
            g_free(config->log_filepath);
1091
            config->log_filepath = g_strdup(optarg);
M
Michael Roth 已提交
1092 1093
            break;
        case 'f':
1094
            g_free(config->pid_filepath);
1095
            config->pid_filepath = g_strdup(optarg);
M
Michael Roth 已提交
1096
            break;
1097 1098
#ifdef CONFIG_FSFREEZE
        case 'F':
1099
            g_free(config->fsfreeze_hook);
1100
            config->fsfreeze_hook = g_strdup(optarg ?: QGA_FSFREEZE_HOOK_DEFAULT);
1101 1102
            break;
#endif
1103
        case 't':
1104
            g_free(config->state_dir);
1105
            config->state_dir = g_strdup(optarg);
M
Marc-André Lureau 已提交
1106
            break;
M
Michael Roth 已提交
1107 1108
        case 'v':
            /* enable all log levels */
1109
            config->log_level = G_LOG_LEVEL_MASK;
M
Michael Roth 已提交
1110 1111
            break;
        case 'V':
1112
            printf("QEMU Guest Agent %s\n", QEMU_VERSION);
1113
            exit(EXIT_SUCCESS);
M
Michael Roth 已提交
1114
        case 'd':
1115
            config->daemonize = 1;
M
Michael Roth 已提交
1116
            break;
M
Marc-André Lureau 已提交
1117 1118 1119
        case 'D':
            config->dumpconf = 1;
            break;
1120
        case 'b': {
1121
            if (is_help_option(optarg)) {
1122
                qmp_for_each_command(ga_print_cmd, NULL);
1123
                exit(EXIT_SUCCESS);
1124
            }
1125 1126
            config->blacklist = g_list_concat(config->blacklist,
                                             split_list(optarg, ","));
1127 1128
            break;
        }
1129 1130
#ifdef _WIN32
        case 's':
1131 1132
            config->service = optarg;
            if (strcmp(config->service, "install") == 0) {
1133
                if (ga_install_vss_provider()) {
1134
                    exit(EXIT_FAILURE);
1135
                }
1136 1137
                if (ga_install_service(config->channel_path,
                                       config->log_filepath, config->state_dir)) {
1138
                    exit(EXIT_FAILURE);
1139
                }
1140
                exit(EXIT_SUCCESS);
1141
            } else if (strcmp(config->service, "uninstall") == 0) {
1142
                ga_uninstall_vss_provider();
1143
                exit(ga_uninstall_service());
1144
            } else if (strcmp(config->service, "vss-install") == 0) {
1145
                if (ga_install_vss_provider()) {
1146
                    exit(EXIT_FAILURE);
1147
                }
1148
                exit(EXIT_SUCCESS);
1149
            } else if (strcmp(config->service, "vss-uninstall") == 0) {
1150
                ga_uninstall_vss_provider();
1151
                exit(EXIT_SUCCESS);
1152 1153
            } else {
                printf("Unknown service command.\n");
1154
                exit(EXIT_FAILURE);
1155 1156 1157
            }
            break;
#endif
M
Michael Roth 已提交
1158 1159
        case 'h':
            usage(argv[0]);
1160
            exit(EXIT_SUCCESS);
M
Michael Roth 已提交
1161 1162 1163
        case '?':
            g_print("Unknown option, try '%s --help' for more information.\n",
                    argv[0]);
1164
            exit(EXIT_FAILURE);
M
Michael Roth 已提交
1165 1166
        }
    }
1167 1168 1169 1170 1171 1172 1173 1174 1175
}

static void config_free(GAConfig *config)
{
    g_free(config->method);
    g_free(config->log_filepath);
    g_free(config->pid_filepath);
    g_free(config->state_dir);
    g_free(config->channel_path);
1176
    g_free(config->bliststr);
1177 1178 1179
#ifdef CONFIG_FSFREEZE
    g_free(config->fsfreeze_hook);
#endif
1180
    g_list_free_full(config->blacklist, g_free);
1181 1182 1183
    g_free(config);
}

1184
static bool check_is_frozen(GAState *s)
1185
{
1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
#ifndef _WIN32
    /* check if a previous instance of qemu-ga exited with filesystems' state
     * marked as frozen. this could be a stale value (a non-qemu-ga process
     * or reboot may have since unfrozen them), but better to require an
     * uneeded unfreeze than to risk hanging on start-up
     */
    struct stat st;
    if (stat(s->state_filepath_isfrozen, &st) == -1) {
        /* it's okay if the file doesn't exist, but if we can't access for
         * some other reason, such as permissions, there's a configuration
         * that needs to be addressed. so just bail now before we get into
         * more trouble later
         */
        if (errno != ENOENT) {
            g_critical("unable to access state file at path %s: %s",
                       s->state_filepath_isfrozen, strerror(errno));
            return EXIT_FAILURE;
        }
    } else {
        g_warning("previous instance appears to have exited with frozen"
                  " filesystems. deferring logging/pidfile creation and"
                  " disabling non-fsfreeze-safe commands until"
                  " guest-fsfreeze-thaw is issued, or filesystems are"
                  " manually unfrozen and the file %s is removed",
                  s->state_filepath_isfrozen);
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
        return true;
    }
#endif
    return false;
}

static int run_agent(GAState *s, GAConfig *config)
{
    ga_state = s;

    g_log_set_default_handler(ga_log, s);
    g_log_set_fatal_mask(NULL, G_LOG_LEVEL_ERROR);
    ga_enable_logging(s);

#ifdef _WIN32
    /* On win32 the state directory is application specific (be it the default
     * or a user override). We got past the command line parsing; let's create
     * the directory (with any intermediate directories). If we run into an
     * error later on, we won't try to clean up the directory, it is considered
     * persistent.
     */
    if (g_mkdir_with_parents(config->state_dir, S_IRWXU) == -1) {
        g_critical("unable to create (an ancestor of) the state directory"
                   " '%s': %s", config->state_dir, strerror(errno));
        return EXIT_FAILURE;
1236 1237 1238 1239
    }
#endif

    if (ga_is_frozen(s)) {
1240
        if (config->daemonize) {
S
Stefan Weil 已提交
1241
            /* delay opening/locking of pidfile till filesystems are unfrozen */
1242
            s->deferred_options.pid_filepath = config->pid_filepath;
1243 1244
            become_daemon(NULL);
        }
1245
        if (config->log_filepath) {
1246
            /* delay opening the log file till filesystems are unfrozen */
1247
            s->deferred_options.log_filepath = config->log_filepath;
1248 1249
        }
        ga_disable_logging(s);
1250
        qmp_for_each_command(ga_disable_non_whitelisted, NULL);
1251
    } else {
1252 1253
        if (config->daemonize) {
            become_daemon(config->pid_filepath);
1254
        }
1255 1256
        if (config->log_filepath) {
            FILE *log_file = ga_open_logfile(config->log_filepath);
1257
            if (!log_file) {
1258 1259
                g_critical("unable to open specified log file: %s",
                           strerror(errno));
1260
                return EXIT_FAILURE;
1261
            }
1262
            s->log_file = log_file;
1263 1264 1265
        }
    }

1266 1267 1268 1269 1270
    /* load persistent state from disk */
    if (!read_persistent_state(&s->pstate,
                               s->pstate_filepath,
                               ga_is_frozen(s))) {
        g_critical("failed to load persistent state");
1271
        return EXIT_FAILURE;
1272 1273
    }

1274 1275 1276 1277
    config->blacklist = ga_command_blacklist_init(config->blacklist);
    if (config->blacklist) {
        GList *l = config->blacklist;
        s->blacklist = config->blacklist;
1278
        do {
1279 1280 1281 1282
            g_debug("disabling command: %s", (char *)l->data);
            qmp_disable_command(l->data);
            l = g_list_next(l);
        } while (l);
1283
    }
1284 1285 1286
    s->command_state = ga_command_state_new();
    ga_command_state_init(s, s->command_state);
    ga_command_state_init_all(s->command_state);
1287
    json_message_parser_init(&s->parser, process_event);
M
Michael Roth 已提交
1288
    ga_state = s;
1289
#ifndef _WIN32
1290 1291
    if (!register_signal_handlers()) {
        g_critical("failed to register signal handlers");
1292
        return EXIT_FAILURE;
1293
    }
1294
#endif
M
Michael Roth 已提交
1295

1296
    s->main_loop = g_main_loop_new(NULL, false);
1297
    if (!channel_init(ga_state, config->method, config->channel_path)) {
1298
        g_critical("failed to initialize guest agent channel");
1299
        return EXIT_FAILURE;
1300
    }
1301
#ifndef _WIN32
M
Michael Roth 已提交
1302
    g_main_loop_run(ga_state->main_loop);
1303
#else
1304
    if (config->daemonize) {
1305 1306 1307 1308 1309 1310 1311
        SERVICE_TABLE_ENTRY service_table[] = {
            { (char *)QGA_SERVICE_NAME, service_main }, { NULL, NULL } };
        StartServiceCtrlDispatcher(service_table);
    } else {
        g_main_loop_run(ga_state->main_loop);
    }
#endif
M
Michael Roth 已提交
1312

1313 1314
    return EXIT_SUCCESS;
}
M
Michael Roth 已提交
1315

1316 1317 1318 1319
int main(int argc, char **argv)
{
    int ret = EXIT_SUCCESS;
    GAState *s = g_new0(GAState, 1);
1320
    GAConfig *config = g_new0(GAConfig, 1);
1321

1322 1323
    config->log_level = G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL;

1324
    qmp_init_marshal();
1325 1326

    init_dfl_pathnames();
1327 1328
    config_load(config);
    config_parse(config, argc, argv);
1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339

    if (config->pid_filepath == NULL) {
        config->pid_filepath = g_strdup(dfl_pathnames.pidfile);
    }

    if (config->state_dir == NULL) {
        config->state_dir = g_strdup(dfl_pathnames.state_dir);
    }

    if (config->method == NULL) {
        config->method = g_strdup("virtio-serial");
1340 1341
    }

1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
    if (config->channel_path == NULL) {
        if (strcmp(config->method, "virtio-serial") == 0) {
            /* try the default path for the virtio-serial port */
            config->channel_path = g_strdup(QGA_VIRTIO_PATH_DEFAULT);
        } else if (strcmp(config->method, "isa-serial") == 0) {
            /* try the default path for the serial port - COM1 */
            config->channel_path = g_strdup(QGA_SERIAL_PATH_DEFAULT);
        } else {
            g_critical("must specify a path for this channel");
            ret = EXIT_FAILURE;
            goto end;
        }
    }

    s->log_level = config->log_level;
    s->log_file = stderr;
#ifdef CONFIG_FSFREEZE
    s->fsfreeze_hook = config->fsfreeze_hook;
#endif
    s->pstate_filepath = g_strdup_printf("%s/qga.state", config->state_dir);
    s->state_filepath_isfrozen = g_strdup_printf("%s/qga.state.isfrozen",
                                                 config->state_dir);
    s->frozen = check_is_frozen(s);

M
Marc-André Lureau 已提交
1366 1367 1368 1369 1370
    if (config->dumpconf) {
        config_dump(config);
        goto end;
    }

1371 1372 1373 1374 1375
    ret = run_agent(s, config);

end:
    if (s->command_state) {
        ga_command_state_cleanup_all(s->command_state);
1376 1377
        ga_command_state_free(s->command_state);
        json_message_parser_destroy(&s->parser);
1378 1379 1380 1381
    }
    if (s->channel) {
        ga_channel_free(s->channel);
    }
M
Marc-André Lureau 已提交
1382 1383
    g_free(s->pstate_filepath);
    g_free(s->state_filepath_isfrozen);
1384

1385 1386
    if (config->daemonize) {
        unlink(config->pid_filepath);
1387
    }
M
Marc-André Lureau 已提交
1388

1389
    config_free(config);
1390 1391 1392 1393
    if (s->main_loop) {
        g_main_loop_unref(s->main_loop);
    }
    g_free(s);
M
Marc-André Lureau 已提交
1394

1395
    return ret;
M
Michael Roth 已提交
1396
}