-
Notifications
You must be signed in to change notification settings - Fork 6
/
jszip-load.js
executable file
·545 lines (508 loc) · 22.5 KB
/
jszip-load.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
/**
JSZip - A Javascript class for generating and reading zip files
<http://stuartk.com/jszip>
(c) 2011 David Duponchel <d.duponchel@gmail.com>
Dual licenced under the MIT license or GPLv3. See LICENSE.markdown.
**/
/*global JSZip,JSZipBase64 */
(function () {
var MAX_VALUE_16BITS = 65535;
var MAX_VALUE_32BITS = -1; // well, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" is parsed as -1
/**
* Prettify a string read as binary.
* @param {string} str the string to prettify.
* @return {string} a pretty string.
*/
var pretty = function (str) {
var res = '', code, i;
for (i = 0; i < (str || "").length; i++) {
code = str.charCodeAt(i);
res += '\\x' + (code < 16 ? "0" : "") + code.toString(16).toUpperCase();
}
return res;
};
/**
* Find a compression registered in JSZip.
* @param {string} compressionMethod the method magic to find.
* @return {Object|null} the JSZip compression object, null if none found.
*/
var findCompression = function (compressionMethod) {
for (var method in JSZip.compressions) {
if (!JSZip.compressions.hasOwnProperty(method)) { continue; }
if (JSZip.compressions[method].magic === compressionMethod) {
return JSZip.compressions[method];
}
}
return null;
};
// class StreamReader {{{
/**
* Read bytes from a stream.
* Developer tip : when debugging, a watch on pretty(this.reader.stream.slice(this.reader.index))
* is very useful :)
* @constructor
* @param {String|ArrayBuffer|Uint8Array} stream the stream to read.
*/
function StreamReader(stream) {
this.stream = "";
if (JSZip.support.uint8array && stream instanceof Uint8Array) {
this.stream = JSZip.utils.uint8Array2String(stream);
} else if (JSZip.support.arraybuffer && stream instanceof ArrayBuffer) {
var bufferView = new Uint8Array(stream);
this.stream = JSZip.utils.uint8Array2String(bufferView);
} else {
this.stream = JSZip.utils.string2binary(stream);
}
this.index = 0;
}
StreamReader.prototype = {
/**
* Check that the offset will not go too far.
* @param {string} offset the additional offset to check.
* @throws {Error} an Error if the offset is out of bounds.
*/
checkOffset: function (offset) {
this.checkIndex(this.index + offset);
},
/**
* Check that the specifed index will not be too far.
* @param {string} newIndex the index to check.
* @throws {Error} an Error if the index is out of bounds.
*/
checkIndex: function (newIndex) {
if (this.stream.length < newIndex || newIndex < 0) {
throw new Error("End of stream reached (stream length = " +
this.stream.length + ", asked index = " +
(newIndex) + "). Corrupted zip ?");
}
},
/**
* Change the index.
* @param {number} newIndex The new index.
* @throws {Error} if the new index is out of the stream.
*/
setIndex: function (newIndex) {
this.checkIndex(newIndex);
this.index = newIndex;
},
/**
* Skip the next n bytes.
* @param {number} n the number of bytes to skip.
* @throws {Error} if the new index is out of the stream.
*/
skip: function (n) {
this.setIndex(this.index + n);
},
/**
* Get the byte at the specified index.
* @param {number} i the index to use.
* @return {number} a byte.
*/
byteAt: function (i) {
return this.stream.charCodeAt(i);
},
/**
* Get the next number with a given byte size.
* @param {number} size the number of bytes to read.
* @return {number} the corresponding number.
*/
readInt: function (size) {
var result = 0, i;
this.checkOffset(size);
for (i = this.index + size - 1; i >= this.index; i--) {
result = (result << 8) + this.byteAt(i);
}
this.index += size;
return result;
},
/**
* Get the next string with a given byte size.
* @param {number} size the number of bytes to read.
* @return {string} the corresponding string.
*/
readString: function (size) {
this.checkOffset(size);
// this will work because the constructor applied the "& 0xff" mask.
var result = this.stream.slice(this.index, this.index + size);
this.index += size;
return result;
},
/**
* Get the next date.
* @return {Date} the date.
*/
readDate: function () {
var dostime = this.readInt(4);
return new Date(
((dostime >> 25) & 0x7f) + 1980, // year
((dostime >> 21) & 0x0f) - 1, // month
(dostime >> 16) & 0x1f, // day
(dostime >> 11) & 0x1f, // hour
(dostime >> 5) & 0x3f, // minute
(dostime & 0x1f) << 1); // second
}
};
// }}} end of StreamReader
// class ZipEntry {{{
/**
* An entry in the zip file.
* @constructor
* @param {Object} options Options of the current file.
* @param {Object} loadOptions Options for loading the stream.
*/
function ZipEntry(options, loadOptions) {
this.options = options;
this.loadOptions = loadOptions;
}
ZipEntry.prototype = {
/**
* say if the file is encrypted.
* @return {boolean} true if the file is encrypted, false otherwise.
*/
isEncrypted: function () {
// bit 1 is set
return (this.bitFlag & 0x0001) === 0x0001;
},
/**
* say if the file has utf-8 filename/comment.
* @return {boolean} true if the filename/comment is in utf-8, false otherwise.
*/
useUTF8: function () {
// bit 11 is set
return (this.bitFlag & 0x0800) === 0x0800;
},
/**
* Read the local part of a zip file and add the info in this object.
* @param {StreamReader} reader the reader to use.
*/
readLocalPart: function (reader) {
var compression, localExtraFieldsLength;
// we already know everything from the central dir !
// If the central dir data are false, we are doomed.
// On the bright side, the local part is scary : zip64, data descriptors, both, etc.
// The less data we get here, the more reliable this should be.
// Let's skip the whole header and dash to the data !
reader.skip(22);
// in some zip created on windows, the filename stored in the central dir contains \ instead of /.
// Strangely, the filename here is OK.
// I would love to treat these zip files as corrupted (see http://www.info-zip.org/FAQ.html#backslashes
// or APPNOTE#4.4.17.1, "All slashes MUST be forward slashes '/'") but there are a lot of bad zip generators...
// Search "unzip mismatching "local" filename continuing with "central" filename version" on
// the internet.
//
// I think I see the logic here : the central directory is used to display
// content and the local directory is used to extract the files. Mixing / and \
// may be used to display \ to windows users and use / when extracting the files.
// Unfortunately, this lead also to some issues : http://seclists.org/fulldisclosure/2009/Sep/394
this.fileNameLength = reader.readInt(2);
localExtraFieldsLength = reader.readInt(2); // can't be sure this will be the same as the central dir
this.fileName = reader.readString(this.fileNameLength);
reader.skip(localExtraFieldsLength);
if (this.compressedSize == -1 || this.uncompressedSize == -1) {
throw new Error("Bug or corrupted zip : didn't get enough informations from the central directory " +
"(compressedSize == -1 || uncompressedSize == -1)");
}
this.compressedFileData = reader.readString(this.compressedSize);
compression = findCompression(this.compressionMethod);
if (compression === null) { // no compression found
throw new Error("Corrupted zip : compression " + pretty(this.compressionMethod) +
" unknown (inner file : " + this.fileName + ")");
}
this.uncompressedFileData = compression.uncompress(this.compressedFileData);
if (this.uncompressedFileData.length !== this.uncompressedSize) {
throw new Error("Bug : uncompressed data size mismatch");
}
if (this.loadOptions.checkCRC32 && JSZip.prototype.crc32(this.uncompressedFileData) !== this.crc32) {
throw new Error("Corrupted zip : CRC32 mismatch");
}
},
/**
* Read the central part of a zip file and add the info in this object.
* @param {StreamReader} reader the reader to use.
*/
readCentralPart: function (reader) {
this.versionMadeBy = reader.readString(2);
this.versionNeeded = reader.readInt(2);
this.bitFlag = reader.readInt(2);
this.compressionMethod = reader.readString(2);
this.date = reader.readDate();
this.crc32 = reader.readInt(4);
this.compressedSize = reader.readInt(4);
this.uncompressedSize = reader.readInt(4);
this.fileNameLength = reader.readInt(2);
this.extraFieldsLength = reader.readInt(2);
this.fileCommentLength = reader.readInt(2);
this.diskNumberStart = reader.readInt(2);
this.internalFileAttributes = reader.readInt(2);
this.externalFileAttributes = reader.readInt(4);
this.localHeaderOffset = reader.readInt(4);
if (this.isEncrypted()) {
throw new Error("Encrypted zip are not supported");
}
this.fileName = reader.readString(this.fileNameLength);
this.readExtraFields(reader);
this.parseZIP64ExtraField(reader);
this.fileComment = reader.readString(this.fileCommentLength);
// warning, this is true only for zip with madeBy == DOS (plateform dependent feature)
this.dir = this.externalFileAttributes & 0x00000010 ? true : false;
},
/**
* Parse the ZIP64 extra field and merge the info in the current ZipEntry.
* @param {StreamReader} reader the reader to use.
*/
parseZIP64ExtraField: function (reader) {
if (!this.extraFields[0x0001]) {
return;
}
// should be something, preparing the extra reader
var extraReader = new StreamReader(this.extraFields[0x0001].value);
// I really hope that these 64bits integer can fit in 32 bits integer, because js
// won't let us have more.
if (this.uncompressedSize === MAX_VALUE_32BITS) {
this.uncompressedSize = extraReader.readInt(8);
}
if (this.compressedSize === MAX_VALUE_32BITS) {
this.compressedSize = extraReader.readInt(8);
}
if (this.localHeaderOffset === MAX_VALUE_32BITS) {
this.localHeaderOffset = extraReader.readInt(8);
}
if (this.diskNumberStart === MAX_VALUE_32BITS) {
this.diskNumberStart = extraReader.readInt(4);
}
},
/**
* Read the central part of a zip file and add the info in this object.
* @param {StreamReader} reader the reader to use.
*/
readExtraFields: function (reader) {
var start = reader.index,
extraFieldId,
extraFieldLength,
extraFieldValue;
this.extraFields = this.extraFields || {};
while (reader.index < start + this.extraFieldsLength) {
extraFieldId = reader.readInt(2);
extraFieldLength = reader.readInt(2);
extraFieldValue = reader.readString(extraFieldLength);
this.extraFields[extraFieldId] = {
id: extraFieldId,
length: extraFieldLength,
value: extraFieldValue
};
}
},
/**
* Apply an UTF8 transformation if needed.
*/
handleUTF8: function () {
if (this.useUTF8()) {
this.fileName = JSZip.prototype.utf8decode(this.fileName);
this.fileComment = JSZip.prototype.utf8decode(this.fileComment);
}
}
};
// }}} end of ZipEntry
// class ZipEntries {{{
/**
* All the entries in the zip file.
* @constructor
* @param {String|ArrayBuffer|Uint8Array} data the binary stream to load.
* @param {Object} loadOptions Options for loading the stream.
*/
function ZipEntries(data, loadOptions) {
this.files = [];
this.loadOptions = loadOptions;
if (data) {
this.load(data);
}
}
ZipEntries.prototype = {
/**
* Check that the reader is on the speficied signature.
* @param {string} expectedSignature the expected signature.
* @throws {Error} if it is an other signature.
*/
checkSignature: function (expectedSignature) {
var signature = this.reader.readString(4);
if (signature !== expectedSignature) {
throw new Error("Corrupted zip or bug : unexpected signature " +
"(" + pretty(signature) + ", expected " + pretty(expectedSignature) + ")");
}
},
/**
* Read the end of the central directory.
*/
readBlockEndOfCentral: function () {
this.diskNumber = this.reader.readInt(2);
this.diskWithCentralDirStart = this.reader.readInt(2);
this.centralDirRecordsOnThisDisk = this.reader.readInt(2);
this.centralDirRecords = this.reader.readInt(2);
this.centralDirSize = this.reader.readInt(4);
this.centralDirOffset = this.reader.readInt(4);
this.zipCommentLength = this.reader.readInt(2);
this.zipComment = this.reader.readString(this.zipCommentLength);
},
/**
* Read the end of the Zip 64 central directory.
* Not merged with the method readEndOfCentral :
* The end of central can coexist with its Zip64 brother,
* I don't want to read the wrong number of bytes !
*/
readBlockZip64EndOfCentral: function () {
this.zip64EndOfCentralSize = this.reader.readInt(8);
this.versionMadeBy = this.reader.readString(2);
this.versionNeeded = this.reader.readInt(2);
this.diskNumber = this.reader.readInt(4);
this.diskWithCentralDirStart = this.reader.readInt(4);
this.centralDirRecordsOnThisDisk = this.reader.readInt(8);
this.centralDirRecords = this.reader.readInt(8);
this.centralDirSize = this.reader.readInt(8);
this.centralDirOffset = this.reader.readInt(8);
this.zip64ExtensibleData = {};
var extraDataSize = this.zip64EndOfCentralSize - 44,
index = 0,
extraFieldId,
extraFieldLength,
extraFieldValue;
while (index < extraDataSize) {
extraFieldId = this.reader.readInt(2);
extraFieldLength = this.reader.readInt(4);
extraFieldValue = this.reader.readString(extraFieldLength);
this.zip64ExtensibleData[extraFieldId] = {
id: extraFieldId,
length: extraFieldLength,
value: extraFieldValue
};
}
},
/**
* Read the end of the Zip 64 central directory locator.
*/
readBlockZip64EndOfCentralLocator: function () {
this.diskWithZip64CentralDirStart = this.reader.readInt(4);
this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8);
this.disksCount = this.reader.readInt(4);
if (this.disksCount > 1) {
throw new Error("Multi-volumes zip are not supported");
}
},
/**
* Read the local files, based on the offset read in the central part.
*/
readLocalFiles: function () {
var i, file;
for (i = 0; i < this.files.length; i++) {
file = this.files[i];
this.reader.setIndex(file.localHeaderOffset);
this.checkSignature(JSZip.signature.LOCAL_FILE_HEADER);
file.readLocalPart(this.reader);
file.handleUTF8();
}
},
/**
* Read the central directory.
*/
readCentralDir: function () {
var file;
this.reader.setIndex(this.centralDirOffset);
while (this.reader.readString(4) === JSZip.signature.CENTRAL_FILE_HEADER) {
file = new ZipEntry({
zip64: this.zip64
}, this.loadOptions);
file.readCentralPart(this.reader);
this.files.push(file);
}
},
/**
* Read the end of central directory.
*/
readEndOfCentral: function () {
var offset = this.reader.stream.lastIndexOf(JSZip.signature.CENTRAL_DIRECTORY_END);
if (offset === -1) {
throw new Error("Corrupted zip : can't find end of central directory");
}
this.reader.setIndex(offset);
this.checkSignature(JSZip.signature.CENTRAL_DIRECTORY_END);
this.readBlockEndOfCentral();
/* extract from the zip spec :
4) If one of the fields in the end of central directory
record is too small to hold required data, the field
should be set to -1 (0xFFFF or 0xFFFFFFFF) and the
ZIP64 format record should be created.
5) The end of central directory record and the
Zip64 end of central directory locator record must
reside on the same disk when splitting or spanning
an archive.
*/
if (this.diskNumber === MAX_VALUE_16BITS
|| this.diskWithCentralDirStart === MAX_VALUE_16BITS
|| this.centralDirRecordsOnThisDisk === MAX_VALUE_16BITS
|| this.centralDirRecords === MAX_VALUE_16BITS
|| this.centralDirSize === MAX_VALUE_32BITS
|| this.centralDirOffset === MAX_VALUE_32BITS
) {
this.zip64 = true;
/*
Warning : the zip64 extension is supported, but ONLY if the 64bits integer read from
the zip file can fit into a 32bits integer. This cannot be solved : Javascript represents
all numbers as 64-bit double precision IEEE 754 floating point numbers.
So, we have 53bits for integers and bitwise operations treat everything as 32bits.
see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Bitwise_Operators
and http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf section 8.5
*/
// should look for a zip64 EOCD locator
offset = this.reader.stream.lastIndexOf(JSZip.signature.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
if (offset === -1) {
throw new Error("Corrupted zip : can't find the ZIP64 end of central directory locator");
}
this.reader.setIndex(offset);
this.checkSignature(JSZip.signature.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
this.readBlockZip64EndOfCentralLocator();
// now the zip64 EOCD record
this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir);
this.checkSignature(JSZip.signature.ZIP64_CENTRAL_DIRECTORY_END);
this.readBlockZip64EndOfCentral();
}
},
/**
* Read a zip file and create ZipEntries.
* @param {String|ArrayBuffer|Uint8Array} data the binary string representing a zip file.
*/
load: function (data) {
this.reader = new StreamReader(data);
this.readEndOfCentral();
this.readCentralDir();
this.readLocalFiles();
}
};
// }}} end of ZipEntries
/**
* Implementation of the load method of JSZip.
* It uses the above classes to decode a zip file, and load every files.
* @param {String|ArrayBuffer|Uint8Array} data the data to load.
* @param {Object} options Options for loading the stream.
* options.base64 : is the stream in base64 ? default : false
*/
JSZip.prototype.load = function (data, options) {
var files, zipEntries, i, input;
options = options || {};
if (options.base64) {
data = JSZipBase64.decode(data);
}
zipEntries = new ZipEntries(data, options);
files = zipEntries.files;
for (i = 0; i < files.length; i++) {
input = files[i];
this.file(input.fileName, input.uncompressedFileData, {
binary: true,
optimizedBinaryString: true,
date: input.date,
dir: input.dir
});
}
return this;
};
}());
// enforcing Stuk's coding style
// vim: set shiftwidth=3 softtabstop=3 foldmethod=marker: