Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

Merge PR #3670: Redaction: follow nested forms as deep as the readers do

aiongg44831a6047cf
diff --cc crates/redact/src/interp.rs
index 5ac6c24ea,bc34cc00b..ee772cd1a
--- a/crates/redact/src/interp.rs
+++ b/crates/redact/src/interp.rs
@@@ -106,10 -111,8 +125,12 @@@ pub(crate) struct Scope<'a>
fonts: HashMap<Vec<u8>, Rc<Metrics>>,
used_names: Vec<Vec<u8>>,
depth: usize,
+ /// Form entries and decoded bytes left for this page, its content streams already charged:
+ /// shared forms drawn from other shared forms would otherwise multiply the work with every
+ /// level.
+ budget: DecodeBudget,
+ /// Forms entered so far in this pass ([`MAX_FORM_VISITS`]).
+ visits: usize,
}
impl<'a> Scope<'a> {
@@@ -130,7 -127,7 +151,8 @@@
fonts: HashMap::new(),
used_names: Vec::new(),
depth: 0,
+ budget,
+ visits: 0,
}
}
@@@ -1269,13 -1003,11 +1291,16 @@@ fn xobject
{
return None;
}
- if scope.depth >= MAX_DEPTH {
+ // Too deep, or too many forms for one page: either way this form cannot be read, so
+ // it goes (Apply) or the page is left alone (Verify), as a form that will not decode
+ // does. The budget is what keeps a fan-out or a cycle from costing 2^50 walks.
+ if scope.depth >= MAX_DEPTH || scope.visits >= MAX_FORM_VISITS {
if scope.mode == Mode::Verify {
+ // Sanitization removes a Form it cannot enter, so the verification scan
+ // must count that conservative removal or it may decide to skip the pass.
+ if scope.everywhere() {
+ scope.layer_blocks += 1;
+ }
return None;
}
scope.report.forms_removed += 1;
@@@ -1283,26 -1015,9 +1308,27 @@@
out.doomed.push(r);
return Some(None);
}
+ scope.visits += 1;
- let data = match s.decoded() {
+ // Strict, like page content: a Form read only in part counts as undecodable.
+ let data = if scope.budget.enter_form() {
+ scope.budget.decode_strict(s)
+ } else {
+ Err(CosError::Filter(format!("the page draws more than {MAX_PAGE_FORMS} form XObjects")))
+ };
+ let data = match data {
Ok(d) => d,
+ // Past the page's budget nothing more is read: apply refuses the page, and
+ // verification counts the form as content that may remain.
+ Err(e) if scope.budget.exhausted() => {
+ if scope.mode == Mode::Apply {
+ out.error = Some(e);
+ } else if scope.everywhere() {
+ scope.layer_blocks += 1;
+ } else {
+ out.residue += 1;
+ }
+ return None;
+ }
Err(_) if scope.mode == Mode::Apply => {
scope.report.forms_removed += 1;
out.replaced.push(name);