]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/rand.rs
Reduce number of syscalls in `rand`
[rust.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 sync::atomic::{AtomicBool, AtomicI32, Ordering};
34     use sys::os::errno;
35
36     static GETRANDOM_URANDOM_FD: AtomicI32 = AtomicI32::new(-1);
37     #[cfg(any(target_os = "linux", target_os = "android"))]
38     static GETRANDOM_UNAVAILABLE: AtomicBool = AtomicBool::new(false);
39
40     #[cfg(any(target_os = "linux", target_os = "android"))]
41     fn is_getrandom_permanently_unavailable() -> bool {
42         GETRANDOM_UNAVAILABLE.load(Ordering::Relaxed)
43     }
44
45     #[cfg(not(any(target_os = "linux", target_os = "android")))]
46     fn is_getrandom_permanently_unavailable() -> bool {
47         true
48     }
49
50     #[cfg(any(target_os = "linux", target_os = "android"))]
51     fn getrandom(buf: &mut [u8]) -> libc::c_long {
52         unsafe {
53             libc::syscall(libc::SYS_getrandom, buf.as_mut_ptr(), buf.len(), libc::GRND_NONBLOCK)
54         }
55     }
56
57     #[cfg(not(any(target_os = "linux", target_os = "android")))]
58     fn getrandom_fill_bytes(_buf: &mut [u8]) -> bool { false }
59
60     #[cfg(any(target_os = "linux", target_os = "android"))]
61     fn getrandom_fill_bytes(v: &mut [u8]) -> bool {
62         if is_getrandom_permanently_unavailable() {
63             return false;
64         }
65
66         let mut read = 0;
67         while read < v.len() {
68             let result = getrandom(&mut v[read..]);
69             if result == -1 {
70                 let err = errno() as libc::c_int;
71                 if err == libc::EINTR {
72                     continue;
73                 } else if err == libc::ENOSYS {
74                     GETRANDOM_UNAVAILABLE.store(true, Ordering::Relaxed);
75                 } else if err == libc::EAGAIN {
76                     return false;
77                 } else {
78                     panic!("unexpected getrandom error: {}", err);
79                 }
80             } else {
81                 read += result as usize;
82             }
83         }
84         true
85     }
86
87     pub fn fill_bytes(v: &mut [u8]) {
88         // getrandom_fill_bytes here can fail if getrandom() returns EAGAIN,
89         // meaning it would have blocked because the non-blocking pool (urandom)
90         // has not initialized in the kernel yet due to a lack of entropy. The
91         // fallback we do here is to avoid blocking applications which could
92         // depend on this call without ever knowing they do and don't have a
93         // work around. The PRNG of /dev/urandom will still be used but over a
94         // possibly predictable entropy pool.
95         if getrandom_fill_bytes(v) {
96             return;
97         }
98
99         // getrandom failed for some reason. If the getrandom call is
100         // permanently unavailable (OS without getrandom, or OS version without
101         // getrandom), we'll keep around the fd for /dev/urandom for future
102         // requests, to avoid re-opening the file on every call.
103         //
104         // Otherwise, open /dev/urandom, read from it, and close it again.
105         use super::super::ext::io::{FromRawFd, IntoRawFd};
106         let mut fd = GETRANDOM_URANDOM_FD.load(Ordering::Relaxed);
107         let mut close_fd = false;
108         if fd == -1 {
109             if !is_getrandom_permanently_unavailable() {
110                 close_fd = true;
111             }
112             let file = File::open("/dev/urandom").expect("failed to open /dev/urandom");
113             fd = file.into_raw_fd();
114             // If some other thread also opened /dev/urandom and set the global
115             // fd already, we close our fd at the end of the function.
116             if !close_fd && GETRANDOM_URANDOM_FD.compare_and_swap(-1, fd, Ordering::Relaxed) != -1 {
117                 close_fd = true;
118             }
119         }
120         let mut file = unsafe { File::from_raw_fd(fd) };
121         let res = file.read_exact(v);
122         if !close_fd {
123             let _ = file.into_raw_fd();
124         }
125         res.expect("failed to read /dev/urandom");
126     }
127 }
128
129 #[cfg(target_os = "openbsd")]
130 mod imp {
131     use libc;
132     use sys::os::errno;
133
134     pub fn fill_bytes(v: &mut [u8]) {
135         // getentropy(2) permits a maximum buffer size of 256 bytes
136         for s in v.chunks_mut(256) {
137             let ret = unsafe {
138                 libc::getentropy(s.as_mut_ptr() as *mut libc::c_void, s.len())
139             };
140             if ret == -1 {
141                 panic!("unexpected getentropy error: {}", errno());
142             }
143         }
144     }
145 }
146
147 #[cfg(target_os = "ios")]
148 mod imp {
149     use io;
150     use libc::{c_int, size_t};
151     use ptr;
152
153     enum SecRandom {}
154
155     #[allow(non_upper_case_globals)]
156     const kSecRandomDefault: *const SecRandom = ptr::null();
157
158     extern {
159         fn SecRandomCopyBytes(rnd: *const SecRandom,
160                               count: size_t,
161                               bytes: *mut u8) -> c_int;
162     }
163
164     pub fn fill_bytes(v: &mut [u8]) {
165         let ret = unsafe {
166             SecRandomCopyBytes(kSecRandomDefault,
167                                v.len(),
168                                v.as_mut_ptr())
169         };
170         if ret == -1 {
171             panic!("couldn't generate random bytes: {}",
172                    io::Error::last_os_error());
173         }
174     }
175 }
176
177 #[cfg(target_os = "freebsd")]
178 mod imp {
179     use libc;
180     use ptr;
181
182     pub fn fill_bytes(v: &mut [u8]) {
183         let mib = [libc::CTL_KERN, libc::KERN_ARND];
184         // kern.arandom permits a maximum buffer size of 256 bytes
185         for s in v.chunks_mut(256) {
186             let mut s_len = s.len();
187             let ret = unsafe {
188                 libc::sysctl(mib.as_ptr(), mib.len() as libc::c_uint,
189                              s.as_mut_ptr() as *mut _, &mut s_len,
190                              ptr::null(), 0)
191             };
192             if ret == -1 || s_len != s.len() {
193                 panic!("kern.arandom sysctl failed! (returned {}, s.len() {}, oldlenp {})",
194                        ret, s.len(), s_len);
195             }
196         }
197     }
198 }
199
200 #[cfg(target_os = "fuchsia")]
201 mod imp {
202     #[link(name = "zircon")]
203     extern {
204         fn zx_cprng_draw(buffer: *mut u8, len: usize);
205     }
206
207     pub fn fill_bytes(v: &mut [u8]) {
208         unsafe { zx_cprng_draw(v.as_mut_ptr(), v.len()) }
209     }
210 }