use std::path::{Path, PathBuf}; pub(super) fn converted_relative_path(relative: &Path, bytes: &[u8]) -> Option { let extension = relative.extension()?.to_str()?; if !extension.eq_ignore_ascii_case("eps") || !(bytes.starts_with(b"%!PS") || bytes.starts_with(&[0xc5, 0xd0, 0xd3, 0xc6])) { return None; } let mut filename = relative.file_stem()?.to_os_string(); filename.push("-eps-converted-to.pdf"); Some(relative.with_file_name(filename)) } #[cfg(not(target_os = "linux"))] pub(super) struct Preparation; #[cfg(not(target_os = "linux"))] impl Preparation { pub(super) fn new(_run: &Path) -> Self { Self } pub(super) fn convert(&self, _source: &[u8]) -> std::io::Result>> { Ok(None) } } #[cfg(target_os = "linux")] pub(super) use linux::Preparation; #[cfg(target_os = "linux")] mod linux { use sha2::{Digest, Sha256}; use std::{ cell::OnceCell, env, fs, io::{self, Read, Write}, os::unix::{ ffi::OsStrExt, fs::{DirBuilderExt, MetadataExt, OpenOptionsExt}, process::CommandExt, }, path::{Path, PathBuf}, process::{Command, Stdio}, sync::atomic::{AtomicU64, Ordering}, thread, time::{Duration, Instant}, }; const MAX_PDF_BYTES: u64 = 64 * 1024 * 1024; const MAX_ADDRESS_SPACE: libc::rlim_t = 768 * 1024 * 1024; const MAX_CPU_SECONDS: libc::rlim_t = 5; const TIME_LIMIT: Duration = Duration::from_secs(8); static NEXT_SCRATCH: AtomicU64 = AtomicU64::new(0); struct Scratch(PathBuf); impl Scratch { fn new(run: &Path) -> io::Result { loop { let serial = NEXT_SCRATCH.fetch_add(1, Ordering::Relaxed); let path = run.join(format!(".texrra-eps-{}-{serial}", std::process::id())); match fs::DirBuilder::new().mode(0o700).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); } } const CACHE_LIMIT: usize = 2 * 1024 * 1024; const CACHE_SLOTS: u8 = 32; const NODE_LIMIT: usize = 16_384; struct CacheIdentity { directory: PathBuf, fingerprint: Sha256, } impl CacheIdentity { fn for_desktop(run: &Path, bwrap: &Path, tools: &Path) -> Option { env::var_os("TEXRRA_DESKTOP_INSTANCE")?; let executable = env::current_exe().ok()?; let runtime = executable.parent()?.parent()?; // The desktop launcher verifies the bundle receipt and the EPS tarball // before starting this executable. Keep arbitrary CLI tools uncached. if runtime.parent()?.file_name()? != "runtime" || executable != runtime.join("bin/native_editor") || tools != runtime.join("eps-tools") || bwrap != tools.join("usr/bin/bwrap") || run.parent()? != runtime.join("web-runs") || fs::metadata("/etc/ld.so.preload").is_ok() { return None; } let receipt = read_regular(&runtime.join("desktop-bundle.json"), 128 * 1024).ok()?; let bundle_version = Sha256::digest(&receipt); if runtime.file_name()?.as_bytes() != format!("{bundle_version:x}").as_bytes() { return None; } let receipt: serde_json::Value = serde_json::from_slice(&receipt).ok()?; if receipt["sha256"]["eps-tools.tar"].as_str()?.len() != 64 { return None; } // The converter binds the unpacked tool tree and host libraries // read-only. Stat the bound trees to invalidate on updates, even // when bytes are replaced without changing the modification time. let mut key = Sha256::new(); key.update(b"texrra desktop EPS pdfwrite 1"); key.update(bundle_version); let mut count = 0; fingerprint_tree(&mut key, tools, tools, &mut count).ok()?; let host = Path::new("/usr/lib64"); fingerprint_tree(&mut key, host, host, &mut count).ok()?; if let Ok(metadata) = fs::symlink_metadata("/etc/ld.so.cache") { fingerprint_metadata(&mut key, &metadata); } Some(Self { directory: run.parent()?.join(".cached-eps"), fingerprint: key, }) } fn for_source(&self, source: &[u8]) -> Cache<'_> { let mut key = self.fingerprint.clone(); key.update(Sha256::digest(source)); Cache { directory: &self.directory, key: key.finalize().into(), } } } struct Cache<'a> { directory: &'a Path, key: [u8; 32], } impl Cache<'_> { fn slot(&self) -> PathBuf { self.directory .join(format!("{:02x}.pdf-cache", self.key[0] % CACHE_SLOTS)) } fn read(&self) -> Option> { if !fs::symlink_metadata(self.directory).ok()?.is_dir() { return None; } let record = read_regular(&self.slot(), CACHE_LIMIT + 64).ok()?; let (key, digest, pdf) = (record.get(..32)?, record.get(32..64)?, record.get(64..)?); let expected: [u8; 32] = Sha256::digest(pdf).into(); if key != self.key || digest != expected || !is_pdf(pdf) { return None; } Some(pdf.to_vec()) } fn write(&self, pdf: &[u8]) -> io::Result<()> { if pdf.len() > CACHE_LIMIT { return Ok(()); } match fs::DirBuilder::new().mode(0o700).create(self.directory) { Ok(()) => {} Err(error) if error.kind() == io::ErrorKind::AlreadyExists => { if !fs::symlink_metadata(self.directory)?.is_dir() { return Err(error); } } Err(error) => return Err(error), } let scratch = Scratch::new(self.directory)?; let temporary = scratch.0.join("artifact"); let mut file = fs::File::create_new(&temporary)?; file.write_all(&self.key)?; file.write_all(&Sha256::digest(pdf))?; file.write_all(pdf)?; file.sync_all()?; fs::rename(temporary, self.slot()) } } fn read_regular(path: &Path, limit: usize) -> io::Result> { let file = fs::OpenOptions::new() .read(true) .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK) .open(path)?; let metadata = file.metadata()?; if !metadata.is_file() || metadata.len() > limit as u64 { return Err(io::Error::other("invalid EPS cache file")); } let mut bytes = Vec::new(); file.take(limit as u64 + 1).read_to_end(&mut bytes)?; if bytes.len() > limit { return Err(io::Error::other("EPS cache file exceeds size limit")); } Ok(bytes) } fn fingerprint_tree( key: &mut Sha256, root: &Path, path: &Path, count: &mut usize, ) -> io::Result<()> { *count += 1; if *count > NODE_LIMIT { return Err(io::Error::other("EPS tool tree exceeds cache scan limit")); } let relative = path .strip_prefix(root) .expect("collecting descendants only"); let relative = relative.as_os_str().as_bytes(); key.update((relative.len() as u64).to_le_bytes()); key.update(relative); let metadata = fs::symlink_metadata(path)?; fingerprint_metadata(key, &metadata); if metadata.is_dir() { let mut children = fs::read_dir(path)? .map(|entry| entry.map(|entry| entry.path())) .collect::>>()?; children.sort_unstable(); for child in children { fingerprint_tree(key, root, &child, count)?; } } Ok(()) } fn fingerprint_metadata(key: &mut Sha256, metadata: &fs::Metadata) { key.update(metadata.dev().to_le_bytes()); key.update(metadata.ino().to_le_bytes()); key.update(metadata.mode().to_le_bytes()); key.update(metadata.len().to_le_bytes()); key.update(metadata.mtime().to_le_bytes()); key.update(metadata.mtime_nsec().to_le_bytes()); key.update(metadata.ctime().to_le_bytes()); key.update(metadata.ctime_nsec().to_le_bytes()); } fn is_pdf(pdf: &[u8]) -> bool { pdf.starts_with(b"%PDF-") && pdf.trim_ascii_end().ends_with(b"%%EOF") } pub(crate) struct Preparation<'a> { run: &'a Path, identity: OnceCell>, } impl<'a> Preparation<'a> { pub(crate) fn new(run: &'a Path) -> Self { Self { run, identity: OnceCell::new(), } } pub(crate) fn convert(&self, source: &[u8]) -> io::Result>> { convert(self.run, source, &self.identity) } } fn convert( run: &Path, source: &[u8], cache_identity: &OnceCell>, ) -> io::Result>> { let bwrap = env::var_os("TEXRRA_EPS_BWRAP"); let tool_root = env::var_os("TEXRRA_EPS_GS_ROOT"); let (bwrap, tool_root) = match (bwrap, tool_root) { (None, None) => return Ok(None), (Some(bwrap), Some(root)) => (PathBuf::from(bwrap), PathBuf::from(root)), _ => { return Err(io::Error::other( "EPS conversion needs both TEXRRA_EPS_BWRAP and TEXRRA_EPS_GS_ROOT", )); } }; if !bwrap.is_absolute() || !tool_root.is_absolute() || !bwrap.is_file() || !tool_root.join("usr/bin/gs").is_file() { return Err(io::Error::other( "EPS conversion needs an absolute bubblewrap executable and Ghostscript tool root", )); } let identity = cache_identity.get_or_init(|| CacheIdentity::for_desktop(run, &bwrap, &tool_root)); let cache = identity .as_ref() .map(|identity| identity.for_source(source)); if let Some(pdf) = cache.as_ref().and_then(Cache::read) { if env::var_os("TEXRRA_EDITOR_PREPARATION_TRACE").is_some_and(|value| value == "1") { eprintln!("Editor EPS cache hit"); } return Ok(Some(pdf)); } let scratch = Scratch::new(run)?; let input = scratch.0.join("input.eps"); let output = scratch.0.join("output.pdf"); fs::write(&input, source)?; fs::File::create_new(&output)?; let mut command = Command::new(bwrap); command .env_clear() .stdin(Stdio::null()) .stdout(Stdio::null()) .stderr(Stdio::null()) .args([ "--unshare-user", "--unshare-pid", "--unshare-net", "--unshare-ipc", "--unshare-uts", "--disable-userns", "--new-session", "--die-with-parent", "--clearenv", "--ro-bind", "/usr/lib64", "/usr/lib64", "--symlink", "usr/lib64", "/lib64", "--dev", "/dev", "--size", "67108864", "--tmpfs", "/tmp", "--chdir", "/tmp", "--ro-bind", ]) .arg(&tool_root) .args([ "/tool", "--symlink", "/tool/usr/share", "/usr/share", "--ro-bind", ]) .arg(&input) .args(["/input.eps", "--bind"]) .arg(&output) .args([ "/output.pdf", "--setenv", "LD_LIBRARY_PATH", "/tool/usr/lib64", "--setenv", "HOME", "/tmp", "--setenv", "TMPDIR", "/tmp", "--setenv", "SOURCE_DATE_EPOCH", "1783900800", "--", "/tool/usr/bin/gs", "-q", "-dSAFER", "-dBATCH", "-dNOPAUSE", "-dEPSCrop", "-dNOPLATFONTS", "-sDEVICE=pdfwrite", "-dCompatibilityLevel=1.5", "-dAutoRotatePages=/None", "-dOmitID", "-dOmitInfoDate", "-dOmitXMP", "-sOutputFile=/output.pdf", "-f", "/input.eps", ]); // These limits are inherited by bubblewrap and every process it launches. unsafe { command.pre_exec(|| { for (resource, maximum) in [ (libc::RLIMIT_FSIZE, MAX_PDF_BYTES as libc::rlim_t), (libc::RLIMIT_AS, MAX_ADDRESS_SPACE), (libc::RLIMIT_CPU, MAX_CPU_SECONDS), ] { let limit = libc::rlimit { rlim_cur: maximum, rlim_max: maximum, }; if libc::setrlimit(resource, &limit) != 0 { return Err(io::Error::last_os_error()); } } Ok(()) }); } let mut child = command.spawn()?; let deadline = Instant::now() + TIME_LIMIT; loop { match child.try_wait() { Ok(Some(status)) if status.success() => break, Ok(Some(status)) => { return Err(io::Error::other(format!( "isolated EPS converter exited with {status}" ))); } Ok(None) if Instant::now() < deadline => thread::sleep(Duration::from_millis(10)), result => { let _ = child.kill(); let _ = child.wait(); return Err(result.err().unwrap_or_else(|| { io::Error::new(io::ErrorKind::TimedOut, "isolated EPS conversion timed out") })); } } } let mut pdf = Vec::new(); fs::File::open(output)? .take(MAX_PDF_BYTES + 1) .read_to_end(&mut pdf)?; if pdf.len() as u64 > MAX_PDF_BYTES || !is_pdf(&pdf) { return Err(io::Error::new( io::ErrorKind::InvalidData, "invalid converted EPS PDF", )); } if let Some(cache) = cache { let _ = cache.write(&pdf); } Ok(Some(pdf)) } }