virsecretobj.c 24.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/*
 * virsecretobj.c: internal <secret> objects handling
 *
 * Copyright (C) 2009-2016 Red Hat, Inc.
 *
 * 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
 * License along with this library.  If not, see
 * <http://www.gnu.org/licenses/>.
 */

#include <config.h>
22 23 24
#include <dirent.h>
#include <fcntl.h>
#include <sys/stat.h>
25 26 27 28

#include "datatypes.h"
#include "virsecretobj.h"
#include "viralloc.h"
29 30
#include "virerror.h"
#include "virfile.h"
31
#include "virhash.h"
32
#include "virlog.h"
33
#include "virstring.h"
34
#include "base64.h"
35

36 37 38
#define VIR_FROM_THIS VIR_FROM_SECRET

VIR_LOG_INIT("conf.virsecretobj");
39

40 41 42 43 44 45 46 47 48
struct _virSecretObj {
    virObjectLockable parent;
    char *configFile;
    char *base64File;
    virSecretDefPtr def;
    unsigned char *value;       /* May be NULL */
    size_t value_size;
};

49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
static virClassPtr virSecretObjClass;
static virClassPtr virSecretObjListClass;
static void virSecretObjDispose(void *obj);
static void virSecretObjListDispose(void *obj);

struct _virSecretObjList {
    virObjectLockable parent;

    /* uuid string -> virSecretObj  mapping
     * for O(1), lockless lookup-by-uuid */
    virHashTable *objs;
};

struct virSecretSearchData {
    int usageType;
    const char *usageID;
};


static int
virSecretObjOnceInit(void)
{
    if (!(virSecretObjClass = virClassNew(virClassForObjectLockable(),
                                          "virSecretObj",
                                          sizeof(virSecretObj),
                                          virSecretObjDispose)))
        return -1;

    if (!(virSecretObjListClass = virClassNew(virClassForObjectLockable(),
                                              "virSecretObjList",
                                              sizeof(virSecretObjList),
                                              virSecretObjListDispose)))
        return -1;

    return 0;
}


VIR_ONCE_GLOBAL_INIT(virSecretObj)

virSecretObjPtr
virSecretObjNew(void)
{
    virSecretObjPtr secret;

    if (virSecretObjInitialize() < 0)
        return NULL;

    if (!(secret = virObjectLockableNew(virSecretObjClass)))
        return NULL;

    return secret;
}


void
virSecretObjEndAPI(virSecretObjPtr *secret)
{
    if (!*secret)
        return;

    virObjectUnlock(*secret);
    virObjectUnref(*secret);
    *secret = NULL;
}


virSecretObjListPtr
virSecretObjListNew(void)
{
    virSecretObjListPtr secrets;

    if (virSecretObjInitialize() < 0)
        return NULL;

    if (!(secrets = virObjectLockableNew(virSecretObjListClass)))
        return NULL;

    if (!(secrets->objs = virHashCreate(50, virObjectFreeHashData))) {
        virObjectUnref(secrets);
        return NULL;
    }

    return secrets;
}


static void
virSecretObjDispose(void *obj)
{
    virSecretObjPtr secret = obj;

    virSecretDefFree(secret->def);
    if (secret->value) {
        /* Wipe before free to ensure we don't leave a secret on the heap */
        memset(secret->value, 0, secret->value_size);
        VIR_FREE(secret->value);
    }
    VIR_FREE(secret->configFile);
    VIR_FREE(secret->base64File);
}


static void
virSecretObjListDispose(void *obj)
{
    virSecretObjListPtr secrets = obj;

    virHashFree(secrets->objs);
}
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298


/**
 * virSecretObjFindByUUIDLocked:
 * @secrets: list of secret objects
 * @uuid: secret uuid to find
 *
 * This functions requires @secrets to be locked already!
 *
 * Returns: not locked, but ref'd secret object.
 */
virSecretObjPtr
virSecretObjListFindByUUIDLocked(virSecretObjListPtr secrets,
                                 const unsigned char *uuid)
{
    char uuidstr[VIR_UUID_STRING_BUFLEN];

    virUUIDFormat(uuid, uuidstr);

    return virObjectRef(virHashLookup(secrets->objs, uuidstr));
}


/**
 * virSecretObjFindByUUID:
 * @secrets: list of secret objects
 * @uuid: secret uuid to find
 *
 * This function locks @secrets and finds the secret object which
 * corresponds to @uuid.
 *
 * Returns: locked and ref'd secret object.
 */
