virstoragefile.c 112.7 KB
Newer Older
1
/*
2
 * virstoragefile.c: file utility functions for FS storage backend
3
 *
E
Eric Blake 已提交
4
 * Copyright (C) 2007-2017 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17
 * Copyright (C) 2007-2008 Daniel P. Berrange
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with this library.  If not, see
O
Osier Yang 已提交
19
 * <http://www.gnu.org/licenses/>.
20 21 22 23 24
 *
 * Author: Daniel P. Berrange <berrange@redhat.com>
 */

#include <config.h>
25
#include "virstoragefile.h"
26

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

#define VIR_FROM_THIS VIR_FROM_STORAGE

51 52
VIR_LOG_INIT("util.storagefile");

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

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 70
              /* Formats with backing file below here */
              "cow", "qcow", "qcow2", "qed", "vmdk")
71

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

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

VIR_ENUM_IMPL(virStorageNetHostTransport, VIR_STORAGE_NET_HOST_TRANS_LAST,
              "tcp",
              "unix",
              "rdma")

97 98 99 100 101
VIR_ENUM_IMPL(virStorageSourcePoolMode,
              VIR_STORAGE_SOURCE_POOL_MODE_LAST,
              "default",
              "host",
              "direct")
102

103 104 105 106
VIR_ENUM_IMPL(virStorageAuth,
              VIR_STORAGE_AUTH_TYPE_LAST,
              "none", "chap", "ceph")

107 108 109 110 111 112 113 114 115 116 117
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 已提交
118
#define FILE_TYPE_VERSIONS_LAST 3
119

120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
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 */
138 139

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

142 143
/* Either 'magic' or 'extension' *must* be provided */
struct FileTypeInfo {
144
    int magicOffset;    /* Byte offset of the magic */
145 146 147 148
    const char *magic;  /* Optional string of file magic
                         * to check at head of file */
    const char *extension; /* Optional file extension to check */
    enum lv_endian endian; /* Endianness of file format */
149

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

172

173
static int cowGetBackingStore(char **, int *,
E
Eric Blake 已提交
174
                              const char *, size_t);
175
static int qcow1GetBackingStore(char **, int *,
E
Eric Blake 已提交
176
                                const char *, size_t);
177
static int qcow2GetBackingStore(char **, int *,
E
Eric Blake 已提交
178
                                const char *, size_t);
179
static int qcow2GetFeatures(virBitmapPtr *features, int format,
E
Eric Blake 已提交
180
                            char *buf, ssize_t len);
181
static int vmdk4GetBackingStore(char **, int *,
E
Eric Blake 已提交
182
                                const char *, size_t);
183
static int
E
Eric Blake 已提交
184
qedGetBackingStore(char **, int *, const char *, size_t);
185 186 187 188 189 190

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

191
#define QCOW1_HDR_CRYPT (QCOWX_HDR_IMAGE_SIZE+8+1+1+2)
192 193 194 195 196 197 198 199
#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

200 201 202 203 204 205 206
#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)

207
#define QED_HDR_FEATURES_OFFSET (4+4+4+4)
208 209
#define QED_HDR_IMAGE_SIZE (QED_HDR_FEATURES_OFFSET+8+8+8+8)
#define QED_HDR_BACKING_FILE_OFFSET (QED_HDR_IMAGE_SIZE+8)
210 211 212
#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 已提交
213

214 215
#define PLOOP_IMAGE_SIZE_OFFSET 36
#define PLOOP_SIZE_MULTIPLIER 512
216

217 218
#define LUKS_HDR_MAGIC_LEN 6
#define LUKS_HDR_VERSION_LEN 2
219 220 221 222
#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
223 224 225

/* Format described by qemu commit id '3e308f20e' */
#define LUKS_HDR_VERSION_OFFSET LUKS_HDR_MAGIC_LEN
226 227 228 229 230
#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)
231

232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
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,
247 248

        .payloadOffset = LUKS_HDR_PAYLOAD_OFFSET,
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
    },
    { 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,
267 268

        .payloadOffset = -1,
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
    },
    { 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,
287 288

        .payloadOffset = -1,
289 290 291
    },
    { 0 }
};
292

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

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

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

385

386 387 388 389 390 391 392 393 394 395 396 397 398 399
/* qcow2 compatible features in the order they appear on-disk */
enum qcow2CompatibleFeature {
    QCOW2_COMPATIBLE_FEATURE_LAZY_REFCOUNTS = 0,

    QCOW2_COMPATIBLE_FEATURE_LAST
};

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

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

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

417
    if (VIR_STRNDUP(*res, (const char*)buf + 4 + 4, COW_FILENAME_MAXLEN) < 0)
418 419 420 421
        return BACKING_STORE_ERROR;
    return BACKING_STORE_OK;
}

422 423 424

static int
qcow2GetBackingStoreFormat(int *format,
E
Eric Blake 已提交
425
                           const char *buf,
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
                           size_t buf_size,
                           size_t extension_start,
                           size_t extension_end)
{
    size_t offset = extension_start;

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

        offset += 8;

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

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

        switch (magic) {
        case QCOW2_HDR_EXTENSION_END:
            goto done;

        case QCOW2_HDR_EXTENSION_BACKING_FORMAT:
            if (buf[offset+len] != '\0')
                break;
            *format = virStorageFileFormatTypeFromString(
                ((const char *)buf)+offset);
E
Eric Blake 已提交
464 465
            if (*format <= VIR_STORAGE_FILE_NONE)
                return -1;
466 467 468 469 470
        }

        offset += len;
    }

471
 done:
472 473 474 475 476

    return 0;
}


477
static int
478
qcowXGetBackingStore(char **res,
479
                     int *format,
E
Eric Blake 已提交
480
                     const char *buf,
481 482
                     size_t buf_size,
                     bool isQCow2)
483 484
{
    unsigned long long offset;
485
    unsigned int size;
486 487
    unsigned long long start;
    int version;
488 489

    *res = NULL;
490 491 492 493
    if (format)
        *format = VIR_STORAGE_FILE_AUTO;

    if (buf_size < QCOWX_HDR_BACKING_FILE_OFFSET+8+4)
494
        return BACKING_STORE_INVALID;
E
Eric Blake 已提交
495
    offset = virReadBufInt64BE(buf + QCOWX_HDR_BACKING_FILE_OFFSET);
496 497
    if (offset > buf_size)
        return BACKING_STORE_INVALID;
498 499 500 501 502 503 504

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

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

    /*
     * 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)
543 544 545
     *
     * for qcow2 v3 images, the length of the header
     * is stored at QCOW2v3_HDR_SIZE
546
     */
547 548 549 550 551 552 553 554 555 556
    if (isQCow2 && format) {
        version = virReadBufInt32BE(buf + QCOWX_HDR_VERSION);
        if (version == 2)
            start = QCOW2_HDR_TOTAL_SIZE;
        else
            start = virReadBufInt32BE(buf + QCOW2v3_HDR_SIZE);
        if (qcow2GetBackingStoreFormat(format, buf, buf_size,
                                       start, offset) < 0)
            return BACKING_STORE_INVALID;
    }
557

558 559 560 561
    return BACKING_STORE_OK;
}


562 563 564
static int
qcow1GetBackingStore(char **res,
                     int *format,
E
Eric Blake 已提交
565
                     const char *buf,
566 567
                     size_t buf_size)
{
E
Eric Blake 已提交
568 569
    int ret;

570 571 572
    /* QCow1 doesn't have the extensions capability
     * used to store backing format */
    *format = VIR_STORAGE_FILE_AUTO;
E
Eric Blake 已提交
573 574 575 576
    ret = qcowXGetBackingStore(res, NULL, buf, buf_size, false);
    if (ret == 0 && *buf == '\0')
        *format = VIR_STORAGE_FILE_NONE;
    return ret;
577 578 579 580 581
}

static int
qcow2GetBackingStore(char **res,
                     int *format,
E
Eric Blake 已提交
582
                     const char *buf,
583 584 585 586 587 588
                     size_t buf_size)
{
    return qcowXGetBackingStore(res, format, buf, buf_size, true);
}


589
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 *desc, *start, *end;
597
    size_t len;
598 599
    int ret = BACKING_STORE_ERROR;

600
    if (VIR_ALLOC_N(desc, VIR_STORAGE_MAX_HEADER) < 0)
601
        goto cleanup;
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 616
    if (buf_size <= 0x200) {
        ret = BACKING_STORE_INVALID;
        goto cleanup;
    }
617
    len = buf_size - 0x200;
618 619
    if (len > VIR_STORAGE_MAX_HEADER)
        len = VIR_STORAGE_MAX_HEADER;
620 621 622
    memcpy(desc, buf + 0x200, len);
    desc[len] = '\0';
    start = strstr(desc, prefix);
623
    if (start == NULL) {
E
Eric Blake 已提交
624
        *format = VIR_STORAGE_FILE_NONE;
625 626 627
        ret = BACKING_STORE_OK;
        goto cleanup;
    }
628 629
    start += strlen(prefix);
    end = strchr(start, '"');
630 631 632 633 634
    if (end == NULL) {
        ret = BACKING_STORE_INVALID;
        goto cleanup;
    }
    if (end == start) {
E
Eric Blake 已提交
635
        *format = VIR_STORAGE_FILE_NONE;
636 637 638
        ret = BACKING_STORE_OK;
        goto cleanup;
    }
639
    *end = '\0';
640
    if (VIR_STRDUP(*res, start) < 0)
641 642 643 644
        goto cleanup;

    ret = BACKING_STORE_OK;

645
 cleanup:
646 647
    VIR_FREE(desc);
    return ret;
648 649
}

