virstoragefile.c 153.0 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 "vircommand.h"
34
#include "virhash.h"
E
Eric Blake 已提交
35
#include "virendian.h"
36
#include "virstring.h"
37
#include "viruri.h"
38
#include "virbuffer.h"
39
#include "virjson.h"
40
#include "virstorageencryption.h"
41
#include "virsecret.h"
42
#include "virutil.h"
43 44 45

#define VIR_FROM_THIS VIR_FROM_STORAGE

46 47
VIR_LOG_INIT("util.storagefile");

48 49
static virClassPtr virStorageSourceClass;

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

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

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

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

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

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

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

114 115 116 117 118 119 120 121 122 123 124
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 已提交
125
#define FILE_TYPE_VERSIONS_LAST 3
126

127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
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 */
145 146

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

149
struct FileTypeInfo {
150
    int magicOffset;    /* Byte offset of the magic */
151 152 153
    const char *magic;  /* Optional string of file magic
                         * to check at head of file */
    enum lv_endian endian; /* Endianness of file format */
154

155 156
    int versionOffset;    /* Byte offset from start of file
                           * where we find version number,
157 158
                           * -1 to always fail the version test,
                           * -2 to always pass the version test */
159
    int versionSize;      /* Size in bytes of version data (0, 2, or 4) */
160 161
    int versionNumbers[FILE_TYPE_VERSIONS_LAST];
                          /* Version numbers to validate. Zeroes are ignored. */
162 163 164 165 166 167 168 169
    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_* */
170
    const struct FileEncryptionInfo *cryptInfo; /* Encryption info */
171
    int (*getBackingStore)(char **res, int *format,
E
Eric Blake 已提交
172
                           const char *buf, size_t buf_size);
173
    int (*getFeatures)(virBitmapPtr *features, int format,
E
Eric Blake 已提交
174
                       char *buf, ssize_t len);
175 176
};

177

178
static int cowGetBackingStore(char **, int *,
E
Eric Blake 已提交
179
                              const char *, size_t);
180
static int qcowXGetBackingStore(char **, int *,
E
Eric Blake 已提交
181
                                const char *, size_t);
182
static int qcow2GetFeatures(virBitmapPtr *features, int format,
E
Eric Blake 已提交
183
                            char *buf, ssize_t len);
184
static int vmdk4GetBackingStore(char **, int *,
E
Eric Blake 已提交
185
                                const char *, size_t);
186
static int
E
Eric Blake 已提交
187
qedGetBackingStore(char **, int *, const char *, size_t);
188 189 190 191 192 193

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

194
#define QCOW1_HDR_CRYPT (QCOWX_HDR_IMAGE_SIZE+8+1+1+2)
195 196 197 198 199 200 201
#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
202
#define QCOW2_HDR_EXTENSION_DATA_FILE 0x44415441
203

204 205 206 207 208 209 210
#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)

211
#define QED_HDR_FEATURES_OFFSET (4+4+4+4)
212 213
#define QED_HDR_IMAGE_SIZE (QED_HDR_FEATURES_OFFSET+8+8+8+8)
#define QED_HDR_BACKING_FILE_OFFSET (QED_HDR_IMAGE_SIZE+8)
214 215 216
#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 已提交
217

218 219
#define PLOOP_IMAGE_SIZE_OFFSET 36
#define PLOOP_SIZE_MULTIPLIER 512
220

221 222
#define LUKS_HDR_MAGIC_LEN 6
#define LUKS_HDR_VERSION_LEN 2
223 224 225 226
#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
227 228 229

/* Format described by qemu commit id '3e308f20e' */
#define LUKS_HDR_VERSION_OFFSET LUKS_HDR_MAGIC_LEN
230 231 232 233 234
#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)
235

236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
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,
251 252

        .payloadOffset = LUKS_HDR_PAYLOAD_OFFSET,
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
    },
    { 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,
271 272

        .payloadOffset = -1,
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
    },
    { 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,
291 292

        .payloadOffset = -1,
293 294 295
    },
    { 0 }
};
296

297
static struct FileTypeInfo const fileTypeInfo[] = {
298
    [VIR_STORAGE_FILE_NONE] = { 0, NULL, LV_LITTLE_ENDIAN,
299
                                -1, 0, {0}, 0, 0, 0, NULL, NULL, NULL },
300
    [VIR_STORAGE_FILE_RAW] = { 0, NULL, LV_LITTLE_ENDIAN,
301 302 303
                               -1, 0, {0}, 0, 0, 0,
                               luksEncryptionInfo,
                               NULL, NULL },
304
    [VIR_STORAGE_FILE_DIR] = { 0, NULL, LV_LITTLE_ENDIAN,
305
                               -1, 0, {0}, 0, 0, 0, NULL, NULL, NULL },
306
    [VIR_STORAGE_FILE_BOCHS] = {
307
        /*"Bochs Virtual HD Image", */ /* Untested */
308
        0, NULL,
309
        LV_LITTLE_ENDIAN, 64, 4, {0x20000},
310
        32+16+16+4+4+4+4+4, 8, 1, NULL, NULL, NULL
311 312
    },
    [VIR_STORAGE_FILE_CLOOP] = {
313 314 315 316
        /* #!/bin/sh
           #V2.0 Format
           modprobe cloop file=$0 && mount -r -t iso9660 /dev/cloop $1
        */ /* Untested */
317
        0, NULL,
318
        LV_LITTLE_ENDIAN, -1, 0, {0},
319
        -1, 0, 0, NULL, NULL, NULL
320 321
    },
    [VIR_STORAGE_FILE_DMG] = {
322 323 324
        /* 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. */
325
        0, NULL,
326
        0, -1, 0, {0},
327
        -1, 0, 0, NULL, NULL, NULL
328 329
    },
    [VIR_STORAGE_FILE_ISO] = {
330
        32769, "CD001",
331
        LV_LITTLE_ENDIAN, -2, 0, {0},
332
        -1, 0, 0, NULL, NULL, NULL
333
    },
334
    [VIR_STORAGE_FILE_VPC] = {
335
        0, "conectix",
336
        LV_BIG_ENDIAN, 12, 4, {0x10000},
337
        8 + 4 + 4 + 8 + 4 + 4 + 2 + 2 + 4, 8, 1, NULL, NULL, NULL
338 339 340
    },
    /* TODO: add getBackingStore function */
    [VIR_STORAGE_FILE_VDI] = {
341
        64, "\x7f\x10\xda\xbe",
342
        LV_LITTLE_ENDIAN, 68, 4, {0x00010001},
343
        64 + 5 * 4 + 256 + 7 * 4, 8, 1, NULL, NULL, NULL},
344 345

    /* Not direct file formats, but used for various drivers */
346
    [VIR_STORAGE_FILE_FAT] = { 0, NULL, LV_LITTLE_ENDIAN,
347
                               -1, 0, {0}, 0, 0, 0, NULL, NULL, NULL },
348
    [VIR_STORAGE_FILE_VHD] = { 0, NULL, LV_LITTLE_ENDIAN,
349
                               -1, 0, {0}, 0, 0, 0, NULL, NULL, NULL },
350
    [VIR_STORAGE_FILE_PLOOP] = { 0, "WithouFreSpacExt", LV_LITTLE_ENDIAN,
351
                                 -2, 0, {0}, PLOOP_IMAGE_SIZE_OFFSET, 0,
352 353
                                 PLOOP_SIZE_MULTIPLIER, NULL, NULL, NULL },

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

389

390 391 392 393 394 395 396 397 398 399 400
/* 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,
};
401
G_STATIC_ASSERT(G_N_ELEMENTS(qcow2CompatibleFeatureArray) ==
402 403
       QCOW2_COMPATIBLE_FEATURE_LAST);

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

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

J
Ján Tomko 已提交
421
    *res = g_strndup((const char *)buf + 4 + 4, COW_FILENAME_MAXLEN);
422 423 424
    return BACKING_STORE_OK;
}

425 426

static int
427 428
qcow2GetExtensions(const char *buf,
                   size_t buf_size,
429 430
                   int *backingFormat,
                   char **externalDataStoreRaw)
431
{
432 433
    size_t offset;
    size_t extension_start;
434
    size_t extension_end;
435 436 437 438 439 440 441 442 443 444 445 446
    int version = virReadBufInt32BE(buf + QCOWX_HDR_VERSION);

    if (version < 2) {
        /* QCow1 doesn't have the extensions capability
         * used to store backing format */
        return 0;
    }

    if (version == 2)
        extension_start = QCOW2_HDR_TOTAL_SIZE;
    else
        extension_start = virReadBufInt32BE(buf + QCOW2v3_HDR_SIZE);
447

448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
    /*
     * 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)
     *
     * for qcow2 v3 images, the length of the header
     * is stored at QCOW2v3_HDR_SIZE
     */
    extension_end = virReadBufInt64BE(buf + QCOWX_HDR_BACKING_FILE_OFFSET);
    if (extension_end > buf_size)
        return -1;

479 480 481 482 483 484 485 486 487 488
    /*
     * 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.
     */
489
    offset = extension_start;
490 491
    while (offset < (buf_size-8) &&
           offset < (extension_end-8)) {
E
Eric Blake 已提交
492 493
        unsigned int magic = virReadBufInt32BE(buf + offset);
        unsigned int len = virReadBufInt32BE(buf + offset + 4);
494 495 496 497 498 499 500 501 502 503

        offset += 8;

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

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

        switch (magic) {
504
        case QCOW2_HDR_EXTENSION_BACKING_FORMAT: {
505
            g_autofree char *tmp = NULL;
506 507 508
            if (!backingFormat)
                break;

509 510 511 512
            if (VIR_ALLOC_N(tmp, len + 1) < 0)
                return -1;
            memcpy(tmp, buf + offset, len);
            tmp[len] = '\0';
513

514
            *backingFormat = virStorageFileFormatTypeFromString(tmp);
515
            if (*backingFormat <= VIR_STORAGE_FILE_NONE)
E
Eric Blake 已提交
516
                return -1;
517 518 519
            break;
        }

520 521 522 523 524 525 526 527 528 529 530 531 532
        case QCOW2_HDR_EXTENSION_DATA_FILE: {
            if (!externalDataStoreRaw)
                break;

            if (VIR_ALLOC_N(*externalDataStoreRaw, len + 1) < 0)
                return -1;
            memcpy(*externalDataStoreRaw, buf + offset, len);
            (*externalDataStoreRaw)[len] = '\0';
            VIR_DEBUG("parsed externalDataStoreRaw='%s'",
                      *externalDataStoreRaw);
            break;
        }

533
        case QCOW2_HDR_EXTENSION_END:
534
            return 0;
535 536 537 538 539 540 541 542 543
        }

        offset += len;
    }

    return 0;
}


544
static int
545
qcowXGetBackingStore(char **res,
546
                     int *format,
E
Eric Blake 已提交
547
                     const char *buf,
548
                     size_t buf_size)
549 550
{
    unsigned long long offset;
551
    unsigned int size;
552 553

    *res = NULL;
554
    *format = VIR_STORAGE_FILE_AUTO;
555 556

    if (buf_size < QCOWX_HDR_BACKING_FILE_OFFSET+8+4)
557
        return BACKING_STORE_INVALID;
558

E
Eric Blake 已提交
559
    offset = virReadBufInt64BE(buf + QCOWX_HDR_BACKING_FILE_OFFSET);
560 561
    if (offset > buf_size)
        return BACKING_STORE_INVALID;
562 563

    if (offset == 0) {
564
        *format = VIR_STORAGE_FILE_NONE;
565 566 567
        return BACKING_STORE_OK;
    }

E
Eric Blake 已提交
568
    size = virReadBufInt32BE(buf + QCOWX_HDR_BACKING_FILE_SIZE);
E
Eric Blake 已提交
569
    if (size == 0) {
570
        *format = VIR_STORAGE_FILE_NONE;
571
        return BACKING_STORE_OK;
E
Eric Blake 已提交
572
    }
573
    if (size > 1023)
574
        return BACKING_STORE_INVALID;
575
    if (offset + size > buf_size || offset + size < offset)
576
        return BACKING_STORE_INVALID;
577
    if (VIR_ALLOC_N(*res, size + 1) < 0)
578 579 580
        return BACKING_STORE_ERROR;
    memcpy(*res, buf + offset, size);
    (*res)[size] = '\0';
581

582
    if (qcow2GetExtensions(buf, buf_size, format, NULL) < 0)
583
        return BACKING_STORE_INVALID;
584

585 586 587 588 589
    return BACKING_STORE_OK;
}


static int
590
vmdk4GetBackingStore(char **res,
591
                     int *format,
E
Eric Blake 已提交
592
                     const char *buf,
593 594 595
                     size_t buf_size)
{
    static const char prefix[] = "parentFileNameHint=\"";
596
    char *start, *end;
597
    size_t len;
598
    g_autofree char *desc = NULL;
599

600
    if (VIR_ALLOC_N(desc, VIR_STORAGE_MAX_HEADER) < 0)
601
        return BACKING_STORE_ERROR;
602 603

    *res = NULL;
604 605
    /*
     * Technically this should have been VMDK, since
J
Ján Tomko 已提交
606
     * VMDK spec / VMware impl only support VMDK backed
607 608 609 610 611
     * by VMDK. QEMU isn't following this though and
     * does probing on VMDK backing files, hence we set
     * AUTO
     */
    *format = VIR_STORAGE_FILE_AUTO;
612

613 614 615
    if (buf_size <= 0x200)
        return BACKING_STORE_INVALID;

616
    len = buf_size - 0x200;
617 618
    if (len > VIR_STORAGE_MAX_HEADER)
        len = VIR_STORAGE_MAX_HEADER;
619 620 621
    memcpy(desc, buf + 0x200, len);
    desc[len] = '\0';
    start = strstr(desc, prefix);
622
    if (start == NULL) {
E
Eric Blake 已提交
623
        *format = VIR_STORAGE_FILE_NONE;
624
        return BACKING_STORE_OK;
625
    }
626 627
    start += strlen(prefix);
    end = strchr(start, '"');
628 629 630
    if (end == NULL)
        return BACKING_STORE_INVALID;

631
    if (end == start) {
E
Eric Blake 已提交
632
        *format = VIR_STORAGE_FILE_NONE;
633
        return BACKING_STORE_OK;
634
    }
635
    *end = '\0';
636
    *res = g_strdup(start);
637

638
    return BACKING_STORE_OK;
639 640
}

641 642 643
static int
qedGetBackingStore(char **res,
                   int *format,
E
Eric Blake 已提交
644
                   const char *buf,
645 646 647 648 649 650 651 652 653
                   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 已提交
654
    flags = virReadBufInt64LE(buf + QED_HDR_FEATURES_OFFSET);
E
Eric Blake 已提交
655 656
    if (!(flags & QED_F_BACKING_FILE)) {
        *format = VIR_STORAGE_FILE_NONE;
657
        return BACKING_STORE_OK;
E
Eric Blake 已提交
658
    }
659 660 661 662

    /* Parse the backing file */
    if (buf_size < QED_HDR_BACKING_FILE_OFFSET+8)
        return BACKING_STORE_INVALID;
E
Eric Blake 已提交
663
    offset = virReadBufInt32LE(buf + QED_HDR_BACKING_FILE_OFFSET);
664 665
    if (offset > buf_size)
        return BACKING_STORE_INVALID;
E
Eric Blake 已提交
666
    size = virReadBufInt32LE(buf + QED_HDR_BACKING_FILE_SIZE);
667 668 669 670
    if (size == 0)
        return BACKING_STORE_OK;
    if (offset + size > buf_size || offset + size < offset)
        return BACKING_STORE_INVALID;
671
    if (VIR_ALLOC_N(*res, size + 1) < 0)
672 673 674 675
        return BACKING_STORE_ERROR;
    memcpy(*res, buf + offset, size);
    (*res)[size] = '\0';

E
Eric Blake 已提交
676 677 678 679
    if (flags & QED_F_BACKING_FORMAT_NO_PROBE)
        *format = VIR_STORAGE_FILE_RAW;
    else
        *format = VIR_STORAGE_FILE_AUTO_SAFE;
680 681 682 683

    return BACKING_STORE_OK;
}

