storage_backend.c 62.4 KB
Newer Older
1
/*
2
 * storage_backend.c: internal storage driver backend contract
3
 *
4
 * Copyright (C) 2007-2014 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17
 * Copyright (C) 2007-2008 Daniel P. Berrange
 *
 * 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
 *
 * Author: Daniel P. Berrange <berrange@redhat.com>
 */

#include <config.h>

#include <string.h>
27
#include <stdio.h>
28
#include <regex.h>
29
#include <sys/types.h>
E
Eric Blake 已提交
30
#include <sys/wait.h>
31
#include <unistd.h>
32 33
#include <fcntl.h>
#include <sys/stat.h>
34
#include <sys/param.h>
35
#include <dirent.h>
36
#include "dirname.h"
37 38 39
#ifdef __linux__
# include <sys/ioctl.h>
# include <linux/fs.h>
C
Chunyan Liu 已提交
40 41 42
# ifndef FS_NOCOW_FL
#  define FS_NOCOW_FL                     0x00800000 /* Do not cow file */
# endif
43
#endif
44

45
#if WITH_SELINUX
46
# include <selinux/selinux.h>
47
#endif
48

49 50 51 52
#if HAVE_LINUX_BTRFS_H
# include <linux/btrfs.h>
#endif

53
#include "datatypes.h"
54
#include "virerror.h"
55
#include "viralloc.h"
56
#include "internal.h"
57
#include "secret_conf.h"
58
#include "viruuid.h"
59
#include "virstoragefile.h"
D
Daniel P. Berrange 已提交
60
#include "storage_backend.h"
61
#include "virlog.h"
E
Eric Blake 已提交
62
#include "virfile.h"
63
#include "stat-time.h"
64
#include "virstring.h"
65
#include "virxml.h"
66
#include "fdstream.h"
67

68
#if WITH_STORAGE_LVM
69
# include "storage_backend_logical.h"
70 71
#endif
#if WITH_STORAGE_ISCSI
72
# include "storage_backend_iscsi.h"
73
#endif
74
#if WITH_STORAGE_SCSI
75
# include "storage_backend_scsi.h"
76
#endif
D
Dave Allan 已提交
77
#if WITH_STORAGE_MPATH
78
# include "storage_backend_mpath.h"
D
Dave Allan 已提交
79
#endif
80
#if WITH_STORAGE_DISK
81
# include "storage_backend_disk.h"
82 83
#endif
#if WITH_STORAGE_DIR
84
# include "storage_backend_fs.h"
85
#endif
86 87 88
#if WITH_STORAGE_RBD
# include "storage_backend_rbd.h"
#endif
89 90 91
#if WITH_STORAGE_SHEEPDOG
# include "storage_backend_sheepdog.h"
#endif
92 93 94
#if WITH_STORAGE_GLUSTER
# include "storage_backend_gluster.h"
#endif
R
Roman Bogorodskiy 已提交
95 96 97
#if WITH_STORAGE_ZFS
# include "storage_backend_zfs.h"
#endif
98

99 100
#define VIR_FROM_THIS VIR_FROM_STORAGE

101 102
VIR_LOG_INIT("storage.storage_backend");

103 104 105 106 107 108 109 110 111 112 113 114 115 116
static virStorageBackendPtr backends[] = {
#if WITH_STORAGE_DIR
    &virStorageBackendDirectory,
#endif
#if WITH_STORAGE_FS
    &virStorageBackendFileSystem,
    &virStorageBackendNetFileSystem,
#endif
#if WITH_STORAGE_LVM
    &virStorageBackendLogical,
#endif
#if WITH_STORAGE_ISCSI
    &virStorageBackendISCSI,
#endif
117 118 119
#if WITH_STORAGE_SCSI
    &virStorageBackendSCSI,
#endif
D
Dave Allan 已提交
120 121 122
#if WITH_STORAGE_MPATH
    &virStorageBackendMpath,
#endif
123 124
#if WITH_STORAGE_DISK
    &virStorageBackendDisk,
125 126 127
#endif
#if WITH_STORAGE_RBD
    &virStorageBackendRBD,
128 129 130
#endif
#if WITH_STORAGE_SHEEPDOG
    &virStorageBackendSheepdog,
131 132 133
#endif
#if WITH_STORAGE_GLUSTER
    &virStorageBackendGluster,
R
Roman Bogorodskiy 已提交
134 135 136
#endif
#if WITH_STORAGE_ZFS
    &virStorageBackendZFS,
137 138 139
#endif
    NULL
};
140

141 142

static virStorageFileBackendPtr fileBackends[] = {
143 144 145
#if WITH_STORAGE_FS
    &virStorageFileBackendFile,
    &virStorageFileBackendBlock,
146 147 148
#endif
#if WITH_STORAGE_GLUSTER
    &virStorageFileBackendGluster,
149
#endif
150 151 152 153
    NULL
};


154 155 156 157 158 159
enum {
    TOOL_QEMU_IMG,
    TOOL_KVM_IMG,
    TOOL_QCOW_CREATE,
};

160 161 162
#define READ_BLOCK_SIZE_DEFAULT  (1024 * 1024)
#define WRITE_BLOCK_SIZE_DEFAULT (4 * 1024)

163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
/*
 * Perform the O(1) btrfs clone operation, if possible.
 * Upon success, return 0.  Otherwise, return -1 and set errno.
 */
#if HAVE_LINUX_BTRFS_H
static inline int
btrfsCloneFile(int dest_fd, int src_fd)
{
    return ioctl(dest_fd, BTRFS_IOC_CLONE, src_fd);
}
#else
static inline int
btrfsCloneFile(int dest_fd ATTRIBUTE_UNUSED,
               int src_fd ATTRIBUTE_UNUSED)
{
    errno = ENOTSUP;
    return -1;
}
#endif

183
static int ATTRIBUTE_NONNULL(2)
184
virStorageBackendCopyToFD(virStorageVolDefPtr vol,
185 186
                          virStorageVolDefPtr inputvol,
                          int fd,
187
                          unsigned long long *total,
J
Ján Tomko 已提交
188
                          bool want_sparse)
189 190 191
{
    int inputfd = -1;
    int amtread = -1;
192
    int ret = 0;
193
    size_t rbytes = READ_BLOCK_SIZE_DEFAULT;
L
Li Zhang 已提交
194
    int wbytes = 0;
195
    int interval;
196
    char *zerobuf = NULL;
197
    char *buf = NULL;
198
    struct stat st;
199

200
    if ((inputfd = open(inputvol->target.path, O_RDONLY)) < 0) {
201
        ret = -errno;
202
        virReportSystemError(errno,
203 204 205
                             _("could not open input path '%s'"),
                             inputvol->target.path);
        goto cleanup;
206 207
    }

208
#ifdef __linux__
209
    if (ioctl(fd, BLKBSZGET, &wbytes) < 0)
210 211 212 213 214 215 216 217 218 219 220
        wbytes = 0;
#endif
    if ((wbytes == 0) && fstat(fd, &st) == 0)
        wbytes = st.st_blksize;
    if (wbytes < WRITE_BLOCK_SIZE_DEFAULT)
        wbytes = WRITE_BLOCK_SIZE_DEFAULT;

    if (VIR_ALLOC_N(zerobuf, wbytes) < 0) {
        ret = -errno;
        goto cleanup;
    }
221

222
    if (VIR_ALLOC_N(buf, rbytes) < 0) {
223
        ret = -errno;
224 225 226 227 228 229
        goto cleanup;
    }

    while (amtread != 0) {
        int amtleft;

230 231
        if (*total < rbytes)
            rbytes = *total;
232

233
        if ((amtread = saferead(inputfd, buf, rbytes)) < 0) {
234
            ret = -errno;
235
            virReportSystemError(errno,
236 237 238 239
                                 _("failed reading from file '%s'"),
                                 inputvol->target.path);
            goto cleanup;
        }
240
        *total -= amtread;
241 242 243 244 245

        /* Loop over amt read in 512 byte increments, looking for sparse
         * blocks */
        amtleft = amtread;
        do {
246
            interval = ((wbytes > amtleft) ? amtleft : wbytes);
247 248
            int offset = amtread - amtleft;

249
            if (want_sparse && memcmp(buf+offset, zerobuf, interval) == 0) {
250
                if (lseek(fd, interval, SEEK_CUR) < 0) {
251
                    ret = -errno;
252
                    virReportSystemError(errno,
253 254 255 256 257
                                         _("cannot extend file '%s'"),
                                         vol->target.path);
                    goto cleanup;
                }
            } else if (safewrite(fd, buf+offset, interval) < 0) {
258
                ret = -errno;
259
                virReportSystemError(errno,
260 261 262 263 264
                                     _("failed writing to file '%s'"),
                                     vol->target.path);
                goto cleanup;

            }
265
        } while ((amtleft -= interval) > 0);
266 267
    }

268 269 270 271 272 273 274 275
    if (fdatasync(fd) < 0) {
        ret = -errno;
        virReportSystemError(errno, _("cannot sync data to file '%s'"),
                             vol->target.path);
        goto cleanup;
    }


276
    if (VIR_CLOSE(inputfd) < 0) {
277
        ret = -errno;
278
        virReportSystemError(errno,
279 280 281 282 283 284
                             _("cannot close file '%s'"),
                             inputvol->target.path);
        goto cleanup;
    }
    inputfd = -1;

285
 cleanup:
286
    VIR_FORCE_CLOSE(inputfd);
287

288
    VIR_FREE(zerobuf);
289 290
    VIR_FREE(buf);

291 292 293
    return ret;
}

