From e2da47b7c71cdaae91dda61f0298cb5894599837 Mon Sep 17 00:00:00 2001 From: Zorg Date: Thu, 28 Jul 2016 22:54:28 -0400 Subject: [PATCH] Improve handling of storing files in cache Create distinct subdirectories in our cache directory so files for different purposes won't conflict. For the installer, move the download archive to the installer's cache location. If the installer is running as root, this moves it to a place only root can access I believe. This is also to prevent other functionality from touching these files. --- Autoupdate/AppInstaller.m | 135 ++++++++++++------ InstallerLauncher/SUInstallerLauncher.m | 13 +- PersistentDownloader/SUPersistentDownloader.m | 14 +- Sparkle.xcodeproj/project.pbxproj | 2 + Sparkle/SUCoreBasedUpdateDriver.m | 4 +- Sparkle/SUInstallerDriver.h | 2 +- Sparkle/SUInstallerDriver.m | 79 +--------- Sparkle/SULocalCacheDirectory.h | 2 + 8 files changed, 111 insertions(+), 140 deletions(-) diff --git a/Autoupdate/AppInstaller.m b/Autoupdate/AppInstaller.m index bd32e387..859ce576 100644 --- a/Autoupdate/AppInstaller.m +++ b/Autoupdate/AppInstaller.m @@ -27,6 +27,7 @@ #import "AgentConnection.h" #import "SUInstallerAgentProtocol.h" #import "SUInstallationType.h" +#import "SULocalCacheDirectory.h" #ifdef _APPKITDEFINES_H #error This is a "daemon-safe" class and should NOT import AppKit @@ -54,7 +55,12 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; @property (nonatomic, readonly, copy) NSString *hostBundleIdentifier; @property (nonatomic) SUHost *host; -@property (nonatomic) SUInstallationInputData *installationData; +@property (nonatomic, copy) NSString *updateDirectoryPath; +@property (nonatomic, copy) NSString *downloadName; +@property (nonatomic, copy) NSString *decryptionPassword; +@property (nonatomic, copy) NSString *dsaSignature; +@property (nonatomic, copy) NSString *relaunchPath; +@property (nonatomic, copy) NSString *installationType; @property (nonatomic, assign) BOOL shouldRelaunch; @property (nonatomic, assign) BOOL shouldShowUI; @@ -81,7 +87,12 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; @synthesize hostBundleIdentifier = _hostBundleIdentifier; @synthesize terminationListener = _terminationListener; @synthesize host = _host; -@synthesize installationData = _installationData; +@synthesize updateDirectoryPath = _updateDirectoryPath; +@synthesize downloadName = _downloadName; +@synthesize decryptionPassword = _decryptionPassword; +@synthesize dsaSignature = _dsaSignature; +@synthesize relaunchPath = _relaunchPath; +@synthesize installationType = _installationType; @synthesize shouldRelaunch = _shouldRelaunch; @synthesize shouldShowUI = _shouldShowUI; @synthesize installer = _installer; @@ -260,8 +271,8 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; { [self.communicator handleMessageWithIdentifier:SUExtractionStarted data:[NSData data]]; - NSString *downloadPath = [self.installationData.updateDirectoryPath stringByAppendingPathComponent:self.installationData.downloadName]; - id unarchiver = [SUUnarchiver unarchiverForPath:downloadPath updatingHostBundlePath:self.host.bundlePath decryptionPassword:self.installationData.decryptionPassword delegate:self]; + NSString *downloadPath = [self.updateDirectoryPath stringByAppendingPathComponent:self.downloadName]; + id unarchiver = [SUUnarchiver unarchiverForPath:downloadPath updatingHostBundlePath:self.host.bundlePath decryptionPassword:self.decryptionPassword delegate:self]; if (!unarchiver) { SULog(@"Error: No valid unarchiver for %@!", downloadPath); [self unarchiverDidFail]; @@ -284,7 +295,14 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; { // Client could try update again with different inputs // Eg: one common case is if a delta update fails, client may want to fall back to regular update - self.installationData = nil; + // We really only need to set updateDirectoryPath to nil since that's the field we check if we've received installation data, + // but may as well set other fields to nil too + self.updateDirectoryPath = nil; + self.downloadName = nil; + self.decryptionPassword = nil; + self.dsaSignature = nil; + self.relaunchPath = nil; + self.host = nil; [self.communicator handleMessageWithIdentifier:SUArchiveExtractionFailed data:[NSData data]]; } @@ -293,8 +311,8 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; { [self.communicator handleMessageWithIdentifier:SUValidationStarted data:[NSData data]]; - NSString *downloadPath = [self.installationData.updateDirectoryPath stringByAppendingPathComponent:self.installationData.downloadName]; - BOOL validationSuccess = [self validateUpdateForHost:self.host downloadedToPath:downloadPath extractedToPath:self.installationData.updateDirectoryPath DSASignature:self.installationData.dsaSignature]; + NSString *downloadPath = [self.updateDirectoryPath stringByAppendingPathComponent:self.downloadName]; + BOOL validationSuccess = [self validateUpdateForHost:self.host downloadedToPath:downloadPath extractedToPath:self.updateDirectoryPath DSASignature:self.dsaSignature]; if (!validationSuccess) { SULog(@"Error: update validation was a failure"); @@ -331,7 +349,7 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; // For a plug-in this makes a big difference; we want to wait until the app hosting the plug-in terminates // Otherwise for an app, the relaunch path and host path should be identical - [self.agentConnection.agent registerRelaunchBundlePath:self.installationData.relaunchPath reply:^(NSNumber * _Nullable processIdentifier) { + [self.agentConnection.agent registerRelaunchBundlePath:self.relaunchPath reply:^(NSNumber * _Nullable processIdentifier) { dispatch_async(dispatch_get_main_queue(), ^{ self.terminationListener = [[TerminationListener alloc] initWithProcessIdentifier:processIdentifier]; [self startInstallation]; @@ -348,44 +366,79 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; - (void)handleMessageWithIdentifier:(int32_t)identifier data:(NSData *)data { - if (identifier == SUInstallationData && self.installationData == nil) { + if (identifier == SUInstallationData && self.updateDirectoryPath == nil) { dispatch_async(dispatch_get_main_queue(), ^{ // Mark that we have received the installation data - // Do not rely on self.installationData != nil because we may set it to nil again if an early stage fails (i.e, archive extraction) + // Do not rely on eg: self.ipdateDirectoryPath != nil because we may set it to nil again if an early stage fails (i.e, archive extraction) self.receivedInstallationData = YES; SUInstallationInputData *installationData = (SUInstallationInputData *)SUUnarchiveRootObjectSecurely(data, [SUInstallationInputData class]); if (installationData == nil) { SULog(@"Error: Failed to unarchive input installation data"); [self cleanupAndExitWithStatus:EXIT_FAILURE]; - } else { - SUInstallationInputData *nonNullInstallationData = installationData; - NSBundle *hostBundle = [NSBundle bundleWithPath:nonNullInstallationData.hostBundlePath]; - SUHost *host = [[SUHost alloc] initWithBundle:hostBundle]; - - NSString *installationType = nonNullInstallationData.installationType; - if (!SUValidInstallationType(installationType)) { - SULog(@"Error: Received invalid installation type: %@", installationType); - [self cleanupAndExitWithStatus:EXIT_FAILURE]; - } else { - NSString *bundleIdentifier = hostBundle.bundleIdentifier; - if (bundleIdentifier == nil || ![bundleIdentifier isEqualToString:self.hostBundleIdentifier]) { - SULog(@"Error: Failed to match host bundle identifiers %@ and %@", self.hostBundleIdentifier, bundleIdentifier); - [self cleanupAndExitWithStatus:EXIT_FAILURE]; - } else { - // This will be important later - if (nonNullInstallationData.relaunchPath == nil) { - SULog(@"Error: Failed to obtain relaunch path from installation data"); - [self cleanupAndExitWithStatus:EXIT_FAILURE]; - } else { - self.host = host; - self.installationData = installationData; - - [self extractAndInstallUpdate]; - } - } - } + return; } + + NSString *installationType = installationData.installationType; + if (!SUValidInstallationType(installationType)) { + SULog(@"Error: Received invalid installation type: %@", installationType); + [self cleanupAndExitWithStatus:EXIT_FAILURE]; + return; + } + + NSBundle *hostBundle = [NSBundle bundleWithPath:installationData.hostBundlePath]; + + NSString *bundleIdentifier = hostBundle.bundleIdentifier; + if (bundleIdentifier == nil || ![bundleIdentifier isEqualToString:self.hostBundleIdentifier]) { + SULog(@"Error: Failed to match host bundle identifiers %@ and %@", self.hostBundleIdentifier, bundleIdentifier); + [self cleanupAndExitWithStatus:EXIT_FAILURE]; + return; + } + + // This will be important later + if (installationData.relaunchPath == nil) { + SULog(@"Error: Failed to obtain relaunch path from installation data"); + [self cleanupAndExitWithStatus:EXIT_FAILURE]; + return; + } + + // This installation path is specific to sparkle and the bundle identifier + NSString *cacheInstallationPath = [[SULocalCacheDirectory cachePathForBundleIdentifier:bundleIdentifier] stringByAppendingPathComponent:@"Installation"]; + + SUFileManager *fileManager = [SUFileManager defaultManager]; + [fileManager removeItemAtURL:[NSURL fileURLWithPath:cacheInstallationPath] error:NULL]; + + NSError *createError = nil; + if (![[NSFileManager defaultManager] createDirectoryAtPath:cacheInstallationPath withIntermediateDirectories:YES attributes:nil error:&createError]) { + SULog(@"Error: Failed to create installation cache directory"); + [self cleanupAndExitWithStatus:EXIT_FAILURE]; + return; + } + + // Move the download archive to somewhere where probably only we will be touching it + // This prevents eg: if a bug exists in the updater that removes files we are trying to install + // When this tool is ran as root, we are moving it into a directory that only root will have access to + NSURL *downloadURL = [[NSURL fileURLWithPath:installationData.updateDirectoryPath] URLByAppendingPathComponent:installationData.downloadName]; + + NSURL *downloadDestinationURL = [[NSURL fileURLWithPath:cacheInstallationPath] URLByAppendingPathComponent:installationData.downloadName]; + + NSError *moveError = nil; + if (![fileManager moveItemAtURL:downloadURL toURL:downloadDestinationURL error:&moveError]) { + SULog(@"Error: Failed to move download archive to new location: %@", moveError); + [self cleanupAndExitWithStatus:EXIT_FAILURE]; + return; + } + + // Carry these properities separately rather than using the SUInstallationInputData object + // Some of our properties may slightly differ than our input and we don't want to make the mistake of using one of those + self.installationType = installationType; + self.relaunchPath = installationData.relaunchPath; + self.downloadName = installationData.downloadName; + self.dsaSignature = installationData.dsaSignature; + self.updateDirectoryPath = cacheInstallationPath; + self.host = [[SUHost alloc] initWithBundle:hostBundle]; + + [self extractAndInstallUpdate]; }); } else if (identifier == SUSentUpdateAppcastItemData) { SUAppcastItem *updateItem = (SUAppcastItem *)SUUnarchiveRootObjectSecurely(data, [SUAppcastItem class]); @@ -431,7 +484,7 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; dispatch_async(self.installerQueue, ^{ NSError *installerError = nil; - id installer = [SUInstaller installerForHost:self.host expectedInstallationType:self.installationData.installationType updateDirectory:self.installationData.updateDirectoryPath versionComparator:[SUStandardVersionComparator standardVersionComparator] error:&installerError]; + id installer = [SUInstaller installerForHost:self.host expectedInstallationType:self.installationType updateDirectory:self.updateDirectoryPath versionComparator:[SUStandardVersionComparator standardVersionComparator] error:&installerError]; if (installer == nil) { SULog(@"Error: Failed to create installer instance with error: %@", installerError); @@ -570,10 +623,10 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; NSString *pathToRelaunch = nil; // If the installation path differs from the host path, we give higher precedence for it than // if the desired relaunch path differs from the host path - if (![installationPath.pathComponents isEqualToArray:self.host.bundlePath.pathComponents] || [self.installationData.relaunchPath.pathComponents isEqualToArray:self.host.bundlePath.pathComponents]) { + if (![installationPath.pathComponents isEqualToArray:self.host.bundlePath.pathComponents] || [self.relaunchPath.pathComponents isEqualToArray:self.host.bundlePath.pathComponents]) { pathToRelaunch = installationPath; } else { - pathToRelaunch = self.installationData.relaunchPath; + pathToRelaunch = self.relaunchPath; } [self.agentConnection.agent relaunchPath:pathToRelaunch]; @@ -605,7 +658,7 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; self.agentConnection = nil; NSError *theError = nil; - if (![[NSFileManager defaultManager] removeItemAtPath:self.installationData.updateDirectoryPath error:&theError]) { + if (![[NSFileManager defaultManager] removeItemAtPath:self.updateDirectoryPath error:&theError]) { SULog(@"Couldn't remove update folder: %@.", theError); } diff --git a/InstallerLauncher/SUInstallerLauncher.m b/InstallerLauncher/SUInstallerLauncher.m index 7f376121..632aeff3 100644 --- a/InstallerLauncher/SUInstallerLauncher.m +++ b/InstallerLauncher/SUInstallerLauncher.m @@ -329,22 +329,19 @@ // they could be different (eg: take a look at sparkle-cli). We also can't easily tell if the signature of the service/framework is the same as the bundle it's inside. // The service/framework also need not even be signed in the first place. We'll just assume for now the original bundle hasn't been tampered with - NSString *cachePath = [SULocalCacheDirectory cachePathForBundleIdentifier:hostBundleIdentifier]; + NSString *launcherCachePath = [[SULocalCacheDirectory cachePathForBundleIdentifier:hostBundleIdentifier] stringByAppendingPathComponent:@"Launcher"]; NSFileManager *fileManager = [NSFileManager defaultManager]; + [fileManager removeItemAtPath:launcherCachePath error:NULL]; + NSError *createCacheError = nil; - // Do not remove the cache directory if it already exists since it may be containing downloaded files - if (![fileManager createDirectoryAtPath:cachePath withIntermediateDirectories:YES attributes:nil error:&createCacheError]) { + if (![fileManager createDirectoryAtPath:launcherCachePath withIntermediateDirectories:YES attributes:nil error:&createCacheError]) { SULog(@"Failed to create cache directory for progress tool: %@", createCacheError); completionHandler(SUInstallerLauncherFailure); return; } - NSString *progressToolPath = [cachePath stringByAppendingPathComponent:@""SPARKLE_INSTALLER_PROGRESS_TOOL_NAME@".app"]; - - if ([fileManager fileExistsAtPath:progressToolPath]) { - [fileManager removeItemAtPath:progressToolPath error:NULL]; - } + NSString *progressToolPath = [launcherCachePath stringByAppendingPathComponent:@""SPARKLE_INSTALLER_PROGRESS_TOOL_NAME@".app"]; NSError *copyError = nil; // SUFileManager is more reliable for copying files around diff --git a/PersistentDownloader/SUPersistentDownloader.m b/PersistentDownloader/SUPersistentDownloader.m index f1468088..bd49c2e3 100644 --- a/PersistentDownloader/SUPersistentDownloader.m +++ b/PersistentDownloader/SUPersistentDownloader.m @@ -47,12 +47,6 @@ static NSString *SUPersistentDownloadingReason = @"Downloading persistent file"; - (void)startDownloadWithRequest:(SUURLRequest *)request bundleIdentifier:(NSString *)bundleIdentifier desiredFilename:(NSString *)desiredFilename { dispatch_async(dispatch_get_main_queue(), ^{ - // Remove our old caches path so we don't start accumulating files in there - NSString *cachePath = [SULocalCacheDirectory cachePathForBundleIdentifier:bundleIdentifier]; - if ([[NSFileManager defaultManager] fileExistsAtPath:cachePath]) { - [[NSFileManager defaultManager] removeItemAtPath:cachePath error:NULL]; - } - // Prevent service from automatically terminating while downloading the update asynchronously without any reply blocks [[NSProcessInfo processInfo] disableAutomaticTermination:SUPersistentDownloadingReason]; self.disabledAutomaticTermination = YES; @@ -91,13 +85,15 @@ static NSString *SUPersistentDownloadingReason = @"Downloading persistent file"; { NSString *downloadFileName = self.desiredFilename; - NSString *cachePath = [SULocalCacheDirectory cachePathForBundleIdentifier:self.bundleIdentifier]; + // Remove our old caches path so we don't start accumulating files in there + NSString *persistentDownloadCachePath = [[SULocalCacheDirectory cachePathForBundleIdentifier:self.bundleIdentifier] stringByAppendingPathComponent:@"PersistentDownloads"]; + [[NSFileManager defaultManager] removeItemAtPath:persistentDownloadCachePath error:NULL]; - NSString *tempDir = [cachePath stringByAppendingPathComponent:downloadFileName]; + NSString *tempDir = [persistentDownloadCachePath stringByAppendingPathComponent:downloadFileName]; int count = 1; while ([[NSFileManager defaultManager] fileExistsAtPath:tempDir] && count <= 999) { - tempDir = [cachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@ %d", downloadFileName, count++]]; + tempDir = [persistentDownloadCachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@ %d", downloadFileName, count++]]; } // Create the temporary directory if necessary. diff --git a/Sparkle.xcodeproj/project.pbxproj b/Sparkle.xcodeproj/project.pbxproj index cd170ae1..f95036b6 100644 --- a/Sparkle.xcodeproj/project.pbxproj +++ b/Sparkle.xcodeproj/project.pbxproj @@ -121,6 +121,7 @@ 721D8A721D4950B80032E472 /* Autoupdate in Copy Tools */ = {isa = PBXBuildFile; fileRef = 72B398D21D3D879300EE297F /* Autoupdate */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; }; 721D8A7B1D4963190032E472 /* SULocalCacheDirectory.m in Sources */ = {isa = PBXBuildFile; fileRef = 721BC20D1D1CDE55002BC71E /* SULocalCacheDirectory.m */; }; 721D8A811D498B9B0032E472 /* Updater.app in Copy Tools */ = {isa = PBXBuildFile; fileRef = 721C24451CB753E6005440CB /* Updater.app */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; + 721D8A861D4ADFEB0032E472 /* SULocalCacheDirectory.m in Sources */ = {isa = PBXBuildFile; fileRef = 721BC20D1D1CDE55002BC71E /* SULocalCacheDirectory.m */; }; 7223E7631AD1AEFF008E3161 /* sais.c in Sources */ = {isa = PBXBuildFile; fileRef = 7223E7611AD1AEFF008E3161 /* sais.c */; }; 7229E1B61C97C91100CB50D0 /* SUUpdateDriver.h in Headers */ = {isa = PBXBuildFile; fileRef = 7229E1B51C97C91100CB50D0 /* SUUpdateDriver.h */; }; 7229E1B91C97CC4D00CB50D0 /* SUScheduledUpdateDriver.h in Headers */ = {isa = PBXBuildFile; fileRef = 7229E1B71C97CC4D00CB50D0 /* SUScheduledUpdateDriver.h */; }; @@ -2700,6 +2701,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 721D8A861D4ADFEB0032E472 /* SULocalCacheDirectory.m in Sources */, 7267E5D91D3D8D4B00D1BF90 /* sais.c in Sources */, 7267E5D81D3D8D4400D1BF90 /* SUStandardVersionComparator.m in Sources */, 7267E5D71D3D8D3F00D1BF90 /* SUHost.m in Sources */, diff --git a/Sparkle/SUCoreBasedUpdateDriver.m b/Sparkle/SUCoreBasedUpdateDriver.m index 371e923f..4e9f8d17 100644 --- a/Sparkle/SUCoreBasedUpdateDriver.m +++ b/Sparkle/SUCoreBasedUpdateDriver.m @@ -12,7 +12,6 @@ #import "SUBasicUpdateDriver.h" #import "SUInstallerDriver.h" #import "SUDownloadDriver.h" -#import "SULocalCacheDirectory.h" #import "SULog.h" #import "SUErrors.h" #import "SUDownloadedUpdate.h" @@ -62,10 +61,9 @@ NSString *bundleIdentifier = host.bundle.bundleIdentifier; assert(bundleIdentifier != nil); - NSString *cachePath = [SULocalCacheDirectory cachePathForBundleIdentifier:bundleIdentifier]; _basicDriver = [[SUBasicUpdateDriver alloc] initWithHost:host updater:updater updaterDelegate:updaterDelegate delegate:self]; - _installerDriver = [[SUInstallerDriver alloc] initWithHost:host cachePath:cachePath sparkleBundle:sparkleBundle updater:updater updaterDelegate:updaterDelegate delegate:self]; + _installerDriver = [[SUInstallerDriver alloc] initWithHost:host sparkleBundle:sparkleBundle updater:updater updaterDelegate:updaterDelegate delegate:self]; _host = host; _updater = updater; diff --git a/Sparkle/SUInstallerDriver.h b/Sparkle/SUInstallerDriver.h index 8b1d1583..1b1506b4 100644 --- a/Sparkle/SUInstallerDriver.h +++ b/Sparkle/SUInstallerDriver.h @@ -29,7 +29,7 @@ NS_ASSUME_NONNULL_BEGIN @interface SUInstallerDriver : NSObject -- (instancetype)initWithHost:(SUHost *)host cachePath:(NSString *)cachePath sparkleBundle:(NSBundle *)sparkleBundle updater:(id)updater updaterDelegate:(nullable id)updaterDelegate delegate:(nullable id)delegate; +- (instancetype)initWithHost:(SUHost *)host sparkleBundle:(NSBundle *)sparkleBundle updater:(id)updater updaterDelegate:(nullable id)updaterDelegate delegate:(nullable id)delegate; - (void)resumeInstallingUpdateWithUpdateItem:(SUAppcastItem *)updateItem; diff --git a/Sparkle/SUInstallerDriver.m b/Sparkle/SUInstallerDriver.m index e9b746ce..b54492aa 100644 --- a/Sparkle/SUInstallerDriver.m +++ b/Sparkle/SUInstallerDriver.m @@ -35,7 +35,6 @@ @interface SUInstallerDriver () @property (nonatomic, readonly) SUHost *host; -@property (nonatomic, readonly, copy) NSString *cachePath; @property (nonatomic, readonly) NSBundle *sparkleBundle; @property (nonatomic, weak, readonly) id delegate; @property (nonatomic) SUInstallerMessageType currentStage; @@ -60,7 +59,6 @@ @implementation SUInstallerDriver @synthesize host = _host; -@synthesize cachePath = _cachePath; @synthesize sparkleBundle = _sparkleBundle; @synthesize delegate = _delegate; @synthesize currentStage = _currentStage; @@ -76,12 +74,11 @@ @synthesize temporaryDirectory = _temporaryDirectory; @synthesize aborted = _aborted; -- (instancetype)initWithHost:(SUHost *)host cachePath:(NSString *)cachePath sparkleBundle:(NSBundle *)sparkleBundle updater:(id)updater updaterDelegate:(id)updaterDelegate delegate:(nullable id)delegate +- (instancetype)initWithHost:(SUHost *)host sparkleBundle:(NSBundle *)sparkleBundle updater:(id)updater updaterDelegate:(id)updaterDelegate delegate:(nullable id)delegate { self = [super init]; if (self != nil) { _host = host; - _cachePath = [cachePath copy]; _sparkleBundle = sparkleBundle; _updater = updater; _updaterDelegate = updaterDelegate; @@ -293,80 +290,6 @@ } } -// Creates intermediate directories up until targetPath if they don't already exist, -// and removes the directory at targetPath if one already exists there -- (BOOL)preparePath:(NSString *)targetPath error:(NSError * __autoreleasing *)error -{ - NSFileManager *fileManager = [[NSFileManager alloc] init]; - if ([fileManager fileExistsAtPath:targetPath]) { - NSError *removeError = nil; - if (![fileManager removeItemAtPath:targetPath error:&removeError]) { - if (error != NULL) { - *error = removeError; - } - return NO; - } - } else { - NSError *createDirectoryError = nil; - if (![fileManager createDirectoryAtPath:[targetPath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:@{} error:&createDirectoryError]) { - if (error != NULL) { - *error = createDirectoryError; - } - return NO; - } - } - return YES; -} - -- (NSString *)copyPathToCacheDirectory:(NSString *)pathToCopy error:(NSError * __autoreleasing *)error -{ - // Copy the resource into the caches directory so we can get to it after the new version's installed. - // Only the paranoid survive: if there's already a stray copy of resource there, we would have problems. - NSString *cachePath = nil; - if (pathToCopy == nil) { - if (error != NULL) { - *error = - [NSError - errorWithDomain:SUSparkleErrorDomain - code:SURelaunchError - userInfo:@{ - NSLocalizedDescriptionKey: [NSString stringWithFormat:SULocalizedString(@"An error occurred while relaunching %1$@, but the new version will be available next time you run %1$@.", nil), [self.host name]], - NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:@"Couldn't find the relauncher (expected to find it at %@)", pathToCopy] - } - ]; - } - } else { - NSString *targetPath = [self.cachePath stringByAppendingPathComponent:[pathToCopy lastPathComponent]]; - - SUFileManager *fileManager = [SUFileManager defaultManager]; - - NSURL *urlToCopy = [NSURL fileURLWithPath:pathToCopy]; - NSURL *targetURL = [NSURL fileURLWithPath:targetPath]; - - NSError *prepareOrCopyError = nil; - - // We only need to run our copy of the app by spawning a task - // Since we are copying the app to a directory that is write-accessible, we don't need to muck with owner/group IDs - if ([self preparePath:targetPath error:&prepareOrCopyError] && [fileManager copyItemAtURL:urlToCopy toURL:targetURL error:&prepareOrCopyError]) { - cachePath = targetPath; - } else { - if (error != NULL) { - *error = - [NSError - errorWithDomain:SUSparkleErrorDomain - code:SURelaunchError - userInfo:@{ - NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while extracting the archive. Please try again later.", nil), - NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:@"Couldn't copy relauncher (%@) to temporary path (%@)! %@", pathToCopy, targetPath, (prepareOrCopyError ? [prepareOrCopyError localizedDescription] : @"")] - } - ]; - } - } - } - - return cachePath; -} - - (void)launchAutoUpdateSilently:(BOOL)silently completion:(void (^)(NSError *_Nullable))completionHandler { id installerLauncher = nil; diff --git a/Sparkle/SULocalCacheDirectory.h b/Sparkle/SULocalCacheDirectory.h index c3b56898..48f4fcc5 100644 --- a/Sparkle/SULocalCacheDirectory.h +++ b/Sparkle/SULocalCacheDirectory.h @@ -16,6 +16,8 @@ NS_ASSUME_NONNULL_BEGIN // Intermediate directories to this path may not exist yet // This path may depend on the type of running process, // such that sandboxed vs non-sandboxed processes could yield different paths +// The caller should create a subdirectory from the path that is returned here so they don't have files that +// conflict with other callers + (NSString *)cachePathForBundleIdentifier:(NSString *)bundleIdentifier; @end