artifactize-foundation 0.27.2

Native file, path and executable primitives for Artifactize.
Documentation
use std::{
    ffi::{OsStr, OsString},
    fs::{self, File},
    io,
    os::unix::ffi::{OsStrExt, OsStringExt},
    path::Path,
};

use icu_casemap::CaseMapper;
use icu_normalizer::DecomposingNormalizer;
use icu_properties::{CodePointSetData, props::DefaultIgnorableCodePoint};

use rustix::{
    fs::{AtFlags, Mode, OFlags, StatxFlags, fstatfs, mkdirat, statat, statx, unlinkat},
    io::Errno,
};

use super::{super::files, NamePolicy};

// Linux statfs types for filesystems whose lookup is not ext4-style Unicode casefold.
const FAT_MAGIC: u32 = libc::MSDOS_SUPER_MAGIC as u32;
const EXFAT_MAGIC: u32 = 0x2011_BAB0;
const NTFS_MAGIC: u32 = 0x7366_746E;
const CIFS_MAGIC: u32 = 0xFF53_4D42;
const SMB2_MAGIC: u32 = 0xFE53_4D42;

pub(super) fn name_policy(path: &Path) -> io::Result<NamePolicy> {
    let directory = match files::open_directory(path) {
        Ok(directory) => directory,
        // A searchable directory need not be readable. Its descriptor can still
        // report its filesystem type and mount ID.
        Err(error) if error.kind() == io::ErrorKind::PermissionDenied => rustix::fs::open(
            path,
            OFlags::PATH | OFlags::DIRECTORY | OFlags::CLOEXEC,
            Mode::empty(),
        )?
        .into(),
        Err(error) => return Err(error),
    };
    let volume = fstatfs(&directory)?;
    match files::native_case_sensitive(&directory, volume.f_type) {
        Some(true) => return Ok(NamePolicy::Literal),
        Some(false) => return Ok(NamePolicy::Folded),
        None => {}
    }
    let kind = volume.f_type as u32;
    // Unlike FAT and NTFS3, exFAT always uses the volume upcase table.
    if kind == EXFAT_MAGIC {
        return Ok(NamePolicy::Upcase);
    }
    let observed = match probe_case_sensitive(&directory) {
        Err(error)
            if matches!(
                error.kind(),
                io::ErrorKind::PermissionDenied | io::ErrorKind::Unsupported
            ) =>
        {
            None
        }
        result => result?,
    };
    // With no usable entry, prefer native mount options before testing a disposable
    // name. Read-only directories on an opaque mount may still provide no evidence.
    let sensitive = match observed.or_else(|| mount_case_sensitive(&directory, kind)) {
        Some(sensitive) => Some(sensitive),
        None => probe_new_name(&directory)?,
    };
    Ok(match sensitive {
        Some(false)
            if kind == libc::EXT4_SUPER_MAGIC as u32 || kind == libc::F2FS_SUPER_MAGIC as u32 =>
        {
            NamePolicy::Folded
        }
        Some(false) => NamePolicy::Upcase,
        _ => NamePolicy::Literal,
    })
}

fn probe_case_sensitive(directory: &File) -> io::Result<Option<bool>> {
    let mut entries = files::read_dir(directory)?;
    while let Some(entry) = entries.next() {
        let name = entry?.file_name();
        let Some(alternate) = alternate_case(&name) else {
            continue;
        };
        let entry = match statat(directory, &name, AtFlags::SYMLINK_NOFOLLOW) {
            Ok(entry) => entry,
            Err(Errno::NOENT) => continue,
            Err(error) => return Err(error.into()),
        };
        return match statat(directory, &alternate, AtFlags::SYMLINK_NOFOLLOW) {
            Err(Errno::NOENT) => Ok(Some(true)),
            Err(error) => Err(error.into()),
            Ok(other) if (entry.st_dev, entry.st_ino) != (other.st_dev, other.st_ino) => {
                Ok(Some(true))
            }
            Ok(_) => {
                // A lookup can reach the same inode via two hard links. A separately
                // listed spelling proves these are two names, not one case alias.
                for entry in entries {
                    if entry?.file_name() == alternate {
                        return Ok(Some(true));
                    }
                }
                Ok(Some(false))
            }
        };
    }
    Ok(None)
}

