virstoragefile.c 139.7 KB
Newer Older
1
/*
2
 * virstoragefile.c: file utility functions for FS storage backend
3
 *
E
Eric Blake 已提交
4
 * Copyright (C) 2007-2017 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
 */

#include <config.h>
23
#include "virstoragefilebackend.h"
24

25
#include <unistd.h>
26
#include <fcntl.h>
27
#include "viralloc.h"
28 29
#include "virxml.h"
#include "viruuid.h"
30
#include "virerror.h"
31
#include "virlog.h"
E
Eric Blake 已提交
32
#include "virfile.h"
33
#include "c-ctype.h"
34
#include "vircommand.h"
35
#include "virhash.h"
E
Eric Blake 已提交
36
#include "virendian.h"
37 38
#include "virstring.h"
#include "virutil.h"
39 40
#include "viruri.h"
#include "dirname.h"
41
#include "virbuffer.h"
42
#include "virjson.h"
43
#include "virstorageencryption.h"
44
#include "virsecret.h"
45 46 47

#define VIR_FROM_THIS VIR_FROM_STORAGE

48 49
VIR_LOG_INIT("util.storagefile");

50 51
static virClassPtr virStorageSourceClass;

52 53
VIR_ENUM_IMPL(virStorage,
              VIR_STORAGE_TYPE_LAST,
54
              "none",
E
Eric Blake 已提交
55
              "file",
56
              "block",
E
Eric Blake 已提交
57 58
              "dir",
              "network",
59 60
              "volume",
);
E
Eric Blake 已提交
61

62 63
VIR_ENUM_IMPL(virStorageFileFormat,
              VIR_STORAGE_FILE_LAST,
E
Eric Blake 已提交
64
              "none",
65
              "raw", "dir", "bochs",
66 67 68
              "cloop", "dmg", "iso",
              "vpc", "vdi",
              /* Not direct file formats, but used for various drivers */
69
              "fat", "vhd", "ploop",
70
              /* Formats with backing file below here */
71 72
              "cow", "qcow", "qcow2", "qed", "vmdk",
);
73

74 75 76
VIR_ENUM_IMPL(virStorageFileFeature,
              VIR_STORAGE_FILE_FEATURE_LAST,
              "lazy_refcounts",
77
);
78

79 80
VIR_ENUM_IMPL(virStorageNetProtocol,
              VIR_STORAGE_NET_PROTOCOL_LAST,
81
              "none",
82 83 84 85 86 87 88 89 90
              "nbd",
              "rbd",
              "sheepdog",
              "gluster",
              "iscsi",
              "http",
              "https",
              "ftp",
              "ftps",
91
              "tftp",
92
              "ssh",
93 94
              "vxhs",
);
95

96 97
VIR_ENUM_IMPL(virStorageNetHostTransport,
              VIR_STORAGE_NET_HOST_TRANS_LAST,
98 99
              "tcp",
              "unix",
100 101
              "rdma",
);
102

103 104 105 106
VIR_ENUM_IMPL(virStorageSourcePoolMode,
              VIR_STORAGE_SOURCE_POOL_MODE_LAST,
              "default",
              "host",
107 108
              "direct",
);
109

110 111
VIR_ENUM_IMPL(virStorageAuth,
              VIR_STORAGE_AUTH_TYPE_LAST,
112 113
              "none", "chap", "ceph",
);
114

115 116 117 118 119 120 121 122 123 124 125
enum lv_endian {
    LV_LITTLE_ENDIAN = 1, /* 1234 */
    LV_BIG_ENDIAN         /* 4321 */
};

enum {
    BACKING_STORE_OK,
    BACKING_STORE_INVALID,
    BACKING_STORE_ERROR,
};

D
Daniel P. Berrange 已提交
126
#define FILE_TYPE_VERSIONS_LAST 3
127

128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
struct FileEncryptionInfo {
    int format; /* Encryption format to assign */

    int magicOffset; /* Byte offset of the magic */
    const char *magic; /* Optional string of magic */

    enum lv_endian endian; /* Endianness of file format */

    int versionOffset;    /* Byte offset from start of file
                           * where we find version number,
                           * -1 to always fail the version test,
                           * -2 to always pass the version test */
    int versionSize;      /* Size in bytes of version data (0, 2, or 4) */
    int versionNumbers[FILE_TYPE_VERSIONS_LAST];
                          /* Version numbers to validate. Zeroes are ignored. */

    int modeOffset; /* Byte offset of the format native encryption mode */
    char modeValue; /* Value expected at offset */
146 147

    int payloadOffset; /* start offset of the volume data (in 512 byte sectors) */
148 149
};

150 151
/* Either 'magic' or 'extension' *must* be provided */
struct FileTypeInfo {
152
    int magicOffset;    /* Byte offset of the magic */
153 154 155 156
    const char *magic;  /* Optional string of file magic
                         * to check at head of file */
    const char *extension; /* Optional file extension to check */
    enum lv_endian endian; /* Endianness of file format */
157

158 159
    int versionOffset;    /* Byte offset from start of file
                           * where we find version number,
160 161
                           * -1 to always fail the version test,
                           * -2 to always pass the version test */
162
    int versionSize;      /* Size in bytes of version data (0, 2, or 4) */
163 164
    int versionNumbers[FILE_TYPE_VERSIONS_LAST];
                          /* Version numbers to validate. Zeroes are ignored. */
165 166 167 168 169 170 171 172
    int sizeOffset;       /* Byte offset from start of file
                           * where we find capacity info,
                           * -1 to use st_size as capacity */
    int sizeBytes;        /* Number of bytes for size field */
    int sizeMultiplier;   /* A scaling factor if size is not in bytes */
                          /* Store a COW base image path (possibly relative),
                           * or NULL if there is no COW base image, to RES;
                           * return BACKING_STORE_* */
173
    const struct FileEncryptionInfo *cryptInfo; /* Encryption info */
174
    int (*getBackingStore)(char **res, int *format,
E
Eric Blake 已提交
175
                           const char *buf, size_t buf_size);
176
    int (*getFeatures)(virBitmapPtr *features, int format,
E
Eric Blake 已提交
177
                       char *buf, ssize_t len);
178 179
};

180

181
static int cowGetBackingStore(char **, int *,
E
Eric Blake 已提交
182
                              const char *, size_t);
183
static int qcow1GetBackingStore(char **, int *,
E
Eric Blake 已提交
184
                                const char *, size_t);
185
static int qcow2GetBackingStore(char **, int *,
E
Eric Blake 已提交
186
                                const char *, size_t);
187
static int qcow2GetFeatures(virBitmapPtr *features, int format,
E
Eric Blake 已提交
188
                            char *buf, ssize_t len);
189
static int vmdk4GetBackingStore(char **, int *,
E
Eric Blake 已提交
190
                                const char *, size_t);
191
static int
E
Eric Blake 已提交
192
qedGetBackingStore(char **, int *, const char *, size_t);
193 194 195 196 197 198

#define QCOWX_HDR_VERSION (4)
#define QCOWX_HDR_BACKING_FILE_OFFSET (QCOWX_HDR_VERSION+4)
#define QCOWX_HDR_BACKING_FILE_SIZE (QCOWX_HDR_BACKING_FILE_OFFSET+8)
#define QCOWX_HDR_IMAGE_SIZE (QCOWX_HDR_BACKING_FILE_SIZE+4+4)

199
#define QCOW1_HDR_CRYPT (QCOWX_HDR_IMAGE_SIZE+8+1+1+2)
200 201 202 203 204 205 206 207
#define QCOW2_HDR_CRYPT (QCOWX_HDR_IMAGE_SIZE+8)

#define QCOW1_HDR_TOTAL_SIZE (QCOW1_HDR_CRYPT+4+8)
#define QCOW2_HDR_TOTAL_SIZE (QCOW2_HDR_CRYPT+4+4+8+8+4+4+8)

#define QCOW2_HDR_EXTENSION_END 0
#define QCOW2_HDR_EXTENSION_BACKING_FORMAT 0xE2792ACA

208 209 210 211 212 213 214
#define QCOW2v3_HDR_FEATURES_INCOMPATIBLE (QCOW2_HDR_TOTAL_SIZE)
#define QCOW2v3_HDR_FEATURES_COMPATIBLE (QCOW2v3_HDR_FEATURES_INCOMPATIBLE+8)
#define QCOW2v3_HDR_FEATURES_AUTOCLEAR (QCOW2v3_HDR_FEATURES_COMPATIBLE+8)

/* The location of the header size [4 bytes] */
#define QCOW2v3_HDR_SIZE       (QCOW2_HDR_TOTAL_SIZE+8+8+8+4)

215
#define QED_HDR_FEATURES_OFFSET (4+4+4+4)
216 217
#define QED_HDR_IMAGE_SIZE (QED_HDR_FEATURES_OFFSET+8+8+8+8)
#define QED_HDR_BACKING_FILE_OFFSET (QED_HDR_IMAGE_SIZE+8)
218 219 220
#define QED_HDR_BACKING_FILE_SIZE (QED_HDR_BACKING_FILE_OFFSET+4)
#define QED_F_BACKING_FILE 0x01
#define QED_F_BACKING_FORMAT_NO_PROBE 0x04
A
Adam Litke 已提交
221

222 223
#define PLOOP_IMAGE_SIZE_OFFSET 36
#define PLOOP_SIZE_MULTIPLIER 512
224

225 226
#define LUKS_HDR_MAGIC_LEN 6
#define LUKS_HDR_VERSION_LEN 2
227 228 229 230
#define LUKS_HDR_CIPHER_NAME_LEN 32
#define LUKS_HDR_CIPHER_MODE_LEN 32
#define LUKS_HDR_HASH_SPEC_LEN 32
#define LUKS_HDR_PAYLOAD_LEN 4
231 232 233

/* Format described by qemu commit id '3e308f20e' */
#define LUKS_HDR_VERSION_OFFSET LUKS_HDR_MAGIC_LEN
234 235 236 237 238
#define LUKS_HDR_PAYLOAD_OFFSET (LUKS_HDR_MAGIC_LEN+\
                                 LUKS_HDR_VERSION_LEN+\
                                 LUKS_HDR_CIPHER_NAME_LEN+\
                                 LUKS_HDR_CIPHER_MODE_LEN+\
                                 LUKS_HDR_HASH_SPEC_LEN)
239

240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
static struct FileEncryptionInfo const luksEncryptionInfo[] = {
    {
        .format = VIR_STORAGE_ENCRYPTION_FORMAT_LUKS,

        /* Magic is 'L','U','K','S', 0xBA, 0xBE */
        .magicOffset = 0,
        .magic = "\x4c\x55\x4b\x53\xba\xbe",
        .endian = LV_BIG_ENDIAN,

        .versionOffset  = LUKS_HDR_VERSION_OFFSET,
        .versionSize = LUKS_HDR_VERSION_LEN,
        .versionNumbers = {1},

        .modeOffset = -1,
        .modeValue = -1,
255 256

        .payloadOffset = LUKS_HDR_PAYLOAD_OFFSET,
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
    },
    { 0 }
};

static struct FileEncryptionInfo const qcow1EncryptionInfo[] = {
    {
        .format = VIR_STORAGE_ENCRYPTION_FORMAT_QCOW,

        .magicOffset = 0,
        .magic = NULL,
        .endian = LV_BIG_ENDIAN,

        .versionOffset  = -1,
        .versionSize = 0,
        .versionNumbers = {},

        .modeOffset = QCOW1_HDR_CRYPT,
        .modeValue = 1,
275 276

        .payloadOffset = -1,
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
    },
    { 0 }
};

static struct FileEncryptionInfo const qcow2EncryptionInfo[] = {
    {
        .format = VIR_STORAGE_ENCRYPTION_FORMAT_QCOW,

        .magicOffset = 0,
        .magic = NULL,
        .endian = LV_BIG_ENDIAN,

        .versionOffset  = -1,
        .versionSize = 0,
        .versionNumbers = {},

        .modeOffset = QCOW2_HDR_CRYPT,
        .modeValue = 1,
295 296

        .payloadOffset = -1,
297 298 299
    },
    { 0 }
};
300

301
static struct FileTypeInfo const fileTypeInfo[] = {
302
    [VIR_STORAGE_FILE_NONE] = { 0, NULL, NULL, LV_LITTLE_ENDIAN,
303
                                -1, 0, {0}, 0, 0, 0, NULL, NULL, NULL },
304
    [VIR_STORAGE_FILE_RAW] = { 0, NULL, NULL, LV_LITTLE_ENDIAN,
305 306 307
                               -1, 0, {0}, 0, 0, 0,
                               luksEncryptionInfo,
                               NULL, NULL },
308
    [VIR_STORAGE_FILE_DIR] = { 0, NULL, NULL, LV_LITTLE_ENDIAN,
309
                               -1, 0, {0}, 0, 0, 0, NULL, NULL, NULL },
310
    [VIR_STORAGE_FILE_BOCHS] = {
311 312
        /*"Bochs Virtual HD Image", */ /* Untested */
        0, NULL, NULL,
313
        LV_LITTLE_ENDIAN, 64, 4, {0x20000},
314
        32+16+16+4+4+4+4+4, 8, 1, NULL, NULL, NULL
315 316
    },
    [VIR_STORAGE_FILE_CLOOP] = {
317 318 319 320 321
        /* #!/bin/sh
           #V2.0 Format
           modprobe cloop file=$0 && mount -r -t iso9660 /dev/cloop $1
        */ /* Untested */
        0, NULL, NULL,
322
        LV_LITTLE_ENDIAN, -1, 0, {0},
323
        -1, 0, 0, NULL, NULL, NULL
324 325
    },
    [VIR_STORAGE_FILE_DMG] = {
326 327 328 329
        /* XXX QEMU says there's no magic for dmg,
         * /usr/share/misc/magic lists double magic (both offsets
         * would have to match) but then disables that check. */
        0, NULL, ".dmg",
330
        0, -1, 0, {0},
331
        -1, 0, 0, NULL, NULL, NULL
332 333
    },
    [VIR_STORAGE_FILE_ISO] = {
334
        32769, "CD001", ".iso",
335
        LV_LITTLE_ENDIAN, -2, 0, {0},
336
        -1, 0, 0, NULL, NULL, NULL
337
    },
338 339
    [VIR_STORAGE_FILE_VPC] = {
        0, "conectix", NULL,
340
        LV_BIG_ENDIAN, 12, 4, {0x10000},
341
        8 + 4 + 4 + 8 + 4 + 4 + 2 + 2 + 4, 8, 1, NULL, NULL, NULL
342 343 344 345
    },
    /* TODO: add getBackingStore function */
    [VIR_STORAGE_FILE_VDI] = {
        64, "\x7f\x10\xda\xbe", ".vdi",
346
        LV_LITTLE_ENDIAN, 68, 4, {0x00010001},
347
        64 + 5 * 4 + 256 + 7 * 4, 8, 1, NULL, NULL, NULL},
348 349 350

    /* Not direct file formats, but used for various drivers */
    [VIR_STORAGE_FILE_FAT] = { 0, NULL, NULL, LV_LITTLE_ENDIAN,
351
                               -1, 0, {0}, 0, 0, 0, NULL, NULL, NULL },
352
    [VIR_STORAGE_FILE_VHD] = { 0, NULL, NULL, LV_LITTLE_ENDIAN,
353
                               -1, 0, {0}, 0, 0, 0, NULL, NULL, NULL },
354
    [VIR_STORAGE_FILE_PLOOP] = { 0, "WithouFreSpacExt", NULL, LV_LITTLE_ENDIAN,
355
                                 -2, 0, {0}, PLOOP_IMAGE_SIZE_OFFSET, 0,
356 357
                                 PLOOP_SIZE_MULTIPLIER, NULL, NULL, NULL },

358 359 360
    /* All formats with a backing store probe below here */
    [VIR_STORAGE_FILE_COW] = {
        0, "OOOM", NULL,
361
        LV_BIG_ENDIAN, 4, 4, {2},
362
        4+4+1024+4, 8, 1, NULL, cowGetBackingStore, NULL
363
    },
364
    [VIR_STORAGE_FILE_QCOW] = {
365
        0, "QFI", NULL,
366
        LV_BIG_ENDIAN, 4, 4, {1},
367 368 369
        QCOWX_HDR_IMAGE_SIZE, 8, 1,
        qcow1EncryptionInfo,
        qcow1GetBackingStore, NULL
370 371
    },
    [VIR_STORAGE_FILE_QCOW2] = {
372
        0, "QFI", NULL,
373
        LV_BIG_ENDIAN, 4, 4, {2, 3},
374 375 376
        QCOWX_HDR_IMAGE_SIZE, 8, 1,
        qcow2EncryptionInfo,
        qcow2GetBackingStore,
377
        qcow2GetFeatures
378
    },
A
Adam Litke 已提交
379
    [VIR_STORAGE_FILE_QED] = {
380
        /* https://wiki.qemu.org/Features/QED */
381
        0, "QED", NULL,
382
        LV_LITTLE_ENDIAN, -2, 0, {0},
383
        QED_HDR_IMAGE_SIZE, 8, 1, NULL, qedGetBackingStore, NULL
A
Adam Litke 已提交
384
    },
385
    [VIR_STORAGE_FILE_VMDK] = {
386
        0, "KDMV", NULL,
D
Daniel P. Berrange 已提交
387
        LV_LITTLE_ENDIAN, 4, 4, {1, 2, 3},
388
        4+4+4, 8, 512, NULL, vmdk4GetBackingStore, NULL
389
    },
390
};
391
verify(ARRAY_CARDINALITY(fileTypeInfo) == VIR_STORAGE_FILE_LAST);
392

393

394 395 396 397 398 399 400 401 402 403 404 405 406 407
/* qcow2 compatible features in the order they appear on-disk */
enum qcow2CompatibleFeature {
    QCOW2_COMPATIBLE_FEATURE_LAZY_REFCOUNTS = 0,

    QCOW2_COMPATIBLE_FEATURE_LAST
};

/* conversion to virStorageFileFeature */
static const int qcow2CompatibleFeatureArray[] = {
    VIR_STORAGE_FILE_FEATURE_LAZY_REFCOUNTS,
};
verify(ARRAY_CARDINALITY(qcow2CompatibleFeatureArray) ==
       QCOW2_COMPATIBLE_FEATURE_LAST);

408
static int
409
cowGetBackingStore(char **res,
410
                   int *format,
E
Eric Blake 已提交
411
                   const char *buf,
412 413 414 415
                   size_t buf_size)
{
#define COW_FILENAME_MAXLEN 1024
    *res = NULL;
416 417
    *format = VIR_STORAGE_FILE_AUTO;

418 419
    if (buf_size < 4+4+ COW_FILENAME_MAXLEN)
        return BACKING_STORE_INVALID;
E
Eric Blake 已提交
420 421
    if (buf[4+4] == '\0') { /* cow_header_v2.backing_file[0] */
        *format = VIR_STORAGE_FILE_NONE;
422
        return BACKING_STORE_OK;
E
Eric Blake 已提交
423
    }
424

425
    if (VIR_STRNDUP(*res, (const char*)buf + 4 + 4, COW_FILENAME_MAXLEN) < 0)
426 427 428 429
        return BACKING_STORE_ERROR;
    return BACKING_STORE_OK;
}

430 431 432

static int
qcow2GetBackingStoreFormat(int *format,
E
Eric Blake 已提交
433
                           const char *buf,
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
                           size_t buf_size,
                           size_t extension_start,
                           size_t extension_end)
{
    size_t offset = extension_start;

    /*
     * The extensions take format of
     *
     * int32: magic
     * int32: length
     * byte[length]: payload
     *
     * Unknown extensions can be ignored by skipping
     * over "length" bytes in the data stream.
     */
    while (offset < (buf_size-8) &&
           offset < (extension_end-8)) {
E
Eric Blake 已提交
452 453
        unsigned int magic = virReadBufInt32BE(buf + offset);
        unsigned int len = virReadBufInt32BE(buf + offset + 4);
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469

        offset += 8;

        if ((offset + len) < offset)
            break;

        if ((offset + len) > buf_size)
            break;

        switch (magic) {
        case QCOW2_HDR_EXTENSION_END:
            goto done;

        case QCOW2_HDR_EXTENSION_BACKING_FORMAT:
            if (buf[offset+len] != '\0')
                break;
470
            *format = virStorageFileFormatTypeFromString(buf+offset);
E
Eric Blake 已提交
471 472
            if (*format <= VIR_STORAGE_FILE_NONE)
                return -1;
473 474 475 476 477
        }

        offset += len;
    }

478
 done:
479 480 481 482 483

    return 0;
}


484
static int
485
qcowXGetBackingStore(char **res,
486
                     int *format,
E
Eric Blake 已提交
487
                     const char *buf,
488 489
                     size_t buf_size,
                     bool isQCow2)
