-
Notifications
You must be signed in to change notification settings - Fork 3
/
MyZip.pas
1556 lines (1409 loc) · 57.8 KB
/
MyZip.pas
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
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2021 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{ Copyright and license exceptions noted in source }
{ }
{*******************************************************}
{*******************************************************}
{ Utility for creating and extracting Zip Files }
{ }
{See .ZIP File Format Specification at }
{http://www.pkware.com/documents/casestudies/APPNOTE.TXT}
{for more information on the .ZIP File Format. }
{ }
{ Support for Compression modes 0(store) and 8(deflate) }
{ Are implemented in this unit. }
{*******************************************************}
unit MyZip;
interface
uses
System.SysUtils,
System.IOUtils,
System.Generics.Collections,
System.Classes, Vcl.Dialogs;
type
/// <summary> Zip Compression Method Enumeration </summary>
TZipCompression = (
zcStored = 0,
zcShrunk,
zcReduce1,
zcReduce2,
zcReduce3,
zcReduce4,
zcImplode,
zcTokenize,
zcDeflate,
zcDeflate64,
zcPKImplode,
{11 RESERVED}
zcBZIP2 = 12,
{13 RESERVED}
zcLZMA = 14,
{15-17 RESERVED}
zcTERSE = 18,
zcLZ77,
zcWavePack = 97,
zcPPMdI1
);
/// <summary> Converts ZIP compression method value to string </summary>
function TZipCompressionToString(Compression: TZipCompression): string;
const
SIGNATURE_ZIPENDOFHEADER: UInt32 = $06054B50;
SIGNATURE_CENTRALHEADER: UInt32 = $02014B50;
SIGNATURE_LOCALHEADER: UInt32 = $04034B50;
LOCALHEADERSIZE = 26;
CENTRALHEADERSIZE = 42;
MADEBY_MSDOS = 0;
MADEBY_UNIX = 3;
type
/// <summary> Final block written to zip file</summary>
TZipEndOfCentralHeader = packed record
DiskNumber: UInt16;
CentralDirStartDisk: UInt16;
NumEntriesThisDisk: UInt16;
CentralDirEntries: UInt16;
CentralDirSize: UInt32;
CentralDirOffset: UInt32;
CommentLength: UInt16;
{Comment: RawByteString}
end;
/// <summary> TZipHeader contains information about a file in a zip archive.
/// </summary>
/// <remarks>
/// <para>
/// This record is overloaded for use in reading/writing ZIP
/// [Local file header] and the Central Directory's [file header].
/// </para>
/// <para> See PKZIP Application Note section V. General Format of a .ZIP file
/// sub section J. Explanation of fields for more detailed description
// of each field's usage.
/// </para>
/// </remarks>
TZipHeader = packed record
MadeByVersion: UInt16; // Start of Central Header
RequiredVersion: UInt16; // Start of Local Header
Flag: UInt16;
CompressionMethod: UInt16;
ModifiedDateTime: UInt32;
CRC32: UInt32;
CompressedSize: UInt32;
UncompressedSize: UInt32;
FileNameLength: UInt16;
ExtraFieldLength: UInt16; // End of Local Header
FileCommentLength: UInt16;
DiskNumberStart: UInt16;
InternalAttributes: UInt16;
ExternalAttributes: UInt32;
LocalHeaderOffset: UInt32; // End of Central Header
FileName: TBytes;
ExtraField: TBytes;
FileComment: TBytes;
function GetUTF8Support: Boolean;
procedure SetUTF8Support(value: Boolean);
property UTF8Support: Boolean read GetUTF8Support write SetUTF8Support;
end;
PZipHeader = ^TZipHeader;
/// <summary> Exception type for all Zip errors. </summary>
EZipException = class( Exception );
TZipMode = (zmClosed, zmRead, zmReadWrite, zmWrite);
/// <summary> On progress event</summary>
TZipProgressEvent = procedure(Sender: TObject; FileName: string; Header: TZipHeader; Position: Int64) of object;
TZipFile = class;
/// <summary> Function to Create a Compression/Decompression stream </summary>
/// <remarks>
/// Call <c>RegisterCompressionHandler</c> to register a compression type that
/// can Compress/Decompress a stream. The output stream reads/write from/to InStream.
/// </remarks>
TStreamConstructor = reference to function(InStream: TStream; const ZipFile: TZipFile; const Item: TZipHeader): TStream;
/// <summary> Callback to create a custom stream based on the original</summary>
TCreateCustomStreamCallBack = reference to function(const InStream: TStream; const ZipFile: TZipFile; const Item: TZipHeader; IsEncrypted: Boolean): TStream;
TOnCreateCustomStream = function(const InStream: TStream; const ZipFile: TZipFile; const Item: TZipHeader; IsEncrypted: Boolean): TStream of object;
/// <summary> Class for creating and reading .ZIP files.
/// </summary>
TZipFile = class
private type
TCompressionDict = TDictionary< TZipCompression , TPair<TStreamConstructor, TStreamConstructor > >;
private class var
FCompressionHandler: TCompressionDict;
FOnCreateDecompressStream: TOnCreateCustomStream;
FCreateDecompressStreamCallBack: TCreateCustomStreamCallBack;
protected class var
FCP437Encoding: TEncoding;
private
FMode: TZipMode;
FStream: TStream;
FFileStream: TFileStream;
FStartFileData: Int64;
FEndFileData: Int64;
FFiles: TList<TZipHeader>;
FComment: TBytes;
FEncoding: TEncoding;
FUTF8Support: Boolean;
FOnProgress: TZipProgressEvent;
FCurrentFile: string;
FCurrentHeader: TZipHeader;
function GetEncoding: TEncoding; virtual;
function GetFileCount: Integer;
function GetFileInfo(Index: Integer): TZipHeader;
function GetFileInfos: TArray<TZipHeader>;
function GetFileName(Index: Integer): string;
function GetFileNames: TArray<string>;
procedure ReadCentralHeader;
procedure SetUTF8Support(const Value: Boolean);
function LocateEndOfCentralHeader(var Header: TZipEndOfCentralHeader): Boolean;
procedure DoZLibProgress(Sender: TObject);
protected
function InternalGetFileName(Index: Integer): string; virtual;
procedure CheckFileName(const ArchiveFileName: string); virtual;
function GetComment: string; virtual;
function GetFileComment(Index: Integer): string; virtual;
function GetTextEncode(const Header: TZipHeader): TEncoding; virtual;
procedure SetComment(Value: string); virtual;
procedure SetFileComment(Index: Integer; Value: string); virtual;
public
class constructor Create;
class destructor Destroy;
/// <remarks>
/// Call <c>RegisterCompressionHandler</c> to register a compression type that
/// can Compress/Decompress a stream. The output stream reads/write from/to InStream.
/// </remarks>
class procedure RegisterCompressionHandler(Compression: TZipCompression;
CompressStream, DecompressStream: TStreamConstructor);
/// <param name="ZipFileName">Path to Zip File</param>
/// <returns>Is the .ZIP file valid</returns>
class function IsValid(const ZipFileName: string): Boolean; static;
/// <summary> Extract a ZipFile</summary>
/// <param name="ZipFileName">File name of the ZIP file</param>
/// <param name="Path">Path to extract to disk</param>
/// <param name="ZipProgress">On progress callback.</param>
class procedure ExtractZipFile(const ZipFileName: string; const Path: string; ZipProgress: TZipProgressEvent = nil); overload; static;
class procedure ExtractZipFile(const ZipFileName: string; const Path: string; const Encoding: TEncoding; ZipProgress: TZipProgressEvent = nil); overload; static;
/// <summary> Zip the contents of a directory </summary>
/// <param name="ZipFileName">File name of the ZIP file</param>
/// <param name="Path">Path of directory to zip</param>
/// <param name="Compression">Compression mode.</param>
/// <param name="ZipProgress">On progress callback.</param>
class procedure ZipDirectoryContents(const ZipFileName: string; const Path: string; Compression: TZipCompression = zcDeflate; ZipProgress: TZipProgressEvent = nil); overload; static;
class procedure ZipDirectoryContents(const ZipFileName: string; const Path: string; const Encoding: TEncoding; Compression: TZipCompression = zcDeflate; ZipProgress: TZipProgressEvent = nil); overload; static;
/// <summary> Checks if header extra field contains unicode path, if true AFilename contains the unicode path</summary>
class function GetUTF8PathFromExtraField(const AHeader: TZipHeader; out AFileName: string): Boolean;
/// <summary> Create a TZipFile</summary>
constructor Create;
/// <remarks> Destroy will close an open zipfile before disposing of it</remarks>
destructor Destroy; override;
/// <summary> Opens a ZIP file for reading or writing.</summary>
/// <param name="ZipFileName">Path to ZipFile</param>
/// <param name="OpenMode"> File Mode to open file.
/// <c>zmWrite</c> Creates a new ZIP file for writing.
/// <c>zmReadWrite</c> Opens the file for reading and allows adding
/// additional new files.
/// <c>zmRead</c> Opens the file for reading.
///</param>
procedure Open(const ZipFileName: string; OpenMode: TZipMode); overload;
procedure Open(ZipFileStream: TStream; OpenMode: TZipMode); overload;
/// <remarks>
/// Closing is required to write the ZipFile's
/// Central Directory to disk. Closing a file that is open for writing
/// writes additonal metadata that is required for reading the file.
/// </remarks>
procedure Close;
/// <summary> Extract a single file </summary>
/// <remarks>
/// <c>FileName</c> specifies a file in the ZIP file. All slashes
/// in ZIP file names should be '/'.
/// The overload that takes an Integer may be useful when a ZIP file
/// has duplicate filenames.
/// </remarks>
/// <param name="FileName">File name in the archive</param>
/// <param name="Path">Path to extract to disk</param>
/// <param name="CreateSubdirs">The output should create sub directories specified in the ZIP file</param>
procedure Extract(const FileName: string; const Path: string = ''; CreateSubdirs: Boolean = True); overload;
procedure Extract(Index: Integer; const Path: string = ''; CreateSubdirs: Boolean = True); overload;
/// <summary> Extract All files </summary>
/// <param name="Path">Path to extract to.</param>
procedure ExtractAll(const Path: string = '');
/// <summary> Read a file from arcive to an array of Bytes </summary>
/// <remarks>
/// The overload that takes an Integer may be useful when a ZIP file
/// has duplicate filenames.
/// </remarks>
/// <param name="FileName">ZIP file FileName</param>
/// <param name="Bytes">Output bytes</param>
///
procedure Read(const FileName: string; out Bytes: TBytes); overload;
procedure Read(Index: Integer; out Bytes: TBytes); overload;
/// <summary> Get a stream to read a file from disk </summary>
/// <remarks>
/// The Stream returned by this function is a decomression stream
/// wrapper around the interal Stream reading the zip file. You must
/// Free this stream before using other TZipFile methods that change the
/// contents of the ZipFile, such as Read or Add.
/// The overload that takes an Integer may be useful when a ZIP file
/// has duplicate filenames.
/// </remarks>
/// <param name="FileName">ZIP file FileName</param>
/// <param name="Stream">Output Stream</param>
/// <param name="LocalHeader">Local File header</param>
procedure Read(const FileName: string; out Stream: TStream; out LocalHeader: TZipHeader); overload;
procedure Read(Index: Integer; out Stream: TStream; out LocalHeader: TZipHeader); overload;
/// <summary> Add a file to the ZIP file </summary>
/// <param name="FileName">FileName to be added</param>
/// <param name="ArchiveFileName">Path + Name of file in the arcive.
/// If Ommitted, <C>ExtractFileName(FileName)</C> will be used.</param>
/// <param name="Compression">Compression mode.</param>
procedure Add(const FileName: string; const ArchiveFileName: string = '';
Compression: TZipCompression = zcDeflate); overload;
/// <summary> Add a memory file to the ZIP file </summary>
/// <param name="Data">Bytes to be added</param>
/// <param name="ArchiveFileName">Path + Name of file in the arcive.</param>
/// <param name="Compression">Compression mode.</param>
///
procedure Add(Data: TBytes; const ArchiveFileName: string; Compression: TZipCompression = zcDeflate); overload;
/// <summary> Add a memory file to the ZIP file </summary>
/// <param name="Data">Stream of file to be added</param>
/// <param name="ArchiveFileName">Path + Name of file in the arcive.</param>
/// <param name="Compression">Compression mode.</param>
/// <param name="AExternalAttributes">External attributes for this file.</param>
procedure Add(Data: TStream; const ArchiveFileName: string; Compression: TZipCompression = zcDeflate;
AExternalAttributes: TFileAttributes = []); overload;
/// <summary> Add a memory file to the ZIP file. Allows programmer to specify
/// the Local and Central Header data for more flexibility on what gets written.
/// Minimal vailidation is done on the Header parameters; speficying bad options
/// could result in a corrupted zip file. </summary>
/// <param name="Data">Stream of file to be added</param>
/// <param name="LocalHeader">The local header data</param>
/// <param name="CentralHeader">A Pointer to an optional central header. If no
/// central Header is provided, the Local Header information is used. </param>
procedure Add(Data: TStream; LocalHeader: TZipHeader; CentralHeader: PZipHeader = nil); overload;
/// <summary>
/// Event fired before a file inside a zip file is decompressed, allows access to the raw stream for decrypt purposes
/// </summary>
class property OnCreateDecompressStream: TOnCreateCustomStream read FOnCreateDecompressStream write FOnCreateDecompressStream;
/// <summary>
/// Callback called before a file inside a zip file is decompressed, allows access to the raw stream for decrypt purposes
/// </summary>
class property CreateDecompressStreamCallBack: TCreateCustomStreamCallBack read FCreateDecompressStreamCallBack write FCreateDecompressStreamCallBack;
/// <summary> Translate from FileName to index in ZIP Central Header
/// </summary>
/// <remarks>
/// A ZIP file may have dupicate entries with the same name. This
/// function will return the index of the first.
/// </remarks>
/// <param name="FileName">Path + Name of file in the arcive.</param>
/// <returns>The index of the file in the archive, or -1 on failure.
/// </returns>
function IndexOf(const FileName: string): Integer;
/// <returns> The mode the TZipFile is opened to</returns>
property Mode: TZipMode read FMode;
/// <returns>Total files in ZIP File</returns>
property FileCount: Integer read GetFileCount;
/// <returns>An array of FileNames in the ZIP file</returns>
property FileNames: TArray<string> read GetFileNames;
/// <returns>An array of the TZipHeader of the files in the ZIP file</returns>
property FileInfos: TArray<TZipHeader> read GetFileInfos;
/// <returns>FileName of a File in the ZipFile</returns>
property FileName[Index: Integer]: string read GetFileName;
/// <returns>TZipHeader of a File in the ZipFile</returns>
property FileInfo[Index: Integer]: TZipHeader read GetFileInfo;
/// <remarks>
/// File Comments can be changed for files opened in write mode at any point.
/// The comment is written when the Central Directory is written to disk.
/// Comments can be a maximum of 65535 bytes long. If a longer comment is supplied,
/// It is truncated before writing to the ZIP File.
/// </remarks>
property FileComment[Index: Integer]: string read GetFileComment write SetFileComment;
/// <remarks>
/// Comments can be a maximum of 65535 bytes long. If a longer comment is supplied,
/// It is truncated before writing to the ZIP File.
/// </remarks>
property Comment: string read GetComment write SetComment;
property UTF8Support: Boolean read FUTF8Support write SetUTF8Support default True;
property Encoding: TEncoding read GetEncoding write FEncoding;
/// <summary> On progress event. </summary>
property OnProgress: TZipProgressEvent read FOnProgress write FOnProgress;
end;
implementation
uses
System.RTLConsts,
System.ZLib,
System.Types;
function DateTimeToWinFileDate(DateTime: TDateTime): UInt32;
var
Year, Month, Day, Hour, Min, Sec, MSec: Word;
begin
DecodeDate(DateTime, Year, Month, Day);
if (Year < 1980) or (Year > 2107)
then Result := 0
else
begin
DecodeTime(DateTime, Hour, Min, Sec, MSec);
LongRec(Result).Lo := (Sec shr 1) or (Min shl 5) or (Hour shl 11);
LongRec(Result).Hi := Day or (Month shl 5) or ((Year - 1980) shl 9);
end;
end;
function WinFileDateToDateTime(FileDate: UInt32; out DateTime: TDateTime): Boolean;
var
LDate: TDateTime;
LTime: TDateTime;
begin
Result := TryEncodeDate(
LongRec(FileDate).Hi shr 9 + 1980,
LongRec(FileDate).Hi shr 5 and 15,
LongRec(FileDate).Hi and 31,
LDate);
if Result then
begin
Result := TryEncodeTime(
LongRec(FileDate).Lo shr 11,
LongRec(FileDate).Lo shr 5 and 63,
LongRec(FileDate).Lo and 31 shl 1, 0, LTime);
if Result then
DateTime := LDate + LTime;
end;
end;
procedure VerifyRead(Stream: TStream; Buffer: TBytes; Count: Integer); overload;
begin
if Stream.Read(Buffer, Count) <> Count then
raise EZipException.CreateRes(@SZipErrorRead) at ReturnAddress;
end;
procedure VerifyRead(Stream: TStream; var Buffer: UInt8; Count: Integer); overload;
begin
if Stream.Read(Buffer, Count) <> Count then
raise EZipException.CreateRes(@SZipErrorRead) at ReturnAddress;
end;
procedure VerifyRead(Stream: TStream; var Buffer: UInt16; Count: Integer); overload;
begin
if Stream.Read(Buffer, Count) <> Count then
raise EZipException.CreateRes(@SZipErrorRead) at ReturnAddress;
end;
procedure VerifyRead(Stream: TStream; var Buffer: UInt32; Count: Integer); overload;
begin
if Stream.Read(Buffer, Count) <> Count then
raise EZipException.CreateRes(@SZipErrorRead) at ReturnAddress;
end;
procedure VerifyWrite(Stream: TStream; Buffer: TBytes; Count: Integer); overload;
begin
if Stream.Write(Buffer, 0, Count) <> Count then
raise EZipException.CreateRes(@SZipErrorWrite) at ReturnAddress;
end;
procedure VerifyWrite(Stream: TStream; Buffer: UInt8; Count: Integer); overload;
begin
if Stream.Write(Buffer, Count) <> Count then
raise EZipException.CreateRes(@SZipErrorWrite) at ReturnAddress;
end;
procedure VerifyWrite(Stream: TStream; Buffer: UInt16; Count: Integer); overload;
begin
if Stream.Write(Buffer, Count) <> Count then
raise EZipException.CreateRes(@SZipErrorWrite) at ReturnAddress;
end;
procedure VerifyWrite(Stream: TStream; Buffer: UInt32; Count: Integer); overload;
begin
if Stream.Write(Buffer, Count) <> Count then
raise EZipException.CreateRes(@SZipErrorWrite) at ReturnAddress;
end;
type
/// <summary> Helper class for reading a segment of another stream.</summary>
TStoredStream = class(TStream)
private
FStream: TStream;
FPos: Int64;
protected
function GetSize: Int64; override;
public
constructor Create(Stream: TStream);
function Read(var Buffer; Count: Longint): Longint; overload; override;
function Write(const Buffer; Count: Longint): Longint; overload; override;
function Read(Buffer: TBytes; Offset, Count: Longint): Longint; overload; override;
function Write(const Buffer: TBytes; Offset, Count: Longint): Longint; overload; override;
function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override;
end;
{ TStoredStream }
constructor TStoredStream.Create(Stream: TStream);
begin
FStream := Stream;
FPos := FStream.Position;
end;
function TStoredStream.GetSize: Int64;
begin
Result := FStream.Size;
end;
function TStoredStream.Read(var Buffer; Count: Longint): Longint;
begin
Result := FStream.Read(Buffer, Count);
end;
function TStoredStream.Read(Buffer: TBytes; Offset, Count: Longint): Longint;
begin
Result := FStream.Read(Buffer, Offset, Count);
end;
function TStoredStream.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64;
begin
Result := FStream.Seek(Offset, Origin)
end;
function TStoredStream.Write(const Buffer; Count: Longint): Longint;
begin
Result := FStream.Write(Buffer, Count);
end;
function TStoredStream.Write(const Buffer: TBytes; Offset, Count: Longint): Longint;
begin
Result := FStream.Write(Buffer, Offset, Count);
end;
function TZipCompressionToString(Compression: TZipCompression): string;
begin
case Compression of
zcStored: Result := 'Stored'; // do not localize
zcShrunk: Result := 'Shrunk'; // do not localize
zcReduce1: Result := 'Reduced1'; // do not localize
zcReduce2: Result := 'Reduced2'; // do not localize
zcReduce3: Result := 'Reduced3'; // do not localize
zcReduce4: Result := 'Reduced4'; // do not localize
zcImplode: Result := 'Imploded'; // do not localize
zcTokenize: Result := 'Tokenized'; // do not localize
zcDeflate: Result := 'Deflated'; // do not localize
zcDeflate64: Result := 'Deflated64'; // do not localize
zcPKImplode: Result := 'Imploded(TERSE)'; // do not localize
zcBZIP2: Result := 'BZIP2'; // do not localize
zcLZMA: Result := 'LZMA'; // do not localize
zcTERSE: Result := 'TERSE'; // do not localize
zcLZ77: Result := 'LZ77'; // do not localize
zcWavePack: Result := 'WavPack'; // do not localize
zcPPMdI1: Result := 'PPMd version I, Rev 1'; // do not localize
else
Result := 'Unknown';
end;
end;
{ TZipHeader }
const
EFSFLAG = 1 shl 11; // Language encoding flag (EFS)
function TZipHeader.GetUTF8Support: Boolean;
begin
Result := Flag and EFSFLAG = EFSFLAG; // Language encoding flag, UTF8
end;
procedure TZipHeader.SetUTF8Support(value: Boolean);
begin
if Value then
Flag := Flag or EFSFLAG
else
Flag := Flag and (not EFSFLAG);
end;
{ TZipFile }
function TZipFile.GetComment: string; // System comment.
var
E: TEncoding;
begin
if FMode = zmClosed then
raise EZipException.CreateRes(@SZipNotOpen);
if self.UTF8Support then
E := TEncoding.UTF8
else
E := Encoding;
Result := E.GetString(FComment);
end;
function TZipFile.GetEncoding: TEncoding;
function GetCP437Encoding: TEncoding;
var
E: TEncoding;
begin
if FCP437Encoding = nil then
begin
E := TEncoding.GetEncoding(437);
{$IFDEF AUTOREFCOUNT}
E.__ObjAddRef;
{$ENDIF AUTOREFCOUNT}
if AtomicCmpExchange(Pointer(FCP437Encoding), Pointer(E), nil) <> nil then
E.Free;
end;
Result := FCP437Encoding;
end;
begin
if FEncoding = nil then
Result := GetCP437Encoding
else
Result := FEncoding;
end;
function TZipFile.GetFileComment(Index: Integer): string;
begin
if FMode = zmClosed then
raise EZipException.CreateRes(@SZipNotOpen);
Result := GetTextEncode(FFiles[Index]).GetString(FFiles[Index].FileComment);
end;
function TZipFile.GetFileCount: Integer;
begin
if FMode = zmClosed then
raise EZipException.CreateRes(@SZipNotOpen);
Result := FFiles.Count;
end;
function TZipFile.GetFileInfo(Index: Integer): TZipHeader;
begin
if FMode = zmClosed then
raise EZipException.CreateRes(@SZipNotOpen);
Result := FFiles[Index];
end;
function TZipFile.GetFileInfos: TArray<TZipHeader>;
begin
if FMode = zmClosed then
raise EZipException.CreateRes(@SZipNotOpen);
Result := FFiles.ToArray;
end;
function TZipFile.InternalGetFileName(Index: Integer): string;
begin
Result := GetTextEncode(FFiles[Index]).GetString(FFiles[Index].FileName);
end;
function TZipFile.GetFileName(Index: Integer): string;
begin
if FMode = zmClosed then
raise EZipException.CreateRes(@SZipNotOpen);
Result := InternalGetFileName(Index);
end;
function TZipFile.GetFileNames: TArray<string>;
var
I: Integer;
begin
if FMode = zmClosed then
raise EZipException.CreateRes(@SZipNotOpen);
SetLength(Result, FFiles.Count);
for I := 0 to High(Result) do
Result[I] := InternalGetFileName(I);
end;
procedure TZipFile.ReadCentralHeader;
var
I: Integer;
Signature: UInt32;
LEndHeader: TZipEndOfCentralHeader;
LHeader: TZipHeader;
begin
FFiles.Clear;
if FStream.Size = 0 then
Exit;
// Read End Of Centeral Direcotry Header
if not LocateEndOfCentralHeader(LEndHeader) then
raise EZipException.CreateRes(@SZipErrorRead);
// Move to the beginning of the CentralDirectory
FStream.Position := LEndHeader.CentralDirOffset;
// Save Begginning of Central Directory. This is where new files
// get written to, and where the new central directory gets written when
// closing.
FEndFileData := LEndHeader.CentralDirOffset;
// Read File Headers
for I := 0 to LEndHeader.CentralDirEntries - 1 do
begin
// Verify Central Header signature
FStream.Read(Signature, Sizeof(Signature));
if Signature <> SIGNATURE_CENTRALHEADER then
raise EZipException.CreateRes(@SZipInvalidCentralHeader);
// Read Central Header
VerifyRead(FStream, LHeader.MadeByVersion, Sizeof(UInt16));
VerifyRead(FStream, LHeader.RequiredVersion, Sizeof(UInt16));
VerifyRead(FStream, LHeader.Flag, Sizeof(UInt16));
VerifyRead(FStream, LHeader.CompressionMethod, Sizeof(UInt16));
VerifyRead(FStream, LHeader.ModifiedDateTime, Sizeof(UInt32));
VerifyRead(FStream, LHeader.CRC32, Sizeof(UInt32));
VerifyRead(FStream, LHeader.CompressedSize, Sizeof(UInt32));
VerifyRead(FStream, LHeader.UncompressedSize, Sizeof(UInt32));
VerifyRead(FStream, LHeader.FileNameLength, Sizeof(UInt16));
VerifyRead(FStream, LHeader.ExtraFieldLength, Sizeof(UInt16));
VerifyRead(FStream, LHeader.FileCommentLength, Sizeof(UInt16));
VerifyRead(FStream, LHeader.DiskNumberStart, Sizeof(UInt16));
VerifyRead(FStream, LHeader.InternalAttributes, Sizeof(UInt16));
VerifyRead(FStream, LHeader.ExternalAttributes, Sizeof(UInt32));
VerifyRead(FStream, LHeader.LocalHeaderOffset, Sizeof(UInt32));
// Read Dynamic length fields (FileName, ExtraField, FileComment)
if LHeader.FileNameLength > 0 then
begin
SetLength(LHeader.FileName, LHeader.FileNameLength);
VerifyRead(FStream, LHeader.FileName, LHeader.FileNameLength);
end;
if LHeader.ExtraFieldLength > 0 then
begin
SetLength(LHeader.ExtraField, LHeader.ExtraFieldLength);
VerifyRead(FStream, LHeader.ExtraField, LHeader.ExtraFieldLength);
end;
if LHeader.FileCommentLength > 0 then
begin
SetLength(LHeader.FileComment, LHeader.FileCommentLength);
VerifyRead(FStream, LHeader.FileComment, LHeader.FileCommentLength);
end;
// Save File Header in interal list
FFiles.Add(LHeader);
end;
end;
procedure TZipFile.SetComment(Value: string);
var
E: TEncoding;
begin
if self.UTF8Support then
E := TEncoding.UTF8
else
E := Encoding;
FComment := E.GetBytes(Value);
if not (FMode in [zmReadWrite, zmWrite]) then
raise EZipException.CreateRes(@SZipNoWrite);
if Length(FComment) > $FFFF then
SetLength(FComment, $FFFF);
end;
procedure TZipFile.SetFileComment(Index: Integer; Value: string);
var
LFile: TZipHeader;
begin
if not (FMode in [zmReadWrite, zmWrite]) then
raise EZipException.CreateRes(@SZipNoWrite);
LFile := FFiles[Index];
LFile.UTF8Support := UTF8Support;
LFile.FileComment := GetTextEncode(LFile).GetBytes(Value);
if Length(LFile.FileComment) > $FFFF then
SetLength(LFile.FileComment, $FFFF);
LFile.FileCommentLength := Length(LFile.FileComment);
FFiles[Index] := LFile;
end;
procedure TZipFile.SetUTF8Support(const Value: Boolean);
begin
if Value = FUTF8Support then Exit;
if not (FMode in [zmReadWrite, zmWrite]) then
raise EZipException.CreateRes(@SZipNoWrite);
FUTF8Support := Value;
end;
class constructor TZipFile.Create;
begin
FCompressionHandler := TCompressionDict.Create;
RegisterCompressionHandler(zcStored,
function(InStream: TStream; const ZipFile: TZipFile; const Item: TZipHeader): TStream
begin
Result := TStoredStream.Create(InStream);
end,
function(InStream: TStream; const ZipFile: TZipFile; const Item: TZipHeader): TStream
begin
Result := TStoredStream.Create(InStream);
end);
RegisterCompressionHandler(zcDeflate,
function(InStream: TStream; const ZipFile: TZipFile; const Item: TZipHeader): TStream
begin
Result := TZCompressionStream.Create(InStream, zcDefault, -15);
end,
function(InStream: TStream; const ZipFile: TZipFile; const Item: TZipHeader): TStream
var
LStream : TStream;
LIsEncrypted: Boolean;
begin
// From https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT
// Section 4.4.4 general purpose bit flag: (2 bytes)
// Bit 0: If set, indicates that the file is encrypted.
LIsEncrypted := (Item.Flag and 1) = 1;
if Assigned(TZipFile.FOnCreateDecompressStream) then
LStream := TZipFile.FOnCreateDecompressStream(InStream, ZipFile, Item, LIsEncrypted)
else if Assigned(TZipFile.FCreateDecompressStreamCallBack) then
LStream := TZipFile.FCreateDecompressStreamCallBack(InStream, ZipFile, Item, LIsEncrypted)
else
LStream := InStream;
Result := TZDecompressionStream.Create(LStream, -15, LStream <> InStream);
end);
end;
class destructor TZipFile.Destroy;
begin
FCompressionHandler.Free;
FCP437Encoding.Free;
end;
class procedure TZipFile.RegisterCompressionHandler(
Compression: TZipCompression; CompressStream, DecompressStream: TStreamConstructor);
begin
FCompressionHandler.AddOrSetValue(Compression,
TPair<TStreamConstructor, TStreamConstructor>.Create(CompressStream, DecompressStream));
end;
class function TZipFile.IsValid(const ZipFileName: string): Boolean;
var
Z: TZipFile;
Header: TZipEndOfCentralHeader;
begin
Result := False;
try
Z := TZipFile.Create;
try
Z.FStream := TFileStream.Create(ZipFileName, fmOpenRead or fmShareDenyWrite);
try
Result := Z.LocateEndOfCentralHeader(Header);
finally
Z.FStream.Free;
end;
finally
Z.Free;
end;
except on E: EStreamError do
// Swallow only Stream exceptions and return False
end;
end;
function TZipFile.LocateEndOfCentralHeader(var Header: TZipEndOfCentralHeader): Boolean;
var
I: Integer;
LBackRead, LReadSize, LMaxBack: UInt32;
LBackBuf: TBytes;
begin
if FStream.Size < $FFFF then
LMaxBack := FStream.Size
else
LMaxBack := $FFFF;
LBackRead := 4;
SetLength(LBackBuf, $404 - 1);
while LBackRead < LMaxBack do
begin
if LBackRead + Cardinal(Length(LBackBuf) - 4) > LMaxBack then
LBackRead := LMaxBack
else
Inc(LBackRead, Length(LBackBuf) -4);
FStream.Position := FStream.Size - LBackRead;
if Length(LBackBuf) < (FStream.Size - FStream.Position) then
LReadSize := Length(LBackBuf)
else
LReadSize := FStream.Size - FStream.Position;
VerifyRead(FStream, LBackBuf, LReadSize);
for I := LReadSize - 4 downto 0 do
begin
if (LBackBuf[I] = ((SIGNATURE_ZIPENDOFHEADER ) and $FF)) and
(LBackBuf[I+1] = ((SIGNATURE_ZIPENDOFHEADER shr 8) and $FF)) and
(LBackBuf[I+2] = ((SIGNATURE_ZIPENDOFHEADER shr 16) and $FF)) and
(LBackBuf[I+3] = ((SIGNATURE_ZIPENDOFHEADER shr 24) and $FF)) then
begin
Move(LBackBuf[I+4], Header, SizeOf(Header));
if Header.CommentLength > 0 then
begin
FStream.Position := FStream.Size - LBackRead + I + 4 + SizeOf(Header);
SetLength(FComment, Header.CommentLength);
FStream.Read(FComment, Header.CommentLength);
end
else
SetLength(FComment, 0);
Exit(True);
end;
end;
end;
Result := False;
end;
class procedure TZipFile.ExtractZipFile(const ZipFileName: string; const Path: string; ZipProgress: TZipProgressEvent);
begin
ExtractZipFile(ZipFileName, Path, nil, ZipProgress);
end;
class procedure TZipFile.ExtractZipFile(const ZipFileName: string; const Path: string; const Encoding: TEncoding; ZipProgress: TZipProgressEvent);
var
LZip: TZipFile;
begin
LZip := TZipFile.Create;
try
LZip.Encoding := Encoding;
if Assigned(ZipProgress) then
LZip.OnProgress := ZipProgress;
LZip.Open(ZipFileName, zmRead);
LZip.ExtractAll(Path);
LZip.Close;
finally
LZip.Free;
end;
end;
class procedure TZipFile.ZipDirectoryContents(const ZipFileName: string; const Path: string;
Compression: TZipCompression; ZipProgress: TZipProgressEvent);
begin
ZipDirectoryContents(ZipFileName, Path, nil, Compression, ZipProgress);
end;
class procedure TZipFile.ZipDirectoryContents(const ZipFileName: string; const Path: string;
const Encoding: TEncoding; Compression: TZipCompression; ZipProgress: TZipProgressEvent);
var
LZipFile: TZipFile;
LFile: string;
LZFile: string;
LPath: string;
LFiles: TStringDynArray;
begin
LZipFile := TZipFile.Create;
try
LZipFile.Encoding := Encoding;
if Assigned(ZipProgress) then
LZipFile.OnProgress := ZipProgress;
if TFile.Exists(ZipFileName) then
TFile.Delete(ZipFileName);
LFiles := TDirectory.GetFiles(Path, '*', TSearchOption.soAllDirectories);
LZipFile.Open(ZipFileName, zmWrite);
LPath := System.SysUtils.IncludeTrailingPathDelimiter(Path);
for LFile in LFiles do
begin
// Strip off root path
{$IFDEF MSWINDOWS}
LZFile := StringReplace(Copy(LFile, Length(LPath) + 1, Length(LFile)), '\', '/', [rfReplaceAll]);
{$ELSE}
LZFile := Copy(LFile, Length(LPath) + 1, Length(LFile));
{$ENDIF MSWINDOWS}
LZipFile.Add(LFile, LZFile, Compression);
end;
finally
LZipFile.Free;
end;
end;
// Extract Unicode Path
// Based on section 4.6.9 -Info-ZIP Unicode Path Extra Field (0x7075) from
// https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT
// Stores the UTF-8 version of the file name field as stored in the
// local header and central directory header. (Last Revision 20070912)
//
// Value Size Description
// ----- ---- -----------
// (UPath) 0x7075 Short tag for this extra block type ("up")
// TSize Short total data size for this block
// Version 1 byte version of this extra field, currently 1
// NameCRC32 4 bytes File Name Field CRC32 Checksum
// UnicodeName Variable UTF-8 version of the entry File Name
class function TZipFile.GetUTF8PathFromExtraField(const AHeader: TZipHeader; out AFileName: string): Boolean;
const
UPATH = $7075;
SIZEPOS = 2;
CRCPOS = 5;
PATHPOS = 9;
PATHSIZESUB = 5;
var
I: Integer;
LTotalSize: Word;
LCRC: Cardinal;
LPathCRC: Cardinal;
begin
Result := False;
for I := 0 to AHeader.ExtraFieldLength - 2 do
begin
if PWord(@AHeader.ExtraField[I])^ = UPATH then
begin
LTotalSize := PWord(@AHeader.ExtraField[I + SIZEPOS])^;
LCRC := PCardinal(@AHeader.ExtraField[I + CRCPOS])^;
LPathCRC := crc32(0, nil, 0);
LPathCRC := crc32(LPathCRC, @AHeader.FileName[0], Length(AHeader.FileName));
if LPathCRC = LCRC then
begin
AFileName := TEncoding.UTF8.GetString(AHeader.ExtraField, I + PATHPOS, LTotalSize - PATHSIZESUB);
Result := True;
end;
Break;
end;
end;
end;
constructor TZipFile.Create;
begin
inherited Create;
FFiles := TList<TZipHeader>.Create;
FMode := zmClosed;
FUTF8Support := True;
end;
destructor TZipFile.Destroy;
begin
Close; // In case a file is open for writing currently
FFiles.Free;
inherited;
end;