Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace fastrand with getrandom and base64 #188

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,9 @@ repository = "https://github.com/Stebalien/tempfile"
description = "A library for managing temporary files and directories."

[dependencies]
base64 = "0.13.0"
cfg-if = "1"
fastrand = "1.6.0"
getrandom = { version = "0.2.7", features = ["std"] }
remove_dir_all = "0.5"

[target.'cfg(any(unix, target_os = "wasi"))'.dependencies]
Expand Down
45 changes: 38 additions & 7 deletions src/util.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,47 @@
use std::ffi::{OsStr, OsString};
use std::path::{Path, PathBuf};
use std::{io, iter::repeat_with};
use std::io;
use std::io::ErrorKind;

use crate::error::IoResultExt;

fn tmpname(prefix: &OsStr, suffix: &OsStr, rand_len: usize) -> OsString {
fn calculate_rand_buf_len(alphanumeric_len: usize) -> usize {
let expected_non_alphanumeric_chars = alphanumeric_len / 32;
(alphanumeric_len + expected_non_alphanumeric_chars) * 3 / 4 + 3
}

fn calculate_base64_len(binary_len: usize) -> usize {
binary_len * 4 / 3 + 4
}

fn fill_with_random_base64(rand_buf: &mut [u8], char_buf: &mut Vec<u8>) -> Result<(), getrandom::Error> {
getrandom::getrandom(rand_buf)?;
char_buf.resize(calculate_base64_len(rand_buf.len()), 0);
base64::encode_config_slice(rand_buf, base64::STANDARD_NO_PAD, char_buf);
Ok(())
}

fn tmpname(prefix: &OsStr, suffix: &OsStr, rand_len: usize) -> Result<OsString, getrandom::Error> {
let mut buf = OsString::with_capacity(prefix.len() + suffix.len() + rand_len);
buf.push(prefix);
let mut char_buf = [0u8; 4];
for c in repeat_with(fastrand::alphanumeric).take(rand_len) {
buf.push(c.encode_utf8(&mut char_buf));

let mut rand_buf = vec![0; calculate_rand_buf_len(rand_len)];
let mut char_buf = vec![0; calculate_base64_len(rand_buf.len())];
let mut remaining_chars = rand_len;
loop {
fill_with_random_base64(&mut rand_buf, &mut char_buf)?;
char_buf.retain(|&c| (c != b'+') & (c != b'/') & (c != 0));
if char_buf.len() >= remaining_chars {
buf.push(std::str::from_utf8(&char_buf[..remaining_chars]).unwrap());
break;
} else {
buf.push(std::str::from_utf8(&char_buf).unwrap());
remaining_chars -= char_buf.len();
}
}

buf.push(suffix);
buf
Ok(buf)
}

pub fn create_helper<F, R>(
Expand All @@ -32,7 +61,9 @@ where
};

for _ in 0..num_retries {
let path = base.join(tmpname(prefix, suffix, random_len));
let name = tmpname(prefix, suffix, random_len)
.map_err(|e| io::Error::new(ErrorKind::Other, e))?;
let path = base.join(name);
return match f(path) {
Err(ref e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
// AddrInUse can happen if we're creating a UNIX domain socket and
Expand Down
25 changes: 11 additions & 14 deletions tests/namedtempfile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use std::ffi::{OsStr, OsString};
use std::fs::File;
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::sync::Barrier;
use tempfile::{tempdir, Builder, NamedTempFile, TempPath};

fn exists<P: AsRef<Path>>(path: P) -> bool {
Expand Down Expand Up @@ -403,39 +404,35 @@ fn test_make_uds_conflict() {
let tries = Arc::new(AtomicUsize::new(0));

let mut threads = Vec::with_capacity(NTHREADS);
let barrier = Arc::new(Barrier::new(NTHREADS));

for _ in 0..NTHREADS {
let c = Arc::clone(&barrier);
let tries = tries.clone();
threads.push(std::thread::spawn(move || {
// Ensure that every thread uses the same seed so we are guaranteed
// to retry. Note that fastrand seeds are thread-local.
fastrand::seed(42);

Builder::new()
let builder = Builder::new()
.prefix("tmp")
.suffix(".sock")
.rand_bytes(12)
.rand_bytes(1)
.make(|path| {
tries.fetch_add(1, Ordering::Relaxed);
UnixListener::bind(path)
})
});
c.wait();
builder
}));
}

// Join all threads, but don't drop the temp file yet. Otherwise, we won't
// get a deterministic number of `tries`.
// Join all threads, but don't drop the temp file yet.
let sockets: Vec<_> = threads
.into_iter()
.map(|thread| thread.join().unwrap().unwrap())
.collect();

// Number of tries is exactly equal to (n*(n+1))/2.
assert_eq!(
tries.load(Ordering::Relaxed),
(NTHREADS * (NTHREADS + 1)) / 2
);
assert!(tries.load(Ordering::Relaxed) > 15);

for socket in sockets {
assert!(socket.path().exists());
}
}