2 * libvirt.c: Main interfaces for the libvirt library to handle virtualization
3 * domains from a process running in domain 0
5 * Copyright (C) 2005-2006, 2008-2014 Red Hat, Inc.
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library. If not, see
19 * <http://www.gnu.org/licenses/>.
24 #include <sys/types.h>
28 #include <gio/gnetworking.h>
30 #include <libxml/parser.h>
31 #include <libxml/xpath.h>
34 # include <curl/curl.h>
39 #include "datatypes.h"
44 #include "configmake.h"
46 #include "rpc/virnettlscontext.h"
47 #include "vircommand.h"
50 #include "virrandom.h"
52 #include "virthread.h"
53 #include "virstring.h"
55 #include "virtypedparam.h"
58 # include "test/test_driver.h"
61 # include "remote/remote_driver.h"
64 # include "openvz/openvz_driver.h"
67 # include "vmware/vmware_driver.h"
70 # include "esx/esx_driver.h"
73 # include "hyperv/hyperv_driver.h"
76 # include "bhyve/bhyve_driver.h"
78 #include "access/viraccessmanager.h"
80 #define VIR_FROM_THIS VIR_FROM_NONE
82 VIR_LOG_INIT("libvirt");
86 * - use lock to protect against concurrent accesses ?
87 * - use reference counting to guarantee coherent pointer state ?
90 #define MAX_DRIVERS 21
92 static virConnectDriver
*virConnectDriverTab
[MAX_DRIVERS
];
93 static int virConnectDriverTabCount
;
94 static virStateDriver
*virStateDriverTab
[MAX_DRIVERS
];
95 static int virStateDriverTabCount
;
97 static virNetworkDriver
*virSharedNetworkDriver
;
98 static virInterfaceDriver
*virSharedInterfaceDriver
;
99 static virStorageDriver
*virSharedStorageDriver
;
100 static virNodeDeviceDriver
*virSharedNodeDeviceDriver
;
101 static virSecretDriver
*virSharedSecretDriver
;
102 static virNWFilterDriver
*virSharedNWFilterDriver
;
106 virConnectAuthCallbackDefault(virConnectCredentialPtr cred
,
108 void *cbdata G_GNUC_UNUSED
)
112 for (i
= 0; i
< ncred
; i
++) {
117 switch (cred
[i
].type
) {
118 case VIR_CRED_EXTERNAL
: {
119 if (STRNEQ(cred
[i
].challenge
, "PolicyKit"))
123 * Ignore & carry on. Although we can't auth
124 * directly, the user may have authenticated
125 * themselves already outside context of libvirt
130 case VIR_CRED_USERNAME
:
131 case VIR_CRED_AUTHNAME
:
132 case VIR_CRED_ECHOPROMPT
:
134 if (printf("%s: ", cred
[i
].prompt
) < 0)
136 if (fflush(stdout
) != 0)
139 if (!fgets(buf
, sizeof(buf
), stdin
)) {
140 if (feof(stdin
)) { /* Treat EOF as "" */
147 if (len
!= 0 && buf
[len
-1] == '\n')
151 bufptr
= g_strdup(buf
);
154 case VIR_CRED_PASSPHRASE
:
155 case VIR_CRED_NOECHOPROMPT
:
156 if (printf("%s: ", cred
[i
].prompt
) < 0)
158 if (fflush(stdout
) != 0)
161 bufptr
= virGetPassword();
162 if (STREQ(bufptr
, ""))
170 if (cred
[i
].type
!= VIR_CRED_EXTERNAL
) {
171 cred
[i
].result
= bufptr
? bufptr
: g_strdup(cred
[i
].defresult
? cred
[i
].defresult
: "");
172 cred
[i
].resultlen
= strlen(cred
[i
].result
);
180 /* Don't typically want VIR_CRED_USERNAME. It enables you to authenticate
181 * as one user, and act as another. It just results in annoying
182 * prompts for the username twice & is very rarely what you want
184 static int virConnectCredTypeDefault
[] = {
189 VIR_CRED_NOECHOPROMPT
,
193 static virConnectAuth virConnectAuthDefault
= {
194 virConnectCredTypeDefault
,
195 G_N_ELEMENTS(virConnectCredTypeDefault
),
196 virConnectAuthCallbackDefault
,
200 /* Explanation in the header file */
201 virConnectAuthPtr virConnectAuthPtrDefault
= &virConnectAuthDefault
;
203 static bool virGlobalError
;
204 static virOnceControl virGlobalOnce
= VIR_ONCE_CONTROL_INITIALIZER
;
209 /* It would be nice if we could trace the use of this call, to
210 * help diagnose in log files if a user calls something other than
211 * virConnectOpen first. But we can't rely on VIR_DEBUG working
212 * until after initialization is complete, and since this is
213 * one-shot, we never get here again. */
214 if (virErrorInitialize() < 0)
217 /* Make glib initialize its own global state. See more:
219 * https://gitlab.gnome.org/GNOME/glib/-/issues/3034
223 g_ascii_strtoull("0", NULL
, 0);
225 virFileActivateDirOverrideForLib();
227 if (getuid() != geteuid() ||
228 getgid() != getegid()) {
229 virReportError(VIR_ERR_INTERNAL_ERROR
, "%s",
230 _("libvirt.so is not safe to use from setuid/setgid programs"));
234 /* Do this upfront rather than every time a child is spawned. */
235 if (virCloseRangeInit() < 0)
238 if (virLogSetFromEnv() < 0)
244 curl_global_init(CURL_GLOBAL_DEFAULT
);
247 VIR_DEBUG("register drivers");
251 #ifdef WITH_LIBINTL_H
252 if (!bindtextdomain(PACKAGE
, LOCALEDIR
))
254 #endif /* WITH_LIBINTL_H */
257 * Note that the order is important: the first ones have a higher
258 * priority when calling virConnectOpen.
261 if (testRegister() == -1)
265 if (openvzRegister() == -1)
269 if (vmwareRegister() == -1)
273 if (esxRegister() == -1)
277 if (hypervRegister() == -1)
281 if (remoteRegister() == -1)
288 virGlobalError
= true;
295 * Initialize the library.
297 * This method is invoked automatically by any of the virConnectOpen() API
298 * calls, and by virGetVersion(). Since release 1.0.0, there is no need to
299 * call this method even in a multithreaded application, since
300 * initialization is performed in a thread safe manner; but applications
301 * using an older version of the library should manually call this before
302 * setting up competing threads that attempt virConnectOpen in parallel.
304 * The only other time it would be necessary to call virInitialize is if the
305 * application did not invoke virConnectOpen as its first API call, such
306 * as when calling virEventRegisterImpl() before setting up connections,
307 * or when using virSetErrorFunc() to alter error reporting of the first
308 * connection attempt.
310 * Returns 0 in case of success, -1 in case of error
317 if (virOnce(&virGlobalOnce
, virGlobalInit
) < 0 ||
319 virDispatchError(NULL
);
329 DllMain(HINSTANCE instance
, DWORD reason
, LPVOID ignore
);
332 DllMain(HINSTANCE instance G_GNUC_UNUSED
,
334 LPVOID ignore G_GNUC_UNUSED
)
337 case DLL_PROCESS_ATTACH
:
341 case DLL_THREAD_ATTACH
:
342 case DLL_THREAD_DETACH
:
343 /* Nothing todo in libvirt yet */
346 case DLL_PROCESS_DETACH
:
347 /* Don't bother releasing per-thread data
348 since (hopefully) windows cleans up
349 everything on process exit */
359 * virSetSharedNetworkDriver:
360 * @driver: pointer to a network driver block
362 * Register a network virtualization driver
364 * Returns 0 on success, or -1 in case of error.
367 virSetSharedNetworkDriver(virNetworkDriver
*driver
)
369 virCheckNonNullArgReturn(driver
, -1);
371 if (virSharedNetworkDriver
) {
372 virReportError(VIR_ERR_INTERNAL_ERROR
, "%s",
373 _("A network driver is already registered"));
377 VIR_DEBUG("registering %s as network driver", driver
->name
);
379 virSharedNetworkDriver
= driver
;
385 * virSetSharedInterfaceDriver:
386 * @driver: pointer to an interface driver block
388 * Register an interface virtualization driver
390 * Returns the driver priority or -1 in case of error.
393 virSetSharedInterfaceDriver(virInterfaceDriver
*driver
)
395 virCheckNonNullArgReturn(driver
, -1);
397 if (virSharedInterfaceDriver
) {
398 virReportError(VIR_ERR_INTERNAL_ERROR
, "%s",
399 _("A interface driver is already registered"));
403 VIR_DEBUG("registering %s as interface driver", driver
->name
);
405 virSharedInterfaceDriver
= driver
;
411 * virSetSharedStorageDriver:
412 * @driver: pointer to a storage driver block
414 * Register a storage virtualization driver
416 * Returns the driver priority or -1 in case of error.
419 virSetSharedStorageDriver(virStorageDriver
*driver
)
421 virCheckNonNullArgReturn(driver
, -1);
423 if (virSharedStorageDriver
) {
424 virReportError(VIR_ERR_INTERNAL_ERROR
, "%s",
425 _("A storage driver is already registered"));
429 VIR_DEBUG("registering %s as storage driver", driver
->name
);
431 virSharedStorageDriver
= driver
;
437 * virSetSharedNodeDeviceDriver:
438 * @driver: pointer to a device monitor block
440 * Register a device monitor
442 * Returns the driver priority or -1 in case of error.
445 virSetSharedNodeDeviceDriver(virNodeDeviceDriver
*driver
)
447 virCheckNonNullArgReturn(driver
, -1);
449 if (virSharedNodeDeviceDriver
) {
450 virReportError(VIR_ERR_INTERNAL_ERROR
, "%s",
451 _("A node device driver is already registered"));
455 VIR_DEBUG("registering %s as device driver", driver
->name
);
457 virSharedNodeDeviceDriver
= driver
;
463 * virSetSharedSecretDriver:
464 * @driver: pointer to a secret driver block
466 * Register a secret driver
468 * Returns the driver priority or -1 in case of error.
471 virSetSharedSecretDriver(virSecretDriver
*driver
)
473 virCheckNonNullArgReturn(driver
, -1);
475 if (virSharedSecretDriver
) {
476 virReportError(VIR_ERR_INTERNAL_ERROR
, "%s",
477 _("A secret driver is already registered"));
481 VIR_DEBUG("registering %s as secret driver", driver
->name
);
483 virSharedSecretDriver
= driver
;
489 * virSetSharedNWFilterDriver:
490 * @driver: pointer to a network filter driver block
492 * Register a network filter virtualization driver
494 * Returns the driver priority or -1 in case of error.
497 virSetSharedNWFilterDriver(virNWFilterDriver
*driver
)
499 virCheckNonNullArgReturn(driver
, -1);
501 if (virSharedNWFilterDriver
) {
502 virReportError(VIR_ERR_INTERNAL_ERROR
, "%s",
503 _("A network filter driver is already registered"));
507 VIR_DEBUG("registering %s as network filter driver", driver
->name
);
509 virSharedNWFilterDriver
= driver
;
515 * virRegisterConnectDriver:
516 * @driver: pointer to a driver block
517 * @setSharedDrivers: populate shared drivers
519 * Register a virtualization driver, optionally filling in
520 * any empty pointers for shared secondary drivers
522 * Returns the driver priority or -1 in case of error.
525 virRegisterConnectDriver(virConnectDriver
*driver
,
526 bool setSharedDrivers
)
528 VIR_DEBUG("driver=%p name=%s", driver
,
529 driver
? NULLSTR(driver
->hypervisorDriver
->name
) : "(null)");
531 virCheckNonNullArgReturn(driver
, -1);
532 if (virConnectDriverTabCount
>= MAX_DRIVERS
) {
533 virReportError(VIR_ERR_INTERNAL_ERROR
,
534 _("Too many drivers, cannot register %1$s"),
535 driver
->hypervisorDriver
->name
);
539 VIR_DEBUG("registering %s as driver %d",
540 driver
->hypervisorDriver
->name
, virConnectDriverTabCount
);
542 if (setSharedDrivers
) {
543 if (driver
->interfaceDriver
== NULL
)
544 driver
->interfaceDriver
= virSharedInterfaceDriver
;
545 if (driver
->networkDriver
== NULL
)
546 driver
->networkDriver
= virSharedNetworkDriver
;
547 if (driver
->nodeDeviceDriver
== NULL
)
548 driver
->nodeDeviceDriver
= virSharedNodeDeviceDriver
;
549 if (driver
->nwfilterDriver
== NULL
)
550 driver
->nwfilterDriver
= virSharedNWFilterDriver
;
551 if (driver
->secretDriver
== NULL
)
552 driver
->secretDriver
= virSharedSecretDriver
;
553 if (driver
->storageDriver
== NULL
)
554 driver
->storageDriver
= virSharedStorageDriver
;
557 virConnectDriverTab
[virConnectDriverTabCount
] = driver
;
558 return virConnectDriverTabCount
++;
563 * virHasDriverForURIScheme:
564 * @scheme: the URI scheme
566 * Determine if there is a driver registered that explicitly
567 * handles URIs with the scheme @scheme.
569 * Returns: true if a driver is registered
572 virHasDriverForURIScheme(const char *scheme
)
577 for (i
= 0; i
< virConnectDriverTabCount
; i
++) {
578 if (!virConnectDriverTab
[i
]->uriSchemes
)
580 for (j
= 0; virConnectDriverTab
[i
]->uriSchemes
[j
]; j
++) {
581 if (STREQ(virConnectDriverTab
[i
]->uriSchemes
[j
], scheme
))
590 * virRegisterStateDriver:
591 * @driver: pointer to a driver block
593 * Register a virtualization driver
595 * Returns the driver priority or -1 in case of error.
598 virRegisterStateDriver(virStateDriver
*driver
)
600 virCheckNonNullArgReturn(driver
, -1);
602 if (virStateDriverTabCount
>= MAX_DRIVERS
) {
603 virReportError(VIR_ERR_INTERNAL_ERROR
,
604 _("Too many drivers, cannot register %1$s"),
609 virStateDriverTab
[virStateDriverTabCount
] = driver
;
610 return virStateDriverTabCount
++;
615 * virStateInitialize:
616 * @privileged: set to true if running with root privilege, false otherwise
617 * @mandatory: set to true if all drivers must report success, not skipped
618 * @root: directory to use for embedded mode
619 * @monolithic: set to true if running in monolithic mode (daemon is libvirtd)
620 * @callback: callback to invoke to inhibit shutdown of the daemon
621 * @opaque: data to pass to @callback
623 * Initialize all virtualization drivers.
625 * Passing a non-NULL @root instructs the driver to run in embedded mode.
626 * Instead of using the compile time $prefix as the basis for directory
627 * paths, @root should be used instead. In addition any '/libvirt'
628 * component of the paths should be stripped.
630 * eg consider a build with prefix=/usr/local. A driver might use the
633 * /usr/local/etc/libvirt/$DRIVER/
634 * /usr/local/var/lib/libvirt/$DRIVER/
635 * /usr/local/run/libvirt/$DRIVER/
637 * When run with @root, the locations should instead be
640 * @root/var/lib/$DRIVER/
643 * Returns 0 if all succeed, -1 upon any failure.
646 virStateInitialize(bool privileged
,
650 virStateInhibitCallback callback
,
655 if (virInitialize() < 0)
658 for (i
= 0; i
< virStateDriverTabCount
; i
++) {
659 if (virStateDriverTab
[i
]->stateInitialize
&&
660 !virStateDriverTab
[i
]->initialized
) {
661 virDrvStateInitResult ret
;
662 VIR_DEBUG("Running global init for %s state driver",
663 virStateDriverTab
[i
]->name
);
664 virStateDriverTab
[i
]->initialized
= true;
665 ret
= virStateDriverTab
[i
]->stateInitialize(privileged
,
670 VIR_DEBUG("State init result %d (mandatory=%d)", ret
, mandatory
);
671 if (ret
== VIR_DRV_STATE_INIT_ERROR
) {
672 VIR_ERROR(_("Initialization of %1$s state driver failed: %2$s"),
673 virStateDriverTab
[i
]->name
,
674 virGetLastErrorMessage());
677 if (ret
== VIR_DRV_STATE_INIT_SKIPPED
&& mandatory
) {
678 VIR_ERROR(_("Initialization of mandatory %1$s state driver skipped"),
679 virStateDriverTab
[i
]->name
);
689 * virStateShutdownPrepare:
691 * Run each virtualization driver's shutdown prepare method.
693 * Returns 0 if all succeed, -1 upon any failure.
696 virStateShutdownPrepare(void)
700 for (i
= 0; i
< virStateDriverTabCount
; i
++) {
701 if (virStateDriverTab
[i
]->stateShutdownPrepare
&&
702 virStateDriverTab
[i
]->stateShutdownPrepare() < 0)
710 * virStateShutdownWait:
712 * Run each virtualization driver's shutdown wait method.
714 * Returns 0 if all succeed, -1 upon any failure.
717 virStateShutdownWait(void)
721 for (i
= 0; i
< virStateDriverTabCount
; i
++) {
722 if (virStateDriverTab
[i
]->stateShutdownWait
&&
723 virStateDriverTab
[i
]->stateShutdownWait() < 0)
733 * Run each virtualization driver's cleanup method.
735 * Returns 0 if all succeed, -1 upon any failure.
738 virStateCleanup(void)
743 for (r
= virStateDriverTabCount
- 1; r
>= 0; r
--) {
744 if (virStateDriverTab
[r
]->stateCleanup
&&
745 virStateDriverTab
[r
]->stateCleanup() < 0)
755 * Run each virtualization driver's reload method.
757 * Returns 0 if all succeed, -1 upon any failure.
765 for (i
= 0; i
< virStateDriverTabCount
; i
++) {
766 if (virStateDriverTab
[i
]->stateReload
&&
767 virStateDriverTab
[i
]->stateReload() < 0)
777 * Run each virtualization driver's "stop" method.
779 * Returns 0 if successful, -1 on failure
787 for (i
= 0; i
< virStateDriverTabCount
; i
++) {
788 if (virStateDriverTab
[i
]->stateStop
&&
789 virStateDriverTab
[i
]->stateStop())
798 * @libVer: return value for the library version (OUT)
799 * @type: ignored; pass NULL
800 * @typeVer: pass NULL; for historical purposes duplicates @libVer if
803 * Provides version information. @libVer is the version of the
804 * library and will always be set unless an error occurs, in which case
805 * an error code will be returned. @typeVer exists for historical
806 * compatibility; if it is not NULL it will duplicate @libVer (it was
807 * originally intended to return hypervisor information based on @type,
808 * but due to the design of remote clients this is not reliable). To
809 * get the version of the running hypervisor use the virConnectGetVersion()
810 * function instead. To get the libvirt library version used by a
811 * connection use the virConnectGetLibVersion() instead.
813 * This function includes a call to virInitialize() when necessary.
815 * Returns -1 in case of failure, 0 otherwise, and values for @libVer and
816 * @typeVer have the format major * 1,000,000 + minor * 1,000 + release.
821 virGetVersion(unsigned long *libVer
, const char *type G_GNUC_UNUSED
,
822 unsigned long *typeVer
)
824 if (virInitialize() < 0)
826 VIR_DEBUG("libVir=%p, type=%s, typeVer=%p", libVer
, type
, typeVer
);
831 *libVer
= LIBVIR_VERSION_NUMBER
;
834 *typeVer
= LIBVIR_VERSION_NUMBER
;
839 virDispatchError(NULL
);
845 virConnectGetDefaultURI(virConf
*conf
,
848 const char *defname
= getenv("LIBVIRT_DEFAULT_URI");
849 if (defname
&& *defname
) {
850 VIR_DEBUG("Using LIBVIRT_DEFAULT_URI '%s'", defname
);
851 *name
= g_strdup(defname
);
853 if (virConfGetValueString(conf
, "uri_default", name
) < 0)
857 VIR_DEBUG("Using config file uri '%s'", *name
);
865 * Check to see if an invalid URI like qemu://system (missing /) was passed,
866 * offer the suggested fix.
869 virConnectCheckURIMissingSlash(const char *uristr
, virURI
*uri
)
871 if (!uri
->path
|| !uri
->server
)
874 /* To avoid false positives, only check drivers that mandate
875 a path component in the URI, like /system or /session */
876 if (STRNEQ(uri
->scheme
, "qemu") &&
877 STRNEQ(uri
->scheme
, "vbox") &&
878 STRNEQ(uri
->scheme
, "vz"))
881 if (STREQ(uri
->server
, "session") ||
882 STREQ(uri
->server
, "system")) {
883 virReportError(VIR_ERR_INTERNAL_ERROR
,
884 _("invalid URI %1$s (maybe you want %2$s:///%3$s)"),
885 uristr
, uri
->scheme
, uri
->server
);
894 virConnectOpenInternal(const char *name
,
895 virConnectAuthPtr auth
,
900 g_autoptr(virConnect
) ret
= NULL
;
901 g_autoptr(virConf
) conf
= NULL
;
902 g_autofree
char *uristr
= NULL
;
905 ret
= virGetConnect();
909 if (virConfLoadConfig(&conf
, "libvirt.conf") < 0)
912 if (name
&& name
[0] == '\0')
915 /* Convert xen -> xen:///system for back compat */
916 if (name
&& STRCASEEQ(name
, "xen"))
917 name
= "xen:///system";
919 /* Convert xen:// -> xen:///system because xmlParseURI cannot parse the
920 * former. This allows URIs such as xen://localhost to work.
922 if (name
&& STREQ(name
, "xen://"))
923 name
= "xen:///system";
926 * If no URI is passed, then check for an environment string if not
927 * available probe the compiled in drivers to find a default hypervisor
931 uristr
= g_strdup(name
);
933 if (virConnectGetDefaultURI(conf
, &uristr
) < 0)
936 if (uristr
== NULL
) {
937 VIR_DEBUG("Trying to probe for default URI");
938 for (i
= 0; i
< virConnectDriverTabCount
&& uristr
== NULL
; i
++) {
939 if (virConnectDriverTab
[i
]->hypervisorDriver
->connectURIProbe
) {
940 if (virConnectDriverTab
[i
]->hypervisorDriver
->connectURIProbe(&uristr
) < 0)
942 VIR_DEBUG("%s driver URI probe returned '%s'",
943 virConnectDriverTab
[i
]->hypervisorDriver
->name
,
953 if (!(flags
& VIR_CONNECT_NO_ALIASES
) &&
954 virURIResolveAlias(conf
, uristr
, &alias
) < 0)
959 uristr
= g_steal_pointer(&alias
);
962 if (!(ret
->uri
= virURIParse(uristr
)))
965 /* Avoid need for drivers to worry about NULLs, as
966 * no one needs to distinguish "" vs NULL */
967 if (ret
->uri
->path
== NULL
)
968 ret
->uri
->path
= g_strdup("");
970 VIR_DEBUG("Split \"%s\" to URI components:\n"
977 NULLSTR(ret
->uri
->scheme
), NULLSTR(ret
->uri
->server
),
978 NULLSTR(ret
->uri
->user
), ret
->uri
->port
,
981 if (ret
->uri
->scheme
== NULL
) {
982 virReportError(VIR_ERR_NO_CONNECT
,
983 _("URI '%1$s' does not include a driver name"),
988 if (virConnectCheckURIMissingSlash(uristr
,
993 if (STREQ(ret
->uri
->path
, "/embed")) {
994 const char *root
= NULL
;
995 g_autofree
char *regMethod
= NULL
;
996 VIR_DEBUG("URI path requests %s driver embedded mode",
998 if (strspn(ret
->uri
->scheme
, "abcdefghijklmnopqrstuvwxyz") !=
999 strlen(ret
->uri
->scheme
)) {
1000 virReportError(VIR_ERR_NO_CONNECT
,
1001 _("URI scheme '%1$s' for embedded driver is not valid"),
1006 root
= virURIGetParam(ret
->uri
, "root");
1010 if (!g_path_is_absolute(root
)) {
1011 virReportError(VIR_ERR_CONFIG_UNSUPPORTED
, "%s",
1012 _("root path must be absolute"));
1016 if (virEventRequireImpl() < 0)
1019 regMethod
= g_strdup_printf("%sRegister", ret
->uri
->scheme
);
1021 if (virDriverLoadModule(ret
->uri
->scheme
, regMethod
, false) < 0)
1024 if (virAccessManagerGetDefault() == NULL
) {
1025 virAccessManager
*acl
;
1027 virResetLastError();
1029 if (!(acl
= virAccessManagerNew("none")))
1031 virAccessManagerSetDefault(acl
);
1034 if (virStateInitialize(geteuid() == 0, true, root
, false, NULL
, NULL
) < 0)
1040 VIR_DEBUG("no name, allowing driver auto-select");
1043 /* Cleansing flags */
1044 ret
->flags
= flags
& VIR_CONNECT_RO
;
1046 for (i
= 0; i
< virConnectDriverTabCount
; i
++) {
1047 /* We're going to probe the remote driver next. So we have already
1048 * probed all other client-side-only driver before, but none of them
1050 * If the scheme corresponds to a known but disabled client-side-only
1051 * driver then report a useful error, instead of a cryptic one about
1052 * not being able to connect to libvirtd or not being able to find
1054 if (STREQ(virConnectDriverTab
[i
]->hypervisorDriver
->name
, "remote") &&
1058 STRCASEEQ(ret
->uri
->scheme
, "vpx") ||
1059 STRCASEEQ(ret
->uri
->scheme
, "esx") ||
1060 STRCASEEQ(ret
->uri
->scheme
, "gsx") ||
1063 STRCASEEQ(ret
->uri
->scheme
, "hyperv") ||
1066 STRCASEEQ(ret
->uri
->scheme
, "parallels") ||
1069 virReportErrorHelper(VIR_FROM_NONE
, VIR_ERR_CONFIG_UNSUPPORTED
,
1070 __FILE__
, __FUNCTION__
, __LINE__
,
1071 _("libvirt was built without the '%1$s' driver"),
1076 VIR_DEBUG("trying driver %zu (%s) ...",
1077 i
, virConnectDriverTab
[i
]->hypervisorDriver
->name
);
1079 if (virConnectDriverTab
[i
]->localOnly
&& ret
->uri
&& ret
->uri
->server
) {
1080 VIR_DEBUG("Server present, skipping local only driver");
1084 /* Filter drivers based on declared URI schemes */
1085 if (virConnectDriverTab
[i
]->uriSchemes
) {
1086 bool matchScheme
= false;
1089 VIR_DEBUG("No URI, skipping driver with URI whitelist");
1092 if (embed
&& !virConnectDriverTab
[i
]->embeddable
) {
1093 VIR_DEBUG("Ignoring non-embeddable driver %s",
1094 virConnectDriverTab
[i
]->hypervisorDriver
->name
);
1098 VIR_DEBUG("Checking for supported URI schemes");
1099 for (s
= 0; virConnectDriverTab
[i
]->uriSchemes
[s
] != NULL
; s
++) {
1100 if (STREQ(ret
->uri
->scheme
, virConnectDriverTab
[i
]->uriSchemes
[s
])) {
1101 VIR_DEBUG("Matched URI scheme '%s'", ret
->uri
->scheme
);
1107 VIR_DEBUG("No matching URI scheme");
1112 VIR_DEBUG("Skipping wildcard for embedded URI");
1115 VIR_DEBUG("Matching any URI scheme for '%s'", ret
->uri
? ret
->uri
->scheme
: "");
1119 if (embed
&& !virConnectDriverTab
[i
]->embeddable
) {
1120 virReportError(VIR_ERR_CONFIG_UNSUPPORTED
,
1121 _("Driver %1$s cannot be used in embedded mode"),
1122 virConnectDriverTab
[i
]->hypervisorDriver
->name
);
1125 /* before starting the new connection, check if the driver only works
1126 * with a server, and so return an error if the server is missing */
1127 if (virConnectDriverTab
[i
]->remoteOnly
&& ret
->uri
&& !ret
->uri
->server
) {
1128 virReportError(VIR_ERR_INVALID_ARG
, "%s", _("URI is missing the server part"));
1132 ret
->driver
= virConnectDriverTab
[i
]->hypervisorDriver
;
1133 ret
->interfaceDriver
= virConnectDriverTab
[i
]->interfaceDriver
;
1134 ret
->networkDriver
= virConnectDriverTab
[i
]->networkDriver
;
1135 ret
->nodeDeviceDriver
= virConnectDriverTab
[i
]->nodeDeviceDriver
;
1136 ret
->nwfilterDriver
= virConnectDriverTab
[i
]->nwfilterDriver
;
1137 ret
->secretDriver
= virConnectDriverTab
[i
]->secretDriver
;
1138 ret
->storageDriver
= virConnectDriverTab
[i
]->storageDriver
;
1140 res
= virConnectDriverTab
[i
]->hypervisorDriver
->connectOpen(ret
, auth
, conf
, flags
);
1141 VIR_DEBUG("driver %zu %s returned %s",
1142 i
, virConnectDriverTab
[i
]->hypervisorDriver
->name
,
1143 res
== VIR_DRV_OPEN_SUCCESS
? "SUCCESS" :
1144 (res
== VIR_DRV_OPEN_DECLINED
? "DECLINED" :
1145 (res
== VIR_DRV_OPEN_ERROR
? "ERROR" : "unknown status")));
1147 if (res
== VIR_DRV_OPEN_SUCCESS
) {
1151 ret
->interfaceDriver
= NULL
;
1152 ret
->networkDriver
= NULL
;
1153 ret
->nodeDeviceDriver
= NULL
;
1154 ret
->nwfilterDriver
= NULL
;
1155 ret
->secretDriver
= NULL
;
1156 ret
->storageDriver
= NULL
;
1158 if (res
== VIR_DRV_OPEN_ERROR
)
1164 /* If we reach here, then all drivers declined the connection. */
1165 virReportError(VIR_ERR_NO_CONNECT
, "%s", NULLSTR(name
));
1169 return g_steal_pointer(&ret
);
1175 * @name: (optional) URI of the hypervisor
1177 * This function should be called first to get a connection to the
1178 * Hypervisor and xen store
1180 * If @name is NULL, if the LIBVIRT_DEFAULT_URI environment variable is set,
1181 * then it will be used. Otherwise if the client configuration file
1182 * has the "uri_default" parameter set, then it will be used. Finally
1183 * probing will be done to determine a suitable default driver to activate.
1184 * This involves trying each hypervisor in turn until one successfully opens.
1186 * If connecting to an unprivileged hypervisor driver which requires
1187 * the libvirtd daemon to be active, it will automatically be launched
1188 * if not already running. This can be prevented by setting the
1189 * environment variable LIBVIRT_AUTOSTART=0
1191 * URIs are documented at https://libvirt.org/uri.html
1193 * virConnectClose should be used to release the resources after the connection
1194 * is no longer needed.
1196 * Returns a pointer to the hypervisor connection or NULL in case of error
1201 virConnectOpen(const char *name
)
1203 virConnectPtr ret
= NULL
;
1205 if (virInitialize() < 0)
1208 VIR_DEBUG("name=%s", NULLSTR(name
));
1209 virResetLastError();
1210 ret
= virConnectOpenInternal(name
, NULL
, 0);
1212 virDispatchError(NULL
);
1219 * virConnectOpenReadOnly:
1220 * @name: (optional) URI of the hypervisor
1222 * This function should be called first to get a restricted connection to the
1223 * library functionalities. The set of APIs usable are then restricted
1224 * on the available methods to control the domains.
1226 * See virConnectOpen for notes about environment variables which can
1227 * have an effect on opening drivers and freeing the connection resources
1229 * URIs are documented at https://libvirt.org/uri.html
1231 * Returns a pointer to the hypervisor connection or NULL in case of error
1236 virConnectOpenReadOnly(const char *name
)
1238 virConnectPtr ret
= NULL
;
1240 if (virInitialize() < 0)
1243 VIR_DEBUG("name=%s", NULLSTR(name
));
1244 virResetLastError();
1245 ret
= virConnectOpenInternal(name
, NULL
, VIR_CONNECT_RO
);
1247 virDispatchError(NULL
);
1253 * virConnectOpenAuth:
1254 * @name: (optional) URI of the hypervisor
1255 * @auth: Authenticate callback parameters
1256 * @flags: bitwise-OR of virConnectFlags
1258 * This function should be called first to get a connection to the
1259 * Hypervisor. If necessary, authentication will be performed fetching
1260 * credentials via the callback
1262 * See virConnectOpen for notes about environment variables which can
1263 * have an effect on opening drivers and freeing the connection resources
1265 * URIs are documented at https://libvirt.org/uri.html
1267 * Returns a pointer to the hypervisor connection or NULL in case of error
1272 virConnectOpenAuth(const char *name
,
1273 virConnectAuthPtr auth
,
1276 virConnectPtr ret
= NULL
;
1278 if (virInitialize() < 0)
1281 VIR_DEBUG("name=%s, auth=%p, flags=0x%x", NULLSTR(name
), auth
, flags
);
1282 virResetLastError();
1283 ret
= virConnectOpenInternal(name
, auth
, flags
);
1285 virDispatchError(NULL
);
1293 * @conn: pointer to the hypervisor connection
1295 * This function closes the connection to the Hypervisor. This should
1296 * not be called if further interaction with the Hypervisor are needed
1297 * especially if there is running domain which need further monitoring by
1300 * Connections are reference counted; the count is explicitly
1301 * increased by the initial open (virConnectOpen, virConnectOpenAuth,
1302 * and the like) as well as virConnectRef; it is also temporarily
1303 * increased by other API that depend on the connection remaining
1304 * alive. The open and every virConnectRef call should have a
1305 * matching virConnectClose, and all other references will be released
1306 * after the corresponding operation completes.
1308 * Returns a positive number if at least 1 reference remains on
1309 * success. The returned value should not be assumed to be the total
1310 * reference count. A return of 0 implies no references remain and
1311 * the connection is closed and memory has been freed. A return of -1
1312 * implies a failure.
1314 * It is possible for the last virConnectClose to return a positive
1315 * value if some other object still has a temporary reference to the
1316 * connection, but the application should not try to further use a
1317 * connection after the virConnectClose that matches the initial open.
1322 virConnectClose(virConnectPtr conn
)
1324 VIR_DEBUG("conn=%p", conn
);
1326 virResetLastError();
1328 virCheckConnectReturn(conn
, -1);
1330 virConnectWatchDispose();
1331 virObjectUnref(conn
);
1332 if (virConnectWasDisposed())
1338 /* Helper function called to validate incoming client array on any
1339 * interface that sets typed parameters in the hypervisor. */
1341 virTypedParameterValidateSet(virConnectPtr conn
,
1342 virTypedParameterPtr params
,
1348 string_okay
= VIR_DRV_SUPPORTS_FEATURE(conn
->driver
, conn
,
1349 VIR_DRV_FEATURE_TYPED_PARAM_STRING
);
1350 if (string_okay
< 0)
1352 for (i
= 0; i
< nparams
; i
++) {
1353 if (strnlen(params
[i
].field
, VIR_TYPED_PARAM_FIELD_LENGTH
) ==
1354 VIR_TYPED_PARAM_FIELD_LENGTH
) {
1355 virReportInvalidArg(params
,
1356 _("string parameter name '%2$.*1$s' too long"),
1357 VIR_TYPED_PARAM_FIELD_LENGTH
,
1361 if (params
[i
].type
== VIR_TYPED_PARAM_STRING
) {
1363 if (!params
[i
].value
.s
) {
1364 virReportInvalidArg(params
,
1365 _("NULL string parameter '%1$s'"),
1370 virReportInvalidArg(params
,
1371 _("string parameter '%1$s' unsupported"),