Replace getrandom() with getentropy()
[tinc] / src / random.c
1 #include "system.h"
2
3 #include "random.h"
4
5 #ifndef HAVE_GETENTROPY
6 static int random_fd = -1;
7 #endif
8
9 void random_init(void) {
10 #ifndef HAVE_GETENTROPY
11         random_fd = open("/dev/urandom", O_RDONLY);
12
13         if(random_fd < 0) {
14                 random_fd = open("/dev/random", O_RDONLY);
15         }
16
17         if(random_fd < 0) {
18                 fprintf(stderr, "Could not open source of random numbers: %s\n", strerror(errno));
19                 abort();
20         }
21
22 #endif
23 }
24
25 void random_exit(void) {
26 #ifndef HAVE_GETENTROPY
27         close(random_fd);
28 #endif
29 }
30
31 void randomize(void *vout, size_t outlen) {
32         uint8_t *out = vout;
33
34         while(outlen) {
35 #ifdef HAVE_GETENTROPY
36                 int reqlen = (int) MIN(256, outlen);
37                 int len = !getentropy(out, reqlen) ? reqlen : -1;
38 #else
39                 ssize_t len = read(random_fd, out, outlen);
40 #endif
41
42                 if(len <= 0) {
43                         if(len == -1 && (errno == EAGAIN || errno == EINTR)) {
44                                 continue;
45                         }
46
47                         fprintf(stderr, "Could not read random numbers: %s\n", strerror(errno));
48                         abort();
49                 }
50
51                 out += len;
52                 outlen -= len;
53         }
54 }