XRef.cc 22.9 KB
Newer Older
1
2
3
4
//========================================================================
//
// XRef.cc
//
5
// Copyright 1996-2003 Glyph & Cog, LLC
6
7
8
//
//========================================================================

Wilco Greven's avatar
Wilco Greven committed
9
10
11
#include <aconf.h>

#ifdef USE_GCC_PRAGMAS
12
13
14
#pragma implementation
#endif

15
#include <limits.h>
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
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <ctype.h>
#include "gmem.h"
#include "Object.h"
#include "Stream.h"
#include "Lexer.h"
#include "Parser.h"
#include "Dict.h"
#ifndef NO_DECRYPTION
#include "Decrypt.h"
#endif
#include "Error.h"
#include "ErrorCodes.h"
#include "XRef.h"

//------------------------------------------------------------------------

#define xrefSearchSize 1024	// read this many bytes at end of file
				//   to look for 'startxref'

#ifndef NO_DECRYPTION
//------------------------------------------------------------------------
// Permission bits
//------------------------------------------------------------------------

#define permPrint    (1<<2)
#define permChange   (1<<3)
#define permCopy     (1<<4)
#define permNotes    (1<<5)
#define defPermFlags 0xfffc
#endif

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
//------------------------------------------------------------------------
// ObjectStream
//------------------------------------------------------------------------

class ObjectStream {
public:

  // Create an object stream, using object number <objStrNum>,
  // generation 0.
  ObjectStream(XRef *xref, int objStrNumA);

  ~ObjectStream();

  // Return the object number of this object stream.
  int getObjStrNum() { return objStrNum; }

  // Get the <objIdx>th object from this stream, which should be
  // object number <objNum>, generation 0.
  Object *getObject(int objIdx, int objNum, Object *obj);

private:

  int objStrNum;		// object number of the object stream
  int nObjects;			// number of objects in the stream
  Object *objs;			// the objects (length = nObjects)
  int *objNums;			// the object numbers (length = nObjects)
};

ObjectStream::ObjectStream(XRef *xref, int objStrNumA) {
  Stream *str;
  Parser *parser;
  int *offsets;
  Object objStr, obj1, obj2;
  int first, i;

  objStrNum = objStrNumA;
  nObjects = 0;
  objs = NULL;
  objNums = NULL;

  if (!xref->fetch(objStrNum, 0, &objStr)->isStream()) {
    goto err1;
  }

  if (!objStr.streamGetDict()->lookup("N", &obj1)->isInt()) {
    obj1.free();
    goto err1;
  }
  nObjects = obj1.getInt();
  obj1.free();
Dirk Mueller's avatar
Dirk Mueller committed
100
  if (nObjects <= 0) {
101
102
103
104
105
106
107
108
109
    goto err1;
  }

  if (!objStr.streamGetDict()->lookup("First", &obj1)->isInt()) {
    obj1.free();
    goto err1;
  }
  first = obj1.getInt();
  obj1.free();
Dirk Mueller's avatar
Dirk Mueller committed
110
111
112
  if (first < 0) {
    goto err1;
  }
113

Dirk Mueller's avatar
Dirk Mueller committed
114
  if ((unsigned) nObjects >= INT_MAX / sizeof(int)) {
Dirk Mueller's avatar
Dirk Mueller committed
115
116
117
118
    error(-1, "Invalid 'nObjects'");
    goto err1;
  }
 
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
  objs = new Object[nObjects];
  objNums = (int *)gmalloc(nObjects * sizeof(int));
  offsets = (int *)gmalloc(nObjects * sizeof(int));

  // parse the header: object numbers and offsets
  objStr.streamReset();
  obj1.initNull();
  str = new EmbedStream(objStr.getStream(), &obj1, gTrue, first);
  parser = new Parser(xref, new Lexer(xref, str));
  for (i = 0; i < nObjects; ++i) {
    parser->getObj(&obj1);
    parser->getObj(&obj2);
    if (!obj1.isInt() || !obj2.isInt()) {
      obj1.free();
      obj2.free();
      delete parser;
      gfree(offsets);
      goto err1;
    }
    objNums[i] = obj1.getInt();
    offsets[i] = obj2.getInt();
    obj1.free();
    obj2.free();
Dirk Mueller's avatar
Dirk Mueller committed
142
143
144
145
146
147
    if (objNums[i] < 0 || offsets[i] < 0 ||
	(i > 0 && offsets[i] < offsets[i-1])) {
      delete parser;
      gfree(offsets);
      goto err1;
    }
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
  }
  while (str->getChar() != EOF) ;
  delete parser;

  // skip to the first object - this shouldn't be necessary because
  // the First key is supposed to be equal to offsets[0], but just in
  // case...
  for (i = first; i < offsets[0]; ++i) {
    objStr.getStream()->getChar();
  }

  // parse the objects
  for (i = 0; i < nObjects; ++i) {
    obj1.initNull();
    if (i == nObjects - 1) {
      str = new EmbedStream(objStr.getStream(), &obj1, gFalse, 0);
    } else {
      str = new EmbedStream(objStr.getStream(), &obj1, gTrue,
			    offsets[i+1] - offsets[i]);
    }
    parser = new Parser(xref, new Lexer(xref, str));
    parser->getObj(&objs[i]);
    while (str->getChar() != EOF) ;
    delete parser;
  }

  gfree(offsets);

 err1:
  objStr.free();
  return;
}

