summaryrefslogtreecommitdiff
path: root/src/random.c
blob: c6da688414a9d9d9b73a8f495d78ef2adae7eea9 (plain) (blame)
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#include "config.h"

#include <assert.h>
#include <errno.h>
#include <stddef.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>

#include "logerr.h"
#include "random.h"


int
urandom_bytes(const size_t n, uint8_t (*const addr)[]) {
	int rc = 0;

	FILE *f = NULL;

	f = fopen("/dev/urandom", "r");
	if (!f) {
		logerr("fopen(\"/dev/urandom\", \"r\"): %s\n", strerror(errno));
		rc = -1;
		goto out;
	}

	const size_t read_count = fread(addr, 1, n, f);
	if (ferror(f)) {
		logerr("fread(addr, 1, n, f): %s\n", strerror(errno));
		rc = -1;
		goto out;
	}
	assert(read_count == n);

out:
	if (f) {
		if (fclose(f)) {
			logerr("fclose(f): %s\n", strerror(errno));
			rc = -1;
		}
	}
	return rc;
}


#ifdef TEST
#include "testing.h"

static int
test_urandom_bytes(void) {
	int rc = 0;

	test_start("urandom_bytes()");

	{
		testing("we get to pick the size that comes out");

		const size_t LEN = 256;
		uint8_t arr[256 /* LEN */] = { 0 };

		for (size_t n = 0; n < LEN; n++) {
			if (urandom_bytes(n, &arr)) {
				logerr("urandom_bytes(n, &arr);\n");
				rc = -1;
				goto out;
			}
			for (size_t i = n; i < LEN; i++) {
				assert(arr[i] == 0);
			}
		}

		test_ok();
	}

	{
		testing("we always get a new value as a result");

		const size_t LEN = 64;
		uint8_t arr1[64 /* LEN */] = { 0 };
		uint8_t arr2[64 /* LEN */] = { 0 };

		if (urandom_bytes(LEN, &arr1)) {
			logerr("urandom_bytes(LEN, &arr1);\n");
			rc = -1;
			goto out;
		}

		const size_t attempts = 10;
		for (size_t n = 0; n < attempts; n++) {
			if (urandom_bytes(LEN, &arr2)) {
				logerr("urandom_bytes(LEN, &arr2);\n");
				rc = -1;
				goto out;
			}
			assert(memcmp(arr1, arr2, LEN) != 0);
		}

		test_ok();
	}

out:
	return rc;
}

int
main(void) {
	int rc = 0;

	if (test_urandom_bytes()) {
		logerr("test_urandom_bytes();\n");
		rc = -1;
		goto out;
	}

out:
	return !!rc;
}
#endif