490 491
{
    unsigned long long offset;
492
    unsigned int size;
493 494
    unsigned long long start;
    int version;
495 496

    *res = NULL;
497 498 499 500
    if (format)
        *format = VIR_STORAGE_FILE_AUTO;

    if (buf_size < QCOWX_HDR_BACKING_FILE_OFFSET+8+4)
501
        return BACKING_STORE_INVALID;
E
Eric Blake 已提交
502
    offset = virReadBufInt64BE(buf + QCOWX_HDR_BACKING_FILE_OFFSET);
503 504
    if (offset > buf_size)
        return BACKING_STORE_INVALID;
505 506 507 508 509 510 511

    if (offset == 0) {
        if (format)
            *format = VIR_STORAGE_FILE_NONE;
        return BACKING_STORE_OK;
    }

E
Eric Blake 已提交
512
    size = virReadBufInt32BE(buf + QCOWX_HDR_BACKING_FILE_SIZE);
E
Eric Blake 已提交
513 514 515
    if (size == 0) {
        if (format)
            *format = VIR_STORAGE_FILE_NONE;
516
        return BACKING_STORE_OK;
E
Eric Blake 已提交
517
    }
518
    if (size > 1023)
519
        return BACKING_STORE_INVALID;
520
    if (offset + size > buf_size || offset + size < offset)
521
        return BACKING_STORE_INVALID;
522
    if (VIR_ALLOC_N(*res, size + 1) < 0)
523 524 525
        return BACKING_STORE_ERROR;
    memcpy(*res, buf + offset, size);
    (*res)[size] = '\0';
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549

    /*
     * Traditionally QCow2 files had a layout of
     *
     * [header]
     * [backingStoreName]
     *
     * Although the backingStoreName typically followed
     * the header immediately, this was not required by
     * the format. By specifying a higher byte offset for
     * the backing file offset in the header, it was
     * possible to leave space between the header and
     * start of backingStore.
     *
     * This hack is now used to store extensions to the
     * qcow2 format:
     *
     * [header]
     * [extensions]
     * [backingStoreName]
     *
     * Thus the file region to search for extensions is
     * between the end of the header (QCOW2_HDR_TOTAL_SIZE)
     * and the start of the backingStoreName (offset)
550 551 552
     *
     * for qcow2 v3 images, the length of the header
     * is stored at QCOW2v3_HDR_SIZE
553
     */
554 555 556 557 558 559 560 561 562 563
    if (isQCow2 && format) {
        version = virReadBufInt32BE(buf + QCOWX_HDR_VERSION);
        if (version == 2)
            start = QCOW2_HDR_TOTAL_SIZE;
        else
            start = virReadBufInt32BE(buf + QCOW2v3_HDR_SIZE);
        if (qcow2GetBackingStoreFormat(format, buf, buf_size,
                                       start, offset) < 0)
            return BACKING_STORE_INVALID;
    }
564

565 566 567 568
    return BACKING_STORE_OK;
}


569 570 571
static int
qcow1GetBackingStore(char **res,
                     int *format,
E
Eric Blake 已提交
572
                     const char *buf,
573 574
                     size_t buf_size)
{
E
Eric Blake 已提交
575 576
    int ret;

577 578 579
    /* QCow1 doesn't have the extensions capability
     * used to store backing format */
    *format = VIR_STORAGE_FILE_AUTO;
E
Eric Blake 已提交
580 581 582 583
    ret = qcowXGetBackingStore(res, NULL, buf, buf_size, false);
    if (ret == 0 && *buf == '\0')
        *format = VIR_STORAGE_FILE_NONE;
    return ret;
584 585 586 587 588
}

static int
qcow2GetBackingStore(char **res,
                     int *format,
E
Eric Blake 已提交
589
                     const char *buf,
590 591 592 593 594 595
                     size_t buf_size)
{
    return qcowXGetBackingStore(res, format, buf, buf_size, true);
}


596
static int
597
vmdk4GetBackingStore(char **res,
598
                     int *format,
E
Eric Blake 已提交
599
                     const char *buf,
600 601 602
                     size_t buf_size)
{
    static const char prefix[] = "parentFileNameHint=\"";
603
    char *start, *end;
604
    size_t len;
605
    int ret = BACKING_STORE_ERROR;
606
    VIR_AUTOFREE(char *) desc = NULL;
607

608
    if (VIR_ALLOC_N(desc, VIR_STORAGE_MAX_HEADER) < 0)
609
        goto cleanup;
610 611

    *res = NULL;
612 613
    /*
     * Technically this should have been VMDK, since
J
Ján Tomko 已提交
614
     * VMDK spec / VMware impl only support VMDK backed
615 616 617 618 619
     * by VMDK. QEMU isn't following this though and
     * does probing on VMDK backing files, hence we set
     * AUTO
     */
    *format = VIR_STORAGE_FILE_AUTO;
620

621 622 623 624
    if (buf_size <= 0x200) {
        ret = BACKING_STORE_INVALID;
        goto cleanup;
    }
625
    len = buf_size - 0x200;
626 627
    if (len > VIR_STORAGE_MAX_HEADER)
        len = VIR_STORAGE_MAX_HEADER;
628 629 630
    memcpy(desc, buf + 0x200, len);
    desc[len] = '\0';
    start = strstr(desc, prefix);
631
    if (start == NULL) {
E
Eric Blake 已提交
632
        *format = VIR_STORAGE_FILE_NONE;
633 634 635
        ret = BACKING_STORE_OK;
        goto cleanup;
    }
636 637
    start += strlen(prefix);
    end = strchr(start, '"');
638 639 640 641 642
    if (end == NULL) {
        ret = BACKING_STORE_INVALID;
        goto cleanup;
    }
    if (end == start) {
E
Eric Blake 已提交
643
        *format = VIR_STORAGE_FILE_NONE;
644 645 646
        ret = BACKING_STORE_OK;
        goto cleanup;
    }
647
    *end = '\0';
648
    if (VIR_STRDUP(*res, start) < 0)
649 650 651 652
        goto cleanup;

    ret = BACKING_STORE_OK;

653
 cleanup:
654
    return ret;
655 656
}

657 658 659
static int
qedGetBackingStore(char **res,
                   int *format,
E
Eric Blake 已提交
660
                   const char *buf,
661 662 663 664 665 666 667 668 669
                   size_t buf_size)
{
    unsigned long long flags;
    unsigned long offset, size;

    *res = NULL;
    /* Check if this image has a backing file */
    if (buf_size < QED_HDR_FEATURES_OFFSET+8)
        return BACKING_STORE_INVALID;
E
Eric Blake 已提交
670
    flags = virReadBufInt64LE(buf + QED_HDR_FEATURES_OFFSET);
E
Eric Blake 已提交
671 672
    if (!(flags & QED_F_BACKING_FILE)) {
        *format = VIR_STORAGE_FILE_NONE;
673
        return BACKING_STORE_OK;
E
Eric Blake 已提交
674
    }
675 676 677 678

    /* Parse the backing file */
    if (buf_size < QED_HDR_BACKING_FILE_OFFSET+8)
        return BACKING_STORE_INVALID;
E
Eric Blake 已提交
679
    offset = virReadBufInt32LE(buf + QED_HDR_BACKING_FILE_OFFSET);
680 681
    if (offset > buf_size)
        return BACKING_STORE_INVALID;
E
Eric Blake 已提交
682
    size = virReadBufInt32LE(buf + QED_HDR_BACKING_FILE_SIZE);
683 684 685 686
    if (size == 0)
        return BACKING_STORE_OK;
    if (offset + size > buf_size || offset + size < offset)
        return BACKING_STORE_INVALID;
687
    if (VIR_ALLOC_N(*res, size + 1) < 0)
688 689 690 691
        return BACKING_STORE_ERROR;
    memcpy(*res, buf + offset, size);
    (*res)[size] = '\0';

E
Eric Blake 已提交
692 693 694 695
    if (flags & QED_F_BACKING_FORMAT_NO_PROBE)
        *format = VIR_STORAGE_FILE_RAW;
    else
        *format = VIR_STORAGE_FILE_AUTO_SAFE;
696 697 698 699

    return BACKING_STORE_OK;
}

700 701

static bool
702 703
virStorageFileMatchesMagic(int magicOffset,
                           const char *magic,
E
Eric Blake 已提交
704
                           char *buf,
705
                           size_t buflen)
706
{
707
    int mlen;
708

709
    if (magic == NULL)
710
        return false;
711

712
    /* Validate magic data */
713 714
    mlen = strlen(magic);
    if (magicOffset + mlen > buflen)
715
        return false;
716

717
    if (memcmp(buf + magicOffset, magic, mlen) != 0)
718 719 720 721 722 723 724
        return false;

    return true;
}


static bool
725
virStorageFileMatchesExtension(const char *extension,
726 727
                               const char *path)
{
728
    if (extension == NULL)
729 730
        return false;

731
    if (virStringHasCaseSuffix(path, extension))
732 733 734 735 736 737 738
        return true;

    return false;
}


static bool
739 740 741 742
virStorageFileMatchesVersion(int versionOffset,
                             int versionSize,
                             const int *versionNumbers,
                             int endian,
E
Eric Blake 已提交
743
                             char *buf,
744 745
                             size_t buflen)
{
746
    int version;
747
    size_t i;
748 749

    /* Validate version number info */
750
    if (versionOffset == -1)
E
Eric Blake 已提交
751
        return false;
752

753
    /* -2 == non-versioned file format, so trivially match */
754
    if (versionOffset == -2)
755 756
        return true;

757
    /* A positive versionOffset, requires using a valid versionSize */
758
    if (versionSize != 2 && versionSize != 4)
759 760
        return false;

761
    if ((versionOffset + versionSize) > buflen)
762 763
        return false;

764 765
    if (endian == LV_LITTLE_ENDIAN) {
        if (versionSize == 4)
766
            version = virReadBufInt32LE(buf +
767
                                        versionOffset);
768 769
        else
            version = virReadBufInt16LE(buf +
770
                                        versionOffset);
771
    } else {
772
        if (versionSize == 4)
773
            version = virReadBufInt32BE(buf +
774
                                        versionOffset);
775 776
        else
            version = virReadBufInt16BE(buf +
777
                                        versionOffset);
778
    }
779

780
    for (i = 0;
781
         i < FILE_TYPE_VERSIONS_LAST && versionNumbers[i];
782 783
         i++) {
        VIR_DEBUG("Compare detected version %d vs one of the expected versions %d",
784 785
                  version, versionNumbers[i]);
        if (version == versionNumbers[i])
786 787
            return true;
    }
788

789
    return false;
790
}
791

792 793
bool
virStorageIsFile(const char *backing)
A
Adam Litke 已提交
794
{
795 796 797 798 799 800 801 802
    char *colon;
    char *slash;

    if (!backing)
        return false;

    colon = strchr(backing, ':');
    slash = strchr(backing, '/');
803 804 805 806 807

    /* Reject anything that looks like a protocol (such as nbd: or
     * rbd:); if someone really does want a relative file name that
     * includes ':', they can always prefix './'.  */
    if (colon && (!slash || colon < slash))
A
Adam Litke 已提交
808 809 810
        return false;
    return true;
}
811

E
Eric Blake 已提交
812

813
bool
814 815 816 817 818 819 820 821 822 823 824 825
virStorageIsRelative(const char *backing)
{
    if (backing[0] == '/')
        return false;

    if (!virStorageIsFile(backing))
        return false;

    return true;
}


826
static int
E
Eric Blake 已提交
827
virStorageFileProbeFormatFromBuf(const char *path,
E
Eric Blake 已提交
828
                                 char *buf,
E
Eric Blake 已提交
829 830 831
                                 size_t buflen)
{
    int format = VIR_STORAGE_FILE_RAW;
832
    size_t i;
E
Eric Blake 已提交
833
    int possibleFormat = VIR_STORAGE_FILE_RAW;
834
    VIR_DEBUG("path=%s, buf=%p, buflen=%zu", path, buf, buflen);
E
Eric Blake 已提交
835 836

    /* First check file magic */
837
    for (i = 0; i < VIR_STORAGE_FILE_LAST; i++) {
838 839 840 841 842 843 844 845
        if (virStorageFileMatchesMagic(fileTypeInfo[i].magicOffset,
                                       fileTypeInfo[i].magic,
                                       buf, buflen)) {
            if (!virStorageFileMatchesVersion(fileTypeInfo[i].versionOffset,
                                              fileTypeInfo[i].versionSize,
                                              fileTypeInfo[i].versionNumbers,
                                              fileTypeInfo[i].endian,
                                              buf, buflen)) {
E
Eric Blake 已提交
846 847 848 849 850 851 852 853 854 855 856 857 858 859
                possibleFormat = i;
                continue;
            }
            format = i;
            goto cleanup;
        }
    }

    if (possibleFormat != VIR_STORAGE_FILE_RAW)
        VIR_WARN("File %s matches %s magic, but version is wrong. "
                 "Please report new version to libvir-list@redhat.com",
                 path, virStorageFileFormatTypeToString(possibleFormat));

    /* No magic, so check file extension */
860
    for (i = 0; i < VIR_STORAGE_FILE_LAST; i++) {
861
        if (virStorageFileMatchesExtension(fileTypeInfo[i].extension, path)) {
E
Eric Blake 已提交
862 863 864 865 866
            format = i;
            goto cleanup;
        }
    }

867
 cleanup:
E
Eric Blake 已提交
868 869 870 871 872
    VIR_DEBUG("format=%d", format);
    return format;
}


873 874 875
static int
qcow2GetFeatures(virBitmapPtr *features,
                 int format,
E
Eric Blake 已提交
876
                 char *buf,
877 878 879 880 881
                 ssize_t len)
{
    int version = -1;
    virBitmapPtr feat = NULL;
    uint64_t bits;
882
    size_t i;
883 884 885 886 887 888 889 890 891

    version = virReadBufInt32BE(buf + fileTypeInfo[format].versionOffset);

    if (version == 2)
        return 0;

    if (len < QCOW2v3_HDR_SIZE)
        return -1;

892
    if (!(feat = virBitmapNew(VIR_STORAGE_FILE_FEATURE_LAST)))
893 894 895 896 897 898 899 900 901 902 903 904 905 906
        return -1;

    /* todo: check for incompatible or autoclear features? */
    bits = virReadBufInt64BE(buf + QCOW2v3_HDR_FEATURES_COMPATIBLE);
    for (i = 0; i < QCOW2_COMPATIBLE_FEATURE_LAST; i++) {
        if (bits & ((uint64_t) 1 << i))
            ignore_value(virBitmapSetBit(feat, qcow2CompatibleFeatureArray[i]));
    }

    *features = feat;
    return 0;
}


907 908 909 910 911 912
static bool
virStorageFileHasEncryptionFormat(const struct FileEncryptionInfo *info,
                                  char *buf,
                                  size_t len)
{
    if (!info->magic && info->modeOffset == -1)
913
        return false; /* Shouldn't happen - expect at least one */
914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930

    if (info->magic) {
        if (!virStorageFileMatchesMagic(info->magicOffset,
                                        info->magic,
                                        buf, len))
            return false;

        if (info->versionOffset != -1 &&
            !virStorageFileMatchesVersion(info->versionOffset,
                                          info->versionSize,
                                          info->versionNumbers,
                                          info->endian,
                                          buf, len))
            return false;

        return true;
    } else if (info->modeOffset != -1) {
931 932
        int crypt_format;

933 934 935
        if (info->modeOffset >= len)
            return false;

936 937
        crypt_format = virReadBufInt32BE(buf + info->modeOffset);
        if (crypt_format != info->modeValue)
938 939 940 941 942 943 944 945 946
            return false;

        return true;
    } else {
        return false;
    }
}


947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963
static int
virStorageFileGetEncryptionPayloadOffset(const struct FileEncryptionInfo *info,
                                         char *buf)
{
    int payload_offset = -1;

    if (info->payloadOffset != -1) {
        if (info->endian == LV_LITTLE_ENDIAN)
            payload_offset = virReadBufInt32LE(buf + info->payloadOffset);
        else
            payload_offset = virReadBufInt32BE(buf + info->payloadOffset);
    }

    return payload_offset;
}


964 965 966 967 968
/* Given a header in BUF with length LEN, as parsed from the storage file
 * assuming it has the given FORMAT, populate information into META
 * with information about the file and its backing store. Return format
 * of the backing store as BACKING_FORMAT. PATH and FORMAT have to be
 * pre-populated in META */
969
int
970
virStorageFileGetMetadataInternal(virStorageSourcePtr meta,
971 972
                                  char *buf,
                                  size_t len,
973
                                  int *backingFormat)
974
{
975
    int dummy;
976
    int ret = -1;
977
    size_t i;
E
Eric Blake 已提交
978

979 980 981
    if (!backingFormat)
        backingFormat = &dummy;

982 983
    VIR_DEBUG("path=%s, buf=%p, len=%zu, meta->format=%d",
              meta->path, buf, len, meta->format);
E
Eric Blake 已提交
984

985
    if (meta->format == VIR_STORAGE_FILE_AUTO)
986
        meta->format = virStorageFileProbeFormatFromBuf(meta->path, buf, len);
987

988 989 990 991
    if (meta->format <= VIR_STORAGE_FILE_NONE ||
        meta->format >= VIR_STORAGE_FILE_LAST) {
        virReportSystemError(EINVAL, _("unknown storage file meta->format %d"),
                             meta->format);
E
Eric Blake 已提交
992 993
        goto cleanup;
    }
994

995 996 997 998
    if (fileTypeInfo[meta->format].cryptInfo != NULL) {
        for (i = 0; fileTypeInfo[meta->format].cryptInfo[i].format != 0; i++) {
            if (virStorageFileHasEncryptionFormat(&fileTypeInfo[meta->format].cryptInfo[i],
                                                  buf, len)) {
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
                int expt_fmt = fileTypeInfo[meta->format].cryptInfo[i].format;
                if (!meta->encryption) {
                    if (VIR_ALLOC(meta->encryption) < 0)
                        goto cleanup;

                    meta->encryption->format = expt_fmt;
                } else {
                    if (meta->encryption->format != expt_fmt) {
                        virReportError(VIR_ERR_XML_ERROR,
                                       _("encryption format %d doesn't match "
                                         "expected format %d"),
                                       meta->encryption->format, expt_fmt);
                        goto cleanup;
                    }
                }
1014 1015
                meta->encryption->payload_offset =
                    virStorageFileGetEncryptionPayloadOffset(&fileTypeInfo[meta->format].cryptInfo[i], buf);
1016 1017 1018 1019
            }
        }
    }

1020 1021 1022
    /* XXX we should consider moving virStorageBackendUpdateVolInfo
     * code into this method, for non-magic files
     */
1023
    if (!fileTypeInfo[meta->format].magic)
E
Eric Blake 已提交
1024
        goto done;
1025

1026
    /* Optionally extract capacity from file */
1027 1028
    if (fileTypeInfo[meta->format].sizeOffset != -1) {
        if ((fileTypeInfo[meta->format].sizeOffset + 8) > len)
E
Eric Blake 已提交
1029
            goto done;
1030

1031
        if (fileTypeInfo[meta->format].endian == LV_LITTLE_ENDIAN)
E
Eric Blake 已提交
1032
            meta->capacity = virReadBufInt64LE(buf +
1033
                                               fileTypeInfo[meta->format].sizeOffset);
E
Eric Blake 已提交
1034 1035
        else
            meta->capacity = virReadBufInt64BE(buf +
1036
                                               fileTypeInfo[meta->format].sizeOffset);
1037
        /* Avoid unlikely, but theoretically possible overflow */
E
Eric Blake 已提交
1038
        if (meta->capacity > (ULLONG_MAX /
1039
                              fileTypeInfo[meta->format].sizeMultiplier))
E
Eric Blake 已提交
1040
            goto done;
1041
        meta->capacity *= fileTypeInfo[meta->format].sizeMultiplier;
1042
    }
1043

1044
    VIR_FREE(meta->backingStoreRaw);
1045 1046
    if (fileTypeInfo[meta->format].getBackingStore != NULL) {
        int store = fileTypeInfo[meta->format].getBackingStore(&meta->backingStoreRaw,
1047 1048
                                                               backingFormat,
                                                               buf, len);
E
Eric Blake 已提交
1049 1050
        if (store == BACKING_STORE_INVALID)
            goto done;
1051

E
Eric Blake 已提交
1052 1053
        if (store == BACKING_STORE_ERROR)
            goto cleanup;
1054 1055
    }

1056 1057
    if (fileTypeInfo[meta->format].getFeatures != NULL &&
        fileTypeInfo[meta->format].getFeatures(&meta->features, meta->format, buf, len) < 0)
1058 1059
        goto cleanup;

1060
    if (meta->format == VIR_STORAGE_FILE_QCOW2 && meta->features &&
1061 1062 1063
        VIR_STRDUP(meta->compat, "1.1") < 0)
        goto cleanup;

1064
 done:
1065
    ret = 0;
E
Eric Blake 已提交
1066

1067
 cleanup:
E
Eric Blake 已提交
1068
    return ret;
1069 1070 1071 1072
}


/**
1073
 * virStorageFileProbeFormat:
1074
 *
1075 1076
 * Probe for the format of 'path', returning the detected
 * disk format.
1077 1078 1079
 *
 * Callers are advised never to trust the returned 'format'
 * unless it is listed as VIR_STORAGE_FILE_RAW, since a
1080
 * malicious guest can turn a raw file into any other non-raw
1081 1082 1083 1084 1085
 * format at will.
 *
 * Best option: Don't use this function
 */
