virshtest: Adapt 'virsh-vcpupin' test
[libvirt.git] / src / libvirt.c
blob26c3fe454fd68f77e8b9b5fc5d0761cfc59d3f22
1 /*
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/>.
22 #include <config.h>
24 #include <sys/types.h>
25 #include <sys/stat.h>
26 #include <unistd.h>
27 #include <time.h>
28 #include <gio/gnetworking.h>
30 #include <libxml/parser.h>
31 #include <libxml/xpath.h>
33 #ifdef WITH_CURL
34 # include <curl/curl.h>
35 #endif
37 #include "virerror.h"
38 #include "virlog.h"
39 #include "datatypes.h"
40 #include "driver.h"
42 #include "viruuid.h"
43 #include "viralloc.h"
44 #include "configmake.h"
45 #include "virconf.h"
46 #include "rpc/virnettlscontext.h"
47 #include "vircommand.h"
48 #include "virevent.h"
49 #include "virfile.h"
50 #include "virrandom.h"
51 #include "viruri.h"
52 #include "virthread.h"
53 #include "virstring.h"
54 #include "virutil.h"
55 #include "virtypedparam.h"
57 #ifdef WITH_TEST
58 # include "test/test_driver.h"
59 #endif
60 #ifdef WITH_REMOTE
61 # include "remote/remote_driver.h"
62 #endif
63 #ifdef WITH_OPENVZ
64 # include "openvz/openvz_driver.h"
65 #endif
66 #ifdef WITH_VMWARE
67 # include "vmware/vmware_driver.h"
68 #endif
69 #ifdef WITH_ESX
70 # include "esx/esx_driver.h"
71 #endif
72 #ifdef WITH_HYPERV
73 # include "hyperv/hyperv_driver.h"
74 #endif
75 #ifdef WITH_BHYVE
76 # include "bhyve/bhyve_driver.h"
77 #endif
78 #include "access/viraccessmanager.h"
80 #define VIR_FROM_THIS VIR_FROM_NONE
82 VIR_LOG_INIT("libvirt");
85 * TODO:
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;
105 static int
106 virConnectAuthCallbackDefault(virConnectCredentialPtr cred,
107 unsigned int ncred,
108 void *cbdata G_GNUC_UNUSED)
110 size_t i;
112 for (i = 0; i < ncred; i++) {
113 char buf[1024];
114 char *bufptr = NULL;
115 size_t len;
117 switch (cred[i].type) {
118 case VIR_CRED_EXTERNAL: {
119 if (STRNEQ(cred[i].challenge, "PolicyKit"))
120 return -1;
123 * Ignore & carry on. Although we can't auth
124 * directly, the user may have authenticated
125 * themselves already outside context of libvirt
127 break;
130 case VIR_CRED_USERNAME:
131 case VIR_CRED_AUTHNAME:
132 case VIR_CRED_ECHOPROMPT:
133 case VIR_CRED_REALM:
134 if (printf("%s: ", cred[i].prompt) < 0)
135 return -1;
136 if (fflush(stdout) != 0)
137 return -1;
139 if (!fgets(buf, sizeof(buf), stdin)) {
140 if (feof(stdin)) { /* Treat EOF as "" */
141 break;
143 return -1;
146 len = strlen(buf);
147 if (len != 0 && buf[len-1] == '\n')
148 buf[len-1] = '\0';
150 if (strlen(buf) > 0)
151 bufptr = g_strdup(buf);
152 break;
154 case VIR_CRED_PASSPHRASE:
155 case VIR_CRED_NOECHOPROMPT:
156 if (printf("%s: ", cred[i].prompt) < 0)
157 return -1;
158 if (fflush(stdout) != 0)
159 return -1;
161 bufptr = virGetPassword();
162 if (STREQ(bufptr, ""))
163 VIR_FREE(bufptr);
164 break;
166 default:
167 return -1;
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);
176 return 0;
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[] = {
185 VIR_CRED_AUTHNAME,
186 VIR_CRED_ECHOPROMPT,
187 VIR_CRED_REALM,
188 VIR_CRED_PASSPHRASE,
189 VIR_CRED_NOECHOPROMPT,
190 VIR_CRED_EXTERNAL,
193 static virConnectAuth virConnectAuthDefault = {
194 virConnectCredTypeDefault,
195 G_N_ELEMENTS(virConnectCredTypeDefault),
196 virConnectAuthCallbackDefault,
197 NULL,
200 /* Explanation in the header file */
201 virConnectAuthPtr virConnectAuthPtrDefault = &virConnectAuthDefault;
203 static bool virGlobalError;
204 static virOnceControl virGlobalOnce = VIR_ONCE_CONTROL_INITIALIZER;
206 static void
207 virGlobalInit(void)
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)
215 goto error;
217 /* Make glib initialize its own global state. See more:
219 * https://gitlab.gnome.org/GNOME/glib/-/issues/3034
221 * TODO: Remove ASAP.
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"));
231 goto error;
234 /* Do this upfront rather than every time a child is spawned. */
235 if (virCloseRangeInit() < 0)
236 goto error;
238 if (virLogSetFromEnv() < 0)
239 goto error;
241 virNetTLSInit();
243 #if WITH_CURL
244 curl_global_init(CURL_GLOBAL_DEFAULT);
245 #endif
247 VIR_DEBUG("register drivers");
249 g_networking_init();
251 #ifdef WITH_LIBINTL_H
252 if (!bindtextdomain(PACKAGE, LOCALEDIR))
253 goto error;
254 #endif /* WITH_LIBINTL_H */
257 * Note that the order is important: the first ones have a higher
258 * priority when calling virConnectOpen.
260 #ifdef WITH_TEST
261 if (testRegister() == -1)
262 goto error;
263 #endif
264 #ifdef WITH_OPENVZ
265 if (openvzRegister() == -1)
266 goto error;
267 #endif
268 #ifdef WITH_VMWARE
269 if (vmwareRegister() == -1)
270 goto error;
271 #endif
272 #ifdef WITH_ESX
273 if (esxRegister() == -1)
274 goto error;
275 #endif
276 #ifdef WITH_HYPERV
277 if (hypervRegister() == -1)
278 goto error;
279 #endif
280 #ifdef WITH_REMOTE
281 if (remoteRegister() == -1)
282 goto error;
283 #endif
285 return;
287 error:
288 virGlobalError = true;
293 * virInitialize:
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
312 * Since: 0.1.0
315 virInitialize(void)
317 if (virOnce(&virGlobalOnce, virGlobalInit) < 0 ||
318 virGlobalError) {
319 virDispatchError(NULL);
320 return -1;
323 return 0;
327 #ifdef WIN32
328 BOOL WINAPI
329 DllMain(HINSTANCE instance, DWORD reason, LPVOID ignore);
331 BOOL WINAPI
332 DllMain(HINSTANCE instance G_GNUC_UNUSED,
333 DWORD reason,
334 LPVOID ignore G_GNUC_UNUSED)
336 switch (reason) {
337 case DLL_PROCESS_ATTACH:
338 virInitialize();
339 break;
341 case DLL_THREAD_ATTACH:
342 case DLL_THREAD_DETACH:
343 /* Nothing todo in libvirt yet */
344 break;
346 case DLL_PROCESS_DETACH:
347 /* Don't bother releasing per-thread data
348 since (hopefully) windows cleans up
349 everything on process exit */
350 break;
353 return TRUE;
355 #endif
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"));
374 return -1;
377 VIR_DEBUG("registering %s as network driver", driver->name);
379 virSharedNetworkDriver = driver;
380 return 0;
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"));
400 return -1;
403 VIR_DEBUG("registering %s as interface driver", driver->name);
405 virSharedInterfaceDriver = driver;
406 return 0;
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"));
426 return -1;
429 VIR_DEBUG("registering %s as storage driver", driver->name);
431 virSharedStorageDriver = driver;
432 return 0;
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"));
452 return -1;
455 VIR_DEBUG("registering %s as device driver", driver->name);
457 virSharedNodeDeviceDriver = driver;
458 return 0;
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"));
478 return -1;
481 VIR_DEBUG("registering %s as secret driver", driver->name);
483 virSharedSecretDriver = driver;
484 return 0;
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"));
504 return -1;
507 VIR_DEBUG("registering %s as network filter driver", driver->name);
509 virSharedNWFilterDriver = driver;
510 return 0;
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);
536 return -1;
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
571 bool
572 virHasDriverForURIScheme(const char *scheme)
574 size_t i;
575 size_t j;
577 for (i = 0; i < virConnectDriverTabCount; i++) {
578 if (!virConnectDriverTab[i]->uriSchemes)
579 continue;
580 for (j = 0; virConnectDriverTab[i]->uriSchemes[j]; j++) {
581 if (STREQ(virConnectDriverTab[i]->uriSchemes[j], scheme))
582 return true;
586 return false;
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"),
605 driver->name);
606 return -1;
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
631 * locations
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
639 * @root/etc/$DRIVER/
640 * @root/var/lib/$DRIVER/
641 * @root/run/$DRIVER/
643 * Returns 0 if all succeed, -1 upon any failure.
646 virStateInitialize(bool privileged,
647 bool mandatory,
648 const char *root,
649 bool monolithic,
650 virStateInhibitCallback callback,
651 void *opaque)
653 size_t i;
655 if (virInitialize() < 0)
656 return -1;
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,
666 root,
667 monolithic,
668 callback,
669 opaque);
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());
675 return -1;
677 if (ret == VIR_DRV_STATE_INIT_SKIPPED && mandatory) {
678 VIR_ERROR(_("Initialization of mandatory %1$s state driver skipped"),
679 virStateDriverTab[i]->name);
680 return -1;
684 return 0;
689 * virStateShutdownPrepare:
691 * Run each virtualization driver's shutdown prepare method.
693 * Returns 0 if all succeed, -1 upon any failure.
696 virStateShutdownPrepare(void)
698 size_t i;
700 for (i = 0; i < virStateDriverTabCount; i++) {
701 if (virStateDriverTab[i]->stateShutdownPrepare &&
702 virStateDriverTab[i]->stateShutdownPrepare() < 0)
703 return -1;
705 return 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)
719 size_t i;
721 for (i = 0; i < virStateDriverTabCount; i++) {
722 if (virStateDriverTab[i]->stateShutdownWait &&
723 virStateDriverTab[i]->stateShutdownWait() < 0)
724 return -1;
726 return 0;
731 * virStateCleanup:
733 * Run each virtualization driver's cleanup method.
735 * Returns 0 if all succeed, -1 upon any failure.
738 virStateCleanup(void)
740 int r;
741 int ret = 0;
743 for (r = virStateDriverTabCount - 1; r >= 0; r--) {
744 if (virStateDriverTab[r]->stateCleanup &&
745 virStateDriverTab[r]->stateCleanup() < 0)
746 ret = -1;
748 return ret;
753 * virStateReload:
755 * Run each virtualization driver's reload method.
757 * Returns 0 if all succeed, -1 upon any failure.
760 virStateReload(void)
762 size_t i;
763 int ret = 0;
765 for (i = 0; i < virStateDriverTabCount; i++) {
766 if (virStateDriverTab[i]->stateReload &&
767 virStateDriverTab[i]->stateReload() < 0)
768 ret = -1;
770 return ret;
775 * virStateStop:
777 * Run each virtualization driver's "stop" method.
779 * Returns 0 if successful, -1 on failure
782 virStateStop(void)
784 size_t i;
785 int ret = 0;
787 for (i = 0; i < virStateDriverTabCount; i++) {
788 if (virStateDriverTab[i]->stateStop &&
789 virStateDriverTab[i]->stateStop())
790 ret = 1;
792 return ret;
797 * virGetVersion:
798 * @libVer: return value for the library version (OUT)
799 * @type: ignored; pass NULL
800 * @typeVer: pass NULL; for historical purposes duplicates @libVer if
801 * non-NULL
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.
818 * Since: 0.0.3
821 virGetVersion(unsigned long *libVer, const char *type G_GNUC_UNUSED,
822 unsigned long *typeVer)
824 if (virInitialize() < 0)
825 goto error;
826 VIR_DEBUG("libVir=%p, type=%s, typeVer=%p", libVer, type, typeVer);
828 virResetLastError();
829 if (libVer == NULL)
830 goto error;
831 *libVer = LIBVIR_VERSION_NUMBER;
833 if (typeVer != NULL)
834 *typeVer = LIBVIR_VERSION_NUMBER;
836 return 0;
838 error:
839 virDispatchError(NULL);
840 return -1;
844 static int
845 virConnectGetDefaultURI(virConf *conf,
846 char **name)
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);
852 } else {
853 if (virConfGetValueString(conf, "uri_default", name) < 0)
854 return -1;
856 if (*name)
857 VIR_DEBUG("Using config file uri '%s'", *name);
860 return 0;
865 * Check to see if an invalid URI like qemu://system (missing /) was passed,
866 * offer the suggested fix.
868 static int
869 virConnectCheckURIMissingSlash(const char *uristr, virURI *uri)
871 if (!uri->path || !uri->server)
872 return 0;
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"))
879 return 0;
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);
886 return -1;
889 return 0;
893 static virConnectPtr
894 virConnectOpenInternal(const char *name,
895 virConnectAuthPtr auth,
896 unsigned int flags)
898 size_t i;
899 int res;
900 g_autoptr(virConnect) ret = NULL;
901 g_autoptr(virConf) conf = NULL;
902 g_autofree char *uristr = NULL;
903 bool embed = false;
905 ret = virGetConnect();
906 if (ret == NULL)
907 return NULL;
909 if (virConfLoadConfig(&conf, "libvirt.conf") < 0)
910 return NULL;
912 if (name && name[0] == '\0')
913 name = NULL;
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
928 * if detectable.
930 if (name) {
931 uristr = g_strdup(name);
932 } else {
933 if (virConnectGetDefaultURI(conf, &uristr) < 0)
934 return NULL;
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)
941 return NULL;
942 VIR_DEBUG("%s driver URI probe returned '%s'",
943 virConnectDriverTab[i]->hypervisorDriver->name,
944 NULLSTR(uristr));
950 if (uristr) {
951 char *alias = NULL;
953 if (!(flags & VIR_CONNECT_NO_ALIASES) &&
954 virURIResolveAlias(conf, uristr, &alias) < 0)
955 return NULL;
957 if (alias) {
958 g_free(uristr);
959 uristr = g_steal_pointer(&alias);
962 if (!(ret->uri = virURIParse(uristr)))
963 return NULL;
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"
971 " scheme %s\n"
972 " server %s\n"
973 " user %s\n"
974 " port %d\n"
975 " path %s",
976 uristr,
977 NULLSTR(ret->uri->scheme), NULLSTR(ret->uri->server),
978 NULLSTR(ret->uri->user), ret->uri->port,
979 ret->uri->path);
981 if (ret->uri->scheme == NULL) {
982 virReportError(VIR_ERR_NO_CONNECT,
983 _("URI '%1$s' does not include a driver name"),
984 name);
985 return NULL;
988 if (virConnectCheckURIMissingSlash(uristr,
989 ret->uri) < 0) {
990 return NULL;
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",
997 ret->uri->scheme);
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"),
1002 ret->uri->scheme);
1003 return NULL;
1006 root = virURIGetParam(ret->uri, "root");
1007 if (!root)
1008 return NULL;
1010 if (!g_path_is_absolute(root)) {
1011 virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
1012 _("root path must be absolute"));
1013 return NULL;
1016 if (virEventRequireImpl() < 0)
1017 return NULL;
1019 regMethod = g_strdup_printf("%sRegister", ret->uri->scheme);
1021 if (virDriverLoadModule(ret->uri->scheme, regMethod, false) < 0)
1022 return NULL;
1024 if (virAccessManagerGetDefault() == NULL) {
1025 virAccessManager *acl;
1027 virResetLastError();
1029 if (!(acl = virAccessManagerNew("none")))
1030 return NULL;
1031 virAccessManagerSetDefault(acl);
1034 if (virStateInitialize(geteuid() == 0, true, root, false, NULL, NULL) < 0)
1035 return NULL;
1037 embed = true;
1039 } else {
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
1049 * accepted the URI.
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
1053 * certificates. */
1054 if (STREQ(virConnectDriverTab[i]->hypervisorDriver->name, "remote") &&
1055 ret->uri != NULL &&
1057 #ifndef WITH_ESX
1058 STRCASEEQ(ret->uri->scheme, "vpx") ||
1059 STRCASEEQ(ret->uri->scheme, "esx") ||
1060 STRCASEEQ(ret->uri->scheme, "gsx") ||
1061 #endif
1062 #ifndef WITH_HYPERV
1063 STRCASEEQ(ret->uri->scheme, "hyperv") ||
1064 #endif
1065 #ifndef WITH_VZ
1066 STRCASEEQ(ret->uri->scheme, "parallels") ||
1067 #endif
1068 false)) {
1069 virReportErrorHelper(VIR_FROM_NONE, VIR_ERR_CONFIG_UNSUPPORTED,
1070 __FILE__, __FUNCTION__, __LINE__,
1071 _("libvirt was built without the '%1$s' driver"),
1072 ret->uri->scheme);
1073 return NULL;
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");
1081 continue;
1084 /* Filter drivers based on declared URI schemes */
1085 if (virConnectDriverTab[i]->uriSchemes) {
1086 bool matchScheme = false;
1087 size_t s;
1088 if (!ret->uri) {
1089 VIR_DEBUG("No URI, skipping driver with URI whitelist");
1090 continue;
1092 if (embed && !virConnectDriverTab[i]->embeddable) {
1093 VIR_DEBUG("Ignoring non-embeddable driver %s",
1094 virConnectDriverTab[i]->hypervisorDriver->name);
1095 continue;
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);
1102 matchScheme = true;
1103 break;
1106 if (!matchScheme) {
1107 VIR_DEBUG("No matching URI scheme");
1108 continue;
1110 } else {
1111 if (embed) {
1112 VIR_DEBUG("Skipping wildcard for embedded URI");
1113 continue;
1114 } else {
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);
1123 return NULL;
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"));
1129 return NULL;
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) {
1148 break;
1149 } else {
1150 ret->driver = NULL;
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)
1159 return NULL;
1163 if (!ret->driver) {
1164 /* If we reach here, then all drivers declined the connection. */
1165 virReportError(VIR_ERR_NO_CONNECT, "%s", NULLSTR(name));
1166 return NULL;
1169 return g_steal_pointer(&ret);
1174 * virConnectOpen:
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
1198 * Since: 0.0.3
1200 virConnectPtr
1201 virConnectOpen(const char *name)
1203 virConnectPtr ret = NULL;
1205 if (virInitialize() < 0)
1206 return NULL;
1208 VIR_DEBUG("name=%s", NULLSTR(name));
1209 virResetLastError();
1210 ret = virConnectOpenInternal(name, NULL, 0);
1211 if (!ret)
1212 virDispatchError(NULL);
1214 return ret;
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
1233 * Since: 0.0.3
1235 virConnectPtr
1236 virConnectOpenReadOnly(const char *name)
1238 virConnectPtr ret = NULL;
1240 if (virInitialize() < 0)
1241 return NULL;
1243 VIR_DEBUG("name=%s", NULLSTR(name));
1244 virResetLastError();
1245 ret = virConnectOpenInternal(name, NULL, VIR_CONNECT_RO);
1246 if (!ret)
1247 virDispatchError(NULL);
1248 return ret;
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
1269 * Since: 0.4.0
1271 virConnectPtr
1272 virConnectOpenAuth(const char *name,
1273 virConnectAuthPtr auth,
1274 unsigned int flags)
1276 virConnectPtr ret = NULL;
1278 if (virInitialize() < 0)
1279 return NULL;
1281 VIR_DEBUG("name=%s, auth=%p, flags=0x%x", NULLSTR(name), auth, flags);
1282 virResetLastError();
1283 ret = virConnectOpenInternal(name, auth, flags);
1284 if (!ret)
1285 virDispatchError(NULL);
1286 return ret;
1292 * virConnectClose:
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
1298 * the application.
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.
1319 * Since: 0.0.3
1322 virConnectClose(virConnectPtr conn)
1324 VIR_DEBUG("conn=%p", conn);
1326 virResetLastError();
1328 virCheckConnectReturn(conn, -1);
1330 virConnectWatchDispose();
1331 virObjectUnref(conn);
1332 if (virConnectWasDisposed())
1333 return 0;
1334 return 1;
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,
1343 int nparams)
1345 int string_okay;
1346 size_t i;
1348 string_okay = VIR_DRV_SUPPORTS_FEATURE(conn->driver, conn,
1349 VIR_DRV_FEATURE_TYPED_PARAM_STRING);
1350 if (string_okay < 0)
1351 return -1;
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,
1358 params[i].field);
1359 return -1;
1361 if (params[i].type == VIR_TYPED_PARAM_STRING) {
1362 if (string_okay) {
1363 if (!params[i].value.s) {
1364 virReportInvalidArg(params,
1365 _("NULL string parameter '%1$s'"),
1366 params[i].field);
1367 return -1;
1369 } else {
1370 virReportInvalidArg(params,
1371 _("string parameter '%1$s' unsupported"),
1372 params[i].field);
1373 return -1;
1377 return 0;