Coverage Report

Created: 2026-12-01 06:45

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/qpdf/libqpdf/QPDFWriter.cc
Line
Count
Source
1
#include <qpdf/qpdf-config.h> // include early for large file support
2
3
#include <qpdf/QPDFWriter_private.hh>
4
5
#include <qpdf/MD5.hh>
6
#include <qpdf/Pl_AES_PDF.hh>
7
#include <qpdf/Pl_Flate.hh>
8
#include <qpdf/Pl_MD5.hh>
9
#include <qpdf/Pl_PNGFilter.hh>
10
#include <qpdf/Pl_RC4.hh>
11
#include <qpdf/Pl_StdioFile.hh>
12
#include <qpdf/QIntC.hh>
13
#include <qpdf/QPDFObjectHandle_private.hh>
14
#include <qpdf/QPDFObject_private.hh>
15
#include <qpdf/QPDF_private.hh>
16
#include <qpdf/QTC.hh>
17
#include <qpdf/QUtil.hh>
18
#include <qpdf/RC4.hh>
19
#include <qpdf/Util.hh>
20
21
#include <algorithm>
22
#include <concepts>
23
#include <cstdlib>
24
#include <stdexcept>
25
#include <tuple>
26
27
using namespace std::literals;
28
using namespace qpdf;
29
30
using Encryption = impl::Doc::Encryption;
31
using Config = Writer::Config;
32
33
QPDFWriter::ProgressReporter::~ProgressReporter() // NOLINT (modernize-use-equals-default)
34
0
{
35
    // Must be explicit and not inline -- see QPDF_DLL_CLASS in README-maintainer
36
0
}
37
38
QPDFWriter::FunctionProgressReporter::FunctionProgressReporter(std::function<void(int)> handler) :
39
0
    handler(handler)
40
0
{
41
0
}
42
43
QPDFWriter::FunctionProgressReporter::~FunctionProgressReporter() // NOLINT
44
                                                                  // (modernize-use-equals-default)
45
0
{
46
    // Must be explicit and not inline -- see QPDF_DLL_CLASS in README-maintainer
47
0
}
48
49
void
50
QPDFWriter::FunctionProgressReporter::reportProgress(int progress)
51
0
{
52
0
    handler(progress);
53
0
}
54
55
namespace
56
{
57
    class Pl_stack
58
    {
59
        // A pipeline Popper is normally returned by Pl_stack::activate, or, if necessary, a
60
        // reference to a Popper instance can be passed into activate. When the Popper goes out of
61
        // scope, the pipeline stack is popped. This causes finish to be called on the current
62
        // pipeline and the pipeline stack to be popped until the top of stack is a previous active
63
        // top of stack and restores the pipeline to that point. It deletes any pipelines that it
64
        // pops.
65
        class Popper
66
        {
67
            friend class Pl_stack;
68
69
          public:
70
            Popper() = default;
71
            Popper(Popper const&) = delete;
72
            Popper(Popper&& other) noexcept
73
0
            {
74
0
                // For MSVC, default pops the stack
75
0
                if (this != &other) {
76
0
                    stack = other.stack;
77
0
                    stack_id = other.stack_id;
78
0
                    other.stack = nullptr;
79
0
                    other.stack_id = 0;
80
0
                };
81
0
            }
82
            Popper& operator=(Popper const&) = delete;
83
            Popper&
84
            operator=(Popper&& other) noexcept
85
0
            {
86
0
                // For MSVC, default pops the stack
87
0
                if (this != &other) {
88
0
                    stack = other.stack;
89
0
                    stack_id = other.stack_id;
90
0
                    other.stack = nullptr;
91
0
                    other.stack_id = 0;
92
0
                };
93
0
                return *this;
94
0
            }
95
96
            ~Popper();
97
98
            // Manually pop pipeline from the pipeline stack.
99
            void pop();
100
101
          private:
102
            Popper(Pl_stack& stack) :
103
57.1k
                stack(&stack)
104
57.1k
            {
105
57.1k
            }
106
107
            Pl_stack* stack{nullptr};
108
            unsigned long stack_id{0};
109
        };
110
111
      public:
112
        Pl_stack(pl::Count*& top) :
113
9.37k
            top(top)
114
9.37k
        {
115
9.37k
        }
116
117
        Popper
118
        popper()
119
9.28k
        {
120
9.28k
            return {*this};
121
9.28k
        }
122
123
        void
124
        initialize(Pipeline* p)
125
9.37k
        {
126
9.37k
            auto c = std::make_unique<pl::Count>(++last_id, p);
127
9.37k
            top = c.get();
128
9.37k
            stack.emplace_back(std::move(c));
129
9.37k
        }
130
131
        Popper
132
        activate(std::string& str)
133
43.4k
        {
134
43.4k
            Popper pp{*this};
135
43.4k
            activate(pp, str);
136
43.4k
            return pp;
137
43.4k
        }
138
139
        void
140
        activate(Popper& pp, std::string& str)
141
43.4k
        {
142
43.4k
            activate(pp, false, &str, nullptr);
143
43.4k
        }
144
145
        void
146
        activate(Popper& pp, std::unique_ptr<Pipeline> next)
147
0
        {
148
0
            count_buffer.clear();
149
0
            activate(pp, false, &count_buffer, std::move(next));
150
0
        }
151
152
        Popper
153
        activate(
154
            bool discard = false,
155
            std::string* str = nullptr,
156
            std::unique_ptr<Pipeline> next = nullptr)
157
4.44k
        {
158
4.44k
            Popper pp{*this};
159
4.44k
            activate(pp, discard, str, std::move(next));
160
4.44k
            return pp;
161
4.44k
        }
162
163
        void
164
        activate(
165
            Popper& pp,
166
            bool discard = false,
167
            std::string* str = nullptr,
168
            std::unique_ptr<Pipeline> next = nullptr)
169
47.8k
        {
170
47.8k
            std::unique_ptr<pl::Count> c;
171
47.8k
            if (next) {
172
0
                c = std::make_unique<pl::Count>(++last_id, count_buffer, std::move(next));
173
47.8k
            } else if (discard) {
174
4.44k
                c = std::make_unique<pl::Count>(++last_id, nullptr);
175
43.4k
            } else if (!str) {
176
0
                c = std::make_unique<pl::Count>(++last_id, top);
177
43.4k
            } else {
178
43.4k
                c = std::make_unique<pl::Count>(++last_id, *str);
179
43.4k
            }
180
47.8k
            pp.stack_id = last_id;
181
47.8k
            top = c.get();
182
47.8k
            stack.emplace_back(std::move(c));
183
47.8k
        }
184
        void
185
        activate_md5(Popper& pp)
186
9.28k
        {
187
9.28k
            qpdf_assert_debug(!md5_pipeline);
188
9.28k
            qpdf_assert_debug(md5_id == 0);
189
9.28k
            qpdf_assert_debug(top->getCount() == 0);
190
9.28k
            md5_pipeline = std::make_unique<Pl_MD5>("qpdf md5", top);
191
9.28k
            md5_pipeline->persistAcrossFinish(true);
192
            // Special case code in pop clears m->md5_pipeline upon deletion.
193
9.28k
            auto c = std::make_unique<pl::Count>(++last_id, md5_pipeline.get());
194
9.28k
            pp.stack_id = last_id;
195
9.28k
            md5_id = last_id;
196
9.28k
            top = c.get();
197
9.28k
            stack.emplace_back(std::move(c));
198
9.28k
        }
199
200
        // Return the hex digest and disable the MD5 pipeline.
201
        std::string
202
        hex_digest()
203
9.18k
        {
204
9.18k
            qpdf_assert_debug(md5_pipeline);
205
9.18k
            auto digest = md5_pipeline->getHexDigest();
206
9.18k
            md5_pipeline->enable(false);
207
9.18k
            return digest;
208
9.18k
        }
209
210
        void
211
        clear_buffer()
212
0
        {
213
0
            count_buffer.clear();
214
0
        }
215
216
      private:
217
        void
218
        pop(unsigned long stack_id)
219
57.1k
        {
220
57.1k
            if (!stack_id) {
221
0
                return;
222
0
            }
223
57.1k
            qpdf_assert_debug(stack.size() >= 2);
224
57.1k
            top->finish();
225
57.1k
            qpdf_assert_debug(stack.back().get() == top);
226
            // It used to be possible for this assertion to fail if writeLinearized exits by
227
            // exception when deterministic ID. There are no longer any cases in which two
228
            // dynamically allocated pipeline Popper objects ever exist at the same time, so the
229
            // assertion will fail if they get popped out of order from automatic destruction.
230
57.1k
            qpdf_assert_debug(top->id() == stack_id);
231
57.1k
            if (stack_id == md5_id) {
232
9.28k
                md5_pipeline = nullptr;
233
9.28k
                md5_id = 0;
234
9.28k
            }
235
57.1k
            stack.pop_back();
236
57.1k
            top = stack.back().get();
237
57.1k
        }
238
239
        std::vector<std::unique_ptr<pl::Count>> stack;
240
        pl::Count*& top;
241
        std::unique_ptr<Pl_MD5> md5_pipeline{nullptr};
242
        unsigned long last_id{0};
243
        unsigned long md5_id{0};
244
        std::string count_buffer;
245
    };
246
} // namespace
247
248
Pl_stack::Popper::~Popper()
249
57.1k
{
250
57.1k
    if (stack) {
251
57.1k
        stack->pop(stack_id);
252
57.1k
    }
253
57.1k
}
254
255
void
256
Pl_stack::Popper::pop()
257
0
{
258
0
    if (stack) {
259
0
        stack->pop(stack_id);
260
0
    }
261
0
    stack_id = 0;
262
0
    stack = nullptr;
263
0
}
264
265
namespace qpdf::impl
266
{
267
    // Writer class is restricted to QPDFWriter so that only it can call certain methods.
268
    class Writer: protected Doc::Common
269
    {
270
      public:
271
        // flags used by unparseObject
272
        static int const f_stream = 1 << 0;
273
        static int const f_filtered = 1 << 1;
274
        static int const f_in_ostream = 1 << 2;
275
        static int const f_hex_string = 1 << 3;
276
        static int const f_no_encryption = 1 << 4;
277
278
        enum trailer_e { t_normal, t_lin_first, t_lin_second };
279
280
        Writer() = delete;
281
        Writer(Writer const&) = delete;
282
        Writer(Writer&&) = delete;
283
        Writer& operator=(Writer const&) = delete;
284
        Writer& operator=(Writer&&) = delete;
285
        ~Writer()
286
9.37k
        {
287
9.37k
            if (file && close_file) {
288
0
                fclose(file);
289
0
            }
290
9.37k
            delete output_buffer;
291
9.37k
        }
292
        Writer(QPDF& qpdf, QPDFWriter& w) :
293
9.37k
            Common(qpdf.doc()),
294
9.37k
            lin(qpdf.doc().linearization()),
295
9.37k
            cfg(true),
296
9.37k
            root_og(qpdf.getRoot().indirect() ? qpdf.getRoot().id_gen() : QPDFObjGen(-1, 0)),
297
9.37k
            pipeline_stack(pipeline)
298
9.37k
        {
299
9.37k
        }
300
301
        void write();
302
        std::map<QPDFObjGen, QPDFXRefEntry> getWrittenXRefTable();
303
        void setMinimumPDFVersion(std::string const& version, int extension_level = 0);
304
        void copyEncryptionParameters(QPDF&);
305
        void doWriteSetup();
306
        void prepareFileForWrite();
307
308
        void disableIncompatibleEncryption(int major, int minor, int extension_level);
309
        void interpretR3EncryptionParameters(
310
            bool allow_accessibility,
311
            bool allow_extract,
312
            bool allow_assemble,
313
            bool allow_annotate_and_form,
314
            bool allow_form_filling,
315
            bool allow_modify_other,
316
            qpdf_r3_print_e print,
317
            qpdf_r3_modify_e modify);
318
        void setEncryptionParameters(char const* user_password, char const* owner_password);
319
        void setEncryptionMinimumVersion();
320
        void parseVersion(std::string const& version, int& major, int& minor) const;
321
        int compareVersions(int major1, int minor1, int major2, int minor2) const;
322
        void generateID(bool encrypted);
323
        std::string getOriginalID1();
324
        void initializeTables(size_t extra = 0);
325
        void preserveObjectStreams();
326
        void generateObjectStreams();
327
        void initializeSpecialStreams();
328
        void enqueue(QPDFObjectHandle const& object);
329
        void enqueueObjectsStandard();
330
        void enqueueObjectsPCLm();
331
        void enqueuePart(std::vector<QPDFObjectHandle>& part);
332
        void assignCompressedObjectNumbers(QPDFObjGen og);
333
        Dictionary trimmed_trailer();
334
335
        // Returns tuple<filter, compress_stream, is_root_metadata>
336
        std::tuple<const bool, const bool, const bool>
337
        will_filter_stream(QPDFObjectHandle stream, std::string* stream_data);
338
339
        // Test whether stream would be filtered if it were written.
340
        bool will_filter_stream(QPDFObjectHandle stream);
341
        unsigned int bytesNeeded(long long n);
342
        void writeBinary(unsigned long long val, unsigned int bytes);
343
        Writer& write(std::string_view str);
344
        Writer& write(size_t count, char c);
345
        Writer& write(std::integral auto val);
346
        Writer& write_name(std::string const& str);
347
        Writer& write_string(std::string const& str, bool force_binary = false);
348
        Writer& write_encrypted(std::string_view str);
349
350
        template <typename... Args>
351
        Writer& write_qdf(Args&&... args);
352
        template <typename... Args>
353
        Writer& write_no_qdf(Args&&... args);
354
        void writeObjectStreamOffsets(std::vector<qpdf_offset_t>& offsets, int first_obj);
355
        void writeObjectStream(QPDFObjectHandle object);
356
        void writeObject(QPDFObjectHandle object, int object_stream_index = -1);
357
        void writeTrailer(
358
            trailer_e which,
359
            int size,
360
            bool xref_stream,
361
            qpdf_offset_t prev,
362
            int linearization_pass);
363
        void unparseObject(
364
            QPDFObjectHandle object,
365
            size_t level,
366
            int flags,
367
            // for stream dictionaries
368
            size_t stream_length = 0,
369
            bool compress = false);
370
        void unparseChild(QPDFObjectHandle const& child, size_t level, int flags);
371
        int openObject(int objid = 0);
372
        void closeObject(int objid);
373
        void writeStandard();
374
        void writeLinearized();
375
        void writeEncryptionDictionary();
376
        void writeHeader();
377
        void writeHintStream(int hint_id);
378
        qpdf_offset_t writeXRefTable(trailer_e which, int first, int last, int size);
379
        qpdf_offset_t writeXRefTable(
380
            trailer_e which,
381
            int first,
382
            int last,
383
            int size,
384
            // for linearization
385
            qpdf_offset_t prev,
386
            bool suppress_offsets,
387
            int hint_id,
388
            qpdf_offset_t hint_offset,
389
            qpdf_offset_t hint_length,
390
            int linearization_pass);
391
        qpdf_offset_t writeXRefStream(
392
            int objid,
393
            int max_id,
394
            qpdf_offset_t max_offset,
395
            trailer_e which,
396
            int first,
397
            int last,
398
            int size);
399
        qpdf_offset_t writeXRefStream(
400
            int objid,
401
            int max_id,
402
            qpdf_offset_t max_offset,
403
            trailer_e which,
404
            int first,
405
            int last,
406
            int size,
407
            // for linearization
408
            qpdf_offset_t prev,
409
            int hint_id,
410
            qpdf_offset_t hint_offset,
411
            qpdf_offset_t hint_length,
412
            bool skip_compression,
413
            int linearization_pass);
414
415
        void setDataKey(int objid);
416
        void indicateProgress(bool decrement, bool finished);
417
        size_t calculateXrefStreamPadding(qpdf_offset_t xref_bytes);
418
419
        void adjustAESStreamLength(size_t& length);
420
        void computeDeterministicIDData();
421
422
      protected:
423
        Doc::Linearization& lin;
424
425
        qpdf::Writer::Config cfg;
426
427
        QPDFObjGen root_og{-1, 0};
428
        char const* filename{"unspecified"};
429
        FILE* file{nullptr};
430
        bool close_file{false};
431
        std::unique_ptr<Pl_Buffer> buffer_pipeline{nullptr};
432
        Buffer* output_buffer{nullptr};
433
434
        std::unique_ptr<QPDF::Doc::Encryption> encryption;
435
        std::string encryption_key;
436
437
        std::string id1; // for /ID key of
438
        std::string id2; // trailer dictionary
439
        std::string final_pdf_version;
440
        int final_extension_level{0};
441
        std::string min_pdf_version;
442
        int min_extension_level{0};
443
        int encryption_dict_objid{0};
444
        std::string cur_data_key;
445
        std::unique_ptr<Pipeline> file_pl;
446
        qpdf::pl::Count* pipeline{nullptr};
447
        std::vector<QPDFObjectHandle> object_queue;
448
        size_t object_queue_front{0};
449
        QPDFWriter::ObjTable obj;
450
        QPDFWriter::NewObjTable new_obj;
451
        int next_objid{1};
452
        int cur_stream_length_id{0};
453
        size_t cur_stream_length{0};
454
        bool added_newline{false};
455
        size_t max_ostream_index{0};
456
        std::set<QPDFObjGen> normalized_streams;
457
        std::map<QPDFObjGen, int> page_object_to_seq;
458
        std::map<QPDFObjGen, int> contents_to_page_seq;
459
        std::map<int, std::vector<QPDFObjGen>> object_stream_to_objects;
460
        Pl_stack pipeline_stack;
461
        std::string deterministic_id_data;
462
        bool did_write_setup{false};
463
464
        // For progress reporting
465
        std::shared_ptr<QPDFWriter::ProgressReporter> progress_reporter;
466
        int events_expected{0};
467
        int events_seen{0};
468
        int next_progress_report{0};
469
    }; // class qpdf::impl::Writer
470
471
} // namespace qpdf::impl
472
473
class QPDFWriter::Members: impl::Writer
474
{
475
    friend class QPDFWriter;
476
    friend class qpdf::Writer;
477
478
  public:
479
    Members(QPDFWriter& w, QPDF& qpdf) :
480
9.37k
        impl::Writer(qpdf, w)
481
9.37k
    {
482
9.37k
    }
483
};
484
485
qpdf::Writer::Writer(QPDF& qpdf, Config cfg) :
486
0
    QPDFWriter(qpdf)
