artifactize-foundation 0.27.0

Native file, path and executable primitives for Artifactize.
Documentation
use super::{File, OsStr, PinnedFile, check_file, io};
use std::os::windows::fs::MetadataExt;
use std::{
    mem,
    os::windows::{
        ffi::OsStrExt,
        io::{AsRawHandle, FromRawHandle},
    },
    ptr,
};
use windows_sys::{
    Wdk::{
        Foundation::OBJECT_ATTRIBUTES,
        Storage::FileSystem::{
            FILE_CREATE, FILE_DIRECTORY_FILE, FILE_DISPOSITION_DELETE,
            FILE_DISPOSITION_INFORMATION, FILE_DISPOSITION_INFORMATION_EX,
            FILE_DISPOSITION_POSIX_SEMANTICS, FILE_NON_DIRECTORY_FILE, FILE_OPEN, FILE_OPEN_IF,
            FILE_OPEN_REPARSE_POINT, FILE_RENAME_INFORMATION, FILE_RENAME_INFORMATION_0,
            FILE_RENAME_POSIX_SEMANTICS, FILE_RENAME_REPLACE_IF_EXISTS,
            FILE_SYNCHRONOUS_IO_NONALERT, FileDispositionInformation, FileDispositionInformationEx,
            FileRenameInformation, FileRenameInformationEx, NtCreateFile, NtSetInformationFile,
        },
    },
    Win32::{
        Foundation::{
            HANDLE, OBJ_CASE_INSENSITIVE, OBJ_DONT_REPARSE, RtlNtStatusToDosError,
            STATUS_INVALID_INFO_CLASS, STATUS_INVALID_PARAMETER, STATUS_NOT_SUPPORTED,
            UNICODE_STRING,
        },
        Storage::FileSystem::{
            BY_HANDLE_FILE_INFORMATION, DELETE, FILE_ATTRIBUTE_REPARSE_POINT, FILE_GENERIC_READ,
            FILE_GENERIC_WRITE, FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE,
            GetFileInformationByHandle,
        },
        System::IO::IO_STATUS_BLOCK,
    },
};

/// Atomically create an owner-only directory and deny delete sharing before its name
/// is exposed. Even a shared parent with FILE_DELETE_CHILD cannot redirect the lease.
pub(in crate::platform::private) fn create_scratch(
    parent: &File,
    name: &OsStr,
) -> io::Result<File> {
    open(
        parent,
        name,
        FILE_GENERIC_READ,
        FILE_CREATE,
        FILE_DIRECTORY_FILE,
        false,
        true,
    )
}

pub(super) fn child(parent: &File, name: &OsStr, create: bool) -> io::Result<File> {
    open(
        parent,
        name,
        FILE_GENERIC_READ,
        if create { FILE_OPEN_IF } else { FILE_OPEN },
        FILE_DIRECTORY_FILE,
        true,
        true,
    )
}

pub(super) fn file(parent: &File, name: &OsStr, mode: PinnedFile) -> io::Result<File> {
    let (access, disposition) = match mode {
        PinnedFile::Read => (FILE_GENERIC_READ, FILE_OPEN),
        PinnedFile::Write => (FILE_GENERIC_READ | FILE_GENERIC_WRITE, FILE_OPEN),
        PinnedFile::OpenOrCreate | PinnedFile::Lease => {
            (FILE_GENERIC_READ | FILE_GENERIC_WRITE, FILE_OPEN_IF)
        }
        PinnedFile::Create => (FILE_GENERIC_READ | FILE_GENERIC_WRITE | DELETE, FILE_CREATE),
    };
    open(
        parent,
        name,
        access,
        disposition,
        FILE_NON_DIRECTORY_FILE,
        !matches!(mode, PinnedFile::Lease),
        true,
    )
}

fn open(
    parent: &File,
    name: &OsStr,
    access: u32,
    disposition: u32,
    options: u32,
    share_delete: bool,
    private: bool,
) -> io::Result<File> {
    let mut name: Vec<u16> = name.encode_wide().collect();
    let length = u16::try_from(mem::size_of_val(name.as_slice()))
        .map_err(|_| io::ErrorKind::InvalidInput)?;
    let name = UNICODE_STRING {
        Length: length,
        MaximumLength: length,
        Buffer: name.as_mut_ptr(),
    };
    let descriptor = (private && disposition != FILE_OPEN)
        .then(|| super::super::windows::owner_only(options == FILE_DIRECTORY_FILE))
        .transpose()?;
    let mut attributes = OBJECT_ATTRIBUTES {
        Length: mem::size_of::<OBJECT_ATTRIBUTES>() as u32,
        RootDirectory: parent.as_raw_handle(),
        ObjectName: &name,
        Attributes: OBJ_CASE_INSENSITIVE | OBJ_DONT_REPARSE,
        SecurityDescriptor: descriptor
            .as_ref()
            .map_or(ptr::null_mut(), |d| d.as_ptr().cast()),
        ..Default::default()
    };
    let mut handle: HANDLE = ptr::null_mut();
    let call = |attributes: &OBJECT_ATTRIBUTES, handle: &mut HANDLE| {
        let mut status = IO_STATUS_BLOCK::default();
        // SAFETY: live directory handle, descriptor, name and writable local outputs.
        unsafe {
            NtCreateFile(
                handle,
                access,
                attributes,
                &mut status,
                ptr::null(),
                0,
                FILE_SHARE_READ
                    | FILE_SHARE_WRITE
                    | if share_delete { FILE_SHARE_DELETE } else { 0 },
                disposition,
                options | FILE_OPEN_REPARSE_POINT | FILE_SYNCHRONOUS_IO_NONALERT,
                ptr::null(),
                0,
            )
        }
    };
    let mut status = call(&attributes, &mut handle);
    if status == STATUS_INVALID_PARAMETER {
        // The final component still cannot be followed on systems lacking this flag.
        attributes.Attributes = OBJ_CASE_INSENSITIVE;
        status = call(&attributes, &mut handle);
    }
    succeeded(status)?;
    // SAFETY: NtCreateFile returned a new synchronous, owned handle.
    let file = unsafe { File::from_raw_handle(handle) };
    if file.metadata()?.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
        return Err(io::ErrorKind::PermissionDenied.into());
    }
    Ok(file)
}

