Skip to content

Commit

Permalink
Remove libstd for opening/reading files
Browse files Browse the repository at this point in the history
  • Loading branch information
josephlr committed Jul 9, 2019
1 parent 0931408 commit 1426f2e
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 19 deletions.
53 changes: 34 additions & 19 deletions src/use_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,13 @@
//! Implementations that just need to read from a file
extern crate std;

use crate::util_libc::{last_os_error, LazyFd};
use crate::util_libc::{last_os_error, open_readonly, sys_fill_exact, LazyFd};
use crate::Error;
use core::mem::ManuallyDrop;
use std::os::unix::io::{FromRawFd, IntoRawFd, RawFd};
use std::{fs::File, io::Read};

#[cfg(target_os = "redox")]
const FILE_PATH: &str = "rand:";
const FILE_PATH: &str = "rand:\0";
#[cfg(any(target_os = "android", target_os = "linux", target_os = "netbsd"))]
const FILE_PATH: &str = "/dev/urandom";
const FILE_PATH: &str = "/dev/urandom\0";
#[cfg(any(
target_os = "dragonfly",
target_os = "emscripten",
Expand All @@ -27,32 +24,50 @@ const FILE_PATH: &str = "/dev/urandom";
target_os = "solaris",
target_os = "illumos"
))]
const FILE_PATH: &str = "/dev/random";
const FILE_PATH: &str = "/dev/random\0";

pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
static FD: LazyFd = LazyFd::new();
let fd = FD.init(init_file).ok_or(last_os_error())?;
let file = ManuallyDrop::new(unsafe { File::from_raw_fd(fd) });
let mut file_ref: &File = &file;
let read = |buf: &mut [u8]| unsafe { libc::read(fd, buf.as_mut_ptr() as *mut _, buf.len()) };

if cfg!(target_os = "emscripten") {
// `Crypto.getRandomValues` documents `dest` should be at most 65536 bytes.
for chunk in dest.chunks_mut(65536) {
file_ref.read_exact(chunk)?;
sys_fill_exact(chunk, read)?;
}
} else {
file_ref.read_exact(dest)?;
sys_fill_exact(dest, read)?;
}
Ok(())
}

fn init_file() -> Option<RawFd> {
if FILE_PATH == "/dev/urandom" {
// read one byte from "/dev/random" to ensure that OS RNG has initialized
File::open("/dev/random")
.ok()?
.read_exact(&mut [0u8; 1])
.ok()?;
fn init_file() -> Option<libc::c_int> {
if FILE_PATH == "/dev/urandom\0" {
// Poll /dev/random to make sure it is ok to read from /dev/urandom.
let mut pfd = libc::pollfd {
fd: unsafe { open_readonly("/dev/random\0")? },
events: libc::POLLIN,
revents: 0,
};

let mut res = -1;
while res <= 0 {
// A negative timeout means an infinite timeout.
res = unsafe { libc::poll(&mut pfd, 1, -1) };
if res < 0 {
match last_os_error().raw_os_error() {
Some(libc::EINTR) | Some(libc::EAGAIN) => {}
_ => break,
}
}
}

unsafe { libc::close(pfd.fd) };
if res != 1 {
// We either hard failed, or poll() returned the wrong pfd.
return None;
}
}
Some(File::open(FILE_PATH).ok()?.into_raw_fd())
unsafe { open_readonly(FILE_PATH) }
}
18 changes: 18 additions & 0 deletions src/util_libc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,3 +121,21 @@ impl LazyFd {
}
}
}

cfg_if! {
if #[cfg(any(target_os = "linux", target_os = "emscripten", target_os = "l4re"))] {
use libc::open64 as open;
} else {
use libc::open;
}
}

// SAFETY: path must be null terminated, FD must be manually closed.
pub unsafe fn open_readonly(path: &str) -> Option<libc::c_int> {
let fd = open(path.as_ptr() as *mut _, libc::O_RDONLY | libc::O_CLOEXEC);
if fd < 0 {
None
} else {
Some(fd)
}
}

0 comments on commit 1426f2e

Please sign in to comment.