secret_driver.c 29.7 KB
Newer Older
1 2 3
/*
 * secret_driver.c: local driver for secret manipulation API
 *
4
 * Copyright (C) 2009-2012 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 "virutil.h"
41
#include "viruuid.h"
42
#include "virterror_internal.h"
E
Eric Blake 已提交
43
#include "virfile.h"
44
#include "configmake.h"
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113

#define VIR_FROM_THIS VIR_FROM_SECRET

enum { SECRET_MAX_XML_FILE = 10*1024*1024 };

 /* Internal driver state */

typedef struct _virSecretEntry virSecretEntry;
typedef virSecretEntry *virSecretEntryPtr;
struct _virSecretEntry {
    virSecretEntryPtr next;
    virSecretDefPtr def;
    unsigned char *value;       /* May be NULL */
    size_t value_size;
};

typedef struct _virSecretDriverState virSecretDriverState;
typedef virSecretDriverState *virSecretDriverStatePtr;
struct _virSecretDriverState {
    virMutex lock;
    virSecretEntry *secrets;
    char *directory;
};

static virSecretDriverStatePtr driverState;

static void
secretDriverLock(virSecretDriverStatePtr driver)
{
    virMutexLock(&driver->lock);
}

static void
secretDriverUnlock(virSecretDriverStatePtr driver)
{
    virMutexUnlock(&driver->lock);
}

