libvirt.c 37.7 KB
Newer Older
D
Daniel P. Berrange 已提交
1
/*
2
 * libvirt.c: Main interfaces for the libvirt library to handle virtualization
D
Daniel Veillard 已提交
3 4
 *           domains from a process running in domain 0
 *
E
Eric Blake 已提交
5
 * Copyright (C) 2005-2006, 2008-2014 Red Hat, Inc.
D
Daniel Veillard 已提交
6
 *
O
Osier Yang 已提交
7 8 9 10 11 12 13 14 15 16 17
 * 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
18
 * License along with this library.  If not, see
O
Osier Yang 已提交
19
 * <http://www.gnu.org/licenses/>.
D
Daniel Veillard 已提交
20 21 22 23
 *
 * Daniel Veillard <veillard@redhat.com>
 */

24
#include <config.h>
D
Daniel Veillard 已提交
25

26
#include <stdio.h>
27
#include <stdlib.h>
28
#include <string.h>
29 30 31
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
E
Eric Blake 已提交
32
#include <sys/wait.h>
33
#include <time.h>
34

35 36
#include <libxml/parser.h>
#include <libxml/xpath.h>
37 38
#include "getpass.h"

39
#ifdef HAVE_WINSOCK2_H
40
# include <winsock2.h>
41
#endif
42

43
#ifdef WITH_CURL
44 45 46
# include <curl/curl.h>
#endif

47
#include "virerror.h"
48
#include "virlog.h"
49
#include "datatypes.h"
50
#include "driver.h"
51

52
#include "viruuid.h"
53
#include "viralloc.h"
54
#include "configmake.h"
55
#include "virconf.h"
56
#if WITH_GNUTLS
57 58 59
# if WITH_GNUTLS_GCRYPT
#  include <gcrypt.h>
# endif
60 61
# include "rpc/virnettlscontext.h"
#endif
62
#include "vircommand.h"
63
#include "virfile.h"
64
#include "virrandom.h"
M
Martin Kletzander 已提交
65
#include "viruri.h"
66
#include "virthread.h"
67
#include "virstring.h"
E
Eric Blake 已提交
68
#include "virutil.h"
69
#include "virtypedparam.h"
70

71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
#ifdef WITH_TEST
# include "test/test_driver.h"
#endif
#ifdef WITH_REMOTE
# include "remote/remote_driver.h"
#endif
#ifdef WITH_OPENVZ
# include "openvz/openvz_driver.h"
#endif
#ifdef WITH_VMWARE
# include "vmware/vmware_driver.h"
#endif
#ifdef WITH_PHYP
# include "phyp/phyp_driver.h"
#endif
#ifdef WITH_ESX
# include "esx/esx_driver.h"
#endif
#ifdef WITH_HYPERV
# include "hyperv/hyperv_driver.h"
#endif
#ifdef WITH_XENAPI
# include "xenapi/xenapi_driver.h"
94
#endif
95
#ifdef WITH_VZ
96
# include "vz/vz_driver.h"
D
Dmitry Guryanov 已提交
97
#endif
R
Roman Bogorodskiy 已提交
98 99 100
#ifdef WITH_BHYVE
# include "bhyve/bhyve_driver.h"
#endif
101

102 103
#define VIR_FROM_THIS VIR_FROM_NONE

104 105
VIR_LOG_INIT("libvirt");

D
Daniel Veillard 已提交
106 107 108
/*
 * TODO:
 * - use lock to protect against concurrent accesses ?
D
Daniel Veillard 已提交
109
 * - use reference counting to guarantee coherent pointer state ?
D
Daniel Veillard 已提交
110 111
 */

112
#define MAX_DRIVERS 21
113

114 115
static virConnectDriverPtr virConnectDriverTab[MAX_DRIVERS];
static int virConnectDriverTabCount;
116
static virStateDriverPtr virStateDriverTab[MAX_DRIVERS];
117
static int virStateDriverTabCount;
118

119 120 121 122 123 124 125
static virNetworkDriverPtr virSharedNetworkDriver;
static virInterfaceDriverPtr virSharedInterfaceDriver;
static virStorageDriverPtr virSharedStorageDriver;
static virNodeDeviceDriverPtr virSharedNodeDeviceDriver;
static virSecretDriverPtr virSharedSecretDriver;
static virNWFilterDriverPtr virSharedNWFilterDriver;

126

127
#if defined(POLKIT_AUTH)
128 129 130
static int
virConnectAuthGainPolkit(const char *privilege)
{
E
Eric Blake 已提交
131 132
    virCommandPtr cmd;
    int ret = -1;
133

134
    if (geteuid() == 0)
135 136
        return 0;

E
Eric Blake 已提交
137
    cmd = virCommandNewArgList(POLKIT_AUTH, "--obtain", privilege, NULL);
138
    if (virCommandRun(cmd, NULL) < 0)
E
Eric Blake 已提交
139
        goto cleanup;
140

E
Eric Blake 已提交
141
    ret = 0;
142
 cleanup:
E
Eric Blake 已提交
143 144
    virCommandFree(cmd);
    return ret;
145 146 147
}
#endif

148 149 150 151 152 153

