1 // Copyright 2013-2014 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, Err};
31 #[cfg(all(target_os = "linux",
32 any(target_arch = "x86_64", target_arch = "x86", target_arch = "arm")))]
33 fn getrandom(buf: &mut [u8]) -> libc::c_long {
35 fn syscall(number: libc::c_long, ...) -> libc::c_long;
38 #[cfg(target_arch = "x86_64")]
39 const NR_GETRANDOM: libc::c_long = 318;
40 #[cfg(target_arch = "x86")]
41 const NR_GETRANDOM: libc::c_long = 355;
42 #[cfg(target_arch = "arm")]
43 const NR_GETRANDOM: libc::c_long = 384;
46 syscall(NR_GETRANDOM, buf.as_mut_ptr(), buf.len(), 0u)
50 #[cfg(not(all(target_os = "linux",
51 any(target_arch = "x86_64", target_arch = "x86", target_arch = "arm"))))]
52 fn getrandom(_buf: &mut [u8]) -> libc::c_long { -1 }
54 fn getrandom_fill_bytes(v: &mut [u8]) {
58 let result = getrandom(v.slice_from_mut(read));
60 let err = errno() as libc::c_int;
61 if err == libc::EINTR {
64 panic!("unexpected getrandom error: {}", err);
67 read += result as uint;
72 fn getrandom_next_u32() -> u32 {
73 let mut buf: [u8; 4] = [0u8; 4];
74 getrandom_fill_bytes(&mut buf);
75 unsafe { mem::transmute::<[u8; 4], u32>(buf) }
78 fn getrandom_next_u64() -> u64 {
79 let mut buf: [u8; 8] = [0u8; 8];
80 getrandom_fill_bytes(&mut buf);
81 unsafe { mem::transmute::<[u8; 8], u64>(buf) }
84 #[cfg(all(target_os = "linux",
85 any(target_arch = "x86_64", target_arch = "x86", target_arch = "arm")))]
86 fn is_getrandom_available() -> bool {
87 use sync::atomic::{AtomicBool, INIT_ATOMIC_BOOL, Relaxed};
89 static GETRANDOM_CHECKED: AtomicBool = INIT_ATOMIC_BOOL;
90 static GETRANDOM_AVAILABLE: AtomicBool = INIT_ATOMIC_BOOL;
92 if !GETRANDOM_CHECKED.load(Relaxed) {
93 let mut buf: [u8; 0] = [];
94 let result = getrandom(&mut buf);
95 let available = if result == -1 {
96 let err = errno() as libc::c_int;
101 GETRANDOM_AVAILABLE.store(available, Relaxed);
102 GETRANDOM_CHECKED.store(true, Relaxed);
105 GETRANDOM_AVAILABLE.load(Relaxed)
109 #[cfg(not(all(target_os = "linux",
110 any(target_arch = "x86_64", target_arch = "x86", target_arch = "arm"))))]
111 fn is_getrandom_available() -> bool { false }
113 /// A random number generator that retrieves randomness straight from
114 /// the operating system. Platform sources:
116 /// - Unix-like systems (Linux, Android, Mac OSX): read directly from
117 /// `/dev/urandom`, or from `getrandom(2)` system call if available.
118 /// - Windows: calls `CryptGenRandom`, using the default cryptographic
119 /// service provider with the `PROV_RSA_FULL` type.
120 /// - iOS: calls SecRandomCopyBytes as /dev/(u)random is sandboxed.
122 /// This does not block.
129 OsReaderRng(ReaderRng<File>),
133 /// Create a new `OsRng`.
134 pub fn new() -> IoResult<OsRng> {
135 if is_getrandom_available() {
136 return Ok(OsRng { inner: OsGetrandomRng });
139 let reader = try!(File::open(&Path::new("/dev/urandom")));
140 let reader_rng = ReaderRng::new(reader);
142 Ok(OsRng { inner: OsReaderRng(reader_rng) })
147 fn next_u32(&mut self) -> u32 {
149 OsGetrandomRng => getrandom_next_u32(),
150 OsReaderRng(ref mut rng) => rng.next_u32(),
153 fn next_u64(&mut self) -> u64 {
155 OsGetrandomRng => getrandom_next_u64(),
156 OsReaderRng(ref mut rng) => rng.next_u64(),
159 fn fill_bytes(&mut self, v: &mut [u8]) {
161 OsGetrandomRng => getrandom_fill_bytes(v),
162 OsReaderRng(ref mut rng) => rng.fill_bytes(v)
168 #[cfg(target_os = "ios")]
177 use result::Result::{Ok};
178 use self::libc::{c_int, size_t};
181 /// A random number generator that retrieves randomness straight from
182 /// the operating system. Platform sources:
184 /// - Unix-like systems (Linux, Android, Mac OSX): read directly from
185 /// `/dev/urandom`, or from `getrandom(2)` system call if available.
186 /// - Windows: calls `CryptGenRandom`, using the default cryptographic
187 /// service provider with the `PROV_RSA_FULL` type.
188 /// - iOS: calls SecRandomCopyBytes as /dev/(u)random is sandboxed.
190 /// This does not block.
191 #[allow(missing_copy_implementations)]
193 // dummy field to ensure that this struct cannot be constructed outside of this module
200 unsafe impl Sync for *const SecRandom {}
202 #[allow(non_upper_case_globals)]
203 static kSecRandomDefault: *const SecRandom = 0 as *const SecRandom;
205 #[link(name = "Security", kind = "framework")]
207 fn SecRandomCopyBytes(rnd: *const SecRandom,
208 count: size_t, bytes: *mut u8) -> c_int;
212 /// Create a new `OsRng`.
213 pub fn new() -> IoResult<OsRng> {
214 Ok(OsRng { _dummy: () })
219 fn next_u32(&mut self) -> u32 {
220 let mut v = [0u8; 4];
221 self.fill_bytes(&mut v);
222 unsafe { mem::transmute(v) }
224 fn next_u64(&mut self) -> u64 {
225 let mut v = [0u8; 8];
226 self.fill_bytes(&mut v);
227 unsafe { mem::transmute(v) }
229 fn fill_bytes(&mut self, v: &mut [u8]) {
231 SecRandomCopyBytes(kSecRandomDefault, v.len() as size_t, v.as_mut_ptr())
234 panic!("couldn't generate random bytes: {}", os::last_os_error());
244 use io::{IoResult, IoError};
249 use result::Result::{Ok, Err};
250 use self::libc::{DWORD, BYTE, LPCSTR, BOOL};
251 use self::libc::types::os::arch::extra::{LONG_PTR};
254 type HCRYPTPROV = LONG_PTR;
256 /// A random number generator that retrieves randomness straight from
257 /// the operating system. Platform sources:
259 /// - Unix-like systems (Linux, Android, Mac OSX): read directly from
260 /// `/dev/urandom`, or from `getrandom(2)` system call if available.
261 /// - Windows: calls `CryptGenRandom`, using the default cryptographic
262 /// service provider with the `PROV_RSA_FULL` type.
263 /// - iOS: calls SecRandomCopyBytes as /dev/(u)random is sandboxed.
265 /// This does not block.
267 hcryptprov: HCRYPTPROV
270 static PROV_RSA_FULL: DWORD = 1;
271 static CRYPT_SILENT: DWORD = 64;
272 static CRYPT_VERIFYCONTEXT: DWORD = 0xF0000000;
274 #[allow(non_snake_case)]
276 fn CryptAcquireContextA(phProv: *mut HCRYPTPROV,
277 pszContainer: LPCSTR,
280 dwFlags: DWORD) -> BOOL;
281 fn CryptGenRandom(hProv: HCRYPTPROV,
283 pbBuffer: *mut BYTE) -> BOOL;
284 fn CryptReleaseContext(hProv: HCRYPTPROV, dwFlags: DWORD) -> BOOL;
288 /// Create a new `OsRng`.
289 pub fn new() -> IoResult<OsRng> {
292 CryptAcquireContextA(&mut hcp, 0 as LPCSTR, 0 as LPCSTR,
294 CRYPT_VERIFYCONTEXT | CRYPT_SILENT)
298 Err(IoError::last_error())
300 Ok(OsRng { hcryptprov: hcp })
306 fn next_u32(&mut self) -> u32 {
307 let mut v = [0u8; 4];
308 self.fill_bytes(&mut v);
309 unsafe { mem::transmute(v) }
311 fn next_u64(&mut self) -> u64 {
312 let mut v = [0u8; 8];
313 self.fill_bytes(&mut v);
314 unsafe { mem::transmute(v) }
316 fn fill_bytes(&mut self, v: &mut [u8]) {
318 CryptGenRandom(self.hcryptprov, v.len() as DWORD,
322 panic!("couldn't generate random bytes: {}", os::last_os_error());
327 impl Drop for OsRng {
330 CryptReleaseContext(self.hcryptprov, 0)
333 panic!("couldn't release context: {}", os::last_os_error());
343 use sync::mpsc::channel;
350 let mut r = OsRng::new().unwrap();
355 let mut v = [0u8; 1000];
356 r.fill_bytes(&mut v);
360 fn test_os_rng_tasks() {
362 let mut txs = vec!();
363 for _ in range(0u, 20) {
364 let (tx, rx) = channel();
367 Thread::spawn(move|| {
368 // wait until all the tasks are ready to go.
371 // deschedule to attempt to interleave things as much
372 // as possible (XXX: is this a good test?)
373 let mut r = OsRng::new().unwrap();
375 let mut v = [0u8; 1000];
377 for _ in range(0u, 100) {
382 r.fill_bytes(&mut v);
388 // start all the tasks
389 for tx in txs.iter() {
390 tx.send(()).unwrap();