]> diplodocus.org Git - nmh/blob - sbr/m_rand.c
uip/flist.c: Make locally defined and used functions static.
[nmh] / sbr / m_rand.c
1 /* m_rand.c -- provides pseudorandom bytes
2 *
3 * This code is Copyright (c) 2012, by the authors of nmh. See the
4 * COPYRIGHT file in the root directory of the nmh distribution for
5 * complete copyright information.
6 */
7
8 #include <stdlib.h> /* for abs(), srand(), rand(), arc4random() */
9 #include <stdio.h> /* for fopen(), fread(), fclose() */
10 #include <unistd.h> /* for getpid() */
11 #include <time.h> /* for time() */
12
13 #include <config.h>
14
15 #if !HAVE_ARC4RANDOM
16 static int seeded = 0;
17 #endif
18
19
20 int
21 m_rand (unsigned char *buf, size_t n) {
22 #if !HAVE_ARC4RANDOM
23 if (! seeded) {
24 FILE *devurandom;
25 unsigned int seed;
26
27 if ((devurandom = fopen ("/dev/urandom", "r"))) {
28 if (fread (&seed, sizeof (seed), 1, devurandom) == 1) seeded = 1;
29 fclose (devurandom);
30 }
31
32 if (! seeded) {
33 /* This seed calculation is from Helmut G. Katzgraber, "Random
34 Numbers in Scientific Computing: An Introduction",
35 arXiv:1005.4117v1 [physics.comp-ph], 22 May 2010, p. 19.
36 time() and getpid() shouldn't fail on POSIX platforms. */
37 seed = abs ((int) ((time (0) * 181 * ((getpid ()-83) * 359)) % 104729));
38 seeded = 1;
39 }
40
41 srand (seed);
42 }
43
44 while (n > 0) {
45 int rnd = rand ();
46 unsigned char *rndp = (unsigned char *) &rnd;
47 unsigned int i;
48
49 for (i = 0; i < sizeof rnd && n > 0; ++i, --n) {
50 *buf++ = *rndp++;
51 }
52 }
53 #else
54 arc4random_buf(buf, n);
55 #endif
56
57 return 0;
58 }