[go: up one dir, main page]

File: XADArchive.m

package info (click to toggle)
unar 1.10.8%2Bds1-9
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 6,212 kB
  • sloc: ansic: 50,891; objc: 47,233; makefile: 77; sh: 34
file content (1239 lines) | stat: -rw-r--r-- 36,019 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
/*
 * XADArchive.m
 *
 * Copyright (c) 2017-present, MacPaw Inc. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301  USA
 */
#define XAD_NO_DEPRECATED

#import "XADArchive.h"
#import "CSMemoryHandle.h"
#import "CSHandle.h"
#import "Progress.h"
#import "NSDateXAD.h"

#import <sys/stat.h>
#import <sys/time.h>


NSString *XADResourceDataKey=@"XADResourceData";
NSString *XADFinderFlags=@"XADFinderFlags";



@implementation XADArchive

+(XADArchive *)archiveForFile:(NSString *)filename
{
	return [[[XADArchive alloc] initWithFile:filename] autorelease];
}

+(XADArchive *)recursiveArchiveForFile:(NSString *)filename
{
	XADArchive *archive=[self archiveForFile:filename];

	while([archive numberOfEntries]==1)
	{
		XADArchive *subarchive=[[XADArchive alloc] initWithArchive:archive entry:0];
		if(subarchive) archive=[subarchive autorelease];
		else
		{
			[subarchive release];
			break;
		}
	}

	return archive;
}

+(NSArray *)volumesForFile:(NSString *)filename // deprecated
{
	return [NSArray arrayWithObject:filename];
}




-(id)init
{
	if((self=[super init]))
	{
		parser=nil;
		unarchiver=nil;
		delegate=nil;
		lasterror=XADNoError;
		immediatedestination=nil;
		immediatefailed=NO;
		immediatesize=0;
		parentarchive=nil;

		dataentries=[[NSMutableArray array] retain];
		resourceentries=[[NSMutableArray array] retain];
		namedict=nil;
 	}
	return self;
}

-(id)initWithFile:(NSString *)file { return [self initWithFile:file delegate:nil error:NULL]; }

-(id)initWithFile:(NSString *)file error:(XADError *)error { return [self initWithFile:file delegate:nil error:error]; }

-(id)initWithFile:(NSString *)file delegate:(id)del error:(XADError *)error
{
	if((self=[self init]))
	{
		delegate=del;

		parser=[[XADArchiveParser archiveParserForPath:file] retain];
		if(parser)
		{
			if([self _parseWithErrorPointer:error]) return self;
		}
		else if(error) *error=XADDataFormatError;

		[self release];
	}

	return nil;
}



-(id)initWithData:(NSData *)data { return [self initWithData:data delegate:nil error:NULL]; }

-(id)initWithData:(NSData *)data error:(XADError *)error { return [self initWithData:data delegate:nil error:error]; }

-(id)initWithData:(NSData *)data delegate:(id)del error:(XADError *)error
{
	if((self=[self init]))
	{
		delegate=del;

		parser=[[XADArchiveParser archiveParserForHandle:[CSMemoryHandle memoryHandleForReadingData:data] name:@""] retain];
		if(parser)
		{
			if([self _parseWithErrorPointer:error]) return self;
		}
		else if(error) *error=XADDataFormatError;

		[self release];
	}
	return nil;
}



-(id)initWithArchive:(XADArchive *)otherarchive entry:(int)n { return [self initWithArchive:otherarchive entry:n delegate:nil error:NULL]; }

-(id)initWithArchive:(XADArchive *)otherarchive entry:(int)n error:(XADError *)error { return [self initWithArchive:otherarchive entry:n delegate:nil error:error]; }

-(id)initWithArchive:(XADArchive *)otherarchive entry:(int)n delegate:(id)del error:(XADError *)error
{
	if((self=[self init]))
	{
		parentarchive=[otherarchive retain];
		delegate=del;

		CSHandle *handle=[otherarchive handleForEntry:n error:error];
		if(handle)
		{
			parser=[[XADArchiveParser archiveParserForHandle:handle name:[otherarchive nameOfEntry:n]] retain];
			if(parser)
			{
				if([self _parseWithErrorPointer:error]) return self;
			}
			else if(error) *error=XADDataFormatError;
		}

		[self release];
	}

	return nil;
}

-(id)initWithArchive:(XADArchive *)otherarchive entry:(int)n
     immediateExtractionTo:(NSString *)destination error:(XADError *)error
{
	return [self initWithArchive:otherarchive entry:n immediateExtractionTo:destination
	subArchives:NO error:error];
}

-(id)initWithArchive:(XADArchive *)otherarchive entry:(int)n
     immediateExtractionTo:(NSString *)destination subArchives:(BOOL)sub error:(XADError *)error
{
	if((self=[self init]))
	{
		parentarchive=[otherarchive retain];
		immediatedestination=destination;
		immediatesubarchives=sub;
		delegate=otherarchive;

		immediatesize=[otherarchive representativeSizeOfEntry:n];

		parser=[[XADArchiveParser archiveParserForEntryWithDictionary:
		[otherarchive dataForkParserDictionaryForEntry:n]
		archiveParser:otherarchive->parser wantChecksum:YES error:error] retain];
		if(parser)
		{
			if([self _parseWithErrorPointer:error])
			{
				if(!immediatefailed)
				{
					XADError checksumerror=[parser testChecksumWithoutExceptions];
					if(checksumerror)
					{
						lasterror=checksumerror;
						if(error) *error=checksumerror;
						immediatefailed=YES;
					}
				}

				[self updateAttributesForDeferredDirectories];
				immediatedestination=nil;
				return self;
			}
		}
		else if(error) *error=XADSubArchiveError;

		[self release];
	}

	return nil;
}


