libvirt.c 35.4 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
R
Roman Bogorodskiy 已提交
95 96 97
#ifdef WITH_BHYVE
# include "bhyve/bhyve_driver.h"
#endif
98

99 100
#define VIR_FROM_THIS VIR_FROM_NONE

101 102
VIR_LOG_INIT("libvirt");

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

109
#define MAX_DRIVERS 21
110

111 112
static virConnectDriverPtr virConnectDriverTab[MAX_DRIVERS];
static int virConnectDriverTabCount;
113
static virStateDriverPtr virStateDriverTab[MAX_DRIVERS];
114
static int virStateDriverTabCount;
115

116 117 118 119 120 121 122
static virNetworkDriverPtr virSharedNetworkDriver;
static virInterfaceDriverPtr virSharedInterfaceDriver;
static virStorageDriverPtr virSharedStorageDriver;
static virNodeDeviceDriverPtr virSharedNodeDeviceDriver;
static virSecretDriverPtr virSharedSecretDriver;
static virNWFilterDriverPtr virSharedNWFilterDriver;

123

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

131
    if (geteuid() == 0)
132 133
        return 0;

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

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

145 146 147 148 149 150

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

153
    for (i = 0; i < ncred; i++) {
154 155
        char buf[1024];
        char *bufptr = buf;
156
        size_t len;
157 158

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

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

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

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

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

204 205 206 207
            bufptr = getpass("");
            if (!bufptr)
                return -1;
            break;
208 209 210

        default:
            return -1;
211 212
        }

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

    return 0;
}

225

226 227 228 229 230 231 232 233 234 235
/* 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,
236
    VIR_CRED_EXTERNAL,
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
};

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;

258 259
#if HAVE_WINSOCK2_H
static int
260
virWinsockInit(void)
261 262 263 264 265 266 267
{
    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 已提交
268
    return err == 0 ? 0 : -1;
269 270 271
}
#endif

272

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

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

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

    *priv = lock;
    return 0;
}

291 292 293

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

301 302 303

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

310 311 312

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

319

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

336

337
static bool virGlobalError;
338
static virOnceControl virGlobalOnce = VIR_ONCE_CONTROL_INITIALIZER;
339

340 341 342
static void
virGlobalInit(void)
{
343 344 345 346 347
    /* 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.  */
348
    if (virThreadInitialize() < 0 ||
349
        virErrorInitialize() < 0)
350
        goto error;
351

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

360
#ifdef WITH_GNUTLS_GCRYPT
361 362 363 364 365 366 367 368 369 370 371 372 373
    /*
     * 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);
    }
374
#endif
D
Daniel P. Berrange 已提交
375

376
    virLogSetFromEnv();
377

378
#ifdef WITH_GNUTLS
379
    virNetTLSInit();
380
#endif
381

382
#if WITH_CURL
383 384 385
    curl_global_init(CURL_GLOBAL_DEFAULT);
#endif

386
    VIR_DEBUG("register drivers");
387

388
#if HAVE_WINSOCK2_H
389
    if (virWinsockInit() == -1)
390
        goto error;
391 392
#endif

393
    if (!bindtextdomain(PACKAGE, LOCALEDIR))
394
        goto error;
395

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

439 440
    return;

441
 error:
442 443 444
    virGlobalError = true;
}

445

446 447 448 449 450
/**
 * virInitialize:
 *
 * Initialize the library.
 *
451 452 453 454 455 456
 * 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.
457
 *
458 459 460 461 462
 * 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.
463 464 465 466 467 468 469 470 471 472 473
 *
 * 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;
474
    return 0;
475 476
}

477

478 479
#ifdef WIN32
BOOL WINAPI
480
DllMain(HINSTANCE instance, DWORD reason, LPVOID ignore);
481 482

BOOL WINAPI
483 484 485
DllMain(HINSTANCE instance ATTRIBUTE_UNUSED,
        DWORD reason,
        LPVOID ignore ATTRIBUTE_UNUSED)
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
{
    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
511

512

513
/**
514
 * virSetSharedNetworkDriver:
515 516 517 518
 * @driver: pointer to a network driver block
 *
 * Register a network virtualization driver
 *
519
 * Returns 0 on success, or -1 in case of error.
520 521
 */
