virstoragefile.c 62.0 KB
Newer Older
1
/*
2
 * virstoragefile.c: file utility functions for FS storage backend
3
 *
4
 * Copyright (C) 2007-2014 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17
 * Copyright (C) 2007-2008 Daniel P. Berrange
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with this library.  If not, see
O
Osier Yang 已提交
19
 * <http://www.gnu.org/licenses/>.
20 21 22 23 24
 *
 * 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
#include "virerror.h"
33
#include "virlog.h"
E
Eric Blake 已提交
34
#include "virfile.h"
35
#include "c-ctype.h"
36
#include "vircommand.h"
37
#include "virhash.h"
E
Eric Blake 已提交
38
#include "virendian.h"
39 40
#include "virstring.h"
#include "virutil.h"
41 42
#include "viruri.h"
#include "dirname.h"
43
#include "virbuffer.h"
44 45 46
#if HAVE_SYS_SYSCALL_H
# include <sys/syscall.h>
#endif
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",
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 87
              "nbd",
              "rbd",
              "sheepdog",
              "gluster",
              "iscsi",
              "http",
              "https",
              "ftp",
              "ftps",
              "tftp")
88 89 90 91 92 93

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

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

100 101 102 103 104 105 106 107 108 109 110
enum lv_endian {
    LV_LITTLE_ENDIAN = 1, /* 1234 */
    LV_BIG_ENDIAN         /* 4321 */
};

enum {
    BACKING_STORE_OK,
    BACKING_STORE_INVALID,
    BACKING_STORE_ERROR,
};

111 112
#define FILE_TYPE_VERSIONS_LAST 2

113 114
/* Either 'magic' or 'extension' *must* be provided */
struct FileTypeInfo {
115
    int magicOffset;    /* Byte offset of the magic */
116 117 118 119 120 121
    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 */
    int versionOffset;    /* Byte offset from start of file
                           * where we find version number,
122 123
                           * -1 to always fail the version test,
                           * -2 to always pass the version test */
124 125
    int versionNumbers[FILE_TYPE_VERSIONS_LAST];
                          /* Version numbers to validate. Zeroes are ignored. */
126 127 128 129 130 131 132 133 134 135 136
    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 */
137
    int (*getBackingStore)(char **res, int *format,
E
Eric Blake 已提交
138
                           const char *buf, size_t buf_size);
139
    int (*getFeatures)(virBitmapPtr *features, int format,
E
Eric Blake 已提交
140
                       char *buf, ssize_t len);
141 142
};

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

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

#define QCOW1_HDR_CRYPT (QCOWX_HDR_IMAGE_SIZE+8+1+1)
#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

170 171 172 173 174 175 176
#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)

177
#define QED_HDR_FEATURES_OFFSET (4+4+4+4)
178 179
#define QED_HDR_IMAGE_SIZE (QED_HDR_FEATURES_OFFSET+8+8+8+8)
#define QED_HDR_BACKING_FILE_OFFSET (QED_HDR_IMAGE_SIZE+8)
180 181 182
#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 已提交
183

184 185

static struct FileTypeInfo const fileTypeInfo[] = {
186
    [VIR_STORAGE_FILE_NONE] = { 0, NULL, NULL, LV_LITTLE_ENDIAN,
187
                                -1, {0}, 0, 0, 0, 0, NULL, NULL },
188
    [VIR_STORAGE_FILE_RAW] = { 0, NULL, NULL, LV_LITTLE_ENDIAN,
189
                               -1, {0}, 0, 0, 0, 0, NULL, NULL },
190
    [VIR_STORAGE_FILE_DIR] = { 0, NULL, NULL, LV_LITTLE_ENDIAN,
191
                               -1, {0}, 0, 0, 0, 0, NULL, NULL },
192
    [VIR_STORAGE_FILE_BOCHS] = {
193 194
        /*"Bochs Virtual HD Image", */ /* Untested */
        0, NULL, NULL,
195 196
        LV_LITTLE_ENDIAN, 64, {0x20000},
        32+16+16+4+4+4+4+4, 8, 1, -1, NULL, NULL
197 198
    },
    [VIR_STORAGE_FILE_CLOOP] = {
199 200 201 202 203
        /* #!/bin/sh
           #V2.0 Format
           modprobe cloop file=$0 && mount -r -t iso9660 /dev/cloop $1
        */ /* Untested */
        0, NULL, NULL,
204 205
        LV_LITTLE_ENDIAN, -1, {0},
        -1, 0, 0, -1, NULL, NULL
206 207
    },
    [VIR_STORAGE_FILE_DMG] = {
208 209 210 211
        /* 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",
212 213
        0, -1, {0},
        -1, 0, 0, -1, NULL, NULL
214 215
    },
    [VIR_STORAGE_FILE_ISO] = {
216
        32769, "CD001", ".iso",
217 218
        LV_LITTLE_ENDIAN, -2, {0},
        -1, 0, 0, -1, NULL, NULL
219
    },
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
    [VIR_STORAGE_FILE_VPC] = {
        0, "conectix", NULL,
        LV_BIG_ENDIAN, 12, {0x10000},
        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",
        LV_LITTLE_ENDIAN, 68, {0x00010001},
        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,
                               -1, {0}, 0, 0, 0, 0, NULL, NULL },
    [VIR_STORAGE_FILE_VHD] = { 0, NULL, NULL, LV_LITTLE_ENDIAN,
                               -1, {0}, 0, 0, 0, 0, NULL, NULL },
236 237
    [VIR_STORAGE_FILE_PLOOP] = { 0, NULL, NULL, LV_LITTLE_ENDIAN,
                               -1, {0}, 0, 0, 0, 0, NULL, NULL },
238 239 240 241 242 243 244

    /* All formats with a backing store probe below here */
    [VIR_STORAGE_FILE_COW] = {
        0, "OOOM", NULL,
        LV_BIG_ENDIAN, 4, {2},
        4+4+1024+4, 8, 1, -1, cowGetBackingStore, NULL
    },
245
    [VIR_STORAGE_FILE_QCOW] = {
246
        0, "QFI", NULL,
247 248
        LV_BIG_ENDIAN, 4, {1},
        QCOWX_HDR_IMAGE_SIZE, 8, 1, QCOW1_HDR_CRYPT, qcow1GetBackingStore, NULL
249 250
    },
    [VIR_STORAGE_FILE_QCOW2] = {
251
        0, "QFI", NULL,
252
        LV_BIG_ENDIAN, 4, {2, 3},
253
        QCOWX_HDR_IMAGE_SIZE, 8, 1, QCOW2_HDR_CRYPT, qcow2GetBackingStore,
254
        qcow2GetFeatures
255
    },
A
Adam Litke 已提交
256 257
    [VIR_STORAGE_FILE_QED] = {
        /* http://wiki.qemu.org/Features/QED */
258
        0, "QED", NULL,
259 260
        LV_LITTLE_ENDIAN, -2, {0},
        QED_HDR_IMAGE_SIZE, 8, 1, -1, qedGetBackingStore, NULL
A
Adam Litke 已提交
261
    },
262
    [VIR_STORAGE_FILE_VMDK] = {
263
        0, "KDMV", NULL,
264
        LV_LITTLE_ENDIAN, 4, {1, 2},
265
        4+4+4, 8, 512, -1, vmdk4GetBackingStore, NULL
266
    },
267
};
268
verify(ARRAY_CARDINALITY(fileTypeInfo) == VIR_STORAGE_FILE_LAST);
269

270 271 272 273 274 275 276 277 278 279 280 281 282 283
/* 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);

284
static int
285
cowGetBackingStore(char **res,
286
                   int *format,
E
Eric Blake 已提交
287
                   const char *buf,
288 289 290 291
                   size_t buf_size)
{
#define COW_FILENAME_MAXLEN 1024
    *res = NULL;
292 293
    *format = VIR_STORAGE_FILE_AUTO;

294 295
    if (buf_size < 4+4+ COW_FILENAME_MAXLEN)
        return BACKING_STORE_INVALID;
E
Eric Blake 已提交
296 297
    if (buf[4+4] == '\0') { /* cow_header_v2.backing_file[0] */
        *format = VIR_STORAGE_FILE_NONE;
298
        return BACKING_STORE_OK;
E
Eric Blake 已提交
299
    }
