Debian Codegraph @

plugins/wcx/zip/src/fparchive/abtartyp.pas

raw
1 (* ***** BEGIN LICENSE BLOCK *****
2 * Version: MPL 1.1
3 *
4 * The contents of this file are subject to the Mozilla Public License Version
5 * 1.1 (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 * http://www.mozilla.org/MPL/
8 *
9 * Software distributed under the License is distributed on an "AS IS" basis,
10 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
11 * for the specific language governing rights and limitations under the
12 * License.
13 *
14 * The Original Code is TurboPower Abbrevia
15 *
16 * The Initial Developer of the Original Code is
17 * TurboPower Software
18 *
19 * Portions created by the Initial Developer are Copyright (C) 1997-2002
20 * the Initial Developer. All Rights Reserved.
21 *
22 * Contributor(s):
23 * Joel Haynie
24 * Craig Peterson <[email protected]>
25 *
26 * ***** END LICENSE BLOCK ***** *)
27
28 {*********************************************************}
29 {* ABBREVIA: AbTarTyp.pas *}
30 {*********************************************************}
31 {* ABBREVIA: TAbTarArchive, TAbTarItem classes *}
32 {*********************************************************}
33 {* Misc. constants, types, and routines for working *}
34 {* with Tar files *}
35 {*********************************************************}
36
37 unit AbTarTyp;
38
39 {$I AbDefine.inc}
40
41 interface
42
43 uses
44 Classes,
45 AbUtils, AbArcTyp;
46
47 const
48 AB_TAR_RECORDSIZE = 512; {Note: SizeOf(TAbTarHeaderRec) = AB_TAR_RECORDSIZE}
49 AB_TAR_NAMESIZE = 100;
50 AB_TAR_V7_EMPTY_SIZE = 167;
51 AB_TAR_USTAR_PREFIX_SIZE = 155;
52 AB_TAR_STAR_PREFIX_SIZE = 131;
53 AB_TAR_OLD_GNU_EMPTY1_SIZE = 5;
54 AB_TAR_OLD_GNU_SPARSE_SIZE = 96;
55 AB_TAR_OLD_GNU_EMPTY2_SIZE = 17;
56 AB_TAR_SIZE_AFTER_STDHDR = 167;
57 AB_TAR_TUSRNAMELEN = 32;
58 AB_TAR_TGRPNAMELEN = 32;
59
60
61 { The checksum field is filled with this while the checksum is computed. }
62 AB_TAR_CHKBLANKS = ' '; { 8 blank spaces(#20), no null }
63 AB_TAR_L_HDR_NAME = '././@LongLink'; { As seen in the GNU File Examples}
64 AB_TAR_L_HDR_USR_NAME='root'; { On Cygwin this is #0, Redhat it is 'root' }
65 AB_TAR_L_HDR_GRP_NAME='root'; { Same on all OS's }
66 AB_TAR_L_HDR_ARR8_0 ='0000000'#0; { 7 zeros and one null }
67 AB_TAR_L_HDR_ARR12_0 ='00000000000'#0;{ 11 zeros and one null }
68 AB_TAR_MAGIC_VAL = 'ustar'#0; { 5 chars & a nul }
69 AB_TAR_MAGIC_VER = '00'; { 2 chars }
70 AB_TAR_MAGIC_GNUOLD = 'ustar '#0; { 7 chars & a null }
71 AB_TAR_MAGIC_V7_NONE = #0#0#0#0#0#0#0#0;{ 8, #0 }
72
73 { The linkflag defines the type of file(FH), and Meta Data about File(MDH) }
74 AB_TAR_LF_OLDNORMAL = #0; { FH, Normal disk file, Unix compatible } { Historically used for V7 }
75 AB_TAR_LF_NORMAL = '0'; { FH, Normal disk file }
76 AB_TAR_LF_LINK = '1'; { FH, Link to previously archived file }
77 AB_TAR_LF_SYMLINK = '2'; { FH, Symbolic(soft) link }
78 AB_TAR_LF_CHR = '3'; { FH, Character special file }{ Used for device nodes, Conditionally compiled into GNUTAR }
79 AB_TAR_LF_BLK = '4'; { FH, Block special file }{ Used for device nodes, Conditionally compiled into GNUTAR }
80 AB_TAR_LF_DIR = '5'; { FH, Directory, Zero size File }
81 AB_TAR_LF_FIFO = '6'; { FH, FIFO special file }{ Used for fifo files(pipe like), Conditionally complied into GNUTAR }
82 AB_TAR_LF_CONTIG = '7'; { FH, Contiguous file } { Normal File, but All blocks should be contiguos on the disk }
83 AB_TAR_LF_XHDR = 'x'; { MDH, POSIX, Next File has Extended Header }
84 AB_TAR_LF_XGL = 'g'; { MDH, POSIX, Global Extended Header }
85 AB_TAR_LF_DUMPDIR = 'D'; { FH, Extra GNU, Dump Directory} { Generated Dump of Files in a directory, has a size }
86 AB_TAR_LF_LONGLINK = 'K'; { MDH, Extra GNU, Next File has Long LinkName}
87 AB_TAR_LF_LONGNAME = 'L'; { MDH, Extra GNU, Next File has Long Name}
88 AB_TAR_LF_MULTIVOL = 'M'; { FH, Extra GNU, MultiVolume File Cont.}{ End of a file that spans multiple TARs }
89 AB_TAR_LF_SPARSE = 'S'; { FH, Extra GNU, Sparse File Cont.}
90 AB_TAR_LF_VOLHDR = 'V'; { FH, Extra GNU, File is Volume Header }
91 AB_TAR_LF_EXHDR = 'X'; { MDH, Extra GNU, Solaris Extended Header }
92 { The only questionable MetaData type is 'V', file or meta-data? will treat as file header }
93 AB_SUPPORTED_F_HEADERS = [AB_TAR_LF_OLDNORMAL, AB_TAR_LF_NORMAL, AB_TAR_LF_LINK,
94 AB_TAR_LF_SYMLINK, AB_TAR_LF_DIR];
95 AB_UNSUPPORTED_F_HEADERS = [AB_TAR_LF_CHR, AB_TAR_LF_BLK, AB_TAR_LF_FIFO,
96 AB_TAR_LF_CONTIG, AB_TAR_LF_DUMPDIR, AB_TAR_LF_MULTIVOL,
97 AB_TAR_LF_SPARSE, AB_TAR_LF_VOLHDR];
98 AB_SUPPORTED_MD_HEADERS = [AB_TAR_LF_LONGNAME, AB_TAR_LF_LONGLINK];
99 AB_UNSUPPORTED_MD_HEADERS= [AB_TAR_LF_XHDR, AB_TAR_LF_XGL, AB_TAR_LF_EXHDR];
100 AB_GNU_MD_HEADERS = [AB_TAR_LF_LONGLINK, AB_TAR_LF_LONGNAME]; { If present then OLD_/GNU_FORMAT }
101 AB_PAX_MD_HEADERS = [AB_TAR_LF_XHDR, AB_TAR_LF_XGL]; { If present then POSIX_FORMAT }
102 AB_IGNORE_SIZE_HEADERS = [AB_TAR_LF_LINK, AB_TAR_LF_SYMLINK, AB_TAR_LF_CHR,
103 AB_TAR_LF_BLK, AB_TAR_LF_DIR, AB_TAR_LF_FIFO];
104 { The rest of the Chars are unsupported and unknown types Treat those headers as File types }
105 { Further link types may be defined later. }
106
107 { Bits used in the mode field - values in octal }
108 AB_TAR_TSUID = $0800; { Set UID on execution }
109 AB_TAR_TSGID = $0400; { Set GID on execution }
110 AB_TAR_TSVTX = $0200; { Save text (sticky bit) }
111
112
113 type
114 Arr8 = array [0..7] of AnsiChar;
115 Arr12 = array [0..11] of AnsiChar;
116 Arr12B = array[0..11] of Byte;
117 ArrName = array [0..AB_TAR_NAMESIZE-1] of AnsiChar;
118 TAbTarHeaderFormat = (UNKNOWN_FORMAT, V7_FORMAT, OLDGNU_FORMAT, GNU_FORMAT,
119 USTAR_FORMAT, STAR_FORMAT, POSIX_FORMAT);
120 TAbTarItemType = (SUPPORTED_ITEM, UNSUPPORTED_ITEM, UNKNOWN_ITEM);
121 TAbTarHeaderType = (FILE_HEADER, META_DATA_HEADER, MD_DATA_HEADER, UNKNOWN_HEADER);
122 TAbTarMagicType = (GNU_OLD, NORMAL);
123 TAbTarMagicRec = packed record
124 case TAbTarMagicType of
125 GNU_OLD: (gnuOld : array[0..7] of AnsiChar); { Old GNU magic: (Magic.gnuOld) }
126 NORMAL : (value : array[0..5] of AnsiChar; { Magic value: (Magic.value)}
127 version: array[0..1] of AnsiChar); { Version: (Magic.version) }
128 end;
129
130 { Notes from GNU Tar & POSIX Spec.: }
131 {All the first 345 bytes are the same. }
132 { "USTAR_header": Prefix(155): 345-499,
133 empty(12): 500-511 }
134 { "old_gnu_header": atime(12): 345-356,
135 ctime(12): 357-368,
136 offset(12): 369-380,
137 longnames(4): 381-384,
138 empty(1): 385,
139 sparse structs(4x(12+12)=96): 386-481,
140 isextended(1): 482,
141 realsize(12): 483-494,
142 empty(16): 495-511 }
143 { "star_header": Prefix(131): 345-475,
144 atime(12): 476-487,
145 ctime(12): 488-499,
146 empty(12): 500-511 }
147 { "star_in_header": prefix(1): 345,
148 empty(9): 346-354,
149 isextended(1): 355,
150 sparse structs(4x(12+12)=96): 356-451,
151 realsize(12): 452-463,
152 offset(12): 464-475,
153 atime(12): 476-487,
154 ctime(12): 488-499,
155 empty(8): 500-507,
156 xmagic(4): 508-511 }
157 { "sparse_header": These two structs are the same, and they are Meta data about file. }
158 {"star_ext_header": sparse structs(21x(12+12)=504): 0-503,
159 isextended(1): 504 }
160 {POSIX(PAX) extended header: is a buffer packed with content of this form:
161 This if from the POSIX spec. References the C printf command string.
162 "%d %s=%s\n". Then they are simply concatenated. }
163 { PAX Extended Header Keywords: }
164 { 'atime', 'charset', 'comment', 'ctime', 'gid', 'gname', 'linkpath', 'mtime', 'path',
165 'realtime.', 'security.', 'size', 'uid', 'uname' }
166 { GNU Added PAX Extended Header Keywords: }
167 { 'GNU.sparse.name', 'GNU.sparse.major', 'GNU.sparse.minor',
168 'GNU.sparse.realsize', 'GNU.sparse.numblocks', 'GNU.sparse.size',
169 'GNU.sparse.offset', 'GNU.sparse.numbytes', 'GNU.sparse.map', 'GNU.dumpdir',
170 'GNU.volume.label', 'GNU.volume.filename', 'GNU.volume.size',
171 'GNU.volume.offset' }
172
173 { V7 uses AB_TAR_LF_OLDNORMAL linkflag, has no magic field & no Usr/Grp Names }
174 { V7 Format ends Empty(padded with zeros), as does the POSIX record. }
175 TAbTarEnd_Empty_Rec = packed record
176 Empty: array[0..AB_TAR_V7_EMPTY_SIZE-1] of Byte; { 345-511, $159-1FF, Empty Space }
177 end;
178 { UStar End Format }
179 TAbTarEnd_UStar_Rec = packed record
180 Prefix: array[0..AB_TAR_USTAR_PREFIX_SIZE-1] of AnsiChar;
181 { 345-499, $159-1F3, Prefix of file & path name, null terminated ASCII string }
182 Empty : Arr12B;{ 500-512, $1F4-1FF, Empty Space }
183 end;
184 { Old GNU End Format }
185 TAbTarEnd_GNU_old_Rec = packed record
186 Atime : Arr12; { 345-356, $159-164, time of last access (UNIX Date in ASCII coded Octal)}
187 Ctime : Arr12; { 357-368, $165-170, time of last status change (UNIX Date in ASCII coded Octal)}
188 Offset: Arr12; { 369-380, $171-17C, Multirecord specific value }
189 Empty1: array[0..AB_TAR_OLD_GNU_EMPTY1_SIZE-1] of Byte;
190 { 381-385, $17D-181, Empty Space, Once contained longname ref. }
191 Sparse: array[0..AB_TAR_OLD_GNU_SPARSE_SIZE-1] of Byte;
192 { 386-481, $182-1E1, Sparse File specific values }
193 IsExtended: byte;{ 482, $ 1E2, Flag to signify Sparse file headers follow }
194 RealSize: Arr12;{ 483-494, $1E3-1EE, Real size of a Sparse File. }
195 Empty2: array[0..AB_TAR_OLD_GNU_EMPTY2_SIZE-1] of Byte;
196 { 495-511, $1EF-1FF, Empty Space }
197 end;
198 { Star End Format }
199 TAbTarEnd_Star_Rec = packed record
200 Prefix: array[0..AB_TAR_STAR_PREFIX_SIZE-1] of AnsiChar;
201 { 345-499, $159-1F3, prefix of file & path name, null terminated ASCII string }
202 Atime : Arr12; { 476-487, $1DC-1E7, time of last access (UNIX Date in ASCII coded Octal)}
203 Ctime : Arr12; { 488-499, $1E8-1F3, time of last status change (UNIX Date in ASCII coded Octal)}
204 Empty : Arr12B;{ 500-512, $1F4-1FF, Empty Space }
205 end;
206 { When support for sparse files is added, Add another record for sparse in header }
207
208
209 { Note: SizeOf(TAbTarHeaderRec) = AB_TAR_RECORDSIZE by design }
210 PAbTarHeaderRec = ^TAbTarHeaderRec; { Declare pointer type for use in the list }
211 TAbTarHeaderRec = packed record
212 Name : ArrName; { 0- 99, $ 0- 63, filename, null terminated ASCII string, unless length is 100 }
213 Mode : Arr8; { 100-107, $ 64- 6B, file mode (UNIX style, ASCII coded Octal) }
214 uid : Arr8; { 108-115, $ 6C- 73, usrid # (UNIX style, ASCII coded Octal) }
215 gid : Arr8; { 116-123, $ 74- 7B, grpid # (UNIX style, ASCII coded Octal) }
216 Size : Arr12; { 124-135, $ 7C- 87, size of TARred file (ASCII coded Octal) }
217 ModTime : Arr12; { 136-147, $ 88- 93, time of last modification.(UNIX Date in ASCII coded Octal)
218 UTC time }
219 ChkSum : Arr8; { 148-155, $ 94- 9B, checksum of header (6 bytes ASCII coded Octal, #00, #20) }
220 LinkFlag: AnsiChar; { 156, $ 9C, type of item, one of the Link Flag constants from above }
221 LinkName: ArrName; { 157-256, $ 9D-100, name of link, null terminated ASCII string }
222 Magic : TAbTarMagicRec;
223 { 257-264, $101-108, identifier, usually 'ustar'#00'00' }
224 UsrName : array [0..AB_TAR_TUSRNAMELEN-1] of AnsiChar;
225 { 265-296, $109-128, username, null terminated ASCII string }
226 GrpName : array [0..AB_TAR_TGRPNAMELEN-1] of AnsiChar;
227 { 297-328, $129-148, groupname, null terminated ASCII string }
228 DevMajor: Arr8; { 329-336, $149-150, major device ID (UNIX style, ASCII coded Octal) }
229 DevMinor: Arr8; { 337-344, $151-158, minor device ID (UNIX style, ASCII coded Octal) }
230 case TAbTarHeaderFormat of{ 345-511, $159-1FF See byte Definitions above.}
231 V7_FORMAT : ( v7 : TAbTarEnd_Empty_Rec );
232 OLDGNU_FORMAT: ( gnuOld: TAbTarEnd_GNU_old_Rec );
233 GNU_FORMAT : ( gnu : TAbTarEnd_GNU_old_Rec );
234 USTAR_FORMAT : ( ustar : TAbTarEnd_UStar_Rec );
235 STAR_FORMAT : ( star : TAbTarEnd_Star_Rec );
236 POSIX_FORMAT : ( pax : TAbTarEnd_Empty_Rec );
237 end;{ end TAbTarHeaderRec }
238 { There are three main types of headers we will see in a Tar file }
239 { TAbTarHeaderType = (STANDARD_HDR, SPARSE_HDR, POSIX_EXTENDED_HDR); }
240 { The 1st is defined above, The later two are simply organized data types. }
241
242 TAbTarItemRec = record
243 { Note: that the actual The name needs to be coherient with the name Inherited
244 from parent type TAbArchiveItem }
245 Name : string; { Path & File name. }
246 Mode : LongWord; { File Permissions }
247 uid : Integer; { User ID }
248 gid : Integer; { Group ID }
249 Size : Int64; { Tared File size }
250 ModTime : Int64; { Last time of Modification, in UnixTime }
251 ChkSumPass : Boolean; { Header Check sum found to be good }
252 LinkFlag : AnsiChar; { Link Flag, Echos the actual File Type of this Item. }
253 ItemType : TAbTarItemType; { Item Type Assigned from LinkFlag Header Types. }
254 LinkName : string; { Link Name }
255 Magic : AnsiString; { Magic value }
256 Version : Integer; { Version Number }
257 UsrName : string; { User Name, for User ID }
258 GrpName : string; { Group Name, for Group ID }
259 DevMajor : Integer; { Major Device ID }
260 DevMinor : Integer; { Minor Device ID }
261 { Additional Types used for holding info. }
262 AccessTime : Int64; { Time of Last Access, in UnixTime }
263 ChangeTime : Int64; { Time of Last Status Change, in UnixTime }
264 ArchiveFormat: TAbTarHeaderFormat; { Type of Archive of this record }
265 StreamPosition: Int64; { Pointer to the top of the item in the file. }
266 Dirty : Boolean; { Indication if this record needs to have its headers CheckSum recalculated }
267 ItemReadOnly: Boolean; { Indication if this record is READ ONLY }
268 FileHeaderCount:Integer;{ Number of Headers in the Orginal TarHeaders in the File Stream }
269 end;
270
271 type
272 PTAbTarItem = ^TAbTarItem;
273 TAbTarItem = class(TAbArchiveItem)
274 private
275 { The following private members are used for Stuffing FTarItem struct }
276 procedure ParseTarHeaders; { Error in header if }
277 procedure ParsePaxHeaders; { Error in header if }
278 procedure DetectHeaderFormat; { Helper to stuff HeaderFormat }
279 procedure GetFileNameFromHeaders; { Helper to pull name from Headers }
280 procedure GetLinkNameFromHeaders; { Helper to pull name from Headers }
281 function TestCheckSum: Boolean; { Helper to Calculate Checksum of a header. }
282 procedure DoGNUExistingLongNameLink(LinkFlag: AnsiChar; I: Integer; const Value: AnsiString);
283 procedure DoGNUNewLongNameLink(LinkFlag: AnsiChar; I: Integer; const Value: AnsiString);
284 protected {private}
285 PTarHeader: PAbTarHeaderRec;{ Points to FTarHeaderList.Items[FTarHeaderList.Count-1] }
286 FTarHeaderList: TList; { List of The Headers }
287 FTarHeaderTypeList: TList; { List of the Header Types }
288 FTarItem: TAbTarItemRec; { Data about current TAR Item }
289 protected
290 function GetDevMajor: Integer;
291 function GetDevMinor: Integer;
292 function GetGroupID: Integer;
293 function GetGroupName: string;
294 function GetLinkName: string;
295 function GetUserID: Integer;
296 function GetUserName: string;
297 function GetModTime: Int64;
298 function GetNumHeaders: Integer;
299 function GetMagic: string;
300
301 { All Sets shall update the headers Or add headers as needed. }
302 procedure SetDevMajor(const Value: Integer);
303 procedure SetDevMinor(const Value: Integer);
304 procedure SetGroupID(const Value: Integer); { Extended Headers }
305 procedure SetGroupName(const Value: string); { Extended Headers }
306 procedure SetLinkFlag(Value: AnsiChar);
307 procedure SetLinkName(const Value: string); { Extended Headers }
308 procedure SetUserID(const Value: Integer); { Extended Headers }
309 procedure SetUserName(const Value: string); { Extended Headers }
310 procedure SetModTime(const Value: Int64);
311 Procedure SetMagic(const Value: string);
312 { TODO: add support for Atime and Ctime here }
313
314 { Overrides for Inherited Properties from type TAbArchiveItem }
315 function GetCompressedSize : Int64; override;
316 function GetExternalFileAttributes : LongWord; override;
317 function GetFileName : string; override;
318 function GetIsDirectory: Boolean; override;
319 function GetIsEncrypted : Boolean; override;
320 function GetLastModFileDate : Word; override;
321 function GetLastModFileTime : Word; override;
322 function GetLastModTimeAsDateTime: TDateTime; override;
323 function GetNativeFileAttributes : LongInt; override;
324 function GetNativeLastModFileTime: Longint; override;
325 function GetUncompressedSize : Int64; override;
326
327 procedure SetCompressedSize(const Value : Int64); override; { Extended Headers }
328 procedure SetExternalFileAttributes( Value : LongWord ); override;
329 procedure SetFileName(const Value : string); override; { Extended Headers }
330 procedure SetIsEncrypted(Value : Boolean); override;
331 procedure SetLastModFileDate(const Value : Word); override; { Extended Headers }
332 procedure SetLastModFileTime(const Value : Word); override; { Extended Headers }
333 procedure SetLastModTimeAsDateTime(const Value: TDateTime); override;
334 procedure SetUncompressedSize(const Value : Int64); override; { Extended Headers }
335
336 procedure SaveTarHeaderToStream(AStream : TStream);
337 procedure LoadTarHeaderFromStream(AStream : TStream);
338
339 property Magic : string { Magic value }
340 read GetMagic write SetMagic;
341 public
342 { property Name : STRING; Path & File name. Inherited from parent type TAbArchiveItem }
343 { read GetFileName write SetFileName; overridden above}
344 property Mode : LongWord { File Permissions }
345 read GetExternalFileAttributes write SetExternalFileAttributes;
346 property UserID : Integer { User ID }
347 read GetUserID write SetUserID;
348 property GroupID : Integer { Group ID }
349 read GetGroupID write SetGroupID;
350 property ModTime : Int64
351 read GetModTime write SetModTime;
352 { property UncompressedSize/CompressedSize(Size): Int64; File size (comp/uncomp) Inherited from parent type TAbArchiveItem }
353 { read GetUncompressedSize, GetCompressedSize; overridden above }
354 { write SetUncompressedSize, SetCompressedSize; overridden above }
355 { property LastModFileTime/LastModFileDate(ModeTime): TDateTime; Last time of Modification Inherited from parent type TAbArchiveItem }
356 { read GetLastModFileTime, GetLastModFileDate; overridden above }
357 { write SetLastModFileTime, SetLastModFileDate; overridden above }
358
359 property CheckSumGood: Boolean
360 read FTarItem.ChkSumPass; { Header Check sum found to be good }
361 property LinkFlag : AnsiChar { Link Flag of File Header }
362 read FTarItem.LinkFlag write SetLinkFlag;
363 property LinkName : string { Link Name }
364 read GetLinkName write SetLinkName;
365 property UserName : string { User Name, for User ID }
366 read GetUserName write SetUserName;
367 property GroupName : string { Group Name, for Group ID }
368 read GetGroupName write SetGroupName;
369 property DevMajor : Integer { Major Device ID }
370 read GetDevMajor write SetDevMajor;
371 property DevMinor : Integer { Minor Device ID }
372 read GetDevMinor write SetDevMinor;
373 { TODO: Add support ATime and CTime }
374 {AccessTime : TDateTime;} { Time of Last Access }
375 {ChangeTime : TDateTime;} { Time of Last Status Change }
376 { Additional Types used for holding info. }
377 property ExternalFileAttributes;
378 property ArchiveFormat: TAbTarHeaderFormat
379 read FTarItem.ArchiveFormat write FTarItem.ArchiveFormat;
380 property ItemType: TAbTarItemType
381 read FTarItem.ItemType write FTarItem.ItemType;
382 property ItemReadOnly: Boolean
383 read FTarItem.ItemReadOnly write FTarItem.ItemReadOnly;
384 property FileHeaderCount: Integer
385 read FTarItem.FileHeaderCount;
386 property HeaderCount: Integer
387 read GetNumHeaders;
388 property StreamPosition: Int64
389 read FTarItem.StreamPosition write FTarItem.StreamPosition;
390 constructor Create;
391 destructor Destroy; override;
392 end; { end TAbArchiveItem }
393
394
395 TAbTarStreamHelper = class(TAbArchiveStreamHelper)
396 private
397 function FindItem: Boolean; { Tool for FindFirst/NextItem functions }
398 protected
399 FOnProgress : TAbProgressEvent;
400 FTarHeader : TAbTarHeaderRec; { Speed-up Buffer only }
401 FCurrItemSize : Int64; { Current Item size }
402 FCurrItemPreHdrs: Integer; { Number of Meta-data Headers before the Item }
403 public
404 constructor Create(AStream : TStream; AEvent : TAbProgressEvent); overload;
405 destructor Destroy; override;
406 procedure ExtractItemData(AStream : TStream); override;
407 function FindFirstItem : Boolean; override;
408 function FindNextItem : Boolean; override;
409 procedure ReadHeader; override;
410 procedure ReadTail; override;
411 function SeekItem(Index : Integer): Boolean; override;
412 procedure WriteArchiveHeader; override;
413 procedure WriteArchiveItem(AStream : TStream); override;
414 procedure WriteArchiveItemSize(AStream : TStream; ASize: Int64);
415 procedure WriteArchiveTail; override;
416 function GetItemCount : Integer; override;
417 end;
418
419
420 TAbTarArchive = class(TAbArchive)
421 private
422 FArchReadOnly : Boolean;
423 FArchFormat: TAbTarHeaderFormat;
424 protected
425 FTargetStream: TStream;
426 protected
427 function CreateItem(const SourceFileName : string;
428 const ArchiveDirectory : string): TAbArchiveItem;
429 override;
430 procedure ExtractItemAt(Index : Integer; const UseName : string);
431 override;
432 procedure ExtractItemToStreamAt(Index : Integer; aStream : TStream);
433 override;
434 procedure LoadArchive;
435 override;
436 procedure SaveArchive;
437 override;
438 procedure TestItemAt(Index : Integer);
439 override;
440 function FixName(const Value: string): string;
441 override;
442 function GetSupportsEmptyFolders: Boolean;
443 override;
444
445 function GetItem(Index: Integer): TAbTarItem;
446 procedure PutItem(Index: Integer; const Value: TAbTarItem);
447
448 public {methods}
449 constructor CreateFromStream(aStream : TStream; const aArchiveName : string);
450 override;
451 destructor Destroy;
452 override;
453 property UnsupportedTypesDetected : Boolean
454 read FArchReadOnly;
455 property Items[Index : Integer] : TAbTarItem
456 read GetItem
457 write PutItem; default;
458 end;
459
460 procedure UnixAttrsToTarAttrs(const UnixAttrs: LongWord;
461 out Permissions: LongWord; out LinkFlag: AnsiChar);
462 procedure TarAttrsToUnixAttrs(const Permissions: LongWord; const LinkFlag: AnsiChar;
463 out UnixAttrs: LongWord);
464
465 function VerifyTar(Strm : TStream) : TAbArchiveType;
466
467
468 implementation
469
470 uses
471 Math, RTLConsts, SysUtils, AbVMStrm, AbExcept, AbProgress,
472 DCOSUtils, DCClassesUtf8, DCConvertEncoding, DCStrUtils;
473
474 { ****************** Helper functions Not from Classes Above ***************** }
475 function OctalToInt(const Oct : PAnsiChar; aLen : integer): Int64;
476 var
477 r : UInt64;
478 i : integer;
479 c, sign : Byte;
480 begin
481 Result := 0;
482 if (aLen = 0 ) then
483 Exit;
484
485 { detect binary number format }
486 if ((Ord(Oct[0]) and $80) <> 0) then
487 begin
488 c:= Ord(Oct[0]);
489
490 if (c and $40 <> 0) then
491 begin
492 sign := $FF;
493 r := High(UInt64);
494 end
495 else begin
496 r := 0;
497 sign := 0;
498 c := c and $7F;
499 end;
500
501 i:= 1;
502 while (aLen > SizeOf(Int64)) do
503 begin
504 if (c <> sign) then
505 begin
506 if (sign <> 0) then
507 Result:= Low(Int64)
508 else begin
509 Result:= High(Int64);
510 end;
511 Exit;
512 end;
513 c := Ord(Oct[i]);
514 Dec(aLen);
515 Inc(i);
516 end;
517
518 if ((c xor sign) and $80 <> 0) then
519 begin
520 if (sign <> 0) then
521 Result:= Low(Int64)
522 else begin
523 Result:= High(Int64);
524 end;
525 Exit;
526 end;
527
528 while (aLen > 1) do
529 begin
530 r := (r shl 8) or c;
531 c:= Ord(Oct[i]);
532 Dec(aLen);
533 Inc(i);
534 end;
535 r := (r shl 8) or c;
536
537 Exit(Int64(r));
538 end;
539
540 i := 0;
541 while (i < aLen) and (Oct[i] = ' ') do
542 inc(i);
543
544 if (i = aLen) then
545 Exit;
546
547 while (i < aLen) and (Oct[i] in ['0'..'7']) do begin
548 Result := (Result * 8) + (Ord(Oct[i]) - Ord('0'));
549 inc(i);
550 end;
551 end;
552
553 function IntToOctal(Value : Int64): AnsiString;
554 const
555 OctDigits : array[0..7] of AnsiChar = '01234567';
556 begin
557 if Value = 0 then
558 Result := '0'
559 else begin
560 Result := '';
561 while Value > 0 do begin
562 Result := OctDigits[Value and 7] + Result;
563 Value := Value shr 3;
564 end;
565 end;
566 end;
567
568
569 function CalcTarHeaderChkSum(const TarH : TAbTarHeaderRec): LongInt;
570 var
571 HdrBuffer : PAnsiChar;
572 HdrChkSum : LongInt;
573 j : Integer;
574 begin
575 { prepare for the checksum calculation }
576 HdrBuffer := PAnsiChar(@TarH);
577 HdrChkSum := 0;
578
579 {calculate the checksum, a simple sum of the bytes in the header}
580 for j := 0 to Pred(SizeOf(TAbTarHeaderRec)) do
581 HdrChkSum := HdrChkSum + Ord(HdrBuffer[j]);
582
583 Result := HdrChkSum;
584 end;
585
586 function VerifyTar(Strm : TStream) : TAbArchiveType;
587 { assumes Tar positioned correctly for test of item }
588 var
589 TarItem : TAbTarItem;
590 StartPos : Int64;
591 begin
592 StartPos := Strm.Position;
593 try
594 { Verifies that the header checksum is valid, and Item type is understood.
595 This does not mean that extraction is supported. }
596 TarItem := TAbTarItem.Create;
597 try
598 { get current Tar Header }
599 TarItem.LoadTarHeaderFromStream(Strm);
600 if TarItem.CheckSumGood then
601 Result := atTar
602 else
603 Result := atUnknown;
604 finally
605 TarItem.Free;
606 end;
607 except
608 on EReadError do
609 Result := atUnknown;
610 end;
611 Strm.Position := StartPos;
612 end;
613
614 function PadString(const S : AnsiString; Places : Integer) : AnsiString;
615 {
616 Pads a string (S) with one right space and as many left spaces as
617 needed to fill Places
618
619 If length S greater than Places, just returns S
620
621 Some TAR utilities evidently expect Octal numeric fields to be in
622 this format
623 }
624 begin
625 if Length(S) >= LongInt(Places) then
626 Result := S
627 else begin
628 Result := S + ' ';
629 Result := StringOfChar(AnsiChar(' '), Places - Length(Result)) + Result;
630 end;
631 end;
632
633 { Round UP to the nearest Tar Block Boundary. }
634 function RoundToTarBlock(Size: Int64) : Int64;
635 begin
636 Result := (Size + (AB_TAR_RECORDSIZE - 1)) and
637 not (AB_TAR_RECORDSIZE - 1);
638 end;
639
640 procedure UnixAttrsToTarAttrs(const UnixAttrs: LongWord;
641 out Permissions: LongWord; out LinkFlag: AnsiChar);
642 begin
643 case (UnixAttrs and $F000) of
644 AB_FMODE_SOCKET:
645 ;
646 AB_FMODE_FILELINK:
647 LinkFlag := AB_TAR_LF_SYMLINK;
648 AB_FMODE_FILE2:
649 LinkFlag := AB_TAR_LF_NORMAL;
650 AB_FMODE_BLOCKSPECFILE:
651 LinkFlag := AB_TAR_LF_BLK;
652 AB_FMODE_DIR:
653 LinkFlag := AB_TAR_LF_DIR;
654 AB_FMODE_CHARSPECFILE:
655 LinkFlag := AB_TAR_LF_CHR;
656 AB_FMODE_FIFO:
657 LinkFlag := AB_TAR_LF_FIFO;
658 AB_FMODE_FILE:
659 LinkFlag := AB_TAR_LF_NORMAL;
660 else
661 LinkFlag := AB_TAR_LF_OLDNORMAL;
662 end;
663
664 Permissions := (UnixAttrs and $0FFF);
665 end;
666 { -------------------------------------------------------------------------- }
667 procedure TarAttrsToUnixAttrs(const Permissions: LongWord; const LinkFlag: AnsiChar;
668 out UnixAttrs: LongWord);
669 begin
670 case LinkFlag of
671 AB_TAR_LF_OLDNORMAL:
672 UnixAttrs := AB_FMODE_FILE;
673 AB_TAR_LF_NORMAL:
674 UnixAttrs := AB_FMODE_FILE2;
675 AB_TAR_LF_SYMLINK:
676 UnixAttrs := AB_FMODE_FILELINK;
677 AB_TAR_LF_BLK:
678 UnixAttrs := AB_FMODE_BLOCKSPECFILE;
679 AB_TAR_LF_DIR:
680 UnixAttrs := AB_FMODE_DIR;
681 AB_TAR_LF_CHR:
682 UnixAttrs := AB_FMODE_CHARSPECFILE;
683 AB_TAR_LF_FIFO:
684 UnixAttrs := AB_FMODE_FIFO;
685 else
686 UnixAttrs := AB_FMODE_FILE;
687 end;
688
689 UnixAttrs := UnixAttrs or (Permissions and $0FFF);
690 end;
691
692 { ****************************** TAbTarItem ********************************** }
693 constructor TAbTarItem.Create;
694 begin
695 inherited Create;
696 FTarHeaderList := TList.Create;
697 FTarHeaderTypeList := TList.Create;
698 GetMem(PTarHeader, AB_TAR_RECORDSIZE); { PTarHeader is our new Header }
699 FillChar(PTarHeader^, AB_TAR_RECORDSIZE, #0);
700 FTarHeaderList.Add(PTarHeader);
701 FTarHeaderTypeList.Add(Pointer(FILE_HEADER));
702 FTarItem.FileHeaderCount := 1;
703 { set defaults }
704 FTarItem.ArchiveFormat := UNKNOWN_FORMAT;
705
706 FileName := '';
707 Mode := AB_FPERMISSION_GENERIC;
708 UserID := 0;
709 GroupID := 0;
710 UncompressedSize := 0;
711 { ModTime }
712 LinkFlag := AB_TAR_LF_OLDNORMAL;
713 { Link Name }
714 PTarHeader.Magic.gnuOld := AB_TAR_MAGIC_V7_NONE; { Default to GNU type }
715 UserName := '';
716 GroupName := '';
717 DevMajor := 0;
718 DevMinor := 0;
719 { TODO: atime, ctime }
720 FTarItem.ItemType := SUPPORTED_ITEM;
721 FTarItem.Dirty := True; { Checksum needs to be generated }
722 FTarItem.ItemReadOnly := False;
723 end;
724
725 destructor TAbTarItem.Destroy;
726 var
727 i : Integer;
728 begin
729 if Assigned(FTarHeaderList) then
730 begin
731 for i := 0 to FTarHeaderList.Count - 1 do
732 FreeMem(FTarHeaderList.Items[i]); { This list holds PAbTarHeaderRec's }
733 FTarHeaderList.Free;
734 end;
735 FTarHeaderTypeList.Free;
736 inherited Destroy;
737 end;
738
739 function TAbTarItem.GetCompressedSize: Int64;
740 { TAR includes no internal compression, returns same value as GetUncompressedSize }
741 begin
742 Result := FTarItem.Size;
743 end;
744
745 function TAbTarItem.GetDevMajor: Integer;
746 begin
747 Result := FTarItem.DevMajor;
748 end;
749
750 function TAbTarItem.GetDevMinor: Integer;
751 begin
752 Result := FTarItem.DevMinor;
753 end;
754
755 function TAbTarItem.GetExternalFileAttributes: LongWord;
756 begin
757 TarAttrsToUnixAttrs(FTarItem.Mode, FTarItem.LinkFlag, Result);
758 end;
759
760 function TAbTarItem.GetFileName: string;
761 begin
762 Result := FTarItem.Name; { Inherited String from Parent Class }
763 end;
764
765 function TAbTarItem.GetGroupID: Integer;
766 begin
767 Result := FTarItem.gid;
768 end;
769
770 function TAbTarItem.GetGroupName: string;
771 begin
772 Result := FTarItem.GrpName;
773 end;
774
775 function TAbTarItem.GetIsDirectory: Boolean;
776 begin
777 Result := (LinkFlag = AB_TAR_LF_DIR);
778 end;
779
780 function TAbTarItem.GetIsEncrypted: Boolean;
781 begin
782 { TAR has no native encryption }
783 Result := False;
784 end;
785
786 function TAbTarItem.GetLastModFileDate: Word;
787 begin
788 { convert to local DOS file Date }
789 Result := LongRec(AbDateTimeToDosFileDate(LastModTimeAsDateTime)).Hi;
790 end;
791
792 function TAbTarItem.GetLastModFileTime: Word;
793 begin
794 { convert to local DOS file Time }
795 Result := LongRec(AbDateTimeToDosFileDate(LastModTimeAsDateTime)).Lo;
796 end;
797
798 function TAbTarItem.GetLastModTimeAsDateTime: TDateTime;
799 begin
800 Result := AbUnixTimeToLocalDateTime(FTarItem.ModTime);
801 end;
802
803 function TAbTarItem.GetNativeLastModFileTime: Longint;
804 {$IFDEF MSWINDOWS}
805 var
806 DateTime: TDateTime;
807 {$ENDIF}
808 begin
809 Result := Self.ModTime;
810
811 {$IFDEF MSWINDOWS}
812 DateTime := AbUnixTimeToLocalDateTime(Result);
813 Result := AbDateTimeToDosFileDate(DateTime);
814 {$ENDIF}
815 end;
816 function TAbTarItem.GetLinkName: string;
817 begin
818 Result := FTarItem.LinkName;
819 end;
820
821 function TAbTarItem.GetMagic: string;
822 begin
823 Result := string(FTarItem.Magic);
824 end;
825
826 function TAbTarItem.GetNativeFileAttributes : LongInt;
827 begin
828 Result := GetExternalFileAttributes;
829 {$IFDEF MSWINDOWS}
830 Result := AbUnix2DosFileAttributes(Result);
831 {$ENDIF}
832 end;
833
834 function TAbTarItem.GetUncompressedSize: Int64;
835 { TAR includes no internal compression, returns same value as GetCompressedSize }
836 begin
837 Result := FTarItem.Size;
838 end;
839
840 function TAbTarItem.GetUserID: Integer;
841 begin
842 Result := FTarItem.uid;
843 end;
844
845 function TAbTarItem.GetUserName: string;
846 begin
847 Result := FTarItem.UsrName;
848 end;
849
850 function TAbTarItem.GetModTime: Int64;
851 begin
852 Result := FTarItem.ModTime;
853 end;
854
855 { Get Number of tar headers currently for this item }
856 function TAbTarItem.GetNumHeaders: Integer;
857 begin
858 Result := FTarHeaderList.Count;
859 end;
860
861 { Takes data from Supported Header types stored in TAbTarItem.FTarHeaderList }
862 { and updates values in the TAbTarItem.FTarItem.X }
863
864 procedure TAbTarItem.DetectHeaderFormat;
865 begin
866 if FTarItem.ArchiveFormat <> UNKNOWN_FORMAT then
867 Exit;{ We have already set the format. }
868 { In the previous header parsing if pax headers are detected the format is changed }
869 { GNU_FORMAT is detected by the presence of GNU extended headers. }
870
871 { These detections are similar to GNU tar's. }
872 if CompareByte(PTarHeader.Magic.value, AB_TAR_MAGIC_VAL, SizeOf(AB_TAR_MAGIC_VAL)) = 0 then
873 begin { We have one of three types, STAR_FORMAT, USTAR_FORMAT, POSIX_FORMAT }
874 { Detect STAR format. Leave disabled until explicit STAR support is added. }
875 {if (PTarHeader.star.Prefix[130] = #00) and
876 (PTarHeader.star.Atime[0] in ['0'..'7']) and
877 (PTarHeader.star.Atime[11] = #20) and
878 (PTarHeader.star.Ctime[0]in ['0'..'7']) and
879 (PTarHeader.star.Ctime[11] = #20) then
880 begin
881 FTarItme.ArchiveType := STAR_FORMAT;
882 end }
883 { else if } { POSIX uses the existance of x headers }
884
885 { This can define false positives, Pax headers/ STAR format could be detected as this }
886 FTarItem.ArchiveFormat := USTAR_FORMAT;
887 end
888 else if CompareByte(PTarHeader.Magic.gnuOld, AB_TAR_MAGIC_GNUOLD, SizeOf(AB_TAR_MAGIC_GNUOLD)) = 0 then
889 begin
890 FTarItem.ArchiveFormat := OLDGNU_FORMAT;
891 end
892 else { V7 uses AB_TAR_LF_OLDNORMAL linkflag, has no magic field & no Usr/Grp Names }
893 begin
894 FTarItem.ArchiveFormat := V7_FORMAT; { Lowest Common Denominator }
895 end;
896 end;
897
898 { Extract the file name from the headers }
899 procedure TAbTarItem.GetFileNameFromHeaders;
900 var
901 I, J : Integer;
902 PHeader: PAbTarHeaderRec;
903 FoundName: Boolean;
904 NameLength : Int64;
905 NumMHeaders: integer;
906 ExtraName: integer;
907 RawFileName, TempStr: AnsiString;
908 begin
909 { UNKNOWN_FORMAT, V7_FORMAT, OLDGNU_FORMAT, GNU_FORMAT, USTAR_FORMAT, STAR_FORMAT, POSIX_FORMAT }
910 FoundName := False;
911 I := 0;
912 while (not FoundName) and (I <= (FTarHeaderList.Count - 1)) do
913 begin
914 PHeader := FTarHeaderList.Items[I];
915 if PHeader.LinkFlag = AB_TAR_LF_LONGNAME then
916 begin
917 FoundName := True;
918 RawFileName := '';
919 NameLength := OctalToInt(PHeader.Size, SizeOf(PHeader.Size));
920 NumMHeaders := NameLength div AB_TAR_RECORDSIZE;
921 ExtraName := NameLength mod AB_TAR_RECORDSIZE; { Chars in the last Header }
922 { NumMHeaders should never be zero }
923 { It appears that it is not null terminated in the blocks }
924 for J := 1 to NumMHeaders do
925 begin
926 { Copy entire content of Header to String }
927 PHeader := FTarHeaderList.Items[I+J];
928 SetString(TempStr, PAnsiChar(PHeader), AB_TAR_RECORDSIZE);
929 RawFileName := RawFileName + TempStr;
930 end;
931 if ExtraName <> 0 then
932 begin
933 PHeader := FTarHeaderList.Items[I+NumMHeaders+1];
934 SetString(TempStr, PAnsiChar(PHeader), ExtraName-1);
935 RawFileName := RawFileName + TempStr;
936 end
937 else { We already copied the entire name, but the string is still null terminated. }
938 begin
939 { Removed the last zero }
940 SetLength(RawFileName, (Length(RawFileName)-1));
941 end;
942 end { end long filename link flag }
943 else
944 I := I + 1;
945 end; { End While }
946
947 if not FoundName then
948 begin
949 if (FTarItem.ArchiveFormat = USTAR_FORMAT) and
950 (PTarHeader.ustar.Prefix[0] <> #0) then
951 RawFileName := PTarHeader.ustar.Prefix+'/'+PTarHeader.Name
952 else
953 { V7_FORMAT, OLDGNU_FORMAT }
954 RawFileName := PTarHeader.Name;
955 end; { End not FoundName }
956
957 FTarItem.Name := CeRawToUtf8(RawFileName);
958 end;
959
960 { Extract the file name from the headers }
961 procedure TAbTarItem.GetLinkNameFromHeaders;
962 var
963 I, J : Integer;
964 PHeader: PAbTarHeaderRec;
965 FoundName: Boolean;
966 NameLength : Int64;
967 NumMHeaders: integer;
968 ExtraName: integer;
969 RawLinkName, TempStr: AnsiString;
970 begin
971 { UNKNOWN_FORMAT, V7_FORMAT, OLDGNU_FORMAT, GNU_FORMAT, USTAR_FORMAT, STAR_FORMAT, POSIX_FORMAT }
972 PHeader := nil;
973 FoundName := False;
974 I := 0;
975 { Note that: FTarHeaderList.Count <= 1, always }
976 while (not FoundName) and (I <= (FTarHeaderList.Count - 1)) do
977 begin
978 PHeader := FTarHeaderList.Items[I];
979 if PHeader.LinkFlag = AB_TAR_LF_LONGLINK then
980 begin
981 FoundName := True;
982 RawLinkName := '';
983 NameLength := OctalToInt(PHeader.Size, SizeOf(PHeader.Size));
984 NumMHeaders := NameLength div AB_TAR_RECORDSIZE;
985 ExtraName := NameLength mod AB_TAR_RECORDSIZE; { Chars in the last Header }
986 { NumMHeaders should never be zero }
987 { It appears that it is not null terminated in the blocks }
988 for J := 1 to NumMHeaders do
989 begin
990 { Copy entire content of Header to String }
991 PHeader := FTarHeaderList.Items[I+J];
992 SetString(TempStr, PAnsiChar(PHeader), AB_TAR_RECORDSIZE);
993 RawLinkName := RawLinkName + TempStr;
994 end;
995 if ExtraName <> 0 then
996 begin
997 PHeader := FTarHeaderList.Items[I+NumMHeaders+1];
998 SetString(TempStr, PAnsiChar(PHeader), ExtraName-1);
999 RawLinkName := RawLinkName + TempStr;
1000 end
1001 else { We already copied the entire name, but the string is still null terminated. }
1002 begin
1003 { Removed the last zero }
1004 SetLength(RawLinkName, (Length(RawLinkName)-1));
1005 end;
1006 end { end long filename link flag }
1007 else
1008 I := I + 1;
1009 end; { End While }
1010
1011 if not FoundName then
1012 RawLinkName := PHeader.LinkName;
1013
1014 FTarItem.LinkName := CeRawToUtf8(RawLinkName);
1015 end;
1016
1017 { Return True if CheckSum passes out. }
1018 function TAbTarItem.TestCheckSum : Boolean;
1019 var
1020 TarChkSum : LongInt;
1021 TarChkSumArr : Arr8; { ChkSum field is Arr8 }
1022 PHeader: PAbTarHeaderRec;
1023 I: Integer;
1024 begin
1025 Result := True;
1026 { Check sums are in valid headers but NOT in the data headers. }
1027 for I := 0 to FTarHeaderList.Count - 1 do
1028 begin
1029 if TAbTarHeaderType(FTarHeaderTypeList.Items[I]) in [FILE_HEADER, META_DATA_HEADER] then
1030 begin
1031 PHeader := FTarHeaderList.Items[i];
1032 { Save off old Check sum }
1033 Move(PHeader.ChkSum, TarChkSumArr, SizeOf(PHeader.ChkSum));
1034 TarChkSum := OctalToInt(TarChkSumArr, SizeOf(TarChkSumArr));
1035 { Set to Generator Value }
1036 PHeader.ChkSum := AB_TAR_CHKBLANKS;
1037 if CalcTarHeaderChkSum(PHeader^) <> TarChkSum then
1038 Result := False; { Pass unless one miss-compares }
1039 { Save back old checksum }
1040 Move(TarChkSumArr, PHeader.ChkSum, SizeOf(TarChkSumArr));
1041 end;
1042 end;
1043 end;
1044
1045 procedure TAbTarItem.ParseTarHeaders;
1046 begin
1047 { The final index is the Item index }
1048 DetectHeaderFormat;
1049 { Long term this parsing is not correct, as the values in extended headers
1050 override the later values in this header }
1051 FTarItem.Mode := OctalToInt(PTarHeader.Mode, SizeOf(PTarHeader.Mode));
1052 FTarItem.uid := OctalToInt(PTarHeader.uid, SizeOf(PTarHeader.uid)); { Extended in PAX Headers }
1053 FTarItem.gid := OctalToInt(PTarHeader.gid, SizeOf(PTarHeader.gid)); { Extended in PAX Headers }
1054 FTarItem.Size := OctalToInt(PTarHeader.Size, SizeOf(PTarHeader.Size)); { Extended in PAX Headers }
1055 { ModTime should be an Int64 but no tool support, No issues until Feb 6th, 2106 :) }
1056 { ModTime is Extended in PAX Headers }
1057 FTarItem.ModTime := OctalToInt(PTarHeader.ModTime, SizeOf(PTarHeader.ModTime));
1058 FTarItem.ChkSumPass := TestCheckSum();
1059 FTarItem.LinkFlag := PTarHeader.LinkFlag;
1060 GetLinkNameFromHeaders; { Extended in PAX Headers }
1061 FTarItem.Magic := PTarHeader.Magic.value;
1062 FTarItem.Version := OctalToInt(PTarHeader.Magic.version, SizeOf(PTarHeader.Magic.version));
1063 FTarItem.UsrName := string(PTarHeader.UsrName); { Extended in PAX Headers }
1064 FTarItem.GrpName := string(PTarHeader.GrpName); { Extended in PAX Headers }
1065 FTarItem.DevMajor := OctalToInt(PTarHeader.DevMajor, SizeOf(PTarHeader.DevMajor));
1066 FTarItem.DevMinor := OctalToInt(PTarHeader.DevMinor, SizeOf(PTarHeader.DevMinor));
1067 GetFileNameFromHeaders;
1068 { FTarItem.ArchiveFormat; Already stuffed }
1069 { FTarItem.StreamPosition: Already Stuffed }
1070 { FTarItem.Dirty; Stuffed upon creaction }
1071 end;
1072
1073 procedure TAbTarItem.ParsePaxHeaders;
1074 var
1075 I, J : Integer;
1076 ALength: Integer;
1077 RawLength: Int64;
1078 RawExtra: Integer;
1079 S, P, O: PAnsiChar;
1080 NumMHeaders: Integer;
1081 PHeader: PAbTarHeaderRec;
1082 AName, AValue: AnsiString;
1083 RawValue, TempStr: AnsiString;
1084 begin
1085 RawValue := EmptyStr;
1086
1087 for I := 0 to FTarHeaderList.Count - 1 do
1088 begin
1089 PHeader := FTarHeaderList.Items[I];
1090 if PHeader.LinkFlag = AB_TAR_LF_XHDR then
1091 begin
1092 RawLength := OctalToInt(PHeader.Size, SizeOf(PHeader.Size));
1093 // Number of headers
1094 NumMHeaders := RawLength div AB_TAR_RECORDSIZE;
1095 // Chars in the last header
1096 RawExtra := RawLength mod AB_TAR_RECORDSIZE;
1097 // Copy data from headers
1098 for J := 1 to NumMHeaders do
1099 begin
1100 PHeader := FTarHeaderList.Items[I + J];
1101 SetString(TempStr, PAnsiChar(PHeader), AB_TAR_RECORDSIZE);
1102 RawValue := RawValue + TempStr;
1103 end;
1104 // Copy data from the last header
1105 if RawExtra <> 0 then
1106 begin
1107 PHeader := FTarHeaderList.Items[I + NumMHeaders + 1];
1108 SetString(TempStr, PAnsiChar(PHeader), RawExtra);
1109 RawValue := RawValue + TempStr;
1110 end;
1111 Break;
1112 end;
1113 end;
1114
1115 // Parse pax headers
1116 if (Length(RawValue) > 0) then
1117 begin
1118 O := nil;
1119 ALength:= 0;
1120 S:= Pointer(RawValue);
1121 P:= S;
1122 while (P^ <> #0) do
1123 begin
1124 case P^ of
1125 #10:
1126 begin
1127 Inc(P);
1128 S := P;
1129 O := nil;
1130 ALength:= 0;
1131 end;
1132 #32:
1133 begin
1134 P^:= #0;
1135 Inc(P);
1136 O:= P;
1137 ALength:= StrToIntDef(S, 0);
1138 end;
1139 '=':
1140 begin
1141 // Something wrong, exit
1142 if (ALength = 0) or (O = nil) then
1143 Exit;
1144
1145 SetString(AName, O, P - O);
1146 ALength:= ALength - (P - S) - 1;
1147
1148 if (AName = 'path') then
1149 begin
1150 SetString(AValue, P + 1, ALength - 1);
1151 FTarItem.Name := CeRawToUtf8(AValue);
1152 end
1153 else if (AName = 'linkpath') then
1154 begin
1155 SetString(AValue, P + 1, ALength - 1);
1156 FTarItem.LinkName := CeRawToUtf8(AValue);
1157 end
1158 else if (AName = 'size') then
1159 begin
1160 SetString(AValue, P + 1, ALength - 1);
1161 FTarItem.Size := StrToInt64Def(AValue, FTarItem.Size);
1162 end
1163 else if (AName = 'mtime') then
1164 begin
1165 SetString(AValue, P + 1, ALength - 1);
1166 FTarItem.ModTime := Round(StrToFloatDef(AValue, FTarItem.ModTime));
1167 end;
1168
1169 Inc(P, ALength);
1170 end;
1171 else begin
1172 Inc(P);
1173 end;
1174 end;
1175 end;
1176 end;
1177 end;
1178
1179 procedure TAbTarItem.LoadTarHeaderFromStream(AStream: TStream);
1180 var
1181 NumMHeaders : Integer;
1182 I : Integer;
1183 FoundItem : Boolean;
1184 begin
1185 { Note: The SizeOf(TAbTarHeaderRec) = AB_TAR_RECORDSIZE }
1186 { We should expect FindNext/FirstItem, and next check for bounds. }
1187 if FTarHeaderList.Count > 0 then
1188 begin { We're Going to stomp over the headers that are already present }
1189 { We need to destory the memory we've used }
1190 PTarHeader := nil;
1191 for i := 0 to FTarHeaderList.Count - 1 do
1192 FreeMem(FTarHeaderList.Items[i]); { This list holds PAbTarHeaderRec's }
1193 FTarHeaderList.Clear;
1194 FTarHeaderTypeList.Clear;
1195 FTarItem.FileHeaderCount := 0;
1196 { All pointers should now be removed from those headers }
1197 end;
1198 { Now lets start filling up that list. }
1199 FTarItem.ItemType := UNKNOWN_ITEM; { We don't know what we have yet }
1200 FoundItem := False;
1201 while not FoundItem do
1202 begin
1203 { Create a Header to be Stored in the Items List }
1204 GetMem(PTarHeader, AB_TAR_RECORDSIZE);
1205 AStream.ReadBuffer(PTarHeader^, AB_TAR_RECORDSIZE);
1206 FTarHeaderList.Add(PTarHeader); { Store the Header to the list }
1207 { Parse header based on LinkFlag }
1208 if PTarHeader.LinkFlag in (AB_SUPPORTED_MD_HEADERS+AB_UNSUPPORTED_MD_HEADERS) then
1209 begin { This Header type is in the Set of un/supported Meta data type headers }
1210 if PTarHeader.LinkFlag in AB_UNSUPPORTED_MD_HEADERS then
1211 FTarItem.ItemReadOnly := True; { We don't fully support this meta-data type }
1212 if (PTarHeader.LinkFlag in AB_PAX_MD_HEADERS) and (CompareByte(PTarHeader.Magic.value, AB_TAR_MAGIC_VAL, SizeOf(AB_TAR_MAGIC_VAL)) = 0) then
1213 FTarItem.ArchiveFormat := POSIX_FORMAT; { We have a POSIX_FORMAT, has x headers, and Magic matches }
1214 if PTarHeader.LinkFlag in AB_GNU_MD_HEADERS then
1215 FTarItem.ArchiveFormat := OLDGNU_FORMAT; { We have a OLDGNU_FORMAT, has L/K headers }
1216 { There can be a unknown number of Headers of data }
1217 { We are for sure going to read at least one more header, but are we going to read more than that? }
1218 FTarHeaderTypeList.Add(Pointer(META_DATA_HEADER));
1219 NumMHeaders := Ceil(OctalToInt(PTarHeader.Size, SizeOf(PTarHeader.Size)) / AB_TAR_RECORDSIZE);
1220 { NumMHeasder should never be zero }
1221 for I := 1 to NumMHeaders do
1222 begin
1223 GetMem(PTarHeader, AB_TAR_RECORDSIZE); { Create a new Header }
1224 AStream.ReadBuffer(PTarHeader^, AB_TAR_RECORDSIZE); { Get the Meta Data }
1225 FTarHeaderList.Add(PTarHeader); { Store the Header to the list }
1226 FTarHeaderTypeList.Add(Pointer(MD_DATA_HEADER));
1227 end;
1228 { Loop and reparse }
1229 end
1230 else if PTarHeader.LinkFlag in AB_SUPPORTED_F_HEADERS then
1231 begin { This Header type is in the Set of supported File type Headers }
1232 FoundItem := True; { Exit Criterion }
1233 FTarItem.ItemType := SUPPORTED_ITEM;
1234 if FTarItem.ItemReadOnly then { Since some of the Headers are read only. }
1235 FTarItem.ItemType := UNSUPPORTED_ITEM; { This Item is unsupported }
1236 FTarHeaderTypeList.Add(Pointer(FILE_HEADER));
1237 end
1238 else if PTarHeader.LinkFlag in AB_UNSUPPORTED_F_HEADERS then
1239 begin { This Header type is in the Set of unsupported File type Headers }
1240 FoundItem := True; { Exit Criterion }
1241 FTarItem.ItemType := UNSUPPORTED_ITEM;
1242 FTarHeaderTypeList.Add(Pointer(FILE_HEADER));
1243 end
1244 else { These are unknown header types }
1245 begin { Note: Some of these unknown types could have known Meta-data headers }
1246 FoundItem := True;
1247 FTarItem.ItemType := UNKNOWN_ITEM;
1248 FTarHeaderTypeList.Add(Pointer(UNKNOWN_HEADER));
1249 end;{ end LinkFlag parsing }
1250 end; { end Found Item While }
1251 { PTarHeader points to FTarHeaderList.Items[FTarHeaderList.Count-1]; }
1252
1253 { Re-wind the Stream back to the begining of this Item inc. all headers }
1254 AStream.Seek(-(FTarHeaderList.Count*AB_TAR_RECORDSIZE), soCurrent);
1255 { AStream.Position := FTarItem.StreamPosition; } { This should be equivalent as above }
1256 FTarItem.FileHeaderCount := FTarHeaderList.Count;
1257 if FTarItem.ItemType <> UNKNOWN_ITEM then
1258 begin
1259 ParseTarHeaders; { Update FTarItem values }
1260 ParsePaxHeaders; { Update FTarItem values }
1261 FFileName := FTarItem.Name; {FTarHeader.Name;}
1262 // FDiskFileName := FileName;
1263 // AbUnfixName(FDiskFileName);
1264 end;
1265 Action := aaNone;
1266 Tagged := False;
1267 end;
1268
1269
1270 { ****************** BEGIN SET ********************** }
1271
1272 procedure TAbTarItem.SaveTarHeaderToStream(AStream: TStream);
1273 var
1274 i : Integer;
1275 j : Integer;
1276 PHeader : PAbTarHeaderRec;
1277 HdrChkSum : Integer;
1278 HdrChkStr : AnsiString;
1279 HdrBuffer : PAnsiChar;
1280 SkipNextChkSum: Integer;
1281 SkipChkSum: Boolean;
1282 begin
1283 if FTarItem.ItemReadOnly then { Read Only - Do Not Save }
1284 Exit;
1285 { Note: The SizeOf(TAbTarHeaderRec) = AB_TAR_RECORDSIZE }
1286 if FTarItem.Dirty then
1287 SkipNextChkSum := 0
1288 else
1289 SkipNextChkSum := FTarHeaderList.Count; { Don't recalc any chkSums }
1290
1291 { The first header in the Item list must have a checksum calculation }
1292 for i := 0 to (FTarHeaderList.Count-1) do
1293 begin
1294 SkipChkSum := False;
1295 PHeader := FTarHeaderList.Items[i];
1296 if (SkipNextChkSum = 0) then
1297 begin { We need to parse this header }
1298 if PHeader.LinkFlag in (AB_SUPPORTED_MD_HEADERS+AB_UNSUPPORTED_MD_HEADERS) then
1299 begin { We have a Meta-Data Header, Calculate how many headers to skip. }
1300 { These meta-data headers have non-Header buffers after this Header }
1301 SkipNextChkSum := Ceil(OctalToInt(PHeader.Size, SizeOf(PHeader.Size)) / AB_TAR_RECORDSIZE);
1302 { Ceil will mandate one run through, and will handle 512 correctly }
1303 end
1304 else if PHeader.LinkFlag in AB_SUPPORTED_F_HEADERS then
1305 begin
1306 SkipNextChkSum := 0;
1307 end
1308 else
1309 begin { Un-Supported Header type, Copy but do nothing to the data }
1310 SkipNextChkSum := 0;
1311 SkipChkSum := True;
1312 end;{ end LinkFlag parsing }
1313 end
1314 else
1315 begin { Do not calcuate the check sum on this meta Data header buffer }
1316 SkipNextChkSum := SkipNextChkSum - 1;
1317 SkipChkSum := True;
1318 end;{ end SkipNextChkSum }
1319
1320 if not SkipChkSum then
1321 begin { We are Calculating the Checksum for this Header }
1322 {Tar ChkSum is "odd" The check sum field is filled with #20 chars as empty }
1323 { ChkSum field itself is #20'd and has an effect on the sum }
1324 PHeader.ChkSum := AB_TAR_CHKBLANKS;
1325 { Set up the buffers }
1326 HdrBuffer := PAnsiChar(PHeader);
1327 HdrChkSum := 0;
1328 { Calculate the checksum, a simple sum of the bytes in the header }
1329 for j := 0 to (AB_TAR_RECORDSIZE-1) do
1330 HdrChkSum := HdrChkSum + Ord(HdrBuffer[j]);
1331 { set the checksum in the header }
1332 HdrChkStr := PadString(IntToOctal(HdrChkSum), SizeOf(PHeader.ChkSum));
1333 Move(HdrChkStr[1], PHeader.ChkSum, Length(HdrChkStr));
1334 end; { end Skip Check Sum }
1335 { write header to the file }
1336 AStream.Write(PHeader^, AB_TAR_RECORDSIZE);
1337 end; { End for the number of headers in the list }
1338 { Updated here as the stream is now updated to the latest number of headers }
1339 FTarItem.FileHeaderCount := FTarHeaderList.Count;
1340 end;
1341
1342 procedure TAbTarItem.SetCompressedSize(const Value: Int64);
1343 var
1344 S : AnsiString;
1345 begin
1346 if FTarItem.ItemReadOnly then { Read Only - Do Not Save }
1347 Exit;
1348 { Size is extendable in PAX Headers, Remember PAX extended Header Over Rule File Headers }
1349 FTarItem.Size := Value; { Store our Vitrual Copy }
1350 S := PadString(IntToOctal(Value), SizeOf(Arr12));{ Stuff to header }
1351 Move(S[1], PTarHeader.Size, Length(S));
1352 FTarItem.Dirty := True;
1353 end;
1354
1355 procedure TAbTarItem.SetDevMajor(const Value: Integer);
1356 var
1357 S : AnsiString;
1358 begin
1359 if FTarItem.ItemReadOnly then { Read Only - Do Not Save }
1360 Exit;
1361 { Dev Major and Minor are Only used for AB_TAR_LF_CHR, AB_TAR_LF_BLK }
1362 { Otherwise they are stuffed with #00 }
1363 FTarItem.DevMajor := Value; { Store to the struct }
1364 S := PadString(IntToOctal(Value), SizeOf(Arr8));
1365 Move(S[1], PTarHeader.DevMajor, Length(S));
1366 FTarItem.Dirty := True;
1367 end;
1368
1369 procedure TAbTarItem.SetDevMinor(const Value: Integer);
1370 var
1371 S : AnsiString;
1372 begin
1373 if FTarItem.ItemReadOnly then { Read Only - Do Not Save }
1374 Exit;
1375 { Dev Major and Minor are Only used for AB_TAR_LF_CHR, AB_TAR_LF_BLK }
1376 { Otherwise they are stuffed with #00 }
1377 FTarItem.DevMinor := Value;
1378 S := PadString(IntToOctal(Value), SizeOf(Arr8));
1379 Move(S[1], PTarHeader.DevMinor, Length(S));
1380 FTarItem.Dirty := True;
1381 end;
1382
1383 procedure TAbTarItem.SetExternalFileAttributes(Value: LongWord);
1384 var
1385 S : AnsiString;
1386 I: Integer;
1387 Permissions: LongWord;
1388 ALinkFlag: AnsiChar;
1389 begin
1390 if FTarItem.ItemReadOnly then { Read Only - Do Not Save }
1391 Exit;
1392
1393 UnixAttrsToTarAttrs(Value, Permissions, ALinkFlag);
1394
1395 FTarItem.Mode := Permissions;
1396 S := PadString(IntToOctal(Permissions), SizeOf(Arr8));
1397 for I := 0 to FTarHeaderList.Count - 1 do
1398 if TAbTarHeaderType(FTarHeaderTypeList.Items[I]) in [FILE_HEADER, META_DATA_HEADER] then
1399 Move(S[1], PAbTarHeaderRec(FTarHeaderList.Items[I]).Mode, Length(S));
1400
1401 Self.LinkFlag := ALinkFlag; // also updates headers
1402 FTarItem.Dirty := True;
1403 end;
1404
1405 { Add/Remove Headers as needed To/From Existing GNU Long (Link/Name) TarItems }
1406 procedure TAbTarItem.DoGNUExistingLongNameLink(LinkFlag: AnsiChar; I: Integer; const Value: AnsiString);
1407 var
1408 PHeader: PAbTarHeaderRec;
1409 J: Integer;
1410 OldNameLength: Integer;
1411 TotalOldNumHeaders: Integer;
1412 TotalNewNumHeaders: Integer;
1413 NumHeaders: Integer;
1414 ExtraName: Integer;
1415 tempStr: AnsiString;
1416 begin
1417 PHeader := FTarHeaderList.Items[I];
1418
1419 { Need this data from the old header }
1420 OldNameLength := OctalToInt(PHeader.Size, SizeOf(PHeader.Size));{ inlcudes Null termination }
1421 { Length(FTarItem.Name)+1 = OldNameLength; }{ This should be true, always }
1422
1423 { Save off the new Length, so we don't have to change the pointers later. }
1424 tempStr := PadString(IntToOctal(Length(Value)+1), SizeOf(PHeader.Size));
1425 Move(tempStr[1], PHeader.Size, Length(tempStr));
1426
1427 TotalOldNumHeaders := Ceil(OldNameLength / AB_TAR_RECORDSIZE);
1428 TotalNewNumHeaders := Ceil((Length(Value)+1) / AB_TAR_RECORDSIZE);{ Null terminated }
1429 {Length(Value)+1: 1-512 = 1, 513-1024 = 2 ... }
1430 J := TotalOldNumHeaders - TotalNewNumHeaders;
1431 while J <> 0 do
1432 begin
1433 if J > 0 then
1434 begin { Old > New, Have to many Headers, Remove }
1435 FreeMem(FTarHeaderList.Items[I+J]); { Free the Memory for the extra Header }
1436 FTarHeaderList.Delete(I+J); { Delete the List index }
1437 FTarHeaderTypeList.Delete(I+J);
1438 J := J - 1;
1439 end
1440 else { if J < 0 then }
1441 begin { Old < New, Need more Headers, Insert }
1442 GetMem(PHeader, AB_TAR_RECORDSIZE);
1443 FTarHeaderList.Insert(I+1,PHeader);{ Insert: Inserts at index }
1444 FTarHeaderTypeList.Insert(I+1,Pointer(MD_DATA_HEADER));{ We are only adding MD Data headers here }
1445 J := J + 1;
1446 end;
1447 end;{ end numHeaders while }
1448 { Yes, GNU Tar adds a Nil filled MD data header if Length(Value) mod AB_TAR_RECORDSIZE = 0 }
1449 NumHeaders := (Length(Value)+1) div AB_TAR_RECORDSIZE; { Include Null terminator }
1450 ExtraName := (Length(Value)+1) mod AB_TAR_RECORDSIZE; { Chars in the last Header }
1451 { Now we have the number of headers set up, stuff the name in the Headers }
1452 TempStr := AnsiString(Value);
1453 for J := 1 to NumHeaders do
1454 begin
1455 { Copy entire next AB_TAR_RECORDSIZE bytes of tempString to content of Header }
1456 { There may only be AB_TAR_RECORDSIZE-1 bytes if this is the last rounded header }
1457 PHeader := FTarHeaderList.Items[I+J];
1458 Move(TempStr[1], PHeader^, AB_TAR_RECORDSIZE);
1459 if Length(TempStr) >= AB_TAR_RECORDSIZE then
1460 Delete(TempStr, 1, AB_TAR_RECORDSIZE);{ Crop string }
1461 end;
1462 if ExtraName <> 0 then
1463 begin
1464 { Copy whatever is left in tempStr into the rest of the buffer }
1465 PHeader := FTarHeaderList.Items[I+NumHeaders+1];
1466 FillChar(PHeader^, AB_TAR_RECORDSIZE, #0); { Zero the whole block }
1467 Move(TempStr[1], PHeader^, ExtraName-1); { The string is null terminated }
1468 end
1469 else { We already copied the entire name, but it must be null terminated }
1470 begin
1471 FillChar(Pointer(PtrInt(PHeader)+AB_TAR_RECORDSIZE-1)^, 1, #0); { Zero rest of the block }
1472 end;
1473
1474 { Finally we need to stuff the file type Header. }
1475 { Note: Value.length > AB_TAR_NAMESIZE(100) }
1476 if LinkFlag = AB_TAR_LF_LONGNAME then
1477 Move(Value[1], PTarHeader.Name, AB_TAR_NAMESIZE)
1478 else
1479 Move(Value[1], PTarHeader.LinkName, AB_TAR_NAMESIZE);
1480 end;
1481
1482
1483 { Always inserts the L/K Headers at index 0+ }
1484 procedure TAbTarItem.DoGNUNewLongNameLink(LinkFlag: AnsiChar; I: Integer; const Value: AnsiString);
1485 var
1486 PHeader: PAbTarHeaderRec;
1487 J: Integer;
1488 NumHeaders: Integer;
1489 ExtraName: Integer;
1490 tempStr: AnsiString;
1491 begin
1492 { We have a GNU_FORMAT, and no L/K Headers.}
1493 { Add a new MD Header and MD Data Headers }
1494 { Make an L/K header }
1495 GetMem(PHeader, AB_TAR_RECORDSIZE);
1496 FTarHeaderList.Insert(I, PHeader);{ Insert: Inserts at base index }
1497 FTarHeaderTypeList.Insert(I, Pointer( META_DATA_HEADER));{ This is the L/K Header }
1498 FillChar(PHeader^, AB_TAR_RECORDSIZE, #0); { Zero the whole block }
1499 StrPCopy(PHeader.Name, AB_TAR_L_HDR_NAME); { Stuff L/K String Name }
1500 StrPCopy(PHeader.Mode, AB_TAR_L_HDR_ARR8_0); { Stuff zeros }
1501 StrPCopy(PHeader.uid, AB_TAR_L_HDR_ARR8_0); { Stuff zeros }
1502 StrPCopy(PHeader.gid, AB_TAR_L_HDR_ARR8_0); { Stuff zeros }
1503 tempStr := PadString(IntToOctal(Length(Value)+1), SizeOf(PHeader.Size)); { Stuff Size }
1504 Move(tempStr[1], PHeader.Size, Length(tempStr));
1505 StrPCopy(PHeader.ModTime, AB_TAR_L_HDR_ARR12_0); { Stuff zeros }
1506 { Check sum will be calculated as the Dirty flag is in caller. }
1507 PHeader.LinkFlag := LinkFlag; { Stuff Link FlagSize }
1508 StrPCopy(PHeader.Magic.gnuOld, AB_TAR_MAGIC_GNUOLD); { Stuff the magic }
1509 StrPCopy(PHeader.UsrName, AB_TAR_L_HDR_USR_NAME);
1510 StrPCopy(PHeader.GrpName, AB_TAR_L_HDR_GRP_NAME);
1511 { All else stays as Zeros. }
1512 { Completed with L/K Header }
1513
1514 { OK, now we need to add the proper number of MD Data Headers, and intialize to new name }
1515 { Yes, GNU Tar adds an extra Nil filled MD data header if Length(Value) mod AB_TAR_RECORDSIZE = 0 }
1516 NumHeaders := Ceil((Length(Value)+1) / AB_TAR_RECORDSIZE); { Include Null terminator }
1517 ExtraName := (Length(Value)+1) mod AB_TAR_RECORDSIZE; { Chars in the last Header }
1518 { Now we have the number of headers set up, stuff the name in the Headers }
1519 TempStr := AnsiString(Value);
1520 for J := 1 to NumHeaders-1 do
1521 begin
1522 { Make a buffer, and copy entire next AB_TAR_RECORDSIZE bytes of tempStr to content of Header }
1523 { There may only be AB_TAR_RECORDSIZE-1 bytes if this is the last rounded header }
1524 GetMem(PHeader, AB_TAR_RECORDSIZE);
1525 FTarHeaderList.Insert(J+I, PHeader);
1526 FTarHeaderTypeList.Insert(J+I, Pointer(MD_DATA_HEADER));{ We are adding MD Data headers here }
1527 Move(TempStr[1], PHeader^, AB_TAR_RECORDSIZE);
1528 if Length(TempStr) >= AB_TAR_RECORDSIZE then
1529 Delete(TempStr, 1, AB_TAR_RECORDSIZE);{ Crop string }
1530 end;
1531 if ExtraName <> 0 then
1532 begin
1533 { Copy what ever is left in tempStr into the rest of the buffer }
1534 { Create the last MD Data Header }
1535 GetMem(PHeader, AB_TAR_RECORDSIZE);
1536 FTarHeaderList.Insert(I+NumHeaders, PHeader);{ Insert: Inserts at base index }
1537 FTarHeaderTypeList.Insert(I+NumHeaders, Pointer(MD_DATA_HEADER));{ We are only adding MD Data headers here }
1538 FillChar(PHeader^, AB_TAR_RECORDSIZE, #0); { Zero the whole block }
1539 Move(TempStr[1], PHeader^, ExtraName-1); { The string is null terminated in the header }
1540 end
1541 else { We already copied the entire name, but it must be null terminated }
1542 begin
1543 FillChar(Pointer(PtrInt(PHeader)+AB_TAR_RECORDSIZE-1)^, 1, #0); { Zero rest of the block }
1544 end;
1545
1546 { Finally we need to stuff the file type Header. }
1547 { Note: Value.length > AB_TAR_NAMESIZE(100) }
1548 if LinkFlag = AB_TAR_LF_LONGNAME then
1549 Move(Value[1], PTarHeader.Name, AB_TAR_NAMESIZE)
1550 else
1551 Move(Value[1], PTarHeader.LinkName, AB_TAR_NAMESIZE);
1552 end;
1553
1554 procedure TAbTarItem.SetFileName(const Value: string);
1555 var
1556 FoundMetaDataHeader: Boolean;
1557 PHeader: PAbTarHeaderRec;
1558 I, J: Integer;
1559 TotalOldNumHeaders: Integer;
1560 RawFileName: AnsiString;
1561 begin
1562 if FTarItem.ItemReadOnly then { Read Only - Do Not Save }
1563 Exit;
1564 { Assume ItemReadOnly is set for all Unsupported Type. }
1565
1566 { Cases:
1567 New File Name is short, Length <= 100,
1568 All formats: Zero Name field and move new name to field.
1569 V7: Work complete, 1 header
1570 USTAR: zero prefix field, 1 Header
1571 OLD_GNU & GNU: Remove old name headers, 1 header.
1572 STAR & PAX: And should not yet get here.
1573 New File Name is Long, Length >=101
1574 Note: The Header Parsing sets any V7 to GNU if 'L'/'K" Headers are present
1575 V7: Raise an exception, as this can NOT be done, no change to header.
1576 USTAR: if new length <= 254 zero fill header, update name fields, 1 updated Header
1577 if new Length >= 255 raise an exception, as this can NOT be done, no change to header
1578 if old was Short, Add files to match format,
1579 OLD_GNU & GNU: Create new Name header, Add N Headers for name, Update name in file header, update name fields, min 3 headers
1580 STAR & PAX: And should not yet get here.
1581 if old was Long,
1582 OLD_GNU & GNU: Add N Headers for name, Update name in MD header, update name field in File Headers, min 3 headers
1583
1584 Add headers to length of new Name Length, update name in file header, update name fields }
1585 RawFileName := CeUtf8ToSys(Value);
1586 { In all cases zero out the name fields in the File Header. }
1587 if Length(RawFileName) > AB_TAR_NAMESIZE then begin { Must be null terminated except at 100 char length }
1588 { Look for long name meta-data headers already in the archive. }
1589 FoundMetaDataHeader := False;
1590 I := 0;
1591 { FTarHeaderList.Count <= 1 always }
1592 while (not FoundMetaDataHeader) and (I <= (FTarHeaderList.Count - 1)) do begin
1593 PHeader := FTarHeaderList.Items[I];
1594 if PHeader.LinkFlag = AB_TAR_LF_LONGNAME then begin
1595 { We are growing or Shriking the Name MD Data fields. }
1596 FoundMetaDataHeader := True;
1597 DoGNUExistingLongNameLink(AB_TAR_LF_LONGNAME, I, RawFileName);
1598 { Need to copy the Name to the header. }
1599 FTarItem.Name := Value;
1600 end
1601 else
1602 I := I + 1;
1603 end; { End While }
1604 { MD Headers & MD Data Headers have been stuffed if FoundMetaDataHeader }
1605 { Still need to stuff the File type header contents. }
1606 if not FoundMetaDataHeader then
1607 begin
1608 case FTarItem.ArchiveFormat of
1609 V7_FORMAT: raise EAbTarBadFileName.Create; { File Name to Long }
1610 USTAR_FORMAT:
1611 begin
1612 { Longest file name is AB_TAR_NAMESIZE(100) chars }
1613 { Longest Prefix is AB_TAR_USTAR_PREFIX_SIZE(155) chars }
1614 { These two fields are delimted by a '/' char }
1615 {0123456789012345, Length = 15, NameLength = 5, PrefixLength = 9}
1616 { AAAA/BBBB/C.txt, Stored as Name := 'C.txt', Prefix := 'AAAA/BBBB' }
1617 { That means Theoretical maximum is 256 for Length(RawFileName) }
1618 if Length(RawFileName) > (AB_TAR_NAMESIZE+AB_TAR_USTAR_PREFIX_SIZE+1) then { Check the obvious one. }
1619 raise EAbTarBadFileName.Create; { File Name to Long }
1620 for I := Length(RawFileName) downto Length(RawFileName)-AB_TAR_NAMESIZE-1 do begin
1621 if RawFileName[I] = '/' then begin
1622 if (I <= AB_TAR_USTAR_PREFIX_SIZE+1) and (Length(RawFileName)-I <= AB_TAR_NAMESIZE) then begin
1623 { We have a successfull parse. }
1624 FillChar(PTarHeader.Name, SizeOf(PTarHeader.Name), #0);
1625 FillChar(PTarHeader.ustar.Prefix, SizeOf(PTarHeader.ustar.Prefix), #0);
1626 Move(RawFileName[I+1], PTarHeader.Name, Length(RawFileName)-I);
1627 Move(RawFileName[1], PTarHeader.ustar.Prefix, I);
1628 break;
1629 end
1630 else if (Length(RawFileName)-I > AB_TAR_NAMESIZE) then
1631 raise EAbTarBadFileName.Create { File Name not splittable }
1632 { else continue; }
1633 end;
1634 end;{ End for I... }
1635 end; { End USTAR Format }
1636 OLDGNU_FORMAT: DoGNUNewLongNameLink(AB_TAR_LF_LONGNAME, 0, RawFileName); {GNU_FORMAT}
1637 else begin
1638 { UNKNOWN_FORMAT, STAR_FORMAT, POSIX_FORMAT }
1639 raise EAbTarBadOp.Create; { Unknown Archive Format }
1640 end;{ End of Else for case statement }
1641 end;{ End of case statement }
1642 FTarItem.Name := Value;
1643 end; { if no Meta data header found }
1644 end { End "name length larger than 100" }
1645 else
1646 begin { Short new name, Simple Case Just put it in the Name Field & remove any headers }
1647 { PTarHeader Points to the File type Header }
1648 { Zero the Name field }
1649 FillChar(PTarHeader.Name, SizeOf(PTarHeader.Name), #0);
1650 if FTarItem.ArchiveFormat in [USTAR_FORMAT] then { Zero the prefix field }
1651 FillChar(PTarHeader.ustar.Prefix, SizeOf(PTarHeader.ustar.Prefix), #0);
1652 if FTarItem.ArchiveFormat in [GNU_FORMAT, OLDGNU_FORMAT] then
1653 begin { We may have AB_TAR_LF_LONGNAME Headers to be removed }
1654 { Remove long file names Headers if they exist}
1655 FoundMetaDataHeader := False;
1656 I := 0;
1657 while not FoundMetaDataHeader and (I <= (FTarHeaderList.Count - 1)) do
1658 begin
1659 PHeader := FTarHeaderList.Items[I];
1660 if PHeader.LinkFlag in [AB_TAR_LF_LONGNAME] then
1661 begin { Delete this Header, and the data Headers. }
1662 FoundMetaDataHeader := True;
1663 TotalOldNumHeaders := Ceil( OctalToInt(PHeader.Size, SizeOf(PHeader.Size)) / AB_TAR_RECORDSIZE);
1664 for J := TotalOldNumHeaders downto 0 do
1665 begin { Note 0 will delete the Long Link MD Header }
1666 FreeMem(FTarHeaderList.Items[I+J]); { This list holds PAbTarHeaderRec's }
1667 FTarHeaderList.Delete(I+J);
1668 FTarHeaderTypeList.Delete(I+J);
1669 end;
1670 end
1671 else
1672 I := I + 1; { Got to next header }
1673 end;{ End While not found... }
1674 end; { End if GNU... }
1675 { Save off the new name and store to the Header }
1676 FTarItem.Name := Value;
1677 { Must add Null Termination before we store to Header }
1678 StrPLCopy(PTarHeader.Name, RawFileName, AB_TAR_NAMESIZE);
1679 end;{ End else Short new name,... }
1680
1681 { Update the inherited file names. }
1682 FFileName := FTarItem.Name;
1683 //DiskFileName := FFileName;
1684 //AbUnfixName(FDiskFileName); // Don't override DiskFileName
1685 FTarItem.Dirty := True;
1686 end;
1687
1688 procedure TAbTarItem.SetGroupID(const Value: Integer);
1689 var
1690 S : AnsiString;
1691 begin
1692 if FTarItem.ItemReadOnly then { Read Only - Do Not Save }
1693 Exit;
1694 { gid is extendable in PAX Headers, Rember PAX extended Header Over Rule File Headers }
1695 FTarItem.gid := Value;
1696 S := PadString(IntToOctal(Value), SizeOf(Arr8));
1697 Move(S[1], PTarHeader.gid, Length(S));
1698 FTarItem.Dirty := True;
1699 end;
1700
1701 procedure TAbTarItem.SetGroupName(const Value: string);
1702 begin
1703 if FTarItem.ItemReadOnly then { Read Only - Do Not Save }
1704 Exit;
1705 { GrpName is extendable in PAX Headers, Rember PAX extended Header Over Rule File Headers }
1706 FTarItem.GrpName := Value;
1707 StrPLCopy(PTarHeader.GrpName, AnsiString(Value), SizeOf(PTarHeader.GrpName));
1708 FTarItem.Dirty := True;
1709 end;
1710
1711 procedure TAbTarItem.SetIsEncrypted(Value: Boolean);
1712 begin
1713 { do nothing, TAR has no native encryption }
1714 end;
1715
1716 procedure TAbTarItem.SetLastModFileDate(const Value: Word);
1717 begin
1718 { replace date, keep existing time }
1719 LastModTimeAsDateTime :=
1720 EncodeDate(
1721 Value shr 9 + 1980,
1722 Value shr 5 and 15,
1723 Value and 31) +
1724 Frac(LastModTimeAsDateTime);
1725 end;
1726
1727 procedure TAbTarItem.SetLastModFileTime(const Value: Word);
1728 begin
1729 { keep current date, replace time }
1730 LastModTimeAsDateTime :=
1731 Trunc(LastModTimeAsDateTime) +
1732 EncodeTime(
1733 Value shr 11,
1734 Value shr 5 and 63,
1735 Value and 31 shl 1, 0);
1736 end;
1737
1738 procedure TAbTarItem.SetLastModTimeAsDateTime(const Value: TDateTime);
1739 begin
1740 // TAR stores always Unix time.
1741 SetModTime(AbLocalDateTimeToUnixTime(Value)); // also updates headers
1742 end;
1743
1744 procedure TAbTarItem.SetLinkFlag(Value: AnsiChar);
1745 begin
1746 if FTarItem.ItemReadOnly then
1747 Exit;
1748 FTarItem.LinkFlag := Value;
1749 PTarHeader.LinkFlag := Value;
1750 FTarItem.Dirty := True;
1751 end;
1752
1753 procedure TAbTarItem.SetLinkName(const Value: string);
1754 var
1755 FoundMetaDataHeader: Boolean;
1756 PHeader: PAbTarHeaderRec;
1757 I, J: Integer;
1758 TotalOldNumHeaders: Integer;
1759 RawLinkName: AnsiString;
1760 begin
1761 if FTarItem.ItemReadOnly then { Read Only - Do Not Save }
1762 Exit;
1763 { Cases:
1764 New Link Name is short, Length <= 100,
1765 All formats: Zero Name field and move new name to field.
1766 V7: Work complete, 1 header
1767 USTAR: Work complete, 1 Header
1768 OLD_GNU & GNU: Remove old link headers, 1 header.
1769 STAR & PAX: And should not yet get here.
1770 New File Name is Long, Length >=101
1771 Note: The Header Parsing sets any V7 to GNU if 'L'/'K' Headers are present
1772 V7: Raise an exception, as this can NOT be done, no change to header.
1773 USTAR: Raise an exception, as this can NOT be done, no change to header.
1774 if old was Short, Add files to match format,
1775 OLD_GNU & GNU: Create new Link header, Add N Headers for name, Update name in file header, update name fields, min 3 headers
1776 if old was Long,
1777 OLD_GNU & GNU: Add N Headers for name, Update name in MD header, update name field in File Headers, min 3 headers
1778 STAR & PAX: And should not yet get here.}
1779 RawLinkName := CeUtf8ToSys(Value);
1780 if Length(RawLinkName) > AB_TAR_NAMESIZE then { Must be null terminated except at 100 char length }
1781 begin
1782 { Look for long name meta-data headers already in the archive. }
1783 FoundMetaDataHeader := False;
1784 I := 0;
1785 { FTarHeaderList.Count <= 1 always }
1786 while (not FoundMetaDataHeader) and (I <= (FTarHeaderList.Count - 1)) do begin
1787 PHeader := FTarHeaderList.Items[I];
1788 if PHeader.LinkFlag = AB_TAR_LF_LONGLINK then
1789 begin { We are growing or Shriking the Name MD Data fields. }
1790 FoundMetaDataHeader := True;
1791 DoGNUExistingLongNameLink(AB_TAR_LF_LONGLINK, I, RawLinkName);
1792 { Need to copy the Name to the header. }
1793 FTarItem.LinkName := Value;
1794 end
1795 else
1796 I := I + 1;
1797 end; { End While }
1798 { MD Headers & MD Data Headers have been stuffed if FoundMetaDataHeader }
1799 { Still need to stuff the File type header contents. }
1800 if not FoundMetaDataHeader then
1801 begin
1802 case FTarItem.ArchiveFormat of
1803 V7_FORMAT: raise EAbTarBadLinkName.Create; { Link Name to Long }
1804 USTAR_FORMAT: raise EAbTarBadLinkName.Create; { Link Name to Long }
1805 OLDGNU_FORMAT: DoGNUNewLongNameLink(AB_TAR_LF_LONGLINK, 0, RawLinkName); {GNU_FORMAT}
1806 else
1807 begin
1808 { UNKNOWN_FORMAT, STAR_FORMAT, POSIX_FORMAT }
1809 raise EAbTarBadOp.Create; { Unknown Archive Format }
1810 end;{ End of Else for case statement }
1811 end;{ End of case statement }
1812 FTarItem.LinkName := Value;
1813 end; { if no Meta data header found }
1814 end { End "name length larger than 100" }
1815 else
1816 begin { Short new name, Simple Case Just put it in the Link Field & remove any headers }
1817 { PTarHeader Points to the File type Header }
1818 { Zero the Link field }
1819 FillChar(PTarHeader.LinkName, SizeOf(PTarHeader.LinkName), #0);
1820 if FTarItem.ArchiveFormat in [GNU_FORMAT, OLDGNU_FORMAT] then
1821 begin { We may have AB_TAR_LF_LONGNAME Headers to be removed }
1822 { Remove long file names Headers if they exist}
1823 FoundMetaDataHeader := False;
1824 I := 0;
1825 while not FoundMetaDataHeader and (I <= (FTarHeaderList.Count - 1)) do
1826 begin
1827 PHeader := FTarHeaderList.Items[I];
1828 if PHeader.LinkFlag in [AB_TAR_LF_LONGLINK] then
1829 begin { Delete this Header, and the data Headers. }
1830 FoundMetaDataHeader := True;
1831 TotalOldNumHeaders := Ceil( OctalToInt(PHeader.Size, SizeOf(PHeader.Size)) / AB_TAR_RECORDSIZE);
1832 for J := TotalOldNumHeaders downto 0 do
1833 begin { Note 0 will delete the Long Link MD Header }
1834 FreeMem(FTarHeaderList.Items[I+J]); { This list holds PAbTarHeaderRec's }
1835 FTarHeaderList.Delete(I+J);
1836 FTarHeaderTypeList.Delete(I+J);
1837 end;
1838 end
1839 else
1840 I := I + 1; { Got to next header }
1841 end;{ End While not found... }
1842 end; { End if GNU... }
1843 { Save off the new name and store to the Header }
1844 FTarItem.LinkName := Value;
1845 StrPLCopy(PTarHeader.LinkName, RawLinkName, AB_TAR_NAMESIZE);
1846 end;{ End else Short new name,... }
1847 FTarItem.Dirty := True;
1848 end;
1849
1850 procedure TAbTarItem.SetMagic(const Value: String);
1851 begin
1852 if FTarItem.ItemReadOnly then { Read Only - Do Not Save }
1853 Exit;
1854 FTarItem.Magic := AnsiString(Value);
1855 Move(Value[1], PTarHeader.Magic, SizeOf(TAbTarMagicRec));
1856 FTarItem.Dirty := True;
1857 end;
1858
1859 procedure TAbTarItem.SetUncompressedSize(const Value: Int64);
1860 var
1861 S : AnsiString;
1862 begin
1863 if FTarItem.ItemReadOnly then { Read Only - Do Not Save }
1864 Exit;
1865 { Size is extendable in PAX Headers, Remember PAX extended Header Over Rule File Headers }
1866 FTarItem.Size := Value; { Store our Vitrual Copy }
1867 S := PadString(IntToOctal(Value), SizeOf(Arr12));{ Stuff to header }
1868 Move(S[1], PTarHeader.Size, Length(S));
1869 FTarItem.Dirty := True;
1870 end;
1871
1872 procedure TAbTarItem.SetUserID(const Value: Integer);
1873 var
1874 S : AnsiString;
1875 begin
1876 if FTarItem.ItemReadOnly then { Read Only - Do Not Save }
1877 Exit;
1878 { uid is extendable in PAX Headers, Remember PAX extended Header Over Rule File Headers }
1879 FTarItem.uid := Value;
1880 S := PadString(IntToOctal(Value), SizeOf(Arr8));
1881 Move(S[1], PTarHeader.uid, Length(S));
1882 FTarItem.Dirty := True;
1883 end;
1884
1885 procedure TAbTarItem.SetUserName(const Value: string);
1886 begin
1887 if FTarItem.ItemReadOnly then { Read Only - Do Not Save }
1888 Exit;
1889 { UsrName is extendable in PAX Headers, Remember PAX extended Header Over Rule File Headers }
1890 FTarItem.UsrName := Value;
1891 StrPLCopy(PTarHeader.UsrName, AnsiString(Value), SizeOf(PTarHeader.UsrName));
1892 FTarItem.Dirty := True;
1893 end;
1894
1895 procedure TAbTarItem.SetModTime(const Value: Int64);
1896 var
1897 S: AnsiString;
1898 begin
1899 if FTarItem.ItemReadOnly then { Read Only - Do Not Save }
1900 Exit;
1901 { ModTime is extendable in PAX Headers, Remember PAX extended Header Over Rule File Headers }
1902 FTarItem.ModTime := Value; { Store our Virtual Copy }
1903 S := PadString(IntToOctal(Value), SizeOf(Arr12));{ Stuff to header }
1904 Move(S[1], PTarHeader.ModTime, Length(S));
1905 FTarItem.Dirty := True;
1906 end;
1907
1908
1909 { ************************** TAbTarStreamHelper ****************************** }
1910 destructor TAbTarStreamHelper.Destroy;
1911 begin
1912 inherited Destroy;
1913 end;
1914
1915 { This is slow, use the archive class instead }
1916 procedure TAbTarStreamHelper.ExtractItemData(AStream: TStream);
1917 begin
1918 { Note: The SizeOf(TAbTarHeaderRec) = AB_TAR_RECORDSIZE }
1919 if FCurrItemSize <> 0 then
1920 begin
1921 { copy stored data to output }
1922 AStream.CopyFrom(FStream, FCurrItemSize);
1923 {reset the stream to the start of the item}
1924 FStream.Seek(-(FCurrItemPreHdrs*AB_TAR_RECORDSIZE+FCurrItemSize), soCurrent);
1925 end;
1926 { else do nothing }
1927 end;
1928
1929 { This function Should only be used from LoadArchive, as it is slow. }
1930 function TAbTarStreamHelper.FindItem: Boolean;
1931 var
1932 DataRead : LongInt;
1933 FoundItem: Boolean;
1934 SkipHdrs : Integer;
1935 begin
1936 { Note: The SizeOf(TAbTarHeaderRec) = AB_TAR_RECORDSIZE }
1937 { Note: Standard LBA size of hard disks is 512 bytes = AB_TAR_RECORDSIZE }
1938 FoundItem := False;
1939 { Getting an new Item reset these numbers }
1940 FCurrItemSize := 0;
1941 FCurrItemPreHdrs := 0;
1942 DataRead := FStream.Read(FTarHeader, AB_TAR_RECORDSIZE); { Read in a header }
1943 { DataRead <> AB_TAR_RECORDSIZE means end of stream, and the End Of Archive
1944 record is all #0's, which the StrLen(FTarHeader.Name) check will catch }
1945 while (DataRead = AB_TAR_RECORDSIZE) and (StrLen(FTarHeader.Name) > 0) and not FoundItem do
1946 begin { Either exit when we find a supported file or end of file or an invalid header name. }
1947 if FTarHeader.LinkFlag in (AB_SUPPORTED_MD_HEADERS+AB_UNSUPPORTED_MD_HEADERS) then
1948 begin { We have a un/supported Meta-Data Header }
1949 { FoundItem := False } { Value remains False. }
1950 SkipHdrs := Ceil(OctalToInt(FTarHeader.Size, SizeOf(FTarHeader.Size))/AB_TAR_RECORDSIZE);
1951 FStream.Seek(SkipHdrs*AB_TAR_RECORDSIZE, soCurrent);
1952 { Tally new Headers: Consumed + Current }
1953 FCurrItemPreHdrs := FCurrItemPreHdrs + SkipHdrs + 1;
1954 { Read our next header, Loop, and re-parse }
1955 DataRead := FStream.Read(FTarHeader, AB_TAR_RECORDSIZE);
1956 end
1957 else if FTarHeader.LinkFlag in (AB_SUPPORTED_F_HEADERS+AB_UNSUPPORTED_F_HEADERS) then
1958 begin { We have a un/supported File Header. }
1959 FoundItem := True;
1960 if not (FTarHeader.LinkFlag in AB_IGNORE_SIZE_HEADERS) then
1961 FCurrItemSize := OctalToInt(FTarHeader.Size, SizeOf(FTarHeader.Size))
1962 else FCurrItemSize := 0; { Per The spec these Headers do not have file content }
1963 FCurrItemPreHdrs := FCurrItemPreHdrs + 1; { Tally current header }
1964 end
1965 else
1966 begin{ We Have an Unknown header }
1967 FoundItem := True;
1968 FCurrItemSize := 0;
1969 { We could have many un/supported headers before this unknown type }
1970 FCurrItemPreHdrs := FCurrItemPreHdrs + 1; { Tally current header }
1971 { These Headers should throw exceptions when TAbTarItem.LoadTarHeaderFromStream is called }
1972 end; { End of Link Flag parsing }
1973 end;
1974 { Rewind to the "The Beginning" of this Item }
1975 { Really that means to the first supported Header Type before a supported Item Type }
1976 if FoundItem then
1977 FStream.Seek(-(FCurrItemPreHdrs*AB_TAR_RECORDSIZE), soCurrent);
1978 Result := FoundItem;
1979 end;
1980
1981 constructor TAbTarStreamHelper.Create(AStream: TStream; AEvent: TAbProgressEvent);
1982 begin
1983 Create(AStream);
1984 FOnProgress:= AEvent;
1985 end;
1986
1987 { Should only be used from LoadArchive, as it is slow. }
1988 function TAbTarStreamHelper.FindFirstItem: Boolean;
1989 begin
1990 FStream.Seek(0, soBeginning);
1991 Result := FindItem;
1992 end;
1993
1994 { Should only be used from LoadArchive, as it is slow. }
1995 function TAbTarStreamHelper.FindNextItem: Boolean;
1996 begin
1997 { Fast Forward Past the current Item }
1998 FStream.Seek((FCurrItemPreHdrs*AB_TAR_RECORDSIZE + RoundToTarBlock(FCurrItemSize)), soCurrent);
1999 Result := FindItem;
2000 end;
2001
2002 { This is slow, use the archive class instead }
2003 function TAbTarStreamHelper.GetItemCount : Integer;
2004 var
2005 Found : Boolean;
2006 begin
2007 Result := 0;
2008 Found := FindFirstItem;
2009 while Found do begin
2010 Inc(Result);
2011 Found := FindNextItem;
2012 end;
2013 end;
2014
2015 procedure TAbTarStreamHelper.ReadHeader;
2016 begin
2017 { do nothing }
2018 { Tar archives have no overall header data }
2019 end;
2020
2021 procedure TAbTarStreamHelper.ReadTail;
2022 begin
2023 { do nothing }
2024 { Tar archives have no overall tail data }
2025 end;
2026
2027 { This is slow, use the archive class instead }
2028 function TAbTarStreamHelper.SeekItem(Index: Integer): Boolean;
2029 var
2030 i : Integer;
2031 begin
2032 Result := FindFirstItem; { see if can get to first item }
2033 i := 1;
2034 while Result and (i < Index) do begin
2035 Result := FindNextItem;
2036 Inc(i);
2037 end;
2038 end;
2039
2040 procedure TAbTarStreamHelper.WriteArchiveHeader;
2041 begin
2042 { do nothing }
2043 { Tar archives have no overall header data }
2044 end;
2045
2046 procedure TAbTarStreamHelper.WriteArchiveItem(AStream: TStream);
2047 begin
2048 WriteArchiveItemSize(AStream, AStream.Size);
2049 end;
2050
2051 procedure TAbTarStreamHelper.WriteArchiveItemSize(AStream: TStream; ASize: Int64);
2052 var
2053 PadBuff : PAnsiChar;
2054 PadSize : Integer;
2055 begin
2056 if ASize = 0 then
2057 Exit;
2058 { transfer actual item data }
2059
2060 with TAbProgressWriteStream.Create(FStream, ASize, FOnProgress) do
2061 try
2062 CopyFrom(AStream, ASize);
2063 finally
2064 Free;
2065 end;
2066
2067 { Pad to Next block }
2068 PadSize := RoundToTarBlock(ASize) - ASize;
2069 GetMem(PadBuff, PadSize);
2070 FillChar(PadBuff^, PadSize, #0);
2071 FStream.Write(PadBuff^, PadSize);
2072 FreeMem(PadBuff, PadSize);
2073 end;
2074
2075
2076 procedure TAbTarStreamHelper.WriteArchiveTail;
2077 var
2078 PadBuff : PAnsiChar;
2079 PadSize : Integer;
2080 begin
2081 { append 2 terminating null blocks }
2082 PadSize := AB_TAR_RECORDSIZE;
2083 GetMem(PadBuff, PadSize);
2084 try
2085 FillChar(PadBuff^, PadSize, #0);
2086 FStream.Write(PadBuff^, PadSize);
2087 FStream.Write(PadBuff^, PadSize);
2088 finally
2089 FreeMem(PadBuff, PadSize);
2090 end;
2091 end;
2092
2093
2094
2095 { ***************************** TAbTarArchive ******************************** }
2096 constructor TAbTarArchive.CreateFromStream(aStream : TStream; const aArchiveName : string);
2097 begin
2098 inherited;
2099 FArchFormat := OLDGNU_FORMAT; // Default for new archives
2100 FSuspiciousLinks := TStringList.Create;
2101 end;
2102
2103 destructor TAbTarArchive.Destroy;
2104 begin
2105 inherited Destroy;
2106 FSuspiciousLinks.Free;
2107 end;
2108
2109 function TAbTarArchive.CreateItem(const SourceFileName : string;
2110 const ArchiveDirectory : string): TAbArchiveItem;
2111 var
2112 Item : TAbTarItem;
2113 I: Integer;
2114 FullSourceFileName, FullArchiveFileName: String;
2115 begin
2116 if FArchReadOnly then
2117 raise EAbTarBadOp.Create; { Create Item Unsupported in this Archive }
2118
2119 MakeFullNames(SourceFileName, ArchiveDirectory,
2120 FullSourceFileName, FullArchiveFileName);
2121
2122 Item := TAbTarItem.Create;
2123 try
2124 // HeaderFormat = (UNKNOWN_FORMAT, V7_FORMAT, OLDGNU_FORMAT, GNU_FORMAT, USTAR_FORMAT, STAR_FORMAT, POSIX_FORMAT);
2125 if FArchFormat in [OLDGNU_FORMAT, GNU_FORMAT] then
2126 begin
2127 Item.ArchiveFormat := FArchFormat;
2128 Item.LinkFlag := AB_TAR_LF_NORMAL;
2129 Item.Magic := AB_TAR_MAGIC_GNUOLD;
2130 end
2131 else if FArchFormat in [USTAR_FORMAT] then
2132 begin
2133 Item.ArchiveFormat := USTAR_FORMAT;
2134 Item.LinkFlag := AB_TAR_LF_NORMAL;
2135 Item.Magic := AB_TAR_MAGIC_VAL+AB_TAR_MAGIC_VER;
2136 end
2137 else if (FArchFormat = V7_FORMAT) and (Length(FullArchiveFileName) > 100) then
2138 begin { Switch the rep over to GNU so it can have long file names. }
2139 FArchFormat := OLDGNU_FORMAT;
2140 Item.ArchiveFormat := OLDGNU_FORMAT;
2141 { Leave the Defaults for LinkFlag, and Magic }
2142 { Update all the rest so that it can transistion to GNU_FORMAT }
2143 for I := 0 to FItemList.Count - 1 do
2144 TAbTarItem(FItemList.Items[i]).ArchiveFormat := OLDGNU_FORMAT;
2145 end;{ This should not execute... }{
2146 else if FArchFormat in [STAR_FORMAT, POSIX_FORMAT] then
2147 begin
2148 Item.ArchiveFormat := FArchFormat;
2149 Item.LinkFlag := AB_TAR_LF_NORMAL;
2150 Item.Magic := AB_TAR_MAGIC_VAL+AB_TAR_MAGIC_VER;
2151 end;
2152 }{ else FArchFormat in [ UNKNOWN_FORMAT, V7_FORMAT and Length(S) <= 100 ] } { This is the default. }
2153
2154 { Most others are initialized in the .Create }
2155 Item.CRC32 := 0;
2156
2157 { Note this can raise exceptions for file name lengths. }
2158 Item.FileName := FullArchiveFileName;
2159 Item.DiskFileName := FullSourceFileName;
2160 Item.Action := aaNone;
2161 finally
2162 Result := Item;
2163 end;
2164 end;
2165
2166
2167 procedure TAbTarArchive.ExtractItemAt(Index: Integer; const UseName: string);
2168 var
2169 AFileName : String;
2170 LinkTarget : String;
2171 OutStream : TStream;
2172 PathType : TPathType;
2173 CurItem : TAbTarItem;
2174 begin
2175 { Check the index is not out of range. }
2176 if(Index >= ItemList.Count) then
2177 raise EListError.CreateFmt(SListIndexError, [Index]);
2178
2179 CurItem := TAbTarItem(ItemList[Index]);
2180
2181 if CurItem.ItemType in [UNKNOWN_ITEM] then
2182 raise EAbTarBadOp.Create; { Unsupported Type, Cannot Extract }
2183
2184 { Link to previously archived file }
2185 if CurItem.LinkFlag in [AB_TAR_LF_LINK] then
2186 begin
2187 { Find link target }
2188 AFileName := NormalizePathDelimiters(CurItem.FileName);
2189 { If link target exists then try to create hard link }
2190 if StrEnds(UseName, AFileName) then
2191 begin
2192 AFileName := StringReplace(UseName, AFileName, CurItem.LinkName, []);
2193 if mbFileExists(AFileName) and CreateHardLink(AFileName, UseName) then
2194 Exit;
2195 end;
2196 { Cannot create hard link, extract previously archived file }
2197 Index := ItemList.Find(CurItem.LinkName);
2198 if (Index >= 0) and (Index < ItemList.Count) then
2199 CurItem := TAbTarItem(ItemList[Index])
2200 else
2201 raise EAbTarBadOp.Create; { Unsupported Type, Cannot Extract }
2202 end;
2203
2204 if CurItem.IsDirectory then
2205 AbCreateDirectory(UseName)
2206 else begin
2207 case (CurItem.Mode and $F000) of
2208 AB_FMODE_FILE, AB_FMODE_FILE2:
2209 begin
2210 VerifyItem(CurItem);
2211 OutStream := TFileStreamEx.Create(UseName, fmCreate or fmShareDenyNone);
2212 try
2213 try {OutStream}
2214 ExtractItemToStreamAt(Index, OutStream);
2215 finally {OutStream}
2216 OutStream.Free;
2217 end; {OutStream}
2218 except
2219 if ExceptObject is EAbUserAbort then
2220 FStatus := asInvalid;
2221 mbDeleteFile(UseName);
2222 raise;
2223 end;
2224 end;
2225
2226 AB_FMODE_FILELINK:
2227 begin
2228 LinkTarget := NormalizePathDelimiters(CurItem.LinkName);
2229
2230 PathType := GetPathType(LinkTarget);
2231 if PathType in [ptRelative, ptAbsolute] then
2232 begin
2233 if PathType = ptAbsolute then
2234 AFileName := LinkTarget
2235 else begin
2236 AFileName := GetAbsoluteFileName(ExtractFilePath(UseName), LinkTarget);
2237 end;
2238 if not IsInPath(BaseDirectory, AFileName, True, True) then
2239 FSuspiciousLinks.Add(NormalizePathDelimiters(CurItem.FileName));
2240 end;
2241
2242 if not CreateSymLink(LinkTarget, UseName) then
2243 raise EOSError.Create(mbSysErrorMessage(GetLastOSError));
2244 end;
2245 end;
2246 end;
2247 if (CurItem.Mode and $F000) <> AB_FMODE_FILELINK then
2248 begin
2249 AbSetFileTime(UseName, CurItem.LastModTimeAsDateTime);
2250 AbSetFileAttr(UseName, CurItem.NativeFileAttributes);
2251 end;
2252 end;
2253
2254 procedure TAbTarArchive.ExtractItemToStreamAt(Index: Integer;
2255 aStream: TStream);
2256 var
2257 CurItem : TAbTarItem;
2258 begin
2259 if(Index >= ItemList.Count) then
2260 raise EListError.CreateFmt(SListIndexError, [Index]);
2261
2262 CurItem := TAbTarItem(ItemList[Index]);
2263
2264 if CurItem.ItemType in [UNKNOWN_ITEM] then
2265 raise EAbTarBadOp.Create; { Unsupported Type, Cannot Extract }
2266
2267 FStream.Position := CurItem.StreamPosition+CurItem.FileHeaderCount*AB_TAR_RECORDSIZE;
2268 if CurItem.UncompressedSize <> 0 then
2269 aStream.CopyFrom(FStream, CurItem.UncompressedSize);
2270 { Else there is nothing to copy. }
2271 end;
2272
2273 procedure TAbTarArchive.LoadArchive;
2274 var
2275 TarHelp : TAbTarStreamHelper;
2276 Item : TAbTarItem;
2277 ItemFound : Boolean;
2278 Abort : Boolean;
2279 Confirm : Boolean;
2280 Duplicate : Boolean;
2281 i : Integer;
2282 Progress : Byte;
2283 begin
2284 { create helper }
2285 TarHelp := TAbTarStreamHelper.Create(FStream);
2286 try {TarHelp}
2287 {build Items list from tar header records}
2288
2289 { reset Tar }
2290 Duplicate := False;
2291 ItemFound := (FStream.Size > 0) and TarHelp.FindFirstItem;
2292 if ItemFound then FArchFormat := UNKNOWN_FORMAT
2293 else FArchFormat := V7_FORMAT;
2294
2295 { while more data in Tar }
2296 while (FStream.Position < FStream.Size) and ItemFound do begin
2297 {create new Item}
2298 Item := TAbTarItem.Create;
2299 Item.FTarItem.StreamPosition := FStream.Position;
2300 try {Item}
2301 Item.LoadTarHeaderFromStream(FStream);
2302 if Item.ItemReadOnly then
2303 FArchReadOnly := True; { Set Archive as Read Only }
2304 if Item.ItemType in [SUPPORTED_ITEM, UNSUPPORTED_ITEM] then begin
2305 { List of supported Item/File Types. }
2306 { Add the New Supported Item to the List }
2307 if FArchFormat < Item.ArchiveFormat then
2308 FArchFormat := Item.ArchiveFormat; { Take the max format }
2309 Item.Action := aaNone;
2310 {
2311 TAR archive can contain the same directory multiple
2312 times. In this case, use the last found directory.
2313 }
2314 if Item.IsDirectory then
2315 begin
2316 I := FItemList.Find(Item.FileName);
2317 if (I >= 0) then
2318 begin
2319 Duplicate := True;
2320 FItemList.Items[I] := Item;
2321 end;
2322 end;
2323 if Duplicate then
2324 Duplicate := False
2325 else begin
2326 FItemList.Add(Item);
2327 end;
2328 end { end if }
2329 else begin
2330 { unhandled Tar file system entity, notify user, but otherwise ignore }
2331 if Assigned(FOnConfirmProcessItem) then
2332 FOnConfirmProcessItem(self, Item, ptFoundUnhandled, Confirm);
2333 end;
2334
2335 { show progress and allow for aborting }
2336 Progress := (FStream.Position*100) div FStream.Size;
2337 DoArchiveProgress(Progress, Abort);
2338 if Abort then begin
2339 FStatus := asInvalid;
2340 raise EAbUserAbort.Create;
2341 end;
2342
2343 { get the next item }
2344 ItemFound := TarHelp.FindNextItem;
2345 except {Item}
2346 raise EAbTarBadOp.Create; { Invalid Item }
2347 end; {Item}
2348 end; {end while }
2349
2350 { All the items need to reflect this information. }
2351 for i := 0 to FItemList.Count - 1 do
2352 begin
2353 TAbTarItem(FItemList.Items[i]).ArchiveFormat := FArchFormat;
2354 TAbTarItem(FItemList.Items[i]).ItemReadOnly := FArchReadOnly;
2355 end;
2356
2357 DoArchiveProgress(100, Abort);
2358 FIsDirty := False;
2359
2360 finally {TarHelp}
2361 { Clean Up }
2362 TarHelp.Free;
2363 end; {TarHelp}
2364 end;
2365
2366
2367 function TAbTarArchive.FixName(const Value: string): string;
2368 { fixup filename for storage }
2369 var
2370 lValue : string;
2371 begin
2372 lValue := Value;
2373 {$IFDEF MSWINDOWS}
2374 if DOSMode then begin
2375 {Add the base directory to the filename before converting }
2376 {the file spec to the short filespec format. }
2377 if BaseDirectory <> '' then begin
2378 {Does the filename contain a drive or a leading backslash? }
2379 if not ((Pos(':', lValue) = 2) or (Pos(AbPathDelim, lValue) = 1)) then
2380 {If not, add the BaseDirectory to the filename.}
2381 lValue := BaseDirectory + AbPathDelim + lValue;
2382 end;
2383 lValue := AbGetShortFileSpec( lValue );
2384 end;
2385 {$ENDIF MSWINDOWS}
2386
2387 { Should always trip drive info if on a Win/Dos system }
2388 StoreOptions := StoreOptions + [soStripDrive];
2389
2390 { strip drive stuff }
2391 if soStripDrive in StoreOptions then
2392 AbStripDrive( lValue );
2393
2394 { check for a leading slash }
2395 if (Length(lValue) > 0) and (lValue[1] = AbPathDelim) then
2396 System.Delete( lValue, 1, 1 );
2397
2398 if soStripPath in StoreOptions then
2399 lValue := ExtractFileName(lValue);
2400
2401 if soRemoveDots in StoreOptions then
2402 AbStripDots(lValue);
2403
2404 AbFixName(lValue);
2405
2406 Result := lValue;
2407 end;
2408
2409 function TAbTarArchive.GetItem(Index: Integer): TAbTarItem;
2410 begin
2411 Result := TAbTarItem(FItemList.Items[Index]);
2412 end;
2413
2414 function TAbTarArchive.GetSupportsEmptyFolders: Boolean;
2415 begin
2416 Result := True;
2417 end;
2418
2419 procedure TAbTarArchive.PutItem(Index: Integer; const Value: TAbTarItem);
2420 begin
2421 //TODO: Remove this from all archives
2422 FItemList.Items[Index] := Value;
2423 end;
2424
2425 procedure TAbTarArchive.SaveArchive;
2426 var
2427 OutTarHelp : TAbTarStreamHelper;
2428 Abort : Boolean;
2429 i : Integer;
2430 NewStream : TStream;
2431 TempStream : TStream;
2432 CurItem : TAbTarItem;
2433 AttrEx : TAbAttrExRec;
2434 ATempName : String;
2435 begin
2436 if FArchReadOnly then
2437 raise EAbTarBadOp.Create; { Archive is read only }
2438
2439 {init new archive stream}
2440 if Assigned(FTargetStream) then
2441 NewStream := FTargetStream
2442 else if FOwnsStream and (FStream is TFileStreamEx) then
2443 begin
2444 if FStream.Size = 0 then
2445 NewStream := FStream
2446 else begin
2447 ATempName := GetTempName(FArchiveName);
2448 NewStream := TFileStreamEx.Create(ATempName, fmCreate or fmShareDenyWrite);
2449 end;
2450 end
2451 else begin
2452 NewStream := TAbVirtualMemoryStream.Create;
2453 TAbVirtualMemoryStream(NewStream).SwapFileDirectory := ExtractFileDir(FArchiveName);
2454 end;
2455 OutTarHelp := TAbTarStreamHelper.Create(NewStream, OnProgress);
2456
2457 try {NewStream/OutTarHelp}
2458 {build new archive from existing archive}
2459 for i := 0 to pred(Count) do begin
2460 FCurrentItem := ItemList[i];
2461 CurItem := TAbTarItem(ItemList[i]);
2462
2463 case CurItem.Action of
2464 aaNone, aaMove : begin {just copy the file to new stream}
2465 { "Seek" to the Item Data } { SaveTarHeaders, Updates FileHeaderCount }
2466 FStream.Position := CurItem.StreamPosition+CurItem.FileHeaderCount*AB_TAR_RECORDSIZE;
2467 CurItem.StreamPosition := NewStream.Position;{ Reset the Stream Pointer. }
2468 { Flush The Headers to the new stream }
2469 CurItem.SaveTarHeaderToStream(NewStream);
2470 { Copy to new Stream, Round to the AB_TAR_RECORDSIZE boundry, and Pad zeros}
2471 outTarhelp.WriteArchiveItemSize(FStream, CurItem.UncompressedSize);
2472 end;
2473
2474 aaDelete: {doing nothing omits file from new stream} ;
2475
2476 aaStreamAdd : begin
2477 try
2478 { adding from a stream }
2479 CurItem.StreamPosition := NewStream.Position;{ Reset the Stream Pointer. }
2480 CurItem.UncompressedSize := InStream.Size;
2481 CurItem.SaveTarHeaderToStream(NewStream);
2482 OutTarHelp.WriteArchiveItemSize(InStream, InStream.Size);
2483 except
2484 ItemList[i].Action := aaDelete;
2485 DoProcessItemFailure(ItemList[i], ptAdd, ecFileOpenError, 0);
2486 end;
2487 end;
2488
2489 aaAdd, aaFreshen, aaReplace: begin
2490 try
2491 { update metadata }
2492 if not AbFileGetAttrEx(CurItem.DiskFileName, AttrEx, False) then
2493 Raise EAbFileNotFound.Create;
2494 CurItem.ExternalFileAttributes := AttrEx.Mode;
2495 CurItem.LastModTimeAsDateTime := AttrEx.Time;
2496 { TODO: uid, gid, uname, gname should be added here }
2497 { TODO: Add support for different types of files here }
2498 case (AttrEx.Mode and $F000) of
2499 AB_FMODE_DIR: begin
2500 CurItem.UncompressedSize := 0;
2501 CurItem.SaveTarHeaderToStream(NewStream);
2502 end;
2503
2504 AB_FMODE_FILELINK: begin
2505 CurItem.UncompressedSize := 0;
2506 CurItem.LinkName := ReadSymlink(CurItem.DiskFileName);
2507 CurItem.SaveTarHeaderToStream(NewStream);
2508 end;
2509
2510 AB_FMODE_FILE, AB_FMODE_FILE2: begin
2511 TempStream := TFileStreamEx.Create(CurItem.DiskFileName,
2512 fmOpenRead or fmShareDenyWrite );
2513 try { TempStream }
2514 CurItem.UncompressedSize := TempStream.Size;
2515 CurItem.StreamPosition := NewStream.Position;{ Reset the Stream Pointer. }
2516 CurItem.SaveTarHeaderToStream(NewStream);
2517 OutTarHelp.WriteArchiveItemSize(TempStream, TempStream.Size);
2518 finally { TempStream }
2519 TempStream.Free;
2520 end; { TempStream }
2521 end;
2522
2523 else begin
2524 CurItem.UncompressedSize := AttrEx.Size;
2525 CurItem.SaveTarHeaderToStream(NewStream);
2526 end;
2527 end;
2528
2529 except
2530 ItemList[i].Action := aaDelete;
2531 DoProcessItemFailure(ItemList[i], ptAdd, ecFileOpenError, 0);
2532 end;
2533 end; { aaAdd ... }
2534 end; { case }
2535 end; { for i ... }
2536
2537 if NewStream.Position > 0 then
2538 OutTarHelp.WriteArchiveTail; { Terminate the TAR }
2539 { Size of NewStream is still 0, and max of the stream will also be 0 }
2540
2541 if (FTargetStream = nil) then
2542 begin
2543 {copy new stream to FStream}
2544 NewStream.Position := 0;
2545 if (FStream is TMemoryStream) then
2546 TMemoryStream(FStream).LoadFromStream(NewStream)
2547 else if (FStream is TAbVirtualMemoryStream) then begin
2548 FStream.Position := 0;
2549 FStream.Size := 0;
2550 TAbVirtualMemoryStream(FStream).CopyFrom(NewStream, NewStream.Size)
2551 end
2552 else begin
2553 if FOwnsStream then
2554 begin
2555 {need new stream to write}
2556 if NewStream = FStream then
2557 NewStream := nil
2558 else begin
2559 FreeAndNil(FStream);
2560 FreeAndNil(NewStream);
2561 if (mbDeleteFile(FArchiveName) and mbRenameFile(ATempName, FArchiveName)) then
2562 FStream := TFileStreamEx.Create(FArchiveName, fmOpenReadWrite or fmShareDenyWrite)
2563 else
2564 RaiseLastOSError;
2565 end;
2566 end
2567 else begin
2568 FStream.Size := 0;
2569 FStream.Position := 0;
2570 FStream.CopyFrom(NewStream, 0)
2571 end;
2572 end;
2573 end;
2574
2575 {update Items list}
2576 for i := pred( Count ) downto 0 do begin
2577 if ItemList[i].Action = aaDelete then
2578 FItemList.Delete( i )
2579 else if ItemList[i].Action <> aaFailed then
2580 ItemList[i].Action := aaNone;
2581 end;
2582
2583 DoArchiveSaveProgress( 100, Abort );
2584 DoArchiveProgress( 100, Abort );
2585 finally {NewStream/OutTarHelp}
2586 OutTarHelp.Free;
2587 if (FStream <> NewStream) and (FTargetStream <> NewStream) then
2588 NewStream.Free;
2589 end;
2590 end;
2591
2592 { This assumes that LoadArchive has been called. }
2593 procedure TAbTarArchive.TestItemAt(Index: Integer);
2594 begin
2595 FStream.Position := TAbTarItem(FItemList[Index]).StreamPosition;
2596 if VerifyTar(FStream) <> atTar then
2597 raise EAbTarInvalid.Create; { Invalid Tar }
2598 end;
2599
2600 end.