diff --git a/Autoupdate/AppInstaller.h b/Autoupdate/AppInstaller.h index 64c999d8..25cf0e3a 100644 --- a/Autoupdate/AppInstaller.h +++ b/Autoupdate/AppInstaller.h @@ -17,6 +17,8 @@ SPU_OBJC_DIRECT_MEMBERS @interface AppInstaller : NSObject - (void)start; +- (void)handleTerminationRequest; + - (void)cleanupAndExitWithStatus:(int)status error:(NSError * _Nullable)error __attribute__((noreturn)); @end diff --git a/Autoupdate/AppInstaller.m b/Autoupdate/AppInstaller.m index 89b83879..0bafd7f6 100644 --- a/Autoupdate/AppInstaller.m +++ b/Autoupdate/AppInstaller.m @@ -45,6 +45,10 @@ */ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; +// This is slightly longer than SUTerminationRequestTargetWaitDelay in the installer progress app +// to give extra time to allow receiving the termination message and finishing installation +static const NSTimeInterval SUTerminationRequestTargetWaitDelay = 2.0; + @interface AppInstaller () @end @@ -103,6 +107,7 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; BOOL _performedStage3Installation; BOOL _targetTerminated; + BOOL _receivedTerminationRequest; } - (instancetype)initWithHostBundleIdentifier:(NSString *)hostBundleIdentifier homeDirectory:(NSString *)homeDirectory userName:(NSString *)userName @@ -382,6 +387,26 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; } } +- (void)handleTerminationRequest +{ + // When we receive a termination quit request do not clean up the update directory + // to reduce risk of removing something in the directory while the installer thread tries to install/swap + // an update bundle from there + if (_performedStage1Installation) { + if (!_receivedTerminationRequest) { + _receivedTerminationRequest = YES; + + // Give grace period before doing forceful exit, + // which may give some time to finish an app update installation. + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(SUTerminationRequestTargetWaitDelay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ + exit(SIGTERM); + }); + } + } else { + exit(SIGTERM); + } +} + - (void)agentConnectionDidInvalidate { if (!_finishedValidation || !_agentInitiatedConnection || !_targetTerminated) { diff --git a/Autoupdate/main.m b/Autoupdate/main.m index 70f2691c..012e32ee 100644 --- a/Autoupdate/main.m +++ b/Autoupdate/main.m @@ -28,11 +28,7 @@ int main(int __unused argc, const char __unused *argv[]) dispatch_source_t sigtermSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, SIGTERM, 0, dispatch_get_main_queue()); dispatch_source_set_event_handler(sigtermSource, ^{ - // Don't clear the update directory because the installer may be in middle of installing an update - // We still need to set an event handler for receiving SIGTERM though, otherwise our job may not terminate - // (This is also recommended from the developer documentation). - // Simply exit with SIGTERM if we receive this signal - exit(SIGTERM); + [appInstaller handleTerminationRequest]; }); dispatch_resume(sigtermSource); diff --git a/Sparkle/InstallerProgress/InstallerProgressAppController.h b/Sparkle/InstallerProgress/InstallerProgressAppController.h index 7cc32ea0..3f903110 100644 --- a/Sparkle/InstallerProgress/InstallerProgressAppController.h +++ b/Sparkle/InstallerProgress/InstallerProgressAppController.h @@ -18,6 +18,8 @@ SPU_OBJC_DIRECT_MEMBERS @interface InstallerProgressAppController : NSObject @end @@ -47,6 +51,7 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.3; __weak id _delegate; void (^_terminationCompletionHandler)(void); + dispatch_source_t _targetProcessExitSource; BOOL _connected; BOOL _repliedToRegistration; @@ -55,6 +60,8 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.3; BOOL _submittedLauncherJob; BOOL _willTerminate; BOOL _applicationInitiallyAlive; + BOOL _receivedTerminationRequest; + BOOL _targetProcessExited; } - (instancetype)initWithApplication:(NSApplication *)application arguments:(NSArray *)arguments delegate:(id)delegate @@ -172,6 +179,39 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.3; [self startConnection]; } +- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)__unused sender +{ + [self handleTerminationRequest]; + + return NSTerminateLater; +} + +- (void)handleTerminationRequest +{ + // Check if we're going to terminate anyway + if (_receivedTerminationRequest) { + return; + } + + // If Autoupdate installer is listening for termination completion, + // we will delay termination for a bit to allow us some time to observe + // the targetted app's termination, otherwise we will exit immediately + + if (_terminationCompletionHandler == nil) { + [self cleanupAndExitWithStatus:SIGTERM error:nil]; + } + + _receivedTerminationRequest = YES; + + if (_targetProcessExited) { + [self notifyTargetTermination]; + } + + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(SUTerminationRequestTargetWaitDelay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ + [self cleanupAndExitWithStatus:SIGTERM error:nil]; + }); +} + - (void)cleanupAndExitWithStatus:(int)status error:(NSError * _Nullable)error __attribute__((noreturn)) { if (error != nil) { @@ -315,17 +355,49 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.3; NSString *isTerminatedKeyPath = NSStringFromSelector(@selector(isTerminated)); if ([keyPath isEqualToString:isTerminatedKeyPath]) { if (_targetRunningApplication.terminated && _terminationCompletionHandler != nil) { - _terminationCompletionHandler(); - - [_targetRunningApplication removeObserver:self forKeyPath:isTerminatedKeyPath]; - _terminationCompletionHandler = nil; - _targetRunningApplication = nil; + [self notifyTargetTermination]; } } else { [super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; } } +- (void)notifyTargetTermination SPU_OBJC_DIRECT +{ + if (_terminationCompletionHandler == nil) { + return; + } + + _terminationCompletionHandler(); + _terminationCompletionHandler = nil; + + [_targetRunningApplication removeObserver:self forKeyPath:NSStringFromSelector(@selector(isTerminated))]; + _targetRunningApplication = nil; + + if (_targetProcessExitSource != nil) { + dispatch_source_cancel(_targetProcessExitSource); + _targetProcessExitSource = nil; + } +} + +- (void)targetProcessDidExit SPU_OBJC_DIRECT +{ + if (_targetProcessExited) { + return; + } + + _targetProcessExited = YES; + + if (_targetProcessExitSource != nil) { + dispatch_source_cancel(_targetProcessExitSource); + _targetProcessExitSource = nil; + } + + if (_receivedTerminationRequest && _terminationCompletionHandler != nil) { + [self notifyTargetTermination]; + } +} + - (void)listenForTerminationWithCompletion:(void (^)(void))completionHandler { dispatch_async(dispatch_get_main_queue(), ^{ @@ -342,6 +414,23 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.3; self->_terminationCompletionHandler = [completionHandler copy]; [self->_targetRunningApplication addObserver:self forKeyPath:NSStringFromSelector(@selector(isTerminated)) options:NSKeyValueObservingOptionNew context:NULL]; + + pid_t targetProcessIdentifier = self->_targetRunningApplication.processIdentifier; + if (targetProcessIdentifier > 0) { + dispatch_source_t targetProcessExitSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_PROC, (uintptr_t)targetProcessIdentifier, DISPATCH_PROC_EXIT, dispatch_get_main_queue()); + if (targetProcessExitSource != nil) { + self->_targetProcessExitSource = targetProcessExitSource; + + dispatch_source_set_event_handler(targetProcessExitSource, ^{ + [self targetProcessDidExit]; + }); + dispatch_resume(targetProcessExitSource); + + if (kill(targetProcessIdentifier, 0) != 0 && errno == ESRCH) { + [self targetProcessDidExit]; + } + } + } } } else { SULog(SULogLevelError, @"Error: -listenForTerminationWithCompletion: called in unexpected state"); @@ -381,7 +470,7 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.3; - (void)relaunchApplication { dispatch_async(dispatch_get_main_queue(), ^{ - if (!self->_willTerminate && self->_applicationBundle != nil && self->_applicationInitiallyAlive) { + if (!self->_willTerminate && !self->_receivedTerminationRequest && self->_applicationBundle != nil && self->_applicationInitiallyAlive) { NSString *pathToRelaunch; if (self->_normalizedPath != nil) { pathToRelaunch = self->_normalizedPath; @@ -417,7 +506,7 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.3; - (void)showProgress { dispatch_async(dispatch_get_main_queue(), ^{ - if (!self->_willTerminate) { + if (!self->_willTerminate && !self->_receivedTerminationRequest) { // Activate ourselves otherwise we will probably be in the background // See comments in -[SPUStandardUserDriver _activateApplication] for why -activate is not used [self->_application activateIgnoringOtherApps:YES]; diff --git a/Sparkle/InstallerProgress/main.m b/Sparkle/InstallerProgress/main.m index a387986c..59a3c686 100644 --- a/Sparkle/InstallerProgress/main.m +++ b/Sparkle/InstallerProgress/main.m @@ -27,7 +27,7 @@ int main(int __unused argc, const char __unused *argv[]) dispatch_source_t sigtermSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, SIGTERM, 0, dispatch_get_main_queue()); dispatch_source_set_event_handler(sigtermSource, ^{ - [appController cleanupAndExitWithStatus:SIGTERM error:nil]; + [appController handleTerminationRequest]; }); dispatch_resume(sigtermSource); diff --git a/Sparkle/SPUInstallerDriver.h b/Sparkle/SPUInstallerDriver.h index 522d9bf9..cebfa745 100644 --- a/Sparkle/SPUInstallerDriver.h +++ b/Sparkle/SPUInstallerDriver.h @@ -33,6 +33,8 @@ SPU_OBJC_DIRECT_MEMBERS @interface SPUInstallerDriver : NSObject - (void)resumeInstallingUpdateWithUpdateItem:(SUAppcastItem *)updateItem systemDomain:(BOOL)systemDomain; +- (void)cancelSupersededInstallerBeforeLaunching; + - (void)setUpdateWillInstallHandler:(void (^)(void))updateWillInstallHandler; - (void)extractDownloadedUpdate:(SPUDownloadedUpdate *)downloadedUpdate silently:(BOOL)silently completion:(void (^)(NSError * _Nullable))completionHandler; diff --git a/Sparkle/SPUInstallerDriver.m b/Sparkle/SPUInstallerDriver.m index fa7b452a..1e9156bf 100644 --- a/Sparkle/SPUInstallerDriver.m +++ b/Sparkle/SPUInstallerDriver.m @@ -32,6 +32,7 @@ #include "AppKitPrevention.h" #define FIRST_INSTALLER_MESSAGE_TIMEOUT 7ull +#define CANCEL_SUPERSEDED_INSTALLER_TIMEOUT 3ull #if SPARKLE_BUILD_LEGACY_SUUPDATER @interface NSObject (PrivateDelegateMethods) @@ -66,6 +67,7 @@ BOOL _systemDomain; BOOL _aborted; BOOL _notifiedDelegateInstallationWillFinish; + BOOL _cancelSupersededInstaller; } - (instancetype)initWithHost:(SUHost *)host applicationBundle:(NSBundle *)applicationBundle updater:(id)updater updaterDelegate:(id)updaterDelegate delegate:(nullable id)delegate @@ -147,26 +149,38 @@ [_delegate installerIsRequestingAbortInstallWithError:installerError]; } +- (id)createInstallerConnectionAndGetServiceName:(NSString * __autoreleasing *)outServiceName SPU_OBJC_DIRECT +{ + NSString *hostBundleIdentifier = _host.bundle.bundleIdentifier; + assert(hostBundleIdentifier != nil); + + id installerConnection; +#if INSTALLER_CONNECTION_XPC_SERVICE_EMBEDDED + if (SPUXPCServiceIsEnabled(SUEnableInstallerConnectionServiceKey)) { + installerConnection = [[SUXPCInstallerConnection alloc] initWithDelegate:self]; + } else +#endif + { + installerConnection = [[SUInstallerConnection alloc] initWithDelegate:self remote:NO]; + } + + if (outServiceName != NULL) { + *outServiceName = SPUInstallerServiceNameForBundleIdentifier(hostBundleIdentifier); + } + return installerConnection; +} + - (void)setUpConnection SPU_OBJC_DIRECT { if (_installerConnection != nil) { return; } - NSString *hostBundleIdentifier = _host.bundle.bundleIdentifier; - assert(hostBundleIdentifier != nil); + NSString *serviceName = nil; + _installerConnection = [self createInstallerConnectionAndGetServiceName:&serviceName]; - BOOL usingInstallerService; -#if INSTALLER_CONNECTION_XPC_SERVICE_EMBEDDED - if (SPUXPCServiceIsEnabled(SUEnableInstallerConnectionServiceKey)) { - _installerConnection = [[SUXPCInstallerConnection alloc] initWithDelegate:self]; - usingInstallerService = YES; - } else -#endif - { - _installerConnection = [[SUInstallerConnection alloc] initWithDelegate:self remote:NO]; - usingInstallerService = NO; - } + // Check if we're using remote SUXPCInstallerConnection for diagnostic purposes + BOOL usingInstallerService = ![(id)_installerConnection isKindOfClass:SUInstallerConnection.class]; __weak __typeof__(self) weakSelf = self; [_installerConnection setInvalidationHandler:^{ @@ -195,7 +209,6 @@ }); }]; - NSString *serviceName = SPUInstallerServiceNameForBundleIdentifier(hostBundleIdentifier); NSString *installationType = _updateItem.installationType; assert(installationType != nil); @@ -211,7 +224,15 @@ _currentStage = SPUInstallerNotStarted; if (_installerConnection == nil) { - [self launchAutoUpdateSilently:silently completion:completionHandler]; + if (_cancelSupersededInstaller) { + _cancelSupersededInstaller = NO; + + [self cancelSupersededInstallerWithCompletion:^{ + [self launchAutoUpdateSilently:silently completion:completionHandler]; + }]; + } else { + [self launchAutoUpdateSilently:silently completion:completionHandler]; + } } else { // The Install tool is already alive; just send out installation input data again [self sendInstallationData]; @@ -225,6 +246,35 @@ _systemDomain = systemDomain; } +- (void)cancelSupersededInstallerBeforeLaunching +{ + _cancelSupersededInstaller = YES; +} + +- (void)cancelSupersededInstallerWithCompletion:(void (^)(void))completionHandler SPU_OBJC_DIRECT +{ + NSString *serviceName = nil; + id installerConnection = [self createInstallerConnectionAndGetServiceName:&serviceName]; + + __block BOOL completed = NO; + void (^completeCancellation)(void) = ^{ + if (!completed) { + completed = YES; + [installerConnection invalidate]; + completionHandler(); + } + }; + + [installerConnection setInvalidationHandler:^{ + dispatch_async(dispatch_get_main_queue(), completeCancellation); + }]; + + [installerConnection setServiceName:serviceName systemDomain:_systemDomain]; + [installerConnection handleMessageWithIdentifier:SPUCancelInstallation data:[NSData data]]; + + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(CANCEL_SUPERSEDED_INSTALLER_TIMEOUT * NSEC_PER_SEC)), dispatch_get_main_queue(), completeCancellation); +} + - (void)sendInstallationData SPU_OBJC_DIRECT { NSString *pathToRelaunch = _applicationBundle.bundlePath; diff --git a/Sparkle/SPUUpdateDriver.m b/Sparkle/SPUUpdateDriver.m index f3bb289b..7ec8b19f 100644 --- a/Sparkle/SPUUpdateDriver.m +++ b/Sparkle/SPUUpdateDriver.m @@ -361,8 +361,7 @@ static BOOL SPUUpdateRequiresUserAttentionBeforeDownloading(SUAppcastItem *updat return; } - // No need to discard the prior resumable installed update. - // The update will be discarded when we submit new installer job + [_installerDriver cancelSupersededInstallerBeforeLaunching]; } else if (_resumableLocalUpdate != nil) { if (![self pendingUpdateItem:_resumableLocalUpdate.updateItem isSupersededByUpdateItem:updateItem]) { [self notifyFoundValidUpdateWithAppcastItem:_resumableLocalUpdate.updateItem secondaryAppcastItem:_resumableLocalUpdate.secondaryUpdateItem systemDomain:nil resumingExistingUpdate:YES];