Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

Allow non-admin accounts to update QS in protected directories. Fixes #521 #1159

Merged
merged 8 commits into from

2 participants

@pjrobertson
Owner

Finally :)
Only took me all weekend…!

Background info on Auth:

Apple is deprecating everything under the sun that allows apps to run in a 'privileged' environment. The currently recommended way is to use a helper app and communicate with this app using XPC or similar (NSMachPorts). See the SMJobBless example project for a little more info.

I chose to use Sparkle to deal with our authentication problems as I thought I'd be an easy solution, unfortunately, they are also using the deprecated methods (as of 10.7) for authentication. Looks like they haven't gone down the route of privileged helper apps (which require independent code signing… ugh!) yet.
I've decided to stick with it. The methods are deprecated, but hopefully if we still close to Sparkle this method won't die too soon

Background on Sparkle:

Since Sparkle is such a large framework, and we only really need one method, I have removed the submodule and added only the required (and butchered) files.
The files have been modified as little as possible, just enough so we don't have to #import the whole project. Hopefully they're still mostly intact that we can easily alter them as Sparkle alter their files.

So background aside, this pull means non admin users can download an update of QS to a protected directory, and be prompted with a dialogue asking for an admin password.
You may notice that in QSUpdateController the following steps are taken

  • Mount the .dmg in a temp folder
  • Copy the Quicksilver.app file in the .dmg to a temp folder in Application support/Quicksilver
  • Chown the Quicksilver.app file from step 2 to give it the right permissions
  • Copy the file from step 2 over the current install

The reason for step 2 is that the .dmg temp folder is read-only, so chown and move methods don't work on it (What Sparkle uses)


To test this:

  • Change the build number in Developer.xcconfig to say 3920
  • build and install in /Applications
  • Log in as a non admin user and run Quicksilver
  • Update from in the app

Sorry for the epic pull message, just… there's a lot to say, and a lot of reasoning behind the few changes!

pjrobertson added some commits
@pjrobertson pjrobertson remove Sparkle as a submodule d128b0a
@pjrobertson pjrobertson Remove the Sparkle directory from the .gitignore 9078f99
@pjrobertson pjrobertson Add the required (and modified) Sparkle files to the project
Modifications include:
* Remove unrequired #imports
* Replace SULog() with NSLog()
1dce3cd
@pjrobertson pjrobertson Use Sparkle's method for copying updates
* Tidy up and remove unused methods in NSApplication_BLTRExtensions
* Use the Sparkle method for copying with authentication as defined n SUPlainInstallerInternals
* Tidy up and remove unused methods from QSUpdateController
* Add extra checks to ensure the update is successful (no more silently dying)
* Add an extra step in the install/update process: copy the update to a writable location (App Support folder)
       * Required so that the permissions can correctly be set on the new update and 'moved' to the right location
15fe34d
@pjrobertson pjrobertson Use the QSApplicationSupportPath extern as opposed to hard coding it a00f25a
@pjrobertson pjrobertson Add a convenience method for creating app notifs (the method taking a…
…n NSDictionary is just too difficult to remember)
2c654ff
@pjrobertson pjrobertson Move a #define from two files into QSPaths 0c86607
@pjrobertson
Owner

P.S. you may need to rm -rf …/Sparkle before you attempt to merge this, sorry

@skurfer
Owner

Just trying it under my normal account to start and I get "It was not possible to decompress downloaded file." It appears to download something, but I'm not sure where it's dumping the file, so I can't verify.

Also, probably outside the scope of this pull request, but nothing in QSUpdateController is localized. :-)

@pjrobertson
Owner

I've only touched the - (NSString *)installAppFromDiskImage:(NSString *)path method, so I suggest adding a breakpoint there and seeing if it gets triggered/seeing what happens after this.

@skurfer
Owner

OK, updating from my admin account works. Trying with a non-admin user will have to wait until later.

@skurfer
Owner

I got a chance to test this and it seems to work as advertised. I am concerned about these two lines:

[manager removeItemAtPath:tempDirectory error:nil];
[manager removeItemAtPath:tempHoldDir error:nil];

Both of those paths are created using [NSString uniqueString]. It should never happen, but if for some reason that method returned nothing, those two lines would remove some things they shouldn't. Could we either test that they don't equal what should be their parent directories, or just hard-code some sensible value like @"QSApplicationUpdate"? Or maybe examine the error when creating the directory instead of passing nil? (We should probably be doing that in any case for something like this.)

Also, I see that setUpdateTimer returns tempHoldDir, but the path referred to by that string was just removed a few lines earlier, so what good does it do?

All in all nice, though. :-)

@pjrobertson
Owner

Good points, I've made the changes as you suggest.

Also, I see that setUpdateTimer returns tempHoldDir, but the path referred to by that string was just removed a few lines earlier, so what good does it do?

I assume you meant

-(NSString *)installAppFromDiskImage:(NSString *)path;

Returning anything signals to the calling method that it went OK. Probably having a BOOL is as simpler option, so I've done this

@skurfer
Owner

I assume you meant

-(NSString *)installAppFromDiskImage:(NSString *)path;

Yeah, sorry. Xcode doesn't parse that file correctly for some reason, so it was showing the wrong method up top.

Code looks good, but enough has changed that I feel like I need to actually test the process again, so I'll try to do that later.

@pjrobertson
Owner
@skurfer
Owner

Anything to keep me away from these plug-ins. I hate dealing with compilers and headers and crap. :-)

@skurfer skurfer merged commit 765fa06 into quicksilver:master
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Oct 7, 2012
  1. @pjrobertson
  2. @pjrobertson
  3. @pjrobertson

    Add the required (and modified) Sparkle files to the project

    pjrobertson authored
    Modifications include:
    * Remove unrequired #imports
    * Replace SULog() with NSLog()
  4. @pjrobertson

    Use Sparkle's method for copying updates

    pjrobertson authored
    * Tidy up and remove unused methods in NSApplication_BLTRExtensions
    * Use the Sparkle method for copying with authentication as defined n SUPlainInstallerInternals
    * Tidy up and remove unused methods from QSUpdateController
    * Add extra checks to ensure the update is successful (no more silently dying)
    * Add an extra step in the install/update process: copy the update to a writable location (App Support folder)
           * Required so that the permissions can correctly be set on the new update and 'moved' to the right location
  5. @pjrobertson
  6. @pjrobertson

    Add a convenience method for creating app notifs (the method taking a…

    pjrobertson authored
    …n NSDictionary is just too difficult to remember)
  7. @pjrobertson
Commits on Oct 25, 2012
  1. @pjrobertson
