secret_driver.c 27.9 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
}

J
John Ferlan 已提交
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186

static virSecretObjPtr
secretAssignDef(virSecretObjPtr *list,
                virSecretDefPtr def)
{
    virSecretObjPtr secret;

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

    listInsert(list, secret);
    secret->def = def;

    return secret;
}

J
John Ferlan 已提交
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203

static virSecretObjPtr
secretObjFromSecret(virSecretPtr secret)
{
    virSecretObjPtr obj;
    char uuidstr[VIR_UUID_STRING_BUFLEN];

    if (!(obj = secretFindByUUID(secret->uuid))) {
        virUUIDFormat(secret->uuid, uuidstr);
        virReportError(VIR_ERR_NO_SECRET,
                       _("no secret with matching uuid '%s'"), uuidstr);
        return NULL;
    }
    return obj;
}


204
/* Permament secret storage */
205

206
/* Secrets are stored in virSecretDriverStatePtr->configDir.  Each secret
207 208 209 210 211
   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
212 213
secretRewriteFile(int fd,
                  void *opaque)
214
{
215
    char *data = opaque;
216

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

220
    return 0;
221 222 223 224
}


static int
225
secretEnsureDirectory(void)
226
{
227
    if (mkdir(driver->configDir, S_IRWXU) < 0 && errno != EEXIST) {
228
        virReportSystemError(errno, _("cannot create '%s'"),
229
                             driver->configDir);
230 231 232 233 234 235
        return -1;
    }
    return 0;
}

static int
J
John Ferlan 已提交
236
secretSaveDef(const virSecretObj *secret)
237
{
238
    char *xml = NULL;
239 240
    int ret = -1;

241
    if (secretEnsureDirectory() < 0)
242 243
        goto cleanup;

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

247
    if (virFileRewrite(secret->configFile, S_IRUSR | S_IWUSR,
248
                       secretRewriteFile, xml) < 0)
249 250 251 252
        goto cleanup;

    ret = 0;

253
 cleanup:
254 255 256 257 258
    VIR_FREE(xml);
    return ret;
}

static int
J
John Ferlan 已提交
259
secretSaveValue(const virSecretObj *secret)
260
{
261
    char *base64 = NULL;
262 263 264 265 266
    int ret = -1;

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

267
    if (secretEnsureDirectory() < 0)
268 269 270 271 272
        goto cleanup;

    base64_encode_alloc((const char *)secret->value, secret->value_size,
                        &base64);
    if (base64 == NULL) {
273
        virReportOOMError();
274 275 276
        goto cleanup;
    }

277
    if (virFileRewrite(secret->base64File, S_IRUSR | S_IWUSR,
278
                       secretRewriteFile, base64) < 0)
279 280 281 282
        goto cleanup;

    ret = 0;

283
 cleanup:
284 285 286 287 288
    VIR_FREE(base64);
    return ret;
}

static int
J
John Ferlan 已提交
289
secretDeleteSaved(const virSecretObj *secret)
290
{
291
    if (unlink(secret->configFile) < 0 && errno != ENOENT)
292 293
        return -1;

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

298
    return 0;
299 300 301
}

static int
302
secretLoadValidateUUID(virSecretDefPtr def,
303
                       const char *file)
304
{
305
    char uuidstr[VIR_UUID_STRING_BUFLEN];
306

307
    virUUIDFormat(def->uuid, uuidstr);
308

309
    if (!virFileMatchesNameSuffix(file, uuidstr, ".xml")) {
310 311
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("<uuid> does not match secret file name '%s'"),
312
                       file);
313 314 315 316 317 318 319
        return -1;
    }

    return 0;
}

static int
J
John Ferlan 已提交
320
secretLoadValue(virSecretObjPtr secret)
321 322 323
{
    int ret = -1, fd = -1;
    struct stat st;
324
    char *contents = NULL, *value = NULL;
325 326
    size_t value_size;

327
    if ((fd = open(secret->base64File, O_RDONLY)) == -1) {
328 329 330 331
        if (errno == ENOENT) {
            ret = 0;
            goto cleanup;
        }
332 333
        virReportSystemError(errno, _("cannot open '%s'"),
                             secret->base64File);
334 335
        goto cleanup;
    }
336

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

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

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

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

359
    VIR_FORCE_CLOSE(fd);
360 361

    if (!base64_decode_alloc(contents, st.st_size, &value, &value_size)) {
362
        virReportError(VIR_ERR_INTERNAL_ERROR,
363 364
                       _("invalid base64 in '%s'"),
                       secret->base64File);
365 366
        goto cleanup;
    }
367
    if (value == NULL)
368 369 370 371 372 373 374 375
        goto cleanup;

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

    ret = 0;

376
 cleanup:
377 378 379 380 381 382 383 384
    if (value != NULL) {
        memset(value, 0, value_size);
        VIR_FREE(value);
    }
    if (contents != NULL) {
        memset(contents, 0, st.st_size);
        VIR_FREE(contents);
    }
385
    VIR_FORCE_CLOSE(fd);
386 387 388
    return ret;
}

J
John Ferlan 已提交
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408

static void
listUnlinkSecret(virSecretObjPtr *pptr,
                 virSecretObjPtr secret)
{
    if (!secret)
        return;

    if (*pptr == secret) {
        *pptr = secret->next;
    } else {
        virSecretObjPtr tmp = *pptr;
        while (tmp && tmp->next != secret)
            tmp = tmp->next;
        if (tmp)
            tmp->next = secret->next;
    }
}


J
John Ferlan 已提交
409
static virSecretObjPtr
J
John Ferlan 已提交
410 411
secretLoad(virSecretObjPtr *list,
           const char *file,
412 413
           const char *path,
           const char *base64path)
414
{
415
    virSecretDefPtr def = NULL;
J
John Ferlan 已提交
416
    virSecretObjPtr secret = NULL, ret = NULL;
417

418
    if (!(def = virSecretDefParseFile(path)))
419
        goto cleanup;
420

421
    if (secretLoadValidateUUID(def, file) < 0)
422 423
        goto cleanup;

J
John Ferlan 已提交
424
    if (!(secret = secretAssignDef(list, def)))
425 426 427
        goto cleanup;
    def = NULL;

428 429 430
    if (VIR_STRDUP(secret->configFile, path) < 0)
        goto cleanup;

431 432 433
    if (VIR_STRDUP(secret->base64File, base64path) < 0)
        goto cleanup;

434
    if (secretLoadValue(secret) < 0)
435 436 437 438 439
        goto cleanup;

    ret = secret;
    secret = NULL;

440
 cleanup:
J
John Ferlan 已提交
441
    listUnlinkSecret(list, secret);
442 443 444 445 446 447
    secretFree(secret);
    virSecretDefFree(def);
    return ret;
}

static int
J
John Ferlan 已提交
448 449
secretLoadAllConfigs(virSecretObjPtr *dest,
                     const char *configDir)
450 451 452
{
    DIR *dir = NULL;
    struct dirent *de;
J
John Ferlan 已提交
453
    virSecretObjPtr list = NULL;
454

J
John Ferlan 已提交
455
    if (!(dir = opendir(configDir))) {
456 457
        if (errno == ENOENT)
            return 0;
J
John Ferlan 已提交
458
        virReportSystemError(errno, _("cannot open '%s'"), configDir);
459
        return -1;
460
    }
461

E
Eric Blake 已提交
462
    while (virDirRead(dir, &de, NULL) > 0) {
463
        char *path, *base64name, *base64path;
J
John Ferlan 已提交
464
        virSecretObjPtr secret;
465 466 467

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

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

J
John Ferlan 已提交
472
        if (!(path = virFileBuildPath(configDir, de->d_name, NULL)))
473 474
            continue;

475 476 477
        /* Copy the .xml file name, but use suffix ".base64" instead */
        if (VIR_STRDUP(base64name, de->d_name) < 0 ||
            !virFileStripSuffix(base64name, ".xml") ||
J
John Ferlan 已提交
478
            !(base64path = virFileBuildPath(configDir,
479 480 481 482 483 484 485
                                            base64name, ".base64"))) {
            VIR_FREE(path);
            VIR_FREE(base64name);
            continue;
        }
        VIR_FREE(base64name);

