Skip to content

Commit b69f832

Browse files
josephlrnewpavlov
authored andcommitted
Remove libstd dependancy for Opening and Reading files (#58)
1 parent 199b115 commit b69f832

File tree

5 files changed

+68
-42
lines changed

5 files changed

+68
-42
lines changed

Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ log = { version = "0.4", optional = true }
2222
cfg-if = "0.1"
2323

2424
[target.'cfg(any(unix, target_os = "redox", target_os = "wasi"))'.dependencies]
25-
libc = "0.2.60"
25+
libc = { version = "0.2.60", default-features = false }
2626

2727
[target.wasm32-unknown-unknown.dependencies]
2828
wasm-bindgen = { version = "0.2.29", optional = true }

README.md

+4-1
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,10 @@ fn get_random_buf() -> Result<[u8; 32], getrandom::Error> {
4040

4141
## Features
4242

43-
This library is `no_std` compatible, but uses `std` on most platforms.
43+
This library is `no_std` for every supported target. However, getting randomness
44+
usually requires calling some external system API. This means most platforms
45+
will require linking against system libraries (i.e. `libc` for Unix,
46+
`Advapi32.dll` for Windows, Security framework on iOS, etc...).
4447

4548
The `log` library is supported as an optional dependency. If enabled, error
4649
reporting will be improved on some platforms.

src/lib.rs

+4-18
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,13 @@
1212
//!
1313
//! | OS | interface
1414
//! |------------------|---------------------------------------------------------
15-
//! | Linux, Android | [`getrandom`][1] system call if available, otherwise [`/dev/urandom`][2] after reading from `/dev/random` once
15+
//! | Linux, Android | [`getrandom`][1] system call if available, otherwise [`/dev/urandom`][2] after successfully polling `/dev/random`
1616
//! | Windows | [`RtlGenRandom`][3]
1717
//! | macOS | [`getentropy()`][19] if available, otherwise [`/dev/random`][20] (identical to `/dev/urandom`)
1818
//! | iOS | [`SecRandomCopyBytes`][4]
1919
//! | FreeBSD | [`getrandom()`][21] if available, otherwise [`kern.arandom`][5]
2020
//! | OpenBSD | [`getentropy`][6]
21-
//! | NetBSD | [`/dev/urandom`][7] after reading from `/dev/random` once
21+
//! | NetBSD | [`/dev/urandom`][7] after successfully polling `/dev/random`
2222
//! | Dragonfly BSD | [`/dev/random`][8]
2323
//! | Solaris, illumos | [`getrandom`][9] system call if available, otherwise [`/dev/random`][10]
2424
//! | Fuchsia OS | [`cprng_draw`][11]
@@ -152,22 +152,8 @@ mod util;
152152
#[allow(dead_code)]
153153
mod util_libc;
154154

155-
// std-only trait definitions (also need for use_file)
156-
#[cfg(any(
157-
feature = "std",
158-
target_os = "android",
159-
target_os = "dragonfly",
160-
target_os = "emscripten",
161-
target_os = "freebsd",
162-
target_os = "haiku",
163-
target_os = "illumos",
164-
target_os = "linux",
165-
target_os = "macos",
166-
target_os = "netbsd",
167-
target_os = "openbsd",
168-
target_os = "redox",
169-
target_os = "solaris",
170-
))]
155+
// std-only trait definitions
156+
#[cfg(feature = "std")]
171157
mod error_impls;
172158

173159
// These targets read from a file as a fallback method.

src/use_file.rs

+37-22
Original file line numberDiff line numberDiff line change
@@ -7,18 +7,11 @@
77
// except according to those terms.
88

99
//! Implementations that just need to read from a file
10-
extern crate std;
11-
12-
use crate::util_libc::{last_os_error, LazyFd};
10+
use crate::util_libc::{last_os_error, open_readonly, sys_fill_exact, LazyFd};
1311
use crate::Error;
14-
use core::mem::ManuallyDrop;
15-
use std::os::unix::io::{FromRawFd, IntoRawFd, RawFd};
16-
use std::{fs::File, io::Read};
1712

