commands-posix.c 81.3 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
 *
 * This work is licensed under the terms of the GNU GPL, version 2 or later.
 * See the COPYING file in the top-level directory.
 */

P
Peter Maydell 已提交
14
#include "qemu/osdep.h"
15
#include <sys/ioctl.h>
16
#include <sys/utsname.h>
17
#include <sys/wait.h>
18
#include <dirent.h>
19
#include "guest-agent-core.h"
20
#include "qga-qapi-commands.h"
21
#include "qapi/error.h"
22
#include "qapi/qmp/qerror.h"
23 24
#include "qemu/queue.h"
#include "qemu/host-utils.h"
25
#include "qemu/sockets.h"
26
#include "qemu/base64.h"
27
#include "qemu/cutils.h"
28

29 30 31 32
#ifdef HAVE_UTMPX
#include <utmpx.h>
#endif

33
#ifndef CONFIG_HAS_ENVIRON
34 35 36 37
#ifdef __APPLE__
#include <crt_externs.h>
#define environ (*_NSGetEnviron())
#else
38 39
extern char **environ;
#endif
40
#endif
41

42
#if defined(__linux__)
43
#include <mntent.h>
44
#include <linux/fs.h>
45 46 47 48
#include <ifaddrs.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <net/if.h>
49
#include <sys/statvfs.h>
50

51 52 53 54
#ifdef CONFIG_LIBUDEV
#include <libudev.h>
#endif

55
#ifdef FIFREEZE
56 57
#define CONFIG_FSFREEZE
#endif
58 59 60
#ifdef FITRIM
#define CONFIG_FSTRIM
#endif
61 62
#endif

63
static void ga_wait_child(pid_t pid, int *status, Error **errp)
64 65 66 67 68 69 70 71 72 73
{
    pid_t rpid;

    *status = 0;

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

    if (rpid == -1) {
74 75
        error_setg_errno(errp, errno, "failed to wait for child (pid: %d)",
                         pid);
76 77 78 79 80 81
        return;
    }

    g_assert(rpid == pid);
}

82
void qmp_guest_shutdown(bool has_mode, const char *mode, Error **errp)
83 84
{
    const char *shutdown_flag;
85 86
    Error *local_err = NULL;
    pid_t pid;
87
    int status;
88 89 90 91 92 93 94 95 96

    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 {
97
        error_setg(errp,
98
                   "mode is invalid (valid values are: halt|powerdown|reboot");
99 100 101
        return;
    }

102 103
    pid = fork();
    if (pid == 0) {
104 105
        /* child, start the shutdown */
        setsid();
106 107 108
        reopen_fd_to_null(0);
        reopen_fd_to_null(1);
        reopen_fd_to_null(2);
109

110
        execle("/sbin/shutdown", "shutdown", "-h", shutdown_flag, "+0",
111 112
               "hypervisor initiated shutdown", (char*)NULL, environ);
        _exit(EXIT_FAILURE);
113
    } else if (pid < 0) {
114
        error_setg_errno(errp, errno, "failed to create child process");
115
        return;
116
    }
117

118
    ga_wait_child(pid, &status, &local_err);
119
    if (local_err) {
120
        error_propagate(errp, local_err);
121 122 123 124
        return;
    }

    if (!WIFEXITED(status)) {
125
        error_setg(errp, "child process has terminated abnormally");
126 127 128 129
        return;
    }

    if (WEXITSTATUS(status)) {
130
        error_setg(errp, "child process has failed to shutdown");
131 132 133
        return;
    }

P
Peter Maydell 已提交
134
    /* succeeded */
135 136
}

L
Lei Li 已提交
137 138 139 140 141 142 143 144 145 146 147
int64_t qmp_guest_get_time(Error **errp)
{
   int ret;
   qemu_timeval tq;

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

148
   return tq.tv_sec * 1000000000LL + tq.tv_usec * 1000;
L
Lei Li 已提交
149 150
}

151
void qmp_guest_set_time(bool has_time, int64_t time_ns, Error **errp)
L
Lei Li 已提交
152 153 154 155 156 157 158
{
    int ret;
    int status;
    pid_t pid;
    Error *local_err = NULL;
    struct timeval tv;

159 160
    /* If user has passed a time, validate and set it. */
    if (has_time) {
161 162
        GDate date = { 0, };

163 164 165 166 167 168 169 170
        /* 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;
171 172 173 174 175
        g_date_set_time_t(&date, tv.tv_sec);
        if (date.year < 1970 || date.year >= 2070) {
            error_setg_errno(errp, errno, "Invalid time");
            return;
        }
176 177 178 179 180 181

        ret = settimeofday(&tv, NULL);
        if (ret < 0) {
            error_setg_errno(errp, errno, "Failed to set time to guest");
            return;
        }
L
Lei Li 已提交
182 183
    }

184 185 186
    /* Now, if user has passed a time to set and the system time is set, we
     * just need to synchronize the hardware clock. However, if no time was
     * passed, user is requesting the opposite: set the system time from the
187
     * hardware clock (RTC). */
L
Lei Li 已提交
188 189 190 191 192 193 194
    pid = fork();
    if (pid == 0) {
        setsid();
        reopen_fd_to_null(0);
        reopen_fd_to_null(1);
        reopen_fd_to_null(2);

195 196 197 198
        /* Use '/sbin/hwclock -w' to set RTC from the system time,
         * or '/sbin/hwclock -s' to set the system time from RTC. */
        execle("/sbin/hwclock", "hwclock", has_time ? "-w" : "-s",
               NULL, environ);
L
Lei Li 已提交
199 200 201 202 203 204 205
        _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);
206
    if (local_err) {
L
Lei Li 已提交
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
        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;
    }
}

222 223 224 225 226 227
typedef enum {
    RW_STATE_NEW,
    RW_STATE_READING,
    RW_STATE_WRITING,
} RwState;

228 229 230
typedef struct GuestFileHandle {
    uint64_t id;
    FILE *fh;
231
    RwState state;
232 233 234 235 236
    QTAILQ_ENTRY(GuestFileHandle) next;
} GuestFileHandle;

static struct {
    QTAILQ_HEAD(, GuestFileHandle) filehandles;
237 238 239
} guest_file_state = {
    .filehandles = QTAILQ_HEAD_INITIALIZER(guest_file_state.filehandles),
};
240

241
static int64_t guest_file_handle_add(FILE *fh, Error **errp)
242 243
{
    GuestFileHandle *gfh;
244 245 246
    int64_t handle;

    handle = ga_get_fd_handle(ga_state, errp);
247 248
    if (handle < 0) {
        return -1;
249
    }
250

251
    gfh = g_new0(GuestFileHandle, 1);
252
    gfh->id = handle;
253 254
    gfh->fh = fh;
    QTAILQ_INSERT_TAIL(&guest_file_state.filehandles, gfh, next);
255 256

    return handle;
257 258
}

259
static GuestFileHandle *guest_file_handle_find(int64_t id, Error **errp)
260 261 262 263 264 265 266 267 268 269
{
    GuestFileHandle *gfh;

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

270
    error_setg(errp, "handle '%" PRId64 "' has not been found", id);
271 272 273
    return NULL;
}

274 275
typedef const char * const ccpc;

276 277 278 279
#ifndef O_BINARY
#define O_BINARY 0
#endif

280 281 282 283 284
/* http://pubs.opengroup.org/onlinepubs/9699919799/functions/fopen.html */
static const struct {
    ccpc *forms;
    int oflag_base;
} guest_file_open_modes[] = {
285 286 287 288 289 290 291 292 293 294 295 296
    { (ccpc[]){ "r",          NULL }, O_RDONLY                                 },
    { (ccpc[]){ "rb",         NULL }, O_RDONLY                      | O_BINARY },
    { (ccpc[]){ "w",          NULL }, O_WRONLY | O_CREAT | O_TRUNC             },
    { (ccpc[]){ "wb",         NULL }, O_WRONLY | O_CREAT | O_TRUNC  | O_BINARY },
    { (ccpc[]){ "a",          NULL }, O_WRONLY | O_CREAT | O_APPEND            },
    { (ccpc[]){ "ab",         NULL }, O_WRONLY | O_CREAT | O_APPEND | O_BINARY },
    { (ccpc[]){ "r+",         NULL }, O_RDWR                                   },
    { (ccpc[]){ "rb+", "r+b", NULL }, O_RDWR                        | O_BINARY },
    { (ccpc[]){ "w+",         NULL }, O_RDWR   | O_CREAT | O_TRUNC             },
    { (ccpc[]){ "wb+", "w+b", NULL }, O_RDWR   | O_CREAT | O_TRUNC  | O_BINARY },
    { (ccpc[]){ "a+",         NULL }, O_RDWR   | O_CREAT | O_APPEND            },
    { (ccpc[]){ "ab+", "a+b", NULL }, O_RDWR   | O_CREAT | O_APPEND | O_BINARY }
297 298 299
};

static int
300
find_open_flag(const char *mode_str, Error **errp)
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
{
    unsigned mode;

    for (mode = 0; mode < ARRAY_SIZE(guest_file_open_modes); ++mode) {
        ccpc *form;

        form = guest_file_open_modes[mode].forms;
        while (*form != NULL && strcmp(*form, mode_str) != 0) {
            ++form;
        }
        if (*form != NULL) {
            break;
        }
    }

    if (mode == ARRAY_SIZE(guest_file_open_modes)) {
317
        error_setg(errp, "invalid file open mode '%s'", mode_str);
318 319 320 321 322 323 324 325 326 327
        return -1;
    }
    return guest_file_open_modes[mode].oflag_base | O_NOCTTY | O_NONBLOCK;
}

#define DEFAULT_NEW_FILE_MODE (S_IRUSR | S_IWUSR | \
                               S_IRGRP | S_IWGRP | \
                               S_IROTH | S_IWOTH)

