rust/src/libstd/rand/os.rs

385 lines
12 KiB
Rust
Raw Normal View History

// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Interfaces to the operating system provided random number
//! generators.
pub use self::imp::OsRng;
2014-09-29 00:31:50 -05:00
#[cfg(all(unix, not(target_os = "ios")))]
mod imp {
extern crate libc;
use self::OsRngInner::*;
std: Recreate a `rand` module This commit shuffles around some of the `rand` code, along with some reorganization. The new state of the world is as follows: * The librand crate now only depends on libcore. This interface is experimental. * The standard library has a new module, `std::rand`. This interface will eventually become stable. Unfortunately, this entailed more of a breaking change than just shuffling some names around. The following breaking changes were made to the rand library: * Rng::gen_vec() was removed. This has been replaced with Rng::gen_iter() which will return an infinite stream of random values. Previous behavior can be regained with `rng.gen_iter().take(n).collect()` * Rng::gen_ascii_str() was removed. This has been replaced with Rng::gen_ascii_chars() which will return an infinite stream of random ascii characters. Similarly to gen_iter(), previous behavior can be emulated with `rng.gen_ascii_chars().take(n).collect()` * {IsaacRng, Isaac64Rng, XorShiftRng}::new() have all been removed. These all relied on being able to use an OSRng for seeding, but this is no longer available in librand (where these types are defined). To retain the same functionality, these types now implement the `Rand` trait so they can be generated with a random seed from another random number generator. This allows the stdlib to use an OSRng to create seeded instances of these RNGs. * Rand implementations for `Box<T>` and `@T` were removed. These seemed to be pretty rare in the codebase, and it allows for librand to not depend on liballoc. Additionally, other pointer types like Rc<T> and Arc<T> were not supported. If this is undesirable, librand can depend on liballoc and regain these implementations. * The WeightedChoice structure is no longer built with a `Vec<Weighted<T>>`, but rather a `&mut [Weighted<T>]`. This means that the WeightedChoice structure now has a lifetime associated with it. * The `sample` method on `Rng` has been moved to a top-level function in the `rand` module due to its dependence on `Vec`. cc #13851 [breaking-change]
2014-05-25 03:39:37 -05:00
use io::{IoResult, File};
use path::Path;
use rand::Rng;
use rand::reader::ReaderRng;
use result::Result::{Ok, Err};
2014-11-06 15:54:32 -06:00
use slice::SlicePrelude;
use mem;
use os::errno;
#[cfg(all(target_os = "linux",
any(target_arch = "x86_64", target_arch = "x86", target_arch = "arm")))]
fn getrandom(buf: &mut [u8]) -> libc::c_long {
extern "C" {
fn syscall(number: libc::c_long, ...) -> libc::c_long;
}
#[cfg(target_arch = "x86_64")]
const NR_GETRANDOM: libc::c_long = 318;
#[cfg(target_arch = "x86")]
const NR_GETRANDOM: libc::c_long = 355;
#[cfg(target_arch = "arm")]
const NR_GETRANDOM: libc::c_long = 384;
unsafe {
syscall(NR_GETRANDOM, buf.as_mut_ptr(), buf.len(), 0u)
}
}
#[cfg(not(all(target_os = "linux",
any(target_arch = "x86_64", target_arch = "x86", target_arch = "arm"))))]
fn getrandom(_buf: &mut [u8]) -> libc::c_long { -1 }
fn getrandom_fill_bytes(v: &mut [u8]) {
let mut read = 0;
let len = v.len();
while read < len {
let result = getrandom(v[mut read..]);
if result == -1 {
let err = errno() as libc::c_int;
if err == libc::EINTR {
continue;
} else {
panic!("unexpected getrandom error: {}", err);
}
} else {
read += result as uint;
}
}
}
fn getrandom_next_u32() -> u32 {
let mut buf: [u8, ..4] = [0u8, ..4];
getrandom_fill_bytes(&mut buf);
unsafe { mem::transmute::<[u8, ..4], u32>(buf) }
}
fn getrandom_next_u64() -> u64 {
let mut buf: [u8, ..8] = [0u8, ..8];
getrandom_fill_bytes(&mut buf);
unsafe { mem::transmute::<[u8, ..8], u64>(buf) }
}
#[cfg(all(target_os = "linux",
any(target_arch = "x86_64", target_arch = "x86", target_arch = "arm")))]
fn is_getrandom_available() -> bool {
use sync::atomic::{AtomicBool, INIT_ATOMIC_BOOL, Relaxed};
static GETRANDOM_CHECKED: AtomicBool = INIT_ATOMIC_BOOL;
static GETRANDOM_AVAILABLE: AtomicBool = INIT_ATOMIC_BOOL;
if !GETRANDOM_CHECKED.load(Relaxed) {
let mut buf: [u8, ..0] = [];
let result = getrandom(&mut buf);
let available = if result == -1 {
let err = errno() as libc::c_int;
err != libc::ENOSYS
} else {
true
};
GETRANDOM_AVAILABLE.store(available, Relaxed);
GETRANDOM_CHECKED.store(true, Relaxed);
available
} else {
GETRANDOM_AVAILABLE.load(Relaxed)
}
}
#[cfg(not(all(target_os = "linux",
any(target_arch = "x86_64", target_arch = "x86", target_arch = "arm"))))]
fn is_getrandom_available() -> bool { false }
/// A random number generator that retrieves randomness straight from
/// the operating system. Platform sources:
///
/// - Unix-like systems (Linux, Android, Mac OSX): read directly from
/// `/dev/urandom`, or from `getrandom(2)` system call if available.
/// - Windows: calls `CryptGenRandom`, using the default cryptographic
/// service provider with the `PROV_RSA_FULL` type.
2014-05-05 02:07:49 -05:00
/// - iOS: calls SecRandomCopyBytes as /dev/(u)random is sandboxed
/// This does not block.
pub struct OsRng {
inner: OsRngInner,
}
enum OsRngInner {
OsGetrandomRng,
OsReaderRng(ReaderRng<File>),
}
impl OsRng {
/// Create a new `OsRng`.
pub fn new() -> IoResult<OsRng> {
if is_getrandom_available() {
return Ok(OsRng { inner: OsGetrandomRng });
}
let reader = try!(File::open(&Path::new("/dev/urandom")));
let reader_rng = ReaderRng::new(reader);
Ok(OsRng { inner: OsReaderRng(reader_rng) })
}
}
impl Rng for OsRng {
fn next_u32(&mut self) -> u32 {
match self.inner {
OsGetrandomRng => getrandom_next_u32(),
OsReaderRng(ref mut rng) => rng.next_u32(),
}
}
fn next_u64(&mut self) -> u64 {
match self.inner {
OsGetrandomRng => getrandom_next_u64(),
OsReaderRng(ref mut rng) => rng.next_u64(),
}
}
fn fill_bytes(&mut self, v: &mut [u8]) {
match self.inner {
OsGetrandomRng => getrandom_fill_bytes(v),
OsReaderRng(ref mut rng) => rng.fill_bytes(v)
}
}
}
}
2014-05-05 02:07:49 -05:00
#[cfg(target_os = "ios")]
mod imp {
extern crate libc;
use io::{IoResult};
use kinds::marker;
use mem;
use os;
use rand::Rng;
use result::Result::{Ok};
2014-05-05 02:07:49 -05:00
use self::libc::{c_int, size_t};
use slice::{SlicePrelude};
2014-05-05 02:07:49 -05:00
/// A random number generator that retrieves randomness straight from
/// the operating system. Platform sources:
///
/// - Unix-like systems (Linux, Android, Mac OSX): read directly from
/// `/dev/urandom`, or from `getrandom(2)` system call if available.
2014-05-05 02:07:49 -05:00
/// - Windows: calls `CryptGenRandom`, using the default cryptographic
/// service provider with the `PROV_RSA_FULL` type.
/// - iOS: calls SecRandomCopyBytes as /dev/(u)random is sandboxed
/// This does not block.
pub struct OsRng {
marker: marker::NoCopy
}
2014-08-25 05:45:07 -05:00
#[repr(C)]
2014-05-05 02:07:49 -05:00
struct SecRandom;
2014-10-27 17:37:07 -05:00
#[allow(non_upper_case_globals)]
2014-06-25 14:47:34 -05:00
static kSecRandomDefault: *const SecRandom = 0 as *const SecRandom;
2014-05-05 02:07:49 -05:00
#[link(name = "Security", kind = "framework")]
extern "C" {
2014-06-25 14:47:34 -05:00
fn SecRandomCopyBytes(rnd: *const SecRandom,
count: size_t, bytes: *mut u8) -> c_int;
2014-05-05 02:07:49 -05:00
}
impl OsRng {
/// Create a new `OsRng`.
pub fn new() -> IoResult<OsRng> {
Ok(OsRng {marker: marker::NoCopy} )
}
}
impl Rng for OsRng {
fn next_u32(&mut self) -> u32 {
let mut v = [0u8, .. 4];
self.fill_bytes(&mut v);
2014-05-05 02:07:49 -05:00
unsafe { mem::transmute(v) }
}
fn next_u64(&mut self) -> u64 {
let mut v = [0u8, .. 8];
self.fill_bytes(&mut v);
2014-05-05 02:07:49 -05:00
unsafe { mem::transmute(v) }
}
fn fill_bytes(&mut self, v: &mut [u8]) {
let ret = unsafe {
SecRandomCopyBytes(kSecRandomDefault, v.len() as size_t, v.as_mut_ptr())
};
if ret == -1 {
panic!("couldn't generate random bytes: {}", os::last_os_error());
2014-05-05 02:07:49 -05:00
}
}
}
}
#[cfg(windows)]
mod imp {
2014-02-26 11:58:41 -06:00
extern crate libc;
std: Recreate a `rand` module This commit shuffles around some of the `rand` code, along with some reorganization. The new state of the world is as follows: * The librand crate now only depends on libcore. This interface is experimental. * The standard library has a new module, `std::rand`. This interface will eventually become stable. Unfortunately, this entailed more of a breaking change than just shuffling some names around. The following breaking changes were made to the rand library: * Rng::gen_vec() was removed. This has been replaced with Rng::gen_iter() which will return an infinite stream of random values. Previous behavior can be regained with `rng.gen_iter().take(n).collect()` * Rng::gen_ascii_str() was removed. This has been replaced with Rng::gen_ascii_chars() which will return an infinite stream of random ascii characters. Similarly to gen_iter(), previous behavior can be emulated with `rng.gen_ascii_chars().take(n).collect()` * {IsaacRng, Isaac64Rng, XorShiftRng}::new() have all been removed. These all relied on being able to use an OSRng for seeding, but this is no longer available in librand (where these types are defined). To retain the same functionality, these types now implement the `Rand` trait so they can be generated with a random seed from another random number generator. This allows the stdlib to use an OSRng to create seeded instances of these RNGs. * Rand implementations for `Box<T>` and `@T` were removed. These seemed to be pretty rare in the codebase, and it allows for librand to not depend on liballoc. Additionally, other pointer types like Rc<T> and Arc<T> were not supported. If this is undesirable, librand can depend on liballoc and regain these implementations. * The WeightedChoice structure is no longer built with a `Vec<Weighted<T>>`, but rather a `&mut [Weighted<T>]`. This means that the WeightedChoice structure now has a lifetime associated with it. * The `sample` method on `Rng` has been moved to a top-level function in the `rand` module due to its dependence on `Vec`. cc #13851 [breaking-change]
2014-05-25 03:39:37 -05:00
use io::{IoResult, IoError};
use mem;
use ops::Drop;
use os;
use rand::Rng;
use result::Result::{Ok, Err};
use self::libc::{DWORD, BYTE, LPCSTR, BOOL};
use self::libc::types::os::arch::extra::{LONG_PTR};
use slice::{SlicePrelude};
type HCRYPTPROV = LONG_PTR;
/// A random number generator that retrieves randomness straight from
/// the operating system. Platform sources:
///
/// - Unix-like systems (Linux, Android, Mac OSX): read directly from
/// `/dev/urandom`, or from `getrandom(2)` system call if available.
/// - Windows: calls `CryptGenRandom`, using the default cryptographic
/// service provider with the `PROV_RSA_FULL` type.
/// - iOS: calls SecRandomCopyBytes as /dev/(u)random is sandboxed
/// This does not block.
pub struct OsRng {
hcryptprov: HCRYPTPROV
}
static PROV_RSA_FULL: DWORD = 1;
static CRYPT_SILENT: DWORD = 64;
static CRYPT_VERIFYCONTEXT: DWORD = 0xF0000000;
#[allow(non_snake_case)]
extern "system" {
fn CryptAcquireContextA(phProv: *mut HCRYPTPROV,
pszContainer: LPCSTR,
pszProvider: LPCSTR,
dwProvType: DWORD,
dwFlags: DWORD) -> BOOL;
fn CryptGenRandom(hProv: HCRYPTPROV,
dwLen: DWORD,
pbBuffer: *mut BYTE) -> BOOL;
fn CryptReleaseContext(hProv: HCRYPTPROV, dwFlags: DWORD) -> BOOL;
}
impl OsRng {
/// Create a new `OsRng`.
pub fn new() -> IoResult<OsRng> {
let mut hcp = 0;
let ret = unsafe {
CryptAcquireContextA(&mut hcp, 0 as LPCSTR, 0 as LPCSTR,
PROV_RSA_FULL,
CRYPT_VERIFYCONTEXT | CRYPT_SILENT)
};
if ret == 0 {
Err(IoError::last_error())
} else {
Ok(OsRng { hcryptprov: hcp })
}
}
}
impl Rng for OsRng {
fn next_u32(&mut self) -> u32 {
let mut v = [0u8, .. 4];
2014-11-17 18:49:09 -06:00
self.fill_bytes(&mut v);
core: Remove the cast module This commit revisits the `cast` module in libcore and libstd, and scrutinizes all functions inside of it. The result was to remove the `cast` module entirely, folding all functionality into the `mem` module. Specifically, this is the fate of each function in the `cast` module. * transmute - This function was moved to `mem`, but it is now marked as #[unstable]. This is due to planned changes to the `transmute` function and how it can be invoked (see the #[unstable] comment). For more information, see RFC 5 and #12898 * transmute_copy - This function was moved to `mem`, with clarification that is is not an error to invoke it with T/U that are different sizes, but rather that it is strongly discouraged. This function is now #[stable] * forget - This function was moved to `mem` and marked #[stable] * bump_box_refcount - This function was removed due to the deprecation of managed boxes as well as its questionable utility. * transmute_mut - This function was previously deprecated, and removed as part of this commit. * transmute_mut_unsafe - This function doesn't serve much of a purpose when it can be achieved with an `as` in safe code, so it was removed. * transmute_lifetime - This function was removed because it is likely a strong indication that code is incorrect in the first place. * transmute_mut_lifetime - This function was removed for the same reasons as `transmute_lifetime` * copy_lifetime - This function was moved to `mem`, but it is marked `#[unstable]` now due to the likelihood of being removed in the future if it is found to not be very useful. * copy_mut_lifetime - This function was also moved to `mem`, but had the same treatment as `copy_lifetime`. * copy_lifetime_vec - This function was removed because it is not used today, and its existence is not necessary with DST (copy_lifetime will suffice). In summary, the cast module was stripped down to these functions, and then the functions were moved to the `mem` module. transmute - #[unstable] transmute_copy - #[stable] forget - #[stable] copy_lifetime - #[unstable] copy_mut_lifetime - #[unstable] [breaking-change]
2014-05-09 12:34:51 -05:00
unsafe { mem::transmute(v) }
}
fn next_u64(&mut self) -> u64 {
let mut v = [0u8, .. 8];
2014-11-17 18:49:09 -06:00
self.fill_bytes(&mut v);
core: Remove the cast module This commit revisits the `cast` module in libcore and libstd, and scrutinizes all functions inside of it. The result was to remove the `cast` module entirely, folding all functionality into the `mem` module. Specifically, this is the fate of each function in the `cast` module. * transmute - This function was moved to `mem`, but it is now marked as #[unstable]. This is due to planned changes to the `transmute` function and how it can be invoked (see the #[unstable] comment). For more information, see RFC 5 and #12898 * transmute_copy - This function was moved to `mem`, with clarification that is is not an error to invoke it with T/U that are different sizes, but rather that it is strongly discouraged. This function is now #[stable] * forget - This function was moved to `mem` and marked #[stable] * bump_box_refcount - This function was removed due to the deprecation of managed boxes as well as its questionable utility. * transmute_mut - This function was previously deprecated, and removed as part of this commit. * transmute_mut_unsafe - This function doesn't serve much of a purpose when it can be achieved with an `as` in safe code, so it was removed. * transmute_lifetime - This function was removed because it is likely a strong indication that code is incorrect in the first place. * transmute_mut_lifetime - This function was removed for the same reasons as `transmute_lifetime` * copy_lifetime - This function was moved to `mem`, but it is marked `#[unstable]` now due to the likelihood of being removed in the future if it is found to not be very useful. * copy_mut_lifetime - This function was also moved to `mem`, but had the same treatment as `copy_lifetime`. * copy_lifetime_vec - This function was removed because it is not used today, and its existence is not necessary with DST (copy_lifetime will suffice). In summary, the cast module was stripped down to these functions, and then the functions were moved to the `mem` module. transmute - #[unstable] transmute_copy - #[stable] forget - #[stable] copy_lifetime - #[unstable] copy_mut_lifetime - #[unstable] [breaking-change]
2014-05-09 12:34:51 -05:00
unsafe { mem::transmute(v) }
}
fn fill_bytes(&mut self, v: &mut [u8]) {
let ret = unsafe {
CryptGenRandom(self.hcryptprov, v.len() as DWORD,
v.as_mut_ptr())
};
if ret == 0 {
panic!("couldn't generate random bytes: {}", os::last_os_error());
}
}
}
impl Drop for OsRng {
fn drop(&mut self) {
let ret = unsafe {
CryptReleaseContext(self.hcryptprov, 0)
};
if ret == 0 {
panic!("couldn't release context: {}", os::last_os_error());
}
}
}
}
#[cfg(test)]
mod test {
std: Recreate a `rand` module This commit shuffles around some of the `rand` code, along with some reorganization. The new state of the world is as follows: * The librand crate now only depends on libcore. This interface is experimental. * The standard library has a new module, `std::rand`. This interface will eventually become stable. Unfortunately, this entailed more of a breaking change than just shuffling some names around. The following breaking changes were made to the rand library: * Rng::gen_vec() was removed. This has been replaced with Rng::gen_iter() which will return an infinite stream of random values. Previous behavior can be regained with `rng.gen_iter().take(n).collect()` * Rng::gen_ascii_str() was removed. This has been replaced with Rng::gen_ascii_chars() which will return an infinite stream of random ascii characters. Similarly to gen_iter(), previous behavior can be emulated with `rng.gen_ascii_chars().take(n).collect()` * {IsaacRng, Isaac64Rng, XorShiftRng}::new() have all been removed. These all relied on being able to use an OSRng for seeding, but this is no longer available in librand (where these types are defined). To retain the same functionality, these types now implement the `Rand` trait so they can be generated with a random seed from another random number generator. This allows the stdlib to use an OSRng to create seeded instances of these RNGs. * Rand implementations for `Box<T>` and `@T` were removed. These seemed to be pretty rare in the codebase, and it allows for librand to not depend on liballoc. Additionally, other pointer types like Rc<T> and Arc<T> were not supported. If this is undesirable, librand can depend on liballoc and regain these implementations. * The WeightedChoice structure is no longer built with a `Vec<Weighted<T>>`, but rather a `&mut [Weighted<T>]`. This means that the WeightedChoice structure now has a lifetime associated with it. * The `sample` method on `Rng` has been moved to a top-level function in the `rand` module due to its dependence on `Vec`. cc #13851 [breaking-change]
2014-05-25 03:39:37 -05:00
use prelude::*;
use super::OsRng;
std: Recreate a `rand` module This commit shuffles around some of the `rand` code, along with some reorganization. The new state of the world is as follows: * The librand crate now only depends on libcore. This interface is experimental. * The standard library has a new module, `std::rand`. This interface will eventually become stable. Unfortunately, this entailed more of a breaking change than just shuffling some names around. The following breaking changes were made to the rand library: * Rng::gen_vec() was removed. This has been replaced with Rng::gen_iter() which will return an infinite stream of random values. Previous behavior can be regained with `rng.gen_iter().take(n).collect()` * Rng::gen_ascii_str() was removed. This has been replaced with Rng::gen_ascii_chars() which will return an infinite stream of random ascii characters. Similarly to gen_iter(), previous behavior can be emulated with `rng.gen_ascii_chars().take(n).collect()` * {IsaacRng, Isaac64Rng, XorShiftRng}::new() have all been removed. These all relied on being able to use an OSRng for seeding, but this is no longer available in librand (where these types are defined). To retain the same functionality, these types now implement the `Rand` trait so they can be generated with a random seed from another random number generator. This allows the stdlib to use an OSRng to create seeded instances of these RNGs. * Rand implementations for `Box<T>` and `@T` were removed. These seemed to be pretty rare in the codebase, and it allows for librand to not depend on liballoc. Additionally, other pointer types like Rc<T> and Arc<T> were not supported. If this is undesirable, librand can depend on liballoc and regain these implementations. * The WeightedChoice structure is no longer built with a `Vec<Weighted<T>>`, but rather a `&mut [Weighted<T>]`. This means that the WeightedChoice structure now has a lifetime associated with it. * The `sample` method on `Rng` has been moved to a top-level function in the `rand` module due to its dependence on `Vec`. cc #13851 [breaking-change]
2014-05-25 03:39:37 -05:00
use rand::Rng;
use task;
#[test]
fn test_os_rng() {
let mut r = OsRng::new().unwrap();
r.next_u32();
r.next_u64();
let mut v = [0u8, .. 1000];
2014-11-17 02:39:01 -06:00
r.fill_bytes(&mut v);
}
#[test]
fn test_os_rng_tasks() {
let mut txs = vec!();
for _ in range(0u, 20) {
let (tx, rx) = channel();
txs.push(tx);
task::spawn(move|| {
// wait until all the tasks are ready to go.
rx.recv();
// deschedule to attempt to interleave things as much
// as possible (XXX: is this a good test?)
let mut r = OsRng::new().unwrap();
task::deschedule();
let mut v = [0u8, .. 1000];
for _ in range(0u, 100) {
r.next_u32();
task::deschedule();
r.next_u64();
task::deschedule();
2014-11-17 02:39:01 -06:00
r.fill_bytes(&mut v);
task::deschedule();
}
})
}
// start all the tasks
for tx in txs.iter() {
tx.send(())
}
}
}