libvirt.c 40.5 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
D
Dmitry Guryanov 已提交
95 96 97
#ifdef WITH_PARALLELS
# include "parallels/parallels_driver.h"
#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 20
113

114 115 116 117 118 119 120 121 122 123
#define virDriverCheckTabMaxReturn(count, ret)                          \
    do {                                                                \
        if ((count) >= MAX_DRIVERS) {                                   \
            virReportError(VIR_ERR_INTERNAL_ERROR,                      \
                           _("Too many drivers, cannot register %s"),   \
                           driver->name);                               \
            return ret;                                                 \
        }                                                               \
    } while (0)

124
static virHypervisorDriverPtr virHypervisorDriverTab[MAX_DRIVERS];
125
static int virHypervisorDriverTabCount;
126
static virNetworkDriverPtr virNetworkDriverTab[MAX_DRIVERS];
127
static int virNetworkDriverTabCount;
D
Daniel Veillard 已提交
128
static virInterfaceDriverPtr virInterfaceDriverTab[MAX_DRIVERS];
129
static int virInterfaceDriverTabCount;
130
static virStorageDriverPtr virStorageDriverTab[MAX_DRIVERS];
131
static int virStorageDriverTabCount;
132
static virNodeDeviceDriverPtr virNodeDeviceDriverTab[MAX_DRIVERS];
133
static int virNodeDeviceDriverTabCount;
134
static virSecretDriverPtr virSecretDriverTab[MAX_DRIVERS];
135
static int virSecretDriverTabCount;
S
Stefan Berger 已提交
136
static virNWFilterDriverPtr virNWFilterDriverTab[MAX_DRIVERS];
137
static int virNWFilterDriverTabCount;
138
static virStateDriverPtr virStateDriverTab[MAX_DRIVERS];
139
static int virStateDriverTabCount;
140

141

142
#if defined(POLKIT_AUTH)
143 144 145
static int
virConnectAuthGainPolkit(const char *privilege)
{
E
Eric Blake 已提交
146 147
    virCommandPtr cmd;
    int ret = -1;
148

149
    if (geteuid() == 0)
150 151
        return 0;

E
Eric Blake 已提交
152
    cmd = virCommandNewArgList(POLKIT_AUTH, "--obtain", privilege, NULL);
153
    if (virCommandRun(cmd, NULL) < 0)
E
Eric Blake 已提交
154
        goto cleanup;
155

E
Eric Blake 已提交
156
    ret = 0;
157
 cleanup:
E
Eric Blake 已提交
158 159
    virCommandFree(cmd);
    return ret;
160 161 162
}
#endif

163 164 165 166 167 168

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

171
    for (i = 0; i < ncred; i++) {
172 173
        char buf[1024];
        char *bufptr = buf;
174
        size_t len;
175 176

        switch (cred[i].type) {
177 178 179 180
        case VIR_CRED_EXTERNAL: {
            if (STRNEQ(cred[i].challenge, "PolicyKit"))
                return -1;

181
#if defined(POLKIT_AUTH)
182
            if (virConnectAuthGainPolkit(cred[i].prompt) < 0)
183
                return -1;
184 185 186 187 188 189 190
#else
            /*
             * Ignore & carry on. Although we can't auth
             * directly, the user may have authenticated
             * themselves already outside context of libvirt
             */
#endif
191 192
            break;
        }
193

194 195 196 197
        case VIR_CRED_USERNAME:
        case VIR_CRED_AUTHNAME:
        case VIR_CRED_ECHOPROMPT:
        case VIR_CRED_REALM:
198
            if (printf("%s: ", cred[i].prompt) < 0)
199 200 201 202
                return -1;
            if (fflush(stdout) != 0)
                return -1;

203 204 205 206 207 208 209
            if (!fgets(buf, sizeof(buf), stdin)) {
                if (feof(stdin)) { /* Treat EOF as "" */
                    buf[0] = '\0';
                    break;
                }
                return -1;
            }
210 211 212
            len = strlen(buf);
            if (len != 0 && buf[len-1] == '\n')
                buf[len-1] = '\0';
213 214 215 216
            break;

        case VIR_CRED_PASSPHRASE:
        case VIR_CRED_NOECHOPROMPT:
217
            if (printf("%s: ", cred[i].prompt) < 0)
218 219 220 221
                return -1;
            if (fflush(stdout) != 0)
                return -1;

222 223 224 225
            bufptr = getpass("");
            if (!bufptr)
                return -1;
            break;
226 227 228

        default:
            return -1;
229 230
        }

D
Daniel P. Berrange 已提交
231
        if (cred[i].type != VIR_CRED_EXTERNAL) {
232 233 234
            if (VIR_STRDUP(cred[i].result,
                           STREQ(bufptr, "") && cred[i].defresult ?
                           cred[i].defresult : bufptr) < 0)
D
Daniel P. Berrange 已提交
235 236 237
                return -1;
            cred[i].resultlen = strlen(cred[i].result);
        }
238 239 240 241 242
    }

    return 0;
}