virSecretObjPtr
virSecretObjListFindByUUID(virSecretObjListPtr secrets,
                           const unsigned char *uuid)
{
    virSecretObjPtr ret;

    virObjectLock(secrets);
    ret = virSecretObjListFindByUUIDLocked(secrets, uuid);
    virObjectUnlock(secrets);
    if (ret)
        virObjectLock(ret);
    return ret;
}


static int
virSecretObjSearchName(const void *payload,
                       const void *name ATTRIBUTE_UNUSED,
                       const void *opaque)
{
    virSecretObjPtr secret = (virSecretObjPtr) payload;
    struct virSecretSearchData *data = (struct virSecretSearchData *) opaque;
    int found = 0;

    virObjectLock(secret);

    if (secret->def->usage_type != data->usageType)
        goto cleanup;

    switch (data->usageType) {
    case VIR_SECRET_USAGE_TYPE_NONE:
    /* never match this */
        break;

    case VIR_SECRET_USAGE_TYPE_VOLUME:
        if (STREQ(secret->def->usage.volume, data->usageID))
            found = 1;
        break;

    case VIR_SECRET_USAGE_TYPE_CEPH:
        if (STREQ(secret->def->usage.ceph, data->usageID))
            found = 1;
        break;

    case VIR_SECRET_USAGE_TYPE_ISCSI:
        if (STREQ(secret->def->usage.target, data->usageID))
            found = 1;
        break;
    }

 cleanup:
    virObjectUnlock(secret);
    return found;
}


/**
 * virSecretObjFindByUsageLocked:
 * @secrets: list of secret objects
 * @usageType: secret usageType to find
 * @usageID: secret usage string
 *
 * This functions requires @secrets to be locked already!
 *
 * Returns: not locked, but ref'd secret object.
 */
virSecretObjPtr
virSecretObjListFindByUsageLocked(virSecretObjListPtr secrets,
                                  int usageType,
                                  const char *usageID)
{
    virSecretObjPtr ret = NULL;
    struct virSecretSearchData data = { .usageType = usageType,
                                        .usageID = usageID };

    ret = virHashSearch(secrets->objs, virSecretObjSearchName, &data);
    if (ret)
        virObjectRef(ret);
    return ret;
}


/**
 * virSecretObjFindByUsage:
 * @secrets: list of secret objects
 * @usageType: secret usageType to find
 * @usageID: secret usage string
 *
 * This function locks @secrets and finds the secret object which
 * corresponds to @usageID of @usageType.
 *
 * Returns: locked and ref'd secret object.
 */
virSecretObjPtr
virSecretObjListFindByUsage(virSecretObjListPtr secrets,
                            int usageType,
                            const char *usageID)
{
    virSecretObjPtr ret;

    virObjectLock(secrets);
    ret = virSecretObjListFindByUsageLocked(secrets, usageType, usageID);
    virObjectUnlock(secrets);
    if (ret)
        virObjectLock(ret);
    return ret;
}
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372


/*
 * virSecretObjListRemove:
 * @secrets: list of secret objects
 * @secret: a secret object
 *
 * Remove the object from the hash table.  The caller must hold the lock
 * on the driver owning @secrets and must have also locked @secret to
 * ensure no one else is either waiting for @secret or still using it.
 */
void
virSecretObjListRemove(virSecretObjListPtr secrets,
                       virSecretObjPtr secret)
{
    char uuidstr[VIR_UUID_STRING_BUFLEN];

    virUUIDFormat(secret->def->uuid, uuidstr);
    virObjectRef(secret);
    virObjectUnlock(secret);

    virObjectLock(secrets);
    virObjectLock(secret);
    virHashRemoveEntry(secrets->objs, uuidstr);
    virObjectUnlock(secret);
    virObjectUnref(secret);
    virObjectUnlock(secrets);
}


/*
 * virSecretObjListAddLocked:
 * @secrets: list of secret objects
 * @def: new secret definition
 * @configDir: directory to place secret config files
 * @oldDef: Former secret def (e.g. a reload path perhaps)
 *
 * Add the new def to the secret obj table hash
 *
 * This functions requires @secrets to be locked already!
 *
 * Returns pointer to secret or NULL if failure to add
 */
