/** * virRandomBits: * @nbits: Number of bits of randommess required * * Generate an evenly distributed random number between [0,2^nbits), where * @nbits must be in the range (0,64]. * * Return: a random number with @nbits entropy */ uint64_t virRandomBits(int nbits) { uint64_t ret = 0; int32_t bits; if (virRandomInitialize() < 0) { /* You're already hosed, so this particular non-random value * isn't any worse. */ VIR_WARN("random number generation is broken"); return 0; } virMutexLock(&randomLock); while (nbits > RANDOM_BITS_PER_ITER) { random_r(&randomData, &bits); ret = (ret << RANDOM_BITS_PER_ITER) | (bits & RANDOM_BITS_MASK); nbits -= RANDOM_BITS_PER_ITER; } random_r(&randomData, &bits); ret = (ret << nbits) | (bits & ((1 << nbits) - 1)); virMutexUnlock(&randomLock); return ret; }
static int virStorageBackendCreateIfaceIQN(const char *initiatoriqn, char **ifacename) { int ret = -1, exitstatus = -1; char temp_ifacename[32]; const char *const cmdargv1[] = { ISCSIADM, "--mode", "iface", "--interface", temp_ifacename, "--op", "new", NULL }; const char *const cmdargv2[] = { ISCSIADM, "--mode", "iface", "--interface", temp_ifacename, "--op", "update", "--name", "iface.initiatorname", "--value", initiatoriqn, NULL }; if (virRandomInitialize(time(NULL) ^ getpid()) == -1) { virStorageReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Failed to initialize random generator " "when creating iscsi interface")); goto out; } snprintf(temp_ifacename, sizeof(temp_ifacename), "libvirt-iface-%08x", virRandom(1024 * 1024 * 1024)); VIR_DEBUG("Attempting to create interface '%s' with IQN '%s'", &temp_ifacename[0], initiatoriqn); /* Note that we ignore the exitstatus. Older versions of iscsiadm * tools returned an exit status of > 0, even if they succeeded. * We will just rely on whether the interface got created * properly. */ if (virRun(cmdargv1, &exitstatus) < 0) { virStorageReportError(VIR_ERR_INTERNAL_ERROR, _("Failed to run command '%s' to create new iscsi interface"), cmdargv1[0]); goto out; } /* Note that we ignore the exitstatus. Older versions of iscsiadm tools * returned an exit status of > 0, even if they succeeded. We will just * rely on whether iface file got updated properly. */ if (virRun(cmdargv2, &exitstatus) < 0) { virStorageReportError(VIR_ERR_INTERNAL_ERROR, _("Failed to run command '%s' to update iscsi interface with IQN '%s'"), cmdargv2[0], initiatoriqn); goto out; } /* Check again to make sure the interface was created. */ if (virStorageBackendIQNFound(initiatoriqn, ifacename) != IQN_FOUND) { VIR_DEBUG("Failed to find interface '%s' with IQN '%s' " "after attempting to create it", &temp_ifacename[0], initiatoriqn); goto out; } else { VIR_DEBUG("Interface '%s' with IQN '%s' was created successfully", *ifacename, initiatoriqn); } ret = 0; out: if (ret != 0) VIR_FREE(*ifacename); return ret; }