487
0
{
488
0
    m->cfg = cfg;
489
0
}
490
QPDFWriter::QPDFWriter(QPDF& pdf) :
491
9.37k
    m(std::make_shared<Members>(*this, pdf))
492
9.37k
{
493
9.37k
}
494
495
QPDFWriter::QPDFWriter(QPDF& pdf, char const* filename) :
496
0
    m(std::make_shared<Members>(*this, pdf))
497
0
{
498
0
    setOutputFilename(filename);
499
0
}
500
501
QPDFWriter::QPDFWriter(QPDF& pdf, char const* description, FILE* file, bool close_file) :
502
0
    m(std::make_shared<Members>(*this, pdf))
503
0
{
504
0
    setOutputFile(description, file, close_file);
505
0
}
506
507
void
508
QPDFWriter::setOutputFilename(char const* filename)
509
0
{
510
0
    char const* description = filename;
511
0
    FILE* f = nullptr;
512
0
    bool close_file = false;
513
0
    if (filename == nullptr) {
514
0
        description = "standard output";
515
0
        f = stdout;
516
0
        QUtil::binary_stdout();
517
0
    } else {
518
0
        f = QUtil::safe_fopen(filename, "wb+");
519
0
        close_file = true;
520
0
    }
521
0
    setOutputFile(description, f, close_file);
522
0
}
523
524
void
525
QPDFWriter::setOutputFile(char const* description, FILE* file, bool close_file)
526
0
{
527
0
    m->filename = description;
528
0
    m->file = file;
529
0
    m->close_file = close_file;
530
0
    m->file_pl = std::make_unique<Pl_StdioFile>("qpdf output", file);
531
0
    m->pipeline_stack.initialize(m->file_pl.get());
532
0
}
533
534
void
535
QPDFWriter::setOutputMemory()
536
0
{
537
0
    m->filename = "memory buffer";
538
0
    m->buffer_pipeline = std::make_unique<Pl_Buffer>("qpdf output");
539
0
    m->pipeline_stack.initialize(m->buffer_pipeline.get());
540
0
}
541
542
Buffer*
543
QPDFWriter::getBuffer()
544
0
{
545
0
    Buffer* result = m->output_buffer;
546
0
    m->output_buffer = nullptr;
547
0
    return result;
548
0
}
549
550
std::shared_ptr<Buffer>
551
QPDFWriter::getBufferSharedPointer()
552
0
{
553
0
    return std::shared_ptr<Buffer>(getBuffer());
554
0
}
555
556
void
557
QPDFWriter::setOutputPipeline(Pipeline* p)
558
9.37k
{
559
9.37k
    m->filename = "custom pipeline";
560
9.37k
    m->pipeline_stack.initialize(p);
561
9.37k
}
562
563
void
564
QPDFWriter::setObjectStreamMode(qpdf_object_stream_e mode)
565
0
{
566
0
    m->cfg.object_streams(mode);
567
0
}
568
569
void
570
QPDFWriter::setStreamDataMode(qpdf_stream_data_e mode)
571
0
{
572
0
    m->cfg.stream_data(mode);
573
0
}
574
575
Config&
576
Config::stream_data(qpdf_stream_data_e mode)
577
0
{
578
0
    switch (mode) {
579
0
    case qpdf_s_uncompress:
580
0
        decode_level(std::max(qpdf_dl_generalized, decode_level_));
581
0
        compress_streams(false);
582
0
        return *this;
583
584
0
    case qpdf_s_preserve:
585
0
        decode_level(qpdf_dl_none);
586
0
        compress_streams(false);
587
0
        return *this;
588
589
0
    case qpdf_s_compress:
590
0
        decode_level(std::max(qpdf_dl_generalized, decode_level_));
591
0
        compress_streams(true);
592
0
    }
593
0
    return *this;
594
0
}
595
596
void
597
QPDFWriter::setCompressStreams(bool val)
598
0
{
599
0
    m->cfg.compress_streams(val);
600
0
}
601
602
Config&
603
Config::compress_streams(bool val)
604
9.37k
{
605
9.37k
    if (pclm_) {
606
0
        usage("compress_streams cannot be set when pclm is set");
607
0
        return *this;
608
0
    }
609
9.37k
    compress_streams_set_ = true;
610
9.37k
    compress_streams_ = val;
611
9.37k
    return *this;
612
9.37k
}
613
614
void
615
QPDFWriter::setDecodeLevel(qpdf_stream_decode_level_e val)
616
9.37k
{
617
9.37k
    m->cfg.decode_level(val);
618
9.37k
}
619
620
Config&
621
Config::decode_level(qpdf_stream_decode_level_e val)
622
9.37k
{
623
9.37k
    if (pclm_) {
624
0
        usage("stream_decode_level cannot be set when pclm is set");
625
0
        return *this;
626
0
    }
627
9.37k
    decode_level_set_ = true;
628
9.37k
    decode_level_ = val;
629
9.37k
    return *this;
630
9.37k
}
631
632
void
633
QPDFWriter::setRecompressFlate(bool val)
634
0
{
635
0
    m->cfg.recompress_flate(val);
636
0
}
637
638
void
639
QPDFWriter::setContentNormalization(bool val)
640
0
{
641
0
    m->cfg.normalize_content(val);
642
0
}
643
644
void
645
QPDFWriter::setQDFMode(bool val)
646
9.37k
{
647
9.37k
    m->cfg.qdf(val);
648
9.37k
}
649
650
Config&
651
Config::qdf(bool val)
652
9.37k
{
653
9.37k
    if (pclm_ || linearize_) {
654
0
        usage("qdf cannot be set when linearize or pclm are set");
655
0
    }
656
9.37k
    if (preserve_encryption_) {
657
9.37k
        usage("preserve_encryption cannot be set when qdf is set");
658
9.37k
    }
659
9.37k
    qdf_ = val;
660
9.37k
    if (val) {
661
9.37k
        if (!normalize_content_set_) {
662
9.37k
            normalize_content(true);
663
9.37k
        }
664
9.37k
        if (!compress_streams_set_) {
665
9.37k
            compress_streams(false);
666
9.37k
        }
667
9.37k
        if (!decode_level_set_) {
668
0
            decode_level(qpdf_dl_generalized);
669
0
        }
670
9.37k
        preserve_encryption_ = false;
671
        // Generate indirect stream lengths for qdf mode since fix-qdf uses them for storing
672
        // recomputed stream length data. Certain streams such as object streams, xref streams, and
673
        // hint streams always get direct stream lengths.
674
9.37k
        direct_stream_lengths_ = false;
675
9.37k
    }
676
9.37k
    return *this;
677
9.37k
}
678
679
void
680
QPDFWriter::setPreserveUnreferencedObjects(bool val)
681
0
{
682
0
    m->cfg.preserve_unreferenced(val);
683
0
}
684
685
void
686
QPDFWriter::setNewlineBeforeEndstream(bool val)
687
0
{
688
0
    m->cfg.newline_before_endstream(val);
689
0
}
690
691
void
692
QPDFWriter::setMinimumPDFVersion(std::string const& version, int extension_level)
693
0
{
694
0
    m->setMinimumPDFVersion(version, extension_level);
695
0
}
696
697
void
698
impl::Writer::setMinimumPDFVersion(std::string const& version, int extension_level)
699
9.74k
{
700
9.74k
    bool set_version = false;
701
9.74k
    bool set_extension_level = false;
702
9.74k
    if (min_pdf_version.empty()) {
703
9.34k
        set_version = true;
704
9.34k
        set_extension_level = true;
705
9.34k
    } else {
706
398
        int old_major = 0;
707
398
        int old_minor = 0;
708
398
        int min_major = 0;
709
398
        int min_minor = 0;
710
398
        parseVersion(version, old_major, old_minor);
711
398
        parseVersion(min_pdf_version, min_major, min_minor);
712
398
        int compare = compareVersions(old_major, old_minor, min_major, min_minor);
713
398
        if (compare > 0) {
714
81
            QTC::TC("qpdf", "QPDFWriter increasing minimum version", extension_level == 0 ? 0 : 1);
715
81
            set_version = true;
716
81
            set_extension_level = true;
717
317
        } else if (compare == 0) {
718
3
            if (extension_level > min_extension_level) {
719
0
                set_extension_level = true;
720
0
            }
721
3
        }
722
398
    }
723
724
9.74k
    if (set_version) {
725
9.42k
        min_pdf_version = version;
726
9.42k
    }
727
9.74k
    if (set_extension_level) {
728
9.42k
        min_extension_level = extension_level;
729
9.42k
    }
730
9.74k
}
731
732
void
733
QPDFWriter::setMinimumPDFVersion(PDFVersion const& v)
734
0
{
735
0
    std::string version;
736
0
    int extension_level;
737
0
    v.getVersion(version, extension_level);
738
0
    setMinimumPDFVersion(version, extension_level);
739
0
}
740
741
void
742
QPDFWriter::forcePDFVersion(std::string const& version, int extension_level)
743
0
{
744
0
    m->cfg.forced_pdf_version(version, extension_level);
745
0
}
746
747
void
748
QPDFWriter::setExtraHeaderText(std::string const& text)
749
0
{
750
0
    m->cfg.extra_header_text(text);
751
0
}
752
753
Config&
754
Config::extra_header_text(std::string const& val)
755
0
{
756
0
    extra_header_text_ = val;
757
0
    if (!extra_header_text_.empty() && extra_header_text_.back() != '\n') {
758
0
        extra_header_text_ += "\n";
759
0
    } else {
760
0
        QTC::TC("qpdf", "QPDFWriter extra header text no newline");
761
0
    }
762
0
    return *this;
763
0
}
764
765
void
766
QPDFWriter::setStaticID(bool val)
767
0
{
768
0
    m->cfg.static_id(val);
769
0
}
770
771
void
772
QPDFWriter::setDeterministicID(bool val)
773
9.37k
{
774
9.37k
    m->cfg.deterministic_id(val);
775
9.37k
}
776
777
void
778
QPDFWriter::setStaticAesIV(bool val)
779
0
{
780
0
    if (val) {
781
0
        Pl_AES_PDF::useStaticIV();
782
0
    }
783
0
}
784
785
void
786
QPDFWriter::setSuppressOriginalObjectIDs(bool val)
787
0
{
788
0
    m->cfg.no_original_object_ids(val);
789
0
}
790
791
void
792
QPDFWriter::setPreserveEncryption(bool val)
793
0
{
794
0
    m->cfg.preserve_encryption(val);
795
0
}
796
797
void
798
QPDFWriter::setLinearization(bool val)
799
0
{
800
0
    m->cfg.linearize(val);
801
0
}
802
803
Config&
804
Config::linearize(bool val)
805
0
{
806
0
    if (pclm_ || qdf_) {
807
0
        usage("linearize cannot be set when qdf or pclm are set");
808
0
        return *this;
809
0
    }
810
0
    linearize_ = val;
811
0
    return *this;
812
0
}
813
814
void
815
QPDFWriter::setLinearizationPass1Filename(std::string const& filename)
816
0
{
817
0
    m->cfg.linearize_pass1(filename);
818
0
}
819
820
void
821
QPDFWriter::setPCLm(bool val)
822
0
{
823
0
    m->cfg.pclm(val);
824
0
}
825
826
Config&
827
Config::pclm(bool val)
828
0
{
829
0
    if (decode_level_set_ || compress_streams_set_ || linearize_) {
830
0
        usage(
831
0
            "pclm cannot be set when stream_decode_level, compress_streams, linearize or qdf are "
832
0
            "set");
833
0
        return *this;
834
0
    }
835
0
    pclm_ = val;
836
0
    if (val) {
837
0
        decode_level_ = qpdf_dl_none;
838
0
        compress_streams_ = false;
839
0
        linearize_ = false;
840
0
    }
841
842
0
    return *this;
843
0
}
844
845
void
846
QPDFWriter::setR2EncryptionParametersInsecure(
847
    char const* user_password,
848
    char const* owner_password,
849
    bool allow_print,
850
    bool allow_modify,
851
    bool allow_extract,
852
    bool allow_annotate)
853
0
{
854
0
    m->encryption = std::make_unique<Encryption>(1, 2, 5, true);
855
0
    if (!allow_print) {
856
0
        m->encryption->setP(3, false);
857
0
    }
858
0
    if (!allow_modify) {
859
0
        m->encryption->setP(4, false);
860
0
    }
861
0
    if (!allow_extract) {
862
0
        m->encryption->setP(5, false);
863
0
    }
864
0
    if (!allow_annotate) {
865
0
        m->encryption->setP(6, false);
866
0
    }
867
0
    m->setEncryptionParameters(user_password, owner_password);
868
0
}
869
870
void
871
QPDFWriter::setR3EncryptionParametersInsecure(
872
    char const* user_password,
873
    char const* owner_password,
874
    bool allow_accessibility,
875
    bool allow_extract,
876
    bool allow_assemble,
877
    bool allow_annotate_and_form,
878
    bool allow_form_filling,
879
    bool allow_modify_other,
880
    qpdf_r3_print_e print)
881
0
{
882
0
    m->encryption = std::make_unique<Encryption>(2, 3, 16, true);
883
0
    m->interpretR3EncryptionParameters(
884
0
        allow_accessibility,
885
0
        allow_extract,
886
0
        allow_assemble,
887
0
        allow_annotate_and_form,
888
0
        allow_form_filling,
889
0
        allow_modify_other,
890
0
        print,
891
0
        qpdf_r3m_all);
892
0
    m->setEncryptionParameters(user_password, owner_password);
893
0
}
894
895
void
896
QPDFWriter::setR4EncryptionParametersInsecure(
897
    char const* user_password,
898
    char const* owner_password,
899
    bool allow_accessibility,
900
    bool allow_extract,
901
    bool allow_assemble,
902
    bool allow_annotate_and_form,
903
    bool allow_form_filling,
904
    bool allow_modify_other,
905
    qpdf_r3_print_e print,
906
    bool encrypt_metadata,
907
    bool use_aes)
908
0
{
909
0
    m->encryption = std::make_unique<Encryption>(4, 4, 16, encrypt_metadata);
910
0
    m->cfg.encrypt_use_aes(use_aes);
911
0
    m->interpretR3EncryptionParameters(
912
0
        allow_accessibility,
913
0
        allow_extract,
914
0
        allow_assemble,
915
0
        allow_annotate_and_form,
916
0
        allow_form_filling,
917
0
        allow_modify_other,
918
0
        print,
919
0
        qpdf_r3m_all);
920
0
    m->setEncryptionParameters(user_password, owner_password);
921
0
}
922
923
void
924
QPDFWriter::setR5EncryptionParameters(
925
    char const* user_password,
926
    char const* owner_password,
927
    bool allow_accessibility,
928
    bool allow_extract,
929
    bool allow_assemble,
930
    bool allow_annotate_and_form,
931
    bool allow_form_filling,
932
    bool allow_modify_other,
933
    qpdf_r3_print_e print,
934
    bool encrypt_metadata)
935
0
{
936
0
    m->encryption = std::make_unique<Encryption>(5, 5, 32, encrypt_metadata);
937
0
    m->cfg.encrypt_use_aes(true);
938
0
    m->interpretR3EncryptionParameters(
939
0
        allow_accessibility,
940
0
        allow_extract,
941
0
        allow_assemble,
942
0
        allow_annotate_and_form,
943
0
        allow_form_filling,
944
0
        allow_modify_other,
945
0
        print,
946
0
        qpdf_r3m_all);
947
0
    m->setEncryptionParameters(user_password, owner_password);
948
0
}
949
950
void
951
QPDFWriter::setR6EncryptionParameters(
952
    char const* user_password,
953
    char const* owner_password,
954
    bool allow_accessibility,
955
    bool allow_extract,
956
    bool allow_assemble,
957
    bool allow_annotate_and_form,
958
    bool allow_form_filling,
959
    bool allow_modify_other,
960
    qpdf_r3_print_e print,
961
    bool encrypt_metadata)
962
0
{
963
0
    m->encryption = std::make_unique<Encryption>(5, 6, 32, encrypt_metadata);
964
0
    m->interpretR3EncryptionParameters(
965
0
        allow_accessibility,
966
0
        allow_extract,
967
0
        allow_assemble,
968
0
        allow_annotate_and_form,
969
0
        allow_form_filling,
970
0
        allow_modify_other,
971
0
        print,
972
0
        qpdf_r3m_all);
973
0
    m->cfg.encrypt_use_aes(true);
974
0
    m->setEncryptionParameters(user_password, owner_password);
975
0
}
976
977
void
978
impl::Writer::interpretR3EncryptionParameters(
979
    bool allow_accessibility,
980
    bool allow_extract,
981
    bool allow_assemble,
982
    bool allow_annotate_and_form,
983
    bool allow_form_filling,
984
    bool allow_modify_other,
985
    qpdf_r3_print_e print,
986
    qpdf_r3_modify_e modify)
