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.
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.
11 //! Interfaces to the operating system provided random number
14 pub use self::imp::OsRng;
16 #[cfg(all(unix, not(target_os = "ios")))]
20 use self::OsRngInner::*;
22 use io::{IoResult, File};
25 use rand::reader::ReaderRng;
26 use result::Result::Ok;
31 #[cfg(all(target_os = "linux",
32 any(target_arch = "x86_64",
35 target_arch = "aarch64",
36 target_arch = "powerpc")))]
37 fn getrandom(buf: &mut [u8]) -> libc::c_long {
39 fn syscall(number: libc::c_long, ...) -> libc::c_long;
42 #[cfg(target_arch = "x86_64")]
43 const NR_GETRANDOM: libc::c_long = 318;
44 #[cfg(target_arch = "x86")]
45 const NR_GETRANDOM: libc::c_long = 355;
46 #[cfg(any(target_arch = "arm", target_arch = "aarch64"))]
47 const NR_GETRANDOM: libc::c_long = 384;
48 #[cfg(target_arch = "powerpc")]
49 const NR_GETRANDOM: libc::c_long = 384;
52 syscall(NR_GETRANDOM, buf.as_mut_ptr(), buf.len(), 0u)
56 #[cfg(not(all(target_os = "linux",
57 any(target_arch = "x86_64",
60 target_arch = "aarch64",
61 target_arch = "powerpc"))))]
62 fn getrandom(_buf: &mut [u8]) -> libc::c_long { -1 }
64 fn getrandom_fill_bytes(v: &mut [u8]) {
68 let result = getrandom(&mut v[read..]);
70 let err = errno() as libc::c_int;
71 if err == libc::EINTR {
74 panic!("unexpected getrandom error: {}", err);
77 read += result as uint;
82 fn getrandom_next_u32() -> u32 {
83 let mut buf: [u8; 4] = [0u8; 4];
84 getrandom_fill_bytes(&mut buf);
85 unsafe { mem::transmute::<[u8; 4], u32>(buf) }
88 fn getrandom_next_u64() -> u64 {
89 let mut buf: [u8; 8] = [0u8; 8];
90 getrandom_fill_bytes(&mut buf);
91 unsafe { mem::transmute::<[u8; 8], u64>(buf) }
94 #[cfg(all(target_os = "linux",
95 any(target_arch = "x86_64",
98 target_arch = "aarch64",
99 target_arch = "powerpc")))]
100 fn is_getrandom_available() -> bool {
101 use sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Ordering};
103 static GETRANDOM_CHECKED: AtomicBool = ATOMIC_BOOL_INIT;
104 static GETRANDOM_AVAILABLE: AtomicBool = ATOMIC_BOOL_INIT;
106 if !GETRANDOM_CHECKED.load(Ordering::Relaxed) {
107 let mut buf: [u8; 0] = [];
108 let result = getrandom(&mut buf);
109 let available = if result == -1 {
110 let err = errno() as libc::c_int;
115 GETRANDOM_AVAILABLE.store(available, Ordering::Relaxed);
116 GETRANDOM_CHECKED.store(true, Ordering::Relaxed);
119 GETRANDOM_AVAILABLE.load(Ordering::Relaxed)
123 #[cfg(not(all(target_os = "linux",
124 any(target_arch = "x86_64",
127 target_arch = "aarch64",
128 target_arch = "powerpc"))))]
129 fn is_getrandom_available() -> bool { false }
131 /// A random number generator that retrieves randomness straight from
132 /// the operating system. Platform sources:
134 /// - Unix-like systems (Linux, Android, Mac OSX): read directly from
135 /// `/dev/urandom`, or from `getrandom(2)` system call if available.
136 /// - Windows: calls `CryptGenRandom`, using the default cryptographic
137 /// service provider with the `PROV_RSA_FULL` type.
138 /// - iOS: calls SecRandomCopyBytes as /dev/(u)random is sandboxed.
140 /// This does not block.
147 OsReaderRng(ReaderRng<File>),
151 /// Create a new `OsRng`.
152 pub fn new() -> IoResult<OsRng> {
153 if is_getrandom_available() {
154 return Ok(OsRng { inner: OsGetrandomRng });
157 let reader = try!(File::open(&Path::new("/dev/urandom")));
158 let reader_rng = ReaderRng::new(reader);
160 Ok(OsRng { inner: OsReaderRng(reader_rng) })
165 fn next_u32(&mut self) -> u32 {
167 OsGetrandomRng => getrandom_next_u32(),
168 OsReaderRng(ref mut rng) => rng.next_u32(),
171 fn next_u64(&mut self) -> u64 {
173 OsGetrandomRng => getrandom_next_u64(),
174 OsReaderRng(ref mut rng) => rng.next_u64(),
177 fn fill_bytes(&mut self, v: &mut [u8]) {
179 OsGetrandomRng => getrandom_fill_bytes(v),
180 OsReaderRng(ref mut rng) => rng.fill_bytes(v)
186 #[cfg(target_os = "ios")]
195 use result::Result::{Ok};
196 use self::libc::{c_int, size_t};
199 /// A random number generator that retrieves randomness straight from
200 /// the operating system. Platform sources:
202 /// - Unix-like systems (Linux, Android, Mac OSX): read directly from
203 /// `/dev/urandom`, or from `getrandom(2)` system call if available.
204 /// - Windows: calls `CryptGenRandom`, using the default cryptographic
205 /// service provider with the `PROV_RSA_FULL` type.
206 /// - iOS: calls SecRandomCopyBytes as /dev/(u)random is sandboxed.
208 /// This does not block.
209 #[allow(missing_copy_implementations)]
211 // dummy field to ensure that this struct cannot be constructed outside of this module
218 unsafe impl Sync for *const SecRandom {}
220 #[allow(non_upper_case_globals)]
221 static kSecRandomDefault: *const SecRandom = 0 as *const SecRandom;
223 #[link(name = "Security", kind = "framework")]
225 fn SecRandomCopyBytes(rnd: *const SecRandom,
226 count: size_t, bytes: *mut u8) -> c_int;
230 /// Create a new `OsRng`.
231 pub fn new() -> IoResult<OsRng> {
232 Ok(OsRng { _dummy: () })
237 fn next_u32(&mut self) -> u32 {
238 let mut v = [0u8; 4];
239 self.fill_bytes(&mut v);
240 unsafe { mem::transmute(v) }
242 fn next_u64(&mut self) -> u64 {
243 let mut v = [0u8; 8];
244 self.fill_bytes(&mut v);
245 unsafe { mem::transmute(v) }
247 fn fill_bytes(&mut self, v: &mut [u8]) {
249 SecRandomCopyBytes(kSecRandomDefault, v.len() as size_t, v.as_mut_ptr())
252 panic!("couldn't generate random bytes: {}", os::last_os_error());
262 use io::{IoResult, IoError};
267 use result::Result::{Ok, Err};
268 use self::libc::{DWORD, BYTE, LPCSTR, BOOL};
269 use self::libc::types::os::arch::extra::{LONG_PTR};
272 type HCRYPTPROV = LONG_PTR;
274 /// A random number generator that retrieves randomness straight from
275 /// the operating system. Platform sources:
277 /// - Unix-like systems (Linux, Android, Mac OSX): read directly from
278 /// `/dev/urandom`, or from `getrandom(2)` system call if available.
279 /// - Windows: calls `CryptGenRandom`, using the default cryptographic
280 /// service provider with the `PROV_RSA_FULL` type.
281 /// - iOS: calls SecRandomCopyBytes as /dev/(u)random is sandboxed.
283 /// This does not block.
285 hcryptprov: HCRYPTPROV
288 static PROV_RSA_FULL: DWORD = 1;
289 static CRYPT_SILENT: DWORD = 64;
290 static CRYPT_VERIFYCONTEXT: DWORD = 0xF0000000;
292 #[allow(non_snake_case)]
294 fn CryptAcquireContextA(phProv: *mut HCRYPTPROV,
295 pszContainer: LPCSTR,
298 dwFlags: DWORD) -> BOOL;
299 fn CryptGenRandom(hProv: HCRYPTPROV,
301 pbBuffer: *mut BYTE) -> BOOL;
302 fn CryptReleaseContext(hProv: HCRYPTPROV, dwFlags: DWORD) -> BOOL;
306 /// Create a new `OsRng`.
307 pub fn new() -> IoResult<OsRng> {
310 CryptAcquireContextA(&mut hcp, 0 as LPCSTR, 0 as LPCSTR,
312 CRYPT_VERIFYCONTEXT | CRYPT_SILENT)
316 Err(IoError::last_error())
318 Ok(OsRng { hcryptprov: hcp })
324 fn next_u32(&mut self) -> u32 {
325 let mut v = [0u8; 4];
326 self.fill_bytes(&mut v);
327 unsafe { mem::transmute(v) }
329 fn next_u64(&mut self) -> u64 {
330 let mut v = [0u8; 8];
331 self.fill_bytes(&mut v);
332 unsafe { mem::transmute(v) }
334 fn fill_bytes(&mut self, v: &mut [u8]) {
336 CryptGenRandom(self.hcryptprov, v.len() as DWORD,
340 panic!("couldn't generate random bytes: {}", os::last_os_error());
345 impl Drop for OsRng {
348 CryptReleaseContext(self.hcryptprov, 0)
351 panic!("couldn't release context: {}", os::last_os_error());
361 use sync::mpsc::channel;
368 let mut r = OsRng::new().unwrap();
373 let mut v = [0u8; 1000];
374 r.fill_bytes(&mut v);
378 fn test_os_rng_tasks() {
380 let mut txs = vec!();
381 for _ in range(0u, 20) {
382 let (tx, rx) = channel();
385 Thread::spawn(move|| {
386 // wait until all the tasks are ready to go.
389 // deschedule to attempt to interleave things as much
390 // as possible (XXX: is this a good test?)
391 let mut r = OsRng::new().unwrap();
393 let mut v = [0u8; 1000];
395 for _ in range(0u, 100) {
400 r.fill_bytes(&mut v);
406 // start all the tasks
407 for tx in txs.iter() {
408 tx.send(()).unwrap();