static virSecretEntryPtr
listUnlink(virSecretEntryPtr *pptr)
{
    virSecretEntryPtr secret;

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

static void
listInsert(virSecretEntryPtr *pptr, virSecretEntryPtr secret)
{
    secret->next = *pptr;
    *pptr = secret;
}

static void
secretFree(virSecretEntryPtr secret)
{
    if (secret == NULL)
        return;

    virSecretDefFree(secret->def);
    if (secret->value != NULL) {
        memset(secret->value, 0, secret->value_size);
        VIR_FREE(secret->value);
    }
    VIR_FREE(secret);
}

114 115
static virSecretEntryPtr
secretFindByUUID(virSecretDriverStatePtr driver, const unsigned char *uuid)
116 117 118 119 120
{
    virSecretEntryPtr *pptr, s;

    for (pptr = &driver->secrets; *pptr != NULL; pptr = &s->next) {
        s = *pptr;
121
        if (memcmp(s->def->uuid, uuid, VIR_UUID_BUFLEN) == 0)
122
            return s;
123 124 125 126 127
    }
    return NULL;
}

static virSecretEntryPtr
128
secretFindByUsage(virSecretDriverStatePtr driver, int usageType, const char *usageID)
129
{
130
    virSecretEntryPtr *pptr, s;
131

132 133
    for (pptr = &driver->secrets; *pptr != NULL; pptr = &s->next) {
        s = *pptr;
134

135 136
        if (s->def->usage_type != usageType)
            continue;
137

138 139 140 141
        switch (usageType) {
        case VIR_SECRET_USAGE_TYPE_NONE:
            /* never match this */
            break;
142

143 144 145 146
        case VIR_SECRET_USAGE_TYPE_VOLUME:
            if (STREQ(s->def->usage.volume, usageID))
                return s;
            break;
S
Sage Weil 已提交
147 148 149 150 151

        case VIR_SECRET_USAGE_TYPE_CEPH:
            if (STREQ(s->def->usage.ceph, usageID))
                return s;
            break;
152
        }
153
    }
154
    return NULL;
155 156
}

157
/* Permament secret storage */
158 159 160 161 162 163 164

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

static int
165
replaceFile(const char *filename, void *data, size_t size)
166 167 168 169 170
{
    char *tmp_path = NULL;
    int fd = -1, ret = -1;

    if (virAsprintf(&tmp_path, "%sXXXXXX", filename) < 0) {
171
        virReportOOMError();
172 173
        goto cleanup;
    }
174
    fd = mkostemp(tmp_path, O_CLOEXEC);
175
    if (fd == -1) {
176
        virReportSystemError(errno, _("mkostemp('%s') failed"), tmp_path);
177 178 179
        goto cleanup;
    }
    if (fchmod(fd, S_IRUSR | S_IWUSR) != 0) {
180
        virReportSystemError(errno, _("fchmod('%s') failed"), tmp_path);
181 182 183 184 185
        goto cleanup;
    }

    ret = safewrite(fd, data, size);
    if (ret < 0) {
186
        virReportSystemError(errno, _("error writing to '%s'"),
187 188 189
                              tmp_path);
        goto cleanup;
    }
190
    if (VIR_CLOSE(fd) < 0) {
191
        virReportSystemError(errno, _("error closing '%s'"), tmp_path);
192 193 194 195 196
        goto cleanup;
    }
    fd = -1;

    if (rename(tmp_path, filename) < 0) {
197
        virReportSystemError(errno, _("rename(%s, %s) failed"), tmp_path,
198 199 200 201 202 203 204
                             filename);
        goto cleanup;
    }
    VIR_FREE(tmp_path);
    ret = 0;

cleanup:
205
    VIR_FORCE_CLOSE(fd);
206 207 208 209 210 211 212 213
    if (tmp_path != NULL) {
        unlink(tmp_path);
        VIR_FREE(tmp_path);
    }
    return ret;
}

static char *
214
secretComputePath(virSecretDriverStatePtr driver,
215 216
                  const virSecretEntry *secret, const char *suffix)
{
217 218
    char *ret;
    char uuidstr[VIR_UUID_STRING_BUFLEN];
219

220
    virUUIDFormat(secret->def->uuid, uuidstr);
221

222
    if (virAsprintf(&ret, "%s/%s%s", driver->directory, uuidstr, suffix) < 0)
223
        /* ret is NULL */
224
        virReportOOMError();
225

226 227 228 229
    return ret;
}

static char *
230
secretXMLPath(virSecretDriverStatePtr driver,
231 232
              const virSecretEntry *secret)
{
233
    return secretComputePath(driver, secret, ".xml");
234 235 236
}

static char *
237
secretBase64Path(virSecretDriverStatePtr driver,
238 239
                 const virSecretEntry *secret)
{
240
    return secretComputePath(driver, secret, ".base64");
241 242 243
}

static int
244
secretEnsureDirectory(virSecretDriverStatePtr driver)
245 246
{
    if (mkdir(driver->directory, S_IRWXU) < 0 && errno != EEXIST) {
247
        virReportSystemError(errno, _("cannot create '%s'"),
248 249 250 251 252 253 254
                             driver->directory);
        return -1;
    }
    return 0;
}

static int
255
secretSaveDef(virSecretDriverStatePtr driver,
256 257 258 259 260
              const virSecretEntry *secret)
{
    char *filename = NULL, *xml = NULL;
    int ret = -1;

261
    if (secretEnsureDirectory(driver) < 0)
262 263
        goto cleanup;

264
    filename = secretXMLPath(driver, secret);
265 266
    if (filename == NULL)
        goto cleanup;
267
    xml = virSecretDefFormat(secret->def);
268 269 270
    if (xml == NULL)
        goto cleanup;

271
    if (replaceFile(filename, xml, strlen(xml)) < 0)
272 273 274 275 276 277 278 279 280 281 282
        goto cleanup;

    ret = 0;

cleanup:
    VIR_FREE(xml);
    VIR_FREE(filename);
    return ret;
}

static int
283
secretSaveValue(virSecretDriverStatePtr driver,
284 285 286 287 288 289 290 291
                const virSecretEntry *secret)
{
    char *filename = NULL, *base64 = NULL;
    int ret = -1;

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

292
    if (secretEnsureDirectory(driver) < 0)
293 294
        goto cleanup;

295
    filename = secretBase64Path(driver, secret);
296 297 298 299 300
    if (filename == NULL)
        goto cleanup;
    base64_encode_alloc((const char *)secret->value, secret->value_size,
                        &base64);
    if (base64 == NULL) {
301
        virReportOOMError();
302 303 304
        goto cleanup;
    }

305
    if (replaceFile(filename, base64, strlen(base64)) < 0)
306 307 308 309 310 311 312 313 314 315 316
        goto cleanup;

    ret = 0;

cleanup:
    VIR_FREE(base64);
    VIR_FREE(filename);
    return ret;
}

static int
317
secretDeleteSaved(virSecretDriverStatePtr driver,
318 319 320 321 322
                  const virSecretEntry *secret)
{
    char *xml_filename = NULL, *value_filename = NULL;
    int ret = -1;

323
    xml_filename = secretXMLPath(driver, secret);
324 325
    if (xml_filename == NULL)
        goto cleanup;
326
    value_filename = secretBase64Path(driver, secret);
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
    if (value_filename == NULL)
        goto cleanup;

    if (unlink(xml_filename) < 0 && errno != ENOENT)
        goto cleanup;
    /* When the XML is missing, the rest may waste disk space, but the secret
       won't be loaded again, so we have succeeded already. */
    ret = 0;

    (void)unlink(value_filename);

cleanup:
    VIR_FREE(value_filename);
    VIR_FREE(xml_filename);
    return ret;
}

static int
345
secretLoadValidateUUID(virSecretDefPtr def,
346 347
                       const char *xml_basename)
{
348
    char uuidstr[VIR_UUID_STRING_BUFLEN];
349

350
    virUUIDFormat(def->uuid, uuidstr);
351

352
    if (!virFileMatchesNameSuffix(xml_basename, uuidstr, ".xml")) {
353 354 355
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("<uuid> does not match secret file name '%s'"),
                       xml_basename);
356 357 358 359 360 361 362
        return -1;
    }

    return 0;
}

