]> git.proxmox.com Git - rustc.git/blame - src/libstd/sys/unix/rand.rs
New upstream version 1.41.1+dfsg1
[rustc.git] / src / libstd / sys / unix / rand.rs
CommitLineData
532ac7d7
XL
1use crate::mem;
2use crate::slice;
9e0c209e 3
abe05a73
XL
4pub fn hashmap_random_keys() -> (u64, u64) {
5 let mut v = (0, 0);
6 unsafe {
60c5eb7d 7 let view = slice::from_raw_parts_mut(&mut v as *mut _ as *mut u8, mem::size_of_val(&v));
abe05a73
XL
8 imp::fill_bytes(view);
9 }
e74abb32 10 v
9e0c209e
SL
11}
12
60c5eb7d
XL
13#[cfg(all(
14 unix,
15 not(target_os = "ios"),
16 not(target_os = "openbsd"),
17 not(target_os = "freebsd"),
18 not(target_os = "netbsd"),
19 not(target_os = "fuchsia"),
20 not(target_os = "redox")
21))]
1a4d82fc 22mod imp {
532ac7d7
XL
23 use crate::fs::File;
24 use crate::io::Read;
1a4d82fc 25
abe05a73 26 #[cfg(any(target_os = "linux", target_os = "android"))]
1a4d82fc 27 fn getrandom(buf: &mut [u8]) -> libc::c_long {
1a4d82fc 28 unsafe {
abe05a73 29 libc::syscall(libc::SYS_getrandom, buf.as_mut_ptr(), buf.len(), libc::GRND_NONBLOCK)
1a4d82fc
JJ
30 }
31 }
32
abe05a73 33 #[cfg(not(any(target_os = "linux", target_os = "android")))]
60c5eb7d
XL
34 fn getrandom_fill_bytes(_buf: &mut [u8]) -> bool {
35 false
36 }
1a4d82fc 37
b7449926 38 #[cfg(any(target_os = "linux", target_os = "android"))]
abe05a73 39 fn getrandom_fill_bytes(v: &mut [u8]) -> bool {
532ac7d7
XL
40 use crate::sync::atomic::{AtomicBool, Ordering};
41 use crate::sys::os::errno;
b7449926
XL
42
43 static GETRANDOM_UNAVAILABLE: AtomicBool = AtomicBool::new(false);
44 if GETRANDOM_UNAVAILABLE.load(Ordering::Relaxed) {
45 return false;
46 }
47
1a4d82fc 48 let mut read = 0;
9cc50fc6 49 while read < v.len() {
85aaf69f 50 let result = getrandom(&mut v[read..]);
1a4d82fc
JJ
51 if result == -1 {
52 let err = errno() as libc::c_int;
53 if err == libc::EINTR {
54 continue;
48663c56
XL
55 } else if err == libc::ENOSYS || err == libc::EPERM {
56 // Fall back to reading /dev/urandom if `getrandom` is not
57 // supported on the current kernel.
58 //
59 // Also fall back in case it is disabled by something like
60 // seccomp or inside of virtual machines.
b7449926
XL
61 GETRANDOM_UNAVAILABLE.store(true, Ordering::Relaxed);
62 return false;
a7813a04 63 } else if err == libc::EAGAIN {
b7449926 64 return false;
1a4d82fc
JJ
65 } else {
66 panic!("unexpected getrandom error: {}", err);
67 }
68 } else {
85aaf69f 69 read += result as usize;
1a4d82fc
JJ
70 }
71 }
b7449926 72 true
1a4d82fc
JJ
73 }
74
abe05a73
XL
75 pub fn fill_bytes(v: &mut [u8]) {
76 // getrandom_fill_bytes here can fail if getrandom() returns EAGAIN,
77 // meaning it would have blocked because the non-blocking pool (urandom)
b7449926 78 // has not initialized in the kernel yet due to a lack of entropy. The
abe05a73
XL
79 // fallback we do here is to avoid blocking applications which could
80 // depend on this call without ever knowing they do and don't have a
b7449926
XL
81 // work around. The PRNG of /dev/urandom will still be used but over a
82 // possibly predictable entropy pool.
83 if getrandom_fill_bytes(v) {
84 return;
1a4d82fc 85 }
1a4d82fc 86
b7449926
XL
87 // getrandom failed because it is permanently or temporarily (because
88 // of missing entropy) unavailable. Open /dev/urandom, read from it,
89 // and close it again.
90 let mut file = File::open("/dev/urandom").expect("failed to open /dev/urandom");
91 file.read_exact(v).expect("failed to read /dev/urandom")
1a4d82fc
JJ
92 }
93}
94
9cc50fc6 95#[cfg(target_os = "openbsd")]
1a4d82fc 96mod imp {
532ac7d7 97 use crate::sys::os::errno;
9cc50fc6 98
abe05a73
XL
99 pub fn fill_bytes(v: &mut [u8]) {
100 // getentropy(2) permits a maximum buffer size of 256 bytes
101 for s in v.chunks_mut(256) {
60c5eb7d 102 let ret = unsafe { libc::getentropy(s.as_mut_ptr() as *mut libc::c_void, s.len()) };
abe05a73
XL
103 if ret == -1 {
104 panic!("unexpected getentropy error: {}", errno());
9cc50fc6
SL
105 }
106 }
107 }
108}
1a4d82fc 109
48663c56
XL
110// On iOS and MacOS `SecRandomCopyBytes` calls `CCRandomCopyBytes` with
111// `kCCRandomDefault`. `CCRandomCopyBytes` manages a CSPRNG which is seeded
112// from `/dev/random` and which runs on its own thread accessed via GCD.
113// This seems needlessly heavyweight for the purposes of generating two u64s
114// once per thread in `hashmap_random_keys`. Therefore `SecRandomCopyBytes` is
115// only used on iOS where direct access to `/dev/urandom` is blocked by the
116// sandbox.
9cc50fc6
SL
117#[cfg(target_os = "ios")]
118mod imp {
532ac7d7
XL
119 use crate::io;
120 use crate::ptr;
e9174d1e 121 use libc::{c_int, size_t};
1a4d82fc 122
e9174d1e 123 enum SecRandom {}
1a4d82fc 124
1a4d82fc 125 #[allow(non_upper_case_globals)]
e9174d1e 126 const kSecRandomDefault: *const SecRandom = ptr::null();
1a4d82fc 127
60c5eb7d
XL
128 extern "C" {
129 fn SecRandomCopyBytes(rnd: *const SecRandom, count: size_t, bytes: *mut u8) -> c_int;
1a4d82fc
JJ
130 }
131
abe05a73 132 pub fn fill_bytes(v: &mut [u8]) {
60c5eb7d 133 let ret = unsafe { SecRandomCopyBytes(kSecRandomDefault, v.len(), v.as_mut_ptr()) };
abe05a73 134 if ret == -1 {
60c5eb7d 135 panic!("couldn't generate random bytes: {}", io::Error::last_os_error());
1a4d82fc
JJ
136 }
137 }
138}
9e0c209e 139
60c5eb7d 140#[cfg(any(target_os = "freebsd", target_os = "netbsd"))]
9e0c209e 141mod imp {
532ac7d7 142 use crate::ptr;
9e0c209e 143
abe05a73
XL
144 pub fn fill_bytes(v: &mut [u8]) {
145 let mib = [libc::CTL_KERN, libc::KERN_ARND];
146 // kern.arandom permits a maximum buffer size of 256 bytes
147 for s in v.chunks_mut(256) {
148 let mut s_len = s.len();
149 let ret = unsafe {
60c5eb7d
XL
150 libc::sysctl(
151 mib.as_ptr(),
152 mib.len() as libc::c_uint,
153 s.as_mut_ptr() as *mut _,
154 &mut s_len,
155 ptr::null(),
156 0,
157 )
abe05a73
XL
158 };
159 if ret == -1 || s_len != s.len() {
60c5eb7d
XL
160 panic!(
161 "kern.arandom sysctl failed! (returned {}, s.len() {}, oldlenp {})",
162 ret,
163 s.len(),
164 s_len
165 );
9e0c209e
SL
166 }
167 }
168 }
169}
c30ab7b3
SL
170
171#[cfg(target_os = "fuchsia")]
172mod imp {
ea8adc8c 173 #[link(name = "zircon")]
60c5eb7d 174 extern "C" {
8faf50e0 175 fn zx_cprng_draw(buffer: *mut u8, len: usize);
c30ab7b3
SL
176 }
177
abe05a73 178 pub fn fill_bytes(v: &mut [u8]) {
8faf50e0 179 unsafe { zx_cprng_draw(v.as_mut_ptr(), v.len()) }
c30ab7b3
SL
180 }
181}
416331ca
XL
182
183#[cfg(target_os = "redox")]
184mod imp {
185 use crate::fs::File;
186 use crate::io::Read;
187
188 pub fn fill_bytes(v: &mut [u8]) {
189 // Open rand:, read from it, and close it again.
190 let mut file = File::open("rand:").expect("failed to open rand:");
191 file.read_exact(v).expect("failed to read rand:")
192 }
193}