]> git.proxmox.com Git - rustc.git/blob - src/libstd/sys/unix/rand.rs
New upstream version 1.23.0+dfsg1
[rustc.git] / src / libstd / sys / unix / rand.rs
1 // Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use mem;
12 use slice;
13
14 pub fn hashmap_random_keys() -> (u64, u64) {
15 let mut v = (0, 0);
16 unsafe {
17 let view = slice::from_raw_parts_mut(&mut v as *mut _ as *mut u8,
18 mem::size_of_val(&v));
19 imp::fill_bytes(view);
20 }
21 return v
22 }
23
24 #[cfg(all(unix,
25 not(target_os = "ios"),
26 not(target_os = "openbsd"),
27 not(target_os = "freebsd"),
28 not(target_os = "fuchsia")))]
29 mod imp {
30 use fs::File;
31 use io::Read;
32 use libc;
33 use sys::os::errno;
34
35 #[cfg(any(target_os = "linux", target_os = "android"))]
36 fn getrandom(buf: &mut [u8]) -> libc::c_long {
37 unsafe {
38 libc::syscall(libc::SYS_getrandom, buf.as_mut_ptr(), buf.len(), libc::GRND_NONBLOCK)
39 }
40 }
41
42 #[cfg(not(any(target_os = "linux", target_os = "android")))]
43 fn getrandom(_buf: &mut [u8]) -> libc::c_long { -1 }
44
45 fn getrandom_fill_bytes(v: &mut [u8]) -> bool {
46 let mut read = 0;
47 while read < v.len() {
48 let result = getrandom(&mut v[read..]);
49 if result == -1 {
50 let err = errno() as libc::c_int;
51 if err == libc::EINTR {
52 continue;
53 } else if err == libc::EAGAIN {
54 return false
55 } else {
56 panic!("unexpected getrandom error: {}", err);
57 }
58 } else {
59 read += result as usize;
60 }
61 }
62
63 return true
64 }
65
66 #[cfg(any(target_os = "linux", target_os = "android"))]
67 fn is_getrandom_available() -> bool {
68 use io;
69 use sync::atomic::{AtomicBool, Ordering};
70 use sync::Once;
71
72 static CHECKER: Once = Once::new();
73 static AVAILABLE: AtomicBool = AtomicBool::new(false);
74
75 CHECKER.call_once(|| {
76 let mut buf: [u8; 0] = [];
77 let result = getrandom(&mut buf);
78 let available = if result == -1 {
79 let err = io::Error::last_os_error().raw_os_error();
80 err != Some(libc::ENOSYS)
81 } else {
82 true
83 };
84 AVAILABLE.store(available, Ordering::Relaxed);
85 });
86
87 AVAILABLE.load(Ordering::Relaxed)
88 }
89
90 #[cfg(not(any(target_os = "linux", target_os = "android")))]
91 fn is_getrandom_available() -> bool { false }
92
93 pub fn fill_bytes(v: &mut [u8]) {
94 // getrandom_fill_bytes here can fail if getrandom() returns EAGAIN,
95 // meaning it would have blocked because the non-blocking pool (urandom)
96 // has not initialized in the kernel yet due to a lack of entropy the
97 // fallback we do here is to avoid blocking applications which could
98 // depend on this call without ever knowing they do and don't have a
99 // work around. The PRNG of /dev/urandom will still be used but not
100 // over a completely full entropy pool
101 if is_getrandom_available() && getrandom_fill_bytes(v) {
102 return
103 }
104
105 let mut file = File::open("/dev/urandom")
106 .expect("failed to open /dev/urandom");
107 file.read_exact(v).expect("failed to read /dev/urandom");
108 }
109 }
110
111 #[cfg(target_os = "openbsd")]
112 mod imp {
113 use libc;
114 use sys::os::errno;
115
116 pub fn fill_bytes(v: &mut [u8]) {
117 // getentropy(2) permits a maximum buffer size of 256 bytes
118 for s in v.chunks_mut(256) {
119 let ret = unsafe {
120 libc::getentropy(s.as_mut_ptr() as *mut libc::c_void, s.len())
121 };
122 if ret == -1 {
123 panic!("unexpected getentropy error: {}", errno());
124 }
125 }
126 }
127 }
128
129 #[cfg(target_os = "ios")]
130 mod imp {
131 use io;
132 use libc::{c_int, size_t};
133 use ptr;
134
135 enum SecRandom {}
136
137 #[allow(non_upper_case_globals)]
138 const kSecRandomDefault: *const SecRandom = ptr::null();
139
140 extern {
141 fn SecRandomCopyBytes(rnd: *const SecRandom,
142 count: size_t,
143 bytes: *mut u8) -> c_int;
144 }
145
146 pub fn fill_bytes(v: &mut [u8]) {
147 let ret = unsafe {
148 SecRandomCopyBytes(kSecRandomDefault,
149 v.len(),
150 v.as_mut_ptr())
151 };
152 if ret == -1 {
153 panic!("couldn't generate random bytes: {}",
154 io::Error::last_os_error());
155 }
156 }
157 }
158
159 #[cfg(target_os = "freebsd")]
160 mod imp {
161 use libc;
162 use ptr;
163
164 pub fn fill_bytes(v: &mut [u8]) {
165 let mib = [libc::CTL_KERN, libc::KERN_ARND];
166 // kern.arandom permits a maximum buffer size of 256 bytes
167 for s in v.chunks_mut(256) {
168 let mut s_len = s.len();
169 let ret = unsafe {
170 libc::sysctl(mib.as_ptr(), mib.len() as libc::c_uint,
171 s.as_mut_ptr() as *mut _, &mut s_len,
172 ptr::null(), 0)
173 };
174 if ret == -1 || s_len != s.len() {
175 panic!("kern.arandom sysctl failed! (returned {}, s.len() {}, oldlenp {})",
176 ret, s.len(), s_len);
177 }
178 }
179 }
180 }
181
182 #[cfg(target_os = "fuchsia")]
183 mod imp {
184 #[link(name = "zircon")]
185 extern {
186 fn zx_cprng_draw(buffer: *mut u8, len: usize, actual: *mut usize) -> i32;
187 }
188
189 fn getrandom(buf: &mut [u8]) -> Result<usize, i32> {
190 unsafe {
191 let mut actual = 0;
192 let status = zx_cprng_draw(buf.as_mut_ptr(), buf.len(), &mut actual);
193 if status == 0 {
194 Ok(actual)
195 } else {
196 Err(status)
197 }
198 }
199 }
200
201 pub fn fill_bytes(v: &mut [u8]) {
202 let mut buf = v;
203 while !buf.is_empty() {
204 let ret = getrandom(buf);
205 match ret {
206 Err(err) => {
207 panic!("kernel zx_cprng_draw call failed! (returned {}, buf.len() {})",
208 err, buf.len())
209 }
210 Ok(actual) => {
211 let move_buf = buf;
212 buf = &mut move_buf[(actual as usize)..];
213 }
214 }
215 }
216 }
217 }