J
John Ferlan 已提交
486
        if (!(secret = secretLoad(&list, de->d_name, path, base64path))) {
487 488
            virErrorPtr err = virGetLastError();

489
            VIR_ERROR(_("Error reading secret: %s"),
490
                      err != NULL ? err->message: _("unknown error"));
491
            virResetError(err);
492
            VIR_FREE(path);
493
            VIR_FREE(base64path);
494 495
            continue;
        }
496

497
        VIR_FREE(path);
498
        VIR_FREE(base64path);
499
    }
E
Eric Blake 已提交
500
    /* Ignore error reported by readdir, if any.  It's better to keep the
501 502 503
       secrets we managed to find. */

    while (list != NULL) {
504
        virSecretObjPtr secret;
505

506 507
        secret = listUnlink(&list);
        listInsert(dest, secret);
508 509
    }

510 511
    closedir(dir);
    return 0;
512 513
}

514
/* Driver functions */
515 516

static int
517
secretConnectNumOfSecrets(virConnectPtr conn)
518
{
519
    size_t i;
J
John Ferlan 已提交
520
    virSecretObjPtr secret;
521

522 523 524
    if (virConnectNumOfSecretsEnsureACL(conn) < 0)
        return -1;

525
    secretDriverLock();
526 527

    i = 0;
528 529 530 531 532
    for (secret = driver->secrets; secret != NULL; secret = secret->next) {
        if (virConnectNumOfSecretsCheckACL(conn,
                                           secret->def))
            i++;
    }
533

534
    secretDriverUnlock();
535 536 537 538
    return i;
}

