artifactize-foundation 0.27.1

Native file, path and executable primitives for Artifactize.
Documentation
//! Private directory capabilities. All child names are single components and are resolved
//! by the OS relative to the held directory object, even if its original name is replaced.
use std::{
    ffi::{OsStr, OsString},
    fs::File,
    io::{self, Write},
    path::Path,
    sync::{
        Arc,
        atomic::{AtomicU64, Ordering},
    },
};

use super::{is_owner_only, is_private_file};
use crate::platform::files;

#[cfg(unix)]
mod unix;
#[cfg(unix)]
use unix as native;
#[cfg(windows)]
mod windows;
#[cfg(windows)]
use windows as native;
#[cfg(windows)]
pub(super) use windows::create_scratch;

#[derive(Clone, Debug)]
pub struct PinnedDir(Arc<File>);

/// Access to a named private regular file. Creation never overwrites an existing entry.
#[derive(Clone, Copy)]
pub enum PinnedFile {
    Read,
    Write,
    OpenOrCreate,
    Create,
    /// Open or create a file whose name cannot be replaced while held, where the OS supports it.
    Lease,
}

impl PinnedDir {
    pub fn open(path: &Path) -> io::Result<Self> {
        let file = files::open_no_follow(File::options().read(true), path)?;
        Self::from_handle(file)
    }

    pub fn from_handle(file: File) -> io::Result<Self> {
        if !file.metadata()?.is_dir() || !is_owner_only(&file)? {
            return Err(io::ErrorKind::PermissionDenied.into());
        }
        Ok(Self(Arc::new(file)))
    }

    pub fn handle(&self) -> &File {
        &self.0
    }

    pub fn child(&self, name: &OsStr) -> io::Result<Self> {
        validate(name)?;
        Self::from_handle(native::child(&self.0, name, false)?)
    }

    pub fn create_child(&self, name: &OsStr) -> io::Result<Self> {
        validate(name)?;
        Self::from_handle(native::child(&self.0, name, true)?)
    }

    pub fn file(&self, name: &OsStr, mode: PinnedFile) -> io::Result<File> {
        validate(name)?;
        let file = native::file(&self.0, name, mode)?;
        check_file(&file)?;
        Ok(file)
    }

    pub fn entries(&self) -> io::Result<Vec<OsString>> {
        files::read_dir(&self.0)?
            .map(|entry| entry.map(|entry| entry.file_name().to_owned()))
            .collect()
    }

    /// Replace a file atomically and persist the renamed directory entry. Neither the staged
    /// file nor the final rename ever uses the original parent pathname.
    pub fn replace(
        &self,
        name: &OsStr,
        write: impl FnOnce(&mut File) -> io::Result<()>,
    ) -> io::Result<()> {
        validate(name)?;
        static NEXT: AtomicU64 = AtomicU64::new(0);
        let (temp, mut file) = loop {
            let temp = format!(
                ".write-{}-{}",
                std::process::id(),
                NEXT.fetch_add(1, Ordering::Relaxed)
            );
            let temp = OsString::from(temp);
            match native::file(&self.0, &temp, PinnedFile::Create) {
                Ok(file) => break (temp, file),
                Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
                Err(error) => return Err(error),
            }
        };
        let result = (|| {
            check_file(&file)?;
            write(&mut file)?;
            file.flush()?;
            file.sync_all()?;
            native::replace(&self.0, &file, &temp, name)?;
            self.sync()
        })();
        if result.is_err() {
            drop(file);
            let _ = self.remove(&temp);
        }
        result
    }

    pub fn remove(&self, name: &OsStr) -> io::Result<()> {
        validate(name)?;
        match native::remove(&self.0, name) {
            Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
            result => result,
        }
    }

    pub fn sync(&self) -> io::Result<()> {
        native::sync(&self.0)
    }
}

/// Open a writable regular entry under an already checked, not necessarily private,
/// directory. This never follows a link or truncates the entry before returning its handle.
pub fn open_workspace_file(directory: &File, name: &OsStr) -> io::Result<File> {
    validate(name)?;
    let file = native::workspace_file(directory, name)?;
    if !file.metadata()?.is_file() || !native::single_link(&file)? {
        return Err(io::ErrorKind::PermissionDenied.into());
    }
    Ok(file)
}

fn validate(name: &OsStr) -> io::Result<()> {
    files::EntryName::new(name)
        .map(|_| ())
        .ok_or(io::ErrorKind::InvalidInput.into())
}

fn check_file(file: &File) -> io::Result<()> {
    if is_private_file(file)? {
        Ok(())
    } else {
        Err(io::ErrorKind::PermissionDenied.into())
    }
}

#[cfg(test)]
mod tests;