You need to sign in or sign up before continuing.
virchrdev.c 11.2 KB
Newer Older
1
/**
2
 * virchrdev.c: api to guarantee mutually exclusive
3
 * access to domain's character devices
4 5 6 7 8 9 10 11 12 13 14 15 16 17
 *
 * Copyright (C) 2011-2012 Red Hat, Inc.
 *
 * 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
18
 * License along with this library.  If not, see
O
Osier Yang 已提交
19
 * <http://www.gnu.org/licenses/>.
20 21 22 23 24 25 26 27 28 29
 *
 * Author: Peter Krempa <pkrempa@redhat.com>
 */

#include <config.h>

#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>

30
#include "virchrdev.h"
31 32 33
#include "virhash.h"
#include "fdstream.h"
#include "internal.h"
34
#include "virthread.h"
35
#include "viralloc.h"
36
#include "virpidfile.h"
37
#include "virlog.h"
38
#include "virerror.h"
39 40 41 42
#include "virfile.h"

#define VIR_FROM_THIS VIR_FROM_NONE

43
/* structure holding information about character devices
44
 * open in a given domain */
45
struct _virChrdevs {
46 47 48 49
    virMutex lock;
    virHashTablePtr hash;
};

50 51 52 53 54
typedef struct _virChrdevStreamInfo virChrdevStreamInfo;
typedef virChrdevStreamInfo *virChrdevStreamInfoPtr;
struct _virChrdevStreamInfo {
    virChrdevsPtr devs;
    const char *path;
55 56
};

57
#ifdef VIR_CHRDEV_LOCK_FILE_PATH
58 59
/**
 * Create a full filename with path to the lock file based on
60
 * name/path of corresponding device
61
 *
62
 * @dev path of the character device
63 64 65 66
 *
 * Returns a modified name that the caller has to free, or NULL
 * on error.
 */
67
static char *virChrdevLockFilePath(const char *dev)
68 69 70
{
    char *path = NULL;
    char *sanitizedPath = NULL;
71
    char *devCopy;
72 73 74
    char *filename;
    char *p;

75
    if (!(devCopy = strdup(dev))) {
76 77 78 79 80
        virReportOOMError();
        goto cleanup;
    }

    /* skip the leading "/dev/" */
81
    filename = STRSKIP(devCopy, "/dev");
82
    if (!filename)
83
        filename = devCopy;
84 85 86 87 88 89 90 91 92

    /* substitute path forward slashes for underscores */
    p = filename;
    while (*p) {
        if (*p == '/')
            *p = '_';
        ++p;
    }

93
    if (virAsprintf(&path, "%s/LCK..%s", VIR_CHRDEV_LOCK_FILE_PATH, filename) < 0)
94 95 96 97 98 99
        goto cleanup;

    sanitizedPath = virFileSanitizePath(path);

cleanup:
    VIR_FREE(path);
100
    VIR_FREE(devCopy);
101 102 103 104 105

    return sanitizedPath;
}

/**
106
 * Verify and create a lock file for a character device
107
 *
108
 * @dev Path of the character device
109 110 111
 *
 * Returns 0 on success, -1 on error
 */
112
static int virChrdevLockFileCreate(const char *dev)
113 114 115 116 117 118 119 120
{
    char *path = NULL;
    int ret = -1;
    int lockfd = -1;
    char *pidStr = NULL;
    pid_t pid;

    /* build lock file path */
121
    if (!(path = virChrdevLockFilePath(dev)))
122 123 124 125 126
        goto cleanup;

    /* check if a log file and process holding the lock still exists */
    if (virPidFileReadPathIfAlive(path, &pid, NULL) == 0 && pid >= 0) {
        /* the process exists, the lockfile is valid */
127
        virReportError(VIR_ERR_OPERATION_FAILED,
128
                       _("Requested device '%s' is locked by "
129
                         "lock file '%s' held by process %lld"),
130
                       dev, path, (long long) pid);
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
        goto cleanup;
    } else {
        /* clean up the stale/corrupted/nonexistent lockfile */
        unlink(path);
    }
    /* lockfile doesn't (shouldn't) exist */

    /* ensure correct format according to filesystem hierarchy standard */
    /* http://www.pathname.com/fhs/pub/fhs-2.3.html#VARLOCKLOCKFILES */
    if (virAsprintf(&pidStr, "%10lld\n", (long long) getpid()) < 0)
        goto cleanup;

    /* create the lock file */
    if ((lockfd = open(path, O_WRONLY | O_CREAT | O_EXCL, 00644)) < 0) {
        /* If we run in session mode, we might have no access to the lock
         * file directory. We have to check for an permission denied error
         * and see if we can reach it. This should cause an error only if
         * we run in daemon mode and thus privileged.
         */
        if (errno == EACCES && geteuid() != 0) {
151 152
            VIR_DEBUG("Skipping lock file creation for device '%s in path '%s'.",
                      dev, path);
153 154 155 156 157
            ret = 0;
            goto cleanup;
        }
        virReportSystemError(errno,
                             _("Couldn't create lock file for "
158 159
                               "device '%s' in path '%s'"),
                             dev, path);
160 161 162 163 164 165 166
        goto cleanup;
    }

    /* write the pid to the file */
    if (safewrite(lockfd, pidStr, strlen(pidStr)) < 0) {
        virReportSystemError(errno,
                             _("Couldn't write to lock file for "
167 168
                               "device '%s' in path '%s'"),
                             dev, path);
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
        VIR_FORCE_CLOSE(lockfd);
        unlink(path);
        goto cleanup;
    }

    /* we hold the lock */
    ret = 0;

cleanup:
    VIR_FORCE_CLOSE(lockfd);
    VIR_FREE(path);
    VIR_FREE(pidStr);

    return ret;
}

