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
#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

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

34
#ifdef HAVE_WINSOCK2_H
35
# include <winsock2.h>
36
#endif
37

38
#ifdef WITH_CURL
39 40 41
# include <curl/curl.h>
#endif

42
#include "virerror.h"
43
#include "virlog.h"
44
#include "datatypes.h"
45
#include "driver.h"
46

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

63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
#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
R
Roman Bogorodskiy 已提交
84 85 86
#ifdef WITH_BHYVE
# include "bhyve/bhyve_driver.h"
#endif
87

88 89
#define VIR_FROM_THIS VIR_FROM_NONE

90 91
VIR_LOG_INIT("libvirt");

D
Daniel Veillard 已提交
92 93 94
/*
 * TODO:
 * - use lock to protect against concurrent accesses ?
D
Daniel Veillard 已提交
95
 * - use reference counting to guarantee coherent pointer state ?
D
Daniel Veillard 已提交
96 97
 */

98
#define MAX_DRIVERS 21
99

100 101
static virConnectDriverPtr virConnectDriverTab[MAX_DRIVERS];
static int virConnectDriverTabCount;
102
static virStateDriverPtr virStateDriverTab[MAX_DRIVERS];
103
static int virStateDriverTabCount;
104

105 106 107 108 109 110 111
static virNetworkDriverPtr virSharedNetworkDriver;
static virInterfaceDriverPtr virSharedInterfaceDriver;
static virStorageDriverPtr virSharedStorageDriver;
static virNodeDeviceDriverPtr virSharedNodeDeviceDriver;
static virSecretDriverPtr virSharedSecretDriver;
static virNWFilterDriverPtr virSharedNWFilterDriver;

112

113 114 115
static int
virConnectAuthCallbackDefault(virConnectCredentialPtr cred,
                              unsigned int ncred,
J
Ján Tomko 已提交
116
                              void *cbdata G_GNUC_UNUSED)
117
{
118
    size_t i;
119

120
    for (i = 0; i < ncred; i++) {
121 122
        char buf[1024];
        char *bufptr = buf;
123
        size_t len;
124 125

        switch (cred[i].type) {
126 127 128 129
        case VIR_CRED_EXTERNAL: {
            if (STRNEQ(cred[i].challenge, "PolicyKit"))
                return -1;

130 131 132 133 134
            /*
             * Ignore & carry on. Although we can't auth
             * directly, the user may have authenticated
             * themselves already outside context of libvirt
             */
135 136
            break;
        }
137

138 139 140 141
        case VIR_CRED_USERNAME:
        case VIR_CRED_AUTHNAME:
        case VIR_CRED_ECHOPROMPT:
        case VIR_CRED_REALM:
142
            if (printf("%s: ", cred[i].prompt) < 0)
143 144 145 146
                return -1;
            if (fflush(stdout) != 0)
                return -1;

147 148 149 150 151 152 153
            if (!fgets(buf, sizeof(buf), stdin)) {
                if (feof(stdin)) { /* Treat EOF as "" */
                    buf[0] = '\0';
                    break;
                }
                return -1;
            }
154 155 156
            len = strlen(buf);
            if (len != 0 && buf[len-1] == '\n')
                buf[len-1] = '\0';
157 158 159 160
            break;

        case VIR_CRED_PASSPHRASE:
        case VIR_CRED_NOECHOPROMPT:
161
            if (printf("%s: ", cred[i].prompt) < 0)
162 163 164 165
                return -1;
            if (fflush(stdout) != 0)
                return -1;

166 167 168 169
            bufptr = getpass("");
            if (!bufptr)
                return -1;
            break;
170 171 172

        default:
            return -1;
173 174
        }

D
Daniel P. Berrange 已提交
175
        if (cred[i].type != VIR_CRED_EXTERNAL) {
176
            cred[i].result = g_strdup(STREQ(bufptr, "") && cred[i].defresult ? cred[i].defresult : bufptr);
D
Daniel P. Berrange 已提交
177 178
            cred[i].resultlen = strlen(cred[i].result);
        }
179 180 181 182 183
    }

    return 0;
}

184