int
522
virSetSharedNetworkDriver(virNetworkDriverPtr driver)
523
{
524
    virCheckNonNullArgReturn(driver, -1);
525

526 527 528 529 530 531 532
    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);
533

534 535
    virSharedNetworkDriver = driver;
    return 0;
536 537
}

538

D
Daniel Veillard 已提交
539
/**
540
 * virSetSharedInterfaceDriver:
L
Laine Stump 已提交
541
 * @driver: pointer to an interface driver block
D
Daniel Veillard 已提交
542
 *
L
Laine Stump 已提交
543
 * Register an interface virtualization driver
D
Daniel Veillard 已提交
544 545 546 547
 *
 * Returns the driver priority or -1 in case of error.
 */
int
548
virSetSharedInterfaceDriver(virInterfaceDriverPtr driver)
D
Daniel Veillard 已提交
549
{
550
    virCheckNonNullArgReturn(driver, -1);
D
Daniel Veillard 已提交
551

552 553 554 555 556
    if (virSharedInterfaceDriver) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("A interface driver is already registered"));
        return -1;
    }
D
Daniel Veillard 已提交
557

558 559 560 561
    VIR_DEBUG("registering %s as interface driver", driver->name);

    virSharedInterfaceDriver = driver;
    return 0;
D
Daniel Veillard 已提交
562 563
}

564

565
/**
566
 * virSetSharedStorageDriver:
567 568 569 570 571 572 573
 * @driver: pointer to a storage driver block
 *
 * Register a storage virtualization driver
 *
 * Returns the driver priority or -1 in case of error.
 */
int
574
virSetSharedStorageDriver(virStorageDriverPtr driver)
575
{
576
    virCheckNonNullArgReturn(driver, -1);
577

578 579 580 581 582 583 584
    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);
585

586 587
    virSharedStorageDriver = driver;
    return 0;
588 589
}

590

591
/**
592
 * virSetSharedNodeDeviceDriver:
593 594 595 596 597 598 599
 * @driver: pointer to a device monitor block
 *
 * Register a device monitor
 *
 * Returns the driver priority or -1 in case of error.
 */
int
600
virSetSharedNodeDeviceDriver(virNodeDeviceDriverPtr driver)
601
{
602
    virCheckNonNullArgReturn(driver, -1);
603

604 605 606 607 608
    if (virSharedNodeDeviceDriver) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("A node device driver is already registered"));
        return -1;
    }
609

610 611 612 613
    VIR_DEBUG("registering %s as device driver", driver->name);

    virSharedNodeDeviceDriver = driver;
    return 0;
614 615
}

616

617
/**
618
 * virSetSharedSecretDriver:
619 620 621 622 623 624 625
 * @driver: pointer to a secret driver block
 *
 * Register a secret driver
 *
 * Returns the driver priority or -1 in case of error.
 */
int
626
virSetSharedSecretDriver(virSecretDriverPtr driver)
627
{
628
    virCheckNonNullArgReturn(driver, -1);
629

630 631 632 633 634 635 636
    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);
637

638 639
    virSharedSecretDriver = driver;
    return 0;
640 641
}

642

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

656 657 658 659 660
    if (virSharedNWFilterDriver) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("A network filter driver is already registered"));
        return -1;
    }
S
Stefan Berger 已提交
661

662 663 664 665
    VIR_DEBUG("registering %s as network filter driver", driver->name);

    virSharedNWFilterDriver = driver;
    return 0;
S
Stefan Berger 已提交
666 667 668
}


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

686
    virCheckNonNullArgReturn(driver, -1);
687 688 689 690 691 692
    if (virConnectDriverTabCount >= MAX_DRIVERS) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Too many drivers, cannot register %s"),
                       driver->hypervisorDriver->name);
        return -1;
    }
693

694
    VIR_DEBUG("registering %s as driver %d",
695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710
           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;
    }
711

712 713
    virConnectDriverTab[virConnectDriverTabCount] = driver;
    return virConnectDriverTabCount++;