243

244 245 246 247 248 249 250 251 252 253
/* 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,
254
    VIR_CRED_EXTERNAL,
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
};

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;

276 277
#if HAVE_WINSOCK2_H
static int
278
winsock_init(void)
279 280 281 282 283 284 285
{
    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 已提交
286
    return err == 0 ? 0 : -1;
287 288 289
}
#endif

290

291
#ifdef WITH_GNUTLS_GCRYPT
292 293
static int
virTLSMutexInit(void **priv)
294
{
D
Daniel P. Berrange 已提交
295 296
    virMutexPtr lock = NULL;

297
    if (VIR_ALLOC_QUIET(lock) < 0)
D
Daniel P. Berrange 已提交
298 299 300 301 302 303 304 305 306 307 308
        return ENOMEM;

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

    *priv = lock;
    return 0;
}

309 310 311

static int
virTLSMutexDestroy(void **priv)
D
Daniel P. Berrange 已提交
312 313 314 315 316 317 318
{
    virMutexPtr lock = *priv;
    virMutexDestroy(lock);
    VIR_FREE(lock);
    return 0;
}

319 320 321

static int
virTLSMutexLock(void **priv)
D
Daniel P. Berrange 已提交
322 323 324 325 326 327
{
    virMutexPtr lock = *priv;
    virMutexLock(lock);
    return 0;
}

328 329 330

static int
virTLSMutexUnlock(void **priv)
D
Daniel P. Berrange 已提交
331 332 333 334 335 336
{
    virMutexPtr lock = *priv;
    virMutexUnlock(lock);
    return 0;
}

337

D
Daniel P. Berrange 已提交
338
static struct gcry_thread_cbs virTLSThreadImpl = {
339
    /* GCRY_THREAD_OPTION_VERSION was added in gcrypt 1.4.2 */
340
# ifdef GCRY_THREAD_OPTION_VERSION
D
Daniel P. Berrange 已提交
341
    (GCRY_THREAD_OPTION_PTHREAD | (GCRY_THREAD_OPTION_VERSION << 8)),
342
# else
343
    GCRY_THREAD_OPTION_PTHREAD,
344
# endif
D
Daniel P. Berrange 已提交
345 346 347 348 349 350 351
    NULL,
    virTLSMutexInit,
    virTLSMutexDestroy,
    virTLSMutexLock,
    virTLSMutexUnlock,
    NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
};
352
#endif /* WITH_GNUTLS_GCRYPT */
D
Daniel P. Berrange 已提交
353

354

355
static bool virGlobalError;
356
static virOnceControl virGlobalOnce = VIR_ONCE_CONTROL_INITIALIZER;
357

358 359 360
static void
virGlobalInit(void)
{
361 362 363 364 365
    /* 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.  */
366
    if (virThreadInitialize() < 0 ||
367
        virErrorInitialize() < 0)
368
        goto error;
369

370
#ifndef LIBVIRT_SETUID_RPC_CLIENT
371 372 373 374 375 376 377
    if (virIsSUID()) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libvirt.so is not safe to use from setuid programs"));
        goto error;
    }
#endif

378
#ifdef WITH_GNUTLS_GCRYPT
379 380 381 382 383 384 385 386 387 388 389 390 391
    /*
     * 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);
    }
392
#endif
D
Daniel P. Berrange 已提交
393

394
    virLogSetFromEnv();
395

396
#ifdef WITH_GNUTLS
397
    virNetTLSInit();
398
#endif
399

400
#if WITH_CURL
401 402 403
    curl_global_init(CURL_GLOBAL_DEFAULT);
#endif

404
    VIR_DEBUG("register drivers");
405

406
#if HAVE_WINSOCK2_H
407
    if (winsock_init() == -1)
408
        goto error;
409 410
#endif

411
    if (!bindtextdomain(PACKAGE, LOCALEDIR))
412
        goto error;
413

414 415 416 417 418
    /*
     * Note we must avoid everything except 'remote' driver
     * for virt-login-shell usage
     */
#ifndef LIBVIRT_SETUID_RPC_CLIENT
419
    /*
420 421
     * Note that the order is important: the first ones have a higher
     * priority when calling virConnectOpen.
422
     */
423
# ifdef WITH_TEST
424 425
    if (testRegister() == -1)
        goto error;
426 427
# endif
# ifdef WITH_OPENVZ
428 429
    if (openvzRegister() == -1)
        goto error;
430 431
# endif
# ifdef WITH_VMWARE
432 433
    if (vmwareRegister() == -1)
        goto error;
434 435
# endif
# ifdef WITH_PHYP
436 437
    if (phypRegister() == -1)
        goto error;
438 439
# endif
# ifdef WITH_ESX
440 441
    if (esxRegister() == -1)
        goto error;
