nk/hwrng: Use libc wrapper for getrandom by default.

This commit is contained in:
Nicholas J. Kain 2022-03-08 13:45:52 -05:00
parent 0b53d93648
commit b21edf205a

View File

@ -1,4 +1,4 @@
// Copyright 2013-2018 Nicholas J. Kain <njkain at gmail dot com>
// Copyright 2013-2022 Nicholas J. Kain <njkain at gmail dot com>
// SPDX-License-Identifier: MIT
#include <stdint.h>
#include <string.h>
@ -13,22 +13,36 @@
#include "nk/log.h"
#include "nk/io.h"
#ifdef NK_USE_GETRANDOM_SYSCALL
#ifdef NK_NO_GETRANDOM_SYSCALL
static bool nk_getrandom(char *seed, size_t len)
{
(void)seed;
(void)len;
return false;
}
#else
#ifdef NK_NO_GETRANDOM_LIBC
#include <sys/syscall.h>
#include <linux/random.h>
#define NK_GETRANDOM_CALL(A,B,C) syscall(SYS_getrandom, (A), (B), (C))
#else
#include <sys/random.h>
#define NK_GETRANDOM_CALL(A,B,C) getrandom((A), (B), (C))
#endif
static bool nk_getrandom(char *seed, size_t len)
{
size_t fetched = 0;
while (fetched < len) {
int r = syscall(SYS_getrandom, seed + fetched, len - fetched, 0);
int r = NK_GETRANDOM_CALL(seed + fetched, len - fetched, 0);
if (r <= 0) {
if (r == 0) {
// Failsafe to guard against infinite loops.
log_line("%s: getrandom() returned no entropy", __func__);
return false;
}
if (errno == EINTR)
continue;
if (errno == EINTR) continue;
if (errno == ENOSYS) return false; // Kernel doesn't support syscall
log_line("%s: getrandom() failed: %s", __func__, strerror(errno));
return false;
}
@ -36,14 +50,9 @@ static bool nk_getrandom(char *seed, size_t len)
}
return true;
}
#else
static bool nk_getrandom(char *seed, size_t len)
{
(void)seed;
(void)len;
return false;
}
#endif
#undef NK_GETRANDOM_CALL
static bool nk_get_rnd_clk(char *seed, size_t len)
{
struct timespec ts;