From 6e754d7e4fb4ef5f00a6efcf45aa978ca4a2f55b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kornel=20Lesin=CC=81ski?= Date: Sun, 4 Dec 2016 13:40:59 +0000 Subject: [PATCH 01/27] Use return instead of state variable --- Sparkle/SUUpdateValidator.m | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/Sparkle/SUUpdateValidator.m b/Sparkle/SUUpdateValidator.m index 71727e89..11d392eb 100644 --- a/Sparkle/SUUpdateValidator.m +++ b/Sparkle/SUUpdateValidator.m @@ -78,14 +78,13 @@ 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; + return NO; } else { NSURL *installSourceURL = [NSURL fileURLWithPath:installSource]; @@ -93,18 +92,19 @@ // Check to see if we have a package or bundle to validate if (isPackage) { // For package type updates, all we do is check if the DSA signature is valid - validationCheckSuccess = [SUDSAVerifier validatePath:downloadPath withEncodedDSASignature:DSASignature withPublicDSAKey:publicDSAKey]; + BOOL validationCheckSuccess = [SUDSAVerifier validatePath:downloadPath withEncodedDSASignature:DSASignature withPublicDSAKey:publicDSAKey]; 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 - validationCheckSuccess = [self validateUpdateForHost:host downloadedToPath:downloadPath newBundleURL:installSourceURL DSASignature:DSASignature]; + return [self validateUpdateForHost:host downloadedToPath:downloadPath newBundleURL:installSourceURL 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"); - validationCheckSuccess = NO; + 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 @@ -112,14 +112,12 @@ NSError *error = nil; if ([SUCodeSigningVerifier bundleAtURLIsCodeSigned:installSourceURL] && ![SUCodeSigningVerifier codeSignatureIsValidAtBundleURL:installSourceURL error:&error]) { SULog(@"Failed to validate apple code sign signature on bundle after archive validation with error: %@", error); - validationCheckSuccess = NO; + return NO; } else { - validationCheckSuccess = YES; + return YES; } } } - - return validationCheckSuccess; } /** From 19455099ff35c4de6ed0a4b5d4ac6feea93b723e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kornel=20Lesin=CC=81ski?= Date: Sun, 4 Dec 2016 13:43:24 +0000 Subject: [PATCH 02/27] Formatting --- Sparkle/SUUpdateValidator.m | 88 ++++++++++++++++++------------------- 1 file changed, 44 insertions(+), 44 deletions(-) diff --git a/Sparkle/SUUpdateValidator.m b/Sparkle/SUUpdateValidator.m index 11d392eb..164da998 100644 --- a/Sparkle/SUUpdateValidator.m +++ b/Sparkle/SUUpdateValidator.m @@ -38,7 +38,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"); @@ -51,13 +51,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]; @@ -70,52 +70,52 @@ - (BOOL)validateWithUpdateDirectory:(NSString *)updateDirectory { assert(self.canValidate); - + NSString *DSASignature = self.dsaSignature; NSString *publicDSAKey = self.host.publicDSAKey; NSString *downloadPath = self.downloadPath; SUHost *host = self.host; - + BOOL prevalidatedDsaSignature = self.prevalidatedDsaSignature; - + 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."); return NO; - } else { - NSURL *installSourceURL = [NSURL fileURLWithPath:installSource]; - - if (!prevalidatedDsaSignature) { - // Check to see if we have a package or bundle to validate - if (isPackage) { - // For package type updates, all we do is check if the DSA signature is valid - BOOL validationCheckSuccess = [SUDSAVerifier validatePath:downloadPath withEncodedDSASignature:DSASignature withPublicDSAKey:publicDSAKey]; - 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 [self validateUpdateForHost:host downloadedToPath:downloadPath newBundleURL:installSourceURL DSASignature:DSASignature]; + } + + NSURL *installSourceURL = [NSURL fileURLWithPath:installSource]; + + if (!prevalidatedDsaSignature) { + // Check to see if we have a package or bundle to validate + if (isPackage) { + // For package type updates, all we do is check if the DSA signature is valid + BOOL validationCheckSuccess = [SUDSAVerifier validatePath:downloadPath withEncodedDSASignature:DSASignature withPublicDSAKey:publicDSAKey]; + 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 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 validationCheckSuccess; + } else { + // For application bundle updates, we check both the DSA and Apple code signing signatures + return [self validateUpdateForHost:host downloadedToPath:downloadPath newBundleURL:installSourceURL 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 + NSError *error = nil; + if ([SUCodeSigningVerifier bundleAtURLIsCodeSigned:installSourceURL] && ![SUCodeSigningVerifier codeSignatureIsValidAtBundleURL:installSourceURL error:&error]) { + SULog(@"Failed to validate apple code sign signature on bundle after archive validation with error: %@", error); 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 - NSError *error = nil; - if ([SUCodeSigningVerifier bundleAtURLIsCodeSigned:installSourceURL] && ![SUCodeSigningVerifier codeSignatureIsValidAtBundleURL:installSourceURL error:&error]) { - SULog(@"Failed to validate apple code sign signature on bundle after archive validation with error: %@", error); - return NO; - } else { - return YES; - } + return YES; } } } @@ -135,20 +135,20 @@ SULog(@"No suitable bundle is found in the update. The update will be rejected."); return NO; } - + NSString *publicDSAKey = host.publicDSAKey; - + SUHost *newHost = [[SUHost alloc] initWithBundle:newBundle]; NSString *newPublicDSAKey = newHost.publicDSAKey; - + // Downgrade in DSA security should not be possible if (publicDSAKey != nil && newPublicDSAKey == nil) { SULog(@"A public DSA key is found in the old bundle but no public DSA key is found in the new update. For security reasons, the update will be rejected."); return NO; } - + BOOL dsaKeysMatch = (publicDSAKey == nil || newPublicDSAKey == nil) ? NO : [publicDSAKey isEqualToString:newPublicDSAKey]; - + // If the new DSA key differs from the old, then this check is not a security measure, because the new key is not trusted. // In that case, the check ensures that the app author has correctly used DSA keys, so that the app will be updateable in the next version. // However if the new and old DSA keys are the same, then this is a security measure. @@ -160,7 +160,7 @@ } } BOOL updateIsCodeSigned = [SUCodeSigningVerifier bundleAtURLIsCodeSigned:newHost.bundle.bundleURL]; - + if (dsaKeysMatch) { NSError *error = nil; if (updateIsCodeSigned && ![SUCodeSigningVerifier codeSignatureIsValidAtBundleURL:newHost.bundle.bundleURL error:&error]) { @@ -169,21 +169,21 @@ } } else { BOOL hostIsCodeSigned = [SUCodeSigningVerifier bundleAtURLIsCodeSigned:host.bundle.bundleURL]; - + NSString *dsaStatus = newPublicDSAKey ? @"has a new DSA key that doesn't match the previous one" : (publicDSAKey ? @"removes the DSA key" : @"isn't signed with a DSA key"); if (!hostIsCodeSigned || !updateIsCodeSigned) { NSString *acsStatus = !hostIsCodeSigned ? @"old app hasn't been signed with app Code Signing" : @"new app isn't signed with app Code Signing"; SULog(@"The update archive %@, and the %@. At least one method of signature verification must be valid. The update will be rejected.", dsaStatus, acsStatus); return NO; } - + NSError *error = nil; if (![SUCodeSigningVerifier codeSignatureAtBundleURL:host.bundle.bundleURL matchesSignatureAtBundleURL:newHost.bundle.bundleURL error:&error]) { SULog(@"The update archive %@, and the app is signed with a new Code Signing identity that doesn't match code signing of the original app: %@. At least one method of signature verification must be valid. The update will be rejected.", dsaStatus, error); return NO; } } - + return YES; } From f3f268388b75188e89c4d1851b44b9f5f963ca6c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kornel=20Lesin=CC=81ski?= Date: Tue, 20 Dec 2016 21:36:31 +0100 Subject: [PATCH 03/27] Nullability declarations --- Sparkle/SUUnarchiver.h | 11 +++++++---- Tests/SUUnarchiverTest.swift | 6 +++--- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/Sparkle/SUUnarchiver.h b/Sparkle/SUUnarchiver.h index e2f79f04..17ba37da 100644 --- a/Sparkle/SUUnarchiver.h +++ b/Sparkle/SUUnarchiver.h @@ -11,17 +11,19 @@ #import +NS_ASSUME_NONNULL_BEGIN + @class SUHost; @protocol SUUnarchiverDelegate; @interface SUUnarchiver : NSObject @property (copy, readonly) NSString *archivePath; -@property (copy, readonly) NSString *updateHostBundlePath; -@property (copy, readonly) NSString *decryptionPassword; -@property (weak) id delegate; +@property (copy, readonly) NSString *_Nullable updateHostBundlePath; +@property (copy, readonly) NSString *_Nullable decryptionPassword; +@property (weak) _Nullable id delegate; -+ (SUUnarchiver *)unarchiverForPath:(NSString *)path updatingHostBundlePath:(NSString *)host withPassword:(NSString *)decryptionPassword; ++ (nullable SUUnarchiver *)unarchiverForPath:(NSString *)path updatingHostBundlePath:(nullable NSString *)host withPassword:(nullable NSString *)decryptionPassword; + (BOOL)unsafeIfArchiveIsNotValidated; @@ -36,4 +38,5 @@ - (void)unarchiver:(SUUnarchiver *)unarchiver extractedProgress:(double)progress; @end +NS_ASSUME_NONNULL_END #endif diff --git a/Tests/SUUnarchiverTest.swift b/Tests/SUUnarchiverTest.swift index 4e70bba8..0505e6c5 100644 --- a/Tests/SUUnarchiverTest.swift +++ b/Tests/SUUnarchiverTest.swift @@ -14,17 +14,17 @@ class SUUnarchiverTest: XCTestCase, SUUnarchiverDelegate var unarchivedExpectation: XCTestExpectation? = nil var unarchivedResult: Bool = false - func unarchiver(_ unarchiver: SUUnarchiver!, extractedProgress progress: Double) + func unarchiver(_ unarchiver: SUUnarchiver, extractedProgress progress: Double) { } - func unarchiverDidFail(_ unarchiver: SUUnarchiver!) + func unarchiverDidFail(_ unarchiver: SUUnarchiver) { self.unarchivedResult = false self.unarchivedExpectation!.fulfill() } - func unarchiverDidFinish(_ unarchiver: SUUnarchiver!) + func unarchiverDidFinish(_ unarchiver: SUUnarchiver) { self.unarchivedResult = true self.unarchivedExpectation!.fulfill() From 9d8b3c0c3611e8c90975e9269b5549b9cf812a31 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kornel=20Lesin=CC=81ski?= Date: Tue, 20 Dec 2016 22:09:28 +0100 Subject: [PATCH 04/27] DRY async dispatch of unarchiver notifications --- Sparkle/SUBinaryDeltaUnarchiver.m | 9 ++------- Sparkle/SUDiskImageUnarchiver.m | 16 ++++------------ Sparkle/SUPipedUnarchiver.m | 8 ++------ Sparkle/SUUnarchiver.m | 16 ++++++++++------ 4 files changed, 18 insertions(+), 31 deletions(-) diff --git a/Sparkle/SUBinaryDeltaUnarchiver.m b/Sparkle/SUBinaryDeltaUnarchiver.m index 5ff34bd8..30c51f05 100644 --- a/Sparkle/SUBinaryDeltaUnarchiver.m +++ b/Sparkle/SUBinaryDeltaUnarchiver.m @@ -71,16 +71,11 @@ BOOL success = applyBinaryDelta(sourcePath, targetPath, self.archivePath, NO, &applyDiffError); if (success) { [[self class] updateSpotlightImportersAtBundlePath:targetPath]; - - dispatch_async(dispatch_get_main_queue(), ^{ - [self notifyDelegateOfSuccess]; - }); + [self notifyDelegateOfSuccess]; } else { SULog(@"Applying delta patch failed with error: %@", applyDiffError); - dispatch_async(dispatch_get_main_queue(), ^{ - [self notifyDelegateOfFailure]; - }); + [self notifyDelegateOfFailure]; } } } diff --git a/Sparkle/SUDiskImageUnarchiver.m b/Sparkle/SUDiskImageUnarchiver.m index e6f743e7..cae38bb1 100644 --- a/Sparkle/SUDiskImageUnarchiver.m +++ b/Sparkle/SUDiskImageUnarchiver.m @@ -45,16 +45,8 @@ 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 notifyDelegateOfFailure]; - }; - dispatch_block_t delegateSuccess = ^{ - [self notifyDelegateOfSuccess]; - }; - 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. @@ -156,11 +148,11 @@ } } - dispatch_async(dispatch_get_main_queue(), delegateSuccess); + [self notifyDelegateOfSuccess]; goto finally; reportError: - dispatch_async(dispatch_get_main_queue(), delegateFailure); + [self notifyDelegateOfFailure]; finally: if (mountedSuccessfully) { diff --git a/Sparkle/SUPipedUnarchiver.m b/Sparkle/SUPipedUnarchiver.m index 0b0157c3..aebc5b46 100644 --- a/Sparkle/SUPipedUnarchiver.m +++ b/Sparkle/SUPipedUnarchiver.m @@ -104,9 +104,7 @@ if ([task terminationStatus] == 0) { if (bytesRead == expectedLength) { - dispatch_async(dispatch_get_main_queue(), ^{ - [self notifyDelegateOfSuccess]; - }); + [self notifyDelegateOfSuccess]; return; } else { SULog(@"Extraction failed, command '%@' got only %ld of %ld bytes", command, (long)bytesRead, (long)expectedLength); @@ -118,9 +116,7 @@ SULog(@"Extraction failed, archive '%@' is empty", self.archivePath); } - dispatch_async(dispatch_get_main_queue(), ^{ - [self notifyDelegateOfFailure]; - }); + [self notifyDelegateOfFailure]; } } diff --git a/Sparkle/SUUnarchiver.m b/Sparkle/SUUnarchiver.m index b12d0648..c65c5166 100644 --- a/Sparkle/SUUnarchiver.m +++ b/Sparkle/SUUnarchiver.m @@ -69,16 +69,20 @@ - (void)notifyDelegateOfSuccess { - if ([self.delegate respondsToSelector:@selector(unarchiverDidFinish:)]) { - [self.delegate unarchiverDidFinish:self]; - } + dispatch_async(dispatch_get_main_queue(), ^{ + if ([self.delegate respondsToSelector:@selector(unarchiverDidFinish:)]) { + [self.delegate unarchiverDidFinish:self]; + } + }); } - (void)notifyDelegateOfFailure { - if ([self.delegate respondsToSelector:@selector(unarchiverDidFail:)]) { - [self.delegate unarchiverDidFail:self]; - } + dispatch_async(dispatch_get_main_queue(), ^{ + if ([self.delegate respondsToSelector:@selector(unarchiverDidFail:)]) { + [self.delegate unarchiverDidFail:self]; + } + }); } static NSMutableArray *gUnarchiverImplementations; From 311ed493b4b0fe25fa8299967e4579cf9f5a3f7d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kornel=20Lesin=CC=81ski?= Date: Tue, 20 Dec 2016 23:54:56 +0100 Subject: [PATCH 05/27] Unused --- Sparkle/SUDiskImageUnarchiver.m | 8 -------- 1 file changed, 8 deletions(-) diff --git a/Sparkle/SUDiskImageUnarchiver.m b/Sparkle/SUDiskImageUnarchiver.m index cae38bb1..68f3f2e6 100644 --- a/Sparkle/SUDiskImageUnarchiver.m +++ b/Sparkle/SUDiskImageUnarchiver.m @@ -25,14 +25,6 @@ // Called on a non-main thread. - (void)extractDMG -{ - @autoreleasepool { - [self extractDMGWithPassword:nil]; - } -} - -// Called on a non-main thread. -- (void)extractDMGWithPassword:(NSString *)__unused password { @autoreleasepool { BOOL mountedSuccessfully = NO; From 23b2b49663963e97d36b22d502c29a233282a558 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kornel=20Lesin=CC=81ski?= Date: Wed, 21 Dec 2016 00:05:16 +0100 Subject: [PATCH 06/27] Ability to report specific unarchiving error --- Sparkle/SUBinaryDeltaUnarchiver.m | 3 +-- Sparkle/SUDiskImageUnarchiver.m | 3 +-- Sparkle/SUPipedUnarchiver.m | 11 ++++++----- Sparkle/SUUnarchiver.m | 2 +- Sparkle/SUUnarchiver_Private.h | 2 +- 5 files changed, 10 insertions(+), 11 deletions(-) diff --git a/Sparkle/SUBinaryDeltaUnarchiver.m b/Sparkle/SUBinaryDeltaUnarchiver.m index 30c51f05..04aba6ff 100644 --- a/Sparkle/SUBinaryDeltaUnarchiver.m +++ b/Sparkle/SUBinaryDeltaUnarchiver.m @@ -74,8 +74,7 @@ [self notifyDelegateOfSuccess]; } else { - SULog(@"Applying delta patch failed with error: %@", applyDiffError); - [self notifyDelegateOfFailure]; + [self unarchiverDidFailWithError:applyDiffError]; } } } diff --git a/Sparkle/SUDiskImageUnarchiver.m b/Sparkle/SUDiskImageUnarchiver.m index 68f3f2e6..40b69fce 100644 --- a/Sparkle/SUDiskImageUnarchiver.m +++ b/Sparkle/SUDiskImageUnarchiver.m @@ -135,7 +135,6 @@ if (![manager copyItemAtPath:fromPath toPath:toPath error:&error]) { - SULog(@"Couldn't copy item: %@ : %@", error, error.userInfo ? error.userInfo : @""); goto reportError; } } @@ -144,7 +143,7 @@ goto finally; reportError: - [self notifyDelegateOfFailure]; + [self unarchiverDidFailWithError:error]; finally: if (mountedSuccessfully) { diff --git a/Sparkle/SUPipedUnarchiver.m b/Sparkle/SUPipedUnarchiver.m index aebc5b46..6b7373e9 100644 --- a/Sparkle/SUPipedUnarchiver.m +++ b/Sparkle/SUPipedUnarchiver.m @@ -61,7 +61,7 @@ { // *** GETS CALLED ON NON-MAIN THREAD!!! @autoreleasepool { - + NSError *error = nil; NSString *destination = [self.archivePath stringByDeletingLastPathComponent]; SULog(@"Extracting using '%@' '%@' < '%@' '%@'", command, [args componentsJoinedByString:@"' '"], self.archivePath, destination); @@ -107,16 +107,17 @@ [self notifyDelegateOfSuccess]; 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]}]; } - [self notifyDelegateOfFailure]; + [self unarchiverDidFailWithError:error]; } } diff --git a/Sparkle/SUUnarchiver.m b/Sparkle/SUUnarchiver.m index c65c5166..1b8d292a 100644 --- a/Sparkle/SUUnarchiver.m +++ b/Sparkle/SUUnarchiver.m @@ -76,7 +76,7 @@ }); } -- (void)notifyDelegateOfFailure +- (void)unarchiverDidFailWithError:(NSError *)error { dispatch_async(dispatch_get_main_queue(), ^{ if ([self.delegate respondsToSelector:@selector(unarchiverDidFail:)]) { diff --git a/Sparkle/SUUnarchiver_Private.h b/Sparkle/SUUnarchiver_Private.h index c29d68cf..f8853d1f 100644 --- a/Sparkle/SUUnarchiver_Private.h +++ b/Sparkle/SUUnarchiver_Private.h @@ -20,7 +20,7 @@ - (void)notifyDelegateOfProgress:(double)progress; - (void)notifyDelegateOfSuccess; -- (void)notifyDelegateOfFailure; +- (void)unarchiverDidFailWithError:(NSError *)error; @end #endif From 5ee02e954e46b488888492d5d6a4ed3011269a2d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kornel=20Lesin=CC=81ski?= Date: Tue, 20 Dec 2016 23:40:30 +0100 Subject: [PATCH 07/27] Renamed callbacks --- Sparkle/SUBasicUpdateDriver.m | 4 ++-- Sparkle/SUBinaryDeltaUnarchiver.m | 2 +- Sparkle/SUDiskImageUnarchiver.m | 2 +- Sparkle/SUPipedUnarchiver.m | 2 +- Sparkle/SUUnarchiver.m | 4 ++-- Sparkle/SUUnarchiver_Private.h | 4 ++-- 6 files changed, 9 insertions(+), 9 deletions(-) diff --git a/Sparkle/SUBasicUpdateDriver.m b/Sparkle/SUBasicUpdateDriver.m index 0c714d03..3735b6ba 100644 --- a/Sparkle/SUBasicUpdateDriver.m +++ b/Sparkle/SUBasicUpdateDriver.m @@ -356,7 +356,7 @@ [self installWithToolAndRelaunch:YES]; } -- (void)unarchiverDidFail:(SUUnarchiver *)__unused ua +- (void)unarchiverDidFail:(NSError *)err { // No longer needed self.updateValidator = nil; @@ -366,7 +366,7 @@ return; } - [self abortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while extracting the archive. Please try again later.", nil) }]]; + [self abortUpdateWithError:err]; } - (void)installWithToolAndRelaunch:(BOOL)relaunch diff --git a/Sparkle/SUBinaryDeltaUnarchiver.m b/Sparkle/SUBinaryDeltaUnarchiver.m index 04aba6ff..046dd0db 100644 --- a/Sparkle/SUBinaryDeltaUnarchiver.m +++ b/Sparkle/SUBinaryDeltaUnarchiver.m @@ -71,7 +71,7 @@ BOOL success = applyBinaryDelta(sourcePath, targetPath, self.archivePath, NO, &applyDiffError); if (success) { [[self class] updateSpotlightImportersAtBundlePath:targetPath]; - [self notifyDelegateOfSuccess]; + [self unarchiverDidFinish]; } else { [self unarchiverDidFailWithError:applyDiffError]; diff --git a/Sparkle/SUDiskImageUnarchiver.m b/Sparkle/SUDiskImageUnarchiver.m index 40b69fce..06cba163 100644 --- a/Sparkle/SUDiskImageUnarchiver.m +++ b/Sparkle/SUDiskImageUnarchiver.m @@ -139,7 +139,7 @@ } } - [self notifyDelegateOfSuccess]; + [self unarchiverDidFinish]; goto finally; reportError: diff --git a/Sparkle/SUPipedUnarchiver.m b/Sparkle/SUPipedUnarchiver.m index 6b7373e9..8b34d666 100644 --- a/Sparkle/SUPipedUnarchiver.m +++ b/Sparkle/SUPipedUnarchiver.m @@ -104,7 +104,7 @@ if ([task terminationStatus] == 0) { if (bytesRead == expectedLength) { - [self notifyDelegateOfSuccess]; + [self unarchiverDidFinish]; return; } else { error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Extraction failed, command '%@' got only %ld of %ld bytes", command, (long)bytesRead, (long)expectedLength]}]; diff --git a/Sparkle/SUUnarchiver.m b/Sparkle/SUUnarchiver.m index 1b8d292a..9b309a70 100644 --- a/Sparkle/SUUnarchiver.m +++ b/Sparkle/SUUnarchiver.m @@ -67,7 +67,7 @@ } } -- (void)notifyDelegateOfSuccess +- (void)unarchiverDidFinish { dispatch_async(dispatch_get_main_queue(), ^{ if ([self.delegate respondsToSelector:@selector(unarchiverDidFinish:)]) { @@ -76,7 +76,7 @@ }); } -- (void)unarchiverDidFailWithError:(NSError *)error +- (void)unarchiverDidFail:(NSError *)reason { dispatch_async(dispatch_get_main_queue(), ^{ if ([self.delegate respondsToSelector:@selector(unarchiverDidFail:)]) { diff --git a/Sparkle/SUUnarchiver_Private.h b/Sparkle/SUUnarchiver_Private.h index f8853d1f..c7718e9f 100644 --- a/Sparkle/SUUnarchiver_Private.h +++ b/Sparkle/SUUnarchiver_Private.h @@ -19,8 +19,8 @@ - (instancetype)initWithPath:(NSString *)archive hostBundlePath:(NSString *)host; - (void)notifyDelegateOfProgress:(double)progress; -- (void)notifyDelegateOfSuccess; -- (void)unarchiverDidFailWithError:(NSError *)error; +- (void)unarchiverDidFinish; +- (void)unarchiverDidFailWithError:(NSError *)err; @end #endif From 70f56817974e034bcfbd7990d2fed8d5f68221fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kornel=20Lesin=CC=81ski?= Date: Wed, 21 Dec 2016 00:16:24 +0100 Subject: [PATCH 08/27] Use completion block for unarchiving --- Sparkle/SUBasicUpdateDriver.h | 2 -- Sparkle/SUBasicUpdateDriver.m | 17 +++++++++-------- Sparkle/SUBinaryDeltaUnarchiver.m | 3 ++- Sparkle/SUDiskImageUnarchiver.m | 3 ++- Sparkle/SUPipedUnarchiver.m | 3 ++- Sparkle/SUUnarchiver.h | 4 +--- Sparkle/SUUnarchiver.m | 25 ++++++++++++++++--------- Tests/SUUnarchiverTest.swift | 21 ++++++--------------- 8 files changed, 38 insertions(+), 40 deletions(-) diff --git a/Sparkle/SUBasicUpdateDriver.h b/Sparkle/SUBasicUpdateDriver.h index 301b4bc5..002d82e2 100644 --- a/Sparkle/SUBasicUpdateDriver.h +++ b/Sparkle/SUBasicUpdateDriver.h @@ -37,8 +37,6 @@ - (void)download:(NSURLDownload *)download didFailWithError:(NSError *)error; - (void)extractUpdate; -- (void)unarchiverDidFinish:(SUUnarchiver *)ua; -- (void)unarchiverDidFail:(SUUnarchiver *)ua; - (void)failedToApplyDeltaUpdate; - (void)installWithToolAndRelaunch:(BOOL)relaunch; diff --git a/Sparkle/SUBasicUpdateDriver.m b/Sparkle/SUBasicUpdateDriver.m index 3735b6ba..76ea355c 100644 --- a/Sparkle/SUBasicUpdateDriver.m +++ b/Sparkle/SUBasicUpdateDriver.m @@ -336,7 +336,15 @@ [self unarchiverDidFail:nil]; } else { unarchiver.delegate = self; - [unarchiver start]; + [unarchiver unarchiveWithCompletionBlock:^(NSError *err){ + if (err) { + [self unarchiverDidFail:err]; + return; + } + + assert(self.updateItem); + [self installWithToolAndRelaunch:YES]; + }]; } } @@ -349,13 +357,6 @@ [self downloadUpdate]; } -- (void)unarchiverDidFinish:(SUUnarchiver *)__unused ua -{ - assert(self.updateItem); - - [self installWithToolAndRelaunch:YES]; -} - - (void)unarchiverDidFail:(NSError *)err { // No longer needed diff --git a/Sparkle/SUBinaryDeltaUnarchiver.m b/Sparkle/SUBinaryDeltaUnarchiver.m index 046dd0db..f45cd26d 100644 --- a/Sparkle/SUBinaryDeltaUnarchiver.m +++ b/Sparkle/SUBinaryDeltaUnarchiver.m @@ -79,8 +79,9 @@ } } -- (void)start +- (void)unarchiveWithCompletionBlock:(void (^)(NSError * _Nullable))block { + [super unarchiveWithCompletionBlock:block]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ [self applyBinaryDelta]; }); diff --git a/Sparkle/SUDiskImageUnarchiver.m b/Sparkle/SUDiskImageUnarchiver.m index 06cba163..e731e9f3 100644 --- a/Sparkle/SUDiskImageUnarchiver.m +++ b/Sparkle/SUDiskImageUnarchiver.m @@ -159,8 +159,9 @@ } } -- (void)start +- (void)unarchiveWithCompletionBlock:(void (^)(NSError * _Nullable))block { + [super unarchiveWithCompletionBlock:block]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ [self extractDMG]; }); diff --git a/Sparkle/SUPipedUnarchiver.m b/Sparkle/SUPipedUnarchiver.m index 8b34d666..320d150d 100644 --- a/Sparkle/SUPipedUnarchiver.m +++ b/Sparkle/SUPipedUnarchiver.m @@ -46,8 +46,9 @@ return NO; } -- (void)start +- (void)unarchiveWithCompletionBlock:(void (^)(NSError * _Nullable))block { + [super unarchiveWithCompletionBlock:block]; [NSThread detachNewThreadSelector:[[self class] selectorConformingToTypeOfPath:self.archivePath] toTarget:self withObject:nil]; } diff --git a/Sparkle/SUUnarchiver.h b/Sparkle/SUUnarchiver.h index 17ba37da..486a3604 100644 --- a/Sparkle/SUUnarchiver.h +++ b/Sparkle/SUUnarchiver.h @@ -27,13 +27,11 @@ NS_ASSUME_NONNULL_BEGIN + (BOOL)unsafeIfArchiveIsNotValidated; -- (void)start; +- (void)unarchiveWithCompletionBlock:(void (^_Nonnull)(NSError *_Nullable))block; @end @protocol SUUnarchiverDelegate -- (void)unarchiverDidFinish:(SUUnarchiver *)unarchiver; -- (void)unarchiverDidFail:(SUUnarchiver *)unarchiver; @optional - (void)unarchiver:(SUUnarchiver *)unarchiver extractedProgress:(double)progress; @end diff --git a/Sparkle/SUUnarchiver.m b/Sparkle/SUUnarchiver.m index 9b309a70..d719a8bd 100644 --- a/Sparkle/SUUnarchiver.m +++ b/Sparkle/SUUnarchiver.m @@ -15,12 +15,17 @@ #import "SUUnarchiver.h" #import "SUUnarchiver_Private.h" +@interface SUUnarchiver () +@property (strong) void (^completionBlock)(NSError * _Nullable); +@end + @implementation SUUnarchiver @synthesize archivePath; @synthesize updateHostBundlePath; @synthesize delegate; @synthesize decryptionPassword; +@synthesize completionBlock; + (SUUnarchiver *)unarchiverForPath:(NSString *)path updatingHostBundlePath:(NSString *)hostPath withPassword:(NSString *)decryptionPassword { @@ -34,9 +39,8 @@ - (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], self.archivePath]; } -- (void)start -{ - // No-op +- (void)unarchiveWithCompletionBlock:(void (^_Nonnull)(NSError * _Nullable))block { + self.completionBlock = block; } - (instancetype)initWithPath:(NSString *)path hostBundlePath:(NSString *)hostPath password:(NSString *)password @@ -70,18 +74,21 @@ - (void)unarchiverDidFinish { dispatch_async(dispatch_get_main_queue(), ^{ - if ([self.delegate respondsToSelector:@selector(unarchiverDidFinish:)]) { - [self.delegate unarchiverDidFinish:self]; - } + self.completionBlock(nil); }); } - (void)unarchiverDidFail:(NSError *)reason { + NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithObject:SULocalizedString(@"An error occurred while extracting the archive. Please try again later.", nil) forKey:NSLocalizedDescriptionKey]; + if (reason) { + [userInfo setObject:reason forKey:NSUnderlyingErrorKey]; + } + + NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:userInfo]; + dispatch_async(dispatch_get_main_queue(), ^{ - if ([self.delegate respondsToSelector:@selector(unarchiverDidFail:)]) { - [self.delegate unarchiverDidFail:self]; - } + self.completionBlock(error); }); } diff --git a/Tests/SUUnarchiverTest.swift b/Tests/SUUnarchiverTest.swift index 0505e6c5..c2261077 100644 --- a/Tests/SUUnarchiverTest.swift +++ b/Tests/SUUnarchiverTest.swift @@ -18,18 +18,6 @@ class SUUnarchiverTest: XCTestCase, SUUnarchiverDelegate { } - func unarchiverDidFail(_ unarchiver: SUUnarchiver) - { - self.unarchivedResult = false - self.unarchivedExpectation!.fulfill() - } - - func unarchiverDidFinish(_ unarchiver: SUUnarchiver) - { - self.unarchivedResult = true - self.unarchivedExpectation!.fulfill() - } - func unarchiveTestAppWithExtension(_ archiveExtension: String) { let appName = "SparkleTestCodeSignApp" @@ -49,10 +37,13 @@ class SUUnarchiverTest: XCTestCase, SUUnarchiverDelegate self.unarchivedExpectation = super.expectation(description: "Unarchived Application (format: \(archiveExtension))") - let unarchiver = SUUnarchiver(forPath: tempArchiveURL.path, updatingHostBundlePath: nil, withPassword: self.password) + let unarchiver = SUUnarchiver(forPath: tempArchiveURL.path, updatingHostBundlePath: nil, withPassword: self.password)! - unarchiver?.delegate = self - unarchiver?.start() + unarchiver.delegate = self + unarchiver.unarchive {(error: Error?) -> Void in + self.unarchivedResult = nil == error; + self.unarchivedExpectation!.fulfill() + } super.waitForExpectations(timeout: 7.0, handler: nil) From 8103f5fd4339a6295a6dbec7e77b1f712ef58254 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kornel=20Lesin=CC=81ski?= Date: Wed, 21 Dec 2016 00:36:04 +0100 Subject: [PATCH 09/27] Replaced progress delegate with a block --- Sparkle/SUAutomaticUpdateDriver.h | 2 +- Sparkle/SUBasicUpdateDriver.h | 2 +- Sparkle/SUBasicUpdateDriver.m | 3 ++- Sparkle/SUBinaryDeltaUnarchiver.m | 4 ++-- Sparkle/SUDiskImageUnarchiver.m | 4 ++-- Sparkle/SUPipedUnarchiver.m | 6 +++--- Sparkle/SUUIBasedUpdateDriver.h | 2 +- Sparkle/SUUnarchiver.h | 9 +-------- Sparkle/SUUnarchiver.m | 14 ++++++++------ Sparkle/SUUnarchiver_Private.h | 2 +- Tests/SUUnarchiverTest.swift | 11 +++-------- 11 files changed, 25 insertions(+), 34 deletions(-) diff --git a/Sparkle/SUAutomaticUpdateDriver.h b/Sparkle/SUAutomaticUpdateDriver.h index 4dd90e8f..4af54a11 100644 --- a/Sparkle/SUAutomaticUpdateDriver.h +++ b/Sparkle/SUAutomaticUpdateDriver.h @@ -13,7 +13,7 @@ #import "SUBasicUpdateDriver.h" #import "SUAutomaticUpdateAlert.h" -@interface SUAutomaticUpdateDriver : SUBasicUpdateDriver +@interface SUAutomaticUpdateDriver : SUBasicUpdateDriver @end diff --git a/Sparkle/SUBasicUpdateDriver.h b/Sparkle/SUBasicUpdateDriver.h index 002d82e2..1dd8f367 100644 --- a/Sparkle/SUBasicUpdateDriver.h +++ b/Sparkle/SUBasicUpdateDriver.h @@ -15,7 +15,7 @@ #import "SUAppcast.h" @class SUAppcastItem, SUHost; -@interface SUBasicUpdateDriver : SUUpdateDriver +@interface SUBasicUpdateDriver : SUUpdateDriver @property (strong, readonly) SUAppcastItem *updateItem; @property (strong, readonly) NSURLDownload *download; diff --git a/Sparkle/SUBasicUpdateDriver.m b/Sparkle/SUBasicUpdateDriver.m index 76ea355c..6ee0aadd 100644 --- a/Sparkle/SUBasicUpdateDriver.m +++ b/Sparkle/SUBasicUpdateDriver.m @@ -335,7 +335,6 @@ if (!success) { [self unarchiverDidFail:nil]; } else { - unarchiver.delegate = self; [unarchiver unarchiveWithCompletionBlock:^(NSError *err){ if (err) { [self unarchiverDidFail:err]; @@ -344,6 +343,8 @@ assert(self.updateItem); [self installWithToolAndRelaunch:YES]; + } progressBlock:^(__unused double progress){ + }]; } } diff --git a/Sparkle/SUBinaryDeltaUnarchiver.m b/Sparkle/SUBinaryDeltaUnarchiver.m index f45cd26d..415c9033 100644 --- a/Sparkle/SUBinaryDeltaUnarchiver.m +++ b/Sparkle/SUBinaryDeltaUnarchiver.m @@ -79,9 +79,9 @@ } } -- (void)unarchiveWithCompletionBlock:(void (^)(NSError * _Nullable))block +- (void)unarchiveWithCompletionBlock:(void (^)(NSError * _Nullable))block progressBlock:(void (^ _Nullable)(double progress))progress { - [super unarchiveWithCompletionBlock:block]; + [super unarchiveWithCompletionBlock:block progressBlock:progress]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ [self applyBinaryDelta]; }); diff --git a/Sparkle/SUDiskImageUnarchiver.m b/Sparkle/SUDiskImageUnarchiver.m index e731e9f3..ae1987ef 100644 --- a/Sparkle/SUDiskImageUnarchiver.m +++ b/Sparkle/SUDiskImageUnarchiver.m @@ -159,9 +159,9 @@ } } -- (void)unarchiveWithCompletionBlock:(void (^)(NSError * _Nullable))block +- (void)unarchiveWithCompletionBlock:(void (^)(NSError * _Nullable))block progressBlock:(void (^ _Nullable)(double progress))progress { - [super unarchiveWithCompletionBlock:block]; + [super unarchiveWithCompletionBlock:block progressBlock:progress]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ [self extractDMG]; }); diff --git a/Sparkle/SUPipedUnarchiver.m b/Sparkle/SUPipedUnarchiver.m index 320d150d..40739497 100644 --- a/Sparkle/SUPipedUnarchiver.m +++ b/Sparkle/SUPipedUnarchiver.m @@ -46,9 +46,9 @@ return NO; } -- (void)unarchiveWithCompletionBlock:(void (^)(NSError * _Nullable))block +- (void)unarchiveWithCompletionBlock:(void (^)(NSError * _Nullable))block progressBlock:(void (^ _Nullable)(double progress))progress { - [super unarchiveWithCompletionBlock:block]; + [super unarchiveWithCompletionBlock:block progressBlock:progress]; [NSThread detachNewThreadSelector:[[self class] selectorConformingToTypeOfPath:self.archivePath] toTarget:self withObject:nil]; } @@ -94,7 +94,7 @@ bytesRead += len; [archiveOutput writeData:data]; dispatch_async(dispatch_get_main_queue(), ^{ - [self notifyDelegateOfProgress:(double)bytesRead / (double)expectedLength]; + [self notifyProgress:(double)bytesRead / (double)expectedLength]; }); } while(bytesRead < expectedLength); diff --git a/Sparkle/SUUIBasedUpdateDriver.h b/Sparkle/SUUIBasedUpdateDriver.h index 8148912b..a511aae9 100644 --- a/Sparkle/SUUIBasedUpdateDriver.h +++ b/Sparkle/SUUIBasedUpdateDriver.h @@ -15,7 +15,7 @@ @class SUStatusController; -@interface SUUIBasedUpdateDriver : SUBasicUpdateDriver +@interface SUUIBasedUpdateDriver : SUBasicUpdateDriver - (void)showAlert:(NSAlert *)alert; - (IBAction)cancelDownload:(id)sender; diff --git a/Sparkle/SUUnarchiver.h b/Sparkle/SUUnarchiver.h index 486a3604..6e38a728 100644 --- a/Sparkle/SUUnarchiver.h +++ b/Sparkle/SUUnarchiver.h @@ -14,27 +14,20 @@ NS_ASSUME_NONNULL_BEGIN @class SUHost; -@protocol SUUnarchiverDelegate; @interface SUUnarchiver : NSObject @property (copy, readonly) NSString *archivePath; @property (copy, readonly) NSString *_Nullable updateHostBundlePath; @property (copy, readonly) NSString *_Nullable decryptionPassword; -@property (weak) _Nullable id delegate; + (nullable SUUnarchiver *)unarchiverForPath:(NSString *)path updatingHostBundlePath:(nullable NSString *)host withPassword:(nullable NSString *)decryptionPassword; + (BOOL)unsafeIfArchiveIsNotValidated; -- (void)unarchiveWithCompletionBlock:(void (^_Nonnull)(NSError *_Nullable))block; +- (void)unarchiveWithCompletionBlock:(void (^)(NSError *_Nullable))completion progressBlock:(void (^_Nullable)(double progress))progress; @end -@protocol SUUnarchiverDelegate -@optional -- (void)unarchiver:(SUUnarchiver *)unarchiver extractedProgress:(double)progress; -@end - NS_ASSUME_NONNULL_END #endif diff --git a/Sparkle/SUUnarchiver.m b/Sparkle/SUUnarchiver.m index d719a8bd..1f146c3f 100644 --- a/Sparkle/SUUnarchiver.m +++ b/Sparkle/SUUnarchiver.m @@ -17,15 +17,16 @@ @interface SUUnarchiver () @property (strong) void (^completionBlock)(NSError * _Nullable); +@property (strong) void (^progressBlock)(double progress); + @end @implementation SUUnarchiver @synthesize archivePath; @synthesize updateHostBundlePath; -@synthesize delegate; @synthesize decryptionPassword; -@synthesize completionBlock; +@synthesize completionBlock, progressBlock; + (SUUnarchiver *)unarchiverForPath:(NSString *)path updatingHostBundlePath:(NSString *)hostPath withPassword:(NSString *)decryptionPassword { @@ -39,8 +40,9 @@ - (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], self.archivePath]; } -- (void)unarchiveWithCompletionBlock:(void (^_Nonnull)(NSError * _Nullable))block { +- (void)unarchiveWithCompletionBlock:(void (^_Nonnull)(NSError * _Nullable))block progressBlock:(void (^_Nullable)(double progress))progress { self.completionBlock = block; + self.progressBlock = progress; } - (instancetype)initWithPath:(NSString *)path hostBundlePath:(NSString *)hostPath password:(NSString *)password @@ -64,10 +66,10 @@ return NO; } -- (void)notifyDelegateOfProgress:(double)progress +- (void)notifyProgress:(double)progress { - if ([self.delegate respondsToSelector:@selector(unarchiver:extractedProgress:)]) { - [self.delegate unarchiver:self extractedProgress:progress]; + if (self.progressBlock) { + self.progressBlock(progress); } } diff --git a/Sparkle/SUUnarchiver_Private.h b/Sparkle/SUUnarchiver_Private.h index c7718e9f..b48792b9 100644 --- a/Sparkle/SUUnarchiver_Private.h +++ b/Sparkle/SUUnarchiver_Private.h @@ -18,7 +18,7 @@ + (BOOL)canUnarchivePath:(NSString *)path; - (instancetype)initWithPath:(NSString *)archive hostBundlePath:(NSString *)host; -- (void)notifyDelegateOfProgress:(double)progress; +- (void)notifyProgress:(double)progress; - (void)unarchiverDidFinish; - (void)unarchiverDidFailWithError:(NSError *)err; @end diff --git a/Tests/SUUnarchiverTest.swift b/Tests/SUUnarchiverTest.swift index c2261077..3e1d55ad 100644 --- a/Tests/SUUnarchiverTest.swift +++ b/Tests/SUUnarchiverTest.swift @@ -8,16 +8,12 @@ import XCTest -class SUUnarchiverTest: XCTestCase, SUUnarchiverDelegate +class SUUnarchiverTest: XCTestCase { var password: String? = nil var unarchivedExpectation: XCTestExpectation? = nil var unarchivedResult: Bool = false - func unarchiver(_ unarchiver: SUUnarchiver, extractedProgress progress: Double) - { - } - func unarchiveTestAppWithExtension(_ archiveExtension: String) { let appName = "SparkleTestCodeSignApp" @@ -39,11 +35,10 @@ class SUUnarchiverTest: XCTestCase, SUUnarchiverDelegate let unarchiver = SUUnarchiver(forPath: tempArchiveURL.path, updatingHostBundlePath: nil, withPassword: self.password)! - unarchiver.delegate = self - unarchiver.unarchive {(error: Error?) -> Void in + unarchiver.unarchive(completionBlock: {(error: Error?) -> Void in self.unarchivedResult = nil == error; self.unarchivedExpectation!.fulfill() - } + }, progressBlock:{(progress: Double) -> Void in }); super.waitForExpectations(timeout: 7.0, handler: nil) From e3fb6bb1a83cd5baf3b16e584c6272b9b2a924d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kornel=20Lesin=CC=81ski?= Date: Wed, 21 Dec 2016 00:49:12 +0100 Subject: [PATCH 10/27] Report DMG extraction progress --- Sparkle/SUDiskImageUnarchiver.m | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Sparkle/SUDiskImageUnarchiver.m b/Sparkle/SUDiskImageUnarchiver.m index ae1987ef..c98725e9 100644 --- a/Sparkle/SUDiskImageUnarchiver.m +++ b/Sparkle/SUDiskImageUnarchiver.m @@ -90,6 +90,8 @@ [task launch]; + [self notifyProgress:0.125]; + [inputPipe.fileHandleForWriting writeData:promptData]; [inputPipe.fileHandleForWriting closeFile]; @@ -104,6 +106,8 @@ goto reportError; } + [self notifyProgress:0.5]; + if (taskResult != 0) { NSString *resultStr = output ? [[NSString alloc] initWithData:output encoding:NSUTF8StringEncoding] : nil; @@ -121,6 +125,9 @@ goto reportError; } + double itemsCopied = 0; + double totalItems = [contents count]; + for (NSString *item in contents) { NSString *fromPath = [mountPoint stringByAppendingPathComponent:item]; @@ -131,6 +138,8 @@ continue; } + itemsCopied += 1.0; + [self notifyProgress:0.5 + itemsCopied/(totalItems*2.0)]; SULog(@"copyItemAtPath:%@ toPath:%@", fromPath, toPath); if (![manager copyItemAtPath:fromPath toPath:toPath error:&error]) From 59d90e0bb1ce7ead7494ff3d99ddb9f74d395538 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kornel=20Lesin=CC=81ski?= Date: Wed, 21 Dec 2016 00:56:39 +0100 Subject: [PATCH 11/27] Basic binary delta progress --- Sparkle/SUBinaryDeltaApply.h | 2 +- Sparkle/SUBinaryDeltaApply.m | 17 ++++++++++++++++- Sparkle/SUBinaryDeltaUnarchiver.m | 4 +++- Tests/SUBinaryDeltaTest.m | 2 +- 4 files changed, 21 insertions(+), 4 deletions(-) diff --git a/Sparkle/SUBinaryDeltaApply.h b/Sparkle/SUBinaryDeltaApply.h index 8390d9c0..4932cd9d 100644 --- a/Sparkle/SUBinaryDeltaApply.h +++ b/Sparkle/SUBinaryDeltaApply.h @@ -10,6 +10,6 @@ #define SUBINARYDELTAAPPLY_H @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/Sparkle/SUBinaryDeltaApply.m b/Sparkle/SUBinaryDeltaApply.m index 63abdb4f..eac297b4 100644 --- a/Sparkle/SUBinaryDeltaApply.m +++ b/Sparkle/SUBinaryDeltaApply.m @@ -25,7 +25,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) { @@ -44,6 +44,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)) { @@ -112,6 +114,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) { @@ -137,6 +141,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"); @@ -146,6 +152,9 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi } return NO; } + + progressCallback(3/6.0); + if (!copyTree(source, destination)) { if (verbose) { fprintf(stderr, "\n"); @@ -156,6 +165,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) { @@ -252,6 +263,8 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi } xar_close(x); + progressCallback(5/6.0); + if (verbose) { fprintf(stderr, "\nVerifying destination..."); } @@ -277,6 +290,8 @@ BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFi return NO; } + progressCallback(6/6.0); + if (verbose) { fprintf(stderr, "\nDone!\n"); } diff --git a/Sparkle/SUBinaryDeltaUnarchiver.m b/Sparkle/SUBinaryDeltaUnarchiver.m index 415c9033..bd9bdcc1 100644 --- a/Sparkle/SUBinaryDeltaUnarchiver.m +++ b/Sparkle/SUBinaryDeltaUnarchiver.m @@ -68,7 +68,9 @@ NSString *targetPath = [[self.archivePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:[sourcePath lastPathComponent]]; NSError *applyDiffError = nil; - BOOL success = applyBinaryDelta(sourcePath, targetPath, self.archivePath, NO, &applyDiffError); + BOOL success = applyBinaryDelta(sourcePath, targetPath, self.archivePath, NO, ^(double progress){ + [self notifyProgress:progress]; + }, &applyDiffError); if (success) { [[self class] updateSpotlightImportersAtBundlePath:targetPath]; [self unarchiverDidFinish]; diff --git a/Tests/SUBinaryDeltaTest.m b/Tests/SUBinaryDeltaTest.m index 550f55e3..210363c6 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); From 921aed0fae5edf477adeb38ad60bbde3248b1a72 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kornel=20Lesin=CC=81ski?= Date: Tue, 20 Dec 2016 20:32:50 +0100 Subject: [PATCH 12/27] Temp vars --- Sparkle/SUBinaryDeltaTool.m | 10 +++++++--- Sparkle/SUPlainInstaller.m | 8 ++++++-- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/Sparkle/SUBinaryDeltaTool.m b/Sparkle/SUBinaryDeltaTool.m index 01f07dcf..ac3cdfc0 100644 --- a/Sparkle/SUBinaryDeltaTool.m +++ b/Sparkle/SUBinaryDeltaTool.m @@ -96,21 +96,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; } diff --git a/Sparkle/SUPlainInstaller.m b/Sparkle/SUPlainInstaller.m index d11e3bb8..1f858604 100644 --- a/Sparkle/SUPlainInstaller.m +++ b/Sparkle/SUPlainInstaller.m @@ -45,7 +45,8 @@ SUFileManager *fileManager = [SUFileManager fileManagerWithAuthorizationToolPath:fileOperationToolPath]; // Create a temporary directory for our new app that resides on our destination's volume - NSURL *tempNewDirectoryURL = [fileManager makeTemporaryDirectoryWithPreferredName:[installationURL.lastPathComponent.stringByDeletingPathExtension stringByAppendingString:@" (Incomplete Update)"] appropriateForDirectoryURL:installationURL.URLByDeletingLastPathComponent error:error]; + NSString *preferredName = [installationURL.lastPathComponent.stringByDeletingPathExtension stringByAppendingString:@" (Incomplete Update)"]; + NSURL *tempNewDirectoryURL = [fileManager makeTemporaryDirectoryWithPreferredName:preferredName appropriateForDirectoryURL:installationURL.URLByDeletingLastPathComponent error:error]; if (tempNewDirectoryURL == nil) { SULog(@"Failed to make new temp directory"); return NO; @@ -163,7 +164,10 @@ // Prevent malicious downgrades if (!allowDowngrades) { - if ([comparator compareVersion:[host version] toVersion:[[NSBundle bundleWithPath:path] objectForInfoDictionaryKey:(__bridge NSString *)kCFBundleVersionKey]] == NSOrderedDescending) { + NSString *hostVersion = [host version]; + NSBundle *bundle = [NSBundle bundleWithPath:path]; + NSString *updateVersion = [bundle objectForInfoDictionaryKey:(__bridge NSString *)kCFBundleVersionKey]; + if (!updateVersion || [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.", [host version], [[NSBundle bundleWithPath:path] objectForInfoDictionaryKey:(__bridge NSString *)kCFBundleVersionKey]]; NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUDowngradeError userInfo:@{ NSLocalizedDescriptionKey: errorMessage }]; [self finishInstallationToPath:installationPath withResult:NO error:error completionHandler:completionHandler]; From c1392bc1906cb653f88d6dbfec4d4dea81b04df5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kornel=20Lesin=CC=81ski?= Date: Tue, 20 Dec 2016 22:45:39 +0100 Subject: [PATCH 13/27] Nullability --- Sparkle/SUAppcast.h | 12 +++++--- Sparkle/SUFileManager.h | 34 ++++++++++++---------- Sparkle/SUStandardVersionComparator.h | 3 ++ Sparkle/SUSystemProfiler.h | 3 ++ Sparkle/SUVersionComparisonProtocol.h | 3 ++ Sparkle/SUVersionDisplayProtocol.h | 2 +- Tests/Sparkle Unit Tests-Bridging-Header.h | 11 ++++--- 7 files changed, 44 insertions(+), 24 deletions(-) diff --git a/Sparkle/SUAppcast.h b/Sparkle/SUAppcast.h index fee97567..08bd9af0 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) NSString *_Nullable userAgentString; +@property (copy) NSDictionary *_Nullable 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) NSArray *_Nullable items; @end +NS_ASSUME_NONNULL_END + #endif diff --git a/Sparkle/SUFileManager.h b/Sparkle/SUFileManager.h index 6aa0f9af..8cd41bed 100644 --- a/Sparkle/SUFileManager.h +++ b/Sparkle/SUFileManager.h @@ -8,6 +8,8 @@ #import +NS_ASSUME_NONNULL_BEGIN + /** * A class used for performing file operations that may also perform authorization if allowed and if permission is denied when trying to * perform them normally as the running user. All operations on this class may be used on thread other than the main thread. @@ -19,7 +21,7 @@ * Creates a file manager that will not authorize for file operations * @return A new file manager instance */ -+ (instancetype)defaultManager; ++ (nullable instancetype)defaultManager; /** * Creates a file manager that allows authorizing for file operations @@ -29,7 +31,7 @@ * * This method just creates the file manager. It doesn't acquire authorization immediately or if it doesn't need to. */ -+ (instancetype)fileManagerWithAuthorizationToolPath:(NSString *)authorizationToolPath; ++ (nullable instancetype)fileManagerWithAuthorizationToolPath:(NSString *)authorizationToolPath; /** * Returns a file manager that allows or disallows authorizing for file operations based on the current file manager @@ -38,7 +40,7 @@ * * This may return a newly created file manager or re-use the existing file manager depending on the current authorization rights. */ -- (instancetype)fileManagerByPreservingAuthorizationRights; +- (nullable instancetype)fileManagerByPreservingAuthorizationRights; /** * Creates a temporary directory on the same volume as a provided URL @@ -50,7 +52,7 @@ * When moving an item from a source to a destination, it is desirable to create a temporary intermediate destination on the same volume as the destination to ensure * that the item will be moved, and not copied, from the intermediate point to the final destination. This ensures file atomicity. */ -- (NSURL *)makeTemporaryDirectoryWithPreferredName:(NSString *)preferredName appropriateForDirectoryURL:(NSURL *)appropriateURL error:(NSError **)error; +- (nullable NSURL *)makeTemporaryDirectoryWithPreferredName:(NSString *)preferredName appropriateForDirectoryURL:(nullable NSURL *)appropriateURL error:(NSError *_Nullable*_Nullable)error; /** * Creates a directory at the target URL @@ -60,7 +62,7 @@ * * This is an atomic operation. */ -- (BOOL)makeDirectoryAtURL:(NSURL *)targetURL error:(NSError **)error; +- (BOOL)makeDirectoryAtURL:(NSURL *)targetURL error:(NSError *_Nullable*_Nullable)error; /** * Moves an item from a source to a destination @@ -68,11 +70,11 @@ * @param destinationURL A URL pointing to the destination the item will be moved at. An item must not already exist at this URL. * @param error If an error occurs, upon returns contains an NSError object that describes the problem. If you are not interested in possible errors, you may pass in NULL. * @return YES if the item was moved successfully, otherwise NO along with a populated error object - * + * * If sourceURL and destinationURL reside on the same volume, this operation will be an atomic move operation. * Otherwise this will be equivalent to a copy & remove which will be a nonatomic operation. */ -- (BOOL)moveItemAtURL:(NSURL *)sourceURL toURL:(NSURL *)destinationURL error:(NSError **)error; +- (BOOL)moveItemAtURL:(NSURL *)sourceURL toURL:(NSURL *)destinationURL error:(NSError *_Nullable*_Nullable)error; /** * Copies an item from a source to a destination @@ -83,7 +85,7 @@ * * This is not an atomic operation. */ -- (BOOL)copyItemAtURL:(NSURL *)sourceURL toURL:(NSURL *)destinationURL error:(NSError **)error; +- (BOOL)copyItemAtURL:(NSURL *)sourceURL toURL:(NSURL *)destinationURL error:(NSError *_Nullable*_Nullable)error; /** * Moves an item at a specified URL to the running user's trash directory @@ -95,10 +97,10 @@ * This method has to locate the trash directory and uses an intermediate temporary directory before trashing the item. * A copy may have to be done if the url is not on the same volume as the running user's trash directory. * If a failure occurs in the middle of this operation, the item to remove may be lost forever or stuck in a temporary location. - * + * * This is not an atomic operation, nor intended to be a recoverable operation if the worst comes to worst. */ -- (BOOL)moveItemAtURLToTrash:(NSURL *)url error:(NSError **)error; +- (BOOL)moveItemAtURLToTrash:(NSURL *)url error:(NSError *_Nullable*_Nullable)error; /** * Removes an item at a URL @@ -108,7 +110,7 @@ * * This is not an atomic operation. */ -- (BOOL)removeItemAtURL:(NSURL *)url error:(NSError **)error; +- (BOOL)removeItemAtURL:(NSURL *)url error:(NSError *_Nullable*_Nullable)error; /** * Changes the owner and group IDs of an item at a specified target URL to match another URL @@ -123,7 +125,7 @@ * * This is not an atomic operation. */ -- (BOOL)changeOwnerAndGroupOfItemAtRootURL:(NSURL *)targetURL toMatchURL:(NSURL *)matchURL error:(NSError **)error; +- (BOOL)changeOwnerAndGroupOfItemAtRootURL:(NSURL *)targetURL toMatchURL:(NSURL *)matchURL error:(NSError *_Nullable*_Nullable)error; /** * Updates the modification and access time of an item at a specified target URL to the current time @@ -136,7 +138,7 @@ * * This is not an atomic operation. */ -- (BOOL)updateModificationAndAccessTimeOfItemAtURL:(NSURL *)targetURL error:(NSError **)error; +- (BOOL)updateModificationAndAccessTimeOfItemAtURL:(NSURL *)targetURL error:(NSError *_Nullable*_Nullable)error; /** * Releases Apple's quarantine extended attribute from the item at the specified root URL @@ -154,7 +156,7 @@ * * This is not an atomic operation. */ -- (BOOL)releaseItemFromQuarantineAtRootURL:(NSURL *)rootURL error:(NSError **)error; +- (BOOL)releaseItemFromQuarantineAtRootURL:(NSURL *)rootURL error:(NSError *_Nullable*_Nullable)error; /** * Runs an installer package (pkg) in a headless mode using /usr/sbin/installer @@ -166,6 +168,8 @@ * an initial authorization prompt if the calling process does not have root privileges. In other words, root privileges are required to use this method, and the file manager instance must have been created by allowing authorization. * An error can occur if the package is unable to be ran by the installer, or if the installer reports a non-zero exit status code. */ -- (BOOL)executePackageAtURL:(NSURL *)packageURL error:(NSError **)error; +- (BOOL)executePackageAtURL:(NSURL *)packageURL error:(NSError *_Nullable*_Nullable)error; + +NS_ASSUME_NONNULL_END @end diff --git a/Sparkle/SUStandardVersionComparator.h b/Sparkle/SUStandardVersionComparator.h index 2eaee42f..8badada5 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. @@ -39,4 +41,5 @@ SU_EXPORT @interface SUStandardVersionComparator : NSObject +NS_ASSUME_NONNULL_BEGIN + @class SUHost; @interface SUSystemProfiler : NSObject + (SUSystemProfiler *)sharedSystemProfiler; - (NSMutableArray *)systemProfileArrayForHost:(SUHost *)host; @end +NS_ASSUME_NONNULL_END #endif diff --git a/Sparkle/SUVersionComparisonProtocol.h b/Sparkle/SUVersionComparisonProtocol.h index c099ad57..7cac76e6 100644 --- a/Sparkle/SUVersionComparisonProtocol.h +++ b/Sparkle/SUVersionComparisonProtocol.h @@ -16,6 +16,8 @@ #endif #import "SUExport.h" +NS_ASSUME_NONNULL_BEGIN + /*! Provides version comparison facilities for Sparkle. */ @@ -31,4 +33,5 @@ @end +NS_ASSUME_NONNULL_END #endif diff --git a/Sparkle/SUVersionDisplayProtocol.h b/Sparkle/SUVersionDisplayProtocol.h index 16e444ff..cda2531f 100644 --- a/Sparkle/SUVersionDisplayProtocol.h +++ b/Sparkle/SUVersionDisplayProtocol.h @@ -24,6 +24,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/Tests/Sparkle Unit Tests-Bridging-Header.h b/Tests/Sparkle Unit Tests-Bridging-Header.h index c38a9f78..043587ed 100644 --- a/Tests/Sparkle Unit Tests-Bridging-Header.h +++ b/Tests/Sparkle Unit Tests-Bridging-Header.h @@ -13,31 +13,34 @@ #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 SUBasicUpdateDriver (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 *)parseAppcastItemsFromXMLFile:(NSURL *)appcastFile error:(NSError *__autoreleasing*)errorp; +- (nullable NSArray *)parseAppcastItemsFromXMLFile:(NSURL *)appcastFile error:(NSError *_Nullable __autoreleasing *_Nullable)errorp; @end @interface SUBinaryDeltaUnarchiver (Private) + (void)updateSpotlightImportersAtBundlePath:(NSString *)targetPath; +NS_ASSUME_NONNULL_END @end From 464972126c1516ad272e163505e5ccbfb53ca3be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kornel=20Lesin=CC=81ski?= Date: Wed, 21 Dec 2016 16:42:34 +0100 Subject: [PATCH 14/27] Unwrap early --- Tests/SUFileManagerTest.swift | 28 +++++++++--------- Tests/SUSpotlightImporterTest.swift | 46 ++++++++++++++--------------- 2 files changed, 37 insertions(+), 37 deletions(-) diff --git a/Tests/SUFileManagerTest.swift b/Tests/SUFileManagerTest.swift index fe5cd6d7..ad3fa7e0 100644 --- a/Tests/SUFileManagerTest.swift +++ b/Tests/SUFileManagerTest.swift @@ -12,30 +12,30 @@ class SUFileManagerTest: XCTestCase { func makeTempFiles(_ testBlock: (SUFileManager, URL, URL, URL, URL, URL, URL) -> Void) { - let fileManager = SUFileManager.default() + let fileManager = SUFileManager.default()! - let tempDirectoryURL = try! fileManager?.makeTemporaryDirectory(withPreferredName: "Sparkle Unit Test Data", appropriateForDirectoryURL: URL(fileURLWithPath: NSHomeDirectory())) + let tempDirectoryURL = (try! fileManager.makeTemporaryDirectory(withPreferredName: "Sparkle Unit Test Data", appropriateForDirectoryURL: URL(fileURLWithPath: NSHomeDirectory()))) defer { - try! fileManager?.removeItem(at: tempDirectoryURL) + try! fileManager.removeItem(at: tempDirectoryURL) } - let ordinaryFileURL = tempDirectoryURL?.appendingPathComponent("a file written by sparkles unit tests") - try! "foo".data(using: String.Encoding.utf8)!.write(to: ordinaryFileURL!, options: .atomic) + let ordinaryFileURL = tempDirectoryURL.appendingPathComponent("a file written by sparkles unit tests") + try! "foo".data(using: String.Encoding.utf8)!.write(to: ordinaryFileURL, options: .atomic) - let directoryURL = tempDirectoryURL?.appendingPathComponent("a directory written by sparkles unit tests") - try! FileManager.default.createDirectory(at: directoryURL!, withIntermediateDirectories: false, attributes: nil) + let directoryURL = tempDirectoryURL.appendingPathComponent("a directory written by sparkles unit tests") + try! FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: false, attributes: nil) - let fileInDirectoryURL = directoryURL?.appendingPathComponent("a file inside a directory written by sparkles unit tests") - try! "bar baz".data(using: String.Encoding.utf8)!.write(to: fileInDirectoryURL!, options: .atomic) + let fileInDirectoryURL = directoryURL.appendingPathComponent("a file inside a directory written by sparkles unit tests") + try! "bar baz".data(using: String.Encoding.utf8)!.write(to: fileInDirectoryURL, options: .atomic) - let validSymlinkURL = tempDirectoryURL?.appendingPathComponent("symlink test") - try! FileManager.default.createSymbolicLink(at: validSymlinkURL!, withDestinationURL: directoryURL!) + let validSymlinkURL = tempDirectoryURL.appendingPathComponent("symlink test") + try! FileManager.default.createSymbolicLink(at: validSymlinkURL, withDestinationURL: directoryURL) - let invalidSymlinkURL = tempDirectoryURL?.appendingPathComponent("symlink test 2") - try! FileManager.default.createSymbolicLink(at: invalidSymlinkURL!, withDestinationURL: (tempDirectoryURL?.appendingPathComponent("does not exist"))!) + let invalidSymlinkURL = tempDirectoryURL.appendingPathComponent("symlink test 2") + try! FileManager.default.createSymbolicLink(at: invalidSymlinkURL, withDestinationURL: (tempDirectoryURL.appendingPathComponent("does not exist"))) - testBlock(fileManager!, tempDirectoryURL!, ordinaryFileURL!, directoryURL!, fileInDirectoryURL!, validSymlinkURL!, invalidSymlinkURL!) + testBlock(fileManager, tempDirectoryURL, ordinaryFileURL, directoryURL, fileInDirectoryURL, validSymlinkURL, invalidSymlinkURL) } func testMoveFiles() diff --git a/Tests/SUSpotlightImporterTest.swift b/Tests/SUSpotlightImporterTest.swift index 3c086e0a..8d48ade5 100644 --- a/Tests/SUSpotlightImporterTest.swift +++ b/Tests/SUSpotlightImporterTest.swift @@ -12,49 +12,49 @@ class SUSpotlightImporterTest: XCTestCase { func testUpdatingSpotlightBundles() { - let fileManager = SUFileManager.default() - let tempDirectoryURL = try! fileManager?.makeTemporaryDirectory(withPreferredName: "Sparkle Unit Test Data", appropriateForDirectoryURL: URL(fileURLWithPath: NSHomeDirectory())) + let fileManager = SUFileManager.default()! + let tempDirectoryURL = try! fileManager.makeTemporaryDirectory(withPreferredName: "Sparkle Unit Test Data", appropriateForDirectoryURL: URL(fileURLWithPath: NSHomeDirectory())) - let bundleDirectory = tempDirectoryURL?.appendingPathComponent("bundle.app") - try! fileManager?.makeDirectory(at: bundleDirectory) + let bundleDirectory = tempDirectoryURL.appendingPathComponent("bundle.app") + try! fileManager.makeDirectory(at: bundleDirectory) - let innerDirectory = bundleDirectory?.appendingPathComponent("foo") - try! fileManager?.makeDirectory(at: innerDirectory) - try! Data().write(to: (bundleDirectory?.appendingPathComponent("bar"))!, options: .atomicWrite) + let innerDirectory = bundleDirectory.appendingPathComponent("foo") + try! fileManager.makeDirectory(at: innerDirectory) + try! Data().write(to: (bundleDirectory.appendingPathComponent("bar")), options: .atomicWrite) - let importerDirectory = innerDirectory?.appendingPathComponent("baz.mdimporter") + let importerDirectory = innerDirectory.appendingPathComponent("baz.mdimporter") - try! fileManager?.makeDirectory(at: importerDirectory) - try! fileManager?.makeDirectory(at: innerDirectory?.appendingPathComponent("flag")) + try! fileManager.makeDirectory(at: importerDirectory) + try! fileManager.makeDirectory(at: innerDirectory.appendingPathComponent("flag")) - try! Data().write(to: (importerDirectory?.appendingPathComponent("file"))!, options: .atomicWrite) + try! Data().write(to: (importerDirectory.appendingPathComponent("file")), options: .atomicWrite) - let oldFooDirectoryAttributes = try! FileManager.default.attributesOfItem(atPath: innerDirectory!.path) - let oldBarFileAttributes = try! FileManager.default.attributesOfItem(atPath: bundleDirectory!.appendingPathComponent("bar").path) - let oldImporterAttributes = try! FileManager.default.attributesOfItem(atPath: importerDirectory!.path) - let oldFlagAttributes = try! FileManager.default.attributesOfItem(atPath: innerDirectory!.appendingPathComponent("flag").path) - let oldFileInImporterAttributes = try! FileManager.default.attributesOfItem(atPath: importerDirectory!.appendingPathComponent("file").path) + let oldFooDirectoryAttributes = try! FileManager.default.attributesOfItem(atPath: innerDirectory.path) + let oldBarFileAttributes = try! FileManager.default.attributesOfItem(atPath: bundleDirectory.appendingPathComponent("bar").path) + let oldImporterAttributes = try! FileManager.default.attributesOfItem(atPath: importerDirectory.path) + let oldFlagAttributes = try! FileManager.default.attributesOfItem(atPath: innerDirectory.appendingPathComponent("flag").path) + let oldFileInImporterAttributes = try! FileManager.default.attributesOfItem(atPath: importerDirectory.appendingPathComponent("file").path) sleep(1) // wait for clock to advance // Update spotlight bundles - SUBinaryDeltaUnarchiver.updateSpotlightImporters(atBundlePath: bundleDirectory!.path) + SUBinaryDeltaUnarchiver.updateSpotlightImporters(atBundlePath: bundleDirectory.path) - let newFooDirectoryAttributes = try! FileManager.default.attributesOfItem(atPath: innerDirectory!.path) + let newFooDirectoryAttributes = try! FileManager.default.attributesOfItem(atPath: innerDirectory.path) XCTAssertEqual((newFooDirectoryAttributes[FileAttributeKey.modificationDate] as! Date).timeIntervalSince(oldFooDirectoryAttributes[FileAttributeKey.modificationDate] as! Date), 0) - let newBarFileAttributes = try! FileManager.default.attributesOfItem(atPath: bundleDirectory!.appendingPathComponent("bar").path) + let newBarFileAttributes = try! FileManager.default.attributesOfItem(atPath: bundleDirectory.appendingPathComponent("bar").path) XCTAssertEqual((newBarFileAttributes[FileAttributeKey.modificationDate] as! Date).timeIntervalSince(oldBarFileAttributes[FileAttributeKey.modificationDate] as! Date), 0) - let newImporterAttributes = try! FileManager.default.attributesOfItem(atPath: importerDirectory!.path) + let newImporterAttributes = try! FileManager.default.attributesOfItem(atPath: importerDirectory.path) XCTAssertGreaterThan((newImporterAttributes[FileAttributeKey.modificationDate] as! Date).timeIntervalSince(oldImporterAttributes[FileAttributeKey.modificationDate] as! Date), 0) - let newFlagAttributes = try! FileManager.default.attributesOfItem(atPath: innerDirectory!.appendingPathComponent("flag").path) + let newFlagAttributes = try! FileManager.default.attributesOfItem(atPath: innerDirectory.appendingPathComponent("flag").path) XCTAssertEqual((newFlagAttributes[FileAttributeKey.modificationDate] as! Date).timeIntervalSince(oldFlagAttributes[FileAttributeKey.modificationDate] as! Date), 0) - let newFileInImporterAttributes = try! FileManager.default.attributesOfItem(atPath: importerDirectory!.appendingPathComponent("file").path) + let newFileInImporterAttributes = try! FileManager.default.attributesOfItem(atPath: importerDirectory.appendingPathComponent("file").path) XCTAssertEqual((newFileInImporterAttributes[FileAttributeKey.modificationDate] as! Date).timeIntervalSince(oldFileInImporterAttributes[FileAttributeKey.modificationDate] as! Date), 0) - try! fileManager?.removeItem(at: tempDirectoryURL) + try! fileManager.removeItem(at: tempDirectoryURL) } } From 60d4f0574399c7343daf2493bb38c6fb2ae8ed9d Mon Sep 17 00:00:00 2001 From: Zorg Date: Wed, 21 Dec 2016 11:07:03 -0500 Subject: [PATCH 15/27] Add SUUnarchiverProtocol & remove runtime registration of unarchivers --- Sparkle.xcodeproj/project.pbxproj | 8 +- Sparkle/SUAutomaticUpdateDriver.h | 1 + Sparkle/SUAutomaticUpdateDriver.m | 2 +- Sparkle/SUBasicUpdateDriver.h | 5 +- Sparkle/SUBasicUpdateDriver.m | 9 +- Sparkle/SUBinaryDeltaUnarchiver.h | 12 ++- Sparkle/SUBinaryDeltaUnarchiver.m | 72 ++++++++------ Sparkle/SUDiskImageUnarchiver.h | 12 ++- Sparkle/SUDiskImageUnarchiver.m | 133 +++++++++++++------------- Sparkle/SUPipedUnarchiver.h | 12 ++- Sparkle/SUPipedUnarchiver.m | 151 +++++++++++++++--------------- Sparkle/SUUIBasedUpdateDriver.h | 1 + Sparkle/SUUIBasedUpdateDriver.m | 2 +- Sparkle/SUUnarchiver.h | 27 +----- Sparkle/SUUnarchiver.m | 97 ++++--------------- Sparkle/SUUnarchiverProtocol.h | 36 +++++++ Sparkle/SUUnarchiver_Private.h | 26 ----- Tests/SUUnarchiverTest.swift | 10 +- 18 files changed, 286 insertions(+), 330 deletions(-) create mode 100644 Sparkle/SUUnarchiverProtocol.h delete mode 100644 Sparkle/SUUnarchiver_Private.h diff --git a/Sparkle.xcodeproj/project.pbxproj b/Sparkle.xcodeproj/project.pbxproj index a9e8c6a6..a47dd397 100644 --- a/Sparkle.xcodeproj/project.pbxproj +++ b/Sparkle.xcodeproj/project.pbxproj @@ -104,7 +104,6 @@ 6102FE460E077FCE00F85D09 /* SUPipedUnarchiver.h in Headers */ = {isa = PBXBuildFile; fileRef = 6102FE440E077FCE00F85D09 /* SUPipedUnarchiver.h */; settings = {ATTRIBUTES = (); }; }; 6102FE4A0E07803800F85D09 /* SUDiskImageUnarchiver.h in Headers */ = {isa = PBXBuildFile; fileRef = 6102FE480E07803800F85D09 /* SUDiskImageUnarchiver.h */; settings = {ATTRIBUTES = (); }; }; 6102FE4B0E07803800F85D09 /* SUDiskImageUnarchiver.m in Sources */ = {isa = PBXBuildFile; fileRef = 6102FE490E07803800F85D09 /* SUDiskImageUnarchiver.m */; }; - 6102FE5B0E08C7EC00F85D09 /* SUUnarchiver_Private.h in Headers */ = {isa = PBXBuildFile; fileRef = 6102FE590E08C7EC00F85D09 /* SUUnarchiver_Private.h */; settings = {ATTRIBUTES = (); }; }; 611142E910FB1BE5009810AA /* bspatch.h in Headers */ = {isa = PBXBuildFile; fileRef = 611142E810FB1BE5009810AA /* bspatch.h */; }; 61177A1F0D1112E900749C97 /* IOKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6117796E0D1112E000749C97 /* IOKit.framework */; }; 61180BCA0D64138900B4E0D1 /* SUWindowController.h in Headers */ = {isa = PBXBuildFile; fileRef = 61180BC80D64138900B4E0D1 /* SUWindowController.h */; settings = {ATTRIBUTES = (); }; }; @@ -176,6 +175,7 @@ 721CF1AA1AD7647000D9AC09 /* libxar.1.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 5D1AF5890FD7678C0065DB48 /* libxar.1.dylib */; }; 721CF1AB1AD764EB00D9AC09 /* libbz2.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 5D06E8FB0FD68D61005AE3F6 /* libbz2.dylib */; }; 7223E7631AD1AEFF008E3161 /* sais.c in Sources */ = {isa = PBXBuildFile; fileRef = 7223E7611AD1AEFF008E3161 /* sais.c */; }; + 722589D71E0AD86B005EA0B9 /* SUUnarchiverProtocol.h in Headers */ = {isa = PBXBuildFile; fileRef = 722589D61E0AD86B005EA0B9 /* SUUnarchiverProtocol.h */; }; 722954B71D04ADAF00ECF9CA /* fileop.m in Sources */ = {isa = PBXBuildFile; fileRef = 722954B61D04ADAF00ECF9CA /* fileop.m */; }; 722954BC1D04AE1100ECF9CA /* SUFileManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 7275F9C01B5F1F2900B1D19E /* SUFileManager.m */; }; 722954BD1D04AE3800ECF9CA /* SUConstants.m in Sources */ = {isa = PBXBuildFile; fileRef = 61299A5F09CA6EB100B7442F /* SUConstants.m */; }; @@ -569,7 +569,6 @@ 6102FE440E077FCE00F85D09 /* SUPipedUnarchiver.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SUPipedUnarchiver.h; sourceTree = ""; }; 6102FE480E07803800F85D09 /* SUDiskImageUnarchiver.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SUDiskImageUnarchiver.h; sourceTree = ""; }; 6102FE490E07803800F85D09 /* SUDiskImageUnarchiver.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SUDiskImageUnarchiver.m; sourceTree = ""; }; - 6102FE590E08C7EC00F85D09 /* SUUnarchiver_Private.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SUUnarchiver_Private.h; sourceTree = ""; }; 611142E810FB1BE5009810AA /* bspatch.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = bspatch.h; sourceTree = ""; }; 61131A050F846CE600E97AF6 /* da */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.strings; name = da; path = da.lproj/Sparkle.strings; sourceTree = ""; }; 61131A090F846D0A00E97AF6 /* zh_CN */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.strings; name = zh_CN; path = zh_CN.lproj/Sparkle.strings; sourceTree = ""; }; @@ -675,6 +674,7 @@ 7210C7671B9A9A1500EB90AC /* SUUnarchiverTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SUUnarchiverTest.swift; sourceTree = ""; }; 7223E7611AD1AEFF008E3161 /* sais.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = sais.c; sourceTree = ""; }; 7223E7621AD1AEFF008E3161 /* sais.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = sais.h; sourceTree = ""; }; + 722589D61E0AD86B005EA0B9 /* SUUnarchiverProtocol.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SUUnarchiverProtocol.h; sourceTree = ""; }; 722954B41D04ADAF00ECF9CA /* fileop */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = fileop; sourceTree = BUILT_PRODUCTS_DIR; }; 722954B61D04ADAF00ECF9CA /* fileop.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = fileop.m; sourceTree = ""; }; 722954C21D04E66F00ECF9CA /* SUFileOperationConstants.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SUFileOperationConstants.h; sourceTree = ""; }; @@ -1015,9 +1015,9 @@ 6102FE490E07803800F85D09 /* SUDiskImageUnarchiver.m */, 6102FE440E077FCE00F85D09 /* SUPipedUnarchiver.h */, 6129C0B90E0B79810062CE76 /* SUPipedUnarchiver.m */, + 722589D61E0AD86B005EA0B9 /* SUUnarchiverProtocol.h */, 61299A8B09CA790200B7442F /* SUUnarchiver.h */, 61299A8C09CA790200B7442F /* SUUnarchiver.m */, - 6102FE590E08C7EC00F85D09 /* SUUnarchiver_Private.h */, ); name = Unarchiving; sourceTree = ""; @@ -1268,6 +1268,7 @@ 61EF67590E25C5B400F754E0 /* SUHost.h in Headers */, 729924731DF3478A00DBCDF5 /* SUUpdateValidator.h in Headers */, 723B25301CEAB3A600909873 /* bscommon.h in Headers */, + 722589D71E0AD86B005EA0B9 /* SUUnarchiverProtocol.h in Headers */, 618FA5010DAE88B40026945C /* SUInstaller.h in Headers */, 55C14F06136EF6DB00649790 /* SULog.h in Headers */, 726F2CE51BC9C33D001971A4 /* SUOperatingSystem.h in Headers */, @@ -1281,7 +1282,6 @@ 61A2279C0D1CEE7600430CCD /* SUSystemProfiler.h in Headers */, 61B93A3C0DD02D7000DCD2F8 /* SUUIBasedUpdateDriver.h in Headers */, 61299A8D09CA790200B7442F /* SUUnarchiver.h in Headers */, - 6102FE5B0E08C7EC00F85D09 /* SUUnarchiver_Private.h in Headers */, 61B5FCDF09C52A9F00B25A18 /* SUUpdateAlert.h in Headers */, 610134730DD250470049ACDF /* SUUpdateDriver.h in Headers */, 612DCBAF0D488BC60015DBEA /* SUUpdatePermissionPrompt.h in Headers */, diff --git a/Sparkle/SUAutomaticUpdateDriver.h b/Sparkle/SUAutomaticUpdateDriver.h index 4dd90e8f..8893be2d 100644 --- a/Sparkle/SUAutomaticUpdateDriver.h +++ b/Sparkle/SUAutomaticUpdateDriver.h @@ -12,6 +12,7 @@ #import #import "SUBasicUpdateDriver.h" #import "SUAutomaticUpdateAlert.h" +#import "SUUnarchiverProtocol.h" @interface SUAutomaticUpdateDriver : SUBasicUpdateDriver diff --git a/Sparkle/SUAutomaticUpdateDriver.m b/Sparkle/SUAutomaticUpdateDriver.m index 6727d0d9..f6d23b04 100644 --- a/Sparkle/SUAutomaticUpdateDriver.m +++ b/Sparkle/SUAutomaticUpdateDriver.m @@ -62,7 +62,7 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive:) name:NSApplicationDidBecomeActiveNotification object:NSApp]; } -- (void)unarchiverDidFinish:(SUUnarchiver *)__unused ua +- (void)unarchiverDidFinish { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate:) name:NSApplicationWillTerminateNotification object:nil]; [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(systemWillPowerOff:) name:NSWorkspaceWillPowerOffNotification object:nil]; diff --git a/Sparkle/SUBasicUpdateDriver.h b/Sparkle/SUBasicUpdateDriver.h index 301b4bc5..7fac32f8 100644 --- a/Sparkle/SUBasicUpdateDriver.h +++ b/Sparkle/SUBasicUpdateDriver.h @@ -13,6 +13,7 @@ #import "SUUpdateDriver.h" #import "SUUnarchiver.h" #import "SUAppcast.h" +#import "SUUnarchiverProtocol.h" @class SUAppcastItem, SUHost; @interface SUBasicUpdateDriver : SUUpdateDriver @@ -37,8 +38,8 @@ - (void)download:(NSURLDownload *)download didFailWithError:(NSError *)error; - (void)extractUpdate; -- (void)unarchiverDidFinish:(SUUnarchiver *)ua; -- (void)unarchiverDidFail:(SUUnarchiver *)ua; +- (void)unarchiverDidFinish; +- (void)unarchiverDidFail; - (void)failedToApplyDeltaUpdate; - (void)installWithToolAndRelaunch:(BOOL)relaunch; diff --git a/Sparkle/SUBasicUpdateDriver.m b/Sparkle/SUBasicUpdateDriver.m index 0c714d03..73cd75e2 100644 --- a/Sparkle/SUBasicUpdateDriver.m +++ b/Sparkle/SUBasicUpdateDriver.m @@ -316,7 +316,7 @@ - (void)extractUpdate { - SUUnarchiver *unarchiver = [SUUnarchiver unarchiverForPath:self.downloadPath updatingHostBundlePath:self.host.bundlePath withPassword:self.updater.decryptionPassword]; + id unarchiver = [SUUnarchiver unarchiverForPath:self.downloadPath updatingHostBundlePath:self.host.bundlePath decryptionPassword:self.updater.decryptionPassword delegate:self]; BOOL success; if (!unarchiver) { @@ -333,9 +333,8 @@ } if (!success) { - [self unarchiverDidFail:nil]; + [self unarchiverDidFail]; } else { - unarchiver.delegate = self; [unarchiver start]; } } @@ -349,14 +348,14 @@ [self downloadUpdate]; } -- (void)unarchiverDidFinish:(SUUnarchiver *)__unused ua +- (void)unarchiverDidFinish { assert(self.updateItem); [self installWithToolAndRelaunch:YES]; } -- (void)unarchiverDidFail:(SUUnarchiver *)__unused ua +- (void)unarchiverDidFail { // No longer needed self.updateValidator = nil; diff --git a/Sparkle/SUBinaryDeltaUnarchiver.h b/Sparkle/SUBinaryDeltaUnarchiver.h index 1e71cbe4..d7e0b7b6 100644 --- a/Sparkle/SUBinaryDeltaUnarchiver.h +++ b/Sparkle/SUBinaryDeltaUnarchiver.h @@ -9,11 +9,17 @@ #ifndef SUBINARYDELTAUNARCHIVER_H #define SUBINARYDELTAUNARCHIVER_H -#import -#import "SUUnarchiver.h" +#import +#import "SUUnarchiverProtocol.h" -@interface SUBinaryDeltaUnarchiver : SUUnarchiver +NS_ASSUME_NONNULL_BEGIN + +@interface SUBinaryDeltaUnarchiver : NSObject + +- (instancetype)initWithArchivePath:(NSString *)archivePath updateHostBundlePath:(NSString *)updateHostBundlePath delegate:(nullable id )delegate; @end +NS_ASSUME_NONNULL_END + #endif diff --git a/Sparkle/SUBinaryDeltaUnarchiver.m b/Sparkle/SUBinaryDeltaUnarchiver.m index 5ff34bd8..666bff83 100644 --- a/Sparkle/SUBinaryDeltaUnarchiver.m +++ b/Sparkle/SUBinaryDeltaUnarchiver.m @@ -6,16 +6,26 @@ // Copyright 2009 Mark Rowe. All rights reserved. // -#import "SUBinaryDeltaCommon.h" #import "SUBinaryDeltaUnarchiver.h" +#import "SUBinaryDeltaCommon.h" #import "SUBinaryDeltaApply.h" -#import "SUUnarchiver_Private.h" -#import "SUFileManager.h" -#import "SUHost.h" #import "SULog.h" +#import "SUFileManager.h" + +@interface SUBinaryDeltaUnarchiver () + +@property (nonatomic, copy, readonly) NSString *archivePath; +@property (nonatomic, copy, readonly) NSString *updateHostBundlePath; +@property (nonatomic, weak, readonly) id delegate; + +@end @implementation SUBinaryDeltaUnarchiver +@synthesize archivePath = _archivePath; +@synthesize updateHostBundlePath = _updateHostBundlePath; +@synthesize delegate = _delegate; + + (BOOL)canUnarchivePath:(NSString *)path { return [[path pathExtension] isEqualToString:@"delta"]; @@ -61,40 +71,44 @@ } } -- (void)applyBinaryDelta +- (instancetype)initWithArchivePath:(NSString *)archivePath updateHostBundlePath:(NSString *)updateHostBundlePath delegate:(id )delegate { - @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 notifyDelegateOfSuccess]; - }); - } - else { - SULog(@"Applying delta patch failed with error: %@", applyDiffError); - dispatch_async(dispatch_get_main_queue(), ^{ - [self notifyDelegateOfFailure]; - }); - } + self = [super init]; + if (self != nil) { + _archivePath = [archivePath copy]; + _updateHostBundlePath = [updateHostBundlePath copy]; + _delegate = delegate; } + return self; } - (void)start { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ - [self applyBinaryDelta]; + @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]; + }); + } + } }); } -+ (void)load -{ - [self registerImplementation:self]; -} +- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], self.archivePath]; } @end diff --git a/Sparkle/SUDiskImageUnarchiver.h b/Sparkle/SUDiskImageUnarchiver.h index 7a8e9167..d39f68b3 100644 --- a/Sparkle/SUDiskImageUnarchiver.h +++ b/Sparkle/SUDiskImageUnarchiver.h @@ -9,11 +9,17 @@ #ifndef SUDISKIMAGEUNARCHIVER_H #define SUDISKIMAGEUNARCHIVER_H -#import -#import "SUUnarchiver.h" +#import +#import "SUUnarchiverProtocol.h" -@interface SUDiskImageUnarchiver : SUUnarchiver +NS_ASSUME_NONNULL_BEGIN + +@interface SUDiskImageUnarchiver : NSObject + +- (instancetype)initWithArchivePath:(NSString *)archivePath decryptionPassword:(nullable NSString *)decryptionPassword delegate:(nullable id )delegate; @end +NS_ASSUME_NONNULL_END + #endif diff --git a/Sparkle/SUDiskImageUnarchiver.m b/Sparkle/SUDiskImageUnarchiver.m index e6f743e7..7c8fc441 100644 --- a/Sparkle/SUDiskImageUnarchiver.m +++ b/Sparkle/SUDiskImageUnarchiver.m @@ -7,12 +7,22 @@ // #import "SUDiskImageUnarchiver.h" -#import "SUUnarchiver_Private.h" #import "SULog.h" -#include + +@interface SUDiskImageUnarchiver () + +@property (nonatomic, copy, readonly) NSString *archivePath; +@property (nullable, nonatomic, copy, readonly) NSString *decryptionPassword; +@property (nonatomic, weak, readonly) id delegate; + +@end @implementation SUDiskImageUnarchiver +@synthesize archivePath = _archivePath; +@synthesize decryptionPassword = _decryptionPassword; +@synthesize delegate = _delegate; + + (BOOL)canUnarchivePath:(NSString *)path { return [[path pathExtension] isEqualToString:@"dmg"]; @@ -23,25 +33,25 @@ return NO; } -// Called on a non-main thread. -- (void)extractDMG +- (instancetype)initWithArchivePath:(NSString *)archivePath decryptionPassword:(nullable NSString *)decryptionPassword delegate:(nullable id )delegate { - @autoreleasepool { - [self extractDMGWithPassword:nil]; + self = [super init]; + if (self != nil) { + _archivePath = [archivePath copy]; + _decryptionPassword = [decryptionPassword copy]; + _delegate = delegate; } + return self; } // Called on a non-main thread. -- (void)extractDMGWithPassword:(NSString *)__unused password +- (void)extractDMG { - @autoreleasepool { + @autoreleasepool { BOOL mountedSuccessfully = NO; - - SULog(@"Extracting %@ as a DMG", self.archivePath); - + // get a unique mount point path NSString *mountPoint = nil; - FSRef tmpRef; NSFileManager *manager; NSError *error; NSArray *contents; @@ -49,33 +59,34 @@ // 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 notifyDelegateOfFailure]; + [self.delegate unarchiverDidFail]; }; dispatch_block_t delegateSuccess = ^{ - [self notifyDelegateOfSuccess]; + [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); } - } - while (noErr == FSPathMakeRefWithOptions((const UInt8 *)[mountPoint fileSystemRepresentation], kFSPathMakeRefDoNotFollowLeafSymlink, &tmpRef, NULL)); - + } + // 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: @@ -85,14 +96,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 = @"/"; @@ -119,53 +130,59 @@ { goto reportError; } - - if (taskResult != 0) - { + + if (taskResult != 0) + { NSString *resultStr = output ? [[NSString alloc] initWithData:output encoding:NSUTF8StringEncoding] : nil; SULog(@"hdiutil failed with code: %ld data: <<%@>>", (long)taskResult, resultStr); 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; } - - for (NSString *item in contents) - { + + 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; } - + SULog(@"copyItemAtPath:%@ toPath:%@", fromPath, toPath); - - if (![manager copyItemAtPath:fromPath toPath:toPath error:&error]) - { + + 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); goto finally; - + reportError: dispatch_async(dispatch_get_main_queue(), delegateFailure); - + finally: if (mountedSuccessfully) { + NSTask *task = [[NSTask alloc] init]; + task.launchPath = @"/usr/bin/hdiutil"; + task.arguments = @[@"detach", mountPoint, @"-force"]; + task.standardOutput = [NSPipe pipe]; + task.standardError = [NSPipe pipe]; + @try { - [NSTask launchedTaskWithLaunchPath:@"/usr/bin/hdiutil" arguments:@[@"detach", mountPoint, @"-force"]]; + [task launch]; } @catch (NSException *exception) { SULog(@"Failed to unmount %@", mountPoint); SULog(@"Exception: %@", exception); @@ -179,28 +196,10 @@ - (void)start { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ - [self extractDMG]; + [self extractDMG]; }); } -+ (void)load -{ - [self registerImplementation:self]; -} - -- (BOOL)isEncrypted:(NSData *)resultData -{ - BOOL result = NO; - if(resultData) - { - NSString *data = [[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding]; - - if ((data != nil) && !NSEqualRanges([data rangeOfString:@"passphrase-count"], NSMakeRange(NSNotFound, 0))) - { - result = YES; - } - } - return result; -} +- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], self.archivePath]; } @end diff --git a/Sparkle/SUPipedUnarchiver.h b/Sparkle/SUPipedUnarchiver.h index 7304ba0a..caec2b9e 100644 --- a/Sparkle/SUPipedUnarchiver.h +++ b/Sparkle/SUPipedUnarchiver.h @@ -9,11 +9,17 @@ #ifndef SUPIPEDUNARCHIVER_H #define SUPIPEDUNARCHIVER_H -#import -#import "SUUnarchiver.h" +#import +#import "SUUnarchiverProtocol.h" -@interface SUPipedUnarchiver : SUUnarchiver +NS_ASSUME_NONNULL_BEGIN + +@interface SUPipedUnarchiver : NSObject + +- (instancetype)initWithArchivePath:(NSString *)archivePath delegate:(nullable id )delegate; @end +NS_ASSUME_NONNULL_END + #endif diff --git a/Sparkle/SUPipedUnarchiver.m b/Sparkle/SUPipedUnarchiver.m index 0b0157c3..0b2a7b85 100644 --- a/Sparkle/SUPipedUnarchiver.m +++ b/Sparkle/SUPipedUnarchiver.m @@ -7,38 +7,56 @@ // #import "SUPipedUnarchiver.h" -#import "SUUnarchiver_Private.h" #import "SULog.h" +@interface SUPipedUnarchiver () + +@property (nonatomic, copy, readonly) NSString *archivePath; +@property (nonatomic, weak, readonly) id delegate; + +@end @implementation SUPipedUnarchiver -+ (SEL)selectorConformingToTypeOfPath:(NSString *)path +@synthesize archivePath = _archivePath; +@synthesize delegate = _delegate; + ++ (nullable NSArray *)commandAndArgumentsConformingToTypeOfPath:(NSString *)path { - static NSDictionary *typeSelectorDictionary; - if (!typeSelectorDictionary) - typeSelectorDictionary = @{ @".zip": @"extractZIP", - @".tar": @"extractTAR", - @".tar.gz": @"extractTGZ", - @".tgz": @"extractTGZ", - @".tar.bz2": @"extractTBZ", - @".tbz": @"extractTBZ", - @".tar.xz": @"extractTXZ", - @".txz": @"extractTXZ", - @".tar.lzma": @"extractTXZ"}; - + NSArray *extractTGZ = @[@"/usr/bin/tar", @"-zxC"]; + NSArray *extractTBZ = @[@"/usr/bin/tar", @"-jxC"]; + NSArray *extractTXZ = extractTGZ; + + NSDictionary *> *extractCommandDictionary = + @{ + @".zip" : @[@"/usr/bin/ditto", @"-x",@"-k",@"-"], + @".tar" : @[@"/usr/bin/tar", @"-xC"], + @".tar.gz" : extractTGZ, + @".tgz" : extractTGZ, + @".tar.bz2" : extractTBZ, + @".tbz" : extractTBZ, + @".tar.xz" : extractTXZ, + @".txz" : extractTXZ, + @".tar.lzma" : extractTXZ + }; + NSString *lastPathComponent = [path lastPathComponent]; - for (NSString *currentType in typeSelectorDictionary) - { - NSString *value = [typeSelectorDictionary objectForKey:currentType]; - assert(value); - - if ([currentType length] > [lastPathComponent length]) continue; + for (NSString *currentType in extractCommandDictionary) + { + NSArray *value = [extractCommandDictionary objectForKey:currentType]; + assert(value != nil); + + if ([currentType length] > [lastPathComponent length]) continue; if ([[lastPathComponent substringFromIndex:[lastPathComponent length] - [currentType length]] isEqualToString:currentType]) { - return NSSelectorFromString(value); + return value; } } - return NULL; + return nil; +} + ++ (BOOL)canUnarchivePath:(NSString *)path +{ + return ([self commandAndArgumentsConformingToTypeOfPath:path] != nil); } + (BOOL)unsafeIfArchiveIsNotValidated @@ -46,35 +64,50 @@ return NO; } -- (void)start +- (instancetype)initWithArchivePath:(NSString *)archivePath delegate:(nullable id )delegate { - [NSThread detachNewThreadSelector:[[self class] selectorConformingToTypeOfPath:self.archivePath] toTarget:self withObject:nil]; + self = [super init]; + if (self != nil) { + _archivePath = [archivePath copy]; + _delegate = delegate; + } + return self; } -+ (BOOL)canUnarchivePath:(NSString *)path +- (void)start { - return ([self selectorConformingToTypeOfPath:path] != nil); + NSArray *commandAndArguments = [[self class] commandAndArgumentsConformingToTypeOfPath:self.archivePath]; + assert(commandAndArguments != nil); + + NSString *command = commandAndArguments.firstObject; + assert(command != nil); + + 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]; + }); } // This method abstracts the types that use a command line tool piping data from stdin. -- (void)extractArchivePipingDataToCommand:(NSString *)command args:(NSArray*)args +- (void)extractArchivePipingDataToCommand:(NSString *)command arguments:(NSArray*)args { // *** GETS CALLED ON NON-MAIN THREAD!!! - @autoreleasepool { - + @autoreleasepool { + NSString *destination = [self.archivePath stringByDeletingLastPathComponent]; SULog(@"Extracting using '%@' '%@' < '%@' '%@'", command, [args componentsJoinedByString:@"' '"], self.archivePath, destination); - + // Get the file size. NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:self.archivePath error:nil]; 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]]; @@ -82,7 +115,7 @@ [task setLaunchPath:command]; [task setArguments:[args arrayByAddingObject:destination]]; [task launch]; - + NSUInteger bytesRead = 0; do { NSData *data = [archiveInput readDataOfLength:256*1024]; @@ -93,19 +126,21 @@ bytesRead += len; [archiveOutput writeData:data]; dispatch_async(dispatch_get_main_queue(), ^{ - [self notifyDelegateOfProgress:(double)bytesRead / (double)expectedLength]; + if ([self.delegate respondsToSelector:@selector(unarchiverExtractedProgress:)]) { + [self.delegate unarchiverExtractedProgress:(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 notifyDelegateOfSuccess]; + [self.delegate unarchiverDidFinish]; }); return; } else { @@ -117,51 +152,13 @@ } else { SULog(@"Extraction failed, archive '%@' is empty", self.archivePath); } - + dispatch_async(dispatch_get_main_queue(), ^{ - [self notifyDelegateOfFailure]; + [self.delegate unarchiverDidFail]; }); } } -- (void)extractTAR -{ - // *** GETS CALLED ON NON-MAIN THREAD!!! - - [self extractArchivePipingDataToCommand:@"/usr/bin/tar" args:@[@"-xC"]]; -} - -- (void)extractTGZ -{ - // *** GETS CALLED ON NON-MAIN THREAD!!! - - [self extractArchivePipingDataToCommand:@"/usr/bin/tar" args:@[@"-zxC"]]; -} - -- (void)extractTBZ -{ - // *** GETS CALLED ON NON-MAIN THREAD!!! - - [self extractArchivePipingDataToCommand:@"/usr/bin/tar" args:@[@"-jxC"]]; -} - -- (void)extractZIP -{ - // *** GETS CALLED ON NON-MAIN THREAD!!! - - [self extractArchivePipingDataToCommand:@"/usr/bin/ditto" args:@[@"-x",@"-k",@"-"]]; -} - -- (void)extractTXZ -{ - // *** GETS CALLED ON NON-MAIN THREAD!!! - - [self extractArchivePipingDataToCommand:@"/usr/bin/tar" args:@[@"-zxC"]]; -} - -+ (void)load -{ - [self registerImplementation:self]; -} +- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], self.archivePath]; } @end diff --git a/Sparkle/SUUIBasedUpdateDriver.h b/Sparkle/SUUIBasedUpdateDriver.h index 8148912b..1018ca99 100644 --- a/Sparkle/SUUIBasedUpdateDriver.h +++ b/Sparkle/SUUIBasedUpdateDriver.h @@ -12,6 +12,7 @@ #import #import "SUBasicUpdateDriver.h" #import "SUUpdateAlert.h" +#import "SUUnarchiverProtocol.h" @class SUStatusController; diff --git a/Sparkle/SUUIBasedUpdateDriver.m b/Sparkle/SUUIBasedUpdateDriver.m index 0a0ae572..58da9bab 100644 --- a/Sparkle/SUUIBasedUpdateDriver.m +++ b/Sparkle/SUUIBasedUpdateDriver.m @@ -225,7 +225,7 @@ [self.statusController setProgressValue:progress]; } -- (void)unarchiverDidFinish:(SUUnarchiver *)__unused ua +- (void)unarchiverDidFinish { if (self.automaticallyInstallUpdates) { [self installWithToolAndRelaunch:YES]; diff --git a/Sparkle/SUUnarchiver.h b/Sparkle/SUUnarchiver.h index e2f79f04..b732c313 100644 --- a/Sparkle/SUUnarchiver.h +++ b/Sparkle/SUUnarchiver.h @@ -6,34 +6,17 @@ // Copyright 2006 Andy Matuschak. All rights reserved. // -#ifndef SUUNARCHIVER_H -#define SUUNARCHIVER_H - #import -@class SUHost; +NS_ASSUME_NONNULL_BEGIN + +@protocol SUUnarchiverProtocol; @protocol SUUnarchiverDelegate; @interface SUUnarchiver : NSObject -@property (copy, readonly) NSString *archivePath; -@property (copy, readonly) NSString *updateHostBundlePath; -@property (copy, readonly) NSString *decryptionPassword; -@property (weak) id delegate; - -+ (SUUnarchiver *)unarchiverForPath:(NSString *)path updatingHostBundlePath:(NSString *)host withPassword:(NSString *)decryptionPassword; - -+ (BOOL)unsafeIfArchiveIsNotValidated; - -- (void)start; ++ (nullable id )unarchiverForPath:(NSString *)path updatingHostBundlePath:(nullable NSString *)hostPath decryptionPassword:(nullable NSString *)decryptionPassword delegate:(nullable id )delegate; @end -@protocol SUUnarchiverDelegate -- (void)unarchiverDidFinish:(SUUnarchiver *)unarchiver; -- (void)unarchiverDidFail:(SUUnarchiver *)unarchiver; -@optional -- (void)unarchiver:(SUUnarchiver *)unarchiver extractedProgress:(double)progress; -@end - -#endif +NS_ASSUME_NONNULL_END diff --git a/Sparkle/SUUnarchiver.m b/Sparkle/SUUnarchiver.m index b12d0648..2d9b204c 100644 --- a/Sparkle/SUUnarchiver.m +++ b/Sparkle/SUUnarchiver.m @@ -6,94 +6,29 @@ // Copyright 2006 Andy Matuschak. All rights reserved. // - -#import "SUUpdater.h" - -#import "SUAppcast.h" -#import "SUAppcastItem.h" -#import "SUVersionComparisonProtocol.h" #import "SUUnarchiver.h" -#import "SUUnarchiver_Private.h" +#import "SUUnarchiverProtocol.h" +#import "SUPipedUnarchiver.h" +#import "SUDiskImageUnarchiver.h" +#import "SUBinaryDeltaUnarchiver.h" @implementation SUUnarchiver -@synthesize archivePath; -@synthesize updateHostBundlePath; -@synthesize delegate; -@synthesize decryptionPassword; - -+ (SUUnarchiver *)unarchiverForPath:(NSString *)path updatingHostBundlePath:(NSString *)hostPath withPassword:(NSString *)decryptionPassword ++ (nullable id )unarchiverForPath:(NSString *)path updatingHostBundlePath:(nullable NSString *)hostPath decryptionPassword:(nullable NSString *)decryptionPassword delegate:(nullable id )delegate { - for (id current in [self unarchiverImplementations]) { - if ([current canUnarchivePath:path]) { - return [[current alloc] initWithPath:path hostBundlePath:hostPath password:decryptionPassword]; - } + if ([SUPipedUnarchiver canUnarchivePath:path]) { + return [[SUPipedUnarchiver alloc] initWithArchivePath:path delegate:delegate]; + + } else if ([SUDiskImageUnarchiver canUnarchivePath:path]) { + return [[SUDiskImageUnarchiver alloc] initWithArchivePath:path decryptionPassword:decryptionPassword delegate:delegate]; + + } else if ([SUBinaryDeltaUnarchiver canUnarchivePath:path]) { + assert(hostPath != nil); + NSString *nonNullHostPath = hostPath; + return [[SUBinaryDeltaUnarchiver alloc] initWithArchivePath:path updateHostBundlePath:nonNullHostPath delegate:delegate]; + } return nil; } -- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], self.archivePath]; } - -- (void)start -{ - // No-op -} - -- (instancetype)initWithPath:(NSString *)path hostBundlePath:(NSString *)hostPath password:(NSString *)password -{ - if ((self = [super init])) - { - archivePath = [path copy]; - updateHostBundlePath = hostPath; - decryptionPassword = password; - } - return self; -} - -+ (BOOL)canUnarchivePath:(NSString *)__unused path -{ - return NO; -} - -+ (BOOL)unsafeIfArchiveIsNotValidated -{ - return NO; -} - -- (void)notifyDelegateOfProgress:(double)progress -{ - if ([self.delegate respondsToSelector:@selector(unarchiver:extractedProgress:)]) { - [self.delegate unarchiver:self extractedProgress:progress]; - } -} - -- (void)notifyDelegateOfSuccess -{ - if ([self.delegate respondsToSelector:@selector(unarchiverDidFinish:)]) { - [self.delegate unarchiverDidFinish:self]; - } -} - -- (void)notifyDelegateOfFailure -{ - if ([self.delegate respondsToSelector:@selector(unarchiverDidFail:)]) { - [self.delegate unarchiverDidFail:self]; - } -} - -static NSMutableArray *gUnarchiverImplementations; - -+ (void)registerImplementation:(Class)implementation -{ - if (!gUnarchiverImplementations) { - gUnarchiverImplementations = [[NSMutableArray alloc] init]; - } - [gUnarchiverImplementations addObject:implementation]; -} - -+ (NSArray *)unarchiverImplementations -{ - return [NSArray arrayWithArray:gUnarchiverImplementations]; -} - @end diff --git a/Sparkle/SUUnarchiverProtocol.h b/Sparkle/SUUnarchiverProtocol.h new file mode 100644 index 00000000..5a349877 --- /dev/null +++ b/Sparkle/SUUnarchiverProtocol.h @@ -0,0 +1,36 @@ +// +// SUUnarchiverProtocol.h +// Sparkle +// +// Created by Mayur Pawashe on 3/26/16. +// Copyright © 2016 Sparkle Project. All rights reserved. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@protocol SUUnarchiverProtocol + ++ (BOOL)canUnarchivePath:(NSString *)path; + ++ (BOOL)unsafeIfArchiveIsNotValidated; + +- (void)start; + +- (NSString *)description; + +@end + +@protocol SUUnarchiverDelegate + +- (void)unarchiverDidFinish; + +- (void)unarchiverDidFail; + +@optional +- (void)unarchiverExtractedProgress:(double)progress; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Sparkle/SUUnarchiver_Private.h b/Sparkle/SUUnarchiver_Private.h deleted file mode 100644 index c29d68cf..00000000 --- a/Sparkle/SUUnarchiver_Private.h +++ /dev/null @@ -1,26 +0,0 @@ -// -// SUUnarchiver_Private.h -// Sparkle -// -// Created by Andy Matuschak on 6/17/08. -// Copyright 2008 Andy Matuschak. All rights reserved. -// - -#ifndef SUUNARCHIVER_PRIVATE_H -#define SUUNARCHIVER_PRIVATE_H - -#import -#import "SUUnarchiver.h" - -@interface SUUnarchiver (Private) -+ (void)registerImplementation:(Class)implementation; -+ (NSArray *)unarchiverImplementations; -+ (BOOL)canUnarchivePath:(NSString *)path; -- (instancetype)initWithPath:(NSString *)archive hostBundlePath:(NSString *)host; - -- (void)notifyDelegateOfProgress:(double)progress; -- (void)notifyDelegateOfSuccess; -- (void)notifyDelegateOfFailure; -@end - -#endif diff --git a/Tests/SUUnarchiverTest.swift b/Tests/SUUnarchiverTest.swift index 4e70bba8..9524f010 100644 --- a/Tests/SUUnarchiverTest.swift +++ b/Tests/SUUnarchiverTest.swift @@ -18,13 +18,13 @@ class SUUnarchiverTest: XCTestCase, SUUnarchiverDelegate { } - func unarchiverDidFail(_ unarchiver: SUUnarchiver!) + func unarchiverDidFail() { self.unarchivedResult = false self.unarchivedExpectation!.fulfill() } - func unarchiverDidFinish(_ unarchiver: SUUnarchiver!) + func unarchiverDidFinish() { self.unarchivedResult = true self.unarchivedExpectation!.fulfill() @@ -49,10 +49,8 @@ class SUUnarchiverTest: XCTestCase, SUUnarchiverDelegate self.unarchivedExpectation = super.expectation(description: "Unarchived Application (format: \(archiveExtension))") - let unarchiver = SUUnarchiver(forPath: tempArchiveURL.path, updatingHostBundlePath: nil, withPassword: self.password) - - unarchiver?.delegate = self - unarchiver?.start() + let unarchiver = SUUnarchiver.unarchiver(forPath: tempArchiveURL.path, updatingHostBundlePath: nil, decryptionPassword: self.password, delegate: self) + unarchiver!.start() super.waitForExpectations(timeout: 7.0, handler: nil) From 97c652e3b07f23b02c4e5183f6e37f890e32773a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kornel=20Lesin=CC=81ski?= Date: Wed, 21 Dec 2016 17:41:09 +0100 Subject: [PATCH 16/27] Fixed method name --- Sparkle/SUUnarchiver.m | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sparkle/SUUnarchiver.m b/Sparkle/SUUnarchiver.m index 1f146c3f..353305e9 100644 --- a/Sparkle/SUUnarchiver.m +++ b/Sparkle/SUUnarchiver.m @@ -80,7 +80,7 @@ }); } -- (void)unarchiverDidFail:(NSError *)reason +- (void)unarchiverDidFailWithError:(NSError *)reason { NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithObject:SULocalizedString(@"An error occurred while extracting the archive. Please try again later.", nil) forKey:NSLocalizedDescriptionKey]; if (reason) { From b03ae0d765a2265b086b05f4719fc78403ad2fca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kornel=20Lesin=CC=81ski?= Date: Wed, 21 Dec 2016 18:00:17 +0100 Subject: [PATCH 17/27] Moved assert --- Tests/SUUnarchiverTest.swift | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/Tests/SUUnarchiverTest.swift b/Tests/SUUnarchiverTest.swift index 3e1d55ad..c047f4c5 100644 --- a/Tests/SUUnarchiverTest.swift +++ b/Tests/SUUnarchiverTest.swift @@ -11,8 +11,7 @@ import XCTest class SUUnarchiverTest: XCTestCase { var password: String? = nil - var unarchivedExpectation: XCTestExpectation? = nil - var unarchivedResult: Bool = false + var unarchivedSuccessExpectation: XCTestExpectation? = nil func unarchiveTestAppWithExtension(_ archiveExtension: String) { @@ -26,23 +25,22 @@ class SUUnarchiverTest: XCTestCase try! fileManager.removeItem(at: tempDirectoryURL) } + self.unarchivedSuccessExpectation = super.expectation(description: "Unarchived Success (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(forPath: tempArchiveURL.path, updatingHostBundlePath: nil, withPassword: self.password)! unarchiver.unarchive(completionBlock: {(error: Error?) -> Void in - self.unarchivedResult = nil == error; - self.unarchivedExpectation!.fulfill() + XCTAssertNil(error); + self.unarchivedSuccessExpectation!.fulfill() }, progressBlock:{(progress: Double) -> Void in }); super.waitForExpectations(timeout: 7.0, handler: nil) - XCTAssertTrue(self.unarchivedResult) XCTAssertTrue(fileManager.fileExists(atPath: extractedAppURL.path)) XCTAssertEqual("6a60ab31430cfca8fb499a884f4a29f73e59b472", hashOfTree(extractedAppURL.path)) From 8a3338b0785f968f12f55ea229174413b688f3b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kornel=20Lesin=CC=81ski?= Date: Wed, 21 Dec 2016 18:04:16 +0100 Subject: [PATCH 18/27] Extracted function --- Tests/SUUnarchiverTest.swift | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/Tests/SUUnarchiverTest.swift b/Tests/SUUnarchiverTest.swift index c047f4c5..29acad85 100644 --- a/Tests/SUUnarchiverTest.swift +++ b/Tests/SUUnarchiverTest.swift @@ -13,8 +13,7 @@ class SUUnarchiverTest: XCTestCase var password: String? = nil var unarchivedSuccessExpectation: XCTestExpectation? = nil - func unarchiveTestAppWithExtension(_ archiveExtension: String) - { + func unarchiveTestAppWithExtension(_ archiveExtension: String) { let appName = "SparkleTestCodeSignApp" let archiveResourceURL = Bundle(for: type(of: self)).url(forResource: appName, withExtension: archiveExtension)! @@ -29,21 +28,28 @@ class SUUnarchiverTest: XCTestCase let tempArchiveURL = tempDirectoryURL.appendingPathComponent(archiveResourceURL.lastPathComponent) let extractedAppURL = tempDirectoryURL.appendingPathComponent(appName).appendingPathExtension("app") + + self.unarchiveTestSuccessAppWithExtension(archiveExtension, appName: appName, tempDirectoryURL: tempDirectoryURL, tempArchiveURL: tempArchiveURL, archiveResourceURL: archiveResourceURL); + + super.waitForExpectations(timeout: 7.0, handler: nil) + + XCTAssertTrue(fileManager.fileExists(atPath: extractedAppURL.path)) + + XCTAssertEqual("6a60ab31430cfca8fb499a884f4a29f73e59b472", hashOfTree(extractedAppURL.path)) + } + + 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(forPath: tempArchiveURL.path, updatingHostBundlePath: nil, withPassword: self.password)! unarchiver.unarchive(completionBlock: {(error: Error?) -> Void in XCTAssertNil(error); self.unarchivedSuccessExpectation!.fulfill() }, progressBlock:{(progress: Double) -> Void in }); - - super.waitForExpectations(timeout: 7.0, handler: nil) - - XCTAssertTrue(fileManager.fileExists(atPath: extractedAppURL.path)) - - XCTAssertEqual("6a60ab31430cfca8fb499a884f4a29f73e59b472", hashOfTree(extractedAppURL.path)) } func testUnarchivingZip() From 2519eb573f74aebd6452627280818e1c2cbce666 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kornel=20Lesin=CC=81ski?= Date: Wed, 21 Dec 2016 18:04:38 +0100 Subject: [PATCH 19/27] Test unarchiving failure --- Tests/SUUnarchiverTest.swift | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/Tests/SUUnarchiverTest.swift b/Tests/SUUnarchiverTest.swift index 29acad85..25710d7e 100644 --- a/Tests/SUUnarchiverTest.swift +++ b/Tests/SUUnarchiverTest.swift @@ -12,6 +12,7 @@ class SUUnarchiverTest: XCTestCase { var password: String? = nil var unarchivedSuccessExpectation: XCTestExpectation? = nil + var unarchivedFailureExpectation: XCTestExpectation? = nil func unarchiveTestAppWithExtension(_ archiveExtension: String) { let appName = "SparkleTestCodeSignApp" @@ -25,11 +26,13 @@ class SUUnarchiverTest: XCTestCase } 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") self.unarchiveTestSuccessAppWithExtension(archiveExtension, appName: appName, tempDirectoryURL: tempDirectoryURL, tempArchiveURL: tempArchiveURL, archiveResourceURL: archiveResourceURL); + self.unarchiveTestFailureAppWithExtension(archiveExtension, tempDirectoryURL: tempDirectoryURL); super.waitForExpectations(timeout: 7.0, handler: nil) @@ -37,6 +40,16 @@ class SUUnarchiverTest: XCTestCase XCTAssertEqual("6a60ab31430cfca8fb499a884f4a29f73e59b472", hashOfTree(extractedAppURL.path)) } + + func unarchiveTestFailureAppWithExtension(_ archiveExtension: String, tempDirectoryURL: URL) { + let tempArchiveURL = tempDirectoryURL.appendingPathComponent("error-invalid").appendingPathExtension(archiveExtension); + let unarchiver = SUUnarchiver(forPath: tempArchiveURL.path, updatingHostBundlePath: nil, withPassword: self.password)! + + unarchiver.unarchive(completionBlock: {(error: Error?) -> Void in + XCTAssertNotNil(error); + self.unarchivedFailureExpectation!.fulfill() + }, progressBlock:{(progress: Double) -> Void in }); + } func unarchiveTestSuccessAppWithExtension(_ archiveExtension: String, appName: String, tempDirectoryURL: URL, tempArchiveURL: URL, archiveResourceURL: URL) { From 7bc7a90a09ed07e7050d9d08494db626a6dae3a8 Mon Sep 17 00:00:00 2001 From: Zorg Date: Wed, 21 Dec 2016 15:59:13 -0500 Subject: [PATCH 20/27] Fix UI update scheduler not prompting for install & relaunch --- Sparkle/SUBasicUpdateDriver.m | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Sparkle/SUBasicUpdateDriver.m b/Sparkle/SUBasicUpdateDriver.m index e4b0e39c..8b22cf33 100644 --- a/Sparkle/SUBasicUpdateDriver.m +++ b/Sparkle/SUBasicUpdateDriver.m @@ -342,8 +342,8 @@ return; } - assert(self.updateItem); - [self installWithToolAndRelaunch:YES]; + // This will call any of the subclass' implementation of -unarchiverDidFinish first + [self unarchiverDidFinish]; } progressBlock:nil]; } } From dd1bda50665f338c6e55b728cf2cdf3a8543fef9 Mon Sep 17 00:00:00 2001 From: Zorg Date: Wed, 21 Dec 2016 16:14:25 -0500 Subject: [PATCH 21/27] Some error reason is better than no reason --- Sparkle/SUBasicUpdateDriver.m | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Sparkle/SUBasicUpdateDriver.m b/Sparkle/SUBasicUpdateDriver.m index 8b22cf33..3b568e73 100644 --- a/Sparkle/SUBasicUpdateDriver.m +++ b/Sparkle/SUBasicUpdateDriver.m @@ -333,8 +333,8 @@ } if (!success) { -#warning this is bad - [self unarchiverDidFail:nil]; + NSError *reason = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{NSLocalizedDescriptionKey: @"Failed to extract update."}]; + [self unarchiverDidFail:reason]; } else { [unarchiver unarchiveWithCompletionBlock:^(NSError *err){ if (err) { From 137b73af4e17dbedc4d19f479bfaa76cac36cbaf Mon Sep 17 00:00:00 2001 From: Zorg Date: Wed, 21 Dec 2016 16:39:33 -0500 Subject: [PATCH 22/27] Fix subclass compatibility and update schedule unarchiving behavior --- Sparkle/SUAutomaticUpdateDriver.m | 2 +- Sparkle/SUBasicUpdateDriver.h | 4 ++++ Sparkle/SUBasicUpdateDriver.m | 27 +++++++++++++++++---------- Sparkle/SUUIBasedUpdateDriver.m | 4 ++-- 4 files changed, 24 insertions(+), 13 deletions(-) diff --git a/Sparkle/SUAutomaticUpdateDriver.m b/Sparkle/SUAutomaticUpdateDriver.m index f6d23b04..6abb1294 100644 --- a/Sparkle/SUAutomaticUpdateDriver.m +++ b/Sparkle/SUAutomaticUpdateDriver.m @@ -62,7 +62,7 @@ static const NSTimeInterval SUAutomaticUpdatePromptImpatienceTimer = 60 * 60 * 2 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive:) name:NSApplicationDidBecomeActiveNotification object:NSApp]; } -- (void)unarchiverDidFinish +- (void)unarchiverDidFinish:(id)__unused ua { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate:) name:NSApplicationWillTerminateNotification object:nil]; [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(systemWillPowerOff:) name:NSWorkspaceWillPowerOffNotification object:nil]; diff --git a/Sparkle/SUBasicUpdateDriver.h b/Sparkle/SUBasicUpdateDriver.h index 0e61f5f3..97dc34e8 100644 --- a/Sparkle/SUBasicUpdateDriver.h +++ b/Sparkle/SUBasicUpdateDriver.h @@ -40,6 +40,10 @@ - (void)extractUpdate; - (void)failedToApplyDeltaUpdate; +// Needed to preserve compatibility to subclasses, even though our unarchiver code uses blocks now +- (void)unarchiver:(id)ua extractedProgress:(double)progress; +- (void)unarchiverDidFinish:(id)ua; + - (void)installWithToolAndRelaunch:(BOOL)relaunch; - (void)installWithToolAndRelaunch:(BOOL)relaunch displayingUserInterface:(BOOL)showUI; - (void)installerForHost:(SUHost *)host failedWithError:(NSError *)error; diff --git a/Sparkle/SUBasicUpdateDriver.m b/Sparkle/SUBasicUpdateDriver.m index 3b568e73..4e6d5d1f 100644 --- a/Sparkle/SUBasicUpdateDriver.m +++ b/Sparkle/SUBasicUpdateDriver.m @@ -334,17 +334,18 @@ if (!success) { NSError *reason = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{NSLocalizedDescriptionKey: @"Failed to extract update."}]; - [self unarchiverDidFail:reason]; + [self unarchiverDidFailWithError:reason]; } else { [unarchiver unarchiveWithCompletionBlock:^(NSError *err){ if (err) { - [self unarchiverDidFail:err]; + [self unarchiverDidFailWithError:err]; return; } - - // This will call any of the subclass' implementation of -unarchiverDidFinish first - [self unarchiverDidFinish]; - } progressBlock:nil]; + + [self unarchiverDidFinish:nil]; + } progressBlock:^(double progress) { + [self unarchiver:nil extractedProgress:progress]; + }]; } } @@ -357,14 +358,20 @@ [self downloadUpdate]; } -- (void)unarchiverDidFinish +// By default does nothing, can be overridden +- (void)unarchiver:(id)__unused ua extractedProgress:(double)__unused progress +{ +} + +// Note this method can be overridden (and is) +- (void)unarchiverDidFinish:(id)__unused ua { assert(self.updateItem); - + [self installWithToolAndRelaunch:YES]; } -- (void)unarchiverDidFail:(NSError *)err +- (void)unarchiverDidFailWithError:(NSError *)err { // No longer needed self.updateValidator = nil; @@ -373,7 +380,7 @@ [self failedToApplyDeltaUpdate]; return; } - + [self abortUpdateWithError:err]; } diff --git a/Sparkle/SUUIBasedUpdateDriver.m b/Sparkle/SUUIBasedUpdateDriver.m index 58da9bab..caa3959a 100644 --- a/Sparkle/SUUIBasedUpdateDriver.m +++ b/Sparkle/SUUIBasedUpdateDriver.m @@ -216,7 +216,7 @@ [super extractUpdate]; } -- (void)unarchiver:(SUUnarchiver *)__unused ua extractedProgress:(double)progress +- (void)unarchiver:(id)__unused ua extractedProgress:(double)progress { // We do this here instead of in extractUpdate so that we only have a determinate progress bar for archives with progress. if ([self.statusController maxProgressValue] == 0.0) { @@ -225,7 +225,7 @@ [self.statusController setProgressValue:progress]; } -- (void)unarchiverDidFinish +- (void)unarchiverDidFinish:(id)__unused ua { if (self.automaticallyInstallUpdates) { [self installWithToolAndRelaunch:YES]; From 98b3a9828abfd0283a3574d21f5c8b15d47ed28f Mon Sep 17 00:00:00 2001 From: Zorg Date: Thu, 22 Dec 2016 12:17:45 -0500 Subject: [PATCH 23/27] Use localhost instead of 0.0.0.0. Latter doesn't work when offline. --- TestApplication/TestApplication-Info.plist | 2 +- TestApplication/sparkletestcast.xml | 2 +- Tests/Resources/testappcast.xml | 12 ++++++------ Tests/Resources/testnamespaces.xml | 4 ++-- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/TestApplication/TestApplication-Info.plist b/TestApplication/TestApplication-Info.plist index 45b0254b..7195cb07 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 NSAppTransportSecurity 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 e3894b41..287dbda4 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 94f5f1de..0f3e5950 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 - + From 6fcd6beb84a70a7a34c45a66d122805626b441b3 Mon Sep 17 00:00:00 2001 From: Zorg Date: Thu, 22 Dec 2016 12:18:31 -0500 Subject: [PATCH 24/27] Fix UI tests from not working when update alert automatically shows --- UITests/SUTestApplicationTest.swift | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) 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() From 657e3d47d0adc9ed7a8d192477f3b9184e5796e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kornel=20Lesin=CC=81ski?= Date: Fri, 23 Dec 2016 16:21:13 +0100 Subject: [PATCH 25/27] Removed unnecessary nullability --- Sparkle/SUAppcast.h | 6 +++--- Sparkle/SUFileManager.h | 8 ++++---- Sparkle/SUPlainInstaller.m | 6 ++++-- Tests/SUFileManagerTest.swift | 2 +- Tests/SUSpotlightImporterTest.swift | 2 +- 5 files changed, 13 insertions(+), 11 deletions(-) diff --git a/Sparkle/SUAppcast.h b/Sparkle/SUAppcast.h index 08bd9af0..c81994b4 100644 --- a/Sparkle/SUAppcast.h +++ b/Sparkle/SUAppcast.h @@ -21,13 +21,13 @@ NS_ASSUME_NONNULL_BEGIN @class SUAppcastItem; SU_EXPORT @interface SUAppcast : NSObject -@property (copy) NSString *_Nullable userAgentString; -@property (copy) NSDictionary *_Nullable httpHeaders; +@property (copy, nullable) NSString *userAgentString; +@property (copy, nullable) NSDictionary *httpHeaders; - (void)fetchAppcastFromURL:(NSURL *)url completionBlock:(void (^)(NSError *_Nullable))err; - (SUAppcast *)copyWithoutDeltaUpdates; -@property (readonly, copy) NSArray *_Nullable items; +@property (readonly, copy, nullable) NSArray *items; @end NS_ASSUME_NONNULL_END diff --git a/Sparkle/SUFileManager.h b/Sparkle/SUFileManager.h index 8cd41bed..0573bf10 100644 --- a/Sparkle/SUFileManager.h +++ b/Sparkle/SUFileManager.h @@ -21,7 +21,7 @@ NS_ASSUME_NONNULL_BEGIN * Creates a file manager that will not authorize for file operations * @return A new file manager instance */ -+ (nullable instancetype)defaultManager; ++ (instancetype)defaultManager; /** * Creates a file manager that allows authorizing for file operations @@ -31,7 +31,7 @@ NS_ASSUME_NONNULL_BEGIN * * This method just creates the file manager. It doesn't acquire authorization immediately or if it doesn't need to. */ -+ (nullable instancetype)fileManagerWithAuthorizationToolPath:(NSString *)authorizationToolPath; ++ (instancetype)fileManagerWithAuthorizationToolPath:(NSString *)authorizationToolPath; /** * Returns a file manager that allows or disallows authorizing for file operations based on the current file manager @@ -40,7 +40,7 @@ NS_ASSUME_NONNULL_BEGIN * * This may return a newly created file manager or re-use the existing file manager depending on the current authorization rights. */ -- (nullable instancetype)fileManagerByPreservingAuthorizationRights; +- (instancetype)fileManagerByPreservingAuthorizationRights; /** * Creates a temporary directory on the same volume as a provided URL @@ -52,7 +52,7 @@ NS_ASSUME_NONNULL_BEGIN * When moving an item from a source to a destination, it is desirable to create a temporary intermediate destination on the same volume as the destination to ensure * that the item will be moved, and not copied, from the intermediate point to the final destination. This ensures file atomicity. */ -- (nullable NSURL *)makeTemporaryDirectoryWithPreferredName:(NSString *)preferredName appropriateForDirectoryURL:(nullable NSURL *)appropriateURL error:(NSError *_Nullable*_Nullable)error; +- (nullable NSURL *)makeTemporaryDirectoryWithPreferredName:(NSString *)preferredName appropriateForDirectoryURL:(NSURL *)appropriateURL error:(NSError *_Nullable*_Nullable)error; /** * Creates a directory at the target URL diff --git a/Sparkle/SUPlainInstaller.m b/Sparkle/SUPlainInstaller.m index 1f858604..0661a641 100644 --- a/Sparkle/SUPlainInstaller.m +++ b/Sparkle/SUPlainInstaller.m @@ -46,7 +46,8 @@ // Create a temporary directory for our new app that resides on our destination's volume NSString *preferredName = [installationURL.lastPathComponent.stringByDeletingPathExtension stringByAppendingString:@" (Incomplete Update)"]; - NSURL *tempNewDirectoryURL = [fileManager makeTemporaryDirectoryWithPreferredName:preferredName appropriateForDirectoryURL:installationURL.URLByDeletingLastPathComponent error:error]; + 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; @@ -105,9 +106,10 @@ NSString *oldURLExtension = oldURL.pathExtension; NSString *oldDestinationNameWithPathExtension = [oldDestinationName stringByAppendingPathExtension:oldURLExtension]; + NSURL *oldURLDirectory = oldURL.URLByDeletingLastPathComponent; // Create a temporary directory for our old app that resides on its volume - NSURL *tempOldDirectoryURL = [fileManager makeTemporaryDirectoryWithPreferredName:oldDestinationName appropriateForDirectoryURL:oldURL.URLByDeletingLastPathComponent error:error]; + NSURL *tempOldDirectoryURL = [fileManager makeTemporaryDirectoryWithPreferredName:oldDestinationName appropriateForDirectoryURL:oldURLDirectory error:error]; if (tempOldDirectoryURL == nil) { SULog(@"Failed to create temporary directory for old app at %@", oldURL.path); [fileManager removeItemAtURL:tempNewDirectoryURL error:NULL]; diff --git a/Tests/SUFileManagerTest.swift b/Tests/SUFileManagerTest.swift index ad3fa7e0..91c30afd 100644 --- a/Tests/SUFileManagerTest.swift +++ b/Tests/SUFileManagerTest.swift @@ -311,6 +311,6 @@ class SUFileManagerTest: XCTestCase func testAcquireBadAuthorization() { let fileManager = SUFileManager.default() - XCTAssertNil(try? fileManager?._acquireAuthorization()) + XCTAssertNil(try? fileManager._acquireAuthorization()) } } diff --git a/Tests/SUSpotlightImporterTest.swift b/Tests/SUSpotlightImporterTest.swift index 8d48ade5..25193055 100644 --- a/Tests/SUSpotlightImporterTest.swift +++ b/Tests/SUSpotlightImporterTest.swift @@ -12,7 +12,7 @@ class SUSpotlightImporterTest: XCTestCase { func testUpdatingSpotlightBundles() { - let fileManager = SUFileManager.default()! + let fileManager = SUFileManager.default() let tempDirectoryURL = try! fileManager.makeTemporaryDirectory(withPreferredName: "Sparkle Unit Test Data", appropriateForDirectoryURL: URL(fileURLWithPath: NSHomeDirectory())) let bundleDirectory = tempDirectoryURL.appendingPathComponent("bundle.app") From c98017dbe2b4b012939d05402464e1e0349f5f2e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kornel=20Lesin=CC=81ski?= Date: Fri, 23 Dec 2016 16:28:34 +0100 Subject: [PATCH 26/27] Fixed binary delta tool --- Sparkle/SUBinaryDeltaTool.m | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sparkle/SUBinaryDeltaTool.m b/Sparkle/SUBinaryDeltaTool.m index 01f07dcf..c242d064 100644 --- a/Sparkle/SUBinaryDeltaTool.m +++ b/Sparkle/SUBinaryDeltaTool.m @@ -158,7 +158,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; } From c77895066a79a18284cb02f176fea8e2767d52d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kornel=20Lesin=CC=81ski?= Date: Fri, 23 Dec 2016 16:59:40 +0100 Subject: [PATCH 27/27] Appropriate deployment target for test app xib --- TestApplication/English.lproj/MainMenu.xib | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/TestApplication/English.lproj/MainMenu.xib b/TestApplication/English.lproj/MainMenu.xib index ccd4e02a..a8e12383 100644 --- a/TestApplication/English.lproj/MainMenu.xib +++ b/TestApplication/English.lproj/MainMenu.xib @@ -1,9 +1,8 @@ - + - - - + + @@ -97,12 +96,14 @@ - + + +