987
0
{
988
    // Acrobat 5 security options:
989
990
    // Checkboxes:
991
    //   Enable Content Access for the Visually Impaired
992
    //   Allow Content Copying and Extraction
993
994
    // Allowed changes menu:
995
    //   None
996
    //   Only Document Assembly
997
    //   Only Form Field Fill-in or Signing
998
    //   Comment Authoring, Form Field Fill-in or Signing
999
    //   General Editing, Comment and Form Field Authoring
1000
1001
    // Allowed printing menu:
1002
    //   None
1003
    //   Low Resolution
1004
    //   Full printing
1005
1006
    // Meanings of bits in P when R >= 3
1007
    //
1008
    //  3: low-resolution printing
1009
    //  4: document modification except as controlled by 6, 9, and 11
1010
    //  5: extraction
1011
    //  6: add/modify annotations (comment), fill in forms
1012
    //     if 4+6 are set, also allows modification of form fields
1013
    //  9: fill in forms even if 6 is clear
1014
    // 10: accessibility; ignored by readers, should always be set
1015
    // 11: document assembly even if 4 is clear
1016
    // 12: high-resolution printing
1017
0
    if (!allow_accessibility && encryption->getR() <= 3) {
1018
        // Bit 10 is deprecated and should always be set.  This used to mean accessibility.  There
1019
        // is no way to disable accessibility with R > 3.
1020
0
        encryption->setP(10, false);
1021
0
    }
1022
0
    if (!allow_extract) {
1023
0
        encryption->setP(5, false);
1024
0
    }
1025
1026
0
    switch (print) {
1027
0
    case qpdf_r3p_none:
1028
0
        encryption->setP(3, false); // any printing
1029
0
        [[fallthrough]];
1030
0
    case qpdf_r3p_low:
1031
0
        encryption->setP(12, false); // high resolution printing
1032
0
        [[fallthrough]];
1033
0
    case qpdf_r3p_full:
1034
0
        break;
1035
        // no default so gcc warns for missing cases
1036
0
    }
1037
1038
    // Modify options. The qpdf_r3_modify_e options control groups of bits and lack the full
1039
    // flexibility of the spec. This is unfortunate, but it's been in the API for ages, and we're
1040
    // stuck with it. See also allow checks below to control the bits individually.
1041
1042
    // NOT EXERCISED IN TEST SUITE
1043
0
    switch (modify) {
1044
0
    case qpdf_r3m_none:
1045
0
        encryption->setP(11, false); // document assembly
1046
0
        [[fallthrough]];
1047
0
    case qpdf_r3m_assembly:
1048
0
        encryption->setP(9, false); // filling in form fields
1049
0
        [[fallthrough]];
1050
0
    case qpdf_r3m_form:
1051
0
        encryption->setP(6, false); // modify annotations, fill in form fields
1052
0
        [[fallthrough]];
1053
0
    case qpdf_r3m_annotate:
1054
0
        encryption->setP(4, false); // other modifications
1055
0
        [[fallthrough]];
1056
0
    case qpdf_r3m_all:
1057
0
        break;
1058
        // no default so gcc warns for missing cases
1059
0
    }
1060
    // END NOT EXERCISED IN TEST SUITE
1061
1062
0
    if (!allow_assemble) {
1063
0
        encryption->setP(11, false);
1064
0
    }
1065
0
    if (!allow_annotate_and_form) {
1066
0
        encryption->setP(6, false);
1067
0
    }
1068
0
    if (!allow_form_filling) {
1069
0
        encryption->setP(9, false);
1070
0
    }
1071
0
    if (!allow_modify_other) {
1072
0
        encryption->setP(4, false);
1073
0
    }
1074
0
}
1075
1076
void
1077
impl::Writer::setEncryptionParameters(char const* user_password, char const* owner_password)
1078
0
{
1079
0
    generateID(true);
1080
0
    encryption->setId1(id1);
1081
0
    encryption_key = encryption->compute_parameters(user_password, owner_password);
1082
0
    setEncryptionMinimumVersion();
1083
0
}
1084
1085
void
1086
QPDFWriter::copyEncryptionParameters(QPDF& qpdf)
1087
0
{
1088
0
    m->copyEncryptionParameters(qpdf);
1089
0
}
1090
1091
void
1092
impl::Writer::copyEncryptionParameters(QPDF& qpdf)
1093
0
{
1094
0
    cfg.preserve_encryption(false);
1095
0
    QPDFObjectHandle trailer = qpdf.getTrailer();
1096
0
    if (trailer.hasKey("/Encrypt")) {
1097
0
        generateID(true);
1098
0
        id1 = trailer.getKey("/ID").getArrayItem(0).getStringValue();
1099
0
        QPDFObjectHandle encrypt = trailer.getKey("/Encrypt");
1100
0
        int V = encrypt.getKey("/V").getIntValueAsInt();
1101
0
        int key_len = 5;
1102
0
        if (V > 1) {
1103
0
            key_len = encrypt.getKey("/Length").getIntValueAsInt() / 8;
1104
0
        }
1105
0
        const bool encrypt_metadata =
1106
0
            encrypt.hasKey("/EncryptMetadata") && encrypt.getKey("/EncryptMetadata").isBool()
1107
0
            ? encrypt.getKey("/EncryptMetadata").getBoolValue()
1108
0
            : true;
1109
0
        if (V >= 4) {
1110
            // When copying encryption parameters, use AES even if the original file did not.
1111
            // Acrobat doesn't create files with V >= 4 that don't use AES, and the logic of
1112
            // figuring out whether AES is used or not is complicated with /StmF, /StrF, and /EFF
1113
            // all potentially having different values.
1114
0
            cfg.encrypt_use_aes(true);
1115
0
        }
1116
0
        QTC::TC("qpdf", "QPDFWriter copy encrypt metadata", encrypt_metadata ? 0 : 1);
1117
0
        QTC::TC("qpdf", "QPDFWriter copy use_aes", cfg.encrypt_use_aes() ? 0 : 1);
1118
1119
0
        encryption = std::make_unique<Encryption>(
1120
0
            V,
1121
0
            encrypt.getKey("/R").getIntValueAsInt(),
1122
0
            key_len,
1123
0
            static_cast<int>(encrypt.getKey("/P").getIntValue()),
1124
0
            encrypt.getKey("/O").getStringValue(),
1125
0
            encrypt.getKey("/U").getStringValue(),
1126
0
            V < 5 ? "" : encrypt.getKey("/OE").getStringValue(),
1127
0
            V < 5 ? "" : encrypt.getKey("/UE").getStringValue(),
1128
0
            V < 5 ? "" : encrypt.getKey("/Perms").getStringValue(),
1129
0
            id1, // id1 == the other file's id1
1130
0
            encrypt_metadata);
1131
0
        encryption_key = V >= 5 ? qpdf.getEncryptionKey()
1132
0
                                : encryption->compute_encryption_key(qpdf.getPaddedUserPassword());
1133
0
        setEncryptionMinimumVersion();
1134
0
    }
1135
0
}
1136
1137
void
1138
impl::Writer::disableIncompatibleEncryption(int major, int minor, int extension_level)
1139
0
{
1140
0
    if (!encryption) {
1141
0
        return;
1142
0
    }
1143
0
    if (compareVersions(major, minor, 1, 3) < 0) {
1144
0
        encryption = nullptr;
1145
0
        return;
1146
0
    }
1147
0
    int V = encryption->getV();
1148
0
    int R = encryption->getR();
1149
0
    if (compareVersions(major, minor, 1, 4) < 0) {
1150
0
        if (V > 1 || R > 2) {
1151
0
            encryption = nullptr;
1152
0
        }
1153
0
    } else if (compareVersions(major, minor, 1, 5) < 0) {
1154
0
        if (V > 2 || R > 3) {
1155
0
            encryption = nullptr;
1156
0
        }
1157
0
    } else if (compareVersions(major, minor, 1, 6) < 0) {
1158
0
        if (cfg.encrypt_use_aes()) {
1159
0
            encryption = nullptr;
1160
0
        }
1161
0
    } else if (
1162
0
        (compareVersions(major, minor, 1, 7) < 0) ||
1163
0
        ((compareVersions(major, minor, 1, 7) == 0) && extension_level < 3)) {
1164
0
        if (V >= 5 || R >= 5) {
1165
0
            encryption = nullptr;
1166
0
        }
1167
0
    }
1168
1169
0
    if (!encryption) {
1170
0
        QTC::TC("qpdf", "QPDFWriter forced version disabled encryption");
1171
0
    }
1172
0
}
1173
1174
void
1175
impl::Writer::parseVersion(std::string const& version, int& major, int& minor) const
1176
784
{
1177
784
    major = QUtil::string_to_int(version.c_str());
1178
784
    minor = 0;
1179
784
    size_t p = version.find('.');
1180
784
    if ((p != std::string::npos) && (version.length() > p)) {
1181
784
        minor = QUtil::string_to_int(version.substr(p + 1).c_str());
1182
784
    }
1183
784
    std::string tmp = std::to_string(major) + "." + std::to_string(minor);
1184
784
    if (tmp != version) {
1185
        // The version number in the input is probably invalid. This happens with some files that
1186
        // are designed to exercise bugs, such as files in the fuzzer corpus. Unfortunately
1187
        // QPDFWriter doesn't have a way to give a warning, so we just ignore this case.
1188
16
    }
1189
784
}
1190
1191
int
1192
impl::Writer::compareVersions(int major1, int minor1, int major2, int minor2) const
1193
386
{
1194
386
    if (major1 < major2) {
1195
4
        return -1;
1196
4
    }
1197
382
    if (major1 > major2) {
1198
26
        return 1;
1199
26
    }
1200
356
    if (minor1 < minor2) {
1201
298
        return -1;
1202
298
    }
1203
58
    return minor1 > minor2 ? 1 : 0;
1204
356
}
1205
1206
void
1207
impl::Writer::setEncryptionMinimumVersion()
1208
0
{
1209
0
    auto const R = encryption->getR();
1210
0
    if (R >= 6) {
1211
0
        setMinimumPDFVersion("1.7", 8);
1212
0
    } else if (R == 5) {
1213
0
        setMinimumPDFVersion("1.7", 3);
1214
0
    } else if (R == 4) {
1215
0
        setMinimumPDFVersion(cfg.encrypt_use_aes() ? "1.6" : "1.5");
1216
0
    } else if (R == 3) {
1217
0
        setMinimumPDFVersion("1.4");
1218
0
    } else {
1219
0
        setMinimumPDFVersion("1.3");
1220
0
    }
1221
0
}
1222
1223
void
1224
impl::Writer::setDataKey(int objid)
1225
79.0k
{
1226
79.0k
    if (encryption) {
1227
0
        cur_data_key = QPDF::compute_data_key(
1228
0
            encryption_key,
1229
0
            objid,
1230
0
            0,
1231
0
            cfg.encrypt_use_aes(),
1232
0
            encryption->getV(),
1233
0
            encryption->getR());
1234
0
    }
1235
79.0k
}
1236
1237
unsigned int
1238
impl::Writer::bytesNeeded(long long n)
1239
1.05k
{
1240
1.05k
    unsigned int bytes = 0;
1241
2.36k
    while (n) {
1242
1.31k
        ++bytes;
1243
1.31k
        n >>= 8;
1244
1.31k
    }
1245
1.05k
    return bytes;
1246
1.05k
}
1247
1248
void
1249
impl::Writer::writeBinary(unsigned long long val, unsigned int bytes)
1250
115k
{
1251
115k
    if (bytes > sizeof(unsigned long long)) {
1252
0
        throw std::logic_error("QPDFWriter::writeBinary called with too many bytes");
1253
0
    }
1254
115k
    unsigned char data[sizeof(unsigned long long)];
1255
277k
    for (unsigned int i = 0; i < bytes; ++i) {
1256
162k
        data[bytes - i - 1] = static_cast<unsigned char>(val & 0xff);
1257
162k
        val >>= 8;
1258
162k
    }
1259
115k
    pipeline->write(data, bytes);
1260
115k
}
1261
1262
impl::Writer&
1263
impl::Writer::write(std::string_view str)
1264
3.52M
{
1265
3.52M
    pipeline->write(str);
1266
3.52M
    return *this;
1267
3.52M
}
1268
1269
impl::Writer&
1270
impl::Writer::write(std::integral auto val)
1271
441k
{
1272
441k
    pipeline->write(std::to_string(val));
1273
441k
    return *this;
1274
441k
}
_ZN4qpdf4impl6Writer5writeITkNSt3__18integralEiEERS1_T_
Line
Count
Source
1271
350k
{
1272
350k
    pipeline->write(std::to_string(val));
1273
350k
    return *this;
1274
350k
}
_ZN4qpdf4impl6Writer5writeITkNSt3__18integralExEERS1_T_
Line
Count
Source
1271
58.5k
{
1272
58.5k
    pipeline->write(std::to_string(val));
1273
58.5k
    return *this;
1274
58.5k
}
_ZN4qpdf4impl6Writer5writeITkNSt3__18integralEmEERS1_T_
Line
Count
Source
1271
31.1k
{
1272
31.1k
    pipeline->write(std::to_string(val));
1273
31.1k
    return *this;
1274
31.1k
}
_ZN4qpdf4impl6Writer5writeITkNSt3__18integralEjEERS1_T_
Line
Count
Source
1271
700
{
1272
700
    pipeline->write(std::to_string(val));
1273
700
    return *this;
1274
700
}
1275
1276
impl::Writer&
1277
impl::Writer::write(size_t count, char c)
1278
0
{
1279
0
    pipeline->write(count, c);
1280
0
    return *this;
1281
0
}
1282
1283
impl::Writer&
1284
impl::Writer::write_name(std::string const& str)
1285
273k
{
1286
273k
    pipeline->write(Name::normalize(str));
1287
273k
    return *this;
1288
273k
}
1289
1290
impl::Writer&
1291
impl::Writer::write_string(std::string const& str, bool force_binary)
1292
18.3k
{
1293
18.3k
    pipeline->write(QPDF_String(str).unparse(force_binary));
1294
18.3k
    return *this;
1295
18.3k
}
1296
1297
template <typename... Args>
1298
impl::Writer&
1299
impl::Writer::write_qdf(Args&&... args)
1300
226k
{
1301
226k
    if (cfg.qdf()) {
1302
226k
        pipeline->write(std::forward<Args>(args)...);
1303
226k
    }
1304
226k
    return *this;
1305
226k
}
qpdf::impl::Writer& qpdf::impl::Writer::write_qdf<char const (&) [2]>(char const (&) [2])
Line
Count
Source
1300
174k
{
1301
174k
    if (cfg.qdf()) {
1302
174k
        pipeline->write(std::forward<Args>(args)...);
1303
174k
    }
1304
174k
    return *this;
1305
174k
}
qpdf::impl::Writer& qpdf::impl::Writer::write_qdf<char const (&) [3]>(char const (&) [3])
Line
Count
Source
1300
33.2k
{
1301
33.2k
    if (cfg.qdf()) {
1302
33.2k
        pipeline->write(std::forward<Args>(args)...);
1303
33.2k
    }
1304
33.2k
    return *this;
1305
33.2k
}
qpdf::impl::Writer& qpdf::impl::Writer::write_qdf<char const (&) [4]>(char const (&) [4])
Line
Count
Source
1300
9.18k
{
1301
9.18k
    if (cfg.qdf()) {
1302
9.18k
        pipeline->write(std::forward<Args>(args)...);
1303
9.18k
    }
1304
9.18k
    return *this;
1305
9.18k
}
qpdf::impl::Writer& qpdf::impl::Writer::write_qdf<char const (&) [11]>(char const (&) [11])
Line
Count
Source
1300
9.28k
{
1301
9.28k
    if (cfg.qdf()) {
1302
9.28k
        pipeline->write(std::forward<Args>(args)...);
1303
9.28k
    }
1304
9.28k
    return *this;
1305
9.28k
}
1306
1307
template <typename... Args>
1308
impl::Writer&
1309
impl::Writer::write_no_qdf(Args&&... args)
1310
63.9k
{
1311
63.9k
    if (!cfg.qdf()) {
1312
0
        pipeline->write(std::forward<Args>(args)...);
1313
0
    }
1314
63.9k
    return *this;
1315
63.9k
}
qpdf::impl::Writer& qpdf::impl::Writer::write_no_qdf<char const (&) [2]>(char const (&) [2])
Line
Count
Source
1310
54.7k
{
1311
54.7k
    if (!cfg.qdf()) {
1312
0
        pipeline->write(std::forward<Args>(args)...);
1313
0
    }
1314
54.7k
    return *this;
1315
54.7k
}
qpdf::impl::Writer& qpdf::impl::Writer::write_no_qdf<char const (&) [4]>(char const (&) [4])
Line
Count
Source
1310
9.18k
{
1311
9.18k
    if (!cfg.qdf()) {
1312
0
        pipeline->write(std::forward<Args>(args)...);
1313
0
    }
1314
9.18k
    return *this;
1315
9.18k
}
1316
1317
void
1318
impl::Writer::adjustAESStreamLength(size_t& length)
1319
26.4k
{
1320
26.4k
    if (encryption && !cur_data_key.empty() && cfg.encrypt_use_aes()) {
1321
        // Stream length will be padded with 1 to 16 bytes to end up as a multiple of 16.  It will
1322
        // also be prepended by 16 bits of random data.
1323
0
        length += 32 - (length & 0xf);
1324
0
    }
1325
26.4k
}
1326
1327
impl::Writer&
1328
impl::Writer::write_encrypted(std::string_view str)
1329
26.3k
{
1330
26.3k
    if (!(encryption && !cur_data_key.empty())) {
1331
26.3k
        write(str);
1332
26.3k
    } else if (cfg.encrypt_use_aes()) {
1333
0
        write(pl::pipe<Pl_AES_PDF>(str, true, cur_data_key));
1334
0
    } else {
1335
0
        write(pl::pipe<Pl_RC4>(str, cur_data_key));
1336
0
    }
1337
1338
26.3k
    return *this;
1339
26.3k
}
1340
1341
void
1342
impl::Writer::computeDeterministicIDData()
1343
9.18k
{
1344
9.18k
    if (!id2.empty()) {
1345
        // Can't happen in the code
1346
0
        throw std::logic_error(
1347
0
            "Deterministic ID computation enabled after ID generation has already occurred.");
1348
0
    }
1349
9.18k
    qpdf_assert_debug(deterministic_id_data.empty());
1350
9.18k
    deterministic_id_data = pipeline_stack.hex_digest();
1351
9.18k
}
1352
1353
int
1354
impl::Writer::openObject(int objid)
1355
101k
{
1356
101k
    if (objid == 0) {
1357
0
        objid = next_objid++;
1358
0
    }
1359
101k
    new_obj[objid].xref = QPDFXRefEntry(pipeline->getCount());
1360
101k
    write(objid).write(" 0 obj\n");
1361
101k
    return objid;
1362
101k
}
1363
1364
void
1365
impl::Writer::closeObject(int objid)
1366
101k
{
1367
    // Write a newline before endobj as it makes the file easier to repair.
1368
101k
    write("\nendobj\n").write_qdf("\n");
1369
101k
    auto& no = new_obj[objid];
1370
101k
    no.length = pipeline->getCount() - no.xref.getOffset();
1371
101k
}
1372
1373
void
1374
impl::Writer::assignCompressedObjectNumbers(QPDFObjGen og)
1375
4.47k
{
1376
4.47k
    int objid = og.getObj();
1377
4.47k
    if (og.getGen() != 0 || !object_stream_to_objects.contains(objid)) {
1378
        // This is not an object stream.
1379
0
        return;
1380
0
    }
1381
1382
    // Reserve numbers for the objects that belong to this object stream.
1383
22.5k
    for (auto const& iter: object_stream_to_objects[objid]) {
1384
22.5k
        obj[iter].renumber = next_objid++;
1385
22.5k
    }
1386
4.47k
}
1387
1388
void
1389
impl::Writer::enqueue(QPDFObjectHandle const& object)
1390
3.55M
{
1391
3.55M
    if (object.indirect()) {
1392
219k
        util::assertion(
1393
            // This owner check can only be done for indirect objects. It is possible for a direct
1394
            // object to have an owning QPDF that is from another file if a direct QPDFObjectHandle
1395
            // from one file was insert into another file without copying. Doing that is safe even
1396
            // if the original QPDF gets destroyed, which just disconnects the QPDFObjectHandle from
1397
            // its owner.
1398
219k
            object.qpdf() == &qpdf,
1399
219k
            "QPDFObjectHandle from different QPDF found while writing.  "
1400
219k
            "Use QPDF::copyForeignObject to add objects from another file." //
1401
219k
        );
1402
1403
219k
        if (cfg.qdf() && object.isStreamOfType("/XRef")) {
1404
            // As a special case, do not output any extraneous XRef streams in QDF mode. Doing so
1405
            // will confuse fix-qdf, which expects to see only one XRef stream at the end of the
1406
            // file. This case can occur when creating a QDF from a file with object streams when
1407
            // preserving unreferenced objects since the old cross reference streams are not
1408
            // actually referenced by object number.
1409
5.02k
            return;
1410
5.02k
        }
1411
1412
214k
        QPDFObjGen og = object.getObjGen();
1413
214k
        auto& o = obj[og];
1414
1415
214k
        if (o.renumber == 0) {
1416
83.9k
            if (o.object_stream > 0) {
1417
                // This is in an object stream.  Don't process it here.  Instead, enqueue the object
1418
                // stream.  Object streams always have generation 0.
1419
                // Detect loops by storing invalid object ID -1, which will get overwritten later.
1420
4.84k
                o.renumber = -1;
1421
4.84k
                enqueue(qpdf.getObject(o.object_stream, 0));
1422
79.0k
            } else {
1423
79.0k
                object_queue.emplace_back(object);
1424
79.0k
                o.renumber = next_objid++;
1425
1426
79.0k
                if (og.getGen() == 0 && object_stream_to_objects.contains(og.getObj())) {
1427
                    // For linearized files, uncompressed objects go at end, and we take care of
1428
                    // assigning numbers to them elsewhere.
1429
4.47k
                    if (!cfg.linearize()) {
1430
4.47k
                        assignCompressedObjectNumbers(og);
1431
4.47k
                    }
1432
74.5k
                } else if (!cfg.direct_stream_lengths() && object.isStream()) {
1433
                    // reserve next object ID for length
1434
21.9k
                    ++next_objid;
1435
21.9k
                }
1436
79.0k
            }
1437
83.9k
        }
1438
214k
        return;
1439
219k
    }
1440
1441
3.33M
    if (cfg.linearize()) {
1442
0
        return;
1443
0
    }
1444
1445
3.33M
    if (Array array = object) {
1446
1.32M
        for (auto& item: array) {
1447
1.32M
            enqueue(item);
1448
1.32M
        }
1449
531k
        return;
1450
531k
    }
1451
1452
2.79M
    for (auto const& item: Dictionary(object)) {
1453
1.97M
        if (!item.second.null()) {
1454
1.31M
            enqueue(item.second);
1455
1.31M
        }
1456
1.97M
    }
1457
2.79M
}
1458
1459
void
1460
impl::Writer::unparseChild(QPDFObjectHandle const& child, size_t level, int flags)
1461
881k
{
1462
881k
    if (!cfg.linearize()) {
1463
881k
        enqueue(child);
1464
881k
    }
1465
881k
    if (child.indirect()) {
1466
119k
        write(obj[child].renumber).write(" 0 R");
1467
761k
    } else {
1468
761k
        unparseObject(child, level, flags);
1469
761k
    }
1470
881k
}
1471
1472
void
1473
impl::Writer::writeTrailer(
1474
    trailer_e which, int size, bool xref_stream, qpdf_offset_t prev, int linearization_pass)
