/
parser.go
1570 lines (1358 loc) · 41 KB
/
parser.go
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
package core
import (
"../common"
"bufio"
"bytes"
"encoding/hex"
"errors"
"io"
"regexp"
"strconv"
"strings"
)
var rePdfVersion = regexp.MustCompile(`%PDF-(\d)\.(\d)`)
var reStartXref = regexp.MustCompile(`startx?ref\s*(\d+)`)
var reXrefSubsection = regexp.MustCompile(`(\d+)\s+(\d+)$`)
var reXrefEntry = regexp.MustCompile(`(\d+)\s+(\d+)\s+([nf])$`)
var reReference = regexp.MustCompile(`^\s*(\d+)\s+(\d+)\s+R`)
var reNumeric = regexp.MustCompile(`^[\+-.]*([0-9.]+)`)
var reExponential = regexp.MustCompile(`^[\+-.]*([0-9.]+)e[\+-.]*([0-9.]+)`)
var reIndirectObject = regexp.MustCompile(`(\d+)\s+(\d+)\s+obj`)
type PdfParser struct {
majorVersion int
minorVersion int
rs io.ReadSeeker
reader *bufio.Reader
//store referenceData
xrefs XrefTable
//trailer dict
trailerDict *PdfObjectDictionary
getRoot bool
getInfo bool
//root dict
rootDict *PdfObjectDictionary
//info dict
infoDict *PdfObjectDictionary
crypter *PdfCrypt
// Tracker for reference lookups when looking up Length entry of stream objects.
// The Length entries of stream objects are a special case, as they can require recursive parsing, i.e. look up
// the length reference (if not object) prior to reading the actual stream. This has risks of endless looping.
// Tracking is necessary to avoid recursive loops.
streamLengthReferenceLookupInProgress map[int64]bool
ObjCache ObjectCache // TODO: Unexport (v3).
objstms ObjectStreams
}
// Skip over comments and spaces. Can handle multi-line comments.
func (parser *PdfParser) skipComments() error {
if _, err := parser.skipSpaces(); err != nil {
return err
}
isFirst := true
for {
bb, err := parser.reader.Peek(1)
if err != nil {
common.Log.Debug("Error %s", err.Error())
return err
}
if isFirst && bb[0] != '%' {
// Not a comment clearly.
return nil
} else {
isFirst = false
}
if (bb[0] != '\r') && (bb[0] != '\n') {
parser.reader.ReadByte()
} else {
break
}
}
// Call recursively to handle multiline comments.
return parser.skipComments()
}
// Skip over any spaces.
func (parser *PdfParser) skipSpaces() (int, error) {
cnt := 0
for {
b, err := parser.reader.ReadByte()
if err != nil {
return 0, err
}
if IsWhiteSpace(b) {
cnt++
} else {
parser.reader.UnreadByte()
break
}
}
return cnt, nil
}
// Return the closest object following offset from the xrefs table.
func (parser *PdfParser) xrefNextObjectOffset(offset int64) int64 {
nextOffset := int64(0)
for _, xref := range parser.xrefs {
if xref.offset > offset && (xref.offset < nextOffset || nextOffset == 0) {
nextOffset = xref.offset
}
}
return nextOffset
}
// Get stream length, avoiding recursive loops.
// The input is the PdfObject that is to be traced to a direct object.
func (parser *PdfParser) traceStreamLength(lengthObj PdfObject) (PdfObject, error) {
lengthRef, isRef := lengthObj.(*PdfObjectReference)
if isRef {
lookupInProgress, has := parser.streamLengthReferenceLookupInProgress[lengthRef.ObjectNumber]
if has && lookupInProgress {
common.Log.Debug("Stream Length reference unresolved (illegal)")
return nil, errors.New("Illegal recursive loop")
}
// Mark lookup as in progress.
parser.streamLengthReferenceLookupInProgress[lengthRef.ObjectNumber] = true
}
slo, err := parser.Trace(lengthObj)
if err != nil {
return nil, err
}
common.Log.Trace("Stream length: %s", slo)
if isRef {
// Mark as completed lookup
parser.streamLengthReferenceLookupInProgress[lengthRef.ObjectNumber] = false
}
return slo, nil
}
// Parse an indirect object from the input stream. Can also be an object stream.
// Returns the indirect object (*PdfIndirectObject) or the stream object (*PdfObjectStream).
// TODO: Unexport (v3).
func (parser *PdfParser) ParseIndirectObject() (PdfObject, error) {
indirect := PdfIndirectObject{}
common.Log.Trace("Reading indirect obj")
bb, err := parser.reader.Peek(20)
if err != nil {
common.Log.Debug("ERROR: Fail to read indirect obj")
return &indirect, err
}
common.Log.Trace("indirect obj peek \"%s\"", string(bb))
indices := reIndirectObject.FindStringSubmatchIndex(string(bb))
if len(indices) < 6 {
common.Log.Debug("ERROR: Unable to find object signature (%s)", string(bb))
return &indirect, errors.New("Unable to detect indirect object signature")
}
parser.reader.Discard(indices[0]) // Take care of any small offset.
common.Log.Trace("Offsets % d", indices)
// Read the object header.
hlen := indices[1] - indices[0]
hb := make([]byte, hlen)
_, err = io.ReadAtLeast(parser.reader, hb, hlen)
if err != nil {
common.Log.Debug("ERROR: unable to read - %s", err)
return nil, err
}
common.Log.Trace("textline: %s", hb)
result := reIndirectObject.FindStringSubmatch(string(hb))
if len(result) < 3 {
common.Log.Debug("ERROR: Unable to find object signature (%s)", string(hb))
return &indirect, errors.New("Unable to detect indirect object signature")
}
on, _ := strconv.ParseInt(result[1], 10, 64)
gn, _ := strconv.ParseInt(result[2], 10, 64)
indirect.ObjectNumber = on
indirect.GenerationNumber = gn
for {
ch, err := parser.reader.ReadByte()
if err != nil {
return &indirect, err
}
if IsWhiteSpace(ch) {
continue
}
switch ch {
case '%':
{
parser.reader.UnreadByte()
parser.skipComments()
}
case '/', '(', '[', '<', 'n', 'f', 't':
{
parser.reader.UnreadByte()
indirect.PdfObject, err = parser.parseObject()
if err != nil {
return &indirect, err
}
common.Log.Trace("Parsed inner object ... finished.")
}
case 'e':
{
line, err := parser.reader.ReadString('j')
if err != nil {
return &indirect, err
}
line = strings.TrimSpace(line)
if line == "ndobj" {
common.Log.Trace("Returning indirect!")
return &indirect, nil
}
}
case 's':
{
//stream
bb := make([]byte, 5)
n, err := parser.reader.Read(bb)
if err != nil {
return nil, err
}
common.Log.Trace("should read 5, actual read: %d", n)
if string(bb[:5]) == "tream" {
//it will skip the real byte when use skipspaces() and it will cause decrypt or decode fail
parser.reader.ReadString('\n')
dict, ok := indirect.PdfObject.(*PdfObjectDictionary)
if !ok {
return nil, errors.New("Stream object missing dictionary")
}
common.Log.Trace("Stream dict %s", dict)
// Special stream length tracing function used to avoid endless recursive looping.
slo, err := parser.traceStreamLength(dict.Get("Length"))
if err != nil {
common.Log.Debug("Fail to trace stream length: %v", err)
return nil, err
}
common.Log.Trace("Stream length: %s", slo)
pstreamLength, ok := slo.(*PdfObjectInteger)
if !ok {
return nil, errors.New("Stream length needs to be an integer")
}
streamLength := *pstreamLength
if streamLength < 0 {
return nil, errors.New("Stream needs to be longer than 0")
}
//TODO: we can delete the logic for effective
// Validate the stream length based on the cross references.
// Find next object with closest offset to current object and calculate
// the expected stream length based on that.
streamStartOffset := parser.GetFileOffset()
nextObjectOffset := parser.xrefNextObjectOffset(streamStartOffset)
if streamStartOffset+int64(streamLength) > nextObjectOffset && nextObjectOffset > streamStartOffset {
common.Log.Debug("Expected ending at %d", streamStartOffset+int64(streamLength))
common.Log.Debug("Next object starting at %d", nextObjectOffset)
// endstream + "\n" endobj + "\n" (17)
newLength := nextObjectOffset - streamStartOffset - 17
if newLength < 0 {
return nil, errors.New("Invalid stream length, going past boundaries")
}
common.Log.Debug("Attempting a length correction to %d...", newLength)
streamLength = PdfObjectInteger(newLength)
dict.Set("Length", &streamLength)
}
common.Log.Trace("stream length: %d", streamLength)
stream := make([]byte, streamLength)
_, err = parser.ReadAtLeast(stream, int(streamLength))
if err != nil {
common.Log.Debug("Error stream (%d): %X, err: %v", len(stream), stream, err)
return nil, err
}
streamobj := PdfObjectStream{}
streamobj.Stream = stream
streamobj.PdfObjectDictionary = indirect.PdfObject.(*PdfObjectDictionary)
streamobj.ObjectNumber = indirect.ObjectNumber
streamobj.GenerationNumber = indirect.GenerationNumber
parser.skipSpaces()
parser.reader.Discard(9) // endstream
parser.skipSpaces()
return &streamobj, nil
} else {
common.Log.Debug("Error: wrong object with s start")
return &indirect, errors.New("wrong object with s start")
}
}
default:
{
parser.reader.UnreadByte()
indirect.PdfObject, err = parser.parseObject()
return &indirect, err
}
}
}
return &indirect, nil
}
//read compressed xref table
func (parser *PdfParser) readXrefStream(xs *PdfObjectStream) error {
sizeObj, ok := xs.PdfObjectDictionary.Get("Size").(*PdfObjectInteger)
if !ok {
common.Log.Debug("Error: missing Size from xref stm")
return errors.New("missing Size from xref stm")
}
// Sanity check to avoid DoS attacks. Maximum number of indirect objects on 32 bit system.
if int64(*sizeObj) > 8388607 {
common.Log.Debug("Error: xref Size exceeded limit, over 8388607 (%d)", *sizeObj)
return errors.New("range check error")
}
wObj := xs.PdfObjectDictionary.Get("W")
wArr, ok := wObj.(*PdfObjectArray)
if !ok {
return errors.New("invalid W in xref stream")
}
wLen := len(*wArr)
if wLen != 3 {
common.Log.Debug("Error: unsupported xref stm (len(W) != 3 - %d)", wLen)
return errors.New("unsupported xref stm len(W) != 3")
}
// get b0 b1 b2
var b []int64
for i := 0; i < 3; i++ {
w, ok := (*wArr)[i].(PdfObject)
if !ok {
return errors.New("invalid W")
}
wVal, ok := w.(*PdfObjectInteger)
if !ok {
return errors.New("invalid w integer object type")
}
b = append(b, int64(*wVal))
}
ds, err := DecodeStream(xs)
if err != nil {
common.Log.Debug("ERROR: Unable to decode stream: %v", err)
return err
}
s0 := int(b[0])
s1 := int(b[0] + b[1])
s2 := int(b[0] + b[1] + b[2])
deltab := int(b[0] + b[1] + b[2])
if s0 < 0 || s1 < 0 || s2 < 0 {
common.Log.Debug("Error W value < 0 (%d,%d,%d)", s0, s1, s2)
return errors.New("Range check error")
}
if deltab == 0 {
common.Log.Debug("No xref objects in stream (deltab == 0)")
return nil
}
// Calculate expected entries.
dsLen := len(ds)
entries := dsLen / deltab
// Get the object indices.
objCount := 0
indexObj := xs.PdfObjectDictionary.Get("Index")
// Table 17 (7.5.8.2 Cross-Reference Stream Dictionary)
// (Optional) An array containing a pair of integers for each
// subsection in this section. The first integer shall be the first
// object number in the subsection; the second integer shall be the
// number of entries in the subsection.
// The array shall be sorted in ascending order by object number.
// Subsections cannot overlap; an object number may have at most
// one entry in a section.
// Default value: [0 Size].
indexList := []int{}
if indexObj != nil {
common.Log.Trace("Index: %b", indexObj)
indicesArray, ok := indexObj.(*PdfObjectArray)
if !ok {
common.Log.Debug("Invalid Index object (should be an array)")
return errors.New("Invalid Index object")
}
// Expect indLen to be a multiple of 2.
if len(*indicesArray)%2 != 0 {
common.Log.Debug("Warning: failed to load xref stm index not multiple of 2.")
return errors.New("Range check error")
}
objCount = 0
indices, err := indicesArray.ToIntegerArray()
if err != nil {
common.Log.Debug("Error getting index array as integers: %v", err)
return err
}
for i := 0; i < len(indices); i += 2 {
// add the indices to the list..
startIdx := indices[i]
numObjs := indices[i+1]
for j := 0; j < numObjs; j++ {
indexList = append(indexList, startIdx+j)
}
objCount += numObjs
}
} else {
// If no Index, then assume [0 Size]
for i := 0; i < int(*sizeObj); i++ {
indexList = append(indexList, i)
}
objCount = int(*sizeObj)
}
//maybe no index obj
if entries == objCount+1 {
// For compatibility, expand the object count.
common.Log.Debug("BAD file: allowing compatibility (append one object to xref stm)")
indexList = append(indexList, objCount)
objCount++
}
if entries != objCount {
// If mismatch -> error (already allowing mismatch of 1 if Index not specified).
common.Log.Debug("ERROR: xref stm: num entries != len(indices) (%d != %d)", entries, objCount)
return errors.New("Xref stm num entries != len(indices)")
}
common.Log.Trace("Objects count %d, Indices: % d", objCount, indexList)
// Convert byte array to a larger integer, little-endian.
convertBytes := func(v []byte) int64 {
var tmp int64 = 0
for i := 0; i < len(v); i++ {
tmp += int64(v[i]) * (1 << uint(8*(len(v)-i-1)))
}
return tmp
}
common.Log.Trace("Decoded stream length: %d", len(ds))
objIndex := 0
for i := 0; i < dsLen; i += deltab {
err := checkBounds(dsLen, i, i+s0)
if err != nil {
common.Log.Debug("Invalid slice range: %v", err)
return err
}
p1 := ds[i : i+s0]
err = checkBounds(dsLen, i+s0, i+s1)
if err != nil {
common.Log.Debug("Invalid slice range: %v", err)
return err
}
p2 := ds[i+s0 : i+s1]
err = checkBounds(dsLen, i+s1, i+s2)
if err != nil {
common.Log.Debug("Invalid slice range: %v", err)
return err
}
p3 := ds[i+s1 : i+s2]
ftype := convertBytes(p1)
n2 := convertBytes(p2)
n3 := convertBytes(p3)
if b[0] == 0 {
// If first entry in W is 0, then default to to type 1.
// (uncompressed object via offset).
ftype = 1
}
if objIndex >= objCount {
common.Log.Debug("XRef stream - Trying to access index out of bounds - breaking")
break
}
objNum := indexList[objIndex]
objIndex++
common.Log.Trace("%d. p1: % x", objNum, p1)
common.Log.Trace("%d. p2: % x", objNum, p2)
common.Log.Trace("%d. p3: % x", objNum, p3)
common.Log.Trace("%d. xref: %d %d %d", objNum, ftype, n2, n3)
if ftype == 0 {
common.Log.Trace("- Free object - can probably ignore")
} else if ftype == 1 {
common.Log.Trace("- In use - uncompressed via offset %b", p2)
// Object type 1: Objects that are in use but are not
// compressed, i.e. defined by an offset (normal entry)
if xr, ok := parser.xrefs[objNum]; !ok || int(n3) > xr.generation {
// Only overload if not already loaded!
// or has a newer generation number. (should not happen)
obj := XrefObject{objectNumber: objNum,
xtype: XREF_TABLE_ENTRY, offset: n2, generation: int(n3)}
parser.xrefs[objNum] = obj
}
} else if ftype == 2 {
// Object type 2: Compressed object.
common.Log.Trace("- In use - compressed object")
if _, ok := parser.xrefs[objNum]; !ok {
obj := XrefObject{objectNumber: objNum,
xtype: XREF_OBJECT_STREAM, osObjNumber: int(n2), osObjIndex: int(n3)}
parser.xrefs[objNum] = obj
common.Log.Trace("entry: %s", parser.xrefs[objNum])
}
} else {
common.Log.Debug("ERROR: --------INVALID TYPE XrefStm invalid?-------")
// Continue, we do not define anything -> null object.
// 7.5.8.3:
//
// In PDF 1.5 through PDF 1.7, only types 0, 1, and 2 are
// allowed. Any other value shall be interpreted as a
// reference to the null object, thus permitting new entry
// types to be defined in the future.
continue
}
}
return nil
}
// read xref table
func (parser *PdfParser) readXrefTable(prevLine string) error {
curObjIdx := -1
objCount := 0
insideSubsection := false
//ref^M34 45 ^M111 000 n
if len(prevLine) > 3 {
splitStrs := strings.Split(prevLine, "\r")
for _, s := range splitStrs {
s = strings.TrimSpace(s)
result1 := reXrefSubsection.FindStringSubmatch(s)
if len(result1) == 3 {
// Match
first, _ := strconv.Atoi(result1[1])
second, _ := strconv.Atoi(result1[2])
curObjIdx = first
objCount = second
insideSubsection = true
common.Log.Trace("xref subsection: first object: %d objects: %d", curObjIdx, objCount)
continue
}
result2 := reXrefEntry.FindStringSubmatch(s)
if len(result2) == 4 {
if !insideSubsection {
common.Log.Debug("Error: Xref invalid format!")
return errors.New("Xref invalid format")
}
first, _ := strconv.ParseInt(result2[1], 10, 64)
gen, _ := strconv.Atoi(result2[2])
third := result2[3]
if strings.ToLower(third) == "n" && first > 1 {
if x, ok := parser.xrefs[curObjIdx]; !ok || gen > x.generation {
obj := XrefObject{
objectNumber: curObjIdx,
xtype: XREF_TABLE_ENTRY,
offset: first,
generation: gen}
parser.xrefs[curObjIdx] = obj
}
}
curObjIdx++
}
}
}
for {
line, err := parser.reader.ReadString('\n')
if err != nil {
//%%EOF exist the same line with trailer
if err == io.EOF {
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "trailer") {
common.Log.Trace("found trailer, %s", line)
// sometimes get "trailer<<"
if len(line) > 9 {
offset := parser.GetFileOffset()
parser.SetFileOffset(offset - int64(len(line)) + 6)
}
parser.skipSpaces()
break
}
}
return err
}
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "trailer") {
common.Log.Trace("found trailer, %s", line)
// sometimes get "trailer<<"
if len(line) > 9 {
offset := parser.GetFileOffset()
parser.SetFileOffset(offset - int64(len(line)) + 6)
}
parser.skipSpaces()
break
}
//like 34 56^M110000 000 n
splitStrs := strings.Split(line, "\r")
for _, s := range splitStrs {
s = strings.TrimSpace(s)
result1 := reXrefSubsection.FindStringSubmatch(s)
if len(result1) == 3 {
// Match
first, _ := strconv.Atoi(result1[1])
second, _ := strconv.Atoi(result1[2])
curObjIdx = first
objCount = second
insideSubsection = true
common.Log.Trace("xref subsection: first object: %d objects: %d", curObjIdx, objCount)
continue
}
result2 := reXrefEntry.FindStringSubmatch(s)
if len(result2) == 4 {
if !insideSubsection {
common.Log.Debug("Error: Xref invalid format!")
return errors.New("Xref invalid format")
}
first, _ := strconv.ParseInt(result2[1], 10, 64)
gen, _ := strconv.Atoi(result2[2])
third := result2[3]
if strings.ToLower(third) == "n" && first > 1 {
// Object in use in the file! Load it.
// Ignore free objects ('f').
//
// Some malformed writers mark the offset as 0 to
// indicate that the object is free, and still mark as 'n'
// Fairly safe to assume is free if offset is 0.
//
// Some malformed writers even seem to have values such as
// 1.. Assume null object for those also. That is referring
// to within the PDF version in the header clearly.
//
// Load if not existing or higher generation number than previous.
// Usually should not happen, lower generation numbers
// would be marked as free. But can still happen!
if x, ok := parser.xrefs[curObjIdx]; !ok || gen > x.generation {
obj := XrefObject{
objectNumber: curObjIdx,
xtype: XREF_TABLE_ENTRY,
offset: first,
generation: gen}
parser.xrefs[curObjIdx] = obj
}
}
curObjIdx++
continue
}
if strings.Compare(s, "%%EOF") == 0 {
common.Log.Debug("ERROR: end of file - trailer not found - error!")
return errors.New("End of file - trailer not found")
}
}
}
return nil
}
// Numeric objects.
// Section 7.3.3.
// Integer or Float.
//
// An integer shall be written as one or more decimal digits optionally
// preceded by a sign. The value shall be interpreted as a signed
// decimal integer and shall be converted to an integer object.
//
// A real value shall be written as one or more decimal digits with an
// optional sign and a leading, trailing, or embedded PERIOD (2Eh)
// (decimal point). The value shall be interpreted as a real number
// and shall be converted to a real object.
//
// Regarding exponential numbers: 7.3.3 Numeric Objects:
// A conforming writer shall not use the PostScript syntax for numbers
// with non-decimal radices (such as 16#FFFE) or in exponential format
// (such as 6.02E23).
// Nonetheless, we sometimes get numbers with exponential format, so
// we will support it in the reader (no confusion with other types, so
// no compromise).
func (parser *PdfParser) parseNumber() (PdfObject, error) {
isFloat := false
allowSigns := true
var r bytes.Buffer
for {
common.Log.Trace("Parsing number \"%s\"", r.String())
bb, err := parser.reader.Peek(1)
if err == io.EOF {
// GH: EOF handling. Handle EOF like end of line. Can happen with
// encoded object streams that the object is at the end.
// In other cases, we will get the EOF error elsewhere at any rate.
break // Handle like EOF
}
if err != nil {
common.Log.Debug("ERROR %s", err)
return nil, err
}
if allowSigns && (bb[0] == '-' || bb[0] == '+') {
// Only appear in the beginning, otherwise serves as a delimiter.
b, _ := parser.reader.ReadByte()
r.WriteByte(b)
allowSigns = false // Only allowed in beginning, and after e (exponential).
} else if IsDecimalDigit(bb[0]) {
b, _ := parser.reader.ReadByte()
r.WriteByte(b)
} else if bb[0] == '.' {
b, _ := parser.reader.ReadByte()
r.WriteByte(b)
isFloat = true
} else if bb[0] == 'e' {
// Exponential number format.
b, _ := parser.reader.ReadByte()
r.WriteByte(b)
isFloat = true
allowSigns = true
} else {
break
}
}
if isFloat {
fVal, err := strconv.ParseFloat(r.String(), 64)
o := PdfObjectFloat(fVal)
return &o, err
} else {
intVal, err := strconv.ParseInt(r.String(), 10, 64)
o := PdfObjectInteger(intVal)
return &o, err
}
}
// Parse a name starting with '/'.
func (parser *PdfParser) parseName() (PdfObjectName, error) {
var ch byte
var err error
var r bytes.Buffer
for {
ch, err = parser.reader.ReadByte()
if err == io.EOF {
return "", errors.New("read until end of file")
}
if ch == '/' {
break
}
}
jump := false
for {
if jump {
parser.reader.UnreadByte()
break
}
ch, err = parser.reader.ReadByte()
if err == io.EOF {
return "", errors.New("read until end of file")
}
if isSpace := IsWhiteSpace(ch); isSpace {
break
}
switch ch {
case '/', '{', '}', '[', ']', '(', ')', '<', '>', '%':
{
jump = true
}
case '#':
// like /A#42 = AB
{
firstByte, err := parser.reader.ReadByte()
if err != nil {
return PdfObjectName(r.String()), err
}
secondByte, _ := parser.reader.ReadByte()
if err != nil {
return PdfObjectName(r.String()), err
}
hexcode := []byte{firstByte, secondByte}
code, err := hex.DecodeString(string(hexcode[:]))
if err != nil {
return PdfObjectName(r.String()), err
}
r.Write(code)
}
default:
r.WriteByte(ch)
}
}
return PdfObjectName(r.String()), nil
}
// Parse reference to an indirect object.
func parseReference(refStr string) (PdfObjectReference, error) {
objref := PdfObjectReference{}
result := reReference.FindStringSubmatch(string(refStr))
if len(result) < 3 {
common.Log.Debug("Error parsing reference")
return objref, errors.New("Unable to parse reference")
}
objNum, _ := strconv.Atoi(result[1])
genNum, _ := strconv.Atoi(result[2])
objref.ObjectNumber = int64(objNum)
objref.GenerationNumber = int64(genNum)
return objref, nil
}
// Starts with '<' ends with '>'.
// Currently not converting the hex codes to characters.
func (parser *PdfParser) parseHexString() (PdfObjectString, error) {
// jump '<'
parser.reader.ReadByte()
var r bytes.Buffer
for {
b, err := parser.reader.ReadByte()
if err != nil {
return PdfObjectString(""), err
}
if b == '>' {
break
}
if !IsWhiteSpace(b) {
r.WriteByte(b)
}
}
if r.Len()%2 == 1 {
common.Log.Debug("no valid hex, append 0")
r.WriteRune('0')
}
buf, _ := hex.DecodeString(r.String())
return PdfObjectString(buf), nil
}
// A string starts with '(' and ends with ')'.
func (parser *PdfParser) parseString() (PdfObjectString, error) {
// jump the '('
parser.reader.ReadByte()
var r bytes.Buffer
parenthesesDepth := 1
for {
bb, err := parser.reader.ReadByte()
if err != nil {
return PdfObjectString(r.String()), err
}
if bb == '\\' { // Escape sequence.
b, err := parser.reader.ReadByte()
if err != nil {
return PdfObjectString(r.String()), err
}
// Octal '\ddd' number (base 8).
if IsOctalDigit(b) {
bb, err := parser.reader.Peek(2)
if err != nil {
return PdfObjectString(r.String()), err
}
numeric := []byte{}
numeric = append(numeric, b)
for _, val := range bb {
if IsOctalDigit(val) {
numeric = append(numeric, val)
} else {
break
}
}
parser.reader.Discard(len(numeric) - 1)
common.Log.Trace("Numeric string \"%s\"", numeric)
code, err := strconv.ParseUint(string(numeric), 8, 32)
if err != nil {
return PdfObjectString(r.String()), err
}
r.WriteByte(byte(code))
continue
}
switch b {
case 'n':
r.WriteRune('\n')
case 'r':
r.WriteRune('\r')
case 't':
r.WriteRune('\t')
case 'b':
r.WriteRune('\b')
case 'f':
r.WriteRune('\f')
case '(':
r.WriteRune('(')
case ')':
r.WriteRune(')')
case '\\':
r.WriteRune('\\')
}
continue
} else if bb == '(' {
//handle parentheses like (())
parenthesesDepth++
} else if bb == ')' {
parenthesesDepth--
if parenthesesDepth == 0 {
break
}
}
r.WriteByte(bb)
}
return PdfObjectString(r.String()), nil
}
// Starts with '[' ends with ']'. Can contain any kinds of direct objects.
func (parser *PdfParser) parseArray() (PdfObjectArray, error) {
arr := make(PdfObjectArray, 0)
//skip '['
parser.reader.ReadByte()
for {
ch, err := parser.reader.ReadByte()
if err != nil {
return arr, err
}
if IsWhiteSpace(ch) {
continue
}
if ch == ']' {
break
}
parser.reader.UnreadByte()
obj, err := parser.parseObject()
if err != nil {
return arr, err
}
arr = append(arr, obj)
}
return arr, nil
}
// Parse null object.
func (parser *PdfParser) parseNull() (PdfObjectNull, error) {
_, err := parser.reader.Discard(4)