300

301
    if (VIR_STRNDUP(*res, (const char*)buf + 4 + 4, COW_FILENAME_MAXLEN) < 0)
302 303 304 305
        return BACKING_STORE_ERROR;
    return BACKING_STORE_OK;
}

306 307 308

static int
qcow2GetBackingStoreFormat(int *format,
E
Eric Blake 已提交
309
                           const char *buf,
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
                           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 已提交
328 329
        unsigned int magic = virReadBufInt32BE(buf + offset);
        unsigned int len = virReadBufInt32BE(buf + offset + 4);
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347

        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 已提交
348 349
            if (*format <= VIR_STORAGE_FILE_NONE)
                return -1;
350 351 352 353 354
        }

        offset += len;
    }

355
 done:
356 357 358 359 360

    return 0;
}


361
static int
362
qcowXGetBackingStore(char **res,
363
                     int *format,
E
Eric Blake 已提交
364
                     const char *buf,
365 366
                     size_t buf_size,
                     bool isQCow2)
367 368
{
    unsigned long long offset;
369
    unsigned int size;
370 371
    unsigned long long start;
    int version;
372 373

    *res = NULL;
374 375 376 377
    if (format)
        *format = VIR_STORAGE_FILE_AUTO;

    if (buf_size < QCOWX_HDR_BACKING_FILE_OFFSET+8+4)
378
        return BACKING_STORE_INVALID;
E
Eric Blake 已提交
379
    offset = virReadBufInt64BE(buf + QCOWX_HDR_BACKING_FILE_OFFSET);
380 381
    if (offset > buf_size)
        return BACKING_STORE_INVALID;
E
Eric Blake 已提交
382
    size = virReadBufInt32BE(buf + QCOWX_HDR_BACKING_FILE_SIZE);
E
Eric Blake 已提交
383 384 385
    if (size == 0) {
        if (format)
            *format = VIR_STORAGE_FILE_NONE;
386
        return BACKING_STORE_OK;
E
Eric Blake 已提交
387
    }
388 389 390 391
    if (offset + size > buf_size || offset + size < offset)
        return BACKING_STORE_INVALID;
    if (size + 1 == 0)
        return BACKING_STORE_INVALID;
392
    if (VIR_ALLOC_N(*res, size + 1) < 0)
393 394 395
        return BACKING_STORE_ERROR;
    memcpy(*res, buf + offset, size);
    (*res)[size] = '\0';
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419

    /*
     * 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)
420 421 422
     *
     * for qcow2 v3 images, the length of the header
     * is stored at QCOW2v3_HDR_SIZE
423
     */
424 425 426 427 428 429 430 431 432 433
    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;
    }
434

435 436 437 438
    return BACKING_STORE_OK;
}


439 440 441
static int
qcow1GetBackingStore(char **res,
                     int *format,
E
Eric Blake 已提交
442
                     const char *buf,
443 444
                     size_t buf_size)
{
E
Eric Blake 已提交
445 446
    int ret;

447 448 449
    /* QCow1 doesn't have the extensions capability
     * used to store backing format */
    *format = VIR_STORAGE_FILE_AUTO;
E
Eric Blake 已提交
450 451 452 453
    ret = qcowXGetBackingStore(res, NULL, buf, buf_size, false);
    if (ret == 0 && *buf == '\0')
        *format = VIR_STORAGE_FILE_NONE;
    return ret;
454 455 456 457 458
}

static int
qcow2GetBackingStore(char **res,
                     int *format,
E
Eric Blake 已提交
459
                     const char *buf,
460 461 462 463 464 465
                     size_t buf_size)
{
    return qcowXGetBackingStore(res, format, buf, buf_size, true);
}