1475
9.18k
{
1476
9.18k
    auto trailer = trimmed_trailer();
1477
9.18k
    if (xref_stream) {
1478
350
        cur_data_key.clear();
1479
8.83k
    } else {
1480
8.83k
        write("trailer <<");
1481
8.83k
    }
1482
9.18k
    write_qdf("\n");
1483
9.18k
    if (which == t_lin_second) {
1484
0
        write(" /Size ").write(size);
1485
9.18k
    } else {
1486
16.4k
        for (auto const& [key, value]: trailer) {
1487
16.4k
            if (value.null()) {
1488
2.17k
                continue;
1489
2.17k
            }
1490
14.3k
            write_qdf("  ").write_no_qdf(" ").write_name(key).write(" ");
1491
14.3k
            if (key == "/Size") {
1492
1.61k
                write(size);
1493
1.61k
                if (which == t_lin_first) {
1494
0
                    write(" /Prev ");
1495
0
                    qpdf_offset_t pos = pipeline->getCount();
1496
0
                    write(prev).write(QIntC::to_size(pos - pipeline->getCount() + 21), ' ');
1497
0
                }
1498
12.6k
            } else {
1499
12.6k
                unparseChild(value, 1, 0);
1500
12.6k
            }
1501
14.3k
            write_qdf("\n");
1502
14.3k
        }
1503
9.18k
    }
1504
1505
    // Write ID
1506
9.18k
    write_qdf(" ").write(" /ID [");
1507
9.18k
    if (linearization_pass == 1) {
1508
0
        std::string original_id1 = getOriginalID1();
1509
0
        if (original_id1.empty()) {
1510
0
            write("<00000000000000000000000000000000>");
1511
0
        } else {
1512
            // Write a string of zeroes equal in length to the representation of the original ID.
1513
            // While writing the original ID would have the same number of bytes, it would cause a
1514
            // change to the deterministic ID generated by older versions of the software that
1515
            // hard-coded the length of the ID to 16 bytes.
1516
0
            size_t len = QPDF_String(original_id1).unparse(true).length() - 2;
1517
0
            write("<").write(len, '0').write(">");
1518
0
        }
1519
0
        write("<00000000000000000000000000000000>");
1520
9.18k
    } else {
1521
9.18k
        if (linearization_pass == 0 && cfg.deterministic_id()) {
1522
9.18k
            computeDeterministicIDData();
1523
9.18k
        }
1524
9.18k
        generateID(encryption.get());
1525
9.18k
        write_string(id1, true).write_string(id2, true);
1526
9.18k
    }
1527
9.18k
    write("]");
1528
1529
9.18k
    if (which != t_lin_second) {
1530
        // Write reference to encryption dictionary
1531
9.18k
        if (encryption) {
1532
0
            write(" /Encrypt ").write(encryption_dict_objid).write(" 0 R");
1533
0
        }
1534
9.18k
    }
1535
1536
9.18k
    write_qdf("\n>>").write_no_qdf(" >>");
1537
9.18k
}
1538
1539
bool
1540
impl::Writer::will_filter_stream(QPDFObjectHandle stream)
1541
0
{
1542
0
    std::string s;
1543
0
    [[maybe_unused]] auto [filter, ignore1, ignore2] = will_filter_stream(stream, &s);
1544
0
    return filter;
1545
0
}
1546
1547
std::tuple<const bool, const bool, const bool>
1548
impl::Writer::will_filter_stream(QPDFObjectHandle stream, std::string* stream_data)
1549
21.9k
{
1550
21.9k
    const bool is_root_metadata = stream.isRootMetadata();
1551
21.9k
    bool filter = false;
1552
21.9k
    auto decode_level = cfg.decode_level();
1553
21.9k
    int encode_flags = 0;
1554
21.9k
    Dictionary stream_dict = stream.getDict();
1555
1556
21.9k
    if (stream.getFilterOnWrite()) {
1557
21.9k
        filter = stream.isDataModified() || cfg.compress_streams() || decode_level != qpdf_dl_none;
1558
21.9k
        if (cfg.compress_streams()) {
1559
            // Don't filter if the stream is already compressed with FlateDecode. This way we don't
1560
            // make it worse if the original file used a better Flate algorithm, and we don't spend
1561
            // time and CPU cycles uncompressing and recompressing stuff. This can be overridden
1562
            // with setRecompressFlate(true).
1563
0
            auto Filter = stream_dict["/Filter"];
1564
0
            Name filter_name = Filter.size() == 1 ? Filter[0] : QPDFObjectHandle();
1565
0
            if (filter_name && !cfg.recompress_flate() && !stream.isDataModified() &&
1566
0
                (filter_name == "/FlateDecode" || filter_name == "/Fl")) {
1567
0
                filter = false;
1568
0
            }
1569
0
        }
1570
21.9k
        if (is_root_metadata && (!encryption || !encryption->getEncryptMetadata())) {
1571
57
            filter = true;
1572
57
            decode_level = qpdf_dl_all;
1573
21.9k
        } else if (cfg.normalize_content() && normalized_streams.contains(stream)) {
1574
3.62k
            encode_flags = qpdf_ef_normalize;
1575
3.62k
            filter = true;
1576
18.3k
        } else if (filter && cfg.compress_streams()) {
1577
0
            encode_flags = qpdf_ef_compress;
1578
0
        }
1579
21.9k
    }
1580
1581
    // Disable compression for empty streams to improve compatibility
1582
21.9k
    if (Integer(stream_dict["/Length"]) == 0) {
1583
25
        filter = true;
1584
25
        encode_flags = 0;
1585
25
    }
1586
1587
34.1k
    for (bool first_attempt: {true, false}) {
1588
34.1k
        auto pp_stream_data =
1589
34.1k
            stream_data ? pipeline_stack.activate(*stream_data) : pipeline_stack.activate(true);
1590
1591
34.1k
        try {
1592
34.1k
            if (stream.pipeStreamData(
1593
34.1k
                    pipeline,
1594
34.1k
                    filter ? encode_flags : 0,
1595
34.1k
                    filter ? decode_level : qpdf_dl_none,
1596
34.1k
                    false,
1597
34.1k
                    first_attempt)) {
1598
9.79k
                return {true, encode_flags & qpdf_ef_compress, is_root_metadata};
1599
9.79k
            }
1600
24.4k
            if (!filter) {
1601
12.1k
                break;
1602
12.1k
            }
1603
24.4k
        } catch (std::runtime_error& e) {
1604
17
            if (!(filter && first_attempt)) {
1605
5
                throw std::runtime_error(
1606
5
                    "error while getting stream data for " + stream.unparse() + ": " + e.what());
1607
5
            }
1608
12
            stream.warn("error while getting stream data: "s + e.what());
1609
12
            stream.warn("qpdf will attempt to write the damaged stream unchanged");
1610
12
        }
1611
        // Try again
1612
12.2k
        filter = false;
1613
12.2k
        stream.setFilterOnWrite(false);
1614
12.2k
        if (stream_data) {
1615
12.2k
            stream_data->clear();
1616
12.2k
        }
1617
12.2k
    }
1618
12.1k
    return {false, false, is_root_metadata};
1619
21.9k
}
1620
1621
void
1622
impl::Writer::unparseObject(
1623
    QPDFObjectHandle object, size_t level, int flags, size_t stream_length, bool compress)