714 715
}

716

717 718 719 720 721 722 723 724 725 726 727
/**
 * 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)
{
728
    virCheckNonNullArgReturn(driver, -1);
729 730 731 732 733 734 735

    if (virStateDriverTabCount >= MAX_DRIVERS) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Too many drivers, cannot register %s"),
                       driver->name);
        return -1;
    }
736 737 738 739 740

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

741

742 743
/**
 * virStateInitialize:
744
 * @privileged: set to true if running with root privilege, false otherwise
745 746
 * @callback: callback to invoke to inhibit shutdown of the daemon
 * @opaque: data to pass to @callback
747
 *
748 749 750 751 752
 * 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.
753
 *
754
 * Returns 0 if all succeed, -1 upon any failure.
755
 */
756 757 758 759
int
virStateInitialize(bool privileged,
                   virStateInhibitCallback callback,
                   void *opaque)
760
{
761
    size_t i;
762 763 764 765

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

766
    for (i = 0; i < virStateDriverTabCount; i++) {
767
        if (virStateDriverTab[i]->stateInitialize) {
768
            VIR_DEBUG("Running global init for %s state driver",
769
                      virStateDriverTab[i]->name);
770 771 772
            if (virStateDriverTab[i]->stateInitialize(privileged,
                                                      callback,
                                                      opaque) < 0) {
773 774
                VIR_ERROR(_("Initialization of %s state driver failed: %s"),
                          virStateDriverTab[i]->name,
775
                          virGetLastErrorMessage());
776 777
                return -1;
            }
778
        }
779
    }
780 781 782 783 784 785 786 787

    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();
        }
    }
788
    return 0;
789 790
}

791

792 793 794 795 796
/**
 * virStateCleanup:
 *
 * Run each virtualization driver's cleanup method.
 *
797
 * Returns 0 if all succeed, -1 upon any failure.
798
 */
799 800 801
int
virStateCleanup(void)
{
802
    int r;
803
    int ret = 0;
804

805 806 807
    for (r = virStateDriverTabCount - 1; r >= 0; r--) {
        if (virStateDriverTab[r]->stateCleanup &&
            virStateDriverTab[r]->stateCleanup() < 0)
808 809 810 811 812
            ret = -1;
    }
    return ret;
}

813

814 815 816 817 818
/**
 * virStateReload:
 *
 * Run each virtualization driver's reload method.
 *
819
 * Returns 0 if all succeed, -1 upon any failure.
820
 */
821 822 823
int
virStateReload(void)
{
824 825
    size_t i;
    int ret = 0;
826

827
    for (i = 0; i < virStateDriverTabCount; i++) {
828 829
        if (virStateDriverTab[i]->stateReload &&
            virStateDriverTab[i]->stateReload() < 0)
830 831 832 833 834
            ret = -1;
    }
    return ret;
}

835

836 837 838 839 840 841 842
/**
 * virStateStop:
 *
 * Run each virtualization driver's "stop" method.
 *
 * Returns 0 if successful, -1 on failure
 */
843 844 845
int
virStateStop(void)
{
846 847
    size_t i;
    int ret = 0;
848

849
    for (i = 0; i < virStateDriverTabCount; i++) {
850 851
        if (virStateDriverTab[i]->stateStop &&
            virStateDriverTab[i]->stateStop())
852 853 854 855
            ret = 1;
    }
    return ret;
}
856 857


