virstoragefile.c 92.5 KB
Newer Older
1
/*
2
 * virstoragefile.c: file utility functions for FS storage backend
3
 *
4
 * Copyright (C) 2007-2014, 2016 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 <sys/stat.h>
28
#include <unistd.h>
29
#include <fcntl.h>
30
#include <stdlib.h>
31
#include "viralloc.h"
32 33
#include "virxml.h"
#include "viruuid.h"
34
#include "virerror.h"
35
#include "virlog.h"
E
Eric Blake 已提交
36
#include "virfile.h"
37
#include "c-ctype.h"
38
#include "vircommand.h"
39
#include "virhash.h"
E
Eric Blake 已提交
40
#include "virendian.h"
41 42
#include "virstring.h"
#include "virutil.h"
43 44
#include "viruri.h"
#include "dirname.h"
45
#include "virbuffer.h"
46
#include "virjson.h"
47 48 49

#define VIR_FROM_THIS VIR_FROM_STORAGE

50 51
VIR_LOG_INIT("util.storagefile");

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

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

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

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

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

95 96 97 98 99
VIR_ENUM_IMPL(virStorageSourcePoolMode,
              VIR_STORAGE_SOURCE_POOL_MODE_LAST,
              "default",
              "host",
              "direct")
100

101 102 103 104
VIR_ENUM_IMPL(virStorageAuth,
              VIR_STORAGE_AUTH_TYPE_LAST,
              "none", "chap", "ceph")

105 106 107 108 109 110 111 112 113 114 115
enum lv_endian {
    LV_LITTLE_ENDIAN = 1, /* 1234 */
    LV_BIG_ENDIAN         /* 4321 */
};

enum {
    BACKING_STORE_OK,
    BACKING_STORE_INVALID,
    BACKING_STORE_ERROR,
};

116 117
#define FILE_TYPE_VERSIONS_LAST 2

118 119
/* Either 'magic' or 'extension' *must* be provided */
struct FileTypeInfo {
120
    int magicOffset;    /* Byte offset of the magic */
121 122 123 124
    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 */
125

126 127
    int versionOffset;    /* Byte offset from start of file
                           * where we find version number,
128 129
                           * -1 to always fail the version test,
                           * -2 to always pass the version test */
130
    int versionSize;      /* Size in bytes of version data (0, 2, or 4) */
131 132
    int versionNumbers[FILE_TYPE_VERSIONS_LAST];
                          /* Version numbers to validate. Zeroes are ignored. */
133 134 135 136 137 138 139 140 141 142 143
    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_* */
    int qcowCryptOffset;  /* Byte offset from start of file
                           * where to find encryption mode,
                           * -1 if encryption is not used */
144
    int (*getBackingStore)(char **res, int *format,
E
Eric Blake 已提交
145
                           const char *buf, size_t buf_size);
146
    int (*getFeatures)(virBitmapPtr *features, int format,
E
Eric Blake 已提交
147
                       char *buf, ssize_t len);
148 149
};

150
static int cowGetBackingStore(char **, int *,
E
Eric Blake 已提交
151
                              const char *, size_t);
152
static int qcow1GetBackingStore(char **, int *,
E
Eric Blake 已提交
153
                                const char *, size_t);
154
static int qcow2GetBackingStore(char **, int *,
E
Eric Blake 已提交
155
                                const char *, size_t);
156
static int qcow2GetFeatures(virBitmapPtr *features, int format,
E
Eric Blake 已提交
157
                            char *buf, ssize_t len);
158
static int vmdk4GetBackingStore(char **, int *,
E
Eric Blake 已提交
159
                                const char *, size_t);
160
static int
E
Eric Blake 已提交
161
qedGetBackingStore(char **, int *, const char *, size_t);
162 163 164 165 166 167

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

168
#define QCOW1_HDR_CRYPT (QCOWX_HDR_IMAGE_SIZE+8+1+1+2)
169 170 171 172 173 174 175 176
#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

177 178 179 180 181 182 183
#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)

184
#define QED_HDR_FEATURES_OFFSET (4+4+4+4)
185 186
#define QED_HDR_IMAGE_SIZE (QED_HDR_FEATURES_OFFSET+8+8+8+8)
#define QED_HDR_BACKING_FILE_OFFSET (QED_HDR_IMAGE_SIZE+8)
187 188 189
#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 已提交
190

191 192
#define PLOOP_IMAGE_SIZE_OFFSET 36
#define PLOOP_SIZE_MULTIPLIER 512
193

194 195 196 197 198 199 200
#define LUKS_HDR_MAGIC_LEN 6
#define LUKS_HDR_VERSION_LEN 2

/* Format described by qemu commit id '3e308f20e' */
#define LUKS_HDR_VERSION_OFFSET LUKS_HDR_MAGIC_LEN


201
static struct FileTypeInfo const fileTypeInfo[] = {
202
    [VIR_STORAGE_FILE_NONE] = { 0, NULL, NULL, LV_LITTLE_ENDIAN,
203
                                -1, 0, {0}, 0, 0, 0, 0, NULL, NULL },
204
    [VIR_STORAGE_FILE_RAW] = { 0, NULL, NULL, LV_LITTLE_ENDIAN,
205
                               -1, 0, {0}, 0, 0, 0, 0, NULL, NULL },
206
    [VIR_STORAGE_FILE_DIR] = { 0, NULL, NULL, LV_LITTLE_ENDIAN,
207
                               -1, 0, {0}, 0, 0, 0, 0, NULL, NULL },
208
    [VIR_STORAGE_FILE_BOCHS] = {
209 210
        /*"Bochs Virtual HD Image", */ /* Untested */
        0, NULL, NULL,
211
        LV_LITTLE_ENDIAN, 64, 4, {0x20000},
212
        32+16+16+4+4+4+4+4, 8, 1, -1, NULL, NULL
213 214
    },
    [VIR_STORAGE_FILE_CLOOP] = {
215 216 217 218 219
        /* #!/bin/sh
           #V2.0 Format
           modprobe cloop file=$0 && mount -r -t iso9660 /dev/cloop $1
        */ /* Untested */
        0, NULL, NULL,
220
        LV_LITTLE_ENDIAN, -1, 0, {0},
221
        -1, 0, 0, -1, NULL, NULL
222 223
    },
    [VIR_STORAGE_FILE_DMG] = {
224 225 226 227
        /* 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",
228
        0, -1, 0, {0},
229
        -1, 0, 0, -1, NULL, NULL
230 231
    },
    [VIR_STORAGE_FILE_ISO] = {
232
        32769, "CD001", ".iso",
233
        LV_LITTLE_ENDIAN, -2, 0, {0},
234
        -1, 0, 0, -1, NULL, NULL
235
    },
236 237
    [VIR_STORAGE_FILE_VPC] = {
        0, "conectix", NULL,
238
        LV_BIG_ENDIAN, 12, 4, {0x10000},
239 240 241 242 243
        8 + 4 + 4 + 8 + 4 + 4 + 2 + 2 + 4, 8, 1, -1, NULL, NULL
    },
    /* TODO: add getBackingStore function */
    [VIR_STORAGE_FILE_VDI] = {
        64, "\x7f\x10\xda\xbe", ".vdi",
244
        LV_LITTLE_ENDIAN, 68, 4, {0x00010001},
245 246 247 248
        64 + 5 * 4 + 256 + 7 * 4, 8, 1, -1, NULL, NULL},

    /* Not direct file formats, but used for various drivers */
    [VIR_STORAGE_FILE_FAT] = { 0, NULL, NULL, LV_LITTLE_ENDIAN,
249
                               -1, 0, {0}, 0, 0, 0, 0, NULL, NULL },
250
    [VIR_STORAGE_FILE_VHD] = { 0, NULL, NULL, LV_LITTLE_ENDIAN,
251
                               -1, 0, {0}, 0, 0, 0, 0, NULL, NULL },
252
    [VIR_STORAGE_FILE_PLOOP] = { 0, "WithouFreSpacExt", NULL, LV_LITTLE_ENDIAN,
253
                                 -2, 0, {0}, PLOOP_IMAGE_SIZE_OFFSET, 0,
254
                                 PLOOP_SIZE_MULTIPLIER, -1, NULL, NULL },
255

256 257 258 259 260 261 262
    /* Magic is 'L','U','K','S', 0xBA, 0xBE
     * Set sizeOffset = -1 and let hypervisor handle */
    [VIR_STORAGE_FILE_LUKS] = {
        0, "\x4c\x55\x4b\x53\xba\xbe", NULL,
        LV_BIG_ENDIAN, LUKS_HDR_VERSION_OFFSET, 2, {1},
        -1, 0, 0, -1, NULL, NULL
    },
263 264 265
    /* All formats with a backing store probe below here */
    [VIR_STORAGE_FILE_COW] = {
        0, "OOOM", NULL,
266
        LV_BIG_ENDIAN, 4, 4, {2},
267 268
        4+4+1024+4, 8, 1, -1, cowGetBackingStore, NULL
    },
269
    [VIR_STORAGE_FILE_QCOW] = {
270
        0, "QFI", NULL,
271
        LV_BIG_ENDIAN, 4, 4, {1},
272
        QCOWX_HDR_IMAGE_SIZE, 8, 1, QCOW1_HDR_CRYPT, qcow1GetBackingStore, NULL
273 274
    },
    [VIR_STORAGE_FILE_QCOW2] = {
275
        0, "QFI", NULL,
276
        LV_BIG_ENDIAN, 4, 4, {2, 3},
277
        QCOWX_HDR_IMAGE_SIZE, 8, 1, QCOW2_HDR_CRYPT, qcow2GetBackingStore,
278
        qcow2GetFeatures
279
    },
A
Adam Litke 已提交
280 281
    [VIR_STORAGE_FILE_QED] = {
        /* http://wiki.qemu.org/Features/QED */
282
        0, "QED", NULL,
283
        LV_LITTLE_ENDIAN, -2, 0, {0},
284
        QED_HDR_IMAGE_SIZE, 8, 1, -1, qedGetBackingStore, NULL
A
Adam Litke 已提交
285
    },
286
    [VIR_STORAGE_FILE_VMDK] = {
287
        0, "KDMV", NULL,
288
        LV_LITTLE_ENDIAN, 4, 4, {1, 2},
289
        4+4+4, 8, 512, -1, vmdk4GetBackingStore, NULL
290
    },
291
};
292
verify(ARRAY_CARDINALITY(fileTypeInfo) == VIR_STORAGE_FILE_LAST);
293

294 295 296 297 298 299 300 301 302 303 304 305 306 307
/* 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);

308
static int
309
cowGetBackingStore(char **res,
310
                   int *format,
E
Eric Blake 已提交
311
                   const char *buf,
312 313 314 315
                   size_t buf_size)
{
#define COW_FILENAME_MAXLEN 1024
    *res = NULL;
316 317
    *format = VIR_STORAGE_FILE_AUTO;

318 319
    if (buf_size < 4+4+ COW_FILENAME_MAXLEN)
        return BACKING_STORE_INVALID;
E
Eric Blake 已提交
320 321
    if (buf[4+4] == '\0') { /* cow_header_v2.backing_file[0] */
        *format = VIR_STORAGE_FILE_NONE;
322
        return BACKING_STORE_OK;
E
Eric Blake 已提交
323
    }
