libvirt.c 34.8 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
#include <config.h>
D
Daniel Veillard 已提交
23

24 25 26
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
E
Eric Blake 已提交
27
#include <sys/wait.h>
28
#include <time.h>
29
#include <gio/gnetworking.h>
30

31 32
#include <libxml/parser.h>
#include <libxml/xpath.h>
33 34
#include "getpass.h"

35
#ifdef WITH_CURL
36 37 38
# include <curl/curl.h>
#endif

39
#include "virerror.h"
40
#include "virlog.h"
41
#include "datatypes.h"
42
#include "driver.h"
43

44
#include "viruuid.h"
45
#include "viralloc.h"
46
#include "configmake.h"
47
#include "virconf.h"
48
#if WITH_GNUTLS
49 50
# include "rpc/virnettlscontext.h"
#endif
51
#include "vircommand.h"
52
#include "virfile.h"
53
#include "virrandom.h"
M
Martin Kletzander 已提交
54
#include "viruri.h"
55
#include "virthread.h"
56
#include "virstring.h"
E
Eric Blake 已提交
57
#include "virutil.h"
58
#include "virtypedparam.h"
59

60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
#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_ESX
# include "esx/esx_driver.h"
#endif
#ifdef WITH_HYPERV
# include "hyperv/hyperv_driver.h"
#endif
R
Roman Bogorodskiy 已提交
78 79 80
#ifdef WITH_BHYVE
# include "bhyve/bhyve_driver.h"
#endif
81

82 83
#define VIR_FROM_THIS VIR_FROM_NONE

84 85
VIR_LOG_INIT("libvirt");

D
Daniel Veillard 已提交
86 87 88
/*
 * TODO:
 * - use lock to protect against concurrent accesses ?
D
Daniel Veillard 已提交
89
 * - use reference counting to guarantee coherent pointer state ?
D
Daniel Veillard 已提交
90 91
 */

92
#define MAX_DRIVERS 21
93

94 95
static virConnectDriverPtr virConnectDriverTab[MAX_DRIVERS];
static int virConnectDriverTabCount;
96
static virStateDriverPtr virStateDriverTab[MAX_DRIVERS];
97
static int virStateDriverTabCount;
98

99 100 101 102 103 104 105
static virNetworkDriverPtr virSharedNetworkDriver;
static virInterfaceDriverPtr virSharedInterfaceDriver;
static virStorageDriverPtr virSharedStorageDriver;
static virNodeDeviceDriverPtr virSharedNodeDeviceDriver;
static virSecretDriverPtr virSharedSecretDriver;
static virNWFilterDriverPtr virSharedNWFilterDriver;

106

107 108 109
static int
virConnectAuthCallbackDefault(virConnectCredentialPtr cred,
                              unsigned int ncred,
J
Ján Tomko 已提交
110
                              void *cbdata G_GNUC_UNUSED)
111
{
112
    size_t i;
113

114
    for (i = 0; i < ncred; i++) {
115 116
        char buf[1024];
        char *bufptr = buf;
117
        size_t len;
118 119

        switch (cred[i].type) {
120 121 122 123
        case VIR_CRED_EXTERNAL: {
            if (STRNEQ(cred[i].challenge, "PolicyKit"))
                return -1;

124 125 126 127 128
            /*
             * Ignore & carry on. Although we can't auth
             * directly, the user may have authenticated
             * themselves already outside context of libvirt
             */
129 130
            break;
        }
131

132 133 134 135
        case VIR_CRED_USERNAME:
        case VIR_CRED_AUTHNAME:
        case VIR_CRED_ECHOPROMPT:
        case VIR_CRED_REALM:
136
            if (printf("%s: ", cred[i].prompt) < 0)
137 138 139 140
                return -1;
            if (fflush(stdout) != 0)
                return -1;

141 142 143 144 145 146 147
            if (!fgets(buf, sizeof(buf), stdin)) {
                if (feof(stdin)) { /* Treat EOF as "" */
                    buf[0] = '\0';
                    break;
                }
                return -1;
            }
148 149 150
            len = strlen(buf);
            if (len != 0 && buf[len-1] == '\n')
                buf[len-1] = '\0';
151 152 153 154
            break;

        case VIR_CRED_PASSPHRASE:
        case VIR_CRED_NOECHOPROMPT:
155
            if (printf("%s: ", cred[i].prompt) < 0)
156 157 158 159
                return -1;
            if (fflush(stdout) != 0)
                return -1;

160 161 162 163
            bufptr = getpass("");
            if (!bufptr)
                return -1;
            break;
164 165 166

        default:
            return -1;
167 168
        }

D
Daniel P. Berrange 已提交
169
        if (cred[i].type != VIR_CRED_EXTERNAL) {
170
            cred[i].result = g_strdup(STREQ(bufptr, "") && cred[i].defresult ? cred[i].defresult : bufptr);
D
Daniel P. Berrange 已提交
171 172
            cred[i].resultlen = strlen(cred[i].result);
        }
173 174 175 176 177
    }

    return 0;
}