int
1086
virStorageFileProbeFormat(const char *path, uid_t uid, gid_t gid)
1087
{
1088
    struct stat sb;
1089
    ssize_t len = VIR_STORAGE_MAX_HEADER;
J
John Ferlan 已提交
1090
    VIR_AUTOCLOSE fd = -1;
1091
    VIR_AUTOFREE(char *) header = NULL;
1092

1093 1094
    if ((fd = virFileOpenAs(path, O_RDONLY, 0, uid, gid, 0)) < 0) {
        virReportSystemError(-fd, _("Failed to open file '%s'"), path);
1095 1096 1097
        return -1;
    }

1098 1099
    if (fstat(fd, &sb) < 0) {
        virReportSystemError(errno, _("cannot stat file '%s'"), path);
J
John Ferlan 已提交
1100
        return -1;
1101 1102
    }

1103
    /* No header to probe for directories */
J
John Ferlan 已提交
1104 1105
    if (S_ISDIR(sb.st_mode))
        return VIR_STORAGE_FILE_DIR;
1106 1107 1108

    if (lseek(fd, 0, SEEK_SET) == (off_t)-1) {
        virReportSystemError(errno, _("cannot set to start of '%s'"), path);
J
John Ferlan 已提交
1109
        return -1;
1110 1111
    }

1112
    if ((len = virFileReadHeaderFD(fd, len, &header)) < 0) {
1113
        virReportSystemError(errno, _("cannot read header '%s'"), path);
J
John Ferlan 已提交
1114
        return -1;
1115 1116
    }

J
John Ferlan 已提交
1117
    return virStorageFileProbeFormatFromBuf(path, header, len);
1118 1119
}

1120

1121
static virStorageSourcePtr
1122 1123 1124
virStorageFileMetadataNew(const char *path,
                          int format)
{
1125 1126
    VIR_AUTOUNREF(virStorageSourcePtr) def = NULL;
    virStorageSourcePtr ret = NULL;
1127

1128
    if (!(def = virStorageSourceNew()))
1129 1130
        return NULL;

1131 1132
    def->format = format;
    def->type = VIR_STORAGE_TYPE_FILE;
1133

1134
    if (VIR_STRDUP(def->path, path) < 0)
1135
        return NULL;
1136

1137 1138
    VIR_STEAL_PTR(ret, def);
    return ret;
1139 1140 1141
}


1142 1143 1144 1145 1146
/**
 * virStorageFileGetMetadataFromBuf:
 * @path: name of file, for error messages
 * @buf: header bytes from @path
 * @len: length of @buf
1147
 * @format: format of the storage file
1148
 * @backingFormat: format of @backing
1149
 *
1150 1151 1152
 * Extract metadata about the storage volume with the specified image format.
 * If image format is VIR_STORAGE_FILE_AUTO, it will probe to automatically
 * identify the format.  Does not recurse.
1153
 *
1154 1155 1156 1157 1158 1159 1160
 * Callers are advised never to use VIR_STORAGE_FILE_AUTO as a format on a file
 * that might be raw if that file will then be passed to a guest, since a
 * malicious guest can turn a raw file into any other non-raw format at will.
 *
 * If the returned @backingFormat is VIR_STORAGE_FILE_AUTO it indicates the
 * image didn't specify an explicit format for its backing store. Callers are
 * advised against probing for the backing store format in this case.
1161
 *
1162
 * Caller MUST free the result after use via virObjectUnref.
1163
 */
1164
virStorageSourcePtr
1165 1166 1167
virStorageFileGetMetadataFromBuf(const char *path,
                                 char *buf,
                                 size_t len,
1168
                                 int format,
1169
                                 int *backingFormat)
1170
{
1171
    virStorageSourcePtr ret = NULL;
1172 1173 1174 1175
    int dummy;

    if (!backingFormat)
        backingFormat = &dummy;
1176

1177
    if (!(ret = virStorageFileMetadataNew(path, format)))
1178
        return NULL;
1179

1180 1181
    if (virStorageFileGetMetadataInternal(ret, buf, len,
                                          backingFormat) < 0) {
1182
        virObjectUnref(ret);
1183 1184
        return NULL;
    }
1185

1186
    return ret;
1187 1188 1189
}


1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
/**
 * virStorageFileGetMetadataFromFD:
 *
 * Extract metadata about the storage volume with the specified
 * image format. If image format is VIR_STORAGE_FILE_AUTO, it
 * will probe to automatically identify the format.  Does not recurse.
 *
 * Callers are advised never to use VIR_STORAGE_FILE_AUTO as a
 * format, since a malicious guest can turn a raw file into any
 * other non-raw format at will.
 *
1201
 * Caller MUST free the result after use via virObjectUnref.
1202 1203 1204 1205 1206 1207 1208
 */
virStorageSourcePtr
virStorageFileGetMetadataFromFD(const char *path,
                                int fd,
                                int format,
                                int *backingFormat)

1209
{
1210
    virStorageSourcePtr ret = NULL;
1211
    ssize_t len = VIR_STORAGE_MAX_HEADER;
1212
    struct stat sb;
1213
    int dummy;
1214
    VIR_AUTOFREE(char *) buf = NULL;
1215
    VIR_AUTOUNREF(virStorageSourcePtr) meta = NULL;
1216

1217 1218
    if (!backingFormat)
        backingFormat = &dummy;
1219

1220
    *backingFormat = VIR_STORAGE_FILE_NONE;
1221

1222 1223
    if (fstat(fd, &sb) < 0) {
        virReportSystemError(errno,
1224 1225
                             _("cannot stat file '%s'"), path);
        return NULL;
1226 1227
    }

1228 1229 1230
    if (!(meta = virStorageFileMetadataNew(path, format)))
        return NULL;

1231
    if (S_ISDIR(sb.st_mode)) {
1232 1233
        /* No header to probe for directories, but also no backing file. Just
         * update the metadata.*/
1234 1235
        meta->type = VIR_STORAGE_TYPE_DIR;
        meta->format = VIR_STORAGE_FILE_DIR;
1236
        VIR_STEAL_PTR(ret, meta);
1237
        return ret;
1238 1239 1240
    }

    if (lseek(fd, 0, SEEK_SET) == (off_t)-1) {
1241
        virReportSystemError(errno, _("cannot seek to start of '%s'"), meta->path);
1242
        return NULL;
1243 1244 1245
    }

    if ((len = virFileReadHeaderFD(fd, len, &buf)) < 0) {
1246
        virReportSystemError(errno, _("cannot read header '%s'"), meta->path);
1247
        return NULL;
1248 1249
    }

1250
    if (virStorageFileGetMetadataInternal(meta, buf, len, backingFormat) < 0)
1251
        return NULL;
1252

1253 1254 1255 1256
    if (S_ISREG(sb.st_mode))
        meta->type = VIR_STORAGE_TYPE_FILE;
    else if (S_ISBLK(sb.st_mode))
        meta->type = VIR_STORAGE_TYPE_BLOCK;
1257

1258
    VIR_STEAL_PTR(ret, meta);
1259
    return ret;
1260 1261
}

1262

1263 1264 1265 1266 1267
/**
 * virStorageFileChainCheckBroken
 *
 * If CHAIN is broken, set *brokenFile to the broken file name,
 * otherwise set it to NULL. Caller MUST free *brokenFile after use.
1268 1269
 * Return 0 on success (including when brokenFile is set), negative on
 * error (allocation failure).
1270 1271
 */
int
1272
virStorageFileChainGetBroken(virStorageSourcePtr chain,
1273 1274
                             char **brokenFile)
{
1275
    virStorageSourcePtr tmp;
1276

1277 1278
    *brokenFile = NULL;

1279 1280 1281
    if (!chain)
        return 0;

1282
    for (tmp = chain; virStorageSourceIsBacking(tmp); tmp = tmp->backingStore) {
1283 1284
        /* Break when we hit end of chain; report error if we detected
         * a missing backing file, infinite loop, or other error */
1285
        if (!tmp->backingStore && tmp->backingStoreRaw) {
1286 1287
            if (VIR_STRDUP(*brokenFile, tmp->backingStoreRaw) < 0)
                return -1;
1288

1289 1290 1291
           return 0;
        }
    }
1292

1293
    return 0;
1294 1295 1296
}


1297 1298 1299 1300 1301 1302
/**
 * virStorageFileResize:
 *
 * Change the capacity of the raw storage file at 'path'.
 */
int
1303 1304 1305
virStorageFileResize(const char *path,
                     unsigned long long capacity,
                     bool pre_allocate)
1306
{
1307
    int rc;
J
John Ferlan 已提交
1308
    VIR_AUTOCLOSE fd = -1;
1309 1310 1311

    if ((fd = open(path, O_RDWR)) < 0) {
        virReportSystemError(errno, _("Unable to open '%s'"), path);
J
John Ferlan 已提交
1312
        return -1;
1313 1314
    }

1315
    if (pre_allocate) {
1316
        if ((rc = virFileAllocate(fd, 0, capacity)) != 0) {
1317 1318 1319 1320 1321 1322 1323 1324
            if (rc == -2) {
                virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
                               _("preallocate is not supported on this platform"));
            } else {
                virReportSystemError(errno,
                                     _("Failed to pre-allocate space for "
                                       "file '%s'"), path);
            }
J
John Ferlan 已提交
1325
            return -1;
1326
        }
1327 1328 1329 1330 1331
    }

    if (ftruncate(fd, capacity) < 0) {
        virReportSystemError(errno,
                             _("Failed to truncate file '%s'"), path);
J
John Ferlan 已提交
1332
        return -1;
1333 1334
    }

1335 1336
    if (VIR_CLOSE(fd) < 0) {
        virReportSystemError(errno, _("Unable to save '%s'"), path);
J
John Ferlan 已提交
1337
        return -1;
1338 1339
    }

J
John Ferlan 已提交
1340
    return 0;
1341 1342
}

1343 1344 1345 1346 1347 1348

int virStorageFileIsClusterFS(const char *path)
{
    /* These are coherent cluster filesystems known to be safe for
     * migration with cache != none
     */
1349 1350
    return virFileIsSharedFSType(path,
                                 VIR_FILE_SHFS_GFS2 |
1351 1352
                                 VIR_FILE_SHFS_OCFS |
                                 VIR_FILE_SHFS_CEPH);
1353
}
1354 1355

#ifdef LVS
1356 1357
int virStorageFileGetLVMKey(const char *path,
                            char **key)
1358 1359 1360 1361 1362
{
    /*
     *  # lvs --noheadings --unbuffered --nosuffix --options "uuid" LVNAME
     *    06UgP5-2rhb-w3Bo-3mdR-WeoL-pytO-SAa2ky
     */
1363 1364
    int status;
    int ret = -1;
1365
    VIR_AUTOPTR(virCommand) cmd = NULL;
1366

1367 1368 1369 1370 1371
    cmd = virCommandNewArgList(LVS, "--noheadings",
                               "--unbuffered", "--nosuffix",
                               "--options", "uuid", path,
                               NULL
                               );
1372
    *key = NULL;
1373 1374

    /* Run the program and capture its output */
1375 1376
    virCommandSetOutputBuffer(cmd, key);
    if (virCommandRun(cmd, &status) < 0)
1377 1378
        goto cleanup;

1379 1380 1381 1382 1383 1384
    /* Explicitly check status == 0, rather than passing NULL
     * to virCommandRun because we don't want to raise an actual
     * error in this scenario, just return a NULL key.
     */

    if (status == 0 && *key) {
1385
        char *nl;
1386
        char *tmp = *key;
1387 1388

        /* Find first non-space character */
1389
        while (*tmp && c_isspace(*tmp))
1390 1391
            tmp++;
        /* Kill leading spaces */
1392 1393
        if (tmp != *key)
            memmove(*key, tmp, strlen(tmp)+1);
1394 1395

        /* Kill trailing newline */
1396
        if ((nl = strchr(*key, '\n')))
1397 1398 1399
            *nl = '\0';
    }

1400
    ret = 0;
1401

1402
 cleanup:
1403 1404 1405 1406
    if (*key && STREQ(*key, ""))
        VIR_FREE(*key);

    return ret;
1407 1408
}
#else
1409 1410
int virStorageFileGetLVMKey(const char *path,
                            char **key ATTRIBUTE_UNUSED)
1411 1412
{
    virReportSystemError(ENOSYS, _("Unable to get LVM key for %s"), path);
1413
    return -1;
1414 1415 1416
}
#endif

1417
#ifdef WITH_UDEV
1418 1419 1420
/* virStorageFileGetSCSIKey
 * @path: Path to the SCSI device
 * @key: Unique key to be returned
1421
 * @ignoreError: Used to not report ENOSYS
1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433
 *
 * Using a udev specific function, query the @path to get and return a
 * unique @key for the caller to use.
 *
 * Returns:
 *     0 On success, with the @key filled in or @key=NULL if the
 *       returned string was empty.
 *    -1 When WITH_UDEV is undefined and a system error is reported
 *    -2 When WITH_UDEV is defined, but calling virCommandRun fails
 */
int
virStorageFileGetSCSIKey(const char *path,
1434 1435
                         char **key,
                         bool ignoreError ATTRIBUTE_UNUSED)
1436
{
1437
    int status;
1438 1439 1440 1441 1442 1443 1444 1445
    VIR_AUTOPTR(virCommand) cmd = NULL;

    cmd = virCommandNewArgList("/lib/udev/scsi_id",
                               "--replace-whitespace",
                               "--whitelisted",
                               "--device", path,
                               NULL
                               );
1446
    *key = NULL;
1447 1448

    /* Run the program and capture its output */
1449 1450
    virCommandSetOutputBuffer(cmd, key);
    if (virCommandRun(cmd, &status) < 0)
1451
        return -2;
1452

1453 1454 1455 1456 1457 1458
    /* Explicitly check status == 0, rather than passing NULL
     * to virCommandRun because we don't want to raise an actual
     * error in this scenario, just return a NULL key.
     */
    if (status == 0 && *key) {
        char *nl = strchr(*key, '\n');
1459 1460 1461 1462
        if (nl)
            *nl = '\0';
    }

1463 1464 1465
    if (*key && STREQ(*key, ""))
        VIR_FREE(*key);

1466
    return 0;
1467 1468
}
#else
1469
int virStorageFileGetSCSIKey(const char *path,
1470 1471
                             char **key ATTRIBUTE_UNUSED,
                             bool ignoreError)
1472
{
1473 1474
    if (!ignoreError)
        virReportSystemError(ENOSYS, _("Unable to get SCSI key for %s"), path);
1475
    return -1;
1476 1477
}
#endif
1478

1479

1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504
#ifdef WITH_UDEV
/* virStorageFileGetNPIVKey
 * @path: Path to the NPIV device
 * @key: Unique key to be returned
 *
 * Using a udev specific function, query the @path to get and return a
 * unique @key for the caller to use. Unlike the GetSCSIKey method, an
 * NPIV LUN is uniquely identified by its ID_TARGET_PORT value.
 *
 * Returns:
 *     0 On success, with the @key filled in or @key=NULL if the
 *       returned output string didn't have the data we need to
 *       formulate a unique key value
 *    -1 When WITH_UDEV is undefined and a system error is reported
 *    -2 When WITH_UDEV is defined, but calling virCommandRun fails
 */
# define ID_SERIAL "ID_SERIAL="
# define ID_TARGET_PORT "ID_TARGET_PORT="
int
virStorageFileGetNPIVKey(const char *path,
                         char **key)
{
    int status;
    const char *serial;
    const char *port;
1505 1506 1507 1508 1509 1510 1511 1512 1513 1514
    VIR_AUTOFREE(char *) outbuf = NULL;
    VIR_AUTOPTR(virCommand) cmd = NULL;

    cmd = virCommandNewArgList("/lib/udev/scsi_id",
                               "--replace-whitespace",
                               "--whitelisted",
                               "--export",
                               "--device", path,
                               NULL
                               );
1515 1516 1517 1518 1519
    *key = NULL;

    /* Run the program and capture its output */
    virCommandSetOutputBuffer(cmd, &outbuf);
    if (virCommandRun(cmd, &status) < 0)
1520
        return -2;
1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543

    /* Explicitly check status == 0, rather than passing NULL
     * to virCommandRun because we don't want to raise an actual
     * error in this scenario, just return a NULL key.
     */
    if (status == 0 && *outbuf &&
        (serial = strstr(outbuf, ID_SERIAL)) &&
        (port = strstr(outbuf, ID_TARGET_PORT))) {
        char *tmp;

        serial += strlen(ID_SERIAL);
        port += strlen(ID_TARGET_PORT);

        if ((tmp = strchr(serial, '\n')))
            *tmp = '\0';

        if ((tmp = strchr(port, '\n')))
            *tmp = '\0';

        if (*serial != '\0' && *port != '\0')
            ignore_value(virAsprintf(key, "%s_PORT%s", serial, port));
    }

1544
    return 0;
1545 1546
}
#else
1547
int virStorageFileGetNPIVKey(const char *path ATTRIBUTE_UNUSED,
1548 1549 1550 1551 1552 1553
                             char **key ATTRIBUTE_UNUSED)
{
    return -1;
}
#endif

1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573
/**
 * virStorageFileParseBackingStoreStr:
 * @str: backing store specifier string to parse
 * @target: returns target device portion of the string
 * @chainIndex: returns the backing store portion of the string
 *
 * Parses the backing store specifier string such as vda[1], or sda into
 * components and returns them via arguments. If the string did not specify an
 * index, 0 is assumed.
 *
 * Returns 0 on success -1 on error
 */
int
virStorageFileParseBackingStoreStr(const char *str,
                                   char **target,
                                   unsigned int *chainIndex)
{
    size_t nstrings;
    unsigned int idx = 0;
    char *suffix;
1574
    VIR_AUTOSTRINGLIST strings = NULL;
1575 1576 1577 1578 1579 1580 1581 1582 1583

    *chainIndex = 0;

    if (!(strings = virStringSplitCount(str, "[", 2, &nstrings)))
        return -1;

    if (nstrings == 2) {
        if (virStrToLong_uip(strings[1], &suffix, 10, &idx) < 0 ||
            STRNEQ(suffix, "]"))
1584
            return -1;
1585 1586 1587 1588
    }

    if (target &&
        VIR_STRDUP(*target, strings[0]) < 0)
1589
        return -1;
1590 1591

    *chainIndex = idx;
1592
    return 0;
1593 1594 1595
}


1596 1597 1598 1599 1600 1601
int
virStorageFileParseChainIndex(const char *diskTarget,
                              const char *name,
                              unsigned int *chainIndex)
{
    unsigned int idx = 0;
1602
    VIR_AUTOFREE(char *) target = NULL;
1603 1604 1605

    *chainIndex = 0;

1606 1607
    if (!name || !diskTarget)
        return 0;
1608

1609 1610
    if (virStorageFileParseBackingStoreStr(name, &target, &idx) < 0)
        return 0;
1611

1612
    if (idx == 0)
1613
        return 0;
1614

1615
    if (STRNEQ(diskTarget, target)) {
1616 1617
        virReportError(VIR_ERR_INVALID_ARG,
                       _("requested target '%s' does not match target '%s'"),
1618
                       target, diskTarget);
1619
        return -1;
1620 1621 1622 1623
    }

    *chainIndex = idx;

1624
    return 0;
1625 1626
}

1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637

/**
 * virStorageSourceIsBacking:
 * @src: storage source
 *
 * Returns true if @src is a eligible backing store structure. Useful
 * for iterators.
 */
bool
virStorageSourceIsBacking(const virStorageSource *src)
{
P
Peter Krempa 已提交
1638
    return src && src->type != VIR_STORAGE_TYPE_NONE;
1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649
}

/**
 * virStorageSourceHasBacking:
 * @src: storage source
 *
 * Returns true if @src has backing store/chain.
 */
bool
virStorageSourceHasBacking(const virStorageSource *src)
{
P
Peter Krempa 已提交
1650 1651
    return virStorageSourceIsBacking(src) && src->backingStore &&
           src->backingStore->type != VIR_STORAGE_TYPE_NONE;
1652 1653 1654
}


E
Eric Blake 已提交
1655 1656 1657 1658 1659 1660 1661 1662 1663 1664
/* Given a @chain, look for the backing store @name that is a backing file
 * of @startFrom (or any member of @chain if @startFrom is NULL) and return
 * that location within the chain.  @chain must always point to the top of
 * the chain.  Pass NULL for @name and 0 for @idx to find the base of the
 * chain.  Pass nonzero @idx to find the backing source according to its
 * position in the backing chain.  If @parent is not NULL, set *@parent to
 * the preferred name of the parent (or to NULL if @name matches the start
 * of the chain).  Since the results point within @chain, they must not be
 * independently freed. Reports an error and returns NULL if @name is not
 * found.
1665
 */
1666
virStorageSourcePtr
1667
virStorageFileChainLookup(virStorageSourcePtr chain,
1668
                          virStorageSourcePtr startFrom,
1669
                          const char *name,
1670
                          unsigned int idx,
1671
                          virStorageSourcePtr *parent)