324

325
    if (VIR_STRNDUP(*res, (const char*)buf + 4 + 4, COW_FILENAME_MAXLEN) < 0)
326 327 328 329
        return BACKING_STORE_ERROR;
    return BACKING_STORE_OK;
}

330 331 332

static int
qcow2GetBackingStoreFormat(int *format,
E
Eric Blake 已提交
333
                           const char *buf,
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
                           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 已提交
352 353
        unsigned int magic = virReadBufInt32BE(buf + offset);
        unsigned int len = virReadBufInt32BE(buf + offset + 4);
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371

        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 已提交
372 373
            if (*format <= VIR_STORAGE_FILE_NONE)
                return -1;
374 375 376 377 378
        }

        offset += len;
    }

379
 done:
380 381 382 383 384

    return 0;
}


385
static int
386
qcowXGetBackingStore(char **res,
387
                     int *format,
E
Eric Blake 已提交
388
                     const char *buf,
389 390
                     size_t buf_size,
                     bool isQCow2)
391 392
{
    unsigned long long offset;
393
    unsigned int size;
394 395
    unsigned long long start;
    int version;
396 397

    *res = NULL;
398 399 400 401
    if (format)
        *format = VIR_STORAGE_FILE_AUTO;

    if (buf_size < QCOWX_HDR_BACKING_FILE_OFFSET+8+4)
402
        return BACKING_STORE_INVALID;
E
Eric Blake 已提交
403
    offset = virReadBufInt64BE(buf + QCOWX_HDR_BACKING_FILE_OFFSET);
404 405
    if (offset > buf_size)
        return BACKING_STORE_INVALID;
406 407 408 409 410 411 412

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

E
Eric Blake 已提交
413
    size = virReadBufInt32BE(buf + QCOWX_HDR_BACKING_FILE_SIZE);
E
Eric Blake 已提交
414 415 416
    if (size == 0) {
        if (format)
            *format = VIR_STORAGE_FILE_NONE;
417
        return BACKING_STORE_OK;
E
Eric Blake 已提交
418
    }
419
    if (size > 1023)
420
        return BACKING_STORE_INVALID;
421
    if (offset + size > buf_size || offset + size < offset)
422
        return BACKING_STORE_INVALID;
423
    if (VIR_ALLOC_N(*res, size + 1) < 0)
424 425 426
        return BACKING_STORE_ERROR;
    memcpy(*res, buf + offset, size);
    (*res)[size] = '\0';
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450

    /*
     * 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)
451 452 453
     *
     * for qcow2 v3 images, the length of the header
     * is stored at QCOW2v3_HDR_SIZE
454
     */
455 456 457 458 459 460 461 462 463 464
    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;
    }
465

466 467 468 469
    return BACKING_STORE_OK;
}


470 471 472
static int
qcow1GetBackingStore(char **res,
                     int *format,
E
Eric Blake 已提交
473
                     const char *buf,
474 475
                     size_t buf_size)
{
E
Eric Blake 已提交
476 477
    int ret;

478 479 480
    /* QCow1 doesn't have the extensions capability
     * used to store backing format */
    *format = VIR_STORAGE_FILE_AUTO;
E
Eric Blake 已提交
481 482 483 484
    ret = qcowXGetBackingStore(res, NULL, buf, buf_size, false);
    if (ret == 0 && *buf == '\0')
        *format = VIR_STORAGE_FILE_NONE;
    return ret;
485 486 487 488 489
}

static int
qcow2GetBackingStore(char **res,
                     int *format,
E
Eric Blake 已提交
490
                     const char *buf,
491 492 493 494 495 496
                     size_t buf_size)
{
    return qcowXGetBackingStore(res, format, buf, buf_size, true);
}


497
static int
498
vmdk4GetBackingStore(char **res,
499
                     int *format,
E
Eric Blake 已提交
500
                     const char *buf,
501 502 503
                     size_t buf_size)
{
    static const char prefix[] = "parentFileNameHint=\"";
504
    char *desc, *start, *end;
505
    size_t len;
506 507
    int ret = BACKING_STORE_ERROR;

508
    if (VIR_ALLOC_N(desc, VIR_STORAGE_MAX_HEADER) < 0)
509
        goto cleanup;
510 511

    *res = NULL;
512 513
    /*
     * Technically this should have been VMDK, since
J
Ján Tomko 已提交
514
     * VMDK spec / VMware impl only support VMDK backed
515 516 517 518 519
     * by VMDK. QEMU isn't following this though and
     * does probing on VMDK backing files, hence we set
     * AUTO
     */
    *format = VIR_STORAGE_FILE_AUTO;
520

521 522 523 524
    if (buf_size <= 0x200) {
        ret = BACKING_STORE_INVALID;
        goto cleanup;
    }
525
    len = buf_size - 0x200;
526 527
    if (len > VIR_STORAGE_MAX_HEADER)
        len = VIR_STORAGE_MAX_HEADER;
528 529 530
    memcpy(desc, buf + 0x200, len);
    desc[len] = '\0';
    start = strstr(desc, prefix);
531
    if (start == NULL) {
E
Eric Blake 已提交
532
        *format = VIR_STORAGE_FILE_NONE;
533 534 535
        ret = BACKING_STORE_OK;
        goto cleanup;
    }
536 537
    start += strlen(prefix);
    end = strchr(start, '"');
538 539 540 541 542
    if (end == NULL) {
        ret = BACKING_STORE_INVALID;
        goto cleanup;
    }
    if (end == start) {
E
Eric Blake 已提交
543
        *format = VIR_STORAGE_FILE_NONE;
544 545 546
        ret = BACKING_STORE_OK;
        goto cleanup;
    }
547
    *end = '\0';
548
    if (VIR_STRDUP(*res, start) < 0)
549 550 551 552
        goto cleanup;

    ret = BACKING_STORE_OK;

553
 cleanup:
554 555
    VIR_FREE(desc);
    return ret;
556 557
}

