1use std::ffi::{OsStr, OsString};
2use std::path::{Path, PathBuf};
3use std::{io, iter::repeat_with};
4
5use crate::error::IoResultExt;
6
7fn tmpname(prefix: &OsStr, suffix: &OsStr, rand_len: usize) -> OsString {
8 let capacity: usize = prefixusize
9 .len()
10 .saturating_add(suffix.len())
11 .saturating_add(rand_len);
12 let mut buf: OsString = OsString::with_capacity(capacity);
13 buf.push(prefix);
14 let mut char_buf: [u8; 4] = [0u8; 4];
15 for c: char in repeat_with(repeater:fastrand::alphanumeric).take(rand_len) {
16 buf.push(c.encode_utf8(&mut char_buf));
17 }
18 buf.push(suffix);
19 buf
20}
21
22pub fn create_helper<R>(
23 base: &Path,
24 prefix: &OsStr,
25 suffix: &OsStr,
26 random_len: usize,
27 mut f: impl FnMut(PathBuf) -> io::Result<R>,
28) -> io::Result<R> {
29 let num_retries = if random_len != 0 {
30 crate::NUM_RETRIES
31 } else {
32 1
33 };
34
35 for i in 0..num_retries {
36 // If we fail to create the file the first three times, re-seed from system randomness in
37 // case an attacker is predicting our randomness (fastrand is predictable). If re-seeding
38 // doesn't help, either:
39 //
40 // 1. We have lots of temporary files, possibly created by an attacker but not necessarily.
41 // Re-seeding the randomness won't help here.
42 // 2. We're failing to create random files for some other reason. This shouldn't be the case
43 // given that we're checking error kinds, but it could happen.
44 #[cfg(all(
45 feature = "getrandom",
46 any(windows, unix, target_os = "redox", target_os = "wasi")
47 ))]
48 if i == 3 {
49 let mut seed = [0u8; 8];
50 if getrandom::getrandom(&mut seed).is_ok() {
51 fastrand::seed(u64::from_ne_bytes(seed));
52 }
53 }
54 let path = base.join(tmpname(prefix, suffix, random_len));
55 return match f(path) {
56 Err(ref e) if e.kind() == io::ErrorKind::AlreadyExists && num_retries > 1 => continue,
57 // AddrInUse can happen if we're creating a UNIX domain socket and
58 // the path already exists.
59 Err(ref e) if e.kind() == io::ErrorKind::AddrInUse && num_retries > 1 => continue,
60 res => res,
61 };
62 }
63
64 Err(io::Error::new(
65 io::ErrorKind::AlreadyExists,
66 "too many temporary files exist",
67 ))
68 .with_err_path(|| base)
69}
70