684 685

static bool
686 687
virStorageFileMatchesMagic(int magicOffset,
                           const char *magic,
E
Eric Blake 已提交
688
                           char *buf,
689
                           size_t buflen)
690
{
691
    int mlen;
692

693
    if (magic == NULL)
694
        return false;
695

696
    /* Validate magic data */
697 698
    mlen = strlen(magic);
    if (magicOffset + mlen > buflen)
699
        return false;
700

701
    if (memcmp(buf + magicOffset, magic, mlen) != 0)
702 703 704 705 706 707 708
        return false;

    return true;
}


static bool
709 710 711 712
virStorageFileMatchesVersion(int versionOffset,
                             int versionSize,
                             const int *versionNumbers,
                             int endian,
E
Eric Blake 已提交
713
                             char *buf,
714 715
                             size_t buflen)
{
716
    int version;
717
    size_t i;
718 719

    /* Validate version number info */
720
    if (versionOffset == -1)
E
Eric Blake 已提交
721
        return false;
722

723
    /* -2 == non-versioned file format, so trivially match */
724
    if (versionOffset == -2)
725 726
        return true;

727
    /* A positive versionOffset, requires using a valid versionSize */
728
    if (versionSize != 2 && versionSize != 4)
729 730
        return false;

731
    if ((versionOffset + versionSize) > buflen)
732 733
        return false;

734 735
    if (endian == LV_LITTLE_ENDIAN) {
        if (versionSize == 4)
736
            version = virReadBufInt32LE(buf +
737
                                        versionOffset);
738 739
        else
            version = virReadBufInt16LE(buf +
740
                                        versionOffset);
741
    } else {
742
        if (versionSize == 4)
743
            version = virReadBufInt32BE(buf +
744
                                        versionOffset);
745 746
        else
            version = virReadBufInt16BE(buf +
747
                                        versionOffset);
748
    }
749

750
    for (i = 0;
751
         i < FILE_TYPE_VERSIONS_LAST && versionNumbers[i];
752 753
         i++) {
        VIR_DEBUG("Compare detected version %d vs one of the expected versions %d",
754 755
                  version, versionNumbers[i]);
        if (version == versionNumbers[i])
756 757
            return true;
    }
758

759
    return false;
760
}
761

762 763
bool
virStorageIsFile(const char *backing)
A
Adam Litke 已提交
764
{
765 766 767 768 769 770 771 772
    char *colon;
    char *slash;

    if (!backing)
        return false;

    colon = strchr(backing, ':');
    slash = strchr(backing, '/');
773 774 775 776 777

    /* 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 已提交
778 779 780
        return false;
    return true;
}
781

E
Eric Blake 已提交
782

783
bool
784 785 786 787 788 789 790 791 792 793 794 795
virStorageIsRelative(const char *backing)
{
    if (backing[0] == '/')
        return false;

    if (!virStorageIsFile(backing))
        return false;

    return true;
}


796
static int
E
Eric Blake 已提交
797
virStorageFileProbeFormatFromBuf(const char *path,
E
Eric Blake 已提交
798
                                 char *buf,
E
Eric Blake 已提交
799 800 801
                                 size_t buflen)
{
    int format = VIR_STORAGE_FILE_RAW;
802
    size_t i;
E
Eric Blake 已提交
803
    int possibleFormat = VIR_STORAGE_FILE_RAW;
804
    VIR_DEBUG("path=%s, buf=%p, buflen=%zu", path, buf, buflen);
E
Eric Blake 已提交
805 806

    /* First check file magic */
807
    for (i = 0; i < VIR_STORAGE_FILE_LAST; i++) {
808 809 810 811 812 813 814 815
        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 已提交
816 817 818 819 820 821 822 823 824 825 826 827 828
                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));

829
 cleanup:
E
Eric Blake 已提交
830 831 832 833 834
    VIR_DEBUG("format=%d", format);
    return format;
}


835 836 837
static int
qcow2GetFeatures(virBitmapPtr *features,
                 int format,
E
Eric Blake 已提交
838
                 char *buf,
839 840 841 842 843
                 ssize_t len)
{
    int version = -1;
    virBitmapPtr feat = NULL;
    uint64_t bits;
844
    size_t i;
845 846 847 848 849 850 851 852 853

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

    if (version == 2)
        return 0;

    if (len < QCOW2v3_HDR_SIZE)
        return -1;

854
    if (!(feat = virBitmapNew(VIR_STORAGE_FILE_FEATURE_LAST)))
855 856 857 858 859 860 861 862 863 864 865 866 867 868
        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;
}


869 870 871 872 873 874
static bool
virStorageFileHasEncryptionFormat(const struct FileEncryptionInfo *info,
                                  char *buf,
                                  size_t len)
{
    if (!info->magic && info->modeOffset == -1)
875
        return false; /* Shouldn't happen - expect at least one */
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892

    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) {
893 894
        int crypt_format;

895 896 897
        if (info->modeOffset >= len)
            return false;

898 899
        crypt_format = virReadBufInt32BE(buf + info->modeOffset);
        if (crypt_format != info->modeValue)
900 901 902 903 904 905 906 907 908
            return false;

        return true;
    } else {
        return false;
    }
}


909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925
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;
}


926 927 928 929
/* 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
930 931 932 933 934
 * pre-populated in META.
 *
 * Note that this function may be called repeatedly on @meta, so it must
 * clean up any existing allocated memory which would be overwritten.
 */
935
static int
936
virStorageFileGetMetadataInternal(virStorageSourcePtr meta,
937
                                  char *buf,
938
                                  size_t len)
939
{
940
    int format;
941
    size_t i;
E
Eric Blake 已提交
942

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

946
    if (meta->format == VIR_STORAGE_FILE_AUTO)
947
        meta->format = virStorageFileProbeFormatFromBuf(meta->path, buf, len);
948

949 950 951 952
    if (meta->format <= VIR_STORAGE_FILE_NONE ||
        meta->format >= VIR_STORAGE_FILE_LAST) {
        virReportSystemError(EINVAL, _("unknown storage file meta->format %d"),
                             meta->format);
953
        return -1;
E
Eric Blake 已提交
954
    }
955

956 957 958 959
    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)) {
960 961 962
                int expt_fmt = fileTypeInfo[meta->format].cryptInfo[i].format;
                if (!meta->encryption) {
                    if (VIR_ALLOC(meta->encryption) < 0)
963
                        return -1;
964 965 966 967 968 969 970 971

                    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);
972
                        return -1;
973 974
                    }
                }
975 976
                meta->encryption->payload_offset =
                    virStorageFileGetEncryptionPayloadOffset(&fileTypeInfo[meta->format].cryptInfo[i], buf);
977 978 979 980
            }
        }
    }

981 982 983
    /* XXX we should consider moving virStorageBackendUpdateVolInfo
     * code into this method, for non-magic files
     */
984
    if (!fileTypeInfo[meta->format].magic)
985
        return 0;
986

987
    /* Optionally extract capacity from file */
988 989
    if (fileTypeInfo[meta->format].sizeOffset != -1) {
        if ((fileTypeInfo[meta->format].sizeOffset + 8) > len)
990
            return 0;
991

992
        if (fileTypeInfo[meta->format].endian == LV_LITTLE_ENDIAN)
E
Eric Blake 已提交
993
            meta->capacity = virReadBufInt64LE(buf +
994
                                               fileTypeInfo[meta->format].sizeOffset);
E
Eric Blake 已提交
995 996
        else
            meta->capacity = virReadBufInt64BE(buf +
997
                                               fileTypeInfo[meta->format].sizeOffset);
998
        /* Avoid unlikely, but theoretically possible overflow */
E
Eric Blake 已提交
999
        if (meta->capacity > (ULLONG_MAX /
1000
                              fileTypeInfo[meta->format].sizeMultiplier))
1001
            return 0;
1002
        meta->capacity *= fileTypeInfo[meta->format].sizeMultiplier;
1003
    }
1004

1005
    VIR_FREE(meta->backingStoreRaw);
1006 1007
    if (fileTypeInfo[meta->format].getBackingStore != NULL) {
        int store = fileTypeInfo[meta->format].getBackingStore(&meta->backingStoreRaw,
1008
                                                               &format,
1009
                                                               buf, len);
1010 1011
        meta->backingStoreRawFormat = format;

E
Eric Blake 已提交
1012
        if (store == BACKING_STORE_INVALID)
1013
            return 0;
1014

E
Eric Blake 已提交
1015
        if (store == BACKING_STORE_ERROR)
1016
            return -1;
1017 1018
    }

1019 1020
    virBitmapFree(meta->features);
    meta->features = NULL;
1021 1022
    if (fileTypeInfo[meta->format].getFeatures != NULL &&
        fileTypeInfo[meta->format].getFeatures(&meta->features, meta->format, buf, len) < 0)
1023
        return -1;
1024

1025
    VIR_FREE(meta->compat);
1026 1027
    if (meta->format == VIR_STORAGE_FILE_QCOW2 && meta->features)
        meta->compat = g_strdup("1.1");
E
Eric Blake 已提交
1028

1029
    return 0;
1030 1031 1032 1033
}


/**
1034
 * virStorageFileProbeFormat:
1035
 *
1036 1037
 * Probe for the format of 'path', returning the detected
 * disk format.
1038 1039 1040
 *
 * Callers are advised never to trust the returned 'format'
 * unless it is listed as VIR_STORAGE_FILE_RAW, since a
1041
 * malicious guest can turn a raw file into any other non-raw
1042 1043 1044 1045 1046
 * format at will.
 *
 * Best option: Don't use this function
 */
int
1047
virStorageFileProbeFormat(const char *path, uid_t uid, gid_t gid)
1048
{
1049
    struct stat sb;
1050
    ssize_t len = VIR_STORAGE_MAX_HEADER;
J
John Ferlan 已提交
1051
    VIR_AUTOCLOSE fd = -1;
1052
    g_autofree char *header = NULL;
1053

1054 1055
    if ((fd = virFileOpenAs(path, O_RDONLY, 0, uid, gid, 0)) < 0) {
        virReportSystemError(-fd, _("Failed to open file '%s'"), path);
1056 1057 1058
        return -1;
    }

1059 1060
    if (fstat(fd, &sb) < 0) {
        virReportSystemError(errno, _("cannot stat file '%s'"), path);
J
John Ferlan 已提交
1061
        return -1;
1062 1063
    }

1064
    /* No header to probe for directories */
J
John Ferlan 已提交
1065 1066
    if (S_ISDIR(sb.st_mode))
        return VIR_STORAGE_FILE_DIR;
1067 1068 1069

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

1073
    if ((len = virFileReadHeaderFD(fd, len, &header)) < 0) {
1074
        virReportSystemError(errno, _("cannot read header '%s'"), path);
J
John Ferlan 已提交
1075
        return -1;
1076 1077
    }

J
John Ferlan 已提交
1078
    return virStorageFileProbeFormatFromBuf(path, header, len);
1079 1080
}

1081

1082
static virStorageSourcePtr
1083 1084 1085
virStorageFileMetadataNew(const char *path,
                          int format)
{
1086
    g_autoptr(virStorageSource) def = NULL;
1087

1088
    if (!(def = virStorageSourceNew()))
1089 1090
        return NULL;

1091 1092
    def->format = format;
    def->type = VIR_STORAGE_TYPE_FILE;
1093

1094
    def->path = g_strdup(path);
1095

M
Michal Privoznik 已提交
1096
    return g_steal_pointer(&def);
1097 1098 1099
}


1100 1101 1102 1103 1104
/**
 * virStorageFileGetMetadataFromBuf:
 * @path: name of file, for error messages
 * @buf: header bytes from @path
 * @len: length of @buf
1105
 * @format: format of the storage file
1106
 *
1107 1108 1109
 * 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.
1110
 *
1111 1112 1113 1114
 * 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.
 *
1115 1116 1117 1118
 * If the 'backingStoreRawFormat' field of the returned structure 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.
1119
 *
1120
 * Caller MUST free the result after use via virObjectUnref.
1121
 */
1122
virStorageSourcePtr
1123 1124 1125
virStorageFileGetMetadataFromBuf(const char *path,
                                 char *buf,
                                 size_t len,
1126
                                 int format)
1127
{
1128
    virStorageSourcePtr ret = NULL;
1129

1130
    if (!(ret = virStorageFileMetadataNew(path, format)))
1131
        return NULL;
1132

1133
    if (virStorageFileGetMetadataInternal(ret, buf, len) < 0) {
1134
        virObjectUnref(ret);
1135 1136
        return NULL;
    }
1137

1138
    return ret;
1139 1140 1141
}


1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
/**
 * 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.
 *
1153
 * Caller MUST free the result after use via virObjectUnref.
1154 1155 1156 1157
 */
virStorageSourcePtr
virStorageFileGetMetadataFromFD(const char *path,
                                int fd,
1158
                                int format)
1159

1160
{
1161
    ssize_t len = VIR_STORAGE_MAX_HEADER;
1162
    struct stat sb;
1163
    g_autofree char *buf = NULL;
1164
    g_autoptr(virStorageSource) meta = NULL;
1165 1166 1167

    if (fstat(fd, &sb) < 0) {
        virReportSystemError(errno,
1168 1169
                             _("cannot stat file '%s'"), path);
        return NULL;
1170 1171
    }

1172 1173 1174
    if (!(meta = virStorageFileMetadataNew(path, format)))
        return NULL;

1175
    if (S_ISDIR(sb.st_mode)) {
1176 1177
        /* No header to probe for directories, but also no backing file. Just
         * update the metadata.*/
1178 1179
        meta->type = VIR_STORAGE_TYPE_DIR;
        meta->format = VIR_STORAGE_FILE_DIR;
M
Michal Privoznik 已提交
1180
        return g_steal_pointer(&meta);
1181 1182 1183
    }

    if (lseek(fd, 0, SEEK_SET) == (off_t)-1) {
1184
        virReportSystemError(errno, _("cannot seek to start of '%s'"), meta->path);
1185
        return NULL;
1186 1187 1188
    }

    if ((len = virFileReadHeaderFD(fd, len, &buf)) < 0) {
1189
        virReportSystemError(errno, _("cannot read header '%s'"), meta->path);
1190
        return NULL;
1191 1192
    }

1193
    if (virStorageFileGetMetadataInternal(meta, buf, len) < 0)
1194
        return NULL;
1195

1196 1197 1198 1199
    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;
1200

M
Michal Privoznik 已提交
1201
    return g_steal_pointer(&meta);
1202 1203
}

1204

1205 1206 1207 1208 1209
/**
 * virStorageFileChainCheckBroken
 *
 * If CHAIN is broken, set *brokenFile to the broken file name,
 * otherwise set it to NULL. Caller MUST free *brokenFile after use.
1210 1211
 * Return 0 on success (including when brokenFile is set), negative on
 * error (allocation failure).
1212 1213
 */