static int
363
secretLoadValue(virSecretDriverStatePtr driver,
364 365 366 367 368 369 370
                virSecretEntryPtr secret)
{
    int ret = -1, fd = -1;
    struct stat st;
    char *filename = NULL, *contents = NULL, *value = NULL;
    size_t value_size;

371
    filename = secretBase64Path(driver, secret);
372 373 374 375 376 377 378 379 380
    if (filename == NULL)
        goto cleanup;

    fd = open(filename, O_RDONLY);
    if (fd == -1) {
        if (errno == ENOENT) {
            ret = 0;
            goto cleanup;
        }
381
        virReportSystemError(errno, _("cannot open '%s'"), filename);
382 383 384
        goto cleanup;
    }
    if (fstat(fd, &st) < 0) {
385
        virReportSystemError(errno, _("cannot stat '%s'"), filename);
386 387 388
        goto cleanup;
    }
    if ((size_t)st.st_size != st.st_size) {
389 390
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("'%s' file does not fit in memory"), filename);
391 392 393 394
        goto cleanup;
    }

    if (VIR_ALLOC_N(contents, st.st_size) < 0) {
395
        virReportOOMError();
396 397 398
        goto cleanup;
    }
    if (saferead(fd, contents, st.st_size) != st.st_size) {
399
        virReportSystemError(errno, _("cannot read '%s'"), filename);
400 401
        goto cleanup;
    }
402
    VIR_FORCE_CLOSE(fd);
403 404

    if (!base64_decode_alloc(contents, st.st_size, &value, &value_size)) {
405 406
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("invalid base64 in '%s'"), filename);
407 408 409
        goto cleanup;
    }
    if (value == NULL) {
410
        virReportOOMError();
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
        goto cleanup;
    }

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

    ret = 0;

cleanup:
    if (value != NULL) {
        memset(value, 0, value_size);
        VIR_FREE(value);
    }
    if (contents != NULL) {
        memset(contents, 0, st.st_size);
        VIR_FREE(contents);
    }
429
    VIR_FORCE_CLOSE(fd);
430 431 432 433 434
    VIR_FREE(filename);
    return ret;
}

