qemu-ga.c 24.7 KB
Newer Older
M
Michael Roth 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*
 * 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.
 */
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <glib.h>
#include <getopt.h>
18
#ifndef _WIN32
M
Michael Roth 已提交
19
#include <syslog.h>
20
#include <sys/wait.h>
21
#include <sys/stat.h>
22
#endif
M
Michael Roth 已提交
23 24 25 26 27 28 29 30 31
#include "json-streamer.h"
#include "json-parser.h"
#include "qint.h"
#include "qjson.h"
#include "qga/guest-agent-core.h"
#include "module.h"
#include "signal.h"
#include "qerror.h"
#include "error_int.h"
32
#include "qapi/qmp-core.h"
33
#include "qga/channel.h"
34 35 36 37
#ifdef _WIN32
#include "qga/service-win32.h"
#include <windows.h>
#endif
M
Michael Roth 已提交
38

39
#ifndef _WIN32
M
Michael Roth 已提交
40
#define QGA_VIRTIO_PATH_DEFAULT "/dev/virtio-ports/org.qemu.guest_agent.0"
41 42 43
#else
#define QGA_VIRTIO_PATH_DEFAULT "\\\\.\\Global\\org.qemu.guest_agent.0"
#endif
M
Michael Roth 已提交
44
#define QGA_PIDFILE_DEFAULT "/var/run/qemu-ga.pid"
45
#define QGA_STATEDIR_DEFAULT "/tmp"
M
Michael Roth 已提交
46
#define QGA_SENTINEL_BYTE 0xFF
M
Michael Roth 已提交
47 48 49 50

struct GAState {
    JSONMessageParser parser;
    GMainLoop *main_loop;
51
    GAChannel *channel;
M
Michael Roth 已提交
52 53 54 55 56
    bool virtio; /* fastpath to check for virtio to deal with poll() quirks */
    GACommandState *command_state;
    GLogLevelFlags log_level;
    FILE *log_file;
    bool logging_enabled;
57 58 59
#ifdef _WIN32
    GAService service;
#endif
M
Michael Roth 已提交
60
    bool delimit_response;
61 62
    bool frozen;
    GList *blacklist;
63 64 65 66 67
    const char *state_filepath_isfrozen;
    struct {
        const char *log_filepath;
        const char *pid_filepath;
    } deferred_options;
M
Michael Roth 已提交
68 69
};

M
Michael Roth 已提交
70
struct GAState *ga_state;
M
Michael Roth 已提交
71

72 73 74 75 76 77 78 79 80 81
/* commands that are safe to issue while filesystems are frozen */
static const char *ga_freeze_whitelist[] = {
    "guest-ping",
    "guest-info",
    "guest-sync",
    "guest-fsfreeze-status",
    "guest-fsfreeze-thaw",
    NULL
};

82 83 84 85 86 87
#ifdef _WIN32
DWORD WINAPI service_ctrl_handler(DWORD ctrl, DWORD type, LPVOID data,
                                  LPVOID ctx);
VOID WINAPI service_main(DWORD argc, TCHAR *argv[]);
#endif

M
Michael Roth 已提交
88 89
static void quit_handler(int sig)
{
90 91 92 93 94 95 96 97 98
    /* 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;
    }
99
    g_debug("received signal num %d, quitting", sig);
M
Michael Roth 已提交
100 101 102 103 104 105

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

106
#ifndef _WIN32
107 108 109 110 111 112 113
/* reap _all_ terminated children */
static void child_handler(int sig)
{
    int status;
    while (waitpid(-1, &status, WNOHANG) > 0) /* NOTHING */;
}

114
static gboolean register_signal_handlers(void)
M
Michael Roth 已提交
115
{
116
    struct sigaction sigact, sigact_chld;
M
Michael Roth 已提交
117 118 119 120 121 122 123 124
    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));
125
        return false;
