virsecretobj.c 23.3 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
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)

89
static virSecretObjPtr
90 91
virSecretObjNew(void)
{
92
    virSecretObjPtr obj;
93 94 95 96

    if (virSecretObjInitialize() < 0)
        return NULL;

97
    if (!(obj = virObjectLockableNew(virSecretObjClass)))
98 99
        return NULL;

100
    virObjectLock(obj);
101

102
    return obj;
103 104 105 106
}


void
107
virSecretObjEndAPI(virSecretObjPtr *obj)
108
{
109
    if (!*obj)
110 111
        return;

112 113 114
    virObjectUnlock(*obj);
    virObjectUnref(*obj);
    *obj = NULL;
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
}


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
139
virSecretObjDispose(void *opaque)
140
{
141
    virSecretObjPtr obj = opaque;
142

143 144
    virSecretDefFree(obj->def);
    if (obj->value) {
145
        /* Wipe before free to ensure we don't leave a secret on the heap */
146 147
        memset(obj->value, 0, obj->value_size);
        VIR_FREE(obj->value);
148
    }
149 150
    VIR_FREE(obj->configFile);
    VIR_FREE(obj->base64File);
151 152 153 154 155 156 157 158 159 160
}


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

    virHashFree(secrets->objs);
}
161 162 163 164 165 166 167 168 169 170 171


/**
 * 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.
 */
172
static virSecretObjPtr
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
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)
{
198
    virSecretObjPtr obj;
199 200

    virObjectLock(secrets);
201
    obj = virSecretObjListFindByUUIDLocked(secrets, uuid);
202
    virObjectUnlock(secrets);
203 204 205
    if (obj)
        virObjectLock(obj);
    return obj;
206 207 208 209 210 211 212 213
}


static int
virSecretObjSearchName(const void *payload,
                       const void *name ATTRIBUTE_UNUSED,
                       const void *opaque)
{
214
    virSecretObjPtr obj = (virSecretObjPtr) payload;
215
    virSecretDefPtr def;
216 217 218
    struct virSecretSearchData *data = (struct virSecretSearchData *) opaque;
    int found = 0;

219
    virObjectLock(obj);
220
    def = obj->def;
221

222
    if (def->usage_type != data->usageType)
223 224
        goto cleanup;

225
    if (data->usageType != VIR_SECRET_USAGE_TYPE_NONE &&
226
        STREQ(def->usage_id, data->usageID))
227
        found = 1;
228 229

 cleanup:
230
    virObjectUnlock(obj);
231 232 233 234 235 236 237 238 239 240 241 242 243 244
    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.
 */
245
static virSecretObjPtr
246 247 248 249
virSecretObjListFindByUsageLocked(virSecretObjListPtr secrets,
                                  int usageType,
                                  const char *usageID)
{
250
    virSecretObjPtr obj = NULL;
251 252 253
    struct virSecretSearchData data = { .usageType = usageType,
                                        .usageID = usageID };

254 255 256 257
    obj = virHashSearch(secrets->objs, virSecretObjSearchName, &data);
    if (obj)
        virObjectRef(obj);
    return obj;
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
}


/**
 * 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)
{
277
    virSecretObjPtr obj;
278 279

    virObjectLock(secrets);
280
    obj = virSecretObjListFindByUsageLocked(secrets, usageType, usageID);
281
    virObjectUnlock(secrets);
282 283 284
    if (obj)
        virObjectLock(obj);
    return obj;
285
}
286 287 288 289 290 291 292 293 294 295 296 297 298


/*
 * 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,
299
                       virSecretObjPtr obj)
300 301
{
    char uuidstr[VIR_UUID_STRING_BUFLEN];
302
    virSecretDefPtr def;
303

304 305
    if (!obj)
        return;
306
    def = obj->def;
307

308
    virUUIDFormat(def->uuid, uuidstr);
309 310
    virObjectRef(obj);
    virObjectUnlock(obj);
311 312

    virObjectLock(secrets);
313
    virObjectLock(obj);
314
    virHashRemoveEntry(secrets->objs, uuidstr);
315 316
    virObjectUnlock(obj);
    virObjectUnref(obj);
317 318 319 320 321 322 323
    virObjectUnlock(secrets);
}


/*
 * virSecretObjListAddLocked:
 * @secrets: list of secret objects
324
 * @newdef: new secret definition
325 326 327
 * @configDir: directory to place secret config files
 * @oldDef: Former secret def (e.g. a reload path perhaps)
 *
328
 * Add the new @newdef to the secret obj table hash
329 330 331 332 333
 *
 * This functions requires @secrets to be locked already!
 *
 * Returns pointer to secret or NULL if failure to add
 */
334
static virSecretObjPtr
335
virSecretObjListAddLocked(virSecretObjListPtr secrets,
336
                          virSecretDefPtr newdef,
337 338 339
                          const char *configDir,
                          virSecretDefPtr *oldDef)
{
340
    virSecretObjPtr obj;
341
    virSecretDefPtr def;
342 343 344 345 346 347 348 349
    virSecretObjPtr ret = NULL;
    char uuidstr[VIR_UUID_STRING_BUFLEN];
    char *configFile = NULL, *base64File = NULL;

    if (oldDef)
        *oldDef = NULL;

    /* Is there a secret already matching this UUID */
350 351
    if ((obj = virSecretObjListFindByUUIDLocked(secrets, newdef->uuid))) {
        virObjectLock(obj);
352
        def = obj->def;
353

354 355
        if (STRNEQ_NULLABLE(def->usage_id, newdef->usage_id)) {
            virUUIDFormat(def->uuid, uuidstr);
356 357 358
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("a secret with UUID %s is already defined for "
                             "use with %s"),
359
                           uuidstr, def->usage_id);
360 361 362
            goto cleanup;
        }

363
        if (def->isprivate && !newdef->isprivate) {
364 365 366 367 368 369
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot change private flag on existing secret"));
            goto cleanup;
        }

        if (oldDef)
370
            *oldDef = def;
371
        else
372
            virSecretDefFree(def);
373
        obj->def = newdef;
374 375 376
    } else {
        /* No existing secret with same UUID,
         * try look for matching usage instead */
377 378 379 380
        if ((obj = virSecretObjListFindByUsageLocked(secrets,
                                                     newdef->usage_type,
                                                     newdef->usage_id))) {
            virObjectLock(obj);
381 382
            def = obj->def;
            virUUIDFormat(def->uuid, uuidstr);
383 384 385
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("a secret with UUID %s already defined for "
                             "use with %s"),
386
                           uuidstr, newdef->usage_id);
387 388 389 390 391 392
            goto cleanup;
        }

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

398
        if (!(obj = virSecretObjNew()))
399 400
            goto cleanup;

401
        if (virHashAddEntry(secrets->objs, uuidstr, obj) < 0)
402 403
            goto cleanup;

404 405 406 407
        obj->def = newdef;
        VIR_STEAL_PTR(obj->configFile, configFile);
        VIR_STEAL_PTR(obj->base64File, base64File);
        virObjectRef(obj);
408 409
    }