int
1214
virStorageFileChainGetBroken(virStorageSourcePtr chain,
1215 1216
                             char **brokenFile)
{
1217
    virStorageSourcePtr tmp;
1218

1219 1220
    *brokenFile = NULL;

1221 1222 1223
    if (!chain)
        return 0;

1224
    for (tmp = chain; virStorageSourceIsBacking(tmp); tmp = tmp->backingStore) {
1225 1226
        /* Break when we hit end of chain; report error if we detected
         * a missing backing file, infinite loop, or other error */
1227
        if (!tmp->backingStore && tmp->backingStoreRaw) {
1228
            *brokenFile = g_strdup(tmp->backingStoreRaw);
1229

1230 1231 1232
           return 0;
        }
    }
1233

1234
    return 0;
1235 1236 1237
}


1238 1239 1240 1241 1242 1243
/**
 * virStorageFileResize:
 *
 * Change the capacity of the raw storage file at 'path'.
 */
int
1244 1245 1246
virStorageFileResize(const char *path,
                     unsigned long long capacity,
                     bool pre_allocate)
1247
{
1248
    int rc;
J
John Ferlan 已提交
1249
    VIR_AUTOCLOSE fd = -1;
1250 1251 1252

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

1256
    if (pre_allocate) {
1257
        if ((rc = virFileAllocate(fd, 0, capacity)) != 0) {
1258 1259 1260 1261 1262 1263 1264 1265
            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 已提交
1266
            return -1;
1267
        }
1268 1269 1270 1271 1272
    }

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

1276 1277
    if (VIR_CLOSE(fd) < 0) {
        virReportSystemError(errno, _("Unable to save '%s'"), path);
J
John Ferlan 已提交
1278
        return -1;
1279 1280
    }

J
John Ferlan 已提交
1281
    return 0;
1282 1283
}

1284 1285 1286 1287 1288 1289

int virStorageFileIsClusterFS(const char *path)
{
    /* These are coherent cluster filesystems known to be safe for
     * migration with cache != none
     */
1290 1291
    return virFileIsSharedFSType(path,
                                 VIR_FILE_SHFS_GFS2 |
1292 1293
                                 VIR_FILE_SHFS_OCFS |
                                 VIR_FILE_SHFS_CEPH);
1294
}
1295 1296

#ifdef LVS
1297 1298
int virStorageFileGetLVMKey(const char *path,
                            char **key)
1299 1300 1301 1302 1303
{
    /*
     *  # lvs --noheadings --unbuffered --nosuffix --options "uuid" LVNAME
     *    06UgP5-2rhb-w3Bo-3mdR-WeoL-pytO-SAa2ky
     */
1304 1305
    int status;
    int ret = -1;
J
Ján Tomko 已提交
1306
    g_autoptr(virCommand) cmd = NULL;
1307

1308 1309 1310 1311 1312
    cmd = virCommandNewArgList(LVS, "--noheadings",
                               "--unbuffered", "--nosuffix",
                               "--options", "uuid", path,
                               NULL
                               );
1313
    *key = NULL;
1314 1315

    /* Run the program and capture its output */
1316 1317
    virCommandSetOutputBuffer(cmd, key);
    if (virCommandRun(cmd, &status) < 0)
1318 1319
        goto cleanup;

1320 1321 1322 1323 1324 1325
    /* 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) {
1326
        char *nl;
1327
        char *tmp = *key;
1328 1329

        /* Find first non-space character */
1330
        while (*tmp && g_ascii_isspace(*tmp))
1331 1332
            tmp++;
        /* Kill leading spaces */
1333 1334
        if (tmp != *key)
            memmove(*key, tmp, strlen(tmp)+1);
1335 1336

        /* Kill trailing newline */
1337
        if ((nl = strchr(*key, '\n')))
1338 1339 1340
            *nl = '\0';
    }

1341
    ret = 0;
1342

1343
 cleanup:
1344 1345 1346 1347
    if (*key && STREQ(*key, ""))
        VIR_FREE(*key);

    return ret;
1348 1349
}
#else
1350
int virStorageFileGetLVMKey(const char *path,
J
Ján Tomko 已提交
1351
                            char **key G_GNUC_UNUSED)
1352 1353
{
    virReportSystemError(ENOSYS, _("Unable to get LVM key for %s"), path);
1354
    return -1;
1355 1356 1357
}
#endif

1358
#ifdef WITH_UDEV
1359 1360 1361
/* virStorageFileGetSCSIKey
 * @path: Path to the SCSI device
 * @key: Unique key to be returned
1362
 * @ignoreError: Used to not report ENOSYS
1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374
 *
 * 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,
1375
                         char **key,
J
Ján Tomko 已提交
1376
                         bool ignoreError G_GNUC_UNUSED)
1377
{
1378
    int status;
J
Ján Tomko 已提交
1379
    g_autoptr(virCommand) cmd = NULL;
1380 1381 1382 1383 1384 1385 1386

    cmd = virCommandNewArgList("/lib/udev/scsi_id",
                               "--replace-whitespace",
                               "--whitelisted",
                               "--device", path,
                               NULL
                               );
1387
    *key = NULL;
1388 1389

    /* Run the program and capture its output */
1390 1391
    virCommandSetOutputBuffer(cmd, key);
    if (virCommandRun(cmd, &status) < 0)
1392
        return -2;
1393

1394 1395 1396 1397 1398 1399
    /* 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');
1400 1401 1402 1403
        if (nl)
            *nl = '\0';
    }

1404 1405 1406
    if (*key && STREQ(*key, ""))
        VIR_FREE(*key);

1407
    return 0;
1408 1409
}
#else
1410
int virStorageFileGetSCSIKey(const char *path,
J
Ján Tomko 已提交
1411
                             char **key G_GNUC_UNUSED,
1412
                             bool ignoreError)
1413
{
1414 1415
    if (!ignoreError)
        virReportSystemError(ENOSYS, _("Unable to get SCSI key for %s"), path);
1416
    return -1;
1417 1418
}
#endif
1419

1420

1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445
#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;
1446
    g_autofree char *outbuf = NULL;
J
Ján Tomko 已提交
1447
    g_autoptr(virCommand) cmd = NULL;
1448 1449 1450 1451 1452 1453 1454 1455

    cmd = virCommandNewArgList("/lib/udev/scsi_id",
                               "--replace-whitespace",
                               "--whitelisted",
                               "--export",
                               "--device", path,
                               NULL
                               );
1456 1457 1458 1459 1460
    *key = NULL;

    /* Run the program and capture its output */
    virCommandSetOutputBuffer(cmd, &outbuf);
    if (virCommandRun(cmd, &status) < 0)
1461
        return -2;
1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481

    /* 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')
1482
            *key = g_strdup_printf("%s_PORT%s", serial, port);
1483 1484
    }

1485
    return 0;
1486 1487
}
#else
J
Ján Tomko 已提交
1488 1489
int virStorageFileGetNPIVKey(const char *path G_GNUC_UNUSED,
                             char **key G_GNUC_UNUSED)
1490 1491 1492 1493 1494
{
    return -1;
}
#endif

1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514
/**
 * 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;
1515
    VIR_AUTOSTRINGLIST strings = NULL;
1516 1517 1518 1519 1520 1521 1522 1523 1524

    *chainIndex = 0;

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

    if (nstrings == 2) {
        if (virStrToLong_uip(strings[1], &suffix, 10, &idx) < 0 ||
            STRNEQ(suffix, "]"))
1525
            return -1;
1526 1527
    }

1528 1529
    if (target)
        *target = g_strdup(strings[0]);
1530 1531

    *chainIndex = idx;
1532
    return 0;
1533 1534 1535
}


1536 1537 1538 1539 1540 1541
int
virStorageFileParseChainIndex(const char *diskTarget,
                              const char *name,
                              unsigned int *chainIndex)
{
    unsigned int idx = 0;
1542
    g_autofree char *target = NULL;
1543 1544 1545

    *chainIndex = 0;

1546 1547
    if (!name || !diskTarget)
        return 0;
1548

1549 1550
    if (virStorageFileParseBackingStoreStr(name, &target, &idx) < 0)
        return 0;
1551

1552
    if (idx == 0)
1553
        return 0;
1554

1555
    if (STRNEQ(diskTarget, target)) {
1556 1557
        virReportError(VIR_ERR_INVALID_ARG,
                       _("requested target '%s' does not match target '%s'"),
1558
                       target, diskTarget);
1559
        return -1;
1560 1561 1562 1563
    }

    *chainIndex = idx;

1564
    return 0;
1565 1566
}

1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577

/**
 * 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 已提交
1578
    return src && src->type != VIR_STORAGE_TYPE_NONE;
1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589
}

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


E
Eric Blake 已提交
1595 1596 1597 1598 1599 1600 1601 1602 1603 1604
/* 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.
1605
 */
1606
virStorageSourcePtr
1607
virStorageFileChainLookup(virStorageSourcePtr chain,
1608
                          virStorageSourcePtr startFrom,
1609
                          const char *name,
1610
                          unsigned int idx,
1611
                          virStorageSourcePtr *parent)
1612
{
1613
    virStorageSourcePtr prev;
1614
    const char *start = chain->path;
1615
    char *parentDir = NULL;
E
Eric Blake 已提交
1616
    bool nameIsFile = virStorageIsFile(name);
1617 1618

    if (!parent)
1619
        parent = &prev;
1620
    *parent = NULL;
1621 1622

    if (startFrom) {
1623 1624
        while (virStorageSourceIsBacking(chain) &&
               chain != startFrom->backingStore)
1625
            chain = chain->backingStore;
1626

1627
        *parent = startFrom;
1628 1629
    }

1630
    while (virStorageSourceIsBacking(chain)) {
1631
        if (!name && !idx) {
1632
            if (!virStorageSourceHasBacking(chain))
1633
                break;
1634
        } else if (idx) {
1635 1636
            VIR_DEBUG("%u: %s", chain->id, chain->path);
            if (idx == chain->id)
1637
                break;
E
Eric Blake 已提交
1638
        } else {
1639
            if (STREQ_NULLABLE(name, chain->relPath) ||
1640
                STREQ_NULLABLE(name, chain->path))
1641
                break;
1642 1643

            if (nameIsFile && virStorageSourceIsLocalStorage(chain)) {
1644
                if (*parent && virStorageSourceIsLocalStorage(*parent))
1645
                    parentDir = g_path_get_dirname((*parent)->path);
1646
                else
1647
                    parentDir = g_strdup(".");
1648

E
Eric Blake 已提交
1649
                int result = virFileRelLinkPointsTo(parentDir, name,
1650
                                                    chain->path);
1651 1652

                VIR_FREE(parentDir);
1653

E
Eric Blake 已提交
1654 1655
                if (result < 0)
                    goto error;
1656

E
Eric Blake 已提交
1657 1658 1659
                if (result > 0)
                    break;
            }
1660
        }
1661
        *parent = chain;
1662
        chain = chain->backingStore;
1663
    }
1664

1665
    if (!virStorageSourceIsBacking(chain))
1666
        goto error;
1667

1668
    return chain;
1669

1670
 error:
1671 1672
    if (idx) {
        virReportError(VIR_ERR_INVALID_ARG,
1673 1674
                       _("could not find backing store index %u in chain "
                         "for '%s'"),
1675
                       idx, NULLSTR(start));
1676
    } else if (name) {
E
Eric Blake 已提交
1677 1678 1679
        if (startFrom)
            virReportError(VIR_ERR_INVALID_ARG,
                           _("could not find image '%s' beneath '%s' in "
1680 1681
                             "chain for '%s'"), name, NULLSTR(startFrom->path),
                           NULLSTR(start));
E
Eric Blake 已提交
1682 1683 1684
        else
            virReportError(VIR_ERR_INVALID_ARG,
                           _("could not find image '%s' in chain for '%s'"),
1685
                           name, NULLSTR(start));
1686
    } else {
1687 1688
        virReportError(VIR_ERR_INVALID_ARG,
                       _("could not find base image in chain for '%s'"),
1689
                       NULLSTR(start));
1690
    }
1691 1692 1693
    *parent = NULL;
    return NULL;
}
1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722


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);
}


1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733
static void
virStoragePermsFree(virStoragePermsPtr def)
{
    if (!def)
        return;

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


1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748
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;
1749
        dst->port = src->port;
1750

1751 1752
        dst->name = g_strdup(src->name);
        dst->socket = g_strdup(src->socket);
1753 1754 1755 1756 1757 1758 1759 1760
    }

    return ret;

 error:
    virStorageNetHostDefFree(nhosts, ret);
    return NULL;
}
1761 1762


1763 1764 1765 1766 1767 1768 1769 1770
void
virStorageAuthDefFree(virStorageAuthDefPtr authdef)
{
    if (!authdef)
        return;

    VIR_FREE(authdef->username);
    VIR_FREE(authdef->secrettype);
1771
    virSecretLookupDefClear(&authdef->seclookupdef);
1772 1773 1774 1775 1776 1777 1778
    VIR_FREE(authdef);
}


virStorageAuthDefPtr
virStorageAuthDefCopy(const virStorageAuthDef *src)
{
J
Ján Tomko 已提交
1779
    g_autoptr(virStorageAuthDef) authdef = NULL;
1780

J
John Ferlan 已提交
1781
    if (VIR_ALLOC(authdef) < 0)
1782 1783
        return NULL;

1784
    authdef->username = g_strdup(src->username);
1785
    /* Not present for storage pool, but used for disk source */
1786
    authdef->secrettype = g_strdup(src->secrettype);
J
John Ferlan 已提交
1787
    authdef->authType = src->authType;
1788

1789
    virSecretLookupDefCopy(&authdef->seclookupdef, &src->seclookupdef);
1790

M
Michal Privoznik 已提交
1791
    return g_steal_pointer(&authdef);
1792 1793 1794
}


1795 1796 1797
virStorageAuthDefPtr
virStorageAuthDefParse(xmlNodePtr node,
                       xmlXPathContextPtr ctxt)
1798
{
1799
    xmlNodePtr saveNode = ctxt->node;
1800
    virStorageAuthDefPtr ret = NULL;
1801
    xmlNodePtr secretnode = NULL;
J
Ján Tomko 已提交
1802
    g_autoptr(virStorageAuthDef) authdef = NULL;
1803
    g_autofree char *authtype = NULL;
1804

1805 1806
    ctxt->node = node;

1807
    if (VIR_ALLOC(authdef) < 0)
1808
        goto cleanup;
1809

1810
    if (!(authdef->username = virXPathString("string(./@username)", ctxt))) {
1811 1812
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing username for auth"));
1813
        goto cleanup;
1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824
    }

    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);
1825
            goto cleanup;
1826 1827 1828
        }
    }

1829 1830 1831
    if (!(secretnode = virXPathNode("./secret ", ctxt))) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("Missing <secret> element in auth"));
1832
        goto cleanup;
