commands-posix.c 30.0 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
#include "qga/guest-agent-core.h"
#include "qga-qmp-commands.h"
20
#include "qapi/qmp/qerror.h"
21 22
#include "qemu/queue.h"
#include "qemu/host-utils.h"
23

24
#ifndef CONFIG_HAS_ENVIRON
25 26 27 28
#ifdef __APPLE__
#include <crt_externs.h>
#define environ (*_NSGetEnviron())
#else
29 30
extern char **environ;
#endif
31
#endif
32

33
#if defined(__linux__)
34
#include <mntent.h>
35
#include <linux/fs.h>
36 37 38 39
#include <ifaddrs.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <net/if.h>
40

41
#ifdef FIFREEZE
42 43
#define CONFIG_FSFREEZE
#endif
44 45 46
#ifdef FITRIM
#define CONFIG_FSTRIM
#endif
47 48
#endif

49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
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);
}

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

    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 {
82 83
        error_setg(err,
                   "mode is invalid (valid values are: halt|powerdown|reboot");
84 85 86
        return;
    }

87 88
    pid = fork();
    if (pid == 0) {
89 90
        /* child, start the shutdown */
        setsid();
91 92 93
        reopen_fd_to_null(0);
        reopen_fd_to_null(1);
        reopen_fd_to_null(2);
94

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

103 104 105 106 107 108 109 110 111 112 113 114 115
    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");
116 117 118
        return;
    }

119
    /* succeded */
120 121
}

L
Lei Li 已提交
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
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 已提交
138 139 140 141 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
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;
    }
}

193 194 195 196 197 198 199 200 201 202
typedef struct GuestFileHandle {
    uint64_t id;
    FILE *fh;
    QTAILQ_ENTRY(GuestFileHandle) next;
} GuestFileHandle;

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

203
static int64_t guest_file_handle_add(FILE *fh, Error **errp)
204 205
{
    GuestFileHandle *gfh;
206 207 208 209 210 211
    int64_t handle;

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

213
    gfh = g_malloc0(sizeof(GuestFileHandle));
214
    gfh->id = handle;
215 216
    gfh->fh = fh;
    QTAILQ_INSERT_TAIL(&guest_file_state.filehandles, gfh, next);
217 218

    return handle;
219 220
}

221
static GuestFileHandle *guest_file_handle_find(int64_t id, Error **err)
222 223 224 225 226 227 228 229 230 231
{
    GuestFileHandle *gfh;

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

232
    error_setg(err, "handle '%" PRId64 "' has not been found", id);
233 234 235 236 237 238 239
    return NULL;
}

int64_t qmp_guest_file_open(const char *path, bool has_mode, const char *mode, Error **err)
{
    FILE *fh;
    int fd;
240
    int64_t ret = -1, handle;
241 242 243 244 245 246 247

    if (!has_mode) {
        mode = "r";
    }
    slog("guest-file-open called, filepath: %s, mode: %s", path, mode);
    fh = fopen(path, mode);
    if (!fh) {
248 249
        error_setg_errno(err, errno, "failed to open file '%s' (mode: '%s')",
                         path, mode);
250 251 252 253 254 255 256 257 258 259
        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) {
260 261
        error_setg_errno(err, errno, "failed to make file '%s' non-blocking",
                         path);
262 263 264 265
        fclose(fh);
        return -1;
    }

266 267 268 269 270 271 272 273
    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;
274 275 276 277
}

void qmp_guest_file_close(int64_t handle, Error **err)
{
278
    GuestFileHandle *gfh = guest_file_handle_find(handle, err);
279 280 281 282 283 284 285 286
    int ret;

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

    ret = fclose(gfh->fh);
287
    if (ret == EOF) {
288
        error_setg_errno(err, errno, "failed to close handle");
289 290 291 292
        return;
    }

    QTAILQ_REMOVE(&guest_file_state.filehandles, gfh, next);
293
    g_free(gfh);
294 295 296 297 298
}

struct GuestFileRead *qmp_guest_file_read(int64_t handle, bool has_count,
                                          int64_t count, Error **err)
{
299
    GuestFileHandle *gfh = guest_file_handle_find(handle, err);
300 301 302 303 304 305 306 307 308 309 310 311
    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) {
312 313
        error_setg(err, "value '%" PRId64 "' is invalid for argument count",
                   count);
314 315 316 317
        return NULL;
    }

    fh = gfh->fh;
