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 * $FreeBSD$
27 */
28
29/*
30 Build this by going:
31
32cc -g -O0 -pthread -DRANDOM_<alg> -I../.. -lstdthreads -Wall \
33	unit_test.c \
34	yarrow.c \
35	fortuna.c \
36	hash.c \
37	../../crypto/rijndael/rijndael-api-fst.c \
38	../../crypto/rijndael/rijndael-alg-fst.c \
39	../../crypto/sha2/sha256c.c \
40        -lz \
41	-o unit_test
42./unit_test
43
44Where <alg> is YARROW or FORTUNA.
45*/
46
47#include <sys/types.h>
48#include <inttypes.h>
49#include <stdbool.h>
50#include <stdio.h>
51#include <stdlib.h>
52#include <threads.h>
53#include <unistd.h>
54#include <zlib.h>
55
56#include "randomdev.h"
57#include "unit_test.h"
58
59#define	NUM_THREADS	  3
60#define	DEBUG
61
62static volatile int stopseeding = 0;
63
64static __inline void
65check_err(int err, const char *func)
66{
67	if (err != Z_OK) {
68		fprintf(stderr, "Compress error in %s: %d\n", func, err);
69		exit(0);
70	}
71}
72
73void *
74myalloc(void *q, unsigned n, unsigned m)
75{
76	q = Z_NULL;
77	return (calloc(n, m));
78}
79
80void myfree(void *q, void *p)
81{
82	q = Z_NULL;
83	free(p);
84}
85
86size_t
87block_deflate(uint8_t *uncompr, uint8_t *compr, const size_t len)
88{
89	z_stream c_stream;
90	int err;
91
92	if (len == 0)
93		return (0);
94
95	c_stream.zalloc = myalloc;
96	c_stream.zfree = myfree;
97	c_stream.opaque = NULL;
98
99	err = deflateInit(&c_stream, Z_DEFAULT_COMPRESSION);
100	check_err(err, "deflateInit");
101
102	c_stream.next_in  = uncompr;
103	c_stream.next_out = compr;
104	c_stream.avail_in = len;
105	c_stream.avail_out = len*2u +512u;
106
107	while (c_stream.total_in != len && c_stream.total_out < (len*2u + 512u)) {
108		err = deflate(&c_stream, Z_NO_FLUSH);
109#ifdef DEBUG
110		printf("deflate progress: len = %zd  total_in = %lu  total_out = %lu\n", len, c_stream.total_in, c_stream.total_out);
111#endif
112		check_err(err, "deflate(..., Z_NO_FLUSH)");
113	}
114
115	for (;;) {
116		err = deflate(&c_stream, Z_FINISH);
117#ifdef DEBUG
118		printf("deflate    final: len = %zd  total_in = %lu  total_out = %lu\n", len, c_stream.total_in, c_stream.total_out);
119#endif
120		if (err == Z_STREAM_END) break;
121		check_err(err, "deflate(..., Z_STREAM_END)");
122	}
123
124	err = deflateEnd(&c_stream);
125	check_err(err, "deflateEnd");
126
127	return ((size_t)c_stream.total_out);
128}
129
130void
131randomdev_unblock(void)
132{
133
134#if 0
135	if (mtx_trylock(&random_reseed_mtx) == thrd_busy)
136		printf("Mutex held. Good.\n");
137	else {
138		printf("Mutex not held. PANIC!!\n");
139		thrd_exit(0);
140	}
141#endif
142	printf("random: unblocking device.\n");
143}
144
145static int
146RunHarvester(void *arg __unused)
147{
148	int i, r;
149	struct harvest_event e;
150
151	for (i = 0; ; i++) {
152		if (stopseeding)
153			break;
154		if (i % 1000 == 0)
155			printf("Harvest: %d\n", i);
156		r = random()%10;
157		e.he_somecounter = i;
158		*((uint64_t *)e.he_entropy) = random();
159		e.he_size = 8;
160		e.he_bits = random()%4;
161		e.he_destination = i;
162		e.he_source = (i + 3)%7;
163		e.he_next = NULL;
164		random_alg_context.ra_event_processor(&e);
165		usleep(r);
166	}
167
168	printf("Thread #0 ends\n");
169
170	thrd_exit(0);
171
172	return (0);
173}
174
175static int
176ReadCSPRNG(void *threadid)
177{
178	size_t tid, zsize;
179	u_int buffersize;
180	uint8_t *buf, *zbuf;
181	int i;
182#ifdef DEBUG
183	int j;
184#endif
185
186	tid = (size_t)threadid;
187	printf("Thread #%zd starts\n", tid);
188
189	while (!random_alg_context.ra_seeded())
190	{
191		random_alg_context.ra_pre_read();
192		usleep(100);
193	}
194
195	for (i = 0; i < 100000; i++) {
196		buffersize = i + RANDOM_BLOCKSIZE;
197		buffersize -= buffersize%RANDOM_BLOCKSIZE;
198		buf = malloc(buffersize);
199		zbuf = malloc(2*i + 1024);
200		if (i % 1000 == 0)
201			printf("Thread read %zd - %d\n", tid, i);
202		if (buf != NULL && zbuf != NULL) {
203			random_alg_context.ra_pre_read();
204			random_alg_context.ra_read(buf, buffersize);
205			zsize = block_deflate(buf, zbuf, i);
206			if (zsize < i)
207				printf("ERROR!! Compressible RNG output!\n");
208#ifdef DEBUG
209			printf("RNG output:\n");
210			for (j = 0; j < i; j++) {
211				printf(" %02X", buf[j]);
212				if (j % 32 == 31 || j == i - 1)
213					printf("\n");
214			}
215			printf("Compressed output:\n");
216			for (j = 0; j < zsize; j++) {
217				printf(" %02X", zbuf[j]);
218				if (j % 32 == 31 || j == zsize - 1)
219					printf("\n");
220			}
221#endif
222			free(zbuf);
223			free(buf);
224		}
225		usleep(100);
226	}
227
228	printf("Thread #%zd ends\n", tid);
229
230	thrd_exit(0);
231
232	return (0);
233}
234
235int
236main(int argc, char *argv[])
237{
238	thrd_t threads[NUM_THREADS];
239	int rc;
240	long t;
241
242	random_alg_context.ra_init_alg(NULL);
243
244	for (t = 0; t < NUM_THREADS; t++) {
245		printf("In main: creating thread %ld\n", t);
246		rc = thrd_create(&threads[t], (t == 0 ? RunHarvester : ReadCSPRNG), NULL);
247		if (rc != thrd_success) {
248			printf("ERROR; return code from thrd_create() is %d\n", rc);
249			exit(-1);
250		}
251	}
252
253	for (t = 2; t < NUM_THREADS; t++)
254		thrd_join(threads[t], &rc);
255
256	stopseeding = 1;
257
258	thrd_join(threads[1], &rc);
259	thrd_join(threads[0], &rc);
260
261	random_alg_context.ra_deinit_alg(NULL);
262
263	/* Last thing that main() should do */
264	thrd_exit(0);
265
266	return (0);
267}
268