From cb4258434ce6893a2384a960ef4d87f788a6ec7c Mon Sep 17 00:00:00 2001 From: Max Kellermann Date: Mon, 27 Jan 2020 22:16:11 +0100 Subject: [PATCH] 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.) --- src/util.cc | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/util.cc b/src/util.cc index 18a4defde5..df7b13f663 100644 --- a/src/util.cc +++ b/src/util.cc @@ -55,6 +55,14 @@ #include "3rdparty/doctest.h" +#if defined(__linux__) && __cplusplus >= 201703L +/* need C++17 for __has_include() */ +#if __has_include() +#define HAVE_GETRANDOM +#include +#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.