| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
#include <stdio.h> |
| 13 |
#include <unistd.h> |
| 14 |
#include <stdlib.h> |
| 15 |
#include <sys/types.h> |
| 16 |
#include <sys/time.h> |
| 17 |
#include <sys/stat.h> |
| 18 |
#include <fcntl.h> |
| 19 |
#include <errno.h> |
| 20 |
|
| 21 |
#ifdef HAVE_DRAND48 |
| 22 |
extern double drand48(void); |
| 23 |
#endif |
| 24 |
|
| 25 |
static int get_random_fd(void); |
| 26 |
|
| 27 |
|
| 28 |
static int get_random_fd() |
| 29 |
{ |
| 30 |
struct timeval tv; |
| 31 |
static int fd = -2; |
| 32 |
|
| 33 |
if (fd == -2) { |
| 34 |
gettimeofday(&tv, 0); |
| 35 |
fd = open("/dev/urandom", O_RDONLY); |
| 36 |
if (fd == -1) |
| 37 |
fd = open("/dev/random", O_RDONLY | O_NONBLOCK); |
| 38 |
} |
| 39 |
return fd; |
| 40 |
} |
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
long int pw_random_number(max_num) |
| 47 |
long int max_num; |
| 48 |
{ |
| 49 |
long int rand_num; |
| 50 |
int i, fd = get_random_fd(); |
| 51 |
int lose_counter = 0, nbytes = sizeof(rand_num); |
| 52 |
char *cp = (char *) &rand_num; |
| 53 |
|
| 54 |
if (fd >= 0) { |
| 55 |
while (nbytes > 0) { |
| 56 |
i = read(fd, cp, nbytes); |
| 57 |
if ((i < 0) && |
| 58 |
((errno == EINTR) || (errno == EAGAIN))) |
| 59 |
continue; |
| 60 |
if (i <= 0) { |
| 61 |
if (lose_counter++ == 8) |
| 62 |
break; |
| 63 |
continue; |
| 64 |
} |
| 65 |
nbytes -= i; |
| 66 |
cp += i; |
| 67 |
lose_counter = 0; |
| 68 |
} |
| 69 |
} |
| 70 |
if (nbytes == 0) |
| 71 |
return (rand_num % max_num); |
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
fprintf(stderr, "No entropy available!\n"); |
| 76 |
exit(1); |
| 77 |
} |