178

179 180 181 182 183 184 185 186 187 188
/* 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,
189
    VIR_CRED_EXTERNAL,
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
};

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;

211
static bool virGlobalError;
212
static virOnceControl virGlobalOnce = VIR_ONCE_CONTROL_INITIALIZER;
213

214 215 216
static void
virGlobalInit(void)
{
217 218 219 220 221
    /* 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.  */
222
    if (virErrorInitialize() < 0)
223
        goto error;
224

225 226
    virFileActivateDirOverrideForLib();

227 228
    if (getuid() != geteuid() ||
        getgid() != getegid()) {
229
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
230
                       _("libvirt.so is not safe to use from setuid/setgid programs"));
231 232 233
        goto error;
    }

234
    virLogSetFromEnv();
235

236
#ifdef WITH_GNUTLS
237
    virNetTLSInit();
238
#endif
239

240
#if WITH_CURL
241 242 243
    curl_global_init(CURL_GLOBAL_DEFAULT);
#endif

244
    VIR_DEBUG("register drivers");
245

246
    g_networking_init();
247

248
#ifdef HAVE_LIBINTL_H
249
    if (!bindtextdomain(PACKAGE, LOCALEDIR))
250
        goto error;
251
#endif /* HAVE_LIBINTL_H */
252

253
    /*
254 255
     * Note that the order is important: the first ones have a higher
     * priority when calling virConnectOpen.
256
     */
257
#ifdef WITH_TEST
258 259
    if (testRegister() == -1)
        goto error;
260 261
#endif
#ifdef WITH_OPENVZ
262 263
    if (openvzRegister() == -1)
        goto error;
264 265
#endif
#ifdef WITH_VMWARE
266 267
    if (vmwareRegister() == -1)
        goto error;
268 269
#endif
#ifdef WITH_ESX
270 271
    if (esxRegister() == -1)
        goto error;
272 273
#endif
#ifdef WITH_HYPERV
274 275
    if (hypervRegister() == -1)
        goto error;
276
#endif
277
#ifdef WITH_REMOTE
278
    if (remoteRegister() == -1)
279
        goto error;
280
#endif
D
Daniel P. Berrange 已提交
281

282 283
    return;

284
 error:
285 286 287
    virGlobalError = true;
}

288

289 290 291 292 293
/**
 * virInitialize:
 *
 * Initialize the library.
 *
294 295 296 297 298 299
 * 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.
300
 *
301 302 303 304 305
 * 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.
306 307 308 309 310 311 312 313 314 315 316
 *
 * 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;
317
    return 0;
318 319
}

320

321 322
#ifdef WIN32
BOOL WINAPI
323
DllMain(HINSTANCE instance, DWORD reason, LPVOID ignore);
324 325

BOOL WINAPI
J
Ján Tomko 已提交
326
DllMain(HINSTANCE instance G_GNUC_UNUSED,
327
        DWORD reason,
J
Ján Tomko 已提交
328
        LPVOID ignore G_GNUC_UNUSED)
329 330 331 332 333 334 335 336
{
    switch (reason) {
    case DLL_PROCESS_ATTACH:
        virInitialize();
        break;

    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
337
        /* Nothing todo in libvirt yet */