442 443
# endif
# ifdef WITH_HYPERV
444 445
    if (hypervRegister() == -1)
        goto error;
446 447
# endif
# ifdef WITH_XENAPI
448 449
    if (xenapiRegister() == -1)
        goto error;
450 451
# endif
# ifdef WITH_PARALLELS
452 453
    if (parallelsRegister() == -1)
        goto error;
454
# endif
D
Dmitry Guryanov 已提交
455
#endif
456
#ifdef WITH_REMOTE
457
    if (remoteRegister() == -1)
458
        goto error;
459
#endif
D
Daniel P. Berrange 已提交
460

461 462
    return;

463
 error:
464 465 466
    virGlobalError = true;
}

467

468 469 470 471 472
/**
 * virInitialize:
 *
 * Initialize the library.
 *
473 474 475 476 477 478
 * 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.
479
 *
480 481 482 483 484
 * 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.
485 486 487 488 489 490 491 492 493 494 495
 *
 * 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;
496
    return 0;
497 498
}

499

500 501
#ifdef WIN32
BOOL WINAPI
502
DllMain(HINSTANCE instance, DWORD reason, LPVOID ignore);
503 504

BOOL WINAPI
505 506 507
DllMain(HINSTANCE instance ATTRIBUTE_UNUSED,
        DWORD reason,
        LPVOID ignore ATTRIBUTE_UNUSED)
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
{
    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
533

534

535 536 537 538 539 540 541 542 543 544 545
/**
 * virRegisterNetworkDriver:
 * @driver: pointer to a network driver block
 *
 * Register a network virtualization driver
 *
 * Returns the driver priority or -1 in case of error.
 */
int
virRegisterNetworkDriver(virNetworkDriverPtr driver)
{
546
    virCheckNonNullArgReturn(driver, -1);
547
    virDriverCheckTabMaxReturn(virNetworkDriverTabCount, -1);
548

549
    VIR_DEBUG("registering %s as network driver %d",
550 551
           driver->name, virNetworkDriverTabCount);

552 553
    virNetworkDriverTab[virNetworkDriverTabCount] = driver;
    return virNetworkDriverTabCount++;
554 555
}

556

D
Daniel Veillard 已提交
557 558
/**
 * virRegisterInterfaceDriver:
L
Laine Stump 已提交
559
 * @driver: pointer to an interface driver block
D
Daniel Veillard 已提交
560
 *
L
Laine Stump 已提交
561
 * Register an interface virtualization driver
D
Daniel Veillard 已提交
562 563 564 565 566 567
 *
 * Returns the driver priority or -1 in case of error.
 */
int
virRegisterInterfaceDriver(virInterfaceDriverPtr driver)
{
568
    virCheckNonNullArgReturn(driver, -1);
569
    virDriverCheckTabMaxReturn(virInterfaceDriverTabCount, -1);
D
Daniel Veillard 已提交
570

571
    VIR_DEBUG("registering %s as interface driver %d",
D
Daniel Veillard 已提交
572 573 574 575 576 577
           driver->name, virInterfaceDriverTabCount);

    virInterfaceDriverTab[virInterfaceDriverTabCount] = driver;
    return virInterfaceDriverTabCount++;
}

578

579 580 581 582 583 584 585 586 587 588 589
/**
 * virRegisterStorageDriver:
 * @driver: pointer to a storage driver block
 *
 * Register a storage virtualization driver
 *
 * Returns the driver priority or -1 in case of error.
 */
int
virRegisterStorageDriver(virStorageDriverPtr driver)
{
590
    virCheckNonNullArgReturn(driver, -1);
591
    virDriverCheckTabMaxReturn(virStorageDriverTabCount, -1);
592

593
    VIR_DEBUG("registering %s as storage driver %d",
594 595
           driver->name, virStorageDriverTabCount);

596 597 598 599
    virStorageDriverTab[virStorageDriverTabCount] = driver;
    return virStorageDriverTabCount++;
}

600

601
/**
602
 * virRegisterNodeDeviceDriver:
603 604 605 606 607 608 609
 * @driver: pointer to a device monitor block
 *
 * Register a device monitor
 *
 * Returns the driver priority or -1 in case of error.
 */
int
610
virRegisterNodeDeviceDriver(virNodeDeviceDriverPtr driver)
611
{
612
    virCheckNonNullArgReturn(driver, -1);
613
    virDriverCheckTabMaxReturn(virNodeDeviceDriverTabCount, -1);
614

615
    VIR_DEBUG("registering %s as device driver %d",
616
           driver->name, virNodeDeviceDriverTabCount);
617

618 619
    virNodeDeviceDriverTab[virNodeDeviceDriverTabCount] = driver;
    return virNodeDeviceDriverTabCount++;
620 621
}

622

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

637
    VIR_DEBUG("registering %s as secret driver %d",
638 639 640 641 642 643
           driver->name, virSecretDriverTabCount);

    virSecretDriverTab[virSecretDriverTabCount] = driver;
    return virSecretDriverTabCount++;
}

