commands-posix.c 34.7 KB
Newer Older
1
/*
2
 * QEMU Guest Agent POSIX-specific command implementations
3 4 5 6 7
 *
 * Copyright IBM Corp. 2011
 *
 * Authors:
 *  Michael Roth      <mdroth@linux.vnet.ibm.com>
8
 *  Michal Privoznik  <mprivozn@redhat.com>
9 10 11 12 13 14
 *
 * 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 <glib.h>
15 16
#include <sys/types.h>
#include <sys/ioctl.h>
17
#include <sys/wait.h>
18 19 20 21
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
22 23
#include "qga/guest-agent-core.h"
#include "qga-qmp-commands.h"
24
#include "qapi/qmp/qerror.h"
25 26
#include "qemu/queue.h"
#include "qemu/host-utils.h"
27

28
#ifndef CONFIG_HAS_ENVIRON
29 30 31 32
#ifdef __APPLE__
#include <crt_externs.h>
#define environ (*_NSGetEnviron())
#else
33 34
extern char **environ;
#endif
35
#endif
36

37
#if defined(__linux__)
38
#include <mntent.h>
39
#include <linux/fs.h>
40 41 42 43
#include <ifaddrs.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <net/if.h>
44

45
#ifdef FIFREEZE
46 47
#define CONFIG_FSFREEZE
#endif
48 49 50
#ifdef FITRIM
#define CONFIG_FSTRIM
#endif
51 52
#endif

53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
static void ga_wait_child(pid_t pid, int *status, Error **err)
{
    pid_t rpid;

    *status = 0;

    do {
        rpid = waitpid(pid, status, 0);
    } while (rpid == -1 && errno == EINTR);

    if (rpid == -1) {
        error_setg_errno(err, errno, "failed to wait for child (pid: %d)", pid);
        return;
    }

    g_assert(rpid == pid);
}

71 72 73
void qmp_guest_shutdown(bool has_mode, const char *mode, Error **err)
{
    const char *shutdown_flag;
74 75
    Error *local_err = NULL;
    pid_t pid;
76
    int status;
77 78 79 80 81 82 83 84 85

    slog("guest-shutdown called, mode: %s", mode);
    if (!has_mode || strcmp(mode, "powerdown") == 0) {
        shutdown_flag = "-P";
    } else if (strcmp(mode, "halt") == 0) {
        shutdown_flag = "-H";
    } else if (strcmp(mode, "reboot") == 0) {
        shutdown_flag = "-r";
    } else {
86 87
        error_setg(err,
                   "mode is invalid (valid values are: halt|powerdown|reboot");
88 89 90
        return;
    }

91 92
    pid = fork();
    if (pid == 0) {
93 94
        /* child, start the shutdown */
        setsid();
95 96 97
        reopen_fd_to_null(0);
        reopen_fd_to_null(1);
        reopen_fd_to_null(2);
98

99 100 101
        execle("/sbin/shutdown", "shutdown", shutdown_flag, "+0",
               "hypervisor initiated shutdown", (char*)NULL, environ);
        _exit(EXIT_FAILURE);
102
    } else if (pid < 0) {
103 104
        error_setg_errno(err, errno, "failed to create child process");
        return;
105
    }
106

107 108 109 110 111 112 113 114 115 116 117 118 119
    ga_wait_child(pid, &status, &local_err);
    if (error_is_set(&local_err)) {
        error_propagate(err, local_err);
        return;
    }

    if (!WIFEXITED(status)) {
        error_setg(err, "child process has terminated abnormally");
        return;
    }

    if (WEXITSTATUS(status)) {
        error_setg(err, "child process has failed to shutdown");
120 121 122
        return;
    }

P
Peter Maydell 已提交
123
    /* succeeded */
124 125
}

L
Lei Li 已提交
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
int64_t qmp_guest_get_time(Error **errp)
{
   int ret;
   qemu_timeval tq;
   int64_t time_ns;

   ret = qemu_gettimeofday(&tq);
   if (ret < 0) {
       error_setg_errno(errp, errno, "Failed to get time");
       return -1;
   }

   time_ns = tq.tv_sec * 1000000000LL + tq.tv_usec * 1000;
   return time_ns;
}

L
Lei Li 已提交
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 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
void qmp_guest_set_time(int64_t time_ns, Error **errp)
{
    int ret;
    int status;
    pid_t pid;
    Error *local_err = NULL;
    struct timeval tv;

    /* year-2038 will overflow in case time_t is 32bit */
    if (time_ns / 1000000000 != (time_t)(time_ns / 1000000000)) {
        error_setg(errp, "Time %" PRId64 " is too large", time_ns);
        return;
    }

    tv.tv_sec = time_ns / 1000000000;
    tv.tv_usec = (time_ns % 1000000000) / 1000;

    ret = settimeofday(&tv, NULL);
    if (ret < 0) {
        error_setg_errno(errp, errno, "Failed to set time to guest");
        return;
    }

    /* Set the Hardware Clock to the current System Time. */
    pid = fork();
    if (pid == 0) {
        setsid();
        reopen_fd_to_null(0);
        reopen_fd_to_null(1);
        reopen_fd_to_null(2);

        execle("/sbin/hwclock", "hwclock", "-w", NULL, environ);
        _exit(EXIT_FAILURE);
    } else if (pid < 0) {
        error_setg_errno(errp, errno, "failed to create child process");
        return;
    }

    ga_wait_child(pid, &status, &local_err);
    if (error_is_set(&local_err)) {
        error_propagate(errp, local_err);
        return;
    }

    if (!WIFEXITED(status)) {
        error_setg(errp, "child process has terminated abnormally");
        return;
    }

    if (WEXITSTATUS(status)) {
        error_setg(errp, "hwclock failed to set hardware clock to system time");
        return;
    }
}

