virchrdev.c 12.1 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
#include "virfile.h"
40
#include "virstring.h"
41 42 43

#define VIR_FROM_THIS VIR_FROM_NONE

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

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

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

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

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

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

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

    sanitizedPath = virFileSanitizePath(path);

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

    return sanitizedPath;
}

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

    /* build lock file path */
122
    if (!(path = virChrdevLockFilePath(dev)))
123 124 125 126 127
        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 */
128
        virReportError(VIR_ERR_OPERATION_FAILED,
129
                       _("Requested device '%s' is locked by "
130
                         "lock file '%s' held by process %lld"),
131
                       dev, path, (long long) pid);
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
        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) {
152 153
            VIR_DEBUG("Skipping lock file creation for device '%s in path '%s'.",
                      dev, path);
154 155 156 157 158
            ret = 0;
            goto cleanup;
        }
        virReportSystemError(errno,
                             _("Couldn't create lock file for "
159 160
                               "device '%s' in path '%s'"),
                             dev, path);
161 162 163 164 165 166 167
        goto cleanup;
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

318
    VIR_FREE(devs);
319 320 321
}

/**
322 323 324
 * 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
325 326
 * same FD by two processes.
 *
327
 * @devs Pointer to private structure holding data about device streams.
328
 * @source Pointer to private structure holding data about device source.
329 330 331
 * @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.
332
 *
333
 * Returns 0 on success and st is connected to the selected device and
334
 * corresponding lock file is created (if configured). Returns -1 on
335
 * error and 1 if the device stream is open and busy.
336
 */
337
int virChrdevOpen(virChrdevsPtr devs,
338 339 340
                  virDomainChrSourceDefPtr source,
                  virStreamPtr st,
                  bool force)
341
{
342
    virChrdevStreamInfoPtr cbdata = NULL;
343
    virStreamPtr savedStream;
344
    const char *path;
345 346
    int ret;

347 348 349 350 351 352 353 354 355 356 357 358 359 360
    switch (source->type) {
    case VIR_DOMAIN_CHR_TYPE_PTY:
        path = source->data.file.path;
        break;
    case VIR_DOMAIN_CHR_TYPE_UNIX:
        path = source->data.nix.path;
        break;
    default:
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Unsupported device type '%s'"),
                       virDomainChrTypeToString(source->type));
        return -1;
    }

361
    virMutexLock(&devs->lock);
362

363
    if ((savedStream = virHashLookup(devs->hash, path))) {
364
        if (!force) {
365 366
             /* entry found, device is busy */
            virMutexUnlock(&devs->lock);
367 368 369
            return 1;
       } else {
           /* terminate existing connection */
370
           /* The internal close callback handler needs to lock devs->lock to
371 372 373
            * 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
374
            * stream manually before we create a new device connection.
375 376 377
            */
           virFDStreamSetInternalCloseCb(savedStream, NULL, NULL, NULL);
           virStreamAbort(savedStream);
378
           virHashRemoveEntry(devs->hash, path);
379 380 381 382 383
           /* continue adding a new stream connection */
       }
    }

    /* create the lock file */
384 385
    if ((ret = virChrdevLockFileCreate(path)) < 0) {
        virMutexUnlock(&devs->lock);
386 387 388 389 390
        return ret;
    }

    /* obtain a reference to the stream */
    if (virStreamRef(st) < 0) {
391
        virMutexUnlock(&devs->lock);
392 393 394 395 396 397 398 399
        return -1;
    }

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

400
    if (virHashAddEntry(devs->hash, path, st) < 0)
401 402
        goto error;

403 404
    cbdata->devs = devs;
    if (!(cbdata->path = strdup(path))) {
405 406 407 408
        virReportOOMError();
        goto error;
    }

409
    /* open the character device */
410 411 412 413 414 415 416 417 418 419 420 421 422
    switch (source->type) {
    case VIR_DOMAIN_CHR_TYPE_PTY:
        if (virFDStreamOpenFile(st, path, 0, 0, O_RDWR) < 0)
            goto error;
        break;
    case VIR_DOMAIN_CHR_TYPE_UNIX:
        if (virFDStreamConnectUNIX(st, path, false) < 0)
            goto error;
        break;
    default:
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Unsupported device type '%s'"),
                       virDomainChrTypeToString(source->type));
423
        goto error;
424
    }
425 426

    /* add cleanup callback */
427
    virFDStreamSetInternalCloseCb(st,
428
                                  virChrdevFDStreamCloseCb,
429
                                  cbdata,
430
                                  virChrdevFDStreamCloseCbFree);
431

432
    virMutexUnlock(&devs->lock);
433 434 435 436
    return 0;

error:
    virStreamFree(st);
437
    virHashRemoveEntry(devs->hash, path);
438
    if (cbdata)
439
        VIR_FREE(cbdata->path);
440
    VIR_FREE(cbdata);
441
    virMutexUnlock(&devs->lock);
442 443
    return -1;
}