latexml_core/util/pathname/
confinement.rs1use std::{
9 cell::{Cell, RefCell},
10 path::{Component, Path},
11 rc::Rc,
12 sync::OnceLock,
13};
14
15use rustc_hash::{FxHashMap, FxHashSet};
16
17use super::{absolute, canonical, is_absolute, is_contained, is_contained_resolved, is_nasty};
18
19#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
21pub struct InputConfinement {
22 pub source: Option<String>,
24 pub destination: Option<String>,
26 pub site: Option<String>,
28 pub paths: Vec<String>,
30}
31
32struct Active {
33 given: InputConfinement,
35 roots: Vec<String>,
37 refused: RefCell<FxHashSet<String>>,
39 dropped_dirs: RefCell<FxHashSet<String>>,
40 resolved: RefCell<FxHashMap<String, bool>>,
42 linked_files: RefCell<FxHashMap<String, bool>>,
44 installed: RefCell<FxHashSet<String>>,
46}
47
48thread_local! {
49 static ACTIVE: RefCell<Option<Rc<Active>>> = const { RefCell::new(None) };
50 static OWN_BEHALF: Cell<u32> = const { Cell::new(0) };
51 static REQUESTED: RefCell<Option<(String, bool)>> = const { RefCell::new(None) };
53 static PROBING: Cell<u32> = const { Cell::new(0) };
55}
56
57#[must_use = "the conversion is confined only while the guard lives"]
59pub struct ConfinementGuard {
60 previous: Option<Rc<Active>>,
61}
62
63impl Drop for ConfinementGuard {
64 fn drop(&mut self) {
65 let previous = self.previous.take();
66 ACTIVE.with(|active| *active.borrow_mut() = previous);
67 }
68}
69
70pub fn confine(roots: InputConfinement) -> ConfinementGuard {
73 let (active, guard) = install(roots, Vec::new());
74 for dir in env_texinputs_dirs() {
75 if !active.allows(&dir) {
76 crate::common::error::warn_at_session_start(
77 "refused_file",
78 &dir,
79 format!(
80 "TEXINPUTS directory '{dir}' lies outside the TeX installation; a confined conversion does not read it \
81 (give it with --path)"
82 ),
83 );
84 }
85 }
86 guard
87}
88
89#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
92pub struct ConfinementSnapshot {
93 pub roots: InputConfinement,
94 pub refused: Vec<String>,
95 pub dropped_dirs: Vec<String>,
96}
97
98pub fn confinement_snapshot() -> Option<ConfinementSnapshot> {
100 let sorted = |set: &RefCell<FxHashSet<String>>| {
101 let mut list: Vec<String> = set.borrow().iter().cloned().collect();
102 list.sort();
103 list
104 };
105 ACTIVE
107 .with(|active| active.borrow().clone())
108 .map(|active| ConfinementSnapshot {
109 roots: active.given.clone(),
110 refused: sorted(&active.refused),
111 dropped_dirs: sorted(&active.dropped_dirs),
112 })
113}
114
115pub fn resume(snapshot: ConfinementSnapshot) -> ConfinementGuard {
118 let (active, guard) = install(snapshot.roots, snapshot.refused);
119 active
120 .dropped_dirs
121 .borrow_mut()
122 .extend(snapshot.dropped_dirs);
123 guard
124}
125
126fn install(roots: InputConfinement, refused: Vec<String>) -> (Rc<Active>, ConfinementGuard) {
127 let mut dirs: Vec<String> = Vec::new();
128 for dir in roots
129 .source
130 .iter()
131 .chain(&roots.destination)
132 .chain(&roots.site)
133 .chain(&roots.paths)
134 {
135 let dir = dir.strip_suffix("//").unwrap_or(dir);
136 if dir.is_empty() {
137 continue;
138 }
139 for dir in [absolute(&canonical(dir)), super::resolved(dir)] {
141 if !dirs.contains(&dir) {
142 dirs.push(dir);
143 }
144 }
145 }
146 let active = Rc::new(Active {
147 given: roots,
148 roots: dirs,
149 refused: RefCell::new(refused.into_iter().collect()),
150 dropped_dirs: RefCell::default(),
151 resolved: RefCell::default(),
152 linked_files: RefCell::default(),
153 installed: RefCell::default(),
154 });
155 let previous = ACTIVE.with(|slot| slot.borrow_mut().replace(active.clone()));
156 (active, ConfinementGuard { previous })
157}
158
159pub fn read_roots() -> Option<(Vec<String>, Vec<String>)> {
162 current().map(|active| (active.roots.clone(), tex_roots().to_vec()))
163}
164
165pub fn is_confined() -> bool { ACTIVE.with(|active| active.borrow().is_some()) }
167
168pub fn own_behalf<T>(f: impl FnOnce() -> T) -> T {
171 OWN_BEHALF.with(|depth| depth.set(depth.get() + 1));
172 struct Restore;
173 impl Drop for Restore {
174 fn drop(&mut self) { OWN_BEHALF.with(|depth| depth.set(depth.get().saturating_sub(1))); }
175 }
176 let _restore = Restore;
177 f()
178}
179
180fn current() -> Option<Rc<Active>> {
181 if OWN_BEHALF.with(Cell::get) > 0 {
182 return None;
183 }
184 ACTIVE.with(|active| active.borrow().clone())
185}
186
187pub fn read_allowed(path: &str) -> bool { current().is_none_or(|active| active.allows(path)) }
191
192#[cfg_attr(not(feature = "kpathsea"), allow(dead_code))]
196pub(super) fn kpse_hit_allowed(name: &str, found: &str) -> bool {
197 let Some(active) = current() else {
198 return true;
199 };
200 if !is_absolute(found) || is_absolute(name) || env_path_overrides() {
202 return active.allows(found);
203 }
204 if let Some(dir) = Path::new(&absolute(found)).parent() {
205 active
206 .installed
207 .borrow_mut()
208 .insert(dir.to_string_lossy().into_owned());
209 }
210 true
211}
212
213pub fn cwd_allowed() -> bool {
215 current().is_none_or(|active| {
216 std::env::current_dir().is_ok_and(|cwd| {
217 let cwd = cwd.to_string_lossy();
218 active
219 .roots
220 .iter()
221 .any(|root| is_contained(&cwd, root).is_some())
222 })
223 })
224}
225
226pub(super) fn kpse_name_ok(name: &str) -> bool {
232 let Some(active) = current() else {
233 return true;
234 };
235 if is_nasty(name) || name.starts_with(['~', '-']) {
236 return false;
237 }
238 if is_absolute(name) {
239 return active.allows(name);
240 }
241 !name.split(['/', '\\']).any(|part| part == "..")
242}
243
244pub fn requested_as<T>(name: &str, f: impl FnOnce() -> Option<T>) -> Option<T> {
248 let outermost = is_confined() && REQUESTED.with(|r| r.borrow().is_none());
249 if !outermost {
250 return f();
251 }
252 REQUESTED.with(|r| *r.borrow_mut() = Some((name.to_string(), false)));
253 struct Restore;
254 impl Drop for Restore {
255 fn drop(&mut self) { REQUESTED.with(|r| *r.borrow_mut() = None); }
256 }
257 let restore = Restore;
258 let found = f();
259 let refused = REQUESTED.with(|r| r.borrow().as_ref().is_some_and(|(_, refused)| *refused));
260 drop(restore);
261 if found.is_none() && refused {
262 refuse(name);
263 }
264 found
265}
266
267pub fn probing<T>(f: impl FnOnce() -> T) -> T {
271 PROBING.with(|depth| depth.set(depth.get() + 1));
272 struct Restore;
273 impl Drop for Restore {
274 fn drop(&mut self) { PROBING.with(|depth| depth.set(depth.get().saturating_sub(1))); }
275 }
276 let _restore = Restore;
277 f()
278}
279
280pub fn refuse(name: &str) {
284 let Some(active) = current() else {
285 return;
286 };
287 let pending = REQUESTED.with(|r| match r.borrow_mut().as_mut() {
288 Some((_, refused)) => {
289 *refused = true;
290 true
291 },
292 None => false,
293 });
294 if pending {
295 return;
296 }
297 let probe = PROBING.with(Cell::get) > 0;
298 if !active
299 .refused
300 .borrow_mut()
301 .insert(format!("{}{name}", if probe { 'P' } else { 'R' }))
302 {
303 return;
304 }
305 let roots = "a confined conversion reads only from its source, destination, site and --path directories and the \
306 TeX installation";
307 if probe {
308 crate::common::error::emit_warn(
309 "refused_file",
310 name,
311 &format!("Refused to look for '{name}' (taken as not found): {roots}"),
312 );
313 } else {
314 crate::common::error::emit_error(
315 "refused_file",
316 name,
317 &format!("Refused to read '{name}': {roots}"),
318 );
319 }
320}
321
322pub fn refused_exists(path: &str) -> bool {
328 let path = Path::new(path);
329 path.is_file()
330 || path
331 .file_name()
332 .and_then(|name| name.to_str())
333 .is_some_and(|name| {
334 let dir = match path.parent() {
335 Some(dir) if !dir.as_os_str().is_empty() => dir,
336 _ => Path::new("."),
337 };
338 super::nocase_dir_cache::lookup(dir, name).is_some()
339 })
340}
341
342pub fn refused_inside(path: &str) -> bool {
345 current().is_some_and(|active| {
346 Active::as_opened(path).is_some_and(|(_, squeezed)| {
347 active
348 .roots
349 .iter()
350 .any(|root| is_contained(&squeezed, root).is_some())
351 }) && !active.allows(path)
352 })
353}
354
355pub fn search_dir_allowed(dir: &str, path: &str) -> bool {
358 let Some(active) = current() else {
359 return true;
360 };
361 if active.allows(path) {
362 return true;
363 }
364 if active.dropped_dirs.borrow_mut().insert(dir.to_string()) {
365 crate::common::error::emit_warn(
366 "refused_file",
367 dir,
368 &format!(
369 "Search directory '{dir}' lies outside the source, destination, site and --path directories and the TeX \
370 installation; a confined conversion drops it"
371 ),
372 );
373 }
374 false
375}
376
377impl Active {
378 fn as_opened(path: &str) -> Option<(String, String)> {
381 let os_path = Path::new(path);
382 let written = if os_path.is_absolute() || os_path.has_root() {
383 path.to_string()
384 } else if path.starts_with('~') {
385 canonical(path)
386 } else {
387 std::env::current_dir()
388 .ok()?
389 .join(path)
390 .to_string_lossy()
391 .into_owned()
392 };
393 let mut squeezed = std::path::PathBuf::new();
394 for part in Path::new(&written).components() {
395 match part {
396 Component::CurDir => {},
397 Component::ParentDir => {
398 squeezed.pop();
399 },
400 part => squeezed.push(part),
401 }
402 }
403 Some((written, canonical(&squeezed.to_string_lossy())))
404 }
405
406 fn allows(&self, path: &str) -> bool {
407 if path.is_empty() || path.contains(['\0', '\r', '\n']) {
411 return false;
412 }
413 let Some((written, squeezed)) = Self::as_opened(path) else {
414 return false;
415 };
416 let lexically = self.allows_squeezed(path, &squeezed);
417 if !Path::new(&written)
421 .components()
422 .any(|part| part == Component::ParentDir)
423 {
424 return lexically;
425 }
426 landing(&written).is_some_and(|target| {
427 (lexically && landing(&squeezed).is_some_and(|squeezed| squeezed == target)) || {
428 let target = target.to_string_lossy();
429 !Path::new(target.as_ref())
430 .components()
431 .any(|part| part == Component::ParentDir)
432 && self.allows(&target)
433 }
434 })
435 }
436
437 fn allows_squeezed(&self, path: &str, squeezed: &str) -> bool {
440 if squeezed == "/dev/null" {
442 return true;
443 }
444 if let Some(root) = self
445 .roots
446 .iter()
447 .find(|root| is_contained(squeezed, root).is_some())
448 {
449 self.resolves_inside(squeezed, root)
451 } else {
452 self.is_installed(squeezed)
453 || is_absolute(path)
455 && tex_roots()
456 .iter()
457 .any(|root| is_contained(squeezed, root).is_some())
458 }
459 }
460
461 fn is_installed(&self, path: &str) -> bool {
463 let installed = self.installed.borrow();
464 Path::new(path)
465 .ancestors()
466 .skip(1)
467 .any(|dir| installed.contains(dir.to_string_lossy().as_ref()))
468 }
469
470 fn resolves_inside(&self, path: &str, root: &str) -> bool {
471 let dir = Path::new(path)
472 .parent()
473 .map_or_else(|| path.to_string(), |p| p.to_string_lossy().into_owned());
474 let key = format!("{dir}\x1f{root}");
475 let known = self.resolved.borrow().get(&key).copied();
476 let inside = known.unwrap_or_else(|| {
477 let inside = is_contained_resolved(path, root).is_some();
478 self.resolved.borrow_mut().insert(key, inside);
479 inside
480 });
481 inside && self.file_link_inside(path, root)
482 }
483
484 fn file_link_inside(&self, path: &str, root: &str) -> bool {
488 let path = match path.trim_end_matches(std::path::is_separator) {
490 "" => path,
491 trimmed => trimmed,
492 };
493 let is_link = std::fs::symlink_metadata(path).is_ok_and(|meta| meta.file_type().is_symlink());
494 if !is_link {
495 return true;
496 }
497 let key = format!("{path}\x1f{root}");
498 if let Some(&known) = self.linked_files.borrow().get(&key) {
499 return known;
500 }
501 let inside = super::canonicalize(path).is_ok_and(|target| {
502 is_contained(&target.to_string_lossy(), &super::resolved(root)).is_some()
503 });
504 self.linked_files.borrow_mut().insert(key, inside);
505 inside
506 }
507}
508
509fn landing(path: &str) -> Option<std::path::PathBuf> {
513 let parts: Vec<Component> = Path::new(path).components().collect();
514 (1..=parts.len()).rev().find_map(|depth| {
515 let real = super::canonicalize(parts[..depth].iter().collect::<std::path::PathBuf>()).ok()?;
516 let rest = &parts[depth..];
517 Some(
518 (!rest.contains(&Component::ParentDir))
519 .then(|| rest.iter().fold(real, |path, part| path.join(part))),
520 )
521 })?
522}
523
524fn tex_roots() -> &'static [String] {
528 static ROOTS: OnceLock<Vec<String>> = OnceLock::new();
529 ROOTS.get_or_init(|| {
530 let Ok(out) = super::tex_tool_command("kpsewhich")
531 .args(["-expand-braces=$TEXMF", "-var-value=OSFONTDIR"])
532 .output()
533 else {
534 return Vec::new();
535 };
536 let home = std::env::var_os("HOME").map(|h| absolute(&h.to_string_lossy()));
537 let mut roots: Vec<String> = Vec::new();
538 for entry in String::from_utf8_lossy(&out.stdout).split(['\n', list_separator()]) {
539 let entry = entry.trim().trim_start_matches("!!");
540 let entry = entry.trim_end_matches('/');
541 if entry.is_empty() || !Path::new(entry).is_absolute() || !Path::new(entry).is_dir() {
542 continue;
543 }
544 let root = canonical(entry);
545 let holds_home = home
547 .as_deref()
548 .is_some_and(|home| is_contained(home, &root).is_some());
549 if Path::new(&root).parent().is_none() || holds_home || roots.contains(&root) {
550 continue;
551 }
552 roots.push(root);
553 }
554 roots
555 })
556}
557
558pub fn is_kpse_path_var(name: &str) -> bool {
564 const OTHER: &[&str] = &[
565 "TEXBIB",
566 "TEXPICTS",
567 "TEXPKS",
568 "TEXMFINI",
569 "TEXINDEXSTYLE",
570 "INDEXSTYLE",
571 "TEXPSHEADERS",
572 "PSHEADERS",
573 "DVIPSHEADERS",
574 "TEXMFSCRIPTS",
575 "TEXCONFIG",
576 "PDFTEXCONFIG",
577 "TEXDOCS",
578 "TEXSOURCES",
579 "TEXFONTMAPS",
580 "FONTCIDMAPS",
581 "FONTFEATURES",
582 "MFBASES",
583 "TEXFORMATS",
584 "MPMEMS",
585 "MPSUPPORT",
586 "MFPOOL",
587 "TEXPOOL",
588 "MPPOOL",
589 "TEXMFDBS",
590 "WEB2C",
591 "TEXMFDOTDIR",
592 "VARTEXFONTS",
593 ];
594 let base = name.split(['_', '.']).next().unwrap_or(name);
595 [name, base]
596 .iter()
597 .any(|n| n.ends_with("INPUTS") || n.ends_with("FONTS") || OTHER.contains(n))
598}
599
600#[cfg_attr(not(feature = "kpathsea"), allow(dead_code))]
603fn env_path_overrides() -> bool {
604 static OVERRIDES: OnceLock<bool> = OnceLock::new();
605 *OVERRIDES.get_or_init(|| {
606 std::env::vars_os()
607 .any(|(name, value)| !value.is_empty() && is_kpse_path_var(&name.to_string_lossy()))
608 })
609}
610
611fn list_separator() -> char { if cfg!(windows) { ';' } else { ':' } }
612
613fn env_texinputs_dirs() -> Vec<String> {
616 let Some(value) = std::env::var_os("TEXINPUTS") else {
617 return Vec::new();
618 };
619 value
620 .to_string_lossy()
621 .split(list_separator())
622 .map(|entry| entry.trim().trim_start_matches("!!").trim_end_matches('/'))
623 .filter(|entry| !entry.is_empty() && *entry != ".")
624 .map(|entry| absolute(&canonical(entry)))
625 .collect()
626}