-
Notifications
You must be signed in to change notification settings - Fork 3
/
ZMUtils.pas
2491 lines (2305 loc) · 62.1 KB
/
ZMUtils.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 ZMUtils;
// ZMUtils.pas - Some utility functions
(* ***************************************************************************
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-01-03
{$INCLUDE '.\ZipVers.inc'}
{$IFDEF VERD6up}
{$WARN UNIT_PLATFORM OFF}
{$WARN SYMBOL_PLATFORM OFF}
{$ENDIF}
{$IFDEF WIN64}
{$DEFINE NO_ASM}
{$ENDIF}
interface
uses
{$IFDEF VERDXE2up}
System.Classes, System.SysUtils, WinApi.Windows, VCL.Graphics,
{$ELSE}
Classes, SysUtils, Windows, Graphics,
{$ENDIF}
ZipMstr;
type
TCharSet = set of AnsiChar;
type
TPathSlashDirection = (PsdExternal, PsdInternal);
TZPathTypes = (ZptNone, ZptError, ZptAbsolute, ZptRelDrive, ZptRelCurDrive,
ZptRelCurDir, ZptExt, ZptUNC);
const // QueryZip return bit values and errors
ZqbStartEXE = 1; // is EXE file may be SFX
ZqbStartLocal = 2; // normal zip file start
ZqbStartSpan = 4; // first part of span
ZqbStartCentral = 8; // continuing Central Header
ZqbHasComment = 16;
// zqbGoodComment = 16; // comment length good (no junk at end)
ZqbHasLocal = 32; // first Central entry points to local header
ZqbHasCentral = 64; // Central entry where it should be
ZqbHasEOC = 128; // End of Central entry
ZqbHasLoc64 = 256; // EOC64 locator entry
ZqbHasEOC64 = 512; // Zip64 EOC
ZqbJunkAtEnd = 1024; // junk at end of zip
ZqbIsDiskZero = 2048; // is disk 0
ZqFieldError = -5; // bad field value
ZqFileError = -7; // file handling error
ZqGeneralError = -9; // unspecified failure
function AbsErr(Err: Integer): Integer;
function AttribStr(Attrs: Cardinal): string;
function BoolStr(const Value: Boolean): string;
function CanHash(const FSpec: string): Boolean;
function CheckSFXType(const Name: string; var ZipName: string;
var Size: Integer): Integer; overload;
function CheckSFXType(AStream: TStream; var ZipName: string; var Size: Integer)
: Integer; overload;
function CleanPath(var PathOut: string; const PathIn: string;
NoLead: Boolean): Integer;
function DelimitPath(const Path: string; Sep: Boolean): string;
function DirExists(const FName: string): Boolean;
function DiskAvailable(const Path: string): Boolean;
function DriveLetter(const Path: string): Char;
// return exe size (if < 4G)
// 0 _ not exe
function ExeSize(const Name: string): Cardinal; overload;
function ExeSize(AStream: TStream): Cardinal; overload;
function ExeVers(const FName: string): Integer;
function ExeVersion(const FName: string; var MS, LS: DWORD): Boolean;
function ExtractNameOfFile(const FileName: string): string;
function FileDateToLocalDateTime(Stamp: Integer): TDateTime;
function FileTimeToLocalDOSTime(const Ft: TFileTime): Cardinal;
function FileTimeToLocalDateTime(const Ft: TFileTime): TDateTime;
// stable replacement for depreciated FileAge()
function File_Age(const FName: string): Cardinal;
procedure File_Close(var Fh: Integer);
procedure File_Delete(const FName: string);
function File_Size(const FSpec: TFilename): Int64;
function ForceDirectory(const DirName: string): Boolean;
function FormTempName(const Where: string): string;
function HashFunc(const Str: string): Cardinal;
function HashFuncNoCase(const Str: string): Cardinal;
function HasSpanSig(const FName: string): Boolean;
// returns position of first wild character or 0
function HasWild(const FSpec: string): Integer;
function HasWildW(const FSpec: WideString): Integer;
function Hi64(I: Int64): Cardinal;
function IsExtPath(const APath: string): Boolean;
function IsFolder(const Name: string): Boolean;
{$IFDEF UNICODE}
overload;
function IsFolder(const Name: TZMRawBytes): Boolean; overload;
{$ENDIF}
function IsWild(const FSpec: string): Boolean;
// true we're running under XP or later.
function IsWinXP: Boolean;
function IsZipSFX(const SFXExeName: string): Integer;
function LastChar(const Name: string): Char;
{$IFDEF UNICODE}
overload;
function LastChar(const Name: TZMRawBytes): AnsiChar; overload;
{$ENDIF}
function LastPos(const S: string; Ch: Char; Before: Integer = MAXINT): Integer;
function LastPosW(const S: WideString; Wch: Widechar;
Before: Integer = MAXINT): Integer;
function Lo64(I: Int64): Cardinal;
// return true if filename is obviously invalid
function NameIsBad(const Astr: string; AllowWild: Boolean): Boolean;
function OEMToStr(const Astr: Ansistring): string;
function OpenResStream(const ResName: string; const Rtype: PChar)
: TResourceStream;
function PathConcat(const Path, Extra: string): string;
function PathIsAbsolute(const APath: string): Boolean;
function PathType(const APath: string): TZPathTypes;
function QualifiedName(const ZipName: string; const FileName: string): string;
function QueryZip(const FName: string): Integer;
// find last SubStr in a string
function RPos(const SubStr, AString: string): Integer; overload;
function RPos(const SubStr, AString: string; StartPos: Integer)
: Integer; overload;
function SetSlash(const Path: string; Dir: TPathSlashDirection): string;
function SetSlashW(const Path: WideString; Dir: TPathSlashDirection)
: WideString;
procedure SplitArgs(const Args: string; var Main: string; var Filearg: string;
var Switches: string; var Password: string);
procedure SplitQualifiedName(const QName: string; var ZipName: string;
var FileName: string);
function StrHasExt(const Astr: AnsiString): Boolean; overload;
{$IFDEF UNICODE}
// 1 return True if contains chars (<#31 ?) >#126
function StrHasExt(const Astr: string): Boolean; overload;
function StrHasExt(const Astr: TZMRawBytes): Boolean; overload;
{$ENDIF}
function StrToOEM(const Astr: string): string;
// trim and dequote
function Unquote(const FName: string): string;
function VersStr(Vers: Integer; Comma: Boolean = False): string;
function WinPathDelimiters(const Path: string): string;
function WinVersion: Integer;
function XData(const X: TZMRawBytes; Tag: Word; var Idx, Size: Integer)
: Boolean;
function XDataAppend(var X: TZMRawBytes; const Src1; Siz1: Integer; const Src2;
Siz2: Integer): Integer;
function XDataKeep(const X: TZMRawBytes; const Tags: array of Integer)
: TZMRawBytes;
function XDataRemove(const X: TZMRawBytes; const Tags: array of Integer)
: TZMRawBytes;
function ZSplitString(const Delim, Raw: string; var Rest: string): string;
// split string at last delim
function ZSplitStringLast(const Delim, Raw: string; var Rest: string): string;
// check for SFX header or detached header
// return <0 error
const
CstNone = 0; // not found
CstExe = 1; // might be stub of unknown type
CstSFX17 = 17; // found 1.7 SFX headers
CstSFX19 = 19; // found 1.9 SFX headers
CstDetached = 2048;
// is detached - if Name specified ZipName will modified for it
const
FILETIME_ZERO = -109205; // Jan 1, 1601
// return true if found (and no time conversion error)
function FileLastModified(const FileName: string;
var LastMod: TDateTime): Boolean;
// test for invalid characters
function IsInvalidIntName(const FName: string): Boolean;
function AppendToName(const Name, Suffix: string): string;
function IntToBase36(Utim: Cardinal): string;
function SysErrorMsg(ErrNo: Cardinal = Cardinal(-1)): string;
function ShortPathName(const APath: string): string;
function ShortenPath(const APath: string): string;
const
Z_BAD_DRIVE = -1;
Z_BAD_UNC = -2;
Z_BAD_SEP = -3;
Z_BAD_SPACE = -4; // trail space
Z_BAD_DOT = -5; // trailing dot
Z_BAD_CLEN = -6; // component too long
Z_BAD_CHAR = -7; // invalid char
Z_BAD_NAME = -8; // has reserved Name
Z_BAD_PARENT = -9; // attempt to back below root
Z_IS_THIS = -10;
Z_IS_PARENT = -11;
Z_EMPTY = 1;
Z_WILD = 2; // 1;
// -------------------------- ------------ -------------------------
implementation
uses
{$IFDEF VERDXE2up}
WinApi.ShellApi, VCL.Forms,
{$ELSE}
ShellApi, Forms, {$IFNDEF VERD7up}ComObj, ActiveX, {$ENDIF}
{$IFNDEF UNICODE}ZMCompat, {$ENDIF}
{$ENDIF}
ZMStructs, ZMSFXInt, ZMWinFuncs, ZMMsg;
type
TInt64Rec = packed record
case Integer of
0:
(I: Int64);
1:
(Lo, Hi: Cardinal);
end;
// --------------------------------------------------------
function Lo64(I: Int64): Cardinal;
var
R: TInt64Rec;
begin
R.I := I;
Result := R.Lo;
end;
function Hi64(I: Int64): Cardinal;
var
R: TInt64Rec;
begin
R.I := I;
Result := R.Hi;
end;
// --------------------------------------------------------
function AbsErr(Err: Integer): Integer;
begin
if Err < 0 then
Result := -Err
else
Result := Err;
Result := Result and ZERR_ERROR_MASK; // remove extended info
end;
function AttribStr(Attrs: Cardinal): string;
type
Attrval = record
V: Cardinal;
D: array [Boolean] of Char;
end;
const
AttrVals: array [0 .. 6] of Attrval = ((V: 1; D: ('r', 'R')), (V: 2;
D: ('h', 'H')), (V: 4; D: ('s', 'S')), (V: $20; D: ('a', 'A')), (V: $100;
D: ('t', 'T')), (V: $1000; D: ('o', 'O')), (V: $4000; D: ('e', 'E')));
var
I: Integer;
begin
SetLength(Result, high(AttrVals) + 1);
for I := low(AttrVals) to high(AttrVals) do
Result[I + 1] := AttrVals[I].D[(Attrs and AttrVals[I].V) <> 0];
end;
function DelimitPath(const Path: string; Sep: Boolean): string;
begin
Result := Path;
if Length(Path) = 0 then
begin
if Sep then
Result := PathDelim{'\'};
// exit;
end
else
if (AnsiLastChar(Path)^ = PathDelim) <> Sep then
begin
if Sep then
Result := Path + PathDelim
else
Result := Copy(Path, 1, Pred(Length(Path)));
end;
end;
function WinPathDelimiters(const Path: string): string;
var
I: Integer;
begin
Result := Path;
for I := 1 to Length(Result) do
if Result[I] = '/' then
Result[I] := '\';
end;
function DirExists(const FName: string): Boolean;
begin
Result := _Z_DirExists(FName);
end;
function DiskAvailable(const Path: string): Boolean;
var
Drv: Integer;
Em: Cardinal;
Pth: string;
begin
Result := False;
Pth := ExpandUNCFileName(Path);
if (Length(Pth) > 1) and (Pth[2] = DriveDelim) then
begin
Drv := Ord(Uppercase(Pth)[1]) - $40;
Em := SetErrorMode(SEM_FAILCRITICALERRORS);
Result := DiskSize(Drv) <> -1;
SetErrorMode(Em);
end;
end;
function ExeVersion(const FName: string; var MS, LS: DWORD): Boolean;
begin
Result := _Z_GetExeVersion(FName, MS, LS);
end;
// format M.N.RR.BBB
// return Version as used by DelphiZip
function ExeVers(const FName: string): Integer;
var
LS: DWORD;
MS: DWORD;
begin
Result := -1;
if ExeVersion(FName, MS, LS) then
begin
Result := (Integer(MS) shr 16) * 1000000;
Result := Result + (Integer(MS and $FFFF) * 100000);
Result := Result + ((Integer(LS) shr 16) * 10000);
Result := Result + Integer(LS and $FFFF) mod 1000;
end;
end;
function ExtractNameOfFile(const FileName: string): string;
var
I: Integer;
J: Integer;
begin
I := LastDelimiter(PathDelim + DriveDelim, FileName);
J := LastDelimiter('.', FileName);
if (J <= I) then
begin
J := MaxInt;
end; // no ext
Result := Copy(FileName, I + 1, J - (I + 1));
end;
function VersStr(Vers: Integer; Comma: Boolean = False): string;
const
Fmt: array [Boolean] of string = ('%d.%d.%d.%4.4d', '%d,%d,%d,%d');
begin
Result := Format(Fmt[Comma], [Vers div 1000000, (Vers mod 1000000) div 100000,
(Vers mod 100000) div 10000, Vers mod 1000]);
end;
function OpenResStream(const ResName: string; const Rtype: PChar)
: TResourceStream;
var
HFindRes: Cardinal;
IdNo: Integer;
Inst: Integer;
Rsn: PChar;
begin
Result := nil;
try
Rsn := PChar(ResName);
Inst := HInstance;
if (Length(ResName) > 1) and (ResName[1] = '#') then
begin
IdNo := StrToInt(Copy(ResName, 2, 25));
Rsn := PChar(IdNo);
end;
HFindRes := FindResource(Inst, Rsn, Rtype);
if (HFindRes = 0) and ModuleIsLib then
begin
Inst := MainInstance;
HFindRes := FindResource(Inst, Rsn, Rtype);
end;
if HFindRes <> 0 then
Result := TResourceStream.Create(Inst, ResName, Rtype);
except
Result := nil;
end;
end;
function File_Age(const FName: string): Cardinal;
var
LocalFileTime: TFileTime;
R: Integer;
SRec: _Z_TSearchRec;
begin
Result := Cardinal(-1);
R := _Z_FindFirst(FName, FaAnyFile, SRec);
if R = 0 then
begin
FileTimeToLocalFileTime(SRec.FindData.FtLastWriteTime, LocalFileTime);
_Z_FindClose(SRec);
FileTimeToDosDateTime(LocalFileTime, LongRec(Result).Hi,
LongRec(Result).Lo);
end;
end;
procedure File_Close(var Fh: Integer);
var
H: Integer;
begin
if Fh <> Invalid_Handle then
begin
H := Fh;
Fh := Invalid_Handle;
FileClose(H);
end;
end;
procedure File_Delete(const FName: string);
begin
_Z_EraseFile(FName, True);
end;
function File_Size(const FSpec: TFilename): Int64;
var
Sr: _Z_TSearchRec;
begin
Result := 0;
if _Z_FindFirst(FSpec, FaAnyFile, Sr) = 0 then
begin
Result := Sr.Size;
_Z_FindClose(Sr);
end;
end;
// return true on success
function ForceDirectory(const DirName: string): Boolean;
begin
Result := _Z_ForceDirectory(DirName);
end;
(*? HasWild
returns position of first wild character or 0
*)
function HasWild(const FSpec: string): Integer;
var
C: Char;
I: Integer;
begin
Result := 0;
for I := 1 to Length(FSpec) do
begin
C := FSpec[I];
if (C = WILD_MULTI) or (C = WILD_CHAR) then
begin
Result := I;
Break;
end;
end;
end;
(*? HasWildW
returns position of first wild character or 0
*)
function HasWildW(const FSpec: WideString): Integer;
var
C: Widechar;
I: Integer;
begin
Result := 0;
for I := 1 to Length(FSpec) do
begin
C := FSpec[I];
if (C = WILD_MULTI) or (C = WILD_CHAR) then
begin
Result := I;
Break;
end;
end;
end;
(*? IsWild
1.73.4
returns true if filespec contains wildcard(s)
*)
function IsWild(const FSpec: string): Boolean;
var
C: Char;
I: Integer;
Len: Integer;
begin
Result := True;
Len := Length(FSpec);
I := 1;
while I <= Len do
begin
C := FSpec[I];
if (C = WILD_MULTI) or (C = WILD_CHAR) then
Exit;
Inc(I);
end;
Result := False;
end;
(* ? IsZipSFX
Return value:
0 = The specified file is not a SFX
>0 = It is one
-7 = Open, read or seek error
-8 = memory error
-9 = exception error
-10 = all other exceptions
*)
function IsZipSFX(const SFXExeName: string): Integer;
const
SFXsig = ZqbStartEXE or ZqbHasCentral or ZqbHasEOC;
var
N: string;
R: Integer;
Sz: Integer;
begin
R := QueryZip(SFXExeName);
// SFX = 1 + 128 + 64
Result := 0;
if (R and SFXsig) = SFXsig then
Result := CheckSFXType(SFXExeName, N, Sz);
end;
function CanHash(const FSpec: string): Boolean;
var
C: Char;
I: Integer;
Len: Integer;
begin
Result := False;
Len := Length(FSpec);
I := 1;
while I <= Len do
begin
C := FSpec[I];
if (C = WILD_MULTI) or (C = WILD_CHAR) or (C = SPEC_SEP) then
Exit;
Inc(I);
end;
Result := True;
end;
// Returns a boolean indicating whether or not we're running under XP or later.
function IsWinXP: Boolean;
var
Osv: TOSVERSIONINFO;
begin
Osv.DwOSVersionInfoSize := SizeOf(OSVERSIONINFO);
GetVersionEx(Osv);
Result := (Osv.DwMajorVersion > 5) or
((Osv.DwMajorVersion = 5) and (Osv.DwMinorVersion >= 1));
end;
// Returns a boolean indicating whether or not we're running under XP or later.
function WinVersion: Integer;
var
Osv: TOSVERSIONINFO;
begin
Osv.DwOSVersionInfoSize := SizeOf(OSVERSIONINFO);
GetVersionEx(Osv);
Result := (Osv.DwMajorVersion * 100) + Osv.DwMinorVersion;
end;
(*? SetSlash
1.76 use enum TPathSlashDirection = (psdExternal, psdInternal)
1.73
forwardSlash = false = Windows normal backslash '\'
forwardSlash = true = forward slash '/'
*)
function SetSlash(const Path: string; Dir: TPathSlashDirection): string;
{$IFDEF Delphi7up}
begin
if Dir = PsdInternal then
Result := AnsiReplaceStr(Path, PathDelim, PathDelimAlt)
else
Result := AnsiReplaceStr(Path, PathDelimAlt, PathDelim);
end;
{$ELSE}
var
C, F, R: Char;
I, Len: Integer;
begin
Result := Path;
Len := Length(Path);
if Dir = PsdInternal then
begin
F := PathDelim{'\'};
R := PathDelimAlt; // '/';
end
else
begin
F := PathDelimAlt; // '/';
R := PathDelim{'\'};
end;
I := 1;
while I <= Len do
begin
C := Path[I];
{$IFNDEF UNICODE}
if C in LeadBytes then
begin
Inc(I, 2);
Continue;
end;
{$ENDIF}
if C = F then
Result[I] := R;
Inc(I);
end;
end;
{$ENDIF}
function SetSlashW(const Path: WideString; Dir: TPathSlashDirection)
: WideString;
var
C: Widechar;
F: Widechar;
I: Integer;
Len: Integer;
R: Widechar;
begin
Result := Path;
Len := Length(Path);
if Dir = PsdInternal then
begin
F := PathDelim;
R := PathDelimAlt;
end
else
begin
F := PathDelimAlt;
R := PathDelim;
end;
I := 1;
while I <= Len do
begin
C := Path[I];
if C = F then
Result[I] := R;
Inc(I);
end;
end;
// ---------------------------------------------------------------------------
// concat path
function PathConcat(const Path, Extra: string): string;
var
PathLen: Integer;
PathLst: Char;
begin
PathLen := Length(Path);
Result := Path;
if PathLen > 0 then
begin
PathLst := AnsiLastChar(Path)^;
if ((PathLst <> DriveDelim) and (Length(Extra) > 0)) and
((Extra[1] = PathDelim) = (PathLst = PathDelim)) then
begin
if PathLst = PathDelim then
Result := Copy(Path, 1, PathLen - 1) // remove trailing
else
Result := Path + PathDelim;
end;
end;
Result := Result + Extra;
end;
(* const // QueryZip return bit values and errors
zqbStartEXE = 1; // is EXE file may be SFX
zqbStartLocal = 2; // normal zip file start
zqbStartSpan = 4; // first part of span
zqbStartCentral = 8; // continuing Central Header
zqbHasComment = 16;
zqbHasLocal = 32; // first Central entry points to local header
zqbHasCentral = 64; // Central entry where it should be
zqbHasEOC = 128; // End of Central entry
zqbHasLoc64 = 256; // EOC64 locator entry
zqbHasEOC64 = 512; // Zip64 EOC
zqbJunkAtEnd = 1024; // junk at end of zip
zqbIsDiskZero = 2048; // is disk 0
zqFieldError = -5; // bad field value
zqFileError = -7; // file handling error
zqGeneralError = -9; // unspecified failure
*)
function QueryZip(const FName: string): Integer;
const
FileMask = (ZqbStartEXE or ZqbStartLocal or ZqbStartSpan or ZqbStartCentral or
ZqbHasComment or ZqbJunkAtEnd);
var
Buf: array of Byte;
BufPos: Integer;
CenDisk: Cardinal;
CenOfs: Int64;
DoCenDir: Boolean;
EOC: TZipEndOfCentral;
EOCLoc: TZip64EOCLocator;
EOCPossible: Boolean;
FileHandle: Integer;
File_Sze: Int64;
Fn: string;
Fs: Int64;
Need64: Boolean;
PEOC: PZipEndOfCentral;
PEOCLoc: PZip64EOCLocator;
Pos0: Integer;
ReadPos: Cardinal;
Res: Integer;
Sig: Cardinal;
Size: Integer;
ThisDisk: Cardinal;
function NeedLoc64(const QEOC: TZipEndOfCentral): Boolean;
begin
Result := (QEOC.ThisDiskNo = MAX_WORD) or (QEOC.CentralDiskNo = MAX_WORD) or
(QEOC.CentralEntries = MAX_WORD) or (QEOC.TotalEntries = MAX_WORD) or
(QEOC.CentralSize = MAX_UNSIGNED) or (QEOC.CentralOffset = MAX_UNSIGNED);
end;
// check central entry and, if same disk, its local header signal
function CheckCen(Fh: Integer; This_Disk: Cardinal; CenOf: Int64): Integer;
type
TXData_tag = packed record
Tag: Word;
Siz: Word;
end;
PXData_tag = ^TXData_tag;
var
Ret: Integer;
CentralHead: TZipCentralHeader;
Sgn: Cardinal;
Ofs: Int64;
Xbuf: array of Byte;
Xlen, Ver: Integer;
Wtg, Wsz: Word;
Has64: Boolean;
P: PByte;
begin // verify start of central
Ret := 0;
Result := ZqFieldError;
if (FileSeek(Fh, CenOf, SoFromBeginning) <> -1) and
(FileRead(Fh, CentralHead, Sizeof(CentralHead)) = Sizeof(CentralHead)) and
(CentralHead.HeaderSig = CentralFileHeaderSig) then
begin
Ret := ZqbHasCentral; // has linked Central
if (CentralHead.DiskStart = This_Disk) then
begin
Ver := CentralHead.VersionNeeded;
if (Ver and VerMask) > ZIP64_VER then
Exit;
Ofs := CentralHead.RelOffLocalHdr;
if (Ofs = MAX_UNSIGNED) and ((Ver and VerMask) >= ZIP64_VER) then
begin
if Ver > 45 then
Exit; // bad version
// have to read extra data
Xlen := CentralHead.FileNameLen + CentralHead.ExtraLen;
SetLength(Xbuf, Xlen); // easier to read filename + extra
if FileRead(Fh, Xbuf, Xlen) <> Xlen then
Exit; // error
// find Zip64 extra data
Has64 := False;
Xlen := CentralHead.ExtraLen;
P := @Xbuf[CentralHead.FileNameLen];
Wsz := 0; // keep compiler happy
while Xlen > Sizeof(TXData_tag) do
begin
Wtg := PXData_tag(P)^.Tag;
Wsz := PXData_tag(P)^.Siz;
if Wtg = Zip64_data_tag then
begin
Has64 := Xlen >= (Wsz + Sizeof(TXData_tag));
Break;
end;
Inc(P, Wsz + Sizeof(TXData_tag));
end;
if (not Has64) or (Wsz > (Xlen - Sizeof(TXData_tag))) then
Exit; // no data so rel ofs is bad
Inc(P, Sizeof(TXData_tag)); // past header
// locate offset - values only exist if needed
if CentralHead.UncomprSize = MAX_UNSIGNED then
begin
if Wsz < Sizeof(Int64) then
Exit; // bad
Inc(P, Sizeof(Int64));
Dec(Wsz, Sizeof(Int64));
end;
if CentralHead.ComprSize = MAX_UNSIGNED then
begin
if Wsz < Sizeof(Int64) then
Exit; // bad
Inc(P, Sizeof(Int64));
Dec(Wsz, Sizeof(Int64));
end;
if Wsz < Sizeof(Int64) then
Exit; // bad
Ofs := PInt64(P)^;
end;
if (FileSeek(Fh, Ofs, 0) <> -1) and
(FileRead(Fh, Sgn, Sizeof(Sgn)) = Sizeof(Sgn)) and
(Sgn = LocalFileHeaderSig) then
Ret := ZqbHasCentral or ZqbHasLocal; // linked local
end;
end;
Result := Ret;
end;
begin
EOCPossible := False;
Result := ZqFileError;
DoCenDir := True; // test central too
if (FName <> '') and (FName[1] = '|') then
begin
DoCenDir := False;
Fn := Copy(FName, 2, Length(FName) - 1);
end
else
Fn := FName;
Fn := Trim(Fn);
if Fn = '' then
Exit;
FileHandle := Invalid_Handle;
Res := 0;
try
try
// Open the input archive, presumably the last disk.
FileHandle := _Z_FileOpen(Fn, FmShareDenyWrite or FmOpenRead);
if FileHandle = Invalid_Handle then
Exit;
Result := 0; // rest errors normally file too small
// first we check if the start of the file has an IMAGE_DOS_SIGNATURE
if (FileRead(FileHandle, Sig, Sizeof(Cardinal)) <> Sizeof(Cardinal)) then
Exit;
if LongRec(Sig).Lo = IMAGE_DOS_SIGNATURE then
Res := ZqbStartEXE
else
if Sig = LocalFileHeaderSig then
Res := ZqbStartLocal
else
if Sig = CentralFileHeaderSig then
Res := ZqbStartCentral
// part of split Central Directory
else
if Sig = ExtLocalSig then
Res := ZqbStartSpan; // first part of span
// A test for a zip archive without a ZipComment.
Fs := FileSeek(FileHandle, -Int64(Sizeof(EOC)), SoFromEnd);
if Fs = -1 then
Exit; // not zip - too small
File_Sze := Fs;
// try no comment
if (FileRead(FileHandle, EOC, Sizeof(EOC)) = Sizeof(EOC)) and
(EOC.HeaderSig = EndCentralDirSig) and (EOC.ZipCommentLen = 0) then
begin
EOCPossible := True;
Res := Res or ZqbHasEOC;
CenDisk := EOC.CentralDiskNo;
ThisDisk := EOC.ThisDiskNo;
CenOfs := EOC.CentralOffset;
Need64 := NeedLoc64(EOC);
if (CenDisk = 0) and (ThisDisk = 0) then
Res := Res or ZqbIsDiskZero;
// check Zip64 EOC
if Need64 and (Fs > Sizeof(TZip64EOCLocator)) then
begin // check for locator
if (FileSeek(FileHandle, Fs - Sizeof(TZip64EOCLocator),
SoFromBeginning) <> -1) and
(FileRead(FileHandle, EOCLoc, Sizeof(TZip64EOCLocator))
= Sizeof(TZip64EOCLocator)) and (EOCLoc.LocSig = EOC64LocatorSig)
then
begin // found possible locator
Res := Res or ZqbHasLoc64;
CenDisk := 0;
ThisDisk := 1;
CenOfs := -1;
end;
end;
if DoCenDir and (CenDisk = ThisDisk) then
begin
Res := Res or CheckCen(FileHandle, ThisDisk, CenOfs);
Exit;
end;
Res := Res and FileMask; // remove rest
end;