gamba 2.0.0 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 025fac5d0c63d47973bd1c28e56c62ccb56ffe6610cdde36f75ce8b927180303
4
- data.tar.gz: d1e45ff6c48a371d1252e67c6dead3cb428ae506c96a614c1632050f3c7eee41
3
+ metadata.gz: 50c5a0eb0a2606ff06311c8ce8ea69acd633ef34846f86cc61990744658a2746
4
+ data.tar.gz: a0f8a019e088c71f118d751e2160712e242aa1666ab6cd269b898730f0ad4ab1
5
5
  SHA512:
6
- metadata.gz: 5c29d5bdb557f2437e3ec9ce9502aa744fe389d7a16f77afced77837af6aab21219bc2ea61564a0e0b7aa7c41ac1ca9a4d59057360db9a88c382d166ab97d7c0
7
- data.tar.gz: 9c82755b0e28d2273c3b32e882ace7c11228fe3ad5356d63a921687b0e0dd68e91eda71dd097915b5160047f532493fe8e7721dbabcf5472e252da739e06c233
6
+ metadata.gz: 84ff4a9295d3078e0864f681e65dcf72f9e624d4a5542bc3cc4fd2233fc2db15c33f0e936e539b6ae29ce7dd5114debceafec21c0d93780044fcd1f2ea189650
7
+ data.tar.gz: 5c3a6d22c9d427386ba0a4fb4ff259c78c05d4ca9b72b73fda006c1a5180f9a3bb554914a9d49b9e5cd7c5da504f03ca86cb68ca7742d9561bd49c44151483c1
data/CHANGELOG.md CHANGED
@@ -2,6 +2,21 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [2.0.1] — 2026-11-06
6
+
7
+ Fonts, images, SVGs and PDFs that users send can no longer hang a server, exhaust its memory or crash it.
8
+
9
+ **Faster**
10
+ - Packed indexed transparency in PNGs goes through a byte table: 4 seconds instead of 48 on an 8 KB file.
11
+ - Inline formatting tokenizes in linear time and dedupes repeated styles: `"<a" * 40_000` took 5.8 seconds, and `"<b>x" * 8000` used 401 MB.
12
+
13
+ **Fixed**
14
+ - SVG ids are read once instead of through XPath built from the id, which could be injected and scanned the whole document for each missing id. `<use>` cycles are skipped, `<use>` draws at most 20,000 elements, gradient cycles paint nothing, nesting stops at 256 levels, and an SVG's `@font-face` faces no longer replace the application's fonts once it is drawn.
15
+ - Composite glyph cycles end, overlapping cmap ranges raise `TrueType::Error`, and malformed name tables or `.otf`/`.ttf` outline mismatches no longer crash. The parsed font cache keeps 64 files.
16
+ - Truncated or zero-sized JPEGs raise `FormatError`, and a PNG without a full row is still written.
17
+ - An encrypted PDF's `/ID` mixes in the passwords, so it can no longer be used to check guesses at the content, and `owner_password: :random` uses SecureRandom.
18
+ - PDF/A metadata with control characters raises `PdfAViolation`, `Gamba.combine` no longer writes NaN for huge reals, and SVG never writes NaN or Infinity.
19
+
5
20
  ## [2.0.0] — 2026-11-05
6
21
 
7
22
  PrawnX is now Gamba, at levups/gamba, and text that overflows onto a page that already exists keeps the state it was drawn with.
@@ -73,7 +88,8 @@ speed. Same API and same pages as Prawn, pixel for pixel, in lighter files.
73
88
  place of combine_pdf.
74
89
  - `Gamba::VERSION` is the gem's; `Prawn::VERSION` stays 2.5.0, the API reproduced.
75
90
 
76
- [Unreleased]: https://github.com/levups/gamba/compare/v2.0.0...HEAD
91
+ [Unreleased]: https://github.com/levups/gamba/compare/v2.0.1...HEAD
92
+ [2.0.1]: https://github.com/levups/gamba/compare/v2.0.0...v2.0.1
77
93
  [2.0.0]: https://github.com/levups/gamba/compare/v1.1.0...v2.0.0
78
94
  [1.1.0]: https://github.com/levups/gamba/compare/v1.0.1...v1.1.0
79
95
  [1.0.1]: https://github.com/levups/gamba/compare/v1.0.0...v1.0.1
data/README.md CHANGED
@@ -1,86 +1,135 @@
1
1
  # Gamba
2
2
 