1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844
    }

    /* 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)
1845
        goto cleanup;
1846

1847
    ret = g_steal_pointer(&authdef);
1848

1849
 cleanup:
1850
    ctxt->node = saveNode;
1851 1852

    return ret;
1853 1854 1855
}


1856
void
1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868
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);
1869 1870
    virSecretLookupFormatSecret(buf, authdef->secrettype,
                                &authdef->seclookupdef);
1871 1872 1873 1874 1875
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</auth>\n");
}


1876 1877 1878 1879 1880 1881 1882
void
virStoragePRDefFree(virStoragePRDefPtr prd)
{
    if (!prd)
        return;

    VIR_FREE(prd->path);
1883
    VIR_FREE(prd->mgralias);
1884 1885 1886 1887 1888 1889 1890
    VIR_FREE(prd);
}


virStoragePRDefPtr
virStoragePRDefParseXML(xmlXPathContextPtr ctxt)
{
1891 1892
    virStoragePRDefPtr prd;
    virStoragePRDefPtr ret = NULL;
1893 1894 1895 1896
    g_autofree char *managed = NULL;
    g_autofree char *type = NULL;
    g_autofree char *path = NULL;
    g_autofree char *mode = NULL;
1897 1898 1899 1900

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

1901
    if (!(managed = virXPathString("string(./@managed)", ctxt))) {
1902
        virReportError(VIR_ERR_XML_ERROR, "%s",
1903
                       _("missing @managed attribute for <reservations/>"));
1904 1905 1906
        goto cleanup;
    }

1907
    if ((prd->managed = virTristateBoolTypeFromString(managed)) <= 0) {
1908
        virReportError(VIR_ERR_XML_ERROR,
1909
                       _("invalid value for 'managed': %s"), managed);
1910 1911 1912
        goto cleanup;
    }

1913 1914 1915
    type = virXPathString("string(./source[1]/@type)", ctxt);
    path = virXPathString("string(./source[1]/@path)", ctxt);
    mode = virXPathString("string(./source[1]/@mode)", ctxt);
1916

1917
    if (prd->managed == VIR_TRISTATE_BOOL_NO || type || path || mode) {
1918
        if (!type) {
1919
            virReportError(VIR_ERR_XML_ERROR, "%s",
1920
                           _("missing connection type for <reservations/>"));
1921 1922 1923
            goto cleanup;
        }

1924 1925 1926
        if (!path) {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("missing path for <reservations/>"));
1927 1928 1929
            goto cleanup;
        }

1930 1931 1932 1933 1934
        if (!mode) {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("missing connection mode for <reservations/>"));
            goto cleanup;
        }
1935
    }
1936

1937 1938 1939 1940 1941 1942
    if (type && STRNEQ(type, "unix")) {
        virReportError(VIR_ERR_XML_ERROR,
                       _("unsupported connection type for <reservations/>: %s"),
                       type);
        goto cleanup;
    }
1943

1944 1945 1946 1947 1948
    if (mode && STRNEQ(mode, "client")) {
        virReportError(VIR_ERR_XML_ERROR,
                       _("unsupported connection mode for <reservations/>: %s"),
                       mode);
        goto cleanup;
1949 1950
    }

1951 1952
    prd->path = g_steal_pointer(&path);
    ret = g_steal_pointer(&prd);
1953 1954 1955 1956 1957 1958 1959 1960 1961

 cleanup:
    virStoragePRDefFree(prd);
    return ret;
}


void
virStoragePRDefFormat(virBufferPtr buf,
1962 1963
                      virStoragePRDefPtr prd,
                      bool migratable)
1964
{
1965 1966
    virBufferAsprintf(buf, "<reservations managed='%s'",
                      virTristateBoolTypeToString(prd->managed));
1967 1968
    if (prd->path &&
        (prd->managed == VIR_TRISTATE_BOOL_NO || !migratable)) {
1969 1970 1971 1972 1973 1974 1975
        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");
1976 1977 1978 1979 1980 1981
    } else {
        virBufferAddLit(buf, "/>\n");
    }
}


1982 1983 1984 1985 1986 1987 1988 1989 1990 1991
bool
virStoragePRDefIsEqual(virStoragePRDefPtr a,
                       virStoragePRDefPtr b)
{
    if (!a && !b)
        return true;

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

1992
    if (a->managed != b->managed ||
1993 1994 1995 1996 1997 1998 1999
        STRNEQ_NULLABLE(a->path, b->path))
        return false;

    return true;
}


2000 2001 2002 2003 2004 2005 2006
bool
virStoragePRDefIsManaged(virStoragePRDefPtr prd)
{
    return prd && prd->managed == VIR_TRISTATE_BOOL_YES;
}


2007 2008 2009 2010 2011 2012
bool
virStorageSourceChainHasManagedPR(virStorageSourcePtr src)
{
    virStorageSourcePtr n;

    for (n = src; virStorageSourceIsBacking(n); n = n->backingStore) {
2013
        if (virStoragePRDefIsManaged(n->pr))
2014 2015 2016 2017 2018 2019 2020
            return true;
    }

    return false;
}


2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031
static virStoragePRDefPtr
virStoragePRDefCopy(virStoragePRDefPtr src)
{
    virStoragePRDefPtr copy = NULL;
    virStoragePRDefPtr ret = NULL;

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

    copy->managed = src->managed;

2032 2033
    copy->path = g_strdup(src->path);
    copy->mgralias = g_strdup(src->mgralias);
2034

2035
    ret = g_steal_pointer(&copy);
2036 2037 2038 2039 2040 2041

    virStoragePRDefFree(copy);
    return ret;
}


2042 2043 2044 2045 2046 2047 2048
static virStorageSourceNVMeDefPtr
virStorageSourceNVMeDefCopy(const virStorageSourceNVMeDef *src)
{
    virStorageSourceNVMeDefPtr ret = NULL;

    ret = g_new0(virStorageSourceNVMeDef, 1);

2049
    ret->namespc = src->namespc;
2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065
    ret->managed = src->managed;
    virPCIDeviceAddressCopy(&ret->pciAddr, &src->pciAddr);
    return ret;
}


static bool
virStorageSourceNVMeDefIsEqual(const virStorageSourceNVMeDef *a,
                               const virStorageSourceNVMeDef *b)
{
    if (!a && !b)
        return true;

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

2066
    if (a->namespc != b->namespc ||
2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084
        a->managed != b->managed ||
        !virPCIDeviceAddressEqual(&a->pciAddr, &b->pciAddr))
        return false;

    return true;
}


void
virStorageSourceNVMeDefFree(virStorageSourceNVMeDefPtr def)
{
    if (!def)
        return;

    VIR_FREE(def);
}


2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098
bool
virStorageSourceChainHasNVMe(const virStorageSource *src)
{
    const virStorageSource *n;

    for (n = src; virStorageSourceIsBacking(n); n = n->backingStore) {
        if (n->type == VIR_STORAGE_TYPE_NVME)
            return true;
    }

    return false;
}


2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113
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;
}


2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152
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;
}


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 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213
void
virStorageNetCookieDefFree(virStorageNetCookieDefPtr def)
{
    if (!def)
        return;

    g_free(def->name);
    g_free(def->value);

    g_free(def);
}


static void
virStorageSourceNetCookiesClear(virStorageSourcePtr src)
{
    size_t i;

    if (!src || !src->cookies)
        return;

    for (i = 0; i < src->ncookies; i++)
        virStorageNetCookieDefFree(src->cookies[i]);

    g_clear_pointer(&src->cookies, g_free);
    src->ncookies = 0;
}


static void
virStorageSourceNetCookiesCopy(virStorageSourcePtr to,
                               const virStorageSource *from)
{
    size_t i;

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

    to->cookies = g_new0(virStorageNetCookieDefPtr, from->ncookies);
    to->ncookies = from->ncookies;

    for (i = 0; i < from->ncookies; i++) {
        to->cookies[i]->name = g_strdup(from->cookies[i]->name);
        to->cookies[i]->value = g_strdup(from->cookies[i]->value);
    }
}


/* see https://tools.ietf.org/html/rfc6265#section-4.1.1 */
static const char virStorageSourceCookieValueInvalidChars[] =
 "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F"
 "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F"
 " \",;\\";

/* in addition cookie name can't contain these */
static const char virStorageSourceCookieNameInvalidChars[] =
 "()<>@:/[]?={}";

static int
virStorageSourceNetCookieValidate(virStorageNetCookieDefPtr def)
{
2214 2215 2216 2217
    g_autofree char *val = g_strdup(def->value);
    const char *checkval = val;
    size_t len = strlen(val);

2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233
    /* name must have at least 1 character */
    if (*(def->name) == '\0') {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("cookie name must not be empty"));
        return -1;
    }

    /* check invalid characters in name */
    if (virStringHasChars(def->name, virStorageSourceCookieValueInvalidChars) ||
        virStringHasChars(def->name, virStorageSourceCookieNameInvalidChars)) {
        virReportError(VIR_ERR_XML_ERROR,
                       _("cookie name '%s' contains invalid characters"),
                       def->name);
        return -1;
    }

2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246
    /* check for optional quotes around the cookie value string */
    if (val[0] == '"') {
        if (val[len - 1] != '"') {
            virReportError(VIR_ERR_XML_ERROR,
                           _("value of cookie '%s' contains invalid characters"),
                           def->name);
            return -1;
        }

        val[len - 1] = '\0';
        checkval++;
    }

2247
    /* check invalid characters in value */
2248
    if (virStringHasChars(checkval, virStorageSourceCookieValueInvalidChars)) {
2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281
        virReportError(VIR_ERR_XML_ERROR,
                       _("value of cookie '%s' contains invalid characters"),
                       def->name);
        return -1;
    }

    return 0;
}


int
virStorageSourceNetCookiesValidate(virStorageSourcePtr src)
{
    size_t i;
    size_t j;

    for (i = 0; i < src->ncookies; i++) {
        if (virStorageSourceNetCookieValidate(src->cookies[i]) < 0)
            return -1;

        for (j = i + 1; j < src->ncookies; j++) {
            if (STREQ(src->cookies[i]->name, src->cookies[j]->name)) {
                virReportError(VIR_ERR_XML_ERROR, _("duplicate cookie '%s'"),
                               src->cookies[i]->name);
                return -1;
            }
        }
    }

    return 0;
}


2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307
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;

2308
    ret->label = g_strdup(src->label);
2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326

    return ret;
}


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;

2327 2328
    ret->pool = g_strdup(src->pool);
    ret->volume = g_strdup(src->volume);
2329 2330 2331 2332 2333

    return ret;
}


2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357
static virStorageSourceSlicePtr
virStorageSourceSliceCopy(const virStorageSourceSlice *src)
{
    virStorageSourceSlicePtr ret = g_new0(virStorageSourceSlice, 1);

    ret->offset = src->offset;
    ret->size = src->size;
    ret->nodename = g_strdup(src->nodename);

    return ret;
}


static void
virStorageSourceSliceFree(virStorageSourceSlicePtr slice)
{
    if (!slice)
        return;

    g_free(slice->nodename);
    g_free(slice);
}


2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370
/**
 * 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)
{
2371
    g_autoptr(virStorageSource) def = NULL;
2372

2373
    if (!(def = virStorageSourceNew()))
2374 2375
        return NULL;

2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394
    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;
2395
    def->sslverify = src->sslverify;
2396 2397
    def->readahead = src->readahead;
    def->timeout = src->timeout;
2398 2399

    /* storage driver metadata are not copied */
2400 2401
    def->drv = NULL;

2402 2403 2404 2405
    def->path = g_strdup(src->path);
    def->volume = g_strdup(src->volume);
    def->relPath = g_strdup(src->relPath);
    def->backingStoreRaw = g_strdup(src->backingStoreRaw);
2406
    def->backingStoreRawFormat = src->backingStoreRawFormat;
2407 2408 2409 2410 2411 2412 2413
    def->snapshot = g_strdup(src->snapshot);
    def->configFile = g_strdup(src->configFile);
    def->nodeformat = g_strdup(src->nodeformat);
    def->nodestorage = g_strdup(src->nodestorage);
    def->compat = g_strdup(src->compat);
    def->tlsAlias = g_strdup(src->tlsAlias);
    def->tlsCertdir = g_strdup(src->tlsCertdir);
2414
    def->query = g_strdup(src->query);
2415

2416 2417 2418
    if (src->sliceStorage)
        def->sliceStorage = virStorageSourceSliceCopy(src->sliceStorage);

2419
    if (src->nhosts) {
2420
        if (!(def->hosts = virStorageNetHostDefCopy(src->nhosts, src->hosts)))
2421
            return NULL;
2422

2423
        def->nhosts = src->nhosts;
2424
    }
2425

2426 2427
    virStorageSourceNetCookiesCopy(def, src);

2428
    if (src->srcpool &&
2429
        !(def->srcpool = virStorageSourcePoolDefCopy(src->srcpool)))
2430
        return NULL;
2431 2432

    if (src->features &&
2433
        !(def->features = virBitmapNewCopy(src->features)))
2434
        return NULL;
2435 2436

    if (src->encryption &&
2437
        !(def->encryption = virStorageEncryptionCopy(src->encryption)))
2438
        return NULL;
2439 2440

    if (src->perms &&
2441
        !(def->perms = virStoragePermsCopy(src->perms)))
2442
        return NULL;
2443 2444

    if (src->timestamps &&
2445
        !(def->timestamps = virStorageTimestampsCopy(src->timestamps)))
2446
        return NULL;
2447

2448
    if (virStorageSourceSeclabelsCopy(def, src) < 0)
2449
        return NULL;
2450 2451

    if (src->auth &&
2452
        !(def->auth = virStorageAuthDefCopy(src->auth)))
2453
        return NULL;
2454

2455
    if (src->pr &&
2456
        !(def->pr = virStoragePRDefCopy(src->pr)))
2457
        return NULL;
2458

2459 2460 2461
    if (src->nvme)
        def->nvme = virStorageSourceNVMeDefCopy(src->nvme);

2462
    if (virStorageSourceInitiatorCopy(&def->initiator, &src->initiator) < 0)
2463
        return NULL;
2464

2465
    if (backingChain && src->backingStore) {
2466
        if (!(def->backingStore = virStorageSourceCopy(src->backingStore,
2467
                                                       true)))
2468
            return NULL;
2469 2470
    }

2471 2472 2473 2474
    /* ssh config passthrough for libguestfs */
    def->ssh_host_key_check_disabled = src->ssh_host_key_check_disabled;
    def->ssh_user = g_strdup(src->ssh_user);

M
Michal Privoznik 已提交
2475
    return g_steal_pointer(&def);
2476 2477 2478
}


2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517
/**
 * 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;
        }
    }

2518 2519 2520 2521
    if (a->type == VIR_STORAGE_TYPE_NVME &&
        !virStorageSourceNVMeDefIsEqual(a->nvme, b->nvme))
        return false;

2522 2523 2524 2525
    return true;
}


2526 2527 2528 2529
/**
 * virStorageSourceInitChainElement:
 * @newelem: New backing chain element disk source
 * @old: Existing top level disk source
N
Nitesh Konkar 已提交
2530
 * @transferLabels: Transfer security labels.
2531 2532 2533 2534 2535
 *
 * 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.
 *
2536 2537
 * 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.
2538 2539 2540 2541 2542 2543
 *
 * Returns 0 on success, -1 on error.
 */
int
virStorageSourceInitChainElement(virStorageSourcePtr newelem,
                                 virStorageSourcePtr old,
2544
                                 bool transferLabels)
2545
{
2546 2547
    if (transferLabels &&
        !newelem->seclabels &&
2548
        virStorageSourceSeclabelsCopy(newelem, old) < 0)
2549
        return -1;
2550 2551 2552 2553

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

2554
    return 0;
2555 2556 2557
}


2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570
void
virStorageSourcePoolDefFree(virStorageSourcePoolDefPtr def)
{
    if (!def)
        return;

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

    VIR_FREE(def);
}


2571 2572 2573 2574 2575 2576 2577 2578
/**
 * virStorageSourceGetActualType:
 * @def: storage source definition
 *
 * Returns type of @def. In case when the type is VIR_STORAGE_TYPE_VOLUME
 * and virDomainDiskTranslateSourcePool was called on @def the actual type
 * of the storage volume is returned rather than VIR_STORAGE_TYPE_VOLUME.
 */