644

S
Stefan Berger 已提交
645 646 647 648 649 650 651 652 653 654 655
/**
 * virRegisterNWFilterDriver:
 * @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
virRegisterNWFilterDriver(virNWFilterDriverPtr driver)
{
656
    virCheckNonNullArgReturn(driver, -1);
657
    virDriverCheckTabMaxReturn(virNWFilterDriverTabCount, -1);
S
Stefan Berger 已提交
658

659
    VIR_DEBUG("registering %s as network filter driver %d",
S
Stefan Berger 已提交
660 661 662 663 664 665 666
           driver->name, virNWFilterDriverTabCount);

    virNWFilterDriverTab[virNWFilterDriverTabCount] = driver;
    return virNWFilterDriverTabCount++;
}


667
/**
668
 * virRegisterHypervisorDriver:
669 670 671 672 673 674 675
 * @driver: pointer to a driver block
 *
 * Register a virtualization driver
 *
 * Returns the driver priority or -1 in case of error.
 */
int
676
virRegisterHypervisorDriver(virHypervisorDriverPtr driver)
677
{
678 679
    VIR_DEBUG("driver=%p name=%s", driver,
              driver ? NULLSTR(driver->name) : "(null)");
680

681
    virCheckNonNullArgReturn(driver, -1);
682
    virDriverCheckTabMaxReturn(virHypervisorDriverTabCount, -1);
683

684
    VIR_DEBUG("registering %s as driver %d",
685
           driver->name, virHypervisorDriverTabCount);
686

687 688
    virHypervisorDriverTab[virHypervisorDriverTabCount] = driver;
    return virHypervisorDriverTabCount++;
689 690
}

691

692 693 694 695 696 697 698 699 700 701 702
/**
 * 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)
{
703
    virCheckNonNullArgReturn(driver, -1);
704
    virDriverCheckTabMaxReturn(virStateDriverTabCount, -1);
705 706 707 708 709

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

710

711 712
/**
 * virStateInitialize:
713
 * @privileged: set to true if running with root privilege, false otherwise
714 715
 * @callback: callback to invoke to inhibit shutdown of the daemon
 * @opaque: data to pass to @callback
716
 *
717 718 719 720 721
 * 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.
722
 *
723
 * Returns 0 if all succeed, -1 upon any failure.
724
 */
725 726 727 728
int
virStateInitialize(bool privileged,
                   virStateInhibitCallback callback,
                   void *opaque)
729
{
730
    size_t i;
731 732 733 734

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

735
    for (i = 0; i < virStateDriverTabCount; i++) {
736
        if (virStateDriverTab[i]->stateInitialize) {
737
            VIR_DEBUG("Running global init for %s state driver",
738
                      virStateDriverTab[i]->name);
739 740 741
            if (virStateDriverTab[i]->stateInitialize(privileged,
                                                      callback,
                                                      opaque) < 0) {
742 743 744 745
                virErrorPtr err = virGetLastError();
                VIR_ERROR(_("Initialization of %s state driver failed: %s"),
                          virStateDriverTab[i]->name,
                          err && err->message ? err->message : _("Unknown problem"));
746 747
                return -1;
            }
748
        }
749
    }
750 751 752 753 754 755 756 757

    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();
        }
    }
758
    return 0;
759 760
}

761

762 763 764 765 766
/**
 * virStateCleanup:
 *
 * Run each virtualization driver's cleanup method.
 *
767
 * Returns 0 if all succeed, -1 upon any failure.
768
 */
769 770 771
int
virStateCleanup(void)
{
772 773
    size_t i;
    int ret = 0;
774

775
    for (i = 0; i < virStateDriverTabCount; i++) {
776 777
        if (virStateDriverTab[i]->stateCleanup &&
            virStateDriverTab[i]->stateCleanup() < 0)
778 779 780 781 782
            ret = -1;
    }
    return ret;
}

783

784 785 786 787 788
/**
 * virStateReload:
 *
 * Run each virtualization driver's reload method.
 *
789
 * Returns 0 if all succeed, -1 upon any failure.
790
 */
791 792 793
int
virStateReload(void)
{
794 795
    size_t i;
    int ret = 0;
796

797
    for (i = 0; i < virStateDriverTabCount; i++) {
798 799
        if (virStateDriverTab[i]->stateReload &&
            virStateDriverTab[i]->stateReload() < 0)
800 801 802 803 804
            ret = -1;
    }
    return ret;
}

805

806 807 808 809 810 811 812
/**
 * virStateStop:
 *
 * Run each virtualization driver's "stop" method.
 *
 * Returns 0 if successful, -1 on failure
 */