197 198 199 200 201 202 203 204 205 206
typedef struct GuestFileHandle {
    uint64_t id;
    FILE *fh;
    QTAILQ_ENTRY(GuestFileHandle) next;
} GuestFileHandle;

static struct {
    QTAILQ_HEAD(, GuestFileHandle) filehandles;
} guest_file_state;

207
static int64_t guest_file_handle_add(FILE *fh, Error **errp)
208 209
{
    GuestFileHandle *gfh;
210 211 212 213 214 215
    int64_t handle;

    handle = ga_get_fd_handle(ga_state, errp);
    if (error_is_set(errp)) {
        return 0;
    }
216

217
    gfh = g_malloc0(sizeof(GuestFileHandle));
218
    gfh->id = handle;
219 220
    gfh->fh = fh;
    QTAILQ_INSERT_TAIL(&guest_file_state.filehandles, gfh, next);
221 222

    return handle;
223 224
}

225
static GuestFileHandle *guest_file_handle_find(int64_t id, Error **err)
226 227 228 229 230 231 232 233 234 235
{
    GuestFileHandle *gfh;

    QTAILQ_FOREACH(gfh, &guest_file_state.filehandles, next)
    {
        if (gfh->id == id) {
            return gfh;
        }
    }

236
    error_setg(err, "handle '%" PRId64 "' has not been found", id);
237 238 239 240 241 242 243
    return NULL;
}

int64_t qmp_guest_file_open(const char *path, bool has_mode, const char *mode, Error **err)
{
    FILE *fh;
    int fd;
244
    int64_t ret = -1, handle;
245 246 247 248 249 250 251

    if (!has_mode) {
        mode = "r";
    }
    slog("guest-file-open called, filepath: %s, mode: %s", path, mode);
    fh = fopen(path, mode);
    if (!fh) {
252 253
        error_setg_errno(err, errno, "failed to open file '%s' (mode: '%s')",
                         path, mode);
254 255 256 257 258 259 260 261 262 263
        return -1;
    }

    /* set fd non-blocking to avoid common use cases (like reading from a
     * named pipe) from hanging the agent
     */
    fd = fileno(fh);
    ret = fcntl(fd, F_GETFL);
    ret = fcntl(fd, F_SETFL, ret | O_NONBLOCK);
    if (ret == -1) {
264 265
        error_setg_errno(err, errno, "failed to make file '%s' non-blocking",
                         path);
266 267 268 269
        fclose(fh);
        return -1;
    }

270 271 272 273 274 275 276 277
    handle = guest_file_handle_add(fh, err);
    if (error_is_set(err)) {
        fclose(fh);
        return -1;
    }

    slog("guest-file-open, handle: %d", handle);
    return handle;
278 279 280 281
}

void qmp_guest_file_close(int64_t handle, Error **err)
{
282
    GuestFileHandle *gfh = guest_file_handle_find(handle, err);
283 284 285 286 287 288 289 290
    int ret;

    slog("guest-file-close called, handle: %ld", handle);
    if (!gfh) {
        return;
    }

    ret = fclose(gfh->fh);
291
    if (ret == EOF) {
292
        error_setg_errno(err, errno, "failed to close handle");
293 294 295 296
        return;
    }

    QTAILQ_REMOVE(&guest_file_state.filehandles, gfh, next);
297
    g_free(gfh);
298 299 300 301 302
}

struct GuestFileRead *qmp_guest_file_read(int64_t handle, bool has_count,
                                          int64_t count, Error **err)
{
303
    GuestFileHandle *gfh = guest_file_handle_find(handle, err);
304 305 306 307 308 309 310 311 312 313 314 315
    GuestFileRead *read_data = NULL;
    guchar *buf;
    FILE *fh;
    size_t read_count;

    if (!gfh) {
        return NULL;
    }

    if (!has_count) {
        count = QGA_READ_COUNT_DEFAULT;
    } else if (count < 0) {
316 317
        error_setg(err, "value '%" PRId64 "' is invalid for argument count",
                   count);
318 319 320 321
        return NULL;
    }

    fh = gfh->fh;
322
    buf = g_malloc0(count+1);
323 324
    read_count = fread(buf, 1, count, fh);
    if (ferror(fh)) {
325
        error_setg_errno(err, errno, "failed to read file");
326 327 328
        slog("guest-file-read failed, handle: %ld", handle);
    } else {
        buf[read_count] = 0;
329
        read_data = g_malloc0(sizeof(GuestFileRead));
330 331 332 333 334 335
        read_data->count = read_count;
        read_data->eof = feof(fh);
        if (read_count) {
            read_data->buf_b64 = g_base64_encode(buf, read_count);
        }
    }
336
    g_free(buf);
337 338 339 340 341 342 343 344 345 346 347 348
    clearerr(fh);

    return read_data;
}