ObjectStream::~ObjectStream() {
  int i;

  if (objs) {
    for (i = 0; i < nObjects; ++i) {
      objs[i].free();
    }
    delete[] objs;
  }
  gfree(objNums);
}

Object *ObjectStream::getObject(int objIdx, int objNum, Object *obj) {
  if (objIdx < 0 || objIdx >= nObjects || objNum != objNums[objIdx]) {
    return obj->initNull();
  }
  return objs[objIdx].copy(obj);
}

200
201
202
203
204
205
//------------------------------------------------------------------------
// XRef
//------------------------------------------------------------------------

XRef::XRef(BaseStream *strA, GString *ownerPassword, GString *userPassword) {
  Guint pos;
206
  Object obj;
207
208
209
210
211
212
213

  ok = gTrue;
  errCode = errNone;
  size = 0;
  entries = NULL;
  streamEnds = NULL;
  streamEndsLen = 0;
214
  objStr = NULL;
215
216
217
218

  // read the trailer
  str = strA;
  start = str->getStart();
219
  pos = getStartXref();
220

221
222
  // if there was a problem with the 'startxref' position, try to
  // reconstruct the xref table
223
224
225
226
227
228
  if (pos == 0) {
    if (!(ok = constructXRef())) {
      errCode = errDamaged;
      return;
    }

229
  // read the xref table
230
231
232
233
234
235
236
237
238
239
240
241
242
  } else {
    while (readXRef(&pos)) ;

    // if there was a problem with the xref table,
    // try to reconstruct it
    if (!ok) {
      if (!(ok = constructXRef())) {
	errCode = errDamaged;
	return;
      }
    }
  }

243
244
245
246
247
248
249
250
251
252
253
254
255
256
  // get the root dictionary (catalog) object
  trailerDict.dictLookupNF("Root", &obj);
  if (obj.isRef()) {
    rootNum = obj.getRefNum();
    rootGen = obj.getRefGen();
    obj.free();
  } else {
    obj.free();
    if (!(ok = constructXRef())) {
      errCode = errDamaged;
      return;
    }
  }

257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
  // now set the trailer dictionary's xref pointer so we can fetch
  // indirect objects from it
  trailerDict.getDict()->setXRef(this);

  // check for encryption
#ifndef NO_DECRYPTION
  encrypted = gFalse;
#endif
  if (checkEncrypted(ownerPassword, userPassword)) {
    ok = gFalse;
    errCode = errEncrypted;
    return;
  }
}

XRef::~XRef() {
  gfree(entries);
  trailerDict.free();
  if (streamEnds) {
    gfree(streamEnds);
  }
278
279
280
  if (objStr) {
    delete objStr;
  }
281
282
}

