-
Notifications
You must be signed in to change notification settings - Fork 95
/
Copy pathURKArchive.mm
1787 lines (1364 loc) · 59.8 KB
/
URKArchive.mm
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
//
// URKArchive.mm
// UnrarKit
//
//
#import "URKArchive.h"
#import "URKFileInfo.h"
#import "UnrarKitMacros.h"
#import "NSString+UnrarKit.h"
#import "zlib.h"
RarHppIgnore
#import "rar.hpp"
#pragma clang diagnostic pop
NSString *URKErrorDomain = @"URKErrorDomain";
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundef"
#if UNIFIED_LOGGING_SUPPORTED
os_log_t unrarkit_log;
BOOL unrarkitIsAtLeast10_13SDK;
#endif
#pragma clang diagnostic pop
static NSBundle *_resources = nil;
typedef enum : NSUInteger {
URKReadHeaderLoopActionStopReading,
URKReadHeaderLoopActionContinueReading,
} URKReadHeaderLoopAction;
@interface URKArchive ()
- (instancetype)initWithFile:(NSURL *)fileURL password:(NSString*)password error:(NSError * __autoreleasing *)error
// iOS 7, macOS 10.9
#if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED > 70000) || (defined(MAC_OS_X_VERSION_MIN_REQUIRED) && MAC_OS_X_VERSION_MIN_REQUIRED > 1090)
NS_DESIGNATED_INITIALIZER
#endif
;
@property (assign) HANDLE rarFile;
@property (assign) struct RARHeaderDataEx *header;
@property (assign) struct RAROpenArchiveDataEx *flags;
@property (strong) NSData *fileBookmark;
@property (strong) NSObject *threadLock;
@property (copy) NSString *lastArchivePath;
@property (copy) NSString *lastFilepath;
@end
@implementation URKArchive
#pragma mark - Deprecated Convenience Methods
+ (URKArchive *)rarArchiveAtPath:(NSString *)filePath
{
return [[URKArchive alloc] initWithPath:filePath error:nil];
}
+ (URKArchive *)rarArchiveAtURL:(NSURL *)fileURL
{
return [[URKArchive alloc] initWithURL:fileURL error:nil];
}
+ (URKArchive *)rarArchiveAtPath:(NSString *)filePath password:(NSString *)password
{
return [[URKArchive alloc] initWithPath:filePath password:password error:nil];
}
+ (URKArchive *)rarArchiveAtURL:(NSURL *)fileURL password:(NSString *)password
{
return [[URKArchive alloc] initWithURL:fileURL password:password error:nil];
}
#pragma mark - Initializers
+ (void)initialize {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSBundle *mainBundle = [NSBundle mainBundle];
NSURL *resourcesURL = [mainBundle URLForResource:@"UnrarKitResources" withExtension:@"bundle"];
_resources = (resourcesURL
? [NSBundle bundleWithURL:resourcesURL]
: mainBundle);
URKLogInit();
});
}
- (instancetype)init {
URKLogError("Attempted to use -init method, which is no longer supported");
@throw [NSException exceptionWithName:NSInternalInconsistencyException
reason:@"-init is not a valid initializer for the class URKArchive"
userInfo:nil];
return nil;
}
- (instancetype)initWithPath:(NSString *)filePath error:(NSError * __autoreleasing *)error
{
return [self initWithFile:[NSURL fileURLWithPath:filePath] error:error];
}
- (instancetype)initWithURL:(NSURL *)fileURL error:(NSError * __autoreleasing *)error
{
return [self initWithFile:fileURL error:error];
}
- (instancetype)initWithPath:(NSString *)filePath password:(NSString *)password error:(NSError * __autoreleasing *)error
{
return [self initWithFile:[NSURL fileURLWithPath:filePath] password:password error:error];
}
- (instancetype)initWithURL:(NSURL *)fileURL password:(NSString *)password error:(NSError * __autoreleasing *)error
{
return [self initWithFile:fileURL password:password error:error];
}
- (instancetype)initWithFile:(NSURL *)fileURL error:(NSError * __autoreleasing *)error
{
return [self initWithFile:fileURL password:nil error:error];
}
- (instancetype)initWithFile:(NSURL *)fileURL password:(NSString*)password error:(NSError * __autoreleasing *)error
{
URKCreateActivity("Init Archive");
URKLogInfo("Initializing archive with URL %{public}@, path %{public}@, password %{public}@", fileURL, fileURL.path, [password length] != 0 ? @"given" : @"not given");
if (!fileURL) {
URKLogError("Cannot initialize archive with nil URL");
return nil;
}
if ((self = [super init])) {
if (error) {
*error = nil;
}
NSURL *firstVolumeURL = [URKArchive firstVolumeURL:fileURL];
NSString * _Nonnull fileURLAbsoluteString = static_cast<NSString * _Nonnull>(fileURL.absoluteString);
if (firstVolumeURL && ![firstVolumeURL.absoluteString isEqualToString:fileURLAbsoluteString]) {
URKLogDebug("Overriding fileURL with first volume URL: %{public}@", firstVolumeURL);
fileURL = firstVolumeURL;
}
URKLogDebug("Initializing private fields");
NSError *bookmarkError = nil;
_fileBookmark = [fileURL bookmarkDataWithOptions:0
includingResourceValuesForKeys:@[]
relativeToURL:nil
error:&bookmarkError];
_password = password;
_threadLock = [[NSObject alloc] init];
_lastArchivePath = nil;
_lastFilepath = nil;
_ignoreCRCMismatches = NO;
if (bookmarkError) {
URKLogFault("Error creating bookmark to RAR archive: %{public}@", bookmarkError);
if (error) {
*error = bookmarkError;
}
return nil;
}
}
return self;
}
#pragma mark - Properties
- (NSURL *)fileURL
{
URKCreateActivity("Read Archive URL");
BOOL bookmarkIsStale = NO;
NSError *error = nil;
NSURL *result = [NSURL URLByResolvingBookmarkData:self.fileBookmark
options:0
relativeToURL:nil
bookmarkDataIsStale:&bookmarkIsStale
error:&error];
if (error) {
URKLogFault("Error resolving bookmark to RAR archive: %{public}@", error);
return nil;
}
if (bookmarkIsStale) {
URKLogDebug("Refreshing stale bookmark");
self.fileBookmark = [result bookmarkDataWithOptions:0
includingResourceValuesForKeys:@[]
relativeToURL:nil
error:&error];
if (error) {
URKLogFault("Error creating fresh bookmark to RAR archive: %{public}@", error);
}
}
return result;
}
- (NSString *)filename
{
URKCreateActivity("Read Archive Filename");
NSURL *url = self.fileURL;
if (!url) {
return nil;
}
return url.path;
}
- (NSNumber *)uncompressedSize
{
URKCreateActivity("Read Archive Uncompressed Size");
NSError *listError = nil;
NSArray *fileInfo = [self listFileInfo:&listError];
if (!fileInfo) {
URKLogError("Error getting uncompressed size: %{public}@", listError);
return nil;
}
if (fileInfo.count == 0) {
URKLogInfo("No files in archive. Size == 0");
return 0;
}
return [fileInfo valueForKeyPath:@"@sum.uncompressedSize"];
}
- (NSNumber *)compressedSize
{
URKCreateActivity("Read Archive Compressed Size");
NSString *filePath = self.filename;
if (!filePath) {
URKLogError("Can't get compressed size, since a file path can't be resolved");
return nil;
}
URKLogInfo("Reading archive file attributes...");
NSError *attributesError = nil;
NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath
error:&attributesError];
if (!attributes) {
URKLogError("Error getting compressed size of %{public}@: %{public}@", filePath, attributesError);
return nil;
}
return [NSNumber numberWithUnsignedLongLong:attributes.fileSize];
}
- (BOOL)hasMultipleVolumes
{
URKCreateActivity("Check If Multi-Volume Archive");
NSError *listError = nil;
NSArray<NSURL*> *volumeURLs = [self listVolumeURLs:&listError];
if (!volumeURLs) {
URKLogError("Error getting file volumes list: %{public}@", listError);
return false;
}
return volumeURLs.count > 1;
}
#pragma mark - Zip file detection
+ (BOOL)pathIsARAR:(NSString *)filePath
{
URKCreateActivity("Determining File Type (Path)");
NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:filePath];
if (!handle) {
URKLogError("No file handle returned for path: %{public}@", filePath);
return NO;
}
@try {
NSData *fileData = [handle readDataOfLength:8];
if (fileData.length < 8) {
URKLogDebug("No file handle returned for path: %{public}@", filePath);
return NO;
}
const unsigned char *dataBytes = (const unsigned char *)fileData.bytes;
// Check the magic numbers for all versions (Rar!..)
if (dataBytes[0] != 0x52 ||
dataBytes[1] != 0x61 ||
dataBytes[2] != 0x72 ||
dataBytes[3] != 0x21 ||
dataBytes[4] != 0x1A ||
dataBytes[5] != 0x07) {
URKLogDebug("File is not a RAR. Magic numbers != 'Rar!..'");
return NO;
}
// Check for v1.5 and on
if (dataBytes[6] == 0x00) {
URKLogDebug("File is a RAR >= v1.5");
return YES;
}
// Check for v5.0
if (dataBytes[6] == 0x01 &&
dataBytes[7] == 0x00) {
URKLogDebug("File is a RAR >= v5.0");
return YES;
}
URKLogDebug("File is not a RAR. Unknown contents in 7th and 8th bytes (%02X %02X)", dataBytes[6], dataBytes[7]);
}
@catch (NSException *e) {
URKLogError("Error checking if %{public}@ is a RAR archive: %{public}@", filePath, e);
}
@finally {
[handle closeFile];
}
return NO;
}
+ (BOOL)urlIsARAR:(NSURL *)fileURL
{
URKCreateActivity("Determining File Type (URL)");
if (!fileURL || !fileURL.path) {
URKLogDebug("File is not a RAR: nil URL or path");
return NO;
}
NSString *_Nonnull path = static_cast<NSString *_Nonnull>(fileURL.path);
return [URKArchive pathIsARAR:path];
}
#pragma mark - Public Methods
- (NSArray<NSString*> *)listFilenames:(NSError * __autoreleasing *)error
{
URKCreateActivity("Listing Filenames");
NSArray *files = [self listFileInfo:error];
return [files valueForKey:@"filename"];
}
- (NSArray<URKFileInfo*> *)listFileInfo:(NSError * __autoreleasing *)error
{
URKCreateActivity("Listing File Info");
NSMutableSet<NSString*> *distinctFilenames = [NSMutableSet set];
NSMutableArray<URKFileInfo*> *distinctFileInfo = [NSMutableArray array];
NSError *innerError = nil;
BOOL wasSuccessful = [self iterateFileInfo:^(URKFileInfo * _Nonnull fileInfo, BOOL * _Nonnull stop) {
if (![distinctFilenames containsObject:fileInfo.filename]) {
[distinctFileInfo addObject:fileInfo];
[distinctFilenames addObject:fileInfo.filename];
} else {
URKLogDebug("Skipping %{public}@ from list of file info, since it's already represented (probably from another archive volume)", fileInfo.filename);
}
}
error:&innerError];
if (!wasSuccessful) {
URKLogError("Failed to iterate file info: %{public}@", innerError);
if (error && innerError) {
*error = innerError;
}
return nil;
}
URKLogDebug("Found %lu file info items", (unsigned long)distinctFileInfo.count);
return [NSArray arrayWithArray:distinctFileInfo];
}
- (BOOL) iterateFileInfo:(void(^)(URKFileInfo *fileInfo, BOOL *stop))action
error:(NSError * __autoreleasing *)error
{
URKCreateActivity("Iterating File Info");
NSAssert(action != nil, @"'action' is a required argument");
NSError *innerError = nil;
URKLogDebug("Beginning to iterate through contents of %{public}@", self.filename);
BOOL wasSuccessful = [self iterateAllFileInfo:action
error:&innerError];
if (!wasSuccessful) {
URKLogError("Failed to iterate all file info: %{public}@", innerError);
if (error && innerError) {
*error = innerError;
}
return NO;
}
return YES;
}
- (nullable NSArray<NSURL*> *)listVolumeURLs:(NSError * __autoreleasing *)error
{
URKCreateActivity("Listing Volume URLs");
NSArray<URKFileInfo*> *allFileInfo = [self allFileInfo:error];
if (!allFileInfo) {
return nil;
}
NSMutableSet<NSURL*> *volumeURLs = [[NSMutableSet alloc] init];
for (URKFileInfo* info in allFileInfo) {
NSURL *archiveURL = [NSURL fileURLWithPath:info.archiveName];
if (archiveURL) {
[volumeURLs addObject:archiveURL];
}
}
SEL sortBySelector = @selector(path);
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:NSStringFromSelector(sortBySelector) ascending:YES];
NSArray<NSURL*> *sortedVolumes = [volumeURLs sortedArrayUsingDescriptors:@[sortDescriptor]];
return sortedVolumes;
}
- (BOOL)extractFilesTo:(NSString *)filePath
overwrite:(BOOL)overwrite
error:(NSError * __autoreleasing *)error
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
return [self extractFilesTo:filePath
overwrite:overwrite
progress:nil
error:error];
#pragma clang diagnostic pop
}
- (BOOL)extractFilesTo:(NSString *)filePath
overwrite:(BOOL)overwrite
progress:(void (^)(URKFileInfo *currentFile, CGFloat percentArchiveDecompressed))progressBlock
error:(NSError * __autoreleasing *)error
{
URKCreateActivity("Extracting Files to Directory");
__block BOOL result = YES;
NSError *listError = nil;
NSArray *fileInfos = [self listFileInfo:&listError];
if (!fileInfos || listError) {
URKLogError("Error listing contents of archive: %{public}@", listError);
if (error) {
*error = listError;
}
return NO;
}
NSNumber *totalSize = [fileInfos valueForKeyPath:@"@sum.uncompressedSize"];
__block long long bytesDecompressed = 0;
NSProgress *progress = [self beginProgressOperation:totalSize.longLongValue];
progress.kind = NSProgressKindFile;
URKLogDebug("Archive has total size of %{iec-bytes}lld", totalSize.longLongValue);
__weak URKArchive *welf = self;
BOOL success = [self performActionWithArchiveOpen:^(NSError **innerError) {
URKCreateActivity("Performing File Extraction");
int RHCode = 0, PFCode = 0, filesExtracted = 0;
URKFileInfo *fileInfo;
URKLogInfo("Extracting to %{public}@", filePath);
URKLogDebug("Reading through RAR header looking for files...");
while ([welf readHeader:&RHCode info:&fileInfo] == URKReadHeaderLoopActionContinueReading) {
URKLogDebug("Extracting %{public}@ (%{iec-bytes}lld)", fileInfo.filename, fileInfo.uncompressedSize);
NSURL *extractedURL = [[NSURL fileURLWithPath:filePath] URLByAppendingPathComponent:fileInfo.filename];
[progress setUserInfoObject:extractedURL
forKey:NSProgressFileURLKey];
[progress setUserInfoObject:fileInfo
forKey:URKProgressInfoKeyFileInfoExtracting];
if ([welf headerContainsErrors:innerError]) {
URKLogError("Header contains an error")
result = NO;
return;
}
if (progress.isCancelled) {
NSString *errorName = nil;
[welf assignError:innerError code:URKErrorCodeUserCancelled errorName:&errorName];
URKLogInfo("Halted file extraction due to user cancellation: %{public}@", errorName);
result = NO;
return;
}
char cFilePath[2048];
BOOL utf8ConversionSucceeded = [filePath getCString:cFilePath
maxLength:sizeof(cFilePath)
encoding:NSUTF8StringEncoding];
if (!utf8ConversionSucceeded) {
NSString *errorName = nil;
[welf assignError:innerError code:URKErrorCodeStringConversion errorName:&errorName];
URKLogError("Error converting file to UTF-8 (buffer too short?)");
result = NO;
return;
}
BOOL (^shouldCancelBlock)() = ^BOOL {
URKCreateActivity("shouldCancelBlock");
URKLogDebug("Progress.isCancelled: %{public}@", progress.isCancelled ? @"YES" : @"NO")
return progress.isCancelled;
};
RARSetCallback(welf.rarFile, AllowCancellationCallbackProc, (long)shouldCancelBlock);
PFCode = RARProcessFile(welf.rarFile, RAR_EXTRACT, cFilePath, NULL);
if (![welf didReturnSuccessfully:PFCode]) {
RARSetCallback(welf.rarFile, NULL, NULL);
NSString *errorName = nil;
NSInteger errorCode = progress.isCancelled ? URKErrorCodeUserCancelled : PFCode;
[welf assignError:innerError code:errorCode errorName:&errorName];
URKLogError("Error extracting file: %{public}@ (%ld)", errorName, (long)errorCode);
result = NO;
return;
}
[progress setUserInfoObject:@(++filesExtracted)
forKey:NSProgressFileCompletedCountKey];
[progress setUserInfoObject:@(fileInfos.count)
forKey:NSProgressFileTotalCountKey];
progress.completedUnitCount += fileInfo.uncompressedSize;
URKLogDebug("Finished extracting %{public}@. Extraction %f complete", fileInfo.filename, progress.fractionCompleted);
if (progressBlock) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdouble-promotion"
// I would change the signature of this block, but it's been deprecated already,
// so it'll just get dropped eventually, and it made sense to silence the warning
progressBlock(fileInfo, bytesDecompressed / totalSize.floatValue);
#pragma clang diagnostic pop
}
bytesDecompressed += fileInfo.uncompressedSize;
}
RARSetCallback(welf.rarFile, NULL, NULL);
if (![welf didReturnSuccessfully:RHCode]) {
NSString *errorName = nil;
[welf assignError:innerError code:RHCode errorName:&errorName];
URKLogError("Error reading file header: %{public}@ (%d)", errorName, RHCode);
result = NO;
}
if (progressBlock) {
progressBlock(fileInfo, 1.0);
}
} inMode:RAR_OM_EXTRACT error:error];
return success && result;
}
- (NSData *)extractData:(URKFileInfo *)fileInfo
error:(NSError * __autoreleasing *)error
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
return [self extractDataFromFile:fileInfo.filename progress:nil error:error];
#pragma clang diagnostic pop
}
- (NSData *)extractData:(URKFileInfo *)fileInfo
progress:(void (^)(CGFloat percentDecompressed))progressBlock
error:(NSError * __autoreleasing *)error
{
return [self extractDataFromFile:fileInfo.filename progress:progressBlock error:error];
}
- (NSData *)extractDataFromFile:(NSString *)filePath
error:(NSError * __autoreleasing *)error
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
return [self extractDataFromFile:filePath progress:nil error:error];
#pragma clang diagnostic pop
}
- (NSData *)extractDataFromFile:(NSString *)filePath
progress:(void (^)(CGFloat percentDecompressed))progressBlock
error:(NSError * __autoreleasing *)error
{
URKCreateActivity("Extracting Data from File");
NSProgress *progress = [self beginProgressOperation:0];
__block NSData *result = nil;
__weak URKArchive *welf = self;
BOOL success = [self performActionWithArchiveOpen:^(NSError **innerError) {
URKCreateActivity("Performing Extraction");
int RHCode = 0, PFCode = 0;
URKFileInfo *fileInfo;
URKLogDebug("Reading through RAR header looking for files...");
while ([welf readHeader:&RHCode info:&fileInfo] == URKReadHeaderLoopActionContinueReading) {
if ([welf headerContainsErrors:innerError]) {
URKLogError("Header contains an error")
return;
}
if ([fileInfo.filename isEqualToString:filePath]) {
URKLogDebug("Extracting %{public}@", fileInfo.filename);
break;
}
else {
URKLogDebug("Skipping %{public}@", fileInfo.filename);
if ((PFCode = RARProcessFileW(welf.rarFile, RAR_SKIP, NULL, NULL)) != 0) {
NSString *errorName = nil;
[welf assignError:innerError code:(NSInteger)PFCode errorName:&errorName];
URKLogError("Error skipping file: %{public}@ (%d)", errorName, PFCode);
return;
}
}
}
if (RHCode != ERAR_SUCCESS) {
NSString *errorName = nil;
[welf assignError:innerError code:RHCode errorName:&errorName];
URKLogError("Error reading file header: %{public}@ (%d)", errorName, RHCode);
return;
}
// Empty file, or a directory
if (fileInfo.uncompressedSize == 0) {
URKLogDebug("%{public}@ is empty or a directory", fileInfo.filename);
result = [NSData data];
return;
}
NSMutableData *fileData = [NSMutableData dataWithCapacity:(NSUInteger)fileInfo.uncompressedSize];
CGFloat totalBytes = fileInfo.uncompressedSize;
progress.totalUnitCount = totalBytes;
__block long long bytesRead = 0;
if (progressBlock) {
progressBlock(0.0);
}
BOOL (^bufferedReadBlock)(NSData*) = ^BOOL(NSData *dataChunk) {
URKLogDebug("Appending buffered data (%lu bytes)", (unsigned long)dataChunk.length);
[fileData appendData:dataChunk];
progress.completedUnitCount += dataChunk.length;
bytesRead += dataChunk.length;
if (progressBlock) {
progressBlock(bytesRead / totalBytes);
}
if (progress.isCancelled) {
URKLogInfo("Cancellation initiated");
return NO;
}
return YES;
};
RARSetCallback(welf.rarFile, BufferedReadCallbackProc, (long)bufferedReadBlock);
URKLogInfo("Processing file...");
PFCode = RARProcessFile(welf.rarFile, RAR_TEST, NULL, NULL);
RARSetCallback(welf.rarFile, NULL, NULL);
if (progress.isCancelled) {
NSString *errorName = nil;
[welf assignError:innerError code:URKErrorCodeUserCancelled errorName:&errorName];
URKLogInfo("Returning nil data from extraction due to user cancellation: %{public}@", errorName);
return;
}
if (![welf didReturnSuccessfully:PFCode]) {
NSString *errorName = nil;
[welf assignError:innerError code:(NSInteger)PFCode errorName:&errorName];
URKLogError("Error extracting file data: %{public}@ (%d)", errorName, PFCode);
return;
}
result = [NSData dataWithData:fileData];
} inMode:RAR_OM_EXTRACT error:error];
if (!success) {
return nil;
}
return result;
}
- (BOOL)performOnFilesInArchive:(void(^)(URKFileInfo *fileInfo, BOOL *stop))action
error:(NSError * __autoreleasing *)error
{
URKCreateActivity("Performing Action on Each File");
URKLogInfo("Listing file info");
NSError *listError = nil;
NSArray *fileInfo = [self listFileInfo:&listError];
if (listError || !fileInfo) {
URKLogError("Failed to list the files in the archive: %{public}@", listError);
if (error) {
*error = listError;
}
return NO;
}
NSProgress *progress = [self beginProgressOperation:fileInfo.count];
URKLogInfo("Sorting file info by name/path");
NSArray *sortedFileInfo = [fileInfo sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"filename" ascending:YES]]];
{
URKCreateActivity("Iterating Each File Info");
[sortedFileInfo enumerateObjectsUsingBlock:^(URKFileInfo *info, NSUInteger idx, BOOL *stop) {
if (progress.isCancelled) {
URKLogInfo("PerformOnFiles iteration was cancelled");
*stop = YES;
}
URKLogDebug("Performing action on %{public}@", info.filename);
action(info, stop);
progress.completedUnitCount += 1;
if (*stop) {
URKLogInfo("Action dictated an early stop");
progress.completedUnitCount = progress.totalUnitCount;
}
}];
}
return YES;
}
- (BOOL)performOnDataInArchive:(void (^)(URKFileInfo *, NSData *, BOOL *))action
error:(NSError * __autoreleasing *)error
{
URKCreateActivity("Performing Action on Each File's Data");
NSError *listError = nil;
NSArray *fileInfo = [self listFileInfo:&listError];
if (!fileInfo || listError) {
URKLogError("Error listing contents of archive: %{public}@", listError);
if (error) {
*error = listError;
}
return NO;
}
NSNumber *totalSize = [fileInfo valueForKeyPath:@"@sum.uncompressedSize"];
__weak URKArchive *welf = self;
BOOL success = [self performActionWithArchiveOpen:^(NSError **innerError) {
int RHCode = 0, PFCode = 0;
BOOL stop = NO;
NSProgress *progress = [welf beginProgressOperation:totalSize.longLongValue];
URKLogDebug("Reading through RAR header looking for files...");
URKFileInfo *info = nil;
while ([welf readHeader:&RHCode info:&info] == URKReadHeaderLoopActionContinueReading) {
if (stop || progress.isCancelled) {
URKLogDebug("Action dictated an early stop");
return;
}
if ([welf headerContainsErrors:innerError]) {
URKLogError("Header contains an error")
return;
}
URKLogDebug("Performing action on %{public}@", info.filename);
// Empty file, or a directory
if (info.isDirectory || info.uncompressedSize == 0) {
URKLogDebug("%{public}@ is an empty file, or a directory", info.filename);
action(info, [NSData data], &stop);
PFCode = RARProcessFile(welf.rarFile, RAR_SKIP, NULL, NULL);
if (PFCode != 0) {
NSString *errorName = nil;
[welf assignError:innerError code:(NSInteger)PFCode errorName:&errorName];
URKLogError("Error skipping directory: %{public}@ (%d)", errorName, PFCode);
return;
}
continue;
}
UInt8 *buffer = (UInt8 *)malloc((size_t)info.uncompressedSize * sizeof(UInt8));
UInt8 *callBackBuffer = buffer;
RARSetCallback(welf.rarFile, CallbackProc, (long) &callBackBuffer);
URKLogInfo("Processing file...");
PFCode = RARProcessFile(welf.rarFile, RAR_TEST, NULL, NULL);
if (![welf didReturnSuccessfully:PFCode]) {
NSString *errorName = nil;
[welf assignError:innerError code:(NSInteger)PFCode errorName:&errorName];
URKLogError("Error processing file: %{public}@ (%d)", errorName, PFCode);
return;
}
URKLogDebug("Performing action on data (%lld bytes)", info.uncompressedSize);
NSData *data = [NSData dataWithBytesNoCopy:buffer length:(NSUInteger)info.uncompressedSize freeWhenDone:YES];
action(info, data, &stop);
progress.completedUnitCount += data.length;
}
if (progress.isCancelled) {
NSString *errorName = nil;
[welf assignError:innerError code:URKErrorCodeUserCancelled errorName:&errorName];
URKLogInfo("Returning NO from performOnData:error: due to user cancellation: %{public}@", errorName);
return;
}
if (![welf didReturnSuccessfully:RHCode]) {
NSString *errorName = nil;
[welf assignError:innerError code:RHCode errorName:&errorName];
URKLogError("Error reading file header: %{public}@ (%d)", errorName, RHCode);
return;
}
} inMode:RAR_OM_EXTRACT error:error];
return success;
}
- (BOOL)extractBufferedDataFromFile:(NSString *)filePath
error:(NSError * __autoreleasing *)error
action:(void(^)(NSData *dataChunk, CGFloat percentDecompressed))action
{
URKCreateActivity("Extracting Buffered Data");
NSError *actionError = nil;
NSProgress *progress = [self beginProgressOperation:0];
__weak URKArchive *welf = self;
BOOL success = [self performActionWithArchiveOpen:^(NSError **innerError) {
URKCreateActivity("Performing action");
int RHCode = 0, PFCode = 0;
URKFileInfo *fileInfo;
URKLogInfo("Looping through files, looking for %{public}@...", filePath);
while ([welf readHeader:&RHCode info:&fileInfo] == URKReadHeaderLoopActionContinueReading) {
if ([welf headerContainsErrors:innerError]) {
URKLogDebug("Header contains error")
return;
}
if ([fileInfo.filename isEqualToString:filePath]) {
URKLogDebug("Found desired file");
break;
}
else {
URKLogDebug("Skipping file...");
PFCode = RARProcessFile(welf.rarFile, RAR_SKIP, NULL, NULL);
if (![welf didReturnSuccessfully:PFCode]) {
NSString *errorName = nil;
[welf assignError:innerError code:(NSInteger)PFCode errorName:&errorName];
URKLogError("Failed to skip file: %{public}@ (%d)", errorName, PFCode);
return;
}
}
}
long long totalBytes = fileInfo.uncompressedSize;
progress.totalUnitCount = totalBytes;
if (![welf didReturnSuccessfully:RHCode]) {
NSString *errorName = nil;
[welf assignError:innerError code:RHCode errorName:&errorName];
URKLogError("Header read yielded error: %{public}@ (%d)", errorName, RHCode);
return;
}
// Empty file, or a directory
if (totalBytes == 0) {
URKLogInfo("File is empty or a directory");
return;
}
__block long long bytesRead = 0;
// Repeating the argument instead of using positional specifiers, because they don't work with the {} formatters
URKLogDebug("Uncompressed size: %{iec-bytes}lld (%lld bytes) in file", totalBytes, totalBytes);
BOOL (^bufferedReadBlock)(NSData*) = ^BOOL(NSData *dataChunk) {
if (progress.isCancelled) {
URKLogInfo("Buffered data read cancelled");
return NO;
}
bytesRead += dataChunk.length;
progress.completedUnitCount += dataChunk.length;
double progressPercent = bytesRead / static_cast<double>(totalBytes);
URKLogDebug("Read data chunk of size %lu (%.3f%% complete). Calling handler...", (unsigned long)dataChunk.length, progressPercent * 100);
action(dataChunk, progressPercent);
return YES;
};
RARSetCallback(welf.rarFile, BufferedReadCallbackProc, (long)bufferedReadBlock);
URKLogDebug("Processing file...");
PFCode = RARProcessFile(welf.rarFile, RAR_TEST, NULL, NULL);
RARSetCallback(welf.rarFile, NULL, NULL);
if (progress.isCancelled) {
NSString *errorName = nil;
[welf assignError:innerError code:URKErrorCodeUserCancelled errorName:&errorName];
URKLogError("Buffered data extraction has been cancelled: %{public}@", errorName);
return;
}
if (![welf didReturnSuccessfully:PFCode]) {
NSString *errorName = nil;
[welf assignError:innerError code:(NSInteger)PFCode errorName:&errorName];
URKLogError("Error processing file: %{public}@ (%d)", errorName, PFCode);
}
} inMode:RAR_OM_EXTRACT error:&actionError];
if (error) {