-(void)dealloc
{
	[parser release];
	[unarchiver release];
	[dataentries release];
	[resourceentries release];
	[namedict release];
	[parentarchive release];

	[super dealloc];
}



-(BOOL)_parseWithErrorPointer:(XADError *)error
{
	unarchiver=[[XADUnarchiver unarchiverForArchiveParser:parser] retain];

	[parser setDelegate:self];
	[unarchiver setDelegate:self];

	namedict=[[NSMutableDictionary dictionary] retain];

	XADError parseerror=[parser parseWithoutExceptions];
	if(parseerror)
	{
		lasterror=parseerror;
		if(error) *error=parseerror;
	}

	if(immediatefailed&&error) *error=lasterror;

	[namedict release];
	namedict=nil;

	return lasterror==XADNoError||[dataentries count]!=0;
}

-(void)archiveParser:(XADArchiveParser *)parser foundEntryWithDictionary:(NSDictionary *)dict
{
	if(immediatefailed) return; // ignore anything after a failure

	NSNumber *resnum=[dict objectForKey:XADIsResourceForkKey];
	BOOL isres=resnum&&[resnum boolValue];

	XADPath *name=[dict objectForKey:XADFileNameKey];

	NSNumber *index=[namedict objectForKey:name];
	if(index) // Try to update an existing entry
	{
		int n=[index intValue];
		if(isres) // Adding a resource fork to an earlier data fork
		{
			if([resourceentries objectAtIndex:n]==[NSNull null])
			{
				[resourceentries replaceObjectAtIndex:n withObject:dict];

				if(immediatedestination)
				{
					if(![self extractEntry:n to:immediatedestination
					deferDirectories:YES dataFork:NO resourceFork:YES])
					immediatefailed=YES;
				}

				return;
			}
		}
		else // Adding a data fork to an earlier resource fork
		{
			if([dataentries objectAtIndex:n]==[NSNull null])
			{
				[dataentries replaceObjectAtIndex:n withObject:dict];

				if(immediatedestination)
				{
					if(immediatesubarchives&&[self entryIsArchive:n])
					{
						// Try to extract as archive, if the format is unknown, extract as regular file
						BOOL res;
						@try { res=[self extractArchiveEntry:n to:immediatedestination]; }
						@catch(id e) { res=NO; }

						if(!res&&lasterror==XADDataFormatError)
						{
							if(![self extractEntry:n to:immediatedestination
							deferDirectories:YES dataFork:YES resourceFork:NO])
							immediatefailed=YES;
						}
						else immediatefailed=YES;
					}
					else
					{
						if(![self extractEntry:n to:immediatedestination
						deferDirectories:YES dataFork:YES resourceFork:NO])
						immediatefailed=YES;
					}
				}

				return;
			}
		}
	}

	// Create a new entry instead

	if(isres)
	{
		[dataentries addObject:[NSNull null]];
		[resourceentries addObject:dict];
	}
	else
	{
		[dataentries addObject:dict];
		[resourceentries addObject:[NSNull null]];
	}

	[namedict setObject:[NSNumber numberWithInt:[dataentries count]-1] forKey:name];

	if(immediatedestination)
	{
		int n=[dataentries count]-1;
		if(immediatesubarchives&&[self entryIsArchive:n])
		{
			// Try to extract as archive, if the format is unknown, extract as regular file
			BOOL res;
			@try { res=[self extractArchiveEntry:n to:immediatedestination]; }
			@catch(id e) { res=NO; }

			if(!res)
			{
				if(lasterror==XADDataFormatError)
				{
					if(![self extractEntry:n to:immediatedestination
					deferDirectories:YES dataFork:YES resourceFork:YES])
					immediatefailed=YES;
				}
				else immediatefailed=YES;
			}
		}
		else
		{
			if(![self extractEntry:n to:immediatedestination
			deferDirectories:YES dataFork:YES resourceFork:YES])
			immediatefailed=YES;
		}
	}
}

-(BOOL)archiveParsingShouldStop:(XADArchiveParser *)parser
{
	return immediatefailed;
}

-(void)archiveParserNeedsPassword:(XADArchiveParser *)parser
{
	[delegate archiveNeedsPassword:self];
}



-(NSString *)filename
{
	return [parser filename];
}

-(NSArray *)allFilenames
{
	return [parser allFilenames];
}

-(NSString *)formatName
{
	if(parentarchive) return [NSString stringWithFormat:@"%@ in %@",[parser formatName],[parentarchive formatName]];
	else return [parser formatName];
}

-(BOOL)isEncrypted { return [parser isEncrypted]; }

-(BOOL)isSolid
{
	NSNumber *issolid=[[parser properties] objectForKey:XADIsSolidKey];
	if(!issolid) return NO;
	return [issolid boolValue];
}