static FILE *
328
safe_open_or_create(const char *path, const char *mode, Error **errp)
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
{
    Error *local_err = NULL;
    int oflag;

    oflag = find_open_flag(mode, &local_err);
    if (local_err == NULL) {
        int fd;

        /* If the caller wants / allows creation of a new file, we implement it
         * with a two step process: open() + (open() / fchmod()).
         *
         * First we insist on creating the file exclusively as a new file. If
         * that succeeds, we're free to set any file-mode bits on it. (The
         * motivation is that we want to set those file-mode bits independently
         * of the current umask.)
         *
         * If the exclusive creation fails because the file already exists
         * (EEXIST is not possible for any other reason), we just attempt to
         * open the file, but in this case we won't be allowed to change the
         * file-mode bits on the preexistent file.
         *
         * The pathname should never disappear between the two open()s in
         * practice. If it happens, then someone very likely tried to race us.
         * In this case just go ahead and report the ENOENT from the second
         * open() to the caller.
         *
         * If the caller wants to open a preexistent file, then the first
         * open() is decisive and its third argument is ignored, and the second
         * open() and the fchmod() are never called.
         */
        fd = open(path, oflag | ((oflag & O_CREAT) ? O_EXCL : 0), 0);
        if (fd == -1 && errno == EEXIST) {
            oflag &= ~(unsigned)O_CREAT;
            fd = open(path, oflag);
        }

        if (fd == -1) {
            error_setg_errno(&local_err, errno, "failed to open file '%s' "
                             "(mode: '%s')", path, mode);
        } else {
            qemu_set_cloexec(fd);

            if ((oflag & O_CREAT) && fchmod(fd, DEFAULT_NEW_FILE_MODE) == -1) {
                error_setg_errno(&local_err, errno, "failed to set permission "
                                 "0%03o on new file '%s' (mode: '%s')",
                                 (unsigned)DEFAULT_NEW_FILE_MODE, path, mode);
            } else {
                FILE *f;

                f = fdopen(fd, mode);
                if (f == NULL) {
                    error_setg_errno(&local_err, errno, "failed to associate "
                                     "stdio stream with file descriptor %d, "
                                     "file '%s' (mode: '%s')", fd, path, mode);
                } else {
                    return f;
                }
            }

            close(fd);
389 390 391
            if (oflag & O_CREAT) {
                unlink(path);
            }
392 393 394
        }
    }

395
    error_propagate(errp, local_err);
396 397 398
    return NULL;
}

399 400
int64_t qmp_guest_file_open(const char *path, bool has_mode, const char *mode,
                            Error **errp)
401 402
{
    FILE *fh;
403
    Error *local_err = NULL;
404
    int64_t handle;
405 406 407 408 409

    if (!has_mode) {
        mode = "r";
    }
    slog("guest-file-open called, filepath: %s, mode: %s", path, mode);
410 411
    fh = safe_open_or_create(path, mode, &local_err);
    if (local_err != NULL) {
412
        error_propagate(errp, local_err);
413 414 415 416 417 418
        return -1;
    }

    /* set fd non-blocking to avoid common use cases (like reading from a
     * named pipe) from hanging the agent
     */
419
    qemu_set_nonblock(fileno(fh));
420

421
    handle = guest_file_handle_add(fh, errp);
422
    if (handle < 0) {
423 424 425 426
        fclose(fh);
        return -1;
    }

427
    slog("guest-file-open, handle: %" PRId64, handle);
428
    return handle;
429 430
}

431
void qmp_guest_file_close(int64_t handle, Error **errp)
432
{
433
    GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
434 435
    int ret;

436
    slog("guest-file-close called, handle: %" PRId64, handle);
437 438 439 440 441
    if (!gfh) {
        return;
    }

    ret = fclose(gfh->fh);
442
    if (ret == EOF) {
443
        error_setg_errno(errp, errno, "failed to close handle");
444 445 446 447
        return;
    }

    QTAILQ_REMOVE(&guest_file_state.filehandles, gfh, next);
448
    g_free(gfh);
449 450 451
}

struct GuestFileRead *qmp_guest_file_read(int64_t handle, bool has_count,
452
                                          int64_t count, Error **errp)
453
{
454
    GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
455 456 457 458 459 460 461 462 463 464 465
    GuestFileRead *read_data = NULL;
    guchar *buf;
    FILE *fh;
    size_t read_count;

    if (!gfh) {
        return NULL;
    }

    if (!has_count) {
        count = QGA_READ_COUNT_DEFAULT;
466
    } else if (count < 0 || count >= UINT32_MAX) {
467
        error_setg(errp, "value '%" PRId64 "' is invalid for argument count",
468
                   count);
469 470 471 472
        return NULL;
    }

    fh = gfh->fh;
473 474 475 476 477 478 479 480 481 482 483

    /* explicitly flush when switching from writing to reading */
    if (gfh->state == RW_STATE_WRITING) {
        int ret = fflush(fh);
        if (ret == EOF) {
            error_setg_errno(errp, errno, "failed to flush file");
            return NULL;
        }
        gfh->state = RW_STATE_NEW;
    }

484
    buf = g_malloc0(count+1);
485 486
    read_count = fread(buf, 1, count, fh);
    if (ferror(fh)) {
487
        error_setg_errno(errp, errno, "failed to read file");
488
        slog("guest-file-read failed, handle: %" PRId64, handle);
489 490
    } else {
        buf[read_count] = 0;
491
        read_data = g_new0(GuestFileRead, 1);
492 493 494 495 496
        read_data->count = read_count;
        read_data->eof = feof(fh);
        if (read_count) {
            read_data->buf_b64 = g_base64_encode(buf, read_count);
        }
497
        gfh->state = RW_STATE_READING;
498
    }
499
    g_free(buf);
500 501 502 503 504 505
    clearerr(fh);

    return read_data;
}

GuestFileWrite *qmp_guest_file_write(int64_t handle, const char *buf_b64,
506 507
                                     bool has_count, int64_t count,
                                     Error **errp)
508 509 510 511 512
{
    GuestFileWrite *write_data = NULL;
    guchar *buf;
    gsize buf_len;
    int write_count;
513
    GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
514 515 516 517 518 519 520
    FILE *fh;

    if (!gfh) {
        return NULL;
    }

    fh = gfh->fh;
521 522 523 524 525 526 527 528 529 530

    if (gfh->state == RW_STATE_READING) {
        int ret = fseek(fh, 0, SEEK_CUR);
        if (ret == -1) {
            error_setg_errno(errp, errno, "failed to seek file");
            return NULL;
        }
        gfh->state = RW_STATE_NEW;
    }

531 532 533 534
    buf = qbase64_decode(buf_b64, -1, &buf_len, errp);
    if (!buf) {
        return NULL;
    }
535 536 537 538

    if (!has_count) {
        count = buf_len;
    } else if (count < 0 || count > buf_len) {
539
        error_setg(errp, "value '%" PRId64 "' is invalid for argument count",
540
                   count);
541
        g_free(buf);
542 543 544 545 546
        return NULL;
    }

    write_count = fwrite(buf, 1, count, fh);
    if (ferror(fh)) {
547
        error_setg_errno(errp, errno, "failed to write to file");
548
        slog("guest-file-write failed, handle: %" PRId64, handle);
549
    } else {
550
        write_data = g_new0(GuestFileWrite, 1);
551 552
        write_data->count = write_count;
        write_data->eof = feof(fh);
553
        gfh->state = RW_STATE_WRITING;
554
    }
555
    g_free(buf);
556 557 558 559 560 561
    clearerr(fh);

    return write_data;
}

struct GuestFileSeek *qmp_guest_file_seek(int64_t handle, int64_t offset,
562 563
                                          GuestFileWhence *whence_code,
                                          Error **errp)
564
{
565
    GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
566 567 568
    GuestFileSeek *seek_data = NULL;
    FILE *fh;
    int ret;
569
    int whence;
570
    Error *err = NULL;
571 572 573 574 575

    if (!gfh) {
        return NULL;
    }

576
    /* We stupidly exposed 'whence':'int' in our qapi */
577 578 579
    whence = ga_parse_whence(whence_code, &err);
    if (err) {
        error_propagate(errp, err);
580 581 582
        return NULL;
    }

583 584 585
    fh = gfh->fh;
    ret = fseek(fh, offset, whence);
    if (ret == -1) {
586
        error_setg_errno(errp, errno, "failed to seek file");
587 588 589 590
        if (errno == ESPIPE) {
            /* file is non-seekable, stdio shouldn't be buffering anyways */
            gfh->state = RW_STATE_NEW;
        }
591
    } else {
592
        seek_data = g_new0(GuestFileSeek, 1);
593 594
        seek_data->position = ftell(fh);
        seek_data->eof = feof(fh);
595
        gfh->state = RW_STATE_NEW;
596 597 598 599 600 601
    }
    clearerr(fh);

    return seek_data;
}

602
void qmp_guest_file_flush(int64_t handle, Error **errp)
603
{
604
    GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
605 606 607 608 609 610 611 612 613 614
    FILE *fh;
    int ret;

    if (!gfh) {
        return;
    }

    fh = gfh->fh;
    ret = fflush(fh);
    if (ret == EOF) {
615
        error_setg_errno(errp, errno, "failed to flush file");
616 617
    } else {
        gfh->state = RW_STATE_NEW;
618 619 620
    }
}

621 622 623
/* linux-specific implementations. avoid this if at all possible. */
#if defined(__linux__)

624
#if defined(CONFIG_FSFREEZE) || defined(CONFIG_FSTRIM)
625
typedef struct FsMount {
626 627
    char *dirname;
    char *devtype;
628
    unsigned int devmajor, devminor;
629 630
    QTAILQ_ENTRY(FsMount) next;
} FsMount;
631

632
typedef QTAILQ_HEAD(FsMountList, FsMount) FsMountList;
633

634
static void free_fs_mount_list(FsMountList *mounts)
635
{
636
     FsMount *mount, *temp;
637 638 639 640 641 642 643 644 645 646 647 648 649

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

650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
static int dev_major_minor(const char *devpath,
                           unsigned int *devmajor, unsigned int *devminor)
{
    struct stat st;

    *devmajor = 0;
    *devminor = 0;

    if (stat(devpath, &st) < 0) {
        slog("failed to stat device file '%s': %s", devpath, strerror(errno));
        return -1;
    }
    if (S_ISDIR(st.st_mode)) {
        /* It is bind mount */
        return -2;
    }
    if (S_ISBLK(st.st_mode)) {
        *devmajor = major(st.st_rdev);
        *devminor = minor(st.st_rdev);
        return 0;
    }
    return -1;
}

674 675 676
/*
 * Walk the mount table and build a list of local file systems
 */
677
static void build_fs_mount_list_from_mtab(FsMountList *mounts, Error **errp)
678 679
{
    struct mntent *ment;
680
    FsMount *mount;
681
    char const *mtab = "/proc/self/mounts";
682
    FILE *fp;
683
    unsigned int devmajor, devminor;
684 685 686

    fp = setmntent(mtab, "r");
    if (!fp) {
687
        error_setg(errp, "failed to open mtab file: '%s'", mtab);
688
        return;
689 690 691 692 693 694 695 696 697 698 699 700 701 702
    }

    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;
        }
703 704 705 706
        if (dev_major_minor(ment->mnt_fsname, &devmajor, &devminor) == -2) {
            /* Skip bind mounts */
            continue;
        }
707

708
        mount = g_new0(FsMount, 1);
709 710
        mount->dirname = g_strdup(ment->mnt_dir);
        mount->devtype = g_strdup(ment->mnt_type);
711 712
        mount->devmajor = devmajor;
        mount->devminor = devminor;
713

714
        QTAILQ_INSERT_TAIL(mounts, mount, next);
715 716 717 718
    }

    endmntent(fp);
}
719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786

