1 #include "dact.h"
2 #ifdef TIME_WITH_SYS_TIME
3 #include <sys/time.h>
4 #include <time.h>
5 #else
6 #ifdef HAVE_SYS_TIME_H
7 #include <sys/time.h>
8 #else
9 #include <time.h>
10 #endif
11 #endif
12 #ifdef HAVE_STDLIB_H
13 #include <stdlib.h>
14 #endif
15 #ifdef HAVE_SYS_TYPES_H
16 #include <sys/types.h>
17 #endif
18 #ifdef HAVE_SYS_STAT_H
19 #include <sys/stat.h>
20 #endif
21 #ifdef HAVE_FCNTL_H
22 #include <fcntl.h>
23 #endif
24 #include "random.h"
25 #include "dendian.h"
26 
rnd_init(void)27 rnd_id rnd_init(void) {
28 	int fd;
29 
30 	fd=open("/dev/urandom", O_RDONLY);
31 	if (fd<0) fd=open("/dev/random", O_RDONLY);
32 	return(fd);
33 }
34 
rnd_getrandom(const rnd_id id,const int64_t low,const int64_t high)35 int64_t rnd_getrandom(const rnd_id id, const int64_t low, const int64_t high) {
36 	uint64_t randval=0;
37 	int64_t retval;
38 	ssize_t read_ret;
39 
40 	if (id>=0) {
41 		read_ret=read_de(id, &randval, sizeof(randval), sizeof(randval));
42 		if (read_ret!=sizeof(randval)) randval=0;
43 	}
44 	if (randval==0) {
45 #if defined(HAVE_SRAND48) && defined(HAVE_LRAND48)
46 		srand48(time(NULL)+rand());
47 		randval=lrand48();
48 #else
49 		srand(time(NULL)+rand());
50 		randval=rand();
51 #endif
52 	}
53 
54 	retval=low+(int64_t) ((high-low+1)*rand()/(RAND_MAX+1.0));
55 
56 	return(retval);
57 }
58 
rnd_deinit(const rnd_id id)59 void rnd_deinit(const rnd_id id) {
60 	if (id>=0) close(id);
61 	return;
62 }
63