Debian Codegraph @

read.go

raw symbols SCIP
1 // Copyright 2014 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Package pdf implements reading of PDF files.
6 //
7 // Overview
8 //
9 // PDF is Adobe's Portable Document Format, ubiquitous on the internet.
10 // A PDF document is a complex data format built on a fairly simple structure.
11 // This package exposes the simple structure along with some wrappers to
12 // extract basic information. If more complex information is needed, it is
13 // possible to extract that information by interpreting the structure exposed
14 // by this package.
15 //
16 // Specifically, a PDF is a data structure built from Values, each of which has
17 // one of the following Kinds:
18 //
19 // Null, for the null object.
20 // Integer, for an integer.
21 // Real, for a floating-point number.
22 // Bool, for a boolean value.
23 // Name, for a name constant (as in /Helvetica).
24 // String, for a string constant.
25 // Dict, for a dictionary of name-value pairs.
26 // Array, for an array of values.
27 // Stream, for an opaque data stream and associated header dictionary.
28 //
29 // The accessors on Value—Int64, Float64, Bool, Name, and so on—return
30 // a view of the data as the given type. When there is no appropriate view,
31 // the accessor returns a zero result. For example, the Name accessor returns
32 // the empty string if called on a Value v for which v.Kind() != Name.
33 // Returning zero values this way, especially from the Dict and Array accessors,
34 // which themselves return Values, makes it possible to traverse a PDF quickly
35 // without writing any error checking. On the other hand, it means that mistakes
36 // can go unreported.
37 //
38 // The basic structure of the PDF file is exposed as the graph of Values.
39 //
40 // Most richer data structures in a PDF file are dictionaries with specific interpretations
41 // of the name-value pairs. The Font and Page wrappers make the interpretation
42 // of a specific Value as the corresponding type easier. They are only helpers, though:
43 // they are implemented only in terms of the Value API and could be moved outside
44 // the package. Equally important, traversal of other PDF data structures can be implemented
45 // in other packages as needed.
46 //
47 package pdf // import "rsc.io/pdf"
48
49 // BUG(rsc): The package is incomplete, although it has been used successfully on some
50 // large real-world PDF files.
51
52 // BUG(rsc): There is no support for closing open PDF files. If you drop all references to a Reader,
53 // the underlying reader will eventually be garbage collected.
54
55 // BUG(rsc): The library makes no attempt at efficiency. A value cache maintained in the Reader
56 // would probably help significantly.
57
58 // BUG(rsc): The support for reading encrypted files is weak.
59
60 // BUG(rsc): The Value API does not support error reporting. The intent is to allow users to
61 // set an error reporting callback in Reader, but that code has not been implemented.
62
63 import (
64 "bytes"
65 "compress/zlib"
66 "crypto/aes"
67 "crypto/cipher"
68 "crypto/md5"
69 "crypto/rc4"
70 "fmt"
71 "io"
72 "io/ioutil"
73 "os"
74 "sort"
75 "strconv"
76 )
77
78 // A Reader is a single PDF file open for reading.
79 type Reader struct {
80 f io.ReaderAt
81 end int64
82 xref []xref
83 trailer dict
84 trailerptr objptr
85 key []byte
86 useAES bool
87 }
88
89 type xref struct {
90 ptr objptr
91 inStream bool
92 stream objptr
93 offset int64
94 }
95
96 func (r *Reader) errorf(format string, args ...interface{}) {
97 panic(fmt.Errorf(format, args...))
98 }
99
100 // Open opens a file for reading.
101 func Open(file string) (*Reader, error) {
102 // TODO: Deal with closing file.
103 f, err := os.Open(file)
104 if err != nil {
105 return nil, err
106 }
107 fi, err := f.Stat()
108 if err != nil {
109 f.Close()
110 return nil, err
111 }
112 return NewReader(f, fi.Size())
113 }
114
115 // NewReader opens a file for reading, using the data in f with the given total size.
116 func NewReader(f io.ReaderAt, size int64) (*Reader, error) {
117 return NewReaderEncrypted(f, size, nil)
118 }
119
120 // NewReaderEncrypted opens a file for reading, using the data in f with the given total size.
121 // If the PDF is encrypted, NewReaderEncrypted calls pw repeatedly to obtain passwords
122 // to try. If pw returns the empty string, NewReaderEncrypted stops trying to decrypt
123 // the file and returns an error.
124 func NewReaderEncrypted(f io.ReaderAt, size int64, pw func() string) (*Reader, error) {
125 buf := make([]byte, 10)
126 f.ReadAt(buf, 0)
127 if !bytes.HasPrefix(buf, []byte("%PDF-1.")) || buf[7] < '0' || buf[7] > '7' || buf[8] != '\r' && buf[8] != '\n' {
128 return nil, fmt.Errorf("not a PDF file: invalid header")
129 }
130 end := size
131 const endChunk = 100
132 buf = make([]byte, endChunk)
133 f.ReadAt(buf, end-endChunk)
134 for len(buf) > 0 && buf[len(buf)-1] == '\n' || buf[len(buf)-1] == '\r' {
135 buf = buf[:len(buf)-1]
136 }
137 buf = bytes.TrimRight(buf, "\r\n\t ")
138 if !bytes.HasSuffix(buf, []byte("%%EOF")) {
139 return nil, fmt.Errorf("not a PDF file: missing %%%%EOF")
140 }
141 i := findLastLine(buf, "startxref")
142 if i < 0 {
143 return nil, fmt.Errorf("malformed PDF file: missing final startxref")
144 }
145
146 r := &Reader{
147 f: f,
148 end: end,
149 }
150 pos := end - endChunk + int64(i)
151 b := newBuffer(io.NewSectionReader(f, pos, end-pos), pos)
152 if b.readToken() != keyword("startxref") {
153 return nil, fmt.Errorf("malformed PDF file: missing startxref")
154 }
155 startxref, ok := b.readToken().(int64)
156 if !ok {
157 return nil, fmt.Errorf("malformed PDF file: startxref not followed by integer")
158 }
159 b = newBuffer(io.NewSectionReader(r.f, startxref, r.end-startxref), startxref)
160 xref, trailerptr, trailer, err := readXref(r, b)
161 if err != nil {
162 return nil, err
163 }
164 r.xref = xref
165 r.trailer = trailer
166 r.trailerptr = trailerptr
167 if trailer["Encrypt"] == nil {
168 return r, nil
169 }
170 err = r.initEncrypt("")
171 if err == nil {
172 return r, nil
173 }
174 if pw == nil || err != ErrInvalidPassword {
175 return nil, err
176 }
177 for {
178 next := pw()
179 if next == "" {
180 break
181 }
182 if r.initEncrypt(next) == nil {
183 return r, nil
184 }
185 }
186 return nil, err
187 }
188
189 // Trailer returns the file's Trailer value.
190 func (r *Reader) Trailer() Value {
191 return Value{r, r.trailerptr, r.trailer}
192 }
193
194 func readXref(r *Reader, b *buffer) ([]xref, objptr, dict, error) {
195 tok := b.readToken()
196 if tok == keyword("xref") {
197 return readXrefTable(r, b)
198 }
199 if _, ok := tok.(int64); ok {
200 b.unreadToken(tok)
201 return readXrefStream(r, b)
202 }
203 return nil, objptr{}, nil, fmt.Errorf("malformed PDF: cross-reference table not found: %v", tok)
204 }
205
206 func readXrefStream(r *Reader, b *buffer) ([]xref, objptr, dict, error) {
207 obj1 := b.readObject()
208 obj, ok := obj1.(objdef)
209 if !ok {
210 return nil, objptr{}, nil, fmt.Errorf("malformed PDF: cross-reference table not found: %v", objfmt(obj1))
211 }
212 strmptr := obj.ptr
213 strm, ok := obj.obj.(stream)
214 if !ok {
215 return nil, objptr{}, nil, fmt.Errorf("malformed PDF: cross-reference table not found: %v", objfmt(obj))
216 }
217 if strm.hdr["Type"] != name("XRef") {
218 return nil, objptr{}, nil, fmt.Errorf("malformed PDF: xref stream does not have type XRef")
219 }
220 size, ok := strm.hdr["Size"].(int64)
221 if !ok {
222 return nil, objptr{}, nil, fmt.Errorf("malformed PDF: xref stream missing Size")
223 }
224 table := make([]xref, size)
225
226 table, err := readXrefStreamData(r, strm, table, size)
227 if err != nil {
228 return nil, objptr{}, nil, fmt.Errorf("malformed PDF: %v", err)
229 }
230
231 for prevoff := strm.hdr["Prev"]; prevoff != nil; {
232 off, ok := prevoff.(int64)
233 if !ok {
234 return nil, objptr{}, nil, fmt.Errorf("malformed PDF: xref Prev is not integer: %v", prevoff)
235 }
236 b := newBuffer(io.NewSectionReader(r.f, off, r.end-off), off)
237 obj1 := b.readObject()
238 obj, ok := obj1.(objdef)
239 if !ok {
240 return nil, objptr{}, nil, fmt.Errorf("malformed PDF: xref prev stream not found: %v", objfmt(obj1))
241 }
242 prevstrm, ok := obj.obj.(stream)
243 if !ok {
244 return nil, objptr{}, nil, fmt.Errorf("malformed PDF: xref prev stream not found: %v", objfmt(obj))
245 }
246 prevoff = prevstrm.hdr["Prev"]
247 prev := Value{r, objptr{}, prevstrm}
248 if prev.Kind() != Stream {
249 return nil, objptr{}, nil, fmt.Errorf("malformed PDF: xref prev stream is not stream: %v", prev)
250 }
251 if prev.Key("Type").Name() != "XRef" {
252 return nil, objptr{}, nil, fmt.Errorf("malformed PDF: xref prev stream does not have type XRef")
253 }
254 psize := prev.Key("Size").Int64()
255 if psize > size {
256 return nil, objptr{}, nil, fmt.Errorf("malformed PDF: xref prev stream larger than last stream")
257 }
258 if table, err = readXrefStreamData(r, prev.data.(stream), table, psize); err != nil {
259 return nil, objptr{}, nil, fmt.Errorf("malformed PDF: reading xref prev stream: %v", err)
260 }
261 }
262
263 return table, strmptr, strm.hdr, nil
264 }
265
266 func readXrefStreamData(r *Reader, strm stream, table []xref, size int64) ([]xref, error) {
267 index, _ := strm.hdr["Index"].(array)
268 if index == nil {
269 index = array{int64(0), size}
270 }
271 if len(index)%2 != 0 {
272 return nil, fmt.Errorf("invalid Index array %v", objfmt(index))
273 }
274 ww, ok := strm.hdr["W"].(array)
275 if !ok {
276 return nil, fmt.Errorf("xref stream missing W array")
277 }
278
279 var w []int
280 for _, x := range ww {
281 i, ok := x.(int64)
282 if !ok || int64(int(i)) != i {
283 return nil, fmt.Errorf("invalid W array %v", objfmt(ww))
284 }
285 w = append(w, int(i))
286 }
287 if len(w) < 3 {
288 return nil, fmt.Errorf("invalid W array %v", objfmt(ww))
289 }
290
291 v := Value{r, objptr{}, strm}
292 wtotal := 0
293 for _, wid := range w {
294 wtotal += wid
295 }
296 buf := make([]byte, wtotal)
297 data := v.Reader()
298 for len(index) > 0 {
299 start, ok1 := index[0].(int64)
300 n, ok2 := index[1].(int64)
301 if !ok1 || !ok2 {
302 return nil, fmt.Errorf("malformed Index pair %v %v %T %T", objfmt(index[0]), objfmt(index[1]), index[0], index[1])
303 }
304 index = index[2:]
305 for i := 0; i < int(n); i++ {
306 _, err := io.ReadFull(data, buf)
307 if err != nil {
308 return nil, fmt.Errorf("error reading xref stream: %v", err)
309 }
310 v1 := decodeInt(buf[0:w[0]])
311 if w[0] == 0 {
312 v1 = 1
313 }
314 v2 := decodeInt(buf[w[0] : w[0]+w[1]])
315 v3 := decodeInt(buf[w[0]+w[1] : w[0]+w[1]+w[2]])
316 x := int(start) + i
317 for cap(table) <= x {
318 table = append(table[:cap(table)], xref{})
319 }
320 if table[x].ptr != (objptr{}) {
321 continue
322 }
323 switch v1 {
324 case 0:
325 table[x] = xref{ptr: objptr{0, 65535}}
326 case 1:
327 table[x] = xref{ptr: objptr{uint32(x), uint16(v3)}, offset: int64(v2)}
328 case 2:
329 table[x] = xref{ptr: objptr{uint32(x), 0}, inStream: true, stream: objptr{uint32(v2), 0}, offset: int64(v3)}
330 default:
331 fmt.Printf("invalid xref stream type %d: %x\n", v1, buf)
332 }
333 }
334 }
335 return table, nil
336 }
337
338 func decodeInt(b []byte) int {
339 x := 0
340 for _, c := range b {
341 x = x<<8 | int(c)
342 }
343 return x
344 }
345
346 func readXrefTable(r *Reader, b *buffer) ([]xref, objptr, dict, error) {
347 var table []xref
348
349 table, err := readXrefTableData(b, table)
350 if err != nil {
351 return nil, objptr{}, nil, fmt.Errorf("malformed PDF: %v", err)
352 }
353
354 trailer, ok := b.readObject().(dict)
355 if !ok {
356 return nil, objptr{}, nil, fmt.Errorf("malformed PDF: xref table not followed by trailer dictionary")
357 }
358
359 for prevoff := trailer["Prev"]; prevoff != nil; {
360 off, ok := prevoff.(int64)
361 if !ok {
362 return nil, objptr{}, nil, fmt.Errorf("malformed PDF: xref Prev is not integer: %v", prevoff)
363 }
364 b := newBuffer(io.NewSectionReader(r.f, off, r.end-off), off)
365 tok := b.readToken()
366 if tok != keyword("xref") {
367 return nil, objptr{}, nil, fmt.Errorf("malformed PDF: xref Prev does not point to xref")
368 }
369 table, err = readXrefTableData(b, table)
370 if err != nil {
371 return nil, objptr{}, nil, fmt.Errorf("malformed PDF: %v", err)
372 }
373
374 trailer, ok := b.readObject().(dict)
375 if !ok {
376 return nil, objptr{}, nil, fmt.Errorf("malformed PDF: xref Prev table not followed by trailer dictionary")
377 }
378 prevoff = trailer["Prev"]
379 }
380
381 size, ok := trailer[name("Size")].(int64)
382 if !ok {
383 return nil, objptr{}, nil, fmt.Errorf("malformed PDF: trailer missing /Size entry")
384 }
385
386 if size < int64(len(table)) {
387 table = table[:size]
388 }
389
390 return table, objptr{}, trailer, nil
391 }
392
393 func readXrefTableData(b *buffer, table []xref) ([]xref, error) {
394 for {
395 tok := b.readToken()
396 if tok == keyword("trailer") {
397 break
398 }
399 start, ok1 := tok.(int64)
400 n, ok2 := b.readToken().(int64)
401 if !ok1 || !ok2 {
402 return nil, fmt.Errorf("malformed xref table")
403 }
404 for i := 0; i < int(n); i++ {
405 off, ok1 := b.readToken().(int64)
406 gen, ok2 := b.readToken().(int64)
407 alloc, ok3 := b.readToken().(keyword)
408 if !ok1 || !ok2 || !ok3 || alloc != keyword("f") && alloc != keyword("n") {
409 return nil, fmt.Errorf("malformed xref table")
410 }
411 x := int(start) + i
412 for cap(table) <= x {
413 table = append(table[:cap(table)], xref{})
414 }
415 if len(table) <= x {
416 table = table[:x+1]
417 }
418 if alloc == "n" && table[x].offset == 0 {
419 table[x] = xref{ptr: objptr{uint32(x), uint16(gen)}, offset: int64(off)}
420 }
421 }
422 }
423 return table, nil
424 }
425
426 func findLastLine(buf []byte, s string) int {
427 bs := []byte(s)
428 max := len(buf)
429 for {
430 i := bytes.LastIndex(buf[:max], bs)
431 if i <= 0 || i+len(bs) >= len(buf) {
432 return -1
433 }
434 if (buf[i-1] == '\n' || buf[i-1] == '\r') && (buf[i+len(bs)] == '\n' || buf[i+len(bs)] == '\r') {
435 return i
436 }
437 max = i
438 }
439 }
440
441 // A Value is a single PDF value, such as an integer, dictionary, or array.
442 // The zero Value is a PDF null (Kind() == Null, IsNull() = true).
443 type Value struct {
444 r *Reader
445 ptr objptr
446 data interface{}
447 }
448
449 // IsNull reports whether the value is a null. It is equivalent to Kind() == Null.
450 func (v Value) IsNull() bool {
451 return v.data == nil
452 }
453
454 // A ValueKind specifies the kind of data underlying a Value.
455 type ValueKind int
456
457 // The PDF value kinds.
458 const (
459 Null ValueKind = iota
460 Bool
461 Integer
462 Real
463 String
464 Name
465 Dict
466 Array
467 Stream
468 )
469
470 // Kind reports the kind of value underlying v.
471 func (v Value) Kind() ValueKind {
472 switch v.data.(type) {
473 default:
474 return Null
475 case bool:
476 return Bool
477 case int64:
478 return Integer
479 case float64:
480 return Real
481 case string:
482 return String
483 case name:
484 return Name
485 case dict:
486 return Dict
487 case array:
488 return Array
489 case stream:
490 return Stream
491 }
492 }
493
494 // String returns a textual representation of the value v.
495 // Note that String is not the accessor for values with Kind() == String.
496 // To access such values, see RawString, Text, and TextFromUTF16.
497 func (v Value) String() string {
498 return objfmt(v.data)
499 }
500
501 func objfmt(x interface{}) string {
502 switch x := x.(type) {
503 default:
504 return fmt.Sprint(x)
505 case string:
506 if isPDFDocEncoded(x) {
507 return strconv.Quote(pdfDocDecode(x))
508 }
509 if isUTF16(x) {
510 return strconv.Quote(utf16Decode(x[2:]))
511 }
512 return strconv.Quote(x)
513 case name:
514 return "/" + string(x)
515 case dict:
516 var keys []string
517 for k := range x {
518 keys = append(keys, string(k))
519 }
520 sort.Strings(keys)
521 var buf bytes.Buffer
522 buf.WriteString("<<")
523 for i, k := range keys {
524 elem := x[name(k)]
525 if i > 0 {
526 buf.WriteString(" ")
527 }
528 buf.WriteString("/")
529 buf.WriteString(k)
530 buf.WriteString(" ")
531 buf.WriteString(objfmt(elem))
532 }
533 buf.WriteString(">>")
534 return buf.String()
535
536 case array:
537 var buf bytes.Buffer
538 buf.WriteString("[")
539 for i, elem := range x {
540 if i > 0 {
541 buf.WriteString(" ")
542 }
543 buf.WriteString(objfmt(elem))
544 }
545 buf.WriteString("]")
546 return buf.String()
547
548 case stream:
549 return fmt.Sprintf("%v@%d", objfmt(x.hdr), x.offset)
550
551 case objptr:
552 return fmt.Sprintf("%d %d R", x.id, x.gen)
553
554 case objdef:
555 return fmt.Sprintf("{%d %d obj}%v", x.ptr.id, x.ptr.gen, objfmt(x.obj))
556 }
557 }
558
559 // Bool returns v's boolean value.
560 // If v.Kind() != Bool, Bool returns false.
561 func (v Value) Bool() bool {
562 x, ok := v.data.(bool)
563 if !ok {
564 return false
565 }
566 return x
567 }
568
569 // Int64 returns v's int64 value.
570 // If v.Kind() != Int64, Int64 returns 0.
571 func (v Value) Int64() int64 {
572 x, ok := v.data.(int64)
573 if !ok {
574 return 0
575 }
576 return x
577 }
578
579 // Float64 returns v's float64 value, converting from integer if necessary.
580 // If v.Kind() != Float64 and v.Kind() != Int64, Float64 returns 0.
581 func (v Value) Float64() float64 {
582 x, ok := v.data.(float64)
583 if !ok {
584 x, ok := v.data.(int64)
585 if ok {
586 return float64(x)
587 }
588 return 0
589 }
590 return x
591 }
592
593 // RawString returns v's string value.
594 // If v.Kind() != String, RawString returns the empty string.
595 func (v Value) RawString() string {
596 x, ok := v.data.(string)
597 if !ok {
598 return ""
599 }
600 return x
601 }
602
603 // Text returns v's string value interpreted as a ``text string'' (defined in the PDF spec)
604 // and converted to UTF-8.
605 // If v.Kind() != String, Text returns the empty string.
606 func (v Value) Text() string {
607 x, ok := v.data.(string)
608 if !ok {
609 return ""
610 }
611 if isPDFDocEncoded(x) {
612 return pdfDocDecode(x)
613 }
614 if isUTF16(x) {
615 return utf16Decode(x[2:])
616 }
617 return x
618 }
619
620 // TextFromUTF16 returns v's string value interpreted as big-endian UTF-16
621 // and then converted to UTF-8.
622 // If v.Kind() != String or if the data is not valid UTF-16, TextFromUTF16 returns
623 // the empty string.
624 func (v Value) TextFromUTF16() string {
625 x, ok := v.data.(string)
626 if !ok {
627 return ""
628 }
629 if len(x)%2 == 1 {
630 return ""
631 }
632 if x == "" {
633 return ""
634 }
635 return utf16Decode(x)
636 }
637
638 // Name returns v's name value.
639 // If v.Kind() != Name, Name returns the empty string.
640 // The returned name does not include the leading slash:
641 // if v corresponds to the name written using the syntax /Helvetica,
642 // Name() == "Helvetica".
643 func (v Value) Name() string {
644 x, ok := v.data.(name)
645 if !ok {
646 return ""
647 }
648 return string(x)
649 }
650
651 // Key returns the value associated with the given name key in the dictionary v.
652 // Like the result of the Name method, the key should not include a leading slash.
653 // If v is a stream, Key applies to the stream's header dictionary.
654 // If v.Kind() != Dict and v.Kind() != Stream, Key returns a null Value.
655 func (v Value) Key(key string) Value {
656 x, ok := v.data.(dict)
657 if !ok {
658 strm, ok := v.data.(stream)
659 if !ok {
660 return Value{}
661 }
662 x = strm.hdr
663 }
664 return v.r.resolve(v.ptr, x[name(key)])
665 }
666
667 // Keys returns a sorted list of the keys in the dictionary v.
668 // If v is a stream, Keys applies to the stream's header dictionary.
669 // If v.Kind() != Dict and v.Kind() != Stream, Keys returns nil.
670 func (v Value) Keys() []string {
671 x, ok := v.data.(dict)
672 if !ok {
673 strm, ok := v.data.(stream)
674 if !ok {
675 return nil
676 }
677 x = strm.hdr
678 }
679 keys := []string{} // not nil
680 for k := range x {
681 keys = append(keys, string(k))
682 }
683 sort.Strings(keys)
684 return keys
685 }
686
687 // Index returns the i'th element in the array v.
688 // If v.Kind() != Array or if i is outside the array bounds,
689 // Index returns a null Value.
690 func (v Value) Index(i int) Value {
691 x, ok := v.data.(array)
692 if !ok || i < 0 || i >= len(x) {
693 return Value{}
694 }
695 return v.r.resolve(v.ptr, x[i])
696 }
697
698 // Len returns the length of the array v.
699 // If v.Kind() != Array, Len returns 0.
700 func (v Value) Len() int {
701 x, ok := v.data.(array)
702 if !ok {
703 return 0
704 }
705 return len(x)
706 }
707
708 func (r *Reader) resolve(parent objptr, x interface{}) Value {
709 if ptr, ok := x.(objptr); ok {
710 if ptr.id >= uint32(len(r.xref)) {
711 return Value{}
712 }
713 xref := r.xref[ptr.id]
714 if xref.ptr != ptr || !xref.inStream && xref.offset == 0 {
715 return Value{}
716 }
717 var obj object
718 if xref.inStream {
719 strm := r.resolve(parent, xref.stream)
720 Search:
721 for {
722 if strm.Kind() != Stream {
723 panic("not a stream")
724 }
725 if strm.Key("Type").Name() != "ObjStm" {
726 panic("not an object stream")
727 }
728 n := int(strm.Key("N").Int64())
729 first := strm.Key("First").Int64()
730 if first == 0 {
731 panic("missing First")
732 }
733 b := newBuffer(strm.Reader(), 0)
734 b.allowEOF = true
735 for i := 0; i < n; i++ {
736 id, _ := b.readToken().(int64)
737 off, _ := b.readToken().(int64)
738 if uint32(id) == ptr.id {
739 b.seekForward(first + off)
740 x = b.readObject()
741 break Search
742 }
743 }
744 ext := strm.Key("Extends")
745 if ext.Kind() != Stream {
746 panic("cannot find object in stream")
747 }
748 strm = ext
749 }
750 } else {
751 b := newBuffer(io.NewSectionReader(r.f, xref.offset, r.end-xref.offset), xref.offset)
752 b.key = r.key
753 b.useAES = r.useAES
754 obj = b.readObject()
755 def, ok := obj.(objdef)
756 if !ok {
757 panic(fmt.Errorf("loading %v: found %T instead of objdef", ptr, obj))
758 //return Value{}
759 }
760 if def.ptr != ptr {
761 panic(fmt.Errorf("loading %v: found %v", ptr, def.ptr))
762 }
763 x = def.obj
764 }
765 parent = ptr
766 }
767
768 switch x := x.(type) {
769 case nil, bool, int64, float64, name, dict, array, stream:
770 return Value{r, parent, x}
771 case string:
772 return Value{r, parent, x}
773 default:
774 panic(fmt.Errorf("unexpected value type %T in resolve", x))
775 }
776 }
777
778 type errorReadCloser struct {
779 err error
780 }
781
782 func (e *errorReadCloser) Read([]byte) (int, error) {
783 return 0, e.err
784 }
785
786 func (e *errorReadCloser) Close() error {
787 return e.err
788 }
789
790 // Reader returns the data contained in the stream v.
791 // If v.Kind() != Stream, Reader returns a ReadCloser that
792 // responds to all reads with a ``stream not present'' error.
793 func (v Value) Reader() io.ReadCloser {
794 x, ok := v.data.(stream)
795 if !ok {
796 return &errorReadCloser{fmt.Errorf("stream not present")}
797 }
798 var rd io.Reader
799 rd = io.NewSectionReader(v.r.f, x.offset, v.Key("Length").Int64())
800 if v.r.key != nil {
801 rd = decryptStream(v.r.key, v.r.useAES, x.ptr, rd)
802 }
803 filter := v.Key("Filter")
804 param := v.Key("DecodeParms")
805 switch filter.Kind() {
806 default:
807 panic(fmt.Errorf("unsupported filter %v", filter))
808 case Null:
809 // ok
810 case Name:
811 rd = applyFilter(rd, filter.Name(), param)
812 case Array:
813 for i := 0; i < filter.Len(); i++ {
814 rd = applyFilter(rd, filter.Index(i).Name(), param.Index(i))
815 }
816 }
817
818 return ioutil.NopCloser(rd)
819 }
820
821 func applyFilter(rd io.Reader, name string, param Value) io.Reader {
822 switch name {
823 default:
824 panic("unknown filter " + name)
825 case "FlateDecode":
826 zr, err := zlib.NewReader(rd)
827 if err != nil {
828 panic(err)
829 }
830 pred := param.Key("Predictor")
831 if pred.Kind() == Null {
832 return zr
833 }
834 columns := param.Key("Columns").Int64()
835 switch pred.Int64() {
836 default:
837 fmt.Println("unknown predictor", pred)
838 panic("pred")
839 case 12:
840 return &pngUpReader{r: zr, hist: make([]byte, 1+columns), tmp: make([]byte, 1+columns)}
841 }
842 }
843 }
844
845 type pngUpReader struct {
846 r io.Reader
847 hist []byte
848 tmp []byte
849 pend []byte
850 }
851
852 func (r *pngUpReader) Read(b []byte) (int, error) {
853 n := 0
854 for len(b) > 0 {
855 if len(r.pend) > 0 {
856 m := copy(b, r.pend)
857 n += m
858 b = b[m:]
859 r.pend = r.pend[m:]
860 continue
861 }
862 _, err := io.ReadFull(r.r, r.tmp)
863 if err != nil {
864 return n, err
865 }
866 if r.tmp[0] != 2 {
867 return n, fmt.Errorf("malformed PNG-Up encoding")
868 }
869 for i, b := range r.tmp {
870 r.hist[i] += b
871 }
872 r.pend = r.hist[1:]
873 }
874 return n, nil
875 }
876
877 var passwordPad = []byte{
878 0x28, 0xBF, 0x4E, 0x5E, 0x4E, 0x75, 0x8A, 0x41, 0x64, 0x00, 0x4E, 0x56, 0xFF, 0xFA, 0x01, 0x08,
879 0x2E, 0x2E, 0x00, 0xB6, 0xD0, 0x68, 0x3E, 0x80, 0x2F, 0x0C, 0xA9, 0xFE, 0x64, 0x53, 0x69, 0x7A,
880 }
881
882 func (r *Reader) initEncrypt(password string) error {
883 // See PDF 32000-1:2008, §7.6.
884 encrypt, _ := r.resolve(objptr{}, r.trailer["Encrypt"]).data.(dict)
885 if encrypt["Filter"] != name("Standard") {
886 return fmt.Errorf("unsupported PDF: encryption filter %v", objfmt(encrypt["Filter"]))
887 }
888 n, _ := encrypt["Length"].(int64)
889 if n == 0 {
890 n = 40
891 }
892 if n%8 != 0 || n > 128 || n < 40 {
893 return fmt.Errorf("malformed PDF: %d-bit encryption key", n)
894 }
895 V, _ := encrypt["V"].(int64)
896 if V != 1 && V != 2 && (V != 4 || !okayV4(encrypt)) {
897 return fmt.Errorf("unsupported PDF: encryption version V=%d; %v", V, objfmt(encrypt))
898 }
899
900 ids, ok := r.trailer["ID"].(array)
901 if !ok || len(ids) < 1 {
902 return fmt.Errorf("malformed PDF: missing ID in trailer")
903 }
904 idstr, ok := ids[0].(string)
905 if !ok {
906 return fmt.Errorf("malformed PDF: missing ID in trailer")
907 }
908 ID := []byte(idstr)
909
910 R, _ := encrypt["R"].(int64)
911 if R < 2 {
912 return fmt.Errorf("malformed PDF: encryption revision R=%d", R)
913 }
914 if R > 4 {
915 return fmt.Errorf("unsupported PDF: encryption revision R=%d", R)
916 }
917 O, _ := encrypt["O"].(string)
918 U, _ := encrypt["U"].(string)
919 if len(O) != 32 || len(U) != 32 {
920 return fmt.Errorf("malformed PDF: missing O= or U= encryption parameters")
921 }
922 p, _ := encrypt["P"].(int64)
923 P := uint32(p)
924
925 // TODO: Password should be converted to Latin-1.
926 pw := []byte(password)
927 h := md5.New()
928 if len(pw) >= 32 {
929 h.Write(pw[:32])
930 } else {
931 h.Write(pw)
932 h.Write(passwordPad[:32-len(pw)])
933 }
934 h.Write([]byte(O))
935 h.Write([]byte{byte(P), byte(P >> 8), byte(P >> 16), byte(P >> 24)})
936 h.Write([]byte(ID))
937 key := h.Sum(nil)
938
939 if R >= 3 {
940 for i := 0; i < 50; i++ {
941 h.Reset()
942 h.Write(key[:n/8])
943 key = h.Sum(key[:0])
944 }
945 key = key[:n/8]
946 } else {
947 key = key[:40/8]
948 }
949
950 c, err := rc4.NewCipher(key)
951 if err != nil {
952 return fmt.Errorf("malformed PDF: invalid RC4 key: %v", err)
953 }
954
955 var u []byte
956 if R == 2 {
957 u = make([]byte, 32)
958 copy(u, passwordPad)
959 c.XORKeyStream(u, u)
960 } else {
961 h.Reset()
962 h.Write(passwordPad)
963 h.Write([]byte(ID))
964 u = h.Sum(nil)
965 c.XORKeyStream(u, u)
966
967 for i := 1; i <= 19; i++ {
968 key1 := make([]byte, len(key))
969 copy(key1, key)
970 for j := range key1 {
971 key1[j] ^= byte(i)
972 }
973 c, _ = rc4.NewCipher(key1)
974 c.XORKeyStream(u, u)
975 }
976 }
977
978 if !bytes.HasPrefix([]byte(U), u) {
979 return ErrInvalidPassword
980 }
981
982 r.key = key
983 r.useAES = V == 4
984
985 return nil
986 }
987
988 var ErrInvalidPassword = fmt.Errorf("encrypted PDF: invalid password")
989
990 func okayV4(encrypt dict) bool {
991 cf, ok := encrypt["CF"].(dict)
992 if !ok {
993 return false
994 }
995 stmf, ok := encrypt["StmF"].(name)
996 if !ok {
997 return false
998 }
999 strf, ok := encrypt["StrF"].(name)
1000 if !ok {
1001 return false
1002 }
1003 if stmf != strf {
1004 return false
1005 }
1006 cfparam, ok := cf[stmf].(dict)
1007 if cfparam["AuthEvent"] != nil && cfparam["AuthEvent"] != name("DocOpen") {
1008 return false
1009 }
1010 if cfparam["Length"] != nil && cfparam["Length"] != int64(16) {
1011 return false
1012 }
1013 if cfparam["CFM"] != name("AESV2") {
1014 return false
1015 }
1016 return true
1017 }
1018
1019 func cryptKey(key []byte, useAES bool, ptr objptr) []byte {
1020 h := md5.New()
1021 h.Write(key)
1022 h.Write([]byte{byte(ptr.id), byte(ptr.id >> 8), byte(ptr.id >> 16), byte(ptr.gen), byte(ptr.gen >> 8)})
1023 if useAES {
1024 h.Write([]byte("sAlT"))
1025 }
1026 return h.Sum(nil)
1027 }
1028
1029 func decryptString(key []byte, useAES bool, ptr objptr, x string) string {
1030 key = cryptKey(key, useAES, ptr)
1031 if useAES {
1032 panic("AES not implemented")
1033 } else {
1034 c, _ := rc4.NewCipher(key)
1035 data := []byte(x)
1036 c.XORKeyStream(data, data)
1037 x = string(data)
1038 }
1039 return x
1040 }
1041
1042 func decryptStream(key []byte, useAES bool, ptr objptr, rd io.Reader) io.Reader {
1043 key = cryptKey(key, useAES, ptr)
1044 if useAES {
1045 cb, err := aes.NewCipher(key)
1046 if err != nil {
1047 panic("AES: " + err.Error())
1048 }
1049 iv := make([]byte, 16)
1050 io.ReadFull(rd, iv)
1051 cbc := cipher.NewCBCDecrypter(cb, iv)
1052 rd = &cbcReader{cbc: cbc, rd: rd, buf: make([]byte, 16)}
1053 } else {
1054 c, _ := rc4.NewCipher(key)
1055 rd = &cipher.StreamReader{S: c, R: rd}
1056 }
1057 return rd
1058 }
1059
1060 type cbcReader struct {
1061 cbc cipher.BlockMode
1062 rd io.Reader
1063 buf []byte
1064 pend []byte
1065 }
1066
1067 func (r *cbcReader) Read(b []byte) (n int, err error) {
1068 if len(r.pend) == 0 {
1069 _, err = io.ReadFull(r.rd, r.buf)
1070 if err != nil {
1071 return 0, err
1072 }
1073 r.cbc.CryptBlocks(r.buf, r.buf)
1074 r.pend = r.buf
1075 }
1076 n = copy(b, r.pend)
1077 r.pend = r.pend[n:]
1078 return n, nil
1079 }