-
Notifications
You must be signed in to change notification settings - Fork 220
/
ZipFS.ts
998 lines (951 loc) · 29.5 KB
/
ZipFS.ts
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
import { ApiError, ErrorCode } from '../ApiError';
import { Stats, FileType } from '../stats';
import { SynchronousFileSystem, type FileSystem, FileSystemMetadata } from '../filesystem';
import { File, FileFlag, ActionType } from '../file';
import { NoSyncFile } from '../generic/preload_file';
import { copyingSlice, bufferValidator } from '../utils';
import { inflateRawSync } from 'zlib';
import { FileIndex, DirInode, FileInode, isDirInode, isFileInode } from '../generic/file_index';
import type { Buffer } from 'buffer';
import { CreateBackend, type BackendOptions } from './backend';
/**
* 8-bit ASCII with the extended character set. Unlike regular ASCII, we do not mask the high bits.
* @see http://en.wikipedia.org/wiki/Extended_ASCII
*/
const extendedASCIIChars = [
'\u00C7',
'\u00FC',
'\u00E9',
'\u00E2',
'\u00E4',
'\u00E0',
'\u00E5',
'\u00E7',
'\u00EA',
'\u00EB',
'\u00E8',
'\u00EF',
'\u00EE',
'\u00EC',
'\u00C4',
'\u00C5',
'\u00C9',
'\u00E6',
'\u00C6',
'\u00F4',
'\u00F6',
'\u00F2',
'\u00FB',
'\u00F9',
'\u00FF',
'\u00D6',
'\u00DC',
'\u00F8',
'\u00A3',
'\u00D8',
'\u00D7',
'\u0192',
'\u00E1',
'\u00ED',
'\u00F3',
'\u00FA',
'\u00F1',
'\u00D1',
'\u00AA',
'\u00BA',
'\u00BF',
'\u00AE',
'\u00AC',
'\u00BD',
'\u00BC',
'\u00A1',
'\u00AB',
'\u00BB',
'_',
'_',
'_',
'\u00A6',
'\u00A6',
'\u00C1',
'\u00C2',
'\u00C0',
'\u00A9',
'\u00A6',
'\u00A6',
'+',
'+',
'\u00A2',
'\u00A5',
'+',
'+',
'-',
'-',
'+',
'-',
'+',
'\u00E3',
'\u00C3',
'+',
'+',
'-',
'-',
'\u00A6',
'-',
'+',
'\u00A4',
'\u00F0',
'\u00D0',
'\u00CA',
'\u00CB',
'\u00C8',
'i',
'\u00CD',
'\u00CE',
'\u00CF',
'+',
'+',
'_',
'_',
'\u00A6',
'\u00CC',
'_',
'\u00D3',
'\u00DF',
'\u00D4',
'\u00D2',
'\u00F5',
'\u00D5',
'\u00B5',
'\u00FE',
'\u00DE',
'\u00DA',
'\u00DB',
'\u00D9',
'\u00FD',
'\u00DD',
'\u00AF',
'\u00B4',
'\u00AD',
'\u00B1',
'_',
'\u00BE',
'\u00B6',
'\u00A7',
'\u00F7',
'\u00B8',
'\u00B0',
'\u00A8',
'\u00B7',
'\u00B9',
'\u00B3',
'\u00B2',
'_',
' ',
];
/**
* Maps CompressionMethod => function that decompresses.
* @hidden
*/
const decompressionMethods: { [method: number]: (data: Buffer, compressedSize: number, uncompressedSize: number, flags: number) => Buffer } = {};
/**
* 4.4.2.2: Indicates the compatibiltiy of a file's external attributes.
*/
export enum ExternalFileAttributeType {
MSDOS = 0,
AMIGA = 1,
OPENVMS = 2,
UNIX = 3,
VM_CMS = 4,
ATARI_ST = 5,
OS2_HPFS = 6,
MAC = 7,
Z_SYSTEM = 8,
CP_M = 9,
NTFS = 10,
MVS = 11,
VSE = 12,
ACORN_RISC = 13,
VFAT = 14,
ALT_MVS = 15,
BEOS = 16,
TANDEM = 17,
OS_400 = 18,
OSX = 19,
}
/**
* 4.4.5
*/
export enum CompressionMethod {
STORED = 0, // The file is stored (no compression)
SHRUNK = 1, // The file is Shrunk
REDUCED_1 = 2, // The file is Reduced with compression factor 1
REDUCED_2 = 3, // The file is Reduced with compression factor 2
REDUCED_3 = 4, // The file is Reduced with compression factor 3
REDUCED_4 = 5, // The file is Reduced with compression factor 4
IMPLODE = 6, // The file is Imploded
DEFLATE = 8, // The file is Deflated
DEFLATE64 = 9, // Enhanced Deflating using Deflate64(tm)
TERSE_OLD = 10, // PKWARE Data Compression Library Imploding (old IBM TERSE)
BZIP2 = 12, // File is compressed using BZIP2 algorithm
LZMA = 14, // LZMA (EFS)
TERSE_NEW = 18, // File is compressed using IBM TERSE (new)
LZ77 = 19, // IBM LZ77 z Architecture (PFS)
WAVPACK = 97, // WavPack compressed data
PPMD = 98, // PPMd version I, Rev 1
}
/**
* Converts the input time and date in MS-DOS format into a JavaScript Date
* object.
* @hidden
*/
function msdos2date(time: number, date: number): Date {
// MS-DOS Date
// |0 0 0 0 0|0 0 0 0|0 0 0 0 0 0 0
// D (1-31) M (1-23) Y (from 1980)
const day = date & 0x1f;
// JS date is 0-indexed, DOS is 1-indexed.
const month = ((date >> 5) & 0xf) - 1;
const year = (date >> 9) + 1980;
// MS DOS Time
// |0 0 0 0 0|0 0 0 0 0 0|0 0 0 0 0
// Second Minute Hour
const second = time & 0x1f;
const minute = (time >> 5) & 0x3f;
const hour = time >> 11;
return new Date(year, month, day, hour, minute, second);
}
/**
* Safely returns the string from the buffer, even if it is 0 bytes long.
* (Normally, calling toString() on a buffer with start === end causes an
* exception).
* @hidden
*/
function safeToString(buff: Buffer, useUTF8: boolean, start: number, length: number): string {
if (length === 0) {
return '';
} else if (useUTF8) {
return buff.toString('utf8', start, start + length);
} else {
return [...buff].map(char => (char > 0x7f ? extendedASCIIChars[char - 128] : String.fromCharCode(char))).join();
}
}
/*
4.3.6 Overall .ZIP file format:
[local file header 1]
[encryption header 1]
[file data 1]
[data descriptor 1]
.
.
.
[local file header n]
[encryption header n]
[file data n]
[data descriptor n]
[archive decryption header]
[archive extra data record]
[central directory header 1]
.
.
.
[central directory header n]
[zip64 end of central directory record]
[zip64 end of central directory locator]
[end of central directory record]
*/
/**
* 4.3.7 Local file header:
*
* local file header signature 4 bytes (0x04034b50)
* version needed to extract 2 bytes
* general purpose bit flag 2 bytes
* compression method 2 bytes
* last mod file time 2 bytes
* last mod file date 2 bytes
* crc-32 4 bytes
* compressed size 4 bytes
* uncompressed size 4 bytes
* file name length 2 bytes
* extra field length 2 bytes
*
* file name (variable size)
* extra field (variable size)
*/
export class FileHeader {
constructor(private data: Buffer) {
if (data.readUInt32LE(0) !== 0x04034b50) {
throw new ApiError(ErrorCode.EINVAL, 'Invalid Zip file: Local file header has invalid signature: ' + this.data.readUInt32LE(0));
}
}
public versionNeeded(): number {
return this.data.readUInt16LE(4);
}
public flags(): number {
return this.data.readUInt16LE(6);
}
public compressionMethod(): CompressionMethod {
return this.data.readUInt16LE(8);
}
public lastModFileTime(): Date {
// Time and date is in MS-DOS format.
return msdos2date(this.data.readUInt16LE(10), this.data.readUInt16LE(12));
}
public rawLastModFileTime(): number {
return this.data.readUInt32LE(10);
}
public crc32(): number {
return this.data.readUInt32LE(14);
}
/**
* These two values are COMPLETELY USELESS.
*
* Section 4.4.9:
* If bit 3 of the general purpose bit flag is set,
* these fields are set to zero in the local header and the
* correct values are put in the data descriptor and
* in the central directory.
*
* So we'll just use the central directory's values.
*/
// public compressedSize(): number { return this.data.readUInt32LE(18); }
// public uncompressedSize(): number { return this.data.readUInt32LE(22); }
public fileNameLength(): number {
return this.data.readUInt16LE(26);
}
public extraFieldLength(): number {
return this.data.readUInt16LE(28);
}
public fileName(): string {
return safeToString(this.data, this.useUTF8(), 30, this.fileNameLength());
}
public extraField(): Buffer {
const start = 30 + this.fileNameLength();
return this.data.subarray(start, start + this.extraFieldLength());
}
public totalSize(): number {
return 30 + this.fileNameLength() + this.extraFieldLength();
}
public useUTF8(): boolean {
return (this.flags() & 0x800) === 0x800;
}
}
/**
* 4.3.8 File data
*
* Immediately following the local header for a file
* SHOULD be placed the compressed or stored data for the file.
* If the file is encrypted, the encryption header for the file
* SHOULD be placed after the local header and before the file
* data. The series of [local file header][encryption header]
* [file data][data descriptor] repeats for each file in the
* .ZIP archive.
*
* Zero-byte files, directories, and other file types that
* contain no content MUST not include file data.
*/
export class FileData {
constructor(private header: FileHeader, private record: CentralDirectory, private data: Buffer) {}
public decompress(): Buffer {
// Check the compression
const compressionMethod: CompressionMethod = this.header.compressionMethod();
const fcn = decompressionMethods[compressionMethod];
if (fcn) {
return fcn(this.data, this.record.compressedSize(), this.record.uncompressedSize(), this.record.flag());
} else {
let name: string = CompressionMethod[compressionMethod];
if (!name) {
name = `Unknown: ${compressionMethod}`;
}
throw new ApiError(ErrorCode.EINVAL, `Invalid compression method on file '${this.header.fileName()}': ${name}`);
}
}
public getHeader(): FileHeader {
return this.header;
}
public getRecord(): CentralDirectory {
return this.record;
}
public getRawData(): Buffer {
return this.data;
}
}
/**
* 4.3.9 Data descriptor:
*
* crc-32 4 bytes
* compressed size 4 bytes
* uncompressed size 4 bytes
*/
export class DataDescriptor {
constructor(private data: Buffer) {}
public crc32(): number {
return this.data.readUInt32LE(0);
}
public compressedSize(): number {
return this.data.readUInt32LE(4);
}
public uncompressedSize(): number {
return this.data.readUInt32LE(8);
}
}
/*
` 4.3.10 Archive decryption header:
4.3.10.1 The Archive Decryption Header is introduced in version 6.2
of the ZIP format specification. This record exists in support
of the Central Directory Encryption Feature implemented as part of
the Strong Encryption Specification as described in this document.
When the Central Directory Structure is encrypted, this decryption
header MUST precede the encrypted data segment.
*/
/**
* 4.3.11 Archive extra data record:
*
* archive extra data signature 4 bytes (0x08064b50)
* extra field length 4 bytes
* extra field data (variable size)
*
* 4.3.11.1 The Archive Extra Data Record is introduced in version 6.2
* of the ZIP format specification. This record MAY be used in support
* of the Central Directory Encryption Feature implemented as part of
* the Strong Encryption Specification as described in this document.
* When present, this record MUST immediately precede the central
* directory data structure.
*/
export class ArchiveExtraDataRecord {
constructor(private data: Buffer) {
if (this.data.readUInt32LE(0) !== 0x08064b50) {
throw new ApiError(ErrorCode.EINVAL, 'Invalid archive extra data record signature: ' + this.data.readUInt32LE(0));
}
}
public length(): number {
return this.data.readUInt32LE(4);
}
public extraFieldData(): Buffer {
return this.data.subarray(8, 8 + this.length());
}
}
/**
* 4.3.13 Digital signature:
*
* header signature 4 bytes (0x05054b50)
* size of data 2 bytes
* signature data (variable size)
*
* With the introduction of the Central Directory Encryption
* feature in version 6.2 of this specification, the Central
* Directory Structure MAY be stored both compressed and encrypted.
* Although not required, it is assumed when encrypting the
* Central Directory Structure, that it will be compressed
* for greater storage efficiency. Information on the
* Central Directory Encryption feature can be found in the section
* describing the Strong Encryption Specification. The Digital
* Signature record will be neither compressed nor encrypted.
*/
export class DigitalSignature {
constructor(private data: Buffer) {
if (this.data.readUInt32LE(0) !== 0x05054b50) {
throw new ApiError(ErrorCode.EINVAL, 'Invalid digital signature signature: ' + this.data.readUInt32LE(0));
}
}
public size(): number {
return this.data.readUInt16LE(4);
}
public signatureData(): Buffer {
return this.data.subarray(6, 6 + this.size());
}
}
/**
* 4.3.12 Central directory structure:
*
* central file header signature 4 bytes (0x02014b50)
* version made by 2 bytes
* version needed to extract 2 bytes
* general purpose bit flag 2 bytes
* compression method 2 bytes
* last mod file time 2 bytes
* last mod file date 2 bytes
* crc-32 4 bytes
* compressed size 4 bytes
* uncompressed size 4 bytes
* file name length 2 bytes
* extra field length 2 bytes
* file comment length 2 bytes
* disk number start 2 bytes
* internal file attributes 2 bytes
* external file attributes 4 bytes
* relative offset of local header 4 bytes
*
* file name (variable size)
* extra field (variable size)
* file comment (variable size)
*/
export class CentralDirectory {
// Optimization: The filename is frequently read, so stash it here.
private _filename: string;
constructor(private zipData: Buffer, private data: Buffer) {
// Sanity check.
if (this.data.readUInt32LE(0) !== 0x02014b50) {
throw new ApiError(ErrorCode.EINVAL, `Invalid Zip file: Central directory record has invalid signature: ${this.data.readUInt32LE(0)}`);
}
this._filename = this.produceFilename();
}
public versionMadeBy(): number {
return this.data.readUInt16LE(4);
}
public versionNeeded(): number {
return this.data.readUInt16LE(6);
}
public flag(): number {
return this.data.readUInt16LE(8);
}
public compressionMethod(): CompressionMethod {
return this.data.readUInt16LE(10);
}
public lastModFileTime(): Date {
// Time and date is in MS-DOS format.
return msdos2date(this.data.readUInt16LE(12), this.data.readUInt16LE(14));
}
public rawLastModFileTime(): number {
return this.data.readUInt32LE(12);
}
public crc32(): number {
return this.data.readUInt32LE(16);
}
public compressedSize(): number {
return this.data.readUInt32LE(20);
}
public uncompressedSize(): number {
return this.data.readUInt32LE(24);
}
public fileNameLength(): number {
return this.data.readUInt16LE(28);
}
public extraFieldLength(): number {
return this.data.readUInt16LE(30);
}
public fileCommentLength(): number {
return this.data.readUInt16LE(32);
}
public diskNumberStart(): number {
return this.data.readUInt16LE(34);
}
public internalAttributes(): number {
return this.data.readUInt16LE(36);
}
public externalAttributes(): number {
return this.data.readUInt32LE(38);
}
public headerRelativeOffset(): number {
return this.data.readUInt32LE(42);
}
public produceFilename(): string {
/*
4.4.17.1 claims:
* All slashes are forward ('/') slashes.
* Filename doesn't begin with a slash.
* No drive letters or any nonsense like that.
* If filename is missing, the input came from standard input.
Unfortunately, this isn't true in practice. Some Windows zip utilities use
a backslash here, but the correct Unix-style path in file headers.
To avoid seeking all over the file to recover the known-good filenames
from file headers, we simply convert '/' to '\' here.
*/
const fileName: string = safeToString(this.data, this.useUTF8(), 46, this.fileNameLength());
return fileName.replace(/\\/g, '/');
}
public fileName(): string {
return this._filename;
}
public rawFileName(): Buffer {
return this.data.subarray(46, 46 + this.fileNameLength());
}
public extraField(): Buffer {
const start = 44 + this.fileNameLength();
return this.data.subarray(start, start + this.extraFieldLength());
}
public fileComment(): string {
const start = 46 + this.fileNameLength() + this.extraFieldLength();
return safeToString(this.data, this.useUTF8(), start, this.fileCommentLength());
}
public rawFileComment(): Buffer {
const start = 46 + this.fileNameLength() + this.extraFieldLength();
return this.data.subarray(start, start + this.fileCommentLength());
}
public totalSize(): number {
return 46 + this.fileNameLength() + this.extraFieldLength() + this.fileCommentLength();
}
public isDirectory(): boolean {
// NOTE: This assumes that the zip file implementation uses the lower byte
// of external attributes for DOS attributes for
// backwards-compatibility. This is not mandated, but appears to be
// commonplace.
// According to the spec, the layout of external attributes is
// platform-dependent.
// If that fails, we also check if the name of the file ends in '/',
// which is what Java's ZipFile implementation does.
const fileName = this.fileName();
return (this.externalAttributes() & 0x10 ? true : false) || fileName.charAt(fileName.length - 1) === '/';
}
public isFile(): boolean {
return !this.isDirectory();
}
public useUTF8(): boolean {
return (this.flag() & 0x800) === 0x800;
}
public isEncrypted(): boolean {
return (this.flag() & 0x1) === 0x1;
}
public getFileData(): FileData {
// Need to grab the header before we can figure out where the actual
// compressed data starts.
const start = this.headerRelativeOffset();
const header = new FileHeader(this.zipData.subarray(start));
return new FileData(header, this, this.zipData.subarray(start + header.totalSize()));
}
public getData(): Buffer {
return this.getFileData().decompress();
}
public getRawData(): Buffer {
return this.getFileData().getRawData();
}
public getStats(): Stats {
return new Stats(FileType.FILE, this.uncompressedSize(), 0x16d, Date.now(), this.lastModFileTime().getTime());
}
}
/**
* 4.3.16: end of central directory record
* end of central dir signature 4 bytes (0x06054b50)
* number of this disk 2 bytes
* number of the disk with the
* start of the central directory 2 bytes
* total number of entries in the
* central directory on this disk 2 bytes
* total number of entries in
* the central directory 2 bytes
* size of the central directory 4 bytes
* offset of start of central
* directory with respect to
* the starting disk number 4 bytes
* .ZIP file comment length 2 bytes
* .ZIP file comment (variable size)
*/
export class EndOfCentralDirectory {
constructor(private data: Buffer) {
if (this.data.readUInt32LE(0) !== 0x06054b50) {
throw new ApiError(ErrorCode.EINVAL, `Invalid Zip file: End of central directory record has invalid signature: ${this.data.readUInt32LE(0)}`);
}
}
public diskNumber(): number {
return this.data.readUInt16LE(4);
}
public cdDiskNumber(): number {
return this.data.readUInt16LE(6);
}
public cdDiskEntryCount(): number {
return this.data.readUInt16LE(8);
}
public cdTotalEntryCount(): number {
return this.data.readUInt16LE(10);
}
public cdSize(): number {
return this.data.readUInt32LE(12);
}
public cdOffset(): number {
return this.data.readUInt32LE(16);
}
public cdZipCommentLength(): number {
return this.data.readUInt16LE(20);
}
public cdZipComment(): string {
// Assuming UTF-8. The specification doesn't specify.
return safeToString(this.data, true, 22, this.cdZipCommentLength());
}
public rawCdZipComment(): Buffer {
return this.data.slice(22, 22 + this.cdZipCommentLength());
}
}
/**
* Contains the table of contents of a Zip file.
*/
export class ZipTOC {
constructor(public index: FileIndex<CentralDirectory>, public directoryEntries: CentralDirectory[], public eocd: EndOfCentralDirectory, public data: Buffer) {}
}
export namespace ZipFS {
/**
* Configuration options for a ZipFS file system.
*/
export interface Options {
/**
* The zip file as a binary buffer.
*/
zipData: Buffer;
/**
* The name of the zip file (optional).
*/
name?: string;
}
}
/**
* Zip file-backed filesystem
* Implemented according to the standard:
* http://www.pkware.com/documents/casestudies/APPNOTE.TXT
*
* While there are a few zip libraries for JavaScript (e.g. JSZip and zip.js),
* they are not a good match for BrowserFS. In particular, these libraries
* perform a lot of unneeded data copying, and eagerly decompress every file
* in the zip file upon loading to check the CRC32. They also eagerly decode
* strings. Furthermore, these libraries duplicate functionality already present
* in BrowserFS (e.g. UTF-8 decoding and binary data manipulation).
*
* This filesystem takes advantage of BrowserFS's Buffer implementation, which
* efficiently represents the zip file in memory (in both ArrayBuffer-enabled
* browsers *and* non-ArrayBuffer browsers), and which can neatly be 'sliced'
* without copying data. Each struct defined in the standard is represented with
* a buffer slice pointing to an offset in the zip file, and has getters for
* each field. As we anticipate that this data will not be read often, we choose
* not to store each struct field in the JavaScript object; instead, to reduce
* memory consumption, we retrieve it directly from the binary data each time it
* is requested.
*
* When the filesystem is instantiated, we determine the directory structure
* of the zip file as quickly as possible. We lazily decompress and check the
* CRC32 of files. We do not cache decompressed files; if this is a desired
* feature, it is best implemented as a generic file system wrapper that can
* cache data from arbitrary file systems.
*
* Current limitations:
* * No encryption.
* * No ZIP64 support.
* * Read-only.
* Write support would require that we:
* - Keep track of changed/new files.
* - Compress changed files, and generate appropriate metadata for each.
* - Update file offsets for other files in the zip file.
* - Stream it out to a location.
* This isn't that bad, so we might do this at a later date.
*/
export class ZipFS extends SynchronousFileSystem {
public static readonly Name = 'ZipFS';
public static Create = CreateBackend.bind(this);
public static readonly Options: BackendOptions = {
zipData: {
type: 'object',
description: 'The zip file as a Buffer object.',
validator: bufferValidator,
},
name: {
type: 'string',
optional: true,
description: 'The name of the zip file (optional).',
},
};
public static readonly CompressionMethod = CompressionMethod;
public static isAvailable(): boolean {
return true;
}
public static RegisterDecompressionMethod(m: CompressionMethod, fcn: (data: Buffer, compressedSize: number, uncompressedSize: number, flags: number) => Buffer): void {
decompressionMethods[m] = fcn;
}
/**
* Locates the end of central directory record at the end of the file.
* Throws an exception if it cannot be found.
*/
private static _getEOCD(data: Buffer): EndOfCentralDirectory {
// Unfortunately, the comment is variable size and up to 64K in size.
// We assume that the magic signature does not appear in the comment, and
// in the bytes between the comment and the signature. Other ZIP
// implementations make this same assumption, since the alternative is to
// read thread every entry in the file to get to it. :(
// These are *negative* offsets from the end of the file.
const startOffset = 22;
const endOffset = Math.min(startOffset + 0xffff, data.length - 1);
// There's not even a byte alignment guarantee on the comment so we need to
// search byte by byte. *grumble grumble*
for (let i = startOffset; i < endOffset; i++) {
// Magic number: EOCD Signature
if (data.readUInt32LE(data.length - i) === 0x06054b50) {
return new EndOfCentralDirectory(data.subarray(data.length - i));
}
}
throw new ApiError(ErrorCode.EINVAL, 'Invalid ZIP file: Could not locate End of Central Directory signature.');
}
private static _addToIndex(cd: CentralDirectory, index: FileIndex<CentralDirectory>) {
// Paths must be absolute, yet zip file paths are always relative to the
// zip root. So we append '/' and call it a day.
let filename = cd.fileName();
if (filename.charAt(0) === '/') {
throw new ApiError(ErrorCode.EPERM, `Unexpectedly encountered an absolute path in a zip file. Please file a bug.`);
}
// XXX: For the file index, strip the trailing '/'.
if (filename.charAt(filename.length - 1) === '/') {
filename = filename.substr(0, filename.length - 1);
}
if (cd.isDirectory()) {
index.addPathFast('/' + filename, new DirInode<CentralDirectory>(cd));
} else {
index.addPathFast('/' + filename, new FileInode<CentralDirectory>(cd));
}
}
private static async _computeIndex(data: Buffer): Promise<ZipTOC> {
const index: FileIndex<CentralDirectory> = new FileIndex<CentralDirectory>();
const eocd: EndOfCentralDirectory = ZipFS._getEOCD(data);
if (eocd.diskNumber() !== eocd.cdDiskNumber()) {
throw new ApiError(ErrorCode.EINVAL, 'ZipFS does not support spanned zip files.');
}
const cdPtr = eocd.cdOffset();
if (cdPtr === 0xffffffff) {
throw new ApiError(ErrorCode.EINVAL, 'ZipFS does not support Zip64.');
}
const cdEnd = cdPtr + eocd.cdSize();
return ZipFS._computeIndexResponsive(data, index, cdPtr, cdEnd, [], eocd);
}
private static async _computeIndexResponsive(
data: Buffer,
index: FileIndex<CentralDirectory>,
cdPtr: number,
cdEnd: number,
cdEntries: CentralDirectory[],
eocd: EndOfCentralDirectory
): Promise<ZipTOC> {
if (cdPtr >= cdEnd) {
return new ZipTOC(index, cdEntries, eocd, data);
}
let count = 0;
while (count++ < 200 && cdPtr < cdEnd) {
const cd: CentralDirectory = new CentralDirectory(data, data.subarray(cdPtr));
ZipFS._addToIndex(cd, index);
cdPtr += cd.totalSize();
cdEntries.push(cd);
}
return ZipFS._computeIndexResponsive(data, index, cdPtr, cdEnd, cdEntries, eocd);
}
private _index: FileIndex<CentralDirectory> = new FileIndex<CentralDirectory>();
private _directoryEntries: CentralDirectory[] = [];
private _eocd: EndOfCentralDirectory | null = null;
private data: Buffer;
public readonly name: string;
public constructor({ zipData, name = '' }: ZipFS.Options) {
super();
this.name = name;
this._ready = ZipFS._computeIndex(zipData).then(zipTOC => {
this._index = zipTOC.index;
this._directoryEntries = zipTOC.directoryEntries;
this._eocd = zipTOC.eocd;
this.data = zipTOC.data;
return this;
});
}
public get metadata(): FileSystemMetadata {
return {
...super.metadata,
name: ZipFS.Name + (this.name !== '' ? ` ${this.name}` : ''),
readonly: true,
synchronous: true,
totalSpace: this.data.length,
};
}
/**
* Get the CentralDirectory object for the given path.
*/
public getCentralDirectoryEntry(path: string): CentralDirectory {
const inode = this._index.getInode(path);
if (inode === null) {
throw ApiError.ENOENT(path);
}
if (isFileInode<CentralDirectory>(inode)) {
return inode.getData();
} else if (isDirInode<CentralDirectory>(inode)) {
return inode.getData()!;
} else {
// Should never occur.
throw ApiError.EPERM(`Invalid inode: ${inode}`);
}
}
public getCentralDirectoryEntryAt(index: number): CentralDirectory {
const dirEntry = this._directoryEntries[index];
if (!dirEntry) {
throw new RangeError(`Invalid directory index: ${index}.`);
}
return dirEntry;
}
public getNumberOfCentralDirectoryEntries(): number {
return this._directoryEntries.length;
}
public getEndOfCentralDirectory(): EndOfCentralDirectory | null {
return this._eocd;
}
public statSync(path: string): Stats {
const inode = this._index.getInode(path);
if (inode === null) {
throw ApiError.ENOENT(path);
}
let stats: Stats;
if (isFileInode<CentralDirectory>(inode)) {
stats = inode.getData().getStats();
} else if (isDirInode(inode)) {
stats = inode.getStats();
} else {
throw new ApiError(ErrorCode.EINVAL, 'Invalid inode.');
}
return stats;
}
public openSync(path: string, flags: FileFlag, mode: number): File {
// INVARIANT: Cannot write to RO file systems.
if (flags.isWriteable()) {
throw new ApiError(ErrorCode.EPERM, path);
}
// Check if the path exists, and is a file.
const inode = this._index.getInode(path);
if (!inode) {
throw ApiError.ENOENT(path);
} else if (isFileInode<CentralDirectory>(inode) || isDirInode<CentralDirectory>(inode)) {
const stats = !isDirInode<CentralDirectory>(inode) ? inode.getData().getStats() : inode.getStats();
const data = !isDirInode<CentralDirectory>(inode) ? inode.getData().getData() : inode.getStats().fileData;
switch (flags.pathExistsAction()) {
case ActionType.THROW_EXCEPTION:
case ActionType.TRUNCATE_FILE:
throw ApiError.EEXIST(path);
case ActionType.NOP:
return new NoSyncFile(this, path, flags, stats, data || undefined);
default:
throw new ApiError(ErrorCode.EINVAL, 'Invalid FileMode object.');
}
} else {
throw ApiError.EPERM(path);
}
}
public readdirSync(path: string): string[] {
// Check if it exists.
const inode = this._index.getInode(path);
if (!inode) {
throw ApiError.ENOENT(path);
} else if (isDirInode(inode)) {
return inode.getListing();
} else {
throw ApiError.ENOTDIR(path);
}
}
/**
* Specially-optimized readfile.
*/
public readFileSync(fname: string, encoding: BufferEncoding, flag: FileFlag): any {
// Get file.
const fd = this.openSync(fname, flag, 0o644);
try {
const fdCast = <NoSyncFile<ZipFS>>fd;
const fdBuff = <Buffer>fdCast.getBuffer();
if (encoding === null) {
return copyingSlice(fdBuff);
}
return fdBuff.toString(encoding);
} finally {
fd.closeSync();
}
}
}
ZipFS.RegisterDecompressionMethod(CompressionMethod.DEFLATE, (data, compressedSize, uncompressedSize) => {
return inflateRawSync(data.subarray(0, compressedSize), { chunkSize: uncompressedSize });
});
ZipFS.RegisterDecompressionMethod(CompressionMethod.STORED, (data, compressedSize, uncompressedSize) => {
return copyingSlice(data, 0, uncompressedSize);
});