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