650 651 652
static int
qedGetBackingStore(char **res,
                   int *format,
E
Eric Blake 已提交
653
                   const char *buf,
654 655 656 657 658 659 660 661 662
                   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 已提交
663
    flags = virReadBufInt64LE(buf + QED_HDR_FEATURES_OFFSET);
E
Eric Blake 已提交
664 665
    if (!(flags & QED_F_BACKING_FILE)) {
        *format = VIR_STORAGE_FILE_NONE;
666
        return BACKING_STORE_OK;
E
Eric Blake 已提交
667
    }
668 669 670 671

    /* Parse the backing file */
    if (buf_size < QED_HDR_BACKING_FILE_OFFSET+8)
        return BACKING_STORE_INVALID;
E
Eric Blake 已提交
672
    offset = virReadBufInt32LE(buf + QED_HDR_BACKING_FILE_OFFSET);
673 674
    if (offset > buf_size)
        return BACKING_STORE_INVALID;
E
Eric Blake 已提交
675
    size = virReadBufInt32LE(buf + QED_HDR_BACKING_FILE_SIZE);
676 677 678 679
    if (size == 0)
        return BACKING_STORE_OK;
    if (offset + size > buf_size || offset + size < offset)
        return BACKING_STORE_INVALID;
680
    if (VIR_ALLOC_N(*res, size + 1) < 0)
681 682 683 684
        return BACKING_STORE_ERROR;
    memcpy(*res, buf + offset, size);
    (*res)[size] = '\0';

E
Eric Blake 已提交
685 686 687 688
    if (flags & QED_F_BACKING_FORMAT_NO_PROBE)
        *format = VIR_STORAGE_FILE_RAW;
    else
        *format = VIR_STORAGE_FILE_AUTO_SAFE;
689 690 691 692

    return BACKING_STORE_OK;
}

693 694

static bool
695 696
virStorageFileMatchesMagic(int magicOffset,
                           const char *magic,
E
Eric Blake 已提交
697
                           char *buf,
698
                           size_t buflen)
699
{
700
    int mlen;
701

702
    if (magic == NULL)
703
        return false;
704

705
    /* Validate magic data */
706 707
    mlen = strlen(magic);
    if (magicOffset + mlen > buflen)
708
        return false;
709

710
    if (memcmp(buf + magicOffset, magic, mlen) != 0)
711 712 713 714 715 716 717
        return false;

    return true;
}


static bool
718
virStorageFileMatchesExtension(const char *extension,
719 720
                               const char *path)
{
721
    if (extension == NULL)
722 723
        return false;

724
    if (virFileHasSuffix(path, extension))
725 726 727 728 729 730 731
        return true;

    return false;
}


static bool
732 733 734 735
virStorageFileMatchesVersion(int versionOffset,
                             int versionSize,
                             const int *versionNumbers,
                             int endian,
E
Eric Blake 已提交
736
                             char *buf,
737 738
                             size_t buflen)
{
739
    int version;
740
    size_t i;
741 742

    /* Validate version number info */
743
    if (versionOffset == -1)
E
Eric Blake 已提交
744
        return false;
745

746
    /* -2 == non-versioned file format, so trivially match */
747
    if (versionOffset == -2)
748 749
        return true;

750
    /* A positive versionOffset, requires using a valid versionSize */
751
    if (versionSize != 2 && versionSize != 4)
752 753
        return false;

754
    if ((versionOffset + versionSize) > buflen)
755 756
        return false;

757 758
    if (endian == LV_LITTLE_ENDIAN) {
        if (versionSize == 4)
759
            version = virReadBufInt32LE(buf +
760
                                        versionOffset);
761 762
        else
            version = virReadBufInt16LE(buf +
763
                                        versionOffset);
764
    } else {
765
        if (versionSize == 4)
766
            version = virReadBufInt32BE(buf +
767
                                        versionOffset);
768 769
        else
            version = virReadBufInt16BE(buf +
770
                                        versionOffset);
771
    }
772

773
    for (i = 0;
774
         i < FILE_TYPE_VERSIONS_LAST && versionNumbers[i];
775 776
         i++) {
        VIR_DEBUG("Compare detected version %d vs one of the expected versions %d",
777 778
                  version, versionNumbers[i]);
        if (version == versionNumbers[i])
779 780
            return true;
    }
781

782
    return false;
783
}
784

785 786
bool
virStorageIsFile(const char *backing)
A
Adam Litke 已提交
787
{
788 789 790 791 792 793 794 795
    char *colon;
    char *slash;

    if (!backing)
        return false;

    colon = strchr(backing, ':');
    slash = strchr(backing, '/');
796 797 798 799 800

    /* 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 已提交
801 802 803
        return false;
    return true;
}
804

E
Eric Blake 已提交
805

806
bool
807 808 809 810 811 812 813 814 815 816 817 818
virStorageIsRelative(const char *backing)
{
    if (backing[0] == '/')
        return false;

    if (!virStorageIsFile(backing))
        return false;

    return true;
}


819
static int
E
Eric Blake 已提交
820
virStorageFileProbeFormatFromBuf(const char *path,
E
Eric Blake 已提交
821
                                 char *buf,
E
Eric Blake 已提交
822 823 824
                                 size_t buflen)
{
    int format = VIR_STORAGE_FILE_RAW;
825
    size_t i;
E
Eric Blake 已提交
826
    int possibleFormat = VIR_STORAGE_FILE_RAW;
827
    VIR_DEBUG("path=%s, buf=%p, buflen=%zu", path, buf, buflen);
E
Eric Blake 已提交
828 829

    /* First check file magic */
830
    for (i = 0; i < VIR_STORAGE_FILE_LAST; i++) {
831 832 833 834 835 836 837 838 839 840
        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 已提交
841 842 843 844 845 846 847 848 849 850 851 852 853 854
                possibleFormat = i;
                continue;
            }
            format = i;
            goto cleanup;
        }
    }

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

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

863
 cleanup:
E
Eric Blake 已提交
864 865 866 867 868
    VIR_DEBUG("format=%d", format);
    return format;
}


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

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

    if (version == 2)
        return 0;

    if (len < QCOW2v3_HDR_SIZE)
        return -1;

888
    if (!(feat = virBitmapNew(VIR_STORAGE_FILE_FEATURE_LAST)))
889 890 891 892 893 894 895 896 897 898 899 900 901 902
        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;
}


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

    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) {
927 928
        int crypt_format;

929 930 931
        if (info->modeOffset >= len)
            return false;

932 933
        crypt_format = virReadBufInt32BE(buf + info->modeOffset);
        if (crypt_format != info->modeValue)
934 935 936 937 938 939 940 941 942
            return false;

        return true;
    } else {
        return false;
    }
}


943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959
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;
}


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

975 976 977
    if (!backingFormat)
        backingFormat = &dummy;

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

981
    if (meta->format == VIR_STORAGE_FILE_AUTO)
982
        meta->format = virStorageFileProbeFormatFromBuf(meta->path, buf, len);
983

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

991 992 993 994
    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)) {
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
                int expt_fmt = fileTypeInfo[meta->format].cryptInfo[i].format;
                if (!meta->encryption) {
                    if (VIR_ALLOC(meta->encryption) < 0)
                        goto cleanup;

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

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

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

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

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

E
Eric Blake 已提交
1048 1049
        if (store == BACKING_STORE_ERROR)
            goto cleanup;
1050 1051
    }

1052 1053
    if (fileTypeInfo[meta->format].getFeatures != NULL &&
        fileTypeInfo[meta->format].getFeatures(&meta->features, meta->format, buf, len) < 0)
1054 1055
        goto cleanup;

1056
    if (meta->format == VIR_STORAGE_FILE_QCOW2 && meta->features &&
1057 1058 1059
        VIR_STRDUP(meta->compat, "1.1") < 0)
        goto cleanup;

1060
 done:
1061
    ret = 0;
E
Eric Blake 已提交
1062

1063
 cleanup:
E
Eric Blake 已提交
1064
    return ret;
1065 1066 1067 1068
}


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

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

1095 1096 1097 1098 1099
    if (fstat(fd, &sb) < 0) {
        virReportSystemError(errno, _("cannot stat file '%s'"), path);
        goto cleanup;
    }

1100 1101
    /* No header to probe for directories */
    if (S_ISDIR(sb.st_mode)) {
1102 1103
        ret = VIR_STORAGE_FILE_DIR;
        goto cleanup;
1104
    }
1105 1106 1107 1108 1109 1110

    if (lseek(fd, 0, SEEK_SET) == (off_t)-1) {
        virReportSystemError(errno, _("cannot set to start of '%s'"), path);
        goto cleanup;
    }

1111
    if ((len = virFileReadHeaderFD(fd, len, &header)) < 0) {
1112 1113 1114 1115
        virReportSystemError(errno, _("cannot read header '%s'"), path);
        goto cleanup;
    }

1116
    ret = virStorageFileProbeFormatFromBuf(path, header, len);
1117

1118
 cleanup:
1119
    VIR_FREE(header);
1120
    VIR_FORCE_CLOSE(fd);
1121 1122 1123 1124

    return ret;
}

1125

1126
static virStorageSourcePtr
1127 1128 1129
virStorageFileMetadataNew(const char *path,
                          int format)
{
1130
    virStorageSourcePtr ret = NULL;
1131 1132 1133 1134 1135 1136 1137

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

    ret->format = format;
    ret->type = VIR_STORAGE_TYPE_FILE;

1138 1139
    if (VIR_STRDUP(ret->path, path) < 0)
        goto error;
1140 1141 1142 1143

    return ret;

 error:
1144
    virStorageSourceFree(ret);
1145 1146 1147 1148
    return NULL;
}