185 186 187 188 189 190 191 192 193 194
/* 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,
195
    VIR_CRED_EXTERNAL,
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
};

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;

217 218
#if HAVE_WINSOCK2_H
static int
219
virWinsockInit(void)
220 221 222 223 224
{
    WORD winsock_version, err;
    WSADATA winsock_data;

    /* http://msdn2.microsoft.com/en-us/library/ms742213.aspx */
225 226
    winsock_version = MAKEWORD(2, 2);
    err = WSAStartup(winsock_version, &winsock_data);
J
Jim Meyering 已提交
227
    return err == 0 ? 0 : -1;
228 229 230
}
#endif

231

232
static bool virGlobalError;
233
static virOnceControl virGlobalOnce = VIR_ONCE_CONTROL_INITIALIZER;
234

235 236 237
static void
virGlobalInit(void)
{
238 239 240 241 242
    /* 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.  */
243
    if (virErrorInitialize() < 0)
244
        goto error;
245

246 247
    virFileActivateDirOverrideForLib();

248 249
    if (getuid() != geteuid() ||
        getgid() != getegid()) {
250
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
251
                       _("libvirt.so is not safe to use from setuid/setgid programs"));
252 253 254
        goto error;
    }

255
    virLogSetFromEnv();
256

257
#ifdef WITH_GNUTLS
258
    virNetTLSInit();
259
#endif
260

261
#if WITH_CURL
262 263 264
    curl_global_init(CURL_GLOBAL_DEFAULT);
#endif

265
    VIR_DEBUG("register drivers");
266

267
#if HAVE_WINSOCK2_H
268
    if (virWinsockInit() == -1)
269
        goto error;
270 271
#endif

272
#ifdef HAVE_LIBINTL_H
273
    if (!bindtextdomain(PACKAGE, LOCALEDIR))
274
        goto error;
275
#endif /* HAVE_LIBINTL_H */
276

277
    /*
278 279
     * Note that the order is important: the first ones have a higher
     * priority when calling virConnectOpen.
280
     */
281
#ifdef WITH_TEST
282 283
    if (testRegister() == -1)
        goto error;
284 285
#endif
#ifdef WITH_OPENVZ
286 287
    if (openvzRegister() == -1)
        goto error;
288 289
#endif
#ifdef WITH_VMWARE
290 291
    if (vmwareRegister() == -1)
        goto error;
292 293
#endif
#ifdef WITH_PHYP
294 295
    if (phypRegister() == -1)
        goto error;
296 297
#endif
#ifdef WITH_ESX
298 299
    if (esxRegister() == -1)
        goto error;
300 301
#endif
#ifdef WITH_HYPERV
302 303
    if (hypervRegister() == -1)
        goto error;
304
#endif
305
#ifdef WITH_REMOTE
306
    if (remoteRegister() == -1)
307
        goto error;
308
#endif
D
Daniel P. Berrange 已提交
309

310 311
    return;

312
 error:
313 314 315
    virGlobalError = true;
}

316

317 318 319 320 321
/**
 * virInitialize:
 *
 * Initialize the library.
 *
322 323 324 325 326 327
 * 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.
328
 *
329 330 331 332 333
 * 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.
334 335 336 337 338 339 340 341 342 343 344
 *
 * 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;
345
    return 0;
346 347
}

348

349 350
#ifdef WIN32
BOOL WINAPI
351
DllMain(HINSTANCE instance, DWORD reason, LPVOID ignore);
352 353

BOOL WINAPI
J
Ján Tomko 已提交
354
DllMain(HINSTANCE instance G_GNUC_UNUSED,
355
        DWORD reason,
J
Ján Tomko 已提交
356
        LPVOID ignore G_GNUC_UNUSED)
357 358 359 360 361 362 363 364
{
    switch (reason) {
    case DLL_PROCESS_ATTACH:
        virInitialize();
        break;

    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
365
        /* Nothing todo in libvirt yet */
366 367 368 369 370 371 372 373 374 375 376 377
        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
378

379

380
/**
381
 * virSetSharedNetworkDriver:
382 383 384 385
 * @driver: pointer to a network driver block
 *
 * Register a network virtualization driver
 *
386
 * Returns 0 on success, or -1 in case of error.
387 388
 */
int
389
virSetSharedNetworkDriver(virNetworkDriverPtr driver)
390
{
391
    virCheckNonNullArgReturn(driver, -1);
392

393 394 395 396 397 398 399
    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);
400

