extern crate std;
use crate::Error;
use crate::utils::use_init;
use std::{thread_local, io::{self, Read}, fs::File};
use core::cell::RefCell;
use core::num::NonZeroU32;
#[cfg(target_os = "illumos")]
type GetRandomFn = unsafe extern "C" fn(*mut u8, libc::size_t, libc::c_uint) -> libc::ssize_t;
#[cfg(target_os = "solaris")]
type GetRandomFn = unsafe extern "C" fn(*mut u8, libc::size_t, libc::c_uint) -> libc::c_int;
enum RngSource {
GetRandom(GetRandomFn),
Device(File),
}
thread_local!(
static RNG_SOURCE: RefCell<Option<RngSource>> = RefCell::new(None);
);
fn libc_getrandom(rand: GetRandomFn, dest: &mut [u8]) -> Result<(), Error> {
let ret = unsafe { rand(dest.as_mut_ptr(), dest.len(), 0) as libc::ssize_t };
if ret == -1 || ret != dest.len() as libc::ssize_t {
error!("getrandom syscall failed with ret={}", ret);
Err(io::Error::last_os_error().into())
} else {
Ok(())
}
}
pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
RNG_SOURCE.with(|f| {
use_init(
f,
|| {
let s = match fetch_getrandom() {
Some(fptr) => RngSource::GetRandom(fptr),
None => RngSource::Device(File::open("/dev/random")?),
};
Ok(s)
},
|f| {
match f {
RngSource::GetRandom(rp) => {
for chunk in dest.chunks_mut(256) {
libc_getrandom(*rp, chunk)?
}
}
RngSource::Device(randf) => {
for chunk in dest.chunks_mut(256) {
randf.read_exact(chunk)?
}
}
};
Ok(())
},
)
})
}
fn fetch_getrandom() -> Option<GetRandomFn> {
use std::mem;
use std::sync::atomic::{AtomicUsize, Ordering};
static FPTR: AtomicUsize = AtomicUsize::new(1);
if FPTR.load(Ordering::SeqCst) == 1 {
let name = "getrandom\0";
let addr = unsafe { libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr() as *const _) as usize };
FPTR.store(addr, Ordering::SeqCst);
}
let ptr = FPTR.load(Ordering::SeqCst);
unsafe { mem::transmute::<usize, Option<GetRandomFn>>(ptr) }
}
#[inline(always)]
pub fn error_msg_inner(_: NonZeroU32) -> Option<&'static str> { None }