summaryrefslogtreecommitdiff
path: root/src/random.c
blob: a35eafd2fa03b7719b96b00860ccade039ee1979 (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
#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;
}