]> git.lizzy.rs Git - rust.git/blob - src/libstd/rand/os.rs
Rename all raw pointers as necessary
[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(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::MutableVector;
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     struct SecRandom;
89
90     static kSecRandomDefault: *const SecRandom = 0 as *const SecRandom;
91
92     #[link(name = "Security", kind = "framework")]
93     extern "C" {
94         fn SecRandomCopyBytes(rnd: *const SecRandom,
95                               count: size_t, bytes: *mut u8) -> c_int;
96     }
97
98     impl OsRng {
99         /// Create a new `OsRng`.
100         pub fn new() -> IoResult<OsRng> {
101             Ok(OsRng {marker: marker::NoCopy} )
102         }
103     }
104
105     impl Rng for OsRng {
106         fn next_u32(&mut self) -> u32 {
107             let mut v = [0u8, .. 4];
108             self.fill_bytes(v);
109             unsafe { mem::transmute(v) }
110         }
111         fn next_u64(&mut self) -> u64 {
112             let mut v = [0u8, .. 8];
113             self.fill_bytes(v);
114             unsafe { mem::transmute(v) }
115         }
116         fn fill_bytes(&mut self, v: &mut [u8]) {
117             let ret = unsafe {
118                 SecRandomCopyBytes(kSecRandomDefault, v.len() as size_t, v.as_mut_ptr())
119             };
120             if ret == -1 {
121                 fail!("couldn't generate random bytes: {}", os::last_os_error());
122             }
123         }
124     }
125 }
126
127 #[cfg(windows)]
128 mod imp {
129     extern crate libc;
130
131     use core_collections::Collection;
132     use io::{IoResult, IoError};
133     use mem;
134     use ops::Drop;
135     use os;
136     use rand::Rng;
137     use result::{Ok, Err};
138     use rt::stack;
139     use self::libc::{c_ulong, DWORD, BYTE, LPCSTR, BOOL};
140     use slice::MutableVector;
141
142     type HCRYPTPROV = c_ulong;
143
144     /// A random number generator that retrieves randomness straight from
145     /// the operating system. Platform sources:
146     ///
147     /// - Unix-like systems (Linux, Android, Mac OSX): read directly from
148     ///   `/dev/urandom`.
149     /// - Windows: calls `CryptGenRandom`, using the default cryptographic
150     ///   service provider with the `PROV_RSA_FULL` type.
151     ///
152     /// This does not block.
153     pub struct OsRng {
154         hcryptprov: HCRYPTPROV
155     }
156
157     static PROV_RSA_FULL: DWORD = 1;
158     static CRYPT_SILENT: DWORD = 64;
159     static CRYPT_VERIFYCONTEXT: DWORD = 0xF0000000;
160     static NTE_BAD_SIGNATURE: DWORD = 0x80090006;
161
162     #[allow(non_snake_case_functions)]
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 mut ret = unsafe {
180                 CryptAcquireContextA(&mut hcp, 0 as LPCSTR, 0 as LPCSTR,
181                                      PROV_RSA_FULL,
182                                      CRYPT_VERIFYCONTEXT | CRYPT_SILENT)
183             };
184
185             // FIXME #13259:
186             // It turns out that if we can't acquire a context with the
187             // NTE_BAD_SIGNATURE error code, the documentation states:
188             //
189             //     The provider DLL signature could not be verified. Either the
190             //     DLL or the digital signature has been tampered with.
191             //
192             // Sounds fishy, no? As it turns out, our signature can be bad
193             // because our Thread Information Block (TIB) isn't exactly what it
194             // expects. As to why, I have no idea. The only data we store in the
195             // TIB is the stack limit for each thread, but apparently that's
196             // enough to make the signature valid.
197             //
198             // Furthermore, this error only happens the *first* time we call
199             // CryptAcquireContext, so we don't have to worry about future
200             // calls.
201             //
202             // Anyway, the fix employed here is that if we see this error, we
203             // pray that we're not close to the end of the stack, temporarily
204             // set the stack limit to 0 (what the TIB originally was), acquire a
205             // context, and then reset the stack limit.
206             //
207             // Again, I'm not sure why this is the fix, nor why we're getting
208             // this error. All I can say is that this seems to allow libnative
209             // to progress where it otherwise would be hindered. Who knew?
210             if ret == 0 && os::errno() as DWORD == NTE_BAD_SIGNATURE {
211                 unsafe {
212                     let limit = stack::get_sp_limit();
213                     stack::record_sp_limit(0);
214                     ret = CryptAcquireContextA(&mut hcp, 0 as LPCSTR, 0 as LPCSTR,
215                                                PROV_RSA_FULL,
216                                                CRYPT_VERIFYCONTEXT | CRYPT_SILENT);
217                     stack::record_sp_limit(limit);
218                 }
219             }
220
221             if ret == 0 {
222                 Err(IoError::last_error())
223             } else {
224                 Ok(OsRng { hcryptprov: hcp })
225             }
226         }
227     }
228
229     impl Rng for OsRng {
230         fn next_u32(&mut self) -> u32 {
231             let mut v = [0u8, .. 4];
232             self.fill_bytes(v);
233             unsafe { mem::transmute(v) }
234         }
235         fn next_u64(&mut self) -> u64 {
236             let mut v = [0u8, .. 8];
237             self.fill_bytes(v);
238             unsafe { mem::transmute(v) }
239         }
240         fn fill_bytes(&mut self, v: &mut [u8]) {
241             let ret = unsafe {
242                 CryptGenRandom(self.hcryptprov, v.len() as DWORD,
243                                v.as_mut_ptr())
244             };
245             if ret == 0 {
246                 fail!("couldn't generate random bytes: {}", os::last_os_error());
247             }
248         }
249     }
250
251     impl Drop for OsRng {
252         fn drop(&mut self) {
253             let ret = unsafe {
254                 CryptReleaseContext(self.hcryptprov, 0)
255             };
256             if ret == 0 {
257                 fail!("couldn't release context: {}", os::last_os_error());
258             }
259         }
260     }
261 }
262
263 #[cfg(test)]
264 mod test {
265     use prelude::*;
266
267     use super::OsRng;
268     use rand::Rng;
269     use task;
270
271     #[test]
272     fn test_os_rng() {
273         let mut r = OsRng::new().unwrap();
274
275         r.next_u32();
276         r.next_u64();
277
278         let mut v = [0u8, .. 1000];
279         r.fill_bytes(v);
280     }
281
282     #[test]
283     fn test_os_rng_tasks() {
284
285         let mut txs = vec!();
286         for _ in range(0u, 20) {
287             let (tx, rx) = channel();
288             txs.push(tx);
289             task::spawn(proc() {
290                 // wait until all the tasks are ready to go.
291                 rx.recv();
292
293                 // deschedule to attempt to interleave things as much
294                 // as possible (XXX: is this a good test?)
295                 let mut r = OsRng::new().unwrap();
296                 task::deschedule();
297                 let mut v = [0u8, .. 1000];
298
299                 for _ in range(0u, 100) {
300                     r.next_u32();
301                     task::deschedule();
302                     r.next_u64();
303                     task::deschedule();
304                     r.fill_bytes(v);
305                     task::deschedule();
306                 }
307             })
308         }
309
310         // start all the tasks
311         for tx in txs.iter() {
312             tx.send(())
313         }
314     }
315 }