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

#include <config.h>

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

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

#define VIR_FROM_THIS VIR_FROM_NONE

42 43
VIR_LOG_INIT("conf.chrdev");

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
        goto cleanup;

    sanitizedPath = virFileSanitizePath(path);

97
 cleanup:
98
    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
        VIR_FORCE_CLOSE(lockfd);
        unlink(path);
        goto cleanup;
    }

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

176
 cleanup:
177 178 179 180 181 182 183 184
    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
#else /* #ifdef VIR_CHRDEV_LOCK_FILE_PATH */
/* file locking for character devices is disabled */
J
Ján Tomko 已提交
198
static int virChrdevLockFileCreate(const char *dev G_GNUC_UNUSED)
199 200 201 202
{
    return 0;
}

J
Ján Tomko 已提交
203
static void virChrdevLockFileRemove(const char *dev G_GNUC_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
    virStreamPtr st = data;

    /* free stream reference */
222
    virObjectUnref(st);
223 224

    /* 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
 */
J
Ján Tomko 已提交
248
static void virChrdevFDStreamCloseCb(virStreamPtr st G_GNUC_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 int virChrdevFreeClearCallbacks(void *payload,
J
Ján Tomko 已提交
294 295
                                       const void *name G_GNUC_UNUSED,
                                       void *data G_GNUC_UNUSED)
296 297 298 299
{
    virStreamPtr st = payload;

    virFDStreamSetInternalCloseCb(st, NULL, NULL, NULL);
300
    return 0;
301 302
}

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

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

319
    VIR_FREE(devs);
320 321 322
}

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

349 350 351
    switch (source->type) {
    case VIR_DOMAIN_CHR_TYPE_PTY:
        path = source->data.file.path;
352 353 354 355 356
        if (!path) {
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("PTY device is not yet assigned"));
            return -1;
        }
357 358 359 360 361 362 363 364 365 366 367
        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;
    }

368
    virMutexLock(&devs->lock);
369

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

    /* create the lock file */
391 392
    if ((ret = virChrdevLockFileCreate(path)) < 0) {
        virMutexUnlock(&devs->lock);
393 394 395 396 397
        return ret;
    }

    /* obtain a reference to the stream */
    if (virStreamRef(st) < 0) {
398
        virMutexUnlock(&devs->lock);
399 400 401
        return -1;
    }

402
    if (VIR_ALLOC(cbdata) < 0)
403 404
        goto error;

405
    if (virHashAddEntry(devs->hash, path, st) < 0)
406
        goto error;
407
    added = true;
408

409
    cbdata->devs = devs;
410
    if (VIR_STRDUP(cbdata->path, path) < 0)
411 412
        goto error;

413
    /* open the character device */
414 415
    switch (source->type) {
    case VIR_DOMAIN_CHR_TYPE_PTY:
R
Roman Bogorodskiy 已提交
416
        if (virFDStreamOpenPTY(st, path, 0, 0, O_RDWR) < 0)
417 418 419 420 421 422 423 424 425 426
            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));
427
        goto error;
428
    }
429 430

    /* add cleanup callback */
431
    virFDStreamSetInternalCloseCb(st,
432
                                  virChrdevFDStreamCloseCb,
433
                                  cbdata,
434
                                  virChrdevFDStreamCloseCbFree);
435

436
    virMutexUnlock(&devs->lock);
437 438
    return 0;

439
 error:
440 441 442
    if (added)
        virHashRemoveEntry(devs->hash, path);
    else
443
        virObjectUnref(st);
444

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