1149 1150 1151 1152 1153
/**
 * virStorageFileGetMetadataFromBuf:
 * @path: name of file, for error messages
 * @buf: header bytes from @path
 * @len: length of @buf
1154
 * @format: format of the storage file
1155
 * @backingFormat: format of @backing
1156
 *
1157 1158 1159
 * 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.
1160
 *
1161 1162 1163 1164 1165 1166 1167
 * Callers are advised never to use VIR_STORAGE_FILE_AUTO as a format on a file
 * that might be raw if that file will then be passed to a guest, since a
 * malicious guest can turn a raw file into any other non-raw format at will.
 *
 * If the returned @backingFormat is VIR_STORAGE_FILE_AUTO it indicates the
 * image didn't specify an explicit format for its backing store. Callers are
 * advised against probing for the backing store format in this case.
1168
 *
1169
 * Caller MUST free the result after use via virStorageSourceFree.
1170
 */
1171
virStorageSourcePtr
1172 1173 1174
virStorageFileGetMetadataFromBuf(const char *path,
                                 char *buf,
                                 size_t len,
1175
                                 int format,
1176
                                 int *backingFormat)
1177
{
1178
    virStorageSourcePtr ret = NULL;
1179 1180 1181 1182
    int dummy;

    if (!backingFormat)
        backingFormat = &dummy;
1183

1184
    if (!(ret = virStorageFileMetadataNew(path, format)))
1185
        return NULL;
1186

1187 1188 1189 1190 1191
    if (virStorageFileGetMetadataInternal(ret, buf, len,
                                          backingFormat) < 0) {
        virStorageSourceFree(ret);
        return NULL;
    }
1192

1193
    return ret;
1194 1195 1196
}


1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
/**
 * 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.
 *
 * Caller MUST free the result after use via virStorageSourceFree.
 */
virStorageSourcePtr
virStorageFileGetMetadataFromFD(const char *path,
                                int fd,
                                int format,
                                int *backingFormat)

1216
{
1217 1218
    virStorageSourcePtr ret = NULL;
    virStorageSourcePtr meta = NULL;
1219
    char *buf = NULL;
1220
    ssize_t len = VIR_STORAGE_MAX_HEADER;
1221
    struct stat sb;
1222
    int dummy;
1223

1224 1225
    if (!backingFormat)
        backingFormat = &dummy;
1226

1227
    *backingFormat = VIR_STORAGE_FILE_NONE;
1228

1229 1230
    if (fstat(fd, &sb) < 0) {
        virReportSystemError(errno,
1231 1232
                             _("cannot stat file '%s'"), path);
        return NULL;
1233 1234
    }

1235 1236 1237
    if (!(meta = virStorageFileMetadataNew(path, format)))
        return NULL;

1238
    if (S_ISDIR(sb.st_mode)) {
1239 1240
        /* No header to probe for directories, but also no backing file. Just
         * update the metadata.*/
1241 1242
        meta->type = VIR_STORAGE_TYPE_DIR;
        meta->format = VIR_STORAGE_FILE_DIR;
1243 1244
        ret = meta;
        meta = NULL;
1245 1246 1247 1248
        goto cleanup;
    }

    if (lseek(fd, 0, SEEK_SET) == (off_t)-1) {
1249
        virReportSystemError(errno, _("cannot seek to start of '%s'"), meta->path);
1250 1251 1252 1253
        goto cleanup;
    }

    if ((len = virFileReadHeaderFD(fd, len, &buf)) < 0) {
1254
        virReportSystemError(errno, _("cannot read header '%s'"), meta->path);
1255 1256 1257
        goto cleanup;
    }

1258 1259
    if (virStorageFileGetMetadataInternal(meta, buf, len, backingFormat) < 0)
        goto cleanup;
1260

1261 1262 1263 1264
    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;
1265

1266 1267
    ret = meta;
    meta = NULL;
1268

1269 1270 1271
 cleanup:
    virStorageSourceFree(meta);
    VIR_FREE(buf);
1272
    return ret;
1273 1274
}

1275

1276 1277 1278 1279 1280
/**
 * virStorageFileChainCheckBroken
 *
 * If CHAIN is broken, set *brokenFile to the broken file name,
 * otherwise set it to NULL. Caller MUST free *brokenFile after use.
1281 1282
 * Return 0 on success (including when brokenFile is set), negative on
 * error (allocation failure).
1283 1284
 */
int
1285
virStorageFileChainGetBroken(virStorageSourcePtr chain,
1286 1287
                             char **brokenFile)
{
1288
    virStorageSourcePtr tmp;
1289

1290 1291
    *brokenFile = NULL;

1292 1293 1294
    if (!chain)
        return 0;

1295
    for (tmp = chain; virStorageSourceIsBacking(tmp); tmp = tmp->backingStore) {
1296 1297
        /* Break when we hit end of chain; report error if we detected
         * a missing backing file, infinite loop, or other error */
1298
        if (!tmp->backingStore && tmp->backingStoreRaw) {
1299 1300
            if (VIR_STRDUP(*brokenFile, tmp->backingStoreRaw) < 0)
                return -1;
1301

1302 1303 1304
           return 0;
        }
    }
1305

1306
    return 0;
1307 1308 1309
}


1310 1311 1312 1313 1314 1315
/**
 * virStorageFileResize:
 *
 * Change the capacity of the raw storage file at 'path'.
 */
int
1316 1317 1318
virStorageFileResize(const char *path,
                     unsigned long long capacity,
                     bool pre_allocate)
1319
{
1320 1321
    int fd = -1;
    int ret = -1;
1322
    int rc;
1323 1324 1325 1326 1327 1328

    if ((fd = open(path, O_RDWR)) < 0) {
        virReportSystemError(errno, _("Unable to open '%s'"), path);
        goto cleanup;
    }

1329
    if (pre_allocate) {
1330
        if ((rc = virFileAllocate(fd, 0, capacity)) != 0) {
1331 1332 1333 1334 1335 1336 1337 1338
            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);
            }
1339 1340
            goto cleanup;
        }
1341 1342 1343 1344 1345 1346
    }

    if (ftruncate(fd, capacity) < 0) {
        virReportSystemError(errno,
                             _("Failed to truncate file '%s'"), path);
        goto cleanup;
1347 1348
    }

1349 1350 1351 1352 1353 1354 1355
    if (VIR_CLOSE(fd) < 0) {
        virReportSystemError(errno, _("Unable to save '%s'"), path);
        goto cleanup;
    }

    ret = 0;

1356
 cleanup:
1357 1358
    VIR_FORCE_CLOSE(fd);
    return ret;
1359 1360
}

1361 1362 1363 1364 1365 1366

int virStorageFileIsClusterFS(const char *path)
{
    /* These are coherent cluster filesystems known to be safe for
     * migration with cache != none
     */
1367 1368 1369
    return virFileIsSharedFSType(path,
                                 VIR_FILE_SHFS_GFS2 |
                                 VIR_FILE_SHFS_OCFS);
1370
}
1371 1372

#ifdef LVS
1373 1374
int virStorageFileGetLVMKey(const char *path,
                            char **key)
1375 1376 1377 1378 1379
{
    /*
     *  # lvs --noheadings --unbuffered --nosuffix --options "uuid" LVNAME
     *    06UgP5-2rhb-w3Bo-3mdR-WeoL-pytO-SAa2ky
     */
1380
    int status;
1381 1382 1383 1384 1385 1386
    virCommandPtr cmd = virCommandNewArgList(
        LVS,
        "--noheadings", "--unbuffered", "--nosuffix",
        "--options", "uuid", path,
        NULL
        );
1387 1388 1389
    int ret = -1;

    *key = NULL;
1390 1391

    /* Run the program and capture its output */
1392 1393
    virCommandSetOutputBuffer(cmd, key);
    if (virCommandRun(cmd, &status) < 0)
1394 1395
        goto cleanup;

1396 1397 1398 1399 1400 1401
    /* 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) {
1402
        char *nl;
1403
        char *tmp = *key;
1404 1405

        /* Find first non-space character */
1406
        while (*tmp && c_isspace(*tmp))
1407 1408
            tmp++;
        /* Kill leading spaces */
1409 1410
        if (tmp != *key)
            memmove(*key, tmp, strlen(tmp)+1);
1411 1412

        /* Kill trailing newline */
1413
        if ((nl = strchr(*key, '\n')))
1414 1415 1416
            *nl = '\0';
    }

1417
    ret = 0;
1418

1419
 cleanup:
1420 1421 1422
    if (*key && STREQ(*key, ""))
        VIR_FREE(*key);

1423 1424
    virCommandFree(cmd);

1425
    return ret;
1426 1427
}
#else
1428 1429
int virStorageFileGetLVMKey(const char *path,
                            char **key ATTRIBUTE_UNUSED)
1430 1431
{
    virReportSystemError(ENOSYS, _("Unable to get LVM key for %s"), path);
1432
    return -1;
1433 1434 1435
}
#endif

1436
#ifdef WITH_UDEV
1437 1438
int virStorageFileGetSCSIKey(const char *path,
                             char **key)