1672
{
1673
    virStorageSourcePtr prev;
1674
    const char *start = chain->path;
1675
    char *parentDir = NULL;
E
Eric Blake 已提交
1676
    bool nameIsFile = virStorageIsFile(name);
1677 1678

    if (!parent)
1679
        parent = &prev;
1680
    *parent = NULL;
1681 1682

    if (startFrom) {
1683 1684
        while (virStorageSourceIsBacking(chain) &&
               chain != startFrom->backingStore)
1685
            chain = chain->backingStore;
1686

1687
        *parent = startFrom;
1688 1689
    }

1690
    while (virStorageSourceIsBacking(chain)) {
1691
        if (!name && !idx) {
1692
            if (!virStorageSourceHasBacking(chain))
1693
                break;
1694
        } else if (idx) {
1695 1696
            VIR_DEBUG("%u: %s", chain->id, chain->path);
            if (idx == chain->id)
1697
                break;
E
Eric Blake 已提交
1698
        } else {
1699
            if (STREQ_NULLABLE(name, chain->relPath) ||
1700
                STREQ_NULLABLE(name, chain->path))
1701
                break;
1702 1703

            if (nameIsFile && virStorageSourceIsLocalStorage(chain)) {
1704 1705
                if (*parent && virStorageSourceIsLocalStorage(*parent))
                    parentDir = mdir_name((*parent)->path);
1706 1707 1708 1709 1710 1711
                else
                    ignore_value(VIR_STRDUP_QUIET(parentDir, "."));

                if (!parentDir) {
                    virReportOOMError();
                    goto error;
1712 1713
                }

E
Eric Blake 已提交
1714
                int result = virFileRelLinkPointsTo(parentDir, name,
1715
                                                    chain->path);
1716 1717

                VIR_FREE(parentDir);
1718

E
Eric Blake 已提交
1719 1720
                if (result < 0)
                    goto error;
1721

E
Eric Blake 已提交
1722 1723 1724
                if (result > 0)
                    break;
            }
1725
        }
1726
        *parent = chain;
1727
        chain = chain->backingStore;
1728
    }
1729

1730
    if (!virStorageSourceIsBacking(chain))
1731
        goto error;
1732

1733
    return chain;
1734

1735
 error:
1736 1737
    if (idx) {
        virReportError(VIR_ERR_INVALID_ARG,
1738 1739
                       _("could not find backing store index %u in chain "
                         "for '%s'"),
1740
                       idx, NULLSTR(start));
1741
    } else if (name) {
E
Eric Blake 已提交
1742 1743 1744
        if (startFrom)
            virReportError(VIR_ERR_INVALID_ARG,
                           _("could not find image '%s' beneath '%s' in "
1745 1746
                             "chain for '%s'"), name, NULLSTR(startFrom->path),
                           NULLSTR(start));
E
Eric Blake 已提交
1747 1748 1749
        else
            virReportError(VIR_ERR_INVALID_ARG,
                           _("could not find image '%s' in chain for '%s'"),
1750
                           name, NULLSTR(start));
1751
    } else {
1752 1753
        virReportError(VIR_ERR_INVALID_ARG,
                       _("could not find base image in chain for '%s'"),
1754
                       NULLSTR(start));
1755
    }
1756 1757 1758
    *parent = NULL;
    return NULL;
}
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


void
virStorageNetHostDefClear(virStorageNetHostDefPtr def)
{
    if (!def)
        return;

    VIR_FREE(def->name);
    VIR_FREE(def->socket);
}


void
virStorageNetHostDefFree(size_t nhosts,
                         virStorageNetHostDefPtr hosts)
{
    size_t i;

    if (!hosts)
        return;

    for (i = 0; i < nhosts; i++)
        virStorageNetHostDefClear(&hosts[i]);

    VIR_FREE(hosts);
}


1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798
static void
virStoragePermsFree(virStoragePermsPtr def)
{
    if (!def)
        return;

    VIR_FREE(def->label);
    VIR_FREE(def);
}


1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813
virStorageNetHostDefPtr
virStorageNetHostDefCopy(size_t nhosts,
                         virStorageNetHostDefPtr hosts)
{
    virStorageNetHostDefPtr ret = NULL;
    size_t i;

    if (VIR_ALLOC_N(ret, nhosts) < 0)
        goto error;

    for (i = 0; i < nhosts; i++) {
        virStorageNetHostDefPtr src = &hosts[i];
        virStorageNetHostDefPtr dst = &ret[i];

        dst->transport = src->transport;
1814
        dst->port = src->port;
1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828

        if (VIR_STRDUP(dst->name, src->name) < 0)
            goto error;

        if (VIR_STRDUP(dst->socket, src->socket) < 0)
            goto error;
    }

    return ret;

 error:
    virStorageNetHostDefFree(nhosts, ret);
    return NULL;
}
1829 1830


1831 1832 1833 1834 1835 1836 1837 1838
void
virStorageAuthDefFree(virStorageAuthDefPtr authdef)
{
    if (!authdef)
        return;

    VIR_FREE(authdef->username);
    VIR_FREE(authdef->secrettype);
1839
    virSecretLookupDefClear(&authdef->seclookupdef);
1840 1841 1842 1843 1844 1845 1846
    VIR_FREE(authdef);
}


virStorageAuthDefPtr
virStorageAuthDefCopy(const virStorageAuthDef *src)
{
J
John Ferlan 已提交
1847
    virStorageAuthDefPtr ret = NULL;
1848
    VIR_AUTOPTR(virStorageAuthDef) authdef = NULL;
1849

J
John Ferlan 已提交
1850
    if (VIR_ALLOC(authdef) < 0)
1851 1852
        return NULL;

J
John Ferlan 已提交
1853
    if (VIR_STRDUP(authdef->username, src->username) < 0)
1854
        return NULL;
1855
    /* Not present for storage pool, but used for disk source */
J
John Ferlan 已提交
1856
    if (VIR_STRDUP(authdef->secrettype, src->secrettype) < 0)
1857
        return NULL;
J
John Ferlan 已提交
1858
    authdef->authType = src->authType;
1859

J
John Ferlan 已提交
1860
    if (virSecretLookupDefCopy(&authdef->seclookupdef, &src->seclookupdef) < 0)
1861
        return NULL;
1862

J
John Ferlan 已提交
1863
    VIR_STEAL_PTR(ret, authdef);
1864 1865 1866 1867
    return ret;
}


1868 1869 1870
virStorageAuthDefPtr
virStorageAuthDefParse(xmlNodePtr node,
                       xmlXPathContextPtr ctxt)
1871
{
1872
    xmlNodePtr saveNode = ctxt->node;
1873
    virStorageAuthDefPtr ret = NULL;
1874
    xmlNodePtr secretnode = NULL;
1875
    VIR_AUTOPTR(virStorageAuthDef) authdef = NULL;
1876
    VIR_AUTOFREE(char *) authtype = NULL;
1877

1878 1879
    ctxt->node = node;

1880
    if (VIR_ALLOC(authdef) < 0)
1881
        goto cleanup;
1882

1883
    if (!(authdef->username = virXPathString("string(./@username)", ctxt))) {
1884 1885
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing username for auth"));
1886
        goto cleanup;
1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897
    }

    authdef->authType = VIR_STORAGE_AUTH_TYPE_NONE;
    authtype = virXPathString("string(./@type)", ctxt);
    if (authtype) {
        /* Used by the storage pool instead of the secret type field
         * to define whether chap or ceph being used
         */
        if ((authdef->authType = virStorageAuthTypeFromString(authtype)) < 0) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("unknown auth type '%s'"), authtype);
1898
            goto cleanup;
1899 1900 1901
        }
    }

1902 1903 1904
    if (!(secretnode = virXPathNode("./secret ", ctxt))) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("Missing <secret> element in auth"));
1905
        goto cleanup;
1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917
    }

    /* Used by the domain disk xml parsing in order to ensure the
     * <secret type='%s' value matches the expected secret type for
     * the style of disk (iscsi is chap, nbd is ceph). For some reason
     * the virSecretUsageType{From|To}String() cannot be linked here
     * and because only the domain parsing code cares - just keep
     * it as a string.
     */
    authdef->secrettype = virXMLPropString(secretnode, "type");

    if (virSecretLookupParseSecret(secretnode, &authdef->seclookupdef) < 0)
1918
        goto cleanup;
1919

1920
    VIR_STEAL_PTR(ret, authdef);
1921

1922
 cleanup:
1923
    ctxt->node = saveNode;
1924 1925

    return ret;
1926 1927 1928
}


1929
void
1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941
virStorageAuthDefFormat(virBufferPtr buf,
                        virStorageAuthDefPtr authdef)
{
    if (authdef->authType == VIR_STORAGE_AUTH_TYPE_NONE) {
        virBufferEscapeString(buf, "<auth username='%s'>\n", authdef->username);
    } else {
        virBufferAsprintf(buf, "<auth type='%s' ",
                          virStorageAuthTypeToString(authdef->authType));
        virBufferEscapeString(buf, "username='%s'>\n", authdef->username);
    }

    virBufferAdjustIndent(buf, 2);
1942 1943
    virSecretLookupFormatSecret(buf, authdef->secrettype,
                                &authdef->seclookupdef);
1944 1945 1946 1947 1948
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</auth>\n");
}


1949 1950 1951 1952 1953 1954 1955
void
virStoragePRDefFree(virStoragePRDefPtr prd)
{
    if (!prd)
        return;

    VIR_FREE(prd->path);
1956
    VIR_FREE(prd->mgralias);
1957 1958 1959 1960 1961 1962 1963
    VIR_FREE(prd);
}


virStoragePRDefPtr
virStoragePRDefParseXML(xmlXPathContextPtr ctxt)
{
1964 1965
    virStoragePRDefPtr prd;
    virStoragePRDefPtr ret = NULL;
1966 1967 1968 1969
    VIR_AUTOFREE(char *) managed = NULL;
    VIR_AUTOFREE(char *) type = NULL;
    VIR_AUTOFREE(char *) path = NULL;
    VIR_AUTOFREE(char *) mode = NULL;
1970 1971 1972 1973

    if (VIR_ALLOC(prd) < 0)
        return NULL;

1974
    if (!(managed = virXPathString("string(./@managed)", ctxt))) {
1975
        virReportError(VIR_ERR_XML_ERROR, "%s",
1976
                       _("missing @managed attribute for <reservations/>"));
1977 1978 1979
        goto cleanup;
    }

1980
    if ((prd->managed = virTristateBoolTypeFromString(managed)) <= 0) {
1981
        virReportError(VIR_ERR_XML_ERROR,
1982
                       _("invalid value for 'managed': %s"), managed);
1983 1984 1985
        goto cleanup;
    }

1986 1987 1988
    type = virXPathString("string(./source[1]/@type)", ctxt);
    path = virXPathString("string(./source[1]/@path)", ctxt);
    mode = virXPathString("string(./source[1]/@mode)", ctxt);
1989

1990
    if (prd->managed == VIR_TRISTATE_BOOL_NO || type || path || mode) {
1991
        if (!type) {
1992
            virReportError(VIR_ERR_XML_ERROR, "%s",
1993
                           _("missing connection type for <reservations/>"));
1994 1995 1996
            goto cleanup;
        }

1997 1998 1999
        if (!path) {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("missing path for <reservations/>"));
2000 2001 2002
            goto cleanup;
        }

2003 2004 2005 2006 2007
        if (!mode) {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("missing connection mode for <reservations/>"));
            goto cleanup;
        }
2008
    }
2009

2010 2011 2012 2013 2014 2015
    if (type && STRNEQ(type, "unix")) {
        virReportError(VIR_ERR_XML_ERROR,
                       _("unsupported connection type for <reservations/>: %s"),
                       type);
        goto cleanup;
    }
2016

2017 2018 2019 2020 2021
    if (mode && STRNEQ(mode, "client")) {
        virReportError(VIR_ERR_XML_ERROR,
                       _("unsupported connection mode for <reservations/>: %s"),
                       mode);
        goto cleanup;
2022 2023
    }

2024
    VIR_STEAL_PTR(prd->path, path);
2025
    VIR_STEAL_PTR(ret, prd);
2026 2027 2028 2029 2030 2031 2032 2033 2034

 cleanup:
    virStoragePRDefFree(prd);
    return ret;
}


void
virStoragePRDefFormat(virBufferPtr buf,
2035 2036
                      virStoragePRDefPtr prd,
                      bool migratable)
2037
{
2038 2039
    virBufferAsprintf(buf, "<reservations managed='%s'",
                      virTristateBoolTypeToString(prd->managed));
2040 2041
    if (prd->path &&
        (prd->managed == VIR_TRISTATE_BOOL_NO || !migratable)) {
2042 2043 2044 2045 2046 2047 2048
        virBufferAddLit(buf, ">\n");
        virBufferAdjustIndent(buf, 2);
        virBufferAddLit(buf, "<source type='unix'");
        virBufferEscapeString(buf, " path='%s'", prd->path);
        virBufferAddLit(buf, " mode='client'/>\n");
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</reservations>\n");
2049 2050 2051 2052 2053 2054
    } else {
        virBufferAddLit(buf, "/>\n");
    }
}


2055 2056 2057 2058 2059 2060 2061 2062 2063 2064
bool
virStoragePRDefIsEqual(virStoragePRDefPtr a,
                       virStoragePRDefPtr b)
{
    if (!a && !b)
        return true;

    if (!a || !b)
        return false;

2065
    if (a->managed != b->managed ||
2066 2067 2068 2069 2070 2071 2072
        STRNEQ_NULLABLE(a->path, b->path))
        return false;

    return true;
}


2073 2074 2075 2076 2077 2078 2079
bool
virStoragePRDefIsManaged(virStoragePRDefPtr prd)
{
    return prd && prd->managed == VIR_TRISTATE_BOOL_YES;
}


2080 2081 2082 2083 2084 2085
bool
virStorageSourceChainHasManagedPR(virStorageSourcePtr src)
{
    virStorageSourcePtr n;

    for (n = src; virStorageSourceIsBacking(n); n = n->backingStore) {
2086
        if (virStoragePRDefIsManaged(n->pr))
2087 2088 2089 2090 2091 2092 2093
            return true;
    }

    return false;
}


2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116
static virStoragePRDefPtr
virStoragePRDefCopy(virStoragePRDefPtr src)
{
    virStoragePRDefPtr copy = NULL;
    virStoragePRDefPtr ret = NULL;

    if (VIR_ALLOC(copy) < 0)
        return NULL;

    copy->managed = src->managed;

    if (VIR_STRDUP(copy->path, src->path) < 0 ||
        VIR_STRDUP(copy->mgralias, src->mgralias) < 0)
        goto cleanup;

    VIR_STEAL_PTR(ret, copy);

 cleanup:
    virStoragePRDefFree(copy);
    return ret;
}


2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131
virSecurityDeviceLabelDefPtr
virStorageSourceGetSecurityLabelDef(virStorageSourcePtr src,
                                    const char *model)
{
    size_t i;

    for (i = 0; i < src->nseclabels; i++) {
        if (STREQ_NULLABLE(src->seclabels[i]->model, model))
            return src->seclabels[i];
    }

    return NULL;
}


2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196
static void
virStorageSourceSeclabelsClear(virStorageSourcePtr def)
{
    size_t i;

    if (def->seclabels) {
        for (i = 0; i < def->nseclabels; i++)
            virSecurityDeviceLabelDefFree(def->seclabels[i]);
        VIR_FREE(def->seclabels);
    }
}


static int
virStorageSourceSeclabelsCopy(virStorageSourcePtr to,
                              const virStorageSource *from)
{
    size_t i;

    if (from->nseclabels == 0)
        return 0;

    if (VIR_ALLOC_N(to->seclabels, from->nseclabels) < 0)
        return -1;
    to->nseclabels = from->nseclabels;

    for (i = 0; i < to->nseclabels; i++) {
        if (!(to->seclabels[i] = virSecurityDeviceLabelDefCopy(from->seclabels[i])))
            goto error;
    }

    return 0;

 error:
    virStorageSourceSeclabelsClear(to);
    return -1;
}


static virStorageTimestampsPtr
virStorageTimestampsCopy(const virStorageTimestamps *src)
{
    virStorageTimestampsPtr ret;

    if (VIR_ALLOC(ret) < 0)
        return NULL;

    memcpy(ret, src, sizeof(*src));

    return ret;
}


static virStoragePermsPtr
virStoragePermsCopy(const virStoragePerms *src)
{
    virStoragePermsPtr ret;

    if (VIR_ALLOC(ret) < 0)
        return NULL;

    ret->mode = src->mode;
    ret->uid = src->uid;
    ret->gid = src->gid;

2197
    if (VIR_STRDUP(ret->label, src->label) < 0)
2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245
        goto error;

    return ret;

 error:
    virStoragePermsFree(ret);
    return NULL;
}


static virStorageSourcePoolDefPtr
virStorageSourcePoolDefCopy(const virStorageSourcePoolDef *src)
{
    virStorageSourcePoolDefPtr ret;

    if (VIR_ALLOC(ret) < 0)
        return NULL;

    ret->voltype = src->voltype;
    ret->pooltype = src->pooltype;
    ret->actualtype = src->actualtype;
    ret->mode = src->mode;

    if (VIR_STRDUP(ret->pool, src->pool) < 0 ||
        VIR_STRDUP(ret->volume, src->volume) < 0)
        goto error;

    return ret;

 error:
    virStorageSourcePoolDefFree(ret);
    return NULL;
}


/**
 * virStorageSourcePtr:
 *
 * Deep-copies a virStorageSource structure. If @backing chain is true
 * then also copies the backing chain recursively, otherwise just
 * the top element is copied. This function doesn't copy the
 * storage driver access structure and thus the struct needs to be initialized
 * separately.
 */
virStorageSourcePtr
virStorageSourceCopy(const virStorageSource *src,
                     bool backingChain)
{
2246 2247
    virStorageSourcePtr ret = NULL;
    VIR_AUTOUNREF(virStorageSourcePtr) def = NULL;
2248

2249
    if (!(def = virStorageSourceNew()))
2250 2251
        return NULL;

2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270
    def->id = src->id;
    def->type = src->type;
    def->protocol = src->protocol;
    def->format = src->format;
    def->capacity = src->capacity;
    def->allocation = src->allocation;
    def->has_allocation = src->has_allocation;
    def->physical = src->physical;
    def->readonly = src->readonly;
    def->shared = src->shared;
    def->haveTLS = src->haveTLS;
    def->tlsFromConfig = src->tlsFromConfig;
    def->detected = src->detected;
    def->debugLevel = src->debugLevel;
    def->debug = src->debug;
    def->iomode = src->iomode;
    def->cachemode = src->cachemode;
    def->discard = src->discard;
    def->detect_zeroes = src->detect_zeroes;
2271 2272

    /* storage driver metadata are not copied */
2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285
    def->drv = NULL;

    if (VIR_STRDUP(def->path, src->path) < 0 ||
        VIR_STRDUP(def->volume, src->volume) < 0 ||
        VIR_STRDUP(def->relPath, src->relPath) < 0 ||
        VIR_STRDUP(def->backingStoreRaw, src->backingStoreRaw) < 0 ||
        VIR_STRDUP(def->snapshot, src->snapshot) < 0 ||
        VIR_STRDUP(def->configFile, src->configFile) < 0 ||
        VIR_STRDUP(def->nodeformat, src->nodeformat) < 0 ||
        VIR_STRDUP(def->nodestorage, src->nodestorage) < 0 ||
        VIR_STRDUP(def->compat, src->compat) < 0 ||
        VIR_STRDUP(def->tlsAlias, src->tlsAlias) < 0 ||
        VIR_STRDUP(def->tlsCertdir, src->tlsCertdir) < 0)
2286
        return NULL;
2287

2288
    if (src->nhosts) {
2289
        if (!(def->hosts = virStorageNetHostDefCopy(src->nhosts, src->hosts)))
2290
            return NULL;
2291

2292
        def->nhosts = src->nhosts;
2293
    }
2294 2295

    if (src->srcpool &&
2296
        !(def->srcpool = virStorageSourcePoolDefCopy(src->srcpool)))
2297
        return NULL;
2298 2299

    if (src->features &&
2300
        !(def->features = virBitmapNewCopy(src->features)))
2301
        return NULL;
2302 2303

    if (src->encryption &&
2304
        !(def->encryption = virStorageEncryptionCopy(src->encryption)))
2305
        return NULL;
2306 2307

    if (src->perms &&
2308
        !(def->perms = virStoragePermsCopy(src->perms)))
2309
        return NULL;
2310 2311

    if (src->timestamps &&
2312
        !(def->timestamps = virStorageTimestampsCopy(src->timestamps)))
2313
        return NULL;
2314

2315
    if (virStorageSourceSeclabelsCopy(def, src) < 0)
2316
        return NULL;
2317 2318

    if (src->auth &&
2319
        !(def->auth = virStorageAuthDefCopy(src->auth)))
2320
        return NULL;
2321

2322
    if (src->pr &&
2323
        !(def->pr = virStoragePRDefCopy(src->pr)))
2324
        return NULL;
2325

2326
    if (virStorageSourceInitiatorCopy(&def->initiator, &src->initiator))
2327
        return NULL;
2328

2329
    if (backingChain && src->backingStore) {
2330
        if (!(def->backingStore = virStorageSourceCopy(src->backingStore,
2331
                                                       true)))
2332
            return NULL;
2333 2334
    }

2335 2336
    VIR_STEAL_PTR(ret, def);
    return ret;
2337 2338 2339
}


