use std::{
io,
path::{Path, PathBuf},
};
pub fn create_private_dir_all(path: &Path) -> io::Result<()> {
let result = match super::create_private_dir(path) {
Err(error) if error.kind() == io::ErrorKind::NotFound => {
let parent = path
.parent()
.filter(|path| !path.as_os_str().is_empty())
.ok_or(error)?;
match parent.metadata() {
Ok(metadata) if metadata.is_dir() => {}
Ok(_) => return Err(io::ErrorKind::NotADirectory.into()),
Err(error) if error.kind() == io::ErrorKind::NotFound => {
create_private_dir_all(parent)?;
}
Err(error) => return Err(error),
}
super::create_private_dir(path)
}
result => result,
};
match result {
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
#[cfg(unix)]
return super::unix::restrict_directory(path);
#[cfg(windows)]
super::windows::restrict_directory(path)
}
result => result,
}
}
pub(in crate::platform) struct ScratchParent {
path: PathBuf,
#[cfg(windows)]
guards: std::sync::Arc<[std::fs::File]>,
}
impl ScratchParent {
pub(in crate::platform) fn open(path: &Path) -> io::Result<Self> {
let path = super::super::paths::canonical_target(path)?;
#[cfg(windows)]
let guards = super::windows::pin_scratch_parent(&path)?.into();
Ok(Self {
path,
#[cfg(windows)]
guards,
})
}
pub(in crate::platform) fn path(&self) -> &Path {
&self.path
}
fn create(&self, name: &str) -> io::Result<PrivateTempDir> {
let path = self.path().join(name);
#[cfg(unix)]
super::create_private_dir(&path)?;
#[cfg(windows)]
let directory = {
let directory = super::pinned::create_scratch(
self.guards.last().expect("parent has a pinned root"),
name.as_ref(),
)?;
let by_path = super::super::files::open_directory(&path)?;
if super::file_identity(&directory)? != super::file_identity(&by_path)? {
return Err(io::ErrorKind::PermissionDenied.into());
}
directory
};
Ok(PrivateTempDir {
path: Some(path),
#[cfg(windows)]
guards: Box::new(ScratchGuards {
child: Some(directory),
_parent: self.guards.clone(),
}),
})
}
}
pub fn private_tempdir_in(prefix: &str, parent: &Path) -> io::Result<PrivateTempDir> {
ScratchParent::open(parent)?.create_temp(prefix)
}
impl ScratchParent {
pub(in crate::platform) fn create_temp(&self, prefix: &str) -> io::Result<PrivateTempDir> {
super::checked_basename(&format!("{prefix}{:0SUFFIX_LENGTH$}", 0))?;
const CREATE_ATTEMPTS: usize = 128;
for _ in 0..CREATE_ATTEMPTS {
let suffix = random_suffix()?;
let name = format!("{prefix}{suffix}");
match self.create(&name) {
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
result => return result,
}
}
Err(io::Error::new(
io::ErrorKind::AlreadyExists,
"could not create a unique private temporary directory",
))
}
}
const SUFFIX_LENGTH: usize = 6;
fn random_suffix() -> io::Result<String> {
const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
const RADIX: u64 = ALPHABET.len() as u64;
const NAME_COUNT: u64 = RADIX.pow(SUFFIX_LENGTH as u32);
let mut value = loop {
let random = getrandom::u64().map_err(io::Error::other)?;
if random < u64::MAX - u64::MAX % NAME_COUNT {
break random;
}
};
let mut suffix = String::with_capacity(SUFFIX_LENGTH);
for _ in 0..SUFFIX_LENGTH {
suffix.push(char::from(ALPHABET[(value % RADIX) as usize]));
value /= RADIX;
}
Ok(suffix)
}
pub fn private_named_dir(parent: &Path, name: &str) -> io::Result<PrivateTempDir> {
super::checked_basename(name)?;
ScratchParent::open(parent)?.create(name)
}
pub struct PrivateTempDir {
path: Option<PathBuf>,
#[cfg(windows)]
guards: Box<ScratchGuards>,
}
#[cfg(windows)]
struct ScratchGuards {
child: Option<std::fs::File>,
_parent: std::sync::Arc<[std::fs::File]>,
}
impl PrivateTempDir {
pub fn path(&self) -> &Path {
self.path
.as_deref()
.expect("temporary directory is still owned")
}
pub fn close(mut self) -> io::Result<()> {
self.cleanup()
}
pub fn keep(mut self) -> io::Result<PathBuf> {
Ok(self
.path
.take()
.expect("temporary directory is still owned"))
}
fn cleanup(&mut self) -> io::Result<()> {
let Some(path) = self.path.take() else {
return Ok(());
};
#[cfg(unix)]
return super::remove_tree(&path);
#[cfg(windows)]
{
super::windows::empty_scratch(&path)?;
drop(self.guards.child.take());
std::fs::remove_dir(&path)
}
}
}
impl Drop for PrivateTempDir {
fn drop(&mut self) {
let _ = self.cleanup();
}
}