static int
virConnectAuthCallbackDefault(virConnectCredentialPtr cred,
                              unsigned int ncred,
                              void *cbdata ATTRIBUTE_UNUSED)
{
154
    size_t i;
155

156
    for (i = 0; i < ncred; i++) {
157 158
        char buf[1024];
        char *bufptr = buf;
159
        size_t len;
160 161

        switch (cred[i].type) {
162 163 164 165
        case VIR_CRED_EXTERNAL: {
            if (STRNEQ(cred[i].challenge, "PolicyKit"))
                return -1;

166
#if defined(POLKIT_AUTH)
167
            if (virConnectAuthGainPolkit(cred[i].prompt) < 0)
168
                return -1;
169 170 171 172 173 174 175
#else
            /*
             * Ignore & carry on. Although we can't auth
             * directly, the user may have authenticated
             * themselves already outside context of libvirt
             */
#endif
176 177
            break;
        }
178

179 180 181 182
        case VIR_CRED_USERNAME:
        case VIR_CRED_AUTHNAME:
        case VIR_CRED_ECHOPROMPT:
        case VIR_CRED_REALM:
183
            if (printf("%s: ", cred[i].prompt) < 0)
184 185 186 187
                return -1;
            if (fflush(stdout) != 0)
                return -1;

188 189 190 191 192 193 194
            if (!fgets(buf, sizeof(buf), stdin)) {
                if (feof(stdin)) { /* Treat EOF as "" */
                    buf[0] = '\0';
                    break;
                }
                return -1;
            }
195 196 197
            len = strlen(buf);
            if (len != 0 && buf[len-1] == '\n')
                buf[len-1] = '\0';
198 199 200 201
            break;

        case VIR_CRED_PASSPHRASE:
        case VIR_CRED_NOECHOPROMPT:
202
            if (printf("%s: ", cred[i].prompt) < 0)
203 204 205 206
                return -1;
            if (fflush(stdout) != 0)
                return -1;

207 208 209 210
            bufptr = getpass("");
            if (!bufptr)
                return -1;
            break;
211 212 213

        default:
            return -1;
214 215
        }

D
Daniel P. Berrange 已提交
216
        if (cred[i].type != VIR_CRED_EXTERNAL) {
217 218 219
            if (VIR_STRDUP(cred[i].result,
                           STREQ(bufptr, "") && cred[i].defresult ?
                           cred[i].defresult : bufptr) < 0)
D
Daniel P. Berrange 已提交
220 221 222
                return -1;
            cred[i].resultlen = strlen(cred[i].result);
        }
223 224 225 226 227
    }

    return 0;
}

228

229 230 231 232 233 234 235 236 237 238
/* Don't typically want VIR_CRED_USERNAME. It enables you to authenticate
 * as one user, and act as another. It just results in annoying
 * prompts for the username twice & is very rarely what you want
 */
static int virConnectCredTypeDefault[] = {
    VIR_CRED_AUTHNAME,
    VIR_CRED_ECHOPROMPT,
    VIR_CRED_REALM,
    VIR_CRED_PASSPHRASE,
    VIR_CRED_NOECHOPROMPT,
239
    VIR_CRED_EXTERNAL,
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
};

static virConnectAuth virConnectAuthDefault = {
    virConnectCredTypeDefault,
    sizeof(virConnectCredTypeDefault)/sizeof(int),
    virConnectAuthCallbackDefault,
    NULL,
};

/*
 * virConnectAuthPtrDefault
 *
 * A default implementation of the authentication callbacks. This
 * implementation is suitable for command line based tools. It will
 * prompt for username, passwords, realm and one time keys as needed.
 * It will print on STDOUT, and read from STDIN. If this is not
 * suitable for the application's needs an alternative implementation
 * should be provided.
 */
virConnectAuthPtr virConnectAuthPtrDefault = &virConnectAuthDefault;

261 262
#if HAVE_WINSOCK2_H
static int
263
winsock_init(void)
264 265 266 267 268 269 270
{
    WORD winsock_version, err;
    WSADATA winsock_data;

    /* http://msdn2.microsoft.com/en-us/library/ms742213.aspx */
    winsock_version = MAKEWORD (2, 2);
    err = WSAStartup (winsock_version, &winsock_data);
J
Jim Meyering 已提交
271
    return err == 0 ? 0 : -1;
272 273 274
}
#endif

275

276
#ifdef WITH_GNUTLS_GCRYPT
277 278
static int
virTLSMutexInit(void **priv)
279
{
D
Daniel P. Berrange 已提交
280 281
    virMutexPtr lock = NULL;

282
    if (VIR_ALLOC_QUIET(lock) < 0)
D
Daniel P. Berrange 已提交
283 284 285 286 287 288 289 290 291 292 293
        return ENOMEM;

    if (virMutexInit(lock) < 0) {
        VIR_FREE(lock);
        return errno;
    }

    *priv = lock;
    return 0;
}

294 295 296

static int
virTLSMutexDestroy(void **priv)
D
Daniel P. Berrange 已提交
297 298 299 300 301 302 303
{
    virMutexPtr lock = *priv;
    virMutexDestroy(lock);
    VIR_FREE(lock);
    return 0;
}

304 305 306

static int
virTLSMutexLock(void **priv)
D
Daniel P. Berrange 已提交
307 308 309 310 311 312
{
    virMutexPtr lock = *priv;
    virMutexLock(lock);
    return 0;
}

313 314 315

static int
virTLSMutexUnlock(void **priv)
D
Daniel P. Berrange 已提交
316 317 318 319 320 321
{
    virMutexPtr lock = *priv;
    virMutexUnlock(lock);
    return 0;
}

322

D
Daniel P. Berrange 已提交
323
static struct gcry_thread_cbs virTLSThreadImpl = {
324
    /* GCRY_THREAD_OPTION_VERSION was added in gcrypt 1.4.2 */
325
# ifdef GCRY_THREAD_OPTION_VERSION
D
Daniel P. Berrange 已提交
326
    (GCRY_THREAD_OPTION_PTHREAD | (GCRY_THREAD_OPTION_VERSION << 8)),
327
# else
328
    GCRY_THREAD_OPTION_PTHREAD,
329
# endif
D
Daniel P. Berrange 已提交
330 331 332 333 334 335 336
    NULL,
    virTLSMutexInit,
    virTLSMutexDestroy,
    virTLSMutexLock,
    virTLSMutexUnlock,
    NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
};
337
#endif /* WITH_GNUTLS_GCRYPT */
D
Daniel P. Berrange 已提交
338

339

340
static bool virGlobalError;
341
static virOnceControl virGlobalOnce = VIR_ONCE_CONTROL_INITIALIZER;
342

343 344 345
static void
virGlobalInit(void)
{
346 347 348 349 350
    /* It would be nice if we could trace the use of this call, to
     * help diagnose in log files if a user calls something other than
     * virConnectOpen first.  But we can't rely on VIR_DEBUG working
     * until after initialization is complete, and since this is
     * one-shot, we never get here again.  */
351
    if (virThreadInitialize() < 0 ||
352
        virErrorInitialize() < 0)
353
        goto error;
354

355
#ifndef LIBVIRT_SETUID_RPC_CLIENT
356 357 358 359 360 361 362
    if (virIsSUID()) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libvirt.so is not safe to use from setuid programs"));
        goto error;
    }
