Skip to main content

flpdf/
reader.rs

1//! PDF input loading, resolution, recovery, and authentication.
2//!
3//! qpdf correspondence: QPDF.cc object resolution, recovery, diagnostics, and authentication responsibilities.
4//!
5pub(crate) mod resolver;
6
7use crate::encryption::password::{password_candidates_for_read, PasswordMode};
8use crate::encryption::permissions::Permissions;
9use crate::encryption::standard::ObjectKeyAlg;
10use crate::encryption::CopyEncryptionSource;
11use crate::error::EncryptedError;
12use crate::object_handle::DocumentResolver;
13use crate::qpdf_obj_gen::QpdfObjGen;
14use crate::{
15    Diagnostics, Error, ObjectHandle, ObjectRef, QpdfErrorCode, QpdfExc, Result, XrefEntry,
16};
17use std::any::Any;
18use std::cell::RefCell;
19use std::collections::{BTreeMap, BTreeSet};
20use std::fs::File;
21use std::io::{self, BufReader, Read, Seek, SeekFrom};
22use std::path::{Path, PathBuf};
23use std::rc::Rc;
24
25use crate::pdf::Pdf;
26
27/// A seekable, owned input source that can cross a qpdf job's document
28/// boundary without exposing the concrete reader kind to its consumers.
29///
30/// qpdf's `QPDF` stores an `InputSource` behind one document type regardless
31/// of whether the source came from a file, memory, or a generated JSON seed.
32/// This trait is the Rust equivalent for job-owned documents: callers retain
33/// lazy reads while `JobDocument` can use one `Pdf` type for every source.
34pub trait ReadSeek: Read + Seek {
35    /// Rust-native downcast boundary corresponding to qpdf InputSource RTTI.
36    fn as_any(&self) -> &dyn Any;
37}
38
39impl<T: Read + Seek + 'static> ReadSeek for T {
40    fn as_any(&self) -> &dyn Any {
41        self
42    }
43}
44
45/// Controller for a file source that can be closed between qpdf page-job
46/// operations and reopened at its last logical position.
47///
48/// This is the Rust equivalent of qpdf's `ClosedFileInputSource::stayOpen`
49/// (`libqpdf/ClosedFileInputSource.cc:18-35,97-104`). It is intentionally
50/// crate-private: callers select the policy through `QPDFJob`, not by
51/// manipulating the underlying reader directly.
52#[derive(Clone)]
53pub(crate) struct InputSourceControl(Rc<RefCell<ReopenableFileState>>);
54
55impl InputSourceControl {
56    pub(crate) fn set_stay_open(&self, value: bool) {
57        let mut state = self.0.borrow_mut();
58        state.stay_open = value;
59        if !value {
60            // Every completed read/seek records `position`, so dropping the
61            // live reader here preserves the same offset qpdf stores in
62            // `ClosedFileInputSource::after` before clearing `fis`.
63            state.reader = None;
64        }
65    }
66
67    #[cfg(test)]
68    pub(crate) fn is_closed_for_test(&self) -> bool {
69        self.0.borrow().reader.is_none()
70    }
71}
72
73struct ReopenableFileState {
74    path: PathBuf,
75    reader: Option<BufReader<File>>,
76    position: u64,
77    stay_open: bool,
78}
79
80/// A file-backed `Read + Seek` source with qpdf's close-and-reopen behavior.
81///
82/// The source opens eagerly so opening a PDF reports the same initial I/O
83/// failure as a normal file reader. Once its controller selects `stay_open =
84/// false`, each completed I/O operation drops the `File`; the next operation
85/// reopens the path and seeks to the saved logical position. This mirrors
86/// qpdf's `ClosedFileInputSource::before`/`after` pair without changing the
87/// resolver's generic `ReadSeek` contract.
88pub(crate) struct ReopenableFile {
89    control: InputSourceControl,
90}
91
92impl ReopenableFile {
93    pub(crate) fn new(path: &Path) -> io::Result<Self> {
94        let file = File::open(path)?;
95        Ok(Self {
96            control: InputSourceControl(Rc::new(RefCell::new(ReopenableFileState {
97                path: path.to_path_buf(),
98                reader: Some(BufReader::new(file)),
99                position: 0,
100                stay_open: true,
101            }))),
102        })
103    }
104
105    pub(crate) fn controller(&self) -> InputSourceControl {
106        self.control.clone()
107    }
108
109    #[cfg(test)]
110    fn is_closed_for_test(&self) -> bool {
111        self.control.0.borrow().reader.is_none()
112    }
113}
114
115impl Read for ReopenableFile {
116    fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
117        let mut state = self.control.0.borrow_mut();
118        if state.reader.is_none() {
119            let file = File::open(&state.path)?;
120            let mut reader = BufReader::new(file);
121            reader.seek(SeekFrom::Start(state.position))?;
122            state.reader = Some(reader);
123        }
124        let bytes_read = match state
125            .reader
126            .as_mut()
127            .expect("reopenable reader is installed")
128            .read(buffer)
129        {
130            Ok(bytes_read) => bytes_read,
131            Err(error) => {
132                if !state.stay_open {
133                    state.reader = None;
134                }
135                return Err(error);
136            }
137        };
138        let position = match state
139            .reader
140            .as_mut()
141            .expect("reopenable reader is installed")
142            .stream_position()
143        {
144            Ok(position) => position,
145            // cov:ignore-start: `ReopenableFile` owns a regular seekable File; a successful read followed by an injected stream_position failure is not representable through this concrete source.
146            Err(error) => {
147                if !state.stay_open {
148                    state.reader = None;
149                }
150                return Err(error);
151            } // cov:ignore-end
152        };
153        state.position = position;
154        if !state.stay_open {
155            state.reader = None;
156        }
157        Ok(bytes_read)
158    }
159}
160
161impl Seek for ReopenableFile {
162    fn seek(&mut self, from: SeekFrom) -> io::Result<u64> {
163        let mut state = self.control.0.borrow_mut();
164        if state.reader.is_none() {
165            let file = File::open(&state.path)?;
166            let mut reader = BufReader::new(file);
167            reader.seek(SeekFrom::Start(state.position))?;
168            state.reader = Some(reader);
169        }
170        let result = state
171            .reader
172            .as_mut()
173            .expect("reopenable reader is installed")
174            .seek(from);
175        if let Ok(position) = result {
176            state.position = position;
177        }
178        if !state.stay_open {
179            state.reader = None;
180        }
181        result
182    }
183}
184
185/// Options for opening a PDF document.
186#[derive(Debug, Clone, PartialEq, Eq)]
187pub struct PdfOpenOptions {
188    /// Enable qpdf-style xref/trailer recovery.
189    ///
190    /// qpdf's `QPDF::attempt_recovery` defaults to `true`; set this to `false`
191    /// for the explicit strict/suppressed-recovery route.
192    pub repair: bool,
193    /// Never read a cross-reference stream, even where `startxref` or a
194    /// `/Prev` chain points at one (qpdf `--ignore-xref-streams`).
195    ///
196    /// Such a section fails as though no cross-reference existed at that
197    /// offset, so with [`repair`](Self::repair) also set the document falls
198    /// back to reconstruction by scanning the body for object headers. Use it
199    /// when a cross-reference stream is malformed but the objects it indexes
200    /// are still readable.
201    pub ignore_xref_streams: bool,
202    /// Password bytes supplied to the Standard security handler.
203    pub password: Vec<u8>,
204    /// How `password` should be interpreted before authentication. qpdf only
205    /// applies `hex-bytes` on the read path; the other modes pass these bytes
206    /// through unchanged. See [`PasswordMode`] for the write-side semantics.
207    pub password_mode: PasswordMode,
208    /// Disable qpdf's alternate password-encoding retry path
209    /// (`--suppress-password-recovery`).
210    pub suppress_password_recovery: bool,
211    /// Interpret [`password`](Self::password) as the precomputed file
212    /// encryption key in hex, NOT a user/owner password (qpdf
213    /// `--password-is-hex-key`). When set, all password→key derivation
214    /// (Algorithm 2 / 2.A / 2.B / 6 / 7) is skipped and `hex_decode(password)`
215    /// is used directly as the file key for stream/string decryption.
216    pub password_is_hex_key: bool,
217    /// Logger that receives document warnings as they occur. `None` selects
218    /// the process-global qpdf-compatible default logger.
219    pub logger: Option<crate::QPDFLogger>,
220    /// Emit qpdf job-level informational messages while opening the document.
221    /// This carries `QPDFJob::doIfVerbose` policy into the reader-owned
222    /// authentication retry boundary.
223    pub verbose: bool,
224    /// Message prefix used for qpdf job-level informational messages.
225    pub message_prefix: Vec<u8>,
226    /// Suppress warning delivery to the logger without removing warnings from
227    /// [`Pdf::repair_diagnostics`].
228    pub suppress_warnings: bool,
229    /// Input-source description used in qpdf-compatible warning prefixes.
230    ///
231    /// qpdf's `InputSource` name is a byte-preserving `std::string`; keep raw
232    /// bytes here so warning output can reproduce non-UTF-8 Unix paths.
233    pub description: Vec<u8>,
234}
235
236impl Default for PdfOpenOptions {
237    fn default() -> Self {
238        Self {
239            // qpdf `QPDF::Members::attempt_recovery` starts enabled
240            // (`include/qpdf/QPDF.hh:1458-1462`). The opt-out is explicit,
241            // matching `QPDFJob::setQPDFOptions` when suppress-recovery is
242            // requested (`libqpdf/QPDF.cc:334-336`, `libqpdf/QPDFJob.cc:652-659`).
243            repair: true,
244            ignore_xref_streams: false,
245            password: Vec::new(),
246            password_mode: PasswordMode::default(),
247            suppress_password_recovery: false,
248            password_is_hex_key: false,
249            logger: None,
250            verbose: false,
251            message_prefix: b"qpdf".to_vec(),
252            suppress_warnings: false,
253            description: Vec::new(),
254        }
255    }
256}
257
258// Stack-growth protection for this module's two recursive hubs: `lift_bounded`
259// here, and `ResolverHandle::resolve_indirect` in the `resolver` child module,
260// which reaches these as `super::READER_STACK_RED_ZONE`/
261// `super::READER_STACK_GROWTH_SIZE`. The red-zone value mirrors
262// `parser.rs`'s own `STACK_RED_ZONE` (kept as a separate local constant rather
263// than imported cross-module, matching this crate's existing per-module
264// duplication in `object_handle.rs`); `resolver.rs` shares *these* rather
265// than minting a third pair because it is a child of this module, not a module
266// across the crate from it.
267// Keep this red zone larger than parser.rs's 32 KiB value: resolver frames
268// retain the post-object-stream offset and recovered-stream state, so the old
269// value let a 256 KiB caller stack exhaust before stacker could switch to its
270// growth segment.
271const READER_STACK_RED_ZONE: usize = 128 * 1024;
272// The resolver's object-attributed diagnostics and recovered-stream state add
273// enough frame state that the deep-chain regression needs an earlier growth
274// check than the original 32 KiB red zone. The callback stack remains 1 MiB;
275// stacker switches to it before the caller's bounded stack can exhaust on any
276// supported platform.
277const READER_STACK_GROWTH_SIZE: usize = 1024 * 1024;
278
279impl<R: Read + Seek> Pdf<R> {
280    /// Return this document's current shared logger.
281    pub fn logger(&self) -> crate::QPDFLogger {
282        self.resolver.logger()
283    }
284
285    /// Replace the shared logger used for warnings raised after this call.
286    pub fn set_logger(&mut self, logger: crate::QPDFLogger) {
287        self.resolver.set_logger(logger);
288    }
289
290    /// Return whether warning delivery is currently suppressed.
291    ///
292    /// Suppression never removes warnings from [`Self::repair_diagnostics`].
293    pub fn suppress_warnings(&self) -> bool {
294        self.resolver.suppress_warnings()
295    }
296
297    /// Enable or disable warning delivery without changing warning collection.
298    pub fn set_suppress_warnings(&mut self, suppress: bool) {
299        self.resolver.set_suppress_warnings(suppress);
300    }
301
302    /// Enable or disable qpdf recovery on this live document.
303    ///
304    /// This is qpdf's `QPDF::setAttemptRecovery` (`include/qpdf/QPDF.hh:234`,
305    /// `libqpdf/QPDF.cc:334`). The policy is read both while loading the
306    /// cross-reference data and when a later object read considers rebuilding
307    /// that data, so this mutator intentionally reaches the shared resolver
308    /// state rather than changing a one-shot open option.
309    pub fn set_attempt_recovery(&mut self, attempt_recovery: bool) {
310        self.resolver.set_attempt_recovery(attempt_recovery);
311    }
312
313    /// Snapshot the document's currently undrained diagnostics — typically warnings from the
314    /// xref/trailer recovery path when called immediately after opening.
315    ///
316    /// Returns an owned snapshot. The collection is qpdf's `m->warnings` and
317    /// lives on the crate-private resolver core rather than on this struct,
318    /// so that `resolve_indirect`, which reaches this document through a
319    /// `Weak` and never holds a `&mut Pdf`, can warn at all — and a
320    /// `&Diagnostics` cannot be handed out from behind the `RefCell` that
321    /// makes that possible. The alternative, `Ref<'_, Diagnostics>`, avoids
322    /// the copy but leaks [`std::cell::Ref`] into the public API and lets a
323    /// caller holding one across a resolving call hit a `BorrowMutError` at
324    /// run time. The copy is cheap: the collection is empty for a document
325    /// that opened cleanly or after [`Self::get_warnings`] has drained it.
326    pub fn repair_diagnostics(&self) -> Diagnostics {
327        self.resolver.repair_diagnostics()
328    }
329
330    /// Return and clear the document's ordered qpdf warnings.
331    ///
332    /// This is qpdf's `QPDF::getWarnings` (`include/qpdf/QPDF.hh:261-266`,
333    /// `libqpdf/QPDF.cc:345-352`). Warning logger delivery happens when the
334    /// warning is recorded, so draining this collection never emits the same
335    /// warning a second time. Warnings raised after this call appear in the
336    /// next returned collection.
337    pub fn get_warnings(&self) -> Diagnostics {
338        self.resolver.get_warnings()
339    }
340
341    /// Return whether this document currently has undrained warnings.
342    ///
343    /// This is qpdf's `QPDF::anyWarnings` (`include/qpdf/QPDF.hh:268-270`): it
344    /// does not clear the collection and remains true until [`Self::get_warnings`]
345    /// drains it.
346    #[must_use]
347    pub fn any_warnings(&self) -> bool {
348        self.resolver.any_warnings()
349    }
350
351    /// The number of warnings recorded so far, without copying the
352    /// collection: qpdf's `QPDF::numWarnings` (`libqpdf/QPDF.cc:360-363`),
353    /// which reports the number since the last [`Self::get_warnings`] drain.
354    #[must_use]
355    pub fn num_warnings(&self) -> usize {
356        self.resolver.num_warnings()
357    }
358
359    /// Record a non-fatal processing warning on this handle.
360    ///
361    /// Used by recoverable code paths (e.g. form-field inheritance walks that hit
362    /// a cyclic / over-deep / non-dictionary `/Parent` chain and fall back rather
363    /// than aborting) so the soft failure is surfaced via [`Pdf::repair_diagnostics`]
364    /// instead of being silently swallowed. Mirrors qpdf, which warns and continues
365    /// on malformed field trees.
366    ///
367    /// Still takes `&mut self` although the sink no longer requires it: every
368    /// caller already holds a `&mut Pdf`, and the resolver's own warnings go
369    /// through [`resolver::ResolverHandle::push_warning`] instead. Both doors
370    /// reach the one collection.
371    pub(crate) fn push_warning(&mut self, message: impl Into<String>) -> Result<()> {
372        self.resolver.push_warning(message)
373    }
374
375    /// Record and route a complete qpdf warning value without rebuilding its
376    /// source/object context at a higher layer.
377    pub(crate) fn push_qpdf_warning(&self, warning: QpdfExc) -> Result<()> {
378        self.resolver.push_qpdf_warning(warning)
379    }
380
381    pub(crate) fn input_description(&self) -> Vec<u8> {
382        self.resolver.input_description()
383    }
384
385    /// Whether this document has an `/Encrypt` dictionary and parsed
386    /// encryption state. The dedicated inspection open path returns `true`
387    /// even when password authentication failed, matching qpdf's
388    /// `isEncrypted()` partial-initialization behavior.
389    pub fn is_encrypted(&self) -> bool {
390        self.encryption.borrow().is_some() || self.encryption_inspection.borrow().is_some()
391    }
392
393    pub(crate) fn encryption_ref(&self) -> Option<ObjectRef> {
394        self.encryption
395            .borrow()
396            .as_ref()
397            .and_then(|encryption| encryption.encrypt_ref)
398    }
399
400    /// Return qpdf `isEncrypted`'s `/V` projection, if the document is encrypted.
401    pub fn encryption_version(&self) -> Option<i64> {
402        self.encryption_inspection
403            .borrow()
404            .as_ref()
405            .map(|inspection| inspection.v)
406    }
407
408    /// Return qpdf `isEncrypted`'s `/R` projection, if the document is encrypted.
409    pub fn encryption_revision(&self) -> Option<i64> {
410        self.encryption_inspection
411            .borrow()
412            .as_ref()
413            .map(|inspection| inspection.r)
414    }
415
416    /// Return the initialized encryption key length in bits.
417    ///
418    /// After authentication, qpdf reports the actual `getEncryptionKey()`
419    /// length, including an overlength value supplied through
420    /// `--password-is-hex-key` (`QPDFJob.cc:1245-1252`). Before authentication,
421    /// the inspection state provides qpdf's revision-aware dictionary length.
422    pub fn encryption_length_bits(&self) -> Option<i64> {
423        let authenticated_bits = self.encryption.borrow().as_ref().and_then(|encryption| {
424            encryption
425                .file_key
426                .len()
427                .checked_mul(8)
428                .and_then(|bits| i64::try_from(bits).ok())
429        });
430        authenticated_bits.or_else(|| {
431            self.encryption_inspection
432                .borrow()
433                .as_ref()
434                .map(|inspection| inspection.length_bits)
435        })
436    }
437
438    /// Return qpdf `getTrimmedUserPassword()` bytes, if the document is encrypted.
439    pub fn trimmed_user_password(&self) -> Option<Vec<u8>> {
440        let user_password = self
441            .encryption_inspection
442            .borrow()
443            .as_ref()
444            .map(|inspection| inspection.user_password.clone())?;
445        Some(crate::encryption::standard::trim_user_password(
446            &user_password,
447        ))
448    }
449
450    /// Return qpdf `isEncrypted`'s stream, string, and file encryption methods.
451    pub fn encryption_methods(&self) -> Option<(&'static str, &'static str, &'static str)> {
452        self.encryption_inspection
453            .borrow()
454            .as_ref()
455            .map(|inspection| {
456                (
457                    inspection.stream_method,
458                    inspection.string_method,
459                    inspection.eff_method,
460                )
461            })
462    }
463
464    /// Whether the document uses a weak encryption method such as RC4 or R=5.
465    ///
466    /// Falls back to the pre-authentication `encryption_inspection` snapshot
467    /// when the authenticated `EncryptionState` is absent -- for example a
468    /// document returned by [`Self::open_for_encryption_inspection`] after a
469    /// `BadPassword` open, which never populates `encryption`. Both sources
470    /// compute the same revision/crypt-filter classification.
471    pub fn uses_weak_crypto(&self) -> bool {
472        self.encryption
473            .borrow()
474            .as_ref()
475            .map(|encryption| encryption.weak_crypto)
476            .or_else(|| {
477                self.encryption_inspection
478                    .borrow()
479                    .as_ref()
480                    .map(|inspection| inspection.weak_crypto)
481            })
482            .unwrap_or(false)
483    }
484
485    /// Advisory standard security handler permissions from `/P`, if the document is encrypted.
486    pub fn permissions(&self) -> Option<Permissions> {
487        self.encryption_inspection
488            .borrow()
489            .as_ref()
490            .map(|inspection| inspection.permissions)
491            .or_else(|| {
492                self.encryption
493                    .borrow()
494                    .as_ref()
495                    .map(|encryption| encryption.permissions)
496            })
497    }
498
499    /// Whether the password supplied at open time authenticated against the
500    /// document's user password (`/U`). Always `false` for plaintext PDFs.
501    pub fn user_password_matched(&self) -> bool {
502        self.encryption_inspection
503            .borrow()
504            .as_ref()
505            .is_some_and(|inspection| inspection.user_password_matched)
506            || self
507                .encryption
508                .borrow()
509                .as_ref()
510                .is_some_and(|encryption| encryption.user_password_matched)
511    }
512
513    /// Whether the password supplied at open time authenticated against the
514    /// document's owner password (`/O`). Always `false` for plaintext PDFs.
515    /// Many PDFs use an empty password for both, so this can be true at the
516    /// same time as [`Pdf::user_password_matched`].
517    pub fn owner_password_matched(&self) -> bool {
518        self.encryption_inspection
519            .borrow()
520            .as_ref()
521            .is_some_and(|inspection| inspection.owner_password_matched)
522            || self
523                .encryption
524                .borrow()
525                .as_ref()
526                .is_some_and(|encryption| encryption.owner_password_matched)
527    }
528
529    /// The derived file encryption key, if the document was opened as an
530    /// encrypted file. `None` for plaintext PDFs.
531    ///
532    /// Read-only accessor for the `show-encryption-key` inspection
533    /// subcommand; does not run or alter authentication. Returns an owned
534    /// copy rather than a borrowed slice, since this is an inspection
535    /// accessor rather than a hot path.
536    pub fn encryption_file_key(&self) -> Option<Vec<u8>> {
537        self.encryption
538            .borrow()
539            .as_ref()
540            .map(|encryption| encryption.file_key.clone())
541    }
542
543    /// Build the qpdf `copyEncryptionParameters` source for a writer attached
544    /// to this already-authenticated document.
545    ///
546    /// The writer must not depend on reader implementation details such as
547    /// `EncryptionState` or `EncryptionMode`. Keep that boundary here: the
548    /// helper snapshots the authenticated file key, the padded user password
549    /// (qpdf's `getPaddedUserPassword`, from which the writer re-derives a
550    /// V<5 output key), the source `/Encrypt` dictionary, and the permanent
551    /// `/ID[0]`; the writer then applies qpdf's canonical copy rules
552    /// (including forcing AES for V>=4).
553    ///
554    /// `/ID[0]` is read from the value cached at authentication time, not
555    /// from a fresh live-trailer lookup: for a V<5 document `file_key` is
556    /// itself derived from `/ID[0]` (PDF 1.7 §7.6.3.3 Algorithm 2), so this
557    /// source's `id0` must stay paired with the SAME bytes `file_key` was
558    /// derived from even if a caller mutates the live trailer's `/ID` after
559    /// authentication completes -- otherwise the emitted `/ID[0]` and the
560    /// copied `/O`/`/U`/`/P` would imply a different file key than the one
561    /// actually used to encrypt the output. The R5/R6 (V=5) handler does not
562    /// derive `file_key` from `/ID` at all, so no cached value is available
563    /// there and a live read is safe.
564    pub fn writer_copy_encryption_source(&mut self) -> Result<Option<CopyEncryptionSource>> {
565        let (file_key, padded_user_password, encryption_v, cached_id0) = {
566            let guard = self.encryption.borrow();
567            let Some(encryption) = guard.as_ref() else {
568                return Ok(None);
569            };
570            (
571                encryption.file_key.clone(),
572                encryption.user_password.clone(),
573                encryption.encryption_v,
574                encryption.id0.clone(),
575            )
576        };
577        let mut encrypt_dict = self.encrypt_dictionary_handle()?.ok_or_else(|| {
578            Error::Unsupported("authenticated input has no /Encrypt dictionary".into())
579        })?;
580        // qpdf's copyEncryptionParameters reads /V and then /Length while
581        // the donor still owns the warning sink. Capture the writer-side
582        // result before make_direct detaches the dictionary from that
583        // document; Some(0) is an actual malformed-input key length.
584        let writer_length_bits = {
585            let version = encrypt_dict
586                .try_get_key(b"/V")?
587                .try_get_int_value_as_int()?;
588            if version > 1 {
589                let key_len = encrypt_dict
590                    .try_get_key(b"/Length")?
591                    .try_get_int_value_as_int()?;
592                Some(i64::from(key_len / 8) * 8)
593            } else {
594                None
595            }
596        };
597        let live_id0 =
598            crate::writer::source_permanent_id_value_handle(&self.trailer_key_handle(b"ID"))?;
599        // `CopyEncryptionSource` outlives this reader in the CLI and in
600        // cross-document writer calls. Detach the authenticated dictionary
601        // from the donor resolver while it is still alive, so later key reads
602        // cannot observe a destroyed donor handle. The Standard encryption
603        // dictionary is a value graph and contains no stream objects, making
604        // qpdf's make-direct copy the appropriate ownership boundary here.
605        encrypt_dict.make_direct(false)?;
606        let id0 = cached_id0.or(live_id0).unwrap_or_default();
607
608        Ok(Some(CopyEncryptionSource {
609            encrypt_dict,
610            writer_length_bits,
611            file_key,
612            padded_user_password,
613            id0,
614            // qpdf's copy path forces AES for V>=4. The field remains part of
615            // the public donor surface for the explicit copy route; the
616            // canonical builder also validates/chooses from /V itself.
617            object_key_alg: if encryption_v >= 4 {
618                ObjectKeyAlg::Aes
619            } else {
620                ObjectKeyAlg::Rc4
621            },
622        }))
623    }
624
625    /// Return all signed AcroForm signature fields in document field order.
626    ///
627    /// This walks `/Catalog /AcroForm /Fields`, descends through field `/Kids`,
628    /// and returns only `/FT /Sig` fields whose `/V` signature dictionary has a
629    /// valid four-integer `/ByteRange`.
630    ///
631    /// # Errors
632    ///
633    /// - Propagates any error from resolving the catalog, `/AcroForm`, and
634    ///   field-tree objects (for example I/O or parse failures surfaced by
635    ///   canonical ObjectHandle resolution).
636    /// - [`Error::Parse`] when a signature field's `/ByteRange` is malformed (not a
637    ///   four-element array of non-negative integers).
638    pub fn signatures(&mut self) -> Result<Vec<crate::SignatureInfo>> {
639        crate::signatures::signatures(self)
640    }
641
642    /// Remove the security restrictions that qpdf removes for
643    /// `QPDF::removeSecurityRestrictions` (`libqpdf/QPDF.cc:2659-2667`).
644    ///
645    /// This is a document-level mutation: it unconditionally removes the
646    /// catalog `/Perms` entry and replaces a visible `/AcroForm /SigFlags`
647    /// value with the direct integer `0`. Signature-field mutation belongs to
648    /// [`crate::AcroFormDocumentHelper::disable_digital_signatures`], matching
649    /// qpdf's split between `QPDF` and `QPDFAcroFormDocumentHelper`.
650    ///
651    /// The qpdf method returns `void`; this Rust port returns `Result<()>` only
652    /// to propagate failures from live-handle resolution and mutation.
653    ///
654    /// # Errors
655    ///
656    /// Returns the same root-resolution and live-handle errors as
657    /// [`Pdf::root_handle`], and propagates failures while resolving the
658    /// `/AcroForm` or `/SigFlags` values.
659    pub fn remove_security_restrictions(&mut self) -> Result<()> {
660        let catalog = self.root_handle()?;
661
662        // qpdf calls removeKey unconditionally. A present null-valued key is
663        // still removed even though QPDF_Dictionary::hasKey treats it as
664        // absent (`libqpdf/QPDF_Dictionary.cc:98-101,150-153`).
665        catalog.remove_key(b"/Perms");
666
667        let acroform = catalog.try_get_key(b"/AcroForm")?;
668        if acroform.try_is_dictionary()? && acroform.try_has_key(b"/SigFlags")? {
669            // qpdf replaces the key whenever its visible hasKey test
670            // succeeds, including an already-zero direct integer.
671            acroform.replace_key(b"/SigFlags", ObjectHandle::integer(0))?;
672        }
673
674        Ok(())
675    }
676
677    pub(crate) fn authenticate_if_encrypted(
678        &mut self,
679        options: &PdfOpenOptions,
680        inspection: &crate::encryption::state::EncryptionInspectionState,
681    ) -> Result<()> {
682        if self.encrypt_dictionary_handle()?.is_none() {
683            return Ok(());
684        }
685        if options.password_is_hex_key || options.suppress_password_recovery {
686            return self.authenticate_if_encrypted_once(options, inspection);
687        }
688
689        let candidates = password_candidates_for_read(&options.password, options.password_mode)?;
690        if candidates.len() == 1 {
691            return self.authenticate_if_encrypted_once(options, inspection);
692        }
693
694        // qpdf tries the original candidate first, then each repaired encoding,
695        // and appends the original one again so the terminal error has the
696        // supplied password's wording and context (`QPDFJob.cc:1752-1790`).
697        let original = candidates[0].clone();
698        let mut final_bad_password = None;
699        let logger = options
700            .logger
701            .clone()
702            .unwrap_or_else(crate::QPDFLogger::default_logger);
703        let mut warned = false;
704        for candidate in candidates.into_iter().chain(std::iter::once(original)) {
705            let mut attempt = options.clone();
706            // Candidates are already decoded bytes. Mark them as bytes so a
707            // hex-bytes input is not decoded a second time.
708            attempt.password = candidate;
709            attempt.password_mode = PasswordMode::Bytes;
710            attempt.suppress_password_recovery = true;
711            match self.authenticate_if_encrypted_once(&attempt, inspection) {
712                Ok(()) => return Ok(()),
713                Err(error) if matches!(error, Error::Encrypted(EncryptedError::BadPassword)) => {
714                    final_bad_password = Some(error);
715                    if options.verbose && !warned {
716                        warned = true;
717                        let mut message = options.message_prefix.clone();
718                        message.extend_from_slice(
719                            b": supplied password didn't work; trying other passwords based on interpreting password with different string encodings\n",
720                        );
721                        logger.info(message)?;
722                    }
723                }
724                Err(error) => return Err(error),
725            }
726        }
727
728        Err(final_bad_password.expect("qpdf password recovery always has the original candidate"))
729    }
730
731    /// Parse qpdf's encryption parameters before authentication so the
732    /// read-only `--show-encryption` path can report them after BadPassword.
733    pub(crate) fn initialize_encryption_inspection(
734        &mut self,
735    ) -> Result<Option<crate::encryption::state::EncryptionInspectionState>> {
736        let encrypt_handle = self.trailer_key_handle(b"Encrypt");
737        if encrypt_handle.try_is_null()? {
738            return Ok(None);
739        }
740        let id_handle = self.trailer_key_handle(b"ID");
741        if !crate::encryption::state::first_file_id_handle_with_status(&id_handle)?.valid {
742            // qpdf's initializeEncryption warns before validating /Encrypt and
743            // then continues with an empty id1
744            // (`QPDF_encryption.cc:718-751`). The warning is emitted here once,
745            // while authentication consumes the same fallback value without
746            // re-emitting it.
747            let offset = self.resolver.last_offset();
748            self.resolver
749                .push_trailer_warning_at(offset, "invalid /ID in trailer dictionary")?;
750        }
751        if !encrypt_handle.try_is_dictionary()? {
752            let object = self.resolver.last_object_description();
753            return Err(Error::QpdfExc(self.encryption_qpdf_exception(
754                QpdfErrorCode::DamagedPdf,
755                &object,
756                b"/Encrypt in trailer dictionary is not a dictionary",
757            )));
758        };
759        self.validate_qpdf_encryption_initialization(&encrypt_handle)?;
760        let encrypt = encrypt_handle;
761        let inspection = crate::encryption::state::parse_inspection_state(&encrypt)?;
762        *self.encryption_inspection.borrow_mut() = Some(inspection.clone());
763        Ok(Some(inspection))
764    }
765
766    fn encryption_qpdf_exception(
767        &self,
768        code: QpdfErrorCode,
769        object: &[u8],
770        message: &[u8],
771    ) -> QpdfExc {
772        QpdfExc::new(
773            code,
774            self.input_description(),
775            object,
776            i64::try_from(self.resolver.last_offset()).unwrap_or(i64::MAX),
777            message,
778        )
779    }
780
781    fn validate_qpdf_encryption_initialization(&self, encrypt: &ObjectHandle) -> Result<()> {
782        let filter = encrypt.try_get_key(b"/Filter")?;
783        if filter.try_as_name()?.as_deref() != Some(b"Standard") {
784            return Err(Error::QpdfExc(self.encryption_qpdf_exception(
785                QpdfErrorCode::Unsupported,
786                b"encryption dictionary",
787                b"unsupported encryption filter",
788            )));
789        }
790
791        let subfilter = encrypt.try_get_key(b"/SubFilter")?;
792        if !subfilter.try_is_null()? {
793            let warning = self.encryption_qpdf_exception(
794                QpdfErrorCode::Unsupported,
795                b"encryption dictionary",
796                b"file uses encryption SubFilters, which qpdf does not support",
797            );
798            self.resolver.push_qpdf_warning(warning)?;
799        }
800
801        let version = encrypt.try_get_key(b"/V")?;
802        if !version.try_is_integer()? {
803            return Err(self.damaged_encryption_dictionary());
804        }
805        let revision = encrypt.try_get_key(b"/R")?;
806        if !revision.try_is_integer()? {
807            return Err(self.damaged_encryption_dictionary());
808        }
809        let owner = encrypt.try_get_key(b"/O")?;
810        if !owner.try_is_string()? {
811            return Err(self.damaged_encryption_dictionary());
812        }
813        let user = encrypt.try_get_key(b"/U")?;
814        if !user.try_is_string()? {
815            return Err(self.damaged_encryption_dictionary());
816        }
817        let permissions = encrypt.try_get_key(b"/P")?;
818        if !permissions.try_is_integer()? {
819            return Err(self.damaged_encryption_dictionary());
820        }
821
822        let version = version.try_get_int_value_as_int()?;
823        let revision = revision.try_get_int_value_as_int()?;
824        let owner = owner.try_as_string()?.unwrap_or_default();
825        let user = user.try_as_string()?.unwrap_or_default();
826
827        if !(2..=6).contains(&revision) || !matches!(version, 1 | 2 | 4 | 5) {
828            let message = format!(
829                "Unsupported /R or /V in encryption dictionary; R = {revision} (max 6), V = {version} (max 5)"
830            );
831            return Err(Error::QpdfExc(self.encryption_qpdf_exception(
832                QpdfErrorCode::Unsupported,
833                b"encryption dictionary",
834                message.as_bytes(),
835            )));
836        }
837
838        // qpdf pads short V<5 /O and /U entries before checking their exact
839        // 32-byte lengths, so only longer values fail this initializer gate.
840        if version < 5 && (owner.len() > 32 || user.len() > 32) {
841            return Err(Error::QpdfExc(self.encryption_qpdf_exception(
842                QpdfErrorCode::DamagedPdf,
843                b"encryption dictionary",
844                b"incorrect length for /O and/or /U in encryption dictionary",
845            )));
846        }
847
848        if version == 5 {
849            for key in [b"/OE".as_ref(), b"/UE", b"/Perms"] {
850                let value = encrypt.try_get_key(key)?;
851                if !value.try_is_string()? {
852                    return Err(Error::QpdfExc(self.encryption_qpdf_exception(
853                        QpdfErrorCode::DamagedPdf,
854                        b"encryption dictionary",
855                        b"some V=5 encryption dictionary parameters are missing or the wrong type",
856                    )));
857                }
858                let _value = value.try_as_string()?;
859            }
860        }
861        Ok(())
862    }
863
864    fn damaged_encryption_dictionary(&self) -> Error {
865        Error::QpdfExc(self.encryption_qpdf_exception(
866            QpdfErrorCode::DamagedPdf,
867            b"encryption dictionary",
868            b"some encryption dictionary parameters are missing or the wrong type",
869        ))
870    }
871
872    fn authenticate_if_encrypted_once(
873        &mut self,
874        options: &PdfOpenOptions,
875        inspection: &crate::encryption::state::EncryptionInspectionState,
876    ) -> Result<()> {
877        let encrypt_handle = self.trailer_key_handle(b"Encrypt");
878        let encrypt_ref = encrypt_handle.object_ref();
879        let id_handle = self.trailer_key_handle(b"ID");
880        let Some(encrypt) = self.encrypt_dictionary_handle()? else {
881            return Ok(());
882        };
883        let authenticated = crate::encryption::state::authenticate(
884            &encrypt,
885            inspection,
886            &id_handle,
887            encrypt_ref,
888            &options.password,
889            options.password_mode,
890            options.password_is_hex_key,
891        )?;
892        let state = authenticated.state;
893        if let Some(warning) = authenticated.perms_warning {
894            self.push_warning(warning)?;
895        }
896        if let Some(inspection) = self.encryption_inspection.borrow_mut().as_mut() {
897            inspection.user_password = state.user_password.clone();
898            inspection.user_password_matched = state.user_password_matched;
899            inspection.owner_password_matched = state.owner_password_matched;
900        }
901        *self.encryption.borrow_mut() = Some(state);
902        Ok(())
903    }
904
905    fn encrypt_dictionary_handle(&mut self) -> Result<Option<ObjectHandle>> {
906        let encrypt = self.trailer_key_handle(b"Encrypt");
907        // qpdf gates on `m->trailer.hasKey("/Encrypt")`
908        // (`libqpdf/QPDF_encryption.cc:729`), which treats a key that
909        // resolves to null the same as an absent key
910        // (`QPDF_Dictionary::hasKey`, `libqpdf/QPDF_Dictionary.cc:98-101`).
911        // A lazily-resolved indirect `/Encrypt` reference must go through
912        // that same resolving check rather than the non-resolving
913        // `ObjectHandle::is_null`, which only sees a direct null literal.
914        if encrypt.try_is_null()? {
915            return Ok(None);
916        }
917        if !encrypt.try_is_dictionary()? {
918            return Err(EncryptedError::Malformed {
919                reason: "/Encrypt object is not a dictionary".into(),
920            }
921            .into());
922        }
923        Ok(Some(encrypt))
924    }
925
926    /// Return qpdf's xref-parser-owned `first_xref_item_offset` used by the
927    /// linearization `/T` check.
928    pub(crate) fn first_xref_item_offset(&self) -> u64 {
929        self.first_xref_item_offset
930    }
931
932    /// Return qpdf's xref-parser-owned `m->uncompressed_after_compressed`
933    /// used by the linearization check.
934    pub(crate) fn uncompressed_after_compressed(&self) -> bool {
935        self.uncompressed_after_compressed
936    }
937
938    pub(crate) fn source_xref_entries(&self) -> BTreeMap<ObjectRef, XrefEntry> {
939        self.resolver.source_xref_entries()
940    }
941
942    /// Append source ObjStm membership without resolving object values.
943    ///
944    /// Ports the writer-private `QPDF::getObjectStreamData` document operation
945    /// (`libqpdf/QPDF.cc:2381-2390`; `include/qpdf/QPDF.hh:757-761`). Existing
946    /// map entries survive unless a type-2 source row overwrites their key.
947    pub(crate) fn get_object_stream_data(&self, mapping: &mut BTreeMap<u32, u32>) {
948        self.resolver.get_object_stream_data(mapping);
949    }
950
951    /// Record a target object's source-backed ObjStm membership for a fresh
952    /// multi-source page-selection document.
953    ///
954    /// The merge target has no physical input xref row for a copied primary
955    /// member, but the plain Preserve writer must see the qpdf-equivalent
956    /// type-2 row when it reconstructs the primary source container.
957    pub(crate) fn install_object_stream_member(
958        &self,
959        object_ref: ObjectRef,
960        stream: ObjectRef,
961        index: u32,
962    ) {
963        self.resolver.insert_source_xref_entry(
964            object_ref,
965            XrefEntry::Compressed {
966                stream: stream.number,
967                index,
968            },
969        );
970    }
971
972    /// Return qpdf's effective source cross-reference table.
973    ///
974    /// This is the reader-owned table represented by qpdf's
975    /// `QPDF::getXRefTable` (`libqpdf/QPDF.cc:2370-2377`), not a writer
976    /// reconstruction or a table derived from resolved values. The returned
977    /// map is a snapshot because the resolver owns the table behind interior
978    /// mutability; resolution-time recovery is reflected in a subsequent
979    /// snapshot. Caller replacements that originated without an effective row
980    /// stay in qpdf's object cache and do not manufacture an xref entry
981    /// (`QPDF.cc:1986-1993`), while a later physical recovery may register and
982    /// expose that source row.
983    pub fn get_xref_table(&self) -> BTreeMap<ObjectRef, XrefEntry> {
984        self.resolver.xref_entries()
985    }
986
987    /// Return qpdf's raw cross-reference table, preserving signed
988    /// object/generation identity before the valid `ObjectRef` boundary.
989    pub(crate) fn get_raw_xref_table(&self) -> BTreeMap<QpdfObjGen, XrefEntry> {
990        self.resolver.raw_xref_entries()
991    }
992
993    /// Return object references from qpdf's one canonical object cache without
994    /// forcing resolution. This is the internal counterpart of the writer's
995    /// cache-key walks; unlike the removed facade enumeration, it reads only
996    /// `ResolverCore::object_cache`.
997    pub(crate) fn canonical_object_refs(&self) -> Vec<ObjectRef> {
998        self.canonical_object_ref_set(false).into_iter().collect()
999    }
1000
1001    /// Return source-backed or qpdf-shaped allocated object references from the
1002    /// canonical cache. Historical xref-stream cache entries and unresolved
1003    /// dangling references are intentionally omitted from this live view.
1004    pub(crate) fn canonical_live_object_refs(&self) -> Vec<ObjectRef> {
1005        self.canonical_object_ref_set(true).into_iter().collect()
1006    }
1007
1008    /// Return qpdf's live preserve-unreferenced seed handles while retaining
1009    /// their raw cache identities. The writer calls `getAllObjects()` before
1010    /// its standard enqueue walk (`libqpdf/QPDFWriter.cc:2907-2913`), so this
1011    /// route must not narrow a raw source generation such as `5 65536` through
1012    /// the public `ObjectRef` projection.
1013    pub(crate) fn canonical_live_object_handles(&self) -> Result<Vec<ObjectHandle>> {
1014        let handles = self.resolver.get_all_objects()?;
1015        let raw_xref = self.resolver.raw_xref_entries();
1016        Ok(handles
1017            .into_iter()
1018            .filter(|handle| {
1019                // cov:ignore-start: ResolverCore::object_cache stores only
1020                // handles carrying a qpdf object generation, and
1021                // get_all_objects enumerates that cache directly.
1022                let Some(object_gen) = handle.qpdf_obj_gen() else {
1023                    return false;
1024                };
1025                // cov:ignore-end
1026                object_gen.is_indirect()
1027                    && (raw_xref.contains_key(&object_gen)
1028                        || self.resolver.is_allocated_qpdf_obj_gen(object_gen))
1029            })
1030            .collect())
1031    }
1032
1033    fn canonical_object_ref_set(&self, live_only: bool) -> BTreeSet<ObjectRef> {
1034        let mut refs: BTreeSet<_> = self
1035            .resolver
1036            .xref_refs()
1037            .into_iter()
1038            .filter(|object_ref| object_ref.number != 0 && object_ref.generation != u16::MAX)
1039            .collect();
1040        refs.extend(
1041            self.resolver
1042                .all_object_handles()
1043                .into_iter()
1044                .filter_map(|handle| {
1045                    let object_ref = handle.object_ref()?;
1046                    if object_ref.number == 0 || object_ref.generation == u16::MAX {
1047                        return None;
1048                    }
1049                    if self.resolver.xref_entry(object_ref).is_none()
1050                        && handle.is_null()
1051                        && !self.resolver.is_allocated_object(object_ref)
1052                    {
1053                        // A canonical handle can resolve an absent reference to
1054                        // null without an xref/cache source. It is not an object
1055                        // in qpdf's cache enumeration unless it was allocated by
1056                        // the document itself.
1057                        return None;
1058                    }
1059                    if live_only
1060                        && self.resolver.xref_entry(object_ref).is_none()
1061                        && !self.resolver.is_allocated_object(object_ref)
1062                    {
1063                        // A historical xref stream and a dangling unresolved
1064                        // handle remain in qpdf's complete cache, but neither is
1065                        // an effective live source object. A reserved sentinel
1066                        // is document-allocated, so it stays visible here and
1067                        // reaches `QPDF_Reserved::unparse`'s error like qpdf's
1068                        // `getAllObjects()`-seeded preserve-unreferenced walk
1069                        // (`libqpdf/QPDFWriter.cc:2909-2915`).
1070                        return None;
1071                    }
1072                    Some(object_ref)
1073                })
1074                .filter(|object_ref| {
1075                    !live_only
1076                        || self.resolver.xref_entry(*object_ref).is_some()
1077                        || self.resolver.is_allocated_object(*object_ref)
1078                }),
1079        );
1080        refs
1081    }
1082
1083    /// Returns the canonical [`ObjectHandle`] for `object_ref`, creating and
1084    /// registering an unresolved one on first request.
1085    ///
1086    /// Repeated calls with the same `object_ref` return the same shared
1087    /// handle rather than a new, independently-identified one, mirroring
1088    /// qpdf's per-document object cache (`QPDF::getObject`,
1089    /// `libqpdf/QPDF.cc:1951-1959`): once an indirect object has been
1090    /// requested, later requests for the same object number/generation
1091    /// observe the same cached identity.
1092    ///
1093    /// This does not perform file I/O or force object-body parsing: the
1094    /// returned handle's value is not read or resolved by this call.
1095    pub fn get_object_handle(&mut self, object_ref: ObjectRef) -> ObjectHandle {
1096        // The registry itself lives on the resolver, which is also what mints
1097        // the handle: it holds both halves `new_indirect_for_pdf_with_resolver`
1098        // needs — the document identity `belongs_to_pdf` answers on and the
1099        // `Weak` `try_dereference` upgrades — and it is the same door
1100        // `resolve_indirect` uses for a nested `N G R`, so the two can never
1101        // hand out different handles for one ref.
1102        self.resolver.get_object_handle(object_ref)
1103    }
1104
1105    /// Return the canonical handle for qpdf's raw signed object/generation
1106    /// identity. Unlike [`Self::get_object_handle`], this preserves an object
1107    /// header generation that cannot be represented by a PDF `N G R`
1108    /// reference, such as `5 65536 obj`.
1109    pub fn get_object_handle_by_raw_identity(
1110        &mut self,
1111        object_number: i32,
1112        generation: i32,
1113    ) -> ObjectHandle {
1114        self.resolver
1115            .get_object_handle_qpdf_obj_gen(QpdfObjGen::new(object_number, generation))
1116    }
1117
1118    /// Whether this document holds the only strong reference to its resolver.
1119    ///
1120    /// Test-only: lets the resolver's own teardown regression assert that
1121    /// handing out `Weak`s cannot keep a dropped document's input source
1122    /// alive, rather than arguing it from the types.
1123    #[cfg(test)]
1124    pub(crate) fn resolver_is_uniquely_owned(&self) -> bool {
1125        Rc::strong_count(&self.resolver) == 1
1126    }
1127
1128    /// Whether cross-reference table reconstruction has occurred for this document.
1129    ///
1130    /// qpdf `m->reconstructed_xref` (`include/qpdf/QPDF.hh:1480`).
1131    #[cfg(test)]
1132    pub(crate) fn reconstructed_xref(&self) -> bool {
1133        self.resolver.reconstructed_xref()
1134    }
1135
1136    #[cfg(test)]
1137    pub(crate) fn dangling_references_fixed(&self) -> bool {
1138        self.resolver.dangling_references_fixed()
1139    }
1140
1141    /// Prepare the canonical object cache and return qpdf's greatest object
1142    /// number (`QPDF::getObjectCount`, `libqpdf/QPDF.cc:1271-1283`). This is
1143    /// intentionally separate from fresh-object allocation, which belongs to
1144    /// `flpdf-25kg.3.24`.
1145    pub(crate) fn get_object_count(&mut self) -> Result<u32> {
1146        self.resolver.get_object_count()
1147    }
1148
1149    /// Collect compressible objects through qpdf's document-owned live walk.
1150    ///
1151    /// Ports `QPDF::getCompressibleObjGens` (`libqpdf/QPDF.cc:2393-2474`).
1152    /// The cache is prepared before sizing a packed visited bitmap, matching
1153    /// C++ `vector<bool>`. Stale generations are removed from the actual
1154    /// document; all retained aliases become direct null rather than relying
1155    /// on writer-side reference suppression. Stream `/Length` edges are
1156    /// omitted here; filtering stream parameters belongs to the writer.
1157    #[cfg(test)]
1158    pub(crate) fn get_compressible_objgens(&mut self) -> Result<Vec<ObjectRef>> {
1159        self.get_compressible_objgens_with_removed()
1160            .map(|(eligible, _)| eligible)
1161    }
1162
1163    /// Collect qpdf's compressible objects together with the stale generations
1164    /// removed by the same live walk. The writer must carry this operation-
1165    /// specific removal set into any later preserve-unreferenced seed pass:
1166    /// `QPDF::removeObject` erases the resolver cache entry; the returned
1167    /// operation-specific removal set lets a writer keep its own traversal
1168    /// bookkeeping without adding a second document cache.
1169    #[cfg(test)]
1170    pub(crate) fn get_compressible_objgens_with_removed(
1171        &mut self,
1172    ) -> Result<(Vec<ObjectRef>, BTreeSet<ObjectRef>)> {
1173        let plan = crate::writer::object_streams::compressible_objgens_qpdf_plan(self)?;
1174        Ok((plan.eligible, plan.removed_refs))
1175    }
1176
1177    /// Return the next qpdf-shaped generation-zero object identity from the
1178    /// prepared canonical cache. Allocation itself belongs to the document's
1179    /// resolver so non-canonical values cannot silently become object-number
1180    /// inputs (`libqpdf/QPDF.cc:1271-1283,1872-1880`).
1181    pub(crate) fn next_obj_gen(&self) -> Result<ObjectRef> {
1182        self.resolver.next_obj_gen()
1183    }
1184
1185    /// Return the current destination allocation identity without preparing
1186    /// the resolver cache. Page-selection replay uses this to delimit the
1187    /// allocations made by one qpdf occurrence.
1188    pub(crate) fn allocation_checkpoint(&self) -> usize {
1189        self.resolver.allocation_checkpoint()
1190    }
1191
1192    /// Return destination identities allocated after a page-selection
1193    /// occurrence checkpoint, in qpdf allocator order.
1194    pub(crate) fn allocated_object_refs_after(&self, checkpoint: usize) -> Vec<ObjectRef> {
1195        self.resolver.allocated_object_refs_after(checkpoint)
1196    }
1197
1198    /// Promote and register an existing initialized handle without cloning its
1199    /// allocation or scheduling writer output. This is qpdf's
1200    /// `makeIndirectFromQPDFObject` (`libqpdf/QPDF.cc:1882-1888`). The returned
1201    /// handle retains the existing object allocation and is not automatically
1202    /// scheduled for output.
1203    pub fn make_indirect_from_object_handle(&self, handle: ObjectHandle) -> Result<ObjectHandle> {
1204        self.resolver.make_indirect_from_object_handle(handle)
1205    }
1206
1207    /// Create qpdf's owned empty stream object.
1208    ///
1209    /// qpdf's `QPDF::newStream()` first constructs an empty
1210    /// `QPDF_Stream` with parsed offset `0` and length `0`, then registers
1211    /// that same object allocation under a fresh generation-zero identity
1212    /// (`include/qpdf/QPDF.hh:319-340`; `libqpdf/QPDF.cc:1912-1931`). The
1213    /// stream constructor retains an empty dictionary and no source buffer
1214    /// (`libqpdf/QPDF_Stream.cc:109-137`). Parsed offset `0` is intentional:
1215    /// qpdf's `pipeStreamData` uses it to distinguish this no-data state from
1216    /// an original source stream (`libqpdf/QPDF_Stream.cc:571-607`).
1217    ///
1218    /// The new stream is registered with the document and can be mutated
1219    /// through the returned handle.
1220    pub fn new_stream(&self) -> Result<ObjectHandle> {
1221        self.resolver.new_stream_handle()
1222    }
1223
1224    /// Create qpdf's document-owned reserved construction sentinel.
1225    ///
1226    /// A reserved object is an indirect identity with no serializable PDF
1227    /// value. It exists to make circular construction possible and must be
1228    /// replaced before writing, matching `QPDF::newReserved` and
1229    /// `QPDF_Reserved::unparse`
1230    /// (`libqpdf/QPDF.cc:1900-1903`; `libqpdf/QPDF_Reserved.cc:20-27`).
1231    pub fn new_reserved(&self) -> Result<ObjectHandle> {
1232        self.resolver.new_reserved_handle()
1233    }
1234
1235    /// Replace a qpdf reserved object with a direct handle value.
1236    ///
1237    /// This is qpdf's `QPDF::replaceReserved`
1238    /// (`libqpdf/QPDF.cc:2008-2016`): only a reserved or null handle is
1239    /// accepted, and the replacement is installed into the existing object
1240    /// slot so every alias of `reserved` observes the new value. qpdf also
1241    /// accepts a direct null handle and passes its default `0 0` object
1242    /// identity to `replaceObject`; preserve that edge case rather than
1243    /// inventing a separate direct-null error path.
1244    ///
1245    /// The replacement keeps qpdf's `replaceObject` contract: it must be a
1246    /// direct handle owned by this document. The target handle's object
1247    /// identity is retained while its shared value state is rebound to the
1248    /// replacement.
1249    pub fn replace_reserved(
1250        &mut self,
1251        reserved: ObjectHandle,
1252        replacement: ObjectHandle,
1253    ) -> Result<()> {
1254        if !reserved.is_reserved() && !reserved.is_null() {
1255            return Err(Error::System(
1256                "replaceReserved called with non-reserved object".to_owned(),
1257            ));
1258        }
1259        let object_ref = reserved.object_ref().unwrap_or(ObjectRef::new(0, 0));
1260        self.replace_object(object_ref, replacement).map(|_| ())
1261    }
1262
1263    /// Create an owned stream and replace its data with the supplied buffer.
1264    ///
1265    /// This follows qpdf's buffer overload: the empty factory runs first and
1266    /// `replaceStreamData` then installs the buffer and applies the
1267    /// zero/nonzero `/Length` boundary
1268    /// (`include/qpdf/QPDF.hh:319-340`; `libqpdf/QPDF.cc:1921-1931`;
1269    /// `libqpdf/QPDF_Stream.cc:640-684`). The `Rc<Vec<u8>>` is retained
1270    /// without copying, matching qpdf's shared buffer overload.
1271    pub fn new_stream_with_data(&self, data: Rc<Vec<u8>>) -> Result<ObjectHandle> {
1272        let stream = self.new_stream()?;
1273        stream.replace_stream_data(data, None, None);
1274        Ok(stream)
1275    }
1276
1277    /// Copy one indirect object and its canonical foreign object graph into
1278    /// this document. This is qpdf's `QPDF::copyForeignObject`
1279    /// (`libqpdf/QPDF.cc:2019-2097`): indirect identities are reserved before
1280    /// recursive replacement, shared children and cycles reuse one
1281    /// destination handle, `/Pages` is a boundary, and stream payloads use
1282    /// the destination resolver's shared buffer/provider boundary.
1283    ///
1284    /// The destination retains the source-to-destination map, so copying the
1285    /// same source handle again returns the same destination identity. The
1286    /// source handle must be indirect and belong to a different live `Pdf`.
1287    ///
1288    /// A copied stream's data is not read until this document is written: a
1289    /// stream backed by [`StreamDataProvider`](crate::StreamDataProvider)
1290    /// stays a provider on the destination, not a materialized buffer, so it
1291    /// is re-read from the source on every write or read of the destination
1292    /// stream, not only the first. Matching qpdf's own documented contract
1293    /// (`include/qpdf/QPDF.hh:401-410`), **the source `Pdf` must remain
1294    /// alive for as long as this document may still read that copied
1295    /// stream** — including every later write, not just the first —
1296    /// because dropping it produces an [`Error::Internal`] the next time the
1297    /// writer tries to read the now-gone source. qpdf's escape hatch,
1298    /// `setImmediateCopyFrom`, is exposed as
1299    /// [`crate::Pdf::set_immediate_copy_from`]. Call it on the source before
1300    /// copying when provider-backed stream data must be materialized at copy
1301    /// time so the source need not survive until the destination is written.
1302    ///
1303    /// # Errors
1304    ///
1305    /// Returns [`Err`] when `foreign` is a direct handle, has no owning
1306    /// document, or is owned by this document itself, and when the
1307    /// underlying graph traversal fails: a foreign reserved sentinel
1308    /// encountered mid-copy, an unresolvable reference, or a prior call
1309    /// against the same source left this document's per-source copy state
1310    /// poisoned (qpdf never rolls this back on failure either, so a failed
1311    /// copy from a given source cannot be retried).
1312    pub fn copy_foreign_object(&mut self, foreign: &ObjectHandle) -> Result<ObjectHandle> {
1313        crate::object_copy::copy_foreign_object(self, foreign)
1314    }
1315
1316    /// Copy a direct or indirect foreign value through the same persistent
1317    /// qpdf-shaped `ObjCopier` map used by [`Self::copy_foreign_object`]. This
1318    /// is the internal counterpart of qpdf's
1319    /// `replaceForeignIndirectObjects` (`libqpdf/QPDF.cc:2158-2213`) for
1320    /// direct Catalog/trailer children.
1321    pub(crate) fn copy_foreign_value(
1322        &mut self,
1323        source_id: u64,
1324        foreign: &ObjectHandle,
1325    ) -> Result<ObjectHandle> {
1326        crate::object_copy::copy_foreign_value(self, source_id, foreign)
1327    }
1328
1329    /// Replace a canonical object value while retaining the target
1330    /// [`ObjectHandle`] identity. This is the qpdf-shaped mutation boundary;
1331    /// raw value snapshots and writer traversal remain outside this
1332    /// layer.
1333    ///
1334    /// This is qpdf's public `QPDF::replaceObject` surface
1335    /// (`include/qpdf/QPDF.hh:380-388`). qpdf accepts a direct, initialized
1336    /// handle and routes it through `updateCache`, whose existing cache slot
1337    /// adopts the replacement `QPDFValue` (`libqpdf/QPDF.cc:1980-1993`;
1338    /// `libqpdf/qpdf/QPDFObject_private.hh:117-120`), so outstanding handles
1339    /// observe the replacement.
1340    ///
1341    /// qpdf records the shared value transition in the canonical object cache;
1342    /// the writer observes that same live value without a separate dirty bit.
1343    pub fn replace_object(
1344        &mut self,
1345        object_ref: ObjectRef,
1346        replacement: ObjectHandle,
1347    ) -> Result<ObjectHandle> {
1348        // Like `set_object`, this is canonical cache replacement only.
1349        self.resolver.replace_object(object_ref, replacement)
1350    }
1351
1352    /// Swap the live values of two object generations while preserving each
1353    /// generation's canonical [`ObjectHandle`] identity.
1354    ///
1355    /// This is qpdf's public `QPDF::swapObjects` operation
1356    /// (`include/qpdf/QPDF.hh:396-399`; `libqpdf/QPDF.cc:2279-2289`). qpdf
1357    /// resolves both cache entries before exchanging their `QPDFValue`
1358    /// allocations, so outstanding handles continue to refer to their
1359    /// original object numbers while observing the swapped values. Unknown
1360    /// generations resolve to qpdf's ordinary null object before the swap.
1361    ///
1362    /// # Errors
1363    ///
1364    /// Propagates source resolution, recovery, and warning-delivery failures
1365    /// from either object.
1366    pub fn swap_objects(&mut self, first: ObjectRef, second: ObjectRef) -> Result<()> {
1367        self.resolver.swap_objects(first, second)
1368    }
1369
1370    /// Remove a canonical object from the resolver's xref/cache view and
1371    /// leave outstanding handles as floating null values. The legacy snapshot
1372    /// metadata is maintained separately by the `Pdf` facade. This is qpdf
1373    /// `removeObject`'s exact xref/cache mutation (`QPDF.cc:1996-2005`),
1374    /// separate from xref registration's transient free-row state
1375    /// (`QPDF.cc:686-708`, `:1187-1210`).
1376    pub(crate) fn remove_object_handle(&mut self, object_ref: ObjectRef) -> Result<()> {
1377        // qpdf's removeObject changes only the requested cache slot; already
1378        // resolved members of an ObjStm remain live in their own cache slots.
1379        self.resolver.remove_object(object_ref)?;
1380        Ok(())
1381    }
1382
1383    /// Return whether qpdf's live object cache has a newer generation for this
1384    /// object number. The writer's compressible walk uses this dynamic lookup
1385    /// rather than an xref-only snapshot (`QPDF.cc:2423-2430`).
1386    pub(crate) fn has_newer_cached_generation(&self, object_ref: ObjectRef) -> bool {
1387        self.resolver.has_newer_cached_generation(object_ref)
1388    }
1389
1390    pub(crate) fn is_canonical_object_handle(&self, handle: &ObjectHandle) -> bool {
1391        handle.qpdf_obj_gen().is_some_and(|object_gen| {
1392            self.resolver
1393                .registered_qpdf_obj_gen_handle(object_gen)
1394                .is_some_and(|canonical| canonical.is_same_object_as(handle))
1395        })
1396    }
1397
1398    /// Register the existing object allocation under a fresh indirect identity.
1399    ///
1400    /// qpdf's `makeIndirectObject` rejects only uninitialized input, prepares
1401    /// the canonical cache through `getObjectCount`, and stores the same
1402    /// object before setting its new identity (`libqpdf/QPDF.cc:1872-1897`).
1403    /// Direct, indirect, and reserved inputs retain their aliases. Existing
1404    /// cache entries for a re-promoted object remain present; looking one up
1405    /// sets the shared value's active identity to that entry's key.
1406    ///
1407    /// # Errors
1408    ///
1409    /// Returns [`Error::Internal`] for an uninitialized handle, or propagates
1410    /// cache preparation and object-number exhaustion errors.
1411    pub fn make_indirect_object_handle(&mut self, handle: ObjectHandle) -> Result<ObjectHandle> {
1412        self.resolver.make_indirect_from_object_handle(handle)
1413    }
1414
1415    /// This document's stable per-instance identity.
1416    ///
1417    /// This is qpdf's `QPDF::getUniqueId` (`include/qpdf/QPDF.hh:283`,
1418    /// `libqpdf/QPDF.cc:2294-2296`): constructed once when the document is
1419    /// created and never changes for the life of this [`Pdf`]. Compare it
1420    /// against [`ObjectHandle::owning_pdf_unique_id`] to test whether a
1421    /// handle is still owned by this document.
1422    pub fn unique_id(&self) -> u64 {
1423        self.unique_id
1424    }
1425
1426    pub(crate) fn take_foreign_object_map(
1427        &mut self,
1428        source_id: u64,
1429    ) -> BTreeMap<QpdfObjGen, ObjectRef> {
1430        self.foreign_object_maps
1431            .remove(&source_id)
1432            .unwrap_or_default()
1433    }
1434
1435    /// Return a snapshot of qpdf's persistent per-source foreign-object map
1436    /// without taking ownership of it. The map is keyed by the source's raw
1437    /// `QpdfObjGen`; page merge projects only its parser-valid source keys at
1438    /// its `ObjectRef`-typed consumer boundaries while the same raw map remains
1439    /// live for subsequent copies.
1440    pub(crate) fn foreign_object_map_snapshot(
1441        &self,
1442        source_id: u64,
1443    ) -> BTreeMap<QpdfObjGen, ObjectRef> {
1444        self.foreign_object_maps
1445            .get(&source_id)
1446            .cloned()
1447            .unwrap_or_default()
1448    }
1449
1450    pub(crate) fn set_foreign_object_map(
1451        &mut self,
1452        source_id: u64,
1453        map: BTreeMap<QpdfObjGen, ObjectRef>,
1454    ) {
1455        self.foreign_object_maps.insert(source_id, map);
1456    }
1457
1458    pub(crate) fn take_foreign_object_to_copy(&mut self, source_id: u64) -> Vec<ObjectHandle> {
1459        self.foreign_object_to_copy
1460            .remove(&source_id)
1461            .unwrap_or_default()
1462    }
1463
1464    pub(crate) fn set_foreign_object_to_copy(
1465        &mut self,
1466        source_id: u64,
1467        to_copy: Vec<ObjectHandle>,
1468    ) {
1469        self.foreign_object_to_copy.insert(source_id, to_copy);
1470    }
1471
1472    /// qpdf's `ObjCopier::visiting` equivalent (see
1473    /// [`Pdf::foreign_object_visiting`]'s own doc). Used only by the
1474    /// canonical `copy_foreign_object` port.
1475    pub(crate) fn take_foreign_object_visiting(&mut self, source_id: u64) -> BTreeSet<QpdfObjGen> {
1476        self.foreign_object_visiting
1477            .remove(&source_id)
1478            .unwrap_or_default()
1479    }
1480
1481    pub(crate) fn set_foreign_object_visiting(
1482        &mut self,
1483        source_id: u64,
1484        visiting: BTreeSet<QpdfObjGen>,
1485    ) {
1486        self.foreign_object_visiting.insert(source_id, visiting);
1487    }
1488
1489    /// Validate that historical xref-stream handles collected during xref
1490    /// loading are already present in the canonical resolver cache. qpdf reads each
1491    /// xref stream before merging the next xref section and keeps the same
1492    /// object cache for those historical objects (`QPDF.cc:626-710,1640-1716`);
1493    /// this handoff must not create a second graph or provenance map.
1494    pub(crate) fn install_parsed_xref_stream_handles(
1495        &mut self,
1496        parsed_xref_streams: BTreeMap<ObjectRef, ObjectHandle>,
1497    ) -> Result<()> {
1498        for (object_ref, _source) in parsed_xref_streams {
1499            if object_ref.number == 0
1500                || object_ref.generation == u16::MAX
1501                || self.resolver.xref_entry(object_ref).is_some()
1502            {
1503                continue;
1504            }
1505            let handle = self.get_object_handle(object_ref);
1506            if !handle.is_resolved() {
1507                // Not a qpdf-modelled state, so this stays an internal error
1508                // rather than a null resolution. `read_xrefStream` reads the
1509                // stream through `readObjectAtOffset(..., skip_cache_if_in_xref
1510                // = true)` (`QPDF.cc:956`), and that skip applies only while
1511                // the object still has an effective xref row (`QPDF.cc:1664`).
1512                // A superseded or freed row therefore takes the
1513                // `updateCache(og, oh.getObj(), ...)` branch (`QPDF.cc:1691`)
1514                // and caches the real /XRef stream, and `QPDF::resolve` returns
1515                // immediately for anything already resolved
1516                // (`QPDF.cc:1700-1704`). Installing a null here would put a
1517                // null where qpdf holds the parsed stream.
1518                return Err(Error::Internal(format!(
1519                    "canonical xref-stream handle {object_ref} was not resolved"
1520                )));
1521            }
1522        }
1523        Ok(())
1524    }
1525
1526    /// Return qpdf's complete canonical object cache in raw `QpdfObjGen` order.
1527    ///
1528    /// `QPDF::getAllObjects` first calls `fixDanglingReferences` and then
1529    /// walks `m->obj_cache` (`libqpdf/QPDF.cc:1258-1294`). The canonical
1530    /// resolver performs that preparation here: every effective source-xref
1531    /// object is resolved, and parser-discovered dangling references are
1532    /// retained as canonical indirect handles. Free rows are not in the
1533    /// effective source table, matching qpdf's `insertFreeXrefEntry` split
1534    /// between `xref_table` and `deleted_objects`.
1535    pub fn get_all_objects(&mut self) -> Result<Vec<ObjectHandle>> {
1536        self.resolver.get_all_objects()
1537    }
1538
1539    /// Prepare the canonical object cache through qpdf's
1540    /// `QPDF::fixDanglingReferences` boundary.
1541    ///
1542    /// `QPDFWriter::prepareFileForWrite` calls this before it touches the
1543    /// Catalog, and the writer must be able to perform that preparation
1544    /// without taking the broader `getAllObjects` enumeration route. Keep the
1545    /// resolver's idempotent fixed-state guard as the single owner of the
1546    /// operation (`libqpdf/QPDF.cc:1259-1269`).
1547    pub(crate) fn fix_dangling_references(&self) -> Result<()> {
1548        self.resolver.fix_dangling_references()
1549    }
1550
1551    /// Compatibility-only explicit resolution for the qtest-driver binary.
1552    /// Normal library users must use the resolving `try_*` accessors; qpdf has
1553    /// no public explicit `QPDF::resolve` handle facade.
1554    #[cfg(feature = "qtest-driver")]
1555    #[doc(hidden)]
1556    pub fn resolve(&mut self, handle: &ObjectHandle) -> Result<()> {
1557        handle.try_dereference()
1558    }
1559
1560    /// Read a linearization hint object and retain qpdf's source position for
1561    /// a following `damagedPDF` warning. The resolver distinguishes an already
1562    /// cached object from a newly parsed one, matching qpdf's
1563    /// `readObjectAtOffset`/`InputSource::getLastOffset` behavior.
1564    /// Read one object at an offset with qpdf's caller-provided description.
1565    /// The description is part of the source warning context, as with
1566    /// `QPDF::readObjectAtOffset` used by `QPDF::readHintStream`
1567    /// (`libqpdf/QPDF_linearization.cc:241-245`).
1568    pub(crate) fn resolve_at_offset_with_description(
1569        &self,
1570        offset: u64,
1571        expected: ObjectRef,
1572        description: impl AsRef<[u8]>,
1573    ) -> Result<(ObjectHandle, Option<u64>)> {
1574        self.resolver
1575            .resolve_at_offset_with_description(offset, expected, description)
1576    }
1577
1578    /// Return qpdf's first-1024-byte linearization candidate as an exact
1579    /// generation-zero object reference.
1580    pub(crate) fn linearization_candidate_ref(&self) -> Result<Option<ObjectRef>> {
1581        let Some(number) = self.resolver.linearization_candidate()? else {
1582            return Ok(None);
1583        };
1584        let Ok(number) = u32::try_from(number) else {
1585            return Ok(None);
1586        };
1587        if number == 0 {
1588            return Ok(None);
1589        }
1590        Ok(Some(ObjectRef::new(number, 0)))
1591    }
1592}
1593
1594#[cfg(test)]
1595mod warning_api_tests {
1596    use super::Pdf;
1597
1598    #[test]
1599    fn warning_api_drains_without_replaying_and_retains_suppressed_warnings() {
1600        let mut pdf =
1601            Pdf::open_mem_owned(crate::engine::EMPTY_PDF_BYTES.to_vec()).expect("empty PDF opens");
1602        pdf.set_suppress_warnings(true);
1603
1604        pdf.push_warning("first warning").unwrap();
1605        assert!(pdf.any_warnings());
1606        assert_eq!(pdf.num_warnings(), 1);
1607
1608        let first = pdf.get_warnings();
1609        assert_eq!(first.len(), 1);
1610        assert!(!pdf.any_warnings());
1611        assert_eq!(pdf.num_warnings(), 0);
1612        assert!(pdf.get_warnings().is_empty());
1613
1614        pdf.push_warning("second warning").unwrap();
1615        let second = pdf.get_warnings();
1616        assert_eq!(second.len(), 1);
1617        assert_eq!(second.entries()[0].get_message_detail(), b"second warning");
1618        assert!(!pdf.any_warnings());
1619    }
1620}
1621
1622#[cfg(test)]
1623mod reopenable_source_tests {
1624    use super::{Pdf, PdfOpenOptions, ReopenableFile};
1625    use crate::engine::EMPTY_PDF_BYTES;
1626    use std::io::Read;
1627
1628    #[test]
1629    fn close_input_source_releases_the_file_backed_reopen_controller() {
1630        // Codex review on PR #1470: close_input_source only replaced the
1631        // resolver's own StreamInput, leaving Pdf::input_source_control -- a
1632        // second, independent owner of the same reopen state -- holding the
1633        // OS file open until the whole Pdf was dropped.
1634        let temp = tempfile::tempdir().expect("temporary source directory");
1635        let path = temp.path().join("source.pdf");
1636        std::fs::write(&path, EMPTY_PDF_BYTES).expect("write source");
1637
1638        let pdf = Pdf::open_file_with_options(&path, PdfOpenOptions::default())
1639            .expect("open file-backed document");
1640        let control = pdf
1641            .input_source_control
1642            .clone()
1643            .expect("file-backed documents install a reopen controller");
1644        assert!(
1645            !control.is_closed_for_test(),
1646            "the controller starts with an open file handle"
1647        );
1648
1649        pdf.close_input_source();
1650
1651        assert!(
1652            control.is_closed_for_test(),
1653            "close_input_source must release the reopen controller's file handle too"
1654        );
1655    }
1656
1657    #[test]
1658    fn closed_source_reopens_at_the_last_reader_position() {
1659        let temp = tempfile::tempdir().expect("temporary source directory");
1660        let path = temp.path().join("source.pdf");
1661        std::fs::write(&path, b"abcdef").expect("write source");
1662
1663        let mut source = ReopenableFile::new(&path).expect("open source");
1664        let controller = source.controller();
1665        controller.set_stay_open(false);
1666
1667        let mut first = [0; 2];
1668        source.read_exact(&mut first).expect("read first bytes");
1669        assert_eq!(&first, b"ab");
1670        assert!(
1671            source.is_closed_for_test(),
1672            "source must close after a read"
1673        );
1674
1675        controller.set_stay_open(true);
1676        let mut second = [0; 2];
1677        source.read_exact(&mut second).expect("reopen and read");
1678        assert_eq!(&second, b"cd");
1679        assert!(
1680            !source.is_closed_for_test(),
1681            "explicit keep-open must retain source"
1682        );
1683    }
1684
1685    #[cfg(unix)]
1686    #[test]
1687    fn read_error_closes_a_nonpersistent_source() {
1688        let temp = tempfile::tempdir().expect("temporary source directory");
1689        let directory = temp.path().join("not-a-file");
1690        std::fs::create_dir(&directory).expect("create directory source");
1691
1692        let mut source = ReopenableFile::new(&directory).expect("open directory source");
1693        source.controller().set_stay_open(false);
1694        let error = source
1695            .read(&mut [0; 1])
1696            .expect_err("directory read must fail");
1697        assert_eq!(error.kind(), std::io::ErrorKind::IsADirectory);
1698        assert!(
1699            source.is_closed_for_test(),
1700            "failed nonpersistent read must close source"
1701        );
1702    }
1703}
1704
1705#[cfg(test)]
1706mod encryption_state_commit_tests {
1707    use super::{Pdf, PdfOpenOptions};
1708    use crate::{Error, ObjectHandle, QPDFLogger};
1709    use std::io::Cursor;
1710
1711    #[test]
1712    fn overlength_raw_hex_key_reports_the_authenticated_key_length() {
1713        let fixture = std::fs::read(
1714            std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1715                .join("../../tests/fixtures/encrypted/v5-aes-256-r6.pdf"),
1716        )
1717        .expect("R6 fixture");
1718        let pdf = Pdf::open_with_options(
1719            Cursor::new(fixture),
1720            PdfOpenOptions {
1721                password: b"abababababababababababababababababababababababababababababababababababababababab"
1722                    .to_vec(),
1723                password_is_hex_key: true,
1724                ..PdfOpenOptions::default()
1725            },
1726        )
1727        .expect("qpdf accepts an overlength raw key for this inspection fixture");
1728
1729        assert_eq!(pdf.encryption_length_bits(), Some(320));
1730    }
1731
1732    #[test]
1733    fn authenticated_state_is_not_committed_before_perms_warning_delivery() {
1734        let fixture = std::fs::read(
1735            std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1736                .join("../../tests/fixtures/encrypted/v5-aes-256-r6.pdf"),
1737        )
1738        .expect("R6 fixture");
1739        let options = PdfOpenOptions {
1740            password: b"user-v5-r6".to_vec(),
1741            ..PdfOpenOptions::default()
1742        };
1743        let mut pdf = Pdf::open_with_options(Cursor::new(fixture), options.clone())
1744            .expect("R6 fixture authenticates");
1745
1746        let encrypt = pdf
1747            .encrypt_dictionary_handle()
1748            .expect("encryption dictionary lookup")
1749            .expect("encrypted fixture");
1750        encrypt
1751            .replace_key(b"/Perms", ObjectHandle::string(vec![0]))
1752            .expect("replace /Perms");
1753        *pdf.encryption.borrow_mut() = None;
1754
1755        let logger = QPDFLogger::create();
1756        logger.set_warn(Some(crate::pipeline::PipelineHandle::new(
1757            crate::pipeline::test_support::NthWriteFailure::new(1),
1758        )));
1759        pdf.set_logger(logger);
1760
1761        let inspection = pdf
1762            .encryption_inspection
1763            .borrow()
1764            .as_ref()
1765            .cloned()
1766            .expect("encrypted document has parsed inspection state");
1767        let error = pdf
1768            .authenticate_if_encrypted_once(&options, &inspection)
1769            .expect_err("warning sink failure must propagate");
1770        assert!(matches!(
1771            error,
1772            Error::System(message) if message == "sink write failure 1"
1773        ));
1774        assert!(
1775            pdf.encryption.borrow().is_none(),
1776            "authentication state must remain uncommitted when /Perms warning delivery fails"
1777        );
1778    }
1779}
1780
1781#[cfg(test)]
1782mod lazy_open_tests {
1783    use super::*;
1784    use std::fs::File;
1785    use std::io::BufReader;
1786
1787    #[test]
1788    fn opens_pdf_without_resolving_any_object_body() {
1789        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1790            .join("../../tests/fixtures/minimal.pdf");
1791        let file = File::open(path).unwrap();
1792        let mut pdf = Pdf::open(BufReader::new(file)).unwrap();
1793
1794        assert_eq!(
1795            pdf.resolver.resolved_object_count_for_test(),
1796            0,
1797            "opening must leave every cached object body unresolved"
1798        );
1799        assert_eq!(pdf.version(), "1.7");
1800        let root = pdf.trailer().try_get_key(b"/Root").unwrap();
1801        assert_eq!(root.object_ref(), Some(ObjectRef::new(1, 0)));
1802        assert_eq!(
1803            pdf.resolver.resolved_object_count_for_test(),
1804            0,
1805            "reading the trailer root reference must not resolve its body"
1806        );
1807    }
1808}
1809
1810#[cfg(test)]
1811mod compressible_owner_tests {
1812    use super::*;
1813    use crate::reader::resolver::ResolverHandle;
1814    use std::cell::Cell;
1815    use std::io::Cursor;
1816
1817    fn pdf() -> Pdf<Cursor<Vec<u8>>> {
1818        Pdf::open(Cursor::new(
1819            include_bytes!("../../../tests/fixtures/compat/one-page-no-ext.pdf").to_vec(),
1820        ))
1821        .unwrap()
1822    }
1823
1824    #[test]
1825    fn canonical_ref_views_ignore_non_indirect_object_generations() {
1826        let mut pdf = pdf();
1827        let zero = pdf.get_object_handle(ObjectRef::new(0, 0));
1828        let max_generation = pdf.get_object_handle(ObjectRef::new(1, u16::MAX));
1829
1830        assert!(!zero.is_indirect());
1831        assert_eq!(zero.object_ref(), None);
1832        assert!(max_generation.is_indirect());
1833        assert_eq!(
1834            max_generation.object_ref(),
1835            None,
1836            "generation 65535 remains raw but is outside qpdf's N G R projection"
1837        );
1838        assert!(!pdf.canonical_object_refs().contains(&ObjectRef::new(0, 0)));
1839        assert!(!pdf
1840            .canonical_object_refs()
1841            .contains(&ObjectRef::new(1, u16::MAX)));
1842        assert!(!pdf
1843            .canonical_live_object_refs()
1844            .contains(&ObjectRef::new(0, 0)));
1845        assert!(!pdf
1846            .canonical_live_object_refs()
1847            .contains(&ObjectRef::new(1, u16::MAX)));
1848    }
1849
1850    #[test]
1851    fn parsed_xref_stream_handoff_rejects_an_unresolved_canonical_slot() {
1852        let mut pdf = pdf();
1853        let object_ref = ObjectRef::new(99, 0);
1854        // qpdf never observes this state. `read_xrefStream` reads the stream
1855        // through `readObjectAtOffset(..., skip_cache_if_in_xref = true)`
1856        // (`QPDF.cc:956`), and that skip only applies when the object still has
1857        // an effective xref row (`QPDF.cc:1664`); an absent or superseded row
1858        // therefore takes the `updateCache(og, oh.getObj(), ...)` branch
1859        // (`QPDF.cc:1691`) and caches the real /XRef stream. `QPDF::resolve`
1860        // returns immediately for anything already resolved
1861        // (`QPDF.cc:1700-1704`), so its absent-entry null path is unreachable
1862        // for a parsed xref stream. An unresolved canonical slot here means the
1863        // loader built a second object graph, which is a flpdf invariant
1864        // violation rather than a qpdf-modelled document state.
1865        let source = ObjectHandle::new_indirect_unresolved(object_ref, -1);
1866        let error = pdf
1867            .install_parsed_xref_stream_handles(BTreeMap::from([(object_ref, source)]))
1868            .expect_err("canonical xref-stream provenance must already be resolved");
1869
1870        assert!(matches!(error, Error::Internal(message) if message.contains("99 0")));
1871    }
1872
1873    #[test]
1874    fn compressible_walk_removes_stale_aliases_without_invalidating_preparation() {
1875        let mut pdf = Pdf::open(Cursor::new(
1876            include_bytes!(
1877                "../../../tests/fixtures/compat/compressible-stale-generation-alias.pdf"
1878            )
1879            .to_vec(),
1880        ))
1881        .unwrap();
1882        let versions = pdf
1883            .root_handle()
1884            .unwrap()
1885            .try_get_key(b"/Versions")
1886            .unwrap();
1887        let old = versions.try_get_array_item(0).unwrap();
1888        let current = versions.try_get_array_item(1).unwrap();
1889        let result = pdf.get_compressible_objgens().unwrap();
1890        assert_eq!(
1891            result,
1892            vec![
1893                ObjectRef::new(1, 0),
1894                ObjectRef::new(2, 0),
1895                ObjectRef::new(3, 1)
1896            ]
1897        );
1898        assert!(old.is_direct() && old.is_null());
1899        assert_eq!(current.object_ref(), Some(ObjectRef::new(3, 1)));
1900        assert!(pdf
1901            .resolver
1902            .registered_handle(ObjectRef::new(3, 0))
1903            .is_none());
1904        assert!(pdf.dangling_references_fixed());
1905    }
1906
1907    #[test]
1908    fn compressible_removal_erases_the_canonical_slot_before_replacement() {
1909        let mut pdf = Pdf::open(Cursor::new(
1910            include_bytes!("../../../tests/fixtures/compat/one-page.pdf").to_vec(),
1911        ))
1912        .unwrap();
1913        let old = pdf
1914            .get_all_objects()
1915            .unwrap()
1916            .into_iter()
1917            .find(|object| object.as_stream_dict().is_some())
1918            .unwrap();
1919        let old_ref = old.object_ref().unwrap();
1920        pdf.replace_object(
1921            ObjectRef::new(old_ref.number, old_ref.generation + 1),
1922            ObjectHandle::integer(42),
1923        )
1924        .unwrap();
1925
1926        let (_, removed) = pdf
1927            .get_compressible_objgens_with_removed()
1928            .expect("compressible walk succeeds");
1929        assert!(removed.contains(&old_ref));
1930        assert!(!pdf.canonical_object_refs().contains(&old_ref));
1931
1932        pdf.replace_object(old_ref, ObjectHandle::integer(99))
1933            .expect("qpdf-style replacement re-registers the removed generation");
1934        assert!(pdf.canonical_live_object_refs().contains(&old_ref));
1935    }
1936
1937    #[test]
1938    fn compressible_walk_checks_visited_before_stale_generation_removal() {
1939        let mut pdf = Pdf::open(Cursor::new(
1940            include_bytes!(
1941                "../../../tests/fixtures/compat/compressible-stale-generation-alias.pdf"
1942            )
1943            .to_vec(),
1944        ))
1945        .unwrap();
1946        let root = pdf.root_handle().unwrap();
1947        let versions = root.try_get_key(b"/Versions").unwrap();
1948        let old = versions.try_get_array_item(0).unwrap();
1949        let current = versions.try_get_array_item(1).unwrap();
1950        versions
1951            .set_array_items(vec![current, old.clone()])
1952            .unwrap();
1953        root.replace_key(b"/ZCycle", root.clone()).unwrap();
1954        assert_eq!(
1955            pdf.get_compressible_objgens().unwrap(),
1956            vec![
1957                ObjectRef::new(1, 0),
1958                ObjectRef::new(2, 0),
1959                ObjectRef::new(3, 1)
1960            ]
1961        );
1962        assert_eq!(old.object_ref(), Some(ObjectRef::new(3, 0)));
1963        assert!(old.is_indirect());
1964    }
1965
1966    #[test]
1967    fn compressible_walk_preserves_order_and_keeps_excluded_container_children() {
1968        let mut pdf = pdf();
1969        let root = pdf.root_handle().unwrap();
1970        for key in root.try_get_keys().unwrap() {
1971            root.remove_key(&key);
1972        }
1973        let a = pdf
1974            .make_indirect_from_object_handle(ObjectHandle::integer(1))
1975            .unwrap();
1976        let b = pdf
1977            .make_indirect_from_object_handle(ObjectHandle::integer(2))
1978            .unwrap();
1979        let c = pdf
1980            .make_indirect_from_object_handle(ObjectHandle::integer(3))
1981            .unwrap();
1982        let null = pdf
1983            .make_indirect_from_object_handle(ObjectHandle::null())
1984            .unwrap();
1985        let length = pdf
1986            .make_indirect_from_object_handle(ObjectHandle::integer(3))
1987            .unwrap();
1988        let sig = pdf
1989            .make_indirect_from_object_handle(ObjectHandle::dictionary(vec![
1990                (b"/Type".to_vec(), ObjectHandle::name(b"Sig".to_vec())),
1991                (b"/ByteRange".to_vec(), ObjectHandle::array(vec![])),
1992                (
1993                    b"/Contents".to_vec(),
1994                    ObjectHandle::string(b"signature".to_vec()),
1995                ),
1996                (b"/Child".to_vec(), a.clone()),
1997            ]))
1998            .unwrap();
1999        let incomplete_sig = pdf
2000            .make_indirect_from_object_handle(ObjectHandle::dictionary(vec![
2001                (b"/Type".to_vec(), ObjectHandle::name(b"Sig".to_vec())),
2002                (b"/ByteRange".to_vec(), ObjectHandle::array(vec![])),
2003                (b"/Contents".to_vec(), ObjectHandle::null()),
2004            ]))
2005            .unwrap();
2006        let encryption = pdf
2007            .make_indirect_from_object_handle(ObjectHandle::dictionary(vec![(
2008                b"/Child".to_vec(),
2009                b.clone(),
2010            )]))
2011            .unwrap();
2012        let stream = pdf.new_stream_with_data(Rc::new(b"xyz".to_vec())).unwrap();
2013        let calls = Rc::new(Cell::new(0));
2014        let provider_calls = calls.clone();
2015        stream
2016            .replace_stream_data_with_callback(
2017                move |pipeline| {
2018                    provider_calls.set(provider_calls.get() + 1);
2019                    pipeline.write(b"xyz")?;
2020                    pipeline.finish()?;
2021                    Ok(())
2022                },
2023                None,
2024                None,
2025            )
2026            .unwrap();
2027        let dict = stream.as_stream_dict().unwrap();
2028        dict.replace_key(b"/Type", ObjectHandle::name(b"ObjStm".to_vec()))
2029            .unwrap();
2030        dict.replace_key(b"/Length", length.clone()).unwrap();
2031        dict.replace_key(b"/Meta", c.clone()).unwrap();
2032        root.replace_key(
2033            b"/AArray",
2034            ObjectHandle::array(vec![a.clone(), null.clone(), a.clone()]),
2035        )
2036        .unwrap();
2037        root.replace_key(b"/BSig", sig.clone()).unwrap();
2038        root.replace_key(b"/CIncomplete", incomplete_sig.clone())
2039            .unwrap();
2040        root.replace_key(b"/DNull", null.clone()).unwrap();
2041        root.replace_key(b"/EStream", stream.clone()).unwrap();
2042        root.replace_key(b"/ZLengthElsewhere", length.clone())
2043            .unwrap();
2044        pdf.trailer()
2045            .replace_key(b"/Encrypt", encryption.clone())
2046            .unwrap();
2047        let expected: Vec<ObjectRef> =
2048            [b, root.clone(), a, null, incomplete_sig, c, length.clone()]
2049                .iter()
2050                .map(|object| object.object_ref().unwrap())
2051                .collect();
2052        assert_eq!(pdf.get_compressible_objgens().unwrap(), expected);
2053        assert_eq!(
2054            calls.get(),
2055            0,
2056            "document traversal must not pipe stream providers"
2057        );
2058        root.remove_key(b"/ZLengthElsewhere");
2059        let without_length = pdf.get_compressible_objgens().unwrap();
2060        assert!(!without_length.contains(&length.object_ref().unwrap()));
2061        assert!(!without_length.contains(&sig.object_ref().unwrap()));
2062        assert!(!without_length.contains(&encryption.object_ref().unwrap()));
2063        assert!(!without_length.contains(&stream.object_ref().unwrap()));
2064        assert_eq!(calls.get(), 0);
2065        assert_eq!(stream.get_raw_stream_data().unwrap().as_slice(), b"xyz");
2066        assert_eq!(calls.get(), 1);
2067    }
2068
2069    #[test]
2070    fn compressible_walk_reports_qpdfs_prepared_object_count_bound() {
2071        struct GrowOnDrop {
2072            resolver: std::rc::Weak<ResolverHandle<Cursor<Vec<u8>>>>,
2073            pending: ObjectHandle,
2074        }
2075        impl crate::StreamDataProvider for GrowOnDrop {}
2076        impl Drop for GrowOnDrop {
2077            fn drop(&mut self) {
2078                let resolver = self.resolver.upgrade().unwrap();
2079                let new_object = resolver
2080                    .make_indirect_from_object_handle(ObjectHandle::integer(7))
2081                    .unwrap();
2082                self.pending.append_array_item(new_object).unwrap();
2083            }
2084        }
2085        let mut pdf = Pdf::open(Cursor::new(
2086            include_bytes!("../../../tests/fixtures/compat/one-page.pdf").to_vec(),
2087        ))
2088        .unwrap();
2089        let old = pdf
2090            .get_all_objects()
2091            .unwrap()
2092            .into_iter()
2093            .find(|object| object.as_stream_dict().is_some())
2094            .unwrap();
2095        let old_id = old.object_ref().unwrap();
2096        pdf.replace_object(
2097            ObjectRef::new(old_id.number, old_id.generation + 1),
2098            ObjectHandle::integer(42),
2099        )
2100        .unwrap();
2101        let pending = ObjectHandle::array(vec![]);
2102        pdf.root_handle()
2103            .unwrap()
2104            .replace_key(b"/ZPending", pending.clone())
2105            .unwrap();
2106        old.replace_stream_data_provider(
2107            Rc::new(GrowOnDrop {
2108                resolver: Rc::downgrade(&pdf.resolver),
2109                pending,
2110            }),
2111            None,
2112            None,
2113        )
2114        .unwrap();
2115        assert!(
2116            matches!(pdf.get_compressible_objgens(), Err(Error::Internal(message)) if message == "unexpected object id encountered in getCompressibleObjGens")
2117        );
2118    }
2119}