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};
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,
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;
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?,
};
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(_) => {
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),
});
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_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)
})?;
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")),
(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();
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 {
return name.to_owned();
};
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;