410 411
    ret = obj;
    obj = NULL;
412 413

 cleanup:
414
    virSecretObjEndAPI(&obj);
415 416 417 418 419 420 421 422
    VIR_FREE(configFile);
    VIR_FREE(base64File);
    return ret;
}


virSecretObjPtr
virSecretObjListAdd(virSecretObjListPtr secrets,
423
                    virSecretDefPtr newdef,
424 425 426
                    const char *configDir,
                    virSecretDefPtr *oldDef)
{
427
    virSecretObjPtr obj;
428 429

    virObjectLock(secrets);
430
    obj = virSecretObjListAddLocked(secrets, newdef, configDir, oldDef);
431
    virObjectUnlock(secrets);
432
    return obj;
433
}
434 435 436 437 438 439


struct virSecretObjListGetHelperData {
    virConnectPtr conn;
    virSecretObjListACLFilter filter;
    int got;
440 441 442
    char **uuids;
    int nuuids;
    bool error;
443 444 445 446 447 448 449 450 451 452
};


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

455 456 457 458 459 460
    if (data->error)
        return 0;

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

461
    virObjectLock(obj);
462
    def = obj->def;
463

464
    if (data->filter && !data->filter(data->conn, def))
465 466
        goto cleanup;

467 468 469
    if (data->uuids) {
        char *uuidstr;

470 471
        if (VIR_ALLOC_N(uuidstr, VIR_UUID_STRING_BUFLEN) < 0) {
            data->error = true;
472
            goto cleanup;
473
        }
474

475
        virUUIDFormat(def->uuid, uuidstr);
476 477 478
        data->uuids[data->got] = uuidstr;
    }

479 480 481 482 483 484 485 486 487 488 489 490 491 492
    data->got++;

 cleanup:
    virObjectUnlock(obj);
    return 0;
}


int
virSecretObjListNumOfSecrets(virSecretObjListPtr secrets,
                             virSecretObjListACLFilter filter,
                             virConnectPtr conn)
{
    struct virSecretObjListGetHelperData data = {
493 494
        .conn = conn, .filter = filter, .got = 0,
        .uuids = NULL, .nuuids = -1, .error = false };
495 496 497 498 499 500 501

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

    return data.got;
}
502 503 504 505


