1#[cfg(feature = "kpathsea")]
2use std::sync::Mutex;
3use std::{
4 env,
5 path::{Path, PathBuf},
6 sync::{LazyLock, OnceLock},
7};
8
9#[cfg(feature = "kpathsea")]
10use kpathsea::Kpaths;
11use regex::Regex;
12
13mod confinement;
14pub use confinement::{
15 ConfinementGuard, ConfinementSnapshot, InputConfinement, confine, confinement_snapshot,
16 cwd_allowed, is_confined, is_kpse_path_var, own_behalf, probing, read_allowed, read_roots,
17 refuse, refused_exists, refused_inside, requested_as, resume, search_dir_allowed,
18};
19
20#[derive(Debug, Clone, Default)]
27pub struct PathnameFindOptions {
28 pub paths: Option<Vec<String>>,
30 pub extensions: Option<Vec<String>>,
32 pub installation_subdir: Option<String>,
34}
35
36static LITERAL_PROTOCOL: &str = "literal:";
37static HOME_TILDE: &str = "~";
38static HOME_PATH: LazyLock<String> =
41 LazyLock::new(
42 || match env::var_os("HOME").or_else(|| env::var_os("USERPROFILE")) {
43 Some(val) => val.to_string_lossy().into_owned(),
44 _ => s!("~"),
45 },
46 );
47static PROTOCOL_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(https|http|ftp):").unwrap());
48static PATHNAME_IS_NASTY_RE: LazyLock<Regex> =
52 LazyLock::new(|| Regex::new(r#"[`$;|<>"\x00\n\r]"#).unwrap());
53static URL_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\w+://(.+)/([^/]+)$").unwrap());
55static URL_PREFIX_RE: LazyLock<Regex> =
64 LazyLock::new(|| Regex::new(r"^(?:https|http|ftp):").unwrap());
65
66#[cfg(feature = "kpathsea")]
83static KPSE: LazyLock<Mutex<Option<Kpaths>>> = LazyLock::new(|| Mutex::new(select_kpaths()));
84
85#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub enum KpathseaBackend {
90 InProcess,
92 Subprocess,
94 Unavailable,
96}
97
98impl KpathseaBackend {
99 pub fn as_str(self) -> &'static str {
101 match self {
102 Self::InProcess => "in-process",
103 Self::Subprocess => "subprocess kpsewhich",
104 Self::Unavailable => "unavailable",
105 }
106 }
107}
108
109#[cfg(feature = "kpathsea")]
111static BACKEND: OnceLock<(KpathseaBackend, &'static str)> = OnceLock::new();
112
113#[cfg(feature = "kpathsea")]
116pub fn kpathsea_backend() -> (KpathseaBackend, &'static str) {
117 drop(KPSE.lock().unwrap());
118 *BACKEND
119 .get()
120 .unwrap_or(&(KpathseaBackend::Unavailable, "not initialized"))
121}
122
123#[cfg(not(feature = "kpathsea"))]
125pub fn kpathsea_backend() -> (KpathseaBackend, &'static str) {
126 (
127 KpathseaBackend::Unavailable,
128 "built without the kpathsea feature",
129 )
130}
131
132#[cfg(feature = "kpathsea")]
141fn choose_kpaths(
142 banner: Option<&str>,
143 new_in_process: impl FnOnce() -> Result<Kpaths, &'static str>,
144 new_subprocess: impl Fn() -> Result<Kpaths, &'static str>,
145 can_resolve: impl FnOnce(&Kpaths) -> bool,
146 same_tree_as_ambient: impl FnOnce(&Kpaths) -> bool,
147) -> (Option<Kpaths>, KpathseaBackend, &'static str) {
148 if banner.is_some_and(|b| b.contains("MiKTeX"))
154 && let Ok(subprocess) = new_subprocess()
155 {
156 return (Some(subprocess), KpathseaBackend::Subprocess, "MiKTeX host");
157 }
158 match new_in_process() {
159 Ok(kpse) if kpse.is_in_process() && !can_resolve(&kpse) => match new_subprocess() {
163 Ok(subprocess) => (
164 Some(subprocess),
165 KpathseaBackend::Subprocess,
166 "linked libkpathsea resolved no host files",
167 ),
168 Err(_) => (
170 Some(kpse),
171 KpathseaBackend::InProcess,
172 "linked libkpathsea resolves no host files, and no kpsewhich to fall back to",
173 ),
174 },
175 Ok(kpse) if kpse.is_in_process() && !same_tree_as_ambient(&kpse) => match new_subprocess() {
188 Ok(subprocess) => (
189 Some(subprocess),
190 KpathseaBackend::Subprocess,
191 "linked libkpathsea anchors a different TeX tree than the PATH kpsewhich",
192 ),
193 Err(_) => (
194 Some(kpse),
195 KpathseaBackend::InProcess,
196 "linked libkpathsea anchors a different TeX tree, and no kpsewhich to fall back to",
197 ),
198 },
199 Ok(kpse) if kpse.is_in_process() => (Some(kpse), KpathseaBackend::InProcess, "linked"),
200 Ok(kpse) => (
201 Some(kpse),
202 KpathseaBackend::Subprocess,
203 "no linked libkpathsea",
204 ),
205 Err(_) => match new_subprocess() {
209 Ok(subprocess) => (
210 Some(subprocess),
211 KpathseaBackend::Subprocess,
212 "libkpathsea unavailable",
213 ),
214 Err(_) => (
215 None,
216 KpathseaBackend::Unavailable,
217 "no usable libkpathsea and no kpsewhich executable",
218 ),
219 },
220 }
221}
222
223#[cfg(feature = "kpathsea")]
224pub use kpathsea::{TEXMF_ROOT_VARS, TrimmedRoot, trim_texmf_root};
225
226#[cfg(not(feature = "kpathsea"))]
228pub const TEXMF_ROOT_VARS: [&str; 9] = [
229 "TEXMFROOT",
230 "TEXMFDIST",
231 "TEXMFMAIN",
232 "TEXMFLOCAL",
233 "TEXMFSYSVAR",
234 "TEXMFSYSCONFIG",
235 "TEXMFHOME",
236 "TEXMFVAR",
237 "TEXMFCONFIG",
238];
239
240#[cfg(not(feature = "kpathsea"))]
243pub fn trim_texmf_root(value: &str) -> Option<String> {
244 let (separators, list_separator): (&[char], char) = if cfg!(windows) {
245 (&['/', '\\'], ';')
246 } else {
247 (&['/'], ':')
248 };
249 if value.contains([list_separator, ',', '{']) {
250 return None;
251 }
252 let stem = value.trim_end_matches(separators);
253 let is_drive = cfg!(windows) && stem.len() == 2 && stem.ends_with(':');
254 let keep = if stem.is_empty() || is_drive {
255 stem.len() + 1
256 } else {
257 stem.len()
258 };
259 (keep < value.len()).then(|| value[..keep].to_string())
260}
261
262#[cfg(feature = "kpathsea")]
265pub fn trimmed_texmf_roots() -> &'static [TrimmedRoot] {
266 drop(
267 KPSE
268 .lock()
269 .unwrap_or_else(std::sync::PoisonError::into_inner),
270 );
271 kpathsea::trimmed_texmf_roots()
272}
273
274#[cfg(not(feature = "kpathsea"))]
276pub fn trimmed_texmf_roots() -> &'static [TrimmedRoot] { &[] }
277
278#[cfg(not(feature = "kpathsea"))]
280#[derive(Debug, Clone, PartialEq, Eq)]
281pub struct TrimmedRoot {
282 pub var: &'static str,
284 pub given: String,
286 pub used: String,
288}
289
290pub fn texmf_root_env() -> Vec<(&'static str, String)> {
293 TEXMF_ROOT_VARS
294 .iter()
295 .filter_map(|&var| Some((var, trim_texmf_root(&env::var(var).ok()?)?)))
296 .collect()
297}
298
299pub fn tex_tool_command(program: impl AsRef<std::ffi::OsStr>) -> std::process::Command {
302 let mut command = std::process::Command::new(program);
303 command.envs(texmf_root_env());
304 command
305}
306
307#[cfg(feature = "kpathsea")]
310fn select_kpaths() -> Option<Kpaths> {
311 if env::var_os("TEXMFROOT").is_none()
316 && let Some(root) = ambient_texlive_root()
317 {
318 unsafe {
319 env::set_var("TEXMFROOT", root);
320 }
321 }
322 let (kpse, backend, why) = choose_kpaths(
323 ambient_kpsewhich_version(),
324 Kpaths::new,
325 Kpaths::new_subprocess,
326 |kpse| kpse.find_file("cmr10.tfm").is_some(),
329 |kpse| match ambient_texlive_root() {
336 None => true,
337 Some(root) => kpse
338 .find_file("latex.ltx")
339 .is_none_or(|p| path_is_under(&p, root)),
340 },
341 );
342 let _ = BACKEND.set((backend, why));
343 kpse
344}
345
346#[cfg(feature = "kpathsea")]
351fn path_is_under(path: &str, root: &str) -> bool {
352 let fold = |s: &str| {
353 if cfg!(windows) {
354 s.replace('\\', "/").to_ascii_lowercase()
355 } else {
356 s.to_string()
357 }
358 };
359 let (path, root) = (fold(path), fold(root));
360 let root = root.trim_end_matches('/');
361 path
362 .strip_prefix(root)
363 .is_some_and(|rest| rest.is_empty() || rest.starts_with('/'))
364}
365
366pub fn ambient_kpsewhich_selfautoparent() -> Option<&'static str> {
377 static SELF_AUTO_PARENT: OnceLock<Option<String>> = OnceLock::new();
378 SELF_AUTO_PARENT
379 .get_or_init(|| {
380 let out = tex_tool_command("kpsewhich")
381 .args(["-var-value=SELFAUTOPARENT"])
382 .output()
383 .ok()?;
384 if !out.status.success() {
385 return None;
386 }
387 let root = String::from_utf8(out.stdout).ok()?.trim().to_string();
388 if root.is_empty() { None } else { Some(root) }
389 })
390 .as_deref()
391}
392
393#[cfg(feature = "kpathsea")]
394fn ambient_texlive_root() -> Option<&'static str> {
395 let root = ambient_kpsewhich_selfautoparent()?;
396 Path::new(root).join("texmf-dist").is_dir().then_some(root)
397}
398
399pub fn ambient_kpsewhich_version() -> Option<&'static str> {
412 static BANNER: OnceLock<Option<String>> = OnceLock::new();
413 BANNER
414 .get_or_init(|| {
415 let out = tex_tool_command("kpsewhich")
416 .arg("--version")
417 .output()
418 .ok()?;
419 if !out.status.success() {
420 return None;
421 }
422 String::from_utf8(out.stdout).ok()
423 })
424 .as_deref()
425}
426
427#[cfg(feature = "kpathsea")]
453pub fn prewarm_kpathsea() {
454 static PREWARM_ONCE: std::sync::Once = std::sync::Once::new();
461 PREWARM_ONCE.call_once(|| {
462 let kpse_guard = KPSE.lock().unwrap();
463 let Some(ref kpse) = *kpse_guard else {
464 return;
465 };
466 if !kpse.is_in_process() {
472 return;
473 }
474 for sentinel in &[
475 "warmup_lxoxide.tex",
476 "warmup_lxoxide.sty",
477 "warmup_lxoxide.cls",
478 "warmup_lxoxide.def",
479 "warmup_lxoxide.bst",
480 "warmup_lxoxide.fmt",
481 "warmup_lxoxide.afm",
482 "warmup_lxoxide.tfm",
483 "warmup_lxoxide.pfb",
484 "warmup_lxoxide.enc",
485 "warmup_lxoxide.map",
486 ] {
487 let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| kpse.find_file(sentinel)));
490 }
491 });
492}
493
494#[cfg(not(feature = "kpathsea"))]
497pub fn prewarm_kpathsea() {}
498
499#[cfg(feature = "kpathsea")]
523pub fn init_kpathsea() {
524 drop(
526 KPSE
527 .lock()
528 .unwrap_or_else(std::sync::PoisonError::into_inner),
529 );
530}
531
532#[cfg(not(feature = "kpathsea"))]
533pub fn init_kpathsea() {}
534
535static CANONICAL_URL_RE: LazyLock<Regex> =
537 LazyLock::new(|| Regex::new(r"^((?:https|http|ftp)://[^/]*)").unwrap());
538
539pub fn is_url(path: &str) -> bool { URL_PREFIX_RE.is_match(path) }
563pub fn is_literaldata(data: &str) -> bool { data.starts_with(LITERAL_PROTOCOL) }
565
566pub fn is_reloadable(pathname: &str) -> bool {
568 let (_dir, _name, ext) = split(pathname);
569 ext == "ldf"
573}
574pub fn is_raw(pathname: &str) -> bool {
577 matches!(
578 extension(pathname).as_str(),
579 "tex" | "pool" | "sty" | "cls" | "clo" | "cnf" | "cfg" | "ldf" | "def" | "dfu"
580 )
581}
582
583pub fn is_absolute(path: &str) -> bool {
587 let canonical = canonical(path);
588 let path = Path::new(&canonical);
589 path.is_absolute() || path.has_root()
590}
591pub fn absolute(path: &str) -> String {
606 let p = Path::new(path);
607 let joined: PathBuf = if p.is_absolute() {
608 p.to_path_buf()
609 } else {
610 let cwd = env::current_dir().expect("cannot make path absolute: current_dir() failed");
611 cwd.join(p)
612 };
613 canonical(&joined.to_string_lossy())
614}
615
616pub fn split(pathname: &str) -> (String, String, String) {
619 let canonical_pathname = canonical(pathname);
620 let canonical_path = Path::new(&canonical_pathname);
621 let pathdir = match canonical_path.parent() {
622 Some(dir) => dir.to_string_lossy().to_string(),
623 None => String::new(),
624 };
625 let name = match canonical_path.file_stem() {
626 Some(n) => n.to_string_lossy().to_string(),
627 None => String::new(),
628 };
629 let pathname_ext = match canonical_path.extension() {
631 Some(e) => e.to_string_lossy().to_string(),
632 None => String::new(),
633 };
634 (pathdir, name, pathname_ext)
635}
636
637pub fn url_split(url: &str) -> (&str, &str) {
639 if let Some(caps) = URL_RE.captures(url) {
640 (
641 caps.get(1).map_or("", |m| m.as_str()),
642 caps.get(2).map_or("", |m| m.as_str()),
643 )
644 } else {
645 (url, "index.tex") }
647}
648
649pub const WINDOWS_VERBATIM_PREFIXES: [&str; 2] = [r"\\?\", "//?/"];
652
653pub fn strip_windows_verbatim_prefix(path: &str) -> &str {
655 WINDOWS_VERBATIM_PREFIXES
656 .iter()
657 .find_map(|prefix| path.strip_prefix(prefix))
658 .unwrap_or(path)
659}
660
661pub fn canonicalize(path: impl AsRef<Path>) -> std::io::Result<PathBuf> {
667 let canonical = std::fs::canonicalize(path)?;
668 if cfg!(windows)
669 && let Some(s) = canonical.to_str()
670 && let Some(rest) = s.strip_prefix(WINDOWS_VERBATIM_PREFIXES[0])
671 && rest.as_bytes().get(1) == Some(&b':')
672 && rest.as_bytes().first().is_some_and(u8::is_ascii_alphabetic)
673 && rest.len() < 260
674 {
675 return Ok(PathBuf::from(rest));
676 }
677 Ok(canonical)
678}
679
680pub fn canonical(pathname: &str) -> String {
683 if is_literaldata(pathname) {
684 return pathname.to_owned();
685 }
686 let home_path: &str = &HOME_PATH;
688
689 let mut pathname = if pathname.starts_with(HOME_TILDE) {
690 pathname.replacen(HOME_TILDE, home_path, 1)
691 } else {
692 pathname.to_string()
693 };
694
695 #[cfg(windows)]
703 {
704 if pathname.contains('\\') {
705 pathname = pathname.replace('\\', "/");
706 }
707 }
708
709 let url_prefix = if let Some(caps) = CANONICAL_URL_RE.captures(&pathname) {
711 let prefix = caps.get(1).unwrap().as_str().to_string();
712 pathname = pathname[prefix.len()..].to_string();
713 Some(prefix)
714 } else {
715 None
716 };
717
718 while pathname.contains("/./") {
720 pathname = pathname.replace("/./", "/");
721 }
722 loop {
726 let collapsed = pathname.match_indices("/..").find_map(|(dotdot_pos, _)| {
729 let after = dotdot_pos + 3;
730 if dotdot_pos == 0 || (after < pathname.len() && pathname.as_bytes()[after] != b'/') {
731 return None;
732 }
733 let (prefix, trail) = (&pathname[..dotdot_pos], &pathname[after..]);
734 match prefix.rfind('/') {
735 Some(slash_pos) => {
736 let component = &prefix[slash_pos + 1..];
737 (component != ".." && !component.is_empty()).then(|| match &pathname[..slash_pos] {
738 "" if trail.is_empty() => "/".to_string(),
740 head => format!("{head}{trail}"),
741 })
742 },
743 None => (prefix != ".." && prefix != ".").then(|| {
745 let rest = trail.trim_start_matches('/');
746 if rest.is_empty() {
747 ".".to_string()
748 } else {
749 rest.to_string()
750 }
751 }),
752 }
753 });
754 match collapsed {
755 Some(shorter) => pathname = shorter,
756 None => break,
757 }
758 }
759 if let Some(rest) = pathname.strip_prefix("./")
762 && !rest.is_empty()
763 {
764 pathname = match rest.trim_start_matches('/') {
765 "" => "./".to_string(),
766 rest => rest.to_string(),
767 };
768 }
769 match url_prefix {
770 Some(prefix) => format!("{}{}", prefix, pathname),
771 None => pathname,
772 }
773}
774
775pub fn protocol(pathname: &str) -> String {
777 if let Some(cap) = PROTOCOL_RE.captures(pathname) {
778 cap.get(1).map_or(String::new(), |m| m.as_str().to_string())
779 } else if is_literaldata(pathname) {
780 "literal".to_string()
781 } else {
782 "file".to_string()
783 }
784}
785
786pub fn concat(dir: &str, file: &str) -> String {
788 if dir.is_empty() {
789 file.to_owned()
790 } else if file.is_empty() || file == "." {
791 dir.to_owned()
792 } else {
793 canonical(&format!("{dir}/{file}"))
798 }
799}
800
801fn expand_recursive_dirs(base: &str) -> Vec<String> {
808 let mut out = vec![base.to_string()];
809 let mut visited = std::collections::HashSet::new();
812 if let Ok(canon) = std::fs::canonicalize(base) {
813 visited.insert(canon);
814 }
815 let mut queue = std::collections::VecDeque::from([PathBuf::from(base)]);
816 while let Some(dir) = queue.pop_front() {
817 let Ok(entries) = std::fs::read_dir(&dir) else {
818 continue;
819 };
820 let mut children: Vec<PathBuf> = entries
821 .flatten()
822 .map(|e| e.path())
823 .filter(|p| p.is_dir())
824 .filter(|p| {
825 p.file_name()
827 .and_then(|n| n.to_str())
828 .is_none_or(|n| !n.starts_with('.'))
829 })
830 .collect();
831 children.sort();
832 for child in children {
833 if let Ok(canon) = std::fs::canonicalize(&child)
835 && !visited.insert(canon)
836 {
837 continue;
838 }
839 if let Some(s) = child.to_str() {
840 out.push(s.replace('\\', "/"));
842 queue.push_back(child);
843 }
844 }
845 }
846 out
847}
848
849pub fn dot_relative(pathname: &str) -> &str {
852 let Some(mut rest) = pathname.strip_prefix("./") else {
853 return pathname;
854 };
855 let mut doubled = false;
856 loop {
857 if let Some(shorter) = rest.strip_prefix('/') {
858 (rest, doubled) = (shorter, true);
859 } else if let Some(shorter) = rest.strip_prefix("./") {
860 rest = shorter;
861 } else {
862 break;
863 }
864 }
865 if doubled && !rest.is_empty() {
866 rest
867 } else {
868 pathname
869 }
870}
871
872pub fn candidate_pathnames(pathname: &str, options: PathnameFindOptions) -> Vec<String> {
876 candidates(pathname, options, false)
877}
878
879fn candidates(pathname: &str, options: PathnameFindOptions, as_written: bool) -> Vec<String> {
882 let mut dirs: Vec<String> = Vec::new();
883 let pathname = dot_relative(pathname);
884 let canonical_pathname = if pathname != "*" {
885 canonical(pathname)
886 } else {
887 pathname.to_owned()
888 };
889
890 let (pathdir, name_stem, pathname_ext) = split(&canonical_pathname);
891 let name = if !pathname_ext.is_empty() {
894 format!("{}.{}", name_stem, pathname_ext)
895 } else {
896 name_stem
897 };
898
899 let cwd = cwd();
900
901 let written: &str = if pathname.starts_with('~') {
903 &canonical_pathname
904 } else {
905 pathname
906 };
907 if is_absolute(&canonical_pathname) {
908 dirs.push(if as_written {
909 String::new()
910 } else {
911 pathdir.clone()
912 });
913 } else if let Some(paths) = options.paths {
914 for p in paths {
915 let (base, recursive) = match p.strip_suffix("//") {
919 Some(b) => (b.trim_end_matches('/'), true),
920 None => (p.as_str(), false),
921 };
922 let pp_base = if is_absolute(base) {
924 canonical(base)
925 } else {
926 concat(&cwd, base)
927 };
928 let roots = if recursive {
931 expand_recursive_dirs(&pp_base)
932 } else {
933 vec![pp_base]
934 };
935 for root in roots {
936 let pp = if as_written {
937 root
938 } else {
939 concat(&root, &pathdir)
940 };
941 if !dirs.contains(&pp) {
943 dirs.push(pp);
944 }
945 }
946 }
947 }
948 if dirs.is_empty() {
951 let from_cwd = if as_written {
952 cwd.clone()
953 } else {
954 concat(&cwd, &pathdir)
955 };
956 if !dirs.contains(&from_cwd) {
957 dirs.push(from_cwd);
958 }
959 }
960
961 if let Some(subdir) = options.installation_subdir {
969 let full_subdir = concat(&cwd, &subdir);
971 if Path::new(&full_subdir).exists() {
972 dirs.push(full_subdir);
973 } else {
974 let full_subdir_oneup = concat(&s!("{}/..", cwd), &subdir);
975 if Path::new(&full_subdir_oneup).exists() {
976 dirs.push(full_subdir_oneup);
977 }
978 }
979 }
980 let mut exts = Vec::new();
984 if let Some(ext_vec) = options.extensions {
985 for ext in ext_vec {
986 if ext.is_empty() {
987 exts.push(String::new());
988 } else if ext == "*" {
989 exts.push(s!(".*"));
990 exts.push(String::new());
991 } else if !pathname_ext.is_empty() && pathname_ext.eq_ignore_ascii_case(&ext) {
992 exts.push(String::new());
996 exts.push(format!(".{}", ext));
998 } else {
999 exts.push(format!(".{}", ext));
1000 }
1001 }
1002 }
1003 if exts.is_empty() {
1004 exts.push(String::new());
1005 }
1006
1007 let mut paths = Vec::new();
1008 for dir in &dirs {
1010 for ext in &exts {
1011 if name == "*" {
1012 } else if as_written {
1014 paths.push(match dir.as_str() {
1015 "" => format!("{written}{ext}"),
1016 dir => format!("{dir}/{written}{ext}"),
1017 });
1018 } else {
1019 paths.push(concat(dir, &(name.clone() + ext)));
1020 }
1021 }
1022 }
1023 paths
1024}
1025
1026mod nocase_dir_cache {
1027 use std::{
1028 cell::RefCell,
1029 fs::{self, Metadata},
1030 path::{Path, PathBuf},
1031 time::SystemTime,
1032 };
1033
1034 use rustc_hash::FxHashMap;
1035
1036 use super::is_readable_file;
1037
1038 const MAX_CACHED_DIRS: usize = 256;
1039
1040 #[derive(Clone, PartialEq, Eq)]
1041 struct DirStamp {
1042 modified: Option<SystemTime>,
1043 #[cfg(unix)]
1044 dev: u64,
1045 #[cfg(unix)]
1046 ino: u64,
1047 #[cfg(unix)]
1048 ctime: i64,
1049 #[cfg(unix)]
1050 ctime_ns: i64,
1051 #[cfg(unix)]
1052 nlink: u64,
1053 #[cfg(not(unix))]
1054 len: u64,
1055 }
1056
1057 impl DirStamp {
1058 fn from_meta(m: &Metadata) -> Self {
1059 #[cfg(unix)]
1060 {
1061 use std::os::unix::fs::MetadataExt;
1062 Self {
1063 modified: m.modified().ok(),
1064 dev: m.dev(),
1065 ino: m.ino(),
1066 ctime: m.ctime(),
1067 ctime_ns: m.ctime_nsec(),
1068 nlink: m.nlink(),
1069 }
1070 }
1071 #[cfg(not(unix))]
1072 {
1073 Self {
1074 modified: m.modified().ok(),
1075 len: m.len(),
1076 }
1077 }
1078 }
1079 }
1080
1081 struct DirIndex {
1082 stamp: DirStamp,
1083 entries: FxHashMap<String, String>,
1084 }
1085
1086 thread_local! {
1087 static CACHE: RefCell<FxHashMap<PathBuf, DirIndex>> = RefCell::new(FxHashMap::default());
1088 }
1089
1090 pub(super) fn clear() { CACHE.with(|cell| cell.borrow_mut().clear()); }
1091
1092 fn build_index(dir: &Path, stamp: DirStamp) -> Option<DirIndex> {
1093 let rd = fs::read_dir(dir).ok()?;
1094 let mut entries = FxHashMap::default();
1095 for entry in rd.flatten() {
1096 let file_name = entry.file_name();
1097 let Some(name) = file_name.to_str() else {
1098 continue;
1099 };
1100 let is_dir = match entry.file_type() {
1103 Ok(ft) if ft.is_dir() => true,
1104 Ok(ft) if ft.is_file() => false,
1105 _ => entry.path().is_dir(),
1106 };
1107 if is_dir {
1108 continue;
1109 }
1110 entries
1111 .entry(name.to_ascii_lowercase())
1112 .or_insert_with(|| name.to_string());
1113 }
1114 Some(DirIndex { stamp, entries })
1115 }
1116
1117 pub(super) fn lookup(dir: &Path, target: &str) -> Option<String> {
1121 let meta = fs::metadata(dir).ok()?;
1122 if !meta.is_dir() {
1123 return None;
1124 }
1125 let stamp = DirStamp::from_meta(&meta);
1126 let target_lower = target.to_ascii_lowercase();
1127
1128 #[cfg(not(unix))]
1130 if !dir.is_absolute() {
1131 let idx = build_index(dir, stamp)?;
1132 let actual = idx.entries.get(&target_lower)?;
1133 let full = dir.join(actual).to_str()?.to_string();
1134 return is_readable_file(&full).then_some(full);
1135 }
1136
1137 let matched = CACHE.with(|cell| {
1138 let mut cache = cell.borrow_mut();
1139 let fresh = cache
1140 .get(dir)
1141 .is_some_and(|existing| existing.stamp == stamp);
1142 if !fresh {
1143 let idx = build_index(dir, stamp)?;
1144 if cache.len() >= MAX_CACHED_DIRS {
1145 cache.clear();
1146 }
1147 cache.insert(dir.to_path_buf(), idx);
1148 }
1149 cache
1150 .get(dir)
1151 .and_then(|idx| idx.entries.get(&target_lower).cloned())
1152 })?;
1153 let full = dir.join(matched).to_str()?.to_string();
1154 is_readable_file(&full).then_some(full)
1155 }
1156}
1157
1158pub fn clear_nocase_dir_cache() { nocase_dir_cache::clear(); }
1163
1164pub fn find(pathname: &str, options: PathnameFindOptions) -> Option<String> {
1174 if pathname.is_empty() {
1175 return None;
1176 }
1177 let no_paths = options.paths.as_ref().is_none_or(|paths| paths.is_empty());
1178 let opened_options = is_confined().then(|| options.clone());
1179 let mut paths = candidate_pathnames(pathname, options);
1180 let mut refused_outside = None;
1184 if let Some(opened_options) = opened_options {
1185 let (inside, outside): (Vec<String>, Vec<String>) =
1186 paths.into_iter().partition(|path| read_allowed(path));
1187 paths = inside;
1188 if !outside.is_empty()
1189 && !(no_paths && !is_absolute(pathname) && confinement::kpse_name_ok(pathname))
1190 {
1191 let all_outside = paths.is_empty();
1192 let names_a_file = move || {
1193 candidates(pathname, opened_options, true)
1194 .iter()
1195 .any(|path| (all_outside || !read_allowed(path)) && refused_exists(path))
1196 };
1197 if all_outside {
1198 if names_a_file() {
1199 refuse(pathname);
1200 }
1201 return None;
1202 }
1203 refused_outside = Some(names_a_file);
1204 } else if paths.is_empty() {
1205 return None;
1206 }
1207 }
1208 for path in &paths {
1214 if is_readable_file(path) {
1215 return Some(path.clone());
1216 }
1217 }
1218 let mut refused_hit = false;
1223 for path in &paths {
1224 let p = Path::new(path);
1225 let dir = match p.parent() {
1226 Some(d) if !d.as_os_str().is_empty() => d,
1227 _ => Path::new("."),
1228 };
1229 let target = match p.file_name().and_then(|n| n.to_str()) {
1230 Some(n) => n,
1231 None => continue,
1232 };
1233 if let Some(found) = nocase_dir_cache::lookup(dir, target) {
1234 if read_allowed(&found) {
1235 return Some(found);
1236 }
1237 refused_hit = true;
1238 }
1239 }
1240 if refused_hit || refused_outside.is_some_and(|names_a_file| names_a_file()) {
1242 refuse(pathname);
1243 }
1244 None
1245}
1246
1247pub fn is_readable_file(path: &str) -> bool { std::fs::metadata(path).is_ok_and(|m| !m.is_dir()) }
1249
1250pub fn file_name(pathname: &str) -> String {
1252 let canonical_pathname = canonical(pathname);
1253 let canonical_path = Path::new(&canonical_pathname);
1254 match canonical_path.file_name() {
1255 Some(e) => e.to_string_lossy().to_string(),
1256 None => String::new(),
1257 }
1258}
1259
1260pub fn file_stem(pathname: &str) -> String {
1263 let canonical_pathname = canonical(pathname);
1264 let canonical_path = Path::new(&canonical_pathname);
1265 match canonical_path.file_stem() {
1266 Some(e) => e.to_string_lossy().to_string(),
1267 None => String::new(),
1268 }
1269}
1270
1271pub fn directory(pathname: &str) -> String {
1274 let canonical_pathname = canonical(pathname);
1275 let canonical_path = Path::new(&canonical_pathname);
1276 match canonical_path.parent() {
1277 Some(e) => e.to_string_lossy().to_string(),
1278 None => String::new(),
1279 }
1280}
1281
1282pub fn extension(pathname: &str) -> String {
1286 let canonical_pathname = canonical(pathname);
1287 let canonical_path = Path::new(&canonical_pathname);
1288 match canonical_path.extension() {
1289 Some(e) => e.to_string_lossy().to_string(),
1290 None => String::new(),
1291 }
1292}
1293
1294pub fn make(dir: Option<&str>, name: Option<&str>, ext: Option<&str>) -> String {
1297 let mut result = String::new();
1298 if let Some(d) = dir {
1299 result.push_str(d);
1300 }
1301 if let Some(n) = name {
1302 if !result.is_empty() && !result.ends_with('/') {
1303 result.push('/');
1304 }
1305 result.push_str(n);
1306 }
1307 if let Some(t) = ext
1308 && !t.is_empty()
1309 {
1310 result.push('.');
1311 result.push_str(t);
1312 }
1313 canonical(&result)
1314}
1315
1316fn abs2rel(target: &Path, base: &Path) -> String {
1322 use std::path::Component;
1323 if !target.is_absolute() || !base.is_absolute() {
1324 return target.to_string_lossy().to_string();
1325 }
1326 let t: Vec<Component> = target.components().collect();
1327 let b: Vec<Component> = base.components().collect();
1328 let common = t.iter().zip(b.iter()).take_while(|(a, c)| a == c).count();
1329 if common == 0 {
1330 return target.to_string_lossy().to_string();
1331 }
1332 let mut result = PathBuf::new();
1333 for _ in 0..(b.len() - common) {
1334 result.push("..");
1335 }
1336 for comp in &t[common..] {
1337 result.push(comp.as_os_str());
1338 }
1339 #[cfg(windows)]
1346 {
1347 result.to_string_lossy().replace('\\', "/")
1348 }
1349 #[cfg(not(windows))]
1350 {
1351 result.to_string_lossy().into_owned()
1352 }
1353}
1354
1355pub fn relative(pathname: &str, base: &str) -> String {
1358 let canonical_pathname = canonical(pathname);
1359 if base.is_empty() || !is_absolute(&canonical_pathname) {
1360 return canonical_pathname;
1361 }
1362 let canonical_base = canonical(base);
1363 abs2rel(Path::new(&canonical_pathname), Path::new(&canonical_base))
1370}
1371
1372pub fn is_contained(pathname: &str, base: &str) -> Option<String> {
1376 let rel = canonical(&relative(&absolute(pathname), &absolute(base)));
1377 let outside = rel == ".." || rel.starts_with("../") || Path::new(&rel).is_absolute();
1378 (!outside).then_some(rel)
1379}
1380
1381pub fn resolved(pathname: &str) -> String {
1389 let abs = PathBuf::from(absolute(pathname));
1390 let mut tail: Vec<std::ffi::OsString> = Vec::new();
1391 let mut dir: &Path = &abs;
1392 loop {
1393 if let Ok(real) = canonicalize(dir) {
1394 let joined = tail.iter().rev().fold(real, |path, part| path.join(part));
1395 return canonical(&joined.to_string_lossy());
1396 }
1397 match (dir.parent(), dir.file_name()) {
1398 (Some(parent), Some(name)) => {
1399 tail.push(name.to_os_string());
1400 dir = parent;
1401 },
1402 _ => return canonical(&abs.to_string_lossy()),
1403 }
1404 }
1405}
1406
1407pub fn resolved_directory_of(pathname: &str) -> String {
1410 let abs = PathBuf::from(absolute(pathname));
1411 match (abs.parent(), abs.file_name()) {
1412 (Some(parent), Some(name)) => {
1413 let dir = resolved(&parent.to_string_lossy());
1414 canonical(&Path::new(&dir).join(name).to_string_lossy())
1415 },
1416 _ => resolved(pathname),
1417 }
1418}
1419
1420pub fn is_contained_resolved(pathname: &str, base: &str) -> Option<String> {
1423 is_contained(&resolved_directory_of(pathname), &resolved(base))
1424}
1425
1426pub fn same_file(a: impl AsRef<Path>, b: impl AsRef<Path>) -> bool {
1429 match (canonicalize(a), canonicalize(b)) {
1430 (Ok(ca), Ok(cb)) => ca == cb,
1431 _ => false,
1432 }
1433}
1434
1435pub fn opens_inside(path: impl AsRef<Path>, dir: impl AsRef<Path>) -> Option<bool> {
1439 match (std::fs::canonicalize(path), std::fs::canonicalize(dir)) {
1440 (Ok(p), Ok(d)) => Some(p.starts_with(&d)),
1441 _ => None,
1442 }
1443}
1444
1445pub fn findall(pathname: &str, options: PathnameFindOptions) -> Vec<String> {
1448 candidate_pathnames(pathname, options)
1449}
1450
1451#[cfg(feature = "kpathsea")]
1453std::thread_local! {
1454 static KPSE_MEMO: std::cell::RefCell<rustc_hash::FxHashMap<String, Option<String>>> =
1455 std::cell::RefCell::new(rustc_hash::FxHashMap::default());
1456}
1457
1458#[cfg(feature = "kpathsea")]
1464pub fn clear_kpsewhich_memo() { KPSE_MEMO.with(|m| m.borrow_mut().clear()); }
1465
1466#[cfg(not(feature = "kpathsea"))]
1467pub fn clear_kpsewhich_memo() {}
1468
1469#[cfg(feature = "kpathsea")]
1487pub fn kpsewhich(candidates: &[&str]) -> Option<String> { kpsewhich_in(candidates, false) }
1488
1489#[cfg(feature = "kpathsea")]
1493pub fn kpsewhich_tex_input(candidates: &[&str]) -> Option<String> { kpsewhich_in(candidates, true) }
1494
1495#[cfg(feature = "kpathsea")]
1496fn kpsewhich_in(candidates: &[&str], tex_only: bool) -> Option<String> {
1497 if is_confined() {
1500 return candidates
1501 .iter()
1502 .filter(|name| confinement::kpse_name_ok(name))
1503 .find_map(|name| {
1504 kpsewhich_memo(&[name], tex_only).filter(|found| confinement::kpse_hit_allowed(name, found))
1505 });
1506 }
1507 kpsewhich_memo(candidates, tex_only)
1508}
1509
1510#[cfg(feature = "kpathsea")]
1511fn kpsewhich_memo(candidates: &[&str], tex_only: bool) -> Option<String> {
1512 let key = format!(
1513 "{}{}",
1514 if tex_only { "\x1etex\x1f" } else { "" },
1515 candidates.join("\x1f")
1516 );
1517 if let Some(cached) = KPSE_MEMO.with(|m| m.borrow().get(&key).cloned()) {
1518 return cached;
1519 }
1520 let result = kpsewhich_uncached(candidates, tex_only);
1521 KPSE_MEMO.with(|m| {
1522 let mut m = m.borrow_mut();
1523 if m.len() >= 4096 {
1526 m.clear();
1527 }
1528 m.insert(key, result.clone());
1529 });
1530 result
1531}
1532
1533#[cfg(feature = "kpathsea")]
1537fn find_first_via(kpse: &Kpaths, candidates: &[&str], tex_only: bool) -> Option<String> {
1538 for candidate in candidates {
1539 let basename = candidate.rsplit(['/', '\\']).next().unwrap_or(candidate);
1549 if basename.starts_with('.') && !basename[1..].contains('.') {
1550 continue;
1551 }
1552 if !tex_only {
1553 let result =
1554 std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| kpse.find_file(candidate)));
1555 if let Ok(Some(path)) = result {
1556 return Some(path);
1557 }
1558 }
1559 let retry = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1569 kpse.find_file_with_format(candidate, kpathsea::formats::TEX)
1570 }));
1571 if let Ok(Some(path)) = retry {
1572 return Some(path);
1573 }
1574 }
1575 None
1576}
1577
1578#[cfg(feature = "kpathsea")]
1579fn kpsewhich_uncached(candidates: &[&str], tex_only: bool) -> Option<String> {
1580 KPSE
1581 .lock()
1582 .unwrap()
1583 .as_ref()
1584 .and_then(|kpse| find_first_via(kpse, candidates, tex_only))
1585}
1586
1587#[cfg(not(feature = "kpathsea"))]
1591pub fn kpsewhich(_candidates: &[&str]) -> Option<String> { None }
1592
1593#[cfg(not(feature = "kpathsea"))]
1595pub fn kpsewhich_tex_input(_candidates: &[&str]) -> Option<String> { None }
1596
1597pub fn is_nasty(file: &str) -> bool { PATHNAME_IS_NASTY_RE.is_match(file) }
1599
1600pub fn cwd() -> String { env::current_dir().unwrap().to_string_lossy().to_string() }
1602
1603#[cfg(test)]
1604mod tests {
1605 use super::*;
1606
1607 #[test]
1610 fn every_kpathsea_format_variable_is_a_search_path() {
1611 let Ok(out) = tex_tool_command("kpsewhich").arg("--help-formats").output() else {
1612 eprintln!("SKIP every_kpathsea_format_variable_is_a_search_path: no kpsewhich");
1613 return;
1614 };
1615 let text = String::from_utf8_lossy(&out.stdout);
1616 let vars: Vec<&str> = text
1617 .lines()
1618 .filter_map(|line| line.split_once("[variables:").map(|(_, rest)| rest))
1619 .flat_map(|rest| rest.trim_end_matches(']').split_whitespace())
1620 .filter(|var| *var != "TEXMFCNF")
1621 .collect();
1622 assert!(
1623 vars.len() > 40,
1624 "kpsewhich --help-formats listed {} variables",
1625 vars.len()
1626 );
1627 let missed: Vec<&&str> = vars.iter().filter(|var| !is_kpse_path_var(var)).collect();
1628 assert!(
1629 missed.is_empty(),
1630 "search-path variables the confinement does not check: {missed:?}"
1631 );
1632 for var in [
1633 "TEXMFDOTDIR",
1634 "VARTEXFONTS",
1635 "TEXINPUTS_latex",
1636 "TEXBIB.bibtex",
1637 ] {
1638 assert!(is_kpse_path_var(var), "{var}");
1639 }
1640 for var in [
1641 "TEXMFCNF",
1642 "TEXMFHOME",
1643 "TEXMFROOT",
1644 "TEXMFDIST",
1645 "XDG_CONFIG_HOME",
1646 "PATH",
1647 ] {
1648 assert!(!is_kpse_path_var(var), "{var}");
1649 }
1650 }
1651
1652 #[test]
1656 fn confinement_follows_its_guard() {
1657 let tmp = env::temp_dir().to_string_lossy().into_owned();
1658 let (a, b) = (
1659 format!("{tmp}/confine_a_{}", std::process::id()),
1660 format!("{tmp}/confine_b_{}", std::process::id()),
1661 );
1662 let in_a = format!("{a}/x.tex");
1663 let in_b = format!("{b}/missing/y.tex");
1664 assert!(!is_confined() && read_allowed(&in_a));
1665 {
1666 let _first = confine(InputConfinement {
1667 source: Some(a.clone()),
1668 ..InputConfinement::default()
1669 });
1670 assert!(is_confined() && read_allowed(&in_a) && !read_allowed(&in_b));
1671 assert!(!read_allowed(&format!("{a}/../escape.tex")));
1672 }
1673 assert!(!is_confined());
1674 let _second = confine(InputConfinement {
1675 source: Some(b.clone()),
1676 ..InputConfinement::default()
1677 });
1678 assert!(!read_allowed(&in_a) && read_allowed(&in_b));
1679 assert!(own_behalf(|| read_allowed(&in_a)));
1680 }
1681
1682 #[test]
1686 fn confinement_judges_a_name_by_where_it_lies() {
1687 let a = format!(
1688 "{}/confine_c_{}",
1689 env::temp_dir().to_string_lossy(),
1690 std::process::id()
1691 );
1692 let _confined = confine(InputConfinement {
1693 source: Some(a.clone()),
1694 ..InputConfinement::default()
1695 });
1696 for name in [
1697 "a>b/x.png",
1698 "q;\"$ x/y.png",
1699 "b`c|d<e/x.png",
1700 "|x.pdf",
1701 "-o.pdf",
1702 ] {
1703 assert!(read_allowed(&format!("{a}/{name}")), "{name}");
1704 assert!(!read_allowed(&format!("{a}/../{name}")), "../{name}");
1705 }
1706 for name in ["a\nb.png", "a\rb.png", "a\0b.png"] {
1707 assert!(!read_allowed(&format!("{a}/{name}")), "{name:?}");
1708 }
1709 assert!(!read_allowed(""));
1710 for name in [
1712 "-var-value=HOME",
1713 "-expand-braces={/etc,x}",
1714 "$HOME/x.sty",
1715 "~/x.sty",
1716 ] {
1717 assert!(!confinement::kpse_name_ok(name), "{name}");
1718 }
1719 assert!(confinement::kpse_name_ok("x.sty"));
1720 }
1721
1722 #[cfg(not(feature = "kpathsea"))]
1724 #[test]
1725 fn trim_texmf_root_without_the_kpathsea_feature() {
1726 assert_eq!(trim_texmf_root("/tl/2024//").as_deref(), Some("/tl/2024"));
1727 assert_eq!(
1728 trim_texmf_root("!!/tl/2024/").as_deref(),
1729 Some("!!/tl/2024")
1730 );
1731 assert_eq!(trim_texmf_root("/tl//2024"), None);
1732 assert_eq!(trim_texmf_root("/"), None);
1733 assert_eq!(trim_texmf_root("{/a/,/b/}"), None);
1734 }
1735
1736 #[cfg(feature = "kpathsea")]
1739 #[test]
1740 fn path_is_under_compares_as_the_file_system_does() {
1741 let file = "c:/texlive/2026/texmf-dist/tex/latex/base/latex.ltx";
1742 assert!(path_is_under(file, "c:/texlive/2026"));
1743 assert!(path_is_under(file, "c:/texlive/2026/"));
1744 assert!(
1745 !path_is_under(file, "c:/texlive/202"),
1746 "a name prefix is not a directory"
1747 );
1748 assert!(!path_is_under(file, "c:/texlive/2025"));
1749 assert_eq!(path_is_under(file, "C:/texlive/2026"), cfg!(windows));
1750 assert_eq!(path_is_under(file, r"C:\texlive\2026"), cfg!(windows));
1751 }
1752
1753 #[test]
1762 fn is_contained_is_underneath_only() {
1763 let abs = |p: &str| {
1764 if cfg!(windows) {
1765 format!("C:{p}")
1766 } else {
1767 p.to_string()
1768 }
1769 };
1770 assert_eq!(
1771 is_contained(&abs("/s/out/x/../img.svg"), &abs("/s")).as_deref(),
1772 Some("out/img.svg")
1773 );
1774 assert!(is_contained(&abs("/s"), &abs("/s")).is_some());
1775 assert_eq!(is_contained(&abs("/s/../c/A.svg"), &abs("/s")), None);
1776 assert_eq!(is_contained(&abs("/p"), &abs("/p/sub")), None);
1777 }
1778
1779 #[cfg(unix)]
1783 #[test]
1784 fn resolved_relates_two_spellings_of_one_directory() {
1785 let root = env::temp_dir().join(format!("lx-resolved-{}", std::process::id()));
1786 let _ = std::fs::remove_dir_all(&root);
1787 std::fs::create_dir_all(&root).unwrap();
1788 let real = canonicalize(&root).unwrap().join("real");
1789 std::fs::create_dir_all(real.join("src/figs")).unwrap();
1790 std::fs::write(real.join("src/figs/a.png"), b"x").unwrap();
1791 let link = real.parent().unwrap().join("link");
1792 std::os::unix::fs::symlink(&real, &link).unwrap();
1793 let (real_src, link_src) = (real.join("src"), link.join("src"));
1794 let (real_img, link_img) = (real.join("src/figs/a.png"), link.join("src/figs/a.png"));
1795 let s = |p: &Path| p.to_string_lossy().into_owned();
1796 assert_eq!(is_contained(&s(&real_img), &s(&link_src)), None);
1798 assert_eq!(
1799 is_contained_resolved(&s(&real_img), &s(&link_src)).as_deref(),
1800 Some("figs/a.png")
1801 );
1802 assert_eq!(
1803 is_contained_resolved(&s(&link_img), &s(&real_src)).as_deref(),
1804 Some("figs/a.png")
1805 );
1806 let out = link_src.join("out");
1809 assert_eq!(
1810 is_contained_resolved(&s(&out.join("figs/b.png")), &s(&out)).as_deref(),
1811 Some("figs/b.png")
1812 );
1813 assert_eq!(resolved(&s(&out)), canonical(&s(&real_src.join("out"))));
1814 let img_link = real.join("src/img.png");
1816 std::os::unix::fs::symlink(real.join("src/figs/a.png"), &img_link).unwrap();
1817 assert_eq!(
1818 is_contained_resolved(&s(&img_link), &s(&link_src)).as_deref(),
1819 Some("img.png")
1820 );
1821 let away = real.join("away");
1822 std::fs::create_dir_all(&away).unwrap();
1823 std::os::unix::fs::symlink(&away, real.join("src/gone")).unwrap();
1824 assert_eq!(
1825 is_contained_resolved(&s(&link_src.join("gone/c.png")), &s(&link_src)),
1826 None
1827 );
1828 assert_eq!(resolved(&s(&real_img)), canonical(&s(&real_img)));
1830 assert!(same_file(&link_img, &real_img));
1831 assert!(!same_file(&link_img, real.join("src/figs/missing.png")));
1832 let _ = std::fs::remove_dir_all(&root);
1833 }
1834
1835 #[test]
1836 fn relative_emits_dotdot_for_non_descendant() {
1837 let abs = |p: &str| {
1840 if cfg!(windows) {
1841 format!("C:{p}")
1842 } else {
1843 p.to_string()
1844 }
1845 };
1846 assert_eq!(
1848 relative(
1849 &abs("/home/u/proj/A/child/images/pic.svg"),
1850 &abs("/home/u/proj/latexml")
1851 ),
1852 "../A/child/images/pic.svg"
1853 );
1854 assert_eq!(
1856 relative(&abs("/home/u/proj/sub/pic.png"), &abs("/home/u/proj")),
1857 "sub/pic.png"
1858 );
1859 assert_eq!(
1861 relative(&abs("/a/b/c/f.tex"), &abs("/a/x/y")),
1862 "../../b/c/f.tex"
1863 );
1864 assert_eq!(relative("sub/pic.png", &abs("/home/u/proj")), "sub/pic.png");
1866 assert_eq!(relative(&abs("/a/b/pic.png"), ""), abs("/a/b/pic.png"));
1868 }
1869
1870 #[cfg(feature = "kpathsea")]
1873 mod backend_selection {
1874 use super::*;
1875
1876 fn subprocess() -> Option<Kpaths> { Kpaths::new_subprocess().ok() }
1878
1879 #[test]
1880 fn no_constructible_backend_reports_unavailable() {
1881 let (kpse, backend, why) = choose_kpaths(
1882 None,
1883 || Err("no lib"),
1884 || Err("no kpsewhich"),
1885 |_| true,
1886 |_| true,
1887 );
1888 assert!(kpse.is_none());
1889 assert_eq!(backend, KpathseaBackend::Unavailable);
1890 assert!(
1891 !why.is_empty(),
1892 "an unavailable backend must explain itself"
1893 );
1894 }
1895
1896 #[test]
1900 fn failed_in_process_construction_falls_back_to_subprocess() {
1901 if subprocess().is_none() {
1902 return; }
1904 let (kpse, backend, _) = choose_kpaths(
1905 None,
1906 || Err("libkpathsea did not initialize"),
1907 Kpaths::new_subprocess,
1908 |_| true,
1909 |_| true,
1910 );
1911 assert!(kpse.is_some(), "must not give up while a kpsewhich exists");
1912 assert_eq!(backend, KpathseaBackend::Subprocess);
1913 }
1914
1915 #[test]
1916 fn miktex_banner_selects_subprocess_without_constructing_in_process() {
1917 if subprocess().is_none() {
1918 return;
1919 }
1920 let (kpse, backend, _) = choose_kpaths(
1921 Some("MiKTeX 24.1"),
1922 || panic!("the in-process backend must not be constructed on a MiKTeX host"),
1923 Kpaths::new_subprocess,
1924 |_| true,
1925 |_| true,
1926 );
1927 assert!(kpse.is_some());
1928 assert_eq!(backend, KpathseaBackend::Subprocess);
1929 }
1930
1931 #[test]
1934 fn sentinel_miss_falls_back_to_subprocess() {
1935 let Some(primary) = subprocess() else { return };
1936 if primary.is_in_process() {
1937 return; }
1939 let (kpse, backend, _) = choose_kpaths(
1940 None,
1941 Kpaths::new,
1942 Kpaths::new_subprocess,
1943 |_| false,
1944 |_| true,
1945 );
1946 assert!(kpse.is_some());
1947 assert_eq!(backend, KpathseaBackend::Subprocess);
1948 }
1949
1950 #[test]
1955 fn ambient_tree_mismatch_falls_back_to_subprocess() {
1956 let Some(primary) = subprocess() else { return };
1957 if primary.is_in_process() {
1958 return; }
1960 let (kpse, backend, why) = choose_kpaths(
1961 None,
1962 Kpaths::new,
1963 Kpaths::new_subprocess,
1964 |_| true,
1965 |_| false,
1966 );
1967 assert!(kpse.is_some());
1968 assert_eq!(backend, KpathseaBackend::Subprocess);
1969 assert!(why.contains("different TeX tree"), "why = {why}");
1970 }
1971 }
1972
1973 #[cfg(feature = "kpathsea")]
1975 #[test]
1976 fn absent_names_resolve_to_none() {
1977 assert!(kpsewhich(&["lxo_definitely_absent_probe_304.tex"]).is_none());
1978 }
1979
1980 #[cfg(feature = "kpathsea")]
1988 #[test]
1989 fn selected_backend_resolves_host_files() {
1990 let cmr = kpsewhich(&["cmr10.tfm"]);
1991 if cmr.is_none() && kpsewhich(&["article.cls"]).is_none() {
1992 return; }
1994 let in_process = KPSE
1995 .lock()
1996 .unwrap()
1997 .as_ref()
1998 .map(|k| k.is_in_process())
1999 .unwrap_or(false);
2000 assert!(
2001 cmr.is_some(),
2002 "selected kpathsea backend failed to resolve the universal cmr10.tfm \
2003 (in_process={in_process}); a MiKTeX host must fall back to subprocess"
2004 );
2005 }
2006
2007 fn pathsearch_tmproot(tag: &str) -> PathBuf {
2008 let mut d = env::temp_dir();
2009 d.push(format!("lxo_pathsearch_{}_{}", std::process::id(), tag));
2010 let _ = std::fs::remove_dir_all(&d);
2011 std::fs::create_dir_all(&d).unwrap();
2012 d
2013 }
2014
2015 #[test]
2018 fn recursive_double_slash_descends_into_subdirs() {
2019 let root = pathsearch_tmproot("rec");
2020 let deep = root.join("a").join("b");
2021 std::fs::create_dir_all(&deep).unwrap();
2022 std::fs::write(deep.join("target.tex"), "x").unwrap();
2023 let root_s = root.to_str().unwrap().replace('\\', "/");
2024
2025 let found = find("target.tex", PathnameFindOptions {
2026 paths: Some(vec![format!("{root_s}//")]),
2027 ..Default::default()
2028 });
2029 assert!(
2030 found.as_deref().is_some_and(|p| p.ends_with("target.tex")),
2031 "recursive `//` should find the nested target.tex, got {found:?}"
2032 );
2033
2034 let flat = find("target.tex", PathnameFindOptions {
2035 paths: Some(vec![root_s]),
2036 ..Default::default()
2037 });
2038 assert!(
2039 flat.is_none(),
2040 "a plain (non-`//`) path must NOT descend into subdirectories, got {flat:?}"
2041 );
2042 let _ = std::fs::remove_dir_all(&root);
2043 }
2044
2045 #[test]
2048 fn plain_path_finds_file_in_that_dir() {
2049 let root = pathsearch_tmproot("flat");
2050 std::fs::write(root.join("here.tex"), "x").unwrap();
2051 let root_s = root.to_str().unwrap().replace('\\', "/");
2052 let found = find("here.tex", PathnameFindOptions {
2053 paths: Some(vec![root_s]),
2054 ..Default::default()
2055 });
2056 assert!(
2057 found.as_deref().is_some_and(|p| p.ends_with("here.tex")),
2058 "plain path should find a file directly in it, got {found:?}"
2059 );
2060 let _ = std::fs::remove_dir_all(&root);
2061 }
2062
2063 #[test]
2064 fn is_url_schemes() {
2065 assert!(is_url("http://example.com/path"));
2068 assert!(is_url("http://example.com/path/file.tex"));
2069 assert!(is_url("ftp://host/file"));
2070 assert!(is_url("https://example.com")); assert!(!is_url("plain/path/file.tex"));
2072 assert!(!is_url("/absolute/path"));
2073 assert!(!is_url(
2078 "myers_http://www.mscs.dal.ca/myers/welcome.html_2014"
2079 ));
2080 assert!(!is_url("foo_ftp://bar/baz"));
2081 }
2082
2083 #[test]
2084 fn is_literaldata_prefix() {
2085 assert!(is_literaldata("literal:foo"));
2086 assert!(!is_literaldata("file:foo"));
2087 assert!(!is_literaldata("plain"));
2088 }
2089
2090 #[test]
2091 fn is_raw_tex_extensions() {
2092 assert!(is_raw("main.tex"));
2093 assert!(is_raw("hyphen.cfg"));
2094 assert!(is_raw("T1enc.def"));
2095 assert!(is_raw("article.cls"));
2096 assert!(is_raw("french.ldf"));
2097 assert!(!is_raw("foo.pdf"));
2098 assert!(!is_raw("bar.png"));
2099 assert!(!is_raw("baz"));
2100 }
2101
2102 #[test]
2103 fn is_reloadable_only_ldf() {
2104 assert!(is_reloadable("french.ldf"));
2105 assert!(!is_reloadable("main.tex"));
2106 assert!(!is_reloadable("foo.sty"));
2107 assert!(!is_reloadable("baz"));
2108 }
2109
2110 #[test]
2111 fn extension_basic() {
2112 assert_eq!(extension("foo.tex"), "tex");
2113 assert_eq!(extension("path/to/main.cls"), "cls");
2114 assert_eq!(extension("no_ext"), "");
2115 assert_eq!(extension("double.dot.ext"), "ext");
2116 }
2117
2118 #[test]
2119 fn file_name_strips_dirs() {
2120 assert_eq!(file_name("path/to/foo.tex"), "foo.tex");
2121 assert_eq!(file_name("foo.tex"), "foo.tex");
2122 assert_eq!(file_name("/abs/path/foo.tex"), "foo.tex");
2123 }
2124
2125 #[test]
2126 fn file_stem_strips_ext() {
2127 assert_eq!(file_stem("foo.tex"), "foo");
2128 assert_eq!(file_stem("path/to/foo.cls"), "foo");
2129 assert_eq!(file_stem("no_ext"), "no_ext");
2130 }
2131
2132 #[test]
2133 fn directory_returns_dir() {
2134 assert_eq!(directory("path/to/foo.tex"), "path/to");
2135 assert!(
2136 directory("foo.tex").is_empty() || directory("foo.tex") == ".",
2137 "relative-only filename: dir is empty or '.'"
2138 );
2139 }
2140
2141 #[test]
2142 fn make_reassembles_components() {
2143 let p = make(Some("path"), Some("foo"), Some("tex"));
2144 assert_eq!(p, "path/foo.tex");
2145 }
2146
2147 #[test]
2148 fn make_none_dir() {
2149 let p = make(None, Some("foo"), Some("tex"));
2150 assert_eq!(p, "foo.tex");
2152 }
2153
2154 #[test]
2155 fn concat_joins_with_slash() {
2156 assert_eq!(concat("path", "foo.tex"), "path/foo.tex");
2157 assert_eq!(concat("a/b", "c.tex"), "a/b/c.tex");
2158 }
2159
2160 #[test]
2163 fn canonical_drops_only_a_real_directory_before_dotdot() {
2164 for (written, expected) in [
2165 ("./../../x", "../../x"),
2166 ("./sub/../../../x", "../../x"),
2167 ("./..", ".."),
2168 ("../a/b/../c", "../a/c"),
2169 ("/a/./b/../c", "/a/c"),
2170 ("/a/..", "/"),
2171 (".//x", "x"),
2173 ("././/etc/x", "etc/x"),
2174 ("./././/x", "x"),
2175 ("x/..//etc/x", "etc/x"),
2176 ("./x/..//etc/x", "etc/x"),
2177 (".//../x", "../x"),
2178 (".//", "./"),
2179 ("/t/doc//../x", "/t/doc//../x"),
2181 ] {
2182 assert_eq!(canonical(written), expected, "{written}");
2183 }
2184 for (written, expected) in [
2185 (".//x", "x"),
2186 ("././/x", "x"),
2187 (".//./x", "x"),
2188 ("./x", "./x"),
2189 ("././x", "././x"),
2190 (".//", ".//"),
2191 ] {
2192 assert_eq!(dot_relative(written), expected, "{written}");
2193 }
2194 }
2195
2196 #[test]
2197 fn url_split_basic() {
2198 let (base, file) = url_split("http://example.com/path/file.tex");
2200 assert_eq!(base, "example.com/path");
2201 assert_eq!(file, "file.tex");
2202 }
2203
2204 #[test]
2205 fn url_split_non_url_gets_index() {
2206 let (proto, rest) = url_split("plain_string");
2208 assert_eq!(proto, "plain_string");
2209 assert_eq!(rest, "index.tex");
2210 }
2211
2212 #[test]
2213 fn split_basic_path() {
2214 let (d, n, e) = split("path/to/foo.tex");
2215 assert_eq!(d, "path/to");
2216 assert_eq!(n, "foo");
2217 assert_eq!(e, "tex");
2218 }
2219
2220 #[test]
2221 fn split_no_ext() {
2222 let (_d, n, e) = split("foo");
2223 assert_eq!(n, "foo");
2224 assert_eq!(e, "");
2225 }
2226
2227 #[test]
2228 fn is_nasty_detects_bad_patterns() {
2229 let has_dotdot = is_nasty("path/../bad");
2232 let safe = is_nasty("foo.tex");
2233 assert!(!safe, "plain filename should not be nasty");
2236 let _ = has_dotdot;
2239 }
2240
2241 #[test]
2242 fn nocase_dir_cache_finds_case_mismatch_and_skips_dirs() {
2243 let root = pathsearch_tmproot("nocase_cache");
2244 std::fs::write(root.join("PASJ95.STY"), "% sty").unwrap();
2245 std::fs::create_dir(root.join("INTRO")).unwrap();
2246 let root_s = root.to_str().unwrap().replace('\\', "/");
2247
2248 let found1 = nocase_dir_cache::lookup(&root, "pasj95.sty");
2252 let found2 = nocase_dir_cache::lookup(&root, "pasj95.sty");
2253 assert!(
2254 found1.as_deref().is_some_and(|p| p.ends_with("PASJ95.STY")),
2255 "expected PASJ95.STY, got {found1:?}"
2256 );
2257 assert_eq!(found2, found1);
2258
2259 assert_eq!(nocase_dir_cache::lookup(&root, "intro"), None);
2261
2262 assert_eq!(nocase_dir_cache::lookup(&root, "later.sty"), None);
2265 std::fs::write(root.join("LATER.STY"), "% later").unwrap();
2266 clear_nocase_dir_cache();
2267 let later = nocase_dir_cache::lookup(&root, "later.sty");
2268 assert!(
2269 later.as_deref().is_some_and(|p| p.ends_with("LATER.STY")),
2270 "expected LATER.STY after cache clear, got {later:?}"
2271 );
2272
2273 #[cfg(unix)]
2277 {
2278 assert_eq!(nocase_dir_cache::lookup(&root, "after_nlink.sty"), None);
2279 std::fs::write(root.join("AFTER_NLINK.STY"), "% nlink").unwrap();
2280 std::fs::create_dir(root.join("BUMP_NLINK")).unwrap();
2281 let after = nocase_dir_cache::lookup(&root, "after_nlink.sty");
2282 assert!(
2283 after
2284 .as_deref()
2285 .is_some_and(|p| p.ends_with("AFTER_NLINK.STY")),
2286 "expected AFTER_NLINK.STY after dir stamp change, got {after:?}"
2287 );
2288 }
2289
2290 let opts = || PathnameFindOptions {
2294 paths: Some(vec![root_s.clone()]),
2295 ..Default::default()
2296 };
2297 clear_nocase_dir_cache();
2298 let case_sensitive = !is_readable_file(&format!("{root_s}/pasj95.sty"));
2299 let via_find = find("pasj95.sty", opts());
2300 let expected_suffix = if case_sensitive {
2301 "PASJ95.STY"
2302 } else {
2303 "pasj95.sty"
2304 };
2305 assert!(
2306 via_find
2307 .as_deref()
2308 .is_some_and(|p| p.ends_with(expected_suffix)),
2309 "expected {expected_suffix}, got {via_find:?}"
2310 );
2311 assert_eq!(find("pasj95.sty", opts()), via_find);
2312 assert_eq!(find("intro", opts()), None);
2313
2314 let _ = std::fs::remove_dir_all(&root);
2315 }
2316}