283
284
// Read the 'startxref' position.
Guint XRef::getStartXref() {
285
286
  char buf[xrefSearchSize+1];
  char *p;
287
  int c, n, i;
288
289
290
291

  // read last xrefSearchSize bytes
  str->setPos(xrefSearchSize, -1);
  for (n = 0; n < xrefSearchSize; ++n) {
292
    if ((c = str->getChar()) == EOF) {
293
      break;
294
    }
295
296
297
298
299
300
    buf[n] = c;
  }
  buf[n] = '\0';

  // find startxref
  for (i = n - 9; i >= 0; --i) {
301
    if (!strncmp(&buf[i], "startxref", 9)) {
302
      break;
303
    }
304
  }
305
  if (i < 0) {
306
    return 0;
307
  }
308
  for (p = &buf[i+9]; isspace(*p); ++p) ;
309
310
311
312
313
314
315
316
317
318
319
320
321
  lastXRefPos = strToUnsigned(p);

  return lastXRefPos;
}

// Read one xref table section.  Also reads the associated trailer
// dictionary, and returns the prev pointer (if any).
GBool XRef::readXRef(Guint *pos) {
  Parser *parser;
  Object obj;
  GBool more;

  // start up a parser, parse one token
322
323
324
  obj.initNull();
  parser = new Parser(NULL,
	     new Lexer(NULL,
325
326
327
328
329
	       str->makeSubStream(start + *pos, gFalse, 0, &obj)));
  parser->getObj(&obj);

  // parse an old-style xref table
  if (obj.isCmd("xref")) {
330
    obj.free();
331
332
333
334
335
336
337
    more = readXRefTable(parser, pos);

  // parse an xref stream
  } else if (obj.isInt()) {
    obj.free();
    if (!parser->getObj(&obj)->isInt()) {
      goto err1;
338
339
    }
    obj.free();
340
341
342
343
344
345
346
347
348
349
    if (!parser->getObj(&obj)->isCmd("obj")) {
      goto err1;
    }
    obj.free();
    if (!parser->getObj(&obj)->isStream()) {
      goto err1;
    }
    more = readXRefStream(obj.getStream(), pos);
    obj.free();

350
  } else {
351
    goto err1;
352
  }
353

354
  delete parser;
355
  return more;
356

357
358
359
360
361
 err1:
  obj.free();
  delete parser;
  ok = gFalse;
  return gFalse;
362
363
}