M
Michael Roth 已提交
126 127 128 129
    }
    ret = sigaction(SIGTERM, &sigact, NULL);
    if (ret == -1) {
        g_error("error configuring signal handler: %s", strerror(errno));
130
        return false;
M
Michael Roth 已提交
131
    }
132 133 134 135 136 137 138 139 140

    memset(&sigact_chld, 0, sizeof(struct sigaction));
    sigact_chld.sa_handler = child_handler;
    sigact_chld.sa_flags = SA_NOCLDSTOP;
    ret = sigaction(SIGCHLD, &sigact_chld, NULL);
    if (ret == -1) {
        g_error("error configuring signal handler: %s", strerror(errno));
    }

141
    return true;
M
Michael Roth 已提交
142
}
143
#endif
M
Michael Roth 已提交
144 145 146 147

static void usage(const char *cmd)
{
    printf(
M
Michael Roth 已提交
148
"Usage: %s [-m <method> -p <path>] [<options>]\n"
M
Michael Roth 已提交
149 150 151 152
"QEMU Guest Agent %s\n"
"\n"
"  -m, --method      transport method: one of unix-listen, virtio-serial, or\n"
"                    isa-serial (virtio-serial is the default)\n"
M
Michael Roth 已提交
153 154
"  -p, --path        device/socket path (the default for virtio-serial is:\n"
"                    %s)\n"
M
Michael Roth 已提交
155 156
"  -l, --logfile     set logfile path, logs to stderr by default\n"
"  -f, --pidfile     specify pidfile (default is %s)\n"
157 158
"  -t, --statedir    specify dir to store state information (absolute paths\n"
"                    only, default is %s)\n"
M
Michael Roth 已提交
159 160 161
"  -v, --verbose     log extra debugging information\n"
"  -V, --version     print version information and exit\n"
"  -d, --daemonize   become a daemon\n"
162 163
#ifdef _WIN32
"  -s, --service     service commands: install, uninstall\n"
164
#endif
M
Michael Roth 已提交
165
"  -b, --blacklist   comma-separated list of RPCs to disable (no spaces, \"?\"\n"
166
"                    to list available RPCs)\n"
M
Michael Roth 已提交
167 168 169
"  -h, --help        display this help and exit\n"
"\n"
"Report bugs to <mdroth@linux.vnet.ibm.com>\n"
170 171
    , cmd, QGA_VERSION, QGA_VIRTIO_PATH_DEFAULT, QGA_PIDFILE_DEFAULT,
    QGA_STATEDIR_DEFAULT);
M
Michael Roth 已提交
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
}

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;
221
#ifndef _WIN32
222
    if (domain && strcmp(domain, "syslog") == 0) {
M
Michael Roth 已提交
223 224
        syslog(LOG_INFO, "%s: %s", level_str, msg);
    } else if (level & s->log_level) {
225 226 227
#else
    if (level & s->log_level) {
#endif
M
Michael Roth 已提交
228 229 230 231 232 233 234
        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 已提交
235 236 237 238 239
void ga_set_response_delimited(GAState *s)
{
    s->delimit_response = true;
}

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
#ifndef _WIN32
static bool ga_open_pidfile(const char *pidfile)
{
    int pidfd;
    char pidstr[32];

    pidfd = open(pidfile, O_CREAT|O_WRONLY, S_IRUSR|S_IWUSR);
    if (pidfd == -1 || lockf(pidfd, F_TLOCK, 0)) {
        g_critical("Cannot lock pid file, %s", strerror(errno));
        return false;
    }

    if (ftruncate(pidfd, 0) || lseek(pidfd, 0, SEEK_SET)) {
        g_critical("Failed to truncate pid file");
        goto fail;
    }
    sprintf(pidstr, "%d", getpid());
    if (write(pidfd, pidstr, strlen(pidstr)) != strlen(pidstr)) {
        g_critical("Failed to write pid file");
        goto fail;
    }

    return true;

fail:
    unlink(pidfile);
    return false;
}
#else /* _WIN32 */
static bool ga_open_pidfile(const char *pidfile)
{
    return true;
}
#endif

275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
static gint ga_strcmp(gconstpointer str1, gconstpointer str2)
{
    return strcmp(str1, str2);
}

/* disable commands that aren't safe for fsfreeze */
static void ga_disable_non_whitelisted(void)
{
    char **list_head, **list;
    bool whitelisted;
    int i;

    list_head = list = qmp_get_command_list();
    while (*list != NULL) {
        whitelisted = false;
        i = 0;
        while (ga_freeze_whitelist[i] != NULL) {
            if (strcmp(*list, ga_freeze_whitelist[i]) == 0) {
                whitelisted = true;
            }
            i++;
        }
        if (!whitelisted) {
            g_debug("disabling command: %s", *list);
            qmp_disable_command(*list);
        }
        g_free(*list);
        list++;
    }
    g_free(list_head);
}

J
Jim Meyering 已提交
307
/* [re-]enable all commands, except those explicitly blacklisted by user */
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
static void ga_enable_non_blacklisted(GList *blacklist)
{
    char **list_head, **list;

    list_head = list = qmp_get_command_list();
    while (*list != NULL) {
        if (g_list_find_custom(blacklist, *list, ga_strcmp) == NULL &&
            !qmp_command_is_enabled(*list)) {
            g_debug("enabling command: %s", *list);
            qmp_enable_command(*list);
        }
        g_free(*list);
        list++;
    }
    g_free(list_head);
}

325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
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;
}

347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
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 */
    ga_disable_non_whitelisted();
    g_warning("disabling logging due to filesystem freeze");
    ga_disable_logging(s);
    s->frozen = true;
362 363 364 365
    if (!ga_create_file(s->state_filepath_isfrozen)) {
        g_warning("unable to create %s, fsfreeze may not function properly",
                  s->state_filepath_isfrozen);
    }
366 367 368 369 370 371 372 373
}

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