294
static int
295
virStorageBackendCreateBlockFrom(virConnectPtr conn ATTRIBUTE_UNUSED,
296
                                 virStoragePoolObjPtr pool ATTRIBUTE_UNUSED,
297 298
                                 virStorageVolDefPtr vol,
                                 virStorageVolDefPtr inputvol,
E
Eric Blake 已提交
299
                                 unsigned int flags)
300 301 302 303
{
    int fd = -1;
    int ret = -1;
    unsigned long long remain;
304 305 306
    struct stat st;
    gid_t gid;
    uid_t uid;
307

308 309 310 311 312 313 314 315
    virCheckFlags(VIR_STORAGE_VOL_CREATE_PREALLOC_METADATA, -1);

    if (flags & VIR_STORAGE_VOL_CREATE_PREALLOC_METADATA) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("metadata preallocation is not supported for block "
                         "volumes"));
        goto cleanup;
    }
E
Eric Blake 已提交
316

317
    if ((fd = open(vol->target.path, O_RDWR)) < 0) {
318
        virReportSystemError(errno,
319 320 321 322 323
                             _("cannot create path '%s'"),
                             vol->target.path);
        goto cleanup;
    }

324
    remain = vol->target.allocation;
325 326

    if (inputvol) {
327
        int res = virStorageBackendCopyToFD(vol, inputvol,
J
Ján Tomko 已提交
328
                                            fd, &remain, false);
329 330 331 332
        if (res < 0)
            goto cleanup;
    }

333
    if (fstat(fd, &st) == -1) {
334
        virReportSystemError(errno, _("stat of '%s' failed"),
335 336 337
                             vol->target.path);
        goto cleanup;
    }
338 339 340 341
    uid = (vol->target.perms->uid != st.st_uid) ? vol->target.perms->uid
        : (uid_t) -1;
    gid = (vol->target.perms->gid != st.st_gid) ? vol->target.perms->gid
        : (gid_t) -1;
P
Philipp Hahn 已提交
342
    if (((uid != (uid_t) -1) || (gid != (gid_t) -1))
343
        && (fchown(fd, uid, gid) < 0)) {
344
        virReportSystemError(errno,
345
                             _("cannot chown '%s' to (%u, %u)"),
346 347
                             vol->target.path, (unsigned int) uid,
                             (unsigned int) gid);
348 349
        goto cleanup;
    }
350
    if (fchmod(fd, vol->target.perms->mode) < 0) {
351
        virReportSystemError(errno,
352
                             _("cannot set mode of '%s' to %04o"),
353
                             vol->target.path, vol->target.perms->mode);
354 355
        goto cleanup;
    }
356
    if (VIR_CLOSE(fd) < 0) {
357
        virReportSystemError(errno,
358 359 360 361 362 363 364
                             _("cannot close file '%s'"),
                             vol->target.path);
        goto cleanup;
    }
    fd = -1;

    ret = 0;
365
 cleanup:
366
    VIR_FORCE_CLOSE(fd);
367 368 369 370

    return ret;
}

E
Eric Blake 已提交
371 372 373 374
static int
createRawFile(int fd, virStorageVolDefPtr vol,
              virStorageVolDefPtr inputvol)
{
J
Ján Tomko 已提交
375
    bool need_alloc = true;
376 377
    int ret = 0;
    unsigned long long remain;
378

379 380
    /* Seek to the final size, so the capacity is available upfront
     * for progress reporting */
381
    if (ftruncate(fd, vol->target.capacity) < 0) {
382
        ret = -errno;
383
        virReportSystemError(errno,
384
                             _("cannot extend file '%s'"),
E
Eric Blake 已提交
385
                             vol->target.path);
386 387 388
        goto cleanup;
    }

E
Eric Blake 已提交
389 390
/* Avoid issues with older kernel's <linux/fs.h> namespace pollution. */
#if HAVE_FALLOCATE - 0
391
    /* Try to preallocate all requested disk space, but fall back to
392 393
     * other methods if this fails with ENOSYS or EOPNOTSUPP. If allocation
     * is 0 (or less than 0), then fallocate will fail with EINVAL.
394 395 396 397
     * NOTE: do not use posix_fallocate; posix_fallocate falls back
     * to writing zeroes block by block in case fallocate isn't
     * available, and since we're going to copy data from another
     * file it doesn't make sense to write the file twice. */
398 399
    if (vol->target.allocation) {
        if (fallocate(fd, 0, 0, vol->target.allocation) == 0) {
400 401 402 403 404
            need_alloc = false;
        } else if (errno != ENOSYS && errno != EOPNOTSUPP) {
            ret = -errno;
            virReportSystemError(errno,
                                 _("cannot allocate %llu bytes in file '%s'"),
405
                                 vol->target.allocation, vol->target.path);
406 407
            goto cleanup;
        }
408 409 410
    }
#endif

411
    remain = vol->target.allocation;
412

E
Eric Blake 已提交
413
    if (inputvol) {
414 415 416
        /* allow zero blocks to be skipped if we've requested sparse
         * allocation (allocation < capacity) or we have already
         * been able to allocate the required space. */
J
Ján Tomko 已提交
417
        bool want_sparse = !need_alloc ||
418
            (vol->target.allocation < inputvol->target.capacity);
419 420

        ret = virStorageBackendCopyToFD(vol, inputvol, fd, &remain, want_sparse);
421
        if (ret < 0)
422 423 424
            goto cleanup;
    }

425
    if (remain && need_alloc) {
426
        if (safezero(fd, vol->target.allocation - remain, remain) < 0) {
427 428 429 430
            ret = -errno;
            virReportSystemError(errno, _("cannot fill file '%s'"),
                                 vol->target.path);
            goto cleanup;
431
        }
432 433 434
    }

    if (fsync(fd) < 0) {
435
        ret = -errno;
436
        virReportSystemError(errno, _("cannot sync data to file '%s'"),
E
Eric Blake 已提交
437
                             vol->target.path);
438
        goto cleanup;
439 440
    }

441
 cleanup:
442 443 444 445 446 447 448 449
    return ret;
}

int
virStorageBackendCreateRaw(virConnectPtr conn ATTRIBUTE_UNUSED,
                           virStoragePoolObjPtr pool,
                           virStorageVolDefPtr vol,
                           virStorageVolDefPtr inputvol,
E
Eric Blake 已提交
450
                           unsigned int flags)
451 452
{
    int ret = -1;
E
Eric Blake 已提交
453 454 455
    int fd = -1;
    int operation_flags;

456 457 458 459 460 461 462 463
    virCheckFlags(VIR_STORAGE_VOL_CREATE_PREALLOC_METADATA, -1);

    if (flags & VIR_STORAGE_VOL_CREATE_PREALLOC_METADATA) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("metadata preallocation is not supported for raw "
                         "volumes"));
        goto cleanup;
    }
464 465

    if (vol->target.encryption != NULL) {
466 467
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("storage pool does not support encrypted volumes"));
468 469
        goto cleanup;
    }
470

L
Laine Stump 已提交
471
    operation_flags = VIR_FILE_OPEN_FORCE_MODE | VIR_FILE_OPEN_FORCE_OWNER;
E
Eric Blake 已提交
472
    if (pool->def->type == VIR_STORAGE_POOL_NETFS)
L
Laine Stump 已提交
473
        operation_flags |= VIR_FILE_OPEN_FORK;
E
Eric Blake 已提交
474

475 476
    if ((fd = virFileOpenAs(vol->target.path,
                            O_RDWR | O_CREAT | O_EXCL,
477 478 479
                            vol->target.perms->mode,
                            vol->target.perms->uid,
                            vol->target.perms->gid,
480
                            operation_flags)) < 0) {
E
Eric Blake 已提交
481
        virReportSystemError(-fd,
482
                             _("Failed to create file '%s'"),
E
Eric Blake 已提交
483 484 485 486
                             vol->target.path);
        goto cleanup;
    }

C
Chunyan Liu 已提交
487 488 489 490 491 492
    if (vol->target.nocow) {
#ifdef __linux__
        int attr;

        /* Set NOCOW flag. This is an optimisation for btrfs.
         * The FS_IOC_SETFLAGS ioctl return value will be ignored since any
493
         * failure of this operation should not block the volume creation.
C
Chunyan Liu 已提交
494
         */
495 496 497
        if (ioctl(fd, FS_IOC_GETFLAGS, &attr) < 0) {
            virReportSystemError(errno, "%s", _("Failed to get fs flags"));
        } else {
C
Chunyan Liu 已提交
498
            attr |= FS_NOCOW_FL;
499 500 501 502
            if (ioctl(fd, FS_IOC_SETFLAGS, &attr) < 0) {
                virReportSystemError(errno, "%s",
                                     _("Failed to set NOCOW flag"));
            }
C
Chunyan Liu 已提交
503 504 505 506
        }
#endif
    }

