Use XPC for IPC to the installer instead of CFMessagePort

We now use XPC for communication between Sparkle.framework and Autoupdate.
Autoupdate is now ran as a launchd agaent/daemon. (Most of the time, it acts as an agent).

Using XPC can only be done from non-sandboxed processes, so a connection and status service had to be created.

Currently, the GUI progress tool doesn't work properly, but everything else should be behaving like before.
This commit is contained in:
Zorg committed 2016-07-12 19:59:24 -04:00
1 parent 80bc8353ed
commit 8563a40cd2
59 files changed
+1394 -1521

No files matched your search

+5 -5
View File
@@ -34,19 +34,19 @@ MACOSX_DEPLOYMENT_TARGET = 10.8
PRODUCT_NAME = ${TARGET_NAME}
PRODUCT_BUNDLE_IDENTIFIER = org.sparkle-project.Sparkle.${PRODUCT_NAME:rfc1034identifier}
INSTALLER_CONNECTION_PRODUCT_NAME = SparkleInstallerConnection
INSTALLER_STATUS_PRODUCT_NAME = SparkleInstallerStatus
INSTALLER_LAUNCHER_PRODUCT_NAME = SparkleInstallerLauncher
TEMPORARY_DOWNLOADER_PRODUCT_NAME = SparkleTemporaryDownloader
PERSISTENT_DOWNLOADER_PRODUCT_NAME = SparklePersistentDownloader
REMOTE_MESSAGE_PORT_PRODUCT_NAME = SparkleRemoteMessagePort
LOCAL_MESSAGE_PORT_PRODUCT_NAME = SparkleLocalMessagePort
INSTALLER_CONNECTION_BUNDLE_ID = org.sparkle-project.${INSTALLER_CONNECTION_PRODUCT_NAME}
INSTALLER_STATUS_BUNDLE_ID = org.sparkle-project.${INSTALLER_STATUS_PRODUCT_NAME}
INSTALLER_LAUNCHER_BUNDLE_ID = org.sparkle-project.${INSTALLER_LAUNCHER_PRODUCT_NAME}
TEMPORARY_DOWNLOADER_BUNDLE_ID = org.sparkle-project.${TEMPORARY_DOWNLOADER_PRODUCT_NAME}
PERSISTENT_DOWNLOADER_BUNDLE_ID = org.sparkle-project.${PERSISTENT_DOWNLOADER_PRODUCT_NAME}
REMOTE_MESSAGE_PORT_BUNDLE_ID = org.sparkle-project.${REMOTE_MESSAGE_PORT_PRODUCT_NAME}
LOCAL_MESSAGE_PORT_BUNDLE_ID = org.sparkle-project.${LOCAL_MESSAGE_PORT_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}\" TEMPORARY_DOWNLOADER_BUNDLE_ID=\"${TEMPORARY_DOWNLOADER_BUNDLE_ID}\" PERSISTENT_DOWNLOADER_BUNDLE_ID=\"${PERSISTENT_DOWNLOADER_BUNDLE_ID}\" REMOTE_MESSAGE_PORT_BUNDLE_ID=\"${REMOTE_MESSAGE_PORT_BUNDLE_ID}\" LOCAL_MESSAGE_PORT_BUNDLE_ID=\"${LOCAL_MESSAGE_PORT_BUNDLE_ID}\" INSTALLER_LAUNCHER_PRODUCT_NAME=\"${INSTALLER_LAUNCHER_PRODUCT_NAME}\" TEMPORARY_DOWNLOADER_PRODUCT_NAME=\"${TEMPORARY_DOWNLOADER_PRODUCT_NAME}\" PERSISTENT_DOWNLOADER_PRODUCT_NAME=\"${PERSISTENT_DOWNLOADER_PRODUCT_NAME}\" REMOTE_MESSAGE_PORT_PRODUCT_NAME=\"${REMOTE_MESSAGE_PORT_PRODUCT_NAME}\" LOCAL_MESSAGE_PORT_PRODUCT_NAME=\"${LOCAL_MESSAGE_PORT_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}\" SPARKLE_FILEOP_TOOL_NAME=\"$(SPARKLE_FILEOP_TOOL_NAME)\"
CLANG_ENABLE_OBJC_ARC = YES
GCC_ENABLE_PASCAL_STRINGS = NO
@@ -0,0 +1,6 @@
// InstallerConnection
INFOPLIST_FILE = InstallerConnection/Info.plist
WRAPPER_EXTENSION = xpc
PRODUCT_BUNDLE_IDENTIFIER = ${INSTALLER_CONNECTION_BUNDLE_ID}
PRODUCT_NAME = ${INSTALLER_CONNECTION_PRODUCT_NAME}
@@ -0,0 +1,5 @@
// InstallerConnection Debug
#include "ConfigInstallerConnection.xcconfig"
CODE_SIGN_IDENTITY = -
@@ -0,0 +1,6 @@
// InstallerStatus
INFOPLIST_FILE = InstallerStatus/Info.plist
WRAPPER_EXTENSION = xpc
PRODUCT_BUNDLE_IDENTIFIER = ${INSTALLER_STATUS_BUNDLE_ID}
PRODUCT_NAME = ${INSTALLER_STATUS_PRODUCT_NAME}
@@ -0,0 +1,5 @@
// InstallerStatus Debug
#include "ConfigInstallerStatus.xcconfig"
CODE_SIGN_IDENTITY = -
@@ -1,6 +0,0 @@
// LocalMessagePort
INFOPLIST_FILE = LocalMessagePort/Info.plist
WRAPPER_EXTENSION = xpc
PRODUCT_BUNDLE_IDENTIFIER = ${LOCAL_MESSAGE_PORT_BUNDLE_ID}
PRODUCT_NAME = ${LOCAL_MESSAGE_PORT_PRODUCT_NAME}
@@ -1,5 +0,0 @@
// LocalMessagePort Debug
#include "ConfigLocalMessagePort.xcconfig"
CODE_SIGN_IDENTITY = -
@@ -1,6 +0,0 @@
// RemoteMessagePort
INFOPLIST_FILE = RemoteMessagePort/Info.plist
WRAPPER_EXTENSION = xpc
PRODUCT_BUNDLE_IDENTIFIER = ${REMOTE_MESSAGE_PORT_BUNDLE_ID}
PRODUCT_NAME = ${REMOTE_MESSAGE_PORT_PRODUCT_NAME}
@@ -1,5 +0,0 @@
// RemoteMessagePort Debug
#include "ConfigRemoteMessagePort.xcconfig"
CODE_SIGN_IDENTITY = -
+4 -4
View File
@@ -24,8 +24,8 @@ if [ "$ACTION" = "" ] ; then
cp -R "$CONFIGURATION_BUILD_DIR/SparkleInstallerLauncher.xpc" "$CONFIGURATION_BUILD_DIR/staging/XPCServices"
cp -R "$CONFIGURATION_BUILD_DIR/SparklePersistentDownloader.xpc" "$CONFIGURATION_BUILD_DIR/staging/XPCServices"
cp -R "$CONFIGURATION_BUILD_DIR/SparkleTemporaryDownloader.xpc" "$CONFIGURATION_BUILD_DIR/staging/XPCServices"
cp -R "$CONFIGURATION_BUILD_DIR/SparkleLocalMessagePort.xpc" "$CONFIGURATION_BUILD_DIR/staging/XPCServices"
cp -R "$CONFIGURATION_BUILD_DIR/SparkleRemoteMessagePort.xpc" "$CONFIGURATION_BUILD_DIR/staging/XPCServices"
cp -R "$CONFIGURATION_BUILD_DIR/SparkleInstallerConnection.xpc" "$CONFIGURATION_BUILD_DIR/staging/XPCServices"
cp -R "$CONFIGURATION_BUILD_DIR/SparkleInstallerStatus.xpc" "$CONFIGURATION_BUILD_DIR/staging/XPCServices"
cp "$SRCROOT/TemporaryDownloader/SparkleTemporaryDownloader.entitlements" "$CONFIGURATION_BUILD_DIR/staging/XPCServices"
cp "$SRCROOT/PersistentDownloader/SparklePersistentDownloader.entitlements" "$CONFIGURATION_BUILD_DIR/staging/XPCServices"
@@ -40,8 +40,8 @@ if [ "$ACTION" = "" ] ; then
cp -R "$CONFIGURATION_BUILD_DIR/SparkleInstallerLauncher.xpc.dSYM" "$CONFIGURATION_BUILD_DIR/staging/XPCServices"
cp -R "$CONFIGURATION_BUILD_DIR/SparklePersistentDownloader.xpc.dSYM" "$CONFIGURATION_BUILD_DIR/staging/XPCServices"
cp -R "$CONFIGURATION_BUILD_DIR/SparkleTemporaryDownloader.xpc.dSYM" "$CONFIGURATION_BUILD_DIR/staging/XPCServices"
cp -R "$CONFIGURATION_BUILD_DIR/SparkleLocalMessagePort.xpc.dSYM" "$CONFIGURATION_BUILD_DIR/staging/XPCServices"
cp -R "$CONFIGURATION_BUILD_DIR/SparkleRemoteMessagePort.xpc.dSYM" "$CONFIGURATION_BUILD_DIR/staging/XPCServices"
cp -R "$CONFIGURATION_BUILD_DIR/SparkleInstallerConnection.xpc.dSYM" "$CONFIGURATION_BUILD_DIR/staging/XPCServices"
cp -R "$CONFIGURATION_BUILD_DIR/SparkleInstallerStatus.xpc.dSYM" "$CONFIGURATION_BUILD_DIR/staging/XPCServices"
fi
cd "$CONFIGURATION_BUILD_DIR/staging"
File renamed without changes.
@@ -0,0 +1,19 @@
//
// SUInstallerCommunicationProtocol.h
// Sparkle
//
// Created by Mayur Pawashe on 7/9/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@protocol SUInstallerCommunicationProtocol
- (void)handleMessageWithIdentifier:(int32_t)identifier data:(NSData *)data;
@end
NS_ASSUME_NONNULL_END
@@ -0,0 +1,22 @@
//
// SUInstallerConnection.h
// InstallerConnection
//
// Created by Mayur Pawashe on 7/9/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "SUInstallerConnectionProtocol.h"
NS_ASSUME_NONNULL_BEGIN
// This object implements the protocol which we have defined. It provides the actual behavior for the service. It is 'exported' by the service to make it available to the process hosting the service over an NSXPCConnection.
@interface SUInstallerConnection : NSObject <SUInstallerConnectionProtocol>
// Due to XPC reasons, this delegate is strongly referenced, until it's invalidated
- (instancetype)initWithDelegate:(id<SUInstallerCommunicationProtocol>)delegate;
@end
NS_ASSUME_NONNULL_END
+113
View File
@@ -0,0 +1,113 @@
//
// SUInstallerConnection.m
// InstallerConnection
//
// Created by Mayur Pawashe on 7/9/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import "SUInstallerConnection.h"
#import "SUSystemAuthorization.h"
static NSString *SUInstallerConnectionKeepAliveReason = @"Installer Connection Keep Alive";
@interface SUInstallerConnection () <SUInstallerCommunicationProtocol>
// Intentionally not weak for XPC reasons
@property (nonatomic) id<SUInstallerCommunicationProtocol> delegate;
@property (nonatomic) BOOL disabledAutomaticTermination;
@property (nonatomic, copy) void (^invalidationBlock)(void);
@property (nonatomic) NSXPCConnection *connection;
@end
@implementation SUInstallerConnection
@synthesize delegate = _delegate;
@synthesize disabledAutomaticTermination = _disabledAutomaticTermination;
@synthesize invalidationBlock = _invalidationBlock;
@synthesize connection = _connection;
- (instancetype)initWithDelegate:(id<SUInstallerCommunicationProtocol>)delegate
{
self = [super init];
if (self != nil) {
_delegate = delegate;
// If we are a XPC service, protect it from being terminated until the invalidation handler is set
_disabledAutomaticTermination = YES;
[[NSProcessInfo processInfo] disableAutomaticTermination:SUInstallerConnectionKeepAliveReason];
}
return self;
}
- (void)enableAutomaticTermination
{
if (self.disabledAutomaticTermination) {
[[NSProcessInfo processInfo] enableAutomaticTermination:SUInstallerConnectionKeepAliveReason];
self.disabledAutomaticTermination = NO;
}
}
- (void)setInvalidationHandler:(void (^)(void))invalidationHandler
{
self.invalidationBlock = invalidationHandler;
// No longer needed because of invalidation callback
[self enableAutomaticTermination];
}
- (void)setServiceName:(NSString *)serviceName
{
NSXPCConnectionOptions options = SUGrantsSystemAuthorizationAccess() ? NSXPCConnectionPrivileged : 0;
NSXPCConnection *connection = [[NSXPCConnection alloc] initWithMachServiceName:serviceName options:options];
connection.exportedInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUInstallerCommunicationProtocol)];
connection.exportedObject = self.delegate;
connection.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUInstallerCommunicationProtocol)];
self.connection = connection;
__weak SUInstallerConnection *weakSelf = self;
self.connection.interruptionHandler = ^{
[weakSelf invalidate];
};
self.connection.invalidationHandler = ^{
SUInstallerConnection *strongSelf = weakSelf;
if (strongSelf != nil) {
strongSelf.connection = nil;
[strongSelf invalidate];
}
};
[self.connection resume];
}
- (void)handleMessageWithIdentifier:(int32_t)identifier data:(NSData *)data
{
[self.connection.remoteObjectProxy handleMessageWithIdentifier:identifier data:data];
}
// This method can be called by us or from a remote
- (void)invalidate
{
dispatch_async(dispatch_get_main_queue(), ^{
[self.connection invalidate];
self.connection = nil;
if (self.invalidationBlock != nil) {
self.invalidationBlock();
self.invalidationBlock = nil;
}
// Break the retain cycle
self.delegate = nil;
[self enableAutomaticTermination];
});
}
@end
@@ -0,0 +1,24 @@
//
// SUInstallerConnectionProtocol.h
// InstallerConnection
//
// Created by Mayur Pawashe on 7/9/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "SUInstallerCommunicationProtocol.h"
NS_ASSUME_NONNULL_BEGIN
@protocol SUInstallerConnectionProtocol <SUInstallerCommunicationProtocol>
- (void)setInvalidationHandler:(void (^)(void))invalidationHandler;
- (void)setServiceName:(NSString *)serviceName;
- (void)invalidate;
@end
NS_ASSUME_NONNULL_END
@@ -0,0 +1,21 @@
//
// SUXPCInstallerConnection.h
// Sparkle
//
// Created by Mayur Pawashe on 7/10/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "SUInstallerConnectionProtocol.h"
NS_ASSUME_NONNULL_BEGIN
@interface SUXPCInstallerConnection : NSObject <SUInstallerConnectionProtocol>
// Due to XPC reasons, this delegate is strongly referenced, until it's invalidated
- (instancetype)initWithDelegate:(id<SUInstallerCommunicationProtocol>)delegate;
@end
NS_ASSUME_NONNULL_END
@@ -0,0 +1,89 @@
//
// SUXPCInstallerConnection.m
// Sparkle
//
// Created by Mayur Pawashe on 7/10/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import "SUXPCInstallerConnection.h"
@interface SUXPCInstallerConnection ()
@property (nonatomic) NSXPCConnection *connection;
@property (nonatomic) id<SUInstallerCommunicationProtocol> delegate; // intentionally not weak for XPC reasons
@property (nonatomic, copy) void (^invalidationBlock)(void);
@end
@implementation SUXPCInstallerConnection
@synthesize connection = _connection;
@synthesize delegate = _delegate;
@synthesize invalidationBlock = _invalidationBlock;
- (instancetype)initWithDelegate:(id<SUInstallerCommunicationProtocol>)delegate
{
self = [super init];
if (self != nil) {
_connection = [[NSXPCConnection alloc] initWithServiceName:@INSTALLER_CONNECTION_BUNDLE_ID];
_connection.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUInstallerConnectionProtocol)];
__weak SUXPCInstallerConnection *weakSelf = self;
_connection.invalidationHandler = ^{
[weakSelf invokeInvalidation];
};
_connection.interruptionHandler = ^{
[weakSelf invokeInvalidation];
[weakSelf.connection invalidate];
};
_delegate = delegate;
_connection.exportedInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUInstallerCommunicationProtocol)];
_connection.exportedObject = _delegate;
[_connection resume];
}
return self;
}
- (void)setInvalidationHandler:(void (^)(void))invalidationHandler
{
self.invalidationBlock = invalidationHandler;
__weak SUXPCInstallerConnection *weakSelf = self;
[self.connection.remoteObjectProxy setInvalidationHandler:^{
[weakSelf invokeInvalidation];
}];
}
- (void)setServiceName:(NSString *)serviceName
{
[self.connection.remoteObjectProxy setServiceName:serviceName];
}
- (void)handleMessageWithIdentifier:(int32_t)identifier data:(NSData *)data
{
[self.connection.remoteObjectProxy handleMessageWithIdentifier:identifier data:data];
}
- (void)invalidate
{
[self.connection.remoteObjectProxy invalidate];
[self.connection invalidate];
self.connection = nil;
}
- (void)invokeInvalidation
{
if (self.invalidationBlock != nil) {
self.invalidationBlock();
self.invalidationBlock = nil;
}
// Break our retain cycle
self.delegate = nil;
}
@end
@@ -1,14 +1,14 @@
//
// main.m
// LocalMessagePort
// InstallerConnection
//
// Created by Mayur Pawashe on 6/14/16.
// Created by Mayur Pawashe on 7/9/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "SULocalMessagePort.h"
#import "SULocalMessagePortDelegate.h"
#import "SUInstallerConnection.h"
#import "SUInstallerCommunicationProtocol.h"
@interface ServiceDelegate : NSObject <NSXPCListenerDelegate>
@end
@@ -19,10 +19,13 @@
// This method is where the NSXPCListener configures, accepts, and resumes a new incoming NSXPCConnection.
// Configure the connection.
newConnection.exportedInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SULocalMessagePortProtocol)];
newConnection.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SULocalMessagePortDelegate)];
// First, set the interface that the exported object implements.
newConnection.exportedInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUInstallerConnectionProtocol)];
newConnection.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUInstallerCommunicationProtocol)];
newConnection.exportedObject = [[SULocalMessagePort alloc] initWithDelegate:newConnection.remoteObjectProxy];
SUInstallerConnection *exportedObject = [[SUInstallerConnection alloc] initWithDelegate:newConnection.remoteObjectProxy];
newConnection.exportedObject = exportedObject;
// Resuming the connection allows the system to deliver more incoming messages.
[newConnection resume];
+46 -36
View File
@@ -9,55 +9,65 @@
#import "SUInstallerLauncher.h"
#import "SUFileManager.h"
#import "SULog.h"
#import <AppKit/AppKit.h>
#import "SUMessageTypes.h"
#import <ServiceManagement/SMLoginItem.h>
#import "SUSystemAuthorization.h"
@implementation SUInstallerLauncher
- (void)launchInstallerAtPath:(NSString *)installerPath withHostBundleIdentifier:(NSString *)hostBundleIdentifier inheritingPrivileges:(BOOL)inheritingPrivileges completion:(void (^)(BOOL success))completionHandler
- (void)launchInstallerAtPath:(NSString *)installerPath withHostBundleIdentifier:(NSString *)hostBundleIdentifier allowingInteraction:(BOOL)allowingInteraction completion:(void (^)(BOOL success))completionHandler
{
dispatch_async(dispatch_get_main_queue(), ^{
NSError *quarantineError = nil;
SUFileManager *fileManager = [SUFileManager defaultManager];
if (![fileManager releaseItemFromQuarantineAtRootURL:[NSURL fileURLWithPath:installerPath] error:&quarantineError]) {
NSURL *installerURL = [NSURL fileURLWithPath:installerPath];
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);
}
NSArray *arguments = @[hostBundleIdentifier, @(inheritingPrivileges).stringValue];
NSString *executablePath = [[[installerPath stringByAppendingPathComponent:@"Contents"] stringByAppendingPathComponent:@"MacOS"] stringByAppendingPathComponent:@SPARKLE_RELAUNCH_TOOL_NAME];
if (!inheritingPrivileges) {
// This new process does not inherit privileges because it's being launched via LaunchServices
// This allows the installer app to make authorization requests for example from a non-sandboxed XPC service
// From testing I have found this is necessary if the entirety of Sparkle's framework is inside a XPC service
NSError *launchError = nil;
NSRunningApplication *runningApplication = [[NSWorkspace sharedWorkspace] launchApplicationAtURL:[NSURL fileURLWithPath:installerPath] options:(NSWorkspaceLaunchOptions)(NSWorkspaceLaunchDefault | NSWorkspaceLaunchNewInstance) configuration:@{NSWorkspaceLaunchConfigurationArguments : arguments} error:&launchError];
if (runningApplication == nil) {
SULog(@"Failed to launch %@ app with error: %@", @SPARKLE_RELAUNCH_TOOL_NAME, launchError);
}
completionHandler(runningApplication != nil);
} else {
// This new process inherits privileges and thus will not use the authorization reference API, nor request a dialog for authorization
// If we have root permissions, so will this new process
// The reason I don't create a NSBundle to locate the executable is because I worry about NSBundle caching and if we enter here multiple times
NSString *executablePath = [[[installerPath stringByAppendingPathComponent:@"Contents"] stringByAppendingPathComponent:@"MacOS"] stringByAppendingPathComponent:@SPARKLE_RELAUNCH_TOOL_NAME];
NSTask *task = [[NSTask alloc] init];
task.launchPath = executablePath;
task.arguments = arguments;
BOOL success = NO;
@try {
[task launch];
success = YES;
} @catch (NSException *exception) {
SULog(@"Failed to launch %@ app with exception: %@", @SPARKLE_RELAUNCH_TOOL_NAME, exception);
}
completionHandler(success);
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 = @[hostBundleIdentifier, @(allowingInteraction).stringValue];
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];
CFErrorRef removeError = NULL;
if (!SMJobRemove(domain, (__bridge CFStringRef)(label), auth, true, &removeError)) {
if (removeError != NULL) {
SULog(@"Remove error: %@", removeError);
CFRelease(removeError);
}
}
NSDictionary *jobDictionary = @{@"Label" : label, @"ProgramArguments" : [@[executablePath] arrayByAddingObjectsFromArray:arguments], @"EnableTransactions" : @NO, @"KeepAlive" : @{@"SuccessfulExit" : @NO}, @"RunAtLoad" : @NO, @"NICE" : @0, @"LaunchOnlyOnce": @YES, @"MachServices" : @{SUAutoUpdateServiceNameForBundleIdentifier(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);
}
}
AuthorizationFree(auth, kAuthorizationFlagDefaults);
}
completionHandler(submittedJob == true);
});
}
@@ -10,6 +10,6 @@
@protocol SUInstallerLauncherProtocol
- (void)launchInstallerAtPath:(NSString *)installerPath withHostBundleIdentifier:(NSString *)hostBundleIdentifier inheritingPrivileges:(BOOL)inheritingPrivileges completion:(void (^)(BOOL success))completionHandler;
- (void)launchInstallerAtPath:(NSString *)installerPath withHostBundleIdentifier:(NSString *)hostBundleIdentifier allowingInteraction:(BOOL)allowingInteraction completion:(void (^)(BOOL success))completionHandler;
@end
File renamed without changes.
+15
View File
@@ -0,0 +1,15 @@
//
// SUInstallerStatus.h
// InstallerStatus
//
// Created by Mayur Pawashe on 7/10/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "SUInstallerStatusProtocol.h"
// This object implements the protocol which we have defined. It provides the actual behavior for the service. It is 'exported' by the service to make it available to the process hosting the service over an NSXPCConnection.
@interface SUInstallerStatus : NSObject <SUInstallerStatusProtocol>
@end
+78
View File
@@ -0,0 +1,78 @@
//
// SUInstallerStatus.m
// InstallerStatus
//
// Created by Mayur Pawashe on 7/10/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import "SUInstallerStatus.h"
#import "SUSystemAuthorization.h"
@interface SUInstallerStatus ()
@property (nonatomic, copy) void (^invalidationBlock)(void);
@property (nonatomic) NSXPCConnection *connection;
@end
@implementation SUInstallerStatus
@synthesize invalidationBlock = _invalidationBlock;
@synthesize connection = _connection;
- (void)setInvalidationHandler:(void (^)(void))invalidationHandler
{
self.invalidationBlock = invalidationHandler;
}
- (void)setServiceName:(NSString *)serviceName
{
NSXPCConnectionOptions options = SUGrantsSystemAuthorizationAccess() ? NSXPCConnectionPrivileged : 0;
NSXPCConnection *connection = [[NSXPCConnection alloc] initWithMachServiceName:serviceName options:options];
connection.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUStatusInfoProtocol)];
self.connection = connection;
__weak SUInstallerStatus *weakSelf = self;
self.connection.interruptionHandler = ^{
[weakSelf invalidate];
};
self.connection.invalidationHandler = ^{
SUInstallerStatus *strongSelf = weakSelf;
if (strongSelf != nil) {
strongSelf.connection = nil;
[strongSelf invalidate];
}
};
[self.connection resume];
}
- (void)probeStatusInfoWithReply:(void (^)(NSData * _Nullable installationInfoData))reply
{
[self.connection.remoteObjectProxy probeStatusInfoWithReply:reply];
}
- (void)probeStatusConnectivityWithReply:(void (^)(void))reply
{
[self.connection.remoteObjectProxy probeStatusConnectivityWithReply:reply];
}
// This method can be called by us or from a remote
- (void)invalidate
{
dispatch_async(dispatch_get_main_queue(), ^{
[self.connection invalidate];
self.connection = nil;
if (self.invalidationBlock != nil) {
self.invalidationBlock();
self.invalidationBlock = nil;
}
});
}
@end
@@ -0,0 +1,21 @@
//
// SUInstallerStatusProtocol.h
// InstallerStatus
//
// Created by Mayur Pawashe on 7/10/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "SUStatusInfoProtocol.h"
// 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>
- (void)setInvalidationHandler:(void (^)(void))invalidationHandler;
- (void)setServiceName:(NSString *)serviceName;
- (void)invalidate;
@end
+14
View File
@@ -0,0 +1,14 @@
//
// SUXPCInstallerStatus.h
// Sparkle
//
// Created by Mayur Pawashe on 7/10/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "SUInstallerStatusProtocol.h"
@interface SUXPCInstallerStatus : NSObject <SUInstallerStatusProtocol>
@end
+85
View File
@@ -0,0 +1,85 @@
//
// SUXPCInstallerStatus.m
// Sparkle
//
// Created by Mayur Pawashe on 7/10/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import "SUXPCInstallerStatus.h"
@interface SUXPCInstallerStatus ()
@property (nonatomic) NSXPCConnection *connection;
@property (nonatomic, copy) void (^invalidationBlock)(void);
@end
@implementation SUXPCInstallerStatus
@synthesize connection = _connection;
@synthesize invalidationBlock = _invalidationBlock;
- (instancetype)init
{
self = [super init];
if (self != nil) {
_connection = [[NSXPCConnection alloc] initWithServiceName:@INSTALLER_STATUS_BUNDLE_ID];
_connection.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUInstallerStatusProtocol)];
__weak SUXPCInstallerStatus *weakSelf = self;
_connection.invalidationHandler = ^{
[weakSelf invokeInvalidation];
};
_connection.interruptionHandler = ^{
[weakSelf invokeInvalidation];
[weakSelf.connection invalidate];
};
[_connection resume];
}
return self;
}
- (void)setInvalidationHandler:(void (^)(void))invalidationHandler
{
self.invalidationBlock = invalidationHandler;
__weak SUXPCInstallerStatus *weakSelf = self;
[self.connection.remoteObjectProxy setInvalidationHandler:^{
[weakSelf invokeInvalidation];
}];
}
- (void)setServiceName:(NSString *)serviceName
{
[self.connection.remoteObjectProxy setServiceName:serviceName];
}
- (void)probeStatusInfoWithReply:(void (^)(NSData * _Nullable installationInfoData))reply
{
[self.connection.remoteObjectProxy probeStatusInfoWithReply:reply];
}
- (void)probeStatusConnectivityWithReply:(void (^)(void))reply
{
[self.connection.remoteObjectProxy probeStatusConnectivityWithReply:reply];
}
- (void)invalidate
{
[self.connection.remoteObjectProxy invalidate];
[self.connection invalidate];
self.connection = nil;
}
- (void)invokeInvalidation
{
if (self.invalidationBlock != nil) {
self.invalidationBlock();
self.invalidationBlock = nil;
}
}
@end
@@ -1,13 +1,13 @@
//
// main.m
// RemoteMessagePort
// InstallerStatus
//
// Created by Mayur Pawashe on 4/3/16.
// Created by Mayur Pawashe on 7/10/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "SURemoteMessagePort.h"
#import "SUInstallerStatus.h"
@interface ServiceDelegate : NSObject <NSXPCListenerDelegate>
@end
@@ -18,13 +18,17 @@
// This method is where the NSXPCListener configures, accepts, and resumes a new incoming NSXPCConnection.
// Configure the connection.
newConnection.exportedInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SURemoteMessagePortProtocol)];
// First, set the interface that the exported object implements.
newConnection.exportedInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUInstallerStatusProtocol)];
newConnection.exportedObject = [[SURemoteMessagePort alloc] init];
// Next, set the object that the connection exports. All messages sent on the connection to this service will be sent to the exported object to handle. The connection retains the exported object.
SUInstallerStatus *exportedObject = [SUInstallerStatus new];
newConnection.exportedObject = exportedObject;
// Resuming the connection allows the system to deliver more incoming messages.
[newConnection resume];
// Returning YES from this method tells the system that you have accepted this connection. If you want to reject the connection for some reason, call -invalidate on the connection and return NO.
return YES;
}
File diff suppressed because it is too large. Load diff
+3 -1
View File
@@ -11,8 +11,10 @@
@interface AppInstaller : NSObject <SUUnarchiverDelegate>
- (instancetype)initWithHostBundleIdentifier:(NSString *)hostBundleIdentifier inheritsPrivileges:(BOOL)inheritsPrivileges;
- (instancetype)initWithHostBundleIdentifier:(NSString *)hostBundleIdentifier allowingInteraction:(BOOL)allowsInteraction;
- (void)start;
- (void)cleanupAndExitWithStatus:(int)status __attribute__((noreturn));
@end
+94 -145
View File
@@ -8,6 +8,7 @@
#import "AppInstaller.h"
#import "TerminationListener.h"
#import "StatusInfo.h"
#import "SUInstaller.h"
#import "SULog.h"
#import "SUHost.h"
@@ -15,8 +16,6 @@
#import "SUStandardVersionComparator.h"
#import "SUDSAVerifier.h"
#import "SUCodeSigningVerifier.h"
#import "SURemoteMessagePort.h"
#import "SULocalMessagePort.h"
#import "SUMessageTypes.h"
#import "SUSecureCoding.h"
#import "SUInstallationInputData.h"
@@ -27,6 +26,7 @@
#import "SUAuthorizationEnvironment.h"
#import "SUApplicationInfo.h"
#import "SUErrors.h"
#import "SUInstallerCommunicationProtocol.h"
/*!
* Terminate the application after a delay from launching the new update to avoid OS activation issues
@@ -42,19 +42,21 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.5;
*/
static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
@interface AppInstaller ()
@interface AppInstaller () <NSXPCListenerDelegate, SUInstallerCommunicationProtocol>
@property (nonatomic) NSXPCListener* xpcListener;
@property (nonatomic) NSXPCConnection *activeConnection;
@property (nonatomic) id<SUInstallerCommunicationProtocol> communicator;
@property (nonatomic) StatusInfo *statusInfo;
@property (nonatomic, strong) TerminationListener *terminationListener;
@property (nonatomic, readonly, copy) NSString *hostBundleIdentifier;
@property (nonatomic, readonly) BOOL inheritsPrivileges;
@property (nonatomic, readonly) BOOL allowsInteraction;
@property (nonatomic) SUHost *host;
@property (nonatomic) SULocalMessagePort *localPort;
@property (nonatomic) SURemoteMessagePort *remotePort;
@property (nonatomic) SUInstallationInputData *installationData;
@property (nonatomic, assign) BOOL shouldRelaunch;
@property (nonatomic, assign) BOOL shouldShowUI;
@property (nonatomic) NSData *installationInfoData;
@property (nonatomic) id<SUInstallerProtocol> installer;
@property (nonatomic) BOOL willCompleteInstallation;
@@ -68,16 +70,17 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
@implementation AppInstaller
@synthesize xpcListener = _xpcListener;
@synthesize activeConnection = _activeConnection;
@synthesize communicator = _communicator;
@synthesize statusInfo = _statusInfo;
@synthesize hostBundleIdentifier = _hostBundleIdentifier;
@synthesize inheritsPrivileges = _inheritsPrivileges;
@synthesize allowsInteraction = _allowsInteraction;
@synthesize terminationListener = _terminationListener;
@synthesize localPort = _localPort;
@synthesize remotePort = _remotePort;
@synthesize host = _host;
@synthesize installationData = _installationData;
@synthesize shouldRelaunch = _shouldRelaunch;
@synthesize shouldShowUI = _shouldShowUI;
@synthesize installationInfoData = _installationInfoData;
@synthesize installer = _installer;
@synthesize willCompleteInstallation = _willCompleteInstallation;
@synthesize installerQueue = _installerQueue;
@@ -85,7 +88,7 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
@synthesize performedStage2Installation = _performedStage2Installation;
@synthesize performedStage3Installation = _performedStage3Installation;
- (instancetype)initWithHostBundleIdentifier:(NSString *)hostBundleIdentifier inheritsPrivileges:(BOOL)inheritsPrivileges
- (instancetype)initWithHostBundleIdentifier:(NSString *)hostBundleIdentifier allowingInteraction:(BOOL)allowsInteraction
{
if (!(self = [super init])) {
return nil;
@@ -93,66 +96,63 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
_hostBundleIdentifier = [hostBundleIdentifier copy];
_inheritsPrivileges = inheritsPrivileges;
_allowsInteraction = allowsInteraction;
self.localPort = [[SULocalMessagePort alloc] init];
_xpcListener = [[NSXPCListener alloc] initWithMachServiceName:SUAutoUpdateServiceNameForBundleIdentifier(hostBundleIdentifier)];
_xpcListener.delegate = self;
[self.localPort setServiceName:SUAutoUpdateServiceNameForBundleIdentifier(hostBundleIdentifier)];
__weak AppInstaller *weakSelf = self;
[self.localPort setMessageCallback:^NSData * _Nullable(int32_t identifier, NSData * _Nonnull data) {
return [weakSelf handleMessageWithIdentifier:identifier data:data];
}];
[self.localPort setInvalidationCallback:^{
dispatch_async(dispatch_get_main_queue(), ^{
AppInstaller *strongSelf = weakSelf;
if (strongSelf.localPort != nil) {
[strongSelf cleanupAndExitWithStatus:EXIT_FAILURE];
}
});
}];
[self startRemotePortWithCompletion:^(BOOL success) {
if (!success) {
SULog(@"Failed creating remote message port from installer");
[self cleanupAndExitWithStatus:EXIT_FAILURE];
}
}];
_statusInfo = [[StatusInfo alloc] initWithHostBundleIdentifier:hostBundleIdentifier];
return self;
}
- (void)startRemotePortWithCompletion:(void (^)(BOOL))completionHandler
- (BOOL)listener:(NSXPCListener *)__unused listener shouldAcceptNewConnection:(NSXPCConnection *)newConnection
{
if (self.remotePort != nil) {
completionHandler(YES);
return;
SULog(@"Incoming connection: %@", newConnection);
if (self.activeConnection != nil) {
SULog(@"Rejecting multiple connections...");
[newConnection invalidate];
return NO;
}
self.remotePort = [[SURemoteMessagePort alloc] initWithServiceName:SUUpdateDriverServiceNameForBundleIdentifier(self.hostBundleIdentifier)];
self.activeConnection = newConnection;
newConnection.exportedInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUInstallerCommunicationProtocol)];
newConnection.exportedObject = self;
newConnection.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUInstallerCommunicationProtocol)];
__weak AppInstaller *weakSelf = self;
[self.remotePort connectWithLookupCompletion:^(BOOL success) {
newConnection.interruptionHandler = ^{
[weakSelf.activeConnection invalidate];
};
newConnection.invalidationHandler = ^{
dispatch_async(dispatch_get_main_queue(), ^{
completionHandler(success);
if (success) {
[weakSelf.remotePort setInvalidationHandler:^{
dispatch_async(dispatch_get_main_queue(), ^{
AppInstaller *strongSelf = weakSelf;
if (strongSelf != nil) {
if (strongSelf.remotePort != nil && !strongSelf.willCompleteInstallation) {
SULog(@"Invalidation on remote port being called, and installation is not close enough to completion!");
[strongSelf cleanupAndExitWithStatus:EXIT_FAILURE];
}
strongSelf.remotePort = nil;
}
});
}];
AppInstaller *strongSelf = weakSelf;
if (strongSelf != nil) {
if (strongSelf.activeConnection != nil && !strongSelf.willCompleteInstallation) {
SULog(@"Invalidation on remote port being called, and installation is not close enough to completion!");
[strongSelf cleanupAndExitWithStatus:EXIT_FAILURE];
}
strongSelf.communicator = nil;
strongSelf.activeConnection = nil;
}
});
}];
};
[newConnection resume];
self.communicator = newConnection.remoteObjectProxy;
return YES;
}
- (void)start
{
[self.xpcListener resume];
[self.statusInfo startListener];
}
/**
@@ -243,18 +243,6 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
return YES;
}
- (void)start
{
[self.remotePort sendMessageWithIdentifier:SURequestInstallationParameters data:[NSData data] completion:^(BOOL success) {
if (!success) {
dispatch_async(dispatch_get_main_queue(), ^{
SULog(@"Error: Failed to send request for installation parameters");
[self cleanupAndExitWithStatus:EXIT_FAILURE];
});
}
}];
}
- (void)extractAndInstallUpdate
{
NSString *downloadPath = [self.installationData.updateDirectoryPath stringByAppendingPathComponent:self.installationData.downloadName];
@@ -272,11 +260,8 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
if (sizeof(progress) == sizeof(uint64_t)) {
uint64_t progressValue = CFSwapInt64HostToLittle(*(uint64_t *)&progress);
NSData *data = [NSData dataWithBytes:&progressValue length:sizeof(progressValue)];
[self.remotePort sendMessageWithIdentifier:SUExtractedArchiveWithProgress data:data completion:^(BOOL success) {
if (!success) {
SULog(@"Error sending extracted progress");
}
}];
[self.communicator handleMessageWithIdentifier:SUExtractedArchiveWithProgress data:data];
}
}
@@ -286,20 +271,12 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
// Eg: one common case is if a delta update fails, client may want to fall back to regular update
self.installationData = nil;
[self.remotePort sendMessageWithIdentifier:SUArchiveExtractionFailed data:[NSData data] completion:^(BOOL success) {
if (!success) {
SULog(@"Error sending extraction failed");
}
}];
[self.communicator handleMessageWithIdentifier:SUArchiveExtractionFailed data:[NSData data]];
}
- (void)unarchiverDidFinish
{
[self.remotePort sendMessageWithIdentifier:SUValidationStarted data:[NSData data] completion:^(BOOL success) {
if (!success) {
SULog(@"Error sending validation finish");
}
}];
[self.communicator handleMessageWithIdentifier:SUValidationStarted data:[NSData data]];
NSString *downloadPath = [self.installationData.updateDirectoryPath stringByAppendingPathComponent:self.installationData.downloadName];
BOOL validationSuccess = [self validateUpdateForHost:self.host downloadedToPath:downloadPath extractedToPath:self.installationData.updateDirectoryPath DSASignature:self.installationData.dsaSignature];
@@ -308,20 +285,14 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
SULog(@"Error: update validation was a failure");
[self cleanupAndExitWithStatus:EXIT_FAILURE];
} else {
[self.remotePort sendMessageWithIdentifier:SUInstallationStartedStage1 data:[NSData data] completion:^(BOOL success) {
if (!success) {
SULog(@"Error sending stage 1 started");
}
}];
[self.communicator handleMessageWithIdentifier:SUInstallationStartedStage1 data:[NSData data]];
[self startInstallation];
}
}
- (NSData *)handleMessageWithIdentifier:(int32_t)identifier data:(NSData *)data
- (void)handleMessageWithIdentifier:(int32_t)identifier data:(NSData *)data
{
NSData *replyData = nil;
if (identifier == SUInstallationData && self.installationData == nil) {
dispatch_async(dispatch_get_main_queue(), ^{
SUInstallationInputData *installationData = (SUInstallationInputData *)SUUnarchiveRootObjectSecurely(data, [SUInstallationInputData class]);
@@ -357,16 +328,14 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
}
});
} else if (identifier == SUSentUpdateAppcastItemData) {
if (self.installationInfoData == nil) {
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.installationInfoData = SUArchiveRootObjectSecurely(installationInfo);
self.statusInfo.installationInfoData = SUArchiveRootObjectSecurely(installationInfo);
}
}
} else if (identifier == SUReceiveUpdateAppcastItemData) {
replyData = self.installationInfoData;
} else if (identifier == SUResumeInstallationToStage2 && data.length == sizeof(uint8_t) * 2) {
uint8_t relaunch = *((const uint8_t *)data.bytes);
uint8_t showsUI = *((const uint8_t *)data.bytes + 1);
@@ -378,26 +347,16 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
// Allow handling if we should relaunch at any time
self.shouldRelaunch = (BOOL)relaunch;
// We should try re-creating the remote port if necessary, in case the client has
// restarted since and wants a reply back when we say it's OK to terminate the app
[self startRemotePortWithCompletion:^(BOOL success) {
if (!success) {
SULog(@"Installer failed to set up remote port to updater before resuming installation");
dispatch_async(dispatch_get_main_queue(), ^{
if (self.performedStage1Installation) {
// Resume the installation if we aren't done with stage 2 yet, and remind the client we are prepared to relaunch
dispatch_async(self.installerQueue, ^{
[self performStage2InstallationIfNeeded];
});
}
dispatch_async(dispatch_get_main_queue(), ^{
if (self.performedStage1Installation) {
// Resume the installation if we aren't done with stage 2 yet, and remind the client we are prepared to relaunch
dispatch_async(self.installerQueue, ^{
[self performStage2InstallationIfNeeded];
});
}
});
}];
});
});
}
return replyData;
}
- (void)startInstallation
@@ -408,7 +367,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 inheritsPrivileges:self.inheritsPrivileges versionComparator:[SUStandardVersionComparator standardVersionComparator] error:&installerError];
id <SUInstallerProtocol> installer = [SUInstaller installerForHost:self.host 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);
@@ -441,12 +400,7 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
NSData *sendData = [NSData dataWithBytes:sendInformation length:sizeof(sendInformation)];
[self.remotePort sendMessageWithIdentifier:SUInstallationFinishedStage1 data:sendData completion:^(BOOL success) {
if (!success) {
SULog(@"Error sending stage 1 finish");
[self cleanupAndExitWithStatus:EXIT_FAILURE];
}
}];
[self.communicator handleMessageWithIdentifier:SUInstallationFinishedStage1 data:sendData];
self.performedStage1Installation = YES;
@@ -465,7 +419,7 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
SUAuthorizationEnvironment *environment = nil;
NSURL *tempIconDirectoryURL = nil;
if (self.shouldShowUI && !self.inheritsPrivileges && [self.installer mayNeedToRequestAuthorization]) {
if (self.shouldShowUI && self.allowsInteraction && [self.installer mayNeedToRequestAuthorization]) {
NSString *prompt = [NSString stringWithFormat:NSLocalizedString(@"%1$@ wants to update.", nil), self.host.name];
NSString *iconPath = nil;
@@ -505,7 +459,7 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
}
NSError *secondStageError = nil;
BOOL performedSecondStage = [self.installer performSecondStageAllowingAuthorization:!self.inheritsPrivileges fileOperationToolPath:fileOperationToolPath environment:environment allowingUI:self.shouldShowUI error:&secondStageError];
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];
@@ -535,15 +489,11 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
uint8_t sendInfo[] = {cancelled, targetTerminated};
NSData *sendData = [NSData dataWithBytes:sendInfo length:sizeof(sendInfo)];
[self.remotePort sendMessageWithIdentifier:SUInstallationFinishedStage2 data:sendData completion:^(BOOL success) {
if (!success) {
SULog(@"Error sending stage 2 finish");
}
if (installationCancelled) {
cleanupAndExit();
}
}];
[self.communicator handleMessageWithIdentifier:SUInstallationFinishedStage2 data:sendData];
if (installationCancelled) {
cleanupAndExit();
}
});
}
@@ -571,7 +521,7 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
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 (shouldLaunchInstallerProgress && self.remotePort == nil) {
if (shouldLaunchInstallerProgress && self.communicator == nil) {
NSError *launchError = nil;
NSArray *arguments = @[self.host.bundlePath];
@@ -615,17 +565,13 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
[installerProgressRunningApplication terminate];
shouldLaunchInstallerProgress = NO;
[self.remotePort sendMessageWithIdentifier:SUInstallationFinishedStage3 data:[NSData data] completion:^(BOOL success) {
if (!success) {
SULog(@"Error sending stage 3 finish");
}
}];
[self.communicator handleMessageWithIdentifier:SUInstallationFinishedStage3 data:[NSData data]];
// Invalidate the local port before re-launching the updated app
// 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.localPort invalidate];
self.localPort = nil;
[self.statusInfo invalidate];
self.statusInfo = nil;
NSString *installationPath = [SUInstaller installationPathForHost:self.host];
@@ -658,11 +604,14 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7;
{
// It's nice to tell the other end we're invalidating
[self.localPort invalidate];
self.localPort = nil;
[self.activeConnection invalidate];
self.activeConnection = nil;
[self.remotePort invalidate];
self.remotePort = nil;
[self.xpcListener invalidate];
self.xpcListener = nil;
[self.statusInfo invalidate];
self.statusInfo = nil;
NSError *theError = nil;
if (![[NSFileManager defaultManager] removeItemAtPath:self.installationData.updateDirectoryPath error:&theError]) {
+12 -2
View File
@@ -11,10 +11,20 @@ int main(int __unused argc, const char __unused *argv[])
}
NSString *hostBundleIdentifier = args[1];
BOOL inheritsPrivileges = args[2].boolValue;
BOOL allowsInteraction = args[2].boolValue;
AppInstaller *appInstaller = [[AppInstaller alloc] initWithHostBundleIdentifier:hostBundleIdentifier inheritsPrivileges:inheritsPrivileges];
AppInstaller *appInstaller = [[AppInstaller alloc] initWithHostBundleIdentifier:hostBundleIdentifier allowingInteraction:allowsInteraction];
[appInstaller start];
// 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, ^{
[appInstaller cleanupAndExitWithStatus:SIGTERM];
});
dispatch_resume(sigtermSource);
[[NSRunLoop currentRunLoop] run];
}
+10 -18
View File
@@ -18,34 +18,26 @@ extern NSString *SUAppcastItemArchiveKey;
typedef NS_ENUM(int32_t, SUInstallerMessageType)
{
SUInstallerNotStarted = 0,
SURequestInstallationParameters = 1,
SUExtractedArchiveWithProgress = 2,
SUArchiveExtractionFailed = 3,
SUValidationStarted = 4,
SUInstallationStartedStage1 = 5,
SUInstallationFinishedStage1 = 6,
SUInstallationFinishedStage2 = 7,
SUInstallationFinishedStage3 = 8
SUExtractedArchiveWithProgress = 1,
SUArchiveExtractionFailed = 2,
SUValidationStarted = 3,
SUInstallationStartedStage1 = 4,
SUInstallationFinishedStage1 = 5,
SUInstallationFinishedStage2 = 6,
SUInstallationFinishedStage3 = 7
};
typedef NS_ENUM(int32_t, SUUpdaterMessageType)
{
SUInstallationData = 0,
SUSentUpdateAppcastItemData = 1,
SUReceiveUpdateAppcastItemData = 2,
SUResumeInstallationToStage2 = 3
};
typedef NS_ENUM(int32_t, SUInstallStatusMessageType)
{
SUAppcastItemData = 0,
SUWaitingOnUpdateData = 1
SUResumeInstallationToStage2 = 2
};
BOOL SUInstallerMessageTypeIsLegal(SUInstallerMessageType oldMessageType, SUInstallerMessageType newMessageType);
NSString *SUUpdateDriverServiceNameForBundleIdentifier(NSString *bundleIdentifier);
NSString *SUAutoUpdateServiceNameForBundleIdentifier(NSString *bundleIdentifier);
NSString *SUStatusInfoServiceNameForBundleIdentifier(NSString *bundleIdentifier);
NS_ASSUME_NONNULL_END
+8 -11
View File
@@ -18,15 +18,12 @@ BOOL SUInstallerMessageTypeIsLegal(SUInstallerMessageType oldMessageType, SUInst
case SUInstallerNotStarted:
legal = (oldMessageType == SUInstallerNotStarted);
break;
case SURequestInstallationParameters:
legal = (oldMessageType == SUInstallerNotStarted);
break;
case SUExtractedArchiveWithProgress:
case SUArchiveExtractionFailed:
legal = (oldMessageType == SURequestInstallationParameters || oldMessageType == SUExtractedArchiveWithProgress);
legal = (oldMessageType == SUInstallerNotStarted || oldMessageType == SUExtractedArchiveWithProgress);
break;
case SUValidationStarted:
legal = (oldMessageType == SURequestInstallationParameters || oldMessageType == SUExtractedArchiveWithProgress);
legal = (oldMessageType == SUInstallerNotStarted || oldMessageType == SUExtractedArchiveWithProgress);
break;
case SUInstallationStartedStage1:
legal = (oldMessageType == SUValidationStarted);
@@ -44,12 +41,12 @@ BOOL SUInstallerMessageTypeIsLegal(SUInstallerMessageType oldMessageType, SUInst
return legal;
}
NSString *SUUpdateDriverServiceNameForBundleIdentifier(NSString *bundleIdentifier)
{
return [NSString stringWithFormat:@"%@-sparkle-updater", bundleIdentifier];
}
NSString *SUAutoUpdateServiceNameForBundleIdentifier(NSString *bundleIdentifier)
{
return [NSString stringWithFormat:@"%@-sparkle-installer", bundleIdentifier];
return [NSString stringWithFormat:@"%@-spkinstll", bundleIdentifier];
}
NSString *SUStatusInfoServiceNameForBundleIdentifier(NSString *bundleIdentifier)
{
return [NSString stringWithFormat:@"%@-spkstat", bundleIdentifier];
}
+21
View File
@@ -0,0 +1,21 @@
//
// SUStatusInfoProtocol.h
// Sparkle
//
// Created by Mayur Pawashe on 7/10/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@protocol SUStatusInfoProtocol
- (void)probeStatusInfoWithReply:(void (^)(NSData * _Nullable installationInfoData))reply;
- (void)probeStatusConnectivityWithReply:(void (^)(void))reply;
@end
NS_ASSUME_NONNULL_END
+26
View File
@@ -0,0 +1,26 @@
//
// StatusInfo.h
// Sparkle
//
// Created by Mayur Pawashe on 7/10/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "SUStatusInfoProtocol.h"
NS_ASSUME_NONNULL_BEGIN
@interface StatusInfo : NSObject <SUStatusInfoProtocol>
- (instancetype)initWithHostBundleIdentifier:(NSString *)bundleIdentifier;
@property (nonatomic, nullable) NSData *installationInfoData;
- (void)startListener;
- (void)invalidate;
@end
NS_ASSUME_NONNULL_END
+67
View File
@@ -0,0 +1,67 @@
//
// StatusInfo.m
// Sparkle
//
// Created by Mayur Pawashe on 7/10/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import "StatusInfo.h"
#import "SUMessageTypes.h"
#import "SULog.h"
@interface StatusInfo () <NSXPCListenerDelegate>
@property (nonatomic) NSXPCListener *xpcListener;
@end
@implementation StatusInfo
@synthesize xpcListener = _xpcListener;
@synthesize installationInfoData = _installationInfoData;
- (instancetype)initWithHostBundleIdentifier:(NSString *)bundleIdentifier
{
self = [super init];
if (self != nil) {
_xpcListener = [[NSXPCListener alloc] initWithMachServiceName:SUStatusInfoServiceNameForBundleIdentifier(bundleIdentifier)];
_xpcListener.delegate = self;
}
return self;
}
- (void)startListener
{
[self.xpcListener resume];
}
- (void)invalidate
{
[self.xpcListener invalidate];
self.xpcListener = nil;
}
- (BOOL)listener:(NSXPCListener *)__unused listener shouldAcceptNewConnection:(NSXPCConnection *)newConnection
{
newConnection.exportedInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUStatusInfoProtocol)];
newConnection.exportedObject = self;
[newConnection resume];
return YES;
}
- (void)probeStatusInfoWithReply:(void (^)(NSData * _Nullable))reply
{
dispatch_async(dispatch_get_main_queue(), ^{
reply(self.installationInfoData);
});
}
- (void)probeStatusConnectivityWithReply:(void (^)(void))reply
{
reply();
}
@end
+1 -1
View File
@@ -12,7 +12,7 @@ NS_ASSUME_NONNULL_BEGIN
@protocol InstallerProgressAppControllerDelegate;
@interface InstallerProgressAppController : NSObject
@interface InstallerProgressAppController : NSObject <NSApplicationDelegate>
- (instancetype)initWithApplication:(NSApplication *)application arguments:(NSArray<NSString *> *)arguments delegate:(id<InstallerProgressAppControllerDelegate>)delegate;
+16 -20
View File
@@ -8,7 +8,7 @@
#import "InstallerProgressAppController.h"
#import "InstallerProgressAppControllerDelegate.h"
#import "SURemoteMessagePort.h"
#import "SUInstallerStatus.h"
#import "SUMessageTypes.h"
#import "SULog.h"
#import "SUApplicationInfo.h"
@@ -25,7 +25,7 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.3;
@property (nonatomic, readonly) NSApplication *application;
@property (nonatomic, readonly) NSBundle *bundle;
@property (nonatomic, readonly, weak) id<InstallerProgressAppControllerDelegate> delegate;
@property (nonatomic, readonly) SURemoteMessagePort *remotePort;
@property (nonatomic, readonly) id<SUInstallerStatusProtocol> statusInfo;
@end
@@ -34,7 +34,7 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.3;
@synthesize application = _application;
@synthesize bundle = _bundle;
@synthesize delegate = _delegate;
@synthesize remotePort = _remotePort;
@synthesize statusInfo = _statusInfo;
- (instancetype)initWithApplication:(NSApplication *)application arguments:(NSArray<NSString *> *)arguments delegate:(id<InstallerProgressAppControllerDelegate>)delegate
{
@@ -64,7 +64,15 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.3;
_application = application;
_delegate = delegate;
_bundle = bundle;
_remotePort = [[SURemoteMessagePort alloc] initWithServiceName:SUAutoUpdateServiceNameForBundleIdentifier(bundleIdentifier)];
_statusInfo = [[SUInstallerStatus alloc] init];
[_statusInfo setInvalidationHandler:^{
dispatch_async(dispatch_get_main_queue(), ^{
[application terminate:nil];
});
}];
[_statusInfo setServiceName:SUStatusInfoServiceNameForBundleIdentifier(bundleIdentifier)];
}
return self;
}
@@ -76,22 +84,10 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.3;
- (void)applicationDidFinishLaunching:(NSNotification *)__unused notification
{
__weak InstallerProgressAppController *weakSelf = self;
[self.remotePort connectWithLookupCompletion:^(BOOL success) {
if (!success) {
[NSApp terminate:nil];
} else {
[weakSelf.remotePort setInvalidationHandler:^{
[weakSelf.application terminate:nil];
}];
dispatch_async(dispatch_get_main_queue(), ^{
InstallerProgressAppController *strongSelf = weakSelf;
if (strongSelf != nil) {
[strongSelf.delegate applicationDidFinishLaunchingWithTargetBundle:strongSelf.bundle];
}
});
}
[self.statusInfo probeStatusConnectivityWithReply:^{
dispatch_async(dispatch_get_main_queue(), ^{
[self.delegate applicationDidFinishLaunchingWithTargetBundle:self.bundle];
});
}];
}
+7 -3
View File
@@ -53,7 +53,7 @@
}
// If we're root, we can allow using the authorization APIs
self.fileManager = (allowsAuthorization || (geteuid() == 0)) ? [SUFileManager fileManagerWithAuthorizationToolPath:fileOperationToolPath environment:authorizationEnvironment] : [SUFileManager defaultManager];
self.fileManager = (allowsAuthorization || [self isRootUser]) ? [SUFileManager fileManagerWithAuthorizationToolPath:fileOperationToolPath environment:authorizationEnvironment] : [SUFileManager defaultManager];
return [self.fileManager grantAuthorizationPrivilegesWithError:error];
}
@@ -68,10 +68,14 @@
return NO;
}
- (BOOL)isRootUser
{
return (geteuid() == 0);
}
- (BOOL)canInstallSilently
{
// Are we root?
return (geteuid() == 0);
return [self isRootUser];
}
- (BOOL)mayNeedToRequestAuthorization
+1 -1
View File
@@ -16,7 +16,7 @@ NS_ASSUME_NONNULL_BEGIN
@interface SUInstaller : NSObject
+ (nullable id<SUInstallerProtocol>)installerForHost:(SUHost *)host updateDirectory:(NSString *)updateDirectory inheritsPrivileges:(BOOL)inheritsPrivileges versionComparator:(id <SUVersionComparison>)comparator error:(NSError **)error;
+ (nullable id<SUInstallerProtocol>)installerForHost:(SUHost *)host 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;
+4 -4
View File
@@ -112,7 +112,7 @@
return newAppDownloadPath;
}
+ (nullable id<SUInstallerProtocol>)installerForHost:(SUHost *)host updateDirectory:(NSString *)updateDirectory inheritsPrivileges:(BOOL)inheritsPrivileges versionComparator:(id <SUVersionComparison>)comparator error:(NSError * __autoreleasing *)error
+ (nullable id<SUInstallerProtocol>)installerForHost:(SUHost *)host updateDirectory:(NSString *)updateDirectory allowingInteraction:(BOOL)allowsInteraction versionComparator:(id <SUVersionComparison>)comparator error:(NSError * __autoreleasing *)error
{
BOOL isPackage = NO;
BOOL isGuided = NO;
@@ -125,10 +125,10 @@
return nil;
}
// If the installer inherits privileges, it could be running as root
// If it's running as root, using a non-guided package installer does not work properly so avoid it at all costs
// 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
id <SUInstallerProtocol> installer = nil;
if (isPackage && (isGuided || inheritsPrivileges)) {
if (isPackage && (isGuided || !allowsInteraction)) {
installer = [[SUGuidedPackageInstaller alloc] initWithPackagePath:newDownloadPath];
} else if (isPackage) {
installer = [[SUPackageInstaller alloc] initWithPackagePath:newDownloadPath];
+59 -178
View File
@@ -9,13 +9,7 @@
#import "SUInstallerDriver.h"
#import "SULog.h"
#import "SUMessageTypes.h"
#import "SULocalMessagePort.h"
#import "SUXPCLocalMessagePort.h"
#import "SULocalMessagePortDelegate.h"
#import "SURemoteMessagePort.h"
#import "SUXPCRemoteMessagePort.h"
#import "SUXPCServiceInfo.h"
#import "SURemoteMessagePortProtocol.h"
#import "SUUpdaterDelegate.h"
#import "SUAppcastItem.h"
#import "SULog.h"
@@ -27,12 +21,15 @@
#import "SUInstallationInputData.h"
#import "SUInstallerLauncher.h"
#import "SUXPCServiceInfo.h"
#import "SUInstallerConnection.h"
#import "SUInstallerConnectionProtocol.h"
#import "SUXPCInstallerConnection.h"
#ifdef _APPKITDEFINES_H
#error This is a "core" class and should NOT import AppKit
#endif
@interface SUInstallerDriver () <SULocalMessagePortDelegate>
@interface SUInstallerDriver () <SUInstallerCommunicationProtocol>
@property (nonatomic, readonly) SUHost *host;
@property (nonatomic, readonly, copy) NSString *cachePath;
@@ -40,8 +37,9 @@
@property (nonatomic, weak, readonly) id<SUInstallerDriverDelegate> delegate;
@property (nonatomic) SUInstallerMessageType currentStage;
@property (nonatomic) BOOL startedInstalling;
@property (nonatomic) id<SULocalMessagePortProtocol> localPort;
@property (nonatomic) id <SURemoteMessagePortProtocol> remotePort;
@property (nonatomic) id<SUInstallerConnectionProtocol> installerConnection;
@property (nonatomic) BOOL postponedOnce;
@property (nonatomic, weak, readonly) id updater;
@property (nonatomic, weak, readonly) id<SUUpdaterDelegate> updaterDelegate;
@@ -61,8 +59,7 @@
@synthesize delegate = _delegate;
@synthesize currentStage = _currentStage;
@synthesize startedInstalling = _startedInstalling;
@synthesize localPort = _localPort;
@synthesize remotePort = _remotePort;
@synthesize installerConnection = _installerConnection;
@synthesize postponedOnce = _postponedOnce;
@synthesize updater = _updater;
@synthesize updaterDelegate = _updaterDelegate;
@@ -85,102 +82,45 @@
return self;
}
- (void)localMessagePortReceivedMessageWithIdentifier:(int32_t)identifier data:(NSData *)data
- (void)setUpConnection
{
dispatch_async(dispatch_get_main_queue(), ^{
[self handleMessageWithIdentifier:identifier data:data];
});
}
- (void)setUpLocalPort
{
if (self.localPort != nil) {
if (self.installerConnection != nil) {
return;
}
NSString *hostBundleIdentifier = self.host.bundle.bundleIdentifier;
assert(hostBundleIdentifier != nil);
__weak SUInstallerDriver *weakSelf = self;
if (SUXPCServiceExists(@LOCAL_MESSAGE_PORT_PRODUCT_NAME)) {
self.localPort = [[SUXPCLocalMessagePort alloc] initWithDelegate:self];
if (!SUXPCServiceExists(@INSTALLER_CONNECTION_PRODUCT_NAME)) {
self.installerConnection = [[SUInstallerConnection alloc] initWithDelegate:self];
} else {
self.localPort = [[SULocalMessagePort alloc] initWithDelegate:self];
self.installerConnection = [[SUXPCInstallerConnection alloc] initWithDelegate:self];
}
[self.localPort setServiceName:SUUpdateDriverServiceNameForBundleIdentifier(hostBundleIdentifier)];
[self.localPort setInvalidationCallback:^{
__weak SUInstallerDriver *weakSelf = self;
[self.installerConnection setInvalidationHandler:^{
dispatch_async(dispatch_get_main_queue(), ^{
SUInstallerDriver *strongSelf = weakSelf;
if (strongSelf.localPort != nil) {
NSError *invalidationError =
if (strongSelf.installerConnection != nil) {
NSError *remoteError =
[NSError
errorWithDomain:SUSparkleErrorDomain
code:SUInstallationError
userInfo:@{
NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while running the updater. Please try again later.", nil),
NSLocalizedFailureReasonErrorKey:@"The local port connection from the updater was invalidated"
NSLocalizedFailureReasonErrorKey:@"The remote port connection was invalidated from the updater"
}
];
[strongSelf.delegate installerIsRequestingAbortInstallWithError:invalidationError];
[strongSelf.delegate installerIsRequestingAbortInstallWithError:remoteError];
}
});
}];
}
- (void)setUpRemotePortWithCompletion:(void (^)(BOOL))completionHandler
{
if (self.remotePort != nil) {
completionHandler(YES);
return;
}
NSString *hostBundleIdentifier = self.host.bundle.bundleIdentifier;
assert(hostBundleIdentifier != nil);
NSString *serviceName = SUAutoUpdateServiceNameForBundleIdentifier(hostBundleIdentifier);
if (!SUXPCServiceExists(@REMOTE_MESSAGE_PORT_PRODUCT_NAME)) {
self.remotePort = [[SURemoteMessagePort alloc] initWithServiceName:serviceName];
} else {
self.remotePort = [[SUXPCRemoteMessagePort alloc] initWithServiceName:serviceName];
}
__weak SUInstallerDriver *weakSelf = self;
[self.installerConnection setServiceName:serviceName];
[self.remotePort connectWithLookupCompletion:^(BOOL lookupSuccess) {
dispatch_async(dispatch_get_main_queue(), ^{
completionHandler(lookupSuccess);
if (lookupSuccess) {
[weakSelf.remotePort setInvalidationHandler:^{
dispatch_async(dispatch_get_main_queue(), ^{
SUInstallerDriver *strongSelf = weakSelf;
if (strongSelf.remotePort != nil) {
NSError *remoteError =
[NSError
errorWithDomain:SUSparkleErrorDomain
code:SUInstallationError
userInfo:@{
NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while running the updater. Please try again later.", nil),
NSLocalizedFailureReasonErrorKey:@"The remote port connection was invalidated from the updater"
}
];
[strongSelf.delegate installerIsRequestingAbortInstallWithError:remoteError];
}
});
}];
}
});
}];
}
- (void)launchInstallToolWithCompletion:(void (^)(NSError * _Nullable ))completionHandler
{
[self setUpLocalPort];
[self launchAutoUpdateWithCompletion:completionHandler];
[self sendInstallationData];
}
// This can be called multiple times (eg: if a delta update fails, this may be called again with a regular update item)
@@ -192,8 +132,8 @@
self.currentStage = SUInstallerNotStarted;
if (self.localPort == nil) {
[self launchInstallToolWithCompletion:completionHandler];
if (self.installerConnection == nil) {
[self launchAutoUpdateWithCompletion:completionHandler];
} else {
// The Install tool is already alive; just send out installation input data again
[self sendInstallationData];
@@ -239,49 +179,26 @@
return;
}
__weak SUInstallerDriver *weakSelf = self;
[self setUpRemotePortWithCompletion:^(BOOL setupSuccess) {
SUInstallerDriver *strongSelf = weakSelf;
if (strongSelf == nil) {
return;
}
if (!setupSuccess) {
NSError *remoteError =
[NSError
errorWithDomain:SUSparkleErrorDomain
code:SUInstallationError
userInfo:@{
NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while running the updater. Please try again later.", nil),
NSLocalizedFailureReasonErrorKey:@"The remote port connection failed being created"
}
];
[strongSelf.delegate installerIsRequestingAbortInstallWithError:remoteError];
} else {
[strongSelf.remotePort sendMessageWithIdentifier:SUInstallationData data:archivedData completion:^(BOOL success) {
if (!success) {
dispatch_async(dispatch_get_main_queue(), ^{
[weakSelf.delegate installerIsRequestingAbortInstallWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey:SULocalizedString(@"An error occurred while starting the installer parameters. Please try again later.", nil) }]];
});
}
}];
strongSelf.currentStage = SURequestInstallationParameters;
}
}];
[self.installerConnection handleMessageWithIdentifier:SUInstallationData data:archivedData];
self.currentStage = SUInstallerNotStarted;
}
- (void)handleMessageWithIdentifier:(int32_t)identifier data:(NSData *)data
{
dispatch_async(dispatch_get_main_queue(), ^{
[self _handleMessageWithIdentifier:identifier data:data];
});
}
- (void)_handleMessageWithIdentifier:(int32_t)identifier data:(NSData *)data
{
if (!SUInstallerMessageTypeIsLegal(self.currentStage, identifier)) {
SULog(@"Error: received out of order message with current stage: %d, requested stage: %d", self.currentStage, identifier);
return;
}
if (identifier == SURequestInstallationParameters) {
[self sendInstallationData];
} else if (identifier == SUExtractedArchiveWithProgress) {
if (identifier == SUExtractedArchiveWithProgress) {
if (data.length == sizeof(double) && sizeof(double) == sizeof(uint64_t)) {
uint64_t progressValue = CFSwapInt64LittleToHost(*(const uint64_t *)data.bytes);
double progress = *(double *)&progressValue;
@@ -311,11 +228,7 @@
NSData *updateItemData = SUArchiveRootObjectSecurely(self.updateItem);
if (updateItemData != nil) {
[self.remotePort sendMessageWithIdentifier:SUSentUpdateAppcastItemData data:updateItemData completion:^(BOOL success) {
if (!success) {
SULog(@"Error: Failed to send update appcast item to installer");
}
}];
[self.installerConnection handleMessageWithIdentifier:SUSentUpdateAppcastItemData data:updateItemData];
} else {
SULog(@"Error: Archived data to send for appcast item is nil");
}
@@ -362,11 +275,8 @@
} else if (identifier == SUInstallationFinishedStage3) {
self.currentStage = identifier;
[self.remotePort invalidate];
self.remotePort = nil;
[self.localPort invalidate];
self.localPort = nil;
[self.installerConnection invalidate];
self.installerConnection = nil;
[self.delegate installerDidFinishInstallation];
[self.delegate installerIsRequestingAbortInstallWithError:nil];
@@ -501,12 +411,12 @@
installerLauncher = launcherConnection.remoteObjectProxy;
}
BOOL shouldInheritPrivileges = NO;
if ([self.updaterDelegate respondsToSelector:@selector(updaterShouldInheritInstallPrivileges:)]) {
shouldInheritPrivileges = [self.updaterDelegate updaterShouldInheritInstallPrivileges:self.updater];
BOOL shouldAllowInstallerInteraction = NO;
if ([self.updaterDelegate respondsToSelector:@selector(updaterShouldAllowInstallerInteraction:)]) {
shouldAllowInstallerInteraction = [self.updaterDelegate updaterShouldAllowInstallerInteraction:self.updater];
}
[installerLauncher launchInstallerAtPath:relaunchToolPath withHostBundleIdentifier:hostBundleIdentifier inheritingPrivileges:shouldInheritPrivileges completion:^(BOOL success) {
[installerLauncher launchInstallerAtPath:relaunchToolPath withHostBundleIdentifier:hostBundleIdentifier allowingInteraction:shouldAllowInstallerInteraction completion:^(BOOL success) {
dispatch_async(dispatch_get_main_queue(), ^{
retrievedLaunchStatus = YES;
[launcherConnection invalidate];
@@ -517,6 +427,8 @@
completionHandler(error);
} else {
[self setUpConnection];
completionHandler(nil);
}
});
@@ -570,58 +482,27 @@
}
}
// Set up local and remote ports to the installer if they are not set up already
[self setUpLocalPort];
// Set up connection to the installer if one is not set up already
[self setUpConnection];
__weak SUInstallerDriver *weakSelf = self;
[self setUpRemotePortWithCompletion:^(BOOL setupSuccess) {
SUInstallerDriver *strongSelf = weakSelf;
if (strongSelf == nil) {
return;
}
if (!setupSuccess) {
[strongSelf.delegate installerIsRequestingAbortInstallWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey:SULocalizedString(@"An error occurred while starting the remote port for the installer. Please try again later.", nil) }]];
} else {
// For resumability, we'll assume we are far enough for the installation to continue
strongSelf.currentStage = SUInstallationFinishedStage1;
strongSelf.willRelaunch = relaunch;
uint8_t response[2] = {(uint8_t)relaunch, (uint8_t)showUI};
NSData *responseData = [NSData dataWithBytes:response length:sizeof(response)];
[strongSelf.remotePort sendMessageWithIdentifier:SUResumeInstallationToStage2 data:responseData completion:^(BOOL success) {
if (!success) {
dispatch_async(dispatch_get_main_queue(), ^{
NSError *remoteError =
[NSError
errorWithDomain:SUSparkleErrorDomain
code:SUInstallationError
userInfo:@{
NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while running the updater. Please try again later.", nil),
NSLocalizedFailureReasonErrorKey:@"The remote port connection failed to send resume install message"
}
];
[weakSelf.delegate installerIsRequestingAbortInstallWithError:remoteError];
});
}
// otherwise we'll terminate later when the installer tells us stage 2 is done
}];
}
}];
// For resumability, we'll assume we are far enough for the installation to continue
self.currentStage = SUInstallationFinishedStage1;
self.willRelaunch = relaunch;
uint8_t response[2] = {(uint8_t)relaunch, (uint8_t)showUI};
NSData *responseData = [NSData dataWithBytes:response length:sizeof(response)];
[self.installerConnection handleMessageWithIdentifier:SUResumeInstallationToStage2 data:responseData];
// we'll terminate later when the installer tells us stage 2 is done
}
- (void)abortInstall
{
if (self.localPort != nil) {
[self.localPort invalidate];
self.localPort = nil;
}
if (self.remotePort != nil) {
[self.remotePort invalidate];
self.remotePort = nil;
if (self.installerConnection != nil) {
[self.installerConnection invalidate];
self.installerConnection = nil;
}
}
-27
View File
@@ -1,27 +0,0 @@
//
// SULocalMessagePort.h
// Sparkle
//
// Created by Mayur Pawashe on 3/9/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "SULocalMessagePortProtocol.h"
#import "SULocalMessagePortDelegate.h"
NS_ASSUME_NONNULL_BEGIN
@interface SULocalMessagePort : NSObject <SULocalMessagePortProtocol>
- (instancetype)init;
// Due to XPC reasons, this delegate is strongly referenced. Make sure to -invalidate when done with this instance.
- (instancetype)initWithDelegate:(id<SULocalMessagePortDelegate>)delegate;
// messageCallback may be invoked on non-main thread
- (void)setMessageCallback:(NSData * _Nullable(^)(int32_t identifier, NSData *data))messageCallback;
@end
NS_ASSUME_NONNULL_END
-177
View File
@@ -1,177 +0,0 @@
//
// SULocalMessagePort.m
// Sparkle
//
// Created by Mayur Pawashe on 3/9/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import "SULocalMessagePort.h"
static NSString *SULocalServiceLookupReason = @"Local Service Connection";
@interface SULocalMessagePort ()
@property (nonatomic) CFMessagePortRef messagePort;
@property (nonatomic, nullable) id<SULocalMessagePortDelegate> delegate;
@property (nonatomic, copy) NSData * _Nullable(^messageHandler)(int32_t, NSData *);
@property (nonatomic, copy) void (^invalidationBlock)(void);
@property (nonatomic, readonly) dispatch_queue_t messageQueue;
@property (nonatomic) BOOL disabledAutomaticTermination;
@end
@implementation SULocalMessagePort
@synthesize messagePort = _messagePort;
@synthesize delegate = _delegate;
@synthesize messageHandler = _messageHandler;
@synthesize invalidationBlock = _invalidationBlock;
@synthesize messageQueue = _messageQueue;
@synthesize disabledAutomaticTermination = _disabledAutomaticTermination;
- (instancetype)init
{
self = [super init];
if (self != nil) {
_messageQueue = dispatch_queue_create("org.sparkle-project.sparkle-local-port", DISPATCH_QUEUE_SERIAL);
// If we are a XPC service, protect it from being terminated until the invalidation handler is set
_disabledAutomaticTermination = YES;
[[NSProcessInfo processInfo] disableAutomaticTermination:SULocalServiceLookupReason];
}
return self;
}
- (instancetype)initWithDelegate:(id<SULocalMessagePortDelegate>)delegate
{
self = [self init];
if (self != nil) {
_delegate = delegate;
}
return self;
}
- (void)dealloc
{
[self enableAutomaticTermination];
}
- (void)setServiceName:(NSString *)serviceName
{
assert(self.messagePort == NULL);
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wcast-qual"
CFMessagePortContext context = {.version = 0, .info = (void *)CFBridgingRetain(self), .retain = NULL, .release = NULL, .copyDescription = NULL};
#pragma clang diagnostic pop
CFMessagePortRef messagePort = CFMessagePortCreateLocal(kCFAllocatorDefault, (CFStringRef)serviceName, messagePortCallback, &context, NULL);
if (messagePort == NULL) {
CFRelease((__bridge CFTypeRef)(self));
self.messageHandler = nil;
[self removeDelegate];
[self enableAutomaticTermination];
} else {
self.messagePort = messagePort;
CFMessagePortSetDispatchQueue(messagePort, self.messageQueue);
}
}
- (void)setMessageCallback:(NSData * _Nullable(^)(int32_t identifier, NSData *data))messageCallback
{
self.messageHandler = messageCallback;
}
- (void)enableAutomaticTermination
{
if (self.disabledAutomaticTermination) {
[[NSProcessInfo processInfo] enableAutomaticTermination:SULocalServiceLookupReason];
self.disabledAutomaticTermination = NO;
}
}
- (void)setInvalidationCallback:(void (^)(void))invalidationCallback
{
// We can disable automatic termination now because we will be protected by the invalidationHandler (if this is a XPC service)
[self enableAutomaticTermination];
if (self.messagePort == NULL) {
invalidationCallback();
} else {
self.invalidationBlock = [invalidationCallback copy];
CFMessagePortSetInvalidationCallBack(self.messagePort, messageInvalidationCallback);
}
}
- (void)invalidate
{
dispatch_async(self.messageQueue, ^{
if (self.invalidationBlock != nil) {
self.invalidationBlock = nil;
CFMessagePortInvalidate(self.messagePort);
} else {
[self removeDelegate];
}
});
}
- (void)removeDelegate
{
// Remove our delegate right away but make sure it is released on main thread
__block id<SULocalMessagePortDelegate> delegate = self.delegate;
if (delegate != nil) {
self.delegate = nil;
dispatch_async(dispatch_get_main_queue(), ^{
delegate = nil;
});
}
}
// Called on non-main thread
static CFDataRef messagePortCallback(CFMessagePortRef __unused messagePort, SInt32 messageID, CFDataRef dataRef, void *info)
{
@autoreleasepool {
SULocalMessagePort *self = (__bridge SULocalMessagePort *)info;
// Create a copy that we can safely pass it asynchronously
// Warning: Do not use a convenience -[NSData copy] or an equivalent call. This crashes, and ASAN will let you know it crashes
// Most likely because the bytes are set to be freed internally, and not deep copied or something
NSData *data = [NSData dataWithBytes:CFDataGetBytePtr(dataRef) length:(NSUInteger)CFDataGetLength(dataRef)];
NSData *replyData = nil;
if (self.delegate != nil) {
[self.delegate localMessagePortReceivedMessageWithIdentifier:messageID data:data];
} else if (self.messageHandler != nil) {
replyData = self.messageHandler(messageID, data);
}
return (CFDataRef)CFBridgingRetain(replyData);
}
}
// Called on non-main thread
static void messageInvalidationCallback(CFMessagePortRef messagePort, void *info)
{
@autoreleasepool {
SULocalMessagePort *self = (__bridge SULocalMessagePort *)info;
dispatch_async(self.messageQueue, ^{
[self removeDelegate];
// note that messageHandler is deallocated on same queue that we're receiving messages from, which is good
self.messageHandler = nil;
if (self.invalidationBlock != nil) {
self.invalidationBlock();
self.invalidationBlock = nil;
}
self.messagePort = NULL;
CFRelease(messagePort);
CFRelease((__bridge CFTypeRef)(self));
});
}
}
@end
-21
View File
@@ -1,21 +0,0 @@
//
// SULocalMessagePortDelegate.h
// Sparkle
//
// Created by Mayur Pawashe on 6/15/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@protocol SULocalMessagePortDelegate <NSObject>
// Note: this method may not be called on the main thread
// Due to XPC/asynchronous reasons, this cannot return any reply data back
- (void)localMessagePortReceivedMessageWithIdentifier:(int32_t)identifier data:(NSData *)data;
@end
NS_ASSUME_NONNULL_END
-23
View File
@@ -1,23 +0,0 @@
//
// SULocalMessagePortProtocol.h
// Sparkle
//
// Created by Mayur Pawashe on 6/14/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@protocol SULocalMessagePortProtocol <NSObject>
- (void)setServiceName:(NSString *)serviceName;
- (void)setInvalidationCallback:(void (^)(void))invalidationCallback;
- (void)invalidate;
@end
NS_ASSUME_NONNULL_END
+83 -40
View File
@@ -7,15 +7,18 @@
//
#import "SUProbeInstallStatus.h"
#import "SULocalMessagePort.h"
#import "SURemoteMessagePort.h"
#import "SUXPCRemoteMessagePort.h"
#import "SUXPCServiceInfo.h"
#import "SURemoteMessagePortProtocol.h"
#import "SUHost.h"
#import "SUMessageTypes.h"
#import "SUInstallationInfo.h"
#import "SUSecureCoding.h"
#import "SUInstallerStatus.h"
#import "SUXPCInstallerStatus.h"
#import "SULog.h"
// This timeout is if probing the installer takes too long
// It should be at least more than 1 second since a probe can take around that much time
#define PROBE_TIMEOUT 7
@implementation SUProbeInstallStatus
@@ -24,20 +27,45 @@
NSString *hostBundleIdentifier = host.bundle.bundleIdentifier;
assert(hostBundleIdentifier != nil);
id <SURemoteMessagePortProtocol> remotePort = nil;
NSString *serviceName = SUAutoUpdateServiceNameForBundleIdentifier(hostBundleIdentifier);
if (!SUXPCServiceExists(@REMOTE_MESSAGE_PORT_PRODUCT_NAME)) {
remotePort = [[SURemoteMessagePort alloc] initWithServiceName:serviceName];
id<SUInstallerStatusProtocol> installerStatus = nil;
if (!SUXPCServiceExists(@INSTALLER_STATUS_PRODUCT_NAME)) {
installerStatus = [[SUInstallerStatus alloc] init];
} else {
remotePort = [[SUXPCRemoteMessagePort alloc] initWithServiceName:serviceName];
installerStatus = [[SUXPCInstallerStatus alloc] init];
}
[remotePort connectWithLookupCompletion:^(BOOL success) {
if (success) {
[remotePort invalidate];
}
completionHandler(success);
__block BOOL handledCompletion = NO;
[installerStatus setInvalidationHandler:^{
dispatch_async(dispatch_get_main_queue(), ^{
if (!handledCompletion) {
completionHandler(NO);
handledCompletion = YES;
}
});
}];
NSString *serviceName = SUStatusInfoServiceNameForBundleIdentifier(hostBundleIdentifier);
[installerStatus setServiceName:serviceName];
[installerStatus probeStatusConnectivityWithReply:^{
dispatch_async(dispatch_get_main_queue(), ^{
if (!handledCompletion) {
completionHandler(YES);
handledCompletion = YES;
}
});
[installerStatus invalidate];
}];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(PROBE_TIMEOUT * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
if (!handledCompletion) {
SULog(@"Timed out while probing installer progress");
completionHandler(NO);
handledCompletion = YES;
}
[installerStatus invalidate];
});
}
+ (void)probeInstallerUpdateItemForHost:(SUHost *)host completion:(void (^)(SUInstallationInfo * _Nullable))completionHandler
@@ -45,36 +73,51 @@
NSString *hostBundleIdentifier = host.bundle.bundleIdentifier;
assert(hostBundleIdentifier != nil);
id <SURemoteMessagePortProtocol> remotePort = nil;
NSString *serviceName = SUAutoUpdateServiceNameForBundleIdentifier(hostBundleIdentifier);
if (!SUXPCServiceExists(@REMOTE_MESSAGE_PORT_PRODUCT_NAME)) {
remotePort = [[SURemoteMessagePort alloc] initWithServiceName:serviceName];
id<SUInstallerStatusProtocol> installerStatus = nil;
if (!SUXPCServiceExists(@INSTALLER_STATUS_PRODUCT_NAME)) {
installerStatus = [[SUInstallerStatus alloc] init];
} else {
remotePort = [[SUXPCRemoteMessagePort alloc] initWithServiceName:serviceName];
installerStatus = [[SUXPCInstallerStatus alloc] init];
}
[remotePort connectWithLookupCompletion:^(BOOL lookupSuccess) {
if (!lookupSuccess) {
completionHandler(nil);
} else {
[remotePort sendMessageWithIdentifier:SUReceiveUpdateAppcastItemData data:[NSData data] reply:^(BOOL success, NSData * _Nullable replyData) {
[remotePort invalidate];
if (!success || replyData == nil) {
completionHandler(nil);
} else {
NSData *nonNullReplyData = replyData;
SUInstallationInfo *installationInfo = (SUInstallationInfo *)SUUnarchiveRootObjectSecurely(nonNullReplyData, [SUInstallationInfo class]);
if (installationInfo != nil) {
completionHandler(installationInfo);
} else {
completionHandler(nil);
}
}
}];
}
__block BOOL handledCompletion = NO;
[installerStatus setInvalidationHandler:^{
dispatch_async(dispatch_get_main_queue(), ^{
if (!handledCompletion) {
completionHandler(nil);
handledCompletion = YES;
}
});
}];
NSString *serviceName = SUStatusInfoServiceNameForBundleIdentifier(hostBundleIdentifier);
[installerStatus setServiceName:serviceName];
[installerStatus probeStatusInfoWithReply:^(NSData * _Nullable installationInfoData) {
SUInstallationInfo *installationInfo = nil;
if (installationInfoData != nil) {
installationInfo = (SUInstallationInfo *)SUUnarchiveRootObjectSecurely((NSData * _Nonnull)installationInfoData, [SUInstallationInfo class]);
}
dispatch_async(dispatch_get_main_queue(), ^{
if (!handledCompletion) {
completionHandler(installationInfo);
handledCompletion = YES;
}
});
[installerStatus invalidate];
}];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(PROBE_TIMEOUT * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
if (!handledCompletion) {
SULog(@"Timed out while probing installer info data");
completionHandler(nil);
handledCompletion = YES;
}
[installerStatus invalidate];
});
}
@end
-21
View File
@@ -1,21 +0,0 @@
//
// SURemoteMessagePort.h
// Sparkle
//
// Created by Mayur Pawashe on 3/9/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "SURemoteMessagePortProtocol.h"
NS_ASSUME_NONNULL_BEGIN
@interface SURemoteMessagePort : NSObject <SURemoteMessagePortProtocol>
- (instancetype)init;
- (instancetype)initWithServiceName:(NSString *)serviceName;
@end
NS_ASSUME_NONNULL_END
-193
View File
@@ -1,193 +0,0 @@
//
// SURemoteMessagePort.m
// Sparkle
//
// Created by Mayur Pawashe on 3/9/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import "SURemoteMessagePort.h"
// Because remote message ports returned to us upon creation can be re-used, we maintain a global table so that
// each instance we create can have its own invalidation block. We really invalidate a port for a service name if
// the number of ports for that service reach 0. If we don't maintain a table, we could run into trouble.
// For instance, invalidating one remote message port could invalidate another.
static NSMutableDictionary<NSString *, NSMutableArray<SURemoteMessagePort *> *> *gMessagePortsTable;
static dispatch_queue_t gMessageQueue;
static NSString *SURemoteServiceLookupReason = @"Remote Service Connection";
@interface SURemoteMessagePort ()
@property (nonatomic, copy) NSString *serviceName;
@property (nonatomic) CFMessagePortRef messagePort;
@property (nonatomic, copy) void (^invalidationCallback)(void);
@property (nonatomic) BOOL disabledAutomaticTermination;
@end
@implementation SURemoteMessagePort
@synthesize serviceName = _serviceName;
@synthesize messagePort = _messagePort;
@synthesize invalidationCallback = _invalidationCallback;
@synthesize disabledAutomaticTermination = _disabledAutomaticTermination;
- (instancetype)init
{
self = [super init];
if (self != nil) {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
gMessagePortsTable = [[NSMutableDictionary alloc] init];
gMessageQueue = dispatch_queue_create("org.sparkle-project.remote-message-port", DISPATCH_QUEUE_SERIAL);
});
// If we are a XPC service, protect it from being terminated until the invalidation handler is set
_disabledAutomaticTermination = YES;
[[NSProcessInfo processInfo] disableAutomaticTermination:SURemoteServiceLookupReason];
}
return self;
}
- (instancetype)initWithServiceName:(NSString *)serviceName
{
self = [self init];
if (self != nil) {
_serviceName = [serviceName copy];
}
return self;
}
- (void)dealloc
{
[self enableAutomaticTermination];
}
- (void)enableAutomaticTermination
{
if (self.disabledAutomaticTermination) {
[[NSProcessInfo processInfo] enableAutomaticTermination:SURemoteServiceLookupReason];
self.disabledAutomaticTermination = NO;
}
}
- (void)connectWithLookupCompletion:(void (^)(BOOL))lookupCompletionHandler
{
dispatch_async(gMessageQueue, ^{
NSMutableArray<SURemoteMessagePort *> *existingMessagePorts = [gMessagePortsTable objectForKey:self.serviceName];
if (existingMessagePorts != nil && existingMessagePorts.count > 0) {
self.messagePort = existingMessagePorts[0].messagePort;
[existingMessagePorts addObject:self];
lookupCompletionHandler(YES);
} else {
CFMessagePortRef messagePort = CFMessagePortCreateRemote(kCFAllocatorDefault, (CFStringRef)self.serviceName);
if (messagePort == NULL) {
lookupCompletionHandler(NO);
[self enableAutomaticTermination];
} else {
self.messagePort = messagePort;
NSMutableArray<SURemoteMessagePort *> *newMessagePorts = [[NSMutableArray alloc] init];
[newMessagePorts addObject:self];
[gMessagePortsTable setObject:newMessagePorts forKey:self.serviceName];
lookupCompletionHandler(YES);
}
}
});
}
- (void)setInvalidationHandler:(void (^)(void))invalidationHandler
{
// We can disable automatic termination now because we will be protected by the invalidationHandler (if this is a XPC service)
[self enableAutomaticTermination];
dispatch_async(gMessageQueue, ^{
if (self.messagePort != NULL) {
self.invalidationCallback = [invalidationHandler copy];
// Note: do not add messagePort to dispatch queue or run loop: it will complain that one shouldn't be added for remote ports
CFMessagePortSetInvalidationCallBack(self.messagePort, messageInvalidationCallback);
}
});
}
- (void)sendMessageWithIdentifier:(int32_t)identifier data:(NSData *)data expectingReply:(BOOL)expectingReply completion:(void (^)(BOOL success, NSData * _Nullable replyData))completionHandler
{
dispatch_async(gMessageQueue, ^{
SInt32 status = 0;
NSData *replyData = nil;
if (self.messagePort != NULL) {
CFDataRef dataRef = (__bridge CFDataRef)(data);
CFDataRef dataReceived = NULL;
status = CFMessagePortSendRequest(self.messagePort, identifier, dataRef, 0.2, 2.0, expectingReply ? kCFRunLoopDefaultMode : NULL, expectingReply ? &dataReceived : NULL);
if (expectingReply && status == kCFMessagePortSuccess) {
replyData = (NSData *)CFBridgingRelease(dataReceived);
}
} else {
status = kCFMessagePortIsInvalid;
}
completionHandler(status == kCFMessagePortSuccess, replyData);
});
}
- (void)sendMessageWithIdentifier:(int32_t)identifier data:(NSData *)data reply:(void (^)(BOOL success, NSData * _Nullable replyData))replyHandler
{
[self sendMessageWithIdentifier:identifier data:data expectingReply:YES completion:replyHandler];
}
- (void)sendMessageWithIdentifier:(int32_t)identifier data:(NSData *)data completion:(void (^)(BOOL success))completionHandler
{
[self sendMessageWithIdentifier:identifier data:data expectingReply:NO completion:^(BOOL success, NSData * _Nullable __unused replyData) {
completionHandler(success);
}];
}
- (void)invalidate
{
dispatch_async(gMessageQueue, ^{
self.invalidationCallback = nil;
if (self.messagePort != NULL) {
NSMutableArray<SURemoteMessagePort *> *messagePorts = [gMessagePortsTable objectForKey:self.serviceName];
[messagePorts removeObject:self];
if (messagePorts.count == 0) {
[gMessagePortsTable removeObjectForKey:self.serviceName];
// Removing our callback is a better decision than waiting for it to be called at an unpredictable time later
CFMessagePortSetInvalidationCallBack(self.messagePort, NULL);
CFMessagePortInvalidate(self.messagePort);
CFRelease(self.messagePort);
self.messagePort = NULL;
}
}
});
}
static void messageInvalidationCallback(CFMessagePortRef messagePort, void * __unused info)
{
@autoreleasepool {
NSString *serviceName = [(const NSString *)CFMessagePortGetName(messagePort) copy];
dispatch_async(gMessageQueue, ^{
if (serviceName != nil) {
for (SURemoteMessagePort *remoteMessagePort in [gMessagePortsTable objectForKey:serviceName]) {
if (remoteMessagePort.invalidationCallback != nil) {
remoteMessagePort.invalidationCallback();
remoteMessagePort.invalidationCallback = nil;
}
remoteMessagePort.messagePort = NULL;
}
[gMessagePortsTable removeObjectForKey:serviceName];
}
CFRelease(messagePort);
});
}
}
@end
-29
View File
@@ -1,29 +0,0 @@
//
// SURemoteMessagePortProtocol.h
// Sparkle
//
// Created by Mayur Pawashe on 4/3/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@protocol SURemoteMessagePortProtocol <NSObject>
- (void)setServiceName:(NSString *)serviceName;
- (void)connectWithLookupCompletion:(void (^)(BOOL))lookupCompletionHandler;
- (void)setInvalidationHandler:(void (^)(void))invalidationHandler;
- (void)sendMessageWithIdentifier:(int32_t)identifier data:(NSData *)data completion:(void (^)(BOOL success))completionHandler;
- (void)sendMessageWithIdentifier:(int32_t)identifier data:(NSData *)data reply:(void (^)(BOOL success, NSData * _Nullable replyData))replyHandler;
- (void)invalidate;
@end
NS_ASSUME_NONNULL_END
+19
View File
@@ -0,0 +1,19 @@
//
// SUSystemAuthorization.h
// Sparkle
//
// Created by Mayur Pawashe on 7/11/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <ServiceManagement/SMLoginItem.h>
NS_ASSUME_NONNULL_BEGIN
// Must free authorization ref later
AuthorizationRef SUCreateAuthorization(BOOL * _Nullable grantedSystemPrivilege);
BOOL SUGrantsSystemAuthorizationAccess(void);
NS_ASSUME_NONNULL_END
+52
View File
@@ -0,0 +1,52 @@
//
// SUSystemAuthorization.m
// Sparkle
//
// Created by Mayur Pawashe on 7/11/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import "SUSystemAuthorization.h"
#import <ServiceManagement/ServiceManagement.h>
AuthorizationRef SUCreateAuthorization(BOOL * _Nullable grantedSystemPrivilege)
{
// 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 auth;
}
BOOL SUGrantsSystemAuthorizationAccess(void)
{
BOOL grantedSystemPrivilege = NO;
AuthorizationRef auth = SUCreateAuthorization(&grantedSystemPrivilege);
AuthorizationFree(auth, kAuthorizationFlagDefaults);
return grantedSystemPrivilege;
}
+7 -7
View File
@@ -241,19 +241,19 @@ SU_EXPORT extern NSString *const SUUpdaterAppcastNotificationKey;
- (NSString *)pathToRelaunchForUpdater:(SUUpdater *)updater;
/*!
Returns whether or not the updater should inherit its parent's privileges during installation
Returns whether or not the updater should allow interaction with its installer
Use this to override the default behavior which is to not inherit privileges.
Use this to override the default behavior which is to allow interaction with the installer.
If privileges are inherited, then no authorization prompt will show up, and
the installation will succeed only if the process has sufficient privileges.
If interaction is allowed, then an authorization prompt may show up to the user if they do
not curently have sufficient privileges to perform the installation of the new update.
On the other hand, if privileges are not inherited (the default), the installer may
request an authorization prompt to obtain additional privileges.
On the other hand, if interaction is not allowed, then an installation may fail if the user does not
have sufficient privileges to perform the installation.
\param updater The SUUpdater instance.
*/
- (BOOL)updaterShouldInheritInstallPrivileges:(SUUpdater *)updater;
- (BOOL)updaterShouldAllowInstallerInteraction:(SUUpdater *)updater;
/*!
Returns the decryption password (if any) which is used to extract the update archive DMG.
-22
View File
@@ -1,22 +0,0 @@
//
// SUXPCLocalMessagePort.h
// Sparkle
//
// Created by Mayur Pawashe on 6/14/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "SULocalMessagePortProtocol.h"
#import "SULocalMessagePortDelegate.h"
NS_ASSUME_NONNULL_BEGIN
@interface SUXPCLocalMessagePort : NSObject <SULocalMessagePortProtocol>
// Due to XPC reasons, this delegate is strongly referenced. Make sure to -invalidate when done with this instance.
- (instancetype)initWithDelegate:(id<SULocalMessagePortDelegate>)delegate;
@end
NS_ASSUME_NONNULL_END
-84
View File
@@ -1,84 +0,0 @@
//
// SUXPCLocalMessagePort.m
// Sparkle
//
// Created by Mayur Pawashe on 6/14/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import "SUXPCLocalMessagePort.h"
#import "SULog.h"
@interface SUXPCLocalMessagePort ()
@property (nonatomic, readonly) NSXPCConnection *connection;
@property (nonatomic) id<SULocalMessagePortDelegate> delegate;
@property (nonatomic, copy) void (^invalidationHandler)(void);
@end
@implementation SUXPCLocalMessagePort
@synthesize connection = _connection;
@synthesize delegate = _delegate;
@synthesize invalidationHandler = _invalidationHandler;
- (instancetype)initWithDelegate:(id<SULocalMessagePortDelegate>)delegate
{
self = [self init];
if (self != nil) {
_connection = [[NSXPCConnection alloc] initWithServiceName:@LOCAL_MESSAGE_PORT_BUNDLE_ID];
_connection.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SULocalMessagePortProtocol)];
__weak SUXPCLocalMessagePort *weakSelf = self;
_connection.invalidationHandler = ^{
[weakSelf invokeInvalidation];
};
_connection.interruptionHandler = ^{
SULog(@"LocalMessagePort service interrupted");
[weakSelf invokeInvalidation];
[weakSelf.connection invalidate];
};
_delegate = delegate;
_connection.exportedInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SULocalMessagePortDelegate)];
_connection.exportedObject = _delegate;
[_connection resume];
}
return self;
}
- (void)setServiceName:(NSString *)serviceName
{
[self.connection.remoteObjectProxy setServiceName:serviceName];
}
- (void)invokeInvalidation
{
if (self.invalidationHandler != nil) {
self.invalidationHandler();
self.invalidationHandler = nil;
}
self.delegate = nil;
}
- (void)setInvalidationCallback:(void (^)(void))invalidationCallback
{
self.invalidationHandler = [invalidationCallback copy];
__weak SUXPCLocalMessagePort *weakSelf = self;
[self.connection.remoteObjectProxy setInvalidationCallback:^{
[weakSelf invokeInvalidation];
}];
}
- (void)invalidate
{
[self.connection.remoteObjectProxy invalidate];
[self.connection invalidate];
}
@end
-20
View File
@@ -1,20 +0,0 @@
//
// SUXPCRemoteMessagePort.h
// Sparkle
//
// Created by Mayur Pawashe on 4/3/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "SURemoteMessagePortProtocol.h"
NS_ASSUME_NONNULL_BEGIN
@interface SUXPCRemoteMessagePort : NSObject <SURemoteMessagePortProtocol>
- (instancetype)initWithServiceName:(NSString *)serviceName;
@end
NS_ASSUME_NONNULL_END
-99
View File
@@ -1,99 +0,0 @@
//
// SUXPCRemoteMessagePort.m
// Sparkle
//
// Created by Mayur Pawashe on 4/3/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import "SUXPCRemoteMessagePort.h"
#import "SURemoteMessagePort.h"
#import "SULog.h"
@interface SUXPCRemoteMessagePort ()
@property (nonatomic, readonly) NSXPCConnection *connection;
@property (nonatomic, copy) void (^invalidationHandler)(void);
@end
@implementation SUXPCRemoteMessagePort
@synthesize connection = _connection;
@synthesize invalidationHandler = _invalidationHandler;
- (instancetype)initWithServiceName:(NSString *)serviceName
{
self = [self init];
if (self != nil) {
_connection = [[NSXPCConnection alloc] initWithServiceName:@REMOTE_MESSAGE_PORT_BUNDLE_ID];
_connection.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SURemoteMessagePortProtocol)];
__weak SUXPCRemoteMessagePort *weakSelf = self;
_connection.invalidationHandler = ^{
[weakSelf invokeInvalidation];
};
_connection.interruptionHandler = ^{
SULog(@"RemoteMessagePort service interrupted");
[weakSelf invokeInvalidation];
[weakSelf.connection invalidate];
};
[_connection resume];
[self setServiceName:serviceName];
}
return self;
}
- (void)setServiceName:(NSString *)serviceName
{
[self.connection.remoteObjectProxy setServiceName:serviceName];
}
- (void)connectWithLookupCompletion:(void (^)(BOOL))lookupCompletionHandler
{
[self.connection.remoteObjectProxy connectWithLookupCompletion:^(BOOL success) {
lookupCompletionHandler(success);
if (!success) {
[self.connection invalidate];
}
}];
}
- (void)invokeInvalidation
{
if (self.invalidationHandler != nil) {
self.invalidationHandler();
self.invalidationHandler = nil;
}
}
- (void)setInvalidationHandler:(void (^)(void))invalidationHandler
{
_invalidationHandler = [invalidationHandler copy];
__weak SUXPCRemoteMessagePort *weakSelf = self;
[self.connection.remoteObjectProxy setInvalidationHandler:^{
[weakSelf invokeInvalidation];
}];
}
- (void)sendMessageWithIdentifier:(int32_t)identifier data:(NSData *)data completion:(void (^)(BOOL success))completionHandler
{
[self.connection.remoteObjectProxy sendMessageWithIdentifier:identifier data:data completion:completionHandler];
}
- (void)sendMessageWithIdentifier:(int32_t)identifier data:(NSData *)data reply:(void (^)(BOOL success, NSData * _Nullable replyData))replyHandler
{
[self.connection.remoteObjectProxy sendMessageWithIdentifier:identifier data:data reply:replyHandler];
}
- (void)invalidate
{
[self.connection.remoteObjectProxy invalidate];
[self.connection invalidate];
}
@end
+1 -1
View File
@@ -54,7 +54,7 @@
SUHost *host = [[SUHost alloc] initWithBundle:bundle];
NSError *installerError = nil;
id<SUInstallerProtocol> installer = [SUInstaller installerForHost:host updateDirectory:[path stringByDeletingLastPathComponent] inheritsPrivileges:YES versionComparator:[SUStandardVersionComparator standardVersionComparator] error:&installerError];
id<SUInstallerProtocol> installer = [SUInstaller installerForHost:host updateDirectory:[path stringByDeletingLastPathComponent] allowingInteraction:NO versionComparator:[SUStandardVersionComparator standardVersionComparator] error:&installerError];
if (installer == nil) {
XCTFail(@"Installer is nil with error: %@", installerError);
+2 -2
View File
@@ -64,11 +64,11 @@ void _SULogDisableStandardErrorStream(void);
return self;
}
- (BOOL)updaterShouldInheritInstallPrivileges:(SUUpdater *)__unused updater
- (BOOL)updaterShouldAllowInstallerInteraction:(SUUpdater *)__unused updater
{
// If the installation is interactive, we can show an authorization prompt for requesting additional privileges,
// otherwise we should have the installer inherit the updater's privileges.
return !self.interactive;
return self.interactive;
}
// In case we find an update during probing, otherwise we leave this to the user driver