374 375 376 377 378 379 380 381 382 383
    /* 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) {
        s->log_file = fopen(s->deferred_options.log_filepath, "a");
        if (!s->log_file) {
            s->log_file = stderr;
        }
        s->deferred_options.log_filepath = NULL;
    }
384
    ga_enable_logging(s);
385 386 387 388 389 390 391
    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;
    }
392 393 394 395

    /* enable all disabled, non-blacklisted commands */
    ga_enable_non_blacklisted(s->blacklist);
    s->frozen = false;
396 397 398 399
    if (!ga_delete_file(s->state_filepath_isfrozen)) {
        g_warning("unable to delete %s, fsfreeze may not function properly",
                  s->state_filepath_isfrozen);
    }
400 401
}

M
Michael Roth 已提交
402 403
static void become_daemon(const char *pidfile)
{
404
#ifndef _WIN32
M
Michael Roth 已提交
405 406 407 408 409 410 411 412 413 414
    pid_t pid, sid;

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

415 416 417 418 419
    if (pidfile) {
        if (!ga_open_pidfile(pidfile)) {
            g_critical("failed to create pidfile");
            exit(EXIT_FAILURE);
        }
M
Michael Roth 已提交
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
    }

    umask(0);
    sid = setsid();
    if (sid < 0) {
        goto fail;
    }
    if ((chdir("/")) < 0) {
        goto fail;
    }

    close(STDIN_FILENO);
    close(STDOUT_FILENO);
    close(STDERR_FILENO);
    return;

fail:
    unlink(pidfile);
    g_critical("failed to daemonize");
    exit(EXIT_FAILURE);
440
#endif
441
}
M
Michael Roth 已提交
442

443
static int send_response(GAState *s, QObject *payload)
M
Michael Roth 已提交
444 445
{
    const char *buf;
M
Michael Roth 已提交
446
    QString *payload_qstr, *response_qstr;
447
    GIOStatus status;
M
Michael Roth 已提交
448

449
    g_assert(payload && s->channel);
M
Michael Roth 已提交
450 451 452 453 454 455

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

M
Michael Roth 已提交
456 457 458 459 460 461 462 463 464 465 466 467
    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);