2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382
/**
 * virStorageSourceIsSameLocation:
 *
 * Returns true if the sources @a and @b point to the same storage location.
 * This does not compare any other configuration option
 */
bool
virStorageSourceIsSameLocation(virStorageSourcePtr a,
                               virStorageSourcePtr b)
{
    size_t i;

    /* there are multiple possibilities to define an empty source */
    if (virStorageSourceIsEmpty(a) &&
        virStorageSourceIsEmpty(b))
        return true;

    if (virStorageSourceGetActualType(a) != virStorageSourceGetActualType(b))
        return false;

    if (STRNEQ_NULLABLE(a->path, b->path) ||
        STRNEQ_NULLABLE(a->volume, b->volume) ||
        STRNEQ_NULLABLE(a->snapshot, b->snapshot))
        return false;

    if (a->type == VIR_STORAGE_TYPE_NETWORK) {
        if (a->protocol != b->protocol ||
            a->nhosts != b->nhosts)
            return false;

        for (i = 0; i < a->nhosts; i++) {
            if (a->hosts[i].transport != b->hosts[i].transport ||
                a->hosts[i].port != b->hosts[i].port ||
                STRNEQ_NULLABLE(a->hosts[i].name, b->hosts[i].name) ||
                STRNEQ_NULLABLE(a->hosts[i].socket, b->hosts[i].socket))
                return false;
        }
    }

    return true;
}


2383 2384 2385 2386
/**
 * virStorageSourceInitChainElement:
 * @newelem: New backing chain element disk source
 * @old: Existing top level disk source
N
Nitesh Konkar 已提交
2387
 * @transferLabels: Transfer security labels.
2388 2389 2390 2391 2392
 *
 * Transfers relevant information from the existing disk source to the new
 * backing chain element if they weren't supplied so that labelling info
 * and possibly other stuff is correct.
 *
2393 2394
 * If @transferLabels is true, security labels from the existing disk are copied
 * to the new disk. Otherwise the default domain imagelabel label will be used.
2395 2396 2397 2398 2399 2400
 *
 * Returns 0 on success, -1 on error.
 */
int
virStorageSourceInitChainElement(virStorageSourcePtr newelem,
                                 virStorageSourcePtr old,
2401
                                 bool transferLabels)
2402 2403 2404
{
    int ret = -1;

2405 2406
    if (transferLabels &&
        !newelem->seclabels &&
2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419
        virStorageSourceSeclabelsCopy(newelem, old) < 0)
        goto cleanup;

    newelem->shared = old->shared;
    newelem->readonly = old->readonly;

    ret = 0;

 cleanup:
    return ret;
}


2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432
void
virStorageSourcePoolDefFree(virStorageSourcePoolDefPtr def)
{
    if (!def)
        return;

    VIR_FREE(def->pool);
    VIR_FREE(def->volume);

    VIR_FREE(def);
}


2433
int
2434
virStorageSourceGetActualType(const virStorageSource *def)
2435 2436 2437 2438 2439 2440 2441 2442
{
    if (def->type == VIR_STORAGE_TYPE_VOLUME && def->srcpool)
        return def->srcpool->actualtype;

    return def->type;
}


2443
bool
2444
virStorageSourceIsLocalStorage(const virStorageSource *src)
2445
{
2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461
    virStorageType type = virStorageSourceGetActualType(src);

    switch (type) {
    case VIR_STORAGE_TYPE_FILE:
    case VIR_STORAGE_TYPE_BLOCK:
    case VIR_STORAGE_TYPE_DIR:
        return true;

    case VIR_STORAGE_TYPE_NETWORK:
    case VIR_STORAGE_TYPE_VOLUME:
    case VIR_STORAGE_TYPE_LAST:
    case VIR_STORAGE_TYPE_NONE:
        return false;
    }

    return false;
2462 2463 2464
}


2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481
/**
 * virStorageSourceIsEmpty:
 *
 * @src: disk source to check
 *
 * Returns true if the guest disk has no associated host storage source
 * (such as an empty cdrom drive).
 */
bool
virStorageSourceIsEmpty(virStorageSourcePtr src)
{
    if (virStorageSourceIsLocalStorage(src) && !src->path)
        return true;

    if (src->type == VIR_STORAGE_TYPE_NONE)
        return true;

2482 2483 2484 2485
    if (src->type == VIR_STORAGE_TYPE_NETWORK &&
        src->protocol == VIR_STORAGE_NET_PROTOCOL_NONE)
        return true;

2486 2487 2488 2489
    return false;
}


2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503
/**
 * virStorageSourceIsBlockLocal:
 * @src: disk source definition
 *
 * Returns true if @src describes a locally accessible block storage source.
 * This includes block devices and host-mapped iSCSI volumes.
 */
bool
virStorageSourceIsBlockLocal(const virStorageSource *src)
{
    return virStorageSourceGetActualType(src) == VIR_STORAGE_TYPE_BLOCK;
}


2504
/**
2505
 * virStorageSourceBackingStoreClear:
2506 2507 2508 2509 2510 2511
 *
 * @src: disk source to clear
 *
 * Clears information about backing store of the current storage file.
 */
void
2512
virStorageSourceBackingStoreClear(virStorageSourcePtr def)
2513 2514 2515 2516 2517 2518 2519 2520
{
    if (!def)
        return;

    VIR_FREE(def->relPath);
    VIR_FREE(def->backingStoreRaw);

    /* recursively free backing chain */
2521
    virObjectUnref(def->backingStore);
2522 2523 2524 2525
    def->backingStore = NULL;
}


2526 2527 2528 2529 2530 2531 2532
void
virStorageSourceClear(virStorageSourcePtr def)
{
    if (!def)
        return;

    VIR_FREE(def->path);
2533
    VIR_FREE(def->volume);
2534 2535
    VIR_FREE(def->snapshot);
    VIR_FREE(def->configFile);
2536
    virStorageSourcePoolDefFree(def->srcpool);
E
Eric Blake 已提交
2537 2538
    virBitmapFree(def->features);
    VIR_FREE(def->compat);
2539
    virStorageEncryptionFree(def->encryption);
2540
    virStoragePRDefFree(def->pr);
2541
    virStorageSourceSeclabelsClear(def);
2542
    virStoragePermsFree(def->perms);
E
Eric Blake 已提交
2543
    VIR_FREE(def->timestamps);
2544 2545

    virStorageNetHostDefFree(def->nhosts, def->hosts);
2546
    virStorageAuthDefFree(def->auth);
2547
    virObjectUnref(def->privateData);
2548

2549
    VIR_FREE(def->nodestorage);
2550 2551
    VIR_FREE(def->nodeformat);

2552
    virStorageSourceBackingStoreClear(def);
2553

2554 2555 2556
    VIR_FREE(def->tlsAlias);
    VIR_FREE(def->tlsCertdir);

2557 2558
    virStorageSourceInitiatorClear(&def->initiator);

2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571
    /* clear everything except the class header as the object APIs
     * will break otherwise */
    memset((char *) def + sizeof(def->parent), 0,
           sizeof(*def) - sizeof(def->parent));
}


static void
virStorageSourceDispose(void *obj)
{
    virStorageSourcePtr src = obj;

    virStorageSourceClear(src);
2572
}
2573 2574


2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587
static int
virStorageSourceOnceInit(void)
{
    if (!VIR_CLASS_NEW(virStorageSource, virClassForObject()))
        return -1;

    return 0;
}


VIR_ONCE_GLOBAL_INIT(virStorageSource);


2588 2589 2590
virStorageSourcePtr
virStorageSourceNew(void)
{
2591
    if (virStorageSourceInitialize() < 0)
2592 2593
        return NULL;

2594
    return virObjectNew(virStorageSourceClass);
2595 2596 2597
}


2598 2599 2600 2601
static virStorageSourcePtr
virStorageSourceNewFromBackingRelative(virStorageSourcePtr parent,
                                       const char *rel)
{
2602
    virStorageSourcePtr ret = NULL;
2603
    VIR_AUTOFREE(char *) dirname = NULL;
2604
    VIR_AUTOUNREF(virStorageSourcePtr) def = NULL;
2605

2606
    if (!(def = virStorageSourceNew()))
2607 2608
        return NULL;

2609
    /* store relative name */
2610
    if (VIR_STRDUP(def->relPath, parent->backingStoreRaw) < 0)
2611
        return NULL;
2612

2613 2614
    if (!(dirname = mdir_name(parent->path))) {
        virReportOOMError();
2615
        return NULL;
2616
    }
2617

2618
    if (STRNEQ(dirname, "/")) {
2619
        if (virAsprintf(&def->path, "%s/%s", dirname, rel) < 0)
2620
            return NULL;
2621
    } else {
2622
        if (virAsprintf(&def->path, "/%s", rel) < 0)
2623
            return NULL;
2624 2625 2626
    }

    if (virStorageSourceGetActualType(parent) == VIR_STORAGE_TYPE_NETWORK) {
2627
        def->type = VIR_STORAGE_TYPE_NETWORK;
2628 2629

        /* copy the host network part */
2630
        def->protocol = parent->protocol;
2631
        if (parent->nhosts) {
2632
            if (!(def->hosts = virStorageNetHostDefCopy(parent->nhosts,
2633
                                                        parent->hosts)))
2634
                return NULL;
2635

2636
            def->nhosts = parent->nhosts;
2637
        }
2638

2639
        if (VIR_STRDUP(def->volume, parent->volume) < 0)
2640
            return NULL;
2641 2642
    } else {
        /* set the type to _FILE, the caller shall update it to the actual type */
2643
        def->type = VIR_STORAGE_TYPE_FILE;
2644 2645
    }

2646 2647
    VIR_STEAL_PTR(ret, def);
    return ret;
2648 2649 2650 2651 2652
}


static int
virStorageSourceParseBackingURI(virStorageSourcePtr src,
2653
                                const char *uristr)
2654 2655
{
    virURIPtr uri = NULL;
2656
    const char *path = NULL;
2657
    int ret = -1;
2658
    VIR_AUTOSTRINGLIST scheme = NULL;
2659

2660
    if (!(uri = virURIParse(uristr))) {
2661 2662
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to parse backing file location '%s'"),
2663
                       uristr);
2664 2665 2666
        goto cleanup;
    }

2667 2668 2669 2670 2671
    if (VIR_ALLOC(src->hosts) < 0)
        goto cleanup;

    src->nhosts = 1;

2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698
    if (!(scheme = virStringSplit(uri->scheme, "+", 2)))
        goto cleanup;

    if (!scheme[0] ||
        (src->protocol = virStorageNetProtocolTypeFromString(scheme[0])) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("invalid backing protocol '%s'"),
                       NULLSTR(scheme[0]));
        goto cleanup;
    }

    if (scheme[1] &&
        (src->hosts->transport = virStorageNetHostTransportTypeFromString(scheme[1])) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("invalid protocol transport type '%s'"),
                       scheme[1]);
        goto cleanup;
    }

    /* handle socket stored as a query */
    if (uri->query) {
        if (VIR_STRDUP(src->hosts->socket, STRSKIP(uri->query, "socket=")) < 0)
            goto cleanup;
    }

    /* XXX We currently don't support auth, so don't bother parsing it */

2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715
    /* uri->path is NULL if the URI does not contain slash after host:
     * transport://host:port */
    if (uri->path)
        path = uri->path;
    else
        path = "";

    /* possibly skip the leading slash  */
    if (path[0] == '/')
        path++;

    /* NBD allows empty export name (path) */
    if (src->protocol == VIR_STORAGE_NET_PROTOCOL_NBD &&
        path[0] == '\0')
        path = NULL;

    if (VIR_STRDUP(src->path, path) < 0)
2716 2717 2718 2719
        goto cleanup;

    if (src->protocol == VIR_STORAGE_NET_PROTOCOL_GLUSTER) {
        char *tmp;
2720 2721 2722 2723 2724 2725 2726

        if (!src->path) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("missing volume name and path for gluster volume"));
            goto cleanup;
        }

2727 2728
        if (!(tmp = strchr(src->path, '/')) ||
            tmp == src->path) {
2729
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
2730 2731 2732 2733 2734 2735 2736
                           _("missing volume name or file name in "
                             "gluster source path '%s'"), src->path);
            goto cleanup;
        }

        src->volume = src->path;

2737
        if (VIR_STRDUP(src->path, tmp + 1) < 0)
2738 2739 2740 2741 2742
            goto cleanup;

        tmp[0] = '\0';
    }

2743
    src->hosts->port = uri->port;
2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755

    if (VIR_STRDUP(src->hosts->name, uri->server) < 0)
        goto cleanup;

    ret = 0;

 cleanup:
    virURIFree(uri);
    return ret;
}


2756 2757 2758 2759 2760 2761
static int
virStorageSourceRBDAddHost(virStorageSourcePtr src,
                           char *hostport)
{
    char *port;
    size_t skip;
2762
    VIR_AUTOSTRINGLIST parts = NULL;
2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778

    if (VIR_EXPAND_N(src->hosts, src->nhosts, 1) < 0)
        return -1;

    if ((port = strchr(hostport, ']'))) {
        /* ipv6, strip brackets */
        hostport += 1;
        skip = 3;
    } else {
        port = strstr(hostport, "\\:");
        skip = 2;
    }

    if (port) {
        *port = '\0';
        port += skip;
2779
        if (virStringParsePort(port, &src->hosts[src->nhosts - 1].port) < 0)
2780 2781 2782 2783 2784 2785
            goto error;
    }

    parts = virStringSplit(hostport, "\\:", 0);
    if (!parts)
        goto error;
2786
    src->hosts[src->nhosts-1].name = virStringListJoin((const char **)parts, ":");
2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805
    if (!src->hosts[src->nhosts-1].name)
        goto error;

    src->hosts[src->nhosts-1].transport = VIR_STORAGE_NET_HOST_TRANS_TCP;
    src->hosts[src->nhosts-1].socket = NULL;

    return 0;

 error:
    VIR_FREE(src->hosts[src->nhosts-1].name);
    return -1;
}


int
virStorageSourceParseRBDColonString(const char *rbdstr,
                                    virStorageSourcePtr src)
{
    char *p, *e, *next;
2806
    VIR_AUTOFREE(char *) options = NULL;
2807
    VIR_AUTOPTR(virStorageAuthDef) authdef = NULL;
2808 2809 2810 2811 2812 2813

    /* optionally skip the "rbd:" prefix if provided */
    if (STRPREFIX(rbdstr, "rbd:"))
        rbdstr += strlen("rbd:");

    if (VIR_STRDUP(src->path, rbdstr) < 0)
2814
        return -1;
2815 2816 2817 2818

    p = strchr(src->path, ':');
    if (p) {
        if (VIR_STRDUP(options, p + 1) < 0)
2819
            return -1;
2820 2821 2822
        *p = '\0';
    }

2823 2824 2825
    /* snapshot name */
    if ((p = strchr(src->path, '@'))) {
        if (VIR_STRDUP(src->snapshot, p + 1) < 0)
2826
            return -1;
2827 2828 2829
        *p = '\0';
    }

2830 2831 2832 2833
    /* pool vs. image name */
    if ((p = strchr(src->path, '/'))) {
        VIR_STEAL_PTR(src->volume, src->path);
        if (VIR_STRDUP(src->path, p + 1) < 0)
2834
            return -1;
2835 2836 2837
        *p = '\0';
    }

2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860
    /* options */
    if (!options)
        return 0; /* all done */

    p = options;
    while (*p) {
        /* find : delimiter or end of string */
        for (e = p; *e && *e != ':'; ++e) {
            if (*e == '\\') {
                e++;
                if (*e == '\0')
                    break;
            }
        }
        if (*e == '\0') {
            next = e;    /* last kv pair */
        } else {
            next = e + 1;
            *e = '\0';
        }

        if (STRPREFIX(p, "id=")) {
            /* formulate authdef for src->auth */
2861 2862 2863 2864 2865
            if (src->auth) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("duplicate 'id' found in '%s'"), src->path);
                return -1;
            }
2866
            if (VIR_ALLOC(authdef) < 0)
2867
                return -1;
2868 2869

            if (VIR_STRDUP(authdef->username, p + strlen("id=")) < 0)
2870
                return -1;
2871 2872

            if (VIR_STRDUP(authdef->secrettype,
2873
                           virSecretUsageTypeToString(VIR_SECRET_USAGE_TYPE_CEPH)) < 0)
2874
                return -1;
2875
            VIR_STEAL_PTR(src->auth, authdef);
2876
            src->authInherited = true;
2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897

            /* Cannot formulate a secretType (eg, usage or uuid) given
             * what is provided.
             */
        }
        if (STRPREFIX(p, "mon_host=")) {
            char *h, *sep;

            h = p + strlen("mon_host=");
            while (h < e) {
                for (sep = h; sep < e; ++sep) {
                    if (*sep == '\\' && (sep[1] == ',' ||
                                         sep[1] == ';' ||
                                         sep[1] == ' ')) {
                        *sep = '\0';
                        sep += 2;
                        break;
                    }
                }

                if (virStorageSourceRBDAddHost(src, h) < 0)
2898
                    return -1;
2899 2900 2901 2902 2903

                h = sep;
            }
        }

2904 2905
        if (STRPREFIX(p, "conf=") &&
            VIR_STRDUP(src->configFile, p + strlen("conf=")) < 0)
2906
            return -1;
2907

2908 2909 2910 2911 2912 2913
        p = next;
    }
    return 0;
}


2914
static int
2915 2916
virStorageSourceParseNBDColonString(const char *nbdstr,
                                    virStorageSourcePtr src)
2917
{
2918
    VIR_AUTOSTRINGLIST backing = NULL;
2919

2920
    if (!(backing = virStringSplit(nbdstr, ":", 0)))
2921
        return -1;
2922 2923 2924 2925

    /* we know that backing[0] now equals to "nbd" */

    if (VIR_ALLOC_N(src->hosts, 1) < 0)
2926
        return -1;
2927

2928 2929 2930 2931 2932 2933 2934 2935
    src->nhosts = 1;
    src->hosts->transport = VIR_STORAGE_NET_HOST_TRANS_TCP;

    /* format: [] denotes optional sections, uppercase are variable strings
     * nbd:unix:/PATH/TO/SOCKET[:exportname=EXPORTNAME]
     * nbd:HOSTNAME:PORT[:exportname=EXPORTNAME]
     */
    if (!backing[1]) {
2936
        virReportError(VIR_ERR_INTERNAL_ERROR,
2937 2938
                       _("missing remote information in '%s' for protocol nbd"),
                       nbdstr);
2939
        return -1;
2940 2941 2942 2943 2944
    } else if (STREQ(backing[1], "unix")) {
        if (!backing[2]) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("missing unix socket path in nbd backing string %s"),
                           nbdstr);
2945
            return -1;
2946
        }
2947

2948
        if (VIR_STRDUP(src->hosts->socket, backing[2]) < 0)
2949
            return -1;
2950

2951 2952
   } else {
        if (VIR_STRDUP(src->hosts->name, backing[1]) < 0)
2953
            return -1;
2954

2955 2956 2957 2958
        if (!backing[2]) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("missing port in nbd string '%s'"),
                           nbdstr);
2959
            return -1;
2960
        }
2961

2962
        if (virStringParsePort(backing[2], &src->hosts->port) < 0)
2963
            return -1;
2964
    }
2965

2966 2967
    if (backing[3] && STRPREFIX(backing[3], "exportname=")) {
        if (VIR_STRDUP(src->path, backing[3] + strlen("exportname=")) < 0)
2968
            return -1;
2969
    }
2970

2971
    return 0;
2972 2973 2974 2975 2976 2977 2978 2979
}


static int
virStorageSourceParseBackingColon(virStorageSourcePtr src,
                                  const char *path)
{
    const char *p;
2980
    VIR_AUTOFREE(char *) protocol = NULL;
2981 2982 2983 2984 2985

    if (!(p = strchr(path, ':'))) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("invalid backing protocol string '%s'"),
                       path);
2986
        return -1;
2987 2988 2989
    }

    if (VIR_STRNDUP(protocol, path, p - path) < 0)
2990
        return -1;
2991 2992 2993 2994 2995

    if ((src->protocol = virStorageNetProtocolTypeFromString(protocol)) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("invalid backing protocol '%s'"),
                       protocol);
2996
        return -1;
2997 2998 2999 3000 3001
    }

    switch ((virStorageNetProtocol) src->protocol) {
    case VIR_STORAGE_NET_PROTOCOL_NBD:
        if (virStorageSourceParseNBDColonString(path, src) < 0)
3002
            return -1;
3003
        break;
3004 3005

    case VIR_STORAGE_NET_PROTOCOL_RBD:
3006
        if (virStorageSourceParseRBDColonString(path, src) < 0)
3007
            return -1;
3008 3009 3010
        break;

    case VIR_STORAGE_NET_PROTOCOL_SHEEPDOG:
3011 3012 3013 3014
    case VIR_STORAGE_NET_PROTOCOL_LAST:
    case VIR_STORAGE_NET_PROTOCOL_NONE:
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("backing store parser is not implemented for protocol %s"),
3015
                       protocol);
