forked from 8l/qbe
-
Notifications
You must be signed in to change notification settings - Fork 1
/
random.c
63 lines (52 loc) · 901 Bytes
/
random.c
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
#include <stdio.h>
#include "all.h"
static FILE *urandom = NULL;
/* Returns -1 on error */
int
openrnd()
{
if (urandom != NULL) {
fprintf(stderr, "Warning: /dev/urandom already opened! Closing...\n");
if (closernd() != 0) {
return -1;
}
}
urandom = fopen("/dev/urandom", "r");
if (urandom == NULL) {
fprintf(stderr, "Error opening /dev/urandom:\n");
perror(__func__);
urandom = NULL;
return -1;
}
return 0;
}
int
closernd()
{
if (urandom == NULL)
return 0;
int res;
if (fclose(urandom) != 0) {
// FAIL
fprintf(stderr, "Error closing /dev/urandom:\n");
perror(__func__);
res = -1;
} else {
res = 0;
}
urandom = NULL;
return res;
}
int
get_random_0to3()
{
if (urandom == NULL) {
return -1;
}
int rnd = 0;
size_t size = fread(&rnd, sizeof(int), 1, urandom);
if (size < 1) {
return -1;
}
return rnd % 4;
}