util: use getrandom() on Linux if available

Unlike /dev/urandom, getrandom() doesn't need a file descriptor and
works when there is no /dev.  It requires Linux 3.17 and glibc 2.25,
but there is a fallback to the old code.

For simplicity, this patch uses __has_include() to detect the
availability of this API, but maybe we should move that to cmake.

(It might be useful to refactor the whole random gathering code to a
separate function.)
This commit is contained in:
Max Kellermann 2020-01-27 22:16:11 +01:00
parent 0412cb3996
commit cb4258434c

View file

@ -55,6 +55,14 @@
#include "3rdparty/doctest.h"
#if defined(__linux__) && __cplusplus >= 201703L
/* need C++17 for __has_include() */
#if __has_include(<sys/random.h>)
#define HAVE_GETRANDOM
#include <sys/random.h>
#endif
#endif
TEST_CASE("util extract_ip")
{
CHECK(extract_ip("[1.2.3.4]") == "1.2.3.4");
@ -1035,6 +1043,14 @@ void init_random_seed(const char* read_file, const char* write_file)
seeds_done = true;
}
#ifdef HAVE_GETRANDOM
if ( ! seeds_done )
{
ssize_t nbytes = getrandom(buf, sizeof(buf), 0);
seeds_done = nbytes == ssize_t(sizeof(buf));
}
#endif
if ( ! seeds_done )
{
// Gather up some entropy.