558 559 560
static int
qedGetBackingStore(char **res,
                   int *format,
E
Eric Blake 已提交
561
                   const char *buf,
562 563 564 565 566 567 568 569 570
                   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 已提交
571
    flags = virReadBufInt64LE(buf + QED_HDR_FEATURES_OFFSET);
E
Eric Blake 已提交
572 573
    if (!(flags & QED_F_BACKING_FILE)) {
        *format = VIR_STORAGE_FILE_NONE;
574
        return BACKING_STORE_OK;
E
Eric Blake 已提交
575
    }
576 577 578 579

    /* Parse the backing file */
    if (buf_size < QED_HDR_BACKING_FILE_OFFSET+8)
        return BACKING_STORE_INVALID;
E
Eric Blake 已提交
580
    offset = virReadBufInt32LE(buf + QED_HDR_BACKING_FILE_OFFSET);
581 582
    if (offset > buf_size)
        return BACKING_STORE_INVALID;
E
Eric Blake 已提交
583
    size = virReadBufInt32LE(buf + QED_HDR_BACKING_FILE_SIZE);
584 585 586 587
    if (size == 0)
        return BACKING_STORE_OK;
    if (offset + size > buf_size || offset + size < offset)
        return BACKING_STORE_INVALID;
588
    if (VIR_ALLOC_N(*res, size + 1) < 0)
589 590 591 592
        return BACKING_STORE_ERROR;
    memcpy(*res, buf + offset, size);
    (*res)[size] = '\0';

E
Eric Blake 已提交
593 594 595 596
    if (flags & QED_F_BACKING_FORMAT_NO_PROBE)
        *format = VIR_STORAGE_FILE_RAW;
    else
        *format = VIR_STORAGE_FILE_AUTO_SAFE;
597 598 599 600

    return BACKING_STORE_OK;
}

601 602

static bool
603 604
virStorageFileMatchesMagic(int magicOffset,
                           const char *magic,
E
Eric Blake 已提交
605
                           char *buf,
606
                           size_t buflen)
607
{
608
    int mlen;
609

610
    if (magic == NULL)
611
        return false;
612

613
    /* Validate magic data */
614 615
    mlen = strlen(magic);
    if (magicOffset + mlen > buflen)
616
        return false;
617

618
    if (memcmp(buf + magicOffset, magic, mlen) != 0)
619 620 621 622 623 624 625
        return false;

    return true;
}


static bool
626
virStorageFileMatchesExtension(const char *extension,
627 628
                               const char *path)
{
629
    if (extension == NULL)
630 631
        return false;

632
    if (virFileHasSuffix(path, extension))
633 634 635 636 637 638 639
        return true;

    return false;
}


static bool
640 641 642 643
virStorageFileMatchesVersion(int versionOffset,
                             int versionSize,
                             const int *versionNumbers,
                             int endian,
E
Eric Blake 已提交
644
                             char *buf,
645 646
                             size_t buflen)
{
647
    int version = 0;
648
    size_t i;
649 650

    /* Validate version number info */
651
    if (versionOffset == -1)
E
Eric Blake 已提交
652
        return false;
653

654
    /* -2 == non-versioned file format, so trivially match */
655
    if (versionOffset == -2)
656 657
        return true;

658
    /* A positive versionOffset, requires using a valid versionSize */
659
    if (versionSize != 2 && versionSize != 4)
660 661
        return false;

662
    if ((versionOffset + versionSize) > buflen)
663 664
        return false;

665 666
    if (endian == LV_LITTLE_ENDIAN) {
        if (versionSize == 4)
667
            version = virReadBufInt32LE(buf +
668
                                        versionOffset);
669 670
        else
            version = virReadBufInt16LE(buf +
671
                                        versionOffset);
672
    } else {
673
        if (versionSize == 4)
674
            version = virReadBufInt32BE(buf +
675
                                        versionOffset);
676 677
        else
            version = virReadBufInt16BE(buf +
678
                                        versionOffset);
679
    }
680

681
    for (i = 0;
682
         i < FILE_TYPE_VERSIONS_LAST && versionNumbers[i];
683 684
         i++) {
        VIR_DEBUG("Compare detected version %d vs one of the expected versions %d",
685 686
                  version, versionNumbers[i]);
        if (version == versionNumbers[i])
687 688
            return true;
    }
689

690
    return false;
691
}
692

693 694
bool
virStorageIsFile(const char *backing)
A
Adam Litke 已提交
695
{
696 697 698 699 700 701 702 703
    char *colon;
    char *slash;

    if (!backing)
        return false;

    colon = strchr(backing, ':');
    slash = strchr(backing, '/');
704 705 706 707 708

    /* 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 已提交
709 710 711
        return false;
    return true;
}
712

E
Eric Blake 已提交
713

714 715 716 717 718 719 720 721 722 723 724 725 726
static bool
virStorageIsRelative(const char *backing)
{
    if (backing[0] == '/')
        return false;

    if (!virStorageIsFile(backing))
        return false;

    return true;
}


727
int
E
Eric Blake 已提交
728
virStorageFileProbeFormatFromBuf(const char *path,
E
Eric Blake 已提交
729
                                 char *buf,
E
Eric Blake 已提交
730 731 732
                                 size_t buflen)
{
    int format = VIR_STORAGE_FILE_RAW;
733
    size_t i;
E
Eric Blake 已提交
734
    int possibleFormat = VIR_STORAGE_FILE_RAW;
735
    VIR_DEBUG("path=%s, buf=%p, buflen=%zu", path, buf, buflen);
E
Eric Blake 已提交
736 737

    /* First check file magic */
738
    for (i = 0; i < VIR_STORAGE_FILE_LAST; i++) {
739 740 741 742 743 744 745 746 747 748
        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 已提交
749 750 751 752 753 754 755 756 757 758 759 760 761 762
                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 */
763
    for (i = 0; i < VIR_STORAGE_FILE_LAST; i++) {
764 765
        if (virStorageFileMatchesExtension(
                fileTypeInfo[i].extension, path)) {
E
Eric Blake 已提交
766 767 768 769 770
            format = i;
            goto cleanup;
        }
    }

771
 cleanup:
E
Eric Blake 已提交
772 773 774 775 776
    VIR_DEBUG("format=%d", format);
    return format;
}


777 778 779
static int
qcow2GetFeatures(virBitmapPtr *features,
                 int format,
E
Eric Blake 已提交
780
                 char *buf,
781 782 783 784 785
                 ssize_t len)
{
    int version = -1;
    virBitmapPtr feat = NULL;
    uint64_t bits;
786
    size_t i;
787 788 789 790 791 792 793 794 795

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

    if (version == 2)
        return 0;

    if (len < QCOW2v3_HDR_SIZE)
        return -1;

796
    if (!(feat = virBitmapNew(VIR_STORAGE_FILE_FEATURE_LAST)))
797 798 799 800 801 802 803 804 805 806 807 808 809 810
        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;
}


811 812 813 814 815
/* 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 */
816
int
817
virStorageFileGetMetadataInternal(virStorageSourcePtr meta,
818 819
                                  char *buf,
                                  size_t len,
820
                                  int *backingFormat)
821
{
822
    int ret = -1;
E
Eric Blake 已提交
823

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

827
    if (meta->format == VIR_STORAGE_FILE_AUTO)
828
        meta->format = virStorageFileProbeFormatFromBuf(meta->path, buf, len);
829

830 831 832 833
    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 已提交
834 835
        goto cleanup;
    }
836

837 838 839
    /* XXX we should consider moving virStorageBackendUpdateVolInfo
     * code into this method, for non-magic files
     */
840
    if (!fileTypeInfo[meta->format].magic)
E
Eric Blake 已提交
841
        goto done;
842

843
    /* Optionally extract capacity from file */
844 845
    if (fileTypeInfo[meta->format].sizeOffset != -1) {
        if ((fileTypeInfo[meta->format].sizeOffset + 8) > len)
E
Eric Blake 已提交
846
            goto done;
847

848
        if (fileTypeInfo[meta->format].endian == LV_LITTLE_ENDIAN)
E
Eric Blake 已提交
849
            meta->capacity = virReadBufInt64LE(buf +
850
                                               fileTypeInfo[meta->format].sizeOffset);
E
Eric Blake 已提交
851 852
        else
            meta->capacity = virReadBufInt64BE(buf +
853
                                               fileTypeInfo[meta->format].sizeOffset);
854
        /* Avoid unlikely, but theoretically possible overflow */
E
Eric Blake 已提交
855
        if (meta->capacity > (ULLONG_MAX /
856
                              fileTypeInfo[meta->format].sizeMultiplier))
E
Eric Blake 已提交
857
            goto done;
858
        meta->capacity *= fileTypeInfo[meta->format].sizeMultiplier;
859
    }
860

861
    if (fileTypeInfo[meta->format].qcowCryptOffset != -1) {
862
        int crypt_format;
863

E
Eric Blake 已提交
864
        crypt_format = virReadBufInt32BE(buf +
865
                                         fileTypeInfo[meta->format].qcowCryptOffset);
866 867
        if (crypt_format && !meta->encryption &&
            VIR_ALLOC(meta->encryption) < 0)
868
            goto cleanup;
869
    }
870

871 872 873 874 875 876
    if (meta->format == VIR_STORAGE_FILE_LUKS) {
        /* By definition, this is encrypted */
        if (!meta->encryption && VIR_ALLOC(meta->encryption) < 0)
            goto cleanup;
    }

877
    VIR_FREE(meta->backingStoreRaw);
878 879
    if (fileTypeInfo[meta->format].getBackingStore != NULL) {
        int store = fileTypeInfo[meta->format].getBackingStore(&meta->backingStoreRaw,
880
                                                         backingFormat,
E
Eric Blake 已提交
881 882 883
                                                         buf, len);
        if (store == BACKING_STORE_INVALID)
            goto done;
884

E
Eric Blake 已提交
885 886
        if (store == BACKING_STORE_ERROR)
            goto cleanup;
887 888
    }

889 890
    if (fileTypeInfo[meta->format].getFeatures != NULL &&
        fileTypeInfo[meta->format].getFeatures(&meta->features, meta->format, buf, len) < 0)
891 892
        goto cleanup;

893
    if (meta->format == VIR_STORAGE_FILE_QCOW2 && meta->features &&
894 895 896
        VIR_STRDUP(meta->compat, "1.1") < 0)
        goto cleanup;

897
 done:
898
    ret = 0;
E
Eric Blake 已提交
899

900
 cleanup:
E
Eric Blake 已提交
901
    return ret;
902 903 904 905
}