static virSecretEntryPtr
435
secretLoad(virSecretDriverStatePtr driver,
436 437
           const char *xml_basename)
{
438
    virSecretDefPtr def = NULL;
439 440 441 442 443
    virSecretEntryPtr secret = NULL, ret = NULL;
    char *xml_filename;

    if (virAsprintf(&xml_filename, "%s/%s", driver->directory,
                    xml_basename) < 0) {
444
        virReportOOMError();
445 446
        goto cleanup;
    }
447
    def = virSecretDefParseFile(xml_filename);
448 449 450 451
    if (def == NULL)
        goto cleanup;
    VIR_FREE(xml_filename);

452
    if (secretLoadValidateUUID(def, xml_basename) < 0)
453 454
        goto cleanup;

455
    if (VIR_ALLOC(secret) < 0) {
456
        virReportOOMError();
457
        goto cleanup;
458
    }
459 460 461
    secret->def = def;
    def = NULL;

462
    if (secretLoadValue(driver, secret) < 0)
463 464 465 466 467 468 469 470 471 472 473 474 475
        goto cleanup;

    ret = secret;
    secret = NULL;

cleanup:
    secretFree(secret);
    virSecretDefFree(def);
    VIR_FREE(xml_filename);
    return ret;
}

static int
476
loadSecrets(virSecretDriverStatePtr driver,
477 478 479 480 481 482 483 484 485 486 487
            virSecretEntryPtr *dest)
{
    int ret = -1;
    DIR *dir = NULL;
    struct dirent *de;
    virSecretEntryPtr list = NULL;

    dir = opendir(driver->directory);
    if (dir == NULL) {
        if (errno == ENOENT)
            return 0;
488
        virReportSystemError(errno, _("cannot open '%s'"),
489 490 491 492 493 494 495 496 497 498 499
                             driver->directory);
        goto cleanup;
    }
    while ((de = readdir(dir)) != NULL) {
        virSecretEntryPtr secret;

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

500
        secret = secretLoad(driver, de->d_name);
501 502 503
        if (secret == NULL) {
            virErrorPtr err = virGetLastError();

504
            VIR_ERROR(_("Error reading secret: %s"),
505
                      err != NULL ? err->message: _("unknown error"));
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
            virResetError(err);
            continue;
        }
        listInsert(&list, secret);
    }
    /* Ignore error reported by readdir(), if any.  It's better to keep the
       secrets we managed to find. */

    while (list != NULL) {
        virSecretEntryPtr s;

        s = listUnlink(&list);
        listInsert(dest, s);
    }

    ret = 0;

cleanup:
    if (dir != NULL)
        closedir(dir);
    return ret;
}

 /* Driver functions */

static virDrvOpenStatus
secretOpen(virConnectPtr conn, virConnectAuthPtr auth ATTRIBUTE_UNUSED,
533 534 535 536
           unsigned int flags)
{
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
    if (driverState == NULL)
        return VIR_DRV_OPEN_DECLINED;

    conn->secretPrivateData = driverState;
    return VIR_DRV_OPEN_SUCCESS;
}

static int
secretClose(virConnectPtr conn) {
    conn->secretPrivateData = NULL;
    return 0;
}

static int
secretNumOfSecrets(virConnectPtr conn)
{
    virSecretDriverStatePtr driver = conn->secretPrivateData;
    int i;
    virSecretEntryPtr secret;

    secretDriverLock(driver);

    i = 0;
    for (secret = driver->secrets; secret != NULL; secret = secret->next)
        i++;

    secretDriverUnlock(driver);
    return i;
}

static int
secretListSecrets(virConnectPtr conn, char **uuids, int maxuuids)
{
    virSecretDriverStatePtr driver = conn->secretPrivateData;
    int i;
    virSecretEntryPtr secret;

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

    secretDriverLock(driver);

    i = 0;
    for (secret = driver->secrets; secret != NULL; secret = secret->next) {
580
        char *uuidstr;
581 582
        if (i == maxuuids)
            break;
583
        if (VIR_ALLOC_N(uuidstr, VIR_UUID_STRING_BUFLEN) < 0) {
584
            virReportOOMError();
585
            goto cleanup;
586
        }
587 588
        virUUIDFormat(secret->def->uuid, uuidstr);
        uuids[i] = uuidstr;
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
        i++;
    }

    secretDriverUnlock(driver);
    return i;

cleanup:
    secretDriverUnlock(driver);

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

    return -1;
}

604 605 606 607 608 609 610 611 612 613
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 已提交
614 615 616
    case VIR_SECRET_USAGE_TYPE_CEPH:
        return def->usage.ceph;

