-
Notifications
You must be signed in to change notification settings - Fork 45
/
index.js
826 lines (770 loc) · 32.5 KB
/
index.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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
var fs = require("fs");
var Transform = require("stream").Transform;
var PassThrough = require("stream").PassThrough;
var zlib = require("zlib");
var util = require("util");
var EventEmitter = require("events").EventEmitter;
var errorMonitor = require("events").errorMonitor;
var crc32 = require("buffer-crc32");
exports.ZipFile = ZipFile;
exports.dateToDosDateTime = dateToDosDateTime;
util.inherits(ZipFile, EventEmitter);
function ZipFile() {
this.outputStream = new PassThrough();
this.entries = [];
this.outputStreamCursor = 0;
this.ended = false; // .end() sets this
this.allDone = false; // set when we've written the last bytes
this.forceZip64Eocd = false; // configurable in .end()
this.errored = false;
this.on(errorMonitor, function() {
this.errored = true;
});
}
ZipFile.prototype.addFile = function(realPath, metadataPath, options) {
var self = this;
metadataPath = validateMetadataPath(metadataPath, false);
if (options == null) options = {};
if (shouldIgnoreAdding(self)) return;
var entry = new Entry(metadataPath, false, options);
self.entries.push(entry);
fs.stat(realPath, function(err, stats) {
if (err) return self.emit("error", err);
if (!stats.isFile()) return self.emit("error", new Error("not a file: " + realPath));
entry.uncompressedSize = stats.size;
if (options.mtime == null) entry.setLastModDate(stats.mtime);
if (options.mode == null) entry.setFileAttributesMode(stats.mode);
entry.setFileDataPumpFunction(function() {
var readStream = fs.createReadStream(realPath);
entry.state = Entry.FILE_DATA_IN_PROGRESS;
readStream.on("error", function(err) {
self.emit("error", err);
});
pumpFileDataReadStream(self, entry, readStream);
});
pumpEntries(self);
});
};
ZipFile.prototype.addReadStream = function(readStream, metadataPath, options) {
this.addReadStreamLazy(metadataPath, options, function(cb) {
cb(null, readStream);
});
};
ZipFile.prototype.addReadStreamLazy = function(metadataPath, options, getReadStreamFunction) {
var self = this;
if (typeof options === "function") {
getReadStreamFunction = options;
options = null;
}
if (options == null) options = {};
metadataPath = validateMetadataPath(metadataPath, false);
if (shouldIgnoreAdding(self)) return;
var entry = new Entry(metadataPath, false, options);
self.entries.push(entry);
entry.setFileDataPumpFunction(function() {
entry.state = Entry.FILE_DATA_IN_PROGRESS;
getReadStreamFunction(function(err, readStream) {
if (err) return self.emit("error", err);
pumpFileDataReadStream(self, entry, readStream);
});
});
pumpEntries(self);
};
ZipFile.prototype.addBuffer = function(buffer, metadataPath, options) {
var self = this;
metadataPath = validateMetadataPath(metadataPath, false);
if (buffer.length > 0x3fffffff) throw new Error("buffer too large: " + buffer.length + " > " + 0x3fffffff);
if (options == null) options = {};
if (options.size != null) throw new Error("options.size not allowed");
if (shouldIgnoreAdding(self)) return;
var entry = new Entry(metadataPath, false, options);
entry.uncompressedSize = buffer.length;
entry.crc32 = crc32.unsigned(buffer);
entry.crcAndFileSizeKnown = true;
self.entries.push(entry);
if (entry.compressionLevel === 0) {
setCompressedBuffer(buffer);
} else {
zlib.deflateRaw(buffer, {level:entry.compressionLevel}, function(err, compressedBuffer) {
setCompressedBuffer(compressedBuffer);
});
}
function setCompressedBuffer(compressedBuffer) {
entry.compressedSize = compressedBuffer.length;
entry.setFileDataPumpFunction(function() {
writeToOutputStream(self, compressedBuffer);
writeToOutputStream(self, entry.getDataDescriptor());
entry.state = Entry.FILE_DATA_DONE;
// don't call pumpEntries() recursively.
// (also, don't call process.nextTick recursively.)
setImmediate(function() {
pumpEntries(self);
});
});
pumpEntries(self);
}
};
ZipFile.prototype.addEmptyDirectory = function(metadataPath, options) {
var self = this;
metadataPath = validateMetadataPath(metadataPath, true);
if (options == null) options = {};
if (options.size != null) throw new Error("options.size not allowed");
if (options.compress != null) throw new Error("options.compress not allowed");
if (options.compressionLevel != null) throw new Error("options.compressionLevel not allowed");
if (shouldIgnoreAdding(self)) return;
var entry = new Entry(metadataPath, true, options);
self.entries.push(entry);
entry.setFileDataPumpFunction(function() {
writeToOutputStream(self, entry.getDataDescriptor());
entry.state = Entry.FILE_DATA_DONE;
pumpEntries(self);
});
pumpEntries(self);
};
var eocdrSignatureBuffer = bufferFrom([0x50, 0x4b, 0x05, 0x06]);
ZipFile.prototype.end = function(options, calculatedTotalSizeCallback) {
if (typeof options === "function") {
calculatedTotalSizeCallback = options;
options = null;
}
if (options == null) options = {};
if (this.ended) return;
this.ended = true;
if (this.errored) return;
this.calculatedTotalSizeCallback = calculatedTotalSizeCallback;
this.forceZip64Eocd = !!options.forceZip64Format;
if (options.comment) {
if (typeof options.comment === "string") {
this.comment = encodeCp437(options.comment);
} else {
// It should be a Buffer
this.comment = options.comment;
}
if (this.comment.length > 0xffff) throw new Error("comment is too large");
// gotta check for this, because the zipfile format is actually ambiguous.
if (bufferIncludes(this.comment, eocdrSignatureBuffer)) throw new Error("comment contains end of central directory record signature");
} else {
// no comment.
this.comment = EMPTY_BUFFER;
}
pumpEntries(this);
};
function writeToOutputStream(self, buffer) {
self.outputStream.write(buffer);
self.outputStreamCursor += buffer.length;
}
function pumpFileDataReadStream(self, entry, readStream) {
var crc32Watcher = new Crc32Watcher();
var uncompressedSizeCounter = new ByteCounter();
var compressor = entry.compressionLevel !== 0 ? new zlib.DeflateRaw({level:entry.compressionLevel}) : new PassThrough();
var compressedSizeCounter = new ByteCounter();
readStream.pipe(crc32Watcher)
.pipe(uncompressedSizeCounter)
.pipe(compressor)
.pipe(compressedSizeCounter)
.pipe(self.outputStream, {end: false});
compressedSizeCounter.on("end", function() {
entry.crc32 = crc32Watcher.crc32;
if (entry.uncompressedSize == null) {
entry.uncompressedSize = uncompressedSizeCounter.byteCount;
} else {
if (entry.uncompressedSize !== uncompressedSizeCounter.byteCount) return self.emit("error", new Error("file data stream has unexpected number of bytes"));
}
entry.compressedSize = compressedSizeCounter.byteCount;
self.outputStreamCursor += entry.compressedSize;
writeToOutputStream(self, entry.getDataDescriptor());
entry.state = Entry.FILE_DATA_DONE;
pumpEntries(self);
});
}
function determineCompressionLevel(options) {
if (options.compress != null && options.compressionLevel != null) {
if (!!options.compress !== !!options.compressionLevel) throw new Error("conflicting settings for compress and compressionLevel");
}
if (options.compressionLevel != null) return options.compressionLevel;
if (options.compress === false) return 0;
return 6;
}
function pumpEntries(self) {
if (self.allDone || self.errored) return;
// first check if calculatedTotalSize is finally known
if (self.ended && self.calculatedTotalSizeCallback != null) {
var calculatedTotalSize = calculateTotalSize(self);
if (calculatedTotalSize != null) {
// we have an answer
self.calculatedTotalSizeCallback(calculatedTotalSize);
self.calculatedTotalSizeCallback = null;
}
}
// pump entries
var entry = getFirstNotDoneEntry();
function getFirstNotDoneEntry() {
for (var i = 0; i < self.entries.length; i++) {
var entry = self.entries[i];
if (entry.state < Entry.FILE_DATA_DONE) return entry;
}
return null;
}
if (entry != null) {
// this entry is not done yet
if (entry.state < Entry.READY_TO_PUMP_FILE_DATA) return; // input file not open yet
if (entry.state === Entry.FILE_DATA_IN_PROGRESS) return; // we'll get there
// start with local file header
entry.relativeOffsetOfLocalHeader = self.outputStreamCursor;
var localFileHeader = entry.getLocalFileHeader();
writeToOutputStream(self, localFileHeader);
entry.doFileDataPump();
} else {
// all cought up on writing entries
if (self.ended) {
// head for the exit
self.offsetOfStartOfCentralDirectory = self.outputStreamCursor;
self.entries.forEach(function(entry) {
var centralDirectoryRecord = entry.getCentralDirectoryRecord();
writeToOutputStream(self, centralDirectoryRecord);
});
writeToOutputStream(self, getEndOfCentralDirectoryRecord(self));
self.outputStream.end();
self.allDone = true;
}
}
}
function calculateTotalSize(self) {
var pretendOutputCursor = 0;
var centralDirectorySize = 0;
for (var i = 0; i < self.entries.length; i++) {
var entry = self.entries[i];
// compression is too hard to predict
if (entry.compressionLevel !== 0) return -1;
if (entry.state >= Entry.READY_TO_PUMP_FILE_DATA) {
// if addReadStream was called without providing the size, we can't predict the total size
if (entry.uncompressedSize == null) return -1;
} else {
// if we're still waiting for fs.stat, we might learn the size someday
if (entry.uncompressedSize == null) return null;
}
// we know this for sure, and this is important to know if we need ZIP64 format.
entry.relativeOffsetOfLocalHeader = pretendOutputCursor;
var useZip64Format = entry.useZip64Format();
pretendOutputCursor += LOCAL_FILE_HEADER_FIXED_SIZE + entry.utf8FileName.length;
pretendOutputCursor += entry.uncompressedSize;
if (!entry.crcAndFileSizeKnown) {
// use a data descriptor
if (useZip64Format) {
pretendOutputCursor += ZIP64_DATA_DESCRIPTOR_SIZE;
} else {
pretendOutputCursor += DATA_DESCRIPTOR_SIZE;
}
}
centralDirectorySize += CENTRAL_DIRECTORY_RECORD_FIXED_SIZE + entry.utf8FileName.length + entry.fileComment.length;
if (!entry.forceDosTimestamp) {
centralDirectorySize += INFO_ZIP_UNIVERSAL_TIMESTAMP_EXTRA_FIELD_SIZE;
}
if (useZip64Format) {
centralDirectorySize += ZIP64_EXTENDED_INFORMATION_EXTRA_FIELD_SIZE;
}
}
var endOfCentralDirectorySize = 0;
if (self.forceZip64Eocd ||
self.entries.length >= 0xffff ||
centralDirectorySize >= 0xffff ||
pretendOutputCursor >= 0xffffffff) {
// use zip64 end of central directory stuff
endOfCentralDirectorySize += ZIP64_END_OF_CENTRAL_DIRECTORY_RECORD_SIZE + ZIP64_END_OF_CENTRAL_DIRECTORY_LOCATOR_SIZE;
}
endOfCentralDirectorySize += END_OF_CENTRAL_DIRECTORY_RECORD_SIZE + self.comment.length;
return pretendOutputCursor + centralDirectorySize + endOfCentralDirectorySize;
}
function shouldIgnoreAdding(self) {
if (self.ended) throw new Error("cannot add entries after calling end()");
if (self.errored) return true;
return false;
}
var ZIP64_END_OF_CENTRAL_DIRECTORY_RECORD_SIZE = 56;
var ZIP64_END_OF_CENTRAL_DIRECTORY_LOCATOR_SIZE = 20;
var END_OF_CENTRAL_DIRECTORY_RECORD_SIZE = 22;
function getEndOfCentralDirectoryRecord(self, actuallyJustTellMeHowLongItWouldBe) {
var needZip64Format = false;
var normalEntriesLength = self.entries.length;
if (self.forceZip64Eocd || self.entries.length >= 0xffff) {
normalEntriesLength = 0xffff;
needZip64Format = true;
}
var sizeOfCentralDirectory = self.outputStreamCursor - self.offsetOfStartOfCentralDirectory;
var normalSizeOfCentralDirectory = sizeOfCentralDirectory;
if (self.forceZip64Eocd || sizeOfCentralDirectory >= 0xffffffff) {
normalSizeOfCentralDirectory = 0xffffffff;
needZip64Format = true;
}
var normalOffsetOfStartOfCentralDirectory = self.offsetOfStartOfCentralDirectory;
if (self.forceZip64Eocd || self.offsetOfStartOfCentralDirectory >= 0xffffffff) {
normalOffsetOfStartOfCentralDirectory = 0xffffffff;
needZip64Format = true;
}
if (actuallyJustTellMeHowLongItWouldBe) {
if (needZip64Format) {
return (
ZIP64_END_OF_CENTRAL_DIRECTORY_RECORD_SIZE +
ZIP64_END_OF_CENTRAL_DIRECTORY_LOCATOR_SIZE +
END_OF_CENTRAL_DIRECTORY_RECORD_SIZE
);
} else {
return END_OF_CENTRAL_DIRECTORY_RECORD_SIZE;
}
}
var eocdrBuffer = bufferAlloc(END_OF_CENTRAL_DIRECTORY_RECORD_SIZE + self.comment.length);
// end of central dir signature 4 bytes (0x06054b50)
eocdrBuffer.writeUInt32LE(0x06054b50, 0);
// number of this disk 2 bytes
eocdrBuffer.writeUInt16LE(0, 4);
// number of the disk with the start of the central directory 2 bytes
eocdrBuffer.writeUInt16LE(0, 6);
// total number of entries in the central directory on this disk 2 bytes
eocdrBuffer.writeUInt16LE(normalEntriesLength, 8);
// total number of entries in the central directory 2 bytes
eocdrBuffer.writeUInt16LE(normalEntriesLength, 10);
// size of the central directory 4 bytes
eocdrBuffer.writeUInt32LE(normalSizeOfCentralDirectory, 12);
// offset of start of central directory with respect to the starting disk number 4 bytes
eocdrBuffer.writeUInt32LE(normalOffsetOfStartOfCentralDirectory, 16);
// .ZIP file comment length 2 bytes
eocdrBuffer.writeUInt16LE(self.comment.length, 20);
// .ZIP file comment (variable size)
self.comment.copy(eocdrBuffer, 22);
if (!needZip64Format) return eocdrBuffer;
// ZIP64 format
// ZIP64 End of Central Directory Record
var zip64EocdrBuffer = bufferAlloc(ZIP64_END_OF_CENTRAL_DIRECTORY_RECORD_SIZE);
// zip64 end of central dir signature 4 bytes (0x06064b50)
zip64EocdrBuffer.writeUInt32LE(0x06064b50, 0);
// size of zip64 end of central directory record 8 bytes
writeUInt64LE(zip64EocdrBuffer, ZIP64_END_OF_CENTRAL_DIRECTORY_RECORD_SIZE - 12, 4);
// version made by 2 bytes
zip64EocdrBuffer.writeUInt16LE(VERSION_MADE_BY, 12);
// version needed to extract 2 bytes
zip64EocdrBuffer.writeUInt16LE(VERSION_NEEDED_TO_EXTRACT_ZIP64, 14);
// number of this disk 4 bytes
zip64EocdrBuffer.writeUInt32LE(0, 16);
// number of the disk with the start of the central directory 4 bytes
zip64EocdrBuffer.writeUInt32LE(0, 20);
// total number of entries in the central directory on this disk 8 bytes
writeUInt64LE(zip64EocdrBuffer, self.entries.length, 24);
// total number of entries in the central directory 8 bytes
writeUInt64LE(zip64EocdrBuffer, self.entries.length, 32);
// size of the central directory 8 bytes
writeUInt64LE(zip64EocdrBuffer, sizeOfCentralDirectory, 40);
// offset of start of central directory with respect to the starting disk number 8 bytes
writeUInt64LE(zip64EocdrBuffer, self.offsetOfStartOfCentralDirectory, 48);
// zip64 extensible data sector (variable size)
// nothing in the zip64 extensible data sector
// ZIP64 End of Central Directory Locator
var zip64EocdlBuffer = bufferAlloc(ZIP64_END_OF_CENTRAL_DIRECTORY_LOCATOR_SIZE);
// zip64 end of central dir locator signature 4 bytes (0x07064b50)
zip64EocdlBuffer.writeUInt32LE(0x07064b50, 0);
// number of the disk with the start of the zip64 end of central directory 4 bytes
zip64EocdlBuffer.writeUInt32LE(0, 4);
// relative offset of the zip64 end of central directory record 8 bytes
writeUInt64LE(zip64EocdlBuffer, self.outputStreamCursor, 8);
// total number of disks 4 bytes
zip64EocdlBuffer.writeUInt32LE(1, 16);
return Buffer.concat([
zip64EocdrBuffer,
zip64EocdlBuffer,
eocdrBuffer,
]);
}
function validateMetadataPath(metadataPath, isDirectory) {
if (metadataPath === "") throw new Error("empty metadataPath");
metadataPath = metadataPath.replace(/\\/g, "/");
if (/^[a-zA-Z]:/.test(metadataPath) || /^\//.test(metadataPath)) throw new Error("absolute path: " + metadataPath);
if (metadataPath.split("/").indexOf("..") !== -1) throw new Error("invalid relative path: " + metadataPath);
var looksLikeDirectory = /\/$/.test(metadataPath);
if (isDirectory) {
// append a trailing '/' if necessary.
if (!looksLikeDirectory) metadataPath += "/";
} else {
if (looksLikeDirectory) throw new Error("file path cannot end with '/': " + metadataPath);
}
return metadataPath;
}
var EMPTY_BUFFER = bufferAlloc(0);
// this class is not part of the public API
function Entry(metadataPath, isDirectory, options) {
this.utf8FileName = bufferFrom(metadataPath);
if (this.utf8FileName.length > 0xffff) throw new Error("utf8 file name too long. " + utf8FileName.length + " > " + 0xffff);
this.isDirectory = isDirectory;
this.state = Entry.WAITING_FOR_METADATA;
this.setLastModDate(options.mtime != null ? options.mtime : new Date());
this.forceDosTimestamp = !!options.forceDosTimestamp;
if (options.mode != null) {
this.setFileAttributesMode(options.mode);
} else {
this.setFileAttributesMode(isDirectory ? 0o40775 : 0o100664);
}
if (isDirectory) {
this.crcAndFileSizeKnown = true;
this.crc32 = 0;
this.uncompressedSize = 0;
this.compressedSize = 0;
} else {
// unknown so far
this.crcAndFileSizeKnown = false;
this.crc32 = null;
this.uncompressedSize = null;
this.compressedSize = null;
if (options.size != null) this.uncompressedSize = options.size;
}
if (isDirectory) {
this.compressionLevel = 0;
} else {
this.compressionLevel = determineCompressionLevel(options);
}
this.forceZip64Format = !!options.forceZip64Format;
if (options.fileComment) {
if (typeof options.fileComment === "string") {
this.fileComment = bufferFrom(options.fileComment, "utf-8");
} else {
// It should be a Buffer
this.fileComment = options.fileComment;
}
if (this.fileComment.length > 0xffff) throw new Error("fileComment is too large");
} else {
// no comment.
this.fileComment = EMPTY_BUFFER;
}
}
Entry.WAITING_FOR_METADATA = 0;
Entry.READY_TO_PUMP_FILE_DATA = 1;
Entry.FILE_DATA_IN_PROGRESS = 2;
Entry.FILE_DATA_DONE = 3;
Entry.prototype.setLastModDate = function(date) {
this.mtime = date;
var dosDateTime = dateToDosDateTime(date);
this.lastModFileTime = dosDateTime.time;
this.lastModFileDate = dosDateTime.date;
};
Entry.prototype.setFileAttributesMode = function(mode) {
if ((mode & 0xffff) !== mode) throw new Error("invalid mode. expected: 0 <= " + mode + " <= " + 0xffff);
// http://unix.stackexchange.com/questions/14705/the-zip-formats-external-file-attribute/14727#14727
this.externalFileAttributes = (mode << 16) >>> 0;
};
// doFileDataPump() should not call pumpEntries() directly. see issue #9.
Entry.prototype.setFileDataPumpFunction = function(doFileDataPump) {
this.doFileDataPump = doFileDataPump;
this.state = Entry.READY_TO_PUMP_FILE_DATA;
};
Entry.prototype.useZip64Format = function() {
return (
(this.forceZip64Format) ||
(this.uncompressedSize != null && this.uncompressedSize > 0xfffffffe) ||
(this.compressedSize != null && this.compressedSize > 0xfffffffe) ||
(this.relativeOffsetOfLocalHeader != null && this.relativeOffsetOfLocalHeader > 0xfffffffe)
);
}
var LOCAL_FILE_HEADER_FIXED_SIZE = 30;
var VERSION_NEEDED_TO_EXTRACT_UTF8 = 20;
var VERSION_NEEDED_TO_EXTRACT_ZIP64 = 45;
// 3 = unix. 63 = spec version 6.3
var VERSION_MADE_BY = (3 << 8) | 63;
var FILE_NAME_IS_UTF8 = 1 << 11;
var UNKNOWN_CRC32_AND_FILE_SIZES = 1 << 3;
Entry.prototype.getLocalFileHeader = function() {
var crc32 = 0;
var compressedSize = 0;
var uncompressedSize = 0;
if (this.crcAndFileSizeKnown) {
crc32 = this.crc32;
compressedSize = this.compressedSize;
uncompressedSize = this.uncompressedSize;
}
var fixedSizeStuff = bufferAlloc(LOCAL_FILE_HEADER_FIXED_SIZE);
var generalPurposeBitFlag = FILE_NAME_IS_UTF8;
if (!this.crcAndFileSizeKnown) generalPurposeBitFlag |= UNKNOWN_CRC32_AND_FILE_SIZES;
// local file header signature 4 bytes (0x04034b50)
fixedSizeStuff.writeUInt32LE(0x04034b50, 0);
// version needed to extract 2 bytes
fixedSizeStuff.writeUInt16LE(VERSION_NEEDED_TO_EXTRACT_UTF8, 4);
// general purpose bit flag 2 bytes
fixedSizeStuff.writeUInt16LE(generalPurposeBitFlag, 6);
// compression method 2 bytes
fixedSizeStuff.writeUInt16LE(this.getCompressionMethod(), 8);
// last mod file time 2 bytes
fixedSizeStuff.writeUInt16LE(this.lastModFileTime, 10);
// last mod file date 2 bytes
fixedSizeStuff.writeUInt16LE(this.lastModFileDate, 12);
// crc-32 4 bytes
fixedSizeStuff.writeUInt32LE(crc32, 14);
// compressed size 4 bytes
fixedSizeStuff.writeUInt32LE(compressedSize, 18);
// uncompressed size 4 bytes
fixedSizeStuff.writeUInt32LE(uncompressedSize, 22);
// file name length 2 bytes
fixedSizeStuff.writeUInt16LE(this.utf8FileName.length, 26);
// extra field length 2 bytes
fixedSizeStuff.writeUInt16LE(0, 28);
return Buffer.concat([
fixedSizeStuff,
// file name (variable size)
this.utf8FileName,
// extra field (variable size)
// no extra fields
]);
};
var DATA_DESCRIPTOR_SIZE = 16;
var ZIP64_DATA_DESCRIPTOR_SIZE = 24;
Entry.prototype.getDataDescriptor = function() {
if (this.crcAndFileSizeKnown) {
// the Mac Archive Utility requires this not be present unless we set general purpose bit 3
return EMPTY_BUFFER;
}
if (!this.useZip64Format()) {
var buffer = bufferAlloc(DATA_DESCRIPTOR_SIZE);
// optional signature (required according to Archive Utility)
buffer.writeUInt32LE(0x08074b50, 0);
// crc-32 4 bytes
buffer.writeUInt32LE(this.crc32, 4);
// compressed size 4 bytes
buffer.writeUInt32LE(this.compressedSize, 8);
// uncompressed size 4 bytes
buffer.writeUInt32LE(this.uncompressedSize, 12);
return buffer;
} else {
// ZIP64 format
var buffer = bufferAlloc(ZIP64_DATA_DESCRIPTOR_SIZE);
// optional signature (unknown if anyone cares about this)
buffer.writeUInt32LE(0x08074b50, 0);
// crc-32 4 bytes
buffer.writeUInt32LE(this.crc32, 4);
// compressed size 8 bytes
writeUInt64LE(buffer, this.compressedSize, 8);
// uncompressed size 8 bytes
writeUInt64LE(buffer, this.uncompressedSize, 16);
return buffer;
}
};
var CENTRAL_DIRECTORY_RECORD_FIXED_SIZE = 46;
var INFO_ZIP_UNIVERSAL_TIMESTAMP_EXTRA_FIELD_SIZE = 9;
var ZIP64_EXTENDED_INFORMATION_EXTRA_FIELD_SIZE = 28;
Entry.prototype.getCentralDirectoryRecord = function() {
var fixedSizeStuff = bufferAlloc(CENTRAL_DIRECTORY_RECORD_FIXED_SIZE);
var generalPurposeBitFlag = FILE_NAME_IS_UTF8;
if (!this.crcAndFileSizeKnown) generalPurposeBitFlag |= UNKNOWN_CRC32_AND_FILE_SIZES;
var izutefBuffer = EMPTY_BUFFER;
if (!this.forceDosTimestamp) {
// Here is one specification for this: https://commons.apache.org/proper/commons-compress/apidocs/org/apache/commons/compress/archivers/zip/X5455_ExtendedTimestamp.html
// See also the Info-ZIP source code unix/unix.c:set_extra_field() and zipfile.c:ef_scan_ut_time().
izutefBuffer = bufferAlloc(INFO_ZIP_UNIVERSAL_TIMESTAMP_EXTRA_FIELD_SIZE);
// 0x5455 Short tag for this extra block type ("UT")
izutefBuffer.writeUInt16LE(0x5455, 0);
// TSize Short total data size for this block
izutefBuffer.writeUInt16LE(INFO_ZIP_UNIVERSAL_TIMESTAMP_EXTRA_FIELD_SIZE - 4, 2);
// See Info-ZIP source code zip.h for these constant values:
var EB_UT_FL_MTIME = (1 << 0);
var EB_UT_FL_ATIME = (1 << 1);
// Note that we set the atime flag despite not providing the atime field.
// The central directory version of this extra field is specified to never contain the atime field even when the flag is set.
// We set it to match the Info-ZIP behavior in order to minimize incompatibility with zip file readers that may have rigid input expectations.
// Flags Byte info bits
izutefBuffer.writeUInt8(EB_UT_FL_MTIME | EB_UT_FL_ATIME, 4);
// (ModTime) Long time of last modification (UTC/GMT)
var timestamp = Math.floor(this.mtime.getTime() / 1000);
if (timestamp < -0x80000000) timestamp = -0x80000000; // 1901-12-13T20:45:52.000Z
if (timestamp > 0x7fffffff) timestamp = 0x7fffffff; // 2038-01-19T03:14:07.000Z
izutefBuffer.writeUInt32LE(timestamp, 5);
}
var normalCompressedSize = this.compressedSize;
var normalUncompressedSize = this.uncompressedSize;
var normalRelativeOffsetOfLocalHeader = this.relativeOffsetOfLocalHeader;
var versionNeededToExtract = VERSION_NEEDED_TO_EXTRACT_UTF8;
var zeiefBuffer = EMPTY_BUFFER;
if (this.useZip64Format()) {
normalCompressedSize = 0xffffffff;
normalUncompressedSize = 0xffffffff;
normalRelativeOffsetOfLocalHeader = 0xffffffff;
versionNeededToExtract = VERSION_NEEDED_TO_EXTRACT_ZIP64;
// ZIP64 extended information extra field
zeiefBuffer = bufferAlloc(ZIP64_EXTENDED_INFORMATION_EXTRA_FIELD_SIZE);
// 0x0001 2 bytes Tag for this "extra" block type
zeiefBuffer.writeUInt16LE(0x0001, 0);
// Size 2 bytes Size of this "extra" block
zeiefBuffer.writeUInt16LE(ZIP64_EXTENDED_INFORMATION_EXTRA_FIELD_SIZE - 4, 2);
// Original Size 8 bytes Original uncompressed file size
writeUInt64LE(zeiefBuffer, this.uncompressedSize, 4);
// Compressed Size 8 bytes Size of compressed data
writeUInt64LE(zeiefBuffer, this.compressedSize, 12);
// Relative Header Offset 8 bytes Offset of local header record
writeUInt64LE(zeiefBuffer, this.relativeOffsetOfLocalHeader, 20);
// Disk Start Number 4 bytes Number of the disk on which this file starts
// (omit)
}
// central file header signature 4 bytes (0x02014b50)
fixedSizeStuff.writeUInt32LE(0x02014b50, 0);
// version made by 2 bytes
fixedSizeStuff.writeUInt16LE(VERSION_MADE_BY, 4);
// version needed to extract 2 bytes
fixedSizeStuff.writeUInt16LE(versionNeededToExtract, 6);
// general purpose bit flag 2 bytes
fixedSizeStuff.writeUInt16LE(generalPurposeBitFlag, 8);
// compression method 2 bytes
fixedSizeStuff.writeUInt16LE(this.getCompressionMethod(), 10);
// last mod file time 2 bytes
fixedSizeStuff.writeUInt16LE(this.lastModFileTime, 12);
// last mod file date 2 bytes
fixedSizeStuff.writeUInt16LE(this.lastModFileDate, 14);
// crc-32 4 bytes
fixedSizeStuff.writeUInt32LE(this.crc32, 16);
// compressed size 4 bytes
fixedSizeStuff.writeUInt32LE(normalCompressedSize, 20);
// uncompressed size 4 bytes
fixedSizeStuff.writeUInt32LE(normalUncompressedSize, 24);
// file name length 2 bytes
fixedSizeStuff.writeUInt16LE(this.utf8FileName.length, 28);
// extra field length 2 bytes
fixedSizeStuff.writeUInt16LE(izutefBuffer.length + zeiefBuffer.length, 30);
// file comment length 2 bytes
fixedSizeStuff.writeUInt16LE(this.fileComment.length, 32);
// disk number start 2 bytes
fixedSizeStuff.writeUInt16LE(0, 34);
// internal file attributes 2 bytes
fixedSizeStuff.writeUInt16LE(0, 36);
// external file attributes 4 bytes
fixedSizeStuff.writeUInt32LE(this.externalFileAttributes, 38);
// relative offset of local header 4 bytes
fixedSizeStuff.writeUInt32LE(normalRelativeOffsetOfLocalHeader, 42);
return Buffer.concat([
fixedSizeStuff,
// file name (variable size)
this.utf8FileName,
// extra field (variable size)
izutefBuffer,
zeiefBuffer,
// file comment (variable size)
this.fileComment,
]);
};
Entry.prototype.getCompressionMethod = function() {
var NO_COMPRESSION = 0;
var DEFLATE_COMPRESSION = 8;
return this.compressionLevel === 0 ? NO_COMPRESSION : DEFLATE_COMPRESSION;
};
// These are intentionally computed in the current system timezone
// to match how the DOS encoding operates in this library.
var minDosDate = new Date(1980, 0, 1);
var maxDosDate = new Date(2107, 11, 31, 23, 59, 58);
function dateToDosDateTime(jsDate) {
// Clamp out of bounds timestamps.
if (jsDate < minDosDate) jsDate = minDosDate;
else if (jsDate > maxDosDate) jsDate = maxDosDate;
var date = 0;
date |= jsDate.getDate() & 0x1f; // 1-31
date |= ((jsDate.getMonth() + 1) & 0xf) << 5; // 0-11, 1-12
date |= ((jsDate.getFullYear() - 1980) & 0x7f) << 9; // 0-128, 1980-2108
var time = 0;
time |= Math.floor(jsDate.getSeconds() / 2); // 0-59, 0-29 (lose odd numbers)
time |= (jsDate.getMinutes() & 0x3f) << 5; // 0-59
time |= (jsDate.getHours() & 0x1f) << 11; // 0-23
return {date: date, time: time};
}
function writeUInt64LE(buffer, n, offset) {
// can't use bitshift here, because JavaScript only allows bitshifting on 32-bit integers.
var high = Math.floor(n / 0x100000000);
var low = n % 0x100000000;
buffer.writeUInt32LE(low, offset);
buffer.writeUInt32LE(high, offset + 4);
}
function defaultCallback(err) {
if (err) throw err;
}
util.inherits(ByteCounter, Transform);
function ByteCounter(options) {
Transform.call(this, options);
this.byteCount = 0;
}
ByteCounter.prototype._transform = function(chunk, encoding, cb) {
this.byteCount += chunk.length;
cb(null, chunk);
};
util.inherits(Crc32Watcher, Transform);
function Crc32Watcher(options) {
Transform.call(this, options);
this.crc32 = 0;
}
Crc32Watcher.prototype._transform = function(chunk, encoding, cb) {
this.crc32 = crc32.unsigned(chunk, this.crc32);
cb(null, chunk);
};
var cp437 = '\u0000☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼ !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~⌂ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ ';
if (cp437.length !== 256) throw new Error("assertion failure");
var reverseCp437 = null;
function encodeCp437(string) {
if (/^[\x20-\x7e]*$/.test(string)) {
// CP437, ASCII, and UTF-8 overlap in this range.
return bufferFrom(string, "utf-8");
}
// This is the slow path.
if (reverseCp437 == null) {
// cache this once
reverseCp437 = {};
for (var i = 0; i < cp437.length; i++) {
reverseCp437[cp437[i]] = i;
}
}
var result = bufferAlloc(string.length);
for (var i = 0; i < string.length; i++) {
var b = reverseCp437[string[i]];
if (b == null) throw new Error("character not encodable in CP437: " + JSON.stringify(string[i]));
result[i] = b;
}
return result;
}
function bufferAlloc(size) {
bufferAlloc = modern;
try {
return bufferAlloc(size);
} catch (e) {
bufferAlloc = legacy;
return bufferAlloc(size);
}
function modern(size) {
return Buffer.allocUnsafe(size);
}
function legacy(size) {
return new Buffer(size);
}
}
function bufferFrom(something, encoding) {
bufferFrom = modern;
try {
return bufferFrom(something, encoding);
} catch (e) {
bufferFrom = legacy;
return bufferFrom(something, encoding);
}
function modern(something, encoding) {
return Buffer.from(something, encoding);
}
function legacy(something, encoding) {
return new Buffer(something, encoding);
}
}
function bufferIncludes(buffer, content) {
bufferIncludes = modern;
try {
return bufferIncludes(buffer, content);
} catch (e) {
bufferIncludes = legacy;
return bufferIncludes(buffer, content);
}
function modern(buffer, content) {
return buffer.includes(content);
}
function legacy(buffer, content) {
for (var i = 0; i <= buffer.length - content.length; i++) {
for (var j = 0;; j++) {
if (j === content.length) return true;
if (buffer[i + j] !== content[j]) break;
}
}
return false;
}
}