2579
int
2580
virStorageSourceGetActualType(const virStorageSource *def)
2581
{
2582 2583 2584
    if (def->type == VIR_STORAGE_TYPE_VOLUME &&
        def->srcpool &&
        def->srcpool->actualtype != VIR_STORAGE_TYPE_NONE)
2585 2586 2587 2588 2589 2590
        return def->srcpool->actualtype;

    return def->type;
}


2591
bool
2592
virStorageSourceIsLocalStorage(const virStorageSource *src)
2593
{
2594 2595 2596 2597 2598 2599 2600 2601 2602 2603
    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:
2604 2605 2606
        /* While NVMe disks are local, they are not accessible via src->path.
         * Therefore, we have to return false here. */
    case VIR_STORAGE_TYPE_NVME:
2607 2608 2609 2610 2611 2612
    case VIR_STORAGE_TYPE_LAST:
    case VIR_STORAGE_TYPE_NONE:
        return false;
    }

    return false;
2613 2614 2615
}


2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632
/**
 * 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;

2633 2634 2635 2636
    if (src->type == VIR_STORAGE_TYPE_NETWORK &&
        src->protocol == VIR_STORAGE_NET_PROTOCOL_NONE)
        return true;

2637 2638 2639 2640
    return false;
}


2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654
/**
 * 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;
}


2655
/**
2656
 * virStorageSourceBackingStoreClear:
2657 2658 2659 2660 2661 2662
 *
 * @src: disk source to clear
 *
 * Clears information about backing store of the current storage file.
 */
void
2663
virStorageSourceBackingStoreClear(virStorageSourcePtr def)
2664 2665 2666 2667 2668 2669 2670 2671
{
    if (!def)
        return;

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

    /* recursively free backing chain */
2672
    virObjectUnref(def->backingStore);
2673 2674 2675 2676
    def->backingStore = NULL;
}


2677 2678 2679 2680 2681 2682 2683
void
virStorageSourceClear(virStorageSourcePtr def)
{
    if (!def)
        return;

    VIR_FREE(def->path);
2684
    VIR_FREE(def->volume);
2685 2686
    VIR_FREE(def->snapshot);
    VIR_FREE(def->configFile);
2687
    VIR_FREE(def->query);
2688
    virStorageSourceNetCookiesClear(def);
2689
    virStorageSourcePoolDefFree(def->srcpool);
E
Eric Blake 已提交
2690 2691
    virBitmapFree(def->features);
    VIR_FREE(def->compat);
2692
    virStorageEncryptionFree(def->encryption);
2693
    virStoragePRDefFree(def->pr);
2694
    virStorageSourceNVMeDefFree(def->nvme);
2695
    virStorageSourceSeclabelsClear(def);
2696
    virStoragePermsFree(def->perms);
E
Eric Blake 已提交
2697
    VIR_FREE(def->timestamps);
2698

2699 2700
    virStorageSourceSliceFree(def->sliceStorage);

2701
    virStorageNetHostDefFree(def->nhosts, def->hosts);
2702
    virStorageAuthDefFree(def->auth);
2703
    virObjectUnref(def->privateData);
2704

2705
    VIR_FREE(def->nodestorage);
2706 2707
    VIR_FREE(def->nodeformat);

2708
    virStorageSourceBackingStoreClear(def);
2709

2710 2711 2712
    VIR_FREE(def->tlsAlias);
    VIR_FREE(def->tlsCertdir);

2713 2714
    VIR_FREE(def->ssh_user);

2715 2716
    virStorageSourceInitiatorClear(&def->initiator);

2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729
    /* 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);
2730
}
2731 2732


2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745
static int
virStorageSourceOnceInit(void)
{
    if (!VIR_CLASS_NEW(virStorageSource, virClassForObject()))
        return -1;

    return 0;
}


VIR_ONCE_GLOBAL_INIT(virStorageSource);


2746 2747 2748
virStorageSourcePtr
virStorageSourceNew(void)
{
2749
    if (virStorageSourceInitialize() < 0)
2750 2751
        return NULL;

2752
    return virObjectNew(virStorageSourceClass);
2753 2754 2755
}


2756 2757 2758 2759
static virStorageSourcePtr
virStorageSourceNewFromBackingRelative(virStorageSourcePtr parent,
                                       const char *rel)
{
2760
    g_autofree char *dirname = NULL;
2761
    g_autoptr(virStorageSource) def = NULL;
2762

2763
    if (!(def = virStorageSourceNew()))
2764 2765
        return NULL;

2766
    /* store relative name */
2767
    def->relPath = g_strdup(rel);
2768

2769
    dirname = g_path_get_dirname(parent->path);
2770

2771
    if (STRNEQ(dirname, "/")) {
2772
        def->path = g_strdup_printf("%s/%s", dirname, rel);
2773
    } else {
2774
        def->path = g_strdup_printf("/%s", rel);
2775 2776 2777
    }

    if (virStorageSourceGetActualType(parent) == VIR_STORAGE_TYPE_NETWORK) {
2778
        def->type = VIR_STORAGE_TYPE_NETWORK;
2779 2780

        /* copy the host network part */
2781
        def->protocol = parent->protocol;
2782
        if (parent->nhosts) {
2783
            if (!(def->hosts = virStorageNetHostDefCopy(parent->nhosts,
2784
                                                        parent->hosts)))
2785
                return NULL;
2786

2787
            def->nhosts = parent->nhosts;
2788
        }
2789

2790
        def->volume = g_strdup(parent->volume);
2791 2792
    } else {
        /* set the type to _FILE, the caller shall update it to the actual type */
2793
        def->type = VIR_STORAGE_TYPE_FILE;
2794 2795
    }

M
Michal Privoznik 已提交
2796
    return g_steal_pointer(&def);
2797 2798 2799 2800 2801
}


static int
virStorageSourceParseBackingURI(virStorageSourcePtr src,
2802
                                const char *uristr)
2803
{
J
Ján Tomko 已提交
2804
    g_autoptr(virURI) uri = NULL;
2805
    const char *path = NULL;
2806
    VIR_AUTOSTRINGLIST scheme = NULL;
2807

2808
    if (!(uri = virURIParse(uristr))) {
2809 2810
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to parse backing file location '%s'"),
2811
                       uristr);
2812
        return -1;
2813 2814
    }

2815
    if (VIR_ALLOC(src->hosts) < 0)
2816
        return -1;
2817 2818 2819

    src->nhosts = 1;

2820
    if (!(scheme = virStringSplit(uri->scheme, "+", 2)))
2821
        return -1;
2822 2823 2824 2825 2826 2827

    if (!scheme[0] ||
        (src->protocol = virStorageNetProtocolTypeFromString(scheme[0])) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("invalid backing protocol '%s'"),
                       NULLSTR(scheme[0]));
2828
        return -1;
2829 2830 2831 2832 2833 2834 2835
    }

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

2839 2840 2841 2842 2843 2844 2845 2846 2847 2848
    if (uri->query) {
        if (src->protocol == VIR_STORAGE_NET_PROTOCOL_HTTP ||
            src->protocol == VIR_STORAGE_NET_PROTOCOL_HTTPS) {
            src->query = g_strdup(uri->query);
        } else {
            /* handle socket stored as a query */
            if (STRPREFIX(uri->query, "socket="))
                src->hosts->socket = g_strdup(STRSKIP(uri->query, "socket="));
        }
    }
2849

2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865
    /* 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;

2866
    src->path = g_strdup(path);
2867 2868 2869

    if (src->protocol == VIR_STORAGE_NET_PROTOCOL_GLUSTER) {
        char *tmp;
2870 2871 2872 2873

        if (!src->path) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("missing volume name and path for gluster volume"));
2874
            return -1;
2875 2876
        }

2877 2878
        if (!(tmp = strchr(src->path, '/')) ||
            tmp == src->path) {
2879
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
2880 2881
                           _("missing volume name or file name in "
                             "gluster source path '%s'"), src->path);
2882
            return -1;
2883 2884 2885 2886
        }

        src->volume = src->path;

2887
        src->path = g_strdup(tmp + 1);
2888 2889 2890 2891

        tmp[0] = '\0';
    }

2892
    src->hosts->port = uri->port;
2893

2894
    src->hosts->name = g_strdup(uri->server);
2895

2896 2897 2898 2899
    /* Libvirt doesn't handle inline authentication. Make the caller aware. */
    if (uri->user)
        return 1;

2900
    return 0;
2901 2902 2903
}


2904 2905 2906 2907 2908 2909
static int
virStorageSourceRBDAddHost(virStorageSourcePtr src,
                           char *hostport)
{
    char *port;
    size_t skip;
2910
    VIR_AUTOSTRINGLIST parts = NULL;
2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926

    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;
2927
        if (virStringParsePort(port, &src->hosts[src->nhosts - 1].port) < 0)
2928 2929 2930 2931 2932 2933
            goto error;
    }

    parts = virStringSplit(hostport, "\\:", 0);
    if (!parts)
        goto error;
2934
    src->hosts[src->nhosts-1].name = virStringListJoin((const char **)parts, ":");
2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953
    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;
2954
    g_autofree char *options = NULL;
J
Ján Tomko 已提交
2955
    g_autoptr(virStorageAuthDef) authdef = NULL;
2956 2957 2958 2959 2960

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

2961
    src->path = g_strdup(rbdstr);
2962 2963 2964

    p = strchr(src->path, ':');
    if (p) {
2965
        options = g_strdup(p + 1);
2966 2967 2968
        *p = '\0';
    }

2969 2970
    /* snapshot name */
    if ((p = strchr(src->path, '@'))) {
2971
        src->snapshot = g_strdup(p + 1);
2972 2973 2974
        *p = '\0';
    }

2975 2976
    /* pool vs. image name */
    if ((p = strchr(src->path, '/'))) {
2977
        src->volume = g_steal_pointer(&src->path);
2978
        src->path = g_strdup(p + 1);
2979 2980 2981
        *p = '\0';
    }

2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004
    /* 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 */
3005 3006 3007 3008 3009
            if (src->auth) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("duplicate 'id' found in '%s'"), src->path);
                return -1;
            }
3010
            if (VIR_ALLOC(authdef) < 0)
3011
                return -1;
3012

3013
            authdef->username = g_strdup(p + strlen("id="));
3014

3015
            authdef->secrettype = g_strdup(virSecretUsageTypeToString(VIR_SECRET_USAGE_TYPE_CEPH));
3016
            src->auth = g_steal_pointer(&authdef);
3017
            src->authInherited = true;
3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038

            /* 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)
3039
                    return -1;
3040 3041 3042 3043 3044

                h = sep;
            }
        }

3045 3046
        if (STRPREFIX(p, "conf="))
            src->configFile = g_strdup(p + strlen("conf="));
3047

3048 3049 3050 3051 3052 3053
        p = next;
    }
    return 0;
}


3054
static int
3055 3056
virStorageSourceParseNBDColonString(const char *nbdstr,
                                    virStorageSourcePtr src)
3057
{
3058 3059 3060 3061 3062
    g_autofree char *nbd = g_strdup(nbdstr);
    char *export_name;
    char *host_spec;
    char *unixpath;
    char *port;
3063

3064
    src->hosts = g_new0(virStorageNetHostDef, 1);
3065
    src->nhosts = 1;
3066 3067

    /* We extract the parameters in a similar way qemu does it */
3068 3069 3070 3071 3072

    /* format: [] denotes optional sections, uppercase are variable strings
     * nbd:unix:/PATH/TO/SOCKET[:exportname=EXPORTNAME]
     * nbd:HOSTNAME:PORT[:exportname=EXPORTNAME]
     */
3073

3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085
    /* first look for ':exportname=' and cut it off */
    if ((export_name = strstr(nbd, ":exportname="))) {
        src->path = g_strdup(export_name + strlen(":exportname="));
        export_name[0] = '\0';
    }

    /* Verify the prefix and contents. Note that we require a
     * "host_spec" part to be present. */
    if (!(host_spec = STRSKIP(nbd, "nbd:")) || host_spec[0] == '\0')
        goto malformed;

    if ((unixpath = STRSKIP(host_spec, "unix:"))) {
3086
        src->hosts->transport = VIR_STORAGE_NET_HOST_TRANS_UNIX;
3087

3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114
        if (unixpath[0] == '\0')
            goto malformed;

        src->hosts->socket = g_strdup(unixpath);
    } else {
        src->hosts->transport = VIR_STORAGE_NET_HOST_TRANS_TCP;

        if (host_spec[0] == ':') {
            /* no host given */
            goto malformed;
        } else if (host_spec[0] == '[') {
            host_spec++;
            /* IPv6 addr */
            if (!(port = strstr(host_spec, "]:")))
                goto malformed;

            port[0] = '\0';
            port += 2;

            if (host_spec[0] == '\0')
                goto malformed;
        } else {
            if (!(port = strchr(host_spec, ':')))
                goto malformed;

            port[0] = '\0';
            port++;
3115
        }
3116

3117
        if (virStringParsePort(port, &src->hosts->port) < 0)
3118
            return -1;
3119

3120
        src->hosts->name = g_strdup(host_spec);
3121
    }
3122

3123
    return 0;
3124 3125 3126 3127 3128

 malformed:
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   _("malformed nbd string '%s'"), nbdstr);
    return -1;
3129 3130 3131 3132 3133 3134 3135 3136
}


static int
virStorageSourceParseBackingColon(virStorageSourcePtr src,
                                  const char *path)
{
    const char *p;
3137
    g_autofree char *protocol = NULL;
3138 3139 3140 3141 3142

    if (!(p = strchr(path, ':'))) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("invalid backing protocol string '%s'"),
                       path);
3143
        return -1;
3144 3145
    }

3146
    protocol = g_strndup(path, p - path);
3147 3148 3149 3150 3151

    if ((src->protocol = virStorageNetProtocolTypeFromString(protocol)) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("invalid backing protocol '%s'"),
                       protocol);
3152
        return -1;
3153 3154 3155 3156 3157
    }

    switch ((virStorageNetProtocol) src->protocol) {
    case VIR_STORAGE_NET_PROTOCOL_NBD:
        if (virStorageSourceParseNBDColonString(path, src) < 0)
3158
            return -1;
3159
        break;
3160 3161

    case VIR_STORAGE_NET_PROTOCOL_RBD:
3162
        if (virStorageSourceParseRBDColonString(path, src) < 0)
3163
            return -1;
3164 3165 3166
        break;

    case VIR_STORAGE_NET_PROTOCOL_SHEEPDOG:
3167 3168 3169 3170
    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"),
3171
                       protocol);
3172
        return -1;
3173 3174 3175 3176 3177 3178 3179 3180

    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:
3181
    case VIR_STORAGE_NET_PROTOCOL_SSH:
3182
    case VIR_STORAGE_NET_PROTOCOL_VXHS:
3183 3184
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("malformed backing store path for protocol %s"),
3185
                       protocol);
3186
        return -1;
3187 3188
    }

3189
    return 0;
3190 3191 3192
}


3193 3194
static int
virStorageSourceParseBackingJSONInternal(virStorageSourcePtr src,
3195
                                         virJSONValuePtr json,
3196 3197
                                         const char *jsonstr,
                                         bool allowformat);
3198 3199


3200 3201 3202
static int
virStorageSourceParseBackingJSONPath(virStorageSourcePtr src,
                                     virJSONValuePtr json,
3203
                                     const char *jsonstr G_GNUC_UNUSED,
3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214
                                     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;
    }

3215
    src->path = g_strdup(path);
3216 3217 3218 3219 3220 3221

    src->type = type;
    return 0;
}