401 402
    virSharedNetworkDriver = driver;
    return 0;
403 404
}

405

D
Daniel Veillard 已提交
406
/**
407
 * virSetSharedInterfaceDriver:
L
Laine Stump 已提交
408
 * @driver: pointer to an interface driver block
D
Daniel Veillard 已提交
409
 *
L
Laine Stump 已提交
410
 * Register an interface virtualization driver
D
Daniel Veillard 已提交
411 412 413 414
 *
 * Returns the driver priority or -1 in case of error.
 */
int
415
virSetSharedInterfaceDriver(virInterfaceDriverPtr driver)
D
Daniel Veillard 已提交
416
{
417
    virCheckNonNullArgReturn(driver, -1);
D
Daniel Veillard 已提交
418

419 420 421 422 423
    if (virSharedInterfaceDriver) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("A interface driver is already registered"));
        return -1;
    }
D
Daniel Veillard 已提交
424

425 426 427 428
    VIR_DEBUG("registering %s as interface driver", driver->name);

    virSharedInterfaceDriver = driver;
    return 0;
D
Daniel Veillard 已提交
429 430
}

431

432
/**
433
 * virSetSharedStorageDriver:
434 435 436 437 438 439 440
 * @driver: pointer to a storage driver block
 *
 * Register a storage virtualization driver
 *
 * Returns the driver priority or -1 in case of error.
 */
int
441
virSetSharedStorageDriver(virStorageDriverPtr driver)
442
{
443
    virCheckNonNullArgReturn(driver, -1);
444

445 446 447 448 449 450 451
    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);
452

453 454
    virSharedStorageDriver = driver;
    return 0;
455 456
}

457

458
/**
459
 * virSetSharedNodeDeviceDriver:
460 461 462 463 464 465 466
 * @driver: pointer to a device monitor block
 *
 * Register a device monitor
 *
 * Returns the driver priority or -1 in case of error.
 */
int
467
virSetSharedNodeDeviceDriver(virNodeDeviceDriverPtr driver)
468
{
469
    virCheckNonNullArgReturn(driver, -1);
470

471 472 473 474 475
    if (virSharedNodeDeviceDriver) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("A node device driver is already registered"));
        return -1;
    }
476

477 478 479 480
    VIR_DEBUG("registering %s as device driver", driver->name);

    virSharedNodeDeviceDriver = driver;
    return 0;
481 482
}

483

484
/**
485
 * virSetSharedSecretDriver:
486 487 488 489 490 491 492
 * @driver: pointer to a secret driver block
 *
 * Register a secret driver
 *
 * Returns the driver priority or -1 in case of error.
 */
int
493
virSetSharedSecretDriver(virSecretDriverPtr driver)
494
{
495
    virCheckNonNullArgReturn(driver, -1);
496

497 498 499 500 501 502 503
    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);
504

505 506
    virSharedSecretDriver = driver;
    return 0;
507 508
}

509

S
Stefan Berger 已提交
510
/**
511
 * virSetSharedNWFilterDriver:
S
Stefan Berger 已提交
512 513 514 515 516 517 518
 * @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
519
virSetSharedNWFilterDriver(virNWFilterDriverPtr driver)
S
Stefan Berger 已提交
520
{
521
    virCheckNonNullArgReturn(driver, -1);
S
Stefan Berger 已提交
522

523 524 525 526 527
    if (virSharedNWFilterDriver) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("A network filter driver is already registered"));
        return -1;
    }
S
Stefan Berger 已提交
528

529 530 531 532
    VIR_DEBUG("registering %s as network filter driver", driver->name);

    virSharedNWFilterDriver = driver;
    return 0;
S
Stefan Berger 已提交
533 534 535
}


536
/**
537
 * virRegisterConnectDriver:
538
 * @driver: pointer to a driver block
539
 * @setSharedDrivers: populate shared drivers
540
 *
541 542
 * Register a virtualization driver, optionally filling in
 * any empty pointers for shared secondary drivers
543 544 545 546
 *
 * Returns the driver priority or -1 in case of error.
 */
int
547 548
virRegisterConnectDriver(virConnectDriverPtr driver,
                         bool setSharedDrivers)