/**
906
 * virStorageFileProbeFormat:
907
 *
908 909
 * Probe for the format of 'path', returning the detected
 * disk format.
910 911 912
 *
 * Callers are advised never to trust the returned 'format'
 * unless it is listed as VIR_STORAGE_FILE_RAW, since a
913
 * malicious guest can turn a raw file into any other non-raw
914 915 916 917 918
 * format at will.
 *
 * Best option: Don't use this function
 */
int
919
virStorageFileProbeFormat(const char *path, uid_t uid, gid_t gid)
920
{
921
    int fd;
922
    int ret = -1;
923
    struct stat sb;
924 925
    ssize_t len = VIR_STORAGE_MAX_HEADER;
    char *header = NULL;
926

927 928
    if ((fd = virFileOpenAs(path, O_RDONLY, 0, uid, gid, 0)) < 0) {
        virReportSystemError(-fd, _("Failed to open file '%s'"), path);
929 930 931
        return -1;
    }

932 933 934 935 936
    if (fstat(fd, &sb) < 0) {
        virReportSystemError(errno, _("cannot stat file '%s'"), path);
        goto cleanup;
    }

937 938
    /* No header to probe for directories */
    if (S_ISDIR(sb.st_mode)) {
939 940
        ret = VIR_STORAGE_FILE_DIR;
        goto cleanup;
941
    }
942 943 944 945 946 947

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

948
    if ((len = virFileReadHeaderFD(fd, len, &header)) < 0) {
949 950 951 952
        virReportSystemError(errno, _("cannot read header '%s'"), path);
        goto cleanup;
    }

953
    ret = virStorageFileProbeFormatFromBuf(path, header, len);
954

955
 cleanup:
956
    VIR_FREE(header);
957
    VIR_FORCE_CLOSE(fd);
958 959 960 961

    return ret;
}

962

963
static virStorageSourcePtr
964 965 966
virStorageFileMetadataNew(const char *path,
                          int format)
{
967
    virStorageSourcePtr ret = NULL;
968 969 970 971 972 973 974

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

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

975 976
    if (VIR_STRDUP(ret->path, path) < 0)
        goto error;
977 978 979 980

    return ret;

 error:
981
    virStorageSourceFree(ret);
982 983 984 985
    return NULL;
}


986 987 988 989 990
/**
 * virStorageFileGetMetadataFromBuf:
 * @path: name of file, for error messages
 * @buf: header bytes from @path
 * @len: length of @buf
991
 * @format: format of the storage file
992
 * @backingFormat: format of @backing
993
 *
994 995 996
 * 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.
997
 *
998 999 1000 1001 1002 1003 1004
 * 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.
1005
 *
1006
 * Caller MUST free the result after use via virStorageSourceFree.
1007
 */
1008
virStorageSourcePtr
1009 1010 1011
virStorageFileGetMetadataFromBuf(const char *path,
                                 char *buf,
                                 size_t len,
1012
                                 int format,
1013
                                 int *backingFormat)
1014
{
1015
    virStorageSourcePtr ret = NULL;
1016 1017 1018 1019
    int dummy;

    if (!backingFormat)
        backingFormat = &dummy;
1020

1021
    if (!(ret = virStorageFileMetadataNew(path, format)))
1022
        return NULL;
1023

1024 1025 1026 1027 1028
    if (virStorageFileGetMetadataInternal(ret, buf, len,
                                          backingFormat) < 0) {
        virStorageSourceFree(ret);
        return NULL;
    }
1029

1030
    return ret;
1031 1032 1033
}


1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
/**
 * 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)

1053
{
1054 1055
    virStorageSourcePtr ret = NULL;
    virStorageSourcePtr meta = NULL;
1056
    char *buf = NULL;
1057
    ssize_t len = VIR_STORAGE_MAX_HEADER;
1058
    struct stat sb;
1059
    int dummy;
1060

1061 1062
    if (!backingFormat)
        backingFormat = &dummy;
1063

1064
    *backingFormat = VIR_STORAGE_FILE_NONE;
1065

1066 1067
    if (fstat(fd, &sb) < 0) {
        virReportSystemError(errno,
1068 1069
                             _("cannot stat file '%s'"), path);
        return NULL;
1070 1071
    }

1072 1073 1074
    if (!(meta = virStorageFileMetadataNew(path, format)))
        return NULL;

1075
    if (S_ISDIR(sb.st_mode)) {
1076 1077
        /* No header to probe for directories, but also no backing file. Just
         * update the metadata.*/
1078 1079
        meta->type = VIR_STORAGE_TYPE_DIR;
        meta->format = VIR_STORAGE_FILE_DIR;
1080 1081
        ret = meta;
        meta = NULL;
1082 1083 1084 1085
        goto cleanup;
    }

    if (lseek(fd, 0, SEEK_SET) == (off_t)-1) {
1086
        virReportSystemError(errno, _("cannot seek to start of '%s'"), meta->path);
1087 1088 1089 1090
        goto cleanup;
    }

    if ((len = virFileReadHeaderFD(fd, len, &buf)) < 0) {
1091
        virReportSystemError(errno, _("cannot read header '%s'"), meta->path);
1092 1093 1094
        goto cleanup;
    }

1095 1096
    if (virStorageFileGetMetadataInternal(meta, buf, len, backingFormat) < 0)
        goto cleanup;
1097

1098 1099 1100 1101
    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;
1102

1103 1104
    ret = meta;
    meta = NULL;
1105

1106 1107 1108
 cleanup:
    virStorageSourceFree(meta);
    VIR_FREE(buf);
1109
    return ret;
1110 1111
}

1112

