virfile.c 116.2 KB
Newer Older
1
/*
E
Eric Blake 已提交
2
 * virfile.c: safer file handling
3
 *
4
 * Copyright (C) 2010-2014 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
 * Copyright (C) 2010 IBM Corporation
 * Copyright (C) 2010 Stefan Berger
 * Copyright (C) 2010 Eric Blake
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
20
 * License along with this library.  If not, see
O
Osier Yang 已提交
21
 * <http://www.gnu.org/licenses/>.
22 23 24 25
 *
 */

#include <config.h>
26
#include "internal.h"
27

28
#include <passfd.h>
29
#include <fcntl.h>
30
#include <pty.h>
31
#include <sys/stat.h>
32 33 34
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
35 36 37
#if defined(HAVE_SYS_MOUNT_H)
# include <sys/mount.h>
#endif
38
#include <unistd.h>
39
#include <dirent.h>
40 41 42 43
#include <dirname.h>
#if defined HAVE_MNTENT_H && defined HAVE_GETMNTENT_R
# include <mntent.h>
#endif
E
Eric Blake 已提交
44 45 46
#if HAVE_MMAP
# include <sys/mman.h>
#endif
47 48 49
#if HAVE_SYS_SYSCALL_H
# include <sys/syscall.h>
#endif
M
Michal Privoznik 已提交
50 51 52
#if HAVE_SYS_ACL_H
# include <sys/acl.h>
#endif
M
Martin Kletzander 已提交
53
#include <sys/file.h>
54

55 56 57 58 59
#ifdef __linux__
# if HAVE_LINUX_MAGIC_H
#  include <linux/magic.h>
# endif
# include <sys/statfs.h>
60 61 62
# if HAVE_DECL_LO_FLAGS_AUTOCLEAR
#  include <linux/loop.h>
# endif
63 64
# include <sys/ioctl.h>
# include <linux/cdrom.h>
65
#endif
66

67 68 69 70
#if HAVE_LIBATTR
# include <sys/xattr.h>
#endif

71
#include "configmake.h"
72
#include "intprops.h"
73
#include "viralloc.h"
74
#include "vircommand.h"
75
#include "virerror.h"
76
#include "virfile.h"
77
#include "virkmod.h"
78
#include "virlog.h"
79
#include "virprocess.h"
80
#include "virstring.h"
81
#include "virutil.h"
82

83
#include "c-ctype.h"
84
#include "areadlink.h"
85

86
#define VIR_FROM_THIS VIR_FROM_NONE
87

88 89
VIR_LOG_INIT("util.file");

90
int virFileClose(int *fdptr, virFileCloseFlags flags)
91
{
92
    int saved_errno = 0;
93 94
    int rc = 0;

95 96 97
    if (*fdptr < 0)
        return 0;

98
    if (flags & VIR_FILE_CLOSE_PRESERVE_ERRNO)
99 100 101
        saved_errno = errno;

    rc = close(*fdptr);
102 103 104 105 106 107 108 109 110 111 112

    if (!(flags & VIR_FILE_CLOSE_DONT_LOG)) {
        if (rc < 0) {
            if (errno == EBADF) {
                if (!(flags & VIR_FILE_CLOSE_IGNORE_EBADF))
                    VIR_WARN("Tried to close invalid fd %d", *fdptr);
            } else {
                char ebuf[1024] ATTRIBUTE_UNUSED;
                VIR_DEBUG("Failed to close fd %d: %s",
                          *fdptr, virStrerror(errno, ebuf, sizeof(ebuf)));
            }
113
        } else {
114
            VIR_DEBUG("Closed fd %d", *fdptr);
115
        }
116
    }
117
    *fdptr = -1;
118 119

    if (flags & VIR_FILE_CLOSE_PRESERVE_ERRNO)
120
        errno = saved_errno;
121 122 123

    return rc;
}
124 125


E
Eric Blake 已提交
126
int virFileFclose(FILE **file, bool preserve_errno)
127
{
128
    int saved_errno = 0;
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
    int rc = 0;

    if (*file) {
        if (preserve_errno)
            saved_errno = errno;
        rc = fclose(*file);
        *file = NULL;
        if (preserve_errno)
            errno = saved_errno;
    }

    return rc;
}


E
Eric Blake 已提交
144
FILE *virFileFdopen(int *fdptr, const char *mode)
145 146 147 148 149 150 151 152 153 154 155 156 157
{
    FILE *file = NULL;

    if (*fdptr >= 0) {
        file = fdopen(*fdptr, mode);
        if (file)
            *fdptr = -1;
    } else {
        errno = EBADF;
    }

    return file;
}
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175


/**
 * virFileDirectFdFlag:
 *
 * Returns 0 if the kernel can avoid file system cache pollution
 * without any additional flags, O_DIRECT if the original fd must be
 * opened in direct mode, or -1 if there is no support for bypassing
 * the file system cache.
 */
int
virFileDirectFdFlag(void)
{
    /* XXX For now, Linux posix_fadvise is not powerful enough to
     * avoid O_DIRECT.  */
    return O_DIRECT ? O_DIRECT : -1;
}

J
Jiri Denemark 已提交
176 177 178
/* Opaque type for managing a wrapper around a fd.  For now,
 * read-write is not supported, just a single direction.  */
struct _virFileWrapperFd {
179
    bool closed; /* Whether virFileWrapperFdClose() has been already called */
J
Jiri Denemark 已提交
180
    virCommandPtr cmd; /* Child iohelper process to do the I/O.  */
181
    char *err_msg; /* stderr of @cmd */
J
Jiri Denemark 已提交
182 183 184
};

#ifndef WIN32
185
/**
J
Jiri Denemark 已提交
186
 * virFileWrapperFdNew:
187 188
 * @fd: pointer to fd to wrap
 * @name: name of fd, for diagnostics
J
Jiri Denemark 已提交
189 190 191 192 193 194 195 196
 * @flags: bitwise-OR of virFileWrapperFdFlags
 *
 * Update @fd so that it meets parameters requested by @flags.
 *
 * If VIR_FILE_WRAPPER_BYPASS_CACHE bit is set in @flags, @fd will be updated
 * in a way that all I/O to that file will bypass the system cache.  The
 * original fd must have been created with virFileDirectFdFlag() among the
 * flags to open().
197
 *
J
Jiri Denemark 已提交
198 199 200 201 202 203 204 205 206
 * If VIR_FILE_WRAPPER_NON_BLOCKING bit is set in @flags, @fd will be updated
 * to ensure it properly supports non-blocking I/O, i.e., it will report
 * EAGAIN.
 *
 * This must be called after open() and optional fchown() or fchmod(), but
 * before any seek or I/O, and only on seekable fd.  The file must be O_RDONLY
 * (to read the entire existing file) or O_WRONLY (to write to an empty file).
 * In some cases, @fd is changed to a non-seekable pipe; in this case, the
 * caller must not do anything further with the original fd.
207 208
 *
 * On success, the new wrapper object is returned, which must be later
J
Jiri Denemark 已提交
209
 * freed with virFileWrapperFdFree().  On failure, @fd is unchanged, an
210 211
 * error message is output, and NULL is returned.
 */
J
Jiri Denemark 已提交
212 213
virFileWrapperFdPtr
virFileWrapperFdNew(int *fd, const char *name, unsigned int flags)
214
{
J
Jiri Denemark 已提交
215
    virFileWrapperFdPtr ret = NULL;
216 217 218
    bool output = false;
    int pipefd[2] = { -1, -1 };
    int mode = -1;
219
    VIR_AUTOFREE(char *) iohelper_path = NULL;
220

J
Jiri Denemark 已提交
221
    if (!flags) {
222 223
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("invalid use with no flags"));
J
Jiri Denemark 已提交
224 225 226 227 228 229 230 231 232
        return NULL;
    }

    /* XXX support posix_fadvise rather than O_DIRECT, if the kernel support
     * for that is decent enough. In that case, we will also need to
     * explicitly support VIR_FILE_WRAPPER_NON_BLOCKING since
     * VIR_FILE_WRAPPER_BYPASS_CACHE alone will no longer require spawning
     * iohelper.
     */
233

J
Jiri Denemark 已提交
234
    if ((flags & VIR_FILE_WRAPPER_BYPASS_CACHE) && !O_DIRECT) {
235 236
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("O_DIRECT unsupported on this platform"));
237 238 239
        return NULL;
    }

240
    if (VIR_ALLOC(ret) < 0)
241 242 243 244 245
        return NULL;

    mode = fcntl(*fd, F_GETFL);

    if (mode < 0) {
246 247
        virReportError(VIR_ERR_INTERNAL_ERROR, _("invalid fd %d for %s"),
                       *fd, name);
248 249 250 251
        goto error;
    } else if ((mode & O_ACCMODE) == O_WRONLY) {
        output = true;
    } else if ((mode & O_ACCMODE) != O_RDONLY) {
252
        virReportError(VIR_ERR_INTERNAL_ERROR, _("unexpected mode 0x%x for %s"),
253
                       mode & O_ACCMODE, name);
254 255 256 257
        goto error;
    }

    if (pipe2(pipefd, O_CLOEXEC) < 0) {
258 259
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unable to create pipe for %s"), name);
260 261 262
        goto error;
    }

263
    if (!(iohelper_path = virFileFindResource("libvirt_iohelper",
264
                                              abs_top_builddir "/src",
265 266 267
                                              LIBEXECDIR)))
        goto error;

268
    ret->cmd = virCommandNewArgList(iohelper_path, name, NULL);
269

270 271 272 273 274 275 276 277 278 279
    if (output) {
        virCommandSetInputFD(ret->cmd, pipefd[0]);
        virCommandSetOutputFD(ret->cmd, fd);
        virCommandAddArg(ret->cmd, "1");
    } else {
        virCommandSetInputFD(ret->cmd, *fd);
        virCommandSetOutputFD(ret->cmd, &pipefd[1]);
        virCommandAddArg(ret->cmd, "0");
    }

280 281
    /* In order to catch iohelper stderr, we must change
     * iohelper's env so virLog functions print to stderr
282 283
     */
    virCommandAddEnvPair(ret->cmd, "LIBVIRT_LOG_OUTPUTS", "1:stderr");
284 285
    virCommandSetErrorBuffer(ret->cmd, &ret->err_msg);
    virCommandDoAsyncIO(ret->cmd);
286

287 288 289 290
    if (virCommandRunAsync(ret->cmd, NULL) < 0)
        goto error;

    if (VIR_CLOSE(pipefd[!output]) < 0) {
291
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("unable to close pipe"));
292 293 294 295 296 297 298
        goto error;
    }

    VIR_FORCE_CLOSE(*fd);
    *fd = pipefd[output];
    return ret;

299
 error:
300 301
    VIR_FORCE_CLOSE(pipefd[0]);
    VIR_FORCE_CLOSE(pipefd[1]);
J
Jiri Denemark 已提交
302
    virFileWrapperFdFree(ret);
303 304
    return NULL;
}
J
Jiri Denemark 已提交
305 306 307 308 309 310
#else
virFileWrapperFdPtr
virFileWrapperFdNew(int *fd ATTRIBUTE_UNUSED,
                    const char *name ATTRIBUTE_UNUSED,
                    unsigned int fdflags ATTRIBUTE_UNUSED)
{
311
    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
312
                   _("virFileWrapperFd unsupported on this platform"));
J
Jiri Denemark 已提交
313 314 315
    return NULL;
}
#endif
316 317

/**
J
Jiri Denemark 已提交
318 319
 * virFileWrapperFdClose:
 * @wfd: fd wrapper, or NULL
320
 *
J
Jiri Denemark 已提交
321
 * If @wfd is valid, then ensure that I/O has completed, which may
322 323
 * include reaping a child process.  Return 0 if all data for the
 * wrapped fd is complete, or -1 on failure with an error emitted.
J
Jiri Denemark 已提交
324 325
 * This function intentionally returns 0 when @wfd is NULL, so that
 * callers can conditionally create a virFileWrapperFd wrapper but
326
 * unconditionally call the cleanup code.  To avoid deadlock, only
J
Jiri Denemark 已提交
327
 * call this after closing the fd resulting from virFileWrapperFdNew().
328 329
 *
 * This function can be safely called multiple times on the same @wfd.
330 331
 */
int
J
Jiri Denemark 已提交
332
virFileWrapperFdClose(virFileWrapperFdPtr wfd)
333
{
334 335
    int ret;

336
    if (!wfd || wfd->closed)
337 338
        return 0;

339
    ret = virCommandWait(wfd->cmd, NULL);
340

341 342 343 344 345 346 347 348
    /* If the command used to process I/O has failed and produced some
     * messages on stderr, it's fair to assume those will be more
     * relevant to the user than whatever eg. QEMU can figure out on its
     * own having no knowledge of the fact a command is handling its I/O
     * in the first place, so it's okay if we end up discarding an
     * existing error here */
    if (ret < 0 && wfd->err_msg && *wfd->err_msg)
        virReportError(VIR_ERR_OPERATION_FAILED, "%s", wfd->err_msg);
349

350 351
    wfd->closed = true;

352 353
    return ret;
}
354

355
/**
J
Jiri Denemark 已提交
356 357
 * virFileWrapperFdFree:
 * @wfd: fd wrapper, or NULL
358
 *
J
Jiri Denemark 已提交
359 360
 * Free all remaining resources associated with @wfd.  If
 * virFileWrapperFdClose() was not previously called, then this may
361
 * discard some previous I/O.  To avoid deadlock, only call this after
J
Jiri Denemark 已提交
362
 * closing the fd resulting from virFileWrapperFdNew().
363 364
 */
void
J
Jiri Denemark 已提交
365
virFileWrapperFdFree(virFileWrapperFdPtr wfd)
366
{
J
Jiri Denemark 已提交
367
    if (!wfd)
368 369
        return;

370
    VIR_FREE(wfd->err_msg);
J
Jiri Denemark 已提交
371 372
    virCommandFree(wfd->cmd);
    VIR_FREE(wfd);
373
}
374 375 376


#ifndef WIN32
M
Martin Kletzander 已提交
377

378 379 380 381 382 383
/**
 * virFileLock:
 * @fd: file descriptor to acquire the lock on
 * @shared: type of lock to acquire
 * @start: byte offset to start lock
 * @len: length of lock (0 to acquire entire remaining file from @start)
384
 * @waitForLock: wait for previously held lock or not
385 386 387 388 389
 *
 * Attempt to acquire a lock on the file @fd. If @shared
 * is true, then a shared lock will be acquired,
 * otherwise an exclusive lock will be acquired. If
 * the lock cannot be acquired, an error will be
390 391
 * returned. If @waitForLock is true, this will wait
 * for the lock if another process has already acquired it.
392 393 394 395 396 397 398 399 400 401
 *
 * The lock will be released when @fd is closed. The lock
 * will also be released if *any* other open file descriptor
 * pointing to the same underlying file is closed. As such
 * this function should not be relied on in multi-threaded
 * apps where other threads can be opening/closing arbitrary
 * files.
 *
 * Returns 0 on success, or -errno otherwise
 */
402
int virFileLock(int fd, bool shared, off_t start, off_t len, bool waitForLock)
403 404 405 406 407 408 409 410
{
    struct flock fl = {
        .l_type = shared ? F_RDLCK : F_WRLCK,
        .l_whence = SEEK_SET,
        .l_start = start,
        .l_len = len,
    };

411 412 413
    int cmd = waitForLock ? F_SETLKW : F_SETLK;

    if (fcntl(fd, cmd, &fl) < 0)
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
        return -errno;

    return 0;
}


/**
 * virFileUnlock:
 * @fd: file descriptor to release the lock on
 * @start: byte offset to start unlock
 * @len: length of lock (0 to release entire remaining file from @start)
 *
 * Release a lock previously acquired with virFileUnlock().
 * NB the lock will also be released if any open file descriptor
 * pointing to the same file as @fd is closed
 *
C
Chen Hanxiao 已提交
430
 * Returns 0 on success, or -errno on error
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
 */
int virFileUnlock(int fd, off_t start, off_t len)
{
    struct flock fl = {
        .l_type = F_UNLCK,
        .l_whence = SEEK_SET,
        .l_start = start,
        .l_len = len,
    };

    if (fcntl(fd, F_SETLK, &fl) < 0)
        return -errno;

    return 0;
}
M
Martin Kletzander 已提交
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469


/**
 * virFileFlock:
 * @fd: file descriptor to call flock on
 * @lock: true for lock, false for unlock
 * @shared: true if shared, false for exclusive, ignored if `@lock == false`
 *
 * This is just a simple wrapper around flock(2) that errors out on unsupported
 * platforms.
 *
 * The lock will be released when @fd is closed or this function is called with
 * `@lock == false`.
 *
 * Returns 0 on success, -1 otherwise (with errno set)
 */
int virFileFlock(int fd, bool lock, bool shared)
{
    if (lock)
        return flock(fd, shared ? LOCK_SH : LOCK_EX);

    return flock(fd, LOCK_UN);
}

470
#else
M
Martin Kletzander 已提交
471

472 473 474
int virFileLock(int fd ATTRIBUTE_UNUSED,
                bool shared ATTRIBUTE_UNUSED,
                off_t start ATTRIBUTE_UNUSED,
475 476
                off_t len ATTRIBUTE_UNUSED,
                bool waitForLock ATTRIBUTE_UNUSED)
477 478 479
{
    return -ENOSYS;
}
M
Martin Kletzander 已提交
480 481


482 483 484 485 486 487
int virFileUnlock(int fd ATTRIBUTE_UNUSED,
                  off_t start ATTRIBUTE_UNUSED,
                  off_t len ATTRIBUTE_UNUSED)
{
    return -ENOSYS;
}
M
Martin Kletzander 已提交
488 489 490 491 492 493 494 495 496 497


int virFileFlock(int fd ATTRIBUTE_UNUSED,
                 bool lock ATTRIBUTE_UNUSED,
                 bool shared ATTRIBUTE_UNUSED)
{
    errno = ENOSYS;
    return -1;
}

498
#endif
499