virSecretObjPtr
virSecretObjListAddLocked(virSecretObjListPtr secrets,
                          virSecretDefPtr def,
                          const char *configDir,
                          virSecretDefPtr *oldDef)
{
    virSecretObjPtr secret;
    virSecretObjPtr ret = NULL;
    const char *newUsageID = virSecretUsageIDForDef(def);
    char uuidstr[VIR_UUID_STRING_BUFLEN];
    char *configFile = NULL, *base64File = NULL;

    if (oldDef)
        *oldDef = NULL;

    /* Is there a secret already matching this UUID */
    if ((secret = virSecretObjListFindByUUIDLocked(secrets, def->uuid))) {
        const char *oldUsageID;

        virObjectLock(secret);

        oldUsageID = virSecretUsageIDForDef(secret->def);
        if (STRNEQ(oldUsageID, newUsageID)) {
            virUUIDFormat(secret->def->uuid, uuidstr);
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("a secret with UUID %s is already defined for "
                             "use with %s"),
                           uuidstr, oldUsageID);
            goto cleanup;
        }

373
        if (secret->def->isprivate && !def->isprivate) {
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot change private flag on existing secret"));
            goto cleanup;
        }

        if (oldDef)
            *oldDef = secret->def;
        else
            virSecretDefFree(secret->def);
        secret->def = def;
    } else {
        /* No existing secret with same UUID,
         * try look for matching usage instead */
        if ((secret = virSecretObjListFindByUsageLocked(secrets,
                                                        def->usage_type,
                                                        newUsageID))) {
            virObjectLock(secret);
            virUUIDFormat(secret->def->uuid, uuidstr);
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("a secret with UUID %s already defined for "
                             "use with %s"),
                           uuidstr, newUsageID);
            goto cleanup;
        }

        /* Generate the possible configFile and base64File strings
         * using the configDir, uuidstr, and appropriate suffix
         */
        virUUIDFormat(def->uuid, uuidstr);
        if (!(configFile = virFileBuildPath(configDir, uuidstr, ".xml")) ||
            !(base64File = virFileBuildPath(configDir, uuidstr, ".base64")))
            goto cleanup;

        if (!(secret = virSecretObjNew()))
            goto cleanup;

        virObjectLock(secret);

        if (virHashAddEntry(secrets->objs, uuidstr, secret) < 0)
            goto cleanup;

        secret->def = def;
        secret->configFile = configFile;
        secret->base64File = base64File;
        configFile = NULL;
        base64File = NULL;
        virObjectRef(secret);
    }

    ret = secret;
    secret = NULL;

 cleanup:
    virSecretObjEndAPI(&secret);
    VIR_FREE(configFile);
    VIR_FREE(base64File);
    return ret;
}


virSecretObjPtr
virSecretObjListAdd(virSecretObjListPtr secrets,
                    virSecretDefPtr def,
                    const char *configDir,
                    virSecretDefPtr *oldDef)
{
    virSecretObjPtr ret;

    virObjectLock(secrets);
    ret = virSecretObjListAddLocked(secrets, def, configDir, oldDef);
    virObjectUnlock(secrets);
    return ret;
}
447 448 449 450 451 452


struct virSecretObjListGetHelperData {
    virConnectPtr conn;
    virSecretObjListACLFilter filter;
    int got;
453 454 455
    char **uuids;
    int nuuids;
    bool error;
456 457 458 459 460 461 462 463 464 465 466
};


static int
virSecretObjListGetHelper(void *payload,
                          const void *name ATTRIBUTE_UNUSED,
                          void *opaque)
{
    struct virSecretObjListGetHelperData *data = opaque;
    virSecretObjPtr obj = payload;

467 468 469 470 471 472
    if (data->error)
        return 0;

    if (data->nuuids >= 0 && data->got == data->nuuids)
        return 0;

473 474 475 476 477
    virObjectLock(obj);

    if (data->filter && !data->filter(data->conn, obj->def))
        goto cleanup;

478 479 480 481 482 483 484 485 486 487
    if (data->uuids) {
        char *uuidstr;

        if (VIR_ALLOC_N(uuidstr, VIR_UUID_STRING_BUFLEN) < 0)
            goto cleanup;

        virUUIDFormat(obj->def->uuid, uuidstr);
        data->uuids[data->got] = uuidstr;
    }

488 489 490 491 492 493 494 495 496 497 498 499 500 501
    data->got++;

 cleanup:
    virObjectUnlock(obj);
    return 0;
}