3016
        return -1;
3017 3018 3019 3020 3021 3022 3023 3024

    case VIR_STORAGE_NET_PROTOCOL_HTTP:
    case VIR_STORAGE_NET_PROTOCOL_HTTPS:
    case VIR_STORAGE_NET_PROTOCOL_FTP:
    case VIR_STORAGE_NET_PROTOCOL_FTPS:
    case VIR_STORAGE_NET_PROTOCOL_TFTP:
    case VIR_STORAGE_NET_PROTOCOL_ISCSI:
    case VIR_STORAGE_NET_PROTOCOL_GLUSTER:
3025
    case VIR_STORAGE_NET_PROTOCOL_SSH:
3026
    case VIR_STORAGE_NET_PROTOCOL_VXHS:
3027 3028
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("malformed backing store path for protocol %s"),
3029
                       protocol);
3030
        return -1;
3031 3032
    }

3033
    return 0;
3034 3035 3036
}


3037 3038 3039 3040 3041
static int
virStorageSourceParseBackingJSONInternal(virStorageSourcePtr src,
                                         virJSONValuePtr json);


3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063
static int
virStorageSourceParseBackingJSONPath(virStorageSourcePtr src,
                                     virJSONValuePtr json,
                                     int type)
{
    const char *path;

    if (!(path = virJSONValueObjectGetString(json, "filename"))) {
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("missing 'filename' field in JSON backing volume "
                         "definition"));
        return -1;
    }

    if (VIR_STRDUP(src->path, path) < 0)
        return -1;

    src->type = type;
    return 0;
}


3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091
static int
virStorageSourceParseBackingJSONUriStr(virStorageSourcePtr src,
                                       const char *uri,
                                       int protocol)
{
    if (virStorageSourceParseBackingURI(src, uri) < 0)
        return -1;

    if (src->protocol != protocol) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("expected protocol '%s' but got '%s' in URI JSON volume "
                         "definition"),
                       virStorageNetProtocolTypeToString(protocol),
                       virStorageNetProtocolTypeToString(src->protocol));
        return -1;
    }

    return 0;
}


static int
virStorageSourceParseBackingJSONUri(virStorageSourcePtr src,
                                    virJSONValuePtr json,
                                    int protocol)
{
    const char *uri;

3092
    if (!(uri = virJSONValueObjectGetString(json, "url"))) {
3093
        virReportError(VIR_ERR_INVALID_ARG, "%s",
3094
                       _("missing 'url' in JSON backing volume definition"));
3095 3096 3097 3098 3099 3100 3101
        return -1;
    }

    return virStorageSourceParseBackingJSONUriStr(src, uri, protocol);
}


3102 3103 3104 3105
static int
virStorageSourceParseBackingJSONInetSocketAddress(virStorageNetHostDefPtr host,
                                                  virJSONValuePtr json)
{
3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117
    const char *hostname;
    const char *port;

    if (!json) {
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("missing remote server specification in JSON "
                         "backing volume definition"));
        return -1;
    }

    hostname = virJSONValueObjectGetString(json, "host");
    port = virJSONValueObjectGetString(json, "port");
3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128

    if (!hostname) {
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("missing hostname for tcp backing server in "
                         "JSON backing volume definition"));
        return -1;
    }

    host->transport = VIR_STORAGE_NET_HOST_TRANS_TCP;

    if (VIR_STRDUP(host->name, hostname) < 0 ||
3129
        virStringParsePort(port, &host->port) < 0)
3130 3131 3132 3133 3134 3135
        return -1;

    return 0;
}


3136
static int
3137 3138
virStorageSourceParseBackingJSONSocketAddress(virStorageNetHostDefPtr host,
                                              virJSONValuePtr json)
3139
{
3140 3141 3142 3143 3144 3145 3146 3147 3148
    const char *type;
    const char *socket;

    if (!json) {
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("missing remote server specification in JSON "
                         "backing volume definition"));
        return -1;
    }
3149

3150
    if (!(type = virJSONValueObjectGetString(json, "type"))) {
3151 3152 3153
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("missing socket address type in "
                         "JSON backing volume definition"));
3154 3155 3156
        return -1;
    }

3157
    if (STREQ(type, "tcp") || STREQ(type, "inet")) {
3158
        return virStorageSourceParseBackingJSONInetSocketAddress(host, json);
3159

3160 3161
    } else if (STREQ(type, "unix")) {
        host->transport = VIR_STORAGE_NET_HOST_TRANS_UNIX;
3162

3163 3164 3165 3166 3167 3168 3169
        socket = virJSONValueObjectGetString(json, "path");

        /* check for old spelling for gluster protocol */
        if (!socket)
            socket = virJSONValueObjectGetString(json, "socket");

        if (!socket) {
3170 3171
            virReportError(VIR_ERR_INVALID_ARG, "%s",
                           _("missing socket path for udp backing server in "
3172
                             "JSON backing volume definition"));
3173 3174 3175 3176 3177
            return -1;
        }

        if (VIR_STRDUP(host->socket, socket) < 0)
            return -1;
3178
    } else {
3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("backing store protocol '%s' is not yet supported"),
                       type);
        return -1;
    }

    return 0;
}


static int
virStorageSourceParseBackingJSONGluster(virStorageSourcePtr src,
                                        virJSONValuePtr json,
                                        int opaque ATTRIBUTE_UNUSED)
{
    const char *uri = virJSONValueObjectGetString(json, "filename");
    const char *volume = virJSONValueObjectGetString(json, "volume");
    const char *path = virJSONValueObjectGetString(json, "path");
    virJSONValuePtr server = virJSONValueObjectGetArray(json, "server");
    size_t nservers;
    size_t i;

    /* legacy URI based syntax passed via 'filename' option */
    if (uri)
        return virStorageSourceParseBackingJSONUriStr(src, uri,
                                                      VIR_STORAGE_NET_PROTOCOL_GLUSTER);

    if (!volume || !path || !server) {
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("missing 'volume', 'path' or 'server' attribute in "
                         "JSON backing definition for gluster volume"));
        return -1;
    }

3213 3214 3215
    src->type = VIR_STORAGE_TYPE_NETWORK;
    src->protocol = VIR_STORAGE_NET_PROTOCOL_GLUSTER;

3216
    if (VIR_STRDUP(src->volume, volume) < 0 ||
3217
        VIR_STRDUP(src->path, path) < 0)
3218 3219 3220
        return -1;

    nservers = virJSONValueArraySize(server);
3221
    if (nservers == 0) {
3222 3223 3224
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("at least 1 server is necessary in "
                         "JSON backing definition for gluster volume"));
3225 3226

        return -1;
3227 3228 3229 3230 3231 3232 3233
    }

    if (VIR_ALLOC_N(src->hosts, nservers) < 0)
        return -1;
    src->nhosts = nservers;

    for (i = 0; i < nservers; i++) {
3234 3235
        if (virStorageSourceParseBackingJSONSocketAddress(src->hosts + i,
                                                          virJSONValueArrayGet(server, i)) < 0)
3236 3237 3238 3239 3240 3241 3242
            return -1;
    }

    return 0;
}


3243 3244 3245 3246 3247
static int
virStorageSourceParseBackingJSONiSCSI(virStorageSourcePtr src,
                                      virJSONValuePtr json,
                                      int opaque ATTRIBUTE_UNUSED)
{
3248 3249 3250
    const char *transport = virJSONValueObjectGetString(json, "transport");
    const char *portal = virJSONValueObjectGetString(json, "portal");
    const char *target = virJSONValueObjectGetString(json, "target");
3251
    const char *lun = virJSONValueObjectGetStringOrNumber(json, "lun");
3252
    const char *uri;
3253 3254
    char *port;
    int ret = -1;
3255 3256 3257 3258 3259 3260

    /* legacy URI based syntax passed via 'filename' option */
    if ((uri = virJSONValueObjectGetString(json, "filename")))
        return virStorageSourceParseBackingJSONUriStr(src, uri,
                                                      VIR_STORAGE_NET_PROTOCOL_ISCSI);

3261 3262
    src->type = VIR_STORAGE_TYPE_NETWORK;
    src->protocol = VIR_STORAGE_NET_PROTOCOL_ISCSI;
3263

3264 3265 3266
    if (!lun)
        lun = "0";

3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294
    if (VIR_ALLOC(src->hosts) < 0)
        goto cleanup;

    src->nhosts = 1;

    if (STRNEQ_NULLABLE(transport, "tcp")) {
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("only TCP transport is supported for iSCSI volumes"));
        goto cleanup;
    }

    src->hosts->transport = VIR_STORAGE_NET_HOST_TRANS_TCP;

    if (!portal) {
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("missing 'portal' address in iSCSI backing definition"));
        goto cleanup;
    }

    if (!target) {
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("missing 'target' in iSCSI backing definition"));
        goto cleanup;
    }

    if (VIR_STRDUP(src->hosts->name, portal) < 0)
        goto cleanup;

3295 3296
    if ((port = strrchr(src->hosts->name, ':')) &&
        !strchr(port, ']')) {
3297
        if (virStringParsePort(port + 1, &src->hosts->port) < 0)
3298 3299 3300 3301 3302
            goto cleanup;

        *port = '\0';
    }

3303
    if (virAsprintf(&src->path, "%s/%s", target, lun) < 0)
3304 3305 3306 3307 3308 3309
        goto cleanup;

    ret = 0;

 cleanup:
    return ret;
3310 3311 3312
}


3313 3314 3315 3316 3317 3318 3319 3320 3321
static int
virStorageSourceParseBackingJSONNbd(virStorageSourcePtr src,
                                    virJSONValuePtr json,
                                    int opaque ATTRIBUTE_UNUSED)
{
    const char *path = virJSONValueObjectGetString(json, "path");
    const char *host = virJSONValueObjectGetString(json, "host");
    const char *port = virJSONValueObjectGetString(json, "port");
    const char *export = virJSONValueObjectGetString(json, "export");
3322
    virJSONValuePtr server = virJSONValueObjectGetObject(json, "server");
3323

3324
    if (!path && !host && !server) {
3325
        virReportError(VIR_ERR_INVALID_ARG, "%s",
3326 3327
                       _("missing host specification of NBD server in JSON "
                         "backing volume definition"));
3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340
        return -1;
    }

    src->type = VIR_STORAGE_TYPE_NETWORK;
    src->protocol = VIR_STORAGE_NET_PROTOCOL_NBD;

    if (VIR_STRDUP(src->path, export) < 0)
        return -1;

    if (VIR_ALLOC_N(src->hosts, 1) < 0)
        return -1;
    src->nhosts = 1;

3341 3342
    if (server) {
        if (virStorageSourceParseBackingJSONSocketAddress(src->hosts, server) < 0)
3343 3344
            return -1;
    } else {
3345 3346 3347 3348 3349 3350 3351 3352
        if (path) {
            src->hosts[0].transport = VIR_STORAGE_NET_HOST_TRANS_UNIX;
            if (VIR_STRDUP(src->hosts[0].socket, path) < 0)
                return -1;
        } else {
            src->hosts[0].transport = VIR_STORAGE_NET_HOST_TRANS_TCP;
            if (VIR_STRDUP(src->hosts[0].name, host) < 0)
                return -1;
3353

3354
            if (virStringParsePort(port, &src->hosts[0].port) < 0)
3355 3356
                return -1;
        }
3357 3358 3359 3360 3361 3362
    }

    return 0;
}


3363 3364 3365 3366 3367 3368
static int
virStorageSourceParseBackingJSONSheepdog(virStorageSourcePtr src,
                                         virJSONValuePtr json,
                                         int opaque ATTRIBUTE_UNUSED)
{
    const char *filename;
3369 3370
    const char *vdi = virJSONValueObjectGetString(json, "vdi");
    virJSONValuePtr server = virJSONValueObjectGetObject(json, "server");
3371 3372 3373 3374 3375 3376 3377 3378

    /* legacy URI based syntax passed via 'filename' option */
    if ((filename = virJSONValueObjectGetString(json, "filename"))) {
        if (strstr(filename, "://"))
            return virStorageSourceParseBackingJSONUriStr(src, filename,
                                                          VIR_STORAGE_NET_PROTOCOL_SHEEPDOG);

        /* libvirt doesn't implement a parser for the legacy non-URI syntax */
3379 3380 3381
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("missing sheepdog URI in JSON backing volume definition"));
        return -1;
3382 3383
    }

3384 3385
    src->type = VIR_STORAGE_TYPE_NETWORK;
    src->protocol = VIR_STORAGE_NET_PROTOCOL_SHEEPDOG;
3386

3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403
    if (!vdi) {
        virReportError(VIR_ERR_INVALID_ARG, "%s", _("missing sheepdog vdi name"));
        return -1;
    }

    if (VIR_STRDUP(src->path, vdi) < 0)
        return -1;

    if (VIR_ALLOC(src->hosts) < 0)
        return -1;

    src->nhosts = 1;

    if (virStorageSourceParseBackingJSONSocketAddress(src->hosts, server) < 0)
        return -1;

    return 0;
3404 3405 3406
}


3407 3408 3409 3410 3411 3412 3413 3414
static int
virStorageSourceParseBackingJSONSSH(virStorageSourcePtr src,
                                    virJSONValuePtr json,
                                    int opaque ATTRIBUTE_UNUSED)
{
    const char *path = virJSONValueObjectGetString(json, "path");
    const char *host = virJSONValueObjectGetString(json, "host");
    const char *port = virJSONValueObjectGetString(json, "port");
3415
    virJSONValuePtr server = virJSONValueObjectGetObject(json, "server");
3416

3417
    if (!(host || server) || !path) {
3418
        virReportError(VIR_ERR_INVALID_ARG, "%s",
3419
                       _("missing host/server or path of SSH JSON backing "
3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433
                         "volume definition"));
        return -1;
    }

    src->type = VIR_STORAGE_TYPE_NETWORK;
    src->protocol = VIR_STORAGE_NET_PROTOCOL_SSH;

    if (VIR_STRDUP(src->path, path) < 0)
        return -1;

    if (VIR_ALLOC_N(src->hosts, 1) < 0)
        return -1;
    src->nhosts = 1;

3434 3435 3436 3437 3438 3439
    if (server) {
        if (virStorageSourceParseBackingJSONInetSocketAddress(src->hosts,
                                                              server) < 0)
            return -1;
    } else {
        src->hosts[0].transport = VIR_STORAGE_NET_HOST_TRANS_TCP;
3440

3441
        if (VIR_STRDUP(src->hosts[0].name, host) < 0 ||
3442
            virStringParsePort(port, &src->hosts[0].port) < 0)
3443 3444
            return -1;
    }
3445 3446 3447 3448 3449

    return 0;
}


3450 3451 3452 3453 3454 3455
static int
virStorageSourceParseBackingJSONRBD(virStorageSourcePtr src,
                                    virJSONValuePtr json,
                                    int opaque ATTRIBUTE_UNUSED)
{
    const char *filename;
3456 3457 3458 3459 3460 3461 3462 3463
    const char *pool = virJSONValueObjectGetString(json, "pool");
    const char *image = virJSONValueObjectGetString(json, "image");
    const char *conf = virJSONValueObjectGetString(json, "conf");
    const char *snapshot = virJSONValueObjectGetString(json, "snapshot");
    virJSONValuePtr servers = virJSONValueObjectGetArray(json, "server");
    size_t nservers;
    size_t i;
    int ret = -1;
3464 3465 3466 3467 3468 3469 3470 3471

    src->type = VIR_STORAGE_TYPE_NETWORK;
    src->protocol = VIR_STORAGE_NET_PROTOCOL_RBD;

    /* legacy syntax passed via 'filename' option */
    if ((filename = virJSONValueObjectGetString(json, "filename")))
        return virStorageSourceParseRBDColonString(filename, src);

3472 3473 3474 3475 3476 3477
    if (!pool || !image) {
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("missing pool or image name in ceph backing volume "
                         "JSON specification"));
        return -1;
    }
3478

3479 3480 3481
    if (VIR_STRDUP(src->volume, pool) < 0 ||
        VIR_STRDUP(src->path, image) < 0 ||
        VIR_STRDUP(src->snapshot, snapshot) < 0 ||
3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502
        VIR_STRDUP(src->configFile, conf) < 0)
        goto cleanup;

    if (servers) {
        nservers = virJSONValueArraySize(servers);

        if (VIR_ALLOC_N(src->hosts, nservers) < 0)
            goto cleanup;

        src->nhosts = nservers;

        for (i = 0; i < nservers; i++) {
            if (virStorageSourceParseBackingJSONInetSocketAddress(src->hosts + i,
                                                                  virJSONValueArrayGet(servers, i)) < 0)
                goto cleanup;
        }
    }

    ret = 0;
 cleanup:
    return ret;
3503 3504
}

3505 3506 3507 3508 3509 3510 3511 3512 3513 3514
static int
virStorageSourceParseBackingJSONRaw(virStorageSourcePtr src,
                                    virJSONValuePtr json,
                                    int opaque ATTRIBUTE_UNUSED)
{
    /* There are no interesting attributes in raw driver.
     * Treat it as pass-through.
     */
    return virStorageSourceParseBackingJSONInternal(src, json);
}
3515

3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549

static int
virStorageSourceParseBackingJSONVxHS(virStorageSourcePtr src,
                                     virJSONValuePtr json,
                                     int opaque ATTRIBUTE_UNUSED)
{
    const char *vdisk_id = virJSONValueObjectGetString(json, "vdisk-id");
    virJSONValuePtr server = virJSONValueObjectGetObject(json, "server");

    if (!vdisk_id || !server) {
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("missing 'vdisk-id' or 'server' attribute in "
                         "JSON backing definition for VxHS volume"));
        return -1;
    }

    src->type = VIR_STORAGE_TYPE_NETWORK;
    src->protocol = VIR_STORAGE_NET_PROTOCOL_VXHS;

    if (VIR_STRDUP(src->path, vdisk_id) < 0)
        return -1;

    if (VIR_ALLOC_N(src->hosts, 1) < 0)
        return -1;
    src->nhosts = 1;

    if (virStorageSourceParseBackingJSONInetSocketAddress(src->hosts,
                                                          server) < 0)
        return -1;

    return 0;
}


3550 3551 3552 3553 3554 3555 3556 3557
struct virStorageSourceJSONDriverParser {
    const char *drvname;
    int (*func)(virStorageSourcePtr src, virJSONValuePtr json, int opaque);
    int opaque;
};

static const struct virStorageSourceJSONDriverParser jsonParsers[] = {
    {"file", virStorageSourceParseBackingJSONPath, VIR_STORAGE_TYPE_FILE},
3558 3559
    {"host_device", virStorageSourceParseBackingJSONPath, VIR_STORAGE_TYPE_BLOCK},
    {"host_cdrom", virStorageSourceParseBackingJSONPath, VIR_STORAGE_TYPE_BLOCK},
3560 3561 3562 3563 3564
    {"http", virStorageSourceParseBackingJSONUri, VIR_STORAGE_NET_PROTOCOL_HTTP},
    {"https", virStorageSourceParseBackingJSONUri, VIR_STORAGE_NET_PROTOCOL_HTTPS},
    {"ftp", virStorageSourceParseBackingJSONUri, VIR_STORAGE_NET_PROTOCOL_FTP},
    {"ftps", virStorageSourceParseBackingJSONUri, VIR_STORAGE_NET_PROTOCOL_FTPS},
    {"tftp", virStorageSourceParseBackingJSONUri, VIR_STORAGE_NET_PROTOCOL_TFTP},
3565
    {"gluster", virStorageSourceParseBackingJSONGluster, 0},
3566
    {"iscsi", virStorageSourceParseBackingJSONiSCSI, 0},
3567
    {"nbd", virStorageSourceParseBackingJSONNbd, 0},
3568
    {"sheepdog", virStorageSourceParseBackingJSONSheepdog, 0},
3569
    {"ssh", virStorageSourceParseBackingJSONSSH, 0},
3570
    {"rbd", virStorageSourceParseBackingJSONRBD, 0},
3571
    {"raw", virStorageSourceParseBackingJSONRaw, 0},
3572
    {"vxhs", virStorageSourceParseBackingJSONVxHS, 0},
3573 3574 3575 3576 3577
};



static int
3578 3579
virStorageSourceParseBackingJSONInternal(virStorageSourcePtr src,
                                         virJSONValuePtr json)
