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 72
    g_autofree char *path = NULL;
    g_autofree char *sanitizedPath = NULL;
    g_autofree char *devCopy = NULL;
73 74 75
    char *filename;
    char *p;

76
    devCopy = g_strdup(dev);
77 78

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

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

91
    path = g_strdup_printf("%s/LCK..%s", VIR_CHRDEV_LOCK_FILE_PATH, filename);
92 93 94

    sanitizedPath = virFileSanitizePath(path);

95
    return g_steal_pointer(&sanitizedPath);
96 97 98
}

/**
99
 * Verify and create a lock file for a character device
100
 *
101
 * @dev Path of the character device
102 103 104
 *
 * Returns 0 on success, -1 on error
 */
105
static int virChrdevLockFileCreate(const char *dev)
106
{
107
    g_autofree char *path = NULL;
108
    int ret = -1;
109 110
    g_autofree char *pidStr = NULL;
    VIR_AUTOCLOSE lockfd = -1;
111 112 113
    pid_t pid;

    /* build lock file path */
114
    if (!(path = virChrdevLockFilePath(dev)))
115 116 117 118 119
        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 */
120
        virReportError(VIR_ERR_OPERATION_FAILED,
121
                       _("Requested device '%s' is locked by "
122
                         "lock file '%s' held by process %lld"),
123
                       dev, path, (long long) pid);
124 125 126 127 128 129 130 131 132
        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 */
133
    pidStr = g_strdup_printf("%10lld\n", (long long)getpid());
134 135 136 137 138 139 140 141 142

    /* 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) {
143 144
            VIR_DEBUG("Skipping lock file creation for device '%s in path '%s'.",
                      dev, path);
145 146 147 148 149
            ret = 0;
            goto cleanup;
        }
        virReportSystemError(errno,
                             _("Couldn't create lock file for "
150 151
                               "device '%s' in path '%s'"),
                             dev, path);
152 153 154 155 156 157 158
        goto cleanup;
    }

    /* write the pid to the file */
    if (safewrite(lockfd, pidStr, strlen(pidStr)) < 0) {
        virReportSystemError(errno,
                             _("Couldn't write to lock file for "
159 160
                               "device '%s' in path '%s'"),
                             dev, path);
161 162 163 164 165 166 167
        unlink(path);
        goto cleanup;
    }

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

168
 cleanup:
169 170 171 172 173

    return ret;
}

/**
174
 * Remove a lock file for a device
175
 *
176
 * @dev Path of the device
177
 */
178
static void virChrdevLockFileRemove(const char *dev)
179
{
180 181
    g_autofree char *path = virChrdevLockFilePath(dev);
    unlink(path);
182
}
183 184
#else /* #ifdef VIR_CHRDEV_LOCK_FILE_PATH */
/* file locking for character devices is disabled */
J
Ján Tomko 已提交
185
static int virChrdevLockFileCreate(const char *dev G_GNUC_UNUSED)
186 187 188 189
{
    return 0;
}

J
Ján Tomko 已提交
190
static void virChrdevLockFileRemove(const char *dev G_GNUC_UNUSED)
191 192 193
{
    return;
}
194
#endif /* #ifdef VIR_CHRDEV_LOCK_FILE_PATH */
195

196 197 198 199 200
typedef struct {
    char *dev;
    virStreamPtr st;
} virChrdevHashEntry;

201
/**
202
 * Frees an entry from the hash containing domain's active devices
203
 *
204
 * @data Opaque data, struct holding information about the device
205
 */
206
static void virChrdevHashEntryFree(void *data)
207
{
208 209 210 211
    virChrdevHashEntry *ent = data;

    if (!ent)
        return;
212 213

    /* free stream reference */
214
    virObjectUnref(ent->st);
215 216

    /* delete lock file */
217 218
    virChrdevLockFileRemove(ent->dev);

219
    g_free(ent->dev);
220
    g_free(ent);
221 222 223 224 225 226 227
}

/**
 * Frees opaque data provided for the stream closing callback
 *
 * @opaque Data to be freed.
 */
228
static void virChrdevFDStreamCloseCbFree(void *opaque)
229
{
230
    virChrdevStreamInfoPtr priv = opaque;
231

232
    VIR_FREE(priv->path);
233 234 235 236
    VIR_FREE(priv);
}

/**
237
 * Callback being called if a FDstream is closed. Frees device entries
238 239 240
 * from data structures and removes lockfiles.
 *
 * @st Pointer to stream being closed.
241
 * @opaque Domain's device information structure.
242
 */
J
Ján Tomko 已提交
243
static void virChrdevFDStreamCloseCb(virStreamPtr st G_GNUC_UNUSED,
244 245
                                      void *opaque)
{
246 247
    virChrdevStreamInfoPtr priv = opaque;
    virMutexLock(&priv->devs->lock);
248 249

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

252
    virMutexUnlock(&priv->devs->lock);
253 254 255
}

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

267
    if (virMutexInit(&devs->lock) < 0) {
268 269
        virReportSystemError(errno, "%s",
                             _("Unable to init device stream mutex"));
270
        VIR_FREE(devs);
271 272 273
        return NULL;
    }

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

279
    return devs;
280
 error:
281
    virChrdevFree(devs);
282 283 284
    return NULL;
}

285 286 287
/**
 * Helper to clear stream callbacks when freeing the hash
 */
288
static int virChrdevFreeClearCallbacks(void *payload,
J
Ján Tomko 已提交
289 290
                                       const void *name G_GNUC_UNUSED,
                                       void *data G_GNUC_UNUSED)
291
{
292
    virChrdevHashEntry *ent = payload;
293

294
    virFDStreamSetInternalCloseCb(ent->st, NULL, NULL, NULL);
295
    return 0;
296 297
}

298
/**
299
 * Free structures for handling open device streams.
300
 *
301
 * @devs Pointer to the private structure.
302
 */
303
void virChrdevFree(virChrdevsPtr devs)
304
{
305
    if (!devs)
306 307
        return;

308 309 310 311 312
    virMutexLock(&devs->lock);
    virHashForEach(devs->hash, virChrdevFreeClearCallbacks, NULL);
    virHashFree(devs->hash);
    virMutexUnlock(&devs->lock);
    virMutexDestroy(&devs->lock);
313

314
    VIR_FREE(devs);
315 316 317
}

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

344 345 346
    switch (source->type) {
    case VIR_DOMAIN_CHR_TYPE_PTY:
        path = source->data.file.path;
347 348 349 350 351
        if (!path) {
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("PTY device is not yet assigned"));
            return -1;
        }
352 353 354 355 356 357 358 359 360 361 362
        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 ((ent = 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(ent->st, NULL, NULL, NULL);
           virStreamAbort(ent->st);
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 401 402 403 404 405 406
    if (VIR_ALLOC(ent) < 0)
        goto error;

    ent->st = st;
    ent->dev = g_strdup(path);

    if (virHashAddEntry(devs->hash, path, ent) < 0)
407
        goto error;
408
    ent = NULL;
409
    added = true;
410

411
    cbdata->devs = devs;
412
    cbdata->path = g_strdup(path);
413

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

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

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

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

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