Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,46 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
past it, one `DiagnosticsSuppressed` entry records how many further reports were dropped instead
of growing without limit. Purely additive: nothing that returned data now returns null, and
nothing that used to succeed now throws. (#385)
- **`PdfDocumentReader.PageCount`, `Pages`, and `GetPage`: a page-tree walk over `/Root` →
`/Pages` → `/Kids` (ISO 32000-2 §7.7.3).** `PageCount` is what the walk finds, never a node's own
`/Count`. Table 30 makes the `/Kids` array and its descendants what "definitively determines the
number of descendant pages", and real producers disagree with their own `/Count` often enough
that trusting it would misreport page counts on ordinary files. Each `PdfReadPage` carries its
`/MediaBox`, `/CropBox`, and `/Rotate` already resolved through the inheritance chain (§7.7.3.4):
the nearest ancestor that defines a valid attribute wins over a farther one, and the page's own
entry wins over all of them when it is itself valid. The walk uses the tree the reader actually
descended, not a page's own `/Parent`, so a forged `/Parent` cannot redirect inheritance.
`CropBox` is additionally intersected with `MediaBox` per §14.11.2.1. The walk is iterative,
budgeted at 1,000,000 `/Kids` elements examined in total and capped at 256 levels of nesting and
100,000 page leaves, and a repeated indirect reference to the same node, page object, or shared
`/Kids` array is treated as a cycle and skipped. A dictionary that fails to resolve, or resolves
to the wrong shape, is skipped rather than aborting the walk: eight new
`PdfReaderDiagnosticCode` values (`PageTreeMissing`, `PageTreeCycle`, `PageTreeDepthExceeded`,
`PageTreeLeafLimitExceeded`, `PageTreeKidNotDictionary`, `PageAttributeInvalid`,
`PageTreeNodeMalformed`, `PageTreeNodeLimitExceeded`) report through the diagnostics channel added
in #385 rather than throwing; a page tree the walk cannot use at all leaves `PageCount` at 0. The
three codes that say the page list found so far is incomplete (`PageTreeLeafLimitExceeded`,
`PageTreeNodeLimitExceeded`, and the first `PageTreeDepthExceeded` of a walk) are retained past
`MaxDiagnostics` rather than risk being the one report a caller most needs and never sees: the
leaf and node limits each end the walk the instant they are reported, so at most one of that
pair, plus the depth code's first occurrence, is ever retained in the same walk. Computed
lazily, on first access, and cached for the reader's lifetime. (#98)

### Changed

- **`PdfObjectParser.ParseReal` now rejects an out-of-range real literal with
`InvalidDataException` instead of letting `PdfReal`'s constructor throw `ArgumentException`.**
A real number with 310 or more integer digits parses to +/-Infinity under `double.TryParse`
(ISO 32000-2 §7.3.3's implementation-limited range, Annex C.2 / Table C.1, informative); every
other malformed-input path in this parser already surfaces as `InvalidDataException`, and this
one now matches, reachable by any caller resolving a real number, not just the page-tree walk
that first exposed the mismatch. `PdfReader.Open` now throws `InvalidDataException` for such a
literal where 2.3.0 threw `ArgumentException` out of `PdfReal`'s constructor (2.3.0's
`ParseReal` had no non-finite guard at all). The page-tree walk, new in this release, does not
let this propagate: it catches the exception per object and reports a diagnostic
(`PageTreeMissing`, `PageTreeKidNotDictionary`, `PageTreeNodeMalformed`, or
`PageAttributeInvalid`, depending on where the literal sits) instead of throwing. (#98)

- **The password-protected-file message now says which of two outcomes happened.** No `--password`
was given, or an empty one was (`--password ""`), and either way it prints "supply it with
--password"; a non-empty `--password` that does not open the file prints "the supplied
Expand Down
101 changes: 94 additions & 7 deletions docs/reader-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,8 +119,87 @@ signature's `/ByteRange`, `/Contents`, `/M` (as `SigningTime`), and `/SubFilter`
*reading*, not *verification* — checking integrity, coverage, or a certificate chain is future
work (see the capability table below).

Page content — text runs, images — is not on the public surface yet. `Catalog` and `Signatures`
are what a v2.3 reader exposes; extracting page content is the next reader milestone.
Page content (text runs, images) is not on the public surface yet; extracting it is the next
reader milestone. Locating the pages themselves is:

### Pages

```csharp
int count = reader.PageCount; // never trusts a node's own /Count
foreach (PdfReadPage page in reader.Pages)
Console.WriteLine($"page {page.Index}: {page.MediaBox.Width}x{page.MediaBox.Height}, rotate {page.Rotate}");

PdfReadPage first = reader.GetPage(0); // throws ArgumentOutOfRangeException outside [0, PageCount)
```

`PageCount`/`Pages`/`GetPage` walk the page tree (ISO 32000-2 §7.7.3) from `/Root` → `/Pages` →
`/Kids` on first access and cache the result (never in `PdfReader.Open` itself). The walk counts
what `/Kids` actually contains, not any node's `/Count`. Table 30 puts that obligation on the
writer, not the reader: the `/Kids` array and its descendants are what "definitively determines
the number of descendant pages", and real producers disagree with their own `/Count` often enough
that trusting it would misreport ordinary files, not just adversarial ones. A dictionary reached
through `/Kids` is classified by its own `/Type` first: `/Type /Pages` is always a node, whether
`/Type` names it explicitly or a usable `/Kids` array decides it structurally, and either way a
stray `/Contents` alongside it is reported as `PageTreeNodeMalformed`: that key is a Table 31
page-object entry with no row in Table 30's node listing, and §7.7.3.4 carries only inheritable
attributes down to descendants, so on a node it describes nothing at all (a meaningless entry, not
a conformance violation, but flagged anyway). `/Type /Page` is always a leaf; a stray `/Kids`
alongside it is both ignored and reported as `PageTreeNodeMalformed` the same way. `/Type
/Template` (Table 31's own Type row admits it as the other legal page `/Type`, §7.7.3.3) and
anything naming neither is skipped and reported as `PageTreeNodeMalformed` too: that same Table
31, in its Parent row, exempts Template from carrying one at all ("Objects of Type Template shall
have no Parent key"), a rule §12.7.7 repeats, so a Template page has no parent and can never
legitimately sit in any node's `/Kids`. A dictionary with no `/Type` at all falls back to whether
it has a `/Kids` array for that classification, silently either way, since plenty of real
producers omit `/Type /Page` on a genuine leaf. Absent, an explicit null, and a reference (or a
chain of references, ISO 32000-2 §7.3.10's 2020 NOTE) that resolves to either of those are the
same thing to the walker for a dictionary ENTRY throughout all of this: §7.3.9 makes a null value
equivalent to an absent key, and extends that to a reference resolving to nothing. This
equivalence is scoped to entries, not `/Kids` ARRAY ELEMENTS: `[3 0 R null]` or `[3 0 R 9 0 R]`
with object 9 undefined still reports `PageTreeKidNotDictionary` for that element rather than
silently skipping it, since Table 30's own `/Kids` row governs what counts as a valid child (a
page object or another page-tree node) separately from §7.3.9's null-equivalence rule.

The root (`/Root/Pages`) goes through the same `/Type`-and-structure classification: a root that
is itself a leaf, or that names something other than `/Type /Pages` (the catalog dictionary
reused as its own `/Pages` entry, say), reports `PageTreeMissing` instead of being walked, since
ISO 32000-2 §7.7.2 Table 29 requires `/Root/Pages` to be the root of the page tree and §7.7.3.2
defines what counts as one. Only a root that FAILS that classification skips its own
stray-`/Contents` check; a root that clears it always reaches that check, whether or not it also
has usable `/Kids` of its own, so a root with neither can report `PageTreeNodeMalformed` (the
stray `/Contents`) and `PageTreeMissing` (the unusable `/Kids`) together, not one instead of the
other. Any node's `/Kids` resolving to a present but empty array, root included, contributes zero
pages for that subtree with no diagnostic at all: §7.7.3 does not require a document to have at
least one page, so an empty tree is a valid zero-page document, not a defect.

Each `PdfReadPage` exposes `MediaBox`, `CropBox`, and `Rotate` already resolved through the
inheritance chain (§7.7.3.4) and normalised: corners ordered low-to-high, rotation folded to one
of 0/90/180/270. A malformed value anywhere in the chain is skipped in favour of the nearest
ancestor that supplies a valid one, each skip reported as `PageAttributeInvalid`; only once nothing
in the chain resolves at all does `MediaBox` fall back to US Letter (612 × 792 points, this
reader's own convention, since the specification names no default), `CropBox` to the page's own
`MediaBox`, and `Rotate` to 0. `CropBox` is additionally intersected with `MediaBox` per §14.11.2.1
once resolved: a crop region extending past the media box is clipped to it, not exposed as
written, and a crop box that collapses to zero width or height at the intersection is kept as that
zero-width (or zero-height) intersection rather than replaced, as long as it still touches the
media box (ISO 32000-2 §7.9.5's NOTE records that rectangles can have zero width or height); a
`CropBox` that shares no overlap with `MediaBox` at all (§14.11.2.1's intersection would be
empty) falls back to `MediaBox` with its own `PageAttributeInvalid` report. A merely absent,
optional `CropBox` or `Rotate` stays silent: that is the spec's own default, not a problem. A
page tree the walk cannot use at all reports `PageTreeMissing` and leaves `PageCount` at 0
rather than throwing; a node whose own `/Type` or `/Kids` shape is wrong is skipped, treated as a
leaf, or still walked as a node, per the rules described above, and reports
`PageTreeNodeMalformed` either way; a cycle (`PageTreeCycle`), a nesting depth past 256
(`PageTreeDepthExceeded`), more than 100,000 leaves (`PageTreeLeafLimitExceeded`), or more than
1,000,000 `/Kids` elements examined in total (`PageTreeNodeLimitExceeded`) each report their own
code and return whatever pages were found up to that point. `PageTreeCycle` also covers a repeat
reached through different aliases, not just a literal repeated reference: two `/Kids` elements
naming different objects that both resolve, one or more indirect references later, to the same
page or node still count as one repeated object, reported once as `PageTreeCycle` naming the
object they both resolve to. A shared page is listed once, under its own object number; a shared
node's descendant pages are listed once each, the same as if the second alias had never been
written, apart from that diagnostic. See `PdfReaderDiagnosticCode`'s `2xx` block for the full
list.

### Diagnostics

Expand All @@ -136,11 +215,18 @@ cross-reference table it had to rebuild, a filter chain entry that didn't resolv
declared itself, a TIFF predictor applied at a bit depth this decoder doesn't undo correctly. Each
entry carries a `Code`, a `Severity` (`Info`/`Warning`/`Error`), a human-readable `Message`, and,
where the condition concerns one, an `ObjectNumber` and `Generation`. `PageIndex` is also on every
entry, but stays `null` until
the page walk lands (#98) — nothing this release reports is scoped to a page. `MaxDiagnostics`
(default 1000) is tighten-only, matching `MaxDecodedStreamBytes` and
`ReconstructionBudgetMultiplier` above — past the cap, a single `DiagnosticsSuppressed` entry says
how many further reports were dropped rather than growing the list without bound.
entry, populated by the page-tree walk's own `PageAttributeInvalid` reports against a page's own
dictionary (see Pages above); a malformed attribute found on an ancestor node instead reports the
same code once against that node with `PageIndex` null, so filtering diagnostics by page index
alone misses it. A caller must also look at reports with a null page index; every other code
either concerns no specific page or is reported before a page index is known.
`MaxDiagnostics` (default 1000) is tighten-only, matching `MaxDecodedStreamBytes` and
`ReconstructionBudgetMultiplier` above: past the cap, a single `DiagnosticsSuppressed` entry says
how many further reports were dropped rather than growing the list without bound. Exempt from
that cap: the `2xx` page-tree codes that say the page list found so far is incomplete
(`PageTreeLeafLimitExceeded`, `PageTreeNodeLimitExceeded`, and the first `PageTreeDepthExceeded`
of a walk), each retained past `MaxDiagnostics` rather than risk going silent on exactly the
input the cap exists to bound (see Pages above and `PdfReaderOptions.MaxDiagnostics`).

`Diagnostics` is a live view: streams decode lazily, so the list can still grow after `Open`
returns, as later calls resolve more of the document. Unlike the reader's other collections, which
Expand Down Expand Up @@ -239,6 +325,7 @@ a guard test keeps the two copies byte-identical.
| Configurable, tighten-only resource limits | ✅ Supported | ISO 32000-2 Annex C.1/C.3, informative (#376) |
| Decryption: Standard handler, `/V` 1/2/4/5, `/R` 2–6, RC4-40–128, AES-128/256 | ✅ Supported | ISO 32000-2 §7.6 |
| Reading the document catalog | ✅ Supported | ISO 32000-2 §7.7.2 |
| Page tree walk and page access (`PageCount`, `Pages`, `GetPage`) with inherited `/MediaBox`, `/CropBox`, `/Rotate` | ✅ Supported | ISO 32000-2 §7.7.3 (#98) |
| Reading digital signature metadata (`/ByteRange`, `/Contents`, `/M`, `/SubFilter`) | ✅ Supported (read only, not verified) | ISO 32000-2 §12.8 |
| Writing a decrypted copy (`SaveDecrypted`/`SaveDecryptedAsync`) | ✅ Supported | #186 |
| Lexer/parser hardened against malformed input (property-based fuzzing, round-trip oracle) | ✅ Supported | #99 |
Expand Down
72 changes: 68 additions & 4 deletions src/VellumPdf.Reader/DiagnosticSink.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,23 @@ namespace VellumPdf.Reader;
/// Collects <see cref="PdfReaderDiagnostic"/> instances for one <see cref="PdfDocumentReader"/> (or
/// one scoped operation on it — see <see cref="CreateScope"/>), deduplicated so the same condition
/// against the same object is recorded once, and capped at <paramref name="cap"/> entries so one
/// recurring across many objects cannot flood the list.
/// recurring across many objects cannot flood the list. <see cref="ReportRetained"/> is the one
/// exception to that cap: a caller uses it for the rare condition that must stay visible even on a
/// document engineered to exhaust the cap on unrelated conditions first, since <see cref="Report"/>
/// alone offers no way to tell such a condition apart from an ordinary one once the cap is full.
/// <see cref="PageTreeWalker"/> is the one caller today, and bounds itself to at most two
/// retained entries per walk, not three, even though three distinct codes each reach
/// <see cref="ReportRetained"/> (see its own remarks for why).
/// </summary>
/// <param name="cap">
/// The maximum number of ordinary diagnostics this sink holds before it starts recording
/// <see cref="PdfReaderDiagnosticCode.DiagnosticsSuppressed"/> instead — see
/// <see cref="PdfReaderOptions.MaxDiagnostics"/>. The cap does not count that one sentinel entry
/// itself, so a sink at capacity holds at most <paramref name="cap"/> ordinary diagnostics plus one
/// sentinel, never more — and, per <see cref="TryAccept"/>, bounds the internal dedupe bookkeeping
/// the same way, not just the list a caller sees.
/// the same way, not just the list a caller sees. It also does not count anything recorded through
/// <see cref="ReportRetained"/>, which bypasses <see cref="TryAccept"/> (and therefore this cap)
/// entirely.
/// </param>
internal sealed class DiagnosticSink(int cap)
{
Expand Down Expand Up @@ -50,6 +58,12 @@ internal sealed class DiagnosticSink(int cap)
private int? _suppressionIndex;
private int _suppressedCount;

// Count of ordinary diagnostics TryAccept has accepted (Report/Forward only, never
// ReportRetained/ForwardRetained): the value the cap is actually checked against. Kept
// separate from _diagnostics.Count so a ReportRetained entry, which is also appended to
// _diagnostics, never advances this and so never brings the ordinary cap closer to full.
private int _ordinaryCount;

private DiagnosticSink(DiagnosticSink parent) : this(parent._cap)
{
_parent = parent;
Expand Down Expand Up @@ -123,6 +137,41 @@ private void Forward(PdfReaderDiagnostic diagnostic)
_parent?.Forward(diagnostic);
}

/// <summary>
/// Records one observation the same way as <see cref="Report"/>, deduped by the same
/// (code, <paramref name="objectNumber"/>, <paramref name="pageIndex"/>) key, against the same
/// <c>_seen</c> set a prior <see cref="Report"/> of that key would also have used, except it
/// never consults <see cref="TryAccept"/>, so it is recorded (and forwarded to the parent sink,
/// when this sink is a <see cref="CreateScope"/> child) even once this sink is already at
/// capacity, and never itself counts toward that capacity. Reserved for a condition a caller
/// must be able to see regardless of how full the sink already is; see this class's own remarks
/// for the one caller today and its own bound on how often it uses this.
/// </summary>
internal void ReportRetained(
PdfReaderDiagnosticCode code, string message,
int? objectNumber = null, int? generation = null, int? pageIndex = null)
{
if (!_seen.Add((code, objectNumber, pageIndex)))
return;

var diagnostic =
new PdfReaderDiagnostic(code, message, objectNumber, generation, pageIndex);
_diagnostics.Add(diagnostic);
_parent?.ForwardRetained(diagnostic);
}

/// <summary>The <see cref="ReportRetained"/> counterpart to <see cref="Forward"/>: preserves
/// <paramref name="diagnostic"/>'s identity into this sink, bypassing <see cref="TryAccept"/>
/// the same way <see cref="ReportRetained"/> itself does.</summary>
private void ForwardRetained(PdfReaderDiagnostic diagnostic)
{
if (!_seen.Add((diagnostic.Code, diagnostic.ObjectNumber, diagnostic.PageIndex)))
return;

_diagnostics.Add(diagnostic);
_parent?.ForwardRetained(diagnostic);
}

/// <summary>
/// Decides whether <paramref name="key"/> should be recorded as a new diagnostic — shared by
/// <see cref="Report"/> and <see cref="Forward"/> so the two can never diverge on where the
Expand All @@ -148,11 +197,26 @@ private void Forward(PdfReaderDiagnostic diagnostic)
/// every one of its later recurrences reaches <see cref="RecordSuppression"/> again — the
/// count past the cap is reports dropped, not distinct conditions dropped.
/// </para>
/// <para>
/// <see cref="ReportRetained"/> and its <see cref="ForwardRetained"/> counterpart never call
/// this method: they read and write <c>_seen</c> directly instead, so a key they record is
/// still visible here (a later <see cref="Report"/> of the same key is deduped against it as
/// usual), but nothing about them advances <c>_ordinaryCount</c> or reaches
/// <see cref="RecordSuppression"/>. That is what keeps them exempt from this cap in both
/// directions: they are never suppressed by it, and they never bring anything reported
/// afterward closer to triggering it either.
/// </para>
/// </remarks>
private bool TryAccept((PdfReaderDiagnosticCode Code, int? ObjectNumber, int? PageIndex) key)
{
if (_diagnostics.Count < _cap)
return _seen.Add(key);
if (_ordinaryCount < _cap)
{
if (!_seen.Add(key))
return false;

_ordinaryCount++;
return true;
}

if (_seen.Contains(key))
return false;
Expand Down
Loading