-
Notifications
You must be signed in to change notification settings - Fork 11
/
zipper.pp
3313 lines (2956 loc) · 99.8 KB
/
zipper.pp
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
{
$Id: header,v 1.3 2013/05/26 06:33:45 michael Exp $
This file is part of the Free Component Library (FCL)
Copyright (c) 1999-2014 by the Free Pascal development team
See the file COPYING.FPC, included in this distribution,
for details about the copyright.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
**********************************************************************}
{$mode objfpc}
{$h+}
unit Zipper;
Interface
Uses
{$IFDEF UNIX}
BaseUnix,
{$ENDIF}
SysUtils,Classes,zstream;
Const
{ Signatures }
END_OF_CENTRAL_DIR_SIGNATURE = $06054B50;
ZIP64_END_OF_CENTRAL_DIR_SIGNATURE = $06064B50;
ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIGNATURE = $07064B50;
LOCAL_FILE_HEADER_SIGNATURE = $04034B50;
CENTRAL_FILE_HEADER_SIGNATURE = $02014B50;
ZIP64_HEADER_ID = $0001;
// infozip unicode path
INFOZIP_UNICODE_PATH_ID = $7075;
EFS_LANGUAGE_ENCODING_FLAG = $800;
const
OS_FAT = 0; //MS-DOS and OS/2 (FAT/VFAT/FAT32)
OS_UNIX = 3;
OS_OS2 = 6; //OS/2 HPFS
OS_NTFS = 10;
OS_VFAT = 14;
OS_OSX = 19;
UNIX_MASK = $F000;
UNIX_FIFO = $1000;
UNIX_CHAR = $2000;
UNIX_DIR = $4000;
UNIX_BLK = $6000;
UNIX_FILE = $8000;
UNIX_LINK = $A000;
UNIX_SOCK = $C000;
UNIX_RUSR = $0100;
UNIX_WUSR = $0080;
UNIX_XUSR = $0040;
UNIX_RGRP = $0020;
UNIX_WGRP = $0010;
UNIX_XGRP = $0008;
UNIX_ROTH = $0004;
UNIX_WOTH = $0002;
UNIX_XOTH = $0001;
UNIX_DEFAULT = UNIX_RUSR or UNIX_WUSR or UNIX_XUSR or UNIX_RGRP or UNIX_ROTH;
Type
Local_File_Header_Type = Packed Record //1 per zipped file
Signature : LongInt; //4 bytes
Extract_Version_Reqd : Word; //if zip64: >= 45
Bit_Flag : Word; //"General purpose bit flag in PKZip appnote
Compress_Method : Word;
Last_Mod_Time : Word;
Last_Mod_Date : Word;
Crc32 : LongWord;
Compressed_Size : LongWord;
Uncompressed_Size : LongWord;
Filename_Length : Word;
Extra_Field_Length : Word; //refers to Extensible data field size
end;
Extensible_Data_Field_Header_Type = Packed Record
// Beginning of extra field
// after local file header
// after central directory header
Header_ID : Word;
//e.g. $0001 (ZIP64_HEADER_ID) Zip64 extended information extra field
// $0009 OS/2: extended attributes
// $000a NTFS: (Win32 really)
// $000d UNIX: uid, gid etc
Data_Size : Word; //size of following field data
//... field data should follow...
end;
Zip64_Extended_Info_Field_Type = Packed Record //goes after Extensible_Data_Field_Header_Type
// overrides Local and Central Directory data
// stored in extra field
Original_Size : QWord; //Uncompressed file
Compressed_Size : QWord; //Compressed data
Relative_Hdr_Offset : QWord; //Offset that leads to local header record
Disk_Start_Number : LongWord; //on which disk this file starts
end;
{ Define the Central Directory record types }
Central_File_Header_Type = Packed Record
Signature : LongInt; //4 bytes
MadeBy_Version : Word; //if zip64: lower byte >= 45
Extract_Version_Reqd : Word; //if zip64: >=45
Bit_Flag : Word; //General purpose bit flag in PKZip appnote
Compress_Method : Word;
Last_Mod_Time : Word;
Last_Mod_Date : Word;
Crc32 : LongWord;
Compressed_Size : LongWord;
Uncompressed_Size : LongWord;
Filename_Length : Word;
Extra_Field_Length : Word;
File_Comment_Length : Word;
Starting_Disk_Num : Word;
Internal_Attributes : Word;
External_Attributes : LongWord;
Local_Header_Offset : LongWord; // if zip64: 0xFFFFFFFF
End;
End_of_Central_Dir_Type = Packed Record //End of central directory record
//1 per zip file, near end, before comment
Signature : LongInt; //4 bytes
Disk_Number : Word;
Central_Dir_Start_Disk : Word;
Entries_This_Disk : Word;
Total_Entries : Word;
Central_Dir_Size : LongWord;
Start_Disk_Offset : LongWord;
ZipFile_Comment_Length : Word;
end;
Zip64_End_of_Central_Dir_type = Packed Record
Signature : LongInt;
Record_Size : QWord;
Version_Made_By : Word; //lower byte >= 45
Extract_Version_Reqd : Word; //version >= 45
Disk_Number : LongWord;
Central_Dir_Start_Disk : LongWord;
Entries_This_Disk : QWord;
Total_Entries : QWord;
Central_Dir_Size : QWord;
Start_Disk_Offset : QWord;
end;
Zip64_End_of_Central_Dir_Locator_type = Packed Record //comes after Zip64_End_of_Central_Dir_type
Signature : LongInt;
Zip64_EOCD_Start_Disk : LongWord; //Starting disk for Zip64 End of Central Directory record
Central_Dir_Zip64_EOCD_Offset : QWord; //offset of Zip64 End of Central Directory record
Total_Disks : LongWord; //total number of disks (contained in zip)
end;
Const
Crc_32_Tab : Array[0..255] of LongWord = (
$00000000, $77073096, $ee0e612c, $990951ba, $076dc419, $706af48f, $e963a535, $9e6495a3,
$0edb8832, $79dcb8a4, $e0d5e91e, $97d2d988, $09b64c2b, $7eb17cbd, $e7b82d07, $90bf1d91,
$1db71064, $6ab020f2, $f3b97148, $84be41de, $1adad47d, $6ddde4eb, $f4d4b551, $83d385c7,
$136c9856, $646ba8c0, $fd62f97a, $8a65c9ec, $14015c4f, $63066cd9, $fa0f3d63, $8d080df5,
$3b6e20c8, $4c69105e, $d56041e4, $a2677172, $3c03e4d1, $4b04d447, $d20d85fd, $a50ab56b,
$35b5a8fa, $42b2986c, $dbbbc9d6, $acbcf940, $32d86ce3, $45df5c75, $dcd60dcf, $abd13d59,
$26d930ac, $51de003a, $c8d75180, $bfd06116, $21b4f4b5, $56b3c423, $cfba9599, $b8bda50f,
$2802b89e, $5f058808, $c60cd9b2, $b10be924, $2f6f7c87, $58684c11, $c1611dab, $b6662d3d,
$76dc4190, $01db7106, $98d220bc, $efd5102a, $71b18589, $06b6b51f, $9fbfe4a5, $e8b8d433,
$7807c9a2, $0f00f934, $9609a88e, $e10e9818, $7f6a0dbb, $086d3d2d, $91646c97, $e6635c01,
$6b6b51f4, $1c6c6162, $856530d8, $f262004e, $6c0695ed, $1b01a57b, $8208f4c1, $f50fc457,
$65b0d9c6, $12b7e950, $8bbeb8ea, $fcb9887c, $62dd1ddf, $15da2d49, $8cd37cf3, $fbd44c65,
$4db26158, $3ab551ce, $a3bc0074, $d4bb30e2, $4adfa541, $3dd895d7, $a4d1c46d, $d3d6f4fb,
$4369e96a, $346ed9fc, $ad678846, $da60b8d0, $44042d73, $33031de5, $aa0a4c5f, $dd0d7cc9,
$5005713c, $270241aa, $be0b1010, $c90c2086, $5768b525, $206f85b3, $b966d409, $ce61e49f,
$5edef90e, $29d9c998, $b0d09822, $c7d7a8b4, $59b33d17, $2eb40d81, $b7bd5c3b, $c0ba6cad,
$edb88320, $9abfb3b6, $03b6e20c, $74b1d29a, $ead54739, $9dd277af, $04db2615, $73dc1683,
$e3630b12, $94643b84, $0d6d6a3e, $7a6a5aa8, $e40ecf0b, $9309ff9d, $0a00ae27, $7d079eb1,
$f00f9344, $8708a3d2, $1e01f268, $6906c2fe, $f762575d, $806567cb, $196c3671, $6e6b06e7,
$fed41b76, $89d32be0, $10da7a5a, $67dd4acc, $f9b9df6f, $8ebeeff9, $17b7be43, $60b08ed5,
$d6d6a3e8, $a1d1937e, $38d8c2c4, $4fdff252, $d1bb67f1, $a6bc5767, $3fb506dd, $48b2364b,
$d80d2bda, $af0a1b4c, $36034af6, $41047a60, $df60efc3, $a867df55, $316e8eef, $4669be79,
$cb61b38c, $bc66831a, $256fd2a0, $5268e236, $cc0c7795, $bb0b4703, $220216b9, $5505262f,
$c5ba3bbe, $b2bd0b28, $2bb45a92, $5cb36a04, $c2d7ffa7, $b5d0cf31, $2cd99e8b, $5bdeae1d,
$9b64c2b0, $ec63f226, $756aa39c, $026d930a, $9c0906a9, $eb0e363f, $72076785, $05005713,
$95bf4a82, $e2b87a14, $7bb12bae, $0cb61b38, $92d28e9b, $e5d5be0d, $7cdcefb7, $0bdbdf21,
$86d3d2d4, $f1d4e242, $68ddb3f8, $1fda836e, $81be16cd, $f6b9265b, $6fb077e1, $18b74777,
$88085ae6, $ff0f6a70, $66063bca, $11010b5c, $8f659eff, $f862ae69, $616bffd3, $166ccf45,
$a00ae278, $d70dd2ee, $4e048354, $3903b3c2, $a7672661, $d06016f7, $4969474d, $3e6e77db,
$aed16a4a, $d9d65adc, $40df0b66, $37d83bf0, $a9bcae53, $debb9ec5, $47b2cf7f, $30b5ffe9,
$bdbdf21c, $cabac28a, $53b39330, $24b4a3a6, $bad03605, $cdd70693, $54de5729, $23d967bf,
$b3667a2e, $c4614ab8, $5d681b02, $2a6f2b94, $b40bbe37, $c30c8ea1, $5a05df1b, $2d02ef8d
);
Type
TProgressEvent = Procedure(Sender : TObject; Const Pct : Double) of object;
TProgressEventEx = Procedure(Sender : TObject; Const ATotPos, ATotSize: Int64) of object;
TOnEndOfFileEvent = Procedure(Sender : TObject; Const Ratio : Double) of object;
TOnStartFileEvent = Procedure(Sender : TObject; Const AFileName : String) of object;
Type
{ TCompressor }
TCompressor = Class(TObject)
private
FTerminated: Boolean;
Protected
FInFile : TStream; { I/O file variables }
FOutFile : TStream;
FCrc32Val : LongWord; { CRC calculation variable }
FBufferSize : LongWord;
FOnPercent : Integer;
FOnProgress : TProgressEvent;
Procedure UpdC32(Octet: Byte);
Public
Constructor Create(AInFile, AOutFile : TStream; ABufSize : LongWord); virtual;
Procedure Compress; Virtual; Abstract;
Class Function ZipID : Word; virtual; Abstract;
Class Function ZipVersionReqd: Word; virtual; Abstract;
Function ZipBitFlag: Word; virtual; Abstract;
Procedure Terminate;
Property BufferSize : LongWord read FBufferSize;
Property OnPercent : Integer Read FOnPercent Write FOnPercent;
Property OnProgress : TProgressEvent Read FOnProgress Write FOnProgress;
Property Crc32Val : LongWord Read FCrc32Val Write FCrc32Val;
Property Terminated : Boolean Read FTerminated;
end;
{ TDeCompressor }
TDeCompressor = Class(TObject)
Protected
FInFile : TStream; { I/O file variables }
FOutFile : TStream;
FCrc32Val : LongWord; { CRC calculation variable }
FBufferSize : LongWord;
FOnPercent : Integer;
FOnProgress : TProgressEvent;
FOnProgressEx: TProgressEventEx;
FTotPos : Int64;
FTotSize : Int64;
FTerminated : Boolean;
Procedure UpdC32(Octet: Byte);
Public
Constructor Create(AInFile, AOutFile : TStream; ABufSize : LongWord); virtual;
Procedure DeCompress; Virtual; Abstract;
Procedure Terminate;
Class Function ZipID : Word; virtual; Abstract;
Property BufferSize : LongWord read FBufferSize;
Property OnPercent : Integer Read FOnPercent Write FOnPercent;
Property OnProgress : TProgressEvent Read FOnProgress Write FOnProgress;
Property OnProgressEx : TProgressEventEx Read FOnProgressEx Write FOnProgressEx;
Property Crc32Val : LongWord Read FCrc32Val Write FCrc32Val;
Property Terminated : Boolean Read FTerminated;
end;
{ TShrinker }
Const
TABLESIZE = 8191;
FIRSTENTRY = 257;
Type
CodeRec = Packed Record
Child : Smallint;
Sibling : Smallint;
Suffix : Byte;
end;
CodeArray = Array[0..TABLESIZE] of CodeRec;
TablePtr = ^CodeArray;
FreeListPtr = ^FreeListArray;
FreeListArray = Array[FIRSTENTRY..TABLESIZE] of Word;
BufPtr = PByte;
TShrinker = Class(TCompressor)
Private
FBufSize : LongWord;
MaxInBufIdx : LongWord; { Count of valid chars in input buffer }
InputEof : Boolean; { End of file indicator }
CodeTable : TablePtr; { Points to code table for LZW compression }
FreeList : FreeListPtr; { Table of free code table entries }
NextFree : Word; { Index into free list table }
ClearList : Array[0..1023] of Byte; { Bit mapped structure used in }
{ during adaptive resets }
CodeSize : Byte; { Size of codes (in bits) currently being written }
MaxCode : Word; { Largest code that can be written in CodeSize bits }
InBufIdx, { Points to next char in buffer to be read }
OutBufIdx : LongWord; { Points to next free space in output buffer }
InBuf, { I/O buffers }
OutBuf : BufPtr;
FirstCh : Boolean; { Flag indicating the START of a shrink operation }
TableFull : Boolean; { Flag indicating a full symbol table }
SaveByte : Byte; { Output code buffer }
BitsUsed : Byte; { Index into output code buffer }
BytesIn : LongWord; { Count of input file bytes processed }
BytesOut : LongWord; { Count of output bytes }
FOnBytes : LongWord;
Procedure FillInputBuffer;
Procedure WriteOutputBuffer;
Procedure FlushOutput;
Procedure PutChar(B : Byte);
procedure PutCode(Code : Smallint);
Procedure InitializeCodeTable;
Procedure Prune(Parent : Word);
Procedure Clear_Table;
Procedure Table_Add(Prefix : Word; Suffix : Byte);
function Table_Lookup(TargetPrefix : Smallint;
TargetSuffix : Byte;
Out FoundAt : Smallint) : Boolean;
Procedure Shrink(Suffix : Smallint);
Procedure ProcessLine(Const Source : String);
Procedure DoOnProgress(Const Pct : Double); Virtual;
Public
Constructor Create(AInFile, AOutFile : TStream; ABufSize : LongWord); override;
Destructor Destroy; override;
Procedure Compress; override;
Class Function ZipID : Word; override;
Class Function ZipVersionReqd : Word; override;
Function ZipBitFlag : Word; override;
end;
{ TDeflater }
TDeflater = Class(TCompressor)
private
FCompressionLevel: TCompressionlevel;
Public
Constructor Create(AInFile, AOutFile : TStream; ABufSize : LongWord);override;
Procedure Compress; override;
Class Function ZipID : Word; override;
Class Function ZipVersionReqd : Word; override;
Function ZipBitFlag : Word; override;
Property CompressionLevel : TCompressionlevel Read FCompressionLevel Write FCompressionLevel;
end;
{ TInflater }
TInflater = Class(TDeCompressor)
Public
Constructor Create(AInFile, AOutFile : TStream; ABufSize : LongWord);override;
Procedure DeCompress; override;
Class Function ZipID : Word; override;
end;
{ TZipFileEntry }
TZipFileEntry = Class(TCollectionItem)
private
FArchiveFileName: String; //Name of the file as it appears in the zip file list
FUTF8FileName : UTF8String;
FUTF8DiskFileName : UTF8String;
FAttributes: LongWord;
FDateTime: TDateTime;
FDiskFileName: String; {Name of the file on disk (i.e. uncompressed. Can be empty if based on a stream.);
uses local OS/filesystem directory separators}
FHeaderPos: int64;
FNeedsZip64: Boolean; //flags whether filesize is big enough so we need a zip64 entry
FOS: Byte;
FSize: Int64;
FStream: TStream;
FCompressionLevel: TCompressionlevel;
function GetArchiveFileName: String;
function GetUTF8ArchiveFileName: UTF8String;
function GetUTF8DiskFileName: UTF8String;
procedure SetArchiveFileName(Const AValue: String);
procedure SetDiskFileName(Const AValue: String);
procedure SetUTF8ArchiveFileName(AValue: UTF8String);
procedure SetUTF8DiskFileName(AValue: UTF8String);
Protected
// For multi-disk support, a disk number property could be added here.
Property HdrPos : int64 Read FHeaderPos Write FheaderPos;
Property NeedsZip64 : boolean Read FNeedsZip64 Write FNeedsZip64;
Public
constructor Create(ACollection: TCollection); override;
function IsDirectory: Boolean;
function IsLink: Boolean;
Procedure Assign(Source : TPersistent); override;
Property Stream : TStream Read FStream Write FStream;
Published
Property ArchiveFileName : String Read GetArchiveFileName Write SetArchiveFileName;
Property UTF8ArchiveFileName : UTF8String Read GetUTF8ArchiveFileName Write SetUTF8ArchiveFileName;
Property DiskFileName : String Read FDiskFileName Write SetDiskFileName;
Property UTF8DiskFileName : UTF8String Read GetUTF8DiskFileName Write SetUTF8DiskFileName;
Property Size : Int64 Read FSize Write FSize;
Property DateTime : TDateTime Read FDateTime Write FDateTime;
property OS: Byte read FOS write FOS;
property Attributes: LongWord read FAttributes write FAttributes;
Property CompressionLevel: TCompressionlevel read FCompressionLevel write FCompressionLevel;
end;
{ TZipFileEntries }
TZipFileEntries = Class(TCollection)
private
function GetZ(AIndex : Integer): TZipFileEntry;
procedure SetZ(AIndex : Integer; const AValue: TZipFileEntry);
Public
Function AddFileEntry(Const ADiskFileName : String): TZipFileEntry;
Function AddFileEntry(Const ADiskFileName, AArchiveFileName : String): TZipFileEntry;
Function AddFileEntry(Const AStream : TSTream; Const AArchiveFileName : String): TZipFileEntry;
Procedure AddFileEntries(Const List : TStrings);
Property Entries[AIndex : Integer] : TZipFileEntry Read GetZ Write SetZ; default;
end;
{ TZipper }
TZipper = Class(TObject)
Private
FEntries : TZipFileEntries;
FTerminated: Boolean;
FZipping : Boolean;
FBufSize : LongWord;
FFileName : RawByteString; { Name of resulting Zip file }
FFileComment : String;
FFiles : TStrings;
FInMemSize : Int64;
FZipFileNeedsZip64 : Boolean; //flags whether at least one file is big enough to require a zip64 record
FOutStream : TStream;
FInFile : TStream; { I/O file variables }
LocalHdr : Local_File_Header_Type;
LocalZip64ExtHdr: Extensible_Data_Field_Header_Type; //Extra field header fixed to zip64 (i.e. .ID=1)
LocalZip64Fld : Zip64_Extended_Info_Field_Type; //header is in LocalZip64ExtHdr
CentralHdr : Central_File_Header_Type;
EndHdr : End_of_Central_Dir_Type;
FOnPercent : LongInt;
FOnProgress : TProgressEvent;
FOnEndOfFile : TOnEndOfFileEvent;
FOnStartFile : TOnStartFileEvent;
FCurrentCompressor : TCompressor;
FUseLanguageEncoding: Boolean;
function CheckEntries: Integer;
procedure SetEntries(const AValue: TZipFileEntries);
Protected
Procedure CloseInput(Item : TZipFileEntry);
Procedure StartZipFile(Item : TZipFileEntry);
Function UpdateZipHeader(Item : TZipFileEntry; FZip : TStream; ACRC : LongWord;AMethod : Word; AZipVersionReqd : Word; AZipBitFlag : Word) : Boolean;
Procedure BuildZipDirectory; //Builds central directory based on local headers
Procedure DoEndOfFile;
Procedure ZipOneFile(Item : TZipFileEntry); virtual;
Function OpenInput(Item : TZipFileEntry) : Boolean;
Procedure GetFileInfo;
Procedure SetBufSize(Value : LongWord);
Procedure SetFileName(Value : RawByteString);
Function CreateCompressor(Item : TZipFileEntry; AinFile,AZipStream : TStream) : TCompressor; virtual;
Property NeedsZip64 : boolean Read FZipFileNeedsZip64 Write FZipFileNeedsZip64;
Public
Constructor Create;
Destructor Destroy;override;
Procedure ZipAllFiles; virtual;
// Saves zip to file and changes FileName
Procedure SaveToFile(const AFileName: RawByteString);
// Saves zip to stream
Procedure SaveToStream(AStream: TStream);
// Zips specified files into a zip with name AFileName
Procedure ZipFile(const aFileToBeZipped : RawByteString);
Procedure ZipFile(const AZipFileName,aFileToBeZipped : RawByteString);
Procedure ZipFiles(const AZipFileName : RawByteString; FileList : TStrings);
Procedure ZipFiles(const AZipFileName : RawByteString; const FileList : Array of RawbyteString);
Procedure ZipFiles(const aFileList : Array of RawbyteString);
Procedure ZipFiles(FileList : TStrings);
// Zips specified entries into a zip with name AFileName
Procedure ZipFiles(const AZipFileName : RawByteString; Entries : TZipFileEntries);
Procedure ZipFiles(Entries : TZipFileEntries);
// Easy access method
// Zip single file
Class Procedure Zip(const AZipFileName : RawByteString; const aFileToBeZipped: RawByteString);
// Zip multiple file
Class Procedure Zip(const AZipFileName : RawByteString; aFileList : Array of RawByteString);
Class Procedure Zip(const AZipFileName : RawByteString; aFileList : TStrings);
Procedure Clear;
Procedure Terminate;
Public
Property BufferSize : LongWord Read FBufSize Write SetBufSize;
Property OnPercent : Integer Read FOnPercent Write FOnPercent;
Property OnProgress : TProgressEvent Read FOnProgress Write FOnProgress;
Property OnStartFile : TOnStartFileEvent Read FOnStartFile Write FOnStartFile;
Property OnEndFile : TOnEndOfFileEvent Read FOnEndOfFile Write FOnEndOfFile;
Property FileName : RawByteString Read FFileName Write SetFileName;
Property FileComment: String Read FFileComment Write FFileComment;
// Deprecated. Use Entries.AddFileEntry(FileName) or Entries.AddFileEntries(List) instead.
Property Files : TStrings Read FFiles; deprecated;
Property InMemSize : Int64 Read FInMemSize Write FInMemSize;
Property Entries : TZipFileEntries Read FEntries Write SetEntries;
Property Terminated : Boolean Read FTerminated;
// EFS/language encoding using UTF-8
Property UseLanguageEncoding : Boolean Read FUseLanguageEncoding Write FUseLanguageEncoding;
end;
{ TFullZipFileEntry }
TFullZipFileEntry = Class(TZipFileEntry)
private
FBitFlags: Word;
FCompressedSize: QWord;
FCompressMethod: Word;
FCRC32: LongWord;
Public
Property BitFlags : Word Read FBitFlags;
Property CompressMethod : Word Read FCompressMethod;
Property CompressedSize : QWord Read FCompressedSize;
property CRC32: LongWord read FCRC32 write FCRC32;
end;
TOnCustomStreamEvent = Procedure(Sender : TObject; var AStream : TStream; AItem : TFullZipFileEntry) of object;
TCustomInputStreamEvent = Procedure(Sender: TObject; var AStream: TStream) of object;
{ TFullZipFileEntries }
TFullZipFileEntries = Class(TZipFileEntries)
private
function GetFZ(AIndex : Integer): TFullZipFileEntry;
procedure SetFZ(AIndex : Integer; const AValue: TFullZipFileEntry);
Public
Property FullEntries[AIndex : Integer] : TFullZipFileEntry Read GetFZ Write SetFZ; default;
end;
{ TUnZipper }
TUnZipper = Class(TObject)
Private
FOnCloseInputStream: TCustomInputStreamEvent;
FOnCreateStream: TOnCustomStreamEvent;
FOnDoneStream: TOnCustomStreamEvent;
FOnOpenInputStream: TCustomInputStreamEvent;
FUnZipping : Boolean;
FBufSize : LongWord;
FFileName : RawByteString; { Name of resulting Zip file }
FOutputPath : RawByteString;
FFileComment: String;
FEntries : TFullZipFileEntries;
FFiles : TStrings;
FUseUTF8 : Boolean;
FFlat : Boolean;
FZipStream : TStream; { I/O file variables }
LocalHdr : Local_File_Header_Type; //Local header, before compressed file data
LocalZip64Fld : Zip64_Extended_Info_Field_Type; //header is in LocalZip64ExtHdr
CentralHdr : Central_File_Header_Type;
FTotPos : Int64;
FTotSize : Int64;
FTerminated: Boolean;
FOnPercent : LongInt;
FOnProgress : TProgressEvent;
FOnProgressEx : TProgressEventEx;
FOnEndOfFile : TOnEndOfFileEvent;
FOnStartFile : TOnStartFileEvent;
FCurrentDecompressor: TDecompressor;
function CalcTotalSize(AllFiles: Boolean): Int64;
function IsMatch(I: TFullZipFileEntry): Boolean;
Protected
Procedure OpenInput;
Procedure CloseOutput(Item : TFullZipFileEntry; var OutStream: TStream);
Procedure CloseInput;
Procedure FindEndHeaders(
out AEndHdr: End_of_Central_Dir_Type;
out AEndHdrPos: Int64;
out AEndZip64Hdr: Zip64_End_of_Central_Dir_type;
out AEndZip64HdrPos: Int64);
Procedure ReadZipDirectory;
Procedure ReadZipHeader(Item : TFullZipFileEntry; out AMethod : Word);
Procedure DoEndOfFile;
Procedure UnZipOneFile(Item : TFullZipFileEntry); virtual;
Function OpenOutput(OutFileName : RawByteString; Out OutStream: TStream; Item : TFullZipFileEntry) : Boolean;
Procedure SetBufSize(Value : LongWord);
Procedure SetFileName(Value : RawByteString);
Procedure SetOutputPath(Value: RawByteString);
Function CreateDeCompressor(Item : TZipFileEntry; AMethod : Word;AZipFile,AOutFile : TStream) : TDeCompressor; virtual;
Public
Constructor Create;
Destructor Destroy;override;
Procedure UnZipAllFiles; virtual;
Procedure UnZipFile(const aExtractFileName: RawByteString);
Procedure UnZipFile(const AZipFileName, aExtractFileName: RawByteString);
Procedure UnZipFiles(const AZipFileName : RawByteString; FileList : TStrings);
Procedure UnZipFiles(const AZipFileName : RawByteString; aFileList : Array of RawBytestring);
Procedure UnZipFiles(aFileList : TStrings);
Procedure UnZipAllFiles(const AZipFileName : RawByteString);
// Easy access methods. No instance needed, uses default options.
// Unzip all files
Class Procedure Unzip(const AZipFileName : RawByteString);
// Unzip a single file.
Class Procedure Unzip(const AZipFileName : RawByteString;aExtractFileName : RawByteString);
// Unzip several files
Class Procedure Unzip(const AZipFileName : RawByteString; aFileList : Array of RawByteString);
Class Procedure Unzip(const AZipFileName : RawByteString; aFileList : TStrings);
Procedure Clear;
Procedure Examine;
Procedure Terminate;
Public
Property BufferSize : LongWord Read FBufSize Write SetBufSize;
Property OnOpenInputStream: TCustomInputStreamEvent read FOnOpenInputStream write FOnOpenInputStream;
Property OnCloseInputStream: TCustomInputStreamEvent read FOnCloseInputStream write FOnCloseInputStream;
Property OnCreateStream : TOnCustomStreamEvent Read FOnCreateStream Write FOnCreateStream;
Property OnDoneStream : TOnCustomStreamEvent Read FOnDoneStream Write FOnDoneStream;
Property OnPercent : Integer Read FOnPercent Write FOnPercent;
Property OnProgress : TProgressEvent Read FOnProgress Write FOnProgress;
Property OnProgressEx : TProgressEventEx Read FOnProgressEx Write FOnProgressEx;
Property OnStartFile : TOnStartFileEvent Read FOnStartFile Write FOnStartFile;
Property OnEndFile : TOnEndOfFileEvent Read FOnEndOfFile Write FOnEndOfFile;
Property FileName : RawByteString Read FFileName Write SetFileName;
Property OutputPath : RawByteString Read FOutputPath Write SetOutputPath;
Property FileComment: String Read FFileComment;
Property Files : TStrings Read FFiles;
Property Entries : TFullZipFileEntries Read FEntries;
Property UseUTF8 : Boolean Read FUseUTF8 Write FUseUTF8;
Property Flat : Boolean Read FFlat Write FFlat; // enable flat extraction, like -j when using unzip
Property Terminated : Boolean Read FTerminated;
end;
EZipError = Class(Exception);
Implementation
uses rtlconsts;
ResourceString
SErrBufsizeChange = 'Changing buffer size is not allowed while (un)zipping.';
SErrFileChange = 'Changing output file name is not allowed while (un)zipping.';
SErrInvalidCRC = 'Invalid CRC checksum while unzipping %s.';
SErrCorruptZIP = 'Corrupt ZIP file %s.';
SErrUnsupportedCompressionFormat = 'Unsupported compression format %d';
SErrUnsupportedMultipleDisksCD = 'A central directory split over multiple disks is unsupported.';
SErrMaxEntries = 'Encountered %d file entries; maximum supported is %d.';
SErrMissingFileName = 'Missing filename in entry %d.';
SErrMissingArchiveName = 'Missing archive filename in streamed entry %d.';
SErrFileDoesNotExist = 'File "%s" does not exist.';
SErrPosTooLarge = 'Position/offset %d is larger than maximum supported %d.';
SErrNoFileName = 'No archive filename for examine operation.';
SErrNoStream = 'No stream is opened.';
SErrEncryptionNotSupported = 'Cannot unzip item "%s" : encryption is not supported.';
SErrPatchSetNotSupported = 'Cannot unzip item "%s" : Patch sets are not supported.';
{$ifdef Windows}
function FixLongFilename(const Fn: RawByteString): RawByteString;
begin
Result := Fn;
if (Length(Fn)>(MAX_PATH-20)) and not ((Pos('\\?\', Fn)=1) or (Pos('\\.\', Fn)=1) or (Pos('\\?\UNC\', Fn)=1)) then
begin
if (Pos('\\', Fn)=1) and (length(FN)>2) then
Insert('?\UNC\',Result,3)
else
Result:='\\?\'+Fn;
end;
end;
{$endif}
{ ---------------------------------------------------------------------
Auxiliary
---------------------------------------------------------------------}
Type
// A local version of TFileStream which uses rawbytestring. It
TFileStream = class(THandleStream)
Private
FFileName : RawBytestring;
public
constructor Create(const AFileName: RawBytestring; Mode: Word);
constructor Create(const AFileName: RawBytestring; Mode: Word; Rights: Cardinal);
destructor Destroy; override;
property FileName : RawBytestring Read FFilename;
end;
constructor TFileStream.Create(const AFileName: rawbytestring; Mode: Word);
begin
Create(AFileName,Mode,438);
end;
constructor TFileStream.Create(const AFileName: rawbytestring; Mode: Word; Rights: Cardinal);
Var
H : Thandle;
begin
{$ifdef Windows}
FFileName:=FixLongFilename(AFileName);
{$else}
FFileName:=AFileName;
{$endif}
If (Mode and fmCreate) > 0 then
H:=FileCreate(FFileName,Mode,Rights)
else
H:=FileOpen(FFileName,Mode);
If (THandle(H)=feInvalidHandle) then
If Mode=fmcreate then
raise EFCreateError.createfmt(SFCreateError,[AFileName])
else
raise EFOpenError.Createfmt(SFOpenError,[AFilename]);
Inherited Create(H);
end;
destructor TFileStream.Destroy;
begin
FileClose(Handle);
end;
{$IFDEF FPC_BIG_ENDIAN}
function SwapLFH(const Values: Local_File_Header_Type): Local_File_Header_Type;
begin
with Values do
begin
Result.Signature := SwapEndian(Signature);
Result.Extract_Version_Reqd := SwapEndian(Extract_Version_Reqd);
Result.Bit_Flag := SwapEndian(Bit_Flag);
Result.Compress_Method := SwapEndian(Compress_Method);
Result.Last_Mod_Time := SwapEndian(Last_Mod_Time);
Result.Last_Mod_Date := SwapEndian(Last_Mod_Date);
Result.Crc32 := SwapEndian(Crc32);
Result.Compressed_Size := SwapEndian(Compressed_Size);
Result.Uncompressed_Size := SwapEndian(Uncompressed_Size);
Result.Filename_Length := SwapEndian(Filename_Length);
Result.Extra_Field_Length := SwapEndian(Extra_Field_Length);
end;
end;
function SwapEDFH(const Values: Extensible_Data_Field_Header_Type): Extensible_Data_Field_Header_Type;
begin
with Values do
begin
Result.Header_ID := SwapEndian(Header_ID);
Result.Data_Size := SwapEndian(Data_Size);
end;
end;
function SwapZ64EIF(const Values: Zip64_Extended_Info_Field_Type): Zip64_Extended_Info_Field_Type;
begin
with Values do
begin
Result.Original_Size := SwapEndian(Original_Size);
Result.Compressed_Size := SwapEndian(Compressed_Size);
Result.Relative_Hdr_Offset := SwapEndian(Relative_Hdr_Offset);
Result.Disk_Start_Number := SwapEndian(Disk_Start_Number);
end;
end;
function SwapCFH(const Values: Central_File_Header_Type): Central_File_Header_Type;
begin
with Values do
begin
Result.Signature := SwapEndian(Signature);
Result.MadeBy_Version := SwapEndian(MadeBy_Version);
Result.Extract_Version_Reqd := SwapEndian(Extract_Version_Reqd);
Result.Bit_Flag := SwapEndian(Bit_Flag);
Result.Compress_Method := SwapEndian(Compress_Method);
Result.Last_Mod_Time := SwapEndian(Last_Mod_Time);
Result.Last_Mod_Date := SwapEndian(Last_Mod_Date);
Result.Crc32 := SwapEndian(Crc32);
Result.Compressed_Size := SwapEndian(Compressed_Size);
Result.Uncompressed_Size := SwapEndian(Uncompressed_Size);
Result.Filename_Length := SwapEndian(Filename_Length);
Result.Extra_Field_Length := SwapEndian(Extra_Field_Length);
Result.File_Comment_Length := SwapEndian(File_Comment_Length);
Result.Starting_Disk_Num := SwapEndian(Starting_Disk_Num);
Result.Internal_Attributes := SwapEndian(Internal_Attributes);
Result.External_Attributes := SwapEndian(External_Attributes);
Result.Local_Header_Offset := SwapEndian(Local_Header_Offset);
end;
end;
function SwapECD(const Values: End_of_Central_Dir_Type): End_of_Central_Dir_Type;
begin
with Values do
begin
Result.Signature := SwapEndian(Signature);
Result.Disk_Number := SwapEndian(Disk_Number);
Result.Central_Dir_Start_Disk := SwapEndian(Central_Dir_Start_Disk);
Result.Entries_This_Disk := SwapEndian(Entries_This_Disk);
Result.Total_Entries := SwapEndian(Total_Entries);
Result.Central_Dir_Size := SwapEndian(Central_Dir_Size);
Result.Start_Disk_Offset := SwapEndian(Start_Disk_Offset);
Result.ZipFile_Comment_Length := SwapEndian(ZipFile_Comment_Length);
end;
end;
function SwapZ64ECD(const Values: Zip64_End_of_Central_Dir_Type): Zip64_End_of_Central_Dir_Type;
begin
with Values do
begin
Result.Signature := SwapEndian(Signature);
Result.Record_Size := SwapEndian(Record_Size);
Result.Version_Made_By := SwapEndian(Version_Made_By);
Result.Extract_Version_Reqd := SwapEndian(Extract_Version_Reqd);
Result.Disk_Number := SwapEndian(Disk_Number);
Result.Central_Dir_Start_Disk := SwapEndian(Central_Dir_Start_Disk);
Result.Entries_This_Disk := SwapEndian(Entries_This_Disk);
Result.Total_Entries := SwapEndian(Total_Entries);
Result.Central_Dir_Size := SwapEndian(Central_Dir_Size);
Result.Start_Disk_Offset := SwapEndian(Start_Disk_Offset);
end;
end;
function SwapZ64ECDL(const Values: Zip64_End_of_Central_Dir_Locator_type): Zip64_End_of_Central_Dir_Locator_type;
begin
with Values do
begin
Result.Signature := SwapEndian(Signature);
Result.Zip64_EOCD_Start_Disk := SwapEndian(Zip64_EOCD_Start_Disk);
Result.Central_Dir_Zip64_EOCD_Offset := SwapEndian(Central_Dir_Zip64_EOCD_Offset);
Result.Total_Disks := SwapEndian(Total_Disks);
end;
end;
{$ENDIF FPC_BIG_ENDIAN}
Procedure DateTimeToZipDateTime(DT : TDateTime; out ZD,ZT : Word);
Var
Y,M,D,H,N,S,MS : Word;
begin
DecodeDate(DT,Y,M,D);
DecodeTime(DT,H,N,S,MS);
if Y<1980 then
begin
// Invalid date/time; set to earliest possible
Y:=0;
M:=1;
D:=1;
H:=0;
N:=0;
S:=0;
MS:=0;
end
else
begin
Y:=Y-1980;
end;
ZD:=d+(32*M)+(512*Y);
ZT:=(S div 2)+(32*N)+(2048*h);
end;
Procedure ZipDateTimeToDateTime(ZD,ZT : Word;out DT : TDateTime);
Var
Y,M,D,H,N,S,MS : Word;
begin
MS:=0;
S:=(ZT and 31) shl 1;
N:=(ZT shr 5) and 63;
H:=ZT shr 11;
D:=ZD and 31;
M:=(ZD shr 5) and 15;
Y:=((ZD shr 9) and 127)+1980;
if M < 1 then M := 1;
if D < 1 then D := 1;
DT:=ComposeDateTime(EncodeDate(Y,M,D),EncodeTime(H,N,S,MS));
end;
function ZipUnixAttrsToFatAttrs(const Name: String; Attrs: Longint): Longint;
begin
Result := faArchive;
if (Pos('.', Name) = 1) and (Name <> '.') and (Name <> '..') then
Result := Result + faHidden;
case (Attrs and UNIX_MASK) of
UNIX_DIR: Result := Result + faDirectory;
UNIX_LINK: Result := Result + faSymLink;
UNIX_FIFO, UNIX_CHAR, UNIX_BLK, UNIX_SOCK:
Result := Result + faSysFile;
end;
if (Attrs and UNIX_WUSR) = 0 then
Result := Result + faReadOnly;
end;
function ZipFatAttrsToUnixAttrs(Attrs: Longint): Longint;
begin
Result := UNIX_DEFAULT;
if (faReadOnly and Attrs) > 0 then
Result := Result and not (UNIX_WUSR);
if (faSymLink and Attrs) > 0 then
Result := Result or UNIX_LINK
else
if (faDirectory and Attrs) > 0 then
Result := Result or UNIX_DIR
else
Result := Result or UNIX_FILE;
end;
function CRC32Str(const s:string):DWord;
var
i:Integer;
begin
Result:=$FFFFFFFF;
if Length(S)>0 then
for i:=1 to Length(s) do
Result:=Crc_32_Tab[Byte(Result XOR LongInt(s[i]))] XOR ((Result SHR 8) AND $00FFFFFF);
Result:=not Result;
end;
{ ---------------------------------------------------------------------
TDeCompressor
---------------------------------------------------------------------}
Procedure TDeCompressor.UpdC32(Octet: Byte);
Begin
FCrc32Val := Crc_32_Tab[Byte(FCrc32Val XOR LongInt(Octet))] XOR ((FCrc32Val SHR 8) AND $00FFFFFF);
end;
constructor TDeCompressor.Create(AInFile, AOutFile: TStream; ABufSize: LongWord);
begin
FinFile:=AInFile;
FoutFile:=AOutFile;
FBufferSize:=ABufSize;
CRC32Val:=$FFFFFFFF;
end;
procedure TDeCompressor.Terminate;
begin
FTerminated:=True;
end;
{ ---------------------------------------------------------------------
TCompressor
---------------------------------------------------------------------}
Procedure TCompressor.UpdC32(Octet: Byte);
Begin
FCrc32Val := Crc_32_Tab[Byte(FCrc32Val XOR LongInt(Octet))] XOR ((FCrc32Val SHR 8) AND $00FFFFFF);
end;
constructor TCompressor.Create(AInFile, AOutFile: TStream; ABufSize: LongWord);
begin
FinFile:=AInFile;
FoutFile:=AOutFile;
FBufferSize:=ABufSize;
CRC32Val:=$FFFFFFFF;
end;
procedure TCompressor.Terminate;
begin
FTerminated:=True;
end;
{ ---------------------------------------------------------------------
TDeflater
---------------------------------------------------------------------}
constructor TDeflater.Create(AInFile, AOutFile: TStream; ABufSize: LongWord);
begin
Inherited;
FCompressionLevel:=clDefault;
end;
procedure TDeflater.Compress;
Var
Buf : PByte;
I,Count,NewCount : integer;
C : TCompressionStream;
BytesNow : Int64;
NextMark : Int64;
OnBytes : Int64;
FSize : Int64;
begin
CRC32Val:=$FFFFFFFF;
Buf:=GetMem(FBufferSize);
if FOnPercent = 0 then
FOnPercent := 1;
OnBytes:=Round((FInFile.Size * FOnPercent) / 100);
BytesNow:=0;
NextMark := OnBytes;
FSize:=FInfile.Size;
Try
C:=TCompressionStream.Create(FCompressionLevel,FOutFile,True);
Try
if assigned(FOnProgress) then
fOnProgress(self,0);
Repeat
Count:=FInFile.Read(Buf^,FBufferSize);
For I:=0 to Count-1 do
UpdC32(Buf[i]);
NewCount:=Count;
while (NewCount>0) do
NewCount:=NewCount-C.Write(Buf^,NewCount);
inc(BytesNow,Count);
if BytesNow>NextMark Then
begin
if (FSize>0) and assigned(FOnProgress) Then
FOnProgress(self,100 * ( BytesNow / FSize));
inc(NextMark,OnBytes);
end;
Until (Count=0) or Terminated;