1439
{
1440
    int status;
1441 1442 1443 1444 1445 1446 1447
    virCommandPtr cmd = virCommandNewArgList(
        "/lib/udev/scsi_id",
        "--replace-whitespace",
        "--whitelisted",
        "--device", path,
        NULL
        );
1448 1449 1450
    int ret = -1;

    *key = NULL;
1451 1452

    /* Run the program and capture its output */
1453 1454
    virCommandSetOutputBuffer(cmd, key);
    if (virCommandRun(cmd, &status) < 0)
1455 1456
        goto cleanup;

1457 1458 1459 1460 1461 1462
    /* 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');
1463 1464 1465 1466
        if (nl)
            *nl = '\0';
    }

1467 1468
    ret = 0;

1469
 cleanup:
1470 1471 1472
    if (*key && STREQ(*key, ""))
        VIR_FREE(*key);

1473 1474
    virCommandFree(cmd);

1475
    return ret;
1476 1477
}
#else
1478 1479
int virStorageFileGetSCSIKey(const char *path,
                             char **key ATTRIBUTE_UNUSED)
1480 1481
{
    virReportSystemError(ENOSYS, _("Unable to get SCSI key for %s"), path);
1482
    return -1;
1483 1484
}
#endif
1485

1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533

/**
 * 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)
{
    char **strings = NULL;
    size_t nstrings;
    unsigned int idx = 0;
    char *suffix;
    int ret = -1;

    *chainIndex = 0;

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

    if (nstrings == 2) {
        if (virStrToLong_uip(strings[1], &suffix, 10, &idx) < 0 ||
            STRNEQ(suffix, "]"))
            goto cleanup;
    }

    if (target &&
        VIR_STRDUP(*target, strings[0]) < 0)
        goto cleanup;

    *chainIndex = idx;
    ret = 0;

 cleanup:
    virStringListFreeCount(strings, nstrings);
    return ret;
}


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

    *chainIndex = 0;

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

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

1551
    if (idx == 0)
1552 1553
        goto cleanup;

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

    *chainIndex = idx;

 cleanup:
1565
    VIR_FREE(target);
1566 1567 1568
    return ret;
}

1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579

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

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


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

    if (!parent)
1621
        parent = &prev;
1622
    *parent = NULL;
1623 1624

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

1629
        *parent = startFrom;
1630 1631
    }

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

            if (nameIsFile && virStorageSourceIsLocalStorage(chain)) {
1646 1647
                if (*parent && virStorageSourceIsLocalStorage(*parent))
                    parentDir = mdir_name((*parent)->path);
1648 1649 1650 1651 1652 1653
                else
                    ignore_value(VIR_STRDUP_QUIET(parentDir, "."));

                if (!parentDir) {
                    virReportOOMError();
                    goto error;
1654 1655
                }

E
Eric Blake 已提交
1656
                int result = virFileRelLinkPointsTo(parentDir, name,
1657
                                                    chain->path);
1658 1659

                VIR_FREE(parentDir);
1660

E
Eric Blake 已提交
1661 1662
                if (result < 0)
                    goto error;
1663

E
Eric Blake 已提交
1664 1665 1666
                if (result > 0)
                    break;
            }
1667
        }
1668
        *parent = chain;
1669
        chain = chain->backingStore;
1670
    }
1671

1672
    if (!virStorageSourceIsBacking(chain))
1673
        goto error;
1674

1675
    return chain;
1676

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


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


1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740
static void
virStoragePermsFree(virStoragePermsPtr def)
{
    if (!def)
        return;

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


1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755
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;
1756
        dst->port = src->port;
1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770

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

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

    return ret;

 error:
    virStorageNetHostDefFree(nhosts, ret);
    return NULL;
}
1771 1772


1773 1774 1775 1776 1777 1778 1779 1780
void
virStorageAuthDefFree(virStorageAuthDefPtr authdef)
{
    if (!authdef)
        return;

    VIR_FREE(authdef->username);
    VIR_FREE(authdef->secrettype);
1781
    virSecretLookupDefClear(&authdef->seclookupdef);
1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799
    VIR_FREE(authdef);
}


virStorageAuthDefPtr
virStorageAuthDefCopy(const virStorageAuthDef *src)
{
    virStorageAuthDefPtr ret;

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

    if (VIR_STRDUP(ret->username, src->username) < 0)
        goto error;
    /* Not present for storage pool, but used for disk source */
    if (VIR_STRDUP(ret->secrettype, src->secrettype) < 0)
        goto error;
    ret->authType = src->authType;
1800 1801 1802 1803

    if (virSecretLookupDefCopy(&ret->seclookupdef, &src->seclookupdef) < 0)
        goto error;

1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815
    return ret;

 error:
    virStorageAuthDefFree(ret);
    return NULL;
}


static virStorageAuthDefPtr
virStorageAuthDefParseXML(xmlXPathContextPtr ctxt)
{
    virStorageAuthDefPtr authdef = NULL;
1816
    xmlNodePtr secretnode = NULL;
1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844
    char *username = NULL;
    char *authtype = NULL;

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

    if (!(username = virXPathString("string(./@username)", ctxt))) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing username for auth"));
        goto error;
    }
    authdef->username = username;
    username = NULL;

    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);
            goto error;
        }
        VIR_FREE(authtype);
    }

1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860
    if (!(secretnode = virXPathNode("./secret ", ctxt))) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("Missing <secret> element in auth"));
        goto error;
    }

    /* 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)
1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906
        goto error;

    return authdef;

 error:
    VIR_FREE(authtype);
    VIR_FREE(username);
    virStorageAuthDefFree(authdef);
    return NULL;
}


virStorageAuthDefPtr
virStorageAuthDefParse(xmlDocPtr xml, xmlNodePtr root)
{
    xmlXPathContextPtr ctxt = NULL;
    virStorageAuthDefPtr authdef = NULL;

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
        virReportOOMError();
        goto cleanup;
    }

    ctxt->node = root;
    authdef = virStorageAuthDefParseXML(ctxt);

 cleanup:
    xmlXPathFreeContext(ctxt);
    return authdef;
}


int
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);
1907 1908
    virSecretLookupFormatSecret(buf, authdef->secrettype,
                                &authdef->seclookupdef);
1909 1910 1911 1912 1913 1914 1915
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</auth>\n");

    return 0;
}


1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930
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;
}


1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995
static void
virStorageSourceSeclabelsClear(virStorageSourcePtr def)
{
    size_t i;

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


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

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

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

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

    return 0;

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


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

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

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

    return ret;
}


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

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

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

1996
    if (VIR_STRDUP(ret->label, src->label) < 0)
1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049
        goto error;

    return ret;

 error:
    virStoragePermsFree(ret);
    return NULL;
}


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

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

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

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

    return ret;

 error:
    virStorageSourcePoolDefFree(ret);
    return NULL;
}


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

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

2050
    ret->id = src->id;
2051 2052 2053 2054
    ret->type = src->type;
    ret->protocol = src->protocol;
    ret->format = src->format;
    ret->capacity = src->capacity;
2055
    ret->allocation = src->allocation;
2056
    ret->has_allocation = src->has_allocation;
2057
    ret->physical = src->physical;
2058 2059
    ret->readonly = src->readonly;
    ret->shared = src->shared;
2060 2061
    ret->haveTLS = src->haveTLS;
    ret->tlsFromConfig = src->tlsFromConfig;
2062
    ret->tlsVerify = src->tlsVerify;
2063
    ret->detected = src->detected;
2064 2065
    ret->debugLevel = src->debugLevel;
    ret->debug = src->debug;
2066 2067 2068 2069 2070 2071 2072 2073 2074

    /* storage driver metadata are not copied */
    ret->drv = NULL;

    if (VIR_STRDUP(ret->path, src->path) < 0 ||
        VIR_STRDUP(ret->volume, src->volume) < 0 ||
        VIR_STRDUP(ret->driverName, src->driverName) < 0 ||
        VIR_STRDUP(ret->relPath, src->relPath) < 0 ||
        VIR_STRDUP(ret->backingStoreRaw, src->backingStoreRaw) < 0 ||
2075
        VIR_STRDUP(ret->snapshot, src->snapshot) < 0 ||
2076
        VIR_STRDUP(ret->configFile, src->configFile) < 0 ||
2077
        VIR_STRDUP(ret->nodeformat, src->nodeformat) < 0 ||
2078
        VIR_STRDUP(ret->nodestorage, src->nodestorage) < 0 ||
2079 2080 2081
        VIR_STRDUP(ret->compat, src->compat) < 0 ||
        VIR_STRDUP(ret->tlsAlias, src->tlsAlias) < 0 ||
        VIR_STRDUP(ret->tlsCertdir, src->tlsCertdir) < 0)
2082 2083
        goto error;

2084 2085 2086 2087 2088 2089
    if (src->nhosts) {
        if (!(ret->hosts = virStorageNetHostDefCopy(src->nhosts, src->hosts)))
            goto error;

        ret->nhosts = src->nhosts;
    }
2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131

    if (src->srcpool &&
        !(ret->srcpool = virStorageSourcePoolDefCopy(src->srcpool)))
        goto error;

    if (src->features &&
        !(ret->features = virBitmapNewCopy(src->features)))
        goto error;

    if (src->encryption &&
        !(ret->encryption = virStorageEncryptionCopy(src->encryption)))
        goto error;

    if (src->perms &&
        !(ret->perms = virStoragePermsCopy(src->perms)))
        goto error;

    if (src->timestamps &&
        !(ret->timestamps = virStorageTimestampsCopy(src->timestamps)))
        goto error;

    if (virStorageSourceSeclabelsCopy(ret, src) < 0)
        goto error;

    if (src->auth &&
        !(ret->auth = virStorageAuthDefCopy(src->auth)))
        goto error;

    if (backingChain && src->backingStore) {
        if (!(ret->backingStore = virStorageSourceCopy(src->backingStore,
                                                       true)))
            goto error;
    }

    return ret;

 error:
    virStorageSourceFree(ret);
    return NULL;
}


2132 2133 2134 2135
/**
 * virStorageSourceInitChainElement:
 * @newelem: New backing chain element disk source
 * @old: Existing top level disk source
N
Nitesh Konkar 已提交
2136
 * @transferLabels: Transfer security labels.
2137 2138 2139 2140 2141
 *
 * 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.
 *
2142 2143
 * 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.
2144 2145 2146 2147 2148 2149
 *
 * Returns 0 on success, -1 on error.
 */
int
virStorageSourceInitChainElement(virStorageSourcePtr newelem,
                                 virStorageSourcePtr old,
2150
                                 bool transferLabels)