468
    status = ga_channel_write_all(s->channel, buf, strlen(buf));
M
Michael Roth 已提交
469
    QDECREF(response_qstr);
470 471
    if (status != G_IO_STATUS_NORMAL) {
        return -EIO;
M
Michael Roth 已提交
472
    }
473 474

    return 0;
M
Michael Roth 已提交
475 476 477 478 479 480 481 482 483 484 485
}

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) {
486
        ret = send_response(s, rsp);
M
Michael Roth 已提交
487
        if (ret) {
488
            g_warning("error sending response: %s", strerror(ret));
M
Michael Roth 已提交
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
        }
        qobject_decref(rsp);
    }
}

/* handle requests/control events coming in over the channel */
static void process_event(JSONMessageParser *parser, QList *tokens)
{
    GAState *s = container_of(parser, GAState, parser);
    QObject *obj;
    QDict *qdict;
    Error *err = NULL;
    int ret;

    g_assert(s && parser);

    g_debug("process_event: called");
    obj = json_parser_parse_err(tokens, NULL, &err);
    if (err || !obj || qobject_type(obj) != QTYPE_QDICT) {
        qobject_decref(obj);
        qdict = qdict_new();
        if (!err) {
            g_warning("failed to parse event: unknown error");
            error_set(&err, QERR_JSON_PARSING);
        } else {
            g_warning("failed to parse event: %s", error_get_pretty(err));
        }
        qdict_put_obj(qdict, "error", error_get_qobject(err));
        error_free(err);
    } else {
        qdict = qobject_to_qdict(obj);
    }

    g_assert(qdict);

    /* 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");
            error_set(&err, QERR_UNSUPPORTED);
            qdict_put_obj(qdict, "error", error_get_qobject(err));
            error_free(err);
        }
536
        ret = send_response(s, QOBJECT(qdict));
M
Michael Roth 已提交
537
        if (ret) {
538
            g_warning("error sending error response: %s", strerror(ret));
M
Michael Roth 已提交
539 540 541 542 543 544
        }
    }

    QDECREF(qdict);
}

545 546
/* false return signals GAChannel to close the current client connection */
static gboolean channel_event_cb(GIOCondition condition, gpointer data)
M
Michael Roth 已提交
547 548
{
    GAState *s = data;
549
    gchar buf[QGA_READ_COUNT_DEFAULT+1];
M
Michael Roth 已提交
550 551
    gsize count;
    GError *err = NULL;
552
    GIOStatus status = ga_channel_read(s->channel, buf, QGA_READ_COUNT_DEFAULT, &count);
M
Michael Roth 已提交
553 554 555 556 557 558 559
    if (err != NULL) {
        g_warning("error reading channel: %s", err->message);
        g_error_free(err);
        return false;
    }
    switch (status) {
    case G_IO_STATUS_ERROR:
560
        g_warning("error reading channel");
M
Michael Roth 已提交
561 562
        return false;
    case G_IO_STATUS_NORMAL:
563
        buf[count] = 0;
M
Michael Roth 已提交
564 565
        g_debug("read data, count: %d, data: %s", (int)count, buf);
        json_message_parser_feed(&s->parser, (char *)buf, (int)count);
566 567 568 569 570 571
        break;
    case G_IO_STATUS_EOF:
        g_debug("received EOF");
        if (!s->virtio) {
            return false;
        }
M
Michael Roth 已提交
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
    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;
}

587
static gboolean channel_init(GAState *s, const gchar *method, const gchar *path)
M
Michael Roth 已提交
588
{
589
    GAChannelMethod channel_method;
M
Michael Roth 已提交
590

591 592
    if (method == NULL) {
        method = "virtio-serial";
M
Michael Roth 已提交
593 594
    }

595 596
    if (path == NULL) {
        if (strcmp(method, "virtio-serial") != 0) {
M
Michael Roth 已提交
597
            g_critical("must specify a path for this channel");
598
            return false;
M
Michael Roth 已提交
599 600
        }
        /* try the default path for the virtio-serial port */
601
        path = QGA_VIRTIO_PATH_DEFAULT;
M
Michael Roth 已提交
602 603
    }

604 605 606 607 608 609 610
    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;
M
Michael Roth 已提交
611
    } else {
612 613
        g_critical("unsupported channel method/type: %s", method);
        return false;
M
Michael Roth 已提交
614 615
    }

616 617 618 619 620 621 622
    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 已提交
623 624
}

625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674
#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

M
Michael Roth 已提交
675 676
int main(int argc, char **argv)
{
677 678 679 680 681
    const char *sopt = "hVvdm:p:l:f:b:s:t:";
    const char *method = NULL, *path = NULL;
    const char *log_filepath = NULL;
    const char *pid_filepath = QGA_PIDFILE_DEFAULT;
    const char *state_dir = QGA_STATEDIR_DEFAULT;
682 683 684
#ifdef _WIN32
    const char *service = NULL;
#endif
M
Michael Roth 已提交
685 686 687
    const struct option lopt[] = {
        { "help", 0, NULL, 'h' },
        { "version", 0, NULL, 'V' },
688 689
        { "logfile", 1, NULL, 'l' },
        { "pidfile", 1, NULL, 'f' },
M
Michael Roth 已提交
690
        { "verbose", 0, NULL, 'v' },
691 692
        { "method", 1, NULL, 'm' },
        { "path", 1, NULL, 'p' },
M
Michael Roth 已提交
693
        { "daemonize", 0, NULL, 'd' },
694 695 696
        { "blacklist", 1, NULL, 'b' },
#ifdef _WIN32
        { "service", 1, NULL, 's' },
697
#endif
698
        { "statedir", 1, NULL, 't' },
M
Michael Roth 已提交
699 700
        { NULL, 0, NULL, 0 }
    };
701
    int opt_ind = 0, ch, daemonize = 0, i, j, len;
M
Michael Roth 已提交
702
    GLogLevelFlags log_level = G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL;
703
    GList *blacklist = NULL;
M
Michael Roth 已提交
704 705
    GAState *s;

706 707
    module_call_init(MODULE_INIT_QAPI);

M
Michael Roth 已提交
708 709 710 711 712 713 714 715 716
    while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
        switch (ch) {
        case 'm':
            method = optarg;
            break;
        case 'p':
            path = optarg;
            break;
        case 'l':
717
            log_filepath = optarg;
M
Michael Roth 已提交
718 719
            break;
        case 'f':
720
            pid_filepath = optarg;
M
Michael Roth 已提交
721
            break;
722 723 724
        case 't':
             state_dir = optarg;
             break;
M
Michael Roth 已提交
725 726 727 728 729 730 731 732 733 734
        case 'v':
            /* enable all log levels */
            log_level = G_LOG_LEVEL_MASK;
            break;
        case 'V':
            printf("QEMU Guest Agent %s\n", QGA_VERSION);
            return 0;
        case 'd':
            daemonize = 1;
            break;
735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
        case 'b': {
            char **list_head, **list;
            if (*optarg == '?') {
                list_head = list = qmp_get_command_list();
                while (*list != NULL) {
                    printf("%s\n", *list);
                    g_free(*list);
                    list++;
                }
                g_free(list_head);
                return 0;
            }
            for (j = 0, i = 0, len = strlen(optarg); i < len; i++) {
                if (optarg[i] == ',') {
                    optarg[i] = 0;
750
                    blacklist = g_list_append(blacklist, &optarg[j]);
751 752 753 754
                    j = i + 1;
                }
            }
            if (j < i) {
755
                blacklist = g_list_append(blacklist, &optarg[j]);
756 757 758
            }
            break;
        }
759 760 761 762
#ifdef _WIN32
        case 's':
            service = optarg;
            if (strcmp(service, "install") == 0) {
763
                return ga_install_service(path, log_filepath);
764 765 766 767 768 769 770 771
            } else if (strcmp(service, "uninstall") == 0) {
                return ga_uninstall_service();
            } else {
                printf("Unknown service command.\n");
                return EXIT_FAILURE;
            }
            break;
#endif
M
Michael Roth 已提交
772 773 774 775 776 777 778 779 780 781
        case 'h':
            usage(argv[0]);
            return 0;
        case '?':
            g_print("Unknown option, try '%s --help' for more information.\n",
                    argv[0]);
            return EXIT_FAILURE;
        }
    }

782
    s = g_malloc0(sizeof(GAState));
M
Michael Roth 已提交
783
    s->log_level = log_level;
784
    s->log_file = stderr;
M
Michael Roth 已提交
785 786
    g_log_set_default_handler(ga_log, s);
    g_log_set_fatal_mask(NULL, G_LOG_LEVEL_ERROR);
787 788 789
    ga_enable_logging(s);
    s->state_filepath_isfrozen = g_strdup_printf("%s/qga.state.isfrozen",
                                                 state_dir);
790
    s->frozen = false;
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
#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);
        s->frozen = true;
    }