fn probe_new_name(directory: &File) -> io::Result<Option<bool>> {
    let nonce = getrandom::u64().map_err(io::Error::other)?;
    let name = format!(".case-probe-{nonce:016x}");
    let alternate = format!(".Case-probe-{nonce:016x}");
    match mkdirat(directory, name.as_str(), Mode::RWXU) {
        Ok(()) => {}
        Err(
            Errno::ACCESS
            | Errno::PERM
            | Errno::ROFS
            | Errno::OPNOTSUPP
            | Errno::EXIST
            | Errno::NOSPC
            | Errno::DQUOT
            | Errno::NAMETOOLONG,
        ) => return Ok(None),
        Err(error) => return Err(error.into()),
    }
    let observed =
        statat(directory, name.as_str(), AtFlags::SYMLINK_NOFOLLOW).and_then(|entry| match statat(
            directory,
            alternate.as_str(),
            AtFlags::SYMLINK_NOFOLLOW,
        ) {
            Ok(other) => Ok((entry.st_dev, entry.st_ino) != (other.st_dev, other.st_ino)),
            Err(Errno::NOENT) => Ok(true),
            Err(error) => Err(error),
        });
    // Relative to the held directory, and only an empty directory can be removed.
    // Attempt cleanup even when the lookup failed; never recurse into anything.
    unlinkat(directory, name.as_str(), AtFlags::REMOVEDIR)?;
    Ok(Some(observed?))
}

fn alternate_case(name: &OsStr) -> Option<OsString> {
    let mut bytes = name.as_bytes().to_vec();
    let letter = bytes.iter_mut().find(|byte| byte.is_ascii_alphabetic())?;
    *letter = if letter.is_ascii_lowercase() {
        letter.to_ascii_uppercase()
    } else {
        letter.to_ascii_lowercase()
    };
    Some(OsString::from_vec(bytes))
}

fn mount_case_sensitive(directory: &File, kind: u32) -> Option<bool> {
    if !matches!(kind, FAT_MAGIC | NTFS_MAGIC | CIFS_MAGIC | SMB2_MAGIC) {
        return None;
    }
    let stat = statx(directory, c"", AtFlags::EMPTY_PATH, StatxFlags::MNT_ID).ok()?;
    if stat.stx_mask & StatxFlags::MNT_ID.bits() == 0 {
        return None;
    }
    let mounts = fs::read("/proc/self/mountinfo").ok()?;
    // Mount paths may contain opaque bytes, but only the ASCII ID and options matter.
    mount_policy(&String::from_utf8_lossy(&mounts), stat.stx_mnt_id, kind)
}

fn mount_policy(mounts: &str, id: u64, kind: u32) -> Option<bool> {
    let line = mounts.lines().find(|line| {
        line.split_ascii_whitespace()
            .next()
            .and_then(|value| value.parse().ok())
            == Some(id)
    })?;
    // After the optional fields and separator: filesystem, source, superblock options.
    // Match the mount ID rather than parsing or comparing escaped path spellings.
    let (filesystem, options) = line.split_once(" - ").and_then(|(_, fields)| {
        let mut fields = fields.split_ascii_whitespace();
        Some((fields.next()?, fields.nth(1)?))
    })?;
    let option = |name| options.split(',').any(|value| value == name);
    match (kind, filesystem) {
        (FAT_MAGIC, "vfat") => Some(option("check=s")),
        (NTFS_MAGIC, "ntfs3") => Some(!option("nocase")),
        // SMB servers can offer either policy. `nocase` positively identifies a
        // client-side insensitive mount; lack of that option is not evidence.
        (CIFS_MAGIC | SMB2_MAGIC, "smb3" | "cifs") if option("nocase") => Some(false),
        _ => None,
    }
}

pub(super) fn upcase(name: &OsStr) -> OsString {
    let Some(name) = name.to_str() else {
        return name.to_owned();
    };
    let casing = CaseMapper::new();
    // Volume upcase tables map individual code points, not whole strings. Do not
    // expand letters, decompose accents, or discard default-ignorables as ext4 does.
    name.chars()
        .map(|ch| casing.simple_uppercase(ch))
        .collect::<String>()
        .into()
}

pub(super) fn fold(name: &OsStr) -> OsString {
    let Some(name) = name.to_str() else {
        // Linux casefold lookup compares invalid UTF-8 as opaque bytes.
        return name.to_owned();
    };
    // ext4 and f2fs casefold lookup uses canonical decomposition, default Unicode
    // case folding and removal of default-ignorable code points.
    let nfd = DecomposingNormalizer::new_nfd();
    let decomposed = nfd.normalize(name);
    let folded = CaseMapper::new().fold_string(&decomposed);
    let ignorable = CodePointSetData::new::<DefaultIgnorableCodePoint>();
    let key = nfd
        .normalize_iter(folded.chars().filter(|&ch| !ignorable.contains(ch)))
        .collect::<String>();
    key.into()
}

#[cfg(test)]
mod tests;