forked from synopse/mORMot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SynZipFiles.pas
2116 lines (1951 loc) · 70.6 KB
/
SynZipFiles.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
/// high-level access to .zip archive file compression
// - this unit is a part of the freeware Synopse framework,
// licensed under a MPL/GPL/LGPL tri-license; version 1.18
unit SynZipFiles;
(*
This file is part of Synopse framework.
Synopse framework. Copyright (C) 2016 Arnaud Bouchez
Synopse Informatique - http://synopse.info
*** BEGIN LICENSE BLOCK *****
Version: MPL 1.1/GPL 2.0/LGPL 2.1
The contents of this file are subject to the Mozilla Public License Version
1.1 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
for the specific language governing rights and limitations under the License.
The Original Code is Synopse framework.
The Initial Developer of the Original Code is Arnaud Bouchez.
Portions created by the Initial Developer are Copyright (C) 2016
the Initial Developer. All Rights Reserved.
Contributor(s):
Alternatively, the contents of this file may be used under the terms of
either the GNU General Public License Version 2 or later (the "GPL"), or
the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
in which case the provisions of the GPL or the LGPL are applicable instead
of those above. If you wish to allow use of your version of this file only
under the terms of either the GPL or the LGPL, and not to allow others to
use your version of this file under the terms of the MPL, indicate your
decision by deleting the provisions above and replace them with the notice
and other provisions required by the GPL or the LGPL. If you do not delete
the provisions above, a recipient may use your version of this file under
the terms of any one of the MPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****
Version 1.10
- code modifications to compile with Delphi 6 compiler
Version 1.13
- handle Unicode versions of Delphi (Delphi 2009/2010/XE)
- now officialy handle UTF-8 encoded file names inside .Zip archive
Version 1.18
- removed uneeded reference to SynCrypto unit in uses clause
- fixed pure pascal compilation issue
- unit fixed and tested with Delphi XE2 (and up) 64-bit compiler
- fixed ticket [63132b355e] about reading empty folders from .zip archive
- added TZipEntry.LocalHeader and TZipEntry.LocalDataPosition methods
*)
interface
{$I Synopse.inc} // define HASINLINE USETYPEINFO CPU32 CPU64
uses
{$ifdef MSWINDOWS}
Windows,
// USEPDF: under Windows: get ZLib 1.2.3 functions from libpdf.dll
{$ifdef USEPDF}pdf,{$endif}
{$else}
{$ifdef FPC}
SynFPCLinux,
{$endif}
{$ifdef KYLIX3}
Types,
{$endif}
{$endif}
SynCommons,
Classes, SysUtils, SynZip;
{
Proprietary compression/encryption adding to standard zip files
- the .zip file structure is 100% compatible with standard
- data is stored uncompressed, but passed via TSynCompressionAlgo class
- algorithms are ID-identified (from 1 to 15)
- algorithm registration is made with SynCompressionAlgos.AlgoRegister
- ID is stored in unused 7..10 bits of "flags" zip entry (cf. PKware appnote)
- TSynCompressionAlgo is called by 64KB chunks or once for whole data
- inherit from TSynCompressionAlgoBuf to simply handle 64KB chunks
- Synopse has registered several TSynCompressionAlgo IDs:
1=SynLZ-chunked 2=SynLZ-whole
3=LzoAsm-chunked 4=LzoAsm-whole
5=Bz2-chunked
6=AES-chunked 7=AES+Zip-chunked 8=AES+SynLz-chunked
so you can use 9..15 for your own purpose
- most of this unit functions are TSynCompressionAlgo aware
}
type
TZipException = class(Exception);
TSynCompressionAlgo = class
protected
fDestStream: TStream;
public
/// initialize compression into OutStream
procedure CompressInit(OutStream: TStream); virtual;
/// compress InP[InLen] into OutStream + update CRC, return compressed length
function Compress(InP: pointer; InLen: cardinal; CRC: PCardinal): cardinal; virtual; abstract;
/// called once at the end for compression flush, return compressed length
// (default implementation: just do nothing)
function CompressFinish: cardinal; virtual;
/// return uncompressed length of InP[InLen] for proper mem allocation
function UnCompressedLength(InP: pointer; InLen: cardinal): cardinal; virtual; abstract;
/// uncompress InP[InLen] into OutP, return uncompressed length (called once for decompression)
function UnCompress(InP: pointer; InLen: cardinal; OutP: pointer): cardinal; virtual; abstract;
end;
TSynCompressionAlgoClass = class of TSynCompressionAlgo;
TSynCompressionAlgos = object
Values: array of record
ID, WholeID: integer;
func: TSynCompressionAlgoClass;
end;
procedure AlgoRegister(aAlgo: TSynCompressionAlgoClass; aID,aWholeID: integer);
function Algo(aID: integer): TSynCompressionAlgoClass;
function WholeAlgoID(aID: integer): integer;
end;
/// template class for 64KB chunked (not whole) algorithm (SynLZ, LZO...)
// which forces storing as uncompressed if compression ratio has no gain
TSynCompressionAlgoBuf = class(TSynCompressionAlgo)
protected
// fast tmp buffer (size=worse case with 64KB chunk)
fCompressBuf: PAnsiChar;
function AlgoCompress(src: PAnsiChar; size: integer; dst: PAnsiChar): integer; virtual; abstract;
function AlgoCompressLength(size: integer): integer; virtual; abstract;
function AlgoUnCompress(src: PAnsiChar; size: integer; dst: PAnsiChar): integer; virtual; abstract;
function AlgoUnCompressLength(src: PAnsiChar; size: integer): integer; virtual; abstract;
public
/// initialize compression into OutStream
procedure CompressInit(OutStream: TStream); override;
/// free fCompressBuf memory if allocated
destructor Destroy; override;
/// compress InP[InLen] into OutStream + update CRC, return compressed length
function Compress(InP: pointer; InLen: cardinal; CRC: PCardinal): cardinal; override;
/// return uncompressed length of InP[InLen] for proper mem allocation
function UnCompressedLength(InP: pointer; InLen: cardinal): cardinal; override;
/// uncompress InP[InLen] into OutP, return uncompressed length
function UnCompress(InP: pointer; InLen: cardinal; OutP: pointer): cardinal; override;
end;
/// template class for whole algorithm (SynLZ, LZO...)
// which forces storing as uncompressed if compression ratio has no gain
TSynCompressionAlgoWhole = class(TSynCompressionAlgo)
protected
function AlgoCompress(src: PAnsiChar; size: integer; dst: PAnsiChar): integer; virtual; abstract;
function AlgoCompressLength(size: integer): integer; virtual; abstract;
function AlgoUnCompress(src: PAnsiChar; size: integer; dst: PAnsiChar): integer; virtual; abstract;
function AlgoUnCompressLength(src: PAnsiChar; size: integer): integer; virtual; abstract;
public
/// compress InP[InLen] into OutStream + update CRC, return compressed length
function Compress(InP: pointer; InLen: cardinal; CRC: PCardinal): cardinal; override;
/// return uncompressed length of InP[InLen] for proper mem allocation
function UnCompressedLength(InP: pointer; InLen: cardinal): cardinal; override;
/// uncompress InP[InLen] into OutP, return uncompressed length
function UnCompress(InP: pointer; InLen: cardinal; OutP: pointer): cardinal; override;
end;
TZipCompressor = class(TStream)
private
fInitialized: Boolean;
fDestStream: TStream;
fStrm: TZStream;
fAlgorithm: TSynCompressionAlgo;
fAlgorithmStream: THeapMemoryStream;
fAlgorithmID: integer; // =0 if not Assigned(fAlgorithm)
fCRC: Cardinal;
fBlobDataHeaderPosition: integer;
fBufferIn, fBufferOut: array[word] of byte; // two 64kb buffers
procedure Finish;
function FlushBufferOut: integer;
function InFlateDeflate: boolean; // return true if error
function GetSizeIn: cardinal;
function GetSizeOut: cardinal;
public
constructor Create(outStream: TStream; CompressionLevel: Integer;
Algorithm: integer=0);
constructor CreateAsBlobData(outStream: TStream; CompressionLevel: Integer;
Algorithm: integer=0);
destructor Destroy; override;
function Read(var Buffer; Count: Longint): Longint; override;
function Write(const Buffer; Count: Longint): Longint; override;
function WriteOnce(const Buffer; Count: Longint): Longint;
function Seek(Offset: Longint; Origin: Word): Longint; override;
property SizeIn: cardinal read GetSizeIn;
property SizeOut: cardinal read GetSizeOut;
property CRC: cardinal read fCRC;
end;
TGzWriter = class(TZipCompressor)
private
outFile: TStream;
outFileToBeFree: boolean;
public
constructor Create(const aFileName: TFileName); overload;
constructor Create(const aDestStream: TStream); overload;
// use Write() to add some data
destructor Destroy; override;
end;
PZipEntry = ^TZipEntry;
TZipEntry = {$ifdef UNICODE} record {$else} object {$endif}
ZipName: RawUTF8;
Header: TFileHeader; // as stored in standard .zip file
function SameAs(const aEntry: TZipEntry): boolean;
// test if algo is registered, perform crc32 check and create one instance
function AlgoCreate(data: pointer; const FileName: TFileName): TSynCompressionAlgo;
function LocalHeader(ZipStart: PByteArray): PLocalFileHeader;
function LocalDataPosition(ZipStart: PByteArray): PtrUInt;
end;
TZipCommon = class
private
fCount: integer;
fFileName: TFileName;
public
Entry: array of TZipEntry;
constructor Create(const aFileName: TFileName);
destructor Destroy; override;
function ZipNameIndexOf(const aZipName: RawUTF8): integer;
property Count: integer read fCount;
property FileName: TFileName read fFileName;
end;
// used to transfert Blob Data from/to Client without compress/uncompress:
{$A-}
PBlobData = ^TBlobData;
TBlobData = object
private
// test if algo is registered, perform crc32 check and create one instance
function AlgoCreate(data: pointer): TSynCompressionAlgo;
public
dataSize, // always used
dataFullSize, dataCRC: cardinal; // used only if AlreadyCompressed
dataMethod: byte; // 0=stored 8=inflate >=16: AlgoID=dataMethod shr 4
databuf: AnsiChar;
function AlgoID: cardinal;
procedure SetFrom(const FileInfo: TFileInfo);
// uncompress if necessary:
function Expand: RawByteString;
// do freemem() if dataMethod<>0; no direct AES since may be mapped
function ExpandBuf(out destSize: cardinal): pointer;
procedure ExpandStream(Stream: TStream);
function Next: PAnsiChar; // points to next bloc
end;
{$A8}
const
BLOBDATA_HEADSIZE = sizeof(TBlobData)-sizeof(AnsiChar); // databuf: AnsiChar
type
TMemoryMap = object
// use mapped files: very fast + avoid unnecessary disk access
private
_map: cardinal;
public
buf: PByteArray;
_file,
_size: integer;
function DoMap(const aFileName: TFileName): boolean; // buf -> mapped file
procedure UnMap;
end;
TZipReader = class(TZipCommon)
protected
fMap: TMemoryMap;
public
constructor Create(const aFileName: TFileName);
destructor Destroy; override;
procedure Clear; // force Count=0
function GetData(aIndex: integer; aStream: TStream=nil; CheckCRC: boolean=false;
asBlobDataStored: boolean=false; withAlgoDataLen: boolean=false): PAnsiChar;
function GetString(aIndex: integer): RawByteString;
function GetBuffer(aIndex: integer; out Dest: PAnsiChar): integer;
function GetBlobData(aIndex: integer): RawByteString; overload; // PBlobData(result)
procedure GetBlobData(aIndex: integer; aStream: TStream); overload; // TBlobData->aStream
procedure DeleteLastEntry; // don't use inside TZipValues: already done in Create
procedure SaveToStream(aStream: TStream); // save uncompressed to stream
function SameAs(aReader: TZipReader): boolean;
property Map: TMemoryMap read fMap;
end;
TZipWriter = class(TZipCommon)
private
outFile: TFileStream;
fNow: integer;
fDestFileName: TFileName;
function AddEntry(const aZipName: RawUTF8; FileAge: integer = 0): PZipEntry;
public
Zip: TZipCompressor;
forceFileAge: integer; // <>0 -> will be used in Destroy to dest file
constructor Create(const aFileName: TFileName); overload;
constructor Create(AppendTo: TZipReader; ReCreate: boolean=false); overload;
constructor Create(fromStream: TStream; const DestFilename: TFileName=''); overload;
// restore after TZipReader.SaveToStream()
destructor Destroy; override;
/// this Creates a TZipCompressor -> user Zip.Write() to send data:
// if CompressionLevel<0: direct copy
procedure ZipCreate(const aZipName: RawUTF8; CompressionLevel: integer;
FileAge: integer = 0; Algorithm: integer=0);
/// compression finish, fileInfo update+save, Zip.Free;
// after ZipCreate: let aIndex=-1 will update Entry[Count]+inc(fCount)
procedure ZipClose(aIndex: integer=-1);
procedure Add(const aZipName: RawUTF8; data: PAnsiChar; dataSize: cardinal;
CompressionLevel: integer; dataCRC: pCardinal=nil;
FileAge: integer = 0; Algorithm: integer=0); overload;
procedure Add(const aZipName: RawUTF8; p: PBlobData); overload;
procedure Add(aReader: TZipReader; aReaderIndex: integer); overload;
procedure AddFile(const aFileName: TFileName; const aZipName: RawUTF8;
CompressionLevel: integer; Algorithm: integer=0);
function LastCRC32Added: cardinal;
end;
// TZip handles ZIP standard files on disk
TZip = class
private
FileQueue: TStringList;
SomeDeleted: boolean;
public
Reader: TZipReader;
Writer: TZipWriter;
constructor Create(const aFileName: TFileName);
destructor Destroy; override;
function FileName: TFileName;
function MarkDeleted(aReaderIndex: integer): boolean; virtual; // before any ZipCreate
function MarkDeletedBefore(aDate: TDateTime; aBackup: TZip=nil): boolean;
procedure BeginWriter; virtual;
function ZipCreate(const aZipName: RawUTF8; CompressionLevel: integer;
Algorithm: integer=0): TZipCompressor;
// use Zip.Write() to send data before ZipClose
procedure ZipClose;
function AddBuf(const aZipName: RawUTF8; CompressionLevel: integer;
data: pointer; dataSize: cardinal; Algorithm: integer=0): boolean;
function AddToFileQueue(const aFileName: TFileName;
const aZipName: RawUTF8): boolean; // flushed at Destroy
function SameAs(aZip: TZip): boolean;
function FileQueueCount: integer;
end;
TZipValues = class(TZip)
// store some Values[] in a .zip file (TBlob, TBlobDiff, TDC4...)
protected // all this must be overrided according to Values[]:
procedure LoadValues(data: PAnsiChar); virtual; abstract;
// SetLength(Values,Count+10); move(data,Values[0],Count*sizeof(Values[0]));
procedure SaveValues(Zip: TZipCompressor); virtual; abstract;
public
Count: integer;
modified: boolean;
constructor Create(const aFileName: TFileName); // make Reader.Create
destructor Destroy; override;
function GetValue(aReaderIndex: integer; aStream: TStream=nil): PAnsiChar;
procedure CopyValue(source, dest: integer); virtual; abstract;
// Values[dest] := Values[source];
procedure BeginWriter; override;
function MarkDeleted(aReaderIndex: integer): boolean; override; // before any AddValue
end;
var
BlobDataNull: TBlobData;
SynCompressionAlgos: TSynCompressionAlgos;
procedure CompressAsBlobData(const data; size: integer; aStream: TStream;
CompressionLevel: integer=6; Algorithm: integer=0);
// create a TBlobData in aStream - can use encryption with algo
// 7=AES+Zip-chunked and 8=AES+SynLz-chunked
function GZRead(const aFileName: TFileName): RawByteString; overload;
function GZRead(gz: PAnsiChar; gzLen: integer): RawByteString; overload;
procedure GZRead(const aFileName: TFileName; aStream: TStream; StoreLen: boolean); overload;
// direct uncompress .gz file into string or TStream
procedure GetDate(out Y,M,D: cardinal);
implementation
const // TZipException messages:
sZlibInternalError = 'zlib: Internal error';
sIncorrectZipFormatN = 'Incorrect zip format in file %s: %s';
sZipAlgoIDNUnknownN = 'Algo ID %d unknown for %s';
sZipCrcErrorNN = 'crc32 checksum error for %s in %s';
{ TZipCommon }
constructor TZipCommon.Create(const aFileName: TFileName);
begin
fFileName := aFileName;
end;
destructor TZipCommon.Destroy;
begin
Finalize(Entry);
inherited;
end;
function TZipCommon.ZipNameIndexOf(const aZipName: RawUTF8): integer;
begin
for result := 0 to Count-1 do
if SameTextU(Entry[result].ZipName,aZipName) then
exit;
result := -1;
end;
{ TZipReader }
procedure TZipReader.Clear;
begin
fCount := 0;
Map.UnMap;
end;
constructor TZipReader.Create(const aFileName: TFileName);
var i: integer;
lhr: ^TLastHeader;
H: ^TFileHeader;
tmp: WinAnsiString;
LastHeaderPosition: integer;
procedure Error(const msg: string);
begin
// MessageBox(0,pointer(fFileName),'Incorrect format',MB_ICONERROR);
Map.UnMap;
fCount := 0;
raise TZipException.CreateFmt(sIncorrectZipFormatN,[fFileName,msg]);
end;
begin
// 1. open aFileName
inherited; // fFileName := aFileName;
Map.DoMap(fFileName);
if Map.buf=nil then exit;
// 2. find last header, in order to reach the TFileHeader entries
if Map._size<sizeof(lhr^) then begin
Error('file too small');
exit;
end;
lhr := @Map.Buf[Map._Size-sizeof(lhr^)];
with lhr^ do begin
if signature<>$06054b50 then begin
Error('missing trailing signature');
exit;
end;
fCount := thisFiles;
SetLength(Entry,Count);
LastHeaderPosition := headerOffset;
end;
// 3. read all TFileHeader entries and fill Entry[] with its values
H := @Map.Buf[LastHeaderPosition];
for i := 0 to Count-1 do
with H^ do begin
if signature<>$02014b50 then begin
Error('missing local signature');
break;
end;
if (fileInfo.flags and (1 shl 3)<>0) or // crc+sizes in "data descriptor"
(fileInfo.zzipSize=0) or (fileInfo.zfullSize=0) then begin
Error('unexpected "data descriptor"');
break; // not handled yet: use SynZip's TZipRead to access this archive
end;
with Entry[i] do begin
{$ifdef MSWINDOWS}
if FileInfo.GetUTF8FileName then
SetString(ZipName,PAnsiChar(H)+sizeof(H^),fileInfo.nameLen) else begin
SetLength(tmp,fileInfo.nameLen); // convert from DOS/OEM into WinAnsi
OemToCharBuffA(PAnsiChar(H)+sizeof(H^),pointer(tmp),fileInfo.nameLen);
ZipName := WinAnsiToUtf8(tmp);
end;
{$else}
SetString(ZipName,PAnsiChar(H)+sizeof(H^),fileInfo.nameLen);
{$endif}
ZipName := StringReplaceChars(ZipName,'/','\');
Header := H^;
end; // next entry is after the ZipNname and some extra/comment
inc(PtrUInt(H),sizeof(H^)+fileInfo.nameLen+fileInfo.extraLen+commentLen);
end;
end;
procedure TZipReader.DeleteLastEntry;
// don't use inside TZipValues: already done in TZipValues.Create
begin
if Count<=0 then
exit;
dec(fCount);
end;
destructor TZipReader.Destroy;
begin
Map.UnMap;
inherited;
end;
function TZipReader.GetBlobData(aIndex: integer): RawByteString;
begin
result := '';
if (self=nil) or (cardinal(aIndex)>=cardinal(Count)) or (Map.buf=nil) then
exit;
with Entry[aIndex], LocalHeader(Map.buf)^ do
if not Header.IsFolder then begin
SetLength(result,fileInfo.zzipSize+BLOBDATA_HEADSIZE);
with PBlobData(result)^ do begin
SetFrom(fileInfo);
move(LocalData^,databuf,datasize);
end;
end;
end;
procedure TZipReader.GetBlobData(aIndex: integer; aStream: TStream);
// put TBlobData in aStream
var blob: TBlobData;
begin
if (self=nil) or (aIndex<0) or (aIndex>=Count) or (Map.buf=nil) then
aStream.Write(BlobDataNull,BLOBDATA_HEADSIZE) else
with Entry[aIndex], LocalHeader(Map.buf)^ do begin
blob.SetFrom(fileInfo);
aStream.Write(blob,BLOBDATA_HEADSIZE);
aStream.Write(LocalData^,blob.dataSize);
end;
end;
function TZipReader.GetBuffer(aIndex: integer; out Dest: PAnsiChar): integer;
begin
result := 0;
Dest := nil;
if (self=nil) or (aIndex<0) or (aIndex>=Count) or (Map.buf=nil) then
exit;
with Entry[aIndex], LocalHeader(Map.buf)^, fileInfo do
if not Header.IsFolder then begin
result := zfullSize;
if AlgoID<>0 then begin
with AlgoCreate(LocalData,FileName) do // crc32+algo object create
try // algo registered (no TZipException raised) -> uncompress
result := UnCompressedLength(LocalData,zfullsize);
Getmem(Dest,result);
UnCompress(LocalData,zfullsize,Dest); // direct uncompress into Dest
finally
Free;
end;
exit;
end;
Getmem(Dest,zfullSize);
if zfullSize>0 then
case zzipMethod of
0: move(LocalData^,Dest^,result); // stored = direct copy
8: if (UnCompressMem(LocalData,Dest,zzipSize,zfullSize)<>integer(zfullSize)) or
(crc32(0,Dest,zfullSize)<>zcrc32) then begin
Freemem(Dest);
Dest := nil;
raise TZipException.CreateFmt(sZipCrcErrorNN,[Entry[aIndex].ZipName,FileName]);
end;
end;
end;
end;
function TZipReader.GetData(aIndex: integer; aStream: TStream=nil;
CheckCRC: boolean=false; asBlobDataStored: boolean=false; withAlgoDataLen: boolean=false): PAnsiChar;
// aStream=nil -> return bulk memory data position in mapped file
// aStream<>nil -> uncompress and un-algo into aStream; CheckCRC=true -> force check CRC
// asBlobDataStored=true -> PBlobData stored format into aStream
// withAlgoDataLen=true -> unCompressed algo length stored into aStream
var CRC: cardinal;
CRCP: PCardinal;
Blob: TBlobData;
tmp: PAnsiChar;
L: cardinal;
begin
result := nil;
if (self=nil) or (aIndex<0) or (aIndex>=Count) or (Map.buf=nil) then
exit;
with Entry[aIndex], LocalHeader(Map.buf)^ do
if not Header.IsFolder then begin
result := LocalData;
if aStream=nil then
exit; // no decompress to stream: only get result PAnsiChar [and DataLen^]
if fileInfo.AlgoID<>0 then begin // bits 7..10 are used for algo
// un-algo specific uncompression
L := GetBuffer(aIndex,tmp); // uncompress with algo (always check crc)
if tmp<>nil then
try
if asBlobDataStored then begin // algo: add uncompressed data header
Blob.dataSize := L;
Blob.dataFullSize := L;
Blob.dataCRC := crc32(0,tmp,L);
Blob.dataMethod := fileInfo.AlgoID shl 4; // 0=stored + AlgoID
aStream.Write(Blob,BLOBDATA_HEADSIZE);
end else
if withAlgoDataLen then
aStream.Write(L,4);
aStream.Write(tmp^,L); // write uncompressed
finally
freemem(tmp);
end;
end else begin // standard zip format
if asBlobDataStored then begin
Blob.dataSize := FileInfo.zfullSize;
Blob.dataFullSize := FileInfo.zfullSize;
Blob.dataCRC := FileInfo.zcrc32;
Blob.dataMethod := 0; // stored, since will be uncompressed below
aStream.Write(Blob,BLOBDATA_HEADSIZE);
end;
case fileInfo.zzipMethod of
0: begin
aStream.Write(result^,fileInfo.zfullSize); // stored = direct copy
if CheckCRC then
CRC := crc32(0,result,fileInfo.zfullSize);
end;
8: begin // deflate
if CheckCRC then
CRCP := @CRC else CRCP := nil;
if UnCompressStream(result,fileInfo.zzipSize,aStream,CRCP)
<>fileInfo.zfullSize then result := nil;
end;
end; // case fileInfo.zzipMethod of
if CheckCRC and (CRC<>fileInfo.zcrc32) then
result := nil;
end;
end;
end;
function TZipReader.GetString(aIndex: integer): RawByteString;
begin
result := '';
if (self=nil) or (aIndex<0) or (aIndex>=Count) or (Map.buf=nil) then
exit;
with Entry[aIndex], LocalHeader(Map.buf)^, fileInfo do
if not Header.IsFolder then begin
if AlgoID<>0 then begin // special algo
with AlgoCreate(LocalData,FileName) do // crc32+algo object create
try // algo registered (no TZipException raised) -> uncompress
SetLength(result,UnCompressedLength(LocalData,zfullsize));
if UnCompress(LocalData,zfullsize,pointer(result))<> // direct uncompress into string
cardinal(length(result)) then
raise TZipException.CreateFmt(sZipCrcErrorNN,[Entry[aIndex].ZipName,FileName]);
finally
Free;
end;
end else // no algo: normal .zip file
case zzipMethod of
0: SetString(result,LocalData,zfullSize); // stored = direct copy
8: begin // deflate:
SetLength(result,zfullSize);
if (UnCompressMem(LocalData,pointer(result),zzipSize,zfullSize)<>integer(zfullSize)) or
(crc32(0,pointer(result),zfullSize)<>zcrc32) then
raise TZipException.CreateFmt(sZipCrcErrorNN,[Entry[aIndex].ZipName,FileName]);
end;
end;
end;
end;
function TZipReader.SameAs(aReader: TZipReader): boolean;
var i: integer;
begin
result := self=aReader; if result then exit;
if (self=nil) or (aReader=nil) or (Count<>aReader.Count) then
exit;
for i := 0 to Count-1 do
if not Entry[i].SameAs(aReader.Entry[i]) then
exit;
for i := 0 to Count-1 do
with Entry[i], LocalHeader(Map.buf)^ do
if not Header.IsFolder then
if not Comparemem(LocalData,
aReader.Entry[i].LocalHeader(aReader.Map.buf).LocalData,fileInfo.zzipSize) then
exit;
result := true;
end;
procedure TZipReader.SaveToStream(aStream: TStream);
var i: integer;
L: cardinal;
aName: RawUTF8;
begin
aName := StringToUTF8(ExtractFileName(fFileName));
// 1. write global params
L := length(aName);
aStream.Write(L,1);
aStream.Write(aName[1],L); // UTF-8 encoded file name
aStream.Write(fCount,4);
// 2. write Entry[].ZipName
for i := 0 to Count-1 do
with Entry[i] do begin
assert(not Header.IsFolder,'empty folders streaming is not implemented');
aStream.Write(Header.fileInfo,sizeof(Header.fileInfo));
aStream.Write(pointer(ZipName)^,Header.fileInfo.NameLen);
end;
// 3. write all uncompressed data
for i := 0 to Count-1 do
with Entry[i] do // withAlgoDataLen=true: algo -> uncompressed length stored
GetData(i,aStream,false,false,true); // deflate and un-algo if necessary
end;
{ TZip }
function TZip.AddBuf(const aZipName: RawUTF8; CompressionLevel: integer;
data: pointer; dataSize: cardinal; Algorithm: integer=0): boolean;
var Z: TZipCompressor;
begin
if self=nil then begin
result := false;
exit;
end;
if dataSize<512 then
CompressionLevel := -1; // force store if too small
Z := ZipCreate(aZipName,CompressionLevel,Algorithm); // Z=Writer.Zip
result := Z<>nil;
if not result then exit;
Z.WriteOnce(data^,dataSize);
ZipClose;
end;
function TZip.AddToFileQueue(const aFileName: TFileName; const aZipName: RawUTF8): boolean;
// flushed at Destroy
var i: integer;
begin
result := false;
if self=nil then exit;
if Writer=nil then begin
i := Reader.ZipNameIndexOf(aZipName);
if i>=0 then
MarkDeleted(i);
end else
if Writer.ZipNameIndexOf(aZipName)>=0 then
exit;
if FileQueue=nil then
FileQueue := TStringList.Create;
FileQueue.Values[aFileName] := UTF8ToString(aZipName);
result := true;
end;
procedure TZip.BeginWriter;
begin
if (self<>nil) and (Writer=nil) then
Writer := TZipWriter.Create(Reader); // append Reader, recreate=false
end;
constructor TZip.Create(const aFileName: TFileName);
begin
Reader := TZipReader.Create(aFileName);
// Writer will be created as necessary
end;
function GetValueFromIndex(List: TStrings; Index: Integer): string;
begin // not defined before Delphi 7
if Index >= 0 then
Result := Copy(List[Index],Length(List.Names[Index])+2,MaxInt) else
Result := '';
end;
destructor TZip.Destroy;
var i, method: integer;
zipName: TFileName;
begin
ZipClose; // close pending Writer.Zip if any
if SomeDeleted and (Writer=nil) and
((FileQueue=nil) or (FileQueue.Count=0)) then
BeginWriter else
if FileQueue<>nil then
for i := 0 to FileQueue.Count-1 do begin
zipName := GetValueFromIndex(FileQueue,i);
if zipName='' then
continue;
if GetFileNameExtIndex(zipName,'zip,jpg,jpeg,gz,bz2,bZ,7z,gif,bj,bjt')>=0 then
method := -1 else // store already compressed file
method := 6; // normal deflate compression
if Writer=nil then
BeginWriter;
Writer.AddFile(FileQueue.Names[i],StringToUTF8(zipName),method);
end;
FreeAndNil(FileQueue);
FreeAndNil(Reader);
FreeAndNil(Writer);
inherited;
end;
function TZip.FileName: TFileName;
begin
if (self=nil) or (Reader=nil) then
result := '' else
result := Reader.fFileName;
end;
function TZip.FileQueueCount: integer;
begin
if FileQueue=nil then
result := 0 else
result := FileQueue.Count;
end;
function TZip.MarkDeleted(aReaderIndex: integer): boolean;
begin
result := (self<>nil)and(Writer=nil)and(aReaderIndex>=0)and(aReaderIndex<Reader.Count);
if not result then
exit;
SomeDeleted := true;
//if aReaderIndex=Reader.Count-1 then Reader.DeleteLastEntry else !TZipValues use signature!
Reader.Entry[aReaderIndex].Header.signature := 0; // just signature = 0 to delete
end;
{$ifndef MSWINDOWS}
function DateTimeToFileDateWindows(DateTime: TDateTime): Integer;
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 NowToFileDateWindows: Integer;
begin
result := DateTimeToFileDateWindows(Now);
end;
{$endif}
function TZip.MarkDeletedBefore(aDate: TDateTime; aBackup: TZip=nil): boolean;
var dt, i: integer;
begin
result := false;
if (self=nil) or (Writer<>nil) then
exit;
dt := {$ifdef MSWINDOWS}DateTimeToFileDate{$else}DateTimeToFileDateWindows{$endif}(aDate);
for i := 0 to Reader.Count-1 do
with Reader.Entry[i].Header do
if (signature<>0) and (fileInfo.zlastMod<dt) then begin
if aBackup<>nil then begin
aBackup.BeginWriter;
aBackup.Writer.Add(Reader,i);
end;
MarkDeleted(i);
result := true;
end;
end;
function TZip.SameAs(aZip: TZip): boolean;
begin
result := self=aZip;
if result then
exit;
if (self=nil) or (aZip=nil) then
exit;
assert(Writer=nil);
if Writer<>nil then
exit;
result := Reader.SameAs(aZip.Reader);
end;
procedure TZip.ZipClose;
begin
if (self=nil) or (Writer=nil) then exit;
Writer.ZipClose;
end;
function TZip.ZipCreate(const aZipName: RawUTF8; CompressionLevel: integer;
Algorithm: integer=0): TZipCompressor;
// use TZipCompressor.Write() to send data - CompressionLevel<0 -> force store
var i: integer;
ZipName: string;
begin
result := nil;
if self=nil then exit;
if Writer=nil then begin
i := Reader.ZipNameIndexOf(aZipName);
if (i>=0) then
MarkDeleted(i);
end else
if Writer.ZipNameIndexOf(aZipName)>=0 then
exit;
if FileQueue<>nil then begin
ZipName := UTF8ToString(aZipName);
for i := 0 to FileQueue.Count-1 do
if GetValueFromIndex(FileQueue,i)=ZipName then begin
FileQueue.Delete(i);
break;
end;
end;
BeginWriter;
if Writer.Zip<>nil then
exit;
Writer.ZipCreate(aZipName,CompressionLevel,0,Algorithm);
result := Writer.Zip;
end;
{ TCompressorDecompressor }
constructor TZipCompressor.Create(outStream: TStream; CompressionLevel, Algorithm: Integer);
var Algo: TSynCompressionAlgoClass;
begin
fDestStream := outStream;
fBlobDataHeaderPosition := -1; // not AsBlobData
StreamInit(FStrm);
FStrm.next_out := @FBufferOut;
FStrm.avail_out := SizeOf(FBufferOut);
FStrm.next_in := @FBufferIn;
if Algorithm<>0 then begin
Algo := SynCompressionAlgos.Algo(Algorithm);
if not Assigned(Algo) then // unknown algo -> error
raise TZipException.CreateFmt(sZipAlgoIDNUnknownN,[Algorithm,ClassName]);
fAlgorithm := Algo.Create;
fAlgorithmID := Algorithm;
fAlgorithm.CompressInit(fDestStream);
if SynCompressionAlgos.WholeAlgoID(Algorithm)=Algorithm then
// whole algo = not a 64KB chunked algo
fAlgorithmStream := THeapMemoryStream.Create; // create temp buffer
end else begin
if CompressionLevel>=0 then // FInitialized=false -> direct copy to FDestStream
fInitialized := Check(deflateInit2_(FStrm, CompressionLevel, Z_DEFLATED,
-MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY,ZLIB_VERSION, sizeof(FStrm)),
[Z_OK])=Z_OK; // -MAX_WBITS -> no zLib header => .zip compatible !
end;
end;
constructor TZipCompressor.CreateAsBlobData(outStream: TStream;
CompressionLevel, Algorithm: Integer);
begin
Create(outStream,CompressionLevel,Algorithm);
fBlobDataHeaderPosition := outStream.Seek(0,soFromCurrent);
outStream.Write(FBufferOut,BLOBDATA_HEADSIZE); // save Bulk header
end;
destructor TZipCompressor.Destroy;
var p: integer;
blob: TBlobData;
begin
if FInitialized then begin
FStrm.next_out := nil;
FStrm.avail_out := 0;
deflateEnd(FStrm);
end else begin
FreeAndNil(fAlgorithmStream);
FreeAndNil(fAlgorithm);
end;
if fBlobDataHeaderPosition>=0 then begin // CreateAsBlobData() -> update header
p := fDestStream.Seek(0,soFromCurrent);
with blob do begin
dataFullSize := SizeIn;
dataSize := p-fBlobDataHeaderPosition-BLOBDATA_HEADSIZE;
assert(dataSize=SizeOut);
dataCRC := CRC;
// dataMethod: 0=stored 8=inflate >16: AlgoID=dataMethod shr 4
if FInitialized then
dataMethod := 8 else
dataMethod := fAlgorithmID shl 4; // stored + AlgoID
end;
fDestStream.Seek(fBlobDataHeaderPosition,soFromBeginning);
fDestStream.Write(blob,BLOBDATA_HEADSIZE);
fDestStream.Seek(p,soFromBeginning);
end;
inherited;
end;
procedure TZipCompressor.Finish;
begin
if (self=nil) then exit;
if assigned(fAlgorithm) then begin
if assigned(fAlgorithmStream) then begin
fAlgorithmStream.Write(fBufferIn,fStrm.avail_in); // write pending data
fStrm.total_in := fAlgorithm.Compress( // compress whole data at once
fAlgorithmStream.Memory,fAlgorithmStream.Seek(0,soFromCurrent),@fCRC);
end else
if FStrm.avail_in>0 then
inc(fStrm.total_in,fAlgorithm.Compress(@fBufferIn,FStrm.avail_in,@fCRC));
inc(fStrm.total_in,fAlgorithm.CompressFinish); // finish compression
fStrm.total_out := fStrm.total_in; // .zip file compression mode = stored
exit;
end;
if not FInitialized then
exit;
while FStrm.avail_in > 0 do begin // compress pending data
if InFlateDeflate then
raise TZipException.Create(SZlibInternalError);
if FStrm.avail_out = 0 then
FlushBufferOut;
end;
FStrm.next_in := nil;
FStrm.avail_in := 0;
while (Check(deflate(FStrm, Z_FINISH), [Z_OK, Z_STREAM_END]) <> Z_STREAM_END) and
(FStrm.avail_out = 0) do
FlushBufferOut;
FlushBufferOut;