1/*-
2 * Copyright (c) 2000-2015 Mark R V Murray
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer
10 *    in this position and unchanged.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 *    notice, this list of conditions and the following disclaimer in the
13 *    documentation and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 */
26
27/*
28 Build this by going:
29
30cc -g -O0 -pthread -DRANDOM_<alg> -I../.. -lstdthreads -Wall \
31	unit_test.c \
32	fortuna.c \
33	hash.c \
34	../../crypto/rijndael/rijndael-api-fst.c \
35	../../crypto/rijndael/rijndael-alg-fst.c \
36	../../crypto/sha2/sha256c.c \
37        -lz \
38	-o unit_test
39./unit_test
40
41Where <alg> is FORTUNA. The parameterisation is a leftover from
42when Yarrow was an option, and remains to enable the testing of
43possible future algorithms.
44*/
45
46#include <sys/types.h>
47#include <inttypes.h>
48#include <stdbool.h>
49#include <stdio.h>
50#include <stdlib.h>
51#include <threads.h>
52#include <unistd.h>
53#include <zlib.h>
54
55#include "randomdev.h"
56#include "unit_test.h"
57
58#define	NUM_THREADS	  3
59#define	DEBUG
60
61static volatile int stopseeding = 0;
62
63static __inline void
64check_err(int err, const char *func)
65{
66	if (err != Z_OK) {
67		fprintf(stderr, "Compress error in %s: %d\n", func, err);
68		exit(0);
69	}
70}
71
72void *
73myalloc(void *q, unsigned n, unsigned m)
74{
75	q = Z_NULL;
76	return (calloc(n, m));
77}
78
79void myfree(void *q, void *p)
80{
81	q = Z_NULL;
82	free(p);
83}
84
85size_t
86block_deflate(uint8_t *uncompr, uint8_t *compr, const size_t len)
87{
88	z_stream c_stream;
89	int err;
90
91	if (len == 0)
92		return (0);
93
94	c_stream.zalloc = myalloc;
95	c_stream.zfree = myfree;
96	c_stream.opaque = NULL;
97
98	err = deflateInit(&c_stream, Z_DEFAULT_COMPRESSION);
99	check_err(err, "deflateInit");
100
101	c_stream.next_in  = uncompr;
102	c_stream.next_out = compr;
103	c_stream.avail_in = len;
104	c_stream.avail_out = len*2u +512u;
105
106	while (c_stream.total_in != len && c_stream.total_out < (len*2u + 512u)) {
107		err = deflate(&c_stream, Z_NO_FLUSH);
108#ifdef DEBUG
109		printf("deflate progress: len = %zd  total_in = %lu  total_out = %lu\n", len, c_stream.total_in, c_stream.total_out);
110#endif
111		check_err(err, "deflate(..., Z_NO_FLUSH)");
112	}
113
114	for (;;) {
115		err = deflate(&c_stream, Z_FINISH);
116#ifdef DEBUG
117		printf("deflate    final: len = %zd  total_in = %lu  total_out = %lu\n", len, c_stream.total_in, c_stream.total_out);
118#endif
119		if (err == Z_STREAM_END) break;
120		check_err(err, "deflate(..., Z_STREAM_END)");
121	}
122
123	err = deflateEnd(&c_stream);
124	check_err(err, "deflateEnd");
125
126	return ((size_t)c_stream.total_out);
127}
128
129void
130randomdev_unblock(void)
131{
132
133#if 0
134	if (mtx_trylock(&random_reseed_mtx) == thrd_busy)
135		printf("Mutex held. Good.\n");
136	else {
137		printf("Mutex not held. PANIC!!\n");
138		thrd_exit(0);
139	}
140#endif
141	printf("random: unblocking device.\n");
142}
143
144static int
145RunHarvester(void *arg __unused)
146{
147	int i, r;
148	struct harvest_event e;
149
150	for (i = 0; ; i++) {
151		if (stopseeding)
152			break;
153		if (i % 1000 == 0)
154			printf("Harvest: %d\n", i);
155		r = random()%10;
156		e.he_somecounter = i;
157		*((uint64_t *)e.he_entropy) = random();
158		e.he_size = 8;
159		e.he_destination = i;
160		e.he_source = (i + 3)%7;
161		e.he_next = NULL;
162		random_alg_context.ra_event_processor(&e);
163		usleep(r);
164	}
165
166	printf("Thread #0 ends\n");
167
168	thrd_exit(0);
169
170	return (0);
171}
172
173static int
174ReadCSPRNG(void *threadid)
175{
176	size_t tid, zsize;
177	u_int buffersize;
178	uint8_t *buf, *zbuf;
179	int i;
180#ifdef DEBUG
181	int j;
182#endif
183
184	tid = (size_t)threadid;
185	printf("Thread #%zd starts\n", tid);
186
187	while (!random_alg_context.ra_seeded())
188	{
189		random_alg_context.ra_pre_read();
190		usleep(100);
191	}
192
193	for (i = 0; i < 100000; i++) {
194		buffersize = i + RANDOM_BLOCKSIZE;
195		buffersize -= buffersize%RANDOM_BLOCKSIZE;
196		buf = malloc(buffersize);
197		zbuf = malloc(2*i + 1024);
198		if (i % 1000 == 0)
199			printf("Thread read %zd - %d\n", tid, i);
200		if (buf != NULL && zbuf != NULL) {
201			random_alg_context.ra_pre_read();
202			random_alg_context.ra_read(buf, buffersize);
203			zsize = block_deflate(buf, zbuf, i);
204			if (zsize < i)
205				printf("ERROR!! Compressible RNG output!\n");
206#ifdef DEBUG
207			printf("RNG output:\n");
208			for (j = 0; j < i; j++) {
209				printf(" %02X", buf[j]);
210				if (j % 32 == 31 || j == i - 1)
211					printf("\n");
212			}
213			printf("Compressed output:\n");
214			for (j = 0; j < zsize; j++) {
215				printf(" %02X", zbuf[j]);
216				if (j % 32 == 31 || j == zsize - 1)
217					printf("\n");
218			}
219#endif
220			free(zbuf);
221			free(buf);
222		}
223		usleep(100);
224	}
225
226	printf("Thread #%zd ends\n", tid);
227
228	thrd_exit(0);
229
230	return (0);
231}
232
233int
234main(int argc, char *argv[])
235{
236	thrd_t threads[NUM_THREADS];
237	int rc;
238	long t;
239
240	random_alg_context.ra_init_alg(NULL);
241
242	for (t = 0; t < NUM_THREADS; t++) {
243		printf("In main: creating thread %ld\n", t);
244		rc = thrd_create(&threads[t], (t == 0 ? RunHarvester : ReadCSPRNG), NULL);
245		if (rc != thrd_success) {
246			printf("ERROR; return code from thrd_create() is %d\n", rc);
247			exit(-1);
248		}
249	}
250
251	for (t = 2; t < NUM_THREADS; t++)
252		thrd_join(threads[t], &rc);
253
254	stopseeding = 1;
255
256	thrd_join(threads[1], &rc);
257	thrd_join(threads[0], &rc);
258
259	random_alg_context.ra_deinit_alg(NULL);
260
261	/* Last thing that main() should do */
262	thrd_exit(0);
263
264	return (0);
265}
266