use sha2::{Digest, Sha256}; use std::{ collections::{BTreeMap, BTreeSet}, fs, io::{self, Read, Write}, path::{Path, PathBuf}, process::{Command, Stdio}, sync::{ Arc, atomic::{AtomicU64, Ordering}, }, thread, time::{Duration, Instant}, }; use texrra_engine::native::{CompileRequest, GeneratedArtifacts, ProjectSnapshot}; use texrra_tex_core::resources::ResourceVersion; const MAX_AUX_BYTES: u64 = 2 * 1024 * 1024; const MAX_INPUT_BYTES: u64 = 32 * 1024 * 1024; const MAX_BBL_BYTES: u64 = 4 * 1024 * 1024; const JOB: &str = "texrra-bibliography"; pub(super) fn from_seed( request: &CompileRequest, artifacts: &GeneratedArtifacts, files: &BTreeMap>, ) -> Result)>, String> { let cwd = &request.world.cwd; let Some(name) = request.input.file_stem() else { return Ok(None); }; let mut jobname = name.to_os_string(); jobname.push(".bbl"); let bbl = cwd.join(jobname); if files.contains_key(&bbl) { return Ok(None); } let mut jobname = name.to_os_string(); jobname.push(".aux"); let aux = cwd.join(jobname); let versions = artifacts .writes .iter() .filter_map(|write| { write .after .as_ref() .filter(|version| version.path == write.path) .map(|version| (write.path.as_path(), version)) }) .collect::>(); if !versions.contains_key(aux.as_path()) { return Ok(None); } let mut input = AuxRecords::default(); input.read(cwd, &aux, &versions, 0)?; if input.databases.is_empty() || !input.has_citation { return Ok(None); } if let Some(issue) = input.include_issue { return Err(issue); } let staged_style = input.style.ok_or("BibTeX requires a bibliography style")?; let style = project_style(cwd, &staged_style, files)?; let mut plan = Plan { cwd: cwd.clone(), output: bbl, records: input.records, databases: input .databases .into_iter() .map(|path| cwd.join(path)) .collect(), style, staged_style, system_style: None, }; let scratch = Scratch::new(cwd).map_err(bib_error)?; if !files.contains_key(&plan.style) { plan.system_style = Some(find_style( &scratch.0, &plan.staged_style, &request.world.texmf_roots, )?); } let data = plan.run(&scratch.0, |path| files.get(path).map(Arc::as_ref))?; Ok(Some((plan, data))) } pub(super) struct Plan { cwd: PathBuf, output: PathBuf, records: Vec, databases: Vec, style: PathBuf, staged_style: PathBuf, system_style: Option>, } impl Plan { pub(super) fn output(&self) -> &Path { &self.output } pub(super) fn update( &self, project: &ProjectSnapshot, edits: &BTreeMap>>, ) -> Result>, String> { if !self .databases .iter() .chain(std::iter::once(&self.style)) .any(|path| { edits.get(path).is_some_and(|new| { new.as_deref() != project.file(path).map(|file| file.data.as_ref()) }) }) { return Ok(None); } let scratch = Scratch::new(&self.cwd).map_err(bib_error)?; self.run(&scratch.0, |path| { edits.get(path).map_or_else( || project.file(path).map(|file| file.data.as_ref()), Option::as_deref, ) }) .map(Some) } fn run<'a>( &self, scratch: &Path, mut contents: impl FnMut(&Path) -> Option<&'a [u8]>, ) -> Result, String> { let mut total = 0; // Stage only named databases and a single style from trusted inputs. for path in self.databases.iter().chain(std::iter::once(&self.style)) { let relative = if path == &self.style { &self.staged_style } else { path.strip_prefix(&self.cwd) .expect("checked bibliography path") }; let data = contents(path) .or_else(|| { (path == &self.style) .then_some(self.system_style.as_deref()) .flatten() }) .ok_or_else(|| { format!("BibTeX input missing from project: {}", relative.display()) })?; total += data.len() as u64; if total > MAX_INPUT_BYTES { return Err("BibTeX inputs exceed the size limit".into()); } stage(scratch, relative, data).map_err(bib_error)?; } fs::write(scratch.join(format!("{JOB}.aux")), &self.records).map_err(bib_error)?; run_bibtex(scratch).map(Into::into) } } #[derive(Default)] struct AuxRecords { records: Vec, databases: Vec, style: Option, has_citation: bool, visited: BTreeSet, total: u64, include_issue: Option, } impl AuxRecords { fn read( &mut self, cwd: &Path, aux: &Path, versions: &BTreeMap<&Path, &ResourceVersion>, depth: usize, ) -> Result<(), String> { if depth > 16 || !self.visited.insert(aux.to_owned()) { return Err("BibTeX auxiliary files are nested too deeply or repeated".into()); } let version = versions .get(aux) .ok_or("BibTeX auxiliary file was not produced by this job")?; let data = read_limited(aux, MAX_AUX_BYTES).map_err(bib_error)?; self.total += data.len() as u64; if self.total > MAX_AUX_BYTES { return Err("BibTeX auxiliary files exceed the size limit".into()); } if data.len() as u64 != version.bytes || format!("{:x}", Sha256::digest(&data)) != version.sha256 { return Err("BibTeX auxiliary file changed after compilation".into()); } for line in data.split(|&byte| byte == b'\n') { let line = line.trim_ascii(); if line.starts_with(br"\@input{") { let included = field(line, br"\@input{") .and_then(|file| relative_name(file.expect("matched auxiliary input"), ".aux")); if let Err(error) = included.and_then(|file| self.read(cwd, &cwd.join(file), versions, depth + 1)) { self.include_issue.get_or_insert(error); } continue; } if let Some(value) = field(line, br"\bibdata{")? { if !self.databases.is_empty() { return Err("BibTeX bibliography databases were specified twice".into()); } self.databases = value .split(|&byte| byte == b',') .map(|name| relative_name(name, ".bib")) .collect::>()?; } else if let Some(value) = field(line, br"\bibstyle{")? { if self.style.replace(relative_name(value, ".bst")?).is_some() { return Err("BibTeX bibliography style was specified twice".into()); } } else if field(line, br"\citation{")?.is_some() { self.has_citation = true; } else { continue; } self.records.extend_from_slice(line); self.records.push(b'\n'); } Ok(()) } } fn field<'a>(line: &'a [u8], prefix: &[u8]) -> Result, String> { let Some(rest) = line.strip_prefix(prefix) else { return Ok(None); }; let value = rest .strip_suffix(b"}") .ok_or("Malformed BibTeX auxiliary record")?; if value .iter() .any(|byte| byte.is_ascii_control() || matches!(byte, b'{' | b'}' | b'\\')) { return Err("Malformed BibTeX auxiliary record".into()); } Ok(Some(value)) } fn relative_name(value: &[u8], extension: &str) -> Result { let name = std::str::from_utf8(value.trim_ascii()).map_err(|_| "BibTeX filenames must be UTF-8")?; if name.is_empty() || name.len() > 240 || name.split('/').any(|part| { !part .as_bytes() .first() .is_some_and(u8::is_ascii_alphanumeric) || !part .bytes() .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-')) || part.ends_with('.') }) { return Err(format!("Unsafe BibTeX filename: {name}")); } if name.ends_with(extension) { Ok(name.into()) } else { Ok(format!("{name}{extension}").into()) } } fn read_limited(path: &Path, limit: u64) -> io::Result> { let mut bytes = Vec::new(); fs::File::open(path)? .take(limit + 1) .read_to_end(&mut bytes)?; if bytes.len() as u64 > limit { return Err(io::Error::other("file exceeds the BibTeX size limit")); } Ok(bytes) } fn stage(root: &Path, relative: &Path, data: &[u8]) -> io::Result<()> { let path = root.join(relative); fs::create_dir_all(path.parent().expect("staged files have a parent"))?; let mut file = fs::OpenOptions::new() .write(true) .create_new(true) .open(path)?; file.write_all(data) } fn bib_error(error: io::Error) -> String { format!("BibTeX: {error}") } fn private_environment<'a>(command: &'a mut Command, scratch: &Path) -> &'a mut Command { command .current_dir(scratch) .env_clear() .env("PATH", std::env::var_os("PATH").unwrap_or_default()) .env("HOME", scratch) .env("TEXMFHOME", scratch) .env("TEXMFVAR", scratch) .env("TEXMFCONFIG", scratch) .env("openin_any", "p") .env("openout_any", "p") .env("shell_escape", "f") .stdin(Stdio::null()) } fn project_style( cwd: &Path, style: &Path, files: &BTreeMap>, ) -> Result { let direct = cwd.join(style); if files.contains_key(&direct) || style.components().count() != 1 { return Ok(direct); } let mut matches = files .keys() .filter(|path| path.starts_with(cwd) && path.file_name() == style.file_name()); let found = matches.next().cloned().unwrap_or(direct); if matches.next().is_some() { return Err(format!( "BibTeX style has more than one project match: {}", style.display() )); } Ok(found) } fn find_style(scratch: &Path, style: &Path, roots: &[PathBuf]) -> Result, String> { if style.components().count() != 1 { return Err(format!( "BibTeX style missing from project: {}", style.display() )); } let result = private_environment(&mut Command::new("kpsewhich"), scratch) .arg("--format=bst") .arg(style) .output() .map_err(bib_error)?; if !result.status.success() { return Err(format!("BibTeX style missing: {}", style.display())); } let found = std::str::from_utf8(&result.stdout) .map_err(|_| "BibTeX style path is not UTF-8")? .trim_ascii(); let path = Path::new(found); if !path.is_absolute() { return Err("BibTeX style is outside the configured TeX resources".into()); } let path = path.canonicalize().map_err(bib_error)?; if !roots .iter() .filter_map(|root| root.canonicalize().ok()) .any(|root| path.starts_with(root)) { return Err("BibTeX style is outside the configured TeX resources".into()); } read_limited(&path, MAX_INPUT_BYTES) .map(Into::into) .map_err(bib_error) } fn run_bibtex(scratch: &Path) -> Result, String> { #[cfg(target_os = "linux")] let mut command = { // Bound project-provided .bst programs on our Linux backend. let mut command = Command::new("prlimit"); command.args([ "--fsize=4194304", "--cpu=4", "--as=134217728", "--", "bibtex", ]); command }; #[cfg(not(target_os = "linux"))] let mut command = Command::new("bibtex"); let mut child = private_environment(&mut command, scratch) .env("BIBINPUTS", ".") .env("BSTINPUTS", ".") .arg(JOB) .stdout(Stdio::null()) .stderr(Stdio::null()) .spawn() .map_err(bib_error)?; let deadline = Instant::now() + Duration::from_secs(5); loop { match child.try_wait() { Ok(Some(status)) if status.success() || status.code() == Some(1) => { return read_limited(&scratch.join(format!("{JOB}.bbl")), MAX_BBL_BYTES) .map_err(bib_error); } Ok(Some(status)) => return Err(format!("BibTeX failed ({status})")), Ok(None) if Instant::now() < deadline => thread::sleep(Duration::from_millis(10)), result => { let _ = child.kill(); let _ = child.wait(); return Err(result .err() .map_or_else(|| "BibTeX exceeded the time limit".into(), bib_error)); } } } } struct Scratch(PathBuf); impl Scratch { fn new(cwd: &Path) -> io::Result { static NEXT: AtomicU64 = AtomicU64::new(0); let mut builder = fs::DirBuilder::new(); #[cfg(unix)] { use std::os::unix::fs::DirBuilderExt; builder.mode(0o700); } loop { let index = NEXT.fetch_add(1, Ordering::Relaxed); let path = cwd.join(format!( ".texrra-bibliography-{}-{index}", std::process::id() )); match builder.create(&path) { Ok(()) => return Ok(Self(path)), Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue, Err(error) => return Err(error), } } } } impl Drop for Scratch { fn drop(&mut self) { let _ = fs::remove_dir_all(&self.0); } } #[cfg(test)] mod tests { use super::*; #[test] fn bibliography_names_stay_inside_scratch_paths() { assert_eq!( relative_name(b"bib/references.v1", ".bib").unwrap(), Path::new("bib/references.v1.bib") ); for name in [ &b"../credentials"[..], b"/home/private", b"C:\\private", b"folder/../private", b"folder//private", b"-option", b"file\0", ] { assert!(relative_name(name, ".bib").is_err()); } assert!(field(br"\bibdata{ok}\@input{../private}", br"\bibdata{").is_err()); assert!(field(br"\citation{ok}", br"\citation{").unwrap().is_some()); } }