364
365
GBool XRef::readXRefTable(Parser *parser, Guint *pos) {
  XRefEntry entry;
366
  GBool more;
367
368
369
  Object obj, obj2;
  Guint pos2;
  int first, n, newSize, i;
370
371

  while (1) {
372
373
374
    parser->getObj(&obj);
    if (obj.isCmd("trailer")) {
      obj.free();
375
376
      break;
    }
377
378
    if (!obj.isInt()) {
      goto err1;
379
    }
380
381
382
383
    first = obj.getInt();
    obj.free();
    if (!parser->getObj(&obj)->isInt()) {
      goto err1;
384
    }
385
386
    n = obj.getInt();
    obj.free();
Dirk Mueller's avatar
Dirk Mueller committed
387
388
389
    if (first < 0 || n < 0 || first + n < 0) {
      goto err1;
    }
390
    if (first + n > size) {
391
      for (newSize = size ? 2 * size : 1024;
Dirk Mueller's avatar
Dirk Mueller committed
392
	   first + n > newSize && newSize > 0;
393
	   newSize <<= 1) ;
Dirk Mueller's avatar
Dirk Mueller committed
394
395
396
      if (newSize < 0) {
	goto err1;
      }
Dirk Mueller's avatar
Dirk Mueller committed
397
      if ((unsigned) newSize >= INT_MAX / sizeof(XRefEntry)) {
Dirk Mueller's avatar
Dirk Mueller committed
398
399
400
401
        error(-1, "Invalid 'obj' parameters'");
        goto err1;
      }
 
402
403
404
      entries = (XRefEntry *)grealloc(entries, newSize * sizeof(XRefEntry));
      for (i = size; i < newSize; ++i) {
	entries[i].offset = 0xffffffff;
405
	entries[i].type = xrefEntryFree;
406
407
408
409
      }
      size = newSize;
    }
    for (i = first; i < first + n; ++i) {
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
      if (!parser->getObj(&obj)->isInt()) {
	goto err1;
      }
      entry.offset = (Guint)obj.getInt();
      obj.free();
      if (!parser->getObj(&obj)->isInt()) {
	goto err1;
      }
      entry.gen = obj.getInt();
      obj.free();
      parser->getObj(&obj);
      if (obj.isCmd("n")) {
	entry.type = xrefEntryUncompressed;
      } else if (obj.isCmd("f")) {
	entry.type = xrefEntryFree;
      } else {
	goto err1;
427
      }
428
      obj.free();
429
      if (entries[i].offset == 0xffffffff) {
430
	entries[i] = entry;
431
432
433
434
435
	// PDF files of patents from the IBM Intellectual Property
	// Network have a bug: the xref table claims to start at 1
	// instead of 0.
	if (i == 1 && first == 1 &&
	    entries[1].offset == 0 && entries[1].gen == 65535 &&
436
	    entries[1].type == xrefEntryFree) {
437
438
439
440
441
442
443
444
	  i = first = 0;
	  entries[0] = entries[1];
	  entries[1].offset = 0xffffffff;
	}
      }
    }
  }

445
446
  // read the trailer dictionary
  if (!parser->getObj(&obj)->isDict()) {
447
448
    goto err1;
  }
449
450

  // get the 'Prev' pointer
451
452
453
454
  obj.getDict()->lookupNF("Prev", &obj2);
  if (obj2.isInt()) {
    *pos = (Guint)obj2.getInt();
    more = gTrue;
455
456
457
458
459
  } else if (obj2.isRef()) {
    // certain buggy PDF generators generate "/Prev NNN 0 R" instead
    // of "/Prev NNN"
    *pos = (Guint)obj2.getRefNum();
    more = gTrue;
460
461
462
463
464
  } else {
    more = gFalse;
  }
  obj2.free();

465
466
467
468
469
470
471
  // save the first trailer dictionary
  if (trailerDict.isNone()) {
    obj.copy(&trailerDict);
  }

  // check for an 'XRefStm' key
  if (obj.getDict()->lookup("XRefStm", &obj2)->isInt()) {
Dirk Mueller's avatar
Dirk Mueller committed
472
    pos2 = (Guint)obj2.getInt();
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
    readXRef(&pos2);
    if (!ok) {
      goto err1;
    }
  }
  obj2.free();

  obj.free();
  return more;

 err1:
  obj.free();
  ok = gFalse;
  return gFalse;
}

GBool XRef::readXRefStream(Stream *xrefStr, Guint *pos) {
  Dict *dict;
  int w[3];
  GBool more;
  Object obj, obj2, idx;
  int newSize, first, n, i;

  dict = xrefStr->getDict();

  if (!dict->lookupNF("Size", &obj)->isInt()) {
    goto err1;
  }
  newSize = obj.getInt();
  obj.free();
Dirk Mueller's avatar
Dirk Mueller committed
503
504
505
  if (newSize < 0) {
    goto err1;
  }
506
  if (newSize > size) {
Dirk Mueller's avatar
Dirk Mueller committed
507
    if ((unsigned) newSize >= INT_MAX / sizeof(XRefEntry)) {
Dirk Mueller's avatar
Dirk Mueller committed
508
509
510
      error(-1, "Invalid 'size' parameter.");
      return gFalse;
    }
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
    entries = (XRefEntry *)grealloc(entries, newSize * sizeof(XRefEntry));
    for (i = size; i < newSize; ++i) {
      entries[i].offset = 0xffffffff;
      entries[i].type = xrefEntryFree;
    }
    size = newSize;
  }

  if (!dict->lookupNF("W", &obj)->isArray() ||
      obj.arrayGetLength() < 3) {
    goto err1;
  }
  for (i = 0; i < 3; ++i) {
    if (!obj.arrayGet(i, &obj2)->isInt()) {
      obj2.free();
      goto err1;
    }
    w[i] = obj2.getInt();
    obj2.free();
Dirk Mueller's avatar
Dirk Mueller committed
530
531
532
    if (w[i] < 0 || w[i] > 4) {
      goto err1;
    }
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
  }
  obj.free();

  xrefStr->reset();
  dict->lookupNF("Index", &idx);
  if (idx.isArray()) {
    for (i = 0; i+1 < idx.arrayGetLength(); i += 2) {
      if (!idx.arrayGet(i, &obj)->isInt()) {
	idx.free();
	goto err1;
      }
      first = obj.getInt();
      obj.free();
      if (!idx.arrayGet(i+1, &obj)->isInt()) {
	idx.free();
	goto err1;
      }
      n = obj.getInt();
      obj.free();
Dirk Mueller's avatar
Dirk Mueller committed
552
553
      if (first < 0 || n < 0 ||
	  !readXRefStreamSection(xrefStr, w, first, n)) {
554
555
556
557
558
	idx.free();
	goto err0;
      }
    }
  } else {
Dirk Mueller's avatar
Dirk Mueller committed
559
    if (!readXRefStreamSection(xrefStr, w, 0, newSize)) {
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
      idx.free();
      goto err0;
    }
  }
  idx.free();

  dict->lookupNF("Prev", &obj);
  if (obj.isInt()) {
    *pos = (Guint)obj.getInt();
    more = gTrue;
  } else {
    more = gFalse;
  }
  obj.free();
  if (trailerDict.isNone()) {
    trailerDict.initDict(dict);
  }

578
579
580
581
  return more;

 err1:
  obj.free();
582
 err0:
583
584
585
586
  ok = gFalse;
  return gFalse;
}