1624
880k
{
1625
880k
    QPDFObjGen old_og = object.getObjGen();
1626
880k
    int child_flags = flags & ~f_stream;
1627
    // For non-qdf, "indent" and "indent_large" are a single space between tokens. For qdf, they
1628
    // include the preceding newline.
1629
880k
    std::string indent_large = " ";
1630
880k
    if (cfg.qdf()) {
1631
880k
        indent_large.append(2 * (level + 1), ' ');
1632
880k
        indent_large[0] = '\n';
1633
880k
    }
1634
880k
    std::string_view indent{indent_large.data(), cfg.qdf() ? indent_large.size() - 2 : 1};
1635
1636
880k
    if (auto const tc = object.getTypeCode(); tc == ::ot_array) {
1637
        // Note: PDF spec 1.4 implementation note 121 states that Acrobat requires a space after the
1638
        // [ in the /H key of the linearization parameter dictionary.  We'll do this unconditionally
1639
        // for all arrays because it looks nicer and doesn't make the files that much bigger.
1640
49.4k
        write("[");
1641
609k
        for (auto const& item: object.as_array()) {
1642
609k
            write(indent_large);
1643
609k
            unparseChild(item, level + 1, child_flags);
1644
609k
        }
1645
49.4k
        write(indent).write("]");
1646
831k
    } else if (tc == ::ot_dictionary) {
1647
        // Handle special cases for specific dictionaries.
1648
1649
93.4k
        if (old_og == root_og) {
1650
            // Extensions dictionaries.
1651
1652
            // We have one of several cases:
1653
            //
1654
            // * We need ADBE
1655
            //    - We already have Extensions
1656
            //       - If it has the right ADBE, preserve it
1657
            //       - Otherwise, replace ADBE
1658
            //    - We don't have Extensions: create one from scratch
1659
            // * We don't want ADBE
1660
            //    - We already have Extensions
1661
            //       - If it only has ADBE, remove it
1662
            //       - If it has other things, keep those and remove ADBE
1663
            //    - We have no extensions: no action required
1664
            //
1665
            // Before writing, we guarantee that /Extensions, if present, is direct through the ADBE
1666
            // dictionary, so we can modify in place.
1667
1668
8.85k
            auto extensions = object.getKey("/Extensions");
1669
8.85k
            const bool has_extensions = extensions.isDictionary();
1670
8.85k
            const bool need_extensions_adbe = final_extension_level > 0;
1671
1672
8.85k
            if (has_extensions || need_extensions_adbe) {
1673
                // Make a shallow copy of this object so we can modify it safely without affecting
1674
                // the original. This code has logic to skip certain keys in agreement with
1675
                // prepareFileForWrite and with skip_stream_parameters so that replacing them
1676
                // doesn't leave unreferenced objects in the output. We can use unsafeShallowCopy
1677
                // here because all we are doing is removing or replacing top-level keys.
1678
198
                object = object.unsafeShallowCopy();
1679
198
                if (!has_extensions) {
1680
0
                    extensions = QPDFObjectHandle();
1681
0
                }
1682
1683
198
                const bool have_extensions_adbe = extensions && extensions.hasKey("/ADBE");
1684
198
                const bool have_extensions_other =
1685
198
                    extensions && extensions.getKeys().size() > (have_extensions_adbe ? 1u : 0u);
1686
1687
198
                if (need_extensions_adbe) {
1688
65
                    if (!(have_extensions_other || have_extensions_adbe)) {
1689
                        // We need Extensions and don't have it.  Create it here.
1690
0
                        QTC::TC("qpdf", "QPDFWriter create Extensions", cfg.qdf() ? 0 : 1);
1691
0
                        extensions = object.replaceKeyAndGetNew(
1692
0
                            "/Extensions", QPDFObjectHandle::newDictionary());
1693
0
                    }
1694
133
                } else if (!have_extensions_other) {
1695
                    // We have Extensions dictionary and don't want one.
1696
4
                    if (have_extensions_adbe) {
1697
2
                        QTC::TC("qpdf", "QPDFWriter remove existing Extensions");
1698
2
                        object.removeKey("/Extensions");
1699
2
                        extensions = QPDFObjectHandle(); // uninitialized
1700
2
                    }
1701
4
                }
1702
1703
198
                if (extensions) {
1704
196
                    QTC::TC("qpdf", "QPDFWriter preserve Extensions");
1705
196
                    QPDFObjectHandle adbe = extensions.getKey("/ADBE");
1706
196
                    if (adbe.isDictionary() &&
1707
67
                        adbe.getKey("/BaseVersion").isNameAndEquals("/" + final_pdf_version) &&
1708
48
                        adbe.getKey("/ExtensionLevel").isInteger() &&
1709
47
                        (adbe.getKey("/ExtensionLevel").getIntValue() == final_extension_level)) {
1710
191
                    } else {
1711
191
                        if (need_extensions_adbe) {
1712
60
                            extensions.replaceKey(
1713
60
                                "/ADBE",
1714
60
                                QPDFObjectHandle::parse(
1715
60
                                    "<< /BaseVersion /" + final_pdf_version + " /ExtensionLevel " +
1716
60
                                    std::to_string(final_extension_level) + " >>"));
1717
131
                        } else {
1718
131
                            extensions.removeKey("/ADBE");
1719
131
                        }
1720
191
                    }
1721
196
                }
1722
198
            }
1723
8.85k
        }
1724
1725
        // Stream dictionaries.
1726
1727
93.4k
        if (flags & f_stream) {
1728
            // Suppress /Length since we will write it manually
1729
1730
            // Make a shallow copy of this object so we can modify it safely without affecting the
1731
            // original. This code has logic to skip certain keys in agreement with
1732
            // prepareFileForWrite and with skip_stream_parameters so that replacing them doesn't
1733
            // leave unreferenced objects in the output. We can use unsafeShallowCopy here because
1734
            // all we are doing is removing or replacing top-level keys.
1735
21.9k
            object = object.unsafeShallowCopy();
1736
1737
21.9k
            object.removeKey("/Length");
1738
1739
            // If /DecodeParms is an empty list, remove it.
1740
21.9k
            if (object.getKey("/DecodeParms").empty()) {
1741
21.3k
                object.removeKey("/DecodeParms");
1742
21.3k
            }
1743
1744
21.9k
            if (flags & f_filtered) {
1745
                // We will supply our own filter and decode parameters.
1746
9.79k
                object.removeKey("/Filter");
1747
9.79k
                object.removeKey("/DecodeParms");
1748
12.1k
            } else {
1749
                // Make sure, no matter what else we have, that we don't have /Crypt in the output
1750
                // filters.
1751
12.1k
                QPDFObjectHandle filter = object.getKey("/Filter");
1752
12.1k
                QPDFObjectHandle decode_parms = object.getKey("/DecodeParms");
1753
12.1k
                if (filter.isOrHasName("/Crypt")) {
1754
271
                    if (filter.isName()) {
1755
45
                        object.removeKey("/Filter");
1756
45
                        object.removeKey("/DecodeParms");
1757
226
                    } else {
1758
226
                        int idx = 0;
1759
37.4k
                        for (auto const& item: filter.as_array()) {
1760
37.4k
                            if (item.isNameAndEquals("/Crypt")) {
1761
                                // If filter is an array, then the code in QPDF_Stream has already
1762
                                // verified that DecodeParms and Filters are arrays of the same
1763
                                // length, but if they weren't for some reason, eraseItem does type
1764
                                // and bounds checking. Fuzzing tells us that this can actually
1765
                                // happen.
1766
226
                                filter.eraseItem(idx);
1767
226
                                decode_parms.eraseItem(idx);
1768
226
                                break;
1769
226
                            }
1770
37.2k
                            ++idx;
1771
37.2k
                        }
1772
226
                    }
1773
271
                }
1774
12.1k
            }
1775
21.9k
        }
1776
1777
93.4k
        write("<<");
1778
1779
307k
        for (auto const& [key, value]: object.as_dictionary()) {
1780
307k
            if (!value.null()) {
1781
259k
                write(indent_large).write_name(key).write(" ");
1782
259k
                if (key == "/Contents" && object.isDictionaryOfType("/Sig") &&
1783
174
                    object.hasKey("/ByteRange")) {
1784
171
                    QTC::TC("qpdf", "QPDFWriter no encryption sig contents");
1785
171
                    unparseChild(value, level + 1, child_flags | f_hex_string | f_no_encryption);
1786
259k
                } else {
1787
259k
                    unparseChild(value, level + 1, child_flags);
1788
259k
                }
1789
259k
            }
1790
307k
        }
1791
1792
93.4k
        if (flags & f_stream) {
1793
21.9k
            write(indent_large).write("/Length ");
1794
1795
21.9k
            if (cfg.direct_stream_lengths()) {
1796
0
                write(stream_length);
1797
21.9k
            } else {
1798
21.9k
                write(cur_stream_length_id).write(" 0 R");
1799
21.9k
            }
1800
21.9k
            if (compress && (flags & f_filtered)) {
1801
0
                write(indent_large).write("/Filter /FlateDecode");
1802
0
            }
1803
21.9k
        }
1804
1805
93.4k
        write(indent).write(">>");
1806
738k
    } else if (tc == ::ot_stream) {
1807
        // Write stream data to a buffer.
1808
21.9k
        if (!cfg.direct_stream_lengths()) {
1809
21.9k
            cur_stream_length_id = obj[old_og].renumber + 1;
1810
21.9k
        }
1811
1812
21.9k
        flags |= f_stream;
1813
21.9k
        std::string stream_data;
1814
21.9k
        auto [filter, compress_stream, is_root_metadata] = will_filter_stream(object, &stream_data);
1815
21.9k
        if (filter) {
1816
9.79k
            flags |= f_filtered;
1817
9.79k
        }
1818
21.9k
        QPDFObjectHandle stream_dict = object.getDict();
1819
1820
21.9k
        cur_stream_length = stream_data.size();
1821
21.9k
        if (is_root_metadata && encryption && !encryption->getEncryptMetadata()) {
1822
            // Don't encrypt stream data for the metadata stream
1823
0
            cur_data_key.clear();
1824
0
        }
1825
21.9k
        adjustAESStreamLength(cur_stream_length);
1826
21.9k
        unparseObject(stream_dict, 0, flags, cur_stream_length, compress_stream);
1827
21.9k
        char last_char = stream_data.empty() ? '\0' : stream_data.back();
1828
21.9k
        write("\nstream\n").write_encrypted(stream_data);
1829
21.9k
        added_newline = cfg.newline_before_endstream() || (cfg.qdf() && last_char != '\n');
1830
21.9k
        write(added_newline ? "\nendstream" : "endstream");
1831
716k
    } else if (tc == ::ot_string) {
1832
11.6k
        std::string val;
1833
11.6k
        if (encryption && !(flags & f_in_ostream) && !(flags & f_no_encryption) &&
1834
0
            !cur_data_key.empty()) {
1835
0
            val = object.getStringValue();
1836
0
            if (cfg.encrypt_use_aes()) {
1837
0
                Pl_Buffer bufpl("encrypted string");
1838
0
                Pl_AES_PDF pl("aes encrypt string", &bufpl, true, cur_data_key);
1839
0
                pl.writeString(val);
1840
0
                pl.finish();
1841
0
                val = QPDF_String(bufpl.getString()).unparse(true);
1842
0
            } else {
1843
0
                auto tmp_ph = QUtil::make_unique_cstr(val);
1844
0
                char* tmp = tmp_ph.get();
1845
0
                size_t vlen = val.length();
1846
0
                RC4 rc4(
1847
0
                    QUtil::unsigned_char_pointer(cur_data_key),
1848
0
                    QIntC::to_int(cur_data_key.length()));
1849
0
                auto data = QUtil::unsigned_char_pointer(tmp);
1850
0
                rc4.process(data, vlen, data);
1851
0
                val = QPDF_String(std::string(tmp, vlen)).unparse();
1852
0
            }
1853
11.6k
        } else if (flags & f_hex_string) {
1854
171
            val = QPDF_String(object.getStringValue()).unparse(true);
1855
11.5k
        } else {
1856
11.5k
            val = object.unparseResolved();
1857
11.5k
        }
1858
11.6k
        write(val);
1859
704k
    } else {
1860
704k
        write(object.unparseResolved());
1861
704k
    }
1862
880k
}
1863
1864
void
1865
impl::Writer::writeObjectStreamOffsets(std::vector<qpdf_offset_t>& offsets, int first_obj)
1866
8.89k
{
1867
8.89k
    qpdf_assert_debug(first_obj > 0);
1868
8.89k
    bool is_first = true;
1869
8.89k
    auto id = std::to_string(first_obj) + ' ';
1870
44.9k
    for (auto& offset: offsets) {
1871
44.9k
        if (is_first) {
1872
8.89k
            is_first = false;
1873
36.0k
        } else {
1874
36.0k
            write_qdf("\n").write_no_qdf(" ");
1875
36.0k
        }
1876
44.9k
        write(id);
1877
44.9k
        util::increment(id, 1);
1878
44.9k
        write(offset);
1879
44.9k
    }
1880
8.89k
    write("\n");
1881
8.89k
}
1882
1883
void
1884
impl::Writer::writeObjectStream(QPDFObjectHandle object)
1885
4.44k
{
1886
    // Note: object might be null if this is a place-holder for an object stream that we are
1887
    // generating from scratch.
1888
1889
4.44k
    QPDFObjGen old_og = object.getObjGen();
1890
4.44k
    qpdf_assert_debug(old_og.getGen() == 0);
1891
4.44k
    int old_id = old_og.getObj();
1892
4.44k
    int new_stream_id = obj[old_og].renumber;
1893
1894
4.44k
    std::vector<qpdf_offset_t> offsets;
1895
4.44k
    qpdf_offset_t first = 0;
1896
1897
    // Generate stream itself.  We have to do this in two passes so we can calculate offsets in the
1898
    // first pass.
1899
4.44k
    std::string stream_buffer_pass1;
1900
4.44k
    std::string stream_buffer_pass2;
1901
4.44k
    int first_obj = -1;
1902
4.44k
    const bool compressed = cfg.compress_streams() && !cfg.qdf();
1903
4.44k
    {
1904
        // Pass 1
1905
4.44k
        auto pp_ostream_pass1 = pipeline_stack.activate(stream_buffer_pass1);
1906
1907
4.44k
        int count = -1;
1908
22.4k
        for (auto const& og: object_stream_to_objects[old_id]) {
1909
22.4k
            ++count;
1910
22.4k
            int new_o = obj[og].renumber;
1911
22.4k
            if (first_obj == -1) {
1912
4.44k
                first_obj = new_o;
1913
4.44k
            }
1914
22.4k
            if (cfg.qdf()) {
1915
22.4k
                write("%% Object stream: object ").write(new_o).write(", index ").write(count);
1916
22.4k
                if (!cfg.no_original_object_ids()) {
1917
22.4k
                    write("; original object ID: ").write(og.getObj());
1918
                    // For compatibility, only write the generation if non-zero.  While object
1919
                    // streams only allow objects with generation 0, if we are generating object
1920
                    // streams, the old object could have a non-zero generation.
1921
22.4k
                    if (og.getGen() != 0) {
1922
0
                        write(" ").write(og.getGen());
1923
0
                    }
1924
22.4k
                }
1925
22.4k
                write("\n");
1926
22.4k
            }
1927
1928
22.4k
            offsets.push_back(pipeline->getCount());
1929
            // To avoid double-counting objects being written in object streams for progress
1930
            // reporting, decrement in pass 1.
1931
22.4k
            indicateProgress(true, false);
1932
1933
22.4k
            QPDFObjectHandle obj_to_write = qpdf.getObject(og);
1934
22.4k
            if (obj_to_write.isStream()) {
1935
                // This condition occurred in a fuzz input. Ideally we should block it at parse
1936
                // time, but it's not clear to me how to construct a case for this.
1937
1
                obj_to_write.warn("stream found inside object stream; treating as null");
1938
1
                obj_to_write = QPDFObjectHandle::newNull();
1939
1
            }
1940
22.4k
            writeObject(obj_to_write, count);
1941
1942
22.4k
            new_obj[new_o].xref = QPDFXRefEntry(new_stream_id, count);
1943
22.4k
        }
1944
4.44k
    }
1945
4.44k
    {
1946
        // Adjust offsets to skip over comment before first object
1947
4.44k
        first = offsets.at(0);
1948
22.4k
        for (auto& iter: offsets) {
1949
22.4k
            iter -= first;
1950
22.4k
        }
1951
1952
        // Take one pass at writing pairs of numbers so we can get their size information
1953
4.44k
        {
1954
4.44k
            auto pp_discard = pipeline_stack.activate(true);
1955
4.44k
            writeObjectStreamOffsets(offsets, first_obj);
1956
4.44k
            first += pipeline->getCount();
1957
4.44k
        }
1958
1959
        // Set up a stream to write the stream data into a buffer.
1960
4.44k
        auto pp_ostream = pipeline_stack.activate(stream_buffer_pass2);
1961
1962
4.44k
        writeObjectStreamOffsets(offsets, first_obj);
1963
4.44k
        write(stream_buffer_pass1);
1964
4.44k
        stream_buffer_pass1.clear();
1965
4.44k
        stream_buffer_pass1.shrink_to_fit();
1966
4.44k
        if (compressed) {
1967
0
            stream_buffer_pass2 = pl::pipe<Pl_Flate>(stream_buffer_pass2, Pl_Flate::a_deflate);
1968
0
        }
1969
4.44k
    }
1970
1971
    // Write the object
1972
4.44k
    openObject(new_stream_id);
1973
4.44k
    setDataKey(new_stream_id);
1974
4.44k
    write("<<").write_qdf("\n ").write(" /Type /ObjStm").write_qdf("\n ");
1975
4.44k
    size_t length = stream_buffer_pass2.size();
1976
4.44k
    adjustAESStreamLength(length);
1977
4.44k
    write(" /Length ").write(length).write_qdf("\n ");
1978
4.44k
    if (compressed) {
1979
0
        write(" /Filter /FlateDecode");
1980
0
    }
1981
4.44k
    write(" /N ").write(offsets.size()).write_qdf("\n ").write(" /First ").write(first);
1982
4.44k
    if (!object.null()) {
1983
        // If the original object has an /Extends key, preserve it.
1984
379
        QPDFObjectHandle dict = object.getDict();
1985
379
        QPDFObjectHandle extends = dict.getKey("/Extends");
1986
379
        if (extends.isIndirect()) {
1987
81
            write_qdf("\n ").write(" /Extends ");
1988
81
            unparseChild(extends, 1, f_in_ostream);
1989
81
        }
1990
379
    }
1991
4.44k
    write_qdf("\n").write_no_qdf(" ").write(">>\nstream\n").write_encrypted(stream_buffer_pass2);
1992
4.44k
    write(cfg.newline_before_endstream() ? "\nendstream" : "endstream");
1993
4.44k
    if (encryption) {
1994
0
        cur_data_key.clear();
1995
0
    }
1996
4.44k
    closeObject(new_stream_id);
1997
4.44k
}
1998
1999
void
2000
impl::Writer::writeObject(QPDFObjectHandle object, int object_stream_index)
2001
101k
{
2002
101k
    QPDFObjGen old_og = object.getObjGen();
2003
2004
101k
    if (object_stream_index == -1 && old_og.getGen() == 0 &&
2005
78.0k
        object_stream_to_objects.contains(old_og.getObj())) {
2006
4.44k
        writeObjectStream(object);
2007
4.44k
        return;
2008
4.44k
    }
2009
2010
97.0k
    indicateProgress(false, false);
2011
97.0k
    auto new_id = obj[old_og].renumber;
2012
97.0k
    if (cfg.qdf()) {
2013
97.0k
        if (page_object_to_seq.contains(old_og)) {
2014
11.3k
            write("%% Page ").write(page_object_to_seq[old_og]).write("\n");
2015
11.3k
        }
2016
97.0k
        if (contents_to_page_seq.contains(old_og)) {
2017
10.1k
            write("%% Contents for page ").write(contents_to_page_seq[old_og]).write("\n");
2018
10.1k
        }
2019
97.0k
    }
2020
97.0k
    if (object_stream_index == -1) {
2021
74.5k
        if (cfg.qdf() && !cfg.no_original_object_ids()) {
2022
74.5k
            write("%% Original object ID: ").write(object.getObjGen().unparse(' ')).write("\n");
2023
74.5k
        }
2024
74.5k
        openObject(new_id);
2025
74.5k
        setDataKey(new_id);
2026
74.5k
        unparseObject(object, 0, 0);
2027
74.5k
        cur_data_key.clear();
2028
74.5k
        closeObject(new_id);
2029
74.5k
    } else {
2030
22.4k
        unparseObject(object, 0, f_in_ostream);
2031
22.4k
        write("\n");
2032
22.4k
    }
2033
2034
97.0k
    if (!cfg.direct_stream_lengths() && object.isStream()) {
2035
21.9k
        if (cfg.qdf()) {
2036
21.9k
            if (added_newline) {
2037
13.3k
                write("%QDF: ignore_newline\n");
2038
13.3k
            }
2039
21.9k
        }
2040
21.9k
        openObject(new_id + 1);
2041
21.9k
        write(cur_stream_length);
2042
21.9k
        closeObject(new_id + 1);
2043
21.9k
    }
2044
97.0k
}
2045
2046
std::string
2047
impl::Writer::getOriginalID1()
2048
9.18k
{
2049
9.18k
    if (String id0 = qpdf.getTrailer()["/ID"][0]) {
2050
669
        return id0;
2051
669
    }
2052
8.51k
    return "";
2053
9.18k
}
2054
2055
void
2056
impl::Writer::generateID(bool encrypted)
2057
9.18k
{
2058
    // Generate the ID lazily so that we can handle the user's preference to use static or
2059
    // deterministic ID generation.
2060
2061
9.18k
    if (!id2.empty()) {
2062
0
        return;
2063
0
    }
2064
2065
9.18k
    QPDFObjectHandle trailer = qpdf.getTrailer();
2066
2067
9.18k
    std::string result;
2068
2069
9.18k
    if (cfg.static_id()) {
2070
        // For test suite use only...
2071
0
        static unsigned char tmp[] = {
2072
0
            0x31,
2073
0
            0x41,
2074
0
            0x59,
2075
0
            0x26,
2076
0
            0x53,
2077
0
            0x58,
2078
0
            0x97,
2079
0
            0x93,
2080
0
            0x23,
2081
0
            0x84,
2082
0
            0x62,
2083
0
            0x64,
2084
0
            0x33,
2085
0
            0x83,
2086
0
            0x27,
2087
0
            0x95,
2088
0
            0x00};
2089
0
        result = reinterpret_cast<char*>(tmp);
2090
9.18k
    } else {
2091
        // The PDF specification has guidelines for creating IDs, but it states clearly that the
2092
        // only thing that's really important is that it is very likely to be unique.  We can't
2093
        // really follow the guidelines in the spec exactly because we haven't written the file yet.
2094
        // This scheme should be fine though.  The deterministic ID case uses a digest of a
2095
        // sufficient portion of the file's contents such no two non-matching files would match in
2096
        // the subsets used for this computation.  Note that we explicitly omit the filename from
2097
        // the digest calculation for deterministic ID so that the same file converted with qpdf, in
2098
        // that case, would have the same ID regardless of the output file's name.
2099
2100
9.18k
        std::string seed;
2101
9.18k
        if (cfg.deterministic_id()) {
2102
9.18k
            if (encrypted) {
2103
0
                throw std::runtime_error(
2104
0
                    "QPDFWriter: unable to generated a deterministic ID because the file to be "
2105
0
                    "written is encrypted (even though the file may not require a password)");
2106
0
            }
2107
9.18k
            if (deterministic_id_data.empty()) {
2108
0
                throw std::logic_error(
2109
0
                    "INTERNAL ERROR: QPDFWriter::generateID has no data for deterministic ID");
2110
0
            }
2111
9.18k
            seed += deterministic_id_data;
2112
9.18k
        } else {
2113
0
            seed += std::to_string(QUtil::get_current_time());
2114
0
            seed += filename;
2115
0
            seed += " ";
2116
0
        }
2117
9.18k
        seed += " QPDF ";
2118
9.18k
        if (trailer.hasKey("/Info")) {
2119
1.20k
            for (auto const& item: trailer.getKey("/Info").as_dictionary()) {
2120
1.20k
                if (item.second.isString()) {
2121
553
                    seed += " ";
2122
553
                    seed += item.second.getStringValue();
2123
553
                }
2124
1.20k
            }
2125
276
        }
2126
2127
9.18k
        MD5 md5;
2128
9.18k
        md5.encodeString(seed.c_str());
2129
9.18k
        MD5::Digest digest;
2130
9.18k
        md5.digest(digest);
2131
9.18k
        result = std::string(reinterpret_cast<char*>(digest), sizeof(MD5::Digest));
2132
9.18k
    }
2133
2134
    // If /ID already exists, follow the spec: use the original first word and generate a new second
2135
    // word.  Otherwise, we'll use the generated ID for both.
2136
2137
9.18k
    id2 = result;
2138
    // Note: keep /ID from old file even if --static-id was given.
2139
9.18k
    id1 = getOriginalID1();
2140
9.18k
    if (id1.empty()) {
2141
8.51k
        id1 = id2;
2142
8.51k
    }
2143
9.18k
}
2144
2145
void
2146
impl::Writer::initializeSpecialStreams()
2147
9.37k
{
2148
    // Mark all page content streams in case we are filtering or normalizing.
2149
9.37k
    int num = 0;
2150
11.5k
    for (auto& page: pages) {
2151
11.5k
        page_object_to_seq[page.getObjGen()] = ++num;
2152
11.5k
        QPDFObjectHandle contents = page.getKey("/Contents");
2153
11.5k
        std::vector<QPDFObjGen> contents_objects;
2154
11.5k
        if (contents.isArray()) {
2155
549
            int n = static_cast<int>(contents.size());
2156
329k
            for (int i = 0; i < n; ++i) {
2157
329k
                contents_objects.push_back(contents.getArrayItem(i).getObjGen());
2158
329k
            }
2159
11.0k
        } else if (contents.isStream()) {
2160
1.78k
            contents_objects.push_back(contents.getObjGen());
2161
1.78k
        }
2162
2163
330k
        for (auto const& c: contents_objects) {
2164
330k
            contents_to_page_seq[c] = num;
2165
330k
            normalized_streams.insert(c);
2166
330k
        }
2167
11.5k
    }
2168
9.37k
}
2169
2170
void
2171
impl::Writer::preserveObjectStreams()
2172
9.37k
{
2173
9.37k
    auto const& xref = objects.xref_table();
2174
    // Our object_to_object_stream map has to map ObjGen -> ObjGen since we may be generating object
2175
    // streams out of old objects that have generation numbers greater than zero. However in an
2176
    // existing PDF, all object stream objects and all objects in them must have generation 0
2177
    // because the PDF spec does not provide any way to do otherwise. This code filters out objects
2178
    // that are not allowed to be in object streams. In addition to removing objects that were
2179
    // erroneously included in object streams in the source PDF, it also prevents unreferenced
2180
    // objects from being included.
2181
9.37k
    auto end = xref.cend();
2182
9.37k
    obj.streams_empty = true;
2183
9.37k
    if (cfg.preserve_unreferenced()) {
2184
0
        for (auto iter = xref.cbegin(); iter != end; ++iter) {
2185
0
            if (iter->second.getType() == 2) {
2186
                // Pdf contains object streams.
2187
0
                obj.streams_empty = false;
2188
0
                obj[iter->first].object_stream = iter->second.getObjStreamNumber();
2189
0
            }
2190
0
        }
2191
9.37k
    } else {
2192
        // Start by scanning for first compressed object in case we don't have any object streams to
2193
        // process.
2194
74.3k
        for (auto iter = xref.cbegin(); iter != end; ++iter) {
2195
65.8k
            if (iter->second.getType() == 2) {
2196
                // Pdf contains object streams.
2197
954
                obj.streams_empty = false;
2198
954
                auto eligible = objects.compressible_set();
2199
                // The object pointed to by iter may be a previous generation, in which case it is
2200
                // removed by compressible_set. We need to restart the loop (while the object
2201
                // table may contain multiple generations of an object).
2202
215k
                for (iter = xref.cbegin(); iter != end; ++iter) {
2203
214k
                    if (iter->second.getType() == 2) {
2204
197k
                        auto id = static_cast<size_t>(iter->first.getObj());
2205
197k
                        if (id < eligible.size() && eligible[id]) {
2206
23.6k
                            obj[iter->first].object_stream = iter->second.getObjStreamNumber();
2207
173k
                        } else {
2208
173k
                            QTC::TC("qpdf", "QPDFWriter exclude from object stream");
2209
173k
                        }
2210
197k
                    }
2211
214k
                }
2212
954
                return;
2213
954
            }
2214
65.8k
        }
2215
9.37k
    }
2216
9.37k
}
2217
2218
void
2219
impl::Writer::generateObjectStreams()
2220
0
{
2221
    // Basic strategy: make a list of objects that can go into an object stream.  Then figure out
2222
    // how many object streams are needed so that we can distribute objects approximately evenly
2223
    // without having any object stream exceed 100 members.  We don't have to worry about linearized
2224
    // files here -- if the file is linearized, we take care of excluding things that aren't allowed
2225
    // here later.
2226
2227
    // This code doesn't do anything with /Extends.
2228
2229
0
    auto eligible = objects.compressible_vector();
2230
0
    size_t n_object_streams = (eligible.size() + 99U) / 100U;
2231
2232
0
    initializeTables(2U * n_object_streams);
2233
0
    if (n_object_streams == 0) {
2234
0
        obj.streams_empty = true;
2235
0
        return;
2236
0
    }
2237
0
    size_t n_per = eligible.size() / n_object_streams;
2238
0
    if (n_per * n_object_streams < eligible.size()) {
2239
0
        ++n_per;
2240
0
    }
2241
0
    unsigned int n = 0;
2242
0
    int cur_ostream = qpdf.newIndirectNull().getObjectID();
2243
0
    for (auto const& item: eligible) {
2244
0
        if (n == n_per) {
2245
0
            n = 0;
2246
            // Construct a new null object as the "original" object stream.  The rest of the code
2247
            // knows that this means we're creating the object stream from scratch.
2248
0
            cur_ostream = qpdf.newIndirectNull().getObjectID();
2249
0
        }
2250
0
        auto& o = obj[item];
2251
0
        o.object_stream = cur_ostream;
2252
0
        o.gen = item.getGen();
2253
0
        ++n;
2254
0
    }
2255
0
}
2256
2257
Dictionary
2258
impl::Writer::trimmed_trailer()
2259
18.4k
{
2260
    // Remove keys from the trailer that necessarily have to be replaced when writing the file.
2261
2262
18.4k
    Dictionary trailer = qpdf.getTrailer().unsafeShallowCopy();
2263
2264
    // Remove encryption keys
2265
18.4k
    trailer.erase("/ID");
2266
18.4k
    trailer.erase("/Encrypt");
2267
2268
    // Remove modification information
2269
18.4k
    trailer.erase("/Prev");
2270
2271
    // Remove all trailer keys that potentially come from a cross-reference stream
2272
18.4k
    trailer.erase("/Index");
2273
18.4k
    trailer.erase("/W");
2274
18.4k
    trailer.erase("/Length");
2275
18.4k
    trailer.erase("/Filter");
2276
18.4k
    trailer.erase("/DecodeParms");
2277
18.4k
    trailer.erase("/Type");
2278
18.4k
    trailer.erase("/XRefStm");
2279
2280
18.4k
    return trailer;
2281
18.4k
}
2282
2283
// Make document extension level information direct as required by the spec.
2284
void
2285
impl::Writer::prepareFileForWrite()
2286
9.33k
{
2287
9.33k
    qpdf.fixDanglingReferences();
2288
9.33k
    auto root = qpdf.getRoot();
2289
9.33k
    auto oh = root.getKey("/Extensions");
2290
9.33k
    if (oh.isDictionary()) {
2291
480
        const bool extensions_indirect = oh.isIndirect();
2292
480
        if (extensions_indirect) {
2293
128
            QTC::TC("qpdf", "QPDFWriter make Extensions direct");
2294
128
            oh = root.replaceKeyAndGetNew("/Extensions", oh.shallowCopy());
2295
128
        }
2296
480
        if (oh.hasKey("/ADBE")) {
2297
345
            auto adbe = oh.getKey("/ADBE");
2298
345
            if (adbe.isIndirect()) {
2299
276
                QTC::TC("qpdf", "QPDFWriter make ADBE direct", extensions_indirect ? 0 : 1);
2300
276
                adbe.makeDirect();
2301
276
                oh.replaceKey("/ADBE", adbe);
2302
276
            }
2303
345
        }
2304
480
    }
2305
9.33k
}
2306
2307
void
2308
impl::Writer::initializeTables(size_t extra)
2309
9.37k
{
2310
9.37k
    auto size = objects.table_size() + 100u + extra;
2311
9.37k
    obj.resize(size);
2312
9.37k
    new_obj.resize(size);
2313
9.37k
}
2314
2315
void
2316
impl::Writer::doWriteSetup()
2317
9.37k
{
2318
9.37k
    if (did_write_setup) {
2319
0
        return;
2320
0
    }
2321
9.37k
    did_write_setup = true;
2322
2323
    // Do preliminary setup
2324
2325
9.37k
    if (cfg.linearize()) {
2326
0
        cfg.qdf(false);
2327
0
    }
2328
2329
9.37k
    if (cfg.pclm()) {
2330
0
        encryption = nullptr;
2331
0
    }
2332
2333
9.37k
    if (encryption) {
2334
        // Encryption has been explicitly set
2335
0
        cfg.preserve_encryption(false);
2336
9.37k
    } else if (cfg.normalize_content() || cfg.pclm()) {
2337
        // Encryption makes looking at contents pretty useless.  If the user explicitly encrypted
2338
        // though, we still obey that.
2339
9.37k
        cfg.preserve_encryption(false);
2340
9.37k
    }
2341
2342
9.37k
    if (cfg.preserve_encryption()) {
2343
0
        copyEncryptionParameters(qpdf);
2344
0
    }
2345
2346
9.37k
    if (!cfg.forced_pdf_version().empty()) {
2347
0
        int major = 0;
2348
0
        int minor = 0;
2349
0
        parseVersion(cfg.forced_pdf_version(), major, minor);
2350
0
        disableIncompatibleEncryption(major, minor, cfg.forced_extension_level());
2351
0
        if (compareVersions(major, minor, 1, 5) < 0) {
2352
0
            cfg.object_streams(qpdf_o_disable);
2353
0
        }
2354
0
    }
2355
2356
    // SOURCE_DATE_EPOCH requests reproducible output, so use a deterministic ID when possible. If
2357
    // the ID has already been generated, such as when encryption parameters were copied before
2358
    // encryption was disabled for an older PDF version, it was generated from the fixed time.
2359
9.37k
    if (util::source_date_epoch() && !encryption && id2.empty() && !cfg.static_id()) {
2360
0
        cfg.deterministic_id(true);
2361
0
    }
2362
2363
9.37k
    if (cfg.qdf() || cfg.normalize_content()) {
2364
9.37k
        initializeSpecialStreams();
2365
9.37k
    }
2366
2367
9.37k
    switch (cfg.object_streams()) {
2368
0
    case qpdf_o_disable:
2369
0
        initializeTables();
2370
0
        obj.streams_empty = true;
2371
0
        break;
2372
2373
9.37k
    case qpdf_o_preserve:
2374
9.37k
        initializeTables();
2375
9.37k
        preserveObjectStreams();
2376
9.37k
        break;
2377
2378
0
    case qpdf_o_generate:
2379
0
        generateObjectStreams();
2380
0
        break;
2381
9.37k
    }
2382
2383
9.37k
    if (!obj.streams_empty) {
2384
954
        if (cfg.linearize()) {
2385
            // Page dictionaries are not allowed to be compressed objects.
2386
0
            for (auto& page: pages) {
2387
0
                if (obj[page].object_stream > 0) {
2388
0
                    obj[page].object_stream = 0;
2389
0
                }
2390
0
            }
2391
0
        }
2392
2393
954
        if (cfg.linearize() || encryption) {
2394
            // The document catalog is not allowed to be compressed in linearized files either.
2395
            // It also appears that Adobe Reader 8.0.0 has a bug that prevents it from being able to
2396
            // handle encrypted files with compressed document catalogs, so we disable them in that
2397
            // case as well.
2398
0
            if (obj[root_og].object_stream > 0) {
2399
0
                obj[root_og].object_stream = 0;
2400
0
            }
2401
0
        }
2402
2403
        // Generate reverse mapping from object stream to objects
2404
1.37M
        obj.forEach([this](auto id, auto const& item) -> void {
2405
1.37M
            if (item.object_stream > 0) {
2406
23.5k
                auto& vec = object_stream_to_objects[item.object_stream];
2407
23.5k
                vec.emplace_back(id, item.gen);
2408
23.5k
                if (max_ostream_index < vec.size()) {
2409
6.34k
                    ++max_ostream_index;
2410
6.34k
                }
2411
23.5k
            }
2412
1.37M
        });
2413
954
        --max_ostream_index;
2414
2415
954
        if (object_stream_to_objects.empty()) {
2416
556
            obj.streams_empty = true;
2417
556
        } else {
2418
398
            setMinimumPDFVersion("1.5");
2419
398
        }
2420
954
    }
2421
2422
9.37k
    setMinimumPDFVersion(qpdf.getPDFVersion(), qpdf.getExtensionLevel());
2423
9.37k
    final_pdf_version = min_pdf_version;
2424
9.37k
    final_extension_level = min_extension_level;
2425
9.37k
    if (!cfg.forced_pdf_version().empty()) {
2426
0
        final_pdf_version = cfg.forced_pdf_version();
2427
0
        final_extension_level = cfg.forced_extension_level();
2428
0
    }
2429
9.37k
}
2430
2431
void
2432
QPDFWriter::write()
2433
9.37k
{
2434
9.37k
    m->write();
2435
9.37k
}
2436
2437
void
2438
impl::Writer::write()
2439
9.37k
{
2440
9.37k
    doWriteSetup();
2441
2442
    // Set up progress reporting. For linearized files, we write two passes. events_expected is an
2443
    // approximation, but it's good enough for progress reporting, which is mostly a guess anyway.
2444
    // Count only objects that, when written, trigger an indicateProgress increment.
2445
9.37k
    size_t in_stream_objs = 0;
2446
9.37k
    for (auto const& kv: object_stream_to_objects) {
2447
4.89k
        in_stream_objs += kv.second.size();
2448
4.89k
    }
2449
9.37k
    const size_t expected =
2450
9.37k
        (qpdf.getObjectCount() - object_stream_to_objects.size() - in_stream_objs) *
2451
9.37k
        (cfg.linearize() ? 2 : 1);
2452
9.37k
    events_expected = std::max(
2453
9.37k
        1,
2454
9.37k
        util::fits<int>(expected) ? static_cast<int>(expected) : std::numeric_limits<int>::max());
2455
2456
9.37k
    prepareFileForWrite();
2457
2458
9.37k
    if (cfg.linearize()) {
2459
0
        writeLinearized();
2460
9.37k
    } else {
2461
9.37k
        writeStandard();
2462
9.37k
    }
2463
2464
9.37k
    pipeline->finish();
2465
9.37k
    if (close_file) {
2466
0
        fclose(file);
2467
0
    }
2468
9.37k
    file = nullptr;
2469
9.37k
    if (buffer_pipeline) {
2470
0
        output_buffer = buffer_pipeline->getBuffer();
2471
0
        buffer_pipeline = nullptr;
2472
0
    }
2473
9.37k
    indicateProgress(false, true);
2474
9.37k
}
2475
2476
QPDFObjGen
2477
QPDFWriter::getRenumberedObjGen(QPDFObjGen og)
2478
0
{
2479
0
    return {m->obj[og].renumber, 0};
2480
0
}
2481
2482
std::map<QPDFObjGen, QPDFXRefEntry>
2483
QPDFWriter::getWrittenXRefTable()
2484
0
{
2485
0
    return m->getWrittenXRefTable();
2486
0
}
2487
2488
std::map<QPDFObjGen, QPDFXRefEntry>
2489
impl::Writer::getWrittenXRefTable()
2490
0
{
2491
0
    std::map<QPDFObjGen, QPDFXRefEntry> result;
2492
2493
0
    auto it = result.begin();
2494
0
    new_obj.forEach([&it, &result](auto id, auto const& item) -> void {
2495
0
        if (item.xref.getType() != 0) {
2496
0
            it = result.emplace_hint(it, QPDFObjGen(id, 0), item.xref);
2497
0
        }
2498
0
    });
2499
0
    return result;
2500
0
}
2501
2502
void
2503
impl::Writer::enqueuePart(std::vector<QPDFObjectHandle>& part)
2504
0
{
2505
0
    for (auto const& oh: part) {
2506
0
        enqueue(oh);
2507
0
    }
2508
0
}
2509
2510
void
2511
impl::Writer::writeEncryptionDictionary()
2512
0
{
2513
0
    encryption_dict_objid = openObject(encryption_dict_objid);
2514
0
    auto& enc = *encryption;
2515
0
    auto const V = enc.getV();
2516
2517
0
    write("<<");
2518
0
    if (V >= 4) {
2519
0
        write(" /CF << /StdCF << /AuthEvent /DocOpen /CFM ");
2520
0
        write(cfg.encrypt_use_aes() ? (V < 5 ? "/AESV2" : "/AESV3") : "/V2");
2521
        // The PDF spec says the /Length key is optional, but the PDF previewer on some versions of
2522
        // MacOS won't open encrypted files without it.
2523
0
        write(V < 5 ? " /Length 16 >> >>" : " /Length 32 >> >>");
2524
0
        if (!encryption->getEncryptMetadata()) {
2525
0
            write(" /EncryptMetadata false");
2526
0
        }
2527
0
    }
2528
0
    write(" /Filter /Standard /Length ").write(enc.getLengthBytes() * 8);
2529
0
    write(" /O ").write_string(enc.getO(), true);
2530
0
    if (V >= 4) {
2531
0
        write(" /OE ").write_string(enc.getOE(), true);
2532
0
    }
2533
0
    write(" /P ").write(enc.getP());
2534
0
    if (V >= 5) {
2535
0
        write(" /Perms ").write_string(enc.getPerms(), true);
2536
0
    }
2537
0
    write(" /R ").write(enc.getR());
2538
2539
0
    if (V >= 4) {
2540
0
        write(" /StmF /StdCF /StrF /StdCF");
2541
0
    }
2542
0
    write(" /U ").write_string(enc.getU(), true);
2543
0
    if (V >= 4) {
2544
0
        write(" /UE ").write_string(enc.getUE(), true);
2545
0
    }
2546
0
    write(" /V ").write(enc.getV()).write(" >>");
2547
0
    closeObject(encryption_dict_objid);
2548
0
}
2549
2550
std::string
2551
QPDFWriter::getFinalVersion()
2552
0
{
2553
0
    m->doWriteSetup();
2554
0
    return m->final_pdf_version;
2555
0
}
2556
2557
void
2558
impl::Writer::writeHeader()
2559
9.28k
{
2560
9.28k
    write("%PDF-").write(final_pdf_version);
2561
9.28k
    if (cfg.pclm()) {
2562
        // PCLm version
2563
0
        write("\n%PCLm 1.0\n");
2564
9.28k
    } else {
2565
        // This string of binary characters would not be valid UTF-8, so it really should be treated
2566
        // as binary.
2567
9.28k
        write("\n%\xbf\xf7\xa2\xfe\n");
2568
9.28k
    }
2569
9.28k
    write_qdf("%QDF-1.0\n\n");
2570
2571
    // Note: do not write extra header text here.  Linearized PDFs must include the entire
2572
    // linearization parameter dictionary within the first 1024 characters of the PDF file, so for
2573
    // linearized files, we have to write extra header text after the linearization parameter
2574
    // dictionary.
2575
9.28k
}
2576
2577
void
2578
impl::Writer::writeHintStream(int hint_id)
2579
0
{
2580
0
    std::string hint_buffer;
2581
0
    int S = 0;
2582
0
    int O = 0;
2583
0
    bool compressed = cfg.compress_streams();
2584
0
    lin.generateHintStream(new_obj, obj, hint_buffer, S, O, compressed);
2585
2586
0
    openObject(hint_id);
2587
0
    setDataKey(hint_id);
2588
2589
0
    size_t hlen = hint_buffer.size();
2590
2591
0
    write("<< ");
2592
0
    if (compressed) {
2593
0
        write("/Filter /FlateDecode ");
2594
0
    }
2595
0
    write("/S ").write(S);
2596
0
    if (O) {
2597
0
        write(" /O ").write(O);
2598
0
    }
2599
0
    adjustAESStreamLength(hlen);
2600
0
    write(" /Length ").write(hlen);
2601
0
    write(" >>\nstream\n").write_encrypted(hint_buffer);
2602
2603
0
    if (encryption) {
2604
0
        QTC::TC("qpdf", "QPDFWriter encrypted hint stream");
2605
0
    }
2606
2607
0
    write(hint_buffer.empty() || hint_buffer.back() != '\n' ? "\nendstream" : "endstream");
2608
0
    closeObject(hint_id);
2609
0
}
2610
2611
qpdf_offset_t
2612
impl::Writer::writeXRefTable(trailer_e which, int first, int last, int size)
2613
8.83k
{
2614
    // There are too many extra arguments to replace overloaded function with defaults in the header
2615
    // file...too much risk of leaving something off.
2616
8.83k
    return writeXRefTable(which, first, last, size, 0, false, 0, 0, 0, 0);
2617
8.83k
}
2618
2619
qpdf_offset_t
2620
impl::Writer::writeXRefTable(
2621
    trailer_e which,
2622
    int first,
2623
    int last,
2624
    int size,
2625
    qpdf_offset_t prev,
2626
    bool suppress_offsets,
2627
    int hint_id,
2628
    qpdf_offset_t hint_offset,
2629
    qpdf_offset_t hint_length,
2630
    int linearization_pass)
