artifactize-foundation 0.27.0

Native file, path and executable primitives for Artifactize.
Documentation
use std::{
    io,
    path::{Path, PathBuf},
};

/// Create an owner-only directory and its missing parents. An existing directory
/// is made private only if it belongs to the current user; existing parents are untouched.
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(),
            )?;
            // Until the child exists, a pre-existing writable handle could turn an empty
            // parent into a reparse point. Verify the pathname after relative creation;
            // the now nonempty ancestors cannot acquire new name-surrogate reparse points.
            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(),
            }),
        })
    }
}

/// A new owner-only temporary directory with a path other users cannot replace.
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))?;
        // Preserve the original six-character names. Privacy comes from the pinned
        // parent and exclusive owner-only creation, not the secrecy of the basename.
        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);
    // Only reduce complete buckets so each name has the same probability.
    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)
}

/// A protected scratch directory whose basename is already reserved by its lease.
pub fn private_named_dir(parent: &Path, name: &str) -> io::Result<PrivateTempDir> {
    super::checked_basename(name)?;
    ScratchParent::open(parent)?.create(name)
}

/// Own the directory until dropped, or transfer cleanup responsibility with `keep`.
pub struct PrivateTempDir {
    path: Option<PathBuf>,
    #[cfg(windows)]
    guards: Box<ScratchGuards>,
}

// The lease is embedded in process/launcher enums; keep its native handles out of line.
#[cfg(windows)]
struct ScratchGuards {
    child: Option<std::fs::File>,
    // Held only so the parent cannot be renamed while the lease lives.
    _parent: std::sync::Arc<[std::fs::File]>,
}

impl PrivateTempDir {
    /// The directory's absolute path, stable against other users while this lease is held.
    pub fn path(&self) -> &Path {
        self.path
            .as_deref()
            .expect("temporary directory is still owned")
    }

    pub fn close(mut self) -> io::Result<()> {
        self.cleanup()
    }

    /// Relinquish cleanup: the owner-only directory stays for the caller to remove.
    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)]
        {
            // Empty only the directory we still hold, never a replacement directory.
            // After releasing its name, only an empty-directory removal is allowed.
            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();
    }
}