static int
539 540 541
secretConnectListSecrets(virConnectPtr conn,
                         char **uuids,
                         int maxuuids)
542
{
543
    size_t i;
J
John Ferlan 已提交
544
    virSecretObjPtr secret;
545 546 547

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

548 549 550
    if (virConnectListSecretsEnsureACL(conn) < 0)
        return -1;

551
    secretDriverLock();
552 553 554

    i = 0;
    for (secret = driver->secrets; secret != NULL; secret = secret->next) {
555
        char *uuidstr;
556 557 558
        if (!virConnectListSecretsCheckACL(conn,
                                           secret->def))
            continue;
559 560
        if (i == maxuuids)
            break;
561
        if (VIR_ALLOC_N(uuidstr, VIR_UUID_STRING_BUFLEN) < 0)
562
            goto cleanup;
563 564
        virUUIDFormat(secret->def->uuid, uuidstr);
        uuids[i] = uuidstr;
565 566 567
        i++;
    }

568
    secretDriverUnlock();
569 570
    return i;

571
 cleanup:
572
    secretDriverUnlock();
573 574 575 576 577 578 579

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

    return -1;
}

580 581 582 583 584 585 586 587 588 589
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 已提交
590 591 592
    case VIR_SECRET_USAGE_TYPE_CEPH:
        return def->usage.ceph;

593 594 595
    case VIR_SECRET_USAGE_TYPE_ISCSI:
        return def->usage.target;

596 597 598 599 600
    default:
        return NULL;
    }
}