#endif

363
#ifdef WITH_GNUTLS_GCRYPT
364 365 366 367 368 369 370 371 372 373 374 375 376
    /*
     * This sequence of API calls it copied exactly from
     * gnutls 2.12.23 source lib/gcrypt/init.c, with
     * exception that GCRYCTL_ENABLE_QUICK_RANDOM, is
     * dropped
     */
    if (gcry_control(GCRYCTL_ANY_INITIALIZATION_P) == 0) {
        gcry_control(GCRYCTL_SET_THREAD_CBS, &virTLSThreadImpl);
        gcry_check_version(NULL);

        gcry_control(GCRYCTL_DISABLE_SECMEM, NULL, 0);
        gcry_control(GCRYCTL_INITIALIZATION_FINISHED, NULL, 0);
    }
377
#endif
D
Daniel P. Berrange 已提交
378

379
    virLogSetFromEnv();
380

381
#ifdef WITH_GNUTLS
382
    virNetTLSInit();
383
#endif
384

385
#if WITH_CURL
386 387 388
    curl_global_init(CURL_GLOBAL_DEFAULT);
#endif

389
    VIR_DEBUG("register drivers");
390

391
#if HAVE_WINSOCK2_H
392
    if (winsock_init() == -1)
393
        goto error;
394 395
#endif

396
    if (!bindtextdomain(PACKAGE, LOCALEDIR))
397
        goto error;
398

399 400 401 402 403
    /*
     * Note we must avoid everything except 'remote' driver
     * for virt-login-shell usage
     */
#ifndef LIBVIRT_SETUID_RPC_CLIENT
404
    /*
405 406
     * Note that the order is important: the first ones have a higher
     * priority when calling virConnectOpen.
407
     */
408
# ifdef WITH_TEST
409 410
    if (testRegister() == -1)
        goto error;
411 412
# endif
# ifdef WITH_OPENVZ
413 414
    if (openvzRegister() == -1)
        goto error;
415 416
# endif
# ifdef WITH_VMWARE
417 418
    if (vmwareRegister() == -1)
        goto error;
419 420
# endif
# ifdef WITH_PHYP
421 422
    if (phypRegister() == -1)
        goto error;
423 424
# endif
# ifdef WITH_ESX
425 426
    if (esxRegister() == -1)
        goto error;
427 428
# endif
# ifdef WITH_HYPERV
429 430
    if (hypervRegister() == -1)
        goto error;
431 432
# endif
# ifdef WITH_XENAPI
433 434
    if (xenapiRegister() == -1)
        goto error;
435
# endif
436
# ifdef WITH_VZ
437
    if (vzRegister() == -1)
438
        goto error;
439
# endif
D
Dmitry Guryanov 已提交
440
#endif
441
#ifdef WITH_REMOTE
442
    if (remoteRegister() == -1)
443
        goto error;
444
#endif
D
Daniel P. Berrange 已提交
445

446 447
    return;

448
 error:
449 450 451
    virGlobalError = true;
}

452

453 454 455 456 457
/**
 * virInitialize:
 *
 * Initialize the library.
 *
458 459 460 461 462 463
 * This method is invoked automatically by any of the virConnectOpen() API
 * calls, and by virGetVersion(). Since release 1.0.0, there is no need to
 * call this method even in a multithreaded application, since
 * initialization is performed in a thread safe manner; but applications
 * using an older version of the library should manually call this before
 * setting up competing threads that attempt virConnectOpen in parallel.
464
 *
465 466 467 468 469
 * The only other time it would be necessary to call virInitialize is if the
 * application did not invoke virConnectOpen as its first API call, such
 * as when calling virEventRegisterImpl() before setting up connections,
 * or when using virSetErrorFunc() to alter error reporting of the first
 * connection attempt.
470 471 472 473 474 475 476 477 478 479 480
 *
 * Returns 0 in case of success, -1 in case of error
 */
int
virInitialize(void)
{
    if (virOnce(&virGlobalOnce, virGlobalInit) < 0)
        return -1;

    if (virGlobalError)
        return -1;
481
    return 0;
482 483
}

484

485 486
#ifdef WIN32
BOOL WINAPI
487
DllMain(HINSTANCE instance, DWORD reason, LPVOID ignore);
488 489

BOOL WINAPI
490 491 492
DllMain(HINSTANCE instance ATTRIBUTE_UNUSED,
        DWORD reason,
        LPVOID ignore ATTRIBUTE_UNUSED)
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
{
    switch (reason) {
    case DLL_PROCESS_ATTACH:
        virInitialize();
        break;

    case DLL_THREAD_ATTACH:
        /* Nothing todo in libvirt yet */
        break;

    case DLL_THREAD_DETACH:
        /* Release per-thread local data */
        virThreadOnExit();
        break;

    case DLL_PROCESS_DETACH:
        /* Don't bother releasing per-thread data
           since (hopefully) windows cleans up
           everything on process exit */
        break;
    }

    return TRUE;
}
#endif
518

519

520
/**
521
 * virSetSharedNetworkDriver:
522 523 524 525
 * @driver: pointer to a network driver block
 *
 * Register a network virtualization driver
 *
526
 * Returns 0 on success, or -1 in case of error.
527 528
 */
int
529
virSetSharedNetworkDriver(virNetworkDriverPtr driver)
530
{
531
    virCheckNonNullArgReturn(driver, -1);
532

533 534 535 536 537 538 539
    if (virSharedNetworkDriver) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("A network driver is already registered"));
        return -1;
    }

    VIR_DEBUG("registering %s as network driver", driver->name);
540

541 542
    virSharedNetworkDriver = driver;
    return 0;
543 544
}

545

D
Daniel Veillard 已提交
546
/**
547
 * virSetSharedInterfaceDriver:
L
Laine Stump 已提交
548
 * @driver: pointer to an interface driver block
D
Daniel Veillard 已提交
549
 *
L
Laine Stump 已提交
550
 * Register an interface virtualization driver
D
Daniel Veillard 已提交
551 552 553 554
 *
 * Returns the driver priority or -1 in case of error.
 */
