use atomic bool to check RNG initialization

This commit is contained in:
newpavlov
2019-02-06 13:47:36 +03:00
parent 5ebbaf787e
commit f860bde8d8
3 changed files with 14 additions and 5 deletions
-2
View File
@@ -5,8 +5,6 @@
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![no_std]
#[cfg(any(
+7 -2
View File
@@ -15,6 +15,9 @@ use std::fs::File;
use std::io;
use std::io::Read;
use std::cell::RefCell;
use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Ordering};
static RNG_INIT: AtomicBool = ATOMIC_BOOL_INIT;
enum RngSource {
GetRandom,
@@ -44,7 +47,10 @@ pub fn getrandom(dest: &mut [u8]) -> Result<(), Error> {
} else {
// read one byte from "/dev/random" to ensure that
// OS RNG has initialized
File::open("/dev/random")?.read_exact(&mut [0u8; 1])?;
if !RNG_INIT.load(Ordering::Relaxed) {
File::open("/dev/random")?.read_exact(&mut [0u8; 1])?;
RNG_INIT.store(true, Ordering::Relaxed)
}
RngSource::Device(File::open("/dev/urandom")?)
};
Ok(s)
@@ -58,7 +64,6 @@ pub fn getrandom(dest: &mut [u8]) -> Result<(), Error> {
}
fn is_getrandom_available() -> bool {
use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Ordering};
use std::sync::{Once, ONCE_INIT};
static CHECKER: Once = ONCE_INIT;
+7 -1
View File
@@ -13,6 +13,9 @@ use super::utils::use_init;
use std::fs::File;
use std::io::Read;
use std::cell::RefCell;
use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Ordering};
static RNG_INIT: AtomicBool = ATOMIC_BOOL_INIT;
thread_local!(static RNG_FILE: RefCell<Option<File>> = RefCell::new(None));
@@ -21,7 +24,10 @@ pub fn getrandom(dest: &mut [u8]) -> Result<(), Error> {
use_init(f, || {
// read one byte from "/dev/random" to ensure that
// OS RNG has initialized
File::open("/dev/random")?.read_exact(&mut [0u8; 1])?;
if !RNG_INIT.load(Ordering::Relaxed) {
File::open("/dev/random")?.read_exact(&mut [0u8; 1])?;
RNG_INIT.store(true, Ordering::Relaxed)
}
File::open("/dev/urandom")
}, |f| f.read_exact(dest))
}).map_err(|_| Error::Unknown)