secret_driver.c 28.0 KB
Newer Older
1 2 3
/*
 * secret_driver.c: local driver for secret manipulation API
 *
4
 * Copyright (C) 2009-2016 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16
 *
 * 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
17
 * License along with this library.  If not, see
O
Osier Yang 已提交
18
 * <http://www.gnu.org/licenses/>.
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
 *
 * Red Hat Author: Miloslav Trmač <mitr@redhat.com>
 */

#include <config.h>

#include <dirent.h>
#include <fcntl.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

#include "internal.h"
#include "base64.h"
#include "datatypes.h"
#include "driver.h"
35
#include "virlog.h"
36
#include "viralloc.h"
37 38
#include "secret_conf.h"
#include "secret_driver.h"
39
#include "virthread.h"
40
#include "viruuid.h"
41
#include "virerror.h"
E
Eric Blake 已提交
42
#include "virfile.h"
43
#include "configmake.h"
44
#include "virstring.h"
45
#include "viraccessapicheck.h"
46 47 48

#define VIR_FROM_THIS VIR_FROM_SECRET

49 50
VIR_LOG_INIT("secret.secret_driver");

51 52
enum { SECRET_MAX_XML_FILE = 10*1024*1024 };

53
/* Internal driver state */
54

J
John Ferlan 已提交
55 56 57 58
typedef struct _virSecretObj virSecretObj;
typedef virSecretObj *virSecretObjPtr;
struct _virSecretObj {
    virSecretObjPtr next;
59
    char *configFile;
60
    char *base64File;
61 62 63 64 65 66 67 68 69
    virSecretDefPtr def;
    unsigned char *value;       /* May be NULL */
    size_t value_size;
};

typedef struct _virSecretDriverState virSecretDriverState;
typedef virSecretDriverState *virSecretDriverStatePtr;
struct _virSecretDriverState {
    virMutex lock;
J
John Ferlan 已提交
70
    virSecretObj *secrets;
71
    char *configDir;
72 73
};

74
static virSecretDriverStatePtr driver;
75 76

static void
77
secretDriverLock(void)
78 79 80 81 82
{
    virMutexLock(&driver->lock);
}

static void
83
secretDriverUnlock(void)
84 85 86 87
{
    virMutexUnlock(&driver->lock);
}

J
John Ferlan 已提交
88 89
static virSecretObjPtr
listUnlink(virSecretObjPtr *pptr)
90
{
J
John Ferlan 已提交
91
    virSecretObjPtr secret;
92 93 94 95 96 97 98

    secret = *pptr;
    *pptr = secret->next;
    return secret;
}

static void
J
John Ferlan 已提交
99 100
listInsert(virSecretObjPtr *pptr,
           virSecretObjPtr secret)
101 102 103 104 105 106
{
    secret->next = *pptr;
    *pptr = secret;
}

static void
J
John Ferlan 已提交
107
secretFree(virSecretObjPtr secret)
108 109 110 111 112 113 114 115 116
{
    if (secret == NULL)
        return;

    virSecretDefFree(secret->def);
    if (secret->value != NULL) {
        memset(secret->value, 0, secret->value_size);
        VIR_FREE(secret->value);
    }
117
    VIR_FREE(secret->configFile);
118
    VIR_FREE(secret->base64File);
119 120 121
    VIR_FREE(secret);
}

J
John Ferlan 已提交
122
static virSecretObjPtr
123
secretFindByUUID(const unsigned char *uuid)
124
{
125
    virSecretObjPtr *pptr, secret;
126

127 128 129 130
    for (pptr = &driver->secrets; *pptr != NULL; pptr = &secret->next) {
        secret = *pptr;
        if (memcmp(secret->def->uuid, uuid, VIR_UUID_BUFLEN) == 0)
            return secret;
131 132 133 134
    }
    return NULL;
}

J
John Ferlan 已提交
135
static virSecretObjPtr
136 137
secretFindByUsage(int usageType,
                  const char *usageID)
