use std::cell::{Cell, RefCell};
use std::collections::{HashMap, VecDeque};
const MAX_LINKS: usize = 40;
const MAX_ENTRIES: usize = 4096;
const MAX_MATCHES: usize = 256;
const SYSTEM_LINKS: [&str; 3] = ["/private/etc", "/private/tmp", "/private/var"];
const DATA_VOLUME: &str = "/System/Volumes/Data";
#[derive(Clone)]
enum Lookup {
Missing,
Other,
Link(Option<String>),
}
thread_local! {
static MEMO: RefCell<HashMap<String, Lookup>> = RefCell::new(HashMap::new());
static EVALUATIONS: Cell<usize> = const { Cell::new(0) };
}
pub(in crate::pathctx) fn evaluation_begins() {
EVALUATIONS.set(EVALUATIONS.get() + 1);
MEMO.with(|m| m.borrow_mut().clear());
}
pub(in crate::pathctx) fn evaluation_ends() {
EVALUATIONS.set(EVALUATIONS.get().saturating_sub(1));
MEMO.with(|m| m.borrow_mut().clear());
}
fn lookup(path: &str) -> Lookup {
let remember = EVALUATIONS.get() > 0;
if remember && let Some(known) = MEMO.with(|m| m.borrow().get(path).cloned()) {
return known;
}
let found = match std::fs::symlink_metadata(path) {
Ok(meta) if meta.file_type().is_symlink() => {
Lookup::Link(std::fs::read_link(path).ok().and_then(|t| t.to_str().map(str::to_string)))
}
Ok(_) => Lookup::Other,
Err(_) => Lookup::Missing,
};
if remember {
MEMO.with(|m| m.borrow_mut().insert(path.to_string(), found.clone()));
}
found
}
#[derive(Debug, PartialEq, Eq)]
enum Outcome {
Plain,
Followed(String),
}
struct Budget {
links: usize,
entries: usize,
matches: usize,
}
pub(in crate::pathctx) fn resolve(raw: &str, follow_last: bool) -> Option<String> {
if !raw.starts_with('/') {
return None;
}
let stripped = crate::engine::resolve::locus::lookup_prefix::strip_lookup_prefixes(raw);
let raw = stripped.as_deref().unwrap_or(raw);
let follow_last = follow_last || raw.ends_with('/') || raw.ends_with("/.");
let mut budget = Budget { links: 0, entries: 0, matches: 0 };
match walk(Vec::new(), parts(raw, true), follow_last, &mut budget) {
Outcome::Plain => None,
Outcome::Followed(real) => (real != crate::pathctx::lexical_join("/", raw)).then_some(real),
}
}
pub(in crate::pathctx) fn root(root: &str) -> String {
resolve(root, true).unwrap_or_else(|| root.to_string())
}
fn parts(path: &str, from_shell: bool) -> VecDeque<(String, bool)> {
path.split('/')
.filter(|s| !s.is_empty() && *s != ".")
.map(|s| (s.to_string(), from_shell))
.collect()
}
fn joined(done: &[String]) -> String {
format!("/{}", done.join("/"))
}
fn unresolved() -> Outcome {
Outcome::Followed(crate::pathctx::UNRESOLVED_CWD.to_string())
}
pub(in crate::pathctx) fn system_spelling(path: String) -> String {
if let Some(rest) = path.strip_prefix(DATA_VOLUME).filter(|rest| rest.starts_with('/')) {
return system_spelling(rest.to_string());
}
for long in SYSTEM_LINKS {
if path == long || path.starts_with(&format!("{long}/")) {
return path["/private".len()..].to_string();
}
}
path
}
fn walk(mut done: Vec<String>, mut todo: VecDeque<(String, bool)>, follow_last: bool, budget: &mut Budget) -> Outcome {
let mut followed = false;
let mut missing: Option<usize> = None;
while let Some((part, from_shell)) = todo.pop_front() {
if part == ".." {
if done
.pop()
.is_some_and(|p| p.contains(crate::cst::eval::TAGGED_PREFIX) || p == "safe-chains-unknown-workdir")
{
return unresolved();
}
if missing.is_some_and(|at| done.len() <= at) {
missing = None;
}
continue;
}
if missing.is_some() || (todo.is_empty() && !follow_last) {
done.push(part);
continue;
}
let candidate = format!("{}/{part}", joined(&done).trim_end_matches('/'));
if from_shell
&& part.contains(['*', '?', '['])
&& let Some(outcome) = glob(&done, &part, &todo, follow_last, budget)
{
let literal_link = matches!(lookup(&candidate), Lookup::Link(_));
let unresolved = matches!(&outcome, Outcome::Followed(real) if real == crate::pathctx::UNRESOLVED_CWD);
if !literal_link || unresolved {
return outcome;
}
}
match lookup(&candidate) {
Lookup::Link(target) => {
budget.links += 1;
if budget.links > MAX_LINKS {
return unresolved();
}
let Some(target) = target else {
return unresolved();
};
if target.starts_with('/') {
done.clear();
}
for item in parts(&target, false).into_iter().rev() {
todo.push_front(item);
}
followed = true;
}
Lookup::Other => done.push(part),
Lookup::Missing => {
missing = Some(done.len());
done.push(part);
}
}
}
if followed { Outcome::Followed(system_spelling(joined(&done))) } else { Outcome::Plain }
}
fn glob(done: &[String], pattern: &str, rest: &VecDeque<(String, bool)>, follow_last: bool, budget: &mut Budget) -> Option<Outcome> {
let dir = joined(done);
#[cfg(test)]
crate::pathctx::guard_listing(&dir);
let entries = std::fs::read_dir(&dir).ok()?;
let mut names = Vec::new();
for entry in entries {
budget.entries += 1;
if budget.entries > MAX_ENTRIES {
return Some(unresolved());
}
let Some(name) = entry.ok().and_then(|e| e.file_name().into_string().ok()) else {
return Some(unresolved());
};
names.push(name);
}
let mut reached: Vec<String> = Vec::new();
let mut plain = 0usize;
for name in names {
if name.starts_with('.') && !pattern.starts_with('.') {
continue;
}
match crate::cst::opaque::glob::matches(pattern.as_bytes(), name.as_bytes()) {
Some(true) => {}
Some(false) => continue,
None => return Some(unresolved()),
}
budget.matches += 1;
if budget.matches > MAX_MATCHES {
return Some(unresolved());
}
let mut next = rest.clone();
next.push_front((name, false));
match walk(done.to_vec(), next, follow_last, budget) {
Outcome::Followed(real) if real == crate::pathctx::UNRESOLVED_CWD => return Some(unresolved()),
Outcome::Followed(real) => reached.push(real),
Outcome::Plain => plain += 1,
}
}
reached.sort();
reached.dedup();
match reached.len() {
0 => None,
1 if plain == 0 => reached.pop().map(Outcome::Followed),
_ if reached.iter().all(|real| stays_unprotected(real)) => None,
_ => Some(unresolved()),
}
}
fn stays_unprotected(real: &str) -> bool {
let crate::pathctx::Root::Known(root) = crate::pathctx::root() else {
return false;
};
if !root.starts_with('/') {
return false;
}
let root = self::root(&root);
let inside = real == root || real.starts_with(&format!("{}/", root.trim_end_matches('/')));
inside && !real.contains(['*', '?', '[']) && crate::engine::resolve::write_target_verdict(real) != crate::verdict::Verdict::Denied
}
#[cfg(test)]
#[path = "physical_tests.rs"]
mod tests;