466
static int
467
vmdk4GetBackingStore(char **res,
468
                     int *format,
E
Eric Blake 已提交
469
                     const char *buf,
470 471 472
                     size_t buf_size)
{
    static const char prefix[] = "parentFileNameHint=\"";
473
    char *desc, *start, *end;
474
    size_t len;
475 476
    int ret = BACKING_STORE_ERROR;

477
    if (VIR_ALLOC_N(desc, VIR_STORAGE_MAX_HEADER) < 0)
478
        goto cleanup;
479 480

    *res = NULL;
481 482 483 484 485 486 487 488
    /*
     * Technically this should have been VMDK, since
     * VMDK spec / VMWare impl only support VMDK backed
     * by VMDK. QEMU isn't following this though and
     * does probing on VMDK backing files, hence we set
     * AUTO
     */
    *format = VIR_STORAGE_FILE_AUTO;
489

490 491 492 493
    if (buf_size <= 0x200) {
        ret = BACKING_STORE_INVALID;
        goto cleanup;
    }
494
    len = buf_size - 0x200;
495 496
    if (len > VIR_STORAGE_MAX_HEADER)
        len = VIR_STORAGE_MAX_HEADER;
497 498 499
    memcpy(desc, buf + 0x200, len);
    desc[len] = '\0';
    start = strstr(desc, prefix);
500
    if (start == NULL) {
E
Eric Blake 已提交
501
        *format = VIR_STORAGE_FILE_NONE;
502 503 504
        ret = BACKING_STORE_OK;
        goto cleanup;
    }
505 506
    start += strlen(prefix);
    end = strchr(start, '"');
507 508 509 510 511
    if (end == NULL) {
        ret = BACKING_STORE_INVALID;
        goto cleanup;
    }
    if (end == start) {
E
Eric Blake 已提交
512
        *format = VIR_STORAGE_FILE_NONE;
513 514 515
        ret = BACKING_STORE_OK;
        goto cleanup;
    }
516
    *end = '\0';
517
    if (VIR_STRDUP(*res, start) < 0)
518 519 520 521
        goto cleanup;

    ret = BACKING_STORE_OK;

522
 cleanup:
523 524
    VIR_FREE(desc);
    return ret;
525 526
}

527 528 529
static int
qedGetBackingStore(char **res,
                   int *format,
E
Eric Blake 已提交
530
                   const char *buf,
531 532 533 534 535 536 537 538 539
                   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 已提交
540
    flags = virReadBufInt64LE(buf + QED_HDR_FEATURES_OFFSET);
E
Eric Blake 已提交
541 542
    if (!(flags & QED_F_BACKING_FILE)) {
        *format = VIR_STORAGE_FILE_NONE;
543
        return BACKING_STORE_OK;
E
Eric Blake 已提交
544
    }
545 546 547 548

    /* Parse the backing file */
    if (buf_size < QED_HDR_BACKING_FILE_OFFSET+8)
        return BACKING_STORE_INVALID;
E
Eric Blake 已提交
549
    offset = virReadBufInt32LE(buf + QED_HDR_BACKING_FILE_OFFSET);
550 551
    if (offset > buf_size)
        return BACKING_STORE_INVALID;
E
Eric Blake 已提交
552
    size = virReadBufInt32LE(buf + QED_HDR_BACKING_FILE_SIZE);
553 554 555 556
    if (size == 0)
        return BACKING_STORE_OK;
    if (offset + size > buf_size || offset + size < offset)
        return BACKING_STORE_INVALID;
557
    if (VIR_ALLOC_N(*res, size + 1) < 0)
558 559 560 561
        return BACKING_STORE_ERROR;
    memcpy(*res, buf + offset, size);
    (*res)[size] = '\0';

E
Eric Blake 已提交
562 563 564 565
    if (flags & QED_F_BACKING_FORMAT_NO_PROBE)
        *format = VIR_STORAGE_FILE_RAW;
    else
        *format = VIR_STORAGE_FILE_AUTO_SAFE;
566 567 568 569

    return BACKING_STORE_OK;
}

570 571 572

static bool
virStorageFileMatchesMagic(int format,
E
Eric Blake 已提交
573
                           char *buf,
574
                           size_t buflen)
575
{
576
    int mlen;
577 578
    int magicOffset = fileTypeInfo[format].magicOffset;
    const char *magic = fileTypeInfo[format].magic;
579

580
    if (magic == NULL)
581
        return false;
582

583
    /* Validate magic data */
584 585
    mlen = strlen(magic);
    if (magicOffset + mlen > buflen)
586
        return false;
587

588
    if (memcmp(buf + magicOffset, magic, mlen) != 0)
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
        return false;

    return true;
}


static bool
virStorageFileMatchesExtension(int format,
                               const char *path)
{
    if (fileTypeInfo[format].extension == NULL)
        return false;

    if (virFileHasSuffix(path, fileTypeInfo[format].extension))
        return true;

    return false;
}


static bool
virStorageFileMatchesVersion(int format,
E
Eric Blake 已提交
611
                             char *buf,
612 613
                             size_t buflen)
{
614 615
    int version;
    size_t i;
616 617 618

    /* Validate version number info */
    if (fileTypeInfo[format].versionOffset == -1)
E
Eric Blake 已提交
619
        return false;
620

621 622 623 624
    /* -2 == non-versioned file format, so trivially match */
    if (fileTypeInfo[format].versionOffset == -2)
        return true;

625 626 627
    if ((fileTypeInfo[format].versionOffset + 4) > buflen)
        return false;

E
Eric Blake 已提交
628 629 630 631
    if (fileTypeInfo[format].endian == LV_LITTLE_ENDIAN)
        version = virReadBufInt32LE(buf + fileTypeInfo[format].versionOffset);
    else
        version = virReadBufInt32BE(buf + fileTypeInfo[format].versionOffset);
632

633 634 635 636 637 638 639 640
    for (i = 0;
         i < FILE_TYPE_VERSIONS_LAST && fileTypeInfo[format].versionNumbers[i];
         i++) {
        VIR_DEBUG("Compare detected version %d vs one of the expected versions %d",
                  version, fileTypeInfo[format].versionNumbers[i]);
        if (version == fileTypeInfo[format].versionNumbers[i])
            return true;
    }
641

642
    return false;
643
}
644

