Debian Codegraph @

debian/randnum.c

raw symbols SCIP
1 /*
2 * randnum.c -- generate (good) randum numbers.
3 *
4 * Copyright (C) 2001,2002 by Theodore Ts'o
5 *
6 * This file may be distributed under the terms of the GNU Public
7 * License.
8 */
9
10 /** This file is from pwgen package, adapted for gpw */
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 /* Borrowed/adapted from e2fsprogs's UUID generation code */
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 * Generate a random number n, where 0 <= n < max_num, using
44 * /dev/urandom if possible.
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 /* We weren't able to use /dev/random, fail hard */
74
75 fprintf(stderr, "No entropy available!\n");
76 exit(1);
77 }