338 339 340 341 342 343 344 345 346 347 348 349
        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
350

351

352
/**
353
 * virSetSharedNetworkDriver:
354 355 356 357
 * @driver: pointer to a network driver block
 *
 * Register a network virtualization driver
 *
358
 * Returns 0 on success, or -1 in case of error.
359 360
 */
int
361
virSetSharedNetworkDriver(virNetworkDriverPtr driver)
362
{
363
    virCheckNonNullArgReturn(driver, -1);
364

365 366 367 368 369 370 371
    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);
372

373 374
    virSharedNetworkDriver = driver;
    return 0;
375 376
}

377

D
Daniel Veillard 已提交
378
/**
379
 * virSetSharedInterfaceDriver:
L
Laine Stump 已提交
380
 * @driver: pointer to an interface driver block
D
Daniel Veillard 已提交
381
 *
L
Laine Stump 已提交
382
 * Register an interface virtualization driver
D
Daniel Veillard 已提交
383 384 385 386
 *
 * Returns the driver priority or -1 in case of error.
 */
int
387
virSetSharedInterfaceDriver(virInterfaceDriverPtr driver)
D
Daniel Veillard 已提交
388
{
389
    virCheckNonNullArgReturn(driver, -1);
D
Daniel Veillard 已提交
390

391 392 393 394 395
    if (virSharedInterfaceDriver) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("A interface driver is already registered"));
        return -1;
    }
D
Daniel Veillard 已提交
396

397 398 399 400
    VIR_DEBUG("registering %s as interface driver", driver->name);

    virSharedInterfaceDriver = driver;
    return 0;
D
Daniel Veillard 已提交
401 402
}

403

404
/**
405
 * virSetSharedStorageDriver:
406 407 408 409 410 411 412
 * @driver: pointer to a storage driver block
 *
 * Register a storage virtualization driver
 *
 * Returns the driver priority or -1 in case of error.
 */
int
413
virSetSharedStorageDriver(virStorageDriverPtr driver)
414
{
415
    virCheckNonNullArgReturn(driver, -1);
416

417 418 419 420 421 422 423
    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);
424

425 426
    virSharedStorageDriver = driver;
    return 0;
427 428
}

429

430
/**
431
 * virSetSharedNodeDeviceDriver:
432 433 434 435 436 437 438
 * @driver: pointer to a device monitor block
 *
 * Register a device monitor
 *
 * Returns the driver priority or -1 in case of error.
 */
int
439
virSetSharedNodeDeviceDriver(virNodeDeviceDriverPtr driver)
440
{
441
    virCheckNonNullArgReturn(driver, -1);
442

443 444 445 446 447
    if (virSharedNodeDeviceDriver) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("A node device driver is already registered"));
        return -1;
    }
448

449 450 451 452
    VIR_DEBUG("registering %s as device driver", driver->name);

    virSharedNodeDeviceDriver = driver;
    return 0;
453 454
}

455

456
/**
457
 * virSetSharedSecretDriver:
458 459 460 461 462 463 464
 * @driver: pointer to a secret driver block
 *
 * Register a secret driver
 *
 * Returns the driver priority or -1 in case of error.
 */
int
465
virSetSharedSecretDriver(virSecretDriverPtr driver)
466
{
467
    virCheckNonNullArgReturn(driver, -1);
468

469 470 471 472 473 474 475
    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);
476

477 478
    virSharedSecretDriver = driver;
    return 0;
479 480
}

481