645 646
bool
virStorageIsFile(const char *backing)
A
Adam Litke 已提交
647
{
648 649 650 651 652 653 654 655
    char *colon;
    char *slash;

    if (!backing)
        return false;

    colon = strchr(backing, ':');
    slash = strchr(backing, '/');
656 657 658 659 660

    /* 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 已提交
661 662 663
        return false;
    return true;
}
664

E
Eric Blake 已提交
665

666 667 668 669 670 671 672 673 674 675 676 677 678
static bool
virStorageIsRelative(const char *backing)
{
    if (backing[0] == '/')
        return false;

    if (!virStorageIsFile(backing))
        return false;

    return true;
}


E
Eric Blake 已提交
679
static int
E
Eric Blake 已提交
680
virStorageFileProbeFormatFromBuf(const char *path,
E
Eric Blake 已提交
681
                                 char *buf,
E
Eric Blake 已提交
682 683 684
                                 size_t buflen)
{
    int format = VIR_STORAGE_FILE_RAW;
685
    size_t i;
E
Eric Blake 已提交
686
    int possibleFormat = VIR_STORAGE_FILE_RAW;
687
    VIR_DEBUG("path=%s, buf=%p, buflen=%zu", path, buf, buflen);
E
Eric Blake 已提交
688 689

    /* First check file magic */
690
    for (i = 0; i < VIR_STORAGE_FILE_LAST; i++) {
E
Eric Blake 已提交
691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706
        if (virStorageFileMatchesMagic(i, buf, buflen)) {
            if (!virStorageFileMatchesVersion(i, buf, buflen)) {
                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 */
707
    for (i = 0; i < VIR_STORAGE_FILE_LAST; i++) {
E
Eric Blake 已提交
708 709 710 711 712 713
        if (virStorageFileMatchesExtension(i, path)) {
            format = i;
            goto cleanup;
        }
    }

714
 cleanup:
E
Eric Blake 已提交
715 716 717 718 719
    VIR_DEBUG("format=%d", format);
    return format;
}


720 721 722
static int
qcow2GetFeatures(virBitmapPtr *features,
                 int format,
E
Eric Blake 已提交
723
                 char *buf,
724 725 726 727 728
                 ssize_t len)
{
    int version = -1;
    virBitmapPtr feat = NULL;
    uint64_t bits;
729
    size_t i;
730 731 732 733 734 735 736 737 738

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

    if (version == 2)
        return 0;

    if (len < QCOW2v3_HDR_SIZE)
        return -1;

739
    if (!(feat = virBitmapNew(VIR_STORAGE_FILE_FEATURE_LAST)))
740 741 742 743 744 745 746 747 748 749 750 751 752 753
        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;
}


754 755 756 757 758
/* 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 */
759
int
760
virStorageFileGetMetadataInternal(virStorageSourcePtr meta,
761 762
                                  char *buf,
                                  size_t len,
763
                                  int *backingFormat)
764
{
765
    int ret = -1;
E
Eric Blake 已提交
766

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

770
    if (meta->format == VIR_STORAGE_FILE_AUTO)
771
        meta->format = virStorageFileProbeFormatFromBuf(meta->path, buf, len);
772

773 774 775 776
    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 已提交
777 778
        goto cleanup;
    }
779

780 781 782
    /* XXX we should consider moving virStorageBackendUpdateVolInfo
     * code into this method, for non-magic files
     */
783
    if (!fileTypeInfo[meta->format].magic)
E
Eric Blake 已提交
784
        goto done;
785

786
    /* Optionally extract capacity from file */
787 788
    if (fileTypeInfo[meta->format].sizeOffset != -1) {
        if ((fileTypeInfo[meta->format].sizeOffset + 8) > len)
E
Eric Blake 已提交
789
            goto done;
790

791
        if (fileTypeInfo[meta->format].endian == LV_LITTLE_ENDIAN)
E
Eric Blake 已提交
792
            meta->capacity = virReadBufInt64LE(buf +
793
                                               fileTypeInfo[meta->format].sizeOffset);
E
Eric Blake 已提交
794 795
        else
            meta->capacity = virReadBufInt64BE(buf +
796
                                               fileTypeInfo[meta->format].sizeOffset);
797
        /* Avoid unlikely, but theoretically possible overflow */
E
Eric Blake 已提交
798
        if (meta->capacity > (ULLONG_MAX /
799
                              fileTypeInfo[meta->format].sizeMultiplier))
E
Eric Blake 已提交
800
            goto done;
801
        meta->capacity *= fileTypeInfo[meta->format].sizeMultiplier;
802
    }
803

804
    if (fileTypeInfo[meta->format].qcowCryptOffset != -1) {
805
        int crypt_format;
806

E
Eric Blake 已提交
807
        crypt_format = virReadBufInt32BE(buf +
808
                                         fileTypeInfo[meta->format].qcowCryptOffset);
809 810
        if (crypt_format && !meta->encryption &&
            VIR_ALLOC(meta->encryption) < 0)
811
            goto cleanup;
812
    }
813

814 815
    if (fileTypeInfo[meta->format].getBackingStore != NULL) {
        int store = fileTypeInfo[meta->format].getBackingStore(&meta->backingStoreRaw,
816
                                                         backingFormat,
E
Eric Blake 已提交
817 818 819
                                                         buf, len);
        if (store == BACKING_STORE_INVALID)
            goto done;
820

E
Eric Blake 已提交
821 822
        if (store == BACKING_STORE_ERROR)
            goto cleanup;
823 824
    }

825 826
    if (fileTypeInfo[meta->format].getFeatures != NULL &&
        fileTypeInfo[meta->format].getFeatures(&meta->features, meta->format, buf, len) < 0)
827 828
        goto cleanup;

829
    if (meta->format == VIR_STORAGE_FILE_QCOW2 && meta->features &&
830 831 832
        VIR_STRDUP(meta->compat, "1.1") < 0)
        goto cleanup;

833
 done:
834
    ret = 0;
E
Eric Blake 已提交
835

836
 cleanup:
E
Eric Blake 已提交
837
    return ret;
838 839 840 841
}


/**
842
 * virStorageFileProbeFormat:
843
 *
844 845
 * Probe for the format of 'path', returning the detected
 * disk format.
846 847 848
 *
 * Callers are advised never to trust the returned 'format'
 * unless it is listed as VIR_STORAGE_FILE_RAW, since a
849
 * malicious guest can turn a raw file into any other non-raw
850 851 852 853 854
 * format at will.
 *
 * Best option: Don't use this function
 */
int
855
virStorageFileProbeFormat(const char *path, uid_t uid, gid_t gid)
856
{
857
    int fd;
858
    int ret = -1;
859
    struct stat sb;
860 861
    ssize_t len = VIR_STORAGE_MAX_HEADER;
    char *header = NULL;
862

863 864
    if ((fd = virFileOpenAs(path, O_RDONLY, 0, uid, gid, 0)) < 0) {
        virReportSystemError(-fd, _("Failed to open file '%s'"), path);
865 866 867
        return -1;
    }

868 869 870 871 872
    if (fstat(fd, &sb) < 0) {
        virReportSystemError(errno, _("cannot stat file '%s'"), path);
        goto cleanup;
    }

873 874
    /* No header to probe for directories */
    if (S_ISDIR(sb.st_mode)) {
875 876
        ret = VIR_STORAGE_FILE_DIR;
        goto cleanup;
877
    }
878 879 880 881 882 883

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

884
    if ((len = virFileReadHeaderFD(fd, len, &header)) < 0) {
885 886 887 888
        virReportSystemError(errno, _("cannot read header '%s'"), path);
        goto cleanup;
    }

889
    ret = virStorageFileProbeFormatFromBuf(path, header, len);
890

891
 cleanup:
892
    VIR_FREE(header);
893
    VIR_FORCE_CLOSE(fd);
894 895 896 897

    return ret;
}

898

899
static virStorageSourcePtr
900 901 902
virStorageFileMetadataNew(const char *path,
                          int format)
{
903
    virStorageSourcePtr ret = NULL;
904 905 906 907 908 909 910

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

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

911 912
    if (VIR_STRDUP(ret->path, path) < 0)
        goto error;
913 914 915 916

    return ret;

 error:
917
    virStorageSourceFree(ret);
918 919 920 921
    return NULL;
}


922 923 924 925 926
/**
 * virStorageFileGetMetadataFromBuf:
 * @path: name of file, for error messages
 * @buf: header bytes from @path
 * @len: length of @buf
927 928
 * @backing: output malloc'd name of backing image, if any
 * @backingFormat: format of @backing
929
 *
E
Eric Blake 已提交
930 931 932 933
 * Extract metadata about the storage volume, including probing its
 * format.  Does not recurse.  Callers are advised not to trust the
 * learned format if a guest has ever used the volume when it was
 * raw, since a malicious guest can turn a raw file into any
934 935
 * other non-raw format at will.
 *
936
 * If the returned @backingFormat is VIR_STORAGE_FILE_AUTO
937 938 939 940
 * 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.
 *
941
 * Caller MUST free the result after use via virStorageSourceFree.
942
 */
943
virStorageSourcePtr
944 945 946
virStorageFileGetMetadataFromBuf(const char *path,
                                 char *buf,
                                 size_t len,
947 948
                                 char **backing,
                                 int *backingFormat)
949
{
950
    virStorageSourcePtr ret = NULL;
951
    virStorageSourcePtr meta = NULL;
952

E
Eric Blake 已提交
953
    if (!(meta = virStorageFileMetadataNew(path, VIR_STORAGE_FILE_AUTO)))
954
        return NULL;
955

956 957 958 959 960
    if (virStorageFileGetMetadataInternal(meta, buf, len,
                                          backingFormat) < 0)
        goto cleanup;
    if (VIR_STRDUP(*backing, meta->backingStoreRaw) < 0)
        goto cleanup;
961

962 963 964 965
    ret = meta;
    meta = NULL;
 cleanup:
    virStorageSourceFree(meta);
966
    return ret;
967 968 969 970
}


/* Internal version that also supports a containing directory name.  */
971
static int
972
virStorageFileGetMetadataFromFDInternal(virStorageSourcePtr meta,
973
                                        int fd,
974
                                        int *backingFormat)
975 976
{
    char *buf = NULL;
977
    ssize_t len = VIR_STORAGE_MAX_HEADER;
978
    struct stat sb;
979
    int ret = -1;
980
    int dummy;
981

982 983
    if (!backingFormat)
        backingFormat = &dummy;
984

985
    *backingFormat = VIR_STORAGE_FILE_NONE;
986

987 988 989
    if (fstat(fd, &sb) < 0) {
        virReportSystemError(errno,
                             _("cannot stat file '%s'"),
990
                             meta->relPath);
991
        return -1;
992 993 994
    }

    if (S_ISDIR(sb.st_mode)) {
995 996
        /* No header to probe for directories, but also no backing file. Just
         * update the metadata.*/
997 998
        meta->type = VIR_STORAGE_TYPE_DIR;
        meta->format = VIR_STORAGE_FILE_DIR;
999
        ret = 0;
1000 1001 1002 1003
        goto cleanup;
    }

    if (lseek(fd, 0, SEEK_SET) == (off_t)-1) {
1004
        virReportSystemError(errno, _("cannot seek to start of '%s'"), meta->relPath);
1005 1006 1007 1008
        goto cleanup;
    }

    if ((len = virFileReadHeaderFD(fd, len, &buf)) < 0) {
1009
        virReportSystemError(errno, _("cannot read header '%s'"), meta->relPath);
1010 1011 1012
        goto cleanup;
    }

1013
    ret = virStorageFileGetMetadataInternal(meta, buf, len, backingFormat);
1014

1015 1016 1017 1018 1019 1020
    if (ret == 0) {
        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;
    }
1021
 cleanup:
1022 1023 1024 1025 1026
    VIR_FREE(buf);
    return ret;
}


1027 1028 1029
/**
 * virStorageFileGetMetadataFromFD:
 *
1030 1031
 * Extract metadata about the storage volume with the specified
 * image format. If image format is VIR_STORAGE_FILE_AUTO, it
1032
 * will probe to automatically identify the format.  Does not recurse.
1033
 *
1034 1035 1036 1037
 * 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.
 *
1038
 * Caller MUST free the result after use via virStorageSourceFree.
1039
 */
1040
virStorageSourcePtr
1041 1042
virStorageFileGetMetadataFromFD(const char *path,
                                int fd,
1043 1044 1045
                                int format,
                                int *backingFormat)

1046
{
1047
    virStorageSourcePtr ret = NULL;
1048
    char *canonPath = NULL;
1049

1050 1051
    if (!(canonPath = canonicalize_file_name(path))) {
        virReportSystemError(errno, _("unable to resolve '%s'"), path);
1052
        goto cleanup;
1053 1054 1055 1056 1057
    }

    if (!(ret = virStorageFileMetadataNew(canonPath, format)))
        goto cleanup;

1058

1059
    if (virStorageFileGetMetadataFromFDInternal(ret, fd, backingFormat) < 0) {
1060
        virStorageSourceFree(ret);
1061 1062 1063 1064
        ret = NULL;
    }

 cleanup:
1065
    VIR_FREE(canonPath);
1066
    return ret;
1067 1068
}

1069

1070 1071 1072 1073 1074
/**
 * virStorageFileChainCheckBroken
 *
 * If CHAIN is broken, set *brokenFile to the broken file name,
 * otherwise set it to NULL. Caller MUST free *brokenFile after use.
1075 1076
 * Return 0 on success (including when brokenFile is set), negative on
 * error (allocation failure).
1077 1078
 */
int
1079
virStorageFileChainGetBroken(virStorageSourcePtr chain,
1080 1081
                             char **brokenFile)
{
1082
    virStorageSourcePtr tmp;
1083

1084 1085
    *brokenFile = NULL;

1086 1087 1088
    if (!chain)
        return 0;

1089
    for (tmp = chain; tmp; tmp = tmp->backingStore) {
1090 1091
        /* Break when we hit end of chain; report error if we detected
         * a missing backing file, infinite loop, or other error */
1092
        if (!tmp->backingStore && tmp->backingStoreRaw) {
1093 1094
            if (VIR_STRDUP(*brokenFile, tmp->backingStoreRaw) < 0)
                return -1;
1095

1096 1097 1098
           return 0;
        }
    }
1099

1100
    return 0;
1101 1102 1103
}


1104 1105 1106 1107 1108 1109
/**
 * virStorageFileResize:
 *
 * Change the capacity of the raw storage file at 'path'.
 */
int
1110 1111 1112 1113
virStorageFileResize(const char *path,
                     unsigned long long capacity,
                     unsigned long long orig_capacity,
                     bool pre_allocate)
1114
{
1115 1116
    int fd = -1;
    int ret = -1;
1117 1118 1119 1120 1121 1122
    int rc ATTRIBUTE_UNUSED;
    off_t offset ATTRIBUTE_UNUSED;
    off_t len ATTRIBUTE_UNUSED;

    offset = orig_capacity;
    len = capacity - orig_capacity;
1123 1124 1125 1126 1127 1128

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

1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
    if (pre_allocate) {
#if HAVE_POSIX_FALLOCATE
        if ((rc = posix_fallocate(fd, offset, len)) != 0) {
            virReportSystemError(rc,
                                 _("Failed to pre-allocate space for "
                                   "file '%s'"), path);
            goto cleanup;
        }
#elif HAVE_SYS_SYSCALL_H && defined(SYS_fallocate)
        if (syscall(SYS_fallocate, fd, 0, offset, len) != 0) {
            virReportSystemError(errno,
1140
                                 _("Failed to pre-allocate space for "
1141 1142 1143 1144 1145
                                   "file '%s'"), path);
            goto cleanup;
        }
#else
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
1146
                       _("preallocate is not supported on this platform"));
1147
        goto cleanup;
1148 1149 1150 1151 1152 1153 1154
#endif
    } else {
        if (ftruncate(fd, capacity) < 0) {
            virReportSystemError(errno,
                                 _("Failed to truncate file '%s'"), path);
            goto cleanup;
        }
1155 1156
    }

1157 1158 1159 1160 1161 1162 1163
    if (VIR_CLOSE(fd) < 0) {
        virReportSystemError(errno, _("Unable to save '%s'"), path);
        goto cleanup;
    }

    ret = 0;

1164
 cleanup:
1165 1166
    VIR_FORCE_CLOSE(fd);
    return ret;
1167 1168
}

1169 1170 1171 1172 1173 1174

int virStorageFileIsClusterFS(const char *path)
{
    /* These are coherent cluster filesystems known to be safe for
     * migration with cache != none
     */
1175 1176 1177
    return virFileIsSharedFSType(path,
                                 VIR_FILE_SHFS_GFS2 |
                                 VIR_FILE_SHFS_OCFS);
1178
}
1179 1180

#ifdef LVS
1181 1182
int virStorageFileGetLVMKey(const char *path,
                            char **key)
1183 1184 1185 1186 1187
{
    /*
     *  # lvs --noheadings --unbuffered --nosuffix --options "uuid" LVNAME
     *    06UgP5-2rhb-w3Bo-3mdR-WeoL-pytO-SAa2ky
     */
1188
    int status;
1189 1190 1191 1192 1193 1194
    virCommandPtr cmd = virCommandNewArgList(
        LVS,
        "--noheadings", "--unbuffered", "--nosuffix",
        "--options", "uuid", path,
        NULL
        );
1195 1196 1197
    int ret = -1;

    *key = NULL;
1198 1199

    /* Run the program and capture its output */
1200 1201
    virCommandSetOutputBuffer(cmd, key);
    if (virCommandRun(cmd, &status) < 0)
1202 1203
        goto cleanup;

1204 1205 1206 1207 1208 1209
    /* 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) {
1210
        char *nl;
1211
        char *tmp = *key;
1212 1213 1214 1215 1216 1217

        /* Find first non-space character */
        while (*tmp && c_isspace(*tmp)) {
            tmp++;
        }
        /* Kill leading spaces */
1218 1219
        if (tmp != *key)
            memmove(*key, tmp, strlen(tmp)+1);
1220 1221

        /* Kill trailing newline */
1222
        if ((nl = strchr(*key, '\n')))
1223 1224 1225
            *nl = '\0';
    }

1226
    ret = 0;
1227

1228
 cleanup:
1229 1230 1231
    if (*key && STREQ(*key, ""))
        VIR_FREE(*key);

1232 1233
    virCommandFree(cmd);

1234
    return ret;
1235 1236
}
#else
1237 1238
int virStorageFileGetLVMKey(const char *path,
                            char **key ATTRIBUTE_UNUSED)
