stun: add header file
[netsniff-ng.git] / rnd.c
blobad321753e02112e92ad06018320d1d3ab9af3b9b
1 #include <sys/types.h>
2 #include <sys/stat.h>
3 #include <fcntl.h>
4 #include <unistd.h>
6 #include "rnd.h"
8 static int fd_rnd = -1;
10 static void randombytes(unsigned char *x, unsigned long long xlen)
12 int ret;
14 if (fd_rnd == -1) {
15 for (;;) {
16 fd_rnd = open("/dev/urandom", O_RDONLY);
17 if (fd_rnd != -1)
18 break;
19 sleep(1);
23 while (xlen > 0) {
24 if (xlen < 1048576)
25 ret = xlen;
26 else
27 ret = 1048576;
29 ret = read(fd_rnd, x, ret);
30 if (ret < 1) {
31 sleep(1);
32 continue;
35 x += ret;
36 xlen -= ret;
40 /* Note: it's not really secure, but the name only suggests it's better to use
41 * than rand(3) when transferring bytes over the network in non-security
42 * critical structure members. secrand() is only used to fill up salts actually.
44 int secrand(void)
46 int ret;
47 randombytes((void *) &ret, sizeof(ret));
48 return ret;