858 859 860
/**
 * virGetVersion:
 * @libVer: return value for the library version (OUT)
861 862 863 864 865 866 867 868 869 870
 * @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
871
 * get the version of the running hypervisor use the virConnectGetVersion()
872
 * function instead. To get the libvirt library version used by a
873 874 875
 * connection use the virConnectGetLibVersion() instead.
 *
 * This function includes a call to virInitialize() when necessary.
876 877 878 879 880
 *
 * 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
881
virGetVersion(unsigned long *libVer, const char *type ATTRIBUTE_UNUSED,
882 883
              unsigned long *typeVer)
{
884 885
    if (virInitialize() < 0)
        goto error;
886
    VIR_DEBUG("libVir=%p, type=%s, typeVer=%p", libVer, type, typeVer);
887

888
    virResetLastError();
889
    if (libVer == NULL)
890
        goto error;
891 892
    *libVer = LIBVIR_VERSION_NUMBER;

893
    if (typeVer != NULL)
894 895
        *typeVer = LIBVIR_VERSION_NUMBER;

896
    return 0;
897

898
 error:
899 900
    virDispatchError(NULL);
    return -1;
901 902
}

903 904 905

static int
virConnectGetDefaultURI(virConfPtr conf,
906
                        char **name)
907 908
{
    int ret = -1;
909
    const char *defname = virGetEnvBlockSUID("LIBVIRT_DEFAULT_URI");
910 911
    if (defname && *defname) {
        VIR_DEBUG("Using LIBVIRT_DEFAULT_URI '%s'", defname);
912
        if (VIR_STRDUP(*name, defname) < 0)
913
            goto cleanup;
914 915 916 917 918 919
    } else {
        if (virConfGetValueString(conf, "uri_default", name) < 0)
            goto cleanup;

        if (*name)
            VIR_DEBUG("Using config file uri '%s'", *name);
920 921 922
    }

    ret = 0;
923
 cleanup:
924 925 926
    return ret;
}

927

928 929 930 931 932 933 934
/*
 * Check to see if an invalid URI like qemu://system (missing /) was passed,
 * offer the suggested fix.
 */
static int
virConnectCheckURIMissingSlash(const char *uristr, virURIPtr uri)
{
935 936 937
    if (!uri->scheme || !uri->path || !uri->server)
        return 0;

938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956
    /* To avoid false positives, only check drivers that mandate
       a path component in the URI, like /system or /session */
    if (STRNEQ(uri->scheme, "qemu") &&
        STRNEQ(uri->scheme, "vbox") &&
        STRNEQ(uri->scheme, "vz"))
        return 0;

    if (STREQ(uri->server, "session") ||
        STREQ(uri->server, "system")) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("invalid URI %s (maybe you want %s:///%s)"),
                       uristr, uri->scheme, uri->server);
        return -1;
    }

    return 0;
}


957
static virConnectPtr
958 959 960
virConnectOpenInternal(const char *name,
                       virConnectAuthPtr auth,
                       unsigned int flags)
961
{
962 963
    size_t i;
    int res;
964
    virConnectPtr ret;
965
    virConfPtr conf = NULL;
966
    char *uristr = NULL;
967 968 969 970

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

972
    if (virConfLoadConfig(&conf, NULL) < 0)
973 974 975 976 977
        goto failed;

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

978 979 980 981 982 983
    if (!name && virIsSUID()) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("An explicit URI must be provided when setuid"));
        goto failed;
    }

984 985 986 987 988 989 990 991 992 993
    /* Convert xen -> xen:/// for back compat */
    if (name && STRCASEEQ(name, "xen"))
        name = "xen:///";

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

994
    /*
E
Eric Blake 已提交
995 996 997
     * 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.
998
     */
999
    if (name) {
1000 1001 1002 1003 1004 1005
        if (VIR_STRDUP(uristr, name) < 0)
            goto failed;
    } else {
        if (virConnectGetDefaultURI(conf, &uristr) < 0)
            goto failed;
    }
1006

1007 1008
    if (uristr) {
        char *alias = NULL;
1009

1010
        if (!(flags & VIR_CONNECT_NO_ALIASES) &&
1011
            virURIResolveAlias(conf, uristr, &alias) < 0)
1012 1013
            goto failed;

1014 1015 1016 1017 1018 1019
        if (alias) {
            VIR_FREE(uristr);
            uristr = alias;
        }

        if (!(ret->uri = virURIParse(uristr))) {
1020
            VIR_FREE(alias);
1021 1022
            goto failed;
        }
1023

1024
        VIR_DEBUG("Split \"%s\" to URI components:\n"
1025 1026 1027 1028
                  "  scheme %s\n"
                  "  server %s\n"
                  "  user %s\n"
                  "  port %d\n"
J
Jiri Denemark 已提交
1029
                  "  path %s",
1030
                  uristr,
1031
                  NULLSTR(ret->uri->scheme), NULLSTR(ret->uri->server),
1032 1033 1034
                  NULLSTR(ret->uri->user), ret->uri->port,
                  NULLSTR(ret->uri->path));

1035
        if (virConnectCheckURIMissingSlash(uristr,
1036 1037 1038
                                           ret->uri) < 0) {
            goto failed;
        }
1039
    } else {
1040
        VIR_DEBUG("no name, allowing driver auto-select");
1041 1042
    }