3
- Prawn's API, rewritten for speed: the same pages, pixel for pixel, in lighter files, faster.
3
+ Gamba is a Ruby library that writes PDF files: invoices, reports, labels, anything you can lay out as text, tables,
4
+ images and shapes. It is a faster rewrite of [Prawn](https://github.com/prawnpdf/prawn), the most widely used PDF
5
+ library for Ruby, together with its two companion gems, prawn-table and prawn-svg.
4
6
 
5
- https://levups.github.io/gamba/
7
+ Code written for Prawn 2.5 runs on Gamba unchanged and draws the same pages, down to the pixel. The difference is
8
+ speed and size: a one-page invoice renders about five times faster and the file is a quarter lighter (see
9
+ [Performance](#performance)).
10
+
11
+ Website and guide: https://levups.github.io/gamba/
6
12
 
7
13
  ## Installation
8
14
 
15
+ Gamba needs Ruby 3.3 or later. In your Gemfile, replace `prawn`, `prawn-table` and `prawn-svg` with one line:
16
+
9
17
  ```ruby
10
- # Gemfile
11
- gem "gamba" # instead of prawn, prawn-table and prawn-svg
18
+ gem "gamba"
12
19
  ```
13
20
 
14
- `pdf.table` and `pdf.svg` work without any other gem; `require "prawn/table"` and `require "prawn-svg"` keep
15
- working.
16
-
17
- Gamba needs Ruby 3.3 or later, and refuses to load when the prawn gem is in the bundle too.
18
-
19
- The gem has its own version, `Gamba::VERSION`. `Prawn::VERSION` is the version of the Prawn API it reproduces,
20
- 2.5.0, so code that checks Prawn's version keeps working.
21
-
22
- ## Usage
21
+ Gamba refuses to load if the prawn gem is in the same bundle, so remove it. Your existing `require "prawn"`,
22
+ `require "prawn/table"` and `require "prawn-svg"` lines keep working, and `pdf.table` and `pdf.svg` are available
23
+ without them.
23
24
 
24
- Code written for Prawn runs unchanged:
25
+ ## A first document
25
26
 
26
27
  ```ruby
28
+ require "prawn"
29
+
27
30
  Prawn::Document.generate("hello.pdf") do
28
31
  text "Hello, World!"
29
32
  table [%w[SKU Qty], %w[A-1 2]]
30
33
  end
31
34
  ```
32
35
 
33
- ## Beyond Prawn
36
+ This writes `hello.pdf` with a line of text and a two-row table. Everything else Prawn documents works the same
37
+ way: fonts, colors, images, columns, page numbers, links, encryption. Prawn's manual applies as it is, and
38
+ [the guide](https://levups.github.io/gamba/guide.html) covers what Gamba adds.
39
+
40
+ The constant is still `Prawn`, so you don't have to rename anything. `Prawn::VERSION` reports `2.5.0`, the
41
+ version of the API Gamba reproduces, for code that checks it. Gamba's own version is `Gamba::VERSION`.
42
+
43
+ ## What Gamba adds
34
44
 
35
- What would move pixels away from Prawn's stays off unless asked for.
45
+ Anything that would change how a page looks compared with Prawn is off until you ask for it.
46
+
47
+ Ligatures and kerning from OpenType fonts, per font:
36
48
 
37
49
  ```ruby
38
- # OpenType ligatures and GPOS pair kerning, per font
39
50
  font "Inter.ttf", features: %i[liga kern]
51
+ ```
40
52
 
41
- # PDF/A-3b: XMP metadata, sRGB output intent, file identifier; standard fonts and encryption raise
53
+ PDF/A-3b archival files, and Factur-X electronic invoices (the French and German standard that embeds the invoice
54
+ data as XML inside the PDF). Gamba embeds the XML your invoicing system produced; it does not build it.
55
+
56
+ ```ruby
42
57
  Prawn::Document.new(pdf_a: true, info: {Title: "Invoice INV-2026-0001"}) do
43
- font "Inter.ttf"
44
- # …
45
- factur_x File.read("factur-x.xml"), profile: :en16931 # Factur-X: minimum, basic_wl, basic, en16931, extended
58
+ font "Inter.ttf" # PDF/A needs embedded fonts: the 14 standard ones raise, and so does encryption
59
+ # ...
60
+ factur_x File.read("factur-x.xml"), profile: :en16931 # or minimum, basic_wl, basic, extended
46
61
  end
62
+ ```
47
63
 
48
- # Before a server forks: load TrueType and SVG support once, shared by every worker
49
- Gamba.eager_load!
64
+ Merging existing PDFs, such as carrier labels or supplier invoices, one page after another. This replaces the
65
+ combine_pdf gem for that use:
50
66
 
51
- # Pages of PDFs written elsewhere, one after the other: carrier labels, supplier invoices (instead of combine_pdf)
67
+ ```ruby
52
68
  Gamba.combine([label, other_label], page_size: [288, 432], orientation: :portrait)
53
69
  ```
54
70
 
55
- OpenType fonts with CFF outlines (`.otf`) embed like TrueType ones, and render like the font itself. Gamba does
56
- not build the Factur-X XML: it embeds the one the invoicing system produced.
71
+ Loading font and SVG support once, before a server such as Puma or Unicorn forks its workers, so they share it in
72
+ memory:
73
+
74
+ ```ruby
75
+ Gamba.eager_load!
76
+ ```
57
77
 
58
- SVG images do not fetch anything from the web unless asked to (`svg data, enable_web_requests: true`): prawn-svg
59
- 0.40 fetches by default, which lets a submitted SVG make the server request any URL. prawn-svg 1.0 plans the same
60
- default.
78
+ ### More on combining PDFs
61
79
 
62
- `Gamba.combine` reads xref tables, cross-reference and object streams, incremental updates, and files encrypted
63
- with an owner password only (RC4, AES-128, AES-256); a file that needs a user password raises
64
- `Prawn::Errors::EncryptedPDF`, a damaged one it cannot repair `Prawn::Errors::MalformedPDF`. Content streams are
65
- copied as they were encoded, and what several sources share (a carrier's fonts and logo) is written once. With
66
- `page_size`, each page is scaled from its lower left corner to fit, keeping its proportions; with `orientation`, a
67
- page the other way round turns a quarter counterclockwise, as combine_pdf does. A `/Rotate` is applied to the
68
- content first, where combine_pdf left it to the viewer. Outlines, forms and tagged structure are not carried over.
80
+ `Gamba.combine` takes the bytes of each PDF and returns the bytes of the merged one. It reads the cross-reference
81
+ formats PDF writers use, including incremental updates, and files encrypted with an owner password only (RC4,
82
+ AES-128 and AES-256). A file that needs a password to open raises `Prawn::Errors::EncryptedPDF`, and a damaged one
83
+ it cannot repair raises `Prawn::Errors::MalformedPDF`.
69
84
 
70
- ## Comparing an app's PDFs
85
+ Pages are copied as they were encoded, and resources several files share, like a carrier's fonts and logo, are
86
+ written once. With `page_size`, each page is scaled from its lower left corner to fit, keeping its proportions.
87
+ With `orientation`, a page the other way round turns a quarter counterclockwise, as combine_pdf does. A page's
88
+ `/Rotate` is applied to its content, where combine_pdf left it to the viewer. Outlines, forms and tagged structure
89
+ are not carried over.
71
90
 
72
- `script/capture_pdfs.rb` writes every PDF an app's test suite renders, named after its test. Run the suite under
73
- Prawn, then under Gamba, and compare both directories with `Oracle.pdf_differences`:
91
+ ## Files your users send
92
+
93
+ Applications often put user content into PDFs: an uploaded logo, a font, a name typed in a form, a PDF to attach.
94
+ Any of it can be built to attack the server that renders it.
95
+
96
+ - SVG images fetch nothing from the web unless you pass `enable_web_requests: true`. prawn-svg 0.40 fetched by
97
+ default, so a submitted SVG could make your server request any URL. prawn-svg 1.0 plans the same default as
98
+ Gamba.
99
+ - An SVG can't make Gamba loop or run out of stack through references (`<use>`, gradients) or deep nesting, and
100
+ fonts it declares with `@font-face` disappear once it is drawn. In prawn-svg, an uploaded SVG declaring a
101
+ "Helvetica" font changed the font of the application's own text.
102
+ - A damaged or malicious PNG, JPEG, TrueType or OpenType file either renders or raises an error Gamba names
103
+ (`Prawn::Errors::UnsupportedImageType`, `Prawn::Images::JPG::FormatError`, `Gamba::TrueType::Error`). A PNG
104
+ inflates no further than the size its header gives. CI corrupts sample files on every run to check this.
105
+ - `Gamba.combine` stops at 64 levels of nested arrays and dictionaries and at 256 MB of decompressed data, and
106
+ ignores references that lead back to themselves, so a crafted PDF can't send it into a loop or fill
107
+ memory.
108
+ - Text with inline formatting (`inline_format: true`) is parsed in linear time, whatever the markup.
109
+ - The `/ID` of an encrypted PDF depends on its passwords, so it reveals nothing about the content to someone
110
+ without them.
111
+
112
+ Inline formatting still turns `<link href="...">` into a clickable link. Escape user text before you put it inside
113
+ markup.
114
+
115
+ To report a vulnerability, see [SECURITY.md](SECURITY.md).
116
+
117
+ ## Checking your app's PDFs
118
+
119
+ Before switching, you can compare what your app produces under both libraries. `script/capture_pdfs.rb` saves
120
+ every PDF your test suite renders, named after the test. Run the suite once with Prawn and once with Gamba:
74
121
 
75
122
  ```sh
76
123
  GAMBA_CAPTURE_DIRECTORY=tmp/prawn RUBYOPT=-r/path/to/gamba/script/capture_pdfs.rb bin/rails test
77
124
  ```
78
125
 
126
+ Then compare the two directories with `Oracle.pdf_differences`, from Gamba's test support.
127
+
79
128
  ## Performance
80
129
 
81
- `bundle exec rake bench` renders each document of `bench/documents` with Prawn 2.5 and with Gamba in 7 fresh YJIT
82
- processes each, taking turns, and writes `docs/benchmarks.json`. Each process times 20 renders; the table shows the
83
- median of the 7 processes, on Ruby 4.0.9:
130
+ `bundle exec rake bench` renders each document in `bench/documents` with Prawn 2.5 and with Gamba, in 7 fresh
131
+ YJIT processes each, taking turns. Each process times 20 renders, and the table shows the median of the 7, on
132
+ Ruby 4.0.9:
84
133
 
85
134
  | Document | Prawn | Gamba | Allocations, Prawn → Gamba | Weight, Prawn → Gamba |
86
135
  |---|---:|---:|---:|---:|
@@ -88,58 +137,71 @@ median of the 7 processes, on Ruby 4.0.9:
88
137
  | Report, 101 pages | 559.4 ms | 216.0 ms | 3,350,853 → 2,089,008 | 207,815 → 164,924 bytes |
89
138
  | Catalog, 1,000 table rows | 544.9 ms | 265.6 ms | 3,979,977 → 2,078,343 | 147,731 → 134,082 bytes |
90
139
 
91
- Charts and peak memory: https://levups.github.io/gamba/benchmarks.html
140
+ Files are lighter because Gamba compresses streams and packs objects together, which PDF 1.5 allows and Prawn
141
+ doesn't do. Charts and peak memory are on the [benchmarks page](https://levups.github.io/gamba/benchmarks.html).
142
+
143
+ ## How we know the pages are the same
144
+
145
+ The test suite renders every example of Prawn's and prawn-table's manuals, and every sample SVG of prawn-svg, once
146
+ with the original gems and once with Gamba. For each pair it compares the text and its position to 0.01 pt, the
147
+ pixels at 150 dpi in two unrelated renderers (MuPDF and Poppler), whether `qpdf --check` accepts the file, and its
148
+ size. We call this the oracle.
149
+
150
+ Gamba does not copy Prawn's bugs. When Prawn crashes, writes an invalid PDF or contradicts its own documentation,
151
+ Gamba fixes it, and the [compatibility page](https://levups.github.io/gamba/compatibility.html) lists each fix with
152
+ its proof.
92
153
 
93
154
  ## Development
94
155
 
95
- - An oracle renders every example of Prawn's and prawn-table's manuals and every sample SVG of prawn-svg, with
96
- Prawn 2.5, prawn-table 0.2.2 and prawn-svg 0.40.4 and with Gamba, each in its own process, and
97
- compares their pages, their text and its positions to 0.01 pt, their pixels at 150 dpi in two renderers that
98
- share no code (MuPDF and Poppler), their validity
99
- (`qpdf --check`) and their weight. Examples listed in `test/oracle_passing.txt` must stay identical; one that
100
- becomes identical must join the list.
101
- - A seeded fuzzer writes random documents (text in all its options, boxes, columns, tables, shapes, pages) and
102
- compares them the same way: `FUZZ_SEED=42 FUZZ_CASES=500 bundle exec ruby -Itest test/fuzz_test.rb`, and
103
- `ruby -Itest script/fuzz_minimize.rb tmp/fuzz/documents/fuzz_0042.rb` shrinks a failing one. CI adds 300 from a
104
- fresh seed on every run.
105
- - An input fuzzer corrupts sample PNGs, JPEGs and fonts (flipped bytes, truncations, forged lengths): each must
106
- render or raise an error Gamba names, never crash inside a parser, hang or exhaust memory. PNG data inflates
107
- no further than its header announces.
108
- - `test/divergences.yml` lists Prawn's bugs Gamba fixes, each with the specification that proves it and the exact
109
- differences the oracle must report. `test/oracle_examples` holds documents of our own for what the manual
110
- does not show.
111
- - PDF/A documents are checked by veraPDF when it is installed (`brew install verapdf`).
112
- - `test/contract/prawn-2.5.0.yml`, generated by `script/contract_extract.rb`, lists Prawn's public methods; Gamba
113
- must accept every call Prawn accepts on those of its contract, settled in `test/contract/decisions.yml`.
114
-
115
- Prawn runs from its own bundle, `oracle/Gemfile`. The oracle needs `mutool`, `pdftoppm` and `qpdf` (`brew install
116
- mupdf-tools poppler qpdf`), and Prawn's manual and data, which `rake corpus:fetch` downloads into the ignored `corpus/cache`.
156
+ Prawn runs from its own bundle, `oracle/Gemfile`, so the oracle can compare the two. The tests need `mutool`,
157
+ `pdftoppm` and `qpdf` (`brew install mupdf-tools poppler qpdf`), and Prawn's manual and sample data, which
158
+ `rake corpus:fetch` downloads into `corpus/cache`. Without that cache, the comparison tests are skipped.
117
159
 
118
160
  ```sh
119
161
  bundle install && BUNDLE_GEMFILE=oracle/Gemfile bundle install
120
162
  bundle exec rake corpus:fetch
121
163
  bundle exec rake test
122
- ORACLE_CANDIDATE=prawn bundle exec rake test # Prawn against itself: proves the oracle
123
- bundle exec rake bench
124
164
  bundle exec rubocop
125
165
  ```
126
166
 
167
+ Other commands:
168
+
169
+ ```sh
170
+ ORACLE_CANDIDATE=prawn bundle exec rake test # Prawn against itself, to check the oracle
171
+ FUZZ_SEED=42 FUZZ_CASES=500 bundle exec ruby -Itest test/fuzz_test.rb # random documents, compared with Prawn
172
+ INPUT_FUZZ_SEED=42 INPUT_FUZZ_CASES=400 bundle exec ruby -Itest test/input_fuzz_test.rb # corrupted images and fonts
173
+ bundle exec rake bench # writes docs/benchmarks.json
174
+ ```
175
+
176
+ `ruby -Itest script/fuzz_minimize.rb tmp/fuzz/documents/fuzz_0042.rb` shrinks a failing fuzz document. PDF/A
177
+ files are also checked by veraPDF when it is installed (`brew install verapdf`).
178
+
179
+ The files that define what "compatible" means:
180
+
181
+ - `test/oracle_passing.txt`: examples that must stay identical to Prawn's. One that becomes identical joins it.
182
+ - `test/divergences.yml`: Prawn bugs Gamba fixes, with the specification that proves each one and the exact
183
+ differences the oracle must find.
184
+ - `test/oracle_examples`: documents of our own, for cases the manuals don't show.
185
+ - `test/contract/prawn-2.5.0.yml`: Prawn's public methods, generated by `script/contract_extract.rb`. Every call
186
+ Prawn accepts must keep working; exceptions are settled in `test/contract/decisions.yml`.
187
+
188
+ See [CONTRIBUTING.md](CONTRIBUTING.md) before opening a pull request.
189
+
127
190
  ### Releasing
128
191
 
129
- Pull requests leave `CHANGELOG.md` alone: a release starts by writing its notes under `## [Unreleased]`, from the
130
- pull requests merged since the last tag, without committing them. Then, from an up-to-date `main` whose CI is
131
- green:
192
+ Pull requests leave `CHANGELOG.md` alone. A release starts by writing its notes under `## [Unreleased]`, from the
193
+ pull requests merged since the last tag, without committing them. Then, from an up-to-date `main` with green CI:
132
194
 
133
195
  ```sh
134
- bin/release minor --dry-run # the notes and the changes, nothing written
196
+ bin/release minor --dry-run # shows the notes and the changes, writes nothing
135
197
  bin/release minor # or patch, major, or an exact version such as 1.2.0
136
198
  ```
137
199
 
138
- `main` takes no direct push, so `bin/release` dates the Unreleased section and bumps the version on a branch
139
- `release/vX.Y.Z`, opens its pull request, which merges itself once CI is green, and waits for it. It then pushes a
140
- signed tag `vX.Y.Z` on the merge commit (`bin/release --tag X.Y.Z` does it if you stopped waiting). The tag starts
141
- the Release workflow, which publishes the gem to RubyGems through trusted publishing and creates the GitHub release
142
- with the version's notes and the `.gem`.
200
+ `main` takes no direct push, so `bin/release` dates the notes and bumps the version on a `release/vX.Y.Z` branch,
201
+ opens a pull request that merges itself once CI is green, and waits for it. It then pushes a signed `vX.Y.Z` tag on
202
+ the merge commit (`bin/release --tag X.Y.Z` does it if you stopped waiting). The tag starts the Release workflow,
203
+ which publishes the gem to RubyGems through trusted publishing and creates the GitHub release with the notes and
204
+ the `.gem`.
143
205
 
144
206
  ## License
145
207
 
data/lib/gamba/combine.rb CHANGED
@@ -283,8 +283,10 @@ module Gamba
283
283
  numeric(@reader.resolve(value))
284
284
  end
285
285
 
286
+ # A real too large for a Float reads as infinite, and would write NaN into the page's matrix: no number then.
286
287
  def numeric(value)
287
- (value.is_a?(PDF::Core::Real) || value.is_a?(Numeric)) ? value.to_f : nil
288
+ number = (value.is_a?(PDF::Core::Real) || value.is_a?(Numeric)) ? value.to_f : nil
289
+ number if number&.finite?
288
290
  end
289
291
 
290
292
  def intersection(crop, media)
data/lib/gamba/font.rb CHANGED
@@ -104,14 +104,23 @@ module Prawn
104
104
 
105
105
  def self.load(document, source, options = {})
106
106
  case font_format(source, options)
107
- when "ttf" then Fonts::TTF.new(document, source, options)
108
- when "otf" then Fonts::OTF.new(document, source, options)
107
+ when "ttf" then outline_class(source, Fonts::TTF).new(document, source, options)
108
+ when "otf" then outline_class(source, Fonts::OTF).new(document, source, options)
109
109
  when "dfont" then Fonts::DFont.new(document, source, options)
110
110
  when "ttc" then Fonts::TTC.new(document, source, options)
111
111
  else Fonts::AFM.new(document, source, options)
112
112
  end
113
113
  end
114
114
 
115
+ # Outlines decide, not the extension: a .otf may hold TrueType outlines, and a .ttf CFF ones.
116
+ def self.outline_class(source, by_extension)
117
+ case (source.respond_to?(:read) ? :unknown : Gamba::TrueType::File.open(source).outline_format)
118
+ when :true_type then Fonts::TTF
119
+ when :open_type then Fonts::OTF
120
+ else by_extension
121
+ end
122
+ end
123
+
115
124
  def self.font_format(source, options)
116
125
  return options.fetch(:format, "ttf") if source.respond_to?(:read)
117
126
 
@@ -58,9 +58,14 @@ module Prawn
58
58
  loop do
59
59
  marker, code, length = data.byteslice(position, 4)&.unpack("CCn")
60
60
  raise FormatError, "JPEG marker not found!" if marker != MARKER_PREFIX
61
+ raise FormatError, "Truncated JPEG" if length.nil?
61
62
 
62
63
  if START_OF_FRAME_MARKERS.include?(code)
64
+ raise FormatError, "Truncated JPEG frame header" if position + 10 > data.bytesize
65
+
63
66
  @bits, @height, @width, @channels = data.unpack("@#{position + 4} CnnC")
67
+ raise FormatError, "JPEG of #{@width}x#{@height} pixels at #{@bits} bits" unless @bits.positive? && @height.positive? && @width.positive?
68
+
64
69
  break
65
70
  end
66
71
  position += 2 + length
@@ -121,8 +126,9 @@ module Prawn
121
126
  @transparency =
122
127
  case @color_type
123
128
  when INDEXED then {palette: chunk.unpack("C*")}
124
- when GRAYSCALE then {grayscale: chunk.unpack1("n")}
125
- when TRUE_COLOR then {rgb: chunk.unpack("nnn")}
129
+ # Shorter than the samples they need, they would write a /Mask of nulls: ignored, as viewers do.
130
+ when GRAYSCALE then (chunk.bytesize >= 2) ? {grayscale: chunk.unpack1("n")} : {}
131
+ when TRUE_COLOR then (chunk.bytesize >= 6) ? {rgb: chunk.unpack("nnn")} : {}
126
132
  else {}
127
133
  end
128
134
  when "IEND" then break
@@ -185,6 +191,7 @@ module Prawn
185
191
  raise Errors::UnsupportedImageType, "PNG uses an unsupported filter method" if filter_method != 0
186
192
  raise Errors::UnsupportedImageType, "PNG uses unsupported interlace method" if interlace_method != 0
187
193
  raise Errors::UnsupportedImageType, "PNG uses an invalid bit depth" if BIT_DEPTHS[color_type]&.include?(bits) == false
194
+ raise Errors::UnsupportedImageType, "PNG has a palette of #{palette.bytesize / 3} colors" if color_type == INDEXED && !(3..768).cover?(palette.bytesize)
188
195
 
189
196
  dictionary = {Type: :XObject, Subtype: :Image, Height: height, Width: width, BitsPerComponent: bits}
190
197
  if color_type == INDEXED && alpha_channel?
@@ -203,6 +210,9 @@ module Prawn
203
210
  else
204
211
  [:Indexed, :DeviceRGB, (palette.bytesize / 3) - 1, document.ref!({}, palette)]
205
212
  end
213
+ # Data too short for one row still makes an image XObject, which must be a stream: viewers pad it.
214
+ image.empty_stream = true
215
+ image.data[:SMask]&.empty_stream = true
206
216
  if transparency[:grayscale]
207
217
  image.data[:Mask] = [transparency[:grayscale]] * 2
208
218
  elsif transparency[:rgb]
@@ -256,14 +266,18 @@ module Prawn
256
266
  img_data.unpack(alpha_layout, offset:).pack("C*", buffer: alpha)
257
267
  end
258
268
 
259
- # Palette indices and their opacity: indices only mean something once the rows are unfiltered.
269
+ # Palette indices and their opacity: indices only mean something once the rows are unfiltered. Each byte of
270
+ # a row maps to the opacity of the 8 / bits pixels it packs, through a table of its 256 values.
260
271
  def split_palette_transparency
261
272
  rows = PngDecoder.unfilter(img_data, ((width * bits) + 7) / 8, 1)
262
273
  alpha_by_index = Array.new(256) { |index| transparency[:palette][index] || 0xFF }
263
- alpha = rows.map do |row|
264
- indices = (bits == 8) ? row.bytes : row.unpack1("B*").scan(/.{#{bits}}/).first(width).map! { _1.to_i(2) }
265
- indices.map { alpha_by_index[_1] }.pack("C*")
266
- end
274
+ pixels_per_byte = 8 / bits
275
+ mask = (1 << bits) - 1
276
+ alpha_by_byte = Array.new(256) do |byte|
277
+ indices = Array.new(pixels_per_byte) { |pixel| (byte >> (8 - (bits * (pixel + 1)))) & mask }
278
+ [byte.chr, indices.map { alpha_by_index[_1] }.pack("C*")]
279
+ end.to_h
280
+ alpha = rows.map { |row| row.gsub(/./mn, alpha_by_byte).byteslice(0, width) }
267
281
  [rows.join, alpha.join]
268
282
  end
269
283
  end
@@ -6,12 +6,14 @@ module PDF
6
6
  class Reference
7
7
  attr_reader :identifier
8
8
  attr_accessor :data, :uncompressed
9
- attr_writer :stream
9
+ # Written as a stream even without bytes, as image XObjects must be.
10
+ attr_writer :stream, :empty_stream
10
11
 
11
12
  def initialize(identifier, data, stream = nil)
12
13
  @identifier = identifier
13
14
  @data = data
14
15
  @stream = stream
16
+ @empty_stream = false
15
17
  end
16
18
 
17
19
  def to_s
@@ -24,7 +26,7 @@ module PDF
24
26
  end
25
27
 
26
28
  def stream?
27
- !@stream.nil? && !@stream.empty?
29
+ !@stream.nil? && (@empty_stream || !@stream.empty?)
28
30
  end
29
31
  end
30
32
  end
@@ -23,7 +23,7 @@ module PDF
23
23
  @trailer = trailer
24
24
  return unless encryption || identified
25
25
 
26
- file_identifier = PDF::Core::ByteString.new(document_digest)
26
+ file_identifier = PDF::Core::ByteString.new(document_digest(encryption&.identifier_secret))
27
27
  @trailer = trailer.merge(ID: [file_identifier, file_identifier])
28
28
  return unless encryption
29
29
 
@@ -56,9 +56,11 @@ module PDF
56
56
 
57
57
  attr_reader :objects, :root, :info, :version, :trailer
58
58
 
59
- # A file identifier derived from the document's content, so the same document always gets the same one.
60
- def document_digest
59
+ # A file identifier derived from the document's content, so the same document always gets the same one; an
60
+ # encrypted document's mixes in its passwords.
61
+ def document_digest(secret)
61
62
  digest = Digest::MD5.new
63
+ digest << secret if secret
62
64
  objects.each do |reference|
63
65
  digest << PDF::Core.serialize(reference.data)
64
66
  digest << reference.stream if reference.stream?
data/lib/gamba/pdf_a.rb CHANGED
@@ -28,6 +28,8 @@ module Gamba
28
28
  Title: "dc:title", Author: "dc:creator", Subject: "dc:description", Keywords: "pdf:Keywords",
29
29
  Creator: "xmp:CreatorTool", Producer: "pdf:Producer", CreationDate: "xmp:CreateDate", ModDate: "xmp:ModifyDate"
30
30
  }.freeze
31
+ # XML 1.0 has no way to write these, not even as references: the XMP would not parse.
32
+ XML_FORBIDDEN_CHARACTERS = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\uFFFE\uFFFF]/
31
33
 
32
34
  def pdf_a?
33
35
  @pdf_a == true
@@ -126,7 +128,12 @@ module Gamba
126
128
  end
127
129
 
128
130
  def escape_xml(text)
131
+ text = text.encode(::Encoding::UTF_8)
132
+ raise Prawn::Errors::PdfAViolation, "PDF/A metadata cannot hold control characters: #{text.inspect}" if text.match?(XML_FORBIDDEN_CHARACTERS)
133
+
129
134
  text.encode(xml: :text)
135
+ rescue EncodingError => error
136
+ raise Prawn::Errors::PdfAViolation, "PDF/A metadata must be text: #{error.message}"
130
137
  end
131
138
  end
132
139
  end
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "digest/md5"
4
+ require "securerandom"
4
5
 
5
6
  module Prawn
6
7
  class Document
@@ -18,7 +19,7 @@ module Prawn
18
19
  Prawn.verify_options(%i[user_password owner_password permissions], options)
19
20
  @user_password = options.delete(:user_password) || ""
20
21
  @owner_password = options.delete(:owner_password) || @user_password
21
- @owner_password = Random.bytes(32) if @owner_password == :random
22
+ @owner_password = SecureRandom.bytes(32) if @owner_password == :random
22
23
  self.permissions = options.delete(:permissions) || {}
23
24
  @encryption = Encryption.new(user_password: @user_password, owner_password: @owner_password, permissions: permissions_value)
24
25
  end
@@ -72,6 +73,13 @@ module Prawn
72
73
  end
73
74
  end
74
75
 
76
+ # Mixed into the file identifier, which is written in clear: without it, anyone holding the template could
77
+ # check guesses at the encrypted content against the identifier. The /U and /O entries already let a password
78
+ # guess be checked, so this tells nothing more about the passwords.
79
+ def identifier_secret
80
+ Security.pad_password(@user_password) + Security.pad_password(@owner_password)
81
+ end
82
+
75
83
  def key(file_identifier)
76
84
  Digest::MD5.digest(Security.pad_password(@user_password) + owner_password_hash + [@permissions].pack("V") + file_identifier)[0, Security::KEY_LENGTH_BYTES]
77
85
  end
@@ -11,6 +11,8 @@ module Prawn
11
11
  "<color[^>]*>|</color>|<font[^>]*>|</font>|<strong>|</strong>|<em>|</em>|<a[^>]*>|</a>|[^<\n]+",
12
12
  Regexp::MULTILINE
13
13
  )
14
+ # Past the last ">", no tag can end: only text and newlines are left.
15
+ TEXT_REGEX = /\n|[^<\n]+/
14
16
  ESCAPE_CHARS = {"&" => "&amp;", ">" => "&gt;", "<" => "&lt;"}.freeze
15
17
  UNESCAPE_CHARS = ESCAPE_CHARS.invert.freeze
16
18
  CMYK_ATTRIBUTES = %w[c m y k].freeze
@@ -25,7 +27,18 @@ module Prawn
25
27
  SUFFIX_BY_STYLE = PREFIX_BY_STYLE.transform_values { _1.sub("<", "</") }.freeze
26
28
 
27
29
  def self.format(string, *_arguments)
28
- array_from_tokens(string.gsub(%r{<br\s*/?>}, "\n").scan(PARSER_REGEX))
30
+ array_from_tokens(tokens(string.gsub(%r{<br\s*/?>}, "\n")))
31
+ end
32
+
33
+ # The same tokens as string.scan(PARSER_REGEX), in linear time: a tag with attributes that never closes
34
+ # scans to the end of the string from each "<" after the last ">", which made "<a" * n quadratic. From the
35
+ # first "<" past the last ">", only TEXT_REGEX can match.
36
+ def self.tokens(string)
37
+ last_tag_end = string.rindex(">")
38
+ cut = last_tag_end ? string.index("<", last_tag_end) : string.index("<")
39
+ return string.scan(PARSER_REGEX) unless cut
40
+
41
+ string[0, cut].scan(PARSER_REGEX).concat(string[cut..].scan(TEXT_REGEX))
29
42
  end
30
43
 
31
44
  def self.to_string(array)
@@ -95,7 +108,9 @@ module Prawn
95
108
  character_spacings = []
96
109
  tokens.each do |token|
97
110
  if (style = STYLE_BY_OPENING_TAG[token])
98
- styles << style
111
+ # A style opened twice is still one: a closing tag removes it whole, and copies would grow every
112
+ # following fragment's styles.
113
+ styles << style unless styles.include?(style)
99
114
  elsif (style = STYLE_BY_CLOSING_TAG[token])
100
115
  styles.delete(style)
101
116
  else
@@ -18,16 +18,26 @@ module Gamba
18
18
  # Reading past the data a malformed font declares raises these: they become a TrueType::Error.
19
19
  MALFORMED_FONT_ERRORS = [ArgumentError, TypeError, RangeError, NoMethodError, FloatDomainError].freeze
20
20
  MAXIMUM_CODE_POINT = 0x10FFFF
21
+ # Codes a cmap may walk, overlaps included: four times the 16-bit range for format 4, the Unicode range for
22
+ # format 12. Valid fonts walk each code once; past these, crafted ranges would hold the parse for minutes.
23
+ MAXIMUM_CMAP_CODES = {4 => 0x40000, 12 => MAXIMUM_CODE_POINT + 1}.freeze
21
24
 
22
25
  Header = Data.define(:units_per_em, :x_min, :y_min, :x_max, :y_max, :index_to_location_format)
23
26
 
24
27
  FILES_BY_KEY = {}
25
28
  FILES_LOCK = Mutex.new
29
+ # Fonts kept parsed, the most recently used last: apps that write each request's font to a new temporary
30
+ # file would otherwise keep every one of them for the life of the process.
31
+ MAXIMUM_CACHED_FILES = 64
26
32
 
27
33
  # Parsed fonts are shared by every document of the process, until their file changes.
28
34
  def self.open(path, index: 0, resource: false)
29
35
  key = [::File.expand_path(path), index, resource, ::File.mtime(path)]
30
- FILES_LOCK.synchronize { FILES_BY_KEY[key] ||= new(::File.binread(path), index:, resource:) }
36
+ FILES_LOCK.synchronize do
37
+ file = FILES_BY_KEY.delete(key) || new(::File.binread(path), index:, resource:)
38
+ FILES_BY_KEY.delete(FILES_BY_KEY.each_key.first) while FILES_BY_KEY.size >= MAXIMUM_CACHED_FILES
39
+ FILES_BY_KEY[key] = file
40
+ end
31
41
  end
32
42
 
33
43
  attr_reader :bytes, :offset
@@ -318,6 +328,7 @@ module Gamba
318
328
  deltas = cmap.unpack("@#{starts_offset + (segment_count * 2)} n#{segment_count}")
319
329
  range_offsets_offset = starts_offset + (segment_count * 4)
320
330
  range_offsets = cmap.unpack("@#{range_offsets_offset} n#{segment_count}")
331
+ check_cmap_size(format, starts.zip(ends))
321
332
  segment_count.times do |segment|
322
333
  (starts[segment]..ends[segment]).each do |code|
323
334
  glyph =
@@ -341,7 +352,9 @@ module Gamba
341
352
  cmap.unpack("@#{offset + 20} n#{count}").each_with_index { |glyph, index| glyph_by_code[first_code + index] = glyph }
342
353
  when 12
343
354
  group_count = [cmap.unpack1("@#{offset + 12} N"), (cmap.bytesize - offset - 16) / 12].min
344
- cmap.unpack("@#{offset + 16} N#{group_count * 3}").each_slice(3) do |start_code, end_code, start_glyph|
355
+ groups = cmap.unpack("@#{offset + 16} N#{group_count * 3}").each_slice(3).to_a
356
+ check_cmap_size(format, groups.map { |start_code, end_code| [start_code, [end_code, MAXIMUM_CODE_POINT].min] })
357
+ groups.each do |start_code, end_code, start_glyph|
345
358
  (start_code..[end_code, MAXIMUM_CODE_POINT].min).each { |code| glyph_by_code[code] = start_glyph + (code - start_code) }
346
359
  end
347
360
  end
@@ -350,11 +363,17 @@ module Gamba
350
363
  glyph_by_code.freeze
351
364
  end
352
365
 
366
+ def check_cmap_size(format, ranges)
367
+ codes = ranges.sum { |first, last| (last >= first) ? last - first + 1 : 0 }
368
+ raise Error, "Malformed font: its cmap maps #{codes} codes" if codes > MAXIMUM_CMAP_CODES.fetch(format)
369
+ end
370
+
353
371
  def name_string(name_id)
354
372
  name = table("name")
355
373
  return unless name
356
374
 
357
375
  count, strings_offset = name.unpack("@2 n2")
376
+ count = count.clamp(0, (name.bytesize - 6) / 12)
358
377
  records = Array.new(count) { |record_index| name.unpack("@#{6 + (record_index * 12)} n6") }
359
378
  record = records.find { |platform, _, _, id| id == name_id && platform == 3 } ||
360
379
  records.find { |platform, _, _, id| id == name_id && platform == 1 } ||
@@ -363,8 +382,10 @@ module Gamba
363
382
 
364
383
  platform, _encoding, _language, _id, length, offset = record
365
384
  raw = name.byteslice(strings_offset + offset, length)
385
+ return unless raw
386
+
366
387
  (platform == 1) ? raw.force_encoding(::Encoding::MacRoman).encode(::Encoding::UTF_8) : raw.force_encoding(::Encoding::UTF_16BE).encode(::Encoding::UTF_8)
367
- rescue ::Encoding::UndefinedConversionError, ::Encoding::InvalidByteSequenceError
388
+ rescue ::Encoding::UndefinedConversionError, ::Encoding::InvalidByteSequenceError, *MALFORMED_FONT_ERRORS
368
389
  nil
369
390
  end
370
391
  end
@@ -29,11 +29,13 @@ module Gamba
29
29
  @new_glyph_by_original.keys
30
30
  end
31
31
 
32
- # Numbers the components of composite glyphs, level by level, in the order of their composites' indices.
32
+ # Numbers the components of composite glyphs, level by level, in the order of their composites' indices. Each
33
+ # glyph's components are read once: a composite that contains itself, directly or not, ends the walk.
33
34
  def add_components(originals)
35
+ expanded = {}
34
36
  level = originals
35
37
  loop do
36
- components = level.flat_map { component_glyphs(@file.glyph_data(_1)) }
38
+ components = level.flat_map { |glyph| expanded.key?(glyph) ? [] : (expanded[glyph] = true) && component_glyphs(@file.glyph_data(glyph)) }
37
39
  break if components.empty?
38
40
 
39
41
  components.each { glyph_for(_1) }
data/lib/gamba/version.rb CHANGED
@@ -6,5 +6,5 @@ module Prawn
6
6
  end
7
7
 
8
8
  module Gamba
9
- VERSION = "2.0.0"
9
+ VERSION = "2.0.1"
10
10
  end
@@ -84,8 +84,8 @@ module Prawn::SVG::CSS
84
84
  def associate_xpath_styles_with_elements(xpath_styles)
85
85
  element_styles = {}
86
86
 
87
- xpath_styles.each do |xpath, declarations, _|
88
- REXML::XPath.match(root, xpath).each do |element|
87
+ xpath_styles.each do |steps, declarations, _|
88
+ matching_elements(steps).each do |element|
89
89
  (element_styles[element] ||= []).concat declarations
90
90
  end
91
91
  end
@@ -93,13 +93,38 @@ module Prawn::SVG::CSS
93
93
  element_styles
94
94
  end
95
95
 
96
+ # Gamba: one compound selector at a time, each matched once from every element the steps before it found.
97
+ # Joined into one XPath, "g g g" became //g//g//g, which REXML evaluates without merging the paths that reach
98
+ # the same element: on nested elements, exponential.
99
+ def matching_elements(steps)
100
+ elements = REXML::XPath.match(root, steps.first).uniq
101
+ steps.drop(1).each do |step|
102
+ found = {}.compare_by_identity
103
+ elements.each { |element| REXML::XPath.match(element, ".#{step}").each { found[_1] = true } }
104
+ elements = found.keys
105
+ end
106
+ elements
107
+ end
108
+
109
+ # Gamba: an XPath 1.0 literal has no escape, so a value holding both quotes is a concat() of pieces that do not;
110
+ # prawn-svg escaped quotes with a backslash, which let a selector's value write its own XPath.
96
111
  def xpath_quote(value)
97
- %("#{value.gsub("\\", "\\\\").gsub('"', '\\"')}") if value
112
+ return unless value
113
+ return %("#{value}") unless value.include?('"')
114
+ return %('#{value}') unless value.include?("'")
115
+
116
+ "concat(#{value.split('"', -1).map { %("#{_1}") }.join(%(, '"', ))})"
98
117
  end
99
118
 
100
119
  RECOGNIZED_PSEUDO_CLASSES = %w[first-child last-child link visited hover active focus].freeze
101
120
 
121
+ # Gamba: REXML's XPath parser splits predicates at brackets, even inside a string literal, so a value holding
122
+ # one would end the predicate early and write the rest as XPath: such a selector matches nothing.
123
+ BRACKET = /[\[\]]/
124
+
102
125
  def css_selector_to_xpath(selector)
126
+ return ["//*[false()]"] if selector.any? { |element| bracketed_value?(element) }
127
+
103
128
  selector.map do |element|
104
129
  pseudo_classes = Set.new(element[:pseudo_class])
105
130
  require_function_name = false
@@ -183,7 +208,12 @@ module Prawn::SVG::CSS
183
208
  result << "[false()]" if never_match
184
209
 
185
210
  result
186
- end.join
211
+ end
212
+ end
213
+
214
+ def bracketed_value?(element)
215
+ (element[:attribute] || []).any? { |_key, _operator, value| value&.match?(BRACKET) } ||
216
+ (element[:pseudo_class] || []).any? { _1.match?(BRACKET) }
187
217
  end
188
218
 
189
219
  def parse_nth_child_expression(expr)
@@ -5,6 +5,11 @@ class Prawn::SVG::Document
5
5
  InvalidSVGData = Class.new(Error)
6
6
 
7
7
  DEFAULT_FALLBACK_FONT_NAME = "Times-Roman".freeze
8
+ # Gamba: limits a crafted SVG would otherwise exceed to hang the process. Elements drawn again through <use>,
9
+ # counted over the whole document: two <use> of the level below, sixteen levels deep, draw 65,536 copies.
10
+ MAXIMUM_ELEMENTS_THROUGH_USE = 20_000
11
+ # Elements inside one another: deeper, Ruby's stack runs out, and REXML resolves each namespace by its ancestors.
12
+ MAXIMUM_DEPTH = 256
8
13
 
9
14
  class << self
10
15
  attr_accessor :enable_web_requests_warned
@@ -28,11 +33,19 @@ class Prawn::SVG::Document
28
33
  @root = REXML::Document.new(data).root or raise_parse_error(data)
29
34
  rescue REXML::ParseException => e
30
35
  raise_parse_error(data, e.message)
36
+ rescue RuntimeError => e
37
+ # Gamba: REXML's entity expansion limits raise a bare RuntimeError.
38
+ raise InvalidSVGData, "The data supplied is not a valid SVG document: #{e.message}"
31
39
  end
40
+ check_tree!(@root)
32
41
 
33
42
  @warnings = []
34
43
  @options = options
35
44
  @elements_by_id = {}
45
+ @element_index_by_root = {}.compare_by_identity
46
+ @elements_through_use = 0
47
+ @references_in_use = []
48
+ @depth = 0
36
49
  @gradients = Prawn::SVG::Gradients.new(self)
37
50
  @external_svg_cache = {}
38
51
  @fallback_font_name = options.fetch(:fallback_font_name, DEFAULT_FALLBACK_FONT_NAME)
@@ -60,6 +73,65 @@ class Prawn::SVG::Document
60
73
  yield self if block_given?
61
74
  end
62
75
 
76
+ # Gamba: the first element of root, in document order, whose id is id. Read once into a hash per root, where
77
+ # prawn-svg built an XPath query from the id: an id holding a quote injected XPath, and each reference to a
78
+ # missing id scanned the whole document.
79
+ def self.element_by_id(root, id, cache = nil)
80
+ index = cache ? (cache[root] ||= element_index(root)) : element_index(root)
81
+ index[id]
82
+ end
83
+
84
+ def self.element_index(root)
85
+ index = {}
86
+ index[root.attributes["id"]] = root if root.attributes["id"]
87
+ root.each_recursive { |element| (id = element.attributes["id"]) && (index[id] ||= element) }
88
+ index
89
+ end
90
+
91
+ def raw_element_by_id(id, root = @root)
92
+ self.class.element_by_id(root, id, @element_index_by_root)
93
+ end
94
+
95
+ # Gamba: the elements a <use> draws, unless it draws one of its own ancestors or the document has drawn too many.
96
+ def drawing_through_use(source)
97
+ raise Prawn::SVG::Elements::Base::SkipElementError, "use tag references an element that contains it" if @references_in_use.any? { _1.equal?(source) }
98
+
99
+ @elements_through_use += 1
100
+ source.each_recursive { @elements_through_use += 1 }
101
+ raise Prawn::SVG::Elements::Base::SkipElementError, "use tags draw more than #{MAXIMUM_ELEMENTS_THROUGH_USE} elements" if @elements_through_use > MAXIMUM_ELEMENTS_THROUGH_USE
102
+
103
+ @references_in_use << source
104
+ yield
105
+ ensure
106
+ @references_in_use.pop if @references_in_use.last.equal?(source)
107
+ end
108
+
109
+ # Gamba: walked without recursion, before anything else walks the tree with it. Texts expand their entities
110
+ # here, so that REXML's limits on expansion raise InvalidSVGData rather than a RuntimeError mid-render.
111
+ def check_tree!(root)
112
+ level = [root]
113
+ MAXIMUM_DEPTH.times do
114
+ level.each { |element| element.texts.each(&:value) }
115
+ level = level.flat_map { _1.elements.to_a }
116
+ return if level.empty?
117
+ end
118
+ raise InvalidSVGData, "The SVG document nests elements deeper than #{MAXIMUM_DEPTH} levels"
119
+ rescue RuntimeError => e
120
+ raise InvalidSVGData, "The data supplied is not a valid SVG document: #{e.message}"
121
+ end
122
+
123
+ # Gamba: one level further down the tree, unless that is too deep.
124
+ def nested
125
+ raise Prawn::SVG::Elements::Base::SkipElementError, "elements nested deeper than #{MAXIMUM_DEPTH} levels" if @depth >= MAXIMUM_DEPTH
126
+
127
+ @depth += 1
128
+ begin
129
+ yield
130
+ ensure
131
+ @depth -= 1
132
+ end
133
+ end
134
+
63
135
  def calculate_sizing(requested_width: nil, requested_height: nil)
64
136
  sizing.requested_width = requested_width
65
137
  sizing.requested_height = requested_height
@@ -142,7 +142,7 @@ class Prawn::SVG::Elements::Base
142
142
  add_call "save"
143
143
 
144
144
  child = element_class.new(@document, elem, @calls, state.dup)
145
- child.process
145
+ @document.nested { child.process }
146
146
 
147
147
  add_call "restore"
148
148
  else
@@ -97,7 +97,8 @@ class Prawn::SVG::Elements::Image < Prawn::SVG::Elements::Base
97
97
  has_web_loader = @document.url_loader.loaders.any?(Prawn::SVG::Loaders::Web)
98
98
  document = Prawn::SVG::Document.new(
99
99
  data, [width, height], {width:, height:, enable_web_requests: has_web_loader},
100
- attribute_overrides:
100
+ # Gamba: the parent's fonts, without which an embedded SVG holding text failed to render.
101
+ attribute_overrides:, font_registry: @document.font_registry
101
102
  )
102
103
 
103
104
  dimensions = [document.sizing.output_width, document.sizing.output_height]
@@ -151,7 +152,7 @@ class Prawn::SVG::Elements::Image < Prawn::SVG::Elements::Base
151
152
  root = REXML::Document.new(data).root
152
153
  return unless root
153
154
 
154
- element = REXML::XPath.match(root, %(//*[@id="#{fragment.gsub('"', '\\"')}"])).first
155
+ element = Prawn::SVG::Document.element_by_id(root, fragment)
155
156
  return unless element&.name == "view"
156
157
 
157
158
  attrs = {}
@@ -191,6 +191,9 @@ module Prawn::SVG
191
191
  end
192
192
 
193
193
  def render_text_directly(prawn, text, font_runs, opts)
194
+ # Gamba: text placed or turned by an infinite or NaN number would write NaN into the page: it is left out.
195
+ return unless opts[:at].all?(&:finite?) && opts.fetch(:rotate, 0).finite?
196
+
194
197
  if font_runs.nil?
195
198
  prawn.draw_text(text, **opts)
196
199
  else
@@ -41,8 +41,10 @@ class Prawn::SVG::Elements::Use < Prawn::SVG::Elements::Base
41
41
  source.attributes["height"] = @height || "100%"
42
42
  end
43
43
 
44
- child = referenced_element_class.new(document, source, calls, state.dup)
45
- child.process
44
+ document.drawing_through_use(referenced_element_source) do
45
+ child = referenced_element_class.new(document, source, calls, state.dup)
46
+ document.nested { child.process }
47
+ end
46
48
 
47
49
  add_call "restore"
48
50
  end
@@ -58,7 +60,7 @@ class Prawn::SVG::Elements::Use < Prawn::SVG::Elements::Base
58
60
  else
59
61
  # Perhaps the element is defined further down in the document. This is not recommended but still valid SVG,
60
62
  # so we'll support it with an exception case that's not particularly performant.
61
- raw_element = REXML::XPath.match(@document.root, %(//*[@id="#{id.gsub('"', '\"')}"])).first
63
+ raw_element = @document.raw_element_by_id(id)
62
64
 
63
65
  if raw_element
64
66
  @referenced_element_class = Prawn::SVG::Elements::TAG_CLASS_MAPPING[raw_element.name.to_sym]
@@ -73,7 +75,7 @@ class Prawn::SVG::Elements::Use < Prawn::SVG::Elements::Base
73
75
 
74
76
  external_root, external_element_styles = load_external_svg(url)
75
77
 
76
- raw_element = REXML::XPath.match(external_root, %(//*[@id="#{fragment.gsub('"', '\"')}"])).first
78
+ raw_element = @document.raw_element_by_id(fragment, external_root)
77
79
  return unless raw_element
78
80
 
79
81
  @referenced_element_class = Prawn::SVG::Elements::TAG_CLASS_MAPPING[raw_element.name.to_sym]
@@ -99,7 +99,9 @@ module Prawn::SVG
99
99
  effective_stretch = (stretch == :normal) ? nil : stretch
100
100
 
101
101
  font = Font.new(family_name, weight, style, effective_stretch)
102
- family = (@font_families[family_name] ||= {})
102
+ # Gamba: a copy, written to. The families merged from the system's fonts are shared by every document of the
103
+ # process, and an SVG's @font-face would otherwise change them for all the documents after it.
104
+ family = @font_families[family_name] = (@font_families[family_name] || {}).dup
103
105
  family[font.subfamily] = font_data
104
106
  @font_case_mapping[family_name.downcase] = family_name
105
107
  end
@@ -3,6 +3,7 @@ module Prawn::SVG
3
3
  def initialize(document)
4
4
  @document = document
5
5
  @gradients_by_id = {}
6
+ @resolving = {}
6
7
  end
7
8
 
8
9
  def [](id)
@@ -11,8 +12,17 @@ module Prawn::SVG
11
12
 
12
13
  if (element = @gradients_by_id[id])
13
14
  element
14
- elsif (raw_element = find_raw_gradient_element_by_id(id))
15
- create_gradient_element(raw_element)
15
+ # Gamba: a gradient or pattern whose href chain comes back to itself stops there, without a parent, and a
16
+ # gradient left without stops paints nothing instead of failing to render.
17
+ elsif !@resolving.key?(id) && (raw_element = find_raw_gradient_element_by_id(id))
18
+ @resolving[id] = true
19
+ begin
20
+ # Gamba: only one that registered itself, which a gradient without stops never does.
21
+ create_gradient_element(raw_element)
22
+ @gradients_by_id[id]
23
+ ensure
24
+ @resolving.delete(id)
25
+ end
16
26
  end
17
27
  end
18
28
 
@@ -35,7 +45,7 @@ module Prawn::SVG
35
45
  end
36
46
 
37
47
  def find_raw_element_by_id(id)
38
- REXML::XPath.match(@document.root, %(//*[@id="#{id.gsub('"', '\"')}"])).first
48
+ @document.raw_element_by_id(id)
39
49
  end
40
50
 
41
51
  def gradient_element?(raw_element)
@@ -32,6 +32,10 @@ module Prawn
32
32
  @prawn = prawn
33
33
  @options = options
34
34
 
35
+ # Gamba: the document's font families as they were, put back once the SVG is drawn. Faces its @font-face
36
+ # rules declare, into the families its text draws with, would otherwise stay: an uploaded SVG could
37
+ # declare "Helvetica" and change the glyphs of every text the application draws after it.
38
+ @font_families_before = prawn.font_families.transform_values(&:dup)
35
39
  font_registry = Prawn::SVG::FontRegistry.new(prawn.font_families)
36
40
 
37
41
  @document = Document.new(
@@ -49,6 +53,8 @@ module Prawn
49
53
  @renderer.draw
50
54
 
51
55
  document.warnings.each { |w| warn w } if options[:log_warnings]
56
+ ensure
57
+ prawn.font_families.replace(@font_families_before)
52
58
  end
53
59
 
54
60
  def sizing
@@ -58,12 +58,19 @@ module Prawn::SVG::Loaders
58
58
 
59
59
  private
60
60
 
61
+ # Gamba: a regular file only, so that a directory, a FIFO or a device inside the root raises the loader's error,
62
+ # which skips the element, instead of failing the document or reading without end. Symbolic links inside the
63
+ # root are followed, as in prawn-svg: deployments link shared directories into it.
61
64
  def load_file(path)
62
65
  path = Addressable::URI.unencode(path)
63
66
  path = build_absolute_and_expand_path(path)
64
67
  assert_valid_path!(path)
65
68
  assert_file_exists!(path)
69
+ raise Prawn::SVG::UrlLoader::Error, "#{path} is not a regular file" unless ::File.file?(path)
70
+
66
71
  ::File.binread(path)
72
+ rescue SystemCallError, ArgumentError => e
73
+ raise Prawn::SVG::UrlLoader::Error, "cannot read #{path}: #{e.message}"
67
74
  end
68
75
 
69
76
  def build_uri(url)
@@ -94,6 +94,14 @@ module Prawn
94
94
 
95
95
  def issue_prawn_command(prawn, calls)
96
96
  calls.each do |call, arguments, kwarguments, children|
97
+ # Gamba: an infinite or NaN number, from a transform such as rotate(1e400), would be written into the page
98
+ # as NaN or Infinity, which no PDF reader parses: the call and what it holds are left out.
99
+ if non_finite?(arguments) || non_finite?(kwarguments)
100
+ warning = "#{call} left out: its arguments are not finite numbers"
101
+ document.warnings << warning unless document.warnings.include?(warning)
102
+ next
103
+ end
104
+
97
105
  skip = false
98
106
 
99
107
  rewrite_call_arguments(prawn, call, arguments, kwarguments, children) do
@@ -117,6 +125,15 @@ module Prawn
117
125
  end
118
126
  end
119
127
 
128
+ def non_finite?(value)
129
+ case value
130
+ when Float then !value.finite?
131
+ when Array then value.any? { non_finite?(_1) }
132
+ when Hash then value.each_value.any? { non_finite?(_1) }
133
+ else false
134
+ end
135
+ end
136
+
120
137
  def rewrite_call_arguments(prawn, call, arguments, kwarguments, children)
121
138
  case call
122
139
  when "svg:render"
@@ -223,13 +240,18 @@ module Prawn
223
240
  # Prawn's soft_mask hardcodes BBox to page.dimensions, which causes
224
241
  # Chrome and Firefox to clip mask content that extends beyond the page.
225
242
  # Temporarily override dimensions to use a large BBox.
243
+ # Gamba: a mask inside a mask finds the method defined already, and leaves it to the outer one to remove.
226
244
  def with_large_page_dimensions(prawn)
227
245
  page = prawn.state.page
246
+ return yield if page.singleton_class.method_defined?(:dimensions, false)
247
+
228
248
  large_bbox = [-10_000, -10_000, 10_000, 10_000]
229
249
  page.define_singleton_method(:dimensions) { large_bbox }
230
- yield
231
- ensure
232
- page.singleton_class.remove_method(:dimensions)
250
+ begin
251
+ yield
252
+ ensure
253
+ page.singleton_class.remove_method(:dimensions)
254
+ end
233
255
  end
234
256
 
235
257
  def inheritable_options
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: gamba
3
3
  version: !ruby/object:Gem::Version
4
- version: 2.0.0
4
+ version: 2.0.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Level UP Solutions
@@ -257,7 +257,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
257
257
  - !ruby/object:Gem::Version
258
258
  version: '0'
259
259
  requirements: []
260
- rubygems_version: 4.0.24
260
+ rubygems_version: 4.0.20
261
261
  specification_version: 4
262
262
  summary: 'Prawn''s API, rewritten for speed: same pages, lighter files'
263
263
  test_files: []