static void decode_mntname(char *name, int len)
{
    int i, j = 0;
    for (i = 0; i <= len; i++) {
        if (name[i] != '\\') {
            name[j++] = name[i];
        } else if (name[i + 1] == '\\') {
            name[j++] = '\\';
            i++;
        } else if (name[i + 1] >= '0' && name[i + 1] <= '3' &&
                   name[i + 2] >= '0' && name[i + 2] <= '7' &&
                   name[i + 3] >= '0' && name[i + 3] <= '7') {
            name[j++] = (name[i + 1] - '0') * 64 +
                        (name[i + 2] - '0') * 8 +
                        (name[i + 3] - '0');
            i += 3;
        } else {
            name[j++] = name[i];
        }
    }
}

static void build_fs_mount_list(FsMountList *mounts, Error **errp)
{
    FsMount *mount;
    char const *mountinfo = "/proc/self/mountinfo";
    FILE *fp;
    char *line = NULL, *dash;
    size_t n;
    char check;
    unsigned int devmajor, devminor;
    int ret, dir_s, dir_e, type_s, type_e, dev_s, dev_e;

    fp = fopen(mountinfo, "r");
    if (!fp) {
        build_fs_mount_list_from_mtab(mounts, errp);
        return;
    }

    while (getline(&line, &n, fp) != -1) {
        ret = sscanf(line, "%*u %*u %u:%u %*s %n%*s%n%c",
                     &devmajor, &devminor, &dir_s, &dir_e, &check);
        if (ret < 3) {
            continue;
        }
        dash = strstr(line + dir_e, " - ");
        if (!dash) {
            continue;
        }
        ret = sscanf(dash, " - %n%*s%n %n%*s%n%c",
                     &type_s, &type_e, &dev_s, &dev_e, &check);
        if (ret < 1) {
            continue;
        }
        line[dir_e] = 0;
        dash[type_e] = 0;
        dash[dev_e] = 0;
        decode_mntname(line + dir_s, dir_e - dir_s);
        decode_mntname(dash + dev_s, dev_e - dev_s);
        if (devmajor == 0) {
            /* btrfs reports major number = 0 */
            if (strcmp("btrfs", dash + type_s) != 0 ||
                dev_major_minor(dash + dev_s, &devmajor, &devminor) < 0) {
                continue;
            }
        }

787
        mount = g_new0(FsMount, 1);
788 789 790 791 792 793 794 795 796 797 798
        mount->dirname = g_strdup(line + dir_s);
        mount->devtype = g_strdup(dash + type_s);
        mount->devmajor = devmajor;
        mount->devminor = devminor;

        QTAILQ_INSERT_TAIL(mounts, mount, next);
    }
    free(line);

    fclose(fp);
}
799 800 801
#endif

#if defined(CONFIG_FSFREEZE)
802

803 804 805 806 807 808 809 810 811 812 813 814 815
static char *get_pci_driver(char const *syspath, int pathlen, Error **errp)
{
    char *path;
    char *dpath;
    char *driver = NULL;
    char buf[PATH_MAX];
    ssize_t len;

    path = g_strndup(syspath, pathlen);
    dpath = g_strdup_printf("%s/driver", path);
    len = readlink(dpath, buf, sizeof(buf) - 1);
    if (len != -1) {
        buf[len] = 0;
816
        driver = g_path_get_basename(buf);
817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878
    }
    g_free(dpath);
    g_free(path);
    return driver;
}

static int compare_uint(const void *_a, const void *_b)
{
    unsigned int a = *(unsigned int *)_a;
    unsigned int b = *(unsigned int *)_b;

    return a < b ? -1 : a > b ? 1 : 0;
}

/* Walk the specified sysfs and build a sorted list of host or ata numbers */
static int build_hosts(char const *syspath, char const *host, bool ata,
                       unsigned int *hosts, int hosts_max, Error **errp)
{
    char *path;
    DIR *dir;
    struct dirent *entry;
    int i = 0;

    path = g_strndup(syspath, host - syspath);
    dir = opendir(path);
    if (!dir) {
        error_setg_errno(errp, errno, "opendir(\"%s\")", path);
        g_free(path);
        return -1;
    }

    while (i < hosts_max) {
        entry = readdir(dir);
        if (!entry) {
            break;
        }
        if (ata && sscanf(entry->d_name, "ata%d", hosts + i) == 1) {
            ++i;
        } else if (!ata && sscanf(entry->d_name, "host%d", hosts + i) == 1) {
            ++i;
        }
    }

    qsort(hosts, i, sizeof(hosts[0]), compare_uint);

    g_free(path);
    closedir(dir);
    return i;
}

/* Store disk device info specified by @sysfs into @fs */
static void build_guest_fsinfo_for_real_device(char const *syspath,
                                               GuestFilesystemInfo *fs,
                                               Error **errp)
{
    unsigned int pci[4], host, hosts[8], tgt[3];
    int i, nhosts = 0, pcilen;
    GuestDiskAddress *disk;
    GuestPCIAddress *pciaddr;
    GuestDiskAddressList *list = NULL;
    bool has_ata = false, has_host = false, has_tgt = false;
    char *p, *q, *driver = NULL;
879 880 881 882
#ifdef CONFIG_LIBUDEV
    struct udev *udev = NULL;
    struct udev_device *udevice = NULL;
#endif
883 884 885 886

    p = strstr(syspath, "/devices/pci");
    if (!p || sscanf(p + 12, "%*x:%*x/%x:%x:%x.%x%n",
                     pci, pci + 1, pci + 2, pci + 3, &pcilen) < 4) {
887
        g_debug("only pci device is supported: sysfs path '%s'", syspath);
888 889 890
        return;
    }

891 892 893 894 895 896 897 898 899 900
    p += 12 + pcilen;
    while (true) {
        driver = get_pci_driver(syspath, p - syspath, errp);
        if (driver && (g_str_equal(driver, "ata_piix") ||
                       g_str_equal(driver, "sym53c8xx") ||
                       g_str_equal(driver, "virtio-pci") ||
                       g_str_equal(driver, "ahci"))) {
            break;
        }

901
        g_free(driver);
902 903 904 905 906 907 908 909
        if (sscanf(p, "/%x:%x:%x.%x%n",
                          pci, pci + 1, pci + 2, pci + 3, &pcilen) == 4) {
            p += pcilen;
            continue;
        }

        g_debug("unsupported driver or sysfs path '%s'", syspath);
        return;
910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928
    }

    p = strstr(syspath, "/target");
    if (p && sscanf(p + 7, "%*u:%*u:%*u/%*u:%u:%u:%u",
                    tgt, tgt + 1, tgt + 2) == 3) {
        has_tgt = true;
    }

    p = strstr(syspath, "/ata");
    if (p) {
        q = p + 4;
        has_ata = true;
    } else {
        p = strstr(syspath, "/host");
        q = p + 5;
    }
    if (p && sscanf(q, "%u", &host) == 1) {
        has_host = true;
        nhosts = build_hosts(syspath, p, has_ata, hosts,
929
                             ARRAY_SIZE(hosts), errp);
930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946
        if (nhosts < 0) {
            goto cleanup;
        }
    }

    pciaddr = g_malloc0(sizeof(*pciaddr));
    pciaddr->domain = pci[0];
    pciaddr->bus = pci[1];
    pciaddr->slot = pci[2];
    pciaddr->function = pci[3];

    disk = g_malloc0(sizeof(*disk));
    disk->pci_controller = pciaddr;

    list = g_malloc0(sizeof(*list));
    list->value = disk;

947 948 949 950 951 952
#ifdef CONFIG_LIBUDEV
    udev = udev_new();
    udevice = udev_device_new_from_syspath(udev, syspath);
    if (udev == NULL || udevice == NULL) {
        g_debug("failed to query udev");
    } else {
953 954 955 956 957 958
        const char *devnode, *serial;
        devnode = udev_device_get_devnode(udevice);
        if (devnode != NULL) {
            disk->dev = g_strdup(devnode);
            disk->has_dev = true;
        }
959 960 961 962 963 964 965 966
        serial = udev_device_get_property_value(udevice, "ID_SERIAL");
        if (serial != NULL && *serial != 0) {
            disk->serial = g_strdup(serial);
            disk->has_serial = true;
        }
    }
#endif

967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
    if (strcmp(driver, "ata_piix") == 0) {
        /* a host per ide bus, target*:0:<unit>:0 */
        if (!has_host || !has_tgt) {
            g_debug("invalid sysfs path '%s' (driver '%s')", syspath, driver);
            goto cleanup;
        }
        for (i = 0; i < nhosts; i++) {
            if (host == hosts[i]) {
                disk->bus_type = GUEST_DISK_BUS_TYPE_IDE;
                disk->bus = i;
                disk->unit = tgt[1];
                break;
            }
        }
        if (i >= nhosts) {
            g_debug("no host for '%s' (driver '%s')", syspath, driver);
            goto cleanup;
        }
    } else if (strcmp(driver, "sym53c8xx") == 0) {
        /* scsi(LSI Logic): target*:0:<unit>:0 */
        if (!has_tgt) {
            g_debug("invalid sysfs path '%s' (driver '%s')", syspath, driver);
            goto cleanup;
        }
        disk->bus_type = GUEST_DISK_BUS_TYPE_SCSI;
        disk->unit = tgt[1];
    } else if (strcmp(driver, "virtio-pci") == 0) {
        if (has_tgt) {
            /* virtio-scsi: target*:0:0:<unit> */
            disk->bus_type = GUEST_DISK_BUS_TYPE_SCSI;
            disk->unit = tgt[2];
        } else {
            /* virtio-blk: 1 disk per 1 device */
            disk->bus_type = GUEST_DISK_BUS_TYPE_VIRTIO;
        }
    } else if (strcmp(driver, "ahci") == 0) {
        /* ahci: 1 host per 1 unit */
        if (!has_host || !has_tgt) {
            g_debug("invalid sysfs path '%s' (driver '%s')", syspath, driver);
            goto cleanup;
        }
        for (i = 0; i < nhosts; i++) {
            if (host == hosts[i]) {
                disk->unit = i;
                disk->bus_type = GUEST_DISK_BUS_TYPE_SATA;
                break;
            }
        }
        if (i >= nhosts) {
            g_debug("no host for '%s' (driver '%s')", syspath, driver);
            goto cleanup;
        }
    } else {
        g_debug("unknown driver '%s' (sysfs path '%s')", driver, syspath);
        goto cleanup;
    }

    list->next = fs->disk;
    fs->disk = list;
1026
    goto out;
1027 1028 1029 1030 1031

cleanup:
    if (list) {
        qapi_free_GuestDiskAddressList(list);
    }
1032
out:
1033
    g_free(driver);
1034 1035 1036 1037 1038
#ifdef CONFIG_LIBUDEV
    udev_unref(udev);
    udev_device_unref(udevice);
#endif
    return;
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
}