1043 1044 1045
    /* Cleansing flags */
    ret->flags = flags & VIR_CONNECT_RO;

1046
    for (i = 0; i < virConnectDriverTabCount; i++) {
1047 1048 1049 1050 1051 1052 1053
        /* 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. */
1054
        if (STREQ(virConnectDriverTab[i]->hypervisorDriver->name, "remote") &&
1055 1056 1057 1058 1059 1060
            ret->uri != NULL && ret->uri->scheme != NULL &&
            (
#ifndef WITH_PHYP
             STRCASEEQ(ret->uri->scheme, "phyp") ||
#endif
#ifndef WITH_ESX
1061
             STRCASEEQ(ret->uri->scheme, "vpx") ||
1062 1063
             STRCASEEQ(ret->uri->scheme, "esx") ||
             STRCASEEQ(ret->uri->scheme, "gsx") ||
M
Matthias Bolte 已提交
1064 1065 1066
#endif
#ifndef WITH_HYPERV
             STRCASEEQ(ret->uri->scheme, "hyperv") ||
1067 1068 1069
#endif
#ifndef WITH_XENAPI
             STRCASEEQ(ret->uri->scheme, "xenapi") ||
D
Dmitry Guryanov 已提交
1070
#endif
1071
#ifndef WITH_VZ
D
Dmitry Guryanov 已提交
1072
             STRCASEEQ(ret->uri->scheme, "parallels") ||
1073 1074
#endif
             false)) {
1075
            virReportErrorHelper(VIR_FROM_NONE, VIR_ERR_CONFIG_UNSUPPORTED,
1076 1077 1078 1079 1080 1081
                                 __FILE__, __FUNCTION__, __LINE__,
                                 _("libvirt was built without the '%s' driver"),
                                 ret->uri->scheme);
            goto failed;
        }

1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
        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;

1093
        res = virConnectDriverTab[i]->hypervisorDriver->connectOpen(ret, auth, conf, flags);
1094
        VIR_DEBUG("driver %zu %s returned %s",
1095
                  i, virConnectDriverTab[i]->hypervisorDriver->name,
O
Osier Yang 已提交
1096 1097 1098 1099 1100
                  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) {
1101
            break;
1102 1103
        } else {
            ret->driver = NULL;
1104 1105 1106 1107 1108 1109 1110 1111 1112
            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;
1113
        }
1114 1115
    }

1116
    if (!ret->driver) {
1117
        /* If we reach here, then all drivers declined the connection. */
1118
        virReportError(VIR_ERR_NO_CONNECT, "%s", NULLSTR(name));
1119
        goto failed;
1120 1121
    }

1122
    virConfFree(conf);
1123
    VIR_FREE(uristr);
1124

1125
    return ret;
1126

1127
 failed:
1128
    VIR_FREE(uristr);
1129
    virConfFree(conf);
1130
    virObjectUnref(ret);
1131

1132
    return NULL;
1133 1134
}

1135

1136 1137
/**
 * virConnectOpen:
1138
 * @name: (optional) URI of the hypervisor
1139
 *
1140
 * This function should be called first to get a connection to the
1141 1142
 * Hypervisor and xen store
 *
1143 1144 1145 1146 1147
 * 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.
1148 1149 1150 1151 1152 1153
 *
 * 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
 *
1154
 * URIs are documented at http://libvirt.org/uri.html
E
Eric Blake 已提交
1155
 *
1156 1157 1158
 * virConnectClose should be used to release the resources after the connection
 * is no longer needed.
 *
E
Eric Blake 已提交
1159
 * Returns a pointer to the hypervisor connection or NULL in case of error
1160 1161
 */