507 508
    if ((ret = createRawFile(fd, vol, inputvol)) < 0)
        /* createRawFile already reported the exact error. */
E
Eric Blake 已提交
509
        ret = -1;
510

511
 cleanup:
E
Eric Blake 已提交
512
    VIR_FORCE_CLOSE(fd);
513 514 515
    return ret;
}

516 517 518 519 520 521 522 523 524
static int
virStorageGenerateSecretUUID(virConnectPtr conn,
                             unsigned char *uuid)
{
    unsigned attempt;

    for (attempt = 0; attempt < 65536; attempt++) {
        virSecretPtr tmp;
        if (virUUIDGenerate(uuid) < 0) {
525 526
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("unable to generate uuid"));
527 528
            return -1;
        }
529
        tmp = conn->secretDriver->secretLookupByUUID(conn, uuid);
530 531 532
        if (tmp == NULL)
            return 0;

533
        virObjectUnref(tmp);
534 535
    }

536
    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
N
Nehal J Wani 已提交
537
                   _("too many conflicts when generating a uuid"));
538 539 540 541

    return -1;
}

542 543 544 545 546 547 548 549 550
static int
virStorageGenerateQcowEncryption(virConnectPtr conn,
                                 virStorageVolDefPtr vol)
{
    virSecretDefPtr def = NULL;
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    virStorageEncryptionPtr enc;
    virStorageEncryptionSecretPtr enc_secret = NULL;
    virSecretPtr secret = NULL;
551
    char *xml;
552 553 554
    unsigned char value[VIR_STORAGE_QCOW_PASSPHRASE_SIZE];
    int ret = -1;

555
    if (conn->secretDriver == NULL ||
556 557 558
        conn->secretDriver->secretLookupByUUID == NULL ||
        conn->secretDriver->secretDefineXML == NULL ||
        conn->secretDriver->secretSetValue == NULL) {
559 560
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("secret storage not supported"));
561 562 563 564 565
        goto cleanup;
    }

    enc = vol->target.encryption;
    if (enc->nsecrets != 0) {
566 567
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("secrets already defined"));
568 569 570 571
        goto cleanup;
    }

    if (VIR_ALLOC(enc_secret) < 0 || VIR_REALLOC_N(enc->secrets, 1) < 0 ||
572
        VIR_ALLOC(def) < 0)
573 574
        goto cleanup;

575
    def->ephemeral = false;
576
    def->private = false;
577
    if (virStorageGenerateSecretUUID(conn, def->uuid) < 0)
578
        goto cleanup;
579

580
    def->usage_type = VIR_SECRET_USAGE_TYPE_VOLUME;
581
    if (VIR_STRDUP(def->usage.volume, vol->target.path) < 0)
582
        goto cleanup;
583
    xml = virSecretDefFormat(def);
584 585 586 587 588
    virSecretDefFree(def);
    def = NULL;
    if (xml == NULL)
        goto cleanup;

589
    secret = conn->secretDriver->secretDefineXML(conn, xml, 0);
590 591 592 593 594 595
    if (secret == NULL) {
        VIR_FREE(xml);
        goto cleanup;
    }
    VIR_FREE(xml);

596
    if (virStorageGenerateQcowPassphrase(value) < 0)
597 598
        goto cleanup;

599
    if (conn->secretDriver->secretSetValue(secret, value, sizeof(value), 0) < 0)
600 601 602
        goto cleanup;

    enc_secret->type = VIR_STORAGE_ENCRYPTION_SECRET_TYPE_PASSPHRASE;
603
    memcpy(enc_secret->uuid, secret->uuid, VIR_UUID_BUFLEN);
604 605 606 607 608 609 610
    enc->format = VIR_STORAGE_ENCRYPTION_FORMAT_QCOW;
    enc->secrets[0] = enc_secret; /* Space for secrets[0] allocated above */
    enc_secret = NULL;
    enc->nsecrets = 1;

    ret = 0;

611
 cleanup:
612
    if (secret != NULL) {
613
        if (ret != 0 &&
614 615
            conn->secretDriver->secretUndefine != NULL)
            conn->secretDriver->secretUndefine(secret);
616
        virObjectUnref(secret);
617
    }
618
    virBufferFreeAndReset(&buf);
619 620 621 622 623
    virSecretDefFree(def);
    VIR_FREE(enc_secret);
    return ret;
}

624 625 626 627 628
static int
virStorageBackendCreateExecCommand(virStoragePoolObjPtr pool,
                                   virStorageVolDefPtr vol,
                                   virCommandPtr cmd)
{
629 630 631
    struct stat st;
    gid_t gid;
    uid_t uid;
632
    bool filecreated = false;
633 634

    if ((pool->def->type == VIR_STORAGE_POOL_NETFS)
635
        && (((geteuid() == 0)
636 637 638 639
             && (vol->target.perms->uid != (uid_t) -1)
             && (vol->target.perms->uid != 0))
            || ((vol->target.perms->gid != (gid_t) -1)
                && (vol->target.perms->gid != getegid())))) {
640

641 642
        virCommandSetUID(cmd, vol->target.perms->uid);
        virCommandSetGID(cmd, vol->target.perms->gid);
643 644

        if (virCommandRun(cmd, NULL) == 0) {
645
            /* command was successfully run, check if the file was created */
646
            if (stat(vol->target.path, &st) >= 0)
647
                filecreated = true;
648 649
        }
    }
650

651 652 653
    /* don't change uid/gid if we retry */
    virCommandSetUID(cmd, -1);
    virCommandSetGID(cmd, -1);
654

655
    if (!filecreated) {
656
        if (virCommandRun(cmd, NULL) < 0)
657 658
            return -1;
        if (stat(vol->target.path, &st) < 0) {
659
            virReportSystemError(errno,
660
                                 _("failed to create %s"), vol->target.path);
661 662 663 664
            return -1;
        }
    }

665 666 667 668
    uid = (vol->target.perms->uid != st.st_uid) ? vol->target.perms->uid
        : (uid_t) -1;
    gid = (vol->target.perms->gid != st.st_gid) ? vol->target.perms->gid
        : (gid_t) -1;
P
Philipp Hahn 已提交
669
    if (((uid != (uid_t) -1) || (gid != (gid_t) -1))
670
        && (chown(vol->target.path, uid, gid) < 0)) {
671
        virReportSystemError(errno,
672
                             _("cannot chown %s to (%u, %u)"),
673 674
                             vol->target.path, (unsigned int) uid,
                             (unsigned int) gid);
675 676
        return -1;
    }
677
    if (chmod(vol->target.path, vol->target.perms->mode) < 0) {
678
        virReportSystemError(errno,
679
                             _("cannot set mode of '%s' to %04o"),
680
                             vol->target.path, vol->target.perms->mode);
681 682 683 684 685
        return -1;
    }
    return 0;
}

686 687 688 689
enum {
    QEMU_IMG_BACKING_FORMAT_NONE = 0,
    QEMU_IMG_BACKING_FORMAT_FLAG,
    QEMU_IMG_BACKING_FORMAT_OPTIONS,
690
    QEMU_IMG_BACKING_FORMAT_OPTIONS_COMPAT,
691 692
};

693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
static bool
virStorageBackendQemuImgSupportsCompat(const char *qemuimg)
{
    bool ret = false;
    char *output;
    virCommandPtr cmd = NULL;

    cmd = virCommandNewArgList(qemuimg, "create", "-o", "?", "-f", "qcow2",
                               "/dev/null", NULL);

    virCommandAddEnvString(cmd, "LC_ALL=C");
    virCommandSetOutputBuffer(cmd, &output);

    if (virCommandRun(cmd, NULL) < 0)
        goto cleanup;

    if (strstr(output, "\ncompat "))
        ret = true;

712
 cleanup:
713 714 715 716 717
    virCommandFree(cmd);
    VIR_FREE(output);
    return ret;
}

718 719
static int
virStorageBackendQEMUImgBackingFormat(const char *qemuimg)
720 721 722 723 724 725
{
    char *help = NULL;
    char *start;
    char *end;
    char *tmp;
    int ret = -1;
726
    int exitstatus;
727
    virCommandPtr cmd = virCommandNewArgList(qemuimg, "-h", NULL);
728

729 730 731
    virCommandAddEnvString(cmd, "LC_ALL=C");
    virCommandSetOutputBuffer(cmd, &help);
    virCommandClearCaps(cmd);
732

733 734 735
    /* qemuimg doesn't return zero exit status on -h,
     * therefore we need to provide pointer for storing
     * exit status, although we don't parse it any later */
736
    if (virCommandRun(cmd, &exitstatus) < 0)
737 738
        goto cleanup;

739 740
    if ((start = strstr(help, " create ")) == NULL ||
        (end = strstr(start, "\n")) == NULL) {
741 742 743
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unable to parse qemu-img output '%s'"),
                       help);
744 745
        goto cleanup;
    }