M
Martin Kletzander 已提交
500

501 502 503 504
int
virFileRewrite(const char *path,
               mode_t mode,
               virFileRewriteFunc rewrite,
505
               const void *opaque)
506
{
507
    VIR_AUTOFREE(char *) newfile = NULL;
508 509 510
    int fd = -1;
    int ret = -1;

511
    if (virAsprintf(&newfile, "%s.new", path) < 0)
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
        goto cleanup;

    if ((fd = open(newfile, O_WRONLY | O_CREAT | O_TRUNC, mode)) < 0) {
        virReportSystemError(errno, _("cannot create file '%s'"),
                             newfile);
        goto cleanup;
    }

    if (rewrite(fd, opaque) < 0) {
        virReportSystemError(errno, _("cannot write data to file '%s'"),
                             newfile);
        goto cleanup;
    }

    if (fsync(fd) < 0) {
        virReportSystemError(errno, _("cannot sync file '%s'"),
                             newfile);
        goto cleanup;
    }

    if (VIR_CLOSE(fd) < 0) {
        virReportSystemError(errno, _("cannot save file '%s'"),
                             newfile);
        goto cleanup;
    }

    if (rename(newfile, path) < 0) {
        virReportSystemError(errno, _("cannot rename file '%s' as '%s'"),
                             newfile, path);
        goto cleanup;
    }

    ret = 0;

546
 cleanup:
547
    VIR_FORCE_CLOSE(fd);
548
    if (newfile)
549 550 551
        unlink(newfile);
    return ret;
}
552 553


554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
static int
virFileRewriteStrHelper(int fd, const void *opaque)
{
    const char *data = opaque;

    if (safewrite(fd, data, strlen(data)) < 0)
        return -1;

    return 0;
}


int
virFileRewriteStr(const char *path,
                  mode_t mode,
                  const char *str)
{
    return virFileRewrite(path, mode,
                          virFileRewriteStrHelper, str);
}


576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
int virFileTouch(const char *path, mode_t mode)
{
    int fd = -1;

    if ((fd = open(path, O_WRONLY | O_CREAT, mode)) < 0) {
        virReportSystemError(errno, _("cannot create file '%s'"),
                             path);
        return -1;
    }

    if (VIR_CLOSE(fd) < 0) {
        virReportSystemError(errno, _("cannot save file '%s'"),
                             path);
        VIR_FORCE_CLOSE(fd);
        return -1;
    }

    return 0;
}
595 596 597 598 599 600 601 602 603 604 605 606


#define MODE_BITS (S_ISUID | S_ISGID | S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO)

int virFileUpdatePerm(const char *path,
                      mode_t mode_remove,
                      mode_t mode_add)
{
    struct stat sb;
    mode_t mode;

    if (mode_remove & ~MODE_BITS || mode_add & ~MODE_BITS) {
607
        virReportError(VIR_ERR_INVALID_ARG, "%s", _("invalid mode"));
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
        return -1;
    }

    if (stat(path, &sb) < 0) {
        virReportSystemError(errno, _("cannot stat '%s'"), path);
        return -1;
    }

    mode = sb.st_mode & MODE_BITS;

    if ((mode & mode_remove) == 0 && (mode & mode_add) == mode_add)
        return 0;

    mode &= MODE_BITS ^ mode_remove;
    mode |= mode_add;

    if (chmod(path, mode) < 0) {
        virReportSystemError(errno, _("cannot change permission of '%s'"),
                             path);
        return -1;
    }

    return 0;
}
632 633


634
#if defined(__linux__) && HAVE_DECL_LO_FLAGS_AUTOCLEAR
635 636 637

# if HAVE_DECL_LOOP_CTL_GET_FREE

N
Nehal J Wani 已提交
638
/* virFileLoopDeviceOpenLoopCtl() returns -1 when a real failure has occurred
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
 * while in the process of allocating or opening the loop device.  On success
 * we return 0 and modify the fd to the appropriate file descriptor.
 * If /dev/loop-control does not exist, we return 0 and do not set fd. */

static int virFileLoopDeviceOpenLoopCtl(char **dev_name, int *fd)
{
    int devnr;
    int ctl_fd;
    char *looppath = NULL;

    VIR_DEBUG("Opening loop-control device");
    if ((ctl_fd = open("/dev/loop-control", O_RDWR)) < 0) {
        if (errno == ENOENT)
            return 0;

        virReportSystemError(errno, "%s",
                             _("Unable to open /dev/loop-control"));
        return -1;
    }

    if ((devnr = ioctl(ctl_fd, LOOP_CTL_GET_FREE)) < 0) {
        virReportSystemError(errno, "%s",
                             _("Unable to get free loop device via ioctl"));
        close(ctl_fd);
        return -1;
    }
    close(ctl_fd);

    VIR_DEBUG("Found free loop device number %i", devnr);

    if (virAsprintf(&looppath, "/dev/loop%i", devnr) < 0)
        return -1;

    if ((*fd = open(looppath, O_RDWR)) < 0) {
        virReportSystemError(errno,
674
                             _("Unable to open %s"), looppath);
675 676 677 678 679 680 681 682 683 684
        VIR_FREE(looppath);
        return -1;
    }

    *dev_name = looppath;
    return 0;
}
# endif /* HAVE_DECL_LOOP_CTL_GET_FREE */

static int virFileLoopDeviceOpenSearch(char **dev_name)
685 686 687 688
{
    int fd = -1;
    DIR *dh = NULL;
    struct dirent *de;
689
    char *looppath = NULL;
690
    struct loop_info64 lo;
E
Eric Blake 已提交
691
    int direrr;
692 693 694

    VIR_DEBUG("Looking for loop devices in /dev");

J
Ján Tomko 已提交
695
    if (virDirOpen(&dh, "/dev") < 0)
696 697
        goto cleanup;

E
Eric Blake 已提交
698
    while ((direrr = virDirRead(dh, &de, "/dev")) > 0) {
699 700 701 702 703
        /* Checking 'loop' prefix is insufficient, since
         * new kernels have a dev named 'loop-control'
         */
        if (!STRPREFIX(de->d_name, "loop") ||
            !c_isdigit(de->d_name[4]))
704 705
            continue;

706
        if (virAsprintf(&looppath, "/dev/%s", de->d_name) < 0)
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731
            goto cleanup;

        VIR_DEBUG("Checking up on device %s", looppath);
        if ((fd = open(looppath, O_RDWR)) < 0) {
            virReportSystemError(errno,
                                 _("Unable to open %s"), looppath);
            goto cleanup;
        }

        if (ioctl(fd, LOOP_GET_STATUS64, &lo) < 0) {
            /* Got a free device, return the fd */
            if (errno == ENXIO)
                goto cleanup;

            VIR_FORCE_CLOSE(fd);
            virReportSystemError(errno,
                                 _("Unable to get loop status on %s"),
                                 looppath);
            goto cleanup;
        }

        /* Oh well, try the next device */
        VIR_FORCE_CLOSE(fd);
        VIR_FREE(looppath);
    }
E
Eric Blake 已提交
732 733 734 735
    if (direrr < 0)
        goto cleanup;
    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                   _("Unable to find a free loop device in /dev"));
736

737
 cleanup:
738 739 740 741 742 743 744
    if (fd != -1) {
        VIR_DEBUG("Got free loop device %s %d", looppath, fd);
        *dev_name = looppath;
    } else {
        VIR_DEBUG("No free loop devices available");
        VIR_FREE(looppath);
    }
J
Ján Tomko 已提交
745
    VIR_DIR_CLOSE(dh);
746 747 748
    return fd;
}

749 750 751 752 753 754 755 756
static int virFileLoopDeviceOpen(char **dev_name)
{
    int loop_fd = -1;

# if HAVE_DECL_LOOP_CTL_GET_FREE
    if (virFileLoopDeviceOpenLoopCtl(dev_name, &loop_fd) < 0)
        return -1;

J
Jiri Denemark 已提交
757
    VIR_DEBUG("Return from loop-control got fd %d", loop_fd);
758 759 760 761 762 763 764 765 766 767

    if (loop_fd >= 0)
        return loop_fd;
# endif /* HAVE_DECL_LOOP_CTL_GET_FREE */

    /* Without the loop control device we just use the old technique. */
    loop_fd = virFileLoopDeviceOpenSearch(dev_name);

    return loop_fd;
}
768 769 770 771 772 773 774

int virFileLoopDeviceAssociate(const char *file,
                               char **dev)
{
    int lofd = -1;
    int fsfd = -1;
    struct loop_info64 lo;
775
    VIR_AUTOFREE(char *) loname = NULL;
776 777 778 779 780 781 782 783
    int ret = -1;

    if ((lofd = virFileLoopDeviceOpen(&loname)) < 0)
        return -1;

    memset(&lo, 0, sizeof(lo));
    lo.lo_flags = LO_FLAGS_AUTOCLEAR;

784 785 786 787 788 789 790 791
    /* Set backing file name for LOOP_GET_STATUS64 queries */
    if (virStrncpy((char *) lo.lo_file_name, file,
                   strlen(file), LO_NAME_SIZE) < 0) {
        virReportSystemError(errno,
                             _("Unable to set backing file %s"), file);
        goto cleanup;
    }

792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
    if ((fsfd = open(file, O_RDWR)) < 0) {
        virReportSystemError(errno,
                             _("Unable to open %s"), file);
        goto cleanup;
    }

    if (ioctl(lofd, LOOP_SET_FD, fsfd) < 0) {
        virReportSystemError(errno,
                             _("Unable to attach %s to loop device"),
                             file);
        goto cleanup;
    }

    if (ioctl(lofd, LOOP_SET_STATUS64, &lo) < 0) {
        virReportSystemError(errno, "%s",
                             _("Unable to mark loop device as autoclear"));

        if (ioctl(lofd, LOOP_CLR_FD, 0) < 0)
            VIR_WARN("Unable to detach %s from loop device", file);
        goto cleanup;
    }

    VIR_DEBUG("Attached loop device  %s %d to %s", file, lofd, loname);
    *dev = loname;
    loname = NULL;

    ret = 0;

820
 cleanup:
821 822 823 824 825 826
    VIR_FORCE_CLOSE(fsfd);
    if (ret == -1)
        VIR_FORCE_CLOSE(lofd);
    return lofd;
}

827 828

# define SYSFS_BLOCK_DIR "/sys/block"
829
# define NBD_DRIVER "nbd"
830 831 832


static int
833
virFileNBDDeviceIsBusy(const char *dev_name)
834
{
835
    VIR_AUTOFREE(char *) path = NULL;
836 837

    if (virAsprintf(&path, SYSFS_BLOCK_DIR "/%s/pid",
838
                    dev_name) < 0)
839 840
        return -1;

841
    if (!virFileExists(path)) {
842
        if (errno == ENOENT)
843
            return 0;
844 845 846
        else
            virReportSystemError(errno,
                                 _("Cannot check NBD device %s pid"),
847
                                 dev_name);
848
        return -1;
849
    }
850
    return 1;
851 852 853 854 855 856 857 858 859
}


static char *
virFileNBDDeviceFindUnused(void)
{
    DIR *dh;
    char *ret = NULL;
    struct dirent *de;
E
Eric Blake 已提交
860
    int direrr;
861

J
Ján Tomko 已提交
862
    if (virDirOpen(&dh, SYSFS_BLOCK_DIR) < 0)
863 864
        return NULL;

E
Eric Blake 已提交
865
    while ((direrr = virDirRead(dh, &de, SYSFS_BLOCK_DIR)) > 0) {
866 867 868 869 870
        if (STRPREFIX(de->d_name, "nbd")) {
            int rv = virFileNBDDeviceIsBusy(de->d_name);
            if (rv < 0)
                goto cleanup;
            if (rv == 0) {
871
                ignore_value(virAsprintf(&ret, "/dev/%s", de->d_name));
872 873 874 875
                goto cleanup;
            }
        }
    }
E
Eric Blake 已提交
876 877 878 879
    if (direrr < 0)
        goto cleanup;
    virReportSystemError(EBUSY, "%s",
                         _("No free NBD devices"));
880

881
 cleanup:
J
Ján Tomko 已提交
882
    VIR_DIR_CLOSE(dh);
883 884 885
    return ret;
}

886 887 888 889
static bool
virFileNBDLoadDriver(void)
{
    if (virKModIsBlacklisted(NBD_DRIVER)) {
890
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
891 892 893 894
                       _("Failed to load nbd module: "
                         "administratively prohibited"));
        return false;
    } else {
895
        VIR_AUTOFREE(char *) errbuf = NULL;
896 897

        if ((errbuf = virKModLoad(NBD_DRIVER, true))) {
898
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
899 900 901 902 903 904
                           _("Failed to load nbd module"));
            return false;
        }
    }
    return true;
}
905 906

int virFileNBDDeviceAssociate(const char *file,
907
                              virStorageFileFormat fmt,
908 909 910
                              bool readonly,
                              char **dev)
{
911 912
    VIR_AUTOFREE(char *) nbddev = NULL;
    VIR_AUTOFREE(char *) qemunbd = NULL;
913
    VIR_AUTOPTR(virCommand) cmd = NULL;
914 915
    const char *fmtstr = NULL;

916
    if (!virFileNBDLoadDriver())
917
        return -1;
918

919
    if (!(nbddev = virFileNBDDeviceFindUnused()))
920
        return -1;
921 922 923 924

    if (!(qemunbd = virFindFileInPath("qemu-nbd"))) {
        virReportSystemError(ENOENT, "%s",
                             _("Unable to find 'qemu-nbd' binary in $PATH"));
925
        return -1;
926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949
    }

    if (fmt > 0)
        fmtstr = virStorageFileFormatTypeToString(fmt);

    cmd = virCommandNew(qemunbd);

    /* Explicitly not trying to cope with old qemu-nbd which
     * lacked --format. We want to see a fatal error in that
     * case since it would be security flaw to continue */
    if (fmtstr)
        virCommandAddArgList(cmd, "--format", fmtstr, NULL);

    if (readonly)
        virCommandAddArg(cmd, "-r");

    virCommandAddArgList(cmd,
                         "-n", /* Don't cache in qemu-nbd layer */
                         "-c", nbddev,
                         file, NULL);

    /* qemu-nbd will daemonize itself */

    if (virCommandRun(cmd, NULL) < 0)
950
        return -1;
951

952 953
    VIR_DEBUG("Associated NBD device %s with file %s and format %s",
              nbddev, file, fmtstr);
954 955 956
    *dev = nbddev;
    nbddev = NULL;

957
    return 0;
958 959
}

960 961 962
#else /* __linux__ */

int virFileLoopDeviceAssociate(const char *file,
963
                               char **dev ATTRIBUTE_UNUSED)
964 965 966 967
{
    virReportSystemError(ENOSYS,
                         _("Unable to associate file %s with loop device"),
                         file);
968 969
    *dev = NULL;
    return -1;
970 971
}

972
int virFileNBDDeviceAssociate(const char *file,
973
                              virStorageFileFormat fmt ATTRIBUTE_UNUSED,
974 975 976 977 978 979 980 981 982
                              bool readonly ATTRIBUTE_UNUSED,
                              char **dev ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS,
                         _("Unable to associate file %s with NBD device"),
                         file);
    return -1;
}

983
#endif /* __linux__ */
984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999


/**
 * virFileDeleteTree:
 *
 * Recursively deletes all files / directories
 * starting from the directory @dir. Does not
 * follow symlinks
 *
 * NB the algorithm is not efficient, and is subject to
 * race conditions which can be exploited by malicious
 * code. It should not be used in any scenarios where
 * performance is important, or security is critical.
 */
int virFileDeleteTree(const char *dir)
{
1000
    DIR *dh;
1001 1002
    struct dirent *de;
    int ret = -1;
E
Eric Blake 已提交
1003
    int direrr;
1004

1005 1006 1007 1008
    /* Silently return 0 if passed NULL or directory doesn't exist */
    if (!dir || !virFileExists(dir))
        return 0;

J
Ján Tomko 已提交
1009
    if (virDirOpen(&dh, dir) < 0)
1010 1011
        return -1;

E
Eric Blake 已提交
1012
    while ((direrr = virDirRead(dh, &de, dir)) > 0) {
1013
        VIR_AUTOFREE(char *) filepath = NULL;
1014 1015 1016
        struct stat sb;

        if (virAsprintf(&filepath, "%s/%s",
1017
                        dir, de->d_name) < 0)
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
            goto cleanup;

        if (lstat(filepath, &sb) < 0) {
            virReportSystemError(errno, _("Cannot access '%s'"),
                                 filepath);
            goto cleanup;
        }

        if (S_ISDIR(sb.st_mode)) {
            if (virFileDeleteTree(filepath) < 0)
                goto cleanup;
        } else {
            if (unlink(filepath) < 0 && errno != ENOENT) {
                virReportSystemError(errno,
                                     _("Cannot delete file '%s'"),
                                     filepath);
                goto cleanup;
            }
        }
    }
E
Eric Blake 已提交
1038
    if (direrr < 0)
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
        goto cleanup;

    if (rmdir(dir) < 0 && errno != ENOENT) {
        virReportSystemError(errno,
                             _("Cannot delete directory '%s'"),
                             dir);
        goto cleanup;
    }

    ret = 0;

1050
 cleanup:
J
Ján Tomko 已提交
1051
    VIR_DIR_CLOSE(dh);
1052 1053
    return ret;
}
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103

/* Like read(), but restarts after EINTR.  Doesn't play
 * nicely with nonblocking FD and EAGAIN, in which case
 * you want to use bare read(). Or even use virSocket()
 * if the FD is related to a socket rather than a plain
 * file or pipe. */
ssize_t
saferead(int fd, void *buf, size_t count)
{
    size_t nread = 0;
    while (count > 0) {
        ssize_t r = read(fd, buf, count);
        if (r < 0 && errno == EINTR)
            continue;
        if (r < 0)
            return r;
        if (r == 0)
            return nread;
        buf = (char *)buf + r;
        count -= r;
        nread += r;
    }
    return nread;
}