int
virSecretObjListNumOfSecrets(virSecretObjListPtr secrets,
                             virSecretObjListACLFilter filter,
                             virConnectPtr conn)
{
    struct virSecretObjListGetHelperData data = {
502 503
        .conn = conn, .filter = filter, .got = 0,
        .uuids = NULL, .nuuids = -1, .error = false };
504 505 506 507 508 509 510

    virObjectLock(secrets);
    virHashForEach(secrets->objs, virSecretObjListGetHelper, &data);
    virObjectUnlock(secrets);

    return data.got;
}
511 512 513 514 515 516 517 518 519 520


#define MATCH(FLAG) (flags & (FLAG))
static bool
virSecretObjMatchFlags(virSecretObjPtr secret,
                       unsigned int flags)
{
    /* filter by whether it's ephemeral */
    if (MATCH(VIR_CONNECT_LIST_SECRETS_FILTERS_EPHEMERAL) &&
        !((MATCH(VIR_CONNECT_LIST_SECRETS_EPHEMERAL) &&
521
           secret->def->isephemeral) ||
522
          (MATCH(VIR_CONNECT_LIST_SECRETS_NO_EPHEMERAL) &&
523
           !secret->def->isephemeral)))
524 525 526 527 528
        return false;

    /* filter by whether it's private */
    if (MATCH(VIR_CONNECT_LIST_SECRETS_FILTERS_PRIVATE) &&
        !((MATCH(VIR_CONNECT_LIST_SECRETS_PRIVATE) &&
529
           secret->def->isprivate) ||
530
          (MATCH(VIR_CONNECT_LIST_SECRETS_NO_PRIVATE) &&
531
           !secret->def->isprivate)))
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627
        return false;

    return true;
}
#undef MATCH


struct virSecretObjListData {
    virConnectPtr conn;
    virSecretPtr *secrets;
    virSecretObjListACLFilter filter;
    unsigned int flags;
    int nsecrets;
    bool error;
};

static int
virSecretObjListPopulate(void *payload,
                         const void *name ATTRIBUTE_UNUSED,
                         void *opaque)
{
    struct virSecretObjListData *data = opaque;
    virSecretObjPtr obj = payload;
    virSecretPtr secret = NULL;

    if (data->error)
        return 0;

    virObjectLock(obj);

    if (data->filter && !data->filter(data->conn, obj->def))
        goto cleanup;

    if (!virSecretObjMatchFlags(obj, data->flags))
        goto cleanup;

    if (!data->secrets) {
        data->nsecrets++;
        goto cleanup;
    }

    if (!(secret = virGetSecret(data->conn, obj->def->uuid,
                                obj->def->usage_type,
                                virSecretUsageIDForDef(obj->def)))) {
        data->error = true;
        goto cleanup;
    }

    data->secrets[data->nsecrets++] = secret;

 cleanup:
    virObjectUnlock(obj);
    return 0;
}


int
virSecretObjListExport(virConnectPtr conn,
                       virSecretObjListPtr secretobjs,
                       virSecretPtr **secrets,
                       virSecretObjListACLFilter filter,
                       unsigned int flags)
{
    int ret = -1;
    struct virSecretObjListData data = {
        .conn = conn, .secrets = NULL,
        .filter = filter, .flags = flags,
        .nsecrets = 0, .error = false };

    virObjectLock(secretobjs);
    if (secrets &&
        VIR_ALLOC_N(data.secrets, virHashSize(secretobjs->objs) + 1) < 0)
        goto cleanup;

    virHashForEach(secretobjs->objs, virSecretObjListPopulate, &data);

    if (data.error)
        goto cleanup;

    if (data.secrets) {
        /* trim the array to the final size */
        ignore_value(VIR_REALLOC_N(data.secrets, data.nsecrets + 1));
        *secrets = data.secrets;
        data.secrets = NULL;
    }

    ret = data.nsecrets;

 cleanup:
    virObjectUnlock(secretobjs);
    while (data.secrets && data.nsecrets)
        virObjectUnref(data.secrets[--data.nsecrets]);

    VIR_FREE(data.secrets);
    return ret;
}
628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658


int
virSecretObjListGetUUIDs(virSecretObjListPtr secrets,
                         char **uuids,
                         int nuuids,
                         virSecretObjListACLFilter filter,
                         virConnectPtr conn)
{
    int ret = -1;

    struct virSecretObjListGetHelperData data = {
        .conn = conn, .filter = filter, .got = 0,
        .uuids = uuids, .nuuids = nuuids, .error = false };

    virObjectLock(secrets);
    virHashForEach(secrets->objs, virSecretObjListGetHelper, &data);
    virObjectUnlock(secrets);

    if (data.error)
        goto cleanup;

    ret = data.got;

 cleanup:
    if (ret < 0) {
        while (data.got)
            VIR_FREE(data.uuids[--data.got]);
    }
    return ret;
}
659 660