746
    if (((tmp = strstr(start, "-F fmt")) && tmp < end) ||
747
        ((tmp = strstr(start, "-F backing_fmt")) && tmp < end)) {
748
        ret = QEMU_IMG_BACKING_FORMAT_FLAG;
749 750 751 752 753 754
    } else if ((tmp = strstr(start, "[-o options]")) && tmp < end) {
        if (virStorageBackendQemuImgSupportsCompat(qemuimg))
            ret = QEMU_IMG_BACKING_FORMAT_OPTIONS_COMPAT;
        else
            ret = QEMU_IMG_BACKING_FORMAT_OPTIONS;
    } else {
755
        ret = QEMU_IMG_BACKING_FORMAT_NONE;
756
    }
757

758
 cleanup:
759
    virCommandFree(cmd);
760 761 762 763
    VIR_FREE(help);
    return ret;
}

764 765 766 767
static int
virStorageBackendCreateQemuImgOpts(char **opts,
                                   const char *backingType,
                                   bool encryption,
768 769 770
                                   bool preallocate,
                                   int format,
                                   const char *compat,
C
Chunyan Liu 已提交
771
                                   bool nocow,
772
                                   virBitmapPtr features)
773 774
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;
775
    bool b;
776
    size_t i;
777

778 779 780 781 782 783
    if (backingType)
        virBufferAsprintf(&buf, "backing_fmt=%s,", backingType);
    if (encryption)
        virBufferAddLit(&buf, "encryption=on,");
    if (preallocate)
        virBufferAddLit(&buf, "preallocation=metadata,");
C
Chunyan Liu 已提交
784 785
    if (nocow)
        virBufferAddLit(&buf, "nocow=on,");
786

787 788 789 790 791 792
    if (compat)
        virBufferAsprintf(&buf, "compat=%s,", compat);
    if (features && format == VIR_STORAGE_FILE_QCOW2) {
        for (i = 0; i < VIR_STORAGE_FILE_FEATURE_LAST; i++) {
            ignore_value(virBitmapGetBit(features, i, &b));
            if (b) {
793
                switch ((virStorageFileFeature) i) {
794 795 796 797 798 799 800 801 802 803
                case VIR_STORAGE_FILE_FEATURE_LAZY_REFCOUNTS:
                    if (STREQ_NULLABLE(compat, "0.10")) {
                        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                       _("Feature %s not supported with compat"
                                         " level %s"),
                                       virStorageFileFeatureTypeToString(i),
                                       compat);
                        goto error;
                    }
                    break;
804

805
                /* coverity[dead_error_begin] */
806 807 808 809 810 811 812 813 814
                case VIR_STORAGE_FILE_FEATURE_LAST:
                    ;
                }
                virBufferAsprintf(&buf, "%s,",
                                  virStorageFileFeatureTypeToString(i));
            }
        }
    }

815 816
    virBufferTrim(&buf, ",", -1);

817 818
    if (virBufferCheckError(&buf) < 0)
        goto error;
819 820 821

    *opts = virBufferContentAndReset(&buf);
    return 0;
822

823
 error:
824 825
    virBufferFreeAndReset(&buf);
    return -1;
826 827
}

828 829 830 831 832 833 834 835
virCommandPtr
virStorageBackendCreateQemuImgCmd(virConnectPtr conn,
                                  virStoragePoolObjPtr pool,
                                  virStorageVolDefPtr vol,
                                  virStorageVolDefPtr inputvol,
                                  unsigned int flags,
                                  const char *create_tool,
                                  int imgformat)
836
{
837 838
    virCommandPtr cmd = NULL;
    bool do_encryption = (vol->target.encryption != NULL);
839
    unsigned long long int size_arg;
840 841 842 843 844
    bool preallocate = !!(flags & VIR_STORAGE_VOL_CREATE_PREALLOC_METADATA);
    const char *type;
    const char *backingType = NULL;
    const char *inputPath = NULL;
    const char *inputType = NULL;
845
    const char *compat = vol->target.compat;
846 847 848
    char *opts = NULL;
    bool convert = false;
    bool backing = false;
849

850 851
    virCheckFlags(VIR_STORAGE_VOL_CREATE_PREALLOC_METADATA, NULL);

852 853 854 855
    /* Treat output block devices as 'raw' format */
    type = virStorageFileFormatTypeToString(vol->type == VIR_STORAGE_VOL_BLOCK ?
                                            VIR_STORAGE_FILE_RAW :
                                            vol->target.format);
856

857
    if (!type) {
858 859 860
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unknown storage vol type %d"),
                       vol->target.format);
861
        return NULL;
862
    }
863

864 865 866
    if (preallocate && vol->target.format != VIR_STORAGE_FILE_QCOW2) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("metadata preallocation only available with qcow2"));
867
        return NULL;
868
    }
869 870 871 872 873 874 875 876 877 878
    if (vol->target.compat && vol->target.format != VIR_STORAGE_FILE_QCOW2) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("compatibility option only available with qcow2"));
        return NULL;
    }
    if (vol->target.features && vol->target.format != VIR_STORAGE_FILE_QCOW2) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("format features only available with qcow2"));
        return NULL;
    }
879

880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899
    if (inputvol) {
        if (!(inputPath = inputvol->target.path)) {
            virReportError(VIR_ERR_INVALID_ARG, "%s",
                           _("missing input volume target path"));
            return NULL;
        }

        inputType = virStorageFileFormatTypeToString(inputvol->type == VIR_STORAGE_VOL_BLOCK ?
                                                     VIR_STORAGE_FILE_RAW :
                                                     inputvol->target.format);

        if (!inputType) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unknown storage vol type %d"),
                           inputvol->target.format);
            return NULL;
        }

    }

900
    if (vol->target.backingStore) {
901 902
        int accessRetCode = -1;
        char *absolutePath = NULL;
903

904
        backingType = virStorageFileFormatTypeToString(vol->target.backingStore->format);
905

906 907 908 909
        if (preallocate) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("metadata preallocation conflicts with backing"
                             " store"));
910
            return NULL;
911 912
        }

913 914 915 916
        /* XXX: Not strictly required: qemu-img has an option a different
         * backing store, not really sure what use it serves though, and it
         * may cause issues with lvm. Untested essentially.
         */
917
        if (inputvol && inputvol->target.backingStore &&
918 919
            STRNEQ_NULLABLE(inputvol->target.backingStore->path,
                            vol->target.backingStore->path)) {
920 921
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("a different backing store cannot be specified."));
922
            return NULL;
923 924 925
        }

        if (backingType == NULL) {
926 927
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unknown storage vol backing store type %d"),
928
                           vol->target.backingStore->format);
929
            return NULL;
930
        }
931 932 933 934

        /* Convert relative backing store paths to absolute paths for access
         * validation.
         */
935
        if ('/' != *(vol->target.backingStore->path) &&
936
            virAsprintf(&absolutePath, "%s/%s", pool->def->target.path,
937
                        vol->target.backingStore->path) < 0)
938
            return NULL;
939
        accessRetCode = access(absolutePath ? absolutePath
940
                               : vol->target.backingStore->path, R_OK);
941 942
        VIR_FREE(absolutePath);
        if (accessRetCode != 0) {
943
            virReportSystemError(errno,
944
                                 _("inaccessible backing store volume %s"),
945
                                 vol->target.backingStore->path);
946
            return NULL;
947 948 949
        }
    }

950
    if (do_encryption) {
951 952
        virStorageEncryptionPtr enc;

953 954
        if (vol->target.format != VIR_STORAGE_FILE_QCOW &&
            vol->target.format != VIR_STORAGE_FILE_QCOW2) {
955 956 957
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("qcow volume encryption unsupported with "
                             "volume format %s"), type);
958
            return NULL;
959
        }
960 961 962
        enc = vol->target.encryption;
        if (enc->format != VIR_STORAGE_ENCRYPTION_FORMAT_QCOW &&
            enc->format != VIR_STORAGE_ENCRYPTION_FORMAT_DEFAULT) {
963 964 965
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("unsupported volume encryption format %d"),
                           vol->target.encryption->format);
966
            return NULL;
967
        }
968
        if (enc->nsecrets > 1) {
969 970
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("too many secrets for qcow encryption"));
971
            return NULL;
972
        }
973 974 975
        if (enc->format == VIR_STORAGE_ENCRYPTION_FORMAT_DEFAULT ||
            enc->nsecrets == 0) {
            if (virStorageGenerateQcowEncryption(conn, vol) < 0)
976
                return NULL;
977
        }
978 979
    }

980
    /* Size in KB */
981
    size_arg = VIR_DIV_UP(vol->target.capacity, 1024);
982

983 984
    cmd = virCommandNew(create_tool);

985
    convert = !!inputvol;
986
    backing = !inputvol && vol->target.backingStore;
987

988 989 990
    if (convert)
        virCommandAddArgList(cmd, "convert", "-f", inputType, "-O", type, NULL);
    else
991
        virCommandAddArgList(cmd, "create", "-f", type, NULL);
992

993
    if (backing)
994
        virCommandAddArgList(cmd, "-b", vol->target.backingStore->path, NULL);
995

