2 * UCW Library -- Strong random generator
4 * (c) 2020--2022 Pavel Charvat <pchar@ucw.cz>
6 * This software may be freely distributed and used according to the terms
7 * of the GNU Lesser General Public License.
13 #include <ucw/random.h>
14 #include <ucw/threads.h>
19 #ifdef CONFIG_UCW_GETRANDOM
20 #include <sys/random.h>
23 /*** getrandom() helpers ***/
25 #ifdef CONFIG_UCW_GETRANDOM
26 static bool strongrand_getrandom_detect(void)
28 static int static_detected;
31 detected = static_detected;
41 int n = getrandom(buf, 1, GRND_NONBLOCK);
48 else if (errno != EINTR)
55 static_detected = detected;
59 DBG("RANDOM: Kernel supports getrandom()");
62 else if (err == ENOSYS)
64 DBG("RANDOM: Kernel does not support getrandom()");
69 // We print an error also for EAGAIN -- for urandom it should be possible only during early boot.
70 msg(L_ERROR, "RANDOM: Failed to call getrandom(): %s -> assuming no support", strerror(err));
75 bool strongrand_getrandom_mem_try(void *buf, size_t size)
77 if (!strongrand_getrandom_detect())
81 ssize_t n = getrandom(buf, size, 0);
86 die("RANDOM: Failed to call getrandom(): %m");
88 buf = (byte *)buf + n;
94 bool strongrand_getrandom_mem_try(void *buf UNUSED, size_t size UNUSED)