home *** CD-ROM | disk | FTP | other *** search
- //========================================================================
- //
- // XRef.cc
- //
- // Copyright 1996 Derek B. Noonburg
- //
- //========================================================================
- //
- // Ported to EPOC by Sander van der Wal
- //
- // $Log: XRef.cpp $
- // Revision 1.2 2000-09-17 13:38:20+02 svdwal
- // Ported
- //
-
- #ifdef __GNUC__
- #pragma implementation
- #endif
-
- #ifndef __E32DEF_H__
- #include <e32def.h>
- #endif
-
- // --o C library
- #include <stdlib.h>
- #include <ctype.h>
-
- // --o GooLib
- #include "gmem.h"
-
- // --o PdfLib
- #include "Object.h"
- #include "Stream.h"
- #include "Lexer.h"
- #include "Parser.h"
- #include "Dict.h"
- #include "Error.h"
- #include "XRef.h"
- #include "md5.h"
- #include "rc4.h"
-
- // --o Pdf impl
- #include "PDFGlobal.h"
- #include "Pdf.rsg"
-
-
- //------------------------------------------------------------------------
-
- #define xrefSearchSize 1024 // read this many bytes at end of file
- // to look for 'startxref'
-
- //------------------------------------------------------------------------
- // The global xref table
- //------------------------------------------------------------------------
-
- #ifdef __SYMBIAN32__
-
- // Initialise global data
- XRefGlobal::XRefGlobal()
- {
- xref = 0;
- }
-
- #else
-
- XRef *xref = NULL;
-
- #endif
-
- //------------------------------------------------------------------------
- // XRef
- //------------------------------------------------------------------------
-
- void XRef::ConstructL(FileStream* str)
- {
- XRef *oldXref;
- int pos=0;
- int i;
-
- ok = gTrue;
- encrypted = gFalse;
-
- // get rid of old xref (otherwise it will try to fetch the Root object
- // in the new document, using the old xref)
- oldXref = Global().XRef.xref;
- Global().XRef.xref = 0;
-
- // read the trailer
- file = str->getFile();
- start = str->getStart();
- TRAPD(err, pos = readTrailerL(str));
- if (err != KErrNone) {
- ok = gFalse;
- Global().XRef.xref = oldXref;
- User::Leave(err);
- }
-
- // if there was a problem with the trailer,
- // try to reconstruct the xref table
- if (pos == 0) {
- TRAP(err, ok = constructXRefL(str));
- if (err != KErrNone || !ok) {
- ok = gFalse;
- Global().XRef.xref = oldXref;
- if (err != KErrNone)
- User::Leave(err);
- return;
- }
-
- // trailer is ok - read the xref table
- }
- else {
- ok = gFalse;
- entries = (XRefEntry *)User::Alloc(size * sizeof(XRefEntry));
- if (!entries) {
- ok = gFalse;
- Global().XRef.xref = oldXref;
- User::Leave(KErrNoMemory);
- }
- for (i = 0; i < size; ++i) {
- entries[i].offset = -1;
- entries[i].used = gFalse;
- }
- TRAP(err, while (readXRefL(str, &pos))) ;
- if (err != KErrNone) {
- ok = gFalse;
- Global().XRef.xref = oldXref;
- User::Leave(KErrNoMemory);
- }
-
- // if there was a problem with the xref table,
- // try to reconstruct it
- if (!ok) {
- User::Free(entries);
- entries = 0;
- size = 0;
- TRAP(err, ok = constructXRefL(str));
- if (err != KErrNone || !ok) {
- Global().XRef.xref = oldXref;
- if (err != KErrNone)
- User::Leave(err);
- return;
- }
- }
- }
-
- // set up new xref table
- Global().XRef.xref = this;
-
- // check for encryption
- m_okToPrint = gTrue;
- m_okToCopy = gTrue;
- m_okToChange = gTrue;
- m_okToAddNotes = gTrue;
- if (checkEncryptedL()) {
- if (setupDecryptionL() == gFalse) {
- ok = gFalse;
- Global().XRef.xref = oldXref;
- return;
- }
- }
- }
-
- XRef::~XRef() {
- User::Free(entries);
- trailerDict.free();
- encryptionDict.free();
- delete encryptionKey;
- }
-
- // Read startxref position, xref table size, and root. Returns
- // first xref position.
- int XRef::readTrailerL(FileStream *str) {
- char buf[xrefSearchSize+1];
- int n, pos, pos1;
- char *p;
- int c;
- int i;
-
- // read last xrefSearchSize bytes
- str->setPos(-xrefSearchSize);
- for (n = 0; n < xrefSearchSize; ++n) {
- if ((c = str->getChar()) == EOF)
- break;
- buf[n] = c;
- }
- buf[n] = '\0';
-
- // find startxref
- for (i = n - 9; i >= 0; --i) {
- if (!strncmp(&buf[i], "startxref", 9))
- break;
- }
- if (i < 0)
- return 0;
- for (p = &buf[i+9]; isspace(*p); ++p) ;
- pos = atoi(p);
-
- // find trailer dict by looking after first xref table
- // (NB: we can't just use the trailer dict at the end of the file --
- // this won't work for linearized files.)
- str->setPos(start + pos);
- for (i = 0; i < 4; ++i)
- buf[i] = str->getChar();
- if (strncmp(buf, "xref", 4))
- return 0;
- pos1 = pos + 4;
- for (;;) {
- str->setPos(start + pos1);
- for (i = 0; i < 35; ++i) {
- if ((c = str->getChar()) == EOF)
- return 0;
- buf[i] = c;
- }
- if (!strncmp(buf, "trailer", 7))
- break;
- p = buf;
- while (isspace(*p)) ++p;
- while ('0' <= *p && *p <= '9') ++p;
- while (isspace(*p)) ++p;
- n = atoi(p);
- while ('0' <= *p && *p <= '9') ++p;
- while (isspace(*p)) ++p;
- if (p == buf)
- return 0;
- pos1 += (p - buf) + n * 20;
- }
- pos1 += 7;
-
- // read trailer dict
- RAutoObject obj;
- obj.initNull();
-
- FileStream* stream = new(ELeave) FileStream(file, start + pos1, -1, &obj);
- CleanupStack::PushL(stream);
-
- Lexer* lexer = new(ELeave) Lexer(stream);
- CleanupStack::Pop(); // stream
- CleanupStack::PushL(lexer);
- lexer->ConstructL();
-
- Parser *parser = new(ELeave) Parser(lexer);
- CleanupStack::Pop(); // lexer
- CleanupStack::PushL(parser);
- parser->ConstructL();
-
- parser->getObjL(&trailerDict);
- if (trailerDict.isDict()) {
- trailerDict.dictLookupNFL("Size", &obj);
- if (obj.isInt())
- size = obj.getInt();
- else
- pos = 0;
- obj.free();
- trailerDict.dictLookupNFL("Root", &obj);
- if (obj.isRef()) {
- rootNum = obj.getRefNum();
- rootGen = obj.getRefGen();
- } else {
- pos = 0;
- }
- obj.free();
- } else {
- pos = 0;
- }
- CleanupStack::PopAndDestroy(); // delete parser;
-
- // return first xref position
- return pos;
- }
-
- // Read an xref table and the prev pointer from the trailer.
- GBool XRef::readXRefL(FileStream *str, int *pos) {
- char s[20];
- GBool more;
- int first, n, i, j;
- int c;
-
- // seek to xref in stream
- str->setPos(start + *pos);
-
- // make sure it's an xref table
- while ((c = str->getChar()) != EOF && isspace(c)) ;
- s[0] = (char)c;
- s[1] = (char)str->getChar();
- s[2] = (char)str->getChar();
- s[3] = (char)str->getChar();
- if (!(s[0] == 'x' && s[1] == 'r' && s[2] == 'e' && s[3] == 'f'))
- return ok = gFalse;
-
- // read xref
- for (;;) {
- while ((c = str->lookChar()) != EOF && isspace(c))
- str->getChar();
- if (c == 't')
- break;
- for (i = 0; (c = str->getChar()) != EOF && isdigit(c) && i < 20; ++i)
- s[i] = (char)c;
- if (i == 0)
- return ok = gFalse;
- s[i] = '\0';
- first = atoi(s);
- while ((c = str->lookChar()) != EOF && isspace(c))
- str->getChar();
- for (i = 0; (c = str->getChar()) != EOF && isdigit(c) && i < 20; ++i)
- s[i] = (char)c;
- if (i == 0)
- return ok = gFalse;
- s[i] = '\0';
- n = atoi(s);
- while ((c = str->lookChar()) != EOF && isspace(c))
- str->getChar();
- for (i = first; i < first + n; ++i) {
- for (j = 0; j < 20; ++j) {
- if ((c = str->getChar()) == EOF)
- return ok = gFalse;
- s[j] = (char)c;
- }
- if (entries[i].offset < 0) {
- s[10] = '\0';
- entries[i].offset = atoi(s);
- s[16] = '\0';
- entries[i].gen = atoi(&s[11]);
- if (s[17] == 'n')
- entries[i].used = gTrue;
- else if (s[17] == 'f')
- entries[i].used = gFalse;
- else
- return ok = gFalse;
- }
- }
- }
-
- ok = gFalse; // on leaves, it is not ok
-
- // read prev pointer from trailer dictionary
- RAutoObject obj, obj2;
- obj.initNull();
-
- FileStream* stream = new(ELeave) FileStream(file, str->getPos(), -1, &obj);
- CleanupStack::PushL(stream);
-
- Lexer* lexer = new(ELeave) Lexer(stream);
- CleanupStack::Pop(); // stream
- CleanupStack::PushL(lexer);
- lexer->ConstructL();
-
- Parser *parser = new(ELeave) Parser(lexer);
- CleanupStack::Pop(); // lexer
- CleanupStack::PushL(parser);
- parser->ConstructL();
-
- parser->getObjL(&obj);
- if (!obj.isCmd("trailer"))
- goto err1;
- obj.free();
- parser->getObjL(&obj);
- if (!obj.isDict())
- goto err1;
- obj.getDict()->lookupNFL("Prev", &obj2);
- if (obj2.isInt()) {
- *pos = obj2.getInt();
- more = gTrue;
- } else {
- more = gFalse;
- }
- obj.free();
- obj2.free();
-
- CleanupStack::PopAndDestroy(); // delete parser;
- ok = gTrue;
- return more;
-
- err1:
- obj.free();
- ok = gFalse;
- return gFalse;
- }
-
- // Attempt to construct an xref table for a damaged file.
- GBool XRef::constructXRefL(FileStream *str) {
- char buf[256];
- int pos;
- int newSize;
- char *p;
- GBool gotRoot;
-
- error(0, R_PDF_FILE_IS_DAMAGED___ATTEMPTING_TO_RECONSTRUCT_XREF_TABLE___);
- gotRoot = gFalse;
-
- str->reset();
- for (;;) {
- pos = str->getPos();
- if (!str->getLine(buf, 256))
- break;
- p = buf;
-
- // got trailer dictionary
- if (!strncmp(p, "trailer", 7)) {
- RAutoObject obj;
- obj.initNull();
-
- FileStream* stream = new(ELeave) FileStream(file, start + pos + 8, -1, &obj);
- CleanupStack::PushL(stream);
-
- Lexer* lexer = new(ELeave) Lexer(stream);
- CleanupStack::Pop(); // stream
- CleanupStack::PushL(lexer);
- lexer->ConstructL();
-
- Parser *parser = new(ELeave) Parser(lexer);
- CleanupStack::Pop(); // lexer
- CleanupStack::PushL(parser);
- parser->ConstructL();
-
- if (!trailerDict.isNone())
- trailerDict.free();
- parser->getObjL(&trailerDict);
- if (trailerDict.isDict()) {
- trailerDict.dictLookupNFL("Root", &obj);
- if (obj.isRef()) {
- rootNum = obj.getRefNum();
- rootGen = obj.getRefGen();
- gotRoot = gTrue;
- }
- obj.free();
- } else {
- pos = 0;
- }
- CleanupStack::PopAndDestroy(); // delete parser;
-
- // look for object
- }
- else if (isdigit(*p)) {
- int num = atoi(p);
- do {
- ++p;
- } while (*p && isdigit(*p));
- if (isspace(*p)) {
- do {
- ++p;
- } while (*p && isspace(*p));
- if (isdigit(*p)) {
- int gen = atoi(p);
- do {
- ++p;
- } 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;
- entries = (XRefEntry *) User::ReAllocL(entries, newSize * sizeof(XRefEntry));
- for (int i = size; i < newSize; ++i) {
- entries[i].offset = -1;
- entries[i].used = gFalse;
- }
- size = newSize;
- }
- if (!entries[num].used || gen >= entries[num].gen) {
- entries[num].offset = pos - start;
- entries[num].gen = gen;
- entries[num].used = gTrue;
- }
- }
- }
- }
- }
- }
- }
-
- if (gotRoot)
- return gTrue;
-
- error(-1, R_COULDN_T_FIND_TRAILER_DICTIONARY);
- return gFalse;
- }
-
- GBool XRef::checkEncryptedL() {
- trailerDict.dictLookupL("Encrypt", &encryptionDict);
- encrypted = encryptionDict.isDict();
- if (encrypted)
- encryptionKey = GString::NewL();
- return encrypted;
- }
-
- GBool XRef::okToPrint() {
- return m_okToPrint;
- }
-
- GBool XRef::okToCopy() {
- return m_okToCopy;
- }
-
- GBool XRef::okToChange() {
- return m_okToChange;
- }
-
- GBool XRef::okToAddNotes() {
- return m_okToAddNotes;
- }
-
- Object *XRef::fetchL(int num, int gen, Object *obj) {
- XRefEntry *e;
- RAutoObject obj1, obj2, obj3;
-
- // check for bogus ref - this can happen in corrupted PDF files
- if (num < 0 || num >= size) {
- obj->initNull();
- return obj;
- }
-
- e = &entries[num];
- if (e->gen == gen && e->offset >= 0) {
- obj1.initNull();
-
- FileStream* stream = new(ELeave) FileStream(file, start + e->offset, -1, &obj1);
- CleanupStack::PushL(stream);
-
- Lexer* lexer = new(ELeave) Lexer(stream);
- CleanupStack::Pop(); // stream
- CleanupStack::PushL(lexer);
- lexer->ConstructL();
-
- Parser *parser = new(ELeave) Parser(lexer);
- CleanupStack::Pop(); // lexer
- CleanupStack::PushL(parser);
- parser->ConstructL();
-
- parser->getObjL(&obj1);
- parser->getObjL(&obj2);
- parser->getObjL(&obj3);
- if (obj1.isInt() && obj1.getInt() == num &&
- obj2.isInt() && obj2.getInt() == gen &&
- obj3.isCmd("obj")) {
- if (encrypted) {
- parser->getEncryptedObjL(obj, num, gen);
- } else {
- parser->getObjL(obj);
- }
- } else {
- obj->initNull();
- }
- obj1.free();
- obj2.free();
- obj3.free();
- CleanupStack::PopAndDestroy(); // delete parser;
- } else {
- obj->initNull();
- }
- return obj;
- }
-
- Object *XRef::getDocInfoL(Object *obj) {
- return trailerDict.dictLookupL("Info", obj);
- }
-
-
- GBool XRef::setupDecryptionL() {
- RAutoObject obj;
- //GBool encrypted;
- //GBool passwordOk;
- GString* userPassword;
-
- // check filter
- encryptionDict.dictLookupNFL("Filter", &obj);
- if (!obj.isName()) {
- error(-1, R_NO_FILTER_SPECIFIED__ASSUME_STANDARD_FILTER);
- } else if (strcmp(obj.getName(), "Standard") != 0) {
- error(-1, R_FILE_IS_ENCRYPTED_WITH_A_NON_STANDARD_FILTER);
- obj.free();
- return gFalse;
- }
- obj.free();
-
- // check for no user password
- userPassword = GString::NewLC();
- if (checkUserPasswordL(userPassword) == gFalse) {
- // ask for user password ... check with user password
- error(-1, R_PDF_FILE_IS_ENCRYPTED_WITH_A_USER_PASSWORD);
- CleanupStack::PopAndDestroy(); // userPassword
- return gFalse;
- }
- CleanupStack::PopAndDestroy(); // userPassword
- userPassword = 0;
-
- // set permissions
- encryptionDict.dictLookupNFL("P", &obj);
- if (obj.isNull() || !obj.isInt()) {
- error(-1, R_NO_PERMISSIONS_SPECIFIED);
- return gFalse;
- }
- int Permissions = obj.getInt();
- obj.free();
- m_okToPrint = Permissions & 0x04 ? gTrue : gFalse;
- m_okToChange = Permissions & 0x08 ? gTrue : gFalse;
- m_okToCopy = Permissions & 0x10 ? gTrue : gFalse;
- m_okToAddNotes = Permissions & 0x20 ? gTrue : gFalse;
-
- return gTrue;
- }
-
- GBool
- XRef::checkUserPasswordL(GString *userPassword)
- {
- GString* preparedPassword = GString::NewLC();
- RC4KEY rc4Key;
- RAutoObject obj;
- char localPassword[32];
-
- if (preparePasswordL(userPassword, preparedPassword) == gFalse) {
- CleanupStack::PopAndDestroy(); // preparedPassword
- return gFalse;
- }
- if (MakeEncryptionKeyL(preparedPassword, encryptionKey) == gFalse) {
- CleanupStack::PopAndDestroy(); // preparedPassword
- return gFalse;
- }
- // get the User password
- encryptionDict.dictLookupNFL("U", &obj);
- if (obj.isNull() || !obj.isString()) {
- error(-1, R_NO_USER_PASSWORD_SPECIFIED);
- CleanupStack::PopAndDestroy(); // preparedPassword
- return gFalse;
- }
- Mem::Copy(localPassword, obj.getString()->getCString(), 32);
- obj.free();
- // prepary RC4 key
- rc4ExpandKey(&rc4Key, (unsigned char *)encryptionKey->getCString(), 5);
- // encrypt User password
- rc4Crypt(&rc4Key, (unsigned char *)&localPassword[0], 32);
- // compare preparedPassword and decryptedPassword
- for (int i=0; i<32; i++) {
- if (localPassword[i] != preparedPassword->getChar(i)) {
- // not equal
- CleanupStack::PopAndDestroy(); // preparedPassword
- return gFalse;
- }
- }
-
- CleanupStack::PopAndDestroy(); // preparedPassword
- // password OK
- return gTrue;
- }
-
- GBool
- XRef::MakeEncryptionKeyL(GString *password, GString *encryptionKey)
- {
- MD5 context;
- RAutoObject obj, obj1;
- unsigned char Pkey[4];
-
- context.update((unsigned char *)password->getCString(), 32);
- // others owner key
- encryptionDict.dictLookupNFL("O", &obj);
- if (obj.isNull() || !obj.isString()) {
- error(-1, R_NO_OWNER_PASSWORD_SPECIFIED);
- return gFalse;
- }
- context.update((unsigned char *)obj.getString()->getCString(), 32);
- obj.free();
- // permissions
- encryptionDict.dictLookupNFL("P", &obj);
- if (obj.isNull() || !obj.isInt()) {
- error(-1, R_NO_PERMISSIONS_SPECIFIED);
- return gFalse;
- }
- int Permissions = obj.getInt();
- Pkey[0] = Guchar( Permissions & 0xff);
- Pkey[1] = Guchar((Permissions >> 8 ) & 0xff);
- Pkey[2] = Guchar((Permissions >> 16) & 0xff);
- Pkey[3] = Guchar((Permissions >> 24) & 0xff);
- context.update(&Pkey[0], 4);
- obj.free();
- // first element from ID
- trailerDict.dictLookupNFL("ID", &obj);
- if (obj.isNull() || !obj.isArray()) {
- error(-1, R_NO_ID_SPECIFIED);
- return gFalse;
- }
- obj.arrayGetL(0, &obj1);
- if (obj1.isNull() || !obj1.isString()) {
- error(-1, R_NO_ID_ELEMENTS_SPECIFIED);
- return gFalse;
- }
- context.update((unsigned char *)(obj1.getString()->getCString()), (int)(obj1.getString()->getLength()));
- obj1.free();
- obj.free();
- context.finalize();
- encryptionKey->clearL();
- char *p = (char *)context.raw_digestL();
- CleanupStack::PushL(p);
- encryptionKey->appendL(p,5);
- CleanupStack::PopAndDestroy(); // delete p;
- return gTrue;
- }
-
- GBool
- XRef::preparePasswordL(GString *password, GString *preparedPassword)
- {
- static const char acFill[32] = {'\x28', '\xbf', '\x4e', '\x5e', '\x4e', '\x75', '\x8a', '\x41',
- '\x64', '\x00', '\x4e', '\x56', '\xff', '\xfa', '\x01', '\x08',
- '\x2e', '\x2e', '\x00', '\xb6', '\xd0', '\x68', '\x3e', '\x80',
- '\x2f', '\x0c', '\xa9', '\xfe', '\x64', '\x53', '\x69', '\x7a'};
- preparedPassword->clearL();
- preparedPassword->appendL(password);
- preparedPassword->appendL(&acFill[0], 32);
- return gTrue;
- }
-