git.iko.soy/typeable/entropy
on main help sign in
typeable/entropy/cbits/random_initialized.c
58 lines 1.2 kB history raw
1#define _GNU_SOURCE
2#include <errno.h>
3#include <fcntl.h>
4#include <poll.h>
5#include <sys/stat.h>
6#include <unistd.h>
8#ifdef HAVE_GETENTROPY
9#ifndef DO_NOT_USE_GET_ENTROPY
10static int ensure_pool_initialized_getentropy()
12 char tmp;
13 return getentropy(&tmp, sizeof(tmp));
15#endif
16#endif
18// Poll /dev/random to wait for randomness. This is a proxy for the /dev/urandom
19// pool being initialized.
20static int ensure_pool_initialized_poll()
22 struct pollfd pfd;
23 int dev_random = open("/dev/random", O_RDONLY);
24 if (dev_random == -1)
25 return -1;
27 pfd.fd = dev_random;
28 pfd.events = POLLIN;
29 pfd.revents = 0;
31 while (1) {
32 int ret = poll(&pfd, 1, -1);
33 if (ret < 0 && (errno == EAGAIN || errno == EINTR))
34 continue;
35 if (ret != 1) {
36 close(dev_random);
37 errno = EIO;
38 return -1;
39 }
41 break;
42 }
44 return close(dev_random);
47// Returns 0 on success, non-zero on failure.
48int ensure_pool_initialized()
50#ifdef HAVE_GETENTROPY
51#ifndef DO_NOT_USE_GET_ENTROPY
52 if (ensure_pool_initialized_getentropy() == 0)
53 return 0;
54#endif
55#endif
57 return ensure_pool_initialized_poll();