pub(super) fn workspace_file(parent: &File, name: &OsStr) -> io::Result<File> {
    open(
        parent,
        name,
        FILE_GENERIC_READ | FILE_GENERIC_WRITE,
        FILE_OPEN_IF,
        FILE_NON_DIRECTORY_FILE,
        true,
        false,
    )
}

pub(super) fn single_link(file: &File) -> io::Result<bool> {
    let mut info = BY_HANDLE_FILE_INFORMATION::default();
    // SAFETY: this is a live file handle and a writable information structure.
    if unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut info) } == 0 {
        return Err(io::Error::last_os_error());
    }
    Ok(info.nNumberOfLinks == 1)
}

pub(super) fn replace(parent: &File, file: &File, _: &OsStr, target: &OsStr) -> io::Result<()> {
    let name: Vec<u16> = target.encode_wide().collect();
    let name_bytes = mem::size_of_val(name.as_slice());
    let size = (mem::offset_of!(FILE_RENAME_INFORMATION, FileName) + name_bytes)
        .max(mem::size_of::<FILE_RENAME_INFORMATION>());
    let mut buffer = vec![0usize; size.div_ceil(mem::size_of::<usize>())];
    let rename = buffer.as_mut_ptr().cast::<FILE_RENAME_INFORMATION>();
    let info = FILE_RENAME_INFORMATION {
        Anonymous: FILE_RENAME_INFORMATION_0 {
            Flags: FILE_RENAME_REPLACE_IF_EXISTS | FILE_RENAME_POSIX_SEMANTICS,
        },
        RootDirectory: parent.as_raw_handle(),
        FileNameLength: name_bytes as u32,
        ..Default::default()
    };
    // SAFETY: `buffer` is aligned and large enough for the structure and trailing UTF-16 name.
    unsafe {
        rename.write(info);
        ptr::copy_nonoverlapping(
            name.as_ptr(),
            ptr::addr_of_mut!((*rename).FileName).cast(),
            name.len(),
        );
    }
    let mut status = set(file, rename.cast(), size as u32, FileRenameInformationEx);
    if unsupported(status) {
        // SAFETY: same allocated and initialized structure, with the original boolean form.
        unsafe {
            (*rename).Anonymous = FILE_RENAME_INFORMATION_0 {
                ReplaceIfExists: true,
            };
        }
        status = set(file, rename.cast(), size as u32, FileRenameInformation);
    }
    succeeded(status)
}

pub(super) fn remove(parent: &File, name: &OsStr) -> io::Result<()> {
    let file = open(
        parent,
        name,
        FILE_GENERIC_READ | DELETE,
        FILE_OPEN,
        FILE_NON_DIRECTORY_FILE,
        true,
        true,
    )?;
    check_file(&file)?;
    let extended = FILE_DISPOSITION_INFORMATION_EX {
        Flags: FILE_DISPOSITION_DELETE | FILE_DISPOSITION_POSIX_SEMANTICS,
    };
    let mut status = set(
        &file,
        ptr::from_ref(&extended).cast(),
        mem::size_of_val(&extended) as u32,
        FileDispositionInformationEx,
    );
    if unsupported(status) {
        let original = FILE_DISPOSITION_INFORMATION { DeleteFile: true };
        status = set(
            &file,
            ptr::from_ref(&original).cast(),
            mem::size_of_val(&original) as u32,
            FileDispositionInformation,
        );
    }
    succeeded(status)
}

fn set(file: &File, buffer: *const core::ffi::c_void, size: u32, class: i32) -> i32 {
    let mut status = IO_STATUS_BLOCK::default();
    // SAFETY: our callers supply the live structure and byte count for the selected info class.
    unsafe { NtSetInformationFile(file.as_raw_handle(), &mut status, buffer, size, class) }
}

fn unsupported(status: i32) -> bool {
    matches!(
        status,
        STATUS_INVALID_PARAMETER | STATUS_INVALID_INFO_CLASS | STATUS_NOT_SUPPORTED
    )
}

fn succeeded(status: i32) -> io::Result<()> {
    if status >= 0 {
        return Ok(());
    }
    // SAFETY: translates an NT status by value.
    Err(io::Error::from_raw_os_error(
        unsafe { RtlNtStatusToDosError(status) } as i32,
    ))
}

pub(super) fn sync(_: &File) -> io::Result<()> {
    // Windows does not support FlushFileBuffers on a normal directory handle. The file was
    // already flushed before the atomic metadata update, as for other private replacements.
    Ok(())
}