]> git.lizzy.rs Git - rust.git/blob - src/libstd/rand/os.rs
auto merge of #17654 : gereeter/rust/no-unnecessary-cell, r=alexcrichton
[rust.git] / src / libstd / rand / os.rs
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.
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 //! Interfaces to the operating system provided random number
12 //! generators.
13
14 pub use self::imp::OsRng;
15
16 #[cfg(all(unix, not(target_os = "ios")))]
17 mod imp {
18     use io::{IoResult, File};
19     use path::Path;
20     use rand::Rng;
21     use rand::reader::ReaderRng;
22     use result::{Ok, Err};
23
24     /// A random number generator that retrieves randomness straight from
25     /// the operating system. Platform sources:
26     ///
27     /// - Unix-like systems (Linux, Android, Mac OSX): read directly from
28     ///   `/dev/urandom`.
29     /// - Windows: calls `CryptGenRandom`, using the default cryptographic
30     ///   service provider with the `PROV_RSA_FULL` type.
31     /// - iOS: calls SecRandomCopyBytes as /dev/(u)random is sandboxed
32     /// This does not block.
33     #[cfg(unix)]
34     pub struct OsRng {
35         inner: ReaderRng<File>
36     }
37
38     impl OsRng {
39         /// Create a new `OsRng`.
40         pub fn new() -> IoResult<OsRng> {
41             let reader = try!(File::open(&Path::new("/dev/urandom")));
42             let reader_rng = ReaderRng::new(reader);
43
44             Ok(OsRng { inner: reader_rng })
45         }
46     }
47
48     impl Rng for OsRng {
49         fn next_u32(&mut self) -> u32 {
50             self.inner.next_u32()
51         }
52         fn next_u64(&mut self) -> u64 {
53             self.inner.next_u64()
54         }
55         fn fill_bytes(&mut self, v: &mut [u8]) {
56             self.inner.fill_bytes(v)
57         }
58     }
59 }
60
61 #[cfg(target_os = "ios")]
62 mod imp {
63     extern crate libc;
64
65     use collections::Collection;
66     use io::{IoResult};
67     use kinds::marker;
68     use mem;
69     use os;
70     use rand::Rng;
71     use result::{Ok};
72     use self::libc::{c_int, size_t};
73     use slice::MutableSlice;
74
75     /// A random number generator that retrieves randomness straight from
76     /// the operating system. Platform sources:
77     ///
78     /// - Unix-like systems (Linux, Android, Mac OSX): read directly from
79     ///   `/dev/urandom`.
80     /// - Windows: calls `CryptGenRandom`, using the default cryptographic
81     ///   service provider with the `PROV_RSA_FULL` type.
82     /// - iOS: calls SecRandomCopyBytes as /dev/(u)random is sandboxed
83     /// This does not block.
84     pub struct OsRng {
85         marker: marker::NoCopy
86     }
87
88     #[repr(C)]
89     struct SecRandom;
90
91     static kSecRandomDefault: *const SecRandom = 0 as *const SecRandom;
92
93     #[link(name = "Security", kind = "framework")]
94     extern "C" {
95         fn SecRandomCopyBytes(rnd: *const SecRandom,
96                               count: size_t, bytes: *mut u8) -> c_int;
97     }
98
99     impl OsRng {
100         /// Create a new `OsRng`.
101         pub fn new() -> IoResult<OsRng> {
102             Ok(OsRng {marker: marker::NoCopy} )
103         }
104     }
105
106     impl Rng for OsRng {
107         fn next_u32(&mut self) -> u32 {
108             let mut v = [0u8, .. 4];
109             self.fill_bytes(v);
110             unsafe { mem::transmute(v) }
111         }
112         fn next_u64(&mut self) -> u64 {
113             let mut v = [0u8, .. 8];
114             self.fill_bytes(v);
115             unsafe { mem::transmute(v) }
116         }
117         fn fill_bytes(&mut self, v: &mut [u8]) {
118             let ret = unsafe {
119                 SecRandomCopyBytes(kSecRandomDefault, v.len() as size_t, v.as_mut_ptr())
120             };
121             if ret == -1 {
122                 fail!("couldn't generate random bytes: {}", os::last_os_error());
123             }
124         }
125     }
126 }
127
128 #[cfg(windows)]
129 mod imp {
130     extern crate libc;
131
132     use core_collections::Collection;
133     use io::{IoResult, IoError};
134     use mem;
135     use ops::Drop;
136     use os;
137     use rand::Rng;
138     use result::{Ok, Err};
139     use self::libc::{DWORD, BYTE, LPCSTR, BOOL};
140     use self::libc::types::os::arch::extra::{LONG_PTR};
141     use slice::MutableSlice;
142
143     type HCRYPTPROV = LONG_PTR;
144
145     /// A random number generator that retrieves randomness straight from
146     /// the operating system. Platform sources:
147     ///
148     /// - Unix-like systems (Linux, Android, Mac OSX): read directly from
149     ///   `/dev/urandom`.
150     /// - Windows: calls `CryptGenRandom`, using the default cryptographic
151     ///   service provider with the `PROV_RSA_FULL` type.
152     ///
153     /// This does not block.
154     pub struct OsRng {
155         hcryptprov: HCRYPTPROV
156     }
157
158     static PROV_RSA_FULL: DWORD = 1;
159     static CRYPT_SILENT: DWORD = 64;
160     static CRYPT_VERIFYCONTEXT: DWORD = 0xF0000000;
161
162     #[allow(non_snake_case)]
163     extern "system" {
164         fn CryptAcquireContextA(phProv: *mut HCRYPTPROV,
165                                 pszContainer: LPCSTR,
166                                 pszProvider: LPCSTR,
167                                 dwProvType: DWORD,
168                                 dwFlags: DWORD) -> BOOL;
169         fn CryptGenRandom(hProv: HCRYPTPROV,
170                           dwLen: DWORD,
171                           pbBuffer: *mut BYTE) -> BOOL;
172         fn CryptReleaseContext(hProv: HCRYPTPROV, dwFlags: DWORD) -> BOOL;
173     }
174
175     impl OsRng {
176         /// Create a new `OsRng`.
177         pub fn new() -> IoResult<OsRng> {
178             let mut hcp = 0;
179             let ret = unsafe {
180                 CryptAcquireContextA(&mut hcp, 0 as LPCSTR, 0 as LPCSTR,
181                                      PROV_RSA_FULL,
182                                      CRYPT_VERIFYCONTEXT | CRYPT_SILENT)
183             };
184
185             if ret == 0 {
186                 Err(IoError::last_error())
187             } else {
188                 Ok(OsRng { hcryptprov: hcp })
189             }
190         }
191     }
192
193     impl Rng for OsRng {
194         fn next_u32(&mut self) -> u32 {
195             let mut v = [0u8, .. 4];
196             self.fill_bytes(v);
197             unsafe { mem::transmute(v) }
198         }
199         fn next_u64(&mut self) -> u64 {
200             let mut v = [0u8, .. 8];
201             self.fill_bytes(v);
202             unsafe { mem::transmute(v) }
203         }
204         fn fill_bytes(&mut self, v: &mut [u8]) {
205             let ret = unsafe {
206                 CryptGenRandom(self.hcryptprov, v.len() as DWORD,
207                                v.as_mut_ptr())
208             };
209             if ret == 0 {
210                 fail!("couldn't generate random bytes: {}", os::last_os_error());
211             }
212         }
213     }
214
215     impl Drop for OsRng {
216         fn drop(&mut self) {
217             let ret = unsafe {
218                 CryptReleaseContext(self.hcryptprov, 0)
219             };
220             if ret == 0 {
221                 fail!("couldn't release context: {}", os::last_os_error());
222             }
223         }
224     }
225 }
226
227 #[cfg(test)]
228 mod test {
229     use prelude::*;
230
231     use super::OsRng;
232     use rand::Rng;
233     use task;
234
235     #[test]
236     fn test_os_rng() {
237         let mut r = OsRng::new().unwrap();
238
239         r.next_u32();
240         r.next_u64();
241
242         let mut v = [0u8, .. 1000];
243         r.fill_bytes(v);
244     }
245
246     #[test]
247     fn test_os_rng_tasks() {
248
249         let mut txs = vec!();
250         for _ in range(0u, 20) {
251             let (tx, rx) = channel();
252             txs.push(tx);
253             task::spawn(proc() {
254                 // wait until all the tasks are ready to go.
255                 rx.recv();
256
257                 // deschedule to attempt to interleave things as much
258                 // as possible (XXX: is this a good test?)
259                 let mut r = OsRng::new().unwrap();
260                 task::deschedule();
261                 let mut v = [0u8, .. 1000];
262
263                 for _ in range(0u, 100) {
264                     r.next_u32();
265                     task::deschedule();
266                     r.next_u64();
267                     task::deschedule();
268                     r.fill_bytes(v);
269                     task::deschedule();
270                 }
271             })
272         }
273
274         // start all the tasks
275         for tx in txs.iter() {
276             tx.send(())
277         }
278     }
279 }