This repository has been archived by the owner on Oct 3, 2020. It is now read-only.
/
BackupController.m
1735 lines (1506 loc) · 66.1 KB
/
BackupController.m
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
/*
This file is part the backup utility Mathusalem for Mac OS X.
Copyright (C) 2008-2009 Pierre-Olivier Latour <info@pol-online.net>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#import <dirent.h>
#import <sys/stat.h>
#import "BackupController.h"
#import "FileTransferController.h"
#import "DiskImageController.h"
#import "DirectoryScanner.h"
#import "Task.h"
#import "NSData+Encryption.h"
#import "NSData+GZip.h"
#import "Keychain.h"
#import "NSURL+Parameters.h"
#define __FAST_FILE_SCHEME__ 1
#define __FORWARD_FILETRANSFERCONTROLLER_ERRORS__ 0
#define kBackupPrefix @"Revision-"
#define kBackupFormat kBackupPrefix "%05i"
#define kSegmentFormat @"-Part-%03i"
#define kBOMFileExtension @"xml.gz"
#define kDittoToolPath @"/usr/bin/ditto"
#define kDiskSpaceMargin 1 //percents
#define CHECK_IMMEDIATE_ABORT() { if([_delegate backupControllerShouldAbort:self]) goto Exit; }
#define MAKE_TMP_PATH() [_scratchDir stringByAppendingPathComponent:[[NSProcessInfo processInfo] globallyUniqueString]]
#define UPDATE_STATUS(_STATUS_, _VALUE_, _MAX_) { \
_currentStatus = _STATUS_; \
[_delegate backupController:self didUpdateStatus:_currentStatus currentValue:_VALUE_ maxValue:_MAX_]; \
}
#define REPORT_SCANNING_ERROR(_PATHS_, _FATAL_) { \
if(_delegate) { \
NSDictionary* info = [NSDictionary dictionaryWithObjectsAndKeys:_PATHS_, kBackupControllerPathsKey, [NSNumber numberWithBool:_FATAL_], kBackupControllerFatalErrorKey, nil]; \
[_delegate backupController:self errorDidOccur:[NSError errorWithDomain:kBackupControllerErrorDomain code:kBackupControllerErrorCode_Scanning userInfo:info]]; \
} \
}
#define REPORT_GENERIC_ERROR(_CODE_, _ERROR_, _FATAL_, _PATH_, _OTHER_PATH_) { \
if(_delegate) { \
NSArray* paths = [NSArray arrayWithObjects:_PATH_, _OTHER_PATH_, nil]; \
NSDictionary* info = [NSDictionary dictionaryWithObjectsAndKeys:paths, kBackupControllerPathsKey, [NSNumber numberWithBool:_FATAL_], kBackupControllerFatalErrorKey, _ERROR_, NSUnderlyingErrorKey, nil]; \
[_delegate backupController:self errorDidOccur:[NSError errorWithDomain:kBackupControllerErrorDomain code:_CODE_ userInfo:info]]; \
} \
}
@interface NSFileManager (BackupController)
@end
@interface BackupController () <FileTransferControllerDelegate>
- (NSDictionary*) _diffDirectories:(NSDictionary*)parameters reverse:(BOOL)reverse;
- (DirectoryScanner*) _scannerForRevision:(NSUInteger)revision fileTransferController:(FileTransferController*)transferController;
@end
@implementation NSFileManager (BackupController)
- (BOOL) copyFileUnlockedAtPath:(NSString*)srcPath toPath:(NSString*)dstPath error:(NSError**)error
{
static NSDictionary* attributes = nil;
if(![self copyItemAtPath:srcPath toPath:dstPath error:error])
return NO;
if([[[self attributesOfItemAtPath:dstPath error:NULL] objectForKey:NSFileImmutable] boolValue]) {
if(attributes == nil)
attributes = [[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:NSFileImmutable] retain];
[self setAttributes:attributes ofItemAtPath:dstPath error:error];
}
return YES;
}
@end
@implementation BackupController
@synthesize delegate=_delegate, scratchDirectory=_scratchDir;
+ (BackupController*) sharedBackupController
{
static BackupController* controller = nil;
if(controller == nil)
controller = [BackupController new];
return controller;
}
+ (NSOperation*) backupOperationWithCommand:(NSString*)command parameters:(NSDictionary*)parameters delegate:(id<BackupOperationDelegate>)delegate
{
BackupController* controller;
NSMutableDictionary* arguments;
controller = [[BackupController new] autorelease];
[controller setDelegate:delegate];
arguments = [NSMutableDictionary dictionaryWithDictionary:parameters];
[arguments setObject:command forKey:@""];
return [[[NSInvocationOperation alloc] initWithTarget:controller selector:@selector(_runOperation:) object:arguments] autorelease];
}
- (void) _runOperation:(NSMutableDictionary*)arguments
{
NSString* command;
id result;
command = [[[arguments objectForKey:@""] retain] autorelease];
[arguments removeObjectForKey:@""];
[(id<BackupOperationDelegate>)[self delegate] backupController:self didStartCommand:command parameters:arguments];
@try {
result = [self performSelector:NSSelectorFromString([command stringByAppendingString:@":"]) withObject:arguments];
}
@catch(NSException* localException) {
NSLog(@"<IGNORED EXCEPTION DURING '%@' OPERATION>\n%@", command, localException);
result = nil;
}
[(id<BackupOperationDelegate>)[self delegate] backupController:self didFinishCommand:command parameters:arguments result:result];
}
- (id) init
{
if((self = [super init]))
_scratchDir = [NSTemporaryDirectory() copy];
return self;
}
- (void) dealloc
{
[_scratchDir release];
[super dealloc];
}
- (BOOL) fileManager:(NSFileManager*)fileManager shouldProceedAfterError:(NSError*)error removingItemAtPath:(NSString*)path
{
return YES;
}
- (id) scan:(NSDictionary*)parameters
{
NSArray* array;
DirectoryScanner* scanner;
NSDictionary* results;
//Create a directory scanner with passed parameters
scanner = [[DirectoryScanner alloc] initWithRootDirectory:[parameters objectForKey:@"source"] scanMetadata:NO];
[scanner setSortPaths:YES];
[scanner setExcludeHiddenItems:[[parameters objectForKey:@"excludeHidden"] boolValue]];
[scanner setExclusionPredicate:[DirectoryScanner exclusionPredicateWithPaths:[parameters objectForKey:@"excludePath"] names:[parameters objectForKey:@"excludeName"]]];
//Scan root and subdirectories
results = [scanner scanRootDirectory];
if(results) {
if((array = [results objectForKey:kDirectoryScannerResultKey_ErrorPaths]))
REPORT_SCANNING_ERROR(array, NO);
array = [scanner subpathsOfRootDirectory];
}
else {
REPORT_SCANNING_ERROR([NSArray arrayWithObject:[parameters objectForKey:@"source"]], YES);
array = nil;
}
//Clean up
[scanner release];
return [array description];
}
- (NSDictionary*) _diffDirectories:(NSDictionary*)parameters reverse:(BOOL)reverse
{
DirectoryScanner* scanner;
DirectoryScanner* otherScanner;
NSDictionary* results;
NSArray* array;
//Create a directory scanner with passed parameters for the source directory
scanner = [[DirectoryScanner alloc] initWithRootDirectory:[parameters objectForKey:@"source"] scanMetadata:NO];
[scanner setSortPaths:YES];
[scanner setExcludeHiddenItems:[[parameters objectForKey:@"excludeHidden"] boolValue]];
[scanner setExclusionPredicate:[DirectoryScanner exclusionPredicateWithPaths:[parameters objectForKey:@"excludePath"] names:[parameters objectForKey:@"excludeName"]]];
//Create a directory scanner with passed parameters for the target directory
otherScanner = [[DirectoryScanner alloc] initWithRootDirectory:[parameters objectForKey:@"target"] scanMetadata:NO];
[otherScanner setSortPaths:YES];
[otherScanner setExcludeHiddenItems:[[parameters objectForKey:@"excludeHidden"] boolValue]];
[otherScanner setExclusionPredicate:[DirectoryScanner exclusionPredicateWithPaths:[parameters objectForKey:@"excludePath"] names:[parameters objectForKey:@"excludeName"]]];
//Scan source root and subdirectories
results = [scanner scanRootDirectory];
if(results) {
if((array = [results objectForKey:kDirectoryScannerResultKey_ErrorPaths]))
REPORT_SCANNING_ERROR(array, NO);
//Scan target root and subdirectories
results = [otherScanner scanRootDirectory];
if(results) {
if((array = [results objectForKey:kDirectoryScannerResultKey_ErrorPaths]))
REPORT_SCANNING_ERROR(array, NO);
//Compare the two scanners
results = (reverse ? [otherScanner compare:scanner options:kDirectoryScannerOption_OnlyReportTopLevelRemovedItems] : [scanner compare:otherScanner options:kDirectoryScannerOption_OnlyReportTopLevelRemovedItems]);
}
else
REPORT_SCANNING_ERROR([NSArray arrayWithObject:[parameters objectForKey:@"target"]], YES);
}
else
REPORT_SCANNING_ERROR([NSArray arrayWithObject:[parameters objectForKey:@"source"]], YES);
//Clean up
[otherScanner release];
[scanner release];
return results;
}
- (id) diff:(NSDictionary*)parameters
{
return [self _diffDirectories:parameters reverse:YES];
}
- (id) sync:(NSDictionary*)parameters
{
NSString* sourcePath = [[parameters objectForKey:@"source"] stringByStandardizingPath];
NSString* targetPath = [[parameters objectForKey:@"target"] stringByStandardizingPath];
BOOL success = YES;
NSAutoreleasePool* localPool = nil;
NSFileManager* manager;
NSDictionary* results;
NSArray* array;
DirectoryItem* item;
NSError* error;
NSUInteger count,
index;
//Create our custom file manager
manager = [[NSFileManager new] autorelease];
[manager setDelegate:self];
do {
CHECK_IMMEDIATE_ABORT();
//Create a local autorelease pool
[localPool release];
localPool = [NSAutoreleasePool new];
//Get differences between source & target
results = [self _diffDirectories:parameters reverse:NO];
if(results == nil) {
[localPool release];
goto Exit;
}
//Nothing to do if source and target are identical
if(![results count])
break;
//Prepare
count = [[results objectForKey:kDirectoryScannerResultKey_RemovedItems] count] + [[results objectForKey:kDirectoryScannerResultKey_ModifiedItems_Data] count] + [[results objectForKey:kDirectoryScannerResultKey_AddedItems] count];
index = 0;
UPDATE_STATUS(kBackupControllerStatus_CopyingFiles, index, count);
//Delete all removed items
array = [results objectForKey:kDirectoryScannerResultKey_RemovedItems];
for(item in array) {
CHECK_IMMEDIATE_ABORT();
++index;
UPDATE_STATUS(kBackupControllerStatus_CopyingFiles, index, count);
if(![manager removeItemAtPath:[targetPath stringByAppendingPathComponent:[item path]] error:&error]) {
success = NO;
REPORT_GENERIC_ERROR(kBackupControllerErrorCode_DeletingItem, error, NO, [targetPath stringByAppendingPathComponent:[item path]], nil);
}
}
//Delete then copy all modified items
array = [results objectForKey:kDirectoryScannerResultKey_ModifiedItems_Data];
for(item in array) {
CHECK_IMMEDIATE_ABORT();
++index;
UPDATE_STATUS(kBackupControllerStatus_CopyingFiles, index, count);
if(![manager removeItemAtPath:[targetPath stringByAppendingPathComponent:[item path]] error:&error]) {
success = NO;
REPORT_GENERIC_ERROR(kBackupControllerErrorCode_DeletingItem, error, NO, [targetPath stringByAppendingPathComponent:[item path]], nil);
continue;
}
if(![manager copyFileUnlockedAtPath:[sourcePath stringByAppendingPathComponent:[item path]] toPath:[targetPath stringByAppendingPathComponent:[item path]] error:&error]) {
success = NO;
REPORT_GENERIC_ERROR(kBackupControllerErrorCode_CopyingItem, error, NO, [sourcePath stringByAppendingPathComponent:[item path]], [targetPath stringByAppendingPathComponent:[item path]]);
}
}
//Copy all added items
array = [results objectForKey:kDirectoryScannerResultKey_AddedItems];
for(item in array) {
CHECK_IMMEDIATE_ABORT();
++index;
UPDATE_STATUS(kBackupControllerStatus_CopyingFiles, index, count);
if([item isDirectory]) {
if(![manager createDirectoryAtPath:[targetPath stringByAppendingPathComponent:[item path]] withIntermediateDirectories:NO attributes:nil error:&error]) {
success = NO;
REPORT_GENERIC_ERROR(kBackupControllerErrorCode_CreatingDirectory, error, NO, [targetPath stringByAppendingPathComponent:[item path]], nil);
}
}
else {
if(![manager copyFileUnlockedAtPath:[sourcePath stringByAppendingPathComponent:[item path]] toPath:[targetPath stringByAppendingPathComponent:[item path]] error:&error]) {
success = NO;
REPORT_GENERIC_ERROR(kBackupControllerErrorCode_CopyingItem, error, NO, [sourcePath stringByAppendingPathComponent:[item path]], [[targetPath stringByAppendingPathComponent:[item path]] UTF8String]);
}
}
}
UPDATE_STATUS(kBackupControllerStatus_Idle, 0, 0);
} while([[parameters objectForKey:kBackupScannerUserInfoKey_Atomic] boolValue]); //In atomic mode, keep syncing until there are no differences
[localPool release];
localPool = nil;
return [NSNumber numberWithBool:success];
Exit:
return nil;
}
- (void) fileTransferControllerDidStart:(FileTransferController*)controller
{
UPDATE_STATUS(_currentStatus, 0, [controller transferSize]);
}
- (void) fileTransferControllerDidFail:(FileTransferController*)controller withError:(NSError*)error
{
#if __FORWARD_FILETRANSFERCONTROLLER_ERRORS__
REPORT_GENERIC_ERROR(_currentStatus, error, NO, nil, nil);
#else
NSLog(@"%@ Failed with error:\n%@\n%@", controller, error, [error userInfo]);
#endif
}
- (BOOL) fileTransferControllerShouldAbort:(FileTransferController*)controller
{
return [_delegate backupControllerShouldAbortCurrentFileTransfer:self];
}
- (void) fileTransferControllerDidUpdateProgress:(FileTransferController*)controller
{
UPDATE_STATUS(_currentStatus, [controller transferProgress] * [controller transferSize], [controller transferSize]);
}
- (DirectoryScanner*) _scannerForRevision:(NSUInteger)revision fileTransferController:(FileTransferController*)transferController
{
NSFileManager* manager = [NSFileManager defaultManager];
DirectoryScanner* scanner = nil;
NSString* path;
NSError* error;
NSString* string;
id results;
BOOL success;
//Do we have a revision explicitely specified?
if(revision > 0) {
path = [[NSString stringWithFormat:kBackupFormat, revision] stringByAppendingPathExtension:kBOMFileExtension];
//Download the BOM file
#if __FAST_FILE_SCHEME__
if([transferController isMemberOfClass:[LocalTransferController class]])
string = [[[transferController baseURL] path] stringByAppendingPathComponent:path];
else
#endif
{
string = MAKE_TMP_PATH();
do {
UPDATE_STATUS(kBackupControllerStatus_DownloadingFile, 0, 0);
success = [transferController downloadFileFromPath:path toPath:string];
UPDATE_STATUS(kBackupControllerStatus_Idle, 0, 0);
} while(!success && ![_delegate backupControllerShouldAbort:self] && [_delegate backupController:self shouldRetryFileTransferWithURL:[transferController absoluteURLForRemotePath:path]]);
if(success == NO) {
if(![_delegate backupControllerShouldAbort:self])
REPORT_GENERIC_ERROR(kBackupControllerErrorCode_DownloadingFile, nil, YES, path, string);
goto Exit;
}
}
CHECK_IMMEDIATE_ABORT();
//Recreate the directory scanner from it
@try {
scanner = [[DirectoryScanner alloc] initWithFile:string];
}
@catch(NSException* localException) {
NSLog(@"%s: %@", __FUNCTION__, localException);
scanner = nil;
}
#if __FAST_FILE_SCHEME__
if(![transferController isMemberOfClass:[LocalTransferController class]])
#endif
{
if(![manager removeItemAtPath:string error:&error])
REPORT_GENERIC_ERROR(kBackupControllerErrorCode_DeletingItem, error, NO, string, nil);
}
if(scanner == nil) {
REPORT_GENERIC_ERROR(kBackupControllerErrorCode_ReadingBOMFile, nil, YES, path, nil);
goto Exit;
}
}
else {
//Get the list of all files
#if __FAST_FILE_SCHEME__
if([transferController isMemberOfClass:[LocalTransferController class]]) {
results = [manager contentsOfDirectoryAtPath:[[transferController baseURL] path] error:&error];
if(results == nil) {
REPORT_GENERIC_ERROR(kBackupControllerErrorCode_Scanning, error, YES, [[transferController baseURL] path], nil);
goto Exit;
}
}
else
#endif
{
UPDATE_STATUS(kBackupControllerStatus_CheckingDestination, 0, 0);
results = [transferController contentsOfDirectoryAtPath:nil];
UPDATE_STATUS(kBackupControllerStatus_Idle, 0, 0);
if(results == nil) {
if(![_delegate backupControllerShouldAbort:self])
REPORT_GENERIC_ERROR(kBackupControllerErrorCode_CheckingDestination, nil, YES, [[transferController absoluteURLForRemotePath:nil] absoluteString], nil);
goto Exit;
}
results = [results allKeys];
}
//Order the list by inverse alphabetical order so that most recent files are first
results = [[results sortedArrayUsingSelector:@selector(compare:)] reverseObjectEnumerator];
//Retrieve the first BOM file in the list
scanner = (DirectoryScanner*)kCFNull;
for(path in results) {
if(![path hasSuffix:kBOMFileExtension])
continue;
//Download the BOM file
#if __FAST_FILE_SCHEME__
if([transferController isMemberOfClass:[LocalTransferController class]])
string = [[[transferController baseURL] path] stringByAppendingPathComponent:path];
else
#endif
{
string = MAKE_TMP_PATH();
do {
UPDATE_STATUS(kBackupControllerStatus_DownloadingFile, 0, 0);
success = [transferController downloadFileFromPath:path toPath:string];
UPDATE_STATUS(kBackupControllerStatus_Idle, 0, 0);
} while(!success && ![_delegate backupControllerShouldAbort:self] && [_delegate backupController:self shouldRetryFileTransferWithURL:[transferController absoluteURLForRemotePath:path]]);
if(success == NO) {
if(![_delegate backupControllerShouldAbort:self])
REPORT_GENERIC_ERROR(kBackupControllerErrorCode_DownloadingFile, nil, YES, path, string);
goto Exit;
}
}
CHECK_IMMEDIATE_ABORT();
//Recreate the directory scanner from it
@try {
scanner = [[DirectoryScanner alloc] initWithFile:string];
}
@catch(NSException* localException) {
NSLog(@"%s: %@", __FUNCTION__, localException);
scanner = nil;
}
#if __FAST_FILE_SCHEME__
if(![transferController isMemberOfClass:[LocalTransferController class]])
#endif
{
if(![manager removeItemAtPath:string error:&error])
REPORT_GENERIC_ERROR(kBackupControllerErrorCode_DeletingItem, error, NO, string, nil);
}
if(scanner == nil) {
REPORT_GENERIC_ERROR(kBackupControllerErrorCode_ReadingBOMFile, nil, YES, string, nil);
goto Exit;
}
break;
}
}
Exit:
return [scanner autorelease];
}
static NSURL* _URLFromDestination(id destination)
{
if([destination isKindOfClass:[NSString class]]) {
if([destination rangeOfString:@"://"].location == NSNotFound)
destination = [NSURL fileURLWithPath:[destination stringByStandardizingPath]];
else
destination = [NSURL URLWithString:destination];
}
else if(![destination isKindOfClass:[NSURL class]])
return nil;
return [[Keychain sharedKeychain] URLWithPasswordForURL:destination];
}
static NSComparisonResult _PathSortFunction(NSString* path1, NSString* path2, void* context)
{
return [path1 compare:path2 options:(NSCaseInsensitiveSearch | NSNumericSearch | NSForcedOrderingSearch)];
}
static NSComparisonResult _ItemInfoSortFunction(DirectoryItem* info1, DirectoryItem* info2, void* context)
{
return _PathSortFunction([info1 path], [info2 path], NULL);
}
- (void) _makeFileReadOnly:(NSString*)path
{
const char* filePath = [path UTF8String];
struct stat stats;
if(lstat(filePath, &stats) == 0) {
if(chmod(filePath, (stats.st_mode & ALLPERMS) & ~(S_IWUSR | S_IWGRP | S_IWOTH)) != 0)
REPORT_GENERIC_ERROR(kBackupControllerErrorCode_SettingItemPermissions, nil, NO, [NSString stringWithUTF8String:filePath], nil);
}
else
REPORT_GENERIC_ERROR(kBackupControllerErrorCode_RetrievingItemInfo, nil, NO, [NSString stringWithUTF8String:filePath], nil);
}
static inline BOOL _EqualData(NSData* data1, NSData* data2)
{
if(data1 == data2)
return YES;
if(data1 && data2 && [data1 isEqualToData:data2])
return YES;
return NO;
}
static BOOL _RunExecutable(NSString* path, ...)
{
NSMutableArray* arguments = [NSMutableArray array];
va_list list;
NSString* string;
va_start(list, path);
while(1) {
string = va_arg(list, id);
if(string)
[arguments addObject:string];
else
break;
}
va_end(list);
string = [[path pathExtension] lowercaseString];
if([string isEqualToString:@"app"])
path = [path stringByAppendingFormat:@"/Contents/MacOS/%@", [[path lastPathComponent] stringByDeletingPathExtension]]; //FIXME: Get real executable name from Info.plist
else if([string isEqualToString:@"applescript"] || [string isEqualToString:@"scpt"]) {
[arguments insertObject:path atIndex:0];
path = @"/usr/bin/osascript";
}
return ([Task runWithToolPath:path arguments:arguments inputString:nil timeOut:0.0] ? YES : NO);
}
static inline NSString* _GetVolumeName(NSString* path)
{
return [[path pathComponents] objectAtIndex:([path hasPrefix:@"/Volumes/"] ? 2 : 1)];
}
- (id) backup:(NSDictionary*)parameters
{
NSString* sourcePath = [[parameters objectForKey:@"source"] stringByStandardizingPath];
NSURL* destinationURL = _URLFromDestination([parameters objectForKey:@"destination"]);
NSString* destinationString = ([destinationURL isFileURL] ? [destinationURL path] : [[NSURL URLWithScheme:[destinationURL scheme] user:nil password:nil host:[destinationURL host] port:[[destinationURL port] unsignedShortValue] path:[destinationURL path]] absoluteString]);
NSString* password = [parameters objectForKey:@"password"];
NSMutableArray* snapshotFiles = [NSMutableArray array];
NSMutableArray* uploadedFiles = [NSMutableArray array];
NSAutoreleasePool* localPool = nil;
DirectoryScanner* scanner = nil;
BOOL success = YES;
id result = nil;
NSUInteger segments = 0;
NSFileManager* manager;
NSMutableDictionary* allResults;
NSString* backupName;
NSDictionary* results;
NSArray* array;
NSError* error;
DirectoryItem* item;
NSString* path;
NSString* snapshotPath;
NSString* archivePath;
NSString* backupPath;
NSUInteger count,
index;
unsigned long long size;
BOOL completed;
NSMutableArray* arguments;
NSUInteger segmentSize;
NSString* string;
//Run pre-backup executable if any
if((path = [parameters objectForKey:@"preExecutable"])) {
UPDATE_STATUS(kBackupControllerStatus_RunningExecutable, 0, 0);
completed = _RunExecutable(path, sourcePath, destinationString, nil);
UPDATE_STATUS(kBackupControllerStatus_Idle, 0, 0);
if(completed == NO) {
REPORT_GENERIC_ERROR(kBackupControllerErrorCode_RunningExecutable, nil, YES, path, nil);
return nil;
}
}
//Create our custom file manager
manager = [[NSFileManager new] autorelease];
[manager setDelegate:self];
//Create a transfer controller to this URL
UPDATE_STATUS(kBackupControllerStatus_AccessingDestination, 0, 0);
_transferController = [FileTransferController fileTransferControllerWithURL:destinationURL];
UPDATE_STATUS(kBackupControllerStatus_Idle, 0, 0);
if(_transferController == nil)
goto Exit;
[_transferController setDelegate:self];
CHECK_IMMEDIATE_ABORT();
//Retrieve last scanner
scanner = [self _scannerForRevision:0 fileTransferController:_transferController];
if(scanner == nil)
goto Exit;
//Create a new one if there wasn't any (i.e. initial backup case)
if(scanner == (DirectoryScanner*)kCFNull) {
scanner = [[[DirectoryScanner alloc] initWithRootDirectory:sourcePath scanMetadata:NO] autorelease];
if(scanner == nil) {
REPORT_GENERIC_ERROR(kBackupControllerErrorCode_Scanning, nil, YES, sourcePath, nil);
goto Exit;
}
[scanner setSortPaths:YES];
}
//Otherwise make sure it is compatible
else if(sourcePath) {
if(([[parameters objectForKey:@"diskImage"] boolValue] != [[scanner userInfoForKey:kBackupScannerUserInfoKey_DiskImage] boolValue]) || ([[parameters objectForKey:@"compressed"] boolValue] != [[scanner userInfoForKey:kBackupScannerUserInfoKey_Compressed] boolValue]) || !_EqualData([[password dataUsingEncoding:NSUTF8StringEncoding] md5Digest], [scanner userInfoForKey:kBackupScannerUserInfoKey_PasswordMD5])) {
REPORT_GENERIC_ERROR(kBackupControllerErrorCode_ReadingBOMFile, nil, YES, nil, nil);
goto Exit;
}
}
//If we are not running in update mode, copy all backup settings to scanner
if(sourcePath) {
[scanner setExcludeHiddenItems:[[parameters objectForKey:@"excludeHidden"] boolValue]];
[scanner setExclusionPredicate:[DirectoryScanner exclusionPredicateWithPaths:[parameters objectForKey:@"excludePath"] names:[parameters objectForKey:@"excludeName"]]];
[scanner setUserInfo:[parameters objectForKey:@"atomic"] forKey:kBackupScannerUserInfoKey_Atomic];
[scanner setUserInfo:[parameters objectForKey:@"fullBackup"] forKey:kBackupScannerUserInfoKey_FullBackup];
[scanner setUserInfo:[parameters objectForKey:@"diskImage"] forKey:kBackupScannerUserInfoKey_DiskImage];
[scanner setUserInfo:[parameters objectForKey:@"compressed"] forKey:kBackupScannerUserInfoKey_Compressed];
[scanner setUserInfo:[parameters objectForKey:@"segment"] forKey:kBackupScannerUserInfoKey_Segment];
[scanner setUserInfo:[[password dataUsingEncoding:NSUTF8StringEncoding] md5Digest] forKey:kBackupScannerUserInfoKey_PasswordMD5];
}
//Check if we need to create segmented archives
segmentSize = [[scanner userInfoForKey:kBackupScannerUserInfoKey_Segment] integerValue];
//Sparse disk images cannot be segmented
if((segmentSize > 0) && [[scanner userInfoForKey:kBackupScannerUserInfoKey_DiskImage] boolValue] && ![[scanner userInfoForKey:kBackupScannerUserInfoKey_Compressed] boolValue])
goto Exit;
//Only disk images can have passwords
if(password && ![[scanner userInfoForKey:kBackupScannerUserInfoKey_DiskImage] boolValue])
goto Exit;
//Remember start date
[scanner setUserInfo:[NSDate date] forKey:kBackupScannerUserInfoKey_StartDate];
CHECK_IMMEDIATE_ABORT();
//Update scanner
UPDATE_STATUS(kBackupControllerStatus_ScanningSource, 0, 0);
if([scanner revision] > 0)
results = [scanner scanAndCompareRootDirectory:(kDirectoryScannerOption_BumpRevision | kDirectoryScannerOption_OnlyReportTopLevelRemovedItems)];
else {
results = [scanner scanRootDirectory];
if(results) {
results = [NSMutableDictionary dictionaryWithDictionary:results];
[(NSMutableDictionary*)results setValue:[scanner subpathsOfRootDirectory] forKey:kDirectoryScannerResultKey_AddedItems];
}
}
UPDATE_STATUS(kBackupControllerStatus_Idle, 0, 0);
if(results == nil) {
REPORT_GENERIC_ERROR(kBackupControllerErrorCode_Scanning, nil, YES, [scanner rootDirectory], nil);
goto Exit;
}
if((array = [results objectForKey:kDirectoryScannerResultKey_ErrorPaths]))
REPORT_SCANNING_ERROR(array, NO);
//Check if are in dry-run mode
if([[parameters objectForKey:@"dryRun"] boolValue]) {
[(NSMutableDictionary*)results removeObjectForKey:kDirectoryScannerResultKey_ErrorPaths];
_transferController = nil;
result = results;
goto Done;
}
CHECK_IMMEDIATE_ABORT();
//Check if there are any changes
if([results objectForKey:kDirectoryScannerResultKey_RemovedItems] || [results objectForKey:kDirectoryScannerResultKey_ModifiedItems_Data] || [results objectForKey:kDirectoryScannerResultKey_AddedItems]) {
allResults = nil;
//Fix results to contain all items when in full-backup mode
if([[scanner userInfoForKey:kBackupScannerUserInfoKey_FullBackup] boolValue])
results = [NSDictionary dictionaryWithObject:[scanner subpathsOfRootDirectory] forKey:kDirectoryScannerResultKey_AddedItems];
else if([scanner revision] > 1) {
allResults = [NSMutableDictionary dictionary];
[allResults setObject:[NSMutableArray array] forKey:kDirectoryScannerResultKey_ModifiedItems_Data];
[allResults setObject:[NSMutableArray array] forKey:kDirectoryScannerResultKey_AddedItems];
[allResults setObject:[NSMutableArray array] forKey:kDirectoryScannerResultKey_RemovedItems];
}
//Build backup name & archive path
backupName = [NSString stringWithFormat:kBackupFormat, [scanner revision]];
#if __FAST_FILE_SCHEME__
if([_transferController isMemberOfClass:[LocalTransferController class]])
archivePath = [[[_transferController baseURL] path] stringByAppendingPathComponent:backupName];
else
#endif
archivePath = MAKE_TMP_PATH();
//Compute total size of all items that will go in the archive and add some margin
size = 0;
for(item in [results objectForKey:kDirectoryScannerResultKey_ModifiedItems_Data])
size += [item totalSize];
for(item in [results objectForKey:kDirectoryScannerResultKey_AddedItems])
size += [item totalSize];
size /= 1024;
size += size * 10 / 100; //Add 10% margin
if([[scanner userInfoForKey:kBackupScannerUserInfoKey_Atomic] boolValue]) //Add another 25% margin in case of atomic backups
size += size / 4;
//Make sure we have enough disk space for the snapshot
if([[scanner userInfoForKey:kBackupScannerUserInfoKey_DiskImage] boolValue] && ![[scanner userInfoForKey:kBackupScannerUserInfoKey_Compressed] boolValue])
size = MAX(5 * 1024, size); //Sparse disk images must be 5Mb minimum
else {
error = nil;
if([[[manager attributesOfFileSystemForPath:_scratchDir error:&error] objectForKey:NSFileSystemFreeSize] unsignedLongLongValue] / 100 * (100 - kDiskSpaceMargin) < size) {
REPORT_GENERIC_ERROR(kBackupControllerErrorCode_CheckingLocalDiskSpace, error, YES, _GetVolumeName(_scratchDir), nil);
goto Exit;
}
}
//Make sure we have enough disk space for the archive
error = nil;
if([[[manager attributesOfFileSystemForPath:[archivePath stringByDeletingLastPathComponent] error:&error] objectForKey:NSFileSystemFreeSize] unsignedLongLongValue] / 100 * (100 - kDiskSpaceMargin) < size) {
REPORT_GENERIC_ERROR(kBackupControllerErrorCode_CheckingLocalDiskSpace, error, YES, _GetVolumeName(archivePath), nil);
goto Exit;
}
//Do we need to create uncompressed disk images i.e. sparse disk images?
if([[scanner userInfoForKey:kBackupScannerUserInfoKey_DiskImage] boolValue] && ![[scanner userInfoForKey:kBackupScannerUserInfoKey_Compressed] boolValue]) {
archivePath = [archivePath stringByAppendingPathExtension:@"sparseimage"];
//Create the sparse disk image, mount it and use it directly as the snapshot directory
UPDATE_STATUS(kBackupControllerStatus_CreatingDiskImage, 0, 0);
completed = [[DiskImageController sharedDiskImageController] makeSparseDiskImageAtPath:archivePath withName:backupName size:size password:password];
UPDATE_STATUS(kBackupControllerStatus_Idle, 0, 0);
if(completed) {
snapshotPath = [@"/tmp" stringByAppendingPathComponent:[[NSProcessInfo processInfo] globallyUniqueString]];
if(![[DiskImageController sharedDiskImageController] mountDiskImage:archivePath atPath:snapshotPath usingShadowFile:nil password:password private:YES verify:NO]) {
REPORT_GENERIC_ERROR(kBackupControllerErrorCode_MountingDiskImage, nil, YES, archivePath, snapshotPath);
if(![manager removeItemAtPath:archivePath error:&error])
REPORT_GENERIC_ERROR(kBackupControllerErrorCode_DeletingItem, error, NO, archivePath, nil);
goto Exit;
}
}
else {
REPORT_GENERIC_ERROR(kBackupControllerErrorCode_CreatingDiskImage, nil, YES, archivePath, nil);
goto Exit;
}
//Check the abort flag
if([_delegate backupControllerShouldAbort:self]) {
[[DiskImageController sharedDiskImageController] unmountDiskImageAtPath:snapshotPath force:YES];
[manager removeItemAtPath:archivePath error:NULL];
goto Exit;
}
}
else {
//Add the proper extension to the archive path
if([[scanner userInfoForKey:kBackupScannerUserInfoKey_DiskImage] boolValue])
archivePath = [archivePath stringByAppendingPathExtension:@"dmg"];
else if([[scanner userInfoForKey:kBackupScannerUserInfoKey_Compressed] boolValue])
archivePath = [archivePath stringByAppendingPathExtension:@"zip"];
else
archivePath = [archivePath stringByAppendingPathExtension:@"cpio"];
CHECK_IMMEDIATE_ABORT();
//Create the snapshot directory
snapshotPath = MAKE_TMP_PATH();
if(![manager createDirectoryAtPath:snapshotPath withIntermediateDirectories:YES attributes:nil error:&error]) {
REPORT_GENERIC_ERROR(kBackupControllerErrorCode_CreatingDirectory, error, YES, snapshotPath, nil);
goto Exit;
}
}
//Copy all modified or added items
completed = YES;
while(1) {
if(allResults) {
array = [allResults objectForKey:kDirectoryScannerResultKey_ModifiedItems_Data];
for(item in [results objectForKey:kDirectoryScannerResultKey_ModifiedItems_Data])
[(NSMutableArray*)array addObject:[item path]];
array = [allResults objectForKey:kDirectoryScannerResultKey_AddedItems];
for(item in [results objectForKey:kDirectoryScannerResultKey_AddedItems])
[(NSMutableArray*)array addObject:[item path]];
array = [allResults objectForKey:kDirectoryScannerResultKey_RemovedItems];
for(item in [results objectForKey:kDirectoryScannerResultKey_RemovedItems])
[(NSMutableArray*)array addObject:[item path]];
}
//Create a local auto-release pool
[results retain];
[localPool release];
localPool = [NSAutoreleasePool new];
[results autorelease];
//In atomic mode, delete removed or modified items
if([[scanner userInfoForKey:kBackupScannerUserInfoKey_Atomic] boolValue]) {
for(item in [results objectForKey:kDirectoryScannerResultKey_RemovedItems]) {
string = [snapshotPath stringByAppendingPathComponent:[item path]];
if([manager fileExistsAtPath:string] && ![manager removeItemAtPath:string error:&error])
REPORT_GENERIC_ERROR(kBackupControllerErrorCode_DeletingItem, error, NO, string, nil);
}
for(item in [results objectForKey:kDirectoryScannerResultKey_ModifiedItems_Data]) {
string = [snapshotPath stringByAppendingPathComponent:[item path]];
if([manager fileExistsAtPath:string] && ![manager removeItemAtPath:string error:&error])
REPORT_GENERIC_ERROR(kBackupControllerErrorCode_DeletingItem, error, NO, string, nil);
}
}
//Concatenate modified and added items into a single list
array = [results objectForKey:kDirectoryScannerResultKey_ModifiedItems_Data];
if([results objectForKey:kDirectoryScannerResultKey_AddedItems]) {
array = [NSMutableArray arrayWithArray:array];
[(NSMutableArray*)array addObjectsFromArray:[results objectForKey:kDirectoryScannerResultKey_AddedItems]];
}
//Make sure the list is not empty
if([array count]) {
[snapshotFiles addObjectsFromArray:array];
//Create subdirectories or copy files into the snapshot directory
index = 0;
count = [array count];
UPDATE_STATUS(kBackupControllerStatus_CopyingFiles, index, count);
for(item in array) {
if([_delegate backupControllerShouldAbort:self]) {
completed = NO;
break;
}
++index;
UPDATE_STATUS(kBackupControllerStatus_CopyingFiles, index, count);
if(![item isDirectory]) {
string = [[snapshotPath stringByAppendingPathComponent:[item path]] stringByDeletingLastPathComponent];
if(![manager fileExistsAtPath:string] && ![manager createDirectoryAtPath:string withIntermediateDirectories:YES attributes:nil error:&error]) {
[snapshotFiles removeObject:item];
[scanner removeDirectoryItemAtSubpath:[item path]];
success = NO;
REPORT_GENERIC_ERROR(kBackupControllerErrorCode_CreatingDirectory, error, NO, string, nil);
continue;
}
if(![manager copyFileUnlockedAtPath:[[scanner rootDirectory] stringByAppendingPathComponent:[item path]] toPath:[snapshotPath stringByAppendingPathComponent:[item path]] error:&error]) {
[snapshotFiles removeObject:item];
[scanner removeDirectoryItemAtSubpath:[item path]];
success = NO;
REPORT_GENERIC_ERROR(kBackupControllerErrorCode_CopyingItem, error, NO, [[scanner rootDirectory] stringByAppendingPathComponent:[item path]], [snapshotPath stringByAppendingPathComponent:[item path]]);
}
}
}
UPDATE_STATUS(kBackupControllerStatus_Idle, 0, 0);
}
//In atomic mode, keep scanning until there are no more changes being reported
if(completed && [[scanner userInfoForKey:kBackupScannerUserInfoKey_Atomic] boolValue]) {
results = [scanner scanAndCompareRootDirectory:kDirectoryScannerOption_OnlyReportTopLevelRemovedItems];
if(results) {
if([results objectForKey:kDirectoryScannerResultKey_RemovedItems] || [results objectForKey:kDirectoryScannerResultKey_ModifiedItems_Data] || [results objectForKey:kDirectoryScannerResultKey_AddedItems])
continue;
}
else
completed = NO;
}
break;
}
[localPool release];
localPool = nil;
//Do we have a sparse disk image acting as the snapshot directory?
if([[scanner userInfoForKey:kBackupScannerUserInfoKey_DiskImage] boolValue] && ![[scanner userInfoForKey:kBackupScannerUserInfoKey_Compressed] boolValue]) {
//Unmount it
if(![[DiskImageController sharedDiskImageController] unmountDiskImageAtPath:snapshotPath force:NO]) {
if(![[DiskImageController sharedDiskImageController] unmountDiskImageAtPath:snapshotPath force:YES]) {
success = NO;
REPORT_GENERIC_ERROR(kBackupControllerErrorCode_UnmountingDiskImage, nil, NO, snapshotPath, nil);
}
}
//Upload sparse disk image to destination
if([snapshotFiles count]) {
#if __FAST_FILE_SCHEME__
if([_transferController isMemberOfClass:[LocalTransferController class]]) {
[uploadedFiles addObject:archivePath];
if(completed == YES) {
if([_delegate backupControllerShouldAbort:self])
completed = NO;
else
[self _makeFileReadOnly:archivePath];
}
}
else
#endif
{
if((completed == YES) && ![_delegate backupControllerShouldAbort:self]) {
[uploadedFiles addObject:[archivePath lastPathComponent]];
do {
UPDATE_STATUS(kBackupControllerStatus_UploadingFile, 0, 0);
completed = [_transferController uploadFileFromPath:archivePath toPath:[archivePath lastPathComponent]];
UPDATE_STATUS(kBackupControllerStatus_Idle, 0, 0);
} while(!completed && ![_delegate backupControllerShouldAbort:self] && [_delegate backupController:self shouldRetryFileTransferWithURL:[_transferController absoluteURLForRemotePath:[archivePath lastPathComponent]]]);
if((completed == NO) && ![_delegate backupControllerShouldAbort:self])
REPORT_GENERIC_ERROR(kBackupControllerErrorCode_UploadingFile, nil, YES, archivePath, [archivePath lastPathComponent]);
}
else
completed = NO;
}
}
//Delete sparse disk image
#if __FAST_FILE_SCHEME__
if(![snapshotFiles count] || ![_transferController isMemberOfClass:[LocalTransferController class]])
#endif
{
if(![manager removeItemAtPath:archivePath error:&error]) {
success = NO;
REPORT_GENERIC_ERROR(kBackupControllerErrorCode_DeletingItem, error, NO, archivePath, nil);
}
}
if(completed == NO)
goto Exit;
}
else {
if((completed == YES) && ![_delegate backupControllerShouldAbort:self]) {
//Make sure we have some items
if([snapshotFiles count]) {
//Precompute the number of segmented archives
if(segmentSize > 0) {
[snapshotFiles sortUsingFunction:_ItemInfoSortFunction context:NULL];
index = 0;
while(1) {
segments += 1;
size = 0;
while(1) {
item = [snapshotFiles objectAtIndex:index++];
if([item isDirectory]) {
if(index == [snapshotFiles count])
break;
else
continue;
}