-(BOOL)isCorrupted
{
	NSNumber *iscorrupted=[[parser properties] objectForKey:XADIsCorruptedKey];
	if(!iscorrupted) return NO;
	return [iscorrupted boolValue];
}

-(int)numberOfEntries { return [dataentries count]; }

-(BOOL)immediateExtractionFailed { return immediatefailed; }

-(NSString *)commonTopDirectory
{
	NSString *firstname=[self nameOfEntry:0];
	NSRange slash=[firstname rangeOfString:@"/"];

	NSString *directory;
	if(slash.location!=NSNotFound) directory=[firstname substringToIndex:slash.location];
	else if([self entryIsDirectory:0]) directory=firstname;
	else return nil;

	NSString *dirprefix=[directory stringByAppendingString:@"/"];

	int numentries=[self numberOfEntries];
	for(int i=1;i<numentries;i++)
	if(![[self nameOfEntry:i] hasPrefix:dirprefix]) return nil;

	return directory;
}

-(NSString *)comment
{
	return [[parser properties] objectForKey:XADCommentKey];
}



-(void)setDelegate:(id)newdelegate { delegate=newdelegate; }

-(id)delegate { return delegate; }



-(NSString *)password { return [parser password]; }

-(void)setPassword:(NSString *)newpassword { [parser setPassword:newpassword]; }



-(NSStringEncoding)nameEncoding { return [[parser stringSource] encoding]; }

-(void)setNameEncoding:(NSStringEncoding)encoding { [[parser stringSource] setFixedEncoding:encoding]; }




-(XADError)lastError { return lasterror; }

-(void)clearLastError { lasterror=XADNoError; }

-(NSString *)describeLastError { return [XADException describeXADError:lasterror]; }

-(NSString *)describeError:(XADError)error { return [XADException describeXADError:error]; }



-(NSString *)description
{
	return [NSString stringWithFormat:@"XADArchive: %@ (%@, %d entries)",[self filename],[self formatName],[self numberOfEntries]];
}



-(NSDictionary *)dataForkParserDictionaryForEntry:(int)n
{
	id obj=[dataentries objectAtIndex:n];
	if(obj==[NSNull null]) return nil;
	else return obj;
}

-(NSDictionary *)resourceForkParserDictionaryForEntry:(int)n
{
	id obj=[resourceentries objectAtIndex:n];
	if(obj==[NSNull null]) return nil;
	else return obj;
}

-(NSDictionary *)combinedParserDictionaryForEntry:(int)n
{
	NSDictionary *data=[dataentries objectAtIndex:n];
	NSDictionary *resource=[resourceentries objectAtIndex:n];

	if((id)data==[NSNull null]) return resource;
	if((id)resource==[NSNull null]) return data;

	NSMutableDictionary *new=[NSMutableDictionary dictionaryWithDictionary:data];

	id obj;

	obj=[resource objectForKey:XADFileTypeKey];
	if(obj) [new setObject:obj forKey:XADFileTypeKey];
	obj=[resource objectForKey:XADFileCreatorKey];
	if(obj) [new setObject:obj forKey:XADFileCreatorKey];
	obj=[resource objectForKey:XADFinderFlagsKey];
	if(obj) [new setObject:obj forKey:XADFinderFlagsKey];
	obj=[resource objectForKey:XADFinderInfoKey];
	if(obj) [new setObject:obj forKey:XADFinderInfoKey];

	return new;
}

-(NSString *)nameOfEntry:(int)n
{
	NSDictionary *dict=[self dataForkParserDictionaryForEntry:n];
	if(!dict) dict=[self resourceForkParserDictionaryForEntry:n];

	XADPath *xadname=[dict objectForKey:XADFileNameKey];
	if(!xadname) return nil;

	if(![xadname encodingIsKnown]&&delegate)
	{
		NSStringEncoding encoding=[delegate archive:self encodingForData:[xadname data]
		guess:[xadname encoding] confidence:[xadname confidence]];
		return [xadname sanitizedPathStringWithEncoding:encoding];
	}
	else
	{
		return [xadname sanitizedPathString];
	}
}

-(BOOL)entryHasSize:(int)n
{
	NSDictionary *dict=[self dataForkParserDictionaryForEntry:n];
	return [dict objectForKey:XADFileSizeKey]?YES:NO;
}

-(off_t)uncompressedSizeOfEntry:(int)n
{
	NSDictionary *dict=[self dataForkParserDictionaryForEntry:n];
	if(!dict) return 0; // Special case for resource forks without data forks
	NSNumber *size=[dict objectForKey:XADFileSizeKey];
	if(!size) return CSHandleMaxLength;
	return [size longLongValue];
}

-(off_t)compressedSizeOfEntry:(int)n
{
	NSDictionary *dict=[self dataForkParserDictionaryForEntry:n];
	if(!dict) return 0; // Special case for resource forks without data forks
	NSNumber *size=[dict objectForKey:XADCompressedSizeKey];
	if(!size) return CSHandleMaxLength;
	return [size longLongValue];
}

-(off_t)representativeSizeOfEntry:(int)n
{
	NSDictionary *dict=[self dataForkParserDictionaryForEntry:n];
	if(!dict) return 0; // Special case for resource forks without data forks
	NSNumber *size=[dict objectForKey:XADFileSizeKey];
	if(!size) size=[dict objectForKey:XADCompressedSizeKey];
	if(!size) return 1000;
	return [size longLongValue];
}

