Add BIND 9.2.4rc7.
[dragonfly.git] / contrib / bind-9.2.4rc7 / lib / isc / random.c
blob50be302a66305e0e370d4e334d5a15ab5013b3c4
1 /*
2 * Copyright (C) 2004 Internet Systems Consortium, Inc. ("ISC")
3 * Copyright (C) 1999-2001, 2003 Internet Software Consortium.
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
9 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
10 * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11 * AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
12 * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13 * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
14 * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15 * PERFORMANCE OF THIS SOFTWARE.
18 /* $Id: random.c,v 1.15.2.5 2004/03/09 06:11:50 marka Exp $ */
20 #include <config.h>
22 #include <stdlib.h>
23 #include <time.h> /* Required for time(). */
24 #ifdef HAVE_SYS_TYPES_H
25 #include <sys/types.h>
26 #endif
27 #ifdef HAVE_UNISTD_H
28 #include <unistd.h>
29 #endif
31 #include <isc/mutex.h>
32 #include <isc/once.h>
33 #include <isc/random.h>
34 #include <isc/string.h>
35 #include <isc/util.h>
37 static isc_once_t once = ISC_ONCE_INIT;
39 static void
40 initialize_rand(void)
42 #ifndef HAVE_ARC4RANDOM
43 unsigned int pid = getpid();
46 * The low bits of pid generally change faster.
47 * Xor them with the high bits of time which change slowly.
49 pid = ((pid << 16) & 0xffff0000) | ((pid >> 16) & 0xffff);
51 srand(time(NULL) ^ pid);
52 #endif
55 static void
56 initialize(void)
58 RUNTIME_CHECK(isc_once_do(&once, initialize_rand) == ISC_R_SUCCESS);
61 void
62 isc_random_seed(isc_uint32_t seed)
64 initialize();
66 #ifndef HAVE_ARC4RANDOM
67 srand(seed);
68 #else
69 arc4random_addrandom((u_char *) &seed, sizeof(isc_uint32_t));
70 #endif
73 void
74 isc_random_get(isc_uint32_t *val)
76 REQUIRE(val != NULL);
78 initialize();
80 #ifndef HAVE_ARC4RANDOM
82 * rand()'s lower bits are not random.
83 * rand()'s upper bit is zero.
85 *val = ((rand() >> 4) & 0xffff) | ((rand() << 12) & 0xffff0000) ;
86 #else
87 *val = arc4random();
88 #endif
91 isc_uint32_t
92 isc_random_jitter(isc_uint32_t max, isc_uint32_t jitter) {
93 REQUIRE(jitter < max);
94 if (jitter == 0)
95 return (max);
96 else
97 #ifndef HAVE_ARC4RANDOM
98 return (max - rand() % jitter);
99 #else
100 return (max - arc4random() % jitter);
101 #endif