-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathZMUnzipOpr.pas
1914 lines (1807 loc) · 53 KB
/
ZMUnzipOpr.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
unit ZMUnzipOpr;
// ZMUnzip.pas - unzip operations
(* ***************************************************************************
TZipMaster VCL originally by Chris Vleghert, Eric W. Engler.
Present Maintainers and Authors Roger Aelbrecht and Russell Peters.
Copyright (C) 1997-2002 Chris Vleghert and Eric W. Engler
Copyright (C) 1992-2008 Eric W. Engler
Copyright (C) 2009, 2010, 2011, 2012, 2013 Russell Peters and Roger Aelbrecht
Copyright (C) 2014 Russell Peters and Roger Aelbrecht
All rights reserved.
For the purposes of Copyright and this license "DelphiZip" is the current
authors, maintainers and developers of its code:
Russell Peters and Roger Aelbrecht.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* DelphiZip reserves the names "DelphiZip", "ZipMaster", "ZipBuilder",
"DelZip" and derivatives of those names for the use in or about this
code and neither those names nor the names of its authors or
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL DELPHIZIP, IT'S AUTHORS OR CONTRIBUTERS BE
LIABLE FOR ANYDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
contact: problems AT delphizip DOT org
updates: http://www.delphizip.org
*************************************************************************** *)
// modified 2014-09-10
{$I '.\ZipVers.inc'}
(*
FSpecArgs --
[global switches]
spec [local switches]
// file.zip>>filespec [local switches]
switches
/D:"[< or >]date" [< _ before or > _ after (default)] date
/D:"[< or >]-days" [< _ before or > _ after (default)] days ago
/J[+ or -] Junk dirs
/O[A or N or O or -] overwrite always, newer, older, never
/N[+ or -] flags not to use AddNewName (default N- _ use AddNewName)
/X:[old]::[new] replace 'old' with 'new' - must result in valid internal name
spec select files in current zip according to spec
/E:[|][spec[|spec]...] set excludes, if starts with | it appends to
globals otherwise use spec
/F: folder change ExtrBaseDir
/S or /S- turns on or off recurse into sub-folders
changes to excludes occur at current line and continue until changed
<password use password (to eol)
- does not change already included files.
local switches only applies to that line and modifies the 'current' excludes.
*)
interface
uses
{$IFDEF VERDXE2up}
System.Classes, System.SysUtils, WinApi.Windows, VCL.Graphics,
{$ELSE}
Classes, SysUtils, Windows, Graphics, {$IFNDEF VERD7up}ZMCompat, {$ENDIF}
{$ENDIF}
ZipMstr, ZMZipReader, ZMZipDirectory, ZMEngine,
ZMArgSplit, ZMZipBase, ZMStructs, ZMBaseOpr;
type
TZMUnzOpts = class(TZMSelectArgs)
private
FBefore: Boolean;
FDOSDate: Cardinal;
FExcludes: string;
FFolder: string;
FJunkDir: Boolean;
FNFlag: Boolean;
FOvrOpt: TZMMergeOpts;
FPassword: string;
FTFlag: Boolean;
FXArg: string;
public
function Accept(Rec: TZMEntryBase): Boolean; override;
procedure Assign(Other: TZMSelectArgs); override;
function Cloned: TZMUnzOpts;
property Before: Boolean read FBefore write FBefore;
property DOSDate: Cardinal read FDOSDate write FDOSDate;
property Excludes: string read FExcludes write FExcludes;
property Folder: string read FFolder write FFolder;
property JunkDir: Boolean read FJunkDir write FJunkDir;
property NFlag: Boolean read FNFlag write FNFlag;
property OvrOpt: TZMMergeOpts read FOvrOpt write FOvrOpt;
property Password: string read FPassword write FPassword;
property TFlag: Boolean read FTFlag write FTFlag;
property XArg: string read FXArg write FXArg;
end;
type
TZMUnzipOpr = class(TZMBaseOpr)
private
FExtractor: TZMDecompressor;
FSingleFile: Boolean;
FSplitter: TZMArgSplitter;
FZName: string;
FZReader: TZMZipReader;
FZRec: TZMEntryBase;
function AsStream(Obj: Pointer): TStream;
function CheckCRC(CRC, ReqCRC: DWORD; const FileName: string): Integer;
function CheckEncryption(const FName: string): Integer;
function CheckEncryptionEx(const FName, Pw: string): Integer;
function CheckExistsOrReplacable(var Exists: Boolean;
const DestFileName: string; const Options: TZMUnzOpts): Integer;
function CleanFileName(var DestFileName: string): Integer;
procedure DeflateProgress(Sender: TObject; const Count: Integer;
IsRead: Boolean);
function DoExtractStreamStream(InStream: TMemoryStream;
InitOutSize: Longword; HeaderType: TZMZHeader): Integer;
function DoUndeflate(OutStream, InStream: TStream; Length: Int64;
var Method: TZMDeflates; var CRC: Cardinal): Integer;
function FinaliseExtracted(Writer: TZMZipBase; const DestName: string;
UseNTFS: Boolean): Integer;
function ForceBaseDir(const BasePath: string): Integer;
function ProcessInclude(SrcZip: TZMZipReader; const Spec: string; const Args:
TZMUnzOpts): Integer;
procedure RemoveExistingFile(const DestFileName: string);
procedure ReportSkipped(const Spec: string; Reason: TZMSkipTypes; Error:
Integer);
function SelectUnzFiles(SrcZip: TZMZipReader): Integer;
procedure SetZReader(const Value: TZMZipReader);
procedure SetZRec(const Value: TZMEntryBase);
function TestEntry(Rec: TZMEntryBase): Integer;
function TestPhrase(const Key: string): Integer;
function UnzipEntry(const BasePath, DestFileName: string;
const Exists: Boolean; const Options: TZMUnzOpts): Integer;
function UnZipSelected(CurZip: TZMZipReader;
SelectedCount: Integer): Integer;
function UnzipTheEntry(const DestFileName: string;
Options: TZMUnzOpts): Integer;
function UpdateName(var DestFileName: string; const BasePath: string;
const Options: TZMUnzOpts): Integer;
function UpdateOptionsFromSplitter(var Args: TZMUnzOpts;
const ParentExcludes: string): Boolean;
protected
AnswerNoAll: Boolean;
function AskOverwrite(const FName: string; Older: Boolean;
Idx: Integer): Boolean;
function BuildPath(const Dir, PathBase: string;
ZFile: TZMZipReader): Boolean;
function CanSkip(const FileName: string; Error: Integer): TZMSkipTypes;
procedure DefaultOptions(Options: TZMUnzOpts);
function DoSetExtNameEvent(const ZBasePath: string;
var OverName: string): Integer;
function FlattenExcludes: string;
function UnzipAFile(var DestName: string; const Rec: TZMEntryBase;
const Options: TZMUnzOpts): Integer;
function UnzipAStream(DestStream: TStream; const Rec: TZMEntryBase)
: Integer;
property SingleFile: Boolean read FSingleFile write FSingleFile;
property ZName: string read FZName;
property ZReader: TZMZipReader read FZReader write SetZReader;
property ZRec: TZMEntryBase read FZRec write SetZRec;
public
procedure AfterConstruction; override;
procedure BeforeDestruction; override;
function ExtractFileToStream(const EntryName: string): Integer;
function ExtractStreamToStream(InStream: TMemoryStream; OutSize: Longword;
HeaderType: TZMZHeader): Integer;
function Undeflate(OutStream, InStream: TStream; Length: Int64;
var Method: TZMDeflates; var CRC: Cardinal): Integer;
function UnzipFiles: Integer;
// extract single file
function UnzipToFile(const DestName: string;
const ExtRec: TZMDirEntry): Integer;
// extract single file
function UnzipToStream(DestStream: TStream;
const ExtRec: TZMDirEntry): Integer;
end;
implementation
uses
{$IFDEF VERDXE2up}
Vcl.Dialogs, WinApi.ShlObj,
{$ELSE}
Dialogs, ShlObj,
{$ENDIF}
ZMLister, ZMBody, ZMUtils, ZMMsg, ZMWinFuncs, ZMCore, ZMMisc, ZMXcpt;
const
__UNIT__ = 37;
type
TZMUnzStreamArg = class(TZMSelectArgs)
private
FTheStream: TStream;
public
constructor Create(AStream: TStream);
function Accept(Rec: TZMEntryBase): Boolean; override;
procedure BeforeDestruction; override;
property TheStream: TStream read FTheStream write FTheStream;
end;
const
BadStatus = ZsbInvalid or ZsbError or ZsbDiscard;
const
UnzIncludeListThreshold = 10;
function ZM_Error(Line, Error: Integer): Integer;
begin
Result := -((__UNIT__ shl ZERR_UNIT_SHIFTS) + (Line shl ZERR_LINE_SHIFTS) or
AbsErr(Error));
end;
{ TZMUnzipOpr }
procedure TZMUnzipOpr.AfterConstruction;
begin
inherited;
FSplitter := TZMArgSplitter.Create;
FExtractor := TZMDecompressor.Create(-32 * 1024);
end;
(* Actioncode = 10, zacOverwrite,
* Extract(UnZip) Overwrite ask.
* (O) Arg3 = 'older'
* (O) Arg2 = Index
* (O) Arg1 = Overwrite_All
* (O) MsgP = filename
* (I) ActionCode -1 = overwrite
* -2 = don't overwrite
*)
function TZMUnzipOpr.AskOverwrite(const FName: string; Older: Boolean;
Idx: Integer): Boolean;
var
DoOverwrite: Boolean;
TmpExtractOverwrite: TZMExtractOverwriteEvent;
begin
Result := False;
TmpExtractOverwrite := Master.OnExtractOverwrite;
if Assigned(TmpExtractOverwrite) then
begin
DoOverwrite := AnswerAll;
TmpExtractOverwrite(Master, FName, Older, DoOverwrite, Idx);
if DoOverwrite then
Result := True;
Body.TraceFmt('[Overwrite] IN=%s,%d OUT=%s', [BoolStr(AnswerAll), Idx,
BoolStr(Result)], {_LINE_}272, __UNIT__);
end;
end;
function TZMUnzipOpr.AsStream(Obj: Pointer): TStream;
var
AnObj: TObject;
begin
Result := nil;
if Obj <> nil then
begin
AnObj := TObject(Obj);
if AnObj is TStream then
Result := TStream(AnObj);
end;
end;
procedure TZMUnzipOpr.BeforeDestruction;
begin
FSplitter.Free;
FExtractor.Free;
inherited;
end;
function TZMUnzipOpr.BuildPath(const Dir, PathBase: string;
ZFile: TZMZipReader): Boolean;
var
FolderRec: TZMEntryBase;
NTFSTimes: TNTFS_Times;
OFileHandle: THandle;
Parent: string;
RelDir: string;
SDir: string;
begin
Result := True;
if Dir <> '' then
begin
Body.Trace('-- build path: ' + Dir, {_LINE_}309, __UNIT__);
SDir := DelimitPath(Dir, False);
if _Z_DirExists(SDir) then
Exit;
if (Length(SDir) = 2) and (SDir[2] = ':') then
Exit;
Parent := ExtractFilePath(SDir);
if Parent = SDir then
Exit; // avoid 'c:\xyz:\' problem.
if BuildPath(Parent, PathBase, ZFile) then
begin
Result := _Z_CreateDir(SDir);
if Result and (ExtrNTFS in Body.ExtrOptions) and
(Length(SDir) > Length(PathBase)) then
begin
// find folder name entry
RelDir := Copy(SDir, Length(PathBase) + 1, MAX_PATH);
RelDir := DelimitPath(RelDir, True);
FolderRec := ZFile.FindName(RelDir, nil);
if (FolderRec <> nil) and (FolderRec.FetchNTFSTimes(NTFSTimes) > 0) then
begin
// set times to NTFS times
OFileHandle := _Z_CreateFile(PChar(SDir),
GENERIC_READ + GENERIC_WRITE, 0, nil, OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS, 0);
if (OFileHandle <> INVALID_HANDLE_VALUE) then
begin
try
Result := SetFileTime(OFileHandle, @NTFSTimes.CTime,
@NTFSTimes.ATime, @NTFSTimes.MTime);
finally
CloseHandle(OFileHandle);
end
end;
end;
end;
end;
end;
end;
function TZMUnzipOpr.CanSkip(const FileName: string; Error: Integer)
: TZMSkipTypes;
var
Err: Integer;
begin
Result := StNoSkip;
Err := AbsErr(Error);
if Error <> 0 then
begin
// What isn't fatal
case Err of
ZE_BadFileName, ZE_FileCreate, ZE_LOHBadRead, ZE_LOHWrongName,
ZE_NoExtrDir, ZE_NoOutFile, ZE_PasswordCancel, ZE_ReadZipError,
ZE_SeekError, ZE_CryptError, ZE_NoChangeDir, ZE_WrongLength,
ZE_ZipDataError:
Result := StGeneralExtractError;
ZE_PasswordFail, ZE_WrongPassword, ZE_UnatExtPWMiss:
Result := StBadPassword;
ZE_NotFound:
Result := StOnFreshen;
ZE_NoOverwrite:
Result := StNoOverwrite;
ZE_BadCRC:
Result := StCRCError;
ZE_BuildPathError:
Result := StPathError;
ZE_EntryCancelled:
Result := StUser;
ZE_SetDateError, ZE_SetFileAttributes, ZE_SetFileTimes,
ZE_SetFileInformation:
Result := StWarning;
ZE_Unsupported:
Result := StCompressionUnknown;
end;
end;
if (Result <> StNoSkip) and Skipping(FileName, Result, Error) then
Result := StNoSkip;
end;
function TZMUnzipOpr.CheckCRC(CRC, ReqCRC: DWORD; const FileName: string):
Integer;
var
DoExtract: Boolean;
TmpCRCError: TZMCRC32ErrorEvent;
begin
Result := 0;
if CRC <> ReqCRC then
begin
Body.InformFmt(' >>> crc error: %4x should be %4x', [CRC, ReqCRC],
{_LINE_}399, __UNIT__);
DoExtract := False;
TmpCRCError := Master.OnCRC32Error;
if Assigned(TmpCRCError) then
TmpCRCError(Master, FileName, CRC, ReqCRC, DoExtract);
if DoExtract then
Result := 0
else
Result := ZE_BadCRC;
Result := ZM_Error({_LINE_}408, Result);
end;
end;
// return 0 _ password match, <0 _ error or cancel, >0 _ no match
function TZMUnzipOpr.CheckEncryption(const FName: string): Integer;
var
AllowedReqs: Integer;
HasKey: Boolean;
Key: string;
PWErr: Integer;
ReqsLeft: Integer;
Response: TMsgDlgBtn;
TmpPasswordError: TZMPasswordErrorEvent;
begin
Key := Body.Password; // test global first
HasKey := Key <> '';
if HasKey then
PWErr := ZE_PasswordFail
else
PWErr := ZE_UnatExtPWMiss;
if HasKey then
begin
Result := TestPhrase(Key);
if Result <= 0 then
Exit; // matched or error
end;
// Ask for password
ReqsLeft := Body.PasswordReqCount;
AllowedReqs := 15;
Result := -1;
while (ReqsLeft > 0) and (AllowedReqs > 0) and not AnswerNoAll do
begin
CheckCancel;
Key := '';
Response := MbOK;
TmpPasswordError := Body.Master.OnPasswordError;
if Assigned(TmpPasswordError) then
begin
TmpPasswordError(Body.Master, False, Key, FName, LongWord(ReqsLeft),
Response);
ReqsLeft := ReqsLeft and 15;
end
else
begin
if not Body.Unattended then
Key := Body._GetExtrPassword(Response)
else
begin
Result := ZM_Error({_LINE_}457, PWErr);
Body.ShowError(Result);
Exit;
end;
end;
if (Response = MbCancel) or (Response = MbAbort) or (Response = MbNoToAll)
then
begin
if Response = MbNoToAll then
AnswerNoAll := True;
Result := ZM_Error({_LINE_}467, ZS_Canceled);
Break;
end;
if Response <> MbOk then
Key := ''; // ignore
Body.Password := Key; // save key for later entries too
if Key <> '' then
begin
if TestPhrase(Key) = 0 then
begin
Result := 0; // matched
Break;
end;
Result := ZM_Error({_LINE_}480, ZE_PasswordFail);
end;
if ReqsLeft > AllowedReqs then
ReqsLeft := AllowedReqs;
Dec(ReqsLeft);
Dec(AllowedReqs);
end;
if Result = -1 then
Result := ZM_Error({_LINE_}488, PWErr);
end;
// return 0 _ password match, <0 _ error or cancel, >0 _ no match
function TZMUnzipOpr.CheckEncryptionEx(const FName, Pw: string): Integer;
begin
if Pw <> '' then
Result := TestPhrase(Pw)
else
Result := CheckEncryption(FName);
end;
function TZMUnzipOpr.CheckExistsOrReplacable(var Exists: Boolean;
const DestFileName: string; const Options: TZMUnzOpts): Integer;
var
DoOverWrite: Boolean;
ExistDate: TDateTime;
TmpOnOverWrite: TZMExtractOverwriteEvent;
begin
Result := 0;
Exists := FileLastModified(DestFileName, ExistDate);
if (not Exists) and (ExtrFreshen in Body.ExtrOptions) then
begin
Result := ZM_Error({_LINE_}511, ZE_NotFound);
Exit; // skip entry
end;
if Exists then
begin
if Verbosity >= ZvVerbose then
begin
Body.InformFmt('"%s" exists = %s file = %s',
[DestFileName, DateTimeToStr(ExistDate), DateTimeToStr(ZRec.DateStamp)],
{_LINE_}521, __UNIT__);
end;
TmpOnOverWrite := Master.OnExtractOverwrite;
DoOverWrite := True;
if ExistDate < ZRec.DateStamp then
begin
// exists older
DoOverWrite := (Options.OvrOpt = ZmoAlways) or
(Options.OvrOpt = ZmoNewer);
if Assigned(TmpOnOverWrite) then
TmpOnOverWrite(Master, DestFileName, True, DoOverWrite, ZRec.ExtIndex);
end
else
begin
// exists newer
DoOverWrite := ((Options.OvrOpt = ZmoAlways) or
(Options.OvrOpt = ZmoOlder)) and
not((ExtrFreshen in Body.ExtrOptions) or
(ExtrUpdate in Body.ExtrOptions));
if Assigned(TmpOnOverWrite) then
TmpOnOverWrite(Master, DestFileName, False, DoOverWrite, ZRec.ExtIndex);
end;
if not DoOverWrite then
Result := Body.PrepareErrMsg(ZE_NoOverwrite, [DestFileName], {_LINE_}544,
__UNIT__); // skip entry
end;
end;
function TZMUnzipOpr.CleanFileName(var DestFileName: string): Integer;
var
Cleaned: string;
begin
Result := 0;
if not IsExtPath(DestFileName) then
begin
Result := CleanPath(Cleaned, DestFileName, True);
if Result <> 0 then
begin
Body.InformFmt('Invalid filename [%d]: "%s"',
[AbsErr(Result), DestFileName], {_LINE_}560, __UNIT__);
Result := Body.PrepareErrMsg(ZE_BadFileName, [DestFileName],
{_LINE_}562, __UNIT__);
end
else
DestFileName := Cleaned;
end;
end;
procedure TZMUnzipOpr.DefaultOptions(Options: TZMUnzOpts);
begin
Options.Before := False;
Options.DOSDate := 0;
Options.Excludes := FlattenExcludes;
Options.Folder := Body.ExtrBaseDir;
Options.JunkDir := not(ExtrDirNames in Body.ExtrOptions);
Options.NFlag := not Assigned(Body.Master.OnSetExtName);
Options.Password := ''; // use global or ask
Options.TFlag := ExtrNTFS in Body.ExtrOptions;
Options.XArg := '';
if ExtrOverWrite in Body.ExtrOptions then
Options.OvrOpt := ZmoAlways
else
Options.OvrOpt := ZmoConfirm;
end;
procedure TZMUnzipOpr.DeflateProgress(Sender: TObject; const Count: Integer;
IsRead: Boolean);
begin
if IsRead then
Progress.Advance(Count)
else
Progress.MoreWritten(Count);
if Body.Cancel <> 0 then
raise EZMAbort.Create;
end;
function TZMUnzipOpr.DoExtractStreamStream(InStream: TMemoryStream;
InitOutSize: Longword; HeaderType: TZMZHeader): Integer;
var
Done: Integer;
Header: TZM_StreamHeader;
Method: TZMDeflates;
Mthd: Integer;
Realsize: Integer;
begin
Result := 0;
Realsize := Integer(InStream.Size - InStream.Position) -
SizeOf(TZM_StreamHeader);
Method := ZmDeflate;
Body.ZipStream.SetSize(InitOutSize);
if (HeaderType = ZzAuto) and (Realsize < 0) then
HeaderType := ZzCompat; // assume a few bytes of data only
if (HeaderType <> ZzCompat) and (Realsize >= 0) then
begin
InStream.ReadBuffer(Header, SizeOf(TZM_StreamHeader));
case Header.Method of
METHOD_DEFLATED:
Method := ZmDeflate;
METHOD_STORED:
Method := ZmStore;
else
if HeaderType = ZzAuto then
begin
HeaderType := ZzCompat;
Realsize := Realsize + SizeOf(TZM_StreamHeader);
if InStream.Seek(-Sizeof(TZM_StreamHeader), SoCurrent) < 0 then
begin
Result := ZM_Error({_LINE_}628, ZE_SeekError);
Body.ZipStream.Size := 0;
Exit;
end;
end
else
begin
Result := ZM_Error({_LINE_}635, ZE_Unsupported);
Body.ZipStream.Size := 0;
Exit;
end;
end;
end;
if Realsize > 0 then
begin
Progress.NewItem('<stream>', InitOutSize);
try
FExtractor.OutStream := Body.ZipStream;
FExtractor.InStream := InStream;
FExtractor.InSize := -1;
FExtractor.OutSize := -1; // no limit
if Method = ZmDeflate then
Mthd := METHOD_DEFLATED
else
Mthd := METHOD_STORED;
Result := FExtractor.Prepare(Mthd);
if Result = 0 then
begin
Done := FExtractor.Decompress;
if Done < 0 then
Result := ZM_Error({_LINE_}658, ZE_InvalidZip)
else
begin
if (HeaderType <> ZzCompat) and (Header.CRC <> FExtractor.CRC) then
begin
Body.InformFmt(' >>> crc error: %4x should be %4x',
[FExtractor.CRC, Header.CRC], {_LINE_}664, __UNIT__);
Result := ZM_Error({_LINE_}665, ZE_BadCRC);
end;
end;
end;
Body.TraceFmt('Inflate returns: %s', [Errors.ErrorStr(Result)],
{_LINE_}670, __UNIT__);
finally
Progress.EndItem;
end;
end;
end;
// return <0 _ skipped, 0 _ did nothing, >0 _ changed
function TZMUnzipOpr.DoSetExtNameEvent(const ZBasePath: string;
var OverName: string): Integer;
var
IsChanged: Boolean;
TempName: string;
TmpSetExtName: TZMSetExtNameEvent;
begin
Result := 0;
TmpSetExtName := Master.OnSetExtName;
if Assigned(TmpSetExtName) then
begin
TempName := ZName;
IsChanged := False;
TmpSetExtName(Master, TempName, ZBasePath, IsChanged);
if IsChanged then
begin
Body.InformFmt('%s changed to: "%s"', [ZName, TempName], {_LINE_}694,
__UNIT__);
TempName := Unquote(TempName);
if TempName = '' then
begin
Result := ZM_Error({_LINE_}699, ZE_EntryCancelled);
Body.InformFmt('user cancelled: %s', [ZName], Result, 0);
end
else
begin
OverName := TempName;
Result := 1; // changed
end;
end;
end;
end;
// return <0 _ error, 0 _ ok, >0 _ error not extracted (skipped)
function TZMUnzipOpr.DoUndeflate(OutStream, InStream: TStream; Length: Int64;
var Method: TZMDeflates; var CRC: Cardinal): Integer;
var
Done: Integer;
Mthd: Integer;
begin
if Length < 0 then
Length := InStream.Size;
if Length = 0 then
begin
Length := InStream.Size;
InStream.Position := 0;
end;
Progress.TotalCount := 1;
Progress.TotalSize := Length; // to read
FExtractor.InStream := InStream;
FExtractor.InSize := Length;
FExtractor.OutStream := OutStream;
FExtractor.OutSize := -1; // no limit
FExtractor.OnProgress := DeflateProgress;
if Method = ZmDeflate then
Mthd := METHOD_DEFLATED
else
Mthd := METHOD_STORED;
Result := FExtractor.Prepare(Mthd);
if Result = 0 then
begin
Progress.NewItem('<stream>', Length);
try
Done := FExtractor.Decompress;
if Done < 0 then
begin
Body.TraceFmt('Undeflate returns: %s', [Errors.ErrorStr(Integer(Done))],
{_LINE_}747, __UNIT__);
Result := ZM_Error({_LINE_}748, ZE_InvalidZip);
end
else
CRC := FExtractor.CRC;
Body.TraceFmt('Inflate returns: %s', [Errors.ErrorStr(Result)],
{_LINE_}753, __UNIT__);
finally
Progress.EndItem;
end;
end;
if Result = 0 then
SuccessCnt := 1;
end;
function TZMUnzipOpr.ExtractFileToStream(const EntryName: string): Integer;
var
CZip: TZMZipReader;
Fn: string;
Rec: TZMEntryBase;
begin
Body.ZipStream.Clear;
Result := 0;
Fn := Trim(EntryName);
if (Length(Fn) = 0) and (IncludeSpecs.Count > 0) then
Fn := Trim(IncludeSpecs[0]);
if IsWild(Fn) then
Result := Body.PrepareErrMsg(ZE_WildName, [Fn], {_LINE_}774, __UNIT__)
else
if Fn = '' then
Result := ZM_Error({_LINE_}777, ZE_NothingToDo);
if Result >= 0 then
begin
Body.ClearIncludeSpecs;
CZip := Lister.CurrentZip(True, False);
Rec := CZip.FindName(Fn, nil);
if Rec <> nil then
begin
Result := UnzipAStream(Body.ZipStream, Rec);
if Result = 0 then
begin
SuccessCnt := 1;
ReportMessage(ZM_Error({_LINE_}789, 0),
Format('Unzipped file %s of size %d',
[Rec.FileName, Rec.UncompressedSize]));
end;
end
else
Result := ZM_Error({_LINE_}795, ZE_NothingToDo);
end;
if Result <> 0 then
begin
// error
Body.ZipStream.Clear;
end;
end;
function TZMUnzipOpr.ExtractStreamToStream(InStream: TMemoryStream;
OutSize: Longword; HeaderType: TZMZHeader): Integer;
begin
Result := 0;
Body.ZipStream.Clear();
if not Assigned(InStream) then
Result := ZM_Error({_LINE_}810, ZE_NothingToDo)
else
if InStream = Body.ZipStream then
Result := ZM_Error({_LINE_}813, ZE_InIsOutStream);
if Result = 0 then
Result := DoExtractStreamStream(InStream, OutSize, HeaderType);
if Result = 0 then
SuccessCnt := 1
else
Body.ZipStream.Size := 0;
end;
function TZMUnzipOpr.FinaliseExtracted(Writer: TZMZipBase;
const DestName: string; UseNTFS: Boolean): Integer;
var
Err: Integer;
NTFSTimes: TNTFS_Times;
begin
Result := 0;
// set times
if UseNTFS and (ZRec.FetchNTFSTimes(NTFSTimes) > 0) then
begin
if not Writer.File_SetTime(@NTFSTimes.CTime, @NTFSTimes.ATime,
@NTFSTimes.MTime) then
Result := Body.PrepareErrMsg(ZE_SetFileTimes, [Writer.RealFileName],
{_LINE_} 835, __UNIT__);
end
else
Result := Writer.FixFileDate;
if Result = 0 then
_Z_ChangeNotify(SHCNE_UPDATEITEM, DestName);
// set attributes
Err := Writer.FixFileAttrs;
if Err = 0 then
_Z_ChangeNotify(SHCNE_ATTRIBUTES, DestName);
if Result = 0 then
Result := Err
else
if Err <> 0 then
Result := Body.PrepareErrMsg(ZE_SetFileInformation, [DestName],
{_LINE_} 850, __UNIT__);
end;
function TZMUnzipOpr.FlattenExcludes: string;
var
I: Integer;
S: string;
begin
Result := '';
// flatten the list
for I := 0 to ExcludeSpecs.Count - 1 do
begin
S := ExcludeSpecs[I];
if S = '' then
Continue;
if Result <> '' then
Result := Result + SPEC_SEP;;
Result := Result + S;
end;
end;
function TZMUnzipOpr.ForceBaseDir(const BasePath: string): Integer;
begin
Result := 0;
if BasePath <> '' then
begin
if ExtrForceDirs in Body.ExtrOptions then
begin
if not ForceDirectory(BasePath) then
begin
Body.InformFmt('ForceDirectory failed: %s', [BasePath], {_LINE_}880,
__UNIT__);
Result := Body.PrepareErrMsg(ZE_BuildBaseError, [BasePath], {_LINE_}882,
__UNIT__);
end;
end
else
if not DirExists(BasePath) then
begin
Body.InformFmt('path must exist: %s', [BasePath], {_LINE_}889,
__UNIT__);
Result := Body.PrepareErrMsg(ZE_BuildBaseError, [BasePath], {_LINE_}891,
__UNIT__);
end;
end;
end;
// select entries
// returns <0 _ error, 0 _ ok, >0 _ number of entries selected
function TZMUnzipOpr.ProcessInclude(SrcZip: TZMZipReader; const Spec: string;
const Args: TZMUnzOpts): Integer;
begin
Result := SrcZip.SelectRec(Spec, Args.Excludes, ZzsSet, Args);
if Result < 1 then
begin
// none found
ReportSkipped(Spec, StNotFound, ZM_Error({_LINE_}906, ZE_NothingToDo));
end;
end;
procedure TZMUnzipOpr.RemoveExistingFile(const DestFileName: string);
var
Attrs: Cardinal;
begin
// is read-only?
Attrs := _Z_GetFileAttributes(DestFileName);
if (Attrs and FILE_ATTRIBUTE_READONLY) <> 0 then
begin
Body.InformFmt('Existing file is Read-Only: %s', [DestFileName],
{_LINE_}919, __UNIT__);
// clear read-only
if not _Z_SetFileAttributes(DestFileName, Attrs xor FILE_ATTRIBUTE_READONLY)
then
Body.InformFmt('Failed to clear Read-Only status: %s', [DestFileName],
{_LINE_}924, __UNIT__);
end;
if _Z_EraseFile(DestFileName, not(ExtrSafe in Body.ExtrOptions)) = 0 then
begin
Body.TraceFmt('Deleted pre-existing file %s', [DestFileName],
{_LINE_}929, __UNIT__);
_Z_ChangeNotify(SHCNE_DELETE, DestFileName);
end
else
Body.InformSysFmt('Deleting pre-existing file %s failed', [DestFileName],
{_LINE_}934, __UNIT__)
end;
procedure TZMUnzipOpr.ReportSkipped(const Spec: string; Reason: TZMSkipTypes;
Error: Integer);
begin
if Skipping(Spec, Reason, Error) then
raise EZipMaster.CreateMsg(Body, Error, 0, 0);
end;
function TZMUnzipOpr.SelectUnzFiles(SrcZip: TZMZipReader): Integer;
var
AStream: TStream;
DefaultExcludes: string;
Effectives: TZMUnzOpts;
I: Integer;
Locals: TZMUnzOpts;
SelectCount: Integer;
ShowXProgress: Boolean;
Spec: string;
StreamArg: TZMUnzStreamArg;
begin
Result := 0;
SelectCount := 0;
Effectives := TZMUnzOpts(SrcZip.AddSelectArgs(TZMUnzOpts.Create));
DefaultOptions(Effectives); // set up defaults
DefaultExcludes := Effectives.Excludes;
Locals := nil;
FSplitter.Allow := '><DEFJNOSTX';
FSplitter.Options := [ZaoWildSpec];
ShowXProgress := IncludeSpecs.Count > UnzIncludeListThreshold;
if ShowXProgress then
Progress.NewXtraItem(ZxProcessing, IncludeSpecs.Count);
for I := 0 to IncludeSpecs.Count - 1 do
begin
if Result < 0 then
Break;
if ShowXProgress then
Progress.AdvanceXtra(1);
CheckCancel;
Result := 0;
AStream := AsStream(IncludeSpecs.Objects[I]);
if AStream <> nil then
begin
StreamArg := TZMUnzStreamArg
(SrcZip.AddSelectArgs(TZMUnzStreamArg.Create(AStream)));
Result := SrcZip.SelectRec(IncludeSpecs[I], '', ZzsSet, StreamArg);
if Result < 1 then
begin
// none found
SrcZip.FreeSelectArgs(StreamArg);
ReportSkipped(IncludeSpecs[I], StNotFound,
ZM_Error({_LINE_}987, ZE_NothingToDo));
end
else
if Result > 0 then
IncludeSpecs.Objects[I] := nil;
// now controlled by list of select args
Continue;
end;
FSplitter.Raw := IncludeSpecs[I];
if FSplitter.Error <> ZasNone then
raise EZipMaster.CreateMsgFmt(Body, ZE_InvalidParameter, [FSplitter.Raw],
{_LINE_}998, __UNIT__);
Spec := FSplitter.Main;
if (Spec = '') and FSplitter.Has('>') then
Spec := FSplitter.Arg('>');
if Spec = '' then
begin
// no spec _ set new globals
// ignore empty lines
if FSplitter.Found <> '' then
begin
// no spec, set defaults
if UpdateOptionsFromSplitter(Effectives, DefaultExcludes) then