/src/qpdf/libqpdf/QPDF_objects.cc
Line | Count | Source (jump to first uncovered line) |
1 | | #include <qpdf/qpdf-config.h> // include first for large file support |
2 | | |
3 | | #include <qpdf/QPDF_private.hh> |
4 | | |
5 | | #include <qpdf/InputSource_private.hh> |
6 | | #include <qpdf/Pipeline.hh> |
7 | | #include <qpdf/QPDFExc.hh> |
8 | | #include <qpdf/QPDFLogger.hh> |
9 | | #include <qpdf/QPDFObjectHandle_private.hh> |
10 | | #include <qpdf/QPDFObject_private.hh> |
11 | | #include <qpdf/QPDFParser.hh> |
12 | | #include <qpdf/QTC.hh> |
13 | | #include <qpdf/QUtil.hh> |
14 | | #include <qpdf/Util.hh> |
15 | | |
16 | | #include <array> |
17 | | #include <atomic> |
18 | | #include <cstring> |
19 | | #include <limits> |
20 | | #include <map> |
21 | | #include <vector> |
22 | | |
23 | | using namespace qpdf; |
24 | | using namespace std::literals; |
25 | | |
26 | | namespace |
27 | | { |
28 | | class InvalidInputSource: public InputSource |
29 | | { |
30 | | public: |
31 | | ~InvalidInputSource() override = default; |
32 | | qpdf_offset_t |
33 | | findAndSkipNextEOL() override |
34 | 0 | { |
35 | 0 | throwException(); |
36 | 0 | return 0; |
37 | 0 | } |
38 | | std::string const& |
39 | | getName() const override |
40 | 0 | { |
41 | 0 | static std::string name("closed input source"); |
42 | 0 | return name; |
43 | 0 | } |
44 | | qpdf_offset_t |
45 | | tell() override |
46 | 0 | { |
47 | 0 | throwException(); |
48 | 0 | return 0; |
49 | 0 | } |
50 | | void |
51 | | seek(qpdf_offset_t offset, int whence) override |
52 | 0 | { |
53 | 0 | throwException(); |
54 | 0 | } |
55 | | void |
56 | | rewind() override |
57 | 0 | { |
58 | 0 | throwException(); |
59 | 0 | } |
60 | | size_t |
61 | | read(char* buffer, size_t length) override |
62 | 0 | { |
63 | 0 | throwException(); |
64 | 0 | return 0; |
65 | 0 | } |
66 | | void |
67 | | unreadCh(char ch) override |
68 | 0 | { |
69 | 0 | throwException(); |
70 | 0 | } |
71 | | |
72 | | private: |
73 | | void |
74 | | throwException() |
75 | 0 | { |
76 | 0 | throw std::logic_error( |
77 | 0 | "QPDF operation attempted on a QPDF object with no input " |
78 | 0 | "source. QPDF operations are invalid before processFile (or " |
79 | 0 | "another process method) or after closeInputSource"); |
80 | 0 | } |
81 | | }; |
82 | | } // namespace |
83 | | |
84 | | class QPDF::ResolveRecorder final |
85 | | { |
86 | | public: |
87 | | ResolveRecorder(QPDF& qpdf, QPDFObjGen const& og) : |
88 | 0 | qpdf(qpdf), |
89 | 0 | iter(qpdf.m->resolving.insert(og).first) |
90 | 0 | { |
91 | 0 | } |
92 | | ~ResolveRecorder() |
93 | 0 | { |
94 | 0 | qpdf.m->resolving.erase(iter); |
95 | 0 | } |
96 | | |
97 | | private: |
98 | | QPDF& qpdf; |
99 | | std::set<QPDFObjGen>::const_iterator iter; |
100 | | }; |
101 | | |
102 | | bool |
103 | | QPDF::findStartxref() |
104 | 7.52k | { |
105 | 7.52k | if (readToken(*m->file).isWord("startxref") && readToken(*m->file).isInteger()) { |
106 | | // Position in front of offset token |
107 | 7.52k | m->file->seek(m->file->getLastOffset(), SEEK_SET); |
108 | 7.52k | return true; |
109 | 7.52k | } |
110 | 0 | return false; |
111 | 7.52k | } |
112 | | |
113 | | void |
114 | | QPDF::parse(char const* password) |
115 | 7.52k | { |
116 | 7.52k | if (password) { |
117 | 0 | m->encp->provided_password = password; |
118 | 0 | } |
119 | | |
120 | | // Find the header anywhere in the first 1024 bytes of the file. |
121 | 7.52k | PatternFinder hf(*this, &QPDF::findHeader); |
122 | 7.52k | if (!m->file->findFirst("%PDF-", 0, 1024, hf)) { |
123 | 0 | QTC::TC("qpdf", "QPDF not a pdf file"); |
124 | 0 | warn(damagedPDF("", -1, "can't find PDF header")); |
125 | | // QPDFWriter writes files that usually require at least version 1.2 for /FlateDecode |
126 | 0 | m->pdf_version = "1.2"; |
127 | 0 | } |
128 | | |
129 | | // PDF spec says %%EOF must be found within the last 1024 bytes of/ the file. We add an extra |
130 | | // 30 characters to leave room for the startxref stuff. |
131 | 7.52k | m->file->seek(0, SEEK_END); |
132 | 7.52k | qpdf_offset_t end_offset = m->file->tell(); |
133 | 7.52k | m->xref_table_max_offset = end_offset; |
134 | | // Sanity check on object ids. All objects must appear in xref table / stream. In all realistic |
135 | | // scenarios at least 3 bytes are required. |
136 | 7.52k | if (m->xref_table_max_id > m->xref_table_max_offset / 3) { |
137 | 7.52k | m->xref_table_max_id = static_cast<int>(m->xref_table_max_offset / 3); |
138 | 7.52k | } |
139 | 7.52k | qpdf_offset_t start_offset = (end_offset > 1054 ? end_offset - 1054 : 0); |
140 | 7.52k | PatternFinder sf(*this, &QPDF::findStartxref); |
141 | 7.52k | qpdf_offset_t xref_offset = 0; |
142 | 7.52k | if (m->file->findLast("startxref", start_offset, 0, sf)) { |
143 | 7.52k | xref_offset = QUtil::string_to_ll(readToken(*m->file).getValue().c_str()); |
144 | 7.52k | } |
145 | | |
146 | 7.52k | try { |
147 | 7.52k | if (xref_offset == 0) { |
148 | 0 | QTC::TC("qpdf", "QPDF can't find startxref"); |
149 | 0 | throw damagedPDF("", -1, "can't find startxref"); |
150 | 0 | } |
151 | 7.52k | try { |
152 | 7.52k | read_xref(xref_offset); |
153 | 7.52k | } catch (QPDFExc&) { |
154 | 0 | throw; |
155 | 0 | } catch (std::exception& e) { |
156 | 0 | throw damagedPDF("", -1, std::string("error reading xref: ") + e.what()); |
157 | 0 | } |
158 | 7.52k | } catch (QPDFExc& e) { |
159 | 0 | if (m->attempt_recovery) { |
160 | 0 | reconstruct_xref(e, xref_offset > 0); |
161 | 0 | QTC::TC("qpdf", "QPDF reconstructed xref table"); |
162 | 0 | } else { |
163 | 0 | throw; |
164 | 0 | } |
165 | 0 | } |
166 | | |
167 | 7.52k | initializeEncryption(); |
168 | 7.52k | m->parsed = true; |
169 | 7.52k | if (!m->xref_table.empty() && !getRoot().getKey("/Pages").isDictionary()) { |
170 | | // QPDFs created from JSON have an empty xref table and no root object yet. |
171 | 0 | throw damagedPDF("", -1, "unable to find page tree"); |
172 | 0 | } |
173 | 7.52k | } |
174 | | |
175 | | void |
176 | | QPDF::inParse(bool v) |
177 | 15.0k | { |
178 | 15.0k | if (m->in_parse == v) { |
179 | | // This happens if QPDFParser::parse tries to resolve an indirect object while it is |
180 | | // parsing. |
181 | 0 | throw std::logic_error( |
182 | 0 | "QPDF: re-entrant parsing detected. This is a qpdf bug." |
183 | 0 | " Please report at https://github.com/qpdf/qpdf/issues."); |
184 | 0 | } |
185 | 15.0k | m->in_parse = v; |
186 | 15.0k | } |
187 | | |
188 | | void |
189 | | QPDF::setTrailer(QPDFObjectHandle obj) |
190 | 7.52k | { |
191 | 7.52k | if (m->trailer) { |
192 | 0 | return; |
193 | 0 | } |
194 | 7.52k | m->trailer = obj; |
195 | 7.52k | } |
196 | | |
197 | | void |
198 | | QPDF::reconstruct_xref(QPDFExc& e, bool found_startxref) |
199 | 0 | { |
200 | 0 | if (m->reconstructed_xref) { |
201 | | // Avoid xref reconstruction infinite loops. This is getting very hard to reproduce because |
202 | | // qpdf is throwing many fewer exceptions while parsing. Most situations are warnings now. |
203 | 0 | throw e; |
204 | 0 | } |
205 | | |
206 | | // If recovery generates more than 1000 warnings, the file is so severely damaged that there |
207 | | // probably is no point trying to continue. |
208 | 0 | const auto max_warnings = m->warnings.size() + 1000U; |
209 | 0 | auto check_warnings = [this, max_warnings]() { |
210 | 0 | if (m->warnings.size() > max_warnings) { |
211 | 0 | throw damagedPDF("", -1, "too many errors while reconstructing cross-reference table"); |
212 | 0 | } |
213 | 0 | }; |
214 | |
|
215 | 0 | m->reconstructed_xref = true; |
216 | | // We may find more objects, which may contain dangling references. |
217 | 0 | m->fixed_dangling_refs = false; |
218 | |
|
219 | 0 | warn(damagedPDF("", -1, "file is damaged")); |
220 | 0 | warn(e); |
221 | 0 | warn(damagedPDF("", -1, "Attempting to reconstruct cross-reference table")); |
222 | | |
223 | | // Delete all references to type 1 (uncompressed) objects |
224 | 0 | std::vector<QPDFObjGen> to_delete; |
225 | 0 | for (auto const& iter: m->xref_table) { |
226 | 0 | if (iter.second.getType() == 1) { |
227 | 0 | to_delete.emplace_back(iter.first); |
228 | 0 | } |
229 | 0 | } |
230 | 0 | for (auto const& iter: to_delete) { |
231 | 0 | m->xref_table.erase(iter); |
232 | 0 | } |
233 | |
|
234 | 0 | std::vector<std::tuple<int, int, qpdf_offset_t>> found_objects; |
235 | 0 | std::vector<qpdf_offset_t> trailers; |
236 | 0 | std::vector<qpdf_offset_t> startxrefs; |
237 | |
|
238 | 0 | m->file->seek(0, SEEK_END); |
239 | 0 | qpdf_offset_t eof = m->file->tell(); |
240 | 0 | m->file->seek(0, SEEK_SET); |
241 | | // Don't allow very long tokens here during recovery. All the interesting tokens are covered. |
242 | 0 | static size_t const MAX_LEN = 10; |
243 | 0 | while (m->file->tell() < eof) { |
244 | 0 | QPDFTokenizer::Token t1 = readToken(*m->file, MAX_LEN); |
245 | 0 | qpdf_offset_t token_start = m->file->tell() - toO(t1.getValue().length()); |
246 | 0 | if (t1.isInteger()) { |
247 | 0 | auto pos = m->file->tell(); |
248 | 0 | auto t2 = readToken(*m->file, MAX_LEN); |
249 | 0 | if (t2.isInteger() && readToken(*m->file, MAX_LEN).isWord("obj")) { |
250 | 0 | int obj = QUtil::string_to_int(t1.getValue().c_str()); |
251 | 0 | int gen = QUtil::string_to_int(t2.getValue().c_str()); |
252 | 0 | if (obj <= m->xref_table_max_id) { |
253 | 0 | found_objects.emplace_back(obj, gen, token_start); |
254 | 0 | } else { |
255 | 0 | warn(damagedPDF( |
256 | 0 | "", -1, "ignoring object with impossibly large id " + std::to_string(obj))); |
257 | 0 | } |
258 | 0 | } |
259 | 0 | m->file->seek(pos, SEEK_SET); |
260 | 0 | } else if (!m->trailer && t1.isWord("trailer")) { |
261 | 0 | trailers.emplace_back(m->file->tell()); |
262 | 0 | } else if (!found_startxref && t1.isWord("startxref")) { |
263 | 0 | startxrefs.emplace_back(m->file->tell()); |
264 | 0 | } |
265 | 0 | check_warnings(); |
266 | 0 | m->file->findAndSkipNextEOL(); |
267 | 0 | } |
268 | |
|
269 | 0 | if (!found_startxref && !startxrefs.empty() && !found_objects.empty() && |
270 | 0 | startxrefs.back() > std::get<2>(found_objects.back())) { |
271 | 0 | auto xref_backup{m->xref_table}; |
272 | 0 | try { |
273 | 0 | m->file->seek(startxrefs.back(), SEEK_SET); |
274 | 0 | if (auto offset = QUtil::string_to_ll(readToken(*m->file).getValue().data())) { |
275 | 0 | read_xref(offset); |
276 | |
|
277 | 0 | if (getRoot().getKey("/Pages").isDictionary()) { |
278 | 0 | QTC::TC("qpdf", "QPDF startxref more than 1024 before end"); |
279 | 0 | warn(damagedPDF( |
280 | 0 | "", -1, "startxref was more than 1024 bytes before end of file")); |
281 | 0 | initializeEncryption(); |
282 | 0 | m->parsed = true; |
283 | 0 | m->reconstructed_xref = false; |
284 | 0 | return; |
285 | 0 | } |
286 | 0 | } |
287 | 0 | } catch (...) { |
288 | | // ok, bad luck. Do recovery. |
289 | 0 | } |
290 | 0 | m->xref_table = std::move(xref_backup); |
291 | 0 | } |
292 | | |
293 | 0 | auto rend = found_objects.rend(); |
294 | 0 | for (auto it = found_objects.rbegin(); it != rend; it++) { |
295 | 0 | auto [obj, gen, token_start] = *it; |
296 | 0 | insertXrefEntry(obj, 1, token_start, gen); |
297 | 0 | check_warnings(); |
298 | 0 | } |
299 | 0 | m->deleted_objects.clear(); |
300 | |
|
301 | 0 | for (auto it = trailers.rbegin(); it != trailers.rend(); it++) { |
302 | 0 | m->file->seek(*it, SEEK_SET); |
303 | 0 | auto t = readTrailer(); |
304 | 0 | if (!t.isDictionary()) { |
305 | | // Oh well. It was worth a try. |
306 | 0 | } else { |
307 | 0 | if (t.hasKey("/Root")) { |
308 | 0 | m->trailer = t; |
309 | 0 | break; |
310 | 0 | } |
311 | 0 | warn(damagedPDF("trailer", *it, "recovered trailer has no /Root entry")); |
312 | 0 | } |
313 | 0 | check_warnings(); |
314 | 0 | } |
315 | |
|
316 | 0 | if (!m->trailer) { |
317 | 0 | qpdf_offset_t max_offset{0}; |
318 | 0 | size_t max_size{0}; |
319 | | // If there are any xref streams, take the last one to appear. |
320 | 0 | for (auto const& iter: m->xref_table) { |
321 | 0 | auto entry = iter.second; |
322 | 0 | if (entry.getType() != 1) { |
323 | 0 | continue; |
324 | 0 | } |
325 | 0 | auto oh = getObject(iter.first); |
326 | 0 | try { |
327 | 0 | if (!oh.isStreamOfType("/XRef")) { |
328 | 0 | continue; |
329 | 0 | } |
330 | 0 | } catch (std::exception&) { |
331 | 0 | continue; |
332 | 0 | } |
333 | 0 | auto offset = entry.getOffset(); |
334 | 0 | auto size = oh.getDict().getKey("/Size").getUIntValueAsUInt(); |
335 | 0 | if (size > max_size || (size == max_size && offset > max_offset)) { |
336 | 0 | max_offset = offset; |
337 | 0 | setTrailer(oh.getDict()); |
338 | 0 | } |
339 | 0 | check_warnings(); |
340 | 0 | } |
341 | 0 | if (max_offset > 0) { |
342 | 0 | try { |
343 | 0 | read_xref(max_offset, true); |
344 | 0 | } catch (std::exception&) { |
345 | 0 | warn(damagedPDF( |
346 | 0 | "", -1, "error decoding candidate xref stream while recovering damaged file")); |
347 | 0 | } |
348 | 0 | QTC::TC("qpdf", "QPDF recover xref stream"); |
349 | 0 | } |
350 | 0 | } |
351 | | |
352 | 0 | if (!m->trailer || (!m->parsed && !m->trailer.getKey("/Root").isDictionary())) { |
353 | | // Try to find a Root dictionary. As a quick fix try the one with the highest object id. |
354 | 0 | QPDFObjectHandle root; |
355 | 0 | for (auto const& iter: m->obj_cache) { |
356 | 0 | try { |
357 | 0 | if (QPDFObjectHandle(iter.second.object).isDictionaryOfType("/Catalog")) { |
358 | 0 | root = iter.second.object; |
359 | 0 | } |
360 | 0 | } catch (std::exception&) { |
361 | 0 | continue; |
362 | 0 | } |
363 | 0 | } |
364 | 0 | if (root) { |
365 | 0 | if (!m->trailer) { |
366 | 0 | warn(damagedPDF( |
367 | 0 | "", -1, "unable to find trailer dictionary while recovering damaged file")); |
368 | 0 | m->trailer = QPDFObjectHandle::newDictionary(); |
369 | 0 | } |
370 | 0 | m->trailer.replaceKey("/Root", root); |
371 | 0 | } |
372 | 0 | } |
373 | | |
374 | 0 | if (!m->trailer) { |
375 | | // We could check the last encountered object to see if it was an xref stream. If so, we |
376 | | // could try to get the trailer from there. This may make it possible to recover files with |
377 | | // bad startxref pointers even when they have object streams. |
378 | |
|
379 | 0 | throw damagedPDF("", -1, "unable to find trailer dictionary while recovering damaged file"); |
380 | 0 | } |
381 | 0 | if (m->xref_table.empty()) { |
382 | | // We cannot check for an empty xref table in parse because empty tables are valid when |
383 | | // creating QPDF objects from JSON. |
384 | 0 | throw damagedPDF("", -1, "unable to find objects while recovering damaged file"); |
385 | 0 | } |
386 | 0 | check_warnings(); |
387 | 0 | if (!m->parsed) { |
388 | 0 | m->parsed = true; |
389 | 0 | getAllPages(); |
390 | 0 | check_warnings(); |
391 | 0 | if (m->all_pages.empty()) { |
392 | 0 | m->parsed = false; |
393 | 0 | throw damagedPDF("", -1, "unable to find any pages while recovering damaged file"); |
394 | 0 | } |
395 | 0 | } |
396 | | |
397 | | // We could iterate through the objects looking for streams and try to find objects inside of |
398 | | // them, but it's probably not worth the trouble. Acrobat can't recover files with any errors |
399 | | // in an xref stream, and this would be a real long shot anyway. If we wanted to do anything |
400 | | // that involved looking at stream contents, we'd also have to call initializeEncryption() here. |
401 | | // It's safe to call it more than once. |
402 | 0 | } |
403 | | |
404 | | void |
405 | | QPDF::read_xref(qpdf_offset_t xref_offset, bool in_stream_recovery) |
406 | 7.52k | { |
407 | 7.52k | std::map<int, int> free_table; |
408 | 7.52k | std::set<qpdf_offset_t> visited; |
409 | 15.0k | while (xref_offset) { |
410 | 7.52k | visited.insert(xref_offset); |
411 | 7.52k | char buf[7]; |
412 | 7.52k | memset(buf, 0, sizeof(buf)); |
413 | 7.52k | m->file->seek(xref_offset, SEEK_SET); |
414 | | // Some files miss the mark a little with startxref. We could do a better job of searching |
415 | | // in the neighborhood for something that looks like either an xref table or stream, but the |
416 | | // simple heuristic of skipping whitespace can help with the xref table case and is harmless |
417 | | // with the stream case. |
418 | 7.52k | bool done = false; |
419 | 7.52k | bool skipped_space = false; |
420 | 15.0k | while (!done) { |
421 | 7.52k | char ch; |
422 | 7.52k | if (1 == m->file->read(&ch, 1)) { |
423 | 7.52k | if (util::is_space(ch)) { |
424 | 0 | skipped_space = true; |
425 | 7.52k | } else { |
426 | 7.52k | m->file->unreadCh(ch); |
427 | 7.52k | done = true; |
428 | 7.52k | } |
429 | 7.52k | } else { |
430 | 0 | QTC::TC("qpdf", "QPDF eof skipping spaces before xref", skipped_space ? 0 : 1); |
431 | 0 | done = true; |
432 | 0 | } |
433 | 7.52k | } |
434 | | |
435 | 7.52k | m->file->read(buf, sizeof(buf) - 1); |
436 | | // The PDF spec says xref must be followed by a line terminator, but files exist in the wild |
437 | | // where it is terminated by arbitrary whitespace. |
438 | 7.52k | if ((strncmp(buf, "xref", 4) == 0) && util::is_space(buf[4])) { |
439 | 7.52k | if (skipped_space) { |
440 | 0 | QTC::TC("qpdf", "QPDF xref skipped space"); |
441 | 0 | warn(damagedPDF("", -1, "extraneous whitespace seen before xref")); |
442 | 0 | } |
443 | 7.52k | QTC::TC( |
444 | 7.52k | "qpdf", |
445 | 7.52k | "QPDF xref space", |
446 | 7.52k | ((buf[4] == '\n') ? 0 |
447 | 7.52k | : (buf[4] == '\r') ? 1 |
448 | 0 | : (buf[4] == ' ') ? 2 |
449 | 0 | : 9999)); |
450 | 7.52k | int skip = 4; |
451 | | // buf is null-terminated, and util::is_space('\0') is false, so this won't overrun. |
452 | 15.0k | while (util::is_space(buf[skip])) { |
453 | 7.52k | ++skip; |
454 | 7.52k | } |
455 | 7.52k | xref_offset = read_xrefTable(xref_offset + skip); |
456 | 7.52k | } else { |
457 | 0 | xref_offset = read_xrefStream(xref_offset, in_stream_recovery); |
458 | 0 | } |
459 | 7.52k | if (visited.contains(xref_offset)) { |
460 | 0 | QTC::TC("qpdf", "QPDF xref loop"); |
461 | 0 | throw damagedPDF("", -1, "loop detected following xref tables"); |
462 | 0 | } |
463 | 7.52k | } |
464 | | |
465 | 7.52k | if (!m->trailer) { |
466 | 0 | throw damagedPDF("", -1, "unable to find trailer while reading xref"); |
467 | 0 | } |
468 | 7.52k | int size = m->trailer.getKey("/Size").getIntValueAsInt(); |
469 | 7.52k | int max_obj = 0; |
470 | 7.52k | if (!m->xref_table.empty()) { |
471 | 0 | max_obj = m->xref_table.rbegin()->first.getObj(); |
472 | 0 | } |
473 | 7.52k | if (!m->deleted_objects.empty()) { |
474 | 7.52k | max_obj = std::max(max_obj, *(m->deleted_objects.rbegin())); |
475 | 7.52k | } |
476 | 7.52k | if ((size < 1) || (size - 1 != max_obj)) { |
477 | 0 | QTC::TC("qpdf", "QPDF xref size mismatch"); |
478 | 0 | warn(damagedPDF( |
479 | 0 | "", |
480 | 0 | -1, |
481 | 0 | ("reported number of objects (" + std::to_string(size) + |
482 | 0 | ") is not one plus the highest object number (" + std::to_string(max_obj) + ")"))); |
483 | 0 | } |
484 | | |
485 | | // We no longer need the deleted_objects table, so go ahead and clear it out to make sure we |
486 | | // never depend on its being set. |
487 | 7.52k | m->deleted_objects.clear(); |
488 | | |
489 | | // Make sure we keep only the highest generation for any object. |
490 | 7.52k | QPDFObjGen last_og{-1, 0}; |
491 | 7.52k | for (auto const& item: m->xref_table) { |
492 | 0 | auto id = item.first.getObj(); |
493 | 0 | if (id == last_og.getObj() && id > 0) { |
494 | 0 | removeObject(last_og); |
495 | 0 | } |
496 | 0 | last_og = item.first; |
497 | 0 | } |
498 | 7.52k | } |
499 | | |
500 | | bool |
501 | | QPDF::parse_xrefFirst(std::string const& line, int& obj, int& num, int& bytes) |
502 | 7.52k | { |
503 | | // is_space and is_digit both return false on '\0', so this will not overrun the null-terminated |
504 | | // buffer. |
505 | 7.52k | char const* p = line.c_str(); |
506 | 7.52k | char const* start = line.c_str(); |
507 | | |
508 | | // Skip zero or more spaces |
509 | 7.52k | while (util::is_space(*p)) { |
510 | 0 | ++p; |
511 | 0 | } |
512 | | // Require digit |
513 | 7.52k | if (!util::is_digit(*p)) { |
514 | 0 | return false; |
515 | 0 | } |
516 | | // Gather digits |
517 | 7.52k | std::string obj_str; |
518 | 15.0k | while (util::is_digit(*p)) { |
519 | 7.52k | obj_str.append(1, *p++); |
520 | 7.52k | } |
521 | | // Require space |
522 | 7.52k | if (!util::is_space(*p)) { |
523 | 0 | return false; |
524 | 0 | } |
525 | | // Skip spaces |
526 | 15.0k | while (util::is_space(*p)) { |
527 | 7.52k | ++p; |
528 | 7.52k | } |
529 | | // Require digit |
530 | 7.52k | if (!util::is_digit(*p)) { |
531 | 0 | return false; |
532 | 0 | } |
533 | | // Gather digits |
534 | 7.52k | std::string num_str; |
535 | 15.0k | while (util::is_digit(*p)) { |
536 | 7.52k | num_str.append(1, *p++); |
537 | 7.52k | } |
538 | | // Skip any space including line terminators |
539 | 15.0k | while (util::is_space(*p)) { |
540 | 7.52k | ++p; |
541 | 7.52k | } |
542 | 7.52k | bytes = toI(p - start); |
543 | 7.52k | obj = QUtil::string_to_int(obj_str.c_str()); |
544 | 7.52k | num = QUtil::string_to_int(num_str.c_str()); |
545 | 7.52k | return true; |
546 | 7.52k | } |
547 | | |
548 | | bool |
549 | | QPDF::read_bad_xrefEntry(qpdf_offset_t& f1, int& f2, char& type) |
550 | 0 | { |
551 | | // Reposition after initial read attempt and reread. |
552 | 0 | m->file->seek(m->file->getLastOffset(), SEEK_SET); |
553 | 0 | auto line = m->file->readLine(30); |
554 | | |
555 | | // is_space and is_digit both return false on '\0', so this will not overrun the null-terminated |
556 | | // buffer. |
557 | 0 | char const* p = line.data(); |
558 | | |
559 | | // Skip zero or more spaces. There aren't supposed to be any. |
560 | 0 | bool invalid = false; |
561 | 0 | while (util::is_space(*p)) { |
562 | 0 | ++p; |
563 | 0 | QTC::TC("qpdf", "QPDF ignore first space in xref entry"); |
564 | 0 | invalid = true; |
565 | 0 | } |
566 | | // Require digit |
567 | 0 | if (!util::is_digit(*p)) { |
568 | 0 | return false; |
569 | 0 | } |
570 | | // Gather digits |
571 | 0 | std::string f1_str; |
572 | 0 | while (util::is_digit(*p)) { |
573 | 0 | f1_str.append(1, *p++); |
574 | 0 | } |
575 | | // Require space |
576 | 0 | if (!util::is_space(*p)) { |
577 | 0 | return false; |
578 | 0 | } |
579 | 0 | if (util::is_space(*(p + 1))) { |
580 | 0 | QTC::TC("qpdf", "QPDF ignore first extra space in xref entry"); |
581 | 0 | invalid = true; |
582 | 0 | } |
583 | | // Skip spaces |
584 | 0 | while (util::is_space(*p)) { |
585 | 0 | ++p; |
586 | 0 | } |
587 | | // Require digit |
588 | 0 | if (!util::is_digit(*p)) { |
589 | 0 | return false; |
590 | 0 | } |
591 | | // Gather digits |
592 | 0 | std::string f2_str; |
593 | 0 | while (util::is_digit(*p)) { |
594 | 0 | f2_str.append(1, *p++); |
595 | 0 | } |
596 | | // Require space |
597 | 0 | if (!util::is_space(*p)) { |
598 | 0 | return false; |
599 | 0 | } |
600 | 0 | if (util::is_space(*(p + 1))) { |
601 | 0 | QTC::TC("qpdf", "QPDF ignore second extra space in xref entry"); |
602 | 0 | invalid = true; |
603 | 0 | } |
604 | | // Skip spaces |
605 | 0 | while (util::is_space(*p)) { |
606 | 0 | ++p; |
607 | 0 | } |
608 | 0 | if ((*p == 'f') || (*p == 'n')) { |
609 | 0 | type = *p; |
610 | 0 | } else { |
611 | 0 | return false; |
612 | 0 | } |
613 | 0 | if ((f1_str.length() != 10) || (f2_str.length() != 5)) { |
614 | 0 | QTC::TC("qpdf", "QPDF ignore length error xref entry"); |
615 | 0 | invalid = true; |
616 | 0 | } |
617 | |
|
618 | 0 | if (invalid) { |
619 | 0 | warn(damagedPDF("xref table", "accepting invalid xref table entry")); |
620 | 0 | } |
621 | |
|
622 | 0 | f1 = QUtil::string_to_ll(f1_str.c_str()); |
623 | 0 | f2 = QUtil::string_to_int(f2_str.c_str()); |
624 | |
|
625 | 0 | return true; |
626 | 0 | } |
627 | | |
628 | | // Optimistically read and parse xref entry. If entry is bad, call read_bad_xrefEntry and return |
629 | | // result. |
630 | | bool |
631 | | QPDF::read_xrefEntry(qpdf_offset_t& f1, int& f2, char& type) |
632 | 7.52k | { |
633 | 7.52k | std::array<char, 21> line; |
634 | 7.52k | if (m->file->read(line.data(), 20) != 20) { |
635 | | // C++20: [[unlikely]] |
636 | 0 | return false; |
637 | 0 | } |
638 | 7.52k | line[20] = '\0'; |
639 | 7.52k | char const* p = line.data(); |
640 | | |
641 | 7.52k | int f1_len = 0; |
642 | 7.52k | int f2_len = 0; |
643 | | |
644 | | // is_space and is_digit both return false on '\0', so this will not overrun the null-terminated |
645 | | // buffer. |
646 | | |
647 | | // Gather f1 digits. NB No risk of overflow as 9'999'999'999 < max long long. |
648 | 82.7k | while (*p == '0') { |
649 | 75.2k | ++f1_len; |
650 | 75.2k | ++p; |
651 | 75.2k | } |
652 | 7.52k | while (util::is_digit(*p) && f1_len++ < 10) { |
653 | 0 | f1 *= 10; |
654 | 0 | f1 += *p++ - '0'; |
655 | 0 | } |
656 | | // Require space |
657 | 7.52k | if (!util::is_space(*p++)) { |
658 | | // Entry doesn't start with space or digit. |
659 | | // C++20: [[unlikely]] |
660 | 0 | return false; |
661 | 0 | } |
662 | | // Gather digits. NB No risk of overflow as 99'999 < max int. |
663 | 7.52k | while (*p == '0') { |
664 | 0 | ++f2_len; |
665 | 0 | ++p; |
666 | 0 | } |
667 | 45.1k | while (util::is_digit(*p) && f2_len++ < 5) { |
668 | 37.6k | f2 *= 10; |
669 | 37.6k | f2 += static_cast<int>(*p++ - '0'); |
670 | 37.6k | } |
671 | 7.52k | if (util::is_space(*p++) && (*p == 'f' || *p == 'n')) { |
672 | | // C++20: [[likely]] |
673 | 7.52k | type = *p; |
674 | | // No test for valid line[19]. |
675 | 7.52k | if (*(++p) && *(++p) && (*p == '\n' || *p == '\r') && f1_len == 10 && f2_len == 5) { |
676 | | // C++20: [[likely]] |
677 | 7.52k | return true; |
678 | 7.52k | } |
679 | 7.52k | } |
680 | 0 | return read_bad_xrefEntry(f1, f2, type); |
681 | 7.52k | } |
682 | | |
683 | | // Read a single cross-reference table section and associated trailer. |
684 | | qpdf_offset_t |
685 | | QPDF::read_xrefTable(qpdf_offset_t xref_offset) |
686 | 7.52k | { |
687 | 7.52k | m->file->seek(xref_offset, SEEK_SET); |
688 | 7.52k | std::string line; |
689 | 7.52k | while (true) { |
690 | 7.52k | line.assign(50, '\0'); |
691 | 7.52k | m->file->read(line.data(), line.size()); |
692 | 7.52k | int obj = 0; |
693 | 7.52k | int num = 0; |
694 | 7.52k | int bytes = 0; |
695 | 7.52k | if (!parse_xrefFirst(line, obj, num, bytes)) { |
696 | 0 | QTC::TC("qpdf", "QPDF invalid xref"); |
697 | 0 | throw damagedPDF("xref table", "xref syntax invalid"); |
698 | 0 | } |
699 | 7.52k | m->file->seek(m->file->getLastOffset() + bytes, SEEK_SET); |
700 | 15.0k | for (qpdf_offset_t i = obj; i - num < obj; ++i) { |
701 | 7.52k | if (i == 0) { |
702 | | // This is needed by checkLinearization() |
703 | 7.52k | m->first_xref_item_offset = m->file->tell(); |
704 | 7.52k | } |
705 | | // For xref_table, these will always be small enough to be ints |
706 | 7.52k | qpdf_offset_t f1 = 0; |
707 | 7.52k | int f2 = 0; |
708 | 7.52k | char type = '\0'; |
709 | 7.52k | if (!read_xrefEntry(f1, f2, type)) { |
710 | 0 | QTC::TC("qpdf", "QPDF invalid xref entry"); |
711 | 0 | throw damagedPDF( |
712 | 0 | "xref table", "invalid xref entry (obj=" + std::to_string(i) + ")"); |
713 | 0 | } |
714 | 7.52k | if (type == 'f') { |
715 | 7.52k | insertFreeXrefEntry(QPDFObjGen(toI(i), f2)); |
716 | 7.52k | } else { |
717 | 0 | insertXrefEntry(toI(i), 1, f1, f2); |
718 | 0 | } |
719 | 7.52k | } |
720 | 7.52k | qpdf_offset_t pos = m->file->tell(); |
721 | 7.52k | if (readToken(*m->file).isWord("trailer")) { |
722 | 7.52k | break; |
723 | 7.52k | } else { |
724 | 0 | m->file->seek(pos, SEEK_SET); |
725 | 0 | } |
726 | 7.52k | } |
727 | | |
728 | | // Set offset to previous xref table if any |
729 | 7.52k | QPDFObjectHandle cur_trailer = readTrailer(); |
730 | 7.52k | if (!cur_trailer.isDictionary()) { |
731 | 0 | QTC::TC("qpdf", "QPDF missing trailer"); |
732 | 0 | throw damagedPDF("", "expected trailer dictionary"); |
733 | 0 | } |
734 | | |
735 | 7.52k | if (!m->trailer) { |
736 | 7.52k | setTrailer(cur_trailer); |
737 | | |
738 | 7.52k | if (!m->trailer.hasKey("/Size")) { |
739 | 0 | QTC::TC("qpdf", "QPDF trailer lacks size"); |
740 | 0 | throw damagedPDF("trailer", "trailer dictionary lacks /Size key"); |
741 | 0 | } |
742 | 7.52k | if (!m->trailer.getKey("/Size").isInteger()) { |
743 | 0 | QTC::TC("qpdf", "QPDF trailer size not integer"); |
744 | 0 | throw damagedPDF("trailer", "/Size key in trailer dictionary is not an integer"); |
745 | 0 | } |
746 | 7.52k | } |
747 | | |
748 | 7.52k | if (cur_trailer.hasKey("/XRefStm")) { |
749 | 0 | if (m->ignore_xref_streams) { |
750 | 0 | QTC::TC("qpdf", "QPDF ignoring XRefStm in trailer"); |
751 | 0 | } else { |
752 | 0 | if (cur_trailer.getKey("/XRefStm").isInteger()) { |
753 | | // Read the xref stream but disregard any return value -- we'll use our trailer's |
754 | | // /Prev key instead of the xref stream's. |
755 | 0 | (void)read_xrefStream(cur_trailer.getKey("/XRefStm").getIntValue()); |
756 | 0 | } else { |
757 | 0 | throw damagedPDF("xref stream", xref_offset, "invalid /XRefStm"); |
758 | 0 | } |
759 | 0 | } |
760 | 0 | } |
761 | | |
762 | 7.52k | if (cur_trailer.hasKey("/Prev")) { |
763 | 0 | if (!cur_trailer.getKey("/Prev").isInteger()) { |
764 | 0 | QTC::TC("qpdf", "QPDF trailer prev not integer"); |
765 | 0 | throw damagedPDF("trailer", "/Prev key in trailer dictionary is not an integer"); |
766 | 0 | } |
767 | 0 | QTC::TC("qpdf", "QPDF prev key in trailer dictionary"); |
768 | 0 | return cur_trailer.getKey("/Prev").getIntValue(); |
769 | 0 | } |
770 | | |
771 | 7.52k | return 0; |
772 | 7.52k | } |
773 | | |
774 | | // Read a single cross-reference stream. |
775 | | qpdf_offset_t |
776 | | QPDF::read_xrefStream(qpdf_offset_t xref_offset, bool in_stream_recovery) |
777 | 0 | { |
778 | 0 | if (!m->ignore_xref_streams) { |
779 | 0 | QPDFObjectHandle xref_obj; |
780 | 0 | try { |
781 | 0 | m->in_read_xref_stream = true; |
782 | 0 | xref_obj = readObjectAtOffset(xref_offset, "xref stream", true); |
783 | 0 | } catch (QPDFExc&) { |
784 | | // ignore -- report error below |
785 | 0 | } |
786 | 0 | m->in_read_xref_stream = false; |
787 | 0 | if (xref_obj.isStreamOfType("/XRef")) { |
788 | 0 | QTC::TC("qpdf", "QPDF found xref stream"); |
789 | 0 | return processXRefStream(xref_offset, xref_obj, in_stream_recovery); |
790 | 0 | } |
791 | 0 | } |
792 | | |
793 | 0 | QTC::TC("qpdf", "QPDF can't find xref"); |
794 | 0 | throw damagedPDF("", xref_offset, "xref not found"); |
795 | 0 | return 0; // unreachable |
796 | 0 | } |
797 | | |
798 | | // Return the entry size of the xref stream and the processed W array. |
799 | | std::pair<int, std::array<int, 3>> |
800 | | QPDF::processXRefW(QPDFObjectHandle& dict, std::function<QPDFExc(std::string_view)> damaged) |
801 | 0 | { |
802 | 0 | auto W_obj = dict.getKey("/W"); |
803 | 0 | if (!(W_obj.size() >= 3 && W_obj.getArrayItem(0).isInteger() && |
804 | 0 | W_obj.getArrayItem(1).isInteger() && W_obj.getArrayItem(2).isInteger())) { |
805 | 0 | throw damaged("Cross-reference stream does not have a proper /W key"); |
806 | 0 | } |
807 | | |
808 | 0 | std::array<int, 3> W; |
809 | 0 | int entry_size = 0; |
810 | 0 | auto w_vector = W_obj.getArrayAsVector(); |
811 | 0 | int max_bytes = sizeof(qpdf_offset_t); |
812 | 0 | for (size_t i = 0; i < 3; ++i) { |
813 | 0 | W[i] = w_vector[i].getIntValueAsInt(); |
814 | 0 | if (W[i] > max_bytes) { |
815 | 0 | throw damaged("Cross-reference stream's /W contains impossibly large values"); |
816 | 0 | } |
817 | 0 | if (W[i] < 0) { |
818 | 0 | throw damaged("Cross-reference stream's /W contains negative values"); |
819 | 0 | } |
820 | 0 | entry_size += W[i]; |
821 | 0 | } |
822 | 0 | if (entry_size == 0) { |
823 | 0 | throw damaged("Cross-reference stream's /W indicates entry size of 0"); |
824 | 0 | } |
825 | 0 | return {entry_size, W}; |
826 | 0 | } |
827 | | |
828 | | // Validate Size key and return the maximum number of entries that the xref stream can contain. |
829 | | int |
830 | | QPDF::processXRefSize( |
831 | | QPDFObjectHandle& dict, int entry_size, std::function<QPDFExc(std::string_view)> damaged) |
832 | 0 | { |
833 | | // Number of entries is limited by the highest possible object id and stream size. |
834 | 0 | auto max_num_entries = std::numeric_limits<int>::max(); |
835 | 0 | if (max_num_entries > (std::numeric_limits<qpdf_offset_t>::max() / entry_size)) { |
836 | 0 | max_num_entries = toI(std::numeric_limits<qpdf_offset_t>::max() / entry_size); |
837 | 0 | } |
838 | |
|
839 | 0 | auto Size_obj = dict.getKey("/Size"); |
840 | 0 | long long size; |
841 | 0 | if (!dict.getKey("/Size").getValueAsInt(size)) { |
842 | 0 | throw damaged("Cross-reference stream does not have a proper /Size key"); |
843 | 0 | } else if (size < 0) { |
844 | 0 | throw damaged("Cross-reference stream has a negative /Size key"); |
845 | 0 | } else if (size >= max_num_entries) { |
846 | 0 | throw damaged("Cross-reference stream has an impossibly large /Size key"); |
847 | 0 | } |
848 | | // We are not validating that Size <= (Size key of parent xref / trailer). |
849 | 0 | return max_num_entries; |
850 | 0 | } |
851 | | |
852 | | // Return the number of entries of the xref stream and the processed Index array. |
853 | | std::pair<int, std::vector<std::pair<int, int>>> |
854 | | QPDF::processXRefIndex( |
855 | | QPDFObjectHandle& dict, int max_num_entries, std::function<QPDFExc(std::string_view)> damaged) |
856 | 0 | { |
857 | 0 | auto size = dict.getKey("/Size").getIntValueAsInt(); |
858 | 0 | auto Index_obj = dict.getKey("/Index"); |
859 | |
|
860 | 0 | if (Index_obj.isArray()) { |
861 | 0 | std::vector<std::pair<int, int>> indx; |
862 | 0 | int num_entries = 0; |
863 | 0 | auto index_vec = Index_obj.getArrayAsVector(); |
864 | 0 | if ((index_vec.size() % 2) || index_vec.size() < 2) { |
865 | 0 | throw damaged("Cross-reference stream's /Index has an invalid number of values"); |
866 | 0 | } |
867 | | |
868 | 0 | int i = 0; |
869 | 0 | long long first = 0; |
870 | 0 | for (auto& val: index_vec) { |
871 | 0 | if (val.isInteger()) { |
872 | 0 | if (i % 2) { |
873 | 0 | auto count = val.getIntValue(); |
874 | 0 | if (count <= 0) { |
875 | 0 | throw damaged( |
876 | 0 | "Cross-reference stream section claims to contain " + |
877 | 0 | std::to_string(count) + " entries"); |
878 | 0 | } |
879 | | // We are guarding against the possibility of num_entries * entry_size |
880 | | // overflowing. We are not checking that entries are in ascending order as |
881 | | // required by the spec, which probably should generate a warning. We are also |
882 | | // not checking that for each subsection first object number + number of entries |
883 | | // <= /Size. The spec requires us to ignore object number > /Size. |
884 | 0 | if (first > (max_num_entries - count) || |
885 | 0 | count > (max_num_entries - num_entries)) { |
886 | 0 | throw damaged( |
887 | 0 | "Cross-reference stream claims to contain too many entries: " + |
888 | 0 | std::to_string(first) + " " + std::to_string(max_num_entries) + " " + |
889 | 0 | std::to_string(num_entries)); |
890 | 0 | } |
891 | 0 | indx.emplace_back(static_cast<int>(first), static_cast<int>(count)); |
892 | 0 | num_entries += static_cast<int>(count); |
893 | 0 | } else { |
894 | 0 | first = val.getIntValue(); |
895 | 0 | if (first < 0) { |
896 | 0 | throw damaged( |
897 | 0 | "Cross-reference stream's /Index contains a negative object id"); |
898 | 0 | } else if (first > max_num_entries) { |
899 | 0 | throw damaged( |
900 | 0 | "Cross-reference stream's /Index contains an impossibly " |
901 | 0 | "large object id"); |
902 | 0 | } |
903 | 0 | } |
904 | 0 | } else { |
905 | 0 | throw damaged( |
906 | 0 | "Cross-reference stream's /Index's item " + std::to_string(i) + |
907 | 0 | " is not an integer"); |
908 | 0 | } |
909 | 0 | i++; |
910 | 0 | } |
911 | 0 | QTC::TC("qpdf", "QPDF xref /Index is array", index_vec.size() == 2 ? 0 : 1); |
912 | 0 | return {num_entries, indx}; |
913 | 0 | } else if (Index_obj.isNull()) { |
914 | 0 | QTC::TC("qpdf", "QPDF xref /Index is null"); |
915 | 0 | return {size, {{0, size}}}; |
916 | 0 | } else { |
917 | 0 | throw damaged("Cross-reference stream does not have a proper /Index key"); |
918 | 0 | } |
919 | 0 | } |
920 | | |
921 | | qpdf_offset_t |
922 | | QPDF::processXRefStream( |
923 | | qpdf_offset_t xref_offset, QPDFObjectHandle& xref_obj, bool in_stream_recovery) |
924 | 0 | { |
925 | 0 | auto damaged = [this, xref_offset](std::string_view msg) -> QPDFExc { |
926 | 0 | return damagedPDF("xref stream", xref_offset, msg.data()); |
927 | 0 | }; |
928 | |
|
929 | 0 | auto dict = xref_obj.getDict(); |
930 | |
|
931 | 0 | auto [entry_size, W] = processXRefW(dict, damaged); |
932 | 0 | int max_num_entries = processXRefSize(dict, entry_size, damaged); |
933 | 0 | auto [num_entries, indx] = processXRefIndex(dict, max_num_entries, damaged); |
934 | |
|
935 | 0 | std::shared_ptr<Buffer> bp = xref_obj.getStreamData(qpdf_dl_specialized); |
936 | 0 | size_t actual_size = bp->getSize(); |
937 | 0 | auto expected_size = toS(entry_size) * toS(num_entries); |
938 | |
|
939 | 0 | if (expected_size != actual_size) { |
940 | 0 | QPDFExc x = damaged( |
941 | 0 | "Cross-reference stream data has the wrong size; expected = " + |
942 | 0 | std::to_string(expected_size) + "; actual = " + std::to_string(actual_size)); |
943 | 0 | if (expected_size > actual_size) { |
944 | 0 | throw x; |
945 | 0 | } else { |
946 | 0 | warn(x); |
947 | 0 | } |
948 | 0 | } |
949 | | |
950 | 0 | bool saw_first_compressed_object = false; |
951 | | |
952 | | // Actual size vs. expected size check above ensures that we will not overflow any buffers here. |
953 | | // We know that entry_size * num_entries is less or equal to the size of the buffer. |
954 | 0 | auto p = bp->getBuffer(); |
955 | 0 | for (auto [obj, sec_entries]: indx) { |
956 | | // Process a subsection. |
957 | 0 | for (int i = 0; i < sec_entries; ++i) { |
958 | | // Read this entry |
959 | 0 | std::array<qpdf_offset_t, 3> fields{}; |
960 | 0 | if (W[0] == 0) { |
961 | 0 | QTC::TC("qpdf", "QPDF default for xref stream field 0"); |
962 | 0 | fields[0] = 1; |
963 | 0 | } |
964 | 0 | for (size_t j = 0; j < 3; ++j) { |
965 | 0 | for (int k = 0; k < W[j]; ++k) { |
966 | 0 | fields[j] <<= 8; |
967 | 0 | fields[j] |= *p++; |
968 | 0 | } |
969 | 0 | } |
970 | | |
971 | | // Get the generation number. The generation number is 0 unless this is an uncompressed |
972 | | // object record, in which case the generation number appears as the third field. |
973 | 0 | if (saw_first_compressed_object) { |
974 | 0 | if (fields[0] != 2) { |
975 | 0 | m->uncompressed_after_compressed = true; |
976 | 0 | } |
977 | 0 | } else if (fields[0] == 2) { |
978 | 0 | saw_first_compressed_object = true; |
979 | 0 | } |
980 | 0 | if (obj == 0) { |
981 | | // This is needed by checkLinearization() |
982 | 0 | m->first_xref_item_offset = xref_offset; |
983 | 0 | } else if (fields[0] == 0) { |
984 | | // Ignore fields[2], which we don't care about in this case. This works around the |
985 | | // issue of some PDF files that put invalid values, like -1, here for deleted |
986 | | // objects. |
987 | 0 | insertFreeXrefEntry(QPDFObjGen(obj, 0)); |
988 | 0 | } else { |
989 | 0 | auto typ = toI(fields[0]); |
990 | 0 | if (!in_stream_recovery || typ == 2) { |
991 | | // If we are in xref stream recovery all actual uncompressed objects have |
992 | | // already been inserted into the xref table. Avoid adding junk data into the |
993 | | // xref table. |
994 | 0 | insertXrefEntry(obj, toI(fields[0]), fields[1], toI(fields[2])); |
995 | 0 | } |
996 | 0 | } |
997 | 0 | ++obj; |
998 | 0 | } |
999 | 0 | } |
1000 | |
|
1001 | 0 | if (!m->trailer) { |
1002 | 0 | setTrailer(dict); |
1003 | 0 | } |
1004 | |
|
1005 | 0 | if (dict.hasKey("/Prev")) { |
1006 | 0 | if (!dict.getKey("/Prev").isInteger()) { |
1007 | 0 | throw damagedPDF( |
1008 | 0 | "xref stream", "/Prev key in xref stream dictionary is not an integer"); |
1009 | 0 | } |
1010 | 0 | QTC::TC("qpdf", "QPDF prev key in xref stream dictionary"); |
1011 | 0 | return dict.getKey("/Prev").getIntValue(); |
1012 | 0 | } else { |
1013 | 0 | return 0; |
1014 | 0 | } |
1015 | 0 | } |
1016 | | |
1017 | | void |
1018 | | QPDF::insertXrefEntry(int obj, int f0, qpdf_offset_t f1, int f2) |
1019 | 0 | { |
1020 | | // Populate the xref table in such a way that the first reference to an object that we see, |
1021 | | // which is the one in the latest xref table in which it appears, is the one that gets stored. |
1022 | | // This works because we are reading more recent appends before older ones. |
1023 | | |
1024 | | // If there is already an entry for this object and generation in the table, it means that a |
1025 | | // later xref table has registered this object. Disregard this one. |
1026 | 0 | int new_gen = f0 == 2 ? 0 : f2; |
1027 | |
|
1028 | 0 | if (!(f0 == 1 || f0 == 2)) { |
1029 | 0 | return; |
1030 | 0 | } |
1031 | | |
1032 | 0 | if (!(obj > 0 && obj <= m->xref_table_max_id && 0 <= f2 && new_gen < 65535)) { |
1033 | | // We are ignoring invalid objgens. Most will arrive here from xref reconstruction. There |
1034 | | // is probably no point having another warning but we could count invalid items in order to |
1035 | | // decide when to give up. |
1036 | 0 | QTC::TC("qpdf", "QPDF xref overwrite invalid objgen"); |
1037 | | // ignore impossibly large object ids or object ids > Size. |
1038 | 0 | return; |
1039 | 0 | } |
1040 | | |
1041 | 0 | if (m->deleted_objects.contains(obj)) { |
1042 | 0 | QTC::TC("qpdf", "QPDF xref deleted object"); |
1043 | 0 | return; |
1044 | 0 | } |
1045 | | |
1046 | 0 | if (f0 == 2) { |
1047 | 0 | if (f1 == obj) { |
1048 | 0 | warn( |
1049 | 0 | damagedPDF("xref stream", "self-referential object stream " + std::to_string(obj))); |
1050 | 0 | return; |
1051 | 0 | } |
1052 | 0 | if (f1 > m->xref_table_max_id) { |
1053 | | // ignore impossibly large object stream ids |
1054 | 0 | warn(damagedPDF( |
1055 | 0 | "xref stream", |
1056 | 0 | "object stream id " + std::to_string(f1) + " for object " + std::to_string(obj) + |
1057 | 0 | " is impossibly large")); |
1058 | 0 | return; |
1059 | 0 | } |
1060 | 0 | } |
1061 | | |
1062 | 0 | auto [iter, created] = m->xref_table.try_emplace(QPDFObjGen(obj, (f0 == 2 ? 0 : f2))); |
1063 | 0 | if (!created) { |
1064 | 0 | QTC::TC("qpdf", "QPDF xref reused object"); |
1065 | 0 | return; |
1066 | 0 | } |
1067 | | |
1068 | 0 | switch (f0) { |
1069 | 0 | case 1: |
1070 | | // f2 is generation |
1071 | 0 | QTC::TC("qpdf", "QPDF xref gen > 0", ((f2 > 0) ? 1 : 0)); |
1072 | 0 | iter->second = QPDFXRefEntry(f1); |
1073 | 0 | break; |
1074 | | |
1075 | 0 | case 2: |
1076 | 0 | iter->second = QPDFXRefEntry(toI(f1), f2); |
1077 | 0 | break; |
1078 | | |
1079 | 0 | default: |
1080 | 0 | throw damagedPDF("xref stream", "unknown xref stream entry type " + std::to_string(f0)); |
1081 | 0 | break; |
1082 | 0 | } |
1083 | 0 | } |
1084 | | |
1085 | | void |
1086 | | QPDF::insertFreeXrefEntry(QPDFObjGen og) |
1087 | 7.52k | { |
1088 | 7.52k | if (!m->xref_table.contains(og)) { |
1089 | 7.52k | m->deleted_objects.insert(og.getObj()); |
1090 | 7.52k | } |
1091 | 7.52k | } |
1092 | | |
1093 | | void |
1094 | | QPDF::showXRefTable() |
1095 | 0 | { |
1096 | 0 | auto& cout = *m->log->getInfo(); |
1097 | 0 | for (auto const& iter: m->xref_table) { |
1098 | 0 | QPDFObjGen const& og = iter.first; |
1099 | 0 | QPDFXRefEntry const& entry = iter.second; |
1100 | 0 | cout << og.unparse('/') << ": "; |
1101 | 0 | switch (entry.getType()) { |
1102 | 0 | case 1: |
1103 | 0 | cout << "uncompressed; offset = " << entry.getOffset(); |
1104 | 0 | break; |
1105 | | |
1106 | 0 | case 2: |
1107 | 0 | *m->log->getInfo() << "compressed; stream = " << entry.getObjStreamNumber() |
1108 | 0 | << ", index = " << entry.getObjStreamIndex(); |
1109 | 0 | break; |
1110 | | |
1111 | 0 | default: |
1112 | 0 | throw std::logic_error("unknown cross-reference table type while showing xref_table"); |
1113 | 0 | break; |
1114 | 0 | } |
1115 | 0 | m->log->info("\n"); |
1116 | 0 | } |
1117 | 0 | } |
1118 | | |
1119 | | // Resolve all objects in the xref table. If this triggers a xref table reconstruction abort and |
1120 | | // return false. Otherwise return true. |
1121 | | bool |
1122 | | QPDF::resolveXRefTable() |
1123 | 0 | { |
1124 | 0 | bool may_change = !m->reconstructed_xref; |
1125 | 0 | for (auto& iter: m->xref_table) { |
1126 | 0 | if (isUnresolved(iter.first)) { |
1127 | 0 | resolve(iter.first); |
1128 | 0 | if (may_change && m->reconstructed_xref) { |
1129 | 0 | return false; |
1130 | 0 | } |
1131 | 0 | } |
1132 | 0 | } |
1133 | 0 | return true; |
1134 | 0 | } |
1135 | | |
1136 | | // Ensure all objects in the pdf file, including those in indirect references, appear in the object |
1137 | | // cache. |
1138 | | void |
1139 | | QPDF::fixDanglingReferences(bool force) |
1140 | 0 | { |
1141 | 0 | if (m->fixed_dangling_refs) { |
1142 | 0 | return; |
1143 | 0 | } |
1144 | 0 | if (!resolveXRefTable()) { |
1145 | 0 | QTC::TC("qpdf", "QPDF fix dangling triggered xref reconstruction"); |
1146 | 0 | resolveXRefTable(); |
1147 | 0 | } |
1148 | 0 | m->fixed_dangling_refs = true; |
1149 | 0 | } |
1150 | | |
1151 | | size_t |
1152 | | QPDF::getObjectCount() |
1153 | 0 | { |
1154 | | // This method returns the next available indirect object number. makeIndirectObject uses it for |
1155 | | // this purpose. After fixDanglingReferences is called, all objects in the xref table will also |
1156 | | // be in obj_cache. |
1157 | 0 | fixDanglingReferences(); |
1158 | 0 | QPDFObjGen og; |
1159 | 0 | if (!m->obj_cache.empty()) { |
1160 | 0 | og = (*(m->obj_cache.rbegin())).first; |
1161 | 0 | } |
1162 | 0 | return toS(og.getObj()); |
1163 | 0 | } |
1164 | | |
1165 | | std::vector<QPDFObjectHandle> |
1166 | | QPDF::getAllObjects() |
1167 | 0 | { |
1168 | | // After fixDanglingReferences is called, all objects are in the object cache. |
1169 | 0 | fixDanglingReferences(); |
1170 | 0 | std::vector<QPDFObjectHandle> result; |
1171 | 0 | for (auto const& iter: m->obj_cache) { |
1172 | 0 | result.push_back(newIndirect(iter.first, iter.second.object)); |
1173 | 0 | } |
1174 | 0 | return result; |
1175 | 0 | } |
1176 | | |
1177 | | void |
1178 | | QPDF::setLastObjectDescription(std::string const& description, QPDFObjGen og) |
1179 | 0 | { |
1180 | 0 | m->last_object_description.clear(); |
1181 | 0 | if (!description.empty()) { |
1182 | 0 | m->last_object_description += description; |
1183 | 0 | if (og.isIndirect()) { |
1184 | 0 | m->last_object_description += ": "; |
1185 | 0 | } |
1186 | 0 | } |
1187 | 0 | if (og.isIndirect()) { |
1188 | 0 | m->last_object_description += "object " + og.unparse(' '); |
1189 | 0 | } |
1190 | 0 | } |
1191 | | |
1192 | | QPDFObjectHandle |
1193 | | QPDF::readTrailer() |
1194 | 7.52k | { |
1195 | 7.52k | qpdf_offset_t offset = m->file->tell(); |
1196 | 7.52k | auto [object, empty] = |
1197 | 7.52k | QPDFParser::parse(*m->file, "trailer", m->tokenizer, nullptr, *this, m->reconstructed_xref); |
1198 | 7.52k | if (empty) { |
1199 | | // Nothing in the PDF spec appears to allow empty objects, but they have been encountered in |
1200 | | // actual PDF files and Adobe Reader appears to ignore them. |
1201 | 0 | warn(damagedPDF("trailer", "empty object treated as null")); |
1202 | 7.52k | } else if (object.isDictionary() && readToken(*m->file).isWord("stream")) { |
1203 | 0 | warn(damagedPDF("trailer", m->file->tell(), "stream keyword found in trailer")); |
1204 | 0 | } |
1205 | | // Override last_offset so that it points to the beginning of the object we just read |
1206 | 7.52k | m->file->setLastOffset(offset); |
1207 | 7.52k | return object; |
1208 | 7.52k | } |
1209 | | |
1210 | | QPDFObjectHandle |
1211 | | QPDF::readObject(std::string const& description, QPDFObjGen og) |
1212 | 0 | { |
1213 | 0 | setLastObjectDescription(description, og); |
1214 | 0 | qpdf_offset_t offset = m->file->tell(); |
1215 | |
|
1216 | 0 | StringDecrypter decrypter{this, og}; |
1217 | 0 | StringDecrypter* decrypter_ptr = m->encp->encrypted ? &decrypter : nullptr; |
1218 | 0 | auto [object, empty] = QPDFParser::parse( |
1219 | 0 | *m->file, |
1220 | 0 | m->last_object_description, |
1221 | 0 | m->tokenizer, |
1222 | 0 | decrypter_ptr, |
1223 | 0 | *this, |
1224 | 0 | m->reconstructed_xref || m->in_read_xref_stream); |
1225 | 0 | ; |
1226 | 0 | if (empty) { |
1227 | | // Nothing in the PDF spec appears to allow empty objects, but they have been encountered in |
1228 | | // actual PDF files and Adobe Reader appears to ignore them. |
1229 | 0 | warn(damagedPDF(*m->file, m->file->getLastOffset(), "empty object treated as null")); |
1230 | 0 | return object; |
1231 | 0 | } |
1232 | 0 | auto token = readToken(*m->file); |
1233 | 0 | if (object.isDictionary() && token.isWord("stream")) { |
1234 | 0 | readStream(object, og, offset); |
1235 | 0 | token = readToken(*m->file); |
1236 | 0 | } |
1237 | 0 | if (!token.isWord("endobj")) { |
1238 | 0 | QTC::TC("qpdf", "QPDF err expected endobj"); |
1239 | 0 | warn(damagedPDF("expected endobj")); |
1240 | 0 | } |
1241 | 0 | return object; |
1242 | 0 | } |
1243 | | |
1244 | | // After reading stream dictionary and stream keyword, read rest of stream. |
1245 | | void |
1246 | | QPDF::readStream(QPDFObjectHandle& object, QPDFObjGen og, qpdf_offset_t offset) |
1247 | 0 | { |
1248 | 0 | validateStreamLineEnd(object, og, offset); |
1249 | | |
1250 | | // Must get offset before accessing any additional objects since resolving a previously |
1251 | | // unresolved indirect object will change file position. |
1252 | 0 | qpdf_offset_t stream_offset = m->file->tell(); |
1253 | 0 | size_t length = 0; |
1254 | |
|
1255 | 0 | try { |
1256 | 0 | auto length_obj = object.getKey("/Length"); |
1257 | |
|
1258 | 0 | if (!length_obj.isInteger()) { |
1259 | 0 | if (length_obj.isNull()) { |
1260 | 0 | QTC::TC("qpdf", "QPDF stream without length"); |
1261 | 0 | throw damagedPDF(offset, "stream dictionary lacks /Length key"); |
1262 | 0 | } |
1263 | 0 | QTC::TC("qpdf", "QPDF stream length not integer"); |
1264 | 0 | throw damagedPDF(offset, "/Length key in stream dictionary is not an integer"); |
1265 | 0 | } |
1266 | | |
1267 | 0 | length = toS(length_obj.getUIntValue()); |
1268 | | // Seek in two steps to avoid potential integer overflow |
1269 | 0 | m->file->seek(stream_offset, SEEK_SET); |
1270 | 0 | m->file->seek(toO(length), SEEK_CUR); |
1271 | 0 | if (!readToken(*m->file).isWord("endstream")) { |
1272 | 0 | QTC::TC("qpdf", "QPDF missing endstream"); |
1273 | 0 | throw damagedPDF("expected endstream"); |
1274 | 0 | } |
1275 | 0 | } catch (QPDFExc& e) { |
1276 | 0 | if (m->attempt_recovery) { |
1277 | 0 | warn(e); |
1278 | 0 | length = recoverStreamLength(m->file, og, stream_offset); |
1279 | 0 | } else { |
1280 | 0 | throw; |
1281 | 0 | } |
1282 | 0 | } |
1283 | 0 | object = QPDFObjectHandle(qpdf::Stream(*this, og, object, stream_offset, length)); |
1284 | 0 | } |
1285 | | |
1286 | | void |
1287 | | QPDF::validateStreamLineEnd(QPDFObjectHandle& object, QPDFObjGen og, qpdf_offset_t offset) |
1288 | 0 | { |
1289 | | // The PDF specification states that the word "stream" should be followed by either a carriage |
1290 | | // return and a newline or by a newline alone. It specifically disallowed following it by a |
1291 | | // carriage return alone since, in that case, there would be no way to tell whether the NL in a |
1292 | | // CR NL sequence was part of the stream data. However, some readers, including Adobe reader, |
1293 | | // accept a carriage return by itself when followed by a non-newline character, so that's what |
1294 | | // we do here. We have also seen files that have extraneous whitespace between the stream |
1295 | | // keyword and the newline. |
1296 | 0 | while (true) { |
1297 | 0 | char ch; |
1298 | 0 | if (m->file->read(&ch, 1) == 0) { |
1299 | | // A premature EOF here will result in some other problem that will get reported at |
1300 | | // another time. |
1301 | 0 | return; |
1302 | 0 | } |
1303 | 0 | if (ch == '\n') { |
1304 | | // ready to read stream data |
1305 | 0 | QTC::TC("qpdf", "QPDF stream with NL only"); |
1306 | 0 | return; |
1307 | 0 | } |
1308 | 0 | if (ch == '\r') { |
1309 | | // Read another character |
1310 | 0 | if (m->file->read(&ch, 1) != 0) { |
1311 | 0 | if (ch == '\n') { |
1312 | | // Ready to read stream data |
1313 | 0 | QTC::TC("qpdf", "QPDF stream with CRNL"); |
1314 | 0 | } else { |
1315 | | // Treat the \r by itself as the whitespace after endstream and start reading |
1316 | | // stream data in spite of not having seen a newline. |
1317 | 0 | QTC::TC("qpdf", "QPDF stream with CR only"); |
1318 | 0 | m->file->unreadCh(ch); |
1319 | 0 | warn(damagedPDF( |
1320 | 0 | m->file->tell(), "stream keyword followed by carriage return only")); |
1321 | 0 | } |
1322 | 0 | } |
1323 | 0 | return; |
1324 | 0 | } |
1325 | 0 | if (!util::is_space(ch)) { |
1326 | 0 | QTC::TC("qpdf", "QPDF stream without newline"); |
1327 | 0 | m->file->unreadCh(ch); |
1328 | 0 | warn(damagedPDF( |
1329 | 0 | m->file->tell(), "stream keyword not followed by proper line terminator")); |
1330 | 0 | return; |
1331 | 0 | } |
1332 | 0 | warn(damagedPDF(m->file->tell(), "stream keyword followed by extraneous whitespace")); |
1333 | 0 | } |
1334 | 0 | } |
1335 | | |
1336 | | QPDFObjectHandle |
1337 | | QPDF::readObjectInStream(is::OffsetBuffer& input, int stream_id, int obj_id) |
1338 | 0 | { |
1339 | 0 | auto [object, empty] = QPDFParser::parse(input, stream_id, obj_id, m->tokenizer, *this); |
1340 | 0 | if (empty) { |
1341 | | // Nothing in the PDF spec appears to allow empty objects, but they have been encountered in |
1342 | | // actual PDF files and Adobe Reader appears to ignore them. |
1343 | 0 | warn(QPDFExc( |
1344 | 0 | qpdf_e_damaged_pdf, |
1345 | 0 | m->file->getName() + " object stream " + std::to_string(stream_id), |
1346 | 0 | +"object " + std::to_string(obj_id) + " 0, offset " + |
1347 | 0 | std::to_string(input.getLastOffset()), |
1348 | 0 | 0, |
1349 | 0 | "empty object treated as null")); |
1350 | 0 | } |
1351 | 0 | return object; |
1352 | 0 | } |
1353 | | |
1354 | | bool |
1355 | | QPDF::findEndstream() |
1356 | 0 | { |
1357 | | // Find endstream or endobj. Position the input at that token. |
1358 | 0 | auto t = readToken(*m->file, 20); |
1359 | 0 | if (t.isWord("endobj") || t.isWord("endstream")) { |
1360 | 0 | m->file->seek(m->file->getLastOffset(), SEEK_SET); |
1361 | 0 | return true; |
1362 | 0 | } |
1363 | 0 | return false; |
1364 | 0 | } |
1365 | | |
1366 | | size_t |
1367 | | QPDF::recoverStreamLength( |
1368 | | std::shared_ptr<InputSource> input, QPDFObjGen og, qpdf_offset_t stream_offset) |
1369 | 0 | { |
1370 | | // Try to reconstruct stream length by looking for endstream or endobj |
1371 | 0 | warn(damagedPDF(*input, stream_offset, "attempting to recover stream length")); |
1372 | |
|
1373 | 0 | PatternFinder ef(*this, &QPDF::findEndstream); |
1374 | 0 | size_t length = 0; |
1375 | 0 | if (m->file->findFirst("end", stream_offset, 0, ef)) { |
1376 | 0 | length = toS(m->file->tell() - stream_offset); |
1377 | | // Reread endstream but, if it was endobj, don't skip that. |
1378 | 0 | QPDFTokenizer::Token t = readToken(*m->file); |
1379 | 0 | if (t.getValue() == "endobj") { |
1380 | 0 | m->file->seek(m->file->getLastOffset(), SEEK_SET); |
1381 | 0 | } |
1382 | 0 | } |
1383 | |
|
1384 | 0 | if (length) { |
1385 | 0 | auto end = stream_offset + toO(length); |
1386 | 0 | qpdf_offset_t found_offset = 0; |
1387 | 0 | QPDFObjGen found_og; |
1388 | | |
1389 | | // Make sure this is inside this object |
1390 | 0 | for (auto const& [current_og, entry]: m->xref_table) { |
1391 | 0 | if (entry.getType() == 1) { |
1392 | 0 | qpdf_offset_t obj_offset = entry.getOffset(); |
1393 | 0 | if (found_offset < obj_offset && obj_offset < end) { |
1394 | 0 | found_offset = obj_offset; |
1395 | 0 | found_og = current_og; |
1396 | 0 | } |
1397 | 0 | } |
1398 | 0 | } |
1399 | 0 | if (!found_offset || found_og == og) { |
1400 | | // If we are trying to recover an XRef stream the xref table will not contain and |
1401 | | // won't contain any entries, therefore we cannot check the found length. Otherwise we |
1402 | | // found endstream\nendobj within the space allowed for this object, so we're probably |
1403 | | // in good shape. |
1404 | 0 | } else { |
1405 | 0 | QTC::TC("qpdf", "QPDF found wrong endstream in recovery"); |
1406 | 0 | length = 0; |
1407 | 0 | } |
1408 | 0 | } |
1409 | |
|
1410 | 0 | if (length == 0) { |
1411 | 0 | warn(damagedPDF( |
1412 | 0 | *input, stream_offset, "unable to recover stream data; treating stream as empty")); |
1413 | 0 | } else { |
1414 | 0 | warn(damagedPDF( |
1415 | 0 | *input, stream_offset, "recovered stream length: " + std::to_string(length))); |
1416 | 0 | } |
1417 | |
|
1418 | 0 | QTC::TC("qpdf", "QPDF recovered stream length"); |
1419 | 0 | return length; |
1420 | 0 | } |
1421 | | |
1422 | | QPDFTokenizer::Token |
1423 | | QPDF::readToken(InputSource& input, size_t max_len) |
1424 | 37.6k | { |
1425 | 37.6k | return m->tokenizer.readToken(input, m->last_object_description, true, max_len); |
1426 | 37.6k | } |
1427 | | |
1428 | | QPDFObjGen |
1429 | | QPDF::read_object_start(qpdf_offset_t offset) |
1430 | 0 | { |
1431 | 0 | m->file->seek(offset, SEEK_SET); |
1432 | 0 | QPDFTokenizer::Token tobjid = readToken(*m->file); |
1433 | 0 | bool objidok = tobjid.isInteger(); |
1434 | 0 | QTC::TC("qpdf", "QPDF check objid", objidok ? 1 : 0); |
1435 | 0 | if (!objidok) { |
1436 | 0 | QTC::TC("qpdf", "QPDF expected n n obj"); |
1437 | 0 | throw damagedPDF(offset, "expected n n obj"); |
1438 | 0 | } |
1439 | 0 | QPDFTokenizer::Token tgen = readToken(*m->file); |
1440 | 0 | bool genok = tgen.isInteger(); |
1441 | 0 | QTC::TC("qpdf", "QPDF check generation", genok ? 1 : 0); |
1442 | 0 | if (!genok) { |
1443 | 0 | throw damagedPDF(offset, "expected n n obj"); |
1444 | 0 | } |
1445 | 0 | QPDFTokenizer::Token tobj = readToken(*m->file); |
1446 | |
|
1447 | 0 | bool objok = tobj.isWord("obj"); |
1448 | 0 | QTC::TC("qpdf", "QPDF check obj", objok ? 1 : 0); |
1449 | |
|
1450 | 0 | if (!objok) { |
1451 | 0 | throw damagedPDF(offset, "expected n n obj"); |
1452 | 0 | } |
1453 | 0 | int objid = QUtil::string_to_int(tobjid.getValue().c_str()); |
1454 | 0 | int generation = QUtil::string_to_int(tgen.getValue().c_str()); |
1455 | 0 | if (objid == 0) { |
1456 | 0 | QTC::TC("qpdf", "QPDF object id 0"); |
1457 | 0 | throw damagedPDF(offset, "object with ID 0"); |
1458 | 0 | } |
1459 | 0 | return {objid, generation}; |
1460 | 0 | } |
1461 | | |
1462 | | void |
1463 | | QPDF::readObjectAtOffset( |
1464 | | bool try_recovery, qpdf_offset_t offset, std::string const& description, QPDFObjGen exp_og) |
1465 | 0 | { |
1466 | 0 | QPDFObjGen og; |
1467 | 0 | setLastObjectDescription(description, exp_og); |
1468 | |
|
1469 | 0 | if (!m->attempt_recovery) { |
1470 | 0 | try_recovery = false; |
1471 | 0 | } |
1472 | | |
1473 | | // Special case: if offset is 0, just return null. Some PDF writers, in particular |
1474 | | // "Mac OS X 10.7.5 Quartz PDFContext", may store deleted objects in the xref table as |
1475 | | // "0000000000 00000 n", which is not correct, but it won't hurt anything for us to ignore |
1476 | | // these. |
1477 | 0 | if (offset == 0) { |
1478 | 0 | QTC::TC("qpdf", "QPDF bogus 0 offset", 0); |
1479 | 0 | warn(damagedPDF(-1, "object has offset 0")); |
1480 | 0 | return; |
1481 | 0 | } |
1482 | | |
1483 | 0 | try { |
1484 | 0 | og = read_object_start(offset); |
1485 | 0 | if (exp_og != og) { |
1486 | 0 | QTC::TC("qpdf", "QPDF err wrong objid/generation"); |
1487 | 0 | QPDFExc e = damagedPDF(offset, "expected " + exp_og.unparse(' ') + " obj"); |
1488 | 0 | if (try_recovery) { |
1489 | | // Will be retried below |
1490 | 0 | throw e; |
1491 | 0 | } else { |
1492 | | // We can try reading the object anyway even if the ID doesn't match. |
1493 | 0 | warn(e); |
1494 | 0 | } |
1495 | 0 | } |
1496 | 0 | } catch (QPDFExc& e) { |
1497 | 0 | if (!try_recovery) { |
1498 | 0 | throw; |
1499 | 0 | } |
1500 | | // Try again after reconstructing xref table |
1501 | 0 | reconstruct_xref(e); |
1502 | 0 | if (m->xref_table.contains(exp_og) && m->xref_table[exp_og].getType() == 1) { |
1503 | 0 | qpdf_offset_t new_offset = m->xref_table[exp_og].getOffset(); |
1504 | 0 | readObjectAtOffset(false, new_offset, description, exp_og); |
1505 | 0 | QTC::TC("qpdf", "QPDF recovered in readObjectAtOffset"); |
1506 | 0 | return; |
1507 | 0 | } |
1508 | 0 | QTC::TC("qpdf", "QPDF object gone after xref reconstruction"); |
1509 | 0 | warn(damagedPDF( |
1510 | 0 | "", |
1511 | 0 | -1, |
1512 | 0 | ("object " + exp_og.unparse(' ') + |
1513 | 0 | " not found in file after regenerating cross reference table"))); |
1514 | 0 | return; |
1515 | 0 | } |
1516 | | |
1517 | 0 | QPDFObjectHandle oh = readObject(description, og); |
1518 | | |
1519 | | // Determine the end offset of this object before and after white space. We use these |
1520 | | // numbers to validate linearization hint tables. Offsets and lengths of objects may imply |
1521 | | // the end of an object to be anywhere between these values. |
1522 | 0 | qpdf_offset_t end_before_space = m->file->tell(); |
1523 | | |
1524 | | // skip over spaces |
1525 | 0 | while (true) { |
1526 | 0 | char ch; |
1527 | 0 | if (!m->file->read(&ch, 1)) { |
1528 | 0 | throw damagedPDF(m->file->tell(), "EOF after endobj"); |
1529 | 0 | } |
1530 | 0 | if (!isspace(static_cast<unsigned char>(ch))) { |
1531 | 0 | m->file->seek(-1, SEEK_CUR); |
1532 | 0 | break; |
1533 | 0 | } |
1534 | 0 | } |
1535 | 0 | updateCache(og, oh.getObj(), end_before_space, m->file->tell()); |
1536 | 0 | } |
1537 | | |
1538 | | QPDFObjectHandle |
1539 | | QPDF::readObjectAtOffset( |
1540 | | qpdf_offset_t offset, std::string const& description, bool skip_cache_if_in_xref) |
1541 | 0 | { |
1542 | 0 | auto og = read_object_start(offset); |
1543 | 0 | auto oh = readObject(description, og); |
1544 | |
|
1545 | 0 | if (!isUnresolved(og)) { |
1546 | 0 | return oh; |
1547 | 0 | } |
1548 | | |
1549 | 0 | if (skip_cache_if_in_xref && m->xref_table.contains(og)) { |
1550 | | // In the special case of the xref stream and linearization hint tables, the offset comes |
1551 | | // from another source. For the specific case of xref streams, the xref stream is read and |
1552 | | // loaded into the object cache very early in parsing. Ordinarily, when a file is updated by |
1553 | | // appending, items inserted into the xref table in later updates take precedence over |
1554 | | // earlier items. In the special case of reusing the object number previously used as the |
1555 | | // xref stream, we have the following order of events: |
1556 | | // |
1557 | | // * reused object gets loaded into the xref table |
1558 | | // * old object is read here while reading xref streams |
1559 | | // * original xref entry is ignored (since already in xref table) |
1560 | | // |
1561 | | // It is the second step that causes a problem. Even though the xref table is correct in |
1562 | | // this case, the old object is already in the cache and so effectively prevails over the |
1563 | | // reused object. To work around this issue, we have a special case for the xref stream (via |
1564 | | // the skip_cache_if_in_xref): if the object is already in the xref stream, don't cache what |
1565 | | // we read here. |
1566 | | // |
1567 | | // It is likely that the same bug may exist for linearization hint tables, but the existing |
1568 | | // code uses end_before_space and end_after_space from the cache, so fixing that would |
1569 | | // require more significant rework. The chances of a linearization hint stream being reused |
1570 | | // seems smaller because the xref stream is probably the highest object in the file and the |
1571 | | // linearization hint stream would be some random place in the middle, so I'm leaving that |
1572 | | // bug unfixed for now. If the bug were to be fixed, we could use !check_og in place of |
1573 | | // skip_cache_if_in_xref. |
1574 | 0 | QTC::TC("qpdf", "QPDF skipping cache for known unchecked object"); |
1575 | 0 | return oh; |
1576 | 0 | } |
1577 | | |
1578 | | // Determine the end offset of this object before and after white space. We use these |
1579 | | // numbers to validate linearization hint tables. Offsets and lengths of objects may imply |
1580 | | // the end of an object to be anywhere between these values. |
1581 | 0 | qpdf_offset_t end_before_space = m->file->tell(); |
1582 | | |
1583 | | // skip over spaces |
1584 | 0 | while (true) { |
1585 | 0 | char ch; |
1586 | 0 | if (!m->file->read(&ch, 1)) { |
1587 | 0 | throw damagedPDF(m->file->tell(), "EOF after endobj"); |
1588 | 0 | } |
1589 | 0 | if (!isspace(static_cast<unsigned char>(ch))) { |
1590 | 0 | m->file->seek(-1, SEEK_CUR); |
1591 | 0 | break; |
1592 | 0 | } |
1593 | 0 | } |
1594 | 0 | updateCache(og, oh.getObj(), end_before_space, m->file->tell()); |
1595 | |
|
1596 | 0 | return oh; |
1597 | 0 | } |
1598 | | |
1599 | | std::shared_ptr<QPDFObject> const& |
1600 | | QPDF::resolve(QPDFObjGen og) |
1601 | 0 | { |
1602 | 0 | if (!isUnresolved(og)) { |
1603 | 0 | return m->obj_cache[og].object; |
1604 | 0 | } |
1605 | | |
1606 | 0 | if (m->resolving.contains(og)) { |
1607 | | // This can happen if an object references itself directly or indirectly in some key that |
1608 | | // has to be resolved during object parsing, such as stream length. |
1609 | 0 | QTC::TC("qpdf", "QPDF recursion loop in resolve"); |
1610 | 0 | warn(damagedPDF("", "loop detected resolving object " + og.unparse(' '))); |
1611 | 0 | updateCache(og, QPDFObject::create<QPDF_Null>(), -1, -1); |
1612 | 0 | return m->obj_cache[og].object; |
1613 | 0 | } |
1614 | 0 | ResolveRecorder rr(*this, og); |
1615 | |
|
1616 | 0 | if (m->xref_table.contains(og)) { |
1617 | 0 | QPDFXRefEntry const& entry = m->xref_table[og]; |
1618 | 0 | try { |
1619 | 0 | switch (entry.getType()) { |
1620 | 0 | case 1: |
1621 | | // Object stored in cache by readObjectAtOffset |
1622 | 0 | readObjectAtOffset(true, entry.getOffset(), "", og); |
1623 | 0 | break; |
1624 | | |
1625 | 0 | case 2: |
1626 | 0 | resolveObjectsInStream(entry.getObjStreamNumber()); |
1627 | 0 | break; |
1628 | | |
1629 | 0 | default: |
1630 | 0 | throw damagedPDF( |
1631 | 0 | "", -1, ("object " + og.unparse('/') + " has unexpected xref entry type")); |
1632 | 0 | } |
1633 | 0 | } catch (QPDFExc& e) { |
1634 | 0 | warn(e); |
1635 | 0 | } catch (std::exception& e) { |
1636 | 0 | warn(damagedPDF( |
1637 | 0 | "", -1, ("object " + og.unparse('/') + ": error reading object: " + e.what()))); |
1638 | 0 | } |
1639 | 0 | } |
1640 | | |
1641 | 0 | if (isUnresolved(og)) { |
1642 | | // PDF spec says unknown objects resolve to the null object. |
1643 | 0 | QTC::TC("qpdf", "QPDF resolve failure to null"); |
1644 | 0 | updateCache(og, QPDFObject::create<QPDF_Null>(), -1, -1); |
1645 | 0 | } |
1646 | |
|
1647 | 0 | auto& result(m->obj_cache[og].object); |
1648 | 0 | result->setDefaultDescription(this, og); |
1649 | 0 | return result; |
1650 | 0 | } |
1651 | | |
1652 | | void |
1653 | | QPDF::resolveObjectsInStream(int obj_stream_number) |
1654 | 0 | { |
1655 | 0 | auto damaged = |
1656 | 0 | [this, obj_stream_number](int id, qpdf_offset_t offset, std::string const& msg) -> QPDFExc { |
1657 | 0 | return { |
1658 | 0 | qpdf_e_damaged_pdf, |
1659 | 0 | m->file->getName() + " object stream " + std::to_string(obj_stream_number), |
1660 | 0 | +"object " + std::to_string(id) + " 0", |
1661 | 0 | offset, |
1662 | 0 | msg, |
1663 | 0 | true}; |
1664 | 0 | }; |
1665 | |
|
1666 | 0 | if (m->resolved_object_streams.contains(obj_stream_number)) { |
1667 | 0 | return; |
1668 | 0 | } |
1669 | 0 | m->resolved_object_streams.insert(obj_stream_number); |
1670 | | // Force resolution of object stream |
1671 | 0 | auto obj_stream = getObject(obj_stream_number, 0).as_stream(); |
1672 | 0 | if (!obj_stream) { |
1673 | 0 | throw damagedPDF( |
1674 | 0 | "object " + std::to_string(obj_stream_number) + " 0", |
1675 | 0 | "supposed object stream " + std::to_string(obj_stream_number) + " is not a stream"); |
1676 | 0 | } |
1677 | | |
1678 | | // For linearization data in the object, use the data from the object stream for the objects in |
1679 | | // the stream. |
1680 | 0 | QPDFObjGen stream_og(obj_stream_number, 0); |
1681 | 0 | qpdf_offset_t end_before_space = m->obj_cache[stream_og].end_before_space; |
1682 | 0 | qpdf_offset_t end_after_space = m->obj_cache[stream_og].end_after_space; |
1683 | |
|
1684 | 0 | QPDFObjectHandle dict = obj_stream.getDict(); |
1685 | 0 | if (!dict.isDictionaryOfType("/ObjStm")) { |
1686 | 0 | QTC::TC("qpdf", "QPDF ERR object stream with wrong type"); |
1687 | 0 | warn(damagedPDF( |
1688 | 0 | "object " + std::to_string(obj_stream_number) + " 0", |
1689 | 0 | "supposed object stream " + std::to_string(obj_stream_number) + " has wrong type")); |
1690 | 0 | } |
1691 | |
|
1692 | 0 | unsigned int n{0}; |
1693 | 0 | int first{0}; |
1694 | 0 | if (!(dict.getKey("/N").getValueAsUInt(n) && dict.getKey("/First").getValueAsInt(first))) { |
1695 | 0 | throw damagedPDF( |
1696 | 0 | "object " + std::to_string(obj_stream_number) + " 0", |
1697 | 0 | "object stream " + std::to_string(obj_stream_number) + " has incorrect keys"); |
1698 | 0 | } |
1699 | | |
1700 | | // id, offset, size |
1701 | 0 | std::vector<std::tuple<int, qpdf_offset_t, size_t>> offsets; |
1702 | |
|
1703 | 0 | auto stream_data = obj_stream.getStreamData(qpdf_dl_specialized); |
1704 | |
|
1705 | 0 | is::OffsetBuffer input("", stream_data); |
1706 | |
|
1707 | 0 | const auto b_size = stream_data.size(); |
1708 | 0 | const auto end_offset = static_cast<qpdf_offset_t>(b_size); |
1709 | 0 | auto b_start = stream_data.data(); |
1710 | |
|
1711 | 0 | if (first >= end_offset) { |
1712 | 0 | throw damagedPDF( |
1713 | 0 | "object " + std::to_string(obj_stream_number) + " 0", |
1714 | 0 | "object stream " + std::to_string(obj_stream_number) + " has invalid /First entry"); |
1715 | 0 | } |
1716 | | |
1717 | 0 | int id = 0; |
1718 | 0 | long long last_offset = -1; |
1719 | 0 | bool is_first = true; |
1720 | 0 | for (unsigned int i = 0; i < n; ++i) { |
1721 | 0 | auto tnum = readToken(input); |
1722 | 0 | auto id_offset = input.getLastOffset(); |
1723 | 0 | auto toffset = readToken(input); |
1724 | 0 | if (!(tnum.isInteger() && toffset.isInteger())) { |
1725 | 0 | throw damaged(0, input.getLastOffset(), "expected integer in object stream header"); |
1726 | 0 | } |
1727 | | |
1728 | 0 | int num = QUtil::string_to_int(tnum.getValue().c_str()); |
1729 | 0 | long long offset = QUtil::string_to_int(toffset.getValue().c_str()); |
1730 | |
|
1731 | 0 | if (num == obj_stream_number) { |
1732 | 0 | QTC::TC("qpdf", "QPDF ignore self-referential object stream"); |
1733 | 0 | warn(damaged(num, id_offset, "object stream claims to contain itself")); |
1734 | 0 | continue; |
1735 | 0 | } |
1736 | | |
1737 | 0 | if (num < 1) { |
1738 | 0 | QTC::TC("qpdf", "QPDF object stream contains id < 1"); |
1739 | 0 | warn(damaged(num, id_offset, "object id is invalid"s)); |
1740 | 0 | continue; |
1741 | 0 | } |
1742 | | |
1743 | 0 | if (offset <= last_offset) { |
1744 | 0 | QTC::TC("qpdf", "QPDF object stream offsets not increasing"); |
1745 | 0 | warn(damaged( |
1746 | 0 | num, |
1747 | 0 | input.getLastOffset(), |
1748 | 0 | "offset " + std::to_string(offset) + |
1749 | 0 | " is invalid (must be larger than previous offset " + |
1750 | 0 | std::to_string(last_offset) + ")")); |
1751 | 0 | continue; |
1752 | 0 | } |
1753 | | |
1754 | 0 | if (num > m->xref_table_max_id) { |
1755 | 0 | continue; |
1756 | 0 | } |
1757 | | |
1758 | 0 | if (first + offset >= end_offset) { |
1759 | 0 | warn(damaged( |
1760 | 0 | num, input.getLastOffset(), "offset " + std::to_string(offset) + " is too large")); |
1761 | 0 | continue; |
1762 | 0 | } |
1763 | | |
1764 | 0 | if (is_first) { |
1765 | 0 | is_first = false; |
1766 | 0 | } else { |
1767 | 0 | offsets.emplace_back( |
1768 | 0 | id, last_offset + first, static_cast<size_t>(offset - last_offset)); |
1769 | 0 | } |
1770 | |
|
1771 | 0 | last_offset = offset; |
1772 | 0 | id = num; |
1773 | 0 | } |
1774 | | |
1775 | 0 | if (!is_first) { |
1776 | | // We found at least one valid entry. |
1777 | 0 | offsets.emplace_back( |
1778 | 0 | id, last_offset + first, b_size - static_cast<size_t>(last_offset + first)); |
1779 | 0 | } |
1780 | | |
1781 | | // To avoid having to read the object stream multiple times, store all objects that would be |
1782 | | // found here in the cache. Remember that some objects stored here might have been overridden |
1783 | | // by new objects appended to the file, so it is necessary to recheck the xref table and only |
1784 | | // cache what would actually be resolved here. |
1785 | 0 | for (auto const& [obj_id, obj_offset, obj_size]: offsets) { |
1786 | 0 | QPDFObjGen og(obj_id, 0); |
1787 | 0 | auto entry = m->xref_table.find(og); |
1788 | 0 | if (entry != m->xref_table.end() && entry->second.getType() == 2 && |
1789 | 0 | entry->second.getObjStreamNumber() == obj_stream_number) { |
1790 | 0 | is::OffsetBuffer in("", {b_start + obj_offset, obj_size}, obj_offset); |
1791 | 0 | auto oh = readObjectInStream(in, obj_stream_number, obj_id); |
1792 | 0 | updateCache(og, oh.getObj(), end_before_space, end_after_space); |
1793 | 0 | } else { |
1794 | 0 | QTC::TC("qpdf", "QPDF not caching overridden objstm object"); |
1795 | 0 | } |
1796 | 0 | } |
1797 | 0 | } |
1798 | | |
1799 | | QPDFObjectHandle |
1800 | | QPDF::newIndirect(QPDFObjGen og, std::shared_ptr<QPDFObject> const& obj) |
1801 | 0 | { |
1802 | 0 | obj->setDefaultDescription(this, og); |
1803 | 0 | return {obj}; |
1804 | 0 | } |
1805 | | |
1806 | | void |
1807 | | QPDF::updateCache( |
1808 | | QPDFObjGen og, |
1809 | | std::shared_ptr<QPDFObject> const& object, |
1810 | | qpdf_offset_t end_before_space, |
1811 | | qpdf_offset_t end_after_space, |
1812 | | bool destroy) |
1813 | 19.9k | { |
1814 | 19.9k | object->setObjGen(this, og); |
1815 | 19.9k | if (isCached(og)) { |
1816 | 19.9k | auto& cache = m->obj_cache[og]; |
1817 | 19.9k | object->move_to(cache.object, destroy); |
1818 | 19.9k | cache.end_before_space = end_before_space; |
1819 | 19.9k | cache.end_after_space = end_after_space; |
1820 | 19.9k | } else { |
1821 | 0 | m->obj_cache[og] = ObjCache(object, end_before_space, end_after_space); |
1822 | 0 | } |
1823 | 19.9k | } |
1824 | | |
1825 | | bool |
1826 | | QPDF::isCached(QPDFObjGen og) |
1827 | 19.9k | { |
1828 | 19.9k | return m->obj_cache.contains(og); |
1829 | 19.9k | } |
1830 | | |
1831 | | bool |
1832 | | QPDF::isUnresolved(QPDFObjGen og) |
1833 | 0 | { |
1834 | 0 | return !isCached(og) || m->obj_cache[og].object->isUnresolved(); |
1835 | 0 | } |
1836 | | |
1837 | | QPDFObjGen |
1838 | | QPDF::nextObjGen() |
1839 | 0 | { |
1840 | 0 | int max_objid = toI(getObjectCount()); |
1841 | 0 | if (max_objid == std::numeric_limits<int>::max()) { |
1842 | 0 | throw std::range_error("max object id is too high to create new objects"); |
1843 | 0 | } |
1844 | 0 | return {max_objid + 1, 0}; |
1845 | 0 | } |
1846 | | |
1847 | | QPDFObjectHandle |
1848 | | QPDF::makeIndirectFromQPDFObject(std::shared_ptr<QPDFObject> const& obj) |
1849 | 0 | { |
1850 | 0 | QPDFObjGen next{nextObjGen()}; |
1851 | 0 | m->obj_cache[next] = ObjCache(obj, -1, -1); |
1852 | 0 | return newIndirect(next, m->obj_cache[next].object); |
1853 | 0 | } |
1854 | | |
1855 | | QPDFObjectHandle |
1856 | | QPDF::makeIndirectObject(QPDFObjectHandle oh) |
1857 | 0 | { |
1858 | 0 | if (!oh) { |
1859 | 0 | throw std::logic_error("attempted to make an uninitialized QPDFObjectHandle indirect"); |
1860 | 0 | } |
1861 | 0 | return makeIndirectFromQPDFObject(oh.getObj()); |
1862 | 0 | } |
1863 | | |
1864 | | std::shared_ptr<QPDFObject> |
1865 | | QPDF::getObjectForParser(int id, int gen, bool parse_pdf) |
1866 | 0 | { |
1867 | | // This method is called by the parser and therefore must not resolve any objects. |
1868 | 0 | auto og = QPDFObjGen(id, gen); |
1869 | 0 | if (auto iter = m->obj_cache.find(og); iter != m->obj_cache.end()) { |
1870 | 0 | return iter->second.object; |
1871 | 0 | } |
1872 | 0 | if (m->xref_table.contains(og) || (!m->parsed && og.getObj() < m->xref_table_max_id)) { |
1873 | 0 | return m->obj_cache.insert({og, QPDFObject::create<QPDF_Unresolved>(this, og)}) |
1874 | 0 | .first->second.object; |
1875 | 0 | } |
1876 | 0 | if (parse_pdf) { |
1877 | 0 | return QPDFObject::create<QPDF_Null>(); |
1878 | 0 | } |
1879 | 0 | return m->obj_cache.insert({og, QPDFObject::create<QPDF_Null>(this, og)}).first->second.object; |
1880 | 0 | } |
1881 | | |
1882 | | std::shared_ptr<QPDFObject> |
1883 | | QPDF::getObjectForJSON(int id, int gen) |
1884 | 211k | { |
1885 | 211k | auto og = QPDFObjGen(id, gen); |
1886 | 211k | auto [it, inserted] = m->obj_cache.try_emplace(og); |
1887 | 211k | auto& obj = it->second.object; |
1888 | 211k | if (inserted) { |
1889 | 12.8k | obj = (m->parsed && !m->xref_table.contains(og)) |
1890 | 12.8k | ? QPDFObject::create<QPDF_Null>(this, og) |
1891 | 12.8k | : QPDFObject::create<QPDF_Unresolved>(this, og); |
1892 | 12.8k | } |
1893 | 211k | return obj; |
1894 | 211k | } |
1895 | | |
1896 | | QPDFObjectHandle |
1897 | | QPDF::getObject(QPDFObjGen og) |
1898 | 19.9k | { |
1899 | 19.9k | if (auto it = m->obj_cache.find(og); it != m->obj_cache.end()) { |
1900 | 19.9k | return {it->second.object}; |
1901 | 19.9k | } else if (m->parsed && !m->xref_table.contains(og)) { |
1902 | 0 | return QPDFObject::create<QPDF_Null>(); |
1903 | 0 | } else { |
1904 | 0 | auto result = |
1905 | 0 | m->obj_cache.try_emplace(og, QPDFObject::create<QPDF_Unresolved>(this, og), -1, -1); |
1906 | 0 | return {result.first->second.object}; |
1907 | 0 | } |
1908 | 19.9k | } |
1909 | | |
1910 | | void |
1911 | | QPDF::replaceObject(int objid, int generation, QPDFObjectHandle oh) |
1912 | 0 | { |
1913 | 0 | replaceObject(QPDFObjGen(objid, generation), oh); |
1914 | 0 | } |
1915 | | |
1916 | | void |
1917 | | QPDF::replaceObject(QPDFObjGen og, QPDFObjectHandle oh) |
1918 | 19.9k | { |
1919 | 19.9k | if (!oh || (oh.isIndirect() && !(oh.isStream() && oh.getObjGen() == og))) { |
1920 | 0 | QTC::TC("qpdf", "QPDF replaceObject called with indirect object"); |
1921 | 0 | throw std::logic_error("QPDF::replaceObject called with indirect object handle"); |
1922 | 0 | } |
1923 | 19.9k | updateCache(og, oh.getObj(), -1, -1, false); |
1924 | 19.9k | } |
1925 | | |
1926 | | void |
1927 | | QPDF::removeObject(QPDFObjGen og) |
1928 | 0 | { |
1929 | 0 | m->xref_table.erase(og); |
1930 | 0 | if (auto cached = m->obj_cache.find(og); cached != m->obj_cache.end()) { |
1931 | | // Take care of any object handles that may be floating around. |
1932 | 0 | cached->second.object->assign_null(); |
1933 | 0 | cached->second.object->setObjGen(nullptr, QPDFObjGen()); |
1934 | 0 | m->obj_cache.erase(cached); |
1935 | 0 | } |
1936 | 0 | } |
1937 | | |
1938 | | void |
1939 | | QPDF::replaceReserved(QPDFObjectHandle reserved, QPDFObjectHandle replacement) |
1940 | 0 | { |
1941 | 0 | QTC::TC("qpdf", "QPDF replaceReserved"); |
1942 | 0 | auto tc = reserved.getTypeCode(); |
1943 | 0 | if (!(tc == ::ot_reserved || tc == ::ot_null)) { |
1944 | 0 | throw std::logic_error("replaceReserved called with non-reserved object"); |
1945 | 0 | } |
1946 | 0 | replaceObject(reserved.getObjGen(), replacement); |
1947 | 0 | } |
1948 | | |
1949 | | void |
1950 | | QPDF::swapObjects(int objid1, int generation1, int objid2, int generation2) |
1951 | 0 | { |
1952 | 0 | swapObjects(QPDFObjGen(objid1, generation1), QPDFObjGen(objid2, generation2)); |
1953 | 0 | } |
1954 | | |
1955 | | void |
1956 | | QPDF::swapObjects(QPDFObjGen og1, QPDFObjGen og2) |
1957 | 0 | { |
1958 | | // Force objects to be read from the input source if needed, then swap them in the cache. |
1959 | 0 | resolve(og1); |
1960 | 0 | resolve(og2); |
1961 | 0 | m->obj_cache[og1].object->swapWith(m->obj_cache[og2].object); |
1962 | 0 | } |
1963 | | |
1964 | | size_t |
1965 | | QPDF::tableSize() |
1966 | 0 | { |
1967 | | // If obj_cache is dense, accommodate all object in tables,else accommodate only original |
1968 | | // objects. |
1969 | 0 | auto max_xref = !m->xref_table.empty() ? m->xref_table.crbegin()->first.getObj() : 0; |
1970 | 0 | auto max_obj = !m->obj_cache.empty() ? m->obj_cache.crbegin()->first.getObj() : 0; |
1971 | 0 | auto max_id = std::numeric_limits<int>::max() - 1; |
1972 | 0 | if (max_obj >= max_id || max_xref >= max_id) { |
1973 | | // Temporary fix. Long-term solution is |
1974 | | // - QPDFObjGen to enforce objgens are valid and sensible |
1975 | | // - xref table and obj cache to protect against insertion of impossibly large obj ids |
1976 | 0 | stopOnError("Impossibly large object id encountered."); |
1977 | 0 | } |
1978 | 0 | if (max_obj < 1.1 * std::max(toI(m->obj_cache.size()), max_xref)) { |
1979 | 0 | return toS(++max_obj); |
1980 | 0 | } |
1981 | 0 | return toS(++max_xref); |
1982 | 0 | } |
1983 | | |
1984 | | std::vector<QPDFObjGen> |
1985 | | QPDF::getCompressibleObjVector() |
1986 | 0 | { |
1987 | 0 | return getCompressibleObjGens<QPDFObjGen>(); |
1988 | 0 | } |
1989 | | |
1990 | | std::vector<bool> |
1991 | | QPDF::getCompressibleObjSet() |
1992 | 0 | { |
1993 | 0 | return getCompressibleObjGens<bool>(); |
1994 | 0 | } |
1995 | | |
1996 | | template <typename T> |
1997 | | std::vector<T> |
1998 | | QPDF::getCompressibleObjGens() |
1999 | 0 | { |
2000 | | // Return a list of objects that are allowed to be in object streams. Walk through the objects |
2001 | | // by traversing the document from the root, including a traversal of the pages tree. This |
2002 | | // makes that objects that are on the same page are more likely to be in the same object stream, |
2003 | | // which is slightly more efficient, particularly with linearized files. This is better than |
2004 | | // iterating through the xref table since it avoids preserving orphaned items. |
2005 | | |
2006 | | // Exclude encryption dictionary, if any |
2007 | 0 | QPDFObjectHandle encryption_dict = m->trailer.getKey("/Encrypt"); |
2008 | 0 | QPDFObjGen encryption_dict_og = encryption_dict.getObjGen(); |
2009 | |
|
2010 | 0 | const size_t max_obj = getObjectCount(); |
2011 | 0 | std::vector<bool> visited(max_obj, false); |
2012 | 0 | std::vector<QPDFObjectHandle> queue; |
2013 | 0 | queue.reserve(512); |
2014 | 0 | queue.push_back(m->trailer); |
2015 | 0 | std::vector<T> result; |
2016 | 0 | if constexpr (std::is_same_v<T, QPDFObjGen>) { |
2017 | 0 | result.reserve(m->obj_cache.size()); |
2018 | 0 | } else if constexpr (std::is_same_v<T, bool>) { |
2019 | 0 | result.resize(max_obj + 1U, false); |
2020 | | } else { |
2021 | | throw std::logic_error("Unsupported type in QPDF::getCompressibleObjGens"); |
2022 | | } |
2023 | 0 | while (!queue.empty()) { |
2024 | 0 | auto obj = queue.back(); |
2025 | 0 | queue.pop_back(); |
2026 | 0 | if (obj.getObjectID() > 0) { |
2027 | 0 | QPDFObjGen og = obj.getObjGen(); |
2028 | 0 | const size_t id = toS(og.getObj() - 1); |
2029 | 0 | if (id >= max_obj) { |
2030 | 0 | throw std::logic_error( |
2031 | 0 | "unexpected object id encountered in getCompressibleObjGens"); |
2032 | 0 | } |
2033 | 0 | if (visited[id]) { |
2034 | 0 | QTC::TC("qpdf", "QPDF loop detected traversing objects"); |
2035 | 0 | continue; |
2036 | 0 | } |
2037 | | |
2038 | | // Check whether this is the current object. If not, remove it (which changes it into a |
2039 | | // direct null and therefore stops us from revisiting it) and move on to the next object |
2040 | | // in the queue. |
2041 | 0 | auto upper = m->obj_cache.upper_bound(og); |
2042 | 0 | if (upper != m->obj_cache.end() && upper->first.getObj() == og.getObj()) { |
2043 | 0 | removeObject(og); |
2044 | 0 | continue; |
2045 | 0 | } |
2046 | | |
2047 | 0 | visited[id] = true; |
2048 | |
|
2049 | 0 | if (og == encryption_dict_og) { |
2050 | 0 | QTC::TC("qpdf", "QPDF exclude encryption dictionary"); |
2051 | 0 | } else if (!(obj.isStream() || |
2052 | 0 | (obj.isDictionaryOfType("/Sig") && obj.hasKey("/ByteRange") && |
2053 | 0 | obj.hasKey("/Contents")))) { |
2054 | 0 | if constexpr (std::is_same_v<T, QPDFObjGen>) { |
2055 | 0 | result.push_back(og); |
2056 | 0 | } else if constexpr (std::is_same_v<T, bool>) { |
2057 | 0 | result[id + 1U] = true; |
2058 | 0 | } |
2059 | 0 | } |
2060 | 0 | } |
2061 | 0 | if (obj.isStream()) { |
2062 | 0 | auto dict = obj.getDict().as_dictionary(); |
2063 | 0 | auto end = dict.crend(); |
2064 | 0 | for (auto iter = dict.crbegin(); iter != end; ++iter) { |
2065 | 0 | std::string const& key = iter->first; |
2066 | 0 | QPDFObjectHandle const& value = iter->second; |
2067 | 0 | if (!value.null()) { |
2068 | 0 | if (key == "/Length") { |
2069 | | // omit stream lengths |
2070 | 0 | if (value.isIndirect()) { |
2071 | 0 | QTC::TC("qpdf", "QPDF exclude indirect length"); |
2072 | 0 | } |
2073 | 0 | } else { |
2074 | 0 | queue.emplace_back(value); |
2075 | 0 | } |
2076 | 0 | } |
2077 | 0 | } |
2078 | 0 | } else if (obj.isDictionary()) { |
2079 | 0 | auto dict = obj.as_dictionary(); |
2080 | 0 | auto end = dict.crend(); |
2081 | 0 | for (auto iter = dict.crbegin(); iter != end; ++iter) { |
2082 | 0 | if (!iter->second.null()) { |
2083 | 0 | queue.emplace_back(iter->second); |
2084 | 0 | } |
2085 | 0 | } |
2086 | 0 | } else if (auto items = obj.as_array()) { |
2087 | 0 | queue.insert(queue.end(), items.crbegin(), items.crend()); |
2088 | 0 | } |
2089 | 0 | } |
2090 | | |
2091 | 0 | return result; |
2092 | 0 | } Unexecuted instantiation: std::__1::vector<QPDFObjGen, std::__1::allocator<QPDFObjGen> > QPDF::getCompressibleObjGens<QPDFObjGen>() Unexecuted instantiation: std::__1::vector<bool, std::__1::allocator<bool> > QPDF::getCompressibleObjGens<bool>() |