From ad541c67761b8aa6da1566802c347cac4018d0c2 Mon Sep 17 00:00:00 2001 From: Dirk Engling Date: Mon, 2 Nov 2026 20:50:24 +0100 Subject: Move the build sources into src/ --- src/ot_random.c | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 src/ot_random.c (limited to 'src/ot_random.c') 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 @@ +/* This software was written by Dirk Engling + It is considered beerware. Prost. Skol. Cheers or whatever. */ + +/* System */ +#include +#include + +/* Opentracker */ +#include "ot_random.h" + +#ifdef WANT_INSECURE_RANDOM_FALLBACK + +#warning WANT_INSECURE_RANDOM_FALLBACK builds without arc4random. UDP connection ids become predictable and announces can be forged. Do not ship this. + +#include + +void random_init(void) { +#ifdef WANT_DEV_RANDOM + srandomdev(); +#else + srandom(time(NULL)); +#endif +} + +/* random() yields 31 bits, so one draw can never set the top bit. Combine + two of them rather than hand out a value that is quietly half as wide as + its type claims. */ +uint32_t random_uint32(void) { return ((uint32_t)random() << 16) ^ (uint32_t)random(); } + +void random_bytes(void *buf, size_t len) { + uint8_t *out = buf; + /* random() leaves the top bit clear and its lowest bits are the weakest, + so take a byte from the middle of each draw */ + while (len--) + *out++ = (uint8_t)(random() >> 8); +} + +#else + +#if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__) && !defined(__DragonFly__) && !defined(__APPLE__) && \ + !(defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 36))) +#include +#endif + +void random_init(void) {} + +uint32_t random_uint32(void) { return arc4random(); } + +void random_bytes(void *buf, size_t len) { arc4random_buf(buf, len); } + +#endif -- cgit v1.3