#define MATCH(FLAG) (flags & (FLAG))
static bool
506
virSecretObjMatchFlags(virSecretObjPtr obj,
507 508
                       unsigned int flags)
{
509 510
    virSecretDefPtr def = obj->def;

511 512 513
    /* filter by whether it's ephemeral */
    if (MATCH(VIR_CONNECT_LIST_SECRETS_FILTERS_EPHEMERAL) &&
        !((MATCH(VIR_CONNECT_LIST_SECRETS_EPHEMERAL) &&
514
           def->isephemeral) ||
515
          (MATCH(VIR_CONNECT_LIST_SECRETS_NO_EPHEMERAL) &&
516
           !def->isephemeral)))
517 518 519 520 521
        return false;

    /* filter by whether it's private */
    if (MATCH(VIR_CONNECT_LIST_SECRETS_FILTERS_PRIVATE) &&
        !((MATCH(VIR_CONNECT_LIST_SECRETS_PRIVATE) &&
522
           def->isprivate) ||
523
          (MATCH(VIR_CONNECT_LIST_SECRETS_NO_PRIVATE) &&
524
           !def->isprivate)))
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
        return false;

    return true;
}
#undef MATCH


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

static int
542 543 544
virSecretObjListExportCallback(void *payload,
                               const void *name ATTRIBUTE_UNUSED,
                               void *opaque)
545 546 547
{
    struct virSecretObjListData *data = opaque;
    virSecretObjPtr obj = payload;
548
    virSecretDefPtr def;
549 550 551 552 553 554
    virSecretPtr secret = NULL;

    if (data->error)
        return 0;

    virObjectLock(obj);
555
    def = obj->def;
556

557
    if (data->filter && !data->filter(data->conn, def))
558 559 560 561 562 563 564 565 566 567
        goto cleanup;

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

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

568 569 570
    if (!(secret = virGetSecret(data->conn, def->uuid,
                                def->usage_type,
                                def->usage_id))) {
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
        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)
{
    struct virSecretObjListData data = {
        .conn = conn, .secrets = NULL,
        .filter = filter, .flags = flags,
        .nsecrets = 0, .error = false };

    virObjectLock(secretobjs);
    if (secrets &&
597 598 599 600
        VIR_ALLOC_N(data.secrets, virHashSize(secretobjs->objs) + 1) < 0) {
        virObjectUnlock(secretobjs);
        return -1;
    }
601

602 603
    virHashForEach(secretobjs->objs, virSecretObjListExportCallback, &data);
    virObjectUnlock(secretobjs);
604 605

    if (data.error)
606
        goto error;
607 608 609 610 611 612 613

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

614
    return data.nsecrets;
615

616 617 618
 error:
    virObjectListFree(data.secrets);
    return -1;
619
}
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650


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


653
int
654
virSecretObjDeleteConfig(virSecretObjPtr obj)
655
{
656 657 658
    virSecretDefPtr def = obj->def;

    if (!def->isephemeral &&
659
        unlink(obj->configFile) < 0 && errno != ENOENT) {
660
        virReportSystemError(errno, _("cannot unlink '%s'"),
661
                             obj->configFile);
662 663 664 665 666 667 668 669
        return -1;
    }

    return 0;
}


void
670
virSecretObjDeleteData(virSecretObjPtr obj)
671 672 673
{
    /* The configFile will already be removed, so secret won't be
     * loaded again if this fails */
674
    (void)unlink(obj->base64File);
675 676 677
}


678 679 680 681 682 683 684
/* 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. */
int
685
virSecretObjSaveConfig(virSecretObjPtr obj)
686 687 688 689
{
    char *xml = NULL;
    int ret = -1;

690
    if (!(xml = virSecretDefFormat(obj->def)))
691 692
        goto cleanup;

693
    if (virFileRewriteStr(obj->configFile, S_IRUSR | S_IWUSR, xml) < 0)
694 695 696 697 698 699 700 701 702 703 704
        goto cleanup;

    ret = 0;

 cleanup:
    VIR_FREE(xml);
    return ret;
}


int
705
virSecretObjSaveData(virSecretObjPtr obj)
706 707 708 709
{
    char *base64 = NULL;
    int ret = -1;

710
    if (!obj->value)
711 712
        return 0;

713
    if (!(base64 = virStringEncodeBase64(obj->value, obj->value_size)))
714 715
        goto cleanup;

716
    if (virFileRewriteStr(obj->base64File, S_IRUSR | S_IWUSR, base64) < 0)
717 718 719 720 721 722 723 724 725 726
        goto cleanup;

    ret = 0;

 cleanup:
    VIR_FREE(base64);
    return ret;
}


727
virSecretDefPtr
728
virSecretObjGetDef(virSecretObjPtr obj)
729
{
730
    return obj->def;
731 732 733 734
}


void
735
virSecretObjSetDef(virSecretObjPtr obj,
736 737
                   virSecretDefPtr def)
{
738
    obj->def = def;
739 740 741
}


742
unsigned char *
743
virSecretObjGetValue(virSecretObjPtr obj)
744
{
745
    virSecretDefPtr def = obj->def;
746 747
    unsigned char *ret = NULL;

748
    if (!obj->value) {
749
        char uuidstr[VIR_UUID_STRING_BUFLEN];
750
        virUUIDFormat(def->uuid, uuidstr);
751 752 753 754 755
        virReportError(VIR_ERR_NO_SECRET,
                       _("secret '%s' does not have a value"), uuidstr);
        goto cleanup;
    }

756
    if (VIR_ALLOC_N(ret, obj->value_size) < 0)
757
        goto cleanup;
758
    memcpy(ret, obj->value, obj->value_size);
759 760 761 762 763 764 765

 cleanup:
    return ret;
}


int
766
virSecretObjSetValue(virSecretObjPtr obj,
767 768 769
                     const unsigned char *value,
                     size_t value_size)
{
770
    virSecretDefPtr def = obj->def;
771 772 773 774 775 776
    unsigned char *old_value, *new_value;
    size_t old_value_size;

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

777 778
    old_value = obj->value;
    old_value_size = obj->value_size;
779 780

    memcpy(new_value, value, value_size);
781 782
    obj->value = new_value;
    obj->value_size = value_size;
783

784
    if (!def->isephemeral && virSecretObjSaveData(obj) < 0)
785 786 787 788 789 790 791 792 793 794 795 796
        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 */
797 798
    obj->value = old_value;
    obj->value_size = old_value_size;
799 800 801 802 803 804 805
    memset(new_value, 0, value_size);
    VIR_FREE(new_value);
    return -1;
}


size_t
806
virSecretObjGetValueSize(virSecretObjPtr obj)
807
{
808
    return obj->value_size;
809 810 811 812
}


void
813
virSecretObjSetValueSize(virSecretObjPtr obj,
814 815
                         size_t value_size)
{
816
    obj->value_size = value_size;
817 818 819
}


820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
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
840
virSecretLoadValue(virSecretObjPtr obj)
841 842 843 844 845 846
{
    int ret = -1, fd = -1;
    struct stat st;
    char *contents = NULL, *value = NULL;
    size_t value_size;

847
    if ((fd = open(obj->base64File, O_RDONLY)) == -1) {
848 849 850 851 852
        if (errno == ENOENT) {
            ret = 0;
            goto cleanup;
        }
        virReportSystemError(errno, _("cannot open '%s'"),
853
                             obj->base64File);
854 855 856 857 858
        goto cleanup;
    }

    if (fstat(fd, &st) < 0) {
        virReportSystemError(errno, _("cannot stat '%s'"),
859
                             obj->base64File);
860 861 862 863 864 865
        goto cleanup;
    }

    if ((size_t)st.st_size != st.st_size) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("'%s' file does not fit in memory"),
866
                       obj->base64File);
867 868 869 870 871 872 873 874
        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'"),
875
                             obj->base64File);