int
555
virSetSharedInterfaceDriver(virInterfaceDriverPtr driver)
D
Daniel Veillard 已提交
556
{
557
    virCheckNonNullArgReturn(driver, -1);
D
Daniel Veillard 已提交
558

559 560 561 562 563
    if (virSharedInterfaceDriver) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("A interface driver is already registered"));
        return -1;
    }
D
Daniel Veillard 已提交
564

565 566 567 568
    VIR_DEBUG("registering %s as interface driver", driver->name);

    virSharedInterfaceDriver = driver;
    return 0;
D
Daniel Veillard 已提交
569 570
}

571

572
/**
573
 * virSetSharedStorageDriver:
574 575 576 577 578 579 580
 * @driver: pointer to a storage driver block
 *
 * Register a storage virtualization driver
 *
 * Returns the driver priority or -1 in case of error.
 */
int
581
virSetSharedStorageDriver(virStorageDriverPtr driver)
582
{
583
    virCheckNonNullArgReturn(driver, -1);
584

585 586 587 588 589 590 591
    if (virSharedStorageDriver) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("A storage driver is already registered"));
        return -1;
    }

    VIR_DEBUG("registering %s as storage driver", driver->name);
592

593 594
    virSharedStorageDriver = driver;
    return 0;
595 596
}

597

598
/**
599
 * virSetSharedNodeDeviceDriver:
600 601 602 603 604 605 606
 * @driver: pointer to a device monitor block
 *
 * Register a device monitor
 *
 * Returns the driver priority or -1 in case of error.
 */
int
607
virSetSharedNodeDeviceDriver(virNodeDeviceDriverPtr driver)
608
{
609
    virCheckNonNullArgReturn(driver, -1);
610

611 612 613 614 615
    if (virSharedNodeDeviceDriver) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("A node device driver is already registered"));
        return -1;
    }
616

617 618 619 620
    VIR_DEBUG("registering %s as device driver", driver->name);

    virSharedNodeDeviceDriver = driver;
    return 0;
621 622
}

623

624
/**
625
 * virSetSharedSecretDriver:
626 627 628 629 630 631 632
 * @driver: pointer to a secret driver block
 *
 * Register a secret driver
 *
 * Returns the driver priority or -1 in case of error.
 */
int
633
virSetSharedSecretDriver(virSecretDriverPtr driver)
634
{
635
    virCheckNonNullArgReturn(driver, -1);
636

637 638 639 640 641 642 643
    if (virSharedSecretDriver) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("A secret driver is already registered"));
        return -1;
    }

    VIR_DEBUG("registering %s as secret driver", driver->name);
644

645 646
    virSharedSecretDriver = driver;
    return 0;
647 648
}

649

S
Stefan Berger 已提交
650
/**
651
 * virSetSharedNWFilterDriver:
S
Stefan Berger 已提交
652 653 654 655 656 657 658
 * @driver: pointer to a network filter driver block
 *
 * Register a network filter virtualization driver
 *
 * Returns the driver priority or -1 in case of error.
 */
int
659
virSetSharedNWFilterDriver(virNWFilterDriverPtr driver)
S
Stefan Berger 已提交
660
{
661
    virCheckNonNullArgReturn(driver, -1);
S
Stefan Berger 已提交
662

663 664 665 666 667
    if (virSharedNWFilterDriver) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("A network filter driver is already registered"));
        return -1;
    }
S
Stefan Berger 已提交
668

669 670 671 672
    VIR_DEBUG("registering %s as network filter driver", driver->name);

    virSharedNWFilterDriver = driver;
    return 0;
S
Stefan Berger 已提交
673 674 675
}


676
/**
677
 * virRegisterConnectDriver:
678
 * @driver: pointer to a driver block
679
 * @setSharedDrivers: populate shared drivers
680
 *
681 682
 * Register a virtualization driver, optionally filling in
 * any empty pointers for shared secondary drivers
683 684 685 686
 *
 * Returns the driver priority or -1 in case of error.
 */
int
687 688
virRegisterConnectDriver(virConnectDriverPtr driver,
                         bool setSharedDrivers)
689
{
690
    VIR_DEBUG("driver=%p name=%s", driver,
691
              driver ? NULLSTR(driver->hypervisorDriver->name) : "(null)");
692

693
    virCheckNonNullArgReturn(driver, -1);
694 695 696 697 698 699
    if (virConnectDriverTabCount >= MAX_DRIVERS) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Too many drivers, cannot register %s"),
                       driver->hypervisorDriver->name);
        return -1;
    }
700

701
    VIR_DEBUG("registering %s as driver %d",
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717
           driver->hypervisorDriver->name, virConnectDriverTabCount);

    if (setSharedDrivers) {
        if (driver->interfaceDriver == NULL)
            driver->interfaceDriver = virSharedInterfaceDriver;
        if (driver->networkDriver == NULL)
            driver->networkDriver = virSharedNetworkDriver;
        if (driver->nodeDeviceDriver == NULL)
            driver->nodeDeviceDriver = virSharedNodeDeviceDriver;
        if (driver->nwfilterDriver == NULL)
            driver->nwfilterDriver = virSharedNWFilterDriver;
        if (driver->secretDriver == NULL)
            driver->secretDriver = virSharedSecretDriver;
        if (driver->storageDriver == NULL)
            driver->storageDriver = virSharedStorageDriver;
    }
718

719 720
    virConnectDriverTab[virConnectDriverTabCount] = driver;
    return virConnectDriverTabCount++;
721 722
}

723

724 725 726 727 728 729 730 731 732 733 734
/**
 * virRegisterStateDriver:
 * @driver: pointer to a driver block
 *
 * Register a virtualization driver
 *
 * Returns the driver priority or -1 in case of error.
 */
int
virRegisterStateDriver(virStateDriverPtr driver)
{
735
    virCheckNonNullArgReturn(driver, -1);
736 737 738 739 740 741 742

    if (virStateDriverTabCount >= MAX_DRIVERS) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Too many drivers, cannot register %s"),
                       driver->name);
        return -1;
    }
743 744 745 746 747

    virStateDriverTab[virStateDriverTabCount] = driver;
    return virStateDriverTabCount++;
}

748

