Make SURemoteMessagePort operations asynchronous

This commit is contained in:
Zorg committed 2016-04-03 17:05:56 -04:00
1 parent d7cca8a594
commit 32c687ed79
7 files changed
+249 -163

No files matched your search

+38 -23
View File
@@ -107,29 +107,42 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.5;
[self cleanupAndExitWithStatus:EXIT_FAILURE];
}
if (![self startRemotePort]) {
SULog(@"Failed creating remote message port from installer");
[self cleanupAndExitWithStatus:EXIT_FAILURE];
}
[self startRemotePortWithCompletion:^(BOOL success) {
if (!success) {
SULog(@"Failed creating remote message port from installer");
[self cleanupAndExitWithStatus:EXIT_FAILURE];
}
}];
return self;
}
- (BOOL)startRemotePort
- (void)startRemotePortWithCompletion:(void (^)(BOOL))completionHandler
{
if (self.remotePort == nil) {
self.remotePort = [[SURemoteMessagePort alloc] initWithServiceName:SUUpdateDriverServiceNameForBundleIdentifier(self.hostBundleIdentifier) invalidationCallback:^{
dispatch_async(dispatch_get_main_queue(), ^{
if (self.remotePort != nil && !self.willCompleteInstallation) {
SULog(@"Invalidation on remote port being called, and installation is not close enough to completion!");
[self cleanupAndExitWithStatus:EXIT_FAILURE];
}
self.remotePort = nil;
});
}];
if (self.remotePort != nil) {
completionHandler(YES);
return;
}
return (self.remotePort != nil);
self.remotePort = [[SURemoteMessagePort alloc] initWithServiceName:SUUpdateDriverServiceNameForBundleIdentifier(self.hostBundleIdentifier)];
__weak AppInstaller *weakSelf = self;
[self.remotePort connectWithLookupCompletion:^(BOOL success) {
dispatch_async(dispatch_get_main_queue(), ^{
completionHandler(success);
});
} invalidationHandler:^{
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;
}
});
}];
}
/**
@@ -334,12 +347,14 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.5;
#warning todo: handle this message even if we aren't ready for stage 2 yet.
// 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
if (![self startRemotePort]) {
SULog(@"Installer failed to set up remote port to updater before resuming installation");
}
// Resume the installation if we aren't done with stage 2 yet, and remind the client we are prepared to relaunch
[self resumeInstallation];
[self startRemotePortWithCompletion:^(BOOL success) {
if (!success) {
SULog(@"Installer failed to set up remote port to updater before resuming installation");
}
// Resume the installation if we aren't done with stage 2 yet, and remind the client we are prepared to relaunch
[self resumeInstallation];
}];
});
}
+73 -62
View File
@@ -128,16 +128,23 @@
return YES;
}
- (BOOL)setUpRemotePort:(NSError * __autoreleasing *)error
- (void)setUpRemotePortWithCompletion:(void (^)(BOOL))completionHandler
{
if (self.remotePort != nil) {
return YES;
completionHandler(YES);
return;
}
NSString *hostBundleIdentifier = self.host.bundle.bundleIdentifier;
assert(hostBundleIdentifier != nil);
self.remotePort = [[SURemoteMessagePort alloc] initWithServiceName:SUAutoUpdateServiceNameForBundleIdentifier(hostBundleIdentifier) invalidationCallback:^{
self.remotePort = [[SURemoteMessagePort alloc] initWithServiceName:SUAutoUpdateServiceNameForBundleIdentifier(hostBundleIdentifier)];
[self.remotePort connectWithLookupCompletion:^(BOOL lookupSuccess) {
dispatch_async(dispatch_get_main_queue(), ^{
completionHandler(lookupSuccess);
});
} invalidationHandler:^{
dispatch_async(dispatch_get_main_queue(), ^{
if (self.remotePort != nil) {
NSError *remoteError =
@@ -153,25 +160,6 @@
}
});
}];
if (self.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 failed being created"
}
];
if (error != NULL) {
*error = remoteError;
}
return NO;
}
return YES;
}
- (void)launchInstallToolWithCompletion:(void (^)(NSError * _Nullable ))completionHandler
@@ -220,20 +208,37 @@
NSData *archivedData = SUArchiveRootObjectSecurely(installationData);
NSError *remoteError = nil;
if (![self setUpRemotePort:&remoteError]) {
[self.delegate installerIsRequestingAbortInstallWithError:remoteError];
} else {
[self.remotePort sendMessageWithIdentifier:SUInstallationData data:archivedData completion:^(BOOL success) {
if (!success) {
dispatch_async(dispatch_get_main_queue(), ^{
[self.delegate installerIsRequestingAbortInstallWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey:SULocalizedString(@"An error occurred while starting the installer parameters. Please try again later.", nil) }]];
});
}
}];
__weak SUInstallerDriver *weakSelf = self;
[self setUpRemotePortWithCompletion:^(BOOL setupSuccess) {
SUInstallerDriver *strongSelf = weakSelf;
if (strongSelf == nil) {
return;
}
self.currentStage = SURequestInstallationParameters;
}
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;
}
}];
}
- (void)handleMessageWithIdentifier:(int32_t)identifier data:(NSData *)data
@@ -467,34 +472,40 @@
return;
}
NSError *remotePortError = nil;
if (![self setUpRemotePort:&remotePortError]) {
[self.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) }]];
return;
}
// For resumability, we'll assume we are far enough for the installation to continue
self.currentStage = SUInstallationFinishedStage1;
uint8_t response[2] = {(uint8_t)relaunch, (uint8_t)showUI};
NSData *responseData = [NSData dataWithBytes:response length:sizeof(response)];
[self.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"
}
];
[self.delegate installerIsRequestingAbortInstallWithError:remoteError];
});
__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;
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
}];
}
// otherwise we'll terminate later when the installer tells us stage 2 is done
}];
}
+1 -1
View File
@@ -14,7 +14,7 @@ NS_ASSUME_NONNULL_BEGIN
@interface SUProbeInstallStatus : NSObject
+ (BOOL)probeInstallerInProgressForHost:(SUHost *)host;
+ (void)probeInstallerInProgressForHost:(SUHost *)host completion:(void (^)(BOOL))completionHandler;
// completionHandler may not be sent on main queue
// additionally, it may be possible that the installer is in progress but we get a nil appcast item back
+41 -20
View File
@@ -16,14 +16,19 @@
@implementation SUProbeInstallStatus
+ (BOOL)probeInstallerInProgressForHost:(SUHost *)host
+ (void)probeInstallerInProgressForHost:(SUHost *)host completion:(void (^)(BOOL))completionHandler
{
NSString *hostBundleIdentifier = host.bundle.bundleIdentifier;
assert(hostBundleIdentifier != nil);
SURemoteMessagePort *remotePort = [[SURemoteMessagePort alloc] initWithServiceName:SUAutoUpdateServiceNameForBundleIdentifier(hostBundleIdentifier) invalidationCallback:^{}];
[remotePort invalidate];
return (remotePort != nil);
SURemoteMessagePort *remotePort = [[SURemoteMessagePort alloc] initWithServiceName:SUAutoUpdateServiceNameForBundleIdentifier(hostBundleIdentifier)];
[remotePort connectWithLookupCompletion:^(BOOL success) {
if (success) {
[remotePort invalidate];
}
completionHandler(success);
} invalidationHandler:^{}];
}
+ (void)probeInstallerUpdateItemForHost:(SUHost *)host completion:(void (^)(SUAppcastItem * _Nullable))completionHandler
@@ -31,26 +36,42 @@
NSString *hostBundleIdentifier = host.bundle.bundleIdentifier;
assert(hostBundleIdentifier != nil);
SURemoteMessagePort *remotePort = [[SURemoteMessagePort alloc] initWithServiceName:SUAutoUpdateServiceNameForBundleIdentifier(hostBundleIdentifier) invalidationCallback:^{}];
if (remotePort == nil) {
completionHandler(nil);
return;
}
SURemoteMessagePort *remotePort = [[SURemoteMessagePort alloc] initWithServiceName:SUAutoUpdateServiceNameForBundleIdentifier(hostBundleIdentifier)];
[remotePort sendMessageWithIdentifier:SUReceiveUpdateAppcastItemData data:[NSData data] reply:^(BOOL success, NSData * _Nullable replyData) {
if (!success || replyData == nil) {
completionHandler(nil);
} else {
NSData *nonNullReplyData = replyData;
SUAppcastItem * _Nullable updateItem = SUUnarchiveRootObjectSecurely(nonNullReplyData, [SUAppcastItem class]);
if (updateItem != nil) {
completionHandler(updateItem);
} else {
__block BOOL handledCompletion = NO;
[remotePort connectWithLookupCompletion:^(BOOL lookupSuccess) {
if (!lookupSuccess) {
if (!handledCompletion) {
completionHandler(nil);
handledCompletion = YES;
}
} else {
[remotePort sendMessageWithIdentifier:SUReceiveUpdateAppcastItemData data:[NSData data] reply:^(BOOL success, NSData * _Nullable replyData) {
[remotePort invalidate];
if (!handledCompletion) {
if (!success || replyData == nil) {
completionHandler(nil);
} else {
NSData *nonNullReplyData = replyData;
SUAppcastItem * _Nullable updateItem = SUUnarchiveRootObjectSecurely(nonNullReplyData, [SUAppcastItem class]);
if (updateItem != nil) {
completionHandler(updateItem);
} else {
completionHandler(nil);
}
}
}
handledCompletion = YES;
}];
}
} invalidationHandler:^{
if (!handledCompletion) {
completionHandler(nil);
handledCompletion = YES;
}
[remotePort invalidate];
}];
}
+3 -1
View File
@@ -12,7 +12,9 @@ NS_ASSUME_NONNULL_BEGIN
@interface SURemoteMessagePort : NSObject
- (nullable instancetype)initWithServiceName:(NSString *)serviceName invalidationCallback:(void (^)(void))invalidationCallback;
- (instancetype)initWithServiceName:(NSString *)serviceName;
- (void)connectWithLookupCompletion:(void (^)(BOOL))lookupCompletionHandler invalidationHandler:(void (^)(void))invalidationHandler;
- (void)sendMessageWithIdentifier:(int32_t)identifier data:(NSData *)data completion:(void (^)(BOOL success))completionHandler;
+45 -28
View File
@@ -9,11 +9,15 @@
#import "SURemoteMessagePort.h"
#import <objc/runtime.h>
// The global message queue where we perform message port operations
// We want this to be global across live remote ports, otherwise I fear for out-of-order invalidation events and the such
static dispatch_queue_t gMessageQueue;
@interface SURemoteMessagePort ()
@property (nonatomic, copy) NSString *serviceName;
@property (nonatomic) CFMessagePortRef messagePort;
@property (nonatomic, copy) void (^invalidationCallback)(void);
@property (nonatomic, readonly) dispatch_queue_t messageQueue;
@property (nonatomic, copy) void (^invalidationHandler)(void);
@end
@@ -21,37 +25,50 @@
static const char *SURemoteMessagePortSelfKey = "su_messagePort";
@synthesize serviceName = _serviceName;
@synthesize messagePort = _messagePort;
@synthesize invalidationCallback = _invalidationCallback;
@synthesize messageQueue = _messageQueue;
@synthesize invalidationHandler = _invalidationHandler;
- (nullable instancetype)initWithServiceName:(NSString *)serviceName invalidationCallback:(void (^)(void))invalidationCallback
- (instancetype)initWithServiceName:(NSString *)serviceName
{
self = [super init];
if (self != nil) {
CFMessagePortRef messagePort = CFMessagePortCreateRemote(kCFAllocatorDefault, (CFStringRef)serviceName);
if (messagePort == NULL) {
return nil;
}
_serviceName = [serviceName copy];
_messageQueue = dispatch_queue_create("org.sparkle-project.remote-message-port", DISPATCH_QUEUE_SERIAL);
_messagePort = messagePort;
_invalidationCallback = [invalidationCallback copy];
CFRetain((__bridge CFTypeRef)(self));
// We have to set an associated object here because we can't pass an info context to remote message ports when setting up an invalidation handler
objc_setAssociatedObject((__bridge id)messagePort, SURemoteMessagePortSelfKey, self, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
// Note: do not add messagePort to dispatch queue or run loop: it will complain that one shouldn't be added for remote ports
CFMessagePortSetInvalidationCallBack(messagePort, messageInvalidationCallback);
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
gMessageQueue = dispatch_queue_create("org.sparkle-project.remote-message-port", DISPATCH_QUEUE_SERIAL);
});
}
return self;
}
- (void)connectWithLookupCompletion:(void (^)(BOOL))lookupCompletionHandler invalidationHandler:(void (^)(void))invalidationHandler
{
dispatch_async(gMessageQueue, ^{
CFMessagePortRef messagePort = CFMessagePortCreateRemote(kCFAllocatorDefault, (CFStringRef)self.serviceName);
if (messagePort == NULL) {
lookupCompletionHandler(NO);
} else {
self.messagePort = messagePort;
self.invalidationHandler = [invalidationHandler copy];
CFRetain((__bridge CFTypeRef)(self));
// We have to set an associated object here because we can't pass an info context to remote message ports when setting up an invalidation handler
objc_setAssociatedObject((__bridge id)messagePort, SURemoteMessagePortSelfKey, self, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
// Note: do not add messagePort to dispatch queue or run loop: it will complain that one shouldn't be added for remote ports
CFMessagePortSetInvalidationCallBack(messagePort, messageInvalidationCallback);
lookupCompletionHandler(YES);
}
});
}
- (void)sendMessageWithIdentifier:(int32_t)identifier data:(NSData *)data expectingReply:(BOOL)expectingReply completion:(void (^)(BOOL success, NSData * _Nullable replyData))completionHandler
{
dispatch_async(self.messageQueue, ^{
dispatch_async(gMessageQueue, ^{
SInt32 status = 0;
NSData *replyData = nil;
if (self.messagePort != NULL) {
@@ -82,9 +99,9 @@ static const char *SURemoteMessagePortSelfKey = "su_messagePort";
- (void)invalidate
{
dispatch_async(self.messageQueue, ^{
if (self.invalidationCallback != nil) {
self.invalidationCallback = nil;
dispatch_async(gMessageQueue, ^{
if (self.invalidationHandler != nil) {
self.invalidationHandler = nil;
CFMessagePortInvalidate(self.messagePort);
}
});
@@ -96,10 +113,10 @@ static void messageInvalidationCallback(CFMessagePortRef messagePort, void * __u
@autoreleasepool {
SURemoteMessagePort *self = objc_getAssociatedObject((__bridge id)(messagePort), SURemoteMessagePortSelfKey);
dispatch_async(self.messageQueue, ^{
if (self.invalidationCallback != nil) {
self.invalidationCallback();
self.invalidationCallback = nil;
dispatch_async(gMessageQueue, ^{
if (self.invalidationHandler != nil) {
self.invalidationHandler();
self.invalidationHandler = nil;
}
self.messagePort = NULL;
+48 -28
View File
@@ -308,32 +308,47 @@ static void SUCheckForUpdatesInBgReachabilityCheck(__weak SUUpdater *updater, id
// Wouldn't want to annoy users on dial-up by establishing a connection every
// hour or so:
// We don't want the reachability check to act on the driver if the updater is going near death
__weak SUUpdater *weakSelf = self;
[self allowsAutomaticUpdatesWithCompletion:^(BOOL allowsAutomaticUpdates) {
id <SUUpdateDriver> updateDriver;
if ([self automaticallyDownloadsUpdates] && allowsAutomaticUpdates && ![SUProbeInstallStatus probeInstallerInProgressForHost:self.host]) {
updateDriver =
[[SUAutomaticUpdateDriver alloc]
initWithHost:self.host
sparkleBundle:self.sparkleBundle
updater:self
updaterDelegate:self.delegate];
} else {
updateDriver =
[[SUScheduledUpdateDriver alloc]
initWithHost:self.host
allowsAutomaticUpdates:allowsAutomaticUpdates
sparkleBundle:self.sparkleBundle
updater:self
userDriver:self.userDriver
updaterDelegate:self.delegate];
SUHost *theHost = weakSelf.host;
if (theHost == nil) {
return;
}
// We don't want the reachability check to act on the driver if the updater is going near death
__weak SUUpdater *updater = self;
NSURL *feedURL = [updater feedURL];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
SUCheckForUpdatesInBgReachabilityCheck(updater, updateDriver, feedURL);
});
[SUProbeInstallStatus probeInstallerInProgressForHost:theHost completion:^(BOOL installerIsRunning) {
dispatch_async(dispatch_get_main_queue(), ^{
SUUpdater *strongSelf = weakSelf;
if (strongSelf == nil) {
return;
}
id <SUUpdateDriver> updateDriver;
if (!installerIsRunning && [strongSelf automaticallyDownloadsUpdates] && allowsAutomaticUpdates) {
updateDriver =
[[SUAutomaticUpdateDriver alloc]
initWithHost:theHost
sparkleBundle:strongSelf.sparkleBundle
updater:strongSelf
updaterDelegate:strongSelf.delegate];
} else {
updateDriver =
[[SUScheduledUpdateDriver alloc]
initWithHost:theHost
allowsAutomaticUpdates:allowsAutomaticUpdates
sparkleBundle:strongSelf.sparkleBundle
updater:strongSelf
userDriver:strongSelf.userDriver
updaterDelegate:strongSelf.delegate];
}
NSURL *feedURL = [strongSelf feedURL];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
SUCheckForUpdatesInBgReachabilityCheck(weakSelf, updateDriver, feedURL);
});
});
}];
}];
}
@@ -398,11 +413,16 @@ static void SUCheckForUpdatesInBgReachabilityCheck(__weak SUUpdater *updater, id
}
};
if (![SUProbeInstallStatus probeInstallerInProgressForHost:self.host]) {
[self.driver checkForUpdatesAtAppcastURL:theFeedURL withUserAgent:[self userAgentString] httpHeaders:[self httpHeaders] completion:completionBlock];
} else {
[self.driver resumeUpdateWithCompletion:completionBlock];
}
[SUProbeInstallStatus probeInstallerInProgressForHost:self.host completion:^(BOOL success) {
SUUpdater *strongSelf = weakSelf;
if (strongSelf != nil) {
if (!success) {
[strongSelf.driver checkForUpdatesAtAppcastURL:theFeedURL withUserAgent:[strongSelf userAgentString] httpHeaders:[strongSelf httpHeaders] completion:completionBlock];
} else {
[strongSelf.driver resumeUpdateWithCompletion:completionBlock];
}
}
}];
} else {
[self.driver abortUpdate];
}