138
{
139
    virSecretObjPtr *pptr, secret;
140

141 142
    for (pptr = &driver->secrets; *pptr != NULL; pptr = &secret->next) {
        secret = *pptr;
143

144
        if (secret->def->usage_type != usageType)
145
            continue;
146

147 148 149 150
        switch (usageType) {
        case VIR_SECRET_USAGE_TYPE_NONE:
            /* never match this */
            break;
151

152
        case VIR_SECRET_USAGE_TYPE_VOLUME:
153 154
            if (STREQ(secret->def->usage.volume, usageID))
                return secret;
155
            break;
S
Sage Weil 已提交
156 157

        case VIR_SECRET_USAGE_TYPE_CEPH:
158 159
            if (STREQ(secret->def->usage.ceph, usageID))
                return secret;
S
Sage Weil 已提交
160
            break;
161 162

        case VIR_SECRET_USAGE_TYPE_ISCSI:
163 164
            if (STREQ(secret->def->usage.target, usageID))
                return secret;
165
            break;
166
        }
167
    }
168
    return NULL;
169 170
}

171
/* Permament secret storage */
172

173
/* Secrets are stored in virSecretDriverStatePtr->configDir.  Each secret
174 175 176 177 178
   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
179 180
secretRewriteFile(int fd,
                  void *opaque)
181
{
182
    char *data = opaque;
183

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

187
    return 0;
188 189 190 191
}


static int
192
secretEnsureDirectory(void)
193
{
194
    if (mkdir(driver->configDir, S_IRWXU) < 0 && errno != EEXIST) {
195
        virReportSystemError(errno, _("cannot create '%s'"),
196
                             driver->configDir);
197 198 199 200 201 202
        return -1;
    }
    return 0;
}

static int
J
John Ferlan 已提交
203
secretSaveDef(const virSecretObj *secret)
204
{
205
    char *xml = NULL;
206 207
    int ret = -1;

208
    if (secretEnsureDirectory() < 0)
209 210
        goto cleanup;

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

214
    if (virFileRewrite(secret->configFile, S_IRUSR | S_IWUSR,
215
                       secretRewriteFile, xml) < 0)
216 217 218 219
        goto cleanup;

    ret = 0;

220
 cleanup:
221 222 223 224 225
    VIR_FREE(xml);
    return ret;
}

static int
J
John Ferlan 已提交
226
secretSaveValue(const virSecretObj *secret)
227
{
228
    char *base64 = NULL;
229 230 231 232 233
    int ret = -1;

    if (secret->value == NULL)
        return 0;

234
    if (secretEnsureDirectory() < 0)
235 236 237 238 239
        goto cleanup;

    base64_encode_alloc((const char *)secret->value, secret->value_size,
                        &base64);
    if (base64 == NULL) {
240
        virReportOOMError();
241 242 243
        goto cleanup;
    }

244
    if (virFileRewrite(secret->base64File, S_IRUSR | S_IWUSR,
245
                       secretRewriteFile, base64) < 0)
246 247 248 249
        goto cleanup;

    ret = 0;

250
 cleanup:
251 252 253 254 255
    VIR_FREE(base64);
    return ret;
}

static int
J
John Ferlan 已提交
256
secretDeleteSaved(const virSecretObj *secret)
257
{
258
    if (unlink(secret->configFile) < 0 && errno != ENOENT)
259 260
        return -1;

261 262
    /* When the XML is missing, the rest may waste disk space, but the secret
       won't be loaded again, so we have succeeded already. */
263
    (void)unlink(secret->base64File);
264

265
    return 0;
266 267 268
}

static int
269
secretLoadValidateUUID(virSecretDefPtr def,
270
                       const char *file)
271
{
272
    char uuidstr[VIR_UUID_STRING_BUFLEN];
273

274
    virUUIDFormat(def->uuid, uuidstr);
275

276
    if (!virFileMatchesNameSuffix(file, uuidstr, ".xml")) {
277 278
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("<uuid> does not match secret file name '%s'"),
279
                       file);
280 281 282 283 284 285 286
        return -1;
    }

    return 0;
}

static int
J
John Ferlan 已提交
287
secretLoadValue(virSecretObjPtr secret)
288 289 290
{
    int ret = -1, fd = -1;
    struct stat st;
291
    char *contents = NULL, *value = NULL;
292 293
    size_t value_size;

294
    if ((fd = open(secret->base64File, O_RDONLY)) == -1) {
295 296 297 298
        if (errno == ENOENT) {
            ret = 0;
            goto cleanup;
        }
299 300
        virReportSystemError(errno, _("cannot open '%s'"),
                             secret->base64File);
301 302
        goto cleanup;
    }
303

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

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

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

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

326
    VIR_FORCE_CLOSE(fd);
327 328

    if (!base64_decode_alloc(contents, st.st_size, &value, &value_size)) {
329
        virReportError(VIR_ERR_INTERNAL_ERROR,
330 331
                       _("invalid base64 in '%s'"),
                       secret->base64File);
332 333
        goto cleanup;
    }
334
    if (value == NULL)
335 336 337 338 339 340 341 342
        goto cleanup;

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

    ret = 0;

343
 cleanup:
344 345 346 347 348 349 350 351
    if (value != NULL) {
        memset(value, 0, value_size);
        VIR_FREE(value);
    }
    if (contents != NULL) {
        memset(contents, 0, st.st_size);
        VIR_FREE(contents);
    }
352
    VIR_FORCE_CLOSE(fd);
353 354 355
    return ret;
}