549
{
550
    VIR_DEBUG("driver=%p name=%s", driver,
551
              driver ? NULLSTR(driver->hypervisorDriver->name) : "(null)");
552

553
    virCheckNonNullArgReturn(driver, -1);
554 555 556 557 558 559
    if (virConnectDriverTabCount >= MAX_DRIVERS) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Too many drivers, cannot register %s"),
                       driver->hypervisorDriver->name);
        return -1;
    }
560

561
    VIR_DEBUG("registering %s as driver %d",
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
           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;
    }
578

579 580
    virConnectDriverTab[virConnectDriverTabCount] = driver;
    return virConnectDriverTabCount++;
581 582
}

583

584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
/**
 * 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;
}

611 612 613 614 615 616 617 618 619 620 621
/**
 * 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)
{
622
    virCheckNonNullArgReturn(driver, -1);
623 624 625 626 627 628 629

    if (virStateDriverTabCount >= MAX_DRIVERS) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Too many drivers, cannot register %s"),
                       driver->name);
        return -1;
    }
630 631 632 633 634

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

635

636 637
/**
 * virStateInitialize:
638
 * @privileged: set to true if running with root privilege, false otherwise
639
 * @mandatory: set to true if all drivers must report success, not skipped
640 641
 * @callback: callback to invoke to inhibit shutdown of the daemon
 * @opaque: data to pass to @callback
642
 *
643
 * Initialize all virtualization drivers.
644
 *
645
 * Returns 0 if all succeed, -1 upon any failure.
646
 */
647 648
int
virStateInitialize(bool privileged,
649
                   bool mandatory,
650 651
                   virStateInhibitCallback callback,
                   void *opaque)
652
{
653
    size_t i;
654 655 656 657

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

658
    for (i = 0; i < virStateDriverTabCount; i++) {
659
        if (virStateDriverTab[i]->stateInitialize) {
660
            virDrvStateInitResult ret;
661
            VIR_DEBUG("Running global init for %s state driver",
662
                      virStateDriverTab[i]->name);
663 664 665 666 667
            ret = virStateDriverTab[i]->stateInitialize(privileged,
                                                        callback,
                                                        opaque);
            VIR_DEBUG("State init result %d (mandatory=%d)", ret, mandatory);
            if (ret == VIR_DRV_STATE_INIT_ERROR) {
668 669
                VIR_ERROR(_("Initialization of %s state driver failed: %s"),
                          virStateDriverTab[i]->name,
670
                          virGetLastErrorMessage());
671
                return -1;
672 673 674 675
            } else if (ret == VIR_DRV_STATE_INIT_SKIPPED && mandatory) {
                VIR_ERROR(_("Initialization of mandatory %s state driver skipped"),
                          virStateDriverTab[i]->name);
                return -1;
676
            }
677
        }
678
    }
679
    return 0;
680 681
}

682

683 684 685 686 687
/**
 * virStateCleanup:
 *
 * Run each virtualization driver's cleanup method.
 *
688
 * Returns 0 if all succeed, -1 upon any failure.
689
 */
690 691 692
int
virStateCleanup(void)
{
693
    int r;
694
    int ret = 0;
695

696 697 698
    for (r = virStateDriverTabCount - 1; r >= 0; r--) {
        if (virStateDriverTab[r]->stateCleanup &&
            virStateDriverTab[r]->stateCleanup() < 0)
699 700 701 702 703
            ret = -1;
    }
    return ret;
}

704

705 706 707 708 709
/**
 * virStateReload:
 *
 * Run each virtualization driver's reload method.
 *
710
 * Returns 0 if all succeed, -1 upon any failure.
711
 */
712 713 714
int
virStateReload(void)
{
715 716
    size_t i;
    int ret = 0;
717

718
    for (i = 0; i < virStateDriverTabCount; i++) {
719 720
        if (virStateDriverTab[i]->stateReload &&
            virStateDriverTab[i]->stateReload() < 0)
721 722 723 724 725
            ret = -1;
    }
    return ret;
}

726

727 728 729 730 731 732 733
/**
 * virStateStop:
 *
 * Run each virtualization driver's "stop" method.
 *
 * Returns 0 if successful, -1 on failure
 */
734 735 736
int
virStateStop(void)
{
737 738
    size_t i;
    int ret = 0;
739

740
    for (i = 0; i < virStateDriverTabCount; i++) {
741 742
        if (virStateDriverTab[i]->stateStop &&
            virStateDriverTab[i]->stateStop())
743 744 745 746
            ret = 1;
    }
    return ret;
}
747 748


