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 $ */
23 #include <time.h> /* Required for time(). */
24 #ifdef HAVE_SYS_TYPES_H
25 #include <sys/types.h>
31 #include <isc/mutex.h>
33 #include <isc/random.h>
34 #include <isc/string.h>
37 static isc_once_t once
= ISC_ONCE_INIT
;
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
);
58 RUNTIME_CHECK(isc_once_do(&once
, initialize_rand
) == ISC_R_SUCCESS
);
62 isc_random_seed(isc_uint32_t seed
)
66 #ifndef HAVE_ARC4RANDOM
69 arc4random_addrandom((u_char
*) &seed
, sizeof(isc_uint32_t
));
74 isc_random_get(isc_uint32_t
*val
)
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) ;
92 isc_random_jitter(isc_uint32_t max
, isc_uint32_t jitter
) {
93 REQUIRE(jitter
< max
);
97 #ifndef HAVE_ARC4RANDOM
98 return (max
- rand() % jitter
);
100 return (max
- arc4random() % jitter
);