diff --git a/Sparkle.xcodeproj/xcshareddata/xcschemes/Sparkle Test App.xcscheme b/Sparkle.xcodeproj/xcshareddata/xcschemes/Sparkle Test App.xcscheme index d3e6a793..fbf8b3c8 100644 --- a/Sparkle.xcodeproj/xcshareddata/xcschemes/Sparkle Test App.xcscheme +++ b/Sparkle.xcodeproj/xcshareddata/xcschemes/Sparkle Test App.xcscheme @@ -58,6 +58,11 @@ value = "DELTA_AND_MARKDOWN" isEnabled = "NO"> + + diff --git a/Sparkle/SPUAutomaticUpdateDriver.h b/Sparkle/SPUAutomaticUpdateDriver.h index 1c06e701..69b9b935 100644 --- a/Sparkle/SPUAutomaticUpdateDriver.h +++ b/Sparkle/SPUAutomaticUpdateDriver.h @@ -16,7 +16,7 @@ NS_ASSUME_NONNULL_BEGIN SPU_OBJC_DIRECT_MEMBERS @interface SPUAutomaticUpdateDriver : NSObject -- (instancetype)initWithHost:(SUHost *)host applicationBundle:(NSBundle *)applicationBundle updater:(id)updater userDriver:(id )userDriver updaterDelegate:(nullable id )updaterDelegate; +- (instancetype)initWithHost:(SUHost *)host applicationBundle:(NSBundle *)applicationBundle updater:(id)updater userDriver:(id )userDriver updaterDelegate:(nullable id )updaterDelegate impatientUpdateCheckInterval:(NSTimeInterval)impatientUpdateCheckInterval lastImpatientCheckedDate:(NSDate *)lastImpatientCheckedDate; @end diff --git a/Sparkle/SPUAutomaticUpdateDriver.m b/Sparkle/SPUAutomaticUpdateDriver.m index bcb5fb0e..e51c52ac 100644 --- a/Sparkle/SPUAutomaticUpdateDriver.m +++ b/Sparkle/SPUAutomaticUpdateDriver.m @@ -26,15 +26,20 @@ { SPUCoreBasedUpdateDriver *_coreDriver; SUAppcastItem* _updateItem; + NSDate *_lastImpatientCheckedDate; __weak id _updater; __weak id _userDriver; __weak id _updaterDelegate; + NSTimeInterval _impatientUpdateCheckInterval; + BOOL _installerDidFinishPreparation; + BOOL _startedResumingInstallingUpdate; + BOOL _impatientIntervalElapsedForResumingInstall; } -- (instancetype)initWithHost:(SUHost *)host applicationBundle:(NSBundle *)applicationBundle updater:(id)updater userDriver:(id )userDriver updaterDelegate:(nullable id )updaterDelegate +- (instancetype)initWithHost:(SUHost *)host applicationBundle:(NSBundle *)applicationBundle updater:(id)updater userDriver:(id )userDriver updaterDelegate:(nullable id )updaterDelegate impatientUpdateCheckInterval:(NSTimeInterval)impatientUpdateCheckInterval lastImpatientCheckedDate:(NSDate *)lastImpatientCheckedDate { self = [super init]; if (self != nil) { @@ -42,6 +47,8 @@ // The user driver is only used for a termination callback _userDriver = userDriver; _updaterDelegate = updaterDelegate; + _impatientUpdateCheckInterval = impatientUpdateCheckInterval; + _lastImpatientCheckedDate = lastImpatientCheckedDate; _coreDriver = [[SPUCoreBasedUpdateDriver alloc] initWithHost:host applicationBundle:applicationBundle updateCheck:SPUUpdateCheckUpdatesInBackground updater:updater updaterDelegate:updaterDelegate delegate:self]; } return self; @@ -66,16 +73,16 @@ [_coreDriver checkForUpdatesAtAppcastURL:appcastURL withUserAgent:userAgent httpHeaders:httpHeaders inBackground:YES requiresSilentInstall:YES]; } -- (void)resumeInstallingUpdate +- (void)resumeInstallingUpdateOrCheckForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders { - // Nothing really to do here.. this shouldn't be called. - SULog(SULogLevelError, @"Error: resumeInstallingUpdate: called on SPUAutomaticUpdateDriver"); + _startedResumingInstallingUpdate = YES; + + [_coreDriver resumeInstallingUpdateOrCheckForUpdatesAtAppcastURL:appcastURL withUserAgent:userAgent httpHeaders:httpHeaders inBackground:YES requiresSilentInstall:YES]; } -- (void)resumeUpdate:(id)__unused resumableUpdate +- (void)resumeUpdate:(id)resumableUpdate orCheckForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders { - // Nothing really to do here.. this shouldn't be called. - SULog(SULogLevelError, @"Error: resumeDownloadedUpdate: called on SPUAutomaticUpdateDriver"); + [_coreDriver resumeUpdate:resumableUpdate orCheckForUpdatesAtAppcastURL:appcastURL withUserAgent:userAgent httpHeaders:httpHeaders inBackground:YES requiresSilentInstall:YES]; } // Note: critical updates can be downloaded automatically first before needing user attention @@ -84,15 +91,29 @@ static BOOL SPUUpdateRequiresUserAttentionBeforeDownloading(SUAppcastItem *updat return (updateItem.isInformationOnlyUpdate || updateItem.majorUpgrade || updateItem.signingValidationStatus == SPUAppcastSigningValidationStatusFailed); } -- (void)basicDriverDidFindUpdateWithAppcastItem:(SUAppcastItem *)updateItem secondaryAppcastItem:(SUAppcastItem * _Nullable)secondaryUpdateItem +- (void)basicDriverDidFindUpdateWithAppcastItem:(SUAppcastItem *)updateItem secondaryAppcastItem:(SUAppcastItem * _Nullable)secondaryUpdateItem resuming:(BOOL)resuming { _updateItem = updateItem; - if (SPUUpdateRequiresUserAttentionBeforeDownloading(updateItem)) { - [_coreDriver deferInformationalUpdate:updateItem secondaryUpdate:secondaryUpdateItem]; + if (resuming) { + if (_startedResumingInstallingUpdate) { + // The update has already finished preparation from a previous cycle + _installerDidFinishPreparation = YES; + + // SPUUpdater before the automatic update driver is invoked tests that the + // _lastImpatientCheckedDate is not in the future. Although there is still a small race + // between then, it's not worth worrying about. + NSTimeInterval intervalSinceImpatientDate = [[NSDate date] timeIntervalSinceDate:_lastImpatientCheckedDate]; + _impatientIntervalElapsedForResumingInstall = (intervalSinceImpatientDate >= _impatientUpdateCheckInterval); + } [self abortUpdate]; } else { - [_coreDriver downloadUpdateFromAppcastItem:updateItem secondaryAppcastItem:secondaryUpdateItem inBackground:YES]; + if (SPUUpdateRequiresUserAttentionBeforeDownloading(updateItem)) { + [_coreDriver deferInformationalUpdate:updateItem secondaryUpdate:secondaryUpdateItem]; + [self abortUpdate]; + } else { + [_coreDriver downloadUpdateFromAppcastItem:updateItem secondaryAppcastItem:secondaryUpdateItem inBackground:YES]; + } } } @@ -147,7 +168,7 @@ static BOOL SPUUpdateRequiresUserAttentionBeforeDownloading(SUAppcastItem *updat { // It should not be necessary to include properties from SPUUpdateRequiresUserAttentionBeforeDownloading() because _installerDidFinishPreparation should be NO in those cases, // but we'll include the check anyway - BOOL showNextUpdateImmediately = (error == nil || error.code == SUInstallationAuthorizeLaterError) && (!_installerDidFinishPreparation || _updateItem.criticalUpdate || SPUUpdateRequiresUserAttentionBeforeDownloading(_updateItem)); + BOOL showNextUpdateImmediately = (error == nil || error.code == SUInstallationAuthorizeLaterError) && (!_installerDidFinishPreparation || _updateItem.criticalUpdate || SPUUpdateRequiresUserAttentionBeforeDownloading(_updateItem) || _impatientIntervalElapsedForResumingInstall); [_coreDriver abortUpdateAndShowNextUpdateImmediately:showNextUpdateImmediately error:error]; } diff --git a/Sparkle/SPUBasicUpdateDriver.h b/Sparkle/SPUBasicUpdateDriver.h index 192921e7..897da6db 100644 --- a/Sparkle/SPUBasicUpdateDriver.h +++ b/Sparkle/SPUBasicUpdateDriver.h @@ -12,19 +12,17 @@ NS_ASSUME_NONNULL_BEGIN -@class SUHost, SUAppcastItem; +@class SUHost, SUAppcastItem, SPUInstallationInfo; @protocol SPUUpdaterDelegate; @protocol SPUBasicUpdateDriverDelegate -- (void)basicDriverDidFindUpdateWithAppcastItem:(SUAppcastItem *)appcastItem secondaryAppcastItem:(SUAppcastItem * _Nullable)secondaryAppcastItem systemDomain:(NSNumber * _Nullable)systemDomain; +- (void)basicDriverDidFindUpdateWithAppcastItem:(SUAppcastItem *)appcastItem secondaryAppcastItem:(SUAppcastItem * _Nullable)secondaryAppcastItem systemDomain:(NSNumber * _Nullable)systemDomain resuming:(BOOL)resuming; + +- (void)basicDriverWillDiscardStaleResumableUpdate:(id)resumableUpdate; - (void)basicDriverIsRequestingAbortUpdateWithError:(nullable NSError *)error; -@optional - -- (void)basicDriverDidFinishLoadingAppcast; - @end SPU_OBJC_DIRECT_MEMBERS @interface SPUBasicUpdateDriver : NSObject @@ -35,9 +33,11 @@ SPU_OBJC_DIRECT_MEMBERS @interface SPUBasicUpdateDriver : NSObject - (void)checkForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders inBackground:(BOOL)background; -- (void)resumeInstallingUpdate; +- (void)queryResumableInstallingUpdate:(void (^)(SPUInstallationInfo * _Nullable))completionHandler; -- (void)resumeUpdate:(id)resumableUpdate; +- (void)resumeInstallingUpdateOrCheckForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders inBackground:(BOOL)background; + +- (void)resumeUpdate:(id)resumableUpdate orCheckForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders inBackground:(BOOL)background; - (void)abortUpdateAndShowNextUpdateImmediately:(BOOL)shouldSignalShowingUpdate resumableUpdate:(id _Nullable)resumableUpdate error:(nullable NSError *)error; diff --git a/Sparkle/SPUBasicUpdateDriver.m b/Sparkle/SPUBasicUpdateDriver.m index 99032279..7efab28f 100644 --- a/Sparkle/SPUBasicUpdateDriver.m +++ b/Sparkle/SPUBasicUpdateDriver.m @@ -22,6 +22,7 @@ #import "SUVersionDisplayProtocol.h" #import "SPUStandardVersionDisplay.h" #import "SPUNoUpdateFoundInfo.h" +#import "SUStandardVersionComparator.h" #include "AppKitPrevention.h" @@ -35,6 +36,9 @@ SUAppcastDriver *_appcastDriver; SUHost *_host; + SPUInstallationInfo *_pendingResumeInstallationInfo; + id _pendingResumableUpdate; + SPUUpdateDriverCompletion _completionBlock; SPUUpdateCheck _updateCheck; @@ -44,6 +48,7 @@ __weak id _delegate; BOOL _aborted; + BOOL _resumedExistingUpdate; } - (instancetype)initWithHost:(SUHost *)host updateCheck:(SPUUpdateCheck)updateCheck updater:(id)updater updaterDelegate:(id )updaterDelegate delegate:(id )delegate @@ -67,6 +72,11 @@ } - (void)checkForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders inBackground:(BOOL)background +{ + [self checkForUpdatesAtAppcastURL:appcastURL withUserAgent:userAgent httpHeaders:httpHeaders inBackground:background resumingUpdate:NO]; +} + +- (void)checkForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders inBackground:(BOOL)background resumingUpdate:(BOOL)resumingUpdate SPU_OBJC_DIRECT { if ([_host isRunningOnReadOnlyVolume]) { NSString *hostName = _host.name; @@ -80,51 +90,70 @@ [delegate basicDriverIsRequestingAbortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SURunningFromDiskImageError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:SULocalizedStringFromTableInBundle(@"%1$@ can’t be updated because it was opened from a read-only or a temporary location.", SPARKLE_TABLE, sparkleBundle, nil), hostName], NSLocalizedRecoverySuggestionErrorKey: [NSString stringWithFormat:SULocalizedStringFromTableInBundle(@"Use Finder to copy %1$@ to the Applications folder, relaunch it from there, and try again.", SPARKLE_TABLE, sparkleBundle, nil), hostName] }]]; } } else { - [_appcastDriver loadAppcastFromURL:appcastURL userAgent:userAgent httpHeaders:httpHeaders inBackground:background]; + [_appcastDriver loadAppcastFromURL:appcastURL userAgent:userAgent httpHeaders:httpHeaders inBackground:background resumingUpdate:resumingUpdate]; } } -- (void)notifyResumableUpdateItem:(SUAppcastItem *)updateItem secondaryUpdateItem:(SUAppcastItem * _Nullable)secondaryUpdateItem systemDomain:(NSNumber * _Nullable)systemDomain SPU_OBJC_DIRECT -{ - if (updateItem == nil) { - [_delegate basicDriverIsRequestingAbortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUResumeAppcastError userInfo:@{ NSLocalizedDescriptionKey: SULocalizedStringFromTableInBundle(@"Failed to resume installing update.", SPARKLE_TABLE, SUSparkleBundle(), nil) }]]; - } else { - // Kind of lying, but triggering the notification so drivers can know when to stop showing initial fetching progress - [self notifyFinishLoadingAppcast]; - - SUAppcastItem *nonNullUpdateItem = updateItem; - [self notifyFoundValidUpdateWithAppcastItem:nonNullUpdateItem secondaryAppcastItem:secondaryUpdateItem systemDomain:systemDomain resuming:YES]; - } -} - -- (void)resumeInstallingUpdate +- (void)queryResumableInstallingUpdate:(void (^)(SPUInstallationInfo * _Nullable))completionHandler { NSString *hostBundleIdentifier = _host.bundle.bundleIdentifier; assert(hostBundleIdentifier != nil); [SPUProbeInstallStatus probeInstallerUpdateItemForHostBundleIdentifier:hostBundleIdentifier completion:^(SPUInstallationInfo * _Nullable installationInfo) { dispatch_async(dispatch_get_main_queue(), ^{ - [self notifyResumableUpdateItem:installationInfo.appcastItem secondaryUpdateItem:nil systemDomain:@(installationInfo.systemDomain)]; + completionHandler(installationInfo); }); }]; } -- (void)resumeUpdate:(id)resumableUpdate +- (void)resumeInstallingUpdateOrCheckForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders inBackground:(BOOL)background { - [self notifyResumableUpdateItem:resumableUpdate.updateItem secondaryUpdateItem:resumableUpdate.secondaryUpdateItem systemDomain:nil]; + __weak __typeof__(self) weakSelf = self; + [self queryResumableInstallingUpdate:^(SPUInstallationInfo * _Nullable installationInfo) { + __typeof__(self) strongSelf = weakSelf; + if (strongSelf != nil) { + if (installationInfo != nil) { + if (installationInfo.systemDomain || ![strongSelf->_host.bundle isEqual:NSBundle.mainBundle]) { + // When an update required auth or when updating another bundle that may + // have been started by another updater, don't risk canceling it + [strongSelf notifyFoundValidUpdateWithAppcastItem:installationInfo.appcastItem secondaryAppcastItem:nil systemDomain:@(installationInfo.systemDomain) resuming:YES]; + return; + } + + strongSelf->_pendingResumeInstallationInfo = installationInfo; + } + + [strongSelf checkForUpdatesAtAppcastURL:appcastURL withUserAgent:userAgent httpHeaders:httpHeaders inBackground:background resumingUpdate:YES]; + } + }]; +} + +- (void)resumeUpdate:(id)resumableUpdate orCheckForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders inBackground:(BOOL)background +{ + _pendingResumableUpdate = resumableUpdate; + + [self checkForUpdatesAtAppcastURL:appcastURL withUserAgent:userAgent httpHeaders:httpHeaders inBackground:background resumingUpdate:YES]; } - (void)didFailToFetchAppcastWithError:(NSError *)error { if (!_aborted) { - [_delegate basicDriverIsRequestingAbortUpdateWithError:error]; - } -} + if (_pendingResumeInstallationInfo != nil) { + SUAppcastItem *pendingItem = _pendingResumeInstallationInfo.appcastItem; + BOOL pendingSystemDomain = _pendingResumeInstallationInfo.systemDomain; + _pendingResumeInstallationInfo = nil; -- (void)notifyFinishLoadingAppcast SPU_OBJC_DIRECT -{ - id delegate = _delegate; - if ([delegate respondsToSelector:@selector(basicDriverDidFinishLoadingAppcast)]) { - [delegate basicDriverDidFinishLoadingAppcast]; + // The appcast check itself failed, so pretend it finished loading so drivers stop showing fetching progress + [self notifyFoundValidUpdateWithAppcastItem:pendingItem secondaryAppcastItem:nil systemDomain:@(pendingSystemDomain) resuming:YES]; + return; + } else if (_pendingResumableUpdate != nil) { + id pendingResumableUpdate = _pendingResumableUpdate; + _pendingResumableUpdate = nil; + + [self notifyFoundValidUpdateWithAppcastItem:pendingResumableUpdate.updateItem secondaryAppcastItem:pendingResumableUpdate.secondaryUpdateItem systemDomain:nil resuming:YES]; + return; + } + + [_delegate basicDriverIsRequestingAbortUpdateWithError:error]; } } @@ -135,13 +164,13 @@ if ([updaterDelegate respondsToSelector:@selector((updater:didFinishLoadingAppcast:))]) { [updaterDelegate updater:_updater didFinishLoadingAppcast:appcast]; } - - [self notifyFinishLoadingAppcast]; } } - (void)notifyFoundValidUpdateWithAppcastItem:(SUAppcastItem *)updateItem secondaryAppcastItem:(SUAppcastItem * _Nullable)secondaryUpdateItem systemDomain:(NSNumber * _Nullable)systemDomain resuming:(BOOL)resuming SPU_OBJC_DIRECT { + _resumedExistingUpdate = resuming; + if (!_aborted) { id delegate = _delegate; id updaterDelegate = _updaterDelegate; @@ -165,18 +194,77 @@ [updaterDelegate updater:updater didFindValidUpdate:updateItem]; } - [delegate basicDriverDidFindUpdateWithAppcastItem:updateItem secondaryAppcastItem:secondaryUpdateItem systemDomain:systemDomain]; + [delegate basicDriverDidFindUpdateWithAppcastItem:updateItem secondaryAppcastItem:secondaryUpdateItem systemDomain:systemDomain resuming:resuming]; } } +- (BOOL)pendingUpdateItem:(SUAppcastItem *)pendingUpdateItem isSupersededByUpdateItem:(SUAppcastItem *)newUpdateItem SPU_OBJC_DIRECT +{ + id versionComparator = nil; + id updaterDelegate = _updaterDelegate; + id updater = _updater; + if (updater != nil && [updaterDelegate respondsToSelector:@selector(versionComparatorForUpdater:)]) { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + versionComparator = [updaterDelegate versionComparatorForUpdater:updater]; +#pragma clang diagnostic pop + } + if (versionComparator == nil) { + versionComparator = [SUStandardVersionComparator defaultComparator]; + } + + return ([versionComparator compareVersion:pendingUpdateItem.versionString toVersion:newUpdateItem.versionString] == NSOrderedAscending); +} + - (void)didFindValidUpdateWithAppcastItem:(SUAppcastItem *)updateItem secondaryAppcastItem:(SUAppcastItem * _Nullable)secondaryAppcastItem { + id delegate = _delegate; + + if (_pendingResumeInstallationInfo != nil) { + SUAppcastItem *pendingItem = _pendingResumeInstallationInfo.appcastItem; + BOOL pendingSystemDomain = _pendingResumeInstallationInfo.systemDomain; + _pendingResumeInstallationInfo = nil; + + if (![self pendingUpdateItem:pendingItem isSupersededByUpdateItem:updateItem]) { + [self notifyFoundValidUpdateWithAppcastItem:pendingItem secondaryAppcastItem:nil systemDomain:@(pendingSystemDomain) resuming:YES]; + return; + } + + // No need to discard the prior resumable installed update. + // The update will be discarded when we submit new installer job + } else if (_pendingResumableUpdate != nil) { + id pendingResumableUpdate = _pendingResumableUpdate; + _pendingResumableUpdate = nil; + + if (![self pendingUpdateItem:pendingResumableUpdate.updateItem isSupersededByUpdateItem:updateItem]) { + [self notifyFoundValidUpdateWithAppcastItem:pendingResumableUpdate.updateItem secondaryAppcastItem:pendingResumableUpdate.secondaryUpdateItem systemDomain:nil resuming:YES]; + return; + } else { + [delegate basicDriverWillDiscardStaleResumableUpdate:pendingResumableUpdate]; + } + } + [self notifyFoundValidUpdateWithAppcastItem:updateItem secondaryAppcastItem:secondaryAppcastItem systemDomain:nil resuming:NO]; } - (void)didNotFindUpdateWithLatestAppcastItem:(nullable SUAppcastItem *)latestAppcastItem hostToLatestAppcastItemComparisonResult:(NSComparisonResult)hostToLatestAppcastItemComparisonResult background:(BOOL)background { if (!_aborted) { + if (_pendingResumeInstallationInfo != nil) { + SUAppcastItem *pendingItem = _pendingResumeInstallationInfo.appcastItem; + BOOL pendingSystemDomain = _pendingResumeInstallationInfo.systemDomain; + _pendingResumeInstallationInfo = nil; + + [self notifyFoundValidUpdateWithAppcastItem:pendingItem secondaryAppcastItem:nil systemDomain:@(pendingSystemDomain) resuming:YES]; + return; + } else if (_pendingResumableUpdate != nil) { + id pendingResumableUpdate = _pendingResumableUpdate; + _pendingResumableUpdate = nil; + + [self notifyFoundValidUpdateWithAppcastItem:pendingResumableUpdate.updateItem secondaryAppcastItem:pendingResumableUpdate.secondaryUpdateItem systemDomain:nil resuming:YES]; + return; + } + NSString *localizedDescription; #if SPARKLE_COPY_LOCALIZATIONS @@ -283,7 +371,7 @@ [_appcastDriver cleanup:^{ if (self->_completionBlock != nil) { - self->_completionBlock(shouldShowUpdateImmediately, resumableUpdate, error); + self->_completionBlock(shouldShowUpdateImmediately, self->_resumedExistingUpdate, resumableUpdate, error); self->_completionBlock = nil; } }]; diff --git a/Sparkle/SPUCoreBasedUpdateDriver.h b/Sparkle/SPUCoreBasedUpdateDriver.h index b608d23d..5890b199 100644 --- a/Sparkle/SPUCoreBasedUpdateDriver.h +++ b/Sparkle/SPUCoreBasedUpdateDriver.h @@ -13,12 +13,12 @@ NS_ASSUME_NONNULL_BEGIN -@class SUHost, SUAppcastItem; +@class SUHost, SUAppcastItem, SPUInstallationInfo; @protocol SPUUpdaterDelegate; @protocol SPUCoreBasedUpdateDriverDelegate -- (void)basicDriverDidFindUpdateWithAppcastItem:(SUAppcastItem *)updateItem secondaryAppcastItem:(SUAppcastItem * _Nullable)secondaryAppcastItem; +- (void)basicDriverDidFindUpdateWithAppcastItem:(SUAppcastItem *)updateItem secondaryAppcastItem:(SUAppcastItem * _Nullable)secondaryAppcastItem resuming:(BOOL)resuming; - (void)installerDidFinishPreparationAndWillInstallImmediately:(BOOL)willInstallImmediately; @@ -28,8 +28,6 @@ NS_ASSUME_NONNULL_BEGIN @optional -- (void)basicDriverDidFinishLoadingAppcast; - - (void)downloadDriverWillBeginDownload; - (void)downloadDriverDidReceiveExpectedContentLength:(uint64_t)expectedContentLength; @@ -56,9 +54,9 @@ SPU_OBJC_DIRECT_MEMBERS @interface SPUCoreBasedUpdateDriver : NSObject - (void)checkForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders inBackground:(BOOL)background requiresSilentInstall:(BOOL)silentInstall; -- (void)resumeInstallingUpdate; +- (void)resumeInstallingUpdateOrCheckForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders inBackground:(BOOL)background requiresSilentInstall:(BOOL)silentInstall; -- (void)resumeUpdate:(id)resumableUpdate; +- (void)resumeUpdate:(id)resumableUpdate orCheckForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders inBackground:(BOOL)background requiresSilentInstall:(BOOL)silentInstall; - (void)downloadUpdateFromAppcastItem:(SUAppcastItem *)updateItem secondaryAppcastItem:(SUAppcastItem * _Nullable)secondaryUpdateItem inBackground:(BOOL)background; diff --git a/Sparkle/SPUCoreBasedUpdateDriver.m b/Sparkle/SPUCoreBasedUpdateDriver.m index 563a136a..434c10a1 100644 --- a/Sparkle/SPUCoreBasedUpdateDriver.m +++ b/Sparkle/SPUCoreBasedUpdateDriver.m @@ -46,7 +46,7 @@ __weak id _updaterDelegate; __weak id _delegate; - BOOL _resumingInstallingUpdate; + BOOL _startedResumingInstallingUpdate; BOOL _silentInstall; } @@ -88,41 +88,37 @@ [_basicDriver checkForUpdatesAtAppcastURL:appcastURL withUserAgent:userAgent httpHeaders:httpHeaders inBackground:background]; } -- (void)resumeInstallingUpdate +- (void)resumeInstallingUpdateOrCheckForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders inBackground:(BOOL)background requiresSilentInstall:(BOOL)silentInstall { - _resumingInstallingUpdate = YES; - _silentInstall = NO; + _userAgent = [userAgent copy]; + _httpHeaders = httpHeaders; + _silentInstall = silentInstall; + _startedResumingInstallingUpdate = YES; - [_basicDriver resumeInstallingUpdate]; + [_basicDriver resumeInstallingUpdateOrCheckForUpdatesAtAppcastURL:appcastURL withUserAgent:userAgent httpHeaders:httpHeaders inBackground:background]; } -- (void)resumeUpdate:(id)resumableUpdate +- (void)resumeUpdate:(id)resumableUpdate orCheckForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders inBackground:(BOOL)background requiresSilentInstall:(BOOL)silentInstall { + _userAgent = [userAgent copy]; + _httpHeaders = httpHeaders; + _silentInstall = silentInstall; _resumableUpdate = resumableUpdate; - _silentInstall = NO; - - [_basicDriver resumeUpdate:resumableUpdate]; + + [_basicDriver resumeUpdate:resumableUpdate orCheckForUpdatesAtAppcastURL:appcastURL withUserAgent:userAgent httpHeaders:httpHeaders inBackground:background]; } -- (void)basicDriverDidFinishLoadingAppcast -{ - id delegate = _delegate; - if ([delegate respondsToSelector:@selector(basicDriverDidFinishLoadingAppcast)]) { - [delegate basicDriverDidFinishLoadingAppcast]; - } -} - -- (void)basicDriverDidFindUpdateWithAppcastItem:(SUAppcastItem *)updateItem secondaryAppcastItem:(SUAppcastItem * _Nullable)secondaryUpdateItem systemDomain:(NSNumber * _Nullable)systemDomain +- (void)basicDriverDidFindUpdateWithAppcastItem:(SUAppcastItem *)updateItem secondaryAppcastItem:(SUAppcastItem * _Nullable)secondaryUpdateItem systemDomain:(NSNumber * _Nullable)systemDomain resuming:(BOOL)resuming { _updateItem = updateItem; _secondaryUpdateItem = secondaryUpdateItem; - - if (_resumingInstallingUpdate) { + + if (resuming && _startedResumingInstallingUpdate) { assert(systemDomain != nil); [_installerDriver resumeInstallingUpdateWithUpdateItem:updateItem systemDomain:systemDomain.boolValue]; } - - [_delegate basicDriverDidFindUpdateWithAppcastItem:updateItem secondaryAppcastItem:secondaryUpdateItem]; + + [_delegate basicDriverDidFindUpdateWithAppcastItem:updateItem secondaryAppcastItem:secondaryUpdateItem resuming:resuming]; } - (void)downloadUpdateFromAppcastItem:(SUAppcastItem *)updateItem secondaryAppcastItem:(SUAppcastItem * _Nullable)secondaryUpdateItem inBackground:(BOOL)background SPU_OBJC_DIRECT @@ -183,6 +179,12 @@ [self extractUpdate:downloadedUpdate]; } +- (void)basicDriverWillDiscardStaleResumableUpdate:(id)resumableUpdate +{ + _resumableUpdate = resumableUpdate; + [self clearDownloadedUpdate]; +} + - (void)deferInformationalUpdate:(SUAppcastItem *)updateItem secondaryUpdate:(SUAppcastItem * _Nullable)secondaryUpdateItem { _resumableUpdate = [[SPUInformationalUpdate alloc] initWithAppcastItem:updateItem secondaryAppcastItem:secondaryUpdateItem]; @@ -238,7 +240,7 @@ [self clearDownloadedUpdate]; } - [self->_delegate coreDriverIsRequestingAbortUpdateWithError:error]; + [delegate coreDriverIsRequestingAbortUpdateWithError:error]; } else { // If the installer started properly, we can't use the downloaded update archive anymore // Especially if the installer fails later and we try resuming the update with a missing archive file diff --git a/Sparkle/SPUProbingUpdateDriver.m b/Sparkle/SPUProbingUpdateDriver.m index f4990ba3..4a8794a7 100644 --- a/Sparkle/SPUProbingUpdateDriver.m +++ b/Sparkle/SPUProbingUpdateDriver.m @@ -49,24 +49,29 @@ [_basicDriver checkForUpdatesAtAppcastURL:appcastURL withUserAgent:userAgent httpHeaders:httpHeaders inBackground:YES]; } -- (void)resumeInstallingUpdate +- (void)resumeInstallingUpdateOrCheckForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders { - [_basicDriver resumeInstallingUpdate]; + [_basicDriver resumeInstallingUpdateOrCheckForUpdatesAtAppcastURL:appcastURL withUserAgent:userAgent httpHeaders:httpHeaders inBackground:YES]; } -- (void)resumeUpdate:(id)resumableUpdate +- (void)resumeUpdate:(id)resumableUpdate orCheckForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders { _resumableUpdate = resumableUpdate; - [_basicDriver resumeUpdate:resumableUpdate]; + [_basicDriver resumeUpdate:resumableUpdate orCheckForUpdatesAtAppcastURL:appcastURL withUserAgent:userAgent httpHeaders:httpHeaders inBackground:YES]; } -- (void)basicDriverDidFindUpdateWithAppcastItem:(SUAppcastItem *)__unused appcastItem secondaryAppcastItem:(SUAppcastItem * _Nullable)__unused secondaryAppcastItem systemDomain:(NSNumber * _Nullable)__unused systemDomain +- (void)basicDriverDidFindUpdateWithAppcastItem:(SUAppcastItem *)__unused appcastItem secondaryAppcastItem:(SUAppcastItem * _Nullable)__unused secondaryAppcastItem systemDomain:(NSNumber * _Nullable)__unused systemDomain resuming:(BOOL)__unused resuming { // Stop as soon as we have an answer [self abortUpdate]; } +- (void)basicDriverWillDiscardStaleResumableUpdate:(id)__unused resumableUpdate +{ + _resumableUpdate = nil; +} + - (BOOL)showingUpdate { return NO; diff --git a/Sparkle/SPUScheduledUpdateDriver.m b/Sparkle/SPUScheduledUpdateDriver.m index 22027d2d..54ef32b6 100644 --- a/Sparkle/SPUScheduledUpdateDriver.m +++ b/Sparkle/SPUScheduledUpdateDriver.m @@ -57,14 +57,14 @@ [_uiDriver checkForUpdatesAtAppcastURL:appcastURL withUserAgent:userAgent httpHeaders:httpHeaders inBackground:YES]; } -- (void)resumeInstallingUpdate +- (void)resumeInstallingUpdateOrCheckForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders { - [_uiDriver resumeInstallingUpdate]; + [_uiDriver resumeInstallingUpdateOrCheckForUpdatesAtAppcastURL:appcastURL withUserAgent:userAgent httpHeaders:httpHeaders inBackground:YES]; } -- (void)resumeUpdate:(id)resumableUpdate +- (void)resumeUpdate:(id)resumableUpdate orCheckForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders { - [_uiDriver resumeUpdate:resumableUpdate]; + [_uiDriver resumeUpdate:resumableUpdate orCheckForUpdatesAtAppcastURL:appcastURL withUserAgent:userAgent httpHeaders:httpHeaders inBackground:YES]; } - (void)uiDriverDidShowUpdate diff --git a/Sparkle/SPUUIBasedUpdateDriver.h b/Sparkle/SPUUIBasedUpdateDriver.h index 0f7817f2..a4f71fcb 100644 --- a/Sparkle/SPUUIBasedUpdateDriver.h +++ b/Sparkle/SPUUIBasedUpdateDriver.h @@ -20,7 +20,6 @@ NS_ASSUME_NONNULL_BEGIN @optional - (void)uiDriverDidShowUpdate; -- (void)basicDriverDidFinishLoadingAppcast; @end @@ -37,9 +36,9 @@ SPU_OBJC_DIRECT_MEMBERS @interface SPUUIBasedUpdateDriver : NSObject - (void)checkForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders inBackground:(BOOL)background; -- (void)resumeInstallingUpdate; +- (void)resumeInstallingUpdateOrCheckForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders inBackground:(BOOL)background; -- (void)resumeUpdate:(id)resumableUpdate; +- (void)resumeUpdate:(id)resumableUpdate orCheckForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders inBackground:(BOOL)background; - (void)abortUpdateWithError:(nullable NSError *)error showErrorToUser:(BOOL)showedUserProgress; diff --git a/Sparkle/SPUUIBasedUpdateDriver.m b/Sparkle/SPUUIBasedUpdateDriver.m index fad56fa1..070e0f8a 100644 --- a/Sparkle/SPUUIBasedUpdateDriver.m +++ b/Sparkle/SPUUIBasedUpdateDriver.m @@ -151,8 +151,8 @@ __weak id _delegate; BOOL _userInitiated; - BOOL _resumingInstallingUpdate; - BOOL _resumingDownloadedInfoOrUpdate; + BOOL _startedResumingInstallingUpdate; + BOOL _startedResumingDownloadedInfoOrUpdate; } - (instancetype)initWithHost:(SUHost *)host applicationBundle:(NSBundle *)applicationBundle updater:(id)updater userDriver:(id )userDriver userInitiated:(BOOL)userInitiated updaterDelegate:(nullable id )updaterDelegate delegate:(id)delegate @@ -200,40 +200,38 @@ [_coreDriver checkForUpdatesAtAppcastURL:appcastURL withUserAgent:userAgent httpHeaders:httpHeaders inBackground:background requiresSilentInstall:NO]; } -- (void)resumeInstallingUpdate +- (void)resumeInstallingUpdateOrCheckForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders inBackground:(BOOL)background { + _httpHeaders = httpHeaders; + _userAgent = userAgent; + [self _clearSkippedUpdatesIfUserInitiated]; - _resumingInstallingUpdate = YES; - [_coreDriver resumeInstallingUpdate]; + _startedResumingInstallingUpdate = YES; + [_coreDriver resumeInstallingUpdateOrCheckForUpdatesAtAppcastURL:appcastURL withUserAgent:userAgent httpHeaders:httpHeaders inBackground:background requiresSilentInstall:NO]; } -- (void)resumeUpdate:(id)resumableUpdate +- (void)resumeUpdate:(id)resumableUpdate orCheckForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders inBackground:(BOOL)background { + _httpHeaders = httpHeaders; + _userAgent = userAgent; + [self _clearSkippedUpdatesIfUserInitiated]; - _resumingDownloadedInfoOrUpdate = YES; - [_coreDriver resumeUpdate:resumableUpdate]; + _startedResumingDownloadedInfoOrUpdate = YES; + [_coreDriver resumeUpdate:resumableUpdate orCheckForUpdatesAtAppcastURL:appcastURL withUserAgent:userAgent httpHeaders:httpHeaders inBackground:background requiresSilentInstall:NO]; } -- (void)basicDriverDidFinishLoadingAppcast -{ - id delegate = _delegate; - if ([delegate respondsToSelector:@selector(basicDriverDidFinishLoadingAppcast)]) { - [delegate basicDriverDidFinishLoadingAppcast]; - } -} - -- (void)basicDriverDidFindUpdateWithAppcastItem:(SUAppcastItem *)updateItem secondaryAppcastItem:(SUAppcastItem * _Nullable)secondaryUpdateItem +- (void)basicDriverDidFindUpdateWithAppcastItem:(SUAppcastItem *)updateItem secondaryAppcastItem:(SUAppcastItem * _Nullable)secondaryUpdateItem resuming:(BOOL)resuming { id updaterDelegate = _updaterDelegate; id delegate = _delegate; SPUUserUpdateStage stage; // Major upgrades and information only updates are not downloaded automatically, as well as feeds that failed signing validation - if (_resumingDownloadedInfoOrUpdate && !updateItem.majorUpgrade && !updateItem.informationOnlyUpdate && updateItem.signingValidationStatus != SPUAppcastSigningValidationStatusFailed) { + if (resuming && _startedResumingDownloadedInfoOrUpdate && !updateItem.majorUpgrade && !updateItem.informationOnlyUpdate && updateItem.signingValidationStatus != SPUAppcastSigningValidationStatusFailed) { stage = SPUUserUpdateStageDownloaded; - } else if (_resumingInstallingUpdate) { + } else if (resuming && _startedResumingInstallingUpdate) { stage = SPUUserUpdateStageInstalling; } else { stage = SPUUserUpdateStageNotDownloaded; @@ -286,8 +284,8 @@ case SPUUserUpdateStageDownloaded: case SPUUserUpdateStageNotDownloaded: // Informational and major updates can be resumed too, so make sure we check - // self->_resumingDownloadedInfoOrUpdate instead of the stage we pass to user driver - if (self->_resumingDownloadedInfoOrUpdate) { + // resume conditions instead of the stage we pass to user driver + if (resuming && self->_startedResumingDownloadedInfoOrUpdate) { [self->_coreDriver clearDownloadedUpdate]; } diff --git a/Sparkle/SPUUpdateDriver.h b/Sparkle/SPUUpdateDriver.h index dd9872e9..eb190612 100644 --- a/Sparkle/SPUUpdateDriver.h +++ b/Sparkle/SPUUpdateDriver.h @@ -10,7 +10,10 @@ NS_ASSUME_NONNULL_BEGIN @protocol SPUResumableUpdate; -typedef void (^SPUUpdateDriverCompletion)(BOOL shouldShowUpdateImmediately, id _Nullable resumableUpdate, NSError * _Nullable error); +// There are two types of 'resumable' updates. One type is passing a SPUResumableUpdate (a downloaded-only update). +// The other type is querying the SPUInstallationInfo from the status service, which is an update that has been staged to install already +// resumedExistingUpdate denotes if the update cycle completed resuming either of these two types +typedef void (^SPUUpdateDriverCompletion)(BOOL shouldShowUpdateImmediately, BOOL resumedExistingUpdate, id _Nullable resumableUpdate, NSError * _Nullable error); // This protocol describes an update driver that drives updates // An update driver may have multiple levels of other controller components (eg: basic update driver, core based update driver, ui based update driver, appcast driver, etc) @@ -27,9 +30,9 @@ typedef void (^SPUUpdateDriverCompletion)(BOOL shouldShowUpdateImmediately, id)resumableUpdate; +- (void)resumeUpdate:(id)resumableUpdate orCheckForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders; @property (nonatomic, readonly) BOOL showingUpdate; diff --git a/Sparkle/SPUUpdater.m b/Sparkle/SPUUpdater.m index 416162da..c27c5886 100644 --- a/Sparkle/SPUUpdater.m +++ b/Sparkle/SPUUpdater.m @@ -66,6 +66,7 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification SPUUpdaterTimer *_updaterTimer; id _resumableUpdate; NSDate *_updateLastCheckedDate; + NSDate *_updateLastImpatientCheckedDate; NSURL *_lastCheckedFeedURL; NSSet * _lastAllowedChannels; @@ -105,6 +106,10 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification _delegate = delegate; + // Initialized to the current date instead of nil so the first update check runs + // correctly if there's a installation in progress by another external updater + _updateLastImpatientCheckedDate = [NSDate date]; + NSBundle *mainBundle = [NSBundle mainBundle]; _updatingMainBundle = [hostBundle isEqualTo:mainBundle]; @@ -461,7 +466,7 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification // We start the update checks and register as observer for changes after the prompt finishes } else { // We check if the user's said they want updates, or they haven't said anything, and the default is set to checking. - [self scheduleNextUpdateCheckFiringImmediately:NO usingCurrentDate:YES]; + [self scheduleNextUpdateCheckFiringImmediately:NO usingCurrentDate:YES forcingUIUpdateDriver:NO]; } } @@ -500,7 +505,7 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification } // Note this method is never called when sessionInProgress is YES -- (void)scheduleNextUpdateCheckFiringImmediately:(BOOL)firingImmediately usingCurrentDate:(BOOL)usingCurrentDate SPU_OBJC_DIRECT +- (void)scheduleNextUpdateCheckFiringImmediately:(BOOL)firingImmediately usingCurrentDate:(BOOL)usingCurrentDate forcingUIUpdateDriver:(BOOL)forcesUIUpdateDriver SPU_OBJC_DIRECT { [_updaterTimer invalidate]; @@ -513,94 +518,65 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification } if (firingImmediately) { - [self _checkForUpdatesInBackground]; + [self _checkForUpdatesInBackgroundForcingUIUpdateDriver:forcesUIUpdateDriver]; } else { - // This may not return the same update check interval as the developer has configured - // Notably it may differ when we have an update that has been already downloaded and needs to resume, - // as well as if that update is marked critical or not - void (^retrieveNextUpdateCheckInterval)(void (^)(NSTimeInterval)) = ^(void (^completionHandler)(NSTimeInterval)) { - NSString *hostBundleIdentifier = self->_host.bundle.bundleIdentifier; - assert(hostBundleIdentifier != nil); - [SPUProbeInstallStatus probeInstallerUpdateItemForHostBundleIdentifier:hostBundleIdentifier completion:^(SPUInstallationInfo * _Nullable installationInfo) { - dispatch_async(dispatch_get_main_queue(), ^{ - NSTimeInterval regularCheckInterval = [self updateCheckInterval]; - NSTimeInterval impatientCheckInterval = [self->_updaterSettings impatientUpdateCheckInterval]; - if (installationInfo == nil) { - // Proceed as normal if there's no resumable updates - completionHandler(regularCheckInterval); - } else { - if ([installationInfo.appcastItem isCriticalUpdate] || [installationInfo.appcastItem isInformationOnlyUpdate]) { - completionHandler(MIN(regularCheckInterval, impatientCheckInterval)); - } else { - completionHandler(MAX(regularCheckInterval, impatientCheckInterval)); - } - } - }); - }]; - }; - - self.canCheckForUpdates = NO; - self.sessionInProgress = YES; - - retrieveNextUpdateCheckInterval(^(NSTimeInterval updateCheckInterval) { - [self setCanCheckForUpdates:YES]; - [self setSessionInProgress:NO]; - - // This callback is asynchronous, so the timer may be set. Invalidate to make sure it isn't. - [self->_updaterTimer invalidate]; - - NSTimeInterval intervalSinceCheck; - if (usingCurrentDate) { - // How long has it been since last we checked for an update? - NSDate *lastCheckDate = [self lastUpdateCheckDate]; - if (!lastCheckDate) { lastCheckDate = [NSDate distantPast]; } - intervalSinceCheck = [[NSDate date] timeIntervalSinceDate:lastCheckDate]; - if (intervalSinceCheck < 0) { - // Last update check date is in the future and bogus, so reset it to current date - [self updateLastUpdateCheckDate]; - - intervalSinceCheck = 0; - } - } else { + NSTimeInterval checkInterval = [self updateCheckInterval]; + + // This callback is asynchronous, so the timer may be set. Invalidate to make sure it isn't. + [_updaterTimer invalidate]; + + NSTimeInterval intervalSinceCheck; + if (usingCurrentDate) { + // How long has it been since last we checked for an update? + NSDate *lastCheckDate = [self lastUpdateCheckDate]; + if (!lastCheckDate) { + lastCheckDate = [NSDate distantPast]; + } + intervalSinceCheck = [[NSDate date] timeIntervalSinceDate:lastCheckDate]; + if (intervalSinceCheck < 0) { + // Last update check date is in the future and bogus, so reset it to current date + [self updateLastUpdateCheckDate]; + intervalSinceCheck = 0; } - - NSTimeInterval minimumUpdateCheckInterval = self->_updaterSettings.minimumUpdateCheckInterval; - - // Now we want to figure out how long until we check again. - if (updateCheckInterval < minimumUpdateCheckInterval) - updateCheckInterval = minimumUpdateCheckInterval; - if (intervalSinceCheck < updateCheckInterval) { - NSTimeInterval delayUntilCheck = (updateCheckInterval - intervalSinceCheck); // It hasn't been long enough. - if ([delegate respondsToSelector:@selector(updater:willScheduleUpdateCheckAfterDelay:)]) { - [delegate updater:self willScheduleUpdateCheckAfterDelay:delayUntilCheck]; - } - - if ([self->_userDriver respondsToSelector:@selector(logGentleScheduledUpdateReminderWarningIfNeeded)]) { - [(id)self->_userDriver logGentleScheduledUpdateReminderWarningIfNeeded]; - } - - uint64_t leewayUpdateCheckInterval = self->_updaterSettings.leewayUpdateCheckInterval; - - [self->_updaterTimer startAndFireAfterDelay:delayUntilCheck leewayUpdateCheckInterval:leewayUpdateCheckInterval]; - } else { - // We're overdue! Run one now. - [self _checkForUpdatesInBackground]; + } else { + intervalSinceCheck = 0; + } + + NSTimeInterval minimumUpdateCheckInterval = self->_updaterSettings.minimumUpdateCheckInterval; + + // Now we want to figure out how long until we check again. + if (checkInterval < minimumUpdateCheckInterval) + checkInterval = minimumUpdateCheckInterval; + if (intervalSinceCheck < checkInterval) { + NSTimeInterval delayUntilCheck = (checkInterval - intervalSinceCheck); // It hasn't been long enough. + if ([delegate respondsToSelector:@selector(updater:willScheduleUpdateCheckAfterDelay:)]) { + [delegate updater:self willScheduleUpdateCheckAfterDelay:delayUntilCheck]; } - }); + + if ([_userDriver respondsToSelector:@selector(logGentleScheduledUpdateReminderWarningIfNeeded)]) { + [(id)_userDriver logGentleScheduledUpdateReminderWarningIfNeeded]; + } + + uint64_t leewayUpdateCheckInterval = _updaterSettings.leewayUpdateCheckInterval; + + [_updaterTimer startAndFireAfterDelay:delayUntilCheck leewayUpdateCheckInterval:leewayUpdateCheckInterval]; + } else { + // We're overdue! Run one now. + [self _checkForUpdatesInBackgroundForcingUIUpdateDriver:forcesUIUpdateDriver]; + } } } - (void)updaterTimerDidFire { // User can perform a checkForUpdates check around the same time the timer is ready to fire - if (!_sessionInProgress) - { - [self _checkForUpdatesInBackground]; + if (!_sessionInProgress) { + [self _checkForUpdatesInBackgroundForcingUIUpdateDriver:NO]; } } -- (void)_checkForUpdatesInBackground SPU_OBJC_DIRECT +- (void)_checkForUpdatesInBackgroundForcingUIUpdateDriver:(BOOL)forcesUIUpdateDriver SPU_OBJC_DIRECT { [self setSessionInProgress:YES]; [self setCanCheckForUpdates:NO]; @@ -618,15 +594,29 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification } id delegate = strongSelf->_delegate; - id updateDriver; - if (!installerIsRunning && [strongSelf automaticallyDownloadsUpdates] && strongSelf->_resumableUpdate == nil) { + id updateDriver = nil; + BOOL usesAutomaticUpdateDriver; + if (forcesUIUpdateDriver) { + usesAutomaticUpdateDriver = NO; + } else { + usesAutomaticUpdateDriver = [strongSelf automaticallyDownloadsUpdates]; + } + + if (usesAutomaticUpdateDriver) { + if ([strongSelf->_updateLastImpatientCheckedDate timeIntervalSinceNow] > 0) { + // Last impatient checked date is bogus (in the future), reset it + strongSelf->_updateLastImpatientCheckedDate = [NSDate date]; + } + updateDriver = [[SPUAutomaticUpdateDriver alloc] initWithHost:strongSelf->_host applicationBundle:strongSelf->_applicationBundle updater:strongSelf userDriver:strongSelf->_userDriver - updaterDelegate:delegate]; + updaterDelegate:delegate + impatientUpdateCheckInterval:strongSelf->_updaterSettings.impatientUpdateCheckInterval + lastImpatientCheckedDate:strongSelf->_updateLastImpatientCheckedDate]; } else { updateDriver = [[SPUScheduledUpdateDriver alloc] @@ -637,7 +627,7 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification updaterDelegate:delegate]; } - [strongSelf checkForUpdatesWithDriver:updateDriver updateCheck:SPUUpdateCheckUpdatesInBackground installerInProgress:installerIsRunning]; + [strongSelf checkForUpdatesWithDriver:updateDriver updateCheck:SPUUpdateCheckUpdatesInBackground installerInProgress:installerIsRunning usesAutomaticUpdateDriver:usesAutomaticUpdateDriver]; }); }]; } @@ -678,7 +668,7 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification } } - [self _checkForUpdatesInBackground]; + [self _checkForUpdatesInBackgroundForcingUIUpdateDriver:NO]; } - (void)checkForUpdates @@ -732,7 +722,7 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification dispatch_async(dispatch_get_main_queue(), ^{ __typeof__(self) strongSelf = weakSelf; if (strongSelf != nil) { - [strongSelf checkForUpdatesWithDriver:theUpdateDriver updateCheck:SPUUpdateCheckUpdates installerInProgress:installerInProgress]; + [strongSelf checkForUpdatesWithDriver:theUpdateDriver updateCheck:SPUUpdateCheckUpdates installerInProgress:installerInProgress usesAutomaticUpdateDriver:NO]; } }); }]; @@ -771,16 +761,16 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification dispatch_async(dispatch_get_main_queue(), ^{ __typeof__(self) strongSelf = weakSelf; if (strongSelf != nil) { - [strongSelf checkForUpdatesWithDriver:[[SPUProbingUpdateDriver alloc] initWithHost:strongSelf->_host updater:strongSelf updaterDelegate:strongSelf->_delegate] updateCheck:SPUUpdateCheckUpdateInformation installerInProgress:installerInProgress]; + [strongSelf checkForUpdatesWithDriver:[[SPUProbingUpdateDriver alloc] initWithHost:strongSelf->_host updater:strongSelf updaterDelegate:strongSelf->_delegate] updateCheck:SPUUpdateCheckUpdateInformation installerInProgress:installerInProgress usesAutomaticUpdateDriver:NO]; } }); }]; } -- (void)checkForUpdatesWithDriver:(id )d updateCheck:(SPUUpdateCheck)updateCheck installerInProgress:(BOOL)installerInProgress SPU_OBJC_DIRECT +- (void)checkForUpdatesWithDriver:(id )d updateCheck:(SPUUpdateCheck)updateCheck installerInProgress:(BOOL)installerInProgress usesAutomaticUpdateDriver:(BOOL)usesAutomaticUpdateDriver SPU_OBJC_DIRECT { if (_driver != nil) { - SULog(SULogLevelError, @"Error: checkForUpdatesWithDriver:updateCheck:installerInProgress: called when _driver != nil"); + SULog(SULogLevelError, @"Error: checkForUpdatesWithDriver:updateCheck:installerInProgress:usesAutomaticUpdateDriver: called when _driver != nil"); return; } @@ -814,7 +804,7 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification void (^abortUpdateDriver)(NSError * _Nullable , BOOL) = ^(NSError * _Nullable abortError, BOOL shouldScheduleNextUpdateCheck) { __weak __typeof__(self) weakSelf = self; - [self->_driver setCompletionHandler:^(BOOL __unused shouldShowUpdateImmediately, id _Nullable __unused resumableUpdate, NSError * _Nullable error) { + [self->_driver setCompletionHandler:^(BOOL __unused shouldShowUpdateImmediately, BOOL __unused resumedExistingUpdate, id _Nullable __unused resumableUpdate, NSError * _Nullable error) { __typeof__(self) strongSelf = weakSelf; if (strongSelf != nil) { strongSelf->_driver = nil; @@ -829,7 +819,7 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification // Ensure the delegate doesn't start a new session when being notified of the previous one ending if (!strongSelf->_sessionInProgress) { if (shouldScheduleNextUpdateCheck) { - [strongSelf scheduleNextUpdateCheckFiringImmediately:NO usingCurrentDate:NO]; + [strongSelf scheduleNextUpdateCheckFiringImmediately:NO usingCurrentDate:NO forcingUIUpdateDriver:NO]; } else { SULog(SULogLevelDefault, @"Disabling scheduled updates.."); } @@ -866,14 +856,21 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification // Run our update driver and schedule next update check on its completion __weak __typeof__(self) weakSelf = self; - [_driver setCompletionHandler:^(BOOL shouldShowUpdateImmediately, id _Nullable resumableUpdate, NSError * _Nullable error) { + [_driver setCompletionHandler:^(BOOL shouldShowUpdateImmediately, BOOL resumedExistingUpdate, id _Nullable resumableUpdate, NSError * _Nullable error) { __typeof__(self) strongSelf = weakSelf; if (strongSelf != nil) { strongSelf->_resumableUpdate = resumableUpdate; - strongSelf->_driver = nil; - + [strongSelf updateLastUpdateCheckDate]; + // Track the last downloaded date locally the first time the automatic update driver + // downloads an update in the background. This is later used for the impatient update check. + if (!shouldShowUpdateImmediately && error == nil && usesAutomaticUpdateDriver && !resumedExistingUpdate) { + strongSelf->_updateLastImpatientCheckedDate = [strongSelf lastUpdateCheckDate]; + } + + strongSelf->_driver = nil; + [strongSelf setSessionInProgress:NO]; [strongSelf setCanCheckForUpdates:YES]; @@ -886,7 +883,7 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification // Ensure the delegate doesn't start a new session when being notified of the previous one ending if (!strongSelf->_sessionInProgress) { - [strongSelf scheduleNextUpdateCheckFiringImmediately:shouldShowUpdateImmediately usingCurrentDate:NO]; + [strongSelf scheduleNextUpdateCheckFiringImmediately:shouldShowUpdateImmediately usingCurrentDate:NO forcingUIUpdateDriver:shouldShowUpdateImmediately]; } } }]; @@ -901,21 +898,21 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification [weakSelf updateLastUpdateCheckDate]; }]; - if (installerInProgress) { - // Resume an update that has already begun installing in the background - [_driver resumeInstallingUpdate]; - } else if (_resumableUpdate != nil) { - // Resume an update or info that has already been downloaded - [_driver resumeUpdate:(id _Nonnull)_resumableUpdate]; + // Check that the parameterized feed URL is valid + NSURL *theFeedURL = [self parameterizedFeedURL]; + if (theFeedURL == nil) { + // I think this is really unlikely to occur but better be safe + // We will not schedule a next update check if the feed URL cannot be formed + SULog(SULogLevelError, @"Error: failed to retrieve feed URL for bundle"); + + abortUpdateDriver([NSError errorWithDomain:SUSparkleErrorDomain code:SUInvalidFeedURLError userInfo:@{ NSLocalizedDescriptionKey: @"Sparkle cannot form a valid feed URL." }], NO); } else { - // Check that the parameterized feed URL is valid - NSURL *theFeedURL = [self parameterizedFeedURL]; - if (theFeedURL == nil) { - // I think this is really unlikely to occur but better be safe - // We will not schedule a next update check if the feed URL cannot be formed - SULog(SULogLevelError, @"Error: failed to retrieve feed URL for bundle"); - - abortUpdateDriver([NSError errorWithDomain:SUSparkleErrorDomain code:SUInvalidFeedURLError userInfo:@{ NSLocalizedDescriptionKey: @"Sparkle cannot form a valid feed URL." }], NO); + if (installerInProgress) { + // Resume an update that has already begun installing in the background + [_driver resumeInstallingUpdateOrCheckForUpdatesAtAppcastURL:theFeedURL withUserAgent:_userAgentString httpHeaders:_httpHeaders]; + } else if (_resumableUpdate != nil) { + // Resume an update or info that has already been downloaded + [_driver resumeUpdate:(id _Nonnull)_resumableUpdate orCheckForUpdatesAtAppcastURL:theFeedURL withUserAgent:_userAgentString httpHeaders:_httpHeaders]; } else { // Check for new updates [_driver checkForUpdatesAtAppcastURL:theFeedURL withUserAgent:_userAgentString httpHeaders:_httpHeaders]; @@ -982,7 +979,7 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification } } - [self scheduleNextUpdateCheckFiringImmediately:fireUpdateCheckImmediately usingCurrentDate:YES]; + [self scheduleNextUpdateCheckFiringImmediately:fireUpdateCheckImmediately usingCurrentDate:YES forcingUIUpdateDriver:NO]; } } diff --git a/Sparkle/SPUUpdaterTimer.m b/Sparkle/SPUUpdaterTimer.m index dd20f887..5a1a2c02 100644 --- a/Sparkle/SPUUpdaterTimer.m +++ b/Sparkle/SPUUpdaterTimer.m @@ -17,6 +17,8 @@ dispatch_source_t _source; __weak id _delegate; + + NSUInteger _timerGeneration; } - (instancetype)initWithDelegate:(id)delegate @@ -37,11 +39,15 @@ dispatch_time_t timeToFire = dispatch_walltime(NULL, (int64_t)(delay * NSEC_PER_SEC)); dispatch_source_set_timer(_source, timeToFire, DISPATCH_TIME_FOREVER, leewayUpdateCheckInterval * NSEC_PER_SEC); + _timerGeneration++; + NSUInteger currentTimerGeneration = _timerGeneration; __weak __typeof__(self) weakSelf = self; dispatch_source_set_event_handler(_source, ^{ __typeof__(self) strongSelf = weakSelf; if (strongSelf != nil) { - [strongSelf->_delegate updaterTimerDidFire]; + if (strongSelf->_timerGeneration == currentTimerGeneration) { + [strongSelf->_delegate updaterTimerDidFire]; + } } }); @@ -53,6 +59,7 @@ if (_source != nil) { dispatch_source_cancel(_source); _source = nil; + _timerGeneration++; } } diff --git a/Sparkle/SPUUserDriver.h b/Sparkle/SPUUserDriver.h index d2cd3cab..cd7a95e5 100644 --- a/Sparkle/SPUUserDriver.h +++ b/Sparkle/SPUUserDriver.h @@ -291,7 +291,7 @@ SU_EXPORT NS_SWIFT_UI_ACTOR @protocol SPUUserDriver - (void)showUpdateInstallationDidFinishWithAcknowledgement:(void (^)(void))acknowledgement __deprecated_msg("Implement -showUpdateInstalledAndRelaunched:acknowledgement: instead"); -- (void)dismissUserInitiatedUpdateCheck __deprecated_msg("Transition to new UI appropriately when a new update is shown, when no update is found, or when an update error occurs."); +- (void)dismissUserInitiatedUpdateCheck __deprecated_msg("Transition to new UI appropriately when a new update is shown, when no update is found, or when an update error occurs. This method is no longer called."); - (void)showInstallingUpdate __deprecated_msg("Implement -showInstallingUpdateWithApplicationTerminated:retryTerminatingApplication: instead."); diff --git a/Sparkle/SPUUserInitiatedUpdateDriver.m b/Sparkle/SPUUserInitiatedUpdateDriver.m index caeb257b..400d3bbb 100644 --- a/Sparkle/SPUUserInitiatedUpdateDriver.m +++ b/Sparkle/SPUUserInitiatedUpdateDriver.m @@ -56,7 +56,7 @@ [_uiDriver setUpdateWillInstallHandler:updateWillInstallHandler]; } -- (void)checkForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders +- (void)_showUserInitiatedProgress { _showingUserInitiatedProgress = YES; @@ -72,18 +72,27 @@ } }); }]; - +} + +- (void)checkForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders +{ + [self _showUserInitiatedProgress]; + [_uiDriver checkForUpdatesAtAppcastURL:appcastURL withUserAgent:userAgent httpHeaders:httpHeaders inBackground:NO]; } -- (void)resumeInstallingUpdate +- (void)resumeInstallingUpdateOrCheckForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders { - [_uiDriver resumeInstallingUpdate]; + [self _showUserInitiatedProgress]; + + [_uiDriver resumeInstallingUpdateOrCheckForUpdatesAtAppcastURL:appcastURL withUserAgent:userAgent httpHeaders:httpHeaders inBackground:NO]; } -- (void)resumeUpdate:(id)resumableUpdate +- (void)resumeUpdate:(id)resumableUpdate orCheckForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders { - [_uiDriver resumeUpdate:resumableUpdate]; + [self _showUserInitiatedProgress]; + + [_uiDriver resumeUpdate:resumableUpdate orCheckForUpdatesAtAppcastURL:appcastURL withUserAgent:userAgent httpHeaders:httpHeaders inBackground:NO]; } - (void)uiDriverDidShowUpdate @@ -113,19 +122,6 @@ [self abortUpdateWithError:error]; } -- (void)basicDriverDidFinishLoadingAppcast -{ - if (_showingUserInitiatedProgress) { - _showingUserInitiatedProgress = NO; -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdeprecated-declarations" - if ([_userDriver respondsToSelector:@selector(dismissUserInitiatedUpdateCheck)]) { - [_userDriver dismissUserInitiatedUpdateCheck]; - } -#pragma clang diagnostic pop - } -} - - (void)abortUpdate { [self abortUpdateWithError:nil]; @@ -133,15 +129,7 @@ - (void)abortUpdateWithError:(nullable NSError *)error { - if (_showingUserInitiatedProgress) { -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdeprecated-declarations" - if ([_userDriver respondsToSelector:@selector(dismissUserInitiatedUpdateCheck)]) { - [_userDriver dismissUserInitiatedUpdateCheck]; - } -#pragma clang diagnostic pop - _showingUserInitiatedProgress = NO; - } + _showingUserInitiatedProgress = NO; _aborted = YES; [_uiDriver abortUpdateWithError:error showErrorToUser:YES]; } diff --git a/Sparkle/SUAppcastDriver.h b/Sparkle/SUAppcastDriver.h index 5f033a7b..4dc482f0 100644 --- a/Sparkle/SUAppcastDriver.h +++ b/Sparkle/SUAppcastDriver.h @@ -33,7 +33,7 @@ SUAppcastDriverDefinitionAttribute - (instancetype)initWithHost:(SUHost *)host updater:(id)updater updaterDelegate:(nullable id )updaterDelegate delegate:(nullable id )delegate; -- (void)loadAppcastFromURL:(NSURL *)appcastURL userAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders inBackground:(BOOL)background; +- (void)loadAppcastFromURL:(NSURL *)appcastURL userAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders inBackground:(BOOL)background resumingUpdate:(BOOL)resumingUpdate; - (void)cleanup:(void (^)(void))completionHandler; diff --git a/Sparkle/SUAppcastDriver.m b/Sparkle/SUAppcastDriver.m index dd8af88b..a9bdfa73 100644 --- a/Sparkle/SUAppcastDriver.m +++ b/Sparkle/SUAppcastDriver.m @@ -65,7 +65,7 @@ return self; } -- (void)loadAppcastFromURL:(NSURL *)appcastURL userAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders inBackground:(BOOL)background +- (void)loadAppcastFromURL:(NSURL *)appcastURL userAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders inBackground:(BOOL)background resumingUpdate:(BOOL)resumingUpdate { assert(NSThread.isMainThread); @@ -76,12 +76,18 @@ requestHTTPHeaders[@"Accept"] = @"application/rss+xml,*/*;q=0.1"; NSURLRequestCachePolicy cachePolicy; - if (!background || [_host boolForInfoDictionaryKey:SUDisableFeedCacheValidationKey]) { - // Always fetch the freshest feed when the user explicitly asks us to check, - // or if the developer disabled feed cache validation + if ([_host boolForInfoDictionaryKey:SUDisableFeedCacheValidationKey]) { + // The developer disabled feed cache validation + cachePolicy = NSURLRequestReloadIgnoringLocalCacheData; + } else if (resumingUpdate) { + // We already have an update downloaded or installing that we can fall back to resuming, + // so we will risk always respecting the cache + cachePolicy = NSURLRequestReloadRevalidatingCacheData; + } else if (!background) { + // Always fetch the freshest feed when the user explicitly asks us to check cachePolicy = NSURLRequestReloadIgnoringLocalCacheData; } else { - // With NSURLRequestReloadRevalidatingCacheData ETag / If-Modified-Since can be used so that + // With NSURLRequestReloadRevalidatingCacheData, ETag / If-Modified-Since can be used so that // a previously cached file can be used if it hasn't changed on the server. // However we have a bypass check interval periodically to force ignoring the cache data if // something happens to go wrong. diff --git a/TestApplication/SUTestApplicationDelegate.m b/TestApplication/SUTestApplicationDelegate.m index 77ed569b..1204ac37 100644 --- a/TestApplication/SUTestApplicationDelegate.m +++ b/TestApplication/SUTestApplicationDelegate.m @@ -24,6 +24,8 @@ SUUpdateSettingsWindowController *_updateSettingsWindowController; SUTestWebServer *_webServer; NSString *_testMode; + + BOOL _supersedeFoundInitialUpdate; } - (void)applicationDidFinishLaunching:(NSNotification * __unused)notification @@ -43,7 +45,7 @@ // Check if we are already up to date NSString *mainBundleVersion = (NSString *)[mainBundle objectForInfoDictionaryKey:(__bridge NSString *)kCFBundleVersionKey]; - if (([mainBundleVersion hasPrefix:@"2."] && [testMode isEqualToString:@"REGULAR"]) || (([mainBundleVersion isEqualToString:@"2.1"] || [mainBundleVersion isEqualToString:@"2.2"]) && [testMode isEqualToString:@"DELTA_AND_MARKDOWN"]) || ([mainBundleVersion isEqualToString:@"2.2"] && [testMode isEqualToString:@"AUTOMATIC"])) { + if (([mainBundleVersion hasPrefix:@"2."] && [testMode isEqualToString:@"REGULAR"]) || (([mainBundleVersion isEqualToString:@"2.1"] || [mainBundleVersion isEqualToString:@"2.2"]) && [testMode isEqualToString:@"DELTA_AND_MARKDOWN"]) || ([mainBundleVersion isEqualToString:@"2.2"] && [testMode isEqualToString:@"AUTOMATIC"]) || ([mainBundleVersion isEqualToString:@"3.1"] && [testMode isEqualToString:@"SUPERSEDE"])) { NSAlert *alreadyUpdatedAlert = [[NSAlert alloc] init]; alreadyUpdatedAlert.messageText = @"Update succeeded!"; alreadyUpdatedAlert.informativeText = @"This is the updated version of Sparkle Test App.\n\nDelete and rebuild the app to test updates again."; @@ -52,9 +54,12 @@ [[NSApplication sharedApplication] terminate:nil]; } -#if SPARKLE_BUILD_UI_BITS // Detect as early as possible if the shift key is held down - BOOL shiftKeyHeldDown = ([NSEvent modifierFlags] & NSEventModifierFlagShift) != 0; + BOOL shiftKeyHeldDown; +#if SPARKLE_BUILD_UI_BITS + shiftKeyHeldDown = ([NSEvent modifierFlags] & NSEventModifierFlagShift) != 0; +#else + shiftKeyHeldDown = NO; #endif NSFileManager *fileManager = [NSFileManager defaultManager]; @@ -70,7 +75,7 @@ NSString *bundleIdentifier = mainBundle.bundleIdentifier; assert(bundleIdentifier != nil); - + // Create a directory that'll be used for our web server listing NSURL *serverDirectoryURL = [[cacheDirectoryURL URLByAppendingPathComponent:bundleIdentifier] URLByAppendingPathComponent:@"ServerData"]; if ([serverDirectoryURL checkResourceIsReachableAndReturnError:nil]) { @@ -114,6 +119,9 @@ finalUpdatedVersion = @"2.1"; } else if ([testMode isEqualToString:@"AUTOMATIC"]) { finalUpdatedVersion = @"2.2"; + } else if ([testMode isEqualToString:@"SUPERSEDE"]) { + // This is the initial version which will later be superseded by 3.1 + finalUpdatedVersion = @"3.0"; } else { assert(false); } @@ -175,10 +183,10 @@ // Don't ever do this at home, kids (seriously) // (that is, including the private key inside of your application) - const unsigned char self_sign_demo_only_insecure_hack[64] = {200, 238, 135, 84, 10, 189, 3, 193, 61, 208, 203, 30, 133, 47, 12, 22, 19, 52, 252, 99, 110, 205, 209, 94, 215, 144, 201, 70, 27, 162, 163, 108, 0, 164, 68, 184, 226, 93, 121, 199, 172, 17, 26, 64, 89, 68, 232, 41, 2, 26, 245, 175, 158, 165, 42, 55, 5, 97, 8, 243, 251, 164, 93, 9}; + static const unsigned char self_sign_demo_only_insecure_hack[64] = {200, 238, 135, 84, 10, 189, 3, 193, 61, 208, 203, 30, 133, 47, 12, 22, 19, 52, 252, 99, 110, 205, 209, 94, 215, 144, 201, 70, 27, 162, 163, 108, 0, 164, 68, 184, 226, 93, 121, 199, 172, 17, 26, 64, 89, 68, 232, 41, 2, 26, 245, 175, 158, 165, 42, 55, 5, 97, 8, 243, 251, 164, 93, 9}; // in normal app this goes to Info.plist - const unsigned char public_key[32] = {121, 17, 79, 45, 155, 141, 51, 169, 188, 110, 91, 102, 182, 147, 215, 225, 252, 202, 110, 231, 200, 215, 62, 171, 40, 145, 237, 128, 130, 44, 150, 89}; - unsigned char signature[64]; + static const unsigned char public_key[32] = {121, 17, 79, 45, 155, 141, 51, 169, 188, 110, 91, 102, 182, 147, 215, 225, 252, 202, 110, 231, 200, 215, 62, 171, 40, 145, 237, 128, 130, 44, 150, 89}; + unsigned char signature[64] = {0}; if ([testMode isEqualToString:@"DELTA_AND_MARKDOWN"]) { NSError *deltaCreationError = nil; @@ -232,6 +240,121 @@ NSLog(@"Failed to write updated appcast with error %@", writeAppcastError); abort(); } + } else if ([testMode isEqualToString:@"SUPERSEDE"]) { + // Create the archive for the initial ("3.0") update from the bundle we already copied + // and signed above + NSString *zipName = @"Sparkle_Test_App.zip"; + NSTask *dittoTask = [[NSTask alloc] init]; + dittoTask.launchPath = @"/usr/bin/ditto"; + dittoTask.arguments = @[@"-c", @"-k", @"--sequesterRsrc", @"--keepParent", (NSString *)destinationBundleURL.lastPathComponent, zipName]; + dittoTask.currentDirectoryPath = serverDirectoryPath; + [dittoTask launch]; + [dittoTask waitUntilExit]; + + assert(dittoTask.terminationStatus == 0); + + [fileManager removeItemAtURL:destinationBundleURL error:NULL]; + + NSURL *archiveURL = [serverDirectoryURL URLByAppendingPathComponent:zipName]; + NSData *archive = [NSData dataWithContentsOfURL:archiveURL]; + assert(archive != nil); + + ed25519_sign(signature, (const unsigned char *)archive.bytes, archive.length, public_key, self_sign_demo_only_insecure_hack); + + NSString *signatureString = [[NSData dataWithBytes:signature length:64] base64EncodedStringWithOptions:(NSDataBase64EncodingOptions)0]; + + NSError *fileAttributesError = nil; + NSString *archiveURLPath = archiveURL.path; + assert(archiveURLPath != nil); + NSDictionary *archiveFileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:archiveURLPath error:&fileAttributesError]; + if (archiveFileAttributes == nil) { + NSLog(@"Failed to retrieve file attributes from archive with error %@", fileAttributesError); + abort(); + } + + NSUInteger numberOfSupercede1LengthReplacements = [appcastContents replaceOccurrencesOfString:@"$INSERT_SUPERCEDE1_ARCHIVE_LENGTH" withString:[NSString stringWithFormat:@"%llu", archiveFileAttributes.fileSize] options:NSLiteralSearch range:NSMakeRange(0, appcastContents.length)]; + assert(numberOfSupercede1LengthReplacements == 1); + + NSUInteger numberOfSupercede1SignatureReplacements = [appcastContents replaceOccurrencesOfString:@"$INSERT_SUPERCEDE1_EDDSA_SIGNATURE" withString:signatureString options:NSLiteralSearch range:NSMakeRange(0, appcastContents.length)]; + assert(numberOfSupercede1SignatureReplacements == 1); + + // Build a second copy of the bundle for the superseding ("3.1") update + NSURL *supersedingDestinationBundleURL = [serverDirectoryURL URLByAppendingPathComponent:@"Superseding.app"]; + NSError *copySupersedingBundleError = nil; + if (![fileManager copyItemAtURL:bundleURL toURL:supersedingDestinationBundleURL error:©SupersedingBundleError]) { + NSLog(@"Failed to copy bundle for superseding update with error %@", copySupersedingBundleError); + abort(); + } + + NSURL *supersedingInfoURL = [[supersedingDestinationBundleURL URLByAppendingPathComponent:@"Contents"] URLByAppendingPathComponent:@"Info.plist"]; + NSMutableDictionary *supersedingInfoDictionary = [[NSMutableDictionary alloc] initWithContentsOfURL:supersedingInfoURL]; + [supersedingInfoDictionary setObject:@"3.1" forKey:(__bridge NSString *)kCFBundleVersionKey]; + [supersedingInfoDictionary setObject:@"3.1" forKey:@"CFBundleShortVersionString"]; + BOOL wroteSupersedingInfoFile = [supersedingInfoDictionary writeToURL:supersedingInfoURL atomically:NO]; + assert(wroteSupersedingInfoFile); + + [self signApplicationIfRequiredAtPath:supersedingDestinationBundleURL.path completion:^{ + dispatch_async(dispatch_get_main_queue(), ^{ + NSString *supersedingZipName = @"Sparkle_Test_App_Superseding.zip"; + NSTask *supersedingDittoTask = [[NSTask alloc] init]; + supersedingDittoTask.launchPath = @"/usr/bin/ditto"; + supersedingDittoTask.arguments = @[@"-c", @"-k", @"--sequesterRsrc", @"--keepParent", (NSString *)supersedingDestinationBundleURL.lastPathComponent, supersedingZipName]; + supersedingDittoTask.currentDirectoryPath = serverDirectoryPath; + [supersedingDittoTask launch]; + [supersedingDittoTask waitUntilExit]; + + assert(supersedingDittoTask.terminationStatus == 0); + + [fileManager removeItemAtURL:supersedingDestinationBundleURL error:NULL]; + + NSURL *supersedingArchiveURL = [serverDirectoryURL URLByAppendingPathComponent:supersedingZipName]; + NSData *supersedingArchive = [NSData dataWithContentsOfURL:supersedingArchiveURL]; + assert(supersedingArchive != nil); + + unsigned char supersedingSignature[64] = {0}; + ed25519_sign(supersedingSignature, (const unsigned char *)supersedingArchive.bytes, supersedingArchive.length, public_key, self_sign_demo_only_insecure_hack); + NSString *supersedingSignatureString = [[NSData dataWithBytes:supersedingSignature length:64] base64EncodedStringWithOptions:(NSDataBase64EncodingOptions)0]; + + NSError *supersedingFileAttributesError = nil; + NSString *supersedingArchiveURLPath = supersedingArchiveURL.path; + assert(supersedingArchiveURLPath != nil); + NSDictionary *supersedingArchiveFileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:supersedingArchiveURLPath error:&supersedingFileAttributesError]; + if (supersedingArchiveFileAttributes == nil) { + NSLog(@"Failed to retrieve file attributes from superseding archive with error %@", supersedingFileAttributesError); + abort(); + } + + NSUInteger numberOfSupercede2LengthReplacements = [appcastContents replaceOccurrencesOfString:@"$INSERT_SUPERCEDE2_ARCHIVE_LENGTH" withString:[NSString stringWithFormat:@"%llu", supersedingArchiveFileAttributes.fileSize] options:NSLiteralSearch range:NSMakeRange(0, appcastContents.length)]; + assert(numberOfSupercede2LengthReplacements == 1); + + NSUInteger numberOfSupercede2SignatureReplacements = [appcastContents replaceOccurrencesOfString:@"$INSERT_SUPERCEDE2_EDDSA_SIGNATURE" withString:supersedingSignatureString options:NSLiteralSearch range:NSMakeRange(0, appcastContents.length)]; + assert(numberOfSupercede2SignatureReplacements == 1); + + NSRange feedSignaturesPrefixRange = [appcastContents rangeOfString:@"