"git@code.vereign.com:code/vcl.git" did not exist on "466e26bffd55729c76b4cb27054f12404cf5d8d1"
Newer
Older
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
else if (remainder === 1) {
k = calculateSHA384(e, 0, e.length);
}
else if (remainder === 2) {
k = calculateSHA512(e, 0, e.length);
}
i++;
}
return k.subarray(0, 32);
}
function PDF20() {
}
function compareByteArrays(array1, array2) {
if (array1.length !== array2.length) {
return false;
}
for (var i = 0; i < array1.length; i++) {
if (array1[i] !== array2[i]) {
return false;
}
}
return true;
}
PDF20.prototype = {
hash: function PDF20_hash(password, concatBytes, userBytes) {
return calculatePDF20Hash(password, concatBytes, userBytes);
},
checkOwnerPassword: function PDF20_checkOwnerPassword(password,
ownerValidationSalt,
userBytes,
ownerPassword) {
var hashData = new Uint8Array(password.length + 56);
hashData.set(password, 0);
hashData.set(ownerValidationSalt, password.length);
hashData.set(userBytes, password.length + ownerValidationSalt.length);
var result = calculatePDF20Hash(password, hashData, userBytes);
return compareByteArrays(result, ownerPassword);
},
checkUserPassword: function PDF20_checkUserPassword(password,
userValidationSalt,
userPassword) {
var hashData = new Uint8Array(password.length + 8);
hashData.set(password, 0);
hashData.set(userValidationSalt, password.length);
var result = calculatePDF20Hash(password, hashData, []);
return compareByteArrays(result, userPassword);
},
getOwnerKey: function PDF20_getOwnerKey(password, ownerKeySalt, userBytes,
ownerEncryption) {
var hashData = new Uint8Array(password.length + 56);
hashData.set(password, 0);
hashData.set(ownerKeySalt, password.length);
hashData.set(userBytes, password.length + ownerKeySalt.length);
var key = calculatePDF20Hash(password, hashData, userBytes);
var cipher = new AES256Cipher(key);
return cipher.decryptBlock(ownerEncryption,
false,
new Uint8Array(16));
},
getUserKey: function PDF20_getUserKey(password, userKeySalt,
userEncryption) {
var hashData = new Uint8Array(password.length + 8);
hashData.set(password, 0);
hashData.set(userKeySalt, password.length);
//key is the decryption key for the UE string
var key = calculatePDF20Hash(password, hashData, []);
var cipher = new AES256Cipher(key);
return cipher.decryptBlock(userEncryption,
false,
new Uint8Array(16));
}
};
return PDF20;
})();
var CipherTransform = (function CipherTransformClosure() {
function CipherTransform(stringCipherConstructor, streamCipherConstructor) {
this.stringCipherConstructor = stringCipherConstructor;
this.streamCipherConstructor = streamCipherConstructor;
}
CipherTransform.prototype = {
createStream: function CipherTransform_createStream(stream, length) {
var cipher = new this.streamCipherConstructor();
return new DecryptStream(stream, length,
function cipherTransformDecryptStream(data, finalize) {
return cipher.decryptBlock(data, finalize);
}
);
},
decryptString: function CipherTransform_decryptString(s) {
var cipher = new this.stringCipherConstructor();
var data = stringToBytes(s);
data = cipher.decryptBlock(data, true);
return bytesToString(data);
}
};
return CipherTransform;
})();
var CipherTransformFactory = (function CipherTransformFactoryClosure() {
var defaultPasswordBytes = new Uint8Array([
0x28, 0xBF, 0x4E, 0x5E, 0x4E, 0x75, 0x8A, 0x41,
0x64, 0x00, 0x4E, 0x56, 0xFF, 0xFA, 0x01, 0x08,
0x2E, 0x2E, 0x00, 0xB6, 0xD0, 0x68, 0x3E, 0x80,
0x2F, 0x0C, 0xA9, 0xFE, 0x64, 0x53, 0x69, 0x7A]);
function createEncryptionKey20(revision, password, ownerPassword,
ownerValidationSalt, ownerKeySalt, uBytes,
userPassword, userValidationSalt, userKeySalt,
ownerEncryption, userEncryption, perms) {
if (password) {
var passwordLength = Math.min(127, password.length);
password = password.subarray(0, passwordLength);
} else {
password = [];
}
var pdfAlgorithm;
if (revision === 6) {
pdfAlgorithm = new PDF20();
} else {
pdfAlgorithm = new PDF17();
}
if (pdfAlgorithm) {
if (pdfAlgorithm.checkUserPassword(password, userValidationSalt,
userPassword)) {
return pdfAlgorithm.getUserKey(password, userKeySalt, userEncryption);
} else if (password.length && pdfAlgorithm.checkOwnerPassword(password,
ownerValidationSalt,
uBytes,
ownerPassword)) {
return pdfAlgorithm.getOwnerKey(password, ownerKeySalt, uBytes,
ownerEncryption);
}
}
return null;
}
function prepareKeyData(fileId, password, ownerPassword, userPassword,
flags, revision, keyLength, encryptMetadata) {
var hashDataSize = 40 + ownerPassword.length + fileId.length;
var hashData = new Uint8Array(hashDataSize), i = 0, j, n;
if (password) {
n = Math.min(32, password.length);
for (; i < n; ++i) {
hashData[i] = password[i];
}
}
j = 0;
while (i < 32) {
hashData[i++] = defaultPasswordBytes[j++];
}
// as now the padded password in the hashData[0..i]
for (j = 0, n = ownerPassword.length; j < n; ++j) {
hashData[i++] = ownerPassword[j];
}
hashData[i++] = flags & 0xFF;
hashData[i++] = (flags >> 8) & 0xFF;
hashData[i++] = (flags >> 16) & 0xFF;
hashData[i++] = (flags >>> 24) & 0xFF;
for (j = 0, n = fileId.length; j < n; ++j) {
hashData[i++] = fileId[j];
}
if (revision >= 4 && !encryptMetadata) {
hashData[i++] = 0xFF;
hashData[i++] = 0xFF;
hashData[i++] = 0xFF;
hashData[i++] = 0xFF;
}
var hash = calculateMD5(hashData, 0, i);
var keyLengthInBytes = keyLength >> 3;
if (revision >= 3) {
for (j = 0; j < 50; ++j) {
hash = calculateMD5(hash, 0, keyLengthInBytes);
}
}
var encryptionKey = hash.subarray(0, keyLengthInBytes);
var cipher, checkData;
if (revision >= 3) {
for (i = 0; i < 32; ++i) {
hashData[i] = defaultPasswordBytes[i];
}
for (j = 0, n = fileId.length; j < n; ++j) {
hashData[i++] = fileId[j];
}
cipher = new ARCFourCipher(encryptionKey);
checkData = cipher.encryptBlock(calculateMD5(hashData, 0, i));
n = encryptionKey.length;
var derivedKey = new Uint8Array(n), k;
for (j = 1; j <= 19; ++j) {
for (k = 0; k < n; ++k) {
derivedKey[k] = encryptionKey[k] ^ j;
}
cipher = new ARCFourCipher(derivedKey);
checkData = cipher.encryptBlock(checkData);
}
for (j = 0, n = checkData.length; j < n; ++j) {
if (userPassword[j] !== checkData[j]) {
return null;
}
}
} else {
cipher = new ARCFourCipher(encryptionKey);
checkData = cipher.encryptBlock(defaultPasswordBytes);
for (j = 0, n = checkData.length; j < n; ++j) {
if (userPassword[j] !== checkData[j]) {
return null;
}
}
}
return encryptionKey;
}
function decodeUserPassword(password, ownerPassword, revision, keyLength) {
var hashData = new Uint8Array(32), i = 0, j, n;
n = Math.min(32, password.length);
for (; i < n; ++i) {
hashData[i] = password[i];
}
j = 0;
while (i < 32) {
hashData[i++] = defaultPasswordBytes[j++];
}
var hash = calculateMD5(hashData, 0, i);
var keyLengthInBytes = keyLength >> 3;
if (revision >= 3) {
for (j = 0; j < 50; ++j) {
hash = calculateMD5(hash, 0, hash.length);
}
}
var cipher, userPassword;
if (revision >= 3) {
userPassword = ownerPassword;
var derivedKey = new Uint8Array(keyLengthInBytes), k;
for (j = 19; j >= 0; j--) {
for (k = 0; k < keyLengthInBytes; ++k) {
derivedKey[k] = hash[k] ^ j;
}
cipher = new ARCFourCipher(derivedKey);
userPassword = cipher.encryptBlock(userPassword);
}
} else {
cipher = new ARCFourCipher(hash.subarray(0, keyLengthInBytes));
userPassword = cipher.encryptBlock(ownerPassword);
}
return userPassword;
}
var identityName = Name.get('Identity');
function CipherTransformFactory(dict, fileId, password) {
var filter = dict.get('Filter');
if (!isName(filter) || filter.name !== 'Standard') {
error('unknown encryption method');
}
this.dict = dict;
var algorithm = dict.get('V');
if (!isInt(algorithm) ||
(algorithm !== 1 && algorithm !== 2 && algorithm !== 4 &&
algorithm !== 5)) {
error('unsupported encryption algorithm');
}
this.algorithm = algorithm;
var keyLength = dict.get('Length') || 40;
if (!isInt(keyLength) ||
keyLength < 40 || (keyLength % 8) !== 0) {
error('invalid key length');
}
// prepare keys
var ownerPassword = stringToBytes(dict.get('O')).subarray(0, 32);
var userPassword = stringToBytes(dict.get('U')).subarray(0, 32);
var flags = dict.get('P');
var revision = dict.get('R');
// meaningful when V is 4 or 5
var encryptMetadata = ((algorithm === 4 || algorithm === 5) &&
dict.get('EncryptMetadata') !== false);
this.encryptMetadata = encryptMetadata;
var fileIdBytes = stringToBytes(fileId);
var passwordBytes;
if (password) {
if (revision === 6) {
try {
password = utf8StringToString(password);
} catch (ex) {
warn('CipherTransformFactory: ' +
'Unable to convert UTF8 encoded password.');
}
}
passwordBytes = stringToBytes(password);
}
var encryptionKey;
if (algorithm !== 5) {
encryptionKey = prepareKeyData(fileIdBytes, passwordBytes,
ownerPassword, userPassword, flags,
revision, keyLength, encryptMetadata);
}
else {
var ownerValidationSalt = stringToBytes(dict.get('O')).subarray(32, 40);
var ownerKeySalt = stringToBytes(dict.get('O')).subarray(40, 48);
var uBytes = stringToBytes(dict.get('U')).subarray(0, 48);
var userValidationSalt = stringToBytes(dict.get('U')).subarray(32, 40);
var userKeySalt = stringToBytes(dict.get('U')).subarray(40, 48);
var ownerEncryption = stringToBytes(dict.get('OE'));
var userEncryption = stringToBytes(dict.get('UE'));
var perms = stringToBytes(dict.get('Perms'));
encryptionKey =
createEncryptionKey20(revision, passwordBytes,
ownerPassword, ownerValidationSalt,
ownerKeySalt, uBytes,
userPassword, userValidationSalt,
userKeySalt, ownerEncryption,
userEncryption, perms);
}
if (!encryptionKey && !password) {
throw new PasswordException('No password given',
PasswordResponses.NEED_PASSWORD);
} else if (!encryptionKey && password) {
// Attempting use the password as an owner password
var decodedPassword = decodeUserPassword(passwordBytes, ownerPassword,
revision, keyLength);
encryptionKey = prepareKeyData(fileIdBytes, decodedPassword,
ownerPassword, userPassword, flags,
revision, keyLength, encryptMetadata);
}
if (!encryptionKey) {
throw new PasswordException('Incorrect Password',
PasswordResponses.INCORRECT_PASSWORD);
}
this.encryptionKey = encryptionKey;
if (algorithm >= 4) {
this.cf = dict.get('CF');
this.stmf = dict.get('StmF') || identityName;
this.strf = dict.get('StrF') || identityName;
this.eff = dict.get('EFF') || this.stmf;
}
}
function buildObjectKey(num, gen, encryptionKey, isAes) {
var key = new Uint8Array(encryptionKey.length + 9), i, n;
for (i = 0, n = encryptionKey.length; i < n; ++i) {
key[i] = encryptionKey[i];
}
key[i++] = num & 0xFF;
key[i++] = (num >> 8) & 0xFF;
key[i++] = (num >> 16) & 0xFF;
key[i++] = gen & 0xFF;
key[i++] = (gen >> 8) & 0xFF;
if (isAes) {
key[i++] = 0x73;
key[i++] = 0x41;
key[i++] = 0x6C;
key[i++] = 0x54;
}
var hash = calculateMD5(key, 0, i);
return hash.subarray(0, Math.min(encryptionKey.length + 5, 16));
}
function buildCipherConstructor(cf, name, num, gen, key) {
var cryptFilter = cf.get(name.name);
var cfm;
if (cryptFilter !== null && cryptFilter !== undefined) {
cfm = cryptFilter.get('CFM');
}
if (!cfm || cfm.name === 'None') {
return function cipherTransformFactoryBuildCipherConstructorNone() {
return new NullCipher();
};
}
if ('V2' === cfm.name) {
return function cipherTransformFactoryBuildCipherConstructorV2() {
return new ARCFourCipher(buildObjectKey(num, gen, key, false));
};
}
if ('AESV2' === cfm.name) {
return function cipherTransformFactoryBuildCipherConstructorAESV2() {
return new AES128Cipher(buildObjectKey(num, gen, key, true));
};
}
if ('AESV3' === cfm.name) {
return function cipherTransformFactoryBuildCipherConstructorAESV3() {
return new AES256Cipher(key);
};
}
error('Unknown crypto method');
}
CipherTransformFactory.prototype = {
createCipherTransform:
function CipherTransformFactory_createCipherTransform(num, gen) {
if (this.algorithm === 4 || this.algorithm === 5) {
return new CipherTransform(
buildCipherConstructor(this.cf, this.stmf,
num, gen, this.encryptionKey),
buildCipherConstructor(this.cf, this.strf,
num, gen, this.encryptionKey));
}
// algorithms 1 and 2
var key = buildObjectKey(num, gen, this.encryptionKey, false);
var cipherConstructor = function buildCipherCipherConstructor() {
return new ARCFourCipher(key);
};
return new CipherTransform(cipherConstructor, cipherConstructor);
}
};
return CipherTransformFactory;
})();
exports.AES128Cipher = AES128Cipher;
exports.AES256Cipher = AES256Cipher;
exports.ARCFourCipher = ARCFourCipher;
exports.CipherTransformFactory = CipherTransformFactory;
exports.PDF17 = PDF17;
exports.PDF20 = PDF20;
exports.calculateMD5 = calculateMD5;
exports.calculateSHA256 = calculateSHA256;
exports.calculateSHA384 = calculateSHA384;
exports.calculateSHA512 = calculateSHA512;
}));
/* Copyright 2012 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
(function (root, factory) {
//if (typeof define === 'function' && define.amd) {
// define('pdfjs/core/obj', ['exports', 'pdfjs/shared/util',
// 'pdfjs/core/primitives', 'pdfjs/core/crypto', 'pdfjs/core/parser',
// 'pdfjs/core/chunked_stream'], factory);
// } else if (typeof exports !== 'undefined') {
// factory(exports, require('../shared/util.js'), require('./primitives.js'),
// require('./crypto.js'), require('./parser.js'),
// require('./chunked_stream.js'));
factory((root.pdfjsCoreObj = {}), root.pdfjsSharedUtil,
root.pdfjsCorePrimitives, root.pdfjsCoreCrypto, root.pdfjsCoreParser,
root.pdfjsCoreChunkedStream);
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
}(window, function (exports, sharedUtil, corePrimitives, coreCrypto, coreParser,
coreChunkedStream) {
var InvalidPDFException = sharedUtil.InvalidPDFException;
var MissingDataException = sharedUtil.MissingDataException;
var XRefParseException = sharedUtil.XRefParseException;
var assert = sharedUtil.assert;
var bytesToString = sharedUtil.bytesToString;
var createPromiseCapability = sharedUtil.createPromiseCapability;
var error = sharedUtil.error;
var info = sharedUtil.info;
var isArray = sharedUtil.isArray;
var isInt = sharedUtil.isInt;
var isString = sharedUtil.isString;
var shadow = sharedUtil.shadow;
var stringToPDFString = sharedUtil.stringToPDFString;
var stringToUTF8String = sharedUtil.stringToUTF8String;
var warn = sharedUtil.warn;
var Ref = corePrimitives.Ref;
var RefSet = corePrimitives.RefSet;
var RefSetCache = corePrimitives.RefSetCache;
var isName = corePrimitives.isName;
var isCmd = corePrimitives.isCmd;
var isDict = corePrimitives.isDict;
var isRef = corePrimitives.isRef;
var isStream = corePrimitives.isStream;
var CipherTransformFactory = coreCrypto.CipherTransformFactory;
var Lexer = coreParser.Lexer;
var Parser = coreParser.Parser;
var ChunkedStream = coreChunkedStream.ChunkedStream;
var Catalog = (function CatalogClosure() {
function Catalog(pdfManager, xref, pageFactory) {
this.pdfManager = pdfManager;
this.xref = xref;
this.catDict = xref.getCatalogObj();
this.fontCache = new RefSetCache();
assert(isDict(this.catDict),
'catalog object is not a dictionary');
// TODO refactor to move getPage() to the PDFDocument.
this.pageFactory = pageFactory;
this.pagePromises = [];
}
Catalog.prototype = {
get metadata() {
var streamRef = this.catDict.getRaw('Metadata');
if (!isRef(streamRef)) {
return shadow(this, 'metadata', null);
}
var encryptMetadata = (!this.xref.encrypt ? false :
this.xref.encrypt.encryptMetadata);
var stream = this.xref.fetch(streamRef, !encryptMetadata);
var metadata;
if (stream && isDict(stream.dict)) {
var type = stream.dict.get('Type');
var subtype = stream.dict.get('Subtype');
if (isName(type) && isName(subtype) &&
type.name === 'Metadata' && subtype.name === 'XML') {
// XXX: This should examine the charset the XML document defines,
// however since there are currently no real means to decode
// arbitrary charsets, let's just hope that the author of the PDF
// was reasonable enough to stick with the XML default charset,
// which is UTF-8.
try {
metadata = stringToUTF8String(bytesToString(stream.getBytes()));
} catch (e) {
info('Skipping invalid metadata.');
}
}
}
return shadow(this, 'metadata', metadata);
},
get toplevelPagesDict() {
var pagesObj = this.catDict.get('Pages');
assert(isDict(pagesObj), 'invalid top-level pages dictionary');
// shadow the prototype getter
return shadow(this, 'toplevelPagesDict', pagesObj);
},
get documentOutline() {
var obj = null;
try {
obj = this.readDocumentOutline();
} catch (ex) {
if (ex instanceof MissingDataException) {
throw ex;
}
warn('Unable to read document outline');
}
return shadow(this, 'documentOutline', obj);
},
readDocumentOutline: function Catalog_readDocumentOutline() {
var xref = this.xref;
var obj = this.catDict.get('Outlines');
var root = { items: [] };
if (isDict(obj)) {
obj = obj.getRaw('First');
var processed = new RefSet();
if (isRef(obj)) {
var queue = [{obj: obj, parent: root}];
// to avoid recursion keeping track of the items
// in the processed dictionary
processed.put(obj);
while (queue.length > 0) {
var i = queue.shift();
var outlineDict = xref.fetchIfRef(i.obj);
if (outlineDict === null) {
continue;
}
if (!outlineDict.has('Title')) {
error('Invalid outline item');
}
var dest = outlineDict.get('A');
if (dest) {
dest = dest.get('D');
} else if (outlineDict.has('Dest')) {
dest = outlineDict.getRaw('Dest');
if (isName(dest)) {
dest = dest.name;
}
}
var title = outlineDict.get('Title');
var outlineItem = {
dest: dest,
title: stringToPDFString(title),
color: outlineDict.get('C') || [0, 0, 0],
count: outlineDict.get('Count'),
bold: !!(outlineDict.get('F') & 2),
italic: !!(outlineDict.get('F') & 1),
items: []
};
i.parent.items.push(outlineItem);
obj = outlineDict.getRaw('First');
if (isRef(obj) && !processed.has(obj)) {
queue.push({obj: obj, parent: outlineItem});
processed.put(obj);
}
obj = outlineDict.getRaw('Next');
if (isRef(obj) && !processed.has(obj)) {
queue.push({obj: obj, parent: i.parent});
processed.put(obj);
}
}
}
}
return (root.items.length > 0 ? root.items : null);
},
get numPages() {
var obj = this.toplevelPagesDict.get('Count');
assert(
isInt(obj),
'page count in top level pages object is not an integer'
);
// shadow the prototype getter
return shadow(this, 'num', obj);
},
get destinations() {
function fetchDestination(dest) {
return isDict(dest) ? dest.get('D') : dest;
}
var xref = this.xref;
var dests = {}, nameTreeRef, nameDictionaryRef;
var obj = this.catDict.get('Names');
if (obj && obj.has('Dests')) {
nameTreeRef = obj.getRaw('Dests');
} else if (this.catDict.has('Dests')) {
nameDictionaryRef = this.catDict.get('Dests');
}
if (nameDictionaryRef) {
// reading simple destination dictionary
obj = nameDictionaryRef;
obj.forEach(function catalogForEach(key, value) {
if (!value) {
return;
}
dests[key] = fetchDestination(value);
});
}
if (nameTreeRef) {
var nameTree = new NameTree(nameTreeRef, xref);
var names = nameTree.getAll();
for (var name in names) {
if (!names.hasOwnProperty(name)) {
continue;
}
dests[name] = fetchDestination(names[name]);
}
}
return shadow(this, 'destinations', dests);
},
getDestination: function Catalog_getDestination(destinationId) {
function fetchDestination(dest) {
return isDict(dest) ? dest.get('D') : dest;
}
var xref = this.xref;
var dest = null, nameTreeRef, nameDictionaryRef;
var obj = this.catDict.get('Names');
if (obj && obj.has('Dests')) {
nameTreeRef = obj.getRaw('Dests');
} else if (this.catDict.has('Dests')) {
nameDictionaryRef = this.catDict.get('Dests');
}
if (nameDictionaryRef) { // Simple destination dictionary.
var value = nameDictionaryRef.get(destinationId);
if (value) {
dest = fetchDestination(value);
}
}
if (nameTreeRef) {
var nameTree = new NameTree(nameTreeRef, xref);
dest = fetchDestination(nameTree.get(destinationId));
}
return dest;
},
get attachments() {
var xref = this.xref;
var attachments = null, nameTreeRef;
var obj = this.catDict.get('Names');
if (obj) {
nameTreeRef = obj.getRaw('EmbeddedFiles');
}
if (nameTreeRef) {
var nameTree = new NameTree(nameTreeRef, xref);
var names = nameTree.getAll();
for (var name in names) {
if (!names.hasOwnProperty(name)) {
continue;
}
var fs = new FileSpec(names[name], xref);
if (!attachments) {
attachments = {};
}
attachments[stringToPDFString(name)] = fs.serializable;
}
}
return shadow(this, 'attachments', attachments);
},
get javaScript() {
var xref = this.xref;
var obj = this.catDict.get('Names');
var javaScript = [];
function appendIfJavaScriptDict(jsDict) {
var type = jsDict.get('S');
if (!isName(type) || type.name !== 'JavaScript') {
return;
}
var js = jsDict.get('JS');
if (isStream(js)) {
js = bytesToString(js.getBytes());
} else if (!isString(js)) {
return;
}
javaScript.push(stringToPDFString(js));
}
if (obj && obj.has('JavaScript')) {
var nameTree = new NameTree(obj.getRaw('JavaScript'), xref);
var names = nameTree.getAll();
for (var name in names) {
if (!names.hasOwnProperty(name)) {
continue;
}
// We don't really use the JavaScript right now. This code is
// defensive so we don't cause errors on document load.
var jsDict = names[name];
if (isDict(jsDict)) {
appendIfJavaScriptDict(jsDict);
}
}
}
// Append OpenAction actions to javaScript array
var openactionDict = this.catDict.get('OpenAction');
if (isDict(openactionDict, 'Action')) {
var actionType = openactionDict.get('S');
if (isName(actionType) && actionType.name === 'Named') {
// The named Print action is not a part of the PDF 1.7 specification,
// but is supported by many PDF readers/writers (including Adobe's).
var action = openactionDict.get('N');
if (isName(action) && action.name === 'Print') {
javaScript.push('print({});');
}
} else {
appendIfJavaScriptDict(openactionDict);
}
}
return shadow(this, 'javaScript', javaScript);
},
cleanup: function Catalog_cleanup() {
var promises = [];
this.fontCache.forEach(function (promise) {
promises.push(promise);
});
return Promise.all(promises).then(function (translatedFonts) {
for (var i = 0, ii = translatedFonts.length; i < ii; i++) {
var font = translatedFonts[i].dict;
delete font.translated;
}
this.fontCache.clear();
}.bind(this));
},
getPage: function Catalog_getPage(pageIndex) {
if (!(pageIndex in this.pagePromises)) {
this.pagePromises[pageIndex] = this.getPageDict(pageIndex).then(
function (a) {
var dict = a[0];
var ref = a[1];
return this.pageFactory.createPage(pageIndex, dict, ref,
this.fontCache);
}.bind(this)
);
}
return this.pagePromises[pageIndex];
},
getPageDict: function Catalog_getPageDict(pageIndex) {
var capability = createPromiseCapability();
var nodesToVisit = [this.catDict.getRaw('Pages')];
var currentPageIndex = 0;
var xref = this.xref;
var checkAllKids = false;
function next() {
while (nodesToVisit.length) {
var currentNode = nodesToVisit.pop();
if (isRef(currentNode)) {
xref.fetchAsync(currentNode).then(function (obj) {
if (isDict(obj, 'Page') || (isDict(obj) && !obj.has('Kids'))) {
if (pageIndex === currentPageIndex) {
capability.resolve([obj, currentNode]);
} else {
currentPageIndex++;
next();
}
return;
}
nodesToVisit.push(obj);
next();
}, capability.reject);
return;
}
// Must be a child page dictionary.
assert(
isDict(currentNode),
'page dictionary kid reference points to wrong type of object'
);
var count = currentNode.get('Count');
// If the current node doesn't have any children, avoid getting stuck
// in an empty node further down in the tree (see issue5644.pdf).
if (count === 0) {
checkAllKids = true;
}
// Skip nodes where the page can't be.
if (currentPageIndex + count <= pageIndex) {
currentPageIndex += count;
continue;
}
var kids = currentNode.get('Kids');
assert(isArray(kids), 'page dictionary kids object is not an array');
if (!checkAllKids && count === kids.length) {
// Nodes that don't have the page have been skipped and this is the
// bottom of the tree which means the page requested must be a
// descendant of this pages node. Ideally we would just resolve the
// promise with the page ref here, but there is the case where more
// pages nodes could link to single a page (see issue 3666 pdf). To
// handle this push it back on the queue so if it is a pages node it
// will be descended into.
nodesToVisit = [kids[pageIndex - currentPageIndex]];
currentPageIndex = pageIndex;
continue;
} else {
for (var last = kids.length - 1; last >= 0; last--) {
nodesToVisit.push(kids[last]);
}
}
}
capability.reject('Page index ' + pageIndex + ' not found.');
}
next();
return capability.promise;
},
getPageIndex: function Catalog_getPageIndex(ref) {
// The page tree nodes have the count of all the leaves below them. To get
// how many pages are before we just have to walk up the tree and keep
// adding the count of siblings to the left of the node.
var xref = this.xref;
function pagesBeforeRef(kidRef) {
var total = 0;
var parentRef;
return xref.fetchAsync(kidRef).then(function (node) {
if (!node) {
return null;
}
parentRef = node.getRaw('Parent');
return node.getAsync('Parent');
}).then(function (parent) {
if (!parent) {
return null;
}
return parent.getAsync('Kids');
}).then(function (kids) {
if (!kids) {
return null;
}
var kidPromises = [];
var found = false;
for (var i = 0; i < kids.length; i++) {
var kid = kids[i];
assert(isRef(kid), 'kids must be a ref');
if (kid.num === kidRef.num) {
found = true;
break;
}
kidPromises.push(xref.fetchAsync(kid).then(function (kid) {
if (kid.has('Count')) {
var count = kid.get('Count');
total += count;
} else { // page leaf node
total++;
}
}));
}
if (!found) {
error('kid ref not found in parents kids');
}
return Promise.all(kidPromises).then(function () {
return [total, parentRef];
});
});
}
var total = 0;
function next(ref) {
return pagesBeforeRef(ref).then(function (args) {
if (!args) {
return total;
}
var count = args[0];
var parentRef = args[1];
total += count;
return next(parentRef);
});
}
return next(ref);
}
};
return Catalog;
})();
var XRef = (function XRefClosure() {
function XRef(stream, password) {
this.stream = stream;
this.entries = [];
this.xrefstms = {};
// prepare the XRef cache
this.cache = [];
this.password = password;
this.stats = {
streamTypes: [],
fontTypes: []
};
}
XRef.prototype = {
setStartXRef: function XRef_setStartXRef(startXRef) {
// Store the starting positions of xref tables as we process them
// so we can recover from missing data errors
this.startXRefQueue = [startXRef];
this.xrefBlocks = [startXRef];
},
parse: function XRef_parse(recoveryMode) {
var trailerDict;
if (!recoveryMode) {
trailerDict = this.readXRef();
} else {
warn('Indexing all PDF objects');
trailerDict = this.indexObjects();
}
trailerDict.assignXref(this);
this.trailer = trailerDict;
var encrypt = trailerDict.get('Encrypt');
if (encrypt) {
var ids = trailerDict.get('ID');
var fileId = (ids && ids.length) ? ids[0] : '';
this.encrypt = new CipherTransformFactory(encrypt, fileId,
this.password);
}
// get the root dictionary (catalog) object
if (!(this.root = trailerDict.get('Root'))) {
error('Invalid root reference');
}
},
processXRefTable: function XRef_processXRefTable(parser) {
if (!('tableState' in this)) {
// Stores state of the table as we process it so we can resume
// from middle of table in case of missing data error
this.tableState = {
entryNum: 0,
streamPos: parser.lexer.stream.pos,
parserBuf1: parser.buf1,
parserBuf2: parser.buf2
};
}
var obj = this.readXRefTable(parser);
// Sanity check
if (!isCmd(obj, 'trailer')) {
error('Invalid XRef table: could not find trailer dictionary');
}
// Read trailer dictionary, e.g.
// trailer
// << /Size 22