1239 1240
{
    virReportSystemError(ENOSYS, _("Unable to get LVM key for %s"), path);
1241
    return -1;
1242 1243 1244
}
#endif

1245
#ifdef WITH_UDEV
1246 1247
int virStorageFileGetSCSIKey(const char *path,
                             char **key)
1248
{
1249
    int status;
1250 1251 1252 1253 1254 1255 1256
    virCommandPtr cmd = virCommandNewArgList(
        "/lib/udev/scsi_id",
        "--replace-whitespace",
        "--whitelisted",
        "--device", path,
        NULL
        );
1257 1258 1259
    int ret = -1;

    *key = NULL;
1260 1261

    /* Run the program and capture its output */
1262 1263
    virCommandSetOutputBuffer(cmd, key);
    if (virCommandRun(cmd, &status) < 0)
1264 1265
        goto cleanup;

1266 1267 1268 1269 1270 1271
    /* 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');
1272 1273 1274 1275
        if (nl)
            *nl = '\0';
    }

1276 1277
    ret = 0;

1278
 cleanup:
1279 1280 1281
    if (*key && STREQ(*key, ""))
        VIR_FREE(*key);

1282 1283
    virCommandFree(cmd);

1284
    return ret;
1285 1286
}
#else
1287 1288
int virStorageFileGetSCSIKey(const char *path,
                             char **key ATTRIBUTE_UNUSED)
1289 1290
{
    virReportSystemError(ENOSYS, _("Unable to get SCSI key for %s"), path);
1291
    return -1;
1292 1293
}
#endif
1294

1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
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);

    if (virStringListLength(strings) != 2)
        goto cleanup;

E
Eric Blake 已提交
1313
    if (virStrToLong_uip(strings[1], &suffix, 10, &idx) < 0 ||
1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331
        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 已提交
1332 1333 1334 1335 1336 1337 1338 1339 1340 1341
/* 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.
1342
 */
1343
virStorageSourcePtr
1344
virStorageFileChainLookup(virStorageSourcePtr chain,
1345
                          virStorageSourcePtr startFrom,
1346
                          const char *name,
1347
                          unsigned int idx,
1348 1349
                          const char **parent)
{
1350
    const char *start = chain->path;
1351
    const char *tmp;
E
Eric Blake 已提交
1352 1353
    const char *parentDir = ".";
    bool nameIsFile = virStorageIsFile(name);
1354
    size_t i;
1355 1356 1357 1358

    if (!parent)
        parent = &tmp;
    *parent = NULL;
1359 1360 1361

    i = 0;
    if (startFrom) {
E
Eric Blake 已提交
1362
        while (chain && chain != startFrom->backingStore) {
1363 1364 1365
            chain = chain->backingStore;
            i++;
        }
E
Eric Blake 已提交
1366
        *parent = startFrom->path;
1367 1368
    }

E
Eric Blake 已提交
1369
    while (chain) {
1370
        if (!name && !idx) {
1371
            if (!chain->backingStore)
1372
                break;
1373 1374 1375 1376
        } else if (idx) {
            VIR_DEBUG("%zu: %s", i, chain->path);
            if (idx == i)
                break;
E
Eric Blake 已提交
1377
        } else {
1378 1379
            if (STREQ_NULLABLE(name, chain->relPath) ||
                STREQ(name, chain->path))
1380
                break;
E
Eric Blake 已提交
1381 1382 1383
            if (nameIsFile && (chain->type == VIR_STORAGE_TYPE_FILE ||
                               chain->type == VIR_STORAGE_TYPE_BLOCK)) {
                int result = virFileRelLinkPointsTo(parentDir, name,
1384
                                                    chain->path);
E
Eric Blake 已提交
1385 1386 1387 1388 1389
                if (result < 0)
                    goto error;
                if (result > 0)
                    break;
            }
1390
        }
1391
        *parent = chain->path;
E
Eric Blake 已提交
1392
        parentDir = chain->relDir;
1393
        chain = chain->backingStore;
1394
        i++;
1395
    }
1396

E
Eric Blake 已提交
1397
    if (!chain)
1398
        goto error;
1399
    return chain;
1400

1401
 error:
1402 1403 1404 1405 1406
    if (idx) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("could not find backing store %u in chain for '%s'"),
                       idx, start);
    } else if (name) {
E
Eric Blake 已提交
1407 1408 1409 1410 1411 1412 1413 1414
        if (startFrom)
            virReportError(VIR_ERR_INVALID_ARG,
                           _("could not find image '%s' beneath '%s' in "
                             "chain for '%s'"), name, startFrom->path, start);
        else
            virReportError(VIR_ERR_INVALID_ARG,
                           _("could not find image '%s' in chain for '%s'"),
                           name, start);
1415
    } else {
1416 1417 1418
        virReportError(VIR_ERR_INVALID_ARG,
                       _("could not find base image in chain for '%s'"),
                       start);
1419
    }
