1405. [func] Use arc4random() if available.

This commit is contained in:
Mark Andrews
2003-08-25 05:06:11 +00:00
parent 6aba9ae3cb
commit 43e2d66621
7 changed files with 159 additions and 13 deletions

View File

@@ -15,13 +15,14 @@
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/* $Id: rdataset.c,v 1.58.2.2.2.4 2003/08/14 04:25:08 marka Exp $ */
/* $Id: rdataset.c,v 1.58.2.2.2.5 2003/08/25 05:06:10 marka Exp $ */
#include <config.h>
#include <stdlib.h>
#include <isc/buffer.h>
#include <isc/random.h>
#include <isc/util.h>
#include <dns/name.h>
@@ -370,7 +371,10 @@ towiresorted(dns_rdataset_t *rdataset, dns_name_t *owner_name,
*/
for (i = 0; i < count; i++) {
dns_rdata_t rdata;
choice = i + (((u_int)rand()>>3) % (count - i));
isc_uint32_t val;
isc_random_get(&val);
choice = i + (val % (count - i));
rdata = shuffled[i];
shuffled[i] = shuffled[choice];
shuffled[choice] = rdata;
@@ -385,7 +389,11 @@ towiresorted(dns_rdataset_t *rdataset, dns_name_t *owner_name,
/*
* "Cyclic" order.
*/
unsigned int j = (((unsigned int)rand()) >> 3) % count;
isc_uint32_t val;
unsigned int j;
isc_random_get(&val);
j = val % count;
for (i = 0; i < count; i++) {
if (order != NULL)
sorted[j].key = (*order)(&shuffled[i],

View File

@@ -15,7 +15,7 @@
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/* $Id: random.c,v 1.15 2001/01/09 21:56:22 bwelling Exp $ */
/* $Id: random.c,v 1.15.74.1 2003/08/25 05:06:11 marka Exp $ */
#include <config.h>
@@ -33,7 +33,17 @@ static isc_once_t once = ISC_ONCE_INIT;
static void
initialize_rand(void)
{
srand(time(NULL));
#ifndef HAVE_ARC4RANDOM
unsigned int pid = getpid();
/*
* The low bits of pid generally change faster.
* Xor them with the high bits of time which change slowly.
*/
pid = ((pid << 16) & 0xffff0000) | ((pid >> 16) & 0xffff);
srand(time(NULL) ^ pid);
#endif
}
static void
@@ -47,7 +57,11 @@ isc_random_seed(isc_uint32_t seed)
{
initialize();
#ifndef HAVE_ARC4RANDOM
srand(seed);
#else
arc4random_addrandom((u_char *) &seed, sizeof(isc_uint32_t));
#endif
}
void
@@ -57,7 +71,15 @@ isc_random_get(isc_uint32_t *val)
initialize();
*val = rand();
#ifndef HAVE_ARC4RANDOM
/*
* rand()'s lower bits are not random.
* rand()'s upper bit is zero.
*/
*val = ((rand() >> 4) & 0xffff) | ((rand() << 12) & 0xffff0000) ;
#else
*val = arc4random();
#endif
}
isc_uint32_t
@@ -66,5 +88,9 @@ isc_random_jitter(isc_uint32_t max, isc_uint32_t jitter) {
if (jitter == 0)
return (max);
else
#ifndef HAVE_ARC4RANDOM
return (max - rand() % jitter);
#else
return (max - arc4random() % jitter);
#endif
}