GuestFileWrite *qmp_guest_file_write(int64_t handle, const char *buf_b64,
                                     bool has_count, int64_t count, Error **err)
{
    GuestFileWrite *write_data = NULL;
    guchar *buf;
    gsize buf_len;
    int write_count;
349
    GuestFileHandle *gfh = guest_file_handle_find(handle, err);
350 351 352 353 354 355 356 357 358 359 360 361
    FILE *fh;

    if (!gfh) {
        return NULL;
    }

    fh = gfh->fh;
    buf = g_base64_decode(buf_b64, &buf_len);

    if (!has_count) {
        count = buf_len;
    } else if (count < 0 || count > buf_len) {
362 363
        error_setg(err, "value '%" PRId64 "' is invalid for argument count",
                   count);
364
        g_free(buf);
365 366 367 368 369
        return NULL;
    }

    write_count = fwrite(buf, 1, count, fh);
    if (ferror(fh)) {
370
        error_setg_errno(err, errno, "failed to write to file");
371 372
        slog("guest-file-write failed, handle: %ld", handle);
    } else {
373
        write_data = g_malloc0(sizeof(GuestFileWrite));
374 375 376
        write_data->count = write_count;
        write_data->eof = feof(fh);
    }
377
    g_free(buf);
378 379 380 381 382 383 384 385
    clearerr(fh);

    return write_data;
}

struct GuestFileSeek *qmp_guest_file_seek(int64_t handle, int64_t offset,
                                          int64_t whence, Error **err)
{
386
    GuestFileHandle *gfh = guest_file_handle_find(handle, err);
387 388 389 390 391 392 393 394 395 396 397
    GuestFileSeek *seek_data = NULL;
    FILE *fh;
    int ret;

    if (!gfh) {
        return NULL;
    }

    fh = gfh->fh;
    ret = fseek(fh, offset, whence);
    if (ret == -1) {
398
        error_setg_errno(err, errno, "failed to seek file");
399
    } else {
400
        seek_data = g_malloc0(sizeof(GuestFileRead));
401 402 403 404 405 406 407 408 409 410
        seek_data->position = ftell(fh);
        seek_data->eof = feof(fh);
    }
    clearerr(fh);

    return seek_data;
}

void qmp_guest_file_flush(int64_t handle, Error **err)
{
411
    GuestFileHandle *gfh = guest_file_handle_find(handle, err);
412 413 414 415 416 417 418 419 420 421
    FILE *fh;
    int ret;

    if (!gfh) {
        return;
    }

    fh = gfh->fh;
    ret = fflush(fh);
    if (ret == EOF) {
422
        error_setg_errno(err, errno, "failed to flush file");
423 424 425 426 427 428 429 430
    }
}

static void guest_file_init(void)
{
    QTAILQ_INIT(&guest_file_state.filehandles);
}

431 432 433
/* linux-specific implementations. avoid this if at all possible. */
#if defined(__linux__)

434
#if defined(CONFIG_FSFREEZE) || defined(CONFIG_FSTRIM)
435
typedef struct FsMount {
436 437
    char *dirname;
    char *devtype;
438 439
    QTAILQ_ENTRY(FsMount) next;
} FsMount;
440

441
typedef QTAILQ_HEAD(, FsMount) FsMountList;
442

443
static void free_fs_mount_list(FsMountList *mounts)
444
{
445
     FsMount *mount, *temp;
446 447 448 449 450 451 452 453 454 455 456 457 458

     if (!mounts) {
         return;
     }

     QTAILQ_FOREACH_SAFE(mount, mounts, next, temp) {
         QTAILQ_REMOVE(mounts, mount, next);
         g_free(mount->dirname);
         g_free(mount->devtype);
         g_free(mount);
     }
}

459 460 461
/*
 * Walk the mount table and build a list of local file systems
 */
462
static void build_fs_mount_list(FsMountList *mounts, Error **err)
463 464
{
    struct mntent *ment;
465
    FsMount *mount;
466
    char const *mtab = "/proc/self/mounts";
467 468 469 470
    FILE *fp;

    fp = setmntent(mtab, "r");
    if (!fp) {
471 472
        error_setg(err, "failed to open mtab file: '%s'", mtab);
        return;
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
    }

    while ((ment = getmntent(fp))) {
        /*
         * An entry which device name doesn't start with a '/' is
         * either a dummy file system or a network file system.
         * Add special handling for smbfs and cifs as is done by
         * coreutils as well.
         */
        if ((ment->mnt_fsname[0] != '/') ||
            (strcmp(ment->mnt_type, "smbfs") == 0) ||
            (strcmp(ment->mnt_type, "cifs") == 0)) {
            continue;
        }

488
        mount = g_malloc0(sizeof(FsMount));
489 490
        mount->dirname = g_strdup(ment->mnt_dir);
        mount->devtype = g_strdup(ment->mnt_type);
491

492
        QTAILQ_INSERT_TAIL(mounts, mount, next);
493 494 495 496
    }

    endmntent(fp);
}
497 498 499
#endif

#if defined(CONFIG_FSFREEZE)
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 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560
typedef enum {
    FSFREEZE_HOOK_THAW = 0,
    FSFREEZE_HOOK_FREEZE,
} FsfreezeHookArg;

const char *fsfreeze_hook_arg_string[] = {
    "thaw",
    "freeze",
};

