[worker] pictor-worker: JSON-lines ops, Job Object memory cap, time caps, hostile PDF tests

This commit is contained in:
2026-11-16 13:53:44 +01:00
parent 66aa2a1f18
commit 81628d4b51
7 changed files with 2836 additions and 0 deletions
Generated
+1605
View File
File diff suppressed because it is too large Load Diff
+35
View File
@@ -0,0 +1,35 @@
[package]
name = "pictor-worker"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
rust-version.workspace = true
[lib]
name = "pictor_worker"
path = "src/lib.rs"
[[bin]]
name = "pictor-worker"
path = "src/main.rs"
[dependencies]
thiserror.workspace = true
serde.workspace = true
serde_json.workspace = true
base64.workspace = true
image.workspace = true
pictor-raster.workspace = true
pictor-pdf.workspace = true
pictor-meta.workspace = true
pictor-qr.workspace = true
pictor-save.workspace = true
[target.'cfg(windows)'.dependencies]
windows = { workspace = true, features = ["Win32_Foundation", "Win32_System_JobObjects", "Win32_System_Threading", "Win32_Security"] }
[dev-dependencies]
tempfile.workspace = true
lopdf.workspace = true
flate2.workspace = true
+312
View File
@@ -0,0 +1,312 @@
//! The app's side of the worker: spawn, send, wait with a time cap, and survive whatever the worker does.
//!
//! On Windows the worker runs inside a Job Object that caps its memory and kills it when the job handle closes (so
//! a worker never outlives the app). A request that exceeds its time cap kills the worker; the next request starts
//! a fresh one (open PDFs must then be opened again: the error kind says `restarted`).
use crate::{OpError, PROTOCOL};
use serde_json::{Value, json};
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::mpsc::{Receiver, RecvTimeoutError, channel};
use std::sync::{Arc, Mutex};
use std::time::Duration;
#[derive(Debug, Clone)]
pub struct WorkerOptions {
pub exe: PathBuf,
/// Where pdfium.dll lives (passed as PICTOR_PDFIUM_DIR).
pub pdfium_dir: Option<PathBuf>,
/// The worker's memory cap.
pub memory_mb: u64,
/// Enables the debug.* operations (tests).
pub debug: bool,
}
impl WorkerOptions {
pub fn new(exe: impl Into<PathBuf>) -> WorkerOptions {
WorkerOptions { exe: exe.into(), pdfium_dir: None, memory_mb: 2048, debug: false }
}
}
#[derive(Debug, thiserror::Error)]
pub enum WorkerError {
/// The operation failed cleanly (bad file, wrong password, …): show `message`.
#[error("{0}")]
Op(OpError),
#[error("Pictor stopped reading this file after {0} seconds. It may be damaged or far too large.")]
TimedOut(u64),
#[error("Pictor ran out of memory reading this file and stopped. It may be damaged or far too large.")]
OutOfMemory,
#[error("Pictor's file reader stopped unexpectedly while reading this file. It may be damaged.")]
Crashed(String),
#[error("Pictor's file reader could not start: {0}")]
Spawn(String),
}
impl WorkerError {
/// A short machine-readable kind, like [`OpError::kind`].
pub fn kind(&self) -> &str {
match self {
WorkerError::Op(e) => &e.kind,
WorkerError::TimedOut(_) => "timed_out",
WorkerError::OutOfMemory => "out_of_memory",
WorkerError::Crashed(_) => "crashed",
WorkerError::Spawn(_) => "spawn",
}
}
}
struct Running {
child: Child,
stdin: ChildStdin,
lines: Receiver<String>,
stderr: Arc<Mutex<String>>,
#[cfg(windows)]
_job: job::Job,
}
pub struct Worker {
opts: WorkerOptions,
running: Option<Running>,
next_id: u64,
/// Set when the worker had to be restarted since the caller last asked (open documents are gone).
restarted: bool,
}
impl Worker {
pub fn new(opts: WorkerOptions) -> Worker {
Worker { opts, running: None, next_id: 1, restarted: false }
}
pub fn exe(&self) -> &Path {
&self.opts.exe
}
/// True once after the worker was restarted (its open documents are gone).
pub fn take_restarted(&mut self) -> bool {
std::mem::take(&mut self.restarted)
}
fn spawn(&mut self) -> Result<(), WorkerError> {
let mut cmd = Command::new(&self.opts.exe);
cmd.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped());
if let Some(d) = &self.opts.pdfium_dir {
cmd.env("PICTOR_PDFIUM_DIR", d);
}
if self.opts.debug {
cmd.env("PICTOR_WORKER_DEBUG", "1");
}
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
cmd.creation_flags(CREATE_NO_WINDOW);
}
let mut child = cmd.spawn().map_err(|e| WorkerError::Spawn(format!("{}: {e}", self.opts.exe.display())))?;
#[cfg(windows)]
let job = match job::Job::new(self.opts.memory_mb).and_then(|j| j.assign(&child).map(|_| j)) {
Ok(j) => j,
Err(e) => {
let _ = child.kill();
return Err(WorkerError::Spawn(format!("job object: {e}")));
}
};
let stdin = child.stdin.take().expect("piped");
let stdout = child.stdout.take().expect("piped");
let stderr_pipe = child.stderr.take().expect("piped");
let (tx, rx) = channel();
std::thread::spawn(move || {
let mut r = BufReader::new(stdout);
loop {
let mut line = String::new();
match r.read_line(&mut line) {
Ok(0) | Err(_) => return,
Ok(_) => {
if tx.send(line).is_err() {
return;
}
}
}
}
});
let stderr = Arc::new(Mutex::new(String::new()));
let sink = stderr.clone();
std::thread::spawn(move || {
let mut r = BufReader::new(stderr_pipe);
let mut line = String::new();
while let Ok(n) = r.read_line(&mut line) {
if n == 0 {
return;
}
let mut s = sink.lock().unwrap_or_else(|p| p.into_inner());
if s.len() < 16 << 10 {
s.push_str(&line);
}
line.clear();
}
});
let mut running = Running {
child,
stdin,
lines: rx,
stderr,
#[cfg(windows)]
_job: job,
};
let hello = running.lines.recv_timeout(Duration::from_secs(20)).map_err(|_| {
let _ = running.child.kill();
WorkerError::Spawn("it did not answer".into())
})?;
let hello: Value = serde_json::from_str(&hello).map_err(|e| WorkerError::Spawn(format!("bad hello: {e}")))?;
if hello["protocol"].as_u64() != Some(PROTOCOL as u64) {
let _ = running.child.kill();
return Err(WorkerError::Spawn(format!("it speaks protocol {}, Pictor needs {PROTOCOL}", hello["protocol"])));
}
self.running = Some(running);
Ok(())
}
fn kill(&mut self) {
if let Some(mut r) = self.running.take() {
let _ = r.child.kill();
let _ = r.child.wait();
self.restarted = true;
}
}
/// Runs `op` with `args`, waiting at most `timeout`. Starts (or restarts) the worker as needed.
pub fn call(&mut self, op: &str, args: Value, timeout: Duration) -> Result<Value, WorkerError> {
if self.running.as_mut().is_some_and(|r| r.child.try_wait().ok().flatten().is_some()) {
self.kill();
}
if self.running.is_none() {
self.spawn()?;
}
let id = self.next_id;
self.next_id += 1;
let r = self.running.as_mut().expect("spawned");
let line = json!({"id": id, "op": op, "args": args}).to_string();
if writeln!(r.stdin, "{line}").and_then(|_| r.stdin.flush()).is_err() {
return Err(self.died());
}
let deadline = std::time::Instant::now() + timeout;
loop {
let r = self.running.as_mut().expect("spawned");
let left = deadline.saturating_duration_since(std::time::Instant::now());
match r.lines.recv_timeout(left) {
Ok(text) => {
let v: Value = match serde_json::from_str(&text) {
Ok(v) => v,
Err(_) => continue,
};
if v["id"].as_u64() != Some(id) {
continue; // a late answer to a request that already timed out
}
if let Some(ok) = v.get("ok") {
return Ok(ok.clone());
}
let err: OpError = serde_json::from_value(v["err"].clone())
.unwrap_or_else(|_| OpError::new("damaged", "The file reader sent a bad answer."));
return Err(WorkerError::Op(err));
}
Err(RecvTimeoutError::Timeout) => {
self.kill();
return Err(WorkerError::TimedOut(timeout.as_secs().max(1)));
}
Err(RecvTimeoutError::Disconnected) => return Err(self.died()),
}
}
}
fn died(&mut self) -> WorkerError {
let stderr = self.running.as_ref().map(|r| r.stderr.lock().map(|s| s.clone()).unwrap_or_default()).unwrap_or_default();
// Give the stderr thread a moment to collect the last words.
std::thread::sleep(Duration::from_millis(50));
let stderr = self.running.as_ref().map(|r| r.stderr.lock().map(|s| s.clone()).unwrap_or_default()).unwrap_or(stderr);
// pdfium aborts without a word when an allocation fails; the job's peak memory tells that story.
#[cfg(windows)]
let hit_cap = self.running.as_ref().and_then(|r| r._job.peak_bytes()).is_some_and(|peak| peak * 10 >= (self.opts.memory_mb << 20) * 9);
#[cfg(not(windows))]
let hit_cap = false;
self.kill();
if hit_cap || stderr.contains("memory allocation") || stderr.contains("out of memory") {
WorkerError::OutOfMemory
} else {
WorkerError::Crashed(stderr.lines().last().unwrap_or("").to_string())
}
}
}
impl Drop for Worker {
fn drop(&mut self) {
self.kill();
}
}
#[cfg(windows)]
mod job {
use windows::Win32::Foundation::{CloseHandle, HANDLE};
use windows::Win32::System::JobObjects::*;
use windows::Win32::System::Threading::{OpenProcess, PROCESS_SET_QUOTA, PROCESS_TERMINATE};
pub struct Job(HANDLE);
unsafe impl Send for Job {}
impl Job {
pub fn new(memory_mb: u64) -> Result<Job, String> {
unsafe {
let h = CreateJobObjectW(None, None).map_err(|e| e.to_string())?;
let mut info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY | JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
info.ProcessMemoryLimit = (memory_mb.max(64) as usize) << 20;
SetInformationJobObject(
h,
JobObjectExtendedLimitInformation,
&info as *const _ as *const _,
std::mem::size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,
)
.map_err(|e| {
let _ = CloseHandle(h);
e.to_string()
})?;
Ok(Job(h))
}
}
pub fn assign(&self, child: &std::process::Child) -> Result<(), String> {
unsafe {
let p = OpenProcess(PROCESS_SET_QUOTA | PROCESS_TERMINATE, false, child.id()).map_err(|e| e.to_string())?;
let r = AssignProcessToJobObject(self.0, p).map_err(|e| e.to_string());
let _ = CloseHandle(p);
r
}
}
}
impl Job {
/// The most memory the worker ever committed, in bytes.
pub fn peak_bytes(&self) -> Option<u64> {
unsafe {
let mut info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
QueryInformationJobObject(
Some(self.0),
JobObjectExtendedLimitInformation,
&mut info as *mut _ as *mut _,
std::mem::size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,
None,
)
.ok()?;
Some(info.PeakProcessMemoryUsed as u64)
}
}
}
impl Drop for Job {
fn drop(&mut self) {
unsafe {
let _ = CloseHandle(self.0);
}
}
}
}
+93
View File
@@ -0,0 +1,93 @@
//! `pictor-worker`: the only Pictor process that parses outside files.
//!
//! The app (the tray process) starts it, sends one JSON request per line on stdin and reads one JSON response per
//! line on stdout (the protocol is in `docs/FORMATS.md`). [`client::Worker`] does that from the app's side: it puts
//! the worker in a Windows Job Object with a memory cap, gives every request a time cap, and kills and restarts the
//! worker when it hangs or crashes — so a hostile PDF can take down a worker, never the tray.
pub mod client;
pub mod ops;
use serde::Serialize;
/// The protocol version in the worker's hello line; the client refuses another.
pub const PROTOCOL: u32 = 1;
/// A typed error the UI can act on (`kind`) with a plain sentence for the user (`message`).
#[derive(Debug, Clone, Serialize, serde::Deserialize, PartialEq)]
pub struct OpError {
pub kind: String,
pub message: String,
}
impl OpError {
pub fn new(kind: &str, message: impl Into<String>) -> OpError {
OpError { kind: kind.into(), message: message.into() }
}
}
impl std::fmt::Display for OpError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.message)
}
}
impl From<pictor_pdf::PdfError> for OpError {
fn from(e: pictor_pdf::PdfError) -> Self {
use pictor_pdf::PdfError as E;
let kind = match &e {
E::EngineMissing(_) => "engine_missing",
E::NeedsPassword => "needs_password",
E::WrongPassword => "wrong_password",
E::Damaged(_) => "damaged",
E::Unsupported(_) => "unsupported",
E::NoSuchPage(_) | E::Invalid(_) => "invalid",
E::Write(_) => "io",
E::TooLarge(_) => "too_large",
};
OpError::new(kind, e.to_string())
}
}
impl From<pictor_raster::RasterError> for OpError {
fn from(e: pictor_raster::RasterError) -> Self {
let text = format!("{e:?}");
let kind = match text.split([' ', '{', '(']).next().unwrap_or("") {
"HeifCodecMissing" | "AvifCodecMissing" => "codec_missing",
"InputTooLarge" | "TooManyPixels" | "TooMuchMemory" => "too_large",
"UnknownFormat" | "UnsupportedFeature" | "CannotWrite" => "unsupported",
"CannotReachTarget" => "cannot_reach_target",
"Empty" | "InvalidCrop" | "InvalidSize" | "InvalidTarget" => "invalid",
_ => "damaged",
};
OpError::new(kind, e.to_string())
}
}
impl From<pictor_meta::MetaError> for OpError {
fn from(e: pictor_meta::MetaError) -> Self {
use pictor_meta::MetaError as E;
let kind = match &e {
E::Encrypted => "needs_password",
E::Unsupported(_) => "unsupported",
E::TooLarge { .. } | E::TooBig(_) => "too_large",
E::Write(_) => "io",
_ => "damaged",
};
OpError::new(kind, e.to_string())
}
}
impl From<pictor_qr::QrError> for OpError {
fn from(e: pictor_qr::QrError) -> Self {
OpError::new("invalid", e.to_string())
}
}
impl From<pictor_save::SaveError> for OpError {
fn from(e: pictor_save::SaveError) -> Self {
match e {
pictor_save::SaveError::Exists(_) => OpError::new("exists", e.to_string()),
_ => OpError::new("io", e.to_string()),
}
}
}
+54
View File
@@ -0,0 +1,54 @@
//! pictor-worker.exe: reads one JSON request per line on stdin, writes one JSON response per line on stdout.
//! → {"id": 1, "op": "pdf.open", "args": {...}}
//! ← {"id": 1, "ok": {...}} or {"id": 1, "err": {"kind": "...", "message": "..."}}
//! The first line it writes is {"hello": "pictor-worker", "protocol": 1, "version": "..."}.
//! Environment: PICTOR_PDFIUM_DIR (where pdfium.dll is; default: next to this exe), PICTOR_WORKER_DEBUG=1 (tests).
use pictor_worker::{OpError, PROTOCOL, ops};
use serde_json::{Value, json};
use std::io::{BufRead, Read, Write};
fn main() {
let exe_dir = std::env::current_exe().ok().and_then(|p| p.parent().map(|d| d.to_path_buf()));
let pdfium_dir = std::env::var_os("PICTOR_PDFIUM_DIR").map(Into::into).or(exe_dir);
let debug = std::env::var("PICTOR_WORKER_DEBUG").as_deref() == Ok("1");
let mut state = ops::State::new(pdfium_dir, debug);
let stdout = std::io::stdout();
let mut out = stdout.lock();
let hello = json!({"hello": "pictor-worker", "protocol": PROTOCOL, "version": env!("CARGO_PKG_VERSION")});
if writeln!(out, "{hello}").and_then(|_| out.flush()).is_err() {
return;
}
let stdin = std::io::stdin();
let mut line = String::new();
let mut input = stdin.lock();
loop {
line.clear();
// Requests are small (paths and edits); refuse absurd lines instead of buffering them.
match input.by_ref().take(64 << 20).read_line(&mut line) {
Ok(0) | Err(_) => return,
Ok(_) => {}
}
let req: Value = match serde_json::from_str(line.trim_end()) {
Ok(v) => v,
Err(e) => {
let _ = writeln!(out, "{}", json!({"id": null, "err": OpError::new("invalid", format!("bad request line: {e}"))}));
let _ = out.flush();
continue;
}
};
let id = req.get("id").cloned().unwrap_or(Value::Null);
let op = req.get("op").and_then(Value::as_str).unwrap_or("").to_string();
let args = req.get("args").cloned().unwrap_or(json!({}));
// A panic inside a library becomes a typed error, not a dead worker (an abort still kills it; the client
// reports that as a crash).
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| ops::dispatch(&mut state, &op, args)))
.unwrap_or_else(|_| Err(OpError::new("damaged", "Pictor could not read this file (it is damaged).")));
let resp = match result {
Ok(v) => json!({"id": id, "ok": v}),
Err(e) => json!({"id": id, "err": e}),
};
if writeln!(out, "{resp}").and_then(|_| out.flush()).is_err() {
return;
}
}
}
+443
View File
@@ -0,0 +1,443 @@
//! The worker's operations. Each takes the request's JSON arguments and returns JSON or an [`OpError`].
//! Files are read and written here (the paths come from the app); open PDFs stay in memory as sessions.
use crate::OpError;
use base64::Engine as _;
use pictor_pdf::{Edits, Engine, PageFit, PageSpec};
use pictor_raster::{Format, Limits};
use serde::Deserialize;
use serde_json::{Value, json};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
/// Largest outside file the worker reads at all.
pub const MAX_FILE_BYTES: u64 = 1 << 30;
pub struct State {
engine: Option<&'static Engine>,
pdfium_dir: Option<PathBuf>,
docs: HashMap<u32, Doc>,
next_doc: u32,
debug: bool,
}
struct Doc {
bytes: Vec<u8>,
password: Option<String>,
}
impl State {
pub fn new(pdfium_dir: Option<PathBuf>, debug: bool) -> State {
State { engine: None, pdfium_dir, docs: HashMap::new(), next_doc: 1, debug }
}
fn engine(&mut self) -> Result<&'static Engine, OpError> {
if let Some(e) = self.engine {
return Ok(e);
}
let e = Engine::load(self.pdfium_dir.as_deref())?;
self.engine = Some(e);
Ok(e)
}
fn doc(&self, id: u32) -> Result<&Doc, OpError> {
self.docs.get(&id).ok_or_else(|| OpError::new("not_open", "That PDF is no longer open. Open it again."))
}
}
fn b64(bytes: &[u8]) -> String {
base64::engine::general_purpose::STANDARD.encode(bytes)
}
fn read_file(path: &str) -> Result<Vec<u8>, OpError> {
let meta = std::fs::metadata(path).map_err(|e| OpError::new("io", format!("Pictor could not open {path}: {e}")))?;
if !meta.is_file() {
return Err(OpError::new("io", format!("{path} is not a file.")));
}
if meta.len() > MAX_FILE_BYTES {
return Err(OpError::new("too_large", "This file is larger than 1 GB, which Pictor does not open."));
}
std::fs::read(path).map_err(|e| OpError::new("io", format!("Pictor could not read {path}: {e}")))
}
fn args<T: for<'de> Deserialize<'de>>(v: Value) -> Result<T, OpError> {
serde_json::from_value(v).map_err(|e| OpError::new("invalid", format!("bad request: {e}")))
}
#[derive(Deserialize)]
#[serde(rename_all = "snake_case")]
enum SaveMode {
/// A new file; refuses to replace one.
New,
/// Replace the file, keeping a .bak.
Overwrite,
}
fn write_out(path: &str, bytes: &[u8], mode: SaveMode) -> Result<Value, OpError> {
let p = Path::new(path);
match mode {
SaveMode::New => {
pictor_save::save_new(p, bytes)?;
Ok(json!({"path": path, "bytes": bytes.len()}))
}
SaveMode::Overwrite => {
let bak = pictor_save::save_overwrite(p, bytes)?;
Ok(json!({"path": path, "bytes": bytes.len(), "bak": bak.exists().then(|| bak.display().to_string())}))
}
}
}
fn png(img: &image::DynamicImage) -> Result<Vec<u8>, OpError> {
let mut out = Vec::new();
image::codecs::png::PngEncoder::new_with_quality(
&mut out,
image::codecs::png::CompressionType::Fast,
image::codecs::png::FilterType::Sub,
)
.write_image(img.as_bytes(), img.width(), img.height(), img.color().into())
.map_err(|e| OpError::new("io", e.to_string()))?;
Ok(out)
}
use image::ImageEncoder;
pub fn dispatch(state: &mut State, op: &str, a: Value) -> Result<Value, OpError> {
match op {
// ---- PDF sessions -------------------------------------------------------------------------------------
"pdf.open" => {
#[derive(Deserialize)]
struct A {
path: String,
password: Option<String>,
}
let a: A = args(a)?;
let bytes = read_file(&a.path)?;
let engine = state.engine()?;
let info = pictor_pdf::info(engine, &bytes, a.password.as_deref())?;
let id = state.next_doc;
state.next_doc += 1;
state.docs.insert(id, Doc { bytes, password: a.password });
Ok(json!({"doc": id, "info": info}))
}
"pdf.close" => {
#[derive(Deserialize)]
struct A {
doc: u32,
}
let a: A = args(a)?;
state.docs.remove(&a.doc);
Ok(json!({}))
}
"pdf.render" => {
#[derive(Deserialize)]
struct A {
doc: u32,
page: usize,
width: u32,
}
let a: A = args(a)?;
let engine = state.engine()?;
let d = state.doc(a.doc)?;
let img = pictor_pdf::render_page(engine, &d.bytes, d.password.as_deref(), a.page, a.width)?;
Ok(json!({"png": b64(&png(&img)?), "width": img.width(), "height": img.height()}))
}
"pdf.text" => {
#[derive(Deserialize)]
struct A {
doc: u32,
}
let a: A = args(a)?;
let engine = state.engine()?;
let d = state.doc(a.doc)?;
Ok(json!({"pages": pictor_pdf::extract_text(engine, &d.bytes, d.password.as_deref())?}))
}
"pdf.search" => {
#[derive(Deserialize)]
struct A {
doc: u32,
query: String,
}
let a: A = args(a)?;
let engine = state.engine()?;
let d = state.doc(a.doc)?;
Ok(json!({"hits": pictor_pdf::search(engine, &d.bytes, d.password.as_deref(), &a.query, 2000)?}))
}
"pdf.form" => {
#[derive(Deserialize)]
struct A {
doc: u32,
}
let a: A = args(a)?;
let engine = state.engine()?;
let d = state.doc(a.doc)?;
Ok(json!({"fields": pictor_pdf::form_fields(engine, &d.bytes, d.password.as_deref())?}))
}
"pdf.save" => {
#[derive(Deserialize)]
struct A {
doc: u32,
edits: Edits,
output: String,
mode: SaveMode,
}
let a: A = args(a)?;
let engine = state.engine()?;
let d = state.doc(a.doc)?;
let applied = pictor_pdf::apply(engine, &d.bytes, d.password.as_deref(), &a.edits)?;
let mut out = write_out(&a.output, &applied.bytes, a.mode)?;
out["warnings"] = json!(applied.warnings);
Ok(out)
}
"pdf.extract" => {
#[derive(Deserialize)]
struct A {
doc: u32,
pages: Vec<usize>,
output: String,
}
let a: A = args(a)?;
let d = state.doc(a.doc)?;
let specs: Vec<PageSpec> = a.pages.iter().map(|&index| PageSpec::Existing { index, rotate: 0 }).collect();
let bytes = pictor_pdf::reorganise(&d.bytes, d.password.as_deref(), &specs)?;
write_out(&a.output, &bytes, SaveMode::New)
}
"pdf.to_images" => {
#[derive(Deserialize)]
struct A {
doc: u32,
pages: Vec<usize>,
dpi: u32,
format: String,
/// Output path pattern with `{n}` for the 1-based page number.
output: String,
}
let a: A = args(a)?;
let engine = state.engine()?;
let d = state.doc(a.doc)?;
let format = Format::from_name(&a.format).ok_or_else(|| OpError::new("invalid", "Choose PNG or JPG."))?;
let mut paths = Vec::new();
for &p in &a.pages {
let img = pictor_pdf::pages_to_images(engine, &d.bytes, d.password.as_deref(), &[p], a.dpi)?.remove(0);
let bytes = pictor_raster::encode(&img, format, &Default::default())?;
let path = a.output.replace("{n}", &(p + 1).to_string());
pictor_save::save_new(Path::new(&path), &bytes)?;
paths.push(path);
}
Ok(json!({"paths": paths}))
}
// ---- PDF files ----------------------------------------------------------------------------------------
"pdf.merge" => {
#[derive(Deserialize)]
struct Input {
path: String,
password: Option<String>,
}
#[derive(Deserialize)]
struct A {
inputs: Vec<Input>,
output: String,
}
let a: A = args(a)?;
let engine = state.engine()?;
let files: Vec<(Vec<u8>, Option<String>)> =
a.inputs.iter().map(|i| read_file(&i.path).map(|b| (b, i.password.clone()))).collect::<Result<_, _>>()?;
let refs: Vec<(&[u8], Option<&str>)> = files.iter().map(|(b, p)| (b.as_slice(), p.as_deref())).collect();
let bytes = pictor_pdf::merge(engine, &refs)?;
write_out(&a.output, &bytes, SaveMode::New)
}
"pdf.split" => {
#[derive(Deserialize)]
struct A {
path: String,
password: Option<String>,
ranges: String,
/// Output path pattern with `{n}` for the part number.
output: String,
}
let a: A = args(a)?;
let engine = state.engine()?;
let bytes = read_file(&a.path)?;
let pages = pictor_pdf::page_sizes(engine, &bytes, a.password.as_deref())?.len();
let ranges = pictor_pdf::parse_ranges(&a.ranges, pages)?;
let parts = pictor_pdf::split(&bytes, a.password.as_deref(), &ranges)?;
let mut paths = Vec::new();
for (i, part) in parts.iter().enumerate() {
let path = a.output.replace("{n}", &(i + 1).to_string());
pictor_save::save_new(Path::new(&path), part)?;
paths.push(path);
}
Ok(json!({"paths": paths}))
}
"pdf.from_images" => {
#[derive(Deserialize)]
struct A {
inputs: Vec<String>,
output: String,
fit: PageFit,
#[serde(default)]
margin: f32,
}
let a: A = args(a)?;
let limits = Limits::default();
let mut images = Vec::new();
for p in &a.inputs {
let bytes = read_file(p)?;
let img = pictor_raster::decode(&bytes, &limits)?;
images.push((bytes, img));
}
let bytes = pictor_pdf::images_to_pdf(&images, a.fit, a.margin)?;
write_out(&a.output, &bytes, SaveMode::New)
}
// ---- Images -------------------------------------------------------------------------------------------
"image.probe" => {
#[derive(Deserialize)]
struct A {
path: String,
}
let a: A = args(a)?;
let bytes = read_file(&a.path)?;
let p = pictor_raster::probe(&bytes, &Limits::default())?;
Ok(json!({"format": p.format, "width": p.width, "height": p.height, "has_alpha": p.has_alpha,
"frames": p.frames, "bytes": bytes.len()}))
}
"image.thumb" => {
#[derive(Deserialize)]
struct A {
path: String,
max: u32,
}
let a: A = args(a)?;
let bytes = read_file(&a.path)?;
let img = pictor_raster::decode(&bytes, &Limits::default())?;
let (w, h) = (img.width(), img.height());
let t = pictor_raster::resize(&img, pictor_raster::Fit::LongEdge(a.max.clamp(16, 2048)), &Limits::default())?;
Ok(json!({"png": b64(&png(&t)?), "width": w, "height": h}))
}
"image.convert" => {
#[derive(Deserialize)]
struct A {
input: String,
output: String,
format: String,
#[serde(default)]
quality: Option<u8>,
#[serde(default)]
crop: Option<pictor_raster::Rect>,
#[serde(default)]
rotate: Option<pictor_raster::Rotation>,
#[serde(default)]
resize: Option<pictor_raster::Fit>,
#[serde(default)]
preset: Option<pictor_raster::Preset>,
#[serde(default)]
target_bytes: Option<u64>,
#[serde(default)]
overwrite: bool,
}
let a: A = args(a)?;
let limits = Limits::default();
let src = read_file(&a.input)?;
let src_format = pictor_raster::probe(&src, &limits)?.format;
let mut img = pictor_raster::decode(&src, &limits)?;
if let Some(c) = a.crop {
img = pictor_raster::crop(&img, c)?;
}
if let Some(r) = a.rotate {
img = pictor_raster::rotate(&img, r);
}
if let Some(f) = a.resize {
img = pictor_raster::resize(&img, f, &limits)?;
}
let format = Format::from_name(&a.format).ok_or_else(|| OpError::new("invalid", "Choose an output format."))?;
let (bytes, format) = if let Some(target) = a.target_bytes {
let c = pictor_raster::compress_to(&img, format, target, &limits)?;
(c.bytes, c.format)
} else if let Some(p) = a.preset {
let _ = src_format;
pictor_raster::apply_preset(&img, format, p)?
} else {
let mut o = pictor_raster::EncodeOptions::default();
if let Some(q) = a.quality {
o.jpeg_quality = q.clamp(10, 100);
}
(pictor_raster::encode(&img, format, &o)?, format)
};
let mut out = write_out(&a.output, &bytes, if a.overwrite { SaveMode::Overwrite } else { SaveMode::New })?;
out["format"] = json!(format);
out["width"] = json!(img.width());
out["height"] = json!(img.height());
Ok(out)
}
"image.heif_support" => Ok(json!({"support": pictor_raster::heif_support()})),
// ---- Metadata -----------------------------------------------------------------------------------------
"meta.read" => {
#[derive(Deserialize)]
struct A {
path: String,
}
let a: A = args(a)?;
let bytes = read_file(&a.path)?;
let report = pictor_meta::read(&bytes)?;
let groups: Vec<_> = report.groups().into_iter().map(|g| json!({"group": g, "label": g.label()})).collect();
Ok(json!({"report": report, "groups": groups}))
}
"meta.strip" => {
#[derive(Deserialize)]
struct A {
input: String,
output: String,
#[serde(default)]
overwrite: bool,
}
let a: A = args(a)?;
let bytes = read_file(&a.input)?;
let stripped = pictor_meta::strip(&bytes)?;
let mut out = write_out(&a.output, &stripped.bytes, if a.overwrite { SaveMode::Overwrite } else { SaveMode::New })?;
out["removed"] = json!(stripped.removed);
Ok(out)
}
// ---- QR -----------------------------------------------------------------------------------------------
"qr.render" => {
#[derive(Deserialize)]
struct A {
payload: pictor_qr::Payload,
#[serde(default)]
level: pictor_qr::Level,
style: pictor_qr::Style,
#[serde(default)]
logo: Option<String>,
}
let a: A = args(a)?;
let text = pictor_qr::payload_string(&a.payload)?;
let logo_bytes = match &a.logo {
Some(p) => Some(read_file(p)?),
None => None,
};
let logo = match &logo_bytes {
Some(b) => Some(pictor_raster::decode(b, &Limits::default())?.to_rgba8()),
None => None,
};
let r = pictor_qr::render_rgba(&text, a.level, &a.style, logo.as_ref())?;
let png = pictor_qr::encode_png(&r.image)?;
let logo_png = match &logo {
Some(l) => Some(pictor_qr::encode_png(l)?),
None => None,
};
let svg = pictor_qr::render_svg(&text, a.level, &a.style, logo_png.as_deref())?;
Ok(json!({"png": b64(&png), "svg": svg, "level_used": r.level_used, "size": r.size_px, "text": text}))
}
// ---- Tests only (PICTOR_WORKER_DEBUG=1) ---------------------------------------------------------------
"debug.crash" if state.debug => std::process::abort(),
"debug.sleep" if state.debug => {
std::thread::sleep(std::time::Duration::from_secs(a["secs"].as_u64().unwrap_or(60)));
Ok(json!({}))
}
"debug.alloc" if state.debug => {
let mb = a["mb"].as_u64().unwrap_or(4096) as usize;
let mut v: Vec<u8> = Vec::new();
v.try_reserve_exact(mb << 20).map_err(|_| OpError::new("too_large", "out of memory"))?;
v.resize(mb << 20, 1);
Ok(json!({"len": v.len()}))
}
_ => Err(OpError::new("invalid", format!("unknown operation {op}"))),
}
}
+294
View File
@@ -0,0 +1,294 @@
//! Mandatory test 2: hostile PDFs. Each fixture goes through the real worker process (open, render page 1, text,
//! metadata, a save with an annotation). Every step either works or fails with a typed error within its time cap;
//! a worker that crashes, hangs or runs out of memory is reported as such and replaced. This test process plays the
//! tray: it must never crash, and the next request after a bad file must work.
//! Fixtures are generated here; fixtures-fetch/fetch.ps1 adds real-world corpora under fixtures/fetched/ (optional).
use flate2::{Compression, write::ZlibEncoder};
use lopdf::{Document, Object, Stream, dictionary};
use pictor_worker::client::{Worker, WorkerError, WorkerOptions};
use serde_json::json;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
const CAP: Duration = Duration::from_secs(15);
fn worker() -> Worker {
let mut o = WorkerOptions::new(env!("CARGO_BIN_EXE_pictor-worker"));
o.pdfium_dir = Some(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../third_party/pdfium/bin"));
o.memory_mb = 1024;
o.debug = true;
Worker::new(o)
}
fn base_doc(content: &[u8]) -> Document {
let mut doc = Document::with_version("1.7");
let pages = doc.new_object_id();
let font = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica"});
let c = doc.add_object(Stream::new(dictionary! {}, content.to_vec()));
let page = doc.add_object(dictionary! {"Type" => "Page", "Parent" => pages, "Contents" => c,
"Resources" => dictionary! {"Font" => dictionary! {"F1" => font}}});
doc.objects.insert(pages, Object::Dictionary(dictionary! {"Type" => "Pages", "Kids" => vec![page.into()], "Count" => 1,
"MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()]}));
let cat = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages});
doc.trailer.set("Root", cat);
doc
}
fn save(mut doc: Document) -> Vec<u8> {
let mut v = Vec::new();
doc.save_to(&mut v).unwrap();
v
}
fn valid() -> Vec<u8> {
save(base_doc(b"BT /F1 24 Tf 72 700 Td (Hello hostile world) Tj ET"))
}
fn replace(hay: &[u8], from: &[u8], to: &[u8]) -> Vec<u8> {
let i = hay.windows(from.len()).position(|w| w == from).expect("pattern");
[&hay[..i], to, &hay[i + from.len()..]].concat()
}
fn font_doc(font_key: &str, font_bytes: Vec<u8>) -> Vec<u8> {
let mut doc = base_doc(b"BT /F2 24 Tf 72 700 Td (Font) Tj ET");
let ff = doc.add_object(Stream::new(dictionary! {}, font_bytes));
let desc = doc.add_object(dictionary! {"Type" => "FontDescriptor", "FontName" => "Broken", "Flags" => 32,
"FontBBox" => vec![0.into(), 0.into(), 1000.into(), 1000.into()], "ItalicAngle" => 0, "Ascent" => 800,
"Descent" => -200, "CapHeight" => 700, "StemV" => 80, font_key => ff});
let font = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => if font_key == "FontFile" { "Type1" } else { "TrueType" },
"BaseFont" => "Broken", "FirstChar" => 32, "LastChar" => 126, "FontDescriptor" => desc});
let page = *doc.get_pages().values().next().unwrap();
doc.get_dictionary_mut(page).unwrap().set("Resources", dictionary! {"Font" => dictionary! {"F2" => font}});
save(doc)
}
fn fixtures() -> Vec<(&'static str, Vec<u8>)> {
let v = valid();
let mut out: Vec<(&str, Vec<u8>)> = vec![
("empty file", Vec::new()),
("header only", b"%PDF-1.7\n".to_vec()),
("truncated at 10%", v[..v.len() / 10].to_vec()),
("truncated at 50%", v[..v.len() / 2].to_vec()),
("truncated before the trailer", v[..v.len() - 40].to_vec()),
("random bytes after a header", {
let mut x = b"%PDF-1.7\n".to_vec();
let mut s = 0x2545_4446u32;
for _ in 0..20_000 {
s ^= s << 13;
s ^= s >> 17;
s ^= s << 5;
x.push(s as u8);
}
x
}),
];
// Broken xref: startxref points nowhere, then the table itself is garbage.
let sx = v.windows(9).rposition(|w| w == b"startxref").unwrap();
out.push(("startxref beyond the end", [&v[..sx], b"startxref\n99999999\n%%EOF\n"].concat()));
// lopdf writes a cross-reference stream: garble its binary table, or cut it off and leave a bare trailer.
let xr = v.windows(10).rposition(|w| w == b"/Type/XRef").unwrap();
let obj_kw = v[..xr].windows(4).rposition(|w| w == b"obj\n").unwrap();
let xr_obj = v[..obj_kw].iter().rposition(|&b| b == b'\n').map(|i| i + 1).unwrap_or(0);
let mut garbled = v.clone();
let data = xr + garbled[xr..].windows(7).position(|w| w == b"stream\n").unwrap() + 7;
let end = (data + 40).min(garbled.len());
for b in garbled[data..end].iter_mut() {
*b = b.wrapping_mul(31).wrapping_add(7);
}
out.push(("garbled xref table", garbled));
out.push(("no xref at all", [&v[..xr_obj], b"trailer\n<< /Root 5 0 R >>\n%%EOF\n"].concat()));
// Recursive references.
{
let mut doc = base_doc(b"");
let pages = doc.catalog().unwrap().get(b"Pages").unwrap().as_reference().unwrap();
doc.get_dictionary_mut(pages).unwrap().set("Kids", vec![Object::Reference(pages)]);
out.push(("page tree that contains itself", save(doc)));
}
{
let mut doc = base_doc(b"");
let page = *doc.get_pages().values().next().unwrap();
let pages = doc.catalog().unwrap().get(b"Pages").unwrap().as_reference().unwrap();
doc.get_dictionary_mut(pages).unwrap().set("Parent", Object::Reference(page));
out.push(("parent loop", save(doc)));
}
out.push(("object that is a reference to itself", replace(&valid(), b"/Contents 3 0 R", b"/Contents 99 0 R").into_iter().chain(b"\n99 0 obj\n99 0 R\nendobj\n".iter().copied()).collect()));
out.push(("deeply nested arrays", {
let mut deep = vec![b'['; 200_000];
deep.extend(vec![b']'; 200_000]);
replace(&valid(), b"/Type/Catalog", &[b"/Type/Catalog /Deep ".as_slice(), &deep].concat())
}));
out.push(("page count of two billion", replace(&valid(), b"/Count 1", b"/Count 2147483647")));
out.push(("media box of 1e30 points", replace(&valid(), b"/MediaBox[0 0 595 842]", b"/MediaBox[0 0 1e30 1e30]")));
// A 1 GB declared stream, and a deflate bomb that expands to 1 GiB.
{
let doc = base_doc(b"BT /F1 24 Tf 72 700 Td (x) Tj ET");
let bytes = save(doc);
let i = bytes.windows(7).position(|w| w == b"/Length").unwrap();
let end = i + bytes[i..].iter().position(|&b| b == b'>').unwrap();
out.push(("stream that declares 1 GB", [&bytes[..i], b"/Length 1073741824", &bytes[end..]].concat()));
}
{
let mut z = ZlibEncoder::new(Vec::new(), Compression::best());
let zeros = vec![b' '; 1 << 20];
for _ in 0..1024 {
z.write_all(&zeros).unwrap();
}
let bomb = z.finish().unwrap();
let mut doc = base_doc(b"");
let page = *doc.get_pages().values().next().unwrap();
let c = doc.add_object(Stream::new(dictionary! {"Filter" => "FlateDecode"}, bomb).with_compression(false));
doc.get_dictionary_mut(page).unwrap().set("Contents", c);
out.push(("content stream that inflates to 1 GiB", save(doc)));
}
// Malformed fonts.
out.push(("TrueType font of garbage", font_doc("FontFile2", (0..4096u32).map(|i| (i * 7919 % 251) as u8).collect())));
out.push(("TrueType claiming 65535 tables", font_doc("FontFile2", [&[0, 1, 0, 0, 0xFF, 0xFF, 0, 0, 0, 0, 0, 0][..], &[0x41; 64]].concat())));
out.push(("truncated Type 1 font", font_doc("FontFile", b"%!PS-AdobeFont-1.0: Broken\n/FontName /Broken def\neexec\x00\x01".to_vec())));
// Encryption with a handler that does not exist.
out.push(("unknown security handler", replace(&valid(), b"/Root 5 0 R", b"/Root 5 0 R /Encrypt << /Filter /Bogus /V 9 /R 9 >>")));
out
}
fn fetched() -> Vec<(String, Vec<u8>)> {
let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/fetched");
let Ok(rd) = std::fs::read_dir(&dir) else { return Vec::new() };
let mut v: Vec<(String, Vec<u8>)> = rd
.filter_map(|e| e.ok())
.filter(|e| e.path().extension().is_some_and(|x| x.eq_ignore_ascii_case("pdf")))
.map(|e| (e.file_name().to_string_lossy().into_owned(), std::fs::read(e.path()).unwrap()))
.collect();
v.sort();
v
}
#[derive(Default, Debug)]
struct Tally {
ok: usize,
typed_error: usize,
timed_out: usize,
out_of_memory: usize,
crashed: usize,
}
fn run(w: &mut Worker, tally: &mut Tally, name: &str, op: &str, args: serde_json::Value) {
let start = Instant::now();
let r = w.call(op, args, CAP);
let took = start.elapsed();
assert!(took < CAP + Duration::from_secs(5), "{name}: {op} took {took:?}, past its cap");
let outcome = match &r {
Ok(_) => {
tally.ok += 1;
"ok".to_string()
}
Err(WorkerError::Op(e)) => {
assert!(!e.message.is_empty() && !e.message.contains("panicked"), "{name}: unclear message {e:?}");
tally.typed_error += 1;
format!("{} ({})", e.kind, e.message)
}
Err(WorkerError::TimedOut(_)) => {
tally.timed_out += 1;
"timed out".into()
}
Err(WorkerError::OutOfMemory) => {
tally.out_of_memory += 1;
"out of memory".into()
}
Err(WorkerError::Crashed(m)) => {
tally.crashed += 1;
format!("crashed: {m}")
}
Err(WorkerError::Spawn(e)) => panic!("worker would not start: {e}"),
};
println!("{name:40} {op:10} {took:>8.2?} {outcome}");
}
#[test]
fn hostile_pdfs_fail_cleanly_and_never_take_the_tray_down() {
let dir = tempfile::tempdir_in(env!("CARGO_TARGET_TMPDIR")).unwrap();
let mut w = worker();
let mut tally = Tally::default();
let mut all: Vec<(String, Vec<u8>)> = fixtures().into_iter().map(|(n, b)| (n.to_string(), b)).collect();
all.extend(fetched());
let annotation = json!({"annotations": [{"page": 0, "kind": "highlight", "rects": [{"x": 10, "y": 10, "w": 50, "h": 10}]}]});
for (i, (name, bytes)) in all.iter().enumerate() {
let path = dir.path().join(format!("f{i}.pdf"));
std::fs::write(&path, bytes).unwrap();
let p = path.to_string_lossy().to_string();
let start = Instant::now();
let opened = w.call("pdf.open", json!({"path": p}), CAP);
let took = start.elapsed();
let doc = match &opened {
Ok(v) => {
tally.ok += 1;
println!("{name:40} {:10} {took:>8.2?} ok, {} pages", "open", v["info"]["pages"].as_array().map(|a| a.len()).unwrap_or(0));
v["doc"].as_u64()
}
Err(e) => {
match e {
WorkerError::Op(_) => tally.typed_error += 1,
WorkerError::TimedOut(_) => tally.timed_out += 1,
WorkerError::OutOfMemory => tally.out_of_memory += 1,
WorkerError::Crashed(_) => tally.crashed += 1,
WorkerError::Spawn(e) => panic!("{e}"),
}
println!("{name:40} {:10} {took:>8.2?} {} ({e})", "open", e.kind());
None
}
};
if let Some(doc) = doc {
run(&mut w, &mut tally, name, "pdf.render", json!({"doc": doc, "page": 0, "width": 800}));
if w.take_restarted() {
continue;
}
run(&mut w, &mut tally, name, "pdf.text", json!({"doc": doc}));
if w.take_restarted() {
continue;
}
let out = dir.path().join(format!("f{i}-edited.pdf")).to_string_lossy().to_string();
run(&mut w, &mut tally, name, "pdf.save", json!({"doc": doc, "edits": annotation, "output": out, "mode": "new"}));
}
run(&mut w, &mut tally, name, "meta.read", json!({"path": p}));
w.take_restarted();
// The tray carries on: a normal request right after works.
let good = dir.path().join("good.pdf");
std::fs::write(&good, valid()).unwrap();
let r = w.call("pdf.open", json!({"path": good.to_string_lossy()}), CAP).expect("a good PDF after a bad one");
w.call("pdf.close", json!({"doc": r["doc"]}), CAP).unwrap();
}
println!("{} fixtures: {tally:?}", all.len());
assert!(all.len() >= 21);
assert_eq!(tally.timed_out, 0, "a fixture hung");
assert_eq!(tally.crashed, 0, "a worker died without a known cause");
}
#[test]
fn the_client_survives_crash_hang_and_memory_blowup() {
let mut w = worker();
let crash = w.call("debug.crash", json!({}), CAP);
assert!(matches!(crash, Err(WorkerError::Crashed(_))), "{crash:?}");
assert!(w.take_restarted());
let start = Instant::now();
let hang = w.call("debug.sleep", json!({"secs": 120}), Duration::from_secs(2));
assert!(matches!(hang, Err(WorkerError::TimedOut(_))), "{hang:?}");
assert!(start.elapsed() < Duration::from_secs(10));
let oom = w.call("debug.alloc", json!({"mb": 3000}), CAP);
// try_reserve fails cleanly under the cap (a typed error); a hard allocation would be OutOfMemory.
assert!(matches!(&oom, Err(WorkerError::OutOfMemory) | Err(WorkerError::Op(_))), "the 1 GB memory cap did not hold: {oom:?}");
// And it works again.
let ok = w.call("image.heif_support", json!({}), CAP).unwrap();
assert!(ok["support"].is_string());
}
#[test]
fn unknown_operations_and_bad_arguments_are_typed_errors() {
let mut w = worker();
for (op, args) in [("nope", json!({})), ("pdf.open", json!({"wrong": 1})), ("pdf.render", json!({"doc": 77, "page": 0, "width": 10}))] {
match w.call(op, args, CAP) {
Err(WorkerError::Op(e)) => assert!(["invalid", "not_open"].contains(&e.kind.as_str()), "{e:?}"),
other => panic!("{op}: {other:?}"),
}
}
let missing = w.call("pdf.open", json!({"path": "F:/definitely/not/here.pdf"}), CAP);
assert!(matches!(missing, Err(WorkerError::Op(ref e)) if e.kind == "io"), "{missing:?}");
}