This page is out of date. Refresh to see the latest.
View
1  .gitignore
@@ -19,5 +19,4 @@ Developer.xcconfig
Quicksilver*.dmg
*.pyc
Quicksilver/SharedSupport/Changes*.html
-Quicksilver/Code-External/Sparkle
Quicksilver/Code-External/VDKQueue
View
3  .gitmodules
@@ -1,6 +1,3 @@
-[submodule "Quicksilver/Code-External/Sparkle"]
- path = Quicksilver/Code-External/Sparkle
- url = git://github.com/andymatuschak/Sparkle.git
[submodule "Quicksilver/Code-External/VDKQueue"]
path = Quicksilver/Code-External/VDKQueue
url = git://github.com/bdkjones/VDKQueue.git
View
2  Quicksilver/Code-App/QSSetupAssistant.m
@@ -273,7 +273,7 @@ - (IBAction)downloadPlugIns:(id)sender {
- (IBAction)finish:(id)sender {
// Create 'Actions' folder if it doesn't already exist
- NSString *actionsFolder = [@"~/Library/Application Support/Quicksilver/Actions"stringByExpandingTildeInPath];
+ NSString *actionsFolder = [QSApplicationSupportPath stringByAppendingPathComponent:@"/Actions/"];
[[NSFileManager defaultManager] createDirectoryAtPath:actionsFolder withIntermediateDirectories:YES attributes:nil error:nil];
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:kSetupAssistantCompleted];
View
3  Quicksilver/Code-App/QSUpdateController.h
@@ -33,10 +33,9 @@
//- (NSArray *)installPlugInFromCompressedFile:(NSString *)path;
//-(float) downloadProgress;
- (void)forceStartupCheck;
-- (NSString *)installAppFromCompressedFile:(NSString *)path;
- (NSArray *)extractFilesFromQSPkg:(NSString *)path toPath:(NSString *)tempDirectory;
- (IBAction)threadedRequestedCheckForUpdate:(id)sender;
- (void)finishAppInstall;
-- (NSString *)installAppFromDiskImage:(NSString *)path;
+- (BOOL)installAppFromDiskImage:(NSString *)path;
- (IBAction)threadedCheckForUpdate:(id)sender;
@end
View
106 Quicksilver/Code-App/QSUpdateController.m
@@ -342,17 +342,16 @@ - (void)finishAppInstall {
update = (selection == NSAlertDefaultReturn);
}
- //[self installAppFromCompressedFile:path];
- NSString *installPath = nil;
+ BOOL installSuccessful = NO;
if (update) {
- installPath = [self installAppFromDiskImage:path];
- if (!installPath) {
+ installSuccessful = [self installAppFromDiskImage:path];
+ if (!installSuccessful) {
selection = NSRunInformationalAlertPanel(@"Installation Failed", @"It was not possible to decompress downloaded file.", @"Cancel Update", @"Download manually", nil);
if (selection == NSAlertAlternateReturn)
[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:kWebSiteURL]];
}
}
- if (installPath) {
+ if (installSuccessful) {
BOOL relaunch = [[NSUserDefaults standardUserDefaults] boolForKey:@"QSUpdateWithoutAsking"];
if (!relaunch) {
selection = NSRunInformationalAlertPanel(@"Installation Successful", @"A new version of Quicksilver has been installed. Quicksilver must relaunch to install it.", @"Relaunch", @"Relaunch Later", nil);
@@ -368,68 +367,91 @@ - (void)finishAppInstall {
[appDownload release], appDownload = nil;
}
-- (NSString *)installAppFromCompressedFile:(NSString *)path {
- NSFileManager *manager = [NSFileManager defaultManager];
-
- NSString *tempDirectory = [NSTemporaryDirectory() stringByAppendingPathComponent:@"QSUpdate"];
- [manager createDirectoryAtPath:tempDirectory withIntermediateDirectories:NO attributes:nil error:nil];
-
- [updateTask setName:@"Installing Update"];
- [updateTask setStatus:@"Extracting Data"];
- [updateTask setProgress:-1.0];
- NSArray *extracted = [self extractFilesFromQSPkg:path toPath:tempDirectory];
- if ([extracted count] != 1) {
- NSLog(@"App Update Error");
- return nil;
- }
-
- NSString *newAppVersionPath = [tempDirectory stringByAppendingPathComponent:[extracted lastObject]];
-
- [updateTask setStatus:@"Copying Application"];
- [NSApp replaceWithUpdateFromPath:newAppVersionPath];
- [updateTask setStatus:@"Cleaning Up"];
-
- return newAppVersionPath;
-}
-
-- (NSString *)installAppFromDiskImage:(NSString *)path {
+- (BOOL)installAppFromDiskImage:(NSString *)path {
NSFileManager *manager = [NSFileManager defaultManager];
+ // Create a temp directory to mount the .dmg
+ NSError *err = nil;
NSString *tempDirectory = [NSTemporaryDirectory() stringByAppendingPathComponent:[NSString uniqueString]];
- [manager createDirectoryAtPath:tempDirectory withIntermediateDirectories:NO attributes:nil error:nil];
+ [manager createDirectoryAtPath:tempDirectory withIntermediateDirectories:YES
+ attributes:nil error:&err];
+ if(err) {
+ NSLog(@"Error: %@", err);
+ return NO;
+ }
[updateTask setName:@"Installing Update"];
[updateTask setStatus:@"Verifying Data"];
[updateTask setProgress:-1.0];
+ // mount the .dmg
NSTask *task = [NSTask launchedTaskWithLaunchPath:@"/usr/bin/hdiutil"
arguments:[NSArray arrayWithObjects:@"attach", path, @"-nobrowse", @"-mountpoint", tempDirectory, nil]];
[task waitUntilExit];
if ([task terminationStatus] != 0)
- return nil;
-
+ return NO;
+
NSArray *extracted = [[manager contentsOfDirectoryAtPath:tempDirectory error:nil] pathsMatchingExtensions:[NSArray arrayWithObject:@"app"]];
if ([extracted count] != 1)
- return nil;
+ return NO;
+
+ NSString *mountedAppPath = [tempDirectory stringByAppendingPathComponent:[extracted lastObject]];
+ if (!mountedAppPath) {
+ return NO;
+ }
+
+ // Copy Quicksilver.app from the .dmg to a writeable folder (QS App Support folder)
+
+ // Attempt to delete any old update folders
+ if ([manager fileExistsAtPath:pUpdatePath]) {
+ [manager removeItemAtPath:pUpdatePath error:&err];
+ if (err) {
+ // report the error, but attempt to carry on
+ NSLog(@"Error: %@",err);
+ err = nil;
+ }
+ }
- NSString *newAppVersionPath = [tempDirectory stringByAppendingPathComponent:[extracted lastObject]];
- if (!newAppVersionPath)
- return nil;
+ [manager createDirectoryAtPath:pUpdatePath withIntermediateDirectories:YES attributes:nil error:&err];
+ if (err) {
+ NSLog(@"Error: %@",err);
+ return NO;
+ }
+ NSString *storedAppPath = [pUpdatePath stringByAppendingPathComponent:[mountedAppPath lastPathComponent]];
+ NSError *copyErr = nil;
+ [manager copyItemAtPath:mountedAppPath toPath:storedAppPath error:&copyErr];
+ if (copyErr) {
+ NSLog(@"Error: %@",copyErr);
+ return NO;
+ }
+
+ // Copy the Application over the current app
[updateTask setStatus:@"Copying Application"];
- [NSApp replaceWithUpdateFromPath:newAppVersionPath];
+ BOOL copySuccess = [NSApp moveToPath:[[NSBundle mainBundle] bundlePath] fromPath:storedAppPath];
[updateTask setStatus:@"Cleaning Up"];
+ // Unmount .dmg and tidyup
task = [NSTask launchedTaskWithLaunchPath:@"/usr/bin/hdiutil"
arguments:[NSArray arrayWithObjects:@"detach", tempDirectory, nil]];
[task waitUntilExit];
- [[NSFileManager defaultManager] removeItemAtPath:tempDirectory error:nil];
+ [manager removeItemAtPath:tempDirectory error:&err];
+ if(err) {
+ // Couldn't delete the temp directory. Not the end of the world: report and continue
+ NSLog(@"Error: %@",err);
+ err = nil;
+ }
+ [manager removeItemAtPath:pUpdatePath error:&err];
+ if(err) {
+ // Couldn't delete the update directory. Not the end of the world: report and continue
+ NSLog(@"Error: %@",err);
+ err = nil;
+ }
+
+ return copySuccess;
- [tempPath release];
- tempPath = nil;
- return newAppVersionPath;
}
- (NSArray *)extractFilesFromQSPkg:(NSString *)path toPath:(NSString *)tempDirectory {
1  Quicksilver/Code-External/Sparkle
@@ -1 +0,0 @@
-Subproject commit 9662452c09a2d87eb6e1154cab5fd6629e9ed7f6
View
113 Quicksilver/Code-External/Sparkle/SUConstants.h
@@ -0,0 +1,113 @@
+//
+// SUConstants.h
+// Sparkle
+//
+// Created by Andy Matuschak on 3/16/06.
+// Copyright 2006 Andy Matuschak. All rights reserved.
+//
+
+
+#ifndef SUCONSTANTS_H
+#define SUCONSTANTS_H
+
+// -----------------------------------------------------------------------------
+// Preprocessor flags:
+// -----------------------------------------------------------------------------
+
+// Turn off DSA signature check (practically invites man-in-the-middle attacks):
+#define ENDANGER_USERS_WITH_INSECURE_UPDATES 0
+
+// Sparkle usually doesn't allow downgrades as they're usually accidental, but
+// if your app has a downgrade function or URL handler, turn this on:
+#define PERMIT_AUTOMATED_DOWNGRADES 0
+
+// If your app file on disk is named "MyApp 1.1b4", Sparkle usually updates it
+// in place, giving you an app named 1.1b4 that is actually 1.2. Turn the
+// following on to always reset the name back to "MyApp":
+#define NORMALIZE_INSTALLED_APP_NAME 0
+
+
+#define TRY_TO_APPEND_VERSION_NUMBER 1
+
+// -----------------------------------------------------------------------------
+// Notifications:
+// -----------------------------------------------------------------------------
+
+extern NSString *const SUUpdaterWillRestartNotification;
+
+extern NSString *const SUTechnicalErrorInformationKey;
+
+// -----------------------------------------------------------------------------
+// PList keys::
+// -----------------------------------------------------------------------------
+
+extern NSString *const SUFeedURLKey;
+extern NSString *const SUHasLaunchedBeforeKey;
+extern NSString *const SUShowReleaseNotesKey;
+extern NSString *const SUSkippedVersionKey;
+extern NSString *const SUScheduledCheckIntervalKey;
+extern NSString *const SULastCheckTimeKey;
+extern NSString *const SUPublicDSAKeyKey;
+extern NSString *const SUPublicDSAKeyFileKey;
+extern NSString *const SUAutomaticallyUpdateKey;
+extern NSString *const SUAllowsAutomaticUpdatesKey;
+extern NSString *const SUEnableAutomaticChecksKey;
+extern NSString *const SUEnableAutomaticChecksKeyOld;
+extern NSString *const SUEnableSystemProfilingKey;
+extern NSString *const SUSendProfileInfoKey;
+extern NSString *const SULastProfileSubmitDateKey;
+extern NSString *const SUPromptUserOnFirstLaunchKey;
+extern NSString *const SUFixedHTMLDisplaySizeKey;
+extern NSString *const SUKeepDownloadOnFailedInstallKey;
+extern NSString *const SUDefaultsDomainKey;
+
+// -----------------------------------------------------------------------------
+// Errors:
+// -----------------------------------------------------------------------------
+
+extern NSString *const SUSparkleErrorDomain;
+// Appcast phase errors.
+extern OSStatus SUAppcastParseError;
+extern OSStatus SUNoUpdateError;
+extern OSStatus SUAppcastError;
+extern OSStatus SURunningFromDiskImageError;
+
+// Downlaod phase errors.
+extern OSStatus SUTemporaryDirectoryError;
+
+// Extraction phase errors.
+extern OSStatus SUUnarchivingError;
+extern OSStatus SUSignatureError;
+
+// Installation phase errors.
+extern OSStatus SUFileCopyFailure;
+extern OSStatus SUAuthenticationFailure;
+extern OSStatus SUMissingUpdateError;
+extern OSStatus SUMissingInstallerToolError;
+extern OSStatus SURelaunchError;
+extern OSStatus SUInstallationError;
+extern OSStatus SUDowngradeError;
+
+
+// -----------------------------------------------------------------------------
+// NSInteger fixer-upper:
+// -----------------------------------------------------------------------------
+
+// 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
+ #ifdef NS_BUILD_32_LIKE_64
+ typedef long NSInteger;
+ typedef unsigned long NSUInteger;
+ #else
+ typedef int NSInteger;
+ typedef unsigned int NSUInteger;
+ #endif
+ #define NSIntegerMax LONG_MAX
+ #define NSIntegerMin LONG_MIN
+ #define NSUIntegerMax ULONG_MAX
+ #define NSINTEGER_DEFINED 1
+#endif
+
+
+#endif
View
52 Quicksilver/Code-External/Sparkle/SUConstants.m
@@ -0,0 +1,52 @@
+//
+// SUConstants.m
+// Sparkle
+//
+// Created by Andy Matuschak on 3/16/06.
+// Copyright 2006 Andy Matuschak. All rights reserved.
+//
+
+#import "SUConstants.h"
+
+NSString *const SUUpdaterWillRestartNotification = @"SUUpdaterWillRestartNotificationName";
+NSString *const SUTechnicalErrorInformationKey = @"SUTechnicalErrorInformation";
+
+NSString *const SUHasLaunchedBeforeKey = @"SUHasLaunchedBefore";
+NSString *const SUFeedURLKey = @"SUFeedURL";
+NSString *const SUShowReleaseNotesKey = @"SUShowReleaseNotes";
+NSString *const SUSkippedVersionKey = @"SUSkippedVersion";
+NSString *const SUScheduledCheckIntervalKey = @"SUScheduledCheckInterval";
+NSString *const SULastCheckTimeKey = @"SULastCheckTime";
+NSString *const SUExpectsDSASignatureKey = @"SUExpectsDSASignature";
+NSString *const SUPublicDSAKeyKey = @"SUPublicDSAKey";
+NSString *const SUPublicDSAKeyFileKey = @"SUPublicDSAKeyFile";
+NSString *const SUAutomaticallyUpdateKey = @"SUAutomaticallyUpdate";
+NSString *const SUAllowsAutomaticUpdatesKey = @"SUAllowsAutomaticUpdates";
+NSString *const SUEnableSystemProfilingKey = @"SUEnableSystemProfiling";
+NSString *const SUEnableAutomaticChecksKey = @"SUEnableAutomaticChecks";
+NSString *const SUEnableAutomaticChecksKeyOld = @"SUCheckAtStartup";
+NSString *const SUSendProfileInfoKey = @"SUSendProfileInfo";
+NSString *const SULastProfileSubmitDateKey = @"SULastProfileSubmissionDate";
+NSString *const SUPromptUserOnFirstLaunchKey = @"SUPromptUserOnFirstLaunch";
+NSString *const SUFixedHTMLDisplaySizeKey = @"SUFixedHTMLDisplaySize";
+NSString *const SUKeepDownloadOnFailedInstallKey = @"SUKeepDownloadOnFailedInstall";
+NSString *const SUDefaultsDomainKey = @"SUDefaultsDomain";
+
+NSString *const SUSparkleErrorDomain = @"SUSparkleErrorDomain";
+OSStatus SUAppcastParseError = 1000;
+OSStatus SUNoUpdateError = 1001;
+OSStatus SUAppcastError = 1002;
+OSStatus SURunningFromDiskImageError = 1003;
+
+OSStatus SUTemporaryDirectoryError = 2000;
+
+OSStatus SUUnarchivingError = 3000;
+OSStatus SUSignatureError = 3001;
+
+OSStatus SUFileCopyFailure = 4000;
+OSStatus SUAuthenticationFailure = 4001;
+OSStatus SUMissingUpdateError = 4002;
+OSStatus SUMissingInstallerToolError = 4003;
+OSStatus SURelaunchError = 4004;
+OSStatus SUInstallationError = 4005;
+OSStatus SUDowngradeError = 4006;
View
20 Quicksilver/Code-External/Sparkle/SUPlainInstallerInternals.h
@@ -0,0 +1,20 @@
+//
+// SUPlainInstallerInternals.m
+// Sparkle
+//
+// Created by Andy Matuschak on 3/9/06.
+// Copyright 2006 Andy Matuschak. All rights reserved.
+//
+
+#ifndef SUPLAININSTALLERINTERNALS_H
+#define SUPLAININSTALLERINTERNALS_H
+
+@interface SUPlainInstaller : NSObject
++ (NSString *)temporaryNameForPath:(NSString *)path;
++ (BOOL)copyPathWithAuthentication:(NSString *)src overPath:(NSString *)dst temporaryName:(NSString *)tmp error:(NSError **)error;
++ (void)_movePathToTrash:(NSString *)path;
++ (BOOL)_removeFileAtPath:(NSString *)path error: (NSError**)error;
++ (BOOL)_removeFileAtPathWithForcedAuthentication:(NSString *)src error:(NSError **)error;
+@end
+
+#endif
View
602 Quicksilver/Code-External/Sparkle/SUPlainInstallerInternals.m
@@ -0,0 +1,602 @@
+//
+// SUPlainInstallerInternals.m
+// Sparkle
+//
+// Created by Andy Matuschak on 3/9/06.
+// Copyright 2006 Andy Matuschak. All rights reserved.
+//
+
+#import "SUPlainInstallerInternals.h"
+#import "SUConstants.h"
+
+#import <CoreServices/CoreServices.h>
+#import <Security/Security.h>
+#import <sys/stat.h>
+#import <sys/wait.h>
+#import <dirent.h>
+#import <unistd.h>
+#import <sys/param.h>
+
+
+@interface SUPlainInstaller (MMExtendedAttributes)
+// Removes the directory tree rooted at |root| from the file quarantine.
+// The quarantine was introduced on Mac OS X 10.5 and is described at:
+//
+// http://developer.apple.com/releasenotes/Carbon/RN-LaunchServices/index.html
+//#apple_ref/doc/uid/TP40001369-DontLinkElementID_2
+//
+// If |root| is not a directory, then it alone is removed from the quarantine.
+// Symbolic links, including |root| if it is a symbolic link, will not be
+// traversed.
+//
+// Ordinarily, the quarantine is managed by calling LSSetItemAttribute
+// to set the kLSItemQuarantineProperties attribute to a dictionary specifying
+// the quarantine properties to be applied. However, it does not appear to be
+// possible to remove an item from the quarantine directly through any public
+// Launch Services calls. Instead, this method takes advantage of the fact
+// that the quarantine is implemented in part by setting an extended attribute,
+// "com.apple.quarantine", on affected files. Removing this attribute is
+// sufficient to remove files from the quarantine.
++ (void)releaseFromQuarantine:(NSString*)root;
+@end
+
+// Authorization code based on generous contribution from Allan Odgaard. Thanks, Allan!
+
+static BOOL AuthorizationExecuteWithPrivilegesAndWait(AuthorizationRef authorization, const char* executablePath, AuthorizationFlags options, const char* const* arguments)
+{
+ // *** MUST BE SAFE TO CALL ON NON-MAIN THREAD!
+
+ sig_t oldSigChildHandler = signal(SIGCHLD, SIG_DFL);
+ 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)
+ returnValue = NO;
+ }
+ else
+ returnValue = NO;
+
+ signal(SIGCHLD, oldSigChildHandler);
+ return returnValue;
+}
+
+@implementation SUPlainInstaller
+
++ (NSString *)temporaryNameForPath:(NSString *)path
+{
+ // Let's try to read the version number so the filename will be more meaningful.
+ NSString *postFix;
+ NSString *version;
+ if ((version = [[NSBundle bundleWithPath:path] objectForInfoDictionaryKey:@"CFBundleVersion"]) && ![version isEqualToString:@""])
+ {
+ // We'll clean it up a little for safety.
+ // The cast is necessary because of a bug in the headers in pre-10.5 SDKs
+ NSMutableCharacterSet *validCharacters = (id)[NSMutableCharacterSet alphanumericCharacterSet];
+ [validCharacters formUnionWithCharacterSet:[NSCharacterSet characterSetWithCharactersInString:@".-()"]];
+ postFix = [version stringByTrimmingCharactersInSet:[validCharacters invertedSet]];
+ }
+ else
+ postFix = @"old";
+ NSString *prefix = [[path stringByDeletingPathExtension] stringByAppendingFormat:@" (%@)", postFix];
+ NSString *tempDir = [prefix stringByAppendingPathExtension:[path pathExtension]];
+ // Now let's make sure we get a unique path.
+ unsigned int cnt=2;
+ while ([[NSFileManager defaultManager] fileExistsAtPath:tempDir] && cnt <= 999)
+ tempDir = [NSString stringWithFormat:@"%@ %u.%@", prefix, cnt++, [path pathExtension]];
+ return [tempDir lastPathComponent];
+}
+
++ (NSString *)_temporaryCopyNameForPath:(NSString *)path didFindTrash: (BOOL*)outDidFindTrash
+{
+ // *** MUST BE SAFE TO CALL ON NON-MAIN THREAD!
+ NSString *tempDir = nil;
+
+ UInt8 trashPath[MAXPATHLEN +1] = { 0 };
+ FSRef trashRef, pathRef;
+ FSVolumeRefNum vSrcRefNum = kFSInvalidVolumeRefNum;
+ FSCatalogInfo catInfo;
+ memset( &catInfo, 0, sizeof(catInfo) );
+ OSStatus err = FSPathMakeRef( (UInt8*) [path fileSystemRepresentation], &pathRef, NULL );
+ if( err == noErr )
+ {
+ err = FSGetCatalogInfo( &pathRef, kFSCatInfoVolume, &catInfo, NULL, NULL, NULL );
+ vSrcRefNum = catInfo.volume;
+ }
+ if( err == noErr )
+ err = FSFindFolder( vSrcRefNum, kTrashFolderType, kCreateFolder, &trashRef );
+ if( err == noErr )
+ err = FSGetCatalogInfo( &trashRef, kFSCatInfoVolume, &catInfo, NULL, NULL, NULL );
+ if( err == noErr && vSrcRefNum != catInfo.volume )
+ err = nsvErr; // Couldn't find a trash folder on same volume as given path. Docs say this may happen in the future.
+ if( err == noErr )
+ err = FSRefMakePath( &trashRef, trashPath, MAXPATHLEN );
+ if( err == noErr )
+ tempDir = [[NSFileManager defaultManager] stringWithFileSystemRepresentation: (char*) trashPath length: strlen((char*) trashPath)];
+ if( outDidFindTrash )
+ *outDidFindTrash = (tempDir != nil);
+ if( !tempDir )
+ tempDir = [path stringByDeletingLastPathComponent];
+
+ // Let's try to read the version number so the filename will be more meaningful.
+ #if TRY_TO_APPEND_VERSION_NUMBER
+ NSString *postFix = nil;
+ NSString *version = nil;
+ if ((version = [[NSBundle bundleWithPath: path] objectForInfoDictionaryKey:@"CFBundleVersion"]) && ![version isEqualToString:@""])
+ {
+ // We'll clean it up a little for safety.
+ // The cast is necessary because of a bug in the headers in pre-10.5 SDKs
+ NSMutableCharacterSet *validCharacters = (id)[NSMutableCharacterSet alphanumericCharacterSet];
+ [validCharacters formUnionWithCharacterSet:[NSCharacterSet characterSetWithCharactersInString:@".-()"]];
+ postFix = [version stringByTrimmingCharactersInSet:[validCharacters invertedSet]];
+ }
+ else
+ postFix = @"old";
+ NSString *prefix = [NSString stringWithFormat: @"%@ (%@)", [[path lastPathComponent] stringByDeletingPathExtension], postFix];
+ #else
+ NSString *prefix = [[path lastPathComponent] stringByDeletingPathExtension];
+ #endif
+ NSString *tempName = [prefix stringByAppendingPathExtension: [path pathExtension]];
+ tempDir = [tempDir stringByAppendingPathComponent: tempName];
+
+ // Now let's make sure we get a unique path.
+ int cnt=2;
+ while ([[NSFileManager defaultManager] fileExistsAtPath:tempDir] && cnt <= 9999)
+ tempDir = [[tempDir stringByDeletingLastPathComponent] stringByAppendingPathComponent: [NSString stringWithFormat:@"%@ %d.%@", prefix, cnt++, [path pathExtension]]];
+
+ return tempDir;
+}
+
++ (BOOL)_copyPathWithForcedAuthentication:(NSString *)src toPath:(NSString *)dst temporaryPath:(NSString *)tmp error:(NSError **)error
+{
+ // *** MUST BE SAFE TO CALL ON NON-MAIN THREAD!
+
+ const char* srcPath = [src fileSystemRepresentation];
+ const char* tmpPath = [tmp fileSystemRepresentation];
+ const char* dstPath = [dst fileSystemRepresentation];
+
+ struct stat dstSB;
+ if( stat(dstPath, &dstSB) != 0 ) // Doesn't exist yet, try containing folder.
+ {
+ const char* dstDirPath = [[dst stringByDeletingLastPathComponent] fileSystemRepresentation];
+ if( stat(dstDirPath, &dstSB) != 0 )
+ {
+ NSString *errorMessage = [NSString stringWithFormat:@"Stat on %@ during authenticated file copy failed.", dst];
+ if (error != NULL)
+ *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUFileCopyFailure userInfo:[NSDictionary dictionaryWithObject:errorMessage forKey:NSLocalizedDescriptionKey]];
+ return NO;
+ }
+ }
+
+ AuthorizationRef auth = NULL;
+ OSStatus authStat = errAuthorizationDenied;
+ while (authStat == errAuthorizationDenied) {
+ authStat = AuthorizationCreate(NULL,
+ kAuthorizationEmptyEnvironment,
+ kAuthorizationFlagDefaults,
+ &auth);
+ }
+
+ BOOL res = NO;
+ if (authStat == errAuthorizationSuccess) {
+ res = YES;
+
+ char uidgid[42];
+ snprintf(uidgid, sizeof(uidgid), "%u:%u",
+ dstSB.st_uid, dstSB.st_gid);
+
+ // 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 with "mv" in case it's moved across filesystems: if
+ // that happens, "mv" actually performs a copy and may result
+ // in the application being quarantined. It also needs to be
+ // done before "chown" changes ownership, because the ownership
+ // change will almost certainly make it impossible to change
+ // attributes to release the files from the quarantine.
+ if (res)
+ {
+ NSLog(@"releaseFromQuarantine");
+ [self performSelectorOnMainThread:@selector(releaseFromQuarantine:) withObject:dst waitUntilDone:YES];
+ }
+
+ if( res ) // Set permissions while it's still in source, so we have it with working and correct perms when it arrives at destination.
+ {
+ const char* coParams[] = { "-R", uidgid, srcPath, NULL };
+ res = AuthorizationExecuteWithPrivilegesAndWait( auth, "/usr/sbin/chown", kAuthorizationFlagDefaults, coParams );
+ if( !res )
+ NSLog( @"chown -R %s %s failed.", uidgid, srcPath );
+ }
+
+ BOOL haveDst = [[NSFileManager defaultManager] fileExistsAtPath: dst];
+ if( res && haveDst ) // If there's something at our tmp path (previous failed update or whatever) delete that first.
+ {
+ const char* rmParams[] = { "-rf", tmpPath, NULL };
+ res = AuthorizationExecuteWithPrivilegesAndWait( auth, "/bin/rm", kAuthorizationFlagDefaults, rmParams );
+ if( !res )
+ NSLog( @"rm failed" );
+ }
+
+ if( res && haveDst ) // Move old exe to tmp path.
+ {
+ const char* mvParams[] = { "-f", dstPath, tmpPath, NULL };
+ res = AuthorizationExecuteWithPrivilegesAndWait( auth, "/bin/mv", kAuthorizationFlagDefaults, mvParams );
+ if( !res )
+ NSLog( @"mv 1 failed" );
+ }
+
+ if( res ) // Move new exe to old exe's path.
+ {
+ const char* mvParams2[] = { "-f", srcPath, dstPath, NULL };
+ res = AuthorizationExecuteWithPrivilegesAndWait( auth, "/bin/mv", kAuthorizationFlagDefaults, mvParams2 );
+ if( !res )
+ NSLog( @"mv 2 failed" );
+ }
+
+// if( res && haveDst /*&& !foundTrash*/ ) // If we managed to put the old exe in the trash, leave it there for the user to delete or recover.
+// { // ... Otherwise we better delete it, wouldn't want dozens of old versions lying around next to the new one.
+// const char* rmParams2[] = { "-rf", tmpPath, NULL };
+// res = AuthorizationExecuteWithPrivilegesAndWait( auth, "/bin/rm", kAuthorizationFlagDefaults, rmParams2 );
+// }
+
+ 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 != nil)
+ *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:[NSDictionary dictionaryWithObject:errorMessage forKey:NSLocalizedDescriptionKey]];
+ }
+ }
+ else
+ {
+ if (error != nil)
+ *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:[NSDictionary dictionaryWithObject:@"Couldn't get permission to authenticate." forKey:NSLocalizedDescriptionKey]];
+ }
+ return res;
+}
+
++ (BOOL)_movePathWithForcedAuthentication:(NSString *)src toPath:(NSString *)dst error:(NSError **)error
+{
+ // *** MUST BE SAFE TO CALL ON NON-MAIN THREAD!
+
+ const char* srcPath = [src fileSystemRepresentation];
+ const char* dstPath = [dst fileSystemRepresentation];
+ const char* dstContainerPath = [[dst stringByDeletingLastPathComponent] fileSystemRepresentation];
+
+ struct stat dstSB;
+ stat(dstContainerPath, &dstSB);
+
+ AuthorizationRef auth = NULL;
+ OSStatus authStat = errAuthorizationDenied;
+ while( authStat == errAuthorizationDenied )
+ {
+ authStat = AuthorizationCreate(NULL,
+ kAuthorizationEmptyEnvironment,
+ kAuthorizationFlagDefaults,
+ &auth);
+ }
+
+ BOOL res = NO;
+ if (authStat == errAuthorizationSuccess)
+ {
+ res = YES;
+
+ char uidgid[42];
+ snprintf(uidgid, sizeof(uidgid), "%d:%d",
+ dstSB.st_uid, dstSB.st_gid);
+
+ if( res ) // Set permissions while it's still in source, so we have it with working and correct perms when it arrives at destination.
+ {
+ const char* coParams[] = { "-R", uidgid, srcPath, NULL };
+ res = AuthorizationExecuteWithPrivilegesAndWait( auth, "/usr/sbin/chown", kAuthorizationFlagDefaults, coParams );
+ if( !res )
+ NSLog(@"Can't set permissions");
+ }
+
+ BOOL haveDst = [[NSFileManager defaultManager] fileExistsAtPath: dst];
+ if( res && haveDst ) // If there's something at our tmp path (previous failed update or whatever) delete that first.
+ {
+ const char* rmParams[] = { "-rf", dstPath, NULL };
+ res = AuthorizationExecuteWithPrivilegesAndWait( auth, "/bin/rm", kAuthorizationFlagDefaults, rmParams );
+ if( !res )
+ NSLog(@"Can't remove destination file");
+ }
+
+ if( res ) // Move!.
+ {
+ const char* mvParams[] = { "-f", srcPath, dstPath, NULL };
+ res = AuthorizationExecuteWithPrivilegesAndWait( auth, "/bin/mv", kAuthorizationFlagDefaults, mvParams );
+ if( !res )
+ NSLog(@"Can't move source file");
+ }
+
+ 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 move 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)_removeFileAtPathWithForcedAuthentication:(NSString *)src error:(NSError **)error
+{
+ // *** MUST BE SAFE TO CALL ON NON-MAIN THREAD!
+
+ const char* srcPath = [src fileSystemRepresentation];
+
+ AuthorizationRef auth = NULL;
+ OSStatus authStat = errAuthorizationDenied;
+ while( authStat == errAuthorizationDenied )
+ {
+ authStat = AuthorizationCreate(NULL,
+ kAuthorizationEmptyEnvironment,
+ kAuthorizationFlagDefaults,
+ &auth);
+ }
+
+ BOOL res = NO;
+ if (authStat == errAuthorizationSuccess)
+ {
+ res = YES;
+
+ if( res ) // If there's something at our tmp path (previous failed update or whatever) delete that first.
+ {
+ const char* rmParams[] = { "-rf", srcPath, NULL };
+ res = AuthorizationExecuteWithPrivilegesAndWait( auth, "/bin/rm", kAuthorizationFlagDefaults, rmParams );
+ if( !res )
+ NSLog(@"Can't remove destination file");
+ }
+
+ 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 remove from %@ failed.", src];
+ 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)_removeFileAtPath:(NSString *)path error: (NSError**)error
+{
+ BOOL success = YES;
+#if MAC_OS_X_VERSION_MIN_REQUIRED <= MAC_OS_X_VERSION_10_4
+ if( ![[NSFileManager defaultManager] removeFileAtPath: path handler: nil] )
+#else
+ if( ![[NSFileManager defaultManager] removeItemAtPath: path error: NULL] )
+#endif
+ {
+ success = [self _removeFileAtPathWithForcedAuthentication: path error: error];
+ }
+
+ return success;
+}
+
++ (void)_movePathToTrash:(NSString *)path
+{
+ //NSLog(@"Moving %@ to the trash.", path);
+ NSInteger tag = 0;
+ if (![[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:[path stringByDeletingLastPathComponent] destination:@"" files:[NSArray arrayWithObject:[path lastPathComponent]] tag:&tag])
+ {
+ BOOL didFindTrash = NO;
+ NSString* trashPath = [self _temporaryCopyNameForPath: path didFindTrash: &didFindTrash];
+ if( didFindTrash )
+ {
+ NSError *err = nil;
+ if( ![self _movePathWithForcedAuthentication: path toPath: trashPath error: &err] )
+ NSLog(@"Sparkle error: couldn't move %@ to the trash (%@). %@", path, trashPath, err);
+ }
+ else
+ NSLog(@"Sparkle error: couldn't move %@ to the trash. This is often a sign of a permissions error.", path);
+ }
+ else
+ ;//NSLog(@"Moved %@ to the trash.", path);
+}
+
++ (BOOL)copyPathWithAuthentication:(NSString *)src overPath:(NSString *)dst temporaryName:(NSString *)tmp error:(NSError **)error
+{
+ FSRef srcRef, dstRef, dstDirRef, movedRef, tmpDirRef;
+ OSStatus err;
+ BOOL hadFileAtDest = NO, didFindTrash = NO;
+ NSString *tmpPath = [self _temporaryCopyNameForPath: dst didFindTrash: &didFindTrash];
+
+ // Make FSRef for destination:
+ err = FSPathMakeRefWithOptions((UInt8 *)[dst fileSystemRepresentation], kFSPathMakeRefDoNotFollowLeafSymlink, &dstRef, NULL);
+ hadFileAtDest = (err == noErr); // There is a file at the destination, move it aside. If we normalized the name, we might not get here, so don't error.
+ if( hadFileAtDest )
+ {
+ if (0 != access([dst fileSystemRepresentation], W_OK) || 0 != access([[dst stringByDeletingLastPathComponent] fileSystemRepresentation], W_OK))
+ {
+ return [self _copyPathWithForcedAuthentication:src toPath:dst temporaryPath:tmpPath error:error];
+ }
+ }
+ else
+ {
+ if (0 != access([[dst stringByDeletingLastPathComponent] fileSystemRepresentation], W_OK)
+ || 0 != access([[[dst stringByDeletingLastPathComponent] stringByDeletingLastPathComponent] fileSystemRepresentation], W_OK))
+ {
+ return [self _copyPathWithForcedAuthentication:src toPath:dst temporaryPath:tmpPath error:error];
+ }
+ }
+
+ if( hadFileAtDest )
+ {
+ err = FSPathMakeRef((UInt8 *)[[tmpPath stringByDeletingLastPathComponent] fileSystemRepresentation], &tmpDirRef, NULL);
+ if (err != noErr)
+ err = FSPathMakeRef((UInt8 *)[[dst stringByDeletingLastPathComponent] fileSystemRepresentation], &tmpDirRef, NULL);
+ }
+
+ err = FSPathMakeRef((UInt8 *)[[dst stringByDeletingLastPathComponent] fileSystemRepresentation], &dstDirRef, NULL);
+
+ if (err == noErr && hadFileAtDest)
+ {
+ if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_5)
+ {
+ NSFileManager *manager = [[[NSFileManager alloc] init] autorelease];
+ BOOL success = [manager moveItemAtPath:dst toPath:tmpPath error:error];
+ if (!success && hadFileAtDest)
+ {
+ if (error != NULL)
+ *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUFileCopyFailure userInfo:[NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"Couldn't move %@ to %@.", dst, tmpPath] forKey:NSLocalizedDescriptionKey]];
+ return NO;
+ }
+
+ } else {
+ err = FSMoveObjectSync(&dstRef, &tmpDirRef, (CFStringRef)[tmpPath lastPathComponent], &movedRef, 0);
+ if (err != noErr && hadFileAtDest)
+ {
+ if (error != NULL)
+ *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUFileCopyFailure userInfo:[NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"Couldn't move %@ to %@.", dst, tmpPath] forKey:NSLocalizedDescriptionKey]];
+ return NO;
+ }
+ }
+ }
+
+ err = FSPathMakeRef((UInt8 *)[src fileSystemRepresentation], &srcRef, NULL);
+ if (err == noErr)
+ {
+ if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_5)
+ {
+ NSFileManager *manager = [[[NSFileManager alloc] init] autorelease];
+ BOOL success = [manager copyItemAtPath:src toPath:dst error:error];
+ if (!success)
+ {
+ // We better move the old version back to its old location
+ if( hadFileAtDest )
+ success = [manager moveItemAtPath:tmpPath toPath:dst error:error];
+ if (error != NULL)
+ *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUFileCopyFailure userInfo:[NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"Couldn't move %@ to %@.", dst, tmpPath] forKey:NSLocalizedDescriptionKey]];
+ return NO;
+
+ }
+ } else {
+ err = FSCopyObjectSync(&srcRef, &dstDirRef, (CFStringRef)[dst lastPathComponent], NULL, 0);
+ if (err != noErr)
+ {
+ // We better move the old version back to its old location
+ if( hadFileAtDest )
+ FSMoveObjectSync(&movedRef, &dstDirRef, (CFStringRef)[dst lastPathComponent], &movedRef, 0);
+ if (error != NULL)
+ *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUFileCopyFailure userInfo:[NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"Couldn't copy %@ to %@.", 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 performSelectorOnMainThread:@selector(releaseFromQuarantine:) withObject:dst waitUntilDone:YES];
+
+ return YES;
+}
+
+@end
+
+#import <dlfcn.h>
+#import <errno.h>
+#import <sys/xattr.h>
+
+@implementation SUPlainInstaller (MMExtendedAttributes)
+
++ (int)removeXAttr:(const char*)name
+ fromFile:(NSString*)file
+ options:(int)options
+{
+ // *** MUST BE SAFE TO CALL ON NON-MAIN THREAD!
+
+ typedef int (*removexattr_type)(const char*, const char*, int);
+ // Reference removexattr directly, it's in the SDK.
+ static removexattr_type removexattr_func = removexattr;
+
+ // Make sure that the symbol is present. This checks the deployment
+ // target instead of the SDK so that it's able to catch dlsym failures
+ // as well as the null symbol that would result from building with the
+ // 10.4 SDK and a lower deployment target, and running on 10.3.
+ if (!removexattr_func) {
+ errno = ENOSYS;
+ return -1;
+ }
+
+ const char* path = NULL;
+ @try {
+ path = [file fileSystemRepresentation];
+ }
+ @catch (id exception) {
+ // -[NSString fileSystemRepresentation] throws an exception if it's
+ // unable to convert the string to something suitable. Map that to
+ // EDOM, "argument out of domain", which sort of conveys that there
+ // was a conversion failure.
+ errno = EDOM;
+ return -1;
+ }
+
+ return removexattr_func(path, name, options);
+}
+
++ (void)releaseFromQuarantine:(NSString*)root
+{
+ // *** MUST BE SAFE TO CALL ON NON-MAIN THREAD!
+
+ const char* quarantineAttribute = "com.apple.quarantine";
+ const int removeXAttrOptions = XATTR_NOFOLLOW;
+
+ [self removeXAttr:quarantineAttribute
+ fromFile:root
+ options:removeXAttrOptions];
+
+ // Only recurse if it's actually a directory. Don't recurse into a
+ // root-level symbolic link.
+#if MAC_OS_X_VERSION_MIN_REQUIRED <= MAC_OS_X_VERSION_10_4
+ NSDictionary* rootAttributes = [[NSFileManager defaultManager] fileAttributesAtPath:root traverseLink:NO];
+#else
+ NSDictionary* rootAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:root error:nil];
+#endif
+ NSString* rootType = [rootAttributes objectForKey:NSFileType];
+
+ if (rootType == NSFileTypeDirectory) {
+ // The NSDirectoryEnumerator will avoid recursing into any contained
+ // symbolic links, so no further type checks are needed.
+ NSDirectoryEnumerator* directoryEnumerator = [[NSFileManager defaultManager] enumeratorAtPath:root];
+ NSString* file = nil;
+ while ((file = [directoryEnumerator nextObject])) {
+ [self removeXAttr:quarantineAttribute
+ fromFile:[root stringByAppendingPathComponent:file]
+ options:removeXAttrOptions];
+ }
+ }
+}
+
+@end
View
1  Quicksilver/Code-QuickStepCore/QSNotifyMediator.h
@@ -25,6 +25,7 @@
#import <Cocoa/Cocoa.h>
+BOOL QSShowAppNotifWithAttributes(NSString *type, NSString *title, NSString *message);
BOOL QSShowNotifierWithAttributes(NSDictionary *attributes);
@protocol QSNotifier
View
3  Quicksilver/Code-QuickStepCore/QSNotifyMediator.m
@@ -1,6 +1,9 @@
#import "QSNotifyMediator.h"
#import "QSResourceManager.h"
+BOOL QSShowAppNotifWithAttributes(NSString *type, NSString *title, NSString *message) {
+ QSShowNotifierWithAttributes([NSDictionary dictionaryWithObjectsAndKeys:type, QSNotifierType, [QSResourceManager imageNamed:kQSBundleID], QSNotifierIcon, title, QSNotifierTitle, message, QSNotifierText, nil]);}
+
BOOL QSShowNotifierWithAttributes(NSDictionary *attributes) {
if ([attributes count]) {
[[QSReg preferredNotifier] displayNotificationWithAttributes:attributes];
View
2  Quicksilver/Code-QuickStepCore/QSPaths.h
@@ -3,11 +3,13 @@
#define pCatalogPresetsDebugLocation QSApplicationSupportSubPath(@"Presets.plist", NO)
#define pMnemonicStorage QSApplicationSupportSubPath(@"Mnemonics.plist", NO)
#define pCacheLocation QSApplicationSupportSubPath(@"Caches/", NO)
+#define pUpdatePath QSApplicationSupportSubPath(@"QSAppUpdateFolder", NO)
#define pIndexLocation [@"~/Library/Caches/Quicksilver/Indexes/" stringByStandardizingPath]
#define pStateLocation [@"~/Library/Caches/Quicksilver/QuicksilverState.plist" stringByStandardizingPath]
#define pCrashReporterFolder [@"~/Library/Logs/DiagnosticReports" stringByStandardizingPath]
#define pShelfLocation QSApplicationSupportSubPath(@"Shelves/", NO)
#define pICloudDocumentsPrefix [@"~/Library/Mobile Documents/" stringByStandardizingPath]
+#define appSupportSubpath @"Application Support/Quicksilver/PlugIns"
#define psMainPlugInsLocation QSApplicationSupportSubPath(@"PlugIns/", NO)
#define psMainPlugInsToInstallLocation QSApplicationSupportSubPath(@"PlugIns/Incoming/", NO)
View
1  Quicksilver/Code-QuickStepCore/QSPlugInManager.m
@@ -493,7 +493,6 @@ - (void)loadPlugInsAtLaunch {
}
-#define appSupportSubpath @"Application Support/Quicksilver/PlugIns"
- (NSMutableArray *)allBundles {
NSMutableSet *bundleSearchPaths = [NSMutableSet set];
View
2  Quicksilver/Code-QuickStepCore/QSRegistry.m
@@ -365,8 +365,6 @@ - (NSDictionary *)restrictionsDict {
}
#endif
-#define appSupportSubpath @"Application Support/Quicksilver/PlugIns"
-
- (NSMutableArray *)allBundles {
NSBundle *appBundle = [NSBundle mainBundle];
NSFileManager *fm = [NSFileManager defaultManager];
View
3  Quicksilver/Code-QuickStepFoundation/NSApplication_BLTRExtensions.h
@@ -24,11 +24,10 @@
@interface NSApplication (Relaunching)
- (IBAction)relaunch:(id)sender;
+- (BOOL)moveToPath:(NSString *)launchPath fromPath:(NSString *)newPath;
- (void)requestRelaunch:(id)sender;
- (void)relaunchFromPath:(NSString *)path;
-- (void)relaunchAfterMovingFromPath:(NSString *)newPath;
- (void)relaunchAtPath:(NSString *)launchPath movedFromPath:(NSString *)newPath;
-- (void)replaceWithUpdateFromPath:(NSString *)newPath;
@end
enum {
View
36 Quicksilver/Code-QuickStepFoundation/NSApplication_BLTRExtensions.m
@@ -9,6 +9,8 @@
#import "NSApplication_BLTRExtensions.h"
#import "NSFileManager_BLTRExtensions.h"
#import "NSString_BLTRExtensions.h"
+#import "SUPlainInstallerInternals.h"
+
#import <unistd.h>
@implementation NSApplication (Info)
@@ -77,37 +79,15 @@ - (void)requestRelaunch:(id)sender {
[self relaunch:self];
}
-- (void)relaunchAfterMovingFromPath:(NSString *)newPath {
- [self relaunchAtPath:[[NSBundle mainBundle] bundlePath] movedFromPath:newPath];
-}
-
-- (NSInteger)moveToPath:(NSString *)launchPath fromPath:(NSString *)newPath {
- NSFileManager *manager = [NSFileManager defaultManager];
- NSString *tempPath = [[launchPath stringByDeletingLastPathComponent] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.old.app",[[NSProcessInfo processInfo] processName]]];
- //NSLog(@"temp %@ new %@", tempPath, newPath);
- BOOL status;
- status = [manager moveItemAtPath:launchPath toPath:tempPath error:nil];
-#ifdef DEBUG
- if (VERBOSE) NSLog(@"Move Old %@", status ? @"DONE" : @"FAILED");
-#endif
- status = [manager copyItemAtPath:newPath toPath:launchPath error:nil];
-#ifdef DEBUG
- if (VERBOSE) NSLog(@"Copy New %@", status ? @"DONE" : @"FAILED");
-#endif
- status = [manager movePathToTrash:tempPath];
-#ifdef DEBUG
- if (VERBOSE) NSLog(@"Trash Old %@", status? @"DONE" : @"FAILED");
-#endif
- return status;
-}
-
-- (void)replaceWithUpdateFromPath:(NSString *)newPath {
- [self moveToPath:[[NSBundle mainBundle] bundlePath] fromPath:newPath];
+// Use a method taken from Sparkle that deals with: Authentication, Quarantine and more
+- (BOOL)moveToPath:(NSString *)launchPath fromPath:(NSString *)newPath {
+ return [SUPlainInstaller copyPathWithAuthentication:newPath overPath:launchPath temporaryName:nil error:nil];
}
- (void)relaunchAtPath:(NSString *)launchPath movedFromPath:(NSString *)newPath {
- [self moveToPath:launchPath fromPath:newPath];
- [self relaunchFromPath:launchPath];
+ if([self moveToPath:launchPath fromPath:newPath]) {
+ [self relaunchFromPath:launchPath];
+ }
}
- (void)relaunchFromPath:(NSString *)path {
View
24 Quicksilver/Quicksilver.xcodeproj/project.pbxproj
@@ -360,6 +360,10 @@
CD53FEB3151A0ACF006B734B /* PluginReporterText.html in Resources */ = {isa = PBXBuildFile; fileRef = CD53FEB2151A0ACF006B734B /* PluginReporterText.html */; };
CD790FA314D21C2100225950 /* Quartz.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7F8D135E09187AE20062C966 /* Quartz.framework */; };
CDA9D3DE1549D13B00607BE4 /* AlertCautionIcon.icns in Resources */ = {isa = PBXBuildFile; fileRef = CDA9D3DD1549D13B00607BE4 /* AlertCautionIcon.icns */; };
+ CDC10E721622146C005FA734 /* SUConstants.h in Headers */ = {isa = PBXBuildFile; fileRef = CDC10E6E1622146C005FA734 /* SUConstants.h */; };
+ CDC10E731622146C005FA734 /* SUConstants.m in Sources */ = {isa = PBXBuildFile; fileRef = CDC10E6F1622146C005FA734 /* SUConstants.m */; };
+ CDC10E741622146C005FA734 /* SUPlainInstallerInternals.h in Headers */ = {isa = PBXBuildFile; fileRef = CDC10E701622146C005FA734 /* SUPlainInstallerInternals.h */; };
+ CDC10E751622146C005FA734 /* SUPlainInstallerInternals.m in Sources */ = {isa = PBXBuildFile; fileRef = CDC10E711622146C005FA734 /* SUPlainInstallerInternals.m */; };
CDC9C6C513DA2B6D0053B09C /* Clipboard.icns in Resources */ = {isa = PBXBuildFile; fileRef = CDC9C6C413DA2B6D0053B09C /* Clipboard.icns */; };
CDCC201010A4C14B009C4EED /* QSMDPredicate.h in Headers */ = {isa = PBXBuildFile; fileRef = CDCC200E10A4C14B009C4EED /* QSMDPredicate.h */; settings = {ATTRIBUTES = (Public, ); }; };
CDCC201110A4C14B009C4EED /* QSMDPredicate.m in Sources */ = {isa = PBXBuildFile; fileRef = CDCC200F10A4C14B009C4EED /* QSMDPredicate.m */; };
@@ -1400,6 +1404,10 @@
CD4FA6E1157A13DE00E549BD /* QSHotKeyEvent.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = QSHotKeyEvent.m; sourceTree = "<group>"; };
CD53FEB2151A0ACF006B734B /* PluginReporterText.html */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.html; path = PluginReporterText.html; sourceTree = "<group>"; };
CDA9D3DD1549D13B00607BE4 /* AlertCautionIcon.icns */ = {isa = PBXFileReference; lastKnownFileType = image.icns; path = AlertCautionIcon.icns; sourceTree = "<group>"; };
+ CDC10E6E1622146C005FA734 /* SUConstants.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SUConstants.h; path = Sparkle/SUConstants.h; sourceTree = "<group>"; };
+ CDC10E6F1622146C005FA734 /* SUConstants.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = SUConstants.m; path = Sparkle/SUConstants.m; sourceTree = "<group>"; };
+ CDC10E701622146C005FA734 /* SUPlainInstallerInternals.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SUPlainInstallerInternals.h; path = Sparkle/SUPlainInstallerInternals.h; sourceTree = "<group>"; };
+ CDC10E711622146C005FA734 /* SUPlainInstallerInternals.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = SUPlainInstallerInternals.m; path = Sparkle/SUPlainInstallerInternals.m; sourceTree = "<group>"; };
CDC9C6C413DA2B6D0053B09C /* Clipboard.icns */ = {isa = PBXFileReference; lastKnownFileType = image.icns; path = Clipboard.icns; sourceTree = "<group>"; };
CDCC200E10A4C14B009C4EED /* QSMDPredicate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = QSMDPredicate.h; sourceTree = "<group>"; };
CDCC200F10A4C14B009C4EED /* QSMDPredicate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = QSMDPredicate.m; sourceTree = "<group>"; };
@@ -2215,6 +2223,17 @@
path = QSDroplet;
sourceTree = "<group>";
};
+ CDC10E6D16221459005FA734 /* Sparkle */ = {
+ isa = PBXGroup;
+ children = (
+ CDC10E6E1622146C005FA734 /* SUConstants.h */,
+ CDC10E6F1622146C005FA734 /* SUConstants.m */,
+ CDC10E701622146C005FA734 /* SUPlainInstallerInternals.h */,
+ CDC10E711622146C005FA734 /* SUPlainInstallerInternals.m */,
+ );
+ name = Sparkle;
+ sourceTree = "<group>";
+ };
CDD30972160B860C00CD34EC /* Count Badges */ = {
isa = PBXGroup;
children = (
@@ -2380,6 +2399,7 @@
E103EE2406471DDE00447FE0 /* Code-External */ = {
isa = PBXGroup;
children = (
+ CDC10E6D16221459005FA734 /* Sparkle */,
D413172B15DEE5D90021479B /* LaunchAtLoginController */,
CDE1E65F158A4CFD00355A9F /* VDKQueue */,
4D66BBD91486FCDE00351C42 /* CPSPrivate.h */,
@@ -3164,6 +3184,8 @@
CDE6C624157E39AE006E66BD /* QSFoundation.h in Headers */,
4D66BC451487024500351C42 /* NSString+NDUtilities.h in Headers */,
CDE8ADBB15824E3E0099CC83 /* NDKeyboardLayout.h in Headers */,
+ CDC10E721622146C005FA734 /* SUConstants.h in Headers */,
+ CDC10E741622146C005FA734 /* SUPlainInstallerInternals.h in Headers */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -4279,6 +4301,8 @@
4D66BC461487024500351C42 /* NSString+NDUtilities.m in Sources */,
CD4FA6E2157A13DE00E549BD /* QSHotKeyEvent.m in Sources */,
CDE8ADBC15824E3E0099CC83 /* NDKeyboardLayout.m in Sources */,
+ CDC10E731622146C005FA734 /* SUConstants.m in Sources */,
+ CDC10E751622146C005FA734 /* SUPlainInstallerInternals.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
Something went wrong with that request. Please try again.