1420 1421 1422
    *parent = NULL;
    return NULL;
}
1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452


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


1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463
static void
virStoragePermsFree(virStoragePermsPtr def)
{
    if (!def)
        return;

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


1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495
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;
}
1496 1497


1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512
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;
}


1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537
void
virStorageSourcePoolDefFree(virStorageSourcePoolDefPtr def)
{
    if (!def)
        return;

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

    VIR_FREE(def);
}


void
virStorageSourceAuthClear(virStorageSourcePtr def)
{
    VIR_FREE(def->auth.username);

    if (def->auth.secretType == VIR_STORAGE_SECRET_TYPE_USAGE)
        VIR_FREE(def->auth.secret.usage);

    def->auth.secretType = VIR_STORAGE_SECRET_TYPE_NONE;
}


1538 1539 1540 1541 1542 1543 1544 1545 1546 1547
int
virStorageSourceGetActualType(virStorageSourcePtr def)
{
    if (def->type == VIR_STORAGE_TYPE_VOLUME && def->srcpool)
        return def->srcpool->actualtype;

    return def->type;
}


1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570
/**
 * virStorageSourceClearBackingStore:
 *
 * @src: disk source to clear
 *
 * Clears information about backing store of the current storage file.
 */
void
virStorageSourceClearBackingStore(virStorageSourcePtr def)
{
    if (!def)
        return;

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

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


1571 1572 1573 1574 1575 1576 1577 1578 1579
void
virStorageSourceClear(virStorageSourcePtr def)
{
    size_t i;

    if (!def)
        return;

    VIR_FREE(def->path);
1580
    VIR_FREE(def->volume);
1581 1582
    virStorageSourcePoolDefFree(def->srcpool);
    VIR_FREE(def->driverName);
E
Eric Blake 已提交
1583 1584
    virBitmapFree(def->features);
    VIR_FREE(def->compat);
1585 1586 1587 1588 1589 1590 1591
    virStorageEncryptionFree(def->encryption);

    if (def->seclabels) {
        for (i = 0; i < def->nseclabels; i++)
            virSecurityDeviceLabelDefFree(def->seclabels[i]);
        VIR_FREE(def->seclabels);
    }
1592
    virStoragePermsFree(def->perms);
E
Eric Blake 已提交
1593
    VIR_FREE(def->timestamps);
1594 1595 1596

    virStorageNetHostDefFree(def->nhosts, def->hosts);
    virStorageSourceAuthClear(def);
1597

1598
    virStorageSourceClearBackingStore(def);
1599
}
1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610


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

    virStorageSourceClear(def);
    VIR_FREE(def);
}
1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623


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

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

