Refactor crypto RNG; add getrandom() support
[tinc] / src / random.c
1 #include "system.h"
2
3 #include "random.h"
4
5 #ifndef HAVE_GETRANDOM
6 static int random_fd = -1;
7 #endif
8
9 void random_init(void) {
10 #ifndef HAVE_GETRANDOM
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_GETRANDOM
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_GETRANDOM
36                 ssize_t len = getrandom(out, outlen, 0);
37 #else
38                 ssize_t len = read(random_fd, out, outlen);
39 #endif
40
41                 if(len <= 0) {
42                         if(len == -1 && (errno == EAGAIN || errno == EINTR)) {
43                                 continue;
44                         }
45
46                         fprintf(stderr, "Could not read random numbers: %s\n", strerror(errno));
47                         abort();
48                 }
49
50                 out += len;
51                 outlen -= len;
52         }
53 }