S
Stefan Berger 已提交
482
/**
483
 * virSetSharedNWFilterDriver:
S
Stefan Berger 已提交
484 485 486 487 488 489 490
 * @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
491
virSetSharedNWFilterDriver(virNWFilterDriverPtr driver)
S
Stefan Berger 已提交
492
{
493
    virCheckNonNullArgReturn(driver, -1);
S
Stefan Berger 已提交
494

495 496 497 498 499
    if (virSharedNWFilterDriver) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("A network filter driver is already registered"));
        return -1;
    }
S
Stefan Berger 已提交
500

501 502 503 504
    VIR_DEBUG("registering %s as network filter driver", driver->name);

    virSharedNWFilterDriver = driver;
    return 0;
S
Stefan Berger 已提交
505 506 507
}


508
/**
509
 * virRegisterConnectDriver:
510
 * @driver: pointer to a driver block
511
 * @setSharedDrivers: populate shared drivers
512
 *
513 514
 * Register a virtualization driver, optionally filling in
 * any empty pointers for shared secondary drivers
515 516 517 518
 *
 * Returns the driver priority or -1 in case of error.
 */
int
519 520
virRegisterConnectDriver(virConnectDriverPtr driver,
                         bool setSharedDrivers)
521
{
522
    VIR_DEBUG("driver=%p name=%s", driver,
523
              driver ? NULLSTR(driver->hypervisorDriver->name) : "(null)");
524

525
    virCheckNonNullArgReturn(driver, -1);
526 527 528 529 530 531
    if (virConnectDriverTabCount >= MAX_DRIVERS) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Too many drivers, cannot register %s"),
                       driver->hypervisorDriver->name);
        return -1;
    }
532

533
    VIR_DEBUG("registering %s as driver %d",
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
           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;
    }
550

551 552
    virConnectDriverTab[virConnectDriverTabCount] = driver;
    return virConnectDriverTabCount++;
553 554
}

555

556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
/**
 * virHasDriverForURIScheme:
 * @scheme: the URI scheme
 *
 * Determine if there is a driver registered that explicitly
 * handles URIs with the scheme @scheme.
 *
 * Returns: true if a driver is registered
 */
bool
virHasDriverForURIScheme(const char *scheme)
{
    size_t i;
    size_t j;

    for (i = 0; i < virConnectDriverTabCount; i++) {
        if (!virConnectDriverTab[i]->uriSchemes)
            continue;
        for (j = 0; virConnectDriverTab[i]->uriSchemes[j]; j++) {
            if (STREQ(virConnectDriverTab[i]->uriSchemes[j], scheme))
                return true;
        }
    }

    return false;
}

583 584 585 586 587 588 589 590 591 592 593
/**
 * 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)
{
594
    virCheckNonNullArgReturn(driver, -1);
595 596 597 598 599 600 601

    if (virStateDriverTabCount >= MAX_DRIVERS) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Too many drivers, cannot register %s"),
                       driver->name);
        return -1;
    }
602 603 604 605 606

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

607

608 609
/**
 * virStateInitialize:
610
 * @privileged: set to true if running with root privilege, false otherwise
611
 * @mandatory: set to true if all drivers must report success, not skipped
612 613
 * @callback: callback to invoke to inhibit shutdown of the daemon
 * @opaque: data to pass to @callback
614
 *
615
 * Initialize all virtualization drivers.
616
 *
617
 * Returns 0 if all succeed, -1 upon any failure.
618
 */
619 620
int
virStateInitialize(bool privileged,
621
                   bool mandatory,
622 623
                   virStateInhibitCallback callback,
                   void *opaque)
624
{
625
    size_t i;
626 627 628 629

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

630
    for (i = 0; i < virStateDriverTabCount; i++) {
631
        if (virStateDriverTab[i]->stateInitialize) {
632
            virDrvStateInitResult ret;
633
            VIR_DEBUG("Running global init for %s state driver",
634
                      virStateDriverTab[i]->name);
635 636 637 638 639
            ret = virStateDriverTab[i]->stateInitialize(privileged,
                                                        callback,
                                                        opaque);
            VIR_DEBUG("State init result %d (mandatory=%d)", ret, mandatory);
            if (ret == VIR_DRV_STATE_INIT_ERROR) {
640 641
                VIR_ERROR(_("Initialization of %s state driver failed: %s"),
                          virStateDriverTab[i]->name,
642
                          virGetLastErrorMessage());
643
                return -1;
644 645 646 647
            } else if (ret == VIR_DRV_STATE_INIT_SKIPPED && mandatory) {
                VIR_ERROR(_("Initialization of mandatory %s state driver skipped"),
                          virStateDriverTab[i]->name);
                return -1;
648
            }
649
        }
650
    }
651
    return 0;
652 653
}

