netsniff-ng: add packet fanout support
[netsniff-ng.git] / rnd.c
blob8c123abb802997808a0fef90f5e46d75776a4e4b
1 #include <sys/types.h>
2 #include <sys/stat.h>
3 #include <fcntl.h>
4 #include <unistd.h>
6 #include "rnd.h"
7 #include "die.h"
8 #include "ioexact.h"
9 #include "ioops.h"
11 static int fdw = -1;
13 static void randombytes_weak(unsigned char *x, size_t xlen)
15 int ret;
17 if (fdw == -1) {
18 for (;;) {
19 fdw = open(LOW_ENTROPY_SOURCE, O_RDONLY);
20 if (fdw != -1)
21 break;
22 sleep(1);
26 while (xlen > 0) {
27 if (xlen < 1048576)
28 ret = xlen;
29 else
30 ret = 1048576;
32 ret = read(fdw, x, ret);
33 if (ret < 1) {
34 sleep(1);
35 continue;
38 x += ret;
39 xlen -= ret;
43 static void randombytes_strong(unsigned char *x, size_t xlen)
45 int fds, ret;
47 fds = open_or_die(HIG_ENTROPY_SOURCE, O_RDONLY);
49 ret = read_exact(fds, x, xlen, 0);
50 if (ret != (int) xlen)
51 panic("Error reading from entropy source!\n");
53 close(fds);
56 int secrand(void)
58 int ret;
60 randombytes_weak((void *) &ret, sizeof(ret));
62 return ret;
65 void gen_key_bytes(unsigned char *area, size_t len)
67 randombytes_strong(area, len);