749 750
/**
 * virStateInitialize:
751
 * @privileged: set to true if running with root privilege, false otherwise
752 753
 * @callback: callback to invoke to inhibit shutdown of the daemon
 * @opaque: data to pass to @callback
754
 *
755 756 757 758 759
 * Initialize all virtualization drivers. Accomplished in two phases,
 * the first being state and structure initialization followed by any
 * auto start supported by the driver.  This is done to ensure dependencies
 * that some drivers may have on another driver having been initialized
 * will exist, such as the storage driver's need to use the secret driver.
760
 *
761
 * Returns 0 if all succeed, -1 upon any failure.
762
 */
763 764 765 766
int
virStateInitialize(bool privileged,
                   virStateInhibitCallback callback,
                   void *opaque)
767
{
768
    size_t i;
769 770 771 772

    if (virInitialize() < 0)
        return -1;

773
    for (i = 0; i < virStateDriverTabCount; i++) {
774
        if (virStateDriverTab[i]->stateInitialize) {
775
            VIR_DEBUG("Running global init for %s state driver",
776
                      virStateDriverTab[i]->name);
777 778 779
            if (virStateDriverTab[i]->stateInitialize(privileged,
                                                      callback,
                                                      opaque) < 0) {
780 781 782 783
                virErrorPtr err = virGetLastError();
                VIR_ERROR(_("Initialization of %s state driver failed: %s"),
                          virStateDriverTab[i]->name,
                          err && err->message ? err->message : _("Unknown problem"));
784 785
                return -1;
            }
786
        }
787
    }
788 789 790 791 792 793 794 795

    for (i = 0; i < virStateDriverTabCount; i++) {
        if (virStateDriverTab[i]->stateAutoStart) {
            VIR_DEBUG("Running global auto start for %s state driver",
                      virStateDriverTab[i]->name);
            virStateDriverTab[i]->stateAutoStart();
        }
    }
796
    return 0;
797 798
}

799

800 801 802 803 804
/**
 * virStateCleanup:
 *
 * Run each virtualization driver's cleanup method.
 *
805
 * Returns 0 if all succeed, -1 upon any failure.
806
 */
807 808 809
int
virStateCleanup(void)
{
810 811
    size_t i;
    int ret = 0;
812

813
    for (i = 0; i < virStateDriverTabCount; i++) {
814 815
        if (virStateDriverTab[i]->stateCleanup &&
            virStateDriverTab[i]->stateCleanup() < 0)
816 817 818 819 820
            ret = -1;
    }
    return ret;
}

821

822 823 824 825 826
/**
 * virStateReload:
 *
 * Run each virtualization driver's reload method.
 *
827
 * Returns 0 if all succeed, -1 upon any failure.
828
 */
829 830 831
int
virStateReload(void)
{
832 833
    size_t i;
    int ret = 0;
834

835
    for (i = 0; i < virStateDriverTabCount; i++) {
836 837
        if (virStateDriverTab[i]->stateReload &&
            virStateDriverTab[i]->stateReload() < 0)
838 839 840 841 842
            ret = -1;
    }
    return ret;
}

843

844 845 846 847 848 849 850
/**
 * virStateStop:
 *
 * Run each virtualization driver's "stop" method.
 *
 * Returns 0 if successful, -1 on failure
 */
851 852 853
int
virStateStop(void)
{
854 855
    size_t i;
    int ret = 0;
856

857
    for (i = 0; i < virStateDriverTabCount; i++) {
858 859
        if (virStateDriverTab[i]->stateStop &&
            virStateDriverTab[i]->stateStop())
860 861 862 863
            ret = 1;
    }
    return ret;
}
864 865


866 867 868
/**
 * virGetVersion:
 * @libVer: return value for the library version (OUT)
869 870 871 872 873 874 875 876 877 878
 * @type: ignored; pass NULL
 * @typeVer: pass NULL; for historical purposes duplicates @libVer if
 * non-NULL
 *
 * Provides version information. @libVer is the version of the
 * library and will always be set unless an error occurs, in which case
 * an error code will be returned. @typeVer exists for historical
 * compatibility; if it is not NULL it will duplicate @libVer (it was
 * originally intended to return hypervisor information based on @type,
 * but due to the design of remote clients this is not reliable). To
879
 * get the version of the running hypervisor use the virConnectGetVersion()
880
 * function instead. To get the libvirt library version used by a
881 882 883
 * connection use the virConnectGetLibVersion() instead.
 *
 * This function includes a call to virInitialize() when necessary.
884 885 886 887 888
 *
 * Returns -1 in case of failure, 0 otherwise, and values for @libVer and
 *       @typeVer have the format major * 1,000,000 + minor * 1,000 + release.
 */
int
889
virGetVersion(unsigned long *libVer, const char *type ATTRIBUTE_UNUSED,
890 891
              unsigned long *typeVer)
{
892 893
    if (virInitialize() < 0)
        goto error;
894
    VIR_DEBUG("libVir=%p, type=%s, typeVer=%p", libVer, type, typeVer);
895

896
    virResetLastError();
897
    if (libVer == NULL)
898
        goto error;
899 900
    *libVer = LIBVIR_VERSION_NUMBER;

901
    if (typeVer != NULL)
902 903
        *typeVer = LIBVIR_VERSION_NUMBER;

904
    return 0;
905

906
 error:
907 908
    virDispatchError(NULL);
    return -1;
909 910
}

911

912
static char *
913
virConnectGetConfigFilePath(void)
914 915 916 917 918
{
    char *path;
    if (geteuid() == 0) {
        if (virAsprintf(&path, "%s/libvirt/libvirt.conf",
                        SYSCONFDIR) < 0)
919
            return NULL;
920
    } else {
921
        char *userdir = virGetUserConfigDirectory();
922
        if (!userdir)
923
            return NULL;
924

925
        if (virAsprintf(&path, "%s/libvirt.conf",
926 927
                        userdir) < 0) {
            VIR_FREE(userdir);
928
            return NULL;
929 930
        }
        VIR_FREE(userdir);
931 932 933 934 935
    }

    return path;
}

936