996 997 998 999 1000
    if (imgformat >= QEMU_IMG_BACKING_FORMAT_OPTIONS) {
        if (vol->target.format == VIR_STORAGE_FILE_QCOW2 && !compat &&
            imgformat == QEMU_IMG_BACKING_FORMAT_OPTIONS_COMPAT)
            compat = "0.10";

1001 1002
        if (virStorageBackendCreateQemuImgOpts(&opts,
                                               backing ? backingType : NULL,
1003 1004
                                               do_encryption, preallocate,
                                               vol->target.format,
1005
                                               compat,
C
Chunyan Liu 已提交
1006
                                               vol->target.nocow,
1007 1008
                                               vol->target.features) < 0) {
            virCommandFree(cmd);
1009
            return NULL;
1010
        }
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
        if (opts)
            virCommandAddArgList(cmd, "-o", opts, NULL);
        VIR_FREE(opts);
    } else {
        if (backing) {
            if (imgformat == QEMU_IMG_BACKING_FORMAT_FLAG)
                virCommandAddArgList(cmd, "-F", backingType, NULL);
            else
                VIR_DEBUG("Unable to set backing store format for %s with %s",
                          vol->target.path, create_tool);
1021
        }
1022 1023
        if (do_encryption)
            virCommandAddArg(cmd, "-e");
1024
    }
1025

1026 1027 1028 1029 1030 1031
    if (convert)
        virCommandAddArg(cmd, inputPath);
    virCommandAddArg(cmd, vol->target.path);
    if (!convert)
        virCommandAddArgFormat(cmd, "%lluK", size_arg);

1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
    return cmd;
}

static int
virStorageBackendCreateQemuImg(virConnectPtr conn,
                               virStoragePoolObjPtr pool,
                               virStorageVolDefPtr vol,
                               virStorageVolDefPtr inputvol,
                               unsigned int flags)
{
    int ret = -1;
1043
    char *create_tool;
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
    int imgformat;
    virCommandPtr cmd;

    virCheckFlags(VIR_STORAGE_VOL_CREATE_PREALLOC_METADATA, -1);

    /* KVM is usually ahead of qemu on features, so try that first */
    create_tool = virFindFileInPath("kvm-img");
    if (!create_tool)
        create_tool = virFindFileInPath("qemu-img");

    if (!create_tool) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("unable to find kvm-img or qemu-img"));
        return -1;
    }

    imgformat = virStorageBackendQEMUImgBackingFormat(create_tool);
    if (imgformat < 0)
        goto cleanup;

    cmd = virStorageBackendCreateQemuImgCmd(conn, pool, vol, inputvol, flags,
                                            create_tool, imgformat);
    if (!cmd)
        goto cleanup;

1069
    ret = virStorageBackendCreateExecCommand(pool, vol, cmd);
1070 1071

    virCommandFree(cmd);
1072
 cleanup:
1073
    VIR_FREE(create_tool);
1074
    return ret;
1075 1076 1077 1078 1079 1080 1081
}

/*
 * Xen removed the fully-functional qemu-img, and replaced it
 * with a partially functional qcow-create. Go figure ??!?
 */
static int
1082
virStorageBackendCreateQcowCreate(virConnectPtr conn ATTRIBUTE_UNUSED,
1083
                                  virStoragePoolObjPtr pool,
1084
                                  virStorageVolDefPtr vol,
1085
                                  virStorageVolDefPtr inputvol,
E
Eric Blake 已提交
1086
                                  unsigned int flags)
1087
{
1088
    int ret;
E
Eric Blake 已提交
1089
    char *size;
1090
    virCommandPtr cmd;
1091

1092 1093 1094 1095 1096 1097 1098 1099
    virCheckFlags(VIR_STORAGE_VOL_CREATE_PREALLOC_METADATA, -1);

    if (flags & VIR_STORAGE_VOL_CREATE_PREALLOC_METADATA) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("metadata preallocation is not supported with "
                         "qcow-create"));
        return -1;
    }
E
Eric Blake 已提交
1100

1101
    if (inputvol) {
1102 1103
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot copy from volume with qcow-create"));
1104 1105 1106
        return -1;
    }

1107
    if (vol->target.format != VIR_STORAGE_FILE_QCOW2) {
1108 1109 1110
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unsupported storage vol type %d"),
                       vol->target.format);
1111 1112
        return -1;
    }
1113
    if (vol->target.backingStore != NULL) {
1114 1115 1116
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("copy-on-write image not supported with "
                         "qcow-create"));
1117 1118
        return -1;
    }
1119
    if (vol->target.encryption != NULL) {
1120 1121 1122
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       "%s", _("encrypted volumes not supported with "
                               "qcow-create"));
1123 1124
        return -1;
    }
1125 1126

    /* Size in MB - yes different units to qemu-img :-( */
1127
    if (virAsprintf(&size, "%llu",
1128
                    VIR_DIV_UP(vol->target.capacity, (1024 * 1024))) < 0)
E
Eric Blake 已提交
1129
        return -1;
1130

1131
    cmd = virCommandNewArgList("qcow-create", size, vol->target.path, NULL);
1132

1133 1134
    ret = virStorageBackendCreateExecCommand(pool, vol, cmd);
    virCommandFree(cmd);
E
Eric Blake 已提交
1135
    VIR_FREE(size);
1136

1137
    return ret;
1138 1139
}

1140
virStorageBackendBuildVolFrom
1141
virStorageBackendFSImageToolTypeToFunc(int tool_type)
1142 1143 1144 1145 1146 1147 1148 1149
{
    switch (tool_type) {
    case TOOL_KVM_IMG:
    case TOOL_QEMU_IMG:
        return virStorageBackendCreateQemuImg;
    case TOOL_QCOW_CREATE:
        return virStorageBackendCreateQcowCreate;
    default:
1150 1151 1152
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unknown file create tool type '%d'."),
                       tool_type);
1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
    }

    return NULL;
}

int
virStorageBackendFindFSImageTool(char **tool)
{
    int tool_type = -1;
    char *tmp = NULL;

    if ((tmp = virFindFileInPath("kvm-img")) != NULL) {
        tool_type = TOOL_KVM_IMG;
    } else if ((tmp = virFindFileInPath("qemu-img")) != NULL) {
        tool_type = TOOL_QEMU_IMG;
    } else if ((tmp = virFindFileInPath("qcow-create")) != NULL) {
        tool_type = TOOL_QCOW_CREATE;
    }

    if (tool)
        *tool = tmp;
    else
        VIR_FREE(tmp);

    return tool_type;
}

1180
virStorageBackendBuildVolFrom
1181
virStorageBackendGetBuildVolFromFunction(virStorageVolDefPtr vol,
1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192
                                         virStorageVolDefPtr inputvol)
{
    int tool_type;

    if (!inputvol)
        return NULL;

    /* If either volume is a non-raw file vol, we need to use an external
     * tool for converting
     */
    if ((vol->type == VIR_STORAGE_VOL_FILE &&
1193
         vol->target.format != VIR_STORAGE_FILE_RAW) ||
1194
        (inputvol->type == VIR_STORAGE_VOL_FILE &&
1195
         inputvol->target.format != VIR_STORAGE_FILE_RAW)) {
1196

D
Daniel P. Berrange 已提交
1197
        if ((tool_type = virStorageBackendFindFSImageTool(NULL)) < 0) {
1198 1199 1200
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("creation of non-raw file images is "
                             "not supported without qemu-img."));
1201 1202 1203
            return NULL;
        }

1204
        return virStorageBackendFSImageToolTypeToFunc(tool_type);
1205 1206
    }

1207 1208 1209 1210
    if (vol->type == VIR_STORAGE_VOL_BLOCK)
        return virStorageBackendCreateBlockFrom;
    else
        return virStorageBackendCreateRaw;
1211
}
1212

1213

1214
virStorageBackendPtr
1215 1216
virStorageBackendForType(int type)
{
1217
    size_t i;
1218
    for (i = 0; backends[i]; i++)
1219 1220 1221
        if (backends[i]->type == type)
            return backends[i];

1222
    virReportError(VIR_ERR_INTERNAL_ERROR,
1223 1224
                   _("missing backend for pool type %d (%s)"),
                   type, NULLSTR(virStoragePoolTypeToString(type)));
1225 1226 1227 1228
    return NULL;
}


1229
virStorageFileBackendPtr
1230 1231 1232
virStorageFileBackendForTypeInternal(int type,
                                     int protocol,
                                     bool report)
1233 1234 1235 1236 1237
{
    size_t i;

    for (i = 0; fileBackends[i]; i++) {
        if (fileBackends[i]->type == type) {
E
Eric Blake 已提交
1238
            if (type == VIR_STORAGE_TYPE_NETWORK &&
1239 1240 1241 1242 1243 1244 1245
                fileBackends[i]->protocol != protocol)
                continue;

            return fileBackends[i];
        }
    }

1246 1247 1248
    if (!report)
        return NULL;

E
Eric Blake 已提交
1249
    if (type == VIR_STORAGE_TYPE_NETWORK) {
1250 1251 1252
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("missing storage backend for network files "
                         "using %s protocol"),
1253
                       virStorageNetProtocolTypeToString(protocol));
1254 1255 1256
    } else {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("missing storage backend for '%s' storage"),
E
Eric Blake 已提交
1257
                       virStorageTypeToString(type));
1258 1259 1260 1261 1262 1263
    }

    return NULL;
}


1264 1265 1266 1267 1268 1269 1270 1271
virStorageFileBackendPtr
virStorageFileBackendForType(int type,
                             int protocol)
{
    return virStorageFileBackendForTypeInternal(type, protocol, true);
}


