diff options
Diffstat (limited to 'src/ot_random.c')
| -rw-r--r-- | src/ot_random.c | 51 |
1 files changed, 51 insertions, 0 deletions
diff --git a/src/ot_random.c b/src/ot_random.c new file mode 100644 index 0000000..43f91bb --- /dev/null +++ b/src/ot_random.c | |||
| @@ -0,0 +1,51 @@ | |||
| 1 | /* This software was written by Dirk Engling <erdgeist@erdgeist.org> | ||
| 2 | It is considered beerware. Prost. Skol. Cheers or whatever. */ | ||
| 3 | |||
| 4 | /* System */ | ||
| 5 | #include <stdint.h> | ||
| 6 | #include <stdlib.h> | ||
| 7 | |||
| 8 | /* Opentracker */ | ||
| 9 | #include "ot_random.h" | ||
| 10 | |||
| 11 | #ifdef WANT_INSECURE_RANDOM_FALLBACK | ||
| 12 | |||
| 13 | #warning WANT_INSECURE_RANDOM_FALLBACK builds without arc4random. UDP connection ids become predictable and announces can be forged. Do not ship this. | ||
| 14 | |||
| 15 | #include <time.h> | ||
| 16 | |||
| 17 | void random_init(void) { | ||
| 18 | #ifdef WANT_DEV_RANDOM | ||
| 19 | srandomdev(); | ||
| 20 | #else | ||
| 21 | srandom(time(NULL)); | ||
| 22 | #endif | ||
| 23 | } | ||
| 24 | |||
| 25 | /* random() yields 31 bits, so one draw can never set the top bit. Combine | ||
| 26 | two of them rather than hand out a value that is quietly half as wide as | ||
| 27 | its type claims. */ | ||
| 28 | uint32_t random_uint32(void) { return ((uint32_t)random() << 16) ^ (uint32_t)random(); } | ||
| 29 | |||
| 30 | void random_bytes(void *buf, size_t len) { | ||
| 31 | uint8_t *out = buf; | ||
| 32 | /* random() leaves the top bit clear and its lowest bits are the weakest, | ||
| 33 | so take a byte from the middle of each draw */ | ||
| 34 | while (len--) | ||
| 35 | *out++ = (uint8_t)(random() >> 8); | ||
| 36 | } | ||
| 37 | |||
| 38 | #else | ||
| 39 | |||
| 40 | #if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__) && !defined(__DragonFly__) && !defined(__APPLE__) && \ | ||
| 41 | !(defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 36))) | ||
| 42 | #include <bsd/stdlib.h> | ||
| 43 | #endif | ||
| 44 | |||
| 45 | void random_init(void) {} | ||
| 46 | |||
| 47 | uint32_t random_uint32(void) { return arc4random(); } | ||
| 48 | |||
| 49 | void random_bytes(void *buf, size_t len) { arc4random_buf(buf, len); } | ||
| 50 | |||
| 51 | #endif | ||