937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958
static int
virConnectGetConfigFile(virConfPtr *conf)
{
    char *filename = NULL;
    int ret = -1;

    *conf = NULL;

    if (!(filename = virConnectGetConfigFilePath()))
        goto cleanup;

    if (!virFileExists(filename)) {
        ret = 0;
        goto cleanup;
    }

    VIR_DEBUG("Loading config file '%s'", filename);
    if (!(*conf = virConfReadFile(filename, 0)))
        goto cleanup;

    ret = 0;

959
 cleanup:
960 961 962 963
    VIR_FREE(filename);
    return ret;
}

964 965
#define URI_ALIAS_CHARS "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-"

966

967
static int
968 969
virConnectOpenFindURIAliasMatch(virConfValuePtr value, const char *alias,
                                char **uri)
970 971
{
    virConfValuePtr entry;
W
Wen Ruo Lv 已提交
972 973
    size_t alias_len;

974
    if (value->type != VIR_CONF_LIST) {
975 976
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Expected a list for 'uri_aliases' config parameter"));
977 978 979 980
        return -1;
    }

    entry = value->list;
W
Wen Ruo Lv 已提交
981
    alias_len = strlen(alias);
982 983 984 985 986
    while (entry) {
        char *offset;
        size_t safe;

        if (entry->type != VIR_CONF_STRING) {
987 988
            virReportError(VIR_ERR_CONF_SYNTAX, "%s",
                           _("Expected a string for 'uri_aliases' config parameter list entry"));
989 990 991 992
            return -1;
        }

        if (!(offset = strchr(entry->str, '='))) {
993 994
            virReportError(VIR_ERR_CONF_SYNTAX,
                           _("Malformed 'uri_aliases' config entry '%s', expected 'alias=uri://host/path'"),
995 996 997 998 999 1000
                            entry->str);
            return -1;
        }

        safe  = strspn(entry->str, URI_ALIAS_CHARS);
        if (safe < (offset - entry->str)) {
1001 1002
            virReportError(VIR_ERR_CONF_SYNTAX,
                           _("Malformed 'uri_aliases' config entry '%s', aliases may only contain 'a-Z, 0-9, _, -'"),
1003 1004 1005 1006
                            entry->str);
            return -1;
        }

W
Wen Ruo Lv 已提交
1007 1008
        if (alias_len == (offset - entry->str) &&
            STREQLEN(entry->str, alias, alias_len)) {
1009 1010
            VIR_DEBUG("Resolved alias '%s' to '%s'",
                      alias, offset+1);
1011
            return VIR_STRDUP(*uri, offset+1);
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
        }

        entry = entry->next;
    }

    VIR_DEBUG("No alias found for '%s', passing through to drivers",
              alias);
    return 0;
}

1022

1023
static int
1024 1025
virConnectOpenResolveURIAlias(virConfPtr conf,
                              const char *alias, char **uri)
1026 1027 1028 1029 1030 1031
{
    int ret = -1;
    virConfValuePtr value = NULL;

    *uri = NULL;

1032
    if ((value = virConfGetValue(conf, "uri_aliases")))
1033 1034 1035 1036
        ret = virConnectOpenFindURIAliasMatch(value, alias, uri);
    else
        ret = 0;

1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
    return ret;
}


static int
virConnectGetDefaultURI(virConfPtr conf,
                        const char **name)
{
    int ret = -1;
    virConfValuePtr value = NULL;
1047
    const char *defname = virGetEnvBlockSUID("LIBVIRT_DEFAULT_URI");
1048 1049 1050 1051 1052
    if (defname && *defname) {
        VIR_DEBUG("Using LIBVIRT_DEFAULT_URI '%s'", defname);
        *name = defname;
    } else if ((value = virConfGetValue(conf, "uri_default"))) {
        if (value->type != VIR_CONF_STRING) {
1053 1054
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Expected a string for 'uri_default' config parameter"));
1055 1056 1057 1058 1059 1060 1061
            goto cleanup;
        }
        VIR_DEBUG("Using config file uri '%s'", value->str);
        *name = value->str;
    }

    ret = 0;
1062
 cleanup:
1063 1064 1065
    return ret;
}

1066

1067
static virConnectPtr
1068 1069 1070
do_open(const char *name,
        virConnectAuthPtr auth,
        unsigned int flags)
1071
{
1072 1073
    size_t i;
    int res;
1074
    virConnectPtr ret;
1075
    virConfPtr conf = NULL;
1076 1077 1078 1079

    ret = virGetConnect();
    if (ret == NULL)
        return NULL;
1080

1081 1082 1083 1084 1085 1086
    if (virConnectGetConfigFile(&conf) < 0)
        goto failed;

    if (name && name[0] == '\0')
        name = NULL;

1087 1088 1089 1090 1091 1092
    if (!name && virIsSUID()) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("An explicit URI must be provided when setuid"));
        goto failed;
    }

1093
    /*
E
Eric Blake 已提交
1094 1095 1096
     * If no URI is passed, then check for an environment string if not
     * available probe the compiled in drivers to find a default hypervisor
     * if detectable.
1097
     */
1098 1099 1100
    if (!name &&
        virConnectGetDefaultURI(conf, &name) < 0)
        goto failed;
1101

1102
    if (name) {
1103
        char *alias = NULL;
1104 1105 1106 1107 1108 1109 1110
        /* Convert xen -> xen:/// for back compat */
        if (STRCASEEQ(name, "xen"))
            name = "xen:///";

        /* Convert xen:// -> xen:/// because xmlParseURI cannot parse the
         * former.  This allows URIs such as xen://localhost to work.
         */
1111
        if (STREQ(name, "xen://"))
1112 1113
            name = "xen:///";

1114
        if (!(flags & VIR_CONNECT_NO_ALIASES) &&
1115
            virConnectOpenResolveURIAlias(conf, name, &alias) < 0)
1116 1117
            goto failed;

1118
        if (!(ret->uri = virURIParse(alias ? alias : name))) {
1119
            VIR_FREE(alias);
1120 1121
            goto failed;
        }
1122

1123
        VIR_DEBUG("name \"%s\" to URI components:\n"
1124 1125 1126 1127
                  "  scheme %s\n"
                  "  server %s\n"
                  "  user %s\n"
                  "  port %d\n"
J
Jiri Denemark 已提交
1128
                  "  path %s",
1129
                  alias ? alias : name,
1130
                  NULLSTR(ret->uri->scheme), NULLSTR(ret->uri->server),
1131 1132 1133 1134
                  NULLSTR(ret->uri->user), ret->uri->port,
                  NULLSTR(ret->uri->path));

        VIR_FREE(alias);
1135
    } else {
1136
        VIR_DEBUG("no name, allowing driver auto-select");
1137 1138
    }

