mirror of
https://github.com/sparkle-project/Sparkle
synced 2026-11-25 04:47:55 +00:00
Merge branch 'xpc-remove-auth' into ui-separation-and-xpc
This commit is contained in:
commit
fe62ad0468
119 files changed
+1904
-1934
No files matched your search
@@ -0,0 +1,34 @@
|
||||
//
|
||||
// AgentConnection.h
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Mayur Pawashe on 7/17/16.
|
||||
// Copyright © 2016 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@protocol AgentConnectionDelegate <NSObject>
|
||||
|
||||
- (void)agentConnectionDidInitiate;
|
||||
- (void)agentConnectionDidInvalidate;
|
||||
|
||||
@end
|
||||
|
||||
@protocol SUInstallerAgentProtocol;
|
||||
|
||||
@interface AgentConnection : NSObject
|
||||
|
||||
- (instancetype)initWithHostBundleIdentifier:(NSString *)bundleIdentifier delegate:(id<AgentConnectionDelegate>)delegate;
|
||||
|
||||
- (void)startListener;
|
||||
- (void)invalidate;
|
||||
|
||||
@property (nonatomic, readonly, nullable) id<SUInstallerAgentProtocol> agent;
|
||||
@property (nonatomic, readonly) BOOL connected;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@@ -0,0 +1,109 @@
|
||||
//
|
||||
// AgentConnection.m
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Mayur Pawashe on 7/17/16.
|
||||
// Copyright © 2016 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#import "AgentConnection.h"
|
||||
#import "SUMessageTypes.h"
|
||||
#import "SUInstallerAgentProtocol.h"
|
||||
#import "SUInstallerAgentInitiationProtocol.h"
|
||||
|
||||
#ifdef _APPKITDEFINES_H
|
||||
#error This is a "daemon-safe" class and should NOT import AppKit
|
||||
#endif
|
||||
|
||||
@interface AgentConnection () <NSXPCListenerDelegate, SUInstallerAgentInitiationProtocol>
|
||||
|
||||
@property (nonatomic) NSXPCListener *xpcListener;
|
||||
@property (nonatomic, nullable) NSXPCConnection *activeConnection;
|
||||
@property (nonatomic, nullable) id<SUInstallerAgentProtocol> agent;
|
||||
@property (nonatomic, weak) id<AgentConnectionDelegate> delegate;
|
||||
@property (nonatomic) BOOL connected;
|
||||
|
||||
@end
|
||||
|
||||
@implementation AgentConnection
|
||||
|
||||
@synthesize xpcListener = _xpcListener;
|
||||
@synthesize activeConnection = _activeConnection;
|
||||
@synthesize agent = _agent;
|
||||
@synthesize delegate = _delegate;
|
||||
@synthesize connected = _connected;
|
||||
|
||||
- (instancetype)initWithHostBundleIdentifier:(NSString *)bundleIdentifier delegate:(id<AgentConnectionDelegate>)delegate
|
||||
{
|
||||
self = [super init];
|
||||
if (self != nil) {
|
||||
// Agents should always be the one that connect to daemons due to how mach bootstraps work
|
||||
// For this reason, we are the ones that are creating a listener, not the agent
|
||||
_xpcListener = [[NSXPCListener alloc] initWithMachServiceName:SUProgressAgentServiceNameForBundleIdentifier(bundleIdentifier)];
|
||||
_xpcListener.delegate = self;
|
||||
_delegate = delegate;
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)startListener
|
||||
{
|
||||
[self.xpcListener resume];
|
||||
}
|
||||
|
||||
- (void)invalidate
|
||||
{
|
||||
self.delegate = nil;
|
||||
|
||||
[self.activeConnection invalidate];
|
||||
self.activeConnection = nil;
|
||||
|
||||
[self.xpcListener invalidate];
|
||||
self.xpcListener = nil;
|
||||
}
|
||||
|
||||
- (BOOL)listener:(NSXPCListener *)__unused listener shouldAcceptNewConnection:(NSXPCConnection *)newConnection
|
||||
{
|
||||
if (self.activeConnection != nil) {
|
||||
[newConnection invalidate];
|
||||
return NO;
|
||||
}
|
||||
|
||||
newConnection.exportedInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUInstallerAgentInitiationProtocol)];
|
||||
newConnection.exportedObject = self;
|
||||
|
||||
newConnection.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUInstallerAgentProtocol)];
|
||||
|
||||
self.activeConnection = newConnection;
|
||||
|
||||
__weak AgentConnection *weakSelf = self;
|
||||
newConnection.interruptionHandler = ^{
|
||||
[weakSelf.activeConnection invalidate];
|
||||
};
|
||||
|
||||
newConnection.invalidationHandler = ^{
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[weakSelf.delegate agentConnectionDidInvalidate];
|
||||
});
|
||||
};
|
||||
|
||||
[newConnection resume];
|
||||
|
||||
self.agent = newConnection.remoteObjectProxy;
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (void)connectionDidInitiateWithReply:(void (^)(void))acknowledgement
|
||||
{
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
self.connected = YES;
|
||||
|
||||
[self.delegate agentConnectionDidInitiate];
|
||||
self.delegate = nil;
|
||||
});
|
||||
|
||||
acknowledgement();
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -6,7 +6,7 @@
|
||||
// Copyright © 2016 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "SUUnarchiverProtocol.h"
|
||||
|
||||
@interface AppInstaller : NSObject <SUUnarchiverDelegate>
|
||||
@@ -8,7 +8,6 @@
|
||||
|
||||
#import "AppInstaller.h"
|
||||
#import "TerminationListener.h"
|
||||
#import "StatusInfo.h"
|
||||
#import "SUInstaller.h"
|
||||
#import "SULog.h"
|
||||
#import "SUHost.h"
|
||||
@@ -23,12 +22,18 @@
|
||||
#import "SUFileManager.h"
|
||||
#import "SUInstallationInfo.h"
|
||||
#import "SUAppcastItem.h"
|
||||
#import "SUAuthorizationEnvironment.h"
|
||||
#import "SUApplicationInfo.h"
|
||||
#import "SUErrors.h"
|
||||
#import "SUInstallerCommunicationProtocol.h"
|
||||
#import "AgentConnection.h"
|
||||
#import "SUInstallerAgentProtocol.h"
|
||||
#import "SUInstallationType.h"
|
||||
|
||||
#ifdef _APPKITDEFINES_H
|
||||
#error This is a "daemon-safe" class and should NOT import AppKit
|
||||
#endif
|
||||
|
||||
#define FIRST_UPDATER_MESSAGE_TIMEOUT 7ull
|
||||
#define RETRIEVE_PROCESS_IDENTIFIER_TIMEOUT 5ull
|
||||
|
||||
/*!
|
||||
* Terminate the application after a delay from launching the new update to avoid OS activation issues
|
||||
@@ -44,12 +49,12 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.5;
|
||||
*/
|
||||
static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
|
||||
|
||||
@interface AppInstaller () <NSXPCListenerDelegate, SUInstallerCommunicationProtocol>
|
||||
@interface AppInstaller () <NSXPCListenerDelegate, SUInstallerCommunicationProtocol, AgentConnectionDelegate>
|
||||
|
||||
@property (nonatomic) NSXPCListener* xpcListener;
|
||||
@property (nonatomic) NSXPCConnection *activeConnection;
|
||||
@property (nonatomic) id<SUInstallerCommunicationProtocol> communicator;
|
||||
@property (nonatomic) StatusInfo *statusInfo;
|
||||
@property (nonatomic) AgentConnection *agentConnection;
|
||||
@property (nonatomic) BOOL receivedUpdaterPong;
|
||||
|
||||
@property (nonatomic, strong) TerminationListener *terminationListener;
|
||||
@@ -70,6 +75,8 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
|
||||
@property (nonatomic) BOOL performedStage2Installation;
|
||||
@property (nonatomic) BOOL performedStage3Installation;
|
||||
|
||||
@property (nonatomic) NSUInteger agentConnectionCounter;
|
||||
|
||||
@end
|
||||
|
||||
@implementation AppInstaller
|
||||
@@ -77,7 +84,7 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
|
||||
@synthesize xpcListener = _xpcListener;
|
||||
@synthesize activeConnection = _activeConnection;
|
||||
@synthesize communicator = _communicator;
|
||||
@synthesize statusInfo = _statusInfo;
|
||||
@synthesize agentConnection = _agentConnection;
|
||||
@synthesize receivedUpdaterPong = _receivedUpdaterPong;
|
||||
@synthesize hostBundleIdentifier = _hostBundleIdentifier;
|
||||
@synthesize allowsInteraction = _allowsInteraction;
|
||||
@@ -93,6 +100,7 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
|
||||
@synthesize performedStage1Installation = _performedStage1Installation;
|
||||
@synthesize performedStage2Installation = _performedStage2Installation;
|
||||
@synthesize performedStage3Installation = _performedStage3Installation;
|
||||
@synthesize agentConnectionCounter = _agentConnectionCounter;
|
||||
|
||||
- (instancetype)initWithHostBundleIdentifier:(NSString *)hostBundleIdentifier allowingInteraction:(BOOL)allowsInteraction
|
||||
{
|
||||
@@ -107,7 +115,7 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
|
||||
_xpcListener = [[NSXPCListener alloc] initWithMachServiceName:SUInstallerServiceNameForBundleIdentifier(hostBundleIdentifier)];
|
||||
_xpcListener.delegate = self;
|
||||
|
||||
_statusInfo = [[StatusInfo alloc] initWithHostBundleIdentifier:hostBundleIdentifier];
|
||||
_agentConnection = [[AgentConnection alloc] initWithHostBundleIdentifier:hostBundleIdentifier delegate:self];
|
||||
|
||||
return self;
|
||||
}
|
||||
@@ -158,13 +166,18 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
|
||||
- (void)start
|
||||
{
|
||||
[self.xpcListener resume];
|
||||
[self.statusInfo startListener];
|
||||
[self.agentConnection startListener];
|
||||
|
||||
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(FIRST_UPDATER_MESSAGE_TIMEOUT * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
|
||||
if (!self.receivedInstallationData) {
|
||||
SULog(@"Timeout: installation data was never received");
|
||||
[self cleanupAndExitWithStatus:EXIT_FAILURE];
|
||||
}
|
||||
|
||||
if (!self.agentConnection.connected) {
|
||||
SULog(@"Timeout: agent connection was never initiated");
|
||||
[self cleanupAndExitWithStatus:EXIT_FAILURE];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -302,10 +315,50 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
|
||||
} else {
|
||||
[self.communicator handleMessageWithIdentifier:SUInstallationStartedStage1 data:[NSData data]];
|
||||
|
||||
[self startInstallation];
|
||||
self.agentConnectionCounter++;
|
||||
if (self.agentConnectionCounter == 2) {
|
||||
[self retrieveProcessIdentifierAndStartInstallation];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
- (void)agentConnectionDidInitiate
|
||||
{
|
||||
self.agentConnectionCounter++;
|
||||
if (self.agentConnectionCounter == 2) {
|
||||
[self retrieveProcessIdentifierAndStartInstallation];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)agentConnectionDidInvalidate
|
||||
{
|
||||
if (self.agentConnectionCounter < 2) {
|
||||
SULog(@"Error: Agent connection invalidated before installation began");
|
||||
[self cleanupAndExitWithStatus:EXIT_FAILURE];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)retrieveProcessIdentifierAndStartInstallation
|
||||
{
|
||||
// We use the relaunch path for the bundle to listen for termination instead of the host path
|
||||
// For a plug-in this makes a big difference; we want to wait until the app hosting the plug-in terminates
|
||||
// Otherwise for an app, the relaunch path and host path should be identical
|
||||
|
||||
[self.agentConnection.agent registerRelaunchBundlePath:self.installationData.relaunchPath reply:^(NSNumber * _Nullable processIdentifier) {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
self.terminationListener = [[TerminationListener alloc] initWithProcessIdentifier:processIdentifier];
|
||||
[self startInstallation];
|
||||
});
|
||||
}];
|
||||
|
||||
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(RETRIEVE_PROCESS_IDENTIFIER_TIMEOUT * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
|
||||
if (self.terminationListener == nil) {
|
||||
SULog(@"Timeour error: failed to retreive process identifier from agent");
|
||||
[self cleanupAndExitWithStatus:EXIT_FAILURE];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
- (void)handleMessageWithIdentifier:(int32_t)identifier data:(NSData *)data
|
||||
{
|
||||
if (identifier == SUInstallationData && self.installationData == nil) {
|
||||
@@ -323,40 +376,38 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
|
||||
NSBundle *hostBundle = [NSBundle bundleWithPath:nonNullInstallationData.hostBundlePath];
|
||||
SUHost *host = [[SUHost alloc] initWithBundle:hostBundle];
|
||||
|
||||
NSString *bundleIdentifier = hostBundle.bundleIdentifier;
|
||||
if (bundleIdentifier == nil || ![bundleIdentifier isEqualToString:self.hostBundleIdentifier]) {
|
||||
SULog(@"Error: Failed to match host bundle identifiers %@ and %@", self.hostBundleIdentifier, bundleIdentifier);
|
||||
NSString *installationType = nonNullInstallationData.installationType;
|
||||
if (!SUValidInstallationType(installationType)) {
|
||||
SULog(@"Error: Received invalid installation type: %@", installationType);
|
||||
[self cleanupAndExitWithStatus:EXIT_FAILURE];
|
||||
} else {
|
||||
NSBundle *relaunchBundle = [NSBundle bundleWithPath:nonNullInstallationData.relaunchPath];
|
||||
if (relaunchBundle == nil) {
|
||||
SULog(@"Error: Failed to locate relaunch bundle path %@", nonNullInstallationData.relaunchPath);
|
||||
NSString *bundleIdentifier = hostBundle.bundleIdentifier;
|
||||
if (bundleIdentifier == nil || ![bundleIdentifier isEqualToString:self.hostBundleIdentifier]) {
|
||||
SULog(@"Error: Failed to match host bundle identifiers %@ and %@", self.hostBundleIdentifier, bundleIdentifier);
|
||||
[self cleanupAndExitWithStatus:EXIT_FAILURE];
|
||||
} else {
|
||||
self.host = host;
|
||||
self.installationData = installationData;
|
||||
|
||||
// We use the relaunch path for the bundle to listen for termination instead of the host path
|
||||
// For a plug-in this makes a big difference; we want to wait until the app hosting the plug-in terminates
|
||||
// Otherwise for an app, the relaunch path and host path should be identical
|
||||
|
||||
NSRunningApplication *runningApplication = [SUApplicationInfo runningApplicationWithBundle:host.bundle];
|
||||
NSNumber *processIdentifier = (runningApplication == nil || runningApplication.terminated) ? nil : @(runningApplication.processIdentifier);
|
||||
|
||||
self.terminationListener = [[TerminationListener alloc] initWithProcessIdentifier:processIdentifier];
|
||||
|
||||
[self extractAndInstallUpdate];
|
||||
// This will be important later
|
||||
if (nonNullInstallationData.relaunchPath == nil) {
|
||||
SULog(@"Error: Failed to obtain relaunch path from installation data");
|
||||
[self cleanupAndExitWithStatus:EXIT_FAILURE];
|
||||
} else {
|
||||
self.host = host;
|
||||
self.installationData = installationData;
|
||||
|
||||
[self extractAndInstallUpdate];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
} else if (identifier == SUSentUpdateAppcastItemData) {
|
||||
if (self.statusInfo.installationInfoData == nil) {
|
||||
SUAppcastItem *updateItem = (SUAppcastItem *)SUUnarchiveRootObjectSecurely(data, [SUAppcastItem class]);
|
||||
if (updateItem != nil) {
|
||||
SUInstallationInfo *installationInfo = [[SUInstallationInfo alloc] initWithAppcastItem:updateItem canSilentlyInstall:[self.installer canInstallSilently]];
|
||||
|
||||
self.statusInfo.installationInfoData = SUArchiveRootObjectSecurely(installationInfo);
|
||||
SUAppcastItem *updateItem = (SUAppcastItem *)SUUnarchiveRootObjectSecurely(data, [SUAppcastItem class]);
|
||||
if (updateItem != nil) {
|
||||
SUInstallationInfo *installationInfo = [[SUInstallationInfo alloc] initWithAppcastItem:updateItem canSilentlyInstall:[self.installer canInstallSilently]];
|
||||
|
||||
NSData *archivedData = SUArchiveRootObjectSecurely(installationInfo);
|
||||
if (archivedData != nil) {
|
||||
[self.agentConnection.agent registerInstallationInfoData:archivedData];
|
||||
}
|
||||
}
|
||||
} else if (identifier == SUResumeInstallationToStage2 && data.length == sizeof(uint8_t) * 2) {
|
||||
@@ -392,7 +443,7 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
|
||||
|
||||
dispatch_async(self.installerQueue, ^{
|
||||
NSError *installerError = nil;
|
||||
id <SUInstallerProtocol> installer = [SUInstaller installerForHost:self.host updateDirectory:self.installationData.updateDirectoryPath allowingInteraction:self.allowsInteraction versionComparator:[SUStandardVersionComparator standardVersionComparator] error:&installerError];
|
||||
id <SUInstallerProtocol> installer = [SUInstaller installerForHost:self.host expectedInstallationType:self.installationData.installationType updateDirectory:self.installationData.updateDirectoryPath allowingInteraction:self.allowsInteraction versionComparator:[SUStandardVersionComparator standardVersionComparator] error:&installerError];
|
||||
|
||||
if (installer == nil) {
|
||||
SULog(@"Error: Failed to create installer instance with error: %@", installerError);
|
||||
@@ -442,53 +493,8 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
|
||||
return;
|
||||
}
|
||||
|
||||
SUAuthorizationEnvironment *environment = nil;
|
||||
NSURL *tempIconDirectoryURL = nil;
|
||||
if (self.shouldShowUI && self.allowsInteraction && [self.installer mayNeedToRequestAuthorization]) {
|
||||
NSString *prompt = [NSString stringWithFormat:NSLocalizedString(@"%1$@ wants to update.", nil), self.host.name];
|
||||
|
||||
NSString *iconPath = nil;
|
||||
|
||||
// Authorization API requires a 32x32 icon image and accepts png (but not icns or tiff)
|
||||
NSImage *icon = [SUApplicationInfo bestIconForBundle:self.host.bundle];
|
||||
[icon setSize:NSMakeSize(32, 32)];
|
||||
|
||||
CGImageRef iconRef = [icon CGImageForProposedRect:NULL context:nil hints:nil];
|
||||
NSBitmapImageRep *representation = [[NSBitmapImageRep alloc] initWithCGImage:iconRef];
|
||||
NSData *pngData = [representation representationUsingType:NSPNGFileType properties:@{}];
|
||||
|
||||
// Write the icon to a temporary directory. This icon file should be in a directory that's readable to everyone.
|
||||
NSError *tempError = nil;
|
||||
tempIconDirectoryURL = [[SUFileManager defaultManager] makeTemporaryDirectoryWithPreferredName:@"sparkle-auth-icon" appropriateForDirectoryURL:[NSURL fileURLWithPath:NSTemporaryDirectory()] error:&tempError];
|
||||
if (tempIconDirectoryURL == nil) {
|
||||
SULog(@"Failed to create temporary directory for authorization icon: %@", tempError);
|
||||
} else {
|
||||
NSURL *iconURL = [tempIconDirectoryURL URLByAppendingPathComponent:@"icon.png"];
|
||||
if ([pngData writeToURL:iconURL atomically:YES]) {
|
||||
iconPath = iconURL.path;
|
||||
}
|
||||
}
|
||||
|
||||
environment = [[SUAuthorizationEnvironment alloc] initWithPrompt:prompt iconPath:(iconPath != nil ? iconPath : @"")];
|
||||
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
// We should activate our app so that the auth prompt will be active
|
||||
[[NSApplication sharedApplication] activateIgnoringOtherApps:YES];
|
||||
});
|
||||
}
|
||||
|
||||
NSString *fileOperationToolPath = [[[[NSBundle mainBundle] executablePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@""SPARKLE_FILEOP_TOOL_NAME];
|
||||
|
||||
if (![[NSFileManager defaultManager] fileExistsAtPath:fileOperationToolPath]) {
|
||||
SULog(@"Potential Installation Error: File operation tool path %@ is not found", fileOperationToolPath);
|
||||
}
|
||||
|
||||
NSError *secondStageError = nil;
|
||||
BOOL performedSecondStage = [self.installer performSecondStageAllowingAuthorization:self.allowsInteraction fileOperationToolPath:fileOperationToolPath environment:environment allowingUI:self.shouldShowUI error:&secondStageError];
|
||||
|
||||
if (tempIconDirectoryURL != nil) {
|
||||
[[SUFileManager defaultManager] removeItemAtURL:tempIconDirectoryURL error:NULL];
|
||||
}
|
||||
BOOL performedSecondStage = [self.installer performSecondStageAllowingUI:self.shouldShowUI error:&secondStageError];
|
||||
|
||||
if (performedSecondStage) {
|
||||
self.performedStage2Installation = YES;
|
||||
@@ -504,25 +510,25 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
|
||||
});
|
||||
};
|
||||
|
||||
// Let the other end know we cancelled so they can fail gracefully without disturbing the user
|
||||
BOOL installationCancelled = (!performedSecondStage && secondStageError.code == SUInstallationCancelledError);
|
||||
if (performedSecondStage || installationCancelled) {
|
||||
// Let the other end know we canceled so they can fail gracefully without disturbing the user
|
||||
BOOL installationCanceled = (!performedSecondStage && secondStageError.code == SUInstallationCanceledError);
|
||||
if (performedSecondStage || installationCanceled) {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
uint8_t cancelled = (uint8_t)installationCancelled;
|
||||
uint8_t canceled = (uint8_t)installationCanceled;
|
||||
uint8_t targetTerminated = (uint8_t)self.terminationListener.terminated;
|
||||
|
||||
uint8_t sendInfo[] = {cancelled, targetTerminated};
|
||||
uint8_t sendInfo[] = {canceled, targetTerminated};
|
||||
|
||||
NSData *sendData = [NSData dataWithBytes:sendInfo length:sizeof(sendInfo)];
|
||||
[self.communicator handleMessageWithIdentifier:SUInstallationFinishedStage2 data:sendData];
|
||||
|
||||
if (installationCancelled) {
|
||||
if (installationCanceled) {
|
||||
cleanupAndExit();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (!performedSecondStage && !installationCancelled) {
|
||||
if (!performedSecondStage && !installationCanceled) {
|
||||
cleanupAndExit();
|
||||
}
|
||||
}
|
||||
@@ -543,37 +549,17 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
|
||||
[self.communicator handleMessageWithIdentifier:SUUpdaterAlivePing data:[NSData data]];
|
||||
|
||||
// Launch our installer progress UI tool if only after a certain amount of time passes
|
||||
__block NSRunningApplication *installerProgressRunningApplication = nil;
|
||||
__block BOOL shouldLaunchInstallerProgress = YES;
|
||||
|
||||
NSString *progressToolPath = self.installationData.progressToolPath;
|
||||
if (progressToolPath != nil && self.shouldShowUI && ![self.installer displaysUserProgress]) {
|
||||
NSURL *progressToolURL = [NSURL fileURLWithPath:progressToolPath];
|
||||
if (progressToolURL != nil) {
|
||||
NSError *quarantineError = nil;
|
||||
if (![[SUFileManager defaultManager] releaseItemFromQuarantineAtRootURL:progressToolURL error:&quarantineError]) {
|
||||
SULog(@"Error: Failed releasing quarantine from installer progress tool: %@", quarantineError);
|
||||
if (self.shouldShowUI && ![self.installer displaysUserProgress]) {
|
||||
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(SUDisplayProgressTimeDelay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
|
||||
// Make sure we're still eligible for showing the installer progress
|
||||
// Also if the updater process is still alive, showing the progress should not be our duty
|
||||
// if the communicator object is nil, the updater definitely isn't alive. However, if it is not nil,
|
||||
// this does not necessarily mean the updater is alive, so we should also check if we got a recent response back from the updater
|
||||
if (shouldLaunchInstallerProgress && (!self.receivedUpdaterPong || self.communicator == nil)) {
|
||||
[self.agentConnection.agent showProgress];
|
||||
}
|
||||
|
||||
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(SUDisplayProgressTimeDelay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
|
||||
// Make sure we're still eligible for showing the installer progress
|
||||
// Also if the updater process is still alive, showing the progress should not be our duty
|
||||
// if the communicator object is nil, the updater definitely isn't alive. However, if it is not nil,
|
||||
// this does not necessarily mean the updater is alive, so we should also check if we got a recent response back from the updater
|
||||
if (shouldLaunchInstallerProgress && (!self.receivedUpdaterPong || self.communicator == nil)) {
|
||||
NSError *launchError = nil;
|
||||
|
||||
NSArray *arguments = @[self.host.bundlePath];
|
||||
NSRunningApplication *runningApplication = [[NSWorkspace sharedWorkspace] launchApplicationAtURL:progressToolURL options:(NSWorkspaceLaunchOptions)(NSWorkspaceLaunchDefault | NSWorkspaceLaunchNewInstance) configuration:@{NSWorkspaceLaunchConfigurationArguments : arguments} error:&launchError];
|
||||
|
||||
if (runningApplication == nil) {
|
||||
SULog(@"Failed to launch installer progress tool with error: %@", launchError);
|
||||
} else {
|
||||
installerProgressRunningApplication = runningApplication;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
dispatch_async(self.installerQueue, ^{
|
||||
@@ -600,18 +586,14 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
|
||||
self.performedStage3Installation = YES;
|
||||
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
// Make sure to terminate our displayed progress before we move onto cleanup
|
||||
[installerProgressRunningApplication terminate];
|
||||
// Make sure to terminate our displayed progress before we move onto cleanup & relaunch
|
||||
// This will also stop the agent from broadcasting the status info service, which we want to do before
|
||||
// we relaunch the app because the relaunched app could check the service upon launch..
|
||||
[self.agentConnection.agent stopProgress];
|
||||
shouldLaunchInstallerProgress = NO;
|
||||
|
||||
[self.communicator handleMessageWithIdentifier:SUInstallationFinishedStage3 data:[NSData data]];
|
||||
|
||||
// Invalidate the status info listener before re-launching the updated app
|
||||
// If we don't do this, the updated app could think the installation can be resumable,
|
||||
// if it checks for updates immediately on launch
|
||||
[self.statusInfo invalidate];
|
||||
self.statusInfo = nil;
|
||||
|
||||
NSString *installationPath = [SUInstaller installationPathForHost:self.host];
|
||||
|
||||
if (self.shouldRelaunch) {
|
||||
@@ -624,7 +606,7 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
|
||||
pathToRelaunch = self.installationData.relaunchPath;
|
||||
}
|
||||
|
||||
[self relaunchAtPath:pathToRelaunch];
|
||||
[self.agentConnection.agent relaunchPath:pathToRelaunch];
|
||||
}
|
||||
|
||||
dispatch_async(self.installerQueue, ^{
|
||||
@@ -649,8 +631,8 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
|
||||
[self.xpcListener invalidate];
|
||||
self.xpcListener = nil;
|
||||
|
||||
[self.statusInfo invalidate];
|
||||
self.statusInfo = nil;
|
||||
[self.agentConnection invalidate];
|
||||
self.agentConnection = nil;
|
||||
|
||||
NSError *theError = nil;
|
||||
if (![[NSFileManager defaultManager] removeItemAtPath:self.installationData.updateDirectoryPath error:&theError]) {
|
||||
@@ -662,12 +644,4 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
|
||||
exit(status);
|
||||
}
|
||||
|
||||
- (void)relaunchAtPath:(NSString *)relaunchPath
|
||||
{
|
||||
// Don't use -launchApplication: because we may not be launching an application. Eg: it could be a system prefpane
|
||||
if (![[NSWorkspace sharedWorkspace] openFile:relaunchPath]) {
|
||||
SULog(@"Failed to launch %@", relaunchPath);
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -43,7 +43,7 @@
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (BOOL)performSecondStageAllowingAuthorization:(BOOL)allowsAuthorization fileOperationToolPath:(NSString *)fileOperationToolPath environment:(SUAuthorizationEnvironment * _Nullable)authorizationEnvironment allowingUI:(BOOL)allowsUI error:(NSError * __autoreleasing *)error
|
||||
- (BOOL)performSecondStageAllowingUI:(BOOL)allowsUI error:(NSError * __autoreleasing *)error
|
||||
{
|
||||
if (!allowsUI && ![self canInstallSilently]) {
|
||||
if (error != NULL) {
|
||||
@@ -53,14 +53,39 @@
|
||||
}
|
||||
|
||||
// If we're root, we can allow using the authorization APIs
|
||||
self.fileManager = (allowsAuthorization || [self isRootUser]) ? [SUFileManager fileManagerWithAuthorizationToolPath:fileOperationToolPath environment:authorizationEnvironment] : [SUFileManager defaultManager];
|
||||
self.fileManager = [SUFileManager defaultManager];
|
||||
|
||||
return [self.fileManager grantAuthorizationPrivilegesWithError:error];
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (BOOL)performThirdStage:(NSError * __autoreleasing *)error
|
||||
{
|
||||
return [self.fileManager executePackageAtURL:[NSURL fileURLWithPath:self.packagePath] error:error];
|
||||
// This command *must* be run as root
|
||||
NSString *installerPath = @"/usr/sbin/installer";
|
||||
|
||||
NSTask *task = [[NSTask alloc] init];
|
||||
task.launchPath = installerPath;
|
||||
task.arguments = @[@"-pkg", self.packagePath, @"-target", @"/"];
|
||||
task.standardError = [NSPipe pipe];
|
||||
task.standardOutput = [NSPipe pipe];
|
||||
|
||||
BOOL success = YES;
|
||||
@try {
|
||||
[task launch];
|
||||
[task waitUntilExit];
|
||||
if (task.terminationStatus != EXIT_SUCCESS) {
|
||||
success = NO;
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Guided package installer returned non-zero exit status (%d)", task.terminationStatus] }];
|
||||
}
|
||||
}
|
||||
} @catch (NSException *) {
|
||||
success = NO;
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Guided package installer task threw an exception"] }];
|
||||
}
|
||||
}
|
||||
return success;
|
||||
}
|
||||
|
||||
- (BOOL)displaysUserProgress
|
||||
@@ -78,11 +103,6 @@
|
||||
return [self isRootUser];
|
||||
}
|
||||
|
||||
- (BOOL)mayNeedToRequestAuthorization
|
||||
{
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (void)cleanup
|
||||
{
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
@@ -14,20 +14,19 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
/*
|
||||
* relaunchPath - path to application bundle to relaunch and listen for termination
|
||||
* progressToolPath - path to optional GUI tool that shows update progress if installation is not quick
|
||||
* hostBundlePath - path to host bundle to update & replace
|
||||
* updateDirectoryPath - path to update directory (i.e, temporary directory containing the new update archive)
|
||||
* downloadName - name of update archive in update directory
|
||||
* dsaSignature - DSA signature for the update that came from the appcast item
|
||||
* decryptionPassword - optional decryption password for dmg archives
|
||||
*/
|
||||
- (instancetype)initWithRelaunchPath:(NSString *)relaunchPath progressToolPath:(nullable NSString *)progressToolPath hostBundlePath:(NSString *)hostBundlePath updateDirectoryPath:(NSString *)updateDirectoryPath downloadName:(NSString *)downloadName dsaSignature:(NSString *)dsaSignature decryptionPassword:(nullable NSString *)decryptionPassword;
|
||||
- (instancetype)initWithRelaunchPath:(NSString *)relaunchPath hostBundlePath:(NSString *)hostBundlePath updateDirectoryPath:(NSString *)updateDirectoryPath downloadName:(NSString *)downloadName installationType:(NSString *)installationType dsaSignature:(NSString *)dsaSignature decryptionPassword:(nullable NSString *)decryptionPassword;
|
||||
|
||||
@property (nonatomic, copy, readonly) NSString *relaunchPath;
|
||||
@property (nonatomic, copy, readonly, nullable) NSString *progressToolPath;
|
||||
@property (nonatomic, copy, readonly) NSString *hostBundlePath;
|
||||
@property (nonatomic, copy, readonly) NSString *updateDirectoryPath;
|
||||
@property (nonatomic, copy, readonly) NSString *downloadName;
|
||||
@property (nonatomic, copy, readonly) NSString *installationType;
|
||||
@property (nonatomic, copy, readonly) NSString *dsaSignature;
|
||||
@property (nonatomic, copy, readonly, nullable) NSString *decryptionPassword;
|
||||
|
||||
+19
-10
@@ -7,34 +7,42 @@
|
||||
//
|
||||
|
||||
#import "SUInstallationInputData.h"
|
||||
#import "SUInstallationType.h"
|
||||
|
||||
#ifdef _APPKITDEFINES_H
|
||||
#error This is a "daemon-safe" class and should NOT import AppKit
|
||||
#endif
|
||||
|
||||
static NSString *SURelaunchPathKey = @"SURelaunchPath";
|
||||
static NSString *SUProgressToolPathKey = @"SUProgressToolPath";
|
||||
static NSString *SUHostBundlePathKey = @"SUHostBundlePath";
|
||||
static NSString *SUUpdateDirectoryPathKey = @"SUUpdateDirectoryPath";
|
||||
static NSString *SUDownloadNameKey = @"SUDownloadName";
|
||||
static NSString *SUDSASignatureKey = @"SUDSASignature";
|
||||
static NSString *SUDecryptionPasswordKey = @"SUDecryptionPassword";
|
||||
static NSString *SUInstallationTypeKey = @"SUInstallationType";
|
||||
|
||||
@implementation SUInstallationInputData
|
||||
|
||||
@synthesize relaunchPath = _relaunchPath;
|
||||
@synthesize progressToolPath = _progressToolPath;
|
||||
@synthesize hostBundlePath = _hostBundlePath;
|
||||
@synthesize updateDirectoryPath = _updateDirectoryPath;
|
||||
@synthesize downloadName = _downloadName;
|
||||
@synthesize dsaSignature = _dsaSignature;
|
||||
@synthesize decryptionPassword = _decryptionPassword;
|
||||
@synthesize installationType = _installationType;
|
||||
|
||||
- (instancetype)initWithRelaunchPath:(NSString *)relaunchPath progressToolPath:(nullable NSString *)progressToolPath hostBundlePath:(NSString *)hostBundlePath updateDirectoryPath:(NSString *)updateDirectoryPath downloadName:(NSString *)downloadName dsaSignature:(NSString *)dsaSignature decryptionPassword:(nullable NSString *)decryptionPassword
|
||||
- (instancetype)initWithRelaunchPath:(NSString *)relaunchPath hostBundlePath:(NSString *)hostBundlePath updateDirectoryPath:(NSString *)updateDirectoryPath downloadName:(NSString *)downloadName installationType:(NSString *)installationType dsaSignature:(NSString *)dsaSignature decryptionPassword:(nullable NSString *)decryptionPassword
|
||||
{
|
||||
self = [super init];
|
||||
if (self != nil) {
|
||||
_relaunchPath = [relaunchPath copy];
|
||||
_progressToolPath = [progressToolPath copy];
|
||||
_hostBundlePath = [hostBundlePath copy];
|
||||
_updateDirectoryPath = [updateDirectoryPath copy];
|
||||
_downloadName = [downloadName copy];
|
||||
|
||||
_installationType = [installationType copy];
|
||||
assert(SUValidInstallationType(_installationType));
|
||||
|
||||
_dsaSignature = [dsaSignature copy];
|
||||
_decryptionPassword = [decryptionPassword copy];
|
||||
}
|
||||
@@ -48,8 +56,6 @@ static NSString *SUDecryptionPasswordKey = @"SUDecryptionPassword";
|
||||
return nil;
|
||||
}
|
||||
|
||||
NSString *progressToolPath = [decoder decodeObjectOfClass:[NSString class] forKey:SUProgressToolPathKey];
|
||||
|
||||
NSString *hostBundlePath = [decoder decodeObjectOfClass:[NSString class] forKey:SUHostBundlePathKey];
|
||||
if (hostBundlePath == nil) {
|
||||
return nil;
|
||||
@@ -65,6 +71,11 @@ static NSString *SUDecryptionPasswordKey = @"SUDecryptionPassword";
|
||||
return nil;
|
||||
}
|
||||
|
||||
NSString *installationType = [decoder decodeObjectOfClass:[NSString class] forKey:SUInstallationTypeKey];
|
||||
if (!SUValidInstallationType(installationType)) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
NSString *dsaSignature = [decoder decodeObjectOfClass:[NSString class] forKey:SUDSASignatureKey];
|
||||
if (dsaSignature == nil) {
|
||||
return nil;
|
||||
@@ -72,17 +83,15 @@ static NSString *SUDecryptionPasswordKey = @"SUDecryptionPassword";
|
||||
|
||||
NSString *decryptionPassword = [decoder decodeObjectOfClass:[NSString class] forKey:SUDecryptionPasswordKey];
|
||||
|
||||
return [self initWithRelaunchPath:relaunchPath progressToolPath:progressToolPath hostBundlePath:hostBundlePath updateDirectoryPath:updateDirectoryPath downloadName:downloadName dsaSignature:dsaSignature decryptionPassword:decryptionPassword];
|
||||
return [self initWithRelaunchPath:relaunchPath hostBundlePath:hostBundlePath updateDirectoryPath:updateDirectoryPath downloadName:downloadName installationType:installationType dsaSignature:dsaSignature decryptionPassword:decryptionPassword];
|
||||
}
|
||||
|
||||
- (void)encodeWithCoder:(NSCoder *)coder
|
||||
{
|
||||
[coder encodeObject:self.relaunchPath forKey:SURelaunchPathKey];
|
||||
if (self.progressToolPath != nil) {
|
||||
[coder encodeObject:self.progressToolPath forKey:SUProgressToolPathKey];
|
||||
}
|
||||
[coder encodeObject:self.hostBundlePath forKey:SUHostBundlePathKey];
|
||||
[coder encodeObject:self.updateDirectoryPath forKey:SUUpdateDirectoryPathKey];
|
||||
[coder encodeObject:self.installationType forKey:SUInstallationTypeKey];
|
||||
[coder encodeObject:self.downloadName forKey:SUDownloadNameKey];
|
||||
[coder encodeObject:self.dsaSignature forKey:SUDSASignatureKey];
|
||||
if (self.decryptionPassword != nil) {
|
||||
@@ -16,7 +16,7 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@interface SUInstaller : NSObject
|
||||
|
||||
+ (nullable id<SUInstallerProtocol>)installerForHost:(SUHost *)host updateDirectory:(NSString *)updateDirectory allowingInteraction:(BOOL)allowsInteraction versionComparator:(id <SUVersionComparison>)comparator error:(NSError **)error;
|
||||
+ (nullable id<SUInstallerProtocol>)installerForHost:(SUHost *)host expectedInstallationType:(NSString *)expectedInstallationType updateDirectory:(NSString *)updateDirectory allowingInteraction:(BOOL)allowsInteraction versionComparator:(id <SUVersionComparison>)comparator error:(NSError **)error;
|
||||
|
||||
+ (NSString *)installSourcePathInUpdateFolder:(NSString *)inUpdateFolder forHost:(SUHost *)host isPackage:(BOOL *)isPackagePtr isGuided:(nullable BOOL *)isGuidedPtr;
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
#import "SULog.h"
|
||||
#import "SUParameterAssert.h"
|
||||
#import "SUErrors.h"
|
||||
#import "SUInstallationType.h"
|
||||
|
||||
#ifdef _APPKITDEFINES_H
|
||||
#error This is a "core" class and should NOT import AppKit
|
||||
@@ -112,7 +113,7 @@
|
||||
return newAppDownloadPath;
|
||||
}
|
||||
|
||||
+ (nullable id<SUInstallerProtocol>)installerForHost:(SUHost *)host updateDirectory:(NSString *)updateDirectory allowingInteraction:(BOOL)allowsInteraction versionComparator:(id <SUVersionComparison>)comparator error:(NSError * __autoreleasing *)error
|
||||
+ (nullable id<SUInstallerProtocol>)installerForHost:(SUHost *)host expectedInstallationType:(NSString *)expectedInstallationType updateDirectory:(NSString *)updateDirectory allowingInteraction:(BOOL)allowsInteraction versionComparator:(id <SUVersionComparison>)comparator error:(NSError * __autoreleasing *)error
|
||||
{
|
||||
BOOL isPackage = NO;
|
||||
BOOL isGuided = NO;
|
||||
@@ -125,16 +126,43 @@
|
||||
return nil;
|
||||
}
|
||||
|
||||
// If the installer does not allow interaction, we could be running as root
|
||||
// If we are running as root, using a non-guided package installer does not work properly so avoid it at all costs
|
||||
// Make sure we find the type of installer that we were expecting to find
|
||||
// We shouldn't implicitly trust the installation type fed into here from the appcast because the installation type helps us determine
|
||||
// ahead of time whether or not this installer tool should be ran as root or not
|
||||
id <SUInstallerProtocol> installer = nil;
|
||||
if (isPackage && (isGuided || !allowsInteraction)) {
|
||||
installer = [[SUGuidedPackageInstaller alloc] initWithPackagePath:newDownloadPath];
|
||||
if (isPackage && isGuided) {
|
||||
if (![expectedInstallationType isEqualToString:SUInstallationTypeGuidedPackage]) {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Found guided package installer but '%@=%@' was probably missing in the appcast item enclosure", SUAppcastAttributeInstallationType, SUInstallationTypeGuidedPackage] }];
|
||||
}
|
||||
} else {
|
||||
installer = [[SUGuidedPackageInstaller alloc] initWithPackagePath:newDownloadPath];
|
||||
}
|
||||
} else if (isPackage) {
|
||||
installer = [[SUPackageInstaller alloc] initWithPackagePath:newDownloadPath];
|
||||
if (![expectedInstallationType isEqualToString:SUInstallationTypePackage]) {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Found package installer but '%@=%@' was probably missing in the appcast item enclosure", SUAppcastAttributeInstallationType, SUInstallationTypePackage] }];
|
||||
}
|
||||
} else {
|
||||
#warning review this
|
||||
// Even if we expect an ordinary package, if we don't allow interaction (eg: because we're already running root) -
|
||||
// we should try a guided installation instead - because an ordinary package installation may not work well
|
||||
if (allowsInteraction) {
|
||||
installer = [[SUPackageInstaller alloc] initWithPackagePath:newDownloadPath];
|
||||
} else {
|
||||
installer = [[SUGuidedPackageInstaller alloc] initWithPackagePath:newDownloadPath];
|
||||
}
|
||||
}
|
||||
} else {
|
||||
installer = [[SUPlainInstaller alloc] initWithHost:host applicationPath:newDownloadPath installationPath:[[self class] installationPathForHost:host] versionComparator:comparator];
|
||||
if (![expectedInstallationType isEqualToString:SUInstallationTypeApplication]) {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Found regular application update but expected '%@=%@' from the appcast item enclosure instead", SUAppcastAttributeInstallationType, expectedInstallationType] }];
|
||||
}
|
||||
} else {
|
||||
installer = [[SUPlainInstaller alloc] initWithHost:host applicationPath:newDownloadPath installationPath:[[self class] installationPathForHost:host] versionComparator:comparator];
|
||||
}
|
||||
}
|
||||
|
||||
return installer;
|
||||
}
|
||||
|
||||
@@ -8,8 +8,6 @@
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
@class SUAuthorizationEnvironment;
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@protocol SUInstallerProtocol <NSObject>
|
||||
@@ -25,7 +23,7 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
// The allowsUI flag indicates whether this and the 3rd stage can show UI or not, possibly affecting whether or not this stage succeeds.
|
||||
// Eg: This may be appropriate for first showing an authorization prompt before the user application is terminated (if the operation succeeds)
|
||||
// Should be able to be called from non-main thread
|
||||
- (BOOL)performSecondStageAllowingAuthorization:(BOOL)allowsAuthorization fileOperationToolPath:(NSString *)fileOperationToolPath environment:(SUAuthorizationEnvironment * _Nullable)authorizationEnvironment allowingUI:(BOOL)allowsUI error:(NSError **)error;
|
||||
- (BOOL)performSecondStageAllowingUI:(BOOL)allowsUI error:(NSError **)error;
|
||||
|
||||
// Stage 3 occurs after the user application has has been terminated. This is where the final installation work can be done.
|
||||
// After this stage is done, the user application will be relaunched.
|
||||
@@ -42,10 +40,6 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
// Should be thread safe
|
||||
- (BOOL)canInstallSilently;
|
||||
|
||||
// Indicates whether or not this installer may need authorization when performing the second stage of the installation
|
||||
// Should be thread safe
|
||||
- (BOOL)mayNeedToRequestAuthorization;
|
||||
|
||||
// Cleans up work done from any of the previous stages. This should be invoked after stage 3 succeeds,
|
||||
// or after any one of the stages fails.
|
||||
// Should be able to be called from non-main thread
|
||||
@@ -43,4 +43,8 @@ NSString *SUInstallerServiceNameForBundleIdentifier(NSString *bundleIdentifier);
|
||||
|
||||
NSString *SUStatusInfoServiceNameForBundleIdentifier(NSString *bundleIdentifier);
|
||||
|
||||
NSString *SUProgressAgentServiceNameForBundleIdentifier(NSString *bundleIdentifier);
|
||||
|
||||
NSString *SUProgressAgentLauncherServiceNameForBundleIdentifier(NSString *bundleIdentifier);
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@@ -15,6 +15,8 @@ NSString *SUAppcastItemArchiveKey = @"SUAppcastItemArchive";
|
||||
// These should be very short because length restrictions exist on earlier versions of macOS
|
||||
#define SPARKLE_INSTALLER_TAG @"-spki"
|
||||
#define SPARKLE_STATUS_TAG @"-spks"
|
||||
#define SPARKLE_PROGRESS_TAG @"-spkp"
|
||||
#define SPARKLE_PROGRESS_LAUNCH_INSTALLER_TAG @"-spkl"
|
||||
|
||||
// macOS 10.8 at least can't handle service names that are 64 characters or longer
|
||||
// This was fixed some point after 10.8, but I'm not sure if it was fixed in 10.9 or 10.10 or 10.11
|
||||
@@ -77,3 +79,13 @@ NSString *SUStatusInfoServiceNameForBundleIdentifier(NSString *bundleIdentifier)
|
||||
{
|
||||
return SUServiceNameWithTag(SPARKLE_STATUS_TAG, bundleIdentifier);
|
||||
}
|
||||
|
||||
NSString *SUProgressAgentServiceNameForBundleIdentifier(NSString *bundleIdentifier)
|
||||
{
|
||||
return SUServiceNameWithTag(SPARKLE_PROGRESS_TAG, bundleIdentifier);
|
||||
}
|
||||
|
||||
NSString *SUProgressAgentLauncherServiceNameForBundleIdentifier(NSString *bundleIdentifier)
|
||||
{
|
||||
return SUServiceNameWithTag(SPARKLE_PROGRESS_LAUNCH_INSTALLER_TAG, bundleIdentifier);
|
||||
}
|
||||
File renamed without changes.
@@ -47,7 +47,7 @@ static NSString *SUOpenUtilityPath = @"/usr/bin/open";
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (BOOL)performSecondStageAllowingAuthorization:(BOOL)__unused allowsAuthorization fileOperationToolPath:(NSString *)__unused fileOperationToolPath environment:(SUAuthorizationEnvironment * _Nullable)__unused authorizationEnvironment allowingUI:(BOOL)allowsUI error:(NSError * __autoreleasing *)error
|
||||
- (BOOL)performSecondStageAllowingUI:(BOOL)allowsUI error:(NSError * __autoreleasing *)error
|
||||
{
|
||||
if (!allowsUI) {
|
||||
if (error != NULL) {
|
||||
@@ -91,11 +91,6 @@ static NSString *SUOpenUtilityPath = @"/usr/bin/open";
|
||||
return NO;
|
||||
}
|
||||
|
||||
- (BOOL)mayNeedToRequestAuthorization
|
||||
{
|
||||
return NO;
|
||||
}
|
||||
|
||||
- (void)cleanup
|
||||
{
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -227,22 +227,11 @@
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (BOOL)performSecondStageAllowingAuthorization:(BOOL)allowsAuthorization fileOperationToolPath:(NSString *)fileOperationToolPath environment:(SUAuthorizationEnvironment * _Nullable)authorizationEnvironment allowingUI:(BOOL)allowsUI error:(NSError * __autoreleasing *)error
|
||||
- (BOOL)performSecondStageAllowingUI:(BOOL)allowsUI error:(NSError * __autoreleasing *)error
|
||||
{
|
||||
self.fileManager = (allowsAuthorization && allowsUI) ? [SUFileManager fileManagerWithAuthorizationToolPath:fileOperationToolPath environment:authorizationEnvironment] : [SUFileManager defaultManager];
|
||||
self.fileManager = [SUFileManager defaultManager];
|
||||
|
||||
// Bring up authorization prompt right away if we need it
|
||||
BOOL canInstallSilently = [self canInstallSilently];
|
||||
if (allowsAuthorization && !canInstallSilently) {
|
||||
return [self.fileManager grantAuthorizationPrivilegesWithError:error];
|
||||
} else {
|
||||
if (!canInstallSilently) {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUDowngradeError userInfo:@{ NSLocalizedDescriptionKey: @"Sparkle cannot install the update silently" }];
|
||||
}
|
||||
}
|
||||
return canInstallSilently;
|
||||
}
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (BOOL)performThirdStage:(NSError * __autoreleasing *)error
|
||||
@@ -259,21 +248,12 @@
|
||||
|
||||
- (BOOL)canInstallSilently
|
||||
{
|
||||
return ![self mayNeedToRequestAuthorization];
|
||||
}
|
||||
|
||||
- (BOOL)mayNeedToRequestAuthorization
|
||||
{
|
||||
NSFileManager *fileManager = [NSFileManager defaultManager];
|
||||
NSString *bundlePath = self.host.bundle.bundlePath;
|
||||
// It's very well possible to have the bundle be writable but not be able to write into the parent directory
|
||||
// And if the bundle isn't writable, but we can write into the parent directory, we will still need to authorize to replace it
|
||||
return ![fileManager isWritableFileAtPath:bundlePath] || ![fileManager isWritableFileAtPath:[bundlePath stringByDeletingLastPathComponent]];
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (void)cleanup
|
||||
{
|
||||
SUFileManager *fileManager = [self.fileManager fileManagerByPreservingAuthorizationRights];;
|
||||
SUFileManager *fileManager = self.fileManager;
|
||||
NSURL *oldTempURL = self.oldTempURL;
|
||||
NSURL *tempOldDirectoryURL = self.tempOldDirectoryURL;
|
||||
NSURL *tempNewDirectoryURL = self.tempNewDirectoryURL;
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -8,7 +8,10 @@
|
||||
|
||||
#import "StatusInfo.h"
|
||||
#import "SUMessageTypes.h"
|
||||
#import "SULog.h"
|
||||
|
||||
#ifdef _APPKITDEFINES_H
|
||||
#error This is a "daemon-safe" class and should NOT import AppKit
|
||||
#endif
|
||||
|
||||
@interface StatusInfo () <NSXPCListenerDelegate>
|
||||
|
||||
File renamed without changes.
@@ -14,7 +14,7 @@
|
||||
#include <sys/time.h>
|
||||
|
||||
#ifdef _APPKITDEFINES_H
|
||||
#error This is class should NOT import AppKit
|
||||
#error This is a "daemon-safe" class and should NOT import AppKit
|
||||
#endif
|
||||
|
||||
@interface TerminationListener ()
|
||||
File renamed without changes.
@@ -3,7 +3,6 @@
|
||||
SPARKLE_BUNDLE_IDENTIFIER = org.sparkle-project.Sparkle
|
||||
SPARKLE_RELAUNCH_TOOL_NAME = Autoupdate
|
||||
SPARKLE_INSTALLER_PROGRESS_TOOL_NAME = Updater
|
||||
SPARKLE_FILEOP_TOOL_NAME = fileop
|
||||
|
||||
SPARKLE_APPEND_VERSION_NUMBER = 1
|
||||
|
||||
@@ -46,7 +45,7 @@ INSTALLER_LAUNCHER_BUNDLE_ID = org.sparkle-project.${INSTALLER_LAUNCHER_PRODUCT_
|
||||
TEMPORARY_DOWNLOADER_BUNDLE_ID = org.sparkle-project.${TEMPORARY_DOWNLOADER_PRODUCT_NAME}
|
||||
PERSISTENT_DOWNLOADER_BUNDLE_ID = org.sparkle-project.${PERSISTENT_DOWNLOADER_PRODUCT_NAME}
|
||||
|
||||
GCC_PREPROCESSOR_DEFINITIONS_COMMON = SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME=$(SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME) SPARKLE_AUTOMATED_DOWNGRADES=$(SPARKLE_AUTOMATED_DOWNGRADES) SPARKLE_APPEND_VERSION_NUMBER=$(SPARKLE_APPEND_VERSION_NUMBER) SPARKLE_BUNDLE_IDENTIFIER=\"$(SPARKLE_BUNDLE_IDENTIFIER)\" CURRENT_PROJECT_VERSION=\"$(CURRENT_PROJECT_VERSION)\" SPARKLE_RELAUNCH_TOOL_NAME=\"$(SPARKLE_RELAUNCH_TOOL_NAME)\" SPARKLE_INSTALLER_PROGRESS_TOOL_NAME=\"$(SPARKLE_INSTALLER_PROGRESS_TOOL_NAME)\" SPARKLE_ICON_NAME=\"$(SPARKLE_ICON_NAME)\" INSTALLER_LAUNCHER_BUNDLE_ID=\"${INSTALLER_LAUNCHER_BUNDLE_ID}\" INSTALLER_CONNECTION_BUNDLE_ID=\"${INSTALLER_CONNECTION_BUNDLE_ID}\" INSTALLER_STATUS_BUNDLE_ID=\"${INSTALLER_STATUS_BUNDLE_ID}\" TEMPORARY_DOWNLOADER_BUNDLE_ID=\"${TEMPORARY_DOWNLOADER_BUNDLE_ID}\" PERSISTENT_DOWNLOADER_BUNDLE_ID=\"${PERSISTENT_DOWNLOADER_BUNDLE_ID}\" INSTALLER_LAUNCHER_PRODUCT_NAME=\"${INSTALLER_LAUNCHER_PRODUCT_NAME}\" INSTALLER_CONNECTION_PRODUCT_NAME=\"${INSTALLER_CONNECTION_PRODUCT_NAME}\" INSTALLER_STATUS_PRODUCT_NAME=\"${INSTALLER_STATUS_PRODUCT_NAME}\" TEMPORARY_DOWNLOADER_PRODUCT_NAME=\"${TEMPORARY_DOWNLOADER_PRODUCT_NAME}\" PERSISTENT_DOWNLOADER_PRODUCT_NAME=\"${PERSISTENT_DOWNLOADER_PRODUCT_NAME}\" SPARKLE_FILEOP_TOOL_NAME=\"$(SPARKLE_FILEOP_TOOL_NAME)\"
|
||||
GCC_PREPROCESSOR_DEFINITIONS_COMMON = SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME=$(SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME) SPARKLE_AUTOMATED_DOWNGRADES=$(SPARKLE_AUTOMATED_DOWNGRADES) SPARKLE_APPEND_VERSION_NUMBER=$(SPARKLE_APPEND_VERSION_NUMBER) SPARKLE_BUNDLE_IDENTIFIER=\"$(SPARKLE_BUNDLE_IDENTIFIER)\" CURRENT_PROJECT_VERSION=\"$(CURRENT_PROJECT_VERSION)\" SPARKLE_RELAUNCH_TOOL_NAME=\"$(SPARKLE_RELAUNCH_TOOL_NAME)\" SPARKLE_INSTALLER_PROGRESS_TOOL_NAME=\"$(SPARKLE_INSTALLER_PROGRESS_TOOL_NAME)\" SPARKLE_ICON_NAME=\"$(SPARKLE_ICON_NAME)\" INSTALLER_LAUNCHER_BUNDLE_ID=\"${INSTALLER_LAUNCHER_BUNDLE_ID}\" INSTALLER_CONNECTION_BUNDLE_ID=\"${INSTALLER_CONNECTION_BUNDLE_ID}\" INSTALLER_STATUS_BUNDLE_ID=\"${INSTALLER_STATUS_BUNDLE_ID}\" TEMPORARY_DOWNLOADER_BUNDLE_ID=\"${TEMPORARY_DOWNLOADER_BUNDLE_ID}\" PERSISTENT_DOWNLOADER_BUNDLE_ID=\"${PERSISTENT_DOWNLOADER_BUNDLE_ID}\" INSTALLER_LAUNCHER_PRODUCT_NAME=\"${INSTALLER_LAUNCHER_PRODUCT_NAME}\" INSTALLER_CONNECTION_PRODUCT_NAME=\"${INSTALLER_CONNECTION_PRODUCT_NAME}\" INSTALLER_STATUS_PRODUCT_NAME=\"${INSTALLER_STATUS_PRODUCT_NAME}\" TEMPORARY_DOWNLOADER_PRODUCT_NAME=\"${TEMPORARY_DOWNLOADER_PRODUCT_NAME}\" PERSISTENT_DOWNLOADER_PRODUCT_NAME=\"${PERSISTENT_DOWNLOADER_PRODUCT_NAME}\"
|
||||
|
||||
CLANG_ENABLE_OBJC_ARC = YES
|
||||
GCC_ENABLE_PASCAL_STRINGS = NO
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
// Fileop tool only
|
||||
|
||||
PRODUCT_NAME = $(SPARKLE_FILEOP_TOOL_NAME)
|
||||
SKIP_INSTALL = YES
|
||||
CLANG_ENABLE_MODULES = NO
|
||||
@@ -1,6 +1,5 @@
|
||||
// Relaunch Tool only
|
||||
|
||||
INFOPLIST_FILE = Sparkle/Autoupdate/Autoupdate-Info.plist
|
||||
PRODUCT_NAME = $(SPARKLE_RELAUNCH_TOOL_NAME)
|
||||
SKIP_INSTALL = YES
|
||||
CLANG_ENABLE_MODULES = NO
|
||||
@@ -58,9 +58,9 @@ static NSString *SUInstallerConnectionKeepAliveReason = @"Installer Connection K
|
||||
[self enableAutomaticTermination];
|
||||
}
|
||||
|
||||
- (void)setServiceName:(NSString *)serviceName
|
||||
- (void)setServiceName:(NSString *)serviceName hostPath:(NSString *)hostPath installationType:(NSString *)installationType
|
||||
{
|
||||
NSXPCConnectionOptions options = SUGrantsSystemAuthorizationAccess() ? NSXPCConnectionPrivileged : 0;
|
||||
NSXPCConnectionOptions options = SUNeedsSystemAuthorizationAccess(hostPath, installationType, NULL) ? NSXPCConnectionPrivileged : 0;
|
||||
NSXPCConnection *connection = [[NSXPCConnection alloc] initWithMachServiceName:serviceName options:options];
|
||||
|
||||
connection.exportedInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUInstallerCommunicationProtocol)];
|
||||
@@ -72,7 +72,7 @@ static NSString *SUInstallerConnectionKeepAliveReason = @"Installer Connection K
|
||||
|
||||
__weak SUInstallerConnection *weakSelf = self;
|
||||
self.connection.interruptionHandler = ^{
|
||||
[weakSelf invalidate];
|
||||
[weakSelf.connection invalidate];
|
||||
};
|
||||
|
||||
self.connection.invalidationHandler = ^{
|
||||
|
||||
@@ -18,7 +18,7 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
- (void)setInvalidationHandler:(void (^)(void))invalidationHandler;
|
||||
|
||||
- (void)setServiceName:(NSString *)serviceName;
|
||||
- (void)setServiceName:(NSString *)serviceName hostPath:(NSString *)hostPath installationType:(NSString *)installationType;
|
||||
|
||||
- (void)invalidate;
|
||||
|
||||
|
||||
@@ -59,9 +59,9 @@
|
||||
}];
|
||||
}
|
||||
|
||||
- (void)setServiceName:(NSString *)serviceName
|
||||
- (void)setServiceName:(NSString *)serviceName hostPath:(NSString *)hostPath installationType:(NSString *)installationType
|
||||
{
|
||||
[self.connection.remoteObjectProxy setServiceName:serviceName];
|
||||
[self.connection.remoteObjectProxy setServiceName:serviceName hostPath:hostPath installationType:installationType];
|
||||
}
|
||||
|
||||
- (void)handleMessageWithIdentifier:(int32_t)identifier data:(NSData *)data
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
//
|
||||
// SUAuthorizationReply.h
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Mayur Pawashe on 7/18/16.
|
||||
// Copyright © 2016 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
typedef NS_ENUM(NSUInteger, SUAuthorizationReply)
|
||||
{
|
||||
SUAuthorizationReplySuccess = 0,
|
||||
SUAuthorizationReplyCanceled = 1,
|
||||
SUAuthorizationReplyFailure = 2,
|
||||
SUAuthorizationReplyAuthorizeLater = 3
|
||||
};
|
||||
@@ -10,76 +10,293 @@
|
||||
#import "SUFileManager.h"
|
||||
#import "SULog.h"
|
||||
#import "SUMessageTypes.h"
|
||||
#import <ServiceManagement/SMLoginItem.h>
|
||||
#import "SUSystemAuthorization.h"
|
||||
#import "SUBundleIcon.h"
|
||||
|
||||
#ifdef _APPKITDEFINES_H
|
||||
#error This is a "core" class and should NOT import AppKit
|
||||
#endif
|
||||
|
||||
@implementation SUInstallerLauncher
|
||||
|
||||
- (void)launchInstallerAtPath:(NSString *)installerPath withHostBundleIdentifier:(NSString *)hostBundleIdentifier allowingInteraction:(BOOL)allowingInteraction completion:(void (^)(BOOL success))completionHandler
|
||||
- (BOOL)submitProgressToolAtPath:(NSString *)progressToolPath withHostBundle:(NSBundle *)hostBundle inSystemDomainForInstaller:(BOOL)inSystemDomainForInstaller
|
||||
{
|
||||
SUFileManager *fileManager = [SUFileManager defaultManager];
|
||||
|
||||
NSURL *progressToolURL = [NSURL fileURLWithPath:progressToolPath];
|
||||
|
||||
NSError *quarantineError = nil;
|
||||
if (![fileManager releaseItemFromQuarantineAtRootURL:progressToolURL error:&quarantineError]) {
|
||||
// This may or may not be a fatal error depending on if the process is sandboxed or not
|
||||
SULog(@"Failed to release quarantine on installer at %@ with error %@", progressToolPath, quarantineError);
|
||||
}
|
||||
|
||||
NSString *executablePath = [[NSBundle bundleWithURL:progressToolURL] executablePath];
|
||||
assert(executablePath != nil);
|
||||
|
||||
NSString *hostBundlePath = hostBundle.bundlePath;
|
||||
assert(hostBundlePath != nil);
|
||||
|
||||
NSString *hostBundleIdentifier = hostBundle.bundleIdentifier;
|
||||
assert(hostBundleIdentifier != nil);
|
||||
|
||||
NSArray<NSString *> *arguments = @[executablePath, hostBundlePath, @(inSystemDomainForInstaller).stringValue];
|
||||
|
||||
#warning support running under system domain if updater is running as root - this means we would have to try running job under a different user
|
||||
CFStringRef domain = kSMDomainUserLaunchd;
|
||||
NSString *label = [NSString stringWithFormat:@"%@-sparkle-progress", hostBundleIdentifier];
|
||||
|
||||
AuthorizationRef auth = NULL;
|
||||
Boolean submittedJob = false;
|
||||
OSStatus createStatus = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, kAuthorizationFlagDefaults, &auth);
|
||||
if (createStatus == errAuthorizationSuccess) {
|
||||
// Try to remove the job from launchd if it is already running
|
||||
// We could invoke SMJobCopyDictionary() first to see if the job exists, but I'd rather avoid
|
||||
// using it because the headers indicate it may be removed one day without any replacement
|
||||
CFErrorRef removeError = NULL;
|
||||
if (!SMJobRemove(domain, (__bridge CFStringRef)(label), auth, true, &removeError)) {
|
||||
if (removeError != NULL) {
|
||||
// It's normal for a job to not be found, so this is not an interesting error
|
||||
if (CFErrorGetCode(removeError) != kSMErrorJobNotFound) {
|
||||
SULog(@"Remove error: %@", removeError);
|
||||
}
|
||||
CFRelease(removeError);
|
||||
}
|
||||
}
|
||||
|
||||
NSMutableDictionary *jobDictionary = [[NSMutableDictionary alloc] init];
|
||||
jobDictionary[@"Label"] = label;
|
||||
jobDictionary[@"ProgramArguments"] = arguments;
|
||||
jobDictionary[@"EnableTransactions"] = @NO;
|
||||
jobDictionary[@"KeepAlive"] = @{@"SuccessfulExit" : @NO};
|
||||
jobDictionary[@"RunAtLoad"] = @NO;
|
||||
jobDictionary[@"NICE"] = @0;
|
||||
jobDictionary[@"LaunchOnlyOnce"] = @YES;
|
||||
jobDictionary[@"MachServices"] = @{SUStatusInfoServiceNameForBundleIdentifier(hostBundleIdentifier) : @YES};
|
||||
|
||||
CFErrorRef submitError = NULL;
|
||||
submittedJob = SMJobSubmit(domain, (__bridge CFDictionaryRef)(jobDictionary), auth, &submitError);
|
||||
if (!submittedJob) {
|
||||
if (submitError != NULL) {
|
||||
SULog(@"Submit progress error: %@", submitError);
|
||||
CFRelease(submitError);
|
||||
}
|
||||
}
|
||||
|
||||
AuthorizationFree(auth, kAuthorizationFlagDefaults);
|
||||
}
|
||||
|
||||
return (submittedJob == true);
|
||||
}
|
||||
|
||||
- (SUAuthorizationReply)submitInstallerAtPath:(NSString *)installerPath withHostBundle:(NSBundle *)hostBundle authorizationPrompt:(NSString *)authorizationPrompt allowingInteraction:(BOOL)allowingInteraction inSystemDomain:(BOOL)systemDomain
|
||||
{
|
||||
SUFileManager *fileManager = [SUFileManager defaultManager];
|
||||
|
||||
NSURL *installerURL = [NSURL fileURLWithPath:installerPath];
|
||||
|
||||
NSError *quarantineError = nil;
|
||||
if (![fileManager releaseItemFromQuarantineAtRootURL:installerURL error:&quarantineError]) {
|
||||
// Probably not a fatal error because we are submitting the executable through launchd
|
||||
SULog(@"Failed to release quarantine on installer at %@ with error %@", installerPath, quarantineError);
|
||||
}
|
||||
|
||||
NSString *hostBundleIdentifier = hostBundle.bundleIdentifier;
|
||||
assert(hostBundleIdentifier != nil);
|
||||
|
||||
NSArray<NSString *> *arguments = @[installerPath, hostBundleIdentifier, @(allowingInteraction).stringValue];
|
||||
|
||||
AuthorizationRef auth = NULL;
|
||||
OSStatus createStatus = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, kAuthorizationFlagDefaults, &auth);
|
||||
if (createStatus != errAuthorizationSuccess) {
|
||||
auth = NULL;
|
||||
SULog(@"Failed to create authorization reference: %d", createStatus);
|
||||
}
|
||||
|
||||
BOOL canceledAuthorization = NO;
|
||||
BOOL failedToUseSystemDomain = NO;
|
||||
if (auth != NULL && systemDomain) {
|
||||
// See Apple's 'EvenBetterAuthorizationSample' sample code and
|
||||
// https://developer.apple.com/library/mac/technotes/tn2095/_index.html#//apple_ref/doc/uid/DTS10003110-CH1-SECTION7
|
||||
// We can set a custom right name for authenticating as an administrator
|
||||
// Using this right rather than using something like kSMRightModifySystemDaemons allows us to present a better worded prompt
|
||||
|
||||
const char *rightName = [[NSString stringWithFormat:@"%@.sparkle-auth", hostBundleIdentifier] UTF8String];
|
||||
assert(rightName != NULL);
|
||||
|
||||
OSStatus getRightResult = AuthorizationRightGet(rightName, NULL);
|
||||
if (getRightResult == errAuthorizationDenied) {
|
||||
if (AuthorizationRightSet(auth, rightName, (__bridge CFTypeRef _Nonnull)(@(kAuthorizationRuleAuthenticateAsAdmin)), (__bridge CFStringRef _Nullable)(authorizationPrompt), NULL, NULL) != errAuthorizationSuccess) {
|
||||
SULog(@"Failed to make auth right set");
|
||||
}
|
||||
}
|
||||
|
||||
AuthorizationItem right = { .name = rightName, .valueLength = 0, .value = NULL, .flags = 0 };
|
||||
AuthorizationRights rights = { .count = 1, .items = &right };
|
||||
|
||||
AuthorizationFlags flags = (AuthorizationFlags)(kAuthorizationFlagExtendRights | kAuthorizationFlagInteractionAllowed);
|
||||
|
||||
AuthorizationItem iconAuthorizationItem = {.name = kAuthorizationEnvironmentIcon, .valueLength = 0, .value = NULL, .flags = 0};
|
||||
AuthorizationEnvironment authorizationEnvironment = {.count = 0, .items = NULL};
|
||||
|
||||
// Find a 32x32 image representation of the icon, and write out a PNG version of it to a temporary location
|
||||
// Then use the icon (if one is available) for the authorization prompt
|
||||
// NSImage is not used because it relies on AppKit
|
||||
NSURL *tempIconDestinationURL = nil;
|
||||
NSURL *iconURL = [SUBundleIcon iconURLForBundle:hostBundle];
|
||||
if (iconURL != nil) {
|
||||
CGImageSourceRef imageSource = CGImageSourceCreateWithURL((CFURLRef)iconURL, (CFDictionaryRef)@{});
|
||||
if (imageSource != NULL) {
|
||||
size_t imageCount = CGImageSourceGetCount(imageSource);
|
||||
for (size_t imageIndex = 0; imageIndex < imageCount; imageIndex++) {
|
||||
CFDictionaryRef cfProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, imageIndex, (CFDictionaryRef)@{});
|
||||
NSDictionary *properties = (__bridge NSDictionary *)(cfProperties);
|
||||
|
||||
NSNumber *pixelWidth = properties[(const NSString *)kCGImagePropertyPixelWidth];
|
||||
NSNumber *pixelHeight = properties[(const NSString *)kCGImagePropertyPixelHeight];
|
||||
|
||||
// If we don't find a 32x32 image representation, then we don't provide an icon
|
||||
// Don't try to make up with it by eg: converting an image representation to this size
|
||||
// The app developer should be providing the icon representation.
|
||||
// The authorization API may not take other size dimensions.
|
||||
NSNumber *targetDimension = @32;
|
||||
if ([pixelWidth isKindOfClass:[NSNumber class]] && [pixelHeight isKindOfClass:[NSNumber class]] && [pixelWidth isEqualToNumber:targetDimension] && [pixelHeight isEqualToNumber:targetDimension]) {
|
||||
|
||||
// Use /tmp rather than NSTemporaryDirectory() or SUFileManager's temp directory function because we want:
|
||||
// a) no spaces in the path (SU/NSFileManager fails here)
|
||||
// b) short file path that does not exceed a small threshold (NSTemporaryDirectory() fails here)
|
||||
// These limitations only apply to older systems (eg: macOS 10.8)
|
||||
// The file also needs to be placed in a system readable place such as /tmp
|
||||
// See https://github.com/sparkle-project/Sparkle/issues/347#issuecomment-149523848 for more info
|
||||
char pathBuffer[] = "/tmp/XXXXXX.png";
|
||||
int tempIconFile = mkstemps(pathBuffer, strlen(".png"));
|
||||
if (tempIconFile == -1) {
|
||||
SULog(@"Failed to open temp icon from path buffer with error: %d", errno);
|
||||
} else {
|
||||
close(tempIconFile);
|
||||
|
||||
NSString *path = [[NSString alloc] initWithUTF8String:pathBuffer];
|
||||
tempIconDestinationURL = [NSURL fileURLWithPath:path];
|
||||
|
||||
CGImageDestinationRef imageDestination = CGImageDestinationCreateWithURL((CFURLRef)tempIconDestinationURL, kUTTypePNG, 1, NULL);
|
||||
if (imageDestination != NULL) {
|
||||
CGImageDestinationAddImageFromSource(imageDestination, imageSource, imageIndex, (CFDictionaryRef)@{});
|
||||
if (CGImageDestinationFinalize(imageDestination)) {
|
||||
iconAuthorizationItem.valueLength = strlen(pathBuffer);
|
||||
iconAuthorizationItem.value = pathBuffer;
|
||||
|
||||
authorizationEnvironment.count = 1;
|
||||
authorizationEnvironment.items = &iconAuthorizationItem;
|
||||
}
|
||||
|
||||
CFRelease(imageDestination);
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
CFRelease(imageSource);
|
||||
}
|
||||
}
|
||||
|
||||
// This should prompt up the authorization dialog if necessary
|
||||
OSStatus copyStatus = AuthorizationCopyRights(auth, &rights, &authorizationEnvironment, flags, NULL);
|
||||
if (copyStatus != errAuthorizationSuccess) {
|
||||
failedToUseSystemDomain = YES;
|
||||
|
||||
if (copyStatus == errAuthorizationCanceled) {
|
||||
canceledAuthorization = YES;
|
||||
} else {
|
||||
SULog(@"Failed copying system domain rights: %d", copyStatus);
|
||||
}
|
||||
}
|
||||
|
||||
if (tempIconDestinationURL != nil) {
|
||||
[fileManager removeItemAtURL:tempIconDestinationURL error:NULL];
|
||||
}
|
||||
}
|
||||
|
||||
Boolean submittedJob = false;
|
||||
if (!canceledAuthorization && !failedToUseSystemDomain && auth != NULL) {
|
||||
CFStringRef domain = (systemDomain ? kSMDomainSystemLaunchd : kSMDomainUserLaunchd);
|
||||
NSString *label = [NSString stringWithFormat:@"%@-sparkle-updater", hostBundleIdentifier];
|
||||
|
||||
// Try to remove the job from launchd if it is already running
|
||||
// We could invoke SMJobCopyDictionary() first to see if the job exists, but I'd rather avoid
|
||||
// using it because the headers indicate it may be removed one day without any replacement
|
||||
CFErrorRef removeError = NULL;
|
||||
if (!SMJobRemove(domain, (__bridge CFStringRef)(label), auth, true, &removeError)) {
|
||||
if (removeError != NULL) {
|
||||
// It's normal for a job to not be found, so this is not an interesting error
|
||||
if (CFErrorGetCode(removeError) != kSMErrorJobNotFound) {
|
||||
SULog(@"Remove job error: %@", removeError);
|
||||
}
|
||||
CFRelease(removeError);
|
||||
}
|
||||
}
|
||||
|
||||
NSDictionary *jobDictionary = @{@"Label" : label, @"ProgramArguments" : arguments, @"EnableTransactions" : @NO, @"KeepAlive" : @{@"SuccessfulExit" : @NO}, @"RunAtLoad" : @NO, @"NICE" : @0, @"LaunchOnlyOnce": @YES, @"MachServices" : @{SUInstallerServiceNameForBundleIdentifier(hostBundleIdentifier) : @YES, SUProgressAgentServiceNameForBundleIdentifier(hostBundleIdentifier) : @YES}};
|
||||
|
||||
CFErrorRef submitError = NULL;
|
||||
submittedJob = SMJobSubmit(domain, (__bridge CFDictionaryRef)(jobDictionary), auth, &submitError);
|
||||
if (!submittedJob) {
|
||||
if (submitError != NULL) {
|
||||
SULog(@"Submit error: %@", submitError);
|
||||
CFRelease(submitError);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (auth != NULL) {
|
||||
AuthorizationFree(auth, kAuthorizationFlagDefaults);
|
||||
}
|
||||
|
||||
SUAuthorizationReply reply;
|
||||
if (submittedJob == true) {
|
||||
reply = SUAuthorizationReplySuccess;
|
||||
} else if (canceledAuthorization) {
|
||||
reply = SUAuthorizationReplyCanceled;
|
||||
} else {
|
||||
reply = SUAuthorizationReplyFailure;
|
||||
}
|
||||
return reply;
|
||||
}
|
||||
|
||||
- (void)launchInstallerAtPath:(NSString *)installerPath progressToolPath:(NSString *)progressToolPath withHostBundlePath:(NSString *)hostBundlePath authorizationPrompt:(NSString *)authorizationPrompt installationType:(NSString *)installationType allowingInteraction:(BOOL)allowingInteraction completion:(void (^)(SUAuthorizationReply))completionHandler
|
||||
{
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
SUFileManager *fileManager = [SUFileManager defaultManager];
|
||||
NSBundle *hostBundle = [NSBundle bundleWithPath:hostBundlePath];
|
||||
|
||||
NSURL *installerURL = [NSURL fileURLWithPath:installerPath];
|
||||
BOOL preflighted = NO;
|
||||
BOOL needsSystemAuthorization = SUNeedsSystemAuthorizationAccess(hostBundlePath, installationType, &preflighted);
|
||||
|
||||
NSError *quarantineError = nil;
|
||||
if (![fileManager releaseItemFromQuarantineAtRootURL:installerURL error:&quarantineError]) {
|
||||
// This may or may not be a fatal error depending on if the process is sandboxed or not
|
||||
SULog(@"Failed to release quarantine on installer at %@ with error %@", installerPath, quarantineError);
|
||||
}
|
||||
|
||||
NSString *executablePath = [[[installerPath stringByAppendingPathComponent:@"Contents"] stringByAppendingPathComponent:@"MacOS"] stringByAppendingPathComponent:@SPARKLE_RELAUNCH_TOOL_NAME];
|
||||
|
||||
NSError *ownershipError = nil;
|
||||
if (![fileManager changeOwnerAndGroupOfItemAtRootURL:[NSURL fileURLWithPath:executablePath] toMatchURL:installerURL error:&ownershipError]) {
|
||||
// This may or may not be a fatal error
|
||||
SULog(@"Failed to change ownership on installer executable at %@ with error %@", executablePath, ownershipError);
|
||||
}
|
||||
|
||||
NSArray *arguments = @[executablePath, hostBundleIdentifier, @(allowingInteraction).stringValue];
|
||||
|
||||
// If the updater is running as the logged in user, we submit a job under the user domain
|
||||
// However if the updater is running as root (which is experimental), we submit the job under the system domain
|
||||
// We don't yet handle the updater running as the logged in user, and submitting a job under the system domain, which
|
||||
// would remove the need for using AuthorizationExecuteWithPrivileges() in the installer. That would require knowing before hand
|
||||
// if we will need to request authorization privileges, and that would prevent this code from being invoked silently/automatically.
|
||||
// Additionally, we would want to remove AppKit references in the installer
|
||||
BOOL grantsSystemPrivilege = NO;
|
||||
AuthorizationRef auth = SUCreateAuthorization(&grantsSystemPrivilege);
|
||||
Boolean submittedJob = false;
|
||||
if (auth != NULL) {
|
||||
CFStringRef domain = (grantsSystemPrivilege ? kSMDomainSystemLaunchd : kSMDomainUserLaunchd);
|
||||
NSString *label = [NSString stringWithFormat:@"%@-sparkle-updater", hostBundleIdentifier];
|
||||
// if we need to use the system domain and we aren't already root and we aren't allowed interaction, then try sometime later when interaction is allowed
|
||||
if (needsSystemAuthorization && !preflighted && !allowingInteraction) {
|
||||
completionHandler(SUAuthorizationReplyAuthorizeLater);
|
||||
} else {
|
||||
SUAuthorizationReply installerReply = [self submitInstallerAtPath:installerPath withHostBundle:hostBundle authorizationPrompt:authorizationPrompt allowingInteraction:allowingInteraction inSystemDomain:needsSystemAuthorization];
|
||||
|
||||
// Try to remove the job from launchd if it is already running
|
||||
// We could invoke SMJobCopyDictionary() first to see if the job exists, but I'd rather avoid
|
||||
// using it because the headers indicate it may be removed one day without any replacement
|
||||
CFErrorRef removeError = NULL;
|
||||
if (!SMJobRemove(domain, (__bridge CFStringRef)(label), auth, true, &removeError)) {
|
||||
if (removeError != NULL) {
|
||||
// It's normal for a job to not be found, so this is not an interesting error
|
||||
if (CFErrorGetCode(removeError) != kSMErrorJobNotFound) {
|
||||
SULog(@"Remove error: %@", removeError);
|
||||
}
|
||||
CFRelease(removeError);
|
||||
if (installerReply == SUAuthorizationReplyFailure) {
|
||||
SULog(@"Failed to submit installer job");
|
||||
}
|
||||
|
||||
BOOL submittedProgressTool = NO;
|
||||
if (installerReply == SUAuthorizationReplySuccess) {
|
||||
submittedProgressTool = [self submitProgressToolAtPath:progressToolPath withHostBundle:hostBundle inSystemDomainForInstaller:needsSystemAuthorization];
|
||||
|
||||
if (!submittedProgressTool) {
|
||||
SULog(@"Failed to submit progress tool job");
|
||||
}
|
||||
}
|
||||
|
||||
NSDictionary *jobDictionary = @{@"Label" : label, @"ProgramArguments" : arguments, @"EnableTransactions" : @NO, @"KeepAlive" : @{@"SuccessfulExit" : @NO}, @"RunAtLoad" : @NO, @"NICE" : @0, @"LaunchOnlyOnce": @YES, @"MachServices" : @{SUInstallerServiceNameForBundleIdentifier(hostBundleIdentifier) : @YES, SUStatusInfoServiceNameForBundleIdentifier(hostBundleIdentifier) : @YES}};
|
||||
|
||||
CFErrorRef submitError = NULL;
|
||||
submittedJob = SMJobSubmit(domain, (__bridge CFDictionaryRef)(jobDictionary), auth, &submitError);
|
||||
if (!submittedJob) {
|
||||
if (submitError != NULL) {
|
||||
SULog(@"Submit error: %@", submitError);
|
||||
CFRelease(submitError);
|
||||
}
|
||||
if (installerReply == SUAuthorizationReplyCanceled) {
|
||||
completionHandler(installerReply);
|
||||
} else {
|
||||
completionHandler(submittedProgressTool ? SUAuthorizationReplySuccess : SUAuthorizationReplyFailure);
|
||||
}
|
||||
|
||||
AuthorizationFree(auth, kAuthorizationFlagDefaults);
|
||||
}
|
||||
|
||||
completionHandler(submittedJob == true);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -7,9 +7,10 @@
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "SUAuthorizationReply.h"
|
||||
|
||||
@protocol SUInstallerLauncherProtocol
|
||||
|
||||
- (void)launchInstallerAtPath:(NSString *)installerPath withHostBundleIdentifier:(NSString *)hostBundleIdentifier allowingInteraction:(BOOL)allowingInteraction completion:(void (^)(BOOL success))completionHandler;
|
||||
- (void)launchInstallerAtPath:(NSString *)installerPath progressToolPath:(NSString *)progressToolPath withHostBundlePath:(NSString *)hostBundlePath authorizationPrompt:(NSString *)authorizationPrompt installationType:(NSString *)installationType allowingInteraction:(BOOL)allowingInteraction completion:(void (^)(SUAuthorizationReply))completionHandler;
|
||||
|
||||
@end
|
||||
@@ -28,8 +28,7 @@
|
||||
|
||||
- (void)setServiceName:(NSString *)serviceName
|
||||
{
|
||||
NSXPCConnectionOptions options = SUGrantsSystemAuthorizationAccess() ? NSXPCConnectionPrivileged : 0;
|
||||
NSXPCConnection *connection = [[NSXPCConnection alloc] initWithMachServiceName:serviceName options:options];
|
||||
NSXPCConnection *connection = [[NSXPCConnection alloc] initWithMachServiceName:serviceName options:(NSXPCConnectionOptions)0];
|
||||
|
||||
connection.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUStatusInfoProtocol)];
|
||||
|
||||
@@ -37,7 +36,7 @@
|
||||
|
||||
__weak SUInstallerStatus *weakSelf = self;
|
||||
self.connection.interruptionHandler = ^{
|
||||
[weakSelf invalidate];
|
||||
[weakSelf.connection invalidate];
|
||||
};
|
||||
|
||||
self.connection.invalidationHandler = ^{
|
||||
|
||||
@@ -14,8 +14,10 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
// The protocol that this service will vend as its API. This header file will also need to be visible to the process hosting the service.
|
||||
@protocol SUInstallerStatusProtocol <SUStatusInfoProtocol>
|
||||
|
||||
// Include SUStatusInfoProtocol protocol methods because XPC on 10.8 won't know about them
|
||||
// Even though this is declared in SUStatusInfoProtocol, we should declare it here because macOS 10.8 doesn't traverse adopted protocols
|
||||
- (void)probeStatusInfoWithReply:(void (^)(NSData * _Nullable installationInfoData))reply;
|
||||
|
||||
// Even though this is declared in SUStatusInfoProtocol, we should declare it here because macOS 10.8 doesn't traverse adopted protocols
|
||||
- (void)probeStatusConnectivityWithReply:(void (^)(void))reply;
|
||||
|
||||
- (void)setInvalidationHandler:(void (^)(void))invalidationHandler;
|
||||
|
||||
+357
-549
File diff suppressed because it is too large.
Load diff
-32
@@ -1,32 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleDevelopmentRegion</key>
|
||||
<string>English</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>${EXECUTABLE_NAME}</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>APPL</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>${CURRENT_PROJECT_VERSION}</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>${CURRENT_PROJECT_VERSION}</string>
|
||||
<key>LSBackgroundOnly</key>
|
||||
<string>1</string>
|
||||
<key>LSMinimumSystemVersion</key>
|
||||
<string>${MACOSX_DEPLOYMENT_TARGET}</string>
|
||||
<key>LSUIElement</key>
|
||||
<string>1</string>
|
||||
<key>NSMainNibFile</key>
|
||||
<string>MainMenu</string>
|
||||
<key>NSPrincipalClass</key>
|
||||
<string>NSApplication</string>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -26,5 +26,9 @@
|
||||
<string>$(MACOSX_DEPLOYMENT_TARGET)</string>
|
||||
<key>NSPrincipalClass</key>
|
||||
<string>NSApplication</string>
|
||||
<key>LSBackgroundOnly</key>
|
||||
<string>1</string>
|
||||
<key>LSUIElement</key>
|
||||
<string>1</string>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -10,14 +10,16 @@
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@protocol InstallerProgressAppControllerDelegate;
|
||||
@protocol InstallerProgressDelegate;
|
||||
|
||||
@interface InstallerProgressAppController : NSObject <NSApplicationDelegate>
|
||||
|
||||
- (instancetype)initWithApplication:(NSApplication *)application arguments:(NSArray<NSString *> *)arguments delegate:(id<InstallerProgressAppControllerDelegate>)delegate;
|
||||
- (instancetype)initWithApplication:(NSApplication *)application arguments:(NSArray<NSString *> *)arguments delegate:(id<InstallerProgressDelegate>)delegate;
|
||||
|
||||
- (void)run;
|
||||
|
||||
- (void)cleanupAndExitWithStatus:(int)status __attribute__((noreturn));
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
+163
-32
@@ -7,11 +7,14 @@
|
||||
//
|
||||
|
||||
#import "InstallerProgressAppController.h"
|
||||
#import "InstallerProgressAppControllerDelegate.h"
|
||||
#import "SUInstallerStatus.h"
|
||||
#import "InstallerProgressDelegate.h"
|
||||
#import "SUMessageTypes.h"
|
||||
#import "SULog.h"
|
||||
#import "SUApplicationInfo.h"
|
||||
#import "SUInstallerAgentProtocol.h"
|
||||
#import "SUInstallerAgentInitiationProtocol.h"
|
||||
#import "StatusInfo.h"
|
||||
#import <ServiceManagement/ServiceManagement.h>
|
||||
|
||||
/*!
|
||||
* Terminate the application after a delay from launching the new update to avoid OS activation issues
|
||||
@@ -20,59 +23,92 @@
|
||||
*/
|
||||
static const NSTimeInterval SUTerminationTimeDelay = 0.3;
|
||||
|
||||
@interface InstallerProgressAppController () <NSApplicationDelegate>
|
||||
@interface InstallerProgressAppController () <NSApplicationDelegate, SUInstallerAgentProtocol>
|
||||
|
||||
@property (nonatomic, readonly) NSApplication *application;
|
||||
@property (nonatomic, readonly) NSBundle *bundle;
|
||||
@property (nonatomic, readonly, weak) id<InstallerProgressAppControllerDelegate> delegate;
|
||||
@property (nonatomic, readonly) id<SUInstallerStatusProtocol> statusInfo;
|
||||
@property (nonatomic, weak) id<InstallerProgressDelegate> delegate;
|
||||
@property (nonatomic, readonly) NSXPCConnection *connection;
|
||||
@property (nonatomic) BOOL connected;
|
||||
@property (nonatomic) BOOL repliedToRegistration;
|
||||
@property (nonatomic, readonly) NSBundle *hostBundle;
|
||||
@property (nonatomic) StatusInfo *statusInfo;
|
||||
@property (nonatomic) BOOL submittedLauncherJob;
|
||||
|
||||
@end
|
||||
|
||||
#define CONNECTION_ACKNOWLEDGEMENT_TIMEOUT 7ull
|
||||
|
||||
@implementation InstallerProgressAppController
|
||||
|
||||
@synthesize application = _application;
|
||||
@synthesize bundle = _bundle;
|
||||
@synthesize delegate = _delegate;
|
||||
@synthesize connection = _connection;
|
||||
@synthesize connected = _connected;
|
||||
@synthesize repliedToRegistration = _repliedToRegistration;
|
||||
@synthesize hostBundle = _hostBundle;
|
||||
@synthesize statusInfo = _statusInfo;
|
||||
@synthesize submittedLauncherJob = _submittedLauncherJob;
|
||||
|
||||
- (instancetype)initWithApplication:(NSApplication *)application arguments:(NSArray<NSString *> *)arguments delegate:(id<InstallerProgressAppControllerDelegate>)delegate
|
||||
- (instancetype)initWithApplication:(NSApplication *)application arguments:(NSArray<NSString *> *)arguments delegate:(id<InstallerProgressDelegate>)delegate
|
||||
{
|
||||
self = [super init];
|
||||
if (self != nil) {
|
||||
if (arguments.count != 2) {
|
||||
exit(EXIT_FAILURE);
|
||||
if (arguments.count != 3) {
|
||||
SULog(@"Error: Invalid number of arguments supplied: %@", arguments);
|
||||
[self cleanupAndExitWithStatus:EXIT_FAILURE];
|
||||
}
|
||||
|
||||
NSString *hostBundlePath = arguments[1];
|
||||
NSBundle *bundle = [NSBundle bundleWithPath:hostBundlePath];
|
||||
if (bundle == nil) {
|
||||
SULog(@"Error: bundle at %@ is nil", hostBundlePath);
|
||||
exit(EXIT_FAILURE);
|
||||
if (hostBundlePath.length == 0) {
|
||||
SULog(@"Error: Host bundle path length is 0");
|
||||
[self cleanupAndExitWithStatus:EXIT_FAILURE];
|
||||
}
|
||||
|
||||
NSString *bundleIdentifier = bundle.bundleIdentifier;
|
||||
if (bundleIdentifier == nil) {
|
||||
SULog(@"Error: Bundle Identifier for target is nil");
|
||||
exit(EXIT_FAILURE);
|
||||
_hostBundle = [NSBundle bundleWithPath:hostBundlePath];
|
||||
if (_hostBundle == nil) {
|
||||
SULog(@"Error: Host bundle for target is nil");
|
||||
[self cleanupAndExitWithStatus:EXIT_FAILURE];
|
||||
}
|
||||
|
||||
application.applicationIconImage = [SUApplicationInfo bestIconForBundle:bundle];
|
||||
|
||||
NSString *hostBundleIdentifier = _hostBundle.bundleIdentifier;
|
||||
if (hostBundleIdentifier == nil) {
|
||||
SULog(@"Error: Host bundle identifier for target is nil");
|
||||
[self cleanupAndExitWithStatus:EXIT_FAILURE];
|
||||
}
|
||||
|
||||
BOOL systemDomain = arguments[2].boolValue;
|
||||
NSXPCConnectionOptions connectionOptions = systemDomain ? NSXPCConnectionPrivileged : 0;
|
||||
_connection = [[NSXPCConnection alloc] initWithMachServiceName:SUProgressAgentServiceNameForBundleIdentifier(hostBundleIdentifier) options:connectionOptions];
|
||||
|
||||
_statusInfo = [[StatusInfo alloc] initWithHostBundleIdentifier:hostBundleIdentifier];
|
||||
|
||||
application.delegate = self;
|
||||
|
||||
_application = application;
|
||||
_delegate = delegate;
|
||||
_bundle = bundle;
|
||||
_statusInfo = [[SUInstallerStatus alloc] init];
|
||||
|
||||
[_statusInfo setInvalidationHandler:^{
|
||||
_connection.exportedInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUInstallerAgentProtocol)];
|
||||
_connection.exportedObject = self;
|
||||
|
||||
_connection.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUInstallerAgentInitiationProtocol)];
|
||||
|
||||
__weak InstallerProgressAppController *weakSelf = self;
|
||||
_connection.interruptionHandler = ^{
|
||||
[weakSelf.connection invalidate];
|
||||
};
|
||||
|
||||
_connection.invalidationHandler = ^{
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[application terminate:nil];
|
||||
InstallerProgressAppController *strongSelf = weakSelf;
|
||||
if (strongSelf != nil) {
|
||||
int exitStatus = (strongSelf.repliedToRegistration ? EXIT_SUCCESS : EXIT_FAILURE);
|
||||
if (!strongSelf.repliedToRegistration) {
|
||||
SULog(@"Error: Agent Invalidating without having the chance to reply to installer");
|
||||
}
|
||||
[strongSelf cleanupAndExitWithStatus:exitStatus];
|
||||
}
|
||||
});
|
||||
}];
|
||||
|
||||
[_statusInfo setServiceName:SUStatusInfoServiceNameForBundleIdentifier(bundleIdentifier)];
|
||||
};
|
||||
}
|
||||
return self;
|
||||
}
|
||||
@@ -82,16 +118,108 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.3;
|
||||
[self.application run];
|
||||
}
|
||||
|
||||
- (void)applicationDidFinishLaunching:(NSNotification *)__unused notification
|
||||
- (void)startConnection
|
||||
{
|
||||
[self.statusInfo probeStatusConnectivityWithReply:^{
|
||||
[self.statusInfo startListener];
|
||||
|
||||
[self.connection resume];
|
||||
[self.connection.remoteObjectProxy connectionDidInitiateWithReply:^{
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[self.delegate applicationDidFinishLaunchingWithTargetBundle:self.bundle];
|
||||
self.connected = YES;
|
||||
});
|
||||
}];
|
||||
|
||||
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(CONNECTION_ACKNOWLEDGEMENT_TIMEOUT * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
|
||||
if (!self.connected) {
|
||||
SULog(@"Timeout error: failed to receive acknowledgement from installer");
|
||||
[self cleanupAndExitWithStatus:EXIT_FAILURE];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Close status window immediately, but delay termination for a little bit to better increase the chance
|
||||
- (void)applicationDidFinishLaunching:(NSNotification *)__unused notification
|
||||
{
|
||||
[self startConnection];
|
||||
}
|
||||
|
||||
- (void)cleanupAndExitWithStatus:(int)status __attribute__((noreturn))
|
||||
{
|
||||
[self.statusInfo invalidate];
|
||||
[self.connection invalidate];
|
||||
|
||||
exit(status);
|
||||
}
|
||||
|
||||
- (void)registerRelaunchBundlePath:(NSString *)relaunchBundlePath reply:(void (^)(NSNumber *))reply
|
||||
{
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
assert(relaunchBundlePath != nil);
|
||||
NSBundle *relaunchBundle = [NSBundle bundleWithPath:relaunchBundlePath];
|
||||
if (relaunchBundle == nil) {
|
||||
[self cleanupAndExitWithStatus:EXIT_FAILURE];
|
||||
}
|
||||
|
||||
NSRunningApplication *runningApplication = [SUApplicationInfo runningApplicationWithBundle:relaunchBundle];
|
||||
NSNumber *processIdentifier = (runningApplication == nil || runningApplication.terminated) ? nil : @(runningApplication.processIdentifier);
|
||||
|
||||
reply(processIdentifier);
|
||||
|
||||
self.repliedToRegistration = YES;
|
||||
});
|
||||
}
|
||||
|
||||
- (void)registerInstallationInfoData:(NSData *)installationInfoData
|
||||
{
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
if (self.statusInfo.installationInfoData == nil) {
|
||||
self.statusInfo.installationInfoData = installationInfoData;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
- (void)relaunchPath:(NSString *)pathToRelaunch
|
||||
{
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
if (![[NSWorkspace sharedWorkspace] openFile:pathToRelaunch]) {
|
||||
SULog(@"Error: Failed to relaunch bundle at %@", pathToRelaunch);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
- (void)showProgress
|
||||
{
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
// Show app icon in the dock
|
||||
ProcessSerialNumber psn = { 0, kCurrentProcess };
|
||||
TransformProcessType(&psn, kProcessTransformToForegroundApplication);
|
||||
|
||||
// Note: the application icon needs to be set after showing the icon in the dock
|
||||
self.application.applicationIconImage = [SUApplicationInfo bestIconForBundle:self.hostBundle];
|
||||
|
||||
// Activate ourselves otherwise we will probably be in the background
|
||||
[self.application activateIgnoringOtherApps:YES];
|
||||
|
||||
[self.delegate installerProgressShouldDisplayWithBundle:self.hostBundle];
|
||||
});
|
||||
}
|
||||
|
||||
- (void)stopProgress
|
||||
{
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[self _stopProgress];
|
||||
});
|
||||
}
|
||||
|
||||
- (void)_stopProgress
|
||||
{
|
||||
[self.statusInfo invalidate];
|
||||
self.statusInfo = nil;
|
||||
|
||||
[self.delegate installerProgressShouldStop];
|
||||
self.delegate = nil;
|
||||
}
|
||||
|
||||
// Dismiss any UI immediately, but delay termination for a little bit to better increase the chance
|
||||
// the updated application when relaunched will be the frontmost application
|
||||
// This is related to macOS activation issues when terminating a frontmost application happens right before
|
||||
// launching another app
|
||||
@@ -99,8 +227,11 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.3;
|
||||
{
|
||||
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(SUTerminationTimeDelay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
|
||||
// Exit right away, don't go through the apple event process again
|
||||
exit(EXIT_SUCCESS);
|
||||
[self cleanupAndExitWithStatus:EXIT_SUCCESS];
|
||||
});
|
||||
|
||||
[self _stopProgress];
|
||||
|
||||
// Reply with a 'cancel' rather than 'later' because 'later' may make the runloop stop completely, not having the dispatch_after above invoked
|
||||
return NSTerminateCancel;
|
||||
}
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
//
|
||||
// InstallerProgressAppControllerDelegate.h
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Mayur Pawashe on 4/10/16.
|
||||
// Copyright © 2016 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@protocol InstallerProgressAppControllerDelegate <NSObject>
|
||||
|
||||
- (void)applicationDidFinishLaunchingWithTargetBundle:(NSBundle *)bundle;
|
||||
- (void)applicationWillTerminateAfterDelay;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@@ -0,0 +1,20 @@
|
||||
//
|
||||
// InstallerProgressDelegate.h
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Mayur Pawashe on 4/10/16.
|
||||
// Copyright © 2016 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@protocol InstallerProgressDelegate <NSObject>
|
||||
|
||||
- (void)installerProgressShouldDisplayWithBundle:(NSBundle *)bundle;
|
||||
- (void)installerProgressShouldStop;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@@ -0,0 +1,15 @@
|
||||
//
|
||||
// SUInstallerAgentInitiationProtocol.h
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Mayur Pawashe on 7/17/16.
|
||||
// Copyright © 2016 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
@protocol SUInstallerAgentInitiationProtocol
|
||||
|
||||
- (void)connectionDidInitiateWithReply:(void (^)(void))acknowledgement;
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,27 @@
|
||||
//
|
||||
// SUInstallerAgentProtocol.h
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Mayur Pawashe on 7/17/16.
|
||||
// Copyright © 2016 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@protocol SUInstallerAgentProtocol
|
||||
|
||||
- (void)registerRelaunchBundlePath:(NSString *)relaunchBundlePath reply:(void (^)(NSNumber * _Nullable processIdentifier))reply;
|
||||
|
||||
- (void)registerInstallationInfoData:(NSData *)installationInfoData;
|
||||
|
||||
- (void)showProgress;
|
||||
|
||||
- (void)stopProgress;
|
||||
|
||||
- (void)relaunchPath:(NSString *)pathToRelaunch;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
+2
-2
@@ -7,11 +7,11 @@
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "InstallerProgressAppControllerDelegate.h"
|
||||
#import "InstallerProgressDelegate.h"
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@interface ShowInstallerProgress : NSObject <InstallerProgressAppControllerDelegate>
|
||||
@interface ShowInstallerProgress : NSObject <InstallerProgressDelegate>
|
||||
|
||||
@end
|
||||
|
||||
|
||||
+2
-2
@@ -22,7 +22,7 @@
|
||||
|
||||
@synthesize statusController = _statusController;
|
||||
|
||||
- (void)applicationDidFinishLaunchingWithTargetBundle:(NSBundle *)bundle
|
||||
- (void)installerProgressShouldDisplayWithBundle:(NSBundle *)bundle
|
||||
{
|
||||
SUHost *host = [[SUHost alloc] initWithBundle:bundle];
|
||||
self.statusController = [[SUStatusController alloc] initWithHost:host];
|
||||
@@ -32,7 +32,7 @@
|
||||
[self.statusController showWindow:self];
|
||||
}
|
||||
|
||||
- (void)applicationWillTerminateAfterDelay
|
||||
- (void)installerProgressShouldStop
|
||||
{
|
||||
[self.statusController close];
|
||||
self.statusController = nil;
|
||||
|
||||
Vendored
+10
-1
@@ -14,7 +14,7 @@ int main(int __unused argc, const char __unused *argv[])
|
||||
{
|
||||
@autoreleasepool
|
||||
{
|
||||
ShowInstallerProgress *showInstallerProgress = [[ShowInstallerProgress alloc] init];
|
||||
id<InstallerProgressDelegate> showInstallerProgress = [[ShowInstallerProgress alloc] init];
|
||||
|
||||
InstallerProgressAppController *appController =
|
||||
[[InstallerProgressAppController alloc]
|
||||
@@ -22,6 +22,15 @@ int main(int __unused argc, const char __unused *argv[])
|
||||
arguments:[[NSProcessInfo processInfo] arguments]
|
||||
delegate:showInstallerProgress];
|
||||
|
||||
// Ignore SIGTERM because we are going to catch it ourselves
|
||||
signal(SIGTERM, SIG_IGN);
|
||||
|
||||
dispatch_source_t sigtermSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, SIGTERM, 0, dispatch_get_main_queue());
|
||||
dispatch_source_set_event_handler(sigtermSource, ^{
|
||||
[appController cleanupAndExitWithStatus:SIGTERM];
|
||||
});
|
||||
dispatch_resume(sigtermSource);
|
||||
|
||||
[appController run];
|
||||
}
|
||||
|
||||
|
||||
Vendored
+1
@@ -30,6 +30,7 @@ SU_EXPORT @interface SUAppcastItem : NSObject<NSSecureCoding>
|
||||
@property (copy, readonly) NSString *displayVersionString;
|
||||
@property (copy, readonly) NSDictionary *deltaUpdates;
|
||||
@property (strong, readonly) NSURL *infoURL;
|
||||
@property (nonatomic, copy, readonly) NSString *installationType;
|
||||
|
||||
// Initializes with data from a dictionary provided by the RSS class.
|
||||
- (instancetype)initWithDictionary:(NSDictionary *)dict;
|
||||
|
||||
Vendored
+24
@@ -10,6 +10,7 @@
|
||||
#import "SUVersionComparisonProtocol.h"
|
||||
#import "SULog.h"
|
||||
#import "SUConstants.h"
|
||||
#import "SUInstallationType.h"
|
||||
|
||||
#ifdef _APPKITDEFINES_H
|
||||
#error This is a "core" class and should NOT import AppKit
|
||||
@@ -28,6 +29,7 @@ static NSString *SUAppcastItemReleaseNotesURLKey = @"releaseNotesURL";
|
||||
static NSString *SUAppcastItemTitleKey = @"title";
|
||||
static NSString *SUAppcastItemVersionStringKey = @"versionString";
|
||||
static NSString *SUAppcastItemPropertiesKey = @"propertiesDictionary";
|
||||
static NSString *SUAppcastItemInstallationTypeKey = @"SUAppcastItemInstallationType";
|
||||
|
||||
@implementation SUAppcastItem
|
||||
|
||||
@@ -45,6 +47,7 @@ static NSString *SUAppcastItemPropertiesKey = @"propertiesDictionary";
|
||||
@synthesize title = _title;
|
||||
@synthesize versionString = _versionString;
|
||||
@synthesize propertiesDictionary = _propertiesDictionary;
|
||||
@synthesize installationType = _installationType;
|
||||
|
||||
+ (BOOL)supportsSecureCoding
|
||||
{
|
||||
@@ -67,6 +70,11 @@ static NSString *SUAppcastItemPropertiesKey = @"propertiesDictionary";
|
||||
return nil;
|
||||
}
|
||||
|
||||
_installationType = [decoder decodeObjectOfClass:[NSString class] forKey:SUAppcastItemInstallationTypeKey];
|
||||
if (!SUValidInstallationType(_installationType)) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
_itemDescription = [[decoder decodeObjectOfClass:[NSString class] forKey:SUAppcastItemDescriptionKey] copy];
|
||||
_maximumSystemVersion = [[decoder decodeObjectOfClass:[NSString class] forKey:SUAppcastItemMaximumSystemVersionKey] copy];
|
||||
_minimumSystemVersion = [[decoder decodeObjectOfClass:[NSString class] forKey:SUAppcastItemMinimumSystemVersionKey] copy];
|
||||
@@ -130,6 +138,10 @@ static NSString *SUAppcastItemPropertiesKey = @"propertiesDictionary";
|
||||
if (self.propertiesDictionary != nil) {
|
||||
[encoder encodeObject:self.propertiesDictionary forKey:SUAppcastItemPropertiesKey];
|
||||
}
|
||||
|
||||
if (self.installationType != nil) {
|
||||
[encoder encodeObject:self.installationType forKey:SUAppcastItemInstallationTypeKey];
|
||||
}
|
||||
}
|
||||
|
||||
- (BOOL)isDeltaUpdate
|
||||
@@ -263,6 +275,18 @@ static NSString *SUAppcastItemPropertiesKey = @"propertiesDictionary";
|
||||
} else {
|
||||
_displayVersionString = [_versionString copy];
|
||||
}
|
||||
|
||||
_installationType = [enclosure objectForKey:SUAppcastAttributeInstallationType];
|
||||
if (_installationType == nil) {
|
||||
_installationType = SUInstallationTypeDefault;
|
||||
} else if (!SUValidInstallationType(_installationType)) {
|
||||
if (error != NULL) {
|
||||
*error = [NSString stringWithFormat:@"Feed item's enclosure lacks valid %@ (found %@)", SUAppcastAttributeInstallationType, _installationType];
|
||||
}
|
||||
return nil;
|
||||
} else if ([_installationType isEqualToString:SUInstallationTypePackage]) {
|
||||
SULog(@"warning: '%@' for %@ is deprecated. Use '%@' instead.", SUInstallationTypePackage, SUAppcastAttributeInstallationType, SUInstallationTypeGuidedPackage);
|
||||
}
|
||||
|
||||
// Find the appropriate release notes URL.
|
||||
NSString *releaseNotesString = [dict objectForKey:SUAppcastElementReleaseNotesLink];
|
||||
|
||||
Vendored
+4
-11
@@ -7,6 +7,7 @@
|
||||
//
|
||||
|
||||
#import "SUApplicationInfo.h"
|
||||
#import "SUBundleIcon.h"
|
||||
|
||||
@implementation SUApplicationInfo
|
||||
|
||||
@@ -17,17 +18,9 @@
|
||||
|
||||
+ (NSImage *)bestIconForBundle:(NSBundle *)bundle
|
||||
{
|
||||
// Cache the application icon.
|
||||
NSString *iconPath = [bundle pathForResource:[bundle objectForInfoDictionaryKey:@"CFBundleIconFile"] ofType:@"icns"];
|
||||
// According to the macOS docs, "CFBundleIconFile - This key identifies the file containing
|
||||
// the icon for the bundle. The filename you specify does not need to include the .icns
|
||||
// extension, although it may."
|
||||
//
|
||||
// However, if it *does* include the '.icns' the above method fails (tested on macOS 10.3.9) so we'll also try:
|
||||
if (!iconPath) {
|
||||
iconPath = [bundle pathForResource:[bundle objectForInfoDictionaryKey:@"CFBundleIconFile"] ofType:nil];
|
||||
}
|
||||
NSImage *icon = [[NSImage alloc] initWithContentsOfFile:iconPath];
|
||||
NSURL *iconURL = [SUBundleIcon iconURLForBundle:bundle];
|
||||
|
||||
NSImage *icon = (iconURL == nil) ? nil : [[NSImage alloc] initWithContentsOfURL:iconURL];
|
||||
// Use a default icon if none is defined.
|
||||
if (!icon) {
|
||||
// this asumption may not be correct (eg. even though we're not the main bundle, it could be still be a regular app)
|
||||
|
||||
Vendored
-43
@@ -1,43 +0,0 @@
|
||||
//
|
||||
// SUAuthorizationEnvironment.h
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Mayur Pawashe on 5/27/16.
|
||||
// Copyright © 2016 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <Security/Security.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
/**
|
||||
* A class used for specifying an environment for an authorization request.
|
||||
* This includes a prompt message and an icon image that may show up on an authorization dialog
|
||||
*/
|
||||
@interface SUAuthorizationEnvironment : NSObject
|
||||
|
||||
/**
|
||||
* Creates an authorization environment
|
||||
*
|
||||
* @param prompt A message that will show up in the authorization prompt dialog. The system may append a message
|
||||
* to this prompt. i.e, something like "Enter your password to allow changes." Supply empty string if the prompt is not important.
|
||||
*
|
||||
* @param iconPath A path to a icon on disk that will be used as the icon that shows up in the authorization dialog.
|
||||
* This should be a PNG image that is 32x32 in dimension. It should also be a path that is readable from anybody,
|
||||
* likely in a temporary directory.
|
||||
*
|
||||
* @return A new authorization environment instance
|
||||
*/
|
||||
- (instancetype)initWithPrompt:(NSString *)prompt iconPath:(NSString *)iconPath;
|
||||
|
||||
/**
|
||||
* Retrieve the authorization environment struct that can be used for the Authorization Service APIs
|
||||
*
|
||||
* @return A authorization environment reference. Because this returns an internal pointer, this may only be valid as long as this object instance is alive.
|
||||
*/
|
||||
@property (nonatomic, readonly) AuthorizationEnvironment *environment NS_RETURNS_INNER_POINTER;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
Vendored
-48
@@ -1,48 +0,0 @@
|
||||
//
|
||||
// SUAuthorizationEnvironment.m
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Mayur Pawashe on 5/27/16.
|
||||
// Copyright © 2016 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#import "SUAuthorizationEnvironment.h"
|
||||
|
||||
@implementation SUAuthorizationEnvironment
|
||||
{
|
||||
// Declare data here so we won't have to do more dynamic allocations
|
||||
char _prompt[1024];
|
||||
char _iconPath[PATH_MAX];
|
||||
AuthorizationItem _environmentItems[2];
|
||||
AuthorizationEnvironment _environment;
|
||||
}
|
||||
|
||||
- (instancetype)initWithPrompt:(NSString *)prompt iconPath:(NSString *)iconPath
|
||||
{
|
||||
self = [super init];
|
||||
if (self != nil) {
|
||||
if (![prompt getFileSystemRepresentation:_prompt maxLength:sizeof(_prompt)]) {
|
||||
bzero(_prompt, sizeof(_prompt));
|
||||
}
|
||||
|
||||
if (![iconPath getFileSystemRepresentation:_iconPath maxLength:sizeof(_iconPath)]) {
|
||||
bzero(_iconPath, sizeof(_iconPath));
|
||||
}
|
||||
|
||||
_environmentItems[0] = (AuthorizationItem){.name = kAuthorizationEnvironmentPrompt, .valueLength = strlen(_prompt), .value = _prompt, .flags = 0};
|
||||
_environmentItems[1] = (AuthorizationItem){.name = kAuthorizationEnvironmentIcon, .valueLength = strlen(_iconPath), .value = _iconPath, .flags = 0};
|
||||
|
||||
_environment = (AuthorizationEnvironment){.count = sizeof(_environmentItems) / sizeof(*_environmentItems), .items = _environmentItems};
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (AuthorizationEnvironment *)environment NS_RETURNS_INNER_POINTER
|
||||
{
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wdirect-ivar-access"
|
||||
return &_environment;
|
||||
#pragma clang diagnostic pop
|
||||
}
|
||||
|
||||
@end
|
||||
Vendored
+13
-9
@@ -13,6 +13,7 @@
|
||||
#import "SUCoreBasedUpdateDriver.h"
|
||||
#import "SULog.h"
|
||||
#import "SUAppcastItem.h"
|
||||
#import "SUErrors.h"
|
||||
|
||||
#ifdef _APPKITDEFINES_H
|
||||
#error This is a "core" class and should NOT import AppKit
|
||||
@@ -49,13 +50,20 @@
|
||||
|
||||
- (void)checkForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary *)httpHeaders completion:(SUUpdateDriverCompletion)completionBlock
|
||||
{
|
||||
[self.coreDriver checkForUpdatesAtAppcastURL:appcastURL withUserAgent:userAgent httpHeaders:httpHeaders includesSkippedUpdates:NO completion:completionBlock];
|
||||
[self.coreDriver checkForUpdatesAtAppcastURL:appcastURL withUserAgent:userAgent httpHeaders:httpHeaders includesSkippedUpdates:NO requiresSilentInstall:YES completion:completionBlock];
|
||||
}
|
||||
|
||||
- (void)resumeUpdateWithCompletion:(SUUpdateDriverCompletion)__unused completionBlock __attribute__((noreturn))
|
||||
- (void)resumeInstallingUpdateWithCompletion:(SUUpdateDriverCompletion)__unused completionBlock __attribute__((noreturn))
|
||||
{
|
||||
// Nothing really to do here.. this shouldn't be called.
|
||||
SULog(@"Error: resumeUpdateWithCompletion: called on SUAutomaticUpdateDriver");
|
||||
SULog(@"Error: resumeInstallingUpdateWithCompletion: called on SUAutomaticUpdateDriver");
|
||||
abort();
|
||||
}
|
||||
|
||||
- (void)resumeDownloadedUpdate:(SUDownloadedUpdate *)__unused downloadedUpdate completion:(SUUpdateDriverCompletion)__unused completionBlock __attribute__((noreturn))
|
||||
{
|
||||
// Nothing really to do here.. this shouldn't be called.
|
||||
SULog(@"Error: resumeDownloadedUpdate:completion: called on SUAutomaticUpdateDriver");
|
||||
abort();
|
||||
}
|
||||
|
||||
@@ -99,11 +107,6 @@
|
||||
}
|
||||
}
|
||||
|
||||
- (BOOL)basicDriverShouldSignalShowingUpdateImmediately
|
||||
{
|
||||
return (!self.willInstallSilently || self.updateItem.isCriticalUpdate);
|
||||
}
|
||||
|
||||
- (void)basicDriverIsRequestingAbortUpdateWithError:(NSError *)error
|
||||
{
|
||||
[self abortUpdateWithError:error];
|
||||
@@ -121,7 +124,8 @@
|
||||
|
||||
- (void)abortUpdateWithError:(NSError *)error
|
||||
{
|
||||
[self.coreDriver abortUpdateWithError:error];
|
||||
BOOL showNextUpdateImmediately = (error == nil || error.code == SUInstallationAuthorizeLaterError) && (!self.willInstallSilently || self.updateItem.isCriticalUpdate);
|
||||
[self.coreDriver abortUpdateAndShowNextUpdateImmediately:showNextUpdateImmediately error:error];
|
||||
}
|
||||
|
||||
@end
|
||||
Vendored
+4
-4
@@ -20,8 +20,6 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
- (void)basicDriverIsRequestingAbortUpdateWithError:(nullable NSError *)error;
|
||||
|
||||
- (BOOL)basicDriverShouldSignalShowingUpdateImmediately;
|
||||
|
||||
@optional
|
||||
|
||||
- (void)basicDriverDidFinishLoadingAppcast;
|
||||
@@ -34,11 +32,13 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
- (void)checkForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary *)httpHeaders includesSkippedUpdates:(BOOL)includesSkippedUpdates completion:(SUUpdateDriverCompletion)completionBlock;
|
||||
|
||||
- (void)resumeUpdateWithCompletion:(SUUpdateDriverCompletion)completionBlock;
|
||||
- (void)resumeInstallingUpdateWithCompletion:(SUUpdateDriverCompletion)completionBlock;
|
||||
|
||||
- (void)resumeDownloadedUpdate:(SUDownloadedUpdate *)downloadedUpdate completion:(SUUpdateDriverCompletion)completionBlock;
|
||||
|
||||
@property (nullable, nonatomic, readonly) SUAppcastItem *nonDeltaUpdateItem;
|
||||
|
||||
- (void)abortUpdateWithError:(nullable NSError *)error;
|
||||
- (void)abortUpdateAndShowNextUpdateImmediately:(BOOL)shouldSignalShowingUpdate downloadedUpdate:(SUDownloadedUpdate * _Nullable)downloadedUpdate error:(nullable NSError *)error;
|
||||
|
||||
@end
|
||||
|
||||
|
||||
Vendored
+65
-40
@@ -16,6 +16,7 @@
|
||||
#import "SUAppcastItem.h"
|
||||
#import "SUProbeInstallStatus.h"
|
||||
#import "SUInstallationInfo.h"
|
||||
#import "SUDownloadedUpdate.h"
|
||||
|
||||
@interface SUBasicUpdateDriver () <SUAppcastDriverDelegate>
|
||||
|
||||
@@ -27,6 +28,8 @@
|
||||
@property (nonatomic, readonly, weak) id updater; // if we didn't have legacy support, I'd remove this..
|
||||
@property (nullable, nonatomic, readonly, weak) id <SUUpdaterDelegate>updaterDelegate;
|
||||
|
||||
@property (nonatomic) BOOL aborted;
|
||||
|
||||
@end
|
||||
|
||||
@implementation SUBasicUpdateDriver
|
||||
@@ -37,6 +40,7 @@
|
||||
@synthesize delegate = _delegate;
|
||||
@synthesize appcastDriver = _appcastDriver;
|
||||
@synthesize completionBlock = _completionBlock;
|
||||
@synthesize aborted = _aborted;
|
||||
|
||||
- (instancetype)initWithHost:(SUHost *)host updater:(id)updater updaterDelegate:(id <SUUpdaterDelegate>)updaterDelegate delegate:(id <SUBasicUpdateDriverDelegate>)delegate
|
||||
{
|
||||
@@ -64,26 +68,37 @@
|
||||
}
|
||||
}
|
||||
|
||||
- (void)resumeUpdateWithCompletion:(SUUpdateDriverCompletion)completionBlock
|
||||
- (void)notifyResumableUpdateItem:(SUAppcastItem *)updateItem
|
||||
{
|
||||
if (updateItem == nil) {
|
||||
[self.delegate basicDriverIsRequestingAbortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUResumeAppcastError userInfo:@{ NSLocalizedDescriptionKey: SULocalizedString(@"Failed to resume installing update.", nil) }]];
|
||||
} else {
|
||||
// Kind of lying, but triggering the notification so drivers can know when to stop showing initial fetching progress
|
||||
[self notifyFinishLoadingAppcast];
|
||||
|
||||
SUAppcastItem *nonNullUpdateItem = updateItem;
|
||||
[self didFindValidUpdateWithAppcastItem:nonNullUpdateItem];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)resumeInstallingUpdateWithCompletion:(SUUpdateDriverCompletion)completionBlock
|
||||
{
|
||||
self.completionBlock = completionBlock;
|
||||
|
||||
[SUProbeInstallStatus probeInstallerUpdateItemForHost:self.host completion:^(SUInstallationInfo * _Nullable installationInfo) {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
SUAppcastItem *updateItem = installationInfo.appcastItem;
|
||||
if (updateItem == nil) {
|
||||
[self.delegate basicDriverIsRequestingAbortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUResumeAppcastError userInfo:@{ NSLocalizedDescriptionKey: SULocalizedString(@"Failed to resume installing update.", nil) }]];
|
||||
} else {
|
||||
// Kind of lying, but triggering the notification so drivers can know when to stop showing initial fetching progress
|
||||
[self notifyFinishLoadingAppcast];
|
||||
|
||||
SUAppcastItem *nonNullUpdateItem = updateItem;
|
||||
[self didFindValidUpdateWithAppcastItem:nonNullUpdateItem];
|
||||
}
|
||||
[self notifyResumableUpdateItem:installationInfo.appcastItem];
|
||||
});
|
||||
}];
|
||||
}
|
||||
|
||||
- (void)resumeDownloadedUpdate:(SUDownloadedUpdate *)downloadedUpdate completion:(SUUpdateDriverCompletion)completionBlock
|
||||
{
|
||||
self.completionBlock = completionBlock;
|
||||
|
||||
[self notifyResumableUpdateItem:downloadedUpdate.updateItem];
|
||||
}
|
||||
|
||||
- (SUAppcastItem *)nonDeltaUpdateItem
|
||||
{
|
||||
return self.appcastDriver.nonDeltaUpdateItem;
|
||||
@@ -91,7 +106,9 @@
|
||||
|
||||
- (void)didFailToFetchAppcastWithError:(NSError *)error
|
||||
{
|
||||
[self.delegate basicDriverIsRequestingAbortUpdateWithError:error];
|
||||
if (!self.aborted) {
|
||||
[self.delegate basicDriverIsRequestingAbortUpdateWithError:error];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)notifyFinishLoadingAppcast
|
||||
@@ -103,48 +120,56 @@
|
||||
|
||||
- (void)didFinishLoadingAppcast:(SUAppcast *)appcast
|
||||
{
|
||||
if ([self.updaterDelegate respondsToSelector:@selector(updater:didFinishLoadingAppcast:)]) {
|
||||
[self.updaterDelegate updater:self.updater didFinishLoadingAppcast:appcast];
|
||||
if (!self.aborted) {
|
||||
if ([self.updaterDelegate respondsToSelector:@selector(updater:didFinishLoadingAppcast:)]) {
|
||||
[self.updaterDelegate updater:self.updater didFinishLoadingAppcast:appcast];
|
||||
}
|
||||
|
||||
[self notifyFinishLoadingAppcast];
|
||||
}
|
||||
|
||||
[self notifyFinishLoadingAppcast];
|
||||
}
|
||||
|
||||
- (void)didFindValidUpdateWithAppcastItem:(SUAppcastItem *)updateItem
|
||||
{
|
||||
[[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterDidFindValidUpdateNotification
|
||||
object:self.updater
|
||||
userInfo:@{ SUUpdaterAppcastItemNotificationKey: updateItem }];
|
||||
|
||||
if ([self.updaterDelegate respondsToSelector:@selector(updater:didFindValidUpdate:)]) {
|
||||
[self.updaterDelegate updater:self.updater didFindValidUpdate:updateItem];
|
||||
if (!self.aborted) {
|
||||
[[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterDidFindValidUpdateNotification
|
||||
object:self.updater
|
||||
userInfo:@{ SUUpdaterAppcastItemNotificationKey: updateItem }];
|
||||
|
||||
if ([self.updaterDelegate respondsToSelector:@selector(updater:didFindValidUpdate:)]) {
|
||||
[self.updaterDelegate updater:self.updater didFindValidUpdate:updateItem];
|
||||
}
|
||||
|
||||
[self.delegate basicDriverDidFindUpdateWithAppcastItem:updateItem];
|
||||
}
|
||||
|
||||
[self.delegate basicDriverDidFindUpdateWithAppcastItem:updateItem];
|
||||
}
|
||||
|
||||
- (void)didNotFindUpdate
|
||||
{
|
||||
if ([self.updaterDelegate respondsToSelector:@selector(updaterDidNotFindUpdate:)]) {
|
||||
[self.updaterDelegate updaterDidNotFindUpdate:self.updater];
|
||||
if (!self.aborted) {
|
||||
if ([self.updaterDelegate respondsToSelector:@selector(updaterDidNotFindUpdate:)]) {
|
||||
[self.updaterDelegate updaterDidNotFindUpdate:self.updater];
|
||||
}
|
||||
[[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterDidNotFindUpdateNotification object:self.updater];
|
||||
|
||||
NSError *notFoundError =
|
||||
[NSError
|
||||
errorWithDomain:SUSparkleErrorDomain
|
||||
code:SUNoUpdateError
|
||||
userInfo:@{
|
||||
NSLocalizedDescriptionKey: [NSString stringWithFormat:SULocalizedString(@"You already have the newest version of %@.", "'Error' message when the user checks for updates but is already current or the feed doesn't contain any updates. (not necessarily shown in UI)"), self.host.name]
|
||||
}
|
||||
];
|
||||
[self.delegate basicDriverIsRequestingAbortUpdateWithError:notFoundError];
|
||||
}
|
||||
[[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterDidNotFindUpdateNotification object:self.updater];
|
||||
|
||||
NSError *notFoundError =
|
||||
[NSError
|
||||
errorWithDomain:SUSparkleErrorDomain
|
||||
code:SUNoUpdateError
|
||||
userInfo:@{
|
||||
NSLocalizedDescriptionKey: [NSString stringWithFormat:SULocalizedString(@"You already have the newest version of %@.", "'Error' message when the user checks for updates but is already current or the feed doesn't contain any updates. (not necessarily shown in UI)"), self.host.name]
|
||||
}
|
||||
];
|
||||
[self.delegate basicDriverIsRequestingAbortUpdateWithError:notFoundError];
|
||||
}
|
||||
|
||||
- (void)abortUpdateWithError:(nullable NSError *)error
|
||||
- (void)abortUpdateAndShowNextUpdateImmediately:(BOOL)shouldShowUpdateImmediately downloadedUpdate:(SUDownloadedUpdate * _Nullable)downloadedUpdate error:(nullable NSError *)error
|
||||
{
|
||||
self.aborted = YES;
|
||||
|
||||
if (error != nil) {
|
||||
if ([error code] != SUNoUpdateError) { // Let's not bother logging this.
|
||||
if (error.code != SUNoUpdateError && error.code != SUInstallationCanceledError && error.code != SUInstallationAuthorizeLaterError) { // Let's not bother logging this.
|
||||
NSError *errorToDisplay = error;
|
||||
int finiteRecursion=5;
|
||||
do {
|
||||
@@ -160,7 +185,7 @@
|
||||
}
|
||||
|
||||
if (self.completionBlock != nil) {
|
||||
self.completionBlock([self.delegate basicDriverShouldSignalShowingUpdateImmediately]);
|
||||
self.completionBlock(shouldShowUpdateImmediately, downloadedUpdate);
|
||||
self.completionBlock = nil;
|
||||
}
|
||||
}
|
||||
|
||||
Vendored
+19
@@ -0,0 +1,19 @@
|
||||
//
|
||||
// SUBundleIcon.h
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Mayur Pawashe on 7/24/16.
|
||||
// Copyright © 2016 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@interface SUBundleIcon : NSObject
|
||||
|
||||
+ (NSURL * _Nullable)iconURLForBundle:(NSBundle *)bundle;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
Vendored
+33
@@ -0,0 +1,33 @@
|
||||
//
|
||||
// SUBundleIcon.m
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Mayur Pawashe on 7/24/16.
|
||||
// Copyright © 2016 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#import "SUBundleIcon.h"
|
||||
|
||||
#ifdef _APPKITDEFINES_H
|
||||
#error This is a "core" class and should NOT import AppKit
|
||||
#endif
|
||||
|
||||
@implementation SUBundleIcon
|
||||
|
||||
+ (NSURL *)iconURLForBundle:(NSBundle *)bundle
|
||||
{
|
||||
NSString *resource = [bundle objectForInfoDictionaryKey:@"CFBundleIconFile"];
|
||||
if (resource == nil || ![resource isKindOfClass:[NSString class]]) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
NSURL *iconURL = [bundle URLForResource:resource withExtension:@"icns"];
|
||||
|
||||
// The resource could already be containing the path extension, so try again without the extra extension
|
||||
if (iconURL == nil) {
|
||||
iconURL = [bundle URLForResource:resource withExtension:nil];
|
||||
}
|
||||
return iconURL;
|
||||
}
|
||||
|
||||
@end
|
||||
Vendored
+1
@@ -66,6 +66,7 @@ extern NSString *const SUAppcastAttributeDeltaFrom;
|
||||
extern NSString *const SUAppcastAttributeDSASignature;
|
||||
extern NSString *const SUAppcastAttributeShortVersionString;
|
||||
extern NSString *const SUAppcastAttributeVersion;
|
||||
extern NSString *const SUAppcastAttributeInstallationType;
|
||||
|
||||
extern NSString *const SUAppcastElementCriticalUpdate;
|
||||
extern NSString *const SUAppcastElementDeltas;
|
||||
|
||||
Vendored
+1
@@ -64,6 +64,7 @@ NSString *const SUAppcastAttributeDeltaFrom = @"sparkle:deltaFrom";
|
||||
NSString *const SUAppcastAttributeDSASignature = @"sparkle:dsaSignature";
|
||||
NSString *const SUAppcastAttributeShortVersionString = @"sparkle:shortVersionString";
|
||||
NSString *const SUAppcastAttributeVersion = @"sparkle:version";
|
||||
NSString *const SUAppcastAttributeInstallationType = @"sparkle:installationType";
|
||||
|
||||
NSString *const SUAppcastElementCriticalUpdate = @"sparkle:criticalUpdate";
|
||||
NSString *const SUAppcastElementDeltas = @"sparkle:deltas";
|
||||
|
||||
Vendored
+10
-6
@@ -25,8 +25,6 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
- (void)basicDriverIsRequestingAbortUpdateWithError:(nullable NSError *)error;
|
||||
|
||||
- (BOOL)basicDriverShouldSignalShowingUpdateImmediately;
|
||||
|
||||
@optional
|
||||
|
||||
- (void)basicDriverDidFinishLoadingAppcast;
|
||||
@@ -37,7 +35,7 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
- (void)downloadDriverDidReceiveDataOfLength:(NSUInteger)length;
|
||||
|
||||
- (void)coreDriverDidFinishDownloadingUpdate;
|
||||
- (void)coreDriverDidStartExtractingUpdate;
|
||||
|
||||
- (void)installerDidStartInstalling;
|
||||
|
||||
@@ -53,15 +51,21 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
- (instancetype)initWithHost:(SUHost *)host sparkleBundle:(NSBundle *)sparkleBundle updater:(id)updater updaterDelegate:(nullable id <SUUpdaterDelegate>)updaterDelegate delegate:(id<SUCoreBasedUpdateDriverDelegate>)delegate;
|
||||
|
||||
- (void)checkForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary *)httpHeaders includesSkippedUpdates:(BOOL)includesSkippedUpdates completion:(SUUpdateDriverCompletion)completionBlock;
|
||||
- (void)checkForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary *)httpHeaders includesSkippedUpdates:(BOOL)includesSkippedUpdates requiresSilentInstall:(BOOL)silentInstall completion:(SUUpdateDriverCompletion)completionBlock;
|
||||
|
||||
- (void)resumeUpdateWithCompletion:(SUUpdateDriverCompletion)completionBlock;
|
||||
- (void)resumeInstallingUpdateWithCompletion:(SUUpdateDriverCompletion)completionBlock;
|
||||
|
||||
- (void)resumeDownloadedUpdate:(SUDownloadedUpdate *)downloadedUpdate completion:(SUUpdateDriverCompletion)completionBlock;
|
||||
|
||||
- (void)downloadUpdateFromAppcastItem:(SUAppcastItem *)updateItem;
|
||||
|
||||
- (void)extractDownloadedUpdate;
|
||||
|
||||
- (void)clearDownloadedUpdate;
|
||||
|
||||
- (void)finishInstallationWithResponse:(SUInstallUpdateStatus)installUpdateStatus displayingUserInterface:(BOOL)displayingUserInterface;
|
||||
|
||||
- (void)abortUpdateWithError:(nullable NSError *)error;
|
||||
- (void)abortUpdateAndShowNextUpdateImmediately:(BOOL)shouldShowUpdateImmediately error:(nullable NSError *)error;
|
||||
|
||||
@end
|
||||
|
||||
|
||||
Vendored
+56
-25
@@ -14,6 +14,8 @@
|
||||
#import "SUDownloadDriver.h"
|
||||
#import "SULocalCacheDirectory.h"
|
||||
#import "SULog.h"
|
||||
#import "SUErrors.h"
|
||||
#import "SUDownloadedUpdate.h"
|
||||
|
||||
#ifdef _APPKITDEFINES_H
|
||||
#error This is a "core" class and should NOT import AppKit
|
||||
@@ -26,9 +28,11 @@
|
||||
@property (nonatomic, readonly) SUInstallerDriver *installerDriver;
|
||||
@property (nonatomic, weak, readonly) id<SUCoreBasedUpdateDriverDelegate> delegate;
|
||||
@property (nonatomic) SUAppcastItem *updateItem;
|
||||
@property (nonatomic) SUDownloadedUpdate *downloadedUpdate;
|
||||
|
||||
@property (nonatomic, readonly) SUHost *host;
|
||||
@property (nonatomic) BOOL resumingUpdate;
|
||||
@property (nonatomic) BOOL resumingInstallingUpdate;
|
||||
@property (nonatomic) BOOL silentInstall;
|
||||
@property (nonatomic, readonly, weak) id updater; // if we didn't have legacy support, I'd remove this..
|
||||
@property (nullable, nonatomic, readonly, weak) id <SUUpdaterDelegate>updaterDelegate;
|
||||
@property (nonatomic) NSString *userAgent;
|
||||
@@ -43,10 +47,12 @@
|
||||
@synthesize delegate = _delegate;
|
||||
@synthesize updateItem = _updateItem;
|
||||
@synthesize host = _host;
|
||||
@synthesize resumingUpdate = _resumingUpdate;
|
||||
@synthesize resumingInstallingUpdate = _resumingInstallingUpdate;
|
||||
@synthesize silentInstall = _silentInstall;
|
||||
@synthesize updater = _updater;
|
||||
@synthesize updaterDelegate = _updaterDelegate;
|
||||
@synthesize userAgent = _userAgent;
|
||||
@synthesize downloadedUpdate = _downloadedUpdate;
|
||||
|
||||
- (instancetype)initWithHost:(SUHost *)host sparkleBundle:(NSBundle *)sparkleBundle updater:(id)updater updaterDelegate:(nullable id <SUUpdaterDelegate>)updaterDelegate delegate:(id<SUCoreBasedUpdateDriverDelegate>)delegate
|
||||
{
|
||||
@@ -68,17 +74,28 @@
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)checkForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary *)httpHeaders includesSkippedUpdates:(BOOL)includesSkippedUpdates completion:(SUUpdateDriverCompletion)completionBlock
|
||||
- (void)checkForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary *)httpHeaders includesSkippedUpdates:(BOOL)includesSkippedUpdates requiresSilentInstall:(BOOL)silentInstall completion:(SUUpdateDriverCompletion)completionBlock
|
||||
{
|
||||
self.userAgent = userAgent;
|
||||
self.silentInstall = silentInstall;
|
||||
|
||||
[self.basicDriver checkForUpdatesAtAppcastURL:appcastURL withUserAgent:userAgent httpHeaders:httpHeaders includesSkippedUpdates:includesSkippedUpdates completion:completionBlock];
|
||||
}
|
||||
|
||||
- (void)resumeUpdateWithCompletion:(SUUpdateDriverCompletion)completionBlock
|
||||
- (void)resumeInstallingUpdateWithCompletion:(SUUpdateDriverCompletion)completionBlock
|
||||
{
|
||||
self.resumingUpdate = YES;
|
||||
[self.basicDriver resumeUpdateWithCompletion:completionBlock];
|
||||
self.resumingInstallingUpdate = YES;
|
||||
self.silentInstall = NO;
|
||||
|
||||
[self.basicDriver resumeInstallingUpdateWithCompletion:completionBlock];
|
||||
}
|
||||
|
||||
- (void)resumeDownloadedUpdate:(SUDownloadedUpdate *)downloadedUpdate completion:(SUUpdateDriverCompletion)completionBlock
|
||||
{
|
||||
self.downloadedUpdate = downloadedUpdate;
|
||||
self.silentInstall = NO;
|
||||
|
||||
[self.basicDriver resumeDownloadedUpdate:downloadedUpdate completion:completionBlock];
|
||||
}
|
||||
|
||||
- (void)basicDriverDidFinishLoadingAppcast
|
||||
@@ -92,8 +109,8 @@
|
||||
{
|
||||
self.updateItem = updateItem;
|
||||
|
||||
if (self.resumingUpdate) {
|
||||
[self.installerDriver resumeUpdateWithUpdateItem:updateItem];
|
||||
if (self.resumingInstallingUpdate) {
|
||||
[self.installerDriver resumeInstallingUpdateWithUpdateItem:updateItem];
|
||||
}
|
||||
|
||||
[self.delegate basicDriverDidFindUpdateWithAppcastItem:updateItem];
|
||||
@@ -133,22 +150,37 @@
|
||||
}
|
||||
}
|
||||
|
||||
- (void)downloadDriverDidDownloadUpdate
|
||||
- (void)downloadDriverDidDownloadUpdate:(SUDownloadedUpdate *)downloadedUpdate
|
||||
{
|
||||
self.downloadedUpdate = downloadedUpdate;
|
||||
[self extractUpdate:downloadedUpdate];
|
||||
}
|
||||
|
||||
- (void)extractDownloadedUpdate
|
||||
{
|
||||
assert(self.downloadedUpdate != nil);
|
||||
[self extractUpdate:self.downloadedUpdate];
|
||||
}
|
||||
|
||||
- (void)clearDownloadedUpdate
|
||||
{
|
||||
self.downloadedUpdate = nil;
|
||||
}
|
||||
|
||||
- (void)extractUpdate:(SUDownloadedUpdate *)downloadedUpdate
|
||||
{
|
||||
// Now we have to extract the downloaded archive.
|
||||
if ([self.delegate respondsToSelector:@selector(coreDriverDidFinishDownloadingUpdate)]) {
|
||||
[self.delegate coreDriverDidFinishDownloadingUpdate];
|
||||
if ([self.delegate respondsToSelector:@selector(coreDriverDidStartExtractingUpdate)]) {
|
||||
[self.delegate coreDriverDidStartExtractingUpdate];
|
||||
}
|
||||
|
||||
NSString *downloadName = self.downloadDriver.downloadName;
|
||||
assert(downloadName != nil);
|
||||
|
||||
NSString *temporaryDirectory = self.downloadDriver.temporaryDirectory;
|
||||
assert(temporaryDirectory != nil);
|
||||
|
||||
[self.installerDriver extractDownloadName:downloadName withUpdateItem:self.updateItem temporaryDirectory:temporaryDirectory completion:^(NSError * _Nullable error) {
|
||||
[self.installerDriver extractDownloadedUpdate:downloadedUpdate silently:self.silentInstall completion:^(NSError * _Nullable error) {
|
||||
if (error != nil) {
|
||||
[self.delegate coreDriverIsRequestingAbortUpdateWithError:error];
|
||||
} else {
|
||||
// If the installer started properly, we can't use the downloaded update archive anymore
|
||||
// Especially if the installer fails later and we try resuming the update with a missing archive file
|
||||
[self clearDownloadedUpdate];
|
||||
}
|
||||
}];
|
||||
}
|
||||
@@ -243,21 +275,20 @@
|
||||
SUAppcastItem *nonDeltaUpdateItem = self.basicDriver.nonDeltaUpdateItem;
|
||||
assert(nonDeltaUpdateItem != nil);
|
||||
|
||||
[self clearDownloadedUpdate];
|
||||
|
||||
// Fall back to the non-delta update. Note that we don't want to trigger another update was found event.
|
||||
self.updateItem = nonDeltaUpdateItem;
|
||||
[self downloadUpdateFromAppcastItem:nonDeltaUpdateItem];
|
||||
}
|
||||
|
||||
- (BOOL)basicDriverShouldSignalShowingUpdateImmediately
|
||||
{
|
||||
return [self.delegate basicDriverShouldSignalShowingUpdateImmediately];
|
||||
}
|
||||
|
||||
- (void)abortUpdateWithError:(nullable NSError *)error
|
||||
- (void)abortUpdateAndShowNextUpdateImmediately:(BOOL)shouldShowUpdateImmediately error:(nullable NSError *)error
|
||||
{
|
||||
[self.installerDriver abortInstall];
|
||||
[self.downloadDriver cleanup];
|
||||
[self.basicDriver abortUpdateWithError:error];
|
||||
|
||||
SUDownloadedUpdate *downloadedUpdate = (error == nil || error.code == SUInstallationAuthorizeLaterError) ? self.downloadedUpdate : nil;
|
||||
[self.basicDriver abortUpdateAndShowNextUpdateImmediately:shouldShowUpdateImmediately downloadedUpdate:downloadedUpdate error:error];
|
||||
}
|
||||
|
||||
@end
|
||||
Vendored
+3
-5
@@ -10,6 +10,8 @@
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@class SUAppcastItem, SUHost, SUDownloadedUpdate;
|
||||
|
||||
@protocol SUDownloadDriverDelegate <NSObject>
|
||||
|
||||
- (void)downloadDriverWillBeginDownload;
|
||||
@@ -18,14 +20,12 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
- (void)downloadDriverDidReceiveDataOfLength:(NSUInteger)length;
|
||||
|
||||
- (void)downloadDriverDidDownloadUpdate;
|
||||
- (void)downloadDriverDidDownloadUpdate:(SUDownloadedUpdate *)downloadedUpdate;
|
||||
|
||||
- (void)downloadDriverDidFailToDownloadUpdateWithError:(NSError *)error;
|
||||
|
||||
@end
|
||||
|
||||
@class SUAppcastItem, SUHost;
|
||||
|
||||
@interface SUDownloadDriver : NSObject
|
||||
|
||||
- (instancetype)initWithUpdateItem:(SUAppcastItem *)updateItem host:(SUHost *)host userAgent:(NSString *)userAgent delegate:(id<SUDownloadDriverDelegate>)delegate;
|
||||
@@ -33,8 +33,6 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
- (void)downloadUpdate;
|
||||
|
||||
@property (nonatomic, readonly) NSMutableURLRequest *request;
|
||||
@property (nullable, nonatomic, readonly, copy) NSString *temporaryDirectory;
|
||||
@property (nullable, nonatomic, readonly, copy) NSString *downloadName;
|
||||
|
||||
- (void)cleanup;
|
||||
|
||||
|
||||
Vendored
+11
-7
@@ -17,6 +17,7 @@
|
||||
#import "SULog.h"
|
||||
#import "SUErrors.h"
|
||||
#import "SUURLRequest.h"
|
||||
#import "SUDownloadedUpdate.h"
|
||||
|
||||
#ifdef _APPKITDEFINES_H
|
||||
#error This is a "core" class and should NOT import AppKit
|
||||
@@ -34,6 +35,7 @@
|
||||
@property (nonatomic) BOOL retrievedDownloadResult;
|
||||
@property (nonatomic) BOOL retrievedDownloadResponse;
|
||||
@property (nonatomic) NSUInteger expectedContentLength;
|
||||
@property (nonatomic) BOOL cleaningUp;
|
||||
|
||||
@end
|
||||
|
||||
@@ -50,6 +52,7 @@
|
||||
@synthesize retrievedDownloadResult = _retrievedDownloadResult;
|
||||
@synthesize retrievedDownloadResponse = _retrievedDownloadResponse;
|
||||
@synthesize expectedContentLength = _expectedContentLength;
|
||||
@synthesize cleaningUp = _cleaningUp;
|
||||
|
||||
- (instancetype)initWithUpdateItem:(SUAppcastItem *)updateItem host:(SUHost *)host userAgent:(NSString *)userAgent delegate:(id<SUDownloadDriverDelegate>)delegate
|
||||
{
|
||||
@@ -97,7 +100,7 @@
|
||||
self.connection.invalidationHandler = ^{
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
SUDownloadDriver *strongSelf = weakSelf;
|
||||
if (strongSelf != nil && !strongSelf.retrievedDownloadResult) {
|
||||
if (strongSelf != nil && !strongSelf.retrievedDownloadResult && !strongSelf.cleaningUp) {
|
||||
SULog(@"Connection to update downloader was invalidated");
|
||||
|
||||
NSDictionary *userInfo =
|
||||
@@ -118,15 +121,14 @@
|
||||
[self.downloader startDownloadWithRequest:[SUURLRequest URLRequestWithRequest:self.request] bundleIdentifier:bundleIdentifier desiredFilename:desiredFilename];
|
||||
}
|
||||
|
||||
- (void)dealloc
|
||||
{
|
||||
[self cleanup];
|
||||
}
|
||||
|
||||
- (void)cleanup
|
||||
{
|
||||
// It's very crucial to wait until they are done with completion before invalidating our XPC connection (if there is one)
|
||||
// Otherwise we can run into some unfortunate crashes
|
||||
// Edit: I think this was an issue because -dealloc was implemented to invoke this method. I have since removed -dealloc
|
||||
// Will have to test around with this later
|
||||
self.cleaningUp = YES;
|
||||
|
||||
[self.downloader cleanupWithCompletion:^{
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
if (self.connection != nil) {
|
||||
@@ -148,7 +150,9 @@
|
||||
SULog(@"Warning: Downloader's expected content length (%lu) != Appcast item's length (%lu)", self.expectedContentLength, self.updateItem.contentLength);
|
||||
}
|
||||
|
||||
[self.delegate downloadDriverDidDownloadUpdate];
|
||||
SUDownloadedUpdate *downloadedUpdate = [[SUDownloadedUpdate alloc] initWithAppcastItem:self.updateItem downloadName:self.downloadName temporaryDirectory:self.temporaryDirectory];
|
||||
|
||||
[self.delegate downloadDriverDidDownloadUpdate:downloadedUpdate];
|
||||
[self cleanup];
|
||||
});
|
||||
}
|
||||
|
||||
Vendored
+25
@@ -0,0 +1,25 @@
|
||||
//
|
||||
// SUDownloadedUpdate.h
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Mayur Pawashe on 7/18/16.
|
||||
// Copyright © 2016 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@class SUAppcastItem;
|
||||
|
||||
@interface SUDownloadedUpdate : NSObject
|
||||
|
||||
- (instancetype)initWithAppcastItem:(SUAppcastItem *)updateItem downloadName:(NSString *)downloadName temporaryDirectory:(NSString *)temporaryDirectory;
|
||||
|
||||
@property (nonatomic, readonly) SUAppcastItem *updateItem;
|
||||
@property (nonatomic, copy, readonly) NSString *downloadName;
|
||||
@property (nonatomic, copy, readonly) NSString *temporaryDirectory;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
Vendored
+28
@@ -0,0 +1,28 @@
|
||||
//
|
||||
// SUDownloadedUpdate.m
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Mayur Pawashe on 7/18/16.
|
||||
// Copyright © 2016 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#import "SUDownloadedUpdate.h"
|
||||
|
||||
@implementation SUDownloadedUpdate
|
||||
|
||||
@synthesize updateItem = _updateItem;
|
||||
@synthesize downloadName = _downloadName;
|
||||
@synthesize temporaryDirectory = _temporaryDirectory;
|
||||
|
||||
- (instancetype)initWithAppcastItem:(SUAppcastItem *)updateItem downloadName:(NSString *)downloadName temporaryDirectory:(NSString *)temporaryDirectory
|
||||
{
|
||||
self = [super init];
|
||||
if (self != nil) {
|
||||
_updateItem = updateItem;
|
||||
_downloadName = [downloadName copy];
|
||||
_temporaryDirectory = [temporaryDirectory copy];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
@end
|
||||
Vendored
+2
-1
@@ -54,7 +54,8 @@ typedef NS_ENUM(OSStatus, SUError) {
|
||||
SURelaunchError = 4004,
|
||||
SUInstallationError = 4005,
|
||||
SUDowngradeError = 4006,
|
||||
SUInstallationCancelledError = 4007
|
||||
SUInstallationCanceledError = 4007,
|
||||
SUInstallationAuthorizeLaterError = 4008
|
||||
};
|
||||
|
||||
#endif
|
||||
Vendored
-45
@@ -9,8 +9,6 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "SUExport.h"
|
||||
|
||||
@class SUAuthorizationEnvironment;
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
/**
|
||||
@@ -27,37 +25,6 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
*/
|
||||
+ (instancetype)defaultManager;
|
||||
|
||||
/**
|
||||
* Creates a file manager that allows authorizing for file operations
|
||||
* @param authorizationToolPath Specifies the path to the tool that can perform file operations and be run as root.
|
||||
* This tool will be invoked when read or write access is denied when attempting ordinary file operations. See the `fileop` tool included in Sparkle.
|
||||
* @param environment Specifies the authorization environment used when making an authorization request. Pass nil to use a default environment.
|
||||
* @return A new file manager instance
|
||||
*
|
||||
* This method just creates the file manager. It doesn't acquire authorization immediately or if it doesn't need to.
|
||||
*/
|
||||
+ (instancetype)fileManagerWithAuthorizationToolPath:(NSString *)authorizationToolPath environment:(SUAuthorizationEnvironment * _Nullable)environment;
|
||||
|
||||
/**
|
||||
* Returns a file manager that allows or disallows authorizing for file operations based on the current file manager
|
||||
* @return A file manager instance that can perform authorized operations if the current file manager has already performed them.
|
||||
* If the current file manager instance hasn't yet performed authorized operations, then neither can the instance returned by this method
|
||||
*
|
||||
* This may return a newly created file manager or re-use the existing file manager depending on the current authorization rights.
|
||||
*/
|
||||
- (instancetype)fileManagerByPreservingAuthorizationRights;
|
||||
|
||||
/**
|
||||
* Requests and grants authorization for performing authorized operations.
|
||||
*
|
||||
* @param error If an error occurs, upon returns contains an NSError object that describes the problem. If you are not interested in possible errors, you may pass in NULL. An error code of SUInstallationCancelledError is returned if an authorization prompt occurs and the user decides to cancel the request.
|
||||
* @return YES on success otherwise returns NO
|
||||
*
|
||||
* This will prompt the user for an authorization dialog if the user's permission is needed to perform authorized operations.
|
||||
* If the process is running as root already, no authorization prompt is made.
|
||||
*/
|
||||
- (BOOL)grantAuthorizationPrivilegesWithError:(NSError * __autoreleasing *)error;
|
||||
|
||||
/**
|
||||
* Creates a temporary directory on the same volume as a provided URL
|
||||
* @param preferredName A name that may be used when creating the temporary directory. Note that in the uncothirdStageErrormmon case this name is used, the temporary directory will be created inside the directory pointed by appropriateURL
|
||||
@@ -188,18 +155,6 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
*/
|
||||
- (BOOL)releaseItemFromQuarantineAtRootURL:(NSURL *)rootURL error:(NSError **)error;
|
||||
|
||||
/**
|
||||
* Runs an installer package (pkg) in a headless mode using /usr/sbin/installer
|
||||
* @param packageURL A URL pointing to the package to execute. The item at this URL must exist.
|
||||
* @param error If an error occurs, upon returns contains an NSError object that describes the problem. If you are not interested in possible errors, you may pass in NULL.
|
||||
* @return YES if the installer ran the package successfully, otherwise NO with a populated error object
|
||||
*
|
||||
* This method uses the system wide installer tool to run the provided package. This process does not show any UI, except for
|
||||
* an initial authorization prompt if the calling process does not have root privileges. In other words, root privileges are required to use this method, and the file manager instance must have been created by allowing authorization.
|
||||
* An error can occur if the package is unable to be ran by the installer, or if the installer reports a non-zero exit status code.
|
||||
*/
|
||||
- (BOOL)executePackageAtURL:(NSURL *)packageURL error:(NSError **)error;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
Vendored
+28
-407
@@ -7,10 +7,7 @@
|
||||
//
|
||||
|
||||
#import "SUFileManager.h"
|
||||
#import "SUAuthorizationEnvironment.h"
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "SUErrors.h"
|
||||
#import "SUFileOperationConstants.h"
|
||||
|
||||
#include <sys/xattr.h>
|
||||
#include <sys/errno.h>
|
||||
@@ -46,179 +43,27 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
|
||||
return YES;
|
||||
}
|
||||
|
||||
// Used to indicate if the type of NSError requires us to attempt to peform the same operation again except with authentication
|
||||
// To be safe, both read and write permission denied's are included because Cocoa's error methods are not very well documented
|
||||
// and at least one case is caused from lack of read permissions (-[NSURL setResourceValue:forKey:error:])
|
||||
#define NS_HAS_PERMISSION_ERROR(error) (error.code == NSFileReadNoPermissionError || error.code == NSFileWriteNoPermissionError)
|
||||
|
||||
#pragma clang diagnostic push
|
||||
// Use direct access because it's easier, clearer, and faster
|
||||
#pragma clang diagnostic ignored "-Wdirect-ivar-access"
|
||||
|
||||
@implementation SUFileManager
|
||||
{
|
||||
AuthorizationRef _auth;
|
||||
NSFileManager *_fileManager;
|
||||
NSString *_authorizationToolPath;
|
||||
SUAuthorizationEnvironment *_environment;
|
||||
}
|
||||
|
||||
- (instancetype)initWithAuthorizationToolPath:(NSString *)authorizationToolPath environment:(SUAuthorizationEnvironment *)environment
|
||||
- (instancetype)init
|
||||
{
|
||||
self = [super init];
|
||||
if (self != nil) {
|
||||
_fileManager = [[NSFileManager alloc] init];
|
||||
_authorizationToolPath = [authorizationToolPath copy];
|
||||
_environment = environment;
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
+ (instancetype)defaultManager
|
||||
{
|
||||
return [[self alloc] initWithAuthorizationToolPath:nil environment:nil];
|
||||
}
|
||||
|
||||
+ (instancetype)fileManagerWithAuthorizationToolPath:(NSString *)authorizationToolPath environment:(SUAuthorizationEnvironment * _Nullable)environment
|
||||
{
|
||||
return [[self alloc] initWithAuthorizationToolPath:authorizationToolPath environment:environment];
|
||||
}
|
||||
|
||||
- (instancetype)fileManagerByPreservingAuthorizationRights
|
||||
{
|
||||
// Check if we don't allow authorization, or that we haven't needed to authorize yet, to create or re-use a
|
||||
// file manager instance with these restrictions
|
||||
return (_authorizationToolPath != nil && _auth != NULL) ? self : [SUFileManager defaultManager];
|
||||
}
|
||||
|
||||
// Acquires an authorization reference with root privileges which is intended to be used for authorized file operations
|
||||
- (BOOL)_acquireAuthorizationWithError:(NSError *__autoreleasing *)error
|
||||
{
|
||||
// No need to continue if we already acquired an authorization reference
|
||||
if (_auth != NULL) {
|
||||
return YES;
|
||||
}
|
||||
|
||||
if (_authorizationToolPath == nil) {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: @"Unable to grant authorization to perform action because it is explicitly turned off" }];
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
// This should almost always succeed, fail in unusual/rare cases
|
||||
OSStatus createStatus = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, kAuthorizationFlagDefaults, &_auth);
|
||||
if (createStatus != errAuthorizationSuccess) {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed creating authorization reference with status code %d.", createStatus] }];
|
||||
}
|
||||
_auth = NULL;
|
||||
return NO;
|
||||
}
|
||||
|
||||
AuthorizationItem rightItems[] = {
|
||||
// The right that allows us to run tools as root user
|
||||
{.name = kAuthorizationRightExecute, .valueLength = 0, .value = NULL, .flags = 0}
|
||||
};
|
||||
|
||||
AuthorizationRights rights = {
|
||||
.count = sizeof(rightItems) / sizeof(*rightItems),
|
||||
.items = rightItems
|
||||
};
|
||||
|
||||
AuthorizationFlags flags =
|
||||
(AuthorizationFlags)(kAuthorizationFlagDefaults | kAuthorizationFlagInteractionAllowed | kAuthorizationFlagExtendRights | kAuthorizationFlagPreAuthorize);
|
||||
|
||||
// This will test if we can gain authorization for running utlities as root
|
||||
OSStatus copyStatus = AuthorizationCopyRights(_auth, &rights, (_environment != nil ? _environment.environment : kAuthorizationEmptyEnvironment), flags, NULL);
|
||||
if (copyStatus != errAuthorizationSuccess) {
|
||||
if (error != NULL) {
|
||||
if (copyStatus == errAuthorizationCanceled) {
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationCancelledError userInfo:@{ NSLocalizedDescriptionKey: @"Authorization access was cancelled by the user." }];
|
||||
} else {
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed granting authorization rights with status code %d.", copyStatus] }];
|
||||
}
|
||||
}
|
||||
|
||||
AuthorizationFree(_auth, kAuthorizationFlagDefaults);
|
||||
_auth = NULL;
|
||||
|
||||
return NO;
|
||||
}
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (BOOL)_authorizeAndExecuteCommand:(char *)command sourcePath:(char *)sourcePath destinationPath:(char *)destinationPath error:(NSError * __autoreleasing *)error
|
||||
{
|
||||
NSError *acquireError = nil;
|
||||
if (![self _acquireAuthorizationWithError:&acquireError]) {
|
||||
if (error != NULL) {
|
||||
*error = acquireError;
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
char *arguments[] = { command, sourcePath, destinationPath, NULL };
|
||||
|
||||
char toolPath[PATH_MAX] = {0};
|
||||
if (![_authorizationToolPath getFileSystemRepresentation:toolPath maxLength:sizeof(toolPath)]) {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Authorization tool (%@) cannot be represented as a valid file name.", _authorizationToolPath.lastPathComponent] }];
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
FILE *pipe = NULL;
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
|
||||
if (AuthorizationExecuteWithPrivileges(_auth, toolPath, kAuthorizationFlagDefaults, arguments, &pipe) != errAuthorizationSuccess) {
|
||||
#pragma clang diagnostic pop
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey:@"Failed to run authorization tool." }];
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
uint32_t pidData = 0;
|
||||
if (fread(&pidData, sizeof(pidData), 1, pipe) < 1) {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey:@"Failed to retrieve authorized executable process identifier." }];
|
||||
}
|
||||
fclose(pipe);
|
||||
return NO;
|
||||
}
|
||||
|
||||
pid_t childPid = (int32_t)CFSwapInt32LittleToHost(pidData);
|
||||
int status = 0;
|
||||
|
||||
pid_t waitResult;
|
||||
do {
|
||||
waitResult = waitpid(childPid, &status, 0);
|
||||
} while (waitResult == -1 && errno == EINTR);
|
||||
|
||||
fclose(pipe);
|
||||
|
||||
if (waitResult == -1 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Failed to execute authorized executable with result %d and status (%d, %d, %d).", waitResult, status, WIFEXITED(status), WEXITSTATUS(status)] }];
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (void)dealloc
|
||||
{
|
||||
if (_auth != NULL) {
|
||||
AuthorizationFree(_auth, kAuthorizationFlagDefaults);
|
||||
}
|
||||
}
|
||||
|
||||
- (BOOL)grantAuthorizationPrivilegesWithError:(NSError * __autoreleasing *)error
|
||||
{
|
||||
return [self _acquireAuthorizationWithError:error];
|
||||
return [[self alloc] init];
|
||||
}
|
||||
|
||||
// -[NSFileManager attributesOfItemAtPath:error:] won't follow symbolic links
|
||||
@@ -275,36 +120,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
|
||||
return removexattr(path, attr, options);
|
||||
}
|
||||
|
||||
#define XATTR_UTILITY_PATH "/usr/bin/xattr"
|
||||
// Recursively remove an xattr at a specified root URL with authentication
|
||||
- (BOOL)_removeQuarantineWithAuthenticationAtRootURL:(NSURL *)rootURL error:(NSError *__autoreleasing *)error
|
||||
{
|
||||
// Because this is a system utility, it's fine to follow the symbolic link if one exists
|
||||
if (![_fileManager fileExistsAtPath:@(XATTR_UTILITY_PATH)]) {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileNoSuchFileError userInfo:@{ NSLocalizedDescriptionKey: @"xattr utility does not exist on this system." }];
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
char path[PATH_MAX] = {0};
|
||||
if (![rootURL.path getFileSystemRepresentation:path maxLength:sizeof(path)]) {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"File to remove (%@) cannot be represented as a valid file name.", rootURL.path.lastPathComponent] }];
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
NSError *executeError = nil;
|
||||
BOOL success = [self _authorizeAndExecuteCommand:SUFileOpRemoveQuarantineCommand sourcePath:path destinationPath:NULL error:&executeError];
|
||||
if (!success && error != NULL) {
|
||||
*error = executeError;
|
||||
}
|
||||
|
||||
return success;
|
||||
}
|
||||
|
||||
- (BOOL)_releaseItemFromQuarantineAtRootURL:(NSURL *)rootURL withQuarantineRetrieval:(BOOL (^)(NSURL *))quarantineRetrieval quarantineRemoval:(BOOL (^)(NSURL *, NSError * __autoreleasing *))quarantineRemoval isAccessError:(BOOL (^)(NSError *))isAccessError error:(NSError * __autoreleasing *)error
|
||||
- (BOOL)_releaseItemFromQuarantineAtRootURL:(NSURL *)rootURL withQuarantineRetrieval:(BOOL (^)(NSURL *))quarantineRetrieval quarantineRemoval:(BOOL (^)(NSURL *, NSError * __autoreleasing *))quarantineRemoval error:(NSError * __autoreleasing *)error
|
||||
{
|
||||
if (![self _itemExistsAtURL:rootURL]) {
|
||||
if (error != NULL) {
|
||||
@@ -322,18 +138,13 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
|
||||
if (quarantineRemoval(fileURL, &removalError)) {
|
||||
removedQuarantine = YES;
|
||||
} else {
|
||||
if (isAccessError(removalError)) {
|
||||
removedQuarantine = [self _removeQuarantineWithAuthenticationAtRootURL:rootURL error:error];
|
||||
attemptedAuthentication = YES;
|
||||
} else {
|
||||
if (success != NULL) {
|
||||
// Make sure we haven't already run into an error
|
||||
if (*success && error != NULL) {
|
||||
*error = removalError;
|
||||
}
|
||||
// Fail, but still try to release other items from quarantine
|
||||
*success = NO;
|
||||
if (success != NULL) {
|
||||
// Make sure we haven't already run into an error
|
||||
if (*success && error != NULL) {
|
||||
*error = removalError;
|
||||
}
|
||||
// Fail, but still try to release other items from quarantine
|
||||
*success = NO;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -400,6 +211,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
|
||||
{
|
||||
static const int removeXAttrOptions = XATTR_NOFOLLOW;
|
||||
|
||||
#warning this code is over complicated now, needs to be rewritten
|
||||
return
|
||||
[self
|
||||
_releaseItemFromQuarantineAtRootURL:rootURL
|
||||
@@ -413,9 +225,6 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
|
||||
}
|
||||
return removedQuarantine;
|
||||
}
|
||||
isAccessError:^BOOL(NSError *removalError) {
|
||||
return (removalError.code == EACCES);
|
||||
}
|
||||
error:error];
|
||||
}
|
||||
|
||||
@@ -464,43 +273,13 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
|
||||
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
|
||||
OSStatus copyResult = FSCopyObjectSync(&sourceRef, &destinationParentRef, (__bridge CFStringRef)(destinationURL.lastPathComponent), NULL, kFSFileOperationDefaultOptions);
|
||||
#pragma clang diagnostic pop
|
||||
if (copyResult == noErr) {
|
||||
return YES;
|
||||
}
|
||||
|
||||
// Note: I have received afpAccessDenied error in testing even when not copying from/to an AFP mount,
|
||||
// when the error should have been a normal permission denied one
|
||||
if (copyResult != permErr && copyResult != afpAccessDenied) {
|
||||
|
||||
if (copyResult != noErr) {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:NSOSStatusErrorDomain code:copyResult userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to copy file (%@)", sourceURL.lastPathComponent] }];
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
char sourcePath[PATH_MAX] = {0};
|
||||
if (![sourceURL.path getFileSystemRepresentation:sourcePath maxLength:sizeof(sourcePath)]) {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Destination to copy file to (%@) cannot be represented as a valid file name.", sourceURL.lastPathComponent] }];
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
char destinationPath[PATH_MAX] = {0};
|
||||
if (![destinationURL.path getFileSystemRepresentation:destinationPath maxLength:sizeof(destinationPath)]) {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Destination to copy file to (%@) cannot be represented as a valid file name.", destinationURL.lastPathComponent] }];
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
NSError *executeError = nil;
|
||||
if (![self _authorizeAndExecuteCommand:SUFileOpCopyCommand sourcePath:sourcePath destinationPath:destinationPath error:&executeError]) {
|
||||
if (error != NULL) {
|
||||
*error = executeError;
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
@@ -572,48 +351,11 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
|
||||
if (foundSourceVolume && foundDestinationVolume && sourceVolume != destinationVolume) {
|
||||
return ([self copyItemAtURL:sourceURL toURL:destinationURL error:error] && [self removeItemAtURL:sourceURL error:error]);
|
||||
}
|
||||
|
||||
NSError *moveError = nil;
|
||||
if ([_fileManager moveItemAtURL:sourceURL toURL:destinationURL error:&moveError]) {
|
||||
return YES;
|
||||
}
|
||||
|
||||
if (!NS_HAS_PERMISSION_ERROR(moveError)) {
|
||||
if (error != NULL) {
|
||||
*error = moveError;
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
char sourcePath[PATH_MAX] = {0};
|
||||
if (![sourceURL.path getFileSystemRepresentation:sourcePath maxLength:sizeof(sourcePath)]) {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"File to move (%@) cannot be represented as a valid file name.", sourceURL.path.lastPathComponent] }];
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
char destinationPath[PATH_MAX] = {0};
|
||||
if (![destinationURL.path getFileSystemRepresentation:destinationPath maxLength:sizeof(destinationPath)]) {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Destination (%@) cannot be represented as a valid file name.", destinationURL.path.lastPathComponent] }];
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
NSError *executeError = nil;
|
||||
if (![self _authorizeAndExecuteCommand:SUFileOpMoveCommand sourcePath:sourcePath destinationPath:destinationPath error:&executeError]) {
|
||||
if (error != NULL) {
|
||||
NSString *errorMessage = [NSString stringWithFormat:@"Failed to perform authorized file move for %@.", sourceURL.lastPathComponent];
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey:errorMessage, NSUnderlyingErrorKey: executeError }];
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
return YES;
|
||||
return [_fileManager moveItemAtURL:sourceURL toURL:destinationURL error:error];
|
||||
}
|
||||
|
||||
- (BOOL)_changeOwnerAndGroupOfItemAtURL:(NSURL *)targetURL ownerID:(NSNumber *)ownerID groupID:(NSNumber *)groupID needsAuth:(BOOL *)needsAuth error:(NSError * __autoreleasing *)error
|
||||
- (BOOL)_changeOwnerAndGroupOfItemAtURL:(NSURL *)targetURL ownerID:(NSNumber *)ownerID groupID:(NSNumber *)groupID error:(NSError * __autoreleasing *)error
|
||||
{
|
||||
char path[PATH_MAX] = {0};
|
||||
if (![targetURL.path getFileSystemRepresentation:path maxLength:sizeof(path)]) {
|
||||
@@ -632,23 +374,16 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
|
||||
}
|
||||
|
||||
// We use fchown instead of chown because the latter can follow symbolic links
|
||||
BOOL success = fchown(fileDescriptor, ownerID.unsignedIntValue, groupID.unsignedIntValue) == 0;
|
||||
BOOL success = (fchown(fileDescriptor, ownerID.unsignedIntValue, groupID.unsignedIntValue) == 0);
|
||||
close(fileDescriptor);
|
||||
|
||||
if (!success) {
|
||||
if (errno == EPERM) {
|
||||
if (needsAuth != NULL) {
|
||||
*needsAuth = YES;
|
||||
}
|
||||
} else {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to change owner & group for %@ with owner ID %u and group ID %u.", targetURL.path.lastPathComponent, ownerID.unsignedIntValue, groupID.unsignedIntValue] }];
|
||||
}
|
||||
return NO;
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to change owner & group for %@ with owner ID %u and group ID %u.", targetURL.path.lastPathComponent, ownerID.unsignedIntValue, groupID.unsignedIntValue] }];
|
||||
}
|
||||
}
|
||||
|
||||
return YES;
|
||||
return success;
|
||||
}
|
||||
|
||||
- (BOOL)changeOwnerAndGroupOfItemAtRootURL:(NSURL *)targetURL toMatchURL:(NSURL *)matchURL error:(NSError * __autoreleasing *)error
|
||||
@@ -715,53 +450,20 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
|
||||
return YES;
|
||||
}
|
||||
|
||||
BOOL needsAuth = NO;
|
||||
|
||||
if (![self _changeOwnerAndGroupOfItemAtURL:targetURL ownerID:ownerID groupID:groupID needsAuth:&needsAuth error:error]) {
|
||||
if (![self _changeOwnerAndGroupOfItemAtURL:targetURL ownerID:ownerID groupID:groupID error:error]) {
|
||||
return NO;
|
||||
}
|
||||
|
||||
if (isTargetADirectory) {
|
||||
NSDirectoryEnumerator *directoryEnumerator = [_fileManager enumeratorAtURL:targetURL includingPropertiesForKeys:nil options:(NSDirectoryEnumerationOptions)0 errorHandler:nil];
|
||||
for (NSURL *url in directoryEnumerator) {
|
||||
if (![self _changeOwnerAndGroupOfItemAtURL:url ownerID:ownerID groupID:groupID needsAuth:&needsAuth error:error]) {
|
||||
if (![self _changeOwnerAndGroupOfItemAtURL:url ownerID:ownerID groupID:groupID error:error]) {
|
||||
return NO;
|
||||
}
|
||||
|
||||
if (needsAuth) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!needsAuth) {
|
||||
return YES;
|
||||
}
|
||||
|
||||
char targetPath[PATH_MAX] = {0};
|
||||
if (![targetURL.path getFileSystemRepresentation:targetPath maxLength:sizeof(targetPath)]) {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Target file (%@) cannot be represented as a valid file name.", targetURL.path.lastPathComponent] }];
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
char matchPath[PATH_MAX] = {0};
|
||||
if (![matchURLPath getFileSystemRepresentation:matchPath maxLength:sizeof(matchPath)]) {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Match file (%@) cannot be represented as a valid file name.", matchURL.path.lastPathComponent] }];
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
NSError *executeError = nil;
|
||||
BOOL success = [self _authorizeAndExecuteCommand:SUFileOpChangeOwnerAndGroupCommand sourcePath:targetPath destinationPath:matchPath error:&executeError];
|
||||
if (!success && error != NULL) {
|
||||
NSString *errorMessage = [NSString stringWithFormat:@"Failed to change owner & group on %@ to match %@ with authorization.", targetURL.path.lastPathComponent, matchURLPath.lastPathComponent];
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: errorMessage, NSUnderlyingErrorKey: executeError }];
|
||||
}
|
||||
|
||||
return success;
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (BOOL)_updateItemAtURL:(NSURL *)targetURL withAccessTime:(struct timeval)accessTime error:(NSError * __autoreleasing *)error
|
||||
@@ -859,7 +561,7 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
|
||||
// The document says LSRegisterURL() can be used as well but this hasn't worked out well for me in practice
|
||||
// Anyway, updating the modification time of the application is important because the system will be aware a new version of your app is available,
|
||||
// Finder will report the correct file size and other metadata for it, URL schemes your app may register will be updated, etc.
|
||||
// Behind the scenes, touch calls to utimes() which is what we use here - unless we need to authenticate
|
||||
// Behind the scenes, touch calls to utimes() which is what we use here
|
||||
- (BOOL)updateModificationAndAccessTimeOfItemAtURL:(NSURL *)targetURL error:(NSError * __autoreleasing *)error
|
||||
{
|
||||
if (![self _itemExistsAtURL:targetURL]) {
|
||||
@@ -887,28 +589,15 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
|
||||
|
||||
// Using futimes() because utimes() follows symbolic links
|
||||
BOOL updatedTime = (futimes(fileDescriptor, NULL) == 0);
|
||||
|
||||
close(fileDescriptor);
|
||||
|
||||
if (updatedTime) {
|
||||
return YES;
|
||||
}
|
||||
|
||||
if (errno != EACCES) {
|
||||
if (!updatedTime) {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to update modification & access time for %@", targetURL.path.lastPathComponent] }];
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
NSError *executeError = nil;
|
||||
BOOL success = [self _authorizeAndExecuteCommand:SUFileOpUpdateModificationAndAccessTimeCommand sourcePath:path destinationPath:NULL error:&executeError];
|
||||
if (!success && error != NULL) {
|
||||
NSString *errorMessage = [NSString stringWithFormat:@"Failed to update modification & access time on %@ with authorization.", targetURL.path.lastPathComponent];
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: errorMessage, NSUnderlyingErrorKey: executeError }];
|
||||
}
|
||||
|
||||
return success;
|
||||
return updatedTime;
|
||||
}
|
||||
|
||||
// Creates a directory at the item pointed by url
|
||||
@@ -932,35 +621,14 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
|
||||
}
|
||||
|
||||
NSError *createDirectoryError = nil;
|
||||
if ([_fileManager createDirectoryAtURL:url withIntermediateDirectories:NO attributes:nil error:&createDirectoryError]) {
|
||||
return YES;
|
||||
}
|
||||
|
||||
if (!NS_HAS_PERMISSION_ERROR(createDirectoryError)) {
|
||||
if (![_fileManager createDirectoryAtURL:url withIntermediateDirectories:NO attributes:nil error:&createDirectoryError]) {
|
||||
if (error != NULL) {
|
||||
*error = createDirectoryError;
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
char path[PATH_MAX] = {0};
|
||||
if (![url.path getFileSystemRepresentation:path maxLength:sizeof(path)]) {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Directory to create (%@) cannot be represented as a valid file name.", url.path.lastPathComponent] }];
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
NSError *executeError = nil;
|
||||
BOOL success = [self _authorizeAndExecuteCommand:SUFileOpMakeDirectoryCommand sourcePath:path destinationPath:NULL error:&executeError];
|
||||
if (!success) {
|
||||
if (error != NULL) {
|
||||
NSString *errorMessage = [NSString stringWithFormat:@"Failed to make directory %@ with authorization.", url.path.lastPathComponent];
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: errorMessage, NSUnderlyingErrorKey: executeError }];
|
||||
}
|
||||
}
|
||||
|
||||
return success;
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (NSURL *)makeTemporaryDirectoryWithPreferredName:(NSString *)preferredName appropriateForDirectoryURL:(NSURL *)directoryURL error:(NSError * __autoreleasing *)error
|
||||
@@ -994,33 +662,14 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
|
||||
}
|
||||
|
||||
NSError *removeError = nil;
|
||||
if ([_fileManager removeItemAtURL:url error:&removeError]) {
|
||||
return YES;
|
||||
}
|
||||
|
||||
if (!NS_HAS_PERMISSION_ERROR(removeError)) {
|
||||
if (![_fileManager removeItemAtURL:url error:&removeError]) {
|
||||
if (error != NULL) {
|
||||
*error = removeError;
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
char path[PATH_MAX] = {0};
|
||||
if (![url.path getFileSystemRepresentation:path maxLength:sizeof(path)]) {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"File to remove (%@) cannot be represented as a valid file name.", url.path.lastPathComponent] }];
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
NSError *executeError = nil;
|
||||
BOOL success = [self _authorizeAndExecuteCommand:SUFileOpRemoveCommand sourcePath:path destinationPath:NULL error:&executeError];
|
||||
|
||||
if (!success && error != NULL) {
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAuthenticationFailure userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to remove %@ with authentication.", url.path.lastPathComponent], NSUnderlyingErrorKey: executeError }];
|
||||
}
|
||||
|
||||
return success;
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (BOOL)moveItemAtURLToTrash:(NSURL *)url error:(NSError *__autoreleasing *)error
|
||||
@@ -1077,34 +726,6 @@ static BOOL SUMakeRefFromURL(NSURL *url, FSRef *ref, NSError **error) {
|
||||
return success;
|
||||
}
|
||||
|
||||
// Unlike other methods, authorization is required to execute this method successfully
|
||||
- (BOOL)executePackageAtURL:(NSURL *)packageURL error:(NSError * __autoreleasing *)error
|
||||
{
|
||||
if (![self _itemExistsAtURL:packageURL]) {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileNoSuchFileError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to execute package %@ because the file does not exist.", packageURL.path.lastPathComponent] }];
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
char path[PATH_MAX] = {0};
|
||||
if (![packageURL.path getFileSystemRepresentation:path maxLength:sizeof(path)]) {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Package to execute (%@) cannot be represented as a valid file name.", packageURL.path.lastPathComponent] }];
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
NSError *executeError = nil;
|
||||
BOOL success = [self _authorizeAndExecuteCommand:SUFileOpInstallCommand sourcePath:path destinationPath:NULL error:&executeError];
|
||||
|
||||
if (!success && error != NULL) {
|
||||
NSString* errorMessage = @"Failed to execute package installer.";
|
||||
*error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{NSLocalizedDescriptionKey: errorMessage, NSUnderlyingErrorKey: executeError}];
|
||||
}
|
||||
return success;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma clang diagnostic pop
|
||||
Vendored
+20
@@ -0,0 +1,20 @@
|
||||
//
|
||||
// SUInstallationType.h
|
||||
// Sparkle
|
||||
//
|
||||
// Created by Mayur Pawashe on 7/24/16.
|
||||
// Copyright © 2016 Sparkle Project. All rights reserved.
|
||||
//
|
||||
|
||||
#ifndef SUInstallationType_h
|
||||
#define SUInstallationType_h
|
||||
|
||||
#define SUInstallationTypeApplication @"application" // the default installation type for ordinary application updates
|
||||
#define SUInstallationTypeGuidedPackage @"guided-package" // the preferred installation type for package installations
|
||||
#define SUInstallationTypePackage @"package" // the deprecated installation type; use guided package instead
|
||||
|
||||
#define SUInstallationTypeDefault SUInstallationTypeApplication
|
||||
#define SUInstallationTypesArray (@[SUInstallationTypeApplication, SUInstallationTypeGuidedPackage, SUInstallationTypePackage])
|
||||
#define SUValidInstallationType(x) ((x != nil) && [SUInstallationTypesArray containsObject:x])
|
||||
|
||||
#endif /* SUInstallationType_h */
|
||||
Vendored
+3
-3
@@ -11,7 +11,7 @@
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@protocol SUUpdaterDelegate;
|
||||
@class SUHost, SUAppcastItem;
|
||||
@class SUHost, SUAppcastItem, SUDownloadedUpdate;
|
||||
|
||||
@protocol SUInstallerDriverDelegate <NSObject>
|
||||
|
||||
@@ -31,9 +31,9 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
- (instancetype)initWithHost:(SUHost *)host cachePath:(NSString *)cachePath sparkleBundle:(NSBundle *)sparkleBundle updater:(id)updater updaterDelegate:(nullable id<SUUpdaterDelegate>)updaterDelegate delegate:(nullable id<SUInstallerDriverDelegate>)delegate;
|
||||
|
||||
- (void)resumeUpdateWithUpdateItem:(SUAppcastItem *)updateItem;
|
||||
- (void)resumeInstallingUpdateWithUpdateItem:(SUAppcastItem *)updateItem;
|
||||
|
||||
- (void)extractDownloadName:(NSString *)downloadName withUpdateItem:(SUAppcastItem *)updateItem temporaryDirectory:(NSString *)temporaryDirectory completion:(void (^)(NSError * _Nullable))completionHandler;
|
||||
- (void)extractDownloadedUpdate:(SUDownloadedUpdate *)downloadedUpdate silently:(BOOL)silently completion:(void (^)(NSError * _Nullable))completionHandler;
|
||||
|
||||
- (void)installWithToolAndRelaunch:(BOOL)relaunch displayingUserInterface:(BOOL)showUI;
|
||||
|
||||
|
||||
Vendored
+52
-42
@@ -24,6 +24,7 @@
|
||||
#import "SUInstallerConnection.h"
|
||||
#import "SUInstallerConnectionProtocol.h"
|
||||
#import "SUXPCInstallerConnection.h"
|
||||
#import "SUDownloadedUpdate.h"
|
||||
|
||||
#ifdef _APPKITDEFINES_H
|
||||
#error This is a "core" class and should NOT import AppKit
|
||||
@@ -52,6 +53,8 @@
|
||||
@property (nonatomic, copy) NSString *downloadName;
|
||||
@property (nonatomic, copy) NSString *temporaryDirectory;
|
||||
|
||||
@property (nonatomic) BOOL aborted;
|
||||
|
||||
@end
|
||||
|
||||
@implementation SUInstallerDriver
|
||||
@@ -71,6 +74,7 @@
|
||||
@synthesize updateItem = _updateItem;
|
||||
@synthesize downloadName = _downloadName;
|
||||
@synthesize temporaryDirectory = _temporaryDirectory;
|
||||
@synthesize aborted = _aborted;
|
||||
|
||||
- (instancetype)initWithHost:(SUHost *)host cachePath:(NSString *)cachePath sparkleBundle:(NSBundle *)sparkleBundle updater:(id)updater updaterDelegate:(id<SUUpdaterDelegate>)updaterDelegate delegate:(nullable id<SUInstallerDriverDelegate>)delegate
|
||||
{
|
||||
@@ -105,7 +109,7 @@
|
||||
[self.installerConnection setInvalidationHandler:^{
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
SUInstallerDriver *strongSelf = weakSelf;
|
||||
if (strongSelf.installerConnection != nil) {
|
||||
if (strongSelf.installerConnection != nil && !strongSelf.aborted) {
|
||||
NSError *remoteError =
|
||||
[NSError
|
||||
errorWithDomain:SUSparkleErrorDomain
|
||||
@@ -121,23 +125,25 @@
|
||||
}];
|
||||
|
||||
NSString *serviceName = SUInstallerServiceNameForBundleIdentifier(hostBundleIdentifier);
|
||||
NSString *installationType = self.updateItem.installationType;
|
||||
assert(installationType != nil);
|
||||
|
||||
[self.installerConnection setServiceName:serviceName];
|
||||
[self.installerConnection setServiceName:serviceName hostPath:self.host.bundlePath installationType:installationType];
|
||||
|
||||
[self sendInstallationData];
|
||||
}
|
||||
|
||||
// This can be called multiple times (eg: if a delta update fails, this may be called again with a regular update item)
|
||||
- (void)extractDownloadName:(NSString *)downloadName withUpdateItem:(SUAppcastItem *)updateItem temporaryDirectory:(NSString *)temporaryDirectory completion:(void (^)(NSError * _Nullable))completionHandler
|
||||
- (void)extractDownloadedUpdate:(SUDownloadedUpdate *)downloadedUpdate silently:(BOOL)silently completion:(void (^)(NSError * _Nullable))completionHandler
|
||||
{
|
||||
self.updateItem = updateItem;
|
||||
self.temporaryDirectory = temporaryDirectory;
|
||||
self.downloadName = downloadName;
|
||||
self.updateItem = downloadedUpdate.updateItem;
|
||||
self.temporaryDirectory = downloadedUpdate.temporaryDirectory;
|
||||
self.downloadName = downloadedUpdate.downloadName;
|
||||
|
||||
self.currentStage = SUInstallerNotStarted;
|
||||
|
||||
if (self.installerConnection == nil) {
|
||||
[self launchAutoUpdateWithCompletion:completionHandler];
|
||||
[self launchAutoUpdateSilently:silently completion:completionHandler];
|
||||
} else {
|
||||
// The Install tool is already alive; just send out installation input data again
|
||||
[self sendInstallationData];
|
||||
@@ -145,7 +151,7 @@
|
||||
}
|
||||
}
|
||||
|
||||
- (void)resumeUpdateWithUpdateItem:(SUAppcastItem *)updateItem
|
||||
- (void)resumeInstallingUpdateWithUpdateItem:(SUAppcastItem *)updateItem
|
||||
{
|
||||
self.updateItem = updateItem;
|
||||
}
|
||||
@@ -164,18 +170,7 @@
|
||||
decryptionPassword = [self.updaterDelegate decryptionPasswordForUpdater:self.updater];
|
||||
}
|
||||
|
||||
NSString *localProgressToolPath = [self.sparkleBundle pathForResource:@""SPARKLE_INSTALLER_PROGRESS_TOOL_NAME ofType:@"app"];
|
||||
if (localProgressToolPath == nil) {
|
||||
SULog(@"Error: Failed to find installer progress tool: %@", localProgressToolPath);
|
||||
}
|
||||
|
||||
NSError *progressToolError = nil;
|
||||
NSString *progressToolPath = [self copyPathToCacheDirectory:localProgressToolPath error:&progressToolError];
|
||||
if (progressToolPath == nil) {
|
||||
SULog(@"Error: Failed to copy or find installer progress tool: %@", progressToolError);
|
||||
}
|
||||
|
||||
SUInstallationInputData *installationData = [[SUInstallationInputData alloc] initWithRelaunchPath:pathToRelaunch progressToolPath:progressToolPath hostBundlePath:self.host.bundlePath updateDirectoryPath:self.temporaryDirectory downloadName:self.downloadName dsaSignature:dsaSignature decryptionPassword:decryptionPassword];
|
||||
SUInstallationInputData *installationData = [[SUInstallationInputData alloc] initWithRelaunchPath:pathToRelaunch hostBundlePath:self.host.bundlePath updateDirectoryPath:self.temporaryDirectory downloadName:self.downloadName installationType:self.updateItem.installationType dsaSignature:dsaSignature decryptionPassword:decryptionPassword];
|
||||
|
||||
NSData *archivedData = SUArchiveRootObjectSecurely(installationData);
|
||||
if (archivedData == nil) {
|
||||
@@ -268,12 +263,12 @@
|
||||
} else if (identifier == SUInstallationFinishedStage2) {
|
||||
self.currentStage = identifier;
|
||||
|
||||
BOOL cancelledInstallation = NO;
|
||||
BOOL canceledInstallation = NO;
|
||||
if (data.length >= sizeof(uint8_t)) {
|
||||
cancelledInstallation = (*(const uint8_t *)data.bytes == 0x1);
|
||||
canceledInstallation = (*(const uint8_t *)data.bytes == 0x1);
|
||||
}
|
||||
|
||||
if (cancelledInstallation) {
|
||||
if (canceledInstallation) {
|
||||
[self.delegate installerIsRequestingAbortInstallWithError:nil];
|
||||
} else {
|
||||
if (!self.startedInstalling) {
|
||||
@@ -381,23 +376,22 @@
|
||||
return cachePath;
|
||||
}
|
||||
|
||||
- (void)launchAutoUpdateWithCompletion:(void (^)(NSError *_Nullable))completionHandler
|
||||
- (void)launchAutoUpdateSilently:(BOOL)silently completion:(void (^)(NSError *_Nullable))completionHandler
|
||||
{
|
||||
// Copy the relauncher into a temporary directory so we can get to it after the new version's installed.
|
||||
// Only the paranoid survive: if there's already a stray copy of relaunch there, we would have problems.
|
||||
NSError *relaunchError = nil;
|
||||
NSString *relaunchToolPath = [self copyPathToCacheDirectory:[self.sparkleBundle pathForResource:@""SPARKLE_RELAUNCH_TOOL_NAME ofType:@"app"] error:&relaunchError];
|
||||
NSString *relaunchToolPath = [self copyPathToCacheDirectory:[self.sparkleBundle pathForResource:@""SPARKLE_RELAUNCH_TOOL_NAME ofType:@""] error:&relaunchError];
|
||||
if (relaunchToolPath == nil) {
|
||||
completionHandler(relaunchError);
|
||||
return;
|
||||
}
|
||||
|
||||
NSString *hostBundleIdentifier = self.host.bundle.bundleIdentifier;
|
||||
if (hostBundleIdentifier == nil) {
|
||||
NSError *error =
|
||||
[NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey:SULocalizedString(@"An error occurred while finding the application's bundle identifier. Please try again later.", nil) }];
|
||||
|
||||
completionHandler(error);
|
||||
// Copy the progress tool as well
|
||||
NSError *progressToolError = nil;
|
||||
NSString *progressToolPath = [self copyPathToCacheDirectory:[self.sparkleBundle pathForResource:@""SPARKLE_INSTALLER_PROGRESS_TOOL_NAME ofType:@"app"] error:&progressToolError];
|
||||
if (progressToolPath == nil) {
|
||||
completionHandler(progressToolError);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -412,6 +406,7 @@
|
||||
launcherConnection.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUInstallerLauncherProtocol)];
|
||||
[launcherConnection resume];
|
||||
|
||||
#warning revisit weak connection
|
||||
__weak NSXPCConnection *weakConnection = launcherConnection;
|
||||
launcherConnection.interruptionHandler = ^{
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
@@ -435,25 +430,39 @@
|
||||
installerLauncher = launcherConnection.remoteObjectProxy;
|
||||
}
|
||||
|
||||
BOOL shouldAllowInstallerInteraction = YES;
|
||||
#warning review this...
|
||||
BOOL shouldAllowInstallerInteraction = !silently;
|
||||
if ([self.updaterDelegate respondsToSelector:@selector(updaterShouldAllowInstallerInteraction:)]) {
|
||||
shouldAllowInstallerInteraction = [self.updaterDelegate updaterShouldAllowInstallerInteraction:self.updater];
|
||||
}
|
||||
|
||||
[installerLauncher launchInstallerAtPath:relaunchToolPath withHostBundleIdentifier:hostBundleIdentifier allowingInteraction:shouldAllowInstallerInteraction completion:^(BOOL success) {
|
||||
NSString *hostBundlePath = self.host.bundle.bundlePath;
|
||||
assert(hostBundlePath != nil);
|
||||
|
||||
NSString *installationType = self.updateItem.installationType;
|
||||
assert(installationType != nil);
|
||||
|
||||
// The installer launcher could be in a XPC service, so we don't want to do localization in there
|
||||
NSString *authorizationPrompt = [NSString stringWithFormat:SULocalizedString(@"%1$@ wants to update.", nil), self.host.name];
|
||||
[installerLauncher launchInstallerAtPath:relaunchToolPath progressToolPath:progressToolPath withHostBundlePath:hostBundlePath authorizationPrompt:authorizationPrompt installationType:installationType allowingInteraction:shouldAllowInstallerInteraction completion:^(SUAuthorizationReply result) {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
retrievedLaunchStatus = YES;
|
||||
[launcherConnection invalidate];
|
||||
|
||||
if (!success) {
|
||||
NSError *error =
|
||||
[NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey:SULocalizedString(@"An error occurred while launching the installer. Please try again later.", nil) }];
|
||||
|
||||
completionHandler(error);
|
||||
} else {
|
||||
[self setUpConnection];
|
||||
|
||||
completionHandler(nil);
|
||||
switch (result) {
|
||||
case SUAuthorizationReplyFailure:
|
||||
completionHandler([NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey:SULocalizedString(@"An error occurred while launching the installer. Please try again later.", nil) }]);
|
||||
break;
|
||||
case SUAuthorizationReplyCanceled:
|
||||
completionHandler([NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationCanceledError userInfo:nil]);
|
||||
break;
|
||||
case SUAuthorizationReplyAuthorizeLater:
|
||||
completionHandler([NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationAuthorizeLaterError userInfo:nil]);
|
||||
break;
|
||||
case SUAuthorizationReplySuccess:
|
||||
[self setUpConnection];
|
||||
completionHandler(nil);
|
||||
break;
|
||||
}
|
||||
});
|
||||
}];
|
||||
@@ -524,6 +533,7 @@
|
||||
|
||||
- (void)abortInstall
|
||||
{
|
||||
self.aborted = YES;
|
||||
if (self.installerConnection != nil) {
|
||||
[self.installerConnection invalidate];
|
||||
self.installerConnection = nil;
|
||||
|
||||
Vendored
+9
-7
@@ -16,12 +16,14 @@
|
||||
@interface SUProbingUpdateDriver () <SUBasicUpdateDriverDelegate>
|
||||
|
||||
@property (nonatomic, readonly) SUBasicUpdateDriver *basicDriver;
|
||||
@property (nonatomic) SUDownloadedUpdate *downloadedUpdate;
|
||||
|
||||
@end
|
||||
|
||||
@implementation SUProbingUpdateDriver
|
||||
|
||||
@synthesize basicDriver = _basicDriver;
|
||||
@synthesize downloadedUpdate = _downloadedUpdate;
|
||||
|
||||
- (instancetype)initWithHost:(SUHost *)host updater:(id)updater updaterDelegate:(id <SUUpdaterDelegate>)updaterDelegate
|
||||
{
|
||||
@@ -37,14 +39,16 @@
|
||||
[self.basicDriver checkForUpdatesAtAppcastURL:appcastURL withUserAgent:userAgent httpHeaders:httpHeaders includesSkippedUpdates:NO completion:completionBlock];
|
||||
}
|
||||
|
||||
- (BOOL)basicDriverShouldSignalShowingUpdateImmediately
|
||||
- (void)resumeInstallingUpdateWithCompletion:(SUUpdateDriverCompletion)completionBlock
|
||||
{
|
||||
return NO;
|
||||
[self.basicDriver resumeInstallingUpdateWithCompletion:completionBlock];
|
||||
}
|
||||
|
||||
- (void)resumeUpdateWithCompletion:(SUUpdateDriverCompletion)completionBlock
|
||||
- (void)resumeDownloadedUpdate:(SUDownloadedUpdate *)downloadedUpdate completion:(SUUpdateDriverCompletion)completionBlock
|
||||
{
|
||||
[self.basicDriver resumeUpdateWithCompletion:completionBlock];
|
||||
self.downloadedUpdate = downloadedUpdate;
|
||||
|
||||
[self.basicDriver resumeDownloadedUpdate:downloadedUpdate completion:completionBlock];
|
||||
}
|
||||
|
||||
- (void)basicDriverDidFindUpdateWithAppcastItem:(SUAppcastItem *)__unused appcastItem
|
||||
@@ -55,9 +59,7 @@
|
||||
|
||||
- (void)basicDriverIsRequestingAbortUpdateWithError:(nullable NSError *)error
|
||||
{
|
||||
|
||||
[self abortUpdateWithError:error];
|
||||
|
||||
}
|
||||
|
||||
- (void)abortUpdate
|
||||
@@ -67,7 +69,7 @@
|
||||
|
||||
- (void)abortUpdateWithError:(nullable NSError *)error
|
||||
{
|
||||
[self.basicDriver abortUpdateWithError:error];
|
||||
[self.basicDriver abortUpdateAndShowNextUpdateImmediately:NO downloadedUpdate:self.downloadedUpdate error:error];
|
||||
}
|
||||
|
||||
@end
|
||||
Vendored
+7
-2
@@ -40,9 +40,14 @@
|
||||
[self.uiDriver checkForUpdatesAtAppcastURL:appcastURL withUserAgent:userAgent httpHeaders:httpHeaders includesSkippedUpdates:NO completion:completionBlock];
|
||||
}
|
||||
|
||||
- (void)resumeUpdateWithCompletion:(SUUpdateDriverCompletion)completionBlock
|
||||
- (void)resumeInstallingUpdateWithCompletion:(SUUpdateDriverCompletion)completionBlock
|
||||
{
|
||||
[self.uiDriver resumeUpdateWithCompletion:completionBlock];
|
||||
[self.uiDriver resumeInstallingUpdateWithCompletion:completionBlock];
|
||||
}
|
||||
|
||||
- (void)resumeDownloadedUpdate:(SUDownloadedUpdate *)downloadedUpdate completion:(SUUpdateDriverCompletion)completionBlock
|
||||
{
|
||||
[self.uiDriver resumeDownloadedUpdate:downloadedUpdate completion:completionBlock];
|
||||
}
|
||||
|
||||
- (void)basicDriverIsRequestingAbortUpdateWithError:(nullable NSError *)__unused error
|
||||
|
||||
Vendored
+23
-4
@@ -162,7 +162,17 @@
|
||||
- (void)showUpdateFoundWithAppcastItem:(SUAppcastItem *)appcastItem reply:(void (^)(SUUpdateAlertChoice))reply
|
||||
{
|
||||
[self showUpdateFoundWithAlertHandler:^SUUpdateAlert *(SUStandardUserDriver *weakSelf, SUHost *host, id<SUVersionDisplay> versionDisplayer) {
|
||||
return [[SUUpdateAlert alloc] initWithAppcastItem:appcastItem host:host versionDisplayer:versionDisplayer completionBlock:^(SUUpdateAlertChoice choice) {
|
||||
return [[SUUpdateAlert alloc] initWithAppcastItem:appcastItem alreadyDownloaded:NO host:host versionDisplayer:versionDisplayer completionBlock:^(SUUpdateAlertChoice choice) {
|
||||
reply(choice);
|
||||
weakSelf.activeUpdateAlert = nil;
|
||||
}];
|
||||
}];
|
||||
}
|
||||
|
||||
- (void)showDownloadedUpdateFoundWithAppcastItem:(SUAppcastItem *)appcastItem reply:(void (^)(SUUpdateAlertChoice))reply
|
||||
{
|
||||
[self showUpdateFoundWithAlertHandler:^SUUpdateAlert *(SUStandardUserDriver *weakSelf, SUHost *host, id<SUVersionDisplay> versionDisplayer) {
|
||||
return [[SUUpdateAlert alloc] initWithAppcastItem:appcastItem alreadyDownloaded:YES host:host versionDisplayer:versionDisplayer completionBlock:^(SUUpdateAlertChoice choice) {
|
||||
reply(choice);
|
||||
weakSelf.activeUpdateAlert = nil;
|
||||
}];
|
||||
@@ -318,15 +328,22 @@
|
||||
|
||||
#pragma mark Download & Install Updates
|
||||
|
||||
- (void)showStatusController
|
||||
{
|
||||
if (self.statusController == nil) {
|
||||
self.statusController = [[SUStatusController alloc] initWithHost:self.host];
|
||||
[self.statusController showWindow:self];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)showDownloadInitiatedWithCompletion:(void (^)(SUDownloadUpdateStatus))downloadUpdateStatusCompletion
|
||||
{
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[self.coreComponent registerDownloadStatusHandler:downloadUpdateStatusCompletion];
|
||||
|
||||
self.statusController = [[SUStatusController alloc] initWithHost:self.host];
|
||||
[self showStatusController];
|
||||
[self.statusController beginActionWithTitle:SULocalizedString(@"Downloading update...", @"Take care not to overflow the status window.") maxProgressValue:0.0 statusText:nil];
|
||||
[self.statusController setButtonTitle:SULocalizedString(@"Cancel", nil) target:self action:@selector(cancelDownload:) isDefault:NO];
|
||||
[self.statusController showWindow:self];
|
||||
});
|
||||
}
|
||||
|
||||
@@ -359,12 +376,14 @@
|
||||
});
|
||||
}
|
||||
|
||||
- (void)showDownloadFinishedAndStartedExtractingUpdate
|
||||
- (void)showDownloadDidStartExtractingUpdate
|
||||
{
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[self.coreComponent completeDownloadStatus];
|
||||
|
||||
[self showStatusController];
|
||||
[self.statusController beginActionWithTitle:SULocalizedString(@"Extracting update...", @"Take care not to overflow the status window.") maxProgressValue:0.0 statusText:nil];
|
||||
[self.statusController setButtonTitle:SULocalizedString(@"Cancel", nil) target:nil action:nil isDefault:NO];
|
||||
[self.statusController setButtonEnabled:NO];
|
||||
});
|
||||
}
|
||||
|
||||
Vendored
+2
-2
@@ -18,12 +18,12 @@ typedef NS_ENUM(NSUInteger, SUUpdateCheckTimerStatus) {
|
||||
|
||||
typedef NS_ENUM(NSUInteger, SUUserInitiatedCheckStatus) {
|
||||
SUUserInitiatedCheckDone,
|
||||
SUUserInitiatedCheckCancelled
|
||||
SUUserInitiatedCheckCanceled
|
||||
};
|
||||
|
||||
typedef NS_ENUM(NSUInteger, SUDownloadUpdateStatus) {
|
||||
SUDownloadUpdateDone,
|
||||
SUDownloadUpdateCancelled
|
||||
SUDownloadUpdateCanceled
|
||||
};
|
||||
|
||||
typedef NS_ENUM(NSUInteger, SUInstallUpdateStatus) {
|
||||
|
||||
Vendored
+1
-4
@@ -11,9 +11,6 @@
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
// Must free authorization ref later
|
||||
AuthorizationRef SUCreateAuthorization(BOOL * _Nullable grantedSystemPrivilege);
|
||||
|
||||
BOOL SUGrantsSystemAuthorizationAccess(void);
|
||||
BOOL SUNeedsSystemAuthorizationAccess(NSString *path, NSString *installationType, BOOL * _Nullable preflighted);
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
Vendored
+39
-31
@@ -8,45 +8,53 @@
|
||||
|
||||
#import "SUSystemAuthorization.h"
|
||||
#import <ServiceManagement/ServiceManagement.h>
|
||||
#import "SUInstallationType.h"
|
||||
|
||||
AuthorizationRef SUCreateAuthorization(BOOL * _Nullable grantedSystemPrivilege)
|
||||
static BOOL SUPreflightSystemAuthorization(void)
|
||||
{
|
||||
// This should almost always succeed, fail in unusual/rare cases
|
||||
AuthorizationRef auth = NULL;
|
||||
OSStatus createStatus = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, kAuthorizationFlagDefaults, &auth);
|
||||
if (createStatus != errAuthorizationSuccess) {
|
||||
auth = NULL;
|
||||
if (grantedSystemPrivilege != NULL) {
|
||||
*grantedSystemPrivilege = NO;
|
||||
}
|
||||
} else {
|
||||
AuthorizationItem rightItems[] = {
|
||||
{ .name = kSMRightModifySystemDaemons, .valueLength = 0, .value = NULL, .flags = 0}
|
||||
};
|
||||
|
||||
AuthorizationRights rights = {
|
||||
.count = sizeof(rightItems) / sizeof(*rightItems),
|
||||
.items = rightItems,
|
||||
};
|
||||
|
||||
AuthorizationFlags flags =
|
||||
(AuthorizationFlags)(kAuthorizationFlagExtendRights | kAuthorizationFlagPreAuthorize);
|
||||
|
||||
// This will test if we can gain authorization for running utlities as root
|
||||
OSStatus copyStatus = AuthorizationCopyRights(auth, &rights, kAuthorizationEmptyEnvironment, flags, NULL);
|
||||
if (grantedSystemPrivilege != NULL) {
|
||||
*grantedSystemPrivilege = (copyStatus == errAuthorizationSuccess);
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
return auth;
|
||||
}
|
||||
|
||||
BOOL SUGrantsSystemAuthorizationAccess(void)
|
||||
{
|
||||
BOOL grantedSystemPrivilege = NO;
|
||||
|
||||
AuthorizationRef auth = SUCreateAuthorization(&grantedSystemPrivilege);
|
||||
AuthorizationItem rightItems[] = {
|
||||
{ .name = kSMRightModifySystemDaemons, .valueLength = 0, .value = NULL, .flags = 0}
|
||||
};
|
||||
|
||||
AuthorizationRights rights = {
|
||||
.count = sizeof(rightItems) / sizeof(*rightItems),
|
||||
.items = rightItems,
|
||||
};
|
||||
|
||||
AuthorizationFlags flags =
|
||||
(AuthorizationFlags)(kAuthorizationFlagExtendRights | kAuthorizationFlagPreAuthorize);
|
||||
|
||||
// This will test if we can gain authorization for running utlities as root
|
||||
OSStatus copyStatus = AuthorizationCopyRights(auth, &rights, kAuthorizationEmptyEnvironment, flags, NULL);
|
||||
|
||||
AuthorizationFree(auth, kAuthorizationFlagDefaults);
|
||||
|
||||
return grantedSystemPrivilege;
|
||||
return (copyStatus == errAuthorizationSuccess);
|
||||
}
|
||||
|
||||
BOOL SUNeedsSystemAuthorizationAccess(NSString *path, NSString *installationType, BOOL * _Nullable preflighted)
|
||||
{
|
||||
BOOL result;
|
||||
if (SUPreflightSystemAuthorization()) {
|
||||
if (preflighted != NULL) {
|
||||
*preflighted = YES;
|
||||
}
|
||||
result = YES;
|
||||
} else if ([installationType isEqualToString:SUInstallationTypeGuidedPackage]) {
|
||||
result = YES;
|
||||
} else if ([installationType isEqualToString:SUInstallationTypePackage]) {
|
||||
result = NO;
|
||||
} else {
|
||||
#warning what about symbolic links?
|
||||
NSFileManager *fileManager = [NSFileManager defaultManager];
|
||||
result = ![fileManager isWritableFileAtPath:path] || ![fileManager isWritableFileAtPath:[path stringByDeletingLastPathComponent]];
|
||||
}
|
||||
return result;
|
||||
}
|
||||
Vendored
+4
-2
@@ -22,7 +22,7 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@end
|
||||
|
||||
@class SUHost;
|
||||
@class SUHost, SUDownloadedUpdate;
|
||||
@protocol SUUserDriver, SUUpdaterDelegate;
|
||||
|
||||
@interface SUUIBasedUpdateDriver : NSObject
|
||||
@@ -31,7 +31,9 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
- (void)checkForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary *)httpHeaders includesSkippedUpdates:(BOOL)includesSkippedUpdates completion:(SUUpdateDriverCompletion)completionBlock;
|
||||
|
||||
- (void)resumeUpdateWithCompletion:(SUUpdateDriverCompletion)completionBlock;
|
||||
- (void)resumeInstallingUpdateWithCompletion:(SUUpdateDriverCompletion)completionBlock;
|
||||
|
||||
- (void)resumeDownloadedUpdate:(SUDownloadedUpdate *)downloadedUpdate completion:(SUUpdateDriverCompletion)completionBlock;
|
||||
|
||||
- (void)abortUpdateWithError:(nullable NSError *)error;
|
||||
|
||||
|
||||
Vendored
+39
-16
@@ -28,7 +28,8 @@
|
||||
@property (weak, nonatomic, readonly) id<SUUpdaterDelegate> updaterDelegate;
|
||||
@property (nonatomic, weak, readonly) id<SUUIBasedUpdateDriverDelegate> delegate;
|
||||
@property (nonatomic, readonly) id<SUUserDriver> userDriver;
|
||||
@property (nonatomic) BOOL resumingUpdate;
|
||||
@property (nonatomic) BOOL resumingInstallingUpdate;
|
||||
@property (nonatomic) BOOL resumingDownloadedUpdate;
|
||||
|
||||
@end
|
||||
|
||||
@@ -40,7 +41,8 @@
|
||||
@synthesize updaterDelegate = _updaterDelegate;
|
||||
@synthesize userDriver = _userDriver;
|
||||
@synthesize delegate = _delegate;
|
||||
@synthesize resumingUpdate = _resumingUpdate;
|
||||
@synthesize resumingInstallingUpdate = _resumingInstallingUpdate;
|
||||
@synthesize resumingDownloadedUpdate = _resumingDownloadedUpdate;
|
||||
|
||||
- (instancetype)initWithHost:(SUHost *)host sparkleBundle:(NSBundle *)sparkleBundle updater:(id)updater userDriver:(id <SUUserDriver>)userDriver updaterDelegate:(nullable id <SUUpdaterDelegate>)updaterDelegate delegate:(id<SUUIBasedUpdateDriverDelegate>)delegate
|
||||
{
|
||||
@@ -59,13 +61,19 @@
|
||||
|
||||
- (void)checkForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary *)httpHeaders includesSkippedUpdates:(BOOL)includesSkippedUpdates completion:(SUUpdateDriverCompletion)completionBlock
|
||||
{
|
||||
[self.coreDriver checkForUpdatesAtAppcastURL:appcastURL withUserAgent:userAgent httpHeaders:httpHeaders includesSkippedUpdates:includesSkippedUpdates completion:completionBlock];
|
||||
[self.coreDriver checkForUpdatesAtAppcastURL:appcastURL withUserAgent:userAgent httpHeaders:httpHeaders includesSkippedUpdates:includesSkippedUpdates requiresSilentInstall:NO completion:completionBlock];
|
||||
}
|
||||
|
||||
- (void)resumeUpdateWithCompletion:(SUUpdateDriverCompletion)completionBlock
|
||||
- (void)resumeInstallingUpdateWithCompletion:(SUUpdateDriverCompletion)completionBlock
|
||||
{
|
||||
self.resumingUpdate = YES;
|
||||
[self.coreDriver resumeUpdateWithCompletion:completionBlock];
|
||||
self.resumingInstallingUpdate = YES;
|
||||
[self.coreDriver resumeInstallingUpdateWithCompletion:completionBlock];
|
||||
}
|
||||
|
||||
- (void)resumeDownloadedUpdate:(SUDownloadedUpdate *)downloadedUpdate completion:(SUUpdateDriverCompletion)completionBlock
|
||||
{
|
||||
self.resumingDownloadedUpdate = YES;
|
||||
[self.coreDriver resumeDownloadedUpdate:downloadedUpdate completion:completionBlock];
|
||||
}
|
||||
|
||||
- (void)basicDriverDidFinishLoadingAppcast
|
||||
@@ -77,7 +85,25 @@
|
||||
|
||||
- (void)basicDriverDidFindUpdateWithAppcastItem:(SUAppcastItem *)updateItem
|
||||
{
|
||||
if (!self.resumingUpdate) {
|
||||
if (self.resumingDownloadedUpdate) {
|
||||
[self.userDriver showDownloadedUpdateFoundWithAppcastItem:updateItem reply:^(SUUpdateAlertChoice choice) {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[self.host setObject:nil forUserDefaultsKey:SUSkippedVersionKey];
|
||||
switch (choice) {
|
||||
case SUInstallUpdateChoice:
|
||||
[self.coreDriver extractDownloadedUpdate];
|
||||
break;
|
||||
case SUSkipThisVersionChoice:
|
||||
[self.coreDriver clearDownloadedUpdate];
|
||||
[self.host setObject:[updateItem versionString] forUserDefaultsKey:SUSkippedVersionKey];
|
||||
// Fall through
|
||||
case SUInstallLaterChoice:
|
||||
[self.delegate uiDriverIsRequestingAbortUpdateWithError:nil];
|
||||
break;
|
||||
}
|
||||
});
|
||||
}];
|
||||
} else if (!self.resumingInstallingUpdate) {
|
||||
[self.userDriver showUpdateFoundWithAppcastItem:updateItem reply:^(SUUpdateAlertChoice choice) {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[self.host setObject:nil forUserDefaultsKey:SUSkippedVersionKey];
|
||||
@@ -124,7 +150,7 @@
|
||||
switch (downloadCompletionStatus) {
|
||||
case SUDownloadUpdateDone:
|
||||
break;
|
||||
case SUDownloadUpdateCancelled:
|
||||
case SUDownloadUpdateCanceled:
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
if ([self.updaterDelegate respondsToSelector:@selector(userDidCancelDownload:)]) {
|
||||
[self.updaterDelegate userDidCancelDownload:self.updater];
|
||||
@@ -147,9 +173,9 @@
|
||||
[self.userDriver showDownloadDidReceiveDataOfLength:length];
|
||||
}
|
||||
|
||||
- (void)coreDriverDidFinishDownloadingUpdate
|
||||
- (void)coreDriverDidStartExtractingUpdate
|
||||
{
|
||||
[self.userDriver showDownloadFinishedAndStartedExtractingUpdate];
|
||||
[self.userDriver showDownloadDidStartExtractingUpdate];
|
||||
}
|
||||
|
||||
- (void)installerDidStartInstalling
|
||||
@@ -183,11 +209,6 @@
|
||||
[self.userDriver showUpdateInstallationDidFinish];
|
||||
}
|
||||
|
||||
- (BOOL)basicDriverShouldSignalShowingUpdateImmediately
|
||||
{
|
||||
return NO;
|
||||
}
|
||||
|
||||
- (void)basicDriverIsRequestingAbortUpdateWithError:(nullable NSError *)error
|
||||
{
|
||||
// A delegate may want to handle this type of error specially
|
||||
@@ -203,7 +224,7 @@
|
||||
{
|
||||
void (^abortUpdate)(void) = ^{
|
||||
[self.userDriver dismissUpdateInstallation];
|
||||
[self.coreDriver abortUpdateWithError:error];
|
||||
[self.coreDriver abortUpdateAndShowNextUpdateImmediately:NO error:error];
|
||||
};
|
||||
|
||||
if (error != nil) {
|
||||
@@ -215,6 +236,8 @@
|
||||
abortUpdate();
|
||||
});
|
||||
}];
|
||||
} else if (error.code == SUInstallationCanceledError || error.code == SUInstallationAuthorizeLaterError) {
|
||||
abortUpdate();
|
||||
} else {
|
||||
[self.userDriver showUpdaterError:nonNullError acknowledgement:^{
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
|
||||
Loaded 100 of 119 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user