O
Osier Yang 已提交
601 602
#define MATCH(FLAG) (flags & (FLAG))
static int
603 604
secretConnectListAllSecrets(virConnectPtr conn,
                            virSecretPtr **secrets,
605 606
                            unsigned int flags)
{
O
Osier Yang 已提交
607 608 609
    virSecretPtr *tmp_secrets = NULL;
    int nsecrets = 0;
    int ret_nsecrets = 0;
610
    virSecretObjPtr secret = NULL;
611
    size_t i = 0;
O
Osier Yang 已提交
612 613 614 615
    int ret = -1;

    virCheckFlags(VIR_CONNECT_LIST_SECRETS_FILTERS_ALL, -1);

616 617 618
    if (virConnectListAllSecretsEnsureACL(conn) < 0)
        return -1;

619
    secretDriverLock();
O
Osier Yang 已提交
620

621
    for (secret = driver->secrets; secret != NULL; secret = secret->next)
O
Osier Yang 已提交
622 623
        nsecrets++;

624 625
    if (secrets && VIR_ALLOC_N(tmp_secrets, nsecrets + 1) < 0)
        goto cleanup;
O
Osier Yang 已提交
626

627
    for (secret = driver->secrets; secret != NULL; secret = secret->next) {
628
        if (!virConnectListAllSecretsCheckACL(conn,
629
                                              secret->def))
630 631
            continue;

O
Osier Yang 已提交
632 633 634
        /* filter by whether it's ephemeral */
        if (MATCH(VIR_CONNECT_LIST_SECRETS_FILTERS_EPHEMERAL) &&
            !((MATCH(VIR_CONNECT_LIST_SECRETS_EPHEMERAL) &&
635
               secret->def->ephemeral) ||
O
Osier Yang 已提交
636
              (MATCH(VIR_CONNECT_LIST_SECRETS_NO_EPHEMERAL) &&
637
               !secret->def->ephemeral)))
O
Osier Yang 已提交
638 639 640 641 642
            continue;

        /* filter by whether it's private */
        if (MATCH(VIR_CONNECT_LIST_SECRETS_FILTERS_PRIVATE) &&
            !((MATCH(VIR_CONNECT_LIST_SECRETS_PRIVATE) &&
643
               secret->def->private) ||
O
Osier Yang 已提交
644
              (MATCH(VIR_CONNECT_LIST_SECRETS_NO_PRIVATE) &&
645
               !secret->def->private)))
O
Osier Yang 已提交
646 647 648
            continue;

        if (secrets) {
649 650
            if (!(tmp_secrets[ret_nsecrets] =
                  virGetSecret(conn,
651 652 653
                               secret->def->uuid,
                               secret->def->usage_type,
                               secretUsageIDForDef(secret->def))))
O
Osier Yang 已提交
654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
                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:
669
    secretDriverUnlock();
O
Osier Yang 已提交
670
    if (tmp_secrets) {
671 672
        for (i = 0; i < ret_nsecrets; i ++)
            virObjectUnref(tmp_secrets[i]);
O
Osier Yang 已提交
673 674 675 676 677 678 679 680
    }
    VIR_FREE(tmp_secrets);

    return ret;
}
#undef MATCH


681
static virSecretPtr
682 683
secretLookupByUUID(virConnectPtr conn,
                   const unsigned char *uuid)
684 685
{
    virSecretPtr ret = NULL;
J
John Ferlan 已提交
686
    virSecretObjPtr secret;
687

688
    secretDriverLock();
689

690
    if (!(secret = secretFindByUUID(uuid))) {
691 692
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(uuid, uuidstr);
693 694
        virReportError(VIR_ERR_NO_SECRET,
                       _("no secret with matching uuid '%s'"), uuidstr);
695 696 697
        goto cleanup;
    }

698 699 700
    if (virSecretLookupByUUIDEnsureACL(conn, secret->def) < 0)
        goto cleanup;

701 702 703 704 705
    ret = virGetSecret(conn,
                       secret->def->uuid,
                       secret->def->usage_type,
                       secretUsageIDForDef(secret->def));

706
 cleanup:
707
    secretDriverUnlock();
708 709 710 711 712
    return ret;
}


static virSecretPtr
713 714 715
secretLookupByUsage(virConnectPtr conn,
                    int usageType,
                    const char *usageID)
716 717
{
    virSecretPtr ret = NULL;
J
John Ferlan 已提交
718
    virSecretObjPtr secret;
719

720
    secretDriverLock();
721

722
    if (!(secret = secretFindByUsage(usageType, usageID))) {
723 724
        virReportError(VIR_ERR_NO_SECRET,
                       _("no secret with matching usage '%s'"), usageID);
725 726 727
        goto cleanup;
    }

728 729 730
    if (virSecretLookupByUsageEnsureACL(conn, secret->def) < 0)
        goto cleanup;

731 732 733 734
    ret = virGetSecret(conn,
                       secret->def->uuid,
                       secret->def->usage_type,
                       secretUsageIDForDef(secret->def));
735

736
 cleanup:
737
    secretDriverUnlock();
738 739 740 741 742
    return ret;
}


static virSecretPtr
743 744
secretDefineXML(virConnectPtr conn,
                const char *xml,
745
                unsigned int flags)
746 747
{
    virSecretPtr ret = NULL;
J
John Ferlan 已提交
748
    virSecretObjPtr secret = NULL;
749 750
    virSecretDefPtr backup = NULL;
    virSecretDefPtr new_attrs;
751

752 753
    virCheckFlags(0, NULL);

754
    if (!(new_attrs = virSecretDefParseString(xml)))
755 756
        return NULL;

757
    secretDriverLock();
758

759 760 761
    if (virSecretDefineXMLEnsureACL(conn, new_attrs) < 0)
        goto cleanup;

762 763 764
    if (!(secret = secretFindByUUID(new_attrs->uuid))) {
        /* No existing secret with same UUID,
         * try look for matching usage instead */
765
        const char *usageID = secretUsageIDForDef(new_attrs);
766 767
        char uuidstr[VIR_UUID_STRING_BUFLEN];

768
        if ((secret = secretFindByUsage(new_attrs->usage_type, usageID))) {
769
            virUUIDFormat(secret->def->uuid, uuidstr);
770
            virReportError(VIR_ERR_INTERNAL_ERROR,
771 772
                           _("a secret with UUID %s already defined for "
                             "use with %s"),
773
                           uuidstr, usageID);
774 775
            goto cleanup;
        }
776

777
        /* No existing secret at all, create one */
J
John Ferlan 已提交
778
        if (!(secret = secretAssignDef(&driver->secrets, new_attrs)))
779
            goto cleanup;
780

781 782 783 784 785 786 787 788 789
        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;
        }
790 791 792 793 794 795 796
        /* Generate base64File using driver->configDir,
         * the uuidstr, and .base64 suffix */
        if (!(secret->base64File = virFileBuildPath(driver->configDir,
                                                    uuidstr, ".base64"))) {
            secretFree(secret);
            goto cleanup;
        }
797 798 799 800 801 802
    } 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);
803
            virReportError(VIR_ERR_INTERNAL_ERROR,
804 805
                           _("a secret with UUID %s is already defined "
                             "for use with %s"),
806
                           uuidstr, oldUsageID);
807 808 809 810
            goto cleanup;
        }

        if (secret->def->private && !new_attrs->private) {
811 812
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot change private flag on existing secret"));
813 814 815 816 817 818
            goto cleanup;
        }

        /* Got an existing secret matches attrs, so reuse that */
        backup = secret->def;
        secret->def = new_attrs;