static void execute_fsfreeze_hook(FsfreezeHookArg arg, Error **err)
{
    int status;
    pid_t pid;
    const char *hook;
    const char *arg_str = fsfreeze_hook_arg_string[arg];
    Error *local_err = NULL;

    hook = ga_fsfreeze_hook(ga_state);
    if (!hook) {
        return;
    }
    if (access(hook, X_OK) != 0) {
        error_setg_errno(err, errno, "can't access fsfreeze hook '%s'", hook);
        return;
    }

    slog("executing fsfreeze hook with arg '%s'", arg_str);
    pid = fork();
    if (pid == 0) {
        setsid();
        reopen_fd_to_null(0);
        reopen_fd_to_null(1);
        reopen_fd_to_null(2);

        execle(hook, hook, arg_str, NULL, environ);
        _exit(EXIT_FAILURE);
    } else if (pid < 0) {
        error_setg_errno(err, errno, "failed to create child process");
        return;
    }

    ga_wait_child(pid, &status, &local_err);
    if (error_is_set(&local_err)) {
        error_propagate(err, local_err);
        return;
    }

    if (!WIFEXITED(status)) {
        error_setg(err, "fsfreeze hook has terminated abnormally");
        return;
    }

    status = WEXITSTATUS(status);
    if (status) {
        error_setg(err, "fsfreeze hook has failed with status %d", status);
        return;
    }
}

561 562 563 564 565
/*
 * Return status of freeze/thaw
 */
GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **err)
{
566 567 568 569 570
    if (ga_is_frozen(ga_state)) {
        return GUEST_FSFREEZE_STATUS_FROZEN;
    }

    return GUEST_FSFREEZE_STATUS_THAWED;
571 572 573 574 575 576 577 578 579
}

/*
 * Walk list of mounted file systems in the guest, and freeze the ones which
 * are real local file systems.
 */
int64_t qmp_guest_fsfreeze_freeze(Error **err)
{
    int ret = 0, i = 0;
580 581
    FsMountList mounts;
    struct FsMount *mount;
582
    Error *local_err = NULL;
583 584 585 586
    int fd;

    slog("guest-fsfreeze called");

587 588 589 590 591 592
    execute_fsfreeze_hook(FSFREEZE_HOOK_FREEZE, &local_err);
    if (error_is_set(&local_err)) {
        error_propagate(err, local_err);
        return -1;
    }

593
    QTAILQ_INIT(&mounts);
594 595 596 597
    build_fs_mount_list(&mounts, &local_err);
    if (error_is_set(&local_err)) {
        error_propagate(err, local_err);
        return -1;
598 599 600
    }

    /* cannot risk guest agent blocking itself on a write in this state */
601
    ga_set_frozen(ga_state);
602

603
    QTAILQ_FOREACH(mount, &mounts, next) {
604 605
        fd = qemu_open(mount->dirname, O_RDONLY);
        if (fd == -1) {
606
            error_setg_errno(err, errno, "failed to open %s", mount->dirname);
607 608 609 610 611
            goto error;
        }

        /* we try to cull filesytems we know won't work in advance, but other
         * filesytems may not implement fsfreeze for less obvious reasons.
612 613 614 615 616 617
         * these will report EOPNOTSUPP. we simply ignore these when tallying
         * the number of frozen filesystems.
         *
         * any other error means a failure to freeze a filesystem we
         * expect to be freezable, so return an error in those cases
         * and return system to thawed state.
618 619
         */
        ret = ioctl(fd, FIFREEZE);
620 621
        if (ret == -1) {
            if (errno != EOPNOTSUPP) {
622 623
                error_setg_errno(err, errno, "failed to freeze %s",
                                 mount->dirname);
624 625 626 627 628
                close(fd);
                goto error;
            }
        } else {
            i++;
629 630 631 632
        }
        close(fd);
    }

633
    free_fs_mount_list(&mounts);
634 635 636
    return i;

error:
637
    free_fs_mount_list(&mounts);
638
    qmp_guest_fsfreeze_thaw(NULL);
639 640 641 642 643 644 645 646 647
    return 0;
}

/*
 * Walk list of frozen file systems in the guest, and thaw them.
 */
int64_t qmp_guest_fsfreeze_thaw(Error **err)
{
    int ret;
648 649
    FsMountList mounts;
    FsMount *mount;
650
    int fd, i = 0, logged;
651
    Error *local_err = NULL;
652 653

    QTAILQ_INIT(&mounts);
654 655 656
    build_fs_mount_list(&mounts, &local_err);
    if (error_is_set(&local_err)) {
        error_propagate(err, local_err);
657 658
        return 0;
    }
659

660 661
    QTAILQ_FOREACH(mount, &mounts, next) {
        logged = false;
662 663 664 665
        fd = qemu_open(mount->dirname, O_RDONLY);
        if (fd == -1) {
            continue;
        }
666 667 668 669 670
        /* we have no way of knowing whether a filesystem was actually unfrozen
         * as a result of a successful call to FITHAW, only that if an error
         * was returned the filesystem was *not* unfrozen by that particular
         * call.
         *
J
Jim Meyering 已提交
671
         * since multiple preceding FIFREEZEs require multiple calls to FITHAW
672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688
         * to unfreeze, continuing issuing FITHAW until an error is returned,
         * in which case either the filesystem is in an unfreezable state, or,
         * more likely, it was thawed previously (and remains so afterward).
         *
         * also, since the most recent successful call is the one that did
         * the actual unfreeze, we can use this to provide an accurate count
         * of the number of filesystems unfrozen by guest-fsfreeze-thaw, which
         * may * be useful for determining whether a filesystem was unfrozen
         * during the freeze/thaw phase by a process other than qemu-ga.
         */
        do {
            ret = ioctl(fd, FITHAW);
            if (ret == 0 && !logged) {
                i++;
                logged = true;
            }
        } while (ret == 0);
689 690 691
        close(fd);
    }

692
    ga_unset_frozen(ga_state);
693
    free_fs_mount_list(&mounts);
694 695 696

    execute_fsfreeze_hook(FSFREEZE_HOOK_THAW, err);

697 698 699 700 701 702 703
    return i;
}

