xref: /freebsd/usr.bin/random/randomize_fd.h (revision d0b2dbfa0ecf2bbc9709efc5e20baf8e4b44bbbf)
1 /*
2  * Copyright (C) 2003 Sean Chittenden <seanc@FreeBSD.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 #ifndef __RANDOMIZE_FD__
28 #define __RANDOMIZE_FD__
29 
30 #define RANDOM_TYPE_UNSET 0
31 #define RANDOM_TYPE_LINES 1
32 #define RANDOM_TYPE_WORDS 2
33 
34 /* The multiple instance single integer key */
35 struct rand_node {
36 	u_char *cp;
37 	u_int len;
38 	struct rand_node *next;
39 };
40 
41 int randomize_fd(int fd, int type, int unique, double denom);
42 
43 /*
44  * Generates a random number uniformly in the range [0.0, 1.0).
45  */
46 static inline double
47 random_unit_float(void)
48 {
49 	static const uint64_t denom = (1ull << 53);
50 	static const uint64_t mask = denom - 1;
51 
52 	uint64_t rand64;
53 
54 	/*
55 	 * arc4random_buf(...) in this use generates integer outputs in [0,
56 	 * UINT64_MAX].
57 	 *
58 	 * The double mantissa only has 53 bits, so we uniformly mask off the
59 	 * high 11 bits and then floating-point divide by 2^53 to achieve a
60 	 * result in [0, 1).
61 	 *
62 	 * We are not allowed to emit 1.0, so denom must be one greater than
63 	 * the possible range of the preceeding step.
64 	 */
65 	arc4random_buf(&rand64, sizeof(rand64));
66 	rand64 &= mask;
67 	return ((double)rand64 / denom);
68 }
69 
70 /*
71  * Returns true with probability 1 / denom (a floating point number >= 1).
72  * Otherwise, returns false.
73  */
74 static inline bool
75 random_uniform_denom(double denom)
76 {
77 	return ((uint64_t)(denom * random_unit_float()) == 0);
78 }
79 #endif
80