forked from qpdf/qpdf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
QPDFJob.cc
3388 lines (3242 loc) · 120 KB
/
QPDFJob.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/QPDFJob.hh>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctype.h>
#include <fcntl.h>
#include <iostream>
#include <memory>
#include <qpdf/ClosedFileInputSource.hh>
#include <qpdf/FileInputSource.hh>
#include <qpdf/Pl_Count.hh>
#include <qpdf/Pl_DCT.hh>
#include <qpdf/Pl_Discard.hh>
#include <qpdf/Pl_Flate.hh>
#include <qpdf/Pl_OStream.hh>
#include <qpdf/Pl_StdioFile.hh>
#include <qpdf/Pl_String.hh>
#include <qpdf/QIntC.hh>
#include <qpdf/QPDF.hh>
#include <qpdf/QPDFAcroFormDocumentHelper.hh>
#include <qpdf/QPDFArgParser.hh>
#include <qpdf/QPDFCryptoProvider.hh>
#include <qpdf/QPDFEmbeddedFileDocumentHelper.hh>
#include <qpdf/QPDFExc.hh>
#include <qpdf/QPDFLogger.hh>
#include <qpdf/QPDFOutlineDocumentHelper.hh>
#include <qpdf/QPDFPageDocumentHelper.hh>
#include <qpdf/QPDFPageLabelDocumentHelper.hh>
#include <qpdf/QPDFPageObjectHelper.hh>
#include <qpdf/QPDFSystemError.hh>
#include <qpdf/QPDFUsage.hh>
#include <qpdf/QPDFWriter.hh>
#include <qpdf/QTC.hh>
#include <qpdf/QUtil.hh>
#include <qpdf/auto_job_schema.hh> // JOB_SCHEMA_DATA
namespace
{
class ImageOptimizer: public QPDFObjectHandle::StreamDataProvider
{
public:
ImageOptimizer(
QPDFJob& o,
size_t oi_min_width,
size_t oi_min_height,
size_t oi_min_area,
QPDFObjectHandle& image);
virtual ~ImageOptimizer() = default;
virtual void
provideStreamData(int objid, int generation, Pipeline* pipeline);
std::shared_ptr<Pipeline>
makePipeline(std::string const& description, Pipeline* next);
bool evaluate(std::string const& description);
private:
QPDFJob& o;
size_t oi_min_width;
size_t oi_min_height;
size_t oi_min_area;
QPDFObjectHandle image;
};
class DiscardContents: public QPDFObjectHandle::ParserCallbacks
{
public:
virtual ~DiscardContents() = default;
virtual void
handleObject(QPDFObjectHandle)
{
}
virtual void
handleEOF()
{
}
};
struct QPDFPageData
{
QPDFPageData(
std::string const& filename, QPDF* qpdf, std::string const& range);
QPDFPageData(QPDFPageData const& other, int page);
std::string filename;
QPDF* qpdf;
std::vector<QPDFObjectHandle> orig_pages;
std::vector<int> selected_pages;
};
class ProgressReporter: public QPDFWriter::ProgressReporter
{
public:
ProgressReporter(
Pipeline& p, std::string const& prefix, char const* filename) :
p(p),
prefix(prefix),
filename(filename)
{
}
virtual ~ProgressReporter() = default;
virtual void reportProgress(int);
private:
Pipeline& p;
std::string prefix;
std::string filename;
};
} // namespace
ImageOptimizer::ImageOptimizer(
QPDFJob& o,
size_t oi_min_width,
size_t oi_min_height,
size_t oi_min_area,
QPDFObjectHandle& image) :
o(o),
oi_min_width(oi_min_width),
oi_min_height(oi_min_height),
oi_min_area(oi_min_area),
image(image)
{
}
std::shared_ptr<Pipeline>
ImageOptimizer::makePipeline(std::string const& description, Pipeline* next)
{
std::shared_ptr<Pipeline> result;
QPDFObjectHandle dict = image.getDict();
QPDFObjectHandle w_obj = dict.getKey("/Width");
QPDFObjectHandle h_obj = dict.getKey("/Height");
QPDFObjectHandle colorspace_obj = dict.getKey("/ColorSpace");
if (!(w_obj.isNumber() && h_obj.isNumber())) {
if (!description.empty()) {
o.doIfVerbose([&](Pipeline& v, std::string const& prefix) {
v << prefix << ": " << description
<< ": not optimizing because image dictionary"
<< " is missing required keys\n";
});
}
return result;
}
QPDFObjectHandle components_obj = dict.getKey("/BitsPerComponent");
if (!(components_obj.isInteger() && (components_obj.getIntValue() == 8))) {
QTC::TC("qpdf", "QPDFJob image optimize bits per component");
if (!description.empty()) {
o.doIfVerbose([&](Pipeline& v, std::string const& prefix) {
v << prefix << ": " << description
<< ": not optimizing because image has other than"
<< " 8 bits per component\n";
});
}
return result;
}
// Files have been seen in the wild whose width and height are
// floating point, which is goofy, but we can deal with it.
JDIMENSION w = 0;
if (w_obj.isInteger()) {
w = w_obj.getUIntValueAsUInt();
} else {
w = static_cast<JDIMENSION>(w_obj.getNumericValue());
}
JDIMENSION h = 0;
if (h_obj.isInteger()) {
h = h_obj.getUIntValueAsUInt();
} else {
h = static_cast<JDIMENSION>(h_obj.getNumericValue());
}
std::string colorspace =
(colorspace_obj.isName() ? colorspace_obj.getName() : std::string());
int components = 0;
J_COLOR_SPACE cs = JCS_UNKNOWN;
if (colorspace == "/DeviceRGB") {
components = 3;
cs = JCS_RGB;
} else if (colorspace == "/DeviceGray") {
components = 1;
cs = JCS_GRAYSCALE;
} else if (colorspace == "/DeviceCMYK") {
components = 4;
cs = JCS_CMYK;
} else {
QTC::TC("qpdf", "QPDFJob image optimize colorspace");
if (!description.empty()) {
o.doIfVerbose([&](Pipeline& v, std::string const& prefix) {
v << prefix << ": " << description
<< ": not optimizing because qpdf can't optimize"
<< " images with this colorspace\n";
});
}
return result;
}
if (((this->oi_min_width > 0) && (w <= this->oi_min_width)) ||
((this->oi_min_height > 0) && (h <= this->oi_min_height)) ||
((this->oi_min_area > 0) && ((w * h) <= this->oi_min_area))) {
QTC::TC("qpdf", "QPDFJob image optimize too small");
if (!description.empty()) {
o.doIfVerbose([&](Pipeline& v, std::string const& prefix) {
v << prefix << ": " << description
<< ": not optimizing because image"
<< " is smaller than requested minimum dimensions\n";
});
}
return result;
}
result = std::make_shared<Pl_DCT>("jpg", next, w, h, components, cs);
return result;
}
bool
ImageOptimizer::evaluate(std::string const& description)
{
if (!image.pipeStreamData(0, 0, qpdf_dl_specialized, true)) {
QTC::TC("qpdf", "QPDFJob image optimize no pipeline");
o.doIfVerbose([&](Pipeline& v, std::string const& prefix) {
v << prefix << ": " << description
<< ": not optimizing because unable to decode data"
<< " or data already uses DCT\n";
});
return false;
}
Pl_Discard d;
Pl_Count c("count", &d);
std::shared_ptr<Pipeline> p = makePipeline(description, &c);
if (p.get() == nullptr) {
// message issued by makePipeline
return false;
}
if (!image.pipeStreamData(p.get(), 0, qpdf_dl_specialized)) {
return false;
}
long long orig_length = image.getDict().getKey("/Length").getIntValue();
if (c.getCount() >= orig_length) {
QTC::TC("qpdf", "QPDFJob image optimize no shrink");
o.doIfVerbose([&](Pipeline& v, std::string const& prefix) {
v << prefix << ": " << description
<< ": not optimizing because DCT compression does not"
<< " reduce image size\n";
});
return false;
}
o.doIfVerbose([&](Pipeline& v, std::string const& prefix) {
v << prefix << ": " << description
<< ": optimizing image reduces size from " << orig_length << " to "
<< c.getCount() << "\n";
});
return true;
}
void
ImageOptimizer::provideStreamData(int, int, Pipeline* pipeline)
{
std::shared_ptr<Pipeline> p = makePipeline("", pipeline);
if (p.get() == nullptr) {
// Should not be possible
image.warnIfPossible("unable to create pipeline after previous"
" success; image data will be lost");
pipeline->finish();
return;
}
image.pipeStreamData(p.get(), 0, qpdf_dl_specialized, false, false);
}
QPDFJob::PageSpec::PageSpec(
std::string const& filename,
char const* password,
std::string const& range) :
filename(filename),
range(range)
{
if (password) {
this->password = QUtil::make_shared_cstr(password);
}
}
QPDFPageData::QPDFPageData(
std::string const& filename, QPDF* qpdf, std::string const& range) :
filename(filename),
qpdf(qpdf),
orig_pages(qpdf->getAllPages())
{
try {
this->selected_pages = QUtil::parse_numrange(
range.c_str(), QIntC::to_int(this->orig_pages.size()));
} catch (std::runtime_error& e) {
throw std::runtime_error(
"parsing numeric range for " + filename + ": " + e.what());
}
}
QPDFPageData::QPDFPageData(QPDFPageData const& other, int page) :
filename(other.filename),
qpdf(other.qpdf),
orig_pages(other.orig_pages)
{
this->selected_pages.push_back(page);
}
void
ProgressReporter::reportProgress(int percentage)
{
this->p << prefix << ": " << filename << ": write progress: " << percentage
<< "%\n";
}
// These default values are duplicated in help and docs.
static int constexpr DEFAULT_KEEP_FILES_OPEN_THRESHOLD = 200;
static int constexpr DEFAULT_OI_MIN_WIDTH = 128;
static int constexpr DEFAULT_OI_MIN_HEIGHT = 128;
static int constexpr DEFAULT_OI_MIN_AREA = 16384;
static int constexpr DEFAULT_II_MIN_BYTES = 1024;
QPDFJob::Members::Members() :
log(QPDFLogger::defaultLogger()),
message_prefix("qpdf"),
warnings(false),
encryption_status(0),
verbose(false),
password(0),
linearize(false),
decrypt(false),
split_pages(0),
progress(false),
progress_handler(nullptr),
suppress_warnings(false),
warnings_exit_zero(false),
copy_encryption(false),
encryption_file_password(0),
encrypt(false),
password_is_hex_key(false),
suppress_password_recovery(false),
password_mode(pm_auto),
allow_insecure(false),
allow_weak_crypto(false),
keylen(0),
r2_print(true),
r2_modify(true),
r2_extract(true),
r2_annotate(true),
r3_accessibility(true),
r3_extract(true),
r3_assemble(true),
r3_annotate_and_form(true),
r3_form_filling(true),
r3_modify_other(true),
r3_print(qpdf_r3p_full),
force_V4(false),
force_R5(false),
cleartext_metadata(false),
use_aes(false),
stream_data_set(false),
stream_data_mode(qpdf_s_compress),
compress_streams(true),
compress_streams_set(false),
recompress_flate(false),
recompress_flate_set(false),
compression_level(-1),
decode_level(qpdf_dl_generalized),
decode_level_set(false),
normalize_set(false),
normalize(false),
suppress_recovery(false),
object_stream_set(false),
object_stream_mode(qpdf_o_preserve),
ignore_xref_streams(false),
qdf_mode(false),
preserve_unreferenced_objects(false),
remove_unreferenced_page_resources(re_auto),
keep_files_open(true),
keep_files_open_set(false),
keep_files_open_threshold(DEFAULT_KEEP_FILES_OPEN_THRESHOLD),
newline_before_endstream(false),
coalesce_contents(false),
flatten_annotations(false),
flatten_annotations_required(0),
flatten_annotations_forbidden(an_invisible | an_hidden),
generate_appearances(false),
show_npages(false),
deterministic_id(false),
static_id(false),
static_aes_iv(false),
suppress_original_object_id(false),
show_encryption(false),
show_encryption_key(false),
check_linearization(false),
show_linearization(false),
show_xref(false),
show_trailer(false),
show_obj(0),
show_gen(0),
show_raw_stream_data(false),
show_filtered_stream_data(false),
show_pages(false),
show_page_images(false),
collate(0),
flatten_rotation(false),
list_attachments(false),
json_version(0),
json_stream_data(qpdf_sj_none),
json_stream_data_set(false),
test_json_schema(false),
check(false),
optimize_images(false),
externalize_inline_images(false),
keep_inline_images(false),
remove_page_labels(false),
oi_min_width(DEFAULT_OI_MIN_WIDTH),
oi_min_height(DEFAULT_OI_MIN_HEIGHT),
oi_min_area(DEFAULT_OI_MIN_AREA),
ii_min_bytes(DEFAULT_II_MIN_BYTES),
underlay("underlay"),
overlay("overlay"),
under_overlay(0),
require_outfile(true),
replace_input(false),
check_is_encrypted(false),
check_requires_password(false),
json_input(false),
json_output(0)
{
}
QPDFJob::QPDFJob() :
m(new Members())
{
}
void
QPDFJob::usage(std::string const& msg)
{
throw QPDFUsage(msg);
}
void
QPDFJob::setMessagePrefix(std::string const& message_prefix)
{
this->m->message_prefix = message_prefix;
}
std::string
QPDFJob::getMessagePrefix() const
{
return this->m->message_prefix;
}
std::shared_ptr<QPDFLogger>
QPDFJob::getLogger()
{
return this->m->log;
}
void
QPDFJob::setLogger(std::shared_ptr<QPDFLogger> l)
{
this->m->log = l;
}
void
QPDFJob::setOutputStreams(std::ostream* out, std::ostream* err)
{
setLogger(std::make_shared<QPDFLogger>());
this->m->log->setOutputStreams(out, err);
}
void
QPDFJob::registerProgressReporter(std::function<void(int)> handler)
{
this->m->progress_handler = handler;
}
void
QPDFJob::doIfVerbose(
std::function<void(Pipeline&, std::string const& prefix)> fn)
{
if (this->m->verbose) {
fn(*this->m->log->getInfo(), this->m->message_prefix);
}
}
std::shared_ptr<QPDFJob::Config>
QPDFJob::config()
{
return std::shared_ptr<Config>(new Config(*this));
}
std::string
QPDFJob::job_json_schema_v1()
{
return JOB_SCHEMA_DATA;
}
void
QPDFJob::parseRotationParameter(std::string const& parameter)
{
std::string angle_str;
std::string range;
size_t colon = parameter.find(':');
int relative = 0;
if (colon != std::string::npos) {
if (colon > 0) {
angle_str = parameter.substr(0, colon);
}
if (colon + 1 < parameter.length()) {
range = parameter.substr(colon + 1);
}
} else {
angle_str = parameter;
}
if (angle_str.length() > 0) {
char first = angle_str.at(0);
if ((first == '+') || (first == '-')) {
relative = ((first == '+') ? 1 : -1);
angle_str = angle_str.substr(1);
} else if (!QUtil::is_digit(angle_str.at(0))) {
angle_str = "";
}
}
if (range.empty()) {
range = "1-z";
}
bool range_valid = false;
try {
QUtil::parse_numrange(range.c_str(), 0);
range_valid = true;
} catch (std::runtime_error const&) {
// ignore
}
if (range_valid &&
((angle_str == "0") || (angle_str == "90") || (angle_str == "180") ||
(angle_str == "270"))) {
int angle = QUtil::string_to_int(angle_str.c_str());
if (relative == -1) {
angle = -angle;
}
m->rotations[range] = RotationSpec(angle, (relative != 0));
} else {
usage("invalid parameter to rotate: " + parameter);
}
}
std::vector<int>
QPDFJob::parseNumrange(char const* range, int max)
{
try {
return QUtil::parse_numrange(range, max);
} catch (std::runtime_error& e) {
usage(e.what());
}
return std::vector<int>();
}
void
QPDFJob::run()
{
checkConfiguration();
std::shared_ptr<QPDF> pdf_ph;
try {
pdf_ph =
processFile(m->infilename.get(), m->password.get(), true, true);
} catch (QPDFExc& e) {
if ((e.getErrorCode() == qpdf_e_password) &&
(m->check_is_encrypted || m->check_requires_password)) {
// Allow --is-encrypted and --requires-password to
// work when an incorrect password is supplied.
this->m->encryption_status =
qpdf_es_encrypted | qpdf_es_password_incorrect;
return;
}
throw e;
}
QPDF& pdf = *pdf_ph;
if (pdf.isEncrypted()) {
this->m->encryption_status = qpdf_es_encrypted;
}
if (m->check_is_encrypted || m->check_requires_password) {
return;
}
// If we are updating from JSON, this has to be done first before
// other options may cause transformations to the input.
if (!this->m->update_from_json.empty()) {
pdf.updateFromJSON(this->m->update_from_json);
}
bool other_warnings = false;
std::vector<std::shared_ptr<QPDF>> page_heap;
if (!m->page_specs.empty()) {
handlePageSpecs(pdf, other_warnings, page_heap);
}
if (!m->rotations.empty()) {
handleRotations(pdf);
}
handleUnderOverlay(pdf);
handleTransformations(pdf);
if (!createsOutput()) {
doInspection(pdf);
} else if (m->split_pages) {
doSplitPages(pdf, other_warnings);
} else {
writeOutfile(pdf);
}
if (!pdf.getWarnings().empty()) {
this->m->warnings = true;
}
if (this->m->warnings && (!this->m->suppress_warnings)) {
if (createsOutput()) {
*this->m->log->getWarn()
<< this->m->message_prefix
<< ": operation succeeded with warnings;"
<< " resulting file may have some problems\n";
} else {
*this->m->log->getWarn() << this->m->message_prefix
<< ": operation succeeded with warnings\n";
}
}
}
bool
QPDFJob::hasWarnings() const
{
return this->m->warnings;
}
bool
QPDFJob::createsOutput() const
{
return ((m->outfilename != nullptr) || m->replace_input);
}
int
QPDFJob::getExitCode() const
{
if (this->m->check_is_encrypted) {
if (this->m->encryption_status & qpdf_es_encrypted) {
QTC::TC("qpdf", "QPDFJob check encrypted encrypted");
return 0;
} else {
QTC::TC("qpdf", "QPDFJob check encrypted not encrypted");
return EXIT_IS_NOT_ENCRYPTED;
}
} else if (this->m->check_requires_password) {
if (this->m->encryption_status & qpdf_es_encrypted) {
if (this->m->encryption_status & qpdf_es_password_incorrect) {
QTC::TC("qpdf", "QPDFJob check password password incorrect");
return 0;
} else {
QTC::TC("qpdf", "QPDFJob check password password correct");
return EXIT_CORRECT_PASSWORD;
}
} else {
QTC::TC("qpdf", "QPDFJob check password not encrypted");
return EXIT_IS_NOT_ENCRYPTED;
}
}
if (this->m->warnings && (!this->m->warnings_exit_zero)) {
return EXIT_WARNING;
}
return 0;
}
void
QPDFJob::checkConfiguration()
{
if (m->replace_input) {
if (m->outfilename) {
usage("--replace-input may not be used when"
" an output file is specified");
} else if (m->split_pages) {
usage("--split-pages may not be used with --replace-input");
}
}
if (m->infilename == 0) {
usage("an input file name is required");
} else if (
m->require_outfile && (m->outfilename == 0) && (!m->replace_input)) {
usage("an output file name is required; use - for standard output");
} else if (
(!m->require_outfile) && ((m->outfilename != 0) || m->replace_input)) {
usage("no output file may be given for this option");
}
if (m->check_requires_password && m->check_is_encrypted) {
usage("--requires-password and --is-encrypted may not be given"
" together");
}
if (m->encrypt && (!m->allow_insecure) &&
(m->owner_password.empty() && (!m->user_password.empty()) &&
(m->keylen == 256))) {
// Note that empty owner passwords for R < 5 are copied from
// the user password, so this lack of security is not an issue
// for those files. Also we are consider only the ability to
// open the file without a password to be insecure. We are not
// concerned about whether the viewer enforces security
// settings when the user and owner password match.
usage("A PDF with a non-empty user password and an empty owner"
" password encrypted with a 256-bit key is insecure as it"
" can be opened without a password. If you really want to"
" do this, you must also give the --allow-insecure option"
" before the -- that follows --encrypt.");
}
bool save_to_stdout = false;
if (m->require_outfile && m->outfilename &&
(strcmp(m->outfilename.get(), "-") == 0)) {
if (m->split_pages) {
usage("--split-pages may not be used when"
" writing to standard output");
}
save_to_stdout = true;
}
if (!m->attachment_to_show.empty()) {
save_to_stdout = true;
}
if (save_to_stdout) {
this->m->log->saveToStandardOutput(true);
}
if ((!m->split_pages) &&
QUtil::same_file(m->infilename.get(), m->outfilename.get())) {
QTC::TC("qpdf", "QPDFJob same file error");
usage("input file and output file are the same;"
" use --replace-input to intentionally"
" overwrite the input file");
}
if (m->json_keys.count("objectinfo")) {
usage("json key \"objectinfo\" is only valid for json version 1");
}
}
unsigned long
QPDFJob::getEncryptionStatus()
{
return this->m->encryption_status;
}
void
QPDFJob::setQPDFOptions(QPDF& pdf)
{
pdf.setLogger(this->m->log);
if (m->ignore_xref_streams) {
pdf.setIgnoreXRefStreams(true);
}
if (m->suppress_recovery) {
pdf.setAttemptRecovery(false);
}
if (m->password_is_hex_key) {
pdf.setPasswordIsHexKey(true);
}
if (m->suppress_warnings) {
pdf.setSuppressWarnings(true);
}
}
static std::string
show_bool(bool v)
{
return v ? "allowed" : "not allowed";
}
static std::string
show_encryption_method(QPDF::encryption_method_e method)
{
std::string result = "unknown";
switch (method) {
case QPDF::e_none:
result = "none";
break;
case QPDF::e_unknown:
result = "unknown";
break;
case QPDF::e_rc4:
result = "RC4";
break;
case QPDF::e_aes:
result = "AESv2";
break;
case QPDF::e_aesv3:
result = "AESv3";
break;
// no default so gcc will warn for missing case
}
return result;
}
void
QPDFJob::showEncryption(QPDF& pdf)
{
// Extract /P from /Encrypt
int R = 0;
int P = 0;
int V = 0;
QPDF::encryption_method_e stream_method = QPDF::e_unknown;
QPDF::encryption_method_e string_method = QPDF::e_unknown;
QPDF::encryption_method_e file_method = QPDF::e_unknown;
auto& cout = *this->m->log->getInfo();
if (!pdf.isEncrypted(R, P, V, stream_method, string_method, file_method)) {
cout << "File is not encrypted\n";
} else {
cout << "R = " << R << "\n";
cout << "P = " << P << "\n";
std::string user_password = pdf.getTrimmedUserPassword();
std::string encryption_key = pdf.getEncryptionKey();
cout << "User password = " << user_password << "\n";
if (m->show_encryption_key) {
cout << "Encryption key = " << QUtil::hex_encode(encryption_key)
<< "\n";
}
if (pdf.ownerPasswordMatched()) {
cout << "Supplied password is owner password\n";
}
if (pdf.userPasswordMatched()) {
cout << "Supplied password is user password\n";
}
cout << "extract for accessibility: "
<< show_bool(pdf.allowAccessibility()) << "\n"
<< "extract for any purpose: " << show_bool(pdf.allowExtractAll())
<< "\n"
<< "print low resolution: " << show_bool(pdf.allowPrintLowRes())
<< "\n"
<< "print high resolution: " << show_bool(pdf.allowPrintHighRes())
<< "\n"
<< "modify document assembly: "
<< show_bool(pdf.allowModifyAssembly()) << "\n"
<< "modify forms: " << show_bool(pdf.allowModifyForm()) << "\n"
<< "modify annotations: " << show_bool(pdf.allowModifyAnnotation())
<< "\n"
<< "modify other: " << show_bool(pdf.allowModifyOther()) << "\n"
<< "modify anything: " << show_bool(pdf.allowModifyAll()) << "\n";
if (V >= 4) {
cout << "stream encryption method: "
<< show_encryption_method(stream_method) << "\n"
<< "string encryption method: "
<< show_encryption_method(string_method) << "\n"
<< "file encryption method: "
<< show_encryption_method(file_method) << "\n";
}
}
}
void
QPDFJob::doCheck(QPDF& pdf)
{
// Code below may set okay to false but not to true.
// We assume okay until we prove otherwise but may
// continue to perform additional checks after finding
// errors.
bool okay = true;
bool warnings = false;
auto& cout = *this->m->log->getInfo();
cout << "checking " << m->infilename.get() << "\n";
try {
int extension_level = pdf.getExtensionLevel();
cout << "PDF Version: " << pdf.getPDFVersion();
if (extension_level > 0) {
cout << " extension level " << pdf.getExtensionLevel();
}
cout << "\n";
showEncryption(pdf);
if (pdf.isLinearized()) {
cout << "File is linearized\n";
// any errors or warnings are reported by
// checkLinearization(). We treat all issues reported here
// as warnings.
if (!pdf.checkLinearization()) {
warnings = true;
}
} else {
cout << "File is not linearized\n";
}
// Write the file to nowhere, uncompressing
// streams. This causes full file traversal and
// decoding of all streams we can decode.
QPDFWriter w(pdf);
Pl_Discard discard;
w.setOutputPipeline(&discard);
w.setDecodeLevel(qpdf_dl_all);
w.write();
// Parse all content streams
DiscardContents discard_contents;
int pageno = 0;
for (auto& page: QPDFPageDocumentHelper(pdf).getAllPages()) {
++pageno;
try {
page.parseContents(&discard_contents);
} catch (QPDFExc& e) {
okay = false;
*this->m->log->getError()
<< "ERROR: page " << pageno << ": " << e.what() << "\n";
}
}
} catch (std::exception& e) {
*this->m->log->getError() << "ERROR: " << e.what() << "\n";
okay = false;
}
if (!okay) {
throw std::runtime_error("errors detected");
}
if ((!pdf.getWarnings().empty()) || warnings) {
this->m->warnings = true;
} else {
*this->m->log->getInfo() << "No syntax or stream encoding errors"
<< " found; the file may still contain\n"
<< "errors that qpdf cannot detect\n";
}
}
void
QPDFJob::doShowObj(QPDF& pdf)
{
QPDFObjectHandle obj;
if (m->show_trailer) {
obj = pdf.getTrailer();
} else {
obj = pdf.getObjectByID(m->show_obj, m->show_gen);
}
bool error = false;
if (obj.isStream()) {
if (m->show_raw_stream_data || m->show_filtered_stream_data) {
bool filter = m->show_filtered_stream_data;
if (filter && (!obj.pipeStreamData(0, 0, qpdf_dl_all))) {
QTC::TC("qpdf", "QPDFJob unable to filter");
obj.warnIfPossible("unable to filter stream data");
error = true;
} else {
// If anything has been written to standard output,
// this will fail.
this->m->log->saveToStandardOutput(true);
obj.pipeStreamData(
this->m->log->getSave().get(),
(filter && m->normalize) ? qpdf_ef_normalize : 0,
filter ? qpdf_dl_all : qpdf_dl_none);
}
} else {
*this->m->log->getInfo() << "Object is stream. Dictionary:\n"
<< obj.getDict().unparseResolved() << "\n";
}
} else {
*this->m->log->getInfo() << obj.unparseResolved() << "\n";
}
if (error) {
throw std::runtime_error(
"unable to get object " + obj.getObjGen().unparse());
}
}
void
QPDFJob::doShowPages(QPDF& pdf)
{
int pageno = 0;
auto& cout = *this->m->log->getInfo();
for (auto& ph: QPDFPageDocumentHelper(pdf).getAllPages()) {
QPDFObjectHandle page = ph.getObjectHandle();
++pageno;
cout << "page " << pageno << ": " << page.getObjectID() << " "
<< page.getGeneration() << " R\n";
if (m->show_page_images) {
std::map<std::string, QPDFObjectHandle> images = ph.getImages();
if (!images.empty()) {
cout << " images:\n";
for (auto const& iter2: images) {
std::string const& name = iter2.first;
QPDFObjectHandle image = iter2.second;
QPDFObjectHandle dict = image.getDict();
int width = dict.getKey("/Width").getIntValueAsInt();
int height = dict.getKey("/Height").getIntValueAsInt();
cout << " " << name << ": " << image.unparse() << ", "
<< width << " x " << height << "\n";
}
}
}
cout << " content:\n";
for (auto& iter2: ph.getPageContents()) {
cout << " " << iter2.unparse() << "\n";
}
}
}
void
QPDFJob::doListAttachments(QPDF& pdf)
{
QPDFEmbeddedFileDocumentHelper efdh(pdf);
if (efdh.hasEmbeddedFiles()) {
for (auto const& i: efdh.getEmbeddedFiles()) {
std::string const& key = i.first;
auto efoh = i.second;
*this->m->log->getInfo()
<< key << " -> "
<< efoh->getEmbeddedFileStream().getObjGen().unparse() << "\n";
doIfVerbose([&](Pipeline& v, std::string const& prefix) {
auto desc = efoh->getDescription();