2151 2152 2153
{
    int ret = -1;

2154 2155
    if (transferLabels &&
        !newelem->seclabels &&
2156 2157 2158
        virStorageSourceSeclabelsCopy(newelem, old) < 0)
        goto cleanup;

2159 2160 2161 2162
    if (!newelem->driverName &&
        VIR_STRDUP(newelem->driverName, old->driverName) < 0)
        goto cleanup;

2163 2164 2165 2166 2167 2168 2169 2170 2171 2172
    newelem->shared = old->shared;
    newelem->readonly = old->readonly;

    ret = 0;

 cleanup:
    return ret;
}


2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185
void
virStorageSourcePoolDefFree(virStorageSourcePoolDefPtr def)
{
    if (!def)
        return;

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

    VIR_FREE(def);
}


2186
int
2187
virStorageSourceGetActualType(const virStorageSource *def)
2188 2189 2190 2191 2192 2193 2194 2195
{
    if (def->type == VIR_STORAGE_TYPE_VOLUME && def->srcpool)
        return def->srcpool->actualtype;

    return def->type;
}


2196
bool
2197
virStorageSourceIsLocalStorage(const virStorageSource *src)
2198
{
2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214
    virStorageType type = virStorageSourceGetActualType(src);

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

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

    return false;
2215 2216 2217
}


2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234
/**
 * 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;

2235 2236 2237 2238
    if (src->type == VIR_STORAGE_TYPE_NETWORK &&
        src->protocol == VIR_STORAGE_NET_PROTOCOL_NONE)
        return true;

2239 2240 2241 2242
    return false;
}


2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256
/**
 * 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;
}


2257
/**
2258
 * virStorageSourceBackingStoreClear:
2259 2260 2261 2262 2263 2264
 *
 * @src: disk source to clear
 *
 * Clears information about backing store of the current storage file.
 */
void
2265
virStorageSourceBackingStoreClear(virStorageSourcePtr def)
2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278
{
    if (!def)
        return;

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

    /* recursively free backing chain */
    virStorageSourceFree(def->backingStore);
    def->backingStore = NULL;
}


2279 2280 2281 2282 2283 2284 2285
void
virStorageSourceClear(virStorageSourcePtr def)
{
    if (!def)
        return;

    VIR_FREE(def->path);
2286
    VIR_FREE(def->volume);
2287 2288
    VIR_FREE(def->snapshot);
    VIR_FREE(def->configFile);
2289 2290
    virStorageSourcePoolDefFree(def->srcpool);
    VIR_FREE(def->driverName);
E
Eric Blake 已提交
2291 2292
    virBitmapFree(def->features);
    VIR_FREE(def->compat);
2293
    virStorageEncryptionFree(def->encryption);
2294
    virStorageSourceSeclabelsClear(def);
2295
    virStoragePermsFree(def->perms);
E
Eric Blake 已提交
2296
    VIR_FREE(def->timestamps);
2297 2298

    virStorageNetHostDefFree(def->nhosts, def->hosts);
2299
    virStorageAuthDefFree(def->auth);
2300
    virObjectUnref(def->privateData);
2301

2302
    VIR_FREE(def->nodestorage);
2303 2304
    VIR_FREE(def->nodeformat);

2305
    virStorageSourceBackingStoreClear(def);
2306

2307 2308 2309
    VIR_FREE(def->tlsAlias);
    VIR_FREE(def->tlsCertdir);

2310
    memset(def, 0, sizeof(*def));
2311
}
2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322


void
virStorageSourceFree(virStorageSourcePtr def)
{
    if (!def)
        return;

    virStorageSourceClear(def);
    VIR_FREE(def);
}
2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334


static virStorageSourcePtr
virStorageSourceNewFromBackingRelative(virStorageSourcePtr parent,
                                       const char *rel)
{
    char *dirname = NULL;
    virStorageSourcePtr ret;

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

2335 2336 2337 2338
    /* store relative name */
    if (VIR_STRDUP(ret->relPath, parent->backingStoreRaw) < 0)
        goto error;

2339 2340
    if (!(dirname = mdir_name(parent->path))) {
        virReportOOMError();
2341
        goto error;
2342
    }
2343

2344 2345
    if (STRNEQ(dirname, "/")) {
        if (virAsprintf(&ret->path, "%s/%s", dirname, rel) < 0)
2346 2347
            goto error;
    } else {
2348 2349 2350 2351 2352
        if (virAsprintf(&ret->path, "/%s", rel) < 0)
            goto error;
    }

    if (virStorageSourceGetActualType(parent) == VIR_STORAGE_TYPE_NETWORK) {
2353 2354 2355 2356
        ret->type = VIR_STORAGE_TYPE_NETWORK;

        /* copy the host network part */
        ret->protocol = parent->protocol;
2357 2358 2359 2360 2361 2362 2363
        if (parent->nhosts) {
            if (!(ret->hosts = virStorageNetHostDefCopy(parent->nhosts,
                                                        parent->hosts)))
                goto error;

            ret->nhosts = parent->nhosts;
        }
2364 2365 2366

        if (VIR_STRDUP(ret->volume, parent->volume) < 0)
            goto error;
2367 2368 2369
    } else {
        /* set the type to _FILE, the caller shall update it to the actual type */
        ret->type = VIR_STORAGE_TYPE_FILE;
2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397
    }

 cleanup:
    VIR_FREE(dirname);
    return ret;

 error:
    virStorageSourceFree(ret);
    ret = NULL;
    goto cleanup;
}


static int
virStorageSourceParseBackingURI(virStorageSourcePtr src,
                                const char *path)
{
    virURIPtr uri = NULL;
    char **scheme = NULL;
    int ret = -1;

    if (!(uri = virURIParse(path))) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to parse backing file location '%s'"),
                       path);
        goto cleanup;
    }

2398 2399 2400 2401 2402
    if (VIR_ALLOC(src->hosts) < 0)
        goto cleanup;

    src->nhosts = 1;

2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430
    if (!(scheme = virStringSplit(uri->scheme, "+", 2)))
        goto cleanup;

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

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

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

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

    /* possibly skip the leading slash */
2431 2432
    if (uri->path &&
        VIR_STRDUP(src->path,
2433 2434 2435 2436 2437
                   *uri->path == '/' ? uri->path + 1 : uri->path) < 0)
        goto cleanup;

    if (src->protocol == VIR_STORAGE_NET_PROTOCOL_GLUSTER) {
        char *tmp;
2438 2439 2440 2441 2442 2443 2444

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

2445 2446
        if (!(tmp = strchr(src->path, '/')) ||
            tmp == src->path) {
2447
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
2448 2449 2450 2451 2452 2453 2454
                           _("missing volume name or file name in "
                             "gluster source path '%s'"), src->path);
            goto cleanup;
        }

        src->volume = src->path;

2455
        if (VIR_STRDUP(src->path, tmp + 1) < 0)
2456 2457 2458 2459 2460
            goto cleanup;

        tmp[0] = '\0';
    }

2461
    src->hosts->port = uri->port;
2462 2463 2464 2465 2466 2467 2468 2469

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

    ret = 0;

 cleanup:
    virURIFree(uri);
2470
    virStringListFree(scheme);
2471 2472 2473 2474
    return ret;
}


2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497
static int
virStorageSourceRBDAddHost(virStorageSourcePtr src,
                           char *hostport)
{
    char *port;
    size_t skip;
    char **parts;

    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;
2498
        if (virStringParsePort(port, &src->hosts[src->nhosts - 1].port) < 0)
2499 2500 2501 2502 2503 2504
            goto error;
    }

    parts = virStringSplit(hostport, "\\:", 0);
    if (!parts)
        goto error;
2505 2506
    src->hosts[src->nhosts-1].name = virStringListJoin((const char **)parts, ":");
    virStringListFree(parts);
2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542
    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 *options = NULL;
    char *p, *e, *next;
    virStorageAuthDefPtr authdef = NULL;

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

    if (VIR_STRDUP(src->path, rbdstr) < 0)
        goto error;

    p = strchr(src->path, ':');
    if (p) {
        if (VIR_STRDUP(options, p + 1) < 0)
            goto error;
        *p = '\0';
    }

2543 2544 2545 2546 2547 2548 2549
    /* snapshot name */
    if ((p = strchr(src->path, '@'))) {
        if (VIR_STRDUP(src->snapshot, p + 1) < 0)
            goto error;
        *p = '\0';
    }

2550 2551 2552 2553 2554 2555 2556 2557
    /* pool vs. image name */
    if ((p = strchr(src->path, '/'))) {
        VIR_STEAL_PTR(src->volume, src->path);
        if (VIR_STRDUP(src->path, p + 1) < 0)
            goto error;
        *p = '\0';
    }

2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587
    /* 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 */
            if (VIR_ALLOC(authdef) < 0)
                goto error;

            if (VIR_STRDUP(authdef->username, p + strlen("id=")) < 0)
                goto error;

            if (VIR_STRDUP(authdef->secrettype,
2588
                           virSecretUsageTypeToString(VIR_SECRET_USAGE_TYPE_CEPH)) < 0)
2589 2590
                goto error;
            src->auth = authdef;
2591
            src->authInherited = true;
