use crate::stdlib::common::throws;
use crate::stdlib::fileres::strerror;
#[cfg(target_os = "macos")]
pub(crate) fn random_bytes_ex(bytes: &mut [u8]) -> Result<(), String> {
extern "C" {
fn CCRandomGenerateBytes(bytes: *mut libc::c_void, count: libc::size_t) -> i32;
}
if unsafe { CCRandomGenerateBytes(bytes.as_mut_ptr().cast(), bytes.len()) } != 0 {
return Err(
"Failed to retrieve randomness from the operating system (CCRandomGenerateBytes)"
.to_string(),
);
}
Ok(())
}
#[cfg(any(target_os = "openbsd", target_os = "netbsd", target_os = "haiku"))]
pub(crate) fn random_bytes_ex(bytes: &mut [u8]) -> Result<(), String> {
unsafe { libc::arc4random_buf(bytes.as_mut_ptr().cast(), bytes.len()) };
Ok(())
}
#[cfg(not(any(
target_os = "macos",
target_os = "openbsd",
target_os = "netbsd",
target_os = "haiku"
)))]
pub(crate) fn random_bytes_ex(bytes: &mut [u8]) -> Result<(), String> {
if getrandom_fill(bytes) < bytes.len() {
urandom_fill(urandom_fd()?, bytes)?;
}
Ok(())
}
#[cfg(any(
target_os = "linux",
target_os = "android",
target_os = "freebsd",
target_os = "dragonfly",
target_os = "solaris",
target_os = "illumos"
))]
fn getrandom_fill(bytes: &mut [u8]) -> usize {
let mut read = 0;
while read < bytes.len() {
let rest = &mut bytes[read..];
#[cfg(any(target_os = "linux", target_os = "android"))]
let n = unsafe {
libc::syscall(libc::SYS_getrandom, rest.as_mut_ptr(), rest.len(), 0) as isize
};
#[cfg(not(any(target_os = "linux", target_os = "android")))]
let n = unsafe { libc::getrandom(rest.as_mut_ptr().cast(), rest.len(), 0) };
if n == -1 {
match std::io::Error::last_os_error().raw_os_error() {
Some(libc::EINTR) | Some(libc::EAGAIN) => continue,
_ => break,
}
}
read += n as usize;
}
read
}
#[cfg(not(any(
target_os = "macos",
target_os = "openbsd",
target_os = "netbsd",
target_os = "haiku",
target_os = "linux",
target_os = "android",
target_os = "freebsd",
target_os = "dragonfly",
target_os = "solaris",
target_os = "illumos"
)))]
fn getrandom_fill(_bytes: &mut [u8]) -> usize {
0
}
#[cfg_attr(
any(
target_os = "macos",
target_os = "openbsd",
target_os = "netbsd",
target_os = "haiku"
),
allow(dead_code)
)]
fn urandom_fd() -> Result<libc::c_int, String> {
use std::sync::atomic::{AtomicI32, Ordering};
static RANDOM_FD: AtomicI32 = AtomicI32::new(-1);
let fd = RANDOM_FD.load(Ordering::Acquire);
if fd >= 0 {
return Ok(fd);
}
let fd = open_urandom(c"/dev/urandom")?;
match RANDOM_FD.compare_exchange(-1, fd, Ordering::AcqRel, Ordering::Acquire) {
Ok(_) => Ok(fd),
Err(winner) => {
unsafe { libc::close(fd) };
Ok(winner)
}
}
}
#[cfg_attr(
any(
target_os = "macos",
target_os = "openbsd",
target_os = "netbsd",
target_os = "haiku"
),
allow(dead_code)
)]
fn open_urandom(path: &std::ffi::CStr) -> Result<libc::c_int, String> {
let fd = unsafe { libc::open(path.as_ptr(), libc::O_RDONLY) };
if fd < 0 {
return Err(with_errno("Cannot open /dev/urandom"));
}
let mut st: libc::stat = unsafe { std::mem::zeroed() };
let failed = unsafe { libc::fstat(fd, &mut st) } != 0;
if failed || (st.st_mode & libc::S_IFMT) != libc::S_IFCHR {
let msg = if failed {
with_errno("Error reading from /dev/urandom")
} else {
"Error reading from /dev/urandom".to_string()
};
unsafe { libc::close(fd) };
return Err(msg);
}
Ok(fd)
}
#[cfg_attr(
any(
target_os = "macos",
target_os = "openbsd",
target_os = "netbsd",
target_os = "haiku"
),
allow(dead_code)
)]
fn urandom_fill(fd: libc::c_int, bytes: &mut [u8]) -> Result<(), String> {
let mut read = 0;
while read < bytes.len() {
let rest = &mut bytes[read..];
let n = unsafe { libc::read(fd, rest.as_mut_ptr().cast(), rest.len()) };
if n == 0 {
return Err("Could not gather sufficient random data".to_string());
}
if n < 0 {
return Err(with_errno("Could not gather sufficient random data"));
}
read += n as usize;
}
Ok(())
}
#[cfg_attr(
any(
target_os = "macos",
target_os = "openbsd",
target_os = "netbsd",
target_os = "haiku"
),
allow(dead_code)
)]
fn with_errno(msg: &str) -> String {
format!("{msg}: {}", strerror(&std::io::Error::last_os_error()))
}
pub(crate) fn random_bytes_throw(bytes: &mut [u8]) -> Result<(), String> {
random_bytes_ex(bytes).map_err(|e| throws("Random\\RandomException", e))
}
pub(crate) fn random_int_throw(min: i64, max: i64) -> Result<i64, String> {
range(min, max, || {
let mut trial = [0u8; 8];
random_bytes_throw(&mut trial)?;
Ok(u64::from_ne_bytes(trial))
})
}
fn range(min: i64, max: i64, mut draw: impl FnMut() -> Result<u64, String>) -> Result<i64, String> {
if min == max {
return Ok(min);
}
let umax = (max as u64).wrapping_sub(min as u64);
let mut trial = draw()?;
if umax == u64::MAX {
return Ok(trial as i64);
}
let umax = umax + 1;
if umax & (umax - 1) != 0 {
let limit = u64::MAX - (u64::MAX % umax) - 1;
while trial > limit {
trial = draw()?;
}
}
Ok((trial % umax).wrapping_add(min as u64) as i64)
}
#[cfg(test)]
mod tests {
use super::*;
fn range_over(min: i64, max: i64, draws: &[u64]) -> (i64, usize) {
let mut it = draws.iter();
let mut taken = 0;
let v = range(min, max, || {
taken += 1;
Ok(*it.next().expect("range drew more than supplied"))
})
.unwrap();
(v, taken)
}
#[test]
fn equal_bounds_draw_nothing() {
assert_eq!(range_over(7, 7, &[]), (7, 0));
}
#[test]
fn full_width_span_is_the_raw_draw() {
assert_eq!(range_over(i64::MIN, i64::MAX, &[u64::MAX]), (-1, 1));
}
#[test]
fn power_of_two_span_never_rejects() {
assert_eq!(range_over(10, 13, &[u64::MAX]), (13, 1));
}
#[test]
fn draws_above_the_limit_are_rejected() {
assert_eq!(range_over(0, 2, &[u64::MAX, 5]), (2, 2));
assert_eq!(
range_over(0, 2, &[u64::MAX - 1]),
(((u64::MAX - 1) % 3) as i64, 1)
);
}
#[test]
fn negative_bounds_offset_without_overflow() {
assert_eq!(range_over(-5, -3, &[4]), (-4, 1));
assert_eq!(range_over(i64::MIN, i64::MIN + 1, &[1]), (i64::MIN + 1, 1));
}
#[test]
fn urandom_errors_use_the_reference_text() {
assert_eq!(
open_urandom(c"/nonexistent/phplang-urandom").unwrap_err(),
"Cannot open /dev/urandom: No such file or directory"
);
assert_eq!(
open_urandom(c"/etc/hosts").unwrap_err(),
"Error reading from /dev/urandom"
);
}
#[test]
fn urandom_short_read_is_insufficient_data() {
let fd = unsafe { libc::open(c"/dev/null".as_ptr(), libc::O_RDONLY) };
assert!(fd >= 0);
let mut buf = [0u8; 4];
assert_eq!(
urandom_fill(fd, &mut buf).unwrap_err(),
"Could not gather sufficient random data"
);
unsafe { libc::close(fd) };
}
#[test]
fn os_source_fills_the_buffer() {
let mut buf = [0u8; 64];
random_bytes_ex(&mut buf).unwrap();
assert!(buf.iter().any(|&b| b != 0));
}
}