From b3e7a03660171334a5bcf604fe712b838a530e1d Mon Sep 17 00:00:00 2001 From: Zorg Date: Fri, 19 Mar 2021 18:53:53 -0700 Subject: [PATCH] Update and replace bundle directories even more atomically on apfs With these changes, it should not be possible for neither an old or new bundle to be at the destination. We also perform temporary directory cleanup after final installation stage is and relaunching an app is performed because we can save some time (150 ms+ in one of my cases). --- Autoupdate/AppInstaller.m | 3 + Autoupdate/SUGuidedPackageInstaller.m | 4 + Autoupdate/SUInstallerProtocol.h | 6 ++ Autoupdate/SUPackageInstaller.m | 4 + Autoupdate/SUPlainInstaller.m | 139 ++++++++++++++++---------- Sparkle/SUFileManager.h | 13 +++ Sparkle/SUFileManager.m | 31 ++++++ 7 files changed, 145 insertions(+), 55 deletions(-) diff --git a/Autoupdate/AppInstaller.m b/Autoupdate/AppInstaller.m index 03839d82..2513b031 100644 --- a/Autoupdate/AppInstaller.m +++ b/Autoupdate/AppInstaller.m @@ -552,6 +552,7 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; NSError *thirdStageError = nil; if (![self.installer performFinalInstallationProgressBlock:nil error:&thirdStageError]) { + [self.installer performCleanup]; self.installer = nil; dispatch_async(dispatch_get_main_queue(), ^{ @@ -585,6 +586,8 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; [self.agentConnection.agent relaunchPath:pathToRelaunch]; } + [self.installer performCleanup]; + [self cleanupAndExitWithStatus:EXIT_SUCCESS error:nil]; }); }); diff --git a/Autoupdate/SUGuidedPackageInstaller.m b/Autoupdate/SUGuidedPackageInstaller.m index cd43bbf4..402e8aff 100644 --- a/Autoupdate/SUGuidedPackageInstaller.m +++ b/Autoupdate/SUGuidedPackageInstaller.m @@ -70,6 +70,10 @@ return success; } +- (void)performCleanup +{ +} + - (BOOL)canInstallSilently { return YES; diff --git a/Autoupdate/SUInstallerProtocol.h b/Autoupdate/SUInstallerProtocol.h index 316ab46a..86fb6f3d 100644 --- a/Autoupdate/SUInstallerProtocol.h +++ b/Autoupdate/SUInstallerProtocol.h @@ -22,6 +22,12 @@ NS_ASSUME_NONNULL_BEGIN // Should be able to be called from non-main thread - (BOOL)performFinalInstallationProgressBlock:(nullable void(^)(double))cb error:(NSError **)error; +// Any clean up work can be done here +// This is work that may be performed after the user application may have been updated / relaunched, +// or after an error occurred in the previous stages. +// Should be able to be called from any thread +- (void)performCleanup; + // Indicates whether or not this installer can install the update silently in the background, without hindering the user // If this returns NO, then the installation can fail if the user did not directly request for the install to occur. // Should be thread safe diff --git a/Autoupdate/SUPackageInstaller.m b/Autoupdate/SUPackageInstaller.m index 251a0561..aaaa2e16 100644 --- a/Autoupdate/SUPackageInstaller.m +++ b/Autoupdate/SUPackageInstaller.m @@ -73,6 +73,10 @@ static NSString *SUOpenUtilityPath = @"/usr/bin/open"; return YES; } +- (void)performCleanup +{ +} + - (BOOL)canInstallSilently { return NO; diff --git a/Autoupdate/SUPlainInstaller.m b/Autoupdate/SUPlainInstaller.m index ab517ab6..585771ae 100644 --- a/Autoupdate/SUPlainInstaller.m +++ b/Autoupdate/SUPlainInstaller.m @@ -24,6 +24,10 @@ @property (nonatomic, copy, readonly) NSString *bundlePath; @property (nonatomic, copy, readonly) NSString *installationPath; +@property (nonatomic) NSURL *temporaryOldDirectory; +// We get an obj-c warning if we use 'newTemporaryDirectory' name about new + ownership stuff, so use 'temporaryNewDirectory' instead +@property (nonatomic) NSURL *temporaryNewDirectory; + @end @implementation SUPlainInstaller @@ -31,6 +35,8 @@ @synthesize host = _host; @synthesize bundlePath = _bundlePath; @synthesize installationPath = _installationPath; +@synthesize temporaryOldDirectory = _temporaryOldDirectory; +@synthesize temporaryNewDirectory = _temporaryNewDirectory; - (instancetype)initWithHost:(SUHost *)host bundlePath:(NSString *)bundlePath installationPath:(NSString *)installationPath { @@ -100,6 +106,8 @@ return NO; } + + self.temporaryNewDirectory = tempNewDirectoryURL; if (progress) { progress(2/10.0); @@ -112,8 +120,6 @@ if (error != NULL) { *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to move the new app from %@ to its temp directory at %@", newURL.path, newTempURL.path] }]; } - - [fileManager removeItemAtURL:tempNewDirectoryURL error:NULL]; return NO; } @@ -143,7 +149,6 @@ } // Try to preserve Finder Tags - // TODO: If we ever migrate to -[NSFileManager replaceItemAtURL:..] method, which we should at some point, we wouldn't have to do this step NSArray *resourceTags = nil; BOOL retrievedResourceTags = [oldURL getResourceValue:&resourceTags forKey:NSURLTagNamesKey error:NULL]; if (retrievedResourceTags && resourceTags.count > 0) { @@ -174,68 +179,79 @@ if (progress) { progress(6/10.0); } - - // Decide on a destination name we should use for the older app when we move it around the file system - NSString *oldDestinationName = oldURL.lastPathComponent.stringByDeletingPathExtension; - NSString *oldDestinationNameWithPathExtension = oldURL.lastPathComponent; - - // Create a temporary directory for our old app that resides on its volume - NSURL *oldDirectoryURL = oldURL.URLByDeletingLastPathComponent; - NSURL *tempOldDirectoryURL = (oldDirectoryURL != nil) ? [fileManager makeTemporaryDirectoryWithPreferredName:oldDestinationName appropriateForDirectoryURL:oldDirectoryURL error:error] : nil; - if (tempOldDirectoryURL == nil) { - if (error != NULL) { - *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to create temporary directory for old app at %@", oldURL.path] }]; + + // First try replacing the application atomically + NSError *replaceError = nil; + BOOL replacedApp; + if (@available(macOS 10.13, *)) { + // If the app is normalized and the installation path differs, go through the old swap path + if (SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME && ![oldURL.path isEqual:installationURL.path]) { + replacedApp = NO; + } else { + // Note: in my experience, a clone of the app may still be left at newTempURL + // This is OK though because we will be cleaning up the temporary directory later in -performCleanup: + replacedApp = [fileManager replaceItemAtURL:installationURL withItemAtURL:newTempURL error:&replaceError]; + } + } else { + replacedApp = NO; + } + + if (!replacedApp) { + // Otherwise swap out the old and new applications using the legacy path + + if (replaceError != nil) { + SULog(SULogLevelDefault, @"Invoking fallback from failing to replace original item with error: %@", replaceError); } - [fileManager removeItemAtURL:tempNewDirectoryURL error:NULL]; - return NO; - } + // Decide on a destination name we should use for the older app when we move it around the file system + NSString *oldDestinationName = oldURL.lastPathComponent.stringByDeletingPathExtension; + NSString *oldDestinationNameWithPathExtension = oldURL.lastPathComponent; - if (progress) { - progress(7/10.0); - } - - // Move the old app to the temporary directory - NSURL *oldTempURL = [tempOldDirectoryURL URLByAppendingPathComponent:oldDestinationNameWithPathExtension]; - if (![fileManager moveItemAtURL:oldURL toURL:oldTempURL error:error]) { - if (error != NULL) { - *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to move the old app at %@ to a temporary location at %@", oldURL.path, oldTempURL.path] }]; + // Create a temporary directory for our old app that resides on its volume + NSURL *oldDirectoryURL = oldURL.URLByDeletingLastPathComponent; + NSURL *tempOldDirectoryURL = (oldDirectoryURL != nil) ? [fileManager makeTemporaryDirectoryWithPreferredName:oldDestinationName appropriateForDirectoryURL:oldDirectoryURL error:error] : nil; + if (tempOldDirectoryURL == nil) { + if (error != NULL) { + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to create temporary directory for old app at %@", oldURL.path] }]; + } + return NO; } - // Just forget about our updated app on failure - [fileManager removeItemAtURL:tempNewDirectoryURL error:NULL]; - [fileManager removeItemAtURL:tempOldDirectoryURL error:NULL]; - - return NO; - } + self.temporaryOldDirectory = tempOldDirectoryURL; - if (progress) { - progress(8/10.0); - } - - // Move the new app to its final destination - if (![fileManager moveItemAtURL:newTempURL toURL:installationURL error:error]) { - if (error != NULL) { - *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to move new app at %@ to final destination %@", newTempURL.path, installationURL.path] }]; + if (progress) { + progress(7/10.0); } - // Forget about our updated app on failure - [fileManager removeItemAtURL:tempNewDirectoryURL error:NULL]; - - // Attempt to restore our old app back the way it was on failure - [fileManager moveItemAtURL:oldTempURL toURL:oldURL error:NULL]; - [fileManager removeItemAtURL:tempOldDirectoryURL error:NULL]; - - return NO; - } + // Move the old app to the temporary directory + NSURL *oldTempURL = [tempOldDirectoryURL URLByAppendingPathComponent:oldDestinationNameWithPathExtension]; + if (![fileManager moveItemAtURL:oldURL toURL:oldTempURL error:error]) { + if (error != NULL) { + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to move the old app at %@ to a temporary location at %@", oldURL.path, oldTempURL.path] }]; + } + return NO; + } - if (progress) { - progress(9/10.0); - } + if (progress) { + progress(8/10.0); + } - // Cleanup - [fileManager removeItemAtURL:tempOldDirectoryURL error:NULL]; - [fileManager removeItemAtURL:tempNewDirectoryURL error:NULL]; + // Move the new app to its final destination + if (![fileManager moveItemAtURL:newTempURL toURL:installationURL error:error]) { + if (error != NULL) { + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to move new app at %@ to final destination %@", newTempURL.path, installationURL.path] }]; + } + + // Attempt to restore our old app back the way it was on failure + [fileManager moveItemAtURL:oldTempURL toURL:oldURL error:NULL]; + + return NO; + } + + if (progress) { + progress(9/10.0); + } + } if (progress) { progress(10/10.0); @@ -280,6 +296,19 @@ return [self startInstallationToURL:[NSURL fileURLWithPath:self.installationPath] fromUpdateAtURL:[NSURL fileURLWithPath:self.bundlePath] withHost:self.host progressBlock:cb error:error]; } +- (void)performCleanup +{ + SUFileManager *fileManager = [[SUFileManager alloc] init]; + + if (self.temporaryNewDirectory != nil) { + [fileManager removeItemAtURL:self.temporaryNewDirectory error:NULL]; + } + + if (self.temporaryOldDirectory != nil) { + [fileManager removeItemAtURL:self.temporaryOldDirectory error:NULL]; + } +} + - (BOOL)canInstallSilently { return YES; diff --git a/Sparkle/SUFileManager.h b/Sparkle/SUFileManager.h index e465eeda..a643fba1 100644 --- a/Sparkle/SUFileManager.h +++ b/Sparkle/SUFileManager.h @@ -59,6 +59,19 @@ NS_ASSUME_NONNULL_BEGIN */ - (BOOL)moveItemAtURL:(NSURL *)sourceURL toURL:(NSURL *)destinationURL error:(NSError **)error; +/** + * Replaces an original item with a new item atomically. + * @param originalItemURL A URL pointing to the original item to replace. The item at this URL must exist. + * @param newItemURL A URL pointing to the new item that will replace the original item. + * @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 original item was replaced with the new item successfully, otherwise NO along with a populated error object + * + * originalItemURL and newItemURL must reside on the same volume. If the operation succeeds, this will be be an atomic operation. + * Otherwise on failure you may need to re-try using move operations. This operation will fail on non-apfs volumes or volumes that don't support rename swapping. + * Both originalItemURL and newItemURL must exist. + */ +- (BOOL)replaceItemAtURL:(NSURL *)originalItemURL withItemAtURL:(NSURL *)newItemURL error:(NSError **)error __OSX_AVAILABLE(10.13); + /** * Copies an item from a source to a destination * @param sourceURL A URL pointing to the item to move. The item at this URL must exist. diff --git a/Sparkle/SUFileManager.m b/Sparkle/SUFileManager.m index 8b29d440..5b8e09d7 100644 --- a/Sparkle/SUFileManager.m +++ b/Sparkle/SUFileManager.m @@ -17,6 +17,8 @@ #include "AppKitPrevention.h" +extern int renamex_np(const char *, const char *, unsigned int) __attribute__((weak_import)); + static char SUAppleQuarantineIdentifier[] = "com.apple.quarantine"; static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { @@ -309,6 +311,35 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) { return [_fileManager moveItemAtURL:sourceURL toURL:destinationURL error:error]; } +- (BOOL)replaceItemAtURL:(NSURL *)originalItemURL withItemAtURL:(NSURL *)newItemURL error:(NSError * __autoreleasing *)error __OSX_AVAILABLE(10.13) +{ + char originalPath[PATH_MAX] = {0}; + if (![originalItemURL.path getFileSystemRepresentation:originalPath maxLength:sizeof(originalPath)]) { + if (error != NULL) { + *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Original item %@ to replace cannot be represented as a valid file name", originalItemURL.lastPathComponent] }]; + } + return NO; + } + + char newPath[PATH_MAX] = {0}; + if (![newItemURL.path getFileSystemRepresentation:newPath maxLength:sizeof(newPath)]) { + if (error != NULL) { + *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"New item %@ to replace cannot be represented as a valid file name", newItemURL.lastPathComponent] }]; + } + return NO; + } + + int status = renamex_np(newPath, originalPath, RENAME_SWAP); + if (status != 0) { + if (error != NULL) { + *error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to replace %@ with %@.", originalItemURL.lastPathComponent, newItemURL.lastPathComponent] }]; + } + return NO; + } + + return YES; +} + - (BOOL)_changeOwnerAndGroupOfItemAtURL:(NSURL *)targetURL ownerID:(NSNumber *)ownerID groupID:(NSNumber *)groupID error:(NSError * __autoreleasing *)error { char path[PATH_MAX] = {0};