1624 1625 1626 1627
    /* store relative name */
    if (VIR_STRDUP(ret->relPath, parent->backingStoreRaw) < 0)
        goto error;

1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 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 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 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 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956
    /* XXX Once we get rid of the need to use canonical names in path, we will be
     * able to use mdir_name on parent->path instead of using parent->relDir */
    if (STRNEQ(parent->relDir, "/"))
        parentdir = parent->relDir;

    if (virAsprintf(&ret->path, "%s/%s", parentdir, rel) < 0)
        goto error;

    if (virStorageSourceGetActualType(parent) != VIR_STORAGE_TYPE_NETWORK) {
        ret->type = VIR_STORAGE_TYPE_FILE;

        /* XXX store the relative directory name for test's sake */
        if (!(ret->relDir = mdir_name(ret->path))) {
            virReportOOMError();
            goto error;
        }

        /* XXX we don't currently need to store the canonical path but the
         * change would break the test suite. Get rid of this later */
        char *tmp = ret->path;
        if (!(ret->path = canonicalize_file_name(tmp))) {
            ret->path = tmp;
            tmp = NULL;
        }
        VIR_FREE(tmp);
    } else {
        ret->type = VIR_STORAGE_TYPE_NETWORK;

        /* copy the host network part */
        ret->protocol = parent->protocol;
        if (!(ret->hosts = virStorageNetHostDefCopy(parent->nhosts, parent->hosts)))
            goto error;
        ret->nhosts = parent->nhosts;

        if (VIR_STRDUP(ret->volume, parent->volume) < 0)
            goto error;

        /* XXX store the relative directory name for test's sake */
        if (!(ret->relDir = mdir_name(ret->path))) {
            virReportOOMError();
            goto error;
        }
    }

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

    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 */
    if (VIR_STRDUP(src->path,
                   *uri->path == '/' ? uri->path + 1 : uri->path) < 0)
        goto cleanup;

    if (src->protocol == VIR_STORAGE_NET_PROTOCOL_GLUSTER) {
        char *tmp;
        if (!(tmp = strchr(src->path, '/')) ||
            tmp == src->path) {
            virReportError(VIR_ERR_XML_ERROR,
                           _("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 (VIR_ALLOC(src->hosts) < 0)
        goto cleanup;

    src->nhosts = 1;

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


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

    if (!(backing = virStringSplit(path, ":", 0)))
        goto cleanup;

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

    switch ((virStorageNetProtocol) src->protocol) {
    case VIR_STORAGE_NET_PROTOCOL_NBD:
        if (VIR_ALLOC_N(src->hosts, 1) < 0)
            goto cleanup;
        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]) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("missing remote information in '%s' for protocol nbd"),
                           path);
            goto cleanup;
        } else if (STREQ(backing[1], "unix")) {
            if (!backing[2]) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("missing unix socket path in nbd backing string %s"),
                               path);
                goto cleanup;
            }

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

       } else {
            if (!backing[1]) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("missing host name in nbd string '%s'"),
                               path);
                goto cleanup;
            }

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

            if (!backing[2]) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("missing port in nbd string '%s'"),
                               path);
                goto cleanup;
            }

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

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

    case VIR_STORAGE_NET_PROTOCOL_SHEEPDOG:
    case VIR_STORAGE_NET_PROTOCOL_RBD:
    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"),
                       backing[0]);
        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:
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("malformed backing store path for protocol %s"),
                       backing[0]);
        goto cleanup;
    }

    ret = 0;

 cleanup:
    virStringFreeList(backing);
    return ret;

}