1139 1140 1141
    /* Cleansing flags */
    ret->flags = flags & VIR_CONNECT_RO;

1142
    for (i = 0; i < virConnectDriverTabCount; i++) {
1143 1144 1145 1146 1147 1148 1149
        /* We're going to probe the remote driver next. So we have already
         * probed all other client-side-only driver before, but none of them
         * accepted the URI.
         * If the scheme corresponds to a known but disabled client-side-only
         * driver then report a useful error, instead of a cryptic one about
         * not being able to connect to libvirtd or not being able to find
         * certificates. */
1150
        if (STREQ(virConnectDriverTab[i]->hypervisorDriver->name, "remote") &&
1151 1152 1153 1154 1155 1156
            ret->uri != NULL && ret->uri->scheme != NULL &&
            (
#ifndef WITH_PHYP
             STRCASEEQ(ret->uri->scheme, "phyp") ||
#endif
#ifndef WITH_ESX
1157
             STRCASEEQ(ret->uri->scheme, "vpx") ||
1158 1159
             STRCASEEQ(ret->uri->scheme, "esx") ||
             STRCASEEQ(ret->uri->scheme, "gsx") ||
M
Matthias Bolte 已提交
1160 1161 1162
#endif
#ifndef WITH_HYPERV
             STRCASEEQ(ret->uri->scheme, "hyperv") ||
1163 1164 1165
#endif
#ifndef WITH_XENAPI
             STRCASEEQ(ret->uri->scheme, "xenapi") ||
D
Dmitry Guryanov 已提交
1166
#endif
1167
#ifndef WITH_VZ
D
Dmitry Guryanov 已提交
1168
             STRCASEEQ(ret->uri->scheme, "parallels") ||
1169 1170
#endif
             false)) {
1171
            virReportErrorHelper(VIR_FROM_NONE, VIR_ERR_CONFIG_UNSUPPORTED,
1172 1173 1174 1175 1176 1177
                                 __FILE__, __FUNCTION__, __LINE__,
                                 _("libvirt was built without the '%s' driver"),
                                 ret->uri->scheme);
            goto failed;
        }

1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
        VIR_DEBUG("trying driver %zu (%s) ...",
                  i, virConnectDriverTab[i]->hypervisorDriver->name);

        ret->driver = virConnectDriverTab[i]->hypervisorDriver;
        ret->interfaceDriver = virConnectDriverTab[i]->interfaceDriver;
        ret->networkDriver = virConnectDriverTab[i]->networkDriver;
        ret->nodeDeviceDriver = virConnectDriverTab[i]->nodeDeviceDriver;
        ret->nwfilterDriver = virConnectDriverTab[i]->nwfilterDriver;
        ret->secretDriver = virConnectDriverTab[i]->secretDriver;
        ret->storageDriver = virConnectDriverTab[i]->storageDriver;

        res = virConnectDriverTab[i]->hypervisorDriver->connectOpen(ret, auth, flags);
1190
        VIR_DEBUG("driver %zu %s returned %s",
1191
                  i, virConnectDriverTab[i]->hypervisorDriver->name,
O
Osier Yang 已提交
1192 1193 1194 1195 1196
                  res == VIR_DRV_OPEN_SUCCESS ? "SUCCESS" :
                  (res == VIR_DRV_OPEN_DECLINED ? "DECLINED" :
                  (res == VIR_DRV_OPEN_ERROR ? "ERROR" : "unknown status")));

        if (res == VIR_DRV_OPEN_SUCCESS) {
1197
            break;
1198 1199
        } else {
            ret->driver = NULL;
1200 1201 1202 1203 1204 1205 1206 1207 1208
            ret->interfaceDriver = NULL;
            ret->networkDriver = NULL;
            ret->nodeDeviceDriver = NULL;
            ret->nwfilterDriver = NULL;
            ret->secretDriver = NULL;
            ret->storageDriver = NULL;

            if (res == VIR_DRV_OPEN_ERROR)
                goto failed;
1209
        }
1210 1211
    }

1212
    if (!ret->driver) {
1213
        /* If we reach here, then all drivers declined the connection. */
1214
        virReportError(VIR_ERR_NO_CONNECT, "%s", NULLSTR(name));
1215
        goto failed;
1216 1217
    }

1218 1219
    virConfFree(conf);

1220
    return ret;
1221

1222
 failed:
1223
    virConfFree(conf);
1224
    virObjectUnref(ret);
1225

1226
    return NULL;
1227 1228
}

1229

1230 1231
/**
 * virConnectOpen:
1232
 * @name: (optional) URI of the hypervisor
1233
 *
1234
 * This function should be called first to get a connection to the
1235 1236
 * Hypervisor and xen store
 *
1237 1238 1239 1240 1241
 * If @name is NULL, if the LIBVIRT_DEFAULT_URI environment variable is set,
 * then it will be used. Otherwise if the client configuration file
 * has the "uri_default" parameter set, then it will be used. Finally
 * probing will be done to determine a suitable default driver to activate.
 * This involves trying each hypervisor in turn until one successfully opens.
1242 1243 1244 1245 1246 1247
 *
 * If connecting to an unprivileged hypervisor driver which requires
 * the libvirtd daemon to be active, it will automatically be launched
 * if not already running. This can be prevented by setting the
 * environment variable LIBVIRT_AUTOSTART=0
 *
1248
 * URIs are documented at http://libvirt.org/uri.html
E
Eric Blake 已提交
1249
 *
1250 1251 1252
 * virConnectClose should be used to release the resources after the connection
 * is no longer needed.
 *
E
Eric Blake 已提交
1253
 * Returns a pointer to the hypervisor connection or NULL in case of error
1254 1255
 */