749 750 751
/**
 * virGetVersion:
 * @libVer: return value for the library version (OUT)
752 753 754 755 756 757 758 759 760 761
 * @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
762
 * get the version of the running hypervisor use the virConnectGetVersion()
763
 * function instead. To get the libvirt library version used by a
764 765 766
 * connection use the virConnectGetLibVersion() instead.
 *
 * This function includes a call to virInitialize() when necessary.
767 768 769 770 771
 *
 * 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 已提交
772
virGetVersion(unsigned long *libVer, const char *type G_GNUC_UNUSED,
773 774
              unsigned long *typeVer)
{
775 776
    if (virInitialize() < 0)
        goto error;
777
    VIR_DEBUG("libVir=%p, type=%s, typeVer=%p", libVer, type, typeVer);
778

779
    virResetLastError();
780
    if (libVer == NULL)
781
        goto error;
782 783
    *libVer = LIBVIR_VERSION_NUMBER;

784
    if (typeVer != NULL)
785 786
        *typeVer = LIBVIR_VERSION_NUMBER;

787
    return 0;
788

789
 error:
790 791
    virDispatchError(NULL);
    return -1;
792 793
}

794 795 796

static int
virConnectGetDefaultURI(virConfPtr conf,
797
                        char **name)
798 799
{
    int ret = -1;
800
    const char *defname = getenv("LIBVIRT_DEFAULT_URI");
801 802
    if (defname && *defname) {
        VIR_DEBUG("Using LIBVIRT_DEFAULT_URI '%s'", defname);
803
        *name = g_strdup(defname);
804 805 806 807 808 809
    } else {
        if (virConfGetValueString(conf, "uri_default", name) < 0)
            goto cleanup;

        if (*name)
            VIR_DEBUG("Using config file uri '%s'", *name);
810 811 812
    }

    ret = 0;
813
 cleanup:
814 815 816
    return ret;
}

817

818 819 820 821 822 823 824
/*
 * 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)
{
825
    if (!uri->path || !uri->server)
826 827
        return 0;

828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846
    /* 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;
}


847
static virConnectPtr
848 849 850
virConnectOpenInternal(const char *name,
                       virConnectAuthPtr auth,
                       unsigned int flags)
851
{
852 853
    size_t i;
    int res;
854
    virConnectPtr ret;
J
Ján Tomko 已提交
855
    g_autoptr(virConf) conf = NULL;
856
    char *uristr = NULL;
857 858 859 860

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

862
    if (virConfLoadConfig(&conf, "libvirt.conf") < 0)
863 864 865 866 867
        goto failed;

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

868
    /* Convert xen -> xen:///system for back compat */
869
    if (name && STRCASEEQ(name, "xen"))
870
        name = "xen:///system";
871

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

878
    /*
E
Eric Blake 已提交
879 880 881
     * 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.
882
     */
883
    if (name) {
884
        uristr = g_strdup(name);
885 886 887
    } else {
        if (virConnectGetDefaultURI(conf, &uristr) < 0)
            goto failed;
888 889 890 891 892 893 894 895 896

        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,
897
                              NULLSTR(uristr));
898 899 900
                }
            }
        }
901
    }
902

903 904
    if (uristr) {
        char *alias = NULL;
905

906
        if (!(flags & VIR_CONNECT_NO_ALIASES) &&
907
            virURIResolveAlias(conf, uristr, &alias) < 0)
908 909
            goto failed;

910 911 912 913 914 915
        if (alias) {
            VIR_FREE(uristr);
            uristr = alias;
        }

        if (!(ret->uri = virURIParse(uristr))) {
916
            VIR_FREE(alias);
917 918
            goto failed;
        }
919

920 921
        /* Avoid need for drivers to worry about NULLs, as
         * no one needs to distinguish "" vs NULL */
922 923
        if (ret->uri->path == NULL)
            ret->uri->path = g_strdup("");
924

925
        VIR_DEBUG("Split \"%s\" to URI components:\n"
926 927 928 929
                  "  scheme %s\n"
                  "  server %s\n"
                  "  user %s\n"
                  "  port %d\n"
J
Jiri Denemark 已提交
930
                  "  path %s",
931
                  uristr,
932
                  NULLSTR(ret->uri->scheme), NULLSTR(ret->uri->server),
933
                  NULLSTR(ret->uri->user), ret->uri->port,
934
                  ret->uri->path);
935

936 937 938 939 940 941 942
        if (ret->uri->scheme == NULL) {
            virReportError(VIR_ERR_NO_CONNECT,
                           _("URI '%s' does not include a driver name"),
                           name);
            goto failed;
        }

943
        if (virConnectCheckURIMissingSlash(uristr,
944 945 946
                                           ret->uri) < 0) {
            goto failed;
        }
947
    } else {
948
        VIR_DEBUG("no name, allowing driver auto-select");
949 950
    }