876 877 878 879 880 881 882 883
        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'"),
884
                       obj->base64File);
885 886 887 888 889
        goto cleanup;
    }
    if (value == NULL)
        goto cleanup;

890
    obj->value = (unsigned char *)value;
891
    value = NULL;
892
    obj->value_size = value_size;
893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916

    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;
917 918
    virSecretObjPtr obj = NULL;
    virSecretObjPtr ret = NULL;
919 920 921 922 923 924 925

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

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

926
    if (!(obj = virSecretObjListAdd(secrets, def, configDir, NULL)))
927 928 929
        goto cleanup;
    def = NULL;

930
    if (virSecretLoadValue(obj) < 0)
931 932
        goto cleanup;

933 934
    ret = obj;
    obj = NULL;
935 936

 cleanup:
937
    virSecretObjListRemove(secrets, obj);
938 939 940 941 942 943 944 945 946 947 948
    virSecretDefFree(def);
    return ret;
}


int
virSecretLoadAllConfigs(virSecretObjListPtr secrets,
                        const char *configDir)
{
    DIR *dir = NULL;
    struct dirent *de;
J
Ján Tomko 已提交
949
    int rc;
950

J
Ján Tomko 已提交
951 952
    if ((rc = virDirOpenIfExists(&dir, configDir)) <= 0)
        return rc;
953 954 955 956 957

    /* 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;
958
        virSecretObjPtr obj;
959 960 961 962 963 964 965

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

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

966
        if (!(obj = virSecretLoad(secrets, de->d_name, path, configDir))) {
967
            VIR_ERROR(_("Error reading secret: %s"),
968
                      virGetLastErrorMessage());
969 970 971 972 973
            VIR_FREE(path);
            continue;
        }

        VIR_FREE(path);
974
        virSecretObjEndAPI(&obj);
975 976
    }

J
Ján Tomko 已提交
977
    VIR_DIR_CLOSE(dir);
978 979
    return 0;
}