1113 1114 1115 1116 1117
/**
 * virStorageFileChainCheckBroken
 *
 * If CHAIN is broken, set *brokenFile to the broken file name,
 * otherwise set it to NULL. Caller MUST free *brokenFile after use.
1118 1119
 * Return 0 on success (including when brokenFile is set), negative on
 * error (allocation failure).
1120 1121
 */
int
1122
virStorageFileChainGetBroken(virStorageSourcePtr chain,
1123 1124
                             char **brokenFile)
{
1125
    virStorageSourcePtr tmp;
1126

1127 1128
    *brokenFile = NULL;

1129 1130 1131
    if (!chain)
        return 0;

1132
    for (tmp = chain; tmp; tmp = tmp->backingStore) {
1133 1134
        /* Break when we hit end of chain; report error if we detected
         * a missing backing file, infinite loop, or other error */
1135
        if (!tmp->backingStore && tmp->backingStoreRaw) {
1136 1137
            if (VIR_STRDUP(*brokenFile, tmp->backingStoreRaw) < 0)
                return -1;
1138

1139 1140 1141
           return 0;
        }
    }
1142

1143
    return 0;
1144 1145 1146
}


1147 1148 1149 1150 1151 1152
/**
 * virStorageFileResize:
 *
 * Change the capacity of the raw storage file at 'path'.
 */
int
1153 1154 1155 1156
virStorageFileResize(const char *path,
                     unsigned long long capacity,
                     unsigned long long orig_capacity,
                     bool pre_allocate)
1157
{
1158 1159
    int fd = -1;
    int ret = -1;
1160 1161 1162 1163 1164 1165
    int rc ATTRIBUTE_UNUSED;
    off_t offset ATTRIBUTE_UNUSED;
    off_t len ATTRIBUTE_UNUSED;

    offset = orig_capacity;
    len = capacity - orig_capacity;
1166 1167 1168 1169 1170 1171

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

1172
    if (pre_allocate) {
1173 1174 1175 1176
        if (safezero(fd, offset, len) != 0) {
            virReportSystemError(errno,
                                 _("Failed to pre-allocate space for "
                                   "file '%s'"), path);
1177 1178 1179 1180 1181 1182 1183 1184
            goto cleanup;
        }
    } else {
        if (ftruncate(fd, capacity) < 0) {
            virReportSystemError(errno,
                                 _("Failed to truncate file '%s'"), path);
            goto cleanup;
        }
1185 1186
    }

1187 1188 1189 1190 1191 1192 1193
    if (VIR_CLOSE(fd) < 0) {
        virReportSystemError(errno, _("Unable to save '%s'"), path);
        goto cleanup;
    }

    ret = 0;

1194
 cleanup:
1195 1196
    VIR_FORCE_CLOSE(fd);
    return ret;
1197 1198
}

1199 1200 1201 1202 1203 1204

int virStorageFileIsClusterFS(const char *path)
{
    /* These are coherent cluster filesystems known to be safe for
     * migration with cache != none
     */
1205 1206 1207
    return virFileIsSharedFSType(path,
                                 VIR_FILE_SHFS_GFS2 |
                                 VIR_FILE_SHFS_OCFS);
1208
}
1209 1210

#ifdef LVS
1211 1212
int virStorageFileGetLVMKey(const char *path,
                            char **key)
1213 1214 1215 1216 1217
{
    /*
     *  # lvs --noheadings --unbuffered --nosuffix --options "uuid" LVNAME
     *    06UgP5-2rhb-w3Bo-3mdR-WeoL-pytO-SAa2ky
     */
1218
    int status;
1219 1220 1221 1222 1223 1224
    virCommandPtr cmd = virCommandNewArgList(
        LVS,
        "--noheadings", "--unbuffered", "--nosuffix",
        "--options", "uuid", path,
        NULL
        );
1225 1226 1227
    int ret = -1;

    *key = NULL;
1228 1229

    /* Run the program and capture its output */
1230 1231
    virCommandSetOutputBuffer(cmd, key);
    if (virCommandRun(cmd, &status) < 0)
1232 1233
        goto cleanup;

1234 1235 1236 1237 1238 1239
    /* 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) {
1240
        char *nl;
1241
        char *tmp = *key;
1242 1243

        /* Find first non-space character */
1244
        while (*tmp && c_isspace(*tmp))
1245 1246
            tmp++;
        /* Kill leading spaces */
1247 1248
        if (tmp != *key)
            memmove(*key, tmp, strlen(tmp)+1);
1249 1250

        /* Kill trailing newline */
1251
        if ((nl = strchr(*key, '\n')))
1252 1253 1254
            *nl = '\0';
    }

1255
    ret = 0;
1256

1257
 cleanup:
1258 1259 1260
    if (*key && STREQ(*key, ""))
        VIR_FREE(*key);

1261 1262
    virCommandFree(cmd);

1263
    return ret;
1264 1265
}
#else
1266 1267
int virStorageFileGetLVMKey(const char *path,
                            char **key ATTRIBUTE_UNUSED)
1268 1269
{
    virReportSystemError(ENOSYS, _("Unable to get LVM key for %s"), path);
1270
    return -1;
1271 1272 1273
}
#endif

1274
#ifdef WITH_UDEV
1275 1276
int virStorageFileGetSCSIKey(const char *path,
                             char **key)
1277
{
1278
    int status;
1279 1280 1281 1282 1283 1284 1285
    virCommandPtr cmd = virCommandNewArgList(
        "/lib/udev/scsi_id",
        "--replace-whitespace",
        "--whitelisted",
        "--device", path,
        NULL
        );
1286 1287 1288
    int ret = -1;

    *key = NULL;
1289 1290

    /* Run the program and capture its output */
1291 1292
    virCommandSetOutputBuffer(cmd, key);
    if (virCommandRun(cmd, &status) < 0)
1293 1294
        goto cleanup;

1295 1296 1297 1298 1299 1300
    /* 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');
1301 1302 1303 1304
        if (nl)
            *nl = '\0';
    }

1305 1306
    ret = 0;

1307
 cleanup:
1308 1309 1310
    if (*key && STREQ(*key, ""))
        VIR_FREE(*key);

1311 1312
    virCommandFree(cmd);

1313
    return ret;
1314 1315
}
#else
1316 1317
int virStorageFileGetSCSIKey(const char *path,
                             char **key ATTRIBUTE_UNUSED)
1318 1319
{
    virReportSystemError(ENOSYS, _("Unable to get SCSI key for %s"), path);
1320
    return -1;
1321 1322
}
#endif
1323

1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338
int
virStorageFileParseChainIndex(const char *diskTarget,
                              const char *name,
                              unsigned int *chainIndex)
{
    char **strings = NULL;
    unsigned int idx = 0;
    char *suffix;
    int ret = 0;

    *chainIndex = 0;

    if (name && diskTarget)
        strings = virStringSplit(name, "[", 2);

1339
    if (virStringListLength((const char * const *)strings) != 2)
1340 1341
        goto cleanup;

E
Eric Blake 已提交
1342
    if (virStrToLong_uip(strings[1], &suffix, 10, &idx) < 0 ||
1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
        STRNEQ(suffix, "]"))
        goto cleanup;

    if (STRNEQ(diskTarget, strings[0])) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("requested target '%s' does not match target '%s'"),
                       strings[0], diskTarget);
        ret = -1;
        goto cleanup;
    }

    *chainIndex = idx;

 cleanup:
    virStringFreeList(strings);
    return ret;
}

E
Eric Blake 已提交
1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
/* 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.
1371
 */
1372
virStorageSourcePtr
1373
virStorageFileChainLookup(virStorageSourcePtr chain,
1374
                          virStorageSourcePtr startFrom,
1375
                          const char *name,
1376
                          unsigned int idx,
1377
                          virStorageSourcePtr *parent)
1378
{
1379
    virStorageSourcePtr prev;
1380
    const char *start = chain->path;
1381
    char *parentDir = NULL;
E
Eric Blake 已提交
1382
    bool nameIsFile = virStorageIsFile(name);
1383
    size_t i = 0;
1384 1385

    if (!parent)
1386
        parent = &prev;
1387
    *parent = NULL;
1388 1389

    if (startFrom) {
E
Eric Blake 已提交
1390
        while (chain && chain != startFrom->backingStore) {
1391 1392 1393
            chain = chain->backingStore;
            i++;
        }
1394 1395 1396 1397 1398 1399 1400 1401 1402

        if (idx && idx < i) {
            virReportError(VIR_ERR_INVALID_ARG,
                           _("requested backing store index %u is above '%s' "
                             "in chain for '%s'"),
                           idx, NULLSTR(startFrom->path), NULLSTR(start));
            return NULL;
        }

1403
        *parent = startFrom;
1404 1405
    }

E
Eric Blake 已提交
1406
    while (chain) {
1407
        if (!name && !idx) {
1408
            if (!chain->backingStore)
1409
                break;
1410 1411 1412 1413
        } else if (idx) {
            VIR_DEBUG("%zu: %s", i, chain->path);
            if (idx == i)
                break;
E
Eric Blake 已提交
1414
        } else {
1415 1416
            if (STREQ_NULLABLE(name, chain->relPath) ||
                STREQ(name, chain->path))
1417
                break;
1418 1419

            if (nameIsFile && virStorageSourceIsLocalStorage(chain)) {
1420 1421
                if (*parent && virStorageSourceIsLocalStorage(*parent))
                    parentDir = mdir_name((*parent)->path);
1422 1423 1424 1425 1426 1427
                else
                    ignore_value(VIR_STRDUP_QUIET(parentDir, "."));

                if (!parentDir) {
                    virReportOOMError();
                    goto error;
1428 1429
                }

E
Eric Blake 已提交
1430
                int result = virFileRelLinkPointsTo(parentDir, name,
1431
                                                    chain->path);
1432 1433

                VIR_FREE(parentDir);
1434

E
Eric Blake 已提交
1435 1436
                if (result < 0)
                    goto error;
1437

E
Eric Blake 已提交
1438 1439 1440
                if (result > 0)
                    break;
            }
1441
        }
1442
        *parent = chain;
1443
        chain = chain->backingStore;
1444
        i++;
1445
    }
1446

E
Eric Blake 已提交
1447
    if (!chain)
1448
        goto error;
1449

1450
    return chain;
1451

1452
 error:
1453 1454
    if (idx) {
        virReportError(VIR_ERR_INVALID_ARG,
1455 1456
                       _("could not find backing store index %u in chain "
                         "for '%s'"),
1457
                       idx, NULLSTR(start));
1458
    } else if (name) {
E
Eric Blake 已提交
1459 1460 1461
        if (startFrom)
            virReportError(VIR_ERR_INVALID_ARG,
                           _("could not find image '%s' beneath '%s' in "
1462 1463
                             "chain for '%s'"), name, NULLSTR(startFrom->path),
                           NULLSTR(start));
E
Eric Blake 已提交
1464 1465 1466
        else
            virReportError(VIR_ERR_INVALID_ARG,
                           _("could not find image '%s' in chain for '%s'"),
1467
                           name, NULLSTR(start));
1468
    } else {
1469 1470
        virReportError(VIR_ERR_INVALID_ARG,
                       _("could not find base image in chain for '%s'"),
1471
                       NULLSTR(start));
1472
    }
1473 1474 1475
    *parent = NULL;
    return NULL;
}
1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505


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

    VIR_FREE(def->name);
    VIR_FREE(def->port);
    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);
}


