PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
M2: stream page content past the 256 MiB cap (item 1 of storytold/pdfcraft#623) (#797)
cyfung1031dd046a25b251
diff --git a/crates/render/src/raster.rs b/crates/render/src/raster.rsindex e6b635ef1..4ee9cce9e 100644--- a/crates/render/src/raster.rs+++ b/crates/render/src/raster.rs@@ -3842,6 +3842,152 @@ trailer << /Root 1 0 R >>}}+ /// Item 1 of storytold/pdfcraft#623: a page's content used to be cut at `MAX_DECODED_STREAM`,+ /// so everything after the cut was lost (the text and the title block of the A1 sample). Content+ /// that expands by a few times over is read to its end, however large it is.+ #[test]+ fn page_content_past_the_old_cap_renders() {+ let limit = hayro::hayro_syntax::MAX_DECODED_STREAM;+ // Blocks of a comment and a run of blanks. Each compresses about thirty times over, well+ // within the budget that `ContentReader` allows.+ let mut content = Vec::with_capacity(limit + (8 << 20));+ let mut state = 0x2545_f491_4f6c_dd1d_u64;+ while content.len() < limit + (8 << 20) {+ content.push(b'%');+ for _ in 0..3 {+ state = state.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);+ content.push(b'a' + ((state >> 33) % 26) as u8);+ }+ content.push(b'\n');+ content.resize(content.len() + 128, b' ');+ }+ content.extend_from_slice(b"1 0 0 rg 0 0 4 4 re f");+ let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());+ std::io::Write::write_all(&mut z, &content).unwrap();+ let stream = z.finish().unwrap();+ assert!(content.len() < 64 * stream.len(), "the content expands by less than the budget allows");++ let mut pdf = b"%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 40 40] /Contents 4 0 R >> endobj\n".to_vec();+ pdf.extend_from_slice(format!("4 0 obj << /Filter /FlateDecode /Length {} >> stream\n", stream.len()).as_bytes());+ pdf.extend_from_slice(&stream);+ pdf.extend_from_slice(b"\nendstream endobj\ntrailer << /Root 1 0 R >>\n%%EOF\n");+ let (tx, rx) = std::sync::mpsc::channel();+ std::thread::spawn(move || {+ let mut r = PageRenderer::new(Arc::new(pdf), RenderConfig::default());+ let _ = tx.send(r.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: 1.0, tag: 0 }));+ });+ let page = rx.recv_timeout(std::time::Duration::from_secs(120)).expect("a large page must render");+ assert!(page.error.is_none(), "{:?}", page.error);+ assert!(!page.warnings.contains(&RenderWarning::ContentTruncated), "nothing was cut");+ assert_eq!(&page.rgba[((38 * 40 + 1) * 4)..][..4], &[255, 0, 0, 255], "the square after the old cap draws");+ }++ /// The content stream is interpreted a window at a time. An inline image with more data than+ /// a window is read whole, and what follows it is still drawn.+ #[test]+ fn inline_images_longer_than_a_window_are_read_whole() {+ let mut content = b"q 300 0 0 300 0 0 cm BI /W 300 /H 300 /BPC 8 /CS /G ID ".to_vec();+ content.extend(std::iter::repeat_n(0x80_u8, 300 * 300));+ content.extend_from_slice(b" EI Q 1 0 0 rg 0 0 4 4 re f");+ let pdf = one_page_pdf(&content, "");+ let (tx, rx) = std::sync::mpsc::channel();+ std::thread::spawn(move || {+ let mut r = PageRenderer::new(Arc::new(pdf), RenderConfig::default());+ let _ = tx.send(r.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: 1.0, tag: 0 }));+ });+ let page = rx.recv_timeout(std::time::Duration::from_secs(60)).expect("an inline image must not stall the renderer");+ assert!(page.error.is_none(), "{:?}", page.error);+ let pixel = |x: u32, y: u32| {+ let offset = ((y * page.width + x) * 4) as usize;+ [page.rgba[offset], page.rgba[offset + 1], page.rgba[offset + 2], page.rgba[offset + 3]]+ };+ assert_eq!(pixel(1, 38), [255, 0, 0, 255], "the square after the image draws");+ let grey = pixel(30, 5);+ assert!(grey[0] == grey[1] && grey[1] == grey[2] && grey[0] < 255, "the image covers the page: {grey:?}");+ }++ /// A one-page PDF whose content is the stream `stream`, with the entries `dict` in its+ /// dictionary.+ fn one_page_pdf(stream: &[u8], dict: &str) -> Vec<u8> {+ let mut pdf = b"%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 40 40] /Contents 4 0 R >> endobj\n".to_vec();+ pdf.extend_from_slice(format!("4 0 obj << {dict} /Length {} >> stream\n", stream.len()).as_bytes());+ pdf.extend_from_slice(stream);+ pdf.extend_from_slice(b"\nendstream endobj\ntrailer << /Root 1 0 R >>\n%%EOF\n");+ }++ /// A page whose content expands far beyond its compressed stream stops at the expansion budget,+ /// which is 64 times the compressed size and at least `MAX_DECODED_STREAM`, and the page says so.+ #[test]+ fn content_bombs_stop_at_the_budget_and_say_so() {+ let bomb = zlib_zeros(hayro::hayro_syntax::MAX_DECODED_STREAM + (32 << 20));+ let pdf = one_page_pdf(&bomb, "/Filter /FlateDecode");+ let (tx, rx) = std::sync::mpsc::channel();+ std::thread::spawn(move || {+ let mut r = PageRenderer::new(Arc::new(pdf), RenderConfig::default());+ let _ = tx.send(r.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: 1.0, tag: 0 }));+ });+ let page = rx.recv_timeout(std::time::Duration::from_secs(60)).expect("a content bomb must not stall the renderer");+ assert!(page.error.is_none(), "{:?}", page.error);+ assert!(page.warnings.contains(&RenderWarning::ContentTruncated), "the cut content is observable");+ }++ /// A stream read in pieces of any size gives the same bytes: stored and dynamic blocks, and in+ /// a `/Contents` array a stream that is not Flate-coded, between two that are.+ #[test]+ fn content_reader_returns_the_same_bytes_in_any_pieces() {+ use hayro::hayro_syntax::Pdf;+ use std::io::Write;+ let mut plain = Vec::new();+ for i in 0..40_000_u32 {+ plain.extend_from_slice(format!("{} {} l\n", i % 977, i % 613).as_bytes());+ }+ let zlib = |data: &[u8], level| {+ let mut z = flate2::write::ZlibEncoder::new(Vec::new(), level);+ z.write_all(data).unwrap();+ z.finish().unwrap()+ };+ let read = |pdf: Vec<u8>, piece: usize| {+ let doc = Pdf::new(pdf).expect("parses");+ let page = doc.pages().first().expect("one page");+ let mut content = page.content_reader();+ let mut out = Vec::new();+ while content.read_into(&mut out, piece) > 0 {}+ out+ };+ let pieces = [1, 3, 64, 4096, 65_536, 1_000_000];++ for level in [flate2::Compression::none(), flate2::Compression::best()] {+ let pdf = one_page_pdf(&zlib(&plain, level), "/Filter /FlateDecode");+ for piece in pieces {+ assert!(read(pdf.clone(), piece) == plain, "piece {piece}");+ }+ }++ // A `/Contents` array: Flate, then ASCIIHex (decoded whole), then Flate. As before, each+ // stream is followed by a space.+ let hex: String = plain[..100].iter().map(|b| format!("{b:02x}")).collect::<String>() + ">";+ let first = zlib(&plain, flate2::Compression::default());+ let last = zlib(&plain[..50], flate2::Compression::default());+ let mut expected = plain.clone();+ expected.push(b' ');+ expected.extend_from_slice(&plain[..100]);+ expected.push(b' ');+ expected.extend_from_slice(&plain[..50]);+ expected.push(b' ');+ let mut pdf = b"%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 40 40] /Contents [4 0 R 5 0 R 6 0 R] >> endobj\n".to_vec();+ pdf.extend_from_slice(format!("4 0 obj << /Filter /FlateDecode /Length {} >> stream\n", first.len()).as_bytes());+ pdf.extend_from_slice(&first);+ pdf.extend_from_slice(format!("\nendstream endobj\n5 0 obj << /Filter /ASCIIHexDecode /Length {} >> stream\n", hex.len()).as_bytes());+ pdf.extend_from_slice(hex.as_bytes());+ pdf.extend_from_slice(format!("\nendstream endobj\n6 0 obj << /Filter /FlateDecode /Length {} >> stream\n", last.len()).as_bytes());+ pdf.extend_from_slice(&last);+ pdf.extend_from_slice(b"\nendstream endobj\ntrailer << /Root 1 0 R >>\n%%EOF\n");+ for piece in pieces {+ assert!(read(pdf.clone(), piece) == expected, "the array: piece {piece}");+ }+ }+/// Zlib data that inflates to `len` zero bytes.fn zlib_zeros(len: usize) -> Vec<u8> {use std::io::Write;diff --git a/vendor/README.md b/vendor/README.mdindex bba6aeb72..e3bbc23e3 100644--- a/vendor/README.md+++ b/vendor/README.md@@ -12,7 +12,7 @@ the fix. Vendoring copyleft code is never allowed (plan/adr/0001).| hayro | 0.7.1 | Apache-2.0 OR MIT | (1) `RenderSettings::{x_offset, y_offset}` to render one tile of a large page; (2) images over `MAX_IMAGE_PIXELS` (2^28) are skipped (a fuzzed `/W 4294967295` hung in resampling); (3) `tiling_cell_scale` keeps a tiling pattern's cell pixmap within 3000 px a side whatever its `/XStep`/`/YStep` (a fuzzed step far beyond `/BBox` allocated 2 GB); (4) stroke widths clamped to 4 × (canvas width + height) device pixels (a fuzzed `/LW 9223372036854775807` allocated 10 GB in stroke expansion); (5) `usable_dash_pattern`: a stroke whose dash pattern could cut it into more than `MAX_DASHES_PER_STROKE` (250,000) pieces, counting kurbo's restart of the pattern at every subpath and `ClosePath`, is drawn solid (a fuzzed `/D [[11] 0]` on a line from x = 92234775807 allocated over 5 GB, `[0.000001] 0 d` on a 20 pt line over 10 GB); (6) a dash pattern with a negative or non-finite entry, or a period that isn't positive, is drawn solid (`[-1 -1] 0 d` looped for ever in kurbo); (7) `render_size` and `render_into`: render into a buffer the caller allocates (PdfCraft renders into pixel-aligned memory that the GUI takes over as texture data); `render` is `render_into` on a new pixmap; (8) checked image source/target/RGBA, alpha-premultiplication scratch and intermediate sizes before resampling, finite transforms and exact source/mask buffers; sources wider than u16 may shrink before backend limits, with a 2^20 source-axis cap and conservative 128 MiB filter-planning estimate; an over-limit or failed resize keeps the original image resolution and geometry when the source fits the backend, otherwise skips it, with a logged warning; staging, resampling output/scratch, RGBA conversion and padding buffers use fallible reserves; (9) `may_paint_canvas`: a fill or stroke whose control-point box, grown by how far its paint reaches past the path (half the stroke width times the larger of the miter limit and √2) plus 0.5 user units and 2 pixels, misses the canvas is not drawn, so a tile no longer strokes and fills every path of its page (item 5 of #623); `set_skip_offscreen_paths` turns this off for the regression test | (1) `raster::tests::tiles_match_full_render`; (2) `raster::tests::absurd_image_dimensions_are_skipped`; (3) `raster::tests::tiling_cells_stay_small_whatever_the_step`; (4) `raster::tests::absurd_predictor_columns_and_line_widths_render`; (5) `raster::tests::dash_patterns_that_cut_a_stroke_into_billions_of_pieces_render`; (6) `raster::tests::invalid_dash_patterns_terminate_and_are_drawn_solid`; (7) `raster::tests::pixels_are_a_plain_renders_bytes_in_a_buffer_a_gui_can_take_over`; (8) `raster::tests::image_resampling_rejects_anisotropic_target_growth`, `raster::tests::image_resampling_bounds_intermediate_before_planning`, `raster::tests::image_resampling_rejects_invalid_sources_and_scales`, `raster::tests::image_resampling_keeps_valid_sizes_and_exact_limits`, `raster::tests::resampling_fallback_preserves_original_geometry_and_pixels`, `raster::tests::image_resampling_wide_sources_shrink_before_backend_side_limits`, `raster::tests::image_resampling_wide_transparent_sources_still_shrink`, `raster::tests::image_resampling_padded_backend_dimensions_stay_checked`, `raster::tests::image_resampling_mismatched_alpha_mask_keeps_pixels_and_placement`; (9) `raster::tests::skipping_paths_off_the_canvas_changes_no_pixel` || hayro-jbig2 | 0.3.0 | Apache-2.0 OR MIT | (1) at most 2^28 pixels per bitmap, page bitmap, halftone grid and grayscale image (each side could be 65535: 4.3 billion pixels decoded one by one); (2) at most 2^26 symbol pixels per symbol dictionary (a fuzzed dictionary decoded for minutes); (3) a symbol dictionary's height classes are capped at one per new symbol and its export runs at `2 × symbols + 1`, each plus `EXTRA_EMPTY_STEPS` (1024): an empty height class or a zero-length export run doesn't advance, and past the end of its data the arithmetic decoder can decode them for ever (one changed byte hung the renderer) | (1) `raster::tests::jbig2_regions_of_billions_of_pixels_are_refused`; (2) the nightly `cargo xtask fuzz` finding, which now finishes in about a second; (3) `raster::tests::jbig2_symbol_dictionaries_that_never_advance_terminate` || lopdf | 0.45.0 | MIT | (1) PNG predictor rows longer than the data are refused before their buffers are allocated (a fuzzed `/Columns 4294967295` allocated two 4 GiB rows), and empty frames return without row buffers; (2) predictor row widths use saturating arithmetic or reject overflow; (3) sub-byte TIFF Predictor 2 scratch is bounded by the samples present in the input instead of the declared `/Colors`, aligned with [lopdf#589](https://github.com/J-F-Liu/lopdf/pull/589) | (1) `inspect::tests::png_predictor_rows_longer_than_the_data_are_refused_before_allocating`, `inspect::tests::empty_png_predictor_frames_do_not_allocate_rows`; (2) `inspect::tests::tiff_subbyte_predictor_row_width_overflow_is_refused`; (3) `inspect::tests::tiff_subbyte_predictor_scratch_is_bounded_by_available_samples`, `inspect::tests::tiff_subbyte_predictors_keep_components_rows_and_padding` |-| hayro-syntax | 0.7.2 | Apache-2.0 OR MIT | (1) Page-tree cycle guard in `resolve_pages` (visited set + depth cap): a `/Kids` loop among compressed objects overflowed the stack and aborted the process; (2) `ccitt_size_ok`: CCITT images wider than 2^20 columns or over 2^28 pixels are not decoded (a fuzzed `/Columns 4294967295` allocated 4 GiB); (3) Flate/LZW predictor row widths are saturating `usize`, a zero width is refused and a row longer than the data is not allocated (a fuzzed `/Columns 9223372036854775807` wrapped to a 2^61-byte allocation and aborted); (4) the inline-image end-of-data check (`EI`) doesn't nest inside its own look-ahead and examines at most 256 candidates and steps (50 images with "EI" in their data ran for over ten minutes); (5) a stream whose `/Length` is wrong is recovered only when `stream` is the next token — scanning ahead to a later object's `stream` made an indirect appearance-state dictionary (Quartz checkboxes: `/AP /N` → `<< /Yes … /Off … >>`) render as a non-form, so the widget was skipped; (6) JPX rescaling uses an exact integer sample range for 1–32-bit components (32 shifted past u32, and floating-point maxima at 25–31 bits wrapped to zero), and refuses zero-sized rows; (7) `decode_limit`: Flate (through flate2 and the fallback inflater), LZW and RunLength never write past `MAX_DECODED_STREAM` (256 MiB), or, for the last filter of an image of known size, past twice its pixel bytes (a predictor tag byte per byte), at most 1 GiB; `Stream::decoded_within` for budgeted callers; a page's `/Contents` array shares one `MAX_DECODED_STREAM` (a 2 MB page whose content stream or 8 × 8 image inflated to 2 GB took the renderer past 3 GB in under a second; naming the stream twenty times in `/Contents`, 5 GB); (8) high-precision numbers (jsPDF MediaBox coordinates with over 19 digits) parse without overflowing the u64 mantissa: fractional digits past it are dropped, integer digits past it scale the value (a real, kept finite); (9) large dictionary indexes are built on first use and shared across repeated reads within each PDF (#307); the validated-byte cache is bounded, reader contexts remain separate, repairs and inline/content dictionaries bypass sharing, and small dictionaries stay eager; (10) decoded object-stream slots publish once under contention, cold loading rejects recursive dependencies, and xref repair serializes without holding recursive read guards; this permits one parser per native render pool with private worker caches; (11) `sync.rs`: a poisoned lock is recovered instead of unwrapped (a worker panic no longer cascades into every reader of the same PDF), and xref repair takes a blocking write lock instead of asserting a non-blocking one; (12) `SegmentList` (`util.rs`) returns `None` for an out-of-range index instead of panicking; (13) a page's `/UserUnit` scales `render_dimensions` and `initial_transform`, so the page and everything on it are sized in points, as Acrobat shows them; it is read as Acrobat reads it (the page's own entry, not inherited; a number from 1 up, at most 75,000; anything else counts as 1), and a page without it keeps exactly the transform it had; (14) revision 2–4 passwords are tried as given and then in PDFDocEncoding (`legacy_passwords` in `crypto/mod.rs`, which resolves the upstream `TODO: Convert to PDFDocEncoding`): passwords arrive as UTF-8 text, so a password with characters outside ASCII (`Çok güzel`, `ılık€`) written in PDFDocEncoding, as ISO 32000-2 §7.6.4.3.2 asks and qpdf and Acrobat write it, was always wrong | (1) `cos/tests/writer.rs::page_tree_loops_in_object_streams_do_not_crash_readers`; (2) `raster::tests::absurd_mask_and_fax_sizes_are_refused_before_decoding`; (3) `raster::tests::absurd_predictor_columns_and_line_widths_render`; (4) `raster::tests::inline_images_with_ei_in_their_data_parse_in_linear_time`; (5) `raster::tests::indirect_appearance_state_dict_is_not_another_stream`; (6) `raster::tests::jpx_stream_bit_depth_boundaries_do_not_panic`, `raster::tests::jpx_32_bit_image_does_not_prevent_other_page_content_from_rendering`, `raster::tests::jpx_gray_rgb_and_alpha_keep_eight_bit_samples`, `raster::tests::jpx_streams_reject_out_of_range_bit_depths`; (7) `raster::tests::decompression_bombs_stop_at_the_stream_limit`, `raster::tests::page_contents_and_nested_forms_share_one_budget`; (8) `inspect::tests::jspdf_high_precision_mediabox_does_not_overflow_dimensions`, `object::number::tests::high_precision_float_does_not_overflow_mantissa` (hayro-syntax); (9) `object::dict::lazy_index_tests`, `raster::tests::large_resource_indexes_preserve_pixels_and_text`; (10) `data::tests`, `xref::tests::concurrent_cold_object_stream_reads_all_succeed`, `raster::tests::shared_parser_is_lazy_and_initializes_once_under_contention`; (11) `data::tests::panicking_initializer_wakes_waiters_and_prevents_retries`, `xref::tests::concurrent_cold_object_stream_reads_all_succeed`; (12) `util::tests::segment_list_rejects_out_of_range_indices`; (13) `raster::tests::user_unit_scales_the_page_and_everything_on_it`; (14) `crypto::pdfcraft_password_tests`, `pdfcraft-engine` `tests::legacy_passwords_with_turkish_characters_open` |+| hayro-syntax | 0.7.2 | Apache-2.0 OR MIT | (1) Page-tree cycle guard in `resolve_pages` (visited set + depth cap): a `/Kids` loop among compressed objects overflowed the stack and aborted the process; (2) `ccitt_size_ok`: CCITT images wider than 2^20 columns or over 2^28 pixels are not decoded (a fuzzed `/Columns 4294967295` allocated 4 GiB); (3) Flate/LZW predictor row widths are saturating `usize`, a zero width is refused and a row longer than the data is not allocated (a fuzzed `/Columns 9223372036854775807` wrapped to a 2^61-byte allocation and aborted); (4) the inline-image end-of-data check (`EI`) doesn't nest inside its own look-ahead and examines at most 256 candidates and steps (50 images with "EI" in their data ran for over ten minutes); (5) a stream whose `/Length` is wrong is recovered only when `stream` is the next token — scanning ahead to a later object's `stream` made an indirect appearance-state dictionary (Quartz checkboxes: `/AP /N` → `<< /Yes … /Off … >>`) render as a non-form, so the widget was skipped; (6) JPX rescaling uses an exact integer sample range for 1–32-bit components (32 shifted past u32, and floating-point maxima at 25–31 bits wrapped to zero), and refuses zero-sized rows; (7) `decode_limit`: Flate (through flate2 and the fallback inflater), LZW and RunLength never write past `MAX_DECODED_STREAM` (256 MiB), or, for the last filter of an image of known size, past twice its pixel bytes (a predictor tag byte per byte), at most 1 GiB; `Stream::decoded_within` for budgeted callers; a page's `/Contents` array shares one `MAX_DECODED_STREAM` (a 2 MB page whose content stream or 8 × 8 image inflated to 2 GB took the renderer past 3 GB in under a second; naming the stream twenty times in `/Contents`, 5 GB); (8) high-precision numbers (jsPDF MediaBox coordinates with over 19 digits) parse without overflowing the u64 mantissa: fractional digits past it are dropped, integer digits past it scale the value (a real, kept finite); (9) large dictionary indexes are built on first use and shared across repeated reads within each PDF (#307); the validated-byte cache is bounded, reader contexts remain separate, repairs and inline/content dictionaries bypass sharing, and small dictionaries stay eager; (10) decoded object-stream slots publish once under contention, cold loading rejects recursive dependencies, and xref repair serializes without holding recursive read guards; this permits one parser per native render pool with private worker caches; (11) `sync.rs`: a poisoned lock is recovered instead of unwrapped (a worker panic no longer cascades into every reader of the same PDF), and xref repair takes a blocking write lock instead of asserting a non-blocking one; (12) `SegmentList` (`util.rs`) returns `None` for an out-of-range index instead of panicking; (13) a page's `/UserUnit` scales `render_dimensions` and `initial_transform`, so the page and everything on it are sized in points, as Acrobat shows them; it is read as Acrobat reads it (the page's own entry, not inherited; a number from 1 up, at most 75,000; anything else counts as 1), and a page without it keeps exactly the transform it had; (14) revision 2–4 passwords are tried as given and then in PDFDocEncoding (`legacy_passwords` in `crypto/mod.rs`, which resolves the upstream `TODO: Convert to PDFDocEncoding`): passwords arrive as UTF-8 text, so a password with characters outside ASCII (`Çok güzel`, `ılık€`) written in PDFDocEncoding, as ISO 32000-2 §7.6.4.3.2 asks and qpdf and Acrobat write it, was always wrong; (15) page content is read a piece at a time (`page::ContentReader`, `Page::content_reader`): plain streams and Flate streams without a predictor are decoded as they are read, with a budget of 64 times their compressed size and never less than `MAX_DECODED_STREAM` (a stream that expands past it is cut and reported); other streams are decoded whole, as before, and share `MAX_DECODED_STREAM`. The content tokenizer reads a window at a time (`UntypedIter::new_window`, `TypedIter::needs_more`, `TypedIter::committed`): an instruction that runs past the window is not decided until more data follows, which `Reader` records by flagging reads and `at_end` past the end of the data, including through the clones the parser makes. The Flate decoder keeps its own 32 KiB history, so it pauses at any output size. `ContentReader::new` reuses raw/decrypted stream bytes for budget accounting and piece creation, and `decoded_raw_within` applies the existing Whole-stream filters and limits to those bytes without decrypting twice. | (1) `cos/tests/writer.rs::page_tree_loops_in_object_streams_do_not_crash_readers`; (2) `raster::tests::absurd_mask_and_fax_sizes_are_refused_before_decoding`; (3) `raster::tests::absurd_predictor_columns_and_line_widths_render`; (4) `raster::tests::inline_images_with_ei_in_their_data_parse_in_linear_time`; (5) `raster::tests::indirect_appearance_state_dict_is_not_another_stream`; (6) `raster::tests::jpx_stream_bit_depth_boundaries_do_not_panic`, `raster::tests::jpx_32_bit_image_does_not_prevent_other_page_content_from_rendering`, `raster::tests::jpx_gray_rgb_and_alpha_keep_eight_bit_samples`, `raster::tests::jpx_streams_reject_out_of_range_bit_depths`; (7) `raster::tests::decompression_bombs_stop_at_the_stream_limit`, `raster::tests::page_contents_and_nested_forms_share_one_budget`; (8) `inspect::tests::jspdf_high_precision_mediabox_does_not_overflow_dimensions`, `object::number::tests::high_precision_float_does_not_overflow_mantissa` (hayro-syntax); (9) `object::dict::lazy_index_tests`, `raster::tests::large_resource_indexes_preserve_pixels_and_text`; (10) `data::tests`, `xref::tests::concurrent_cold_object_stream_reads_all_succeed`, `raster::tests::shared_parser_is_lazy_and_initializes_once_under_contention`; (11) `data::tests::panicking_initializer_wakes_waiters_and_prevents_retries`, `xref::tests::concurrent_cold_object_stream_reads_all_succeed`; (12) `util::tests::segment_list_rejects_out_of_range_indices`; (13) `raster::tests::user_unit_scales_the_page_and_everything_on_it`; (14) `crypto::pdfcraft_password_tests`, `pdfcraft-engine` `tests::legacy_passwords_with_turkish_characters_open`; (15) `content::tests::windows_keep_every_instruction_at_every_split`, `content::tests::windows_keep_every_instruction_in_pieces_of_any_size`, `content::tests::windows_match_the_slice_on_random_content`, `content::tests::windows_drop_blanks_and_keep_a_comment_that_may_go_on`, `page::content_reader_tests::content_past_the_cap_is_read_to_the_end`, `page::content_reader_tests::a_stream_that_expands_past_the_budget_is_cut_there`, `page::content_reader_tests::a_small_expansion_under_the_cap_is_not_cut`, `raster::tests::page_content_past_the_old_cap_renders`, `raster::tests::content_reader_returns_the_same_bytes_in_any_pieces`, `raster::tests::content_bombs_stop_at_the_budget_and_say_so`, `page::content_reader_tests::plain_and_whole_pieces_keep_their_bytes`, `page::content_reader_tests::repeated_content_reference_counts_compressed_bytes_once`, `page::content_reader_tests::whole_cap_still_counts_later_unique_streams`| lopdf | 0.45.0 | MIT | (1) PNG predictor rows longer than the data are refused before their buffers are allocated (a fuzzed `/Columns 4294967295` allocated two 4 GiB rows), and empty frames return without row buffers; (2) predictor row widths use saturating arithmetic or reject overflow; (3) sub-byte TIFF Predictor 2 scratch is bounded by the samples present in the input instead of the declared `/Colors`, aligned with [lopdf#589](https://github.com/J-F-Liu/lopdf/pull/589); (4) the object lookup keeps its cycle history through compressed objects, requires an ordinary in-file container, and caps the chain of indirect lookups at 16 (a chain of new objects, each a `/Length` compressed in a container whose own `/Length` names the next, or a stream whose `/Length` names the next stream, overflowed the stack: a dev build's 2 MiB thread within 800 hops); (5) object-stream members are parsed within their own extent (up to the next distinct offset), an entry whose offset repeats an earlier entry's is skipped (so a repeated object number can resolve to its earlier entry), and offsets are processed in index order | (1) `inspect::tests::png_predictor_rows_longer_than_the_data_are_refused_before_allocating`, `inspect::tests::empty_png_predictor_frames_do_not_allocate_rows`; (2) `inspect::tests::tiff_subbyte_predictor_row_width_overflow_is_refused`; (3) `inspect::tests::tiff_subbyte_predictor_scratch_is_bounded_by_available_samples`, `inspect::tests::tiff_subbyte_predictors_keep_components_rows_and_padding`; (4) `inspect::tests::compressed_object_self_container_does_not_recurse`, `inspect::tests::compressed_object_mutual_containers_do_not_recurse`, `inspect::tests::object_stream_length_cycle_does_not_recurse`, `inspect::tests::compressed_object_container_chain_does_not_recurse`, `inspect::tests::compressed_length_chain_does_not_recurse`, `inspect::tests::plain_stream_length_chain_does_not_recurse`, `inspect::tests::compressed_objects_and_indirect_stream_length_still_load`, `inspect::tests::compressed_length_in_a_container_with_an_indirect_length_still_loads`; (5) `inspect::tests::object_stream_member_extents_bound_owned_strings`, `inspect::tests::object_stream_member_extents_preserve_index_order_and_whitespace` || hayro-syntax | 0.7.2 | Apache-2.0 OR MIT | (1) Page-tree cycle guard in `resolve_pages` (visited set + depth cap): a `/Kids` loop among compressed objects overflowed the stack and aborted the process; (2) `ccitt_size_ok`: CCITT images wider than 2^20 columns or over 2^28 pixels are not decoded (a fuzzed `/Columns 4294967295` allocated 4 GiB); (3) Flate/LZW predictor row widths are saturating `usize`, a zero width is refused and a row longer than the data is not allocated (a fuzzed `/Columns 9223372036854775807` wrapped to a 2^61-byte allocation and aborted); (4) the inline-image end-of-data check (`EI`) doesn't nest inside its own look-ahead and examines at most 256 candidates and steps (50 images with "EI" in their data ran for over ten minutes); (5) a stream whose `/Length` is wrong is recovered only when `stream` is the next token — scanning ahead to a later object's `stream` made an indirect appearance-state dictionary (Quartz checkboxes: `/AP /N` → `<< /Yes … /Off … >>`) render as a non-form, so the widget was skipped; (6) JPX rescaling uses an exact integer sample range for 1–32-bit components (32 shifted past u32, and floating-point maxima at 25–31 bits wrapped to zero), and refuses zero-sized rows; (7) `decode_limit`: Flate (through flate2 and the fallback inflater), LZW and RunLength never write past `MAX_DECODED_STREAM` (256 MiB), or, for the last filter of an image of known size, past twice its pixel bytes (a predictor tag byte per byte), at most 1 GiB; `Stream::decoded_within` for budgeted callers; a page's `/Contents` array shares one `MAX_DECODED_STREAM` (a 2 MB page whose content stream or 8 × 8 image inflated to 2 GB took the renderer past 3 GB in under a second; naming the stream twenty times in `/Contents`, 5 GB); (8) high-precision numbers (jsPDF MediaBox coordinates with over 19 digits) parse without overflowing the u64 mantissa: fractional digits past it are dropped, integer digits past it scale the value (a real, kept finite); (9) large dictionary indexes are built on first use and shared across repeated reads within each PDF (#307); the validated-byte cache is bounded, reader contexts remain separate, repairs and inline/content dictionaries bypass sharing, and small dictionaries stay eager; (10) decoded object-stream slots publish once under contention, cold loading rejects recursive dependencies, and xref repair serializes without holding recursive read guards; this permits one parser per native render pool with private worker caches; (11) `sync.rs`: a poisoned lock is recovered instead of unwrapped (a worker panic no longer cascades into every reader of the same PDF), and xref repair takes a blocking write lock instead of asserting a non-blocking one; (12) `SegmentList` (`util.rs`) returns `None` for an out-of-range index instead of panicking; (13) a page's `/UserUnit` scales `render_dimensions` and `initial_transform`, so the page and everything on it are sized in points, as Acrobat shows them; it is read as Acrobat reads it (the page's own entry, not inherited; a number from 1 up, at most 75,000; anything else counts as 1), and a page without it keeps exactly the transform it had | (1) `cos/tests/writer.rs::page_tree_loops_in_object_streams_do_not_crash_readers`; (2) `raster::tests::absurd_mask_and_fax_sizes_are_refused_before_decoding`; (3) `raster::tests::absurd_predictor_columns_and_line_widths_render`; (4) `raster::tests::inline_images_with_ei_in_their_data_parse_in_linear_time`; (5) `raster::tests::indirect_appearance_state_dict_is_not_another_stream`; (6) `raster::tests::jpx_stream_bit_depth_boundaries_do_not_panic`, `raster::tests::jpx_32_bit_image_does_not_prevent_other_page_content_from_rendering`, `raster::tests::jpx_gray_rgb_and_alpha_keep_eight_bit_samples`, `raster::tests::jpx_streams_reject_out_of_range_bit_depths`; (7) `raster::tests::decompression_bombs_stop_at_the_stream_limit`, `raster::tests::page_contents_and_nested_forms_share_one_budget`; (8) `inspect::tests::jspdf_high_precision_mediabox_does_not_overflow_dimensions`, `object::number::tests::high_precision_float_does_not_overflow_mantissa` (hayro-syntax); (9) `object::dict::lazy_index_tests`, `raster::tests::large_resource_indexes_preserve_pixels_and_text`; (10) `data::tests`, `xref::tests::concurrent_cold_object_stream_reads_all_succeed`, `raster::tests::shared_parser_is_lazy_and_initializes_once_under_contention`; (11) `data::tests::panicking_initializer_wakes_waiters_and_prevents_retries`, `xref::tests::concurrent_cold_object_stream_reads_all_succeed`; (12) `util::tests::segment_list_rejects_out_of_range_indices`; (13) `raster::tests::user_unit_scales_the_page_and_everything_on_it` || lopdf | 0.45.0 | MIT | (1) PNG predictor rows longer than the data are refused before their buffers are allocated (a fuzzed `/Columns 4294967295` allocated two 4 GiB rows), and empty frames return without row buffers; (2) predictor row widths use saturating arithmetic or reject overflow; (3) sub-byte TIFF Predictor 2 scratch is bounded by the samples present in the input instead of the declared `/Colors`, aligned with [lopdf#589](https://github.com/J-F-Liu/lopdf/pull/589) | (1) `inspect::tests::png_predictor_rows_longer_than_the_data_are_refused_before_allocating`, `inspect::tests::empty_png_predictor_frames_do_not_allocate_rows`; (2) `inspect::tests::tiff_subbyte_predictor_row_width_overflow_is_refused`; (3) `inspect::tests::tiff_subbyte_predictor_scratch_is_bounded_by_available_samples`, `inspect::tests::tiff_subbyte_predictors_keep_components_rows_and_padding` |diff --git a/vendor/hayro-interpret/src/interpret/mod.rs b/vendor/hayro-interpret/src/interpret/mod.rsindex 8f5e7ce77..5ede4d444 100644--- a/vendor/hayro-interpret/src/interpret/mod.rs+++ b/vendor/hayro-interpret/src/interpret/mod.rs@@ -21,7 +21,8 @@ use hayro_syntax::object::dict::keys::{ANNOTS, AP, AS, C, CA, F, MCID, N, OC, QUADPOINTS, RECT, SUBTYPE,};use hayro_syntax::object::{Array, Dict, Object, Rect, Stream, dict_or_stream};-use hayro_syntax::page::{Page, Resources};+use hayro_syntax::page::{ContentReader, Page, Resources};+use hayro_syntax::MAX_DECODED_STREAM;use kurbo::{Affine, BezPath, Point, Shape};use smallvec::smallvec;use std::sync::Arc;@@ -159,9 +160,11 @@ pub fn interpret_page<'a>(device: &mut impl Device<'a>,) {let resources = page.resources();- // PdfCraft patch: the page's own contents count against its content budget too.- crate::context::charge_content(page.page_stream().map_or(0, <[u8]>::len));- interpret(page.typed_operations(), resources, context, device);+ let mut content = page.content_reader();+ // PdfCraft patch: the page's own contents count against its content budget too, where they+ // are decoded whole. Streamed content is only ever held a window at a time.+ crate::context::charge_content(content.materialized_len());+ interpret_content(&mut content, resources, context, device);if context.settings.render_annotations&& let Some(annot_arr) = page.raw().get::<Array<'_>>(ANNOTS)@@ -323,17 +326,15 @@ fn draw_highlight_without_appearance<'a>(context.restore_state(device);}-/// Interpret the instructions from `ops` and render them into the device.-pub fn interpret<'a>(- mut ops: TypedIter<'_>,+/// Interprets the instructions that `ops` yields, until they run out or the caller cancels. It runs+/// once per window of a content stream, between one `save_state` and its restore (see+/// `interpret_content`).+fn interpret_window<'a>(+ ops: &mut TypedIter<'_>,resources: &Resources<'a>,context: &mut Context<'a>,device: &mut impl Device<'a>,) {- let num_states = context.num_states();-- context.save_state();-while let Some(op) = ops.next() {// PdfCraft patch: stop when the caller cancelled (see `InterpreterSettings::cancelled`).if context.settings.cancelled.as_ref().is_some_and(|c| c.load(Ordering::Relaxed)) {@@ -842,6 +843,20 @@ pub fn interpret<'a>(}}}+}++/// Interpret the instructions from `ops` and render them into the device.+pub fn interpret<'a>(+ mut ops: TypedIter<'_>,+ resources: &Resources<'a>,+ context: &mut Context<'a>,+ device: &mut impl Device<'a>,+) {+ let num_states = context.num_states();++ context.save_state();++ interpret_window(&mut ops, resources, context, device);while context.num_states() > num_states {context.restore_state(device);@@ -851,3 +866,61 @@ pub fn interpret<'a>((context.settings.warning_sink)(InterpreterWarning::ContentTruncated);}}++/// PdfCraft patch: the bytes of a window of page content. A window grows only while an instruction+/// at its end is incomplete.+const CONTENT_WINDOW: usize = 64 << 10;++/// PdfCraft patch: interprets the content of a page a window at a time, so the decoded content is+/// never all in memory (see `ContentReader`). A window ends at an instruction that is not complete+/// yet: its bytes are kept, and the next window starts with them.+fn interpret_content<'a>(+ content: &mut ContentReader<'_>,+ resources: &Resources<'a>,+ context: &mut Context<'a>,+ device: &mut impl Device<'a>,+) {+ let num_states = context.num_states();++ context.save_state();++ let mut window = Vec::with_capacity(CONTENT_WINDOW);+ let mut exhausted = false;+ let mut cut = false;+ loop {+ let (committed, needs_more) = {+ let mut ops = TypedIter::new_window(&window, exhausted);+ interpret_window(&mut ops, resources, context, device);+ (ops.committed(), ops.needs_more())+ };+ window.drain(..committed);++ let cancelled = context+ .settings+ .cancelled+ .as_ref()+ .is_some_and(|c| c.load(Ordering::Relaxed));+ if !needs_more || cancelled || exhausted {+ break;+ }+ // A window that is still incomplete at its end waits for more of the stream. It doubles+ // while it waits, so one long instruction costs time in proportion to its length, and it+ // stops growing at `MAX_DECODED_STREAM`, the most any one stream may decode to.+ if window.len() >= MAX_DECODED_STREAM {+ cut = true;+ break;+ }+ let want = window.len().max(CONTENT_WINDOW);+ if content.read_into(&mut window, want) == 0 {+ exhausted = true;+ }+ }++ while context.num_states() > num_states {+ context.restore_state(device);+ }+ // PdfCraft patch (18): say that content was skipped, so a truncated page isn't a clean render.+ if cut || content.truncated() || crate::context::content_was_truncated() {+ (context.settings.warning_sink)(InterpreterWarning::ContentTruncated);+ }+}diff --git a/vendor/hayro-syntax/src/byte_reader.rs b/vendor/hayro-syntax/src/byte_reader.rsindex f3c7a20e0..78b282c8f 100644--- a/vendor/hayro-syntax/src/byte_reader.rs+++ b/vendor/hayro-syntax/src/byte_reader.rs@@ -1,5 +1,6 @@//! A byte reader.+use core::cell::Cell;use core::ops::Range;/// PdfCraft patch: how deeply direct arrays and dictionaries may nest (the same cap as `pdfcraft-cos`; a@@ -13,6 +14,9 @@ pub struct Reader<'a> {pub data: &'a [u8],/// The current byte-offset.pub offset: usize,+ /// PdfCraft patch: set when a read needed a byte past the end of `data`. A decision made from+ /// such a read could change if more data followed (see `content::UntypedIter`).+ past_end: Cell<bool>,// PdfCraft patch: bound direct-object nesting while skipping arrays and dictionaries// and while parsing dictionaries (`Dict::skip`, `Array::skip`, `parse_dict_with`).skip_depth: usize,@@ -22,13 +26,26 @@ impl<'a> Reader<'a> {/// Create a new reader.#[inline]pub fn new(data: &'a [u8]) -> Self {- Self { data, offset: 0, skip_depth: 0 }+ Self::new_with(data, 0)}/// Create a new reader at the given offset.#[inline]pub fn new_with(data: &'a [u8], offset: usize) -> Self {- Self { data, offset, skip_depth: 0 }+ Self { data, offset, past_end: Cell::new(false), skip_depth: 0 }+ }++ /// PdfCraft patch: whether a read needed bytes past the end of the data since the flag was+ /// last cleared.+ #[inline]+ pub(crate) fn looked_past_end(&self) -> bool {+ self.past_end.get()+ }++ /// PdfCraft patch: clears the flag set by [`Reader::looked_past_end`].+ #[inline]+ pub(crate) fn clear_looked_past_end(&self) {+ self.past_end.set(false);}pub(crate) fn enter_container(&mut self) -> Option<()> {@@ -46,7 +63,21 @@ impl<'a> Reader<'a> {/// Returns `true` if the reader has reached the end of the data.#[inline]pub fn at_end(&self) -> bool {- self.offset >= self.data.len()+ let at_end = self.offset >= self.data.len();+ if at_end {+ // PdfCraft patch: a parser that stops at the end decides from it (see `past_end`).+ self.past_end.set(true);+ }++ at_end+ }++ /// PdfCraft patch: carries over whether `other`, a clone of this reader, looked past the end.+ #[inline]+ pub(crate) fn absorb_past_end(&self, other: &Reader<'_>) {+ if other.past_end.get() {+ self.past_end.set(true);+ }}/// Moves the reader offset to the end of the data.@@ -118,15 +149,26 @@ impl<'a> Reader<'a> {/// Peeks the specified number of bytes.#[inline]pub fn peek_bytes(&self, len: usize) -> Option<&'a [u8]> {- self.offset+ let bytes = self+ .offset.checked_add(len)- .and_then(|end| self.data.get(self.offset..end))+ .and_then(|end| self.data.get(self.offset..end));+ if bytes.is_none() {+ self.past_end.set(true);+ }++ bytes}/// Peeks a single byte.#[inline]pub fn peek_byte(&self) -> Option<u8> {- self.data.get(self.offset).copied()+ let byte = self.data.get(self.offset).copied();+ if byte.is_none() {+ self.past_end.set(true);+ }++ byte}/// Eat the next byte if it satisfies the condition.@@ -197,6 +239,7 @@ impl<'a> Reader<'a> {if cloned.peek_byte() == Some(b) {cloned.forward();} else {+ self.past_end.set(cloned.past_end.get());return None;}}diff --git a/vendor/hayro-syntax/src/content/mod.rs b/vendor/hayro-syntax/src/content/mod.rsindex ce0a4b56a..8e47324d0 100644--- a/vendor/hayro-syntax/src/content/mod.rs+++ b/vendor/hayro-syntax/src/content/mod.rs@@ -40,7 +40,7 @@ use crate::object::name::{Name, skip_name_like};use crate::object::{Array, Null, Number, Object, Stream};use crate::reader::Reader;use crate::reader::{Readable, ReaderContext, ReaderExt, Skippable};-use crate::trivia::is_white_space_character;+use crate::trivia::{Comment, is_white_space_character};use crate::util::find_needle;use core::array;use core::fmt::{Debug, Formatter};@@ -120,27 +120,40 @@ pub struct UntypedIter<'a> {/// PdfCraft patch: this iterator only checks whether data reads as content (the/// end-of-data heuristic below); inline images it meets end at their first `EI`.lookahead: bool,+ /// PdfCraft patch: whether `reader` holds the whole content stream. The end of a window of a+ /// longer stream can fall inside an instruction, so nothing that reads up to it is decided+ /// (see `needs_more`).+ complete: bool,+ /// PdfCraft patch: set when `next` stopped because the window ran out before the next+ /// instruction was decided. The caller reads more data and resumes at `committed`.+ needs_more: bool,+ /// PdfCraft patch: the offset just after the instruction `next` returned last.+ committed: usize,}impl<'a> UntypedIter<'a> {/// Create a new untyped iterator.pub fn new(data: &'a [u8]) -> Self {+ Self::new_window(data, true)+ }++ /// PdfCraft patch: an iterator over `data`, which is the whole stream when `complete`, and+ /// otherwise the start of a longer one.+ pub(crate) fn new_window(data: &'a [u8], complete: bool) -> Self {Self {reader: Reader::new(data),stack: Stack::new(),operator: None,lookahead: false,+ complete,+ needs_more: false,+ committed: 0,}}/// Create a new empty untyped iterator.pub fn empty() -> Self {- Self {- reader: Reader::new(&[]),- stack: Stack::new(),- operator: None,- lookahead: false,- }+ Self::new_window(&[], true)}/// Return the next instruction.@@ -148,8 +161,16 @@ impl<'a> UntypedIter<'a> {pub fn next(&mut self) -> Option<Instruction<'_, 'a>> {self.stack.clear();self.operator = None;+ self.needs_more = false;+ self.reader.clear_looked_past_end();- self.reader.skip_white_spaces_and_comments();+ if self.complete {+ self.reader.skip_white_spaces_and_comments();+ } else {+ // A window may drop what comes before the next instruction, blanks included, but not a+ // comment that the window ends in: that comment may go on in the next window.+ self.committed = self.skip_blanks_and_comments();+ }while !self.reader.at_end() {// I believe booleans/null never appear as an operator?@@ -165,35 +186,61 @@ impl<'a> UntypedIter<'a> {// similar behavior to Acrobat and Chromium, we try to consume// such an operator and then simply skip it.if let Some(object) = self.reader.read_without_context::<Object<'_>>() {+ if self.undecided() {+ return None;+ }self.stack.push(object)?;} else if self.reader.read_without_context::<Operator<'_>>().is_some() {+ if self.undecided() {+ return None;+ }self.stack.clear();} else {+ self.undecided();return None;}} else {let operator = match self.reader.read_without_context::<Operator<'_>>() {Some(o) => o,None => {+ if self.undecided() {+ return None;+ }+warn!("failed to read operator in content stream");self.reader.jump_to_end();return None;}};+ if self.undecided() {+ return None;+ }// Inline images need special casing...if operator.as_ref() == b"BI" {// The ID operator will already be consumed by this.- let inline_dict = self.reader.read_without_context::<InlineImageDict<'_>>()?;+ let Some(inline_dict) = self+ .reader+ .read_without_context::<InlineImageDict<'_>>()+ else {+ self.undecided();+ return None;+ };let dict = inline_dict.get_dict().clone();// One whitespace after "ID".- self.reader.read_white_space()?;+ if self.reader.read_white_space().is_none() {+ self.undecided();+ return None;+ }let stream_data = self.reader.tail()?;let start_offset = self.reader.offset();let mut candidates = 0;+ // PdfCraft patch: set when a look-ahead below ran into the end of the window.+ let mut lookahead_touched = false;+ let mut accepted = false;'outer: while let Some(pos) = find_needle(self.reader.tail()?, b"EI") {self.reader.read_bytes(pos)?;@@ -228,7 +275,11 @@ impl<'a> UntypedIter<'a> {let mut steps = 0;let heuristic = !self.lookahead && candidates <= MAX_EI_CANDIDATES;- while heuristic && !find_reader.at_end() && steps < MAX_EI_LOOKAHEAD_STEPS {+ while heuristic && steps < MAX_EI_LOOKAHEAD_STEPS {+ if find_reader.at_end() {+ lookahead_touched = true;+ break;+ }steps += 1;let remaining = find_reader.tail()?;let next_ei = find_needle(remaining, b"EI");@@ -239,7 +290,10 @@ impl<'a> UntypedIter<'a> {(Some(_), Some(bi)) => (bi, false),(Some(ei), None) => (ei, true),(None, Some(bi)) => (bi, false),- (None, None) => break,+ (None, None) => {+ lookahead_touched = true;+ break;+ }};find_reader.read_bytes(next_pos)?;@@ -262,7 +316,10 @@ impl<'a> UntypedIter<'a> {// stream and there should be at least one text-related// operator that can be parsed correctly.- let mut iter = TypedIter::from_untyped(UntypedIter { lookahead: true, ..UntypedIter::new(tail) });+ let mut iter = TypedIter::from_untyped(UntypedIter {+ lookahead: true,+ ..UntypedIter::new_window(tail, self.complete)+ });let mut found = false;let mut counter = 0;@@ -292,6 +349,8 @@ impl<'a> UntypedIter<'a> {counter += 1;}+ lookahead_touched |=+ iter.needs_more() || iter.untyped.reader.looked_past_end();if !found {// Seems like the data in-between is not a valid content@@ -304,10 +363,11 @@ impl<'a> UntypedIter<'a> {// is indeed the end of data.let mut cloned = find_reader.clone();cloned.read_bytes(2)?;- if cloned+ let is_inline_image_dict = cloned.read_without_context::<InlineImageDict<'_>>()- .is_some()- {+ .is_some();+ lookahead_touched |= cloned.looked_past_end();+ if is_inline_image_dict {break;}}@@ -315,17 +375,35 @@ impl<'a> UntypedIter<'a> {find_reader.read_byte()?;}+ // PdfCraft patch: the end is only certain if no look-ahead needed bytes+ // past the window. Otherwise read more and decide again.+ if !self.complete+ && (lookahead_touched || self.reader.looked_past_end())+ {+ self.needs_more = true;+ return None;+ }+self.stack.push(Object::Stream(stream))?;self.reader.read_bytes(2)?;self.reader.skip_white_spaces();+ accepted = true;+break;}}++ // PdfCraft patch: without an accepted "EI" the image may still end in later data.+ if !accepted && !self.complete {+ self.needs_more = true;+ return None;+ }}self.operator = Some(operator);+ self.committed = self.reader.offset();return Some(Instruction {operands: &self.stack,operator: self.operator.as_ref().unwrap(),@@ -335,8 +413,43 @@ impl<'a> UntypedIter<'a> {self.reader.skip_white_spaces_and_comments();}+ // PdfCraft patch: the window ended between instructions, and another may follow.+ if !self.complete {+ self.needs_more = true;+ }+None}++ /// PdfCraft patch: skips the blanks and comments before an instruction, as+ /// `skip_white_spaces_and_comments` does, and returns where a window may be cut: the start of a+ /// comment that runs into the end of the window, or else where the skipping stopped.+ fn skip_blanks_and_comments(&mut self) -> usize {+ let mut open_comment = None;+ while let Some(b) = self.reader.peek_byte() {+ if is_white_space_character(b) {+ self.reader.skip_white_spaces();+ } else if b == b'%' {+ let start = self.reader.offset();+ Comment::skip(&mut self.reader, true);+ open_comment = self.reader.at_end().then_some(start);+ } else {+ break;+ }+ }++ open_comment.unwrap_or(self.reader.offset())+ }++ /// PdfCraft patch: whether the instruction being read ran into the end of a window, so it+ /// cannot be decided yet. Records that more data is needed.+ fn undecided(&mut self) -> bool {+ if !self.complete && self.reader.looked_past_end() {+ self.needs_more = true;+ }++ self.needs_more+ }}impl<'a> ContentTokenizer<'a> for UntypedIter<'a> {@@ -345,6 +458,7 @@ impl<'a> ContentTokenizer<'a> for UntypedIter<'a> {}}+/// An iterator over PDF content streams that provide access to the instructions/// in a typed fashion.#[derive(Clone)]@@ -362,6 +476,27 @@ impl<'a> TypedIter<'a, UntypedIter<'a>> {}}+ /// PdfCraft patch: an iterator over a window of a content stream: the whole stream when+ /// `complete`, and otherwise the start of a longer one (see [`TypedIter::needs_more`]).+ pub fn new_window(data: &'a [u8], complete: bool) -> Self {+ Self {+ untyped: UntypedIter::new_window(data, complete),+ marker: PhantomData,+ }+ }++ /// PdfCraft patch: whether the last `next` returned `None` only because the window ran out+ /// before the next instruction was decided. Read more of the stream, then resume at+ /// [`TypedIter::committed`] in a window that starts there.+ pub fn needs_more(&self) -> bool {+ self.untyped.needs_more+ }++ /// PdfCraft patch: the offset in the window just after the last instruction `next` returned.+ pub fn committed(&self) -> usize {+ self.untyped.committed+ }+pub(crate) fn from_untyped(untyped: UntypedIter<'a>) -> Self {Self { untyped, marker: PhantomData }}@@ -749,4 +884,134 @@ mod tests {assert_eq!(operators(&joined), expected, "split at byte {split}");}}++ /// The instructions of `data`, read from the whole of it.+ fn slice_instructions(data: &[u8]) -> Vec<String> {+ let mut tokenizer = UntypedIter::new(data);+ let mut result = Vec::new();+ while let Some(instruction) = tokenizer.next_instruction() {+ result.push(format!("{:?} {:?}", instruction.operator, instruction.operands));+ }+ result+ }++ /// The instructions of `data` as a window driver reads them: the stream arrives in pieces of+ /// the lengths `next_piece` gives. Each window holds the bytes from the first instruction+ /// that is not yet decided, and another piece is appended when a window runs out.+ fn windowed_instructions(data: &[u8], mut next_piece: impl FnMut() -> usize) -> Vec<String> {+ let mut result = Vec::new();+ let mut window: Vec<u8> = Vec::new();+ let mut fed = 0;+ let mut exhausted = false;+ loop {+ let (committed, needs_more) = {+ let mut tokenizer = UntypedIter::new_window(&window, exhausted);+ while let Some(instruction) = tokenizer.next_instruction() {+ result.push(format!("{:?} {:?}", instruction.operator, instruction.operands));+ }+ (tokenizer.committed, tokenizer.needs_more)+ };+ window.drain(..committed);+ if !needs_more || exhausted {+ break;+ }+ if fed == data.len() {+ exhausted = true;+ continue;+ }+ let end = fed.saturating_add(next_piece().max(1)).min(data.len());+ window.extend_from_slice(&data[fed..end]);+ fed = end;+ }++ result+ }++ /// Content whose instructions are hard to read in pieces: inline images with `EI` in their+ /// data or right after it, unterminated tokens, and operands that are too many or invalid.+ const WINDOWED_CORPUS: [&[u8]; 14] = [+ b"% comment\n1 -2.5 /Name /A#20B (a\\(b\\) \\101) <4869> [1 2] << /Key (value) >> [(a) 1] TJ BI /W 1 /H 1 /BPC 8 /CS /DeviceGray ID \x00 EI q Q",+ b"BT /F1 12 Tf 10 20 Td [(Hel) -250 (lo)] TJ (x) Tj ET",+ b"q 1 0 0 1 0 0 cm BI /W 2 /H 2 /BPC 8 /CS /G ID \x00\x01EI\x00 EI Q 0 0 m 1 1 l S",+ b"BI /W 1 /H 1 /BPC 8 /CS /G ID EI x EI EI BT (a) Tj ET",+ b"0.5 .5 -.5 +5 12.3.4 f",+ b"/A B C /D 1 2 3 4 5 6 7 8 9 10 11 12 re",+ b"BI /W 1 /H 1 /BPC 8 /CS /G ID\n\x00\nEI BI /W 1 /H 1 /BPC 8 /CS /G ID \x01 EI Q",+ b"(unterminated string 1 0 0 1 0 0 cm",+ b"1 0 0 1 0 0 cm\n%comment at the end",+ b"BI /W 1 /H 1 /BPC 8 /CS /G ID \x00 EIxy q",+ b"BI /W 2 /H 1 /BPC 8 /CS /G ID \x00\x01 EI \x00 EI \x01 q",+ b"[1 [2 [3]]] 0 d q Q",+ b"/Lbl BDC EMC 1 w",+ b"<</A 1>> BDC BI /W 1 /H 1 /BPC 8 /CS /G ID \x07 EI (end) Tj",+ ];++ #[test]+ fn windows_keep_every_instruction_at_every_split() {+ for data in WINDOWED_CORPUS {+ let expected = slice_instructions(data);+ for split in 1..=data.len() {+ let mut lengths = [split, data.len()].into_iter();+ let windowed = windowed_instructions(data, || lengths.next().unwrap_or(data.len()));+ assert_eq!(windowed, expected, "{:?} split at byte {split}", String::from_utf8_lossy(data));+ }+ }+ }++ #[test]+ fn windows_keep_every_instruction_in_pieces_of_any_size() {+ for data in WINDOWED_CORPUS {+ let expected = slice_instructions(data);+ for piece in 1..=data.len() {+ let windowed = windowed_instructions(data, || piece);+ assert_eq!(windowed, expected, "{:?} in pieces of {piece}", String::from_utf8_lossy(data));+ }+ }+ }++ #[test]+ fn windows_drop_blanks_and_keep_a_comment_that_may_go_on() {+ // Blanks alone decide nothing, so a window of them can be dropped whole.+ let blanks = vec![b' '; 4096];+ let mut tokenizer = UntypedIter::new_window(&blanks, false);+ assert!(tokenizer.next().is_none());+ assert!(tokenizer.needs_more);+ assert_eq!(tokenizer.committed, blanks.len());++ // The window ends in a comment: it is kept, from its `%`, for the next window.+ let data = b"1 0 0 1 0 0 cm % a comment that goes on";+ let mut tokenizer = UntypedIter::new_window(data, false);+ assert!(tokenizer.next().is_some());+ assert!(tokenizer.next().is_none());+ assert!(tokenizer.needs_more);+ assert_eq!(tokenizer.committed, data.iter().position(|&b| b == b'%').expect("a comment"));+ }++ #[test]+ fn windows_match_the_slice_on_random_content() {+ const PARTS: [&[u8]; 24] = [+ b"BI", b" ID ", b"EI", b" EI ", b"/W", b" 1 ", b"-2.5", b".5", b"(", b")", b"\\", b"<",+ b">", b"[", b"]", b"TJ", b"Tj", b"q", b"Q", b"re", b"f", b"% c\n", b"\n", b"\x00\xff",+ ];+ // A fixed xorshift sequence, so that a failure can be reproduced.+ let mut state = 0x9e37_79b9_7f4a_7c15_u64;+ let mut next = move || {+ state ^= state << 13;+ state ^= state >> 7;+ state ^= state << 17;+ state+ };++ for _ in 0..2000 {+ let mut data = Vec::new();+ for _ in 0..next() % 40 {+ let part = PARTS[(next() % PARTS.len() as u64) as usize];+ data.extend_from_slice(part);+ }++ let expected = slice_instructions(&data);+ let windowed = windowed_instructions(&data, || 1 + (next() % 12) as usize);+ assert_eq!(windowed, expected, "{:?}", String::from_utf8_lossy(&data));+ }+ }}diff --git a/vendor/hayro-syntax/src/filter/lzw_flate.rs b/vendor/hayro-syntax/src/filter/lzw_flate.rsindex c82bc033d..ac1c19d6c 100644--- a/vendor/hayro-syntax/src/filter/lzw_flate.rs+++ b/vendor/hayro-syntax/src/filter/lzw_flate.rs@@ -7,6 +7,14 @@ use alloc::vec::Vec;pub(crate) mod flate {use super::*;use crate::filter::lzw_flate::{PredictorParams, apply_predictor};++ pub(crate) use fallback::FlateState;++ /// PdfCraft patch: whether a Flate stream with `params` has no predictor, so that+ /// [`FlateState`] can produce it a piece at a time.+ pub(crate) fn is_plain(params: &Dict<'_>) -> bool {+ PredictorParams::from_params(params).predictor == 1+ }use crate::object::Dict;/// PdfCraft patch: `limit` is the most bytes inflated (see `filter::decode_limit`).@@ -69,53 +77,148 @@ pub(crate) mod flate {}fn flate_decode(data: &[u8], limit: usize) -> Option<Vec<u8>> {- if data.len() >= 2 {- let cmf = data[0];- let flg = data[1];-- if (cmf & 0x0f) == 0x08- && ((cmf as u16) << 8 | flg as u16).is_multiple_of(31)- && (flg & 0x20) == 0- {- let mut stream = FlateStream::new(&data[2..], limit);- return stream.decode();+ let mut state = FlateState::new(data);+ let mut output = Vec::new();+ state.decode_into(data, &mut output, limit);++ Some(output)+ }++ /// PdfCraft patch: where a Flate stream is between two calls of [`FlateState::decode_into`].+ /// Decoding pauses at any output size and resumes where it stopped, so a stream can be+ /// produced a piece at a time without holding all of it.+ #[derive(Default)]+ pub(crate) struct FlateState {+ pos: usize,+ code_buf: u32,+ code_size: u8,+ eof: bool,+ block: Block,+ /// The last `WINDOW` bytes decoded: back-references copy from them, whatever the caller+ /// has done with the bytes it was given.+ history: Vec<u8>,+ /// How many bytes have been decoded in all.+ total: usize,+ }++ /// The furthest a Flate back-reference reaches: the largest distance in `DIST_DECODE`.+ const WINDOW: usize = 32 << 10;++ impl FlateState {+ /// The state at the start of `data`, past a zlib header if it has one.+ pub(crate) fn new(data: &[u8]) -> Self {+ let pos = match data {+ [cmf, flg, ..]+ if (cmf & 0x0f) == 0x08+ && (u16::from(*cmf) << 8 | u16::from(*flg)).is_multiple_of(31)+ && (flg & 0x20) == 0 =>+ {+ 2+ }+ _ => 0,+ };++ Self {+ pos,+ ..Self::default()}}- let mut stream = FlateStream::new(data, limit);- stream.decode()+ /// Whether nothing more can be decoded from `data`.+ pub(crate) fn finished(&self, data: &[u8]) -> bool {+ self.eof || (matches!(self.block, Block::Header) && self.pos >= data.len())+ }++ /// Appends decoded bytes to `out` until it holds `until` bytes or the stream ends.+ /// `data` is the whole encoded stream, the same on every call.+ pub(crate) fn decode_into(&mut self, data: &[u8], out: &mut Vec<u8>, until: usize) {+ // The working buffer is the history followed by the bytes decoded now. Only the+ // latter go to `out`, which the caller may have drained since.+ let base = self.history.len();+ let mut stream = FlateStream {+ data,+ pos: self.pos,+ code_buf: self.code_buf,+ code_size: self.code_size,+ output: core::mem::take(&mut self.history),+ base,+ total: self.total,+ eof: self.eof,+ limit: base.saturating_add(until.saturating_sub(out.len())),+ block: core::mem::take(&mut self.block),+ };+ stream.run();++ out.extend_from_slice(stream.output.get(base..).unwrap_or(&[]));+ self.total = self.total.saturating_add(stream.output.len() - base);+ let keep = stream.output.len().min(WINDOW);+ stream.output.drain(..stream.output.len() - keep);+ self.history = stream.output;++ self.pos = stream.pos;+ self.code_buf = stream.code_buf;+ self.code_size = stream.code_size;+ self.eof = stream.eof;+ self.block = stream.block;+ }}+ /// PdfCraft patch: the working state of one [`FlateState::decode_into`] call.struct FlateStream<'a> {data: &'a [u8],pos: usize,code_buf: u32,code_size: u8,+ /// The history, then the bytes decoded in this call.output: Vec<u8>,+ /// How many bytes of `output` are history.+ base: usize,+ /// How many bytes were decoded before this call.+ total: usize,eof: bool,- /// PdfCraft patch: the most bytes inflated (see `filter::decode_limit`).+ /// PdfCraft patch: the most bytes in `output` (see `filter::decode_limit`).limit: usize,+ block: Block,}- impl<'a> FlateStream<'a> {- fn new(data: &'a [u8], limit: usize) -> Self {- FlateStream {- data,- pos: 0,- code_buf: 0,- code_size: 0,- output: Vec::new(),- eof: false,- limit,- }- }+ /// PdfCraft patch: the block a Flate stream is in.+ #[derive(Default)]+ enum Block {+ /// Between blocks, at a block header (or at the end of the data).+ #[default]+ Header,+ /// Inside a stored block, with `left` bytes still to copy.+ Stored { left: usize, last: bool },+ /// Inside a block coded with Huffman tables. `copy` is a back-reference that the limit+ /// cut off, as (whether its source exists, distance, bytes left to copy).+ Coded {+ lit: HuffmanTable,+ dist: HuffmanTable,+ last: bool,+ copy: Option<(bool, usize, usize)>,+ },+ }- fn decode(&mut self) -> Option<Vec<u8>> {- while !self.eof && self.pos < self.data.len() && self.output.len() < self.limit {- self.read_block();- }+ impl FlateStream<'_> {+ /// Decodes until `output` holds `limit` bytes or the stream ends.+ fn run(&mut self) {+ loop {+ if self.eof || self.output.len() >= self.limit {+ return;+ }- Some(core::mem::take(&mut self.output))+ match self.block {+ Block::Header => {+ if self.pos >= self.data.len() {+ return;+ }++ self.read_block();+ }+ Block::Stored { .. } => self.copy_stored(),+ Block::Coded { .. } => self.read_codes(),+ }+ }}fn get_byte(&mut self) -> Option<u8> {@@ -136,13 +239,6 @@ pub(crate) mod flate {}}- fn get_bytes(&mut self, n: usize) -> Vec<u8> {- let end = (self.pos + n).min(self.data.len());- let bytes = self.data[self.pos..end].to_vec();- self.pos = end;- bytes- }-fn get_bits(&mut self, bits: u8) -> Option<u32> {while self.code_size < bits {let b = self.get_byte()?;@@ -196,16 +292,16 @@ pub(crate) mod flate {}};- if (hdr & 1) != 0 {- self.eof = true;- }+ // PdfCraft patch: the final block ends the stream once it is decoded, not when its+ // header is read: a stored block still has its bytes to copy.+ let last = (hdr & 1) != 0;let hdr = hdr >> 1;match hdr {- 0 => self.read_uncompressed_block(),- 1 => self.read_compressed_block(true),- 2 => self.read_compressed_block(false),+ 0 => self.start_uncompressed_block(last),+ 1 => self.start_compressed_block(true, last),+ 2 => self.start_compressed_block(false, last),_ => {warn!("unknown block type in flate stream");self.eof = true;@@ -213,7 +309,7 @@ pub(crate) mod flate {}}- fn read_uncompressed_block(&mut self) {+ fn start_uncompressed_block(&mut self, last: bool) {// Skip any remaining bits in current byteself.code_buf = 0;self.code_size = 0;@@ -264,22 +360,49 @@ pub(crate) mod flate {}if block_len == 0 {- if self.peek_byte().is_none() {+ if last || self.peek_byte().is_none() {self.eof = true;}} else {- let block = self.get_bytes(block_len as usize);- // PdfCraft patch: never past `limit`.- let left = self.limit.saturating_sub(self.output.len());+ self.block = Block::Stored {+ left: usize::from(block_len),+ last,+ };+ }+ }++ /// Copies the stored block's bytes, up to the limit or the end of the data.+ fn copy_stored(&mut self) {+ let Block::Stored { mut left, last } = self.block else {+ return;+ };++ while left > 0 && self.output.len() < self.limit {+ let rest = self.data.get(self.pos..).unwrap_or(&[]);+ if rest.is_empty() {+ // Premature end of stream: the rest of the block is missing.+ self.eof = true;+ return;+ }++ let take = left.min(rest.len()).min(self.limit - self.output.len());self.output- .extend_from_slice(block.get(..block.len().min(left)).unwrap_or(&[]));- if block.len() < block_len as usize {+ .extend_from_slice(rest.get(..take).unwrap_or(&[]));+ self.pos += take;+ left -= take;+ }++ if left > 0 {+ self.block = Block::Stored { left, last };+ } else {+ self.block = Block::Header;+ if last {self.eof = true;}}}- fn read_compressed_block(&mut self, fixed: bool) {+ fn start_compressed_block(&mut self, fixed: bool, last: bool) {let (lit_code_table, dist_code_table) = if fixed {(get_fixed_lit_table(), get_fixed_dist_table())} else {@@ -292,11 +415,54 @@ pub(crate) mod flate {}};+ self.block = Block::Coded {+ lit: lit_code_table,+ dist: dist_code_table,+ last,+ copy: None,+ };+ }++ /// Decodes the codes of a Huffman-coded block until its end, the limit or the end of+ /// the data.+ fn read_codes(&mut self) {+ let Block::Coded {+ lit: lit_code_table,+ dist: dist_code_table,+ last,+ mut copy,+ } = core::mem::take(&mut self.block)+ else {+ return;+ };+loop {+ if let Some((valid, distance, left)) = copy {+ let left = self.copy_back(valid, distance, left);+ if left > 0 {+ // The limit cut the copy short: it resumes on the next call.+ self.block = Block::Coded {+ lit: lit_code_table,+ dist: dist_code_table,+ last,+ copy: Some((valid, distance, left)),+ };+ return;+ }+ copy = None;+ }+// PdfCraft patch: one code adds at most 258 bytes; stop at the limit.if self.output.len() >= self.limit {+ self.block = Block::Coded {+ lit: lit_code_table,+ dist: dist_code_table,+ last,+ copy,+ };return;}+let code1 = match self.get_code(&lit_code_table) {Some(c) => c,None => {@@ -308,6 +474,9 @@ pub(crate) mod flate {if code1 < 256 {self.output.push(code1 as u8);} else if code1 == 256 {+ if last {+ self.eof = true;+ }return;} else {let code1 = code1 - 257;@@ -354,20 +523,34 @@ pub(crate) mod flate {}}- // Copy from previous output- let start = self.output.len().wrapping_sub(distance);- for _ in 0..length {- // PdfCraft patch: never past `limit`.- if self.output.len() >= self.limit {- return;- }- if start < self.output.len() {- let byte = self.output[self.output.len() - distance];- self.output.push(byte);- }+ // Copy from previous output. As before, a distance reaching before the first+ // byte decoded copies nothing.+ let decoded = self.total.saturating_add(self.output.len().saturating_sub(self.base));+ let valid = distance > 0 && distance <= decoded;+ copy = Some((valid, distance, length));+ }+ }+ }++ /// Copies `left` bytes from `distance` back in the output, up to the limit. Returns how+ /// many are still to copy. A copy whose source does not exist writes nothing.+ fn copy_back(&mut self, valid: bool, distance: usize, mut left: usize) -> usize {+ while left > 0 && self.output.len() < self.limit {+ if valid {+ let byte = self+ .output+ .len()+ .checked_sub(distance)+ .and_then(|index| self.output.get(index))+ .copied();+ if let Some(byte) = byte {+ self.output.push(byte);}}+ left -= 1;}++ left}fn read_dynamic_tables(&mut self) -> Option<(HuffmanTable, HuffmanTable)> {diff --git a/vendor/hayro-syntax/src/filter/mod.rs b/vendor/hayro-syntax/src/filter/mod.rsindex e5353f355..22bebf6d3 100644--- a/vendor/hayro-syntax/src/filter/mod.rs+++ b/vendor/hayro-syntax/src/filter/mod.rs@@ -13,6 +13,9 @@ mod jpx;mod lzw_flate;mod run_length;+// PdfCraft patch: the incremental Flate decoder that `page::ContentReader` drives.+pub(crate) use lzw_flate::flate::{FlateState, is_plain as flate_is_plain};+use crate::object::Dict;use crate::object::Name;use crate::object::dict::keys::*;diff --git a/vendor/hayro-syntax/src/object/mod.rs b/vendor/hayro-syntax/src/object/mod.rsindex d9b4816de..d692db8b3 100644--- a/vendor/hayro-syntax/src/object/mod.rs+++ b/vendor/hayro-syntax/src/object/mod.rs@@ -189,10 +189,14 @@ impl<'a> Readable<'a> for Object<'a> {b'<' => match r.peek_bytes(2)? {b"<<" => {let mut cloned = r.clone();- let dict = Dict::read(&mut cloned, ctx)?;+ let dict = Dict::read(&mut cloned, ctx);cloned.skip_white_spaces_and_comments();+ let is_stream = cloned.forward_tag(b"stream").is_some();+ // PdfCraft patch: what the clone looked at past the end counts for `r` too.+ r.absorb_past_end(&cloned);+ let dict = dict?;- if cloned.forward_tag(b"stream").is_some() {+ if is_stream {Object::Stream(Stream::read(r, ctx)?)} else {r.jump(cloned.offset());diff --git a/vendor/hayro-syntax/src/object/stream.rs b/vendor/hayro-syntax/src/object/stream.rsindex f48566825..833610817 100644--- a/vendor/hayro-syntax/src/object/stream.rs+++ b/vendor/hayro-syntax/src/object/stream.rs@@ -22,6 +22,16 @@ struct FiltersAndParams<'a> {params: SmallVec<[Dict<'a>; 2]>,}+/// PdfCraft patch: how the decoded data of a stream can be produced (see `Stream::incremental`).+pub(crate) enum Incremental {+ /// The stream has no filter, so its data is its own bytes.+ Plain,+ /// The stream is Flate-compressed without a predictor, so it decodes a piece at a time.+ Flate,+ /// Anything else decodes whole.+ Whole,+}+/// A stream of arbitrary data.#[derive(Clone)]pub struct Stream<'a> {@@ -152,6 +162,22 @@ impl<'a> Stream<'a> {self.filters_and_params().filters}+ /// PdfCraft patch: how the decoded data of the stream can be produced a piece at a time.+ pub(crate) fn incremental(&self) -> Incremental {+ let filters_and_params = self.filters_and_params();++ match (+ filters_and_params.filters.as_slice(),+ filters_and_params.params.first(),+ ) {+ ([], _) => Incremental::Plain,+ ([Filter::FlateDecode], Some(params)) if crate::filter::flate_is_plain(params) => {+ Incremental::Flate+ }+ _ => Incremental::Whole,+ }+ }+/// Return the decoded data of the stream.////// Note that the result of this method will not be cached, so calling it multiple@@ -185,7 +211,25 @@ impl<'a> Stream<'a> {image_params: &ImageDecodeParams,max: usize,) -> Result<FilterResult<'a>, DecodeFailure> {- let data = self.raw_data();+ self.decode_raw_within(self.raw_data(), image_params, max)+ }++ /// PdfCraft patch: decode caller-supplied raw/decrypted bytes with the same filters and limits.+ pub(crate) fn decoded_raw_within(+ &self,+ data: Cow<'a, [u8]>,+ max: usize,+ ) -> Result<Cow<'a, [u8]>, DecodeFailure> {+ self.decode_raw_within(data, &ImageDecodeParams::default(), max)+ .map(|r| r.data)+ }++ fn decode_raw_within(+ &self,+ data: Cow<'a, [u8]>,+ image_params: &ImageDecodeParams,+ max: usize,+ ) -> Result<FilterResult<'a>, DecodeFailure> {let filters_and_params = self.filters_and_params();let count = filters_and_params.filters.len();diff --git a/vendor/hayro-syntax/src/page.rs b/vendor/hayro-syntax/src/page.rsindex 2aed89633..7d63931a3 100644--- a/vendor/hayro-syntax/src/page.rs+++ b/vendor/hayro-syntax/src/page.rs@@ -13,8 +13,11 @@ use crate::sync::OnceLock;use crate::transform::Transform;use crate::util::FloatExt;use crate::xref::XRef;+use crate::filter::{FlateState, MAX_DECODED_STREAM};+use crate::object::stream::Incremental;+use alloc::borrow::Cow;use alloc::boxed::Box;-use alloc::collections::BTreeSet;+use alloc::collections::{BTreeSet, VecDeque};use crate::object::ObjectIdentifier;use alloc::vec;use alloc::vec::Vec;@@ -183,6 +186,198 @@ pub enum Rotation {FlippedHorizontal,}+/// PdfCraft patch: the cut-off for content that expands from its compressed streams. The decoded+/// content of a page may be `MAX_CONTENT_EXPANSION` times the size of those streams, and never less+/// than `MAX_DECODED_STREAM`. Real content expands a few times, and a stream that inflates a+/// thousandfold from a few kilobytes is a decompression bomb.+const MAX_CONTENT_EXPANSION: usize = 64;++/// PdfCraft patch: the decoded content of a page, produced a piece at a time, so that the whole of+/// it need not be in memory at once (see `interpret_page`). Plain streams and Flate streams without+/// a predictor are decoded as they are read. Any other stream is decoded whole when the reader is+/// made, as `page_stream` does, and the decoded streams share one `MAX_DECODED_STREAM`.+///+/// The decoded bytes of the page's streams are also cut off at a budget: `MAX_CONTENT_EXPANSION`+/// times their compressed size, counting each distinct stream once however many times `/Contents`+/// names it. Content that reaches the budget is cut short, and [`ContentReader::truncated`] says so.+pub struct ContentReader<'a> {+ pieces: VecDeque<Piece<'a>>,+ budget: usize,+ produced: usize,+ materialized: usize,+ truncated: bool,+}++/// One part of the content of a page, in order.+enum Piece<'a> {+ /// A stream's own bytes, which are not decoded.+ Plain { data: Cow<'a, [u8]>, pos: usize },+ /// A Flate stream, decoded as it is read.+ Flate { data: Cow<'a, [u8]>, state: FlateState },+ /// A stream that was decoded whole.+ Whole { data: Vec<u8>, pos: usize },+ /// The space that separates the streams of a `/Contents` array.+ Separator { written: bool },+}++impl Piece<'_> {+ fn exhausted(&self) -> bool {+ match self {+ Piece::Plain { data, pos } => *pos >= data.len(),+ Piece::Flate { data, state } => state.finished(data),+ Piece::Whole { data, pos } => *pos >= data.len(),+ Piece::Separator { written } => *written,+ }+ }++ /// Appends the next bytes of the piece to `out`, which may end at `limit` bytes.+ fn append_to(&mut self, out: &mut Vec<u8>, limit: usize) {+ match self {+ Piece::Plain { data, pos } => copy_from(data, pos, out, limit),+ Piece::Flate { data, state } => state.decode_into(data, out, limit),+ Piece::Whole { data, pos } => copy_from(data, pos, out, limit),+ Piece::Separator { written } => {+ out.push(b' ');+ *written = true;+ }+ }+ }+}++/// Copies the bytes of `data` from `pos` to `out`, up to `limit` bytes in all.+fn copy_from(data: &[u8], pos: &mut usize, out: &mut Vec<u8>, limit: usize) {+ let rest = data.get(*pos..).unwrap_or(&[]);+ let take = rest.len().min(limit.saturating_sub(out.len()));+ out.extend_from_slice(rest.get(..take).unwrap_or(&[]));+ *pos += take;+}++impl<'a> ContentReader<'a> {+ /// A reader of no content.+ fn empty() -> Self {+ Self {+ pieces: VecDeque::new(),+ budget: 0,+ produced: 0,+ materialized: 0,+ truncated: false,+ }+ }++ /// A reader of `streams`, the content of a page in order. `separated` says whether they come+ /// from an array, whose streams are separated by spaces. `cap` is the most bytes that streams+ /// decoded whole may make in all, and at least the budget's floor.+ fn new(streams: Vec<Stream<'a>>, separated: bool, cap: usize) -> Self {+ let mut counted = BTreeSet::new();+ let mut compressed = 0_usize;+ let mut pieces = VecDeque::new();+ let mut materialized = 0_usize;+ // The bytes that the streams decoded whole take up, separators included, as `page_stream`+ // counted them against `MAX_DECODED_STREAM`.+ let mut whole_used = 0_usize;+ let mut accepting_pieces = true;+ for stream in streams {+ let newly_counted = counted.insert(stream.obj_id());+ if !accepting_pieces {+ if newly_counted {+ compressed = compressed.saturating_add(stream.raw_data().len());+ }+ continue;+ }++ let incremental = stream.incremental();+ let left = cap.saturating_sub(whole_used);+ if matches!(&incremental, Incremental::Whole) && left == 0 {+ accepting_pieces = false;+ if newly_counted {+ compressed = compressed.saturating_add(stream.raw_data().len());+ }+ continue;+ }++ let raw = stream.raw_data();+ if newly_counted {+ compressed = compressed.saturating_add(raw.len());+ }++ match incremental {+ Incremental::Plain => pieces.push_back(Piece::Plain {+ data: raw,+ pos: 0,+ }),+ Incremental::Flate => {+ let state = FlateState::new(&raw);+ pieces.push_back(Piece::Flate { data: raw, state });+ }+ Incremental::Whole => {+ let Ok(data) = stream.decoded_raw_within(raw, left) else {+ continue;+ };+ let data = data.into_owned();+ whole_used = whole_used.saturating_add(data.len());+ materialized = materialized.saturating_add(data.len());+ pieces.push_back(Piece::Whole { data, pos: 0 });+ }+ }++ if separated {+ whole_used = whole_used.saturating_add(1);+ pieces.push_back(Piece::Separator { written: false });+ }+ }+ let budget = cap.max(MAX_CONTENT_EXPANSION.saturating_mul(compressed));++ Self {+ pieces,+ budget,+ produced: 0,+ materialized,+ truncated: false,+ }+ }++ /// Appends up to `max` bytes of the decoded content to `out`, and returns how many it appended.+ /// That is fewer than `max` only at the end of the content, or where it is cut short.+ pub fn read_into(&mut self, out: &mut Vec<u8>, max: usize) -> usize {+ let start = out.len();+ let end = start.saturating_add(max);++ while out.len() < end {+ let Some(piece) = self.pieces.front_mut() else {+ break;+ };+ if piece.exhausted() {+ self.pieces.pop_front();+ continue;+ }++ let allowed = self.budget.saturating_sub(self.produced);+ if allowed == 0 {+ self.truncated = true;+ self.pieces.clear();+ break;+ }++ let before = out.len();+ piece.append_to(out, end.min(before.saturating_add(allowed)));+ self.produced += out.len() - before;+ }++ out.len() - start+ }++ /// The bytes of the content that were decoded whole when the reader was made. The caller+ /// charges these against its own budget, as it did for the whole content.+ pub fn materialized_len(&self) -> usize {+ self.materialized+ }++ /// Whether the content was cut short at its budget (see [`ContentReader`]).+ pub fn truncated(&self) -> bool {+ self.truncated+ }+}+/// A PDF page.pub struct Page<'a> {inner: Dict<'a>,@@ -260,6 +455,25 @@ impl<'a> Page<'a> {Some(iter)}+ /// PdfCraft patch: the content of the page, to be read a piece at a time (see+ /// [`ContentReader`]).+ pub fn content_reader(&self) -> ContentReader<'a> {+ self.content_reader_within(MAX_DECODED_STREAM)+ }++ /// PdfCraft patch: [`Page::content_reader`], with `cap` in place of `MAX_DECODED_STREAM`.+ fn content_reader_within(&self, cap: usize) -> ContentReader<'a> {+ if let Some(stream) = self.inner.get::<Stream<'a>>(CONTENTS) {+ ContentReader::new(vec![stream], false, cap)+ } else if let Some(array) = self.inner.get::<Array<'a>>(CONTENTS) {+ ContentReader::new(array.iter::<Stream<'a>>().collect(), true, cap)+ } else {+ warn!("contents entry of page was neither stream nor array of streams");++ ContentReader::empty()+ }+ }+/// Return the decoded content stream of the page.pub fn page_stream(&self) -> Option<&[u8]> {let convert_single = |s: Stream<'_>| {@@ -279,8 +493,7 @@ impl<'a> Page<'a> {for stream in array.iter::<Stream<'_>>() {// PdfCraft patch: the streams share one `MAX_DECODED_STREAM` (an array// naming one inflating stream twenty times decoded 5 GB).- let left =- crate::filter::MAX_DECODED_STREAM.saturating_sub(collected.len());+ let left = MAX_DECODED_STREAM.saturating_sub(collected.len());if left == 0 {break;}@@ -606,3 +819,240 @@ pub(crate) mod cached {}}}++#[cfg(test)]+mod content_reader_tests {+ use crate::Pdf;++ /// A zlib stream of `data` in stored blocks, which expands by nothing.+ fn stored_zlib(data: &[u8]) -> Vec<u8> {+ let mut out = vec![0x78, 0x01];+ let mut chunks = data.chunks(0xffff).peekable();+ if chunks.peek().is_none() {+ out.extend_from_slice(&[1, 0, 0, 0xff, 0xff]);+ }+ while let Some(chunk) = chunks.next() {+ out.push(u8::from(chunks.peek().is_none()));+ let len = u16::try_from(chunk.len()).expect("a stored block holds at most 65535 bytes");+ out.extend_from_slice(&len.to_le_bytes());+ out.extend_from_slice(&(!len).to_le_bytes());+ out.extend_from_slice(chunk);+ }+ out.extend_from_slice(&[0; 4]);+ out+ }++ /// A zlib stream of one literal byte and then `count` copies of a 258-byte match from it, in+ /// fixed Huffman codes: about 160 bytes of output for each byte of input.+ fn fixed_run_bomb(count: usize) -> Vec<u8> {+ struct Bits {+ out: Vec<u8>,+ buf: u8,+ len: u32,+ }+ impl Bits {+ /// Bits are sent least significant first.+ fn put(&mut self, value: u32, bits: u32) {+ for i in 0..bits {+ self.buf |= (((value >> i) & 1) as u8) << self.len;+ self.len += 1;+ if self.len == 8 {+ self.out.push(self.buf);+ self.buf = 0;+ self.len = 0;+ }+ }+ }++ /// Huffman codes are sent most significant bit first.+ fn code(&mut self, code: u32, bits: u32) {+ for i in (0..bits).rev() {+ self.put((code >> i) & 1, 1);+ }+ }+ }++ let mut bits = Bits {+ out: vec![0x78, 0x01],+ buf: 0,+ len: 0,+ };+ bits.put(1, 1); // The final block.+ bits.put(1, 2); // Fixed Huffman codes.+ bits.code(0x30 + u32::from(b'a'), 8); // The literal 'a'.+ for _ in 0..count {+ bits.code(0xc5, 8); // Length 258 (code 285), no extra bits.+ bits.code(0, 5); // Distance 1 (code 0), no extra bits.+ }+ bits.code(0, 7); // End of block (code 256).+ if bits.len > 0 {+ bits.out.push(bits.buf);+ }+ bits.out.extend_from_slice(&[0; 4]);+ bits.out+ }++ /// A one-page PDF whose content is `stream`, with the stream dictionary entries `dict`.+ fn page_pdf(stream: &[u8], dict: &str) -> Vec<u8> {+ let mut pdf = format!(+ "%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 40 40] /Contents 4 0 R >> endobj\n4 0 obj << {dict} /Length {} >> stream\n",+ stream.len()+ )+ .into_bytes();+ pdf.extend_from_slice(stream);+ pdf.extend_from_slice(b"\nendstream endobj\ntrailer << /Root 1 0 R >>\n%%EOF\n");+ }++ /// A one-page PDF with an array of content references to `streams`.+ fn page_pdf_array(streams: &[(&[u8], &str)], refs: &[usize]) -> Vec<u8> {+ let contents = refs+ .iter()+ .map(|index| format!("{} 0 R", 4 + index))+ .collect::<Vec<_>>()+ .join(" ");+ let mut pdf = format!(+ "%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 40 40] /Contents [{contents}] >> endobj\n"+ )+ .into_bytes();+ for (index, (stream, dict)) in streams.iter().enumerate() {+ let object = 4 + index;+ pdf.extend_from_slice(+ format!("{object} 0 obj << {dict} /Length {} >> stream\n", stream.len())+ .as_bytes(),+ );+ pdf.extend_from_slice(stream);+ pdf.extend_from_slice(b"\nendstream endobj\n");+ }+ pdf.extend_from_slice(b"trailer << /Root 1 0 R >>\n%%EOF\n");+ }++ /// The content of the first page, read `piece` bytes at a time, with a budget of `cap`.+ fn read_content(pdf: Vec<u8>, cap: usize, piece: usize) -> (Vec<u8>, bool) {+ let doc = Pdf::new(pdf).expect("parses");+ let page = doc.pages().first().expect("one page");+ let mut content = page.content_reader_within(cap);+ let mut out = Vec::new();+ while content.read_into(&mut out, piece) > 0 {}++ (out, content.truncated())+ }++ #[test]+ fn plain_and_whole_pieces_keep_their_bytes() {+ let plain = b"q 1 0 0 1 0 0 cm Q\n";+ let whole = b"q 0 0 m Q\n";+ let encoded: String = whole.iter().map(|byte| format!("{byte:02x}")).collect::<String>() + ">";++ for piece in [1, 7, 4096, 65_536] {+ let (plain_out, plain_truncated) = read_content(page_pdf(plain, ""), 1 << 20, piece);+ assert_eq!(plain_out, plain, "plain piece {piece}");+ assert!(!plain_truncated, "plain piece {piece}");++ let (whole_out, whole_truncated) = read_content(+ page_pdf(encoded.as_bytes(), "/Filter /ASCIIHexDecode"),+ 1 << 20,+ piece,+ );+ assert_eq!(whole_out, whole, "whole piece {piece}");+ assert!(!whole_truncated, "whole piece {piece}");+ }+ }++ #[test]+ fn repeated_content_reference_counts_compressed_bytes_once() {+ let data = vec![b'q'; 1 << 16];+ let pdf = page_pdf_array(&[(data.as_slice(), "")], &[0, 0]);+ let doc = Pdf::new(pdf).expect("parses");+ let page = doc.pages().first().expect("one page");+ let mut content = page.content_reader_within(1 << 20);+ let expected_budget = 64 * data.len();+ assert_eq!(content.budget, expected_budget);++ let mut out = Vec::new();+ while content.read_into(&mut out, 4096) > 0 {}+ let mut expected = data.clone();+ expected.push(b' ');+ expected.extend_from_slice(&data);+ expected.push(b' ');+ assert!(+ out == expected,+ "expected {} bytes, got {}",+ expected.len(),+ out.len()+ );+ assert!(!content.truncated());+ }++ #[test]+ fn whole_cap_still_counts_later_unique_streams() {+ let first = vec![b'q'; 1 << 20];+ let later = vec![b'Q'; 12_000];+ let hex = |data: &[u8]| {+ data.iter()+ .map(|byte| format!("{byte:02x}"))+ .collect::<String>()+ + ">"+ };+ let first_raw = hex(&first);+ let later_raw = hex(&later);+ let pdf = page_pdf_array(+ &[+ (first_raw.as_bytes(), "/Filter /ASCIIHexDecode"),+ (later_raw.as_bytes(), "/Filter /ASCIIHexDecode"),+ ],+ &[0, 1],+ );+ let cap = 1 << 20;+ let doc = Pdf::new(pdf).expect("parses");+ let page = doc.pages().first().expect("one page");+ let mut content = page.content_reader_within(cap);+ let expected_budget = 64 * (first_raw.len() + later_raw.len());+ assert!(expected_budget > cap);+ assert_eq!(content.budget, expected_budget);+ assert_eq!(content.materialized_len(), cap);+ assert_eq!(content.pieces.len(), 2, "only the first whole stream and separator are kept");++ let mut out = Vec::new();+ while content.read_into(&mut out, 65_536) > 0 {}+ let mut expected = first;+ expected.push(b' ');+ assert_eq!(out, expected);+ assert!(!content.truncated());+ }++ #[test]+ fn content_past_the_cap_is_read_to_the_end() {+ let content: Vec<u8> = b"q 1 0 0 1 0 0 cm Q\n".iter().copied().cycle().take(3 << 20).collect();+ let pdf = page_pdf(&stored_zlib(&content), "/Filter /FlateDecode");+ // The cap is far below the content, but stored data expands by nothing, so nothing is cut.+ for piece in [7, 4096, 1 << 16] {+ let (out, truncated) = read_content(pdf.clone(), 1 << 20, piece);+ assert_eq!(out.len(), content.len(), "piece {piece}");+ assert!(out == content, "piece {piece}: the bytes are the content's");+ assert!(!truncated, "piece {piece}");+ }+ }++ #[test]+ fn a_stream_that_expands_past_the_budget_is_cut_there() {+ let cap = 1 << 20;+ let bomb = fixed_run_bomb(400_000);+ let (out, truncated) = read_content(page_pdf(&bomb, "/Filter /FlateDecode"), cap, 1 << 16);++ assert!(truncated, "the expansion is past the budget");+ // The budget is 64 times the compressed stream, which is more than the cap here.+ assert_eq!(out.len(), 64 * bomb.len());+ assert!(out.iter().all(|&b| b == b'a'));+ }++ #[test]+ fn a_small_expansion_under_the_cap_is_not_cut() {+ let bomb = fixed_run_bomb(1000);+ let (out, truncated) = read_content(page_pdf(&bomb, "/Filter /FlateDecode"), 1 << 20, 4096);++ assert!(!truncated);+ assert_eq!(out.len(), 1 + 258 * 1000);+ }+}