J
John Ferlan 已提交
356
static virSecretObjPtr
357
secretLoad(const char *file,
358 359
           const char *path,
           const char *base64path)
360
{
361
    virSecretDefPtr def = NULL;
J
John Ferlan 已提交
362
    virSecretObjPtr secret = NULL, ret = NULL;
363

364
    if (!(def = virSecretDefParseFile(path)))
365
        goto cleanup;
366

367
    if (secretLoadValidateUUID(def, file) < 0)
368 369
        goto cleanup;

370
    if (VIR_ALLOC(secret) < 0)
371 372 373 374
        goto cleanup;
    secret->def = def;
    def = NULL;

375 376 377
    if (VIR_STRDUP(secret->configFile, path) < 0)
        goto cleanup;

378 379 380
    if (VIR_STRDUP(secret->base64File, base64path) < 0)
        goto cleanup;

381
    if (secretLoadValue(secret) < 0)
382 383 384 385 386
        goto cleanup;

    ret = secret;
    secret = NULL;

387
 cleanup:
388 389 390 391 392 393
    secretFree(secret);
    virSecretDefFree(def);
    return ret;
}

static int
J
John Ferlan 已提交
394
loadSecrets(virSecretObjPtr *dest)
395 396 397
{
    DIR *dir = NULL;
    struct dirent *de;
J
John Ferlan 已提交
398
    virSecretObjPtr list = NULL;
399

400
    if (!(dir = opendir(driver->configDir))) {
401 402
        if (errno == ENOENT)
            return 0;
403
        virReportSystemError(errno, _("cannot open '%s'"),
404
                             driver->configDir);
405
        return -1;
406
    }
407

E
Eric Blake 已提交
408
    while (virDirRead(dir, &de, NULL) > 0) {
409
        char *path, *base64name, *base64path;
J
John Ferlan 已提交
410
        virSecretObjPtr secret;
411 412 413

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

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

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

421 422 423 424 425 426 427 428 429 430 431 432
        /* Copy the .xml file name, but use suffix ".base64" instead */
        if (VIR_STRDUP(base64name, de->d_name) < 0 ||
            !virFileStripSuffix(base64name, ".xml") ||
            !(base64path = virFileBuildPath(driver->configDir,
                                            base64name, ".base64"))) {
            VIR_FREE(path);
            VIR_FREE(base64name);
            continue;
        }
        VIR_FREE(base64name);

        if (!(secret = secretLoad(de->d_name, path, base64path))) {
433 434
            virErrorPtr err = virGetLastError();

435
            VIR_ERROR(_("Error reading secret: %s"),
436
                      err != NULL ? err->message: _("unknown error"));
437
            virResetError(err);
438
            VIR_FREE(path);
439
            VIR_FREE(base64path);
440 441
            continue;
        }
442

443
        VIR_FREE(path);
444
        VIR_FREE(base64path);
445 446
        listInsert(&list, secret);
    }
E
Eric Blake 已提交
447
    /* Ignore error reported by readdir, if any.  It's better to keep the
448 449 450
       secrets we managed to find. */

    while (list != NULL) {
451
        virSecretObjPtr secret;
452

453 454
        secret = listUnlink(&list);
        listInsert(dest, secret);
455 456
    }

457 458
    closedir(dir);
    return 0;
459 460
}

461
/* Driver functions */
462 463

static int
464
secretConnectNumOfSecrets(virConnectPtr conn)
465
{
466
    size_t i;
J
John Ferlan 已提交
467
    virSecretObjPtr secret;
468

469 470 471
    if (virConnectNumOfSecretsEnsureACL(conn) < 0)
        return -1;

472
    secretDriverLock();
473 474

    i = 0;
475 476 477 478 479
    for (secret = driver->secrets; secret != NULL; secret = secret->next) {
        if (virConnectNumOfSecretsCheckACL(conn,
                                           secret->def))
            i++;
    }
480

481
    secretDriverUnlock();
482 483 484 485
    return i;
}

