2014-12-12 17:39:27 -06:00
|
|
|
// Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT
|
2013-09-22 05:51:57 -05:00
|
|
|
// 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.
|
|
|
|
|
2014-05-29 23:37:31 -05:00
|
|
|
pub use self::imp::OsRng;
|
2013-09-22 05:51:57 -05:00
|
|
|
|
2014-09-29 00:31:50 -05:00
|
|
|
#[cfg(all(unix, not(target_os = "ios")))]
|
2014-03-19 19:53:57 -05:00
|
|
|
mod imp {
|
2015-03-30 13:00:05 -05:00
|
|
|
use prelude::v1::*;
|
2014-11-06 02:05:53 -06:00
|
|
|
use self::OsRngInner::*;
|
|
|
|
|
2015-04-09 19:42:22 -05:00
|
|
|
use fs::File;
|
|
|
|
use io;
|
2015-03-30 13:00:05 -05:00
|
|
|
use libc;
|
|
|
|
use mem;
|
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 rand::reader::ReaderRng;
|
2015-03-30 13:00:05 -05:00
|
|
|
use sys::os::errno;
|
2014-11-05 12:53:27 -06:00
|
|
|
|
|
|
|
#[cfg(all(target_os = "linux",
|
2014-12-12 17:39:27 -06:00
|
|
|
any(target_arch = "x86_64",
|
|
|
|
target_arch = "x86",
|
|
|
|
target_arch = "arm",
|
2015-01-09 22:20:15 -06:00
|
|
|
target_arch = "aarch64",
|
|
|
|
target_arch = "powerpc")))]
|
2014-11-05 12:53:27 -06:00
|
|
|
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;
|
2014-12-12 17:39:27 -06:00
|
|
|
#[cfg(any(target_arch = "arm", target_arch = "aarch64"))]
|
2014-11-05 12:53:27 -06:00
|
|
|
const NR_GETRANDOM: libc::c_long = 384;
|
2015-01-09 22:20:15 -06:00
|
|
|
#[cfg(target_arch = "powerpc")]
|
|
|
|
const NR_GETRANDOM: libc::c_long = 384;
|
2014-11-05 12:53:27 -06:00
|
|
|
|
|
|
|
unsafe {
|
2015-01-26 19:18:24 -06:00
|
|
|
syscall(NR_GETRANDOM, buf.as_mut_ptr(), buf.len(), 0)
|
2014-11-05 12:53:27 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(not(all(target_os = "linux",
|
2014-12-12 17:39:27 -06:00
|
|
|
any(target_arch = "x86_64",
|
|
|
|
target_arch = "x86",
|
|
|
|
target_arch = "arm",
|
2015-01-09 22:20:15 -06:00
|
|
|
target_arch = "aarch64",
|
|
|
|
target_arch = "powerpc"))))]
|
2014-11-05 12:53:27 -06:00
|
|
|
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 {
|
2015-01-17 18:15:52 -06:00
|
|
|
let result = getrandom(&mut v[read..]);
|
2014-11-05 12:53:27 -06:00
|
|
|
if result == -1 {
|
|
|
|
let err = errno() as libc::c_int;
|
|
|
|
if err == libc::EINTR {
|
|
|
|
continue;
|
|
|
|
} else {
|
|
|
|
panic!("unexpected getrandom error: {}", err);
|
|
|
|
}
|
|
|
|
} else {
|
2015-01-26 18:48:29 -06:00
|
|
|
read += result as usize;
|
2014-11-05 12:53:27 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn getrandom_next_u32() -> u32 {
|
2015-03-03 02:42:26 -06:00
|
|
|
let mut buf: [u8; 4] = [0; 4];
|
2014-11-05 12:53:27 -06:00
|
|
|
getrandom_fill_bytes(&mut buf);
|
2014-12-30 02:19:41 -06:00
|
|
|
unsafe { mem::transmute::<[u8; 4], u32>(buf) }
|
2014-11-05 12:53:27 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
fn getrandom_next_u64() -> u64 {
|
2015-03-03 02:42:26 -06:00
|
|
|
let mut buf: [u8; 8] = [0; 8];
|
2014-11-05 12:53:27 -06:00
|
|
|
getrandom_fill_bytes(&mut buf);
|
2014-12-30 02:19:41 -06:00
|
|
|
unsafe { mem::transmute::<[u8; 8], u64>(buf) }
|
2014-11-05 12:53:27 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(all(target_os = "linux",
|
2014-12-12 17:39:27 -06:00
|
|
|
any(target_arch = "x86_64",
|
|
|
|
target_arch = "x86",
|
|
|
|
target_arch = "arm",
|
2015-01-09 22:20:15 -06:00
|
|
|
target_arch = "aarch64",
|
|
|
|
target_arch = "powerpc")))]
|
2014-11-05 12:53:27 -06:00
|
|
|
fn is_getrandom_available() -> bool {
|
2015-05-27 03:18:36 -05:00
|
|
|
use sync::atomic::{AtomicBool, Ordering};
|
|
|
|
use sync::Once;
|
2014-11-05 12:53:27 -06:00
|
|
|
|
2015-05-27 03:18:36 -05:00
|
|
|
static CHECKER: Once = Once::new();
|
|
|
|
static AVAILABLE: AtomicBool = AtomicBool::new(false);
|
2014-11-05 12:53:27 -06:00
|
|
|
|
2015-04-17 07:17:33 -05:00
|
|
|
CHECKER.call_once(|| {
|
2014-12-30 02:19:41 -06:00
|
|
|
let mut buf: [u8; 0] = [];
|
2014-11-05 12:53:27 -06:00
|
|
|
let result = getrandom(&mut buf);
|
|
|
|
let available = if result == -1 {
|
2015-04-17 07:17:33 -05:00
|
|
|
let err = io::Error::last_os_error().raw_os_error();
|
|
|
|
err != Some(libc::ENOSYS)
|
2014-11-05 12:53:27 -06:00
|
|
|
} else {
|
|
|
|
true
|
|
|
|
};
|
2015-04-17 07:17:33 -05:00
|
|
|
AVAILABLE.store(available, Ordering::Relaxed);
|
|
|
|
});
|
|
|
|
|
|
|
|
AVAILABLE.load(Ordering::Relaxed)
|
2014-11-05 12:53:27 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(not(all(target_os = "linux",
|
2014-12-12 17:39:27 -06:00
|
|
|
any(target_arch = "x86_64",
|
|
|
|
target_arch = "x86",
|
|
|
|
target_arch = "arm",
|
2015-01-09 22:20:15 -06:00
|
|
|
target_arch = "aarch64",
|
|
|
|
target_arch = "powerpc"))))]
|
2014-11-05 12:53:27 -06:00
|
|
|
fn is_getrandom_available() -> bool { false }
|
2014-03-19 19:53:57 -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
|
2014-11-05 12:53:27 -06:00
|
|
|
/// `/dev/urandom`, or from `getrandom(2)` system call if available.
|
2014-03-19 19:53:57 -05:00
|
|
|
/// - Windows: calls `CryptGenRandom`, using the default cryptographic
|
|
|
|
/// service provider with the `PROV_RSA_FULL` type.
|
2014-12-15 00:26:09 -06:00
|
|
|
/// - iOS: calls SecRandomCopyBytes as /dev/(u)random is sandboxed.
|
|
|
|
///
|
2014-03-19 19:53:57 -05:00
|
|
|
/// This does not block.
|
2014-05-29 23:37:31 -05:00
|
|
|
pub struct OsRng {
|
2014-11-05 12:53:27 -06:00
|
|
|
inner: OsRngInner,
|
|
|
|
}
|
|
|
|
|
|
|
|
enum OsRngInner {
|
|
|
|
OsGetrandomRng,
|
|
|
|
OsReaderRng(ReaderRng<File>),
|
2013-09-22 05:51:57 -05:00
|
|
|
}
|
|
|
|
|
2014-05-29 23:37:31 -05:00
|
|
|
impl OsRng {
|
|
|
|
/// Create a new `OsRng`.
|
2015-04-09 19:42:22 -05:00
|
|
|
pub fn new() -> io::Result<OsRng> {
|
2014-11-05 12:53:27 -06:00
|
|
|
if is_getrandom_available() {
|
|
|
|
return Ok(OsRng { inner: OsGetrandomRng });
|
|
|
|
}
|
|
|
|
|
2015-04-09 19:42:22 -05:00
|
|
|
let reader = try!(File::open("/dev/urandom"));
|
2014-03-19 19:53:57 -05:00
|
|
|
let reader_rng = ReaderRng::new(reader);
|
2013-09-22 05:51:57 -05:00
|
|
|
|
2014-11-05 12:53:27 -06:00
|
|
|
Ok(OsRng { inner: OsReaderRng(reader_rng) })
|
2014-03-19 19:53:57 -05:00
|
|
|
}
|
2013-09-22 05:51:57 -05:00
|
|
|
}
|
|
|
|
|
2014-05-29 23:37:31 -05:00
|
|
|
impl Rng for OsRng {
|
2014-03-19 19:53:57 -05:00
|
|
|
fn next_u32(&mut self) -> u32 {
|
2014-11-05 12:53:27 -06:00
|
|
|
match self.inner {
|
|
|
|
OsGetrandomRng => getrandom_next_u32(),
|
|
|
|
OsReaderRng(ref mut rng) => rng.next_u32(),
|
|
|
|
}
|
2014-03-19 19:53:57 -05:00
|
|
|
}
|
|
|
|
fn next_u64(&mut self) -> u64 {
|
2014-11-05 12:53:27 -06:00
|
|
|
match self.inner {
|
|
|
|
OsGetrandomRng => getrandom_next_u64(),
|
|
|
|
OsReaderRng(ref mut rng) => rng.next_u64(),
|
|
|
|
}
|
2014-03-19 19:53:57 -05:00
|
|
|
}
|
|
|
|
fn fill_bytes(&mut self, v: &mut [u8]) {
|
2014-11-05 12:53:27 -06:00
|
|
|
match self.inner {
|
|
|
|
OsGetrandomRng => getrandom_fill_bytes(v),
|
|
|
|
OsReaderRng(ref mut rng) => rng.fill_bytes(v)
|
|
|
|
}
|
2014-03-19 19:53:57 -05:00
|
|
|
}
|
2013-09-22 05:51:57 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-05-05 02:07:49 -05:00
|
|
|
#[cfg(target_os = "ios")]
|
|
|
|
mod imp {
|
2015-03-30 13:00:05 -05:00
|
|
|
use prelude::v1::*;
|
2014-05-05 02:07:49 -05:00
|
|
|
|
2015-04-01 12:38:58 -05:00
|
|
|
use io;
|
2014-05-05 02:07:49 -05:00
|
|
|
use mem;
|
|
|
|
use rand::Rng;
|
2015-03-30 13:00:05 -05:00
|
|
|
use libc::{c_int, size_t};
|
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
|
2014-11-05 12:53:27 -06:00
|
|
|
/// `/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.
|
2014-12-15 00:26:09 -06:00
|
|
|
/// - iOS: calls SecRandomCopyBytes as /dev/(u)random is sandboxed.
|
|
|
|
///
|
2014-05-05 02:07:49 -05:00
|
|
|
/// This does not block.
|
|
|
|
pub struct OsRng {
|
2015-04-09 19:42:22 -05:00
|
|
|
// dummy field to ensure that this struct cannot be constructed outside
|
|
|
|
// of this module
|
2014-12-15 14:35:34 -06:00
|
|
|
_dummy: (),
|
2014-05-05 02:07:49 -05:00
|
|
|
}
|
|
|
|
|
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)]
|
2015-02-24 08:44:30 -06:00
|
|
|
const 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`.
|
2015-04-09 19:42:22 -05:00
|
|
|
pub fn new() -> io::Result<OsRng> {
|
2014-12-15 14:35:34 -06:00
|
|
|
Ok(OsRng { _dummy: () })
|
2014-05-05 02:07:49 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Rng for OsRng {
|
|
|
|
fn next_u32(&mut self) -> u32 {
|
2015-03-03 02:42:26 -06:00
|
|
|
let mut v = [0; 4];
|
2014-11-19 00:54:52 -06:00
|
|
|
self.fill_bytes(&mut v);
|
2014-05-05 02:07:49 -05:00
|
|
|
unsafe { mem::transmute(v) }
|
|
|
|
}
|
|
|
|
fn next_u64(&mut self) -> u64 {
|
2015-03-03 02:42:26 -06:00
|
|
|
let mut v = [0; 8];
|
2014-11-19 00:54:52 -06:00
|
|
|
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 {
|
2015-04-09 19:42:22 -05:00
|
|
|
SecRandomCopyBytes(kSecRandomDefault, v.len() as size_t,
|
|
|
|
v.as_mut_ptr())
|
2014-05-05 02:07:49 -05:00
|
|
|
};
|
|
|
|
if ret == -1 {
|
2015-04-09 19:42:22 -05:00
|
|
|
panic!("couldn't generate random bytes: {}",
|
|
|
|
io::Error::last_os_error());
|
2014-05-05 02:07:49 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-09-22 05:51:57 -05:00
|
|
|
#[cfg(windows)]
|
2014-03-19 19:53:57 -05:00
|
|
|
mod imp {
|
2015-03-30 13:00:05 -05:00
|
|
|
use prelude::v1::*;
|
2014-02-26 11:58:41 -06:00
|
|
|
|
2015-03-30 13:00:05 -05:00
|
|
|
use io;
|
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 mem;
|
|
|
|
use rand::Rng;
|
2015-03-30 13:00:05 -05:00
|
|
|
use libc::types::os::arch::extra::{LONG_PTR};
|
|
|
|
use libc::{DWORD, BYTE, LPCSTR, BOOL};
|
2014-03-19 19:53:57 -05:00
|
|
|
|
2014-07-28 15:35:34 -05:00
|
|
|
type HCRYPTPROV = LONG_PTR;
|
2014-03-19 19:53:57 -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
|
2014-11-05 12:53:27 -06:00
|
|
|
/// `/dev/urandom`, or from `getrandom(2)` system call if available.
|
2014-03-19 19:53:57 -05:00
|
|
|
/// - Windows: calls `CryptGenRandom`, using the default cryptographic
|
|
|
|
/// service provider with the `PROV_RSA_FULL` type.
|
2014-12-15 00:26:09 -06:00
|
|
|
/// - iOS: calls SecRandomCopyBytes as /dev/(u)random is sandboxed.
|
|
|
|
///
|
2014-03-19 19:53:57 -05:00
|
|
|
/// This does not block.
|
2014-05-29 23:37:31 -05:00
|
|
|
pub struct OsRng {
|
2014-03-27 17:10:38 -05:00
|
|
|
hcryptprov: HCRYPTPROV
|
2013-09-22 05:51:57 -05:00
|
|
|
}
|
2013-10-01 11:18:57 -05:00
|
|
|
|
2015-02-27 08:36:53 -06:00
|
|
|
const PROV_RSA_FULL: DWORD = 1;
|
|
|
|
const CRYPT_SILENT: DWORD = 64;
|
|
|
|
const CRYPT_VERIFYCONTEXT: DWORD = 0xF0000000;
|
2014-03-19 19:53:57 -05:00
|
|
|
|
2014-07-18 07:45:17 -05:00
|
|
|
#[allow(non_snake_case)]
|
2015-03-04 16:58:59 -06:00
|
|
|
#[link(name = "advapi32")]
|
2014-03-19 19:53:57 -05:00
|
|
|
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;
|
2013-09-22 05:51:57 -05:00
|
|
|
}
|
|
|
|
|
2014-05-29 23:37:31 -05:00
|
|
|
impl OsRng {
|
|
|
|
/// Create a new `OsRng`.
|
2015-04-09 19:42:22 -05:00
|
|
|
pub fn new() -> io::Result<OsRng> {
|
2014-03-19 19:53:57 -05:00
|
|
|
let mut hcp = 0;
|
2014-09-24 17:35:44 -05:00
|
|
|
let ret = unsafe {
|
2014-03-19 19:53:57 -05:00
|
|
|
CryptAcquireContextA(&mut hcp, 0 as LPCSTR, 0 as LPCSTR,
|
|
|
|
PROV_RSA_FULL,
|
|
|
|
CRYPT_VERIFYCONTEXT | CRYPT_SILENT)
|
|
|
|
};
|
2014-03-21 13:51:11 -05:00
|
|
|
|
2014-03-19 19:53:57 -05:00
|
|
|
if ret == 0 {
|
2015-04-09 19:42:22 -05:00
|
|
|
Err(io::Error::last_os_error())
|
2014-03-24 08:41:43 -05:00
|
|
|
} else {
|
2014-05-29 23:37:31 -05:00
|
|
|
Ok(OsRng { hcryptprov: hcp })
|
2014-03-19 19:53:57 -05:00
|
|
|
}
|
|
|
|
}
|
2013-09-22 05:51:57 -05:00
|
|
|
}
|
|
|
|
|
2014-05-29 23:37:31 -05:00
|
|
|
impl Rng for OsRng {
|
2014-03-19 19:53:57 -05:00
|
|
|
fn next_u32(&mut self) -> u32 {
|
2015-03-03 02:42:26 -06:00
|
|
|
let mut v = [0; 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) }
|
2014-03-19 19:53:57 -05:00
|
|
|
}
|
|
|
|
fn next_u64(&mut self) -> u64 {
|
2015-03-03 02:42:26 -06:00
|
|
|
let mut v = [0; 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) }
|
2014-03-19 19:53:57 -05:00
|
|
|
}
|
|
|
|
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 {
|
2015-03-30 13:00:05 -05:00
|
|
|
panic!("couldn't generate random bytes: {}",
|
|
|
|
io::Error::last_os_error());
|
2014-03-19 19:53:57 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2013-09-22 05:51:57 -05:00
|
|
|
|
2014-05-29 23:37:31 -05:00
|
|
|
impl Drop for OsRng {
|
2014-03-19 19:53:57 -05:00
|
|
|
fn drop(&mut self) {
|
|
|
|
let ret = unsafe {
|
|
|
|
CryptReleaseContext(self.hcryptprov, 0)
|
|
|
|
};
|
|
|
|
if ret == 0 {
|
2015-03-30 13:00:05 -05:00
|
|
|
panic!("couldn't release context: {}",
|
|
|
|
io::Error::last_os_error());
|
2014-03-19 19:53:57 -05:00
|
|
|
}
|
|
|
|
}
|
2013-09-22 05:51:57 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
2015-04-24 10:30:41 -05:00
|
|
|
mod tests {
|
2014-12-22 11:04:23 -06:00
|
|
|
use prelude::v1::*;
|
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
|
|
|
|
2014-12-23 13:53:35 -06:00
|
|
|
use sync::mpsc::channel;
|
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;
|
2014-12-22 11:04:23 -06:00
|
|
|
use super::OsRng;
|
2015-02-17 17:10:25 -06:00
|
|
|
use thread;
|
2013-09-22 05:51:57 -05:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_os_rng() {
|
2014-05-29 23:37:31 -05:00
|
|
|
let mut r = OsRng::new().unwrap();
|
2013-09-22 05:51:57 -05:00
|
|
|
|
|
|
|
r.next_u32();
|
|
|
|
r.next_u64();
|
|
|
|
|
2015-03-03 02:42:26 -06:00
|
|
|
let mut v = [0; 1000];
|
2014-11-17 02:39:01 -06:00
|
|
|
r.fill_bytes(&mut v);
|
2013-09-22 05:51:57 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_os_rng_tasks() {
|
|
|
|
|
2014-03-27 07:00:46 -05:00
|
|
|
let mut txs = vec!();
|
2015-02-17 08:47:49 -06:00
|
|
|
for _ in 0..20 {
|
2014-03-09 16:58:32 -05:00
|
|
|
let (tx, rx) = channel();
|
|
|
|
txs.push(tx);
|
2014-12-06 20:34:37 -06:00
|
|
|
|
2015-02-17 17:10:25 -06:00
|
|
|
thread::spawn(move|| {
|
2015-05-08 10:12:29 -05:00
|
|
|
// wait until all the threads are ready to go.
|
2014-12-23 13:53:35 -06:00
|
|
|
rx.recv().unwrap();
|
2013-09-22 05:51:57 -05:00
|
|
|
|
|
|
|
// deschedule to attempt to interleave things as much
|
|
|
|
// as possible (XXX: is this a good test?)
|
2014-05-29 23:37:31 -05:00
|
|
|
let mut r = OsRng::new().unwrap();
|
2015-02-17 17:10:25 -06:00
|
|
|
thread::yield_now();
|
2015-03-03 02:42:26 -06:00
|
|
|
let mut v = [0; 1000];
|
2013-09-22 05:51:57 -05:00
|
|
|
|
2015-02-17 08:47:49 -06:00
|
|
|
for _ in 0..100 {
|
2013-09-22 05:51:57 -05:00
|
|
|
r.next_u32();
|
2015-02-17 17:10:25 -06:00
|
|
|
thread::yield_now();
|
2013-09-22 05:51:57 -05:00
|
|
|
r.next_u64();
|
2015-02-17 17:10:25 -06:00
|
|
|
thread::yield_now();
|
2014-11-17 02:39:01 -06:00
|
|
|
r.fill_bytes(&mut v);
|
2015-02-17 17:10:25 -06:00
|
|
|
thread::yield_now();
|
2013-09-22 05:51:57 -05:00
|
|
|
}
|
2015-01-05 23:59:45 -06:00
|
|
|
});
|
2013-09-22 05:51:57 -05:00
|
|
|
}
|
|
|
|
|
2015-05-08 10:12:29 -05:00
|
|
|
// start all the threads
|
2015-01-31 11:20:46 -06:00
|
|
|
for tx in &txs {
|
2014-12-23 13:53:35 -06:00
|
|
|
tx.send(()).unwrap();
|
2013-09-22 05:51:57 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|