/**
186
 * Remove a lock file for a device
187
 *
188
 * @dev Path of the device
189
 */
190
static void virChrdevLockFileRemove(const char *dev)
191
{
192
    char *path = virChrdevLockFilePath(dev);
193 194 195 196
    if (path)
        unlink(path);
    VIR_FREE(path);
}
197 198 199
#else /* #ifdef VIR_CHRDEV_LOCK_FILE_PATH */
/* file locking for character devices is disabled */
static int virChrdevLockFileCreate(const char *dev ATTRIBUTE_UNUSED)
200 201 202 203
{
    return 0;
}

204
static void virChrdevLockFileRemove(const char *dev ATTRIBUTE_UNUSED)
205 206 207
{
    return;
}
208
#endif /* #ifdef VIR_CHRDEV_LOCK_FILE_PATH */
209 210

/**
211
 * Frees an entry from the hash containing domain's active devices
212
 *
213 214
 * @data Opaque data, struct holding information about the device
 * @name Path of the device.
215
 */
216
static void virChrdevHashEntryFree(void *data,
217 218
                                    const void *name)
{
219
    const char *dev = name;
220 221 222 223 224 225
    virStreamPtr st = data;

    /* free stream reference */
    virStreamFree(st);

    /* delete lock file */
226
    virChrdevLockFileRemove(dev);
227 228 229 230 231 232 233
}

/**
 * Frees opaque data provided for the stream closing callback
 *
 * @opaque Data to be freed.
 */
234
static void virChrdevFDStreamCloseCbFree(void *opaque)
235
{
236
    virChrdevStreamInfoPtr priv = opaque;
237

238
    VIR_FREE(priv->path);
239 240 241 242
    VIR_FREE(priv);
}

/**
243
 * Callback being called if a FDstream is closed. Frees device entries
244 245 246
 * from data structures and removes lockfiles.
 *
 * @st Pointer to stream being closed.
247
 * @opaque Domain's device information structure.
248
 */
249
static void virChrdevFDStreamCloseCb(virStreamPtr st ATTRIBUTE_UNUSED,
250 251
                                      void *opaque)
{
252 253
    virChrdevStreamInfoPtr priv = opaque;
    virMutexLock(&priv->devs->lock);
254 255

    /* remove entry from hash */
256
    virHashRemoveEntry(priv->devs->hash, priv->path);
257

258
    virMutexUnlock(&priv->devs->lock);
259 260 261
}

/**
262
 * Allocate structures for storing information about active device streams
263 264 265 266
 * in domain's private data section.
 *
 * Returns pointer to the allocated structure or NULL on error
 */
267
virChrdevsPtr virChrdevAlloc(void)
268
{
269 270
    virChrdevsPtr devs;
    if (VIR_ALLOC(devs) < 0)
271 272
        return NULL;

273 274
    if (virMutexInit(&devs->lock) < 0) {
        VIR_FREE(devs);
275 276 277
        return NULL;
    }

278
    /* there will hardly be any devices most of the time, the hash
279
     * does not have to be huge */
280
    if (!(devs->hash = virHashCreate(3, virChrdevHashEntryFree)))
281 282
        goto error;

283
    return devs;
284
error:
285
    virChrdevFree(devs);
286 287 288
    return NULL;
}