static int
486 487 488
secretConnectListSecrets(virConnectPtr conn,
                         char **uuids,
                         int maxuuids)
489
{
490
    size_t i;
J
John Ferlan 已提交
491
    virSecretObjPtr secret;
492 493 494

    memset(uuids, 0, maxuuids * sizeof(*uuids));

495 496 497
    if (virConnectListSecretsEnsureACL(conn) < 0)
        return -1;

498
    secretDriverLock();
499 500 501

    i = 0;
    for (secret = driver->secrets; secret != NULL; secret = secret->next) {
502
        char *uuidstr;
503 504 505
        if (!virConnectListSecretsCheckACL(conn,
                                           secret->def))
            continue;
506 507
        if (i == maxuuids)
            break;
508
        if (VIR_ALLOC_N(uuidstr, VIR_UUID_STRING_BUFLEN) < 0)
509
            goto cleanup;
510 511
        virUUIDFormat(secret->def->uuid, uuidstr);
        uuids[i] = uuidstr;
512 513 514
        i++;
    }

515
    secretDriverUnlock();
516 517
    return i;

518
 cleanup:
519
    secretDriverUnlock();
520 521 522 523 524 525 526

    for (i = 0; i < maxuuids; i++)
        VIR_FREE(uuids[i]);

    return -1;
}

527 528 529 530 531 532 533 534 535 536
static const char *
secretUsageIDForDef(virSecretDefPtr def)
{
    switch (def->usage_type) {
    case VIR_SECRET_USAGE_TYPE_NONE:
        return "";

    case VIR_SECRET_USAGE_TYPE_VOLUME:
        return def->usage.volume;

S
Sage Weil 已提交
537 538 539
    case VIR_SECRET_USAGE_TYPE_CEPH:
        return def->usage.ceph;

540 541 542
    case VIR_SECRET_USAGE_TYPE_ISCSI:
        return def->usage.target;

543 544 545 546 547
    default:
        return NULL;
    }
}

O
Osier Yang 已提交
548 549
#define MATCH(FLAG) (flags & (FLAG))
static int
550 551
secretConnectListAllSecrets(virConnectPtr conn,
                            virSecretPtr **secrets,
552 553
                            unsigned int flags)
{
O
Osier Yang 已提交
554 555 556
    virSecretPtr *tmp_secrets = NULL;
    int nsecrets = 0;
    int ret_nsecrets = 0;
557
    virSecretObjPtr secret = NULL;
558
    size_t i = 0;
O
Osier Yang 已提交
559 560 561 562
    int ret = -1;

    virCheckFlags(VIR_CONNECT_LIST_SECRETS_FILTERS_ALL, -1);

563 564 565
    if (virConnectListAllSecretsEnsureACL(conn) < 0)
        return -1;

566
    secretDriverLock();
O
Osier Yang 已提交
567

568
    for (secret = driver->secrets; secret != NULL; secret = secret->next)
O
Osier Yang 已提交
569 570
        nsecrets++;

571 572
    if (secrets && VIR_ALLOC_N(tmp_secrets, nsecrets + 1) < 0)
        goto cleanup;
O
Osier Yang 已提交
573

574
    for (secret = driver->secrets; secret != NULL; secret = secret->next) {
575
        if (!virConnectListAllSecretsCheckACL(conn,
576
                                              secret->def))
577 578
            continue;

O
Osier Yang 已提交
579 580 581
        /* filter by whether it's ephemeral */
        if (MATCH(VIR_CONNECT_LIST_SECRETS_FILTERS_EPHEMERAL) &&
            !((MATCH(VIR_CONNECT_LIST_SECRETS_EPHEMERAL) &&
582
               secret->def->ephemeral) ||
O
Osier Yang 已提交
583
              (MATCH(VIR_CONNECT_LIST_SECRETS_NO_EPHEMERAL) &&
584
               !secret->def->ephemeral)))
O
Osier Yang 已提交
585 586 587 588 589
            continue;

        /* filter by whether it's private */
        if (MATCH(VIR_CONNECT_LIST_SECRETS_FILTERS_PRIVATE) &&
            !((MATCH(VIR_CONNECT_LIST_SECRETS_PRIVATE) &&
590
               secret->def->private) ||
O
Osier Yang 已提交
591
              (MATCH(VIR_CONNECT_LIST_SECRETS_NO_PRIVATE) &&
592
               !secret->def->private)))
O
Osier Yang 已提交
593 594 595
            continue;

        if (secrets) {
596 597
            if (!(tmp_secrets[ret_nsecrets] =
                  virGetSecret(conn,
598 599 600
                               secret->def->uuid,
                               secret->def->usage_type,
                               secretUsageIDForDef(secret->def))))
O
Osier Yang 已提交
601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
                goto cleanup;
        }
        ret_nsecrets++;
    }

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

    ret = ret_nsecrets;

 cleanup:
616
    secretDriverUnlock();
O
Osier Yang 已提交
617
    if (tmp_secrets) {
618 619
        for (i = 0; i < ret_nsecrets; i ++)
            virObjectUnref(tmp_secrets[i]);
O
Osier Yang 已提交
620 621 622 623 624 625 626 627
    }
    VIR_FREE(tmp_secrets);

    return ret;
}
#undef MATCH