2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619
            authdef = NULL;

            /* 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)
                    goto error;

                h = sep;
            }
        }

2620 2621 2622 2623
        if (STRPREFIX(p, "conf=") &&
            VIR_STRDUP(src->configFile, p + strlen("conf=")) < 0)
            goto error;

2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635
        p = next;
    }
    VIR_FREE(options);
    return 0;

 error:
    VIR_FREE(options);
    virStorageAuthDefFree(authdef);
    return -1;
}


2636
static int
2637 2638
virStorageSourceParseNBDColonString(const char *nbdstr,
                                    virStorageSourcePtr src)
2639 2640 2641 2642
{
    char **backing = NULL;
    int ret = -1;

2643 2644 2645 2646 2647 2648
    if (!(backing = virStringSplit(nbdstr, ":", 0)))
        goto cleanup;

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

    if (VIR_ALLOC_N(src->hosts, 1) < 0)
2649 2650
        goto cleanup;

2651 2652 2653 2654 2655 2656 2657 2658
    src->nhosts = 1;
    src->hosts->transport = VIR_STORAGE_NET_HOST_TRANS_TCP;

    /* format: [] denotes optional sections, uppercase are variable strings
     * nbd:unix:/PATH/TO/SOCKET[:exportname=EXPORTNAME]
     * nbd:HOSTNAME:PORT[:exportname=EXPORTNAME]
     */
    if (!backing[1]) {
2659
        virReportError(VIR_ERR_INTERNAL_ERROR,
2660 2661
                       _("missing remote information in '%s' for protocol nbd"),
                       nbdstr);
2662
        goto cleanup;
2663 2664 2665 2666 2667 2668 2669
    } else if (STREQ(backing[1], "unix")) {
        if (!backing[2]) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("missing unix socket path in nbd backing string %s"),
                           nbdstr);
            goto cleanup;
        }
2670

2671
        if (VIR_STRDUP(src->hosts->socket, backing[2]) < 0)
2672 2673
            goto cleanup;

2674 2675 2676
   } else {
        if (VIR_STRDUP(src->hosts->name, backing[1]) < 0)
            goto cleanup;
2677

2678 2679 2680 2681 2682 2683
        if (!backing[2]) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("missing port in nbd string '%s'"),
                           nbdstr);
            goto cleanup;
        }
2684

2685
        if (virStringParsePort(backing[2], &src->hosts->port) < 0)
2686 2687
            goto cleanup;
    }
2688

2689 2690 2691 2692
    if (backing[3] && STRPREFIX(backing[3], "exportname=")) {
        if (VIR_STRDUP(src->path, backing[3] + strlen("exportname=")) < 0)
            goto cleanup;
    }
2693

2694
    ret = 0;
2695

2696
 cleanup:
2697
    virStringListFree(backing);
2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732

    return ret;
}


static int
virStorageSourceParseBackingColon(virStorageSourcePtr src,
                                  const char *path)
{
    char *protocol = NULL;
    const char *p;
    int ret = -1;

    if (!(p = strchr(path, ':'))) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("invalid backing protocol string '%s'"),
                       path);
        goto cleanup;
    }

    if (VIR_STRNDUP(protocol, path, p - path) < 0)
        goto cleanup;

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

    switch ((virStorageNetProtocol) src->protocol) {
    case VIR_STORAGE_NET_PROTOCOL_NBD:
        if (virStorageSourceParseNBDColonString(path, src) < 0)
            goto cleanup;
        break;
2733 2734

    case VIR_STORAGE_NET_PROTOCOL_RBD:
2735 2736 2737 2738 2739
        if (virStorageSourceParseRBDColonString(path, src) < 0)
            goto cleanup;
        break;

    case VIR_STORAGE_NET_PROTOCOL_SHEEPDOG:
2740 2741 2742 2743
    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"),
2744
                       protocol);
2745 2746 2747 2748 2749 2750 2751 2752 2753
        goto cleanup;

    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:
2754
    case VIR_STORAGE_NET_PROTOCOL_SSH:
2755
    case VIR_STORAGE_NET_PROTOCOL_VXHS:
2756 2757
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("malformed backing store path for protocol %s"),
2758
                       protocol);
2759 2760 2761 2762 2763 2764
        goto cleanup;
    }

    ret = 0;

 cleanup:
2765
    VIR_FREE(protocol);
2766 2767 2768 2769
    return ret;
}


2770 2771 2772 2773 2774
static int
virStorageSourceParseBackingJSONInternal(virStorageSourcePtr src,
                                         virJSONValuePtr json);


2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796
static int
virStorageSourceParseBackingJSONPath(virStorageSourcePtr src,
                                     virJSONValuePtr json,
                                     int type)
{
    const char *path;

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

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

    src->type = type;
    return 0;
}


2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824
static int
virStorageSourceParseBackingJSONUriStr(virStorageSourcePtr src,
                                       const char *uri,
                                       int protocol)
{
    if (virStorageSourceParseBackingURI(src, uri) < 0)
        return -1;

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

    return 0;
}


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

2825
    if (!(uri = virJSONValueObjectGetString(json, "url"))) {
2826
        virReportError(VIR_ERR_INVALID_ARG, "%s",
2827
                       _("missing 'url' in JSON backing volume definition"));
2828 2829 2830 2831 2832 2833 2834
        return -1;
    }

    return virStorageSourceParseBackingJSONUriStr(src, uri, protocol);
}


2835 2836 2837 2838
static int
virStorageSourceParseBackingJSONInetSocketAddress(virStorageNetHostDefPtr host,
                                                  virJSONValuePtr json)
{
2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850
    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");
2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861

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

    host->transport = VIR_STORAGE_NET_HOST_TRANS_TCP;

    if (VIR_STRDUP(host->name, hostname) < 0 ||
2862
        virStringParsePort(port, &host->port) < 0)
2863 2864 2865 2866 2867 2868
        return -1;

    return 0;
}


2869
static int
2870 2871
virStorageSourceParseBackingJSONSocketAddress(virStorageNetHostDefPtr host,
                                              virJSONValuePtr json)
2872
{
2873 2874 2875 2876 2877 2878 2879 2880 2881
    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;
    }
2882

2883
    if (!(type = virJSONValueObjectGetString(json, "type"))) {
2884 2885 2886
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("missing socket address type in "
                         "JSON backing volume definition"));
2887 2888 2889
        return -1;
    }

2890
    if (STREQ(type, "tcp") || STREQ(type, "inet")) {
2891
        return virStorageSourceParseBackingJSONInetSocketAddress(host, json);
2892

2893 2894
    } else if (STREQ(type, "unix")) {
        host->transport = VIR_STORAGE_NET_HOST_TRANS_UNIX;
2895

2896
        if (!(socket = virJSONValueObjectGetString(json, "socket"))) {
2897 2898
            virReportError(VIR_ERR_INVALID_ARG, "%s",
                           _("missing socket path for udp backing server in "
2899
                             "JSON backing volume definition"));
2900 2901 2902 2903 2904
            return -1;
        }

        if (VIR_STRDUP(host->socket, socket) < 0)
            return -1;
2905
    } else {
2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("backing store protocol '%s' is not yet supported"),
                       type);
        return -1;
    }

    return 0;
}


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

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

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

2940 2941 2942
    src->type = VIR_STORAGE_TYPE_NETWORK;
    src->protocol = VIR_STORAGE_NET_PROTOCOL_GLUSTER;

2943
    if (VIR_STRDUP(src->volume, volume) < 0 ||
2944
        VIR_STRDUP(src->path, path) < 0)
2945 2946 2947 2948 2949 2950 2951 2952
        return -1;

    nservers = virJSONValueArraySize(server);

    if (nservers < 1) {
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("at least 1 server is necessary in "
                         "JSON backing definition for gluster volume"));
2953 2954

        return -1;
2955 2956 2957 2958 2959 2960 2961
    }

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

    for (i = 0; i < nservers; i++) {
2962 2963
        if (virStorageSourceParseBackingJSONSocketAddress(src->hosts + i,
                                                          virJSONValueArrayGet(server, i)) < 0)
2964 2965 2966 2967 2968 2969 2970
            return -1;
    }

    return 0;
}


2971 2972 2973 2974 2975
static int
virStorageSourceParseBackingJSONiSCSI(virStorageSourcePtr src,
                                      virJSONValuePtr json,
                                      int opaque ATTRIBUTE_UNUSED)
{
2976 2977 2978
    const char *transport = virJSONValueObjectGetString(json, "transport");
    const char *portal = virJSONValueObjectGetString(json, "portal");
    const char *target = virJSONValueObjectGetString(json, "target");
2979
    const char *uri;
2980 2981 2982 2983
    char *port;
    unsigned int lun = 0;
    char *fulltarget = NULL;
    int ret = -1;
2984 2985 2986 2987 2988 2989

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

2990 2991
    src->type = VIR_STORAGE_TYPE_NETWORK;
    src->protocol = VIR_STORAGE_NET_PROTOCOL_ISCSI;
2992

2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020
    if (VIR_ALLOC(src->hosts) < 0)
        goto cleanup;

    src->nhosts = 1;

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

    src->hosts->transport = VIR_STORAGE_NET_HOST_TRANS_TCP;

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

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

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

3021 3022
    if ((port = strrchr(src->hosts->name, ':')) &&
        !strchr(port, ']')) {
3023
        if (virStringParsePort(port + 1, &src->hosts->port) < 0)
3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040
            goto cleanup;

        *port = '\0';
    }

    ignore_value(virJSONValueObjectGetNumberUint(json, "lun", &lun));

    if (virAsprintf(&fulltarget, "%s/%u", target, lun) < 0)
        goto cleanup;

    VIR_STEAL_PTR(src->path, fulltarget);

    ret = 0;

 cleanup:
    VIR_FREE(fulltarget);
    return ret;
3041 3042 3043
}


