1 /* $NetBSD: random.c,v 1.5 2014/12/10 04:37:59 christos Exp $ */
4 * Copyright (C) 2004, 2005, 2007, 2009, 2013, 2014 Internet Systems Consortium, Inc. ("ISC")
5 * Copyright (C) 1999-2003 Internet Software Consortium.
7 * Permission to use, copy, modify, and/or distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
11 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
12 * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
13 * AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
14 * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
15 * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
16 * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
17 * PERFORMANCE OF THIS SOFTWARE.
20 /* Id: random.c,v 1.28 2009/07/16 05:52:46 marka Exp */
27 #include <time.h> /* Required for time(). */
28 #ifdef HAVE_SYS_TYPES_H
29 #include <sys/types.h>
35 #include <isc/mutex.h>
37 #include <isc/random.h>
38 #include <isc/string.h>
41 static isc_once_t once
= ISC_ONCE_INIT
;
46 #ifndef HAVE_ARC4RANDOM
47 unsigned int pid
= getpid();
50 * The low bits of pid generally change faster.
51 * Xor them with the high bits of time which change slowly.
53 pid
= ((pid
<< 16) & 0xffff0000) | ((pid
>> 16) & 0xffff);
55 srand((unsigned)time(NULL
) ^ pid
);
62 RUNTIME_CHECK(isc_once_do(&once
, initialize_rand
) == ISC_R_SUCCESS
);
66 isc_random_seed(isc_uint32_t seed
)
70 #ifndef HAVE_ARC4RANDOM
72 #elif defined(HAVE_ARC4RANDOM_ADDRANDOM)
73 arc4random_addrandom((u_char
*) &seed
, sizeof(isc_uint32_t
));
76 * If arcrandom() is available and no corresponding seeding
77 * function arc4random_addrandom() is available, no seeding is
78 * done on such platforms (e.g., OpenBSD 5.5). This is because
79 * the OS itself is supposed to seed the RNG and it is assumed
80 * that no explicit seeding is required.
86 isc_random_get(isc_uint32_t
*val
)
92 #ifndef HAVE_ARC4RANDOM
94 * rand()'s lower bits are not random.
95 * rand()'s upper bit is zero.
97 #if RAND_MAX >= 0xfffff
98 /* We have at least 20 bits. Use lower 16 excluding lower most 4 */
99 *val
= ((rand() >> 4) & 0xffff) | ((rand() << 12) & 0xffff0000);
100 #elif RAND_MAX >= 0x7fff
101 /* We have at least 15 bits. Use lower 10/11 excluding lower most 4 */
102 *val
= ((rand() >> 4) & 0x000007ff) | ((rand() << 7) & 0x003ff800) |
103 ((rand() << 18) & 0xffc00000);
105 #error RAND_MAX is too small
113 isc_random_jitter(isc_uint32_t max
, isc_uint32_t jitter
) {
116 REQUIRE(jitter
< max
|| (jitter
== 0 && max
== 0));
121 isc_random_get(&rnd
);
122 return (max
- rnd
% jitter
);