1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516
static void
virStoragePermsFree(virStoragePermsPtr def)
{
    if (!def)
        return;

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


1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548
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;

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

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

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

    return ret;

 error:
    virStorageNetHostDefFree(nhosts, ret);
    return NULL;
}
1549 1550


1551 1552 1553 1554 1555 1556 1557 1558
void
virStorageAuthDefFree(virStorageAuthDefPtr authdef)
{
    if (!authdef)
        return;

    VIR_FREE(authdef->username);
    VIR_FREE(authdef->secrettype);
1559
    virSecretLookupDefClear(&authdef->seclookupdef);
1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577
    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;
1578 1579 1580 1581

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

1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593
    return ret;

 error:
    virStorageAuthDefFree(ret);
    return NULL;
}


static virStorageAuthDefPtr
virStorageAuthDefParseXML(xmlXPathContextPtr ctxt)
{
    virStorageAuthDefPtr authdef = NULL;
1594
    xmlNodePtr secretnode = NULL;
1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622
    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);
    }

1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638
    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)
1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684
        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);
1685 1686
    virSecretLookupFormatSecret(buf, authdef->secrettype,
                                &authdef->seclookupdef);
1687 1688 1689 1690 1691 1692 1693
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</auth>\n");

    return 0;
}


1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708
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;
}


1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831
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;

    if (VIR_STRDUP(ret->label, src->label))
        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;

    ret->type = src->type;
    ret->protocol = src->protocol;
    ret->format = src->format;
    ret->capacity = src->capacity;
1832
    ret->allocation = src->allocation;
1833
    ret->has_allocation = src->has_allocation;
1834
    ret->physical = src->physical;
1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845
    ret->readonly = src->readonly;
    ret->shared = src->shared;

    /* 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 ||
1846
        VIR_STRDUP(ret->snapshot, src->snapshot) < 0 ||
1847
        VIR_STRDUP(ret->configFile, src->configFile) < 0 ||
1848 1849 1850
        VIR_STRDUP(ret->compat, src->compat) < 0)
        goto error;

1851 1852 1853 1854 1855 1856
    if (src->nhosts) {
        if (!(ret->hosts = virStorageNetHostDefCopy(src->nhosts, src->hosts)))
            goto error;

        ret->nhosts = src->nhosts;
    }
1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898

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


1899 1900 1901 1902
/**
 * virStorageSourceInitChainElement:
 * @newelem: New backing chain element disk source
 * @old: Existing top level disk source
1903
 * @transferLabels: Transfer security lables.
1904 1905 1906 1907 1908
 *
 * 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.
 *
1909 1910
 * 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.
1911 1912 1913 1914 1915 1916
 *
 * Returns 0 on success, -1 on error.
 */
int
virStorageSourceInitChainElement(virStorageSourcePtr newelem,
                                 virStorageSourcePtr old,
1917
                                 bool transferLabels)
1918 1919 1920
{
    int ret = -1;

1921 1922
    if (transferLabels &&
        !newelem->seclabels &&
1923 1924 1925
        virStorageSourceSeclabelsCopy(newelem, old) < 0)
        goto cleanup;

1926 1927 1928 1929
    if (!newelem->driverName &&
        VIR_STRDUP(newelem->driverName, old->driverName) < 0)
        goto cleanup;

1930 1931 1932 1933 1934 1935 1936 1937 1938 1939
    newelem->shared = old->shared;
    newelem->readonly = old->readonly;

    ret = 0;

 cleanup:
    return ret;
}


1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952
void
virStorageSourcePoolDefFree(virStorageSourcePoolDefPtr def)
{
    if (!def)
        return;

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

    VIR_FREE(def);
}


1953
int
1954
virStorageSourceGetActualType(const virStorageSource *def)
1955 1956 1957 1958 1959 1960 1961 1962
{
    if (def->type == VIR_STORAGE_TYPE_VOLUME && def->srcpool)
        return def->srcpool->actualtype;

    return def->type;
}


1963 1964 1965
bool
virStorageSourceIsLocalStorage(virStorageSourcePtr src)
{
1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981
    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;
1982 1983 1984
}


1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001
/**
 * 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;

2002 2003 2004 2005
    if (src->type == VIR_STORAGE_TYPE_NETWORK &&
        src->protocol == VIR_STORAGE_NET_PROTOCOL_NONE)
        return true;

2006 2007 2008 2009
    return false;
}


2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023
/**
 * 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;
}


2024
/**
2025
 * virStorageSourceBackingStoreClear:
2026 2027 2028 2029 2030 2031
 *
 * @src: disk source to clear
 *
 * Clears information about backing store of the current storage file.
 */
void
2032
virStorageSourceBackingStoreClear(virStorageSourcePtr def)
2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045
{
    if (!def)
        return;

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

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


2046 2047 2048 2049 2050 2051 2052
void
virStorageSourceClear(virStorageSourcePtr def)
{
    if (!def)
        return;

    VIR_FREE(def->path);
2053
    VIR_FREE(def->volume);
2054 2055
    VIR_FREE(def->snapshot);
    VIR_FREE(def->configFile);
2056 2057
    virStorageSourcePoolDefFree(def->srcpool);
    VIR_FREE(def->driverName);
E
Eric Blake 已提交
2058 2059
    virBitmapFree(def->features);
    VIR_FREE(def->compat);
2060
    virStorageEncryptionFree(def->encryption);
2061
    virStorageSourceSeclabelsClear(def);
2062
    virStoragePermsFree(def->perms);
E
Eric Blake 已提交
2063
    VIR_FREE(def->timestamps);
2064 2065

    virStorageNetHostDefFree(def->nhosts, def->hosts);
2066
    virStorageAuthDefFree(def->auth);
2067

2068
    virStorageSourceBackingStoreClear(def);
2069
}
2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080


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

    virStorageSourceClear(def);
    VIR_FREE(def);
}
2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092


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

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

