virchrdev.c 12.3 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
typedef struct _virChrdevStreamInfo virChrdevStreamInfo;
typedef virChrdevStreamInfo *virChrdevStreamInfoPtr;
struct _virChrdevStreamInfo {
    virChrdevsPtr devs;
55
    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 (VIR_STRDUP(devCopy, dev) < 0)
77 78 79
        goto cleanup;

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

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

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

    sanitizedPath = virFileSanitizePath(path);

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

    return sanitizedPath;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

272
    if (virMutexInit(&devs->lock) < 0) {
273 274
        virReportSystemError(errno, "%s",
                             _("Unable to init device stream mutex"));
275
        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
    char *path;
345
    int ret;
346 347
    bool added = false;
    virErrorPtr savedError;
348

349 350 351 352 353 354 355 356 357 358 359 360 361 362
    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;
    }

363
    virMutexLock(&devs->lock);
364

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

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

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

397
    if (VIR_ALLOC(cbdata) < 0)
398 399
        goto error;

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

404
    cbdata->devs = devs;
405
    if (VIR_STRDUP(cbdata->path, path) < 0)
406 407
        goto error;

408
    /* open the character device */
409 410 411 412 413 414 415 416 417 418 419 420 421
    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));
422
        goto error;
423
    }
424 425

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

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

error:
435 436 437 438 439 440 441 442 443 444
    savedError = virSaveLastError();

    if (added)
        virHashRemoveEntry(devs->hash, path);
    else
        virStreamFree(st);

    virSetError(savedError);
    virFreeError(savedError);

445
    if (cbdata)
446
        VIR_FREE(cbdata->path);
447
    VIR_FREE(cbdata);
448
    virMutexUnlock(&devs->lock);
449 450
    return -1;
}