654

655 656 657 658 659
/**
 * virStateCleanup:
 *
 * Run each virtualization driver's cleanup method.
 *
660
 * Returns 0 if all succeed, -1 upon any failure.
661
 */
662 663 664
int
virStateCleanup(void)
{
665
    int r;
666
    int ret = 0;
667

668 669 670
    for (r = virStateDriverTabCount - 1; r >= 0; r--) {
        if (virStateDriverTab[r]->stateCleanup &&
            virStateDriverTab[r]->stateCleanup() < 0)
671 672 673 674 675
            ret = -1;
    }
    return ret;
}

676

677 678 679 680 681
/**
 * virStateReload:
 *
 * Run each virtualization driver's reload method.
 *
682
 * Returns 0 if all succeed, -1 upon any failure.
683
 */
684 685 686
int
virStateReload(void)
{
687 688
    size_t i;
    int ret = 0;
689

690
    for (i = 0; i < virStateDriverTabCount; i++) {
691 692
        if (virStateDriverTab[i]->stateReload &&
            virStateDriverTab[i]->stateReload() < 0)
693 694 695 696 697
            ret = -1;
    }
    return ret;
}

698

699 700 701 702 703 704 705
/**
 * virStateStop:
 *
 * Run each virtualization driver's "stop" method.
 *
 * Returns 0 if successful, -1 on failure
 */
706 707 708
int
virStateStop(void)
{
709 710
    size_t i;
    int ret = 0;
711

712
    for (i = 0; i < virStateDriverTabCount; i++) {
713 714
        if (virStateDriverTab[i]->stateStop &&
            virStateDriverTab[i]->stateStop())
715 716 717 718
            ret = 1;
    }
    return ret;
}
719 720


721 722 723
/**
 * virGetVersion:
 * @libVer: return value for the library version (OUT)
724 725 726 727 728 729 730 731 732 733
 * @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
734
 * get the version of the running hypervisor use the virConnectGetVersion()
735
 * function instead. To get the libvirt library version used by a
736 737 738
 * connection use the virConnectGetLibVersion() instead.
 *
 * This function includes a call to virInitialize() when necessary.
739 740 741 742 743
 *
 * 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
J
Ján Tomko 已提交
744
virGetVersion(unsigned long *libVer, const char *type G_GNUC_UNUSED,
745 746
              unsigned long *typeVer)
{
747 748
    if (virInitialize() < 0)
        goto error;
749
    VIR_DEBUG("libVir=%p, type=%s, typeVer=%p", libVer, type, typeVer);
750

751
    virResetLastError();
752
    if (libVer == NULL)
753
        goto error;
754 755
    *libVer = LIBVIR_VERSION_NUMBER;

756
    if (typeVer != NULL)
757 758
        *typeVer = LIBVIR_VERSION_NUMBER;

759
    return 0;
760

761
 error:
762 763
    virDispatchError(NULL);
    return -1;
764 765
}

766 767 768

static int
virConnectGetDefaultURI(virConfPtr conf,
769
                        char **name)
770
{
771
    const char *defname = getenv("LIBVIRT_DEFAULT_URI");
772 773
    if (defname && *defname) {
        VIR_DEBUG("Using LIBVIRT_DEFAULT_URI '%s'", defname);
774
        *name = g_strdup(defname);
775 776
    } else {
        if (virConfGetValueString(conf, "uri_default", name) < 0)
777
            return -1;
778 779 780

        if (*name)
            VIR_DEBUG("Using config file uri '%s'", *name);
781 782
    }

783
    return 0;
784 785
}

786

787 788 789 790 791 792 793
/*
 * 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)
{
794
    if (!uri->path || !uri->server)
795 796
        return 0;

797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815
    /* 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;
}


816
static virConnectPtr
817 818 819
virConnectOpenInternal(const char *name,
                       virConnectAuthPtr auth,
                       unsigned int flags)
820
{
821 822
    size_t i;
    int res;
823
    virConnectPtr ret;
J
Ján Tomko 已提交
824
    g_autoptr(virConf) conf = NULL;
825
    char *uristr = NULL;
826 827 828 829

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

831
    if (virConfLoadConfig(&conf, "libvirt.conf") < 0)
832 833 834 835 836
        goto failed;

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

837
    /* Convert xen -> xen:///system for back compat */