819 820 821
    }

    if (!new_attrs->ephemeral) {
822
        if (backup && backup->ephemeral) {
823
            if (secretSaveValue(secret) < 0)
824 825
                goto restore_backup;
        }
826
        if (secretSaveDef(secret) < 0) {
827
            if (backup && backup->ephemeral) {
828
                /* Undo the secretSaveValue() above; ignore errors */
829
                (void)unlink(secret->base64File);
830 831 832
            }
            goto restore_backup;
        }
833
    } else if (backup && !backup->ephemeral) {
834
        if (secretDeleteSaved(secret) < 0)
835 836
            goto restore_backup;
    }
837
    /* Saved successfully - drop old values */
838 839 840
    new_attrs = NULL;
    virSecretDefFree(backup);

841 842 843 844
    ret = virGetSecret(conn,
                       secret->def->uuid,
                       secret->def->usage_type,
                       secretUsageIDForDef(secret->def));
845 846
    goto cleanup;

847
 restore_backup:
848 849 850 851
    if (backup) {
        /* Error - restore previous state and free new attributes */
        secret->def = backup;
    } else {
852
        /* "secret" was added to the head of the list above */
853
        if (listUnlink(&driver->secrets) != secret)
854 855
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("list of secrets is inconsistent"));
856 857 858 859
        else
            secretFree(secret);
    }

860
 cleanup:
861
    virSecretDefFree(new_attrs);
862
    secretDriverUnlock();
863 864 865 866 867

    return ret;
}

static char *
868 869
secretGetXMLDesc(virSecretPtr obj,
                 unsigned int flags)
