tempfile/
util.rs

1use std::ffi::{OsStr, OsString};
2use std::path::{Path, PathBuf};
3use std::{io, iter::repeat_with};
4
5use crate::error::IoResultExt;
6
7fn tmpname(rng: &mut fastrand::Rng, prefix: &OsStr, suffix: &OsStr, rand_len: usize) -> OsString {
8    let capacity = prefix
9        .len()
10        .saturating_add(suffix.len())
11        .saturating_add(rand_len);
12    let mut buf = OsString::with_capacity(capacity);
13    buf.push(prefix);
14    let mut char_buf = [0u8; 4];
15    for c in repeat_with(|| rng.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    // Make the path absolute. Otherwise, changing the current directory can invalidate a stored
30    // path (causing issues when cleaning up temporary files.
31    let mut base = base; // re-borrow to shrink lifetime
32    let base_path_storage; // slot to store the absolute path, if necessary.
33    if !base.is_absolute() {
34        let cur_dir = std::env::current_dir()?;
35        base_path_storage = cur_dir.join(base);
36        base = &base_path_storage;
37    }
38
39    let num_retries = if random_len != 0 {
40        crate::NUM_RETRIES
41    } else {
42        1
43    };
44
45    // We fork the fastrand rng.
46    let mut rng = fastrand::Rng::new();
47    for i in 0..num_retries {
48        // If we fail to create the file the first three times, re-seed from system randomness in
49        // case an attacker is predicting our randomness (fastrand is predictable). If re-seeding
50        // doesn't help, either:
51        //
52        // 1. We have lots of temporary files, possibly created by an attacker but not necessarily.
53        //    Re-seeding the randomness won't help here.
54        // 2. We're failing to create random files for some other reason. This shouldn't be the case
55        //    given that we're checking error kinds, but it could happen.
56        #[cfg(all(
57            feature = "getrandom",
58            any(windows, unix, target_os = "redox", target_os = "wasi")
59        ))]
60        if i == 3 {
61            if let Ok(seed) = getrandom::u64() {
62                rng.seed(seed);
63            }
64        }
65        let path = base.join(tmpname(&mut rng, prefix, suffix, random_len));
66        return match f(path) {
67            Err(ref e) if e.kind() == io::ErrorKind::AlreadyExists && num_retries > 1 => continue,
68            // AddrInUse can happen if we're creating a UNIX domain socket and
69            // the path already exists.
70            Err(ref e) if e.kind() == io::ErrorKind::AddrInUse && num_retries > 1 => continue,
71            res => res,
72        };
73    }
74
75    Err(io::Error::new(
76        io::ErrorKind::AlreadyExists,
77        "too many temporary files exist",
78    ))
79    .with_err_path(|| base)
80}