318
    buf = g_malloc0(count+1);
319 320
    read_count = fread(buf, 1, count, fh);
    if (ferror(fh)) {
321
        error_setg_errno(err, errno, "failed to read file");
322 323 324
        slog("guest-file-read failed, handle: %ld", handle);
    } else {
        buf[read_count] = 0;
325
        read_data = g_malloc0(sizeof(GuestFileRead));
326 327 328 329 330 331
        read_data->count = read_count;
        read_data->eof = feof(fh);
        if (read_count) {
            read_data->buf_b64 = g_base64_encode(buf, read_count);
        }
    }
332
    g_free(buf);
333 334 335 336 337 338 339 340 341 342 343 344
    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;
345
    GuestFileHandle *gfh = guest_file_handle_find(handle, err);
346 347 348 349 350 351 352 353 354 355 356 357
    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) {
358 359
        error_setg(err, "value '%" PRId64 "' is invalid for argument count",
                   count);
360
        g_free(buf);
361 362 363 364 365
        return NULL;
    }

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

    return write_data;
}

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

    if (!gfh) {
        return NULL;
    }

    fh = gfh->fh;
    ret = fseek(fh, offset, whence);
    if (ret == -1) {
394
        error_setg_errno(err, errno, "failed to seek file");
395
    } else {
396
        seek_data = g_malloc0(sizeof(GuestFileRead));
397 398 399 400 401 402 403 404 405 406
        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)
{
407
    GuestFileHandle *gfh = guest_file_handle_find(handle, err);
408 409 410 411 412 413 414 415 416 417
    FILE *fh;
    int ret;

    if (!gfh) {
        return;
    }

    fh = gfh->fh;
    ret = fflush(fh);
    if (ret == EOF) {
418
        error_setg_errno(err, errno, "failed to flush file");
419 420 421 422 423 424 425 426
    }
}

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

427 428 429
/* linux-specific implementations. avoid this if at all possible. */
#if defined(__linux__)

430
#if defined(CONFIG_FSFREEZE) || defined(CONFIG_FSTRIM)
431
typedef struct FsMount {
432 433
    char *dirname;
    char *devtype;
434 435
    QTAILQ_ENTRY(FsMount) next;
} FsMount;
436

437
typedef QTAILQ_HEAD(, FsMount) FsMountList;
438

439
static void free_fs_mount_list(FsMountList *mounts)
440
{
441
     FsMount *mount, *temp;
442 443 444 445 446 447 448 449 450 451 452 453 454

     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);
     }
}

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

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

    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;
        }

484
        mount = g_malloc0(sizeof(FsMount));
485 486
        mount->dirname = g_strdup(ment->mnt_dir);
        mount->devtype = g_strdup(ment->mnt_type);
487

488
        QTAILQ_INSERT_TAIL(mounts, mount, next);
489 490 491 492
    }

    endmntent(fp);
}
493 494 495
#endif

#if defined(CONFIG_FSFREEZE)
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 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
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;
    }
}

557 558 559 560 561
/*
 * Return status of freeze/thaw
 */
GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **err)
{
562 563 564 565 566
    if (ga_is_frozen(ga_state)) {
        return GUEST_FSFREEZE_STATUS_FROZEN;
    }

    return GUEST_FSFREEZE_STATUS_THAWED;
567 568 569 570 571 572 573 574 575
}

/*
 * 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;
576 577
    FsMountList mounts;
    struct FsMount *mount;
578
    Error *local_err = NULL;
579 580 581 582
    int fd;

    slog("guest-fsfreeze called");

583 584 585 586 587 588
    execute_fsfreeze_hook(FSFREEZE_HOOK_FREEZE, &local_err);
    if (error_is_set(&local_err)) {
        error_propagate(err, local_err);
        return -1;
    }

589
    QTAILQ_INIT(&mounts);
590 591 592 593
    build_fs_mount_list(&mounts, &local_err);
    if (error_is_set(&local_err)) {
        error_propagate(err, local_err);
        return -1;
594 595 596
    }

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

599
    QTAILQ_FOREACH(mount, &mounts, next) {
600 601
        fd = qemu_open(mount->dirname, O_RDONLY);
        if (fd == -1) {
602
            error_setg_errno(err, errno, "failed to open %s", mount->dirname);
603 604 605 606 607
            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.
608 609 610 611 612 613
         * 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.
614 615
         */
        ret = ioctl(fd, FIFREEZE);