870 871
{
    char *ret = NULL;
J
John Ferlan 已提交
872
    virSecretObjPtr secret;
873

874 875
    virCheckFlags(0, NULL);

876
    secretDriverLock();
877

J
John Ferlan 已提交
878
    if (!(secret = secretObjFromSecret(obj)))
879 880
        goto cleanup;

881 882 883
    if (virSecretGetXMLDescEnsureACL(obj->conn, secret->def) < 0)
        goto cleanup;

884
    ret = virSecretDefFormat(secret->def);
885

886
 cleanup:
887
    secretDriverUnlock();
888 889 890 891 892

    return ret;
}

static int
893 894 895 896
secretSetValue(virSecretPtr obj,
               const unsigned char *value,
               size_t value_size,
               unsigned int flags)
897 898 899 900
{
    int ret = -1;
    unsigned char *old_value, *new_value;
    size_t old_value_size;
J
John Ferlan 已提交
901
    virSecretObjPtr secret;
902

903 904
    virCheckFlags(0, -1);

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

908
    secretDriverLock();
909

J
John Ferlan 已提交
910
    if (!(secret = secretObjFromSecret(obj)))
911 912
        goto cleanup;

913 914 915
    if (virSecretSetValueEnsureACL(obj->conn, secret->def) < 0)
        goto cleanup;

916 917 918 919 920 921 922
    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) {
923
        if (secretSaveValue(secret) < 0)
924 925
            goto restore_backup;
    }
926
    /* Saved successfully - drop old value */
927 928 929 930 931 932 933 934 935
    if (old_value != NULL) {
        memset(old_value, 0, old_value_size);
        VIR_FREE(old_value);
    }
    new_value = NULL;

    ret = 0;
    goto cleanup;

936
 restore_backup:
937 938 939 940 941
    /* Error - restore previous state and free new value */
    secret->value = old_value;
    secret->value_size = old_value_size;
    memset(new_value, 0, value_size);

942
 cleanup:
943
    secretDriverUnlock();
944 945 946 947 948 949 950

    VIR_FREE(new_value);

    return ret;
}

static unsigned char *
951 952 953
secretGetValue(virSecretPtr obj,
               size_t *value_size,
               unsigned int flags,
954
               unsigned int internalFlags)
955 956
{
    unsigned char *ret = NULL;
J
John Ferlan 已提交
957
    virSecretObjPtr secret;
958

959 960
    virCheckFlags(0, NULL);

961
    secretDriverLock();
962

J
John Ferlan 已提交
963
    if (!(secret = secretObjFromSecret(obj)))
964
        goto cleanup;
965

966 967 968
    if (virSecretGetValueEnsureACL(obj->conn, secret->def) < 0)
        goto cleanup;

969
    if (secret->value == NULL) {
970 971
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(obj->uuid, uuidstr);
972 973
        virReportError(VIR_ERR_NO_SECRET,
                       _("secret '%s' does not have a value"), uuidstr);
974 975 976
        goto cleanup;
    }

977
    if ((internalFlags & VIR_SECRET_GET_VALUE_INTERNAL_CALL) == 0 &&
978
        secret->def->private) {
979
        virReportError(VIR_ERR_INVALID_SECRET, "%s",
980
                       _("secret is private"));
981 982 983
        goto cleanup;
    }

984
    if (VIR_ALLOC_N(ret, secret->value_size) < 0)
985 986 987 988
        goto cleanup;
    memcpy(ret, secret->value, secret->value_size);
    *value_size = secret->value_size;

989
 cleanup:
990
    secretDriverUnlock();
991 992 993 994 995 996 997 998

    return ret;
}

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

1001
    secretDriverLock();
1002

J
John Ferlan 已提交
1003
    if (!(secret = secretObjFromSecret(obj)))
1004 1005
        goto cleanup;

1006 1007 1008
    if (virSecretUndefineEnsureACL(obj->conn, secret->def) < 0)
        goto cleanup;

1009
    if (!secret->def->ephemeral &&
1010
        secretDeleteSaved(secret) < 0)
1011 1012
        goto cleanup;

J
John Ferlan 已提交
1013
    listUnlinkSecret(&driver->secrets, secret);
1014 1015 1016 1017
    secretFree(secret);

    ret = 0;