3222 3223 3224 3225 3226
static int
virStorageSourceParseBackingJSONUriStr(virStorageSourcePtr src,
                                       const char *uri,
                                       int protocol)
{
3227 3228 3229
    int rc;

    if ((rc = virStorageSourceParseBackingURI(src, uri)) < 0)
3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240
        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;
    }

3241
    return rc;
3242 3243 3244
}


3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 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 3295
static int
virStorageSourceParseBackingJSONUriCookies(virStorageSourcePtr src,
                                           virJSONValuePtr json,
                                           const char *jsonstr)
{
    const char *cookiestr;
    VIR_AUTOSTRINGLIST cookies = NULL;
    size_t ncookies = 0;
    size_t i;

    if (!virJSONValueObjectHasKey(json, "cookie"))
        return 0;

    if (!(cookiestr = virJSONValueObjectGetString(json, "cookie"))) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("wrong format of 'cookie' field in backing store definition '%s'"),
                       jsonstr);
        return -1;
    }

    if (!(cookies = virStringSplitCount(cookiestr, ";", 0, &ncookies)))
        return -1;

    src->cookies = g_new0(virStorageNetCookieDefPtr, ncookies);
    src->ncookies = ncookies;

    for (i = 0; i < ncookies; i++) {
        char *cookiename = cookies[i];
        char *cookievalue;

        virSkipSpaces((const char **) &cookiename);

        if (!(cookievalue = strchr(cookiename, '='))) {
            virReportError(VIR_ERR_INVALID_ARG,
                           _("malformed http cookie '%s' in backing store definition '%s'"),
                           cookies[i], jsonstr);
            return -1;
        }

        *cookievalue = '\0';
        cookievalue++;

        src->cookies[i] = g_new0(virStorageNetCookieDef, 1);
        src->cookies[i]->name = g_strdup(cookiename);
        src->cookies[i]->value = g_strdup(cookievalue);
    }

    return 0;
}


3296 3297 3298
static int
virStorageSourceParseBackingJSONUri(virStorageSourcePtr src,
                                    virJSONValuePtr json,
3299
                                    const char *jsonstr,
3300 3301 3302 3303
                                    int protocol)
{
    const char *uri;

3304
    if (!(uri = virJSONValueObjectGetString(json, "url"))) {
3305
        virReportError(VIR_ERR_INVALID_ARG, "%s",
3306
                       _("missing 'url' in JSON backing volume definition"));
3307 3308 3309
        return -1;
    }

3310 3311 3312
    if (protocol == VIR_STORAGE_NET_PROTOCOL_HTTPS ||
        protocol == VIR_STORAGE_NET_PROTOCOL_FTPS) {
        if (virJSONValueObjectHasKey(json, "sslverify")) {
3313
            const char *tmpstr;
3314 3315
            bool tmp;

3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326
            /* libguestfs still uses undocumented legacy value of 'off' */
            if ((tmpstr = virJSONValueObjectGetString(json, "sslverify")) &&
                STREQ(tmpstr, "off")) {
                src->sslverify = VIR_TRISTATE_BOOL_NO;
            } else {
                if (virJSONValueObjectGetBoolean(json, "sslverify", &tmp) < 0) {
                    virReportError(VIR_ERR_INVALID_ARG,
                                   _("malformed 'sslverify' field in backing store definition '%s'"),
                                   jsonstr);
                    return -1;
                }
3327

3328 3329
                src->sslverify = virTristateBoolFromBool(tmp);
            }
3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354
        }
    }

    if (protocol == VIR_STORAGE_NET_PROTOCOL_HTTPS ||
        protocol == VIR_STORAGE_NET_PROTOCOL_HTTP) {
        if (virStorageSourceParseBackingJSONUriCookies(src, json, jsonstr) < 0)
            return -1;
    }

    if (virJSONValueObjectHasKey(json, "readahead") &&
        virJSONValueObjectGetNumberUlong(json, "readahead", &src->readahead) < 0) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("malformed 'readahead' field in backing store definition '%s'"),
                       jsonstr);
        return -1;
    }

    if (virJSONValueObjectHasKey(json, "timeout") &&
        virJSONValueObjectGetNumberUlong(json, "timeout", &src->timeout) < 0) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("malformed 'timeout' field in backing store definition '%s'"),
                       jsonstr);
        return -1;
    }

3355 3356 3357 3358
    return virStorageSourceParseBackingJSONUriStr(src, uri, protocol);
}


3359 3360 3361 3362
static int
virStorageSourceParseBackingJSONInetSocketAddress(virStorageNetHostDefPtr host,
                                                  virJSONValuePtr json)
{
3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374
    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");
3375 3376 3377 3378 3379 3380 3381 3382 3383

    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;
3384
    host->name = g_strdup(hostname);
3385

3386
    if (virStringParsePort(port, &host->port) < 0)
3387 3388 3389 3390 3391 3392
        return -1;

    return 0;
}


3393
static int
3394 3395
virStorageSourceParseBackingJSONSocketAddress(virStorageNetHostDefPtr host,
                                              virJSONValuePtr json)
3396
{
3397 3398 3399 3400 3401 3402 3403 3404 3405
    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;
    }
3406

3407
    if (!(type = virJSONValueObjectGetString(json, "type"))) {
3408 3409 3410
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("missing socket address type in "
                         "JSON backing volume definition"));
3411 3412 3413
        return -1;
    }

3414
    if (STREQ(type, "tcp") || STREQ(type, "inet")) {
3415
        return virStorageSourceParseBackingJSONInetSocketAddress(host, json);
3416

3417 3418
    } else if (STREQ(type, "unix")) {
        host->transport = VIR_STORAGE_NET_HOST_TRANS_UNIX;
3419

3420 3421 3422 3423 3424 3425 3426
        socket = virJSONValueObjectGetString(json, "path");

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

        if (!socket) {
3427 3428
            virReportError(VIR_ERR_INVALID_ARG, "%s",
                           _("missing socket path for udp backing server in "
3429
                             "JSON backing volume definition"));
3430 3431 3432
            return -1;
        }

3433
        host->socket = g_strdup(socket);
3434
    } else {
3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447
        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,
3448
                                        const char *jsonstr G_GNUC_UNUSED,
J
Ján Tomko 已提交
3449
                                        int opaque G_GNUC_UNUSED)
3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469
{
    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;
    }

3470 3471 3472
    src->type = VIR_STORAGE_TYPE_NETWORK;
    src->protocol = VIR_STORAGE_NET_PROTOCOL_GLUSTER;

3473 3474
    src->volume = g_strdup(volume);
    src->path = g_strdup(path);
3475 3476

    nservers = virJSONValueArraySize(server);
3477
    if (nservers == 0) {
3478 3479 3480
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("at least 1 server is necessary in "
                         "JSON backing definition for gluster volume"));
3481 3482

        return -1;
3483 3484 3485 3486 3487 3488 3489
    }

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

    for (i = 0; i < nservers; i++) {
3490 3491
        if (virStorageSourceParseBackingJSONSocketAddress(src->hosts + i,
                                                          virJSONValueArrayGet(server, i)) < 0)
3492 3493 3494 3495 3496 3497 3498
            return -1;
    }

    return 0;
}


3499 3500 3501
static int
virStorageSourceParseBackingJSONiSCSI(virStorageSourcePtr src,
                                      virJSONValuePtr json,
3502
                                      const char *jsonstr G_GNUC_UNUSED,
J
Ján Tomko 已提交
3503
                                      int opaque G_GNUC_UNUSED)
3504
{
3505 3506 3507
    const char *transport = virJSONValueObjectGetString(json, "transport");
    const char *portal = virJSONValueObjectGetString(json, "portal");
    const char *target = virJSONValueObjectGetString(json, "target");
3508
    const char *lun = virJSONValueObjectGetStringOrNumber(json, "lun");
3509
    const char *uri;
3510
    char *port;
3511 3512 3513 3514 3515 3516

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

3517 3518
    src->type = VIR_STORAGE_TYPE_NETWORK;
    src->protocol = VIR_STORAGE_NET_PROTOCOL_ISCSI;
3519

3520 3521 3522
    if (!lun)
        lun = "0";

3523
    if (VIR_ALLOC(src->hosts) < 0)
3524
        return -1;
3525 3526 3527 3528 3529 3530

    src->nhosts = 1;

    if (STRNEQ_NULLABLE(transport, "tcp")) {
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("only TCP transport is supported for iSCSI volumes"));
3531
        return -1;
3532 3533 3534 3535 3536 3537 3538
    }

    src->hosts->transport = VIR_STORAGE_NET_HOST_TRANS_TCP;

    if (!portal) {
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("missing 'portal' address in iSCSI backing definition"));
3539
        return -1;
3540 3541 3542 3543 3544
    }

    if (!target) {
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("missing 'target' in iSCSI backing definition"));
3545
        return -1;
3546 3547
    }

3548
    src->hosts->name = g_strdup(portal);
3549

3550 3551
    if ((port = strrchr(src->hosts->name, ':')) &&
        !strchr(port, ']')) {
3552
        if (virStringParsePort(port + 1, &src->hosts->port) < 0)
3553
            return -1;
3554 3555 3556 3557

        *port = '\0';
    }

3558
    src->path = g_strdup_printf("%s/%s", target, lun);
3559

3560 3561 3562 3563 3564
    /* Libvirt doesn't handle inline authentication. Make the caller aware. */
    if (virJSONValueObjectGetString(json, "user") ||
        virJSONValueObjectGetString(json, "password"))
        return 1;

3565
    return 0;
3566 3567 3568
}


3569 3570 3571
static int
virStorageSourceParseBackingJSONNbd(virStorageSourcePtr src,
                                    virJSONValuePtr json,
3572
                                    const char *jsonstr G_GNUC_UNUSED,
J
Ján Tomko 已提交
3573
                                    int opaque G_GNUC_UNUSED)
3574 3575 3576 3577 3578
{
    const char *path = virJSONValueObjectGetString(json, "path");
    const char *host = virJSONValueObjectGetString(json, "host");
    const char *port = virJSONValueObjectGetString(json, "port");
    const char *export = virJSONValueObjectGetString(json, "export");
3579
    virJSONValuePtr server = virJSONValueObjectGetObject(json, "server");
3580

3581
    if (!path && !host && !server) {
3582
        virReportError(VIR_ERR_INVALID_ARG, "%s",
3583 3584
                       _("missing host specification of NBD server in JSON "
                         "backing volume definition"));
3585 3586 3587 3588 3589 3590
        return -1;
    }

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

3591
    src->path = g_strdup(export);
3592 3593 3594 3595 3596

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

3597 3598
    if (server) {
        if (virStorageSourceParseBackingJSONSocketAddress(src->hosts, server) < 0)
3599 3600
            return -1;
    } else {
3601 3602
        if (path) {
            src->hosts[0].transport = VIR_STORAGE_NET_HOST_TRANS_UNIX;
3603
            src->hosts[0].socket = g_strdup(path);
3604 3605
        } else {
            src->hosts[0].transport = VIR_STORAGE_NET_HOST_TRANS_TCP;
3606
            src->hosts[0].name = g_strdup(host);
3607

3608
            if (virStringParsePort(port, &src->hosts[0].port) < 0)
3609 3610
                return -1;
        }
3611 3612 3613 3614 3615 3616
    }

    return 0;
}


3617 3618 3619
static int
virStorageSourceParseBackingJSONSheepdog(virStorageSourcePtr src,
                                         virJSONValuePtr json,
3620
                                         const char *jsonstr G_GNUC_UNUSED,
J
Ján Tomko 已提交
3621
                                         int opaque G_GNUC_UNUSED)
3622 3623
{
    const char *filename;
3624 3625
    const char *vdi = virJSONValueObjectGetString(json, "vdi");
    virJSONValuePtr server = virJSONValueObjectGetObject(json, "server");
3626 3627 3628 3629 3630 3631 3632 3633

    /* 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 */
3634 3635 3636
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("missing sheepdog URI in JSON backing volume definition"));
        return -1;
3637 3638
    }

3639 3640
    src->type = VIR_STORAGE_TYPE_NETWORK;
    src->protocol = VIR_STORAGE_NET_PROTOCOL_SHEEPDOG;
3641

3642 3643 3644 3645 3646
    if (!vdi) {
        virReportError(VIR_ERR_INVALID_ARG, "%s", _("missing sheepdog vdi name"));
        return -1;
    }

3647
    src->path = g_strdup(vdi);
3648 3649 3650 3651 3652 3653 3654 3655 3656 3657

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

    src->nhosts = 1;

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

    return 0;
3658 3659 3660
}


3661 3662 3663
static int
virStorageSourceParseBackingJSONSSH(virStorageSourcePtr src,
                                    virJSONValuePtr json,
3664
                                    const char *jsonstr G_GNUC_UNUSED,
J
Ján Tomko 已提交
3665
                                    int opaque G_GNUC_UNUSED)
3666 3667 3668 3669
{
    const char *path = virJSONValueObjectGetString(json, "path");
    const char *host = virJSONValueObjectGetString(json, "host");
    const char *port = virJSONValueObjectGetString(json, "port");
3670 3671
    const char *user = virJSONValueObjectGetString(json, "user");
    const char *host_key_check = virJSONValueObjectGetString(json, "host_key_check");
3672
    virJSONValuePtr server = virJSONValueObjectGetObject(json, "server");
3673

3674
    if (!(host || server) || !path) {
3675
        virReportError(VIR_ERR_INVALID_ARG, "%s",
3676
                       _("missing host/server or path of SSH JSON backing "
3677 3678 3679 3680 3681 3682 3683
                         "volume definition"));
        return -1;
    }

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

3684
    src->path = g_strdup(path);
3685 3686 3687 3688 3689

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

3690 3691 3692 3693 3694 3695
    if (server) {
        if (virStorageSourceParseBackingJSONInetSocketAddress(src->hosts,
                                                              server) < 0)
            return -1;
    } else {
        src->hosts[0].transport = VIR_STORAGE_NET_HOST_TRANS_TCP;
3696
        src->hosts[0].name = g_strdup(host);
3697

3698
        if (virStringParsePort(port, &src->hosts[0].port) < 0)
3699 3700
            return -1;
    }
3701

3702 3703 3704 3705 3706
    /* these two are parsed just to be passed back as we don't model them yet */
    src->ssh_user = g_strdup(user);
    if (STREQ_NULLABLE(host_key_check, "no"))
        src->ssh_host_key_check_disabled = true;

3707 3708 3709 3710
    return 0;
}


3711 3712 3713
static int
virStorageSourceParseBackingJSONRBD(virStorageSourcePtr src,
                                    virJSONValuePtr json,
3714
                                    const char *jsonstr G_GNUC_UNUSED,
J
Ján Tomko 已提交
3715
                                    int opaque G_GNUC_UNUSED)
3716 3717
{
    const char *filename;
3718 3719 3720 3721 3722 3723 3724
    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;
3725 3726 3727 3728 3729 3730 3731 3732

    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);

3733 3734 3735 3736 3737 3738
    if (!pool || !image) {
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("missing pool or image name in ceph backing volume "
                         "JSON specification"));
        return -1;
    }
3739

3740 3741 3742 3743
    src->volume = g_strdup(pool);
    src->path = g_strdup(image);
    src->snapshot = g_strdup(snapshot);
    src->configFile = g_strdup(conf);
3744 3745 3746 3747 3748

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

        if (VIR_ALLOC_N(src->hosts, nservers) < 0)
3749
            return -1;