#endif

    if (ga_is_frozen(s)) {
        if (daemonize) {
            /* delay opening/locking of pidfile till filesystem are unfrozen */
            s->deferred_options.pid_filepath = pid_filepath;
            become_daemon(NULL);
        }
        if (log_filepath) {
            /* delay opening the log file till filesystems are unfrozen */
            s->deferred_options.log_filepath = log_filepath;
        }
        ga_disable_logging(s);
        ga_disable_non_whitelisted();
    } else {
        if (daemonize) {
            become_daemon(pid_filepath);
        }
        if (log_filepath) {
            s->log_file = fopen(log_filepath, "a");
            if (!s->log_file) {
                g_critical("unable to open specified log file: %s",
                           strerror(errno));
                goto out_bad;
            }
        }
    }

846 847 848 849 850 851 852 853
    if (blacklist) {
        s->blacklist = blacklist;
        do {
            g_debug("disabling command: %s", (char *)blacklist->data);
            qmp_disable_command(blacklist->data);
            blacklist = g_list_next(blacklist);
        } while (blacklist);
    }
854 855 856
    s->command_state = ga_command_state_new();
    ga_command_state_init(s, s->command_state);
    ga_command_state_init_all(s->command_state);
857
    json_message_parser_init(&s->parser, process_event);
M
Michael Roth 已提交
858
    ga_state = s;
859
#ifndef _WIN32
860 861 862 863
    if (!register_signal_handlers()) {
        g_critical("failed to register signal handlers");
        goto out_bad;
    }
864
#endif
M
Michael Roth 已提交
865

866 867 868 869 870
    s->main_loop = g_main_loop_new(NULL, false);
    if (!channel_init(ga_state, method, path)) {
        g_critical("failed to initialize guest agent channel");
        goto out_bad;
    }
871
#ifndef _WIN32
M
Michael Roth 已提交
872
    g_main_loop_run(ga_state->main_loop);
873 874 875 876 877 878 879 880 881
#else
    if (daemonize) {
        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 已提交
882

883
    ga_command_state_cleanup_all(ga_state->command_state);
884
    ga_channel_free(ga_state->channel);
M
Michael Roth 已提交
885

886
    if (daemonize) {
887
        unlink(pid_filepath);
888
    }
M
Michael Roth 已提交
889
    return 0;
890 891 892

out_bad:
    if (daemonize) {
893
        unlink(pid_filepath);
894 895
    }
    return EXIT_FAILURE;
M
Michael Roth 已提交
896
}