1 /*	$OpenBSD: kqueue-random.c,v 1.11 2018/04/26 15:55:14 guenther Exp $	*/
2 /*	Written by Michael Shalayeff, 2002, Public Domain	*/
3 
4 #include <sys/param.h>		/* MIN() */
5 #include <sys/event.h>
6 
7 #include <err.h>
8 #include <fcntl.h>
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <unistd.h>
13 
14 #include "main.h"
15 
16 int
17 do_random(void)
18 {
19 	int n, fd, kq;
20 	struct timespec ts;
21 	struct kevent ev;
22 	u_int32_t buf[BUFSIZ];
23 
24 	ASS((fd = open("/dev/random", O_RDONLY)) >= 0,
25 	    warn("open: /dev/random"));
26 	ASS(fcntl(fd, F_SETFL, O_NONBLOCK) == 0,
27 	    warn("fcntl"));
28 
29 	ASS((kq = kqueue()) >= 0,
30 	    warn("kqueue"));
31 
32 	memset(&ev, 0, sizeof(ev));
33 	ev.ident = fd;
34 	ev.filter = EVFILT_READ;
35 	ev.flags = EV_ADD | EV_ENABLE;
36 	n = kevent(kq, &ev, 1, NULL, 0, NULL);
37 	ASSX(n != -1);
38 
39 	ts.tv_sec = 0;
40 	ts.tv_nsec = 0;
41 	n = kevent(kq, NULL, 0, &ev, 1, &ts);
42 	ASSX(n >= 0);
43 
44 	n = MIN((ev.data + 7) / 8, sizeof(buf));
45 	ASSX(read(fd, buf, n) > 0);
46 
47 	close(kq);
48 	close(fd);
49 
50 	return (0);
51 }
52