Skip to content

Commit

Permalink
freebsd: Try getrandom() first
Browse files Browse the repository at this point in the history
  • Loading branch information
josephlr committed Jul 8, 2019
1 parent f3f947b commit 61eaf8f
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
14 changes: 11 additions & 3 deletions src/freebsd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@
// except according to those terms.

//! Implementation for FreeBSD
use crate::util_libc::fill_exact;
use crate::util_libc::{fill_exact, Weak};
use crate::Error;
use core::ptr;
use core::{mem, ptr};

type GetRandomFn = unsafe extern "C" fn(*mut u8, libc::size_t, libc::c_uint) -> libc::ssize_t;

fn kern_arnd(buf: &mut [u8]) -> libc::ssize_t {
static MIB: [libc::c_int; 2] = [libc::CTL_KERN, libc::KERN_ARND];
Expand All @@ -33,5 +35,11 @@ fn kern_arnd(buf: &mut [u8]) -> libc::ssize_t {
}

pub fn getrandom_inner(dest: &mut [u8]) -> Result<(), Error> {
fill_exact(dest, kern_arnd)
static GETRANDOM: Weak = unsafe { Weak::new("getrandom\0") };
if let Some(fptr) = GETRANDOM.ptr() {
let func: GetRandomFn = unsafe { mem::transmute(fptr) };
fill_exact(dest, |buf| unsafe { func(buf.as_mut_ptr(), buf.len(), 0) })
} else {
fill_exact(dest, kern_arnd)
}
}
3 changes: 2 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
//! | Windows | [`RtlGenRandom`][3]
//! | macOS | [`getentropy()`][19] if available, otherise [`/dev/random`][20] (identical to `/dev/urandom`)
//! | iOS | [`SecRandomCopyBytes`][4]
//! | FreeBSD | [`kern.arandom`][5]
//! | FreeBSD | [`getrandom()`][21] if available, otherise [`kern.arandom`][5]
//! | OpenBSD | [`getentropy`][6]
//! | NetBSD | [`/dev/urandom`][7] after reading from `/dev/random` once
//! | Dragonfly BSD | [`/dev/random`][8]
Expand Down Expand Up @@ -101,6 +101,7 @@
//! [18]: https://software.intel.com/en-us/articles/intel-digital-random-number-generator-drng-software-implementation-guide
//! [19]: https://www.unix.com/man-page/mojave/2/getentropy/
//! [20]: https://www.unix.com/man-page/mojave/4/random/
//! [21]: https://www.freebsd.org/cgi/man.cgi?query=getrandom&manpath=FreeBSD+12.0-stable

#![doc(
html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png",
Expand Down

0 comments on commit 61eaf8f

Please sign in to comment.