813 814 815
int
virStateStop(void)
{
816 817
    size_t i;
    int ret = 0;
818

819
    for (i = 0; i < virStateDriverTabCount; i++) {
820 821
        if (virStateDriverTab[i]->stateStop &&
            virStateDriverTab[i]->stateStop())
822 823 824 825
            ret = 1;
    }
    return ret;
}
826 827


828 829 830
/**
 * virGetVersion:
 * @libVer: return value for the library version (OUT)
831 832 833 834 835 836 837 838 839 840
 * @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
841
 * get the version of the running hypervisor use the virConnectGetVersion()
842
 * function instead. To get the libvirt library version used by a
843 844 845
 * connection use the virConnectGetLibVersion() instead.
 *
 * This function includes a call to virInitialize() when necessary.
846 847 848 849 850
 *
 * 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
851
virGetVersion(unsigned long *libVer, const char *type ATTRIBUTE_UNUSED,
852 853
              unsigned long *typeVer)
{
854 855
    if (virInitialize() < 0)
        goto error;
856
    VIR_DEBUG("libVir=%p, type=%s, typeVer=%p", libVer, type, typeVer);
857

858
    virResetLastError();
859
    if (libVer == NULL)
860
        goto error;
861 862
    *libVer = LIBVIR_VERSION_NUMBER;

863
    if (typeVer != NULL)
864 865
        *typeVer = LIBVIR_VERSION_NUMBER;

866
    return 0;
867

868
 error:
869 870
    virDispatchError(NULL);
    return -1;
871 872
}

873

874
static char *
875
virConnectGetConfigFilePath(void)
876 877 878 879 880
{
    char *path;
    if (geteuid() == 0) {
        if (virAsprintf(&path, "%s/libvirt/libvirt.conf",
                        SYSCONFDIR) < 0)
881
            return NULL;
882
    } else {
883
        char *userdir = virGetUserConfigDirectory();
884
        if (!userdir)
885
            return NULL;
886

887
        if (virAsprintf(&path, "%s/libvirt.conf",
888 889
                        userdir) < 0) {
            VIR_FREE(userdir);
890
            return NULL;
891 892
        }
        VIR_FREE(userdir);
893 894 895 896 897
    }

    return path;
}

898

899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920
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;

921
 cleanup:
922 923 924 925
    VIR_FREE(filename);
    return ret;
}

926 927
#define URI_ALIAS_CHARS "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-"

928

929
static int
930 931
virConnectOpenFindURIAliasMatch(virConfValuePtr value, const char *alias,
                                char **uri)
932 933
{
    virConfValuePtr entry;
W
Wen Ruo Lv 已提交
934 935
    size_t alias_len;

936
    if (value->type != VIR_CONF_LIST) {
937 938
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Expected a list for 'uri_aliases' config parameter"));
939 940 941 942
        return -1;
    }

    entry = value->list;
W
Wen Ruo Lv 已提交
943
    alias_len = strlen(alias);
944 945 946 947 948
    while (entry) {
        char *offset;
        size_t safe;

        if (entry->type != VIR_CONF_STRING) {
949 950
            virReportError(VIR_ERR_CONF_SYNTAX, "%s",
                           _("Expected a string for 'uri_aliases' config parameter list entry"));
951 952 953 954
            return -1;
        }

        if (!(offset = strchr(entry->str, '='))) {
955 956
            virReportError(VIR_ERR_CONF_SYNTAX,
                           _("Malformed 'uri_aliases' config entry '%s', expected 'alias=uri://host/path'"),
957 958 959 960 961 962
                            entry->str);
            return -1;
        }

        safe  = strspn(entry->str, URI_ALIAS_CHARS);
        if (safe < (offset - entry->str)) {
963 964
            virReportError(VIR_ERR_CONF_SYNTAX,
                           _("Malformed 'uri_aliases' config entry '%s', aliases may only contain 'a-Z, 0-9, _, -'"),
965 966 967 968
                            entry->str);
            return -1;
        }

W
Wen Ruo Lv 已提交
969 970
        if (alias_len == (offset - entry->str) &&
            STREQLEN(entry->str, alias, alias_len)) {
971 972
            VIR_DEBUG("Resolved alias '%s' to '%s'",
                      alias, offset+1);
973
            return VIR_STRDUP(*uri, offset+1);
974 975 976 977 978 979 980 981 982 983
        }

        entry = entry->next;
    }

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

984

985
static int
986 987
virConnectOpenResolveURIAlias(virConfPtr conf,
                              const char *alias, char **uri)
988 989 990 991 992 993
{
    int ret = -1;
    virConfValuePtr value = NULL;

    *uri = NULL;

994
    if ((value = virConfGetValue(conf, "uri_aliases")))
995 996 997 998
        ret = virConnectOpenFindURIAliasMatch(value, alias, uri);
    else
        ret = 0;

999 1000 1001 1002 1003 1004 1005 1006 1007 1008
    return ret;
}


static int
virConnectGetDefaultURI(virConfPtr conf,
                        const char **name)
{
    int ret = -1;
    virConfValuePtr value = NULL;
1009
    const char *defname = virGetEnvBlockSUID("LIBVIRT_DEFAULT_URI");
1010 1011 1012 1013 1014
    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) {
1015 1016
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Expected a string for 'uri_default' config parameter"));
1017 1018 1019 1020 1021 1022 1023
            goto cleanup;
        }
        VIR_DEBUG("Using config file uri '%s'", value->str);
        *name = value->str;
    }

    ret = 0;
1024
 cleanup:
1025 1026 1027
    return ret;
}

1028

1029
static virConnectPtr
1030 1031 1032
do_open(const char *name,
        virConnectAuthPtr auth,
        unsigned int flags)
1033
{
1034 1035
    size_t i;
    int res;
1036
    virConnectPtr ret;
1037
    virConfPtr conf = NULL;
1038 1039 1040 1041

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

1043 1044 1045 1046 1047 1048
    if (virConnectGetConfigFile(&conf) < 0)
        goto failed;

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

1049 1050 1051 1052 1053 1054
    if (!name && virIsSUID()) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("An explicit URI must be provided when setuid"));
        goto failed;
    }

1055
    /*
E
Eric Blake 已提交
1056 1057 1058
     * 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.
1059
     */