static void build_guest_fsinfo_for_device(char const *devpath,
                                          GuestFilesystemInfo *fs,
                                          Error **errp);

/* Store a list of slave devices of virtual volume specified by @syspath into
 * @fs */
static void build_guest_fsinfo_for_virtual_device(char const *syspath,
                                                  GuestFilesystemInfo *fs,
                                                  Error **errp)
{
    DIR *dir;
    char *dirpath;
1053
    struct dirent *entry;
1054 1055 1056 1057

    dirpath = g_strdup_printf("%s/slaves", syspath);
    dir = opendir(dirpath);
    if (!dir) {
1058 1059 1060
        if (errno != ENOENT) {
            error_setg_errno(errp, errno, "opendir(\"%s\")", dirpath);
        }
1061 1062 1063 1064 1065
        g_free(dirpath);
        return;
    }

    for (;;) {
1066 1067 1068 1069 1070 1071
        errno = 0;
        entry = readdir(dir);
        if (entry == NULL) {
            if (errno) {
                error_setg_errno(errp, errno, "readdir(\"%s\")", dirpath);
            }
1072 1073 1074
            break;
        }

1075 1076 1077 1078 1079 1080 1081
        if (entry->d_type == DT_LNK) {
            char *path;

            g_debug(" slave device '%s'", entry->d_name);
            path = g_strdup_printf("%s/slaves/%s", syspath, entry->d_name);
            build_guest_fsinfo_for_device(path, fs, errp);
            g_free(path);
1082 1083 1084 1085 1086 1087 1088

            if (*errp) {
                break;
            }
        }
    }

1089
    g_free(dirpath);
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
    closedir(dir);
}

/* Dispatch to functions for virtual/real device */
static void build_guest_fsinfo_for_device(char const *devpath,
                                          GuestFilesystemInfo *fs,
                                          Error **errp)
{
    char *syspath = realpath(devpath, NULL);

    if (!syspath) {
        error_setg_errno(errp, errno, "realpath(\"%s\")", devpath);
        return;
    }

    if (!fs->name) {
1106
        fs->name = g_path_get_basename(syspath);
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
    }

    g_debug("  parse sysfs path '%s'", syspath);

    if (strstr(syspath, "/devices/virtual/block/")) {
        build_guest_fsinfo_for_virtual_device(syspath, fs, errp);
    } else {
        build_guest_fsinfo_for_real_device(syspath, fs, errp);
    }

    free(syspath);
}

/* Return a list of the disk device(s)' info which @mount lies on */
static GuestFilesystemInfo *build_guest_fsinfo(struct FsMount *mount,
                                               Error **errp)
{
    GuestFilesystemInfo *fs = g_malloc0(sizeof(*fs));
1125 1126
    struct statvfs buf;
    unsigned long used, nonroot_total, fr_size;
1127 1128 1129 1130 1131 1132 1133
    char *devpath = g_strdup_printf("/sys/dev/block/%u:%u",
                                    mount->devmajor, mount->devminor);

    fs->mountpoint = g_strdup(mount->dirname);
    fs->type = g_strdup(mount->devtype);
    build_guest_fsinfo_for_device(devpath, fs, errp);

1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
    if (statvfs(fs->mountpoint, &buf) == 0) {
        fr_size = buf.f_frsize;
        used = buf.f_blocks - buf.f_bfree;
        nonroot_total = used + buf.f_bavail;
        fs->used_bytes = used * fr_size;
        fs->total_bytes = nonroot_total * fr_size;

        fs->has_total_bytes = true;
        fs->has_used_bytes = true;
    }

1145
    g_free(devpath);
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
    return fs;
}

GuestFilesystemInfoList *qmp_guest_get_fsinfo(Error **errp)
{
    FsMountList mounts;
    struct FsMount *mount;
    GuestFilesystemInfoList *new, *ret = NULL;
    Error *local_err = NULL;

    QTAILQ_INIT(&mounts);
    build_fs_mount_list(&mounts, &local_err);
    if (local_err) {
        error_propagate(errp, local_err);
        return NULL;
    }

    QTAILQ_FOREACH(mount, &mounts, next) {
        g_debug("Building guest fsinfo for '%s'", mount->dirname);

        new = g_malloc0(sizeof(*ret));
        new->value = build_guest_fsinfo(mount, &local_err);
        new->next = ret;
        ret = new;
        if (local_err) {
            error_propagate(errp, local_err);
            qapi_free_GuestFilesystemInfoList(ret);
            ret = NULL;
            break;
        }
    }

    free_fs_mount_list(&mounts);
    return ret;
}


1184 1185 1186 1187 1188
typedef enum {
    FSFREEZE_HOOK_THAW = 0,
    FSFREEZE_HOOK_FREEZE,
} FsfreezeHookArg;

1189
static const char *fsfreeze_hook_arg_string[] = {
1190 1191 1192 1193
    "thaw",
    "freeze",
};

1194
static void execute_fsfreeze_hook(FsfreezeHookArg arg, Error **errp)
1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206
{
    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) {
1207
        error_setg_errno(errp, errno, "can't access fsfreeze hook '%s'", hook);
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
        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) {
1222
        error_setg_errno(errp, errno, "failed to create child process");
1223 1224 1225 1226
        return;
    }

    ga_wait_child(pid, &status, &local_err);
1227
    if (local_err) {
1228
        error_propagate(errp, local_err);
1229 1230 1231 1232
        return;
    }

    if (!WIFEXITED(status)) {
1233
        error_setg(errp, "fsfreeze hook has terminated abnormally");
1234 1235 1236 1237 1238
        return;
    }

    status = WEXITSTATUS(status);
    if (status) {
1239
        error_setg(errp, "fsfreeze hook has failed with status %d", status);
1240 1241 1242 1243
        return;
    }
}

1244 1245 1246
/*
 * Return status of freeze/thaw
 */
1247
GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **errp)
1248
{
1249 1250 1251 1252 1253
    if (ga_is_frozen(ga_state)) {
        return GUEST_FSFREEZE_STATUS_FROZEN;
    }

    return GUEST_FSFREEZE_STATUS_THAWED;
1254 1255
}

1256 1257 1258 1259 1260
int64_t qmp_guest_fsfreeze_freeze(Error **errp)
{
    return qmp_guest_fsfreeze_freeze_list(false, NULL, errp);
}

1261 1262 1263 1264
/*
 * Walk list of mounted file systems in the guest, and freeze the ones which
 * are real local file systems.
 */
1265 1266 1267
int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints,
                                       strList *mountpoints,
                                       Error **errp)
1268 1269
{
    int ret = 0, i = 0;
1270
    strList *list;
1271 1272
    FsMountList mounts;
    struct FsMount *mount;
1273
    Error *local_err = NULL;
1274 1275 1276 1277
    int fd;

    slog("guest-fsfreeze called");

1278
    execute_fsfreeze_hook(FSFREEZE_HOOK_FREEZE, &local_err);
1279
    if (local_err) {
1280
        error_propagate(errp, local_err);
1281 1282 1283
        return -1;
    }

1284
    QTAILQ_INIT(&mounts);
1285
    build_fs_mount_list(&mounts, &local_err);
1286
    if (local_err) {
1287
        error_propagate(errp, local_err);
1288
        return -1;
1289 1290 1291
    }

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

1294
    QTAILQ_FOREACH_REVERSE(mount, &mounts, FsMountList, next) {
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
        /* To issue fsfreeze in the reverse order of mounts, check if the
         * mount is listed in the list here */
        if (has_mountpoints) {
            for (list = mountpoints; list; list = list->next) {
                if (strcmp(list->value, mount->dirname) == 0) {
                    break;
                }
            }
            if (!list) {
                continue;
            }
        }

1308 1309
        fd = qemu_open(mount->dirname, O_RDONLY);
        if (fd == -1) {
1310
            error_setg_errno(errp, errno, "failed to open %s", mount->dirname);
1311 1312 1313
            goto error;
        }

M
Michael Tokarev 已提交
1314 1315
        /* we try to cull filesystems we know won't work in advance, but other
         * filesystems may not implement fsfreeze for less obvious reasons.
1316 1317
         * these will report EOPNOTSUPP. we simply ignore these when tallying
         * the number of frozen filesystems.
1318 1319 1320
         * if a filesystem is mounted more than once (aka bind mount) a
         * consecutive attempt to freeze an already frozen filesystem will
         * return EBUSY.
1321 1322 1323 1324
         *
         * 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.
1325 1326
         */
        ret = ioctl(fd, FIFREEZE);
1327
        if (ret == -1) {
1328
            if (errno != EOPNOTSUPP && errno != EBUSY) {
1329
                error_setg_errno(errp, errno, "failed to freeze %s",
1330
                                 mount->dirname);
1331 1332 1333 1334 1335
                close(fd);
                goto error;
            }
        } else {
            i++;
1336 1337 1338 1339
        }
        close(fd);
    }

1340
    free_fs_mount_list(&mounts);
1341 1342 1343 1344 1345 1346
    /* We may not issue any FIFREEZE here.
     * Just unset ga_state here and ready for the next call.
     */
    if (i == 0) {
        ga_unset_frozen(ga_state);
    }
1347 1348 1349
    return i;

error:
1350
    free_fs_mount_list(&mounts);
1351
    qmp_guest_fsfreeze_thaw(NULL);
1352 1353 1354 1355 1356 1357
    return 0;
}

/*
 * Walk list of frozen file systems in the guest, and thaw them.
 */
