From 0aa52ef4e63148c30eb5958ebbbeed399009341d Mon Sep 17 00:00:00 2001 From: Joe Richey Date: Sun, 7 Jul 2019 02:38:46 -0700 Subject: [PATCH] Remove libstd for opening/reading files --- src/lib.rs | 18 ++-------------- src/use_file.rs | 55 ++++++++++++++++++++++++++++++------------------ src/util_libc.rs | 18 ++++++++++++++++ 3 files changed, 54 insertions(+), 37 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 03e1cc48..c6e008fc 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -152,22 +152,8 @@ mod util; #[allow(dead_code)] mod util_libc; -// std-only trait definitions (also need for use_file) -#[cfg(any( - feature = "std", - target_os = "android", - target_os = "dragonfly", - target_os = "emscripten", - target_os = "freebsd", - target_os = "haiku", - target_os = "illumos", - target_os = "linux", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd", - target_os = "redox", - target_os = "solaris", -))] +// std-only trait definitions +#[cfg(feature = "std")] mod error_impls; // These targets read from a file as a fallback method. diff --git a/src/use_file.rs b/src/use_file.rs index 74a12ef7..a1a01c9b 100644 --- a/src/use_file.rs +++ b/src/use_file.rs @@ -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::{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", @@ -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)?; + sys_fill_exact(chunk, read)?; } } else { - file_ref.read_exact(dest)?; + sys_fill_exact(dest, read)?; } Ok(()) } -fn init_file() -> Option { - 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 { + 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) } } diff --git a/src/util_libc.rs b/src/util_libc.rs index 033a2f86..42bde39a 100644 --- a/src/util_libc.rs +++ b/src/util_libc.rs @@ -109,3 +109,21 @@ impl LazyFd { } } } + +cfg_if! { + if #[cfg(any(target_os = "linux", target_os = "emscripten"))] { + 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 { + // We don't care about Linux OSes too old to support O_CLOEXEC. + let fd = open(path.as_ptr() as *mut _, libc::O_RDONLY | libc::O_CLOEXEC); + if fd < 0 { + return None; + } + Some(fd) +}