/* Like write(), but restarts after EINTR. Doesn't play
 * nicely with nonblocking FD and EAGAIN, in which case
 * you want to use bare write(). Or even use virSocket()
 * if the FD is related to a socket rather than a plain
 * file or pipe. */
ssize_t
safewrite(int fd, const void *buf, size_t count)
{
    size_t nwritten = 0;
    while (count > 0) {
        ssize_t r = write(fd, buf, count);

        if (r < 0 && errno == EINTR)
            continue;
        if (r < 0)
            return r;
        if (r == 0)
            return nwritten;
        buf = (const char *)buf + r;
        count -= r;
        nwritten += r;
    }
    return nwritten;
}

1104
#ifdef HAVE_POSIX_FALLOCATE
J
John Ferlan 已提交
1105 1106
static int
safezero_posix_fallocate(int fd, off_t offset, off_t len)
1107 1108 1109 1110 1111 1112 1113
{
    int ret = posix_fallocate(fd, offset, len);
    if (ret == 0)
        return 0;
    errno = ret;
    return -1;
}
1114 1115 1116 1117 1118 1119
#else /* !HAVE_POSIX_FALLOCATE */
static int
safezero_posix_fallocate(int fd ATTRIBUTE_UNUSED,
                         off_t offset ATTRIBUTE_UNUSED,
                         off_t len ATTRIBUTE_UNUSED)
{
1120
    return -2;
1121 1122
}
#endif /* !HAVE_POSIX_FALLOCATE */
1123

1124
#if HAVE_SYS_SYSCALL_H && defined(SYS_fallocate)
1125 1126 1127 1128 1129
static int
safezero_sys_fallocate(int fd,
                       off_t offset,
                       off_t len)
{
1130
    return syscall(SYS_fallocate, fd, 0, offset, len);
1131 1132 1133 1134 1135 1136 1137
}
#else /* !HAVE_SYS_SYSCALL_H || !defined(SYS_fallocate) */
static int
safezero_sys_fallocate(int fd ATTRIBUTE_UNUSED,
                       off_t offset ATTRIBUTE_UNUSED,
                       off_t len ATTRIBUTE_UNUSED)
{
1138
    return -2;
1139
}
1140
#endif /* !HAVE_SYS_SYSCALL_H || !defined(SYS_fallocate) */
1141

1142
#ifdef HAVE_MMAP
J
John Ferlan 已提交
1143 1144
static int
safezero_mmap(int fd, off_t offset, off_t len)
1145 1146 1147
{
    int r;
    char *buf;
1148
    static long pagemask;
1149
    off_t map_skip;
1150

1151 1152
    /* align offset and length, rounding offset down and length up */
    if (pagemask == 0)
1153
        pagemask = ~(virGetSystemPageSize() - 1);
1154 1155
    map_skip = offset - (offset & pagemask);

1156 1157 1158 1159 1160 1161 1162
    /* memset wants the mmap'ed file to be present on disk so create a
     * sparse file
     */
    r = ftruncate(fd, offset + len);
    if (r < 0)
        return -1;

1163 1164
    buf = mmap(NULL, len + map_skip, PROT_READ | PROT_WRITE, MAP_SHARED,
               fd, offset - map_skip);
1165 1166 1167
    if (buf != MAP_FAILED) {
        memset(buf + map_skip, 0, len);
        munmap(buf, len + map_skip);
1168

1169 1170
        return 0;
    }
1171

1172 1173
    /* fall back to writing zeroes using safewrite if mmap fails (for
     * example because of virtual memory limits) */
1174
    return -2;
J
John Ferlan 已提交
1175
}
1176 1177 1178 1179 1180 1181
#else /* !HAVE_MMAP */
static int
safezero_mmap(int fd ATTRIBUTE_UNUSED,
              off_t offset ATTRIBUTE_UNUSED,
              off_t len ATTRIBUTE_UNUSED)
{
1182
    return -2;
1183 1184
}
#endif /* !HAVE_MMAP */
J
John Ferlan 已提交
1185 1186 1187 1188 1189

static int
safezero_slow(int fd, off_t offset, off_t len)
{
    int r;
1190
    VIR_AUTOFREE(char *) buf = NULL;
J
John Ferlan 已提交
1191
    unsigned long long remain, bytes;
1192 1193 1194 1195 1196 1197

    if (lseek(fd, offset, SEEK_SET) < 0)
        return -1;

    /* Split up the write in small chunks so as not to allocate lots of RAM */
    remain = len;
1198
    bytes = MIN(1024 * 1024, len);
1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210

    r = VIR_ALLOC_N(buf, bytes);
    if (r < 0) {
        errno = ENOMEM;
        return -1;
    }

    while (remain) {
        if (bytes > remain)
            bytes = remain;

        r = safewrite(fd, buf, bytes);
1211
        if (r < 0)
1212 1213 1214 1215 1216 1217 1218 1219
            return -1;

        /* safewrite() guarantees all data will be written */
        remain -= bytes;
    }
    return 0;
}

1220
int safezero(int fd, off_t offset, off_t len)
J
John Ferlan 已提交
1221 1222 1223 1224
{
    int ret;

    ret = safezero_posix_fallocate(fd, offset, len);
1225
    if (ret != -2)
J
John Ferlan 已提交
1226 1227
        return ret;

1228
    if (safezero_sys_fallocate(fd, offset, len) == 0)
J
John Ferlan 已提交
1229
        return 0;
1230 1231 1232 1233

    ret = safezero_mmap(fd, offset, len);
    if (ret != -2)
        return ret;
J
John Ferlan 已提交
1234 1235
    return safezero_slow(fd, offset, len);
}
1236

1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
int virFileAllocate(int fd, off_t offset, off_t len)
{
    int ret;

    ret = safezero_posix_fallocate(fd, offset, len);
    if (ret != -2)
        return ret;

    return safezero_sys_fallocate(fd, offset, len);
}

1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
#if defined HAVE_MNTENT_H && defined HAVE_GETMNTENT_R
/* search /proc/mounts for mount point of *type; return pointer to
 * malloc'ed string of the path if found, otherwise return NULL
 * with errno set to an appropriate value.
 */
char *
virFileFindMountPoint(const char *type)
{
    FILE *f;
    struct mntent mb;
    char mntbuf[1024];
    char *ret = NULL;

    f = setmntent("/proc/mounts", "r");
    if (!f)
        return NULL;

    while (getmntent_r(f, &mb, mntbuf, sizeof(mntbuf))) {
        if (STREQ(mb.mnt_type, type)) {
1267
            ignore_value(VIR_STRDUP_QUIET(ret, mb.mnt_dir));
1268 1269 1270 1271 1272 1273 1274
            goto cleanup;
        }
    }

    if (!ret)
        errno = ENOENT;

1275
 cleanup:
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305
    endmntent(f);

    return ret;
}

#else /* defined HAVE_MNTENT_H && defined HAVE_GETMNTENT_R */

char *
virFileFindMountPoint(const char *type ATTRIBUTE_UNUSED)
{
    errno = ENOSYS;

    return NULL;
}

#endif /* defined HAVE_MNTENT_H && defined HAVE_GETMNTENT_R */

int
virBuildPathInternal(char **path, ...)
{
    char *path_component = NULL;
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    va_list ap;
    int ret = 0;

    va_start(ap, path);

    path_component = va_arg(ap, char *);
    virBufferAdd(&buf, path_component, -1);

E
Eric Blake 已提交
1306
    while ((path_component = va_arg(ap, char *)) != NULL) {
1307 1308 1309 1310 1311 1312 1313
        virBufferAddChar(&buf, '/');
        virBufferAdd(&buf, path_component, -1);
    }

    va_end(ap);

    *path = virBufferContentAndReset(&buf);
1314
    if (*path == NULL)
1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
        ret = -1;

    return ret;
}

/* Like gnulib's fread_file, but read no more than the specified maximum
   number of bytes.  If the length of the input is <= max_len, and
   upon error while reading that data, it works just like fread_file.  */
static char *
saferead_lim(int fd, size_t max_len, size_t *length)
{
    char *buf = NULL;
    size_t alloc = 0;
    size_t size = 0;
    int save_errno;

    for (;;) {
        int count;
        int requested;

        if (size + BUFSIZ + 1 > alloc) {
            alloc += alloc / 2;
            if (alloc < size + BUFSIZ + 1)
                alloc = size + BUFSIZ + 1;

            if (VIR_REALLOC_N(buf, alloc) < 0) {
                save_errno = errno;
                break;
            }
        }

        /* Ensure that (size + requested <= max_len); */
        requested = MIN(size < max_len ? max_len - size : 0,
                        alloc - size - 1);
        count = saferead(fd, buf + size, requested);
        size += count;

        if (count != requested || requested == 0) {
            save_errno = errno;
            if (count < 0)
                break;
            buf[size] = '\0';
            *length = size;
            return buf;
        }
    }

    VIR_FREE(buf);
    errno = save_errno;
    return NULL;
}

1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387

/* A wrapper around saferead_lim that merely stops reading at the
 * specified maximum size.  */
int
virFileReadHeaderFD(int fd, int maxlen, char **buf)
{
    size_t len;
    char *s;

    if (maxlen <= 0) {
        errno = EINVAL;
        return -1;
    }
    s = saferead_lim(fd, maxlen, &len);
    if (s == NULL)
        return -1;
    *buf = s;
    return len;
}


1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406
int
virFileReadHeaderQuiet(const char *path,
                       int maxlen,
                       char **buf)
{
    int fd;
    int len;

    fd = open(path, O_RDONLY);
    if (fd < 0)
        return -1;

    len = virFileReadHeaderFD(fd, maxlen, buf);
    VIR_FORCE_CLOSE(fd);

    return len;
}


1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451
/* A wrapper around saferead_lim that maps a failure due to
   exceeding the maximum size limitation to EOVERFLOW.  */
int
virFileReadLimFD(int fd, int maxlen, char **buf)
{
    size_t len;
    char *s;

    if (maxlen <= 0) {
        errno = EINVAL;
        return -1;
    }
    s = saferead_lim(fd, maxlen+1, &len);
    if (s == NULL)
        return -1;
    if (len > maxlen || (int)len != len) {
        VIR_FREE(s);
        /* There was at least one byte more than MAXLEN.
           Set errno accordingly. */
        errno = EOVERFLOW;
        return -1;
    }
    *buf = s;
    return len;
}

int
virFileReadAll(const char *path, int maxlen, char **buf)
{
    int fd = open(path, O_RDONLY);
    if (fd < 0) {
        virReportSystemError(errno, _("Failed to open file '%s'"), path);
        return -1;
    }

    int len = virFileReadLimFD(fd, maxlen, buf);
    VIR_FORCE_CLOSE(fd);
    if (len < 0) {
        virReportSystemError(errno, _("Failed to read file '%s'"), path);
        return -1;
    }

    return len;
}

J
Ján Tomko 已提交
1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466
int
virFileReadAllQuiet(const char *path, int maxlen, char **buf)
{
    int fd = open(path, O_RDONLY);
    if (fd < 0)
        return -errno;

    int len = virFileReadLimFD(fd, maxlen, buf);
    VIR_FORCE_CLOSE(fd);
    if (len < 0)
        return -errno;

    return len;
}

1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490
/* Read @file into preallocated buffer @buf of size @len.
 * Return value is -errno in case of errors and size
 * of data read (no trailing zero) in case of success.
 * If there is more data then @len - 1 then data will be
 * truncated. */
int
virFileReadBufQuiet(const char *file, char *buf, int len)
{
    int fd;
    ssize_t sz;

    fd = open(file, O_RDONLY);
    if (fd < 0)
        return -errno;

    sz = saferead(fd, buf, len - 1);
    VIR_FORCE_CLOSE(fd);
    if (sz < 0)
        return -errno;

    buf[sz] = '\0';
    return sz;
}

1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523
/* Truncate @path and write @str to it.  If @mode is 0, ensure that
   @path exists; otherwise, use @mode if @path must be created.
   Return 0 for success, nonzero for failure.
   Be careful to preserve any errno value upon failure. */
int
virFileWriteStr(const char *path, const char *str, mode_t mode)
{
    int fd;

    if (mode)
        fd = open(path, O_WRONLY|O_TRUNC|O_CREAT, mode);
    else
        fd = open(path, O_WRONLY|O_TRUNC);
    if (fd == -1)
        return -1;

    if (safewrite(fd, str, strlen(str)) < 0) {
        VIR_FORCE_CLOSE(fd);
        return -1;
    }

    /* Use errno from failed close only if there was no write error.  */
    if (VIR_CLOSE(fd) != 0)
        return -1;

    return 0;
}

#define SAME_INODE(Stat_buf_1, Stat_buf_2) \
  ((Stat_buf_1).st_ino == (Stat_buf_2).st_ino \
   && (Stat_buf_1).st_dev == (Stat_buf_2).st_dev)

/* Return nonzero if checkLink and checkDest
1524 1525
 * refer to the same file.  Otherwise, return 0.
 */
1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538
int
virFileLinkPointsTo(const char *checkLink,
                    const char *checkDest)
{
    struct stat src_sb;
    struct stat dest_sb;

    return (stat(checkLink, &src_sb) == 0
            && stat(checkDest, &dest_sb) == 0
            && SAME_INODE(src_sb, dest_sb));
}


1539 1540 1541 1542 1543 1544 1545 1546 1547 1548
/* Return positive if checkLink (residing within directory if not
 * absolute) and checkDest refer to the same file.  Otherwise, return
 * -1 on allocation failure (error reported), or 0 if not the same
 * (silent).
 */
int
virFileRelLinkPointsTo(const char *directory,
                       const char *checkLink,
                       const char *checkDest)
{
1549
    VIR_AUTOFREE(char *) candidate = NULL;
1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560

    if (*checkLink == '/')
        return virFileLinkPointsTo(checkLink, checkDest);
    if (!directory) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("cannot resolve '%s' without starting directory"),
                       checkLink);
        return -1;
    }
    if (virAsprintf(&candidate, "%s/%s", directory, checkLink) < 0)
        return -1;
1561
    return virFileLinkPointsTo(candidate, checkDest);
1562 1563 1564
}


1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580
static int
virFileResolveLinkHelper(const char *linkpath,
                         bool intermediatePaths,
                         char **resultpath)
{
    struct stat st;

    *resultpath = NULL;

    /* We don't need the full canonicalization of intermediate
     * directories, if linkpath is absolute and the basename is
     * already a non-symlink.  */
    if (IS_ABSOLUTE_FILE_NAME(linkpath) && !intermediatePaths) {
        if (lstat(linkpath, &st) < 0)
            return -1;

1581 1582
        if (!S_ISLNK(st.st_mode))
            return VIR_STRDUP_QUIET(*resultpath, linkpath) < 0 ? -1 : 0;
1583 1584
    }

1585
    *resultpath = virFileCanonicalizePath(linkpath);
1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633

    return *resultpath == NULL ? -1 : 0;
}

/*
 * Attempt to resolve a symbolic link, returning an
 * absolute path where only the last component is guaranteed
 * not to be a symlink.
 *
 * Return 0 if path was not a symbolic, or the link was
 * resolved. Return -1 with errno set upon error
 */
int
virFileResolveLink(const char *linkpath, char **resultpath)
{
    return virFileResolveLinkHelper(linkpath, false, resultpath);
}

/*
 * Attempt to resolve a symbolic link, returning an
 * absolute path where every component is guaranteed
 * not to be a symlink.
 *
 * Return 0 if path was not a symbolic, or the link was
 * resolved. Return -1 with errno set upon error
 */
int
virFileResolveAllLinks(const char *linkpath, char **resultpath)
{
    return virFileResolveLinkHelper(linkpath, true, resultpath);
}

/*
 * Check whether the given file is a link.
 * Returns 1 in case of the file being a link, 0 in case it is not
 * a link and the negative errno in all other cases.
 */
int
virFileIsLink(const char *linkpath)
{
    struct stat st;

    if (lstat(linkpath, &st) < 0)
        return -errno;

    return S_ISLNK(st.st_mode) != 0;
}

1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644
/*
 * Read where symlink is pointing to.
 *
 * Returns 0 on success (@linkpath is a successfully read link),
 *        -1 with errno set upon error.
 */
int
virFileReadLink(const char *linkpath, char **resultpath)
{
    return (*resultpath = areadlink(linkpath)) ? 0 : -1;
}
1645 1646 1647

/*
 * Finds a requested executable file in the PATH env. e.g.:
1648
 * "qemu-img" will return "/usr/bin/qemu-img"
1649 1650 1651 1652 1653 1654
 *
 * You must free the result
 */
char *
virFindFileInPath(const char *file)
{
1655
    const char *origpath = NULL;
1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667
    char *path = NULL;
    char *pathiter;
    char *pathseg;
    char *fullpath = NULL;

    if (file == NULL)
        return NULL;

    /* if we are passed an absolute path (starting with /), return a
     * copy of that path, after validating that it is executable
     */
    if (IS_ABSOLUTE_FILE_NAME(file)) {
1668
        char *ret = NULL;
1669
        if (virFileIsExecutable(file))
1670 1671
            ignore_value(VIR_STRDUP_QUIET(ret, file));
        return ret;
1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683
    }

    /* If we are passed an anchored path (containing a /), then there
     * is no path search - it must exist in the current directory
     */
    if (strchr(file, '/')) {
        if (virFileIsExecutable(file))
            ignore_value(virFileAbsPath(file, &path));
        return path;
    }

    /* copy PATH env so we can tweak it */
1684
    origpath = getenv("PATH");
1685 1686
    if (!origpath)
        origpath = "/bin:/usr/bin";
1687

1688
    if (VIR_STRDUP_QUIET(path, origpath) <= 0)
1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705
        return NULL;

    /* for each path segment, append the file to search for and test for
     * it. return it if found.
     */
    pathiter = path;
    while ((pathseg = strsep(&pathiter, ":")) != NULL) {
        if (virAsprintf(&fullpath, "%s/%s", pathseg, file) < 0 ||
            virFileIsExecutable(fullpath))
            break;
        VIR_FREE(fullpath);
    }

    VIR_FREE(path);
    return fullpath;
}