1358
int64_t qmp_guest_fsfreeze_thaw(Error **errp)
1359 1360
{
    int ret;
1361 1362
    FsMountList mounts;
    FsMount *mount;
1363
    int fd, i = 0, logged;
1364
    Error *local_err = NULL;
1365 1366

    QTAILQ_INIT(&mounts);
1367
    build_fs_mount_list(&mounts, &local_err);
1368
    if (local_err) {
1369
        error_propagate(errp, local_err);
1370 1371
        return 0;
    }
1372

1373 1374
    QTAILQ_FOREACH(mount, &mounts, next) {
        logged = false;
1375 1376 1377 1378
        fd = qemu_open(mount->dirname, O_RDONLY);
        if (fd == -1) {
            continue;
        }
1379 1380 1381 1382 1383
        /* 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 已提交
1384
         * since multiple preceding FIFREEZEs require multiple calls to FITHAW
1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401
         * 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);
1402 1403 1404
        close(fd);
    }

1405
    ga_unset_frozen(ga_state);
1406
    free_fs_mount_list(&mounts);
1407

1408
    execute_fsfreeze_hook(FSFREEZE_HOOK_THAW, errp);
1409

1410 1411 1412 1413 1414 1415 1416
    return i;
}

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

1417
    if (ga_is_frozen(ga_state) == GUEST_FSFREEZE_STATUS_FROZEN) {
1418 1419 1420 1421 1422
        qmp_guest_fsfreeze_thaw(&err);
        if (err) {
            slog("failed to clean up frozen filesystems: %s",
                 error_get_pretty(err));
            error_free(err);
1423 1424 1425
        }
    }
}
1426
#endif /* CONFIG_FSFREEZE */
1427

1428 1429 1430 1431
#if defined(CONFIG_FSTRIM)
/*
 * Walk list of mounted file systems in the guest, and trim them.
 */
1432 1433
GuestFilesystemTrimResponse *
qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **errp)
1434
{
1435 1436 1437
    GuestFilesystemTrimResponse *response;
    GuestFilesystemTrimResultList *list;
    GuestFilesystemTrimResult *result;
1438 1439 1440 1441
    int ret = 0;
    FsMountList mounts;
    struct FsMount *mount;
    int fd;
1442
    Error *local_err = NULL;
1443
    struct fstrim_range r;
1444 1445 1446 1447

    slog("guest-fstrim called");

    QTAILQ_INIT(&mounts);
1448
    build_fs_mount_list(&mounts, &local_err);
1449
    if (local_err) {
1450
        error_propagate(errp, local_err);
1451
        return NULL;
1452 1453
    }

1454 1455
    response = g_malloc0(sizeof(*response));

1456
    QTAILQ_FOREACH(mount, &mounts, next) {
1457 1458 1459 1460 1461 1462 1463 1464
        result = g_malloc0(sizeof(*result));
        result->path = g_strdup(mount->dirname);

        list = g_malloc0(sizeof(*list));
        list->value = result;
        list->next = response->paths;
        response->paths = list;

1465 1466
        fd = qemu_open(mount->dirname, O_RDONLY);
        if (fd == -1) {
1467 1468 1469 1470
            result->error = g_strdup_printf("failed to open: %s",
                                            strerror(errno));
            result->has_error = true;
            continue;
1471 1472
        }

M
Michael Tokarev 已提交
1473 1474 1475 1476
        /* We try to cull filesystems we know won't work in advance, but other
         * filesystems may not implement fstrim for less obvious reasons.
         * These will report EOPNOTSUPP; while in some other cases ENOTTY
         * will be reported (e.g. CD-ROMs).
1477
         * Any other error means an unexpected error.
1478
         */
1479 1480 1481
        r.start = 0;
        r.len = -1;
        r.minlen = has_minimum ? minimum : 0;
1482 1483
        ret = ioctl(fd, FITRIM, &r);
        if (ret == -1) {
1484 1485 1486 1487 1488 1489
            result->has_error = true;
            if (errno == ENOTTY || errno == EOPNOTSUPP) {
                result->error = g_strdup("trim not supported");
            } else {
                result->error = g_strdup_printf("failed to trim: %s",
                                                strerror(errno));
1490
            }
1491 1492
            close(fd);
            continue;
1493
        }
1494 1495 1496 1497 1498

        result->has_minimum = true;
        result->minimum = r.minlen;
        result->has_trimmed = true;
        result->trimmed = r.len;
1499 1500 1501 1502
        close(fd);
    }

    free_fs_mount_list(&mounts);
1503
    return response;
1504 1505 1506 1507
}
#endif /* CONFIG_FSTRIM */


1508 1509 1510 1511
#define LINUX_SYS_STATE_FILE "/sys/power/state"
#define SUSPEND_SUPPORTED 0
#define SUSPEND_NOT_SUPPORTED 1

1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528
typedef enum {
    SUSPEND_MODE_DISK = 0,
    SUSPEND_MODE_RAM = 1,
    SUSPEND_MODE_HYBRID = 2,
} SuspendMode;

/*
 * Executes a command in a child process using g_spawn_sync,
 * returning an int >= 0 representing the exit status of the
 * process.
 *
 * If the program wasn't found in path, returns -1.
 *
 * If a problem happened when creating the child process,
 * returns -1 and errp is set.
 */
static int run_process_child(const char *command[], Error **errp)
1529
{
1530 1531 1532 1533 1534 1535
    int exit_status, spawn_flag;
    GError *g_err = NULL;
    bool success;

    spawn_flag = G_SPAWN_SEARCH_PATH | G_SPAWN_STDOUT_TO_DEV_NULL |
                 G_SPAWN_STDERR_TO_DEV_NULL;
1536

1537 1538 1539
    success =  g_spawn_sync(NULL, (char **)command, environ, spawn_flag,
                            NULL, NULL, NULL, NULL,
                            &exit_status, &g_err);
1540

1541 1542
    if (success) {
        return WEXITSTATUS(exit_status);
1543 1544
    }

1545 1546 1547
    if (g_err && (g_err->code != G_SPAWN_ERROR_NOENT)) {
        error_setg(errp, "failed to create child process, error '%s'",
                   g_err->message);
1548
    }
1549

1550 1551 1552 1553
    g_error_free(g_err);
    return -1;
}

1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575
static bool systemd_supports_mode(SuspendMode mode, Error **errp)
{
    Error *local_err = NULL;
    const char *systemctl_args[3] = {"systemd-hibernate", "systemd-suspend",
                                     "systemd-hybrid-sleep"};
    const char *cmd[4] = {"systemctl", "status", systemctl_args[mode], NULL};
    int status;

    status = run_process_child(cmd, &local_err);

    /*
     * systemctl status uses LSB return codes so we can expect
     * status > 0 and be ok. To assert if the guest has support
     * for the selected suspend mode, status should be < 4. 4 is
     * the code for unknown service status, the return value when
     * the service does not exist. A common value is status = 3
     * (program is not running).
     */
    if (status > 0 && status < 4) {
        return true;
    }

1576
    error_propagate(errp, local_err);
1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607
    return false;
}

static void systemd_suspend(SuspendMode mode, Error **errp)
{
    Error *local_err = NULL;
    const char *systemctl_args[3] = {"hibernate", "suspend", "hybrid-sleep"};
    const char *cmd[3] = {"systemctl", systemctl_args[mode], NULL};
    int status;

    status = run_process_child(cmd, &local_err);

    if (status == 0) {
        return;
    }

    if ((status == -1) && !local_err) {
        error_setg(errp, "the helper program 'systemctl %s' was not found",
                   systemctl_args[mode]);
        return;
    }

    if (local_err) {
        error_propagate(errp, local_err);
    } else {
        error_setg(errp, "the helper program 'systemctl %s' returned an "
                   "unexpected exit status code (%d)",
                   systemctl_args[mode], status);
    }
}

1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619
static bool pmutils_supports_mode(SuspendMode mode, Error **errp)
{
    Error *local_err = NULL;
    const char *pmutils_args[3] = {"--hibernate", "--suspend",
                                   "--suspend-hybrid"};
    const char *cmd[3] = {"pm-is-supported", pmutils_args[mode], NULL};
    int status;

    status = run_process_child(cmd, &local_err);

    if (status == SUSPEND_SUPPORTED) {
        return true;
1620 1621
    }

1622 1623
    if ((status == -1) && !local_err) {
        return false;
1624
    }
1625

1626 1627 1628
    if (local_err) {
        error_propagate(errp, local_err);
    } else {
1629
        error_setg(errp,
1630 1631
                   "the helper program '%s' returned an unexpected exit"
                   " status code (%d)", "pm-is-supported", status);
1632 1633
    }

1634
    return false;
1635 1636
}

1637
static void pmutils_suspend(SuspendMode mode, Error **errp)
1638 1639
{
    Error *local_err = NULL;
1640 1641 1642
    const char *pmutils_binaries[3] = {"pm-hibernate", "pm-suspend",
                                       "pm-suspend-hybrid"};
    const char *cmd[2] = {pmutils_binaries[mode], NULL};
1643 1644
    int status;

1645
    status = run_process_child(cmd, &local_err);
1646

1647
    if (status == 0) {
1648 1649 1650
        return;
    }

1651 1652 1653 1654
    if ((status == -1) && !local_err) {
        error_setg(errp, "the helper program '%s' was not found",
                   pmutils_binaries[mode]);
        return;
1655 1656 1657 1658
    }

    if (local_err) {
        error_propagate(errp, local_err);
1659
    } else {
1660
        error_setg(errp,
1661 1662
                   "the helper program '%s' returned an unexpected exit"
                   " status code (%d)", pmutils_binaries[mode], status);
1663 1664 1665
    }
}

1666
static bool linux_sys_state_supports_mode(SuspendMode mode, Error **errp)
1667
{
1668 1669
    const char *sysfile_strs[3] = {"disk", "mem", NULL};
    const char *sysfile_str = sysfile_strs[mode];
1670 1671 1672 1673
    char buf[32]; /* hopefully big enough */
    int fd;
    ssize_t ret;

1674 1675
    if (!sysfile_str) {
        error_setg(errp, "unknown guest suspend mode");
1676 1677 1678 1679 1680 1681 1682 1683 1684
        return false;
    }

    fd = open(LINUX_SYS_STATE_FILE, O_RDONLY);
    if (fd < 0) {
        return false;
    }

    ret = read(fd, buf, sizeof(buf) - 1);
P
Paolo Bonzini 已提交
1685
    close(fd);
1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696
    if (ret <= 0) {
        return false;
    }
    buf[ret] = '\0';

    if (strstr(buf, sysfile_str)) {
        return true;
    }
    return false;
}

1697
static void linux_sys_state_suspend(SuspendMode mode, Error **errp)
1698
{
1699
    Error *local_err = NULL;
1700 1701
    const char *sysfile_strs[3] = {"disk", "mem", NULL};
    const char *sysfile_str = sysfile_strs[mode];
1702
    pid_t pid;
1703
    int status;
1704

1705
    if (!sysfile_str) {
1706 1707 1708 1709
        error_setg(errp, "unknown guest suspend mode");
        return;
    }

1710
    pid = fork();
1711
    if (!pid) {
1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729
        /* child */
        int fd;

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

        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);
1730
    } else if (pid < 0) {
1731
        error_setg_errno(errp, errno, "failed to create child process");
1732
        return;
1733 1734
    }

1735
    ga_wait_child(pid, &status, &local_err);
1736
    if (local_err) {
1737
        error_propagate(errp, local_err);
1738
        return;
1739 1740
    }

1741
    if (WEXITSTATUS(status)) {
1742
        error_setg(errp, "child process has failed to suspend");
1743
    }
1744

1745 1746
}