951 952 953
    /* Cleansing flags */
    ret->flags = flags & VIR_CONNECT_RO;

954
    for (i = 0; i < virConnectDriverTabCount; i++) {
955 956 957 958 959 960 961
        /* 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. */
962
        if (STREQ(virConnectDriverTab[i]->hypervisorDriver->name, "remote") &&
963
            ret->uri != NULL &&
964 965 966 967 968
            (
#ifndef WITH_PHYP
             STRCASEEQ(ret->uri->scheme, "phyp") ||
#endif
#ifndef WITH_ESX
969
             STRCASEEQ(ret->uri->scheme, "vpx") ||
970 971
             STRCASEEQ(ret->uri->scheme, "esx") ||
             STRCASEEQ(ret->uri->scheme, "gsx") ||
M
Matthias Bolte 已提交
972 973 974
#endif
#ifndef WITH_HYPERV
             STRCASEEQ(ret->uri->scheme, "hyperv") ||
D
Dmitry Guryanov 已提交
975
#endif
976
#ifndef WITH_VZ
D
Dmitry Guryanov 已提交
977
             STRCASEEQ(ret->uri->scheme, "parallels") ||
978 979
#endif
             false)) {
980
            virReportErrorHelper(VIR_FROM_NONE, VIR_ERR_CONFIG_UNSUPPORTED,
981 982 983 984 985 986
                                 __FILE__, __FUNCTION__, __LINE__,
                                 _("libvirt was built without the '%s' driver"),
                                 ret->uri->scheme);
            goto failed;
        }

987 988 989
        VIR_DEBUG("trying driver %zu (%s) ...",
                  i, virConnectDriverTab[i]->hypervisorDriver->name);

990 991 992 993 994
        if (virConnectDriverTab[i]->localOnly && ret->uri && ret->uri->server) {
            VIR_DEBUG("Server present, skipping local only driver");
            continue;
        }

995
        /* Filter drivers based on declared URI schemes */
996
        if (virConnectDriverTab[i]->uriSchemes) {
997 998
            bool matchScheme = false;
            size_t s;
999 1000 1001 1002
            if (!ret->uri) {
                VIR_DEBUG("No URI, skipping driver with URI whitelist");
                continue;
            }
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
            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 : "");
        }

1019 1020 1021 1022 1023 1024 1025
        /* 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;
        }

1026 1027 1028 1029 1030 1031 1032 1033
        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;

1034
        res = virConnectDriverTab[i]->hypervisorDriver->connectOpen(ret, auth, conf, flags);
1035
        VIR_DEBUG("driver %zu %s returned %s",
1036
                  i, virConnectDriverTab[i]->hypervisorDriver->name,
O
Osier Yang 已提交
1037 1038 1039 1040 1041
                  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) {
1042
            break;
1043 1044
        } else {
            ret->driver = NULL;
1045 1046 1047 1048 1049 1050 1051 1052 1053
            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;
1054
        }
1055 1056
    }

1057
    if (!ret->driver) {
1058
        /* If we reach here, then all drivers declined the connection. */
1059
        virReportError(VIR_ERR_NO_CONNECT, "%s", NULLSTR(name));
1060
        goto failed;
1061 1062
    }

1063
    VIR_FREE(uristr);
1064

1065
    return ret;
1066

1067
 failed:
1068
    VIR_FREE(uristr);
1069
    virObjectUnref(ret);
1070

1071
    return NULL;
1072 1073
}

1074