1706 1707 1708 1709 1710 1711 1712 1713

static bool useDirOverride;

/**
 * virFileFindResourceFull:
 * @filename: libvirt distributed filename without any path
 * @prefix: optional string to prepend to filename
 * @suffix: optional string to append to filename
1714
 * @builddir: location of the filename in the build tree including
1715
 *            abs_top_srcdir or abs_top_builddir prefix
1716 1717 1718 1719 1720 1721 1722 1723
 * @installdir: location of the installed binary
 * @envname: environment variable used to override all dirs
 *
 * A helper which will return a path to @filename within
 * the current build tree, if the calling binary is being
 * run from the source tree. Otherwise it will return the
 * path in the installed location.
 *
1724 1725 1726 1727
 * Note that this function does not actually check whether
 * the file exists on disk, it merely builds the fully
 * qualified path where it is supposed to exist.
 *
1728
 * If @envname is non-NULL it will override all other
1729
 * directory lookup.
1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744
 *
 * Only use this with @filename files that are part of
 * the libvirt tree, not 3rd party binaries/files.
 *
 * Returns the resolved path (caller frees) or NULL on error
 */
char *
virFileFindResourceFull(const char *filename,
                        const char *prefix,
                        const char *suffix,
                        const char *builddir,
                        const char *installdir,
                        const char *envname)
{
    char *ret = NULL;
1745
    const char *envval = envname ? getenv(envname) : NULL;
1746
    const char *path;
1747 1748 1749 1750 1751 1752

    if (!prefix)
        prefix = "";
    if (!suffix)
        suffix = "";

1753 1754 1755 1756 1757 1758 1759 1760 1761
    if (envval)
        path = envval;
    else if (useDirOverride)
        path = builddir;
    else
        path = installdir;

    if (virAsprintf(&ret, "%s/%s%s%s", path, prefix, filename, suffix) < 0)
        return NULL;
1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776

    VIR_DEBUG("Resolved '%s' to '%s'", filename, ret);
    return ret;
}

char *
virFileFindResource(const char *filename,
                    const char *builddir,
                    const char *installdir)
{
    return virFileFindResourceFull(filename, NULL, NULL, builddir, installdir, NULL);
}


/**
1777
 * virFileActivateDirOverrideForProg:
1778 1779 1780 1781 1782 1783 1784
 * @argv0: argv[0] of the calling program
 *
 * Look at @argv0 and try to detect if running from
 * a build directory, by looking for a 'lt-' prefix
 * on the binary name, or '/.libs/' in the path
 */
void
1785
virFileActivateDirOverrideForProg(const char *argv0)
1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797
{
    char *file = strrchr(argv0, '/');
    if (!file || file[1] == '\0')
        return;
    file++;
    if (STRPREFIX(file, "lt-") ||
        strstr(argv0, "/.libs/")) {
        useDirOverride = true;
        VIR_DEBUG("Activating build dir override for %s", argv0);
    }
}

L
Laine Stump 已提交
1798

1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812
/**
 * virFileActivateDirOverrideForLib:
 *
 * Look for LIBVIRT_DIR_OVERRIDE env var to see if we should find files from
 * the build/src tree instead of install tree.
 */
void
virFileActivateDirOverrideForLib(void)
{
    if (getenv("LIBVIRT_DIR_OVERRIDE") != NULL)
        useDirOverride = true;
}


L
Laine Stump 已提交
1813 1814 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
/**
 * virFileLength:
 * @path: full path of the file
 * @fd: open file descriptor for file (or -1 to use @path)
 *
 * If fd >= 0, return the length of the open file indicated by @fd.
 * If fd < 0 (i.e. -1) return the length of the file indicated by
 * @path.
 *
 * Returns the length, or -1 if the file doesn't
 * exist or its info was inaccessible. No error is logged.
 */
off_t
virFileLength(const char *path, int fd)
{
    struct stat s;

    if (fd >= 0) {
        if (fstat(fd, &s) < 0)
            return -1;
    } else {
        if (stat(path, &s) < 0)
            return -1;
    }

    if (!S_ISREG(s.st_mode))
       return -1;

    return s.st_size;

}


1846 1847 1848 1849 1850 1851 1852
bool
virFileIsDir(const char *path)
{
    struct stat s;
    return (stat(path, &s) == 0) && S_ISDIR(s.st_mode);
}

1853 1854 1855 1856 1857 1858 1859 1860 1861

bool
virFileIsRegular(const char *path)
{
    struct stat s;
    return (stat(path, &s) == 0) && S_ISREG(s.st_mode);
}


1862 1863 1864 1865
/**
 * virFileExists: Check for presence of file
 * @path: Path of file to check
 *
1866 1867
 * Returns true if the file exists, false if it doesn't, setting errno
 * appropriately.
1868
 */
1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896
bool
virFileExists(const char *path)
{
    return access(path, F_OK) == 0;
}

/* Check that a file is regular and has executable bits.  If false is
 * returned, errno is valid.
 *
 * Note: In the presence of ACLs, this may return true for a file that
 * would actually fail with EACCES for a given user, or false for a
 * file that the user could actually execute, but setups with ACLs
 * that weird are unusual. */
bool
virFileIsExecutable(const char *file)
{
    struct stat sb;

    /* We would also want to check faccessat if we cared about ACLs,
     * but we don't.  */
    if (stat(file, &sb) < 0)
        return false;
    if (S_ISREG(sb.st_mode) && (sb.st_mode & 0111) != 0)
        return true;
    errno = S_ISDIR(sb.st_mode) ? EISDIR : EACCES;
    return false;
}

1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907

/*
 * Check that a file refers to a mount point. Trick is that for
 * a mount point, the st_dev field will differ from the parent
 * directory.
 *
 * Note that this will not detect bind mounts of dirs/files,
 * only true filesystem mounts.
 */
int virFileIsMountPoint(const char *file)
{
1908 1909
    VIR_AUTOFREE(char *) parent = NULL;
    int ret;
1910 1911 1912 1913
    struct stat sb1, sb2;

    if (!(parent = mdir_name(file))) {
        virReportOOMError();
1914
        return -1;
1915 1916 1917 1918 1919 1920
    }

    VIR_DEBUG("Comparing '%s' to '%s'", file, parent);

    if (stat(file, &sb1) < 0) {
        if (errno == ENOENT)
1921
            return 0;
1922 1923 1924 1925
        else
            virReportSystemError(errno,
                                 _("Cannot stat '%s'"),
                                 file);
1926
        return -1;
1927 1928 1929 1930 1931 1932
    }

    if (stat(parent, &sb2) < 0) {
        virReportSystemError(errno,
                             _("Cannot stat '%s'"),
                             parent);
1933
        return -1;
1934 1935
    }

1936 1937
    if (!S_ISDIR(sb1.st_mode))
        return 0;
1938 1939 1940 1941 1942 1943 1944

    ret = sb1.st_dev != sb2.st_dev;
    VIR_DEBUG("Is mount %d", ret);

    return ret;
}

1945

1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958
#if defined(__linux__)
/**
 * virFileIsCDROM:
 * @path: File to check
 *
 * Returns 1 if @path is a cdrom device 0 if it is not a cdrom and -1 on
 * error. 'errno' of the failure is preserved and no libvirt errors are
 * reported.
 */
int
virFileIsCDROM(const char *path)
{
    struct stat st;
1959
    VIR_AUTOCLOSE fd = -1;
1960 1961

    if ((fd = open(path, O_RDONLY | O_NONBLOCK)) < 0)
1962
        return -1;
1963 1964

    if (fstat(fd, &st) < 0)
1965
        return -1;
1966

1967 1968
    if (!S_ISBLK(st.st_mode))
        return 0;
1969 1970 1971

    /* Attempt to detect via a CDROM specific ioctl */
    if (ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT) >= 0)
1972
        return 1;
1973

1974
    return 0;
1975 1976 1977 1978 1979 1980 1981
}

#else

int
virFileIsCDROM(const char *path)
{
1982 1983
    if (STRPREFIX(path, "/dev/cd") ||
        STRPREFIX(path, "/dev/acd"))
1984 1985 1986 1987 1988 1989 1990 1991
        return 1;

    return 0;
}

#endif /* defined(__linux__) */


1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018
#if defined HAVE_MNTENT_H && defined HAVE_GETMNTENT_R
static int
virFileGetMountSubtreeImpl(const char *mtabpath,
                           const char *prefix,
                           char ***mountsret,
                           size_t *nmountsret,
                           bool reverse)
{
    FILE *procmnt;
    struct mntent mntent;
    char mntbuf[1024];
    int ret = -1;
    char **mounts = NULL;
    size_t nmounts = 0;

    VIR_DEBUG("prefix=%s", prefix);

    *mountsret = NULL;
    *nmountsret = 0;

    if (!(procmnt = setmntent(mtabpath, "r"))) {
        virReportSystemError(errno,
                             _("Failed to read %s"), mtabpath);
        return -1;
    }

    while (getmntent_r(procmnt, &mntent, mntbuf, sizeof(mntbuf)) != NULL) {
2019 2020 2021
        if (!(STREQ(mntent.mnt_dir, prefix) ||
              (STRPREFIX(mntent.mnt_dir, prefix) &&
               mntent.mnt_dir[strlen(prefix)] == '/')))
2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037
            continue;

        if (VIR_EXPAND_N(mounts, nmounts, nmounts ? 1 : 2) < 0)
            goto cleanup;
        if (VIR_STRDUP(mounts[nmounts - 2], mntent.mnt_dir) < 0)
            goto cleanup;
    }

    if (mounts)
        qsort(mounts, nmounts - 1, sizeof(mounts[0]),
              reverse ? virStringSortRevCompare : virStringSortCompare);

    *mountsret = mounts;
    *nmountsret = nmounts ? nmounts - 1 : 0;
    ret = 0;

2038
 cleanup:
2039
    if (ret < 0)
2040
        virStringListFree(mounts);
2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065
    endmntent(procmnt);
    return ret;
}
#else /* ! defined HAVE_MNTENT_H && defined HAVE_GETMNTENT_R */
static int
virFileGetMountSubtreeImpl(const char *mtabpath ATTRIBUTE_UNUSED,
                           const char *prefix ATTRIBUTE_UNUSED,
                           char ***mountsret ATTRIBUTE_UNUSED,
                           size_t *nmountsret ATTRIBUTE_UNUSED,
                           bool reverse ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Unable to determine mount table on this platform"));
    return -1;
}
#endif /* ! defined HAVE_MNTENT_H && defined HAVE_GETMNTENT_R */

/**
 * virFileGetMountSubtree:
 * @mtabpath: mount file to parser (eg /proc/mounts)
 * @prefix: mount path prefix to match
 * @mountsret: allocated and filled with matching mounts
 * @nmountsret: filled with number of matching mounts, not counting NULL terminator
 *
 * Return the list of mounts from @mtabpath which contain
2066
 * the path @prefix, sorted alphabetically.
2067 2068
 *
 * The @mountsret array will be NULL terminated and should
2069
 * be freed with virStringListFree
2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088
 *
 * Returns 0 on success, -1 on error
 */
int virFileGetMountSubtree(const char *mtabpath,
                           const char *prefix,
                           char ***mountsret,
                           size_t *nmountsret)
{
    return virFileGetMountSubtreeImpl(mtabpath, prefix, mountsret, nmountsret, false);
}

/**
 * virFileGetMountReverseSubtree:
 * @mtabpath: mount file to parser (eg /proc/mounts)
 * @prefix: mount path prefix to match
 * @mountsret: allocated and filled with matching mounts
 * @nmountsret: filled with number of matching mounts, not counting NULL terminator
 *
 * Return the list of mounts from @mtabpath which contain
2089
 * the path @prefix, reverse-sorted alphabetically.
2090 2091
 *
 * The @mountsret array will be NULL terminated and should
2092
 * be freed with virStringListFree
2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103
 *
 * Returns 0 on success, -1 on error
 */
int virFileGetMountReverseSubtree(const char *mtabpath,
                                  const char *prefix,
                                  char ***mountsret,
                                  size_t *nmountsret)
{
    return virFileGetMountSubtreeImpl(mtabpath, prefix, mountsret, nmountsret, true);
}

2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116
#ifndef WIN32
/* Check that a file is accessible under certain
 * user & gid.
 * @mode can be F_OK, or a bitwise combination of R_OK, W_OK, and X_OK.
 * see 'man access' for more details.
 * Returns 0 on success, -1 on fail with errno set.
 */
int
virFileAccessibleAs(const char *path, int mode,
                    uid_t uid, gid_t gid)
{
    pid_t pid = 0;
    int status, ret = 0;
2117
    VIR_AUTOFREE(gid_t *) groups = NULL;
2118
    int ngroups;
2119

2120 2121
    if (uid == geteuid() &&
        gid == getegid())
2122 2123
        return access(path, mode);

2124 2125 2126 2127
    ngroups = virGetGroupList(uid, gid, &groups);
    if (ngroups < 0)
        return -1;

E
Eric Blake 已提交
2128
    pid = virFork();
2129

2130
    if (pid < 0)
2131 2132 2133
        return -1;

    if (pid) { /* parent */
2134 2135
        if (virProcessWait(pid, &status, false) < 0) {
            /* virProcessWait() already reported error */
E
Eric Blake 已提交
2136
            errno = EINTR;
2137 2138 2139 2140
            return -1;
        }

        if (status) {
2141
            errno = status;
2142 2143 2144 2145 2146 2147
            return -1;
        }

        return 0;
    }

2148
    if (virSetUIDGID(uid, gid, groups, ngroups) < 0) {
2149 2150 2151 2152 2153 2154 2155
        ret = errno;
        goto childerror;
    }

    if (access(path, mode) < 0)
        ret = errno;

2156
 childerror:
2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213
    if ((ret & 0xFF) != ret) {
        VIR_WARN("unable to pass desired return value %d", ret);
        ret = 0xFF;
    }

    _exit(ret);
}

/* virFileOpenForceOwnerMode() - an internal utility function called
 * only by virFileOpenAs().  Sets the owner and mode of the file
 * opened as "fd" if it's not correct AND the flags say it should be
 * forced. */
static int
virFileOpenForceOwnerMode(const char *path, int fd, mode_t mode,
                          uid_t uid, gid_t gid, unsigned int flags)
{
    int ret = 0;
    struct stat st;

    if (!(flags & (VIR_FILE_OPEN_FORCE_OWNER | VIR_FILE_OPEN_FORCE_MODE)))
        return 0;

    if (fstat(fd, &st) == -1) {
        ret = -errno;
        virReportSystemError(errno, _("stat of '%s' failed"), path);
        return ret;
    }
    /* NB: uid:gid are never "-1" (default) at this point - the caller
     * has always changed -1 to the value of get[gu]id().
    */
    if ((flags & VIR_FILE_OPEN_FORCE_OWNER) &&
        ((st.st_uid != uid) || (st.st_gid != gid)) &&
        (fchown(fd, uid, gid) < 0)) {
        ret = -errno;
        virReportSystemError(errno,
                             _("cannot chown '%s' to (%u, %u)"),
                             path, (unsigned int) uid,
                             (unsigned int) gid);
        return ret;
    }
    if ((flags & VIR_FILE_OPEN_FORCE_MODE) &&
        ((mode & (S_IRWXU|S_IRWXG|S_IRWXO)) !=
         (st.st_mode & (S_IRWXU|S_IRWXG|S_IRWXO))) &&
        (fchmod(fd, mode) < 0)) {
        ret = -errno;
        virReportSystemError(errno,
                             _("cannot set mode of '%s' to %04o"),
                             path, mode);
        return ret;
    }
    return ret;
}

/* virFileOpenForked() - an internal utility function called only by
 * virFileOpenAs(). It forks, then the child does setuid+setgid to
 * given uid:gid and attempts to open the file, while the parent just
 * calls recvfd to get the open fd back from the child. returns the
2214 2215 2216 2217 2218 2219
 * fd, or -errno if there is an error. Additionally, to avoid another
 * round-trip to unlink the file in a forked process; on error if this
 * function created the file, but failed to perform some action after
 * creation, then perform the unlink of the file. The storage driver
 * buildVol backend function expects the file to be deleted on error.
 */