2093 2094 2095 2096
    /* store relative name */
    if (VIR_STRDUP(ret->relPath, parent->backingStoreRaw) < 0)
        goto error;

2097 2098
    if (!(dirname = mdir_name(parent->path))) {
        virReportOOMError();
2099
        goto error;
2100
    }
2101

2102 2103
    if (STRNEQ(dirname, "/")) {
        if (virAsprintf(&ret->path, "%s/%s", dirname, rel) < 0)
2104 2105
            goto error;
    } else {
2106 2107 2108 2109 2110
        if (virAsprintf(&ret->path, "/%s", rel) < 0)
            goto error;
    }

    if (virStorageSourceGetActualType(parent) == VIR_STORAGE_TYPE_NETWORK) {
2111 2112 2113 2114
        ret->type = VIR_STORAGE_TYPE_NETWORK;

        /* copy the host network part */
        ret->protocol = parent->protocol;
2115 2116 2117 2118 2119 2120 2121
        if (parent->nhosts) {
            if (!(ret->hosts = virStorageNetHostDefCopy(parent->nhosts,
                                                        parent->hosts)))
                goto error;

            ret->nhosts = parent->nhosts;
        }
2122 2123 2124

        if (VIR_STRDUP(ret->volume, parent->volume) < 0)
            goto error;
2125 2126 2127
    } else {
        /* set the type to _FILE, the caller shall update it to the actual type */
        ret->type = VIR_STORAGE_TYPE_FILE;
2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155
    }

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

2156 2157 2158 2159 2160
    if (VIR_ALLOC(src->hosts) < 0)
        goto cleanup;

    src->nhosts = 1;

2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188
    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 */
2189 2190
    if (uri->path &&
        VIR_STRDUP(src->path,
2191 2192 2193 2194 2195
                   *uri->path == '/' ? uri->path + 1 : uri->path) < 0)
        goto cleanup;

    if (src->protocol == VIR_STORAGE_NET_PROTOCOL_GLUSTER) {
        char *tmp;
2196 2197 2198 2199 2200 2201 2202

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

2203 2204
        if (!(tmp = strchr(src->path, '/')) ||
            tmp == src->path) {
2205
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235
                           _("missing volume name or file name in "
                             "gluster source path '%s'"), src->path);
            goto cleanup;
        }

        src->volume = src->path;

        if (VIR_STRDUP(src->path, tmp) < 0)
            goto cleanup;

        tmp[0] = '\0';
    }

    if (uri->port > 0) {
        if (virAsprintf(&src->hosts->port, "%d", uri->port) < 0)
            goto cleanup;
    }

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

    ret = 0;

 cleanup:
    virURIFree(uri);
    virStringFreeList(scheme);
    return ret;
}


2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304
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;
        if (VIR_STRDUP(src->hosts[src->nhosts - 1].port, port) < 0)
            goto error;
    }

    parts = virStringSplit(hostport, "\\:", 0);
    if (!parts)
        goto error;
    src->hosts[src->nhosts-1].name = virStringJoin((const char **)parts, ":");
    virStringFreeList(parts);
    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].port);
    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';
    }

2305 2306 2307 2308 2309 2310 2311
    /* snapshot name */
    if ((p = strchr(src->path, '@'))) {
        if (VIR_STRDUP(src->snapshot, p + 1) < 0)
            goto error;
        *p = '\0';
    }

2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372
    /* 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,
                           virStorageAuthTypeToString(VIR_STORAGE_AUTH_TYPE_CEPHX)) < 0)
                goto error;
            src->auth = authdef;
            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;
            }
        }

2373 2374 2375 2376
        if (STRPREFIX(p, "conf=") &&
            VIR_STRDUP(src->configFile, p + strlen("conf=")) < 0)
            goto error;

2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388
        p = next;
    }
    VIR_FREE(options);
    return 0;

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


2389
static int
2390 2391
virStorageSourceParseNBDColonString(const char *nbdstr,
                                    virStorageSourcePtr src)
2392 2393 2394 2395
{
    char **backing = NULL;
    int ret = -1;

2396 2397 2398 2399 2400 2401
    if (!(backing = virStringSplit(nbdstr, ":", 0)))
        goto cleanup;

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

    if (VIR_ALLOC_N(src->hosts, 1) < 0)
2402 2403
        goto cleanup;

2404 2405 2406 2407 2408 2409 2410 2411
    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]) {
2412
        virReportError(VIR_ERR_INTERNAL_ERROR,
2413 2414
                       _("missing remote information in '%s' for protocol nbd"),
                       nbdstr);
2415
        goto cleanup;
2416 2417 2418 2419 2420 2421 2422
    } 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;
        }
2423

2424
        if (VIR_STRDUP(src->hosts->socket, backing[2]) < 0)
2425 2426
            goto cleanup;

2427
   } else {
2428 2429
        if (!backing[1]) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
2430 2431
                           _("missing host name in nbd string '%s'"),
                           nbdstr);
2432
            goto cleanup;
2433
        }
2434

2435 2436
        if (VIR_STRDUP(src->hosts->name, backing[1]) < 0)
            goto cleanup;
2437

2438 2439 2440 2441 2442 2443
        if (!backing[2]) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("missing port in nbd string '%s'"),
                           nbdstr);
            goto cleanup;
        }
2444

2445 2446 2447
        if (VIR_STRDUP(src->hosts->port, backing[2]) < 0)
            goto cleanup;
    }
2448

2449 2450 2451 2452
    if (backing[3] && STRPREFIX(backing[3], "exportname=")) {
        if (VIR_STRDUP(src->path, backing[3] + strlen("exportname=")) < 0)
            goto cleanup;
    }
2453

2454
    ret = 0;
2455

2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492
 cleanup:
    virStringFreeList(backing);

    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;
2493 2494

    case VIR_STORAGE_NET_PROTOCOL_RBD:
2495 2496 2497 2498 2499
        if (virStorageSourceParseRBDColonString(path, src) < 0)
            goto cleanup;
        break;

    case VIR_STORAGE_NET_PROTOCOL_SHEEPDOG:
2500 2501 2502 2503
    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"),
2504
                       protocol);
2505 2506 2507 2508 2509 2510 2511 2512 2513
        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:
2514
    case VIR_STORAGE_NET_PROTOCOL_SSH:
2515 2516
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("malformed backing store path for protocol %s"),
2517
                       protocol);
2518 2519 2520 2521 2522 2523
        goto cleanup;
    }

    ret = 0;

 cleanup:
2524
    VIR_FREE(protocol);
2525 2526 2527 2528
    return ret;
}


2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550
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;
}


2551 2552 2553 2554 2555 2556 2557 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 2588
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;

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

    return virStorageSourceParseBackingJSONUriStr(src, uri, protocol);
}


2589 2590 2591 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 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695
static int
virStorageSourceParseBackingJSONGlusterHost(virStorageNetHostDefPtr host,
                                            virJSONValuePtr json)
{
    const char *type = virJSONValueObjectGetString(json, "type");
    const char *hostname = virJSONValueObjectGetString(json, "host");
    const char *port = virJSONValueObjectGetString(json, "port");
    const char *socket = virJSONValueObjectGetString(json, "socket");
    int transport;

    if ((transport = virStorageNetHostTransportTypeFromString(type)) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unknown backing store transport protocol '%s'"), type);
        return -1;
    }

    host->transport = transport;

    switch ((virStorageNetHostTransport) transport) {
    case VIR_STORAGE_NET_HOST_TRANS_TCP:
        if (!hostname) {
            virReportError(VIR_ERR_INVALID_ARG, "%s",
                           _("missing hostname for tcp backing server in "
                             "JSON backing definition for gluster volume"));
            return -1;
        }

        if (VIR_STRDUP(host->name, hostname) < 0 ||
            VIR_STRDUP(host->port, port) < 0)
            return -1;
        break;

    case VIR_STORAGE_NET_HOST_TRANS_UNIX:
        if (!socket) {
            virReportError(VIR_ERR_INVALID_ARG, "%s",
                           _("missing socket path for udp backing server in "
                             "JSON backing definition for gluster volume"));
            return -1;
        }


        if (VIR_STRDUP(host->socket, socket) < 0)
            return -1;
        break;

    case VIR_STORAGE_NET_HOST_TRANS_RDMA:
    case VIR_STORAGE_NET_HOST_TRANS_LAST:
        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;
    }

    if (VIR_STRDUP(src->volume, volume) < 0 ||
        virAsprintf(&src->path, "/%s", path) < 0)
        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"));
    }

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

    for (i = 0; i < nservers; i++) {
        if (virStorageSourceParseBackingJSONGlusterHost(src->hosts + i,
                                                        virJSONValueArrayGet(server, i)) < 0)
            return -1;
    }

    return 0;
}


2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715
static int
virStorageSourceParseBackingJSONiSCSI(virStorageSourcePtr src,
                                      virJSONValuePtr json,
                                      int opaque ATTRIBUTE_UNUSED)
{
    const char *uri;

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

    /* iSCSI currently supports only URI syntax passed in as filename */
    virReportError(VIR_ERR_INVALID_ARG, "%s",
                   _("missing iSCSI URI in JSON backing volume definition"));

    return -1;
}


