Repository navigation
Expand file tree
/
Copy pathread.go
More file actions
1605 lines (1433 loc) · 44.6 KB
/
Copy pathread.go
File metadata and controls
1605 lines (1433 loc) · 44.6 KB
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
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package pdf
import (
"bytes"
"compress/zlib"
"crypto/aes"
"crypto/cipher"
"crypto/md5"
"crypto/rand"
"crypto/rc4"
"crypto/sha256"
"crypto/sha512"
"encoding/ascii85"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"slices"
"sort"
"strconv"
)
// A Reader is a single PDF file open for reading.
type Reader struct {
f io.ReaderAt
end int64
xref []xref
trailer Object // was dict
trailerptr objptr
key []byte
useAES bool
encVersion int // encryption version (V), 0 if not encrypted
encKey []byte // File Encryption Key (FEK) - for V=5 calls this is the final key
plainMetadata bool // the document metadata stream is not encrypted (/EncryptMetadata false)
cryptFilters map[string]string // the method of each crypt filter of /CF, by name
XrefInformation ReaderXrefInformation
PDFVersion string
closer io.Closer
// objCache caches resolved objects to prevent repetitive disk I/O.
// Map key is the object ID.
objCache map[uint32]Value
// objStms holds the object streams being searched, to detect cycles.
objStms []objptr
// Failures that depend on the object streams being searched must not be
// cached.
objStmLoops int
objStmFailed bool
}
// maxObjStmDepth bounds the object streams searched at once, since a key of one,
// such as /Length, may be in another. A long chain would overflow the stack.
const maxObjStmDepth = 32
type ReaderXrefInformation struct {
StartPos int64
EndPos int64
Length int64
PositionLength int64
PositionStartPos int64
PositionEndPos int64
ItemCount int64
Type string
IncludingTrailerEndPos int64
IncludingTrailerLength int64
}
func (info *ReaderXrefInformation) PrintDebug() {
log.Printf("Start of xref position bytes: %d", info.PositionStartPos)
log.Printf("Length of xref position bytes: %d", info.PositionLength)
log.Printf("End of xref position bytes: %d", info.PositionEndPos)
log.Printf("xref start position byte: %d", info.StartPos)
log.Printf("xref end position byte: %d", info.EndPos)
log.Printf("xref length in bytes: %d", info.Length)
log.Printf("xref type: %s", info.Type)
log.Printf("Amount of items in xref: %d", info.ItemCount)
log.Printf("xref end (including trailer) position byte: %d", info.IncludingTrailerEndPos)
log.Printf("xref length (including trailer) in bytes: %d", info.IncludingTrailerLength)
}
type xref struct {
ptr objptr
inStream bool
stream objptr
offset int64
}
func (x *xref) Ptr() Ptr {
return Ptr{id: x.ptr.id, gen: x.ptr.gen}
}
func (x *xref) Stream() objptr {
return x.stream
}
func GetDict() Object {
return Object{Kind: Dict, DictVal: make(map[string]Object)}
}
func (r *Reader) errorf(format string, args ...interface{}) {
panic(fmt.Errorf(format, args...))
}
func (r *Reader) Xref() []xref {
return r.xref
}
// GetObject reads and returns the object with the given ID.
// It resolves the object from the XRef table, using the cache if available.
func (r *Reader) GetObject(id uint32) (Value, error) {
if int(id) >= len(r.xref) {
return Value{}, fmt.Errorf("object ID %d out of range", id)
}
x := r.xref[id]
if x.offset == 0 && !x.inStream {
// Possibly free or invalid
return Value{}, fmt.Errorf("object ID %d is not in use", id)
}
ptr := x.ptr
if ptr.id != id {
ptr.id = id
}
return r.resolve(objptr{}, Object{Kind: Indirect, PtrVal: ptr}), nil
}
// Open opens a file for reading.
func Open(file string) (*Reader, error) {
// TODO: Deal with closing file.
f, err := os.Open(file)
if err != nil {
return nil, err
}
fi, err := f.Stat()
if err != nil {
f.Close()
return nil, err
}
return NewReader(f, fi.Size())
}
// NewReader opens a file for reading, using the data in f with the given total size.
func NewReader(f io.ReaderAt, size int64) (*Reader, error) {
return NewReaderEncrypted(f, size, nil)
}
// NewReaderEncrypted opens a file for reading, using the data in f with the given total size.
// If the PDF is encrypted, NewReaderEncrypted calls pw repeatedly to obtain passwords
// to try. If pw returns the empty string, NewReaderEncrypted stops trying to decrypt
// the file and returns an error.
func NewReaderEncrypted(f io.ReaderAt, size int64, pw func() string) (r *Reader, err error) {
defer func() {
if e := recover(); e != nil {
r = nil
if err, _ = e.(error); err == nil {
err = fmt.Errorf("malformed PDF: %v", e)
}
}
}()
return newReaderEncrypted(f, size, pw)
}
func newReaderEncrypted(f io.ReaderAt, size int64, pw func() string) (*Reader, error) {
buf := make([]byte, 10)
f.ReadAt(buf, 0)
if (!bytes.HasPrefix(buf, []byte("%PDF-1.")) || buf[7] < '0' || buf[7] > '7') && (!bytes.HasPrefix(buf, []byte("%PDF-2.")) || buf[7] < '0' || buf[7] > '0') {
return nil, fmt.Errorf("not a PDF file: invalid header")
}
version := buf[5:8]
end := size
// Some PDF's are quite broken and have a lot of stuff after %%EOF.
eof := findEOF(f, end)
if eof < 0 {
return nil, fmt.Errorf("not a PDF file: missing %%%%EOF")
}
start := max(eof-200, 0)
buf = make([]byte, eof-start)
f.ReadAt(buf, start)
i := findLastLine(buf, "startxref")
if i < 0 {
return nil, fmt.Errorf("malformed PDF file: missing final startxref")
}
r := &Reader{
f: f,
end: end,
XrefInformation: ReaderXrefInformation{},
PDFVersion: string(version),
objCache: make(map[uint32]Value),
}
if c, ok := f.(io.Closer); ok {
r.closer = c
}
pos := start + int64(i)
// Save the position of the startxref element.
r.XrefInformation.PositionStartPos = pos
b := newBuffer(io.NewSectionReader(f, pos, end-pos), pos, r.encVersion)
tok := b.readToken()
if tok.Kind != Keyword || tok.KeywordVal != "startxref" {
return nil, fmt.Errorf("malformed PDF file: missing startxref")
}
startXRefObj := b.readToken()
if startXRefObj.Kind != Integer {
return nil, fmt.Errorf("malformed PDF file: startxref not followed by integer")
}
startxref := startXRefObj.Int64Val
// Save length. Useful for calculations later on.
r.XrefInformation.PositionLength = b.realPos + 1
// Save end position. Add 1 for the newline character.
r.XrefInformation.PositionEndPos = r.XrefInformation.PositionStartPos + r.XrefInformation.PositionLength
// Save start position of xref.
r.XrefInformation.StartPos = startxref
b = newBuffer(io.NewSectionReader(r.f, startxref, r.end-startxref), startxref, r.encVersion)
xref, trailerptr, trailer, err := readXref(r, b)
if err != nil {
return nil, err
}
r.xref = xref
r.trailer = trailer
r.trailerptr = trailerptr
if trailer.Kind == Dict && trailer.DictVal["Encrypt"].Kind == Null {
return r, nil
}
// Check if Encrypt is present properly
enc := trailer.DictVal["Encrypt"]
if enc.Kind == Null {
return r, nil
}
err = r.initEncrypt("")
if err == nil {
return r, nil
}
if pw == nil || err != ErrInvalidPassword {
return nil, err
}
for {
next := pw()
if next == "" {
break
}
if r.initEncrypt(next) == nil {
return r, nil
}
}
return nil, err
}
// Trailer returns the file's Trailer value.
func (r *Reader) Trailer() Value {
return Value{r: r, ptr: r.trailerptr, obj: r.trailer}
}
func readXref(r *Reader, b *buffer) ([]xref, objptr, Object, error) {
tok := b.readToken()
if tok.Kind == Keyword && tok.KeywordVal == "xref" {
return readXrefTable(r, b)
}
if tok.Kind == Integer {
b.unreadToken(tok)
return readXrefStream(r, b)
}
return nil, objptr{}, Object{Kind: Null}, fmt.Errorf("malformed PDF: cross-reference table not found: %v", tok)
}
func readXrefStream(r *Reader, b *buffer) ([]xref, objptr, Object, error) {
obj1 := b.readObject()
// readObject returns the object. If it was an indirect definition, it has PtrVal set.
strmptr := obj1.PtrVal
if obj1.Kind != Stream {
return nil, objptr{}, Object{Kind: Null}, fmt.Errorf("malformed PDF: cross-reference table not found: %v", objfmt(obj1))
}
strm := obj1
if strm.DictVal["Type"].NameVal != "XRef" {
return nil, objptr{}, Object{Kind: Null}, fmt.Errorf("malformed PDF: xref stream does not have type XRef")
}
sizeObj := strm.DictVal["Size"]
if sizeObj.Kind != Integer {
return nil, objptr{}, Object{Kind: Null}, fmt.Errorf("malformed PDF: xref stream missing Size")
}
size := sizeObj.Int64Val
if size < 0 {
return nil, objptr{}, Object{Kind: Null}, fmt.Errorf("malformed PDF: negative xref stream Size")
}
// The table grows as the entries are read, so /Size only gives the initial
// capacity: a file that declares a huge one must not make the table that
// large before a single entry is read.
table := make([]xref, 0, min(size, 4096))
table, err := readXrefStreamData(r, strm, table, size)
if err != nil {
return nil, objptr{}, Object{Kind: Null}, fmt.Errorf("malformed PDF: %v", err)
}
seenPrev := map[int64]bool{}
prevoff := strm.DictVal["Prev"]
for prevoff.Kind != Null {
off := prevoff.Int64Val
if prevoff.Kind != Integer {
return nil, objptr{}, Object{Kind: Null}, fmt.Errorf("malformed PDF: xref Prev is not integer: %v", prevoff)
}
if _, ok := seenPrev[off]; ok {
return nil, objptr{}, Object{Kind: Null}, fmt.Errorf("malformed PDF: xref Prev loop detected: %v", off)
}
seenPrev[off] = true
b := newBuffer(io.NewSectionReader(r.f, off, r.end-off), off, r.encVersion)
obj1 := b.readObject()
if obj1.Kind != Stream {
return nil, objptr{}, Object{Kind: Null}, fmt.Errorf("malformed PDF: xref prev stream not found: %v", objfmt(obj1))
}
prevstrm := obj1
prevoff = prevstrm.DictVal["Prev"]
prev := Value{r: r, obj: prevstrm}
if prev.Kind() != Stream {
return nil, objptr{}, Object{Kind: Null}, fmt.Errorf("malformed PDF: xref prev stream is not stream: %v", prev)
}
if prev.Key("Type").Name() != "XRef" {
return nil, objptr{}, Object{Kind: Null}, fmt.Errorf("malformed PDF: xref prev stream does not have type XRef")
}
psize := prev.Key("Size").Int64()
if psize > size {
return nil, objptr{}, Object{Kind: Null}, fmt.Errorf("malformed PDF: xref prev stream larger than last stream")
}
if table, err = readXrefStreamData(r, prev.obj, table, psize); err != nil {
return nil, objptr{}, Object{Kind: Null}, fmt.Errorf("malformed PDF: reading xref prev stream: %v", err)
}
}
// Save the xref type. Useful for adding data to it.
r.XrefInformation.Type = "stream"
// Writers take the /Size of the next section from ItemCount, and it must not
// be smaller than this one, even if the table lists fewer objects.
r.XrefInformation.ItemCount = max(size, int64(len(table)))
return table, strmptr, strm, nil
}
func readXrefStreamData(r *Reader, strm Object, table []xref, size int64) ([]xref, error) {
index := strm.DictVal["Index"]
if index.Kind == Null {
index = Object{Kind: Array, ArrayVal: []Object{{Kind: Integer, Int64Val: 0}, {Kind: Integer, Int64Val: size}}}
}
if len(index.ArrayVal)%2 != 0 {
return nil, fmt.Errorf("invalid Index array %v", objfmt(index))
}
ww := strm.DictVal["W"]
if ww.Kind != Array {
return nil, fmt.Errorf("xref stream missing W array")
}
// A field is at most 8 bytes wide, like in qpdf, and an entry takes at least
// one byte: an entry of no bytes would let a short /Index list any number.
var w []int
wtotal := 0
for _, x := range ww.ArrayVal {
i := x.Int64Val
if x.Kind != Integer || i < 0 || i > 8 {
return nil, fmt.Errorf("invalid W array %v", objfmt(ww))
}
w = append(w, int(i))
wtotal += int(i)
}
if len(w) < 3 || wtotal == 0 {
return nil, fmt.Errorf("invalid W array %v", objfmt(ww))
}
v := Value{r: r, obj: strm}
buf := make([]byte, wtotal)
data := v.Reader()
entries := int64(0)
idxArr := index.ArrayVal
for len(idxArr) > 0 {
start := idxArr[0].Int64Val
n := idxArr[1].Int64Val
if idxArr[0].Kind != Integer || idxArr[1].Kind != Integer {
return nil, fmt.Errorf("malformed Index pair %v %v", objfmt(idxArr[0]), objfmt(idxArr[1]))
}
if n > maxObjects+1-entries {
return nil, fmt.Errorf("xref stream lists more than %d objects", maxObjects+1)
}
entries += max(n, 0)
idxArr = idxArr[2:]
for i := 0; i < int(n); i++ {
_, err := io.ReadFull(data, buf)
if err != nil {
return nil, fmt.Errorf("error reading xref stream: %v", err)
}
v1 := decodeInt(buf[0:w[0]])
if w[0] == 0 {
v1 = 1
}
v2 := decodeInt(buf[w[0] : w[0]+w[1]])
v3 := decodeInt(buf[w[0]+w[1] : w[0]+w[1]+w[2]])
x, err := xrefIndex(start + int64(i))
if err != nil {
return nil, err
}
if x >= len(table) {
table = append(table, make([]xref, x+1-len(table))...)
}
if table[x].ptr != (objptr{}) {
continue
}
switch v1 {
case 0:
table[x] = xref{ptr: objptr{0, 65535}}
case 1:
table[x] = xref{ptr: objptr{uint32(x), uint16(v3)}, offset: int64(v2)}
case 2:
table[x] = xref{ptr: objptr{uint32(x), 0}, inStream: true, stream: objptr{uint32(v2), 0}, offset: int64(v3)}
default:
fmt.Printf("invalid xref stream type %d: %x\n", v1, buf)
}
}
}
return table, nil
}
func decodeInt(b []byte) int {
x := 0
for _, c := range b {
x = x<<8 | int(c)
}
return x
}
func readXrefTable(r *Reader, b *buffer) ([]xref, objptr, Object, error) {
var table []xref
table, err := readXrefTableData(b, table)
if err != nil {
return nil, objptr{}, Object{Kind: Null}, fmt.Errorf("malformed PDF: %v", err)
}
// Get length of trailer keyword and newline.
trailer_length := int64(len("trailer")) + 1
// Save end position.
r.XrefInformation.EndPos = (r.XrefInformation.StartPos - trailer_length) + b.realPos
// Save length position. Useful for calculations. Remove trailer keyword length, add 1 for newline.
r.XrefInformation.Length = (b.realPos - trailer_length) + 1
trailer := b.readObject()
if trailer.Kind != Dict {
return nil, objptr{}, Object{Kind: Null}, fmt.Errorf("malformed PDF: xref table not followed by trailer dictionary")
}
seenPrev := map[int64]bool{}
prevoff := trailer.DictVal["Prev"]
for prevoff.Kind != Null {
off := prevoff.Int64Val
if prevoff.Kind != Integer {
return nil, objptr{}, Object{Kind: Null}, fmt.Errorf("malformed PDF: xref Prev is not integer: %v", prevoff)
}
if _, ok := seenPrev[off]; ok {
return nil, objptr{}, Object{Kind: Null}, fmt.Errorf("malformed PDF: xref Prev loop detected: %v", off)
}
seenPrev[off] = true
b := newBuffer(io.NewSectionReader(r.f, off, r.end-off), off, r.encVersion)
tok := b.readToken()
if tok.Kind != Keyword || tok.KeywordVal != "xref" {
return nil, objptr{}, Object{Kind: Null}, fmt.Errorf("malformed PDF: xref Prev does not point to xref")
}
table, err = readXrefTableData(b, table)
if err != nil {
return nil, objptr{}, Object{Kind: Null}, fmt.Errorf("malformed PDF: %v", err)
}
t := b.readObject()
if t.Kind != Dict {
return nil, objptr{}, Object{Kind: Null}, fmt.Errorf("malformed PDF: xref Prev table not followed by trailer dictionary")
}
prevoff = t.DictVal["Prev"]
}
sizeObj := trailer.DictVal["Size"]
if sizeObj.Kind != Integer {
return nil, objptr{}, Object{Kind: Null}, fmt.Errorf("malformed PDF: trailer missing /Size entry")
}
size := sizeObj.Int64Val
if size < 0 {
return nil, objptr{}, Object{Kind: Null}, fmt.Errorf("malformed PDF: negative trailer Size")
}
if size < int64(len(table)) {
table = table[:size]
}
// Save the xref type. Useful for adding data to it.
r.XrefInformation.Type = "table"
// Save the amount of items in the table. Useful for generating a new id for the signature.
r.XrefInformation.ItemCount = int64(len(table))
// Save end position. Note that this is including the trailer and startxref (without value).
r.XrefInformation.IncludingTrailerEndPos = r.XrefInformation.StartPos + b.realPos
// Save length position. Useful for calculations.
r.XrefInformation.IncludingTrailerLength = b.realPos + 1
return table, objptr{}, trailer, nil
}
// maxObjects is the architectural limit on the number of indirect objects in a
// document (ISO 32000-1, Annex C.2), numbered 1 to maxObjects. It bounds the
// cross-reference table, which a file would otherwise size with a single entry,
// however few objects it holds.
const maxObjects = 8388607
// xrefIndex returns the object number x as an index into the cross-reference
// table.
func xrefIndex(x int64) (int, error) {
if x < 0 || x > maxObjects {
return 0, fmt.Errorf("object number %d over the limit of %d", x, maxObjects)
}
return int(x), nil
}
func readXrefTableData(b *buffer, table []xref) ([]xref, error) {
for {
tok := b.readToken()
if tok.Kind == Keyword && tok.KeywordVal == "trailer" {
break
}
if tok.Kind != Integer {
return nil, fmt.Errorf("malformed xref table: expected integer start")
}
start := tok.Int64Val
nObj := b.readToken()
if nObj.Kind != Integer {
return nil, fmt.Errorf("malformed xref table: expected integer count")
}
n := nObj.Int64Val
for i := 0; i < int(n); i++ {
offObj := b.readToken()
genObj := b.readToken()
allocObj := b.readToken()
if offObj.Kind != Integer || genObj.Kind != Integer || allocObj.Kind != Keyword {
return nil, fmt.Errorf("malformed xref table entry")
}
off := offObj.Int64Val
gen := genObj.Int64Val
alloc := allocObj.KeywordVal
if alloc != "f" && alloc != "n" {
return nil, fmt.Errorf("malformed xref table entry: invalid type %q", alloc)
}
x, err := xrefIndex(start + int64(i))
if err != nil {
return nil, err
}
if x >= len(table) {
table = append(table, make([]xref, x+1-len(table))...)
}
if alloc == "n" && table[x].offset == 0 {
table[x] = xref{ptr: objptr{uint32(x), uint16(gen)}, offset: int64(off)}
}
}
}
return table, nil
}
// findEOF returns the offset just after the last %%EOF in f, or -1.
func findEOF(f io.ReaderAt, end int64) int64 {
const chunk = 64 << 10
marker := []byte("%%EOF")
buf := make([]byte, chunk+len(marker)-1)
for hi := end; hi > 0; {
// The chunks overlap, for a marker across two of them.
lo := max(hi-chunk, 0)
n, _ := f.ReadAt(buf[:min(end, hi+int64(len(marker)-1))-lo], lo)
if i := bytes.LastIndex(buf[:n], marker); i >= 0 {
return lo + int64(i+len(marker))
}
hi = lo
}
return -1
}
func findLastLine(buf []byte, s string) int {
bs := []byte(s)
max := len(buf)
for {
i := bytes.LastIndex(buf[:max], bs)
if i <= 0 || i+len(bs) >= len(buf) {
return -1
}
if (buf[i-1] == '\n' || buf[i-1] == '\r') && (buf[i+len(bs)] == '\n' || buf[i+len(bs)] == '\r') {
return i
}
max = i
}
}
func objfmt(x Object) string {
switch x.Kind {
default:
return fmt.Sprintf("?Kind=%v?", x.Kind)
case Null:
return "null"
case Bool:
return strconv.FormatBool(x.BoolVal)
case Integer:
return strconv.FormatInt(x.Int64Val, 10)
case Real:
return strconv.FormatFloat(x.Float64Val, 'f', -1, 64)
case String:
return "(" + x.StringVal + ")"
case Name:
return "/" + x.NameVal
case Keyword:
return x.KeywordVal
case Indirect:
return fmt.Sprintf("%d %d R", x.PtrVal.id, x.PtrVal.gen)
case Dict:
var keys []string
for k := range x.DictVal {
keys = append(keys, k)
}
sort.Strings(keys)
var buf bytes.Buffer
buf.WriteString("<<")
for i, k := range keys {
elem := x.DictVal[k]
if i > 0 {
buf.WriteString(" ")
}
buf.WriteString("/")
buf.WriteString(k)
buf.WriteString(" ")
buf.WriteString(objfmt(elem))
}
buf.WriteString(">>")
return buf.String()
case Array:
var buf bytes.Buffer
buf.WriteString("[")
for i, elem := range x.ArrayVal {
if i > 0 {
buf.WriteString(" ")
}
buf.WriteString(objfmt(elem))
}
buf.WriteString("]")
return buf.String()
case Stream:
hdr := Object{Kind: Dict, DictVal: x.DictVal}
return fmt.Sprintf("%v@%d", objfmt(hdr), x.StreamOffset)
}
}
// objectInStream returns the object ptr from the object stream strm, and
// whether the stream holds it.
func (r *Reader) objectInStream(strm Value, ptr objptr) (Object, bool) {
if strm.Kind() != Stream {
panic("not a stream")
}
if strm.Key("Type").Name() != "ObjStm" {
panic("not an object stream")
}
n := int(strm.Key("N").Int64())
first := strm.Key("First").Int64()
if first == 0 {
panic("missing First")
}
b := newBuffer(strm.Reader(), 0, r.encVersion)
defer bufferPool.Put(b)
b.allowEOF = true
for i := 0; i < n && !b.eof; i++ {
id := b.readToken().Int64Val
off := b.readToken().Int64Val
if uint32(id) == ptr.id {
b.seekForward(first + off)
return b.readObject(), true
}
}
return Object{}, false
}
func (r *Reader) resolve(parent objptr, x Object) (v Value) {
orig, loops := x, 0
if r != nil {
loops = r.objStmLoops
}
defer func() {
if e := recover(); e != nil {
v = Value{err: fmt.Errorf("panic resolving %v: %v", objfmt(orig), e)}
// A chain of object streams would otherwise resolve a failing object
// once for each key of each stream.
if orig.Kind == Indirect && r != nil && r.objCache != nil && r.objStmLoops == loops {
r.objCache[orig.PtrVal.id] = v
}
}
}()
if x.Kind == Indirect {
ptr := x.PtrVal
// Check cache first
if v, ok := r.objCache[ptr.id]; ok {
return v
}
if ptr.id >= uint32(len(r.xref)) {
return Value{}
}
xref := r.xref[ptr.id]
if xref.ptr != ptr || !xref.inStream && xref.offset == 0 {
return Value{}
}
var obj Object
if xref.inStream {
if slices.Contains(r.objStms, xref.stream) || len(r.objStms) >= maxObjStmDepth || r.objStmFailed {
// Otherwise each stream would search the next ones again for
// each of its keys.
r.objStmLoops++
r.objStmFailed = len(r.objStms) > 0
panic("cyclic or too deeply nested object streams")
}
// An object stream is a stream, and a stream is never stored in an
// object stream (ISO 32000-1, 7.5.7).
if s := xref.stream.id; s < uint32(len(r.xref)) && r.xref[s].inStream {
panic("object stream in an object stream")
}
r.objStms = append(r.objStms, xref.stream)
defer func() {
r.objStms = r.objStms[:len(r.objStms)-1]
if len(r.objStms) == 0 {
r.objStmFailed = false
}
}()
strm := r.resolve(parent, Object{Kind: Indirect, PtrVal: xref.stream})
// The object stream is searched first, then the chain of the object
// streams it extends, each of them only once.
var extends []objptr
for {
var found bool
if x, found = r.objectInStream(strm, ptr); found {
break
}
ext := strm.Key("Extends")
next := ext.obj.PtrVal
if ext.Kind() != Stream || next == xref.stream || slices.Contains(extends, next) {
panic("cannot find object in stream")
}
extends = append(extends, next)
strm = ext
}
} else {
b := newBuffer(io.NewSectionReader(r.f, xref.offset, r.end-xref.offset), xref.offset, r.encVersion)
defer bufferPool.Put(b) // Return to pool
b.key = r.key
b.useAES = r.useAES
obj = b.readObject()
if b.key != nil && obj.Kind == Stream && obj.DictVal["Type"].NameVal == "XRef" {
// The strings of a cross-reference stream are not encrypted.
b = newBuffer(io.NewSectionReader(r.f, xref.offset, r.end-xref.offset), xref.offset, r.encVersion)
defer bufferPool.Put(b)
obj = b.readObject()
}
// readObject handles the "objdef" structure internally by returning the Object
// but storing the definition ID in PtrVal if it was an indirect definition.
// Let's verify it matches the pointer we expected.
// If obj matches criteria for definition:
// In readObject, we return the object with PtrVal set to the def ID.
// We check if PtrVal is set and check if it matches.
// However, if obj IS an Indirect reference, PtrVal will be the reference ID.
// But readObject for a definition returns the defined object (not Kind=Indirect).
if obj.Kind != Indirect && obj.PtrVal != (objptr{}) {
if obj.PtrVal.id != ptr.id || obj.PtrVal.gen != ptr.gen {
panic(fmt.Errorf("loading %v: found %v", ptr, obj.PtrVal))
}
} else if obj.Kind == Indirect && obj.PtrVal != ptr {
// It turned out to be a reference? A definition cannot act as a reference directly unless it's a stream?
panic(fmt.Errorf("loading %v: found reference %v", ptr, obj.PtrVal))
}
x = obj
}
parent = ptr
// Cache the resolved value
val := r.createValue(parent, x)
r.objCache[ptr.id] = val
return val
}
return r.createValue(parent, x)
}
// Close closes the Reader and the underlying file if it implements io.Closer.
func (r *Reader) Close() error {
if r.closer != nil {
return r.closer.Close()
}
return nil
}
func (r *Reader) createValue(ptr objptr, obj Object) Value {
return Value{r: r, ptr: ptr, obj: obj}
}
type errorReadCloser struct {
err error
}
func (e *errorReadCloser) Read([]byte) (int, error) {
return 0, e.err
}
func (e *errorReadCloser) Close() error {
return e.err
}
// newStreamReader returns a reader for the stream s.
func newStreamReader(s Object, r *Reader) io.ReadCloser {
var rd io.Reader
// s is Object(Stream). DictVal is header. StreamOffset is offset.
// Need "Length" from header.
// We can wrap s in Value to use Key method.
val := Value{r: r, obj: s}
length := val.Key("Length").Int64()
rd = io.NewSectionReader(r.f, s.StreamOffset, length)
if r.key != nil {
// We need the stream's object ID for decryption. Use s.PtrVal, which
// readObject sets to the definition ID.
encrypted, useAES, err := r.streamCipher(s)
if err != nil {
return &errorReadCloser{err}
}
if encrypted {
rd, err = decryptStream(r.key, useAES, r.encVersion, s.PtrVal, rd)
if err != nil {
return &errorReadCloser{err}
}
}
}
names, params := streamFilters(val)
for i, name := range names {
var err error
rd, err = applyFilter(rd, name, params(i))
if err != nil {
return &errorReadCloser{err}
}
}
return ioutil.NopCloser(rd)
}
// streamFilters returns the names of the filters of the stream s, and a function
// that returns the parameters of the i-th one. Like pdf.js, it accepts a single
// filter in an array, a single filter with its parameters in an array, and a
// single DecodeParms dictionary for all the filters.
func streamFilters(s Value) (names []string, params func(i int) Value) {
filter, decodeParms := s.Key("Filter"), s.Key("DecodeParms")
switch filter.Kind() {
case Name:
names = []string{filter.Name()}
case Array:
for i := 0; i < filter.Len(); i++ {
names = append(names, filter.Index(i).Name())
}
}
params = func(i int) Value {
if decodeParms.Kind() == Array {
return decodeParms.Index(i)
}
return decodeParms
}
return names, params
}
// streamCipher reports whether the stream s is encrypted, and whether its crypt
// filter uses AES. A cross-reference stream, the metadata stream of the catalog
// when /EncryptMetadata is false, and a stream whose Crypt filter is Identity or
// does not encrypt are not encrypted. A stream that names another crypt filter
// of the document uses the method of that filter, not the one of /StmF.
func (r *Reader) streamCipher(s Object) (encrypted, useAES bool, err error) {
switch s.DictVal["Type"].NameVal {
case "XRef":
return false, false, nil
case "Metadata":
if r.plainMetadata && s.PtrVal == r.resolve(objptr{}, r.trailer.DictVal["Root"]).obj.DictVal["Metadata"].PtrVal {
return false, false, nil
}
}
// A Crypt filter comes first.
names, params := streamFilters(Value{r: r, obj: s})
if len(names) == 0 || names[0] != "Crypt" {
return true, r.useAES, nil
}
name := params(0).Key("Name").Name()
if name == "" || name == "Identity" {
return false, false, nil
}
switch method := r.cryptFilters[name]; method {
case "Identity", "None":
return false, false, nil
case "V2":
return true, false, nil
case "AESV2", "AESV3":
return true, true, nil
case "":
return false, false, fmt.Errorf("undefined crypt filter %s", name)
default:
return false, false, fmt.Errorf("unsupported PDF: crypt filter method %s", method)
}
}
// maxColumns bounds the /Columns of a predictor, whose rows are buffered.
const maxColumns = 1 << 24
func applyFilter(rd io.Reader, name string, param Value) (io.Reader, error) {
switch name {
default:
return nil, fmt.Errorf("unknown filter %s", name)
case "Crypt":
// newStreamReader decrypts the stream.
return rd, nil
case "ASCIIHexDecode":
return asciiHexReader{rd}, nil
case "ASCII85Decode":
return ascii85.NewDecoder(rd), nil
case "FlateDecode":
zr, err := zlib.NewReader(rd)
if err != nil {
return nil, err
}
pred := param.Key("Predictor")
if pred.Kind() == Null {
return zr, nil
}
columns := param.Key("Columns").Int64()
if columns < 0 || columns > maxColumns {
return nil, fmt.Errorf("invalid predictor Columns %d", columns)
}
switch pred.Int64() {
default:
return nil, fmt.Errorf("unknown predictor %v", pred)
case 12:
return &pngUpReader{r: zr, hist: make([]byte, 1+columns), tmp: make([]byte, 1+columns)}, nil
}
}
}
type asciiHexReader struct {
r io.Reader
}
func (r asciiHexReader) Read(dst []byte) (int, error) {
if len(dst) == 0 {
return 0, nil
}
var src [2]byte
n := 0
for n < len(dst) {
_, err := io.ReadFull(r.r, src[:1])