-
Notifications
You must be signed in to change notification settings - Fork 137
/
Copy pathstreamzip.js
1936 lines (1839 loc) · 69.6 KB
/
streamzip.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
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @license node-stream-zip | (c) 2020 Antelle | https://github.com/antelle/node-stream-zip/blob/master/LICENSE
* Portions copyright https://github.com/cthackers/adm-zip | https://raw.githubusercontent.com/cthackers/adm-zip/master/LICENSE
* Updated for PCjs with ES13 (ES2022) features and support for assorted "legacy" archive/compressed data formats
*/
import fs from 'fs';
import path from 'path';
import events from 'events';
import zlib from 'zlib';
import stream from 'stream';
import Structure from './structure.js';
import {LegacyArc, LegacyZip} from './legacyzip.js';
/**
* @typedef {Object} Config
* @property {string} file (filename; required, unless fd is specified)
* @property {string} password (decryption password; optional)
* @property {Buffer} buffer (buffer; optional, and if present, used instead of file/fd)
* @property {boolean} arcType (ARC file if 1, ZIP file if 2 or undefined; added for PCjs)
* @property {boolean} storeEntries (default is true; ie, always store entries)
* @property {boolean} skipEntryNameValidation (default is false; ie, always validate entry names)
* @property {string} nameEncoding (default is "utf8"; undocumented)
* @property {number} fd (file descriptor; undocumented as normally we open our own file descriptor)
* @property {number} chunkSize (size of internal file buffer, default is generally 1024; undocumented)
* @property {boolean} holdErrors (hold errors instead of throwing them; added for PCjs and LegacyZip support)
* @property {function()} printfDebug (optional debug logging function; added for PCjs)
*/
/**
* @class StreamZip
*/
export default class StreamZip extends events.EventEmitter {
/**
* Public class fields
*/
static TYPE_ARC = 1;
static TYPE_ZIP = 2;
static LocalHeader = new Structure("LocalHeader")
.field('signature', Structure.UINT32, {
'LOCSIG': 0x04034b50 // "PK\003\004" (local file header signature)
})
.field('version', Structure.UINT16) // version needed to extract
.field('flags', Structure.UINT16, { // general purpose bit flag
ENC: 0x0001, // encrypted file
COMP1: 0x0002, // compression option
COMP2: 0x0004, // compression option
DESC: 0x0008, // data descriptor
ENH: 0x0010, // enhanced deflation
STR: 0x0040, // strong encryption
LNG: 0x0400 // UNICODE encoding
})
.field('method', Structure.UINT16) // compression method
.field('time', Structure.UINT16) // modification time
.field('date', Structure.UINT16) // modification date
.field('crc', Structure.INT32) // uncompressed file CRC-32 value
.field('compressedSize',Structure.UINT32) // compressed size
.field('size', Structure.UINT32) // uncompressed size
.field('fnameLen', Structure.UINT16) // filename length
.field('extraLen', Structure.UINT16) // extra field length
.verifySize(30);
static ExtHeader = new Structure("ExtHeader")
.field('signature', Structure.UINT32, {
'EXTSIG': 0x08074b50 // "PK\007\008" (data descriptor signature)
})
.field('crc', Structure.INT32) // uncompressed file CRC-32 value
.field('compressedSize',Structure.UINT32) // compressed size
.field('size', Structure.UINT32) // uncompressed size
.verifySize(16);
static CentralHeader = new Structure("CentralHeader")
.field('signature', Structure.UINT32, {
'CENSIG': 0x02014b50 // "PK\001\002" (central file header signature)
})
.field('verMade', Structure.UINT16) // version made by
.field('version', Structure.UINT16) // version needed to extract
.field('flags', Structure.UINT16) // general purpose bit flag
.field('method', Structure.UINT16) // compression method
.field('time', Structure.UINT16) // modification time
.field('date', Structure.UINT16) // modification date
.field('crc', Structure.INT32) // uncompressed file CRC-32 value
.field('compressedSize',Structure.UINT32) // compressed size
.field('size', Structure.UINT32) // uncompressed size
.field('fnameLen', Structure.UINT16) // filename length
.field('extraLen', Structure.UINT16) // extra field length
.field('comLen', Structure.UINT16) // file comment length
.field('diskStart', Structure.UINT16) // disk number start
.field('intAttr', Structure.UINT16) // internal file attributes
.field('attr', Structure.UINT32) // external file attributes (host system dependent)
.field('offset', Structure.UINT32) // relative offset of local header
.verifySize(46);
static CentralEndHeader = new Structure("CentralEndHeader")
.field('signature', Structure.UINT32, {
'ENDSIG': 0x06054b50 // "PK\005\006" (end of central dir signature)
})
.field('diskNum', Structure.UINT16) // number of this disk
.field('diskStart', Structure.UINT16) // disk where central directory starts
.field('volumeEntries', Structure.UINT16) // number of entries on this disk
.field('totalEntries', Structure.UINT16) // total number of entries
.field('size', Structure.UINT32) // central directory size in bytes
.field('offset', Structure.UINT32) // offset of first CEN header
.field('commentLength', Structure.UINT16) // zip file comment length
.verifySize(22);
static MAXFILECOMMENT = 0xffff;
static Central64LocHeader = new Structure("Central64LocHeader")
.field('signature', Structure.UINT32,{
'ENDL64SIG': 0x07064b50 // "PK\006\007" (ZIP64 end of central directory locator)
})
.field('diskNum', Structure.UINT32) // number of this disk
.field('headerOffset', Structure.UINT64) // offset of the ZIP64 end of central directory record
.field('disks', Structure.UINT32) // total number of disks
.verifySize(20);
static Central64EndHeader = new Structure("Central64EndHeader")
.field('signature', Structure.UINT32, {
'END64SIG': 0x06064b50 // "PK\006\006" (ZIP64 end of central directory record)
})
.field('sizeEOCD', Structure.UINT64) // size of zip64 end of central directory record
.field('verMade', Structure.UINT16) // version made by
.field('version', Structure.UINT16) // version needed to extract
.field('diskNum', Structure.UINT32) // number of this disk
.field('diskStart', Structure.UINT32) // disk where central directory starts
.field('volumeEntries', Structure.UINT64) // number of entries on this disk
.field('totalEntries', Structure.UINT64) // total number of entries
.field('size', Structure.UINT64) // central directory size in bytes
.field('offset', Structure.UINT64) // offset of first CEN header
.verifySize(56);
static ArcHeader = new Structure("ArcHeader")
.field('signature', Structure.UINT8, {
'ARC_SIG': 0x1a // EOF
})
.field('type', Structure.UINT8, { // header type
'ARC_END': 0x00, // end of archive
'ARC_OLD': 0x01, // old archive header (unpacked, no 'size' field)
'ARC_UNP': 0x02, // new archive header (unpacked, 'size' == 'compressedSize')
'ARC_NR': 0x03, // non-repeat packing ("pack")
'ARC_HS': 0x04, // Huffman squeezing ("squeeze")
'ARC_LZ': 0x05, // LZ compression
'ARC_LZNR': 0x06, // LZ non-repeat compression
'ARC_LZNH': 0x07, // LZ with new hash
'ARC_LZC': 0x08, // LZ dynamic ("crunch")
'ARC_LZS': 0x09 // LZ dynamic ("squash")
})
.field('name', 13) // filename (null terminated)
.field('compressedSize',Structure.UINT32) // compressed size
.field('date', Structure.UINT16) // modification date
.field('time', Structure.UINT16) // modification time (date and time order is reversed from ZIP files)
.field('crc', Structure.UINT16) // CRC value
.field('size', Structure.UINT32) // uncompressed size (not present if type == ARC_OLD)
.verifySize(29);
/* Compression methods */
static ARC_UNP = -2; // unpacked (no compression)
static ARC_NR = -3; // non-repeat packing ("pack")
static ARC_HS = -4; // Huffman squeezing ("squeeze")
static ARC_LZ = -5; // LZ compression
static ARC_LZNR = -6; // LZ non-repeat compression
static ARC_LZNH = -7; // LZ with new hash
static ARC_LZC = -8; // LZ dynamic ("crunch")
static ARC_LZS = -9; // LZ dynamic ("squash")
static ZIP_STORE = 0; // no compression
static ZIP_SHRINK = 1; // shrink
static ZIP_REDUCE1 = 2; // reduce with compression factor 1
static ZIP_REDUCE2 = 3; // reduce with compression factor 2
static ZIP_REDUCE3 = 4; // reduce with compression factor 3
static ZIP_REDUCE4 = 5; // reduce with compression factor 4
static ZIP_IMPLODE = 6; // implode
static ZIP_DEFLATE = 8; // deflate
static ZIP_DEFLATE64 = 9; // deflate64
static ZIP_IMPLODE_DCL = 10; // PKWare DCL implode
static ZIP_BZIP2 = 12; // compressed using BZIP2
static ZIP_LZMA = 14; // LZMA
static ZIP_IBM_TERSE = 18; // compressed using IBM TERSE
static ZIP_IBM_LZ77 = 19; // IBM LZ77
/* 4.5 Extensible data fields */
static EF_ID = 0;
static EF_SIZE = 2;
/* Header IDs */
static ID_ZIP64 = 0x0001;
static ID_AVINFO = 0x0007;
static ID_PFS = 0x0008;
static ID_OS2 = 0x0009;
static ID_NTFS = 0x000a;
static ID_OPENVMS = 0x000c;
static ID_UNIX = 0x000d;
static ID_FORK = 0x000e;
static ID_PATCH = 0x000f;
static ID_X509_PKCS7 = 0x0014;
static ID_X509_CERTID_F = 0x0015;
static ID_X509_CERTID_C = 0x0016;
static ID_STRONGENC = 0x0017;
static ID_RECORD_MGT = 0x0018;
static ID_X509_PKCS7_RL = 0x0019;
static ID_IBM1 = 0x0065;
static ID_IBM2 = 0x0066;
static ID_POSZIP = 0x4690;
static EF_ZIP64_OR_32 = 0xffffffff;
static EF_ZIP64_OR_16 = 0xffff;
/**
* Private instance fields
*
* Most of the StreamZip instance data is private, but instead of prefixing everything with '#', explicitly
* private fields will be limited to those that conflict with public methods.
*/
#entries;
/**
* Most of the instance methods are private as well, but again, in the interest of simplicity, we'll just
* explicitly mark each public method in its comment header (wouldn't it be nice if all methods and properties
* in JavaScript classes could default to private unless explicitly declared public?)
*/
/**
* @this {StreamZip}
* @param {Config} config
*/
constructor(config)
{
super();
this.config = config;
this.opened = false; // true if WE opened the file (as opposed to the caller)
this.ready = false;
this.#entries = config.storeEntries !== false? {} : null,
this.fileName = config.file,
this.password = typeof config.password == "string"? config.password.toUpperCase() : null;
this.buffer = config.buffer;
this.arcType = config.arcType || StreamZip.TYPE_ZIP;
this.arcOffset = config.arcOffset || 0;
this.textDecoder = config.nameEncoding? new TextDecoder(config.nameEncoding) : null;
this.printfDebug = config.printfDebug || function() {};
/**
* Don't automatically call open() if the caller has provided a buffer, because in that case,
* all the initial reads are synchronous, and so the caller won't have a chance to set up its
* event handlers before we start emitting events.
*
* Personally, I don't think open() should have *ever* been automatic in the first place....
*/
if (!this.buffer) {
this.open();
}
Object.defineProperty(this, 'ready', {
get() {
return this.ready;
},
});
}
/**
* open()
*
* @this {StreamZip}
*/
open()
{
if (this.buffer) {
this.readFile();
}
else if (this.config.fd) {
this.fd = this.config.fd;
this.readFile();
} else {
fs.open(this.fileName, 'r', (err, f) => {
if (err) {
return this.emit('error', err);
}
this.fd = f;
this.opened = true;
this.readFile();
});
}
}
/**
* readFile()
*
* @this {StreamZip}
*/
readFile()
{
let readFileDone = function(archive) {
if (archive.arcType == StreamZip.TYPE_ARC) {
archive.readArcEntries();
} else {
archive.readCentralDirectory();
}
};
if (this.buffer) {
this.fileSize = this.chunkSize = this.buffer.length;
readFileDone(this);
} else {
fs.fstat(this.fd, (err, stat) => {
if (err) {
return this.emit('error', err);
}
this.fileSize = stat.size;
this.chunkSize = this.config.chunkSize || Math.round(this.fileSize / 1000);
this.chunkSize = Math.max(
Math.min(this.chunkSize, Math.min(128 * 1024, this.fileSize)), Math.min(1024, this.fileSize)
);
readFileDone(this);
});
}
}
/**
* readCentralDirectoryCallback()
*
* @this {StreamZip}
*/
readCentralDirectoryCallback(err, bytesRead)
{
if (err || !bytesRead) {
return this.emit('error', err || new Error('archive read failure'));
}
let pos = this.op.lastPos;
let bufferPosition = pos - this.op.win.position;
const buffer = this.op.win.buffer;
const minPos = this.op.minPos;
while (--pos >= minPos && --bufferPosition >= 0) {
if (buffer.length - bufferPosition >= 4 && buffer[bufferPosition] === this.op.firstByte) {
// quick check first signature byte
if (buffer.readUInt32LE(bufferPosition) === this.op.sig) {
this.op.lastBufferPosition = bufferPosition;
this.op.lastBytesRead = bytesRead;
this.op.complete();
return;
}
}
}
if (pos === minPos) {
return this.emit('error', new Error('bad archive'));
}
this.op.lastPos = pos + 1;
this.op.chunkSize *= 2;
if (pos <= minPos) {
return this.emit('error', new Error('bad archive'));
}
const expandLength = Math.min(this.op.chunkSize, pos - minPos);
this.op.win.expandLeft(expandLength, this.readCentralDirectoryCallback.bind(this));
}
/**
* readCentralDirectory()
*
* @this {StreamZip}
*/
readCentralDirectory()
{
const totalReadLength = this.buffer?
this.fileSize :
Math.min(StreamZip.CentralEndHeader.getSize() + StreamZip.MAXFILECOMMENT, this.fileSize);
this.op = {
totalReadLength,
minPos: this.fileSize - totalReadLength,
lastPos: this.fileSize,
chunkSize: Math.min(1024, this.chunkSize),
firstByte: StreamZip.CentralEndHeader.signature.ENDSIG & 0xff,
sig: StreamZip.CentralEndHeader.signature.ENDSIG,
complete: this.readCentralDirectoryComplete.bind(this),
};
if (this.buffer) {
this.op.win = {
buffer: this.buffer,
position: 0
};
this.readCentralDirectoryCallback(null, this.fileSize);
} else {
this.op.win = new FileWindowBuffer(this, "CentralDirectory");
this.op.win.read(this.fileSize - this.op.chunkSize, this.op.chunkSize, this.readCentralDirectoryCallback.bind(this));
}
}
/**
* readCentralDirectoryComplete()
*
* @this {StreamZip}
*/
readCentralDirectoryComplete()
{
const buffer = this.op.win.buffer;
const pos = this.op.lastBufferPosition;
try {
this.centralDirectory = new CentralDirectoryHeader();
this.centralDirectory.read(buffer.slice(pos, pos + StreamZip.CentralEndHeader.getSize()));
this.centralDirectory.headerOffset = this.op.win.position + pos;
if (this.centralDirectory.commentLength) {
this.comment = buffer
.slice(
pos + StreamZip.CentralEndHeader.getSize(),
pos + StreamZip.CentralEndHeader.getSize() + this.centralDirectory.commentLength
)
.toString();
} else {
this.comment = null;
}
this.entriesCount = this.centralDirectory.volumeEntries;
if ((this.centralDirectory.volumeEntries === StreamZip.EF_ZIP64_OR_16 && this.centralDirectory.totalEntries === StreamZip.EF_ZIP64_OR_16) ||
this.centralDirectory.size === StreamZip.EF_ZIP64_OR_32 || this.centralDirectory.offset === StreamZip.EF_ZIP64_OR_32) {
this.readZip64CentralDirectoryLocator();
} else {
this.readEntries();
}
} catch (err) {
this.emit('error', err);
}
}
/**
* readZip64CentralDirectoryLocator()
*
* @this {StreamZip}
*/
readZip64CentralDirectoryLocator()
{
const length = StreamZip.Central64LocHeader.getSize();
if (this.op.lastBufferPosition > length) {
this.op.lastBufferPosition -= length;
this.readZip64CentralDirectoryLocatorComplete();
} else {
this.op = {
win: this.op.win,
totalReadLength: length,
minPos: this.op.win.position - length,
lastPos: this.op.win.position,
chunkSize: this.op.chunkSize,
firstByte: StreamZip.ENDL64SIGFIRST,
sig: StreamZip.ENDL64SIG,
complete: this.readZip64CentralDirectoryLocatorComplete.bind(this),
};
this.op.win.read(this.op.lastPos - this.op.chunkSize, this.op.chunkSize, this.readCentralDirectoryCallback.bind(this));
}
}
/**
* readZip64CentralDirectoryLocatorComplete()
*
* @this {StreamZip}
*/
readZip64CentralDirectoryLocatorComplete()
{
const buffer = this.op.win.buffer;
const locHeader = new CentralDirectoryLoc64Header();
locHeader.read(
buffer.slice(this.op.lastBufferPosition, this.op.lastBufferPosition + StreamZip.Central64LocHeader.getSize())
);
const readLength = this.fileSize - locHeader.headerOffset;
this.op = {
win: this.op.win,
totalReadLength: readLength,
minPos: locHeader.headerOffset,
lastPos: this.op.lastPos,
chunkSize: this.op.chunkSize,
firstByte: StreamZip.Central64EndHeader.signature.END64SIG & 0xff,
sig: StreamZip.Central64EndHeader.signature.END64SIG,
complete: this.readZip64CentralDirectoryComplete.bind(this),
};
this.op.win.read(this.fileSize - this.op.chunkSize, this.op.chunkSize, this.readCentralDirectoryCallback.bind(this));
}
/**
* readZip64CentralDirectoryComplete()
*
* @this {StreamZip}
*/
readZip64CentralDirectoryComplete()
{
const buffer = this.op.win.buffer;
const zip64cd = new CentralDirectoryZip64Header();
zip64cd.read(buffer.slice(this.op.lastBufferPosition, this.op.lastBufferPosition + StreamZip.Central64EndHeader.getSize()));
this.centralDirectory.volumeEntries = zip64cd.volumeEntries;
this.centralDirectory.totalEntries = zip64cd.totalEntries;
this.centralDirectory.size = zip64cd.size;
this.centralDirectory.offset = zip64cd.offset;
this.entriesCount = zip64cd.volumeEntries;
this.readEntries();
}
/**
* readArcEntries()
*
* @this {StreamZip}
*/
readArcEntries()
{
let win;
if (this.buffer) {
win = { // fake FileWindowBuffer
buffer: this.buffer,
position: this.arcOffset,
avail: this.buffer.length - this.arcOffset
};
} else {
win = new FileWindowBuffer(this, "readArcEntries");
}
this.op = {
win,
pos: this.arcOffset,
chunkSize: this.chunkSize, // StreamZip.ArcHeader.getSize(),
entriesLeft: -1
};
this.entryTotal = 0; // used as a sanity check to make sure we didn't miss any entries
if (this.buffer) {
this.readArcEntriesCallback(null, 0);
} else {
this.op.win.read(this.op.pos, Math.min(this.op.chunkSize, this.fileSize - this.op.pos), this.readArcEntriesCallback.bind(this));
}
}
/**
* readArcEntriesCallback()
*
* @this {StreamZip}
*/
readArcEntriesCallback(err, bytesRead)
{
if (err) {
return this.emit('error', err);
}
const buffer = this.op.win.buffer;
let bufferPos = this.op.pos - this.op.win.position;
let bufferAvail = Math.min(this.op.win.avail + bytesRead, buffer.length - bufferPos);
const headerLen = StreamZip.ArcHeader.getSize();
try {
while (this.op.entriesLeft != 0) {
let entry = new ArcEntry(this, this.config.holdErrors);
if (!entry.getArcHeader(buffer, bufferPos, bufferAvail)) {
/**
* Too many ARC files are padded with garbage to enable this sanity check....
*
* if (this.entryTotal + 2 < this.fileSize) {
* this.emit('error', new Error("ARC entry total (" + this.entryTotal + ") does not match ARC size (" + this.fileSize + ")"));
* }
*/
break;
}
let entrySize = headerLen + entry.compressedSize;
entry.offset = this.op.win.position + bufferPos;
if (!this.config.skipEntryNameValidation) {
entry.validateName();
}
if (this.#entries) {
this.#entries[entry.name] = entry;
}
this.entryTotal += entrySize;
this.emit('entry', entry);
if (!--this.op.entriesLeft) break;
this.op.pos += entrySize;
bufferPos += entrySize;
bufferAvail -= entrySize;
if (bufferPos + headerLen > buffer.length) {
if (this.op.win.moveRight) {
this.op.win.moveRight(bufferPos, this.readArcEntriesCallback.bind(this));
this.op.move = true;
return;
}
}
}
this.emit('ready');
} catch (e) {
this.emit('error', e);
}
}
/**
* readEntries()
*
* @this {StreamZip}
*/
readEntries() {
this.op = {
pos: this.centralDirectory.offset,
chunkSize: this.chunkSize,
entriesLeft: this.centralDirectory.volumeEntries,
};
if (this.buffer) {
this.op.win = {
buffer: this.buffer,
position: 0
};
this.readEntriesCallback(null, this.fileSize);
} else {
this.op.win = new FileWindowBuffer(this, "readEntries");
this.op.win.read(this.op.pos, Math.min(this.chunkSize, this.fileSize - this.op.pos), this.readEntriesCallback.bind(this));
}
}
/**
* readEntriesCallback()
*
* @this {StreamZip}
*/
readEntriesCallback(err, bytesRead)
{
if (err || !bytesRead) {
return this.emit('error', err || new Error('ZIP entries read failure'));
}
let bufferPos = this.op.pos - this.op.win.position;
let entry = this.op.entry;
const buffer = this.op.win.buffer;
const bufferLength = buffer.length;
try {
while (this.op.entriesLeft > 0) {
if (!entry) {
entry = new ZipEntry(this, this.config.holdErrors);
entry.getCentralHeader(buffer, bufferPos);
entry.headerOffset = this.op.win.position + bufferPos;
this.op.entry = entry;
this.op.pos += StreamZip.CentralHeader.getSize();
bufferPos += StreamZip.CentralHeader.getSize();
}
const entryHeaderSize = entry.fnameLen + entry.extraLen + entry.comLen;
const advanceBytes = entryHeaderSize + (this.op.entriesLeft > 1? StreamZip.CentralHeader.getSize() : 0);
if (bufferLength - bufferPos < advanceBytes) {
this.op.win.moveRight(bufferPos, this.readEntriesCallback.bind(this));
this.op.move = true;
return;
}
entry.getEntryName(buffer, bufferPos, this.textDecoder);
if (!this.config.skipEntryNameValidation) {
entry.validateName();
}
if (this.#entries) {
this.#entries[entry.name] = entry;
}
this.emit('entry', entry);
this.op.entry = entry = null;
this.op.entriesLeft--;
this.op.pos += entryHeaderSize;
bufferPos += entryHeaderSize;
}
this.emit('ready');
} catch (e) {
this.emit('error', e);
}
}
/**
* checkEntriesExist(callback)
*
* @this {StreamZip}
* @param {function} callback
*/
checkEntriesExist(callback)
{
if (!this.#entries) {
let err = new Error('storeEntries disabled');
if (callback) {
callback(err);
return;
}
throw err;
}
}
/**
* entry(name)
*
* @public
* @this {StreamZip}
*/
entry(name)
{
this.checkEntriesExist();
return this.#entries[name];
}
/**
* entries()
*
* @public
* @this {StreamZip}
*/
entries()
{
this.checkEntriesExist();
return this.#entries;
}
/**
* stream()
*
* @public
* @this {StreamZip}
*/
stream(entry, callback)
{
return this.openEntry(
entry,
(err, entry) => {
if (err) {
return callback(err);
}
const offset = this.dataOffset(entry);
let entryStream = new EntryDataReaderStream(this, "stream", offset, entry.compressedSize);
if (entry.method === StreamZip.ZIP_STORE) {
// nothing to do
} else if (entry.method === StreamZip.ZIP_DEFLATE) {
entryStream = entryStream.pipe(zlib.createInflateRaw());
} else {
return callback(new Error("unsupported compression method (" + entry.method + ")"));
}
if (this.canVerifyCRC(entry)) {
entryStream = entryStream.pipe(
new EntryVerifyStream(entryStream, entry)
);
}
callback(null, entryStream);
},
false
);
}
/**
* entryDataSync()
*
* We now call entry.error() instead of throwing errors ourselves, to accommodate callers who want to
* hold errors instead of catching them. This also makes it possible for the caller to process as many
* GOOD entries as possible, even if some of them are BAD. Treating all errors as equally fatal is not
* the best design and is something this entire library should probably revisit. It's not clear what
* mixture of try/catch and emit error handlers the caller is supposed to use, because relying just on
* the emit 'error' handler means that any problem with a single entry can halt processing of the entire
* archive.
*
* @public
* @this {StreamZip}
* @param {ZipEntry} entry
* @returns {Buffer}
*/
entryDataSync(entry)
{
let dst;
let err = null;
this.openEntry(
entry,
(e, en) => {
err = e;
entry = en;
},
true
);
if (err) {
if (!entry) {
throw err;
}
entry.error(err);
return dst;
}
let src = Buffer.alloc(entry.compressedSize);
if (this.buffer) {
this.buffer.copy(src, 0, this.dataOffset(entry), this.dataOffset(entry) + entry.compressedSize);
} else {
new FsRead(this, "entryDataSync", src, 0, entry.compressedSize, this.dataOffset(entry), (e) => {
err = e;
}).read(true);
if (err) {
entry.error(err);
return dst;
}
}
/**
* The actual decompression is now inside a loop AND a try/catch block, to automatically retry
* decryption in case 1) a password was supplied but not actually required (the ARC file doesn't tell
* us one way or the other) or 2) the ARC contains a mixture of encrypted and unencrypted files.
*
* With ARC files, our only clue that no password (or a different password) is required is when
* decompression fails, and failure can take almost any form, since we may be feeding the decompressor
* garbage.
*
* In the rare case where we do make a 2nd attempt, re-running the password code will restore the
* src data to its original state, and entry.reset() will clear any logged errors from the 1st attempt.
*/
let attempts = 2; // maximum of two attempts
while (attempts--) {
try {
if (this.arcType != StreamZip.TYPE_ARC || !this.password) {
attempts = 0; // only one attempt for the normal case
} else {
/**
* TODO: decryption of password-protected files is limited to ARC archives, because
* the ARC implementation is simple and I haven't looked into how PKZIP implemented it yet.
*/
for (let off = 0; off < src.length; off++) {
src.writeUInt8(src.readUInt8(off) ^ this.password.charCodeAt(off % this.password.length), off);
}
/**
* ARC file headers don't have a "flags" field, but we still include a flags field in the entry object,
* and we borrow the "ENC" flag from the ZIP file header definition to track whether this particular file
* was encrypted.
*/
if (attempts) {
entry.flags |= StreamZip.LocalHeader.flags.ENC;
} else {
entry.reset(); // clear any errors from the previous attempt
entry.flags &= ~StreamZip.LocalHeader.flags.ENC;
}
}
let largeWindow, literalTree;
switch(entry.method) {
case StreamZip.ARC_UNP:
case StreamZip.ZIP_STORE:
dst = src;
break;
case StreamZip.ARC_NR: // aka "Pack"
dst = LegacyArc.unpackSync(src, entry.size).getOutput();
break;
case StreamZip.ARC_HS: // aka "Squeeze" (Huffman squeezing)
dst = LegacyArc.unsqueezeSync(src, entry.size).getOutput();
break;
case StreamZip.ARC_LZ: // aka "Crunch5" (LZ compression)
dst = LegacyArc.uncrunchSync(src, entry.size, 0).getOutput();
break;
case StreamZip.ARC_LZNR: // aka "Crunch6" (LZ non-repeat compression)
dst = LegacyArc.uncrunchSync(src, entry.size, 1).getOutput();
break;
case StreamZip.ARC_LZNH: // aka "Crunch7" (LZ with new hash)
dst = LegacyArc.uncrunchSync(src, entry.size, 2).getOutput();
break;
case StreamZip.ARC_LZC: // aka "Crush" (dynamic LZW)
dst = LegacyArc.uncrushSync(src, entry.size, false).getOutput();
break;
case StreamZip.ARC_LZS: // aka "Squash"
dst = LegacyArc.uncrushSync(src, entry.size, true).getOutput();
break;
case StreamZip.ZIP_SHRINK:
dst = LegacyZip.stretchSync(src, entry.size).getOutput();
break;
case StreamZip.ZIP_REDUCE1:
case StreamZip.ZIP_REDUCE2:
case StreamZip.ZIP_REDUCE3:
case StreamZip.ZIP_REDUCE4:
dst = LegacyZip.expandSync(src, entry.size, entry.method - StreamZip.ZIP_REDUCE1 + 1).getOutput();
break;
case StreamZip.ZIP_IMPLODE:
largeWindow = !!(entry.flags & StreamZip.LocalHeader.flags.COMP1);
literalTree = !!(entry.flags & StreamZip.LocalHeader.flags.COMP2);
dst = LegacyZip.explodeSync(src, entry.size, largeWindow, literalTree).getOutput();
break;
case StreamZip.ZIP_IMPLODE_DCL:
dst = LegacyZip.blastSync(src).getOutput();
break;
case StreamZip.ZIP_DEFLATE:
case StreamZip.ZIP_DEFLATE64:
dst = zlib.inflateRawSync(src);
break;
default:
attempts = 0;
break;
}
if (dst) break;
} catch(e) {
entry.error(e);
}
}
if (dst) {
if (dst.length !== entry.size) {
entry.error("expected " + entry.size + " bytes, received " + dst.length + " (method " + entry.method + ")");
}
else {
/**
* If the sizes didn't match, then it's pretty much a given that the CRCs won't match either,
* so let's cut down on unnecessary errors.
*/
if (this.arcType == StreamZip.TYPE_ARC) {
let crc = LegacyArc.getCRC(dst);
if (crc != entry.crc) {
entry.error("expected CRC 0x" + entry.crc.toString(16) + ", received 0x" + crc.toString(16));
}
} else {
if (this.canVerifyCRC(entry)) {
const verify = new CRCVerify(entry);
verify.data(dst);
}
}
}
}
else if (!entry.errors) {
if (dst !== undefined) {
entry.error("decompression failure");
} else {
entry.error("unsupported compression method (" + entry.method + ")");
}
}
return dst;
}
/**
* openEntry()
*
* @this {StreamZip}
*/
openEntry(entry, callback, sync)
{
if (typeof entry === 'string') {
this.checkEntriesExist(callback);
entry = this.#entries[entry];
if (!entry) {
return callback(new Error('entry not found'));
}
}
if (!entry.isFile) {
return callback(new Error('entry is not file'), entry);
}
if (this.arcType == StreamZip.TYPE_ARC) {
/**
* ARC files contain only one set of file headers, which we have already read,
* so all we have to do is return the entry.
*/
callback(null, entry);
}
else {
/**
* ZIP files have both central directory entries (which were used to create the list
* of entries) and local directory entries, which is what we read now.
*/
if (this.buffer) {
/**
* If we're using a buffer, we can simply use the buffer's data as the local header.
*/
let err = null;
try {
entry.getLocalHeader(this.buffer, entry.offset);
if (entry.encrypted) {
err = new Error('entry encrypted');
}
} catch (e) {
err = e;
}
return callback(err, entry);
}
if (!this.fd) {
return callback(new Error('archive closed'), entry);
}
const buffer = Buffer.alloc(StreamZip.LocalHeader.getSize());
new FsRead(this, "openEntry", buffer, 0, buffer.length, entry.offset, (err) => {
if (!err) {
try {
entry.getLocalHeader(buffer, 0);
if (entry.encrypted) {
err = new Error('entry encrypted');
}
} catch (e) {
err = e;
}
}
callback(err, entry);
}).read(sync);
}
}
/**
* dataOffset()
*
* @this {StreamZip}
*/
dataOffset(entry)
{
let sizeHeader = (this.arcType == StreamZip.TYPE_ARC? StreamZip.ArcHeader.getSize() : StreamZip.LocalHeader.getSize());
return entry.offset + sizeHeader + entry.fnameLen + entry.extraLen;
}
/**
* canVerifyCRC()
*
* @this {StreamZip}
* @returns {boolean}
*/
canVerifyCRC(entry)
{
// 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
return !(entry.flags & StreamZip.LocalHeader.flags.DESC);
}
/**
* createDirectories()
*
* @this {StreamZip}
*/
createDirectories(baseDir, dirs, callback)
{
if (!dirs.length) {
return callback();
}
let dir = dirs.shift();
dir = path.join(baseDir, path.join(...dir));
fs.mkdir(dir, { recursive: true }, (err) => {
if (err && err.code !== 'EEXIST') {
return callback(err);