2220 2221 2222 2223 2224
static int
virFileOpenForked(const char *path, int openflags, mode_t mode,
                  uid_t uid, gid_t gid, unsigned int flags)
{
    pid_t pid;
2225
    int status = 0, ret = 0;
2226
    int recvfd_errno = 0;
2227 2228
    int fd = -1;
    int pair[2] = { -1, -1 };
2229
    VIR_AUTOFREE(gid_t *) groups = NULL;
2230
    int ngroups;
2231
    bool created = false;
2232 2233 2234 2235 2236 2237

    /* parent is running as root, but caller requested that the
     * file be opened as some other user and/or group). The
     * following dance avoids problems caused by root-squashing
     * NFS servers. */

2238 2239 2240 2241
    ngroups = virGetGroupList(uid, gid, &groups);
    if (ngroups < 0)
        return -errno;

2242 2243 2244 2245 2246 2247 2248 2249
    if (socketpair(AF_UNIX, SOCK_STREAM, 0, pair) < 0) {
        ret = -errno;
        virReportSystemError(errno,
                             _("failed to create socket needed for '%s'"),
                             path);
        return ret;
    }

E
Eric Blake 已提交
2250
    pid = virFork();
2251 2252
    if (pid < 0)
        return -errno;
2253 2254 2255 2256 2257 2258

    if (pid == 0) {

        /* child */

        /* set desired uid/gid, then attempt to create the file */
E
Eric Blake 已提交
2259
        VIR_FORCE_CLOSE(pair[0]);
2260
        if (virSetUIDGID(uid, gid, groups, ngroups) < 0) {
2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271
            ret = -errno;
            goto childerror;
        }

        if ((fd = open(path, openflags, mode)) < 0) {
            ret = -errno;
            virReportSystemError(errno,
                                 _("child process failed to create file '%s'"),
                                 path);
            goto childerror;
        }
2272 2273
        if (openflags & O_CREAT)
            created = true;
2274 2275 2276

        /* File is successfully open. Set permissions if requested. */
        ret = virFileOpenForceOwnerMode(path, fd, mode, uid, gid, flags);
2277 2278 2279 2280 2281
        if (ret < 0) {
            ret = -errno;
            virReportSystemError(errno,
                                 _("child process failed to force owner mode file '%s'"),
                                 path);
2282
            goto childerror;
2283
        }
2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301

        do {
            ret = sendfd(pair[1], fd);
        } while (ret < 0 && errno == EINTR);

        if (ret < 0) {
            ret = -errno;
            virReportSystemError(errno, "%s",
                                 _("child process failed to send fd to parent"));
            goto childerror;
        }

    childerror:
        /* ret tracks -errno on failure, but exit value must be positive.
         * If the child exits with EACCES, then the parent tries again.  */
        /* XXX This makes assumptions about errno being < 255, which is
         * not true on Hurd.  */
        VIR_FORCE_CLOSE(pair[1]);
2302
        if (ret < 0) {
2303
            VIR_FORCE_CLOSE(fd);
2304 2305 2306
            if (created)
                unlink(path);
        }
2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322
        ret = -ret;
        if ((ret & 0xff) != ret) {
            VIR_WARN("unable to pass desired return value %d", ret);
            ret = 0xff;
        }
        _exit(ret);
    }

    /* parent */

    VIR_FORCE_CLOSE(pair[1]);

    do {
        fd = recvfd(pair[0], 0);
    } while (fd < 0 && errno == EINTR);
    VIR_FORCE_CLOSE(pair[0]); /* NB: this preserves errno */
2323 2324
    if (fd < 0)
        recvfd_errno = errno;
2325

2326 2327 2328 2329 2330 2331 2332 2333 2334 2335
    if (virProcessWait(pid, &status, 0) < 0) {
        /* virProcessWait() reports errno on waitpid failure, so we'll just
         * set our return status to EINTR; otherwise, set status to EACCES
         * since the original failure for the fork+setuid path would have
         * been EACCES or EPERM by definition.
         */
        if (virLastErrorIsSystemErrno(0))
            status = EINTR;
        else if (!status)
            status = EACCES;
2336
    }
2337

2338
    if (status) {
2339
        VIR_FORCE_CLOSE(fd);
2340
        return -status;
2341
    }
2342 2343 2344 2345 2346 2347 2348 2349 2350 2351

    /* if waitpid succeeded, but recvfd failed, report recvfd_errno */
    if (recvfd_errno != 0) {
        virReportSystemError(recvfd_errno,
                             _("failed recvfd for child creating '%s'"),
                             path);
        return -recvfd_errno;
    }

    /* otherwise, waitpid and recvfd succeeded, return the fd */
2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380
    return fd;
}

/**
 * virFileOpenAs:
 * @path: file to open or create
 * @openflags: flags to pass to open
 * @mode: mode to use on creation or when forcing permissions
 * @uid: uid that should own file on creation
 * @gid: gid that should own file
 * @flags: bit-wise or of VIR_FILE_OPEN_* flags
 *
 * Open @path, and return an fd to the open file. @openflags contains
 * the flags normally passed to open(2), while those in @flags are
 * used internally. If @flags includes VIR_FILE_OPEN_NOFORK, then try
 * opening the file while executing with the current uid:gid
 * (i.e. don't fork+setuid+setgid before the call to open()).  If
 * @flags includes VIR_FILE_OPEN_FORK, then try opening the file while
 * the effective user id is @uid (by forking a child process); this
 * allows one to bypass root-squashing NFS issues; NOFORK is always
 * tried before FORK (the absence of both flags is treated identically
 * to (VIR_FILE_OPEN_NOFORK | VIR_FILE_OPEN_FORK)). If @flags includes
 * VIR_FILE_OPEN_FORCE_OWNER, then ensure that @path is owned by
 * uid:gid before returning (even if it already existed with a
 * different owner). If @flags includes VIR_FILE_OPEN_FORCE_MODE,
 * ensure it has those permissions before returning (again, even if
 * the file already existed with different permissions).
 *
 * The return value (if non-negative) is the file descriptor, left
2381 2382 2383 2384 2385
 * open.  Returns -errno on failure. Additionally, to avoid another
 * round-trip to unlink the file; on error if this function created the
 * file, but failed to perform some action after creation, then perform
 * the unlink of the file. The storage driver buildVol backend function
 * expects the file to be deleted on error.
2386 2387 2388 2389 2390 2391
 */
int
virFileOpenAs(const char *path, int openflags, mode_t mode,
              uid_t uid, gid_t gid, unsigned int flags)
{
    int ret = 0, fd = -1;
2392
    bool created = false;
2393 2394 2395

    /* allow using -1 to mean "current value" */
    if (uid == (uid_t) -1)
2396
        uid = geteuid();
2397
    if (gid == (gid_t) -1)
2398
        gid = getegid();
2399 2400 2401 2402 2403 2404 2405

    /* treat absence of both flags as presence of both for simpler
     * calling. */
    if (!(flags & (VIR_FILE_OPEN_NOFORK|VIR_FILE_OPEN_FORK)))
        flags |= VIR_FILE_OPEN_NOFORK|VIR_FILE_OPEN_FORK;

    if ((flags & VIR_FILE_OPEN_NOFORK)
2406
        || (geteuid() != 0)
2407 2408 2409 2410 2411 2412 2413
        || ((uid == 0) && (gid == 0))) {

        if ((fd = open(path, openflags, mode)) < 0) {
            ret = -errno;
            if (!(flags & VIR_FILE_OPEN_FORK))
                goto error;
        } else {
2414 2415
            if (openflags & O_CREAT)
                created = true;
2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439
            ret = virFileOpenForceOwnerMode(path, fd, mode, uid, gid, flags);
            if (ret < 0)
                goto error;
        }
    }

    /* If we either 1) didn't try opening as current user at all, or
     * 2) failed, and errno/virStorageFileIsSharedFS indicate we might
     * be successful if we try as a different uid, then try doing
     * fork+setuid+setgid before opening.
     */
    if ((fd < 0) && (flags & VIR_FILE_OPEN_FORK)) {

        if (ret < 0) {
            /* An open(2) that failed due to insufficient permissions
             * could return one or the other of these depending on OS
             * version and circumstances. Any other errno indicates a
             * problem that couldn't be remedied by fork+setuid
             * anyway. */
            if (ret != -EACCES && ret != -EPERM)
                goto error;

            /* On Linux we can also verify the FS-type of the
             * directory.  (this is a NOP on other platforms). */
2440
            if (virFileIsSharedFS(path) <= 0)
2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453
                goto error;
        }

        /* passed all prerequisites - retry the open w/fork+setuid */
        if ((fd = virFileOpenForked(path, openflags, mode, uid, gid, flags)) < 0) {
            ret = fd;
            goto error;
        }
    }

    /* File is successfully opened */
    return fd;

2454
 error:
2455 2456 2457
    if (fd >= 0) {
        /* some other failure after the open succeeded */
        VIR_FORCE_CLOSE(fd);
2458 2459
        if (created)
            unlink(path);
2460 2461 2462 2463 2464
    }
    /* whoever failed the open last has already set ret = -errno */
    return ret;
}

J
John Ferlan 已提交
2465

2466
/* virFileRemoveNeedsSetuid:
2467
 * @path: file we plan to remove
2468 2469 2470 2471 2472 2473 2474
 * @uid: file uid to check
 * @gid: file gid to check
 *
 * Return true if we should use setuid/setgid before deleting a file
 * owned by the passed uid/gid pair. Needed for NFS with root-squash
 */
static bool
2475
virFileRemoveNeedsSetuid(const char *path, uid_t uid, gid_t gid)
2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488
{
    /* If running unprivileged, setuid isn't going to work */
    if (geteuid() != 0)
        return false;

    /* uid/gid weren't specified */
    if ((uid == (uid_t) -1) && (gid == (gid_t) -1))
        return false;

    /* already running as proper uid/gid */
    if (uid == geteuid() && gid == getegid())
        return false;

2489 2490 2491 2492 2493 2494
    /* Only perform the setuid stuff for NFS, which is the only case
       that may actually need it. This can error, but just be safe and
       only check for a clear negative result. */
    if (virFileIsSharedFSType(path, VIR_FILE_SHFS_NFS) == 0)
        return false;

2495 2496 2497 2498
    return true;
}


2499 2500
/* virFileRemove:
 * @path: file to unlink or directory to remove
J
John Ferlan 已提交
2501 2502 2503 2504 2505 2506 2507 2508 2509 2510
 * @uid: uid that was used to create the file (not required)
 * @gid: gid that was used to create the file (not required)
 *
 * If a file/volume was created in an NFS root-squash environment,
 * then we must 'unlink' the file in the same environment. Unlike
 * the virFileOpenAs[Forked] and virDirCreate[NoFork], this code
 * takes no extra flags and does not bother with EACCES failures
 * from the child.
 */
int
2511
virFileRemove(const char *path,
J
John Ferlan 已提交
2512 2513 2514 2515
              uid_t uid,
              gid_t gid)
{
    pid_t pid;
2516
    int status = 0, ret = 0;
2517
    VIR_AUTOFREE(gid_t *) groups = NULL;
J
John Ferlan 已提交
2518 2519
    int ngroups;

2520
    if (!virFileRemoveNeedsSetuid(path, uid, gid)) {
2521 2522 2523 2524 2525
        if (virFileIsDir(path))
            return rmdir(path);
        else
            return unlink(path);
    }
J
John Ferlan 已提交
2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541

    /* Otherwise, we have to deal with the NFS root-squash craziness
     * to run under the uid/gid that created the volume in order to
     * perform the unlink of the volume.
     */
    if (uid == (uid_t) -1)
        uid = geteuid();
    if (gid == (gid_t) -1)
        gid = getegid();

    ngroups = virGetGroupList(uid, gid, &groups);
    if (ngroups < 0)
        return -errno;

    pid = virFork();

2542 2543
    if (pid < 0)
        return -errno;
J
John Ferlan 已提交
2544 2545 2546 2547

    if (pid) { /* parent */
        /* wait for child to complete, and retrieve its exit code */

2548 2549 2550 2551 2552 2553 2554 2555 2556 2557
        if (virProcessWait(pid, &status, 0) < 0) {
            /* virProcessWait() reports errno on waitpid failure, so we'll just
             * set our return status to EINTR; otherwise, set status to EACCES
             * since the original failure for the fork+setuid path would have
             * been EACCES or EPERM by definition.
             */
            if (virLastErrorIsSystemErrno(0))
                status = EINTR;
            else if (!status)
                status = EACCES;
J
John Ferlan 已提交
2558 2559
        }

2560 2561 2562 2563
        if (status) {
            errno = status;
            ret = -1;
        }
J
John Ferlan 已提交
2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575

        return ret;
    }

    /* child */

    /* set desired uid/gid, then attempt to unlink the file */
    if (virSetUIDGID(uid, gid, groups, ngroups) < 0) {
        ret = errno;
        goto childerror;
    }

2576 2577 2578 2579 2580 2581 2582 2583 2584 2585
    if (virFileIsDir(path)) {
        if (rmdir(path) < 0) {
            ret = errno;
            goto childerror;
        }
    } else {
        if (unlink(path) < 0) {
            ret = errno;
            goto childerror;
        }
J
John Ferlan 已提交
2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596
    }

 childerror:
    if ((ret & 0xff) != ret) {
        VIR_WARN("unable to pass desired return value %d", ret);
        ret = 0xff;
    }
    _exit(ret);
}


2597 2598 2599 2600 2601 2602 2603 2604 2605
/* Attempt to create a directory and possibly adjust its owner/group and
 * permissions.
 *
 * return 0 on success or -errno on failure. Additionally to avoid another
 * round-trip to remove the directory on failure, perform the rmdir when
 * a mkdir was successful, but some other failure would cause a -1 return.
 * The storage driver buildVol backend function expects the directory to
 * be deleted on error.
 */
2606 2607 2608 2609 2610 2611 2612
static int
virDirCreateNoFork(const char *path,
                   mode_t mode, uid_t uid, gid_t gid,
                   unsigned int flags)
{
    int ret = 0;
    struct stat st;
2613
    bool created = false;
2614

2615
    if (!((flags & VIR_DIR_CREATE_ALLOW_EXIST) && virFileExists(path))) {
2616 2617 2618 2619 2620 2621
        if (mkdir(path, mode) < 0) {
            ret = -errno;
            virReportSystemError(errno, _("failed to create directory '%s'"),
                                 path);
            goto error;
        }
2622
        created = true;
2623 2624 2625 2626 2627 2628 2629
    }

    if (stat(path, &st) == -1) {
        ret = -errno;
        virReportSystemError(errno, _("stat of '%s' failed"), path);
        goto error;
    }
2630 2631
    if (((uid != (uid_t) -1 && st.st_uid != uid) ||
         (gid != (gid_t) -1 && st.st_gid != gid))
2632 2633 2634 2635 2636 2637
        && (chown(path, uid, gid) < 0)) {
        ret = -errno;
        virReportSystemError(errno, _("cannot chown '%s' to (%u, %u)"),
                             path, (unsigned int) uid, (unsigned int) gid);
        goto error;
    }
2638
    if (mode != (mode_t) -1 && chmod(path, mode) < 0) {
2639 2640 2641 2642 2643 2644
        ret = -errno;
        virReportSystemError(errno,
                             _("cannot set mode of '%s' to %04o"),
                             path, mode);
        goto error;
    }
2645
 error:
2646 2647
    if (ret < 0 && created)
        rmdir(path);
2648 2649 2650
    return ret;
}

2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669
/*
 * virDirCreate:
 * @path: directory to create
 * @mode: mode to use on creation or when forcing permissions
 * @uid: uid that should own directory
 * @gid: gid that should own directory
 * @flags: bit-wise or of VIR_DIR_CREATE_* flags
 *
 * Attempt to create a directory and possibly adjust its owner/group and
 * permissions. If conditions allow, use the *NoFork code in order to create
 * the directory under current owner/group rather than via a forked process.
 *
 * return 0 on success or -errno on failure. Additionally to avoid another
 * round-trip to remove the directory on failure, perform the rmdir if a
 * mkdir was successful, but some other failure would cause a -1 return.
 * The storage driver buildVol backend function expects the directory to
 * be deleted on error.
 *
 */
2670 2671 2672 2673 2674 2675 2676
int
virDirCreate(const char *path,
             mode_t mode, uid_t uid, gid_t gid,
             unsigned int flags)
{
    struct stat st;
    pid_t pid;
2677
    int status = 0, ret = 0;
2678
    VIR_AUTOFREE(gid_t *) groups = NULL;
2679
    int ngroups;
2680
    bool created = false;
2681

2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695
    /* Everything after this check is crazyness to allow setting uid/gid
     * on directories that are on root-squash NFS shares. We only want
     * to go that route if the follow conditions are true:
     *
     * 1) VIR_DIR_CREATE_AS_UID was passed, currently only used when
     *    directory is being created for a NETFS pool
     * 2) We are running as root, since that's when the root-squash
     *    workaround is required.
     * 3) An explicit uid/gid was requested
     * 4) The directory doesn't already exist and the ALLOW_EXIST flag
     *    wasn't passed.
     *
     * If any of those conditions are _not_ met, ignore the fork crazyness
     */
2696
    if ((!(flags & VIR_DIR_CREATE_AS_UID))
2697
        || (geteuid() != 0)
2698 2699
        || ((uid == (uid_t) -1) && (gid == (gid_t) -1))
        || ((flags & VIR_DIR_CREATE_ALLOW_EXIST) && virFileExists(path))) {
2700 2701 2702
        return virDirCreateNoFork(path, mode, uid, gid, flags);
    }

2703 2704 2705 2706 2707
    if (uid == (uid_t) -1)
        uid = geteuid();
    if (gid == (gid_t) -1)
        gid = getegid();

2708 2709 2710 2711
    ngroups = virGetGroupList(uid, gid, &groups);
    if (ngroups < 0)
        return -errno;

E
Eric Blake 已提交
2712
    pid = virFork();
2713

2714 2715
    if (pid < 0)
        return -errno;
2716 2717 2718

    if (pid) { /* parent */
        /* wait for child to complete, and retrieve its exit code */
2719

2720 2721 2722 2723 2724 2725 2726 2727 2728 2729
        if (virProcessWait(pid, &status, 0) < 0) {
            /* virProcessWait() reports errno on waitpid failure, so we'll just
             * set our return status to EINTR; otherwise, set status to EACCES
             * since the original failure for the fork+setuid path would have
             * been EACCES or EPERM by definition.
             */
            if (virLastErrorIsSystemErrno(0))
                status = EINTR;
            else if (!status)
                status = EACCES;
2730
        }
2731 2732

        /*
2733 2734
         * If the child exited with EACCES, then fall back to non-fork method
         * as in the original logic introduced and explained by commit 98f6f381.
2735
         */
2736 2737 2738
        if (status == EACCES) {
            virResetLastError();
            return virDirCreateNoFork(path, mode, uid, gid, flags);
2739
        }
2740

2741 2742 2743
        if (status)
            ret = -status;

2744 2745 2746 2747 2748 2749
        return ret;
    }

    /* child */

    /* set desired uid/gid, then attempt to create the directory */
2750
    if (virSetUIDGID(uid, gid, groups, ngroups) < 0) {
2751
        ret = errno;
2752 2753
        goto childerror;
    }
2754

2755
    if (mkdir(path, mode) < 0) {
2756 2757
        ret = errno;
        if (ret != EACCES) {
2758 2759 2760 2761 2762 2763
            /* in case of EACCES, the parent will retry */
            virReportSystemError(errno, _("child failed to create directory '%s'"),
                                 path);
        }
        goto childerror;
    }
2764
    created = true;
2765

2766 2767 2768
    /* check if group was set properly by creating after
     * setgid. If not, try doing it with chown */
    if (stat(path, &st) == -1) {
2769
        ret = errno;
2770 2771 2772 2773
        virReportSystemError(errno,
                             _("stat of '%s' failed"), path);
        goto childerror;
    }
2774

2775
    if ((st.st_gid != gid) && (chown(path, (uid_t) -1, gid) < 0)) {
2776
        ret = errno;
2777 2778 2779 2780 2781
        virReportSystemError(errno,
                             _("cannot chown '%s' to group %u"),
                             path, (unsigned int) gid);
        goto childerror;
    }
2782

2783
    if (mode != (mode_t) -1 && chmod(path, mode) < 0) {
2784 2785 2786 2787 2788
        virReportSystemError(errno,
                             _("cannot set mode of '%s' to %04o"),
                             path, mode);
        goto childerror;
    }
2789

2790
 childerror:
2791 2792 2793
    if (ret != 0 && created)
        rmdir(path);

2794 2795 2796 2797
    if ((ret & 0xff) != ret) {
        VIR_WARN("unable to pass desired return value %d", ret);
        ret = 0xff;
    }
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 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840
    _exit(ret);
}