628
static virSecretPtr
629 630
secretLookupByUUID(virConnectPtr conn,
                   const unsigned char *uuid)
631 632
{
    virSecretPtr ret = NULL;
J
John Ferlan 已提交
633
    virSecretObjPtr secret;
634

635
    secretDriverLock();
636

637
    if (!(secret = secretFindByUUID(uuid))) {
638 639
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(uuid, uuidstr);
640 641
        virReportError(VIR_ERR_NO_SECRET,
                       _("no secret with matching uuid '%s'"), uuidstr);
642 643 644
        goto cleanup;
    }

645 646 647
    if (virSecretLookupByUUIDEnsureACL(conn, secret->def) < 0)
        goto cleanup;

648 649 650 651 652
    ret = virGetSecret(conn,
                       secret->def->uuid,
                       secret->def->usage_type,
                       secretUsageIDForDef(secret->def));

653
 cleanup:
654
    secretDriverUnlock();
655 656 657 658 659
    return ret;
}


static virSecretPtr
660 661 662
secretLookupByUsage(virConnectPtr conn,
                    int usageType,
                    const char *usageID)
663 664
{
    virSecretPtr ret = NULL;
J
John Ferlan 已提交
665
    virSecretObjPtr secret;
666

667
    secretDriverLock();
668

669
    if (!(secret = secretFindByUsage(usageType, usageID))) {
670 671
        virReportError(VIR_ERR_NO_SECRET,
                       _("no secret with matching usage '%s'"), usageID);
672 673 674
        goto cleanup;
    }

675 676 677
    if (virSecretLookupByUsageEnsureACL(conn, secret->def) < 0)
        goto cleanup;

678 679 680 681
    ret = virGetSecret(conn,
                       secret->def->uuid,
                       secret->def->usage_type,
                       secretUsageIDForDef(secret->def));
682

683
 cleanup:
684
    secretDriverUnlock();
685 686 687 688 689
    return ret;
}


static virSecretPtr
690 691
secretDefineXML(virConnectPtr conn,
                const char *xml,
692
                unsigned int flags)