-(BOOL)entryIsDirectory:(int)n
{
	NSDictionary *dict=[self combinedParserDictionaryForEntry:n];
	NSNumber *isdir=[dict objectForKey:XADIsDirectoryKey];

	return isdir&&[isdir boolValue];
}

-(BOOL)entryIsLink:(int)n
{
	NSDictionary *dict=[self dataForkParserDictionaryForEntry:n];
	NSNumber *islink=[dict objectForKey:XADIsLinkKey];

	return islink&&[islink boolValue];
}

-(BOOL)entryIsEncrypted:(int)n
{
	NSDictionary *dict=[self dataForkParserDictionaryForEntry:n];
	NSNumber *isenc=[dict objectForKey:XADIsEncryptedKey];

	return isenc&&[isenc boolValue];
}

-(BOOL)entryIsArchive:(int)n
{
	NSDictionary *dict=[self dataForkParserDictionaryForEntry:n];
	NSNumber *isarc=[dict objectForKey:XADIsArchiveKey];

	return isarc&&[isarc boolValue];
}

-(BOOL)entryHasResourceFork:(int)n
{
	NSDictionary *resdict=[self resourceForkParserDictionaryForEntry:n];
	if(!resdict) return NO;
	NSNumber *num=[resdict objectForKey:XADFileSizeKey];
	if(!num) return NO;

	return [num intValue]!=0;
}

-(NSString *)commentForEntry:(int)n
{
	NSDictionary *dict=[self dataForkParserDictionaryForEntry:n]; // TODO: combined or data?
	return [dict objectForKey:XADCommentKey];
}

-(NSDictionary *)attributesOfEntry:(int)n { return [self attributesOfEntry:n withResourceFork:NO]; }

-(NSDictionary *)attributesOfEntry:(int)n withResourceFork:(BOOL)resfork
{
	NSDictionary *dict=[self combinedParserDictionaryForEntry:n];
	NSMutableDictionary *attrs=[NSMutableDictionary dictionary];

	NSDate *creation=[dict objectForKey:XADCreationDateKey];
	NSDate *modification=[dict objectForKey:XADLastModificationDateKey];
	if(modification) [attrs setObject:modification forKey:NSFileModificationDate];
	if(creation) [attrs setObject:creation forKey:NSFileCreationDate];

	NSNumber *type=[dict objectForKey:XADFileTypeKey];
	if(type) [attrs setObject:type forKey:NSFileHFSTypeCode];

	NSNumber *creator=[dict objectForKey:XADFileCreatorKey];
	if(creator) [attrs setObject:creator forKey:NSFileHFSCreatorCode];

	NSNumber *flags=[dict objectForKey:XADFinderFlagsKey];
	if(flags) [attrs setObject:flags forKey:XADFinderFlagsKey];

	NSNumber *perm=[dict objectForKey:XADPosixPermissionsKey];
	if(perm) [attrs setObject:perm forKey:NSFilePosixPermissions];

	XADString *user=[dict objectForKey:XADPosixUserNameKey];
	if(user)
	{
		NSString *username=[user string];
		if(username) [attrs setObject:username forKey:NSFileOwnerAccountName];
	}

	XADString *group=[dict objectForKey:XADPosixGroupNameKey];
	if(group)
	{
		NSString *groupname=[group string];
		if(groupname) [attrs setObject:groupname forKey:NSFileGroupOwnerAccountName];
	}

	if(resfork)
	{
		NSDictionary *resdict=[self resourceForkParserDictionaryForEntry:n];
		if(resdict)
		{
			for(;;)
			{
				@try
				{
					CSHandle *handle=[parser handleForEntryWithDictionary:resdict wantChecksum:YES];
					if(!handle) [XADException raiseDecrunchException];
					NSData *forkdata=[handle remainingFileContents];
					if([handle hasChecksum]&&![handle isChecksumCorrect]) [XADException raiseChecksumException];

					[attrs setObject:forkdata forKey:XADResourceDataKey];
					break;
				}
				@catch(id e)
				{
					lasterror=[XADException parseException:e];
					XADAction action=[delegate archive:self extractionOfResourceForkForEntryDidFail:n error:lasterror];
					if(action==XADSkipAction) break;
					else if(action!=XADRetryAction) return nil;
				}
			}
		}
	}

	return [NSDictionary dictionaryWithDictionary:attrs];
}

-(CSHandle *)handleForEntry:(int)n
{
	return [self handleForEntry:n error:NULL];
}

-(CSHandle *)handleForEntry:(int)n error:(XADError *)error
{
	NSDictionary *dict=[self dataForkParserDictionaryForEntry:n];
	if(!dict) return [CSMemoryHandle memoryHandleForReadingData:[NSData data]]; // Special case for files with only a resource fork

	@try
	{ return [parser handleForEntryWithDictionary:dict wantChecksum:YES]; }
	@catch(id e)
	{
		lasterror=[XADException parseException:e];
		if(error) *error=lasterror;
	}
	return nil;
}

-(CSHandle *)resourceHandleForEntry:(int)n
{
	return [self resourceHandleForEntry:n error:NULL];
}

