summaryrefslogtreecommitdiff
path: root/util/libreboot-utils/lib/rand.c
diff options
context:
space:
mode:
Diffstat (limited to 'util/libreboot-utils/lib/rand.c')
-rw-r--r--util/libreboot-utils/lib/rand.c42
1 files changed, 12 insertions, 30 deletions
diff --git a/util/libreboot-utils/lib/rand.c b/util/libreboot-utils/lib/rand.c
index 4c7458c7..9edc8a5b 100644
--- a/util/libreboot-utils/lib/rand.c
+++ b/util/libreboot-utils/lib/rand.c
@@ -72,20 +72,14 @@
* or your program dies.
*/
-void *
-rmalloc(size_t *rval)
-{
- return if_err(rval == NULL, EFAULT) ?
- NULL : mkrstr(*rval = rsize(BUFSIZ));
-}
-
size_t
rsize(size_t n)
{
size_t rval = SIZE_MAX;
if (!n)
- err_no_cleanup(0, EFAULT, "rsize: division by zero");
+ err_exit(EFAULT, "rsize: division by zero");
+ /* rejection sampling (clamp rand to eliminate modulo bias) */
for (; rval >= SIZE_MAX - (SIZE_MAX % n); rset(&rval, sizeof(rval)));
return rval % n;
@@ -98,13 +92,13 @@ mkrstr(size_t n) /* emulates spkmodem-decode */
size_t i;
if (n == 0)
- err_no_cleanup(0, EPERM, "mkrbuf: zero-byte request");
+ err_exit(EPERM, "mkrbuf: zero-byte request");
if (n >= SIZE_MAX - 1)
- err_no_cleanup(0, EOVERFLOW, "mkrbuf: overflow");
+ err_exit(EOVERFLOW, "mkrbuf: overflow");
if (if_err((s = mkrbuf(n + 1)) == NULL, EFAULT))
- err_no_cleanup(0, EFAULT, "mkrstr: null");
+ err_exit(EFAULT, "mkrstr: null");
for (i = 0; i < n; i++)
while(*(s + i) == '\0')
@@ -118,18 +112,8 @@ mkrstr(size_t n) /* emulates spkmodem-decode */
void *
mkrbuf(size_t n)
{
- void *buf = "";
-
- if (n == 0)
- err_no_cleanup(0, EPERM, "mkrbuf: zero-byte request");
-
- if (n >= SIZE_MAX - 1)
- err_no_cleanup(0, EOVERFLOW, "integer overflow in mkrbuf");
-
- if ((buf = malloc(n)) == NULL)
- err_no_cleanup(0, ENOMEM, "mkrbuf: malloc");
-
- rset(buf, n);
+ void *buf = NULL;
+ rset(vmalloc(&buf, n), n);
return buf; /* basically malloc() but with rand */
}
@@ -142,7 +126,7 @@ rset(void *buf, size_t n)
goto err;
if (n == 0)
- err_no_cleanup(0, EPERM, "rset: zero-byte request");
+ err_exit(EPERM, "rset: zero-byte request");
#if (defined(__OpenBSD__) || defined(__FreeBSD__) || \
defined(__NetBSD__) || defined(__APPLE__) || \
@@ -158,9 +142,7 @@ rset(void *buf, size_t n)
#if defined(USE_URANDOM) && \
((USE_URANDOM) > 0)
int fd = -1;
-
- if ((fd = open("/dev/urandom", O_RDONLY)) < 0)
- goto err;
+ open_on_eintr("/dev/urandom", &fd, O_RDONLY, 0400, NULL);
retry_rand:
if ((rc = read(fd, (unsigned char *)buf + off, n - off)) < 0) {
#elif defined(__linux__)
@@ -185,7 +167,7 @@ retry_rand:
#if defined(USE_URANDOM) && \
((USE_URANDOM) > 0)
- close_no_err(&fd);
+ close_on_eintr(&fd);
#endif
goto out;
#endif
@@ -195,9 +177,9 @@ out:
err:
#if defined(USE_URANDOM) && \
((USE_URANDOM) > 0)
- close_no_err(&fd);
+ close_on_eintr(&fd);
#endif
- err_no_cleanup(0, ECANCELED,
+ err_exit(ECANCELED,
"Randomisation failure, possibly unsupported in your kernel");
exit(EXIT_FAILURE);
}