587
588
589
590
GBool XRef::readXRefStreamSection(Stream *xrefStr, int *w, int first, int n) {
  Guint offset;
  int type, gen, c, newSize, i, j;

Dirk Mueller's avatar
Dirk Mueller committed
591
592
593
  if (first + n < 0) {
    return gFalse;
  }
594
595
  if (first + n > size) {
    for (newSize = size ? 2 * size : 1024;
Dirk Mueller's avatar
Dirk Mueller committed
596
	 first + n > newSize && newSize > 0;
597
	 newSize <<= 1) ;
Dirk Mueller's avatar
Dirk Mueller committed
598
599
600
    if (newSize < 0) {
      return gFalse;
    }
Dirk Mueller's avatar
Dirk Mueller committed
601
    if ((unsigned) newSize >= INT_MAX / sizeof(XRefEntry)) {
Dirk Mueller's avatar
Dirk Mueller committed
602
603
604
      error(-1, "Invalid 'size' inside xref table.");
      return gFalse;
    }
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
    entries = (XRefEntry *)grealloc(entries, newSize * sizeof(XRefEntry));
    for (i = size; i < newSize; ++i) {
      entries[i].offset = 0xffffffff;
      entries[i].type = xrefEntryFree;
    }
    size = newSize;
  }
  for (i = first; i < first + n; ++i) {
    if (w[0] == 0) {
      type = 1;
    } else {
      for (type = 0, j = 0; j < w[0]; ++j) {
	if ((c = xrefStr->getChar()) == EOF) {
	  return gFalse;
	}
	type = (type << 8) + c;
      }
    }
    for (offset = 0, j = 0; j < w[1]; ++j) {
      if ((c = xrefStr->getChar()) == EOF) {
	return gFalse;
      }
      offset = (offset << 8) + c;
    }
    for (gen = 0, j = 0; j < w[2]; ++j) {
      if ((c = xrefStr->getChar()) == EOF) {
	return gFalse;
      }
      gen = (gen << 8) + c;
    }
Dirk Mueller's avatar
Dirk Mueller committed
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
    if (entries[i].offset == 0xffffffff) {
      switch (type) {
      case 0:
	entries[i].offset = offset;
	entries[i].gen = gen;
	entries[i].type = xrefEntryFree;
	break;
      case 1:
	entries[i].offset = offset;
	entries[i].gen = gen;
	entries[i].type = xrefEntryUncompressed;
	break;
      case 2:
	entries[i].offset = offset;
	entries[i].gen = gen;
	entries[i].type = xrefEntryCompressed;
	break;
      default:
	return gFalse;
      }
655
656
657
658
659
660
    }
  }

  return gTrue;
}

