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 a2a9161 commit 116738a
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 21 deletions.
55 changes: 34 additions & 21 deletions src/use_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,13 @@
// except according to those terms.

//! Implementations that just need to read from a file
extern crate std;

use crate::util_libc::{last_os_error, LazyFd};
use crate::util_libc::{fill_exact, last_os_error, open_readonly, 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 +22,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)?;
fill_exact(chunk, read)?;
}
} else {
file_ref.read_exact(dest)?;
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) }
}
19 changes: 19 additions & 0 deletions src/util_libc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,3 +115,22 @@ 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> {
// We don't care about kernels too old to support O_CLOEXEC.
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 116738a

Please sign in to comment.