661 662 663
int
virSecretObjDeleteConfig(virSecretObjPtr secret)
{
664
    if (!secret->def->isephemeral &&
665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
        unlink(secret->configFile) < 0 && errno != ENOENT) {
        virReportSystemError(errno, _("cannot unlink '%s'"),
                             secret->configFile);
        return -1;
    }

    return 0;
}


void
virSecretObjDeleteData(virSecretObjPtr secret)
{
    /* The configFile will already be removed, so secret won't be
     * loaded again if this fails */
    (void)unlink(secret->base64File);
}


684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733
/* Permanent secret storage */

/* Secrets are stored in virSecretDriverStatePtr->configDir.  Each secret
   has virSecretDef stored as XML in "$basename.xml".  If a value of the
   secret is defined, it is stored as base64 (with no formatting) in
   "$basename.base64".  "$basename" is in both cases the base64-encoded UUID. */

static int
virSecretRewriteFile(int fd,
                     void *opaque)
{
    char *data = opaque;

    if (safewrite(fd, data, strlen(data)) < 0)
        return -1;

    return 0;
}


int
virSecretObjSaveConfig(virSecretObjPtr secret)
{
    char *xml = NULL;
    int ret = -1;

    if (!(xml = virSecretDefFormat(secret->def)))
        goto cleanup;

    if (virFileRewrite(secret->configFile, S_IRUSR | S_IWUSR,
                       virSecretRewriteFile, xml) < 0)
        goto cleanup;

    ret = 0;

 cleanup:
    VIR_FREE(xml);
    return ret;
}


int
virSecretObjSaveData(virSecretObjPtr secret)
{
    char *base64 = NULL;
    int ret = -1;

    if (!secret->value)
        return 0;

734
    if (!(base64 = virStringEncodeBase64(secret->value, secret->value_size)))
735 736 737 738 739 740 741 742 743 744 745 746 747 748
        goto cleanup;

    if (virFileRewrite(secret->base64File, S_IRUSR | S_IWUSR,
                       virSecretRewriteFile, base64) < 0)
        goto cleanup;

    ret = 0;

 cleanup:
    VIR_FREE(base64);
    return ret;
}


749 750 751 752 753 754 755 756 757 758 759 760 761 762 763
virSecretDefPtr
virSecretObjGetDef(virSecretObjPtr secret)
{
    return secret->def;
}


void
virSecretObjSetDef(virSecretObjPtr secret,
                   virSecretDefPtr def)
{
    secret->def = def;
}


764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803
unsigned char *
virSecretObjGetValue(virSecretObjPtr secret)
{
    unsigned char *ret = NULL;

    if (!secret->value) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(secret->def->uuid, uuidstr);
        virReportError(VIR_ERR_NO_SECRET,
                       _("secret '%s' does not have a value"), uuidstr);
        goto cleanup;
    }

    if (VIR_ALLOC_N(ret, secret->value_size) < 0)
        goto cleanup;
    memcpy(ret, secret->value, secret->value_size);

 cleanup:
    return ret;
}


int
virSecretObjSetValue(virSecretObjPtr secret,
                     const unsigned char *value,
                     size_t value_size)
{
    unsigned char *old_value, *new_value;
    size_t old_value_size;

    if (VIR_ALLOC_N(new_value, value_size) < 0)
        return -1;

    old_value = secret->value;
    old_value_size = secret->value_size;

    memcpy(new_value, value, value_size);
    secret->value = new_value;
    secret->value_size = value_size;

804
    if (!secret->def->isephemeral && virSecretObjSaveData(secret) < 0)
805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
        goto error;

    /* Saved successfully - drop old value */
    if (old_value) {
        memset(old_value, 0, old_value_size);
        VIR_FREE(old_value);
    }

    return 0;

 error:
    /* Error - restore previous state and free new value */
    secret->value = old_value;
    secret->value_size = old_value_size;
    memset(new_value, 0, value_size);
    VIR_FREE(new_value);
    return -1;
}


size_t
virSecretObjGetValueSize(virSecretObjPtr secret)
{
    return secret->value_size;
}