1747
static void guest_suspend(SuspendMode mode, Error **errp)
1748 1749
{
    Error *local_err = NULL;
1750
    bool mode_supported = false;
1751

1752 1753 1754
    if (systemd_supports_mode(mode, &local_err)) {
        mode_supported = true;
        systemd_suspend(mode, &local_err);
1755 1756
    }

1757 1758 1759 1760 1761 1762
    if (!local_err) {
        return;
    }

    error_free(local_err);

1763 1764 1765 1766 1767
    if (pmutils_supports_mode(mode, &local_err)) {
        mode_supported = true;
        pmutils_suspend(mode, &local_err);
    }

1768 1769 1770 1771 1772 1773
    if (!local_err) {
        return;
    }

    error_free(local_err);

1774 1775 1776 1777 1778 1779 1780 1781
    if (linux_sys_state_supports_mode(mode, &local_err)) {
        mode_supported = true;
        linux_sys_state_suspend(mode, &local_err);
    }

    if (!mode_supported) {
        error_setg(errp,
                   "the requested suspend mode is not supported by the guest");
1782
    } else {
1783 1784
        error_propagate(errp, local_err);
    }
1785 1786
}

1787
void qmp_guest_suspend_disk(Error **errp)
1788
{
1789
    guest_suspend(SUSPEND_MODE_DISK, errp);
1790 1791
}

1792
void qmp_guest_suspend_ram(Error **errp)
L
Luiz Capitulino 已提交
1793
{
1794
    guest_suspend(SUSPEND_MODE_RAM, errp);
L
Luiz Capitulino 已提交
1795 1796
}

1797
void qmp_guest_suspend_hybrid(Error **errp)
1798
{
1799
    guest_suspend(SUSPEND_MODE_HYBRID, errp);
1800 1801
}

1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814
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;
}

1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875
static int guest_get_network_stats(const char *name,
                       GuestNetworkInterfaceStat *stats)
{
    int name_len;
    char const *devinfo = "/proc/net/dev";
    FILE *fp;
    char *line = NULL, *colon;
    size_t n = 0;
    fp = fopen(devinfo, "r");
    if (!fp) {
        return -1;
    }
    name_len = strlen(name);
    while (getline(&line, &n, fp) != -1) {
        long long dummy;
        long long rx_bytes;
        long long rx_packets;
        long long rx_errs;
        long long rx_dropped;
        long long tx_bytes;
        long long tx_packets;
        long long tx_errs;
        long long tx_dropped;
        char *trim_line;
        trim_line = g_strchug(line);
        if (trim_line[0] == '\0') {
            continue;
        }
        colon = strchr(trim_line, ':');
        if (!colon) {
            continue;
        }
        if (colon - name_len  == trim_line &&
           strncmp(trim_line, name, name_len) == 0) {
            if (sscanf(colon + 1,
                "%lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld",
                  &rx_bytes, &rx_packets, &rx_errs, &rx_dropped,
                  &dummy, &dummy, &dummy, &dummy,
                  &tx_bytes, &tx_packets, &tx_errs, &tx_dropped,
                  &dummy, &dummy, &dummy, &dummy) != 16) {
                continue;
            }
            stats->rx_bytes = rx_bytes;
            stats->rx_packets = rx_packets;
            stats->rx_errs = rx_errs;
            stats->rx_dropped = rx_dropped;
            stats->tx_bytes = tx_bytes;
            stats->tx_packets = tx_packets;
            stats->tx_errs = tx_errs;
            stats->tx_dropped = tx_dropped;
            fclose(fp);
            g_free(line);
            return 0;
        }
    }
    fclose(fp);
    g_free(line);
    g_debug("/proc/net/dev: Interface '%s' not found", name);
    return -1;
}

1876 1877 1878 1879 1880 1881 1882 1883 1884
/*
 * 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) {
1885
        error_setg_errno(errp, errno, "getifaddrs failed");
1886 1887 1888 1889 1890 1891
        goto error;
    }

    for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
        GuestNetworkInterfaceList *info;
        GuestIpAddressList **address_list = NULL, *address_item = NULL;
1892
        GuestNetworkInterfaceStat  *interface_stat = NULL;
1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921
        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) {
1922
                error_setg_errno(errp, errno, "failed to create socket");
1923 1924 1925 1926
                goto error;
            }

            memset(&ifr, 0, sizeof(ifr));
1927
            pstrcpy(ifr.ifr_name, IF_NAMESIZE, info->value->name);
1928
            if (ioctl(sock, SIOCGIFHWADDR, &ifr) == -1) {
1929 1930 1931
                error_setg_errno(errp, errno,
                                 "failed to get MAC address of %s",
                                 ifa->ifa_name);
1932
                close(sock);
1933 1934 1935
                goto error;
            }

1936
            close(sock);
1937 1938
            mac_addr = (unsigned char *) &ifr.ifr_hwaddr.sa_data;

1939 1940 1941 1942 1943
            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]);
1944 1945 1946 1947 1948 1949 1950 1951 1952

            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))) {
1953
                error_setg_errno(errp, errno, "inet_ntop failed");
1954 1955 1956
                goto error;
            }

1957 1958
            address_item = g_malloc0(sizeof(*address_item));
            address_item->value = g_malloc0(sizeof(*address_item->value));
1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972
            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))) {
1973
                error_setg_errno(errp, errno, "inet_ntop failed");
1974 1975 1976
                goto error;
            }

1977 1978
            address_item = g_malloc0(sizeof(*address_item));
            address_item->value = g_malloc0(sizeof(*address_item->value));
1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011
            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;

2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022
        if (!info->value->has_statistics) {
            interface_stat = g_malloc0(sizeof(*interface_stat));
            if (guest_get_network_stats(info->value->name,
                interface_stat) == -1) {
                info->value->has_statistics = false;
                g_free(interface_stat);
            } else {
                info->value->statistics = interface_stat;
                info->value->has_statistics = true;
            }
        }
2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033
    }

    freeifaddrs(ifap);
    return head;

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

2034
#define SYSCONF_EXACT(name, errp) sysconf_exact((name), #name, (errp))
2035

2036
static long sysconf_exact(int name, const char *name_str, Error **errp)
2037 2038 2039 2040 2041 2042 2043
{
    long ret;

    errno = 0;
    ret = sysconf(name);
    if (ret == -1) {
        if (errno == 0) {
2044
            error_setg(errp, "sysconf(%s): value indefinite", name_str);
2045
        } else {
2046
            error_setg_errno(errp, errno, "sysconf(%s)", name_str);
2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067
        }
    }
    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,
2068
                          char *dirpath, Error **errp)
2069
{
2070 2071
    int fd;
    int res;
2072
    int dirfd;
2073
    static const char fn[] = "online";
2074 2075 2076 2077

    dirfd = open(dirpath, O_RDONLY | O_DIRECTORY);
    if (dirfd == -1) {
        error_setg_errno(errp, errno, "open(\"%s\")", dirpath);
2078 2079
        return;
    }
2080

2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110
    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 */
2111

2112
        res = close(fd);
2113 2114 2115
        g_assert(res == 0);
    }

2116 2117
    res = close(dirfd);
    g_assert(res == 0);
2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134
}

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;
2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149
        int64_t id = current++;
        char *path = g_strdup_printf("/sys/devices/system/cpu/cpu%" PRId64 "/",
                                     id);

        if (g_file_test(path, G_FILE_TEST_EXISTS)) {
            vcpu = g_malloc0(sizeof *vcpu);
            vcpu->logical_id = id;
            vcpu->has_can_offline = true; /* lolspeak ftw */
            transfer_vcpu(vcpu, true, path, &local_err);
            entry = g_malloc0(sizeof *entry);
            entry->value = vcpu;
            *link = entry;
            link = &entry->next;
        }
        g_free(path);
2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162
    }

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

