Prepare EPS graphics and BibTeX references for desktop previews
This commit is contained in:
1 parent
715ad81bcf
commit
b38e39416e
8 files changed
+787
-7
No files matched your search
@@ -0,0 +1,475 @@
|
||||
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<PathBuf, Arc<[u8]>>,
|
||||
) -> Result<Option<(Plan, Arc<[u8]>)>, 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::<BTreeMap<_, _>>();
|
||||
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<u8>,
|
||||
databases: Vec<PathBuf>,
|
||||
style: PathBuf,
|
||||
staged_style: PathBuf,
|
||||
system_style: Option<Arc<[u8]>>,
|
||||
}
|
||||
|
||||
impl Plan {
|
||||
pub(super) fn output(&self) -> &Path {
|
||||
&self.output
|
||||
}
|
||||
|
||||
pub(super) fn update(
|
||||
&self,
|
||||
project: &ProjectSnapshot,
|
||||
edits: &BTreeMap<PathBuf, Option<Arc<[u8]>>>,
|
||||
) -> Result<Option<Arc<[u8]>>, 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<Arc<[u8]>, 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<u8>,
|
||||
databases: Vec<PathBuf>,
|
||||
style: Option<PathBuf>,
|
||||
has_citation: bool,
|
||||
visited: BTreeSet<PathBuf>,
|
||||
total: u64,
|
||||
include_issue: Option<String>,
|
||||
}
|
||||
|
||||
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::<Result<_, _>>()?;
|
||||
} 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<Option<&'a [u8]>, 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<PathBuf, String> {
|
||||
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<Vec<u8>> {
|
||||
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<PathBuf, Arc<[u8]>>,
|
||||
) -> Result<PathBuf, String> {
|
||||
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<Arc<[u8]>, 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<Vec<u8>, 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<Self> {
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub(super) fn converted_relative_path(relative: &Path, bytes: &[u8]) -> Option<PathBuf> {
|
||||
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) fn convert(_run: &Path, _source: &[u8]) -> std::io::Result<Option<Vec<u8>>> {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(super) use linux::convert;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
mod linux {
|
||||
use std::{
|
||||
env, fs,
|
||||
io::{self, Read},
|
||||
os::unix::{fs::DirBuilderExt, 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<Self> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn convert(run: &Path, source: &[u8]) -> io::Result<Option<Vec<u8>>> {
|
||||
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 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
|
||||
|| !pdf.starts_with(b"%PDF-")
|
||||
|| !pdf.trim_ascii_end().ends_with(b"%%EOF")
|
||||
{
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"invalid converted EPS PDF",
|
||||
));
|
||||
}
|
||||
Ok(Some(pdf))
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,8 @@ use texrra_tex_core::{
|
||||
use thread_usage::ThreadUsage;
|
||||
use tiny_http::{Header, Method, Request, Response, Server};
|
||||
|
||||
mod bibliography;
|
||||
mod figure_conversion;
|
||||
mod library;
|
||||
mod preview_socket;
|
||||
#[path = "../../src/projects.rs"]
|
||||
@@ -674,6 +676,7 @@ impl EditorSession {
|
||||
entry,
|
||||
editable,
|
||||
options,
|
||||
bibliography,
|
||||
..
|
||||
} = &mut self.editor;
|
||||
if edit.sequence <= self.queue.current.load(Ordering::Acquire) {
|
||||
@@ -699,6 +702,11 @@ impl EditorSession {
|
||||
{
|
||||
return Err("The entry file was edited twice".into());
|
||||
}
|
||||
if let Some(plan) = bibliography
|
||||
&& let Some(contents) = plan.update(project, &updates)?
|
||||
{
|
||||
updates.insert(plan.output().to_owned(), Some(contents));
|
||||
}
|
||||
project.with_file_changes(edit.sequence, updates)
|
||||
});
|
||||
*project = match next {
|
||||
@@ -759,6 +767,7 @@ struct EditorProject {
|
||||
editable: BTreeMap<String, PathBuf>,
|
||||
declared: BTreeSet<PathBuf>,
|
||||
options: CompileRequest,
|
||||
bibliography: Option<bibliography::Plan>,
|
||||
}
|
||||
|
||||
fn copy_with_date(
|
||||
@@ -869,6 +878,27 @@ fn prepare(
|
||||
files.insert(logical, Arc::from(data));
|
||||
}
|
||||
}
|
||||
let figures = additional.iter().filter_map(|relative| {
|
||||
let input = run.join(relative);
|
||||
let data = files.get(&input)?;
|
||||
let converted = run.join(figure_conversion::converted_relative_path(relative, data)?);
|
||||
if files.contains_key(&converted) {
|
||||
return None;
|
||||
}
|
||||
let date = dates.get(&input).and_then(|time| time.to_system_time());
|
||||
Some((converted, data.clone(), date))
|
||||
}).collect::<Vec<_>>();
|
||||
for (path, source, date) in figures {
|
||||
match figure_conversion::convert(run, &source) {
|
||||
Ok(Some(pdf)) => {
|
||||
let modified = date.unwrap_or_else(SystemTime::now);
|
||||
copy_with_date(&path, &pdf, Some(modified), &mut dates)?;
|
||||
files.insert(path, Arc::from(pdf));
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(error) => eprintln!("Editor EPS conversion for {}: {error}", path.display()),
|
||||
}
|
||||
}
|
||||
let mut output = entry.with_extension("pdf");
|
||||
if declared.contains(&output) || declared.contains(&output.with_extension("log")) {
|
||||
let directory = run.join(".texrra-output");
|
||||
@@ -884,7 +914,22 @@ fn prepare(
|
||||
request = request.observe_generated_initial();
|
||||
// Provision the finite, immutable resource bundle used by this trial.
|
||||
// The seed uses the same native compiler and actual package bytes.
|
||||
let seed = NativeCompiler::default().compile_detailed(request.clone());
|
||||
let compiler = NativeCompiler::default();
|
||||
let mut seed = compiler.compile_detailed(request.clone());
|
||||
let mut bibliography = None;
|
||||
if let Ok(initial) = &seed {
|
||||
match bibliography::from_seed(&request, &initial.resources.generated_artifacts, &files) {
|
||||
Ok(Some((plan, contents))) => {
|
||||
let path = plan.output().to_owned();
|
||||
copy_with_date(&path, &contents, Some(SystemTime::now()), &mut dates)?;
|
||||
files.insert(path, contents);
|
||||
bibliography = Some(plan);
|
||||
seed = compiler.compile_detailed(request.clone());
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(error) => eprintln!("Editor bibliography: {error}"),
|
||||
}
|
||||
}
|
||||
let (inputs, trace, generated) = match &seed {
|
||||
Ok(seed) => (
|
||||
Some(seed.inputs.as_ref()),
|
||||
@@ -969,6 +1014,7 @@ fn prepare(
|
||||
editable,
|
||||
declared,
|
||||
options: request,
|
||||
bibliography,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user