use std::path::{Path, PathBuf};
const RESERVED_ROOT: &str = "__hookfs__";
#[cfg(windows)]
const RESERVED_DRIVE: &str = "C:";
#[cfg(windows)]
pub(crate) const SEP: char = '\\';
#[cfg(unix)]
pub(crate) const SEP: char = '/';
pub(crate) struct Namespace {
root: PathBuf,
predicate: Box<dyn Fn(&Path) -> bool + Send + Sync>,
}
impl std::fmt::Debug for Namespace {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Namespace")
.field("root", &self.root)
.finish_non_exhaustive()
}
}
#[cfg(windows)]
pub(crate) fn reserved_root() -> PathBuf {
PathBuf::from(format!(
"{RESERVED_DRIVE}{SEP}{RESERVED_ROOT}{SEP}{}",
random_mount_id()
))
}
#[cfg(unix)]
pub(crate) fn reserved_root() -> PathBuf {
PathBuf::from(format!("{SEP}{RESERVED_ROOT}{SEP}{}", random_mount_id()))
}
impl Namespace {
pub(crate) fn from_root(root: PathBuf) -> Self {
let key_for_predicate = normalize_key_str(&root.to_string_lossy());
let predicate =
Box::new(move |path: &Path| key_has_prefix(&normalize_key(path), &key_for_predicate));
Self { root, predicate }
}
pub(crate) fn reserved() -> Self {
Self::from_root(reserved_root())
}
pub(crate) fn for_prefix(prefix: impl Into<PathBuf>) -> Self {
Self::from_root(prefix.into())
}
pub(crate) fn with_predicate(predicate: Box<dyn Fn(&Path) -> bool + Send + Sync>) -> Self {
let mut ns = Self::reserved();
ns.predicate = predicate;
ns
}
#[cfg(hookfs_backend)]
pub(crate) fn is_virtual(&self, path: &Path) -> bool {
(self.predicate)(path)
}
}
#[cfg(windows)]
pub(crate) fn is_lexically_safe(decoded: &str) -> bool {
if decoded.contains('\0') {
return false;
}
for raw in decoded.split(['\\', '/']) {
if is_dot_component(raw) {
return false;
}
let comp = raw.trim_end_matches([' ', '.']);
if comp.contains(':')
&& !(comp.len() == 2 && comp.as_bytes().first().is_some_and(u8::is_ascii_alphabetic))
{
return false;
}
}
true
}
#[cfg(unix)]
pub(crate) fn is_lexically_safe(decoded: &str) -> bool {
if decoded.contains('\0') {
return false;
}
!decoded.split('/').any(|comp| comp == "." || comp == "..")
}
#[cfg(windows)]
fn is_dot_component(comp: &str) -> bool {
!comp.is_empty()
&& comp.bytes().all(|b| b == b'.' || b == b' ')
&& comp.bytes().any(|b| b == b'.')
}
#[cfg(windows)]
pub(crate) fn normalize_key_str(input: &str) -> String {
let mut s = input;
if let Some(rest) = s.strip_prefix("\\\\?\\UNC\\") {
return normalize_key_str(&format!("\\\\{rest}"));
}
if let Some(rest) = s.strip_prefix("\\\\?\\") {
s = rest;
}
let mut out = String::with_capacity(s.len());
let mut prev_sep = false;
for ch in s.chars() {
let c = if ch == '/' { '\\' } else { ch };
if c == '\\' {
if prev_sep {
continue; }
prev_sep = true;
out.push('\\');
} else {
prev_sep = false;
out.extend(c.to_lowercase());
}
}
if out.len() > 3 && out.ends_with('\\') {
out.pop();
}
out
}
#[cfg(unix)]
pub(crate) fn normalize_key_str(input: &str) -> String {
let mut out = String::with_capacity(input.len());
let mut prev_sep = false;
for c in input.chars() {
if c == '/' {
if prev_sep {
continue; }
prev_sep = true;
out.push('/');
} else {
prev_sep = false;
out.push(c);
}
}
if out.len() > 1 && out.ends_with('/') {
out.pop();
}
out
}
pub(crate) fn normalize_key(path: &Path) -> String {
normalize_key_str(&path.to_string_lossy())
}
fn key_has_prefix(key: &str, prefix: &str) -> bool {
if let Some(rest) = key.strip_prefix(prefix) {
rest.is_empty() || rest.starts_with(SEP)
} else {
false
}
}
#[cfg(windows)]
pub(crate) unsafe fn decode_wide(ptr: *const u16) -> Option<Vec<u16>> {
const MAX: usize = 0x8000; if ptr.is_null() {
return None;
}
let mut out = Vec::new();
for i in 0..MAX {
let unit = unsafe { *ptr.add(i) };
if unit == 0 {
return Some(out);
}
out.push(unit);
}
None
}
#[cfg(windows)]
pub(crate) unsafe fn decode_ansi(ptr: *const u8) -> Option<String> {
const MAX: usize = 0x8000;
if ptr.is_null() {
return None;
}
let mut out = Vec::new();
for i in 0..MAX {
let byte = unsafe { *ptr.add(i) };
if byte == 0 {
return Some(String::from_utf8_lossy(&out).into_owned());
}
out.push(byte);
}
None
}
#[cfg(all(unix, hookfs_backend))]
pub(crate) unsafe fn decode_cstr(ptr: *const core::ffi::c_char) -> Option<String> {
const MAX: usize = 0x8000;
if ptr.is_null() {
return None;
}
let mut out = Vec::new();
for i in 0..MAX {
let byte = u8::from_ne_bytes(unsafe { *ptr.add(i) }.to_ne_bytes());
if byte == 0 {
return Some(String::from_utf8_lossy(&out).into_owned());
}
out.push(byte);
}
None
}
#[cfg(windows)]
pub(crate) fn wildcard_match(pattern: &str, name: &str) -> bool {
let pat: Vec<char> = pattern.chars().flat_map(char::to_lowercase).collect();
let txt: Vec<char> = name.chars().flat_map(char::to_lowercase).collect();
matches_from(&pat, &txt)
}
#[cfg(windows)]
fn matches_from(pat: &[char], txt: &[char]) -> bool {
let (mut pi, mut ti) = (0usize, 0usize);
let (mut star_pat, mut star_txt): (Option<usize>, usize) = (None, 0);
while ti < txt.len() {
match pat.get(pi) {
Some('*') => {
star_pat = Some(pi);
star_txt = ti;
pi += 1;
}
Some('?') => {
pi += 1;
ti += 1;
}
Some(&c) if txt.get(ti) == Some(&c) => {
pi += 1;
ti += 1;
}
_ => {
if let Some(sp) = star_pat {
pi = sp + 1;
star_txt += 1;
ti = star_txt;
} else {
return false;
}
}
}
}
while pat.get(pi) == Some(&'*') {
pi += 1;
}
pi == pat.len()
}
fn random_mount_id() -> String {
use std::hash::{BuildHasher, Hasher};
let state = std::collections::hash_map::RandomState::new();
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| u64::try_from(d.as_nanos()).unwrap_or(u64::MAX));
let mut h1 = state.build_hasher();
h1.write_u64(u64::from(std::process::id()));
h1.write_u64(nanos);
let a = h1.finish();
let mut h2 = state.build_hasher();
h2.write_u64(a);
h2.write_usize(&raw const state as usize);
let b = h2.finish();
format!("{a:016x}{b:016x}")
}
#[cfg(all(test, windows))]
#[allow(clippy::unwrap_used, clippy::indexing_slicing)]
mod tests {
use super::*;
#[test]
fn normalizes_separators_case_and_long_prefix() {
assert_eq!(normalize_key_str("C:/Foo/Bar/"), "c:\\foo\\bar");
assert_eq!(normalize_key_str("\\\\?\\C:\\Foo\\BAR"), "c:\\foo\\bar");
assert_eq!(normalize_key_str("C:\\a\\\\b"), "c:\\a\\b");
assert_eq!(normalize_key_str("c:\\"), "c:\\");
}
#[test]
fn prefix_matching_respects_component_boundary() {
let prefix = "c:\\__hookfs__\\abc";
assert!(key_has_prefix("c:\\__hookfs__\\abc", prefix));
assert!(key_has_prefix("c:\\__hookfs__\\abc\\clip.braw", prefix));
assert!(!key_has_prefix("c:\\__hookfs__\\abcdef\\clip.braw", prefix));
assert!(!key_has_prefix("c:\\other", prefix));
}
#[test]
fn rejects_traversal_and_streams() {
assert!(is_lexically_safe("C:\\__hookfs__\\id\\clip.braw"));
assert!(!is_lexically_safe("C:\\__hookfs__\\id\\..\\..\\secret"));
assert!(!is_lexically_safe("C:\\__hookfs__\\id\\clip.braw:stream"));
assert!(!is_lexically_safe("C:\\__hookfs__\\id\\clip\0.braw"));
}
#[test]
fn rejects_trailing_dot_and_space_traversal_variants() {
assert!(!is_lexically_safe("C:\\__hookfs__\\id\\.. \\secret")); assert!(!is_lexically_safe("C:\\__hookfs__\\id\\...\\secret")); assert!(!is_lexically_safe("C:\\__hookfs__\\id\\. \\clip")); assert!(!is_lexically_safe("C:\\__hookfs__\\id\\.\\clip")); assert!(!is_lexically_safe("C:\\__hookfs__\\id\\.. \\x")); assert!(!is_lexically_safe("C:/__hookfs__/id/.. /secret"));
assert!(!is_lexically_safe("C:\\__hookfs__/id\\..\\x"));
assert!(is_lexically_safe("C:\\__hookfs__\\id\\clip.braw"));
assert!(is_lexically_safe("C:\\__hookfs__\\id\\..foo")); assert!(is_lexically_safe("C:\\__hookfs__\\id\\a...b"));
assert!(is_lexically_safe("C:\\__hookfs__\\id\\file.name.ext"));
}
#[test]
fn is_dot_component_classification() {
for bad in [".", "..", "...", ".. ", " ..", ". .", ".. ", " . "] {
assert!(is_dot_component(bad), "{bad:?} should be a dot component");
}
for good in ["", "clip.braw", "..foo", "a..", "foo.", " ", "..a"] {
assert!(
!is_dot_component(good),
"{good:?} should not be a dot component"
);
}
}
#[test]
fn wildcards() {
assert!(wildcard_match("*", "anything.braw"));
assert!(wildcard_match("*.braw", "SAMPLE.BRAW"));
assert!(wildcard_match("sample.braw", "sample.braw"));
assert!(!wildcard_match("*.sidecar", "sample.braw"));
assert!(wildcard_match("sam???.braw", "sample.braw"));
}
#[test]
fn namespace_matches_children_only() {
let ns = Namespace::from_root(PathBuf::from("C:\\__hookfs__\\abc"));
assert!(ns.is_virtual(Path::new("C:\\__hookfs__\\abc\\clip.braw")));
assert!(ns.is_virtual(Path::new("c:/__HOOKFS__/abc")));
assert!(!ns.is_virtual(Path::new("C:\\__hookfs__\\abcdef\\clip.braw")));
assert!(!ns.is_virtual(Path::new("C:\\Windows\\notepad.exe")));
}
#[test]
fn reserved_roots_are_process_random() {
assert_ne!(reserved_root(), reserved_root());
}
}
#[cfg(all(test, unix))]
#[allow(clippy::unwrap_used)]
mod posix_tests {
use super::*;
#[test]
fn normalizes_case_sensitively_and_collapses_separators() {
assert_eq!(normalize_key_str("/Foo/Bar/"), "/Foo/Bar");
assert_eq!(normalize_key_str("/a//b"), "/a/b");
assert_eq!(normalize_key_str("/"), "/");
assert_eq!(normalize_key_str("/a\\b"), "/a\\b");
}
#[test]
fn prefix_matching_respects_component_boundary() {
let prefix = "/__hookfs__/abc";
assert!(key_has_prefix("/__hookfs__/abc", prefix));
assert!(key_has_prefix("/__hookfs__/abc/clip.braw", prefix));
assert!(!key_has_prefix("/__hookfs__/abcdef/clip.braw", prefix));
assert!(!key_has_prefix("/other", prefix));
}
#[test]
fn rejects_traversal_and_nul_but_allows_colons() {
assert!(is_lexically_safe("/__hookfs__/id/clip.braw"));
assert!(!is_lexically_safe("/__hookfs__/id/../../secret"));
assert!(!is_lexically_safe("/__hookfs__/id/./clip"));
assert!(!is_lexically_safe("/__hookfs__/id/clip\0.braw"));
assert!(is_lexically_safe("/__hookfs__/id/a:b.braw"));
assert!(is_lexically_safe("/__hookfs__/id/..foo"));
assert!(is_lexically_safe("/__hookfs__/id/a...b"));
}
#[cfg(hookfs_backend)]
#[test]
fn namespace_matches_children_only_case_sensitively() {
let ns = Namespace::from_root(PathBuf::from("/__hookfs__/abc"));
assert!(ns.is_virtual(Path::new("/__hookfs__/abc/clip.braw")));
assert!(ns.is_virtual(Path::new("/__hookfs__/abc")));
assert!(!ns.is_virtual(Path::new("/__hookfs__/abcdef/clip.braw")));
assert!(!ns.is_virtual(Path::new("/__HOOKFS__/abc")));
assert!(!ns.is_virtual(Path::new("/usr/bin/ls")));
}
#[test]
fn reserved_root_is_posix_and_random() {
let root = reserved_root();
assert!(root.to_string_lossy().starts_with("/__hookfs__/"));
assert_ne!(reserved_root(), reserved_root());
}
}