static void guest_fsfreeze_cleanup(void)
{
    Error *err = NULL;

704
    if (ga_is_frozen(ga_state) == GUEST_FSFREEZE_STATUS_FROZEN) {
705 706 707 708 709
        qmp_guest_fsfreeze_thaw(&err);
        if (err) {
            slog("failed to clean up frozen filesystems: %s",
                 error_get_pretty(err));
            error_free(err);
710 711 712
        }
    }
}
713
#endif /* CONFIG_FSFREEZE */
714

715 716 717 718 719 720 721 722 723 724
#if defined(CONFIG_FSTRIM)
/*
 * Walk list of mounted file systems in the guest, and trim them.
 */
void qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **err)
{
    int ret = 0;
    FsMountList mounts;
    struct FsMount *mount;
    int fd;
725
    Error *local_err = NULL;
726 727 728 729 730 731 732 733 734
    struct fstrim_range r = {
        .start = 0,
        .len = -1,
        .minlen = has_minimum ? minimum : 0,
    };

    slog("guest-fstrim called");

    QTAILQ_INIT(&mounts);
735 736 737
    build_fs_mount_list(&mounts, &local_err);
    if (error_is_set(&local_err)) {
        error_propagate(err, local_err);
738 739 740 741 742 743
        return;
    }

    QTAILQ_FOREACH(mount, &mounts, next) {
        fd = qemu_open(mount->dirname, O_RDONLY);
        if (fd == -1) {
744
            error_setg_errno(err, errno, "failed to open %s", mount->dirname);
745 746 747 748 749 750 751 752 753 754 755 756
            goto error;
        }

        /* We try to cull filesytems we know won't work in advance, but other
         * filesytems may not implement fstrim for less obvious reasons.  These
         * will report EOPNOTSUPP; we simply ignore these errors.  Any other
         * error means an unexpected error, so return it in those cases.  In
         * some other cases ENOTTY will be reported (e.g. CD-ROMs).
         */
        ret = ioctl(fd, FITRIM, &r);
        if (ret == -1) {
            if (errno != ENOTTY && errno != EOPNOTSUPP) {
757 758
                error_setg_errno(err, errno, "failed to trim %s",
                                 mount->dirname);
759 760 761 762 763 764 765 766 767 768 769 770 771
                close(fd);
                goto error;
            }
        }
        close(fd);
    }

error:
    free_fs_mount_list(&mounts);
}
#endif /* CONFIG_FSTRIM */


772 773 774 775 776 777 778
#define LINUX_SYS_STATE_FILE "/sys/power/state"
#define SUSPEND_SUPPORTED 0
#define SUSPEND_NOT_SUPPORTED 1

static void bios_supports_mode(const char *pmutils_bin, const char *pmutils_arg,
                               const char *sysfile_str, Error **err)
{
779
    Error *local_err = NULL;
780
    char *pmutils_path;
781
    pid_t pid;
782
    int status;
783 784 785 786 787

    pmutils_path = g_find_program_in_path(pmutils_bin);

    pid = fork();
    if (!pid) {
788 789 790
        char buf[32]; /* hopefully big enough */
        ssize_t ret;
        int fd;
791 792 793 794 795 796

        setsid();
        reopen_fd_to_null(0);
        reopen_fd_to_null(1);
        reopen_fd_to_null(2);

797 798 799
        if (pmutils_path) {
            execle(pmutils_path, pmutils_bin, pmutils_arg, NULL, environ);
        }
800

801 802 803 804
        /*
         * If we get here either pm-utils is not installed or execle() has
         * failed. Let's try the manual method if the caller wants it.
         */
805

806 807 808
        if (!sysfile_str) {
            _exit(SUSPEND_NOT_SUPPORTED);
        }
809

810 811
        fd = open(LINUX_SYS_STATE_FILE, O_RDONLY);
        if (fd < 0) {
812 813 814
            _exit(SUSPEND_NOT_SUPPORTED);
        }

815 816 817
        ret = read(fd, buf, sizeof(buf)-1);
        if (ret <= 0) {
            _exit(SUSPEND_NOT_SUPPORTED);
818
        }
819
        buf[ret] = '\0';
820

821 822
        if (strstr(buf, sysfile_str)) {
            _exit(SUSPEND_SUPPORTED);
823 824
        }

825
        _exit(SUSPEND_NOT_SUPPORTED);
826 827 828
    } else if (pid < 0) {
        error_setg_errno(err, errno, "failed to create child process");
        goto out;
829 830
    }

831 832 833 834 835
    ga_wait_child(pid, &status, &local_err);
    if (error_is_set(&local_err)) {
        error_propagate(err, local_err);
        goto out;
    }
836

837 838 839
    if (!WIFEXITED(status)) {
        error_setg(err, "child process has terminated abnormally");
        goto out;
840 841
    }

842 843 844 845 846 847 848 849 850 851 852 853
    switch (WEXITSTATUS(status)) {
    case SUSPEND_SUPPORTED:
        goto out;
    case SUSPEND_NOT_SUPPORTED:
        error_setg(err,
                   "the requested suspend mode is not supported by the guest");
        goto out;
    default:
        error_setg(err,
                   "the helper program '%s' returned an unexpected exit status"
                   " code (%d)", pmutils_path, WEXITSTATUS(status));
        goto out;
854 855
    }

856 857
out:
    g_free(pmutils_path);
858 859 860 861 862
}