3580
{
3581
    virJSONValuePtr deflattened = NULL;
3582 3583 3584 3585
    virJSONValuePtr file;
    const char *drvname;
    size_t i;
    int ret = -1;
3586
    VIR_AUTOFREE(char *) str = NULL;
3587

3588 3589
    if (!(deflattened = virJSONValueObjectDeflatten(json)))
        goto cleanup;
3590

3591 3592 3593
    if (!(file = virJSONValueObjectGetObject(deflattened, "file"))) {
        str = virJSONValueToString(json, false);
        virReportError(VIR_ERR_INVALID_ARG,
3594
                       _("JSON backing volume definition '%s' lacks 'file' object"),
3595 3596
                       NULLSTR(str));
        goto cleanup;
3597 3598 3599
    }

    if (!(drvname = virJSONValueObjectGetString(file, "driver"))) {
3600 3601
        str = virJSONValueToString(json, false);
        virReportError(VIR_ERR_INVALID_ARG,
3602
                       _("JSON backing volume definition '%s' lacks driver name"),
3603
                       NULLSTR(str));
3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618
        goto cleanup;
    }

    for (i = 0; i < ARRAY_CARDINALITY(jsonParsers); i++) {
        if (STREQ(drvname, jsonParsers[i].drvname)) {
            ret = jsonParsers[i].func(src, file, jsonParsers[i].opaque);
            goto cleanup;
        }
    }

    virReportError(VIR_ERR_INTERNAL_ERROR,
                   _("missing parser implementation for JSON backing volume "
                     "driver '%s'"), drvname);

 cleanup:
3619
    virJSONValueFree(deflattened);
3620 3621 3622 3623
    return ret;
}


3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640
static int
virStorageSourceParseBackingJSON(virStorageSourcePtr src,
                                 const char *json)
{
    virJSONValuePtr root = NULL;
    int ret = -1;

    if (!(root = virJSONValueFromString(json)))
        return -1;

    ret = virStorageSourceParseBackingJSONInternal(src, root);

    virJSONValueFree(root);
    return ret;
}


3641
virStorageSourcePtr
3642 3643
virStorageSourceNewFromBackingAbsolute(const char *path)
{
3644
    const char *json;
3645
    virStorageSourcePtr ret = NULL;
3646
    int rc;
3647
    VIR_AUTOUNREF(virStorageSourcePtr) def = NULL;
3648

3649
    if (!(def = virStorageSourceNew()))
3650 3651 3652
        return NULL;

    if (virStorageIsFile(path)) {
3653
        def->type = VIR_STORAGE_TYPE_FILE;
3654

3655
        if (VIR_STRDUP(def->path, path) < 0)
3656
            return NULL;
3657
    } else {
3658
        def->type = VIR_STORAGE_TYPE_NETWORK;
3659

3660 3661
        VIR_DEBUG("parsing backing store string: '%s'", path);

3662
        /* handle URI formatted backing stores */
3663
        if ((json = STRSKIP(path, "json:")))
3664
            rc = virStorageSourceParseBackingJSON(def, json);
3665
        else if (strstr(path, "://"))
3666
            rc = virStorageSourceParseBackingURI(def, path);
3667
        else
3668
            rc = virStorageSourceParseBackingColon(def, path);
3669 3670

        if (rc < 0)
3671
            return NULL;
3672

3673
        virStorageSourceNetworkAssignDefaultPorts(def);
3674 3675 3676 3677

        /* Some of the legacy parsers parse authentication data since they are
         * also used in other places. For backing store detection the
         * authentication data would be invalid anyways, so we clear it */
3678 3679 3680
        if (def->auth) {
            virStorageAuthDefFree(def->auth);
            def->auth = NULL;
3681
        }
3682 3683
    }

3684 3685
    VIR_STEAL_PTR(ret, def);
    return ret;
3686 3687 3688 3689 3690 3691 3692
}


virStorageSourcePtr
virStorageSourceNewFromBacking(virStorageSourcePtr parent)
{
    struct stat st;
3693 3694
    virStorageSourcePtr ret = NULL;
    VIR_AUTOUNREF(virStorageSourcePtr) def = NULL;
3695 3696

    if (virStorageIsRelative(parent->backingStoreRaw))
3697
        def = virStorageSourceNewFromBackingRelative(parent,
3698 3699
                                                     parent->backingStoreRaw);
    else
3700
        def = virStorageSourceNewFromBackingAbsolute(parent->backingStoreRaw);
3701

3702
    if (def) {
3703
        /* possibly update local type */
3704 3705
        if (def->type == VIR_STORAGE_TYPE_FILE) {
            if (stat(def->path, &st) == 0) {
3706
                if (S_ISDIR(st.st_mode)) {
3707 3708
                    def->type = VIR_STORAGE_TYPE_DIR;
                    def->format = VIR_STORAGE_FILE_DIR;
3709
                } else if (S_ISBLK(st.st_mode)) {
3710
                    def->type = VIR_STORAGE_TYPE_BLOCK;
3711 3712 3713
                }
            }
        }
3714 3715

        /* copy parent's labelling and other top level stuff */
3716
        if (virStorageSourceInitChainElement(def, parent, true) < 0)
3717
            return NULL;
3718

3719 3720
        def->readonly = true;
        def->detected = true;
3721 3722
    }

3723 3724
    VIR_STEAL_PTR(ret, def);
    return ret;
3725
}
3726 3727


3728
/**
3729 3730 3731
 * @src: disk source definition structure
 * @fd: file descriptor
 * @sb: stat buffer
3732
 *
3733 3734 3735 3736 3737
 * Updates src->physical depending on the actual type of storage being used.
 * To be called for domain storage source reporting as the volume code does
 * not set/use the 'type' field for the voldef->source.target
 *
 * Returns 0 on success, -1 on error.
3738 3739
 */
int
3740 3741 3742
virStorageSourceUpdatePhysicalSize(virStorageSourcePtr src,
                                   int fd,
                                   struct stat const *sb)
3743 3744
{
    off_t end;
3745
    virStorageType actual_type = virStorageSourceGetActualType(src);
3746

3747 3748 3749 3750 3751
    switch (actual_type) {
    case VIR_STORAGE_TYPE_FILE:
    case VIR_STORAGE_TYPE_NETWORK:
        src->physical = sb->st_size;
        break;
3752

3753 3754 3755
    case VIR_STORAGE_TYPE_BLOCK:
        if ((end = lseek(fd, 0, SEEK_END)) == (off_t) -1) {
            virReportSystemError(errno, _("failed to seek to end of '%s'"),
3756
                                 src->path);
3757 3758
            return -1;
        }
3759 3760

        src->physical = end;
3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771
        break;

    case VIR_STORAGE_TYPE_DIR:
        src->physical = 0;
        break;

    /* We shouldn't get VOLUME, but the switch requires all cases */
    case VIR_STORAGE_TYPE_VOLUME:
    case VIR_STORAGE_TYPE_NONE:
    case VIR_STORAGE_TYPE_LAST:
        virReportError(VIR_ERR_INTERNAL_ERROR,
3772 3773 3774
                       _("cannot retrieve physical for path '%s' type '%s'"),
                       NULLSTR(src->path),
                       virStorageTypeToString(actual_type));
3775 3776
        return -1;
        break;
3777 3778
    }

3779
    return 0;
3780 3781 3782
}


3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847
/**
 * @src: disk source definition structure
 * @fd: file descriptor
 * @sb: stat buffer
 *
 * Update the capacity, allocation, physical values for the storage @src
 * Shared between the domain storage source for an inactive domain and the
 * voldef source target as the result is not affected by the 'type' field.
 *
 * Returns 0 on success, -1 on error.
 */
int
virStorageSourceUpdateBackingSizes(virStorageSourcePtr src,
                                   int fd,
                                   struct stat const *sb)
{
    /* Get info for normal formats */
    if (S_ISREG(sb->st_mode) || fd == -1) {
#ifndef WIN32
        src->allocation = (unsigned long long)sb->st_blocks *
            (unsigned long long)DEV_BSIZE;
#else
        src->allocation = sb->st_size;
#endif
        /* Regular files may be sparse, so logical size (capacity) is not same
         * as actual allocation above
         */
        src->capacity = sb->st_size;

        /* Allocation tracks when the file is sparse, physical is the
         * last offset of the file. */
        src->physical = sb->st_size;
    } else if (S_ISDIR(sb->st_mode)) {
        src->allocation = 0;
        src->capacity = 0;
        src->physical = 0;
    } 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
         *
         * NB. Because we configure with AC_SYS_LARGEFILE, off_t
         * should be 64 bits on all platforms.  For block devices, we
         * have to seek (safe even if someone else is writing) to
         * determine physical size, and assume that allocation is the
         * same as physical (but can refine that assumption later if
         * qemu is still running).
         */
        if ((end = lseek(fd, 0, SEEK_END)) == (off_t)-1) {
            virReportSystemError(errno,
                                 _("failed to seek to end of %s"), src->path);
            return -1;
        }
        src->physical = end;
        src->allocation = end;
        src->capacity = end;
    }

    return 0;
}


3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865
/**
 * @src: disk source definition structure
 * @buf: buffer to the storage file header
 * @len: length of the storage file header
 * @probe: allow probe
 *
 * Update the storage @src capacity. This may involve probing the storage
 * @src in order to "see" if we can recognize what exists.
 *
 * Returns 0 on success, -1 on error.
 */
int
virStorageSourceUpdateCapacity(virStorageSourcePtr src,
                               char *buf,
                               ssize_t len,
                               bool probe)
{
    int format = src->format;
3866
    VIR_AUTOUNREF(virStorageSourcePtr) meta = NULL;
3867 3868 3869 3870 3871 3872 3873 3874 3875

    /* Raw files: capacity is physical size.  For all other files: if
     * the metadata has a capacity, use that, otherwise fall back to
     * physical size.  */
    if (format == VIR_STORAGE_FILE_NONE) {
        if (!probe) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("no disk format for %s and probing is disabled"),
                           src->path);
3876
            return -1;
3877 3878 3879 3880
        }

        if ((format = virStorageFileProbeFormatFromBuf(src->path,
                                                       buf, len)) < 0)
3881
            return -1;
3882 3883 3884 3885

        src->format = format;
    }

3886
    if (format == VIR_STORAGE_FILE_RAW && !src->encryption) {
3887
        src->capacity = src->physical;
3888 3889
    } else if ((meta = virStorageFileGetMetadataFromBuf(src->path, buf,
                                                        len, format, NULL))) {
3890
        src->capacity = meta->capacity ? meta->capacity : src->physical;
3891 3892 3893
        if (src->encryption && meta->encryption)
            src->encryption->payload_offset = meta->encryption->payload_offset;
    } else {
3894
        return -1;
3895
    }
3896

3897 3898 3899
    if (src->encryption && src->encryption->payload_offset != -1)
        src->capacity -= src->encryption->payload_offset * 512;

3900
    return 0;
3901 3902 3903
}


3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926
static char *
virStorageFileCanonicalizeFormatPath(char **components,
                                     size_t ncomponents,
                                     bool beginSlash,
                                     bool beginDoubleSlash)
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    size_t i;
    char *ret = NULL;

    if (beginSlash)
        virBufferAddLit(&buf, "/");

    if (beginDoubleSlash)
        virBufferAddLit(&buf, "/");

    for (i = 0; i < ncomponents; i++) {
        if (i != 0)
            virBufferAddLit(&buf, "/");

        virBufferAdd(&buf, components[i], -1);
    }

3927
    if (virBufferCheckError(&buf) < 0)
3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962
        return NULL;

    /* if the output string is empty just return an empty string */
    if (!(ret = virBufferContentAndReset(&buf)))
        ignore_value(VIR_STRDUP(ret, ""));

    return ret;
}


static int
virStorageFileCanonicalizeInjectSymlink(const char *path,
                                        size_t at,
                                        char ***components,
                                        size_t *ncomponents)
{
    char **tmp = NULL;
    char **next;
    size_t ntmp = 0;
    int ret = -1;

    if (!(tmp = virStringSplitCount(path, "/", 0, &ntmp)))
        goto cleanup;

    /* prepend */
    for (next = tmp; *next; next++) {
        if (VIR_INSERT_ELEMENT(*components, at, *ncomponents, *next) < 0)
            goto cleanup;

        at++;
    }

    ret = 0;

 cleanup:
3963
    virStringListFreeCount(tmp, ntmp);
3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981
    return ret;
}


char *
virStorageFileCanonicalizePath(const char *path,
                               virStorageFileSimplifyPathReadlinkCallback cb,
                               void *cbdata)
{
    virHashTablePtr cycle = NULL;
    bool beginSlash = false;
    bool beginDoubleSlash = false;
    char **components = NULL;
    size_t ncomponents = 0;
    size_t i = 0;
    size_t j = 0;
    int rc;
    char *ret = NULL;
3982 3983
    VIR_AUTOFREE(char *) linkpath = NULL;
    VIR_AUTOFREE(char *) currentpath = NULL;
3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110

    if (path[0] == '/') {
        beginSlash = true;

        if (path[1] == '/' && path[2] != '/')
            beginDoubleSlash = true;
    }

    if (!(cycle = virHashCreate(10, NULL)))
        goto cleanup;

    if (!(components = virStringSplitCount(path, "/", 0, &ncomponents)))
        goto cleanup;

    j = 0;
    while (j < ncomponents) {
        /* skip slashes */
        if (STREQ(components[j], "")) {
            VIR_FREE(components[j]);
            VIR_DELETE_ELEMENT(components, j, ncomponents);
            continue;
        }
        j++;
    }

    while (i < ncomponents) {
        /* skip '.'s unless it's the last one remaining */
        if (STREQ(components[i], ".") &&
            (beginSlash || ncomponents  > 1)) {
            VIR_FREE(components[i]);
            VIR_DELETE_ELEMENT(components, i, ncomponents);
            continue;
        }

        /* resolve changes to parent directory */
        if (STREQ(components[i], "..")) {
            if (!beginSlash &&
                (i == 0 || STREQ(components[i - 1], ".."))) {
                i++;
                continue;
            }

            VIR_FREE(components[i]);
            VIR_DELETE_ELEMENT(components, i, ncomponents);

            if (i != 0) {
                VIR_FREE(components[i - 1]);
                VIR_DELETE_ELEMENT(components, i - 1, ncomponents);
                i--;
            }

            continue;
        }

        /* check if the actual path isn't resulting into a symlink */
        if (!(currentpath = virStorageFileCanonicalizeFormatPath(components,
                                                                 i + 1,
                                                                 beginSlash,
                                                                 beginDoubleSlash)))
            goto cleanup;

        if ((rc = cb(currentpath, &linkpath, cbdata)) < 0)
            goto cleanup;

        if (rc == 0) {
            if (virHashLookup(cycle, currentpath)) {
                virReportSystemError(ELOOP,
                                     _("Failed to canonicalize path '%s'"), path);
                goto cleanup;
            }

            if (virHashAddEntry(cycle, currentpath, (void *) 1) < 0)
                goto cleanup;

            if (linkpath[0] == '/') {
                /* kill everything from the beginning including the actual component */
                i++;
                while (i--) {
                    VIR_FREE(components[0]);
                    VIR_DELETE_ELEMENT(components, 0, ncomponents);
                }
                beginSlash = true;

                if (linkpath[1] == '/' && linkpath[2] != '/')
                    beginDoubleSlash = true;
                else
                    beginDoubleSlash = false;

                i = 0;
            } else {
                VIR_FREE(components[i]);
                VIR_DELETE_ELEMENT(components, i, ncomponents);
            }

            if (virStorageFileCanonicalizeInjectSymlink(linkpath,
                                                        i,
                                                        &components,
                                                        &ncomponents) < 0)
                goto cleanup;

            j = 0;
            while (j < ncomponents) {
                /* skip slashes */
                if (STREQ(components[j], "")) {
                    VIR_FREE(components[j]);
                    VIR_DELETE_ELEMENT(components, j, ncomponents);
                    continue;
                }
                j++;
            }

            VIR_FREE(linkpath);
            VIR_FREE(currentpath);

            continue;
        }

        VIR_FREE(currentpath);

        i++;
    }

    ret = virStorageFileCanonicalizeFormatPath(components, ncomponents,
                                               beginSlash, beginDoubleSlash);

 cleanup:
    virHashFree(cycle);
4111
    virStringListFreeCount(components, ncomponents);
4112 4113 4114

    return ret;
}
4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130


/**
 * virStorageFileRemoveLastPathComponent:
 *
 * @path: Path string to remove the last component from
 *
 * Removes the last path component of a path. This function is designed to be
 * called on file paths only (no trailing slashes in @path). Caller is
 * responsible to free the returned string.
 */
static char *
virStorageFileRemoveLastPathComponent(const char *path)
{
    char *ret;

J
Ján Tomko 已提交
4131
    if (VIR_STRDUP(ret, NULLSTR_EMPTY(path)) < 0)
4132 4133
        return NULL;

4134
    virFileRemoveLastComponent(ret);
4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153

    return ret;
}


/*
 * virStorageFileGetRelativeBackingPath:
 *
 * Resolve relative path to be written to the overlay of @top image when
 * collapsing the backing chain between @top and @base.
 *
 * Returns 0 on success; 1 if backing chain isn't relative and -1 on error.
 */
int
virStorageFileGetRelativeBackingPath(virStorageSourcePtr top,
                                     virStorageSourcePtr base,
                                     char **relpath)
{
    virStorageSourcePtr next;
4154 4155
    VIR_AUTOFREE(char *) tmp = NULL;
    VIR_AUTOFREE(char *) path = NULL;
4156 4157 4158

    *relpath = NULL;

4159
    for (next = top; virStorageSourceIsBacking(next); next = next->backingStore) {
4160 4161
        if (!next->relPath)
            return 1;
4162 4163

        if (!(tmp = virStorageFileRemoveLastPathComponent(path)))
4164
            return -1;
4165 4166 4167 4168

        VIR_FREE(path);

        if (virAsprintf(&path, "%s%s", tmp, next->relPath) < 0)
4169
            return -1;
4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180

        VIR_FREE(tmp);

        if (next == base)
            break;
    }

    if (next != base) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("failed to resolve relative backing name: "
                         "base image is not in backing chain"));
4181
        return -1;
4182 4183
    }

4184
    VIR_STEAL_PTR(*relpath, path);
4185
    return 0;
4186
}
4187 4188 4189 4190 4191 4192 4193 4194 4195


/*
 * virStorageFileCheckCompat
 */
int
virStorageFileCheckCompat(const char *compat)
{
    unsigned int result;
4196
    VIR_AUTOSTRINGLIST version = NULL;
4197 4198 4199 4200 4201 4202 4203 4204 4205 4206

    if (!compat)
        return 0;

    version = virStringSplit(compat, ".", 2);
    if (!version || !version[1] ||
        virStrToLong_ui(version[0], NULL, 10, &result) < 0 ||
        virStrToLong_ui(version[1], NULL, 10, &result) < 0) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("forbidden characters in 'compat' attribute"));
4207
        return -1;
4208
    }
4209
    return 0;
4210
}
4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241


/**
 * virStorageSourceIsRelative:
 * @src: storage source to check
 *
 * Returns true if given storage source definition is a relative path.
 */
bool
virStorageSourceIsRelative(virStorageSourcePtr src)
{
    virStorageType actual_type = virStorageSourceGetActualType(src);

    if (!src->path)
        return false;

    switch (actual_type) {
    case VIR_STORAGE_TYPE_FILE:
    case VIR_STORAGE_TYPE_BLOCK:
    case VIR_STORAGE_TYPE_DIR:
        return src->path[0] != '/';

    case VIR_STORAGE_TYPE_NETWORK:
    case VIR_STORAGE_TYPE_VOLUME:
    case VIR_STORAGE_TYPE_NONE:
    case VIR_STORAGE_TYPE_LAST:
        return false;
    }

    return false;
}
4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256


/**
 * virStorageSourceFindByNodeName:
 * @top: backing chain top
 * @nodeName: node name to find in backing chain
 * @index: if provided the index in the backing chain
 *
 * Looks up the given storage source in the backing chain and returns the
 * pointer to it. If @index is passed then it's filled by the index in the
 * backing chain. On failure NULL is returned and no error is reported.
 */
virStorageSourcePtr
virStorageSourceFindByNodeName(virStorageSourcePtr top,
                               const char *nodeName,
E
Eric Blake 已提交
4257
                               unsigned int *idx)
4258 4259 4260
{
    virStorageSourcePtr tmp;

E
Eric Blake 已提交
4261 4262
    if (idx)
        *idx = 0;
4263

4264
    for (tmp = top; virStorageSourceIsBacking(tmp); tmp = tmp->backingStore) {
4265
        if ((tmp->nodeformat && STREQ(tmp->nodeformat, nodeName)) ||
4266
            (tmp->nodestorage && STREQ(tmp->nodestorage, nodeName)))
4267 4268
            return tmp;

E
Eric Blake 已提交
4269 4270
        if (idx)
            (*idx)++;
4271 4272
    }

E
Eric Blake 已提交
4273 4274
    if (idx)
        *idx = 0;
4275 4276
    return NULL;
}
4277 4278


