diff --git a/Sparkle.xcodeproj/project.pbxproj b/Sparkle.xcodeproj/project.pbxproj index e0a5985a..b84c79ed 100644 --- a/Sparkle.xcodeproj/project.pbxproj +++ b/Sparkle.xcodeproj/project.pbxproj @@ -73,8 +73,10 @@ 55C14F9A136F045400649790 /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 61B5F8F609C4CEB300B25A18 /* Security.framework */; }; 55C14FC7136F05E100649790 /* Sparkle.strings in Resources */ = {isa = PBXBuildFile; fileRef = 61AAE8220A321A7F00D8810D /* Sparkle.strings */; }; 55E6F33319EC9F6C00005E76 /* SUErrors.h in Headers */ = {isa = PBXBuildFile; fileRef = 55E6F33219EC9F6C00005E76 /* SUErrors.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 5AF6C1E91AE86E270014A3AB /* test archive.zip in Resources */ = {isa = PBXBuildFile; fileRef = 5AF6C1E81AE86E270014A3AB /* test archive.zip */; }; 5AF6C1E51AE86A410014A3AB /* SUPipedUnarchiverTest.m in Sources */ = {isa = PBXBuildFile; fileRef = 5AF6C1EA1AE870A90014A3AB /* SUPipedUnarchiverTest.m */; }; + 5AF6C1E91AE86E270014A3AB /* test archive.zip in Resources */ = {isa = PBXBuildFile; fileRef = 5AF6C1E81AE86E270014A3AB /* test archive.zip */; }; + 5AF6C74F1AEA46D10014A3AB /* test.sparkle_guided.pkg in Resources */ = {isa = PBXBuildFile; fileRef = 5AF6C74E1AEA46D10014A3AB /* test.sparkle_guided.pkg */; }; + 5AF6C7541AEA49840014A3AB /* SUInstallerTest.m in Sources */ = {isa = PBXBuildFile; fileRef = 5AF6C74C1AEA40760014A3AB /* SUInstallerTest.m */; }; 5AF9DC3C1981DBEE001EA135 /* SUDSAVerifierTest.m in Sources */ = {isa = PBXBuildFile; fileRef = 5AF9DC3B1981DBEE001EA135 /* SUDSAVerifierTest.m */; }; 5D06E8E90FD68CDB005AE3F6 /* bsdiff.c in Sources */ = {isa = PBXBuildFile; fileRef = 5D06E8DB0FD68CB9005AE3F6 /* bsdiff.c */; settings = {COMPILER_FLAGS = "-w"; }; }; 5D06E8EA0FD68CDB005AE3F6 /* SUBinaryDeltaTool.m in Sources */ = {isa = PBXBuildFile; fileRef = 5D06E8E30FD68CC7005AE3F6 /* SUBinaryDeltaTool.m */; }; @@ -415,6 +417,8 @@ 5AEF45D9189D1CC90030D7DC /* tr */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = tr; path = tr.lproj/Sparkle.strings; sourceTree = ""; }; 5AF6C1E81AE86E270014A3AB /* test archive.zip */ = {isa = PBXFileReference; lastKnownFileType = archive.zip; path = "test archive.zip"; sourceTree = ""; }; 5AF6C1EA1AE870A90014A3AB /* SUPipedUnarchiverTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SUPipedUnarchiverTest.m; sourceTree = ""; }; + 5AF6C74C1AEA40760014A3AB /* SUInstallerTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SUInstallerTest.m; sourceTree = ""; }; + 5AF6C74E1AEA46D10014A3AB /* test.sparkle_guided.pkg */ = {isa = PBXFileReference; lastKnownFileType = file; path = test.sparkle_guided.pkg; sourceTree = ""; }; 5AF9DC3B1981DBEE001EA135 /* SUDSAVerifierTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SUDSAVerifierTest.m; sourceTree = ""; }; 5D06E8D00FD68C7C005AE3F6 /* BinaryDelta */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = BinaryDelta; sourceTree = BUILT_PRODUCTS_DIR; }; 5D06E8DB0FD68CB9005AE3F6 /* bsdiff.c */ = {isa = PBXFileReference; comments = "-Wno-shorten-64-to-32"; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = bsdiff.c; sourceTree = ""; }; @@ -787,6 +791,7 @@ F8761EB21ADC50EB000C9034 /* SparkleTestCodeSignApp.zip */, 5AF6C1E81AE86E270014A3AB /* test archive.zip */, 14958C6C19AEBC610061B14F /* test-pubkey.pem */, + 5AF6C74E1AEA46D10014A3AB /* test.sparkle_guided.pkg */, ); path = Resources; sourceTree = ""; @@ -839,6 +844,7 @@ 142E0E0819A83AAC00E4312B /* SUBinaryDeltaTest.m */, F8761EB01ADC5068000C9034 /* SUCodeSigningVerifierTest.m */, 5AF9DC3B1981DBEE001EA135 /* SUDSAVerifierTest.m */, + 5AF6C74C1AEA40760014A3AB /* SUInstallerTest.m */, 5AF6C1EA1AE870A90014A3AB /* SUPipedUnarchiverTest.m */, 14950074195FDF5900BC5B5B /* SUUpdaterTest.m */, 61227A150DB548B800AB99EA /* SUVersionComparisonTest.m */, @@ -1276,6 +1282,7 @@ F8761EB31ADC50EB000C9034 /* SparkleTestCodeSignApp.zip in Resources */, 5AF6C1E91AE86E270014A3AB /* test archive.zip in Resources */, 14958C6F19AEBC980061B14F /* test-pubkey.pem in Resources */, + 5AF6C74F1AEA46D10014A3AB /* test.sparkle_guided.pkg in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -1443,6 +1450,7 @@ 142E0E0919A83AAC00E4312B /* SUBinaryDeltaTest.m in Sources */, F8761EB11ADC5068000C9034 /* SUCodeSigningVerifierTest.m in Sources */, 5AF9DC3C1981DBEE001EA135 /* SUDSAVerifierTest.m in Sources */, + 5AF6C7541AEA49840014A3AB /* SUInstallerTest.m in Sources */, 14652F8219A9746000959E44 /* SULog.m in Sources */, 5AF6C1E51AE86A410014A3AB /* SUPipedUnarchiverTest.m in Sources */, ); diff --git a/Sparkle/Autoupdate/Autoupdate.m b/Sparkle/Autoupdate/Autoupdate.m index 860d35bd..11887adf 100644 --- a/Sparkle/Autoupdate/Autoupdate.m +++ b/Sparkle/Autoupdate/Autoupdate.m @@ -18,7 +18,7 @@ static const NSTimeInterval SUInstallationTimeLimit = 5; */ static const NSTimeInterval SUParentQuitCheckInterval = .25; -@interface TerminationListener : NSObject +@interface TerminationListener : NSObject @property (copy) NSString *hostpath; @property (copy) NSString *executablepath; @@ -163,36 +163,32 @@ static const NSTimeInterval SUParentQuitCheckInterval = .25; [SUInstaller installFromUpdateFolder:self.folderpath overHost:self.host installationPath:self.installationPath - delegate:self - versionComparator:[SUStandardVersionComparator defaultComparator]]; -} - -- (void)installerFinishedForHost:(SUHost *)__unused aHost -{ - [self relaunch]; -} - -- (void)installerForHost:(SUHost *)__unused host failedWithError:(NSError *)error __attribute__((noreturn)) -{ - if (self.shouldShowUI) { - NSRunAlertPanel(@"", @"%@", @"OK", @"", @"", [error localizedDescription]); - } - exit(EXIT_FAILURE); + versionComparator:[SUStandardVersionComparator defaultComparator] + completionHandler:^(NSError *error) { + if (error) { + if (self.shouldShowUI) { + NSRunAlertPanel(@"", @"%@", @"OK", @"", @"", [error localizedDescription]); + } + exit(EXIT_FAILURE); + } else { + [self relaunch]; + } + }]; } @end int main(int __unused argc, const char __unused *argv[]) { - @autoreleasepool { + @autoreleasepool + { NSArray *args = [[NSProcessInfo processInfo] arguments]; if (args.count < 5 || args.count > 7) { return EXIT_FAILURE; } BOOL shouldShowUI = (args.count > 6) ? [args[6] boolValue] : YES; - if (shouldShowUI) - { + if (shouldShowUI) { [[NSApplication sharedApplication] activateIgnoringOtherApps:YES]; } diff --git a/Sparkle/SUGuidedPackageInstaller.h b/Sparkle/SUGuidedPackageInstaller.h index 37df2657..92082a34 100644 --- a/Sparkle/SUGuidedPackageInstaller.h +++ b/Sparkle/SUGuidedPackageInstaller.h @@ -11,34 +11,10 @@ A guided installation allows Sparkle to download and install a package (pkg) or multi-package (mpkg) without user interaction. -A guided installation occurs when Sparkle finds a `.sparkle_guide.plist` in the root of the download; the file contains the relative path of the installer package to install. - -The file must be a property list and have a dictionary root. The only required key pair value is `package`. - -The `package` key value pair must be set to a relative path to the package or multi-package to install. The path is relative to the guide file. - -Example Contents of Sparkle Guide file: - - - - - - package - My Package.pkg - - - -Example Path of Sparkle Guide file: - - /Volumes/MyUpdateDiskImage/.sparkle_guide.plist - The installer package is installed using Mac OS X's built-in command line installer, `/usr/sbin/installer`. No installation interface is shown to the user. A guided installation can be started by applications other than the application being replaced. This is particularly useful where helper applications or agents are used. -## Notes -This method has been tested and successfully deployed on Mac OS X 10.4 - 10.8. - ## To Do - Replace the use of `AuthorizationExecuteWithPrivilegesAndWait`. This method remains because it is well supported and tested. Ideally a helper tool or XPC would be used. */ @@ -49,14 +25,11 @@ This method has been tested and successfully deployed on Mac OS X 10.4 - 10.8. #import "Sparkle.h" #import "SUInstaller.h" -extern NSString* SUInstallerGuidedInstallerFilename; // default filename for guided installer property list - -@interface SUGuidedPackageInstaller : SUInstaller { } -/*! Search for and return any installer guide */ -+ (NSString *)installerGuideWithinUpdateFolder:(NSString *)updateFolder; +@interface SUGuidedPackageInstaller : SUInstaller { +} /*! Perform the guided installation */ -+ (void)performInstallationToPath:(NSString *)path fromPath:(NSString *)installerGuide host:(SUHost *)host delegate:delegate synchronously:(BOOL)synchronously versionComparator:(id )comparator; ++ (void)performInstallationToPath:(NSString *)path fromPath:(NSString *)installerGuide host:(SUHost *)host versionComparator:(id)comparator completionHandler:(void (^)(NSError *))completionHandler; @end #endif diff --git a/Sparkle/SUGuidedPackageInstaller.m b/Sparkle/SUGuidedPackageInstaller.m index 4cab7d42..bc83d42b 100644 --- a/Sparkle/SUGuidedPackageInstaller.m +++ b/Sparkle/SUGuidedPackageInstaller.m @@ -11,18 +11,6 @@ #import "SUGuidedPackageInstaller.h" -NSString* SUInstallerGuidedInstallerFilename = @".sparkle_guide.plist"; // top level file to search for within update folder - -// Constants -static NSString* SUGuidedPackageInstallerKeyGuidePath = @"SUGuidedPackageInstallerKeyGuidePath"; // NSString* -static NSString* SUGuidedPackageInstallerKeyGuide = @"SUGuidedPackageInstallerKeyGuide"; // NSDictionary* -static NSString* SUGuidedPackageInstallerKeyHost = @"SUGuidedPackageInstallerKeyHost"; // SUHost* -static NSString* SUGuidedPackageInstallerKeyDelegate = @"SUGuidedPackageInstallerKeyDelegate"; // id -static NSString* SUGuidedPackageInstallerKeyResult = @"SUGuidedPackageInstallerKeyResult"; // NSNumber[bool] -static NSString* SUGuidedPackageInstallerKeyError = @"SUGuidedPackageInstallerKeyError"; // NSError* - -static NSString* SUGuidedPackageInstallerGuideKeyPackage = @"package"; // NSString* - static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authorization, const char* executablePath, AuthorizationFlags options, const char* const* arguments) { sig_t oldSigChildHandler = signal(SIGCHLD, SIG_DFL); @@ -46,83 +34,6 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza return returnValue; } -@interface SUGuidedPackageInstaller (SUGuidedPackageInstallerAuthentication) -+ (AuthorizationRef)authorizationForExecutable:(NSString*)executablePath; -@end - -@interface SUGuidedPackageInstaller (SUGuidedPackageInstallerThreads) -// Perform the installation script -+ (void)performInstallationWithInfo:(NSDictionary *)theInfo; -// Complete the installation process -+ (void)finishInstallationWithInfo:(NSDictionary *)theInfo; -@end - -@implementation SUGuidedPackageInstaller - -// Search for and return any installer guide -+ (NSString *)installerGuideWithinUpdateFolder:(NSString *)updateFolder -{ - NSParameterAssert(updateFolder); - - NSDirectoryEnumerator *dirEnum = [[NSFileManager defaultManager] enumeratorAtPath:updateFolder]; - NSString *currentFile; - while ((currentFile = [dirEnum nextObject])) - { - if ([[currentFile lastPathComponent] isEqualToString:SUInstallerGuidedInstallerFilename]) - { - // Found an installer guide - return [updateFolder stringByAppendingPathComponent:currentFile]; - } - } - - // No guide found - return nil; -} - -+ (void)performInstallationToPath:(NSString *) __unused path fromPath:(NSString *)installerGuide host:(SUHost *)host delegate:delegate synchronously:(BOOL)synchronously versionComparator:(id ) __unused comparator -{ - NSParameterAssert(installerGuide); - NSParameterAssert(host); - - // Fetch the contents of the guide - NSDictionary* guide = [NSDictionary dictionaryWithContentsOfFile:installerGuide]; - if (guide == nil) - { - NSString* errorMessage = [NSString stringWithFormat:@"Sparkle Updater: Installer guide contents are malformed '%@'.",installerGuide]; - NSError* error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:[NSDictionary dictionaryWithObject:errorMessage forKey:NSLocalizedDescriptionKey]]; - [self finishInstallationToPath:installerGuide withResult:NO host:host error:error delegate:delegate]; - return; - } - - // Sanity check the contents of the guide - if ([guide objectForKey:SUGuidedPackageInstallerGuideKeyPackage] == NO) - { - NSString* errorMessage = [NSString stringWithFormat:@"Sparkle Updater: Installer guide is missing '%@' entry.",SUGuidedPackageInstallerGuideKeyPackage]; - NSError* error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:[NSDictionary dictionaryWithObject:errorMessage forKey:NSLocalizedDescriptionKey]]; - [self finishInstallationToPath:installerGuide withResult:NO host:host error:error delegate:delegate]; - return; - } - - // Package up installation details to allow for synchronous installation - NSDictionary* info = [NSDictionary dictionaryWithObjectsAndKeys: - installerGuide,SUGuidedPackageInstallerKeyGuidePath, - guide,SUGuidedPackageInstallerKeyGuide, - host,SUGuidedPackageInstallerKeyHost, - delegate,SUGuidedPackageInstallerKeyDelegate, - nil]; - - if (synchronously) - { - [self performInstallationWithInfo:info]; - } - else - { - [NSThread detachNewThreadSelector:@selector(performInstallationWithInfo:) toTarget:self withObject:info]; - } -} - -@end - @implementation SUGuidedPackageInstaller (SUGuidedPackageInstallerAuthentication) + (AuthorizationRef)authorizationForExecutable:(NSString*)executablePath @@ -177,99 +88,52 @@ static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authoriza @end -@implementation SUGuidedPackageInstaller (SUGuidedPackageInstallerThreads) +@implementation SUGuidedPackageInstaller -// Perform the installation script -+ (void)performInstallationWithInfo:(NSDictionary *)theInfo ++ (void)performInstallationToPath:(NSString *)destinationPath fromPath:(NSString *)packagePath host:(SUHost *)__unused host versionComparator:(id)__unused comparator completionHandler:(void (^)(NSError *))completionHandler { - NSParameterAssert(theInfo); - - // Preflight - NSString* installerPath = @"/usr/sbin/installer"; // Mac OS X 10.2+ command line installer tool - NSError* error = nil; - - // Check installer executable exists - if ([[NSFileManager defaultManager] isExecutableFileAtPath:installerPath] == NO) - { - NSString* errorMessage = [NSString stringWithFormat:@"Sparkle Updater: Guide installer tool is missing."]; - error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:[NSDictionary dictionaryWithObject:errorMessage forKey:NSLocalizedDescriptionKey]]; - } - - // Package is relative to installer guide file - NSString* absolutePackagePath = nil; - if (error == nil) - { - NSString* installerGuideParentFolderPath = [[theInfo objectForKey:SUGuidedPackageInstallerKeyGuidePath] stringByDeletingLastPathComponent]; - NSString* packagePath = [(NSDictionary*)[theInfo objectForKey:SUGuidedPackageInstallerKeyGuide] objectForKey:SUGuidedPackageInstallerGuideKeyPackage]; - NSAssert(packagePath,@"package entry is missing from guide"); - absolutePackagePath = [installerGuideParentFolderPath stringByAppendingPathComponent:packagePath]; - - // Sanity check absolute package path exists - if ([[NSFileManager defaultManager] fileExistsAtPath:absolutePackagePath] == NO) - { - NSString* errorMessage = [NSString stringWithFormat:@"Sparkle Updater: Guide installer tool is missing."]; - error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:[NSDictionary dictionaryWithObject:errorMessage forKey:NSLocalizedDescriptionKey]]; - } - } - - // Create authorization for installer executable - AuthorizationRef auth = nil; - BOOL validInstallation = NO; - if (error == nil) - { - auth = [self authorizationForExecutable:installerPath]; - if (auth != NULL) - { - // Permission was granted to execute the installer with privileges - const char* const arguments[] = { -// [installerPath fileSystemRepresentation], - "-pkg", - [absolutePackagePath fileSystemRepresentation], - "-target", - "/", - NULL - }; - validInstallation = AuthorizationExecuteWithPrivilegesAndWait(auth, - [installerPath fileSystemRepresentation], - kAuthorizationFlagDefaults, - arguments); - // TODO: wait for communications pipe to close via fileno & CFSocketCreateWithNative - } - else - { - NSString* errorMessage = [NSString stringWithFormat:@"Sparkle Updater: Script authorization denied."]; - error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:[NSDictionary dictionaryWithObject:errorMessage forKey:NSLocalizedDescriptionKey]]; - } - } - - // Release any authorization - if (auth) - { - AuthorizationFree(auth,kAuthorizationFlagDefaults); - } - - // Modify info to include the installation script's outcome - NSMutableDictionary* resultInfo = [theInfo mutableCopy]; - [resultInfo setObject:[NSNumber numberWithBool:validInstallation] forKey:SUGuidedPackageInstallerKeyResult]; - if ((validInstallation == NO) && - (error)) - { - [resultInfo setObject:error forKey:SUGuidedPackageInstallerKeyError]; - } - - [self performSelectorOnMainThread:@selector(finishInstallationWithInfo:) withObject:resultInfo waitUntilDone:NO]; -} + NSParameterAssert(packagePath); -// Complete the installation process -+ (void)finishInstallationWithInfo:(NSDictionary *)theInfo -{ - NSParameterAssert(theInfo); - - [self finishInstallationToPath:[theInfo objectForKey:SUGuidedPackageInstallerKeyGuidePath] - withResult:[[theInfo objectForKey:SUGuidedPackageInstallerKeyResult] boolValue] - host:[theInfo objectForKey:SUGuidedPackageInstallerKeyHost] - error:[theInfo objectForKey:SUGuidedPackageInstallerKeyError] - delegate:[theInfo objectForKey:SUGuidedPackageInstallerKeyDelegate]]; + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ + + // Preflight + NSString* installerPath = @"/usr/sbin/installer"; // Mac OS X 10.2+ command line installer tool + NSError* error = nil; + + // Create authorization for installer executable + BOOL validInstallation = NO; + AuthorizationRef auth = [self authorizationForExecutable:installerPath]; + if (auth != NULL) + { + // Permission was granted to execute the installer with privileges + const char* const arguments[] = { + "-pkg", + [packagePath fileSystemRepresentation], + "-target", + "/", + NULL + }; + validInstallation = AuthorizationExecuteWithPrivilegesAndWait(auth, + [installerPath fileSystemRepresentation], + kAuthorizationFlagDefaults, + arguments); + // TODO: wait for communications pipe to close via fileno & CFSocketCreateWithNative + AuthorizationFree(auth,kAuthorizationFlagDefaults); + } + else + { + NSString* errorMessage = [NSString stringWithFormat:@"Sparkle Updater: Script authorization denied."]; + error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:[NSDictionary dictionaryWithObject:errorMessage forKey:NSLocalizedDescriptionKey]]; + } + + dispatch_async(dispatch_get_main_queue(), ^{ + [self finishInstallationToPath:destinationPath + withResult:validInstallation + error:error + completionHandler:completionHandler]; + + }); + }); } @end diff --git a/Sparkle/SUInstaller.h b/Sparkle/SUInstaller.h index c1b01898..fe82f885 100644 --- a/Sparkle/SUInstaller.h +++ b/Sparkle/SUInstaller.h @@ -12,21 +12,14 @@ #import #import "SUVersionComparisonProtocol.h" -@protocol SUInstallerDelegate; - @class SUHost; @interface SUInstaller : NSObject + (NSString *)appPathInUpdateFolder:(NSString *)updateFolder forHost:(SUHost *)host; -+ (void)installFromUpdateFolder:(NSString *)updateFolder overHost:(SUHost *)host installationPath:(NSString *)installationPath delegate:(id)delegate versionComparator:(id)comparator; -+ (void)finishInstallationToPath:(NSString *)installationPath withResult:(BOOL)result host:(SUHost *)host error:(NSError *)error delegate:(id)delegate; ++ (void)installFromUpdateFolder:(NSString *)updateFolder overHost:(SUHost *)host installationPath:(NSString *)installationPath versionComparator:(id)comparator completionHandler:(void (^)(NSError *))completionHandler; ++ (void)finishInstallationToPath:(NSString *)installationPath withResult:(BOOL)result error:(NSError *)error completionHandler:(void (^)(NSError *))completionHandler; + (NSString *)updateFolder; @end -@protocol SUInstallerDelegate -- (void)installerFinishedForHost:(SUHost *)host; -- (void)installerForHost:(SUHost *)host failedWithError:(NSError *)error; -@end - #endif diff --git a/Sparkle/SUInstaller.m b/Sparkle/SUInstaller.m index c10434ae..2513973a 100644 --- a/Sparkle/SUInstaller.m +++ b/Sparkle/SUInstaller.m @@ -14,7 +14,6 @@ #import "SUConstants.h" #import "SULog.h" - @implementation SUInstaller static NSString *sUpdateFolder = nil; @@ -43,22 +42,25 @@ static NSString *sUpdateFolder = nil; return NO; } -+ (NSString *)installSourcePathInUpdateFolder:(NSString *)inUpdateFolder forHost:(SUHost *)host isPackage:(BOOL *)isPackagePtr ++ (NSString *)installSourcePathInUpdateFolder:(NSString *)inUpdateFolder forHost:(SUHost *)host isPackage:(BOOL *)isPackagePtr isGuided:(BOOL *)isGuidedPtr { + NSParameterAssert(inUpdateFolder); + NSParameterAssert(host); + // Search subdirectories for the application NSString *currentFile, *newAppDownloadPath = nil, *bundleFileName = [[host bundlePath] lastPathComponent], *alternateBundleFileName = [[host name] stringByAppendingPathExtension:[[host bundlePath] pathExtension]]; BOOL isPackage = NO; + BOOL isGuided = NO; NSString *fallbackPackagePath = nil; NSDirectoryEnumerator *dirEnum = [[NSFileManager defaultManager] enumeratorAtPath:inUpdateFolder]; NSString *bundleFileNameNoExtension = [bundleFileName stringByDeletingPathExtension]; - + sUpdateFolder = inUpdateFolder; - while ((currentFile = [dirEnum nextObject])) - { + while ((currentFile = [dirEnum nextObject])) { NSString *currentPath = [inUpdateFolder stringByAppendingPathComponent:currentFile]; NSString *currentFilename = [currentFile lastPathComponent]; NSString *currentExtension = [currentFile pathExtension]; @@ -69,28 +71,20 @@ static NSString *sUpdateFolder = nil; isPackage = NO; newAppDownloadPath = currentPath; break; - } - else if ([currentExtension isEqualToString:@"pkg"] || - [currentExtension isEqualToString:@"mpkg"]) - { - if ([currentFilenameNoExtension isEqualToString:bundleFileNameNoExtension]) - { + } else if ([currentExtension isEqualToString:@"pkg"] || + [currentExtension isEqualToString:@"mpkg"]) { + if ([currentFilenameNoExtension isEqualToString:bundleFileNameNoExtension]) { isPackage = YES; newAppDownloadPath = currentPath; break; - } - else - { + } else { // Remember any other non-matching packages we have seen should we need to use one of them as a fallback. fallbackPackagePath = currentPath; } - } - else - { + } else { // Try matching on bundle identifiers in case the user has changed the name of the host app NSBundle *incomingBundle = [NSBundle bundleWithPath:currentPath]; - if(incomingBundle && [[incomingBundle bundleIdentifier] isEqualToString:[[host bundle] bundleIdentifier]]) - { + if (incomingBundle && [[incomingBundle bundleIdentifier] isEqualToString:[[host bundle] bundleIdentifier]]) { isPackage = NO; newAppDownloadPath = currentPath; break; @@ -104,45 +98,53 @@ static NSString *sUpdateFolder = nil; // We don't have a valid path. Try to use the fallback package. - if (newAppDownloadPath == nil && fallbackPackagePath != nil) - { + if (newAppDownloadPath == nil && fallbackPackagePath != nil) { isPackage = YES; newAppDownloadPath = fallbackPackagePath; } - if (isPackagePtr) *isPackagePtr = isPackage; + if (isPackage) { + // foo.app -> foo.sparkle_guided.pkg or foo.sparkle_guided.mpkg + if ([[[newAppDownloadPath stringByDeletingPathExtension] pathExtension] isEqualToString:@"sparkle_guided"]) { + isGuided = YES; + } + } + + if (isPackagePtr) + *isPackagePtr = isPackage; + if (isGuidedPtr) + *isGuidedPtr = isGuided; + + if (!newAppDownloadPath) { + SULog(@"Searched %@ for %@.(app|pkg)", inUpdateFolder, bundleFileNameNoExtension); + } return newAppDownloadPath; } + (NSString *)appPathInUpdateFolder:(NSString *)updateFolder forHost:(SUHost *)host { BOOL isPackage = NO; - NSString *path = [self installSourcePathInUpdateFolder:updateFolder forHost:host isPackage:&isPackage]; + NSString *path = [self installSourcePathInUpdateFolder:updateFolder forHost:host isPackage:&isPackage isGuided:nil]; return isPackage ? nil : path; } -+ (void)installFromUpdateFolder:(NSString *)inUpdateFolder overHost:(SUHost *)host installationPath:(NSString *)installationPath delegate:(id)delegate versionComparator:(id)comparator ++ (void)installFromUpdateFolder:(NSString *)inUpdateFolder overHost:(SUHost *)host installationPath:(NSString *)installationPath versionComparator:(id)comparator completionHandler:(void (^)(NSError *))completionHandler { - // Look for installer guide - NSString* installerGuide = [SUGuidedPackageInstaller installerGuideWithinUpdateFolder:inUpdateFolder]; - if (installerGuide) - { - [SUGuidedPackageInstaller performInstallationToPath:installationPath fromPath:installerGuide host:host delegate:delegate synchronously:NO versionComparator:comparator]; - } - else - { - BOOL isPackage = NO; - NSString *newAppDownloadPath = [self installSourcePathInUpdateFolder:inUpdateFolder forHost:host isPackage:&isPackage]; + BOOL isPackage = NO; + BOOL isGuided = NO; + NSString *newAppDownloadPath = [self installSourcePathInUpdateFolder:inUpdateFolder forHost:host isPackage:&isPackage isGuided:&isGuided]; - if (newAppDownloadPath == nil) - { - [self finishInstallationToPath:installationPath withResult:NO host:host error:[NSError errorWithDomain:SUSparkleErrorDomain code:SUMissingUpdateError userInfo:@{ NSLocalizedDescriptionKey: @"Couldn't find an appropriate update in the downloaded package." }] delegate:delegate]; - } - else - { - [(isPackage ? [SUPackageInstaller class] : [SUPlainInstaller class])performInstallationToPath:installationPath fromPath:newAppDownloadPath host:host delegate:delegate versionComparator:comparator]; - } - } + if (newAppDownloadPath == nil) { + [self finishInstallationToPath:installationPath withResult:NO error:[NSError errorWithDomain:SUSparkleErrorDomain code:SUMissingUpdateError userInfo:@{ NSLocalizedDescriptionKey: @"Couldn't find an appropriate update in the downloaded package." }] completionHandler:completionHandler]; + } else { + if (isPackage && isGuided) { + [SUGuidedPackageInstaller performInstallationToPath:installationPath fromPath:newAppDownloadPath host:host versionComparator:comparator completionHandler:completionHandler]; + } else if (isPackage) { + [SUPackageInstaller performInstallationToPath:installationPath fromPath:newAppDownloadPath host:host versionComparator:comparator completionHandler:completionHandler]; + } else { + [SUPlainInstaller performInstallationToPath:installationPath fromPath:newAppDownloadPath host:host versionComparator:comparator completionHandler:completionHandler]; + } + } } + (void)mdimportInstallationPath:(NSString *)installationPath @@ -154,8 +156,7 @@ static NSString *sUpdateFolder = nil; NSTask *mdimport = [[NSTask alloc] init]; [mdimport setLaunchPath:@"/usr/bin/mdimport"]; [mdimport setArguments:@[installationPath]]; - @try - { + @try { [mdimport launch]; [mdimport waitUntilExit]; } @@ -166,24 +167,20 @@ static NSString *sUpdateFolder = nil; } } -+ (void)finishInstallationToPath:(NSString *)installationPath withResult:(BOOL)result host:(SUHost *)host error:(NSError *)error delegate:(id)delegate ++ (void)finishInstallationToPath:(NSString *)installationPath withResult:(BOOL)result error:(NSError *)error completionHandler:(void (^)(NSError *))completionHandler { - if (result) - { + if (result) { [self mdimportInstallationPath:installationPath]; - if ([delegate respondsToSelector:@selector(installerFinishedForHost:)]) { - dispatch_async(dispatch_get_main_queue(), ^{ - [delegate installerFinishedForHost:host]; - }); - } - } - else - { - if ([delegate respondsToSelector:@selector(installerForHost:failedWithError:)]) { - dispatch_async(dispatch_get_main_queue(), ^{ - [delegate installerForHost:host failedWithError:error]; - }); + dispatch_async(dispatch_get_main_queue(), ^{ + completionHandler(nil); + }); + } else { + if (!error) { + error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:nil]; } + dispatch_async(dispatch_get_main_queue(), ^{ + completionHandler(error); + }); } } diff --git a/Sparkle/SUPackageInstaller.m b/Sparkle/SUPackageInstaller.m index 23ad954f..64637433 100644 --- a/Sparkle/SUPackageInstaller.m +++ b/Sparkle/SUPackageInstaller.m @@ -12,7 +12,7 @@ @implementation SUPackageInstaller -+ (void)performInstallationToPath:(NSString *)installationPath fromPath:(NSString *)path host:(SUHost *)host delegate:(id)delegate versionComparator:(id)__unused comparator ++ (void)performInstallationToPath:(NSString *)installationPath fromPath:(NSString *)path host:(SUHost *)__unused host versionComparator:(id)__unused comparator completionHandler:(void (^)(NSError *))completionHandler { // Run installer using the "open" command to ensure it is launched in front of current application. // -W = wait until the app has quit. @@ -23,7 +23,7 @@ if (![[NSFileManager defaultManager] fileExistsAtPath:command]) { NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUMissingInstallerToolError userInfo:@{ NSLocalizedDescriptionKey: @"Couldn't find Apple's installer tool!" }]; - [self finishInstallationToPath:installationPath withResult:NO host:host error:error delegate:delegate]; + [self finishInstallationToPath:installationPath withResult:NO error:error completionHandler:completionHandler]; return; } @@ -33,7 +33,7 @@ // Known bug: if the installation fails or is canceled, Sparkle goes ahead and restarts, thinking everything is fine. dispatch_async(dispatch_get_main_queue(), ^{ - [self finishInstallationToPath:installationPath withResult:YES host:host error:nil delegate:delegate]; + [self finishInstallationToPath:installationPath withResult:YES error:nil completionHandler:completionHandler]; }); }); } diff --git a/Sparkle/SUPlainInstaller.h b/Sparkle/SUPlainInstaller.h index bb7827a6..9fd78f6f 100644 --- a/Sparkle/SUPlainInstaller.h +++ b/Sparkle/SUPlainInstaller.h @@ -21,7 +21,7 @@ @interface SUPlainInstaller : SUInstaller -+ (void)performInstallationToPath:(NSString *)installationPath fromPath:(NSString *)path host:(SUHost *)host delegate:(id)delegate versionComparator:(id)comparator; ++ (void)performInstallationToPath:(NSString *)installationPath fromPath:(NSString *)path host:(SUHost *)host versionComparator:(id)comparator completionHandler:(void (^)(NSError *))completionHandler; @end diff --git a/Sparkle/SUPlainInstaller.m b/Sparkle/SUPlainInstaller.m index f9ff7faa..1aeb6317 100644 --- a/Sparkle/SUPlainInstaller.m +++ b/Sparkle/SUPlainInstaller.m @@ -14,15 +14,16 @@ @implementation SUPlainInstaller -+ (void)performInstallationToPath:(NSString *)installationPath fromPath:(NSString *)path host:(SUHost *)host delegate:(id)delegate versionComparator:(id)comparator ++ (void)performInstallationToPath:(NSString *)installationPath fromPath:(NSString *)path host:(SUHost *)host versionComparator:(id)comparator completionHandler:(void (^)(NSError *))completionHandler { + NSParameterAssert(host); + // Prevent malicious downgrades if (![[[NSBundle bundleWithIdentifier:SUBundleIdentifier] infoDictionary][SUEnableAutomatedDowngradesKey] boolValue]) { - if ([comparator compareVersion:[host version] toVersion:[[NSBundle bundleWithPath:path] objectForInfoDictionaryKey:(__bridge NSString *)kCFBundleVersionKey]] == NSOrderedDescending) - { + if ([comparator compareVersion:[host version] toVersion:[[NSBundle bundleWithPath:path] objectForInfoDictionaryKey:(__bridge NSString *)kCFBundleVersionKey]] == NSOrderedDescending) { NSString *errorMessage = [NSString stringWithFormat:@"Sparkle Updater: Possible attack in progress! Attempting to \"upgrade\" from %@ to %@. Aborting update.", [host version], [[NSBundle bundleWithPath:path] objectForInfoDictionaryKey:(__bridge NSString *)kCFBundleVersionKey]]; NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUDowngradeError userInfo:@{ NSLocalizedDescriptionKey: errorMessage }]; - [self finishInstallationToPath:installationPath withResult:NO host:host error:error delegate:delegate]; + [self finishInstallationToPath:installationPath withResult:NO error:error completionHandler:completionHandler]; return; } } @@ -52,7 +53,7 @@ } dispatch_async(dispatch_get_main_queue(), ^{ - [self finishInstallationToPath:installationPath withResult:result host:host error:error delegate:delegate]; + [self finishInstallationToPath:installationPath withResult:result error:error completionHandler:completionHandler]; }); }); } diff --git a/Tests/Resources/test.sparkle_guided.pkg b/Tests/Resources/test.sparkle_guided.pkg new file mode 100644 index 00000000..f4933a80 Binary files /dev/null and b/Tests/Resources/test.sparkle_guided.pkg differ diff --git a/Tests/SUInstallerTest.m b/Tests/SUInstallerTest.m new file mode 100644 index 00000000..ceee0b6c --- /dev/null +++ b/Tests/SUInstallerTest.m @@ -0,0 +1,65 @@ +// +// SUInstallerTest.m +// Sparkle +// +// Created by Kornel on 24/04/2015. +// Copyright (c) 2015 Sparkle Project. All rights reserved. +// + +#import +#import +#import "SUHost.h" +#import "SUInstaller.h" +#import + +@interface SUInstallerTest : XCTestCase + +@end + +@implementation SUInstallerTest + +- (void)setUp +{ + [super setUp]; + // Put setup code here. This method is called before the invocation of each test method in the class. +} + +- (void)tearDown +{ + // Put teardown code here. This method is called after the invocation of each test method in the class. + [super tearDown]; +} + +- (void)testInstallIfRoot +{ + uid_t uid = getuid(); + + if (uid) { + NSLog(@"Test must be run as root: sudo xctest -XCTest SUInstallerTest 'Sparkle Unit Tests.xctest'"); + return; + } + + NSString *expectedDestination = @"/tmp/sparklepkgtest.app"; + NSFileManager *fm = [NSFileManager defaultManager]; + [fm removeItemAtPath:expectedDestination error:nil]; + XCTAssertFalse([fm fileExistsAtPath:expectedDestination isDirectory:nil]); + + XCTestExpectation *done = [self expectationWithDescription:@"install finished"]; + + NSBundle *bundle = [NSBundle bundleForClass:[self class]]; + NSString *path = [bundle pathForResource:@"test.sparkle_guided" ofType:@"pkg"]; + XCTAssertNotNil(path); + + SUHost *host = [[SUHost alloc] initWithBundle:bundle]; + + [SUInstaller installFromUpdateFolder:[path stringByDeletingLastPathComponent] overHost:host installationPath:@"/tmp" versionComparator:nil completionHandler:^(NSError *error) { + XCTAssertNil(error); + XCTAssertTrue([fm fileExistsAtPath:expectedDestination isDirectory:nil]); + [done fulfill]; + }]; + + [self waitForExpectationsWithTimeout:40 handler:nil]; + [fm removeItemAtPath:expectedDestination error:nil]; +} + +@end