617 618 619 620 621
    default:
        return NULL;
    }
}

O
Osier Yang 已提交
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 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701
#define MATCH(FLAG) (flags & (FLAG))
static int
secretListAllSecrets(virConnectPtr conn,
                     virSecretPtr **secrets,
                     unsigned int flags) {
    virSecretDriverStatePtr driver = conn->secretPrivateData;
    virSecretPtr *tmp_secrets = NULL;
    int nsecrets = 0;
    int ret_nsecrets = 0;
    virSecretPtr secret = NULL;
    virSecretEntryPtr entry = NULL;
    int i = 0;
    int ret = -1;

    virCheckFlags(VIR_CONNECT_LIST_SECRETS_FILTERS_ALL, -1);

    secretDriverLock(driver);

    for (entry = driver->secrets; entry != NULL; entry = entry->next)
        nsecrets++;

    if (secrets) {
        if (VIR_ALLOC_N(tmp_secrets, nsecrets + 1) < 0) {
            virReportOOMError();
            goto cleanup;
        }
    }

    for (entry = driver->secrets; entry != NULL; entry = entry->next) {
        /* filter by whether it's ephemeral */
        if (MATCH(VIR_CONNECT_LIST_SECRETS_FILTERS_EPHEMERAL) &&
            !((MATCH(VIR_CONNECT_LIST_SECRETS_EPHEMERAL) &&
               entry->def->ephemeral) ||
              (MATCH(VIR_CONNECT_LIST_SECRETS_NO_EPHEMERAL) &&
               !entry->def->ephemeral)))
            continue;

        /* filter by whether it's private */
        if (MATCH(VIR_CONNECT_LIST_SECRETS_FILTERS_PRIVATE) &&
            !((MATCH(VIR_CONNECT_LIST_SECRETS_PRIVATE) &&
               entry->def->private) ||
              (MATCH(VIR_CONNECT_LIST_SECRETS_NO_PRIVATE) &&
               !entry->def->private)))
            continue;

        if (secrets) {
            if (!(secret = virGetSecret(conn,
                                        entry->def->uuid,
                                        entry->def->usage_type,
                                        secretUsageIDForDef(entry->def))))
                goto cleanup;
            tmp_secrets[ret_nsecrets] = secret;
        }
        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:
    secretDriverUnlock(driver);
    if (tmp_secrets) {
        for (i = 0; i < ret_nsecrets; i ++) {
            if (tmp_secrets[i])
                virSecretFree(tmp_secrets[i]);
        }
    }
    VIR_FREE(tmp_secrets);

    return ret;
}
#undef MATCH


702
static virSecretPtr
703
secretLookupByUUID(virConnectPtr conn, const unsigned char *uuid)
704 705 706
{
    virSecretDriverStatePtr driver = conn->secretPrivateData;
    virSecretPtr ret = NULL;
707
    virSecretEntryPtr secret;
708 709 710

    secretDriverLock(driver);

711 712
    secret = secretFindByUUID(driver, uuid);
    if (secret == NULL) {
713 714
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(uuid, uuidstr);
715 716
        virReportError(VIR_ERR_NO_SECRET,
                       _("no secret with matching uuid '%s'"), uuidstr);
717 718 719
        goto cleanup;
    }

720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741
    ret = virGetSecret(conn,
                       secret->def->uuid,
                       secret->def->usage_type,
                       secretUsageIDForDef(secret->def));

cleanup:
    secretDriverUnlock(driver);
    return ret;
}


static virSecretPtr
secretLookupByUsage(virConnectPtr conn, int usageType, const char *usageID)
{
    virSecretDriverStatePtr driver = conn->secretPrivateData;
    virSecretPtr ret = NULL;
    virSecretEntryPtr secret;

    secretDriverLock(driver);

    secret = secretFindByUsage(driver, usageType, usageID);
    if (secret == NULL) {
742 743
        virReportError(VIR_ERR_NO_SECRET,
                       _("no secret with matching usage '%s'"), usageID);
744 745 746 747 748 749 750
        goto cleanup;
    }

    ret = virGetSecret(conn,
                       secret->def->uuid,
                       secret->def->usage_type,
                       secretUsageIDForDef(secret->def));
751 752 753 754 755 756 757 758 759

cleanup:
    secretDriverUnlock(driver);
    return ret;
}


static virSecretPtr
secretDefineXML(virConnectPtr conn, const char *xml,
760
                unsigned int flags)
761 762 763 764
{
    virSecretDriverStatePtr driver = conn->secretPrivateData;
    virSecretPtr ret = NULL;
    virSecretEntryPtr secret;
765 766
    virSecretDefPtr backup = NULL;
    virSecretDefPtr new_attrs;
767

768 769
    virCheckFlags(0, NULL);

770
    new_attrs = virSecretDefParseString(xml);
771 772 773 774 775
    if (new_attrs == NULL)
        return NULL;

    secretDriverLock(driver);

776 777 778 779 780 781 782 783
    secret = secretFindByUUID(driver, new_attrs->uuid);
    if (secret == NULL) {
        /* No existing secret with same UUID, try look for matching usage instead */
        const char *usageID = secretUsageIDForDef(new_attrs);
        secret = secretFindByUsage(driver, new_attrs->usage_type, usageID);
        if (secret) {
            char uuidstr[VIR_UUID_STRING_BUFLEN];
            virUUIDFormat(secret->def->uuid, uuidstr);
784 785 786
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("a secret with UUID %s already defined for use with %s"),
                           uuidstr, usageID);
787 788
            goto cleanup;
        }
789

790 791
        /* No existing secret at all, create one */
        if (VIR_ALLOC(secret) < 0) {
792
            virReportOOMError();
793 794
            goto cleanup;
        }
795

796 797 798 799 800 801 802 803
        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);
804 805 806
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("a secret with UUID %s is already defined for use with %s"),
                           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(driver, secret) < 0)
