Skip to main content

latexml_core/util/pathname/
confinement.rs

1//! Read confinement (OXIDIZED_DESIGN_DIVERGENCES #1183): a confined conversion reads only from its roots — the source
2//! directory, the destination and site directories, the operator's `--path` directories and the TeX installation
3//! (kpathsea's `$TEXMF` trees and `OSFONTDIR`). Every other name is never read; it is refused when it names a file
4//! ([`refused_exists`]), else it is missing as before. `pathname::find`, `pathname::kpsewhich` and the image searches
5//! ask [`read_allowed`] of the name they open, after every case fold, join or added extension; a conversion is
6//! confined while a [`ConfinementGuard`] from [`confine`] lives on its thread.
7
8use 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/// The roots a confined conversion reads from besides the TeX installation, as the front end knows them.
20#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
21pub struct InputConfinement {
22  /// The source directory: the unpacked archive, or the input's own folder (`--paranoid-input`).
23  pub source:      Option<String>,
24  /// The destination directory; none when the output goes to standard output.
25  pub destination: Option<String>,
26  /// The site directory (`--sitedirectory`, else the destination's).
27  pub site:        Option<String>,
28  /// The `--path` directories given on the command line or in the fleet's configuration.
29  pub paths:       Vec<String>,
30}
31
32struct Active {
33  /// The roots as the front end gave them (a render worker is confined to them again, [`resume`]).
34  given:        InputConfinement,
35  /// The document and operator roots, absolute and canonical.
36  roots:        Vec<String>,
37  /// Names already refused (one Error each) and search directories already dropped (one Warning each).
38  refused:      RefCell<FxHashSet<String>>,
39  dropped_dirs: RefCell<FxHashSet<String>>,
40  /// Whether a directory, every link followed, lies in the root it is lexically under.
41  resolved:     RefCell<FxHashMap<String, bool>>,
42  /// Whether a file that is a link leads to an existing file in that root.
43  linked_files: RefCell<FxHashMap<String, bool>>,
44  /// The directories of the installation's files kpathsea found, admitted without asking `kpsewhich` for `$TEXMF`.
45  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  /// The name the document gave, while a lookup tries its variants (`x.tex`, `x`), and whether one was refused.
52  static REQUESTED: RefCell<Option<(String, bool)>> = const { RefCell::new(None) };
53  /// Inside a test of whether a file exists ([`probing`]).
54  static PROBING: Cell<u32> = const { Cell::new(0) };
55}
56
57/// Keeps a conversion confined on this thread; dropping it restores what was there before.
58#[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
70/// Confine this thread's reads to `roots` and the TeX installation until the guard drops. An environment `TEXINPUTS`
71/// directory outside them is not read; the session says so once per directory, pointing to `--path`.
72pub 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/// A confined conversion as a render worker takes it over: its roots, the names refused and the search directories
90/// dropped already (each reported once for the run).
91#[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
98/// This thread's confinement, to carry into a render worker; `None` unconfined.
99pub 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  // (the thread's, whatever own-behalf read is in progress)
106  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
115/// Confine a render worker's thread as its parent was ([`confinement_snapshot`]): a refusal its parent reported is
116/// not reported again, and the session's notices are the parent's.
117pub 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    // As written and as the system names it (a temp dir under a linked `/tmp`, macOS's `/var` → `/private/var`).
140    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
159/// A confined conversion's read roots (absolute, canonical): its document and operator roots, whose links must stay
160/// inside them, and the TeX installation's, matched by spelling; `None` unconfined.
161pub fn read_roots() -> Option<(Vec<String>, Vec<String>)> {
162  current().map(|active| (active.roots.clone(), tex_roots().to_vec()))
163}
164
165/// Whether a conversion on this thread is confined.
166pub fn is_confined() -> bool { ACTIVE.with(|active| active.borrow().is_some()) }
167
168/// Run `f` with confinement lifted: the engine's own reads on its own behalf (the compiled schema, its resources),
169/// never a name a document gave.
170pub 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
187/// Whether this conversion may read `path` (relative to the working directory, as the system opens it). Always true
188/// when unconfined. A name is judged by where it lies, as written, and by its root's links; one with a `..` part,
189/// where it lands.
190pub fn read_allowed(path: &str) -> bool { current().is_none_or(|active| active.allows(path)) }
191
192/// Whether this conversion may read `found`, a file kpathsea found. An absolute hit is the installation's (kpathsea
193/// searches only its trees, `.` and the environment's path overrides) unless an override is set; a relative one is
194/// kpathsea's `.`, the working directory. An admitted hit's directory is the installation's from then on.
195#[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  // (kpathsea opens an absolute name in its own directory, a letter case folded: that hit is no installation's)
201  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
213/// Whether this conversion may search the working directory: only when it lies in a document or operator root.
214pub 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
226/// Whether kpathsea may be asked for `name`: a plain relative name (no `..`, no `~` or `$`, no leading `-`), or an
227/// absolute one [`read_allowed`] admits. kpathsea's `p` mode judges the name by its spelling too (kpathsea.info "Safe
228/// filenames": `..`, absolute names), kpathsea expands a name's `~` and `$VAR` (`kpsewhich '$TEXMFDIST/…'`), and a
229/// subprocess `kpsewhich` reads a leading `-` as an option (`-var-value=HOME`). The rest of [`is_nasty`]'s characters
230/// are refused besides, harmlessly: the source's own files are found by the directory search first.
231pub(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
244/// Run `f`, a lookup of the document's `name` under whatever variants it tries (`x.tex`, then `x`): a variant refused
245/// on the way is reported, as `name`, only when the lookup finds nothing (`\IfFileExists{/dev/null}` tries
246/// `/dev/null.tex` first). An enclosing lookup's name wins.
247pub 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
267/// Run `f`, a test of whether a file exists (`\IfFileExists`, `\openin`, `\pdffilesize`): a name refused on the way
268/// is a Warning and the document takes its not-found branch; a refused read stays an Error (DG 2026-11-26). The
269/// severity follows the construct, never whether the file exists.
270pub 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
280/// `Error:refused_file` for `name`, once per name looked for (a Warning, once, inside [`probing`]): it names a file
281/// outside every root. Inside a lookup ([`requested_as`]) the refusal waits for the lookup's outcome and is the
282/// lookup's name, whatever variants (`x.tex`, `x`) it tried.
283pub 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
322/// Whether `path`, a name the roots refuse as the system opens it, names a file: a refusal is an Error (or a test's
323/// Warning) only for a file that exists, and a missing one keeps the missing file's outcome. Any letter case counts,
324/// for every refused name alike (most lookups fall back to a case-insensitive match, kpathsea's casefold; an absolute
325/// name has none, and is refused the same way so that a refusal never depends on the file system's case
326/// sensitivity). Only "a file" or "none" is learnt of outside, in the log.
327pub 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
342/// Whether `path` lies in a document or operator root but is refused there: it, or a directory on its way, is a link
343/// leading out of the root or dangling (the root's own contents, so this tells nothing of what lies outside).
344pub 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
355/// Whether a search directory a document names `dir` (`\graphicspath`, `\input@path`), at `path`, may be searched:
356/// when not, one Warning per directory and the caller drops it.
357pub 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  /// `path` absolute as the system opens it, and that with `.`, `dir/..` and repeated separators squeezed out, each
379  /// `..` taken lexically (`.//x` is `./x` there, 1801.09240).
380  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    // Judged by where it lies, not by its spelling: a source's `pics/CAE_>2shapes_test/` is read (2204.02075,
408    // 2112.09412). A NUL would cut the name at the system call; a CR or LF is refused with it, one rule with the file
409    // finder (OXIDIZED_DESIGN_DIVERGENCES #1193).
410    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    // The system opens a `..` where the directory before it really leads, every link followed (`texmf/doc/../x` under
418    // a linked `doc`): a name with one is judged where it lands, a missing one too (a case-insensitive lookup lists
419    // that directory), unless that is where the squeezed name lands.
420    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  /// [`Active::allows`] for `squeezed` ([`Active::as_opened`]): lexically under a root, and under a document or
438  /// operator root with every link followed.
439  fn allows_squeezed(&self, path: &str, squeezed: &str) -> bool {
440    // The null device reads as an empty file: packages probe it (`\IfFileExists{/dev/null}`, 2606.05098, 2108.08086).
441    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      // The document's and operator's trees: lexically, then with every link followed.
450      self.resolves_inside(squeezed, root)
451    } else {
452      self.is_installed(squeezed)
453        // (a name relative to the working directory, no root, is never the installation's)
454        || is_absolute(path)
455          && tex_roots()
456            .iter()
457            .any(|root| is_contained(squeezed, root).is_some())
458    }
459  }
460
461  /// Whether `path` lies in a directory of a file kpathsea found (or below it).
462  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  /// Whether `path`, when itself a symbolic link (a `--paranoid-input` folder's `leak.tex -> ../secret.tex`), leads to
485  /// an existing file in `root`: a link out to a regular file is refused with an Error, a dangling one keeps the
486  /// missing file's outcome ([`refused_exists`]).
487  fn file_link_inside(&self, path: &str, root: &str) -> bool {
488    // (a directory named with a trailing `/`, `\graphicspath{{gdir/}}`, is the link itself, not what it leads to)
489    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
509/// Where the system opens `path`, an absolute name: its deepest existing ancestor with every link followed, the rest
510/// joined as written. `None` when nothing on its way exists or a `..` follows a missing directory (no file is opened
511/// through one).
512fn 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
524/// The TeX installation's trees, read-only roots of every confined conversion: kpathsea's brace-expanded `$TEXMF`
525/// (user trees included, as kpathsea gives them) and `OSFONTDIR`, the existing absolute directories among them. Matched
526/// by spelling, not resolved: a distribution's tree links to files outside it. Asked of `kpsewhich` once per process.
527fn 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      // Never the file-system root, nor a tree holding the user's home directory.
546      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
558/// Whether `name` is an environment variable that sets a kpathsea search path: every variable of kpathsea's format
559/// table (`kpsewhich --help-formats`: the `…INPUTS` and `…FONTS` families, `TEXBIB`, `TEXPICTS`, `TEXPSHEADERS`, …),
560/// `TEXMFDOTDIR` and `VARTEXFONTS` (which the format paths expand outside the `$TEXMF` trees), and each of them in
561/// kpathsea's per-program form (`TEXINPUTS_latex`, `TEXINPUTS.latex`). `TEXMFCNF`, `OSFONTDIR` and the `TEXMF…` tree
562/// variables are the installation's own configuration, trusted as the installation (docs/release/SAFETY.md).
563pub 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/// Whether the environment overrides a kpathsea search path ([`is_kpse_path_var`]): a hit may then come from a
601/// directory outside the installation.
602#[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
613/// The directories of an environment `TEXINPUTS` (kpathsea's `!!` and `//` marks dropped; an empty entry, kpathsea's
614/// default path, is the installation's).
615fn 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}