693 694
{
    virSecretPtr ret = NULL;
J
John Ferlan 已提交
695
    virSecretObjPtr secret;
696 697
    virSecretDefPtr backup = NULL;
    virSecretDefPtr new_attrs;
698

699 700
    virCheckFlags(0, NULL);

701
    if (!(new_attrs = virSecretDefParseString(xml)))
702 703
        return NULL;

704
    secretDriverLock();
705

706 707 708
    if (virSecretDefineXMLEnsureACL(conn, new_attrs) < 0)
        goto cleanup;

709 710 711
    if (!(secret = secretFindByUUID(new_attrs->uuid))) {
        /* No existing secret with same UUID,
         * try look for matching usage instead */
712
        const char *usageID = secretUsageIDForDef(new_attrs);
713 714
        char uuidstr[VIR_UUID_STRING_BUFLEN];

715
        if ((secret = secretFindByUsage(new_attrs->usage_type, usageID))) {
716
            virUUIDFormat(secret->def->uuid, uuidstr);
717
            virReportError(VIR_ERR_INTERNAL_ERROR,
718 719
                           _("a secret with UUID %s already defined for "
                             "use with %s"),
720
                           uuidstr, usageID);
721 722
            goto cleanup;
        }
723

724
        /* No existing secret at all, create one */
725
        if (VIR_ALLOC(secret) < 0)
726
            goto cleanup;
727

728 729 730 731 732 733 734 735 736
        virUUIDFormat(secret->def->uuid, uuidstr);

        /* Generate configFile using driver->configDir,
         * the uuidstr, and .xml suffix */
        if (!(secret->configFile = virFileBuildPath(driver->configDir,
                                                    uuidstr, ".xml"))) {
            secretFree(secret);
            goto cleanup;
        }
737 738 739 740 741 742 743
        /* Generate base64File using driver->configDir,
         * the uuidstr, and .base64 suffix */
        if (!(secret->base64File = virFileBuildPath(driver->configDir,
                                                    uuidstr, ".base64"))) {
            secretFree(secret);
            goto cleanup;
        }
744

745 746 747 748 749 750 751 752
        listInsert(&driver->secrets, secret);
        secret->def = new_attrs;
    } else {
        const char *newUsageID = secretUsageIDForDef(new_attrs);
        const char *oldUsageID = secretUsageIDForDef(secret->def);
        if (STRNEQ(oldUsageID, newUsageID)) {
            char uuidstr[VIR_UUID_STRING_BUFLEN];
            virUUIDFormat(secret->def->uuid, uuidstr);
753
            virReportError(VIR_ERR_INTERNAL_ERROR,
754 755
                           _("a secret with UUID %s is already defined "
                             "for use with %s"),
756
                           uuidstr, oldUsageID);
757 758 759 760
            goto cleanup;
        }

        if (secret->def->private && !new_attrs->private) {
761 762
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot change private flag on existing secret"));
763 764 765 766 767 768
            goto cleanup;
        }

        /* Got an existing secret matches attrs, so reuse that */
        backup = secret->def;
        secret->def = new_attrs;
769 770 771
    }

    if (!new_attrs->ephemeral) {
772
        if (backup && backup->ephemeral) {
773
            if (secretSaveValue(secret) < 0)
774 775
                goto restore_backup;
        }
776
        if (secretSaveDef(secret) < 0) {
777
            if (backup && backup->ephemeral) {
778
                /* Undo the secretSaveValue() above; ignore errors */
779
                (void)unlink(secret->base64File);
780 781 782
            }
            goto restore_backup;
        }
783
    } else if (backup && !backup->ephemeral) {
784
        if (secretDeleteSaved(secret) < 0)
785 786
            goto restore_backup;
    }
787
    /* Saved successfully - drop old values */
788 789 790
    new_attrs = NULL;
    virSecretDefFree(backup);

791 792 793 794
    ret = virGetSecret(conn,
                       secret->def->uuid,
                       secret->def->usage_type,
                       secretUsageIDForDef(secret->def));
795 796
    goto cleanup;

797
 restore_backup:
798 799 800 801
    if (backup) {
        /* Error - restore previous state and free new attributes */
        secret->def = backup;
    } else {
802
        /* "secret" was added to the head of the list above */
803
        if (listUnlink(&driver->secrets) != secret)
804 805
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("list of secrets is inconsistent"));
806 807 808 809
        else
            secretFree(secret);
    }

810
 cleanup:
811
    virSecretDefFree(new_attrs);
812
    secretDriverUnlock();
813 814 815 816 817

    return ret;
}

static char *
818 819
secretGetXMLDesc(virSecretPtr obj,
                 unsigned int flags)
820 821
{
    char *ret = NULL;
J
John Ferlan 已提交
822
    virSecretObjPtr secret;
823

824 825
    virCheckFlags(0, NULL);

826
    secretDriverLock();
827

828
    if (!(secret = secretFindByUUID(obj->uuid))) {
829 830
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(obj->uuid, uuidstr);
831 832
        virReportError(VIR_ERR_NO_SECRET,
                       _("no secret with matching uuid '%s'"), uuidstr);
833 834 835
        goto cleanup;
    }

836 837 838
    if (virSecretGetXMLDescEnsureACL(obj->conn, secret->def) < 0)
        goto cleanup;

839
    ret = virSecretDefFormat(secret->def);
840

841
 cleanup:
842
    secretDriverUnlock();
843 844 845 846 847

    return ret;
}

static int
848 849 850 851
secretSetValue(virSecretPtr obj,
               const unsigned char *value,
               size_t value_size,
               unsigned int flags)
