From 49e3d819bf48e3b4ae595bb434887251d21b4e29 Mon Sep 17 00:00:00 2001 From: andym Date: Tue, 15 Apr 2008 15:22:18 +0000 Subject: [PATCH] Major refactoring, yay. Moved out installation phase to separate classes, separating packages and flat-file installs. Made the DMG cleanup less horrifying. All-around prettification. This may or may not break the world; please let me know. --- NSFileManager+Authentication.h | 2 +- NSFileManager+Authentication.m | 185 ++++++++++++++++-------------- NTSynchronousTask.h | 2 +- NTSynchronousTask.m | 2 +- SUConstants.h | 6 + SUConstants.m | 6 + SUInstaller.h | 23 ++++ SUInstaller.m | 77 +++++++++++++ SUPackageInstaller.h | 14 +++ SUPackageInstaller.m | 32 ++++++ SUPlainInstaller.h | 13 +++ SUPlainInstaller.m | 26 +++++ SUStandardVersionComparator.m | 2 +- SUStatusController.m | 1 + SUSystemProfiler.h | 2 +- SUUnarchiver.h | 2 + SUUnarchiver.m | 63 ++++++---- SUUpdater.h | 4 +- SUUpdater.m | 106 +++++------------ Sparkle.h | 1 + Sparkle.xcodeproj/project.pbxproj | 32 ++++++ 21 files changed, 408 insertions(+), 193 deletions(-) create mode 100644 SUInstaller.h create mode 100644 SUInstaller.m create mode 100644 SUPackageInstaller.h create mode 100644 SUPackageInstaller.m create mode 100644 SUPlainInstaller.h create mode 100644 SUPlainInstaller.m diff --git a/NSFileManager+Authentication.h b/NSFileManager+Authentication.h index 50eefc24..80b91a9b 100644 --- a/NSFileManager+Authentication.h +++ b/NSFileManager+Authentication.h @@ -10,7 +10,7 @@ #define NSFILEMANAGER_PLUS_AUTHENTICATION_H @interface NSFileManager (SUAuthenticationAdditions) -- (BOOL)copyPath:(NSString *)src overPath:(NSString *)dst withAuthentication:(BOOL)useAuthentication; +- (BOOL)copyPathWithAuthentication:(NSString *)src overPath:(NSString *)dst error:(NSError **)error; @end #endif diff --git a/NSFileManager+Authentication.m b/NSFileManager+Authentication.m index 07876427..3cffc550 100644 --- a/NSFileManager+Authentication.m +++ b/NSFileManager+Authentication.m @@ -18,34 +18,23 @@ #import #import "NSFileManager+ExtendedAttributes.h" - -// TN OV02 says that the range between 1000 and 9999 can be used for -// application-defined errors. errToolFailedError will indicate that an -// executed program crashed or indicated failure with a nonzero exit status -static const OSStatus errToolFailedError = 1000; - -static OSStatus AuthorizationExecuteWithPrivilegesAndWait( - AuthorizationRef authorization, - const char* executablePath, - AuthorizationFlags options, - const char* const* arguments) { +static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authorization, const char* executablePath, AuthorizationFlags options, const char* const* arguments) +{ sig_t oldSigChildHandler = signal(SIGCHLD, SIG_DFL); - OSStatus ret; - ret = AuthorizationExecuteWithPrivileges(authorization, - executablePath, - options, - (char* const*)arguments, - NULL); - if (ret == errAuthorizationSuccess) { + BOOL returnValue = YES; + + if (AuthorizationExecuteWithPrivileges(authorization, executablePath, options, (char* const*)arguments, NULL) == errAuthorizationSuccess) + { int status; pid_t pid = wait(&status); - if (pid == -1 || - !WIFEXITED(status) || WEXITSTATUS(status) != 0) { - ret = errToolFailedError; - } + if (pid == -1 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) + returnValue = NO; } + else + returnValue = NO; + signal(SIGCHLD, oldSigChildHandler); - return ret; + return returnValue; } @implementation NSFileManager (SUAuthenticationAdditions) @@ -85,24 +74,32 @@ static OSStatus AuthorizationExecuteWithPrivilegesAndWait( return res; } -- (NSString *)_temporaryCopyNameForPath:(NSString *)filename +- (NSString *)_temporaryCopyNameForPath:(NSString *)path { - return [[[filename stringByDeletingPathExtension] stringByAppendingString:@".old"] stringByAppendingPathExtension:[filename pathExtension]]; + // Let's try to read the version number so the filename will be more meaningful. + NSString *postFix; + NSBundle *bundle; + if ((bundle = [NSBundle bundleWithPath:path])) + { + // We'll clean it up a little for safety. + NSMutableCharacterSet *validCharacters = [NSMutableCharacterSet alphanumericCharacterSet]; + [validCharacters formUnionWithCharacterSet:[NSCharacterSet characterSetWithCharactersInString:@".-()"]]; + postFix = [[bundle objectForInfoDictionaryKey:@"CFBundleVersion"] stringByTrimmingCharactersInSet:[validCharacters invertedSet]]; + } + else + postFix = @"old"; + return [[[path stringByDeletingPathExtension] stringByAppendingFormat:@" (%@)", postFix] stringByAppendingPathExtension:[path pathExtension]]; } -- (BOOL)_copyPathWithForcedAuthentication:(NSString *)src toPath:(NSString *)dst +- (BOOL)_copyPathWithForcedAuthentication:(NSString *)src toPath:(NSString *)dst error:(NSError **)error { NSString *tmp = [self _temporaryCopyNameForPath:dst]; const char* srcPath = [src fileSystemRepresentation]; const char* tmpPath = [tmp fileSystemRepresentation]; const char* dstPath = [dst fileSystemRepresentation]; - struct stat sb, dstSB; - if ((stat(srcPath, &sb) != 0) || - (stat(tmpPath, &sb) == 0) || - (stat(dstPath, &dstSB) != 0)) { - return NO; - } + struct stat dstSB; + stat(dstPath, &dstSB); AuthorizationRef auth = NULL; OSStatus authStat = errAuthorizationDenied; @@ -122,6 +119,7 @@ static OSStatus AuthorizationExecuteWithPrivilegesAndWait( dstSB.st_uid, dstSB.st_gid); const char* executables[] = { + "/bin/rm", "/bin/mv", "/bin/mv", "/bin/rm", @@ -135,6 +133,7 @@ static OSStatus AuthorizationExecuteWithPrivilegesAndWait( // including the NULL that signals the end of an argument // list. const char* const argumentLists[][4] = { + { "-rf", tmpPath, NULL }, // make room for the temporary file... this is kinda unsafe; should probably do something better. { "-f", dstPath, tmpPath, NULL }, // mv { "-f", srcPath, dstPath, NULL }, // mv { "-rf", tmpPath, NULL }, // rm @@ -146,14 +145,8 @@ static OSStatus AuthorizationExecuteWithPrivilegesAndWait( // Process the commands up until the first NULL int commandIndex = 0; for (; executables[commandIndex] != NULL; ++commandIndex) { - if (res) { - res = ( - AuthorizationExecuteWithPrivilegesAndWait(auth, - executables[commandIndex], - kAuthorizationFlagDefaults, - argumentLists[commandIndex]) == - errAuthorizationSuccess); - } + if (res) + res = AuthorizationExecuteWithPrivilegesAndWait(auth, executables[commandIndex], kAuthorizationFlagDefaults, argumentLists[commandIndex]); } // If the currently-running application is trusted, the new @@ -177,62 +170,86 @@ static OSStatus AuthorizationExecuteWithPrivilegesAndWait( ++commandIndex; for (; executables[commandIndex] != NULL; ++commandIndex) { - if (res) { - res = ( - AuthorizationExecuteWithPrivilegesAndWait(auth, - executables[commandIndex], - kAuthorizationFlagDefaults, - argumentLists[commandIndex]) == - errAuthorizationSuccess); - } + if (res) + res = AuthorizationExecuteWithPrivilegesAndWait(auth, executables[commandIndex], kAuthorizationFlagDefaults, argumentLists[commandIndex]); } AuthorizationFree(auth, 0); + + if (!res) + { + // Something went wrong somewhere along the way, but we're not sure exactly where. + NSString *errorMessage = [NSString stringWithFormat:@"Authenticated file copy from %@ to %@ failed.", src, dst]; + if (error != NULL) + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:[NSDictionary dictionaryWithObject:errorMessage forKey:NSLocalizedDescriptionKey]]; + } + } + else + { + if (error != NULL) + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:[NSDictionary dictionaryWithObject:@"Couldn't get permission to authenticate." forKey:NSLocalizedDescriptionKey]]; } return res; } -- (BOOL)copyPath:(NSString *)src overPath:(NSString *)dst withAuthentication:(BOOL)useAuthentication +- (BOOL)copyPathWithAuthentication:(NSString *)src overPath:(NSString *)dst error:(NSError **)error { - if ([[NSFileManager defaultManager] isWritableFileAtPath:dst] && [[NSFileManager defaultManager] isWritableFileAtPath:[dst stringByDeletingLastPathComponent]]) + if (![[NSFileManager defaultManager] fileExistsAtPath:dst]) { - NSInteger tag = 0; - BOOL result; - NSString *tmpPath = [self _temporaryCopyNameForPath:dst]; - result = [[NSFileManager defaultManager] movePath:dst toPath:tmpPath handler:self]; - result &= [[NSFileManager defaultManager] copyPath:src toPath:dst handler:nil]; - result &= [[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:[tmpPath stringByDeletingLastPathComponent] destination:@"" files:[NSArray arrayWithObject:[tmpPath lastPathComponent]] tag:&tag]; - - // If the currently-running application is trusted, the new - // version should be trusted as well. Remove it from the - // quarantine to avoid a delay at launch, and to avoid - // presenting the user with a confusing trust dialog. - // - // This needs to be done after the application is moved to its - // new home in case it's moved across filesystems: if that - // happens, the move is actually a copy, and it may result - // in the application being quarantined. - if (result) - [self releaseFromQuarantine:dst]; - - return result; - } - else if (useAuthentication == YES) - return [self _copyPathWithForcedAuthentication:src toPath:dst]; - else + NSString *errorMessage = [NSString stringWithFormat:@"Couldn't copy %@ over %@ because there is no file at %@.", src, dst, dst]; + if (error != NULL) + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUFileCopyFailure userInfo:[NSDictionary dictionaryWithObject:errorMessage forKey:NSLocalizedDescriptionKey]]; return NO; -} + } -- (BOOL)fileManager:(NSFileManager *)fileManager shouldProceedAfterError:(NSError *)error copyingItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath -{ - NSLog(@"Sparkle: An error occurred in copying %@ to %@: %@", srcPath, dstPath, [error localizedDescription]); - return NO; -} + if (![[NSFileManager defaultManager] isWritableFileAtPath:dst] || ![[NSFileManager defaultManager] isWritableFileAtPath:[dst stringByDeletingLastPathComponent]]) + return [self _copyPathWithForcedAuthentication:src toPath:dst error:error]; -- (BOOL)fileManager:(NSFileManager *)fileManager shouldProceedAfterError:(NSError *)error movingItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath -{ - NSLog(@"Sparkle: An error occurred in moving %@ to %@: %@", srcPath, dstPath, [error localizedDescription]); - return NO; + NSString *tmpPath = [self _temporaryCopyNameForPath:dst]; + + // We get more error information if we're running on Leopard, so let's use that if we can. + if ([[NSFileManager defaultManager] respondsToSelector:@selector(moveItemAtPath:toPath:error:)]) + { + if (![[NSFileManager defaultManager] moveItemAtPath:dst toPath:tmpPath error:error]) { return NO; } + if (![[NSFileManager defaultManager] copyItemAtPath:src toPath:dst error:error]) { return NO; } + } + else // We just get generic error messages. + { + if (![[NSFileManager defaultManager] movePath:dst toPath:tmpPath handler:self]) + { + if (error != NULL) + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUFileCopyFailure userInfo:[NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"Couldn't move %@ to %@.", dst, tmpPath] forKey:NSLocalizedDescriptionKey]]; + return NO; + } + if (![[NSFileManager defaultManager] copyPath:src toPath:dst handler:self]) + { + if (error != NULL) + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUFileCopyFailure userInfo:[NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"Couldn't copy %@ to %@.", src, dst] forKey:NSLocalizedDescriptionKey]]; + return NO; + } + } + + // Trash the old copy of the app. + NSInteger tag = 0; + if (![[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:[tmpPath stringByDeletingLastPathComponent] destination:@"" files:[NSArray arrayWithObject:[tmpPath lastPathComponent]] tag:&tag]) + { + if (error != NULL) + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUFileCopyFailure userInfo:[NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"Couldn't move %@ to the trash. This is often a sign of a permissions error.", src, dst] forKey:NSLocalizedDescriptionKey]]; + return NO; + } + + // If the currently-running application is trusted, the new + // version should be trusted as well. Remove it from the + // quarantine to avoid a delay at launch, and to avoid + // presenting the user with a confusing trust dialog. + // + // This needs to be done after the application is moved to its + // new home in case it's moved across filesystems: if that + // happens, the move is actually a copy, and it may result + // in the application being quarantined. + [self releaseFromQuarantine:dst]; + + return YES; } @end diff --git a/NTSynchronousTask.h b/NTSynchronousTask.h index 23ca6ef6..1cf5c04e 100644 --- a/NTSynchronousTask.h +++ b/NTSynchronousTask.h @@ -3,7 +3,7 @@ // CocoatechCore // // Created by Steve Gehrman on 9/29/05. -// Copyright 2005 __MyCompanyName__. All rights reserved. +// Copyright 2005 Steve Gehrman. All rights reserved. // #ifndef NTSYNCHRONOUSTASK_H diff --git a/NTSynchronousTask.m b/NTSynchronousTask.m index 2b992e2e..541483a6 100644 --- a/NTSynchronousTask.m +++ b/NTSynchronousTask.m @@ -3,7 +3,7 @@ // CocoatechCore // // Created by Steve Gehrman on 9/29/05. -// Copyright 2005 __MyCompanyName__. All rights reserved. +// Copyright 2005 Steve Gehrman. All rights reserved. // #import "Sparkle.h" diff --git a/SUConstants.h b/SUConstants.h index 0f38d1cb..d177519a 100644 --- a/SUConstants.h +++ b/SUConstants.h @@ -27,6 +27,12 @@ extern NSString *SUEnableAutomaticChecksKey; extern NSString *SUEnableSystemProfilingKey; extern NSString *SUSendProfileInfoKey; +extern NSString *SUSparkleErrorDomain; +extern OSStatus SUFileCopyFailure; +extern OSStatus SUAuthenticationFailure; +extern OSStatus SUMissingUpdateError; +extern OSStatus SUMissingInstallerToolError; + // NSInteger is a type that was added to Leopard. // Here is some glue to ensure that NSInteger will work with pre-10.5 SDKs: #ifndef NSINTEGER_DEFINED diff --git a/SUConstants.m b/SUConstants.m index c788e4a9..6d03748c 100644 --- a/SUConstants.m +++ b/SUConstants.m @@ -24,3 +24,9 @@ NSString *SUAllowsAutomaticUpdatesKey = @"SUAllowsAutomaticUpdates"; NSString *SUEnableSystemProfilingKey = @"SUEnableSystemProfiling"; NSString *SUEnableAutomaticChecksKey = @"SUEnableAutomaticChecks"; NSString *SUSendProfileInfoKey = @"SUSendProfileInfo"; + +NSString *SUSparkleErrorDomain = @"SUSparkleErrorDomain"; +OSStatus SUFileCopyFailure = 9000; +OSStatus SUAuthenticationFailure = 9001; +OSStatus SUMissingUpdateError = 9002; +OSStatus SUMissingInstallerToolError = 9003; diff --git a/SUInstaller.h b/SUInstaller.h new file mode 100644 index 00000000..46b48441 --- /dev/null +++ b/SUInstaller.h @@ -0,0 +1,23 @@ +// +// SUInstaller.h +// Sparkle +// +// Created by Andy Matuschak on 4/10/08. +// Copyright 2008 Andy Matuschak. All rights reserved. +// + +#import + +@interface SUInstaller : NSObject { } ++ (void)installFromUpdateFolder:(NSString *)updateFolder overHostBundle:(NSBundle *)hostBundle delegate:delegate; ++ (void)_finishInstallationWithResult:(BOOL)result hostBundle:(NSBundle *)hostBundle error:(NSError *)error delegate:delegate; +@end + +@interface NSObject (SUInstallerDelegateInformalProtocol) +- installerFinishedForHostBundle:(NSBundle *)hostBundle; +- installerForHostBundle:(NSBundle *)hostBundle failedWithError:(NSError *)error; +@end + +extern NSString *SUInstallerPathKey; +extern NSString *SUInstallerHostBundleKey; +extern NSString *SUInstallerDelegateKey; diff --git a/SUInstaller.m b/SUInstaller.m new file mode 100644 index 00000000..fdb5f531 --- /dev/null +++ b/SUInstaller.m @@ -0,0 +1,77 @@ +// +// SUInstaller.m +// Sparkle +// +// Created by Andy Matuschak on 4/10/08. +// Copyright 2008 Andy Matuschak. All rights reserved. +// + +#import "SUInstaller.h" +#import "SUPlainInstaller.h" +#import "SUPackageInstaller.h" + +NSString *SUInstallerPathKey = @"SUInstallerPath"; +NSString *SUInstallerHostBundleKey = @"SUInstallerHostBundle"; +NSString *SUInstallerDelegateKey = @"SUInstallerDelegate"; + +@implementation SUInstaller + ++ (void)installFromUpdateFolder:(NSString *)updateFolder overHostBundle:(NSBundle *)hostBundle delegate:delegate; +{ + // Search subdirectories for the application + NSString *currentFile, *newAppDownloadPath = nil, *bundleFileName = [[hostBundle bundlePath] lastPathComponent]; + BOOL isPackage = NO; + NSDirectoryEnumerator *dirEnum = [[NSFileManager defaultManager] enumeratorAtPath:updateFolder]; + while ((currentFile = [dirEnum nextObject])) + { + NSString *currentPath = [updateFolder stringByAppendingPathComponent:currentFile]; + if ([[currentFile lastPathComponent] isEqualToString:bundleFileName]) // We found one! + { + isPackage = NO; + newAppDownloadPath = currentPath; + break; + } + else if (([[currentFile pathExtension] isEqualToString:@"pkg"] || [[currentFile pathExtension] isEqualToString:@"mpkg"]) && + [[[currentFile lastPathComponent] stringByDeletingPathExtension] isEqualToString:[bundleFileName stringByDeletingPathExtension]]) + { + isPackage = YES; + newAppDownloadPath = currentPath; + break; + } + + // Some DMGs have symlinks into /Applications! That's no good! And there's no point in looking in bundles. + if ([[NSFileManager defaultManager] isAliasFolderAtPath:currentPath] || + [[currentFile pathExtension] isEqualToString:[[hostBundle bundlePath] pathExtension]] || + [[currentFile pathExtension] isEqualToString:@"pkg"] || + [[currentFile pathExtension] isEqualToString:@"mpkg"]) + { + [dirEnum skipDescendents]; + } + } + + if (newAppDownloadPath == nil) + { + [self _finishInstallationWithResult:NO hostBundle:hostBundle error:[NSError errorWithDomain:SUSparkleErrorDomain code:SUMissingUpdateError userInfo:[NSDictionary dictionaryWithObject:@"Couldn't find an appropriate update in the downloaded package." forKey:NSLocalizedDescriptionKey]] delegate:delegate]; + } + else + { + NSDictionary *info = [NSDictionary dictionaryWithObjectsAndKeys:newAppDownloadPath, SUInstallerPathKey, hostBundle, SUInstallerHostBundleKey, delegate, SUInstallerDelegateKey, nil]; + [NSThread detachNewThreadSelector:@selector(performInstallationWithInfo:) toTarget:(isPackage ? [SUPackageInstaller class] : [SUPlainInstaller class]) withObject:info]; + } +} + ++ (void)_finishInstallationWithResult:(BOOL)result hostBundle:(NSBundle *)hostBundle error:(NSError *)error delegate:delegate +{ + if (result == YES) + { + if ([delegate respondsToSelector:@selector(installerFinishedForHostBundle:)]) + [delegate installerFinishedForHostBundle:hostBundle]; + } + else + { + if ([delegate respondsToSelector:@selector(installerForHostBundle:failedWithError:)]) + [delegate installerForHostBundle:hostBundle failedWithError:error]; + } +} + +@end diff --git a/SUPackageInstaller.h b/SUPackageInstaller.h new file mode 100644 index 00000000..97b09d76 --- /dev/null +++ b/SUPackageInstaller.h @@ -0,0 +1,14 @@ +// +// SUPackageInstaller.h +// Sparkle +// +// Created by Andy Matuschak on 4/10/08. +// Copyright 2008 Andy Matuschak. All rights reserved. +// + +#import "Sparkle.h" +#import "SUPlainInstaller.h" + +@interface SUPackageInstaller : SUPlainInstaller { } ++ (void)installPath:(NSString *)path overHostBundle:(NSBundle *)bundle delegate:delegate; +@end diff --git a/SUPackageInstaller.m b/SUPackageInstaller.m new file mode 100644 index 00000000..0fc20ed5 --- /dev/null +++ b/SUPackageInstaller.m @@ -0,0 +1,32 @@ +// +// SUPackageInstaller.m +// Sparkle +// +// Created by Andy Matuschak on 4/10/08. +// Copyright 2008 Andy Matuschak. All rights reserved. +// + +#import "SUPackageInstaller.h" + + +@implementation SUPackageInstaller + ++ (void)installPath:(NSString *)path overHostBundle:(NSBundle *)bundle delegate:delegate +{ + NSError *error; + BOOL result = YES; + + NSString *installerPath = [[NSWorkspace sharedWorkspace] absolutePathForAppBundleWithIdentifier:@"com.apple.installer"]; + installerPath = [installerPath stringByAppendingString:@"/Contents/MacOS/Installer"]; + if (![[NSFileManager defaultManager] fileExistsAtPath:installerPath]) + { + error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUMissingInstallerToolError userInfo:[NSDictionary dictionaryWithObject:@"Couldn't find Apple's installer tool!" forKey:NSLocalizedDescriptionKey]]; + result = NO; + } + NSTask *installer = [NSTask launchedTaskWithLaunchPath:installerPath arguments:[NSArray arrayWithObjects:path, nil]]; + [installer waitUntilExit]; + // Known bug: if the installation fails or is canceled, Sparkle goes ahead and restarts, thinking everything is fine. + [self _finishInstallationWithResult:result hostBundle:bundle error:error delegate:delegate]; +} + +@end diff --git a/SUPlainInstaller.h b/SUPlainInstaller.h new file mode 100644 index 00000000..804dc99e --- /dev/null +++ b/SUPlainInstaller.h @@ -0,0 +1,13 @@ +// +// SUPlainInstaller.h +// Sparkle +// +// Created by Andy Matuschak on 4/10/08. +// Copyright 2008 Andy Matuschak. All rights reserved. +// + +#import "Sparkle.h" + +@interface SUPlainInstaller : SUInstaller { } ++ (void)installPath:(NSString *)path overHostBundle:(NSBundle *)bundle delegate:delegate; +@end diff --git a/SUPlainInstaller.m b/SUPlainInstaller.m new file mode 100644 index 00000000..9367dcfb --- /dev/null +++ b/SUPlainInstaller.m @@ -0,0 +1,26 @@ +// +// SUPlainInstaller.m +// Sparkle +// +// Created by Andy Matuschak on 4/10/08. +// Copyright 2008 Andy Matuschak. All rights reserved. +// + +#import "SUPlainInstaller.h" + + +@implementation SUPlainInstaller + ++ (void)installPath:(NSString *)path overHostBundle:(NSBundle *)bundle delegate:delegate +{ + NSError *error; + BOOL result = [[NSFileManager defaultManager] copyPathWithAuthentication:path overPath:[bundle bundlePath] error:&error]; + [self _finishInstallationWithResult:result hostBundle:bundle error:error delegate:delegate]; +} + ++ (void)performInstallationWithInfo:(NSDictionary *)info +{ + [self installPath:[info objectForKey:SUInstallerPathKey] overHostBundle:[info objectForKey:SUInstallerHostBundleKey] delegate:[info objectForKey:SUInstallerDelegateKey]]; +} + +@end diff --git a/SUStandardVersionComparator.m b/SUStandardVersionComparator.m index 87505481..d82ca27c 100644 --- a/SUStandardVersionComparator.m +++ b/SUStandardVersionComparator.m @@ -3,7 +3,7 @@ // Sparkle // // Created by Andy Matuschak on 12/21/07. -// Copyright 2007 __MyCompanyName__. All rights reserved. +// Copyright 2007 Andy Matuschak. All rights reserved. // #import "Sparkle.h" diff --git a/SUStatusController.m b/SUStatusController.m index 79c567c6..7101c74c 100644 --- a/SUStatusController.m +++ b/SUStatusController.m @@ -102,6 +102,7 @@ { maxProgressValue = value; [self setProgressValue:0]; + [progressBar setIndeterminate:(value == 0)]; } - (void)setStatusText:(NSString *)aStatusText diff --git a/SUSystemProfiler.h b/SUSystemProfiler.h index 9a08f0c1..8ce9f545 100644 --- a/SUSystemProfiler.h +++ b/SUSystemProfiler.h @@ -3,7 +3,7 @@ // Sparkle // // Created by Andy Matuschak on 12/22/07. -// Copyright 2007 __MyCompanyName__. All rights reserved. +// Copyright 2007 Andy Matuschak. All rights reserved. // #ifndef SUSYSTEMPROFILER_H diff --git a/SUUnarchiver.h b/SUUnarchiver.h index c5e037a4..337bf500 100644 --- a/SUUnarchiver.h +++ b/SUUnarchiver.h @@ -11,10 +11,12 @@ @interface SUUnarchiver : NSObject { id delegate; + NSString *archivePath; } - (void)unarchivePath:(NSString *)path; - (void)setDelegate:delegate; +- (void)cleanUp; @end diff --git a/SUUnarchiver.m b/SUUnarchiver.m index 0994139c..118205f1 100644 --- a/SUUnarchiver.m +++ b/SUUnarchiver.m @@ -13,7 +13,7 @@ @implementation SUUnarchiver // This method abstracts the types that use a command line tool piping data from stdin. -- (BOOL)_extractArchivePath:archivePath pipingDataToCommand:(NSString *)command +- (BOOL)_extractArchivePipingDataToCommand:(NSString *)command { // Get the file size. NSNumber *fs = [[[NSFileManager defaultManager] fileAttributesAtPath:archivePath traverseLink:NO] objectForKey:NSFileSize]; @@ -52,27 +52,27 @@ return YES; } -- (BOOL)_extractTAR:(NSString *)archivePath +- (BOOL)_extractTAR { - return [self _extractArchivePath:archivePath pipingDataToCommand:@"tar -xC \"$DESTINATION\""]; + return [self _extractArchivePipingDataToCommand:@"tar -xC \"$DESTINATION\""]; } -- (BOOL)_extractTGZ:(NSString *)archivePath +- (BOOL)_extractTGZ { - return [self _extractArchivePath:archivePath pipingDataToCommand:@"tar -zxC \"$DESTINATION\""]; + return [self _extractArchivePipingDataToCommand:@"tar -zxC \"$DESTINATION\""]; } -- (BOOL)_extractTBZ:(NSString *)archivePath +- (BOOL)_extractTBZ { - return [self _extractArchivePath:archivePath pipingDataToCommand:@"tar -jxC \"$DESTINATION\""]; + return [self _extractArchivePipingDataToCommand:@"tar -jxC \"$DESTINATION\""]; } -- (BOOL)_extractZIP:(NSString *)archivePath +- (BOOL)_extractZIP { - return [self _extractArchivePath:archivePath pipingDataToCommand:@"ditto -x -k - \"$DESTINATION\""]; + return [self _extractArchivePipingDataToCommand:@"ditto -x -k - \"$DESTINATION\""]; } -- (BOOL)_extractDMG:(NSString *)archivePath +- (BOOL)_extractDMG { // get a unique mount point path NSString *mountPoint = [[archivePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"mp"]; @@ -99,7 +99,7 @@ return YES; } -- (void)_unarchivePath:(NSString *)path +- (void)_unarchive { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; @@ -107,33 +107,32 @@ // The methods take the path of the archive to extract. They return a BOOL indicating whether // we should continue with the update; returns NO if an error occurred. NSDictionary *commandDictionary = [NSDictionary dictionaryWithObjectsAndKeys: - @"_extractTBZ:", @".tbz", - @"_extractTBZ:", @".tar.bz2", - @"_extractTGZ:", @".tgz", - @"_extractTGZ:", @".tar.gz", - @"_extractTAR:", @".tar", - @"_extractZIP:", @".zip", - @"_extractDMG:", @".dmg", + @"_extractTBZ", @".tbz", + @"_extractTBZ", @".tar.bz2", + @"_extractTGZ", @".tgz", + @"_extractTGZ", @".tar.gz", + @"_extractTAR", @".tar", + @"_extractZIP", @".zip", + @"_extractDMG", @".dmg", nil]; SEL command = NULL; - NSString *theLastPathComponent = [[path lastPathComponent] lowercaseString]; + NSString *theLastPathComponent = [[archivePath lastPathComponent] lowercaseString]; NSEnumerator *theEnumerator = [[commandDictionary allKeys] objectEnumerator]; NSString *theExtension = NULL; while ((theExtension = [theEnumerator nextObject]) != NULL) - { + { if ([[theLastPathComponent substringFromIndex:[theLastPathComponent length] - [theExtension length]] isEqualToString:theExtension]) - { + { command = NSSelectorFromString([commandDictionary objectForKey:theExtension]); break; - } } + } BOOL result; if (command) { NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:command]]; [invocation setSelector:command]; - [invocation setArgument:&path atIndex:2]; // 0 and 1 are private! [invocation invokeWithTarget:self]; [invocation getReturnValue:&result]; } @@ -156,7 +155,8 @@ - (void)unarchivePath:(NSString *)path { - [NSThread detachNewThreadSelector:@selector(_unarchivePath:) toTarget:self withObject:path]; + archivePath = [path copy]; + [NSThread detachNewThreadSelector:@selector(_unarchive) toTarget:self withObject:nil]; } - (void)setDelegate:del @@ -164,4 +164,19 @@ delegate = del; } +- (void)cleanUp +{ + if ([[archivePath pathExtension] isEqualToString:@".dmg"]) + { + [NSTask launchedTaskWithLaunchPath:@"/usr/bin/hdiutil" arguments:[NSArray arrayWithObjects:@"detach", [archivePath stringByDeletingLastPathComponent], @"-force", nil]]; + } + [[NSFileManager defaultManager] removeFileAtPath:archivePath handler:nil]; +} + +- (void)dealloc +{ + [archivePath release]; + [super dealloc]; +} + @end diff --git a/SUUpdater.h b/SUUpdater.h index 3e8391b0..69757ab6 100644 --- a/SUUpdater.h +++ b/SUUpdater.h @@ -15,7 +15,7 @@ // .zip, .dmg, .tar, .tbz, .tgz archives are supported at this time. -@class SUAppcastItem, SUUpdateAlert, SUStatusController; +@class SUAppcastItem, SUUpdateAlert, SUStatusController, SUUnarchiver; @interface SUUpdater : NSObject { SUAppcastItem *updateItem; @@ -33,6 +33,8 @@ NSBundle *hostBundle; id delegate; + + SUUnarchiver *unarchiver; } - (void)setHostBundle:(NSBundle *)hostBundle; diff --git a/SUUpdater.m b/SUUpdater.m index 6dedf7dd..aa9aafca 100644 --- a/SUUpdater.m +++ b/SUUpdater.m @@ -436,9 +436,7 @@ static SUUpdater *sharedUpdater = nil; } - (void)unarchiverDidFinish:(SUUnarchiver *)ua -{ - [ua autorelease]; - +{ if ([self isAutomaticallyUpdating]) { [self installAndRestart:self]; @@ -454,7 +452,7 @@ static SUUpdater *sharedUpdater = nil; - (void)unarchiverDidFail:(SUUnarchiver *)ua { - [ua autorelease]; + [ua release]; [self showUpdateErrorAlertWithInfo:SULocalizedString(@"An error occurred while extracting the archive. Please try again later.", nil)]; [self abandonUpdate]; } @@ -477,7 +475,7 @@ static SUUpdater *sharedUpdater = nil; } } - SUUnarchiver *unarchiver = [[SUUnarchiver alloc] init]; + unarchiver = [[SUUnarchiver alloc] init]; [unarchiver setDelegate:self]; [unarchiver unarchivePath:downloadPath]; // asynchronous extraction! } @@ -495,70 +493,6 @@ static SUUpdater *sharedUpdater = nil; [statusController beginActionWithTitle:SULocalizedString(@"Installing update...", nil) maxProgressValue:0 statusText:nil]; [statusController setButtonEnabled:NO]; - // Hack to force us to wait for the UI to update. - NSEvent *event; - while((event = [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:nil inMode:NSDefaultRunLoopMode dequeue:YES])) - [NSApp sendEvent:event]; - - // Search subdirectories for the application - NSString *currentFile, *newAppDownloadPath = nil, *bundleFileName = [[hostBundle bundlePath] lastPathComponent]; - BOOL isPackage = NO; - NSDirectoryEnumerator *dirEnum = [[NSFileManager defaultManager] enumeratorAtPath:[downloadPath stringByDeletingLastPathComponent]]; - while ((currentFile = [dirEnum nextObject])) - { - // Some DMGs have symlinks into /Applications! That's no good! And there's no point in looking in bundles. - if ([[NSFileManager defaultManager] isAliasFolderAtPath:[[downloadPath stringByDeletingLastPathComponent] stringByAppendingPathComponent:currentFile]] || - [[currentFile pathExtension] isEqualToString:[[hostBundle bundlePath] pathExtension]] || - [[currentFile pathExtension] isEqualToString:@"pkg"] || - [[currentFile pathExtension] isEqualToString:@"mpkg"]) - { - [dirEnum skipDescendents]; - } - - if ([[currentFile lastPathComponent] isEqualToString:bundleFileName]) // We found one! - { - isPackage = NO; - newAppDownloadPath = [[downloadPath stringByDeletingLastPathComponent] stringByAppendingPathComponent:currentFile]; - break; - } - else if (([[currentFile pathExtension] isEqualToString:@"pkg"] || [[currentFile pathExtension] isEqualToString:@"mpkg"]) && - [[[currentFile lastPathComponent] stringByDeletingPathExtension] isEqualToString:[bundleFileName stringByDeletingPathExtension]]) - { - isPackage = YES; - newAppDownloadPath = [[downloadPath stringByDeletingLastPathComponent] stringByAppendingPathComponent:currentFile]; - break; - } - } - - if (![[NSFileManager defaultManager] fileExistsAtPath:newAppDownloadPath]) - { - NSLog(@"The update archive didn't contain an application or package with the proper name: %@ or %@.", bundleFileName, [[bundleFileName stringByDeletingPathExtension] stringByAppendingPathComponent:@".[m]pkg"]); - [self showUpdateErrorAlertWithInfo:SULocalizedString(@"An error occurred during installation. Please try again later.", nil)]; - [self abandonUpdate]; - return; - } - - // Alright, *now* we can actually install the new version. - int processIdentifierToWatch = [[NSProcessInfo processInfo] processIdentifier]; - if (isPackage) - { - NSString *installerPath = [[NSWorkspace sharedWorkspace] absolutePathForAppBundleWithIdentifier:@"com.apple.installer"]; - installerPath = [installerPath stringByAppendingString:@"/Contents/MacOS/Installer"]; - NSTask *installer = [NSTask launchedTaskWithLaunchPath:installerPath arguments:[NSArray arrayWithObjects:newAppDownloadPath, nil]]; - processIdentifierToWatch = [installer processIdentifier]; // We want to wait until the installer quits. - } - else - { - if (![[NSFileManager defaultManager] copyPath:newAppDownloadPath - overPath:[hostBundle bundlePath] - withAuthentication:![self isAutomaticallyUpdating]]) - { - [self showUpdateErrorAlertWithInfo:[NSString stringWithFormat:SULocalizedString(@"%@ can't install the update! Make sure you have enough disk space.", nil), [hostBundle name]]]; - [self abandonUpdate]; - return; - } - } - // Prompt for permission to restart if we're automatically updating. if ([self isAutomaticallyUpdating]) { @@ -570,24 +504,38 @@ static SUUpdater *sharedUpdater = nil; } } - // This is really sloppy and coupled, but I can't think of a better way to deal with this. - // If we've got a DMG, we've mounted it; now we've got to unmount it. - if ([[[downloadPath pathExtension] lowercaseString] isEqualToString:@"dmg"]) - { - [NSTask launchedTaskWithLaunchPath:@"/usr/bin/hdiutil" arguments:[NSArray arrayWithObjects:@"detach", [newAppDownloadPath stringByDeletingLastPathComponent], @"-force", nil]]; - } + [SUInstaller installFromUpdateFolder:[downloadPath stringByDeletingLastPathComponent] overHostBundle:hostBundle delegate:self]; +} +- (void)installerFinishedForHostBundle:(NSBundle *)hb +{ + if (hb != hostBundle) { return; } + + [unarchiver cleanUp]; [[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterWillRestartNotification object:self]; NSString *relaunchPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"relaunch" ofType:nil]; - @try { - [NSTask launchedTaskWithLaunchPath:relaunchPath arguments:[NSArray arrayWithObjects:[hostBundle bundlePath], [NSString stringWithFormat:@"%d", processIdentifierToWatch], nil]]; - } @catch (NSException *e) { - NSLog(@"relaunch error: %@", e); + @try + { + [NSTask launchedTaskWithLaunchPath:relaunchPath arguments:[NSArray arrayWithObjects:[hostBundle bundlePath], [NSString stringWithFormat:@"%d", [[NSProcessInfo processInfo] processIdentifier]], nil]]; + } + @catch (NSException *e) + { + NSLog(@"Sparkle relaunch error: %@", e); + [self showUpdateErrorAlertWithInfo:[NSString stringWithFormat:SULocalizedString(@"Couldn't restart %1$@, but the new version will be available next time you run %1$@.", nil), [hostBundle name]]]; + [self abandonUpdate]; } [NSApp terminate:self]; } +- (void)installerForHostBundle:(NSBundle *)hb failedWithError:(NSError *)error +{ + if (hb != hostBundle) { return; } + NSLog(@"Sparkle Installation Error: %@", [error localizedDescription]); + [self showUpdateErrorAlertWithInfo:SULocalizedString(@"An error occurred during installation. Please try again later.", nil)]; + [self abandonUpdate]; +} + #pragma mark Error handling - (void)showUpdateErrorAlertWithInfo:(NSString *)info diff --git a/Sparkle.h b/Sparkle.h index 655a4efb..a982185c 100644 --- a/Sparkle.h +++ b/Sparkle.h @@ -39,6 +39,7 @@ #import "SUAppcastItem.h" #import "SUAutomaticUpdateAlert.h" #import "SUConstants.h" +#import "SUInstaller.h" #import "SUStandardVersionComparator.h" #import "SUStatusChecker.h" #import "SUStatusController.h" diff --git a/Sparkle.xcodeproj/project.pbxproj b/Sparkle.xcodeproj/project.pbxproj index e32fec11..22b4b1f4 100644 --- a/Sparkle.xcodeproj/project.pbxproj +++ b/Sparkle.xcodeproj/project.pbxproj @@ -34,6 +34,12 @@ 6160E7E10D3B4A8800E9CD71 /* NTSynchronousTask.h in Headers */ = {isa = PBXBuildFile; fileRef = 610EC1C00CF3914D00AE239E /* NTSynchronousTask.h */; settings = {ATTRIBUTES = (Public, ); }; }; 6171D9070D57B81800BFE886 /* NSFileManager+Aliases.h in Headers */ = {isa = PBXBuildFile; fileRef = 6171D9050D57B81800BFE886 /* NSFileManager+Aliases.h */; settings = {ATTRIBUTES = (Public, ); }; }; 6171D9080D57B81800BFE886 /* NSFileManager+Aliases.m in Sources */ = {isa = PBXBuildFile; fileRef = 6171D9060D57B81800BFE886 /* NSFileManager+Aliases.m */; }; + 618FA5010DAE88B40026945C /* SUInstaller.h in Headers */ = {isa = PBXBuildFile; fileRef = 618FA4FF0DAE88B40026945C /* SUInstaller.h */; }; + 618FA5020DAE88B40026945C /* SUInstaller.m in Sources */ = {isa = PBXBuildFile; fileRef = 618FA5000DAE88B40026945C /* SUInstaller.m */; }; + 618FA5050DAE8AB80026945C /* SUPlainInstaller.h in Headers */ = {isa = PBXBuildFile; fileRef = 618FA5030DAE8AB80026945C /* SUPlainInstaller.h */; }; + 618FA5060DAE8AB80026945C /* SUPlainInstaller.m in Sources */ = {isa = PBXBuildFile; fileRef = 618FA5040DAE8AB80026945C /* SUPlainInstaller.m */; }; + 618FA5220DAE8E8A0026945C /* SUPackageInstaller.h in Headers */ = {isa = PBXBuildFile; fileRef = 618FA5200DAE8E8A0026945C /* SUPackageInstaller.h */; }; + 618FA5230DAE8E8A0026945C /* SUPackageInstaller.m in Sources */ = {isa = PBXBuildFile; fileRef = 618FA5210DAE8E8A0026945C /* SUPackageInstaller.m */; }; 6196CFF909C72148000DC222 /* SUStatusController.h in Headers */ = {isa = PBXBuildFile; fileRef = 6196CFE309C71ADE000DC222 /* SUStatusController.h */; settings = {ATTRIBUTES = (Public, ); }; }; 6196CFFA09C72149000DC222 /* SUStatusController.m in Sources */ = {isa = PBXBuildFile; fileRef = 6196CFE409C71ADE000DC222 /* SUStatusController.m */; }; 61A225930D1C3ADD00430CCD /* NSBundle+SUAdditions.h in Headers */ = {isa = PBXBuildFile; fileRef = 61A225910D1C3ADD00430CCD /* NSBundle+SUAdditions.h */; settings = {ATTRIBUTES = (Public, ); }; }; @@ -149,6 +155,12 @@ 615AE3CF0D64DC40001CA7BD /* SUModelTranslation.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = SUModelTranslation.plist; sourceTree = ""; }; 6171D9050D57B81800BFE886 /* NSFileManager+Aliases.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "NSFileManager+Aliases.h"; sourceTree = ""; }; 6171D9060D57B81800BFE886 /* NSFileManager+Aliases.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSFileManager+Aliases.m"; sourceTree = ""; }; + 618FA4FF0DAE88B40026945C /* SUInstaller.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SUInstaller.h; sourceTree = ""; }; + 618FA5000DAE88B40026945C /* SUInstaller.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SUInstaller.m; sourceTree = ""; }; + 618FA5030DAE8AB80026945C /* SUPlainInstaller.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SUPlainInstaller.h; sourceTree = ""; }; + 618FA5040DAE8AB80026945C /* SUPlainInstaller.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SUPlainInstaller.m; sourceTree = ""; }; + 618FA5200DAE8E8A0026945C /* SUPackageInstaller.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SUPackageInstaller.h; sourceTree = ""; }; + 618FA5210DAE8E8A0026945C /* SUPackageInstaller.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SUPackageInstaller.m; sourceTree = ""; }; 6196CFE309C71ADE000DC222 /* SUStatusController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SUStatusController.h; sourceTree = ""; }; 6196CFE409C71ADE000DC222 /* SUStatusController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SUStatusController.m; sourceTree = ""; }; 61A225910D1C3ADD00430CCD /* NSBundle+SUAdditions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "NSBundle+SUAdditions.h"; sourceTree = ""; }; @@ -365,6 +377,7 @@ 61299B3909CB055000B7442F /* Appcast Support */, 61299B3809CB053D00B7442F /* Cocoa Categories */, 61299B3A09CB056100B7442F /* User Interface */, + 618FA6DB0DB485440026945C /* Installation */, 61B5F8F309C4CE5900B25A18 /* Utilities */, 61B5F8E309C4CE3C00B25A18 /* SUUpdater.h */, 61B5F8E409C4CE3C00B25A18 /* SUUpdater.m */, @@ -431,6 +444,19 @@ name = "User Interface"; sourceTree = ""; }; + 618FA6DB0DB485440026945C /* Installation */ = { + isa = PBXGroup; + children = ( + 618FA4FF0DAE88B40026945C /* SUInstaller.h */, + 618FA5000DAE88B40026945C /* SUInstaller.m */, + 618FA5030DAE8AB80026945C /* SUPlainInstaller.h */, + 618FA5040DAE8AB80026945C /* SUPlainInstaller.m */, + 618FA5200DAE8E8A0026945C /* SUPackageInstaller.h */, + 618FA5210DAE8E8A0026945C /* SUPackageInstaller.m */, + ); + name = Installation; + sourceTree = ""; + }; 61B5F8F309C4CE5900B25A18 /* Utilities */ = { isa = PBXGroup; children = ( @@ -523,6 +549,9 @@ 6171D9070D57B81800BFE886 /* NSFileManager+Aliases.h in Headers */, 61180BCA0D64138900B4E0D1 /* SUWindowController.h in Headers */, 61C1F2780DA066C2007ACE13 /* NSFileManager+ExtendedAttributes.h in Headers */, + 618FA5010DAE88B40026945C /* SUInstaller.h in Headers */, + 618FA5050DAE8AB80026945C /* SUPlainInstaller.h in Headers */, + 618FA5220DAE8E8A0026945C /* SUPackageInstaller.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -700,6 +729,9 @@ 6171D9080D57B81800BFE886 /* NSFileManager+Aliases.m in Sources */, 61180BCB0D64138900B4E0D1 /* SUWindowController.m in Sources */, 61C1F2790DA066C2007ACE13 /* NSFileManager+ExtendedAttributes.m in Sources */, + 618FA5020DAE88B40026945C /* SUInstaller.m in Sources */, + 618FA5060DAE8AB80026945C /* SUPlainInstaller.m in Sources */, + 618FA5230DAE8E8A0026945C /* SUPackageInstaller.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; };