1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305
struct diskType {
    int part_table_type;
    unsigned short offset;
    unsigned short length;
    unsigned long long magic;
};


static struct diskType const disk_types[] = {
    { VIR_STORAGE_POOL_DISK_LVM2, 0x218, 8, 0x31303020324D564CULL },
    { VIR_STORAGE_POOL_DISK_GPT,  0x200, 8, 0x5452415020494645ULL },
    { VIR_STORAGE_POOL_DISK_DVH,  0x0,   4, 0x41A9E50BULL },
    { VIR_STORAGE_POOL_DISK_MAC,  0x0,   2, 0x5245ULL },
    { VIR_STORAGE_POOL_DISK_BSD,  0x40,  4, 0x82564557ULL },
    { VIR_STORAGE_POOL_DISK_SUN,  0x1fc, 2, 0xBEDAULL },
    /*
     * NOTE: pc98 is funky; the actual signature is 0x55AA (just like dos), so
     * we can't use that.  At the moment I'm relying on the "dummy" IPL
     * bootloader data that comes from parted.  Luckily, the chances of running
     * into a pc98 machine running libvirt are approximately nil.
     */
    /*{ 0x1fe, 2, 0xAA55UL },*/
    { VIR_STORAGE_POOL_DISK_PC98, 0x0,   8, 0x314C5049000000CBULL },
    /*
     * NOTE: the order is important here; some other disk types (like GPT and
     * and PC98) also have 0x55AA at this offset.  For that reason, the DOS
     * one must be the last one.
     */
    { VIR_STORAGE_POOL_DISK_DOS,  0x1fe, 2, 0xAA55ULL },
    { -1,                         0x0,   0, 0x0ULL },
};


static int
1306
virStorageBackendDetectBlockVolFormatFD(virStorageSourcePtr target,
1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345
                                        int fd)
{
    size_t i;
    off_t start;
    unsigned char buffer[1024];
    ssize_t bytes;

    /* make sure to set the target format "unknown" to begin with */
    target->format = VIR_STORAGE_POOL_DISK_UNKNOWN;

    start = lseek(fd, 0, SEEK_SET);
    if (start < 0) {
        virReportSystemError(errno,
                             _("cannot seek to beginning of file '%s'"),
                             target->path);
        return -1;
    }
    bytes = saferead(fd, buffer, sizeof(buffer));
    if (bytes < 0) {
        virReportSystemError(errno,
                             _("cannot read beginning of file '%s'"),
                             target->path);
        return -1;
    }

    for (i = 0; disk_types[i].part_table_type != -1; i++) {
        if (disk_types[i].offset + disk_types[i].length > bytes)
            continue;
        if (memcmp(buffer+disk_types[i].offset, &disk_types[i].magic,
            disk_types[i].length) == 0) {
            target->format = disk_types[i].part_table_type;
            break;
        }
    }

    return 0;
}


1346 1347 1348
/*
 * Allows caller to silently ignore files with improper mode
 *
1349 1350 1351
 * Returns -1 on error. If VIR_STORAGE_VOL_OPEN_NOERROR is passed, we
 * return -2 if file mode is unexpected or the volume is a dangling
 * symbolic link.
1352
 */
1353
int
1354 1355
virStorageBackendVolOpen(const char *path, struct stat *sb,
                         unsigned int flags)
1356
{
1357
    int fd, mode = 0;
1358
    char *base = last_component(path);
1359
    bool noerror = (flags & VIR_STORAGE_VOL_OPEN_NOERROR);
1360

E
Eric Blake 已提交
1361
    if (lstat(path, sb) < 0) {
1362 1363 1364 1365 1366 1367 1368 1369 1370
        if (errno == ENOENT) {
            if (noerror) {
                VIR_WARN("ignoring missing file '%s'", path);
                return -2;
            }
            virReportError(VIR_ERR_NO_STORAGE_VOL,
                           _("no storage vol with matching path '%s'"),
                           path);
            return -1;
1371
        }
1372 1373 1374 1375 1376 1377
        virReportSystemError(errno,
                             _("cannot stat file '%s'"),
                             path);
        return -1;
    }

E
Eric Blake 已提交
1378
    if (S_ISFIFO(sb->st_mode)) {
1379 1380 1381 1382 1383 1384 1385
        if (noerror) {
            VIR_WARN("ignoring FIFO '%s'", path);
            return -2;
        }
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Volume path '%s' is a FIFO"), path);
        return -1;
E
Eric Blake 已提交
1386
    } else if (S_ISSOCK(sb->st_mode)) {
1387 1388 1389 1390 1391 1392 1393
        if (noerror) {
            VIR_WARN("ignoring socket '%s'", path);
            return -2;
        }
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Volume path '%s' is a socket"), path);
        return -1;
1394 1395
    }

1396 1397 1398 1399 1400 1401
    /* O_NONBLOCK should only matter during open() for fifos and
     * sockets, which we already filtered; but using it prevents a
     * TOCTTOU race.  However, later on we will want to read() the
     * header from this fd, and virFileRead* routines require a
     * blocking fd, so fix it up after verifying we avoided a
     * race.  */
1402
    if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_NOCTTY)) < 0) {
1403
        if ((errno == ENOENT || errno == ELOOP) &&
1404
            S_ISLNK(sb->st_mode) && noerror) {
1405 1406
            VIR_WARN("ignoring dangling symlink '%s'", path);
            return -2;
1407
        }
1408
        if (errno == ENOENT && noerror) {
1409 1410
            VIR_WARN("ignoring missing file '%s'", path);
            return -2;
1411 1412
        }

1413
        virReportSystemError(errno, _("cannot open volume '%s'"), path);
1414 1415 1416
        return -1;
    }

E
Eric Blake 已提交
1417
    if (fstat(fd, sb) < 0) {
1418
        virReportSystemError(errno, _("cannot stat file '%s'"), path);
1419 1420 1421 1422
        VIR_FORCE_CLOSE(fd);
        return -1;
    }

1423
    if (S_ISREG(sb->st_mode)) {
1424
        mode = VIR_STORAGE_VOL_OPEN_REG;
1425
    } else if (S_ISCHR(sb->st_mode)) {
1426
        mode = VIR_STORAGE_VOL_OPEN_CHAR;
1427
    } else if (S_ISBLK(sb->st_mode)) {
1428
        mode = VIR_STORAGE_VOL_OPEN_BLOCK;
1429
    } else if (S_ISDIR(sb->st_mode)) {
1430 1431 1432 1433 1434
        mode = VIR_STORAGE_VOL_OPEN_DIR;

        if (STREQ(base, ".") ||
            STREQ(base, "..")) {
            VIR_FORCE_CLOSE(fd);
1435 1436 1437 1438 1439 1440 1441
            if (noerror) {
                VIR_INFO("Skipping special dir '%s'", base);
                return -2;
            }
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Cannot use volume path '%s'"), path);
            return -1;
1442
        }
1443 1444
    } else {
        VIR_FORCE_CLOSE(fd);
1445 1446 1447 1448 1449 1450 1451
        if (noerror) {
            VIR_WARN("ignoring unexpected type for file '%s'", path);
            return -2;
        }
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected type for file '%s'"), path);
        return -1;
1452 1453 1454
    }

    if (virSetBlocking(fd, true) < 0) {
1455
        VIR_FORCE_CLOSE(fd);
1456 1457
        virReportSystemError(errno, _("unable to set blocking mode for '%s'"),
                             path);
1458
        return -1;
1459
    }
1460 1461

    if (!(mode & flags)) {
1462
        VIR_FORCE_CLOSE(fd);
1463 1464 1465
        if (noerror) {
            VIR_INFO("Skipping volume '%s'", path);
            return -2;
1466 1467
        }

1468 1469 1470
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected storage mode for '%s'"), path);
        return -1;
1471 1472 1473 1474 1475 1476
    }

    return fd;
}

int
1477
virStorageBackendUpdateVolTargetInfo(virStorageSourcePtr target,
1478
                                     bool updateCapacity,
1479
                                     bool withBlockVolFormat,
1480
                                     unsigned int openflags)
1481
{
1482
    int ret, fd = -1;
E
Eric Blake 已提交
1483
    struct stat sb;
1484

1485
    if ((ret = virStorageBackendVolOpen(target->path, &sb, openflags)) < 0)
1486
        goto cleanup;
1487
    fd = ret;
1488

1489 1490
    if ((ret = virStorageBackendUpdateVolTargetInfoFD(target, fd, &sb,
                                                      updateCapacity)) < 0)
1491 1492 1493 1494 1495 1496 1497
        goto cleanup;

    if (withBlockVolFormat) {
        if ((ret = virStorageBackendDetectBlockVolFormatFD(target, fd)) < 0)
            goto cleanup;
    }

1498
 cleanup:
1499
    VIR_FORCE_CLOSE(fd);
1500 1501 1502 1503

    return ret;
}

1504
int
1505
virStorageBackendUpdateVolInfo(virStorageVolDefPtr vol,
1506
                               bool updateCapacity,
1507
                               bool withBlockVolFormat,
1508
                               unsigned int openflags)