838
    if (name && STRCASEEQ(name, "xen"))
839
        name = "xen:///system";
840

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

847
    /*
E
Eric Blake 已提交
848 849 850
     * 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.
851
     */
852
    if (name) {
853
        uristr = g_strdup(name);
854 855 856
    } else {
        if (virConnectGetDefaultURI(conf, &uristr) < 0)
            goto failed;
857 858 859 860 861 862 863 864 865

        if (uristr == NULL) {
            VIR_DEBUG("Trying to probe for default URI");
            for (i = 0; i < virConnectDriverTabCount && uristr == NULL; i++) {
                if (virConnectDriverTab[i]->hypervisorDriver->connectURIProbe) {
                    if (virConnectDriverTab[i]->hypervisorDriver->connectURIProbe(&uristr) < 0)
                        goto failed;
                    VIR_DEBUG("%s driver URI probe returned '%s'",
                              virConnectDriverTab[i]->hypervisorDriver->name,
866
                              NULLSTR(uristr));
867 868 869
                }
            }
        }
870
    }
871

872 873
    if (uristr) {
        char *alias = NULL;
874

875
        if (!(flags & VIR_CONNECT_NO_ALIASES) &&
876
            virURIResolveAlias(conf, uristr, &alias) < 0)
877 878
            goto failed;

879 880 881 882 883 884
        if (alias) {
            VIR_FREE(uristr);
            uristr = alias;
        }

        if (!(ret->uri = virURIParse(uristr))) {
885
            VIR_FREE(alias);
886 887
            goto failed;
        }
888

889 890
        /* Avoid need for drivers to worry about NULLs, as
         * no one needs to distinguish "" vs NULL */
891 892
        if (ret->uri->path == NULL)
            ret->uri->path = g_strdup("");
893

894
        VIR_DEBUG("Split \"%s\" to URI components:\n"
895 896 897 898
                  "  scheme %s\n"
                  "  server %s\n"
                  "  user %s\n"
                  "  port %d\n"
J
Jiri Denemark 已提交
899
                  "  path %s",
900
                  uristr,
901
                  NULLSTR(ret->uri->scheme), NULLSTR(ret->uri->server),
902
                  NULLSTR(ret->uri->user), ret->uri->port,
903
                  ret->uri->path);
904

905 906 907 908 909 910 911
        if (ret->uri->scheme == NULL) {
            virReportError(VIR_ERR_NO_CONNECT,
                           _("URI '%s' does not include a driver name"),
                           name);
            goto failed;
        }

912
        if (virConnectCheckURIMissingSlash(uristr,
913 914 915
                                           ret->uri) < 0) {
            goto failed;
        }
916
    } else {
917
        VIR_DEBUG("no name, allowing driver auto-select");
918 919
    }

920 921 922
    /* Cleansing flags */
    ret->flags = flags & VIR_CONNECT_RO;