289 290 291
/**
 * Helper to clear stream callbacks when freeing the hash
 */
292
static void virChrdevFreeClearCallbacks(void *payload,
293 294 295 296 297 298 299 300
                                         const void *name ATTRIBUTE_UNUSED,
                                         void *data ATTRIBUTE_UNUSED)
{
    virStreamPtr st = payload;

    virFDStreamSetInternalCloseCb(st, NULL, NULL, NULL);
}

301
/**
302
 * Free structures for handling open device streams.
303
 *
304
 * @devs Pointer to the private structure.
305
 */
306
void virChrdevFree(virChrdevsPtr devs)
307
{
308
    if (!devs || !devs->hash)
309 310
        return;

311 312 313 314 315
    virMutexLock(&devs->lock);
    virHashForEach(devs->hash, virChrdevFreeClearCallbacks, NULL);
    virHashFree(devs->hash);
    virMutexUnlock(&devs->lock);
    virMutexDestroy(&devs->lock);
316

317
    VIR_FREE(devs);
318 319 320
}

/**
321 322 323
 * Open a device stream for a domain ensuring that other streams are
 * not using the device, nor any lockfiles exist. This ensures that
 * the device stream does not get corrupted due to a race on reading
324 325
 * same FD by two processes.
 *
326 327 328 329 330
 * @devs Pointer to private structure holding data about device streams.
 * @path Path to the character device to be opened.
 * @st Stream the client wishes to use for the device connection.
 * @force On true, close active device streams for the selected character
 *        device before opening this connection.
331
 *
332
 * Returns 0 on success and st is connected to the selected device and
333
 * corresponding lock file is created (if configured). Returns -1 on
334
 * error and 1 if the device stream is open and busy.
335
 */
336 337
int virChrdevOpen(virChrdevsPtr devs,
                   const char *path,
338 339 340
                   virStreamPtr st,
                   bool force)
{
341
    virChrdevStreamInfoPtr cbdata = NULL;
342 343 344
    virStreamPtr savedStream;
    int ret;

345
    virMutexLock(&devs->lock);
346

347
    if ((savedStream = virHashLookup(devs->hash, path))) {
348
        if (!force) {
349 350
             /* entry found, device is busy */
            virMutexUnlock(&devs->lock);
351 352 353
            return 1;
       } else {
           /* terminate existing connection */
354
           /* The internal close callback handler needs to lock devs->lock to
355 356 357
            * remove the aborted stream from the hash. This would cause a
            * deadlock as we would try to enter the lock twice from the very
            * same thread. We need to unregister the callback and abort the
358
            * stream manually before we create a new device connection.
359 360 361
            */
           virFDStreamSetInternalCloseCb(savedStream, NULL, NULL, NULL);
           virStreamAbort(savedStream);
362
           virHashRemoveEntry(devs->hash, path);
363 364 365 366 367
           /* continue adding a new stream connection */
       }
    }

    /* create the lock file */
368 369
    if ((ret = virChrdevLockFileCreate(path)) < 0) {
        virMutexUnlock(&devs->lock);
370 371 372 373 374
        return ret;
    }

    /* obtain a reference to the stream */
    if (virStreamRef(st) < 0) {
375
        virMutexUnlock(&devs->lock);
376 377 378 379 380 381 382 383
        return -1;
    }

    if (VIR_ALLOC(cbdata) < 0) {
        virReportOOMError();
        goto error;
    }

384
    if (virHashAddEntry(devs->hash, path, st) < 0)
385 386
        goto error;

387 388
    cbdata->devs = devs;
    if (!(cbdata->path = strdup(path))) {
389 390 391 392
        virReportOOMError();
        goto error;
    }

393 394
    /* open the character device */
    if (virFDStreamOpenFile(st, path, 0, 0, O_RDWR) < 0)
395 396 397
        goto error;

    /* add cleanup callback */
398
    virFDStreamSetInternalCloseCb(st,
399
                                  virChrdevFDStreamCloseCb,
400
                                  cbdata,
401
                                  virChrdevFDStreamCloseCbFree);
402

403
    virMutexUnlock(&devs->lock);
404 405 406 407
    return 0;

error:
    virStreamFree(st);
408
    virHashRemoveEntry(devs->hash, path);
409
    if (cbdata)
410
        VIR_FREE(cbdata->path);
411
    VIR_FREE(cbdata);
412
    virMutexUnlock(&devs->lock);
413 414
    return -1;
}