virConnectPtr
1256
virConnectOpen(const char *name)
1257
{
1258
    virConnectPtr ret = NULL;
1259 1260 1261

    if (virInitialize() < 0)
        goto error;
1262

1263
    VIR_DEBUG("name=%s", NULLSTR(name));
1264
    virResetLastError();
1265
    ret = do_open(name, NULL, 0);
1266 1267 1268 1269
    if (!ret)
        goto error;
    return ret;

1270
 error:
1271 1272
    virDispatchError(NULL);
    return NULL;
1273 1274
}

1275

1276
/**
1277
 * virConnectOpenReadOnly:
1278
 * @name: (optional) URI of the hypervisor
1279
 *
1280
 * This function should be called first to get a restricted connection to the
D
Daniel Veillard 已提交
1281
 * library functionalities. The set of APIs usable are then restricted
1282
 * on the available methods to control the domains.
1283
 *
1284
 * See virConnectOpen for notes about environment variables which can
1285
 * have an effect on opening drivers and freeing the connection resources
1286
 *
1287
 * URIs are documented at http://libvirt.org/uri.html
E
Eric Blake 已提交
1288 1289
 *
 * Returns a pointer to the hypervisor connection or NULL in case of error
1290
 */
1291
virConnectPtr
1292 1293
virConnectOpenReadOnly(const char *name)
{
1294
    virConnectPtr ret = NULL;
1295 1296 1297

    if (virInitialize() < 0)
        goto error;
1298

1299
    VIR_DEBUG("name=%s", NULLSTR(name));
1300
    virResetLastError();
1301
    ret = do_open(name, NULL, VIR_CONNECT_RO);
1302 1303 1304 1305
    if (!ret)
        goto error;
    return ret;

1306
 error:
1307 1308
    virDispatchError(NULL);
    return NULL;
1309 1310
}

1311

1312 1313
/**
 * virConnectOpenAuth:
1314
 * @name: (optional) URI of the hypervisor
1315
 * @auth: Authenticate callback parameters
1316
 * @flags: bitwise-OR of virConnectFlags
1317
 *
1318
 * This function should be called first to get a connection to the
1319
 * Hypervisor. If necessary, authentication will be performed fetching
1320 1321
 * credentials via the callback
 *
1322
 * See virConnectOpen for notes about environment variables which can
1323
 * have an effect on opening drivers and freeing the connection resources
1324
 *
1325
 * URIs are documented at http://libvirt.org/uri.html
E
Eric Blake 已提交
1326 1327
 *
 * Returns a pointer to the hypervisor connection or NULL in case of error
1328 1329 1330 1331
 */
virConnectPtr
virConnectOpenAuth(const char *name,
                   virConnectAuthPtr auth,
1332
                   unsigned int flags)
1333
{
1334
    virConnectPtr ret = NULL;
1335 1336 1337

    if (virInitialize() < 0)
        goto error;
1338

1339
    VIR_DEBUG("name=%s, auth=%p, flags=%x", NULLSTR(name), auth, flags);
1340
    virResetLastError();
1341
    ret = do_open(name, auth, flags);
1342 1343 1344 1345
    if (!ret)
        goto error;
    return ret;

1346
 error:
1347 1348
    virDispatchError(NULL);
    return NULL;
D
Daniel Veillard 已提交
1349 1350
}

1351

1352

D
Daniel Veillard 已提交
1353
/**
1354
 * virConnectClose:
D
Daniel Veillard 已提交
1355 1356 1357 1358 1359 1360 1361
 * @conn: pointer to the hypervisor connection
 *
 * This function closes the connection to the Hypervisor. This should
 * not be called if further interaction with the Hypervisor are needed
 * especially if there is running domain which need further monitoring by
 * the application.
 *
1362 1363 1364 1365 1366 1367 1368 1369
 * Connections are reference counted; the count is explicitly
 * increased by the initial open (virConnectOpen, virConnectOpenAuth,
 * and the like) as well as virConnectRef; it is also temporarily
 * increased by other API that depend on the connection remaining
 * alive.  The open and every virConnectRef call should have a
 * matching virConnectClose, and all other references will be released
 * after the corresponding operation completes.
 *
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379
 * Returns a positive number if at least 1 reference remains on
 * success. The returned value should not be assumed to be the total
 * reference count. A return of 0 implies no references remain and
 * the connection is closed and memory has been freed. A return of -1
 * implies a failure.
 *
 * It is possible for the last virConnectClose to return a positive
 * value if some other object still has a temporary reference to the
 * connection, but the application should not try to further use a
 * connection after the virConnectClose that matches the initial open.
D
Daniel Veillard 已提交
1380 1381
 */
int
1382 1383
virConnectClose(virConnectPtr conn)
{
1384
    VIR_DEBUG("conn=%p", conn);
1385

1386 1387
    virResetLastError();

1388
    virCheckConnectReturn(conn, -1);
1389

1390 1391 1392
    if (!virObjectUnref(conn))
        return 0;
    return 1;
D
Daniel Veillard 已提交
1393 1394
}

1395

1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435
/* Helper function called to validate incoming client array on any
 * interface that sets typed parameters in the hypervisor.  */
int
virTypedParameterValidateSet(virConnectPtr conn,
                             virTypedParameterPtr params,
                             int nparams)
{
    bool string_okay;
    size_t i;

    string_okay = VIR_DRV_SUPPORTS_FEATURE(conn->driver,
                                           conn,
                                           VIR_DRV_FEATURE_TYPED_PARAM_STRING);
    for (i = 0; i < nparams; i++) {
        if (strnlen(params[i].field, VIR_TYPED_PARAM_FIELD_LENGTH) ==
            VIR_TYPED_PARAM_FIELD_LENGTH) {
            virReportInvalidArg(params,
                                _("string parameter name '%.*s' too long"),
                                VIR_TYPED_PARAM_FIELD_LENGTH,
                                params[i].field);
            return -1;
        }
        if (params[i].type == VIR_TYPED_PARAM_STRING) {
            if (string_okay) {
                if (!params[i].value.s) {
                    virReportInvalidArg(params,
                                        _("NULL string parameter '%s'"),
                                        params[i].field);
                    return -1;
                }
            } else {
                virReportInvalidArg(params,
                                    _("string parameter '%s' unsupported"),
                                    params[i].field);
                return -1;
            }
        }
    }
    return 0;
}