#else /* WIN32 */

int
virFileAccessibleAs(const char *path,
                    int mode,
                    uid_t uid ATTRIBUTE_UNUSED,
                    gid_t gid ATTRIBUTE_UNUSED)
{
    VIR_WARN("Ignoring uid/gid due to WIN32");

    return access(path, mode);
}

/* return -errno on failure, or 0 on success */
int
virFileOpenAs(const char *path ATTRIBUTE_UNUSED,
              int openflags ATTRIBUTE_UNUSED,
              mode_t mode ATTRIBUTE_UNUSED,
              uid_t uid ATTRIBUTE_UNUSED,
              gid_t gid ATTRIBUTE_UNUSED,
              unsigned int flags_unused ATTRIBUTE_UNUSED)
{
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   "%s", _("virFileOpenAs is not implemented for WIN32"));

    return -ENOSYS;
}

int
virDirCreate(const char *path ATTRIBUTE_UNUSED,
             mode_t mode ATTRIBUTE_UNUSED,
             uid_t uid ATTRIBUTE_UNUSED,
             gid_t gid ATTRIBUTE_UNUSED,
             unsigned int flags_unused ATTRIBUTE_UNUSED)
{
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   "%s", _("virDirCreate is not implemented for WIN32"));

    return -ENOSYS;
}
2841 2842

int
2843
virFileRemove(const char *path,
2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854
              uid_t uid ATTRIBUTE_UNUSED,
              gid_t gid ATTRIBUTE_UNUSED)
{
    if (unlink(path) < 0) {
        virReportSystemError(errno, _("Unable to unlink path '%s'"),
                             path);
        return -1;
    }

    return 0;
}
2855 2856
#endif /* WIN32 */

J
Ján Tomko 已提交
2857
static int
J
Ján Tomko 已提交
2858
virDirOpenInternal(DIR **dirp, const char *name, bool ignoreENOENT, bool quiet)
J
Ján Tomko 已提交
2859
{
J
Ján Tomko 已提交
2860
    *dirp = opendir(name); /* exempt from syntax-check */
J
Ján Tomko 已提交
2861
    if (!*dirp) {
J
Ján Tomko 已提交
2862 2863 2864
        if (quiet)
            return -1;

J
Ján Tomko 已提交
2865 2866
        if (ignoreENOENT && errno == ENOENT)
            return 0;
J
Ján Tomko 已提交
2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883
        virReportSystemError(errno, _("cannot open directory '%s'"), name);
        return -1;
    }
    return 1;
}

/**
 * virDirOpen
 * @dirp: directory stream
 * @name: path of the directory
 *
 * Returns 1 on success.
 * On failure, -1 is returned and an error is reported.
 */
int
virDirOpen(DIR **dirp, const char *name)
{
J
Ján Tomko 已提交
2884
    return virDirOpenInternal(dirp, name, false, false);
J
Ján Tomko 已提交
2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898
}

/**
 * virDirOpenIfExists
 * @dirp: directory stream
 * @name: path of the directory
 *
 * Returns 1 on success.
 * If opendir returns ENOENT, 0 is returned without reporting an error.
 * On other errors, -1 is returned and an error is reported.
 */
int
virDirOpenIfExists(DIR **dirp, const char *name)
{
J
Ján Tomko 已提交
2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915
    return virDirOpenInternal(dirp, name, true, false);
}

/**
 * virDirOpenQuiet
 * @dirp: directory stream
 * @name: path of the directory
 *
 * Returns 1 on success.
 *        -1 on failure.
 *
 * Does not report any errors and errno is preserved.
 */
int
virDirOpenQuiet(DIR **dirp, const char *name)
{
    return virDirOpenInternal(dirp, name, false, true);
J
Ján Tomko 已提交
2916 2917
}

2918 2919 2920
/**
 * virDirRead:
 * @dirp: directory to read
2921
 * @ent: output one entry
2922 2923 2924
 * @name: if non-NULL, the name related to @dirp for use in error reporting
 *
 * Wrapper around readdir. Typical usage:
2925
 *   struct dirent *ent;
J
Ján Tomko 已提交
2926
 *   int rc;
2927
 *   DIR *dir;
J
Ján Tomko 已提交
2928
 *   if (virDirOpen(&dir, name) < 0)
2929
 *       goto error;
J
Ján Tomko 已提交
2930
 *   while ((rc = virDirRead(dir, &ent, name)) > 0)
2931
 *       process ent;
J
Ján Tomko 已提交
2932
 *   if (rc < 0)
2933 2934 2935 2936 2937 2938 2939
 *       goto error;
 *
 * Returns -1 on error, with error already reported if @name was
 * supplied.  On success, returns 1 for entry read, 0 for end-of-dir.
 */
int virDirRead(DIR *dirp, struct dirent **ent, const char *name)
{
J
Ján Tomko 已提交
2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950
    do {
        errno = 0;
        *ent = readdir(dirp); /* exempt from syntax-check */
        if (!*ent && errno) {
            if (name)
                virReportSystemError(errno, _("Unable to read directory '%s'"),
                                     name);
            return -1;
        }
    } while (*ent && (STREQ((*ent)->d_name, ".") ||
                      STREQ((*ent)->d_name, "..")));
2951 2952 2953
    return !!*ent;
}

J
Ján Tomko 已提交
2954 2955 2956 2957 2958 2959 2960 2961 2962
void virDirClose(DIR **dirp)
{
    if (!*dirp)
        return;

    closedir(*dirp); /* exempt from syntax-check */
    *dirp = NULL;
}

2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986

/*
 * virFileChownFiles:
 * @name: name of the directory
 * @uid: uid
 * @gid: gid
 *
 * Change ownership of all regular files in a directory.
 *
 * Returns -1 on error, with error already reported, 0 on success.
 */
int virFileChownFiles(const char *name,
                      uid_t uid,
                      gid_t gid)
{
    struct dirent *ent;
    int ret = -1;
    int direrr;
    DIR *dir;

    if (virDirOpen(&dir, name) < 0)
        return -1;

    while ((direrr = virDirRead(dir, &ent, name)) > 0) {
2987 2988
        VIR_AUTOFREE(char *) path = NULL;

2989 2990 2991
        if (virAsprintf(&path, "%s/%s", name, ent->d_name) < 0)
            goto cleanup;

2992 2993 2994
        if (!virFileIsRegular(path))
            continue;

2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015
        if (chown(path, uid, gid) < 0) {
            virReportSystemError(errno,
                                 _("cannot chown '%s' to (%u, %u)"),
                                 ent->d_name, (unsigned int) uid,
                                 (unsigned int) gid);
            goto cleanup;
        }
    }

    if (direrr < 0)
        goto cleanup;

    ret = 0;

 cleanup:
    virDirClose(&dir);

    return ret;
}


3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070
static int
virFileMakePathHelper(char *path, mode_t mode)
{
    struct stat st;
    char *p;

    VIR_DEBUG("path=%s mode=0%o", path, mode);

    if (stat(path, &st) >= 0) {
        if (S_ISDIR(st.st_mode))
            return 0;

        errno = ENOTDIR;
        return -1;
    }

    if (errno != ENOENT)
        return -1;

    if ((p = strrchr(path, '/')) == NULL) {
        errno = EINVAL;
        return -1;
    }

    if (p != path) {
        *p = '\0';

        if (virFileMakePathHelper(path, mode) < 0)
            return -1;

        *p = '/';
    }

    if (mkdir(path, mode) < 0 && errno != EEXIST)
        return -1;

    return 0;
}

/**
 * Creates the given directory with mode 0777 if it's not already existing.
 *
 * Returns 0 on success, or -1 if an error occurred (in which case, errno
 * is set appropriately).
 */
int
virFileMakePath(const char *path)
{
    return virFileMakePathWithMode(path, 0777);
}

int
virFileMakePathWithMode(const char *path,
                        mode_t mode)
{
3071
    VIR_AUTOFREE(char *) tmp = NULL;
3072

3073 3074
    if (VIR_STRDUP(tmp, path) < 0) {
        errno = ENOMEM;
3075
        return -1;
3076
    }
3077

3078
    return virFileMakePathHelper(tmp, mode);
3079 3080
}

3081 3082 3083 3084 3085

int
virFileMakeParentPath(const char *path)
{
    char *p;
3086
    VIR_AUTOFREE(char *) tmp = NULL;
3087 3088 3089 3090 3091 3092 3093 3094 3095 3096

    VIR_DEBUG("path=%s", path);

    if (VIR_STRDUP(tmp, path) < 0) {
        errno = ENOMEM;
        return -1;
    }

    if ((p = strrchr(tmp, '/')) == NULL) {
        errno = EINVAL;
3097
        return -1;
3098 3099 3100
    }
    *p = '\0';

3101
    return virFileMakePathHelper(tmp, 0777);
3102 3103 3104
}


3105 3106 3107 3108 3109 3110 3111 3112
/* Build up a fully qualified path for a config file to be
 * associated with a persistent guest or network */
char *
virFileBuildPath(const char *dir, const char *name, const char *ext)
{
    char *path;

    if (ext == NULL) {
3113
        ignore_value(virAsprintf(&path, "%s/%s", dir, name));
3114
    } else {
3115
        ignore_value(virAsprintf(&path, "%s/%s%s", dir, name, ext));
3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134
    }

    return path;
}

/* Open a non-blocking master side of a pty.  If ttyName is not NULL,
 * then populate it with the name of the slave.  If rawmode is set,
 * also put the master side into raw mode before returning.  */
#ifndef WIN32
int
virFileOpenTty(int *ttymaster, char **ttyName, int rawmode)
{
    /* XXX A word of caution - on some platforms (Solaris and HP-UX),
     * additional ioctl() calls are needs after opening the slave
     * before it will cause isatty() to return true.  Should we make
     * virFileOpenTty also return the opened slave fd, so the caller
     * doesn't have to worry about that mess?  */
    int ret = -1;
    int slave = -1;
3135
    VIR_AUTOFREE(char *) name = NULL;
3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191

    /* Unfortunately, we can't use the name argument of openpty, since
     * there is no guarantee on how large the buffer has to be.
     * Likewise, we can't use the termios argument: we have to use
     * read-modify-write since there is no portable way to initialize
     * a struct termios without use of tcgetattr.  */
    if (openpty(ttymaster, &slave, NULL, NULL, NULL) < 0)
        return -1;

    /* What a shame that openpty cannot atomically set FD_CLOEXEC, but
     * that using posix_openpt/grantpt/unlockpt/ptsname is not
     * thread-safe, and that ptsname_r is not portable.  */
    if (virSetNonBlock(*ttymaster) < 0 ||
        virSetCloseExec(*ttymaster) < 0)
        goto cleanup;

    /* While Linux supports tcgetattr on either the master or the
     * slave, Solaris requires it to be on the slave.  */
    if (rawmode) {
        struct termios ttyAttr;
        if (tcgetattr(slave, &ttyAttr) < 0)
            goto cleanup;

        cfmakeraw(&ttyAttr);

        if (tcsetattr(slave, TCSADRAIN, &ttyAttr) < 0)
            goto cleanup;
    }

    /* ttyname_r on the slave is required by POSIX, while ptsname_r on
     * the master is a glibc extension, and the POSIX ptsname is not
     * thread-safe.  Since openpty gave us both descriptors, guess
     * which way we will determine the name?  :)  */
    if (ttyName) {
        /* Initial guess of 64 is generally sufficient; rely on ERANGE
         * to tell us if we need to grow.  */
        size_t len = 64;
        int rc;

        if (VIR_ALLOC_N(name, len) < 0)
            goto cleanup;

        while ((rc = ttyname_r(slave, name, len)) == ERANGE) {
            if (VIR_RESIZE_N(name, len, len, len) < 0)
                goto cleanup;
        }
        if (rc != 0) {
            errno = rc;
            goto cleanup;
        }
        *ttyName = name;
        name = NULL;
    }

    ret = 0;

3192
 cleanup:
3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295
    if (ret != 0)
        VIR_FORCE_CLOSE(*ttymaster);
    VIR_FORCE_CLOSE(slave);

    return ret;
}
#else /* WIN32 */
int
virFileOpenTty(int *ttymaster ATTRIBUTE_UNUSED,
               char **ttyName ATTRIBUTE_UNUSED,
               int rawmode ATTRIBUTE_UNUSED)
{
    /* mingw completely lacks pseudo-terminals, and the gnulib
     * replacements are not (yet) license compatible.  */
    errno = ENOSYS;
    return -1;
}
#endif /* WIN32 */

bool
virFileIsAbsPath(const char *path)
{
    if (!path)
        return false;

    if (VIR_FILE_IS_DIR_SEPARATOR(path[0]))
        return true;

#ifdef WIN32
    if (c_isalpha(path[0]) &&
        path[1] == ':' &&
        VIR_FILE_IS_DIR_SEPARATOR(path[2]))
        return true;
#endif

    return false;
}


const char *
virFileSkipRoot(const char *path)
{
#ifdef WIN32
    /* Skip \\server\share or //server/share */
    if (VIR_FILE_IS_DIR_SEPARATOR(path[0]) &&
        VIR_FILE_IS_DIR_SEPARATOR(path[1]) &&
        path[2] &&
        !VIR_FILE_IS_DIR_SEPARATOR(path[2]))
    {
        const char *p = strchr(path + 2, VIR_FILE_DIR_SEPARATOR);
        const char *q = strchr(path + 2, '/');

        if (p == NULL || (q != NULL && q < p))
            p = q;

        if (p && p > path + 2 && p[1]) {
            path = p + 1;

            while (path[0] &&
                   !VIR_FILE_IS_DIR_SEPARATOR(path[0]))
                path++;

            /* Possibly skip a backslash after the share name */
            if (VIR_FILE_IS_DIR_SEPARATOR(path[0]))
                path++;

            return path;
        }
    }
#endif

    /* Skip initial slashes */
    if (VIR_FILE_IS_DIR_SEPARATOR(path[0])) {
        while (VIR_FILE_IS_DIR_SEPARATOR(path[0]))
            path++;

        return path;
    }

#ifdef WIN32
    /* Skip X:\ */
    if (c_isalpha(path[0]) &&
        path[1] == ':' &&
        VIR_FILE_IS_DIR_SEPARATOR(path[2]))
        return path + 3;
#endif

    return path;
}



/*
 * Creates an absolute path for a potentially relative path.
 * Return 0 if the path was not relative, or on success.
 * Return -1 on error.
 *
 * You must free the result.
 */
int
virFileAbsPath(const char *path, char **abspath)
{
    if (path[0] == '/') {
3296
        if (VIR_STRDUP(*abspath, path) < 0)
3297 3298
            return -1;
    } else {
3299 3300
        VIR_AUTOFREE(char *) buf = getcwd(NULL, 0);

3301 3302 3303
        if (buf == NULL)
            return -1;

3304
        if (virAsprintf(abspath, "%s/%s", buf, path) < 0)
3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315
            return -1;
    }

    return 0;
}

/* Remove spurious / characters from a path. The result must be freed */
char *
virFileSanitizePath(const char *path)
{
    const char *cur = path;
3316
    char *uri;
3317 3318 3319
    char *cleanpath;
    int idx = 0;

3320
    if (VIR_STRDUP(cleanpath, path) < 0)
3321 3322
        return NULL;

3323 3324 3325 3326 3327
    /* don't sanitize URIs - rfc3986 states that two slashes may lead to a
     * different resource, thus removing them would possibly change the path */
    if ((uri = strstr(path, "://")) && strchr(path, '/') > uri)
        return cleanpath;

3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361
    /* Need to sanitize:
     * //           -> //
     * ///          -> /
     * /../foo      -> /../foo
     * /foo///bar/  -> /foo/bar
     */

    /* Starting with // is valid posix, but ///foo == /foo */
    if (cur[0] == '/' && cur[1] == '/' && cur[2] != '/') {
        idx = 2;
        cur += 2;
    }

    /* Sanitize path in place */
    while (*cur != '\0') {
        if (*cur != '/') {
            cleanpath[idx++] = *cur++;
            continue;
        }

        /* Skip all extra / */
        while (*++cur == '/')
            continue;

        /* Don't add a trailing / */
        if (idx != 0 && *cur == '\0')
            break;

        cleanpath[idx++] = '/';
    }
    cleanpath[idx] = '\0';

    return cleanpath;
}
3362

3363 3364 3365 3366 3367 3368 3369 3370 3371 3372
/**
 * virFileCanonicalizePath:
 *
 * Returns the canonical representation of @path.
 *
 * The returned string must be freed after use.
 */
char *
virFileCanonicalizePath(const char *path)
{
3373
    return canonicalize_file_name(path); /* exempt from syntax-check */
3374 3375
}

3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392
/**
 * virFileRemoveLastComponent:
 *
 * For given path cut off the last component. If there's no dir
 * separator (whole path is one file name), @path is turned into
 * an empty string.
 */
