virCryptoGenerateRandom(unsigned char *buf,
size_t buflen)
{
+#if WITH_GNUTLS
int rv;
-#if WITH_GNUTLS
/* Generate the byte stream using gnutls_rnd() if possible */
if ((rv = gnutls_rnd(GNUTLS_RND_RANDOM, buf, buflen)) < 0) {
virReportError(VIR_ERR_INTERNAL_ERROR,
/* If we don't have gnutls_rnd(), we will generate a less cryptographically
* strong master buf from /dev/urandom.
*/
- if ((rv = virRandomBytes(buf, buflen)) < 0) {
- virReportSystemError(-rv, "%s", _("failed to generate byte stream"));
+ if (virRandomBytes(buf, buflen) < 0)
return -1;
- }
#endif
return 0;
VIR_LOG_INIT("util.random");
+#define RANDOM_SOURCE "/dev/urandom"
+
/* The algorithm of virRandomBits relies on gnulib's guarantee that
* 'random_r' matches the POSIX requirements on 'random' of being
* evenly distributed among exactly [0, 2**31) (that is, we always get
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;
}
* @buf: Pointer to location to store bytes
* @buflen: Number of bytes to store
*
- * Generate a stream of random bytes from /dev/urandom
+ * Generate a stream of random bytes from RANDOM_SOURCE
* into @buf of size @buflen
*
- * Returns 0 on success or -errno on failure
+ * Returns 0 on success or -1 (with error reported)
*/
int
virRandomBytes(unsigned char *buf,
{
int fd;
- if ((fd = open("/dev/urandom", O_RDONLY)) < 0)
- return -errno;
+ if ((fd = open(RANDOM_SOURCE, O_RDONLY)) < 0) {
+ virReportSystemError(errno,
+ _("unable to open %s"),
+ RANDOM_SOURCE);
+ return -1;
+ }
while (buflen > 0) {
ssize_t n;
if ((n = saferead(fd, buf, buflen)) <= 0) {
+ virReportSystemError(errno,
+ _("unable to read from %s"),
+ RANDOM_SOURCE);
VIR_FORCE_CLOSE(fd);
return n < 0 ? -errno : -ENODATA;
}