923
    for (i = 0; i < virConnectDriverTabCount; i++) {
924 925 926 927 928 929 930
        /* 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. */
931
        if (STREQ(virConnectDriverTab[i]->hypervisorDriver->name, "remote") &&
932
            ret->uri != NULL &&
933 934
            (
#ifndef WITH_ESX
935
             STRCASEEQ(ret->uri->scheme, "vpx") ||
936 937
             STRCASEEQ(ret->uri->scheme, "esx") ||
             STRCASEEQ(ret->uri->scheme, "gsx") ||
M
Matthias Bolte 已提交
938 939 940
#endif
#ifndef WITH_HYPERV
             STRCASEEQ(ret->uri->scheme, "hyperv") ||
D
Dmitry Guryanov 已提交
941
#endif
942
#ifndef WITH_VZ
D
Dmitry Guryanov 已提交
943
             STRCASEEQ(ret->uri->scheme, "parallels") ||
944 945
#endif
             false)) {
946
            virReportErrorHelper(VIR_FROM_NONE, VIR_ERR_CONFIG_UNSUPPORTED,
947 948 949 950 951 952
                                 __FILE__, __FUNCTION__, __LINE__,
                                 _("libvirt was built without the '%s' driver"),
                                 ret->uri->scheme);
            goto failed;
        }

953 954 955
        VIR_DEBUG("trying driver %zu (%s) ...",
                  i, virConnectDriverTab[i]->hypervisorDriver->name);

956 957 958 959 960
        if (virConnectDriverTab[i]->localOnly && ret->uri && ret->uri->server) {
            VIR_DEBUG("Server present, skipping local only driver");
            continue;
        }

961
        /* Filter drivers based on declared URI schemes */
962
        if (virConnectDriverTab[i]->uriSchemes) {
963 964
            bool matchScheme = false;
            size_t s;
965 966 967 968
            if (!ret->uri) {
                VIR_DEBUG("No URI, skipping driver with URI whitelist");
                continue;
            }
969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984
            VIR_DEBUG("Checking for supported URI schemes");
            for (s = 0; virConnectDriverTab[i]->uriSchemes[s] != NULL; s++) {
                if (STREQ(ret->uri->scheme, virConnectDriverTab[i]->uriSchemes[s])) {
                    VIR_DEBUG("Matched URI scheme '%s'", ret->uri->scheme);
                    matchScheme = true;
                    break;
                }
            }
            if (!matchScheme) {
                VIR_DEBUG("No matching URI scheme");
                continue;
            }
        } else {
            VIR_DEBUG("Matching any URI scheme for '%s'", ret->uri ? ret->uri->scheme : "");
        }

985 986 987 988 989 990 991
        /* before starting the new connection, check if the driver only works
         * with a server, and so return an error if the server is missing */
        if (virConnectDriverTab[i]->remoteOnly && ret->uri && !ret->uri->server) {
            virReportError(VIR_ERR_INVALID_ARG, "%s", _("URI is missing the server part"));
            goto failed;
        }

992 993 994 995 996 997 998 999
        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;

1000
        res = virConnectDriverTab[i]->hypervisorDriver->connectOpen(ret, auth, conf, flags);
1001
        VIR_DEBUG("driver %zu %s returned %s",
1002
                  i, virConnectDriverTab[i]->hypervisorDriver->name,
O
Osier Yang 已提交
1003 1004 1005 1006 1007
                  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) {
1008
            break;
1009 1010
        } else {
            ret->driver = NULL;
1011 1012 1013 1014 1015 1016 1017 1018 1019
            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;
1020
        }
1021 1022
    }

1023
    if (!ret->driver) {
1024
        /* If we reach here, then all drivers declined the connection. */
1025
        virReportError(VIR_ERR_NO_CONNECT, "%s", NULLSTR(name));
1026
        goto failed;
1027 1028
    }

1029
    VIR_FREE(uristr);
1030

1031
    return ret;
1032

1033
 failed:
1034
    VIR_FREE(uristr);
1035
    virObjectUnref(ret);
1036

1037
    return NULL;
1038 1039
}

1040

1041 1042
/**
 * virConnectOpen:
1043
 * @name: (optional) URI of the hypervisor
1044
 *
1045
 * This function should be called first to get a connection to the
1046 1047
 * Hypervisor and xen store
 *
1048 1049 1050 1051 1052
 * 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.
1053 1054 1055 1056 1057 1058
 *
 * 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
 *
C
Chen Hanxiao 已提交
1059
 * URIs are documented at https://libvirt.org/uri.html
E
Eric Blake 已提交
1060
 *
1061 1062 1063
 * virConnectClose should be used to release the resources after the connection
 * is no longer needed.
 *
E
Eric Blake 已提交
1064
 * Returns a pointer to the hypervisor connection or NULL in case of error
1065 1066
 */