3044 3045 3046 3047 3048 3049 3050 3051 3052
static int
virStorageSourceParseBackingJSONNbd(virStorageSourcePtr src,
                                    virJSONValuePtr json,
                                    int opaque ATTRIBUTE_UNUSED)
{
    const char *path = virJSONValueObjectGetString(json, "path");
    const char *host = virJSONValueObjectGetString(json, "host");
    const char *port = virJSONValueObjectGetString(json, "port");
    const char *export = virJSONValueObjectGetString(json, "export");
3053
    virJSONValuePtr server = virJSONValueObjectGetObject(json, "server");
3054

3055
    if (!path && !host && !server) {
3056
        virReportError(VIR_ERR_INVALID_ARG, "%s",
3057 3058
                       _("missing host specification of NBD server in JSON "
                         "backing volume definition"));
3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071
        return -1;
    }

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

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

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

3072 3073
    if (server) {
        if (virStorageSourceParseBackingJSONSocketAddress(src->hosts, server) < 0)
3074 3075
            return -1;
    } else {
3076 3077 3078 3079 3080 3081 3082 3083
        if (path) {
            src->hosts[0].transport = VIR_STORAGE_NET_HOST_TRANS_UNIX;
            if (VIR_STRDUP(src->hosts[0].socket, path) < 0)
                return -1;
        } else {
            src->hosts[0].transport = VIR_STORAGE_NET_HOST_TRANS_TCP;
            if (VIR_STRDUP(src->hosts[0].name, host) < 0)
                return -1;
3084

3085
            if (virStringParsePort(port, &src->hosts[0].port) < 0)
3086 3087
                return -1;
        }
3088 3089 3090 3091 3092 3093
    }

    return 0;
}


3094 3095 3096 3097 3098 3099
static int
virStorageSourceParseBackingJSONSheepdog(virStorageSourcePtr src,
                                         virJSONValuePtr json,
                                         int opaque ATTRIBUTE_UNUSED)
{
    const char *filename;
3100 3101
    const char *vdi = virJSONValueObjectGetString(json, "vdi");
    virJSONValuePtr server = virJSONValueObjectGetObject(json, "server");
3102 3103 3104 3105 3106 3107 3108 3109

    /* 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 */
3110 3111 3112
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("missing sheepdog URI in JSON backing volume definition"));
        return -1;
3113 3114
    }

3115 3116
    src->type = VIR_STORAGE_TYPE_NETWORK;
    src->protocol = VIR_STORAGE_NET_PROTOCOL_SHEEPDOG;
3117

3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134
    if (!vdi) {
        virReportError(VIR_ERR_INVALID_ARG, "%s", _("missing sheepdog vdi name"));
        return -1;
    }

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

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

    src->nhosts = 1;

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

    return 0;
3135 3136 3137
}


3138 3139 3140 3141 3142 3143 3144 3145
static int
virStorageSourceParseBackingJSONSSH(virStorageSourcePtr src,
                                    virJSONValuePtr json,
                                    int opaque ATTRIBUTE_UNUSED)
{
    const char *path = virJSONValueObjectGetString(json, "path");
    const char *host = virJSONValueObjectGetString(json, "host");
    const char *port = virJSONValueObjectGetString(json, "port");
3146
    virJSONValuePtr server = virJSONValueObjectGetObject(json, "server");
3147

3148
    if (!(host || server) || !path) {
3149
        virReportError(VIR_ERR_INVALID_ARG, "%s",
3150
                       _("missing host/server or path of SSH JSON backing "
3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164
                         "volume definition"));
        return -1;
    }

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

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

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

3165 3166 3167 3168 3169 3170
    if (server) {
        if (virStorageSourceParseBackingJSONInetSocketAddress(src->hosts,
                                                              server) < 0)
            return -1;
    } else {
        src->hosts[0].transport = VIR_STORAGE_NET_HOST_TRANS_TCP;
3171

3172
        if (VIR_STRDUP(src->hosts[0].name, host) < 0 ||
3173
            virStringParsePort(port, &src->hosts[0].port) < 0)
3174 3175
            return -1;
    }
3176 3177 3178 3179 3180

    return 0;
}


3181 3182 3183 3184 3185 3186
static int
virStorageSourceParseBackingJSONRBD(virStorageSourcePtr src,
                                    virJSONValuePtr json,
                                    int opaque ATTRIBUTE_UNUSED)
{
    const char *filename;
3187 3188 3189 3190 3191 3192 3193 3194
    const char *pool = virJSONValueObjectGetString(json, "pool");
    const char *image = virJSONValueObjectGetString(json, "image");
    const char *conf = virJSONValueObjectGetString(json, "conf");
    const char *snapshot = virJSONValueObjectGetString(json, "snapshot");
    virJSONValuePtr servers = virJSONValueObjectGetArray(json, "server");
    size_t nservers;
    size_t i;
    int ret = -1;
3195 3196 3197 3198 3199 3200 3201 3202

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

3203 3204 3205 3206 3207 3208
    if (!pool || !image) {
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("missing pool or image name in ceph backing volume "
                         "JSON specification"));
        return -1;
    }
3209

3210 3211 3212
    if (VIR_STRDUP(src->volume, pool) < 0 ||
        VIR_STRDUP(src->path, image) < 0 ||
        VIR_STRDUP(src->snapshot, snapshot) < 0 ||
3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233
        VIR_STRDUP(src->configFile, conf) < 0)
        goto cleanup;

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

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

        src->nhosts = nservers;

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

    ret = 0;
 cleanup:
    return ret;
3234 3235
}

3236 3237 3238 3239 3240 3241 3242 3243 3244 3245
static int
virStorageSourceParseBackingJSONRaw(virStorageSourcePtr src,
                                    virJSONValuePtr json,
                                    int opaque ATTRIBUTE_UNUSED)
{
    /* There are no interesting attributes in raw driver.
     * Treat it as pass-through.
     */
    return virStorageSourceParseBackingJSONInternal(src, json);
}
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

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

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

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

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

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

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

    return 0;
}


3281 3282 3283 3284 3285 3286 3287 3288
struct virStorageSourceJSONDriverParser {
    const char *drvname;
    int (*func)(virStorageSourcePtr src, virJSONValuePtr json, int opaque);
    int opaque;
};

static const struct virStorageSourceJSONDriverParser jsonParsers[] = {
    {"file", virStorageSourceParseBackingJSONPath, VIR_STORAGE_TYPE_FILE},
3289 3290
    {"host_device", virStorageSourceParseBackingJSONPath, VIR_STORAGE_TYPE_BLOCK},
    {"host_cdrom", virStorageSourceParseBackingJSONPath, VIR_STORAGE_TYPE_BLOCK},
3291 3292 3293 3294 3295
    {"http", virStorageSourceParseBackingJSONUri, VIR_STORAGE_NET_PROTOCOL_HTTP},
    {"https", virStorageSourceParseBackingJSONUri, VIR_STORAGE_NET_PROTOCOL_HTTPS},
    {"ftp", virStorageSourceParseBackingJSONUri, VIR_STORAGE_NET_PROTOCOL_FTP},
    {"ftps", virStorageSourceParseBackingJSONUri, VIR_STORAGE_NET_PROTOCOL_FTPS},
    {"tftp", virStorageSourceParseBackingJSONUri, VIR_STORAGE_NET_PROTOCOL_TFTP},
3296
    {"gluster", virStorageSourceParseBackingJSONGluster, 0},
3297
    {"iscsi", virStorageSourceParseBackingJSONiSCSI, 0},
3298
    {"nbd", virStorageSourceParseBackingJSONNbd, 0},
3299
    {"sheepdog", virStorageSourceParseBackingJSONSheepdog, 0},
3300
    {"ssh", virStorageSourceParseBackingJSONSSH, 0},
3301
    {"rbd", virStorageSourceParseBackingJSONRBD, 0},
3302
    {"raw", virStorageSourceParseBackingJSONRaw, 0},
3303
    {"vxhs", virStorageSourceParseBackingJSONVxHS, 0},
3304 3305 3306 3307 3308
};



static int
3309 3310
virStorageSourceParseBackingJSONInternal(virStorageSourcePtr src,
                                         virJSONValuePtr json)
3311
{
3312
    virJSONValuePtr deflattened = NULL;
3313 3314
    virJSONValuePtr file;
    const char *drvname;
3315
    char *str = NULL;
3316 3317 3318
    size_t i;
    int ret = -1;

3319 3320
    if (!(deflattened = virJSONValueObjectDeflatten(json)))
        goto cleanup;
3321

3322 3323 3324
    if (!(file = virJSONValueObjectGetObject(deflattened, "file"))) {
        str = virJSONValueToString(json, false);
        virReportError(VIR_ERR_INVALID_ARG,
3325
                       _("JSON backing volume definition '%s' lacks 'file' object"),
3326 3327
                       NULLSTR(str));
        goto cleanup;
3328 3329 3330
    }

    if (!(drvname = virJSONValueObjectGetString(file, "driver"))) {
3331 3332
        str = virJSONValueToString(json, false);
        virReportError(VIR_ERR_INVALID_ARG,
3333
                       _("JSON backing volume definition '%s' lacks driver name"),
3334
                       NULLSTR(str));
3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349
        goto cleanup;
    }

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

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

 cleanup:
3350
    VIR_FREE(str);
3351
    virJSONValueFree(deflattened);
3352 3353 3354 3355
    return ret;
}


3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372
static int
virStorageSourceParseBackingJSON(virStorageSourcePtr src,
                                 const char *json)
{
    virJSONValuePtr root = NULL;
    int ret = -1;

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

    ret = virStorageSourceParseBackingJSONInternal(src, root);

    virJSONValueFree(root);
    return ret;
}


3373
virStorageSourcePtr
3374 3375
virStorageSourceNewFromBackingAbsolute(const char *path)
{
3376
    const char *json;
3377
    virStorageSourcePtr ret;
3378
    int rc;
3379 3380 3381 3382 3383 3384 3385

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

    if (virStorageIsFile(path)) {
        ret->type = VIR_STORAGE_TYPE_FILE;

3386 3387
        if (VIR_STRDUP(ret->path, path) < 0)
            goto error;
3388 3389 3390
    } else {
        ret->type = VIR_STORAGE_TYPE_NETWORK;

3391 3392
        VIR_DEBUG("parsing backing store string: '%s'", path);

3393
        /* handle URI formatted backing stores */
3394 3395 3396 3397 3398 3399 3400 3401 3402
        if ((json = STRSKIP(path, "json:")))
            rc = virStorageSourceParseBackingJSON(ret, json);
        else if (strstr(path, "://"))
            rc = virStorageSourceParseBackingURI(ret, path);
        else
            rc = virStorageSourceParseBackingColon(ret, path);

        if (rc < 0)
            goto error;
3403

3404
        virStorageSourceNetworkAssignDefaultPorts(ret);
3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438
    }

    return ret;

 error:
    virStorageSourceFree(ret);
    return NULL;
}