1509 1510 1511
{
    int ret;

1512
    if ((ret = virStorageBackendUpdateVolTargetInfo(&vol->target,
1513 1514 1515
                                                    updateCapacity,
                                                    withBlockVolFormat,
                                                    openflags)) < 0)
1516 1517
        return ret;

1518 1519
    if (vol->target.backingStore &&
        (ret = virStorageBackendUpdateVolTargetInfo(vol->target.backingStore,
1520 1521
                                                    updateCapacity,
                                                    withBlockVolFormat,
1522 1523
                                                    VIR_STORAGE_VOL_OPEN_DEFAULT |
                                                    VIR_STORAGE_VOL_OPEN_NOERROR) < 0))
1524 1525 1526 1527 1528
        return ret;

    return 0;
}

1529 1530 1531
/*
 * virStorageBackendUpdateVolTargetInfoFD:
 * @target: target definition ptr of volume to update
1532 1533
 * @fd: fd of storage volume to update, via virStorageBackendOpenVol*, or -1
 * @sb: details about file (must match @fd, if that is provided)
1534
 * @updateCapacity: If true, updated capacity info will be stored
1535
 *
1536
 * Returns 0 for success, -1 on a legitimate error condition.
1537
 */
1538
int
1539
virStorageBackendUpdateVolTargetInfoFD(virStorageSourcePtr target,
1540
                                       int fd,
1541 1542
                                       struct stat *sb,
                                       bool updateCapacity)
1543
{
1544
#if WITH_SELINUX
1545 1546 1547
    security_context_t filecon = NULL;
#endif

1548
    if (S_ISREG(sb->st_mode)) {
1549
#ifndef WIN32
1550 1551
        target->allocation = (unsigned long long)sb->st_blocks *
            (unsigned long long)DEV_BSIZE;
D
Daniel P. Berrange 已提交
1552
#else
1553
        target->allocation = sb->st_size;
D
Daniel P. Berrange 已提交
1554
#endif
1555 1556 1557
        /* Regular files may be sparse, so logical size (capacity) is not same
         * as actual allocation above
         */
1558 1559
        if (updateCapacity)
            target->capacity = sb->st_size;
1560 1561
    } else if (S_ISDIR(sb->st_mode)) {
        target->allocation = 0;
1562 1563
        if (updateCapacity)
            target->capacity = 0;
1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576
    } else if (fd >= 0) {
        off_t end;
        /* XXX this is POSIX compliant, but doesn't work for CHAR files,
         * only BLOCK. There is a Linux specific ioctl() for getting
         * size of both CHAR / BLOCK devices we should check for in
         * configure
         */
        end = lseek(fd, 0, SEEK_END);
        if (end == (off_t)-1) {
            virReportSystemError(errno,
                                 _("cannot seek to end of file '%s'"),
                                 target->path);
            return -1;
1577
        }
1578
        target->allocation = end;
1579 1580
        if (updateCapacity)
            target->capacity = end;
1581 1582
    }

1583 1584 1585 1586 1587
    if (!target->perms && VIR_ALLOC(target->perms) < 0)
        return -1;
    target->perms->mode = sb->st_mode & S_IRWXUGO;
    target->perms->uid = sb->st_uid;
    target->perms->gid = sb->st_gid;
1588

1589
    if (!target->timestamps && VIR_ALLOC(target->timestamps) < 0)
1590
        return -1;
E
Eric Blake 已提交
1591 1592 1593 1594
    target->timestamps->atime = get_stat_atime(sb);
    target->timestamps->btime = get_stat_birthtime(sb);
    target->timestamps->ctime = get_stat_ctime(sb);
    target->timestamps->mtime = get_stat_mtime(sb);
1595

1596
    VIR_FREE(target->perms->label);
1597

1598
#if WITH_SELINUX
1599
    /* XXX: make this a security driver call */
1600 1601 1602 1603 1604 1605 1606 1607
    if (fd >= 0) {
        if (fgetfilecon_raw(fd, &filecon) == -1) {
            if (errno != ENODATA && errno != ENOTSUP) {
                virReportSystemError(errno,
                                     _("cannot get file context of '%s'"),
                                     target->path);
                return -1;
            }
1608
        } else {
1609
            if (VIR_STRDUP(target->perms->label, filecon) < 0) {
1610 1611 1612
                freecon(filecon);
                return -1;
            }
1613
            freecon(filecon);
1614
        }
1615 1616 1617 1618 1619 1620
    }
#endif

    return 0;
}

D
Dave Allan 已提交
1621

1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633
/*
 * Given a volume path directly in /dev/XXX, iterate over the
 * entries in the directory pool->def->target.path and find the
 * first symlink pointing to the volume path.
 *
 * If, the target.path is /dev/, then return the original volume
 * path.
 *
 * If no symlink is found, then return the original volume path
 *
 * Typically target.path is one of the /dev/disk/by-XXX dirs
 * with stable paths.
1634
 *
1635
 * If 'loop' is true, we use a timeout loop to give dynamic paths
1636
 * a change to appear.
1637 1638
 */
char *
1639
virStorageBackendStablePath(virStoragePoolObjPtr pool,
1640
                            const char *devpath,
1641
                            bool loop)
1642 1643 1644
{
    DIR *dh;
    struct dirent *dent;
1645
    char *stablepath;
1646
    int opentries = 0;
1647
    int retry = 0;
E
Eric Blake 已提交
1648
    int direrr;
1649 1650 1651 1652 1653

    /* Short circuit if pool has no target, or if its /dev */
    if (pool->def->target.path == NULL ||
        STREQ(pool->def->target.path, "/dev") ||
        STREQ(pool->def->target.path, "/dev/"))
1654
        goto ret_strdup;
1655

1656
    /* Skip whole thing for a pool which isn't in /dev
1657
     * so we don't mess filesystem/dir based pools
1658 1659 1660 1661
     */
    if (!STRPREFIX(pool->def->target.path, "/dev"))
        goto ret_strdup;

1662 1663 1664 1665
    /* Logical pools are under /dev but already have stable paths */
    if (pool->def->type == VIR_STORAGE_POOL_LOGICAL)
        goto ret_strdup;

1666 1667 1668
    /* We loop here because /dev/disk/by-{id,path} may not have existed
     * before we started this operation, so we have to give it some time to
     * get created.
1669
     */
1670
 reopen:
1671
    if ((dh = opendir(pool->def->target.path)) == NULL) {
1672
        opentries++;
1673
        if (loop && errno == ENOENT && opentries < 50) {
1674 1675 1676
            usleep(100 * 1000);
            goto reopen;
        }
1677
        virReportSystemError(errno,
1678 1679
                             _("cannot read dir '%s'"),
                             pool->def->target.path);
1680 1681 1682
        return NULL;
    }

1683 1684 1685
    /* The pool is pointing somewhere like /dev/disk/by-path
     * or /dev/disk/by-id, so we need to check all symlinks in
     * the target directory and figure out which one points
1686 1687
     * to this device node.
     *
1688
     * And it might need some time till the stable path shows
E
Eric Blake 已提交
1689 1690
     * up, so add timeout to retry here.  Ignore readdir failures,
     * since we have a fallback.
1691
     */
1692
 retry:
E
Eric Blake 已提交
1693
    while ((direrr = virDirRead(dh, &dent, NULL)) > 0) {
1694 1695 1696
        if (dent->d_name[0] == '.')
            continue;

1697 1698 1699
        if (virAsprintf(&stablepath, "%s/%s",
                        pool->def->target.path,
                        dent->d_name) == -1) {
1700 1701 1702 1703 1704 1705 1706 1707 1708
            closedir(dh);
            return NULL;
        }

        if (virFileLinkPointsTo(stablepath, devpath)) {
            closedir(dh);
            return stablepath;
        }

1709
        VIR_FREE(stablepath);
1710 1711
    }

E
Eric Blake 已提交
1712
    if (!direrr && loop && ++retry < 100) {
1713 1714 1715 1716
        usleep(100 * 1000);
        goto retry;
    }

1717 1718
    closedir(dh);

1719
 ret_strdup:
1720 1721 1722
    /* Couldn't find any matching stable link so give back
     * the original non-stable dev path
     */
1723

1724
    ignore_value(VIR_STRDUP(stablepath, devpath));
1725 1726

    return stablepath;
1727
}
1728

1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741
int
virStorageBackendVolUploadLocal(virConnectPtr conn ATTRIBUTE_UNUSED,
                                virStoragePoolObjPtr pool ATTRIBUTE_UNUSED,
                                virStorageVolDefPtr vol,
                                virStreamPtr stream,
                                unsigned long long offset,
                                unsigned long long len,
                                unsigned int flags)
{
    virCheckFlags(0, -1);

    /* Not using O_CREAT because the file is required to already exist at
     * this point */
1742 1743
    return virFDStreamOpenBlockDevice(stream, vol->target.path,
                                      offset, len, O_WRONLY);
1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756
}

int
virStorageBackendVolDownloadLocal(virConnectPtr conn ATTRIBUTE_UNUSED,
                                  virStoragePoolObjPtr pool ATTRIBUTE_UNUSED,
                                  virStorageVolDefPtr vol,
                                  virStreamPtr stream,
                                  unsigned long long offset,
                                  unsigned long long len,
                                  unsigned int flags)
{
    virCheckFlags(0, -1);

1757 1758
    return virFDStreamOpenBlockDevice(stream, vol->target.path,
                                      offset, len, O_RDONLY);
1759 1760
}