616 617
        if (ret == -1) {
            if (errno != EOPNOTSUPP) {
618 619
                error_setg_errno(err, errno, "failed to freeze %s",
                                 mount->dirname);
620 621 622 623 624
                close(fd);
                goto error;
            }
        } else {
            i++;
625 626 627 628
        }
        close(fd);
    }

629
    free_fs_mount_list(&mounts);
630 631 632
    return i;

error:
633
    free_fs_mount_list(&mounts);
634
    qmp_guest_fsfreeze_thaw(NULL);
635 636 637 638 639 640 641 642 643
    return 0;
}

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

    QTAILQ_INIT(&mounts);
650 651 652
    build_fs_mount_list(&mounts, &local_err);
    if (error_is_set(&local_err)) {
        error_propagate(err, local_err);
653 654
        return 0;
    }
655

656 657
    QTAILQ_FOREACH(mount, &mounts, next) {
        logged = false;
658 659 660 661
        fd = qemu_open(mount->dirname, O_RDONLY);
        if (fd == -1) {
            continue;
        }
662 663 664 665 666
        /* 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 已提交
667
         * since multiple preceding FIFREEZEs require multiple calls to FITHAW
668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
         * 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);
685 686 687
        close(fd);
    }

688
    ga_unset_frozen(ga_state);
689
    free_fs_mount_list(&mounts);
690 691 692

    execute_fsfreeze_hook(FSFREEZE_HOOK_THAW, err);

693 694 695 696 697 698 699
    return i;
}

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

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

711 712 713 714 715 716 717 718 719 720
#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;
721
    Error *local_err = NULL;
722 723 724 725 726 727 728 729 730
    struct fstrim_range r = {
        .start = 0,
        .len = -1,
        .minlen = has_minimum ? minimum : 0,
    };

    slog("guest-fstrim called");

    QTAILQ_INIT(&mounts);
731 732 733
    build_fs_mount_list(&mounts, &local_err);
    if (error_is_set(&local_err)) {
        error_propagate(err, local_err);
734 735 736 737 738 739
        return;
    }

    QTAILQ_FOREACH(mount, &mounts, next) {
        fd = qemu_open(mount->dirname, O_RDONLY);
        if (fd == -1) {
740
            error_setg_errno(err, errno, "failed to open %s", mount->dirname);
741 742 743 744 745 746 747 748 749 750 751 752
            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) {
753 754
                error_setg_errno(err, errno, "failed to trim %s",
                                 mount->dirname);
755 756 757 758 759 760 761 762 763 764 765 766 767
                close(fd);
                goto error;
            }
        }
        close(fd);
    }

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


768 769 770 771 772 773 774
#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)
{
775
    Error *local_err = NULL;
776
    char *pmutils_path;
777
    pid_t pid;
778
    int status;
779 780 781 782 783

    pmutils_path = g_find_program_in_path(pmutils_bin);

    pid = fork();
    if (!pid) {
784 785 786
        char buf[32]; /* hopefully big enough */
        ssize_t ret;
        int fd;
787 788 789 790 791 792

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

793 794 795
        if (pmutils_path) {
            execle(pmutils_path, pmutils_bin, pmutils_arg, NULL, environ);
        }
796

797 798 799 800
        /*
         * 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.
         */
801

802 803 804
        if (!sysfile_str) {
            _exit(SUSPEND_NOT_SUPPORTED);
        }
805

806 807
        fd = open(LINUX_SYS_STATE_FILE, O_RDONLY);
        if (fd < 0) {
808 809 810
            _exit(SUSPEND_NOT_SUPPORTED);
        }

811 812 813
        ret = read(fd, buf, sizeof(buf)-1);
        if (ret <= 0) {
            _exit(SUSPEND_NOT_SUPPORTED);
814
        }
815
        buf[ret] = '\0';
816

817 818
        if (strstr(buf, sysfile_str)) {
            _exit(SUSPEND_SUPPORTED);
819 820
        }

821
        _exit(SUSPEND_NOT_SUPPORTED);
822 823 824
    } else if (pid < 0) {
        error_setg_errno(err, errno, "failed to create child process");
        goto out;
825 826
    }

827 828 829 830 831
    ga_wait_child(pid, &status, &local_err);
    if (error_is_set(&local_err)) {
        error_propagate(err, local_err);
        goto out;
    }