static void guest_suspend(const char *pmutils_bin, const char *sysfile_str,
                          Error **err)
{
863
    Error *local_err = NULL;
864
    char *pmutils_path;
865
    pid_t pid;
866
    int status;
867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902

    pmutils_path = g_find_program_in_path(pmutils_bin);

    pid = fork();
    if (pid == 0) {
        /* child */
        int fd;

        setsid();
        reopen_fd_to_null(0);
        reopen_fd_to_null(1);
        reopen_fd_to_null(2);

        if (pmutils_path) {
            execle(pmutils_path, pmutils_bin, NULL, environ);
        }

        /*
         * If we get here either pm-utils is not installed or execle() has
         * failed. Let's try the manual method if the caller wants it.
         */

        if (!sysfile_str) {
            _exit(EXIT_FAILURE);
        }

        fd = open(LINUX_SYS_STATE_FILE, O_WRONLY);
        if (fd < 0) {
            _exit(EXIT_FAILURE);
        }

        if (write(fd, sysfile_str, strlen(sysfile_str)) < 0) {
            _exit(EXIT_FAILURE);
        }

        _exit(EXIT_SUCCESS);
903 904 905
    } else if (pid < 0) {
        error_setg_errno(err, errno, "failed to create child process");
        goto out;
906 907
    }

908 909 910 911 912
    ga_wait_child(pid, &status, &local_err);
    if (error_is_set(&local_err)) {
        error_propagate(err, local_err);
        goto out;
    }
913

914 915 916
    if (!WIFEXITED(status)) {
        error_setg(err, "child process has terminated abnormally");
        goto out;
917 918
    }

919 920 921
    if (WEXITSTATUS(status)) {
        error_setg(err, "child process has failed to suspend");
        goto out;
922
    }
923

924 925
out:
    g_free(pmutils_path);
926 927 928 929 930 931 932 933 934 935 936 937
}

void qmp_guest_suspend_disk(Error **err)
{
    bios_supports_mode("pm-is-supported", "--hibernate", "disk", err);
    if (error_is_set(err)) {
        return;
    }

    guest_suspend("pm-hibernate", "disk", err);
}

L
Luiz Capitulino 已提交
938 939 940 941 942 943 944 945 946 947
void qmp_guest_suspend_ram(Error **err)
{
    bios_supports_mode("pm-is-supported", "--suspend", "mem", err);
    if (error_is_set(err)) {
        return;
    }

    guest_suspend("pm-suspend", "mem", err);
}

948 949 950 951 952 953 954 955 956 957
void qmp_guest_suspend_hybrid(Error **err)
{
    bios_supports_mode("pm-is-supported", "--suspend-hybrid", NULL, err);
    if (error_is_set(err)) {
        return;
    }

    guest_suspend("pm-suspend-hybrid", NULL, err);
}

958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979
static GuestNetworkInterfaceList *
guest_find_interface(GuestNetworkInterfaceList *head,
                     const char *name)
{
    for (; head; head = head->next) {
        if (strcmp(head->value->name, name) == 0) {
            break;
        }
    }

    return head;
}

/*
 * Build information about guest interfaces
 */
GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
{
    GuestNetworkInterfaceList *head = NULL, *cur_item = NULL;
    struct ifaddrs *ifap, *ifa;

    if (getifaddrs(&ifap) < 0) {
980
        error_setg_errno(errp, errno, "getifaddrs failed");
981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
        goto error;
    }

    for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
        GuestNetworkInterfaceList *info;
        GuestIpAddressList **address_list = NULL, *address_item = NULL;
        char addr4[INET_ADDRSTRLEN];
        char addr6[INET6_ADDRSTRLEN];
        int sock;
        struct ifreq ifr;
        unsigned char *mac_addr;
        void *p;

        g_debug("Processing %s interface", ifa->ifa_name);

        info = guest_find_interface(head, ifa->ifa_name);

        if (!info) {
            info = g_malloc0(sizeof(*info));
            info->value = g_malloc0(sizeof(*info->value));
            info->value->name = g_strdup(ifa->ifa_name);

            if (!cur_item) {
                head = cur_item = info;
            } else {
                cur_item->next = info;
                cur_item = info;
            }
        }

        if (!info->value->has_hardware_address &&
            ifa->ifa_flags & SIOCGIFHWADDR) {
            /* we haven't obtained HW address yet */
            sock = socket(PF_INET, SOCK_STREAM, 0);
            if (sock == -1) {
1016
                error_setg_errno(errp, errno, "failed to create socket");
1017 1018 1019 1020
                goto error;
            }

            memset(&ifr, 0, sizeof(ifr));
1021
            pstrcpy(ifr.ifr_name, IF_NAMESIZE, info->value->name);
1022
            if (ioctl(sock, SIOCGIFHWADDR, &ifr) == -1) {
1023 1024 1025
                error_setg_errno(errp, errno,
                                 "failed to get MAC address of %s",
                                 ifa->ifa_name);
1026
                close(sock);
1027 1028 1029
                goto error;
            }

1030
            close(sock);
1031 1032
            mac_addr = (unsigned char *) &ifr.ifr_hwaddr.sa_data;

1033 1034 1035 1036 1037
            info->value->hardware_address =
                g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
                                (int) mac_addr[0], (int) mac_addr[1],
                                (int) mac_addr[2], (int) mac_addr[3],
                                (int) mac_addr[4], (int) mac_addr[5]);
1038 1039 1040 1041 1042 1043 1044 1045 1046

            info->value->has_hardware_address = true;
        }

        if (ifa->ifa_addr &&
            ifa->ifa_addr->sa_family == AF_INET) {
            /* interface with IPv4 address */
            p = &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
            if (!inet_ntop(AF_INET, p, addr4, sizeof(addr4))) {
1047
                error_setg_errno(errp, errno, "inet_ntop failed");
1048 1049 1050
                goto error;
            }

1051 1052
            address_item = g_malloc0(sizeof(*address_item));
            address_item->value = g_malloc0(sizeof(*address_item->value));
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
            address_item->value->ip_address = g_strdup(addr4);
            address_item->value->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV4;

            if (ifa->ifa_netmask) {
                /* Count the number of set bits in netmask.
                 * This is safe as '1' and '0' cannot be shuffled in netmask. */
                p = &((struct sockaddr_in *)ifa->ifa_netmask)->sin_addr;
                address_item->value->prefix = ctpop32(((uint32_t *) p)[0]);
            }
        } else if (ifa->ifa_addr &&
                   ifa->ifa_addr->sa_family == AF_INET6) {
            /* interface with IPv6 address */
            p = &((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr;
            if (!inet_ntop(AF_INET6, p, addr6, sizeof(addr6))) {
1067
                error_setg_errno(errp, errno, "inet_ntop failed");
1068 1069 1070
                goto error;
            }

1071 1072
            address_item = g_malloc0(sizeof(*address_item));
            address_item->value = g_malloc0(sizeof(*address_item->value));
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
            address_item->value->ip_address = g_strdup(addr6);
            address_item->value->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV6;

            if (ifa->ifa_netmask) {
                /* Count the number of set bits in netmask.
                 * This is safe as '1' and '0' cannot be shuffled in netmask. */
                p = &((struct sockaddr_in6 *)ifa->ifa_netmask)->sin6_addr;
                address_item->value->prefix =
                    ctpop32(((uint32_t *) p)[0]) +
                    ctpop32(((uint32_t *) p)[1]) +
                    ctpop32(((uint32_t *) p)[2]) +
                    ctpop32(((uint32_t *) p)[3]);
            }
        }

        if (!address_item) {
            continue;
        }

        address_list = &info->value->ip_addresses;

        while (*address_list && (*address_list)->next) {
            address_list = &(*address_list)->next;
        }

        if (!*address_list) {
            *address_list = address_item;
        } else {
            (*address_list)->next = address_item;
        }

        info->value->has_ip_addresses = true;


    }

    freeifaddrs(ifap);
    return head;

error:
    freeifaddrs(ifap);
    qapi_free_GuestNetworkInterfaceList(head);
    return NULL;
}

1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 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 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 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
#define SYSCONF_EXACT(name, err) sysconf_exact((name), #name, (err))

static long sysconf_exact(int name, const char *name_str, Error **err)
{
    long ret;

    errno = 0;
    ret = sysconf(name);
    if (ret == -1) {
        if (errno == 0) {
            error_setg(err, "sysconf(%s): value indefinite", name_str);
        } else {
            error_setg_errno(err, errno, "sysconf(%s)", name_str);
        }
    }
    return ret;
}

/* Transfer online/offline status between @vcpu and the guest system.
 *
 * On input either @errp or *@errp must be NULL.
 *
 * In system-to-@vcpu direction, the following @vcpu fields are accessed:
 * - R: vcpu->logical_id
 * - W: vcpu->online
 * - W: vcpu->can_offline
 *
 * In @vcpu-to-system direction, the following @vcpu fields are accessed:
 * - R: vcpu->logical_id
 * - R: vcpu->online
 *
 * Written members remain unmodified on error.
 */