-(CSHandle *)resourceHandleForEntry:(int)n error:(XADError *)error
{
	NSDictionary *resdict=[self resourceForkParserDictionaryForEntry:n];
	if(!resdict) return nil;
	NSNumber *isdir=[resdict objectForKey:XADIsDirectoryKey];
	if(isdir&&[isdir boolValue]) return nil;

	@try
	{ return [parser handleForEntryWithDictionary:resdict wantChecksum:YES]; }
	@catch(id e)
	{
		lasterror=[XADException parseException:e];
		if(error) *error=lasterror;
	}
	return nil;
}

-(NSData *)contentsOfEntry:(int)n
{
	NSDictionary *dict=[self dataForkParserDictionaryForEntry:n];
	if(!dict) return [NSData data]; // Special case for files with only a resource fork

	@try
	{
		CSHandle *handle=[parser handleForEntryWithDictionary:dict wantChecksum:YES];
		if(!handle) [XADException raiseDecrunchException];
		NSData *data=[handle remainingFileContents];
		if([handle hasChecksum]&&![handle isChecksumCorrect]) [XADException raiseChecksumException];

		return data;
	}
	@catch(id e)
	{
		lasterror=[XADException parseException:e];
	}
	return nil;
}




// Extraction functions

-(BOOL)extractTo:(NSString *)destination
{
	return [self extractEntries:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0,[self numberOfEntries])] to:destination subArchives:NO];
}

-(BOOL)extractTo:(NSString *)destination subArchives:(BOOL)sub
{
	return [self extractEntries:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0,[self numberOfEntries])] to:destination subArchives:sub];
}

-(BOOL)extractEntries:(NSIndexSet *)entryset to:(NSString *)destination
{
	return [self extractEntries:entryset to:destination subArchives:NO];
}

-(BOOL)extractEntries:(NSIndexSet *)entryset to:(NSString *)destination subArchives:(BOOL)sub
{
	extractsize=0;
	totalsize=0;

	for(NSUInteger i=[entryset firstIndex];i!=NSNotFound;i=[entryset indexGreaterThanIndex:i])
	totalsize+=[self representativeSizeOfEntry:i];

	int numentries=[entryset count];
	[delegate archive:self extractionProgressFiles:0 of:numentries];
	[delegate archive:self extractionProgressBytes:0 of:totalsize];

	for(NSUInteger i=[entryset firstIndex];i!=NSNotFound;i=[entryset indexGreaterThanIndex:i])
	{
		BOOL res;

		if(sub&&[self entryIsArchive:i])
		{
			@try { res=[self extractArchiveEntry:i to:destination]; }
			@catch(id e) { res=NO; }

			if(!res&&lasterror==XADDataFormatError) // Retry as regular file if the archive format was not known
			{
				res=[self extractEntry:i to:destination deferDirectories:YES];
			}
		}
		else res=[self extractEntry:i to:destination deferDirectories:YES];

		if(!res)
		{
			totalsize=0;
			return NO;
		}

		extractsize+=[self representativeSizeOfEntry:i];

		[delegate archive:self extractionProgressFiles:i+1 of:numentries];
		[delegate archive:self extractionProgressBytes:extractsize of:totalsize];
	}

	[self updateAttributesForDeferredDirectories];

	totalsize=0;
	return YES;
}

-(BOOL)extractEntry:(int)n to:(NSString *)destination
{ return [self extractEntry:n to:destination deferDirectories:NO dataFork:YES resourceFork:YES]; }

-(BOOL)extractEntry:(int)n to:(NSString *)destination deferDirectories:(BOOL)defer
{ return [self extractEntry:n to:destination deferDirectories:defer dataFork:YES resourceFork:YES]; }

-(BOOL)extractEntry:(int)n to:(NSString *)destination deferDirectories:(BOOL)defer
resourceFork:(BOOL)resfork
{ return [self extractEntry:n to:destination deferDirectories:defer dataFork:YES resourceFork:resfork]; }

-(BOOL)extractEntry:(int)n to:(NSString *)destination deferDirectories:(BOOL)defer
dataFork:(BOOL)datafork resourceFork:(BOOL)resfork
{
	if(datafork) [delegate archive:self extractionOfEntryWillStart:n];

	NSString *name;

	while(!(name=[self nameOfEntry:n]))
	{
		if(delegate)
		{
			XADAction action=[delegate archive:self nameDecodingDidFailForEntry:n
			data:[[[self dataForkParserDictionaryForEntry:n] objectForKey:XADFileNameKey] data]];
			if(action==XADSkipAction) return YES;
			else if(action!=XADRetryAction)
			{
				lasterror=XADBreakError;
				return NO;
			}
		}
		else
		{
			lasterror=XADEncodingError;
			return NO;
		}
	}

	if(![name length]) return YES; // Silently ignore unnamed files (or more likely, directories).

	NSString *destfile=[destination stringByAppendingPathComponent:name];
	while(![self _extractEntry:n as:destfile deferDirectories:defer dataFork:datafork resourceFork:resfork])
	{
		if(lasterror==XADBreakError) return NO;
		else if(delegate&&datafork)
		{
			XADAction action=[delegate archive:self extractionOfEntryDidFail:n error:lasterror];

			if(action==XADSkipAction) return YES;
			else if(action!=XADRetryAction) return NO;
		}
		else return NO;
	}

	if(datafork) [delegate archive:self extractionOfEntryDidSucceed:n];

	return YES;
}