832

833 834 835
    if (!WIFEXITED(status)) {
        error_setg(err, "child process has terminated abnormally");
        goto out;
836 837
    }

838 839 840 841 842 843 844 845 846 847 848 849
    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;
850 851
    }

852 853
out:
    g_free(pmutils_path);
854 855 856 857 858
}

static void guest_suspend(const char *pmutils_bin, const char *sysfile_str,
                          Error **err)
{
859
    Error *local_err = NULL;
860
    char *pmutils_path;
861
    pid_t pid;
862
    int status;
863 864 865 866 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

    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);
899 900 901
    } else if (pid < 0) {
        error_setg_errno(err, errno, "failed to create child process");
        goto out;
902 903
    }

904 905 906 907 908
    ga_wait_child(pid, &status, &local_err);
    if (error_is_set(&local_err)) {
        error_propagate(err, local_err);
        goto out;
    }
909

910 911 912
    if (!WIFEXITED(status)) {
        error_setg(err, "child process has terminated abnormally");
        goto out;
913 914
    }

915 916 917
    if (WEXITSTATUS(status)) {
        error_setg(err, "child process has failed to suspend");
        goto out;
918
    }
919

920 921
out:
    g_free(pmutils_path);
922 923 924 925 926 927 928 929 930 931 932 933
}

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 已提交
934 935 936 937 938 939 940 941 942 943
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);
}

944 945 946 947 948 949 950 951 952 953
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);
}

954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975
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) {
976
        error_setg_errno(errp, errno, "getifaddrs failed");
977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
        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) {
1012
                error_setg_errno(errp, errno, "failed to create socket");
1013 1014 1015 1016
                goto error;
            }

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

1026
            close(sock);
1027 1028
            mac_addr = (unsigned char *) &ifr.ifr_hwaddr.sa_data;

1029 1030 1031 1032 1033
            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]);
1034 1035 1036 1037 1038 1039 1040 1041 1042

            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))) {
1043
                error_setg_errno(errp, errno, "inet_ntop failed");
1044 1045 1046
                goto error;
            }

1047 1048
            address_item = g_malloc0(sizeof(*address_item));
            address_item->value = g_malloc0(sizeof(*address_item->value));
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
            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))) {
1063
                error_setg_errno(errp, errno, "inet_ntop failed");
1064 1065 1066
                goto error;
            }

1067 1068
            address_item = g_malloc0(sizeof(*address_item));
            address_item->value = g_malloc0(sizeof(*address_item->value));
1069 1070 1071 1072 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
            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;
}

1114 1115
#else /* defined(__linux__) */

1116
void qmp_guest_suspend_disk(Error **err)
1117 1118 1119 1120
{
    error_set(err, QERR_UNSUPPORTED);
}

1121
void qmp_guest_suspend_ram(Error **err)
1122 1123 1124 1125
{
    error_set(err, QERR_UNSUPPORTED);
}

1126
void qmp_guest_suspend_hybrid(Error **err)
1127 1128 1129 1130
{
    error_set(err, QERR_UNSUPPORTED);
}

1131
GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
1132
{
1133 1134
    error_set(errp, QERR_UNSUPPORTED);
    return NULL;
1135 1136
}

1137 1138 1139 1140 1141
#endif

#if !defined(CONFIG_FSFREEZE)

GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **err)
1142 1143
{
    error_set(err, QERR_UNSUPPORTED);
1144 1145

    return 0;
1146 1147
}

1148
int64_t qmp_guest_fsfreeze_freeze(Error **err)
1149 1150
{
    error_set(err, QERR_UNSUPPORTED);
1151 1152

    return 0;
1153 1154
}

1155
int64_t qmp_guest_fsfreeze_thaw(Error **err)
1156
{
1157 1158 1159
    error_set(err, QERR_UNSUPPORTED);

    return 0;
1160
}
1161 1162 1163 1164 1165 1166 1167
#endif /* CONFIG_FSFREEZE */

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

1170 1171 1172
/* register init/cleanup routines for stateful command groups */
void ga_command_state_init(GAState *s, GACommandState *cs)
{
1173
#if defined(CONFIG_FSFREEZE)
1174
    ga_command_state_add(cs, NULL, guest_fsfreeze_cleanup);
1175
#endif
1176 1177
    ga_command_state_add(cs, guest_file_init, NULL);
}