forked from qpdf/qpdf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQPDFWriter.cc
3653 lines (3366 loc) · 104 KB
/
QPDFWriter.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <qpdf/qpdf-config.h> // include first for large file support
#include <qpdf/QPDFWriter.hh>
#include <assert.h>
#include <qpdf/Pl_StdioFile.hh>
#include <qpdf/Pl_Count.hh>
#include <qpdf/Pl_Discard.hh>
#include <qpdf/Pl_RC4.hh>
#include <qpdf/Pl_AES_PDF.hh>
#include <qpdf/Pl_Flate.hh>
#include <qpdf/Pl_PNGFilter.hh>
#include <qpdf/Pl_MD5.hh>
#include <qpdf/QUtil.hh>
#include <qpdf/MD5.hh>
#include <qpdf/RC4.hh>
#include <qpdf/QTC.hh>
#include <qpdf/QPDF.hh>
#include <qpdf/QPDFObjectHandle.hh>
#include <qpdf/QPDF_Name.hh>
#include <qpdf/QPDF_String.hh>
#include <qpdf/QIntC.hh>
#include <algorithm>
#include <stdlib.h>
QPDFWriter::Members::Members(QPDF& pdf) :
pdf(pdf),
filename("unspecified"),
file(0),
close_file(false),
buffer_pipeline(0),
output_buffer(0),
normalize_content_set(false),
normalize_content(false),
compress_streams(true),
compress_streams_set(false),
stream_decode_level(qpdf_dl_none),
stream_decode_level_set(false),
recompress_flate(false),
qdf_mode(false),
preserve_unreferenced_objects(false),
newline_before_endstream(false),
static_id(false),
suppress_original_object_ids(false),
direct_stream_lengths(true),
encrypted(false),
preserve_encryption(true),
linearized(false),
pclm(false),
object_stream_mode(qpdf_o_preserve),
encrypt_metadata(true),
encrypt_use_aes(false),
encryption_V(0),
encryption_R(0),
final_extension_level(0),
min_extension_level(0),
forced_extension_level(0),
encryption_dict_objid(0),
pipeline(0),
next_objid(1),
cur_stream_length_id(0),
cur_stream_length(0),
added_newline(false),
max_ostream_index(0),
next_stack_id(0),
deterministic_id(false),
md5_pipeline(0),
did_write_setup(false),
events_expected(0),
events_seen(0),
next_progress_report(0)
{
}
QPDFWriter::Members::~Members()
{
if (file && close_file)
{
fclose(file);
}
delete output_buffer;
}
QPDFWriter::QPDFWriter(QPDF& pdf) :
m(new Members(pdf))
{
}
QPDFWriter::QPDFWriter(QPDF& pdf, char const* filename) :
m(new Members(pdf))
{
setOutputFilename(filename);
}
QPDFWriter::QPDFWriter(QPDF& pdf, char const* description,
FILE *file, bool close_file) :
m(new Members(pdf))
{
setOutputFile(description, file, close_file);
}
QPDFWriter::~QPDFWriter()
{
}
void
QPDFWriter::setOutputFilename(char const* filename)
{
char const* description = filename;
FILE* f = 0;
bool close_file = false;
if (filename == 0)
{
description = "standard output";
QTC::TC("qpdf", "QPDFWriter write to stdout");
f = stdout;
QUtil::binary_stdout();
}
else
{
QTC::TC("qpdf", "QPDFWriter write to file");
f = QUtil::safe_fopen(filename, "wb+");
close_file = true;
}
setOutputFile(description, f, close_file);
}
void
QPDFWriter::setOutputFile(char const* description, FILE* file, bool close_file)
{
this->m->filename = description;
this->m->file = file;
this->m->close_file = close_file;
Pipeline* p = new Pl_StdioFile("qpdf output", file);
this->m->to_delete.push_back(p);
initializePipelineStack(p);
}
void
QPDFWriter::setOutputMemory()
{
this->m->filename = "memory buffer";
this->m->buffer_pipeline = new Pl_Buffer("qpdf output");
this->m->to_delete.push_back(this->m->buffer_pipeline);
initializePipelineStack(this->m->buffer_pipeline);
}
Buffer*
QPDFWriter::getBuffer()
{
Buffer* result = this->m->output_buffer;
this->m->output_buffer = 0;
return result;
}
void
QPDFWriter::setOutputPipeline(Pipeline* p)
{
this->m->filename = "custom pipeline";
initializePipelineStack(p);
}
void
QPDFWriter::setObjectStreamMode(qpdf_object_stream_e mode)
{
this->m->object_stream_mode = mode;
}
void
QPDFWriter::setStreamDataMode(qpdf_stream_data_e mode)
{
switch (mode)
{
case qpdf_s_uncompress:
this->m->stream_decode_level =
std::max(qpdf_dl_generalized, this->m->stream_decode_level);
this->m->compress_streams = false;
break;
case qpdf_s_preserve:
this->m->stream_decode_level = qpdf_dl_none;
this->m->compress_streams = false;
break;
case qpdf_s_compress:
this->m->stream_decode_level =
std::max(qpdf_dl_generalized, this->m->stream_decode_level);
this->m->compress_streams = true;
break;
}
this->m->stream_decode_level_set = true;
this->m->compress_streams_set = true;
}
void
QPDFWriter::setCompressStreams(bool val)
{
this->m->compress_streams = val;
this->m->compress_streams_set = true;
}
void
QPDFWriter::setDecodeLevel(qpdf_stream_decode_level_e val)
{
this->m->stream_decode_level = val;
this->m->stream_decode_level_set = true;
}
void
QPDFWriter::setRecompressFlate(bool val)
{
this->m->recompress_flate = val;
}
void
QPDFWriter::setContentNormalization(bool val)
{
this->m->normalize_content_set = true;
this->m->normalize_content = val;
}
void
QPDFWriter::setQDFMode(bool val)
{
this->m->qdf_mode = val;
}
void
QPDFWriter::setPreserveUnreferencedObjects(bool val)
{
this->m->preserve_unreferenced_objects = val;
}
void
QPDFWriter::setNewlineBeforeEndstream(bool val)
{
this->m->newline_before_endstream = val;
}
void
QPDFWriter::setMinimumPDFVersion(std::string const& version,
int extension_level)
{
bool set_version = false;
bool set_extension_level = false;
if (this->m->min_pdf_version.empty())
{
set_version = true;
set_extension_level = true;
}
else
{
int old_major = 0;
int old_minor = 0;
int min_major = 0;
int min_minor = 0;
parseVersion(version, old_major, old_minor);
parseVersion(this->m->min_pdf_version, min_major, min_minor);
int compare = compareVersions(
old_major, old_minor, min_major, min_minor);
if (compare > 0)
{
QTC::TC("qpdf", "QPDFWriter increasing minimum version",
extension_level == 0 ? 0 : 1);
set_version = true;
set_extension_level = true;
}
else if (compare == 0)
{
if (extension_level > this->m->min_extension_level)
{
QTC::TC("qpdf", "QPDFWriter increasing extension level");
set_extension_level = true;
}
}
}
if (set_version)
{
this->m->min_pdf_version = version;
}
if (set_extension_level)
{
this->m->min_extension_level = extension_level;
}
}
void
QPDFWriter::forcePDFVersion(std::string const& version,
int extension_level)
{
this->m->forced_pdf_version = version;
this->m->forced_extension_level = extension_level;
}
void
QPDFWriter::setExtraHeaderText(std::string const& text)
{
this->m->extra_header_text = text;
if ((this->m->extra_header_text.length() > 0) &&
(*(this->m->extra_header_text.rbegin()) != '\n'))
{
QTC::TC("qpdf", "QPDFWriter extra header text add newline");
this->m->extra_header_text += "\n";
}
else
{
QTC::TC("qpdf", "QPDFWriter extra header text no newline");
}
}
void
QPDFWriter::setStaticID(bool val)
{
this->m->static_id = val;
}
void
QPDFWriter::setDeterministicID(bool val)
{
this->m->deterministic_id = val;
}
void
QPDFWriter::setStaticAesIV(bool val)
{
if (val)
{
Pl_AES_PDF::useStaticIV();
}
}
void
QPDFWriter::setSuppressOriginalObjectIDs(bool val)
{
this->m->suppress_original_object_ids = val;
}
void
QPDFWriter::setPreserveEncryption(bool val)
{
this->m->preserve_encryption = val;
}
void
QPDFWriter::setLinearization(bool val)
{
this->m->linearized = val;
if (val)
{
this->m->pclm = false;
}
}
void
QPDFWriter::setLinearizationPass1Filename(std::string const& filename)
{
this->m->lin_pass1_filename = filename;
}
void
QPDFWriter::setPCLm(bool val)
{
this->m->pclm = val;
if (val)
{
this->m->linearized = false;
}
}
void
QPDFWriter::setR2EncryptionParameters(
char const* user_password, char const* owner_password,
bool allow_print, bool allow_modify,
bool allow_extract, bool allow_annotate)
{
std::set<int> clear;
if (! allow_print)
{
clear.insert(3);
}
if (! allow_modify)
{
clear.insert(4);
}
if (! allow_extract)
{
clear.insert(5);
}
if (! allow_annotate)
{
clear.insert(6);
}
setEncryptionParameters(user_password, owner_password, 1, 2, 5, clear);
}
void
QPDFWriter::setR3EncryptionParameters(
char const* user_password, char const* owner_password,
bool allow_accessibility, bool allow_extract,
qpdf_r3_print_e print, qpdf_r3_modify_e modify)
{
std::set<int> clear;
interpretR3EncryptionParameters(
clear, user_password, owner_password,
allow_accessibility, allow_extract,
true, true, true, true, print, modify);
setEncryptionParameters(user_password, owner_password, 2, 3, 16, clear);
}
void
QPDFWriter::setR3EncryptionParameters(
char const* user_password, char const* owner_password,
bool allow_accessibility, bool allow_extract,
bool allow_assemble, bool allow_annotate_and_form,
bool allow_form_filling, bool allow_modify_other,
qpdf_r3_print_e print)
{
std::set<int> clear;
interpretR3EncryptionParameters(
clear, user_password, owner_password,
allow_accessibility, allow_extract,
allow_assemble, allow_annotate_and_form,
allow_form_filling, allow_modify_other,
print, qpdf_r3m_all);
setEncryptionParameters(user_password, owner_password, 2, 3, 16, clear);
}
void
QPDFWriter::setR4EncryptionParameters(
char const* user_password, char const* owner_password,
bool allow_accessibility, bool allow_extract,
qpdf_r3_print_e print, qpdf_r3_modify_e modify,
bool encrypt_metadata, bool use_aes)
{
std::set<int> clear;
interpretR3EncryptionParameters(
clear, user_password, owner_password,
allow_accessibility, allow_extract,
true, true, true, true, print, modify);
this->m->encrypt_use_aes = use_aes;
this->m->encrypt_metadata = encrypt_metadata;
setEncryptionParameters(user_password, owner_password, 4, 4, 16, clear);
}
void
QPDFWriter::setR4EncryptionParameters(
char const* user_password, char const* owner_password,
bool allow_accessibility, bool allow_extract,
bool allow_assemble, bool allow_annotate_and_form,
bool allow_form_filling, bool allow_modify_other,
qpdf_r3_print_e print,
bool encrypt_metadata, bool use_aes)
{
std::set<int> clear;
interpretR3EncryptionParameters(
clear, user_password, owner_password,
allow_accessibility, allow_extract,
allow_assemble, allow_annotate_and_form,
allow_form_filling, allow_modify_other,
print, qpdf_r3m_all);
this->m->encrypt_use_aes = use_aes;
this->m->encrypt_metadata = encrypt_metadata;
setEncryptionParameters(user_password, owner_password, 4, 4, 16, clear);
}
void
QPDFWriter::setR5EncryptionParameters(
char const* user_password, char const* owner_password,
bool allow_accessibility, bool allow_extract,
qpdf_r3_print_e print, qpdf_r3_modify_e modify,
bool encrypt_metadata)
{
std::set<int> clear;
interpretR3EncryptionParameters(
clear, user_password, owner_password,
allow_accessibility, allow_extract,
true, true, true, true, print, modify);
this->m->encrypt_use_aes = true;
this->m->encrypt_metadata = encrypt_metadata;
setEncryptionParameters(user_password, owner_password, 5, 5, 32, clear);
}
void
QPDFWriter::setR5EncryptionParameters(
char const* user_password, char const* owner_password,
bool allow_accessibility, bool allow_extract,
bool allow_assemble, bool allow_annotate_and_form,
bool allow_form_filling, bool allow_modify_other,
qpdf_r3_print_e print,
bool encrypt_metadata)
{
std::set<int> clear;
interpretR3EncryptionParameters(
clear, user_password, owner_password,
allow_accessibility, allow_extract,
allow_assemble, allow_annotate_and_form,
allow_form_filling, allow_modify_other,
print, qpdf_r3m_all);
this->m->encrypt_use_aes = true;
this->m->encrypt_metadata = encrypt_metadata;
setEncryptionParameters(user_password, owner_password, 5, 5, 32, clear);
}
void
QPDFWriter::setR6EncryptionParameters(
char const* user_password, char const* owner_password,
bool allow_accessibility, bool allow_extract,
qpdf_r3_print_e print, qpdf_r3_modify_e modify,
bool encrypt_metadata)
{
std::set<int> clear;
interpretR3EncryptionParameters(
clear, user_password, owner_password,
allow_accessibility, allow_extract,
true, true, true, true, print, modify);
this->m->encrypt_use_aes = true;
this->m->encrypt_metadata = encrypt_metadata;
setEncryptionParameters(user_password, owner_password, 5, 6, 32, clear);
}
void
QPDFWriter::setR6EncryptionParameters(
char const* user_password, char const* owner_password,
bool allow_accessibility, bool allow_extract,
bool allow_assemble, bool allow_annotate_and_form,
bool allow_form_filling, bool allow_modify_other,
qpdf_r3_print_e print,
bool encrypt_metadata)
{
std::set<int> clear;
interpretR3EncryptionParameters(
clear, user_password, owner_password,
allow_accessibility, allow_extract,
allow_assemble, allow_annotate_and_form,
allow_form_filling, allow_modify_other,
print, qpdf_r3m_all);
this->m->encrypt_use_aes = true;
this->m->encrypt_metadata = encrypt_metadata;
setEncryptionParameters(user_password, owner_password, 5, 6, 32, clear);
}
void
QPDFWriter::interpretR3EncryptionParameters(
std::set<int>& clear,
char const* user_password, char const* owner_password,
bool allow_accessibility, bool allow_extract,
bool allow_assemble, bool allow_annotate_and_form,
bool allow_form_filling, bool allow_modify_other,
qpdf_r3_print_e print, qpdf_r3_modify_e modify)
{
// Acrobat 5 security options:
// Checkboxes:
// Enable Content Access for the Visually Impaired
// Allow Content Copying and Extraction
// Allowed changes menu:
// None
// Only Document Assembly
// Only Form Field Fill-in or Signing
// Comment Authoring, Form Field Fill-in or Signing
// General Editing, Comment and Form Field Authoring
// Allowed printing menu:
// None
// Low Resolution
// Full printing
// Meanings of bits in P when R >= 3
//
// 3: low-resolution printing
// 4: document modification except as controlled by 6, 9, and 11
// 5: extraction
// 6: add/modify annotations (comment), fill in forms
// if 4+6 are set, also allows modification of form fields
// 9: fill in forms even if 6 is clear
// 10: accessibility; ignored by readers, should always be set
// 11: document assembly even if 4 is clear
// 12: high-resolution printing
if (! allow_accessibility)
{
// setEncryptionParameters sets this if R > 3
clear.insert(10);
}
if (! allow_extract)
{
clear.insert(5);
}
// Note: these switch statements all "fall through" (no break
// statements). Each option clears successively more access bits.
switch (print)
{
case qpdf_r3p_none:
clear.insert(3); // any printing
case qpdf_r3p_low:
clear.insert(12); // high resolution printing
case qpdf_r3p_full:
break;
// no default so gcc warns for missing cases
}
// Modify options. The qpdf_r3_modify_e options control groups of
// bits and lack the full flexibility of the spec. This is
// unfortunate, but it's been in the API for ages, and we're stuck
// with it. See also allow checks below to control the bits
// individually.
// NOT EXERCISED IN TEST SUITE
switch (modify)
{
case qpdf_r3m_none:
clear.insert(11); // document assembly
case qpdf_r3m_assembly:
clear.insert(9); // filling in form fields
case qpdf_r3m_form:
clear.insert(6); // modify annotations, fill in form fields
case qpdf_r3m_annotate:
clear.insert(4); // other modifications
case qpdf_r3m_all:
break;
// no default so gcc warns for missing cases
}
// END NOT EXERCISED IN TEST SUITE
if (! allow_assemble)
{
clear.insert(11);
}
if (! allow_annotate_and_form)
{
clear.insert(6);
}
if (! allow_form_filling)
{
clear.insert(9);
}
if (! allow_modify_other)
{
clear.insert(4);
}
}
void
QPDFWriter::setEncryptionParameters(
char const* user_password, char const* owner_password,
int V, int R, int key_len, std::set<int>& bits_to_clear)
{
// PDF specification refers to bits with the low bit numbered 1.
// We have to convert this into a bit field.
// Specification always requires bits 1 and 2 to be cleared.
bits_to_clear.insert(1);
bits_to_clear.insert(2);
if (R > 3)
{
// Bit 10 is deprecated and should always be set. This used
// to mean accessibility. There is no way to disable
// accessibility with R > 3.
bits_to_clear.erase(10);
}
int P = 0;
// Create the complement of P, then invert.
for (std::set<int>::iterator iter = bits_to_clear.begin();
iter != bits_to_clear.end(); ++iter)
{
P |= (1 << ((*iter) - 1));
}
P = ~P;
generateID();
std::string O;
std::string U;
std::string OE;
std::string UE;
std::string Perms;
std::string encryption_key;
if (V < 5)
{
QPDF::compute_encryption_O_U(
user_password, owner_password, V, R, key_len, P,
this->m->encrypt_metadata, this->m->id1, O, U);
}
else
{
QPDF::compute_encryption_parameters_V5(
user_password, owner_password, V, R, key_len, P,
this->m->encrypt_metadata, this->m->id1,
encryption_key, O, U, OE, UE, Perms);
}
setEncryptionParametersInternal(
V, R, key_len, P, O, U, OE, UE, Perms,
this->m->id1, user_password, encryption_key);
}
void
QPDFWriter::copyEncryptionParameters(QPDF& qpdf)
{
this->m->preserve_encryption = false;
QPDFObjectHandle trailer = qpdf.getTrailer();
if (trailer.hasKey("/Encrypt"))
{
generateID();
this->m->id1 =
trailer.getKey("/ID").getArrayItem(0).getStringValue();
QPDFObjectHandle encrypt = trailer.getKey("/Encrypt");
int V = encrypt.getKey("/V").getIntValueAsInt();
int key_len = 5;
if (V > 1)
{
key_len = encrypt.getKey("/Length").getIntValueAsInt() / 8;
}
if (encrypt.hasKey("/EncryptMetadata") &&
encrypt.getKey("/EncryptMetadata").isBool())
{
this->m->encrypt_metadata =
encrypt.getKey("/EncryptMetadata").getBoolValue();
}
if (V >= 4)
{
// When copying encryption parameters, use AES even if the
// original file did not. Acrobat doesn't create files
// with V >= 4 that don't use AES, and the logic of
// figuring out whether AES is used or not is complicated
// with /StmF, /StrF, and /EFF all potentially having
// different values.
this->m->encrypt_use_aes = true;
}
QTC::TC("qpdf", "QPDFWriter copy encrypt metadata",
this->m->encrypt_metadata ? 0 : 1);
QTC::TC("qpdf", "QPDFWriter copy use_aes",
this->m->encrypt_use_aes ? 0 : 1);
std::string OE;
std::string UE;
std::string Perms;
std::string encryption_key;
if (V >= 5)
{
QTC::TC("qpdf", "QPDFWriter copy V5");
OE = encrypt.getKey("/OE").getStringValue();
UE = encrypt.getKey("/UE").getStringValue();
Perms = encrypt.getKey("/Perms").getStringValue();
encryption_key = qpdf.getEncryptionKey();
}
setEncryptionParametersInternal(
V,
encrypt.getKey("/R").getIntValueAsInt(),
key_len,
encrypt.getKey("/P").getIntValueAsInt(),
encrypt.getKey("/O").getStringValue(),
encrypt.getKey("/U").getStringValue(),
OE,
UE,
Perms,
this->m->id1, // this->m->id1 == the other file's id1
qpdf.getPaddedUserPassword(),
encryption_key);
}
}
void
QPDFWriter::disableIncompatibleEncryption(int major, int minor,
int extension_level)
{
if (! this->m->encrypted)
{
return;
}
bool disable = false;
if (compareVersions(major, minor, 1, 3) < 0)
{
disable = true;
}
else
{
int V = QUtil::string_to_int(
this->m->encryption_dictionary["/V"].c_str());
int R = QUtil::string_to_int(
this->m->encryption_dictionary["/R"].c_str());
if (compareVersions(major, minor, 1, 4) < 0)
{
if ((V > 1) || (R > 2))
{
disable = true;
}
}
else if (compareVersions(major, minor, 1, 5) < 0)
{
if ((V > 2) || (R > 3))
{
disable = true;
}
}
else if (compareVersions(major, minor, 1, 6) < 0)
{
if (this->m->encrypt_use_aes)
{
disable = true;
}
}
else if ((compareVersions(major, minor, 1, 7) < 0) ||
((compareVersions(major, minor, 1, 7) == 0) &&
extension_level < 3))
{
if ((V >= 5) || (R >= 5))
{
disable = true;
}
}
}
if (disable)
{
QTC::TC("qpdf", "QPDFWriter forced version disabled encryption");
this->m->encrypted = false;
}
}
void
QPDFWriter::parseVersion(std::string const& version,
int& major, int& minor) const
{
major = QUtil::string_to_int(version.c_str());
minor = 0;
size_t p = version.find('.');
if ((p != std::string::npos) && (version.length() > p))
{
minor = QUtil::string_to_int(version.substr(p + 1).c_str());
}
std::string tmp = QUtil::int_to_string(major) + "." +
QUtil::int_to_string(minor);
if (tmp != version)
{
// The version number in the input is probably invalid. This
// happens with some files that are designed to exercise bugs,
// such as files in the fuzzer corpus. Unfortunately
// QPDFWriter doesn't have a way to give a warning, so we just
// ignore this case.
}
}
int
QPDFWriter::compareVersions(int major1, int minor1,
int major2, int minor2) const
{
if (major1 < major2)
{
return -1;
}
else if (major1 > major2)
{
return 1;
}
else if (minor1 < minor2)
{
return -1;
}
else if (minor1 > minor2)
{
return 1;
}
else
{
return 0;
}
}
void
QPDFWriter::setEncryptionParametersInternal(
int V, int R, int key_len, int P,
std::string const& O, std::string const& U,
std::string const& OE, std::string const& UE, std::string const& Perms,
std::string const& id1, std::string const& user_password,
std::string const& encryption_key)
{
this->m->encryption_V = V;
this->m->encryption_R = R;
this->m->encryption_dictionary["/Filter"] = "/Standard";
this->m->encryption_dictionary["/V"] = QUtil::int_to_string(V);
this->m->encryption_dictionary["/Length"] =
QUtil::int_to_string(key_len * 8);
this->m->encryption_dictionary["/R"] = QUtil::int_to_string(R);
this->m->encryption_dictionary["/P"] = QUtil::int_to_string(P);
this->m->encryption_dictionary["/O"] = QPDF_String(O).unparse(true);
this->m->encryption_dictionary["/U"] = QPDF_String(U).unparse(true);
if (V >= 5)
{
this->m->encryption_dictionary["/OE"] = QPDF_String(OE).unparse(true);
this->m->encryption_dictionary["/UE"] = QPDF_String(UE).unparse(true);
this->m->encryption_dictionary["/Perms"] =
QPDF_String(Perms).unparse(true);
}
if (R >= 6)
{
setMinimumPDFVersion("1.7", 8);
}
else if (R == 5)
{
setMinimumPDFVersion("1.7", 3);
}
else if (R == 4)
{
setMinimumPDFVersion(this->m->encrypt_use_aes ? "1.6" : "1.5");
}
else if (R == 3)
{
setMinimumPDFVersion("1.4");
}
else
{
setMinimumPDFVersion("1.3");
}
if ((R >= 4) && (! this->m->encrypt_metadata))
{
this->m->encryption_dictionary["/EncryptMetadata"] = "false";
}
if ((V == 4) || (V == 5))
{
// The spec says the value for the crypt filter key can be
// anything, and xpdf seems to agree. However, Adobe Reader
// won't open our files unless we use /StdCF.
this->m->encryption_dictionary["/StmF"] = "/StdCF";
this->m->encryption_dictionary["/StrF"] = "/StdCF";
std::string method = (this->m->encrypt_use_aes
? ((V < 5) ? "/AESV2" : "/AESV3")
: "/V2");
// The PDF spec says the /Length key is optional, but the PDF
// previewer on some versions of MacOS won't open encrypted
// files without it.
this->m->encryption_dictionary["/CF"] =
"<< /StdCF << /AuthEvent /DocOpen /CFM " + method +
" /Length " + std::string((V < 5) ? "16" : "32") + " >> >>";
}
this->m->encrypted = true;
QPDF::EncryptionData encryption_data(
V, R, key_len, P, O, U, OE, UE, Perms, id1, this->m->encrypt_metadata);
if (V < 5)
{
this->m->encryption_key = QPDF::compute_encryption_key(
user_password, encryption_data);
}
else
{
this->m->encryption_key = encryption_key;
}
}
void
QPDFWriter::setDataKey(int objid)
{
this->m->cur_data_key = QPDF::compute_data_key(
this->m->encryption_key, objid, 0,
this->m->encrypt_use_aes, this->m->encryption_V, this->m->encryption_R);
}
unsigned int
QPDFWriter::bytesNeeded(long long n)
{
unsigned int bytes = 0;
while (n)
{
++bytes;
n >>= 8;
}
return bytes;
}
void
QPDFWriter::writeBinary(unsigned long long val, unsigned int bytes)
{
if (bytes > sizeof(unsigned long long))
{
throw std::logic_error(
"QPDFWriter::writeBinary called with too many bytes");
}
unsigned char data[sizeof(unsigned long long)];
for (unsigned int i = 0; i < bytes; ++i)
{
data[bytes - i - 1] = static_cast<unsigned char>(val & 0xff);
val >>= 8;
}
this->m->pipeline->write(data, bytes);