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
142
|
/* See LICENSE file for copyright and license details. */
#include "common.h"
#ifndef TEST
int
librecrypt_fill_with_random_(void *out, size_t n, ssize_t (*rng)(void *out, size_t n, void *user), void *user)
{
char *buf = out;
ssize_t r;
if (!rng)
rng = &librecrypt_rng_;
while (n) {
r = (*rng)(buf, n, user);
if (r <= 0) {
if (!r)
abort();
return -1;
}
buf = &buf[(size_t)r];
n -= (size_t)r;
}
return 0;
}
#else
static ssize_t
zero(void *out, size_t n, void *user)
{
(void) user;
memset(out, 0, n);
return (ssize_t)n;
}
static ssize_t
seq(void *out, size_t n, void *user)
{
unsigned char *restrict buf = out;
unsigned char *restrict num = user;
size_t i;
if (n > 64u)
n = 64u;
for (i = 0u; i < n; i++)
buf[i] = (*num)++;
return (ssize_t)n;
}
static ssize_t
next(void *out, size_t n, void *user)
{
unsigned char *restrict buf = out;
unsigned char *restrict num = user;
assert(n);
*buf = (*num)++;
return 1;
}
static ssize_t
failer(void *out, size_t n, void *user)
{
(void) out;
(void) n;
(void) user;
errno = EDOM;
return -1;
}
static ssize_t
zero_ret(void *out, size_t n, void *user)
{
(void) out;
(void) n;
(void) user;
return 0;
}
int
main(void)
{
unsigned char buf1[1024u];
unsigned char buf2[sizeof(buf1)];
unsigned char s;
size_t i;
int rv = 0;
INIT_TEST_ABORT();
SET_UP_ALARM();
EXPECT(librecrypt_fill_with_random_(buf1, sizeof(buf1), NULL, NULL) == 0);
EXPECT(librecrypt_fill_with_random_(buf2, sizeof(buf1), NULL, NULL) == 0);
EXPECT(memcmp(buf1, buf2, sizeof(buf1)));
memset(buf1, 99, sizeof(buf1));
errno = 0;
EXPECT(librecrypt_fill_with_random_(buf1, sizeof(buf1), &zero, NULL) == 0);
EXPECT(errno == 0);
for (s = 0u, i = 0u; i < sizeof(buf1); i++, s++)
EXPECT(!buf1[i]);
memset(buf1, 99, sizeof(buf1));
s = 0u;
errno = 0;
EXPECT(librecrypt_fill_with_random_(buf1, sizeof(buf1), &seq, &s) == 0);
EXPECT(errno == 0);
for (s = 0u, i = 0u; i < sizeof(buf1); i++, s++)
EXPECT(buf1[i] == s);
memset(buf1, 99, sizeof(buf1));
s = 0u;
errno = 0;
EXPECT(librecrypt_fill_with_random_(buf1, sizeof(buf1), &next, &s) == 0);
EXPECT(errno == 0);
for (s = 0u, i = 0u; i < sizeof(buf1); i++, s++)
EXPECT(buf1[i] == s);
memset(buf1, 99, sizeof(buf1));
s = 0u;
errno = 0;
EXPECT(librecrypt_fill_with_random_(buf1, sizeof(buf1), &failer, NULL) == -1);
EXPECT(errno == EDOM);
for (s = 0u, i = 0u; i < sizeof(buf1); i++, s++)
EXPECT(buf1[i] == 99);
EXPECT_ABORT(rv = librecrypt_fill_with_random_(buf1, sizeof(buf1), &zero_ret, NULL));
return rv;
}
#endif
|