661
662
663
// Attempt to construct an xref table for a damaged file.
GBool XRef::constructXRef() {
  Parser *parser;
664
  Object newTrailerDict, obj;
665
666
667
668
669
670
671
672
673
  char buf[256];
  Guint pos;
  int num, gen;
  int newSize;
  int streamEndsSize;
  char *p;
  int i;
  GBool gotRoot;

674
675
676
677
  gfree(entries);
  size = 0;
  entries = NULL;

678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
  error(0, "PDF file is damaged - attempting to reconstruct xref table...");
  gotRoot = gFalse;
  streamEndsLen = streamEndsSize = 0;

  str->reset();
  while (1) {
    pos = str->getPos();
    if (!str->getLine(buf, 256)) {
      break;
    }
    p = buf;

    // got trailer dictionary
    if (!strncmp(p, "trailer", 7)) {
      obj.initNull();
      parser = new Parser(NULL,
		 new Lexer(NULL,
		   str->makeSubStream(start + pos + 7, gFalse, 0, &obj)));
696
697
698
      parser->getObj(&newTrailerDict);
      if (newTrailerDict.isDict()) {
	newTrailerDict.dictLookupNF("Root", &obj);
699
700
701
	if (obj.isRef()) {
	  rootNum = obj.getRefNum();
	  rootGen = obj.getRefGen();
702
703
704
705
	  if (!trailerDict.isNone()) {
	    trailerDict.free();
	  }
	  newTrailerDict.copy(&trailerDict);
706
707
708
709
	  gotRoot = gTrue;
	}
	obj.free();
      }
710
      newTrailerDict.free();
711
712
713
714
715
      delete parser;

    // look for object
    } else if (isdigit(*p)) {
      num = atoi(p);
Dirk Mueller's avatar
Dirk Mueller committed
716
      if (num > 0) {
717
718
	do {
	  ++p;
Dirk Mueller's avatar
Dirk Mueller committed
719
720
	} while (*p && isdigit(*p));
	if (isspace(*p)) {
721
722
	  do {
	    ++p;
Dirk Mueller's avatar
Dirk Mueller committed
723
724
725
	  } while (*p && isspace(*p));
	  if (isdigit(*p)) {
	    gen = atoi(p);
726
727
	    do {
	      ++p;
Dirk Mueller's avatar
Dirk Mueller committed
728
729
730
731
732
733
734
735
736
737
738
739
	    } while (*p && isdigit(*p));
	    if (isspace(*p)) {
	      do {
		++p;
	      } while (*p && isspace(*p));
	      if (!strncmp(p, "obj", 3)) {
		if (num >= size) {
		  newSize = (num + 1 + 255) & ~255;
		  if (newSize < 0) {
		    error(-1, "Bad object number");
		    return gFalse;
		  }
Dirk Mueller's avatar
Dirk Mueller committed
740
                  if ((unsigned) newSize >= INT_MAX / sizeof(XRefEntry)) {
Dirk Mueller's avatar
Dirk Mueller committed
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
                    error(-1, "Invalid 'obj' parameters.");
                    return gFalse;
                  }
		  entries = (XRefEntry *)
		      grealloc(entries, newSize * sizeof(XRefEntry));
		  for (i = size; i < newSize; ++i) {
		    entries[i].offset = 0xffffffff;
		    entries[i].type = xrefEntryFree;
		  }
		  size = newSize;
		}
		if (entries[num].type == xrefEntryFree ||
		    gen >= entries[num].gen) {
		  entries[num].offset = pos - start;
		  entries[num].gen = gen;
		  entries[num].type = xrefEntryUncompressed;
757
758
759
760
761
762
763
764
765
766
		}
	      }
	    }
	  }
	}
      }

    } else if (!strncmp(p, "endstream", 9)) {
      if (streamEndsLen == streamEndsSize) {
	streamEndsSize += 64;
Dirk Mueller's avatar
Dirk Mueller committed
767
        if ((unsigned) streamEndsSize >= INT_MAX / sizeof(int)) {
Dirk Mueller's avatar
Dirk Mueller committed
768
769
770
          error(-1, "Invalid 'endstream' parameter.");
          return gFalse;
        }
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
	streamEnds = (Guint *)grealloc(streamEnds,
				       streamEndsSize * sizeof(int));
      }
      streamEnds[streamEndsLen++] = pos;
    }
  }

  if (gotRoot)
    return gTrue;

  error(-1, "Couldn't find trailer dictionary");
  return gFalse;
}