2631
8.83k
{
2632
8.83k
    write("xref\n").write(first).write(" ").write(last - first + 1);
2633
8.83k
    qpdf_offset_t space_before_zero = pipeline->getCount();
2634
8.83k
    write("\n");
2635
8.83k
    if (first == 0) {
2636
8.83k
        write("0000000000 65535 f \n");
2637
8.83k
        ++first;
2638
8.83k
    }
2639
93.1k
    for (int i = first; i <= last; ++i) {
2640
84.2k
        qpdf_offset_t offset = 0;
2641
84.2k
        if (!suppress_offsets) {
2642
84.2k
            offset = new_obj[i].xref.getOffset();
2643
84.2k
            if ((hint_id != 0) && (i != hint_id) && (offset >= hint_offset)) {
2644
0
                offset += hint_length;
2645
0
            }
2646
84.2k
        }
2647
84.2k
        write(QUtil::int_to_string(offset, 10)).write(" 00000 n \n");
2648
84.2k
    }
2649
8.83k
    writeTrailer(which, size, false, prev, linearization_pass);
2650
8.83k
    write("\n");
2651
8.83k
    return space_before_zero;
2652
8.83k
}
2653
2654
qpdf_offset_t
2655
impl::Writer::writeXRefStream(
2656
    int objid, int max_id, qpdf_offset_t max_offset, trailer_e which, int first, int last, int size)