3750 3751 3752 3753 3754 3755

        src->nhosts = nservers;

        for (i = 0; i < nservers; i++) {
            if (virStorageSourceParseBackingJSONInetSocketAddress(src->hosts + i,
                                                                  virJSONValueArrayGet(servers, i)) < 0)
3756
                return -1;
3757 3758 3759
        }
    }

3760
    return 0;
3761 3762
}

3763 3764 3765
static int
virStorageSourceParseBackingJSONRaw(virStorageSourcePtr src,
                                    virJSONValuePtr json,
3766
                                    const char *jsonstr,
J
Ján Tomko 已提交
3767
                                    int opaque G_GNUC_UNUSED)
3768
{
3769 3770
    bool has_offset = virJSONValueObjectHasKey(json, "offset");
    bool has_size = virJSONValueObjectHasKey(json, "size");
3771 3772
    virJSONValuePtr file;

3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790
    if (has_offset || has_size) {
        src->sliceStorage = g_new0(virStorageSourceSlice, 1);

        if (has_offset &&
            virJSONValueObjectGetNumberUlong(json, "offset", &src->sliceStorage->offset) < 0) {
            virReportError(VIR_ERR_INVALID_ARG, "%s",
                           _("malformed 'offset' property of 'raw' driver"));
            return -1;
        }

        if (has_size &&
            virJSONValueObjectGetNumberUlong(json, "size", &src->sliceStorage->size) < 0) {
            virReportError(VIR_ERR_INVALID_ARG, "%s",
                           _("malformed 'size' property of 'raw' driver"));
            return -1;
        }
    }

3791 3792 3793 3794 3795 3796 3797 3798
    /* 'raw' is a format driver so it can have protocol driver children */
    if (!(file = virJSONValueObjectGetObject(json, "file"))) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("JSON backing volume definition '%s' lacks 'file' object"),
                       jsonstr);
        return -1;
    }

3799
    return virStorageSourceParseBackingJSONInternal(src, file, jsonstr, false);
3800
}
3801

3802 3803 3804 3805

static int
virStorageSourceParseBackingJSONVxHS(virStorageSourcePtr src,
                                     virJSONValuePtr json,
3806
                                     const char *jsonstr G_GNUC_UNUSED,
J
Ján Tomko 已提交
3807
                                     int opaque G_GNUC_UNUSED)
3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821
{
    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;

3822
    src->path = g_strdup(vdisk_id);
3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835

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

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

    return 0;
}


3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864
static int
virStorageSourceParseBackingJSONNVMe(virStorageSourcePtr src,
                                     virJSONValuePtr json,
                                     const char *jsonstr G_GNUC_UNUSED,
                                     int opaque G_GNUC_UNUSED)
{
    g_autoptr(virStorageSourceNVMeDef) nvme = g_new0(virStorageSourceNVMeDef, 1);
    const char *device = virJSONValueObjectGetString(json, "device");

    if (!device || virPCIDeviceAddressParse((char *) device, &nvme->pciAddr) < 0) {
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("missing or malformed 'device' field of 'nvme' storage"));
        return -1;
    }

    if (virJSONValueObjectGetNumberUlong(json, "namespace", &nvme->namespc) < 0 ||
        nvme->namespc == 0) {
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("missing or malformed 'namespace' field of 'nvme' storage"));
        return -1;
    }

    src->type = VIR_STORAGE_TYPE_NVME;
    src->nvme = g_steal_pointer(&nvme);

    return 0;
}


3865 3866
struct virStorageSourceJSONDriverParser {
    const char *drvname;
3867
    bool formatdriver;
3868 3869 3870 3871 3872 3873 3874
    /**
     * The callback gets a pre-allocated storage source @src and the JSON
     * object to parse. The callback shall return -1 on error and report error
     * 0 on success and 1 in cases when the configuration itself is valid, but
     * can't be converted to libvirt's configuration (e.g. inline authentication
     * credentials are present).
     */
3875
    int (*func)(virStorageSourcePtr src, virJSONValuePtr json, const char *jsonstr, int opaque);
3876 3877 3878 3879
    int opaque;
};

static const struct virStorageSourceJSONDriverParser jsonParsers[] = {
3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895
    {"file", false, virStorageSourceParseBackingJSONPath, VIR_STORAGE_TYPE_FILE},
    {"host_device", false, virStorageSourceParseBackingJSONPath, VIR_STORAGE_TYPE_BLOCK},
    {"host_cdrom", false, virStorageSourceParseBackingJSONPath, VIR_STORAGE_TYPE_BLOCK},
    {"http", false, virStorageSourceParseBackingJSONUri, VIR_STORAGE_NET_PROTOCOL_HTTP},
    {"https", false, virStorageSourceParseBackingJSONUri, VIR_STORAGE_NET_PROTOCOL_HTTPS},
    {"ftp", false, virStorageSourceParseBackingJSONUri, VIR_STORAGE_NET_PROTOCOL_FTP},
    {"ftps", false, virStorageSourceParseBackingJSONUri, VIR_STORAGE_NET_PROTOCOL_FTPS},
    {"tftp", false, virStorageSourceParseBackingJSONUri, VIR_STORAGE_NET_PROTOCOL_TFTP},
    {"gluster", false, virStorageSourceParseBackingJSONGluster, 0},
    {"iscsi", false, virStorageSourceParseBackingJSONiSCSI, 0},
    {"nbd", false, virStorageSourceParseBackingJSONNbd, 0},
    {"sheepdog", false, virStorageSourceParseBackingJSONSheepdog, 0},
    {"ssh", false, virStorageSourceParseBackingJSONSSH, 0},
    {"rbd", false, virStorageSourceParseBackingJSONRBD, 0},
    {"raw", true, virStorageSourceParseBackingJSONRaw, 0},
    {"vxhs", false, virStorageSourceParseBackingJSONVxHS, 0},
3896
    {"nvme", false, virStorageSourceParseBackingJSONNVMe, 0},
3897 3898 3899 3900 3901
};



static int
3902
virStorageSourceParseBackingJSONInternal(virStorageSourcePtr src,
3903
                                         virJSONValuePtr json,
3904 3905
                                         const char *jsonstr,
                                         bool allowformat)
3906 3907 3908 3909
{
    const char *drvname;
    size_t i;

3910
    if (!(drvname = virJSONValueObjectGetString(json, "driver"))) {
3911
        virReportError(VIR_ERR_INVALID_ARG,
3912
                       _("JSON backing volume definition '%s' lacks driver name"),
3913
                       jsonstr);
3914
        return -1;
3915 3916
    }

3917
    for (i = 0; i < G_N_ELEMENTS(jsonParsers); i++) {
3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928
        if (STRNEQ(drvname, jsonParsers[i].drvname))
            continue;

        if (jsonParsers[i].formatdriver && !allowformat) {
            virReportError(VIR_ERR_INVALID_ARG,
                           _("JSON backing volume definition '%s' must not have nested format drivers"),
                           jsonstr);
            return -1;
        }

        return jsonParsers[i].func(src, json, jsonstr, jsonParsers[i].opaque);
3929 3930 3931 3932 3933
    }

    virReportError(VIR_ERR_INTERNAL_ERROR,
                   _("missing parser implementation for JSON backing volume "
                     "driver '%s'"), drvname);
3934
    return -1;
3935 3936 3937
}


3938 3939 3940 3941
static int
virStorageSourceParseBackingJSON(virStorageSourcePtr src,
                                 const char *json)
{
J
Ján Tomko 已提交
3942
    g_autoptr(virJSONValue) root = NULL;
3943
    g_autoptr(virJSONValue) deflattened = NULL;
3944
    virJSONValuePtr file = NULL;
3945 3946 3947 3948

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

3949 3950 3951
    if (!(deflattened = virJSONValueObjectDeflatten(root)))
        return -1;

3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962
    /* There are 2 possible syntaxes:
     * 1) json:{"file":{"driver":...}}
     * 2) json:{"driver":...}
     * Remove the 'file' wrapper object in case 1.
     */
    if (!virJSONValueObjectHasKey(deflattened, "driver"))
        file = virJSONValueObjectGetObject(deflattened, "file");

    if (!file)
        file = deflattened;

3963
    return virStorageSourceParseBackingJSONInternal(src, file, json, true);
3964 3965 3966
}


3967 3968 3969 3970 3971
/**
 * virStorageSourceNewFromBackingAbsolute
 * @path: string representing absolute location of a storage source
 * @src: filled with virStorageSource object representing @path
 *
3972 3973 3974 3975
 * Returns 0 on success, 1 if we could parse all location data but @path
 * specified other data unrepresentable by libvirt (e.g. inline authentication).
 * In both cases @src is filled. On error -1 is returned @src is NULL and an
 * error is reported.
3976 3977 3978 3979
 */
int
virStorageSourceNewFromBackingAbsolute(const char *path,
                                       virStorageSourcePtr *src)
3980
{
3981
    const char *json;
3982
    const char *dirpath;
3983
    int rc = 0;
3984
    g_autoptr(virStorageSource) def = NULL;
3985

3986 3987
    *src = NULL;

3988
    if (!(def = virStorageSourceNew()))
3989
        return -1;
3990 3991

    if (virStorageIsFile(path)) {
3992
        def->type = VIR_STORAGE_TYPE_FILE;
3993

3994
        def->path = g_strdup(path);
3995
    } else {
3996 3997 3998 3999 4000 4001 4002 4003
        if ((dirpath = STRSKIP(path, "fat:"))) {
            def->type = VIR_STORAGE_TYPE_DIR;
            def->format = VIR_STORAGE_FILE_FAT;
            def->path = g_strdup(dirpath);
            *src = g_steal_pointer(&def);
            return 0;
        }

4004
        def->type = VIR_STORAGE_TYPE_NETWORK;
4005

4006 4007
        VIR_DEBUG("parsing backing store string: '%s'", path);

4008
        /* handle URI formatted backing stores */
4009
        if ((json = STRSKIP(path, "json:")))
4010
            rc = virStorageSourceParseBackingJSON(def, json);
4011
        else if (strstr(path, "://"))
4012
            rc = virStorageSourceParseBackingURI(def, path);
4013
        else
4014
            rc = virStorageSourceParseBackingColon(def, path);
4015 4016

        if (rc < 0)
4017
            return -1;
4018

4019
        virStorageSourceNetworkAssignDefaultPorts(def);
4020 4021 4022 4023

        /* 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 */
4024 4025 4026
        if (def->auth) {
            virStorageAuthDefFree(def->auth);
            def->auth = NULL;
4027
        }
4028 4029
    }

4030
    *src = g_steal_pointer(&def);
4031
    return rc;
4032 4033 4034
}


4035
/**
4036
 * virStorageSourceNewFromChild:
4037
 * @parent: storage source parent
4038 4039
 * @child: returned child/backing store definition
 * @parentRaw: raw child string (backingStoreRaw)
4040 4041
 *
 * Creates a storage source which describes the backing image of @parent and
4042
 * fills it into @backing depending on the passed parentRaw (backingStoreRaw)
4043
 * and other data. Note that for local storage this function accesses the file
4044
 * to update the actual type of the child store.
4045
 *
4046
 * Returns 0 on success, 1 if we could parse all location data but the child
4047 4048 4049 4050
 * store specification contained other data unrepresentable by libvirt (e.g.
 * inline authentication).
 * In both cases @src is filled. On error -1 is returned @src is NULL and an
 * error is reported.
4051
 */
4052 4053 4054 4055
static int
virStorageSourceNewFromChild(virStorageSourcePtr parent,
                             const char *parentRaw,
                             virStorageSourcePtr *child)
4056 4057
{
    struct stat st;
4058
    g_autoptr(virStorageSource) def = NULL;
4059
    int rc = 0;
4060

4061
    *child = NULL;
4062

4063 4064
    if (virStorageIsRelative(parentRaw)) {
        if (!(def = virStorageSourceNewFromBackingRelative(parent, parentRaw)))
4065 4066
            return -1;
    } else {
4067
        if ((rc = virStorageSourceNewFromBackingAbsolute(parentRaw, &def)) < 0)
4068 4069
            return -1;
    }
4070 4071 4072 4073 4074 4075 4076 4077 4078

    /* possibly update local type */
    if (def->type == VIR_STORAGE_TYPE_FILE) {
        if (stat(def->path, &st) == 0) {
            if (S_ISDIR(st.st_mode)) {
                def->type = VIR_STORAGE_TYPE_DIR;
                def->format = VIR_STORAGE_FILE_DIR;
            } else if (S_ISBLK(st.st_mode)) {
                def->type = VIR_STORAGE_TYPE_BLOCK;
4079 4080
            }
        }
4081
    }
4082

4083 4084 4085
    /* copy parent's labelling and other top level stuff */
    if (virStorageSourceInitChainElement(def, parent, true) < 0)
        return -1;
4086

4087
    def->detected = true;
4088

4089
    *child = g_steal_pointer(&def);
4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104
    return rc;
}


int
virStorageSourceNewFromBacking(virStorageSourcePtr parent,
                               virStorageSourcePtr *backing)
{
    int rc;

    if ((rc = virStorageSourceNewFromChild(parent,
                                           parent->backingStoreRaw,
                                           backing)) < 0)
        return rc;

4105
    (*backing)->format = parent->backingStoreRawFormat;
4106
    (*backing)->readonly = true;
4107
    return rc;
4108
}
4109 4110


4111
/**
4112 4113 4114
 * @src: disk source definition structure
 * @fd: file descriptor
 * @sb: stat buffer
4115
 *
4116 4117 4118 4119
 * 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
 *
4120
 * Returns 0 on success, -1 on error. No libvirt errors are reported.
4121 4122
 */
int
4123 4124 4125
virStorageSourceUpdatePhysicalSize(virStorageSourcePtr src,
                                   int fd,
                                   struct stat const *sb)
4126 4127
{
    off_t end;
4128
    virStorageType actual_type = virStorageSourceGetActualType(src);
4129

4130 4131 4132 4133 4134
    switch (actual_type) {
    case VIR_STORAGE_TYPE_FILE:
    case VIR_STORAGE_TYPE_NETWORK:
        src->physical = sb->st_size;
        break;
4135

4136
    case VIR_STORAGE_TYPE_BLOCK:
4137
        if ((end = lseek(fd, 0, SEEK_END)) == (off_t) -1)
4138
            return -1;
4139 4140

        src->physical = end;
4141 4142 4143 4144 4145 4146 4147 4148
        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:
4149
    case VIR_STORAGE_TYPE_NVME:
4150 4151 4152
    case VIR_STORAGE_TYPE_NONE:
    case VIR_STORAGE_TYPE_LAST:
        return -1;
4153 4154
    }

4155
    return 0;
4156 4157 4158
}


4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223
/**
 * @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;
}


4224 4225 4226 4227 4228
/**
 * @src: disk source definition structure
 * @buf: buffer to the storage file header
 * @len: length of the storage file header
 *
4229
 * Update the storage @src capacity.
4230 4231 4232 4233 4234 4235
 *
 * Returns 0 on success, -1 on error.
 */
int
virStorageSourceUpdateCapacity(virStorageSourcePtr src,
                               char *buf,
4236
                               ssize_t len)