1813
#[cfg(target_os = "redox")]
19-
const FILE_PATH: &str = "rand:";
20-
#[cfg(any(target_os = "android", target_os = "linux", target_os = "netbsd"))]
21-
const FILE_PATH: &str = "/dev/urandom";
14+
const FILE_PATH: &str = "rand:\0";
2215
#[cfg(any(
2316
target_os = "dragonfly",
2417
target_os = "emscripten",
@@ -27,32 +20,54 @@ const FILE_PATH: &str = "/dev/urandom";
2720
target_os = "solaris",
2821
target_os = "illumos"
2922
))]
30-
const FILE_PATH: &str = "/dev/random";
23+
const FILE_PATH: &str = "/dev/random\0";
3124

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

3830
if cfg!(target_os = "emscripten") {
3931
// `Crypto.getRandomValues` documents `dest` should be at most 65536 bytes.
4032
for chunk in dest.chunks_mut(65536) {
41-
file_ref.read_exact(chunk)?;
33+
sys_fill_exact(chunk, read)?;
4234
}
4335
} else {
44-
file_ref.read_exact(dest)?;
36+
sys_fill_exact(dest, read)?;
4537
}
4638
Ok(())
4739
}
4840

49-
fn init_file() -> Option<RawFd> {
50-
if FILE_PATH == "/dev/urandom" {
51-
// read one byte from "/dev/random" to ensure that OS RNG has initialized
52-
File::open("/dev/random")
53-
.ok()?
54-
.read_exact(&mut [0u8; 1])
55-
.ok()?;
41+
cfg_if! {
42+
if #[cfg(any(target_os = "android", target_os = "linux", target_os = "netbsd"))] {
43+
fn init_file() -> Option<libc::c_int> {
44+
// Poll /dev/random to make sure it is ok to read from /dev/urandom.
45+
let mut pfd = libc::pollfd {
46+
fd: unsafe { open_readonly("/dev/random\0")? },
47+
events: libc::POLLIN,
48+
revents: 0,
49+
};
50+
51+
let ret = loop {
52+
// A negative timeout means an infinite timeout.
53+
let res = unsafe { libc::poll(&mut pfd, 1, -1) };
54+
if res == 1 {
55+
break unsafe { open_readonly("/dev/urandom\0") };
56+
} else if res < 0 {
57+
let e = last_os_error().raw_os_error();
58+
if e == Some(libc::EINTR) || e == Some(libc::EAGAIN) {
59+
continue;
60+
}
61+
}
62+
// We either hard failed, or poll() returned the wrong pfd.
63+
break None;
64+
};
65+
unsafe { libc::close(pfd.fd) };
66+
ret
67+
}
68+
} else {
69+
fn init_file() -> Option<libc::c_int> {
70+
unsafe { open_readonly(FILE_PATH) }
71+
}
5672
}
57-
Some(File::open(FILE_PATH).ok()?.into_raw_fd())
5873
}

src/util_libc.rs

+22
Original file line numberDiff line numberDiff line change
@@ -116,3 +116,25 @@ impl LazyFd {
116116
}
117117
}
118118
}
119+
120+
cfg_if! {
121+
if #[cfg(any(target_os = "linux", target_os = "emscripten"))] {
122+
use libc::open64 as open;
123+
} else {
124+
use libc::open;
125+
}
126+
}
127+
128+
// SAFETY: path must be null terminated, FD must be manually closed.
129+
pub unsafe fn open_readonly(path: &str) -> Option<libc::c_int> {
130+
debug_assert!(path.as_bytes().last() == Some(&0));
131+
let fd = open(path.as_ptr() as *mut _, libc::O_RDONLY | libc::O_CLOEXEC);
132+
if fd < 0 {
133+
return None;
134+
}
135+
// O_CLOEXEC works on all Unix targets except for older Linux kernels (pre
136+
// 2.6.23), so we also use an ioctl to make sure FD_CLOEXEC is set.
137+
#[cfg(target_os = "linux")]
138+
libc::ioctl(fd, libc::FIOCLEX);
139+
Some(fd)
140+
}

0 commit comments

Comments
 (0)