virConnectPtr
1067
virConnectOpen(const char *name)
1068
{
1069
    virConnectPtr ret = NULL;
1070 1071 1072

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

1074
    VIR_DEBUG("name=%s", NULLSTR(name));
1075
    virResetLastError();
1076
    ret = virConnectOpenInternal(name, NULL, 0);
1077 1078 1079 1080
    if (!ret)
        goto error;
    return ret;

1081
 error:
1082 1083
    virDispatchError(NULL);
    return NULL;
1084 1085
}

1086

1087
/**
1088
 * virConnectOpenReadOnly:
1089
 * @name: (optional) URI of the hypervisor
1090
 *
1091
 * This function should be called first to get a restricted connection to the
D
Daniel Veillard 已提交
1092
 * library functionalities. The set of APIs usable are then restricted
1093
 * on the available methods to control the domains.
1094
 *
1095
 * See virConnectOpen for notes about environment variables which can
1096
 * have an effect on opening drivers and freeing the connection resources
1097
 *
1098
 * URIs are documented at https://libvirt.org/uri.html
E
Eric Blake 已提交
1099 1100
 *
 * Returns a pointer to the hypervisor connection or NULL in case of error
1101
 */
1102
virConnectPtr
1103 1104
virConnectOpenReadOnly(const char *name)
{
1105
    virConnectPtr ret = NULL;
1106 1107 1108

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

1110
    VIR_DEBUG("name=%s", NULLSTR(name));
1111
    virResetLastError();
1112
    ret = virConnectOpenInternal(name, NULL, VIR_CONNECT_RO);
1113 1114 1115 1116
    if (!ret)
        goto error;
    return ret;

1117
 error:
1118 1119
    virDispatchError(NULL);
    return NULL;
1120 1121
}

1122

1123 1124
/**
 * virConnectOpenAuth:
1125
 * @name: (optional) URI of the hypervisor
1126
 * @auth: Authenticate callback parameters
1127
 * @flags: bitwise-OR of virConnectFlags
1128
 *
1129
 * This function should be called first to get a connection to the
1130
 * Hypervisor. If necessary, authentication will be performed fetching
1131 1132
 * credentials via the callback
 *
1133
 * See virConnectOpen for notes about environment variables which can
1134
 * have an effect on opening drivers and freeing the connection resources
1135
 *
1136
 * URIs are documented at https://libvirt.org/uri.html
E
Eric Blake 已提交
1137 1138
 *
 * Returns a pointer to the hypervisor connection or NULL in case of error
1139 1140 1141 1142
 */
virConnectPtr
virConnectOpenAuth(const char *name,
                   virConnectAuthPtr auth,
1143
                   unsigned int flags)
1144
{
1145
    virConnectPtr ret = NULL;
1146 1147 1148

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

1150
    VIR_DEBUG("name=%s, auth=%p, flags=0x%x", NULLSTR(name), auth, flags);
1151
    virResetLastError();
1152
    ret = virConnectOpenInternal(name, auth, flags);
1153 1154 1155 1156
    if (!ret)
        goto error;
    return ret;

1157
 error:
1158 1159
    virDispatchError(NULL);
    return NULL;
D
Daniel Veillard 已提交
1160 1161
}

1162

1163

D
Daniel Veillard 已提交
1164
/**
1165
 * virConnectClose:
D
Daniel Veillard 已提交
1166 1167 1168 1169 1170 1171 1172
 * @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.
 *
1173 1174 1175 1176 1177 1178 1179 1180
 * 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.
 *
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190
 * 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 已提交
1191 1192
 */
int
1193 1194
virConnectClose(virConnectPtr conn)
{
1195
    VIR_DEBUG("conn=%p", conn);
1196

1197 1198
    virResetLastError();

1199
    virCheckConnectReturn(conn, -1);
1200

1201 1202 1203
    if (!virObjectUnref(conn))
        return 0;
    return 1;
D
Daniel Veillard 已提交
1204 1205
}

1206

1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
/* 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;
}