void
virFileRemoveLastComponent(char *path)
{
    char *tmp;

    if ((tmp = strrchr(path, VIR_FILE_DIR_SEPARATOR)))
        tmp[1] = '\0';
    else
        path[0] = '\0';
}
3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404

/**
 * virFilePrintf:
 *
 * A replacement for fprintf() which uses virVasprintf to
 * ensure that portable string format placeholders can be
 * used, since gnulib's fprintf() replacement is not
 * LGPLV2+ compatible
 */
int virFilePrintf(FILE *fp, const char *msg, ...)
{
    va_list vargs;
3405
    VIR_AUTOFREE(char *) str = NULL;
3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418
    int ret;

    va_start(vargs, msg);

    if ((ret = virVasprintf(&str, msg, vargs)) < 0)
        goto cleanup;

    if (fwrite(str, 1, ret, fp) != ret) {
        virReportSystemError(errno, "%s",
                             _("Could not write to stream"));
        ret = -1;
    }

3419
 cleanup:
3420 3421 3422 3423
    va_end(vargs);

    return ret;
}
3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445


#ifdef __linux__

# ifndef NFS_SUPER_MAGIC
#  define NFS_SUPER_MAGIC 0x6969
# endif
# ifndef OCFS2_SUPER_MAGIC
#  define OCFS2_SUPER_MAGIC 0x7461636f
# endif
# ifndef GFS2_MAGIC
#  define GFS2_MAGIC 0x01161970
# endif
# ifndef AFS_FS_MAGIC
#  define AFS_FS_MAGIC 0x6B414653
# endif
# ifndef SMB_SUPER_MAGIC
#  define SMB_SUPER_MAGIC 0x517B
# endif
# ifndef CIFS_SUPER_MAGIC
#  define CIFS_SUPER_MAGIC 0xFF534D42
# endif
3446 3447 3448
# ifndef HUGETLBFS_MAGIC
#  define HUGETLBFS_MAGIC 0x958458f6
# endif
3449 3450 3451
# ifndef FUSE_SUPER_MAGIC
#  define FUSE_SUPER_MAGIC 0x65735546
# endif
3452 3453 3454
# ifndef CEPH_SUPER_MAGIC
#  define CEPH_SUPER_MAGIC 0x00C36400
# endif
3455 3456 3457
# ifndef GPFS_SUPER_MAGIC
#  define GPFS_SUPER_MAGIC 0x47504653
# endif
3458 3459 3460
# ifndef QB_MAGIC
#  define QB_MAGIC 0x51626d6e
# endif
3461 3462 3463 3464 3465

# define PROC_MOUNTS "/proc/mounts"

static int
virFileIsSharedFixFUSE(const char *path,
M
Marc Hartmayer 已提交
3466
                       long long *f_type)
3467 3468 3469 3470
{
    FILE *f = NULL;
    struct mntent mb;
    char mntbuf[1024];
3471 3472
    char *mntDir = NULL;
    char *mntType = NULL;
3473
    char *canonPath = NULL;
3474
    size_t maxMatching = 0;
3475 3476
    int ret = -1;

3477 3478 3479 3480 3481 3482 3483 3484 3485
    if (!(canonPath = virFileCanonicalizePath(path))) {
        virReportSystemError(errno,
                             _("unable to canonicalize %s"),
                             path);
        return -1;
    }

    VIR_DEBUG("Path canonicalization: %s->%s", path, canonPath);

3486 3487 3488 3489 3490 3491 3492 3493
    if (!(f = setmntent(PROC_MOUNTS, "r"))) {
        virReportSystemError(errno,
                             _("Unable to open %s"),
                             PROC_MOUNTS);
        goto cleanup;
    }

    while (getmntent_r(f, &mb, mntbuf, sizeof(mntbuf))) {
3494 3495
        const char *p;
        size_t len = strlen(mb.mnt_dir);
3496

3497
        if (!(p = STRSKIP(canonPath, mb.mnt_dir)))
3498
            continue;
3499

3500 3501
        if (*(p - 1) != '/' && *p != '/' && *p != '\0')
            continue;
3502

3503 3504 3505 3506 3507 3508 3509
        if (len > maxMatching) {
            maxMatching = len;
            VIR_FREE(mntType);
            VIR_FREE(mntDir);
            if (VIR_STRDUP(mntDir, mb.mnt_dir) < 0 ||
                VIR_STRDUP(mntType, mb.mnt_type) < 0)
                goto cleanup;
3510
        }
3511
    }
3512

3513 3514
    if (STREQ_NULLABLE(mntType, "fuse.glusterfs")) {
        VIR_DEBUG("Found gluster FUSE mountpoint=%s for path=%s. "
3515
                  "Fixing shared FS type", mntDir, canonPath);
3516
        *f_type = GFS2_MAGIC;
3517 3518 3519 3520
    } else if (STREQ_NULLABLE(mntType, "fuse.quobyte")) {
        VIR_DEBUG("Found Quobyte FUSE mountpoint=%s for path=%s. "
                  "Fixing shared FS type", mntDir, canonPath);
        *f_type = QB_MAGIC;
3521
    }
3522 3523 3524

    ret = 0;
 cleanup:
3525
    VIR_FREE(canonPath);
3526 3527
    VIR_FREE(mntType);
    VIR_FREE(mntDir);
3528 3529 3530 3531
    endmntent(f);
    return ret;
}

3532 3533 3534 3535 3536

int
virFileIsSharedFSType(const char *path,
                      int fstypes)
{
3537
    VIR_AUTOFREE(char *) dirpath = NULL;
3538
    char *p = NULL;
3539 3540
    struct statfs sb;
    int statfs_ret;
M
Marc Hartmayer 已提交
3541
    long long f_type = 0;
3542 3543 3544 3545

    if (VIR_STRDUP(dirpath, path) < 0)
        return -1;

3546
    statfs_ret = statfs(dirpath, &sb);
3547

3548
    while ((statfs_ret < 0) && (p != dirpath)) {
3549 3550 3551 3552 3553 3554 3555 3556 3557 3558
        /* Try less and less of the path until we get to a
         * directory we can stat. Even if we don't have 'x'
         * permission on any directory in the path on the NFS
         * server (assuming it's NFS), we will be able to stat the
         * mount point, and that will properly tell us if the
         * fstype is NFS.
         */

        if ((p = strrchr(dirpath, '/')) == NULL) {
            virReportSystemError(EINVAL,
3559
                                 _("Invalid relative path '%s'"), path);
3560 3561 3562 3563 3564 3565 3566 3567 3568
            return -1;
        }

        if (p == dirpath)
            *(p+1) = '\0';
        else
            *p = '\0';

        statfs_ret = statfs(dirpath, &sb);
3569
    }
3570 3571 3572 3573 3574 3575 3576 3577

    if (statfs_ret < 0) {
        virReportSystemError(errno,
                             _("cannot determine filesystem for '%s'"),
                             path);
        return -1;
    }

M
Marc Hartmayer 已提交
3578 3579 3580
    f_type = sb.f_type;

    if (f_type == FUSE_SUPER_MAGIC) {
3581
        VIR_DEBUG("Found FUSE mount for path=%s. Trying to fix it", path);
M
Marc Hartmayer 已提交
3582
        virFileIsSharedFixFUSE(path, &f_type);
3583 3584
    }

3585
    VIR_DEBUG("Check if path %s with FS magic %lld is shared",
M
Marc Hartmayer 已提交
3586
              path, f_type);
3587 3588

    if ((fstypes & VIR_FILE_SHFS_NFS) &&
M
Marc Hartmayer 已提交
3589
        (f_type == NFS_SUPER_MAGIC))
3590 3591 3592
        return 1;

    if ((fstypes & VIR_FILE_SHFS_GFS2) &&
M
Marc Hartmayer 已提交
3593
        (f_type == GFS2_MAGIC))
3594 3595
        return 1;
    if ((fstypes & VIR_FILE_SHFS_OCFS) &&
M
Marc Hartmayer 已提交
3596
        (f_type == OCFS2_SUPER_MAGIC))
3597 3598
        return 1;
    if ((fstypes & VIR_FILE_SHFS_AFS) &&
M
Marc Hartmayer 已提交
3599
        (f_type == AFS_FS_MAGIC))
3600 3601
        return 1;
    if ((fstypes & VIR_FILE_SHFS_SMB) &&
M
Marc Hartmayer 已提交
3602
        (f_type == SMB_SUPER_MAGIC))
3603 3604
        return 1;
    if ((fstypes & VIR_FILE_SHFS_CIFS) &&
M
Marc Hartmayer 已提交
3605
        (f_type == CIFS_SUPER_MAGIC))
3606
        return 1;
3607 3608 3609
    if ((fstypes & VIR_FILE_SHFS_CEPH) &&
        (f_type == CEPH_SUPER_MAGIC))
        return 1;
3610 3611 3612
    if ((fstypes & VIR_FILE_SHFS_GPFS) &&
        (f_type == GPFS_SUPER_MAGIC))
        return 1;
3613 3614 3615
    if ((fstypes & VIR_FILE_SHFS_QB) &&
        (f_type == QB_MAGIC))
        return 1;
3616 3617 3618

    return 0;
}
3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652

int
virFileGetHugepageSize(const char *path,
                       unsigned long long *size)
{
    int ret = -1;
    struct statfs fs;

    if (statfs(path, &fs) < 0) {
        virReportSystemError(errno,
                             _("cannot determine filesystem for '%s'"),
                             path);
        goto cleanup;
    }

    if (fs.f_type != HUGETLBFS_MAGIC) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("not a hugetlbfs mount: '%s'"),
                       path);
        goto cleanup;
    }

    *size = fs.f_bsize / 1024; /* we are storing size in KiB */
    ret = 0;
 cleanup:
    return ret;
}

# define PROC_MEMINFO "/proc/meminfo"
# define HUGEPAGESIZE_STR "Hugepagesize:"

static int
virFileGetDefaultHugepageSize(unsigned long long *size)
{
3653 3654 3655 3656
    VIR_AUTOFREE(char *) meminfo = NULL;
    char *c;
    char *n;
    char *unit;
3657 3658

    if (virFileReadAll(PROC_MEMINFO, 4096, &meminfo) < 0)
3659
        return -1;
3660 3661

    if (!(c = strstr(meminfo, HUGEPAGESIZE_STR))) {
3662 3663 3664
        virReportError(VIR_ERR_NO_SUPPORT,
                       _("%s not found in %s"),
                       HUGEPAGESIZE_STR,
3665
                       PROC_MEMINFO);
3666
        return -1;
3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678
    }
    c += strlen(HUGEPAGESIZE_STR);

    if ((n = strchr(c, '\n'))) {
        /* Cut off the rest of the meminfo file */
        *n = '\0';
    }

    if (virStrToLong_ull(c, &unit, 10, size) < 0 || STRNEQ(unit, " kB")) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unable to parse %s %s"),
                       HUGEPAGESIZE_STR, c);
3679
        return -1;
3680 3681
    }

3682
    return 0;
3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694
}

int
virFileFindHugeTLBFS(virHugeTLBFSPtr *ret_fs,
                     size_t *ret_nfs)
{
    int ret = -1;
    FILE *f = NULL;
    struct mntent mb;
    char mntbuf[1024];
    virHugeTLBFSPtr fs = NULL;
    size_t nfs = 0;
3695
    unsigned long long default_hugepagesz = 0;
3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720

    if (!(f = setmntent(PROC_MOUNTS, "r"))) {
        virReportSystemError(errno,
                             _("Unable to open %s"),
                             PROC_MOUNTS);
        goto cleanup;
    }

    while (getmntent_r(f, &mb, mntbuf, sizeof(mntbuf))) {
        virHugeTLBFSPtr tmp;

        if (STRNEQ(mb.mnt_type, "hugetlbfs"))
            continue;

        if (VIR_EXPAND_N(fs, nfs, 1) < 0)
             goto cleanup;

        tmp = &fs[nfs - 1];

        if (VIR_STRDUP(tmp->mnt_dir, mb.mnt_dir) < 0)
            goto cleanup;

        if (virFileGetHugepageSize(tmp->mnt_dir, &tmp->size) < 0)
            goto cleanup;

3721 3722 3723 3724
        if (!default_hugepagesz &&
            virFileGetDefaultHugepageSize(&default_hugepagesz) < 0)
            goto cleanup;

3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743
        tmp->deflt = tmp->size == default_hugepagesz;
    }

    *ret_fs = fs;
    *ret_nfs = nfs;
    fs = NULL;
    nfs = 0;
    ret = 0;

 cleanup:
    endmntent(f);
    while (nfs)
        VIR_FREE(fs[--nfs].mnt_dir);
    VIR_FREE(fs);
    return ret;
}

#else /* defined __linux__ */

3744 3745 3746 3747 3748 3749
int virFileIsSharedFSType(const char *path ATTRIBUTE_UNUSED,
                          int fstypes ATTRIBUTE_UNUSED)
{
    /* XXX implement me :-) */
    return 0;
}
3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768

int
virFileGetHugepageSize(const char *path ATTRIBUTE_UNUSED,
                       unsigned long long *size ATTRIBUTE_UNUSED)
{
    /* XXX implement me :-) */
    virReportUnsupportedError();
    return -1;
}

int
virFileFindHugeTLBFS(virHugeTLBFSPtr *ret_fs ATTRIBUTE_UNUSED,
                     size_t *ret_nfs ATTRIBUTE_UNUSED)
{
    /* XXX implement me :-) */
    virReportUnsupportedError();
    return -1;
}
#endif /* defined __linux__ */
3769

3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794
/**
 * virFileGetDefaultHugepage:
 * @fs: array of hugetlbfs mount points
 * @nfs: number of items in @fs
 *
 * In the passed array of hugetlbfs mount points @fs find the
 * default one. It's the one which has no '-o pagesize'.
 *
 * Returns: default hugepage, or
 *          NULL if none found
 */
virHugeTLBFSPtr
virFileGetDefaultHugepage(virHugeTLBFSPtr fs,
                          size_t nfs)
{
    size_t i;

    for (i = 0; i < nfs; i++) {
        if (fs[i].deflt)
            return &fs[i];
    }

    return NULL;
}

3795 3796 3797 3798 3799 3800 3801 3802
int virFileIsSharedFS(const char *path)
{
    return virFileIsSharedFSType(path,
                                 VIR_FILE_SHFS_NFS |
                                 VIR_FILE_SHFS_GFS2 |
                                 VIR_FILE_SHFS_OCFS |
                                 VIR_FILE_SHFS_AFS |
                                 VIR_FILE_SHFS_SMB |
3803
                                 VIR_FILE_SHFS_CIFS |
3804
                                 VIR_FILE_SHFS_CEPH |
3805 3806
                                 VIR_FILE_SHFS_GPFS|
                                 VIR_FILE_SHFS_QB);
3807
}
3808 3809


3810
#if defined(__linux__) && defined(HAVE_SYS_MOUNT_H)
3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824
int
virFileSetupDev(const char *path,
                const char *mount_options)
{
    const unsigned long mount_flags = MS_NOSUID;
    const char *mount_fs = "tmpfs";
    int ret = -1;

    if (virFileMakePath(path) < 0) {
        virReportSystemError(errno,
                             _("Failed to make path %s"), path);
        goto cleanup;
    }

3825
    VIR_DEBUG("Mount devfs on %s type=tmpfs flags=0x%lx, opts=%s",
3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855
              path, mount_flags, mount_options);
    if (mount("devfs", path, mount_fs, mount_flags, mount_options) < 0) {
        virReportSystemError(errno,
                             _("Failed to mount devfs on %s type %s (%s)"),
                             path, mount_fs, mount_options);
        goto cleanup;
    }

    ret = 0;
 cleanup:
    return ret;
}


int
virFileBindMountDevice(const char *src,
                       const char *dst)
{
    if (virFileTouch(dst, 0666) < 0)
        return -1;

    if (mount(src, dst, "none", MS_BIND, NULL) < 0) {
        virReportSystemError(errno, _("Failed to bind %s on to %s"), src,
                             dst);
        return -1;
    }

    return 0;
}

3856 3857 3858 3859 3860 3861 3862

int
virFileMoveMount(const char *src,
                 const char *dst)
{
    const unsigned long mount_flags = MS_MOVE;

3863
    if (mount(src, dst, "none", mount_flags, NULL) < 0) {
3864 3865 3866 3867 3868 3869 3870 3871 3872 3873
        virReportSystemError(errno,
                             _("Unable to move %s mount to %s"),
                             src, dst);
        return -1;
    }

    return 0;
}


3874
#else /* !defined(__linux__) || !defined(HAVE_SYS_MOUNT_H) */
3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893

int
virFileSetupDev(const char *path ATTRIBUTE_UNUSED,
                const char *mount_options ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("mount is not supported on this platform."));
    return -1;
}


int
virFileBindMountDevice(const char *src ATTRIBUTE_UNUSED,
                       const char *dst ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("mount is not supported on this platform."));
    return -1;
}
3894 3895 3896 3897 3898 3899 3900 3901 3902 3903


int
virFileMoveMount(const char *src ATTRIBUTE_UNUSED,
                 const char *dst ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("mount move is not supported on this platform."));
    return -1;
}
3904
#endif /* !defined(__linux__) || !defined(HAVE_SYS_MOUNT_H) */
M
Michal Privoznik 已提交
3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982


#if defined(HAVE_SYS_ACL_H)
int
virFileGetACLs(const char *file,
               void **acl)
{
    if (!(*acl = acl_get_file(file, ACL_TYPE_ACCESS)))
        return -1;

    return 0;
}


int
virFileSetACLs(const char *file,
               void *acl)
{
    if (acl_set_file(file, ACL_TYPE_ACCESS, acl) < 0)
        return -1;

    return 0;
}


void
virFileFreeACLs(void **acl)
{
    acl_free(*acl);
    *acl = NULL;
}

#else /* !defined(HAVE_SYS_ACL_H) */

int
virFileGetACLs(const char *file ATTRIBUTE_UNUSED,
               void **acl ATTRIBUTE_UNUSED)
{
    errno = ENOTSUP;
    return -1;
}