-(BOOL)extractArchiveEntry:(int)n to:(NSString *)destination
{
	NSString *path=[destination stringByAppendingPathComponent:
	[[self nameOfEntry:n] stringByDeletingLastPathComponent]];

	for(;;)
	{
		XADError err;
		XADArchive *subarchive=[[XADArchive alloc] initWithArchive:self entry:n
		immediateExtractionTo:path subArchives:YES error:&err];

		if(!subarchive)
		{
			lasterror=err;
		}
		else
		{
			err=[subarchive lastError];
			if(err) lasterror=err;
		}

		BOOL res=subarchive&&![subarchive immediateExtractionFailed];

		[subarchive release];

		if(res) return YES;
		else if(err==XADBreakError||err==XADDataFormatError) return NO;
		else if(delegate)
		{
			XADAction action=[delegate archive:self extractionOfEntryDidFail:n error:err];

			if(action==XADSkipAction) return YES;
			else if(action!=XADRetryAction) return NO;
		}
		else return NO;
	}
}



-(BOOL)_extractEntry:(int)n as:(NSString *)destfile deferDirectories:(BOOL)defer
dataFork:(BOOL)datafork resourceFork:(BOOL)resfork
{
	for(;;)
	{
		XADError error=[unarchiver _ensureDirectoryExists:[destfile stringByDeletingLastPathComponent]];

		if(error==XADNoError)
		{
			break;
		}
		else if(delegate)
		{
			XADAction action=[delegate archive:self creatingDirectoryDidFailForEntry:n];
			if(action==XADSkipAction) return YES;
			else if(action!=XADRetryAction)
			{
				lasterror=XADBreakError;
				return NO;
			}
		}
		else
		{
			lasterror=error;
			return NO;
		}
	}

	struct stat st;
	BOOL isdir=[self entryIsDirectory:n];

	if(delegate)
	while(lstat([destfile fileSystemRepresentation],&st)==0)
	{
		BOOL dir=(st.st_mode&S_IFMT)==S_IFDIR;
		NSString *newname=nil;
		XADAction action;

		if(dir)
		{
			if(isdir) return YES;
			else action=[delegate archive:self entry:n collidesWithDirectory:destfile newFilename:&newname];
		}
		else action=[delegate archive:self entry:n collidesWithFile:destfile newFilename:&newname];

		if(action==XADOverwriteAction&&!dir) break;
		else if(action==XADSkipAction) return YES;
		else if(action==XADRenameAction) destfile=[[destfile stringByDeletingLastPathComponent] stringByAppendingPathComponent:newname];
		else if(action!=XADRetryAction)
		{
			lasterror=XADBreakError;
			return NO;
		}
	}

	NSDictionary *datadict=[self dataForkParserDictionaryForEntry:n];
	NSDictionary *resdict=[self resourceForkParserDictionaryForEntry:n];

	//extractEntryWithDictionary:(NSDictionary *)dict as:(NSString *)path forceDirectories:(BOOL)force

	if(datafork&&datadict)
	{
		extractingentry=n;
		extractingresource=NO;
		XADError error=[unarchiver extractEntryWithDictionary:datadict as:destfile forceDirectories:!defer];
		if(error) { lasterror=error; return NO; }
	}

	if(resfork&&resdict)
	{
		extractingentry=n;
		extractingresource=YES;
		XADError error=[unarchiver extractEntryWithDictionary:resdict as:destfile forceDirectories:!defer];
		if(error) { lasterror=error; return NO; }
	}

	return YES;
}

-(void)updateAttributesForDeferredDirectories
{
	[unarchiver finishExtractions];
}



-(BOOL)extractionShouldStopForUnarchiver:(XADUnarchiver *)unarchiver;
{
	return delegate&&[delegate archiveExtractionShouldStop:self];
}

-(void)unarchiver:(XADUnarchiver *)unarchiver extractionProgressForEntryWithDictionary:(NSDictionary *)dict
fileFraction:(double)fileprogress estimatedTotalFraction:(double)totalprogress
{
	if(extractingresource) return;

	off_t size=[self representativeSizeOfEntry:extractingentry];
	off_t progress=fileprogress*size;
	[delegate archive:self extractionProgressForEntry:extractingentry bytes:progress of:size];

	if(totalsize)
	{
		[delegate archive:self extractionProgressBytes:extractsize+progress of:totalsize];
	}
	else if(immediatedestination)
	{
		[delegate archive:self extractionProgressBytes:totalprogress*immediatesize of:immediatesize];
	}
}

-(NSString *)unarchiver:(XADUnarchiver *)unarchiver destinationForLink:(XADString *)link from:(NSString *)path
{
	NSString *linkstring;
	if(![link encodingIsKnown]&&delegate)
	{
		// TODO: should there be a better way to deal with encodings?
		NSStringEncoding encoding=[delegate archive:self encodingForData:[link data]
		guess:[link encoding] confidence:[link confidence]];
		linkstring=[link stringWithEncoding:encoding];
	}
	else linkstring=[link string];

	return linkstring;
}

-(BOOL)unarchiver:(XADUnarchiver *)unarchiver shouldCreateDirectory:(NSString *)directory
{
	if(!delegate||[delegate archive:self shouldCreateDirectory:directory]) return YES;
	else return NO;
}