1018
 cleanup:
1019
    secretDriverUnlock();
1020 1021 1022 1023 1024

    return ret;
}

static int
1025
secretStateCleanup(void)
1026
{
1027
    if (driver == NULL)
1028 1029
        return -1;

1030
    secretDriverLock();
1031

1032
    while (driver->secrets != NULL) {
1033
        virSecretObjPtr secret;
1034

1035 1036
        secret = listUnlink(&driver->secrets);
        secretFree(secret);
1037
    }
1038
    VIR_FREE(driver->configDir);
1039

1040 1041 1042
    secretDriverUnlock();
    virMutexDestroy(&driver->lock);
    VIR_FREE(driver);
1043 1044 1045 1046 1047

    return 0;
}

static int
1048 1049 1050
secretStateInitialize(bool privileged,
                      virStateInhibitCallback callback ATTRIBUTE_UNUSED,
                      void *opaque ATTRIBUTE_UNUSED)
1051 1052 1053
{
    char *base = NULL;

1054
    if (VIR_ALLOC(driver) < 0)
1055 1056
        return -1;

1057 1058
    if (virMutexInit(&driver->lock) < 0) {
        VIR_FREE(driver);
1059 1060
        return -1;
    }
1061
    secretDriverLock();
1062 1063

    if (privileged) {
1064 1065
        if (VIR_STRDUP(base, SYSCONFDIR "/libvirt") < 0)
            goto error;
1066
    } else {
1067
        if (!(base = virGetUserConfigDirectory()))
1068 1069
            goto error;
    }
1070
    if (virAsprintf(&driver->configDir, "%s/secrets", base) < 0)
1071
        goto error;
1072 1073
    VIR_FREE(base);

J
John Ferlan 已提交
1074
    if (secretLoadAllConfigs(&driver->secrets, driver->configDir) < 0)
1075 1076
        goto error;

1077
    secretDriverUnlock();
1078 1079 1080 1081
    return 0;

 error:
    VIR_FREE(base);
1082
    secretDriverUnlock();
1083
    secretStateCleanup();
1084 1085 1086 1087
    return -1;
}

static int
1088
secretStateReload(void)
1089
{
J
John Ferlan 已提交
1090
    virSecretObjPtr new_secrets = NULL;
1091

1092
    if (!driver)
1093 1094
        return -1;

1095
    secretDriverLock();
1096

J
John Ferlan 已提交
1097
    if (secretLoadAllConfigs(&new_secrets, driver->configDir) < 0)
1098 1099
        goto end;

1100 1101
    /* Keep ephemeral secrets from current state.
     * Discard non-ephemeral secrets that were removed
1102
     * by the secrets configDir.  */
1103
    while (driver->secrets != NULL) {
1104
        virSecretObjPtr secret;
1105

1106 1107 1108
        secret = listUnlink(&driver->secrets);
        if (secret->def->ephemeral)
            listInsert(&new_secrets, secret);
1109
        else
1110
            secretFree(secret);
1111
    }
1112
    driver->secrets = new_secrets;
1113 1114

 end:
1115
    secretDriverUnlock();
1116 1117 1118 1119 1120
    return 0;
}

static virSecretDriver secretDriver = {
    .name = "secret",
1121 1122 1123
    .connectNumOfSecrets = secretConnectNumOfSecrets, /* 0.7.1 */
    .connectListSecrets = secretConnectListSecrets, /* 0.7.1 */
    .connectListAllSecrets = secretConnectListAllSecrets, /* 0.10.2 */
1124 1125 1126 1127 1128 1129 1130
    .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 */
1131 1132 1133
};

static virStateDriver stateDriver = {
1134
    .name = "secret",
1135 1136 1137
    .stateInitialize = secretStateInitialize,
    .stateCleanup = secretStateCleanup,
    .stateReload = secretStateReload,
1138 1139 1140 1141 1142
};

int
secretRegister(void)
{
1143
    if (virSetSharedSecretDriver(&secretDriver) < 0)
1144 1145 1146
        return -1;
    if (virRegisterStateDriver(&stateDriver) < 0)
        return -1;
1147 1148
    return 0;
}