artifactize-foundation 0.27.2

Native file, path and executable primitives for Artifactize.
Documentation
//! Darwin ACLs act independently of the POSIX mode, including at creation.

use std::{
    ffi::{CString, c_void},
    fs::{File, OpenOptions},
    io,
    os::{
        fd::{AsRawFd, FromRawFd},
        unix::{ffi::OsStrExt, fs::OpenOptionsExt},
    },
    path::Path,
    ptr,
};

// Darwin's sys/acl.h: the extended ACL and selectors for iterating over its entries.
const ACL_TYPE_EXTENDED: libc::c_uint = 0x100;
const ACL_FIRST_ENTRY: libc::c_int = 0;
const ACL_NEXT_ENTRY: libc::c_int = -1;
const ACL_EXTENDED_ALLOW: libc::c_uint = 1;
const ACL_EXTENDED_DENY: libc::c_uint = 2;

// Darwin's sys/acl.h uses this flag to block inheritance even for an empty ACL.
const ACL_FLAG_NO_INHERIT: libc::c_uint = 1 << 17;
// Darwin's sys/fcntl.h: filesec_property_t values for a mode_t and an acl_t.
const FILESEC_MODE: libc::c_uint = 4;
const FILESEC_ACL: libc::c_uint = 5;

// SAFETY: these declarations match Darwin's sys/acl.h, sys/fcntl.h and sys/stat.h;
// their acl_t, flagset, entry and filesec_t types are opaque C pointers.
unsafe extern "C" {
    fn acl_init(count: libc::c_int) -> *mut c_void;
    fn acl_get_flagset_np(acl: *mut c_void, flags: *mut *mut c_void) -> libc::c_int;
    fn acl_add_flag_np(flags: *mut c_void, flag: libc::c_uint) -> libc::c_int;
    fn acl_set_fd_np(fd: libc::c_int, acl: *mut c_void, kind: libc::c_uint) -> libc::c_int;
    fn filesec_init() -> *mut c_void;
    fn filesec_free(security: *mut c_void);
    fn filesec_set_property(
        security: *mut c_void,
        property: libc::c_uint,
        value: *const c_void,
    ) -> libc::c_int;
    fn mkdirx_np(path: *const libc::c_char, security: *mut c_void) -> libc::c_int;
    fn openx_np(
        path: *const libc::c_char,
        flags: libc::c_int,
        security: *mut c_void,
    ) -> libc::c_int;
    fn acl_get_fd_np(fd: libc::c_int, kind: libc::c_uint) -> *mut c_void;
    fn acl_get_entry(acl: *mut c_void, index: libc::c_int, entry: *mut *mut c_void) -> libc::c_int;
    fn acl_get_tag_type(entry: *mut c_void, tag: *mut libc::c_uint) -> libc::c_int;
    fn acl_get_permset(entry: *mut c_void, perms: *mut *mut c_void) -> libc::c_int;
    fn acl_get_perm_np(perms: *mut c_void, perm: libc::c_uint) -> libc::c_int;
    fn acl_free(acl: *mut c_void) -> libc::c_int;
}

struct Acl(*mut c_void);

impl Drop for Acl {
    fn drop(&mut self) {
        // SAFETY: the successful acl_init or acl_get_fd_np allocation is owned by this value.
        unsafe { acl_free(self.0) };
    }
}

impl Acl {
    fn without_inheritance() -> io::Result<Self> {
        // SAFETY: acl_init(0) allocates a valid, empty, owned ACL.
        let acl = unsafe { acl_init(0) };
        if acl.is_null() {
            return Err(io::Error::last_os_error());
        }
        let acl = Self(acl);
        let mut flags = ptr::null_mut();
        // SAFETY: the ACL is live and flags is an initialized out pointer; successful
        // lookup returns the mutable flag set inside the ACL.
        status(unsafe { acl_get_flagset_np(acl.0, &mut flags) })?;
        // SAFETY: flags belongs to the live ACL and the flag is valid for an ACL object.
        status(unsafe { acl_add_flag_np(flags, ACL_FLAG_NO_INHERIT) })?;
        Ok(acl)
    }

    fn for_file(file: &File) -> io::Result<Option<Self>> {
        // SAFETY: this descriptor is open and the request is for Darwin's extended ACL.
        let acl = unsafe { acl_get_fd_np(file.as_raw_fd(), ACL_TYPE_EXTENDED) };
        if acl.is_null() {
            let error = io::Error::last_os_error();
            return match error.raw_os_error() {
                Some(libc::ENOENT | libc::ENOTSUP) => Ok(None),
                _ => Err(error),
            };
        }
        Ok(Some(Self(acl)))
    }
}

struct FileSecurity(*mut c_void);

impl Drop for FileSecurity {
    fn drop(&mut self) {
        // SAFETY: this value owns the successful filesec_init allocation.
        unsafe { filesec_free(self.0) };
    }
}

