From 6c10c32e03263c1845ac4a028d054937a3c9a5c4 Mon Sep 17 00:00:00 2001 From: Paul Duncan Date: Wed, 8 May 2024 17:58:59 -0400 Subject: rand-bytes.h: use getentropy() instead of getrandom() to support macos --- rand-bytes.h | 32 ++++++++++++++++++++++++-------- 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/rand-bytes.h b/rand-bytes.h index b9d38d4..14b2861 100644 --- a/rand-bytes.h +++ b/rand-bytes.h @@ -2,18 +2,34 @@ #define RAND_BYTES_H #include // size_t -#include // getrandom() +#include // getentropy() #include // errx() -// Fill `buf` with `len` random bytes using `getrandom()`. +// Fill `buf` with `len` random bytes using `getentropy()`. // -// Prints an error and exits with an error code if `len` random bytes -// could not be read. -static void rand_bytes(void * const buf, const size_t len) { - const ssize_t got = getrandom(buf, len, 0); - if (got < (ssize_t) len) { +// Prints an error message to standard error and exits with a non-zero +// error code if `len` random bytes could not be read. +static void rand_bytes(void * const buf, size_t len) { + uint8_t *u8 = (uint8_t*) buf; + + // the maximum length for getentropy() is 256 bytes, so split requests + // for more than 256 bytes into multiple calls to `getentropy()`. + while (len > 256) { + // read 256 bytes, check for error + if (getentropy(u8, 256) == -1) { + // print error message, exit with error + errx(-1, "getentropy() failed"); + } + + // increment pointer, decrement length + u8 += 256; + len -= 256; + } + + // read remaining bytes, check for error + if (getentropy(u8, len) == -1) { // print error message, exit with error - errx(-1, "getrandom() failed"); + errx(-1, "getentropy() failed"); } } -- cgit v1.2.3