int
virFileSetACLs(const char *file ATTRIBUTE_UNUSED,
               void *acl ATTRIBUTE_UNUSED)
{
    errno = ENOTSUP;
    return -1;
}


void
virFileFreeACLs(void **acl)
{
    *acl = NULL;
}

#endif /* !defined(HAVE_SYS_ACL_H) */

int
virFileCopyACLs(const char *src,
                const char *dst)
{
    void *acl = NULL;
    int ret = -1;

    if (virFileGetACLs(src, &acl) < 0)
        return ret;

    if (virFileSetACLs(dst, acl) < 0)
        goto cleanup;

    ret = 0;
 cleanup:
    virFileFreeACLs(&acl);
    return ret;
}
3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001

/*
 * virFileComparePaths:
 * @p1: source path 1
 * @p2: source path 2
 *
 * Compares two paths for equality. To do so, it first canonicalizes both paths
 * to resolve all symlinks and discard relative path components. If symlinks
 * resolution or path canonicalization fails, plain string equality of @p1
 * and @p2 is performed.
 *
 * Returns:
 *  1 : Equal
 *  0 : Non-Equal
 * -1 : Error
 */
int
virFileComparePaths(const char *p1, const char *p2)
{
4002 4003
    VIR_AUTOFREE(char *) res1 = NULL;
    VIR_AUTOFREE(char *) res2 = NULL;
4004 4005 4006 4007 4008 4009 4010 4011

    /* Assume p1 and p2 are symlinks, so try to resolve and canonicalize them.
     * Canonicalization fails for example on file systems names like 'proc' or
     * 'sysfs', since they're no real paths so fallback to plain string
     * comparison.
     */
    ignore_value(virFileResolveLink(p1, &res1));
    if (!res1 && VIR_STRDUP(res1, p1) < 0)
4012
        return -1;
4013 4014 4015

    ignore_value(virFileResolveLink(p2, &res2));
    if (!res2 && VIR_STRDUP(res2, p2) < 0)
4016
        return -1;
M
Michal Privoznik 已提交
4017

4018
    return STREQ_NULLABLE(res1, res2);
M
Michal Privoznik 已提交
4019 4020 4021
}


4022
#if HAVE_DECL_SEEK_HOLE
M
Michal Privoznik 已提交
4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123
/**
 * virFileInData:
 * @fd: file to check
 * @inData: true if current position in the @fd is in data section
 * @length: amount of bytes until the end of the current section
 *
 * With sparse files not every extent has to be physically stored on
 * the disk. This results in so called data or hole sections.  This
 * function checks whether the current position in the file @fd is
 * in a data section (@inData = 1) or in a hole (@inData = 0). Also,
 * it sets @length to match the number of bytes remaining until the
 * end of the current section.
 *
 * As a special case, there is an implicit hole at the end of any
 * file. In this case, the function sets @inData = 0, @length = 0.
 *
 * Upon its return, the position in the @fd is left unchanged, i.e.
 * despite this function lseek()-ing back and forth it always
 * restores the original position in the file.
 *
 * NB, @length is type of long long because it corresponds to off_t
 * the best.
 *
 * Returns 0 on success,
 *        -1 otherwise.
 */
int
virFileInData(int fd,
              int *inData,
              long long *length)
{
    int ret = -1;
    off_t cur, data, hole, end;

    /* Get current position */
    cur = lseek(fd, 0, SEEK_CUR);
    if (cur == (off_t) -1) {
        virReportSystemError(errno, "%s",
                             _("Unable to get current position in file"));
        goto cleanup;
    }

    /* Now try to get data and hole offsets */
    data = lseek(fd, cur, SEEK_DATA);

    /* There are four options:
     * 1) data == cur;  @cur is in data
     * 2) data > cur; @cur is in a hole, next data at @data
     * 3) data < 0, errno = ENXIO; either @cur is in trailing hole, or @cur is beyond EOF.
     * 4) data < 0, errno != ENXIO; we learned nothing
     */

    if (data == (off_t) -1) {
        /* cases 3 and 4 */
        if (errno != ENXIO) {
            virReportSystemError(errno, "%s",
                                 _("Unable to seek to data"));
            goto cleanup;
        }

        *inData = 0;
        /* There are two situations now. There is always an
         * implicit hole at EOF. However, there might be a
         * trailing hole just before EOF too. If that's the case
         * report it. */
        if ((end = lseek(fd, 0, SEEK_END)) == (off_t) -1) {
            virReportSystemError(errno, "%s",
                                 _("Unable to seek to EOF"));
            goto cleanup;
        }
        *length = end - cur;
    } else if (data > cur) {
        /* case 2 */
        *inData = 0;
        *length = data - cur;
    } else {
        /* case 1 */
        *inData = 1;

        /* We don't know where does the next hole start. Let's
         * find out. Here we get the same 4 possibilities as
         * described above.*/
        hole = lseek(fd, data, SEEK_HOLE);
        if (hole == (off_t) -1 || hole == data) {
            /* cases 1, 3 and 4 */
            /* Wait a second. The reason why we are here is
             * because we are in data. But at the same time we
             * are in a trailing hole? Wut!? Do the best what we
             * can do here. */
            virReportSystemError(errno, "%s",
                                 _("unable to seek to hole"));
            goto cleanup;
        } else {
            /* case 2 */
            *length = (hole - data);
        }
    }

    ret = 0;
 cleanup:
    /* At any rate, reposition back to where we started. */
4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135
    if (cur != (off_t) -1) {
        int theerrno = errno;

        if (lseek(fd, cur, SEEK_SET) == (off_t) -1) {
            virReportSystemError(errno, "%s",
                                 _("unable to restore position in file"));
            ret = -1;
            if (theerrno == 0)
                theerrno = errno;
        }

        errno = theerrno;
4136
    }
4137 4138
    return ret;
}
4139

4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154
#else /* !HAVE_DECL_SEEK_HOLE */

int
virFileInData(int fd ATTRIBUTE_UNUSED,
              int *inData ATTRIBUTE_UNUSED,
              long long *length ATTRIBUTE_UNUSED)
{
    errno = ENOSYS;
    virReportSystemError(errno, "%s",
                         _("sparse files not supported"));
    return -1;
}

#endif /* !HAVE_DECL_SEEK_HOLE */

4155 4156 4157 4158

/**
 * virFileReadValueInt:
 * @value: pointer to int to be filled in with the value
4159
 * @format, ...: file to read from
4160
 *
4161
 * Read int from @format and put it into @value.
4162 4163 4164 4165 4166
 *
 * Return -2 for non-existing file, -1 on other errors and 0 if everything went
 * fine.
 */
int
4167
virFileReadValueInt(int *value, const char *format, ...)
4168
{
4169 4170
    VIR_AUTOFREE(char *) str = NULL;
    VIR_AUTOFREE(char *) path = NULL;
4171
    va_list ap;
4172

4173 4174 4175
    va_start(ap, format);
    if (virVasprintf(&path, format, ap) < 0) {
        va_end(ap);
4176
        return -1;
4177 4178
    }
    va_end(ap);
4179

4180 4181
    if (!virFileExists(path))
        return -2;
4182 4183

    if (virFileReadAll(path, INT_BUFSIZE_BOUND(*value), &str) < 0)
4184
        return -1;
4185

4186 4187 4188
    virStringTrimOptionalNewline(str);

    if (virStrToLong_i(str, NULL, 10, value) < 0) {
4189 4190 4191
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Invalid integer value '%s' in file '%s'"),
                       str, path);
4192
        return -1;
4193 4194
    }

4195
    return 0;
4196 4197 4198 4199 4200
}


/**
 * virFileReadValueUint:
4201 4202
 * @value: pointer to int to be filled in with the value
 * @format, ...: file to read from
4203
 *
4204
 * Read unsigned int from @format and put it into @value.
4205 4206 4207 4208 4209
 *
 * Return -2 for non-existing file, -1 on other errors and 0 if everything went
 * fine.
 */
int
4210
virFileReadValueUint(unsigned int *value, const char *format, ...)
4211
{
4212 4213
    VIR_AUTOFREE(char *) str = NULL;
    VIR_AUTOFREE(char *) path = NULL;
4214
    va_list ap;
4215

4216 4217 4218
    va_start(ap, format);
    if (virVasprintf(&path, format, ap) < 0) {
        va_end(ap);
4219
        return -1;
4220 4221
    }
    va_end(ap);
4222

4223 4224
    if (!virFileExists(path))
        return -2;
4225 4226

    if (virFileReadAll(path, INT_BUFSIZE_BOUND(*value), &str) < 0)
4227
        return -1;
4228

4229 4230
    virStringTrimOptionalNewline(str);

4231
    if (virStrToLong_uip(str, NULL, 10, value) < 0) {
4232 4233 4234
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Invalid unsigned integer value '%s' in file '%s'"),
                       str, path);
4235
        return -1;
4236 4237
    }

4238
    return 0;
4239
}
4240

4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254

/**
 * virFileReadValueScaledInt:
 * @value: pointer to unsigned long long int to be filled in with the value
 * @format, ...: file to read from
 *
 * Read unsigned scaled int from @format and put it into @value.
 *
 * Return -2 for non-existing file, -1 on other errors and 0 if everything went
 * fine.
 */
int
virFileReadValueScaledInt(unsigned long long *value, const char *format, ...)
{
4255 4256
    VIR_AUTOFREE(char *) str = NULL;
    VIR_AUTOFREE(char *) path = NULL;
4257 4258 4259 4260 4261 4262
    char *endp = NULL;
    va_list ap;

    va_start(ap, format);
    if (virVasprintf(&path, format, ap) < 0) {
        va_end(ap);
4263
        return -1;
4264 4265 4266
    }
    va_end(ap);

4267 4268
    if (!virFileExists(path))
        return -2;
4269 4270

    if (virFileReadAll(path, INT_BUFSIZE_BOUND(*value), &str) < 0)
4271
        return -1;
4272 4273 4274 4275 4276 4277 4278

    virStringTrimOptionalNewline(str);

    if (virStrToLong_ullp(str, &endp, 10, value) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Invalid unsigned scaled integer value '%s' in file '%s'"),
                       str, path);
4279
        return -1;
4280 4281
    }

4282
    return virScaleInteger(value, endp, 1024, ULLONG_MAX);
4283 4284
}

4285 4286 4287 4288
/* Arbitrarily sized number, feel free to change, but the function should be
 * used for small, interface-like files, so it should not be huge (subjective) */
#define VIR_FILE_READ_VALUE_STRING_MAX 4096

4289 4290
/**
 * virFileReadValueBitmap:
4291 4292
 * @value: pointer to virBitmapPtr to be allocated and filled in with the value
 * @format, ...: file to read from
4293
 *
4294
 * Read int from @format and put it into @value.
4295 4296 4297 4298 4299
 *
 * Return -2 for non-existing file, -1 on other errors and 0 if everything went
 * fine.
 */
int
4300
virFileReadValueBitmap(virBitmapPtr *value, const char *format, ...)
4301
{
4302 4303
    VIR_AUTOFREE(char *) str = NULL;
    VIR_AUTOFREE(char *) path = NULL;
4304
    va_list ap;
4305

4306 4307 4308
    va_start(ap, format);
    if (virVasprintf(&path, format, ap) < 0) {
        va_end(ap);
4309
        return -1;
4310 4311
    }
    va_end(ap);
4312

4313 4314
    if (!virFileExists(path))
        return -2;
4315

4316
    if (virFileReadAll(path, VIR_FILE_READ_VALUE_STRING_MAX, &str) < 0)
4317
        return -1;
4318

4319 4320 4321
    virStringTrimOptionalNewline(str);

    *value = virBitmapParseUnlimited(str);
4322
    if (!*value)
4323
        return -1;
4324

4325
    return 0;
4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342
}

/**
 * virFileReadValueString:
 * @value: pointer to char * to be allocated and filled in with the value
 * @format, ...: file to read from
 *
 * Read string from @format and put it into @value.  Don't get this mixed with
 * virFileReadAll().  This function is a wrapper over it with the behaviour
 * aligned to other virFileReadValue* functions
 *
 * Return -2 for non-existing file, -1 on other errors and 0 if everything went
 * fine.
 */
int
virFileReadValueString(char **value, const char *format, ...)
{
4343 4344
    int ret;
    VIR_AUTOFREE(char *) path = NULL;
4345 4346 4347 4348 4349
    va_list ap;

    va_start(ap, format);
    if (virVasprintf(&path, format, ap) < 0) {
        va_end(ap);
4350
        return -1;
4351 4352 4353
    }
    va_end(ap);

4354 4355
    if (!virFileExists(path))
        return -2;
4356 4357 4358 4359 4360

    ret = virFileReadAll(path, VIR_FILE_READ_VALUE_STRING_MAX, value);

    if (*value)
        virStringTrimOptionalNewline(*value);
4361

4362 4363
    return ret;
}
4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389


/**
 * virFileWaitForExists:
 * @path: absolute path to a sysfs attribute (can be a symlink)
 * @ms: how long to wait (in milliseconds)
 * @tries: how many times should we try to wait for @path to become accessible
 *
 * Checks the existence of @path. In case the file defined by @path
 * doesn't exist, we wait for it to appear in @ms milliseconds (for up to
 * @tries attempts).
 *
 * Returns 0 on success, -1 on error, setting errno appropriately.
 */
int
virFileWaitForExists(const char *path,
                     size_t ms,
                     size_t tries)
{
    errno = 0;

    /* wait for @path to be accessible in @ms milliseconds, up to @tries */
    while (tries-- > 0 && !virFileExists(path)) {
        if (tries == 0 || errno != ENOENT)
            return -1;

4390
        g_usleep(ms * 1000);
4391 4392 4393 4394
    }

    return 0;
}
4395 4396 4397 4398


#if HAVE_LIBATTR
/**
4399
 * virFileGetXAttrQuiet;
4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410
 * @path: a filename
 * @name: name of xattr
 * @value: read value
 *
 * Reads xattr with @name for given @path and stores it into
 * @value. Caller is responsible for freeing @value.
 *
 * Returns: 0 on success,
 *         -1 otherwise (with errno set).
 */
int
4411 4412 4413
virFileGetXAttrQuiet(const char *path,
                     const char *name,
                     char **value)
4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455
{
    char *buf = NULL;
    int ret = -1;

    /* We might be racing with somebody who sets the same attribute. */
    while (1) {
        ssize_t need;
        ssize_t got;

        /* The first call determines how many bytes we need to allocate. */
        if ((need = getxattr(path, name, NULL, 0)) < 0)
            goto cleanup;

        if (VIR_REALLOC_N_QUIET(buf, need + 1) < 0)
            goto cleanup;

        if ((got = getxattr(path, name, buf, need)) < 0) {
            if (errno == ERANGE)
                continue;
            goto cleanup;
        }

        buf[got] = '\0';
        break;
    }

    VIR_STEAL_PTR(*value, buf);
    ret = 0;
 cleanup:
    VIR_FREE(buf);
    return ret;
}

/**
 * virFileSetXAttr:
 * @path: a filename
 * @name: name of xattr
 * @value: value to set
 *
 * Sets xattr of @name and @value on @path.
 *
 * Returns: 0 on success,
4456
 *         -1 otherwise (with errno set AND error reported).
4457 4458 4459 4460 4461 4462
 */
int
virFileSetXAttr(const char *path,
                const char *name,
                const char *value)
{
4463 4464 4465 4466 4467 4468 4469 4470
    if (setxattr(path, name, value, strlen(value), 0) < 0) {
        virReportSystemError(errno,
                             _("Unable to set XATTR %s on %s"),
                             name, path);
        return -1;
    }

    return 0;
4471 4472 4473 4474 4475 4476 4477 4478 4479 4480
}

/**
 * virFileRemoveXAttr:
 * @path: a filename
 * @name: name of xattr
 *
 * Remove xattr of @name on @path.
 *
 * Returns: 0 on success,
4481
 *         -1 otherwise (with errno set AND error reported).
4482 4483 4484 4485 4486
 */
int
virFileRemoveXAttr(const char *path,
                   const char *name)
{
4487 4488 4489 4490 4491 4492 4493 4494
    if (removexattr(path, name) < 0) {
        virReportSystemError(errno,
                             _("Unable to remove XATTR %s on %s"),
                             name, path);
        return -1;
    }

    return 0;
4495 4496 4497 4498 4499
}

#else /* !HAVE_LIBATTR */

int
4500 4501 4502
virFileGetXAttrQuiet(const char *path ATTRIBUTE_UNUSED,
                     const char *name ATTRIBUTE_UNUSED,
                     char **value ATTRIBUTE_UNUSED)
4503 4504 4505 4506 4507 4508
{
    errno = ENOSYS;
    return -1;
}

int
4509 4510
virFileSetXAttr(const char *path,
                const char *name,
4511 4512 4513
                const char *value ATTRIBUTE_UNUSED)
{
    errno = ENOSYS;
4514 4515 4516
    virReportSystemError(errno,
                         _("Unable to set XATTR %s on %s"),
                         name, path);
4517 4518 4519 4520
    return -1;
}

int
4521 4522
virFileRemoveXAttr(const char *path,
                   const char *name)
4523 4524
{
    errno = ENOSYS;
4525 4526 4527
    virReportSystemError(errno,
                         _("Unable to remove XATTR %s on %s"),
                         name, path);
4528 4529 4530 4531
    return -1;
}

#endif /* HAVE_LIBATTR */
4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559

/**
 * virFileGetXAttr;
 * @path: a filename
 * @name: name of xattr
 * @value: read value
 *
 * Reads xattr with @name for given @path and stores it into
 * @value. Caller is responsible for freeing @value.
 *
 * Returns: 0 on success,
 *         -1 otherwise (with errno set AND error reported).
 */
int
virFileGetXAttr(const char *path,
                const char *name,
                char **value)
{
    int ret;

    if ((ret = virFileGetXAttrQuiet(path, name, value)) < 0) {
        virReportSystemError(errno,
                             _("Unable to get XATTR %s on %s"),
                             name, path);
    }

    return ret;
}