UNPKG

36.4 kBJavaScriptView Raw
1/**
2 * @license node-stream-zip | (c) 2015 Antelle | https://github.com/antelle/node-stream-zip/blob/master/LICENSE
3 * Portions copyright https://github.com/cthackers/adm-zip | https://raw.githubusercontent.com/cthackers/adm-zip/master/LICENSE
4 */
5
6// region Deps
7
8var
9 util = require('util'),
10 fs = require('fs'),
11 path = require('path'),
12 events = require('events'),
13 zlib = require('zlib'),
14 stream = require('stream');
15
16// endregion
17
18// region Constants
19
20var consts = {
21 /* The local file header */
22 LOCHDR : 30, // LOC header size
23 LOCSIG : 0x04034b50, // "PK\003\004"
24 LOCVER : 4, // version needed to extract
25 LOCFLG : 6, // general purpose bit flag
26 LOCHOW : 8, // compression method
27 LOCTIM : 10, // modification time (2 bytes time, 2 bytes date)
28 LOCCRC : 14, // uncompressed file crc-32 value
29 LOCSIZ : 18, // compressed size
30 LOCLEN : 22, // uncompressed size
31 LOCNAM : 26, // filename length
32 LOCEXT : 28, // extra field length
33
34 /* The Data descriptor */
35 EXTSIG : 0x08074b50, // "PK\007\008"
36 EXTHDR : 16, // EXT header size
37 EXTCRC : 4, // uncompressed file crc-32 value
38 EXTSIZ : 8, // compressed size
39 EXTLEN : 12, // uncompressed size
40
41 /* The central directory file header */
42 CENHDR : 46, // CEN header size
43 CENSIG : 0x02014b50, // "PK\001\002"
44 CENVEM : 4, // version made by
45 CENVER : 6, // version needed to extract
46 CENFLG : 8, // encrypt, decrypt flags
47 CENHOW : 10, // compression method
48 CENTIM : 12, // modification time (2 bytes time, 2 bytes date)
49 CENCRC : 16, // uncompressed file crc-32 value
50 CENSIZ : 20, // compressed size
51 CENLEN : 24, // uncompressed size
52 CENNAM : 28, // filename length
53 CENEXT : 30, // extra field length
54 CENCOM : 32, // file comment length
55 CENDSK : 34, // volume number start
56 CENATT : 36, // internal file attributes
57 CENATX : 38, // external file attributes (host system dependent)
58 CENOFF : 42, // LOC header offset
59
60 /* The entries in the end of central directory */
61 ENDHDR : 22, // END header size
62 ENDSIG : 0x06054b50, // "PK\005\006"
63 ENDSIGFIRST : 0x50,
64 ENDSUB : 8, // number of entries on this disk
65 ENDTOT : 10, // total number of entries
66 ENDSIZ : 12, // central directory size in bytes
67 ENDOFF : 16, // offset of first CEN header
68 ENDCOM : 20, // zip file comment length
69 MAXFILECOMMENT : 0xFFFF,
70
71 /* The entries in the end of ZIP64 central directory locator */
72 ENDL64HDR : 20, // ZIP64 end of central directory locator header size
73 ENDL64SIG : 0x07064b50, // ZIP64 end of central directory locator signature
74 ENDL64SIGFIRST : 0x50,
75 ENDL64OFS : 8, // ZIP64 end of central directory offset
76
77 /* The entries in the end of ZIP64 central directory */
78 END64HDR : 56, // ZIP64 end of central directory header size
79 END64SIG : 0x06064b50, // ZIP64 end of central directory signature
80 END64SIGFIRST : 0x50,
81 END64SUB : 24, // number of entries on this disk
82 END64TOT : 32, // total number of entries
83 END64SIZ : 40,
84 END64OFF : 48,
85
86 /* Compression methods */
87 STORED : 0, // no compression
88 SHRUNK : 1, // shrunk
89 REDUCED1 : 2, // reduced with compression factor 1
90 REDUCED2 : 3, // reduced with compression factor 2
91 REDUCED3 : 4, // reduced with compression factor 3
92 REDUCED4 : 5, // reduced with compression factor 4
93 IMPLODED : 6, // imploded
94 // 7 reserved
95 DEFLATED : 8, // deflated
96 ENHANCED_DEFLATED: 9, // enhanced deflated
97 PKWARE : 10,// PKWare DCL imploded
98 // 11 reserved
99 BZIP2 : 12, // compressed using BZIP2
100 // 13 reserved
101 LZMA : 14, // LZMA
102 // 15-17 reserved
103 IBM_TERSE : 18, // compressed using IBM TERSE
104 IBM_LZ77 : 19, //IBM LZ77 z
105
106 /* General purpose bit flag */
107 FLG_ENC : 0, // encrypted file
108 FLG_COMP1 : 1, // compression option
109 FLG_COMP2 : 2, // compression option
110 FLG_DESC : 4, // data descriptor
111 FLG_ENH : 8, // enhanced deflation
112 FLG_STR : 16, // strong encryption
113 FLG_LNG : 1024, // language encoding
114 FLG_MSK : 4096, // mask header values
115 FLG_ENTRY_ENC : 1,
116
117 /* 4.5 Extensible data fields */
118 EF_ID : 0,
119 EF_SIZE : 2,
120
121 /* Header IDs */
122 ID_ZIP64 : 0x0001,
123 ID_AVINFO : 0x0007,
124 ID_PFS : 0x0008,
125 ID_OS2 : 0x0009,
126 ID_NTFS : 0x000a,
127 ID_OPENVMS : 0x000c,
128 ID_UNIX : 0x000d,
129 ID_FORK : 0x000e,
130 ID_PATCH : 0x000f,
131 ID_X509_PKCS7 : 0x0014,
132 ID_X509_CERTID_F : 0x0015,
133 ID_X509_CERTID_C : 0x0016,
134 ID_STRONGENC : 0x0017,
135 ID_RECORD_MGT : 0x0018,
136 ID_X509_PKCS7_RL : 0x0019,
137 ID_IBM1 : 0x0065,
138 ID_IBM2 : 0x0066,
139 ID_POSZIP : 0x4690,
140
141 EF_ZIP64_OR_32 : 0xffffffff,
142 EF_ZIP64_OR_16 : 0xffff
143};
144
145// endregion
146
147// region StreamZip
148
149var StreamZip = function(config) {
150 var
151 fd,
152 fileSize,
153 chunkSize,
154 ready = false,
155 that = this,
156 op,
157 centralDirectory,
158 closed,
159
160 entries = config.storeEntries !== false ? {} : null,
161 fileName = config.file;
162
163 open();
164
165 function open() {
166 fs.open(fileName, 'r', function(err, f) {
167 if (err)
168 return that.emit('error', err);
169 fd = f;
170 fs.fstat(fd, function(err, stat) {
171 if (err)
172 return that.emit('error', err);
173 fileSize = stat.size;
174 chunkSize = config.chunkSize || Math.round(fileSize / 1000);
175 chunkSize = Math.max(Math.min(chunkSize, Math.min(128*1024, fileSize)), Math.min(1024, fileSize));
176 readCentralDirectory();
177 });
178 });
179 }
180
181 function readUntilFoundCallback(err, bytesRead) {
182 if (err || !bytesRead)
183 return that.emit('error', err || 'Archive read error');
184 var
185 buffer = op.win.buffer,
186 pos = op.lastPos,
187 bufferPosition = pos - op.win.position,
188 minPos = op.minPos;
189 while (--pos >= minPos && --bufferPosition >= 0) {
190 if (buffer.length - bufferPosition >= 4 &&
191 buffer[bufferPosition] === op.firstByte) { // quick check first signature byte
192 if (buffer.readUInt32LE(bufferPosition) === op.sig) {
193 op.lastBufferPosition = bufferPosition;
194 op.lastBytesRead = bytesRead;
195 op.complete();
196 return;
197 }
198 }
199 }
200 if (pos === minPos) {
201 return that.emit('error', 'Bad archive');
202 }
203 op.lastPos = pos + 1;
204 op.chunkSize *= 2;
205 if (pos <= minPos)
206 return that.emit('error', 'Bad archive');
207 var expandLength = Math.min(op.chunkSize, pos - minPos);
208 op.win.expandLeft(expandLength, readUntilFoundCallback);
209
210 }
211
212 function readCentralDirectory() {
213 var totalReadLength = Math.min(consts.ENDHDR + consts.MAXFILECOMMENT, fileSize);
214 op = {
215 win: new FileWindowBuffer(fd),
216 totalReadLength: totalReadLength,
217 minPos: fileSize - totalReadLength,
218 lastPos: fileSize,
219 chunkSize: Math.min(1024, chunkSize),
220 firstByte: consts.ENDSIGFIRST,
221 sig: consts.ENDSIG,
222 complete: readCentralDirectoryComplete
223 };
224 op.win.read(fileSize - op.chunkSize, op.chunkSize, readUntilFoundCallback);
225 }
226
227 function readCentralDirectoryComplete() {
228 var buffer = op.win.buffer;
229 var pos = op.lastBufferPosition;
230 try {
231 centralDirectory = new CentralDirectoryHeader();
232 centralDirectory.read(buffer.slice(pos, pos + consts.ENDHDR));
233 centralDirectory.headerOffset = op.win.position + pos;
234 if (centralDirectory.commentLength)
235 that.comment = buffer.slice(pos + consts.ENDHDR,
236 pos + consts.ENDHDR + centralDirectory.commentLength).toString();
237 else
238 that.comment = null;
239 that.entriesCount = centralDirectory.volumeEntries;
240 that.centralDirectory = centralDirectory;
241 if (centralDirectory.volumeEntries === consts.EF_ZIP64_OR_16 && centralDirectory.totalEntries === consts.EF_ZIP64_OR_16
242 || centralDirectory.size === consts.EF_ZIP64_OR_32 || centralDirectory.offset === consts.EF_ZIP64_OR_32) {
243 readZip64CentralDirectoryLocator();
244 } else {
245 op = {};
246 readEntries();
247 }
248 } catch (err) {
249 that.emit('error', err);
250 }
251 }
252
253 function readZip64CentralDirectoryLocator() {
254 var length = consts.ENDL64HDR;
255 if (op.lastBufferPosition > length) {
256 op.lastBufferPosition -= length;
257 readZip64CentralDirectoryLocatorComplete();
258 } else {
259 op = {
260 win: op.win,
261 totalReadLength: length,
262 minPos: op.win.position - length,
263 lastPos: op.win.position,
264 chunkSize: op.chunkSize,
265 firstByte: consts.ENDL64SIGFIRST,
266 sig: consts.ENDL64SIG,
267 complete: readZip64CentralDirectoryLocatorComplete
268 };
269 op.win.read(op.lastPos - op.chunkSize, op.chunkSize, readUntilFoundCallback);
270 }
271 }
272
273 function readZip64CentralDirectoryLocatorComplete() {
274 var buffer = op.win.buffer;
275 var locHeader = new CentralDirectoryLoc64Header();
276 locHeader.read(buffer.slice(op.lastBufferPosition, op.lastBufferPosition + consts.ENDL64HDR));
277 var readLength = fileSize - locHeader.headerOffset;
278 op = {
279 win: op.win,
280 totalReadLength: readLength,
281 minPos: locHeader.headerOffset,
282 lastPos: op.lastPos,
283 chunkSize: op.chunkSize,
284 firstByte: consts.END64SIGFIRST,
285 sig: consts.END64SIG,
286 complete: readZip64CentralDirectoryComplete
287 };
288 op.win.read(fileSize - op.chunkSize, op.chunkSize, readUntilFoundCallback);
289 }
290
291 function readZip64CentralDirectoryComplete() {
292 var buffer = op.win.buffer;
293 var zip64cd = new CentralDirectoryZip64Header();
294 zip64cd.read(buffer.slice(op.lastBufferPosition, op.lastBufferPosition + consts.END64HDR));
295 that.centralDirectory.volumeEntries = zip64cd.volumeEntries;
296 that.centralDirectory.totalEntries = zip64cd.totalEntries;
297 that.centralDirectory.size = zip64cd.size;
298 that.centralDirectory.offset = zip64cd.offset;
299 that.entriesCount = zip64cd.volumeEntries;
300 op = {};
301 readEntries();
302 }
303
304 function readEntries() {
305 op = {
306 win: new FileWindowBuffer(fd),
307 pos: centralDirectory.offset,
308 chunkSize: chunkSize,
309 entriesLeft: centralDirectory.volumeEntries
310 };
311 op.win.read(op.pos, Math.min(chunkSize, fileSize - op.pos), readEntriesCallback);
312 }
313
314 function readEntriesCallback(err, bytesRead) {
315 if (err || !bytesRead)
316 return that.emit('error', err || 'Entries read error');
317 var
318 buffer = op.win.buffer,
319 bufferPos = op.pos - op.win.position,
320 bufferLength = buffer.length,
321 entry = op.entry;
322 try {
323 while (op.entriesLeft > 0) {
324 if (!entry) {
325 entry = new ZipEntry();
326 entry.readHeader(buffer, bufferPos);
327 entry.headerOffset = op.win.position + bufferPos;
328 op.entry = entry;
329 op.pos += consts.CENHDR;
330 bufferPos += consts.CENHDR;
331 }
332 var entryHeaderSize = entry.fnameLen + entry.extraLen + entry.comLen;
333 var advanceBytes = entryHeaderSize + (op.entriesLeft > 1 ? consts.CENHDR : 0);
334 if (bufferLength - bufferPos < advanceBytes) {
335 op.win.moveRight(chunkSize, readEntriesCallback, bufferPos);
336 op.move = true;
337 return;
338 }
339 entry.read(buffer, bufferPos);
340 if (!config.skipEntryNameValidation) {
341 entry.validateName();
342 }
343 if (entries)
344 entries[entry.name] = entry;
345 that.emit('entry', entry);
346 op.entry = entry = null;
347 op.entriesLeft--;
348 op.pos += entryHeaderSize;
349 bufferPos += entryHeaderSize;
350 }
351 that.emit('ready');
352 } catch (err) {
353 that.emit('error', err);
354 }
355 }
356
357 function checkEntriesExist() {
358 if (!entries)
359 throw new Error('storeEntries disabled');
360 }
361
362 Object.defineProperty(this, 'ready', { get: function() { return ready; } });
363
364 this.entry = function(name) {
365 checkEntriesExist();
366 return entries[name];
367 };
368
369 this.entries = function() {
370 checkEntriesExist();
371 return entries;
372 };
373
374 this.stream = function(entry, callback) {
375 return this.openEntry(entry, function(err, entry) {
376 if (err)
377 return callback(err);
378 var offset = dataOffset(entry);
379 var entryStream = new EntryDataReaderStream(fd, offset, entry.compressedSize);
380 if (entry.method === consts.STORED) {
381 } else if (entry.method === consts.DEFLATED || entry.method === consts.ENHANCED_DEFLATED) {
382 entryStream = entryStream.pipe(zlib.createInflateRaw());
383 } else {
384 return callback('Unknown compression method: ' + entry.method);
385 }
386 if (canVerifyCrc(entry))
387 entryStream = entryStream.pipe(new EntryVerifyStream(entryStream, entry.crc, entry.size));
388 callback(null, entryStream);
389 }, false);
390 };
391
392 this.entryDataSync = function(entry) {
393 var err = null;
394 this.openEntry(entry, function(e, en) {
395 err = e;
396 entry = en;
397 }, true);
398 if (err)
399 throw err;
400 var
401 data = Buffer.alloc(entry.compressedSize),
402 bytesRead;
403 new FsRead(fd, data, 0, entry.compressedSize, dataOffset(entry), function(e, br) {
404 err = e;
405 bytesRead = br;
406 }).read(true);
407 if (err)
408 throw err;
409 if (entry.method === consts.STORED) {
410 } else if (entry.method === consts.DEFLATED || entry.method === consts.ENHANCED_DEFLATED) {
411 data = zlib.inflateRawSync(data);
412 } else {
413 throw new Error('Unknown compression method: ' + entry.method);
414 }
415 if (data.length !== entry.size)
416 throw new Error('Invalid size');
417 if (canVerifyCrc(entry)) {
418 var verify = new CrcVerify(entry.crc, entry.size);
419 verify.data(data);
420 }
421 return data;
422 };
423
424 this.openEntry = function(entry, callback, sync) {
425 if (typeof entry === 'string') {
426 checkEntriesExist();
427 entry = entries[entry];
428 if (!entry)
429 return callback('Entry not found');
430 }
431 if (!entry.isFile)
432 return callback('Entry is not file');
433 if (!fd)
434 return callback('Archive closed');
435 var buffer = Buffer.alloc(consts.LOCHDR);
436 new FsRead(fd, buffer, 0, buffer.length, entry.offset, function(err) {
437 if (err)
438 return callback(err);
439 var readEx;
440 try {
441 entry.readDataHeader(buffer);
442 if (entry.encrypted) {
443 readEx = 'Entry encrypted';
444 }
445 } catch (ex) {
446 readEx = ex
447 }
448 callback(readEx, entry);
449 }).read(sync);
450 };
451
452 function dataOffset(entry) {
453 return entry.offset + consts.LOCHDR + entry.fnameLen + entry.extraLen;
454 }
455
456 function canVerifyCrc(entry) {
457 // if bit 3 (0x08) of the general-purpose flags field is set, then the CRC-32 and file sizes are not known when the header is written
458 return (entry.flags & 0x8) != 0x8;
459 }
460
461 function extract(entry, outPath, callback) {
462 that.stream(entry, function (err, stm) {
463 if (err) {
464 callback(err);
465 } else {
466 var fsStm, errThrown;
467 stm.on('error', function(err) {
468 errThrown = err;
469 if (fsStm) {
470 stm.unpipe(fsStm);
471 fsStm.close(function () {
472 callback(err);
473 });
474 }
475 });
476 fs.open(outPath, 'w', function(err, fdFile) {
477 if (err)
478 return callback(err || errThrown);
479 if (errThrown) {
480 fs.close(fd, function() {
481 callback(errThrown);
482 });
483 return;
484 }
485 fsStm = fs.createWriteStream(outPath, { fd: fdFile });
486 fsStm.on('finish', function() {
487 that.emit('extract', entry, outPath);
488 if (!errThrown)
489 callback();
490 });
491 stm.pipe(fsStm);
492 });
493 }
494 });
495 }
496
497 function createDirectories(baseDir, dirs, callback) {
498 if (!dirs.length)
499 return callback();
500 var dir = dirs.shift();
501 dir = path.join(baseDir, path.join.apply(path, dir));
502 fs.mkdir(dir, function(err) {
503 if (err && err.code !== 'EEXIST')
504 return callback(err);
505 createDirectories(baseDir, dirs, callback);
506 });
507 }
508
509 function extractFiles(baseDir, baseRelPath, files, callback, extractedCount) {
510 if (!files.length)
511 return callback(null, extractedCount);
512 var file = files.shift();
513 var targetPath = path.join(baseDir, file.name.replace(baseRelPath, ''));
514 extract(file, targetPath, function (err) {
515 if (err)
516 return callback(err, extractedCount);
517 extractFiles(baseDir, baseRelPath, files, callback, extractedCount + 1);
518 });
519 }
520
521 this.extract = function(entry, outPath, callback) {
522 var entryName = entry || '';
523 if (typeof entry === 'string') {
524 entry = this.entry(entry);
525 if (entry) {
526 entryName = entry.name;
527 } else {
528 if (entryName.length && entryName[entryName.length - 1] !== '/')
529 entryName += '/';
530 }
531 }
532 if (!entry || entry.isDirectory) {
533 var files = [], dirs = [], allDirs = {};
534 for (var e in entries) {
535 if (Object.prototype.hasOwnProperty.call(entries, e) && e.lastIndexOf(entryName, 0) === 0) {
536 var relPath = e.replace(entryName, '');
537 var childEntry = entries[e];
538 if (childEntry.isFile) {
539 files.push(childEntry);
540 relPath = path.dirname(relPath);
541 }
542 if (relPath && !allDirs[relPath] && relPath !== '.') {
543 allDirs[relPath] = true;
544 var parts = relPath.split('/').filter(function (f) { return f; });
545 if (parts.length)
546 dirs.push(parts);
547 while (parts.length > 1) {
548 parts = parts.slice(0, parts.length - 1);
549 var partsPath = parts.join('/');
550 if (allDirs[partsPath] || partsPath === '.') {
551 break;
552 }
553 allDirs[partsPath] = true;
554 dirs.push(parts);
555 }
556 }
557 }
558 }
559 dirs.sort(function(x, y) { return x.length - y.length; });
560 if (dirs.length) {
561 createDirectories(outPath, dirs, function (err) {
562 if (err)
563 callback(err);
564 else
565 extractFiles(outPath, entryName, files, callback, 0);
566 });
567 } else {
568 extractFiles(outPath, entryName, files, callback, 0);
569 }
570 } else {
571 fs.stat(outPath, function(err, stat) {
572 if (stat && stat.isDirectory())
573 extract(entry, path.join(outPath, path.basename(entry.name)), callback);
574 else
575 extract(entry, outPath, callback);
576 });
577 }
578 };
579
580 this.close = function(callback) {
581 if (closed || !fd) {
582 closed = true;
583 if (callback)
584 callback();
585 } else {
586 closed = true;
587 fs.close(fd, function(err) {
588 fd = null;
589 if (callback)
590 callback(err);
591 });
592 }
593 };
594
595 var originalEmit = events.EventEmitter.prototype.emit;
596 this.emit = function() {
597 if (!closed) {
598 return originalEmit.apply(this, arguments);
599 }
600 };
601};
602
603StreamZip.setFs = function(customFs) {
604 fs = customFs;
605};
606
607util.inherits(StreamZip, events.EventEmitter);
608
609// endregion
610
611// region CentralDirectoryHeader
612
613var CentralDirectoryHeader = function() {
614};
615
616CentralDirectoryHeader.prototype.read = function(data) {
617 if (data.length != consts.ENDHDR || data.readUInt32LE(0) != consts.ENDSIG)
618 throw new Error('Invalid central directory');
619 // number of entries on this volume
620 this.volumeEntries = data.readUInt16LE(consts.ENDSUB);
621 // total number of entries
622 this.totalEntries = data.readUInt16LE(consts.ENDTOT);
623 // central directory size in bytes
624 this.size = data.readUInt32LE(consts.ENDSIZ);
625 // offset of first CEN header
626 this.offset = data.readUInt32LE(consts.ENDOFF);
627 // zip file comment length
628 this.commentLength = data.readUInt16LE(consts.ENDCOM);
629};
630
631// endregion
632
633// region CentralDirectoryLoc64Header
634
635var CentralDirectoryLoc64Header = function() {
636};
637
638CentralDirectoryLoc64Header.prototype.read = function(data) {
639 if (data.length != consts.ENDL64HDR || data.readUInt32LE(0) != consts.ENDL64SIG)
640 throw new Error('Invalid zip64 central directory locator');
641 // ZIP64 EOCD header offset
642 this.headerOffset = Util.readUInt64LE(data, consts.ENDSUB);
643};
644
645// endregion
646
647// region CentralDirectoryZip64Header
648
649var CentralDirectoryZip64Header = function() {
650};
651
652CentralDirectoryZip64Header.prototype.read = function(data) {
653 if (data.length != consts.END64HDR || data.readUInt32LE(0) != consts.END64SIG)
654 throw new Error('Invalid central directory');
655 // number of entries on this volume
656 this.volumeEntries = Util.readUInt64LE(data, consts.END64SUB);
657 // total number of entries
658 this.totalEntries = Util.readUInt64LE(data, consts.END64TOT);
659 // central directory size in bytes
660 this.size = Util.readUInt64LE(data, consts.END64SIZ);
661 // offset of first CEN header
662 this.offset = Util.readUInt64LE(data, consts.END64OFF);
663};
664
665// endregion
666
667// region ZipEntry
668
669var ZipEntry = function() {
670};
671
672function toBits(dec, size) {
673 var b = (dec >>> 0).toString(2);
674 while (b.length < size)
675 b = '0' + b;
676 return b.split('');
677}
678
679function parseZipTime(timebytes, datebytes) {
680 var timebits = toBits(timebytes, 16);
681 var datebits = toBits(datebytes, 16);
682
683 var mt = {
684 h: parseInt(timebits.slice(0,5).join(''), 2),
685 m: parseInt(timebits.slice(5,11).join(''), 2),
686 s: parseInt(timebits.slice(11,16).join(''), 2) * 2,
687 Y: parseInt(datebits.slice(0,7).join(''), 2) + 1980,
688 M: parseInt(datebits.slice(7,11).join(''), 2),
689 D: parseInt(datebits.slice(11,16).join(''), 2),
690 };
691 var dt_str = [mt.Y, mt.M, mt.D].join('-') + ' ' + [mt.h, mt.m, mt.s].join(':') + ' GMT+0';
692 return new Date(dt_str).getTime();
693}
694
695ZipEntry.prototype.readHeader = function(data, offset) {
696 // data should be 46 bytes and start with "PK 01 02"
697 if (data.length < offset + consts.CENHDR || data.readUInt32LE(offset) != consts.CENSIG) {
698 throw new Error('Invalid entry header');
699 }
700 // version made by
701 this.verMade = data.readUInt16LE(offset + consts.CENVEM);
702 // version needed to extract
703 this.version = data.readUInt16LE(offset + consts.CENVER);
704 // encrypt, decrypt flags
705 this.flags = data.readUInt16LE(offset + consts.CENFLG);
706 // compression method
707 this.method = data.readUInt16LE(offset + consts.CENHOW);
708 // modification time (2 bytes time, 2 bytes date)
709 var timebytes = data.readUInt16LE(offset + consts.CENTIM);
710 var datebytes = data.readUInt16LE(offset + consts.CENTIM + 2);
711 this.time = parseZipTime(timebytes, datebytes);
712
713 // uncompressed file crc-32 value
714 this.crc = data.readUInt32LE(offset + consts.CENCRC);
715 // compressed size
716 this.compressedSize = data.readUInt32LE(offset + consts.CENSIZ);
717 // uncompressed size
718 this.size = data.readUInt32LE(offset + consts.CENLEN);
719 // filename length
720 this.fnameLen = data.readUInt16LE(offset + consts.CENNAM);
721 // extra field length
722 this.extraLen = data.readUInt16LE(offset + consts.CENEXT);
723 // file comment length
724 this.comLen = data.readUInt16LE(offset + consts.CENCOM);
725 // volume number start
726 this.diskStart = data.readUInt16LE(offset + consts.CENDSK);
727 // internal file attributes
728 this.inattr = data.readUInt16LE(offset + consts.CENATT);
729 // external file attributes
730 this.attr = data.readUInt32LE(offset + consts.CENATX);
731 // LOC header offset
732 this.offset = data.readUInt32LE(offset + consts.CENOFF);
733};
734
735ZipEntry.prototype.readDataHeader = function(data) {
736 // 30 bytes and should start with "PK\003\004"
737 if (data.readUInt32LE(0) != consts.LOCSIG) {
738 throw new Error('Invalid local header');
739 }
740 // version needed to extract
741 this.version = data.readUInt16LE(consts.LOCVER);
742 // general purpose bit flag
743 this.flags = data.readUInt16LE(consts.LOCFLG);
744 // compression method
745 this.method = data.readUInt16LE(consts.LOCHOW);
746 // modification time (2 bytes time ; 2 bytes date)
747 var timebytes = data.readUInt16LE(consts.LOCTIM);
748 var datebytes = data.readUInt16LE(consts.LOCTIM + 2);
749 this.time = parseZipTime(timebytes, datebytes);
750
751 // uncompressed file crc-32 value
752 this.crc = data.readUInt32LE(consts.LOCCRC) || this.crc;
753 // compressed size
754 var compressedSize = data.readUInt32LE(consts.LOCSIZ);
755 if (compressedSize && compressedSize !== consts.EF_ZIP64_OR_32) {
756 this.compressedSize = compressedSize;
757 }
758 // uncompressed size
759 var size = data.readUInt32LE(consts.LOCLEN);
760 if (size && size !== consts.EF_ZIP64_OR_32) {
761 this.size = size;
762 }
763 // filename length
764 this.fnameLen = data.readUInt16LE(consts.LOCNAM);
765 // extra field length
766 this.extraLen = data.readUInt16LE(consts.LOCEXT);
767};
768
769ZipEntry.prototype.read = function(data, offset) {
770 this.name = data.slice(offset, offset += this.fnameLen).toString();
771 var lastChar = data[offset - 1];
772 this.isDirectory = (lastChar == 47) || (lastChar == 92);
773
774 if (this.extraLen) {
775 this.readExtra(data, offset);
776 offset += this.extraLen;
777 }
778 this.comment = this.comLen ? data.slice(offset, offset + this.comLen).toString() : null;
779};
780
781ZipEntry.prototype.validateName = function() {
782 if (/\\|^\w+:|^\/|(^|\/)\.\.(\/|$)/.test(this.name)) {
783 throw new Error('Malicious entry: ' + this.name);
784 }
785};
786
787ZipEntry.prototype.readExtra = function(data, offset) {
788 var signature, size, maxPos = offset + this.extraLen;
789 while (offset < maxPos) {
790 signature = data.readUInt16LE(offset);
791 offset += 2;
792 size = data.readUInt16LE(offset);
793 offset += 2;
794 if (consts.ID_ZIP64 === signature) {
795 this.parseZip64Extra(data, offset, size);
796 }
797 offset += size;
798 }
799};
800
801ZipEntry.prototype.parseZip64Extra = function(data, offset, length) {
802 if (length >= 8 && this.size === consts.EF_ZIP64_OR_32) {
803 this.size = Util.readUInt64LE(data, offset);
804 offset += 8; length -= 8;
805 }
806 if (length >= 8 && this.compressedSize === consts.EF_ZIP64_OR_32) {
807 this.compressedSize = Util.readUInt64LE(data, offset);
808 offset += 8; length -= 8;
809 }
810 if (length >= 8 && this.offset === consts.EF_ZIP64_OR_32) {
811 this.offset = Util.readUInt64LE(data, offset);
812 offset += 8; length -= 8;
813 }
814 if (length >= 4 && this.diskStart === consts.EF_ZIP64_OR_16) {
815 this.diskStart = data.readUInt32LE(offset);
816 // offset += 4; length -= 4;
817 }
818};
819
820Object.defineProperty(ZipEntry.prototype, 'encrypted', {
821 get: function() { return (this.flags & consts.FLG_ENTRY_ENC) == consts.FLG_ENTRY_ENC; }
822});
823
824Object.defineProperty(ZipEntry.prototype, 'isFile', {
825 get: function() { return !this.isDirectory; }
826});
827
828// endregion
829
830// region FsRead
831
832var FsRead = function(fd, buffer, offset, length, position, callback) {
833 this.fd = fd;
834 this.buffer = buffer;
835 this.offset = offset;
836 this.length = length;
837 this.position = position;
838 this.callback = callback;
839 this.bytesRead = 0;
840 this.waiting = false;
841};
842
843FsRead.prototype.read = function(sync) {
844 if (StreamZip.debug) {
845 console.log('read', this.position, this.bytesRead, this.length, this.offset);
846 }
847 this.waiting = true;
848 var err;
849 if (sync) {
850 try {
851 var bytesRead = fs.readSync(this.fd, this.buffer, this.offset + this.bytesRead,
852 this.length - this.bytesRead, this.position + this.bytesRead);
853 } catch (e) {
854 err = e;
855 }
856 this.readCallback(sync, err, err ? bytesRead : null);
857 } else {
858 fs.read(this.fd, this.buffer, this.offset + this.bytesRead,
859 this.length - this.bytesRead, this.position + this.bytesRead,
860 this.readCallback.bind(this, sync));
861 }
862};
863
864FsRead.prototype.readCallback = function(sync, err, bytesRead) {
865 if (typeof bytesRead === 'number')
866 this.bytesRead += bytesRead;
867 if (err || !bytesRead || this.bytesRead === this.length) {
868 this.waiting = false;
869 return this.callback(err, this.bytesRead);
870 } else {
871 this.read(sync);
872 }
873};
874
875// endregion
876
877// region FileWindowBuffer
878
879var FileWindowBuffer = function(fd) {
880 this.position = 0;
881 this.buffer = Buffer.alloc(0);
882
883 var fsOp = null;
884
885 this.checkOp = function() {
886 if (fsOp && fsOp.waiting)
887 throw new Error('Operation in progress');
888 };
889
890 this.read = function(pos, length, callback) {
891 this.checkOp();
892 if (this.buffer.length < length)
893 this.buffer = Buffer.alloc(length);
894 this.position = pos;
895 fsOp = new FsRead(fd, this.buffer, 0, length, this.position, callback).read();
896 };
897
898 this.expandLeft = function(length, callback) {
899 this.checkOp();
900 this.buffer = Buffer.concat([Buffer.alloc(length), this.buffer]);
901 this.position -= length;
902 if (this.position < 0)
903 this.position = 0;
904 fsOp = new FsRead(fd, this.buffer, 0, length, this.position, callback).read();
905 };
906
907 this.expandRight = function(length, callback) {
908 this.checkOp();
909 var offset = this.buffer.length;
910 this.buffer = Buffer.concat([this.buffer, Buffer.alloc(length)]);
911 fsOp = new FsRead(fd, this.buffer, offset, length, this.position + offset, callback).read();
912 };
913
914 this.moveRight = function(length, callback, shift) {
915 this.checkOp();
916 if (shift) {
917 this.buffer.copy(this.buffer, 0, shift);
918 } else {
919 shift = 0;
920 }
921 this.position += shift;
922 fsOp = new FsRead(fd, this.buffer, this.buffer.length - shift, shift, this.position + this.buffer.length - shift, callback).read();
923 };
924};
925
926// endregion
927
928// region EntryDataReaderStream
929
930var EntryDataReaderStream = function(fd, offset, length) {
931 stream.Readable.prototype.constructor.call(this);
932 this.fd = fd;
933 this.offset = offset;
934 this.length = length;
935 this.pos = 0;
936 this.readCallback = this.readCallback.bind(this);
937};
938
939util.inherits(EntryDataReaderStream, stream.Readable);
940
941EntryDataReaderStream.prototype._read = function(n) {
942 var buffer = Buffer.alloc(Math.min(n, this.length - this.pos));
943 if (buffer.length) {
944 fs.read(this.fd, buffer, 0, buffer.length, this.offset + this.pos, this.readCallback);
945 } else {
946 this.push(null);
947 }
948};
949
950EntryDataReaderStream.prototype.readCallback = function(err, bytesRead, buffer) {
951 this.pos += bytesRead;
952 if (err) {
953 this.emit('error', err);
954 this.push(null);
955 } else if (!bytesRead) {
956 this.push(null);
957 } else {
958 if (bytesRead !== buffer.length)
959 buffer = buffer.slice(0, bytesRead);
960 this.push(buffer);
961 }
962};
963
964// endregion
965
966// region EntryVerifyStream
967
968var EntryVerifyStream = function(baseStm, crc, size) {
969 stream.Transform.prototype.constructor.call(this);
970 this.verify = new CrcVerify(crc, size);
971 var that = this;
972 baseStm.on('error', function(e) {
973 that.emit('error', e);
974 });
975};
976
977util.inherits(EntryVerifyStream, stream.Transform);
978
979EntryVerifyStream.prototype._transform = function(data, encoding, callback) {
980 var err;
981 try {
982 this.verify.data(data);
983 } catch (e) {
984 err = e;
985 }
986 callback(err, data);
987};
988
989// endregion
990
991// region CrcVerify
992
993var CrcVerify = function(crc, size) {
994 this.crc = crc;
995 this.size = size;
996 this.state = {
997 crc: ~0,
998 size: 0
999 };
1000};
1001
1002CrcVerify.prototype.data = function(data) {
1003 var crcTable = CrcVerify.getCrcTable();
1004 var crc = this.state.crc, off = 0, len = data.length;
1005 while (--len >= 0)
1006 crc = crcTable[(crc ^ data[off++]) & 0xff] ^ (crc >>> 8);
1007 this.state.crc = crc;
1008 this.state.size += data.length;
1009 if (this.state.size >= this.size) {
1010 var buf = Buffer.alloc(4);
1011 buf.writeInt32LE(~this.state.crc & 0xffffffff, 0);
1012 crc = buf.readUInt32LE(0);
1013 if (crc !== this.crc)
1014 throw new Error('Invalid CRC');
1015 if (this.state.size !== this.size)
1016 throw new Error('Invalid size');
1017 }
1018};
1019
1020CrcVerify.getCrcTable = function() {
1021 var crcTable = CrcVerify.crcTable;
1022 if (!crcTable) {
1023 CrcVerify.crcTable = crcTable = [];
1024 var b = Buffer.alloc(4);
1025 for (var n = 0; n < 256; n++) {
1026 var c = n;
1027 for (var k = 8; --k >= 0; )
1028 if ((c & 1) != 0) { c = 0xedb88320 ^ (c >>> 1); } else { c = c >>> 1; }
1029 if (c < 0) {
1030 b.writeInt32LE(c, 0);
1031 c = b.readUInt32LE(0);
1032 }
1033 crcTable[n] = c;
1034 }
1035 }
1036 return crcTable;
1037};
1038
1039// endregion
1040
1041// region Util
1042
1043var Util = {
1044 readUInt64LE: function(buffer, offset) {
1045 return (buffer.readUInt32LE(offset + 4) * 0x0000000100000000) + buffer.readUInt32LE(offset);
1046 }
1047};
1048
1049// endregion
1050
1051// region exports
1052
1053module.exports = StreamZip;
1054
1055// endregion