2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759
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");

    if (!path && !host) {
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("missing path or host of NBD server in JSON backing "
                         "volume definition"));
        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;

    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;

        if (VIR_STRDUP(src->hosts[0].port, port) < 0)
            return -1;
    }

    return 0;
}


2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783
static int
virStorageSourceParseBackingJSONSheepdog(virStorageSourcePtr src,
                                         virJSONValuePtr json,
                                         int opaque ATTRIBUTE_UNUSED)
{
    const char *filename;

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

    /* Sheepdog currently supports only URI and legacy syntax passed in as filename */
    virReportError(VIR_ERR_INVALID_ARG, "%s",
                   _("missing sheepdog URI in JSON backing volume definition"));

    return -1;
}


2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820
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");

    if (!host || !path) {
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("missing host or path of SSH JSON backing "
                         "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;

    src->hosts[0].transport = VIR_STORAGE_NET_HOST_TRANS_TCP;
    if (VIR_STRDUP(src->hosts[0].name, host) < 0)
        return -1;

    if (VIR_STRDUP(src->hosts[0].port, port) < 0)
        return -1;

    return 0;
}


2821 2822 2823 2824 2825 2826 2827 2828
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},
2829 2830
    {"host_device", virStorageSourceParseBackingJSONPath, VIR_STORAGE_TYPE_BLOCK},
    {"host_cdrom", virStorageSourceParseBackingJSONPath, VIR_STORAGE_TYPE_BLOCK},
2831 2832 2833 2834 2835
    {"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},
2836
    {"gluster", virStorageSourceParseBackingJSONGluster, 0},
2837
    {"iscsi", virStorageSourceParseBackingJSONiSCSI, 0},
2838
    {"nbd", virStorageSourceParseBackingJSONNbd, 0},
2839
    {"sheepdog", virStorageSourceParseBackingJSONSheepdog, 0},
2840
    {"ssh", virStorageSourceParseBackingJSONSSH, 0},
2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 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 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952
};


static int
virStorageSourceParseBackingJSONDeflattenWorker(const char *key,
                                                const virJSONValue *value,
                                                void *opaque)
{
    virJSONValuePtr retobj = opaque;
    virJSONValuePtr newval = NULL;
    const char *newkey;

    if (!(newkey = STRSKIP(key, "file."))) {
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("JSON backing file syntax is neither nested nor "
                         "flattened"));
        return -1;
    }

    if (!(newval = virJSONValueCopy(value)))
        return -1;

    if (virJSONValueObjectAppend(retobj, newkey, newval) < 0) {
        virJSONValueFree(newval);
        return -1;
    }

    return 0;
}


/**
 * virStorageSourceParseBackingJSONDeflatten:
 *
 * The json: pseudo-protocol syntax in qemu allows multiple approaches to
 * describe nesting of the values. This is due to the lax handling of the string
 * in qemu and the fact that internally qemu is flattening the values using '.'.
 *
 * This allows to specify nested json strings either using nested json objects
 * or prefixing object members with the parent object name followed by the dot.
 *
 * This function will attempt to reverse the process and provide a nested json
 * hierarchy so that the parsers can be kept simple and we still can use the
 * weird syntax some users might use.
 *
 * Currently this function will flatten out just the 'file.' prefix into a new
 * tree. Any other syntax will be rejected.
 */
static virJSONValuePtr
virStorageSourceParseBackingJSONDeflatten(virJSONValuePtr json)
{
    virJSONValuePtr ret;

    if (!(ret = virJSONValueNewObject()))
        return NULL;

    if (virJSONValueObjectForeachKeyValue(json,
                                          virStorageSourceParseBackingJSONDeflattenWorker,
                                          ret) < 0) {
        virJSONValueFree(ret);
        return NULL;
    }

    return ret;
}


static int
virStorageSourceParseBackingJSON(virStorageSourcePtr src,
                                 const char *json)
{
    virJSONValuePtr root = NULL;
    virJSONValuePtr fixedroot = NULL;
    virJSONValuePtr file;
    const char *drvname;
    size_t i;
    int ret = -1;

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

    if (!(file = virJSONValueObjectGetObject(root, "file"))) {
        if (!(fixedroot = virStorageSourceParseBackingJSONDeflatten(root)))
            goto cleanup;

        file = fixedroot;
    }

    if (!(drvname = virJSONValueObjectGetString(file, "driver"))) {
        virReportError(VIR_ERR_INVALID_ARG, _("JSON backing volume defintion "
                                              "'%s' lacks driver name"), json);
        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:
    virJSONValueFree(root);
    virJSONValueFree(fixedroot);
    return ret;
}


2953
virStorageSourcePtr
2954 2955
virStorageSourceNewFromBackingAbsolute(const char *path)
{
2956
    const char *json;
2957
    virStorageSourcePtr ret;
2958
    int rc;
2959 2960 2961 2962 2963 2964 2965

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

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

2966 2967
        if (VIR_STRDUP(ret->path, path) < 0)
            goto error;
2968 2969 2970 2971
    } else {
        ret->type = VIR_STORAGE_TYPE_NETWORK;

        /* handle URI formatted backing stores */
2972 2973 2974 2975 2976 2977 2978 2979 2980
        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;
2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014
    }

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

        /* copy parent's labelling and other top level stuff */
3017
        if (virStorageSourceInitChainElement(ret, parent, true) < 0)
3018
            goto error;
3019 3020 3021
    }

    return ret;
3022 3023 3024 3025

 error:
    virStorageSourceFree(ret);
    return NULL;
3026
}
3027 3028


3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067
/**
 * @src: disk source definiton structure
 * @report: report libvirt errors if set to true
 *
 * Updates src->physical for block devices since qemu doesn't report the current
 * size correctly for them. Returns 0 on success, -1 on error.
 */
int
virStorageSourceUpdateBlockPhysicalSize(virStorageSourcePtr src,
                                        bool report)
{
    int fd = -1;
    off_t end;
    int ret = -1;

    if (virStorageSourceGetActualType(src) != VIR_STORAGE_TYPE_BLOCK)
        return 0;

    if ((fd = open(src->path, O_RDONLY)) < 0) {
        if (report)
            virReportSystemError(errno, _("failed to open block device '%s'"),
                                 src->path);
        return -1;
    }

    if ((end = lseek(fd, 0, SEEK_END)) == (off_t) -1) {
        if (report)
            virReportSystemError(errno,
                                 _("failed to seek to end of '%s'"), src->path);
    } else {
        src->physical = end;
        ret = 0;
    }

    VIR_FORCE_CLOSE(fd);
    return ret;
}


3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090
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);
    }

3091
    if (virBufferCheckError(&buf) < 0)
3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280
        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:
    virStringFreeListCount(tmp, ntmp);
    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);
    virStringFreeListCount(components, ncomponents);
    VIR_FREE(linkpath);
    VIR_FREE(currentpath);

    return ret;
}
3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299


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

3300
    virFileRemoveLastComponent(ret);
3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326

    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;

    for (next = top; next; next = next->backingStore) {
3327
        if (!next->relPath) {
3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362
            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;
}
3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391


/*
 * 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:
    virStringFreeList(version);
    return ret;
}