824 825
                goto restore_backup;
        }
826
        if (secretSaveDef(driver, secret) < 0) {
827
            if (backup && backup->ephemeral) {
828 829 830
                char *filename;

                /* Undo the secretSaveValue() above; ignore errors */
831
                filename = secretBase64Path(driver, secret);
832 833 834 835 836 837
                if (filename != NULL)
                    (void)unlink(filename);
                VIR_FREE(filename);
            }
            goto restore_backup;
        }
838
    } else if (backup && !backup->ephemeral) {
839
        if (secretDeleteSaved(driver, secret) < 0)
840 841
            goto restore_backup;
    }
842
    /* Saved successfully - drop old values */
843 844 845
    new_attrs = NULL;
    virSecretDefFree(backup);

846 847 848 849
    ret = virGetSecret(conn,
                       secret->def->uuid,
                       secret->def->usage_type,
                       secretUsageIDForDef(secret->def));
850 851 852
    goto cleanup;

restore_backup:
853 854 855 856
    if (backup) {
        /* Error - restore previous state and free new attributes */
        secret->def = backup;
    } else {
857 858
        /* "secret" was added to the head of the list above */
        if (listUnlink(&driverState->secrets) != secret)
859 860
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("list of secrets is inconsistent"));
861 862 863 864 865 866 867 868 869 870 871 872
        else
            secretFree(secret);
    }

cleanup:
    virSecretDefFree(new_attrs);
    secretDriverUnlock(driver);

    return ret;
}

static char *
873
secretGetXMLDesc(virSecretPtr obj, unsigned int flags)
874 875 876
{
    virSecretDriverStatePtr driver = obj->conn->secretPrivateData;
    char *ret = NULL;
877
    virSecretEntryPtr secret;
878

879 880
    virCheckFlags(0, NULL);

881 882
    secretDriverLock(driver);

883 884
    secret = secretFindByUUID(driver, obj->uuid);
    if (secret == NULL) {
885 886
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(obj->uuid, uuidstr);
887 888
        virReportError(VIR_ERR_NO_SECRET,
                       _("no secret with matching uuid '%s'"), uuidstr);
889 890 891
        goto cleanup;
    }

892
    ret = virSecretDefFormat(secret->def);
893 894 895 896 897 898 899 900 901

cleanup:
    secretDriverUnlock(driver);

    return ret;
}