2163 2164 2165 2166 2167 2168 2169
int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList *vcpus, Error **errp)
{
    int64_t processed;
    Error *local_err = NULL;

    processed = 0;
    while (vcpus != NULL) {
2170 2171 2172 2173 2174
        char *path = g_strdup_printf("/sys/devices/system/cpu/cpu%" PRId64 "/",
                                     vcpus->value->logical_id);

        transfer_vcpu(vcpus->value, false, path, &local_err);
        g_free(path);
2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192
        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;
}

2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207
void qmp_guest_set_user_password(const char *username,
                                 const char *password,
                                 bool crypted,
                                 Error **errp)
{
    Error *local_err = NULL;
    char *passwd_path = NULL;
    pid_t pid;
    int status;
    int datafd[2] = { -1, -1 };
    char *rawpasswddata = NULL;
    size_t rawpasswdlen;
    char *chpasswddata = NULL;
    size_t chpasswdlen;

2208 2209 2210 2211
    rawpasswddata = (char *)qbase64_decode(password, -1, &rawpasswdlen, errp);
    if (!rawpasswddata) {
        return;
    }
2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297
    rawpasswddata = g_renew(char, rawpasswddata, rawpasswdlen + 1);
    rawpasswddata[rawpasswdlen] = '\0';

    if (strchr(rawpasswddata, '\n')) {
        error_setg(errp, "forbidden characters in raw password");
        goto out;
    }

    if (strchr(username, '\n') ||
        strchr(username, ':')) {
        error_setg(errp, "forbidden characters in username");
        goto out;
    }

    chpasswddata = g_strdup_printf("%s:%s\n", username, rawpasswddata);
    chpasswdlen = strlen(chpasswddata);

    passwd_path = g_find_program_in_path("chpasswd");

    if (!passwd_path) {
        error_setg(errp, "cannot find 'passwd' program in PATH");
        goto out;
    }

    if (pipe(datafd) < 0) {
        error_setg(errp, "cannot create pipe FDs");
        goto out;
    }

    pid = fork();
    if (pid == 0) {
        close(datafd[1]);
        /* child */
        setsid();
        dup2(datafd[0], 0);
        reopen_fd_to_null(1);
        reopen_fd_to_null(2);

        if (crypted) {
            execle(passwd_path, "chpasswd", "-e", NULL, environ);
        } else {
            execle(passwd_path, "chpasswd", NULL, environ);
        }
        _exit(EXIT_FAILURE);
    } else if (pid < 0) {
        error_setg_errno(errp, errno, "failed to create child process");
        goto out;
    }
    close(datafd[0]);
    datafd[0] = -1;

    if (qemu_write_full(datafd[1], chpasswddata, chpasswdlen) != chpasswdlen) {
        error_setg_errno(errp, errno, "cannot write new account password");
        goto out;
    }
    close(datafd[1]);
    datafd[1] = -1;

    ga_wait_child(pid, &status, &local_err);
    if (local_err) {
        error_propagate(errp, local_err);
        goto out;
    }

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

    if (WEXITSTATUS(status)) {
        error_setg(errp, "child process has failed to set user password");
        goto out;
    }

out:
    g_free(chpasswddata);
    g_free(rawpasswddata);
    g_free(passwd_path);
    if (datafd[0] != -1) {
        close(datafd[0]);
    }
    if (datafd[1] != -1) {
        close(datafd[1]);
    }
}

2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375
static void ga_read_sysfs_file(int dirfd, const char *pathname, char *buf,
                               int size, Error **errp)
{
    int fd;
    int res;

    errno = 0;
    fd = openat(dirfd, pathname, O_RDONLY);
    if (fd == -1) {
        error_setg_errno(errp, errno, "open sysfs file \"%s\"", pathname);
        return;
    }

    res = pread(fd, buf, size, 0);
    if (res == -1) {
        error_setg_errno(errp, errno, "pread sysfs file \"%s\"", pathname);
    } else if (res == 0) {
        error_setg(errp, "pread sysfs file \"%s\": unexpected EOF", pathname);
    }
    close(fd);
}

static void ga_write_sysfs_file(int dirfd, const char *pathname,
                                const char *buf, int size, Error **errp)
{
    int fd;

    errno = 0;
    fd = openat(dirfd, pathname, O_WRONLY);
    if (fd == -1) {
        error_setg_errno(errp, errno, "open sysfs file \"%s\"", pathname);
        return;
    }

    if (pwrite(fd, buf, size, 0) == -1) {
        error_setg_errno(errp, errno, "pwrite sysfs file \"%s\"", pathname);
    }

    close(fd);
}

/* Transfer online/offline status between @mem_blk and the guest system.
 *
 * On input either @errp or *@errp must be NULL.
 *
 * In system-to-@mem_blk direction, the following @mem_blk fields are accessed:
 * - R: mem_blk->phys_index
 * - W: mem_blk->online
 * - W: mem_blk->can_offline
 *
 * In @mem_blk-to-system direction, the following @mem_blk fields are accessed:
 * - R: mem_blk->phys_index
 * - R: mem_blk->online
 *-  R: mem_blk->can_offline
 * Written members remain unmodified on error.
 */
static void transfer_memory_block(GuestMemoryBlock *mem_blk, bool sys2memblk,
                                  GuestMemoryBlockResponse *result,
                                  Error **errp)
{
    char *dirpath;
    int dirfd;
    char *status;
    Error *local_err = NULL;

    if (!sys2memblk) {
        DIR *dp;

        if (!result) {
            error_setg(errp, "Internal error, 'result' should not be NULL");
            return;
        }
        errno = 0;
        dp = opendir("/sys/devices/system/memory/");
         /* if there is no 'memory' directory in sysfs,
         * we think this VM does not support online/offline memory block,
         * any other solution?
         */
2376 2377 2378 2379 2380
        if (!dp) {
            if (errno == ENOENT) {
                result->response =
                    GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED;
            }
2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435
            goto out1;
        }
        closedir(dp);
    }

    dirpath = g_strdup_printf("/sys/devices/system/memory/memory%" PRId64 "/",
                              mem_blk->phys_index);
    dirfd = open(dirpath, O_RDONLY | O_DIRECTORY);
    if (dirfd == -1) {
        if (sys2memblk) {
            error_setg_errno(errp, errno, "open(\"%s\")", dirpath);
        } else {
            if (errno == ENOENT) {
                result->response = GUEST_MEMORY_BLOCK_RESPONSE_TYPE_NOT_FOUND;
            } else {
                result->response =
                    GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED;
            }
        }
        g_free(dirpath);
        goto out1;
    }
    g_free(dirpath);

    status = g_malloc0(10);
    ga_read_sysfs_file(dirfd, "state", status, 10, &local_err);
    if (local_err) {
        /* treat with sysfs file that not exist in old kernel */
        if (errno == ENOENT) {
            error_free(local_err);
            if (sys2memblk) {
                mem_blk->online = true;
                mem_blk->can_offline = false;
            } else if (!mem_blk->online) {
                result->response =
                    GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED;
            }
        } else {
            if (sys2memblk) {
                error_propagate(errp, local_err);
            } else {
                result->response =
                    GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED;
            }
        }
        goto out2;
    }

    if (sys2memblk) {
        char removable = '0';

        mem_blk->online = (strncmp(status, "online", 6) == 0);

        ga_read_sysfs_file(dirfd, "removable", &removable, 1, &local_err);
        if (local_err) {
V
Veres Lajos 已提交
2436
            /* if no 'removable' file, it doesn't support offline mem blk */
2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447
            if (errno == ENOENT) {
                error_free(local_err);
                mem_blk->can_offline = false;
            } else {
                error_propagate(errp, local_err);
            }
        } else {
            mem_blk->can_offline = (removable != '0');
        }
    } else {
        if (mem_blk->online != (strncmp(status, "online", 6) == 0)) {
2448
            const char *new_state = mem_blk->online ? "online" : "offline";
2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476

            ga_write_sysfs_file(dirfd, "state", new_state, strlen(new_state),
                                &local_err);
            if (local_err) {
                error_free(local_err);
                result->response =
                    GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED;
                goto out2;
            }

            result->response = GUEST_MEMORY_BLOCK_RESPONSE_TYPE_SUCCESS;
            result->has_error_code = false;
        } /* otherwise pretend successful re-(on|off)-lining */
    }
    g_free(status);
    close(dirfd);
    return;

out2:
    g_free(status);
    close(dirfd);
out1:
    if (!sys2memblk) {
        result->has_error_code = true;
        result->error_code = errno;
    }
}

2477 2478
GuestMemoryBlockList *qmp_guest_get_memory_blocks(Error **errp)
{
2479 2480 2481 2482 2483 2484 2485 2486 2487 2488
    GuestMemoryBlockList *head, **link;
    Error *local_err = NULL;
    struct dirent *de;
    DIR *dp;

    head = NULL;
    link = &head;

    dp = opendir("/sys/devices/system/memory/");
    if (!dp) {
2489 2490 2491 2492 2493 2494
        /* it's ok if this happens to be a system that doesn't expose
         * memory blocks via sysfs, but otherwise we should report
         * an error
         */
        if (errno != ENOENT) {
            error_setg_errno(errp, errno, "Can't open directory"
2495
                             "\"/sys/devices/system/memory/\"");
2496
        }
2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537
        return NULL;
    }

    /* Note: the phys_index of memory block may be discontinuous,
     * this is because a memblk is the unit of the Sparse Memory design, which
     * allows discontinuous memory ranges (ex. NUMA), so here we should
     * traverse the memory block directory.
     */
    while ((de = readdir(dp)) != NULL) {
        GuestMemoryBlock *mem_blk;
        GuestMemoryBlockList *entry;

        if ((strncmp(de->d_name, "memory", 6) != 0) ||
            !(de->d_type & DT_DIR)) {
            continue;
        }

        mem_blk = g_malloc0(sizeof *mem_blk);
        /* The d_name is "memoryXXX",  phys_index is block id, same as XXX */
        mem_blk->phys_index = strtoul(&de->d_name[6], NULL, 10);
        mem_blk->has_can_offline = true; /* lolspeak ftw */
        transfer_memory_block(mem_blk, true, NULL, &local_err);

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

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

    closedir(dp);
    if (local_err == NULL) {
        /* there's no guest with zero memory blocks */
        if (head == NULL) {
            error_setg(errp, "guest reported zero memory blocks!");
        }
        return head;
    }

    qapi_free_GuestMemoryBlockList(head);
    error_propagate(errp, local_err);
2538 2539 2540 2541 2542 2543
    return NULL;
}

GuestMemoryBlockResponseList *
qmp_guest_set_memory_blocks(GuestMemoryBlockList *mem_blks, Error **errp)
{
2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572
    GuestMemoryBlockResponseList *head, **link;
    Error *local_err = NULL;

    head = NULL;
    link = &head;

    while (mem_blks != NULL) {
        GuestMemoryBlockResponse *result;
        GuestMemoryBlockResponseList *entry;
        GuestMemoryBlock *current_mem_blk = mem_blks->value;

        result = g_malloc0(sizeof(*result));
        result->phys_index = current_mem_blk->phys_index;
        transfer_memory_block(current_mem_blk, false, result, &local_err);
        if (local_err) { /* should never happen */
            goto err;
        }
        entry = g_malloc0(sizeof *entry);
        entry->value = result;

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

    return head;
err:
    qapi_free_GuestMemoryBlockResponseList(head);
    error_propagate(errp, local_err);
2573 2574 2575 2576 2577
    return NULL;
}

GuestMemoryBlockInfo *qmp_guest_get_memory_block_info(Error **errp)
{
2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594
    Error *local_err = NULL;
    char *dirpath;
    int dirfd;
    char *buf;
    GuestMemoryBlockInfo *info;

    dirpath = g_strdup_printf("/sys/devices/system/memory/");
    dirfd = open(dirpath, O_RDONLY | O_DIRECTORY);
    if (dirfd == -1) {
        error_setg_errno(errp, errno, "open(\"%s\")", dirpath);
        g_free(dirpath);
        return NULL;
    }
    g_free(dirpath);

    buf = g_malloc0(20);
    ga_read_sysfs_file(dirfd, "block_size_bytes", buf, 20, &local_err);
2595
    close(dirfd);
2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607
    if (local_err) {
        g_free(buf);
        error_propagate(errp, local_err);
        return NULL;
    }

    info = g_new0(GuestMemoryBlockInfo, 1);
    info->size = strtol(buf, NULL, 16); /* the unit is bytes */

    g_free(buf);

    return info;
2608 2609
}

2610 2611
#else /* defined(__linux__) */

2612
void qmp_guest_suspend_disk(Error **errp)
2613
{
2614
    error_setg(errp, QERR_UNSUPPORTED);
2615 2616
}

2617
void qmp_guest_suspend_ram(Error **errp)
2618
{
2619
    error_setg(errp, QERR_UNSUPPORTED);
2620 2621
}

2622
void qmp_guest_suspend_hybrid(Error **errp)
2623
{
2624
    error_setg(errp, QERR_UNSUPPORTED);
2625 2626
}

2627
GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
2628
{
2629
    error_setg(errp, QERR_UNSUPPORTED);
2630
    return NULL;
2631 2632
}

2633 2634
GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp)
{
2635
    error_setg(errp, QERR_UNSUPPORTED);
2636 2637 2638
    return NULL;
}

2639 2640
int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList *vcpus, Error **errp)
{
2641
    error_setg(errp, QERR_UNSUPPORTED);
2642 2643 2644
    return -1;
}

2645 2646 2647 2648 2649
void qmp_guest_set_user_password(const char *username,
                                 const char *password,
                                 bool crypted,
                                 Error **errp)
{
2650
    error_setg(errp, QERR_UNSUPPORTED);
2651 2652
}

2653 2654
GuestMemoryBlockList *qmp_guest_get_memory_blocks(Error **errp)
{
2655
    error_setg(errp, QERR_UNSUPPORTED);
2656 2657 2658 2659 2660 2661
    return NULL;
}

GuestMemoryBlockResponseList *
qmp_guest_set_memory_blocks(GuestMemoryBlockList *mem_blks, Error **errp)
{
2662
    error_setg(errp, QERR_UNSUPPORTED);
2663 2664 2665 2666 2667
    return NULL;
}

GuestMemoryBlockInfo *qmp_guest_get_memory_block_info(Error **errp)
{
2668
    error_setg(errp, QERR_UNSUPPORTED);
2669 2670 2671
    return NULL;
}

2672 2673 2674 2675
#endif

#if !defined(CONFIG_FSFREEZE)

2676 2677
GuestFilesystemInfoList *qmp_guest_get_fsinfo(Error **errp)
{
2678
    error_setg(errp, QERR_UNSUPPORTED);
2679 2680 2681
    return NULL;
}

2682
GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **errp)
2683
{
2684
    error_setg(errp, QERR_UNSUPPORTED);
2685 2686

    return 0;
2687 2688
}