static virStorageSourcePtr
virStorageSourceNewFromBackingAbsolute(const char *path)
{
    virStorageSourcePtr ret;

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

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

        /* XXX store the relative directory name for test's sake */
        if (!(ret->relDir = mdir_name(path))) {
            virReportOOMError();
            goto error;
        }

        /* XXX we don't currently need to store the canonical path but the
         * change would break the test suite. Get rid of this later */
        if (!(ret->path = canonicalize_file_name(path))) {
            if (VIR_STRDUP(ret->path, path) < 0)
                goto error;
        }
    } else {
        ret->type = VIR_STORAGE_TYPE_NETWORK;

        /* handle URI formatted backing stores */
        if (strstr(path, "://")) {
            if (virStorageSourceParseBackingURI(ret, path) < 0)
                goto error;
        } else {
            if (virStorageSourceParseBackingColon(ret, path) < 0)
                goto error;
        }

        /* XXX fill relative path so that relative names work with network storage too */
        if (ret->path) {
            if (!(ret->relDir = mdir_name(ret->path))) {
                virReportOOMError();
                goto error;
            }
        } else {
            if (VIR_STRDUP(ret->relDir, "") < 0)
                goto error;
        }
    }

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

    return ret;
}
1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173


static char *
virStorageFileCanonicalizeFormatPath(char **components,
                                     size_t ncomponents,
                                     bool beginSlash,
                                     bool beginDoubleSlash)
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    size_t i;
    char *ret = NULL;

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

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

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

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

    if (virBufferError(&buf) != 0) {
        virReportOOMError();
        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;
}
2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223


/**
 * 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 *tmp;
    char *ret;

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

    if ((tmp = strrchr(ret, '/')))
        tmp[1] = '\0';
    else
        ret[0] = '\0';

    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) {
2224
        if (!next->relPath) {
2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259
            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;
}