virConnectPtr
1162
virConnectOpen(const char *name)
1163
{
1164
    virConnectPtr ret = NULL;
1165 1166 1167

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

1169
    VIR_DEBUG("name=%s", NULLSTR(name));
1170
    virResetLastError();
1171
    ret = virConnectOpenInternal(name, NULL, 0);
1172 1173 1174 1175
    if (!ret)
        goto error;
    return ret;

1176
 error:
1177 1178
    virDispatchError(NULL);
    return NULL;
1179 1180
}

1181

1182
/**
1183
 * virConnectOpenReadOnly:
1184
 * @name: (optional) URI of the hypervisor
1185
 *
1186
 * This function should be called first to get a restricted connection to the
D
Daniel Veillard 已提交
1187
 * library functionalities. The set of APIs usable are then restricted
1188
 * on the available methods to control the domains.
1189
 *
1190
 * See virConnectOpen for notes about environment variables which can
1191
 * have an effect on opening drivers and freeing the connection resources
1192
 *
1193
 * URIs are documented at http://libvirt.org/uri.html
E
Eric Blake 已提交
1194 1195
 *
 * Returns a pointer to the hypervisor connection or NULL in case of error
1196
 */
1197
virConnectPtr
1198 1199
virConnectOpenReadOnly(const char *name)
{
1200
    virConnectPtr ret = NULL;
1201 1202 1203

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

1205
    VIR_DEBUG("name=%s", NULLSTR(name));
1206
    virResetLastError();
1207
    ret = virConnectOpenInternal(name, NULL, VIR_CONNECT_RO);
1208 1209 1210 1211
    if (!ret)
        goto error;
    return ret;

1212
 error:
1213 1214
    virDispatchError(NULL);
    return NULL;
1215 1216
}

1217

1218 1219
/**
 * virConnectOpenAuth:
1220
 * @name: (optional) URI of the hypervisor
1221
 * @auth: Authenticate callback parameters
1222
 * @flags: bitwise-OR of virConnectFlags
1223
 *
1224
 * This function should be called first to get a connection to the
1225
 * Hypervisor. If necessary, authentication will be performed fetching
1226 1227
 * credentials via the callback
 *
1228
 * See virConnectOpen for notes about environment variables which can
1229
 * have an effect on opening drivers and freeing the connection resources
1230
 *
1231
 * URIs are documented at http://libvirt.org/uri.html
E
Eric Blake 已提交
1232 1233
 *
 * Returns a pointer to the hypervisor connection or NULL in case of error
1234 1235 1236 1237
 */
virConnectPtr
virConnectOpenAuth(const char *name,
                   virConnectAuthPtr auth,
1238
                   unsigned int flags)
1239
{
1240
    virConnectPtr ret = NULL;
1241 1242 1243

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

1245
    VIR_DEBUG("name=%s, auth=%p, flags=%x", NULLSTR(name), auth, flags);
1246
    virResetLastError();
1247
    ret = virConnectOpenInternal(name, auth, flags);
1248 1249 1250 1251
    if (!ret)
        goto error;
    return ret;

1252
 error:
1253 1254
    virDispatchError(NULL);
    return NULL;
D
Daniel Veillard 已提交
1255 1256
}

1257

1258

D
Daniel Veillard 已提交
1259
/**
1260
 * virConnectClose:
D
Daniel Veillard 已提交
1261 1262 1263 1264 1265 1266 1267
 * @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.
 *
1268 1269 1270 1271 1272 1273 1274 1275
 * 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.
 *
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285
 * 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 已提交
1286 1287
 */
int
1288 1289
virConnectClose(virConnectPtr conn)
{
1290
    VIR_DEBUG("conn=%p", conn);
1291

1292 1293
    virResetLastError();

1294
    virCheckConnectReturn(conn, -1);
1295

1296 1297 1298
    if (!virObjectUnref(conn))
        return 0;
    return 1;
D
Daniel Veillard 已提交
1299 1300
}

1301

1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341
/* 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;
}