static void transfer_vcpu(GuestLogicalProcessor *vcpu, bool sys2vcpu,
                          Error **errp)
{
    char *dirpath;
    int dirfd;

    dirpath = g_strdup_printf("/sys/devices/system/cpu/cpu%" PRId64 "/",
                              vcpu->logical_id);
    dirfd = open(dirpath, O_RDONLY | O_DIRECTORY);
    if (dirfd == -1) {
        error_setg_errno(errp, errno, "open(\"%s\")", dirpath);
    } else {
        static const char fn[] = "online";
        int fd;
        int res;

        fd = openat(dirfd, fn, sys2vcpu ? O_RDONLY : O_RDWR);
        if (fd == -1) {
            if (errno != ENOENT) {
                error_setg_errno(errp, errno, "open(\"%s/%s\")", dirpath, fn);
            } else if (sys2vcpu) {
                vcpu->online = true;
                vcpu->can_offline = false;
            } else if (!vcpu->online) {
                error_setg(errp, "logical processor #%" PRId64 " can't be "
                           "offlined", vcpu->logical_id);
            } /* otherwise pretend successful re-onlining */
        } else {
            unsigned char status;

            res = pread(fd, &status, 1, 0);
            if (res == -1) {
                error_setg_errno(errp, errno, "pread(\"%s/%s\")", dirpath, fn);
            } else if (res == 0) {
                error_setg(errp, "pread(\"%s/%s\"): unexpected EOF", dirpath,
                           fn);
            } else if (sys2vcpu) {
                vcpu->online = (status != '0');
                vcpu->can_offline = true;
            } else if (vcpu->online != (status != '0')) {
                status = '0' + vcpu->online;
                if (pwrite(fd, &status, 1, 0) == -1) {
                    error_setg_errno(errp, errno, "pwrite(\"%s/%s\")", dirpath,
                                     fn);
                }
            } /* otherwise pretend successful re-(on|off)-lining */

            res = close(fd);
            g_assert(res == 0);
        }

        res = close(dirfd);
        g_assert(res == 0);
    }

    g_free(dirpath);
}

GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp)
{
    int64_t current;
    GuestLogicalProcessorList *head, **link;
    long sc_max;
    Error *local_err = NULL;

    current = 0;
    head = NULL;
    link = &head;
    sc_max = SYSCONF_EXACT(_SC_NPROCESSORS_CONF, &local_err);

    while (local_err == NULL && current < sc_max) {
        GuestLogicalProcessor *vcpu;
        GuestLogicalProcessorList *entry;

        vcpu = g_malloc0(sizeof *vcpu);
        vcpu->logical_id = current++;
        vcpu->has_can_offline = true; /* lolspeak ftw */
        transfer_vcpu(vcpu, true, &local_err);

        entry = g_malloc0(sizeof *entry);
        entry->value = vcpu;

        *link = entry;
        link = &entry->next;
    }

    if (local_err == NULL) {
        /* there's no guest with zero VCPUs */
        g_assert(head != NULL);
        return head;
    }

    qapi_free_GuestLogicalProcessorList(head);
    error_propagate(errp, local_err);
    return NULL;
}

1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273
int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList *vcpus, Error **errp)
{
    int64_t processed;
    Error *local_err = NULL;

    processed = 0;
    while (vcpus != NULL) {
        transfer_vcpu(vcpus->value, false, &local_err);
        if (local_err != NULL) {
            break;
        }
        ++processed;
        vcpus = vcpus->next;
    }

    if (local_err != NULL) {
        if (processed == 0) {
            error_propagate(errp, local_err);
        } else {
            error_free(local_err);
        }
    }

    return processed;
}

1274 1275
#else /* defined(__linux__) */

1276
void qmp_guest_suspend_disk(Error **err)
1277 1278 1279 1280
{
    error_set(err, QERR_UNSUPPORTED);
}

1281
void qmp_guest_suspend_ram(Error **err)
1282 1283 1284 1285
{
    error_set(err, QERR_UNSUPPORTED);
}

1286
void qmp_guest_suspend_hybrid(Error **err)
1287 1288 1289 1290
{
    error_set(err, QERR_UNSUPPORTED);
}

1291
GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
1292
{
1293 1294
    error_set(errp, QERR_UNSUPPORTED);
    return NULL;
1295 1296
}

1297 1298 1299 1300 1301 1302
GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp)
{
    error_set(errp, QERR_UNSUPPORTED);
    return NULL;
}

1303 1304 1305 1306 1307 1308
int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList *vcpus, Error **errp)
{
    error_set(errp, QERR_UNSUPPORTED);
    return -1;
}

1309 1310 1311 1312 1313
#endif

#if !defined(CONFIG_FSFREEZE)

GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **err)
1314 1315
{
    error_set(err, QERR_UNSUPPORTED);
1316 1317

    return 0;
1318 1319
}

1320
int64_t qmp_guest_fsfreeze_freeze(Error **err)
1321 1322
{
    error_set(err, QERR_UNSUPPORTED);
1323 1324

    return 0;
1325 1326
}

1327
int64_t qmp_guest_fsfreeze_thaw(Error **err)
1328
{
1329 1330 1331
    error_set(err, QERR_UNSUPPORTED);

    return 0;
1332
}
1333 1334 1335 1336 1337 1338 1339
#endif /* CONFIG_FSFREEZE */

#if !defined(CONFIG_FSTRIM)
void qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **err)
{
    error_set(err, QERR_UNSUPPORTED);
}
1340 1341
#endif

1342 1343 1344
/* register init/cleanup routines for stateful command groups */
void ga_command_state_init(GAState *s, GACommandState *cs)
{
1345
#if defined(CONFIG_FSFREEZE)
1346
    ga_command_state_add(cs, NULL, guest_fsfreeze_cleanup);
1347
#endif
1348 1349
    ga_command_state_add(cs, guest_file_init, NULL);
}