2657
350
{
2658
    // There are too many extra arguments to replace overloaded function with defaults in the header
2659
    // file...too much risk of leaving something off.
2660
350
    return writeXRefStream(
2661
350
        objid, max_id, max_offset, which, first, last, size, 0, 0, 0, 0, false, 0);
2662
350
}
2663
2664
qpdf_offset_t
2665
impl::Writer::writeXRefStream(
2666
    int xref_id,
2667
    int max_id,
2668
    qpdf_offset_t max_offset,
2669
    trailer_e which,
2670
    int first,
2671
    int last,
2672
    int size,
2673
    qpdf_offset_t prev,
2674
    int hint_id,
2675
    qpdf_offset_t hint_offset,
2676
    qpdf_offset_t hint_length,
2677
    bool skip_compression,
2678
    int linearization_pass)
2679
350
{
2680
350
    qpdf_offset_t xref_offset = pipeline->getCount();
2681
350
    qpdf_offset_t space_before_zero = xref_offset - 1;
2682
2683
    // field 1 contains offsets and object stream identifiers
2684
350
    unsigned int f1_size = std::max(bytesNeeded(max_offset + hint_length), bytesNeeded(max_id));
2685
2686
    // field 2 contains object stream indices
2687
350
    unsigned int f2_size = bytesNeeded(QIntC::to_longlong(max_ostream_index));
2688
2689
350
    unsigned int esize = 1 + f1_size + f2_size;
2690
2691
    // Must store in xref table in advance of writing the actual data rather than waiting for
2692
    // openObject to do it.
2693
350
    new_obj[xref_id].xref = QPDFXRefEntry(pipeline->getCount());
2694
2695
350
    std::string xref_data;
2696
350
    const bool compressed = cfg.compress_streams() && !cfg.qdf();
2697
350
    {
2698
350
        auto pp_xref = pipeline_stack.activate(xref_data);
2699
2700
38.7k
        for (int i = first; i <= last; ++i) {
2701
38.3k
            QPDFXRefEntry& e = new_obj[i].xref;
2702
38.3k
            switch (e.getType()) {
2703
350
            case 0:
2704
350
                writeBinary(0, 1);
2705
350
                writeBinary(0, f1_size);
2706
350
                writeBinary(0, f2_size);
2707
350
                break;
2708
2709
16.3k
            case 1:
2710
16.3k
                {
2711
16.3k
                    qpdf_offset_t offset = e.getOffset();
2712
16.3k
                    if ((hint_id != 0) && (i != hint_id) && (offset >= hint_offset)) {
2713
0
                        offset += hint_length;
2714
0
                    }
2715
16.3k
                    writeBinary(1, 1);
2716
16.3k
                    writeBinary(QIntC::to_ulonglong(offset), f1_size);
2717
16.3k
                    writeBinary(0, f2_size);
2718
16.3k
                }
2719
16.3k
                break;
2720
2721
21.6k
            case 2:
2722
21.6k
                writeBinary(2, 1);
2723
21.6k
                writeBinary(QIntC::to_ulonglong(e.getObjStreamNumber()), f1_size);
2724
21.6k
                writeBinary(QIntC::to_ulonglong(e.getObjStreamIndex()), f2_size);
2725
21.6k
                break;
2726
2727
0
            default:
2728
0
                throw std::logic_error("invalid type writing xref stream");
2729
0
                break;
2730
38.3k
            }
2731
38.3k
        }
2732
350
    }
2733
2734
350
    if (compressed) {
2735
0
        xref_data = pl::pipe<Pl_PNGFilter>(xref_data, Pl_PNGFilter::a_encode, esize);
2736
0
        if (!skip_compression) {
2737
            // Write the stream dictionary for compression but don't actually compress.  This
2738
            // helps us with computation of padding for pass 1 of linearization.
2739
0
            xref_data = pl::pipe<Pl_Flate>(xref_data, Pl_Flate::a_deflate);
2740
0
        }
2741
0
    }
2742
2743
350
    openObject(xref_id);
2744
350
    write("<<").write_qdf("\n ").write(" /Type /XRef").write_qdf("\n ");
2745
350
    write(" /Length ").write(xref_data.size());
2746
350
    if (compressed) {
2747
0
        write_qdf("\n ").write(" /Filter /FlateDecode").write_qdf("\n ");
2748
0
        write(" /DecodeParms << /Columns ").write(esize).write(" /Predictor 12 >>");
2749
0
    }
2750
350
    write_qdf("\n ").write(" /W [ 1 ").write(f1_size).write(" ").write(f2_size).write(" ]");
2751
350
    if (!(first == 0 && last == (size - 1))) {
2752
0
        write(" /Index [ ").write(first).write(" ").write(last - first + 1).write(" ]");
2753
0
    }
2754
350
    writeTrailer(which, size, true, prev, linearization_pass);
2755
350
    write("\nstream\n").write(xref_data).write("\nendstream");
2756
350
    closeObject(xref_id);
2757
350
    return space_before_zero;
2758
350
}
2759
2760
size_t
2761
impl::Writer::calculateXrefStreamPadding(qpdf_offset_t xref_bytes)
2762
0
{
2763
    // This routine is called right after a linearization first pass xref stream has been written
2764
    // without compression.  Calculate the amount of padding that would be required in the worst
2765
    // case, assuming the number of uncompressed bytes remains the same. The worst case for zlib is
2766
    // that the output is larger than the input by 6 bytes plus 5 bytes per 16K, and then we'll add
2767
    // 10 extra bytes for number length increases.
2768
2769
0
    return QIntC::to_size(16 + (5 * ((xref_bytes + 16383) / 16384)));
2770
0
}
2771
2772
void
2773
impl::Writer::writeLinearized()
2774
0
{
2775
    // Optimize file and enqueue objects in order
2776
2777
0
    std::map<int, int> stream_cache;
2778
2779
0
    auto skip_stream_parameters = [this, &stream_cache](QPDFObjectHandle& stream) {
2780
0
        if (auto& result = stream_cache[stream.getObjectID()]) {
2781
0
            return result;
2782
0
        } else {
2783
0
            return result = will_filter_stream(stream) ? 2 : 1;
2784
0
        }
2785
0
    };
2786
2787
0
    std::vector<QPDFObjectHandle> part4;
2788
0
    std::vector<QPDFObjectHandle> part6;
2789
0
    std::vector<QPDFObjectHandle> part7;
2790
0
    std::vector<QPDFObjectHandle> part8;
2791
0
    std::vector<QPDFObjectHandle> part9;
2792
0
    lin.parts(obj, skip_stream_parameters, part4, part6, part7, part8, part9);
2793
2794
    // Object number sequence:
2795
    //
2796
    //  second half
2797
    //    second half uncompressed objects
2798
    //    second half xref stream, if any
2799
    //    second half compressed objects
2800
    //  first half
2801
    //    linearization dictionary
2802
    //    first half xref stream, if any
2803
    //    part 4 uncompresesd objects
2804
    //    encryption dictionary, if any
2805
    //    hint stream
2806
    //    part 6 uncompressed objects
2807
    //    first half compressed objects
2808
    //
2809
2810
    // Second half objects
2811
0
    int second_half_uncompressed = QIntC::to_int(part7.size() + part8.size() + part9.size());
2812
0
    int second_half_first_obj = 1;
2813
0
    int after_second_half = 1 + second_half_uncompressed;
2814
0
    next_objid = after_second_half;
2815
0
    int second_half_xref = 0;
2816
0
    bool need_xref_stream = !obj.streams_empty;
2817
0
    if (need_xref_stream) {
2818
0
        second_half_xref = next_objid++;
2819
0
    }
2820
    // Assign numbers to all compressed objects in the second half.
2821
0
    std::vector<QPDFObjectHandle>* vecs2[] = {&part7, &part8, &part9};
2822
0
    for (int i = 0; i < 3; ++i) {
2823
0
        for (auto const& oh: *vecs2[i]) {
2824
0
            assignCompressedObjectNumbers(oh.getObjGen());
2825
0
        }
2826
0
    }
2827
0
    int second_half_end = next_objid - 1;
2828
0
    int second_trailer_size = next_objid;
2829
2830
    // First half objects
2831
0
    int first_half_start = next_objid;
2832
0
    int lindict_id = next_objid++;
2833
0
    int first_half_xref = 0;
2834
0
    if (need_xref_stream) {
2835
0
        first_half_xref = next_objid++;
2836
0
    }
2837
0
    int part4_first_obj = next_objid;
2838
0
    next_objid += QIntC::to_int(part4.size());
2839
0
    int after_part4 = next_objid;
2840
0
    if (encryption) {
2841
0
        encryption_dict_objid = next_objid++;
2842
0
    }
2843
0
    int hint_id = next_objid++;
2844
0
    int part6_first_obj = next_objid;
2845
0
    next_objid += QIntC::to_int(part6.size());
2846
0
    int after_part6 = next_objid;
2847
    // Assign numbers to all compressed objects in the first half
2848
0
    std::vector<QPDFObjectHandle>* vecs1[] = {&part4, &part6};
2849
0
    for (int i = 0; i < 2; ++i) {
2850
0
        for (auto const& oh: *vecs1[i]) {
2851
0
            assignCompressedObjectNumbers(oh.getObjGen());
2852
0
        }
2853
0
    }
2854
0
    int first_half_end = next_objid - 1;
2855
0
    int first_trailer_size = next_objid;
2856
2857
0
    int part4_end_marker = part4.back().getObjectID();
2858
0
    int part6_end_marker = part6.back().getObjectID();
2859
0
    qpdf_offset_t space_before_zero = 0;
2860
0
    qpdf_offset_t file_size = 0;
2861
0
    qpdf_offset_t part6_end_offset = 0;
2862
0
    qpdf_offset_t first_half_max_obj_offset = 0;
2863
0
    qpdf_offset_t second_xref_offset = 0;
2864
0
    qpdf_offset_t first_xref_end = 0;
2865
0
    qpdf_offset_t second_xref_end = 0;
2866
2867
0
    next_objid = part4_first_obj;
2868
0
    enqueuePart(part4);
2869
0
    if (next_objid != after_part4) {
2870
        // This can happen with very botched files as in the fuzzer test. There are likely some
2871
        // faulty assumptions in calculateLinearizationData
2872
0
        throw std::runtime_error("error encountered after writing part 4 of linearized data");
2873
0
    }
2874
0
    next_objid = part6_first_obj;
2875
0
    enqueuePart(part6);
2876
0
    util::no_ci_rt_error_if(
2877
0
        next_objid != after_part6, "error encountered after writing part 6 of linearized data" //
2878
0
    );
2879
0
    next_objid = second_half_first_obj;
2880
0
    enqueuePart(part7);
2881
0
    enqueuePart(part8);
2882
0
    enqueuePart(part9);
2883
0
    util::no_ci_rt_error_if(
2884
0
        next_objid != after_second_half,
2885
0
        "error encountered after writing part 9 of linearized data" //
2886
0
    );
2887
2888
0
    qpdf_offset_t hint_length = 0;
2889
0
    std::string hint_buffer;
2890
2891
    // Write file in two passes.  Part numbers refer to PDF spec 1.4.
2892
2893
0
    FILE* lin_pass1_file = nullptr;
2894
0
    auto pp_pass1 = pipeline_stack.popper();
2895
0
    auto pp_md5 = pipeline_stack.popper();
2896
0
    for (int pass: {1, 2}) {
2897
0
        if (pass == 1) {
2898
0
            if (!cfg.linearize_pass1().empty()) {
2899
0
                lin_pass1_file = QUtil::safe_fopen(cfg.linearize_pass1().data(), "wb");
2900
0
                pipeline_stack.activate(
2901
0
                    pp_pass1,
2902
0
                    std::make_unique<Pl_StdioFile>("linearization pass1", lin_pass1_file));
2903
0
            } else {
2904
0
                pipeline_stack.activate(pp_pass1, true);
2905
0
            }
2906
0
            if (cfg.deterministic_id()) {
2907
0
                pipeline_stack.activate_md5(pp_md5);
2908
0
            }
2909
0
        }
2910
2911
        // Part 1: header
2912
2913
0
        writeHeader();
2914
2915
        // Part 2: linearization parameter dictionary.  Save enough space to write real dictionary.
2916
        // 200 characters is enough space if all numerical values in the parameter dictionary that
2917
        // contain offsets are 20 digits long plus a few extra characters for safety.  The entire
2918
        // linearization parameter dictionary must appear within the first 1024 characters of the
2919
        // file.
2920
2921
0
        qpdf_offset_t pos = pipeline->getCount();
2922
0
        openObject(lindict_id);
2923
0
        write("<<");
2924
0
        if (pass == 2) {
2925
0
            write(" /Linearized 1 /L ").write(file_size + hint_length);
2926
            // Implementation note 121 states that a space is mandatory after this open bracket.
2927
0
            write(" /H [ ").write(new_obj[hint_id].xref.getOffset()).write(" ");
2928
0
            write(hint_length);
2929
0
            write(" ] /O ").write(obj[pages.all().at(0)].renumber);
2930
0
            write(" /E ").write(part6_end_offset + hint_length);
2931
0
            write(" /N ").write(pages.size());
2932
0
            write(" /T ").write(space_before_zero + hint_length);
2933
0
        }
2934
0
        write(" >>");
2935
0
        closeObject(lindict_id);
2936
0
        static int const pad = 200;
2937
0
        write(QIntC::to_size(pos - pipeline->getCount() + pad), ' ').write("\n");
2938
2939
        // If the user supplied any additional header text, write it here after the linearization
2940
        // parameter dictionary.
2941
0
        write(cfg.extra_header_text());
2942
2943
        // Part 3: first page cross reference table and trailer.
2944
2945
0
        qpdf_offset_t first_xref_offset = pipeline->getCount();
2946
0
        qpdf_offset_t hint_offset = 0;
2947
0
        if (pass == 2) {
2948
0
            hint_offset = new_obj[hint_id].xref.getOffset();
2949
0
        }
2950
0
        if (need_xref_stream) {
2951
            // Must pad here too.
2952
0
            if (pass == 1) {
2953
                // Set first_half_max_obj_offset to a value large enough to force four bytes to be
2954
                // reserved for each file offset.  This would provide adequate space for the xref
2955
                // stream as long as the last object in page 1 starts with in the first 4 GB of the
2956
                // file, which is extremely likely.  In the second pass, we will know the actual
2957
                // value for this, but it's okay if it's smaller.
2958
0
                first_half_max_obj_offset = 1 << 25;
2959
0
            }
2960
0
            pos = pipeline->getCount();
2961
0
            writeXRefStream(
2962
0
                first_half_xref,
2963
0
                first_half_end,
2964
0
                first_half_max_obj_offset,
2965
0
                t_lin_first,
2966
0
                first_half_start,
2967
0
                first_half_end,
2968
0
                first_trailer_size,
2969
0
                hint_length + second_xref_offset,
2970
0
                hint_id,
2971
0
                hint_offset,
2972
0
                hint_length,
2973
0
                (pass == 1),
2974
0
                pass);
2975
0
            qpdf_offset_t endpos = pipeline->getCount();
2976
0
            if (pass == 1) {
2977
                // Pad so we have enough room for the real xref stream.
2978
0
                write(calculateXrefStreamPadding(endpos - pos), ' ');
2979
0
                first_xref_end = pipeline->getCount();
2980
0
            } else {
2981
                // Pad so that the next object starts at the same place as in pass 1.
2982
0
                write(QIntC::to_size(first_xref_end - endpos), ' ');
2983
2984
0
                if (pipeline->getCount() != first_xref_end) {
2985
0
                    throw std::logic_error(
2986
0
                        "insufficient padding for first pass xref stream; first_xref_end=" +
2987
0
                        std::to_string(first_xref_end) + "; endpos=" + std::to_string(endpos));
2988
0
                }
2989
0
            }
2990
0
            write("\n");
2991
0
        } else {
2992
0
            writeXRefTable(
2993
0
                t_lin_first,
2994
0
                first_half_start,
2995
0
                first_half_end,
2996
0
                first_trailer_size,
2997
0
                hint_length + second_xref_offset,
2998
0
                (pass == 1),
2999
0
                hint_id,
3000
0
                hint_offset,
3001
0
                hint_length,
3002
0
                pass);
3003
0
            write("startxref\n0\n%%EOF\n");
3004
0
        }
3005
3006
        // Parts 4 through 9
3007
3008
0
        for (auto const& cur_object: object_queue) {
3009
0
            if (cur_object.getObjectID() == part6_end_marker) {
3010
0
                first_half_max_obj_offset = pipeline->getCount();
3011
0
            }
3012
0
            writeObject(cur_object);
3013
0
            if (cur_object.getObjectID() == part4_end_marker) {
3014
0
                if (encryption) {
3015
0
                    writeEncryptionDictionary();
3016
0
                }
3017
0
                if (pass == 1) {
3018
0
                    new_obj[hint_id].xref = QPDFXRefEntry(pipeline->getCount());
3019
0
                } else {
3020
                    // Part 5: hint stream
3021
0
                    write(hint_buffer);
3022
0
                }
3023
0
            }
3024
0
            if (cur_object.getObjectID() == part6_end_marker) {
3025
0
                part6_end_offset = pipeline->getCount();
3026
0
            }
3027
0
        }
3028
3029
        // Part 10: overflow hint stream -- not used
3030
3031
        // Part 11: main cross reference table and trailer
3032
3033
0
        second_xref_offset = pipeline->getCount();
3034
0
        if (need_xref_stream) {
3035
0
            pos = pipeline->getCount();
3036
0
            space_before_zero = writeXRefStream(
3037
0
                second_half_xref,
3038
0
                second_half_end,
3039
0
                second_xref_offset,
3040
0
                t_lin_second,
3041
0
                0,
3042
0
                second_half_end,
3043
0
                second_trailer_size,
3044
0
                0,
3045
0
                0,
3046
0
                0,
3047
0
                0,
3048
0
                (pass == 1),
3049
0
                pass);
3050
0
            qpdf_offset_t endpos = pipeline->getCount();
3051
3052
0
            if (pass == 1) {
3053
                // Pad so we have enough room for the real xref stream.  See comments for previous
3054
                // xref stream on how we calculate the padding.
3055
0
                write(calculateXrefStreamPadding(endpos - pos), ' ').write("\n");
3056
0
                second_xref_end = pipeline->getCount();
3057
0
            } else {
3058
                // Make the file size the same.
3059
0
                auto padding =
3060
0
                    QIntC::to_size(second_xref_end + hint_length - 1 - pipeline->getCount());
3061
0
                write(padding, ' ').write("\n");
3062
3063
                // If this assertion fails, maybe we didn't have enough padding above.
3064
0
                if (pipeline->getCount() != second_xref_end + hint_length) {
3065
0
                    throw std::logic_error(
3066
0
                        "count mismatch after xref stream; possible insufficient padding?");
3067
0
                }
3068
0
            }
3069
0
        } else {
3070
0
            space_before_zero = writeXRefTable(
3071
0
                t_lin_second, 0, second_half_end, second_trailer_size, 0, false, 0, 0, 0, pass);
3072
0
        }
3073
0
        write("startxref\n").write(first_xref_offset).write("\n%%EOF\n");
3074
3075
0
        if (pass == 1) {
3076
0
            if (cfg.deterministic_id()) {
3077
0
                QTC::TC("qpdf", "QPDFWriter linearized deterministic ID", need_xref_stream ? 0 : 1);
3078
0
                computeDeterministicIDData();
3079
0
                pp_md5.pop();
3080
0
            }
3081
3082
            // Close first pass pipeline
3083
0
            file_size = pipeline->getCount();
3084
0
            pp_pass1.pop();
3085
3086
            // Save hint offset since it will be set to zero by calling openObject.
3087
0
            qpdf_offset_t hint_offset1 = new_obj[hint_id].xref.getOffset();
3088
3089
            // Write hint stream to a buffer
3090
0
            {
3091
0
                auto pp_hint = pipeline_stack.activate(hint_buffer);
3092
0
                writeHintStream(hint_id);
3093
0
            }
3094
0
            hint_length = QIntC::to_offset(hint_buffer.size());
3095
3096
            // Restore hint offset
3097
0
            new_obj[hint_id].xref = QPDFXRefEntry(hint_offset1);
3098
0
            if (lin_pass1_file) {
3099
                // Write some debugging information
3100
0
                fprintf(
3101
0
                    lin_pass1_file, "%% hint_offset=%s\n", std::to_string(hint_offset1).c_str());
3102
0
                fprintf(lin_pass1_file, "%% hint_length=%s\n", std::to_string(hint_length).c_str());
3103
0
                fprintf(
3104
0
                    lin_pass1_file,
3105
0
                    "%% second_xref_offset=%s\n",
3106
0
                    std::to_string(second_xref_offset).c_str());
3107
0
                fprintf(
3108
0
                    lin_pass1_file,
3109
0
                    "%% second_xref_end=%s\n",
3110
0
                    std::to_string(second_xref_end).c_str());
3111
0
                fclose(lin_pass1_file);
3112
0
                lin_pass1_file = nullptr;
3113
0
            }
3114
0
        }
3115
0
    }
3116
0
}
3117
3118
void
3119
impl::Writer::enqueueObjectsStandard()
3120
9.28k
{
3121
9.28k
    if (cfg.preserve_unreferenced()) {
3122
0
        for (auto const& oh: qpdf.getAllObjects()) {
3123
0
            enqueue(oh);
3124
0
        }
3125
0
    }
3126
3127
    // Put root first on queue.
3128
9.28k
    auto trailer = trimmed_trailer();
3129
9.28k
    enqueue(trailer["/Root"]);
3130
3131
    // Next place any other objects referenced from the trailer dictionary into the queue, handling
3132
    // direct objects recursively. Root is already there, so enqueuing it a second time is a no-op.
3133
16.7k
    for (auto& item: trailer) {
3134
16.7k
        if (!item.second.null()) {
3135
14.5k
            enqueue(item.second);
3136
14.5k
        }
3137
16.7k
    }
3138
9.28k
}
3139
3140
void
3141
impl::Writer::enqueueObjectsPCLm()
3142
0
{
3143
    // Image transform stream content for page strip images. Each of this new stream has to come
3144
    // after every page image strip written in the pclm file.
3145
0
    std::string image_transform_content = "q /image Do Q\n";
3146
3147
    // enqueue all pages first
3148
0
    for (auto& page: pages) {
3149
0
        enqueue(page);
3150
0
        enqueue(page["/Contents"]);
3151
3152
        // enqueue all the strips for each page
3153
0
        for (auto& image: Dictionary(page["/Resources"]["/XObject"])) {
3154
0
            if (!image.second.null()) {
3155
0
                enqueue(image.second);
3156
0
                enqueue(qpdf.newStream(image_transform_content));
3157
0
            }
3158
0
        }
3159
0
    }
3160
3161
0
    enqueue(trimmed_trailer()["/Root"]);
3162
0
}
3163
3164
void
3165
impl::Writer::indicateProgress(bool decrement, bool finished)
3166
128k
{
3167
128k
    if (decrement) {
3168
22.4k
        --events_seen;
3169
22.4k
        return;
3170
22.4k
    }
3171
3172
106k
    ++events_seen;
3173
3174
106k
    if (!progress_reporter.get()) {
3175
106k
        return;
3176
106k
    }
3177
3178
0
    if (finished || events_seen >= next_progress_report) {
3179
0
        int percentage =
3180
0
            (finished ? 100
3181
0
                 : next_progress_report == 0
3182
0
                 ? 0
3183
0
                 : std::min(99, 1 + ((100 * events_seen) / events_expected)));
3184
0
        if (cfg.linearize()) {
3185
            // When linearizing, we register a separate progress reporter with the linearization
3186
            // engine and scale its progress to the first half of overall progress. This logic moves
3187
            // the writer's internal progress to the second half. The division is not really 50%,
3188
            // but this still results in a meaningful and relatively steady advancement of progress.
3189
            // Otherwise, progress reporting doesn't start until after the linearization
3190
            // computations are done.
3191
0
            percentage = 50 + percentage / 2;
3192
0
        }
3193
0
        progress_reporter->reportProgress(percentage);
3194
0
    }
3195
0
    int increment = std::max(1, (events_expected / 100));
3196
0
    while (events_seen >= next_progress_report) {
3197
0
        next_progress_report += increment;
3198
0
    }
3199
0
}
3200
3201
void
3202
QPDFWriter::registerProgressReporter(std::shared_ptr<ProgressReporter> pr)
3203
0
{
3204
0
    m->progress_reporter = pr;
3205
    // When writing linearized files, linearization accounts for a significant fraction of the total
3206
    // time. Register a linearization progress callback, and then normalize its output to the first
3207
    // half of the overall progress. This is only used when we linearize. When linearizing,
3208
    // Writer::indicateProgress scales remaining progress to the second half.
3209
0
    m->lin.progress_callback([pr, last_reported = -1](int analysis_pct) mutable {
3210
0
        int p = analysis_pct / 2;
3211
0
        if (p != last_reported) {
3212
0
            pr->reportProgress(p);
3213
0
            last_reported = p;
3214
0
        }
3215
0
    });
3216
0
}
3217
3218
void
3219
impl::Writer::writeStandard()
3220
9.28k
{
3221
9.28k
    auto pp_md5 = pipeline_stack.popper();
3222
9.28k
    if (cfg.deterministic_id()) {
3223
9.28k
        pipeline_stack.activate_md5(pp_md5);
3224
9.28k
    }
3225
3226
    // Start writing
3227
3228
9.28k
    writeHeader();
3229
9.28k
    write(cfg.extra_header_text());
3230
3231
9.28k
    if (cfg.pclm()) {
3232
0
        enqueueObjectsPCLm();
3233
9.28k
    } else {
3234
9.28k
        enqueueObjectsStandard();
3235
9.28k
    }
3236
3237
    // Now start walking queue, outputting each object.
3238
88.3k
    while (object_queue_front < object_queue.size()) {
3239
79.0k
        QPDFObjectHandle cur_object = object_queue.at(object_queue_front);
3240
79.0k
        ++object_queue_front;
3241
79.0k
        writeObject(cur_object);
3242
79.0k
    }
3243
3244
    // Write out the encryption dictionary, if any
3245
9.28k
    if (encryption) {
3246
0
        writeEncryptionDictionary();
3247
0
    }
3248
3249
    // Now write out xref.  next_objid is now the number of objects.
3250
9.28k
    qpdf_offset_t xref_offset = pipeline->getCount();
3251
9.28k
    if (object_stream_to_objects.empty()) {
3252
        // Write regular cross-reference table
3253
8.83k
        writeXRefTable(t_normal, 0, next_objid - 1, next_objid);
3254
8.83k
    } else {
3255
        // Write cross-reference stream.
3256
455
        int xref_id = next_objid++;
3257
455
        writeXRefStream(xref_id, xref_id, xref_offset, t_normal, 0, next_objid - 1, next_objid);
3258
455
    }
3259
9.28k
    write("startxref\n").write(xref_offset).write("\n%%EOF\n");
3260
3261
9.28k
    if (cfg.deterministic_id()) {
3262
9.18k
        QTC::TC(
3263
9.18k
            "qpdf",
3264
9.18k
            "QPDFWriter standard deterministic ID",
3265
9.18k
            object_stream_to_objects.empty() ? 0 : 1);
3266
9.18k
    }
3267
9.28k
}