-(void)unarchiver:(XADUnarchiver *)unarchiver didCreateDirectory:(NSString *)directory
{
    if(delegate) {
        [delegate archive:self didCreateDirectory:directory];
    }
}


//
// Deprecated
//

-(int)sizeOfEntry:(int)n // deprecated and broken
{
	NSDictionary *dict=[self dataForkParserDictionaryForEntry:n];
	if(!dict) return 0; // Special case for resource forks without data forks
	NSNumber *size=[dict objectForKey:XADFileSizeKey];
	if(!size) return INT_MAX;
	return [size intValue];
}

// Ugly hack to support old versions of Xee.
-(void *)xadFileInfoForEntry:(int)n
{
	struct xadFileInfo
	{
		void *xfi_Next;
		uint32_t xfi_EntryNumber;/* number of entry */
		char *xfi_EntryInfo;  /* additional archiver text */
		void *xfi_PrivateInfo;/* client private, see XAD_OBJPRIVINFOSIZE */
		uint32_t xfi_Flags;      /* see XADFIF_xxx defines */
		char *xfi_FileName;   /* see XAD_OBJNAMESIZE tag */
		char *xfi_Comment;    /* see XAD_OBJCOMMENTSIZE tag */
		uint32_t xfi_Protection; /* AmigaOS3 bits (including multiuser) */
		uint32_t xfi_OwnerUID;   /* user ID */
		uint32_t xfi_OwnerGID;   /* group ID */
		char *xfi_UserName;   /* user name */
		char *xfi_GroupName;  /* group name */
		uint64_t xfi_Size;       /* size of this file */
		uint64_t xfi_GroupCrSize;/* crunched size of group */
		uint64_t xfi_CrunchSize; /* crunched size */
		char *xfi_LinkName;   /* name and path of link */
		struct xadDate {
			uint32_t xd_Micros;  /* values 0 to 999999     */
			int32_t xd_Year;    /* values 1 to 2147483648 */
			uint8_t xd_Month;   /* values 1 to 12         */
			uint8_t xd_WeekDay; /* values 1 to 7          */
			uint8_t xd_Day;     /* values 1 to 31         */
			uint8_t xd_Hour;    /* values 0 to 23         */
			uint8_t xd_Minute;  /* values 0 to 59         */
			uint8_t xd_Second;  /* values 0 to 59         */
		} xfi_Date;
		uint16_t xfi_Generation; /* File Generation [0...0xFFFF] (V3) */
		uint64_t xfi_DataPos;    /* crunched data position (V3) */
		void *xfi_MacFork;    /* pointer to 2nd fork for Mac (V7) */
		uint16_t xfi_UnixProtect;/* protection bits for Unix (V11) */
		uint8_t xfi_DosProtect; /* protection bits for MS-DOS (V11) */
		uint8_t xfi_FileType;   /* XADFILETYPE to define type of exe files (V11) */
		void *xfi_Special;    /* pointer to special data (V11) */
	};

	NSDictionary *dict=[self combinedParserDictionaryForEntry:n];
	NSDate *mod=[dict objectForKey:XADLastModificationDateKey];
	NSNumber *size=[dict objectForKey:XADFileSizeKey];

	NSMutableData *data=[NSMutableData dataWithLength:sizeof(struct xadFileInfo)];
	struct xadFileInfo *fi=[data mutableBytes];

	if(mod)
	{
		NSCalendarDate *cal=[mod dateWithCalendarFormat:nil timeZone:[NSTimeZone defaultTimeZone]];
		fi->xfi_Date.xd_Year=[cal yearOfCommonEra];
		fi->xfi_Date.xd_Month=[cal monthOfYear];
		fi->xfi_Date.xd_Day=[cal dayOfMonth];
		fi->xfi_Date.xd_Hour=[cal hourOfDay];
		fi->xfi_Date.xd_Minute=[cal minuteOfHour];
		fi->xfi_Date.xd_Second=[cal secondOfMinute];
	}
	else fi->xfi_Flags|=1<<6;

	if(size) fi->xfi_Size=[size longLongValue];
	else fi->xfi_Size=0;

	return fi;
}

-(BOOL)extractEntry:(int)n to:(NSString *)destination overrideWritePermissions:(BOOL)override
{ return [self extractEntry:n to:destination deferDirectories:override resourceFork:YES]; }

-(BOOL)extractEntry:(int)n to:(NSString *)destination overrideWritePermissions:(BOOL)override resourceFork:(BOOL)resfork
{ return [self extractEntry:n to:destination deferDirectories:override resourceFork:resfork]; }

-(void)fixWritePermissions { [self updateAttributesForDeferredDirectories]; }





-(NSStringEncoding)archive:(XADArchive *)archive encodingForData:(NSData *)data guess:(NSStringEncoding)guess confidence:(float)confidence
{ return [delegate archive:archive encodingForData:data guess:guess confidence:confidence]; }

-(XADAction)archive:(XADArchive *)archive nameDecodingDidFailForEntry:(int)n data:(NSData *)data
{ return [delegate archive:archive nameDecodingDidFailForEntry:n data:data]; }

-(BOOL)archiveExtractionShouldStop:(XADArchive *)arc
{ return [delegate archiveExtractionShouldStop:arc]; }

-(BOOL)archive:(XADArchive *)arc shouldCreateDirectory:(NSString *)directory
{ return [delegate archive:arc shouldCreateDirectory:directory]; }