#ifndef NO_DECRYPTION
GBool XRef::checkEncrypted(GString *ownerPassword, GString *userPassword) {
  Object encrypt, filterObj, versionObj, revisionObj, lengthObj;
  Object ownerKey, userKey, permissions, fileID, fileID1;
  GBool encrypted1;
  GBool ret;

792
793
  keyLength = 0;
  encVersion = encRevision = 0;
794
795
796
  ret = gFalse;

  permFlags = defPermFlags;
Wilco Greven's avatar
Wilco Greven committed
797
  ownerPasswordOk = gFalse;
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
  trailerDict.dictLookup("Encrypt", &encrypt);
  if ((encrypted1 = encrypt.isDict())) {
    ret = gTrue;
    encrypt.dictLookup("Filter", &filterObj);
    if (filterObj.isName("Standard")) {
      encrypt.dictLookup("V", &versionObj);
      encrypt.dictLookup("R", &revisionObj);
      encrypt.dictLookup("Length", &lengthObj);
      encrypt.dictLookup("O", &ownerKey);
      encrypt.dictLookup("U", &userKey);
      encrypt.dictLookup("P", &permissions);
      trailerDict.dictLookup("ID", &fileID);
      if (versionObj.isInt() &&
	  revisionObj.isInt() &&
	  ownerKey.isString() && ownerKey.getString()->getLength() == 32 &&
	  userKey.isString() && userKey.getString()->getLength() == 32 &&
	  permissions.isInt() &&
	  fileID.isArray()) {
	encVersion = versionObj.getInt();
	encRevision = revisionObj.getInt();
	if (lengthObj.isInt()) {
	  keyLength = lengthObj.getInt() / 8;
	} else {
	  keyLength = 5;
	}
823
824
825
        if (keyLength < 1) {
          keyLength = 1;
        }
826
827
828
  if (keyLength > 16) {
    keyLength = 16;
  }
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
	permFlags = permissions.getInt();
	if (encVersion >= 1 && encVersion <= 2 &&
	    encRevision >= 2 && encRevision <= 3) {
	  fileID.arrayGet(0, &fileID1);
	  if (fileID1.isString()) {
	    if (Decrypt::makeFileKey(encVersion, encRevision, keyLength,
				     ownerKey.getString(), userKey.getString(),
				     permFlags, fileID1.getString(),
				     ownerPassword, userPassword, fileKey,
				     &ownerPasswordOk)) {
	      if (ownerPassword && !ownerPasswordOk) {
		error(-1, "Incorrect owner password");
	      }
	      ret = gFalse;
	    } else {
	      error(-1, "Incorrect password");
	    }
	  } else {
	    error(-1, "Weird encryption info");
	  }
	  fileID1.free();
	} else {
	  error(-1, "Unsupported version/revision (%d/%d) of Standard security handler",
		encVersion, encRevision);
	}
      } else {
	error(-1, "Weird encryption info");
      }
      fileID.free();
      permissions.free();
      userKey.free();
      ownerKey.free();
      lengthObj.free();
      revisionObj.free();
      versionObj.free();
    } else {
      error(-1, "Unknown security handler '%s'",
	    filterObj.isName() ? filterObj.getName() : "???");
    }
    filterObj.free();
  }
  encrypt.free();

  // this flag has to be set *after* we read the O/U/P strings
  encrypted = encrypted1;

  return ret;
}
#else
GBool XRef::checkEncrypted(GString *ownerPassword, GString *userPassword) {
  Object obj;
  GBool encrypted;

  trailerDict.dictLookup("Encrypt", &obj);
  if ((encrypted = !obj.isNull())) {
    error(-1, "PDF file is encrypted and this version of the Xpdf tools");
    error(-1, "was built without decryption support.");
  }
  obj.free();
  return encrypted;
}
#endif

