virchrdev.c 12.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
 */

#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
    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 95

    sanitizedPath = virFileSanitizePath(path);

    VIR_FREE(path);
96
    VIR_FREE(devCopy);
97 98 99 100 101

    return sanitizedPath;
}

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

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

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

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

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

172
 cleanup:
173 174 175 176 177 178 179 180
    VIR_FORCE_CLOSE(lockfd);
    VIR_FREE(path);
    VIR_FREE(pidStr);

    return ret;
}

/**
181
 * Remove a lock file for a device
182
 *
183
 * @dev Path of the device
184
 */
185
static void virChrdevLockFileRemove(const char *dev)
186
{
187
    char *path = virChrdevLockFilePath(dev);
188 189 190 191
    if (path)
        unlink(path);
    VIR_FREE(path);
}
192 193
#else /* #ifdef VIR_CHRDEV_LOCK_FILE_PATH */
/* file locking for character devices is disabled */
J
Ján Tomko 已提交
194
static int virChrdevLockFileCreate(const char *dev G_GNUC_UNUSED)
195 196 197 198
{
    return 0;
}

J
Ján Tomko 已提交
199
static void virChrdevLockFileRemove(const char *dev G_GNUC_UNUSED)
200 201 202
{
    return;
}
203
#endif /* #ifdef VIR_CHRDEV_LOCK_FILE_PATH */
204 205

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

    /* free stream reference */
218
    virObjectUnref(st);
219 220

    /* delete lock file */
221
    virChrdevLockFileRemove(dev);
222 223 224 225 226 227 228
}

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

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

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

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

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

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

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

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

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

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

    virFDStreamSetInternalCloseCb(st, NULL, NULL, NULL);
296
    return 0;
297 298
}

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

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

315
    VIR_FREE(devs);
316 317 318
}

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

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

364
    virMutexLock(&devs->lock);
365

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

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

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

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

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

405
    cbdata->devs = devs;
406
    cbdata->path = g_strdup(path);
407

408
    /* open the character device */
409 410
    switch (source->type) {
    case VIR_DOMAIN_CHR_TYPE_PTY:
R
Roman Bogorodskiy 已提交
411
        if (virFDStreamOpenPTY(st, path, 0, 0, O_RDWR) < 0)
412 413 414 415 416 417 418 419 420 421
            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
    return 0;

434
 error:
435 436 437
    if (added)
        virHashRemoveEntry(devs->hash, path);
    else
438
        virObjectUnref(st);
439

440
    if (cbdata)
441
        VIR_FREE(cbdata->path);
442
    VIR_FREE(cbdata);
443
    virMutexUnlock(&devs->lock);
444 445
    return -1;
}