1060 1061 1062
    if (!name &&
        virConnectGetDefaultURI(conf, &name) < 0)
        goto failed;
1063

1064
    if (name) {
1065
        char *alias = NULL;
1066 1067 1068 1069 1070 1071 1072
        /* 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.
         */
1073
        if (STREQ(name, "xen://"))
1074 1075
            name = "xen:///";

1076
        if (!(flags & VIR_CONNECT_NO_ALIASES) &&
1077
            virConnectOpenResolveURIAlias(conf, name, &alias) < 0)
1078 1079
            goto failed;

1080
        if (!(ret->uri = virURIParse(alias ? alias : name))) {
1081
            VIR_FREE(alias);
1082 1083
            goto failed;
        }
1084

1085
        VIR_DEBUG("name \"%s\" to URI components:\n"
1086 1087 1088 1089 1090 1091
                  "  scheme %s\n"
                  "  server %s\n"
                  "  user %s\n"
                  "  port %d\n"
                  "  path %s\n",
                  alias ? alias : name,
1092
                  NULLSTR(ret->uri->scheme), NULLSTR(ret->uri->server),
1093 1094 1095 1096
                  NULLSTR(ret->uri->user), ret->uri->port,
                  NULLSTR(ret->uri->path));

        VIR_FREE(alias);
1097
    } else {
1098
        VIR_DEBUG("no name, allowing driver auto-select");
1099 1100
    }

1101 1102 1103
    /* Cleansing flags */
    ret->flags = flags & VIR_CONNECT_RO;

1104
    for (i = 0; i < virHypervisorDriverTabCount; i++) {
1105 1106 1107 1108 1109 1110 1111
        /* 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. */
1112
        if (virHypervisorDriverTab[i]->no == VIR_DRV_REMOTE &&
1113 1114 1115 1116 1117 1118
            ret->uri != NULL && ret->uri->scheme != NULL &&
            (
#ifndef WITH_PHYP
             STRCASEEQ(ret->uri->scheme, "phyp") ||
#endif
#ifndef WITH_ESX
1119
             STRCASEEQ(ret->uri->scheme, "vpx") ||
1120 1121
             STRCASEEQ(ret->uri->scheme, "esx") ||
             STRCASEEQ(ret->uri->scheme, "gsx") ||
M
Matthias Bolte 已提交
1122 1123 1124
#endif
#ifndef WITH_HYPERV
             STRCASEEQ(ret->uri->scheme, "hyperv") ||
1125 1126 1127
#endif
#ifndef WITH_XENAPI
             STRCASEEQ(ret->uri->scheme, "xenapi") ||
D
Dmitry Guryanov 已提交
1128 1129 1130
#endif
#ifndef WITH_PARALLELS
             STRCASEEQ(ret->uri->scheme, "parallels") ||
1131 1132
#endif
             false)) {
1133
            virReportErrorHelper(VIR_FROM_NONE, VIR_ERR_CONFIG_UNSUPPORTED,
1134 1135 1136 1137 1138 1139
                                 __FILE__, __FUNCTION__, __LINE__,
                                 _("libvirt was built without the '%s' driver"),
                                 ret->uri->scheme);
            goto failed;
        }

1140 1141 1142
        VIR_DEBUG("trying driver %zu (%s) ...", i, virHypervisorDriverTab[i]->name);
        ret->driver = virHypervisorDriverTab[i];
        res = virHypervisorDriverTab[i]->connectOpen(ret, auth, flags);
1143
        VIR_DEBUG("driver %zu %s returned %s",
1144
                  i, virHypervisorDriverTab[i]->name,
O
Osier Yang 已提交
1145 1146 1147 1148 1149
                  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) {
1150
            break;
O
Osier Yang 已提交
1151
        } else if (res == VIR_DRV_OPEN_ERROR) {
1152
            ret->driver = NULL;
O
Osier Yang 已提交
1153
            goto failed;
1154 1155
        } else {
            ret->driver = NULL;
1156
        }
1157 1158
    }