GBool XRef::okToPrint(GBool ignoreOwnerPW) {
#ifndef NO_DECRYPTION
894
895
  return (!ignoreOwnerPW && ownerPasswordOk) || (permFlags & permPrint);
#else
896
  return gTrue;
897
#endif
898
899
900
901
}

GBool XRef::okToChange(GBool ignoreOwnerPW) {
#ifndef NO_DECRYPTION
902
903
  return (!ignoreOwnerPW && ownerPasswordOk) || (permFlags & permChange);
#else
904
  return gTrue;
905
#endif
906
907
908
909
}

GBool XRef::okToCopy(GBool ignoreOwnerPW) {
#ifndef NO_DECRYPTION
910
911
  return (!ignoreOwnerPW && ownerPasswordOk) || (permFlags & permCopy);
#else
912
  return gTrue;
913
#endif
914
915
916
917
}

GBool XRef::okToAddNotes(GBool ignoreOwnerPW) {
#ifndef NO_DECRYPTION
918
919
  return (!ignoreOwnerPW && ownerPasswordOk) || (permFlags & permNotes);
#else
920
  return gTrue;
921
#endif
922
923
924
925
926
927
928
929
930
}

Object *XRef::fetch(int num, int gen, Object *obj) {
  XRefEntry *e;
  Parser *parser;
  Object obj1, obj2, obj3;

  // check for bogus ref - this can happen in corrupted PDF files
  if (num < 0 || num >= size) {
931
    goto err;
932
933
934
  }

  e = &entries[num];
935
936
937
938
939
940
  switch (e->type) {

  case xrefEntryUncompressed:
    if (e->gen != gen) {
      goto err;
    }
941
942
943
944
945
946
947
    obj1.initNull();
    parser = new Parser(this,
	       new Lexer(this,
		 str->makeSubStream(start + e->offset, gFalse, 0, &obj1)));
    parser->getObj(&obj1);
    parser->getObj(&obj2);
    parser->getObj(&obj3);
948
949
950
951
952
    if (!obj1.isInt() || obj1.getInt() != num ||
	!obj2.isInt() || obj2.getInt() != gen ||
	!obj3.isCmd("obj")) {
      goto err;
    }
953
#ifndef NO_DECRYPTION
954
955
    parser->getObj(obj, encrypted ? fileKey : (Guchar *)NULL, keyLength,
		   num, gen);
956
#else
957
    parser->getObj(obj);
958
959
960
961
962
#endif
    obj1.free();
    obj2.free();
    obj3.free();
    delete parser;
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
    break;

  case xrefEntryCompressed:
    if (gen != 0) {
      goto err;
    }
    if (!objStr || objStr->getObjStrNum() != (int)e->offset) {
      if (objStr) {
	delete objStr;
      }
      objStr = new ObjectStream(this, e->offset);
    }
    objStr->getObject(e->gen, num, obj);
    break;

  default:
    goto err;
980
  }
981

982
  return obj;
983
984
985

 err:
  return obj->initNull();
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
}

Object *XRef::getDocInfo(Object *obj) {
  return trailerDict.dictLookup("Info", obj);
}

// Added for the pdftex project.
Object *XRef::getDocInfoNF(Object *obj) {
  return trailerDict.dictLookupNF("Info", obj);
}

GBool XRef::getStreamEnd(Guint streamStart, Guint *streamEnd) {
  int a, b, m;

  if (streamEndsLen == 0 ||
      streamStart > streamEnds[streamEndsLen - 1]) {
    return gFalse;
  }

  a = -1;
  b = streamEndsLen - 1;
  // invariant: streamEnds[a] < streamStart <= streamEnds[b]
  while (b - a > 1) {
    m = (a + b) / 2;
    if (streamStart <= streamEnds[m]) {
      b = m;
    } else {
      a = m;
    }
  }
  *streamEnd = streamEnds[b];
  return gTrue;
}

Guint XRef::strToUnsigned(char *s) {
  Guint x;
  char *p;
  int i;

  x = 0;
  for (p = s, i = 0; *p && isdigit(*p) && i < 10; ++p, ++i) {
    x = 10 * x + (*p - '0');
  }
  return x;
}