void
virSecretObjSetValueSize(virSecretObjPtr secret,
                         size_t value_size)
{
    secret->value_size = value_size;
}


840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
static int
virSecretLoadValidateUUID(virSecretDefPtr def,
                          const char *file)
{
    char uuidstr[VIR_UUID_STRING_BUFLEN];

    virUUIDFormat(def->uuid, uuidstr);

    if (!virFileMatchesNameSuffix(file, uuidstr, ".xml")) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("<uuid> does not match secret file name '%s'"),
                       file);
        return -1;
    }

    return 0;
}


static int
virSecretLoadValue(virSecretObjPtr secret)
{
    int ret = -1, fd = -1;
    struct stat st;
    char *contents = NULL, *value = NULL;
    size_t value_size;

    if ((fd = open(secret->base64File, O_RDONLY)) == -1) {
        if (errno == ENOENT) {
            ret = 0;
            goto cleanup;
        }
        virReportSystemError(errno, _("cannot open '%s'"),
                             secret->base64File);
        goto cleanup;
    }

    if (fstat(fd, &st) < 0) {
        virReportSystemError(errno, _("cannot stat '%s'"),
                             secret->base64File);
        goto cleanup;
    }

    if ((size_t)st.st_size != st.st_size) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("'%s' file does not fit in memory"),
                       secret->base64File);
        goto cleanup;
    }

    if (VIR_ALLOC_N(contents, st.st_size) < 0)
        goto cleanup;

    if (saferead(fd, contents, st.st_size) != st.st_size) {
        virReportSystemError(errno, _("cannot read '%s'"),
                             secret->base64File);
        goto cleanup;
    }

    VIR_FORCE_CLOSE(fd);

    if (!base64_decode_alloc(contents, st.st_size, &value, &value_size)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("invalid base64 in '%s'"),
                       secret->base64File);
        goto cleanup;
    }
    if (value == NULL)
        goto cleanup;

    secret->value = (unsigned char *)value;
    value = NULL;
    secret->value_size = value_size;

    ret = 0;

 cleanup:
    if (value != NULL) {
        memset(value, 0, value_size);
        VIR_FREE(value);
    }
    if (contents != NULL) {
        memset(contents, 0, st.st_size);
        VIR_FREE(contents);
    }
    VIR_FORCE_CLOSE(fd);
    return ret;
}


static virSecretObjPtr
virSecretLoad(virSecretObjListPtr secrets,
              const char *file,
              const char *path,
              const char *configDir)
{
    virSecretDefPtr def = NULL;
    virSecretObjPtr secret = NULL, ret = NULL;

    if (!(def = virSecretDefParseFile(path)))
        goto cleanup;

    if (virSecretLoadValidateUUID(def, file) < 0)
        goto cleanup;

    if (!(secret = virSecretObjListAdd(secrets, def, configDir, NULL)))
        goto cleanup;
    def = NULL;

    if (virSecretLoadValue(secret) < 0)
        goto cleanup;

    ret = secret;
    secret = NULL;

 cleanup:
    if (secret)
        virSecretObjListRemove(secrets, secret);
    virSecretDefFree(def);
    return ret;
}


int
virSecretLoadAllConfigs(virSecretObjListPtr secrets,
                        const char *configDir)
{
    DIR *dir = NULL;
    struct dirent *de;

    if (!(dir = opendir(configDir))) {
        if (errno == ENOENT)
            return 0;
        virReportSystemError(errno, _("cannot open '%s'"), configDir);
        return -1;
    }

    /* Ignore errors reported by readdir or other calls within the
     * loop (if any).  It's better to keep the secrets we managed to find. */
    while (virDirRead(dir, &de, NULL) > 0) {
        char *path;
        virSecretObjPtr secret;

        if (STREQ(de->d_name, ".") || STREQ(de->d_name, ".."))
            continue;

        if (!virFileHasSuffix(de->d_name, ".xml"))
            continue;

        if (!(path = virFileBuildPath(configDir, de->d_name, NULL)))
            continue;

        if (!(secret = virSecretLoad(secrets, de->d_name, path, configDir))) {
            virErrorPtr err = virGetLastError();

            VIR_ERROR(_("Error reading secret: %s"),
                      err != NULL ? err->message: _("unknown error"));
            virResetError(err);
            VIR_FREE(path);
            continue;
        }

        VIR_FREE(path);
        virSecretObjEndAPI(&secret);
    }

    closedir(dir);
    return 0;
}