static int
secretSetValue(virSecretPtr obj, const unsigned char *value,
902
               size_t value_size, unsigned int flags)
903 904 905 906 907
{
    virSecretDriverStatePtr driver = obj->conn->secretPrivateData;
    int ret = -1;
    unsigned char *old_value, *new_value;
    size_t old_value_size;
908
    virSecretEntryPtr secret;
909

910 911
    virCheckFlags(0, -1);

912
    if (VIR_ALLOC_N(new_value, value_size) < 0) {
913
        virReportOOMError();
914 915 916 917 918
        return -1;
    }

    secretDriverLock(driver);

919 920
    secret = secretFindByUUID(driver, obj->uuid);
    if (secret == NULL) {
921 922
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(obj->uuid, uuidstr);
923 924
        virReportError(VIR_ERR_NO_SECRET,
                       _("no secret with matching uuid '%s'"), uuidstr);
925 926 927 928 929 930 931 932 933 934
        goto cleanup;
    }

    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) {
935
        if (secretSaveValue(driver, secret) < 0)
936 937
            goto restore_backup;
    }
938
    /* Saved successfully - drop old value */
939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962
    if (old_value != NULL) {
        memset(old_value, 0, old_value_size);
        VIR_FREE(old_value);
    }
    new_value = NULL;

    ret = 0;
    goto cleanup;

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

cleanup:
    secretDriverUnlock(driver);

    VIR_FREE(new_value);

    return ret;
}

static unsigned char *
963 964
secretGetValue(virSecretPtr obj, size_t *value_size, unsigned int flags,
               unsigned int internalFlags)
965 966 967
{
    virSecretDriverStatePtr driver = obj->conn->secretPrivateData;
    unsigned char *ret = NULL;
968
    virSecretEntryPtr secret;
969

970 971
    virCheckFlags(0, NULL);

972 973
    secretDriverLock(driver);

974 975
    secret = secretFindByUUID(driver, obj->uuid);
    if (secret == NULL) {
976 977
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(obj->uuid, uuidstr);
978 979
        virReportError(VIR_ERR_NO_SECRET,
                       _("no secret with matching uuid '%s'"), uuidstr);
980 981
        goto cleanup;
    }
982

983
    if (secret->value == NULL) {
984 985
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(obj->uuid, uuidstr);
986 987
        virReportError(VIR_ERR_NO_SECRET,
                       _("secret '%s' does not have a value"), uuidstr);
988 989 990
        goto cleanup;
    }

991
    if ((internalFlags & VIR_SECRET_GET_VALUE_INTERNAL_CALL) == 0 &&
992
        secret->def->private) {
993
        virReportError(VIR_ERR_INVALID_SECRET, "%s",
994
                       _("secret is private"));
995 996 997 998
        goto cleanup;
    }

    if (VIR_ALLOC_N(ret, secret->value_size) < 0) {
999
        virReportOOMError();
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
        goto cleanup;
    }
    memcpy(ret, secret->value, secret->value_size);
    *value_size = secret->value_size;

cleanup:
    secretDriverUnlock(driver);

    return ret;
}

static int
secretUndefine(virSecretPtr obj)
{
    virSecretDriverStatePtr driver = obj->conn->secretPrivateData;
    int ret = -1;
1016
    virSecretEntryPtr secret;
1017 1018 1019

    secretDriverLock(driver);

1020 1021
    secret = secretFindByUUID(driver, obj->uuid);
    if (secret == NULL) {
1022 1023
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(obj->uuid, uuidstr);
1024 1025
        virReportError(VIR_ERR_NO_SECRET,
                       _("no secret with matching uuid '%s'"), uuidstr);
1026 1027 1028
        goto cleanup;
    }

1029
    if (!secret->def->ephemeral &&
1030
        secretDeleteSaved(driver, secret) < 0)
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
        goto cleanup;

    if (driver->secrets == secret) {
        driver->secrets = secret->next;
    } else {
        virSecretEntryPtr tmp = driver->secrets;
        while (tmp && tmp->next != secret)
            tmp = tmp->next;
        if (tmp)
            tmp->next = secret->next;
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
    }
    secretFree(secret);

    ret = 0;

cleanup:
    secretDriverUnlock(driver);

    return ret;
}

