diff --git a/Autoupdate/AppInstaller.h b/Autoupdate/AppInstaller.h index a342051d..dde6c42a 100644 --- a/Autoupdate/AppInstaller.h +++ b/Autoupdate/AppInstaller.h @@ -9,7 +9,7 @@ #import #import "SUUnarchiverProtocol.h" -@interface AppInstaller : NSObject +@interface AppInstaller : NSObject - (instancetype)initWithHostBundleIdentifier:(NSString *)hostBundleIdentifier; diff --git a/Autoupdate/AppInstaller.m b/Autoupdate/AppInstaller.m index 3367fed4..4de79583 100644 --- a/Autoupdate/AppInstaller.m +++ b/Autoupdate/AppInstaller.m @@ -187,7 +187,7 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; [self.communicator handleMessageWithIdentifier:SPUExtractionStarted data:[NSData data]]; NSString *archivePath = [self.updateDirectoryPath stringByAppendingPathComponent:self.downloadName]; - id unarchiver = [SUUnarchiver unarchiverForPath:archivePath updatingHostBundlePath:self.host.bundlePath decryptionPassword:self.decryptionPassword delegate:self]; + id unarchiver = [SUUnarchiver unarchiverForPath:archivePath updatingHostBundlePath:self.host.bundlePath decryptionPassword:self.decryptionPassword]; BOOL success; if (!unarchiver) { @@ -207,17 +207,36 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; if (!success) { [self unarchiverDidFail]; } else { - [unarchiver start]; - } -} - -- (void)unarchiverExtractedProgress:(double)progress -{ - if (sizeof(progress) == sizeof(uint64_t)) { - uint64_t progressValue = CFSwapInt64HostToLittle(*(uint64_t *)&progress); - NSData *data = [NSData dataWithBytes:&progressValue length:sizeof(progressValue)]; - - [self.communicator handleMessageWithIdentifier:SPUExtractedArchiveWithProgress data:data]; + [unarchiver + unarchiveWithCompletionBlock:^(NSError * _Nullable error) { + if (error != nil) { + [self unarchiverDidFail]; + } else { + [self.communicator handleMessageWithIdentifier:SPUValidationStarted data:[NSData data]]; + + BOOL validationSuccess = [self.updateValidator validateWithUpdateDirectory:self.updateDirectoryPath]; + + if (!validationSuccess) { + SULog(@"Error: update validation was a failure"); + [self cleanupAndExitWithStatus:EXIT_FAILURE]; + } else { + [self.communicator handleMessageWithIdentifier:SPUInstallationStartedStage1 data:[NSData data]]; + + self.finishedValidation = YES; + if (self.agentInitiatedConnection) { + [self retrieveProcessIdentifierAndStartInstallation]; + } + } + } + } + progressBlock:^(double progress) { + if (sizeof(progress) == sizeof(uint64_t)) { + uint64_t progressValue = CFSwapInt64HostToLittle(*(uint64_t *)&progress); + NSData *data = [NSData dataWithBytes:&progressValue length:sizeof(progressValue)]; + + [self.communicator handleMessageWithIdentifier:SPUExtractedArchiveWithProgress data:data]; + } + }]; } } @@ -240,25 +259,6 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; [self.communicator handleMessageWithIdentifier:SPUArchiveExtractionFailed data:[NSData data]]; } -- (void)unarchiverDidFinish -{ - [self.communicator handleMessageWithIdentifier:SPUValidationStarted data:[NSData data]]; - - BOOL validationSuccess = [self.updateValidator validateWithUpdateDirectory:self.updateDirectoryPath]; - - if (!validationSuccess) { - SULog(@"Error: update validation was a failure"); - [self cleanupAndExitWithStatus:EXIT_FAILURE]; - } else { - [self.communicator handleMessageWithIdentifier:SPUInstallationStartedStage1 data:[NSData data]]; - - self.finishedValidation = YES; - if (self.agentInitiatedConnection) { - [self retrieveProcessIdentifierAndStartInstallation]; - } - } -} - - (void)agentConnectionDidInitiate { self.agentInitiatedConnection = YES; diff --git a/Autoupdate/SUBinaryDeltaApply.h b/Autoupdate/SUBinaryDeltaApply.h index 2f1f90ad..c8baa029 100644 --- a/Autoupdate/SUBinaryDeltaApply.h +++ b/Autoupdate/SUBinaryDeltaApply.h @@ -12,6 +12,6 @@ #import @class NSString; -BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFile, BOOL verbose, NSError * __autoreleasing *error); +BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFile, BOOL verbose, void (^progressCallback)(double), NSError * __autoreleasing *error); #endif diff --git a/Autoupdate/SUBinaryDeltaApply.m b/Autoupdate/SUBinaryDeltaApply.m index c7837894..da6c6f85 100644 --- a/Autoupdate/SUBinaryDeltaApply.m +++ b/Autoupdate/SUBinaryDeltaApply.m @@ -29,7 +29,7 @@ static BOOL applyBinaryDeltaToFile(xar_t x, xar_file_t file, NSString *sourceFil return success; } -BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFile, BOOL verbose, NSError * __autoreleasing *error) +BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFile, BOOL verbose, void (^progressCallback)(double progress), NSError * __autoreleasing *error) { xar_t x = xar_open([patchFile fileSystemRepresentation], READ); if (!x) { @@ -48,6 +48,8 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi NSString *expectedNewBeforeHash = nil; NSString *expectedNewAfterHash = nil; + progressCallback(0/6.0); + xar_subdoc_t subdoc; for (subdoc = xar_subdoc_first(x); subdoc; subdoc = xar_subdoc_next(subdoc)) { if (!strcmp(xar_subdoc_name(subdoc), BINARY_DELTA_ATTRIBUTES_KEY)) { @@ -116,6 +118,8 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi fprintf(stderr, "Verifying source..."); } + progressCallback(1/6.0); + NSString *beforeHash = hashOfTreeWithVersion(source, majorDiffVersion); if (!beforeHash) { if (verbose) { @@ -141,6 +145,8 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi fprintf(stderr, "\nCopying files..."); } + progressCallback(2/6.0); + if (!removeTree(destination)) { if (verbose) { fprintf(stderr, "\n"); @@ -150,6 +156,9 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi } return NO; } + + progressCallback(3/6.0); + if (!copyTree(source, destination)) { if (verbose) { fprintf(stderr, "\n"); @@ -160,6 +169,8 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi return NO; } + progressCallback(4/6.0); + BOOL hasExtractKeyAvailable = MAJOR_VERSION_IS_AT_LEAST(majorDiffVersion, SUBeigeMajorVersion); if (verbose) { @@ -256,6 +267,8 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi } xar_close(x); + progressCallback(5/6.0); + if (verbose) { fprintf(stderr, "\nVerifying destination..."); } @@ -281,6 +294,8 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi return NO; } + progressCallback(6/6.0); + if (verbose) { fprintf(stderr, "\nDone!\n"); } diff --git a/Autoupdate/SUBinaryDeltaTool.m b/Autoupdate/SUBinaryDeltaTool.m index 3024bda5..d2d9be2d 100644 --- a/Autoupdate/SUBinaryDeltaTool.m +++ b/Autoupdate/SUBinaryDeltaTool.m @@ -100,21 +100,25 @@ static BOOL runCreateCommand(NSString *programName, NSArray *args) return NO; } + NSString *sourcePath = fileArgs[0]; + NSString *destPath = fileArgs[1]; + NSString *patchPath = fileArgs[2]; + BOOL isDirectory; - if (![[NSFileManager defaultManager] fileExistsAtPath:fileArgs[0] isDirectory:&isDirectory] || !isDirectory) { + if (![[NSFileManager defaultManager] fileExistsAtPath:sourcePath isDirectory:&isDirectory] || !isDirectory) { printUsage(programName); fprintf(stderr, "Error: before-tree must be a directory\n"); return NO; } - if (![[NSFileManager defaultManager] fileExistsAtPath:fileArgs[1] isDirectory:&isDirectory] || !isDirectory) { + if (![[NSFileManager defaultManager] fileExistsAtPath:destPath isDirectory:&isDirectory] || !isDirectory) { printUsage(programName); fprintf(stderr, "Error: after-tree must be a directory\n"); return NO; } NSError *createDiffError = nil; - if (!createBinaryDelta(fileArgs[0], fileArgs[1], fileArgs[2], patchVersion, verbose, &createDiffError)) { + if (!createBinaryDelta(sourcePath, destPath, patchPath, patchVersion, verbose, &createDiffError)) { fprintf(stderr, "%s\n", [createDiffError.localizedDescription UTF8String]); return NO; } @@ -162,7 +166,7 @@ static BOOL runApplyCommand(NSString *programName, NSArray *args) } NSError *applyDiffError = nil; - if (!applyBinaryDelta(fileArgs[0], fileArgs[1], fileArgs[2], verbose, &applyDiffError)) { + if (!applyBinaryDelta(fileArgs[0], fileArgs[1], fileArgs[2], verbose, ^(__unused double x){}, &applyDiffError)) { fprintf(stderr, "%s\n", [applyDiffError.localizedDescription UTF8String]); return NO; } diff --git a/Autoupdate/SUBinaryDeltaUnarchiver.h b/Autoupdate/SUBinaryDeltaUnarchiver.h index d7e0b7b6..ba79a047 100644 --- a/Autoupdate/SUBinaryDeltaUnarchiver.h +++ b/Autoupdate/SUBinaryDeltaUnarchiver.h @@ -16,7 +16,7 @@ NS_ASSUME_NONNULL_BEGIN @interface SUBinaryDeltaUnarchiver : NSObject -- (instancetype)initWithArchivePath:(NSString *)archivePath updateHostBundlePath:(NSString *)updateHostBundlePath delegate:(nullable id )delegate; +- (instancetype)initWithArchivePath:(NSString *)archivePath updateHostBundlePath:(NSString *)updateHostBundlePath; @end diff --git a/Autoupdate/SUBinaryDeltaUnarchiver.m b/Autoupdate/SUBinaryDeltaUnarchiver.m index d9abcf20..2a68bcd3 100644 --- a/Autoupdate/SUBinaryDeltaUnarchiver.m +++ b/Autoupdate/SUBinaryDeltaUnarchiver.m @@ -7,6 +7,7 @@ // #import "SUBinaryDeltaUnarchiver.h" +#import "SUUnarchiverNotifier.h" #import "SUBinaryDeltaCommon.h" #import "SUBinaryDeltaApply.h" #import "SULog.h" @@ -20,7 +21,6 @@ @property (nonatomic, copy, readonly) NSString *archivePath; @property (nonatomic, copy, readonly) NSString *updateHostBundlePath; -@property (nonatomic, weak, readonly) id delegate; @end @@ -28,7 +28,6 @@ @synthesize archivePath = _archivePath; @synthesize updateHostBundlePath = _updateHostBundlePath; -@synthesize delegate = _delegate; + (BOOL)canUnarchivePath:(NSString *)path { @@ -75,44 +74,46 @@ } } -- (instancetype)initWithArchivePath:(NSString *)archivePath updateHostBundlePath:(NSString *)updateHostBundlePath delegate:(id )delegate +- (instancetype)initWithArchivePath:(NSString *)archivePath updateHostBundlePath:(NSString *)updateHostBundlePath { self = [super init]; if (self != nil) { _archivePath = [archivePath copy]; _updateHostBundlePath = [updateHostBundlePath copy]; - _delegate = delegate; } return self; } -- (void)start +- (void)unarchiveWithCompletionBlock:(void (^)(NSError * _Nullable))completionBlock progressBlock:(void (^ _Nullable)(double))progressBlock { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ @autoreleasepool { - NSString *sourcePath = self.updateHostBundlePath; - NSString *targetPath = [[self.archivePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:[sourcePath lastPathComponent]]; - - NSError *applyDiffError = nil; - BOOL success = applyBinaryDelta(sourcePath, targetPath, self.archivePath, NO, &applyDiffError); - - if (success) { - [[self class] updateSpotlightImportersAtBundlePath:targetPath]; - - dispatch_async(dispatch_get_main_queue(), ^{ - [self.delegate unarchiverDidFinish]; - }); - } - else { - SULog(@"Applying delta patch failed with error: %@", applyDiffError); - dispatch_async(dispatch_get_main_queue(), ^{ - [self.delegate unarchiverDidFail]; - }); - } + SUUnarchiverNotifier *notifier = [[SUUnarchiverNotifier alloc] initWithCompletionBlock:completionBlock progressBlock:progressBlock]; + [self extractDeltaWithNotifier:notifier]; } }); } +- (void)extractDeltaWithNotifier:(SUUnarchiverNotifier *)notifier +{ + NSString *sourcePath = self.updateHostBundlePath; + NSString *targetPath = [[self.archivePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:[sourcePath lastPathComponent]]; + + NSError *applyDiffError = nil; + BOOL success = applyBinaryDelta(sourcePath, targetPath, self.archivePath, NO, ^(double progress){ + [notifier notifyProgress:progress]; + + }, &applyDiffError); + + if (success) { + [[self class] updateSpotlightImportersAtBundlePath:targetPath]; + [notifier notifySuccess]; + } + else { + [notifier notifyFailureWithError:applyDiffError]; + } +} + - (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], self.archivePath]; } @end diff --git a/Autoupdate/SUDiskImageUnarchiver.h b/Autoupdate/SUDiskImageUnarchiver.h index d39f68b3..f0de0462 100644 --- a/Autoupdate/SUDiskImageUnarchiver.h +++ b/Autoupdate/SUDiskImageUnarchiver.h @@ -16,7 +16,7 @@ NS_ASSUME_NONNULL_BEGIN @interface SUDiskImageUnarchiver : NSObject -- (instancetype)initWithArchivePath:(NSString *)archivePath decryptionPassword:(nullable NSString *)decryptionPassword delegate:(nullable id )delegate; +- (instancetype)initWithArchivePath:(NSString *)archivePath decryptionPassword:(nullable NSString *)decryptionPassword; @end diff --git a/Autoupdate/SUDiskImageUnarchiver.m b/Autoupdate/SUDiskImageUnarchiver.m index f32e54f5..4863d597 100644 --- a/Autoupdate/SUDiskImageUnarchiver.m +++ b/Autoupdate/SUDiskImageUnarchiver.m @@ -7,6 +7,7 @@ // #import "SUDiskImageUnarchiver.h" +#import "SUUnarchiverNotifier.h" #import "SULog.h" #ifdef _APPKITDEFINES_H @@ -17,7 +18,6 @@ @property (nonatomic, copy, readonly) NSString *archivePath; @property (nullable, nonatomic, copy, readonly) NSString *decryptionPassword; -@property (nonatomic, weak, readonly) id delegate; @end @@ -25,7 +25,6 @@ @synthesize archivePath = _archivePath; @synthesize decryptionPassword = _decryptionPassword; -@synthesize delegate = _delegate; + (BOOL)canUnarchivePath:(NSString *)path { @@ -37,19 +36,26 @@ return NO; } -- (instancetype)initWithArchivePath:(NSString *)archivePath decryptionPassword:(nullable NSString *)decryptionPassword delegate:(nullable id )delegate +- (instancetype)initWithArchivePath:(NSString *)archivePath decryptionPassword:(nullable NSString *)decryptionPassword { self = [super init]; if (self != nil) { _archivePath = [archivePath copy]; _decryptionPassword = [decryptionPassword copy]; - _delegate = delegate; } return self; } +- (void)unarchiveWithCompletionBlock:(void (^)(NSError * _Nullable))completionBlock progressBlock:(void (^ _Nullable)(double))progressBlock +{ + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ + SUUnarchiverNotifier *notifier = [[SUUnarchiverNotifier alloc] initWithCompletionBlock:completionBlock progressBlock:progressBlock]; + [self extractDMGWithNotifier:notifier]; + }); +} + // Called on a non-main thread. -- (void)extractDMG +- (void)extractDMGWithNotifier:(SUUnarchiverNotifier *)notifier { @autoreleasepool { BOOL mountedSuccessfully = NO; @@ -59,25 +65,16 @@ NSFileManager *manager; NSError *error; NSArray *contents; - // We have to declare these before a goto to prevent an error under ARC. - // No, we cannot have them in the dispatch_async calls, as the goto "jump enters - // lifetime of block which strongly captures a variable" - dispatch_block_t delegateFailure = ^{ - [self.delegate unarchiverDidFail]; - }; - dispatch_block_t delegateSuccess = ^{ - [self.delegate unarchiverDidFinish]; - }; - do + do { // Using NSUUID would make creating UUIDs be done in Cocoa, // and thus managed under ARC. Sadly, the class is in 10.8 and later. CFUUIDRef uuid = CFUUIDCreate(NULL); - if (uuid) - { + if (uuid) + { NSString *uuidString = CFBridgingRelease(CFUUIDCreateString(NULL, uuid)); - if (uuidString) - { + if (uuidString) + { mountPoint = [@"/Volumes" stringByAppendingPathComponent:uuidString]; } CFRelease(uuid); @@ -85,12 +82,12 @@ } // Note: this check does not follow symbolic links, which is what we want while ([[NSURL fileURLWithPath:mountPoint] checkResourceIsReachableAndReturnError:NULL]); - + NSData *promptData = nil; promptData = [NSData dataWithBytes:"yes\n" length:4]; - + NSMutableArray *arguments = [@[@"attach", self.archivePath, @"-mountpoint", mountPoint, /*@"-noverify",*/ @"-nobrowse", @"-noautoopen"] mutableCopy]; - + if (self.decryptionPassword) { NSMutableData *passwordData = [[self.decryptionPassword dataUsingEncoding:NSUTF8StringEncoding] mutableCopy]; // From the hdiutil docs: @@ -100,14 +97,14 @@ [passwordData appendData:[NSData dataWithBytes:"\0" length:1]]; [passwordData appendData:promptData]; promptData = passwordData; - + [arguments addObject:@"-stdinpass"]; } - + NSData *output = nil; NSInteger taskResult = -1; - @try - { + @try + { NSTask *task = [[NSTask alloc] init]; task.launchPath = @"/usr/bin/hdiutil"; task.currentDirectoryPath = @"/"; @@ -121,6 +118,8 @@ [task launch]; + [notifier notifyProgress:0.125]; + [inputPipe.fileHandleForWriting writeData:promptData]; [inputPipe.fileHandleForWriting closeFile]; @@ -134,6 +133,8 @@ { goto reportError; } + + [notifier notifyProgress:0.5]; if (taskResult != 0) { @@ -142,38 +143,43 @@ goto reportError; } mountedSuccessfully = YES; - + // Now that we've mounted it, we need to copy out its contents. manager = [[NSFileManager alloc] init]; contents = [manager contentsOfDirectoryAtPath:mountPoint error:&error]; - if (error) - { + if (error) + { SULog(@"Couldn't enumerate contents of archive mounted at %@: %@", mountPoint, error); goto reportError; } + double itemsCopied = 0; + double totalItems = [contents count]; + for (NSString *item in contents) { NSString *fromPath = [mountPoint stringByAppendingPathComponent:item]; NSString *toPath = [[self.archivePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:item]; - + // We skip any files in the DMG which are not readable. if (![manager isReadableFileAtPath:fromPath]) { continue; } + + itemsCopied += 1.0; + [notifier notifyProgress:0.5 + itemsCopied/(totalItems*2.0)]; if (![manager copyItemAtPath:fromPath toPath:toPath error:&error]) { - SULog(@"Couldn't copy item: %@ : %@", error, error.userInfo ? error.userInfo : @""); goto reportError; } } - - dispatch_async(dispatch_get_main_queue(), delegateSuccess); + + [notifier notifySuccess]; goto finally; - + reportError: - dispatch_async(dispatch_get_main_queue(), delegateFailure); + [notifier notifyFailureWithError:error]; finally: if (mountedSuccessfully) { @@ -195,13 +201,6 @@ } } -- (void)start -{ - dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ - [self extractDMG]; - }); -} - - (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], self.archivePath]; } @end diff --git a/Autoupdate/SUPipedUnarchiver.h b/Autoupdate/SUPipedUnarchiver.h index caec2b9e..6e9c682f 100644 --- a/Autoupdate/SUPipedUnarchiver.h +++ b/Autoupdate/SUPipedUnarchiver.h @@ -16,7 +16,7 @@ NS_ASSUME_NONNULL_BEGIN @interface SUPipedUnarchiver : NSObject -- (instancetype)initWithArchivePath:(NSString *)archivePath delegate:(nullable id )delegate; +- (instancetype)initWithArchivePath:(NSString *)archivePath; @end diff --git a/Autoupdate/SUPipedUnarchiver.m b/Autoupdate/SUPipedUnarchiver.m index cd79dc14..44e07d49 100644 --- a/Autoupdate/SUPipedUnarchiver.m +++ b/Autoupdate/SUPipedUnarchiver.m @@ -7,7 +7,9 @@ // #import "SUPipedUnarchiver.h" +#import "SUUnarchiverNotifier.h" #import "SULog.h" +#import "SUErrors.h" #ifdef _APPKITDEFINES_H #error This is a "core" class and should NOT import AppKit @@ -16,14 +18,12 @@ @interface SUPipedUnarchiver () @property (nonatomic, copy, readonly) NSString *archivePath; -@property (nonatomic, weak, readonly) id delegate; @end @implementation SUPipedUnarchiver @synthesize archivePath = _archivePath; -@synthesize delegate = _delegate; + (nullable NSArray *)commandAndArgumentsConformingToTypeOfPath:(NSString *)path { @@ -68,17 +68,16 @@ return NO; } -- (instancetype)initWithArchivePath:(NSString *)archivePath delegate:(nullable id )delegate +- (instancetype)initWithArchivePath:(NSString *)archivePath { self = [super init]; if (self != nil) { _archivePath = [archivePath copy]; - _delegate = delegate; } return self; } -- (void)start +- (void)unarchiveWithCompletionBlock:(void (^)(NSError * _Nullable))completionBlock progressBlock:(void (^ _Nullable)(double))progressBlock { NSArray *commandAndArguments = [[self class] commandAndArgumentsConformingToTypeOfPath:self.archivePath]; assert(commandAndArguments != nil); @@ -89,16 +88,17 @@ NSArray *arguments = [commandAndArguments subarrayWithRange:NSMakeRange(1, commandAndArguments.count - 1)]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ - [self extractArchivePipingDataToCommand:command arguments:arguments]; + SUUnarchiverNotifier *notifier = [[SUUnarchiverNotifier alloc] initWithCompletionBlock:completionBlock progressBlock:progressBlock]; + [self extractArchivePipingDataToCommand:command arguments:arguments notifier:notifier]; }); } // This method abstracts the types that use a command line tool piping data from stdin. -- (void)extractArchivePipingDataToCommand:(NSString *)command arguments:(NSArray*)args +- (void)extractArchivePipingDataToCommand:(NSString *)command arguments:(NSArray*)args notifier:(SUUnarchiverNotifier *)notifier { // *** GETS CALLED ON NON-MAIN THREAD!!! @autoreleasepool { - + NSError *error = nil; NSString *destination = [self.archivePath stringByDeletingLastPathComponent]; // Get the file size. @@ -106,10 +106,10 @@ NSUInteger expectedLength = [[attributes objectForKey:NSFileSize] unsignedIntegerValue]; if (expectedLength > 0) { NSFileHandle *archiveInput = [NSFileHandle fileHandleForReadingAtPath:self.archivePath]; - + NSPipe *pipe = [NSPipe pipe]; NSFileHandle *archiveOutput = [pipe fileHandleForWriting]; - + NSTask *task = [[NSTask alloc] init]; [task setStandardInput:[pipe fileHandleForReading]]; [task setStandardError:[NSFileHandle fileHandleWithStandardError]]; @@ -117,7 +117,7 @@ [task setLaunchPath:command]; [task setArguments:[args arrayByAddingObject:destination]]; [task launch]; - + NSUInteger bytesRead = 0; do { NSData *data = [archiveInput readDataOfLength:256*1024]; @@ -127,37 +127,29 @@ } bytesRead += len; [archiveOutput writeData:data]; - dispatch_async(dispatch_get_main_queue(), ^{ - if ([self.delegate respondsToSelector:@selector(unarchiverExtractedProgress:)]) { - [self.delegate unarchiverExtractedProgress:(double)bytesRead / (double)expectedLength]; - } - }); + [notifier notifyProgress:(double)bytesRead / (double)expectedLength]; } while(bytesRead < expectedLength); [archiveOutput closeFile]; - + [task waitUntilExit]; if ([task terminationStatus] == 0) { if (bytesRead == expectedLength) { - dispatch_async(dispatch_get_main_queue(), ^{ - [self.delegate unarchiverDidFinish]; - }); + [notifier notifySuccess]; return; } else { - SULog(@"Extraction failed, command '%@' got only %ld of %ld bytes", command, (long)bytesRead, (long)expectedLength); + error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Extraction failed, command '%@' got only %ld of %ld bytes", command, (long)bytesRead, (long)expectedLength]}]; + } } else { - SULog(@"Extraction failed, command '%@' returned %d", command, [task terminationStatus]); + error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Extraction failed, command '%@' returned %d", command, [task terminationStatus]]}]; } } else { - SULog(@"Extraction failed, archive '%@' is empty", self.archivePath); + error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Extraction failed, archive '%@' is empty", self.archivePath]}]; } - - dispatch_async(dispatch_get_main_queue(), ^{ - [self.delegate unarchiverDidFail]; - }); + [notifier notifyFailureWithError:error]; } } diff --git a/Autoupdate/SUPlainInstaller.m b/Autoupdate/SUPlainInstaller.m index badc6f95..f0551913 100644 --- a/Autoupdate/SUPlainInstaller.m +++ b/Autoupdate/SUPlainInstaller.m @@ -92,9 +92,10 @@ } // Create a temporary directory for our new app that resides on our destination's volume - NSString *installationDirectoryName = installationURL.lastPathComponent; - NSURL *installationDirectoryURL = installationURL.URLByDeletingLastPathComponent; - NSURL *tempNewDirectoryURL = (installationDirectoryName != nil && installationDirectoryURL != nil) ? [fileManager makeTemporaryDirectoryWithPreferredName:[installationDirectoryName.stringByDeletingPathExtension stringByAppendingString:@" (Incomplete Update)"] appropriateForDirectoryURL:installationDirectoryURL error:error] : nil; + NSString *preferredName = [installationURL.lastPathComponent.stringByDeletingPathExtension stringByAppendingString:@" (Incomplete Update)"]; + NSURL *installationDirectory = installationURL.URLByDeletingLastPathComponent; + NSURL *tempNewDirectoryURL = [fileManager makeTemporaryDirectoryWithPreferredName:preferredName appropriateForDirectoryURL:installationDirectory error:error]; + if (tempNewDirectoryURL == nil) { SULog(@"Failed to make new temp directory"); return NO; @@ -195,14 +196,13 @@ // Prevent malicious downgrades // Note that we may not be able to do this for package installations, hence this code being done here if (!allowDowngrades) { + NSString *hostVersion = [self.host version]; NSBundle *bundle = [NSBundle bundleWithPath:self.applicationPath]; - - if ([self.comparator compareVersion:self.host.version toVersion:[bundle objectForInfoDictionaryKey:(__bridge NSString *)kCFBundleVersionKey]] == NSOrderedDescending) { - if (error != NULL) { - NSString *errorMessage = [NSString stringWithFormat:@"For security reasons, updates that downgrade version of the application are not allowed. Refusing to downgrade app from version %@ to %@. Aborting update.", [self.host version], [bundle objectForInfoDictionaryKey:(__bridge NSString *)kCFBundleVersionKey]]; - - *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUDowngradeError userInfo:@{ NSLocalizedDescriptionKey: errorMessage }]; - } + NSString *updateVersion = [bundle objectForInfoDictionaryKey:(__bridge NSString *)kCFBundleVersionKey]; + if (!updateVersion || [self.comparator compareVersion:hostVersion toVersion:updateVersion] == NSOrderedDescending) { + NSString *errorMessage = [NSString stringWithFormat:@"For security reasons, updates that downgrade version of the application are not allowed. Refusing to downgrade app from version %@ to %@. Aborting update.", hostVersion, [bundle objectForInfoDictionaryKey:(__bridge NSString *)kCFBundleVersionKey]]; + + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUDowngradeError userInfo:@{ NSLocalizedDescriptionKey: errorMessage }]; return NO; } diff --git a/Autoupdate/SUUnarchiver.h b/Autoupdate/SUUnarchiver.h index b732c313..a52bf5a2 100644 --- a/Autoupdate/SUUnarchiver.h +++ b/Autoupdate/SUUnarchiver.h @@ -11,11 +11,10 @@ NS_ASSUME_NONNULL_BEGIN @protocol SUUnarchiverProtocol; -@protocol SUUnarchiverDelegate; @interface SUUnarchiver : NSObject -+ (nullable id )unarchiverForPath:(NSString *)path updatingHostBundlePath:(nullable NSString *)hostPath decryptionPassword:(nullable NSString *)decryptionPassword delegate:(nullable id )delegate; ++ (nullable id )unarchiverForPath:(NSString *)path updatingHostBundlePath:(nullable NSString *)hostPath decryptionPassword:(nullable NSString *)decryptionPassword; @end diff --git a/Autoupdate/SUUnarchiver.m b/Autoupdate/SUUnarchiver.m index cf630f57..d91159f9 100644 --- a/Autoupdate/SUUnarchiver.m +++ b/Autoupdate/SUUnarchiver.m @@ -18,19 +18,18 @@ @implementation SUUnarchiver -+ (nullable id )unarchiverForPath:(NSString *)path updatingHostBundlePath:(nullable NSString *)hostPath decryptionPassword:(nullable NSString *)decryptionPassword delegate:(nullable id )delegate ++ (nullable id )unarchiverForPath:(NSString *)path updatingHostBundlePath:(nullable NSString *)hostPath decryptionPassword:(nullable NSString *)decryptionPassword { if ([SUPipedUnarchiver canUnarchivePath:path]) { - return [[SUPipedUnarchiver alloc] initWithArchivePath:path delegate:delegate]; + return [[SUPipedUnarchiver alloc] initWithArchivePath:path]; } else if ([SUDiskImageUnarchiver canUnarchivePath:path]) { - return [[SUDiskImageUnarchiver alloc] initWithArchivePath:path decryptionPassword:decryptionPassword delegate:delegate]; + return [[SUDiskImageUnarchiver alloc] initWithArchivePath:path decryptionPassword:decryptionPassword]; } else if ([SUBinaryDeltaUnarchiver canUnarchivePath:path]) { assert(hostPath != nil); NSString *nonNullHostPath = hostPath; - return [[SUBinaryDeltaUnarchiver alloc] initWithArchivePath:path updateHostBundlePath:nonNullHostPath delegate:delegate]; - + return [[SUBinaryDeltaUnarchiver alloc] initWithArchivePath:path updateHostBundlePath:nonNullHostPath]; } return nil; } diff --git a/Autoupdate/SUUnarchiverNotifier.h b/Autoupdate/SUUnarchiverNotifier.h new file mode 100644 index 00000000..9c8b65a8 --- /dev/null +++ b/Autoupdate/SUUnarchiverNotifier.h @@ -0,0 +1,25 @@ +// +// SUUnarchiverNotifier.h +// Sparkle +// +// Created by Mayur Pawashe on 12/21/16. +// Copyright © 2016 Sparkle Project. All rights reserved. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface SUUnarchiverNotifier : NSObject + +- (instancetype)initWithCompletionBlock:(void (^)(NSError * _Nullable))completionBlock progressBlock:(void (^ _Nullable)(double))progressBlock; + +- (void)notifySuccess; + +- (void)notifyFailureWithError:(NSError * _Nullable)reason; + +- (void)notifyProgress:(double)progress; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Autoupdate/SUUnarchiverNotifier.m b/Autoupdate/SUUnarchiverNotifier.m new file mode 100644 index 00000000..914a08e7 --- /dev/null +++ b/Autoupdate/SUUnarchiverNotifier.m @@ -0,0 +1,69 @@ +// +// SUUnarchiverNotifier.m +// Sparkle +// +// Created by Mayur Pawashe on 12/21/16. +// Copyright © 2016 Sparkle Project. All rights reserved. +// + +#import "SUUnarchiverNotifier.h" +#import "SULocalizations.h" +#import "SUErrors.h" + +#ifdef _APPKITDEFINES_H +#error This is a "core" class and should NOT import AppKit +#endif + +@interface SUUnarchiverNotifier () + +@property (nonatomic, readonly, copy) void (^completionBlock)(NSError * _Nullable); +@property (nonatomic, readonly, copy) void (^ _Nullable progressBlock)(double); + +@end + +@implementation SUUnarchiverNotifier + +@synthesize completionBlock = _completionBlock; +@synthesize progressBlock = _progressBlock; + +- (instancetype)initWithCompletionBlock:(void (^)(NSError * _Nullable))completionBlock progressBlock:(void (^ _Nullable)(double))progressBlock +{ + self = [super init]; + if (self != nil) { + _completionBlock = [completionBlock copy]; + _progressBlock = [progressBlock copy]; + } + return self; +} + +- (void)notifySuccess +{ + dispatch_async(dispatch_get_main_queue(), ^{ + self.completionBlock(nil); + }); +} + +- (void)notifyFailureWithError:(NSError * _Nullable)reason +{ + NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithObject:SULocalizedString(@"An error occurred while extracting the archive. Please try again later.", nil) forKey:NSLocalizedDescriptionKey]; + if (reason) { + [userInfo setObject:(NSError * _Nonnull)reason forKey:NSUnderlyingErrorKey]; + } + + NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:userInfo]; + + dispatch_async(dispatch_get_main_queue(), ^{ + self.completionBlock(error); + }); +} + +- (void)notifyProgress:(double)progress +{ + if (self.progressBlock != nil) { + dispatch_async(dispatch_get_main_queue(), ^{ + self.progressBlock(progress); + }); + } +} + +@end diff --git a/Autoupdate/SUUnarchiverProtocol.h b/Autoupdate/SUUnarchiverProtocol.h index 5a349877..25a7797d 100644 --- a/Autoupdate/SUUnarchiverProtocol.h +++ b/Autoupdate/SUUnarchiverProtocol.h @@ -16,21 +16,10 @@ NS_ASSUME_NONNULL_BEGIN + (BOOL)unsafeIfArchiveIsNotValidated; -- (void)start; +- (void)unarchiveWithCompletionBlock:(void (^)(NSError * _Nullable))completionBlock progressBlock:(void (^ _Nullable)(double))progressBlock; - (NSString *)description; @end -@protocol SUUnarchiverDelegate - -- (void)unarchiverDidFinish; - -- (void)unarchiverDidFail; - -@optional -- (void)unarchiverExtractedProgress:(double)progress; - -@end - NS_ASSUME_NONNULL_END diff --git a/Sparkle.xcodeproj/project.pbxproj b/Sparkle.xcodeproj/project.pbxproj index 1c9327bd..aec70873 100644 --- a/Sparkle.xcodeproj/project.pbxproj +++ b/Sparkle.xcodeproj/project.pbxproj @@ -130,6 +130,8 @@ 7229E1BA1C97CC4D00CB50D0 /* SPUScheduledUpdateDriver.m in Sources */ = {isa = PBXBuildFile; fileRef = 7229E1B81C97CC4D00CB50D0 /* SPUScheduledUpdateDriver.m */; }; 7229E1BD1C98EFF200CB50D0 /* SPUDownloadDriver.h in Headers */ = {isa = PBXBuildFile; fileRef = 7229E1BB1C98EFF200CB50D0 /* SPUDownloadDriver.h */; }; 7229E1BE1C98EFF200CB50D0 /* SPUDownloadDriver.m in Sources */ = {isa = PBXBuildFile; fileRef = 7229E1BC1C98EFF200CB50D0 /* SPUDownloadDriver.m */; }; + 72316BD31E0DA8430039EFD9 /* SUUnarchiverNotifier.m in Sources */ = {isa = PBXBuildFile; fileRef = 72316BD21E0DA8430039EFD9 /* SUUnarchiverNotifier.m */; }; + 72316BD41E0DB37E0039EFD9 /* SUUnarchiverNotifier.m in Sources */ = {isa = PBXBuildFile; fileRef = 72316BD21E0DA8430039EFD9 /* SUUnarchiverNotifier.m */; }; 723B252A1CEA7F3B00909873 /* bscommon.c in Sources */ = {isa = PBXBuildFile; fileRef = 72B09CE91CEA18900052EF9E /* bscommon.c */; }; 723B5DA71CF7AB0100365F95 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 723B5DA01CF7AB0100365F95 /* main.m */; }; 723B5DA91CF7AB0100365F95 /* SPUDownloader.m in Sources */ = {isa = PBXBuildFile; fileRef = 723B5DA31CF7AB0100365F95 /* SPUDownloader.m */; }; @@ -915,6 +917,8 @@ 7229E1BB1C98EFF200CB50D0 /* SPUDownloadDriver.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SPUDownloadDriver.h; sourceTree = ""; }; 7229E1BC1C98EFF200CB50D0 /* SPUDownloadDriver.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SPUDownloadDriver.m; sourceTree = ""; }; 722FB7CA1DD69897001D40CE /* ConfigSwift.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = ConfigSwift.xcconfig; sourceTree = ""; }; + 72316BD11E0DA8430039EFD9 /* SUUnarchiverNotifier.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SUUnarchiverNotifier.h; path = Autoupdate/SUUnarchiverNotifier.h; sourceTree = SOURCE_ROOT; }; + 72316BD21E0DA8430039EFD9 /* SUUnarchiverNotifier.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = SUUnarchiverNotifier.m; path = Autoupdate/SUUnarchiverNotifier.m; sourceTree = SOURCE_ROOT; }; 723B5D9F1CF7AB0100365F95 /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = Info.plist; path = Downloader/Info.plist; sourceTree = SOURCE_ROOT; }; 723B5DA01CF7AB0100365F95 /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = main.m; path = Downloader/main.m; sourceTree = SOURCE_ROOT; }; 723B5DA21CF7AB0100365F95 /* SPUDownloader.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SPUDownloader.h; path = Downloader/SPUDownloader.h; sourceTree = SOURCE_ROOT; }; @@ -1494,6 +1498,8 @@ 7267E5831D3D89B300D1BF90 /* SUPipedUnarchiver.m */, 7267E5841D3D89B300D1BF90 /* SUUnarchiver.h */, 7267E5851D3D89B300D1BF90 /* SUUnarchiver.m */, + 72316BD11E0DA8430039EFD9 /* SUUnarchiverNotifier.h */, + 72316BD21E0DA8430039EFD9 /* SUUnarchiverNotifier.m */, ); name = Unarchiving; path = ..; @@ -2790,6 +2796,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 72316BD41E0DB37E0039EFD9 /* SUUnarchiverNotifier.m in Sources */, 7267E5F81D3D91A800D1BF90 /* SUPipedUnarchiver.m in Sources */, 7267E5F71D3D919600D1BF90 /* SUPlainInstaller.m in Sources */, 7267E5F61D3D919000D1BF90 /* SUDiskImageUnarchiver.m in Sources */, @@ -2999,6 +3006,7 @@ 7267E5CC1D3D8C6B00D1BF90 /* SUConstants.m in Sources */, 7267E5CB1D3D8C6400D1BF90 /* SUAppcastItem.m in Sources */, 7267E5C31D3D8B2700D1BF90 /* SUInstaller.m in Sources */, + 72316BD31E0DA8430039EFD9 /* SUUnarchiverNotifier.m in Sources */, 7267E5AB1D3D8AA800D1BF90 /* TerminationListener.m in Sources */, 7267E5A81D3D8A9900D1BF90 /* AgentConnection.m in Sources */, 7267E5E71D3D90AA00D1BF90 /* SUFileManager.m in Sources */, diff --git a/Sparkle/SUAppcast.h b/Sparkle/SUAppcast.h index fee97567..c81994b4 100644 --- a/Sparkle/SUAppcast.h +++ b/Sparkle/SUAppcast.h @@ -16,16 +16,20 @@ #endif #import "SUExport.h" +NS_ASSUME_NONNULL_BEGIN + @class SUAppcastItem; SU_EXPORT @interface SUAppcast : NSObject -@property (copy) NSString *userAgentString; -@property (copy) NSDictionary *httpHeaders; +@property (copy, nullable) NSString *userAgentString; +@property (copy, nullable) NSDictionary *httpHeaders; -- (void)fetchAppcastFromURL:(NSURL *)url completionBlock:(void (^)(NSError *))err; +- (void)fetchAppcastFromURL:(NSURL *)url completionBlock:(void (^)(NSError *_Nullable))err; - (SUAppcast *)copyWithoutDeltaUpdates; -@property (readonly, copy) NSArray *items; +@property (readonly, copy, nullable) NSArray *items; @end +NS_ASSUME_NONNULL_END + #endif diff --git a/Sparkle/SUStandardVersionComparator.h b/Sparkle/SUStandardVersionComparator.h index eb9bceb3..23d17c5d 100644 --- a/Sparkle/SUStandardVersionComparator.h +++ b/Sparkle/SUStandardVersionComparator.h @@ -17,6 +17,8 @@ #import "SUExport.h" #import "SUVersionComparisonProtocol.h" +NS_ASSUME_NONNULL_BEGIN + /*! Sparkle's default version comparator. @@ -46,4 +48,5 @@ SU_EXPORT @interface SUStandardVersionComparator : NSObject +NS_ASSUME_NONNULL_BEGIN + @class SUHost; @interface SUSystemProfiler : NSObject @@ -18,4 +20,5 @@ @end +NS_ASSUME_NONNULL_END #endif diff --git a/Sparkle/SUUpdateValidator.m b/Sparkle/SUUpdateValidator.m index d6c49dc1..f967516a 100644 --- a/Sparkle/SUUpdateValidator.m +++ b/Sparkle/SUUpdateValidator.m @@ -41,7 +41,7 @@ BOOL prevalidatedDsaSignature; if (performingPrevalidation) { NSString *publicDSAKey = host.publicDSAKey; - + if (publicDSAKey == nil) { prevalidatedDsaSignature = NO; SULog(@"Failed to validate update before unarchiving because no DSA key was found"); @@ -54,13 +54,13 @@ SULog(@"DSA signature validation before unarchiving failed for update %@", downloadPath); } } - + canValidate = prevalidatedDsaSignature; } else { prevalidatedDsaSignature = NO; canValidate = YES; } - + _canValidate = canValidate; _prevalidatedDsaSignature = prevalidatedDsaSignature; _downloadPath = [downloadPath copy]; @@ -73,50 +73,48 @@ - (BOOL)validateWithUpdateDirectory:(NSString *)updateDirectory { assert(self.canValidate); - + NSString *DSASignature = self.dsaSignature; NSString *downloadPath = self.downloadPath; SUHost *host = self.host; - + BOOL prevalidatedDsaSignature = self.prevalidatedDsaSignature; - - BOOL validationCheckSuccess; + BOOL isPackage = NO; - + // install source could point to a new bundle or a package NSString *installSource = [SUInstaller installSourcePathInUpdateFolder:updateDirectory forHost:host isPackage:&isPackage isGuided:NULL]; if (installSource == nil) { SULog(@"No suitable install is found in the update. The update will be rejected."); - validationCheckSuccess = NO; - } else { - NSURL *installSourceURL = [NSURL fileURLWithPath:installSource]; - - if (!prevalidatedDsaSignature) { - // Check to see if we have a package or bundle to validate - if (isPackage) { - // If we get here, then the appcast installation type was lying to us.. This error will be caught later when starting the installer. - // For package type updates, all we do is check if the DSA signature is valid - validationCheckSuccess = [SPUInstallerValidation validateUpdateForHost:host archivePath:downloadPath DSASignature:DSASignature]; - - if (!validationCheckSuccess) { - SULog(@"DSA signature validation of the package failed. The update contains an installer package, and valid DSA signatures are mandatory for all installer packages. The update will be rejected. Sign the installer with a valid DSA key or use an .app bundle update instead."); - } - } else { - // For application bundle updates, validate the bundle code signatures and DSA signatures of archive together - validationCheckSuccess = [SPUInstallerValidation validateBundleUpdateForHost:host newBundleURL:installSourceURL archivePath:downloadPath DSASignature:DSASignature]; - } - } else if (isPackage) { - // We already prevalidated the package and nothing else needs to be done - validationCheckSuccess = YES; - } else { - // Because we already prevalidated the DSA signature, this is just a consistency check to see - // if the developer signed their application properly with their Apple ID - // Currently, this case only gets hit for binary delta updates - validationCheckSuccess = [SPUInstallerValidation validateCodeSignatureIfAvailableForBundleURL:installSourceURL]; - } + return NO; + } + + NSURL *installSourceURL = [NSURL fileURLWithPath:installSource]; + + if (!prevalidatedDsaSignature) { + // Check to see if we have a package or bundle to validate + if (isPackage) { + // If we get here, then the appcast installation type was lying to us.. This error will be caught later when starting the installer. + // For package type updates, all we do is check if the DSA signature is valid + BOOL validationCheckSuccess = [SPUInstallerValidation validateUpdateForHost:host archivePath:downloadPath DSASignature:DSASignature]; + if (!validationCheckSuccess) { + SULog(@"DSA signature validation of the package failed. The update contains an installer package, and valid DSA signatures are mandatory for all installer packages. The update will be rejected. Sign the installer with a valid DSA key or use an .app bundle update instead."); + } + return validationCheckSuccess; + } else { + // For application bundle updates, we check both the DSA and Apple code signing signatures + return [SPUInstallerValidation validateBundleUpdateForHost:host newBundleURL:installSourceURL archivePath:downloadPath DSASignature:DSASignature]; + } + } else if (isPackage) { + // We shouldn't get here because we don't validate packages before extracting them currently + SULog(@"Error: not expecting to find package after being required to validate update before extraction"); + return NO; + } else { + // Because we already validated the DSA signature, this is just a consistency check to see + // if the developer signed their application properly with their Apple ID + // Currently, this case only gets hit for binary delta updates + return [SPUInstallerValidation validateCodeSignatureIfAvailableForBundleURL:installSourceURL]; } - - return validationCheckSuccess; } @end diff --git a/Sparkle/SUVersionComparisonProtocol.h b/Sparkle/SUVersionComparisonProtocol.h index 23260c44..018cd23b 100644 --- a/Sparkle/SUVersionComparisonProtocol.h +++ b/Sparkle/SUVersionComparisonProtocol.h @@ -17,6 +17,8 @@ #import "SUExport.h" +NS_ASSUME_NONNULL_BEGIN + /*! Provides version comparison facilities for Sparkle. */ @@ -32,4 +34,5 @@ @end +NS_ASSUME_NONNULL_END #endif diff --git a/Sparkle/SUVersionDisplayProtocol.h b/Sparkle/SUVersionDisplayProtocol.h index 088e0683..14e10652 100644 --- a/Sparkle/SUVersionDisplayProtocol.h +++ b/Sparkle/SUVersionDisplayProtocol.h @@ -25,6 +25,6 @@ Both versions are provided so that important distinguishing information can be displayed while also leaving out unnecessary/confusing parts. */ -- (void)formatVersion:(NSString **)inOutVersionA andVersion:(NSString **)inOutVersionB; +- (void)formatVersion:(NSString *_Nonnull*_Nonnull)inOutVersionA andVersion:(NSString *_Nonnull*_Nonnull)inOutVersionB; @end diff --git a/TestApplication/English.lproj/MainMenu.xib b/TestApplication/English.lproj/MainMenu.xib index fabc5747..a8e12383 100644 --- a/TestApplication/English.lproj/MainMenu.xib +++ b/TestApplication/English.lproj/MainMenu.xib @@ -1,7 +1,7 @@ - - + + - + @@ -96,12 +96,14 @@ - + + + diff --git a/TestApplication/TestApplication-Info.plist b/TestApplication/TestApplication-Info.plist index a6496358..6a2ddafe 100644 --- a/TestApplication/TestApplication-Info.plist +++ b/TestApplication/TestApplication-Info.plist @@ -27,7 +27,7 @@ SUEnableSystemProfiling SUFeedURL - http://0.0.0.0:1337/sparkletestcast.xml + http://localhost:1337/sparkletestcast.xml SUPublicDSAKeyFile test_app_only_dsa_pub.pem diff --git a/TestApplication/sparkletestcast.xml b/TestApplication/sparkletestcast.xml index 670d606c..38eb19b8 100644 --- a/TestApplication/sparkletestcast.xml +++ b/TestApplication/sparkletestcast.xml @@ -17,7 +17,7 @@ ]]> Sat, 26 Jul 2014 15:20:11 +0000 - + diff --git a/Tests/Resources/testappcast.xml b/Tests/Resources/testappcast.xml index 2a5d2ef9..ff8e6b41 100644 --- a/Tests/Resources/testappcast.xml +++ b/Tests/Resources/testappcast.xml @@ -6,21 +6,21 @@ Version 2.0 desc Sat, 26 Jul 2014 15:20:11 +0000 - + Version 3.0 - + - - Version 4.0 Sat, 26 Jul 2014 15:20:13 +0000 - + 17.0.0 Version 5.0 - + 2.0.0 diff --git a/Tests/Resources/testnamespaces.xml b/Tests/Resources/testnamespaces.xml index 97236909..4bfd7f89 100644 --- a/Tests/Resources/testnamespaces.xml +++ b/Tests/Resources/testnamespaces.xml @@ -6,13 +6,13 @@ Version 3.0 Sat, 26 Jul 2014 15:20:12 +0000 https://sparkle-project.org/#works - + Version 2.0 desc Sat, 26 Jul 2014 15:20:11 +0000 - + diff --git a/Tests/SUBinaryDeltaTest.m b/Tests/SUBinaryDeltaTest.m index 45c47633..7978fa5c 100644 --- a/Tests/SUBinaryDeltaTest.m +++ b/Tests/SUBinaryDeltaTest.m @@ -69,7 +69,7 @@ typedef void (^SUDeltaHandler)(NSFileManager *fileManager, NSString *sourceDirec NSError *applyDiffError = nil; BOOL appliedDiff = NO; if (createdDiff) { - if (applyBinaryDelta(sourceDirectory, patchDirectory, diffFile, NO, &applyDiffError)) { + if (applyBinaryDelta(sourceDirectory, patchDirectory, diffFile, NO, ^(__unused double progress){}, &applyDiffError)) { appliedDiff = YES; } else { NSLog(@"Applying binary diff failed with error: %@", applyDiffError); diff --git a/Tests/SUUnarchiverTest.swift b/Tests/SUUnarchiverTest.swift index 91348f95..c0ce8435 100644 --- a/Tests/SUUnarchiverTest.swift +++ b/Tests/SUUnarchiverTest.swift @@ -8,26 +8,13 @@ import XCTest -class SUUnarchiverTest: XCTestCase, SUUnarchiverDelegate +class SUUnarchiverTest: XCTestCase { var password: String? = nil - var unarchivedExpectation: XCTestExpectation? = nil - var unarchivedResult: Bool = false + var unarchivedSuccessExpectation: XCTestExpectation? = nil + var unarchivedFailureExpectation: XCTestExpectation? = nil - func unarchiverDidFail() - { - self.unarchivedResult = false - self.unarchivedExpectation!.fulfill() - } - - func unarchiverDidFinish() - { - self.unarchivedResult = true - self.unarchivedExpectation!.fulfill() - } - - func unarchiveTestAppWithExtension(_ archiveExtension: String) - { + func unarchiveTestAppWithExtension(_ archiveExtension: String) { let appName = "SparkleTestCodeSignApp" let archiveResourceURL = Bundle(for: type(of: self)).url(forResource: appName, withExtension: archiveExtension)! @@ -38,24 +25,46 @@ class SUUnarchiverTest: XCTestCase, SUUnarchiverDelegate try! fileManager.removeItem(at: tempDirectoryURL) } + self.unarchivedSuccessExpectation = super.expectation(description: "Unarchived Success (format: \(archiveExtension))") + self.unarchivedFailureExpectation = super.expectation(description: "Unarchived Failure (format: \(archiveExtension))") + let tempArchiveURL = tempDirectoryURL.appendingPathComponent(archiveResourceURL.lastPathComponent) let extractedAppURL = tempDirectoryURL.appendingPathComponent(appName).appendingPathExtension("app") - try! fileManager.copyItem(at: archiveResourceURL, to: tempArchiveURL) - - self.unarchivedExpectation = super.expectation(description: "Unarchived Application (format: \(archiveExtension))") - - let unarchiver = SUUnarchiver.unarchiver(forPath: tempArchiveURL.path, updatingHostBundlePath: nil, decryptionPassword: self.password, delegate: self) - unarchiver!.start() + self.unarchiveTestSuccessAppWithExtension(archiveExtension, appName: appName, tempDirectoryURL: tempDirectoryURL, tempArchiveURL: tempArchiveURL, archiveResourceURL: archiveResourceURL); + self.unarchiveTestFailureAppWithExtension(archiveExtension, tempDirectoryURL: tempDirectoryURL); super.waitForExpectations(timeout: 7.0, handler: nil) - - XCTAssertTrue(self.unarchivedResult) + XCTAssertTrue(fileManager.fileExists(atPath: extractedAppURL.path)) XCTAssertEqual("6a60ab31430cfca8fb499a884f4a29f73e59b472", hashOfTree(extractedAppURL.path)) } + func unarchiveTestFailureAppWithExtension(_ archiveExtension: String, tempDirectoryURL: URL) { + let tempArchiveURL = tempDirectoryURL.appendingPathComponent("error-invalid").appendingPathExtension(archiveExtension); + let unarchiver = SUUnarchiver.unarchiver(forPath: tempArchiveURL.path, updatingHostBundlePath: nil, decryptionPassword: self.password)! + + unarchiver.unarchive(completionBlock: {(error: Error?) -> Void in + XCTAssertNotNil(error); + self.unarchivedFailureExpectation!.fulfill() + }, progressBlock: nil); + } + + func unarchiveTestSuccessAppWithExtension(_ archiveExtension: String, appName: String, tempDirectoryURL: URL, tempArchiveURL: URL, archiveResourceURL: URL) { + + let fileManager = FileManager.default + + try! fileManager.copyItem(at: archiveResourceURL, to: tempArchiveURL) + + let unarchiver = SUUnarchiver.unarchiver(forPath: tempArchiveURL.path, updatingHostBundlePath: nil, decryptionPassword: self.password)! + + unarchiver.unarchive(completionBlock: {(error: Error?) -> Void in + XCTAssertNil(error); + self.unarchivedSuccessExpectation!.fulfill() + }, progressBlock: nil); + } + func testUnarchivingZip() { self.unarchiveTestAppWithExtension("zip") diff --git a/Tests/Sparkle Unit Tests-Bridging-Header.h b/Tests/Sparkle Unit Tests-Bridging-Header.h index 665dd14d..5938acd2 100644 --- a/Tests/Sparkle Unit Tests-Bridging-Header.h +++ b/Tests/Sparkle Unit Tests-Bridging-Header.h @@ -14,27 +14,31 @@ #import "SUVersionComparisonProtocol.h" #import "SUStandardVersionComparator.h" +NS_ASSUME_NONNULL_BEGIN + // Duplicated to avoid exporting a private symbol from SUFileManager static const char *SUAppleQuarantineIdentifier = "com.apple.quarantine"; @interface SUFileManager (Private) -- (BOOL)_acquireAuthorizationWithError:(NSError *__autoreleasing *)error; +- (BOOL)_acquireAuthorizationWithError:(NSError *_Nullable __autoreleasing *_Nullable)error; - (BOOL)_itemExistsAtURL:(NSURL *)fileURL; -- (BOOL)_itemExistsAtURL:(NSURL *)fileURL isDirectory:(BOOL *)isDirectory; +- (BOOL)_itemExistsAtURL:(NSURL *)fileURL isDirectory:(nullable BOOL *)isDirectory; @end @interface SUAppcastDriver (Private) -+ (SUAppcastItem *)bestItemFromAppcastItems:(NSArray *)appcastItems getDeltaItem:(SUAppcastItem * __autoreleasing *)deltaItem withHostVersion:(NSString *)hostVersion comparator:(id)comparator; ++ (SUAppcastItem *)bestItemFromAppcastItems:(NSArray *)appcastItems getDeltaItem:(SUAppcastItem *_Nullable __autoreleasing *_Nullable)deltaItem withHostVersion:(NSString *)hostVersion comparator:(id)comparator; @end @interface SUAppcast (Private) -- (NSArray *)parseAppcastItemsFromXMLData:(NSData *)appcastData error:(NSError *__autoreleasing*)errorp; + +-(NSArray * _Nullable)parseAppcastItemsFromXMLData:(NSData *)appcastData error:(NSError *__autoreleasing*)errorp; + @end @interface SUBinaryDeltaUnarchiver (Private) @@ -42,3 +46,5 @@ static const char *SUAppleQuarantineIdentifier = "com.apple.quarantine"; + (void)updateSpotlightImportersAtBundlePath:(NSString *)targetPath; @end + +NS_ASSUME_NONNULL_END diff --git a/UITests/SUTestApplicationTest.swift b/UITests/SUTestApplicationTest.swift index 72cd02fb..7074953b 100644 --- a/UITests/SUTestApplicationTest.swift +++ b/UITests/SUTestApplicationTest.swift @@ -76,13 +76,18 @@ class SUTestApplicationTest: XCTestCase { let app = XCUIApplication() let menuBarsQuery = app.menuBars - + menuBarsQuery.menuBarItems["Sparkle Test App"].click() // If the update window already showed up automatically, this option will be disabled. // Even if it's disabled, attempting to click it will do no harm and continue on menuBarsQuery.menuItems["Check for Updates…"].click() + // Workaround to make sure we can click the install update button later + // This workaround is needed if the alert prompts up automatically *before* we manually check for updates + // I'm not sure why this workaround works or is necessary + app.dialogs["SUUpdateAlert"].staticTexts["Software Update"].click() + app.dialogs["SUUpdateAlert"].buttons["Install Update"].click() app.buttons["Install and Relaunch"].click()