virfile.c 6.9 KB
Newer Older
1
/*
E
Eric Blake 已提交
2
 * virfile.c: safer file handling
3
 *
E
Eric Blake 已提交
4
 * Copyright (C) 2010-2011 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
 * 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
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
 *
 */

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

28 29 30 31
#include "virfile.h"

#include <fcntl.h>
#include <sys/stat.h>
32 33
#include <unistd.h>

34 35 36 37 38 39 40 41 42 43
#include "command.h"
#include "configmake.h"
#include "memory.h"
#include "virterror_internal.h"

#define VIR_FROM_THIS VIR_FROM_NONE
#define virFileError(code, ...)                                   \
    virReportErrorHelper(VIR_FROM_THIS, code, __FILE__,           \
                         __FUNCTION__, __LINE__, __VA_ARGS__)

44

E
Eric Blake 已提交
45
int virFileClose(int *fdptr, bool preserve_errno)
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
{
    int saved_errno;
    int rc = 0;

    if (*fdptr >= 0) {
        if (preserve_errno)
            saved_errno = errno;
        rc = close(*fdptr);
        *fdptr = -1;
        if (preserve_errno)
            errno = saved_errno;
    }

    return rc;
}
61 62


E
Eric Blake 已提交
63
int virFileFclose(FILE **file, bool preserve_errno)
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
{
    int saved_errno;
    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 已提交
81
FILE *virFileFdopen(int *fdptr, const char *mode)
82 83 84 85 86 87 88 89 90 91 92 93 94
{
    FILE *file = NULL;

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

    return file;
}
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253


/* Opaque type for managing a wrapper around an O_DIRECT fd.  For now,
 * read-write is not supported, just a single direction.  */
struct _virFileDirectFd {
    virCommandPtr cmd; /* Child iohelper process to do the I/O.  */
};

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

/**
 * virFileDirectFdNew:
 * @fd: pointer to fd to wrap
 * @name: name of fd, for diagnostics
 *
 * Update *FD (created with virFileDirectFdFlag() among the flags to
 * open()) to ensure that all I/O to that file will bypass the system
 * cache.  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.
 *
 * On success, the new wrapper object is returned, which must be later
 * freed with virFileDirectFdFree().  On failure, *FD is unchanged, an
 * error message is output, and NULL is returned.
 */
virFileDirectFdPtr
virFileDirectFdNew(int *fd, const char *name)
{
    virFileDirectFdPtr ret = NULL;
    bool output = false;
    int pipefd[2] = { -1, -1 };
    int mode = -1;

    /* XXX support posix_fadvise rather than spawning a child, if the
     * kernel support for that is decent enough.  */

    if (!O_DIRECT) {
        virFileError(VIR_ERR_INTERNAL_ERROR, "%s",
                     _("O_DIRECT unsupported on this platform"));
        return NULL;
    }

    if (VIR_ALLOC(ret) < 0) {
        virReportOOMError();
        return NULL;
    }

#ifdef F_GETFL
    /* Mingw lacks F_GETFL, but it also lacks O_DIRECT so didn't get
     * here in the first place.  All other platforms reach this
     * line.  */
    mode = fcntl(*fd, F_GETFL);
#endif

    if (mode < 0) {
        virFileError(VIR_ERR_INTERNAL_ERROR, _("invalid fd %d for %s"),
                     *fd, name);
        goto error;
    } else if ((mode & O_ACCMODE) == O_WRONLY) {
        output = true;
    } else if ((mode & O_ACCMODE) != O_RDONLY) {
        virFileError(VIR_ERR_INTERNAL_ERROR, _("unexpected mode %x for %s"),
                     mode & O_ACCMODE, name);
        goto error;
    }

    if (pipe2(pipefd, O_CLOEXEC) < 0) {
        virFileError(VIR_ERR_INTERNAL_ERROR,
                     _("unable to create pipe for %s"), name);
        goto error;
    }

    ret->cmd = virCommandNewArgList(LIBEXECDIR "/libvirt_iohelper",
                                    name, "0", NULL);
    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");
    }

    if (virCommandRunAsync(ret->cmd, NULL) < 0)
        goto error;

    if (VIR_CLOSE(pipefd[!output]) < 0) {
        virFileError(VIR_ERR_INTERNAL_ERROR, "%s", _("unable to close pipe"));
        goto error;
    }

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

error:
    VIR_FORCE_CLOSE(pipefd[0]);
    VIR_FORCE_CLOSE(pipefd[1]);
    virFileDirectFdFree(ret);
    return NULL;
}

/**
 * virFileDirectFdClose:
 * @dfd: direct fd wrapper, or NULL
 *
 * If DFD is valid, then ensure that I/O has completed, which may
 * include reaping a child process.  Return 0 if all data for the
 * wrapped fd is complete, or -1 on failure with an error emitted.
 * This function intentionally returns 0 when DFD is NULL, so that
 * callers can conditionally create a virFileDirectFd wrapper but
 * unconditionally call the cleanup code.  To avoid deadlock, only
 * call this after closing the fd resulting from virFileDirectFdNew().
 */
int
virFileDirectFdClose(virFileDirectFdPtr dfd)
{
    if (!dfd)
        return 0;

    return virCommandWait(dfd->cmd, NULL);
}

/**
 * virFileDirectFdFree:
 * @dfd: direct fd wrapper, or NULL
 *
 * Free all remaining resources associated with DFD.  If
 * virFileDirectFdClose() was not previously called, then this may
 * discard some previous I/O.  To avoid deadlock, only call this after
 * closing the fd resulting from virFileDirectFdNew().
 */
void
virFileDirectFdFree(virFileDirectFdPtr dfd)
{
    if (!dfd)
        return;

    virCommandFree(dfd->cmd);
    VIR_FREE(dfd);
}