static int
secretDriverCleanup(void)
{
    if (driverState == NULL)
        return -1;

    secretDriverLock(driverState);

    while (driverState->secrets != NULL) {
        virSecretEntryPtr s;

        s = listUnlink(&driverState->secrets);
        secretFree(s);
    }
    VIR_FREE(driverState->directory);

    secretDriverUnlock(driverState);
    virMutexDestroy(&driverState->lock);
    VIR_FREE(driverState);

    return 0;
}

static int
1076 1077 1078
secretDriverStartup(bool privileged,
                    virStateInhibitCallback callback ATTRIBUTE_UNUSED,
                    void *opaque ATTRIBUTE_UNUSED)
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
{
    char *base = NULL;

    if (VIR_ALLOC(driverState) < 0)
        return -1;

    if (virMutexInit(&driverState->lock) < 0) {
        VIR_FREE(driverState);
        return -1;
    }
    secretDriverLock(driverState);

    if (privileged) {
1092
        base = strdup(SYSCONFDIR "/libvirt");
1093 1094 1095
        if (base == NULL)
            goto out_of_memory;
    } else {
1096
        base = virGetUserConfigDirectory();
1097
        if (!base)
1098 1099 1100 1101 1102 1103
            goto error;
    }
    if (virAsprintf(&driverState->directory, "%s/secrets", base) == -1)
        goto out_of_memory;
    VIR_FREE(base);

1104
    if (loadSecrets(driverState, &driverState->secrets) < 0)
1105 1106 1107 1108 1109 1110
        goto error;

    secretDriverUnlock(driverState);
    return 0;

 out_of_memory:
1111
    VIR_ERROR(_("Out of memory initializing secrets"));
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
 error:
    VIR_FREE(base);
    secretDriverUnlock(driverState);
    secretDriverCleanup();
    return -1;
}

static int
secretDriverReload(void)
{
    virSecretEntryPtr new_secrets = NULL;

    if (!driverState)
        return -1;

    secretDriverLock(driverState);

1129
    if (loadSecrets(driverState, &new_secrets) < 0)
1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
        goto end;

    /* Keep ephemeral secrets from current state.  Discard non-ephemeral secrets
       that were removed by the secrets directory.  */
    while (driverState->secrets != NULL) {
        virSecretEntryPtr s;

        s = listUnlink(&driverState->secrets);
        if (s->def->ephemeral)
            listInsert(&new_secrets, s);
        else
            secretFree(s);
    }
    driverState->secrets = new_secrets;

 end:
    secretDriverUnlock(driverState);
    return 0;
}

static virSecretDriver secretDriver = {
    .name = "secret",
1152 1153 1154 1155
    .open = secretOpen, /* 0.7.1 */
    .close = secretClose, /* 0.7.1 */
    .numOfSecrets = secretNumOfSecrets, /* 0.7.1 */
    .listSecrets = secretListSecrets, /* 0.7.1 */
O
Osier Yang 已提交
1156
    .listAllSecrets = secretListAllSecrets, /* 0.10.2 */
1157 1158 1159 1160 1161 1162 1163
    .lookupByUUID = secretLookupByUUID, /* 0.7.1 */
    .lookupByUsage = secretLookupByUsage, /* 0.7.1 */
    .defineXML = secretDefineXML, /* 0.7.1 */
    .getXMLDesc = secretGetXMLDesc, /* 0.7.1 */
    .setValue = secretSetValue, /* 0.7.1 */
    .getValue = secretGetValue, /* 0.7.1 */
    .undefine = secretUndefine, /* 0.7.1 */
1164 1165 1166
};

static virStateDriver stateDriver = {
1167
    .name = "Secret",
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
    .initialize = secretDriverStartup,
    .cleanup = secretDriverCleanup,
    .reload = secretDriverReload,
};

int
secretRegister(void)
{
    virRegisterSecretDriver(&secretDriver);
    virRegisterStateDriver(&stateDriver);
    return 0;
}