1159
    if (!ret->driver) {
1160
        /* If we reach here, then all drivers declined the connection. */
1161
        virReportError(VIR_ERR_NO_CONNECT, "%s", NULLSTR(name));
1162
        goto failed;
1163 1164
    }

1165
    for (i = 0; i < virNetworkDriverTabCount; i++) {
1166
        res = virNetworkDriverTab[i]->networkOpen(ret, auth, flags);
1167
        VIR_DEBUG("network driver %zu %s returned %s",
O
Osier Yang 已提交
1168 1169 1170 1171 1172 1173
                  i, virNetworkDriverTab[i]->name,
                  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) {
1174 1175
            ret->networkDriver = virNetworkDriverTab[i];
            break;
O
Osier Yang 已提交
1176 1177
        } else if (res == VIR_DRV_OPEN_ERROR) {
            break;
1178
        }
1179
    }
1180

D
Daniel Veillard 已提交
1181
    for (i = 0; i < virInterfaceDriverTabCount; i++) {
1182
        res = virInterfaceDriverTab[i]->interfaceOpen(ret, auth, flags);
1183
        VIR_DEBUG("interface driver %zu %s returned %s",
O
Osier Yang 已提交
1184 1185 1186 1187 1188 1189
                  i, virInterfaceDriverTab[i]->name,
                  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) {
D
Daniel Veillard 已提交
1190 1191
            ret->interfaceDriver = virInterfaceDriverTab[i];
            break;
O
Osier Yang 已提交
1192 1193
        } else if (res == VIR_DRV_OPEN_ERROR) {
            break;
D
Daniel Veillard 已提交
1194 1195
        }
    }
1196 1197 1198

    /* Secondary driver for storage. Optional */
    for (i = 0; i < virStorageDriverTabCount; i++) {
1199
        res = virStorageDriverTab[i]->storageOpen(ret, auth, flags);
1200
        VIR_DEBUG("storage driver %zu %s returned %s",
O
Osier Yang 已提交
1201 1202 1203 1204 1205 1206
                  i, virStorageDriverTab[i]->name,
                  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) {
1207 1208
            ret->storageDriver = virStorageDriverTab[i];
            break;
O
Osier Yang 已提交
1209 1210
        } else if (res == VIR_DRV_OPEN_ERROR) {
            break;
1211 1212 1213
        }
    }

1214
    /* Node driver (optional) */
1215
    for (i = 0; i < virNodeDeviceDriverTabCount; i++) {
1216
        res = virNodeDeviceDriverTab[i]->nodeDeviceOpen(ret, auth, flags);
1217
        VIR_DEBUG("node driver %zu %s returned %s",
1218
                  i, virNodeDeviceDriverTab[i]->name,
O
Osier Yang 已提交
1219 1220 1221 1222 1223
                  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) {
1224
            ret->nodeDeviceDriver = virNodeDeviceDriverTab[i];
1225
            break;
O
Osier Yang 已提交
1226 1227
        } else if (res == VIR_DRV_OPEN_ERROR) {
            break;
1228 1229 1230
        }
    }

1231 1232
    /* Secret manipulation driver. Optional */
    for (i = 0; i < virSecretDriverTabCount; i++) {
1233
        res = virSecretDriverTab[i]->secretOpen(ret, auth, flags);
1234
        VIR_DEBUG("secret driver %zu %s returned %s",
O
Osier Yang 已提交
1235 1236 1237 1238 1239 1240
                  i, virSecretDriverTab[i]->name,
                  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) {
1241 1242
            ret->secretDriver = virSecretDriverTab[i];
            break;
O
Osier Yang 已提交
1243 1244
        } else if (res == VIR_DRV_OPEN_ERROR) {
            break;
1245 1246 1247
        }
    }

S
Stefan Berger 已提交
1248 1249
    /* Network filter driver. Optional */
    for (i = 0; i < virNWFilterDriverTabCount; i++) {
1250
        res = virNWFilterDriverTab[i]->nwfilterOpen(ret, auth, flags);
1251
        VIR_DEBUG("nwfilter driver %zu %s returned %s",
O
Osier Yang 已提交
1252 1253 1254 1255 1256 1257
                  i, virNWFilterDriverTab[i]->name,
                  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) {
S
Stefan Berger 已提交
1258 1259
            ret->nwfilterDriver = virNWFilterDriverTab[i];
            break;
O
Osier Yang 已提交
1260 1261
        } else if (res == VIR_DRV_OPEN_ERROR) {
            break;
S
Stefan Berger 已提交
1262 1263 1264
        }
    }

1265 1266
    virConfFree(conf);