impl FileSecurity {
    fn owner_only(mode: libc::mode_t) -> io::Result<Self> {
        let acl = Acl::without_inheritance()?;
        // SAFETY: filesec_init has no preconditions and returns an owned allocation or NULL.
        let security = unsafe { filesec_init() };
        if security.is_null() {
            return Err(io::Error::last_os_error());
        }
        let security = Self(security);
        // SAFETY: filesec_set_property copies the typed mode and ACL from live pointers.
        unsafe {
            status(filesec_set_property(
                security.0,
                FILESEC_MODE,
                ptr::from_ref(&mode).cast(),
            ))?;
            status(filesec_set_property(
                security.0,
                FILESEC_ACL,
                ptr::from_ref(&acl.0).cast(),
            ))?;
        }
        Ok(security)
    }
}

fn status(result: libc::c_int) -> io::Result<()> {
    if result == 0 {
        Ok(())
    } else {
        Err(io::Error::last_os_error())
    }
}

fn native_path(path: &Path) -> io::Result<CString> {
    CString::new(path.as_os_str().as_bytes()).map_err(|_| io::ErrorKind::InvalidInput.into())
}

pub(super) fn create_dir(path: &Path, mode: libc::mode_t) -> io::Result<()> {
    let path = native_path(path)?;
    let security = FileSecurity::owner_only(mode)?;
    // SAFETY: path is NUL-terminated; security is live and supplies mode and ACL.
    status(unsafe { mkdirx_np(path.as_ptr(), security.0) })
}

pub(super) fn create_file(path: &Path, mode: libc::mode_t) -> io::Result<File> {
    let path = native_path(path)?;
    let security = FileSecurity::owner_only(mode)?;
    let flags = libc::O_CREAT | libc::O_EXCL | libc::O_CLOEXEC | libc::O_RDWR;
    // SAFETY: path is NUL-terminated; O_CREAT uses the supplied live security attributes.
    let fd = unsafe { openx_np(path.as_ptr(), flags, security.0) };
    if fd < 0 {
        return Err(io::Error::last_os_error());
    }
    // SAFETY: successful exclusive creation returned a new owned descriptor.
    Ok(unsafe { File::from_raw_fd(fd) })
}

pub(in crate::platform) fn open_directory_for_acl(path: &Path) -> io::Result<File> {
    // O_EVTONLY does not require read permission, even when umask removed it on creation.
    OpenOptions::new()
        .read(true)
        .custom_flags(libc::O_EVTONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW)
        .open(super::super::files::terminal_component(path).0)
}

pub(super) fn clear_acl(file: &File) -> io::Result<()> {
    if Acl::for_file(file)?.is_some() {
        let acl = Acl::without_inheritance()?;
        // SAFETY: both the descriptor and the replacement Darwin ACL are live.
        status(unsafe { acl_set_fd_np(file.as_raw_fd(), acl.0, ACL_TYPE_EXTENDED) })?;
    }
    require_no_grants(file)
}

pub(super) fn require_no_grants(file: &File) -> io::Result<()> {
    if has_no_grants(file)? {
        Ok(())
    } else {
        Err(io::ErrorKind::PermissionDenied.into())
    }
}

pub(in crate::platform) fn has_no_grants(file: &File) -> io::Result<bool> {
    acl_has_no_grants(file, None)
}

fn acl_has_no_grants(file: &File, rights: Option<&[libc::c_uint]>) -> io::Result<bool> {
    let Some(acl) = Acl::for_file(file)? else {
        return Ok(true);
    };
    let mut index = ACL_FIRST_ENTRY;
    loop {
        let mut entry = ptr::null_mut();
        // SAFETY: the ACL lives through iteration and entry is an initialized out pointer.
        if unsafe { acl_get_entry(acl.0, index, &mut entry) } != 0 {
            let error = io::Error::last_os_error();
            // Darwin returns EINVAL at the end of a valid ACL's entry list.
            return if error.raw_os_error() == Some(libc::EINVAL) {
                Ok(true)
            } else {
                Err(error)
            };
        }
        let mut tag = 0;
        // SAFETY: the entry came from the live ACL and tag is a writable out parameter.
        if unsafe { acl_get_tag_type(entry, &mut tag) } != 0 {
            return Err(io::Error::last_os_error());
        }
        // A deny ACE grants nothing. Unknown types fail closed.
        if tag != ACL_EXTENDED_DENY {
            let Some(rights) = rights.filter(|_| tag == ACL_EXTENDED_ALLOW) else {
                return Ok(false);
            };
            let mut perms = ptr::null_mut();
            // SAFETY: the entry is live and perms is a writable out pointer.
            status(unsafe { acl_get_permset(entry, &mut perms) })?;
            for &right in rights {
                // SAFETY: perms borrows the live entry; each selector is an acl_perm_t.
                match unsafe { acl_get_perm_np(perms, right) } {
                    0 => {}
                    1 => return Ok(false),
                    _ => return Err(io::Error::last_os_error()),
                }
            }
        }
        index = ACL_NEXT_ENTRY;
    }
}

#[cfg(test)]
mod tests;