852 853 854 855
{
    int ret = -1;
    unsigned char *old_value, *new_value;
    size_t old_value_size;
J
John Ferlan 已提交
856
    virSecretObjPtr secret;
857

858 859
    virCheckFlags(0, -1);

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

863
    secretDriverLock();
864

865
    if (!(secret = secretFindByUUID(obj->uuid))) {
866 867
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(obj->uuid, uuidstr);
868 869
        virReportError(VIR_ERR_NO_SECRET,
                       _("no secret with matching uuid '%s'"), uuidstr);
870 871 872
        goto cleanup;
    }

873 874 875
    if (virSecretSetValueEnsureACL(obj->conn, secret->def) < 0)
        goto cleanup;

876 877 878 879 880 881 882
    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;
    if (!secret->def->ephemeral) {
883
        if (secretSaveValue(secret) < 0)
884 885
            goto restore_backup;
    }
886
    /* Saved successfully - drop old value */
887 888 889 890 891 892 893 894 895
    if (old_value != NULL) {
        memset(old_value, 0, old_value_size);
        VIR_FREE(old_value);
    }
    new_value = NULL;

    ret = 0;
    goto cleanup;

896
 restore_backup:
897 898 899 900 901
    /* Error - restore previous state and free new value */
    secret->value = old_value;
    secret->value_size = old_value_size;
    memset(new_value, 0, value_size);

902
 cleanup:
903
    secretDriverUnlock();
904 905 906 907 908 909 910

    VIR_FREE(new_value);

    return ret;
}

static unsigned char *
911 912 913
secretGetValue(virSecretPtr obj,
               size_t *value_size,
               unsigned int flags,
914
               unsigned int internalFlags)
915 916
{
    unsigned char *ret = NULL;
J
John Ferlan 已提交
917
    virSecretObjPtr secret;
918

919 920
    virCheckFlags(0, NULL);

921
    secretDriverLock();
922

923
    if (!(secret = secretFindByUUID(obj->uuid))) {
924 925
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(obj->uuid, uuidstr);
926 927
        virReportError(VIR_ERR_NO_SECRET,
                       _("no secret with matching uuid '%s'"), uuidstr);
928 929
        goto cleanup;
    }
930

931 932 933
    if (virSecretGetValueEnsureACL(obj->conn, secret->def) < 0)
        goto cleanup;

934
    if (secret->value == NULL) {
935 936
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(obj->uuid, uuidstr);
937 938
        virReportError(VIR_ERR_NO_SECRET,
                       _("secret '%s' does not have a value"), uuidstr);
939 940 941
        goto cleanup;
    }

942
    if ((internalFlags & VIR_SECRET_GET_VALUE_INTERNAL_CALL) == 0 &&
943
        secret->def->private) {
944
        virReportError(VIR_ERR_INVALID_SECRET, "%s",
945
                       _("secret is private"));
946 947 948
        goto cleanup;
    }

949
    if (VIR_ALLOC_N(ret, secret->value_size) < 0)
950 951 952 953
        goto cleanup;
    memcpy(ret, secret->value, secret->value_size);
    *value_size = secret->value_size;

954
 cleanup:
955
    secretDriverUnlock();
956 957 958 959 960 961 962 963

    return ret;
}

static int
secretUndefine(virSecretPtr obj)
{
    int ret = -1;
J
John Ferlan 已提交
964
    virSecretObjPtr secret;
965

966
    secretDriverLock();
967

968
    if (!(secret = secretFindByUUID(obj->uuid))) {
969 970
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(obj->uuid, uuidstr);
971 972
        virReportError(VIR_ERR_NO_SECRET,
                       _("no secret with matching uuid '%s'"), uuidstr);
973 974 975
        goto cleanup;
    }

976 977 978
    if (virSecretUndefineEnsureACL(obj->conn, secret->def) < 0)
        goto cleanup;

979
    if (!secret->def->ephemeral &&
980
        secretDeleteSaved(secret) < 0)
981 982 983 984 985
        goto cleanup;

    if (driver->secrets == secret) {
        driver->secrets = secret->next;
    } else {
J
John Ferlan 已提交
986
        virSecretObjPtr tmp = driver->secrets;
987 988 989 990
        while (tmp && tmp->next != secret)
            tmp = tmp->next;
        if (tmp)
            tmp->next = secret->next;
991 992 993 994 995
    }
    secretFree(secret);

    ret = 0;

996
 cleanup:
997
    secretDriverUnlock();
998 999 1000 1001 1002

    return ret;
}

