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