virStorageSourcePtr
virStorageSourceNewFromBacking(virStorageSourcePtr parent)
{
    struct stat st;
    virStorageSourcePtr ret;

    if (virStorageIsRelative(parent->backingStoreRaw))
        ret = virStorageSourceNewFromBackingRelative(parent,
                                                     parent->backingStoreRaw);
    else
        ret = virStorageSourceNewFromBackingAbsolute(parent->backingStoreRaw);

    if (ret) {
        /* possibly update local type */
        if (ret->type == VIR_STORAGE_TYPE_FILE) {
            if (stat(ret->path, &st) == 0) {
                if (S_ISDIR(st.st_mode)) {
                    ret->type = VIR_STORAGE_TYPE_DIR;
                    ret->format = VIR_STORAGE_FILE_DIR;
                } else if (S_ISBLK(st.st_mode)) {
                    ret->type = VIR_STORAGE_TYPE_BLOCK;
                }
            }
        }
3439 3440

        /* copy parent's labelling and other top level stuff */
3441
        if (virStorageSourceInitChainElement(ret, parent, true) < 0)
3442
            goto error;
3443 3444

        ret->detected = true;
3445 3446 3447
    }

    return ret;
3448 3449 3450 3451

 error:
    virStorageSourceFree(ret);
    return NULL;
3452
}
3453 3454


3455
/**
3456 3457 3458
 * @src: disk source definition structure
 * @fd: file descriptor
 * @sb: stat buffer
3459
 *
3460 3461 3462 3463 3464
 * Updates src->physical depending on the actual type of storage being used.
 * To be called for domain storage source reporting as the volume code does
 * not set/use the 'type' field for the voldef->source.target
 *
 * Returns 0 on success, -1 on error.
3465 3466
 */
int
3467 3468 3469
virStorageSourceUpdatePhysicalSize(virStorageSourcePtr src,
                                   int fd,
                                   struct stat const *sb)
3470 3471
{
    off_t end;
3472
    virStorageType actual_type = virStorageSourceGetActualType(src);
3473

3474 3475 3476 3477 3478
    switch (actual_type) {
    case VIR_STORAGE_TYPE_FILE:
    case VIR_STORAGE_TYPE_NETWORK:
        src->physical = sb->st_size;
        break;
3479

3480 3481 3482
    case VIR_STORAGE_TYPE_BLOCK:
        if ((end = lseek(fd, 0, SEEK_END)) == (off_t) -1) {
            virReportSystemError(errno, _("failed to seek to end of '%s'"),
3483
                                 src->path);
3484 3485
            return -1;
        }
3486 3487

        src->physical = end;
3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503
        break;

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

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

3506
    return 0;
3507 3508 3509
}


3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574
/**
 * @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;
}


3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613
/**
 * @src: disk source definition structure
 * @buf: buffer to the storage file header
 * @len: length of the storage file header
 * @probe: allow probe
 *
 * Update the storage @src capacity. This may involve probing the storage
 * @src in order to "see" if we can recognize what exists.
 *
 * Returns 0 on success, -1 on error.
 */
int
virStorageSourceUpdateCapacity(virStorageSourcePtr src,
                               char *buf,
                               ssize_t len,
                               bool probe)
{
    int ret = -1;
    virStorageSourcePtr meta = NULL;
    int format = src->format;

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

        if ((format = virStorageFileProbeFormatFromBuf(src->path,
                                                       buf, len)) < 0)
            goto cleanup;

        src->format = format;
    }

3614
    if (format == VIR_STORAGE_FILE_RAW && !src->encryption) {
3615
        src->capacity = src->physical;
3616 3617
    } else if ((meta = virStorageFileGetMetadataFromBuf(src->path, buf,
                                                        len, format, NULL))) {
3618
        src->capacity = meta->capacity ? meta->capacity : src->physical;
3619 3620 3621
        if (src->encryption && meta->encryption)
            src->encryption->payload_offset = meta->encryption->payload_offset;
    } else {
3622
        goto cleanup;
3623
    }
3624

3625 3626 3627
    if (src->encryption && src->encryption->payload_offset != -1)
        src->capacity -= src->encryption->payload_offset * 512;

3628 3629 3630 3631 3632 3633 3634 3635
    ret = 0;

 cleanup:
    virStorageSourceFree(meta);
    return ret;
}


3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658
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);
    }

3659
    if (virBufferCheckError(&buf) < 0)
3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694
        return NULL;

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

    return ret;
}


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

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

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

        at++;
    }

    ret = 0;

 cleanup:
3695
    virStringListFreeCount(tmp, ntmp);
3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842
    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;
    char *linkpath = NULL;
    char *currentpath = NULL;
    size_t i = 0;
    size_t j = 0;
    int rc;
    char *ret = NULL;

    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);
3843
    virStringListFreeCount(components, ncomponents);
3844 3845 3846 3847 3848
    VIR_FREE(linkpath);
    VIR_FREE(currentpath);

    return ret;
}
3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867


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

    if (VIR_STRDUP(ret, path ? path : "") < 0)
        return NULL;

3868
    virFileRemoveLastComponent(ret);
3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893

    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;
    char *tmp = NULL;
    char *path = NULL;
    char ret = -1;

    *relpath = NULL;

3894
    for (next = top; virStorageSourceIsBacking(next); next = next->backingStore) {
3895
        if (!next->relPath) {
3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930
            ret = 1;
            goto cleanup;
        }

        if (!(tmp = virStorageFileRemoveLastPathComponent(path)))
            goto cleanup;

        VIR_FREE(path);

        if (virAsprintf(&path, "%s%s", tmp, next->relPath) < 0)
            goto cleanup;

        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"));
        goto cleanup;
    }

    *relpath = path;
    path = NULL;

    ret = 0;

 cleanup:
    VIR_FREE(path);
    VIR_FREE(tmp);
    return ret;
}
3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956


/*
 * virStorageFileCheckCompat
 */
int
virStorageFileCheckCompat(const char *compat)
{
    char **version;
    unsigned int result;
    int ret = -1;

    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"));
        goto cleanup;
    }
    ret = 0;

 cleanup:
3957
    virStringListFree(version);
3958 3959
    return ret;
}
3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990


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

    if (!src->path)
        return false;

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

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

    return false;
}
3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005


/**
 * 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 已提交
4006
                               unsigned int *idx)
4007 4008 4009
{
    virStorageSourcePtr tmp;

E
Eric Blake 已提交
4010 4011
    if (idx)
        *idx = 0;
4012

4013
    for (tmp = top; virStorageSourceIsBacking(tmp); tmp = tmp->backingStore) {
4014
        if ((tmp->nodeformat && STREQ(tmp->nodeformat, nodeName)) ||
4015
            (tmp->nodestorage && STREQ(tmp->nodestorage, nodeName)))
4016 4017
            return tmp;

E
Eric Blake 已提交
4018 4019
        if (idx)
            (*idx)++;
4020 4021
    }

E
Eric Blake 已提交
4022 4023
    if (idx)
        *idx = 0;
4024 4025
    return NULL;
}
4026 4027


4028
static unsigned int
4029 4030 4031 4032
virStorageSourceNetworkDefaultPort(virStorageNetProtocol protocol)
{
    switch (protocol) {
        case VIR_STORAGE_NET_PROTOCOL_HTTP:
4033
            return 80;
4034 4035

        case VIR_STORAGE_NET_PROTOCOL_HTTPS:
4036
            return 443;
4037 4038

        case VIR_STORAGE_NET_PROTOCOL_FTP:
4039
            return 21;
4040 4041

        case VIR_STORAGE_NET_PROTOCOL_FTPS:
4042
            return 990;
4043 4044

        case VIR_STORAGE_NET_PROTOCOL_TFTP:
4045
            return 69;
4046 4047

        case VIR_STORAGE_NET_PROTOCOL_SHEEPDOG:
4048
            return 7000;
4049 4050

        case VIR_STORAGE_NET_PROTOCOL_NBD:
4051
            return 10809;
4052 4053

        case VIR_STORAGE_NET_PROTOCOL_SSH:
4054
            return 22;
4055 4056

        case VIR_STORAGE_NET_PROTOCOL_ISCSI:
4057
            return 3260;
4058

4059
        case VIR_STORAGE_NET_PROTOCOL_GLUSTER:
4060
            return 24007;
4061 4062

        case VIR_STORAGE_NET_PROTOCOL_RBD:
4063
            /* we don't provide a default for RBD */
4064
            return 0;
4065

4066
        case VIR_STORAGE_NET_PROTOCOL_VXHS:
4067 4068
            return 9999;

4069 4070
        case VIR_STORAGE_NET_PROTOCOL_LAST:
        case VIR_STORAGE_NET_PROTOCOL_NONE:
4071
            return 0;
4072 4073
    }

4074
    return 0;
4075
}
4076 4077


4078
void
4079 4080 4081 4082 4083 4084
virStorageSourceNetworkAssignDefaultPorts(virStorageSourcePtr src)
{
    size_t i;

    for (i = 0; i < src->nhosts; i++) {
        if (src->hosts[i].transport == VIR_STORAGE_NET_HOST_TRANS_TCP &&
4085 4086
            src->hosts[i].port == 0)
            src->hosts[i].port = virStorageSourceNetworkDefaultPort(src->protocol);
4087 4088
    }
}
4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108


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