static int
1003
secretStateCleanup(void)
1004
{
1005
    if (driver == NULL)
1006 1007
        return -1;

1008
    secretDriverLock();
1009

1010
    while (driver->secrets != NULL) {
1011
        virSecretObjPtr secret;
1012

1013 1014
        secret = listUnlink(&driver->secrets);
        secretFree(secret);
1015
    }
1016
    VIR_FREE(driver->configDir);
1017

1018 1019 1020
    secretDriverUnlock();
    virMutexDestroy(&driver->lock);
    VIR_FREE(driver);
1021 1022 1023 1024 1025

    return 0;
}

static int
1026 1027 1028
secretStateInitialize(bool privileged,
                      virStateInhibitCallback callback ATTRIBUTE_UNUSED,
                      void *opaque ATTRIBUTE_UNUSED)
1029 1030 1031
{
    char *base = NULL;

1032
    if (VIR_ALLOC(driver) < 0)
1033 1034
        return -1;

1035 1036
    if (virMutexInit(&driver->lock) < 0) {
        VIR_FREE(driver);
1037 1038
        return -1;
    }
1039
    secretDriverLock();
1040 1041

    if (privileged) {
1042 1043
        if (VIR_STRDUP(base, SYSCONFDIR "/libvirt") < 0)
            goto error;
1044
    } else {
1045
        if (!(base = virGetUserConfigDirectory()))
1046 1047
            goto error;
    }
1048
    if (virAsprintf(&driver->configDir, "%s/secrets", base) < 0)
1049
        goto error;
1050 1051
    VIR_FREE(base);

1052
    if (loadSecrets(&driver->secrets) < 0)
1053 1054
        goto error;

1055
    secretDriverUnlock();
1056 1057 1058 1059
    return 0;

 error:
    VIR_FREE(base);
1060
    secretDriverUnlock();
1061
    secretStateCleanup();
1062 1063 1064 1065
    return -1;
}

static int
1066
secretStateReload(void)
1067
{
J
John Ferlan 已提交
1068
    virSecretObjPtr new_secrets = NULL;
1069

1070
    if (!driver)
1071 1072
        return -1;

1073
    secretDriverLock();
1074

1075
    if (loadSecrets(&new_secrets) < 0)
1076 1077
        goto end;

1078 1079
    /* Keep ephemeral secrets from current state.
     * Discard non-ephemeral secrets that were removed
1080
     * by the secrets configDir.  */
1081
    while (driver->secrets != NULL) {
1082
        virSecretObjPtr secret;
1083

1084 1085 1086
        secret = listUnlink(&driver->secrets);
        if (secret->def->ephemeral)
            listInsert(&new_secrets, secret);
1087
        else
1088
            secretFree(secret);
1089
    }
1090
    driver->secrets = new_secrets;
1091 1092

 end:
1093
    secretDriverUnlock();
1094 1095 1096 1097 1098
    return 0;
}

static virSecretDriver secretDriver = {
    .name = "secret",
1099 1100 1101
    .connectNumOfSecrets = secretConnectNumOfSecrets, /* 0.7.1 */
    .connectListSecrets = secretConnectListSecrets, /* 0.7.1 */
    .connectListAllSecrets = secretConnectListAllSecrets, /* 0.10.2 */
1102 1103 1104 1105 1106 1107 1108
    .secretLookupByUUID = secretLookupByUUID, /* 0.7.1 */
    .secretLookupByUsage = secretLookupByUsage, /* 0.7.1 */
    .secretDefineXML = secretDefineXML, /* 0.7.1 */
    .secretGetXMLDesc = secretGetXMLDesc, /* 0.7.1 */
    .secretSetValue = secretSetValue, /* 0.7.1 */
    .secretGetValue = secretGetValue, /* 0.7.1 */
    .secretUndefine = secretUndefine, /* 0.7.1 */
1109 1110 1111
};

static virStateDriver stateDriver = {
1112
    .name = "secret",
1113 1114 1115
    .stateInitialize = secretStateInitialize,
    .stateCleanup = secretStateCleanup,
    .stateReload = secretStateReload,
1116 1117 1118 1119 1120
};

int
secretRegister(void)
{
1121
    if (virSetSharedSecretDriver(&secretDriver) < 0)
1122 1123 1124
        return -1;
    if (virRegisterStateDriver(&stateDriver) < 0)
        return -1;
1125 1126
    return 0;
}