4237 4238
{
    int format = src->format;
4239
    g_autoptr(virStorageSource) meta = NULL;
4240 4241 4242 4243 4244

    /* 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) {
4245 4246 4247 4248
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("no disk format for %s was specified"),
                       src->path);
        return -1;
4249 4250
    }

4251
    if (format == VIR_STORAGE_FILE_RAW && !src->encryption) {
4252
        src->capacity = src->physical;
4253
    } else if ((meta = virStorageFileGetMetadataFromBuf(src->path, buf,
4254
                                                        len, format))) {
4255
        src->capacity = meta->capacity ? meta->capacity : src->physical;
4256 4257 4258
        if (src->encryption && meta->encryption)
            src->encryption->payload_offset = meta->encryption->payload_offset;
    } else {
4259
        return -1;
4260
    }
4261

4262 4263 4264
    if (src->encryption && src->encryption->payload_offset != -1)
        src->capacity -= src->encryption->payload_offset * 512;

4265
    return 0;
4266 4267 4268
}


4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293
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);
    }

    /* if the output string is empty just return an empty string */
    if (!(ret = virBufferContentAndReset(&buf)))
4294
        ret = g_strdup("");
4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324

    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:
4325
    virStringListFreeCount(tmp, ntmp);
4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343
    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;
4344 4345
    g_autofree char *linkpath = NULL;
    g_autofree char *currentpath = NULL;
4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 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 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472

    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);
4473
    virStringListFreeCount(components, ncomponents);
4474 4475 4476

    return ret;
}
4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492


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

4493
    ret = g_strdup(NULLSTR_EMPTY(path));
4494

4495
    virFileRemoveLastComponent(ret);
4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514

    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;
4515 4516
    g_autofree char *tmp = NULL;
    g_autofree char *path = NULL;
4517 4518 4519

    *relpath = NULL;

4520
    for (next = top; virStorageSourceIsBacking(next); next = next->backingStore) {
4521 4522
        if (!next->relPath)
            return 1;
4523 4524

        if (!(tmp = virStorageFileRemoveLastPathComponent(path)))
4525
            return -1;
4526 4527 4528

        VIR_FREE(path);

4529
        path = g_strdup_printf("%s%s", tmp, next->relPath);
4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540

        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"));
4541
        return -1;
4542 4543
    }

4544
    *relpath = g_steal_pointer(&path);
4545
    return 0;
4546
}
4547 4548 4549 4550 4551 4552 4553 4554 4555


/*
 * virStorageFileCheckCompat
 */
int
virStorageFileCheckCompat(const char *compat)
{
    unsigned int result;
4556
    VIR_AUTOSTRINGLIST version = NULL;
4557 4558 4559 4560 4561 4562 4563 4564 4565 4566

    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"));
4567
        return -1;
4568
    }
4569
    return 0;
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


/**
 * 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:
4595
    case VIR_STORAGE_TYPE_NVME:
4596 4597 4598 4599 4600 4601 4602
    case VIR_STORAGE_TYPE_NONE:
    case VIR_STORAGE_TYPE_LAST:
        return false;
    }

    return false;
}
4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617


/**
 * 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 已提交
4618
                               unsigned int *idx)
4619 4620 4621
{
    virStorageSourcePtr tmp;

E
Eric Blake 已提交
4622 4623
    if (idx)
        *idx = 0;
4624

4625
    for (tmp = top; virStorageSourceIsBacking(tmp); tmp = tmp->backingStore) {
4626
        if ((tmp->nodeformat && STREQ(tmp->nodeformat, nodeName)) ||
4627
            (tmp->nodestorage && STREQ(tmp->nodestorage, nodeName)))
4628 4629
            return tmp;

E
Eric Blake 已提交
4630 4631
        if (idx)
            (*idx)++;
4632 4633
    }

E
Eric Blake 已提交
4634 4635
    if (idx)
        *idx = 0;
4636 4637
    return NULL;
}
4638 4639


4640
static unsigned int
4641 4642 4643 4644
virStorageSourceNetworkDefaultPort(virStorageNetProtocol protocol)
{
    switch (protocol) {
        case VIR_STORAGE_NET_PROTOCOL_HTTP:
4645
            return 80;
4646 4647

        case VIR_STORAGE_NET_PROTOCOL_HTTPS:
4648
            return 443;
4649 4650

        case VIR_STORAGE_NET_PROTOCOL_FTP:
4651
            return 21;
4652 4653

        case VIR_STORAGE_NET_PROTOCOL_FTPS:
4654
            return 990;
4655 4656

        case VIR_STORAGE_NET_PROTOCOL_TFTP:
4657
            return 69;
4658 4659

        case VIR_STORAGE_NET_PROTOCOL_SHEEPDOG:
4660
            return 7000;
4661 4662

        case VIR_STORAGE_NET_PROTOCOL_NBD:
4663
            return 10809;
4664 4665

        case VIR_STORAGE_NET_PROTOCOL_SSH:
4666
            return 22;
4667 4668

        case VIR_STORAGE_NET_PROTOCOL_ISCSI:
4669
            return 3260;
4670

4671
        case VIR_STORAGE_NET_PROTOCOL_GLUSTER:
4672
            return 24007;
4673 4674

        case VIR_STORAGE_NET_PROTOCOL_RBD:
4675
            /* we don't provide a default for RBD */
4676
            return 0;
4677

4678
        case VIR_STORAGE_NET_PROTOCOL_VXHS:
4679 4680
            return 9999;

4681 4682
        case VIR_STORAGE_NET_PROTOCOL_LAST:
        case VIR_STORAGE_NET_PROTOCOL_NONE:
4683
            return 0;
4684 4685
    }

4686
    return 0;
4687
}
4688 4689


4690
void
4691 4692 4693 4694 4695 4696
virStorageSourceNetworkAssignDefaultPorts(virStorageSourcePtr src)
{
    size_t i;

    for (i = 0; i < src->nhosts; i++) {
        if (src->hosts[i].transport == VIR_STORAGE_NET_HOST_TRANS_TCP &&
4697 4698
            src->hosts[i].port == 0)
            src->hosts[i].port = virStorageSourceNetworkDefaultPort(src->protocol);
4699 4700
    }
}
4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720


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;
}
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
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)
{
4747 4748
    dest->iqn = g_strdup(src->iqn);
    return 0;
4749 4750 4751 4752 4753 4754 4755 4756
}

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

4757 4758 4759 4760 4761 4762 4763
static bool
virStorageFileIsInitialized(const virStorageSource *src)
{
    return src && src->drv;
}


4764 4765 4766 4767 4768 4769 4770 4771
/**
 * virStorageFileGetBackendForSupportCheck:
 * @src: storage source to check support for
 * @backend: pointer to the storage backend for @src if it's supported
 *
 * Returns 0 if @src is not supported by any storage backend currently linked
 * 1 if it is supported and -1 on error with an error reported.
 */
4772 4773 4774
static int
virStorageFileGetBackendForSupportCheck(const virStorageSource *src,
                                        virStorageFileBackendPtr *backend)
4775 4776 4777 4778
{
    int actualType;


4779 4780 4781 4782 4783 4784 4785
    if (!src) {
        *backend = NULL;
        return 0;
    }

    if (src->drv) {
        *backend = src->drv->backend;
4786
        return 1;
4787
    }
4788 4789 4790

    actualType = virStorageSourceGetActualType(src);

4791 4792 4793
    if (virStorageFileBackendForType(actualType, src->protocol, false, backend) < 0)
        return -1;

4794 4795 4796 4797
    if (!*backend)
        return 0;

    return 1;
4798 4799 4800
}


4801 4802
int
virStorageFileSupportsBackingChainTraversal(const virStorageSource *src)
4803 4804
{
    virStorageFileBackendPtr backend;
4805
    int rv;
4806

4807 4808
    if ((rv = virStorageFileGetBackendForSupportCheck(src, &backend)) < 1)
        return rv;
4809 4810 4811

    return backend->storageFileGetUniqueIdentifier &&
           backend->storageFileRead &&
4812
           backend->storageFileAccess ? 1 : 0;
4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823
}


/**
 * virStorageFileSupportsSecurityDriver:
 *
 * @src: a storage file structure
 *
 * Check if a storage file supports operations needed by the security
 * driver to perform labelling
 */
4824
int
4825 4826 4827
virStorageFileSupportsSecurityDriver(const virStorageSource *src)
{
    virStorageFileBackendPtr backend;
4828
    int rv;
4829

4830 4831
    if ((rv = virStorageFileGetBackendForSupportCheck(src, &backend)) < 1)
        return rv;
4832

4833
    return backend->storageFileChown ? 1 : 0;
4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844
}


/**
 * virStorageFileSupportsAccess:
 *
 * @src: a storage file structure
 *
 * Check if a storage file supports checking if the storage source is accessible
 * for the given vm.
 */
4845
int
4846 4847 4848
virStorageFileSupportsAccess(const virStorageSource *src)
{
    virStorageFileBackendPtr backend;
4849
    int rv;
4850

4851 4852
    if ((rv = virStorageFileGetBackendForSupportCheck(src, &backend)) < 1)
        return rv;
4853

4854
    return backend->storageFileAccess ? 1 : 0;
4855 4856 4857
}


4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877
/**
 * virStorageFileSupportsCreate:
 * @src: a storage file structure
 *
 * Check if the storage driver supports creating storage described by @src
 * via virStorageFileCreate.
 */
int
virStorageFileSupportsCreate(const virStorageSource *src)
{
    virStorageFileBackendPtr backend;
    int rv;

    if ((rv = virStorageFileGetBackendForSupportCheck(src, &backend)) < 1)
        return rv;

    return backend->storageFileCreate ? 1 : 0;
}


4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922
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;

4923 4924 4925 4926
    if (virStorageFileBackendForType(actualType,
                                     src->protocol,
                                     true,
                                     &src->drv->backend) < 0)
4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067
        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;
    }

5068
    if (!src->drv->backend->storageFileRead)
5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099
        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 "
5100
                         "storage type %s (protocol: %s)'"),
5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208
                       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);
        }
    }
}


static int
5209 5210 5211 5212 5213 5214 5215
virStorageFileGetMetadataRecurseReadHeader(virStorageSourcePtr src,
                                           virStorageSourcePtr parent,
                                           uid_t uid,
                                           gid_t gid,
                                           char **buf,
                                           size_t *headerLen,
                                           virHashTablePtr cycle)
5216 5217 5218
{
    int ret = -1;
    const char *uniqueName;
5219
    ssize_t len;
5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231

    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;

5232
    if (virHashHasEntry(cycle, uniqueName)) {
5233 5234
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("backing store for %s (%s) is self-referential"),
5235
                       NULLSTR(src->path), uniqueName);
5236 5237 5238
        goto cleanup;
    }

5239
    if (virHashAddEntry(cycle, uniqueName, NULL) < 0)
5240 5241
        goto cleanup;

5242
    if ((len = virStorageFileRead(src, 0, VIR_STORAGE_MAX_HEADER, buf)) < 0)
5243 5244
        goto cleanup;

5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262
    *headerLen = len;
    ret = 0;

 cleanup:
    virStorageFileDeinit(src);
    return ret;
}


/* 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)
{
5263
    virStorageFileFormat orig_format = src->format;
5264 5265 5266 5267 5268 5269 5270 5271 5272
    size_t headerLen;
    int rv;
    g_autofree char *buf = NULL;
    g_autoptr(virStorageSource) backingStore = NULL;

    VIR_DEBUG("path=%s format=%d uid=%u gid=%u",
              NULLSTR(src->path), src->format,
              (unsigned int)uid, (unsigned int)gid);

5273 5274 5275
    if (src->format == VIR_STORAGE_FILE_AUTO_SAFE)
        src->format = VIR_STORAGE_FILE_AUTO;

5276 5277
    /* exit if we can't load information about the current image */
    rv = virStorageFileSupportsBackingChainTraversal(src);
5278 5279 5280 5281
    if (rv <= 0) {
        if (orig_format == VIR_STORAGE_FILE_AUTO)
            return -2;

5282
        return rv;
5283
    }
5284 5285 5286 5287 5288

    if (virStorageFileGetMetadataRecurseReadHeader(src, parent, uid, gid,
                                                   &buf, &headerLen, cycle) < 0)
        return -1;

5289
    if (virStorageFileGetMetadataInternal(src, buf, headerLen) < 0)
5290
        return -1;
5291

5292
    /* If we probed the format we MUST ensure that nothing else than the current
5293
     * image is considered for security labelling and/or recursion. */
5294
    if (orig_format == VIR_STORAGE_FILE_AUTO) {
5295
        if (src->backingStoreRaw) {
5296 5297 5298 5299 5300 5301
            src->format = VIR_STORAGE_FILE_RAW;
            VIR_FREE(src->backingStoreRaw);
            return -2;
        }
    }

5302
    if (src->backingStoreRaw) {
5303
        if ((rv = virStorageSourceNewFromBacking(src, &backingStore)) < 0)
5304
            return -1;
5305

5306 5307 5308
        /* the backing file would not be usable for VM usage */
        if (rv == 1)
            return 0;
5309

5310 5311 5312 5313 5314 5315 5316 5317
        if ((rv = virStorageFileGetMetadataRecurse(backingStore, parent,
                                                   uid, gid,
                                                   report_broken,
                                                   cycle, depth + 1)) < 0) {
            if (!report_broken)
                return 0;

            if (rv == -2) {
5318
                virReportError(VIR_ERR_OPERATION_INVALID,
5319 5320
                               _("format of backing image '%s' of image '%s' was not specified in the image metadata "
                                 "(See https://libvirt.org/kbase/backing_chains.html for troubleshooting)"),
5321 5322 5323
                               src->backingStoreRaw, NULLSTR(src->path));
            }

5324
            return -1;
5325
        }
5326 5327 5328

        backingStore->id = depth;
        src->backingStore = g_steal_pointer(&backingStore);
5329 5330
    } else {
        /* add terminator */
5331
        if (!(src->backingStore = virStorageSourceNew()))
5332
            return -1;
5333 5334
    }

5335
    return 0;
5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354
}


/**
 * 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
5355 5356
 * error instead of just returning a broken chain. Note that the inability for
 * libvirt to traverse a given source is not considered an error.
5357
 *
5358
 * Caller MUST free result after use via virObjectUnref.
5359 5360 5361 5362 5363 5364
 */
int
virStorageFileGetMetadata(virStorageSourcePtr src,
                          uid_t uid, gid_t gid,
                          bool report_broken)
{
5365
    VIR_DEBUG("path=%s format=%d uid=%u gid=%u report_broken=%d",
5366
              src->path, src->format, (unsigned int)uid, (unsigned int)gid,
5367
              report_broken);
5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383

    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,
5384
                                           report_broken, cycle, 1);
5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399

    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.
 */
5400 5401 5402
int
virStorageFileGetBackingStoreStr(virStorageSourcePtr src,
                                 char **backing)
5403 5404
{
    ssize_t headerLen;
5405
    int rv;
5406
    g_autofree char *buf = NULL;
5407
    g_autoptr(virStorageSource) tmp = NULL;
5408 5409

    *backing = NULL;
5410 5411 5412

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

5415 5416 5417 5418 5419 5420 5421
    rv = virStorageFileAccess(src, F_OK);
    if (rv == -2)
        return 0;
    if (rv < 0) {
        virStorageFileReportBrokenChain(errno, src, src);
        return -1;
    }
5422 5423

    if ((headerLen = virStorageFileRead(src, 0, VIR_STORAGE_MAX_HEADER,
5424 5425 5426 5427 5428
                                        &buf)) < 0) {
        if (headerLen == -2)
            return 0;
        return -1;
    }
5429 5430

    if (!(tmp = virStorageSourceCopy(src, false)))
5431
        return -1;
5432

5433
    if (virStorageFileGetMetadataInternal(tmp, buf, headerLen) < 0)
5434
        return -1;
5435

5436
    *backing = g_steal_pointer(&tmp->backingStoreRaw);
5437
    return 0;
5438
}