summaryrefslogtreecommitdiff
path: root/ot_random.c
blob: 3fae87683f2e1d62cb715e774625edb43802149a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
   It is considered beerware. Prost. Skol. Cheers or whatever.

   $id$ */

/* System */
#include <stdint.h>
#include <stdlib.h>

/* 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 <time.h>

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 <bsd/stdlib.h>
#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