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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
|
#include "config.h"
#include <assert.h>
#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "logerr.h"
#include "util.h"
#include "random.h"
struct Random {
FILE *const file_handle;
};
int
urandom_bytes(const size_t n, uint8_t (*const addr)[]) {
int rc = -1;
uint8_t *ret = NULL;
FILE *f = NULL;
ret = malloc(n);
if (ret == NULL) {
logerr("malloc(): %s", strerror(errno));
goto out;
}
f = fopen("/dev/urandom", "r");
if (f == NULL) {
logerr("fopen(): %s", strerror(errno));
goto out;
}
const size_t read_count = fread(ret, 1U, n, f);
if (ferror(f)) {
logerr("fread(): %s", strerror(errno));
goto out;
}
assert(read_count == n);
if (fclose(f)) {
logerr("fclose(): %s", strerror(errno));
goto out;
}
f = NULL;
memcpy(addr, ret, n);
rc = 0;
out:
if (f != NULL) {
if (fclose(f)) {
logerr("fclose(): %s", strerror(errno));
rc = -1;
}
}
if (ret != NULL) {
freeit((void *)&ret);
}
return rc;
}
int
random_generate(
const struct Random *const r,
const size_t length,
uint8_t (*const out)[]
) {
int rc = -1;
const size_t read_count = fread(out, 1U, length, r->file_handle);
if (ferror(r->file_handle)) {
logerr("fread(): %s", strerror(errno));
goto out;
}
assert(read_count == length);
rc = 0;
out:
return rc;
}
int
random_new(const struct Random **const out) {
int rc = -1;
const struct Random *ret = NULL;
FILE *f = NULL;
ret = malloc(sizeof(*ret));
if (ret == NULL) {
logerr("malloc(): %s", strerror(errno));
goto out;
}
f = fopen("/dev/urandom", "r");
if (f == NULL) {
logerr("fopen(): %s", strerror(errno));
goto out;
}
memcpy((void *)ret, &(struct Random) {
.file_handle = f,
}, sizeof(*ret));
*out = ret;
rc = 0;
out:
if (rc) {
random_free(&ret);
}
return rc;
}
int
random_free(const struct Random **const r) {
if (r == NULL) {
return 0;
}
if (*r == NULL) {
return 0;
}
int rc = -1;
if (fclose((*r)->file_handle)) {
logerr("fclose(): %s", strerror(errno));
goto out;
}
rc = 0;
out:
freeit((void *)r);
return rc;
}
|