4279
static unsigned int
4280 4281 4282 4283
virStorageSourceNetworkDefaultPort(virStorageNetProtocol protocol)
{
    switch (protocol) {
        case VIR_STORAGE_NET_PROTOCOL_HTTP:
4284
            return 80;
4285 4286

        case VIR_STORAGE_NET_PROTOCOL_HTTPS:
4287
            return 443;
4288 4289

        case VIR_STORAGE_NET_PROTOCOL_FTP:
4290
            return 21;
4291 4292

        case VIR_STORAGE_NET_PROTOCOL_FTPS:
4293
            return 990;
4294 4295

        case VIR_STORAGE_NET_PROTOCOL_TFTP:
4296
            return 69;
4297 4298

        case VIR_STORAGE_NET_PROTOCOL_SHEEPDOG:
4299
            return 7000;
4300 4301

        case VIR_STORAGE_NET_PROTOCOL_NBD:
4302
            return 10809;
4303 4304

        case VIR_STORAGE_NET_PROTOCOL_SSH:
4305
            return 22;
4306 4307

        case VIR_STORAGE_NET_PROTOCOL_ISCSI:
4308
            return 3260;
4309

4310
        case VIR_STORAGE_NET_PROTOCOL_GLUSTER:
4311
            return 24007;
4312 4313

        case VIR_STORAGE_NET_PROTOCOL_RBD:
4314
            /* we don't provide a default for RBD */
4315
            return 0;
4316

4317
        case VIR_STORAGE_NET_PROTOCOL_VXHS:
4318 4319
            return 9999;

4320 4321
        case VIR_STORAGE_NET_PROTOCOL_LAST:
        case VIR_STORAGE_NET_PROTOCOL_NONE:
4322
            return 0;
4323 4324
    }

4325
    return 0;
4326
}
4327 4328


4329
void
4330 4331 4332 4333 4334 4335
virStorageSourceNetworkAssignDefaultPorts(virStorageSourcePtr src)
{
    size_t i;

    for (i = 0; i < src->nhosts; i++) {
        if (src->hosts[i].transport == VIR_STORAGE_NET_HOST_TRANS_TCP &&
4336 4337
            src->hosts[i].port == 0)
            src->hosts[i].port = virStorageSourceNetworkDefaultPort(src->protocol);
4338 4339
    }
}
4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359


int
virStorageSourcePrivateDataParseRelPath(xmlXPathContextPtr ctxt,
                                        virStorageSourcePtr src)
{
    src->relPath = virXPathString("string(./relPath)", ctxt);
    return 0;
}


int
virStorageSourcePrivateDataFormatRelPath(virStorageSourcePtr src,
                                         virBufferPtr buf)
{
    if (src->relPath)
        virBufferEscapeString(buf, "<relPath>%s</relPath>\n", src->relPath);

    return 0;
}
4360

4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394
void
virStorageSourceInitiatorParseXML(xmlXPathContextPtr ctxt,
                                  virStorageSourceInitiatorDefPtr initiator)
{
    initiator->iqn = virXPathString("string(./initiator/iqn/@name)", ctxt);
}

void
virStorageSourceInitiatorFormatXML(virStorageSourceInitiatorDefPtr initiator,
                                   virBufferPtr buf)
{
    if (!initiator->iqn)
        return;

    virBufferAddLit(buf, "<initiator>\n");
    virBufferAdjustIndent(buf, 2);
    virBufferEscapeString(buf, "<iqn name='%s'/>\n", initiator->iqn);
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</initiator>\n");
}

int
virStorageSourceInitiatorCopy(virStorageSourceInitiatorDefPtr dest,
                              const virStorageSourceInitiatorDef *src)
{
    return VIR_STRDUP(dest->iqn, src->iqn);
}

void
virStorageSourceInitiatorClear(virStorageSourceInitiatorDefPtr initiator)
{
    VIR_FREE(initiator->iqn);
}

4395 4396 4397 4398 4399 4400 4401
static bool
virStorageFileIsInitialized(const virStorageSource *src)
{
    return src && src->drv;
}


4402 4403 4404
static int
virStorageFileGetBackendForSupportCheck(const virStorageSource *src,
                                        virStorageFileBackendPtr *backend)
4405 4406 4407 4408
{
    int actualType;


4409 4410 4411 4412 4413 4414 4415 4416 4417
    if (!src) {
        *backend = NULL;
        return 0;
    }

    if (src->drv) {
        *backend = src->drv->backend;
        return 0;
    }
4418 4419 4420

    actualType = virStorageSourceGetActualType(src);

4421 4422 4423
    if (virStorageFileBackendForType(actualType, src->protocol, false, backend) < 0)
        return -1;

4424
    return 0;
4425 4426 4427
}


4428
static int
4429 4430 4431
virStorageFileSupportsBackingChainTraversal(virStorageSourcePtr src)
{
    virStorageFileBackendPtr backend;
4432
    int rv;
4433

4434 4435 4436 4437 4438 4439
    rv = virStorageFileGetBackendForSupportCheck(src, &backend);
    if (rv < 0)
        return -1;

    if (!backend)
        return 0;
4440 4441 4442

    return backend->storageFileGetUniqueIdentifier &&
           backend->storageFileRead &&
4443
           backend->storageFileAccess ? 1 : 0;
4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454
}


/**
 * virStorageFileSupportsSecurityDriver:
 *
 * @src: a storage file structure
 *
 * Check if a storage file supports operations needed by the security
 * driver to perform labelling
 */
4455
int
4456 4457 4458
virStorageFileSupportsSecurityDriver(const virStorageSource *src)
{
    virStorageFileBackendPtr backend;
4459
    int rv;
4460

4461 4462 4463 4464 4465
    rv = virStorageFileGetBackendForSupportCheck(src, &backend);
    if (rv < 0)
        return -1;
    if (backend == NULL)
        return 0;
4466

4467
    return backend->storageFileChown ? 1 : 0;
4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478
}


/**
 * virStorageFileSupportsAccess:
 *
 * @src: a storage file structure
 *
 * Check if a storage file supports checking if the storage source is accessible
 * for the given vm.
 */
4479
int
4480 4481 4482
virStorageFileSupportsAccess(const virStorageSource *src)
{
    virStorageFileBackendPtr backend;
4483
    int ret;
4484

4485 4486 4487 4488 4489
    ret = virStorageFileGetBackendForSupportCheck(src, &backend);
    if (ret < 0)
        return -1;
    if (backend == NULL)
        return 0;
4490

4491
    return backend->storageFileAccess ? 1 : 0;
4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539
}


void
virStorageFileDeinit(virStorageSourcePtr src)
{
    if (!virStorageFileIsInitialized(src))
        return;

    if (src->drv->backend &&
        src->drv->backend->backendDeinit)
        src->drv->backend->backendDeinit(src);

    VIR_FREE(src->drv);
}


/**
 * virStorageFileInitAs:
 *
 * @src: storage source definition
 * @uid: uid used to access the file, or -1 for current uid
 * @gid: gid used to access the file, or -1 for current gid
 *
 * Initialize a storage source to be used with storage driver. Use the provided
 * uid and gid if possible for the operations.
 *
 * Returns 0 if the storage file was successfully initialized, -1 if the
 * initialization failed. Libvirt error is reported.
 */
int
virStorageFileInitAs(virStorageSourcePtr src,
                     uid_t uid, gid_t gid)
{
    int actualType = virStorageSourceGetActualType(src);
    if (VIR_ALLOC(src->drv) < 0)
        return -1;

    if (uid == (uid_t) -1)
        src->drv->uid = geteuid();
    else
        src->drv->uid = uid;

    if (gid == (gid_t) -1)
        src->drv->gid = getegid();
    else
        src->drv->gid = gid;

4540 4541 4542 4543
    if (virStorageFileBackendForType(actualType,
                                     src->protocol,
                                     true,
                                     &src->drv->backend) < 0)
4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684
        goto error;

    if (src->drv->backend->backendInit &&
        src->drv->backend->backendInit(src) < 0)
        goto error;

    return 0;

 error:
    VIR_FREE(src->drv);
    return -1;
}


/**
 * virStorageFileInit:
 *
 * See virStorageFileInitAs. The file is initialized to be accessed by the
 * current user.
 */
int
virStorageFileInit(virStorageSourcePtr src)
{
    return virStorageFileInitAs(src, -1, -1);
}


/**
 * virStorageFileCreate: Creates an empty storage file via storage driver
 *
 * @src: file structure pointing to the file
 *
 * Returns 0 on success, -2 if the function isn't supported by the backend,
 * -1 on other failure. Errno is set in case of failure.
 */
int
virStorageFileCreate(virStorageSourcePtr src)
{
    int ret;

    if (!virStorageFileIsInitialized(src) ||
        !src->drv->backend->storageFileCreate) {
        errno = ENOSYS;
        return -2;
    }

    ret = src->drv->backend->storageFileCreate(src);

    VIR_DEBUG("created storage file %p: ret=%d, errno=%d",
              src, ret, errno);

    return ret;
}


/**
 * virStorageFileUnlink: Unlink storage file via storage driver
 *
 * @src: file structure pointing to the file
 *
 * Unlinks the file described by the @file structure.
 *
 * Returns 0 on success, -2 if the function isn't supported by the backend,
 * -1 on other failure. Errno is set in case of failure.
 */
int
virStorageFileUnlink(virStorageSourcePtr src)
{
    int ret;

    if (!virStorageFileIsInitialized(src) ||
        !src->drv->backend->storageFileUnlink) {
        errno = ENOSYS;
        return -2;
    }

    ret = src->drv->backend->storageFileUnlink(src);

    VIR_DEBUG("unlinked storage file %p: ret=%d, errno=%d",
              src, ret, errno);

    return ret;
}


/**
 * virStorageFileStat: returns stat struct of a file via storage driver
 *
 * @src: file structure pointing to the file
 * @stat: stat structure to return data
 *
 * Returns 0 on success, -2 if the function isn't supported by the backend,
 * -1 on other failure. Errno is set in case of failure.
*/
int
virStorageFileStat(virStorageSourcePtr src,
                   struct stat *st)
{
    int ret;

    if (!virStorageFileIsInitialized(src) ||
        !src->drv->backend->storageFileStat) {
        errno = ENOSYS;
        return -2;
    }

    ret = src->drv->backend->storageFileStat(src, st);

    VIR_DEBUG("stat of storage file %p: ret=%d, errno=%d",
              src, ret, errno);

    return ret;
}


/**
 * virStorageFileRead: read bytes from a file into a buffer
 *
 * @src: file structure pointing to the file
 * @offset: number of bytes to skip in the storage file
 * @len: maximum number of bytes read from the storage file
 * @buf: buffer to read the data into. (buffer shall be freed by caller)
 *
 * Returns the count of bytes read on success and -1 on failure, -2 if the
 * function isn't supported by the backend.
 * Libvirt error is reported on failure.
 */
ssize_t
virStorageFileRead(virStorageSourcePtr src,
                   size_t offset,
                   size_t len,
                   char **buf)
{
    ssize_t ret;

    if (!virStorageFileIsInitialized(src)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("storage file backend not initialized"));
        return -1;
    }

4685
    if (!src->drv->backend->storageFileRead)
4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716
        return -2;

    ret = src->drv->backend->storageFileRead(src, offset, len, buf);

    VIR_DEBUG("read '%zd' bytes from storage '%p' starting at offset '%zu'",
              ret, src, offset);

    return ret;
}


/*
 * virStorageFileGetUniqueIdentifier: Get a unique string describing the volume
 *
 * @src: file structure pointing to the file
 *
 * Returns a string uniquely describing a single volume (canonical path).
 * The string shall not be freed and is valid until the storage file is
 * deinitialized. Returns NULL on error and sets a libvirt error code */
const char *
virStorageFileGetUniqueIdentifier(virStorageSourcePtr src)
{
    if (!virStorageFileIsInitialized(src)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("storage file backend not initialized"));
        return NULL;
    }

    if (!src->drv->backend->storageFileGetUniqueIdentifier) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unique storage file identifier not implemented for "
4717
                         "storage type %s (protocol: %s)'"),
4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837
                       virStorageTypeToString(src->type),
                       virStorageNetProtocolTypeToString(src->protocol));
        return NULL;
    }

    return src->drv->backend->storageFileGetUniqueIdentifier(src);
}


/**
 * virStorageFileAccess: Check accessibility of a storage file
 *
 * @src: storage file to check access permissions
 * @mode: accessibility check options (see man 2 access)
 *
 * Returns 0 on success, -1 on error and sets errno. No libvirt
 * error is reported. Returns -2 if the operation isn't supported
 * by libvirt storage backend.
 */
int
virStorageFileAccess(virStorageSourcePtr src,
                     int mode)
{
    if (!virStorageFileIsInitialized(src) ||
        !src->drv->backend->storageFileAccess) {
        errno = ENOSYS;
        return -2;
    }

    return src->drv->backend->storageFileAccess(src, mode);
}


/**
 * virStorageFileChown: Change owner of a storage file
 *
 * @src: storage file to change owner of
 * @uid: new owner id
 * @gid: new group id
 *
 * Returns 0 on success, -1 on error and sets errno. No libvirt
 * error is reported. Returns -2 if the operation isn't supported
 * by libvirt storage backend.
 */
int
virStorageFileChown(const virStorageSource *src,
                    uid_t uid,
                    gid_t gid)
{
    if (!virStorageFileIsInitialized(src) ||
        !src->drv->backend->storageFileChown) {
        errno = ENOSYS;
        return -2;
    }

    VIR_DEBUG("chown of storage file %p to %u:%u",
              src, (unsigned int)uid, (unsigned int)gid);

    return src->drv->backend->storageFileChown(src, uid, gid);
}


/**
 * virStorageFileReportBrokenChain:
 *
 * @errcode: errno when accessing @src
 * @src: inaccessible file in the backing chain of @parent
 * @parent: root virStorageSource being checked
 *
 * Reports the correct error message if @src is missing in the backing chain
 * for @parent.
 */
void
virStorageFileReportBrokenChain(int errcode,
                                virStorageSourcePtr src,
                                virStorageSourcePtr parent)
{
    if (src->drv) {
        unsigned int access_user = src->drv->uid;
        unsigned int access_group = src->drv->gid;

        if (src == parent) {
            virReportSystemError(errcode,
                                 _("Cannot access storage file '%s' "
                                   "(as uid:%u, gid:%u)"),
                                 src->path, access_user, access_group);
        } else {
            virReportSystemError(errcode,
                                 _("Cannot access backing file '%s' "
                                   "of storage file '%s' (as uid:%u, gid:%u)"),
                                 src->path, parent->path, access_user, access_group);
        }
    } else {
        if (src == parent) {
            virReportSystemError(errcode,
                                 _("Cannot access storage file '%s'"),
                                 src->path);
        } else {
            virReportSystemError(errcode,
                                 _("Cannot access backing file '%s' "
                                   "of storage file '%s'"),
                                 src->path, parent->path);
        }
    }
}


/* Recursive workhorse for virStorageFileGetMetadata.  */
static int
virStorageFileGetMetadataRecurse(virStorageSourcePtr src,
                                 virStorageSourcePtr parent,
                                 uid_t uid, gid_t gid,
                                 bool report_broken,
                                 virHashTablePtr cycle,
                                 unsigned int depth)
{
    int ret = -1;
    const char *uniqueName;
    ssize_t headerLen;
    int backingFormat;
4838
    int rv;
4839
    VIR_AUTOFREE(char *) buf = NULL;
4840
    VIR_AUTOUNREF(virStorageSourcePtr) backingStore = NULL;
4841

4842
    VIR_DEBUG("path=%s format=%d uid=%u gid=%u",
4843
              src->path, src->format,
4844
              (unsigned int)uid, (unsigned int)gid);
4845 4846

    /* exit if we can't load information about the current image */
4847 4848 4849
    rv = virStorageFileSupportsBackingChainTraversal(src);
    if (rv <= 0)
        return rv;
4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872

    if (virStorageFileInitAs(src, uid, gid) < 0)
        return -1;

    if (virStorageFileAccess(src, F_OK) < 0) {
        virStorageFileReportBrokenChain(errno, src, parent);
        goto cleanup;
    }

    if (!(uniqueName = virStorageFileGetUniqueIdentifier(src)))
        goto cleanup;

    if (virHashLookup(cycle, uniqueName)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("backing store for %s (%s) is self-referential"),
                       src->path, uniqueName);
        goto cleanup;
    }

    if (virHashAddEntry(cycle, uniqueName, (void *)1) < 0)
        goto cleanup;

    if ((headerLen = virStorageFileRead(src, 0, VIR_STORAGE_MAX_HEADER,
4873 4874 4875 4876 4877 4878 4879
                                        &buf)) < 0) {
        if (headerLen == -2)
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("storage file reading is not supported for "
                             "storage type %s (protocol: %s)"),
                           virStorageTypeToString(src->type),
                           virStorageNetProtocolTypeToString(src->protocol));
4880
        goto cleanup;
4881
    }
4882 4883 4884 4885 4886 4887 4888 4889 4890

    if (virStorageFileGetMetadataInternal(src, buf, headerLen,
                                          &backingFormat) < 0)
        goto cleanup;

    if (src->backingStoreRaw) {
        if (!(backingStore = virStorageSourceNewFromBacking(src)))
            goto cleanup;

4891
        if (backingFormat == VIR_STORAGE_FILE_AUTO)
4892 4893 4894 4895 4896 4897 4898 4899
            backingStore->format = VIR_STORAGE_FILE_RAW;
        else if (backingFormat == VIR_STORAGE_FILE_AUTO_SAFE)
            backingStore->format = VIR_STORAGE_FILE_AUTO;
        else
            backingStore->format = backingFormat;

        if ((ret = virStorageFileGetMetadataRecurse(backingStore, parent,
                                                    uid, gid,
4900
                                                    report_broken,
4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911
                                                    cycle, depth + 1)) < 0) {
            if (report_broken)
                goto cleanup;

            /* if we fail somewhere midway, just accept and return a
             * broken chain */
            ret = 0;
            goto cleanup;
        }
    } else {
        /* add terminator */
4912
        if (!(backingStore = virStorageSourceNew()))
4913 4914 4915
            goto cleanup;
    }

4916
    VIR_STEAL_PTR(src->backingStore, backingStore);
4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944
    ret = 0;

 cleanup:
    if (virStorageSourceHasBacking(src))
        src->backingStore->id = depth;
    virStorageFileDeinit(src);
    return ret;
}


/**
 * virStorageFileGetMetadata:
 *
 * Extract metadata about the storage volume with the specified
 * image format. If image format is VIR_STORAGE_FILE_AUTO, it
 * will probe to automatically identify the format.  Recurses through
 * the entire chain.
 *
 * Open files using UID and GID (or pass -1 for the current user/group).
 * Treat any backing files without explicit type as raw, unless ALLOW_PROBE.
 *
 * Callers are advised never to use VIR_STORAGE_FILE_AUTO as a
 * format, since a malicious guest can turn a raw file into any
 * other non-raw format at will.
 *
 * If @report_broken is true, the whole function fails with a possibly sane
 * error instead of just returning a broken chain.
 *
4945
 * Caller MUST free result after use via virObjectUnref.
4946 4947 4948 4949 4950 4951
 */
int
virStorageFileGetMetadata(virStorageSourcePtr src,
                          uid_t uid, gid_t gid,
                          bool report_broken)
{
4952
    VIR_DEBUG("path=%s format=%d uid=%u gid=%u report_broken=%d",
4953
              src->path, src->format, (unsigned int)uid, (unsigned int)gid,
4954
              report_broken);
4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970

    virHashTablePtr cycle = NULL;
    virStorageType actualType = virStorageSourceGetActualType(src);
    int ret = -1;

    if (!(cycle = virHashCreate(5, NULL)))
        return -1;

    if (src->format <= VIR_STORAGE_FILE_NONE) {
        if (actualType == VIR_STORAGE_TYPE_DIR)
            src->format = VIR_STORAGE_FILE_DIR;
        else
            src->format = VIR_STORAGE_FILE_RAW;
    }

    ret = virStorageFileGetMetadataRecurse(src, src, uid, gid,
4971
                                           report_broken, cycle, 1);
4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986

    virHashFree(cycle);
    return ret;
}


/**
 * virStorageFileGetBackingStoreStr:
 * @src: storage object
 *
 * Extracts the backing store string as stored in the storage volume described
 * by @src and returns it to the user. Caller is responsible for freeing it.
 * In case when the string can't be retrieved or does not exist NULL is
 * returned.
 */
4987 4988 4989
int
virStorageFileGetBackingStoreStr(virStorageSourcePtr src,
                                 char **backing)
4990 4991
{
    ssize_t headerLen;
4992
    int rv;
4993
    VIR_AUTOFREE(char *) buf = NULL;
4994
    VIR_AUTOUNREF(virStorageSourcePtr) tmp = NULL;
4995 4996

    *backing = NULL;
4997 4998 4999

    /* exit if we can't load information about the current image */
    if (!virStorageFileSupportsBackingChainTraversal(src))
5000
        return 0;
5001

5002 5003 5004 5005 5006 5007 5008
    rv = virStorageFileAccess(src, F_OK);
    if (rv == -2)
        return 0;
    if (rv < 0) {
        virStorageFileReportBrokenChain(errno, src, src);
        return -1;
    }
5009 5010

    if ((headerLen = virStorageFileRead(src, 0, VIR_STORAGE_MAX_HEADER,
5011 5012 5013 5014 5015
                                        &buf)) < 0) {
        if (headerLen == -2)
            return 0;
        return -1;
    }
5016 5017

    if (!(tmp = virStorageSourceCopy(src, false)))
5018
        return -1;
5019 5020

    if (virStorageFileGetMetadataInternal(tmp, buf, headerLen, NULL) < 0)
5021
        return -1;
5022

5023
    VIR_STEAL_PTR(*backing, tmp->backingStoreRaw);
5024
    return 0;
5025
}