1075 1076
/**
 * virConnectOpen:
1077
 * @name: (optional) URI of the hypervisor
1078
 *
1079
 * This function should be called first to get a connection to the
1080 1081
 * Hypervisor and xen store
 *
1082 1083 1084 1085 1086
 * 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.
1087 1088 1089 1090 1091 1092
 *
 * 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 已提交
1093
 * URIs are documented at https://libvirt.org/uri.html
E
Eric Blake 已提交
1094
 *
1095 1096 1097
 * virConnectClose should be used to release the resources after the connection
 * is no longer needed.
 *
E
Eric Blake 已提交
1098
 * Returns a pointer to the hypervisor connection or NULL in case of error
1099 1100
 */
virConnectPtr
1101
virConnectOpen(const char *name)
1102
{
1103
    virConnectPtr ret = NULL;
1104 1105 1106

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

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

1115
 error:
1116 1117
    virDispatchError(NULL);
    return NULL;
1118 1119
}

1120

1121
/**
1122
 * virConnectOpenReadOnly:
1123
 * @name: (optional) URI of the hypervisor
1124
 *
1125
 * This function should be called first to get a restricted connection to the
D
Daniel Veillard 已提交
1126
 * library functionalities. The set of APIs usable are then restricted
1127
 * on the available methods to control the domains.
1128
 *
1129
 * See virConnectOpen for notes about environment variables which can
1130
 * have an effect on opening drivers and freeing the connection resources
1131
 *
1132
 * URIs are documented at https://libvirt.org/uri.html
E
Eric Blake 已提交
1133 1134
 *
 * Returns a pointer to the hypervisor connection or NULL in case of error
1135
 */
1136
virConnectPtr
1137 1138
virConnectOpenReadOnly(const char *name)
{
1139
    virConnectPtr ret = NULL;
1140 1141 1142

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

1144
    VIR_DEBUG("name=%s", NULLSTR(name));
1145
    virResetLastError();
1146
    ret = virConnectOpenInternal(name, NULL, VIR_CONNECT_RO);
1147 1148 1149 1150
    if (!ret)
        goto error;
    return ret;

1151
 error:
1152 1153
    virDispatchError(NULL);
    return NULL;
1154 1155
}

1156

1157 1158
/**
 * virConnectOpenAuth:
1159
 * @name: (optional) URI of the hypervisor
1160
 * @auth: Authenticate callback parameters
1161
 * @flags: bitwise-OR of virConnectFlags
1162
 *
1163
 * This function should be called first to get a connection to the
1164
 * Hypervisor. If necessary, authentication will be performed fetching
1165 1166
 * credentials via the callback
 *
1167
 * See virConnectOpen for notes about environment variables which can
1168
 * have an effect on opening drivers and freeing the connection resources
1169
 *
1170
 * URIs are documented at https://libvirt.org/uri.html
E
Eric Blake 已提交
1171 1172
 *
 * Returns a pointer to the hypervisor connection or NULL in case of error
1173 1174 1175 1176
 */
virConnectPtr
virConnectOpenAuth(const char *name,
                   virConnectAuthPtr auth,
1177
                   unsigned int flags)
1178
{
1179
    virConnectPtr ret = NULL;
1180 1181 1182

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

1184
    VIR_DEBUG("name=%s, auth=%p, flags=0x%x", NULLSTR(name), auth, flags);
1185
    virResetLastError();
1186
    ret = virConnectOpenInternal(name, auth, flags);
1187 1188 1189 1190
    if (!ret)
        goto error;
    return ret;

1191
 error:
1192 1193
    virDispatchError(NULL);
    return NULL;
D
Daniel Veillard 已提交
1194 1195
}

1196

1197

D
Daniel Veillard 已提交
1198
/**
1199
 * virConnectClose:
D
Daniel Veillard 已提交
1200 1201 1202 1203 1204 1205 1206
 * @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.
 *
1207 1208 1209 1210 1211 1212 1213 1214
 * 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.
 *
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224
 * 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 已提交
1225 1226
 */
int
1227 1228
virConnectClose(virConnectPtr conn)
{
1229
    VIR_DEBUG("conn=%p", conn);
1230

1231 1232
    virResetLastError();

1233
    virCheckConnectReturn(conn, -1);
1234

1235 1236 1237
    if (!virObjectUnref(conn))
        return 0;
    return 1;
D
Daniel Veillard 已提交
1238 1239
}

1240

1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280
/* 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;
}