1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963

/* If the volume we're wiping is already a sparse file, we simply
 * truncate and extend it to its original size, filling it with
 * zeroes.  This behavior is guaranteed by POSIX:
 *
 * http://www.opengroup.org/onlinepubs/9699919799/functions/ftruncate.html
 *
 * If fildes refers to a regular file, the ftruncate() function shall
 * cause the size of the file to be truncated to length. If the size
 * of the file previously exceeded length, the extra data shall no
 * longer be available to reads on the file. If the file previously
 * was smaller than this size, ftruncate() shall increase the size of
 * the file. If the file size is increased, the extended area shall
 * appear as if it were zero-filled.
 */
static int
virStorageBackendVolZeroSparseFileLocal(virStorageVolDefPtr vol,
                                        off_t size,
                                        int fd)
{
    int ret = -1;

    ret = ftruncate(fd, 0);
    if (ret == -1) {
        virReportSystemError(errno,
                             _("Failed to truncate volume with "
                               "path '%s' to 0 bytes"),
                             vol->target.path);
        return ret;
    }

    ret = ftruncate(fd, size);
    if (ret == -1) {
        virReportSystemError(errno,
                             _("Failed to truncate volume with "
                               "path '%s' to %ju bytes"),
                             vol->target.path, (uintmax_t)size);
    }

    return ret;
}


static int
virStorageBackendWipeExtentLocal(virStorageVolDefPtr vol,
                                 int fd,
                                 off_t extent_start,
                                 off_t extent_length,
                                 char *writebuf,
                                 size_t writebuf_length,
                                 size_t *bytes_wiped)
{
    int ret = -1, written = 0;
    off_t remaining = 0;
    size_t write_size = 0;

    VIR_DEBUG("extent logical start: %ju len: %ju",
              (uintmax_t)extent_start, (uintmax_t)extent_length);

    if ((ret = lseek(fd, extent_start, SEEK_SET)) < 0) {
        virReportSystemError(errno,
                             _("Failed to seek to position %ju in volume "
                               "with path '%s'"),
                             (uintmax_t)extent_start, vol->target.path);
        goto cleanup;
    }

    remaining = extent_length;
    while (remaining > 0) {

        write_size = (writebuf_length < remaining) ? writebuf_length : remaining;
        written = safewrite(fd, writebuf, write_size);
        if (written < 0) {
            virReportSystemError(errno,
                                 _("Failed to write %zu bytes to "
                                   "storage volume with path '%s'"),
                                 write_size, vol->target.path);

            goto cleanup;
        }

        *bytes_wiped += written;
        remaining -= written;
    }

    if (fdatasync(fd) < 0) {
        ret = -errno;
        virReportSystemError(errno,
                             _("cannot sync data to volume with path '%s'"),
                             vol->target.path);
        goto cleanup;
    }

    VIR_DEBUG("Wrote %zu bytes to volume with path '%s'",
              *bytes_wiped, vol->target.path);

    ret = 0;

 cleanup:
    return ret;
}


int
virStorageBackendVolWipeLocal(virConnectPtr conn ATTRIBUTE_UNUSED,
                              virStoragePoolObjPtr pool ATTRIBUTE_UNUSED,
                              virStorageVolDefPtr vol,
                              unsigned int algorithm,
                              unsigned int flags)
{
    int ret = -1, fd = -1;
    struct stat st;
    char *writebuf = NULL;
    size_t bytes_wiped = 0;
    virCommandPtr cmd = NULL;

    virCheckFlags(0, -1);

    VIR_DEBUG("Wiping volume with path '%s' and algorithm %u",
              vol->target.path, algorithm);

    fd = open(vol->target.path, O_RDWR);
    if (fd == -1) {
        virReportSystemError(errno,
                             _("Failed to open storage volume with path '%s'"),
                             vol->target.path);
        goto cleanup;
    }

    if (fstat(fd, &st) == -1) {
        virReportSystemError(errno,
                             _("Failed to stat storage volume with path '%s'"),
                             vol->target.path);
        goto cleanup;
    }

    if (algorithm != VIR_STORAGE_VOL_WIPE_ALG_ZERO) {
        const char *alg_char ATTRIBUTE_UNUSED = NULL;
        switch (algorithm) {
        case VIR_STORAGE_VOL_WIPE_ALG_NNSA:
            alg_char = "nnsa";
            break;
        case VIR_STORAGE_VOL_WIPE_ALG_DOD:
            alg_char = "dod";
            break;
        case VIR_STORAGE_VOL_WIPE_ALG_BSI:
            alg_char = "bsi";
            break;
        case VIR_STORAGE_VOL_WIPE_ALG_GUTMANN:
            alg_char = "gutmann";
            break;
        case VIR_STORAGE_VOL_WIPE_ALG_SCHNEIER:
            alg_char = "schneier";
            break;
        case VIR_STORAGE_VOL_WIPE_ALG_PFITZNER7:
            alg_char = "pfitzner7";
            break;
        case VIR_STORAGE_VOL_WIPE_ALG_PFITZNER33:
            alg_char = "pfitzner33";
            break;
        case VIR_STORAGE_VOL_WIPE_ALG_RANDOM:
            alg_char = "random";
            break;
        default:
            virReportError(VIR_ERR_INVALID_ARG,
                           _("unsupported algorithm %d"),
                           algorithm);
        }
        cmd = virCommandNew(SCRUB);
        virCommandAddArgList(cmd, "-f", "-p", alg_char,
                             vol->target.path, NULL);

        if (virCommandRun(cmd, NULL) < 0)
            goto cleanup;

        ret = 0;
        goto cleanup;
    } else {
        if (S_ISREG(st.st_mode) && st.st_blocks < (st.st_size / DEV_BSIZE)) {
            ret = virStorageBackendVolZeroSparseFileLocal(vol, st.st_size, fd);
        } else {

            if (VIR_ALLOC_N(writebuf, st.st_blksize) < 0)
                goto cleanup;

            ret = virStorageBackendWipeExtentLocal(vol,
                                                   fd,
                                                   0,
                                                   vol->target.allocation,
                                                   writebuf,
                                                   st.st_blksize,
                                                   &bytes_wiped);
        }
    }

 cleanup:
    virCommandFree(cmd);
    VIR_FREE(writebuf);
    VIR_FORCE_CLOSE(fd);
    return ret;
}


1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051
#ifdef GLUSTER_CLI
int
virStorageBackendFindGlusterPoolSources(const char *host,
                                        int pooltype,
                                        virStoragePoolSourceListPtr list)
{
    char *outbuf = NULL;
    virCommandPtr cmd = NULL;
    xmlDocPtr doc = NULL;
    xmlXPathContextPtr ctxt = NULL;
    xmlNodePtr *nodes = NULL;
    virStoragePoolSource *src = NULL;
    size_t i;
    int nnodes;
    int rc;

    int ret = -1;

    cmd = virCommandNewArgList(GLUSTER_CLI,
                               "--xml",
                               "--log-file=/dev/null",
                               "volume", "info", "all", NULL);

    virCommandAddArgFormat(cmd, "--remote-host=%s", host);
    virCommandSetOutputBuffer(cmd, &outbuf);

    if (virCommandRun(cmd, &rc) < 0)
        goto cleanup;

    if (rc != 0) {
        VIR_INFO("failed to query host '%s' for gluster volumes: %s",
                 host, outbuf);
        ret = 0;
        goto cleanup;
    }

    if (!(doc = virXMLParseStringCtxt(outbuf, _("(gluster_cli_output)"),
                                      &ctxt)))
        goto cleanup;

    if ((nnodes = virXPathNodeSet("//volumes/volume", ctxt, &nodes)) <= 0) {
        VIR_INFO("no gluster volumes available on '%s'", host);
        ret = 0;
        goto cleanup;
    }

    for (i = 0; i < nnodes; i++) {
        ctxt->node = nodes[i];

        if (!(src = virStoragePoolSourceListNewSource(list)))
            goto cleanup;

        if (!(src->dir = virXPathString("string(//name)", ctxt))) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("failed to extract gluster volume name"));
            goto cleanup;
        }

        if (VIR_ALLOC_N(src->hosts, 1) < 0)
            goto cleanup;
        src->nhost = 1;

        if (VIR_STRDUP(src->hosts[0].name, host) < 0)
            goto cleanup;

        src->format = pooltype;
    }

    ret = 0;

 cleanup:
    VIR_FREE(nodes);
    xmlXPathFreeContext(ctxt);
    xmlFreeDoc(doc);
    VIR_FREE(outbuf);
    virCommandFree(cmd);
    return ret;
}
#else /* #ifdef GLUSTER_CLI */
int
virStorageBackendFindGlusterPoolSources(const char *host ATTRIBUTE_UNUSED,
                                        int pooltype ATTRIBUTE_UNUSED,
                                        virStoragePoolSourceListPtr list ATTRIBUTE_UNUSED)
{
    VIR_INFO("gluster cli tool not installed");
    return 0;
}
#endif /* #ifdef GLUSTER_CLI */