1267
    return ret;
1268

1269
 failed:
1270
    virConfFree(conf);
1271
    virObjectUnref(ret);
1272

1273
    return NULL;
1274 1275
}

1276

1277 1278
/**
 * virConnectOpen:
1279
 * @name: (optional) URI of the hypervisor
1280
 *
1281
 * This function should be called first to get a connection to the
1282 1283
 * Hypervisor and xen store
 *
1284 1285 1286 1287 1288
 * 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.
1289 1290 1291 1292 1293 1294
 *
 * 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
 *
1295
 * URIs are documented at http://libvirt.org/uri.html
E
Eric Blake 已提交
1296
 *
1297 1298 1299
 * virConnectClose should be used to release the resources after the connection
 * is no longer needed.
 *
E
Eric Blake 已提交
1300
 * Returns a pointer to the hypervisor connection or NULL in case of error
1301 1302
 */
virConnectPtr
1303
virConnectOpen(const char *name)
1304
{
1305
    virConnectPtr ret = NULL;
1306 1307 1308

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

1310
    VIR_DEBUG("name=%s", NULLSTR(name));
1311
    virResetLastError();
1312
    ret = do_open(name, NULL, 0);
1313 1314 1315 1316
    if (!ret)
        goto error;
    return ret;

1317
 error:
1318 1319
    virDispatchError(NULL);
    return NULL;
1320 1321
}

1322

1323
/**
1324
 * virConnectOpenReadOnly:
1325
 * @name: (optional) URI of the hypervisor
1326
 *
1327
 * This function should be called first to get a restricted connection to the
D
Daniel Veillard 已提交
1328
 * library functionalities. The set of APIs usable are then restricted
1329
 * on the available methods to control the domains.
1330
 *
1331
 * See virConnectOpen for notes about environment variables which can
1332
 * have an effect on opening drivers and freeing the connection resources
1333
 *
1334
 * URIs are documented at http://libvirt.org/uri.html
E
Eric Blake 已提交
1335 1336
 *
 * Returns a pointer to the hypervisor connection or NULL in case of error
1337
 */
1338
virConnectPtr
1339 1340
virConnectOpenReadOnly(const char *name)
{
1341
    virConnectPtr ret = NULL;
1342 1343 1344

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

1346
    VIR_DEBUG("name=%s", NULLSTR(name));
1347
    virResetLastError();
1348
    ret = do_open(name, NULL, VIR_CONNECT_RO);
1349 1350 1351 1352
    if (!ret)
        goto error;
    return ret;

1353
 error:
1354 1355
    virDispatchError(NULL);
    return NULL;
1356 1357
}

1358

1359 1360
/**
 * virConnectOpenAuth:
1361
 * @name: (optional) URI of the hypervisor
1362
 * @auth: Authenticate callback parameters
1363
 * @flags: bitwise-OR of virConnectFlags
1364
 *
1365
 * This function should be called first to get a connection to the
1366
 * Hypervisor. If necessary, authentication will be performed fetching
1367 1368
 * credentials via the callback
 *
1369
 * See virConnectOpen for notes about environment variables which can
1370
 * have an effect on opening drivers and freeing the connection resources
1371
 *
1372
 * URIs are documented at http://libvirt.org/uri.html
E
Eric Blake 已提交
1373 1374
 *
 * Returns a pointer to the hypervisor connection or NULL in case of error
1375 1376 1377 1378
 */
virConnectPtr
virConnectOpenAuth(const char *name,
                   virConnectAuthPtr auth,
1379
                   unsigned int flags)
1380
{
1381
    virConnectPtr ret = NULL;
1382 1383 1384

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

1386
    VIR_DEBUG("name=%s, auth=%p, flags=%x", NULLSTR(name), auth, flags);
1387
    virResetLastError();
1388
    ret = do_open(name, auth, flags);
1389 1390 1391 1392
    if (!ret)
        goto error;
    return ret;

1393
 error:
1394 1395
    virDispatchError(NULL);
    return NULL;
D
Daniel Veillard 已提交
1396 1397
}

1398

1399

D
Daniel Veillard 已提交
1400
/**
1401
 * virConnectClose:
D
Daniel Veillard 已提交
1402 1403 1404 1405 1406 1407 1408
 * @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.
 *
1409 1410 1411 1412 1413 1414 1415 1416
 * 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.
 *
1417 1418 1419 1420 1421 1422 1423 1424 1425 1426
 * 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 已提交
1427 1428
 */
int
1429 1430
virConnectClose(virConnectPtr conn)
{
1431
    VIR_DEBUG("conn=%p", conn);
1432

1433 1434
    virResetLastError();

1435
    virCheckConnectReturn(conn, -1);
1436

1437 1438 1439
    if (!virObjectUnref(conn))
        return 0;
    return 1;
D
Daniel Veillard 已提交
1440 1441
}

1442

1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482
/* 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;
}