2689
int64_t qmp_guest_fsfreeze_freeze(Error **errp)
2690
{
2691
    error_setg(errp, QERR_UNSUPPORTED);
2692 2693

    return 0;
2694 2695
}

2696 2697 2698 2699
int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints,
                                       strList *mountpoints,
                                       Error **errp)
{
2700
    error_setg(errp, QERR_UNSUPPORTED);
2701 2702 2703 2704

    return 0;
}

2705
int64_t qmp_guest_fsfreeze_thaw(Error **errp)
2706
{
2707
    error_setg(errp, QERR_UNSUPPORTED);
2708 2709

    return 0;
2710
}
2711 2712 2713
#endif /* CONFIG_FSFREEZE */

#if !defined(CONFIG_FSTRIM)
2714 2715
GuestFilesystemTrimResponse *
qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **errp)
2716
{
2717
    error_setg(errp, QERR_UNSUPPORTED);
2718
    return NULL;
2719
}
2720 2721
#endif

2722 2723 2724 2725 2726 2727 2728 2729
/* add unsupported commands to the blacklist */
GList *ga_command_blacklist_init(GList *blacklist)
{
#if !defined(__linux__)
    {
        const char *list[] = {
            "guest-suspend-disk", "guest-suspend-ram",
            "guest-suspend-hybrid", "guest-network-get-interfaces",
2730 2731 2732
            "guest-get-vcpus", "guest-set-vcpus",
            "guest-get-memory-blocks", "guest-set-memory-blocks",
            "guest-get-memory-block-size", NULL};
2733 2734 2735
        char **p = (char **)list;

        while (*p) {
2736
            blacklist = g_list_append(blacklist, g_strdup(*p++));
2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749
        }
    }
#endif

#if !defined(CONFIG_FSFREEZE)
    {
        const char *list[] = {
            "guest-get-fsinfo", "guest-fsfreeze-status",
            "guest-fsfreeze-freeze", "guest-fsfreeze-freeze-list",
            "guest-fsfreeze-thaw", "guest-get-fsinfo", NULL};
        char **p = (char **)list;

        while (*p) {
2750
            blacklist = g_list_append(blacklist, g_strdup(*p++));
2751 2752 2753 2754 2755
        }
    }
#endif

#if !defined(CONFIG_FSTRIM)
2756
    blacklist = g_list_append(blacklist, g_strdup("guest-fstrim"));
2757 2758 2759 2760 2761
#endif

    return blacklist;
}

2762 2763 2764
/* register init/cleanup routines for stateful command groups */
void ga_command_state_init(GAState *s, GACommandState *cs)
{
2765
#if defined(CONFIG_FSFREEZE)
2766
    ga_command_state_add(cs, NULL, guest_fsfreeze_cleanup);
2767
#endif
2768
}
2769

2770 2771
#ifdef HAVE_UTMPX

2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829
#define QGA_MICRO_SECOND_TO_SECOND 1000000

static double ga_get_login_time(struct utmpx *user_info)
{
    double seconds = (double)user_info->ut_tv.tv_sec;
    double useconds = (double)user_info->ut_tv.tv_usec;
    useconds /= QGA_MICRO_SECOND_TO_SECOND;
    return seconds + useconds;
}

GuestUserList *qmp_guest_get_users(Error **err)
{
    GHashTable *cache = NULL;
    GuestUserList *head = NULL, *cur_item = NULL;
    struct utmpx *user_info = NULL;
    gpointer value = NULL;
    GuestUser *user = NULL;
    GuestUserList *item = NULL;
    double login_time = 0;

    cache = g_hash_table_new(g_str_hash, g_str_equal);
    setutxent();

    for (;;) {
        user_info = getutxent();
        if (user_info == NULL) {
            break;
        } else if (user_info->ut_type != USER_PROCESS) {
            continue;
        } else if (g_hash_table_contains(cache, user_info->ut_user)) {
            value = g_hash_table_lookup(cache, user_info->ut_user);
            user = (GuestUser *)value;
            login_time = ga_get_login_time(user_info);
            /* We're ensuring the earliest login time to be sent */
            if (login_time < user->login_time) {
                user->login_time = login_time;
            }
            continue;
        }

        item = g_new0(GuestUserList, 1);
        item->value = g_new0(GuestUser, 1);
        item->value->user = g_strdup(user_info->ut_user);
        item->value->login_time = ga_get_login_time(user_info);

        g_hash_table_insert(cache, item->value->user, item->value);

        if (!cur_item) {
            head = cur_item = item;
        } else {
            cur_item->next = item;
            cur_item = item;
        }
    }
    endutxent();
    g_hash_table_destroy(cache);
    return head;
}
2830 2831 2832 2833 2834 2835 2836 2837 2838 2839

#else

GuestUserList *qmp_guest_get_users(Error **errp)
{
    error_setg(errp, QERR_UNSUPPORTED);
    return NULL;
}

#endif
2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928

/* Replace escaped special characters with theire real values. The replacement
 * is done in place -- returned value is in the original string.
 */
static void ga_osrelease_replace_special(gchar *value)
{
    gchar *p, *p2, quote;

    /* Trim the string at first space or semicolon if it is not enclosed in
     * single or double quotes. */
    if ((value[0] != '"') || (value[0] == '\'')) {
        p = strchr(value, ' ');
        if (p != NULL) {
            *p = 0;
        }
        p = strchr(value, ';');
        if (p != NULL) {
            *p = 0;
        }
        return;
    }

    quote = value[0];
    p2 = value;
    p = value + 1;
    while (*p != 0) {
        if (*p == '\\') {
            p++;
            switch (*p) {
            case '$':
            case '\'':
            case '"':
            case '\\':
            case '`':
                break;
            default:
                /* Keep literal backslash followed by whatever is there */
                p--;
                break;
            }
        } else if (*p == quote) {
            *p2 = 0;
            break;
        }
        *(p2++) = *(p++);
    }
}

static GKeyFile *ga_parse_osrelease(const char *fname)
{
    gchar *content = NULL;
    gchar *content2 = NULL;
    GError *err = NULL;
    GKeyFile *keys = g_key_file_new();
    const char *group = "[os-release]\n";

    if (!g_file_get_contents(fname, &content, NULL, &err)) {
        slog("failed to read '%s', error: %s", fname, err->message);
        goto fail;
    }

    if (!g_utf8_validate(content, -1, NULL)) {
        slog("file is not utf-8 encoded: %s", fname);
        goto fail;
    }
    content2 = g_strdup_printf("%s%s", group, content);

    if (!g_key_file_load_from_data(keys, content2, -1, G_KEY_FILE_NONE,
                                   &err)) {
        slog("failed to parse file '%s', error: %s", fname, err->message);
        goto fail;
    }

    g_free(content);
    g_free(content2);
    return keys;

fail:
    g_error_free(err);
    g_free(content);
    g_free(content2);
    g_key_file_free(keys);
    return NULL;
}

GuestOSInfo *qmp_guest_get_osinfo(Error **errp)
{
    GuestOSInfo *info = NULL;
    struct utsname kinfo;
2929 2930
    GKeyFile *osrelease = NULL;
    const char *qga_os_release = g_getenv("QGA_OS_RELEASE");
2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944

    info = g_new0(GuestOSInfo, 1);

    if (uname(&kinfo) != 0) {
        error_setg_errno(errp, errno, "uname failed");
    } else {
        info->has_kernel_version = true;
        info->kernel_version = g_strdup(kinfo.version);
        info->has_kernel_release = true;
        info->kernel_release = g_strdup(kinfo.release);
        info->has_machine = true;
        info->machine = g_strdup(kinfo.machine);
    }

2945 2946 2947 2948 2949 2950 2951
    if (qga_os_release != NULL) {
        osrelease = ga_parse_osrelease(qga_os_release);
    } else {
        osrelease = ga_parse_osrelease("/etc/os-release");
        if (osrelease == NULL) {
            osrelease = ga_parse_osrelease("/usr/lib/os-release");
        }
2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978
    }

    if (osrelease != NULL) {
        char *value;

#define GET_FIELD(field, osfield) do { \
    value = g_key_file_get_value(osrelease, "os-release", osfield, NULL); \
    if (value != NULL) { \
        ga_osrelease_replace_special(value); \
        info->has_ ## field = true; \
        info->field = value; \
    } \
} while (0)
        GET_FIELD(id, "ID");
        GET_FIELD(name, "NAME");
        GET_FIELD(pretty_name, "PRETTY_NAME");
        GET_FIELD(version, "VERSION");
        GET_FIELD(version_id, "VERSION_ID");
        GET_FIELD(variant, "VARIANT");
        GET_FIELD(variant_id, "VARIANT_ID");
#undef GET_FIELD

        g_key_file_free(osrelease);
    }

    return info;
}