Files
texrra-engine/examples/native_editor/figure_conversion.rs
T

224 lines
7.3 KiB
Rust

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))
}
}