-(void)archive:(XADArchive *)arc didCreateDirectory:(NSString *)directory
{ [delegate archive:arc didCreateDirectory:directory]; }

-(XADAction)archive:(XADArchive *)arc entry:(int)n collidesWithFile:(NSString *)file newFilename:(NSString **)newname
{ return [delegate archive:arc entry:n collidesWithFile:file newFilename:newname]; }

-(XADAction)archive:(XADArchive *)arc entry:(int)n collidesWithDirectory:(NSString *)file newFilename:(NSString **)newname
{ return [delegate archive:arc entry:n collidesWithDirectory:file newFilename:newname]; }

-(XADAction)archive:(XADArchive *)arc creatingDirectoryDidFailForEntry:(int)n
{ return [delegate archive:arc creatingDirectoryDidFailForEntry:n]; }

-(void)archiveNeedsPassword:(XADArchive *)arc
{ [delegate archiveNeedsPassword:arc]; }

-(void)archive:(XADArchive *)arc extractionOfEntryWillStart:(int)n
{ [delegate archive:arc extractionOfEntryWillStart:n]; }

-(void)archive:(XADArchive *)arc extractionProgressForEntry:(int)n bytes:(off_t)bytes of:(off_t)total
{ [delegate archive:arc extractionProgressForEntry:n bytes:bytes of:total]; }

-(void)archive:(XADArchive *)arc extractionOfEntryDidSucceed:(int)n
{ [delegate archive:arc extractionOfEntryDidSucceed:n]; }

-(XADAction)archive:(XADArchive *)arc extractionOfEntryDidFail:(int)n error:(XADError)error
{ return [delegate archive:arc extractionOfEntryDidFail:n error:error]; }

-(XADAction)archive:(XADArchive *)arc extractionOfResourceForkForEntryDidFail:(int)n error:(XADError)error
{ return [delegate archive:arc extractionOfResourceForkForEntryDidFail:n error:error]; }

-(void)archive:(XADArchive *)arc extractionProgressBytes:(off_t)bytes of:(off_t)total
{ [delegate archive:arc extractionProgressBytes:bytes of:total]; }

//-(void)archive:(XADArchive *)arc extractionProgressFiles:(int)files of:(int)total;
//{}

@end



@implementation NSObject (XADArchiveDelegate)

-(NSStringEncoding)archive:(XADArchive *)archive encodingForData:(NSData *)data guess:(NSStringEncoding)guess confidence:(float)confidence
{
	// Default implementation calls old method
	NSMutableData *terminateddata=[[NSMutableData alloc] initWithData:data];
	[terminateddata increaseLengthBy:1]; // append a 0 byte
	NSStringEncoding enc=[self archive:archive encodingForName:[terminateddata bytes] guess:guess confidence:confidence];
	[terminateddata release];
	return enc;
}

-(XADAction)archive:(XADArchive *)archive nameDecodingDidFailForEntry:(int)n data:(NSData *)data
{
	// Default implementation calls old method
	NSMutableData *terminateddata=[[NSMutableData alloc] initWithData:data];
	XADAction action=[self archive:archive nameDecodingDidFailForEntry:n bytes:[terminateddata bytes]];
	[terminateddata release];
	return action;
}

-(BOOL)archiveExtractionShouldStop:(XADArchive *)archive { return NO; }
-(BOOL)archive:(XADArchive *)archive shouldCreateDirectory:(NSString *)directory { return YES; }
-(void)archive:(XADArchive *)archive didCreateDirectory:(NSString *)directory { }
-(XADAction)archive:(XADArchive *)archive entry:(int)n collidesWithFile:(NSString *)file newFilename:(NSString **)newname { return XADOverwriteAction; }
-(XADAction)archive:(XADArchive *)archive entry:(int)n collidesWithDirectory:(NSString *)file newFilename:(NSString **)newname { return XADSkipAction; }
-(XADAction)archive:(XADArchive *)archive creatingDirectoryDidFailForEntry:(int)n { return XADAbortAction; }

-(void)archiveNeedsPassword:(XADArchive *)archive {}

-(void)archive:(XADArchive *)archive extractionOfEntryWillStart:(int)n {}
-(void)archive:(XADArchive *)archive extractionProgressForEntry:(int)n bytes:(off_t)bytes of:(off_t)total {}
-(void)archive:(XADArchive *)archive extractionOfEntryDidSucceed:(int)n {}
-(XADAction)archive:(XADArchive *)archive extractionOfEntryDidFail:(int)n error:(XADError)error { return XADAbortAction; }
-(XADAction)archive:(XADArchive *)archive extractionOfResourceForkForEntryDidFail:(int)n error:(XADError)error { return XADAbortAction; }

-(void)archive:(XADArchive *)archive extractionProgressBytes:(off_t)bytes of:(off_t)total {}
-(void)archive:(XADArchive *)archive extractionProgressFiles:(int)files of:(int)total {}

// Deprecated
-(NSStringEncoding)archive:(XADArchive *)archive encodingForName:(const char *)bytes guess:(NSStringEncoding)guess confidence:(float)confidence { return guess; }
-(XADAction)archive:(XADArchive *)archive nameDecodingDidFailForEntry:(int)n bytes:(const char *)bytes { return XADAbortAction; }

@end