diff --git a/Autoupdate/AgentConnection.h b/Autoupdate/AgentConnection.h index 77bb2eab..3ac85b96 100644 --- a/Autoupdate/AgentConnection.h +++ b/Autoupdate/AgentConnection.h @@ -19,7 +19,7 @@ NS_ASSUME_NONNULL_BEGIN @protocol SPUInstallerAgentProtocol; -@interface AgentConnection : NSObject +SPU_OBJC_DIRECT_MEMBERS @interface AgentConnection : NSObject - (instancetype)initWithHostBundleIdentifier:(NSString *)bundleIdentifier delegate:(id)delegate; diff --git a/Autoupdate/AgentConnection.m b/Autoupdate/AgentConnection.m index 9396d95d..21dfea88 100644 --- a/Autoupdate/AgentConnection.m +++ b/Autoupdate/AgentConnection.m @@ -16,20 +16,16 @@ @interface AgentConnection () -@property (nonatomic) NSXPCListener *xpcListener; -@property (nonatomic, nullable) NSXPCConnection *activeConnection; -@property (nonatomic, nullable) id agent; -@property (nonatomic, weak) id delegate; -@property (nonatomic) BOOL connected; - @end @implementation AgentConnection +{ + NSXPCListener *_xpcListener; + NSXPCConnection *_activeConnection; + __weak id _delegate; +} -@synthesize xpcListener = _xpcListener; -@synthesize activeConnection = _activeConnection; @synthesize agent = _agent; -@synthesize delegate = _delegate; @synthesize connected = _connected; @synthesize invalidationError = _invalidationError; @@ -48,23 +44,23 @@ - (void)startListener { - [self.xpcListener resume]; + [_xpcListener resume]; } - (void)invalidate { - self.delegate = nil; + _delegate = nil; - [self.activeConnection invalidate]; - self.activeConnection = nil; + [_activeConnection invalidate]; + _activeConnection = nil; - [self.xpcListener invalidate]; - self.xpcListener = nil; + [_xpcListener invalidate]; + _xpcListener = nil; } - (BOOL)listener:(NSXPCListener *)__unused listener shouldAcceptNewConnection:(NSXPCConnection *)newConnection { - if (self.activeConnection != nil) { + if (_activeConnection != nil) { [newConnection invalidate]; return NO; } @@ -74,24 +70,30 @@ newConnection.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SPUInstallerAgentProtocol)]; - self.activeConnection = newConnection; + _activeConnection = newConnection; - __weak AgentConnection *weakSelf = self; + __weak __typeof__(self) weakSelf = self; newConnection.interruptionHandler = ^{ dispatch_async(dispatch_get_main_queue(), ^{ - [weakSelf.activeConnection invalidate]; + __typeof__(self) strongSelf = weakSelf; + if (strongSelf != nil) { + [strongSelf->_activeConnection invalidate]; + } }); }; newConnection.invalidationHandler = ^{ dispatch_async(dispatch_get_main_queue(), ^{ - [weakSelf.delegate agentConnectionDidInvalidate]; + __typeof__(self) strongSelf = weakSelf; + if (strongSelf != nil) { + [strongSelf->_delegate agentConnectionDidInvalidate]; + } }); }; [newConnection resume]; - self.agent = newConnection.remoteObjectProxy; + _agent = newConnection.remoteObjectProxy; return YES; } @@ -99,10 +101,10 @@ - (void)connectionDidInitiateWithReply:(void (^)(void))acknowledgement { dispatch_async(dispatch_get_main_queue(), ^{ - self.connected = YES; + self->_connected = YES; - [self.delegate agentConnectionDidInitiate]; - self.delegate = nil; + [self->_delegate agentConnectionDidInitiate]; + self->_delegate = nil; }); acknowledgement(); @@ -111,7 +113,7 @@ - (void)connectionWillInvalidateWithError:(NSError *)error { dispatch_async(dispatch_get_main_queue(), ^{ - self.invalidationError = error; + self->_invalidationError = error; }); } diff --git a/Autoupdate/AppInstaller.h b/Autoupdate/AppInstaller.h index 66746209..64c999d8 100644 --- a/Autoupdate/AppInstaller.h +++ b/Autoupdate/AppInstaller.h @@ -11,7 +11,7 @@ NS_ASSUME_NONNULL_BEGIN -@interface AppInstaller : NSObject +SPU_OBJC_DIRECT_MEMBERS @interface AppInstaller : NSObject - (instancetype)initWithHostBundleIdentifier:(NSString *)hostBundleIdentifier homeDirectory:(NSString *)homeDirectory userName:(NSString *)userName; diff --git a/Autoupdate/AppInstaller.m b/Autoupdate/AppInstaller.m index e09bbc54..5694a23d 100644 --- a/Autoupdate/AppInstaller.m +++ b/Autoupdate/AppInstaller.m @@ -43,73 +43,48 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; @interface AppInstaller () - -@property (nonatomic) NSXPCListener* xpcListener; -@property (nonatomic) NSXPCConnection *activeConnection; -@property (nonatomic) id communicator; -@property (nonatomic) AgentConnection *agentConnection; -@property (nonatomic) BOOL receivedUpdaterPong; - -@property (nonatomic, strong) TerminationListener *terminationListener; - -@property (nonatomic) SUUpdateValidator *updateValidator; - -@property (nonatomic, readonly, copy) NSString *hostBundleIdentifier; -@property (nonatomic, readonly) NSString *homeDirectory; -@property (nonatomic, readonly) NSString *userName; -@property (nonatomic) SUHost *host; -@property (nonatomic, copy) NSString *updateDirectoryPath; -@property (nonatomic, copy) NSString *downloadName; -@property (nonatomic, copy) NSString *decryptionPassword; -@property (nonatomic, strong) SUSignatures *signatures; -@property (nonatomic, copy) NSString *relaunchPath; -@property (nonatomic, copy) NSString *installationType; -@property (nonatomic, assign) BOOL shouldRelaunch; -@property (nonatomic, assign) BOOL shouldShowUI; - -@property (nonatomic) id installer; -@property (nonatomic) BOOL willCompleteInstallation; -@property (nonatomic) BOOL receivedInstallationData; -@property (nonatomic) BOOL finishedValidation; -@property (nonatomic) BOOL agentInitiatedConnection; - -@property (nonatomic) dispatch_queue_t installerQueue; -@property (nonatomic) BOOL performedStage1Installation; -@property (nonatomic) BOOL performedStage2Installation; -@property (nonatomic) BOOL performedStage3Installation; - @end @implementation AppInstaller +{ + NSXPCListener* _xpcListener; + NSXPCConnection *_activeConnection; + id _communicator; + AgentConnection *_agentConnection; -@synthesize xpcListener = _xpcListener; -@synthesize activeConnection = _activeConnection; -@synthesize communicator = _communicator; -@synthesize agentConnection = _agentConnection; -@synthesize receivedUpdaterPong = _receivedUpdaterPong; -@synthesize hostBundleIdentifier = _hostBundleIdentifier; -@synthesize homeDirectory = _homeDirectory; -@synthesize userName = _userName; -@synthesize terminationListener = _terminationListener; -@synthesize updateValidator = _updateValidator; -@synthesize host = _host; -@synthesize updateDirectoryPath = _updateDirectoryPath; -@synthesize downloadName = _downloadName; -@synthesize decryptionPassword = _decryptionPassword; -@synthesize signatures = _signatures; -@synthesize relaunchPath = _relaunchPath; -@synthesize installationType = _installationType; -@synthesize shouldRelaunch = _shouldRelaunch; -@synthesize shouldShowUI = _shouldShowUI; -@synthesize installer = _installer; -@synthesize willCompleteInstallation = _willCompleteInstallation; -@synthesize receivedInstallationData = _receivedInstallationData; -@synthesize installerQueue = _installerQueue; -@synthesize performedStage1Installation = _performedStage1Installation; -@synthesize performedStage2Installation = _performedStage2Installation; -@synthesize performedStage3Installation = _performedStage3Installation; -@synthesize finishedValidation = _finishedValidation; -@synthesize agentInitiatedConnection = _agentInitiatedConnection; + TerminationListener *_terminationListener; + + SUUpdateValidator *_updateValidator; + + NSString *_hostBundleIdentifier; + NSString *_homeDirectory; + NSString *_userName; + SUHost *_host; + NSString *_updateDirectoryPath; + NSString *_downloadName; + NSString *_decryptionPassword; + SUSignatures *_signatures; + NSString *_relaunchPath; + NSString *_installationType; + + id _installer; + + dispatch_queue_t _installerQueue; + + BOOL _shouldRelaunch; + BOOL _shouldShowUI; + + BOOL _receivedUpdaterPong; + + BOOL _willCompleteInstallation; + BOOL _receivedInstallationData; + BOOL _finishedValidation; + BOOL _agentInitiatedConnection; + + BOOL _performedStage1Installation; + BOOL _performedStage2Installation; + BOOL _performedStage3Installation; +} - (instancetype)initWithHostBundleIdentifier:(NSString *)hostBundleIdentifier homeDirectory:(NSString *)homeDirectory userName:(NSString *)userName { @@ -132,68 +107,71 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; - (BOOL)listener:(NSXPCListener *)__unused listener shouldAcceptNewConnection:(NSXPCConnection *)newConnection { - if (self.activeConnection != nil) { + if (_activeConnection != nil) { SULog(SULogLevelDefault, @"Rejecting multiple connections..."); [newConnection invalidate]; return NO; } - self.activeConnection = newConnection; + _activeConnection = newConnection; newConnection.exportedInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUInstallerCommunicationProtocol)]; newConnection.exportedObject = self; newConnection.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUInstallerCommunicationProtocol)]; - __weak AppInstaller *weakSelf = self; + __weak __typeof__(self) weakSelf = self; newConnection.interruptionHandler = ^{ dispatch_async(dispatch_get_main_queue(), ^{ - [weakSelf.activeConnection invalidate]; + __typeof__(self) strongSelf = weakSelf; + if (strongSelf != nil) { + [strongSelf->_activeConnection invalidate]; + } }); }; newConnection.invalidationHandler = ^{ dispatch_async(dispatch_get_main_queue(), ^{ - AppInstaller *strongSelf = weakSelf; + __typeof__(self) strongSelf = weakSelf; if (strongSelf != nil) { - if (strongSelf.activeConnection != nil && !strongSelf.willCompleteInstallation) { + if (strongSelf->_activeConnection != nil && !strongSelf->_willCompleteInstallation) { [strongSelf cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: @"Invalidation on remote port being called, and installation is not close enough to completion!" }]]; } - strongSelf.communicator = nil; - strongSelf.activeConnection = nil; + strongSelf->_communicator = nil; + strongSelf->_activeConnection = nil; } }); }; [newConnection resume]; - self.communicator = newConnection.remoteObjectProxy; + _communicator = newConnection.remoteObjectProxy; return YES; } - (void)start { - [self.xpcListener resume]; - [self.agentConnection startListener]; + [_xpcListener resume]; + [_agentConnection startListener]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(FIRST_UPDATER_MESSAGE_TIMEOUT * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ - if (!self.receivedInstallationData) { + if (!self->_receivedInstallationData) { [self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: @"Timeout: installation data was never received" }]]; } - if (!self.agentConnection.connected) { + if (!self->_agentConnection.connected) { [self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: @"Timeout: agent connection was never initiated" }]]; } }); } -- (void)extractAndInstallUpdate +- (void)extractAndInstallUpdate SPU_OBJC_DIRECT { - [self.communicator handleMessageWithIdentifier:SPUExtractionStarted data:[NSData data]]; + [_communicator handleMessageWithIdentifier:SPUExtractionStarted data:[NSData data]]; - NSString *archivePath = [self.updateDirectoryPath stringByAppendingPathComponent:self.downloadName]; - id unarchiver = [SUUnarchiver unarchiverForPath:archivePath updatingHostBundlePath:self.host.bundlePath decryptionPassword:self.decryptionPassword expectingInstallationType:self.installationType]; + NSString *archivePath = [_updateDirectoryPath stringByAppendingPathComponent:_downloadName]; + id unarchiver = [SUUnarchiver unarchiverForPath:archivePath updatingHostBundlePath:_host.bundlePath decryptionPassword:_decryptionPassword expectingInstallationType:_installationType]; NSError *unarchiverError = nil; BOOL success = NO; @@ -202,14 +180,14 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; success = NO; } else { - self.updateValidator = [[SUUpdateValidator alloc] initWithDownloadPath:archivePath signatures:self.signatures host:self.host]; + _updateValidator = [[SUUpdateValidator alloc] initWithDownloadPath:archivePath signatures:_signatures host:_host]; // Delta & package updates will require validation before extraction // Normal application updates are a bit more lenient allowing developers to change one of apple dev ID or EdDSA keys - BOOL needsPrevalidation = [[unarchiver class] mustValidateBeforeExtraction] || ![self.installationType isEqualToString:SPUInstallationTypeApplication]; + BOOL needsPrevalidation = [[unarchiver class] mustValidateBeforeExtraction] || ![_installationType isEqualToString:SPUInstallationTypeApplication]; if (needsPrevalidation) { - success = [self.updateValidator validateDownloadPathWithError:&unarchiverError]; + success = [_updateValidator validateDownloadPathWithError:&unarchiverError]; } else { success = YES; } @@ -223,18 +201,18 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; if (error != nil) { [self unarchiverDidFailWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to unarchive %@", archivePath], NSUnderlyingErrorKey: (NSError * _Nonnull)error }]]; } else { - [self.communicator handleMessageWithIdentifier:SPUValidationStarted data:[NSData data]]; + [self->_communicator handleMessageWithIdentifier:SPUValidationStarted data:[NSData data]]; NSError *validationError = nil; - BOOL validationSuccess = [self.updateValidator validateWithUpdateDirectory:self.updateDirectoryPath error:&validationError]; + BOOL validationSuccess = [self->_updateValidator validateWithUpdateDirectory:self->_updateDirectoryPath error:&validationError]; if (!validationSuccess) { [self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: @"Update validation was a failure", NSUnderlyingErrorKey: validationError }]]; } else { - [self.communicator handleMessageWithIdentifier:SPUInstallationStartedStage1 data:[NSData data]]; + [self->_communicator handleMessageWithIdentifier:SPUInstallationStartedStage1 data:[NSData data]]; - self.finishedValidation = YES; - if (self.agentInitiatedConnection) { + self->_finishedValidation = YES; + if (self->_agentInitiatedConnection) { [self retrieveProcessIdentifierAndStartInstallation]; } } @@ -245,60 +223,60 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; uint64_t progressValue = CFSwapInt64HostToLittle(*(uint64_t *)&progress); NSData *data = [NSData dataWithBytes:&progressValue length:sizeof(progressValue)]; - [self.communicator handleMessageWithIdentifier:SPUExtractedArchiveWithProgress data:data]; + [self->_communicator handleMessageWithIdentifier:SPUExtractedArchiveWithProgress data:data]; } }]; } } -- (void)clearUpdateDirectory +- (void)clearUpdateDirectory SPU_OBJC_DIRECT { - if (self.updateDirectoryPath != nil) { + if (_updateDirectoryPath != nil) { NSError *theError = nil; - if (![[[SUFileManager alloc] init] removeItemAtURL:[NSURL fileURLWithPath:self.updateDirectoryPath] error:&theError]) { + if (![[[SUFileManager alloc] init] removeItemAtURL:[NSURL fileURLWithPath:_updateDirectoryPath] error:&theError]) { SULog(SULogLevelError, @"Couldn't remove update folder: %@.", theError); } - self.updateDirectoryPath = nil; + _updateDirectoryPath = nil; } } -- (void)unarchiverDidFailWithError:(NSError *)error +- (void)unarchiverDidFailWithError:(NSError *)error SPU_OBJC_DIRECT { SULog(SULogLevelError, @"Failed to unarchive file"); SULogError(error); // No longer need update validator until next possible extraction (eg: if initial delta update fails) - self.updateValidator = nil; + _updateValidator = nil; // Client could try update again with different inputs // Eg: one common case is if a delta update fails, client may want to fall back to regular update // We really only need to set updateDirectoryPath to nil since that's the field we check if we've received installation data, // but may as well set other fields to nil too [self clearUpdateDirectory]; - self.downloadName = nil; - self.decryptionPassword = nil; - self.signatures = nil; - self.relaunchPath = nil; - self.host = nil; + _downloadName = nil; + _decryptionPassword = nil; + _signatures = nil; + _relaunchPath = nil; + _host = nil; NSData *archivedError = SPUArchiveRootObjectSecurely(error); - [self.communicator handleMessageWithIdentifier:SPUArchiveExtractionFailed data:archivedError != nil ? archivedError : [NSData data]]; + [_communicator handleMessageWithIdentifier:SPUArchiveExtractionFailed data:archivedError != nil ? archivedError : [NSData data]]; } - (void)agentConnectionDidInitiate { - self.agentInitiatedConnection = YES; - if (self.finishedValidation) { + _agentInitiatedConnection = YES; + if (_finishedValidation) { [self retrieveProcessIdentifierAndStartInstallation]; } } - (void)agentConnectionDidInvalidate { - if (!self.finishedValidation || !self.agentInitiatedConnection) { + if (!_finishedValidation || !_agentInitiatedConnection) { NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:@{ NSLocalizedDescriptionKey: @"Error: Agent connection invalidated before installation began" }]; - NSError *agentError = self.agentConnection.invalidationError; + NSError *agentError = _agentConnection.invalidationError; if (agentError != nil) { userInfo[NSUnderlyingErrorKey] = agentError; } @@ -307,21 +285,21 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; } } -- (void)retrieveProcessIdentifierAndStartInstallation +- (void)retrieveProcessIdentifierAndStartInstallation SPU_OBJC_DIRECT { // We use the relaunch path for the bundle to listen for termination instead of the host path // For a plug-in this makes a big difference; we want to wait until the app hosting the plug-in terminates // Otherwise for an app, the relaunch path and host path should be identical - [self.agentConnection.agent registerApplicationBundlePath:self.relaunchPath reply:^(NSNumber * _Nullable processIdentifier) { + [_agentConnection.agent registerApplicationBundlePath:_relaunchPath reply:^(NSNumber * _Nullable processIdentifier) { dispatch_async(dispatch_get_main_queue(), ^{ - self.terminationListener = [[TerminationListener alloc] initWithProcessIdentifier:processIdentifier]; + self->_terminationListener = [[TerminationListener alloc] initWithProcessIdentifier:processIdentifier]; [self startInstallation]; }); }]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(RETRIEVE_PROCESS_IDENTIFIER_TIMEOUT * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ - if (self.terminationListener == nil) { + if (self->_terminationListener == nil) { [self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: @"Timeout error: failed to retreive process identifier from agent" }]]; } }); @@ -329,11 +307,11 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; - (void)handleMessageWithIdentifier:(int32_t)identifier data:(NSData *)data { - if (identifier == SPUInstallationData && self.updateDirectoryPath == nil) { + if (identifier == SPUInstallationData && _updateDirectoryPath == nil) { dispatch_async(dispatch_get_main_queue(), ^{ // Mark that we have received the installation data - // Do not rely on eg: self.updateDirectoryPath != nil because we may set it to nil again if an early stage fails (i.e, archive extraction) - self.receivedInstallationData = YES; + // Do not rely on eg: self->_updateDirectoryPath != nil because we may set it to nil again if an early stage fails (i.e, archive extraction) + self->_receivedInstallationData = YES; SPUInstallationInputData *installationData = (SPUInstallationInputData *)SPUUnarchiveRootObjectSecurely(data, [SPUInstallationInputData class]); if (installationData == nil) { @@ -350,8 +328,8 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; NSBundle *hostBundle = [NSBundle bundleWithPath:installationData.hostBundlePath]; NSString *bundleIdentifier = hostBundle.bundleIdentifier; - if (bundleIdentifier == nil || ![bundleIdentifier isEqualToString:self.hostBundleIdentifier]) { - [self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Error: Failed to match host bundle identifiers %@ and %@", self.hostBundleIdentifier, bundleIdentifier] }]]; + if (bundleIdentifier == nil || ![bundleIdentifier isEqualToString:self->_hostBundleIdentifier]) { + [self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Error: Failed to match host bundle identifiers %@ and %@", self->_hostBundleIdentifier, bundleIdentifier] }]]; return; } @@ -409,23 +387,23 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; // Carry these properities separately rather than using the SUInstallationInputData object // Some of our properties may slightly differ than our input and we don't want to make the mistake of using one of those - self.installationType = installationType; - self.relaunchPath = installationData.relaunchPath; - self.downloadName = installationData.downloadName; - self.signatures = installationData.signatures; - self.updateDirectoryPath = cacheInstallationPath; - self.host = [[SUHost alloc] initWithBundle:hostBundle]; + self->_installationType = installationType; + self->_relaunchPath = installationData.relaunchPath; + self->_downloadName = installationData.downloadName; + self->_signatures = installationData.signatures; + self->_updateDirectoryPath = cacheInstallationPath; + self->_host = [[SUHost alloc] initWithBundle:hostBundle]; [self extractAndInstallUpdate]; }); } else if (identifier == SPUSentUpdateAppcastItemData) { SUAppcastItem *updateItem = (SUAppcastItem *)SPUUnarchiveRootObjectSecurely(data, [SUAppcastItem class]); if (updateItem != nil) { - SPUInstallationInfo *installationInfo = [[SPUInstallationInfo alloc] initWithAppcastItem:updateItem canSilentlyInstall:[self.installer canInstallSilently]]; + SPUInstallationInfo *installationInfo = [[SPUInstallationInfo alloc] initWithAppcastItem:updateItem canSilentlyInstall:[_installer canInstallSilently]]; NSData *archivedData = SPUArchiveRootObjectSecurely(installationInfo); if (archivedData != nil) { - [self.agentConnection.agent registerInstallationInfoData:archivedData]; + [_agentConnection.agent registerInstallationInfoData:archivedData]; } } } else if (identifier == SPUResumeInstallationToStage2 && data.length == sizeof(uint8_t) * 2) { @@ -435,21 +413,21 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; dispatch_async(dispatch_get_main_queue(), ^{ // This flag has an impact on interactive type installations and showing UI progress during non-interactive installations - self.shouldShowUI = (BOOL)showsUI; + self->_shouldShowUI = (BOOL)showsUI; // Don't test if the application was alive initially, leave that to the progress agent if we decide to relaunch - self.shouldRelaunch = (BOOL)relaunch; + self->_shouldRelaunch = (BOOL)relaunch; - if (self.performedStage1Installation) { + 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, ^{ - if (!self.performedStage2Installation) { + dispatch_async(self->_installerQueue, ^{ + if (!self->_performedStage2Installation) { [self performStage2Installation]; - } else if (!self.performedStage3Installation) { + } else if (!self->_performedStage3Installation) { // If we already performed the 2nd stage, re-purpose this request to re-try sending another termination signal dispatch_async(dispatch_get_main_queue(), ^{ // Don't check if the target is already terminated, leave that to the progress agent // We could be slightly off if there were multiple instances running - [self.agentConnection.agent sendTerminationSignal]; + [self->_agentConnection.agent sendTerminationSignal]; }); } }); @@ -460,19 +438,19 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; [self cleanupAndExitWithStatus:0 error:nil]; }); } else if (identifier == SPUUpdaterAlivePong) { - self.receivedUpdaterPong = YES; + _receivedUpdaterPong = YES; } } -- (void)startInstallation +- (void)startInstallation SPU_OBJC_DIRECT { - self.willCompleteInstallation = YES; + _willCompleteInstallation = YES; - self.installerQueue = dispatch_queue_create("org.sparkle-project.sparkle.installer", DISPATCH_QUEUE_SERIAL); + _installerQueue = dispatch_queue_create("org.sparkle-project.sparkle.installer", DISPATCH_QUEUE_SERIAL); - dispatch_async(self.installerQueue, ^{ + dispatch_async(_installerQueue, ^{ NSError *installerError = nil; - id installer = [SUInstaller installerForHost:self.host expectedInstallationType:self.installationType updateDirectory:self.updateDirectoryPath homeDirectory:self.homeDirectory userName:self.userName error:&installerError]; + id installer = [SUInstaller installerForHost:self->_host expectedInstallationType:self->_installationType updateDirectory:self->_updateDirectoryPath homeDirectory:self->_homeDirectory userName:self->_userName error:&installerError]; if (installer == nil) { dispatch_async(dispatch_get_main_queue(), ^{ @@ -483,7 +461,7 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; NSError *firstStageError = nil; if (![installer performInitialInstallation:&firstStageError]) { - self.installer = nil; + self->_installer = nil; dispatch_async(dispatch_get_main_queue(), ^{ [self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: @"Error: Failed to start installer", NSUnderlyingErrorKey: firstStageError }]]; @@ -494,17 +472,17 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; uint8_t canPerformSilentInstall = (uint8_t)[installer canInstallSilently]; dispatch_async(dispatch_get_main_queue(), ^{ - self.installer = installer; + self->_installer = installer; - uint8_t targetTerminated = (uint8_t)self.terminationListener.terminated; + uint8_t targetTerminated = (uint8_t)self->_terminationListener.terminated; uint8_t sendInformation[] = {canPerformSilentInstall, targetTerminated}; NSData *sendData = [NSData dataWithBytes:sendInformation length:sizeof(sendInformation)]; - [self.communicator handleMessageWithIdentifier:SPUInstallationFinishedStage1 data:sendData]; + [self->_communicator handleMessageWithIdentifier:SPUInstallationFinishedStage1 data:sendData]; - self.performedStage1Installation = YES; + self->_performedStage1Installation = YES; // Stage 2 can still be run before we finish installation // if the updater requests for it before the app is terminated @@ -513,24 +491,24 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; }); } -- (void)performStage2Installation +- (void)performStage2Installation SPU_OBJC_DIRECT { - BOOL canPerformSecondStage = self.shouldShowUI || [self.installer canInstallSilently]; + BOOL canPerformSecondStage = _shouldShowUI || [_installer canInstallSilently]; if (canPerformSecondStage) { - self.performedStage2Installation = YES; + _performedStage2Installation = YES; dispatch_async(dispatch_get_main_queue(), ^{ - uint8_t targetTerminated = (uint8_t)self.terminationListener.terminated; + uint8_t targetTerminated = (uint8_t)self->_terminationListener.terminated; NSData *sendData = [NSData dataWithBytes:&targetTerminated length:sizeof(targetTerminated)]; - [self.communicator handleMessageWithIdentifier:SPUInstallationFinishedStage2 data:sendData]; + [self->_communicator handleMessageWithIdentifier:SPUInstallationFinishedStage2 data:sendData]; // Don't check if the target is already terminated, leave that to the progress agent // We could be slightly off if there were multiple instances running - [self.agentConnection.agent sendTerminationSignal]; + [self->_agentConnection.agent sendTerminationSignal]; }); } else { - self.installer = nil; + _installer = nil; dispatch_async(dispatch_get_main_queue(), ^{ [self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: @"Error: Failed to resume installer on stage 2 because installation cannot be installed silently" }]]; @@ -538,9 +516,9 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; } } -- (void)finishInstallationAfterHostTermination +- (void)finishInstallationAfterHostTermination SPU_OBJC_DIRECT { - [self.terminationListener startListeningWithCompletion:^(BOOL success) { + [_terminationListener startListeningWithCompletion:^(BOOL success) { if (!success) { [self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: @"Failed to listen for application termination" }]]; return; @@ -549,38 +527,38 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; // Show our installer progress UI tool if only after a certain amount of time passes, // and if our installer is silent (i.e, doesn't show progress on its own) __block BOOL shouldShowUIProgress = YES; - if (self.shouldShowUI && [self.installer canInstallSilently]) { + if (self->_shouldShowUI && [self->_installer canInstallSilently]) { // Ask the updater if it is still alive // If they are, we will receive a pong response back // Reset if we received a pong just to be on the safe side - self.receivedUpdaterPong = NO; - [self.communicator handleMessageWithIdentifier:SPUUpdaterAlivePing data:[NSData data]]; + self->_receivedUpdaterPong = NO; + [self->_communicator handleMessageWithIdentifier:SPUUpdaterAlivePing data:[NSData data]]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(SUDisplayProgressTimeDelay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ // Make sure we're still eligible for showing the installer progress // Also if the updater process is still alive, showing the progress should not be our duty // if the communicator object is nil, the updater definitely isn't alive. However, if it is not nil, // this does not necessarily mean the updater is alive, so we should also check if we got a recent response back from the updater - if (shouldShowUIProgress && (!self.receivedUpdaterPong || self.communicator == nil)) { - [self.agentConnection.agent showProgress]; + if (shouldShowUIProgress && (!self->_receivedUpdaterPong || self->_communicator == nil)) { + [self->_agentConnection.agent showProgress]; } }); } - dispatch_async(self.installerQueue, ^{ - if (!self.performedStage2Installation) { + dispatch_async(self->_installerQueue, ^{ + if (!self->_performedStage2Installation) { [self performStage2Installation]; } - if (!self.performedStage2Installation) { + if (!self->_performedStage2Installation) { // We failed and we're going to exit shortly return; } NSError *thirdStageError = nil; - if (![self.installer performFinalInstallationProgressBlock:nil error:&thirdStageError]) { - [self.installer performCleanup]; - self.installer = nil; + if (![self->_installer performFinalInstallationProgressBlock:nil error:&thirdStageError]) { + [self->_installer performCleanup]; + self->_installer = nil; dispatch_async(dispatch_get_main_queue(), ^{ [self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SPUInstallerError userInfo:@{ NSLocalizedDescriptionKey: @"Failed to finalize installation", NSUnderlyingErrorKey: thirdStageError }]]; @@ -588,23 +566,23 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; return; } - self.performedStage3Installation = YES; + self->_performedStage3Installation = YES; dispatch_async(dispatch_get_main_queue(), ^{ // Make sure to stop our displayed progress before we move onto cleanup & relaunch // This will also stop the agent from broadcasting the status info service, which we want to do before // we relaunch the app because the relaunched app could check the service upon launch.. - [self.agentConnection.agent stopProgress]; + [self->_agentConnection.agent stopProgress]; shouldShowUIProgress = NO; - [self.communicator handleMessageWithIdentifier:SPUInstallationFinishedStage3 data:[NSData data]]; + [self->_communicator handleMessageWithIdentifier:SPUInstallationFinishedStage3 data:[NSData data]]; - if (self.shouldRelaunch) { + if (self->_shouldRelaunch) { // This will also signal to the agent that it will terminate soon - [self.agentConnection.agent relaunchApplication]; + [self->_agentConnection.agent relaunchApplication]; } - [self.installer performCleanup]; + [self->_installer performCleanup]; [self cleanupAndExitWithStatus:EXIT_SUCCESS error:nil]; }); @@ -619,20 +597,20 @@ static const NSTimeInterval SUDisplayProgressTimeDelay = 0.7; NSData *errorData = SPUArchiveRootObjectSecurely((NSError * _Nonnull)error); if (errorData != nil) { - [self.communicator handleMessageWithIdentifier:SPUInstallerError data:errorData]; + [_communicator handleMessageWithIdentifier:SPUInstallerError data:errorData]; } } // It's nice to tell the other end we're invalidating - [self.activeConnection invalidate]; - self.activeConnection = nil; + [_activeConnection invalidate]; + _activeConnection = nil; - [self.xpcListener invalidate]; - self.xpcListener = nil; + [_xpcListener invalidate]; + _xpcListener = nil; - [self.agentConnection invalidate]; - self.agentConnection = nil; + [_agentConnection invalidate]; + _agentConnection = nil; [self clearUpdateDirectory]; diff --git a/Autoupdate/SPUDeltaArchive.m b/Autoupdate/SPUDeltaArchive.m index d8a41289..ca7ade75 100644 --- a/Autoupdate/SPUDeltaArchive.m +++ b/Autoupdate/SPUDeltaArchive.m @@ -23,6 +23,7 @@ id SPUDeltaArchiveReadPatchAndHeader(NSString *patchFil SPUDeltaArchiveHeader *header = [sparkleArchive readHeader]; if (header == nil) { +#if SPARKLE_BUILD_LEGACY_DELTA_SUPPORT NSError *archiveError = sparkleArchive.error; if (archiveError != nil && [archiveError.domain isEqualToString:SPARKLE_DELTA_ARCHIVE_ERROR_DOMAIN] && archiveError.code == SPARKLE_DELTA_ARCHIVE_ERROR_CODE_BAD_MAGIC) { // Retry with XAR archive if the magic value is unexpected @@ -35,7 +36,9 @@ id SPUDeltaArchiveReadPatchAndHeader(NSString *patchFil *outHeader = xarHeader; } return xarArchive; - } else { + } else +#endif + { if (outHeader != NULL) { *outHeader = nil; } @@ -56,7 +59,9 @@ id SPUDeltaArchiveReadPatchAndHeader(NSString *patchFil @synthesize clonedRelativePath = _clonedRelativePath; @synthesize sourcePath = _sourcePath; @synthesize commands = _commands; +#if SPARKLE_BUILD_LEGACY_DELTA_SUPPORT @synthesize xarContext = _xarContext; +#endif @synthesize mode = _mode; @synthesize codedDataLength = _codedDataLength; @@ -103,9 +108,6 @@ id SPUDeltaArchiveReadPatchAndHeader(NSString *patchFil return self; } -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdirect-ivar-access" - - (unsigned char *)beforeTreeHash { return _beforeTreeHash; @@ -116,6 +118,4 @@ id SPUDeltaArchiveReadPatchAndHeader(NSString *patchFil return _afterTreeHash; } -#pragma clang diagnostic pop - @end diff --git a/Autoupdate/SPUDeltaArchiveProtocol.h b/Autoupdate/SPUDeltaArchiveProtocol.h index a9db5da3..606908c0 100644 --- a/Autoupdate/SPUDeltaArchiveProtocol.h +++ b/Autoupdate/SPUDeltaArchiveProtocol.h @@ -24,7 +24,7 @@ typedef NS_ENUM(uint8_t, SPUDeltaItemCommands) { }; // Represents header for our archive -@interface SPUDeltaArchiveHeader : NSObject +SPU_OBJC_DIRECT_MEMBERS @interface SPUDeltaArchiveHeader : NSObject - (instancetype)initWithCompression:(SPUDeltaCompressionMode)compression compressionLevel:(uint8_t)compressionLevel fileSystemCompression:(bool)fileSystemCompression majorVersion:(uint16_t)majorVersion minorVersion:(uint16_t)minorVersion beforeTreeHash:(const unsigned char *)beforeTreeHash afterTreeHash:(const unsigned char *)afterTreeHash; @@ -39,7 +39,7 @@ typedef NS_ENUM(uint8_t, SPUDeltaItemCommands) { @end // Represents an item we read or write to in our delta archive -@interface SPUDeltaArchiveItem : NSObject +SPU_OBJC_DIRECT_MEMBERS @interface SPUDeltaArchiveItem : NSObject - (instancetype)initWithRelativeFilePath:(NSString *)relativeFilePath commands:(SPUDeltaItemCommands)commands mode:(uint16_t)mode; @@ -58,8 +58,10 @@ typedef NS_ENUM(uint8_t, SPUDeltaItemCommands) { @property (nonatomic) uint16_t mode; // Private properties +#if SPARKLE_BUILD_LEGACY_DELTA_SUPPORT // xar_file context for Xar delta archiver @property (nonatomic, nullable) const void *xarContext; +#endif // Tracking length of item's data in data section, when encoding items and when extracting items @property (nonatomic) uint64_t codedDataLength; diff --git a/Autoupdate/SPUInstallationInfo.h b/Autoupdate/SPUInstallationInfo.h index e0c4f2db..5f364839 100644 --- a/Autoupdate/SPUInstallationInfo.h +++ b/Autoupdate/SPUInstallationInfo.h @@ -12,7 +12,7 @@ NS_ASSUME_NONNULL_BEGIN @class SUAppcastItem; -@interface SPUInstallationInfo : NSObject +SPU_OBJC_DIRECT_MEMBERS @interface SPUInstallationInfo : NSObject - (instancetype)initWithAppcastItem:(SUAppcastItem *)appcastItem canSilentlyInstall:(BOOL)canSilentyInstall; diff --git a/Autoupdate/SPUInstallationInfo.m b/Autoupdate/SPUInstallationInfo.m index 6e8e51d9..b7aa8989 100644 --- a/Autoupdate/SPUInstallationInfo.m +++ b/Autoupdate/SPUInstallationInfo.m @@ -52,9 +52,9 @@ static NSString *SUSystemDomainKey = @"SUSystemDomain"; - (void)encodeWithCoder:(NSCoder *)coder { - [coder encodeObject:self.appcastItem forKey:SUAppcastItemKey]; - [coder encodeBool:self.canSilentlyInstall forKey:SUCanSilentlyInstallKey]; - [coder encodeBool:self.systemDomain forKey:SUSystemDomainKey]; + [coder encodeObject:_appcastItem forKey:SUAppcastItemKey]; + [coder encodeBool:_canSilentlyInstall forKey:SUCanSilentlyInstallKey]; + [coder encodeBool:_systemDomain forKey:SUSystemDomainKey]; } + (BOOL)supportsSecureCoding diff --git a/Autoupdate/SPUInstallationInputData.h b/Autoupdate/SPUInstallationInputData.h index 849805a0..88c07142 100644 --- a/Autoupdate/SPUInstallationInputData.h +++ b/Autoupdate/SPUInstallationInputData.h @@ -12,7 +12,7 @@ NS_ASSUME_NONNULL_BEGIN -@interface SPUInstallationInputData : NSObject +SPU_OBJC_DIRECT_MEMBERS @interface SPUInstallationInputData : NSObject /* * relaunchPath - path to application bundle to relaunch and listen for termination diff --git a/Autoupdate/SPUInstallationInputData.m b/Autoupdate/SPUInstallationInputData.m index c4714729..ea82f937 100644 --- a/Autoupdate/SPUInstallationInputData.m +++ b/Autoupdate/SPUInstallationInputData.m @@ -87,14 +87,14 @@ static NSString *SUInstallationTypeKey = @"SUInstallationType"; - (void)encodeWithCoder:(NSCoder *)coder { - [coder encodeObject:self.relaunchPath forKey:SURelaunchPathKey]; - [coder encodeObject:self.hostBundlePath forKey:SUHostBundlePathKey]; - [coder encodeObject:self.updateDirectoryPath forKey:SUUpdateDirectoryPathKey]; - [coder encodeObject:self.installationType forKey:SUInstallationTypeKey]; - [coder encodeObject:self.downloadName forKey:SUDownloadNameKey]; - [coder encodeObject:self.signatures forKey:SUSignaturesKey]; - if (self.decryptionPassword != nil) { - [coder encodeObject:self.decryptionPassword forKey:SUDecryptionPasswordKey]; + [coder encodeObject:_relaunchPath forKey:SURelaunchPathKey]; + [coder encodeObject:_hostBundlePath forKey:SUHostBundlePathKey]; + [coder encodeObject:_updateDirectoryPath forKey:SUUpdateDirectoryPathKey]; + [coder encodeObject:_installationType forKey:SUInstallationTypeKey]; + [coder encodeObject:_downloadName forKey:SUDownloadNameKey]; + [coder encodeObject:_signatures forKey:SUSignaturesKey]; + if (_decryptionPassword != nil) { + [coder encodeObject:_decryptionPassword forKey:SUDecryptionPasswordKey]; } } diff --git a/Autoupdate/SPUSparkleDeltaArchive.h b/Autoupdate/SPUSparkleDeltaArchive.h index c741ab2c..48c6a0e4 100644 --- a/Autoupdate/SPUSparkleDeltaArchive.h +++ b/Autoupdate/SPUSparkleDeltaArchive.h @@ -97,7 +97,7 @@ NS_ASSUME_NONNULL_BEGIN (P number of blobs where P <= M commands) (Indexes for data blobs correspond to indexes for a filtered list of applicable commands (EXTRACT_FILE, BINARY_DIFF_FILE) that have data content) */ -@interface SPUSparkleDeltaArchive : NSObject +SPU_OBJC_DIRECT_MEMBERS @interface SPUSparkleDeltaArchive : NSObject - (instancetype)initWithPatchFileForWriting:(NSString *)patchFile; - (instancetype)initWithPatchFileForReading:(NSString *)patchFile; diff --git a/Autoupdate/SPUSparkleDeltaArchive.m b/Autoupdate/SPUSparkleDeltaArchive.m index b5d4b2ec..cb71c73c 100644 --- a/Autoupdate/SPUSparkleDeltaArchive.m +++ b/Autoupdate/SPUSparkleDeltaArchive.m @@ -7,12 +7,15 @@ // #import "SPUSparkleDeltaArchive.h" -#import #import #import #import "SUBinaryDeltaCommon.h" #import +#if SPARKLE_BUILD_BZIP2_DELTA_SUPPORT +#import +#endif + #include "AppKitPrevention.h" #define SPARKLE_DELTA_FORMAT_MAGIC "spk!" @@ -28,39 +31,26 @@ typedef struct bool fileSystemCompression : 1; } SparkleDeltaArchiveMetadata; -@interface SPUSparkleDeltaArchive () - -@property (nonatomic) FILE *file; -@property (nonatomic) BZFILE *bzipFile; -@property (nonatomic) compression_stream compressionStream; -@property (nonatomic) BOOL initializedCompressionStream; -@property (nonatomic, readonly) NSString *patchFile; -@property (nonatomic) SPUDeltaCompressionMode compression; -@property (nonatomic, readonly) BOOL writeMode; -@property (nonatomic) NSError *error; -@property (nonatomic) void *partialChunkBuffer; -@property (nonatomic) void *compressionBuffer; - -@property (nonatomic) NSMutableArray *writableItems; - -@end - -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdirect-ivar-access" - @implementation SPUSparkleDeltaArchive +{ + FILE *_file; +#if SPARKLE_BUILD_BZIP2_DELTA_SUPPORT + BZFILE *_bzipFile; +#endif + NSString *_patchFile; + NSError *_error; + void *_partialChunkBuffer; + void *_compressionBuffer; + NSMutableArray *_writableItems; + + compression_stream _compressionStream; + SPUDeltaCompressionMode _compression; + + BOOL _initializedCompressionStream; + BOOL _writeMode; +} -@synthesize file = _file; -@synthesize bzipFile = _bzipFile; -@synthesize compressionStream = _compressionStream; -@synthesize initializedCompressionStream = _initializedCompressionStream; -@synthesize patchFile = _patchFile; -@synthesize compression = _compression; -@synthesize writeMode = _writeMode; -@synthesize writableItems = _writableItems; @synthesize error = _error; -@synthesize partialChunkBuffer = _partialChunkBuffer; -@synthesize compressionBuffer = _compressionBuffer; + (BOOL)maySupportSafeExtraction { @@ -94,42 +84,45 @@ typedef struct - (void)close { - if (self.bzipFile != NULL) { - if (!self.writeMode) { +#if SPARKLE_BUILD_BZIP2_DELTA_SUPPORT + if (_bzipFile != NULL) { + if (!_writeMode) { int bzerror = 0; - BZ2_bzReadClose(&bzerror, self.bzipFile); + BZ2_bzReadClose(&bzerror, _bzipFile); } - self.bzipFile = NULL; - } else if (self.initializedCompressionStream) { + _bzipFile = NULL; + } else +#endif + if (_initializedCompressionStream) { compression_stream_destroy(&_compressionStream); - self.initializedCompressionStream = NO; + _initializedCompressionStream = NO; } - if (self.file != NULL) { - fclose(self.file); - self.file = NULL; + if (_file != NULL) { + fclose(_file); + _file = NULL; } - free(self.partialChunkBuffer); - self.partialChunkBuffer = NULL; + free(_partialChunkBuffer); + _partialChunkBuffer = NULL; - free(self.compressionBuffer); - self.compressionBuffer = NULL; + free(_compressionBuffer); + _compressionBuffer = NULL; } -- (BOOL)createBuffers +- (BOOL)createBuffers SPU_OBJC_DIRECT { - self.partialChunkBuffer = calloc(1, PARTIAL_IO_CHUNK_SIZE); - if (self.partialChunkBuffer == NULL) { - self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to calloc() %d bytes for partial chunk buffer.", PARTIAL_IO_CHUNK_SIZE] }]; + _partialChunkBuffer = calloc(1, PARTIAL_IO_CHUNK_SIZE); + if (_partialChunkBuffer == NULL) { + _error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to calloc() %d bytes for partial chunk buffer.", PARTIAL_IO_CHUNK_SIZE] }]; return NO; } - if (self.initializedCompressionStream) { - self.compressionBuffer = calloc(1, COMPRESSION_BUFFER_SIZE); - if (self.compressionBuffer == NULL) { - self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to calloc() %d bytes for compression buffer.", COMPRESSION_BUFFER_SIZE] }]; + if (_initializedCompressionStream) { + _compressionBuffer = calloc(1, COMPRESSION_BUFFER_SIZE); + if (_compressionBuffer == NULL) { + _error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to calloc() %d bytes for compression buffer.", COMPRESSION_BUFFER_SIZE] }]; return NO; } } @@ -137,48 +130,53 @@ typedef struct return YES; } -- (BOOL)_readBuffer:(void *)buffer length:(int32_t)length +- (BOOL)_readBuffer:(void *)buffer length:(int32_t)length SPU_OBJC_DIRECT { - if (self.error != nil) { + if (_error != nil) { return NO; } - switch (self.compression) { + switch (_compression) { case SPUDeltaCompressionModeNone: { - if (fread(buffer, (size_t)length, 1, self.file) < 1) { - self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to read %d uncompressed bytes from archive.", length] }]; + if (fread(buffer, (size_t)length, 1, _file) < 1) { + _error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to read %d uncompressed bytes from archive.", length] }]; return NO; } else { return YES; } } - case SPUDeltaCompressionModeBzip2: { + case SPUDeltaCompressionModeBzip2: + { +#if SPARKLE_BUILD_BZIP2_DELTA_SUPPORT int bzerror = 0; - int bytesRead = BZ2_bzRead(&bzerror, self.bzipFile, buffer, length); + int bytesRead = BZ2_bzRead(&bzerror, _bzipFile, buffer, length); switch (bzerror) { case BZ_OK: case BZ_STREAM_END: if (bytesRead < length) { - self.error = [NSError errorWithDomain:SPARKLE_BZIP2_ERROR_DOMAIN code:0 userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Only %d out of %d expected bytes were read from the bz2 archive.", bytesRead, length] }]; + _error = [NSError errorWithDomain:SPARKLE_BZIP2_ERROR_DOMAIN code:0 userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Only %d out of %d expected bytes were read from the bz2 archive.", bytesRead, length] }]; return NO; } else { return YES; } case BZ_IO_ERROR: - self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: @"Encountered unexpected IO error when reading compressed bytes from bz2 archive." }]; + _error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: @"Encountered unexpected IO error when reading compressed bytes from bz2 archive." }]; return NO; default: - self.error = [NSError errorWithDomain:SPARKLE_BZIP2_ERROR_DOMAIN code:bzerror userInfo:@{ NSLocalizedDescriptionKey: @"Encountered unexpected error when reading compressed bytes from bz2 archive." }]; + _error = [NSError errorWithDomain:SPARKLE_BZIP2_ERROR_DOMAIN code:bzerror userInfo:@{ NSLocalizedDescriptionKey: @"Encountered unexpected error when reading compressed bytes from bz2 archive." }]; return NO; } +#else + return NO; +#endif } case SPUDeltaCompressionModeLZMA: case SPUDeltaCompressionModeLZFSE: case SPUDeltaCompressionModeLZ4: case SPUDeltaCompressionModeZLIB: { - FILE *file = self.file; - void *compressionBuffer = self.compressionBuffer; + FILE *file = _file; + void *compressionBuffer = _compressionBuffer; _compressionStream.dst_ptr = buffer; _compressionStream.dst_size = (size_t)length; @@ -190,7 +188,7 @@ typedef struct size_t bytesRead = fread(compressionBuffer, 1, COMPRESSION_BUFFER_SIZE, file); if (bytesRead < COMPRESSION_BUFFER_SIZE) { if (feof(file) == 0) { - self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to read %d compressed raw bytes from archive.", length] }]; + _error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to read %d compressed raw bytes from archive.", length] }]; return NO; } } @@ -202,13 +200,13 @@ typedef struct compression_status status = compression_stream_process(&_compressionStream, feof(file) != 0 ? COMPRESSION_STREAM_FINALIZE : 0); if (status == COMPRESSION_STATUS_ERROR) { - self.error = [NSError errorWithDomain:SPARKLE_COMPRESSION_ERROR_DOMAIN code:COMPRESSION_STATUS_ERROR userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to read %d compressed bytes.", length] }]; + _error = [NSError errorWithDomain:SPARKLE_COMPRESSION_ERROR_DOMAIN code:COMPRESSION_STATUS_ERROR userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to read %d compressed bytes.", length] }]; return NO; } if (status == COMPRESSION_STATUS_END && _compressionStream.dst_size > 0) { // We're expecting more bytes but we can't read any more bytes - self.error = [NSError errorWithDomain:SPARKLE_DELTA_ARCHIVE_ERROR_DOMAIN code:-1 userInfo:@{ NSLocalizedDescriptionKey: @"Failed to decompress and read bytes because we reached EOF" }]; + _error = [NSError errorWithDomain:SPARKLE_DELTA_ARCHIVE_ERROR_DOMAIN code:-1 userInfo:@{ NSLocalizedDescriptionKey: @"Failed to decompress and read bytes because we reached EOF" }]; return NO; } } @@ -239,44 +237,44 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod - (nullable SPUDeltaArchiveHeader *)readHeader { - NSString *patchFile = self.patchFile; + NSString *patchFile = _patchFile; char patchFilePath[PATH_MAX + 1] = {0}; if (![patchFile getFileSystemRepresentation:patchFilePath maxLength:sizeof(patchFilePath) - 1]) { - self.error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to open and represent as a file system representation: %@", patchFile] }]; + _error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to open and represent as a file system representation: %@", patchFile] }]; return nil; } FILE *file = fopen(patchFilePath, "rb"); if (file == NULL) { - self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to open patch file for writing value due to io error: %@", patchFile] }]; + _error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to open patch file for writing value due to io error: %@", patchFile] }]; return nil; } - self.file = file; + _file = file; char magic[5] = {0}; if (fread(magic, sizeof(magic) - 1, 1, file) < 1) { - self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to read magic value from patch file: %@", patchFile] }]; + _error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to read magic value from patch file: %@", patchFile] }]; return nil; } if (strncmp(magic, SPARKLE_DELTA_FORMAT_MAGIC, sizeof(magic) - 1) != 0) { - self.error = [NSError errorWithDomain:SPARKLE_DELTA_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_ARCHIVE_ERROR_CODE_BAD_MAGIC userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Patch file does not have '%@' magic value", @SPARKLE_DELTA_FORMAT_MAGIC] }]; + _error = [NSError errorWithDomain:SPARKLE_DELTA_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_ARCHIVE_ERROR_CODE_BAD_MAGIC userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Patch file does not have '%@' magic value", @SPARKLE_DELTA_FORMAT_MAGIC] }]; return nil; } SPUDeltaCompressionMode compression = 0; if (fread(&compression, sizeof(compression), 1, file) < 1) { - self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to read compression value from patch file: %@", patchFile] }]; + _error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to read compression value from patch file: %@", patchFile] }]; return nil; } - self.compression = compression; + _compression = compression; SparkleDeltaArchiveMetadata metadata = {0}; if (fread(&metadata, sizeof(metadata), 1, file) < 1) { - self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to read compression level value from patch file: %@", patchFile] }]; + _error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to read compression level value from patch file: %@", patchFile] }]; return nil; } @@ -284,40 +282,45 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod case SPUDeltaCompressionModeNone: break; case SPUDeltaCompressionModeBzip2: { +#if SPARKLE_BUILD_BZIP2_DELTA_SUPPORT int bzerror = 0; BZFILE *bzipFile = BZ2_bzReadOpen(&bzerror, file, 0, 0, NULL, 0); if (bzipFile == NULL) { switch (bzerror) { case BZ_IO_ERROR: - self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to open patch as bz2 file due to io error: %@", patchFile] }]; + _error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to open patch as bz2 file due to io error: %@", patchFile] }]; break; default: - self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:bzerror userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to open patch as bz2 file: %@", patchFile] }]; + _error = [NSError errorWithDomain:NSPOSIXErrorDomain code:bzerror userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to open patch as bz2 file: %@", patchFile] }]; break; } return nil; } - self.bzipFile = bzipFile; + _bzipFile = bzipFile; break; +#else + _error = [NSError errorWithDomain:SPARKLE_BZIP2_ERROR_DOMAIN code:-1 userInfo:@{ NSLocalizedDescriptionKey: @"Failed to open patch as bz2 file because bzip2 support is disabled" }]; + return nil; +#endif } case SPUDeltaCompressionModeLZMA: case SPUDeltaCompressionModeLZFSE: case SPUDeltaCompressionModeLZ4: case SPUDeltaCompressionModeZLIB: { if (compression_stream_init(&_compressionStream, COMPRESSION_STREAM_DECODE, _compressionAlgorithmForMode(compression)) != COMPRESSION_STATUS_OK) { - self.error = [NSError errorWithDomain:SPARKLE_COMPRESSION_ERROR_DOMAIN code:COMPRESSION_STATUS_ERROR userInfo:@{ NSLocalizedDescriptionKey: @"Failed to open compression stream for reading" }]; + _error = [NSError errorWithDomain:SPARKLE_COMPRESSION_ERROR_DOMAIN code:COMPRESSION_STATUS_ERROR userInfo:@{ NSLocalizedDescriptionKey: @"Failed to open compression stream for reading" }]; return nil; } - self.initializedCompressionStream = YES; + _initializedCompressionStream = YES; break; } default: - self.error = [NSError errorWithDomain:SPARKLE_DELTA_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_ARCHIVE_ERROR_CODE_BAD_COMPRESSION_VALUE userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Compression value read %d is not recognized.", compression] }]; + _error = [NSError errorWithDomain:SPARKLE_DELTA_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_ARCHIVE_ERROR_CODE_BAD_COMPRESSION_VALUE userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Compression value read %d is not recognized.", compression] }]; return nil; } @@ -348,9 +351,9 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod return [[SPUDeltaArchiveHeader alloc] initWithCompression:compression compressionLevel:metadata.compressionLevel fileSystemCompression:metadata.fileSystemCompression majorVersion:majorVersion minorVersion:minorVersion beforeTreeHash:beforeTreeHash afterTreeHash:afterTreeHash]; } -- (NSArray *)_readRelativeFilePaths +- (NSArray *)_readRelativeFilePaths SPU_OBJC_DIRECT { - if (self.error != nil) { + if (_error != nil) { return nil; } @@ -366,7 +369,7 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod char *fileTableData = calloc(1, filePathSectionSize); if (fileTableData == NULL) { - self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to calloc() %llu bytes for relative file paths.", filePathSectionSize] }]; + _error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to calloc() %llu bytes for relative file paths.", filePathSectionSize] }]; return nil; } @@ -393,7 +396,7 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod if (fileTableData[index] == '\0') { NSString *relativePath = [fileManager stringWithFileSystemRepresentation:&fileTableData[currentStartIndex] length:index - currentStartIndex]; if (relativePath == nil) { - self.error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Relative path cannot be decoded as a file system representation: %@", relativePath] }]; + _error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Relative path cannot be decoded as a file system representation: %@", relativePath] }]; free(fileTableData); return nil; @@ -425,7 +428,7 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod if (relativeFilePaths.count > UINT32_MAX) { // Very unlikely but we should guard against this // Clones rely on 32-bit indexes - self.error = [NSError errorWithDomain:SPARKLE_DELTA_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_ARCHIVE_ERROR_CODE_TOO_MANY_FILES userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"There are too many file entries to apply a patch for (more than %u)", UINT32_MAX] }]; + _error = [NSError errorWithDomain:SPARKLE_DELTA_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_ARCHIVE_ERROR_CODE_TOO_MANY_FILES userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"There are too many file entries to apply a patch for (more than %u)", UINT32_MAX] }]; return; } @@ -464,7 +467,7 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod } if ((NSUInteger)cloneRelativePathIndex >= relativeFilePaths.count) { - self.error = [NSError errorWithDomain:SPARKLE_DELTA_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_ARCHIVE_ERROR_CODE_BAD_CLONE_LOOKUP userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Index %u is past relative path table bounds of length %lu", cloneRelativePathIndex, (unsigned long)relativeFilePaths.count] }]; + _error = [NSError errorWithDomain:SPARKLE_DELTA_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_ARCHIVE_ERROR_CODE_BAD_CLONE_LOOKUP userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Index %u is past relative path table bounds of length %lu", cloneRelativePathIndex, (unsigned long)relativeFilePaths.count] }]; break; } @@ -525,7 +528,7 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod } } - if (self.error != nil) { + if (_error != nil) { return; } @@ -563,13 +566,13 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod char itemFilePathString[PATH_MAX + 1] = {0}; if (![itemFilePath getFileSystemRepresentation:itemFilePathString maxLength:sizeof(itemFilePathString) - 1]) { - self.error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Path to extract cannot be decoded and expressed as a file system representation: %@", itemFilePath] }]; + _error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Path to extract cannot be decoded and expressed as a file system representation: %@", itemFilePath] }]; return NO; } FILE *outputFile = fopen(itemFilePathString, "wb"); if (outputFile == NULL) { - self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to fopen() %@", itemFilePath] }]; + _error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to fopen() %@", itemFilePath] }]; return NO; } @@ -580,14 +583,14 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod while (bytesLeftoverToCopy > 0) { uint64_t currentBlockSize = (bytesLeftoverToCopy >= PARTIAL_IO_CHUNK_SIZE) ? PARTIAL_IO_CHUNK_SIZE : bytesLeftoverToCopy; - void *tempBuffer = self.partialChunkBuffer; + void *tempBuffer = _partialChunkBuffer; if (![self _readBuffer:tempBuffer length:(int32_t)currentBlockSize]) { break; } if (fwrite(tempBuffer, currentBlockSize, 1, outputFile) < 1) { - self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to fwrite() %llu bytes during extraction.", currentBlockSize] }]; + _error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to fwrite() %llu bytes during extraction.", currentBlockSize] }]; break; } @@ -597,12 +600,12 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod fclose(outputFile); - if (self.error != nil) { + if (_error != nil) { return NO; } if ((commands & SPUDeltaItemCommandExtract) != 0 && chmod(itemFilePathString, mode) != 0) { - self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to chmod() mode %d on %@", mode, itemFilePath] }]; + _error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to chmod() mode %d on %@", mode, itemFilePath] }]; return NO; } } else { @@ -610,13 +613,13 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod if (PARTIAL_IO_CHUNK_SIZE < decodedLength) { // Something is seriously wrong - self.error = [NSError errorWithDomain:SPARKLE_DELTA_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_ARCHIVE_ERROR_CODE_BAD_CHUNK_SIZE userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"PARTIAL_IO_CHUNK_SIZE (%d) < decodedLength (%llu)", PARTIAL_IO_CHUNK_SIZE, decodedLength] }]; + _error = [NSError errorWithDomain:SPARKLE_DELTA_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_ARCHIVE_ERROR_CODE_BAD_CHUNK_SIZE userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"PARTIAL_IO_CHUNK_SIZE (%d) < decodedLength (%llu)", PARTIAL_IO_CHUNK_SIZE, decodedLength] }]; return NO; } if (decodedLength > PATH_MAX) { // Link is too long - self.error = [NSError errorWithDomain:SPARKLE_DELTA_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_ARCHIVE_ERROR_CODE_LINK_TOO_LONG userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Decoded length for link (%llu) is too long.", decodedLength] }]; + _error = [NSError errorWithDomain:SPARKLE_DELTA_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_ARCHIVE_ERROR_CODE_LINK_TOO_LONG userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Decoded length for link (%llu) is too long.", decodedLength] }]; return NO; } @@ -628,7 +631,7 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod NSString *destinationPath = [fileManager stringWithFileSystemRepresentation:buffer length:decodedLength]; if (destinationPath == nil) { - self.error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Destination path for link %@ cannot be created in a file system representation: %@",itemFilePath, destinationPath] }]; + _error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Destination path for link %@ cannot be created in a file system representation: %@",itemFilePath, destinationPath] }]; return NO; } @@ -636,13 +639,13 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod NSError *createLinkError = nil; if (![fileManager createSymbolicLinkAtPath:itemFilePath withDestinationPath:destinationPath error:&createLinkError]) { - self.error = createLinkError; + _error = createLinkError; return NO; } char itemFilePathString[PATH_MAX + 1] = {0}; if (![itemFilePath getFileSystemRepresentation:itemFilePathString maxLength:sizeof(itemFilePathString) - 1]) { - self.error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Link path to extract cannot be decoded and expressed as a file system representation: %@", itemFilePath] }]; + _error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Link path to extract cannot be decoded and expressed as a file system representation: %@", itemFilePath] }]; return NO; } @@ -654,7 +657,7 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod } else if (S_ISDIR(mode)) { NSError *createDirectoryError = nil; if (![fileManager createDirectoryAtPath:itemFilePath withIntermediateDirectories:NO attributes:@{NSFilePosixPermissions: @(mode)} error:&createDirectoryError]) { - self.error = createDirectoryError; + _error = createDirectoryError; return NO; } } @@ -662,34 +665,39 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod return YES; } -- (BOOL)_writeBuffer:(void *)buffer length:(int32_t)length +- (BOOL)_writeBuffer:(void *)buffer length:(int32_t)length SPU_OBJC_DIRECT { - if (self.error != nil) { + if (_error != nil) { return NO; } - switch (self.compression) { + switch (_compression) { case SPUDeltaCompressionModeNone: { - BOOL success = (fwrite(buffer, (size_t)length, 1, self.file) == 1); + BOOL success = (fwrite(buffer, (size_t)length, 1, _file) == 1); if (!success) { - self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to write %d uncompressed bytes.", length] }]; + _error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to write %d uncompressed bytes.", length] }]; } return success; } - case SPUDeltaCompressionModeBzip2: { + case SPUDeltaCompressionModeBzip2: + { +#if SPARKLE_BUILD_BZIP2_DELTA_SUPPORT int bzerror = 0; - BZ2_bzWrite(&bzerror, self.bzipFile, buffer, length); + BZ2_bzWrite(&bzerror, _bzipFile, buffer, length); switch (bzerror) { case BZ_OK: return YES; case BZ_IO_ERROR: - self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to write %d compressed bz2 bytes due to io error.", length] }]; + _error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to write %d compressed bz2 bytes due to io error.", length] }]; return NO; default: - self.error = [NSError errorWithDomain:SPARKLE_BZIP2_ERROR_DOMAIN code:bzerror userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to write %d compressed bz2 bytes.", length] }]; + _error = [NSError errorWithDomain:SPARKLE_BZIP2_ERROR_DOMAIN code:bzerror userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to write %d compressed bz2 bytes.", length] }]; return NO; } +#else + return NO; +#endif } case SPUDeltaCompressionModeLZMA: case SPUDeltaCompressionModeLZFSE: @@ -698,21 +706,21 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod _compressionStream.src_ptr = buffer; _compressionStream.src_size = (size_t)length; - FILE *file = self.file; - void *compressionBuffer = self.compressionBuffer; + FILE *file = _file; + void *compressionBuffer = _compressionBuffer; while (_compressionStream.src_size > 0) { // Reset destination buffer _compressionStream.dst_ptr = compressionBuffer; _compressionStream.dst_size = COMPRESSION_BUFFER_SIZE; if (compression_stream_process(&_compressionStream, 0) == COMPRESSION_STATUS_ERROR) { - self.error = [NSError errorWithDomain:SPARKLE_COMPRESSION_ERROR_DOMAIN code:COMPRESSION_STATUS_ERROR userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to write %d compressed bytes.", length] }]; + _error = [NSError errorWithDomain:SPARKLE_COMPRESSION_ERROR_DOMAIN code:COMPRESSION_STATUS_ERROR userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to write %d compressed bytes.", length] }]; return NO; } size_t compressedBytesWritten = (size_t)(_compressionStream.dst_ptr - (uint8_t *)compressionBuffer); if (compressedBytesWritten > 0 && fwrite(compressionBuffer, compressedBytesWritten, 1, file) < 1) { - self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to write %zu compressed bytes.", compressedBytesWritten] }]; + _error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to write %zu compressed bytes.", compressedBytesWritten] }]; return NO; } } @@ -725,31 +733,31 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod - (void)writeHeader:(SPUDeltaArchiveHeader *)header { char patchFilePath[PATH_MAX + 1] = {0}; - if (![self.patchFile getFileSystemRepresentation:patchFilePath maxLength:sizeof(patchFilePath) - 1]) { - self.error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to open header and represent as a file system representation: %@", self.patchFile] }]; + if (![_patchFile getFileSystemRepresentation:patchFilePath maxLength:sizeof(patchFilePath) - 1]) { + _error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to open header and represent as a file system representation: %@", _patchFile] }]; return; } FILE *file = fopen(patchFilePath, "wb"); if (file == NULL) { - self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to open patch file for writing: %@", self.patchFile] }]; + _error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to open patch file for writing: %@", _patchFile] }]; return; } - self.file = file; + _file = file; char magic[] = SPARKLE_DELTA_FORMAT_MAGIC; if (fwrite(magic, sizeof(magic) - 1, 1, file) < 1) { - self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: @"Failed to write magic value due to io error" }]; + _error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: @"Failed to write magic value due to io error" }]; return; } SPUDeltaCompressionMode compression = (header.compression == SPUDeltaCompressionModeDefault) ? SPUDeltaCompressionModeLZMA : header.compression; - self.compression = compression; + _compression = compression; if (fwrite(&compression, sizeof(compression), 1, file) < 1) { - self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: @"Failed to write compression value due to io error" }]; + _error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: @"Failed to write compression value due to io error" }]; return; } @@ -757,13 +765,19 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod uint8_t compressionLevel = 0; switch (compression) { case SPUDeltaCompressionModeBzip2: +#if SPARKLE_BUILD_BZIP2_DELTA_SUPPORT // Only 1 - 9 are valid, 0 is a special case for using default 9 if (header.compressionLevel <= 0 || header.compressionLevel > 9) { compressionLevel = 9; } else { compressionLevel = header.compressionLevel; } + break; +#else + _error = [NSError errorWithDomain:SPARKLE_BZIP2_ERROR_DOMAIN code:-1 userInfo:@{ NSLocalizedDescriptionKey: @"Failed to write bzip2 patch because bzip2 support is disabled" }]; + return; +#endif // Some supported formats below have a documented level even though it's not customizable // Let's record them in the archive case SPUDeltaCompressionModeLZMA: @@ -782,7 +796,7 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod SparkleDeltaArchiveMetadata metadata = {.compressionLevel = compressionLevel, .fileSystemCompression = header.fileSystemCompression}; if (fwrite(&metadata, sizeof(metadata), 1, file) < 1) { - self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: @"Failed to write metadata value due to io error" }]; + _error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: @"Failed to write metadata value due to io error" }]; return; } @@ -790,6 +804,7 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod case SPUDeltaCompressionModeNone: break; case SPUDeltaCompressionModeBzip2: { +#if SPARKLE_BUILD_BZIP2_DELTA_SUPPORT int bzerror = 0; // Compression level can be 1 - 9 int blockSize100k = (int)compressionLevel; @@ -798,17 +813,18 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod if (bzipFile == NULL) { switch (bzerror) { case BZ_IO_ERROR: - self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: @"Failed to open bz2 stream for writing due to io error" }]; + _error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: @"Failed to open bz2 stream for writing due to io error" }]; break; default: - self.error = [NSError errorWithDomain:SPARKLE_BZIP2_ERROR_DOMAIN code:bzerror userInfo:@{ NSLocalizedDescriptionKey: @"Failed to open bz2 stream for writing" }]; + _error = [NSError errorWithDomain:SPARKLE_BZIP2_ERROR_DOMAIN code:bzerror userInfo:@{ NSLocalizedDescriptionKey: @"Failed to open bz2 stream for writing" }]; break; } return; } - self.bzipFile = bzipFile; + _bzipFile = bzipFile; +#endif break; } @@ -817,12 +833,12 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod case SPUDeltaCompressionModeLZ4: case SPUDeltaCompressionModeZLIB: { if (compression_stream_init(&_compressionStream, COMPRESSION_STREAM_ENCODE, _compressionAlgorithmForMode(compression)) != COMPRESSION_STATUS_OK) { - self.error = [NSError errorWithDomain:SPARKLE_COMPRESSION_ERROR_DOMAIN code:COMPRESSION_STATUS_ERROR userInfo:@{ NSLocalizedDescriptionKey: @"Failed to open compression stream for writing" }]; + _error = [NSError errorWithDomain:SPARKLE_COMPRESSION_ERROR_DOMAIN code:COMPRESSION_STATUS_ERROR userInfo:@{ NSLocalizedDescriptionKey: @"Failed to open compression stream for writing" }]; return; } - self.initializedCompressionStream = YES; + _initializedCompressionStream = YES; break; } } @@ -843,16 +859,16 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod - (void)addItem:(SPUDeltaArchiveItem *)item { - [self.writableItems addObject:item]; + [_writableItems addObject:item]; } - (void)finishEncodingItems { - if (self.error != nil) { + if (_error != nil) { return; } - NSMutableArray *writableItems = self.writableItems; + NSMutableArray *writableItems = _writableItems; // Build relative path table for tracking file clones NSMutableDictionary *relativePathToIndexTable = [NSMutableDictionary dictionary]; @@ -884,7 +900,7 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod if (relativePathToIndexTable.count > UINT32_MAX) { // Very unlikely but we should guard against this // Clones rely on 32-bit indexes - self.error = [NSError errorWithDomain:SPARKLE_DELTA_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_ARCHIVE_ERROR_CODE_TOO_MANY_FILES userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"There are too many file entries to create a patch for (more than %u)", UINT32_MAX] }]; + _error = [NSError errorWithDomain:SPARKLE_DELTA_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_ARCHIVE_ERROR_CODE_TOO_MANY_FILES userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"There are too many file entries to create a patch for (more than %u)", UINT32_MAX] }]; return; } @@ -895,7 +911,7 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod char relativePathString[PATH_MAX + 1] = {0}; if (![relativePath getFileSystemRepresentation:relativePathString maxLength:sizeof(relativePathString) - 1]) { - self.error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Relative path cannot be retrieved and expressed as a file system representation: %@", relativePath] }]; + _error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Relative path cannot be retrieved and expressed as a file system representation: %@", relativePath] }]; break; } @@ -904,14 +920,14 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod for (NSString *clonedPathEntry in newClonedPathEntries) { char relativePathString[PATH_MAX + 1] = {0}; if (![clonedPathEntry getFileSystemRepresentation:relativePathString maxLength:sizeof(relativePathString) - 1]) { - self.error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Relative path for clone cannot be retrieved and expressed as a file system representation: %@", clonedPathEntry] }]; + _error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Relative path for clone cannot be retrieved and expressed as a file system representation: %@", clonedPathEntry] }]; break; } totalPathLength += strlen(relativePathString) + 1; } - if (self.error != nil) { + if (_error != nil) { return; } @@ -926,7 +942,7 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod char pathBuffer[PATH_MAX + 1] = {0}; if (![relativePath getFileSystemRepresentation:pathBuffer maxLength:PATH_MAX]) { - self.error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Relative path cannot be encoded and expressed as a file system representation: %@", relativePath] }]; + _error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Relative path cannot be encoded and expressed as a file system representation: %@", relativePath] }]; break; } @@ -937,7 +953,7 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod for (NSString *clonedPathEntry in newClonedPathEntries) { char pathBuffer[PATH_MAX + 1] = {0}; if (![clonedPathEntry getFileSystemRepresentation:pathBuffer maxLength:PATH_MAX]) { - self.error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Relative path for clone cannot be encoded and expressed as a file system representation: %@", clonedPathEntry] }]; + _error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Relative path for clone cannot be encoded and expressed as a file system representation: %@", clonedPathEntry] }]; break; } @@ -946,7 +962,7 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod } } - if (self.error != nil) { + if (_error != nil) { return; } @@ -969,13 +985,13 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod char sourcePathString[PATH_MAX + 1] = {0}; if (![sourcePath getFileSystemRepresentation:sourcePathString maxLength:sizeof(sourcePathString) - 1]) { - self.error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Path cannot be decoded and expressed as a file system representation while encoding cloned binary diff item: %@", sourcePath] }]; + _error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Path cannot be decoded and expressed as a file system representation while encoding cloned binary diff item: %@", sourcePath] }]; break; } struct stat fileInfo = {0}; if (lstat(sourcePathString, &fileInfo) != 0) { - self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to lstat() on %@", sourcePath] }]; + _error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to lstat() on %@", sourcePath] }]; break; } @@ -1002,7 +1018,7 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod NSNumber *relativePathIndex = relativePathToIndexTable[clonedRelativePath]; if (relativePathIndex == nil) { // We have quite a problem here - self.error = [NSError errorWithDomain:SPARKLE_DELTA_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_ARCHIVE_ERROR_CODE_BAD_CLONE_LOOKUP userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Relative file path index for %@ could not be located", clonedRelativePath] }]; + _error = [NSError errorWithDomain:SPARKLE_DELTA_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_ARCHIVE_ERROR_CODE_BAD_CLONE_LOOKUP userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Relative file path index for %@ could not be located", clonedRelativePath] }]; break; } @@ -1017,13 +1033,13 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod char itemFilePathString[PATH_MAX + 1] = {0}; if (![itemPath getFileSystemRepresentation:itemFilePathString maxLength:sizeof(itemFilePathString) - 1]) { - self.error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Path cannot be decoded and expressed as a file system representation while encoding cloned binary diff item: %@", itemPath] }]; + _error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Path cannot be decoded and expressed as a file system representation while encoding cloned binary diff item: %@", itemPath] }]; break; } struct stat fileInfo = {0}; if (lstat(itemFilePathString, &fileInfo) != 0) { - self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to lstat() on %@", itemPath] }]; + _error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to lstat() on %@", itemPath] }]; break; } @@ -1043,13 +1059,13 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod char sourceFilePathString[PATH_MAX + 1] = {0}; if (![sourcePath getFileSystemRepresentation:sourceFilePathString maxLength:sizeof(sourceFilePathString) - 1]) { - self.error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Path cannot be decoded and expressed as a file system representation while encoding items: %@", sourcePath] }]; + _error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Path cannot be decoded and expressed as a file system representation while encoding items: %@", sourcePath] }]; break; } struct stat sourceFileInfo = {0}; if (lstat(sourceFilePathString, &sourceFileInfo) != 0) { - self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to lstat() on %@", sourcePath] }]; + _error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to lstat() on %@", sourcePath] }]; break; } @@ -1085,13 +1101,13 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod char itemFilePathString[PATH_MAX + 1] = {0}; if (![itemPath getFileSystemRepresentation:itemFilePathString maxLength:sizeof(itemFilePathString) - 1]) { - self.error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Path cannot be decoded and expressed as a file system representation while encoding items: %@", itemPath] }]; + _error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Path cannot be decoded and expressed as a file system representation while encoding items: %@", itemPath] }]; break; } struct stat itemFileInfo = {0}; if (lstat(itemFilePathString, &itemFileInfo) != 0) { - self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to lstat() on %@", itemPath] }]; + _error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to lstat() on %@", itemPath] }]; break; } @@ -1105,7 +1121,7 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod } else if (S_ISLNK(extractMode)) { off_t fileSize = itemFileInfo.st_size; if (fileSize > UINT16_MAX) { - self.error = [NSError errorWithDomain:SPARKLE_DELTA_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_ARCHIVE_ERROR_CODE_LINK_TOO_LONG userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Link path has a destination that is too long: %llu bytes", fileSize] }]; + _error = [NSError errorWithDomain:SPARKLE_DELTA_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_ARCHIVE_ERROR_CODE_LINK_TOO_LONG userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Link path has a destination that is too long: %llu bytes", fileSize] }]; break; } @@ -1125,7 +1141,7 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod } } - if (self.error != nil) { + if (_error != nil) { return; } @@ -1136,7 +1152,7 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod } // Encode all of our file contents - void *tempBuffer = self.partialChunkBuffer; + void *tempBuffer = _partialChunkBuffer; for (SPUDeltaArchiveItem *item in writableItems) { SPUDeltaItemCommands commands = item.commands; if ((commands & SPUDeltaItemCommandExtract) != 0 || (commands & SPUDeltaItemCommandBinaryDiff) != 0) { @@ -1151,13 +1167,13 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod if (totalItemSize > 0) { char itemFilePathString[PATH_MAX + 1] = {0}; if (![itemPath getFileSystemRepresentation:itemFilePathString maxLength:sizeof(itemFilePathString) - 1]) { - self.error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Path to finish encoding cannot be decoded and expressed as a file system representation: %@", itemPath] }]; + _error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Path to finish encoding cannot be decoded and expressed as a file system representation: %@", itemPath] }]; break; } FILE *inputFile = fopen(itemFilePathString, "rb"); if (inputFile == NULL) { - self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to open file for reading while encoding items: %@", itemPath] }]; + _error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to open file for reading while encoding items: %@", itemPath] }]; break; } @@ -1166,7 +1182,7 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod uint64_t currentBlockSize = (bytesLeftoverToCopy >= PARTIAL_IO_CHUNK_SIZE) ? PARTIAL_IO_CHUNK_SIZE : bytesLeftoverToCopy; if (fread(tempBuffer, currentBlockSize, 1, inputFile) < 1) { - self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to read %llu chunk bytes while encoding items", currentBlockSize] }]; + _error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to read %llu chunk bytes while encoding items", currentBlockSize] }]; break; } @@ -1179,21 +1195,21 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod fclose(inputFile); - if (self.error != nil) { + if (_error != nil) { break; } } } else if (S_ISLNK(extractMode)) { char itemFilePathString[PATH_MAX + 1] = {0}; if (![itemPath getFileSystemRepresentation:itemFilePathString maxLength:sizeof(itemFilePathString) - 1]) { - self.error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Link path to finish encoding cannot be decoded and expressed as a file system representation: %@", itemPath] }]; + _error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadInvalidFileNameError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Link path to finish encoding cannot be decoded and expressed as a file system representation: %@", itemPath] }]; break; } char linkDestination[PATH_MAX + 1] = {0}; ssize_t linkDestinationLength = readlink(itemFilePathString, linkDestination, PATH_MAX); if (linkDestinationLength < 0) { - self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to readlink() file at %@", itemPath] }]; + _error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to readlink() file at %@", itemPath] }]; break; } @@ -1206,16 +1222,19 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod // Close up and write final data to compressed streams - if (self.bzipFile != NULL) { +#if SPARKLE_BUILD_BZIP2_DELTA_SUPPORT + if (_bzipFile != NULL) { int bzerror = 0; - BZ2_bzWriteClose64(&bzerror, self.bzipFile, 0, NULL, NULL, NULL, NULL); + BZ2_bzWriteClose64(&bzerror, _bzipFile, 0, NULL, NULL, NULL, NULL); if (bzerror == BZ_IO_ERROR) { - self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: @"Failed to write and close bzip2 file due to IO error" }]; + _error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: @"Failed to write and close bzip2 file due to IO error" }]; return; } - } else if (self.initializedCompressionStream) { - void *compressionBuffer = self.compressionBuffer; - FILE *file = self.file; + } else +#endif + if (_initializedCompressionStream) { + void *compressionBuffer = _compressionBuffer; + FILE *file = _file; _compressionStream.src_size = 0; @@ -1225,14 +1244,14 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod compression_status status = compression_stream_process(&_compressionStream, COMPRESSION_STREAM_FINALIZE); if (status == COMPRESSION_STATUS_ERROR) { - self.error = [NSError errorWithDomain:SPARKLE_COMPRESSION_ERROR_DOMAIN code:COMPRESSION_STATUS_ERROR userInfo:@{ NSLocalizedDescriptionKey: @"Failed to write final bits of Compression based file" }]; + _error = [NSError errorWithDomain:SPARKLE_COMPRESSION_ERROR_DOMAIN code:COMPRESSION_STATUS_ERROR userInfo:@{ NSLocalizedDescriptionKey: @"Failed to write final bits of Compression based file" }]; return; } size_t compressedBytesToWrite = (size_t)(_compressionStream.dst_ptr - (uint8_t *)compressionBuffer); if (compressedBytesToWrite > 0) { if (fwrite(compressionBuffer, compressedBytesToWrite, 1, file) < 1) { - self.error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: @"Failed to write and close Compression based file due to io error" }]; + _error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:@{ NSLocalizedDescriptionKey: @"Failed to write and close Compression based file due to io error" }]; return; } } @@ -1246,5 +1265,3 @@ static compression_algorithm _compressionAlgorithmForMode(SPUDeltaCompressionMod } @end - -#pragma clang diagnostic pop diff --git a/Autoupdate/SPUXarDeltaArchive.h b/Autoupdate/SPUXarDeltaArchive.h index f4426735..8db7397c 100644 --- a/Autoupdate/SPUXarDeltaArchive.h +++ b/Autoupdate/SPUXarDeltaArchive.h @@ -6,6 +6,8 @@ // Copyright © 2021 Sparkle Project. All rights reserved. // +#if SPARKLE_BUILD_LEGACY_DELTA_SUPPORT + #import #import "SPUDeltaArchiveProtocol.h" @@ -14,11 +16,13 @@ NS_ASSUME_NONNULL_BEGIN // Legacy container format for binary delta archives -@interface SPUXarDeltaArchive : NSObject +SPU_OBJC_DIRECT_MEMBERS @interface SPUXarDeltaArchive : NSObject -- (instancetype)initWithPatchFileForWriting:(NSString *)patchFile; -- (instancetype)initWithPatchFileForReading:(NSString *)patchFile; +- (instancetype)initWithPatchFileForWriting:(NSString *)patchFile SPU_OBJC_DIRECT; +- (instancetype)initWithPatchFileForReading:(NSString *)patchFile SPU_OBJC_DIRECT; @end NS_ASSUME_NONNULL_END + +#endif diff --git a/Autoupdate/SPUXarDeltaArchive.m b/Autoupdate/SPUXarDeltaArchive.m index 0e949226..7c3f4bbc 100644 --- a/Autoupdate/SPUXarDeltaArchive.m +++ b/Autoupdate/SPUXarDeltaArchive.m @@ -6,6 +6,8 @@ // Copyright © 2021 Sparkle Project. All rights reserved. // +#if SPARKLE_BUILD_LEGACY_DELTA_SUPPORT + #import "SPUXarDeltaArchive.h" #include #include "SUBinaryDeltaCommon.h" @@ -45,22 +47,15 @@ extern char *xar_get_safe_path(xar_file_t f) __attribute__((weak_import)); #define SPARKLE_DELTA_XAR_ARCHIVE_ERROR_CODE_EXTRACT_FAILURE 3 #define SPARKLE_DELTA_XAR_ARCHIVE_ERROR_CODE_UNSUPPORTED_COMPRESSION_FAILURE 4 -@interface SPUXarDeltaArchive () - -@property (nonatomic) xar_t x; -@property (nonatomic, readonly) int32_t xarMode; -@property (nonatomic, readonly) NSMutableDictionary *fileTable; -@property (nonatomic, readonly) NSString *patchFile; -@property (nonatomic) NSError *error; - -@end - @implementation SPUXarDeltaArchive +{ + NSMutableDictionary *_fileTable; + NSString *_patchFile; + + xar_t _x; + int32_t _xarMode; +} -@synthesize x = _x; -@synthesize xarMode = _xarMode; -@synthesize patchFile = _patchFile; -@synthesize fileTable = _fileTable; @synthesize error = _error; - (instancetype)initWithPatchFileForWriting:(NSString *)patchFile @@ -91,9 +86,9 @@ extern char *xar_get_safe_path(xar_file_t f) __attribute__((weak_import)); - (void)close { - if (self.x != NULL) { - xar_close(self.x); - self.x = NULL; + if (_x != NULL) { + xar_close(_x); + _x = NULL; } } @@ -105,18 +100,18 @@ extern char *xar_get_safe_path(xar_file_t f) __attribute__((weak_import)); - (nullable SPUDeltaArchiveHeader *)readHeader { - NSString *patchFile = self.patchFile; + NSString *patchFile = _patchFile; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" // Sparkle's XAR delta archives have been superceded by Sparkle's own format xar_t x = xar_open(patchFile.fileSystemRepresentation, READ); #pragma clang diagnostic pop if (x == NULL) { - self.error = [NSError errorWithDomain:SPARKLE_DELTA_XAR_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_XAR_ARCHIVE_ERROR_CODE_OPEN_FAILURE userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to xar_open() file for reading: %@", patchFile] }]; + _error = [NSError errorWithDomain:SPARKLE_DELTA_XAR_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_XAR_ARCHIVE_ERROR_CODE_OPEN_FAILURE userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to xar_open() file for reading: %@", patchFile] }]; return nil; } - self.x = x; + _x = x; uint16_t majorDiffVersion = SUBinaryDeltaMajorVersionFirst; uint16_t minorDiffVersion = 0; @@ -124,7 +119,7 @@ extern char *xar_get_safe_path(xar_file_t f) __attribute__((weak_import)); NSString *expectedAfterHash = nil; xar_subdoc_t subdoc; - for (subdoc = xar_subdoc_first(self.x); subdoc; subdoc = xar_subdoc_next(subdoc)) { + for (subdoc = xar_subdoc_first(_x); subdoc; subdoc = xar_subdoc_next(subdoc)) { if (strcmp(xar_subdoc_name(subdoc), BINARY_DELTA_ATTRIBUTES_KEY) == 0) { { // available in version 2.0 or later @@ -177,7 +172,7 @@ extern char *xar_get_safe_path(xar_file_t f) __attribute__((weak_import)); - (void)writeHeader:(SPUDeltaArchiveHeader *)header { - NSString *patchFile = self.patchFile; + NSString *patchFile = _patchFile; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" @@ -185,11 +180,11 @@ extern char *xar_get_safe_path(xar_file_t f) __attribute__((weak_import)); xar_t x = xar_open(patchFile.fileSystemRepresentation, WRITE); #pragma clang diagnostic pop if (x == NULL) { - self.error = [NSError errorWithDomain:SPARKLE_DELTA_XAR_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_XAR_ARCHIVE_ERROR_CODE_OPEN_FAILURE userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to xar_open() file for writing: %@", patchFile] }]; + _error = [NSError errorWithDomain:SPARKLE_DELTA_XAR_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_XAR_ARCHIVE_ERROR_CODE_OPEN_FAILURE userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to xar_open() file for writing: %@", patchFile] }]; return; } - self.x = x; + _x = x; SPUDeltaCompressionMode compression = (header.compression == SPUDeltaCompressionModeDefault ? SPUDeltaCompressionModeBzip2 : header.compression); @@ -218,7 +213,7 @@ extern char *xar_get_safe_path(xar_file_t f) __attribute__((weak_import)); case SPUDeltaCompressionModeLZFSE: case SPUDeltaCompressionModeLZ4: case SPUDeltaCompressionModeZLIB: { - self.error = [NSError errorWithDomain:SPARKLE_DELTA_XAR_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_XAR_ARCHIVE_ERROR_CODE_UNSUPPORTED_COMPRESSION_FAILURE userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Version 2 patches only support bzip2 compression."] }]; + _error = [NSError errorWithDomain:SPARKLE_DELTA_XAR_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_XAR_ARCHIVE_ERROR_CODE_UNSUPPORTED_COMPRESSION_FAILURE userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Version 2 patches only support bzip2 compression."] }]; return; } @@ -281,7 +276,7 @@ static xar_file_t _xarAddFile(NSMutableDictionary *fileTa - (void)addItem:(SPUDeltaArchiveItem *)item { - if (self.error != nil) { + if (_error != nil) { return; } @@ -290,9 +285,9 @@ static xar_file_t _xarAddFile(NSMutableDictionary *fileTa SPUDeltaItemCommands commands = item.commands; uint16_t mode = item.mode; - xar_file_t newFile = _xarAddFile(self.fileTable, self.x, relativeFilePath, filePath); + xar_file_t newFile = _xarAddFile(_fileTable, _x, relativeFilePath, filePath); if (newFile == NULL) { - self.error = [NSError errorWithDomain:SPARKLE_DELTA_XAR_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_XAR_ARCHIVE_ERROR_CODE_ADD_FAILURE userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to add xar file entry: %@", relativeFilePath] }]; + _error = [NSError errorWithDomain:SPARKLE_DELTA_XAR_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_XAR_ARCHIVE_ERROR_CODE_ADD_FAILURE userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to add xar file entry: %@", relativeFilePath] }]; return; } @@ -320,13 +315,13 @@ static xar_file_t _xarAddFile(NSMutableDictionary *fileTa - (void)enumerateItems:(void (^)(SPUDeltaArchiveItem *, BOOL *))itemHandler { - if (self.error != nil) { + if (_error != nil) { return; } BOOL exitedEarly = NO; xar_iter_t iter = xar_iter_new(); - for (xar_file_t file = xar_file_first(self.x, iter); file; file = xar_file_next(iter)) { + for (xar_file_t file = xar_file_first(_x, iter); file; file = xar_file_next(iter)) { char *pathCString; #if HAS_XAR_GET_SAFE_PATH #pragma clang diagnostic push @@ -397,7 +392,7 @@ static xar_file_t _xarAddFile(NSMutableDictionary *fileTa - (BOOL)extractItem:(SPUDeltaArchiveItem *)item { - if (self.error != nil) { + if (_error != nil) { return NO; } @@ -405,8 +400,8 @@ static xar_file_t _xarAddFile(NSMutableDictionary *fileTa assert(item.xarContext != NULL); xar_file_t file = item.xarContext; - if (xar_extract_tofile(self.x, file, item.itemFilePath.fileSystemRepresentation) != 0) { - self.error = [NSError errorWithDomain:SPARKLE_DELTA_XAR_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_XAR_ARCHIVE_ERROR_CODE_EXTRACT_FAILURE userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to extract xar file entry to %@", item.itemFilePath] }]; + if (xar_extract_tofile(_x, file, item.itemFilePath.fileSystemRepresentation) != 0) { + _error = [NSError errorWithDomain:SPARKLE_DELTA_XAR_ARCHIVE_ERROR_DOMAIN code:SPARKLE_DELTA_XAR_ARCHIVE_ERROR_CODE_EXTRACT_FAILURE userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to extract xar file entry to %@", item.itemFilePath] }]; return NO; } @@ -414,3 +409,5 @@ static xar_file_t _xarAddFile(NSMutableDictionary *fileTa } @end + +#endif diff --git a/Autoupdate/SUBinaryDeltaCreate.m b/Autoupdate/SUBinaryDeltaCreate.m index 2b13423c..9924872f 100644 --- a/Autoupdate/SUBinaryDeltaCreate.m +++ b/Autoupdate/SUBinaryDeltaCreate.m @@ -29,42 +29,47 @@ extern int bsdiff(int argc, const char **argv); @interface CreateBinaryDeltaOperation : NSOperation -@property (copy) NSString *relativePath; -@property (copy) NSString *clonedRelativePath; -@property (strong) NSString *resultPath; -@property (strong) NSNumber *oldPermissions; -@property (strong) NSNumber *permissions; -@property (nonatomic) BOOL changingPermissions; -@property (strong) NSString *_fromPath; -@property (strong) NSString *_toPath; -- (id)initWithRelativePath:(NSString *)relativePath clonedRelativePath:(NSString *)clonedRelativePath oldTree:(NSString *)oldTree newTree:(NSString *)newTree oldPermissions:(NSNumber *)oldPermissions newPermissions:(NSNumber *)permissions changingPermissions:(BOOL)changingPermissions; + +@property (nonatomic, copy, readonly) NSString *relativePath; +@property (nonatomic, copy, readonly) NSString *clonedRelativePath; +@property (nonatomic, readonly) NSString *resultPath; +@property (nonatomic, readonly) NSNumber *oldPermissions; +@property (nonatomic, readonly) NSNumber *permissions; +@property (nonatomic, readonly) NSString *fromPath; +@property (nonatomic, readonly) BOOL changingPermissions; + +- (id)initWithRelativePath:(NSString *)relativePath clonedRelativePath:(NSString *)clonedRelativePath oldTree:(NSString *)oldTree newTree:(NSString *)newTree oldPermissions:(NSNumber *)oldPermissions newPermissions:(NSNumber *)permissions changingPermissions:(BOOL)changingPermissions SPU_OBJC_DIRECT; + @end @implementation CreateBinaryDeltaOperation +{ + NSString *_toPath; +} + @synthesize relativePath = _relativePath; @synthesize clonedRelativePath = _clonedRelativePath; @synthesize resultPath = _resultPath; @synthesize oldPermissions = _oldPermissions; @synthesize permissions = _permissions; +@synthesize fromPath = _fromPath; @synthesize changingPermissions = _changingPermissions; -@synthesize _fromPath = _fromPath; -@synthesize _toPath = _toPath; - (id)initWithRelativePath:(NSString *)relativePath clonedRelativePath:(NSString *)clonedRelativePath oldTree:(NSString *)oldTree newTree:(NSString *)newTree oldPermissions:(NSNumber *)oldPermissions newPermissions:(NSNumber *)permissions changingPermissions:(BOOL)changingPermissions { if ((self = [super init])) { - self.relativePath = relativePath; - self.clonedRelativePath = clonedRelativePath; - self.oldPermissions = oldPermissions; - self.permissions = permissions; - self.changingPermissions = changingPermissions; + _relativePath = [relativePath copy]; + _clonedRelativePath = [clonedRelativePath copy]; + _oldPermissions = oldPermissions; + _permissions = permissions; + _changingPermissions = changingPermissions; if (clonedRelativePath == nil) { - self._fromPath = [oldTree stringByAppendingPathComponent:relativePath]; + _fromPath = [oldTree stringByAppendingPathComponent:relativePath]; } else { - self._fromPath = [oldTree stringByAppendingPathComponent:clonedRelativePath]; + _fromPath = [oldTree stringByAppendingPathComponent:clonedRelativePath]; } - self._toPath = [newTree stringByAppendingPathComponent:relativePath]; + _toPath = [newTree stringByAppendingPathComponent:relativePath]; } return self; } @@ -72,10 +77,11 @@ extern int bsdiff(int argc, const char **argv); - (void)main { NSString *temporaryFile = temporaryFilename(@"BinaryDelta"); - const char *argv[] = { "/usr/bin/bsdiff", [self._fromPath fileSystemRepresentation], [self._toPath fileSystemRepresentation], [temporaryFile fileSystemRepresentation] }; + const char *argv[] = { "/usr/bin/bsdiff", [_fromPath fileSystemRepresentation], [_toPath fileSystemRepresentation], [temporaryFile fileSystemRepresentation] }; int result = bsdiff(4, argv); - if (!result) - self.resultPath = temporaryFile; + if (result == 0) { + _resultPath = temporaryFile; + } } @end @@ -704,7 +710,17 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF if (majorVersion >= SUBinaryDeltaMajorVersion3) { archive = [[SPUSparkleDeltaArchive alloc] initWithPatchFileForWriting:temporaryFile]; } else { +#if SPARKLE_BUILD_LEGACY_DELTA_SUPPORT archive = [[SPUXarDeltaArchive alloc] initWithPatchFileForWriting:temporaryFile]; +#else + if (verbose) { + fprintf(stderr, "\n"); + } + if (error != NULL) { + *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadUnknownError userInfo:@{ NSLocalizedDescriptionKey: @"Support for creating legacy delta updates is disabled" }]; + } + return NO; +#endif } SPUDeltaArchiveHeader *header = [[SPUDeltaArchiveHeader alloc] initWithCompression:compression compressionLevel:compressionLevel fileSystemCompression:foundFilesystemCompression majorVersion:majorVersion minorVersion:minorVersion beforeTreeHash:beforeHash afterTreeHash:afterHash]; @@ -918,7 +934,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF BOOL deltaOperationsFailed = NO; for (CreateBinaryDeltaOperation *operation in deltaOperations) { - NSString *resultPath = [operation resultPath]; + NSString *resultPath = operation.resultPath; if (resultPath == nil) { if (verbose) { fprintf(stderr, "\n"); @@ -952,7 +968,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF SPUDeltaArchiveItem *item = [[SPUDeltaArchiveItem alloc] initWithRelativeFilePath:relativePath commands:commands mode:mode.unsignedShortValue]; item.itemFilePath = resultPath; - item.sourcePath = operation._fromPath; + item.sourcePath = operation.fromPath; item.clonedRelativePath = clonedRelativePath; [archive addItem:item]; @@ -972,7 +988,7 @@ BOOL createBinaryDelta(NSString *source, NSString *destination, NSString *patchF // Clean up operations after the archive has finished encoding for (CreateBinaryDeltaOperation *operation in deltaOperations) { - NSString *resultPath = [operation resultPath]; + NSString *resultPath = operation.resultPath; if (resultPath != nil) { unlink(resultPath.fileSystemRepresentation); } diff --git a/Autoupdate/SUBinaryDeltaUnarchiver.h b/Autoupdate/SUBinaryDeltaUnarchiver.h index ba79a047..db3a2886 100644 --- a/Autoupdate/SUBinaryDeltaUnarchiver.h +++ b/Autoupdate/SUBinaryDeltaUnarchiver.h @@ -14,10 +14,15 @@ NS_ASSUME_NONNULL_BEGIN +#ifndef BUILDING_SPARKLE_TESTS +SPU_OBJC_DIRECT_MEMBERS +#endif @interface SUBinaryDeltaUnarchiver : NSObject - (instancetype)initWithArchivePath:(NSString *)archivePath updateHostBundlePath:(NSString *)updateHostBundlePath; ++ (BOOL)canUnarchivePath:(NSString *)path; + @end NS_ASSUME_NONNULL_END diff --git a/Autoupdate/SUBinaryDeltaUnarchiver.m b/Autoupdate/SUBinaryDeltaUnarchiver.m index 3aba85ad..f9bdbc15 100644 --- a/Autoupdate/SUBinaryDeltaUnarchiver.m +++ b/Autoupdate/SUBinaryDeltaUnarchiver.m @@ -16,17 +16,11 @@ #include "AppKitPrevention.h" -@interface SUBinaryDeltaUnarchiver () - -@property (nonatomic, copy, readonly) NSString *archivePath; -@property (nonatomic, copy, readonly) NSString *updateHostBundlePath; - -@end - @implementation SUBinaryDeltaUnarchiver - -@synthesize archivePath = _archivePath; -@synthesize updateHostBundlePath = _updateHostBundlePath; +{ + NSString *_archivePath; + NSString *_updateHostBundlePath; +} + (BOOL)canUnarchivePath:(NSString *)path { @@ -43,7 +37,11 @@ // We used to invoke mdimport on the bundle but this is not a very good approach. // There's no need to do that for non-delta updates and for updates that contain no mdimporters. // Moreover, updating the timestamp on the mdimporter bundles is what developers have to do anyway when shipping their new update outside of Sparkle +// Note: this is used from unit tests + (void)updateSpotlightImportersAtBundlePath:(NSString *)targetPath +#ifndef BUILDING_SPARKLE_TESTS +SPU_OBJC_DIRECT +#endif { NSURL *targetURL = [NSURL fileURLWithPath:targetPath]; // Only recurse if it's actually a directory. Don't recurse into a @@ -95,17 +93,17 @@ - (void)extractDeltaWithNotifier:(SUUnarchiverNotifier *)notifier { - NSString *sourcePath = self.updateHostBundlePath; - NSString *targetPath = [[self.archivePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:[sourcePath lastPathComponent]]; + NSString *sourcePath = _updateHostBundlePath; + NSString *targetPath = [[_archivePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:[sourcePath lastPathComponent]]; NSError *applyDiffError = nil; - BOOL success = applyBinaryDelta(sourcePath, targetPath, self.archivePath, NO, ^(double progress){ + BOOL success = applyBinaryDelta(sourcePath, targetPath, _archivePath, NO, ^(double progress){ [notifier notifyProgress:progress]; }, &applyDiffError); if (success) { - [[self class] updateSpotlightImportersAtBundlePath:targetPath]; + [SUBinaryDeltaUnarchiver updateSpotlightImportersAtBundlePath:targetPath]; [notifier notifySuccess]; } else { @@ -113,6 +111,6 @@ } } -- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], self.archivePath]; } +- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], _archivePath]; } @end diff --git a/Autoupdate/SUCodeSigningVerifier.h b/Autoupdate/SUCodeSigningVerifier.h index 027b02d8..f35c6d8f 100644 --- a/Autoupdate/SUCodeSigningVerifier.h +++ b/Autoupdate/SUCodeSigningVerifier.h @@ -11,6 +11,9 @@ #import +#ifndef BUILDING_SPARKLE_TESTS +SPU_OBJC_DIRECT_MEMBERS +#endif @interface SUCodeSigningVerifier : NSObject + (BOOL)codeSignatureAtBundleURL:(NSURL *)oldBundleURL matchesSignatureAtBundleURL:(NSURL *)newBundleURL error:(NSError **)error; diff --git a/Autoupdate/SUCodeSigningVerifier.m b/Autoupdate/SUCodeSigningVerifier.m index 03fe731e..4b92bc27 100644 --- a/Autoupdate/SUCodeSigningVerifier.m +++ b/Autoupdate/SUCodeSigningVerifier.m @@ -209,22 +209,8 @@ static id valueOrNSNull(id value) { return value ? value : [NSNull null]; } -+ (NSDictionary *)codeSignatureInfoAtBundleURL:(NSURL *)bundlePath { - NSDictionary *info = nil; - SecStaticCodeRef code = NULL; - OSStatus result = SecStaticCodeCreateWithPath((__bridge CFURLRef)bundlePath, kSecCSDefaultFlags, &code); - if (result != noErr) { - SULog(SULogLevelError, @"Failed to get static code %d", result); - goto finally; - } - info = [self codeSignatureInfoForCode:code]; - -finally: - if (code) CFRelease(code); - return info; -} - -+ (NSDictionary *)codeSignatureInfoForCode:(SecStaticCodeRef)code { ++ (NSDictionary *)codeSignatureInfoForCode:(SecStaticCodeRef)code SPU_OBJC_DIRECT +{ CFDictionaryRef signingInfo = nil; const SecCSFlags flags = (SecCSFlags) (kSecCSSigningInformation | kSecCSRequirementInformation | kSecCSDynamicInformation | kSecCSContentInformation); if (SecCodeCopySigningInformation(code, flags, &signingInfo) == noErr) { @@ -241,7 +227,8 @@ finally: return nil; } -+ (NSDictionary *)logSigningInfoForCode:(SecStaticCodeRef)code label:(NSString*)label { ++ (NSDictionary *)logSigningInfoForCode:(SecStaticCodeRef)code label:(NSString*)label SPU_OBJC_DIRECT +{ NSDictionary *relevantInfo = [self codeSignatureInfoForCode:code]; SULog(SULogLevelDefault, @"%@: %@", label, relevantInfo); return relevantInfo; diff --git a/Autoupdate/SUDiskImageUnarchiver.h b/Autoupdate/SUDiskImageUnarchiver.h index f0de0462..311983ac 100644 --- a/Autoupdate/SUDiskImageUnarchiver.h +++ b/Autoupdate/SUDiskImageUnarchiver.h @@ -6,6 +6,8 @@ // Copyright 2008 Andy Matuschak. All rights reserved. // +#if SPARKLE_BUILD_DMG_SUPPORT + #ifndef SUDISKIMAGEUNARCHIVER_H #define SUDISKIMAGEUNARCHIVER_H @@ -14,12 +16,16 @@ NS_ASSUME_NONNULL_BEGIN -@interface SUDiskImageUnarchiver : NSObject +SPU_OBJC_DIRECT_MEMBERS @interface SUDiskImageUnarchiver : NSObject - (instancetype)initWithArchivePath:(NSString *)archivePath decryptionPassword:(nullable NSString *)decryptionPassword; ++ (BOOL)canUnarchivePath:(NSString *)path; + @end NS_ASSUME_NONNULL_END #endif + +#endif diff --git a/Autoupdate/SUDiskImageUnarchiver.m b/Autoupdate/SUDiskImageUnarchiver.m index a8031cc0..d3204135 100644 --- a/Autoupdate/SUDiskImageUnarchiver.m +++ b/Autoupdate/SUDiskImageUnarchiver.m @@ -6,6 +6,8 @@ // Copyright 2008 Andy Matuschak. All rights reserved. // +#if SPARKLE_BUILD_DMG_SUPPORT + #import "SUDiskImageUnarchiver.h" #import "SUUnarchiverNotifier.h" #import "SULog.h" @@ -13,17 +15,11 @@ #include "AppKitPrevention.h" -@interface SUDiskImageUnarchiver () - -@property (nonatomic, copy, readonly) NSString *archivePath; -@property (nullable, nonatomic, copy, readonly) NSString *decryptionPassword; - -@end - @implementation SUDiskImageUnarchiver - -@synthesize archivePath = _archivePath; -@synthesize decryptionPassword = _decryptionPassword; +{ + NSString *_archivePath; + NSString *_decryptionPassword; +} + (BOOL)canUnarchivePath:(NSString *)path { @@ -54,7 +50,7 @@ } // Called on a non-main thread. -- (void)extractDMGWithNotifier:(SUUnarchiverNotifier *)notifier +- (void)extractDMGWithNotifier:(SUUnarchiverNotifier *)notifier SPU_OBJC_DIRECT { @autoreleasepool { BOOL mountedSuccessfully = NO; @@ -84,10 +80,10 @@ NSData *promptData = [NSData dataWithBytes:"yes\n" length:4]; - NSMutableArray *arguments = [@[@"attach", self.archivePath, @"-mountpoint", mountPoint, /*@"-noverify",*/ @"-nobrowse", @"-noautoopen"] mutableCopy]; + NSMutableArray *arguments = [@[@"attach", _archivePath, @"-mountpoint", mountPoint, /*@"-noverify",*/ @"-nobrowse", @"-noautoopen"] mutableCopy]; - if (self.decryptionPassword) { - NSMutableData *passwordData = [[self.decryptionPassword dataUsingEncoding:NSUTF8StringEncoding] mutableCopy]; + if (_decryptionPassword) { + NSMutableData *passwordData = [[_decryptionPassword dataUsingEncoding:NSUTF8StringEncoding] mutableCopy]; // From the hdiutil docs: // read a null-terminated passphrase from standard input // @@ -136,17 +132,24 @@ [inputPipe.fileHandleForWriting writeData:promptData]; - if (@available(macOS 10.15, *)) { +#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_15 + if (@available(macOS 10.15, *)) +#endif + { if (![inputPipe.fileHandleForWriting writeData:promptData error:&error]) { goto reportError; } - } else { + } +#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_15 + else + { @try { [inputPipe.fileHandleForWriting writeData:promptData]; } @catch (NSException *) { goto reportError; } } +#endif [inputPipe.fileHandleForWriting closeFile]; @@ -181,7 +184,7 @@ for (NSString *item in contents) { NSString *fromPath = [mountPoint stringByAppendingPathComponent:item]; - NSString *toPath = [[self.archivePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:item]; + NSString *toPath = [[_archivePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:item]; itemsCopied += 1.0; [notifier notifyProgress:0.5 + itemsCopied/(totalItems*2.0)]; @@ -219,11 +222,13 @@ SULog(SULogLevelError, @"Error: %@", launchCleanupError); } } else { - SULog(SULogLevelError, @"Can't mount DMG %@", self.archivePath); + SULog(SULogLevelError, @"Can't mount DMG %@", _archivePath); } } } -- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], self.archivePath]; } +- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], _archivePath]; } @end + +#endif diff --git a/Autoupdate/SUFlatPackageUnarchiver.h b/Autoupdate/SUFlatPackageUnarchiver.h index 7a18f263..41afd296 100644 --- a/Autoupdate/SUFlatPackageUnarchiver.h +++ b/Autoupdate/SUFlatPackageUnarchiver.h @@ -6,16 +6,22 @@ // Copyright © 2021 Sparkle Project. All rights reserved. // +#if SPARKLE_BUILD_PACKAGE_SUPPORT + #import #import "SUUnarchiverProtocol.h" NS_ASSUME_NONNULL_BEGIN // An unarchiver for flat packages that doesn't really do any unarchiving -@interface SUFlatPackageUnarchiver : NSObject +SPU_OBJC_DIRECT_MEMBERS @interface SUFlatPackageUnarchiver : NSObject - (instancetype)initWithFlatPackagePath:(NSString *)flatPackagePath expectingInstallationType:(NSString *)installationType; ++ (BOOL)canUnarchivePath:(NSString *)path; + @end NS_ASSUME_NONNULL_END + +#endif diff --git a/Autoupdate/SUFlatPackageUnarchiver.m b/Autoupdate/SUFlatPackageUnarchiver.m index def788bd..9259438a 100644 --- a/Autoupdate/SUFlatPackageUnarchiver.m +++ b/Autoupdate/SUFlatPackageUnarchiver.m @@ -6,6 +6,8 @@ // Copyright © 2021 Sparkle Project. All rights reserved. // +#if SPARKLE_BUILD_PACKAGE_SUPPORT + #import "SUFlatPackageUnarchiver.h" #import "SUUnarchiverNotifier.h" #import "SPUInstallationType.h" @@ -14,17 +16,11 @@ #include "AppKitPrevention.h" -@interface SUFlatPackageUnarchiver () - -@property (nonatomic, readonly) NSString *flatPackagePath; -@property (nonatomic, readonly) NSString *expectedInstallationType; - -@end - @implementation SUFlatPackageUnarchiver - -@synthesize flatPackagePath = _flatPackagePath; -@synthesize expectedInstallationType = _expectedInstallationType; +{ + NSString *_flatPackagePath; + NSString *_expectedInstallationType; +} + (BOOL)canUnarchivePath:(NSString *)path { @@ -52,16 +48,18 @@ // Flat packages must use guided package installs, not interactive BOOL isDirectory = NO; - if (![self.expectedInstallationType isEqualToString:SPUInstallationTypeGuidedPackage]) { - [notifier notifyFailureWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Flat package does not have guided installation type but %@ instead", self.expectedInstallationType]}]]; - } else if (![[NSFileManager defaultManager] fileExistsAtPath:self.flatPackagePath isDirectory:&isDirectory] || isDirectory) { - [notifier notifyFailureWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Flat package does not exist at %@", self.flatPackagePath]}]]; + if (![_expectedInstallationType isEqualToString:SPUInstallationTypeGuidedPackage]) { + [notifier notifyFailureWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Flat package does not have guided installation type but %@ instead", _expectedInstallationType]}]]; + } else if (![[NSFileManager defaultManager] fileExistsAtPath:_flatPackagePath isDirectory:&isDirectory] || isDirectory) { + [notifier notifyFailureWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Flat package does not exist at %@", _flatPackagePath]}]]; } else { [notifier notifyProgress:1.0]; [notifier notifySuccess]; } } -- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], self.flatPackagePath]; } +- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], _flatPackagePath]; } @end + +#endif diff --git a/Autoupdate/SUGuidedPackageInstaller.h b/Autoupdate/SUGuidedPackageInstaller.h index 5ba4c4be..88153bca 100644 --- a/Autoupdate/SUGuidedPackageInstaller.h +++ b/Autoupdate/SUGuidedPackageInstaller.h @@ -16,11 +16,15 @@ The installer package is installed using macOS's built-in command line installer A guided installation can be started by applications other than the application being replaced. This is particularly useful where helper applications or agents are used. */ +#if SPARKLE_BUILD_PACKAGE_SUPPORT + #import #import "SUInstallerProtocol.h" -@interface SUGuidedPackageInstaller : NSObject +SPU_OBJC_DIRECT_MEMBERS @interface SUGuidedPackageInstaller : NSObject - (instancetype)initWithPackagePath:(NSString *)packagePath homeDirectory:(NSString *)homeDirectory userName:(NSString *)userName; @end + +#endif diff --git a/Autoupdate/SUGuidedPackageInstaller.m b/Autoupdate/SUGuidedPackageInstaller.m index 3b04910b..88dd540b 100644 --- a/Autoupdate/SUGuidedPackageInstaller.m +++ b/Autoupdate/SUGuidedPackageInstaller.m @@ -6,6 +6,8 @@ // Copyright 2010 Dragon Systems Software Limited. All rights reserved. // +#if SPARKLE_BUILD_PACKAGE_SUPPORT + #import #import "SUGuidedPackageInstaller.h" #import "SUErrors.h" @@ -13,19 +15,12 @@ #include "AppKitPrevention.h" -@interface SUGuidedPackageInstaller () - -@property (nonatomic, readonly, copy) NSString *packagePath; -@property (nonatomic, readonly, copy) NSString *homeDirectory; -@property (nonatomic, readonly, copy) NSString *userName; - -@end - @implementation SUGuidedPackageInstaller - -@synthesize packagePath = _packagePath; -@synthesize homeDirectory = _homeDirectory; -@synthesize userName = _userName; +{ + NSString *_packagePath; + NSString *_homeDirectory; + NSString *_userName; +} - (instancetype)initWithPackagePath:(NSString *)packagePath homeDirectory:(NSString *)homeDirectory userName:(NSString *)userName { @@ -50,9 +45,9 @@ NSTask *task = [[NSTask alloc] init]; task.launchPath = installerPath; - task.arguments = @[@"-pkg", self.packagePath, @"-target", @"/"]; + task.arguments = @[@"-pkg", _packagePath, @"-target", @"/"]; // Set the $HOME and $USER variables so pre/post install scripts reference the correct user environment - task.environment = @{@"HOME": self.homeDirectory, @"USER": self.userName}; + task.environment = @{@"HOME": _homeDirectory, @"USER": _userName}; task.standardError = nil; task.standardOutput = nil; @@ -93,3 +88,5 @@ } @end + +#endif diff --git a/Autoupdate/SUInstaller.h b/Autoupdate/SUInstaller.h index 83273039..76481fd7 100644 --- a/Autoupdate/SUInstaller.h +++ b/Autoupdate/SUInstaller.h @@ -13,11 +13,15 @@ NS_ASSUME_NONNULL_BEGIN @class SUHost; -@interface SUInstaller : NSObject +SPU_OBJC_DIRECT_MEMBERS @interface SUInstaller : NSObject + (nullable id)installerForHost:(SUHost *)host expectedInstallationType:(NSString *)expectedInstallationType updateDirectory:(NSString *)updateDirectory homeDirectory:(NSString *)homeDirectory userName:(NSString *)userName error:(NSError **)error; -+ (nullable NSString *)installSourcePathInUpdateFolder:(NSString *)inUpdateFolder forHost:(SUHost *)host isPackage:(BOOL *)isPackagePtr isGuided:(nullable BOOL *)isGuidedPtr; ++ (nullable NSString *)installSourcePathInUpdateFolder:(NSString *)inUpdateFolder forHost:(SUHost *)host +#if SPARKLE_BUILD_PACKAGE_SUPPORT + isPackage:(BOOL *)isPackagePtr isGuided:(nullable BOOL *)isGuidedPtr +#endif +; @end diff --git a/Autoupdate/SUInstaller.m b/Autoupdate/SUInstaller.m index 9c687632..f76402a1 100644 --- a/Autoupdate/SUInstaller.m +++ b/Autoupdate/SUInstaller.m @@ -22,7 +22,7 @@ @implementation SUInstaller -+ (BOOL)isAliasFolderAtPath:(NSString *)path ++ (BOOL)isAliasFolderAtPath:(NSString *)path SPU_OBJC_DIRECT { NSNumber *aliasFlag = nil; [[NSURL fileURLWithPath:path] getResourceValue:&aliasFlag forKey:NSURLIsAliasFileKey error:nil]; @@ -31,7 +31,10 @@ return aliasFlag.boolValue && directoryFlag.boolValue; } -+ (nullable NSString *)installSourcePathInUpdateFolder:(NSString *)inUpdateFolder forHost:(SUHost *)host isPackage:(BOOL *)isPackagePtr isGuided:(BOOL *)isGuidedPtr ++ (nullable NSString *)installSourcePathInUpdateFolder:(NSString *)inUpdateFolder forHost:(SUHost *)host +#if SPARKLE_BUILD_PACKAGE_SUPPORT + isPackage:(BOOL *)isPackagePtr isGuided:(BOOL *)isGuidedPtr +#endif { NSParameterAssert(inUpdateFolder); NSParameterAssert(host); @@ -41,23 +44,31 @@ *newAppDownloadPath = nil, *bundleFileName = [[host bundlePath] lastPathComponent], *alternateBundleFileName = [[host name] stringByAppendingPathExtension:[[host bundlePath] pathExtension]]; +#if SPARKLE_BUILD_PACKAGE_SUPPORT + NSString *fallbackPackagePath = nil; + BOOL isPackage = NO; BOOL isGuided = YES; - NSString *fallbackPackagePath = nil; +#endif NSDirectoryEnumerator *dirEnum = [[NSFileManager defaultManager] enumeratorAtPath:inUpdateFolder]; NSString *bundleFileNameNoExtension = [bundleFileName stringByDeletingPathExtension]; while ((currentFile = [dirEnum nextObject])) { NSString *currentPath = [inUpdateFolder stringByAppendingPathComponent:currentFile]; NSString *currentFilename = [currentFile lastPathComponent]; +#if SPARKLE_BUILD_PACKAGE_SUPPORT NSString *currentExtension = [currentFile pathExtension]; NSString *currentFilenameNoExtension = [currentFilename stringByDeletingPathExtension]; +#endif if ([currentFilename isEqualToString:bundleFileName] || [currentFilename isEqualToString:alternateBundleFileName]) // We found one! { +#if SPARKLE_BUILD_PACKAGE_SUPPORT isPackage = NO; +#endif newAppDownloadPath = currentPath; break; +#if SPARKLE_BUILD_PACKAGE_SUPPORT } else if ([currentExtension isEqualToString:@"pkg"] || [currentExtension isEqualToString:@"mpkg"]) { if ([currentFilenameNoExtension isEqualToString:bundleFileNameNoExtension]) { @@ -68,12 +79,15 @@ // Remember any other non-matching packages we have seen should we need to use one of them as a fallback. fallbackPackagePath = currentPath; } +#endif } else { // Try matching on bundle identifiers in case the user has changed the name of the host app NSBundle *incomingBundle = [NSBundle bundleWithPath:currentPath]; NSString *hostBundleIdentifier = host.bundle.bundleIdentifier; if (incomingBundle && [incomingBundle.bundleIdentifier isEqualToString:hostBundleIdentifier]) { +#if SPARKLE_BUILD_PACKAGE_SUPPORT isPackage = NO; +#endif newAppDownloadPath = currentPath; break; } @@ -84,6 +98,7 @@ [dirEnum skipDescendents]; } +#if SPARKLE_BUILD_PACKAGE_SUPPORT // We don't have a valid path. Try to use the fallback package. if (newAppDownloadPath == nil && fallbackPackagePath != nil) { @@ -105,18 +120,33 @@ *isPackagePtr = isPackage; if (isGuidedPtr) *isGuidedPtr = isGuided; + +#endif if (!newAppDownloadPath) { - SULog(SULogLevelError, @"Searched %@ for %@.(app|pkg)", inUpdateFolder, bundleFileNameNoExtension); + SULog(SULogLevelError, @"Searched %@ for %@.(app%@)", inUpdateFolder, bundleFileNameNoExtension, +#if SPARKLE_BUILD_PACKAGE_SUPPORT + @"|pkg" +#else + @"" +#endif + ); } return newAppDownloadPath; } + (nullable id)installerForHost:(SUHost *)host expectedInstallationType:(NSString *)expectedInstallationType updateDirectory:(NSString *)updateDirectory homeDirectory:(NSString *)homeDirectory userName:(NSString *)userName error:(NSError * __autoreleasing *)error { +#if SPARKLE_BUILD_PACKAGE_SUPPORT BOOL isPackage = NO; BOOL isGuided = NO; - NSString *newDownloadPath = [self installSourcePathInUpdateFolder:updateDirectory forHost:host isPackage:&isPackage isGuided:&isGuided]; +#endif + + NSString *newDownloadPath = [self installSourcePathInUpdateFolder:updateDirectory forHost:host +#if SPARKLE_BUILD_PACKAGE_SUPPORT + isPackage:&isPackage isGuided:&isGuided +#endif + ]; if (newDownloadPath == nil) { if (error != NULL) { @@ -129,6 +159,7 @@ // We shouldn't implicitly trust the installation type fed into here from the appcast because the installation type helps us determine // ahead of time whether or not this installer tool should be ran as root or not id installer = nil; +#if SPARKLE_BUILD_PACKAGE_SUPPORT if (isPackage && isGuided) { if (![expectedInstallationType isEqualToString:SPUInstallationTypeGuidedPackage]) { if (error != NULL) { @@ -145,7 +176,9 @@ } else { installer = [[SUPackageInstaller alloc] initWithPackagePath:newDownloadPath]; } - } else { + } else +#endif + { if (![expectedInstallationType isEqualToString:SPUInstallationTypeApplication]) { if (error != NULL) { *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Found regular application update but expected '%@=%@' from the appcast item enclosure instead", SUAppcastAttributeInstallationType, expectedInstallationType] }]; diff --git a/Autoupdate/SUPackageInstaller.h b/Autoupdate/SUPackageInstaller.h index 779118af..8f4c7f71 100644 --- a/Autoupdate/SUPackageInstaller.h +++ b/Autoupdate/SUPackageInstaller.h @@ -6,14 +6,18 @@ // Copyright 2008 Andy Matuschak. All rights reserved. // +#if SPARKLE_BUILD_PACKAGE_SUPPORT + #import #import "SUInstallerProtocol.h" // This is the deprecated package installation type, aka the "interactive" package installer // For a more supported package installation, see SUGuidedPackageInstaller -@interface SUPackageInstaller : NSObject +SPU_OBJC_DIRECT_MEMBERS @interface SUPackageInstaller : NSObject - (instancetype)initWithPackagePath:(NSString *)packagePath; @end + +#endif diff --git a/Autoupdate/SUPackageInstaller.m b/Autoupdate/SUPackageInstaller.m index 056567fb..61c71071 100644 --- a/Autoupdate/SUPackageInstaller.m +++ b/Autoupdate/SUPackageInstaller.m @@ -6,6 +6,8 @@ // Copyright 2008 Andy Matuschak. All rights reserved. // +#if SPARKLE_BUILD_PACKAGE_SUPPORT + #import "SUPackageInstaller.h" #import "SUConstants.h" #import "SUErrors.h" @@ -14,18 +16,13 @@ #include "AppKitPrevention.h" -@interface SUPackageInstaller () - -@property (nonatomic, readonly, copy) NSString *packagePath; - -@end - @implementation SUPackageInstaller +{ + NSString *_packagePath; +} static NSString *SUOpenUtilityPath = @"/usr/bin/open"; -@synthesize packagePath = _packagePath; - - (instancetype)initWithPackagePath:(NSString *)packagePath { self = [super init]; @@ -52,7 +49,7 @@ static NSString *SUOpenUtilityPath = @"/usr/bin/open"; // -W = wait until the app has quit. // -n = Open another instance if already open. // -b = app bundle identifier - NSArray *args = @[@"-W", @"-n", @"-b", @"com.apple.installer", self.packagePath]; + NSArray *args = @[@"-W", @"-n", @"-b", @"com.apple.installer", _packagePath]; // Known bug: if the installation fails or is canceled, Sparkle goes ahead and restarts, thinking everything is fine. @try { @@ -80,3 +77,5 @@ static NSString *SUOpenUtilityPath = @"/usr/bin/open"; } @end + +#endif diff --git a/Autoupdate/SUPipedUnarchiver.h b/Autoupdate/SUPipedUnarchiver.h index 6e9c682f..47cec537 100644 --- a/Autoupdate/SUPipedUnarchiver.h +++ b/Autoupdate/SUPipedUnarchiver.h @@ -14,10 +14,12 @@ NS_ASSUME_NONNULL_BEGIN -@interface SUPipedUnarchiver : NSObject +SPU_OBJC_DIRECT_MEMBERS @interface SUPipedUnarchiver : NSObject - (instancetype)initWithArchivePath:(NSString *)archivePath; ++ (BOOL)canUnarchivePath:(NSString *)path; + @end NS_ASSUME_NONNULL_END diff --git a/Autoupdate/SUPipedUnarchiver.m b/Autoupdate/SUPipedUnarchiver.m index 43dd8a33..fcc24aa7 100644 --- a/Autoupdate/SUPipedUnarchiver.m +++ b/Autoupdate/SUPipedUnarchiver.m @@ -14,17 +14,12 @@ #include "AppKitPrevention.h" -@interface SUPipedUnarchiver () - -@property (nonatomic, copy, readonly) NSString *archivePath; - -@end - @implementation SUPipedUnarchiver +{ + NSString *_archivePath; +} -@synthesize archivePath = _archivePath; - -+ (nullable NSArray *)commandAndArgumentsConformingToTypeOfPath:(NSString *)path +static NSArray * _Nullable _commandAndArgumentsConformingToTypeOfPath(NSString *path) { NSArray *extractTGZ = @[@"/usr/bin/tar", @"-zxC"]; NSArray *extractTBZ = @[@"/usr/bin/tar", @"-jxC"]; @@ -55,7 +50,7 @@ + (BOOL)canUnarchivePath:(NSString *)path { - return ([self commandAndArgumentsConformingToTypeOfPath:path] != nil); + return _commandAndArgumentsConformingToTypeOfPath(path) != nil; } + (BOOL)mustValidateBeforeExtraction @@ -74,7 +69,7 @@ - (void)unarchiveWithCompletionBlock:(void (^)(NSError * _Nullable))completionBlock progressBlock:(void (^ _Nullable)(double))progressBlock { - NSArray *commandAndArguments = [[self class] commandAndArgumentsConformingToTypeOfPath:self.archivePath]; + NSArray *commandAndArguments = _commandAndArgumentsConformingToTypeOfPath(_archivePath); assert(commandAndArguments != nil); NSString *command = commandAndArguments.firstObject; @@ -89,26 +84,26 @@ } // This method abstracts the types that use a command line tool piping data from stdin. -- (void)extractArchivePipingDataToCommand:(NSString *)command arguments:(NSArray*)args notifier:(SUUnarchiverNotifier *)notifier +- (void)extractArchivePipingDataToCommand:(NSString *)command arguments:(NSArray*)args notifier:(SUUnarchiverNotifier *)notifier SPU_OBJC_DIRECT { // *** GETS CALLED ON NON-MAIN THREAD!!! @autoreleasepool { - NSString *destination = [self.archivePath stringByDeletingLastPathComponent]; + NSString *destination = [_archivePath stringByDeletingLastPathComponent]; - SULog(SULogLevelDefault, @"Extracting using '%@' '%@' < '%@' '%@'", command, [args componentsJoinedByString:@"' '"], self.archivePath, destination); + SULog(SULogLevelDefault, @"Extracting using '%@' '%@' < '%@' '%@'", command, [args componentsJoinedByString:@"' '"], _archivePath, destination); // Get the file size. - NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:self.archivePath error:nil]; + NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:_archivePath error:nil]; NSUInteger expectedLength = [(NSNumber *)[attributes objectForKey:NSFileSize] unsignedIntegerValue]; if (expectedLength == 0) { - NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Extraction failed, archive '%@' is empty", self.archivePath]}]; + NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Extraction failed, archive '%@' is empty", _archivePath]}]; [notifier notifyFailureWithError:error]; return; } - NSFileHandle *archiveInput = [NSFileHandle fileHandleForReadingAtPath:self.archivePath]; + NSFileHandle *archiveInput = [NSFileHandle fileHandleForReadingAtPath:_archivePath]; NSPipe *pipe = [NSPipe pipe]; NSTask *task = [[NSTask alloc] init]; @@ -127,16 +122,29 @@ NSFileHandle *archiveOutput = [pipe fileHandleForWriting]; NSUInteger bytesWritten = 0; +#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_15 BOOL hasIOErrorMethods; if (@available(macOS 10.15, *)) { hasIOErrorMethods = YES; } else { hasIOErrorMethods = NO; } +#endif do { NSData *data; - if (hasIOErrorMethods) { +#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_15 + if (!hasIOErrorMethods) { + @try { + data = [archiveInput readDataOfLength:256*1024]; + } @catch (NSException *exception) { + SULog(SULogLevelError, @"Failed to read data from archive with exception reason %@", exception.reason); + data = nil; + } + } + else +#endif + { NSError *readError = nil; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpartial-availability" @@ -145,13 +153,6 @@ if (data == nil) { SULog(SULogLevelError, @"Failed to read data from archive with error %@", readError); } - } else { - @try { - data = [archiveInput readDataOfLength:256*1024]; - } @catch (NSException *exception) { - SULog(SULogLevelError, @"Failed to read data from archive with exception reason %@", exception.reason); - data = nil; - } } NSUInteger len = [data length]; @@ -160,7 +161,18 @@ } NSError *writeError = nil; - if (hasIOErrorMethods) { +#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_15 + if (!hasIOErrorMethods) { + @try { + [archiveOutput writeData:data]; + } @catch (NSException *exception) { + SULog(SULogLevelError, @"Failed to write data to pipe with exception reason %@", exception.reason); + break; + } + } + else +#endif + { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpartial-availability" if (![archiveOutput writeData:data error:&writeError]) { @@ -168,13 +180,6 @@ SULog(SULogLevelError, @"Failed to write data to pipe with error %@", writeError); break; } - } else { - @try { - [archiveOutput writeData:data]; - } @catch (NSException *exception) { - SULog(SULogLevelError, @"Failed to write data to pipe with exception reason %@", exception.reason); - break; - } } bytesWritten += len; @@ -183,23 +188,37 @@ } while(bytesWritten < expectedLength); - if (@available(macOS 10.15, *)) { +#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_15 + if (@available(macOS 10.15, *)) +#endif + { NSError *archiveOutputCloseError = nil; if (![archiveOutput closeAndReturnError:&archiveOutputCloseError]) { SULog(SULogLevelError, @"Failed to close pipe with error %@", archiveOutputCloseError); } - } else { + } +#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_15 + else + { [archiveOutput closeFile]; } +#endif - if (@available(macOS 10.15, *)) { +#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_15 + if (@available(macOS 10.15, *)) +#endif + { NSError *archiveInputCloseError = nil; if (![archiveInput closeAndReturnError:&archiveInputCloseError]) { SULog(SULogLevelError, @"Failed to close archive input with error %@", archiveInputCloseError); } - } else { + } +#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_15 + else + { [archiveInput closeFile]; } +#endif [task waitUntilExit]; @@ -221,6 +240,6 @@ } } -- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], self.archivePath]; } +- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], _archivePath]; } @end diff --git a/Autoupdate/SUPlainInstaller.h b/Autoupdate/SUPlainInstaller.h index 6cee3006..c83fb66e 100644 --- a/Autoupdate/SUPlainInstaller.h +++ b/Autoupdate/SUPlainInstaller.h @@ -12,7 +12,7 @@ @class SUHost; @protocol SUVersionComparison; -@interface SUPlainInstaller : NSObject +SPU_OBJC_DIRECT_MEMBERS @interface SUPlainInstaller : NSObject /** @param host The current (old) bundle host diff --git a/Autoupdate/SUPlainInstaller.m b/Autoupdate/SUPlainInstaller.m index db8fd2af..177a634b 100644 --- a/Autoupdate/SUPlainInstaller.m +++ b/Autoupdate/SUPlainInstaller.m @@ -18,25 +18,15 @@ #include "AppKitPrevention.h" -@interface SUPlainInstaller () - -@property (nonatomic, readonly) SUHost *host; -@property (nonatomic, copy, readonly) NSString *bundlePath; -@property (nonatomic, copy, readonly) NSString *installationPath; - -@property (nonatomic) NSURL *temporaryOldDirectory; -// We get an obj-c warning if we use 'newTemporaryDirectory' name about new + ownership stuff, so use 'temporaryNewDirectory' instead -@property (nonatomic) NSURL *temporaryNewDirectory; - -@end - @implementation SUPlainInstaller - -@synthesize host = _host; -@synthesize bundlePath = _bundlePath; -@synthesize installationPath = _installationPath; -@synthesize temporaryOldDirectory = _temporaryOldDirectory; -@synthesize temporaryNewDirectory = _temporaryNewDirectory; +{ + SUHost *_host; + NSString *_bundlePath; + NSString *_installationPath; + NSURL *_temporaryOldDirectory; + // We get an obj-c warning if we use 'newTemporaryDirectory' name about new + ownership stuff, so use 'temporaryNewDirectory' instead + NSURL *_temporaryNewDirectory; +} - (instancetype)initWithHost:(SUHost *)host bundlePath:(NSString *)bundlePath installationPath:(NSString *)installationPath { @@ -49,23 +39,7 @@ return self; } -// Returns the bundle version from the specified host that is appropriate to use as a filename, or nil if we're unable to retrieve one -- (NSString *)bundleVersionAppropriateForFilenameFromHost:(SUHost *)host -{ - NSString *bundleVersion = [host objectForInfoDictionaryKey:(__bridge NSString *)kCFBundleVersionKey]; - NSString *trimmedVersion = @""; - - if (bundleVersion != nil) { - NSMutableCharacterSet *validCharacters = [NSMutableCharacterSet alphanumericCharacterSet]; - [validCharacters formUnionWithCharacterSet:[NSCharacterSet characterSetWithCharactersInString:@".-()"]]; - - trimmedVersion = [bundleVersion stringByTrimmingCharactersInSet:[validCharacters invertedSet]]; - } - - return trimmedVersion.length > 0 ? trimmedVersion : nil; -} - -- (BOOL)startInstallationToURL:(NSURL *)installationURL fromUpdateAtURL:(NSURL *)newURL withHost:(SUHost *)host progressBlock:(nullable void(^)(double))progress error:(NSError * __autoreleasing *)error +- (BOOL)startInstallationToURL:(NSURL *)installationURL fromUpdateAtURL:(NSURL *)newURL withHost:(SUHost *)host progressBlock:(nullable void(^)(double))progress error:(NSError * __autoreleasing *)error SPU_OBJC_DIRECT { if (installationURL == nil || newURL == nil) { // this really shouldn't happen but just in case @@ -123,7 +97,7 @@ return NO; } - self.temporaryNewDirectory = tempNewDirectoryURL; + _temporaryNewDirectory = tempNewDirectoryURL; if (progress) { progress(3/10.0); @@ -222,7 +196,7 @@ return NO; } - self.temporaryOldDirectory = tempOldDirectoryURL; + _temporaryOldDirectory = tempOldDirectoryURL; if (progress) { progress(9/10.0); @@ -289,9 +263,9 @@ { // Prevent malicious downgrades // Note that we may not be able to do this for package installations, hence this code being done here - NSString *hostVersion = [self.host version]; + NSString *hostVersion = [_host version]; - NSBundle *bundle = [NSBundle bundleWithPath:self.bundlePath]; + NSBundle *bundle = [NSBundle bundleWithPath:_bundlePath]; SUHost *updateHost = [[SUHost alloc] initWithBundle:bundle]; NSString *updateVersion = [updateHost objectForInfoDictionaryKey:(__bridge NSString *)kCFBundleVersionKey]; @@ -314,19 +288,19 @@ { // Note: we must do most installation work in the third stage due to relying on our application sitting in temporary directories. // It must not be possible for our update to sit in temporary directories for a very long time. - return [self startInstallationToURL:[NSURL fileURLWithPath:self.installationPath] fromUpdateAtURL:[NSURL fileURLWithPath:self.bundlePath] withHost:self.host progressBlock:cb error:error]; + return [self startInstallationToURL:[NSURL fileURLWithPath:_installationPath] fromUpdateAtURL:[NSURL fileURLWithPath:_bundlePath] withHost:_host progressBlock:cb error:error]; } - (void)performCleanup { SUFileManager *fileManager = [[SUFileManager alloc] init]; - if (self.temporaryNewDirectory != nil) { - [fileManager removeItemAtURL:self.temporaryNewDirectory error:NULL]; + if (_temporaryNewDirectory != nil) { + [fileManager removeItemAtURL:_temporaryNewDirectory error:NULL]; } - if (self.temporaryOldDirectory != nil) { - [fileManager removeItemAtURL:self.temporaryOldDirectory error:NULL]; + if (_temporaryOldDirectory != nil) { + [fileManager removeItemAtURL:_temporaryOldDirectory error:NULL]; } } diff --git a/Autoupdate/SUSignatureVerifier.h b/Autoupdate/SUSignatureVerifier.h index e5ce518b..fb6c577b 100644 --- a/Autoupdate/SUSignatureVerifier.h +++ b/Autoupdate/SUSignatureVerifier.h @@ -19,7 +19,7 @@ @class SUSignatures; @class SUPublicKeys; -@interface SUSignatureVerifier : NSObject +SPU_OBJC_DIRECT_MEMBERS @interface SUSignatureVerifier : NSObject + (BOOL)validatePath:(NSString *)path withSignatures:(SUSignatures *)signatures withPublicKeys:(SUPublicKeys *)pkeys error:(NSError * __autoreleasing *)error; diff --git a/Autoupdate/SUSignatureVerifier.m b/Autoupdate/SUSignatureVerifier.m index f20d2a96..a40863ee 100644 --- a/Autoupdate/SUSignatureVerifier.m +++ b/Autoupdate/SUSignatureVerifier.m @@ -16,21 +16,19 @@ #import "SULog.h" #import "SUSignatures.h" #import "SUErrors.h" +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT #include +#endif #import "ed25519.h" #include "AppKitPrevention.h" -@interface SUSignatureVerifier () -@property (readonly) SUPublicKeys *pubKeys; -@end - -@implementation SUSignatureVerifier { +@implementation SUSignatureVerifier +{ + SUPublicKeys *_pubKeys; } -@synthesize pubKeys = _pubKeys; - + (BOOL)validatePath:(NSString *)path withSignatures:(SUSignatures *)signatures withPublicKeys:(SUPublicKeys *)pkeys error:(NSError * __autoreleasing *)error { SUSignatureVerifier *verifier = [(SUSignatureVerifier *)[self alloc] initWithPublicKeys:pkeys]; @@ -54,9 +52,10 @@ return self; } -- (SecKeyRef)dsaSecKeyRef { - - NSData *data = [self.pubKeys.dsaPubKey dataUsingEncoding:NSASCIIStringEncoding]; +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT +- (SecKeyRef)dsaSecKeyRef SPU_OBJC_DIRECT +{ + NSData *data = [_pubKeys.dsaPubKey dataUsingEncoding:NSASCIIStringEncoding]; if (!self || !data.length) { SULog(SULogLevelError, @"Could not read public DSA key"); return nil; @@ -89,6 +88,7 @@ CFRelease(items); return dsaPubKeySecKey; } +#endif - (BOOL)verifyFileAtPath:(NSString *)path signatures:(SUSignatures *)signatures error:(NSError * __autoreleasing *)error { @@ -106,7 +106,7 @@ return NO; } - switch (self.pubKeys.ed25519PubKeyStatus) { + switch (_pubKeys.ed25519PubKeyStatus) { case SUSigningInputStatusAbsent: if (signatures.ed25519SignatureStatus != SUSigningInputStatusAbsent) { SULog(SULogLevelDefault, @"The update has an EdDSA signature, but it won't be used, because the old app doesn't have an EdDSA public key"); @@ -165,11 +165,14 @@ return NO; } - if (ed25519_verify(signatures.ed25519Signature, data.bytes, data.length, self.pubKeys.ed25519PubKey)) { + if (ed25519_verify(signatures.ed25519Signature, data.bytes, data.length, _pubKeys.ed25519PubKey)) { SULog(SULogLevelDefault, @"OK: EdDSA signature is correct"); +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT // No need to check DSA when EdDSA verification succeeded, unless a DSA signature is provided and it's // erroneously invalid - if (signatures.dsaSignatureStatus != SUSigningInputStatusInvalid) { + if (signatures.dsaSignatureStatus != SUSigningInputStatusInvalid) +#endif + { return YES; } } else { @@ -177,9 +180,11 @@ SULog(SULogLevelError, @"%@", message); +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT if (signatures.dsaSignatureStatus != SUSigningInputStatusAbsent) { SULog(SULogLevelDefault, @"DSA signature won't be checked, because EdDSA verification has already failed"); } +#endif if (error != NULL) { *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUValidationError userInfo:@{ NSLocalizedDescriptionKey: message }]; @@ -192,7 +197,8 @@ break; } - switch (self.pubKeys.dsaPubKeyStatus) { +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT + switch (_pubKeys.dsaPubKeyStatus) { case SUSigningInputStatusAbsent: if (signatures.dsaSignatureStatus != SUSigningInputStatusAbsent) { SULog(SULogLevelDefault, @"The update has a DSA signature, but it can't be used, because the old app doesn't have a DSA public key"); @@ -235,6 +241,7 @@ } } } +#endif if (error != NULL) { // Use generic failure @@ -244,7 +251,8 @@ return NO; } -- (BOOL)verifyDSASignatureOfStream:(NSInputStream *)stream dsaSignature:(NSData *)dsaSignature error:(NSError * __autoreleasing *)outError +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT +- (BOOL)verifyDSASignatureOfStream:(NSInputStream *)stream dsaSignature:(NSData *)dsaSignature error:(NSError * __autoreleasing *)outError SPU_OBJC_DIRECT { if (!stream || !dsaSignature) { SULog(SULogLevelError, @"Invalid arguments to verifyStream"); @@ -301,10 +309,7 @@ return cleanup(); } -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdirect-ivar-access" dataVerifyTransform = SecVerifyTransformCreate(dsaPubKeySecKey, (__bridge CFDataRef)dsaSignature, &error); -#pragma clang diagnostic pop if (!dataVerifyTransform) { SULog(SULogLevelError, @"Could not understand format of the signature: %@; Signature data: %@", error, dsaSignature); if (outError != NULL) { @@ -368,5 +373,6 @@ cleanup(); return result.boolValue; } +#endif @end diff --git a/Autoupdate/SUUnarchiver.h b/Autoupdate/SUUnarchiver.h index de440b9b..d885a552 100644 --- a/Autoupdate/SUUnarchiver.h +++ b/Autoupdate/SUUnarchiver.h @@ -12,7 +12,7 @@ NS_ASSUME_NONNULL_BEGIN @protocol SUUnarchiverProtocol; -@interface SUUnarchiver : NSObject +SPU_OBJC_DIRECT_MEMBERS @interface SUUnarchiver : NSObject + (nullable id )unarchiverForPath:(NSString *)path updatingHostBundlePath:(nullable NSString *)hostPath decryptionPassword:(nullable NSString *)decryptionPassword expectingInstallationType:(NSString *)installationType; diff --git a/Autoupdate/SUUnarchiver.m b/Autoupdate/SUUnarchiver.m index 5550589d..515c2f0a 100644 --- a/Autoupdate/SUUnarchiver.m +++ b/Autoupdate/SUUnarchiver.m @@ -23,17 +23,24 @@ if ([SUPipedUnarchiver canUnarchivePath:path]) { return [[SUPipedUnarchiver alloc] initWithArchivePath:path]; - } else if ([SUDiskImageUnarchiver canUnarchivePath:path]) { + } +#if SPARKLE_BUILD_DMG_SUPPORT + else if ([SUDiskImageUnarchiver canUnarchivePath:path]) { return [[SUDiskImageUnarchiver alloc] initWithArchivePath:path decryptionPassword:decryptionPassword]; - } else if ([SUBinaryDeltaUnarchiver canUnarchivePath:path]) { + } +#endif + else if ([SUBinaryDeltaUnarchiver canUnarchivePath:path]) { assert(hostPath != nil); NSString *nonNullHostPath = hostPath; return [[SUBinaryDeltaUnarchiver alloc] initWithArchivePath:path updateHostBundlePath:nonNullHostPath]; - } else if ([SUFlatPackageUnarchiver canUnarchivePath:path]) { + } +#if SPARKLE_BUILD_PACKAGE_SUPPORT + else if ([SUFlatPackageUnarchiver canUnarchivePath:path]) { // Flat packages are only supported for guided packaage installs return [[SUFlatPackageUnarchiver alloc] initWithFlatPackagePath:path expectingInstallationType:installationType]; } +#endif return nil; } diff --git a/Autoupdate/SUUnarchiverNotifier.h b/Autoupdate/SUUnarchiverNotifier.h index 9c8b65a8..91091107 100644 --- a/Autoupdate/SUUnarchiverNotifier.h +++ b/Autoupdate/SUUnarchiverNotifier.h @@ -10,7 +10,7 @@ NS_ASSUME_NONNULL_BEGIN -@interface SUUnarchiverNotifier : NSObject +SPU_OBJC_DIRECT_MEMBERS @interface SUUnarchiverNotifier : NSObject - (instancetype)initWithCompletionBlock:(void (^)(NSError * _Nullable))completionBlock progressBlock:(void (^ _Nullable)(double))progressBlock; diff --git a/Autoupdate/SUUnarchiverNotifier.m b/Autoupdate/SUUnarchiverNotifier.m index 4fd5e37d..5fdbdbb6 100644 --- a/Autoupdate/SUUnarchiverNotifier.m +++ b/Autoupdate/SUUnarchiverNotifier.m @@ -13,17 +13,11 @@ #include "AppKitPrevention.h" -@interface SUUnarchiverNotifier () - -@property (nonatomic, readonly, copy) void (^completionBlock)(NSError * _Nullable); -@property (nonatomic, readonly, copy) void (^ _Nullable progressBlock)(double); - -@end - @implementation SUUnarchiverNotifier - -@synthesize completionBlock = _completionBlock; -@synthesize progressBlock = _progressBlock; +{ + void (^_completionBlock)(NSError * _Nullable); + void (^ _Nullable _progressBlock)(double); +} - (instancetype)initWithCompletionBlock:(void (^)(NSError * _Nullable))completionBlock progressBlock:(void (^ _Nullable)(double))progressBlock { @@ -40,13 +34,13 @@ - (void)notifySuccess { dispatch_async(dispatch_get_main_queue(), ^{ - self.completionBlock(nil); + self->_completionBlock(nil); }); } - (void)notifyFailureWithError:(NSError * _Nullable)reason { - NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithObject:SULocalizedString(@"An error occurred while extracting the archive. Please try again later.", nil) forKey:NSLocalizedDescriptionKey]; + NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithObject:@"An error occurred while extracting the archive. Please try again later." forKey:NSLocalizedDescriptionKey]; if (reason) { [userInfo setObject:(NSError * _Nonnull)reason forKey:NSUnderlyingErrorKey]; } @@ -54,15 +48,15 @@ NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUUnarchivingError userInfo:userInfo]; dispatch_async(dispatch_get_main_queue(), ^{ - self.completionBlock(error); + self->_completionBlock(error); }); } - (void)notifyProgress:(double)progress { - if (self.progressBlock != nil) { + if (_progressBlock != nil) { dispatch_async(dispatch_get_main_queue(), ^{ - self.progressBlock(progress); + self->_progressBlock(progress); }); } } diff --git a/Autoupdate/SUUnarchiverProtocol.h b/Autoupdate/SUUnarchiverProtocol.h index 4be1ea49..5e20ccb3 100644 --- a/Autoupdate/SUUnarchiverProtocol.h +++ b/Autoupdate/SUUnarchiverProtocol.h @@ -12,8 +12,6 @@ NS_ASSUME_NONNULL_BEGIN @protocol SUUnarchiverProtocol -+ (BOOL)canUnarchivePath:(NSString *)path; - + (BOOL)mustValidateBeforeExtraction; - (void)unarchiveWithCompletionBlock:(void (^)(NSError * _Nullable))completionBlock progressBlock:(void (^ _Nullable)(double))progressBlock; diff --git a/Autoupdate/StatusInfo.h b/Autoupdate/StatusInfo.h index 12fc98fe..d84dd04f 100644 --- a/Autoupdate/StatusInfo.h +++ b/Autoupdate/StatusInfo.h @@ -11,7 +11,7 @@ NS_ASSUME_NONNULL_BEGIN -@interface StatusInfo : NSObject +SPU_OBJC_DIRECT_MEMBERS @interface StatusInfo : NSObject - (instancetype)initWithHostBundleIdentifier:(NSString *)bundleIdentifier; diff --git a/Autoupdate/StatusInfo.m b/Autoupdate/StatusInfo.m index 24ca173c..d2e208a0 100644 --- a/Autoupdate/StatusInfo.m +++ b/Autoupdate/StatusInfo.m @@ -21,6 +21,7 @@ { NSXPCListener *_xpcListener; NSMutableDictionary *_pendingReplies; + NSUInteger _pendingReplyCounter; } diff --git a/Autoupdate/TerminationListener.h b/Autoupdate/TerminationListener.h index f097e941..b8ebe11e 100644 --- a/Autoupdate/TerminationListener.h +++ b/Autoupdate/TerminationListener.h @@ -10,7 +10,7 @@ NS_ASSUME_NONNULL_BEGIN -@interface TerminationListener : NSObject +SPU_OBJC_DIRECT_MEMBERS @interface TerminationListener : NSObject - (instancetype)initWithProcessIdentifier:(NSNumber * _Nullable)processIdentifier; diff --git a/Autoupdate/TerminationListener.m b/Autoupdate/TerminationListener.m index 8c20fd07..1f365b7b 100644 --- a/Autoupdate/TerminationListener.m +++ b/Autoupdate/TerminationListener.m @@ -16,19 +16,14 @@ #include "AppKitPrevention.h" -@interface TerminationListener () - -@property (nonatomic, readonly, nullable) NSNumber *processIdentifier; -@property (nonatomic) BOOL watchedTermination; -@property (nonatomic, copy) void (^completionBlock)(BOOL); - -@end - @implementation TerminationListener - -@synthesize completionBlock = _completionBlock; -@synthesize processIdentifier = _processIdentifier; -@synthesize watchedTermination = _watchedTermination; +{ + NSNumber *_processIdentifier; + + void (^_completionBlock)(BOOL); + + BOOL _watchedTermination; +} - (instancetype)initWithProcessIdentifier:(NSNumber * _Nullable)processIdentifier { @@ -42,22 +37,22 @@ - (BOOL)terminated { - return (self.watchedTermination || self.processIdentifier == nil) ? YES : (kill(self.processIdentifier.intValue, 0) != 0); + return (_watchedTermination || _processIdentifier == nil) ? YES : (kill(_processIdentifier.intValue, 0) != 0); } -- (void)invokeCompletionWithSuccess:(BOOL)success +- (void)invokeCompletionWithSuccess:(BOOL)success SPU_OBJC_DIRECT { - if (self.completionBlock != nil) { - self.completionBlock(success); - self.completionBlock = nil; + if (_completionBlock != nil) { + _completionBlock(success); + _completionBlock = nil; } } - (void)startListeningWithCompletion:(void (^)(BOOL))completionBlock { - self.completionBlock = completionBlock; + _completionBlock = [completionBlock copy]; - if (self.processIdentifier == nil) { + if (_processIdentifier == nil) { [self invokeCompletionWithSuccess:YES]; return; } @@ -66,7 +61,7 @@ // As described in https://developer.apple.com/library/mac/technotes/tn2050/_index.html#//apple_ref/doc/uid/DTS10003081-CH1-SUBSECTION10 // By using kqueues, we can stay away from using AppKit in case we ever decide to abandon it - pid_t processIdentifier = self.processIdentifier.intValue; + pid_t processIdentifier = _processIdentifier.intValue; int queue = kqueue(); if (queue == -1) { SULog(SULogLevelError, @"Failed to create kqueue() due to error %d: %@", errno, @(strerror(errno))); @@ -124,7 +119,7 @@ static void noteExitKQueueCallback(CFFileDescriptorRef file, CFOptionFlags __unu kevent(CFFileDescriptorGetNativeDescriptor(file), NULL, 0, &event, 1, NULL); TerminationListener *self = CFBridgingRelease(info); - self.watchedTermination = YES; + self->_watchedTermination = YES; [self invokeCompletionWithSuccess:YES]; } diff --git a/Configurations/CommandLineTool-Shared.xcconfig b/Configurations/CommandLineTool-Shared.xcconfig index 218fec5c..568f63c9 100644 --- a/Configurations/CommandLineTool-Shared.xcconfig +++ b/Configurations/CommandLineTool-Shared.xcconfig @@ -3,4 +3,4 @@ #include "ConfigSwift.xcconfig" SWIFT_OBJC_BRIDGING_HEADER = $(PRODUCT_NAME)/Bridging-Header.h -GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS) BUILDING_SPARKLE_TOOL=1 +GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS) BUILDING_EXTERNALLY=1 diff --git a/Configurations/ConfigCommon.xcconfig b/Configurations/ConfigCommon.xcconfig index 2c6c2b8a..b86750d3 100644 --- a/Configurations/ConfigCommon.xcconfig +++ b/Configurations/ConfigCommon.xcconfig @@ -1,15 +1,55 @@ // Common -SPARKLE_BUNDLE_IDENTIFIER = org.sparkle-project.Sparkle -SPARKLE_RELAUNCH_TOOL_NAME = Autoupdate -SPARKLE_INSTALLER_PROGRESS_TOOL_NAME = Updater - -// Set to 1 or 0 to bundle or not bundle provided XPC Services in Sparkle framework +// Set to 1 or 0 to build and bundle the provided XPC Services in Sparkle framework +// (Note for testing purposes for sandboxed apps, disabling all XPC services and then re-enabling them +// may not work on the same login session due to a system caching issue. See comments for setting FRAMEWORK_VERSION for more info) SPARKLE_EMBED_INSTALLER_LAUNCHER_XPC_SERVICE = 1 +// Embedding the downloader service also enables building legacy WebKit1 support SPARKLE_EMBED_DOWNLOADER_XPC_SERVICE = 1 SPARKLE_EMBED_INSTALLER_STATUS_XPC_SERVICE = 0 SPARKLE_EMBED_INSTALLER_CONNECTION_XPC_SERVICE = 0 +// Set to 0 to disable building legacy 1.x SUUpdater stub +SPARKLE_BUILD_LEGACY_SUUPDATER = 1 + +// Set to 0 to not build legacy DSA signing support (useful for migrating to EdDSA) +SPARKLE_BUILD_LEGACY_DSA_SUPPORT = 1 + +// Set to 0 to not build legacy / xar based delta update support +SPARKLE_BUILD_LEGACY_DELTA_SUPPORT = 1 + +// Set to 0 to not build bzip2 support for version 3 delta based updates +SPARKLE_BUILD_BZIP2_DELTA_SUPPORT = 1 + +// Set to 0 to not build support for package (pkg) based installations +SPARKLE_BUILD_PACKAGE_SUPPORT = 1 + +// Set to 0 to not build support for extracting updates from disk images (dmgs) +SPARKLE_BUILD_DMG_SUPPORT = 1 + +// Set to 0 to only build all non-UI bits (which means client uses a custom SPUUserDriver) +SPARKLE_BUILD_UI_BITS = 1 + +// Set to 0 to not use and copy localization / string files to framework +SPARKLE_COPY_LOCALIZATIONS = 1 + +// Compilation flags for Swift tools and unit tests +// If SPARKLE_BUILD_LEGACY_DELTA_SUPPORT is set to 0, remove -DSPARKLE_BUILD_LEGACY_DSA_SUPPORT +// If SPARKLE_BUILD_PACKAGE_SUPPORT is set to 0, remove -DSPARKLE_BUILD_PACKAGE_SUPPORT +// If SPARKLE_BUILD_DMG_SUPPORT is set to 0, remove -DSPARKLE_BUILD_DMG_SUPPORT +OTHER_SWIFT_FLAGS_COMMON = -DSPARKLE_BUILD_LEGACY_DSA_SUPPORT -DSPARKLE_BUILD_PACKAGE_SUPPORT -DSPARKLE_BUILD_DMG_SUPPORT + +// Minimum supported macOS version +MACOSX_DEPLOYMENT_TARGET = 10.13 + +// Supported architectures +ARCHS = $(ARCHS_STANDARD) + +// Default Sparkle names +SPARKLE_BUNDLE_IDENTIFIER = org.sparkle-project.Sparkle +SPARKLE_RELAUNCH_TOOL_NAME = Autoupdate +SPARKLE_INSTALLER_PROGRESS_TOOL_NAME = Updater + // Set these if you want to use custom name for the XPC Services // For the Installer one in particular, this name may show up in an authorization prompt // when installing an update that requires authorization. @@ -26,9 +66,6 @@ INSTALLER_STATUS_BUNDLE_ID = ${XPC_SERVICE_BUNDLE_ID_PREFIX}.InstallerStatus INSTALLER_LAUNCHER_BUNDLE_ID = ${XPC_SERVICE_BUNDLE_ID_PREFIX}.InstallerLauncher DOWNLOADER_BUNDLE_ID = ${XPC_SERVICE_BUNDLE_ID_PREFIX}.Downloader -// Set to 0 to only build all non-UI bits -SPARKLE_BUILD_UI_BITS = 1 - // If your app file on disk is named "MyApp 1.1b4", Sparkle usually updates it // in place, giving you an app named 1.1b4 that is actually 1.2. Turn the // following on to always reset the name back to "MyApp" @@ -55,12 +92,10 @@ ALWAYS_SEARCH_USER_PATHS = NO ENABLE_STRICT_OBJC_MSGSEND = YES GCC_SYMBOLS_PRIVATE_EXTERN = YES GCC_INLINES_ARE_PRIVATE_EXTERN = YES -ARCHS = $(ARCHS_STANDARD) -MACOSX_DEPLOYMENT_TARGET = 10.13 PRODUCT_NAME = ${TARGET_NAME} PRODUCT_BUNDLE_IDENTIFIER = org.sparkle-project.Sparkle.${PRODUCT_NAME:rfc1034identifier} -GCC_PREPROCESSOR_DEFINITIONS_COMMON = SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME=$(SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME) SPARKLE_BUILD_UI_BITS=$(SPARKLE_BUILD_UI_BITS) SPARKLE_BUNDLE_IDENTIFIER=\"$(SPARKLE_BUNDLE_IDENTIFIER)\" CURRENT_PROJECT_VERSION=\"$(CURRENT_PROJECT_VERSION)\" MARKETING_VERSION=\"$(MARKETING_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_NAME=\"${INSTALLER_LAUNCHER_NAME}\" INSTALLER_LAUNCHER_BUNDLE_ID=\"${INSTALLER_LAUNCHER_BUNDLE_ID}\" INSTALLER_CONNECTION_NAME=\"${INSTALLER_CONNECTION_NAME}\" INSTALLER_CONNECTION_BUNDLE_ID=\"${INSTALLER_CONNECTION_BUNDLE_ID}\" INSTALLER_STATUS_NAME=\"${INSTALLER_STATUS_NAME}\" INSTALLER_STATUS_BUNDLE_ID=\"${INSTALLER_STATUS_BUNDLE_ID}\" DOWNLOADER_NAME=\"${DOWNLOADER_NAME}\" DOWNLOADER_BUNDLE_ID=\"${DOWNLOADER_BUNDLE_ID}\" +GCC_PREPROCESSOR_DEFINITIONS_COMMON = SPU_OBJC_DIRECT=__attribute__((objc_direct)) SPU_OBJC_DIRECT_MEMBERS=__attribute__((objc_direct_members)) SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME=$(SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME) SPARKLE_BUILD_UI_BITS=$(SPARKLE_BUILD_UI_BITS) SPARKLE_COPY_LOCALIZATIONS=$(SPARKLE_COPY_LOCALIZATIONS) SPARKLE_BUILD_LEGACY_SUUPDATER=$(SPARKLE_BUILD_LEGACY_SUUPDATER) SPARKLE_BUILD_PACKAGE_SUPPORT=$(SPARKLE_BUILD_PACKAGE_SUPPORT) SPARKLE_BUILD_DMG_SUPPORT=$(SPARKLE_BUILD_DMG_SUPPORT) SPARKLE_BUILD_LEGACY_DELTA_SUPPORT=$(SPARKLE_BUILD_LEGACY_DELTA_SUPPORT) SPARKLE_BUILD_BZIP2_DELTA_SUPPORT=$(SPARKLE_BUILD_BZIP2_DELTA_SUPPORT) SPARKLE_BUILD_LEGACY_DSA_SUPPORT=$(SPARKLE_BUILD_LEGACY_DSA_SUPPORT) SPARKLE_BUNDLE_IDENTIFIER=\"$(SPARKLE_BUNDLE_IDENTIFIER)\" CURRENT_PROJECT_VERSION=\"$(CURRENT_PROJECT_VERSION)\" MARKETING_VERSION=\"$(MARKETING_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_NAME=\"${INSTALLER_LAUNCHER_NAME}\" INSTALLER_LAUNCHER_BUNDLE_ID=\"${INSTALLER_LAUNCHER_BUNDLE_ID}\" INSTALLER_LAUNCHER_XPC_SERVICE_EMBEDDED=$(SPARKLE_EMBED_INSTALLER_LAUNCHER_XPC_SERVICE) INSTALLER_CONNECTION_NAME=\"${INSTALLER_CONNECTION_NAME}\" INSTALLER_CONNECTION_BUNDLE_ID=\"${INSTALLER_CONNECTION_BUNDLE_ID}\" INSTALLER_CONNECTION_XPC_SERVICE_EMBEDDED=$(SPARKLE_EMBED_INSTALLER_CONNECTION_XPC_SERVICE) INSTALLER_STATUS_NAME=\"${INSTALLER_STATUS_NAME}\" INSTALLER_STATUS_BUNDLE_ID=\"${INSTALLER_STATUS_BUNDLE_ID}\" INSTALLER_STATUS_XPC_SERVICE_EMBEDDED=$(SPARKLE_EMBED_INSTALLER_STATUS_XPC_SERVICE) DOWNLOADER_NAME=\"${DOWNLOADER_NAME}\" DOWNLOADER_BUNDLE_ID=\"${DOWNLOADER_BUNDLE_ID}\" DOWNLOADER_XPC_SERVICE_EMBEDDED=$(SPARKLE_EMBED_DOWNLOADER_XPC_SERVICE) CODE_SIGN_IDENTITY = - SDKROOT = macosx @@ -114,8 +149,5 @@ GCC_WARN_UNUSED_LABEL = YES GCC_WARN_UNUSED_PARAMETER = YES GCC_WARN_UNUSED_VARIABLE = YES -// These should be removed once the conversion to ARC is complete -WARNING_CFLAGS_EXTRA = -Wno-custom-atomic-properties -Wno-implicit-atomic-properties - // Turn on all warnings, then disable a few which are almost impossible to avoid -WARNING_CFLAGS = -Wall -Weverything -Wno-unused-macros -Wno-gnu-statement-expression -Wno-arc-repeated-use-of-weak -Wno-auto-import -Wno-gnu-zero-variadic-macro-arguments -Wno-format-non-iso -Wno-direct-ivar-access $(WARNING_CFLAGS_EXTRA) +WARNING_CFLAGS = -Wall -Weverything -Wno-unused-macros -Wno-gnu-statement-expression -Wno-auto-import -Wno-gnu-zero-variadic-macro-arguments -Wno-format-non-iso -Wno-direct-ivar-access -Werror=undef diff --git a/Configurations/ConfigCommonCoverage.xcconfig b/Configurations/ConfigCommonCoverage.xcconfig index 6473d933..22fa4fb2 100644 --- a/Configurations/ConfigCommonCoverage.xcconfig +++ b/Configurations/ConfigCommonCoverage.xcconfig @@ -1,6 +1,7 @@ #include "ConfigCommonDebug.xcconfig" GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS_COMMON) +OTHER_SWIFT_FLAGS = $(OTHER_SWIFT_FLAGS_COMMON) CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_COMMA = YES; diff --git a/Configurations/ConfigCommonDebug.xcconfig b/Configurations/ConfigCommonDebug.xcconfig index a47e02c6..54bfb6b3 100644 --- a/Configurations/ConfigCommonDebug.xcconfig +++ b/Configurations/ConfigCommonDebug.xcconfig @@ -13,5 +13,6 @@ DEBUG_INFORMATION_FORMAT = dwarf ENABLE_TESTABILITY = YES GCC_GENERATE_DEBUGGING_SYMBOLS = YES GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS_COMMON) DEBUG=1 +OTHER_SWIFT_FLAGS = $(OTHER_SWIFT_FLAGS_COMMON) ONLY_ACTIVE_ARCH = YES COPY_PHASE_STRIP = NO diff --git a/Configurations/ConfigCommonRelease.xcconfig b/Configurations/ConfigCommonRelease.xcconfig index f2ea3561..8b7ed850 100644 --- a/Configurations/ConfigCommonRelease.xcconfig +++ b/Configurations/ConfigCommonRelease.xcconfig @@ -12,6 +12,7 @@ GCC_OPTIMIZATION_LEVEL = s DEBUG_INFORMATION_FORMAT = dwarf-with-dsym GCC_GENERATE_DEBUGGING_SYMBOLS = YES GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS_COMMON) DEBUG=0 +OTHER_SWIFT_FLAGS = $(OTHER_SWIFT_FLAGS_COMMON) DEAD_CODE_STRIPPING = YES GCC_TREAT_WARNINGS_AS_ERRORS = NO GCC_WARN_UNINITIALIZED_AUTOS = YES diff --git a/Configurations/ConfigDownloader.xcconfig b/Configurations/ConfigDownloader.xcconfig index f767b341..7b692e29 100644 --- a/Configurations/ConfigDownloader.xcconfig +++ b/Configurations/ConfigDownloader.xcconfig @@ -5,4 +5,4 @@ WRAPPER_EXTENSION = xpc PRODUCT_BUNDLE_IDENTIFIER = ${DOWNLOADER_BUNDLE_ID} PRODUCT_NAME = ${DOWNLOADER_NAME} CODE_SIGN_ENTITLEMENTS = Downloader/${DOWNLOADER_BUNDLE_ID}.entitlements -GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS) BUILDING_SPARKLE_DOWNLOADER_SERVICE=1 +GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS) BUILDING_SPARKLE_SOURCES_EXTERNALLY=1 diff --git a/Configurations/ConfigFrameworkRelease.xcconfig b/Configurations/ConfigFrameworkRelease.xcconfig new file mode 100644 index 00000000..5f16cbe8 --- /dev/null +++ b/Configurations/ConfigFrameworkRelease.xcconfig @@ -0,0 +1,4 @@ +#include "ConfigFramework.xcconfig" + +// Strip all non-global symbols (including debug symbols) +STRIP_STYLE = non-global diff --git a/Configurations/ConfigInstallerConnection.xcconfig b/Configurations/ConfigInstallerConnection.xcconfig index d9204a7c..41ee7c46 100644 --- a/Configurations/ConfigInstallerConnection.xcconfig +++ b/Configurations/ConfigInstallerConnection.xcconfig @@ -4,3 +4,4 @@ INFOPLIST_FILE = InstallerConnection/Info.plist WRAPPER_EXTENSION = xpc PRODUCT_BUNDLE_IDENTIFIER = ${INSTALLER_CONNECTION_BUNDLE_ID} PRODUCT_NAME = ${INSTALLER_CONNECTION_NAME} +GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS) BUILDING_SPARKLE_SOURCES_EXTERNALLY=1 diff --git a/Configurations/ConfigInstallerLauncher.xcconfig b/Configurations/ConfigInstallerLauncher.xcconfig index 2db6ec80..1bc46e23 100644 --- a/Configurations/ConfigInstallerLauncher.xcconfig +++ b/Configurations/ConfigInstallerLauncher.xcconfig @@ -4,3 +4,4 @@ INFOPLIST_FILE = InstallerLauncher/Info.plist WRAPPER_EXTENSION = xpc PRODUCT_BUNDLE_IDENTIFIER = ${INSTALLER_LAUNCHER_BUNDLE_ID} PRODUCT_NAME = ${INSTALLER_LAUNCHER_NAME} +GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS) BUILDING_SPARKLE_SOURCES_EXTERNALLY=1 diff --git a/Configurations/ConfigInstallerProgress.xcconfig b/Configurations/ConfigInstallerProgress.xcconfig index 2538c9d7..0d1a5d43 100644 --- a/Configurations/ConfigInstallerProgress.xcconfig +++ b/Configurations/ConfigInstallerProgress.xcconfig @@ -2,6 +2,6 @@ INFOPLIST_FILE = Sparkle/InstallerProgress/InstallerProgress-Info.plist PRODUCT_NAME = $(SPARKLE_INSTALLER_PROGRESS_TOOL_NAME) -GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS) BUILDING_SPARKLE=0 +GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS) BUILDING_SPARKLE=0 BUILDING_SPARKLE_SOURCES_EXTERNALLY=1 SKIP_INSTALL = YES CLANG_ENABLE_MODULES = NO diff --git a/Configurations/ConfigInstallerStatus.xcconfig b/Configurations/ConfigInstallerStatus.xcconfig index 5085802f..8b42eb58 100644 --- a/Configurations/ConfigInstallerStatus.xcconfig +++ b/Configurations/ConfigInstallerStatus.xcconfig @@ -4,3 +4,4 @@ INFOPLIST_FILE = InstallerStatus/Info.plist WRAPPER_EXTENSION = xpc PRODUCT_BUNDLE_IDENTIFIER = ${INSTALLER_STATUS_BUNDLE_ID} PRODUCT_NAME = ${INSTALLER_STATUS_NAME} +GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS) BUILDING_SPARKLE=0 BUILDING_SPARKLE_SOURCES_EXTERNALLY=1 diff --git a/Configurations/ConfigRelaunch.xcconfig b/Configurations/ConfigRelaunch.xcconfig index b2de1b6c..aa0de5d5 100644 --- a/Configurations/ConfigRelaunch.xcconfig +++ b/Configurations/ConfigRelaunch.xcconfig @@ -3,3 +3,4 @@ PRODUCT_NAME = $(SPARKLE_RELAUNCH_TOOL_NAME) SKIP_INSTALL = YES CLANG_ENABLE_MODULES = NO +GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS) BUILDING_SPARKLE_SOURCES_EXTERNALLY=1 diff --git a/Configurations/ConfigUnitTest.xcconfig b/Configurations/ConfigUnitTest.xcconfig index aca29e5e..cc48d397 100644 --- a/Configurations/ConfigUnitTest.xcconfig +++ b/Configurations/ConfigUnitTest.xcconfig @@ -11,4 +11,4 @@ FRAMEWORK_SEARCH_PATHS = $(inherited) $(DEVELOPER_FRAMEWORKS_DIR) LD_RUNPATH_SEARCH_PATHS = @loader_path/../Frameworks CLANG_ENABLE_MODULES = YES SWIFT_OBJC_BRIDGING_HEADER = Tests/Sparkle Unit Tests-Bridging-Header.h -GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS) BUILDING_SPARKLE_TESTS=1 +GCC_PREPROCESSOR_DEFINITIONS = $(GCC_PREPROCESSOR_DEFINITIONS) BUILDING_SPARKLE_TESTS=1 BUILDING_SPARKLE_SOURCES_EXTERNALLY=1 diff --git a/Configurations/strip-framework.sh b/Configurations/strip-framework.sh new file mode 100755 index 00000000..c0fd21e5 --- /dev/null +++ b/Configurations/strip-framework.sh @@ -0,0 +1,58 @@ +#!/bin/sh + +FRAMEWORK_PATH="${TARGET_BUILD_DIR}"/"${FULL_PRODUCT_NAME}" + +# Remove any unused XPC Services + +removedservices=0 + +if [[ "$SPARKLE_EMBED_INSTALLER_LAUNCHER_XPC_SERVICE" -eq 0 ]]; then + rm -rf "${FRAMEWORK_PATH}"/"Versions/"${FRAMEWORK_VERSION}"/XPCServices"/"${INSTALLER_LAUNCHER_NAME}.xpc" + removedservices=$((removedservices+1)) +fi + +if [[ "$SPARKLE_EMBED_DOWNLOADER_XPC_SERVICE" -eq 0 ]]; then + rm -rf "${FRAMEWORK_PATH}"/"Versions/"${FRAMEWORK_VERSION}"/XPCServices"/"${DOWNLOADER_NAME}.xpc" + removedservices=$((removedservices+1)) +fi + +if [[ "$SPARKLE_EMBED_INSTALLER_STATUS_XPC_SERVICE" -eq 0 ]]; then + rm -rf "${FRAMEWORK_PATH}"/"Versions/"${FRAMEWORK_VERSION}"/XPCServices"/"${INSTALLER_STATUS_NAME}.xpc" + removedservices=$((removedservices+1)) +fi + +if [[ "$SPARKLE_EMBED_INSTALLER_CONNECTION_XPC_SERVICE" -eq 0 ]]; then + rm -rf "${FRAMEWORK_PATH}"/"Versions/"${FRAMEWORK_VERSION}"/XPCServices"/"${INSTALLER_CONNECTION_NAME}.xpc" + removedservices=$((removedservices+1)) +fi + +if [[ "$removedservices" -eq 4 ]]; then + rm -rf "${FRAMEWORK_PATH}"/"Versions/"${FRAMEWORK_VERSION}"/XPCServices" + rm -rf "${FRAMEWORK_PATH}"/"XPCServices" +fi + +# Remove any unused nibs + +if [[ "$SPARKLE_BUILD_UI_BITS" -eq 0 ]]; then + rm -rf "${FRAMEWORK_PATH}"/"Versions/"${FRAMEWORK_VERSION}"/Resources"/"SUStatus.nib" + rm -rf "${FRAMEWORK_PATH}"/"Versions/"${FRAMEWORK_VERSION}"/Resources"/"Base.lproj/SUUpdateAlert.nib" + rm -rf "${FRAMEWORK_PATH}"/"Versions/"${FRAMEWORK_VERSION}"/Resources"/"Base.lproj/SUUpdatePermissionPrompt.nib" + rm -rf "${FRAMEWORK_PATH}"/"Versions/"${FRAMEWORK_VERSION}"/Resources"/"ReleaseNotesColorStyle.css" +fi + +# Remove localization files if requested + +if [[ "$SPARKLE_COPY_LOCALIZATIONS" -eq 0 ]]; then + for dir in "${FRAMEWORK_PATH}"/"Versions/"${FRAMEWORK_VERSION}"/Resources"/*; do + base=$(basename "$dir") + if [[ "$base" =~ .*".lproj" ]]; then + if [[ "$base" = "Base.lproj" ]]; then + rm -rf "$dir/Sparkle.strings" + # Remove Base.lproj if it's empty and the nibs have been stripped out already + rmdir "$dir" + else + rm -rf "$dir" + fi + fi + done +fi diff --git a/Configurations/strip-xpc-services.sh b/Configurations/strip-xpc-services.sh deleted file mode 100755 index 8463004e..00000000 --- a/Configurations/strip-xpc-services.sh +++ /dev/null @@ -1,30 +0,0 @@ -#!/bin/sh - -FRAMEWORK_PATH="${TARGET_BUILD_DIR}"/"${FULL_PRODUCT_NAME}" - -removedservices=0 - -if [[ "$SPARKLE_EMBED_INSTALLER_LAUNCHER_XPC_SERVICE" -eq 0 ]]; then - rm -rf "${FRAMEWORK_PATH}"/"Versions/"${FRAMEWORK_VERSION}"/XPCServices"/"${INSTALLER_LAUNCHER_NAME}.xpc" - removedservices=$((removedservices+1)) -fi - -if [[ "$SPARKLE_EMBED_DOWNLOADER_XPC_SERVICE" -eq 0 ]]; then - rm -rf "${FRAMEWORK_PATH}"/"Versions/"${FRAMEWORK_VERSION}"/XPCServices"/"${DOWNLOADER_NAME}.xpc" - removedservices=$((removedservices+1)) -fi - -if [[ "$SPARKLE_EMBED_INSTALLER_STATUS_XPC_SERVICE" -eq 0 ]]; then - rm -rf "${FRAMEWORK_PATH}"/"Versions/"${FRAMEWORK_VERSION}"/XPCServices"/"${INSTALLER_STATUS_NAME}.xpc" - removedservices=$((removedservices+1)) -fi - -if [[ "$SPARKLE_EMBED_INSTALLER_CONNECTION_XPC_SERVICE" -eq 0 ]]; then - rm -rf "${FRAMEWORK_PATH}"/"Versions/"${FRAMEWORK_VERSION}"/XPCServices"/"${INSTALLER_CONNECTION_NAME}.xpc" - removedservices=$((removedservices+1)) -fi - -if [[ "$removedservices" -eq 4 ]]; then - rm -rf "${FRAMEWORK_PATH}"/"Versions/"${FRAMEWORK_VERSION}"/XPCServices" - rm -rf "${FRAMEWORK_PATH}"/"XPCServices" -fi diff --git a/Documentation/Design Practices.md b/Documentation/Design Practices.md index b08fec91..7479d623 100644 --- a/Documentation/Design Practices.md +++ b/Documentation/Design Practices.md @@ -36,6 +36,12 @@ Two software components should not directly know about each other. Preferrably t See `Documentation/graph-of-sparkle.png` for a graph of how the code looks like currently. This was generated via [objc_dep](https://github.com/nst/objc_dep) (great tool). Note that there are no red edges which would mean that two nodes know of each other. -## Attributes +## Attributes & Code Size -`nonatomic` should really be used wherever possible with regards to obj-c properties (`atomic` is a bad default). `readonly` should be used wherever possible as well, which also implies that only ivar access should be used in initializers. `NS_ASSUME_NONNULL_BEGIN` and `NS_ASSUME_NONNULL_END` should be used around new headers whenever possible. AppKit prevention guards should be used for any non-UI class whenever possible. \ No newline at end of file +Instance variables and instance variable access should be used for private members (declared in `@implementation` block) whenever possible over properties. Preferring instance variables over properties for internal usage can significantly reduce code size. Instance variables should also be ordered by having the larger sized data members declared first. + +`SPU_OBJC_DIRECT_MEMBERS` should be used for any internal class in Sparkle and `SPU_OBJC_DIRECT` should be used for any other internal methods to Sparkle that doesn't need to utilize the Obj-C runtime to reduce code size. Note these attributes should not be used for *any* class or method that is exported to the developer (this includes private headers / APIs we carefully decided to expose too). For internal methods and classes that are also used by our Swift tools or unit tests, we may not expose them as direct specifically when building for those targets. + +`nonatomic` should really be used wherever possible with regards to obj-c properties (`atomic` is a bad default). `readonly` should be used wherever possible as well, which also implies that only ivar access should be used in initializers. `NS_ASSUME_NONNULL_BEGIN` and `NS_ASSUME_NONNULL_END` should be used around new headers whenever possible. AppKit prevention guards should be used for any non-UI class whenever possible. + +Sparkle has several feature flags in ConfigCommon.xcconfig (e.g. `SPARKLE_BUILD_LEGACY_SUUPDATER`, `SPARKLE_BUILD_LEGACY_DSA_SUPPORT`, `SPARKLE_BUILD_UI_BITS`, etc). This allows disabling any combination of these features and building Sparkle with a more minimal feature set. These flags (with the exception for stripping UI bits, localizations, or XPC Services) are for disabling features that are legacy or not recommended to use for most applications. Note when altering these flags, `OTHER_SWIFT_FLAGS_COMMON` may need to be updated appropriately too. diff --git a/Downloader/SPUDownloader.h b/Downloader/SPUDownloader.h index 6f7434d8..6f5c32f1 100644 --- a/Downloader/SPUDownloader.h +++ b/Downloader/SPUDownloader.h @@ -12,7 +12,7 @@ @protocol SPUDownloaderDelegate; // 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 SPUDownloader : NSObject +SPU_OBJC_DIRECT_MEMBERS @interface SPUDownloader : NSObject // Due to XPC remote object reasons, this delegate is strongly referenced // Invoke cleanup when done with this instance diff --git a/Downloader/SPUDownloader.m b/Downloader/SPUDownloader.m index 35cbe1ca..ee58bd8a 100644 --- a/Downloader/SPUDownloader.m +++ b/Downloader/SPUDownloader.m @@ -25,31 +25,24 @@ typedef NS_ENUM(NSUInteger, SPUDownloadMode) static NSString *SUDownloadingReason = @"Downloading update related file"; @interface SPUDownloader () - -// Delegate is intentionally strongly referenced; see header -@property (nonatomic) id delegate; -@property (nonatomic) NSURLSessionDownloadTask *download; -@property (nonatomic) NSURLSession *downloadSession; -@property (nonatomic, copy) NSString *bundleIdentifier; -@property (nonatomic, copy) NSString *desiredFilename; -@property (nonatomic, copy) NSString *downloadFilename; -@property (nonatomic) BOOL disabledAutomaticTermination; -@property (nonatomic) SPUDownloadMode mode; -@property (nonatomic) BOOL receivedExpectedBytes; - @end @implementation SPUDownloader - -@synthesize delegate = _delegate; -@synthesize download = _download; -@synthesize downloadSession = _downloadSession; -@synthesize bundleIdentifier = _bundleIdentifier; -@synthesize desiredFilename = _desiredFilename; -@synthesize downloadFilename = _downloadFilename; -@synthesize disabledAutomaticTermination = _disabledAutomaticTermination; -@synthesize mode = _mode; -@synthesize receivedExpectedBytes = _receivedExpectedBytes; +{ + NSURLSessionDownloadTask *_download; + NSURLSession *_downloadSession; + NSString *_bundleIdentifier; + NSString *_desiredFilename; + NSString *_downloadFilename; + + // Delegate is intentionally strongly referenced; see header + id _delegate; + + SPUDownloadMode _mode; + + BOOL _disabledAutomaticTermination; + BOOL _receivedExpectedBytes; +} - (instancetype)initWithDelegate:(id )delegate { @@ -60,14 +53,14 @@ static NSString *SUDownloadingReason = @"Downloading update related file"; return self; } -- (void)startDownloadWithRequest:(NSURLRequest *)request +- (void)startDownloadWithRequest:(NSURLRequest *)request SPU_OBJC_DIRECT { - self.downloadSession = [NSURLSession + _downloadSession = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]]; - self.download = [self.downloadSession downloadTaskWithRequest:request]; - [self.download resume]; + _download = [_downloadSession downloadTaskWithRequest:request]; + [_download resume]; } // Don't implement dealloc - make the client call cleanup, which is the only way to remove the reference cycle from the delegate anyway @@ -75,14 +68,14 @@ static NSString *SUDownloadingReason = @"Downloading update related file"; - (void)startPersistentDownloadWithRequest:(NSURLRequest *)request bundleIdentifier:(NSString *)bundleIdentifier desiredFilename:(NSString *)desiredFilename { dispatch_async(dispatch_get_main_queue(), ^{ - if (self.download == nil && self.delegate != nil) { + if (self->_download == nil && self->_delegate != nil) { // Prevent service from automatically terminating while downloading the update asynchronously without any reply blocks [[NSProcessInfo processInfo] disableAutomaticTermination:SUDownloadingReason]; - self.disabledAutomaticTermination = YES; + self->_disabledAutomaticTermination = YES; - self.mode = SPUDownloadModePersistent; - self.desiredFilename = desiredFilename; - self.bundleIdentifier = bundleIdentifier; + self->_mode = SPUDownloadModePersistent; + self->_desiredFilename = desiredFilename; + self->_bundleIdentifier = [bundleIdentifier copy]; [self startDownloadWithRequest:request]; } @@ -92,26 +85,26 @@ static NSString *SUDownloadingReason = @"Downloading update related file"; - (void)startTemporaryDownloadWithRequest:(NSURLRequest *)request { dispatch_async(dispatch_get_main_queue(), ^{ - if (self.download == nil && self.delegate != nil) { + if (self->_download == nil && self->_delegate != nil) { // Prevent service from automatically terminating while downloading the update asynchronously without any reply blocks [[NSProcessInfo processInfo] disableAutomaticTermination:SUDownloadingReason]; - self.disabledAutomaticTermination = YES; + self->_disabledAutomaticTermination = YES; - self.mode = SPUDownloadModeTemporary; + self->_mode = SPUDownloadModeTemporary; [self startDownloadWithRequest:request]; } }); } -- (void)enableAutomaticTermination +- (void)enableAutomaticTermination SPU_OBJC_DIRECT { - if (self.disabledAutomaticTermination) { + if (_disabledAutomaticTermination) { [[NSProcessInfo processInfo] enableAutomaticTermination:SUDownloadingReason]; - self.disabledAutomaticTermination = NO; + _disabledAutomaticTermination = NO; } } -- (NSString *)rootPersistentDownloadCachePathForBundleIdentifier:(NSString *)bundleIdentifier +- (NSString *)rootPersistentDownloadCachePathForBundleIdentifier:(NSString *)bundleIdentifier SPU_OBJC_DIRECT { return [[SPULocalCacheDirectory cachePathForBundleIdentifier:bundleIdentifier] stringByAppendingPathComponent:@"PersistentDownloads"]; } @@ -133,19 +126,19 @@ static NSString *SUDownloadingReason = @"Downloading update related file"; }); } -- (void)_cleanup +- (void)_cleanup SPU_OBJC_DIRECT { [self enableAutomaticTermination]; - [self.download cancel]; - [self.downloadSession finishTasksAndInvalidate]; - self.download = nil; - self.downloadSession = nil; - self.delegate = nil; + [_download cancel]; + [_downloadSession finishTasksAndInvalidate]; + _download = nil; + _downloadSession = nil; + _delegate = nil; - if (self.mode == SPUDownloadModeTemporary && self.downloadFilename != nil) + if (_mode == SPUDownloadModeTemporary && _downloadFilename != nil) { - [[NSFileManager defaultManager] removeItemAtPath:self.downloadFilename error:NULL]; - self.downloadFilename = nil; + [[NSFileManager defaultManager] removeItemAtPath:_downloadFilename error:NULL]; + _downloadFilename = nil; } } @@ -165,17 +158,17 @@ static NSString *SUDownloadingReason = @"Downloading update related file"; { NSString *message = [NSString stringWithFormat:@"A network error occurred while downloading %@. %@ (%ld)", downloadTask.originalRequest.URL.absoluteString, [NSHTTPURLResponse localizedStringForStatusCode:statusCode], (long)statusCode]; NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUDownloadError userInfo:@{ NSLocalizedDescriptionKey: message }]; - [self.delegate downloaderDidFailWithError:error]; + [_delegate downloaderDidFailWithError:error]; } - else if (self.mode == SPUDownloadModeTemporary) + else if (_mode == SPUDownloadModeTemporary) { - self.downloadFilename = location.path; + _downloadFilename = location.path; [self downloadDidFinish]; // file is already in a system temp dir } else { // Remove our old caches path so we don't start accumulating files in there - NSString *rootPersistentDownloadCachePath = [self rootPersistentDownloadCachePathForBundleIdentifier:self.bundleIdentifier]; + NSString *rootPersistentDownloadCachePath = [self rootPersistentDownloadCachePathForBundleIdentifier:_bundleIdentifier]; [SPULocalCacheDirectory removeOldItemsInDirectory:rootPersistentDownloadCachePath]; @@ -183,23 +176,23 @@ static NSString *SUDownloadingReason = @"Downloading update related file"; if (tempDir == nil) { // Okay, something's really broken with this user's file structure. - [self.download cancel]; - self.download = nil; + [_download cancel]; + _download = nil; NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUTemporaryDirectoryError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Can't make a temporary directory for the update download at %@.", tempDir] }]; - [self.delegate downloaderDidFailWithError:error]; + [_delegate downloaderDidFailWithError:error]; } else { - NSString *downloadFileName = self.desiredFilename; + NSString *downloadFileName = _desiredFilename; NSString *downloadFileNameDirectory = [tempDir stringByAppendingPathComponent:downloadFileName]; NSError *createError = nil; if (![[NSFileManager defaultManager] createDirectoryAtPath:downloadFileNameDirectory withIntermediateDirectories:NO attributes:nil error:&createError]) { NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUTemporaryDirectoryError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Can't make a download file name %@ directory inside temporary directory for the update download at %@.", downloadFileName, downloadFileNameDirectory] }]; - [self.delegate downloaderDidFailWithError:error]; + [_delegate downloaderDidFailWithError:error]; } else { - NSString *name = self.download.response.suggestedFilename; + NSString *name = _download.response.suggestedFilename; if (!name) { name = location.lastPathComponent; // This likely contains nothing useful to identify the file (e.g. CFNetworkDownload_87LVIz.tmp) } @@ -207,11 +200,11 @@ static NSString *SUDownloadingReason = @"Downloading update related file"; NSString *fromPath = location.path; // suppress moveItemAtPath: non-null warning NSError *error = nil; if ([[NSFileManager defaultManager] moveItemAtPath:fromPath toPath:toPath error:&error]) { - self.downloadFilename = toPath; - [self.delegate downloaderDidSetDestinationName:name temporaryDirectory:downloadFileNameDirectory]; + _downloadFilename = toPath; + [_delegate downloaderDidSetDestinationName:name temporaryDirectory:downloadFileNameDirectory]; [self downloadDidFinish]; } else { - [self.delegate downloaderDidFailWithError:error]; + [_delegate downloaderDidFailWithError:error]; } } } @@ -221,33 +214,33 @@ static NSString *SUDownloadingReason = @"Downloading update related file"; - (void)URLSession:(NSURLSession *)__unused session downloadTask:(NSURLSessionDownloadTask *)__unused downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)__unused totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite { - if (self.mode == SPUDownloadModePersistent && totalBytesExpectedToWrite > 0 && !self.receivedExpectedBytes) { - self.receivedExpectedBytes = YES; - [self.delegate downloaderDidReceiveExpectedContentLength:totalBytesExpectedToWrite]; + if (_mode == SPUDownloadModePersistent && totalBytesExpectedToWrite > 0 && !_receivedExpectedBytes) { + _receivedExpectedBytes = YES; + [_delegate downloaderDidReceiveExpectedContentLength:totalBytesExpectedToWrite]; } - if (self.mode == SPUDownloadModePersistent && bytesWritten >= 0) { - [self.delegate downloaderDidReceiveDataOfLength:(uint64_t)bytesWritten]; + if (_mode == SPUDownloadModePersistent && bytesWritten >= 0) { + [_delegate downloaderDidReceiveDataOfLength:(uint64_t)bytesWritten]; } } -- (void)downloadDidFinish +- (void)downloadDidFinish SPU_OBJC_DIRECT { - assert(self.downloadFilename != nil); + assert(_downloadFilename != nil); SPUDownloadData *downloadData = nil; - if (self.mode == SPUDownloadModeTemporary) { - NSData *data = [NSData dataWithContentsOfFile:self.downloadFilename]; + if (_mode == SPUDownloadModeTemporary) { + NSData *data = [NSData dataWithContentsOfFile:_downloadFilename]; if (data != nil) { - NSURLResponse *response = self.download.response; + NSURLResponse *response = _download.response; assert(response != nil); NSURL *responseURL = response.URL; if (responseURL == nil) { - responseURL = self.download.currentRequest.URL; + responseURL = _download.currentRequest.URL; } if (responseURL == nil) { - responseURL = self.download.originalRequest.URL; + responseURL = _download.originalRequest.URL; } assert(responseURL != nil); @@ -255,29 +248,29 @@ static NSString *SUDownloadingReason = @"Downloading update related file"; } } - self.download = nil; + _download = nil; - switch (self.mode) { + switch (_mode) { case SPUDownloadModeTemporary: if (downloadData != nil) { - [self.delegate downloaderDidFinishWithTemporaryDownloadData:downloadData]; + [_delegate downloaderDidFinishWithTemporaryDownloadData:downloadData]; } else { - [self.delegate downloaderDidFailWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUDownloadError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to read temporary downloaded data from %@", self.downloadFilename]}]]; + [_delegate downloaderDidFailWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUDownloadError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to read temporary downloaded data from %@", _downloadFilename]}]]; } [self _cleanup]; break; case SPUDownloadModePersistent: - [self.delegate downloaderDidFinishWithTemporaryDownloadData:nil]; + [_delegate downloaderDidFinishWithTemporaryDownloadData:nil]; break; } } - (void)URLSession:(NSURLSession *)__unused session task:(NSURLSessionTask *)__unused task didCompleteWithError:(NSError *)error { - self.download = nil; + _download = nil; if (error != nil) { - [self.delegate downloaderDidFailWithError:error]; + [_delegate downloaderDidFailWithError:error]; } } diff --git a/InstallerConnection/SUInstallerConnection.h b/InstallerConnection/SUInstallerConnection.h index 2134c177..6b445e8b 100644 --- a/InstallerConnection/SUInstallerConnection.h +++ b/InstallerConnection/SUInstallerConnection.h @@ -12,7 +12,7 @@ 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 +SPU_OBJC_DIRECT_MEMBERS @interface SUInstallerConnection : NSObject // Due to XPC reasons, this delegate is strongly referenced, until it's invalidated - (instancetype)initWithDelegate:(id)delegate remote:(BOOL)remote; diff --git a/InstallerConnection/SUInstallerConnection.m b/InstallerConnection/SUInstallerConnection.m index 857fc4e4..52722a46 100644 --- a/InstallerConnection/SUInstallerConnection.m +++ b/InstallerConnection/SUInstallerConnection.m @@ -14,26 +14,20 @@ static NSString *SUInstallerConnectionKeepAliveReason = @"Installer Connection Keep Alive"; @interface SUInstallerConnection () - -// Intentionally not weak for XPC reasons -@property (nonatomic) id delegate; - -@property (nonatomic) BOOL disabledAutomaticTermination; -@property (nonatomic, copy) void (^invalidationBlock)(void); -@property (nonatomic) NSXPCConnection *connection; - @end @implementation SUInstallerConnection { + NSXPCConnection *_connection; + // Intentionally not weak for XPC reasons + id _delegate; + + void (^_invalidationBlock)(void); + + BOOL _disabledAutomaticTermination; BOOL _remote; } -@synthesize delegate = _delegate; -@synthesize disabledAutomaticTermination = _disabledAutomaticTermination; -@synthesize invalidationBlock = _invalidationBlock; -@synthesize connection = _connection; - - (instancetype)initWithDelegate:(id)delegate remote:(BOOL)remote { self = [super init]; @@ -50,17 +44,17 @@ static NSString *SUInstallerConnectionKeepAliveReason = @"Installer Connection K return self; } -- (void)enableAutomaticTermination +- (void)enableAutomaticTermination SPU_OBJC_DIRECT { - if (self.disabledAutomaticTermination) { + if (_disabledAutomaticTermination) { [[NSProcessInfo processInfo] enableAutomaticTermination:SUInstallerConnectionKeepAliveReason]; - self.disabledAutomaticTermination = NO; + _disabledAutomaticTermination = NO; } } -- (void)_setInvalidationHandler:(void (^)(void))invalidationHandler +- (void)_setInvalidationHandler:(void (^)(void))invalidationHandler SPU_OBJC_DIRECT { - self.invalidationBlock = invalidationHandler; + _invalidationBlock = [invalidationHandler copy]; // No longer needed because of invalidation callback [self enableAutomaticTermination]; @@ -77,36 +71,39 @@ static NSString *SUInstallerConnectionKeepAliveReason = @"Installer Connection K } } -- (void)_setServiceName:(NSString *)serviceName systemDomain:(BOOL)systemDomain +- (void)_setServiceName:(NSString *)serviceName systemDomain:(BOOL)systemDomain SPU_OBJC_DIRECT { NSXPCConnectionOptions options = systemDomain ? NSXPCConnectionPrivileged : 0; NSXPCConnection *connection = [[NSXPCConnection alloc] initWithMachServiceName:serviceName options:options]; connection.exportedInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUInstallerCommunicationProtocol)]; - connection.exportedObject = self.delegate; + connection.exportedObject = _delegate; connection.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUInstallerCommunicationProtocol)]; - self.connection = connection; + _connection = connection; - __weak SUInstallerConnection *weakSelf = self; - self.connection.interruptionHandler = ^{ + __weak __typeof__(self) weakSelf = self; + _connection.interruptionHandler = ^{ dispatch_async(dispatch_get_main_queue(), ^{ - [weakSelf.connection invalidate]; + __typeof__(self) strongSelf = weakSelf; + if (strongSelf != nil) { + [strongSelf->_connection invalidate]; + } }); }; - self.connection.invalidationHandler = ^{ + _connection.invalidationHandler = ^{ dispatch_async(dispatch_get_main_queue(), ^{ - SUInstallerConnection *strongSelf = weakSelf; + __typeof__(self) strongSelf = weakSelf; if (strongSelf != nil) { - strongSelf.connection = nil; + strongSelf->_connection = nil; [strongSelf _invalidate]; } }); }; - [self.connection resume]; + [_connection resume]; } - (void)setServiceName:(NSString *)serviceName systemDomain:(BOOL)systemDomain @@ -124,22 +121,22 @@ static NSString *SUInstallerConnectionKeepAliveReason = @"Installer Connection K { if (_remote) { dispatch_async(dispatch_get_main_queue(), ^{ - [(id)self.connection.remoteObjectProxy handleMessageWithIdentifier:identifier data:data]; + [(id)self->_connection.remoteObjectProxy handleMessageWithIdentifier:identifier data:data]; }); } else { - [(id)self.connection.remoteObjectProxy handleMessageWithIdentifier:identifier data:data]; + [(id)_connection.remoteObjectProxy handleMessageWithIdentifier:identifier data:data]; } } -- (void)_invalidate +- (void)_invalidate SPU_OBJC_DIRECT { - if (self.invalidationBlock != nil) { - self.invalidationBlock(); - self.invalidationBlock = nil; + if (_invalidationBlock != nil) { + _invalidationBlock(); + _invalidationBlock = nil; } // Break the retain cycle - self.delegate = nil; + _delegate = nil; [self enableAutomaticTermination]; } @@ -148,8 +145,8 @@ static NSString *SUInstallerConnectionKeepAliveReason = @"Installer Connection K - (void)invalidate { dispatch_async(dispatch_get_main_queue(), ^{ - [self.connection invalidate]; - self.connection = nil; + [self->_connection invalidate]; + self->_connection = nil; [self _invalidate]; }); diff --git a/InstallerConnection/SUXPCInstallerConnection.h b/InstallerConnection/SUXPCInstallerConnection.h index da201369..cbc9828b 100644 --- a/InstallerConnection/SUXPCInstallerConnection.h +++ b/InstallerConnection/SUXPCInstallerConnection.h @@ -6,12 +6,14 @@ // Copyright © 2016 Sparkle Project. All rights reserved. // +#if INSTALLER_CONNECTION_XPC_SERVICE_EMBEDDED + #import #import "SUInstallerConnectionProtocol.h" NS_ASSUME_NONNULL_BEGIN -@interface SUXPCInstallerConnection : NSObject +SPU_OBJC_DIRECT_MEMBERS @interface SUXPCInstallerConnection : NSObject // Due to XPC reasons, this delegate is strongly referenced, until it's invalidated - (instancetype)initWithDelegate:(id)delegate; @@ -19,3 +21,5 @@ NS_ASSUME_NONNULL_BEGIN @end NS_ASSUME_NONNULL_END + +#endif diff --git a/InstallerConnection/SUXPCInstallerConnection.m b/InstallerConnection/SUXPCInstallerConnection.m index d077f190..53f09db9 100644 --- a/InstallerConnection/SUXPCInstallerConnection.m +++ b/InstallerConnection/SUXPCInstallerConnection.m @@ -6,24 +6,21 @@ // Copyright © 2016 Sparkle Project. All rights reserved. // +#if INSTALLER_CONNECTION_XPC_SERVICE_EMBEDDED + #import "SUXPCInstallerConnection.h" #include "AppKitPrevention.h" -@interface SUXPCInstallerConnection () - -@property (nonatomic) NSXPCConnection *connection; -@property (nonatomic) id 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; +{ + NSXPCConnection *_connection; + // Intentionally not weak for XPC reasons + id _delegate; + + void (^_invalidationBlock)(void); +} - (instancetype)initWithDelegate:(id)delegate { @@ -32,14 +29,17 @@ _connection = [[NSXPCConnection alloc] initWithServiceName:@INSTALLER_CONNECTION_BUNDLE_ID]; _connection.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUInstallerConnectionProtocol)]; - __weak SUXPCInstallerConnection *weakSelf = self; + __weak __typeof__(self) weakSelf = self; _connection.invalidationHandler = ^{ [weakSelf invokeInvalidation]; }; _connection.interruptionHandler = ^{ - [weakSelf invokeInvalidation]; - [weakSelf.connection invalidate]; + __typeof__(self) strongSelf = weakSelf; + if (strongSelf != nil) { + [strongSelf invokeInvalidation]; + [strongSelf->_connection invalidate]; + } }; _delegate = delegate; @@ -54,39 +54,41 @@ - (void)setInvalidationHandler:(void (^)(void))invalidationHandler { - self.invalidationBlock = invalidationHandler; + _invalidationBlock = [invalidationHandler copy]; - __weak SUXPCInstallerConnection *weakSelf = self; - [(id)self.connection.remoteObjectProxy setInvalidationHandler:^{ + __weak __typeof__(self) weakSelf = self; + [(id)_connection.remoteObjectProxy setInvalidationHandler:^{ [weakSelf invokeInvalidation]; }]; } - (void)setServiceName:(NSString *)serviceName systemDomain:(BOOL)systemDomain { - [(id)self.connection.remoteObjectProxy setServiceName:serviceName systemDomain:systemDomain]; + [(id)_connection.remoteObjectProxy setServiceName:serviceName systemDomain:systemDomain]; } - (void)handleMessageWithIdentifier:(int32_t)identifier data:(NSData *)data { - [(id)self.connection.remoteObjectProxy handleMessageWithIdentifier:identifier data:data]; + [(id)_connection.remoteObjectProxy handleMessageWithIdentifier:identifier data:data]; } - (void)invalidate { - [(id)self.connection.remoteObjectProxy invalidate]; - [self.connection invalidate]; - self.connection = nil; + [(id)_connection.remoteObjectProxy invalidate]; + [_connection invalidate]; + _connection = nil; } -- (void)invokeInvalidation +- (void)invokeInvalidation SPU_OBJC_DIRECT { - if (self.invalidationBlock != nil) { - self.invalidationBlock(); - self.invalidationBlock = nil; + if (_invalidationBlock != nil) { + _invalidationBlock(); + _invalidationBlock = nil; } // Break our retain cycle - self.delegate = nil; + _delegate = nil; } @end + +#endif diff --git a/InstallerLauncher/SUInstallerLauncher+Private.h b/InstallerLauncher/SUInstallerLauncher+Private.h index f8e0410c..8922e181 100644 --- a/InstallerLauncher/SUInstallerLauncher+Private.h +++ b/InstallerLauncher/SUInstallerLauncher+Private.h @@ -9,10 +9,18 @@ #ifndef SUInstallerLauncher_Private_h #define SUInstallerLauncher_Private_h +#if defined(BUILDING_SPARKLE_SOURCES_EXTERNALLY) +// Ignore incorrect warning +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wquoted-include-in-framework-header" +#import "SUExport.h" +#import "SPUInstallationType.h" +#pragma clang diagnostic pop +#else #import - // Chances are clients will need this too #import +#endif @class NSString; diff --git a/InstallerLauncher/SUInstallerLauncher.m b/InstallerLauncher/SUInstallerLauncher.m index afe3a4bf..864c2b31 100644 --- a/InstallerLauncher/SUInstallerLauncher.m +++ b/InstallerLauncher/SUInstallerLauncher.m @@ -25,7 +25,7 @@ @implementation SUInstallerLauncher -- (BOOL)submitProgressToolAtPath:(NSString *)progressToolPath withHostBundle:(NSBundle *)hostBundle inSystemDomainForInstaller:(BOOL)inSystemDomainForInstaller +- (BOOL)submitProgressToolAtPath:(NSString *)progressToolPath withHostBundle:(NSBundle *)hostBundle inSystemDomainForInstaller:(BOOL)inSystemDomainForInstaller SPU_OBJC_DIRECT { SUFileManager *fileManager = [[SUFileManager alloc] init]; @@ -106,7 +106,7 @@ return (submittedJob == true); } -- (SUInstallerLauncherStatus)submitInstallerAtPath:(NSString *)installerPath withHostBundle:(NSBundle *)hostBundle updaterIdentifier:(NSString *)updaterIdentifier userName:(NSString *)userName homeDirectory:(NSString *)homeDirectory authorizationPrompt:(NSString *)authorizationPrompt inSystemDomain:(BOOL)systemDomain rootUser:(BOOL)rootUser +- (SUInstallerLauncherStatus)submitInstallerAtPath:(NSString *)installerPath withHostBundle:(NSBundle *)hostBundle updaterIdentifier:(NSString *)updaterIdentifier userName:(NSString *)userName homeDirectory:(NSString *)homeDirectory authorizationPrompt:(NSString *)authorizationPrompt inSystemDomain:(BOOL)systemDomain rootUser:(BOOL)rootUser SPU_OBJC_DIRECT { SUFileManager *fileManager = [[SUFileManager alloc] init]; @@ -208,15 +208,19 @@ tempIconDestinationURL = [NSURL fileURLWithPath:path]; CGImageDestinationRef imageDestination = NULL; - if (@available(macOS 11, *)) { +#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_VERSION_11_0 + if (@available(macOS 11, *)) +#endif + { CFStringRef uti = (__bridge CFStringRef)[UTTypePNG identifier]; imageDestination = CGImageDestinationCreateWithURL((CFURLRef)tempIconDestinationURL, uti, 1, NULL); - } else { -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdeprecated-declarations" - imageDestination = CGImageDestinationCreateWithURL((CFURLRef)tempIconDestinationURL, kUTTypePNG, 1, NULL); -#pragma clang diagnostic pop } +#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_VERSION_11_0 + else + { + imageDestination = CGImageDestinationCreateWithURL((CFURLRef)tempIconDestinationURL, kUTTypePNG, 1, NULL); + } +#endif if (imageDestination != NULL) { CGImageDestinationAddImageFromSource(imageDestination, imageSource, imageIndex, (CFDictionaryRef)@{}); if (CGImageDestinationFinalize(imageDestination)) { @@ -310,7 +314,7 @@ return status; } -- (NSString *)pathForBundledTool:(NSString *)toolName extension:(NSString *)extension fromBundle:(NSBundle *)bundle +- (NSString *)pathForBundledTool:(NSString *)toolName extension:(NSString *)extension fromBundle:(NSBundle *)bundle SPU_OBJC_DIRECT { // If the path extension is empty, we don't want to add a "." at the end NSString *nameWithExtension = (extension.length > 0) ? [toolName stringByAppendingPathExtension:extension] : toolName; @@ -370,14 +374,21 @@ BOOL SPUSystemNeedsAuthorizationAccessForBundlePath(NSString *bundlePath) return needsAuthorization; } -static BOOL SPUUsesSystemDomainForBundlePath(NSString *path, NSString *installationType, BOOL rootUser) +static BOOL SPUUsesSystemDomainForBundlePath(NSString *path, BOOL rootUser +#if SPARKLE_BUILD_PACKAGE_SUPPORT + , NSString *installationType +#endif +) { if (!rootUser) { +#if SPARKLE_BUILD_PACKAGE_SUPPORT if ([installationType isEqualToString:SPUInstallationTypeGuidedPackage]) { return YES; } else if ([installationType isEqualToString:SPUInstallationTypeInteractivePackage]) { return NO; - } else { + } else +#endif + { return SPUSystemNeedsAuthorizationAccessForBundlePath(path); } } else { @@ -396,7 +407,11 @@ static BOOL SPUUsesSystemDomainForBundlePath(NSString *path, NSString *installat // and that is not necessarily related to a preflight test. It's more related to being ran under a root / different user from the active GUI session BOOL rootUser = (geteuid() == 0); - BOOL inSystemDomain = SPUUsesSystemDomainForBundlePath(hostBundlePath, installationType, rootUser); + BOOL inSystemDomain = SPUUsesSystemDomainForBundlePath(hostBundlePath, rootUser +#if SPARKLE_BUILD_PACKAGE_SUPPORT + , installationType +#endif + ); NSBundle *hostBundle = [NSBundle bundleWithPath:hostBundlePath]; if (hostBundle == nil) { diff --git a/InstallerStatus/SUInstallerStatus.h b/InstallerStatus/SUInstallerStatus.h index 04f7aa8c..fec4c9fc 100644 --- a/InstallerStatus/SUInstallerStatus.h +++ b/InstallerStatus/SUInstallerStatus.h @@ -10,7 +10,7 @@ #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 +SPU_OBJC_DIRECT_MEMBERS @interface SUInstallerStatus : NSObject - (instancetype)initWithRemote:(BOOL)remote; diff --git a/InstallerStatus/SUInstallerStatus.m b/InstallerStatus/SUInstallerStatus.m index f12c56be..1f92c536 100644 --- a/InstallerStatus/SUInstallerStatus.m +++ b/InstallerStatus/SUInstallerStatus.m @@ -11,21 +11,15 @@ #include "AppKitPrevention.h" -@interface SUInstallerStatus () - -@property (nonatomic, copy) void (^invalidationBlock)(void); -@property (nonatomic) NSXPCConnection *connection; - -@end - @implementation SUInstallerStatus { + NSXPCConnection *_connection; + + void (^_invalidationBlock)(void); + BOOL _remote; } -@synthesize invalidationBlock = _invalidationBlock; -@synthesize connection = _connection; - - (instancetype)initWithRemote:(BOOL)remote { self = [super init]; @@ -39,39 +33,42 @@ { if (_remote) { dispatch_async(dispatch_get_main_queue(), ^{ - self.invalidationBlock = invalidationHandler; + self->_invalidationBlock = [invalidationHandler copy]; }); } else { - self.invalidationBlock = invalidationHandler; + _invalidationBlock = [invalidationHandler copy]; } } -- (void)_setServiceName:(NSString *)serviceName +- (void)_setServiceName:(NSString *)serviceName SPU_OBJC_DIRECT { NSXPCConnection *connection = [[NSXPCConnection alloc] initWithMachServiceName:serviceName options:(NSXPCConnectionOptions)0]; connection.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUStatusInfoProtocol)]; - self.connection = connection; + _connection = connection; - __weak SUInstallerStatus *weakSelf = self; - self.connection.interruptionHandler = ^{ + __weak __typeof__(self) weakSelf = self; + _connection.interruptionHandler = ^{ dispatch_async(dispatch_get_main_queue(), ^{ - [weakSelf.connection invalidate]; + __typeof__(self) strongSelf = weakSelf; + if (strongSelf != nil) { + [strongSelf->_connection invalidate]; + } }); }; - self.connection.invalidationHandler = ^{ + _connection.invalidationHandler = ^{ dispatch_async(dispatch_get_main_queue(), ^{ - SUInstallerStatus *strongSelf = weakSelf; + __typeof__(self) strongSelf = weakSelf; if (strongSelf != nil) { - strongSelf.connection = nil; + strongSelf->_connection = nil; [strongSelf _invokeInvalidationBlock]; } }); }; - [self.connection resume]; + [_connection resume]; } - (void)setServiceName:(NSString *)serviceName @@ -89,10 +86,10 @@ { if (_remote) { dispatch_async(dispatch_get_main_queue(), ^{ - [(id)self.connection.remoteObjectProxy probeStatusInfoWithReply:reply]; + [(id)self->_connection.remoteObjectProxy probeStatusInfoWithReply:reply]; }); } else { - [(id)self.connection.remoteObjectProxy probeStatusInfoWithReply:reply]; + [(id)_connection.remoteObjectProxy probeStatusInfoWithReply:reply]; } } @@ -100,18 +97,18 @@ { if (_remote) { dispatch_async(dispatch_get_main_queue(), ^{ - [(id)self.connection.remoteObjectProxy probeStatusConnectivityWithReply:reply]; + [(id)self->_connection.remoteObjectProxy probeStatusConnectivityWithReply:reply]; }); } else { - [(id)self.connection.remoteObjectProxy probeStatusConnectivityWithReply:reply]; + [(id)_connection.remoteObjectProxy probeStatusConnectivityWithReply:reply]; } } -- (void)_invokeInvalidationBlock +- (void)_invokeInvalidationBlock SPU_OBJC_DIRECT { - if (self.invalidationBlock != nil) { - self.invalidationBlock(); - self.invalidationBlock = nil; + if (_invalidationBlock != nil) { + _invalidationBlock(); + _invalidationBlock = nil; } } @@ -119,8 +116,8 @@ - (void)invalidate { dispatch_async(dispatch_get_main_queue(), ^{ - [self.connection invalidate]; - self.connection = nil; + [self->_connection invalidate]; + self->_connection = nil; [self _invokeInvalidationBlock]; }); diff --git a/InstallerStatus/SUXPCInstallerStatus.h b/InstallerStatus/SUXPCInstallerStatus.h index f48839fa..cb13de0e 100644 --- a/InstallerStatus/SUXPCInstallerStatus.h +++ b/InstallerStatus/SUXPCInstallerStatus.h @@ -6,9 +6,13 @@ // Copyright © 2016 Sparkle Project. All rights reserved. // +#if INSTALLER_STATUS_XPC_SERVICE_EMBEDDED + #import #import "SUInstallerStatusProtocol.h" @interface SUXPCInstallerStatus : NSObject @end + +#endif diff --git a/InstallerStatus/SUXPCInstallerStatus.m b/InstallerStatus/SUXPCInstallerStatus.m index 0c282d58..1f822acb 100644 --- a/InstallerStatus/SUXPCInstallerStatus.m +++ b/InstallerStatus/SUXPCInstallerStatus.m @@ -6,22 +6,19 @@ // Copyright © 2016 Sparkle Project. All rights reserved. // +#if INSTALLER_STATUS_XPC_SERVICE_EMBEDDED + #import "SUXPCInstallerStatus.h" #include "AppKitPrevention.h" -@interface SUXPCInstallerStatus () - -@property (nonatomic) NSXPCConnection *connection; -@property (nonatomic, copy) void (^invalidationBlock)(void); - -@end - @implementation SUXPCInstallerStatus - -@synthesize connection = _connection; -@synthesize invalidationBlock = _invalidationBlock; +{ + NSXPCConnection *_connection; + + void (^_invalidationBlock)(void); +} - (instancetype)init { @@ -30,14 +27,17 @@ _connection = [[NSXPCConnection alloc] initWithServiceName:@INSTALLER_STATUS_BUNDLE_ID]; _connection.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUInstallerStatusProtocol)]; - __weak SUXPCInstallerStatus *weakSelf = self; + __weak __typeof__(self) weakSelf = self; _connection.invalidationHandler = ^{ [weakSelf invokeInvalidation]; }; _connection.interruptionHandler = ^{ - [weakSelf invokeInvalidation]; - [weakSelf.connection invalidate]; + __typeof__(self) strongSelf = weakSelf; + if (strongSelf != nil) { + [strongSelf invokeInvalidation]; + [strongSelf->_connection invalidate]; + } }; [_connection resume]; @@ -47,42 +47,44 @@ - (void)setInvalidationHandler:(void (^)(void))invalidationHandler { - self.invalidationBlock = invalidationHandler; + _invalidationBlock = [invalidationHandler copy]; - __weak SUXPCInstallerStatus *weakSelf = self; - [(id)self.connection.remoteObjectProxy setInvalidationHandler:^{ + __weak __typeof__(self) weakSelf = self; + [(id)_connection.remoteObjectProxy setInvalidationHandler:^{ [weakSelf invokeInvalidation]; }]; } - (void)setServiceName:(NSString *)serviceName { - [(id)self.connection.remoteObjectProxy setServiceName:serviceName]; + [(id)_connection.remoteObjectProxy setServiceName:serviceName]; } - (void)probeStatusInfoWithReply:(void (^)(NSData * _Nullable installationInfoData))reply { - [(id)self.connection.remoteObjectProxy probeStatusInfoWithReply:reply]; + [(id)_connection.remoteObjectProxy probeStatusInfoWithReply:reply]; } - (void)probeStatusConnectivityWithReply:(void (^)(void))reply { - [(id)self.connection.remoteObjectProxy probeStatusConnectivityWithReply:reply]; + [(id)_connection.remoteObjectProxy probeStatusConnectivityWithReply:reply]; } - (void)invalidate { - [(id)self.connection.remoteObjectProxy invalidate]; - [self.connection invalidate]; - self.connection = nil; + [(id)_connection.remoteObjectProxy invalidate]; + [_connection invalidate]; + _connection = nil; } - (void)invokeInvalidation { - if (self.invalidationBlock != nil) { - self.invalidationBlock(); - self.invalidationBlock = nil; + if (_invalidationBlock != nil) { + _invalidationBlock(); + _invalidationBlock = nil; } } @end + +#endif diff --git a/Sparkle.xcodeproj/project.pbxproj b/Sparkle.xcodeproj/project.pbxproj index ea92932f..521083e5 100644 --- a/Sparkle.xcodeproj/project.pbxproj +++ b/Sparkle.xcodeproj/project.pbxproj @@ -165,6 +165,12 @@ 721D8A861D4ADFEB0032E472 /* SPULocalCacheDirectory.m in Sources */ = {isa = PBXBuildFile; fileRef = 721BC20D1D1CDE55002BC71E /* SPULocalCacheDirectory.m */; }; 721D8A871D4C5BF10032E472 /* SULog.m in Sources */ = {isa = PBXBuildFile; fileRef = 55C14F05136EF6DB00649790 /* SULog.m */; }; 722545B626805FF80036465C /* testappcast_info_updates.xml in Resources */ = {isa = PBXBuildFile; fileRef = 722545B526805FF80036465C /* testappcast_info_updates.xml */; }; + 72266A872946359600645376 /* SUFileManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 7267E5E41D3D90AA00D1BF90 /* SUFileManager.m */; }; + 72266A88294635BA00645376 /* SUAppcastDriver.m in Sources */ = {isa = PBXBuildFile; fileRef = 72B767C91C9B707000A07552 /* SUAppcastDriver.m */; }; + 72266A89294636FB00645376 /* SUStandardVersionComparator.m in Sources */ = {isa = PBXBuildFile; fileRef = 61A225A30D1C4AC000430CCD /* SUStandardVersionComparator.m */; }; + 72266A8A2946493C00645376 /* SUCodeSigningVerifier.m in Sources */ = {isa = PBXBuildFile; fileRef = 7267E5991D3D8A5A00D1BF90 /* SUCodeSigningVerifier.m */; }; + 72266A8B29464CEA00645376 /* SUHost.m in Sources */ = {isa = PBXBuildFile; fileRef = 61EF67550E25B58D00F754E0 /* SUHost.m */; }; + 72266A8C29464D0200645376 /* SUSignatures.m in Sources */ = {isa = PBXBuildFile; fileRef = EA1E286D22B665E8004AA304 /* SUSignatures.m */; }; 7229E1B61C97C91100CB50D0 /* SPUUpdateDriver.h in Headers */ = {isa = PBXBuildFile; fileRef = 7229E1B51C97C91100CB50D0 /* SPUUpdateDriver.h */; }; 7229E1B91C97CC4D00CB50D0 /* SPUScheduledUpdateDriver.h in Headers */ = {isa = PBXBuildFile; fileRef = 7229E1B71C97CC4D00CB50D0 /* SPUScheduledUpdateDriver.h */; }; 7229E1BA1C97CC4D00CB50D0 /* SPUScheduledUpdateDriver.m in Sources */ = {isa = PBXBuildFile; fileRef = 7229E1B81C97CC4D00CB50D0 /* SPUScheduledUpdateDriver.m */; }; @@ -194,8 +200,6 @@ 723C8A561E2D60DB00C14942 /* SUTouchBarButtonGroup.m in Sources */ = {isa = PBXBuildFile; fileRef = 723C8A531E2D60DB00C14942 /* SUTouchBarButtonGroup.m */; }; 723EDC3F26885A8E000BCBA4 /* testappcast_channels.xml in Resources */ = {isa = PBXBuildFile; fileRef = 723EDC3E26885A8E000BCBA4 /* testappcast_channels.xml */; }; 72464F701E1F31E000FB341C /* SUOperatingSystem.m in Sources */ = {isa = PBXBuildFile; fileRef = 726F2CE41BC9C33D001971A4 /* SUOperatingSystem.m */; }; - 72464F711E1F326A00FB341C /* SUOperatingSystem.m in Sources */ = {isa = PBXBuildFile; fileRef = 726F2CE41BC9C33D001971A4 /* SUOperatingSystem.m */; }; - 72464F721E1F327C00FB341C /* SUOperatingSystem.m in Sources */ = {isa = PBXBuildFile; fileRef = 726F2CE41BC9C33D001971A4 /* SUOperatingSystem.m */; }; 72464F7C1E2097F600FB341C /* SUOperatingSystem.m in Sources */ = {isa = PBXBuildFile; fileRef = 726F2CE41BC9C33D001971A4 /* SUOperatingSystem.m */; }; 72464F7E1E21ED8C00FB341C /* SUHost.m in Sources */ = {isa = PBXBuildFile; fileRef = 61EF67550E25B58D00F754E0 /* SUHost.m */; }; 7246E0A31C83B685003B4E75 /* SPUStandardUpdaterController.h in Headers */ = {isa = PBXBuildFile; fileRef = 7246E0A11C83B685003B4E75 /* SPUStandardUpdaterController.h */; settings = {ATTRIBUTES = (Public, ); }; }; @@ -420,8 +424,6 @@ 72F94F5A1CC450DE002DEE68 /* SUInstallerLauncher.m in Sources */ = {isa = PBXBuildFile; fileRef = 726E07B11CAF08D6001A286B /* SUInstallerLauncher.m */; }; 72F9EBE21D517E2F004AC8B6 /* SUUpdater.h in Headers */ = {isa = PBXBuildFile; fileRef = 72F9EBE01D517E2F004AC8B6 /* SUUpdater.h */; settings = {ATTRIBUTES = (Public, ); }; }; 72F9EBE31D517E2F004AC8B6 /* SUUpdater.m in Sources */ = {isa = PBXBuildFile; fileRef = 72F9EBE11D517E2F004AC8B6 /* SUUpdater.m */; }; - 72F9EC341D5BF542004AC8B6 /* SUFileManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 7267E5E41D3D90AA00D1BF90 /* SUFileManager.m */; }; - 72F9EC351D5BF54E004AC8B6 /* SUFileManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 7267E5E41D3D90AA00D1BF90 /* SUFileManager.m */; }; 72F9EC3F1D5E823F004AC8B6 /* SPUUpdaterTimer.h in Headers */ = {isa = PBXBuildFile; fileRef = 72F9EC3D1D5E823F004AC8B6 /* SPUUpdaterTimer.h */; }; 72F9EC401D5E823F004AC8B6 /* SPUUpdaterTimer.m in Sources */ = {isa = PBXBuildFile; fileRef = 72F9EC3E1D5E823F004AC8B6 /* SPUUpdaterTimer.m */; }; 72F9EC441D5E9ED8004AC8B6 /* SPUDownloadData.h in Headers */ = {isa = PBXBuildFile; fileRef = 72F9EC421D5E9ED8004AC8B6 /* SPUDownloadData.h */; settings = {ATTRIBUTES = (Public, ); }; }; @@ -1003,7 +1005,7 @@ 61F3AC1215C22D4A00260CA2 /* th */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = th; path = th.lproj/Sparkle.strings; sourceTree = ""; }; 61F614540E24A12D009F47E7 /* it */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.strings; name = it; path = it.lproj/Sparkle.strings; sourceTree = ""; }; 7202DC99269ABD3500737EC4 /* testappcast_phasedRollout.xml */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xml; path = testappcast_phasedRollout.xml; sourceTree = ""; }; - 72045CE426FEE708004F96E5 /* strip-xpc-services.sh */ = {isa = PBXFileReference; lastKnownFileType = text.script.sh; path = "strip-xpc-services.sh"; sourceTree = ""; }; + 72045CE426FEE708004F96E5 /* strip-framework.sh */ = {isa = PBXFileReference; lastKnownFileType = text.script.sh; path = "strip-framework.sh"; sourceTree = ""; }; 7205C43E1E13049400E370AE /* generate_appcast */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = generate_appcast; sourceTree = BUILT_PRODUCTS_DIR; }; 7205C4401E13049400E370AE /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = ""; }; 7205C4461E1304C300E370AE /* Bridging-Header.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "Bridging-Header.h"; sourceTree = ""; }; @@ -1324,6 +1326,7 @@ 729F7EAD273F1840004592DC /* SPUUserAgent+Private.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "SPUUserAgent+Private.h"; sourceTree = ""; }; 729F7EAE273F1840004592DC /* SPUUserAgent+Private.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = "SPUUserAgent+Private.m"; sourceTree = ""; }; 729F7ECD27409076004592DC /* SparkleTestCodeSignApp_bad_extraneous.zip */ = {isa = PBXFileReference; lastKnownFileType = archive.zip; path = SparkleTestCodeSignApp_bad_extraneous.zip; sourceTree = ""; }; + 72A40F082956120D007C7DD5 /* ConfigFrameworkRelease.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = ConfigFrameworkRelease.xcconfig; sourceTree = ""; }; 72A450511C69A68900D67EEA /* SUUpdatePermissionResponse.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SUUpdatePermissionResponse.h; sourceTree = ""; }; 72A450521C69A68900D67EEA /* SUUpdatePermissionResponse.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SUUpdatePermissionResponse.m; sourceTree = ""; }; 72A4A23F1BB6567D00E7820D /* SUFileManagerTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SUFileManagerTest.swift; sourceTree = ""; }; @@ -2422,6 +2425,7 @@ 72F94ED61CC344A7002DEE68 /* ConfigDownloaderDebug.xcconfig */, FA1941D10D94A70100DD942E /* ConfigFramework.xcconfig */, FA1941CA0D94A70100DD942E /* ConfigFrameworkDebug.xcconfig */, + 72A40F082956120D007C7DD5 /* ConfigFrameworkRelease.xcconfig */, 724BB37E1D31D1EA005D534A /* ConfigInstallerConnection.xcconfig */, 724BB37F1D31D1EA005D534A /* ConfigInstallerConnectionDebug.xcconfig */, 726E07C11CAF1E79001A286B /* ConfigInstallerLauncher.xcconfig */, @@ -2451,7 +2455,7 @@ EA1E285922B6622E004AA304 /* ed25519-Shared.xcconfig */, 14732BC91960F70A00593899 /* make-release-package.sh */, 14652F7919A93E5F00959E44 /* set-git-version-info.sh */, - 72045CE426FEE708004F96E5 /* strip-xpc-services.sh */, + 72045CE426FEE708004F96E5 /* strip-framework.sh */, 720C192827127A3800740C8E /* release-move-tag.sh */, 720B4C2325EBFAFD005A0592 /* link-tools.sh */, 146EC84E19A68CF8004A50C5 /* Sparkle.podspec */, @@ -2826,7 +2830,7 @@ 8DC2EF520486A6940098B216 /* Resources */, 142E0E0319A6A24100E4312B /* Copy Tools */, 72045CDF26FEE51D004F96E5 /* Copy XPC Services */, - 72045CE626FEE8CC004F96E5 /* Strip XPC Services */, + 72045CE626FEE8CC004F96E5 /* Strip Framework */, 8DC2EF540486A6940098B216 /* Sources */, 8DC2EF560486A6940098B216 /* Frameworks */, 6131B1910DDCDE32005215F0 /* Run Script: Set Git Version Info */, @@ -3217,7 +3221,7 @@ shellScript = "\"$SRCROOT/Configurations/set-git-version-info.sh\"\n"; showEnvVarsInLog = 0; }; - 72045CE626FEE8CC004F96E5 /* Strip XPC Services */ = { + 72045CE626FEE8CC004F96E5 /* Strip Framework */ = { isa = PBXShellScriptBuildPhase; alwaysOutOfDate = 1; buildActionMask = 2147483647; @@ -3227,14 +3231,14 @@ ); inputPaths = ( ); - name = "Strip XPC Services"; + name = "Strip Framework"; outputFileListPaths = ( ); outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "\"$SRCROOT/Configurations/strip-xpc-services.sh\"\n"; + shellScript = "\"$SRCROOT/Configurations/strip-framework.sh\"\n"; }; 720B4C2125EBFAA5005A0592 /* Run Script: Link Tools */ = { isa = PBXShellScriptBuildPhase; @@ -3296,6 +3300,12 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 72266A8C29464D0200645376 /* SUSignatures.m in Sources */, + 72266A8B29464CEA00645376 /* SUHost.m in Sources */, + 72266A8A2946493C00645376 /* SUCodeSigningVerifier.m in Sources */, + 72266A89294636FB00645376 /* SUStandardVersionComparator.m in Sources */, + 72266A88294635BA00645376 /* SUAppcastDriver.m in Sources */, + 72266A872946359600645376 /* SUFileManager.m in Sources */, 725EE488277D398100D820CE /* SPUDeltaArchive.m in Sources */, 725EE483277C767A00D820CE /* SPUXarDeltaArchive.m in Sources */, 7269E4982648D3460088C213 /* SPUSkippedUpdate.m in Sources */, @@ -3417,7 +3427,6 @@ buildActionMask = 2147483647; files = ( 724BB3731D31D0B7005D534A /* main.m in Sources */, - 72F9EC341D5BF542004AC8B6 /* SUFileManager.m in Sources */, 724BB3711D31D0B7005D534A /* SUInstallerConnection.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; @@ -3427,7 +3436,6 @@ buildActionMask = 2147483647; files = ( 724BB39A1D333832005D534A /* main.m in Sources */, - 72F9EC351D5BF54E004AC8B6 /* SUFileManager.m in Sources */, 724BB3981D333832005D534A /* SUInstallerStatus.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; @@ -3445,7 +3453,6 @@ buildActionMask = 2147483647; files = ( 72464F7E1E21ED8C00FB341C /* SUHost.m in Sources */, - 72464F711E1F326A00FB341C /* SUOperatingSystem.m in Sources */, 726E07B41CAF08D6001A286B /* main.m in Sources */, 721D8A7B1D4963190032E472 /* SPULocalCacheDirectory.m in Sources */, 7267E5E11D3D901600D1BF90 /* SPUMessageTypes.m in Sources */, @@ -3462,7 +3469,6 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - 72464F721E1F327C00FB341C /* SUOperatingSystem.m in Sources */, 723B5DA71CF7AB0100365F95 /* main.m in Sources */, 72E539121D68C3FA0092CE5E /* SPUDownloadData.m in Sources */, 723B5DA91CF7AB0100365F95 /* SPUDownloader.m in Sources */, @@ -4112,7 +4118,7 @@ }; 1DEB91AF08733DA50010E9CD /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = FA1941D10D94A70100DD942E /* ConfigFramework.xcconfig */; + baseConfigurationReference = 72A40F082956120D007C7DD5 /* ConfigFrameworkRelease.xcconfig */; buildSettings = { }; name = Release; diff --git a/Sparkle/Base.lproj/SUUpdateAlert.xib b/Sparkle/Base.lproj/SUUpdateAlert.xib index 266912e7..59e601db 100644 --- a/Sparkle/Base.lproj/SUUpdateAlert.xib +++ b/Sparkle/Base.lproj/SUUpdateAlert.xib @@ -1,20 +1,20 @@ - + - + - - - - - - - + + + + + + + diff --git a/Sparkle/Base.lproj/SUUpdatePermissionPrompt.xib b/Sparkle/Base.lproj/SUUpdatePermissionPrompt.xib index 2463d83f..20cc4154 100644 --- a/Sparkle/Base.lproj/SUUpdatePermissionPrompt.xib +++ b/Sparkle/Base.lproj/SUUpdatePermissionPrompt.xib @@ -8,17 +8,17 @@ - - - - - - - - - - - + + + + + + + + + + + @@ -357,7 +357,7 @@ Gw - + diff --git a/Sparkle/InstallerProgress/InstallerProgressAppController.h b/Sparkle/InstallerProgress/InstallerProgressAppController.h index f7a5099d..7cc32ea0 100644 --- a/Sparkle/InstallerProgress/InstallerProgressAppController.h +++ b/Sparkle/InstallerProgress/InstallerProgressAppController.h @@ -12,7 +12,7 @@ NS_ASSUME_NONNULL_BEGIN @protocol InstallerProgressDelegate; -@interface InstallerProgressAppController : NSObject +SPU_OBJC_DIRECT_MEMBERS @interface InstallerProgressAppController : NSObject - (instancetype)initWithApplication:(NSApplication *)application arguments:(NSArray *)arguments delegate:(id)delegate; diff --git a/Sparkle/InstallerProgress/InstallerProgressAppController.m b/Sparkle/InstallerProgress/InstallerProgressAppController.m index 51fb5096..34cadf28 100644 --- a/Sparkle/InstallerProgress/InstallerProgressAppController.m +++ b/Sparkle/InstallerProgress/InstallerProgressAppController.m @@ -30,44 +30,30 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.3; @interface InstallerProgressAppController () - -@property (nonatomic, readonly) NSApplication *application; -@property (nonatomic, weak) id delegate; -@property (nonatomic, readonly) NSXPCConnection *connection; -@property (nonatomic) BOOL connected; -@property (nonatomic) BOOL repliedToRegistration; -@property (nonatomic, readonly) SUHost *oldHost; -@property (nonatomic, readonly) BOOL shouldRelaunchHostBundle; -@property (nonatomic, readonly) NSString *oldHostBundlePath; -@property (nonatomic, readonly) BOOL systemDomain; -@property (nonatomic) StatusInfo *statusInfo; -@property (nonatomic) BOOL submittedLauncherJob; -@property (nonatomic) BOOL willTerminate; -@property (nonatomic) BOOL applicationInitiallyAlive; -@property (nonatomic) NSBundle *applicationBundle; -@property (nonatomic) NSString *normalizedPath; - @end #define CONNECTION_ACKNOWLEDGEMENT_TIMEOUT 7ull @implementation InstallerProgressAppController - -@synthesize application = _application; -@synthesize delegate = _delegate; -@synthesize connection = _connection; -@synthesize connected = _connected; -@synthesize repliedToRegistration = _repliedToRegistration; -@synthesize oldHost = _oldHost; -@synthesize shouldRelaunchHostBundle = _shouldRelaunchHostBundle; -@synthesize oldHostBundlePath = _oldHostBundlePath; -@synthesize systemDomain = _systemDomain; -@synthesize statusInfo = _statusInfo; -@synthesize submittedLauncherJob = _submittedLauncherJob; -@synthesize willTerminate = _willTerminate; -@synthesize applicationInitiallyAlive = _applicationInitiallyAlive; -@synthesize applicationBundle = _applicationBundle; -@synthesize normalizedPath = _normalizedPath; +{ + NSApplication *_application; + NSXPCConnection *_connection; + SUHost *_oldHost; + NSString *_oldHostBundlePath; + StatusInfo *_statusInfo; + NSBundle *_applicationBundle; + NSString *_normalizedPath; + + __weak id _delegate; + + BOOL _connected; + BOOL _repliedToRegistration; + BOOL _shouldRelaunchHostBundle; + BOOL _systemDomain; + BOOL _submittedLauncherJob; + BOOL _willTerminate; + BOOL _applicationInitiallyAlive; +} - (instancetype)initWithApplication:(NSApplication *)application arguments:(NSArray *)arguments delegate:(id)delegate { @@ -126,25 +112,28 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.3; _connection.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUInstallerAgentInitiationProtocol)]; - __weak InstallerProgressAppController *weakSelf = self; + __weak __typeof__(self) weakSelf = self; _connection.interruptionHandler = ^{ dispatch_async(dispatch_get_main_queue(), ^{ - [weakSelf.connection invalidate]; + __typeof__(self) strongSelf = weakSelf; + if (strongSelf != nil) { + [strongSelf->_connection invalidate]; + } }); }; _connection.invalidationHandler = ^{ dispatch_async(dispatch_get_main_queue(), ^{ - InstallerProgressAppController *strongSelf = weakSelf; + __typeof__(self) strongSelf = weakSelf; if (strongSelf != nil) { - int exitStatus = (strongSelf.repliedToRegistration ? EXIT_SUCCESS : EXIT_FAILURE); + int exitStatus = (strongSelf->_repliedToRegistration ? EXIT_SUCCESS : EXIT_FAILURE); NSError *registrationError; - if (!strongSelf.repliedToRegistration) { + if (!strongSelf->_repliedToRegistration) { registrationError = [NSError errorWithDomain:SUSparkleErrorDomain code:SUAgentInvalidationError userInfo:@{ NSLocalizedDescriptionKey: @"Error: Agent Invalidating without having the chance to reply to installer" }]; } else { registrationError = nil; } - if (!strongSelf.willTerminate) { + if (!strongSelf->_willTerminate) { [strongSelf cleanupAndExitWithStatus:exitStatus error:registrationError]; } } @@ -156,22 +145,22 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.3; - (void)run { - [self.application run]; + [_application run]; } -- (void)startConnection +- (void)startConnection SPU_OBJC_DIRECT { - [self.statusInfo startListener]; + [_statusInfo startListener]; - [self.connection resume]; - [(id)self.connection.remoteObjectProxy connectionDidInitiateWithReply:^{ + [_connection resume]; + [(id)_connection.remoteObjectProxy connectionDidInitiateWithReply:^{ dispatch_async(dispatch_get_main_queue(), ^{ - self.connected = YES; + self->_connected = YES; }); }]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(CONNECTION_ACKNOWLEDGEMENT_TIMEOUT * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ - if (!self.connected) { + if (!self->_connected) { SULog(SULogLevelError, @"Timeout error: failed to receive acknowledgement from installer"); [self cleanupAndExitWithStatus:EXIT_FAILURE error:nil]; } @@ -189,11 +178,11 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.3; SULog(SULogLevelError, @"Agent failed.."); SULogError(error); - [(id)self.connection.remoteObjectProxy connectionWillInvalidateWithError:error]; + [(id)_connection.remoteObjectProxy connectionWillInvalidateWithError:error]; } - [self.statusInfo invalidate]; - [self.connection invalidate]; + [_statusInfo invalidate]; + [_connection invalidate]; // Remove the agent bundle; it is assumed this bundle is in a temporary/cache/support directory NSError *theError = nil; @@ -217,7 +206,7 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.3; exit(status); } -- (NSArray *)runningApplicationsWithBundle:(NSBundle *)bundle +- (NSArray *)runningApplicationsWithBundle:(NSBundle *)bundle SPU_OBJC_DIRECT { // Resolve symlinks otherwise when we compare file paths, we may not realize two paths that are represented differently are the same NSArray *bundlePathComponents = bundle.bundlePath.stringByResolvingSymlinksInPath.pathComponents; @@ -262,7 +251,7 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.3; - (void)registerApplicationBundlePath:(NSString *)applicationBundlePath reply:(void (^)(NSNumber *))reply { dispatch_async(dispatch_get_main_queue(), ^{ - if (applicationBundlePath != nil && !self.willTerminate) { + if (applicationBundlePath != nil && !self->_willTerminate) { NSBundle *applicationBundle = [NSBundle bundleWithPath:applicationBundlePath]; if (applicationBundle == nil) { [self cleanupAndExitWithStatus:EXIT_FAILURE error:[NSError errorWithDomain:SUSparkleErrorDomain code:SUAgentInvalidationError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Error: Encountered invalid path for waiting termination: %@", applicationBundlePath] }]]; @@ -271,12 +260,12 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.3; // Compute normalized path that we may use later for relaunching the application // We compute normalized path from progress agent instead of trusting or having the installer // pass it to us - if (SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME && [applicationBundle.bundlePath isEqualToString:self.oldHostBundlePath]) { - NSString *normalizedPath = SUNormalizedInstallationPath(self.oldHost); + if (SPARKLE_NORMALIZE_INSTALLED_APPLICATION_NAME && [applicationBundle.bundlePath isEqualToString:self->_oldHostBundlePath]) { + NSString *normalizedPath = SUNormalizedInstallationPath(self->_oldHost); // We only use normalized path if it doesn't already exist // Check the installer which has the same logic if (![[NSFileManager defaultManager] fileExistsAtPath:normalizedPath]) { - self.normalizedPath = SUNormalizedInstallationPath(self.oldHost); + self->_normalizedPath = SUNormalizedInstallationPath(self->_oldHost); } } @@ -293,9 +282,9 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.3; reply(processIdentifier); - self.repliedToRegistration = YES; - self.applicationBundle = applicationBundle; - self.applicationInitiallyAlive = (processIdentifier != nil); + self->_repliedToRegistration = YES; + self->_applicationBundle = applicationBundle; + self->_applicationInitiallyAlive = (processIdentifier != nil); } else { assert(false); } @@ -305,12 +294,12 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.3; - (void)registerInstallationInfoData:(NSData *)installationInfoData { dispatch_async(dispatch_get_main_queue(), ^{ - if (self.statusInfo.installationInfoData == nil && installationInfoData != nil) { + if (self->_statusInfo.installationInfoData == nil && installationInfoData != nil) { SPUInstallationInfo *installationInfo = (SPUInstallationInfo *)SPUUnarchiveRootObjectSecurely(installationInfoData, [SPUInstallationInfo class]); if (installationInfo != nil) { - installationInfo.systemDomain = self.systemDomain; - self.statusInfo.installationInfoData = SPUArchiveRootObjectSecurely(installationInfo); + installationInfo.systemDomain = self->_systemDomain; + self->_statusInfo.installationInfoData = SPUArchiveRootObjectSecurely(installationInfo); } else { SULog(SULogLevelError, @"Error: Failed to decode initial installation info from installer: %@", installationInfoData); } @@ -321,9 +310,9 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.3; - (void)sendTerminationSignal { dispatch_async(dispatch_get_main_queue(), ^{ - if (!self.willTerminate && self.applicationBundle != nil) { + if (!self->_willTerminate && self->_applicationBundle != nil) { // Note we are sending an Apple quit event, which gives the application or user a chance to delay or cancel the request, which is what we desire - for (NSRunningApplication *runningApplication in [self runningApplicationsWithBundle:self.applicationBundle]) { + for (NSRunningApplication *runningApplication in [self runningApplicationsWithBundle:self->_applicationBundle]) { [runningApplication terminate]; } } @@ -333,15 +322,15 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.3; - (void)relaunchApplication { dispatch_async(dispatch_get_main_queue(), ^{ - if (!self.willTerminate && self.applicationBundle != nil && self.applicationInitiallyAlive) { + if (!self->_willTerminate && self->_applicationBundle != nil && self->_applicationInitiallyAlive) { NSString *pathToRelaunch; - if (self.normalizedPath != nil) { - pathToRelaunch = self.normalizedPath; - } else if (self.shouldRelaunchHostBundle) { - // Use self.oldHostBundlePath because it was computed before self.oldHost could have been removed - pathToRelaunch = self.oldHostBundlePath; + if (self->_normalizedPath != nil) { + pathToRelaunch = self->_normalizedPath; + } else if (self->_shouldRelaunchHostBundle) { + // Use self->_oldHostBundlePath because it was computed before self->_oldHost could have been removed + pathToRelaunch = self->_oldHostBundlePath; } else { - pathToRelaunch = self.applicationBundle.bundlePath; + pathToRelaunch = self->_applicationBundle.bundlePath; } // We should at least make sure we're opening a bundle @@ -358,7 +347,7 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.3; // Delay termination for a little bit to better increase the chance the updated application when relaunched will be the frontmost application // This is related to macOS activation issues when terminating a frontmost application happens right before launching another app - self.willTerminate = YES; + self->_willTerminate = YES; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(SUTerminationTimeDelay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [self cleanupAndExitWithStatus:EXIT_SUCCESS error:nil]; }); @@ -369,18 +358,18 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.3; - (void)showProgress { dispatch_async(dispatch_get_main_queue(), ^{ - if (!self.willTerminate) { + if (!self->_willTerminate) { // Show app icon in the dock ProcessSerialNumber psn = { 0, kCurrentProcess }; TransformProcessType(&psn, kProcessTransformToForegroundApplication); // Note: the application icon needs to be set after showing the icon in the dock - self.application.applicationIconImage = [SUApplicationInfo bestIconForHost:self.oldHost]; + self->_application.applicationIconImage = [SUApplicationInfo bestIconForHost:self->_oldHost]; // Activate ourselves otherwise we will probably be in the background - [self.application activateIgnoringOtherApps:YES]; + [self->_application activateIgnoringOtherApps:YES]; - [self.delegate installerProgressShouldDisplayWithHost:self.oldHost]; + [self->_delegate installerProgressShouldDisplayWithHost:self->_oldHost]; } }); } @@ -389,13 +378,13 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.3; { dispatch_async(dispatch_get_main_queue(), ^{ // Dismiss any UI immediately - [self.delegate installerProgressShouldStop]; - self.delegate = nil; + [self->_delegate installerProgressShouldStop]; + self->_delegate = nil; // No need to broadcast status service anymore // In fact we shouldn't when we decide to relaunch the update - [self.statusInfo invalidate]; - self.statusInfo = nil; + [self->_statusInfo invalidate]; + self->_statusInfo = nil; }); } diff --git a/Sparkle/InstallerProgress/ShowInstallerProgress.m b/Sparkle/InstallerProgress/ShowInstallerProgress.m index 54800a92..bf897010 100644 --- a/Sparkle/InstallerProgress/ShowInstallerProgress.m +++ b/Sparkle/InstallerProgress/ShowInstallerProgress.m @@ -12,21 +12,14 @@ #import "SUHost.h" #import "SULocalizations.h" -@interface ShowInstallerProgress () - -@property (nonatomic) SUStatusController *statusController; - -@end - @implementation ShowInstallerProgress { + SUStatusController *_statusController; NSString *_updatingString; NSString *_cancelUpdateTitle; NSString *_installingUpdateTitle; } -@synthesize statusController = _statusController; - - (void)loadLocalizationStringsFromHost:(SUHost *)host { // Try to retrieve localization strings from the old bundle if possible @@ -34,6 +27,7 @@ // (which will be after the update is trusted) // If we fail to load localizations in any way, we default to English +#if SPARKLE_COPY_LOCALIZATIONS NSBundle *hostSparkleBundle; { NSURL *hostSparkleURL = [host.bundle.privateFrameworksURL URLByAppendingPathComponent:@"Sparkle.framework" isDirectory:YES]; @@ -43,55 +37,76 @@ hostSparkleBundle = [NSBundle bundleWithURL:hostSparkleURL]; } } +#endif NSString *updatingString; { - NSString *updatingFormatStringFromBundle = (hostSparkleBundle != nil) ? SULocalizedStringFromTableInBundle(@"Updating %@", @"Sparkle", hostSparkleBundle, nil) : nil; - NSString *hostNameFromBundle = host.name; NSString *hostName = (hostNameFromBundle != nil) ? hostNameFromBundle : @""; - if (updatingFormatStringFromBundle != nil) { - // Replacing the %@ will be a bit safer than using +[NSString stringWithFormat:] - updatingString = [updatingFormatStringFromBundle stringByReplacingOccurrencesOfString:@"%@" withString:hostName]; - } else { +#if SPARKLE_COPY_LOCALIZATIONS + { + NSString *updatingFormatStringFromBundle = (hostSparkleBundle != nil) ? SULocalizedStringFromTableInBundle(@"Updating %@", @"Sparkle", hostSparkleBundle, nil) : nil; + + if (updatingFormatStringFromBundle != nil) { + // Replacing the %@ will be a bit safer than using +[NSString stringWithFormat:] + updatingString = [updatingFormatStringFromBundle stringByReplacingOccurrencesOfString:@"%@" withString:hostName]; + } else { + updatingString = [@"Updating " stringByAppendingString:hostName]; + } + } +#else + { updatingString = [@"Updating " stringByAppendingString:hostName]; } +#endif } _updatingString = updatingString; NSString *cancelUpdateTitle; +#if SPARKLE_COPY_LOCALIZATIONS { NSString *cancelUpdateTitleFromBundle = (hostSparkleBundle != nil) ? SULocalizedStringFromTableInBundle(@"Cancel Update", @"Sparkle", hostSparkleBundle, @"") : nil; cancelUpdateTitle = (cancelUpdateTitleFromBundle != nil) ? cancelUpdateTitleFromBundle : @"Cancel Update"; } - +#else + { + cancelUpdateTitle = @"Cancel Update"; + } +#endif _cancelUpdateTitle = cancelUpdateTitle; NSString *installingUpdateTitle; +#if SPARKLE_COPY_LOCALIZATIONS { NSString *installingUpdateTitleFromBundle = (hostSparkleBundle != nil) ? SULocalizedStringFromTableInBundle(@"Installing update…", @"Sparkle", hostSparkleBundle, @"") : nil; installingUpdateTitle = (installingUpdateTitleFromBundle != nil) ? installingUpdateTitleFromBundle : @"Installing update…"; } +#else + { + installingUpdateTitle = @"Installing update…"; + } +#endif _installingUpdateTitle = installingUpdateTitle; } - (void)installerProgressShouldDisplayWithHost:(SUHost *)host { - self.statusController = [[SUStatusController alloc] initWithHost:host windowTitle:_updatingString centerPointValue:nil minimizable:NO closable:NO]; + _statusController = [[SUStatusController alloc] initWithHost:host windowTitle:_updatingString centerPointValue:nil minimizable:NO closable:NO]; - [self.statusController setButtonTitle:_cancelUpdateTitle target:nil action:nil isDefault:NO]; - [self.statusController beginActionWithTitle:_installingUpdateTitle maxProgressValue:0 statusText:@""]; + [_statusController setButtonTitle:_cancelUpdateTitle target:nil action:nil isDefault:NO]; - [self.statusController showWindow:self]; + [_statusController beginActionWithTitle:_installingUpdateTitle maxProgressValue:0 statusText:@""]; + + [_statusController showWindow:self]; } - (void)installerProgressShouldStop { - [self.statusController close]; - self.statusController = nil; + [_statusController close]; + _statusController = nil; } @end diff --git a/Sparkle/SPUAppcastItemState.h b/Sparkle/SPUAppcastItemState.h index 8dcb6e60..64967a67 100644 --- a/Sparkle/SPUAppcastItemState.h +++ b/Sparkle/SPUAppcastItemState.h @@ -11,7 +11,7 @@ NS_ASSUME_NONNULL_BEGIN // Appcast Item state that contains properties that depends on a host -@interface SPUAppcastItemState : NSObject +SPU_OBJC_DIRECT_MEMBERS @interface SPUAppcastItemState : NSObject - (instancetype)init NS_UNAVAILABLE; diff --git a/Sparkle/SPUAppcastItemState.m b/Sparkle/SPUAppcastItemState.m index 6d6ee1fd..c82df935 100644 --- a/Sparkle/SPUAppcastItemState.m +++ b/Sparkle/SPUAppcastItemState.m @@ -48,11 +48,11 @@ - (void)encodeWithCoder:(NSCoder *)encoder { - [encoder encodeBool:self.majorUpgrade forKey:SPUAppcastItemStateMajorUpgradeKey]; - [encoder encodeBool:self.criticalUpdate forKey:SPUAppcastItemStateCriticalUpdateKey]; - [encoder encodeBool:self.informationalUpdate forKey:SPUAppcastItemStateInformationalUpdateKey]; - [encoder encodeBool:self.minimumOperatingSystemVersionIsOK forKey:SPUAppcastItemStateMinimumOperatingSystemVersionIsOKKey]; - [encoder encodeBool:self.maximumOperatingSystemVersionIsOK forKey:SPUAppcastItemStateMaximumOperatingSystemVersionIsOKKey]; + [encoder encodeBool:_majorUpgrade forKey:SPUAppcastItemStateMajorUpgradeKey]; + [encoder encodeBool:_criticalUpdate forKey:SPUAppcastItemStateCriticalUpdateKey]; + [encoder encodeBool:_informationalUpdate forKey:SPUAppcastItemStateInformationalUpdateKey]; + [encoder encodeBool:_minimumOperatingSystemVersionIsOK forKey:SPUAppcastItemStateMinimumOperatingSystemVersionIsOKKey]; + [encoder encodeBool:_maximumOperatingSystemVersionIsOK forKey:SPUAppcastItemStateMaximumOperatingSystemVersionIsOKKey]; } - (instancetype)initWithCoder:(NSCoder *)decoder diff --git a/Sparkle/SPUAppcastItemStateResolver.h b/Sparkle/SPUAppcastItemStateResolver.h index 825a5e2e..929d3f1b 100644 --- a/Sparkle/SPUAppcastItemStateResolver.h +++ b/Sparkle/SPUAppcastItemStateResolver.h @@ -8,7 +8,15 @@ #import +#if defined(BUILDING_SPARKLE_SOURCES_EXTERNALLY) +// Ignore incorrect warning +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wquoted-include-in-framework-header" +#import "SUExport.h" +#pragma clang diagnostic pop +#else #import +#endif NS_ASSUME_NONNULL_BEGIN diff --git a/Sparkle/SPUAppcastItemStateResolver.m b/Sparkle/SPUAppcastItemStateResolver.m index 482ad53d..31a0b2cc 100644 --- a/Sparkle/SPUAppcastItemStateResolver.m +++ b/Sparkle/SPUAppcastItemStateResolver.m @@ -17,19 +17,12 @@ #include "AppKitPrevention.h" -@interface SPUAppcastItemStateResolver () - -@property (nonatomic, readonly) NSString *hostVersion; -@property (nonatomic, readonly) id applicationVersionComparator; -@property (nonatomic, readonly) SUStandardVersionComparator *standardVersionComparator; - -@end - @implementation SPUAppcastItemStateResolver - -@synthesize hostVersion = _hostVersion; -@synthesize applicationVersionComparator = _applicationVersionComparator; -@synthesize standardVersionComparator = _standardVersionComparator; +{ + NSString *_hostVersion; + id _applicationVersionComparator; + SUStandardVersionComparator *_standardVersionComparator; +} - (instancetype)initWithHostVersion:(NSString *)hostVersion applicationVersionComparator:(id)applicationVersionComparator standardVersionComparator:(SUStandardVersionComparator *)standardVersionComparator { @@ -46,7 +39,7 @@ { BOOL minimumVersionOK = YES; if (minimumSystemVersion != nil && ![minimumSystemVersion isEqualToString:@""]) { - minimumVersionOK = [self.standardVersionComparator compareVersion:(NSString * _Nonnull)minimumSystemVersion toVersion:[SUOperatingSystem systemVersionString]] != NSOrderedDescending; + minimumVersionOK = [_standardVersionComparator compareVersion:(NSString * _Nonnull)minimumSystemVersion toVersion:[SUOperatingSystem systemVersionString]] != NSOrderedDescending; } return minimumVersionOK; } @@ -55,7 +48,7 @@ { BOOL maximumVersionOK = YES; if (maximumSystemVersion != nil && ![maximumSystemVersion isEqualToString:@""]) { - maximumVersionOK = [self.standardVersionComparator compareVersion:(NSString * _Nonnull)maximumSystemVersion toVersion:[SUOperatingSystem systemVersionString]] != NSOrderedAscending; + maximumVersionOK = [_standardVersionComparator compareVersion:(NSString * _Nonnull)maximumSystemVersion toVersion:[SUOperatingSystem systemVersionString]] != NSOrderedAscending; } return maximumVersionOK; } @@ -67,7 +60,7 @@ - (BOOL)isMinimumAutoupdateVersionOK:(NSString * _Nullable)minimumAutoupdateVersion { - return [[self class] isMinimumAutoupdateVersionOK:minimumAutoupdateVersion hostVersion:self.hostVersion versionComparator:self.applicationVersionComparator]; + return [[self class] isMinimumAutoupdateVersionOK:minimumAutoupdateVersion hostVersion:_hostVersion versionComparator:_applicationVersionComparator]; } - (BOOL)isCriticalUpdateWithCriticalUpdateDictionary:(NSDictionary * _Nullable)criticalUpdateDictionary @@ -84,7 +77,7 @@ } // Update is only critical when coming from previous versions - return ([self.applicationVersionComparator compareVersion:self.hostVersion toVersion:criticalVersion] == NSOrderedAscending); + return ([_applicationVersionComparator compareVersion:_hostVersion toVersion:criticalVersion] == NSOrderedAscending); } - (BOOL)isInformationalUpdateWithInformationalUpdateVersions:(NSSet * _Nullable)informationalUpdateVersions @@ -98,7 +91,7 @@ return YES; } - NSString *hostVersion = self.hostVersion; + NSString *hostVersion = _hostVersion; // Informational update only for a set of host versions we're updating from if ([informationalUpdateVersions containsObject:hostVersion]) { @@ -108,7 +101,7 @@ // If an informational update version has a '<' prefix, this is an informational update if // hostVersion < this info update version for (NSString *informationalUpdateVersion in informationalUpdateVersions) { - if ([informationalUpdateVersion hasPrefix:@"<"] && [self.applicationVersionComparator compareVersion:hostVersion toVersion:[informationalUpdateVersion substringFromIndex:1]] == NSOrderedAscending) { + if ([informationalUpdateVersion hasPrefix:@"<"] && [_applicationVersionComparator compareVersion:hostVersion toVersion:[informationalUpdateVersion substringFromIndex:1]] == NSOrderedAscending) { return YES; } } diff --git a/Sparkle/SPUAutomaticUpdateDriver.h b/Sparkle/SPUAutomaticUpdateDriver.h index 91373567..1c06e701 100644 --- a/Sparkle/SPUAutomaticUpdateDriver.h +++ b/Sparkle/SPUAutomaticUpdateDriver.h @@ -14,7 +14,7 @@ NS_ASSUME_NONNULL_BEGIN @class SUHost; @protocol SPUUpdaterDelegate, SPUUserDriver; -@interface SPUAutomaticUpdateDriver : NSObject +SPU_OBJC_DIRECT_MEMBERS @interface SPUAutomaticUpdateDriver : NSObject - (instancetype)initWithHost:(SUHost *)host applicationBundle:(NSBundle *)applicationBundle updater:(id)updater userDriver:(id )userDriver updaterDelegate:(nullable id )updaterDelegate; diff --git a/Sparkle/SPUAutomaticUpdateDriver.m b/Sparkle/SPUAutomaticUpdateDriver.m index d3f1e8d8..087b44d4 100644 --- a/Sparkle/SPUAutomaticUpdateDriver.m +++ b/Sparkle/SPUAutomaticUpdateDriver.m @@ -20,24 +20,19 @@ #include "AppKitPrevention.h" @interface SPUAutomaticUpdateDriver () - -@property (nonatomic, readonly, weak) id updater; -@property (nonatomic, readonly, weak) id userDriver; -@property (nonatomic, readonly, weak, nullable) id updaterDelegate; -@property (nonatomic, readonly) SPUCoreBasedUpdateDriver *coreDriver; -@property (nonatomic) SUAppcastItem* updateItem; -@property (nonatomic) BOOL willInstallSilently; - @end @implementation SPUAutomaticUpdateDriver - -@synthesize updater = _updater; -@synthesize userDriver = _userDriver; -@synthesize updaterDelegate = _updaterDelegate; -@synthesize coreDriver = _coreDriver; -@synthesize updateItem = _updateItem; -@synthesize willInstallSilently = _willInstallSilently; +{ + SPUCoreBasedUpdateDriver *_coreDriver; + SUAppcastItem* _updateItem; + + __weak id _updater; + __weak id _userDriver; + __weak id _updaterDelegate; + + BOOL _willInstallSilently; +} - (instancetype)initWithHost:(SUHost *)host applicationBundle:(NSBundle *)applicationBundle updater:(id)updater userDriver:(id )userDriver updaterDelegate:(nullable id )updaterDelegate { @@ -54,7 +49,7 @@ - (void)setCompletionHandler:(SPUUpdateDriverCompletion)completionBlock { - [self.coreDriver setCompletionHandler:completionBlock]; + [_coreDriver setCompletionHandler:completionBlock]; } - (void)setUpdateShownHandler:(void (^)(void))updateShownHandler @@ -63,12 +58,12 @@ - (void)setUpdateWillInstallHandler:(void (^)(void))updateWillInstallHandler { - [self.coreDriver setUpdateWillInstallHandler:updateWillInstallHandler]; + [_coreDriver setUpdateWillInstallHandler:updateWillInstallHandler]; } - (void)checkForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders { - [self.coreDriver checkForUpdatesAtAppcastURL:appcastURL withUserAgent:userAgent httpHeaders:httpHeaders inBackground:YES requiresSilentInstall:YES]; + [_coreDriver checkForUpdatesAtAppcastURL:appcastURL withUserAgent:userAgent httpHeaders:httpHeaders inBackground:YES requiresSilentInstall:YES]; } - (void)resumeInstallingUpdate @@ -85,13 +80,13 @@ - (void)basicDriverDidFindUpdateWithAppcastItem:(SUAppcastItem *)updateItem secondaryAppcastItem:(SUAppcastItem * _Nullable)secondaryUpdateItem { - self.updateItem = updateItem; + _updateItem = updateItem; if (updateItem.isInformationOnlyUpdate || updateItem.majorUpgrade) { - [self.coreDriver deferInformationalUpdate:updateItem secondaryUpdate:secondaryUpdateItem]; + [_coreDriver deferInformationalUpdate:updateItem secondaryUpdate:secondaryUpdateItem]; [self abortUpdate]; } else { - [self.coreDriver downloadUpdateFromAppcastItem:updateItem secondaryAppcastItem:secondaryUpdateItem inBackground:YES]; + [_coreDriver downloadUpdateFromAppcastItem:updateItem secondaryAppcastItem:secondaryUpdateItem inBackground:YES]; } } @@ -102,16 +97,19 @@ - (void)installerDidFinishPreparationAndWillInstallImmediately:(BOOL)willInstallImmediately silently:(BOOL)willInstallSilently { - self.willInstallSilently = willInstallSilently; + _willInstallSilently = willInstallSilently; if (!willInstallImmediately) { BOOL installationHandledByDelegate = NO; - id updaterDelegate = self.updaterDelegate; - if (self.willInstallSilently && [updaterDelegate respondsToSelector:@selector(updater:willInstallUpdateOnQuit:immediateInstallationBlock:)]) { - __weak SPUAutomaticUpdateDriver *weakSelf = self; - installationHandledByDelegate = [updaterDelegate updater:self.updater willInstallUpdateOnQuit:self.updateItem immediateInstallationBlock:^{ + id updaterDelegate = _updaterDelegate; + if (_willInstallSilently && [updaterDelegate respondsToSelector:@selector(updater:willInstallUpdateOnQuit:immediateInstallationBlock:)]) { + __weak __typeof__(self) weakSelf = self; + installationHandledByDelegate = [updaterDelegate updater:_updater willInstallUpdateOnQuit:_updateItem immediateInstallationBlock:^{ dispatch_async(dispatch_get_main_queue(), ^{ - [weakSelf.coreDriver finishInstallationWithResponse:SPUUserUpdateChoiceInstall displayingUserInterface:NO]; + __typeof__(self) strongSelf = weakSelf; + if (strongSelf != nil) { + [strongSelf->_coreDriver finishInstallationWithResponse:SPUUserUpdateChoiceInstall displayingUserInterface:NO]; + } }); }]; } @@ -141,9 +139,9 @@ - (void)abortUpdateWithError:(NSError *)error { - BOOL showNextUpdateImmediately = (error == nil || error.code == SUInstallationAuthorizeLaterError) && (!self.willInstallSilently || self.updateItem.criticalUpdate || self.updateItem.isInformationOnlyUpdate); + BOOL showNextUpdateImmediately = (error == nil || error.code == SUInstallationAuthorizeLaterError) && (!_willInstallSilently || _updateItem.criticalUpdate || _updateItem.isInformationOnlyUpdate); - [self.coreDriver abortUpdateAndShowNextUpdateImmediately:showNextUpdateImmediately error:error]; + [_coreDriver abortUpdateAndShowNextUpdateImmediately:showNextUpdateImmediately error:error]; } @end diff --git a/Sparkle/SPUBasicUpdateDriver.h b/Sparkle/SPUBasicUpdateDriver.h index 92af089a..192921e7 100644 --- a/Sparkle/SPUBasicUpdateDriver.h +++ b/Sparkle/SPUBasicUpdateDriver.h @@ -27,7 +27,7 @@ NS_ASSUME_NONNULL_BEGIN @end -@interface SPUBasicUpdateDriver : NSObject +SPU_OBJC_DIRECT_MEMBERS @interface SPUBasicUpdateDriver : NSObject - (instancetype)initWithHost:(SUHost *)host updateCheck:(SPUUpdateCheck)updateCheck updater:(id)updater updaterDelegate:(nullable id )updaterDelegate delegate:(id )delegate; diff --git a/Sparkle/SPUBasicUpdateDriver.m b/Sparkle/SPUBasicUpdateDriver.m index 7bc8deda..28dfe40c 100644 --- a/Sparkle/SPUBasicUpdateDriver.m +++ b/Sparkle/SPUBasicUpdateDriver.m @@ -25,29 +25,23 @@ @interface SPUBasicUpdateDriver () -@property (nonatomic, weak, readonly) id delegate; -@property (nonatomic, readonly) SUAppcastDriver *appcastDriver; -@property (nonatomic, copy) SPUUpdateDriverCompletion completionBlock; - -@property (nonatomic, readonly) SUHost *host; -@property (nonatomic, readonly) SPUUpdateCheck updateCheck; -@property (nonatomic, readonly, weak) id updater; // if we didn't have legacy support, I'd remove this.. -@property (nullable, nonatomic, readonly, weak) id updaterDelegate; - -@property (nonatomic) BOOL aborted; - @end @implementation SPUBasicUpdateDriver - -@synthesize host = _host; -@synthesize updateCheck = _updateCheck; -@synthesize updater = _updater; -@synthesize updaterDelegate = _updaterDelegate; -@synthesize delegate = _delegate; -@synthesize appcastDriver = _appcastDriver; -@synthesize completionBlock = _completionBlock; -@synthesize aborted = _aborted; +{ + SUAppcastDriver *_appcastDriver; + SUHost *_host; + + SPUUpdateDriverCompletion _completionBlock; + + SPUUpdateCheck _updateCheck; + + __weak id _updater; + __weak id _updaterDelegate; + __weak id _delegate; + + BOOL _aborted; +} - (instancetype)initWithHost:(SUHost *)host updateCheck:(SPUUpdateCheck)updateCheck updater:(id)updater updaterDelegate:(id )updaterDelegate delegate:(id )delegate { @@ -66,27 +60,31 @@ - (void)setCompletionHandler:(SPUUpdateDriverCompletion)completionBlock { - self.completionBlock = completionBlock; + _completionBlock = [completionBlock copy]; } - (void)checkForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders inBackground:(BOOL)background { - if ([self.host isRunningOnReadOnlyVolume]) { - NSString *hostName = self.host.name; - if ([self.host isRunningTranslocated]) { - [self.delegate basicDriverIsRequestingAbortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SURunningTranslocated userInfo:@{ NSLocalizedRecoverySuggestionErrorKey: [NSString stringWithFormat:SULocalizedString(@"Quit %1$@, move it into your Applications folder, relaunch it from there and try again.", nil), hostName], NSLocalizedDescriptionKey: [NSString stringWithFormat:SULocalizedString(@"%1$@ can’t be updated if it’s running from the location it was downloaded to.", nil), hostName], }]]; + if ([_host isRunningOnReadOnlyVolume]) { + NSString *hostName = _host.name; + id delegate = _delegate; +#if SPARKLE_COPY_LOCALIZATIONS + NSBundle *sparkleBundle = SUSparkleBundle(); +#endif + if ([_host isRunningTranslocated]) { + [delegate basicDriverIsRequestingAbortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SURunningTranslocated userInfo:@{ NSLocalizedRecoverySuggestionErrorKey: [NSString stringWithFormat:SULocalizedStringFromTableInBundle(@"Quit %1$@, move it into your Applications folder, relaunch it from there and try again.", SPARKLE_TABLE, sparkleBundle, nil), hostName], NSLocalizedDescriptionKey: [NSString stringWithFormat:SULocalizedStringFromTableInBundle(@"%1$@ can’t be updated if it’s running from the location it was downloaded to.", SPARKLE_TABLE, sparkleBundle, nil), hostName], }]]; } else { - [self.delegate basicDriverIsRequestingAbortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SURunningFromDiskImageError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:SULocalizedString(@"%1$@ can’t be updated, because it was opened from a read-only or a temporary location.", nil), hostName], NSLocalizedRecoverySuggestionErrorKey: [NSString stringWithFormat:SULocalizedString(@"Use Finder to copy %1$@ to the Applications folder, relaunch it from there, and try again.", nil), hostName] }]]; + [delegate basicDriverIsRequestingAbortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SURunningFromDiskImageError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:SULocalizedStringFromTableInBundle(@"%1$@ can’t be updated, because it was opened from a read-only or a temporary location.", SPARKLE_TABLE, sparkleBundle, nil), hostName], NSLocalizedRecoverySuggestionErrorKey: [NSString stringWithFormat:SULocalizedStringFromTableInBundle(@"Use Finder to copy %1$@ to the Applications folder, relaunch it from there, and try again.", SPARKLE_TABLE, sparkleBundle, nil), hostName] }]]; } } else { - [self.appcastDriver loadAppcastFromURL:appcastURL userAgent:userAgent httpHeaders:httpHeaders inBackground:background]; + [_appcastDriver loadAppcastFromURL:appcastURL userAgent:userAgent httpHeaders:httpHeaders inBackground:background]; } } -- (void)notifyResumableUpdateItem:(SUAppcastItem *)updateItem secondaryUpdateItem:(SUAppcastItem * _Nullable)secondaryUpdateItem systemDomain:(NSNumber * _Nullable)systemDomain +- (void)notifyResumableUpdateItem:(SUAppcastItem *)updateItem secondaryUpdateItem:(SUAppcastItem * _Nullable)secondaryUpdateItem systemDomain:(NSNumber * _Nullable)systemDomain SPU_OBJC_DIRECT { if (updateItem == nil) { - [self.delegate basicDriverIsRequestingAbortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUResumeAppcastError userInfo:@{ NSLocalizedDescriptionKey: SULocalizedString(@"Failed to resume installing update.", nil) }]]; + [_delegate basicDriverIsRequestingAbortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUResumeAppcastError userInfo:@{ NSLocalizedDescriptionKey: SULocalizedStringFromTableInBundle(@"Failed to resume installing update.", SPARKLE_TABLE, SUSparkleBundle(), nil) }]]; } else { // Kind of lying, but triggering the notification so drivers can know when to stop showing initial fetching progress [self notifyFinishLoadingAppcast]; @@ -98,7 +96,7 @@ - (void)resumeInstallingUpdate { - NSString *hostBundleIdentifier = self.host.bundle.bundleIdentifier; + NSString *hostBundleIdentifier = _host.bundle.bundleIdentifier; assert(hostBundleIdentifier != nil); [SPUProbeInstallStatus probeInstallerUpdateItemForHostBundleIdentifier:hostBundleIdentifier completion:^(SPUInstallationInfo * _Nullable installationInfo) { dispatch_async(dispatch_get_main_queue(), ^{ @@ -114,57 +112,66 @@ - (void)didFailToFetchAppcastWithError:(NSError *)error { - if (!self.aborted) { - [self.delegate basicDriverIsRequestingAbortUpdateWithError:error]; + if (!_aborted) { + [_delegate basicDriverIsRequestingAbortUpdateWithError:error]; } } -- (void)notifyFinishLoadingAppcast +- (void)notifyFinishLoadingAppcast SPU_OBJC_DIRECT { - if ([self.delegate respondsToSelector:@selector(basicDriverDidFinishLoadingAppcast)]) { - [self.delegate basicDriverDidFinishLoadingAppcast]; + id delegate = _delegate; + if ([delegate respondsToSelector:@selector(basicDriverDidFinishLoadingAppcast)]) { + [delegate basicDriverDidFinishLoadingAppcast]; } } - (void)didFinishLoadingAppcast:(SUAppcast *)appcast { - if (!self.aborted) { - if ([self.updaterDelegate respondsToSelector:@selector((updater:didFinishLoadingAppcast:))]) { - [self.updaterDelegate updater:self.updater didFinishLoadingAppcast:appcast]; + if (!_aborted) { + id updaterDelegate = _updaterDelegate; + if ([updaterDelegate respondsToSelector:@selector((updater:didFinishLoadingAppcast:))]) { + [updaterDelegate updater:_updater didFinishLoadingAppcast:appcast]; } [self notifyFinishLoadingAppcast]; } } -- (void)notifyFoundValidUpdateWithAppcastItem:(SUAppcastItem *)updateItem secondaryAppcastItem:(SUAppcastItem * _Nullable)secondaryUpdateItem systemDomain:(NSNumber * _Nullable)systemDomain resuming:(BOOL)resuming +- (void)notifyFoundValidUpdateWithAppcastItem:(SUAppcastItem *)updateItem secondaryAppcastItem:(SUAppcastItem * _Nullable)secondaryUpdateItem systemDomain:(NSNumber * _Nullable)systemDomain resuming:(BOOL)resuming SPU_OBJC_DIRECT { - if (!self.aborted) { + if (!_aborted) { + id delegate = _delegate; + id updaterDelegate = _updaterDelegate; + id updater = _updater; + if (!resuming) { +#if SPARKLE_BUILD_PACKAGE_SUPPORT // interactive pkg based updates are not supported under root user if ([updateItem.installationType isEqualToString:SPUInstallationTypeInteractivePackage] && geteuid() == 0) { - [self.delegate basicDriverIsRequestingAbortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationRootInteractiveError userInfo:@{ NSLocalizedDescriptionKey: SULocalizedString(@"Interactive based packages cannot be installed as the root user.", nil) }]]; + [delegate basicDriverIsRequestingAbortUpdateWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationRootInteractiveError userInfo:@{ NSLocalizedDescriptionKey: SULocalizedStringFromTableInBundle(@"Interactive based packages cannot be installed as the root user.", SPARKLE_TABLE, SUSparkleBundle(), nil) }]]; return; - } else { + } else +#endif + { // Give the delegate a chance to bail NSError *shouldNotProceedError = nil; - if ([self.updaterDelegate respondsToSelector:@selector(updater:shouldProceedWithUpdate:updateCheck:error:)] && ![self.updaterDelegate updater:self.updater shouldProceedWithUpdate:updateItem updateCheck:self.updateCheck error:&shouldNotProceedError]) { - [self.delegate basicDriverIsRequestingAbortUpdateWithError:shouldNotProceedError]; + if ([updaterDelegate respondsToSelector:@selector(updater:shouldProceedWithUpdate:updateCheck:error:)] && ![updaterDelegate updater:updater shouldProceedWithUpdate:updateItem updateCheck:_updateCheck error:&shouldNotProceedError]) { + [delegate basicDriverIsRequestingAbortUpdateWithError:shouldNotProceedError]; return; } } } [[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterDidFindValidUpdateNotification - object:self.updater + object:updater userInfo:@{ SUUpdaterAppcastItemNotificationKey: updateItem }]; - if ([self.updaterDelegate respondsToSelector:@selector((updater:didFindValidUpdate:))]) { - [self.updaterDelegate updater:self.updater didFindValidUpdate:updateItem]; + if ([updaterDelegate respondsToSelector:@selector((updater:didFindValidUpdate:))]) { + [updaterDelegate updater:updater didFindValidUpdate:updateItem]; } - [self.delegate basicDriverDidFindUpdateWithAppcastItem:updateItem secondaryAppcastItem:secondaryUpdateItem systemDomain:systemDomain]; + [delegate basicDriverDidFindUpdateWithAppcastItem:updateItem secondaryAppcastItem:secondaryUpdateItem systemDomain:systemDomain]; } } @@ -175,26 +182,30 @@ - (void)didNotFindUpdateWithLatestAppcastItem:(nullable SUAppcastItem *)latestAppcastItem hostToLatestAppcastItemComparisonResult:(NSComparisonResult)hostToLatestAppcastItemComparisonResult background:(BOOL)background { - if (!self.aborted) { + if (!_aborted) { NSString *localizedDescription; NSString *recoverySuggestion; +#if SPARKLE_COPY_LOCALIZATIONS + NSBundle *sparkleBundle = SUSparkleBundle(); +#endif + SPUNoUpdateFoundReason reason; if (latestAppcastItem != nil) { switch (hostToLatestAppcastItemComparisonResult) { case NSOrderedDescending: // This means the user is a 'newer than latest' version. give a slight hint to the user instead of wrongly claiming this version is identical to the latest feed version. - localizedDescription = SULocalizedString(@"You’re up-to-date!", "Status message shown when the user checks for updates but is already current or the feed doesn't contain any updates."); + localizedDescription = SULocalizedStringFromTableInBundle(@"You’re up-to-date!", SPARKLE_TABLE, sparkleBundle, "Status message shown when the user checks for updates but is already current or the feed doesn't contain any updates."); - recoverySuggestion = [NSString stringWithFormat:SULocalizedString(@"%@ %@ is currently the newest version available.\n(You are currently running version %@.)", nil), [self.host name], latestAppcastItem.displayVersionString, [self.host displayVersion]]; + recoverySuggestion = [NSString stringWithFormat:SULocalizedStringFromTableInBundle(@"%@ %@ is currently the newest version available.\n(You are currently running version %@.)", SPARKLE_TABLE, sparkleBundle, nil), [_host name], latestAppcastItem.displayVersionString, [_host displayVersion]]; reason = SPUNoUpdateFoundReasonOnNewerThanLatestVersion; break; case NSOrderedSame: // No new update is available and we're on the latest - localizedDescription = SULocalizedString(@"You’re up-to-date!", "Status message shown when the user checks for updates but is already current or the feed doesn't contain any updates."); + localizedDescription = SULocalizedStringFromTableInBundle(@"You’re up-to-date!", SPARKLE_TABLE, sparkleBundle, "Status message shown when the user checks for updates but is already current or the feed doesn't contain any updates."); - recoverySuggestion = [NSString stringWithFormat:SULocalizedString(@"%@ %@ is currently the newest version available.", nil), [self.host name], [self.host displayVersion]]; + recoverySuggestion = [NSString stringWithFormat:SULocalizedStringFromTableInBundle(@"%@ %@ is currently the newest version available.", SPARKLE_TABLE, sparkleBundle, nil), [_host name], [_host displayVersion]]; reason = SPUNoUpdateFoundReasonOnLatestVersion; break; @@ -202,22 +213,22 @@ // A new update is available but cannot be installed if (!latestAppcastItem.minimumOperatingSystemVersionIsOK) { - localizedDescription = SULocalizedString(@"Your macOS version is too old", nil); + localizedDescription = SULocalizedStringFromTableInBundle(@"Your macOS version is too old", SPARKLE_TABLE, sparkleBundle, nil); - recoverySuggestion = [NSString stringWithFormat:SULocalizedString(@"%1$@ %2$@ is available but your macOS version is too old to install it. At least macOS %3$@ is required.", nil), [self.host name], latestAppcastItem.displayVersionString, latestAppcastItem.minimumSystemVersion]; + recoverySuggestion = [NSString stringWithFormat:SULocalizedStringFromTableInBundle(@"%1$@ %2$@ is available but your macOS version is too old to install it. At least macOS %3$@ is required.", SPARKLE_TABLE, sparkleBundle, nil), [_host name], latestAppcastItem.displayVersionString, latestAppcastItem.minimumSystemVersion]; reason = SPUNoUpdateFoundReasonSystemIsTooOld; } else if (!latestAppcastItem.maximumOperatingSystemVersionIsOK) { - localizedDescription = SULocalizedString(@"Your macOS version is too new", nil); + localizedDescription = SULocalizedStringFromTableInBundle(@"Your macOS version is too new", SPARKLE_TABLE, sparkleBundle, nil); - recoverySuggestion = [NSString stringWithFormat:SULocalizedString(@"%1$@ %2$@ is available but your macOS version is too new for this update. This update only supports up to macOS %3$@.", nil), [self.host name], latestAppcastItem.displayVersionString, latestAppcastItem.maximumSystemVersion]; + recoverySuggestion = [NSString stringWithFormat:SULocalizedStringFromTableInBundle(@"%1$@ %2$@ is available but your macOS version is too new for this update. This update only supports up to macOS %3$@.", SPARKLE_TABLE, sparkleBundle, nil), [_host name], latestAppcastItem.displayVersionString, latestAppcastItem.maximumSystemVersion]; reason = SPUNoUpdateFoundReasonSystemIsTooNew; } else { // We shouldn't realistically get here - localizedDescription = SULocalizedString(@"You’re up-to-date!", "Status message shown when the user checks for updates but is already current or the feed doesn't contain any updates."); + localizedDescription = SULocalizedStringFromTableInBundle(@"You’re up-to-date!", SPARKLE_TABLE, sparkleBundle, "Status message shown when the user checks for updates but is already current or the feed doesn't contain any updates."); - recoverySuggestion = [NSString stringWithFormat:SULocalizedString(@"%@ %@ is currently the newest version available.", nil), [self.host name], [self.host displayVersion]]; + recoverySuggestion = [NSString stringWithFormat:SULocalizedStringFromTableInBundle(@"%@ %@ is currently the newest version available.", SPARKLE_TABLE, sparkleBundle, nil), [_host name], [_host displayVersion]]; reason = SPUNoUpdateFoundReasonUnknown; } @@ -228,13 +239,13 @@ // We will need to assume the user is up to date if the feed doen't have any applicable update items // There could be update items on channels the updater is not subscribed to for example. But we can't tell the user about them. // There could also only be update items available for other platforms or none at all. - localizedDescription = SULocalizedString(@"You’re up-to-date!", "Status message shown when the user checks for updates but is already current or the feed doesn't contain any updates."); - recoverySuggestion = [NSString stringWithFormat:SULocalizedString(@"%@ %@ is currently the newest version available.", nil), [self.host name], [self.host displayVersion]]; + localizedDescription = SULocalizedStringFromTableInBundle(@"You’re up-to-date!", SPARKLE_TABLE, sparkleBundle, "Status message shown when the user checks for updates but is already current or the feed doesn't contain any updates."); + recoverySuggestion = [NSString stringWithFormat:SULocalizedStringFromTableInBundle(@"%@ %@ is currently the newest version available.", SPARKLE_TABLE, sparkleBundle, nil), [_host name], [_host displayVersion]]; reason = SPUNoUpdateFoundReasonOnLatestVersion; } - NSString *recoveryOption = SULocalizedString(@"OK", nil); + NSString *recoveryOption = SULocalizedStringFromTableInBundle(@"OK", SPARKLE_TABLE, sparkleBundle, nil); NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:@{ @@ -255,26 +266,31 @@ code:SUNoUpdateError userInfo:[userInfo copy]]; - if ([self.updaterDelegate respondsToSelector:@selector((updaterDidNotFindUpdate:error:))]) { - [self.updaterDelegate updaterDidNotFindUpdate:self.updater error:notFoundError]; - } else if ([self.updaterDelegate respondsToSelector:@selector((updaterDidNotFindUpdate:))]) { - [self.updaterDelegate updaterDidNotFindUpdate:self.updater]; + id updaterDelegate = _updaterDelegate; + id updater = _updater; + + if (updater != nil) { + if ([updaterDelegate respondsToSelector:@selector((updaterDidNotFindUpdate:error:))]) { + [updaterDelegate updaterDidNotFindUpdate:updater error:notFoundError]; + } else if ([updaterDelegate respondsToSelector:@selector((updaterDidNotFindUpdate:))]) { + [updaterDelegate updaterDidNotFindUpdate:updater]; + } + + [[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterDidNotFindUpdateNotification object:updater userInfo:userInfo]; } - [[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterDidNotFindUpdateNotification object:self.updater userInfo:userInfo]; - - [self.delegate basicDriverIsRequestingAbortUpdateWithError:notFoundError]; + [_delegate basicDriverIsRequestingAbortUpdateWithError:notFoundError]; } } - (void)abortUpdateAndShowNextUpdateImmediately:(BOOL)shouldShowUpdateImmediately resumableUpdate:(id _Nullable)resumableUpdate error:(nullable NSError *)error { - self.aborted = YES; + _aborted = YES; - [self.appcastDriver cleanup:^{ - if (self.completionBlock != nil) { - self.completionBlock(shouldShowUpdateImmediately, resumableUpdate, error); - self.completionBlock = nil; + [_appcastDriver cleanup:^{ + if (self->_completionBlock != nil) { + self->_completionBlock(shouldShowUpdateImmediately, resumableUpdate, error); + self->_completionBlock = nil; } }]; } diff --git a/Sparkle/SPUCoreBasedUpdateDriver.h b/Sparkle/SPUCoreBasedUpdateDriver.h index 29d27e28..4c1f2a99 100644 --- a/Sparkle/SPUCoreBasedUpdateDriver.h +++ b/Sparkle/SPUCoreBasedUpdateDriver.h @@ -46,7 +46,7 @@ NS_ASSUME_NONNULL_BEGIN @end -@interface SPUCoreBasedUpdateDriver : NSObject +SPU_OBJC_DIRECT_MEMBERS @interface SPUCoreBasedUpdateDriver : NSObject - (instancetype)initWithHost:(SUHost *)host applicationBundle:(NSBundle *)applicationBundle updateCheck:(SPUUpdateCheck)updateCheck updater:(id)updater updaterDelegate:(nullable id )updaterDelegate delegate:(id)delegate; diff --git a/Sparkle/SPUCoreBasedUpdateDriver.m b/Sparkle/SPUCoreBasedUpdateDriver.m index decadd46..3373773d 100644 --- a/Sparkle/SPUCoreBasedUpdateDriver.m +++ b/Sparkle/SPUCoreBasedUpdateDriver.m @@ -27,43 +27,28 @@ #include "AppKitPrevention.h" @interface SPUCoreBasedUpdateDriver () - -@property (nonatomic, readonly) SPUBasicUpdateDriver *basicDriver; -@property (nonatomic) SPUDownloadDriver *downloadDriver; -@property (nonatomic, readonly) SPUInstallerDriver *installerDriver; -@property (nonatomic, weak, readonly) id delegate; -@property (nonatomic) SUAppcastItem *updateItem; -@property (nonatomic, nullable) SUAppcastItem *secondaryUpdateItem; -@property (nonatomic) id resumableUpdate; -@property (nonatomic) SPUDownloadedUpdate *downloadedUpdateForRemoval; - -@property (nonatomic, readonly) SUHost *host; -@property (nonatomic) BOOL resumingInstallingUpdate; -@property (nonatomic) BOOL silentInstall; -@property (nonatomic, readonly, weak) id updater; // if we didn't have legacy support, I'd remove this.. -@property (nullable, nonatomic, readonly, weak) id updaterDelegate; -@property (nonatomic) NSString *userAgent; -@property (nonatomic, nullable) NSDictionary *httpHeaders; - @end @implementation SPUCoreBasedUpdateDriver - -@synthesize basicDriver = _basicDriver; -@synthesize downloadDriver = _downloadDriver; -@synthesize installerDriver = _installerDriver; -@synthesize delegate = _delegate; -@synthesize updateItem = _updateItem; -@synthesize secondaryUpdateItem = _secondaryUpdateItem; -@synthesize host = _host; -@synthesize resumingInstallingUpdate = _resumingInstallingUpdate; -@synthesize silentInstall = _silentInstall; -@synthesize updater = _updater; -@synthesize updaterDelegate = _updaterDelegate; -@synthesize userAgent = _userAgent; -@synthesize httpHeaders = _httpHeaders; -@synthesize resumableUpdate = _resumableUpdate; -@synthesize downloadedUpdateForRemoval = _downloadedUpdateForRemoval; +{ + SPUBasicUpdateDriver *_basicDriver; + SPUDownloadDriver *_downloadDriver; + SPUInstallerDriver *_installerDriver; + SUAppcastItem *_updateItem; + SUAppcastItem * _Nullable _secondaryUpdateItem; + id _resumableUpdate; + SPUDownloadedUpdate *_downloadedUpdateForRemoval; + SUHost *_host; + NSString *_userAgent; + NSDictionary * _Nullable _httpHeaders; + + __weak id _updater; // if we didn't have legacy support, I'd remove this.. + __weak id _updaterDelegate; + __weak id _delegate; + + BOOL _resumingInstallingUpdate; + BOOL _silentInstall; +} - (instancetype)initWithHost:(SUHost *)host applicationBundle:(NSBundle *)applicationBundle updateCheck:(SPUUpdateCheck)updateCheck updater:(id)updater updaterDelegate:(nullable id )updaterDelegate delegate:(id)delegate { @@ -86,90 +71,95 @@ - (void)setCompletionHandler:(SPUUpdateDriverCompletion)completionBlock { - [self.basicDriver setCompletionHandler:completionBlock]; + [_basicDriver setCompletionHandler:completionBlock]; } - (void)setUpdateWillInstallHandler:(void (^)(void))updateWillInstallHandler { - [self.installerDriver setUpdateWillInstallHandler:updateWillInstallHandler]; + [_installerDriver setUpdateWillInstallHandler:updateWillInstallHandler]; } - (void)checkForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders inBackground:(BOOL)background requiresSilentInstall:(BOOL)silentInstall { - self.userAgent = userAgent; - self.httpHeaders = httpHeaders; - self.silentInstall = silentInstall; + _userAgent = [userAgent copy]; + _httpHeaders = httpHeaders; + _silentInstall = silentInstall; - [self.basicDriver checkForUpdatesAtAppcastURL:appcastURL withUserAgent:userAgent httpHeaders:httpHeaders inBackground:background]; + [_basicDriver checkForUpdatesAtAppcastURL:appcastURL withUserAgent:userAgent httpHeaders:httpHeaders inBackground:background]; } - (void)resumeInstallingUpdate { - self.resumingInstallingUpdate = YES; - self.silentInstall = NO; + _resumingInstallingUpdate = YES; + _silentInstall = NO; - [self.basicDriver resumeInstallingUpdate]; + [_basicDriver resumeInstallingUpdate]; } - (void)resumeUpdate:(id)resumableUpdate { - self.resumableUpdate = resumableUpdate; - self.silentInstall = NO; + _resumableUpdate = resumableUpdate; + _silentInstall = NO; - [self.basicDriver resumeUpdate:resumableUpdate]; + [_basicDriver resumeUpdate:resumableUpdate]; } - (void)basicDriverDidFinishLoadingAppcast { - if ([self.delegate respondsToSelector:@selector(basicDriverDidFinishLoadingAppcast)]) { - [self.delegate basicDriverDidFinishLoadingAppcast]; + id delegate = _delegate; + if ([delegate respondsToSelector:@selector(basicDriverDidFinishLoadingAppcast)]) { + [delegate basicDriverDidFinishLoadingAppcast]; } } - (void)basicDriverDidFindUpdateWithAppcastItem:(SUAppcastItem *)updateItem secondaryAppcastItem:(SUAppcastItem * _Nullable)secondaryUpdateItem systemDomain:(NSNumber * _Nullable)systemDomain { - self.updateItem = updateItem; - self.secondaryUpdateItem = secondaryUpdateItem; + _updateItem = updateItem; + _secondaryUpdateItem = secondaryUpdateItem; - if (self.resumingInstallingUpdate) { + if (_resumingInstallingUpdate) { assert(systemDomain != nil); - [self.installerDriver resumeInstallingUpdateWithUpdateItem:updateItem systemDomain:systemDomain.boolValue]; + [_installerDriver resumeInstallingUpdateWithUpdateItem:updateItem systemDomain:systemDomain.boolValue]; } - [self.delegate basicDriverDidFindUpdateWithAppcastItem:updateItem secondaryAppcastItem:secondaryUpdateItem]; + [_delegate basicDriverDidFindUpdateWithAppcastItem:updateItem secondaryAppcastItem:secondaryUpdateItem]; } -- (void)downloadUpdateFromAppcastItem:(SUAppcastItem *)updateItem secondaryAppcastItem:(SUAppcastItem * _Nullable)secondaryUpdateItem inBackground:(BOOL)background +- (void)downloadUpdateFromAppcastItem:(SUAppcastItem *)updateItem secondaryAppcastItem:(SUAppcastItem * _Nullable)secondaryUpdateItem inBackground:(BOOL)background SPU_OBJC_DIRECT { - self.downloadDriver = [[SPUDownloadDriver alloc] initWithUpdateItem:updateItem secondaryUpdateItem:secondaryUpdateItem host:self.host userAgent:self.userAgent httpHeaders:self.httpHeaders inBackground:background delegate:self]; + _downloadDriver = [[SPUDownloadDriver alloc] initWithUpdateItem:updateItem secondaryUpdateItem:secondaryUpdateItem host:_host userAgent:_userAgent httpHeaders:_httpHeaders inBackground:background delegate:self]; - if ([self.updaterDelegate respondsToSelector:@selector((updater:willDownloadUpdate:withRequest:))]) { - [self.updaterDelegate updater:self.updater - willDownloadUpdate:updateItem - withRequest:self.downloadDriver.request]; + id updater = _updater; + id updaterDelegate = _updaterDelegate; + + if (updater != nil && [updaterDelegate respondsToSelector:@selector((updater:willDownloadUpdate:withRequest:))]) { + [updaterDelegate updater:updater willDownloadUpdate:updateItem withRequest:_downloadDriver.request]; } - [self.downloadDriver downloadFile]; + [_downloadDriver downloadFile]; } - (void)downloadDriverWillBeginDownload { - if ([self.delegate respondsToSelector:@selector(downloadDriverWillBeginDownload)]) { - [self.delegate downloadDriverWillBeginDownload]; + id delegate = _delegate; + if ([delegate respondsToSelector:@selector(downloadDriverWillBeginDownload)]) { + [delegate downloadDriverWillBeginDownload]; } } - (void)downloadDriverDidReceiveExpectedContentLength:(uint64_t)expectedContentLength { - if ([self.delegate respondsToSelector:@selector(downloadDriverDidReceiveExpectedContentLength:)]) { - [self.delegate downloadDriverDidReceiveExpectedContentLength:expectedContentLength]; + id delegate = _delegate; + if ([delegate respondsToSelector:@selector(downloadDriverDidReceiveExpectedContentLength:)]) { + [delegate downloadDriverDidReceiveExpectedContentLength:expectedContentLength]; } } - (void)downloadDriverDidReceiveDataOfLength:(uint64_t)length { - if ([self.delegate respondsToSelector:@selector(downloadDriverDidReceiveDataOfLength:)]) { - [self.delegate downloadDriverDidReceiveDataOfLength:length]; + id delegate = _delegate; + if ([delegate respondsToSelector:@selector(downloadDriverDidReceiveDataOfLength:)]) { + [delegate downloadDriverDidReceiveDataOfLength:length]; } } @@ -179,73 +169,80 @@ // We could restrict this to when the appcast was downloaded in the background, // but it shouldn't matter. if (downloadedUpdate.updateItem.phasedRolloutInterval != nil) { - [SUPhasedUpdateGroupInfo setNewUpdateGroupIdentifierForHost:self.host]; + [SUPhasedUpdateGroupInfo setNewUpdateGroupIdentifierForHost:_host]; } - if ([self.updaterDelegate respondsToSelector:@selector(updater:didDownloadUpdate:)]) { - [self.updaterDelegate updater:self.updater didDownloadUpdate:self.updateItem]; + id updater = _updater; + id updaterDelegate = _updaterDelegate; + + if (updater != nil && [updaterDelegate respondsToSelector:@selector(updater:didDownloadUpdate:)]) { + [updaterDelegate updater:updater didDownloadUpdate:_updateItem]; } - self.resumableUpdate = downloadedUpdate; + _resumableUpdate = downloadedUpdate; [self extractUpdate:downloadedUpdate]; } - (void)deferInformationalUpdate:(SUAppcastItem *)updateItem secondaryUpdate:(SUAppcastItem * _Nullable)secondaryUpdateItem { - self.resumableUpdate = [[SPUInformationalUpdate alloc] initWithAppcastItem:updateItem secondaryAppcastItem:secondaryUpdateItem]; + _resumableUpdate = [[SPUInformationalUpdate alloc] initWithAppcastItem:updateItem secondaryAppcastItem:secondaryUpdateItem]; } - (void)extractDownloadedUpdate { - assert(self.resumableUpdate != nil); - [self extractUpdate:self.resumableUpdate]; + assert(_resumableUpdate != nil); + [self extractUpdate:_resumableUpdate]; } - (void)clearDownloadedUpdate { - id downloadedUpdateObject = (self.resumableUpdate != nil) ? self.resumableUpdate : self.downloadedUpdateForRemoval; + id downloadedUpdateObject = (_resumableUpdate != nil) ? _resumableUpdate : _downloadedUpdateForRemoval; assert(downloadedUpdateObject != nil); if (downloadedUpdateObject != nil && [downloadedUpdateObject isKindOfClass:[SPUDownloadedUpdate class]]) { - if (self.downloadDriver == nil) { - self.downloadDriver = [[SPUDownloadDriver alloc] initWithHost:self.host]; + if (_downloadDriver == nil) { + _downloadDriver = [[SPUDownloadDriver alloc] initWithHost:_host]; } SPUDownloadedUpdate *downloadedUpdate = (SPUDownloadedUpdate *)downloadedUpdateObject; - [self.downloadDriver removeDownloadedUpdate:downloadedUpdate]; + [_downloadDriver removeDownloadedUpdate:downloadedUpdate]; } // Clear any type of resumable update - self.resumableUpdate = nil; + _resumableUpdate = nil; } -- (void)extractUpdate:(SPUDownloadedUpdate *)downloadedUpdate +- (void)extractUpdate:(SPUDownloadedUpdate *)downloadedUpdate SPU_OBJC_DIRECT { - if ([self.updaterDelegate respondsToSelector:@selector(updater:willExtractUpdate:)]) { - [self.updaterDelegate updater:self.updater willExtractUpdate:self.updateItem]; + id updater = _updater; + id updaterDelegate = _updaterDelegate; + + if (updater != nil && [updaterDelegate respondsToSelector:@selector(updater:willExtractUpdate:)]) { + [updaterDelegate updater:updater willExtractUpdate:_updateItem]; } // Now we have to extract the downloaded archive. - if ([self.delegate respondsToSelector:@selector(coreDriverDidStartExtractingUpdate)]) { - [self.delegate coreDriverDidStartExtractingUpdate]; + id delegate = _delegate; + if ([delegate respondsToSelector:@selector(coreDriverDidStartExtractingUpdate)]) { + [delegate coreDriverDidStartExtractingUpdate]; } - [self.installerDriver extractDownloadedUpdate:downloadedUpdate silently:self.silentInstall completion:^(NSError * _Nullable error) { + [_installerDriver extractDownloadedUpdate:downloadedUpdate silently:_silentInstall completion:^(NSError * _Nullable error) { if (error != nil) { if (error.code != SUInstallationAuthorizeLaterError) { [self clearDownloadedUpdate]; } - [self.delegate coreDriverIsRequestingAbortUpdateWithError:error]; + [self->_delegate coreDriverIsRequestingAbortUpdateWithError:error]; } else { // If the installer started properly, we can't use the downloaded update archive anymore // Especially if the installer fails later and we try resuming the update with a missing archive file // We must clear the download after the installer begins using it however (in -installerDidStartInstalling) - self.downloadedUpdateForRemoval = downloadedUpdate; - self.resumableUpdate = nil; + self->_downloadedUpdateForRemoval = downloadedUpdate; + self->_resumableUpdate = nil; - if ([self.updaterDelegate respondsToSelector:@selector(updater:didExtractUpdate:)]) { - [self.updaterDelegate updater:self.updater didExtractUpdate:self.updateItem]; + if (updater != nil && [updaterDelegate respondsToSelector:@selector(updater:didExtractUpdate:)]) { + [updaterDelegate updater:updater didExtractUpdate:self->_updateItem]; } } }]; @@ -253,31 +250,33 @@ - (void)downloadDriverDidFailToDownloadFileWithError:(NSError *)error { - if ([self.updateItem isDeltaUpdate]) { + if ([_updateItem isDeltaUpdate]) { SULog(SULogLevelError, @"Failed to download delta update. Falling back to regular update..."); SULogError(error); [self fallBackAndDownloadRegularUpdate]; } else { - if ([self.updaterDelegate respondsToSelector:@selector((updater:failedToDownloadUpdate:error:))]) { + id updater = _updater; + id updaterDelegate = _updaterDelegate; + + if (updater != nil && [updaterDelegate respondsToSelector:@selector((updater:failedToDownloadUpdate:error:))]) { NSError *errorToReport = [error.userInfo objectForKey:NSUnderlyingErrorKey]; if (errorToReport == nil) { errorToReport = error; } - [self.updaterDelegate updater:self.updater - failedToDownloadUpdate:self.updateItem - error:errorToReport]; + [updaterDelegate updater:updater failedToDownloadUpdate:_updateItem error:errorToReport]; } - [self.delegate coreDriverIsRequestingAbortUpdateWithError:error]; + [_delegate coreDriverIsRequestingAbortUpdateWithError:error]; } } - (void)installerDidStartInstallingWithApplicationTerminated:(BOOL)applicationTerminated { - if ([self.delegate respondsToSelector:@selector(installerDidStartInstallingWithApplicationTerminated:)]) { - [self.delegate installerDidStartInstallingWithApplicationTerminated:applicationTerminated]; + id delegate = _delegate; + if ([delegate respondsToSelector:@selector(installerDidStartInstallingWithApplicationTerminated:)]) { + [delegate installerDidStartInstallingWithApplicationTerminated:applicationTerminated]; } } @@ -289,49 +288,56 @@ - (void)installerDidExtractUpdateWithProgress:(double)progress { - if ([self.delegate respondsToSelector:@selector(installerDidExtractUpdateWithProgress:)]) { - [self.delegate installerDidExtractUpdateWithProgress:progress]; + id delegate = _delegate; + if ([delegate respondsToSelector:@selector(installerDidExtractUpdateWithProgress:)]) { + [delegate installerDidExtractUpdateWithProgress:progress]; } } - (void)installerDidFinishPreparationAndWillInstallImmediately:(BOOL)willInstallImmediately silently:(BOOL)willInstallSilently { - [self.delegate installerDidFinishPreparationAndWillInstallImmediately:willInstallImmediately silently:willInstallSilently]; + [_delegate installerDidFinishPreparationAndWillInstallImmediately:willInstallImmediately silently:willInstallSilently]; } - (void)finishInstallationWithResponse:(SPUUserUpdateChoice)response displayingUserInterface:(BOOL)displayingUserInterface { switch (response) { case SPUUserUpdateChoiceDismiss: - [self.delegate coreDriverIsRequestingAbortUpdateWithError:nil]; + [_delegate coreDriverIsRequestingAbortUpdateWithError:nil]; break; case SPUUserUpdateChoiceSkip: - [self.installerDriver cancelUpdate]; + [_installerDriver cancelUpdate]; break; case SPUUserUpdateChoiceInstall: - [self.installerDriver installWithToolAndRelaunch:YES displayingUserInterface:displayingUserInterface]; + [_installerDriver installWithToolAndRelaunch:YES displayingUserInterface:displayingUserInterface]; break; } } - (void)installerWillFinishInstallationAndRelaunch:(BOOL)relaunch { - if ([self.updaterDelegate respondsToSelector:@selector((updater:willInstallUpdate:))]) { - [self.updaterDelegate updater:self.updater willInstallUpdate:self.updateItem]; - } + id updater = _updater; + id updaterDelegate = _updaterDelegate; - if (relaunch) { - [[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterWillRestartNotification object:self]; - if ([self.updaterDelegate respondsToSelector:@selector((updaterWillRelaunchApplication:))]) { - [self.updaterDelegate updaterWillRelaunchApplication:self.updater]; + if (updater != nil) { + if ([updaterDelegate respondsToSelector:@selector((updater:willInstallUpdate:))]) { + [updaterDelegate updater:updater willInstallUpdate:_updateItem]; + } + + if (relaunch) { + [[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterWillRestartNotification object:updater]; + if ([updaterDelegate respondsToSelector:@selector((updaterWillRelaunchApplication:))]) { + [updaterDelegate updaterWillRelaunchApplication:updater]; + } } } } - (void)installerDidFinishInstallationAndRelaunched:(BOOL)relaunched acknowledgement:(void(^)(void))acknowledgement { - if ([self.delegate respondsToSelector:@selector(installerDidFinishInstallationAndRelaunched:acknowledgement:)]) { - [self.delegate installerDidFinishInstallationAndRelaunched:relaunched acknowledgement:acknowledgement]; + id delegate = _delegate; + if ([delegate respondsToSelector:@selector(installerDidFinishInstallationAndRelaunched:acknowledgement:)]) { + [delegate installerDidFinishInstallationAndRelaunched:relaunched acknowledgement:acknowledgement]; } else { acknowledgement(); } @@ -339,25 +345,25 @@ - (void)installerIsRequestingAbortInstallWithError:(nullable NSError *)error { - [self.delegate coreDriverIsRequestingAbortUpdateWithError:error]; + [_delegate coreDriverIsRequestingAbortUpdateWithError:error]; } - (void)basicDriverIsRequestingAbortUpdateWithError:(nullable NSError *)error { // A delegate may want to handle this type of error specially - [self.delegate basicDriverIsRequestingAbortUpdateWithError:error]; + [_delegate basicDriverIsRequestingAbortUpdateWithError:error]; } -- (void)fallBackAndDownloadRegularUpdate +- (void)fallBackAndDownloadRegularUpdate SPU_OBJC_DIRECT { - SUAppcastItem *secondaryUpdateItem = self.secondaryUpdateItem; + SUAppcastItem *secondaryUpdateItem = _secondaryUpdateItem; assert(secondaryUpdateItem != nil); - BOOL backgroundDownload = self.downloadDriver.inBackground; + BOOL backgroundDownload = _downloadDriver.inBackground; // Fall back to the non-delta update. Note that we don't want to trigger another update was found event. - self.updateItem = secondaryUpdateItem; - self.secondaryUpdateItem = nil; + _updateItem = secondaryUpdateItem; + _secondaryUpdateItem = nil; [self downloadUpdateFromAppcastItem:secondaryUpdateItem secondaryAppcastItem:nil inBackground:backgroundDownload]; } @@ -371,16 +377,16 @@ - (void)abortUpdateAndShowNextUpdateImmediately:(BOOL)shouldShowUpdateImmediately error:(nullable NSError *)error { - [self.installerDriver abortInstall]; + [_installerDriver abortInstall]; void (^basicDriverAbort)(void) = ^{ - id resumableUpdate = (error == nil || error.code == SUInstallationAuthorizeLaterError) ? self.resumableUpdate : nil; + id resumableUpdate = (error == nil || error.code == SUInstallationAuthorizeLaterError) ? self->_resumableUpdate : nil; - [self.basicDriver abortUpdateAndShowNextUpdateImmediately:shouldShowUpdateImmediately resumableUpdate:resumableUpdate error:error]; + [self->_basicDriver abortUpdateAndShowNextUpdateImmediately:shouldShowUpdateImmediately resumableUpdate:resumableUpdate error:error]; }; - if (self.downloadDriver != nil) { - [self.downloadDriver cleanup:^{ + if (_downloadDriver != nil) { + [_downloadDriver cleanup:^{ basicDriverAbort(); }]; } else { diff --git a/Sparkle/SPUDownloadData.h b/Sparkle/SPUDownloadData.h index 680b3989..d33ab011 100644 --- a/Sparkle/SPUDownloadData.h +++ b/Sparkle/SPUDownloadData.h @@ -8,7 +8,7 @@ #import -#ifdef BUILDING_SPARKLE_DOWNLOADER_SERVICE +#if defined(BUILDING_SPARKLE_SOURCES_EXTERNALLY) // Ignore incorrect warning #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wquoted-include-in-framework-header" diff --git a/Sparkle/SPUDownloadData.m b/Sparkle/SPUDownloadData.m index 7b5edc80..13fe6b56 100644 --- a/Sparkle/SPUDownloadData.m +++ b/Sparkle/SPUDownloadData.m @@ -42,15 +42,15 @@ static NSString *SPUDownloadMIMETypeKey = @"SPUDownloadMIMEType"; - (void)encodeWithCoder:(NSCoder *)coder { - [coder encodeObject:self.data forKey:SPUDownloadDataKey]; - [coder encodeObject:self.URL forKey:SPUDownloadURLKey]; + [coder encodeObject:_data forKey:SPUDownloadDataKey]; + [coder encodeObject:_URL forKey:SPUDownloadURLKey]; - if (self.textEncodingName != nil) { - [coder encodeObject:self.textEncodingName forKey:SPUDownloadTextEncodingKey]; + if (_textEncodingName != nil) { + [coder encodeObject:_textEncodingName forKey:SPUDownloadTextEncodingKey]; } - if (self.MIMEType != nil) { - [coder encodeObject:self.MIMEType forKey:SPUDownloadMIMETypeKey]; + if (_MIMEType != nil) { + [coder encodeObject:_MIMEType forKey:SPUDownloadMIMETypeKey]; } } diff --git a/Sparkle/SPUDownloadDriver.h b/Sparkle/SPUDownloadDriver.h index 449f4151..ef252402 100644 --- a/Sparkle/SPUDownloadDriver.h +++ b/Sparkle/SPUDownloadDriver.h @@ -34,6 +34,9 @@ NS_ASSUME_NONNULL_BEGIN @end +#ifndef BUILDING_SPARKLE_TESTS +SPU_OBJC_DIRECT_MEMBERS +#endif @interface SPUDownloadDriver : NSObject - (instancetype)initWithRequestURL:(NSURL *)requestURL host:(SUHost *)host userAgent:(NSString * _Nullable)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders inBackground:(BOOL)background delegate:(id)delegate; diff --git a/Sparkle/SPUDownloadDriver.m b/Sparkle/SPUDownloadDriver.m index 893fc118..03f25e00 100644 --- a/Sparkle/SPUDownloadDriver.m +++ b/Sparkle/SPUDownloadDriver.m @@ -18,41 +18,36 @@ #import "SUErrors.h" #import "SPUDownloadedUpdate.h" #import "SPUDownloadData.h" +#import "SUConstants.h" #include "AppKitPrevention.h" @interface SPUDownloadDriver () - -@property (nonatomic) id downloader; -@property (nonatomic) NSXPCConnection *connection; -@property (nonatomic, readonly) SUAppcastItem *updateItem; -@property (nonatomic, readonly, nullable) SUAppcastItem *secondaryUpdateItem; -@property (nonatomic, readonly) SUHost *host; -@property (nonatomic, copy) NSString *temporaryDirectory; -@property (nonatomic, copy) NSString *downloadName; -@property (nonatomic, weak) id delegate; -@property (nonatomic) BOOL retrievedDownloadResult; -@property (nonatomic) uint64_t expectedContentLength; -@property (nonatomic) BOOL cleaningUp; - @end @implementation SPUDownloadDriver +{ + id _downloader; +#if DOWNLOADER_XPC_SERVICE_EMBEDDED + NSXPCConnection *_connection; +#endif + SUAppcastItem *_updateItem; + SUAppcastItem * _Nullable _secondaryUpdateItem; + SUHost *_host; + NSString *_temporaryDirectory; + NSString *_downloadName; + + __weak id _delegate; + + uint64_t _expectedContentLength; + + BOOL _retrievedDownloadResult; + BOOL _cleaningUp; +} -@synthesize downloader = _downloader; -@synthesize connection = _connection; -@synthesize updateItem = _updateItem; -@synthesize secondaryUpdateItem = _secondaryUpdateItem; @synthesize request = _request; @synthesize inBackground = _inBackground; -@synthesize host = _host; -@synthesize temporaryDirectory = _temporaryDirectory; -@synthesize downloadName = _downloadName; -@synthesize delegate = _delegate; -@synthesize retrievedDownloadResult = _retrievedDownloadResult; -@synthesize expectedContentLength = _expectedContentLength; -@synthesize cleaningUp = _cleaningUp; - (instancetype)initWithHost:(SUHost *)host { @@ -60,9 +55,8 @@ if (self != nil) { _host = host; - if (!SPUXPCServiceIsEnabled(SUEnableDownloaderServiceKey)) { - _downloader = [[SPUDownloader alloc] initWithDelegate:self]; - } else { +#if DOWNLOADER_XPC_SERVICE_EMBEDDED + if (SPUXPCServiceIsEnabled(SUEnableDownloaderServiceKey)) { _connection = [[NSXPCConnection alloc] initWithServiceName:@DOWNLOADER_BUNDLE_ID]; _connection.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SPUDownloaderProtocol)]; _connection.exportedInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SPUDownloaderDelegate)]; @@ -70,38 +64,42 @@ _downloader = _connection.remoteObjectProxy; - __weak SPUDownloadDriver *weakSelf = self; + __weak __typeof__(self) weakSelf = self; _connection.interruptionHandler = ^{ dispatch_async(dispatch_get_main_queue(), ^{ - SPUDownloadDriver *strongSelf = weakSelf; - if (strongSelf != nil && !strongSelf.retrievedDownloadResult) { - [strongSelf.connection invalidate]; + __typeof__(self) strongSelf = weakSelf; + if (strongSelf != nil && !strongSelf->_retrievedDownloadResult) { + [strongSelf->_connection invalidate]; } }); }; _connection.invalidationHandler = ^{ dispatch_async(dispatch_get_main_queue(), ^{ - SPUDownloadDriver *strongSelf = weakSelf; - if (strongSelf != nil && !strongSelf.retrievedDownloadResult && !strongSelf.cleaningUp) { - strongSelf.downloader = nil; + __typeof__(self) strongSelf = weakSelf; + if (strongSelf != nil && !strongSelf->_retrievedDownloadResult && !strongSelf->_cleaningUp) { + strongSelf->_downloader = nil; SULog(SULogLevelError, @"Connection to update downloader was invalidated"); NSDictionary *userInfo = @{ - NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while downloading the update. Please try again later.", nil), + NSLocalizedDescriptionKey: SULocalizedStringFromTableInBundle(@"An error occurred while downloading the update. Please try again later.", SPARKLE_TABLE, SUSparkleBundle(), nil), }; NSError *downloadError = [NSError errorWithDomain:SUSparkleErrorDomain code:SUDownloadError userInfo:userInfo]; - [strongSelf.delegate downloadDriverDidFailToDownloadFileWithError:downloadError]; + [strongSelf->_delegate downloadDriverDidFailToDownloadFileWithError:downloadError]; } }); }; [_connection resume]; + } else +#endif + { + _downloader = [[SPUDownloader alloc] initWithDelegate:self]; } } return self; @@ -149,54 +147,57 @@ - (void)downloadFile { - if ([self.delegate respondsToSelector:@selector(downloadDriverWillBeginDownload)]) { - [self.delegate downloadDriverWillBeginDownload]; + id delegate = _delegate; + if ([delegate respondsToSelector:@selector(downloadDriverWillBeginDownload)]) { + [delegate downloadDriverWillBeginDownload]; } - if (self.updateItem != nil) { - NSString *desiredFilename = [NSString stringWithFormat:@"%@ %@", [self.host name], [self.updateItem versionString]]; + if (_updateItem != nil) { + NSString *desiredFilename = [NSString stringWithFormat:@"%@ %@", [_host name], [_updateItem versionString]]; - NSString *bundleIdentifier = self.host.bundle.bundleIdentifier; + NSString *bundleIdentifier = _host.bundle.bundleIdentifier; assert(bundleIdentifier != nil); - [self.downloader startPersistentDownloadWithRequest:self.request bundleIdentifier:bundleIdentifier desiredFilename:desiredFilename]; + [_downloader startPersistentDownloadWithRequest:_request bundleIdentifier:bundleIdentifier desiredFilename:desiredFilename]; } else { - [self.downloader startTemporaryDownloadWithRequest:self.request]; + [_downloader startTemporaryDownloadWithRequest:_request]; } } - (void)removeDownloadedUpdate:(SPUDownloadedUpdate *)downloadedUpdate { - NSString *bundleIdentifier = self.host.bundle.bundleIdentifier; + NSString *bundleIdentifier = _host.bundle.bundleIdentifier; assert(bundleIdentifier != nil); if (bundleIdentifier != nil) { // Grab eg "0bCSun8tj" from org.sparkle-project.Sparkle/PersistentDownloads/0bCSun8tj/Sparkle Test App 2.0/ NSString *tempDirectoryName = downloadedUpdate.temporaryDirectory.stringByDeletingLastPathComponent.lastPathComponent; - [self.downloader removeDownloadDirectory:tempDirectoryName bundleIdentifier:bundleIdentifier]; + [_downloader removeDownloadDirectory:tempDirectoryName bundleIdentifier:bundleIdentifier]; } } - (void)cleanup:(void (^)(void))completionHandler { void (^cleanupBlock)(void) = ^{ - self.cleaningUp = YES; + self->_cleaningUp = YES; - if (self.connection != nil) { - [self.connection invalidate]; - self.connection = nil; +#if DOWNLOADER_XPC_SERVICE_EMBEDDED + if (self->_connection != nil) { + [self->_connection invalidate]; + self->_connection = nil; } - self.downloadName = nil; - self.downloader = nil; +#endif + self->_downloadName = nil; + self->_downloader = nil; completionHandler(); }; - if (self.downloader == nil) { + if (_downloader == nil) { cleanupBlock(); } else { - [self.downloader cleanup:^{ + [_downloader cleanup:^{ dispatch_async(dispatch_get_main_queue(), ^{ cleanupBlock(); }); @@ -207,23 +208,24 @@ - (void)downloaderDidFinishWithTemporaryDownloadData:(SPUDownloadData * _Nullable)downloadData { dispatch_async(dispatch_get_main_queue(), ^{ - self.retrievedDownloadResult = YES; + self->_retrievedDownloadResult = YES; - if (self.updateItem != nil) { - if (self.expectedContentLength > 0 && self.updateItem.contentLength > 0 && self.expectedContentLength != self.updateItem.contentLength) { - SULog(SULogLevelError, @"Warning: Downloader's expected content length (%llu) != Appcast item's length (%llu)", self.expectedContentLength, self.updateItem.contentLength); + id delegate = self->_delegate; + if (self->_updateItem != nil) { + if (self->_expectedContentLength > 0 && self->_updateItem.contentLength > 0 && self->_expectedContentLength != self->_updateItem.contentLength) { + SULog(SULogLevelError, @"Warning: Downloader's expected content length (%llu) != Appcast item's length (%llu)", self->_expectedContentLength, self->_updateItem.contentLength); } - SPUDownloadedUpdate *downloadedUpdate = [[SPUDownloadedUpdate alloc] initWithAppcastItem:self.updateItem secondaryAppcastItem:self.secondaryUpdateItem downloadName:self.downloadName temporaryDirectory:self.temporaryDirectory]; + SPUDownloadedUpdate *downloadedUpdate = [[SPUDownloadedUpdate alloc] initWithAppcastItem:self->_updateItem secondaryAppcastItem:self->_secondaryUpdateItem downloadName:self->_downloadName temporaryDirectory:self->_temporaryDirectory]; - if ([self.delegate respondsToSelector:@selector(downloadDriverDidDownloadUpdate:)]) { - [self.delegate downloadDriverDidDownloadUpdate:downloadedUpdate]; + if ([delegate respondsToSelector:@selector(downloadDriverDidDownloadUpdate:)]) { + [delegate downloadDriverDidDownloadUpdate:downloadedUpdate]; } } else { assert(downloadData != nil); SPUDownloadData *nonNullDownloadData = downloadData; - if ([self.delegate respondsToSelector:@selector(downloadDriverDidDownloadData:)]) { - [self.delegate downloadDriverDidDownloadData:nonNullDownloadData]; + if ([delegate respondsToSelector:@selector(downloadDriverDidDownloadData:)]) { + [delegate downloadDriverDidDownloadData:nonNullDownloadData]; } } }); @@ -232,15 +234,15 @@ - (void)downloaderDidFailWithError:(NSError *)error { dispatch_async(dispatch_get_main_queue(), ^{ - self.retrievedDownloadResult = YES; + self->_retrievedDownloadResult = YES; NSURL *failingUrl = error.userInfo[NSURLErrorFailingURLErrorKey]; if (!failingUrl) { - failingUrl = [self.updateItem fileURL]; + failingUrl = [self->_updateItem fileURL]; } NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:@{ - NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while downloading the update. Please try again later.", nil), + NSLocalizedDescriptionKey: SULocalizedStringFromTableInBundle(@"An error occurred while downloading the update. Please try again later.", SPARKLE_TABLE, SUSparkleBundle(), nil), NSUnderlyingErrorKey: error, }]; if (failingUrl) { @@ -248,15 +250,15 @@ } NSError *downloadError = [NSError errorWithDomain:SUSparkleErrorDomain code:SUDownloadError userInfo:userInfo]; - [self.delegate downloadDriverDidFailToDownloadFileWithError:downloadError]; + [self->_delegate downloadDriverDidFailToDownloadFileWithError:downloadError]; }); } - (void)downloaderDidSetDestinationName:(NSString *)destinationName temporaryDirectory:(NSString *)temporaryDirectory { dispatch_async(dispatch_get_main_queue(), ^{ - self.downloadName = destinationName; - self.temporaryDirectory = temporaryDirectory; + self->_downloadName = destinationName; + self->_temporaryDirectory = temporaryDirectory; }); } @@ -264,14 +266,15 @@ { dispatch_async(dispatch_get_main_queue(), ^{ // Fallback to appcast item's content length if we don't get the length from HTTP header - if ([self.delegate respondsToSelector:@selector(downloadDriverDidReceiveExpectedContentLength:)]) { - [self.delegate downloadDriverDidReceiveExpectedContentLength:expectedContentLength > 0 ? (uint64_t)expectedContentLength : self.updateItem.contentLength]; + id delegate = self->_delegate; + if ([delegate respondsToSelector:@selector(downloadDriverDidReceiveExpectedContentLength:)]) { + [delegate downloadDriverDidReceiveExpectedContentLength:expectedContentLength > 0 ? (uint64_t)expectedContentLength : self->_updateItem.contentLength]; } // Reset expected content length from downloader // Later we verify if the total length matches with the content length from the appcast if (expectedContentLength > 0) { - self.expectedContentLength = (uint64_t)expectedContentLength; + self->_expectedContentLength = (uint64_t)expectedContentLength; } }); } @@ -279,8 +282,9 @@ - (void)downloaderDidReceiveDataOfLength:(uint64_t)length { dispatch_async(dispatch_get_main_queue(), ^{ - if ([self.delegate respondsToSelector:@selector(downloadDriverDidReceiveDataOfLength:)]) { - [self.delegate downloadDriverDidReceiveDataOfLength:length]; + id delegate = self->_delegate; + if ([delegate respondsToSelector:@selector(downloadDriverDidReceiveDataOfLength:)]) { + [delegate downloadDriverDidReceiveDataOfLength:length]; } }); } diff --git a/Sparkle/SPUDownloadedUpdate.h b/Sparkle/SPUDownloadedUpdate.h index 2dc0a842..e0e32a86 100644 --- a/Sparkle/SPUDownloadedUpdate.h +++ b/Sparkle/SPUDownloadedUpdate.h @@ -11,7 +11,7 @@ NS_ASSUME_NONNULL_BEGIN -@interface SPUDownloadedUpdate : NSObject +SPU_OBJC_DIRECT_MEMBERS @interface SPUDownloadedUpdate : NSObject - (instancetype)initWithAppcastItem:(SUAppcastItem *)updateItem secondaryAppcastItem:(SUAppcastItem * _Nullable)secondaryItem downloadName:(NSString *)downloadName temporaryDirectory:(NSString *)temporaryDirectory; diff --git a/Sparkle/SPUInformationalUpdate.h b/Sparkle/SPUInformationalUpdate.h index 94998a27..32882b13 100644 --- a/Sparkle/SPUInformationalUpdate.h +++ b/Sparkle/SPUInformationalUpdate.h @@ -11,7 +11,7 @@ NS_ASSUME_NONNULL_BEGIN -@interface SPUInformationalUpdate : NSObject +SPU_OBJC_DIRECT_MEMBERS @interface SPUInformationalUpdate : NSObject - (instancetype)initWithAppcastItem:(SUAppcastItem *)updateItem secondaryAppcastItem:(SUAppcastItem * _Nullable)secondaryUpdateItem; diff --git a/Sparkle/SPUInstallerDriver.h b/Sparkle/SPUInstallerDriver.h index 4a9cf65f..f77bf3a8 100644 --- a/Sparkle/SPUInstallerDriver.h +++ b/Sparkle/SPUInstallerDriver.h @@ -27,7 +27,7 @@ NS_ASSUME_NONNULL_BEGIN @end -@interface SPUInstallerDriver : NSObject +SPU_OBJC_DIRECT_MEMBERS @interface SPUInstallerDriver : NSObject - (instancetype)initWithHost:(SUHost *)host applicationBundle:(NSBundle *)applicationBundle updater:(id)updater updaterDelegate:(nullable id)updaterDelegate delegate:(nullable id)delegate; diff --git a/Sparkle/SPUInstallerDriver.m b/Sparkle/SPUInstallerDriver.m index 36bfdf12..310ef381 100644 --- a/Sparkle/SPUInstallerDriver.m +++ b/Sparkle/SPUInstallerDriver.m @@ -25,66 +25,49 @@ #import "SUXPCInstallerConnection.h" #import "SPUDownloadedUpdate.h" #import "SPUInstallationType.h" +#import "SUConstants.h" #include "AppKitPrevention.h" #define FIRST_INSTALLER_MESSAGE_TIMEOUT 7ull +#if SPARKLE_BUILD_LEGACY_SUUPDATER @interface NSObject (PrivateDelegateMethods) - (nullable NSString *)_pathToRelaunchForUpdater:(SPUUpdater *)updater; @end +#endif @interface SPUInstallerDriver () - -@property (nonatomic, readonly) SUHost *host; -@property (nonatomic, readonly) NSBundle *applicationBundle; -@property (nonatomic, weak, readonly) id delegate; -@property (nonatomic) SPUInstallerMessageType currentStage; - -@property (nonatomic) id installerConnection; - -@property (nonatomic) NSUInteger extractionAttempts; -@property (nonatomic) BOOL postponedOnce; -@property (nonatomic, weak, readonly) id updater; -@property (nonatomic, weak, readonly) id updaterDelegate; -@property (nonatomic) BOOL relaunch; - -@property (nonatomic) BOOL systemDomain; - -@property (nonatomic) SUAppcastItem *updateItem; -@property (nonatomic, copy) NSString *downloadName; -@property (nonatomic, copy) NSString *temporaryDirectory; - -@property (nonatomic) BOOL aborted; -@property (nonatomic, nullable) NSError *installerError; - @end @implementation SPUInstallerDriver { + SUHost *_host; + NSBundle *_applicationBundle; + id _installerConnection; + SUAppcastItem *_updateItem; + NSString *_downloadName; + NSString *_temporaryDirectory; + NSError *_installerError; + + __weak id _updater; + __weak id _updaterDelegate; + __weak id _delegate; + void (^_updateWillInstallHandler)(void); + + SPUInstallerMessageType _currentStage; + NSUInteger _extractionAttempts; + + BOOL _postponedOnce; + BOOL _relaunch; + BOOL _systemDomain; + BOOL _aborted; } -@synthesize host = _host; -@synthesize applicationBundle = _applicationBundle; -@synthesize delegate = _delegate; -@synthesize currentStage = _currentStage; -@synthesize installerConnection = _installerConnection; -@synthesize extractionAttempts = _extractionAttempts; -@synthesize postponedOnce = _postponedOnce; -@synthesize updater = _updater; -@synthesize updaterDelegate = _updaterDelegate; -@synthesize relaunch = _relaunch; -@synthesize systemDomain = _systemDomain; -@synthesize updateItem = _updateItem; -@synthesize downloadName = _downloadName; -@synthesize temporaryDirectory = _temporaryDirectory; -@synthesize aborted = _aborted; -@synthesize installerError = _installerError; - - (instancetype)initWithHost:(SUHost *)host applicationBundle:(NSBundle *)applicationBundle updater:(id)updater updaterDelegate:(id)updaterDelegate delegate:(nullable id)delegate { self = [super init]; @@ -103,7 +86,7 @@ _updateWillInstallHandler = [updateWillInstallHandler copy]; } -- (void)_reportInstallerError:(nullable NSError *)currentInstallerError genericErrorCode:(NSInteger)genericErrorCode genericUserInfo:(NSDictionary *)genericUserInfo +- (void)_reportInstallerError:(nullable NSError *)currentInstallerError genericErrorCode:(NSInteger)genericErrorCode genericUserInfo:(NSDictionary *)genericUserInfo SPU_OBJC_DIRECT { // First see if there is a good custom error we can show // We only check for signing validation errors and installation errors due to not having write permission currently @@ -113,7 +96,7 @@ if (underlyingError != nil) { if (underlyingError.code == SUValidationError) { NSDictionary *userInfo = @{ - NSLocalizedDescriptionKey: SULocalizedString(@"The update is improperly signed and could not be validated. Please try again later or contact the app developer.", nil), + NSLocalizedDescriptionKey: SULocalizedStringFromTableInBundle(@"The update is improperly signed and could not be validated. Please try again later or contact the app developer.", SPARKLE_TABLE, SUSparkleBundle(), nil), NSUnderlyingErrorKey: (NSError * _Nonnull)currentInstallerError }; @@ -123,18 +106,25 @@ if (secondUnderlyingError != nil && [secondUnderlyingError.domain isEqualToString:NSCocoaErrorDomain] && secondUnderlyingError.code == NSFileWriteNoPermissionError) { // Note: these error strings will only surface for external app updaters like sparkle-cli (i.e, updaters that update other app bundles) +#if SPARKLE_COPY_LOCALIZATIONS + NSBundle *sparkleBundle = SUSparkleBundle(); +#endif + NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:@{ - NSLocalizedDescriptionKey: SULocalizedString(@"The installation failed due to not having permission to write the new update.", nil), + NSLocalizedDescriptionKey: SULocalizedStringFromTableInBundle(@"The installation failed due to not having permission to write the new update.", SPARKLE_TABLE, sparkleBundle, nil), NSUnderlyingErrorKey: (NSError * _Nonnull)currentInstallerError }]; // macOS 13 and later introduce a policy where Gatekeeper can block app modifications if the apps have different Team IDs - if (@available(macOS 13, *)) { +#if !defined(MAC_OS_VERSION_13_0) || MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_VERSION_13_0 + if (@available(macOS 13, *)) +#endif + { NSBundle *mainBundle = [NSBundle mainBundle]; - if (![mainBundle isEqual:self.host.bundle]) { + if (![mainBundle isEqual:_host.bundle]) { SUHost *mainBundleHost = [[SUHost alloc] initWithBundle:mainBundle]; - userInfo[NSLocalizedRecoverySuggestionErrorKey] = [NSString stringWithFormat:SULocalizedString(@"You may need to allow modifications from %1$@ in System Settings under Privacy & Security and App Management to install future updates.", nil), mainBundleHost.name]; + userInfo[NSLocalizedRecoverySuggestionErrorKey] = [NSString stringWithFormat:SULocalizedStringFromTableInBundle(@"You may need to allow modifications from %1$@ in System Settings under Privacy & Security and App Management to install future updates.", SPARKLE_TABLE, sparkleBundle, nil), mainBundleHost.name]; } } @@ -157,56 +147,59 @@ installerError = [NSError errorWithDomain:SUSparkleErrorDomain code:genericErrorCode userInfo:userInfo]; } - [self.delegate installerIsRequestingAbortInstallWithError:installerError]; + [_delegate installerIsRequestingAbortInstallWithError:installerError]; } -- (void)setUpConnection +- (void)setUpConnection SPU_OBJC_DIRECT { - if (self.installerConnection != nil) { + if (_installerConnection != nil) { return; } - NSString *hostBundleIdentifier = self.host.bundle.bundleIdentifier; + NSString *hostBundleIdentifier = _host.bundle.bundleIdentifier; assert(hostBundleIdentifier != nil); - if (!SPUXPCServiceIsEnabled(SUEnableInstallerConnectionServiceKey)) { - self.installerConnection = [[SUInstallerConnection alloc] initWithDelegate:self remote:NO]; - } else { - self.installerConnection = [[SUXPCInstallerConnection alloc] initWithDelegate:self]; +#if INSTALLER_CONNECTION_XPC_SERVICE_EMBEDDED + if (SPUXPCServiceIsEnabled(SUEnableInstallerConnectionServiceKey)) { + _installerConnection = [[SUXPCInstallerConnection alloc] initWithDelegate:self]; + } else +#endif + { + _installerConnection = [[SUInstallerConnection alloc] initWithDelegate:self remote:NO]; } - __weak SPUInstallerDriver *weakSelf = self; - [self.installerConnection setInvalidationHandler:^{ + __weak __typeof__(self) weakSelf = self; + [_installerConnection setInvalidationHandler:^{ dispatch_async(dispatch_get_main_queue(), ^{ - SPUInstallerDriver *strongSelf = weakSelf; - if (strongSelf.installerConnection != nil && !strongSelf.aborted) { + __typeof__(self) strongSelf = weakSelf; + if (strongSelf != nil && strongSelf->_installerConnection != nil && !strongSelf->_aborted) { NSDictionary *genericUserInfo = @{ - NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while running the updater. Please try again later.", nil), + NSLocalizedDescriptionKey: SULocalizedStringFromTableInBundle(@"An error occurred while running the updater. Please try again later.", SPARKLE_TABLE, SUSparkleBundle(), nil), NSLocalizedFailureReasonErrorKey:@"The remote port connection was invalidated from the updater. For additional details, please check Console logs for "@SPARKLE_RELAUNCH_TOOL_NAME". If your application is sandboxed, please also ensure Installer Connection & Status entitlements are correctly set up: https://sparkle-project.org/documentation/sandboxing/" }; - [strongSelf _reportInstallerError:strongSelf.installerError genericErrorCode:SUInstallationError genericUserInfo:genericUserInfo]; + [strongSelf _reportInstallerError:strongSelf->_installerError genericErrorCode:SUInstallationError genericUserInfo:genericUserInfo]; } }); }]; NSString *serviceName = SPUInstallerServiceNameForBundleIdentifier(hostBundleIdentifier); - NSString *installationType = self.updateItem.installationType; + NSString *installationType = _updateItem.installationType; assert(installationType != nil); - [self.installerConnection setServiceName:serviceName systemDomain:self.systemDomain]; + [_installerConnection setServiceName:serviceName systemDomain:_systemDomain]; } // This can be called multiple times (eg: if a delta update fails, this may be called again with a regular update item) - (void)extractDownloadedUpdate:(SPUDownloadedUpdate *)downloadedUpdate silently:(BOOL)silently completion:(void (^)(NSError * _Nullable))completionHandler { - self.updateItem = downloadedUpdate.updateItem; - self.temporaryDirectory = downloadedUpdate.temporaryDirectory; - self.downloadName = downloadedUpdate.downloadName; + _updateItem = downloadedUpdate.updateItem; + _temporaryDirectory = downloadedUpdate.temporaryDirectory; + _downloadName = downloadedUpdate.downloadName; - self.currentStage = SPUInstallerNotStarted; + _currentStage = SPUInstallerNotStarted; - if (self.installerConnection == nil) { + if (_installerConnection == nil) { [self launchAutoUpdateSilently:silently completion:completionHandler]; } else { // The Install tool is already alive; just send out installation input data again @@ -217,49 +210,59 @@ - (void)resumeInstallingUpdateWithUpdateItem:(SUAppcastItem *)updateItem systemDomain:(BOOL)systemDomain { - self.updateItem = updateItem; - self.systemDomain = systemDomain; + _updateItem = updateItem; + _systemDomain = systemDomain; } -- (void)sendInstallationData +- (void)sendInstallationData SPU_OBJC_DIRECT { - NSString *pathToRelaunch = self.applicationBundle.bundlePath; + NSString *pathToRelaunch = _applicationBundle.bundlePath; + +#if SPARKLE_BUILD_DMG_SUPPORT || SPARKLE_BUILD_LEGACY_SUUPDATER + id updaterDelegate = _updaterDelegate; + id updater = _updater; +#endif + +#if SPARKLE_BUILD_LEGACY_SUUPDATER // Give the delegate one more chance for determining the path to relaunch via a private API used by SUUpdater - if ([self.updaterDelegate respondsToSelector:@selector(_pathToRelaunchForUpdater:)]) { - NSString *relaunchPath = [(NSObject *)self.updaterDelegate _pathToRelaunchForUpdater:self.updater]; + if (updater != nil && [updaterDelegate respondsToSelector:@selector(_pathToRelaunchForUpdater:)]) { + NSString *relaunchPath = [(NSObject *)updaterDelegate _pathToRelaunchForUpdater:updater]; if (relaunchPath != nil) { pathToRelaunch = relaunchPath; } } +#endif NSString *decryptionPassword = nil; - if ([self.updaterDelegate respondsToSelector:@selector(decryptionPasswordForUpdater:)]) { - decryptionPassword = [self.updaterDelegate decryptionPasswordForUpdater:self.updater]; +#if SPARKLE_BUILD_DMG_SUPPORT + if (updater != nil && [updaterDelegate respondsToSelector:@selector(decryptionPasswordForUpdater:)]) { + decryptionPassword = [updaterDelegate decryptionPasswordForUpdater:updater]; } +#endif - SPUInstallationInputData *installationData = [[SPUInstallationInputData alloc] initWithRelaunchPath:pathToRelaunch hostBundlePath:self.host.bundlePath updateDirectoryPath:self.temporaryDirectory downloadName:self.downloadName installationType:self.updateItem.installationType signatures:self.updateItem.signatures decryptionPassword:decryptionPassword]; + SPUInstallationInputData *installationData = [[SPUInstallationInputData alloc] initWithRelaunchPath:pathToRelaunch hostBundlePath:_host.bundlePath updateDirectoryPath:_temporaryDirectory downloadName:_downloadName installationType:_updateItem.installationType signatures:_updateItem.signatures decryptionPassword:decryptionPassword]; NSData *archivedData = SPUArchiveRootObjectSecurely(installationData); if (archivedData == nil) { - [self.delegate installerIsRequestingAbortInstallWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey:@"An error occurred while encoding the installer parameters. Please try again later." }]]; + [_delegate installerIsRequestingAbortInstallWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey:@"An error occurred while encoding the installer parameters. Please try again later." }]]; return; } - [self.installerConnection handleMessageWithIdentifier:SPUInstallationData data:archivedData]; + [_installerConnection handleMessageWithIdentifier:SPUInstallationData data:archivedData]; - self.currentStage = SPUInstallerNotStarted; + _currentStage = SPUInstallerNotStarted; // If the number of extractions attempts stays the same, then we've waited too long and should abort the installation // The extraction attempts is incremented when we receive an extraction should start message from the installer // This also handles the case when a delta extraction fails and tries to re-try another extraction attempt later // We will also want to make sure current stage is still SUInstallerNotStarted because it may not be due to resumability - NSUInteger currentExtractionAttempts = self.extractionAttempts; - __weak SPUInstallerDriver *weakSelf = self; + NSUInteger currentExtractionAttempts = _extractionAttempts; + __weak __typeof__(self) weakSelf = self; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(FIRST_INSTALLER_MESSAGE_TIMEOUT * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ - SPUInstallerDriver *strongSelf = weakSelf; - if (strongSelf != nil && strongSelf.currentStage == SPUInstallerNotStarted && currentExtractionAttempts == self.extractionAttempts) { + __typeof__(self) strongSelf = weakSelf; + if (strongSelf != nil && strongSelf->_currentStage == SPUInstallerNotStarted && currentExtractionAttempts == strongSelf->_extractionAttempts) { SULog(SULogLevelError, @"Timeout: Installer never started archive extraction"); - [strongSelf.delegate installerIsRequestingAbortInstallWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey:SULocalizedString(@"An error occurred while starting the installer. Please try again later.", nil) }]]; + [strongSelf->_delegate installerIsRequestingAbortInstallWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey:SULocalizedStringFromTableInBundle(@"An error occurred while starting the installer. Please try again later.", SPARKLE_TABLE, SUSparkleBundle(), nil) }]]; } }); } @@ -271,48 +274,50 @@ }); } -- (void)_handleMessageWithIdentifier:(int32_t)identifier data:(NSData *)data +- (void)_handleMessageWithIdentifier:(int32_t)identifier data:(NSData *)data SPU_OBJC_DIRECT { - if (!SPUInstallerMessageTypeIsLegal(self.currentStage, identifier)) { - SULog(SULogLevelError, @"Error: received out of order message with current stage: %d, requested stage: %d", self.currentStage, identifier); + if (!SPUInstallerMessageTypeIsLegal(_currentStage, identifier)) { + SULog(SULogLevelError, @"Error: received out of order message with current stage: %d, requested stage: %d", _currentStage, identifier); return; } + id delegate = _delegate; + if (identifier == SPUExtractionStarted) { - self.extractionAttempts++; - self.currentStage = identifier; - [self.delegate installerDidStartExtracting]; + _extractionAttempts++; + _currentStage = identifier; + [delegate installerDidStartExtracting]; } else if (identifier == SPUExtractedArchiveWithProgress) { if (data.length == sizeof(double) && sizeof(double) == sizeof(uint64_t)) { uint64_t progressValue = CFSwapInt64LittleToHost(*(const uint64_t *)data.bytes); double progress = *(double *)&progressValue; - [self.delegate installerDidExtractUpdateWithProgress:progress]; - self.currentStage = identifier; + [delegate installerDidExtractUpdateWithProgress:progress]; + _currentStage = identifier; } } else if (identifier == SPUArchiveExtractionFailed) { // If this is a delta update, there must be a regular update we can fall back to - if ([self.updateItem isDeltaUpdate]) { - [self.delegate installerDidFailToApplyDeltaUpdate]; + if ([_updateItem isDeltaUpdate]) { + [delegate installerDidFailToApplyDeltaUpdate]; } else { // Don't have to store current stage because we're going to abort - NSDictionary *genericUserInfo = @{ NSLocalizedDescriptionKey:SULocalizedString(@"An error occurred while extracting the archive. Please try again later.", nil) }; + NSDictionary *genericUserInfo = @{ NSLocalizedDescriptionKey:SULocalizedStringFromTableInBundle(@"An error occurred while extracting the archive. Please try again later.", SPARKLE_TABLE, SUSparkleBundle(), nil) }; NSError *unarchivedError = (NSError *)SPUUnarchiveRootObjectSecurely(data, [NSError class]); [self _reportInstallerError:unarchivedError genericErrorCode:SUUnarchivingError genericUserInfo:genericUserInfo]; } } else if (identifier == SPUValidationStarted) { - self.currentStage = identifier; + _currentStage = identifier; } else if (identifier == SPUInstallationStartedStage1) { - self.currentStage = identifier; + _currentStage = identifier; } else if (identifier == SPUInstallationFinishedStage1) { - self.currentStage = identifier; + _currentStage = identifier; // Let the installer keep a copy of the appcast item data // We may want to ask for it later (note the updater can relaunch without the app necessarily having relaunched) - NSData *updateItemData = SPUArchiveRootObjectSecurely(self.updateItem); + NSData *updateItemData = SPUArchiveRootObjectSecurely(_updateItem); if (updateItemData != nil) { - [self.installerConnection handleMessageWithIdentifier:SPUSentUpdateAppcastItemData data:updateItemData]; + [_installerConnection handleMessageWithIdentifier:SPUSentUpdateAppcastItemData data:updateItemData]; } else { SULog(SULogLevelError, @"Error: Archived data to send for appcast item is nil"); } @@ -327,47 +332,47 @@ hasTargetTerminated = (BOOL)*((const uint8_t *)data.bytes + 1); } - [self.delegate installerDidFinishPreparationAndWillInstallImmediately:hasTargetTerminated silently:canInstallSilently]; + [delegate installerDidFinishPreparationAndWillInstallImmediately:hasTargetTerminated silently:canInstallSilently]; } else if (identifier == SPUInstallationFinishedStage2) { - self.currentStage = identifier; + _currentStage = identifier; BOOL hasTargetTerminated = NO; if (data.length >= sizeof(uint8_t)) { hasTargetTerminated = (BOOL)*((const uint8_t *)data.bytes); } - [self.delegate installerWillFinishInstallationAndRelaunch:self.relaunch]; + [delegate installerWillFinishInstallationAndRelaunch:_relaunch]; - [self.delegate installerDidStartInstallingWithApplicationTerminated:hasTargetTerminated]; + [delegate installerDidStartInstallingWithApplicationTerminated:hasTargetTerminated]; } else if (identifier == SPUInstallationFinishedStage3) { - self.currentStage = identifier; + _currentStage = identifier; - [self.installerConnection invalidate]; - self.installerConnection = nil; + [_installerConnection invalidate]; + _installerConnection = nil; - [self.delegate installerDidFinishInstallationAndRelaunched:self.relaunch acknowledgement:^{ + [delegate installerDidFinishInstallationAndRelaunched:_relaunch acknowledgement:^{ dispatch_async(dispatch_get_main_queue(), ^{ - [self.delegate installerIsRequestingAbortInstallWithError:nil]; + [delegate installerIsRequestingAbortInstallWithError:nil]; }); }]; } else if (identifier == SPUUpdaterAlivePing) { // Don't update the current stage; a ping request has no effect on that. - [self.installerConnection handleMessageWithIdentifier:SPUUpdaterAlivePong data:[NSData data]]; + [_installerConnection handleMessageWithIdentifier:SPUUpdaterAlivePong data:[NSData data]]; } else if (identifier == SPUInstallerError) { // Don't update the current stage; an installation error has no effect on that. - self.installerError = (NSError *)SPUUnarchiveRootObjectSecurely(data, [NSError class]); + _installerError = (NSError *)SPUUnarchiveRootObjectSecurely(data, [NSError class]); } } -- (void)launchAutoUpdateSilently:(BOOL)silently completion:(void (^)(NSError *_Nullable))completionHandler +- (void)launchAutoUpdateSilently:(BOOL)silently completion:(void (^)(NSError *_Nullable))completionHandler SPU_OBJC_DIRECT { - id installerLauncher = nil; + id installerLauncher; + +#if INSTALLER_LAUNCHER_XPC_SERVICE_EMBEDDED __block BOOL retrievedLaunchStatus = NO; NSXPCConnection *launcherConnection = nil; - if (!SPUXPCServiceIsEnabled(SUEnableInstallerLauncherServiceKey)) { - installerLauncher = [[SUInstallerLauncher alloc] init]; - } else { + if (SPUXPCServiceIsEnabled(SUEnableInstallerLauncherServiceKey)) { launcherConnection = [[NSXPCConnection alloc] initWithServiceName:@INSTALLER_LAUNCHER_BUNDLE_ID]; launcherConnection.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUInstallerLauncherProtocol)]; @@ -392,7 +397,7 @@ if (!retrievedLaunchStatus) { #pragma clang diagnostic pop NSError *error = - [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey:SULocalizedString(@"An error occurred while connecting to the installer. Please try again later.", nil) }]; + [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey:SULocalizedStringFromTableInBundle(@"An error occurred while connecting to the installer. Please try again later.", SPARKLE_TABLE, SUSparkleBundle(), nil) }]; completionHandler(error); @@ -409,16 +414,20 @@ [launcherConnection resume]; installerLauncher = launcherConnection.remoteObjectProxy; + } else +#endif + { + installerLauncher = [[SUInstallerLauncher alloc] init]; } // Our driver (automatic or UI based) has a say if interaction is allowed as well // An automatic driver may disallow interaction but the updater could try again later for a UI based driver that does allow interaction BOOL driverAllowsInteraction = !silently; - NSString *hostBundlePath = self.host.bundle.bundlePath; + NSString *hostBundlePath = _host.bundle.bundlePath; assert(hostBundlePath != nil); - NSString *installationType = self.updateItem.installationType; + NSString *installationType = _updateItem.installationType; assert(installationType != nil); // The installer launcher could be in a XPC service, so we don't want to do localization in there @@ -428,7 +437,7 @@ SUHost *mainBundleHost = [[SUHost alloc] initWithBundle:[NSBundle mainBundle]]; NSString *mainBundleName = mainBundleHost.name; - NSString *hostName = self.host.name; + NSString *hostName = _host.name; // Changing this authorization prompt is a little complicated because the // Auth database retains and caches the right we use, and there isn't a good way @@ -450,13 +459,15 @@ [installerLauncher launchInstallerWithHostBundlePath:hostBundlePath updaterIdentifier:mainBundleIdentifier authorizationPrompt:authorizationPrompt installationType:installationType allowingDriverInteraction:driverAllowsInteraction completion:^(SUInstallerLauncherStatus result, BOOL systemDomain) { dispatch_async(dispatch_get_main_queue(), ^{ +#if INSTALLER_LAUNCHER_XPC_SERVICE_EMBEDDED retrievedLaunchStatus = YES; [launcherConnection invalidate]; +#endif switch (result) { case SUInstallerLauncherFailure: SULog(SULogLevelError, @"Error: Failed to gain authorization required to update target"); - completionHandler([NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey:SULocalizedString(@"An error occurred while launching the installer. Please try again later.", nil) }]); + completionHandler([NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey:SULocalizedStringFromTableInBundle(@"An error occurred while launching the installer. Please try again later.", SPARKLE_TABLE, SUSparkleBundle(), nil) }]); break; case SUInstallerLauncherCanceled: completionHandler([NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationCanceledError userInfo:nil]); @@ -465,7 +476,7 @@ completionHandler([NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationAuthorizeLaterError userInfo:nil]); break; case SUInstallerLauncherSuccess: - self.systemDomain = systemDomain; + self->_systemDomain = systemDomain; [self setUpConnection]; [self sendInstallationData]; completionHandler(nil); @@ -475,28 +486,31 @@ }]; } -- (BOOL)mayUpdateAndRestart +- (BOOL)mayUpdateAndRestart SPU_OBJC_DIRECT { - return (!self.updaterDelegate || ![self.updaterDelegate respondsToSelector:@selector((updaterShouldRelaunchApplication:))] || [self.updaterDelegate updaterShouldRelaunchApplication:self.updater]); + id updaterDelegate = _updaterDelegate; + return (!updaterDelegate || ![updaterDelegate respondsToSelector:@selector((updaterShouldRelaunchApplication:))] || [updaterDelegate updaterShouldRelaunchApplication:_updater]); } - (void)installWithToolAndRelaunch:(BOOL)relaunch displayingUserInterface:(BOOL)showUI { - assert(self.updateItem); + assert(_updateItem); if (![self mayUpdateAndRestart]) { - [self.delegate installerIsRequestingAbortInstallWithError:nil]; + [_delegate installerIsRequestingAbortInstallWithError:nil]; return; } // Give the host app an opportunity to postpone the install and relaunch. - if (!self.postponedOnce) + if (!_postponedOnce) { - if ([self.updaterDelegate respondsToSelector:@selector(updater:shouldPostponeRelaunchForUpdate:untilInvokingBlock:)]) { - self.postponedOnce = YES; - __weak SPUInstallerDriver *weakSelf = self; - if ([self.updaterDelegate updater:self.updater shouldPostponeRelaunchForUpdate:self.updateItem untilInvokingBlock:^{ + id updater = _updater; + id updaterDelegate = _updaterDelegate; + if (updater != nil && [updaterDelegate respondsToSelector:@selector(updater:shouldPostponeRelaunchForUpdate:untilInvokingBlock:)]) { + _postponedOnce = YES; + __weak __typeof__(self) weakSelf = self; + if ([updaterDelegate updater:updater shouldPostponeRelaunchForUpdate:_updateItem untilInvokingBlock:^{ [weakSelf installWithToolAndRelaunch:relaunch displayingUserInterface:showUI]; }]) { return; @@ -512,14 +526,14 @@ [self setUpConnection]; // For resumability, we'll assume we are far enough for the installation to continue - self.currentStage = SPUInstallationFinishedStage1; + _currentStage = SPUInstallationFinishedStage1; - self.relaunch = relaunch; + _relaunch = relaunch; uint8_t response[2] = {(uint8_t)relaunch, (uint8_t)showUI}; NSData *responseData = [NSData dataWithBytes:response length:sizeof(response)]; - [self.installerConnection handleMessageWithIdentifier:SPUResumeInstallationToStage2 data:responseData]; + [_installerConnection handleMessageWithIdentifier:SPUResumeInstallationToStage2 data:responseData]; // the installer will send us SPUInstallationFinishedStage2 when stage 2 is done } @@ -529,19 +543,19 @@ // Set up connection to the installer if one is not set up already [self setUpConnection]; - self.aborted = YES; + _aborted = YES; - [self.installerConnection handleMessageWithIdentifier:SPUCancelInstallation data:[NSData data]]; + [_installerConnection handleMessageWithIdentifier:SPUCancelInstallation data:[NSData data]]; - [self.delegate installerIsRequestingAbortInstallWithError:nil]; + [_delegate installerIsRequestingAbortInstallWithError:nil]; } - (void)abortInstall { - self.aborted = YES; - if (self.installerConnection != nil) { - [self.installerConnection invalidate]; - self.installerConnection = nil; + _aborted = YES; + if (_installerConnection != nil) { + [_installerConnection invalidate]; + _installerConnection = nil; } } diff --git a/Sparkle/SPULocalCacheDirectory.h b/Sparkle/SPULocalCacheDirectory.h index eff88ba9..6bb229d7 100644 --- a/Sparkle/SPULocalCacheDirectory.h +++ b/Sparkle/SPULocalCacheDirectory.h @@ -10,7 +10,7 @@ NS_ASSUME_NONNULL_BEGIN -@interface SPULocalCacheDirectory : NSObject +SPU_OBJC_DIRECT_MEMBERS @interface SPULocalCacheDirectory : NSObject // Returns a path to a suitable cache directory to create specifically for Sparkle // Intermediate directories to this path may not exist yet diff --git a/Sparkle/SPUProbeInstallStatus.h b/Sparkle/SPUProbeInstallStatus.h index ee919b92..a1af21da 100644 --- a/Sparkle/SPUProbeInstallStatus.h +++ b/Sparkle/SPUProbeInstallStatus.h @@ -12,7 +12,7 @@ NS_ASSUME_NONNULL_BEGIN @class SPUInstallationInfo; -@interface SPUProbeInstallStatus : NSObject +SPU_OBJC_DIRECT_MEMBERS @interface SPUProbeInstallStatus : NSObject + (void)probeInstallerInProgressForHostBundleIdentifier:(NSString *)hostBundleIdentifier completion:(void (^)(BOOL))completionHandler; diff --git a/Sparkle/SPUProbeInstallStatus.m b/Sparkle/SPUProbeInstallStatus.m index e1ff69f0..fcec723a 100644 --- a/Sparkle/SPUProbeInstallStatus.m +++ b/Sparkle/SPUProbeInstallStatus.m @@ -27,12 +27,14 @@ + (void)probeInstallerInProgressForHostBundleIdentifier:(NSString *)hostBundleIdentifier completion:(void (^)(BOOL))completionHandler { - id installerStatus = nil; - BOOL usesXPC = SPUXPCServiceIsEnabled(SUEnableInstallerStatusServiceKey); - if (!usesXPC) { - installerStatus = [[SUInstallerStatus alloc] initWithRemote:NO]; - } else { + id installerStatus; +#if INSTALLER_STATUS_XPC_SERVICE_EMBEDDED + if (SPUXPCServiceIsEnabled(SUEnableInstallerStatusServiceKey)) { installerStatus = [[SUXPCInstallerStatus alloc] init]; + } else +#endif + { + installerStatus = [[SUInstallerStatus alloc] initWithRemote:NO]; } __block BOOL handledCompletion = NO; @@ -76,11 +78,7 @@ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(PROBE_TIMEOUT * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ if (!handledCompletion) { #pragma clang diagnostic pop - if (usesXPC) { - SULog(SULogLevelError, @"Timed out while probing installer progress. Please see https://sparkle-project.org/documentation/sandboxing/#testing for potential cause."); - } else { - SULog(SULogLevelError, @"Timed out while probing installer progress"); - } + SULog(SULogLevelError, @"Timed out while probing installer progress. If your app is sandboxed, please see https://sparkle-project.org/documentation/sandboxing/#testing for the potential cause."); completionHandler(NO); handledCompletion = YES; } @@ -91,11 +89,13 @@ + (void)probeInstallerUpdateItemForHostBundleIdentifier:(NSString *)hostBundleIdentifier completion:(void (^)(SPUInstallationInfo * _Nullable))completionHandler { id installerStatus = nil; - BOOL usesXPC = SPUXPCServiceIsEnabled(SUEnableInstallerStatusServiceKey); - if (!usesXPC) { - installerStatus = [[SUInstallerStatus alloc] initWithRemote:NO]; - } else { +#if INSTALLER_STATUS_XPC_SERVICE_EMBEDDED + if (SPUXPCServiceIsEnabled(SUEnableInstallerStatusServiceKey)) { installerStatus = [[SUXPCInstallerStatus alloc] init]; + } else +#endif + { + installerStatus = [[SUInstallerStatus alloc] initWithRemote:NO]; } __block BOOL handledCompletion = NO; @@ -145,11 +145,7 @@ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(PROBE_TIMEOUT * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ if (!handledCompletion) { #pragma clang diagnostic pop - if (usesXPC) { - SULog(SULogLevelDefault, @"Timed out while probing installer info data. Please see https://sparkle-project.org/documentation/sandboxing/#testing for potential cause."); - } else { - SULog(SULogLevelDefault, @"Timed out while probing installer info data"); - } + SULog(SULogLevelDefault, @"Timed out while probing installer info data. If your app is sandboxed, please see https://sparkle-project.org/documentation/sandboxing/#testing for the potential cause."); completionHandler(nil); handledCompletion = YES; } diff --git a/Sparkle/SPUProbingUpdateDriver.h b/Sparkle/SPUProbingUpdateDriver.h index 2e101695..30d7a48d 100644 --- a/Sparkle/SPUProbingUpdateDriver.h +++ b/Sparkle/SPUProbingUpdateDriver.h @@ -14,7 +14,7 @@ NS_ASSUME_NONNULL_BEGIN @class SUHost; @protocol SPUUpdaterDelegate; -@interface SPUProbingUpdateDriver : NSObject +SPU_OBJC_DIRECT_MEMBERS @interface SPUProbingUpdateDriver : NSObject - (instancetype)initWithHost:(SUHost *)host updater:(id)updater updaterDelegate:(nullable id )updaterDelegate; diff --git a/Sparkle/SPUProbingUpdateDriver.m b/Sparkle/SPUProbingUpdateDriver.m index 09846c66..f4990ba3 100644 --- a/Sparkle/SPUProbingUpdateDriver.m +++ b/Sparkle/SPUProbingUpdateDriver.m @@ -14,15 +14,13 @@ @interface SPUProbingUpdateDriver () -@property (nonatomic, readonly) SPUBasicUpdateDriver *basicDriver; -@property (nonatomic) id resumableUpdate; - @end @implementation SPUProbingUpdateDriver - -@synthesize basicDriver = _basicDriver; -@synthesize resumableUpdate = _resumableUpdate; +{ + SPUBasicUpdateDriver *_basicDriver; + id _resumableUpdate; +} - (instancetype)initWithHost:(SUHost *)host updater:(id)updater updaterDelegate:(id )updaterDelegate { @@ -35,7 +33,7 @@ - (void)setCompletionHandler:(SPUUpdateDriverCompletion)completionBlock { - [self.basicDriver setCompletionHandler:completionBlock]; + [_basicDriver setCompletionHandler:completionBlock]; } - (void)setUpdateShownHandler:(void (^)(void))updateShownHandler @@ -48,19 +46,19 @@ - (void)checkForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders { - [self.basicDriver checkForUpdatesAtAppcastURL:appcastURL withUserAgent:userAgent httpHeaders:httpHeaders inBackground:YES]; + [_basicDriver checkForUpdatesAtAppcastURL:appcastURL withUserAgent:userAgent httpHeaders:httpHeaders inBackground:YES]; } - (void)resumeInstallingUpdate { - [self.basicDriver resumeInstallingUpdate]; + [_basicDriver resumeInstallingUpdate]; } - (void)resumeUpdate:(id)resumableUpdate { - self.resumableUpdate = resumableUpdate; + _resumableUpdate = resumableUpdate; - [self.basicDriver resumeUpdate:resumableUpdate]; + [_basicDriver resumeUpdate:resumableUpdate]; } - (void)basicDriverDidFindUpdateWithAppcastItem:(SUAppcastItem *)__unused appcastItem secondaryAppcastItem:(SUAppcastItem * _Nullable)__unused secondaryAppcastItem systemDomain:(NSNumber * _Nullable)__unused systemDomain @@ -86,7 +84,7 @@ - (void)abortUpdateWithError:(nullable NSError *)error { - [self.basicDriver abortUpdateAndShowNextUpdateImmediately:NO resumableUpdate:self.resumableUpdate error:error]; + [_basicDriver abortUpdateAndShowNextUpdateImmediately:NO resumableUpdate:_resumableUpdate error:error]; } @end diff --git a/Sparkle/SPUScheduledUpdateDriver.h b/Sparkle/SPUScheduledUpdateDriver.h index 65fca3d3..5cf0e294 100644 --- a/Sparkle/SPUScheduledUpdateDriver.h +++ b/Sparkle/SPUScheduledUpdateDriver.h @@ -15,7 +15,7 @@ NS_ASSUME_NONNULL_BEGIN @class SUHost; @protocol SPUUserDriver, SPUUpdaterDelegate; -@interface SPUScheduledUpdateDriver : NSObject +SPU_OBJC_DIRECT_MEMBERS @interface SPUScheduledUpdateDriver : NSObject - (instancetype)initWithHost:(SUHost *)host applicationBundle:(NSBundle *)applicationBundle updater:(id)updater userDriver:(id )userDriver updaterDelegate:(nullable id )updaterDelegate; diff --git a/Sparkle/SPUScheduledUpdateDriver.m b/Sparkle/SPUScheduledUpdateDriver.m index b1c141c4..22027d2d 100644 --- a/Sparkle/SPUScheduledUpdateDriver.m +++ b/Sparkle/SPUScheduledUpdateDriver.m @@ -17,17 +17,16 @@ @interface SPUScheduledUpdateDriver() -@property (nonatomic, readonly) SPUUIBasedUpdateDriver *uiDriver; -@property (nonatomic) BOOL showedUpdate; -@property (nonatomic) void (^updateDidShowHandler)(void); - @end @implementation SPUScheduledUpdateDriver - -@synthesize uiDriver = _uiDriver; -@synthesize showedUpdate = _showedUpdate; -@synthesize updateDidShowHandler = _updateDidShowHandler; +{ + SPUUIBasedUpdateDriver *_uiDriver; + + void (^_updateDidShowHandler)(void); + + BOOL _showedUpdate; +} - (instancetype)initWithHost:(SUHost *)host applicationBundle:(NSBundle *)applicationBundle updater:(id)updater userDriver:(id )userDriver updaterDelegate:(nullable id )updaterDelegate { @@ -40,46 +39,46 @@ - (void)setCompletionHandler:(SPUUpdateDriverCompletion)completionBlock { - [self.uiDriver setCompletionHandler:completionBlock]; + [_uiDriver setCompletionHandler:completionBlock]; } - (void)setUpdateShownHandler:(void (^)(void))handler { - self.updateDidShowHandler = handler; + _updateDidShowHandler = [handler copy]; } - (void)setUpdateWillInstallHandler:(void (^)(void))updateWillInstallHandler { - [self.uiDriver setUpdateWillInstallHandler:updateWillInstallHandler]; + [_uiDriver setUpdateWillInstallHandler:updateWillInstallHandler]; } - (void)checkForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders { - [self.uiDriver checkForUpdatesAtAppcastURL:appcastURL withUserAgent:userAgent httpHeaders:httpHeaders inBackground:YES]; + [_uiDriver checkForUpdatesAtAppcastURL:appcastURL withUserAgent:userAgent httpHeaders:httpHeaders inBackground:YES]; } - (void)resumeInstallingUpdate { - [self.uiDriver resumeInstallingUpdate]; + [_uiDriver resumeInstallingUpdate]; } - (void)resumeUpdate:(id)resumableUpdate { - [self.uiDriver resumeUpdate:resumableUpdate]; + [_uiDriver resumeUpdate:resumableUpdate]; } - (void)uiDriverDidShowUpdate { - self.showedUpdate = YES; + _showedUpdate = YES; - if (self.updateDidShowHandler != nil) { - self.updateDidShowHandler(); + if (_updateDidShowHandler != nil) { + _updateDidShowHandler(); } } - (BOOL)showingUpdate { - return self.showedUpdate; + return _showedUpdate; } - (void)basicDriverIsRequestingAbortUpdateWithError:(nullable NSError *) error @@ -104,7 +103,7 @@ - (void)abortUpdateWithError:(nullable NSError *)error { - [self.uiDriver abortUpdateWithError:error showErrorToUser:self.showedUpdate]; + [_uiDriver abortUpdateWithError:error showErrorToUser:_showedUpdate]; } @end diff --git a/Sparkle/SPUSkippedUpdate.h b/Sparkle/SPUSkippedUpdate.h index d88f24db..319de05d 100644 --- a/Sparkle/SPUSkippedUpdate.h +++ b/Sparkle/SPUSkippedUpdate.h @@ -18,6 +18,9 @@ NS_ASSUME_NONNULL_BEGIN The intent is when the user is faced with a major upgrade, they can skip a major version. Otherwise they can choose to skip a minor version. */ +#ifndef BUILDING_SPARKLE_TESTS +SPU_OBJC_DIRECT_MEMBERS +#endif @interface SPUSkippedUpdate : NSObject + (nullable SPUSkippedUpdate *)skippedUpdateForHost:(SUHost *)host; diff --git a/Sparkle/SPUStandardUpdaterController.h b/Sparkle/SPUStandardUpdaterController.h index a34100dc..2ebce1aa 100644 --- a/Sparkle/SPUStandardUpdaterController.h +++ b/Sparkle/SPUStandardUpdaterController.h @@ -7,7 +7,16 @@ // #import + +#if defined(BUILDING_SPARKLE_SOURCES_EXTERNALLY) +// Ignore incorrect warning +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wquoted-include-in-framework-header" +#import "SUExport.h" +#pragma clang diagnostic pop +#else #import +#endif NS_ASSUME_NONNULL_BEGIN diff --git a/Sparkle/SPUStandardUpdaterController.m b/Sparkle/SPUStandardUpdaterController.m index e7a5f7fe..e755b25b 100644 --- a/Sparkle/SPUStandardUpdaterController.m +++ b/Sparkle/SPUStandardUpdaterController.m @@ -22,10 +22,6 @@ // programmatically. @interface SPUStandardUpdaterController () - -@property (nonatomic) SPUUpdater *updater; -@property (nonatomic) id userDriver; - @end @implementation SPUStandardUpdaterController @@ -38,22 +34,19 @@ // Note: awakeFromNib might be called more than once // We have to use awakeFromNib otherwise the delegate outlets may not be connected yet, // and we aren't a proper window or view controller, so we don't have a proper "did load" point - if (self.updater == nil) { + if (_updater == nil) { [self _initUpdater]; [self startUpdater]; } } -- (void)_initUpdater +- (void)_initUpdater SPU_OBJC_DIRECT { NSBundle *hostBundle = [NSBundle mainBundle]; -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdirect-ivar-access" SPUStandardUserDriver *userDriver = [[SPUStandardUserDriver alloc] initWithHostBundle:hostBundle delegate:self->userDriverDelegate]; - self.updater = [[SPUUpdater alloc] initWithHostBundle:hostBundle applicationBundle:hostBundle userDriver:userDriver delegate:self->updaterDelegate]; - self.userDriver = userDriver; -#pragma clang diagnostic pop + _updater = [[SPUUpdater alloc] initWithHostBundle:hostBundle applicationBundle:hostBundle userDriver:userDriver delegate:self->updaterDelegate]; + _userDriver = userDriver; } - (instancetype)initWithUpdaterDelegate:(nullable id)theUpdaterDelegate userDriverDelegate:(nullable id)theUserDriverDelegate @@ -79,14 +72,18 @@ - (void)startUpdater { NSError *updaterError = nil; - if (![self.updater startUpdater:&updaterError]) { + if (![_updater startUpdater:&updaterError]) { SULog(SULogLevelError, @"Fatal updater error (%ld): %@", updaterError.code, updaterError.localizedDescription); // Delay the alert four seconds so it doesn't show RIGHT as the app launches, but also doesn't interrupt the user once they really get to work. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ +#if SPARKLE_COPY_LOCALIZATIONS + NSBundle *sparkleBundle = SUSparkleBundle(); +#endif + NSAlert *alert = [[NSAlert alloc] init]; - alert.messageText = SULocalizedString(@"Unable to Check For Updates", nil); - alert.informativeText = SULocalizedString(@"The update checker failed to start correctly. You should contact the app developer to report this issue and verify that you have the latest version.", nil); + alert.messageText = SULocalizedStringFromTableInBundle(@"Unable to Check For Updates", SPARKLE_TABLE, sparkleBundle, nil); + alert.informativeText = SULocalizedStringFromTableInBundle(@"The update checker failed to start correctly. You should contact the app developer to report this issue and verify that you have the latest version.", SPARKLE_TABLE, sparkleBundle, nil); [alert runModal]; }); } @@ -94,13 +91,13 @@ - (IBAction)checkForUpdates:(nullable id)__unused sender { - [self.updater checkForUpdates]; + [_updater checkForUpdates]; } - (BOOL)validateMenuItem:(NSMenuItem *)item { if ([item action] == @selector(checkForUpdates:)) { - return self.updater.canCheckForUpdates; + return _updater.canCheckForUpdates; } return YES; } diff --git a/Sparkle/SPUStandardUserDriver+Private.h b/Sparkle/SPUStandardUserDriver+Private.h index 877cadf2..45bd43fe 100644 --- a/Sparkle/SPUStandardUserDriver+Private.h +++ b/Sparkle/SPUStandardUserDriver+Private.h @@ -8,8 +8,17 @@ #ifndef SPUStandardUserDriver_Private_h #define SPUStandardUserDriver_Private_h +#if defined(BUILDING_SPARKLE_SOURCES_EXTERNALLY) +// Ignore incorrect warning +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wquoted-include-in-framework-header" +#import "SPUStandardUserDriver.h" +#import "SUExport.h" +#pragma clang diagnostic pop +#else #import #import +#endif @class NSWindowController; diff --git a/Sparkle/SPUStandardUserDriver.h b/Sparkle/SPUStandardUserDriver.h index 36eda907..f8d5ef09 100644 --- a/Sparkle/SPUStandardUserDriver.h +++ b/Sparkle/SPUStandardUserDriver.h @@ -7,8 +7,18 @@ // #import + +#if defined(BUILDING_SPARKLE_SOURCES_EXTERNALLY) +// Ignore incorrect warning +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wquoted-include-in-framework-header" +#import "SPUUserDriver.h" +#import "SUExport.h" +#pragma clang diagnostic pop +#else #import #import +#endif NS_ASSUME_NONNULL_BEGIN diff --git a/Sparkle/SPUStandardUserDriver.m b/Sparkle/SPUStandardUserDriver.m index bdba0520..b3bef007 100644 --- a/Sparkle/SPUStandardUserDriver.m +++ b/Sparkle/SPUStandardUserDriver.m @@ -19,7 +19,6 @@ #import "SUUpdateAlert.h" #import "SULocalizations.h" #import "SUApplicationInfo.h" -#import "SUOperatingSystem.h" #import "SPUUserUpdateState.h" #import "SUErrors.h" #import "SPUInstallationType.h" @@ -36,53 +35,47 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 @interface SPUStandardUserDriver () -@property (nonatomic, readonly) SUHost *host; -// We must store the oldHostName before the host is potentially replaced -// because we may use this property after update has been installed -@property (nonatomic, readonly) NSString *oldHostName; -@property (nonatomic, readonly) NSURL *oldHostBundleURL; - -@property (nonatomic, weak, nullable, readonly) id delegate; - -@property (nonatomic, copy) void (^installUpdateHandler)(SPUUserUpdateChoice); -@property (nonatomic, copy) void (^cancellation)(void); - -@property (nonatomic) SUStatusController *checkingController; -// Note: we expose a private interface for activeUpdateAlert in SPUStandardUserDriver+Private.h as NSWindowController -@property (nonatomic) SUUpdateAlert *activeUpdateAlert; -@property (nonatomic) SUStatusController *statusController; -@property (nonatomic) SUUpdatePermissionPrompt *permissionPrompt; - -@property (nonatomic) uint64_t expectedContentLength; -@property (nonatomic) uint64_t bytesDownloaded; +// Note: we expose a private interface for activeUpdateAlert property in SPUStandardUserDriver+Private.h as NSWindowController +@property (nonatomic, readonly, nullable) NSWindowController *activeUpdateAlert; @end @implementation SPUStandardUserDriver { void (^_retryTerminatingApplication)(void); - mach_timebase_info_data_t _timebaseInfo; - double _timeSinceOpportuneUpdateNotice; + void (^_installUpdateHandler)(SPUUserUpdateChoice); + void (^_cancellation)(void); + + SUHost *_host; + // We must store the oldHostName before the host is potentially replaced + // because we may use this property after update has been installed + NSString *_oldHostName; + NSURL *_oldHostBundleURL; + id _applicationBecameActiveAfterUpdateAlertBecameKeyObserver; NSValue *_updateAlertWindowFrameValue; + SUStatusController *_checkingController; + + SUUpdateAlert *_activeUpdateAlert; + + SUStatusController *_statusController; + SUUpdatePermissionPrompt *_permissionPrompt; + + __weak id _delegate; + + mach_timebase_info_data_t _timebaseInfo; + + uint64_t _expectedContentLength; + uint64_t _bytesDownloaded; + double _timeSinceOpportuneUpdateNotice; + BOOL _updateAlertWindowWasInactive; BOOL _loggedGentleUpdateReminderWarning; BOOL _regularApplicationUpdate; BOOL _updateReceivedUserAttention; } -@synthesize host = _host; -@synthesize oldHostName = _oldHostName; -@synthesize oldHostBundleURL = _oldHostBundleURL; -@synthesize installUpdateHandler = _installUpdateHandler; -@synthesize cancellation = _cancellation; -@synthesize delegate = _delegate; -@synthesize checkingController = _checkingController; @synthesize activeUpdateAlert = _activeUpdateAlert; -@synthesize statusController = _statusController; -@synthesize permissionPrompt = _permissionPrompt; -@synthesize expectedContentLength = _expectedContentLength; -@synthesize bytesDownloaded = _bytesDownloaded; #pragma mark Birth @@ -106,7 +99,7 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 return self; } -- (double)currentTime +- (double)currentTime SPU_OBJC_DIRECT { if (_timebaseInfo.denom > 0) { return (1.0 * mach_absolute_time() * _timebaseInfo.numer / _timebaseInfo.denom); @@ -132,12 +125,16 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 } __weak __typeof__(self) weakSelf = self; - self.permissionPrompt = [[SUUpdatePermissionPrompt alloc] initPromptWithHost:self.host request:request reply:^(SUUpdatePermissionResponse *response) { + _permissionPrompt = [[SUUpdatePermissionPrompt alloc] initPromptWithHost:_host request:request reply:^(SUUpdatePermissionResponse *response) { reply(response); - weakSelf.permissionPrompt = nil; + + __typeof__(self) strongSelf = weakSelf; + if (strongSelf != nil) { + strongSelf->_permissionPrompt = nil; + } }]; - [self.permissionPrompt showWindow:nil]; + [_permissionPrompt showWindow:nil]; } #pragma mark Update Alert Focus @@ -145,7 +142,7 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 // This private method is used by SPUUpdater when scheduling for update checks - (void)logGentleScheduledUpdateReminderWarningIfNeeded { - id delegate = self.delegate; + id delegate = _delegate; if (!_loggedGentleUpdateReminderWarning && (![delegate respondsToSelector:@selector(supportsGentleScheduledUpdateReminders)] || !delegate.supportsGentleScheduledUpdateReminders)) { BOOL isBackgroundApp = [SUApplicationInfo isBackgroundApplication:[NSApplication sharedApplication]]; if (isBackgroundApp) { @@ -158,10 +155,10 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 // updateItem should be non-nil when showing an update for first time for scheduled updates // If appcastItem is != nil, then state must be != nil -- (void)setUpActiveUpdateAlertForScheduledUpdate:(SUAppcastItem * _Nullable)updateItem state:(SPUUserUpdateState * _Nullable)state +- (void)setUpActiveUpdateAlertForScheduledUpdate:(SUAppcastItem * _Nullable)updateItem state:(SPUUserUpdateState * _Nullable)state SPU_OBJC_DIRECT { // Make sure the window is loaded in any case - [self.activeUpdateAlert window]; + [_activeUpdateAlert window]; [self _removeApplicationBecomeActiveObserver]; @@ -173,8 +170,8 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 [NSApp activateIgnoringOtherApps:YES]; } - [self.activeUpdateAlert showWindow:nil]; - [self.activeUpdateAlert setInstallButtonFocus:YES]; + [_activeUpdateAlert showWindow:nil]; + [_activeUpdateAlert setInstallButtonFocus:YES]; } else { // Handle scheduled update check uint64_t timeElapsedSinceOpportuneUpdateNotice = (uint64_t)([self currentTime] - _timeSinceOpportuneUpdateNotice); @@ -183,7 +180,7 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 BOOL appNearUpdaterInitialization = (timeElapsedSinceOpportuneUpdateNotice <= 3000000000ULL); // We will always show an update alert at the right time - [self.activeUpdateAlert setInstallButtonFocus:YES]; + [_activeUpdateAlert setInstallButtonFocus:YES]; // If the delegate doesn't override our behavior: // For regular applications, only show the update alert if the app is active and if it's an an opportune time, otherwise, we'll wait until the app becomes active again. @@ -269,29 +266,33 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 } } + id delegate = _delegate; BOOL handleShowingUpdates; - if ([self.delegate respondsToSelector:@selector(standardUserDriverShouldHandleShowingScheduledUpdate:andInImmediateFocus:)]) { - handleShowingUpdates = [self.delegate standardUserDriverShouldHandleShowingScheduledUpdate:(SUAppcastItem * _Nonnull)updateItem andInImmediateFocus:immediateFocus]; + if ([delegate respondsToSelector:@selector(standardUserDriverShouldHandleShowingScheduledUpdate:andInImmediateFocus:)]) { + handleShowingUpdates = [delegate standardUserDriverShouldHandleShowingScheduledUpdate:(SUAppcastItem * _Nonnull)updateItem andInImmediateFocus:immediateFocus]; } else { handleShowingUpdates = YES; } if (!handleShowingUpdates) { // Delay a runloop cycle to make sure the update can properly be checked - SPUStandardUserDriver *__weak weakSelf = self; + __weak __typeof__(self) weakSelf = self; dispatch_async(dispatch_get_main_queue(), ^{ - id delegate = weakSelf.delegate; - if ([delegate respondsToSelector:@selector(standardUserDriverWillHandleShowingUpdate:forUpdate:state:)]) { - [delegate standardUserDriverWillHandleShowingUpdate:handleShowingUpdates forUpdate:(SUAppcastItem * _Nonnull)updateItem state:(SPUUserUpdateState * _Nonnull)state]; - } else { - SULog(SULogLevelError, @"Error: Delegate <%@> is handling showing scheduled update but does not implement %@", delegate, NSStringFromSelector(@selector(standardUserDriverWillHandleShowingUpdate:forUpdate:state:))); + __typeof__(self) strongSelf = weakSelf; + if (strongSelf != nil) { + id innerDelegate = strongSelf->_delegate; + if ([innerDelegate respondsToSelector:@selector(standardUserDriverWillHandleShowingUpdate:forUpdate:state:)]) { + [innerDelegate standardUserDriverWillHandleShowingUpdate:handleShowingUpdates forUpdate:(SUAppcastItem * _Nonnull)updateItem state:(SPUUserUpdateState * _Nonnull)state]; + } else { + SULog(SULogLevelError, @"Error: Delegate <%@> is handling showing scheduled update but does not implement %@", innerDelegate, NSStringFromSelector(@selector(standardUserDriverWillHandleShowingUpdate:forUpdate:state:))); + } } }); } else { // The update will be shown, but not necessarily immediately if !driverShowingUpdateNow // It is useful to post this early in case the delegate wants to post a notification - if ([self.delegate respondsToSelector:@selector(standardUserDriverWillHandleShowingUpdate:forUpdate:state:)]) { - [self.delegate standardUserDriverWillHandleShowingUpdate:handleShowingUpdates forUpdate:(SUAppcastItem * _Nonnull)updateItem state:(SPUUserUpdateState * _Nonnull)state]; + if ([delegate respondsToSelector:@selector(standardUserDriverWillHandleShowingUpdate:forUpdate:state:)]) { + [delegate standardUserDriverWillHandleShowingUpdate:handleShowingUpdates forUpdate:(SUAppcastItem * _Nonnull)updateItem state:(SPUUserUpdateState * _Nonnull)state]; } if (!driverShowingUpdateNow) { @@ -302,24 +303,24 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 } if (showingUpdateInBack) { - [self.activeUpdateAlert.window orderBack:nil]; + [_activeUpdateAlert.window orderBack:nil]; } else { - [self.activeUpdateAlert showWindow:nil]; + [_activeUpdateAlert showWindow:nil]; } } } } } -- (void)_removeApplicationBecomeActiveObserver +- (void)_removeApplicationBecomeActiveObserver SPU_OBJC_DIRECT { [[NSNotificationCenter defaultCenter] removeObserver:self name:NSApplicationDidBecomeActiveNotification object:NSApp]; } - (void)applicationDidBecomeActive:(NSNotification *)__unused aNotification { - [self.activeUpdateAlert showWindow:nil]; - [self.activeUpdateAlert setInstallButtonFocus:YES]; + [_activeUpdateAlert showWindow:nil]; + [_activeUpdateAlert setInstallButtonFocus:YES]; [self _removeApplicationBecomeActiveObserver]; } @@ -332,19 +333,21 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 [self closeCheckingWindow]; + id delegate = _delegate; id versionDisplayer = nil; - if ([self.delegate respondsToSelector:@selector(standardUserDriverRequestsVersionDisplayer)]) { - versionDisplayer = [self.delegate standardUserDriverRequestsVersionDisplayer]; + + if ([delegate respondsToSelector:@selector(standardUserDriverRequestsVersionDisplayer)]) { + versionDisplayer = [delegate standardUserDriverRequestsVersionDisplayer]; } - BOOL needsToObserveUserAttention = [self.delegate respondsToSelector:@selector(standardUserDriverDidReceiveUserAttentionForUpdate:)]; + BOOL needsToObserveUserAttention = [delegate respondsToSelector:@selector(standardUserDriverDidReceiveUserAttentionForUpdate:)]; - __weak SPUStandardUserDriver *weakSelf = self; - __weak id weakDelegate = self.delegate; - self.activeUpdateAlert = [[SUUpdateAlert alloc] initWithAppcastItem:appcastItem state:state host:self.host versionDisplayer:versionDisplayer completionBlock:^(SPUUserUpdateChoice choice, NSRect windowFrame, BOOL wasKeyWindow) { + __weak __typeof__(self) weakSelf = self; + __weak id weakDelegate = delegate; + _activeUpdateAlert = [[SUUpdateAlert alloc] initWithAppcastItem:appcastItem state:state host:_host versionDisplayer:versionDisplayer completionBlock:^(SPUUserUpdateChoice choice, NSRect windowFrame, BOOL wasKeyWindow) { reply(choice); - SPUStandardUserDriver *strongSelf = weakSelf; + __typeof__(self) strongSelf = weakSelf; if (strongSelf != nil) { if (needsToObserveUserAttention && !strongSelf->_updateReceivedUserAttention) { @@ -362,7 +365,7 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 strongSelf->_updateAlertWindowFrameValue = [NSValue valueWithRect:windowFrame]; strongSelf->_updateAlertWindowWasInactive = !wasKeyWindow; - strongSelf.activeUpdateAlert = nil; + strongSelf->_activeUpdateAlert = nil; } } didBecomeKeyBlock:^{ if (!needsToObserveUserAttention) { @@ -370,7 +373,7 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 } if ([NSApp isActive]) { - SPUStandardUserDriver *strongSelf = weakSelf; + __typeof__(self) strongSelf = weakSelf; if (strongSelf != nil && !strongSelf->_updateReceivedUserAttention) { strongSelf->_updateReceivedUserAttention = YES; @@ -382,12 +385,12 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 // We need to listen for when the app becomes active again, and then test if the window alert // is still key. if it is, let the delegate know. Remove the observation after that. - SPUStandardUserDriver *strongSelfOuter = weakSelf; + __typeof__(self) strongSelfOuter = weakSelf; if (strongSelfOuter != nil && strongSelfOuter->_applicationBecameActiveAfterUpdateAlertBecameKeyObserver == nil) { strongSelfOuter->_applicationBecameActiveAfterUpdateAlertBecameKeyObserver = [[NSNotificationCenter defaultCenter] addObserverForName:NSApplicationDidBecomeActiveNotification object:NSApp queue:NSOperationQueue.mainQueue usingBlock:^(NSNotification * _Nonnull __unused note) { - SPUStandardUserDriver *strongSelf = weakSelf; + __typeof__(self) strongSelf = weakSelf; if (strongSelf != nil) { - if (!strongSelf->_updateReceivedUserAttention && [strongSelf.activeUpdateAlert.window isKeyWindow]) { + if (!strongSelf->_updateReceivedUserAttention && [strongSelf->_activeUpdateAlert.window isKeyWindow]) { strongSelf->_updateReceivedUserAttention = YES; id strongDelegate = weakDelegate; @@ -410,8 +413,8 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 // For user initiated checks, let the delegate know we'll be showing an update // For scheduled checks, -setUpActiveUpdateAlertForUpdate:state: below will handle this - if (state.userInitiated && [self.delegate respondsToSelector:@selector(standardUserDriverWillHandleShowingUpdate:forUpdate:state:)]) { - [self.delegate standardUserDriverWillHandleShowingUpdate:YES forUpdate:appcastItem state:state]; + if (state.userInitiated && [delegate respondsToSelector:@selector(standardUserDriverWillHandleShowingUpdate:forUpdate:state:)]) { + [delegate standardUserDriverWillHandleShowingUpdate:YES forUpdate:appcastItem state:state]; } [self setUpActiveUpdateAlertForScheduledUpdate:(state.userInitiated ? nil : appcastItem) state:state]; @@ -421,7 +424,7 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 { assert(NSThread.isMainThread); - [self.activeUpdateAlert showUpdateReleaseNotesWithDownloadData:downloadData]; + [_activeUpdateAlert showUpdateReleaseNotesWithDownloadData:downloadData]; } - (void)showUpdateReleaseNotesFailedToDownloadWithError:(NSError *)error @@ -431,23 +434,23 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 // I don't want to expose SULog here because it's more of a user driver facing error // For our purposes we just ignore it and continue on.. NSLog(@"Failed to download release notes with error: %@", error); - [self.activeUpdateAlert showReleaseNotesFailedToDownload]; + [_activeUpdateAlert showReleaseNotesFailedToDownload]; } - (void)showUpdateInFocus { BOOL mayNeedToActivateApp; - if (self.activeUpdateAlert != nil) { + if (_activeUpdateAlert != nil) { [self setUpActiveUpdateAlertForScheduledUpdate:nil state:nil]; mayNeedToActivateApp = NO; - } else if (self.permissionPrompt != nil) { - [self.permissionPrompt showWindow:nil]; + } else if (_permissionPrompt != nil) { + [_permissionPrompt showWindow:nil]; mayNeedToActivateApp = YES; - } else if (self.statusController != nil) { - [self.statusController showWindow:nil]; + } else if (_statusController != nil) { + [_statusController showWindow:nil]; mayNeedToActivateApp = YES; - } else if (self.checkingController != nil) { - [self.checkingController showWindow:nil]; + } else if (_checkingController != nil) { + [_checkingController showWindow:nil]; mayNeedToActivateApp = YES; } else if (_retryTerminatingApplication != nil) { [self _showAndConfigureStatusControllerForReadyToInstallWithAction:@selector(retryTermination:) closable:YES]; @@ -464,14 +467,18 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 #pragma mark Install & Relaunch Update -- (void)_showAndConfigureStatusControllerForReadyToInstallWithAction:(SEL)selector closable:(BOOL)closable +- (void)_showAndConfigureStatusControllerForReadyToInstallWithAction:(SEL)selector closable:(BOOL)closable SPU_OBJC_DIRECT { [self createAndShowStatusControllerWithClosable:closable]; - [self.statusController beginActionWithTitle:SULocalizedString(@"Ready to Install", nil) maxProgressValue:1.0 statusText:nil]; - [self.statusController setProgressValue:1.0]; // Fill the bar. - [self.statusController setButtonEnabled:YES]; - [self.statusController setButtonTitle:SULocalizedString(@"Install and Relaunch", nil) target:self action:selector isDefault:YES]; +#if SPARKLE_COPY_LOCALIZATIONS + NSBundle *sparkleBundle = SUSparkleBundle(); +#endif + + [_statusController beginActionWithTitle:SULocalizedStringFromTableInBundle(@"Ready to Install", SPARKLE_TABLE, sparkleBundle, nil) maxProgressValue:1.0 statusText:nil]; + [_statusController setProgressValue:1.0]; // Fill the bar. + [_statusController setButtonEnabled:YES]; + [_statusController setButtonTitle:SULocalizedStringFromTableInBundle(@"Install and Relaunch", SPARKLE_TABLE, sparkleBundle, nil) target:self action:selector isDefault:YES]; } - (void)showReadyToInstallAndRelaunch:(void (^)(SPUUserUpdateChoice))installUpdateHandler @@ -482,14 +489,14 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 [NSApp requestUserAttention:NSInformationalRequest]; - self.installUpdateHandler = installUpdateHandler; + _installUpdateHandler = [installUpdateHandler copy]; } - (void)installAndRestart:(id)__unused sender { - if (self.installUpdateHandler != nil) { - self.installUpdateHandler(SPUUserUpdateChoiceInstall); - self.installUpdateHandler = nil; + if (_installUpdateHandler != nil) { + _installUpdateHandler(SPUUserUpdateChoiceInstall); + _installUpdateHandler = nil; } } @@ -506,13 +513,17 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 { assert(NSThread.isMainThread); - self.cancellation = cancellation; + _cancellation = [cancellation copy]; - self.checkingController = [[SUStatusController alloc] initWithHost:self.host windowTitle:[NSString stringWithFormat:SULocalizedString(@"Updating %@", nil), [self.host name]] centerPointValue:nil minimizable:NO closable:NO]; - [[self.checkingController window] center]; // Force the checking controller to load its window. - [self.checkingController beginActionWithTitle:SULocalizedString(@"Checking for updates…", nil) maxProgressValue:0.0 statusText:nil]; - [self.checkingController setButtonTitle:SULocalizedString(@"Cancel", nil) target:self action:@selector(cancelCheckForUpdates:) isDefault:NO]; - [self.checkingController showWindow:self]; +#if SPARKLE_COPY_LOCALIZATIONS + NSBundle *sparkleBundle = SUSparkleBundle(); +#endif + + _checkingController = [[SUStatusController alloc] initWithHost:_host windowTitle:[NSString stringWithFormat:SULocalizedStringFromTableInBundle(@"Updating %@", SPARKLE_TABLE, sparkleBundle, nil), [_host name]] centerPointValue:nil minimizable:NO closable:NO]; + [[_checkingController window] center]; // Force the checking controller to load its window. + [_checkingController beginActionWithTitle:SULocalizedStringFromTableInBundle(@"Checking for updates…", SPARKLE_TABLE, sparkleBundle, nil) maxProgressValue:0.0 statusText:nil]; + [_checkingController setButtonTitle:SULocalizedStringFromTableInBundle(@"Cancel", SPARKLE_TABLE, sparkleBundle, nil) target:self action:@selector(cancelCheckForUpdates:) isDefault:NO]; + [_checkingController showWindow:self]; // For background applications, obtain focus. // Useful if the update check is requested from another app like System Preferences. @@ -522,21 +533,21 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 } } -- (void)closeCheckingWindow +- (void)closeCheckingWindow SPU_OBJC_DIRECT { - if (self.checkingController != nil) + if (_checkingController != nil) { - [self.checkingController close]; - self.checkingController = nil; - self.cancellation = nil; + [_checkingController close]; + _checkingController = nil; + _cancellation = nil; } } - (void)cancelCheckForUpdates:(id)__unused sender { - if (self.cancellation != nil) { - self.cancellation(); - self.cancellation = nil; + if (_cancellation != nil) { + _cancellation(); + _cancellation = nil; } [self closeCheckingWindow]; } @@ -549,13 +560,17 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 [self closeCheckingWindow]; - [self.statusController close]; - self.statusController = nil; + [_statusController close]; + _statusController = nil; + +#if SPARKLE_COPY_LOCALIZATIONS + NSBundle *sparkleBundle = SUSparkleBundle(); +#endif NSAlert *alert = [[NSAlert alloc] init]; - alert.messageText = SULocalizedString(@"Update Error!", nil); + alert.messageText = SULocalizedStringFromTableInBundle(@"Update Error!", SPARKLE_TABLE, sparkleBundle, nil); alert.informativeText = [NSString stringWithFormat:@"%@", [error localizedDescription]]; - [alert addButtonWithTitle:SULocalizedString(@"Cancel Update", nil)]; + [alert addButtonWithTitle:SULocalizedStringFromTableInBundle(@"Cancel Update", SPARKLE_TABLE, sparkleBundle, nil)]; [self showAlert:alert secondaryAction:nil]; acknowledgement(); @@ -576,17 +591,20 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 void (^secondaryAction)(void) = nil; SUAppcastItem *latestAppcastItem = error.userInfo[SPULatestAppcastItemFoundKey]; if (latestAppcastItem != nil) { +#if SPARKLE_COPY_LOCALIZATIONS + NSBundle *sparkleBundle = SUSparkleBundle(); +#endif switch (reason) { case SPUNoUpdateFoundReasonOnLatestVersion: case SPUNoUpdateFoundReasonOnNewerThanLatestVersion: { // Show the user the past version history if available // Check if the delegate allows showing the Version History - id delegate = self.delegate; + id delegate = _delegate; BOOL shouldShowVersionHistory = (![delegate respondsToSelector:@selector(standardUserDriverShouldShowVersionHistoryForAppcastItem:)] || [delegate standardUserDriverShouldShowVersionHistoryForAppcastItem:latestAppcastItem]); if (shouldShowVersionHistory) { - NSString *localizedButtonTitle = SULocalizedString(@"Version History", nil); + NSString *localizedButtonTitle = SULocalizedStringFromTableInBundle(@"Version History", SPARKLE_TABLE, sparkleBundle, nil); // Check if the delegate implements its own Version History action if ([delegate respondsToSelector:@selector(standardUserDriverShowVersionHistoryForAppcastItem:)]) { @@ -618,7 +636,7 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 case SPUNoUpdateFoundReasonSystemIsTooNew: if (latestAppcastItem.infoURL != nil) { // Show the user the product's link if available - [alert addButtonWithTitle:SULocalizedString(@"Learn More…", nil)]; + [alert addButtonWithTitle:SULocalizedStringFromTableInBundle(@"Learn More…", SPARKLE_TABLE, sparkleBundle, nil)]; secondaryAction = ^{ [[NSWorkspace sharedWorkspace] openURL:(NSURL * _Nonnull)latestAppcastItem.infoURL]; @@ -635,15 +653,15 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 acknowledgement(); } -- (void)showAlert:(NSAlert *)alert secondaryAction:(void (^ _Nullable)(void))secondaryAction +- (void)showAlert:(NSAlert *)alert secondaryAction:(void (^ _Nullable)(void))secondaryAction SPU_OBJC_DIRECT { - id delegate = self.delegate; + id delegate = _delegate; if ([delegate respondsToSelector:@selector(standardUserDriverWillShowModalAlert)]) { [delegate standardUserDriverWillShowModalAlert]; } - [alert setIcon:[SUApplicationInfo bestIconForHost:self.host]]; + [alert setIcon:[SUApplicationInfo bestIconForHost:_host]]; NSModalResponse response = [alert runModal]; if (response == NSAlertSecondButtonReturn && secondaryAction != nil) { @@ -657,16 +675,17 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 #pragma mark Download & Install Updates -- (void)createAndShowStatusControllerWithClosable:(BOOL)closable +- (void)createAndShowStatusControllerWithClosable:(BOOL)closable SPU_OBJC_DIRECT { - if (self.statusController == nil) { + if (_statusController == nil) { // We will make the status window minimizable for regular app updates which are often // quick and atomic to install on quit. But we won't do this for package based updates. + id delegate = _delegate; BOOL minimizable; if (!_regularApplicationUpdate) { minimizable = NO; - } else if ([self.delegate respondsToSelector:@selector(standardUserDriverAllowsMinimizableStatusWindow)]) { - minimizable = [self.delegate standardUserDriverAllowsMinimizableStatusWindow]; + } else if ([delegate respondsToSelector:@selector(standardUserDriverAllowsMinimizableStatusWindow)]) { + minimizable = [delegate standardUserDriverAllowsMinimizableStatusWindow]; } else { minimizable = YES; } @@ -681,12 +700,12 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 centerPointValue = nil; } - self.statusController = [[SUStatusController alloc] initWithHost:self.host windowTitle:[NSString stringWithFormat:SULocalizedString(@"Updating %@", nil), [self.host name]] centerPointValue:centerPointValue minimizable:minimizable closable:closable]; + _statusController = [[SUStatusController alloc] initWithHost:_host windowTitle:[NSString stringWithFormat:SULocalizedStringFromTableInBundle(@"Updating %@", SPARKLE_TABLE, SUSparkleBundle(), nil), _host.name] centerPointValue:centerPointValue minimizable:minimizable closable:closable]; if (_updateAlertWindowWasInactive) { - [self.statusController.window orderFront:nil]; + [_statusController.window orderFront:nil]; } else { - [self.statusController showWindow:self]; + [_statusController showWindow:self]; } } } @@ -695,22 +714,26 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 { assert(NSThread.isMainThread); - self.cancellation = cancellation; + _cancellation = [cancellation copy]; [self createAndShowStatusControllerWithClosable:NO]; - [self.statusController beginActionWithTitle:SULocalizedString(@"Downloading update…", @"Take care not to overflow the status window.") maxProgressValue:1.0 statusText:nil]; - [self.statusController setProgressValue:0.0]; - [self.statusController setButtonTitle:SULocalizedString(@"Cancel", nil) target:self action:@selector(cancelDownload:) isDefault:NO]; +#if SPARKLE_COPY_LOCALIZATIONS + NSBundle *sparkleBundle = SUSparkleBundle(); +#endif - self.bytesDownloaded = 0; + [_statusController beginActionWithTitle:SULocalizedStringFromTableInBundle(@"Downloading update…", SPARKLE_TABLE, sparkleBundle, @"Take care not to overflow the status window.") maxProgressValue:1.0 statusText:nil]; + [_statusController setProgressValue:0.0]; + [_statusController setButtonTitle:SULocalizedStringFromTableInBundle(@"Cancel", SPARKLE_TABLE, sparkleBundle, nil) target:self action:@selector(cancelDownload:) isDefault:NO]; + + _bytesDownloaded = 0; } - (void)cancelDownload:(id)__unused sender { - if (self.cancellation != nil) { - self.cancellation(); - self.cancellation = nil; + if (_cancellation != nil) { + _cancellation(); + _cancellation = nil; } } @@ -718,9 +741,9 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 { assert(NSThread.isMainThread); - self.expectedContentLength = expectedContentLength; + _expectedContentLength = expectedContentLength; if (expectedContentLength == 0) { - [self.statusController setMaxProgressValue:0.0]; + [_statusController setMaxProgressValue:0.0]; } } @@ -728,19 +751,23 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 { assert(NSThread.isMainThread); - self.bytesDownloaded += length; + _bytesDownloaded += length; NSByteCountFormatter *formatter = [[NSByteCountFormatter alloc] init]; [formatter setZeroPadsFractionDigits:YES]; + +#if SPARKLE_COPY_LOCALIZATIONS + NSBundle *sparkleBundle = SUSparkleBundle(); +#endif - if (self.expectedContentLength > 0.0) { - double newProgressValue = (double)self.bytesDownloaded / (double)self.expectedContentLength; + if (_expectedContentLength > 0.0) { + double newProgressValue = (double)_bytesDownloaded / (double)_expectedContentLength; - [self.statusController setProgressValue:MIN(newProgressValue, 1.0)]; + [_statusController setProgressValue:MIN(newProgressValue, 1.0)]; - [self.statusController setStatusText:[NSString stringWithFormat:SULocalizedString(@"%@ of %@", @"The download progress in units of bytes, e.g. 100 KB of 1,0 MB"), [formatter stringFromByteCount:(long long)self.bytesDownloaded], [formatter stringFromByteCount:(long long)MAX(self.bytesDownloaded, self.expectedContentLength)]]]; + [_statusController setStatusText:[NSString stringWithFormat:SULocalizedStringFromTableInBundle(@"%@ of %@", SPARKLE_TABLE, sparkleBundle, @"The download progress in units of bytes, e.g. 100 KB of 1,0 MB"), [formatter stringFromByteCount:(long long)_bytesDownloaded], [formatter stringFromByteCount:(long long)MAX(_bytesDownloaded, _expectedContentLength)]]]; } else { - [self.statusController setStatusText:[NSString stringWithFormat:SULocalizedString(@"%@ downloaded", @"The download progress in a unit of bytes, e.g. 100 KB"), [formatter stringFromByteCount:(long long)self.bytesDownloaded]]]; + [_statusController setStatusText:[NSString stringWithFormat:SULocalizedStringFromTableInBundle(@"%@ downloaded", SPARKLE_TABLE, sparkleBundle, @"The download progress in a unit of bytes, e.g. 100 KB"), [formatter stringFromByteCount:(long long)_bytesDownloaded]]]; } } @@ -748,20 +775,24 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 { assert(NSThread.isMainThread); - self.cancellation = nil; + _cancellation = nil; [self createAndShowStatusControllerWithClosable:NO]; - [self.statusController beginActionWithTitle:SULocalizedString(@"Extracting update…", @"Take care not to overflow the status window.") maxProgressValue:1.0 statusText:nil]; - [self.statusController setProgressValue:0.0]; - [self.statusController setButtonTitle:SULocalizedString(@"Cancel", nil) target:nil action:nil isDefault:NO]; - [self.statusController setButtonEnabled:NO]; +#if SPARKLE_COPY_LOCALIZATIONS + NSBundle *sparkleBundle = SUSparkleBundle(); +#endif + + [_statusController beginActionWithTitle:SULocalizedStringFromTableInBundle(@"Extracting update…", SPARKLE_TABLE, sparkleBundle, @"Take care not to overflow the status window.") maxProgressValue:1.0 statusText:nil]; + [_statusController setProgressValue:0.0]; + [_statusController setButtonTitle:SULocalizedStringFromTableInBundle(@"Cancel", SPARKLE_TABLE, sparkleBundle, nil) target:nil action:nil isDefault:NO]; + [_statusController setButtonEnabled:NO]; } - (void)showExtractionReceivedProgress:(double)progress { assert(NSThread.isMainThread); - [self.statusController setProgressValue:progress]; + [_statusController setProgressValue:progress]; } - (void)showInstallingUpdateWithApplicationTerminated:(BOOL)applicationTerminated retryTerminatingApplication:(void (^)(void))retryTerminatingApplication @@ -770,14 +801,14 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 if (applicationTerminated) { // Note this will only show up if -showReadyToInstallAndRelaunch: was called beforehand - [self.statusController beginActionWithTitle:SULocalizedString(@"Installing update…", @"Take care not to overflow the status window.") maxProgressValue:0.0 statusText:nil]; - [self.statusController setButtonEnabled:NO]; + [_statusController beginActionWithTitle:SULocalizedStringFromTableInBundle(@"Installing update…", SPARKLE_TABLE, SUSparkleBundle(), @"Take care not to overflow the status window.") maxProgressValue:0.0 statusText:nil]; + [_statusController setButtonEnabled:NO]; } else { // The "quit" event can always be canceled or delayed by the application we're updating // So we can't easily predict how long the installation will take or if it won't happen right away // We close our status window because we don't want it persisting for too long and have it obscure other windows - [self.statusController close]; - self.statusController = nil; + [_statusController close]; + _statusController = nil; // Keep retry handler in case user tries to show update in focus again _retryTerminatingApplication = [retryTerminatingApplication copy]; @@ -789,33 +820,37 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 assert(NSThread.isMainThread); // Close window showing update is installing - [self.statusController close]; - self.statusController = nil; + [_statusController close]; + _statusController = nil; // Only show installed prompt when the app is not relaunched // When the app is relaunched, there is enough of a UI from relaunching the app. if (!relaunched) { +#if SPARKLE_COPY_LOCALIZATIONS + NSBundle *sparkleBundle = SUSparkleBundle(); +#endif + NSAlert *alert = [[NSAlert alloc] init]; - alert.messageText = SULocalizedString(@"Update Installed", nil); + alert.messageText = SULocalizedStringFromTableInBundle(@"Update Installed", SPARKLE_TABLE, sparkleBundle, nil); // Extract information from newly updated bundle if available NSString *hostName; NSString *hostVersion; - NSBundle *newBundle = [NSBundle bundleWithURL:self.oldHostBundleURL]; + NSBundle *newBundle = [NSBundle bundleWithURL:_oldHostBundleURL]; if (newBundle != nil) { SUHost *newHost = [[SUHost alloc] initWithBundle:newBundle]; hostName = newHost.name; hostVersion = newHost.displayVersion; } else { // This may happen if Sparkle's normalization is enabled - hostName = self.oldHostName; + hostName = _oldHostName; hostVersion = nil; } if (hostVersion != nil) { - alert.informativeText = [NSString stringWithFormat:SULocalizedString(@"%@ is now updated to version %@!", nil), hostName, hostVersion]; + alert.informativeText = [NSString stringWithFormat:SULocalizedStringFromTableInBundle(@"%@ is now updated to version %@!", SPARKLE_TABLE, sparkleBundle, nil), hostName, hostVersion]; } else { - alert.informativeText = [NSString stringWithFormat:SULocalizedString(@"%@ is now updated!", nil), hostName]; + alert.informativeText = [NSString stringWithFormat:SULocalizedStringFromTableInBundle(@"%@ is now updated!", SPARKLE_TABLE, sparkleBundle, nil), hostName]; } [self showAlert:alert secondaryAction:nil]; } @@ -829,7 +864,7 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 { assert(NSThread.isMainThread); - id delegate = self.delegate; + id delegate = _delegate; if ([delegate respondsToSelector:@selector(standardUserDriverWillFinishUpdateSession)]) { [delegate standardUserDriverWillFinishUpdateSession]; } @@ -840,25 +875,25 @@ static const NSTimeInterval SUScheduledUpdateIdleEventLeewayInterval = DEBUG ? 3 } _updateReceivedUserAttention = NO; - self.installUpdateHandler = nil; - self.cancellation = nil; + _installUpdateHandler = nil; + _cancellation = nil; _retryTerminatingApplication = nil; [self closeCheckingWindow]; - if (self.permissionPrompt) { - [self.permissionPrompt close]; - self.permissionPrompt = nil; + if (_permissionPrompt) { + [_permissionPrompt close]; + _permissionPrompt = nil; } - if (self.statusController) { - [self.statusController close]; - self.statusController = nil; + if (_statusController) { + [_statusController close]; + _statusController = nil; } - if (self.activeUpdateAlert) { - [self.activeUpdateAlert close]; - self.activeUpdateAlert = nil; + if (_activeUpdateAlert) { + [_activeUpdateAlert close]; + _activeUpdateAlert = nil; } [self _removeApplicationBecomeActiveObserver]; diff --git a/Sparkle/SPUStandardUserDriverDelegate.h b/Sparkle/SPUStandardUserDriverDelegate.h index b111a4a8..7ed3bff0 100644 --- a/Sparkle/SPUStandardUserDriverDelegate.h +++ b/Sparkle/SPUStandardUserDriverDelegate.h @@ -7,7 +7,15 @@ // #import +#if defined(BUILDING_SPARKLE_SOURCES_EXTERNALLY) +// Ignore incorrect warning +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wquoted-include-in-framework-header" +#import "SUExport.h" +#pragma clang diagnostic pop +#else #import +#endif NS_ASSUME_NONNULL_BEGIN diff --git a/Sparkle/SPUUIBasedUpdateDriver.h b/Sparkle/SPUUIBasedUpdateDriver.h index 38130a9f..0f7817f2 100644 --- a/Sparkle/SPUUIBasedUpdateDriver.h +++ b/Sparkle/SPUUIBasedUpdateDriver.h @@ -27,7 +27,7 @@ NS_ASSUME_NONNULL_BEGIN @class SUHost; @protocol SPUUserDriver, SPUUpdaterDelegate; -@interface SPUUIBasedUpdateDriver : NSObject +SPU_OBJC_DIRECT_MEMBERS @interface SPUUIBasedUpdateDriver : NSObject - (instancetype)initWithHost:(SUHost *)host applicationBundle:(NSBundle *)applicationBundle updater:(id)updater userDriver:(id )userDriver userInitiated:(BOOL)userInitiated updaterDelegate:(nullable id )updaterDelegate delegate:(id)delegate; diff --git a/Sparkle/SPUUIBasedUpdateDriver.m b/Sparkle/SPUUIBasedUpdateDriver.m index 3652e01c..e6f5b0ae 100644 --- a/Sparkle/SPUUIBasedUpdateDriver.m +++ b/Sparkle/SPUUIBasedUpdateDriver.m @@ -25,18 +25,16 @@ // Private class for downloading release notes @interface SPUReleaseNotesDriver: NSObject - -@property (nonatomic, readonly) SPUDownloadDriver *downloadDriver; -@property (nonatomic) void (^completionHandler)(SPUDownloadData * _Nullable, NSError * _Nullable ); - @end @implementation SPUReleaseNotesDriver +{ + SPUDownloadDriver *_downloadDriver; + + void (^_completionHandler)(SPUDownloadData * _Nullable, NSError * _Nullable); +} -@synthesize downloadDriver = _downloadDriver; -@synthesize completionHandler = _completionHandler; - -- (instancetype)initWithReleaseNotesURL:(NSURL *)releaseNotesURL httpHeaders:(NSDictionary * _Nullable)httpHeaders userAgent:(NSString * _Nullable)userAgent host:(SUHost *)host completionHandler:(void (^)(SPUDownloadData * _Nullable, NSError * _Nullable))completionHandler +- (instancetype)initWithReleaseNotesURL:(NSURL *)releaseNotesURL httpHeaders:(NSDictionary * _Nullable)httpHeaders userAgent:(NSString * _Nullable)userAgent host:(SUHost *)host completionHandler:(void (^)(SPUDownloadData * _Nullable, NSError * _Nullable))completionHandler SPU_OBJC_DIRECT { self = [super init]; if (self != nil) { @@ -48,66 +46,55 @@ return self; } -- (void)startDownload +- (void)startDownload SPU_OBJC_DIRECT { - [self.downloadDriver downloadFile]; + [_downloadDriver downloadFile]; } - (void)downloadDriverDidDownloadData:(SPUDownloadData *)downloadData { - if (self.completionHandler != nil) { - self.completionHandler(downloadData, nil); - self.completionHandler = nil; + if (_completionHandler != nil) { + _completionHandler(downloadData, nil); + _completionHandler = nil; } } - (void)downloadDriverDidFailToDownloadFileWithError:(nonnull NSError *)error { - if (self.completionHandler != nil) { - self.completionHandler(nil, error); - self.completionHandler = nil; + if (_completionHandler != nil) { + _completionHandler(nil, error); + _completionHandler = nil; } } -- (void)cleanup:(void (^)(void))cleanupHandler +- (void)cleanup:(void (^)(void))cleanupHandler SPU_OBJC_DIRECT { - self.completionHandler = nil; - [self.downloadDriver cleanup:cleanupHandler]; + _completionHandler = nil; + [_downloadDriver cleanup:cleanupHandler]; } @end @interface SPUUIBasedUpdateDriver() - -@property (nonatomic, readonly) SPUCoreBasedUpdateDriver *coreDriver; -@property (nonatomic, readonly) SUHost *host; -@property (nonatomic, weak, readonly) id updater; -@property (nonatomic, readonly) BOOL userInitiated; -@property (weak, nonatomic, readonly) id updaterDelegate; -@property (nonatomic, weak, readonly) id delegate; -@property (nonatomic, readonly) id userDriver; -@property (nonatomic) SPUReleaseNotesDriver *releaseNotesDriver; -@property (nonatomic) BOOL resumingInstallingUpdate; -@property (nonatomic) BOOL resumingDownloadedInfoOrUpdate; -@property (nonatomic, nullable) NSDictionary *httpHeaders; -@property (nonatomic, nullable) NSString *userAgent; - @end @implementation SPUUIBasedUpdateDriver - -@synthesize coreDriver = _coreDriver; -@synthesize host = _host; -@synthesize updater = _updater; -@synthesize userInitiated = _userInitiated; -@synthesize updaterDelegate = _updaterDelegate; -@synthesize userDriver = _userDriver; -@synthesize releaseNotesDriver = _releaseNotesDriver; -@synthesize delegate = _delegate; -@synthesize resumingInstallingUpdate = _resumingInstallingUpdate; -@synthesize resumingDownloadedInfoOrUpdate = _resumingDownloadedInfoOrUpdate; -@synthesize httpHeaders = _httpHeaders; -@synthesize userAgent = _userAgent; +{ + SPUCoreBasedUpdateDriver *_coreDriver; + SUHost *_host; + id _userDriver; + SPUReleaseNotesDriver *_releaseNotesDriver; + NSDictionary *_httpHeaders; + NSString *_userAgent; + + __weak id _updater; + __weak id _updaterDelegate; + __weak id _delegate; + + BOOL _userInitiated; + BOOL _resumingInstallingUpdate; + BOOL _resumingDownloadedInfoOrUpdate; +} - (instancetype)initWithHost:(SUHost *)host applicationBundle:(NSBundle *)applicationBundle updater:(id)updater userDriver:(id )userDriver userInitiated:(BOOL)userInitiated updaterDelegate:(nullable id )updaterDelegate delegate:(id)delegate { @@ -129,71 +116,73 @@ - (void)setCompletionHandler:(SPUUpdateDriverCompletion)completionBlock { - [self.coreDriver setCompletionHandler:completionBlock]; + [_coreDriver setCompletionHandler:completionBlock]; } - (void)setUpdateWillInstallHandler:(void (^)(void))updateWillInstallHandler { - [self.coreDriver setUpdateWillInstallHandler:updateWillInstallHandler]; + [_coreDriver setUpdateWillInstallHandler:updateWillInstallHandler]; } -- (void)_clearSkippedUpdatesIfUserInitiated +- (void)_clearSkippedUpdatesIfUserInitiated SPU_OBJC_DIRECT { - if (self.userInitiated) { - [SPUSkippedUpdate clearSkippedUpdateForHost:self.host]; + if (_userInitiated) { + [SPUSkippedUpdate clearSkippedUpdateForHost:_host]; } } - (void)checkForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders inBackground:(BOOL)background { - self.httpHeaders = httpHeaders; - self.userAgent = userAgent; + _httpHeaders = httpHeaders; + _userAgent = userAgent; [self _clearSkippedUpdatesIfUserInitiated]; - [self.coreDriver checkForUpdatesAtAppcastURL:appcastURL withUserAgent:userAgent httpHeaders:httpHeaders inBackground:background requiresSilentInstall:NO]; + [_coreDriver checkForUpdatesAtAppcastURL:appcastURL withUserAgent:userAgent httpHeaders:httpHeaders inBackground:background requiresSilentInstall:NO]; } - (void)resumeInstallingUpdate { [self _clearSkippedUpdatesIfUserInitiated]; - self.resumingInstallingUpdate = YES; - [self.coreDriver resumeInstallingUpdate]; + _resumingInstallingUpdate = YES; + [_coreDriver resumeInstallingUpdate]; } - (void)resumeUpdate:(id)resumableUpdate { [self _clearSkippedUpdatesIfUserInitiated]; - self.resumingDownloadedInfoOrUpdate = YES; - [self.coreDriver resumeUpdate:resumableUpdate]; + _resumingDownloadedInfoOrUpdate = YES; + [_coreDriver resumeUpdate:resumableUpdate]; } - (void)basicDriverDidFinishLoadingAppcast { - if ([self.delegate respondsToSelector:@selector(basicDriverDidFinishLoadingAppcast)]) { - [self.delegate basicDriverDidFinishLoadingAppcast]; + id delegate = _delegate; + if ([delegate respondsToSelector:@selector(basicDriverDidFinishLoadingAppcast)]) { + [delegate basicDriverDidFinishLoadingAppcast]; } } - (void)basicDriverDidFindUpdateWithAppcastItem:(SUAppcastItem *)updateItem secondaryAppcastItem:(SUAppcastItem * _Nullable)secondaryUpdateItem { - id updaterDelegate = self.updaterDelegate; + id updaterDelegate = _updaterDelegate; + id delegate = _delegate; SPUUserUpdateStage stage; // Major upgrades and information only updates are not downloaded automatically - if (self.resumingDownloadedInfoOrUpdate && !updateItem.majorUpgrade && !updateItem.informationOnlyUpdate) { + if (_resumingDownloadedInfoOrUpdate && !updateItem.majorUpgrade && !updateItem.informationOnlyUpdate) { stage = SPUUserUpdateStageDownloaded; - } else if (self.resumingInstallingUpdate) { + } else if (_resumingInstallingUpdate) { stage = SPUUserUpdateStageInstalling; } else { stage = SPUUserUpdateStageNotDownloaded; } - SPUUserUpdateState *state = [[SPUUserUpdateState alloc] initWithStage:stage userInitiated:self.userInitiated]; + SPUUserUpdateState *state = [[SPUUserUpdateState alloc] initWithStage:stage userInitiated:_userInitiated]; - [self.userDriver showUpdateFoundWithAppcastItem:updateItem state:state reply:^(SPUUserUpdateChoice userChoice) { + [_userDriver showUpdateFoundWithAppcastItem:updateItem state:state reply:^(SPUUserUpdateChoice userChoice) { dispatch_async(dispatch_get_main_queue(), ^{ // Rule out invalid choices @@ -204,47 +193,50 @@ validatedChoice = userChoice; } - if ([self.updaterDelegate respondsToSelector:@selector(updater:userDidMakeChoice:forUpdate:state:)]) { - [self.updaterDelegate updater:self.updater userDidMakeChoice:validatedChoice forUpdate:updateItem state:state]; - } else if (validatedChoice == SPUUserUpdateChoiceSkip && [self.updaterDelegate respondsToSelector:@selector(updater:userDidSkipThisVersion:)]) { -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdeprecated-declarations" - [self.updaterDelegate updater:self.updater userDidSkipThisVersion:updateItem]; -#pragma clang diagnostic pop + id updater = self->_updater; + if (updater != nil) { + if ([updaterDelegate respondsToSelector:@selector(updater:userDidMakeChoice:forUpdate:state:)]) { + [updaterDelegate updater:updater userDidMakeChoice:validatedChoice forUpdate:updateItem state:state]; + } else if (validatedChoice == SPUUserUpdateChoiceSkip && [updaterDelegate respondsToSelector:@selector(updater:userDidSkipThisVersion:)]) { + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Wdeprecated-declarations" + [updaterDelegate updater:updater userDidSkipThisVersion:updateItem]; + #pragma clang diagnostic pop + } } switch (validatedChoice) { case SPUUserUpdateChoiceInstall: { switch (stage) { case SPUUserUpdateStageDownloaded: - [self.coreDriver extractDownloadedUpdate]; + [self->_coreDriver extractDownloadedUpdate]; break; case SPUUserUpdateStageInstalling: - [self.coreDriver finishInstallationWithResponse:validatedChoice displayingUserInterface:YES]; + [self->_coreDriver finishInstallationWithResponse:validatedChoice displayingUserInterface:YES]; break; case SPUUserUpdateStageNotDownloaded: - [self.coreDriver downloadUpdateFromAppcastItem:updateItem secondaryAppcastItem:secondaryUpdateItem inBackground:NO]; + [self->_coreDriver downloadUpdateFromAppcastItem:updateItem secondaryAppcastItem:secondaryUpdateItem inBackground:NO]; break; } break; } case SPUUserUpdateChoiceSkip: { - [SPUSkippedUpdate skipUpdate:updateItem host:self.host]; + [SPUSkippedUpdate skipUpdate:updateItem host:self->_host]; switch (stage) { case SPUUserUpdateStageDownloaded: case SPUUserUpdateStageNotDownloaded: // Informational and major updates can be resumed too, so make sure we check - // self.resumingDownloadedInfoOrUpdate instead of the stage we pass to user driver - if (self.resumingDownloadedInfoOrUpdate) { - [self.coreDriver clearDownloadedUpdate]; + // self->_resumingDownloadedInfoOrUpdate instead of the stage we pass to user driver + if (self->_resumingDownloadedInfoOrUpdate) { + [self->_coreDriver clearDownloadedUpdate]; } - [self.delegate uiDriverIsRequestingAbortUpdateWithError:nil]; + [delegate uiDriverIsRequestingAbortUpdateWithError:nil]; break; case SPUUserUpdateStageInstalling: - [self.coreDriver finishInstallationWithResponse:validatedChoice displayingUserInterface:YES]; + [self->_coreDriver finishInstallationWithResponse:validatedChoice displayingUserInterface:YES]; break; } @@ -254,11 +246,11 @@ switch (stage) { case SPUUserUpdateStageDownloaded: case SPUUserUpdateStageNotDownloaded: { - [self.delegate uiDriverIsRequestingAbortUpdateWithError:nil]; + [self->_delegate uiDriverIsRequestingAbortUpdateWithError:nil]; break; } case SPUUserUpdateStageInstalling: { - [self.coreDriver finishInstallationWithResponse:validatedChoice displayingUserInterface:YES]; + [self->_coreDriver finishInstallationWithResponse:validatedChoice displayingUserInterface:YES]; break; } } @@ -269,24 +261,26 @@ }); }]; - if ([self.delegate respondsToSelector:@selector(uiDriverDidShowUpdate)]) { - [self.delegate uiDriverDidShowUpdate]; + if ([delegate respondsToSelector:@selector(uiDriverDidShowUpdate)]) { + [delegate uiDriverDidShowUpdate]; } - if (updateItem.releaseNotesURL != nil && (![updaterDelegate respondsToSelector:@selector(updater:shouldDownloadReleaseNotesForUpdate:)] || [updaterDelegate updater:self.updater shouldDownloadReleaseNotesForUpdate:updateItem])) { + if (updateItem.releaseNotesURL != nil && (![updaterDelegate respondsToSelector:@selector(updater:shouldDownloadReleaseNotesForUpdate:)] || [updaterDelegate updater:_updater shouldDownloadReleaseNotesForUpdate:updateItem])) { __weak __typeof__(self) weakSelf = self; - self.releaseNotesDriver = [[SPUReleaseNotesDriver alloc] initWithReleaseNotesURL:updateItem.releaseNotesURL httpHeaders:self.httpHeaders userAgent:self.userAgent host:self.host completionHandler:^(SPUDownloadData * _Nullable downloadData, NSError * _Nullable error) { + _releaseNotesDriver = [[SPUReleaseNotesDriver alloc] initWithReleaseNotesURL:updateItem.releaseNotesURL httpHeaders:_httpHeaders userAgent:_userAgent host:_host completionHandler:^(SPUDownloadData * _Nullable downloadData, NSError * _Nullable error) { __typeof__(self) strongSelf = weakSelf; - id userDriver = strongSelf.userDriver; - if (downloadData != nil) { - [userDriver showUpdateReleaseNotesWithDownloadData:(SPUDownloadData * _Nonnull)downloadData]; - } else { - [userDriver showUpdateReleaseNotesFailedToDownloadWithError:(NSError * _Nonnull)error]; + if (strongSelf != nil) { + id userDriver = strongSelf->_userDriver; + if (downloadData != nil) { + [userDriver showUpdateReleaseNotesWithDownloadData:(SPUDownloadData * _Nonnull)downloadData]; + } else { + [userDriver showUpdateReleaseNotesFailedToDownloadWithError:(NSError * _Nonnull)error]; + } } }]; - [self.releaseNotesDriver startDownload]; + [_releaseNotesDriver startDownload]; } } @@ -294,58 +288,62 @@ { void (^cancelDownload)(void) = ^{ dispatch_async(dispatch_get_main_queue(), ^{ - if ([self.updaterDelegate respondsToSelector:@selector((userDidCancelDownload:))]) { - [self.updaterDelegate userDidCancelDownload:self.updater]; + id updaterDelegate = self->_updaterDelegate; + if ([updaterDelegate respondsToSelector:@selector((userDidCancelDownload:))]) { + [updaterDelegate userDidCancelDownload:self->_updater]; } - [self.delegate uiDriverIsRequestingAbortUpdateWithError:nil]; + [self->_delegate uiDriverIsRequestingAbortUpdateWithError:nil]; }); }; - [self.userDriver showDownloadInitiatedWithCancellation:cancelDownload]; + [_userDriver showDownloadInitiatedWithCancellation:cancelDownload]; } - (void)downloadDriverDidReceiveExpectedContentLength:(uint64_t)expectedContentLength { - [self.userDriver showDownloadDidReceiveExpectedContentLength:expectedContentLength]; + [_userDriver showDownloadDidReceiveExpectedContentLength:expectedContentLength]; } - (void)downloadDriverDidReceiveDataOfLength:(uint64_t)length { - [self.userDriver showDownloadDidReceiveDataOfLength:length]; + [_userDriver showDownloadDidReceiveDataOfLength:length]; } - (void)coreDriverDidStartExtractingUpdate { - [self.userDriver showDownloadDidStartExtractingUpdate]; + [_userDriver showDownloadDidStartExtractingUpdate]; } - (void)installerDidStartInstallingWithApplicationTerminated:(BOOL)applicationTerminated { - if ([self.userDriver respondsToSelector:@selector(showInstallingUpdateWithApplicationTerminated:retryTerminatingApplication:)]) { + if ([_userDriver respondsToSelector:@selector(showInstallingUpdateWithApplicationTerminated:retryTerminatingApplication:)]) { __weak __typeof__(self) weakSelf = self; - [self.userDriver showInstallingUpdateWithApplicationTerminated:applicationTerminated retryTerminatingApplication:^{ + [_userDriver showInstallingUpdateWithApplicationTerminated:applicationTerminated retryTerminatingApplication:^{ if (!applicationTerminated) { dispatch_async(dispatch_get_main_queue(), ^{ - [weakSelf.coreDriver finishInstallationWithResponse:SPUUserUpdateChoiceInstall displayingUserInterface:YES]; + __typeof__(self) strongSelf = weakSelf; + if (strongSelf != nil) { + [strongSelf->_coreDriver finishInstallationWithResponse:SPUUserUpdateChoiceInstall displayingUserInterface:YES]; + } }); } }]; - } else if ([self.userDriver respondsToSelector:@selector(showInstallingUpdateWithApplicationTerminated:)]) { + } else if ([_userDriver respondsToSelector:@selector(showInstallingUpdateWithApplicationTerminated:)]) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" - [self.userDriver showInstallingUpdateWithApplicationTerminated:applicationTerminated]; + [_userDriver showInstallingUpdateWithApplicationTerminated:applicationTerminated]; #pragma clang diagnostic pop } else { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" - if ([self.userDriver respondsToSelector:@selector(showInstallingUpdate)]) { - [self.userDriver showInstallingUpdate]; + if ([_userDriver respondsToSelector:@selector(showInstallingUpdate)]) { + [_userDriver showInstallingUpdate]; } if (!applicationTerminated) { - if ([self.userDriver respondsToSelector:@selector(showSendingTerminationSignal)]) { - [self.userDriver showSendingTerminationSignal]; + if ([_userDriver respondsToSelector:@selector(showSendingTerminationSignal)]) { + [_userDriver showSendingTerminationSignal]; } } #pragma clang diagnostic pop @@ -354,15 +352,15 @@ - (void)installerDidExtractUpdateWithProgress:(double)progress { - [self.userDriver showExtractionReceivedProgress:progress]; + [_userDriver showExtractionReceivedProgress:progress]; } - (void)installerDidFinishPreparationAndWillInstallImmediately:(BOOL)willInstallImmediately silently:(BOOL)__unused willInstallSilently { if (!willInstallImmediately) { - [self.userDriver showReadyToInstallAndRelaunch:^(SPUUserUpdateChoice choice) { + [_userDriver showReadyToInstallAndRelaunch:^(SPUUserUpdateChoice choice) { dispatch_async(dispatch_get_main_queue(), ^{ - [self.coreDriver finishInstallationWithResponse:choice displayingUserInterface:YES]; + [self->_coreDriver finishInstallationWithResponse:choice displayingUserInterface:YES]; }); }]; } @@ -370,12 +368,12 @@ - (void)installerDidFinishInstallationAndRelaunched:(BOOL)relaunched acknowledgement:(void(^)(void))acknowledgement { - if ([self.userDriver respondsToSelector:@selector(showUpdateInstalledAndRelaunched:acknowledgement:)]) { - [self.userDriver showUpdateInstalledAndRelaunched:relaunched acknowledgement:acknowledgement]; + if ([_userDriver respondsToSelector:@selector(showUpdateInstalledAndRelaunched:acknowledgement:)]) { + [_userDriver showUpdateInstalledAndRelaunched:relaunched acknowledgement:acknowledgement]; } else { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" - [self.userDriver showUpdateInstallationDidFinishWithAcknowledgement:acknowledgement]; + [_userDriver showUpdateInstallationDidFinishWithAcknowledgement:acknowledgement]; #pragma clang diagnostic pop } } @@ -383,39 +381,39 @@ - (void)basicDriverIsRequestingAbortUpdateWithError:(nullable NSError *)error { // A delegate may want to handle this type of error specially - [self.delegate basicDriverIsRequestingAbortUpdateWithError:error]; + [_delegate basicDriverIsRequestingAbortUpdateWithError:error]; } - (void)coreDriverIsRequestingAbortUpdateWithError:(NSError *)error { // A delegate may want to handle this type of error specially - [self.delegate coreDriverIsRequestingAbortUpdateWithError:error]; + [_delegate coreDriverIsRequestingAbortUpdateWithError:error]; } -- (void)_abortUpdateWithError:(nullable NSError *)error showErrorToUser:(BOOL)showErrorToUser +- (void)_abortUpdateWithError:(nullable NSError *)error showErrorToUser:(BOOL)showErrorToUser SPU_OBJC_DIRECT { void (^abortUpdate)(void) = ^{ if (showErrorToUser) { - [self.userDriver dismissUpdateInstallation]; + [self->_userDriver dismissUpdateInstallation]; } - [self.coreDriver abortUpdateAndShowNextUpdateImmediately:NO error:error]; + [self->_coreDriver abortUpdateAndShowNextUpdateImmediately:NO error:error]; }; if (error != nil && showErrorToUser) { NSError *nonNullError = error; if (error.code == SUNoUpdateError) { - if ([self.userDriver respondsToSelector:@selector(showUpdateNotFoundWithError:acknowledgement:)]) { - [self.userDriver showUpdateNotFoundWithError:(NSError * _Nonnull)error acknowledgement:^{ + if ([_userDriver respondsToSelector:@selector(showUpdateNotFoundWithError:acknowledgement:)]) { + [_userDriver showUpdateNotFoundWithError:(NSError * _Nonnull)error acknowledgement:^{ dispatch_async(dispatch_get_main_queue(), ^{ abortUpdate(); }); }]; - } else if ([self.userDriver respondsToSelector:@selector(showUpdateNotFoundWithAcknowledgement:)]) { + } else if ([_userDriver respondsToSelector:@selector(showUpdateNotFoundWithAcknowledgement:)]) { // Eventually we should remove this fallback once clients adopt -showUpdateNotFoundWithError:acknowledgement: #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" - [self.userDriver showUpdateNotFoundWithAcknowledgement:^{ + [_userDriver showUpdateNotFoundWithAcknowledgement:^{ #pragma clang diagnostic pop dispatch_async(dispatch_get_main_queue(), ^{ abortUpdate(); @@ -425,7 +423,7 @@ } else if (error.code == SUInstallationCanceledError || error.code == SUInstallationAuthorizeLaterError) { abortUpdate(); } else { - [self.userDriver showUpdaterError:nonNullError acknowledgement:^{ + [_userDriver showUpdaterError:nonNullError acknowledgement:^{ dispatch_async(dispatch_get_main_queue(), ^{ abortUpdate(); }); @@ -438,8 +436,8 @@ - (void)abortUpdateWithError:(nullable NSError *)error showErrorToUser:(BOOL)showErrorToUser { - if (self.releaseNotesDriver != nil) { - [self.releaseNotesDriver cleanup:^{ + if (_releaseNotesDriver != nil) { + [_releaseNotesDriver cleanup:^{ [self _abortUpdateWithError:error showErrorToUser:showErrorToUser]; }]; } else { diff --git a/Sparkle/SPUUpdatePermissionRequest.h b/Sparkle/SPUUpdatePermissionRequest.h index 010e50bf..c1a362c3 100644 --- a/Sparkle/SPUUpdatePermissionRequest.h +++ b/Sparkle/SPUUpdatePermissionRequest.h @@ -7,7 +7,16 @@ // #import + +#if defined(BUILDING_SPARKLE_SOURCES_EXTERNALLY) +// Ignore incorrect warning +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wquoted-include-in-framework-header" +#import "SUExport.h" +#pragma clang diagnostic pop +#else #import +#endif NS_ASSUME_NONNULL_BEGIN diff --git a/Sparkle/SPUUpdatePermissionRequest.m b/Sparkle/SPUUpdatePermissionRequest.m index aea0f70f..c6e54a23 100644 --- a/Sparkle/SPUUpdatePermissionRequest.m +++ b/Sparkle/SPUUpdatePermissionRequest.m @@ -34,7 +34,7 @@ static NSString *SPUUpdatePermissionRequestSystemProfileKey = @"SPUUpdatePermiss - (void)encodeWithCoder:(NSCoder *)encoder { - [encoder encodeObject:self.systemProfile forKey:SPUUpdatePermissionRequestSystemProfileKey]; + [encoder encodeObject:_systemProfile forKey:SPUUpdatePermissionRequestSystemProfileKey]; } - (instancetype)initWithSystemProfile:(NSArray *> *)systemProfile diff --git a/Sparkle/SPUUpdater.h b/Sparkle/SPUUpdater.h index 00aae592..1cb82ffa 100644 --- a/Sparkle/SPUUpdater.h +++ b/Sparkle/SPUUpdater.h @@ -7,8 +7,18 @@ // #import + +#if defined(BUILDING_SPARKLE_SOURCES_EXTERNALLY) +// Ignore incorrect warning +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wquoted-include-in-framework-header" +#import "SUExport.h" +#import "SPUUserDriver.h" +#pragma clang diagnostic pop +#else #import #import +#endif NS_ASSUME_NONNULL_BEGIN diff --git a/Sparkle/SPUUpdater.m b/Sparkle/SPUUpdater.m index 9403fca8..7121aaa6 100644 --- a/Sparkle/SPUUpdater.m +++ b/Sparkle/SPUUpdater.m @@ -46,56 +46,42 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification @interface SPUUpdater () -@property (readonly, copy) NSURL *parameterizedFeedURL; - -@property (nonatomic, readonly) id userDriver; -@property (weak, readonly, nullable) id delegate; -@property (nonatomic) id driver; -@property (nonatomic, readonly) SUHost *host; -@property (nonatomic, readonly) SUHost *mainBundleHost; -@property (nonatomic, readonly) NSBundle *applicationBundle; -@property (nonatomic, readonly) NSBundle *sparkleBundle; -@property (nonatomic, readonly) SPUUpdaterSettings *updaterSettings; -@property (nonatomic, readonly) SPUUpdaterCycle *updaterCycle; -@property (nonatomic, readonly) SPUUpdaterTimer *updaterTimer; -@property (nonatomic) BOOL startedUpdater; -@property (nonatomic, nullable) id resumableUpdate; +// These two properties are needed for KVO @property (nonatomic) BOOL sessionInProgress; @property (nonatomic) BOOL canCheckForUpdates; -@property (nonatomic) BOOL showingPermissionRequest; - -@property (nonatomic, copy) NSDate *updateLastCheckedDate; - -@property (nonatomic) BOOL loggedATSWarning; -@property (nonatomic) BOOL loggedNoSecureKeyWarning; @end @implementation SPUUpdater { + id _userDriver; + id _driver; + SUHost *_host; + SUHost *_mainBundleHost; + NSBundle *_applicationBundle; + NSBundle *_sparkleBundle; + SPUUpdaterSettings *_updaterSettings; + SPUUpdaterCycle *_updaterCycle; + SPUUpdaterTimer *_updaterTimer; + id _resumableUpdate; + NSDate *_updateLastCheckedDate; + NSURL *_parameterizedFeedURL; + + __weak id _delegate; + + BOOL _startedUpdater; + BOOL _sessionInProgress; + BOOL _canCheckForUpdates; + BOOL _showingPermissionRequest; + BOOL _loggedATSWarning; + BOOL _loggedNoSecureKeyWarning; BOOL _updatingMainBundle; } -@synthesize delegate = _delegate; -@synthesize userDriver = _userDriver; @synthesize userAgentString = _userAgentString; -@synthesize httpHeaders; -@synthesize driver; -@synthesize host = _host; -@synthesize mainBundleHost = _mainBundleHost; -@synthesize applicationBundle = _applicationBundle; -@synthesize updaterSettings = _updaterSettings; -@synthesize updaterCycle = _updaterCycle; -@synthesize updaterTimer = _updaterTimer; -@synthesize sparkleBundle = _sparkleBundle; -@synthesize startedUpdater = _startedUpdater; -@synthesize resumableUpdate = _resumableUpdate; +@synthesize httpHeaders = _httpHeaders; @synthesize sessionInProgress = _sessionInProgress; @synthesize canCheckForUpdates = _canCheckForUpdates; -@synthesize showingPermissionRequest = _showingPermissionRequest; -@synthesize updateLastCheckedDate = _updateLastCheckedDate; -@synthesize loggedATSWarning = _loggedATSWarning; -@synthesize loggedNoSecureKeyWarning = _loggedNoSecureKeyWarning; #if DEBUG + (void)initialize @@ -168,7 +154,7 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification - (BOOL)startUpdater:(NSError * __autoreleasing *)error { - if (self.startedUpdater) { + if (_startedUpdater) { return YES; } @@ -176,12 +162,12 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification return NO; } - if ([self.userDriver respondsToSelector:@selector(resetTimeSinceOpportuneUpdateNotice)]) { - [(id)self.userDriver resetTimeSinceOpportuneUpdateNotice]; + if ([_userDriver respondsToSelector:@selector(resetTimeSinceOpportuneUpdateNotice)]) { + [(id)_userDriver resetTimeSinceOpportuneUpdateNotice]; } - self.startedUpdater = YES; - self.canCheckForUpdates = YES; + _startedUpdater = YES; + [self setCanCheckForUpdates:YES]; // Start updater on next update cycle so we make sure the application invoking the updater is ready // This also gives the developer a cycle to check for updates before Sparkle's update cycle scheduler kicks in @@ -190,13 +176,13 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification // We perform this check one runloop cycle after starting the updater to give the developer // a chance to call -clearFeedURLFromUserDefaults before this warning can show up if (self->_updatingMainBundle) { - NSString *appcastUserDefaultsString = [self.host objectForUserDefaultsKey:SUFeedURLKey]; + NSString *appcastUserDefaultsString = [self->_host objectForUserDefaultsKey:SUFeedURLKey]; if (appcastUserDefaultsString != nil) { - SULog(SULogLevelError, @"Warning: A feed URL was found stored in user defaults for %@. This was likely set using -[SPUUpdater setFeedURL:] which is deprecated. Please migrate away from using this API and call -[SPUUpdater clearFeedURLFromUserDefaults] to remove any stored defaults, otherwise Sparkle may continue to use the feed stored from the defaults. If the feed url was set via a defaults write command for testing purposes, then please ignore this warning.", self.host.name); + SULog(SULogLevelError, @"Warning: A feed URL was found stored in user defaults for %@. This was likely set using -[SPUUpdater setFeedURL:] which is deprecated. Please migrate away from using this API and call -[SPUUpdater clearFeedURLFromUserDefaults] to remove any stored defaults, otherwise Sparkle may continue to use the feed stored from the defaults. If the feed url was set via a defaults write command for testing purposes, then please ignore this warning.", self->_host.name); } } - if (!self.sessionInProgress) { + if (!self->_sessionInProgress) { [self startUpdateCycle]; } }); @@ -204,7 +190,7 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification return YES; } -- (BOOL)checkATSIssueForBundle:(NSBundle * _Nullable)bundle getBundleExists:(BOOL *)bundleExists +- (BOOL)checkATSIssueForBundle:(NSBundle * _Nullable)bundle getBundleExists:(BOOL *)bundleExists SPU_OBJC_DIRECT { if (bundleExists != NULL) { *bundleExists = (bundle != nil); @@ -217,11 +203,11 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification return ([bundle objectForInfoDictionaryKey:@"NSAppTransportSecurity"] == nil); } -- (BOOL)checkIfConfiguredProperlyAndRequireFeedURL:(BOOL)requireFeedURL validateXPCServices:(BOOL)validateXPCServices error:(NSError * __autoreleasing *)error +- (BOOL)checkIfConfiguredProperlyAndRequireFeedURL:(BOOL)requireFeedURL validateXPCServices:(BOOL)validateXPCServices error:(NSError * __autoreleasing *)error SPU_OBJC_DIRECT { - NSString *hostName = self.host.name; + NSString *hostName = _host.name; - if (self.sparkleBundle == nil) { + if (_sparkleBundle == nil) { if (error != NULL) { *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInvalidUpdaterError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"%@ can't find Sparkle.framework it belongs to in %@.", NSStringFromClass([self class]), hostName] }]; } @@ -235,14 +221,14 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification return NO; } - if (!self.host.validVersion) { + if (!_host.validVersion) { if (error != NULL) { *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInvalidHostVersionError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Sparkle cannot target a bundle that does not have a valid version for %@.", hostName] }]; } return NO; } - SUHost *mainBundleHost = self.mainBundleHost; + SUHost *mainBundleHost = _mainBundleHost; if (validateXPCServices) { // Check that all enabled XPC Services are embedded NSArray *xpcServiceIDs = @[@INSTALLER_LAUNCHER_NAME, @DOWNLOADER_NAME, @INSTALLER_CONNECTION_NAME, @INSTALLER_STATUS_NAME]; @@ -254,7 +240,7 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification NSString *xpcServiceBundleName = [xpcServiceIDs[xpcServiceIndex] stringByAppendingPathExtension:@"xpc"]; if ([mainBundleHost boolForInfoDictionaryKey:xpcServiceEnabledKey]) { - NSURL *xpcServiceBundleURL = [[self.sparkleBundle.bundleURL URLByAppendingPathComponent:@"XPCServices"] URLByAppendingPathComponent:xpcServiceBundleName]; + NSURL *xpcServiceBundleURL = [[_sparkleBundle.bundleURL URLByAppendingPathComponent:@"XPCServices"] URLByAppendingPathComponent:xpcServiceBundleName]; if (![xpcServiceBundleURL checkResourceIsReachableAndReturnError:NULL]) { if (error != NULL) { @@ -292,12 +278,12 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification if (feedURL != nil) { servingOverHttps = [[[feedURL scheme] lowercaseString] isEqualToString:@"https"]; - if (!servingOverHttps && !self.loggedATSWarning) { + if (!servingOverHttps && !_loggedATSWarning) { BOOL foundXPCDownloaderService = NO; NSBundle *downloaderBundle; if ([mainBundleHost boolForInfoDictionaryKey:SUEnableDownloaderServiceKey]) { - NSURL *downloaderServiceBundleURL = [[[self.sparkleBundle.bundleURL URLByAppendingPathComponent:@"XPCServices"] URLByAppendingPathComponent:@DOWNLOADER_NAME] URLByAppendingPathExtension:@"xpc"]; + NSURL *downloaderServiceBundleURL = [[[_sparkleBundle.bundleURL URLByAppendingPathComponent:@"XPCServices"] URLByAppendingPathComponent:@DOWNLOADER_NAME] URLByAppendingPathExtension:@"xpc"]; downloaderBundle = [NSBundle bundleWithURL:downloaderServiceBundleURL]; } else { downloaderBundle = nil; @@ -320,16 +306,17 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification // Just log a warning. Don't outright fail in case we are wrong (eg: app is linked on an old SDK where ATS doesn't take effect) SULog(SULogLevelDefault, @"The feed URL (%@) may need to change to use HTTPS.\nFor more information: https://sparkle-project.org/documentation/app-transport-security", [feedURL absoluteString]); - self.loggedATSWarning = YES; + _loggedATSWarning = YES; } } } - SUPublicKeys *publicKeys = self.host.publicKeys; + SUPublicKeys *publicKeys = _host.publicKeys; BOOL hasAnyPublicKey = publicKeys.hasAnyKeys; +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT if (!hasAnyPublicKey) { // If we failed to retrieve a DSA key but the bundle specifies a path to one, we should consider this a configuration failure - NSString *publicDSAKeyFileKey = [self.host publicDSAKeyFileKey]; + NSString *publicDSAKeyFileKey = [_host publicDSAKeyFileKey]; if (publicDSAKeyFileKey != nil) { if (error != NULL) { *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUNoPublicDSAFoundError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"The DSA public key '%@' could not be found for %@.", publicDSAKeyFileKey, hostName] }]; @@ -337,6 +324,7 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification return NO; } } +#endif // Don't allow invalid EdDSA public keys if (publicKeys.ed25519PubKeyStatus == SUSigningInputStatusInvalid) { @@ -353,10 +341,10 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification } return NO; } else { - if (_updatingMainBundle && !self.loggedNoSecureKeyWarning) { + if (_updatingMainBundle && !_loggedNoSecureKeyWarning) { SULog(SULogLevelError, @"Error: Serving updates without an EdDSA key and only using Apple Code Signing is deprecated and may be unsupported in a future release. Visit Sparkle's documentation for more information: https://sparkle-project.org/documentation/#3-segue-for-security-concerns"); - self.loggedNoSecureKeyWarning = YES; + _loggedNoSecureKeyWarning = YES; } } } else if (publicKeys.ed25519PubKey == nil) { @@ -372,37 +360,39 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification return YES; } -- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], [self.host bundlePath]]; } +- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], [_host bundlePath]]; } -- (void)startUpdateCycle +- (void)startUpdateCycle SPU_OBJC_DIRECT { BOOL shouldPrompt = NO; - BOOL hasLaunchedBefore = [self.host boolForUserDefaultsKey:SUHasLaunchedBeforeKey]; + BOOL hasLaunchedBefore = [_host boolForUserDefaultsKey:SUHasLaunchedBeforeKey]; + id delegate = _delegate; + // If the user has been asked about automatic checks, don't bother prompting // When the user answers to the permission prompt, this will be set to either @YES or @NO instead of nil - if ([self.host objectForUserDefaultsKey:SUEnableAutomaticChecksKey] != nil) { + if ([_host objectForUserDefaultsKey:SUEnableAutomaticChecksKey] != nil) { shouldPrompt = NO; } // Does the delegate want to take care of the logic for when we should ask permission to update? - else if ([self.delegate respondsToSelector:@selector((updaterShouldPromptForPermissionToCheckForUpdates:))]) { - shouldPrompt = [self.delegate updaterShouldPromptForPermissionToCheckForUpdates:self]; + else if ([delegate respondsToSelector:@selector((updaterShouldPromptForPermissionToCheckForUpdates:))]) { + shouldPrompt = [delegate updaterShouldPromptForPermissionToCheckForUpdates:self]; } // Has the user been asked already? And don't ask if the host has a default value set in its Info.plist. - else if ([self.host objectForKey:SUEnableAutomaticChecksKey] == nil) { + else if ([_host objectForKey:SUEnableAutomaticChecksKey] == nil) { // We wait until the second launch of the updater for this host bundle, unless explicitly overridden via SUPromptUserOnFirstLaunchKey. - shouldPrompt = [self.host objectForKey:SUPromptUserOnFirstLaunchKey] || hasLaunchedBefore; + shouldPrompt = [_host objectForKey:SUPromptUserOnFirstLaunchKey] || hasLaunchedBefore; } if (!hasLaunchedBefore) { - [self.host setBool:YES forUserDefaultsKey:SUHasLaunchedBeforeKey]; + [_host setBool:YES forUserDefaultsKey:SUHasLaunchedBeforeKey]; } if (shouldPrompt) { NSArray *> *profileInfo = self.systemProfileArray; // Always say we're sending the system profile here so that the delegate displays the parameters it would send. - if ([self.delegate respondsToSelector:@selector((feedParametersForUpdater:sendingSystemProfile:))]) { - NSArray *feedParameters = [self.delegate feedParametersForUpdater:self sendingSystemProfile:YES]; + if ([delegate respondsToSelector:@selector((feedParametersForUpdater:sendingSystemProfile:))]) { + NSArray *feedParameters = [delegate feedParametersForUpdater:self sendingSystemProfile:YES]; if (feedParameters != nil) { profileInfo = [profileInfo arrayByAddingObjectsFromArray:feedParameters]; } @@ -410,17 +400,17 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification SPUUpdatePermissionRequest *updatePermissionRequest = [[SPUUpdatePermissionRequest alloc] initWithSystemProfile:profileInfo]; - self.showingPermissionRequest = YES; - self.sessionInProgress = YES; - self.canCheckForUpdates = YES; + _showingPermissionRequest = YES; + [self setSessionInProgress:YES]; + [self setCanCheckForUpdates:YES]; - __weak SPUUpdater *weakSelf = self; - [self.userDriver showUpdatePermissionRequest:updatePermissionRequest reply:^(SUUpdatePermissionResponse *response) { + __weak __typeof__(self) weakSelf = self; + [_userDriver showUpdatePermissionRequest:updatePermissionRequest reply:^(SUUpdatePermissionResponse *response) { dispatch_async(dispatch_get_main_queue(), ^{ - SPUUpdater *strongSelf = weakSelf; + __typeof__(self) strongSelf = weakSelf; if (strongSelf != nil) { - strongSelf.sessionInProgress = NO; - strongSelf.showingPermissionRequest = NO; + [strongSelf setSessionInProgress:NO]; + strongSelf->_showingPermissionRequest = NO; [strongSelf updatePermissionRequestFinishedWithResponse:response]; // Schedule checks, but make sure we ignore the delayed call from KVO @@ -436,7 +426,7 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification } } -- (void)updatePermissionRequestFinishedWithResponse:(SUUpdatePermissionResponse *)response +- (void)updatePermissionRequestFinishedWithResponse:(SUUpdatePermissionResponse *)response SPU_OBJC_DIRECT { [self setSendsSystemProfile:response.sendSystemProfile]; [self setAutomaticallyChecksForUpdates:response.automaticUpdateChecks]; @@ -449,31 +439,32 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification - (NSDate *)lastUpdateCheckDate { - if ([self updateLastCheckedDate] == nil) + if (_updateLastCheckedDate == nil) { - [self setUpdateLastCheckedDate:[self.host objectForUserDefaultsKey:SULastCheckTimeKey]]; + _updateLastCheckedDate = [_host objectForUserDefaultsKey:SULastCheckTimeKey]; } - return [self updateLastCheckedDate]; + return _updateLastCheckedDate; } -- (void)updateLastUpdateCheckDate +- (void)updateLastUpdateCheckDate SPU_OBJC_DIRECT { [self willChangeValueForKey:NSStringFromSelector(@selector((lastUpdateCheckDate)))]; // We use an intermediate property for last update check date due to https://github.com/sparkle-project/Sparkle/pull/1135 - [self setUpdateLastCheckedDate:[NSDate date]]; - [self.host setObject:[self updateLastCheckedDate] forUserDefaultsKey:SULastCheckTimeKey]; + _updateLastCheckedDate = [NSDate date]; + [_host setObject:_updateLastCheckedDate forUserDefaultsKey:SULastCheckTimeKey]; [self didChangeValueForKey:NSStringFromSelector(@selector((lastUpdateCheckDate)))]; } // Note this method is never called when sessionInProgress is YES -- (void)scheduleNextUpdateCheckFiringImmediately:(BOOL)firingImmediately usingCurrentDate:(BOOL)usingCurrentDate +- (void)scheduleNextUpdateCheckFiringImmediately:(BOOL)firingImmediately usingCurrentDate:(BOOL)usingCurrentDate SPU_OBJC_DIRECT { - [self.updaterTimer invalidate]; + [_updaterTimer invalidate]; + id delegate = _delegate; if (!firingImmediately && ![self automaticallyChecksForUpdates]) { - if ([self.delegate respondsToSelector:@selector(updaterWillNotScheduleUpdateCheck:)]) { - [self.delegate updaterWillNotScheduleUpdateCheck:self]; + if ([delegate respondsToSelector:@selector(updaterWillNotScheduleUpdateCheck:)]) { + [delegate updaterWillNotScheduleUpdateCheck:self]; } return; } @@ -485,7 +476,7 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification // Notably it may differ when we have an update that has been already downloaded and needs to resume, // as well as if that update is marked critical or not void (^retrieveNextUpdateCheckInterval)(void (^)(NSTimeInterval)) = ^(void (^completionHandler)(NSTimeInterval)) { - NSString *hostBundleIdentifier = self.host.bundle.bundleIdentifier; + NSString *hostBundleIdentifier = self->_host.bundle.bundleIdentifier; assert(hostBundleIdentifier != nil); [SPUProbeInstallStatus probeInstallerUpdateItemForHostBundleIdentifier:hostBundleIdentifier completion:^(SPUInstallationInfo * _Nullable installationInfo) { dispatch_async(dispatch_get_main_queue(), ^{ @@ -508,11 +499,11 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification self.sessionInProgress = YES; retrieveNextUpdateCheckInterval(^(NSTimeInterval updateCheckInterval) { - self.canCheckForUpdates = YES; - self.sessionInProgress = NO; + [self setCanCheckForUpdates:YES]; + [self setSessionInProgress:NO]; // This callback is asynchronous, so the timer may be set. Invalidate to make sure it isn't. - [self.updaterTimer invalidate]; + [self->_updaterTimer invalidate]; NSTimeInterval intervalSinceCheck; if (usingCurrentDate) { @@ -535,15 +526,15 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification updateCheckInterval = SUMinimumUpdateCheckInterval; if (intervalSinceCheck < updateCheckInterval) { NSTimeInterval delayUntilCheck = (updateCheckInterval - intervalSinceCheck); // It hasn't been long enough. - if ([self.delegate respondsToSelector:@selector(updater:willScheduleUpdateCheckAfterDelay:)]) { - [self.delegate updater:self willScheduleUpdateCheckAfterDelay:delayUntilCheck]; + if ([delegate respondsToSelector:@selector(updater:willScheduleUpdateCheckAfterDelay:)]) { + [delegate updater:self willScheduleUpdateCheckAfterDelay:delayUntilCheck]; } - if ([self.userDriver respondsToSelector:@selector(logGentleScheduledUpdateReminderWarningIfNeeded)]) { - [(id)self.userDriver logGentleScheduledUpdateReminderWarningIfNeeded]; + if ([self->_userDriver respondsToSelector:@selector(logGentleScheduledUpdateReminderWarningIfNeeded)]) { + [(id)self->_userDriver logGentleScheduledUpdateReminderWarningIfNeeded]; } - [self.updaterTimer startAndFireAfterDelay:delayUntilCheck]; + [self->_updaterTimer startAndFireAfterDelay:delayUntilCheck]; } else { // We're overdue! Run one now. [self _checkForUpdatesInBackground]; @@ -557,40 +548,41 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification [self _checkForUpdatesInBackground]; } -- (void)_checkForUpdatesInBackground +- (void)_checkForUpdatesInBackground SPU_OBJC_DIRECT { - self.sessionInProgress = YES; - self.canCheckForUpdates = NO; + [self setSessionInProgress:YES]; + [self setCanCheckForUpdates:NO]; // We don't want the probe check to act on the driver if the updater is going near death - __weak SPUUpdater *weakSelf = self; + __weak __typeof__(self) weakSelf = self; - NSString *hostBundleIdentifier = self.host.bundle.bundleIdentifier; + NSString *hostBundleIdentifier = _host.bundle.bundleIdentifier; assert(hostBundleIdentifier != nil); [SPUProbeInstallStatus probeInstallerInProgressForHostBundleIdentifier:hostBundleIdentifier completion:^(BOOL installerIsRunning) { dispatch_async(dispatch_get_main_queue(), ^{ - SPUUpdater *strongSelf = weakSelf; + __typeof__(self) strongSelf = weakSelf; if (strongSelf == nil) { return; } + id delegate = strongSelf->_delegate; id updateDriver; - if (!installerIsRunning && [strongSelf automaticallyDownloadsUpdates] && strongSelf.resumableUpdate == nil) { + if (!installerIsRunning && [strongSelf automaticallyDownloadsUpdates] && strongSelf->_resumableUpdate == nil) { updateDriver = [[SPUAutomaticUpdateDriver alloc] - initWithHost:strongSelf.host - applicationBundle:strongSelf.applicationBundle + initWithHost:strongSelf->_host + applicationBundle:strongSelf->_applicationBundle updater:strongSelf - userDriver:strongSelf.userDriver - updaterDelegate:strongSelf.delegate]; + userDriver:strongSelf->_userDriver + updaterDelegate:delegate]; } else { updateDriver = [[SPUScheduledUpdateDriver alloc] - initWithHost:strongSelf.host - applicationBundle:strongSelf.applicationBundle + initWithHost:strongSelf->_host + applicationBundle:strongSelf->_applicationBundle updater:strongSelf - userDriver:strongSelf.userDriver - updaterDelegate:strongSelf.delegate]; + userDriver:strongSelf->_userDriver + updaterDelegate:delegate]; } [strongSelf checkForUpdatesWithDriver:updateDriver updateCheck:SPUUpdateCheckUpdatesInBackground installerInProgress:installerIsRunning]; @@ -602,19 +594,19 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification // Sparkle internally uses _checkForUpdatesInBackground - (void)checkForUpdatesInBackground { - if (!self.startedUpdater) { + if (!_startedUpdater) { SULog(SULogLevelError, @"Error: checkForUpdatesInBackground - updater hasn't been started yet. Please call -startUpdater: first"); return; } - - if (self.sessionInProgress) { + + if (_sessionInProgress) { SULog(SULogLevelError, @"Error: -checkForUpdatesInBackground called but .sessionInProgress == YES"); return; } if (_updatingMainBundle) { // Check if Sparkle is configured to ask the user's permission to enable automatic update checks - NSNumber *automaticChecksInInfoPlist = [self.host objectForInfoDictionaryKey:SUEnableAutomaticChecksKey]; + NSNumber *automaticChecksInInfoPlist = [_host objectForInfoDictionaryKey:SUEnableAutomaticChecksKey]; if (automaticChecksInInfoPlist == nil) { // Check if automatic update checking is disabled or if the user hasn't given permission for Sparkle to check BOOL automaticChecksInDefaults = [self automaticallyChecksForUpdates]; @@ -629,39 +621,39 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification - (void)checkForUpdates { - if (self.showingPermissionRequest || self.driver.showingUpdate) { - if ([self.userDriver respondsToSelector:@selector(showUpdateInFocus)]) { - [self.userDriver showUpdateInFocus]; + if (_showingPermissionRequest || _driver.showingUpdate) { + if ([_userDriver respondsToSelector:@selector(showUpdateInFocus)]) { + [_userDriver showUpdateInFocus]; } return; } - if (!self.startedUpdater) { + if (!_startedUpdater) { SULog(SULogLevelError, @"Error: checkForUpdates - updater hasn't been started yet. Please call -startUpdater: first"); return; } - if (self.sessionInProgress) { + if (_sessionInProgress) { SULog(SULogLevelError, @"Error: -checkForUpdates called but .sessionInProgress == YES"); return; } - if (self.driver != nil) { + if (_driver != nil) { return; } - self.sessionInProgress = YES; - self.canCheckForUpdates = NO; + [self setSessionInProgress:YES]; + [self setCanCheckForUpdates:NO]; - id theUpdateDriver = [[SPUUserInitiatedUpdateDriver alloc] initWithHost:self.host applicationBundle:self.applicationBundle updater:self userDriver:self.userDriver updaterDelegate:self.delegate]; + id theUpdateDriver = [[SPUUserInitiatedUpdateDriver alloc] initWithHost:_host applicationBundle:_applicationBundle updater:self userDriver:_userDriver updaterDelegate:_delegate]; - NSString *bundleIdentifier = self.host.bundle.bundleIdentifier; + NSString *bundleIdentifier = _host.bundle.bundleIdentifier; assert(bundleIdentifier != nil); - __weak SPUUpdater *weakSelf = self; + __weak __typeof__(self) weakSelf = self; [SPUProbeInstallStatus probeInstallerInProgressForHostBundleIdentifier:bundleIdentifier completion:^(BOOL installerInProgress) { dispatch_async(dispatch_get_main_queue(), ^{ - SPUUpdater *strongSelf = weakSelf; + __typeof__(self) strongSelf = weakSelf; if (strongSelf != nil) { [strongSelf checkForUpdatesWithDriver:theUpdateDriver updateCheck:SPUUpdateCheckUpdates installerInProgress:installerInProgress]; } @@ -671,71 +663,73 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification - (void)checkForUpdateInformation { - __weak SPUUpdater *weakSelf = self; - if (!self.startedUpdater) { + __weak __typeof__(self) weakSelf = self; + if (!_startedUpdater) { SULog(SULogLevelError, @"Error: checkForUpdateInformation - updater hasn't been started yet. Please call -startUpdater: first"); return; } - if (self.sessionInProgress) { + if (_sessionInProgress) { SULog(SULogLevelError, @"Error: -checkForUpdateInformation called but .sessionInProgress == YES"); return; } - self.sessionInProgress = YES; - self.canCheckForUpdates = NO; + [self setSessionInProgress:YES]; + [self setCanCheckForUpdates:NO]; - NSString *bundleIdentifier = self.host.bundle.bundleIdentifier; + NSString *bundleIdentifier = _host.bundle.bundleIdentifier; assert(bundleIdentifier != nil); [SPUProbeInstallStatus probeInstallerInProgressForHostBundleIdentifier:bundleIdentifier completion:^(BOOL installerInProgress) { dispatch_async(dispatch_get_main_queue(), ^{ - SPUUpdater *strongSelf = weakSelf; + __typeof__(self) strongSelf = weakSelf; if (strongSelf != nil) { - [strongSelf checkForUpdatesWithDriver:[[SPUProbingUpdateDriver alloc] initWithHost:strongSelf.host updater:strongSelf updaterDelegate:strongSelf.delegate] updateCheck:SPUUpdateCheckUpdateInformation installerInProgress:installerInProgress]; + [strongSelf checkForUpdatesWithDriver:[[SPUProbingUpdateDriver alloc] initWithHost:strongSelf->_host updater:strongSelf updaterDelegate:strongSelf->_delegate] updateCheck:SPUUpdateCheckUpdateInformation installerInProgress:installerInProgress]; } }); }]; } -- (void)checkForUpdatesWithDriver:(id )d updateCheck:(SPUUpdateCheck)updateCheck installerInProgress:(BOOL)installerInProgress +- (void)checkForUpdatesWithDriver:(id )d updateCheck:(SPUUpdateCheck)updateCheck installerInProgress:(BOOL)installerInProgress SPU_OBJC_DIRECT { - assert(self.driver == nil); - if (self.driver != nil) { + assert(_driver == nil); + if (_driver != nil) { return; } - [self.updaterTimer invalidate]; + [_updaterTimer invalidate]; [self updateLastUpdateCheckDate]; - self.driver = d; - assert(self.driver != nil); + _driver = d; + assert(_driver != nil); void (^notifyDelegateOfDriverCompletion)(NSError * _Nullable, BOOL) = ^(NSError * _Nullable error, BOOL shouldShowUpdateImmediately) { + id delegate = self->_delegate; + if (error != nil) { if (error.code != SUNoUpdateError && error.code != SUInstallationCanceledError && error.code != SUInstallationAuthorizeLaterError) { // Let's not bother logging this. SULogError(error); } // Notify host app that update driver has aborted if a non-recoverable error occurs - if (error.code != SUInstallationAuthorizeLaterError && [self.delegate respondsToSelector:@selector((updater:didAbortWithError:))]) { - [self.delegate updater:self didAbortWithError:(NSError * _Nonnull)error]; + if (error.code != SUInstallationAuthorizeLaterError && [delegate respondsToSelector:@selector((updater:didAbortWithError:))]) { + [delegate updater:self didAbortWithError:(NSError * _Nonnull)error]; } } // Notify host app that update driver has finished // As long as we're not going to immmediately kick off a new check - if (!shouldShowUpdateImmediately && [self.delegate respondsToSelector:@selector((updater:didFinishUpdateCycleForUpdateCheck:error:))]) { - [self.delegate updater:self didFinishUpdateCycleForUpdateCheck:updateCheck error:error]; + if (!shouldShowUpdateImmediately && [delegate respondsToSelector:@selector((updater:didFinishUpdateCycleForUpdateCheck:error:))]) { + [delegate updater:self didFinishUpdateCycleForUpdateCheck:updateCheck error:error]; } }; void (^abortUpdateDriver)(NSError * _Nullable , BOOL) = ^(NSError * _Nullable abortError, BOOL shouldScheduleNextUpdateCheck) { - __weak SPUUpdater *weakSelf = self; - [self.driver setCompletionHandler:^(BOOL __unused shouldShowUpdateImmediately, id _Nullable __unused resumableUpdate, NSError * _Nullable error) { - SPUUpdater *strongSelf = weakSelf; + __weak __typeof__(self) weakSelf = self; + [self->_driver setCompletionHandler:^(BOOL __unused shouldShowUpdateImmediately, id _Nullable __unused resumableUpdate, NSError * _Nullable error) { + __typeof__(self) strongSelf = weakSelf; if (strongSelf != nil) { - strongSelf.driver = nil; + strongSelf->_driver = nil; [strongSelf updateLastUpdateCheckDate]; @@ -745,7 +739,7 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification notifyDelegateOfDriverCompletion(error, NO); // Ensure the delegate doesn't start a new session when being notified of the previous one ending - if (!strongSelf.sessionInProgress) { + if (!strongSelf->_sessionInProgress) { if (shouldScheduleNextUpdateCheck) { [strongSelf scheduleNextUpdateCheckFiringImmediately:NO usingCurrentDate:NO]; } else { @@ -755,16 +749,17 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification } }]; - [self.driver abortUpdateWithError:abortError]; + [self->_driver abortUpdateWithError:abortError]; }; // Check if the delegate wants to defer checking for updates + id delegate = _delegate; NSError *mayCheckForUpdatesError = nil; if ( - ([self.delegate respondsToSelector:@selector(updater:mayPerformUpdateCheck:error:)] && ![self.delegate updater:self mayPerformUpdateCheck:updateCheck error:&mayCheckForUpdatesError]) || + ([delegate respondsToSelector:@selector(updater:mayPerformUpdateCheck:error:)] && ![delegate updater:self mayPerformUpdateCheck:updateCheck error:&mayCheckForUpdatesError]) || #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" - ([self.delegate respondsToSelector:@selector((updaterMayCheckForUpdates:))] && ![self.delegate updaterMayCheckForUpdates:self])) + ([delegate respondsToSelector:@selector((updaterMayCheckForUpdates:))] && ![delegate updaterMayCheckForUpdates:self])) #pragma clang diagnostic pop { abortUpdateDriver(mayCheckForUpdatesError, YES); @@ -782,41 +777,41 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification } // Run our update driver and schedule next update check on its completion - __weak SPUUpdater *weakSelf = self; - [self.driver setCompletionHandler:^(BOOL shouldShowUpdateImmediately, id _Nullable resumableUpdate, NSError * _Nullable error) { - SPUUpdater *strongSelf = weakSelf; + __weak __typeof__(self) weakSelf = self; + [_driver setCompletionHandler:^(BOOL shouldShowUpdateImmediately, id _Nullable resumableUpdate, NSError * _Nullable error) { + __typeof__(self) strongSelf = weakSelf; if (strongSelf != nil) { - strongSelf.resumableUpdate = resumableUpdate; - strongSelf.driver = nil; + strongSelf->_resumableUpdate = resumableUpdate; + strongSelf->_driver = nil; [strongSelf updateLastUpdateCheckDate]; - strongSelf.sessionInProgress = NO; - strongSelf.canCheckForUpdates = YES; + [strongSelf setSessionInProgress:NO]; + [strongSelf setCanCheckForUpdates:YES]; notifyDelegateOfDriverCompletion(error, shouldShowUpdateImmediately); // Ensure the delegate doesn't start a new session when being notified of the previous one ending - if (!strongSelf.sessionInProgress) { + if (!strongSelf->_sessionInProgress) { [strongSelf scheduleNextUpdateCheckFiringImmediately:shouldShowUpdateImmediately usingCurrentDate:NO]; } } }]; - [self.driver setUpdateShownHandler:^{ + [_driver setUpdateShownHandler:^{ weakSelf.canCheckForUpdates = YES; }]; - [self.driver setUpdateWillInstallHandler:^{ + [_driver setUpdateWillInstallHandler:^{ [weakSelf updateLastUpdateCheckDate]; }]; if (installerInProgress) { // Resume an update that has already begun installing in the background - [self.driver resumeInstallingUpdate]; - } else if (self.resumableUpdate != nil) { + [_driver resumeInstallingUpdate]; + } else if (_resumableUpdate != nil) { // Resume an update or info that has already been downloaded - [self.driver resumeUpdate:(id _Nonnull)self.resumableUpdate]; + [_driver resumeUpdate:(id _Nonnull)_resumableUpdate]; } else { // Check that the parameterized feed URL is valid NSURL *theFeedURL = [self parameterizedFeedURL]; @@ -828,30 +823,30 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification abortUpdateDriver([NSError errorWithDomain:SUSparkleErrorDomain code:SUInvalidFeedURLError userInfo:@{ NSLocalizedDescriptionKey: @"Sparkle cannot form a valid feed URL." }], NO); } else { // Check for new updates - [self.driver checkForUpdatesAtAppcastURL:theFeedURL withUserAgent:self.userAgentString httpHeaders:[self httpHeaders]]; + [_driver checkForUpdatesAtAppcastURL:theFeedURL withUserAgent:_userAgentString httpHeaders:_httpHeaders]; } } } - (void)cancelNextUpdateCycle { - [self.updaterCycle cancelNextUpdateCycle]; + [_updaterCycle cancelNextUpdateCycle]; } - (void)resetUpdateCycle { - if (!self.startedUpdater) { + if (!_startedUpdater) { SULog(SULogLevelError, @"Error: resetUpdateCycle - updater hasn't been started yet. Please call -startUpdater: first"); return; // not even ready yet } // Note this resets the opportune time when user grants Sparkle permission to check for updates // and when the user changes preferences on automatically checking for updates or the update time check interval - if ([self.userDriver respondsToSelector:@selector(resetTimeSinceOpportuneUpdateNotice)]) { - [(id)self.userDriver resetTimeSinceOpportuneUpdateNotice]; + if ([_userDriver respondsToSelector:@selector(resetTimeSinceOpportuneUpdateNotice)]) { + [(id)_userDriver resetTimeSinceOpportuneUpdateNotice]; } - if (!self.sessionInProgress) { + if (!_sessionInProgress) { [self cancelNextUpdateCycle]; [self scheduleNextUpdateCheckFiringImmediately:NO usingCurrentDate:YES]; } @@ -860,19 +855,19 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification - (void)resetUpdateCycleAfterShortDelay { [self cancelNextUpdateCycle]; - [self.updaterCycle resetUpdateCycleAfterDelay]; + [_updaterCycle resetUpdateCycleAfterDelay]; } - (void)setAutomaticallyChecksForUpdates:(BOOL)automaticallyCheckForUpdates { - [self.host setBool:automaticallyCheckForUpdates forUserDefaultsKey:SUEnableAutomaticChecksKey]; + [_host setBool:automaticallyCheckForUpdates forUserDefaultsKey:SUEnableAutomaticChecksKey]; // Hack to support backwards compatibility with older Sparkle versions, which supported // disabling updates by setting the check interval to 0. if (automaticallyCheckForUpdates && (NSInteger)[self updateCheckInterval] == 0) { [self setUpdateCheckInterval:SUDefaultUpdateCheckInterval]; } - if (self.startedUpdater) { + if (_startedUpdater) { // Provide a small delay in case multiple preferences are being updated simultaneously. [self resetUpdateCycleAfterShortDelay]; } @@ -880,17 +875,17 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification - (BOOL)automaticallyChecksForUpdates { - return [self.updaterSettings automaticallyChecksForUpdates]; + return [_updaterSettings automaticallyChecksForUpdates]; } - (void)setAutomaticallyDownloadsUpdates:(BOOL)automaticallyUpdates { - [self.host setBool:automaticallyUpdates forUserDefaultsKey:SUAutomaticallyUpdateKey]; + [_host setBool:automaticallyUpdates forUserDefaultsKey:SUAutomaticallyUpdateKey]; } - (BOOL)automaticallyDownloadsUpdates { - return [self.updaterSettings allowsAutomaticUpdates] && [self.updaterSettings automaticallyDownloadsUpdates]; + return [_updaterSettings allowsAutomaticUpdates] && [_updaterSettings automaticallyDownloadsUpdates]; } - (void)setFeedURL:(NSURL * _Nullable)feedURL @@ -901,7 +896,7 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification } // When feedURL is nil, -absoluteString will return nil and will remove the user default key - [self.host setObject:[feedURL absoluteString] forUserDefaultsKey:SUFeedURLKey]; + [_host setObject:[feedURL absoluteString] forUserDefaultsKey:SUFeedURLKey]; } - (nullable NSURL *)clearFeedURLFromUserDefaults @@ -911,9 +906,9 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification SULog(SULogLevelError, @"Error: -[SPUUpdater clearFeedURLFromUserDefaults] must be called on the main thread."); } - NSString *appcastString = [self.host objectForUserDefaultsKey:SUFeedURLKey]; + NSString *appcastString = [_host objectForUserDefaultsKey:SUFeedURLKey]; - [self.host setObject:nil forUserDefaultsKey:SUFeedURLKey]; + [_host setObject:nil forUserDefaultsKey:SUFeedURLKey]; if (appcastString == nil) { return nil; @@ -928,7 +923,7 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification return [NSURL URLWithString:castUrlStr]; } -- (NSString * _Nullable)_stripFeedString:(NSString *)appcastString hostName:(NSString *)hostName error:(NSError * __autoreleasing *)error +- (NSString * _Nullable)_stripFeedString:(NSString *)appcastString hostName:(NSString *)hostName error:(NSError * __autoreleasing *)error SPU_OBJC_DIRECT { NSCharacterSet *quoteSet = [NSCharacterSet characterSetWithCharactersInString:@"\"\'"]; // Some feed publishers add quotes; strip 'em. NSString *castUrlStr = [appcastString stringByTrimmingCharactersInSet:quoteSet]; @@ -942,9 +937,9 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification return castUrlStr; } -- (NSURL * _Nullable)retrieveFeedURL:(NSError * __autoreleasing *)error +- (NSURL * _Nullable)retrieveFeedURL:(NSError * __autoreleasing *)error SPU_OBJC_DIRECT { - NSString *hostName = self.host.name; + NSString *hostName = _host.name; if (![NSThread isMainThread]) { SULog(SULogLevelError, @"Error: -[SPUUpdater retrieveFeedURL:error:] must be called on the main thread."); @@ -955,9 +950,10 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification } // Delegate gets first priority for determining the feed URL - NSString *appcastString = nil; - if ([self.delegate respondsToSelector:@selector((feedURLStringForUpdater:))]) { - NSString *delegateAppcastString = [self.delegate feedURLStringForUpdater:self]; + NSString *appcastString = [_host objectForKey:SUFeedURLKey]; + id delegate = _delegate; + if ([delegate respondsToSelector:@selector((feedURLStringForUpdater:))]) { + NSString *delegateAppcastString = [delegate feedURLStringForUpdater:self]; if (delegateAppcastString != nil) { appcastString = delegateAppcastString; } @@ -966,7 +962,7 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification // A value in the user defaults overrides one in the Info.plist // (as this used to be used for setting alternative feed URLs but is now deprecated) if (appcastString == nil) { - appcastString = [self.host objectForKey:SUFeedURLKey]; + appcastString = [_host objectForKey:SUFeedURLKey]; } if (appcastString == nil) { // Can't find an appcast string! @@ -1006,12 +1002,12 @@ NSString *const SUUpdaterAppcastNotificationKey = @"SUUpdaterAppCastNotification - (void)setSendsSystemProfile:(BOOL)sendsSystemProfile { - [self.host setBool:sendsSystemProfile forUserDefaultsKey:SUSendProfileInfoKey]; + [_host setBool:sendsSystemProfile forUserDefaultsKey:SUSendProfileInfoKey]; } - (BOOL)sendsSystemProfile { - return [self.updaterSettings sendsSystemProfile]; + return [_updaterSettings sendsSystemProfile]; } static NSString *escapeURLComponent(NSString *str) { @@ -1021,7 +1017,7 @@ static NSString *escapeURLComponent(NSString *str) { } // Precondition: The feed URL should be valid -- (NSURL * _Nullable)parameterizedFeedURL +- (NSURL * _Nullable)parameterizedFeedURL SPU_OBJC_DIRECT { NSURL *baseFeedURL = [self retrieveFeedURL:NULL]; if (baseFeedURL == nil) { @@ -1033,24 +1029,25 @@ static NSString *escapeURLComponent(NSString *str) { BOOL sendingSystemProfile = [self sendsSystemProfile]; // Let's only send the system profiling information once per week at most, so we normalize daily-checkers vs. biweekly-checkers and the such. - NSDate *lastSubmitDate = [self.host objectForUserDefaultsKey:SULastProfileSubmitDateKey]; + NSDate *lastSubmitDate = [_host objectForUserDefaultsKey:SULastProfileSubmitDateKey]; if (!lastSubmitDate) { lastSubmitDate = [NSDate distantPast]; } const NSTimeInterval oneWeek = 60 * 60 * 24 * 7; sendingSystemProfile &= (-[lastSubmitDate timeIntervalSinceNow] >= oneWeek); + id delegate = _delegate; NSArray *> *parameters = @[]; - if ([self.delegate respondsToSelector:@selector((feedParametersForUpdater:sendingSystemProfile:))]) { - NSArray *feedParameters = [self.delegate feedParametersForUpdater:self sendingSystemProfile:sendingSystemProfile]; + if ([delegate respondsToSelector:@selector((feedParametersForUpdater:sendingSystemProfile:))]) { + NSArray *feedParameters = [delegate feedParametersForUpdater:self sendingSystemProfile:sendingSystemProfile]; if (feedParameters != nil) { parameters = [parameters arrayByAddingObjectsFromArray:feedParameters]; } } if (sendingSystemProfile) { - parameters = [parameters arrayByAddingObjectsFromArray:self.systemProfileArray]; - [self.host setObject:[NSDate date] forUserDefaultsKey:SULastProfileSubmitDateKey]; + parameters = [parameters arrayByAddingObjectsFromArray:[self systemProfileArray]]; + [_host setObject:[NSDate date] forUserDefaultsKey:SULastProfileSubmitDateKey]; } if ([parameters count] == 0) { return baseFeedURL; } @@ -1075,9 +1072,10 @@ static NSString *escapeURLComponent(NSString *str) { } - (NSArray *> *)systemProfileArray { - NSArray *systemProfile = [SUSystemProfiler systemProfileArrayForHost:self.host]; - if ([self.delegate respondsToSelector:@selector(allowedSystemProfileKeysForUpdater:)]) { - NSArray * allowedKeys = [self.delegate allowedSystemProfileKeysForUpdater:self]; + id delegate = _delegate; + NSArray *systemProfile = [SUSystemProfiler systemProfileArrayForHost:_host]; + if ([delegate respondsToSelector:@selector(allowedSystemProfileKeysForUpdater:)]) { + NSArray * allowedKeys = [delegate allowedSystemProfileKeysForUpdater:self]; if (allowedKeys != nil) { NSMutableArray *filteredProfile = [NSMutableArray array]; for (NSDictionary *profileElement in systemProfile) { @@ -1094,12 +1092,12 @@ static NSString *escapeURLComponent(NSString *str) { - (void)setUpdateCheckInterval:(NSTimeInterval)updateCheckInterval { - [self.host setObject:@(updateCheckInterval) forUserDefaultsKey:SUScheduledCheckIntervalKey]; + [_host setObject:@(updateCheckInterval) forUserDefaultsKey:SUScheduledCheckIntervalKey]; if ((NSInteger)updateCheckInterval == 0) { // For compatibility with 1.1's settings. [self setAutomaticallyChecksForUpdates:NO]; } - if (self.startedUpdater) { + if (_startedUpdater) { // Provide a small delay in case multiple preferences are being updated simultaneously. [self resetUpdateCycleAfterShortDelay]; } @@ -1107,22 +1105,25 @@ static NSString *escapeURLComponent(NSString *str) { - (NSTimeInterval)updateCheckInterval { - return [self.updaterSettings updateCheckInterval]; + return [_updaterSettings updateCheckInterval]; } - (void)dealloc { // Stop checking for updates [self cancelNextUpdateCycle]; - [self.updaterTimer invalidate]; + [_updaterTimer invalidate]; // Abort any on-going updates // A driver could be retained by another object (eg: a timer), // so not aborting could mean it stays alive longer than we'd want - [self.driver abortUpdate]; - self.driver = nil; + [_driver abortUpdate]; + _driver = nil; } -- (NSBundle *)hostBundle { return [self.host bundle]; } +- (NSBundle *)hostBundle +{ + return _host.bundle; +} @end diff --git a/Sparkle/SPUUpdaterCycle.h b/Sparkle/SPUUpdaterCycle.h index 2c9c6b15..b1fb8189 100644 --- a/Sparkle/SPUUpdaterCycle.h +++ b/Sparkle/SPUUpdaterCycle.h @@ -18,7 +18,7 @@ NS_ASSUME_NONNULL_BEGIN // This notifies the updater for (re-)starting and canceling update cycles // This class is used so that an updater instance isn't kept alive by a pending update cycle -@interface SPUUpdaterCycle : NSObject +SPU_OBJC_DIRECT_MEMBERS @interface SPUUpdaterCycle : NSObject // This delegate is weakly referenced - (instancetype)initWithDelegate:(id)delegate; diff --git a/Sparkle/SPUUpdaterCycle.m b/Sparkle/SPUUpdaterCycle.m index a3f32249..ae309e3b 100644 --- a/Sparkle/SPUUpdaterCycle.m +++ b/Sparkle/SPUUpdaterCycle.m @@ -11,15 +11,10 @@ #include "AppKitPrevention.h" -@interface SPUUpdaterCycle () - -@property (nonatomic, weak, readonly) id delegate; - -@end - @implementation SPUUpdaterCycle - -@synthesize delegate = _delegate; +{ + __weak id _delegate; +} - (instancetype)initWithDelegate:(id)delegate { @@ -32,7 +27,7 @@ - (void)resetUpdateCycle { - [self.delegate resetUpdateCycle]; + [_delegate resetUpdateCycle]; } - (void)resetUpdateCycleAfterDelay diff --git a/Sparkle/SPUUpdaterDelegate.h b/Sparkle/SPUUpdaterDelegate.h index a18e967f..c879e8f8 100644 --- a/Sparkle/SPUUpdaterDelegate.h +++ b/Sparkle/SPUUpdaterDelegate.h @@ -7,9 +7,20 @@ // #import + +#if defined(BUILDING_SPARKLE_SOURCES_EXTERNALLY) +// Ignore incorrect warning +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wquoted-include-in-framework-header" +#import "SUExport.h" +#import "SPUUpdateCheck.h" +#import "SPUUserUpdateState.h" +#pragma clang diagnostic pop +#else #import #import #import +#endif @protocol SUVersionComparison; @class SPUUpdater, SUAppcast, SUAppcastItem, SPUUserUpdateState; diff --git a/Sparkle/SPUUpdaterSettings.h b/Sparkle/SPUUpdaterSettings.h index a480a42a..8b69e962 100644 --- a/Sparkle/SPUUpdaterSettings.h +++ b/Sparkle/SPUUpdaterSettings.h @@ -7,7 +7,16 @@ // #import + +#if defined(BUILDING_SPARKLE_SOURCES_EXTERNALLY) +// Ignore incorrect warning +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wquoted-include-in-framework-header" +#import "SUExport.h" +#pragma clang diagnostic pop +#else #import +#endif NS_ASSUME_NONNULL_BEGIN diff --git a/Sparkle/SPUUpdaterSettings.m b/Sparkle/SPUUpdaterSettings.m index 691231d2..d74001fc 100644 --- a/Sparkle/SPUUpdaterSettings.m +++ b/Sparkle/SPUUpdaterSettings.m @@ -13,15 +13,10 @@ #include "AppKitPrevention.h" -@interface SPUUpdaterSettings () - -@property (nonatomic, readonly) SUHost *host; - -@end - @implementation SPUUpdaterSettings - -@synthesize host = _host; +{ + SUHost *_host; +} - (instancetype)initWithHostBundle:(NSBundle *)hostBundle { @@ -38,13 +33,13 @@ if ((NSInteger)[self updateCheckInterval] == 0) { return NO; } - return [self.host boolForKey:SUEnableAutomaticChecksKey]; + return [_host boolForKey:SUEnableAutomaticChecksKey]; } - (NSTimeInterval)updateCheckInterval { // Find the stored check interval. User defaults override Info.plist. - NSNumber *intervalValue = [self.host objectForKey:SUScheduledCheckIntervalKey]; + NSNumber *intervalValue = [_host objectForKey:SUScheduledCheckIntervalKey]; if (intervalValue) return [intervalValue doubleValue]; else @@ -54,7 +49,7 @@ // For allowing automatic downloaded updates to be turned on or off - (NSNumber * _Nullable)allowsAutomaticUpdatesOption { - NSNumber *developerAllowsAutomaticUpdates = [self.host objectForInfoDictionaryKey:SUAllowsAutomaticUpdatesKey]; + NSNumber *developerAllowsAutomaticUpdates = [_host objectForInfoDictionaryKey:SUAllowsAutomaticUpdatesKey]; return [developerAllowsAutomaticUpdates isKindOfClass:[NSNumber class]] ? developerAllowsAutomaticUpdates : nil; } @@ -66,12 +61,12 @@ - (BOOL)automaticallyDownloadsUpdates { - return [self.host boolForKey:SUAutomaticallyUpdateKey]; + return [_host boolForKey:SUAutomaticallyUpdateKey]; } - (BOOL)sendsSystemProfile { - return [self.host boolForKey:SUSendProfileInfoKey]; + return [_host boolForKey:SUSendProfileInfoKey]; } @end diff --git a/Sparkle/SPUUpdaterTimer.h b/Sparkle/SPUUpdaterTimer.h index 6f82647f..ecd1bc96 100644 --- a/Sparkle/SPUUpdaterTimer.h +++ b/Sparkle/SPUUpdaterTimer.h @@ -18,7 +18,7 @@ NS_ASSUME_NONNULL_BEGIN // This notifies the updater for scheduled update checks // This class is used so that an updater instance isn't kept alive by a scheduled update check -@interface SPUUpdaterTimer : NSObject +SPU_OBJC_DIRECT_MEMBERS @interface SPUUpdaterTimer : NSObject - (instancetype)initWithDelegate:(id)delegate; diff --git a/Sparkle/SPUUpdaterTimer.m b/Sparkle/SPUUpdaterTimer.m index 6baa9200..1b9afea4 100644 --- a/Sparkle/SPUUpdaterTimer.m +++ b/Sparkle/SPUUpdaterTimer.m @@ -12,17 +12,12 @@ #include "AppKitPrevention.h" -@interface SPUUpdaterTimer () - -@property (nonatomic, readonly, weak) id delegate; -@property (nonatomic) dispatch_source_t source; - -@end - @implementation SPUUpdaterTimer - -@synthesize delegate = _delegate; -@synthesize source = _source; +{ + dispatch_source_t _source; + + __weak id _delegate; +} - (instancetype)initWithDelegate:(id)delegate { @@ -35,26 +30,29 @@ - (void)startAndFireAfterDelay:(NSTimeInterval)delay { - self.source = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue()); + _source = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue()); // We use the wall time instead of cpu time for our dispatch timer // So eg if the computer sleeps we want to include that time spent in our timer dispatch_time_t timeToFire = dispatch_walltime(NULL, (int64_t)(delay * NSEC_PER_SEC)); - dispatch_source_set_timer(self.source, timeToFire, DISPATCH_TIME_FOREVER, SULeewayUpdateCheckInterval * NSEC_PER_SEC); + dispatch_source_set_timer(_source, timeToFire, DISPATCH_TIME_FOREVER, SULeewayUpdateCheckInterval * NSEC_PER_SEC); __weak __typeof__(self) weakSelf = self; - dispatch_source_set_event_handler(self.source, ^{ - [weakSelf.delegate updaterTimerDidFire]; + dispatch_source_set_event_handler(_source, ^{ + __typeof__(self) strongSelf = weakSelf; + if (strongSelf != nil) { + [strongSelf->_delegate updaterTimerDidFire]; + } }); - dispatch_resume(self.source); + dispatch_resume(_source); } - (void)invalidate { - if (self.source != nil) { - dispatch_source_cancel(self.source); - self.source = nil; + if (_source != nil) { + dispatch_source_cancel(_source); + _source = nil; } } diff --git a/Sparkle/SPUUserAgent+Private.h b/Sparkle/SPUUserAgent+Private.h index 0b3c3c71..392fccb4 100644 --- a/Sparkle/SPUUserAgent+Private.h +++ b/Sparkle/SPUUserAgent+Private.h @@ -7,7 +7,16 @@ // #import + +#if defined(BUILDING_SPARKLE_SOURCES_EXTERNALLY) +// Ignore incorrect warning +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wquoted-include-in-framework-header" +#import "SUExport.h" +#pragma clang diagnostic pop +#else #import +#endif NS_ASSUME_NONNULL_BEGIN diff --git a/Sparkle/SPUUserDriver.h b/Sparkle/SPUUserDriver.h index 22cc1670..c43003f9 100644 --- a/Sparkle/SPUUserDriver.h +++ b/Sparkle/SPUUserDriver.h @@ -8,8 +8,17 @@ #import +#if defined(BUILDING_SPARKLE_SOURCES_EXTERNALLY) +// Ignore incorrect warning +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wquoted-include-in-framework-header" +#import "SPUUserUpdateState.h" +#import "SUExport.h" +#pragma clang diagnostic pop +#else #import #import +#endif NS_ASSUME_NONNULL_BEGIN diff --git a/Sparkle/SPUUserInitiatedUpdateDriver.h b/Sparkle/SPUUserInitiatedUpdateDriver.h index 02aba16e..97648c5c 100644 --- a/Sparkle/SPUUserInitiatedUpdateDriver.h +++ b/Sparkle/SPUUserInitiatedUpdateDriver.h @@ -14,7 +14,7 @@ NS_ASSUME_NONNULL_BEGIN @class SUHost; @protocol SPUUpdaterDelegate, SPUUserDriver; -@interface SPUUserInitiatedUpdateDriver : NSObject +SPU_OBJC_DIRECT_MEMBERS @interface SPUUserInitiatedUpdateDriver : NSObject - (instancetype)initWithHost:(SUHost *)host applicationBundle:(NSBundle *)applicationBundle updater:(id)updater userDriver:(id )userDriver updaterDelegate:(nullable id )updaterDelegate; diff --git a/Sparkle/SPUUserInitiatedUpdateDriver.m b/Sparkle/SPUUserInitiatedUpdateDriver.m index 2f529416..caeb257b 100644 --- a/Sparkle/SPUUserInitiatedUpdateDriver.m +++ b/Sparkle/SPUUserInitiatedUpdateDriver.m @@ -15,23 +15,21 @@ @interface SPUUserInitiatedUpdateDriver () -@property (nonatomic, readonly) SPUUIBasedUpdateDriver *uiDriver; -@property (nonatomic, readonly) id userDriver; -@property (nonatomic) BOOL showingUserInitiatedProgress; -@property (nonatomic) BOOL showingUpdate; -@property (nonatomic) BOOL aborted; -@property (nonatomic) void (^updateDidShowHandler)(void); - @end @implementation SPUUserInitiatedUpdateDriver +{ + SPUUIBasedUpdateDriver *_uiDriver; + id _userDriver; + + void (^_updateDidShowHandler)(void); + + BOOL _showingUserInitiatedProgress; + BOOL _showingUpdate; + BOOL _aborted; +} -@synthesize uiDriver = _uiDriver; -@synthesize userDriver = _userDriver; -@synthesize showingUserInitiatedProgress = _showingUserInitiatedProgress; @synthesize showingUpdate = _showingUpdate; -@synthesize aborted = _aborted; -@synthesize updateDidShowHandler = _updateDidShowHandler; - (instancetype)initWithHost:(SUHost *)host applicationBundle:(NSBundle *)applicationBundle updater:(id)updater userDriver:(id )userDriver updaterDelegate:(nullable id )updaterDelegate { @@ -45,58 +43,58 @@ - (void)setCompletionHandler:(SPUUpdateDriverCompletion)completionBlock { - [self.uiDriver setCompletionHandler:completionBlock]; + [_uiDriver setCompletionHandler:completionBlock]; } - (void)setUpdateShownHandler:(void (^)(void))handler { - self.updateDidShowHandler = handler; + _updateDidShowHandler = [handler copy]; } - (void)setUpdateWillInstallHandler:(void (^)(void))updateWillInstallHandler { - [self.uiDriver setUpdateWillInstallHandler:updateWillInstallHandler]; + [_uiDriver setUpdateWillInstallHandler:updateWillInstallHandler]; } - (void)checkForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders { - self.showingUserInitiatedProgress = YES; + _showingUserInitiatedProgress = YES; - if (self.updateDidShowHandler != nil) { - self.updateDidShowHandler(); - self.updateDidShowHandler = nil; + if (_updateDidShowHandler != nil) { + _updateDidShowHandler(); + _updateDidShowHandler = nil; } - [self.userDriver showUserInitiatedUpdateCheckWithCancellation:^{ + [_userDriver showUserInitiatedUpdateCheckWithCancellation:^{ dispatch_async(dispatch_get_main_queue(), ^{ - if (self.showingUserInitiatedProgress) { + if (self->_showingUserInitiatedProgress) { [self abortUpdate]; } }); }]; - [self.uiDriver checkForUpdatesAtAppcastURL:appcastURL withUserAgent:userAgent httpHeaders:httpHeaders inBackground:NO]; + [_uiDriver checkForUpdatesAtAppcastURL:appcastURL withUserAgent:userAgent httpHeaders:httpHeaders inBackground:NO]; } - (void)resumeInstallingUpdate { - [self.uiDriver resumeInstallingUpdate]; + [_uiDriver resumeInstallingUpdate]; } - (void)resumeUpdate:(id)resumableUpdate { - [self.uiDriver resumeUpdate:resumableUpdate]; + [_uiDriver resumeUpdate:resumableUpdate]; } - (void)uiDriverDidShowUpdate { // When a new update check has not been initiated and an update has been resumed, // update the driver to indicate we are showing an update to the user - self.showingUpdate = YES; + _showingUpdate = YES; - if (self.updateDidShowHandler != nil) { - self.updateDidShowHandler(); - self.updateDidShowHandler = nil; + if (_updateDidShowHandler != nil) { + _updateDidShowHandler(); + _updateDidShowHandler = nil; } } @@ -117,12 +115,12 @@ - (void)basicDriverDidFinishLoadingAppcast { - if (self.showingUserInitiatedProgress) { - self.showingUserInitiatedProgress = NO; + if (_showingUserInitiatedProgress) { + _showingUserInitiatedProgress = NO; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" - if ([self.userDriver respondsToSelector:@selector(dismissUserInitiatedUpdateCheck)]) { - [self.userDriver dismissUserInitiatedUpdateCheck]; + if ([_userDriver respondsToSelector:@selector(dismissUserInitiatedUpdateCheck)]) { + [_userDriver dismissUserInitiatedUpdateCheck]; } #pragma clang diagnostic pop } @@ -135,17 +133,17 @@ - (void)abortUpdateWithError:(nullable NSError *)error { - if (self.showingUserInitiatedProgress) { + if (_showingUserInitiatedProgress) { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" - if ([self.userDriver respondsToSelector:@selector(dismissUserInitiatedUpdateCheck)]) { - [self.userDriver dismissUserInitiatedUpdateCheck]; + if ([_userDriver respondsToSelector:@selector(dismissUserInitiatedUpdateCheck)]) { + [_userDriver dismissUserInitiatedUpdateCheck]; } #pragma clang diagnostic pop - self.showingUserInitiatedProgress = NO; + _showingUserInitiatedProgress = NO; } - self.aborted = YES; - [self.uiDriver abortUpdateWithError:error showErrorToUser:YES]; + _aborted = YES; + [_uiDriver abortUpdateWithError:error showErrorToUser:YES]; } @end diff --git a/Sparkle/SPUUserUpdateState.h b/Sparkle/SPUUserUpdateState.h index f7fcc1e8..06725ccc 100644 --- a/Sparkle/SPUUserUpdateState.h +++ b/Sparkle/SPUUserUpdateState.h @@ -11,7 +11,15 @@ #import +#if defined(BUILDING_SPARKLE_SOURCES_EXTERNALLY) +// Ignore incorrect warning +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wquoted-include-in-framework-header" +#import "SUExport.h" +#pragma clang diagnostic pop +#else #import +#endif NS_ASSUME_NONNULL_BEGIN diff --git a/Sparkle/SPUUserUpdateState.m b/Sparkle/SPUUserUpdateState.m index 32654807..176c7af5 100644 --- a/Sparkle/SPUUserUpdateState.m +++ b/Sparkle/SPUUserUpdateState.m @@ -37,8 +37,8 @@ - (void)encodeWithCoder:(NSCoder *)encoder { - [encoder encodeInteger:self.stage forKey:SPUUserUpdateStateStageKey]; - [encoder encodeBool:self.userInitiated forKey:SPUUserUpdateStateUserInitiatedKey]; + [encoder encodeInteger:_stage forKey:SPUUserUpdateStateStageKey]; + [encoder encodeBool:_userInitiated forKey:SPUUserUpdateStateUserInitiatedKey]; } - (instancetype)initWithCoder:(NSCoder *)decoder diff --git a/Sparkle/SUAppcast+Private.h b/Sparkle/SUAppcast+Private.h index bf6a0a8b..a472a87c 100644 --- a/Sparkle/SUAppcast+Private.h +++ b/Sparkle/SUAppcast+Private.h @@ -8,6 +8,16 @@ #import +#ifdef BUILDING_SPARKLE_SOURCES_EXTERNALLY +// Ignore incorrect warning +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wquoted-include-in-framework-header" +#import "SUAppcast.h" +#pragma clang diagnostic pop +#else +#import +#endif + NS_ASSUME_NONNULL_BEGIN @class SPUAppcastItemStateResolver; diff --git a/Sparkle/SUAppcast.h b/Sparkle/SUAppcast.h index 3454b1b0..4f8e3cb1 100644 --- a/Sparkle/SUAppcast.h +++ b/Sparkle/SUAppcast.h @@ -10,7 +10,15 @@ #define SUAPPCAST_H #import +#if defined(BUILDING_SPARKLE_SOURCES_EXTERNALLY) +// Ignore incorrect warning +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wquoted-include-in-framework-header" +#import "SUExport.h" +#pragma clang diagnostic pop +#else #import +#endif NS_ASSUME_NONNULL_BEGIN @@ -28,7 +36,7 @@ SU_EXPORT @interface SUAppcast : NSObject These `SUAppcastItem` items are in the same order as specified in the appcast XML feed and are thus not sorted by version. */ -@property (readonly, copy) NSArray *items; +@property (readonly, nonatomic, copy) NSArray *items; @end diff --git a/Sparkle/SUAppcast.m b/Sparkle/SUAppcast.m index 9c5ddb9b..843e8c6d 100644 --- a/Sparkle/SUAppcast.m +++ b/Sparkle/SUAppcast.m @@ -21,12 +21,6 @@ #include "AppKitPrevention.h" -@interface SUAppcast () - -@property (nonatomic, copy) NSArray *items; - -@end - @implementation SUAppcast @synthesize items = _items; @@ -43,7 +37,7 @@ return self; } -- (NSDictionary *)attributesOfNode:(NSXMLElement *)node +- (NSDictionary *)attributesOfNode:(NSXMLElement *)node SPU_OBJC_DIRECT { NSEnumerator *attributeEnum = [[node attributes] objectEnumerator]; NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; @@ -61,7 +55,8 @@ return dictionary; } --(NSString *)sparkleNamespacedNameOfNode:(NSXMLNode *)node { +-(NSString *)sparkleNamespacedNameOfNode:(NSXMLNode *)node SPU_OBJC_DIRECT +{ // XML namespace prefix is semantically meaningless, so compare namespace URI // NS URI isn't used to fetch anything, and must match exactly, so we look for http:// not https:// if ([[node URI] isEqualToString:@"http://www.andymatuschak.org/xml-namespaces/sparkle"]) { @@ -73,7 +68,8 @@ } } --(NSArray *)parseAppcastItemsFromXMLData:(NSData *)appcastData relativeToURL:(NSURL * _Nullable)appcastURL stateResolver:(SPUAppcastItemStateResolver *)stateResolver error:(NSError *__autoreleasing*)errorp { +-(NSArray *)parseAppcastItemsFromXMLData:(NSData *)appcastData relativeToURL:(NSURL * _Nullable)appcastURL stateResolver:(SPUAppcastItemStateResolver *)stateResolver error:(NSError *__autoreleasing*)errorp SPU_OBJC_DIRECT +{ if (errorp) { *errorp = nil; } @@ -201,7 +197,7 @@ return appcastItems; } -- (NSXMLNode *)bestNodeInNodes:(NSArray *)nodes +- (NSXMLNode *)bestNodeInNodes:(NSArray *)nodes SPU_OBJC_DIRECT { // We use this method to pick out the localized version of a node when one's available. if ([nodes count] == 1) @@ -229,13 +225,13 @@ SUAppcast *other = [SUAppcast new]; NSMutableArray *newItems = [NSMutableArray new]; - for (SUAppcastItem *item in self.items) { + for (SUAppcastItem *item in _items) { if (filterBlock(item)) { [newItems addObject:item]; } } - other.items = newItems; + other->_items = newItems; return other; } diff --git a/Sparkle/SUAppcastDriver.h b/Sparkle/SUAppcastDriver.h index 33ef4058..4830babe 100644 --- a/Sparkle/SUAppcastDriver.h +++ b/Sparkle/SUAppcastDriver.h @@ -22,6 +22,9 @@ NS_ASSUME_NONNULL_BEGIN @end +#ifndef BUILDING_SPARKLE_TESTS +SPU_OBJC_DIRECT_MEMBERS +#endif @interface SUAppcastDriver : NSObject - (instancetype)initWithHost:(SUHost *)host updater:(id)updater updaterDelegate:(nullable id )updaterDelegate delegate:(nullable id )delegate; diff --git a/Sparkle/SUAppcastDriver.m b/Sparkle/SUAppcastDriver.m index 827ed5bf..22885e23 100644 --- a/Sparkle/SUAppcastDriver.m +++ b/Sparkle/SUAppcastDriver.m @@ -13,7 +13,6 @@ #import "SUAppcastItem+Private.h" #import "SUVersionComparisonProtocol.h" #import "SUStandardVersionComparator.h" -#import "SUOperatingSystem.h" #import "SPUUpdaterDelegate.h" #import "SUHost.h" #import "SPUSkippedUpdate.h" @@ -32,22 +31,17 @@ #include "AppKitPrevention.h" @interface SUAppcastDriver () - -@property (nonatomic, readonly) SUHost *host; -@property (nonatomic, readonly, weak) id updater; -@property (nullable, nonatomic, readonly, weak) id updaterDelegate; -@property (nullable, nonatomic, readonly, weak) id delegate; -@property (nonatomic) SPUDownloadDriver *downloadDriver; - @end @implementation SUAppcastDriver - -@synthesize host = _host; -@synthesize updater = _updater; -@synthesize updaterDelegate = _updaterDelegate; -@synthesize delegate = _delegate; -@synthesize downloadDriver = _downloadDriver; +{ + SUHost *_host; + SPUDownloadDriver *_downloadDriver; + + __weak id _updater; + __weak id _updaterDelegate; + __weak id _delegate; +} - (instancetype)initWithHost:(SUHost *)host updater:(id)updater updaterDelegate:(id )updaterDelegate delegate:(id )delegate { @@ -69,28 +63,28 @@ } requestHTTPHeaders[@"Accept"] = @"application/rss+xml,*/*;q=0.1"; - self.downloadDriver = [[SPUDownloadDriver alloc] initWithRequestURL:appcastURL host:self.host userAgent:userAgent httpHeaders:requestHTTPHeaders inBackground:background delegate:self]; + _downloadDriver = [[SPUDownloadDriver alloc] initWithRequestURL:appcastURL host:_host userAgent:userAgent httpHeaders:requestHTTPHeaders inBackground:background delegate:self]; - [self.downloadDriver downloadFile]; + [_downloadDriver downloadFile]; } - (void)downloadDriverDidDownloadData:(SPUDownloadData *)downloadData { - SPUAppcastItemStateResolver *stateResolver = [[SPUAppcastItemStateResolver alloc] initWithHostVersion:self.host.version applicationVersionComparator:[self versionComparator] standardVersionComparator:[SUStandardVersionComparator defaultComparator]]; + SPUAppcastItemStateResolver *stateResolver = [[SPUAppcastItemStateResolver alloc] initWithHostVersion:_host.version applicationVersionComparator:[self versionComparator] standardVersionComparator:[SUStandardVersionComparator defaultComparator]]; NSError *appcastError = nil; SUAppcast *appcast = [[SUAppcast alloc] initWithXMLData:downloadData.data relativeToURL:downloadData.URL stateResolver:stateResolver error:&appcastError]; if (appcast == nil) { - NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithObject:SULocalizedString(@"An error occurred while parsing the update feed.", nil) forKey:NSLocalizedDescriptionKey]; + NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithObject:SULocalizedStringFromTableInBundle(@"An error occurred while parsing the update feed.", SPARKLE_TABLE, SUSparkleBundle(), nil) forKey:NSLocalizedDescriptionKey]; if (appcastError != nil) { [userInfo setObject:appcastError forKey:NSUnderlyingErrorKey]; } - [self.delegate didFailToFetchAppcastWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUAppcastParseError userInfo:userInfo]]; + [_delegate didFailToFetchAppcastWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUAppcastParseError userInfo:userInfo]]; } else { - [self appcastDidFinishLoading:appcast inBackground:self.downloadDriver.inBackground]; + [self appcastDidFinishLoading:appcast inBackground:_downloadDriver.inBackground]; } } @@ -98,18 +92,18 @@ { SULog(SULogLevelError, @"Encountered download feed error: %@", error); - NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:@{NSLocalizedDescriptionKey:SULocalizedString(@"An error occurred in retrieving update information. Please try again later.", nil)}]; + NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:@{NSLocalizedDescriptionKey:SULocalizedStringFromTableInBundle(@"An error occurred in retrieving update information. Please try again later.", SPARKLE_TABLE, SUSparkleBundle(), nil)}]; if (error != nil) { [userInfo setObject:error forKey:NSUnderlyingErrorKey]; } - [self.delegate didFailToFetchAppcastWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUDownloadError userInfo:userInfo]]; + [_delegate didFailToFetchAppcastWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUDownloadError userInfo:userInfo]]; } -- (SUAppcastItem * _Nullable)preferredUpdateForRegularAppcastItem:(SUAppcastItem * _Nullable)regularItem secondaryUpdate:(SUAppcastItem * __autoreleasing _Nullable *)secondaryUpdate +- (SUAppcastItem * _Nullable)preferredUpdateForRegularAppcastItem:(SUAppcastItem * _Nullable)regularItem secondaryUpdate:(SUAppcastItem * __autoreleasing _Nullable *)secondaryUpdate SPU_OBJC_DIRECT { - SUAppcastItem *deltaItem = (regularItem != nil) ? [[self class] deltaUpdateFromAppcastItem:regularItem hostVersion:self.host.version] : nil; + SUAppcastItem *deltaItem = (regularItem != nil) ? [[self class] deltaUpdateFromAppcastItem:regularItem hostVersion:_host.version] : nil; BOOL supportsDeltaItem; if (deltaItem == nil) { @@ -125,7 +119,7 @@ NSFileManager *fileManager = NSFileManager.defaultManager; - NSBundle *hostBundle = self.host.bundle; + NSBundle *hostBundle = _host.bundle; NSString *sparkleExecutablePath; NSString *sparkleResourcesPath; if ([hostBundle isEqual:NSBundle.mainBundle]) { @@ -225,14 +219,16 @@ } } -- (SUAppcastItem *)retrieveBestAppcastItemFromAppcast:(SUAppcast *)appcast versionComparator:(id)versionComparator secondaryUpdate:(SUAppcastItem * __autoreleasing _Nullable *)secondaryAppcastItem +- (SUAppcastItem *)retrieveBestAppcastItemFromAppcast:(SUAppcast *)appcast versionComparator:(id)versionComparator secondaryUpdate:(SUAppcastItem * __autoreleasing _Nullable *)secondaryAppcastItem SPU_OBJC_DIRECT { // Find the best valid update in the appcast by asking the delegate // Don't ask the delegate if the appcast has no items though + id updaterDelegate = _updaterDelegate; + id updater = _updater; SUAppcastItem *regularItemFromDelegate; BOOL delegateOptedOutOfSelection; - if (appcast.items.count > 0 && [self.updaterDelegate respondsToSelector:@selector((bestValidUpdateInAppcast:forUpdater:))]) { - SUAppcastItem *candidateItem = [self.updaterDelegate bestValidUpdateInAppcast:appcast forUpdater:(id _Nonnull)self.updater]; + if (appcast.items.count > 0 && updater != nil && [updaterDelegate respondsToSelector:@selector((bestValidUpdateInAppcast:forUpdater:))]) { + SUAppcastItem *candidateItem = [updaterDelegate bestValidUpdateInAppcast:appcast forUpdater:updater]; if (candidateItem == SUAppcastItem.emptyAppcastItem) { regularItemFromDelegate = nil; @@ -260,7 +256,7 @@ // Take care of finding best appcast item ourselves if delegate does not SUAppcastItem *regularItem; if (regularItemFromDelegate == nil && !delegateOptedOutOfSelection) { - regularItem = [[self class] bestItemFromAppcastItems:appcast.items comparator:versionComparator]; + regularItem = [SUAppcastDriver bestItemFromAppcastItems:appcast.items comparator:versionComparator]; } else { regularItem = regularItemFromDelegate; } @@ -271,16 +267,21 @@ return [self preferredUpdateForRegularAppcastItem:regularItem secondaryUpdate:secondaryAppcastItem]; } -- (void)appcastDidFinishLoading:(SUAppcast *)loadedAppcast inBackground:(BOOL)background +- (void)appcastDidFinishLoading:(SUAppcast *)loadedAppcast inBackground:(BOOL)background SPU_OBJC_DIRECT { - [self.delegate didFinishLoadingAppcast:loadedAppcast]; + id delegate = _delegate; + [delegate didFinishLoadingAppcast:loadedAppcast]; - NSDictionary *userInfo = @{ SUUpdaterAppcastNotificationKey: loadedAppcast }; - [[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterDidFinishLoadingAppCastNotification object:self.updater userInfo:userInfo]; + id updater = _updater; + if (updater != nil) { + NSDictionary *userInfo = @{ SUUpdaterAppcastNotificationKey: loadedAppcast }; + [[NSNotificationCenter defaultCenter] postNotificationName:SUUpdaterDidFinishLoadingAppCastNotification object:updater userInfo:userInfo]; + } NSSet *allowedChannels; - if ([self.updaterDelegate respondsToSelector:@selector(allowedChannelsForUpdater:)]) { - allowedChannels = [self.updaterDelegate allowedChannelsForUpdater:self.updater]; + id updaterDelegate = _updaterDelegate; + if (updater != nil && [updaterDelegate respondsToSelector:@selector(allowedChannelsForUpdater:)]) { + allowedChannels = [updaterDelegate allowedChannelsForUpdater:updater]; if (allowedChannels == nil) { SULog(SULogLevelError, @"Error: -allowedChannelsForUpdater: cannot return nil. Treating this as an empty set."); allowedChannels = [NSSet set]; @@ -289,13 +290,13 @@ allowedChannels = [NSSet set]; } - SUAppcast *macOSAppcast = [[self class] filterAppcast:loadedAppcast forMacOSAndAllowedChannels:allowedChannels]; + SUAppcast *macOSAppcast = [SUAppcastDriver filterAppcast:loadedAppcast forMacOSAndAllowedChannels:allowedChannels]; id applicationVersionComparator = [self versionComparator]; - NSNumber *phasedUpdateGroup = background ? @([SUPhasedUpdateGroupInfo updateGroupForHost:self.host]) : nil; + NSNumber *phasedUpdateGroup = background ? @([SUPhasedUpdateGroupInfo updateGroupForHost:_host]) : nil; - SPUSkippedUpdate *skippedUpdate = background ? [SPUSkippedUpdate skippedUpdateForHost:self.host] : nil; + SPUSkippedUpdate *skippedUpdate = background ? [SPUSkippedUpdate skippedUpdateForHost:_host] : nil; NSDate *currentDate = [NSDate date]; @@ -303,7 +304,7 @@ // the minimum autoupdate version. We filter out updates that fail the minimum // autoupdate version test because we have a preference over minor updates that can be // downloaded and installed with less disturbance - SUAppcast *passesMinimumAutoupdateAppcast = [[self class] filterSupportedAppcast:macOSAppcast phasedUpdateGroup:phasedUpdateGroup skippedUpdate:skippedUpdate currentDate:currentDate hostVersion:self.host.version versionComparator:applicationVersionComparator testOSVersion:YES testMinimumAutoupdateVersion:YES]; + SUAppcast *passesMinimumAutoupdateAppcast = [SUAppcastDriver filterSupportedAppcast:macOSAppcast phasedUpdateGroup:phasedUpdateGroup skippedUpdate:skippedUpdate currentDate:currentDate hostVersion:_host.version versionComparator:applicationVersionComparator testOSVersion:YES testMinimumAutoupdateVersion:YES]; SUAppcastItem *secondaryItemPassesMinimumAutoupdate = nil; SUAppcastItem *primaryItemPassesMinimumAutoupdate = [self retrieveBestAppcastItemFromAppcast:passesMinimumAutoupdateAppcast versionComparator:applicationVersionComparator secondaryUpdate:&secondaryItemPassesMinimumAutoupdate]; @@ -313,7 +314,7 @@ SUAppcastItem *finalPrimaryItem; SUAppcastItem *finalSecondaryItem = nil; if (![self isItemNewer:primaryItemPassesMinimumAutoupdate]) { - SUAppcast *failsMinimumAutoupdateAppcast = [[self class] filterSupportedAppcast:macOSAppcast phasedUpdateGroup:phasedUpdateGroup skippedUpdate:skippedUpdate currentDate:currentDate hostVersion:self.host.version versionComparator:applicationVersionComparator testOSVersion:YES testMinimumAutoupdateVersion:NO]; + SUAppcast *failsMinimumAutoupdateAppcast = [SUAppcastDriver filterSupportedAppcast:macOSAppcast phasedUpdateGroup:phasedUpdateGroup skippedUpdate:skippedUpdate currentDate:currentDate hostVersion:_host.version versionComparator:applicationVersionComparator testOSVersion:YES testMinimumAutoupdateVersion:NO]; finalPrimaryItem = [self retrieveBestAppcastItemFromAppcast:failsMinimumAutoupdateAppcast versionComparator:applicationVersionComparator secondaryUpdate:&finalSecondaryItem]; } else { @@ -323,28 +324,31 @@ if ([self isItemNewer:finalPrimaryItem]) { // We found a suitable update - [self.delegate didFindValidUpdateWithAppcastItem:finalPrimaryItem secondaryAppcastItem:finalSecondaryItem]; + [delegate didFindValidUpdateWithAppcastItem:finalPrimaryItem secondaryAppcastItem:finalSecondaryItem]; } else { // Find the latest appcast item that we can report to the user and updater delegates // This may include updates that fail due to OS version requirements. // This excludes newer backgrounded updates that fail because they are skipped or not in current phased rollout group - SUAppcast *notFoundAppcast = [[self class] filterSupportedAppcast:macOSAppcast phasedUpdateGroup:phasedUpdateGroup skippedUpdate:skippedUpdate currentDate:currentDate hostVersion:self.host.version versionComparator:applicationVersionComparator testOSVersion:NO testMinimumAutoupdateVersion:NO]; + SUAppcast *notFoundAppcast = [SUAppcastDriver filterSupportedAppcast:macOSAppcast phasedUpdateGroup:phasedUpdateGroup skippedUpdate:skippedUpdate currentDate:currentDate hostVersion:_host.version versionComparator:applicationVersionComparator testOSVersion:NO testMinimumAutoupdateVersion:NO]; SUAppcastItem *notFoundPrimaryItem = [self retrieveBestAppcastItemFromAppcast:notFoundAppcast versionComparator:applicationVersionComparator secondaryUpdate:nil]; NSComparisonResult hostToLatestAppcastItemComparisonResult; if (notFoundPrimaryItem != nil) { - hostToLatestAppcastItemComparisonResult = [applicationVersionComparator compareVersion:self.host.version toVersion:notFoundPrimaryItem.versionString]; + hostToLatestAppcastItemComparisonResult = [applicationVersionComparator compareVersion:_host.version toVersion:notFoundPrimaryItem.versionString]; } else { hostToLatestAppcastItemComparisonResult = 0; } - [self.delegate didNotFindUpdateWithLatestAppcastItem:notFoundPrimaryItem hostToLatestAppcastItemComparisonResult:hostToLatestAppcastItemComparisonResult background:background]; + [delegate didNotFindUpdateWithLatestAppcastItem:notFoundPrimaryItem hostToLatestAppcastItemComparisonResult:hostToLatestAppcastItemComparisonResult background:background]; } } -// This method is used by unit tests +// Note: This method is used by unit tests + (SUAppcast *)filterAppcast:(SUAppcast *)appcast forMacOSAndAllowedChannels:(NSSet *)allowedChannels +#ifndef BUILDING_SPARKLE_TESTS +SPU_OBJC_DIRECT +#endif { return [appcast copyByFilteringItems:^(SUAppcastItem *item) { // We will never care about other OS's @@ -369,8 +373,11 @@ }]; } -// This method is used by unit tests +// Note: This method is used by unit tests + (SUAppcast *)filterSupportedAppcast:(SUAppcast *)appcast phasedUpdateGroup:(NSNumber * _Nullable)phasedUpdateGroup skippedUpdate:(SPUSkippedUpdate * _Nullable)skippedUpdate currentDate:(NSDate *)currentDate hostVersion:(NSString *)hostVersion versionComparator:(id)versionComparator testOSVersion:(BOOL)testOSVersion testMinimumAutoupdateVersion:(BOOL)testMinimumAutoupdateVersion +#ifndef BUILDING_SPARKLE_TESTS +SPU_OBJC_DIRECT +#endif { BOOL hostPassesSkippedMajorVersion = [SPUAppcastItemStateResolver isMinimumAutoupdateVersionOK:skippedUpdate.majorVersion hostVersion:hostVersion versionComparator:versionComparator]; @@ -404,9 +411,12 @@ return item; } -// This method is used by unit tests +// Note: this method is used by unit tests // This method should not do *any* filtering, only version comparing + (SUAppcastItem *)bestItemFromAppcastItems:(NSArray *)appcastItems getDeltaItem:(SUAppcastItem * __autoreleasing *)deltaItem withHostVersion:(NSString *)hostVersion comparator:(id)comparator +#ifndef BUILDING_SPARKLE_TESTS +SPU_OBJC_DIRECT +#endif { SUAppcastItem *item = [self bestItemFromAppcastItems:appcastItems comparator:comparator]; if (item != nil && deltaItem != NULL) { @@ -415,13 +425,14 @@ return item; } -- (id)versionComparator +- (id)versionComparator SPU_OBJC_DIRECT { id comparator = nil; // Give the delegate a chance to provide a custom version comparator - if ([self.updaterDelegate respondsToSelector:@selector((versionComparatorForUpdater:))]) { - comparator = [self.updaterDelegate versionComparatorForUpdater:self.updater]; + id updaterDelegate = _updaterDelegate; + if ([updaterDelegate respondsToSelector:@selector((versionComparatorForUpdater:))]) { + comparator = [updaterDelegate versionComparatorForUpdater:_updater]; } // If we don't get a comparator from the delegate, use the default comparator @@ -432,12 +443,12 @@ return comparator; } -- (BOOL)isItemNewer:(SUAppcastItem *)ui +- (BOOL)isItemNewer:(SUAppcastItem *)ui SPU_OBJC_DIRECT { - return ui != nil && [[self versionComparator] compareVersion:self.host.version toVersion:ui.versionString] == NSOrderedAscending; + return ui != nil && [[self versionComparator] compareVersion:_host.version toVersion:ui.versionString] == NSOrderedAscending; } -+ (BOOL)item:(SUAppcastItem *)ui containsSkippedUpdate:(SPUSkippedUpdate * _Nullable)skippedUpdate hostPassesSkippedMajorVersion:(BOOL)hostPassesSkippedMajorVersion versionComparator:(id)versionComparator ++ (BOOL)item:(SUAppcastItem *)ui containsSkippedUpdate:(SPUSkippedUpdate * _Nullable)skippedUpdate hostPassesSkippedMajorVersion:(BOOL)hostPassesSkippedMajorVersion versionComparator:(id)versionComparator SPU_OBJC_DIRECT { NSString *skippedMajorVersion = skippedUpdate.majorVersion; NSString *skippedMajorSubreleaseVersion = skippedUpdate.majorSubreleaseVersion; @@ -460,7 +471,7 @@ return NO; } -+ (BOOL)itemIsReadyForPhasedRollout:(SUAppcastItem *)ui phasedUpdateGroup:(NSNumber * _Nullable)phasedUpdateGroup currentDate:(NSDate *)currentDate hostVersion:(NSString *)hostVersion versionComparator:(id)versionComparator ++ (BOOL)itemIsReadyForPhasedRollout:(SUAppcastItem *)ui phasedUpdateGroup:(NSNumber * _Nullable)phasedUpdateGroup currentDate:(NSDate *)currentDate hostVersion:(NSString *)hostVersion versionComparator:(id)versionComparator SPU_OBJC_DIRECT { if (phasedUpdateGroup == nil || ui.criticalUpdate) { return YES; @@ -490,10 +501,10 @@ - (void)cleanup:(void (^)(void))completionHandler { - if (self.downloadDriver == nil) { + if (_downloadDriver == nil) { completionHandler(); } else { - [self.downloadDriver cleanup:completionHandler]; + [_downloadDriver cleanup:completionHandler]; } } diff --git a/Sparkle/SUAppcastItem+Private.h b/Sparkle/SUAppcastItem+Private.h index 7527a8f0..1005ded9 100644 --- a/Sparkle/SUAppcastItem+Private.h +++ b/Sparkle/SUAppcastItem+Private.h @@ -28,9 +28,9 @@ NS_ASSUME_NONNULL_BEGIN - (nullable instancetype)initWithDictionary:(NSDictionary *)dict relativeToURL:(NSURL * _Nullable)appcastURL stateResolver:(SPUAppcastItemStateResolver *)stateResolver failureReason:(NSString * _Nullable __autoreleasing *_Nullable)error; /** - The DSA and EdDSA signatures along with their statuses. + The EdDSA and DSA signatures along with their statuses. */ -@property (readonly, nullable) SUSignatures *signatures; +@property (readonly, nonatomic, nullable) SUSignatures *signatures; @end diff --git a/Sparkle/SUAppcastItem.h b/Sparkle/SUAppcastItem.h index c53c87ca..be6e8212 100644 --- a/Sparkle/SUAppcastItem.h +++ b/Sparkle/SUAppcastItem.h @@ -11,7 +11,7 @@ #import -#ifdef BUILDING_SPARKLE_TESTS +#ifdef BUILDING_SPARKLE_SOURCES_EXTERNALLY // Ignore incorrect warning #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wquoted-include-in-framework-header" @@ -45,7 +45,7 @@ SU_EXPORT @interface SUAppcastItem : NSObject This is extracted from the @c element, or the @c sparkle:version attribute from the @c element. */ -@property (copy, readonly) NSString *versionString; +@property (nonatomic, copy, readonly) NSString *versionString; /** The human-readable display version of the update item if provided. @@ -58,7 +58,7 @@ SU_EXPORT @interface SUAppcastItem : NSObject If no short version string is available, this falls back to the update's `versionString`. */ -@property (copy, readonly) NSString *displayVersionString; +@property (nonatomic, copy, readonly) NSString *displayVersionString; /** The file URL to the update item if provided. @@ -70,7 +70,7 @@ SU_EXPORT @interface SUAppcastItem : NSObject This is extracted from the @c url attribute in the @c element. */ -@property (readonly, nullable) NSURL *fileURL; +@property (nonatomic, readonly, nullable) NSURL *fileURL; /** The content length of the download in bytes. @@ -95,7 +95,7 @@ SU_EXPORT @interface SUAppcastItem : NSObject This is extracted from the @c element. */ -@property (readonly, nullable) NSURL *infoURL; +@property (nonatomic, readonly, nullable) NSURL *infoURL; /** Indicates whether or not the update item is only informational and has no download. @@ -106,14 +106,14 @@ SU_EXPORT @interface SUAppcastItem : NSObject Otherwise this is determined based on the contents extracted from the @c element. */ -@property (getter=isInformationOnlyUpdate, readonly) BOOL informationOnlyUpdate; +@property (nonatomic, getter=isInformationOnlyUpdate, readonly) BOOL informationOnlyUpdate; /** The title of the appcast item if provided. This is extracted from the @c element. */ -@property (copy, readonly, nullable) NSString *title; +@property (nonatomic, copy, readonly, nullable) NSString *title; /** The date string of the appcast item if provided. @@ -123,7 +123,7 @@ SU_EXPORT @interface SUAppcastItem : NSObject<NSSecureCoding> This is extracted from the @c <pubDate> element. */ -@property (copy, readonly, nullable) NSString *dateString; +@property (nonatomic, copy, readonly, nullable) NSString *dateString; /** The date constructed from the `dateString` property if provided. @@ -132,7 +132,7 @@ SU_EXPORT @interface SUAppcastItem : NSObject<NSSecureCoding> This date is constructed using the @c en_US locale. */ -@property (copy, readonly, nullable) NSDate *date; +@property (nonatomic, copy, readonly, nullable) NSDate *date; /** The release notes URL of the appcast item if provided. @@ -143,7 +143,7 @@ SU_EXPORT @interface SUAppcastItem : NSObject<NSSecureCoding> This is extracted from the @c <sparkle:releaseNotesLink> element. */ -@property (readonly, nullable) NSURL *releaseNotesURL; +@property (nonatomic, readonly, nullable) NSURL *releaseNotesURL; /** The description of the appcast item if provided. @@ -153,7 +153,7 @@ SU_EXPORT @interface SUAppcastItem : NSObject<NSSecureCoding> This is extracted from the @c <description> element. */ -@property (copy, readonly, nullable) NSString *itemDescription; +@property (nonatomic, copy, readonly, nullable) NSString *itemDescription; /** The full release notes URL of the appcast item if provided. @@ -164,7 +164,7 @@ SU_EXPORT @interface SUAppcastItem : NSObject<NSSecureCoding> This is extracted from the @c <sparkle:fullReleaseNotesLink> element. */ -@property (readonly, nullable) NSURL *fullReleaseNotesURL; +@property (nonatomic, readonly, nullable) NSURL *fullReleaseNotesURL; /** The required minimum system operating version string for this update if provided. @@ -177,7 +177,7 @@ SU_EXPORT @interface SUAppcastItem : NSObject<NSSecureCoding> This is extracted from the @c <sparkle:minimumSystemVersion> element. */ -@property (copy, readonly, nullable) NSString *minimumSystemVersion; +@property (nonatomic, copy, readonly, nullable) NSString *minimumSystemVersion; /** Indicates whether or not the current running system passes the `minimumSystemVersion` requirement. @@ -197,7 +197,7 @@ SU_EXPORT @interface SUAppcastItem : NSObject<NSSecureCoding> This is extracted from the @c <sparkle:maximumSystemVersion> element. */ -@property (copy, readonly, nullable) NSString *maximumSystemVersion; +@property (nonatomic, copy, readonly, nullable) NSString *maximumSystemVersion; /** Indicates whether or not the current running system passes the `maximumSystemVersion` requirement. @@ -248,7 +248,7 @@ SU_EXPORT @interface SUAppcastItem : NSObject<NSSecureCoding> Old applications must be using Sparkle 1.25 or later to support phased rollout intervals, otherwise they may assume updates are immediately available. */ -@property (copy, readonly, nullable) NSNumber* phasedRolloutInterval; +@property (nonatomic, copy, readonly, nullable) NSNumber* phasedRolloutInterval; /** The minimum bundle version string this update requires for automatically downloading and installing updates if provided. @@ -263,14 +263,14 @@ SU_EXPORT @interface SUAppcastItem : NSObject<NSSecureCoding> This is extracted from the @c <sparkle:minimumAutoupdateVersion> element. */ -@property (copy, readonly, nullable) NSString *minimumAutoupdateVersion; +@property (nonatomic, copy, readonly, nullable) NSString *minimumAutoupdateVersion; /** Indicates whether or not the update item is a major upgrade. An update is a major upgrade if the application's bundle version doesn't meet the `minimumAutoupdateVersion` requirement. */ -@property (getter=isMajorUpgrade, readonly) BOOL majorUpgrade; +@property (nonatomic, getter=isMajorUpgrade, readonly) BOOL majorUpgrade; /** Previously skipped upgrades by the user will be ignored if they skipped an update whose version precedes this version. @@ -294,7 +294,7 @@ SU_EXPORT @interface SUAppcastItem : NSObject<NSSecureCoding> Old applications must be using Sparkle 2 or later to support the top-level @c <sparkle:criticalUpdate> element. */ -@property (getter=isCriticalUpdate, readonly) BOOL criticalUpdate; +@property (nonatomic, getter=isCriticalUpdate, readonly) BOOL criticalUpdate; /** Specifies the operating system the download update is available for if provided. @@ -310,14 +310,14 @@ SU_EXPORT @interface SUAppcastItem : NSObject<NSSecureCoding> This is extracted from the @c sparkle:os attribute in the @c <enclosure> element. */ -@property (copy, readonly, nullable) NSString *osString; +@property (nonatomic, copy, readonly, nullable) NSString *osString; /** Indicates whether or not this update item is for macOS. This is determined from the `osString` property. */ -@property (getter=isMacOsUpdate, readonly) BOOL macOsUpdate; +@property (nonatomic, getter=isMacOsUpdate, readonly) BOOL macOsUpdate; /** The delta updates for this update item. @@ -331,7 +331,7 @@ SU_EXPORT @interface SUAppcastItem : NSObject<NSSecureCoding> This is extracted from the @c <sparkle:deltas> element. */ -@property (copy, readonly, nullable) NSDictionary<NSString *, SUAppcastItem *> *deltaUpdates; +@property (nonatomic, copy, readonly, nullable) NSDictionary<NSString *, SUAppcastItem *> *deltaUpdates; /** The expected size of the Sparkle executable file before applying this delta update. @@ -342,7 +342,7 @@ SU_EXPORT @interface SUAppcastItem : NSObject<NSSecureCoding> This is extracted from the @c sparkle:deltaFromSparkleExecutableSize attribute from the @c <enclosure> element of a @c sparkle:deltas item. This attribute is optional for delta update items. */ -@property (nonatomic, readonly, nullable) NSNumber *deltaFromSparkleExecutableSize; +@property (nonatomic, nonatomic, readonly, nullable) NSNumber *deltaFromSparkleExecutableSize; /** An expected set of Sparkle's locales present on disk before applying this delta update. @@ -354,21 +354,21 @@ SU_EXPORT @interface SUAppcastItem : NSObject<NSSecureCoding> This is extracted from the @c sparkle:deltaFromSparkleLocales attribute from the @c <enclosure> element of a @c sparkle:deltas item. The locales extracted from this attribute are delimited by a comma (e.g. "en,ca,fr,hr,hu"). This attribute is optional for delta update items. */ -@property (nonatomic, readonly, nullable) NSSet<NSString *> *deltaFromSparkleLocales; +@property (nonatomic, nonatomic, readonly, nullable) NSSet<NSString *> *deltaFromSparkleLocales; /** Indicates whether or not the update item is a delta update. An update item is a delta update if it is in the `deltaUpdates` of another update item. */ -@property (getter=isDeltaUpdate, readonly) BOOL deltaUpdate; +@property (nonatomic, getter=isDeltaUpdate, readonly) BOOL deltaUpdate; /** The dictionary representing the entire appcast item. This is useful for querying custom extensions or elements from the appcast item. */ -@property (readonly, copy) NSDictionary *propertiesDictionary; +@property (nonatomic, readonly, copy) NSDictionary *propertiesDictionary; - (instancetype)init NS_UNAVAILABLE; diff --git a/Sparkle/SUAppcastItem.m b/Sparkle/SUAppcastItem.m index 92cbf1b3..1a7fea27 100644 --- a/Sparkle/SUAppcastItem.m +++ b/Sparkle/SUAppcastItem.m @@ -42,22 +42,23 @@ static NSString *SUAppcastItemDeltaFromSparkleLocalesKey = @"SUAppcastItemDeltaF @interface SUAppcastItem () -@property (readonly, nullable) SUSignatures *signatures; - -// Auxillary appcast item state that needs to be evaluated based on the host state -// This may be nil if the client creates an SUAppcastItem with a deprecated initializer -// In that case we will need to fallback to safe behavior -@property (nonatomic, readonly, nullable) SPUAppcastItemState *state; - -// Indicates if we have any critical information. Used as a fallback if state is nil -@property (nonatomic, readonly) BOOL hasCriticalInformation; - -// Indicates the versions we update from that are informational-only -@property (nonatomic, readonly, nullable) NSSet<NSString *> *informationalUpdateVersions; +@property (readonly, nonatomic, nullable) SUSignatures *signatures; @end @implementation SUAppcastItem +{ + // Auxillary appcast item state that needs to be evaluated based on the host state + // This may be nil if the client creates an SUAppcastItem with a deprecated initializer + // In that case we will need to fallback to safe behavior + SPUAppcastItemState *_state; + + // Indicates if we have any critical information. Used as a fallback if state is nil + BOOL _hasCriticalInformation; + + // Indicates the versions we update from that are informational-only + NSSet<NSString *> *_informationalUpdateVersions; +} @synthesize dateString = _dateString; @synthesize deltaUpdates = _deltaUpdates; @@ -79,9 +80,6 @@ static NSString *SUAppcastItemDeltaFromSparkleLocalesKey = @"SUAppcastItemDeltaF @synthesize minimumAutoupdateVersion = _minimumAutoupdateVersion; @synthesize ignoreSkippedUpgradesBelowVersion = _ignoreSkippedUpgradesBelowVersion; @synthesize phasedRolloutInterval = _phasedRolloutInterval; -@synthesize state = _state; -@synthesize hasCriticalInformation = _hasCriticalInformation; -@synthesize informationalUpdateVersions = _informationalUpdateVersions; @synthesize channel = _channel; @synthesize deltaFromSparkleExecutableSize = _deltaFromSparkleExecutableSize; @synthesize deltaFromSparkleLocales = _deltaFromSparkleLocales; @@ -156,116 +154,116 @@ static NSString *SUAppcastItemDeltaFromSparkleLocalesKey = @"SUAppcastItemDeltaF - (void)encodeWithCoder:(NSCoder *)encoder { - if (self.deltaUpdates != nil) { - [encoder encodeObject:self.deltaUpdates forKey:SUAppcastItemDeltaUpdatesKey]; + if (_deltaUpdates != nil) { + [encoder encodeObject:_deltaUpdates forKey:SUAppcastItemDeltaUpdatesKey]; } - if (self.deltaFromSparkleExecutableSize != nil) { - [encoder encodeObject:self.deltaFromSparkleExecutableSize forKey:SUAppcastItemDeltaFromSparkleExecutableSizeKey]; + if (_deltaFromSparkleExecutableSize != nil) { + [encoder encodeObject:_deltaFromSparkleExecutableSize forKey:SUAppcastItemDeltaFromSparkleExecutableSizeKey]; } - if (self.deltaFromSparkleLocales != nil) { - [encoder encodeObject:self.deltaFromSparkleLocales forKey:SUAppcastItemDeltaFromSparkleLocalesKey]; + if (_deltaFromSparkleLocales != nil) { + [encoder encodeObject:_deltaFromSparkleLocales forKey:SUAppcastItemDeltaFromSparkleLocalesKey]; } - if (self.displayVersionString != nil) { - [encoder encodeObject:self.displayVersionString forKey:SUAppcastItemDisplayVersionStringKey]; + if (_displayVersionString != nil) { + [encoder encodeObject:_displayVersionString forKey:SUAppcastItemDisplayVersionStringKey]; } - if (self.signatures != nil) { - [encoder encodeObject:self.signatures forKey:SUAppcastItemSignaturesKey]; + if (_signatures != nil) { + [encoder encodeObject:_signatures forKey:SUAppcastItemSignaturesKey]; } - if (self.fileURL != nil) { - [encoder encodeObject:self.fileURL forKey:SUAppcastItemFileURLKey]; + if (_fileURL != nil) { + [encoder encodeObject:_fileURL forKey:SUAppcastItemFileURLKey]; } - if (self.infoURL != nil) { - [encoder encodeObject:self.infoURL forKey:SUAppcastItemInfoURLKey]; + if (_infoURL != nil) { + [encoder encodeObject:_infoURL forKey:SUAppcastItemInfoURLKey]; } - [encoder encodeInt64:(int64_t)self.contentLength forKey:SUAppcastItemContentLengthKey]; + [encoder encodeInt64:(int64_t)_contentLength forKey:SUAppcastItemContentLengthKey]; - if (self.itemDescription != nil) { - [encoder encodeObject:self.itemDescription forKey:SUAppcastItemDescriptionKey]; + if (_itemDescription != nil) { + [encoder encodeObject:_itemDescription forKey:SUAppcastItemDescriptionKey]; } - if (self.maximumSystemVersion != nil) { - [encoder encodeObject:self.maximumSystemVersion forKey:SUAppcastItemMaximumSystemVersionKey]; + if (_maximumSystemVersion != nil) { + [encoder encodeObject:_maximumSystemVersion forKey:SUAppcastItemMaximumSystemVersionKey]; } - if (self.minimumSystemVersion != nil) { - [encoder encodeObject:self.minimumSystemVersion forKey:SUAppcastItemMinimumSystemVersionKey]; + if (_minimumSystemVersion != nil) { + [encoder encodeObject:_minimumSystemVersion forKey:SUAppcastItemMinimumSystemVersionKey]; } - if (self.minimumAutoupdateVersion != nil) { - [encoder encodeObject:self.minimumAutoupdateVersion forKey:SUAppcastElementMinimumAutoupdateVersion]; + if (_minimumAutoupdateVersion != nil) { + [encoder encodeObject:_minimumAutoupdateVersion forKey:SUAppcastElementMinimumAutoupdateVersion]; } - if (self.ignoreSkippedUpgradesBelowVersion != nil) { - [encoder encodeObject:self.ignoreSkippedUpgradesBelowVersion forKey:SUAppcastElementIgnoreSkippedUpgradesBelowVersion]; + if (_ignoreSkippedUpgradesBelowVersion != nil) { + [encoder encodeObject:_ignoreSkippedUpgradesBelowVersion forKey:SUAppcastElementIgnoreSkippedUpgradesBelowVersion]; } - if (self.state != nil) { - [encoder encodeObject:self.state forKey:SUAppcastItemStateKey]; + if (_state != nil) { + [encoder encodeObject:_state forKey:SUAppcastItemStateKey]; } - if (self.releaseNotesURL != nil) { - [encoder encodeObject:self.releaseNotesURL forKey:SUAppcastItemReleaseNotesURLKey]; + if (_releaseNotesURL != nil) { + [encoder encodeObject:_releaseNotesURL forKey:SUAppcastItemReleaseNotesURLKey]; } - if (self.fullReleaseNotesURL != nil) { - [encoder encodeObject:self.fullReleaseNotesURL forKey:SUAppcastItemFullReleaseNotesURLKey]; + if (_fullReleaseNotesURL != nil) { + [encoder encodeObject:_fullReleaseNotesURL forKey:SUAppcastItemFullReleaseNotesURLKey]; } - if (self.title != nil) { - [encoder encodeObject:self.title forKey:SUAppcastItemTitleKey]; + if (_title != nil) { + [encoder encodeObject:_title forKey:SUAppcastItemTitleKey]; } - if (self.versionString != nil) { - [encoder encodeObject:self.versionString forKey:SUAppcastItemVersionStringKey]; + if (_versionString != nil) { + [encoder encodeObject:_versionString forKey:SUAppcastItemVersionStringKey]; } - if (self.osString != nil) { - [encoder encodeObject:self.osString forKey:SUAppcastAttributeOsType]; + if (_osString != nil) { + [encoder encodeObject:_osString forKey:SUAppcastAttributeOsType]; } - if (self.propertiesDictionary != nil) { - [encoder encodeObject:self.propertiesDictionary forKey:SUAppcastItemPropertiesKey]; + if (_propertiesDictionary != nil) { + [encoder encodeObject:_propertiesDictionary forKey:SUAppcastItemPropertiesKey]; } - if (self.installationType != nil) { - [encoder encodeObject:self.installationType forKey:SUAppcastItemInstallationTypeKey]; + if (_installationType != nil) { + [encoder encodeObject:_installationType forKey:SUAppcastItemInstallationTypeKey]; } - if (self.phasedRolloutInterval != nil) { - [encoder encodeObject:self.phasedRolloutInterval forKey:SUAppcastElementPhasedRolloutInterval]; + if (_phasedRolloutInterval != nil) { + [encoder encodeObject:_phasedRolloutInterval forKey:SUAppcastElementPhasedRolloutInterval]; } - if (self.channel != nil) { - [encoder encodeObject:self.channel forKey:SUAppcastElementChannel]; + if (_channel != nil) { + [encoder encodeObject:_channel forKey:SUAppcastElementChannel]; } } - (BOOL)isDeltaUpdate { - NSDictionary *rssElementEnclosure = [self.propertiesDictionary objectForKey:SURSSElementEnclosure]; + NSDictionary *rssElementEnclosure = [_propertiesDictionary objectForKey:SURSSElementEnclosure]; return [rssElementEnclosure objectForKey:SUAppcastAttributeDeltaFrom] != nil; } - (BOOL)isCriticalUpdate { - if (self.state != nil) { - return self.state.criticalUpdate; + if (_state != nil) { + return _state.criticalUpdate; } else { - return self.hasCriticalInformation; + return _hasCriticalInformation; } } - (BOOL)isMajorUpgrade { - if (self.state != nil) { - return self.state.majorUpgrade; + if (_state != nil) { + return _state.majorUpgrade; } else { return NO; } @@ -273,8 +271,8 @@ static NSString *SUAppcastItemDeltaFromSparkleLocalesKey = @"SUAppcastItemDeltaF - (BOOL)minimumOperatingSystemVersionIsOK { - if (self.state != nil) { - return self.state.minimumOperatingSystemVersionIsOK; + if (_state != nil) { + return _state.minimumOperatingSystemVersionIsOK; } else { return YES; } @@ -282,8 +280,8 @@ static NSString *SUAppcastItemDeltaFromSparkleLocalesKey = @"SUAppcastItemDeltaF - (BOOL)maximumOperatingSystemVersionIsOK { - if (self.state != nil) { - return self.state.maximumOperatingSystemVersionIsOK; + if (_state != nil) { + return _state.maximumOperatingSystemVersionIsOK; } else { return YES; } @@ -291,12 +289,12 @@ static NSString *SUAppcastItemDeltaFromSparkleLocalesKey = @"SUAppcastItemDeltaF - (BOOL)isMacOsUpdate { - return self.osString == nil || [self.osString isEqualToString:SUAppcastAttributeValueMacOS]; + return _osString == nil || [_osString isEqualToString:SUAppcastAttributeValueMacOS]; } - (NSDate *)date { - NSString *dateString = self.dateString; + NSString *dateString = _dateString; if (dateString == nil) { return nil; } @@ -310,10 +308,10 @@ static NSString *SUAppcastItemDeltaFromSparkleLocalesKey = @"SUAppcastItemDeltaF - (BOOL)isInformationOnlyUpdate { - if (self.state != nil) { - return self.state.informationalUpdate; + if (_state != nil) { + return _state.informationalUpdate; } else { - return (self.informationalUpdateVersions != nil && self.informationalUpdateVersions.count == 0); + return (_informationalUpdateVersions != nil && _informationalUpdateVersions.count == 0); } } @@ -328,7 +326,7 @@ static NSString *SUAppcastItemDeltaFromSparkleLocalesKey = @"SUAppcastItemDeltaF } // Initializer used for making delta items -- (nullable instancetype)initWithDictionary:(NSDictionary *)dict relativeToURL:(NSURL * _Nullable)appcastURL state:(SPUAppcastItemState * _Nullable)state +- (nullable instancetype)initWithDictionary:(NSDictionary *)dict relativeToURL:(NSURL * _Nullable)appcastURL state:(SPUAppcastItemState * _Nullable)state SPU_OBJC_DIRECT { return [self initWithDictionary:dict relativeToURL:nil stateResolver:nil resolvedState:state failureReason:nil]; } @@ -477,7 +475,11 @@ static NSString *SUAppcastItemDeltaFromSparkleLocalesKey = @"SUAppcastItemDeltaF } } if (enclosure) { - _signatures = [[SUSignatures alloc] initWithDsa:[enclosure objectForKey:SUAppcastAttributeDSASignature] ed:[enclosure objectForKey:SUAppcastAttributeEDSignature]]; + _signatures = [[SUSignatures alloc] initWithEd:[enclosure objectForKey:SUAppcastAttributeEDSignature] +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT + dsa:[enclosure objectForKey:SUAppcastAttributeDSASignature] +#endif + ]; _osString = [enclosure objectForKey:SUAppcastAttributeOsType]; } @@ -546,15 +548,17 @@ static NSString *SUAppcastItemDeltaFromSparkleLocalesKey = @"SUAppcastItemDeltaF _displayVersionString = [_versionString copy]; } - NSString *attributeInstallationType = [enclosure objectForKey:SUAppcastAttributeInstallationType]; NSString *chosenInstallationType; +#if SPARKLE_BUILD_PACKAGE_SUPPORT + NSString *attributeInstallationType = [enclosure objectForKey:SUAppcastAttributeInstallationType]; if (attributeInstallationType == nil) { // If we have a flat package, assume installation type is guided // (flat / non-archived interactive packages are not supported) // Otherwise assume we have a normal application inside an archive if ([_fileURL.pathExtension isEqualToString:@"pkg"] || [_fileURL.pathExtension isEqualToString:@"mpkg"]) { chosenInstallationType = SPUInstallationTypeGuidedPackage; - } else { + } else + { chosenInstallationType = SPUInstallationTypeApplication; } } else if (!SPUValidInstallationType(attributeInstallationType)) { @@ -569,6 +573,9 @@ static NSString *SUAppcastItemDeltaFromSparkleLocalesKey = @"SUAppcastItemDeltaF } else { chosenInstallationType = attributeInstallationType; } +#else + chosenInstallationType = SPUInstallationTypeApplication; +#endif _installationType = [chosenInstallationType copy]; @@ -618,8 +625,8 @@ static NSString *SUAppcastItemDeltaFromSparkleLocalesKey = @"SUAppcastItemDeltaF SULog(SULogLevelError, @"Release notes must have a http or https URL scheme."); _releaseNotesURL = nil; } - } else if ([self.itemDescription hasPrefix:@"http://"] || [self.itemDescription hasPrefix:@"https://"]) { // if the description starts with http:// or https:// use that. - _releaseNotesURL = [NSURL URLWithString:(NSString * _Nonnull)self.itemDescription]; + } else if ([_itemDescription hasPrefix:@"http://"] || [_itemDescription hasPrefix:@"https://"]) { // if the description starts with http:// or https:// use that. + _releaseNotesURL = [NSURL URLWithString:(NSString * _Nonnull)_itemDescription]; } else { _releaseNotesURL = nil; } diff --git a/Sparkle/SUApplicationInfo.h b/Sparkle/SUApplicationInfo.h index ee98978a..f2456296 100644 --- a/Sparkle/SUApplicationInfo.h +++ b/Sparkle/SUApplicationInfo.h @@ -14,7 +14,7 @@ NS_ASSUME_NONNULL_BEGIN @class SUHost, NSImage, NSApplication; -@interface SUApplicationInfo : NSObject +SPU_OBJC_DIRECT_MEMBERS @interface SUApplicationInfo : NSObject + (BOOL)isBackgroundApplication:(NSApplication *)application; diff --git a/Sparkle/SUApplicationInfo.m b/Sparkle/SUApplicationInfo.m index 4d9c11b0..c8183955 100644 --- a/Sparkle/SUApplicationInfo.m +++ b/Sparkle/SUApplicationInfo.m @@ -38,16 +38,20 @@ // but still better than nothing if no icon was included BOOL isMainBundle = [host.bundle isEqualTo:[NSBundle mainBundle]]; - if (@available(macOS 11, *)) { +#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_VERSION_11_0 + if (@available(macOS 11, *)) +#endif + { UTType *contentType = isMainBundle ? UTTypeApplication : UTTypeBundle; icon = [[NSWorkspace sharedWorkspace] iconForContentType:contentType]; - } else { -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdeprecated-declarations" + } +#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_VERSION_11_0 + else + { NSString *fileType = isMainBundle ? (__bridge NSString *)kUTTypeApplication : (__bridge NSString *)kUTTypeBundle; icon = [[NSWorkspace sharedWorkspace] iconForFileType:fileType]; -#pragma clang diagnostic pop } +#endif } return icon; } diff --git a/Sparkle/SUBundleIcon.h b/Sparkle/SUBundleIcon.h index 3e709b5d..91ca005e 100644 --- a/Sparkle/SUBundleIcon.h +++ b/Sparkle/SUBundleIcon.h @@ -12,7 +12,7 @@ NS_ASSUME_NONNULL_BEGIN @class SUHost; -@interface SUBundleIcon : NSObject +SPU_OBJC_DIRECT_MEMBERS @interface SUBundleIcon : NSObject + (NSURL * _Nullable)iconURLForHost:(SUHost *)host; diff --git a/Sparkle/SUConstants.h b/Sparkle/SUConstants.h index 8b2226ef..62ae463e 100644 --- a/Sparkle/SUConstants.h +++ b/Sparkle/SUConstants.h @@ -45,10 +45,11 @@ extern NSString *const SUSkippedMajorVersionKey; extern NSString *const SUSkippedMajorSubreleaseVersionKey; extern NSString *const SUScheduledCheckIntervalKey; extern NSString *const SULastCheckTimeKey; +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT extern NSString *const SUExpectsDSASignatureKey; -extern NSString *const SUExpectsEDSignatureKey; extern NSString *const SUPublicDSAKeyKey; extern NSString *const SUPublicDSAKeyFileKey; +#endif extern NSString *const SUPublicEDKeyKey; extern NSString *const SUAutomaticallyUpdateKey; extern NSString *const SUAllowsAutomaticUpdatesKey; diff --git a/Sparkle/SUConstants.m b/Sparkle/SUConstants.m index e313cf42..5b98bd35 100644 --- a/Sparkle/SUConstants.m +++ b/Sparkle/SUConstants.m @@ -41,10 +41,11 @@ NSString *const SUSkippedMajorVersionKey = @"SUSkippedMajorVersion"; NSString *const SUSkippedMajorSubreleaseVersionKey = @"SUSkippedMajorSubreleaseVersion"; NSString *const SUScheduledCheckIntervalKey = @"SUScheduledCheckInterval"; NSString *const SULastCheckTimeKey = @"SULastCheckTime"; +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT NSString *const SUExpectsDSASignatureKey = @"SUExpectsDSASignature"; -NSString *const SUExpectsEDSignatureKey = @"SUExpectsEDSignatureKey"; NSString *const SUPublicDSAKeyKey = @"SUPublicDSAKey"; NSString *const SUPublicDSAKeyFileKey = @"SUPublicDSAKeyFile"; +#endif NSString *const SUPublicEDKeyKey = @"SUPublicEDKey"; NSString *const SUAutomaticallyUpdateKey = @"SUAutomaticallyUpdate"; NSString *const SUAllowsAutomaticUpdatesKey = @"SUAllowsAutomaticUpdates"; @@ -74,7 +75,9 @@ NSString *const SURelaunchToolNameKey = @"SURelaunchToolName"; NSString *const SUAppcastAttributeDeltaFrom = @"sparkle:deltaFrom"; NSString *const SUAppcastAttributeDeltaFromSparkleExecutableSize = @"sparkle:deltaFromSparkleExecutableSize"; NSString *const SUAppcastAttributeDeltaFromSparkleLocales = @"sparkle:deltaFromSparkleLocales"; +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT NSString *const SUAppcastAttributeDSASignature = @"sparkle:dsaSignature"; +#endif NSString *const SUAppcastAttributeEDSignature = @"sparkle:edSignature"; NSString *const SUAppcastAttributeShortVersionString = @"sparkle:shortVersionString"; NSString *const SUAppcastAttributeVersion = @"sparkle:version"; diff --git a/Sparkle/SUErrors.h b/Sparkle/SUErrors.h index 22bf6066..cf2e47d5 100644 --- a/Sparkle/SUErrors.h +++ b/Sparkle/SUErrors.h @@ -11,7 +11,7 @@ #import <Foundation/Foundation.h> -#if defined(BUILDING_SPARKLE_TOOL) || defined(BUILDING_SPARKLE_TESTS) +#if defined(BUILDING_SPARKLE_SOURCES_EXTERNALLY) // Ignore incorrect warning #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wquoted-include-in-framework-header" diff --git a/Sparkle/SUFileManager.h b/Sparkle/SUFileManager.h index a0c18cc9..7b59c67e 100644 --- a/Sparkle/SUFileManager.h +++ b/Sparkle/SUFileManager.h @@ -16,15 +16,11 @@ NS_ASSUME_NONNULL_BEGIN * All operations on this class may be used on thread other than the main thread. * This class provides just basic file operations and stays away from including much application-level logic. */ +#ifndef BUILDING_SPARKLE_TESTS +SPU_OBJC_DIRECT_MEMBERS +#endif @interface SUFileManager : NSObject -/** - * Initializes a new file manager - * - * @return A new file manager instance - */ -- (instancetype)init; - /** * Creates a temporary directory on the same volume as a provided URL * @param appropriateURL A URL to a directory that resides on the volume that the temporary directory will be created on. In the uncommon case, the temporary directory may be created inside this directory. diff --git a/Sparkle/SUFileManager.m b/Sparkle/SUFileManager.m index 6ba1a63e..57c032f8 100644 --- a/Sparkle/SUFileManager.m +++ b/Sparkle/SUFileManager.m @@ -21,10 +21,6 @@ extern int renamex_np(const char *, const char *, unsigned int) __attribute__((w static char SUAppleQuarantineIdentifier[] = "com.apple.quarantine"; -#pragma clang diagnostic push -// Use direct access because it's easier, clearer, and faster -#pragma clang diagnostic ignored "-Wdirect-ivar-access" - @implementation SUFileManager { NSFileManager *_fileManager; @@ -42,6 +38,9 @@ static char SUAppleQuarantineIdentifier[] = "com.apple.quarantine"; // -[NSFileManager attributesOfItemAtPath:error:] won't follow symbolic links - (BOOL)_itemExistsAtURL:(NSURL *)fileURL +#ifndef BUILDING_SPARKLE_TESTS +SPU_OBJC_DIRECT +#endif { NSString *path = fileURL.path; if (path == nil) { @@ -51,6 +50,9 @@ static char SUAppleQuarantineIdentifier[] = "com.apple.quarantine"; } - (BOOL)_itemExistsAtURL:(NSURL *)fileURL isDirectory:(BOOL *)isDirectory +#ifndef BUILDING_SPARKLE_TESTS +SPU_OBJC_DIRECT +#endif { NSString *path = fileURL.path; if (path == nil) { @@ -70,7 +72,7 @@ static char SUAppleQuarantineIdentifier[] = "com.apple.quarantine"; } // Wrapper around getxattr() -- (ssize_t)_getXAttr:(const char *)name fromFile:(NSString *)file options:(int)options +- (ssize_t)_getXAttr:(const char *)name fromFile:(NSString *)file options:(int)options SPU_OBJC_DIRECT { char path[PATH_MAX] = {0}; if (![file getFileSystemRepresentation:path maxLength:sizeof(path)]) { @@ -82,7 +84,7 @@ static char SUAppleQuarantineIdentifier[] = "com.apple.quarantine"; } // Wrapper around removexattr() -- (int)_removeXAttr:(const char *)attr fromFile:(NSString *)file options:(int)options +- (int)_removeXAttr:(const char *)attr fromFile:(NSString *)file options:(int)options SPU_OBJC_DIRECT { char path[PATH_MAX] = {0}; if (![file getFileSystemRepresentation:path maxLength:sizeof(path)]) { @@ -166,7 +168,7 @@ static char SUAppleQuarantineIdentifier[] = "com.apple.quarantine"; return [_fileManager copyItemAtURL:sourceURL toURL:destinationURL error:error]; } -- (BOOL)_getVolumeID:(out id _Nullable __autoreleasing * _Nonnull)outVolumeIdentifier ofItemAtURL:(NSURL *)url +- (BOOL)_getVolumeID:(out id _Nullable __autoreleasing * _Nonnull)outVolumeIdentifier ofItemAtURL:(NSURL *)url SPU_OBJC_DIRECT { NSError *error = nil; return [url getResourceValue:outVolumeIdentifier forKey:NSURLVolumeIdentifierKey error:&error]; @@ -369,7 +371,7 @@ static char SUAppleQuarantineIdentifier[] = "com.apple.quarantine"; return YES; } -- (BOOL)_updateItemAtURL:(NSURL *)targetURL withAccessTime:(struct timeval)accessTime error:(NSError * __autoreleasing *)error +- (BOOL)_updateItemAtURL:(NSURL *)targetURL withAccessTime:(struct timeval)accessTime error:(NSError * __autoreleasing *)error SPU_OBJC_DIRECT { char path[PATH_MAX] = {0}; @@ -570,5 +572,3 @@ static char SUAppleQuarantineIdentifier[] = "com.apple.quarantine"; } @end - -#pragma clang diagnostic pop diff --git a/Sparkle/SUHost.h b/Sparkle/SUHost.h index 2e95b4ce..3f5c5944 100644 --- a/Sparkle/SUHost.h +++ b/Sparkle/SUHost.h @@ -11,24 +11,29 @@ NS_ASSUME_NONNULL_BEGIN @class SUPublicKeys; +#ifndef BUILDING_SPARKLE_TESTS +SPU_OBJC_DIRECT_MEMBERS +#endif @interface SUHost : NSObject -@property (strong, readonly) NSBundle *bundle; +@property (nonatomic, readonly) NSBundle *bundle; - (instancetype)initWithBundle:(NSBundle *)aBundle; - (instancetype)init NS_UNAVAILABLE; -@property (readonly, copy) NSString *bundlePath; -@property (readonly, copy) NSString *name; -@property (readonly, copy) NSString *version; +@property (readonly, nonatomic, copy) NSString *bundlePath; +@property (readonly, nonatomic, copy) NSString *name; +@property (readonly, nonatomic, copy) NSString *version; @property (readonly, nonatomic) BOOL validVersion; -@property (readonly, copy) NSString *displayVersion; -@property (readonly) SUPublicKeys *publicKeys; +@property (readonly, nonatomic, copy) NSString *displayVersion; +@property (readonly, nonatomic) SUPublicKeys *publicKeys; -@property (getter=isRunningOnReadOnlyVolume, readonly) BOOL runningOnReadOnlyVolume; -@property (getter=isRunningTranslocated, readonly) BOOL runningTranslocated; +@property (getter=isRunningOnReadOnlyVolume, nonatomic, readonly) BOOL runningOnReadOnlyVolume; +@property (getter=isRunningTranslocated, nonatomic, readonly) BOOL runningTranslocated; +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT @property (readonly, nonatomic, copy, nullable) NSString *publicDSAKeyFileKey; +#endif - (nullable id)objectForInfoDictionaryKey:(NSString *)key; - (BOOL)boolForInfoDictionaryKey:(NSString *)key; diff --git a/Sparkle/SUHost.m b/Sparkle/SUHost.m index 518039bf..a6bc4266 100644 --- a/Sparkle/SUHost.m +++ b/Sparkle/SUHost.m @@ -23,43 +23,36 @@ NS_ASSUME_NONNULL_BEGIN // if the process is sandboxed or not; eg: finding the user's caches directory. Or code that depends // on compilation flags and if other files exist relative to the host bundle. -@interface SUHost () - -@property (strong, readwrite) NSBundle *bundle; -@property (nonatomic, readonly) BOOL isMainBundle; -@property (copy, nullable) NSString *defaultsDomain; -@property (assign) BOOL usesStandardUserDefaults; -@property (readonly, copy, nullable) NSString *publicDSAKey; - -@end - @implementation SUHost +{ + NSString *_defaultsDomain; + + BOOL _usesStandardUserDefaults; + BOOL _isMainBundle; +} -@synthesize bundle; -@synthesize isMainBundle = _isMainBundle; -@synthesize defaultsDomain; -@synthesize usesStandardUserDefaults; +@synthesize bundle = _bundle; - (instancetype)initWithBundle:(NSBundle *)aBundle { if ((self = [super init])) { NSParameterAssert(aBundle); - self.bundle = aBundle; - if (![self.bundle bundleIdentifier]) { - SULog(SULogLevelError, @"Error: the bundle being updated at %@ has no %@! This will cause preference read/write to not work properly.", self.bundle, kCFBundleIdentifierKey); + _bundle = aBundle; + if (_bundle.bundleIdentifier == nil) { + SULog(SULogLevelError, @"Error: the bundle being updated at %@ has no %@! This will cause preference read/write to not work properly.", _bundle, kCFBundleIdentifierKey); } _isMainBundle = [aBundle isEqualTo:[NSBundle mainBundle]]; - self.defaultsDomain = [self objectForInfoDictionaryKey:SUDefaultsDomainKey]; - if (!self.defaultsDomain) { - self.defaultsDomain = [self.bundle bundleIdentifier]; + _defaultsDomain = [self objectForInfoDictionaryKey:SUDefaultsDomainKey]; + if (_defaultsDomain == nil) { + _defaultsDomain = [_bundle bundleIdentifier]; } // If we're using the main bundle's defaults we'll use the standard user defaults mechanism, otherwise we have to get CF-y. NSString *mainBundleIdentifier = NSBundle.mainBundle.bundleIdentifier; - usesStandardUserDefaults = !self.defaultsDomain || [self.defaultsDomain isEqualToString:mainBundleIdentifier]; + _usesStandardUserDefaults = _defaultsDomain == nil || [_defaultsDomain isEqualToString:mainBundleIdentifier]; } return self; } @@ -68,7 +61,7 @@ NS_ASSUME_NONNULL_BEGIN - (NSString *)bundlePath { - return [self.bundle bundlePath]; + return _bundle.bundlePath; } - (NSString * _Nonnull)name @@ -93,12 +86,12 @@ NS_ASSUME_NONNULL_BEGIN return [self isValidVersion:[self _version]]; } -- (BOOL)isValidVersion:(NSString * _Nullable)version +- (BOOL)isValidVersion:(NSString * _Nullable)version SPU_OBJC_DIRECT { return (version != nil && version.length != 0); } -- (NSString * _Nullable)_version +- (NSString * _Nullable)_version SPU_OBJC_DIRECT { NSString *version = [self objectForInfoDictionaryKey:(__bridge NSString *)kCFBundleVersionKey]; return ([self isValidVersion:version] ? version : nil); @@ -127,22 +120,23 @@ NS_ASSUME_NONNULL_BEGIN - (BOOL)isRunningOnReadOnlyVolume { struct statfs statfs_info; - statfs([[self.bundle bundlePath] fileSystemRepresentation], &statfs_info); + statfs(_bundle.bundlePath.fileSystemRepresentation, &statfs_info); return (statfs_info.f_flags & MNT_RDONLY) != 0; } - (BOOL)isRunningTranslocated { - NSString *path = [self.bundle bundlePath]; + NSString *path = _bundle.bundlePath; return [path rangeOfString:@"/AppTranslocation/"].location != NSNotFound; } -- (NSString *_Nullable)publicEDKey +- (NSString *_Nullable)publicEDKey SPU_OBJC_DIRECT { return [self objectForInfoDictionaryKey:SUPublicEDKeyKey]; } -- (NSString *_Nullable)publicDSAKey +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT +- (NSString *_Nullable)publicDSAKey SPU_OBJC_DIRECT { // Maybe the key is just a string in the Info.plist. NSString *key = [self objectForInfoDictionaryKey:SUPublicDSAKeyKey]; @@ -156,7 +150,7 @@ NS_ASSUME_NONNULL_BEGIN return nil; } - NSString *keyPath = [self.bundle pathForResource:keyFilename ofType:nil]; + NSString *keyPath = [_bundle pathForResource:keyFilename ofType:nil]; if (!keyPath) { return nil; } @@ -167,30 +161,37 @@ NS_ASSUME_NONNULL_BEGIN } return key; } +#endif - (SUPublicKeys *)publicKeys { - return [[SUPublicKeys alloc] initWithDsa:[self publicDSAKey] ed:[self publicEDKey]]; + return [[SUPublicKeys alloc] initWithEd:[self publicEDKey] +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT + dsa:[self publicDSAKey] +#endif + ]; } +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT - (NSString * _Nullable)publicDSAKeyFileKey { return [self objectForInfoDictionaryKey:SUPublicDSAKeyFileKey]; } +#endif - (nullable id)objectForInfoDictionaryKey:(NSString *)key { - if (self.isMainBundle) { + if (_isMainBundle) { // Common fast path - if we're updating the main bundle, that means our updater and host bundle's lifetime is the same // If the bundle happens to be updated or change, that means our updater process needs to be terminated first to do it safely // Thus we can rely on the cached Info dictionary - return [self.bundle objectForInfoDictionaryKey:key]; + return [_bundle objectForInfoDictionaryKey:key]; } else { // Slow path - if we're updating another bundle, we should read in the most up to date Info dictionary because // the bundle can be replaced externally or even by us. // This is the easiest way to read the Info dictionary values *correctly* despite some performance loss. // A mutable method to reload the Info dictionary at certain points and have it cached at other points is challenging to do correctly. - CFDictionaryRef cfInfoDictionary = CFBundleCopyInfoDictionaryInDirectory((CFURLRef)self.bundle.bundleURL); + CFDictionaryRef cfInfoDictionary = CFBundleCopyInfoDictionaryInDirectory((CFURLRef)_bundle.bundleURL); NSDictionary *infoDictionary = CFBridgingRelease(cfInfoDictionary); return [infoDictionary objectForKey:key]; @@ -204,43 +205,43 @@ NS_ASSUME_NONNULL_BEGIN - (nullable id)objectForUserDefaultsKey:(NSString *)defaultName { - if (!defaultName || !self.defaultsDomain) { + if (!defaultName || _defaultsDomain == nil) { return nil; } // Under Tiger, CFPreferencesCopyAppValue doesn't get values from NSRegistrationDomain, so anything // passed into -[NSUserDefaults registerDefaults:] is ignored. The following line falls // back to using NSUserDefaults, but only if the host bundle is the main bundle. - if (self.usesStandardUserDefaults) { + if (_usesStandardUserDefaults) { return [[NSUserDefaults standardUserDefaults] objectForKey:defaultName]; } - CFPropertyListRef obj = CFPreferencesCopyAppValue((__bridge CFStringRef)defaultName, (__bridge CFStringRef)self.defaultsDomain); + CFPropertyListRef obj = CFPreferencesCopyAppValue((__bridge CFStringRef)defaultName, (__bridge CFStringRef)_defaultsDomain); return CFBridgingRelease(obj); } // Note this handles nil being passed for defaultName, in which case the user default will be removed - (void)setObject:(nullable id)value forUserDefaultsKey:(NSString *)defaultName { - if (self.usesStandardUserDefaults) + if (_usesStandardUserDefaults) { [[NSUserDefaults standardUserDefaults] setObject:value forKey:defaultName]; } else { - CFPreferencesSetValue((__bridge CFStringRef)defaultName, (__bridge CFPropertyListRef)(value), (__bridge CFStringRef)self.defaultsDomain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost); - CFPreferencesSynchronize((__bridge CFStringRef)self.defaultsDomain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost); + CFPreferencesSetValue((__bridge CFStringRef)defaultName, (__bridge CFPropertyListRef)(value), (__bridge CFStringRef)_defaultsDomain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost); + CFPreferencesSynchronize((__bridge CFStringRef)_defaultsDomain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost); } } - (BOOL)boolForUserDefaultsKey:(NSString *)defaultName { - if (self.usesStandardUserDefaults) { + if (_usesStandardUserDefaults) { return [[NSUserDefaults standardUserDefaults] boolForKey:defaultName]; } BOOL value; - CFPropertyListRef plr = CFPreferencesCopyAppValue((__bridge CFStringRef)defaultName, (__bridge CFStringRef)self.defaultsDomain); + CFPropertyListRef plr = CFPreferencesCopyAppValue((__bridge CFStringRef)defaultName, (__bridge CFStringRef)_defaultsDomain); if (plr == NULL) { value = NO; } @@ -254,14 +255,14 @@ NS_ASSUME_NONNULL_BEGIN - (void)setBool:(BOOL)value forUserDefaultsKey:(NSString *)defaultName { - if (self.usesStandardUserDefaults) + if (_usesStandardUserDefaults) { [[NSUserDefaults standardUserDefaults] setBool:value forKey:defaultName]; } else { - CFPreferencesSetValue((__bridge CFStringRef)defaultName, (__bridge CFBooleanRef) @(value), (__bridge CFStringRef)self.defaultsDomain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost); - CFPreferencesSynchronize((__bridge CFStringRef)self.defaultsDomain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost); + CFPreferencesSetValue((__bridge CFStringRef)defaultName, (__bridge CFBooleanRef) @(value), (__bridge CFStringRef)_defaultsDomain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost); + CFPreferencesSynchronize((__bridge CFStringRef)_defaultsDomain, kCFPreferencesCurrentUser, kCFPreferencesAnyHost); } } diff --git a/Sparkle/SULegacyWebView.h b/Sparkle/SULegacyWebView.h index 2d0d2205..eb4825ea 100644 --- a/Sparkle/SULegacyWebView.h +++ b/Sparkle/SULegacyWebView.h @@ -6,14 +6,14 @@ // Copyright © 2020 Sparkle Project. All rights reserved. // -#if SPARKLE_BUILD_UI_BITS +#if SPARKLE_BUILD_UI_BITS && DOWNLOADER_XPC_SERVICE_EMBEDDED #import <Foundation/Foundation.h> #import "SUWebView.h" NS_ASSUME_NONNULL_BEGIN -@interface SULegacyWebView : NSObject <SUWebView> +SPU_OBJC_DIRECT_MEMBERS @interface SULegacyWebView : NSObject <SUWebView> - (instancetype)initWithColorStyleSheetLocation:(NSURL *)colorStyleSheetLocation fontFamily:(NSString *)fontFamily fontPointSize:(int)fontPointSize javaScriptEnabled:(BOOL)javaScriptEnabled; diff --git a/Sparkle/SULegacyWebView.m b/Sparkle/SULegacyWebView.m index 45c1b55e..2622fc77 100644 --- a/Sparkle/SULegacyWebView.m +++ b/Sparkle/SULegacyWebView.m @@ -6,7 +6,7 @@ // Copyright © 2020 Sparkle Project. All rights reserved. // -#if SPARKLE_BUILD_UI_BITS +#if SPARKLE_BUILD_UI_BITS && DOWNLOADER_XPC_SERVICE_EMBEDDED #import "SULegacyWebView.h" #import "SUWebViewCommon.h" @@ -17,16 +17,14 @@ #pragma clang diagnostic ignored "-Wdeprecated-declarations" @interface SULegacyWebView () <WebPolicyDelegate, WebFrameLoadDelegate, WebUIDelegate> - -@property (nonatomic, readonly) WebView *webView; -@property (nonatomic) void (^completionHandler)(NSError * _Nullable); - @end @implementation SULegacyWebView - -@synthesize webView = _webView; -@synthesize completionHandler = _completionHandler; +{ + WebView *_webView; + + void (^_completionHandler)(NSError * _Nullable); +} - (instancetype)initWithColorStyleSheetLocation:(NSURL *)colorStyleSheetLocation fontFamily:(NSString *)fontFamily fontPointSize:(int)fontPointSize javaScriptEnabled:(BOOL)javaScriptEnabled { @@ -61,38 +59,38 @@ - (NSView *)view { - return self.webView; + return _webView; } - (void)loadHTMLString:(NSString *)htmlString baseURL:(NSURL * _Nullable)baseURL completionHandler:(void (^)(NSError * _Nullable))completionHandler { - self.completionHandler = [completionHandler copy]; - [[self.webView mainFrame] loadHTMLString:htmlString baseURL:baseURL]; + _completionHandler = [completionHandler copy]; + [[_webView mainFrame] loadHTMLString:htmlString baseURL:baseURL]; } - (void)loadData:(NSData *)data MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)textEncodingName baseURL:(NSURL *)baseURL completionHandler:(void (^)(NSError * _Nullable))completionHandler { - self.completionHandler = [completionHandler copy]; - [[self.webView mainFrame] loadData:data MIMEType:MIMEType textEncodingName:textEncodingName baseURL:baseURL]; + _completionHandler = [completionHandler copy]; + [[_webView mainFrame] loadData:data MIMEType:MIMEType textEncodingName:textEncodingName baseURL:baseURL]; } - (void)stopLoading { - self.completionHandler = nil; - [self.webView stopLoading:self]; + _completionHandler = nil; + [_webView stopLoading:self]; } - (void)setDrawsBackground:(BOOL)drawsBackground { - self.webView.drawsBackground = drawsBackground; + _webView.drawsBackground = drawsBackground; } - (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame { if ([frame parentFrame] == nil) { - if (self.completionHandler != nil) { - self.completionHandler(nil); - self.completionHandler = nil; + if (_completionHandler != nil) { + _completionHandler(nil); + _completionHandler = nil; } [sender display]; // necessary to prevent weird scroll bar artifacting } @@ -101,9 +99,9 @@ - (void)webView:(WebView *)sender didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame { if ([frame parentFrame] == nil) { - if (self.completionHandler != nil) { - self.completionHandler(error); - self.completionHandler = nil; + if (_completionHandler != nil) { + _completionHandler(error); + _completionHandler = nil; } } } @@ -122,7 +120,7 @@ } // Ensure we are finished loading - if (self.completionHandler == nil) { + if (_completionHandler == nil) { if (requestURL && !isAboutBlank) { [[NSWorkspace sharedWorkspace] openURL:requestURL]; } diff --git a/Sparkle/SULocalizations.h b/Sparkle/SULocalizations.h index a291f257..2656bfbb 100644 --- a/Sparkle/SULocalizations.h +++ b/Sparkle/SULocalizations.h @@ -9,10 +9,17 @@ #ifndef SULocalizations_h #define SULocalizations_h -#import "SUConstants.h" +#if SPARKLE_COPY_LOCALIZATIONS + #import "SUConstants.h" -#define SULocalizedStringFromTableInBundle(key, tbl, bundle, comment) NSLocalizedStringFromTableInBundle(key, tbl, bundle, comment) + // This should only be used from inside the framework (not helper tools) + #define SUSparkleBundle() ((NSBundle * _Nonnull)([NSBundle bundleWithIdentifier:SUBundleIdentifier])) -#define SULocalizedString(key, comment) SULocalizedStringFromTableInBundle(key, @"Sparkle", (NSBundle * _Nonnull)([NSBundle bundleWithIdentifier:SUBundleIdentifier] ? [NSBundle bundleWithIdentifier:SUBundleIdentifier] : [NSBundle mainBundle]), comment) + #define SPARKLE_TABLE @"Sparkle" + + #define SULocalizedStringFromTableInBundle(key, tbl, bundle, comment) NSLocalizedStringFromTableInBundle(key, tbl, bundle, comment) +#else + #define SULocalizedStringFromTableInBundle(key, tbl, bundle, comment) key +#endif #endif /* SULocalizations_h */ diff --git a/Sparkle/SUOperatingSystem.h b/Sparkle/SUOperatingSystem.h index c42bb25f..8564528e 100644 --- a/Sparkle/SUOperatingSystem.h +++ b/Sparkle/SUOperatingSystem.h @@ -7,7 +7,7 @@ #import <Foundation/Foundation.h> -@interface SUOperatingSystem : NSObject +SPU_OBJC_DIRECT_MEMBERS @interface SUOperatingSystem : NSObject + (NSString *)systemVersionString; diff --git a/Sparkle/SUPhasedUpdateGroupInfo.h b/Sparkle/SUPhasedUpdateGroupInfo.h index 6f54c7a3..b0a7e2bd 100644 --- a/Sparkle/SUPhasedUpdateGroupInfo.h +++ b/Sparkle/SUPhasedUpdateGroupInfo.h @@ -12,6 +12,9 @@ NS_ASSUME_NONNULL_BEGIN @class SUHost; +#ifndef BUILDING_SPARKLE_TESTS +SPU_OBJC_DIRECT_MEMBERS +#endif @interface SUPhasedUpdateGroupInfo : NSObject + (NSUInteger)updateGroupForHost:(SUHost*)host; diff --git a/Sparkle/SUPhasedUpdateGroupInfo.m b/Sparkle/SUPhasedUpdateGroupInfo.m index 48e84892..fdafd4ed 100644 --- a/Sparkle/SUPhasedUpdateGroupInfo.m +++ b/Sparkle/SUPhasedUpdateGroupInfo.m @@ -16,12 +16,14 @@ @implementation SUPhasedUpdateGroupInfo #define NUM_UPDATE_GROUPS 7 -+ (NSUInteger)updateGroupForHost:(SUHost*)host { ++ (NSUInteger)updateGroupForHost:(SUHost*)host +{ NSNumber* updateGroupIdentifier = [self updateGroupIdentifierForHost:host]; return ([updateGroupIdentifier unsignedIntValue] % NUM_UPDATE_GROUPS); } -+ (NSNumber*)updateGroupIdentifierForHost:(SUHost*)host { ++ (NSNumber*)updateGroupIdentifierForHost:(SUHost*)host SPU_OBJC_DIRECT +{ NSNumber* updateGroupIdentifier = [host objectForUserDefaultsKey:SUUpdateGroupIdentifierKey]; if(updateGroupIdentifier == nil) { updateGroupIdentifier = [self setNewUpdateGroupIdentifierForHost:host]; @@ -30,7 +32,8 @@ return updateGroupIdentifier; } -+ (NSNumber*)setNewUpdateGroupIdentifierForHost:(SUHost*)host { ++ (NSNumber*)setNewUpdateGroupIdentifierForHost:(SUHost*)host +{ unsigned int r = arc4random_uniform(UINT_MAX); NSNumber* updateGroupIdentifier = @(r); diff --git a/Sparkle/SUSignatures.h b/Sparkle/SUSignatures.h index 9a98dc7e..fe48afe6 100644 --- a/Sparkle/SUSignatures.h +++ b/Sparkle/SUSignatures.h @@ -22,32 +22,47 @@ typedef NS_ENUM(uint8_t, SUSigningInputStatus) { SUSigningInputStatusLastValidCase = SUSigningInputStatusPresent }; -@interface SUSignatures : NSObject <NSSecureCoding> { - unsigned char ed25519_signature[64]; -} -@property (strong, readonly, nullable) NSData *dsaSignature; -@property (readonly) SUSigningInputStatus dsaSignatureStatus; +#ifndef BUILDING_SPARKLE_TESTS +SPU_OBJC_DIRECT_MEMBERS +#endif +@interface SUSignatures : NSObject <NSSecureCoding> +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT +@property (nonatomic, readonly, nullable) NSData *dsaSignature; +@property (nonatomic, readonly) SUSigningInputStatus dsaSignatureStatus; +#endif -@property (readonly, nullable, nonatomic) const unsigned char *ed25519Signature; -@property (readonly) SUSigningInputStatus ed25519SignatureStatus; +@property (nonatomic, readonly, nullable) const unsigned char *ed25519Signature; +@property (nonatomic, readonly) SUSigningInputStatus ed25519SignatureStatus; -- (instancetype)initWithDsa:(NSString * _Nullable)dsa ed:(NSString * _Nullable)ed; +- (instancetype)initWithEd:(NSString * _Nullable)ed +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT + dsa:(NSString * _Nullable)dsa +#endif +; @end -@interface SUPublicKeys : NSObject { - unsigned char ed25519_public_key[32]; -} -@property (strong, readonly, nullable) NSString *dsaPubKey; -@property (readonly) SUSigningInputStatus dsaPubKeyStatus; +#ifndef BUILDING_SPARKLE_TESTS +SPU_OBJC_DIRECT_MEMBERS +#endif +@interface SUPublicKeys : NSObject -@property (readonly, nullable, nonatomic) const unsigned char *ed25519PubKey; -@property (readonly) SUSigningInputStatus ed25519PubKeyStatus; +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT +@property (nonatomic, readonly, nullable) NSString *dsaPubKey; +@property (nonatomic, readonly) SUSigningInputStatus dsaPubKeyStatus; +#endif + +@property (nonatomic, readonly, nullable) const unsigned char *ed25519PubKey; +@property (nonatomic, readonly) SUSigningInputStatus ed25519PubKeyStatus; /// Returns YES if either key is present (though they may be invalid). -@property (readonly) BOOL hasAnyKeys; +@property (nonatomic, readonly) BOOL hasAnyKeys; -- (instancetype)initWithDsa:(NSString * _Nullable)dsa ed:(NSString * _Nullable)ed; +- (instancetype)initWithEd:(NSString * _Nullable)ed +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT + dsa:(NSString * _Nullable)dsa +#endif +; @end diff --git a/Sparkle/SUSignatures.m b/Sparkle/SUSignatures.m index 123a673d..b871b79b 100644 --- a/Sparkle/SUSignatures.m +++ b/Sparkle/SUSignatures.m @@ -13,14 +13,22 @@ #include "AppKitPrevention.h" +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT static NSString *SUDSASignatureKey = @"SUDSASignature"; static NSString *SUDSASignatureStatusKey = @"SUDSASignatureStatus"; +#endif static NSString *SUEDSignatureKey = @"SUEDSignature"; static NSString *SUEDSignatureStatusKey = @"SUEDSignatureStatus"; @implementation SUSignatures +{ + unsigned char _ed25519_signature[64]; +} + +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT @synthesize dsaSignature = _dsaSignature; @synthesize dsaSignatureStatus = _dsaSignatureStatus; +#endif @synthesize ed25519SignatureStatus = _ed25519SignatureStatus; static SUSigningInputStatus decode(NSString *str, NSData * __strong *outData) { @@ -37,22 +45,26 @@ static SUSigningInputStatus decode(NSString *str, NSData * __strong *outData) { return SUSigningInputStatusPresent; } -- (instancetype)initWithDsa:(NSString * _Nullable)maybeDsa ed:(NSString * _Nullable)maybeEd25519 +- (instancetype)initWithEd:(NSString * _Nullable)maybeEd25519 +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT + dsa:(NSString * _Nullable)maybeDsa +#endif { self = [super init]; if (self) { +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT _dsaSignatureStatus = decode(maybeDsa, &_dsaSignature); if (_dsaSignatureStatus == SUSigningInputStatusInvalid) { SULog(SULogLevelError, @"The provided DSA signature could not be decoded."); } - +#endif if (maybeEd25519 != nil) { NSData *data = nil; _ed25519SignatureStatus = decode(maybeEd25519, &data); if (data) { - assert(64 == sizeof(self->ed25519_signature)); - if ([data length] == sizeof(self->ed25519_signature)) { - [data getBytes:self->ed25519_signature length:sizeof(self->ed25519_signature)]; + assert(64 == sizeof(_ed25519_signature)); + if ([data length] == sizeof(_ed25519_signature)) { + [data getBytes:_ed25519_signature length:sizeof(_ed25519_signature)]; } else { _ed25519SignatureStatus = SUSigningInputStatusInvalid; } @@ -67,14 +79,10 @@ static SUSigningInputStatus decode(NSString *str, NSData * __strong *outData) { } - (const unsigned char *)ed25519Signature { -// Xcode may enable this in pedantic mode -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdirect-ivar-access" - if (self.ed25519SignatureStatus == SUSigningInputStatusPresent) { - return self->ed25519_signature; + if (_ed25519SignatureStatus == SUSigningInputStatusPresent) { + return _ed25519_signature; } return NULL; -#pragma clang diagnostic pop } static BOOL decodeStatus(NSCoder *decoder, NSString *key, SUSigningInputStatus *outStatus) { @@ -90,6 +98,7 @@ static BOOL decodeStatus(NSCoder *decoder, NSString *key, SUSigningInputStatus * { self = [super init]; if (self) { +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT if (!decodeStatus(decoder, SUDSASignatureStatusKey, &_dsaSignatureStatus)) { return nil; } @@ -98,6 +107,7 @@ static BOOL decodeStatus(NSCoder *decoder, NSString *key, SUSigningInputStatus * if (dsaSignature) { _dsaSignature = dsaSignature; } +#endif if (!decodeStatus(decoder, SUEDSignatureStatusKey, &_ed25519SignatureStatus)) { return nil; @@ -105,10 +115,10 @@ static BOOL decodeStatus(NSCoder *decoder, NSString *key, SUSigningInputStatus * NSData *edSignature = [decoder decodeObjectOfClass:[NSData class] forKey:SUEDSignatureKey]; if (edSignature) { - if (edSignature.length != sizeof(self->ed25519_signature)) { + if (edSignature.length != sizeof(_ed25519_signature)) { return nil; } - [edSignature getBytes:self->ed25519_signature length:sizeof(self->ed25519_signature)]; + [edSignature getBytes:_ed25519_signature length:sizeof(_ed25519_signature)]; } } return self; @@ -116,17 +126,15 @@ static BOOL decodeStatus(NSCoder *decoder, NSString *key, SUSigningInputStatus * - (void)encodeWithCoder:(NSCoder *)coder { - [coder encodeInteger:self.dsaSignatureStatus forKey:SUDSASignatureStatusKey]; - if (self.dsaSignature) { - [coder encodeObject:self.dsaSignature forKey:SUDSASignatureKey]; +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT + [coder encodeInteger:_dsaSignatureStatus forKey:SUDSASignatureStatusKey]; + if (_dsaSignature) { + [coder encodeObject:_dsaSignature forKey:SUDSASignatureKey]; } - [coder encodeInteger:self.ed25519SignatureStatus forKey:SUEDSignatureStatusKey]; - if (self.ed25519Signature) { -// Xcode may enable this in pedantic mode -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdirect-ivar-access" - NSData *edSignature = [NSData dataWithBytesNoCopy:&self->ed25519_signature length:sizeof(self->ed25519_signature) freeWhenDone:false]; -#pragma clang diagnostic pop +#endif + [coder encodeInteger:_ed25519SignatureStatus forKey:SUEDSignatureStatusKey]; + if ([self ed25519Signature] != NULL) { + NSData *edSignature = [NSData dataWithBytesNoCopy:&_ed25519_signature length:sizeof(_ed25519_signature) freeWhenDone:false]; [coder encodeObject:edSignature forKey:SUEDSignatureKey]; } } @@ -138,21 +146,32 @@ static BOOL decodeStatus(NSCoder *decoder, NSString *key, SUSigningInputStatus * @end @implementation SUPublicKeys +{ + unsigned char _ed25519_public_key[32]; +} + +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT @synthesize dsaPubKey = _dsaPubKey; +#endif @synthesize ed25519PubKeyStatus = _ed25519PubKeyStatus; -- (instancetype)initWithDsa:(NSString * _Nullable)maybeDsa ed:(NSString * _Nullable)maybeEd25519 +- (instancetype)initWithEd:(NSString * _Nullable)maybeEd25519 +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT + dsa:(NSString * _Nullable)maybeDsa +#endif { self = [super init]; if (self) { +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT _dsaPubKey = maybeDsa; +#endif if (maybeEd25519 != nil) { NSData *ed = nil; _ed25519PubKeyStatus = decode(maybeEd25519, &ed); if (ed) { - assert(32 == sizeof(self->ed25519_public_key)); - if ([ed length] == sizeof(self->ed25519_public_key)) { - [ed getBytes:self->ed25519_public_key length:sizeof(self->ed25519_public_key)]; + assert(32 == sizeof(_ed25519_public_key)); + if ([ed length] == sizeof(_ed25519_public_key)) { + [ed getBytes:_ed25519_public_key length:sizeof(_ed25519_public_key)]; } else { _ed25519PubKeyStatus = SUSigningInputStatusInvalid; } @@ -166,25 +185,28 @@ static BOOL decodeStatus(NSCoder *decoder, NSString *key, SUSigningInputStatus * return self; } +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT - (SUSigningInputStatus)dsaPubKeyStatus { // We don't currently do any prevalidation of DSA public keys, // so this is always going to be "present" or "absent". - return self.dsaPubKey ? SUSigningInputStatusPresent : SUSigningInputStatusAbsent; + return (_dsaPubKey != nil) ? SUSigningInputStatusPresent : SUSigningInputStatusAbsent; } +#endif - (const unsigned char *)ed25519PubKey { -// Xcode may enable this in pedantic mode -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdirect-ivar-access" - if (self.ed25519PubKeyStatus == SUSigningInputStatusPresent) { - return self->ed25519_public_key; + if (_ed25519PubKeyStatus == SUSigningInputStatusPresent) { + return _ed25519_public_key; } return NULL; -#pragma clang diagnostic pop } - (BOOL)hasAnyKeys { - return self.dsaPubKeyStatus != SUSigningInputStatusAbsent || self.ed25519PubKeyStatus != SUSigningInputStatusAbsent; + return + _ed25519PubKeyStatus != SUSigningInputStatusAbsent +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT + || [self dsaPubKeyStatus] != SUSigningInputStatusAbsent +#endif + ; } @end diff --git a/Sparkle/SUStandardVersionComparator.h b/Sparkle/SUStandardVersionComparator.h index b9cfae6f..1316819a 100644 --- a/Sparkle/SUStandardVersionComparator.h +++ b/Sparkle/SUStandardVersionComparator.h @@ -11,7 +11,7 @@ #import <Foundation/Foundation.h> -#ifdef BUILDING_SPARKLE_TOOL +#if defined(BUILDING_SPARKLE_SOURCES_EXTERNALLY) // Ignore incorrect warning #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wquoted-include-in-framework-header" diff --git a/Sparkle/SUStandardVersionComparator.m b/Sparkle/SUStandardVersionComparator.m index dd69f549..29b56eb1 100644 --- a/Sparkle/SUStandardVersionComparator.m +++ b/Sparkle/SUStandardVersionComparator.m @@ -38,7 +38,7 @@ typedef NS_ENUM(NSInteger, SUCharacterType) { kDashType, }; -- (SUCharacterType)typeOfCharacter:(NSString *)character +- (SUCharacterType)typeOfCharacter:(NSString *)character SPU_OBJC_DIRECT { if ([character isEqualToString:@"."]) { return kPeriodSeparatorType; @@ -55,7 +55,7 @@ typedef NS_ENUM(NSInteger, SUCharacterType) { } } -- (BOOL)isSeparatorType:(SUCharacterType)characterType +- (BOOL)isSeparatorType:(SUCharacterType)characterType SPU_OBJC_DIRECT { switch (characterType) { case kNumberType: @@ -70,7 +70,7 @@ typedef NS_ENUM(NSInteger, SUCharacterType) { } // If type A and type B are some sort of separator, consider them to be equal -- (BOOL)isEqualCharacterTypeClassForTypeA:(SUCharacterType)typeA typeB:(SUCharacterType)typeB +- (BOOL)isEqualCharacterTypeClassForTypeA:(SUCharacterType)typeA typeB:(SUCharacterType)typeB SPU_OBJC_DIRECT { switch (typeA) { case kNumberType: @@ -94,7 +94,7 @@ typedef NS_ENUM(NSInteger, SUCharacterType) { } } -- (NSMutableArray<NSString *> *)splitVersionString:(NSString *)version +- (NSMutableArray<NSString *> *)splitVersionString:(NSString *)version SPU_OBJC_DIRECT { NSString *character; NSMutableString *s; @@ -133,7 +133,7 @@ typedef NS_ENUM(NSInteger, SUCharacterType) { // This returns the count of number and period parts at the beginning of the version // See -balanceVersionPartsA:partsB below -- (NSUInteger)countOfNumberAndPeriodStartingParts:(NSArray<NSString *> *)parts +- (NSUInteger)countOfNumberAndPeriodStartingParts:(NSArray<NSString *> *)parts SPU_OBJC_DIRECT { NSUInteger count = 0; for (NSString *part in parts) { @@ -149,7 +149,7 @@ typedef NS_ENUM(NSInteger, SUCharacterType) { } // See -balanceVersionPartsA:partsB below -- (void)addNumberAndPeriodPartsToParts:(NSMutableArray<NSString *> *)toParts toNumberAndPeriodPartsCount:(NSUInteger)toNumberAndPeriodPartsCount fromParts:(NSArray<NSString *> *)fromParts fromNumberAndPeriodPartsCount:(NSUInteger)fromNumberAndPeriodPartsCount +- (void)addNumberAndPeriodPartsToParts:(NSMutableArray<NSString *> *)toParts toNumberAndPeriodPartsCount:(NSUInteger)toNumberAndPeriodPartsCount fromParts:(NSArray<NSString *> *)fromParts fromNumberAndPeriodPartsCount:(NSUInteger)fromNumberAndPeriodPartsCount SPU_OBJC_DIRECT { NSUInteger partsCountDifference = (fromNumberAndPeriodPartsCount - toNumberAndPeriodPartsCount); @@ -168,7 +168,7 @@ typedef NS_ENUM(NSInteger, SUCharacterType) { // If one version starts with "1.0.0" and the other starts with "1.1" we make sure they're balanced // such that the latter version now becomes "1.1.0". This helps ensure that versions like "1.0" and "1.0.0" are equal. -- (void)balanceVersionPartsA:(NSMutableArray<NSString *> *)partsA partsB:(NSMutableArray<NSString *> *)partsB +- (void)balanceVersionPartsA:(NSMutableArray<NSString *> *)partsA partsB:(NSMutableArray<NSString *> *)partsB SPU_OBJC_DIRECT { NSUInteger partANumberAndPeriodPartsCount = [self countOfNumberAndPeriodStartingParts:partsA]; NSUInteger partBNumberAndPeriodPartsCount = [self countOfNumberAndPeriodStartingParts:partsB];; diff --git a/Sparkle/SUStatus.xib b/Sparkle/SUStatus.xib index ebd4c973..8f1efb73 100644 --- a/Sparkle/SUStatus.xib +++ b/Sparkle/SUStatus.xib @@ -8,9 +8,9 @@ <objects> <customObject id="-2" userLabel="File's Owner" customClass="SUStatusController"> <connections> - <outlet property="actionButton" destination="12" id="34"/> - <outlet property="progressBar" destination="11" id="49"/> - <outlet property="statusTextField" destination="16" id="MiZ-Tn-yVg"/> + <outlet property="_actionButton" destination="12" id="0jE-Zn-L18"/> + <outlet property="_progressBar" destination="11" id="Cwm-99-fCT"/> + <outlet property="_statusTextField" destination="16" id="oOr-uc-6cX"/> <outlet property="window" destination="5" id="25"/> </connections> </customObject> diff --git a/Sparkle/SUStatusController.h b/Sparkle/SUStatusController.h index e5597c19..f5ff48d4 100644 --- a/Sparkle/SUStatusController.h +++ b/Sparkle/SUStatusController.h @@ -15,23 +15,22 @@ @class SUHost; @interface SUStatusController : NSWindowController -@property (weak) IBOutlet NSButton *actionButton; -@property (weak) IBOutlet NSProgressIndicator *progressBar; -@property (weak) IBOutlet NSTextField *statusTextField; -@property (copy) NSString *statusText; -@property double progressValue; +// These three properties are connected via bindings +@property (nonatomic, copy) NSString *statusText; +@property (nonatomic) double progressValue; @property (nonatomic) double maxProgressValue; -@property (getter=isButtonEnabled) BOOL buttonEnabled; -- (instancetype)initWithHost:(SUHost *)aHost windowTitle:(NSString *)windowTitle centerPointValue:(NSValue *)centerPointValue minimizable:(BOOL)minimizable closable:(BOOL)closable; +@property (nonatomic, getter=isButtonEnabled, direct) BOOL buttonEnabled; + +- (instancetype)initWithHost:(SUHost *)aHost windowTitle:(NSString *)windowTitle centerPointValue:(NSValue *)centerPointValue minimizable:(BOOL)minimizable closable:(BOOL)closable SPU_OBJC_DIRECT; // Pass 0 for the max progress value to get an indeterminate progress bar. // Pass nil for the status text to not show it. -- (void)beginActionWithTitle:(NSString *)title maxProgressValue:(double)maxProgressValue statusText:(NSString *)statusText; +- (void)beginActionWithTitle:(NSString *)title maxProgressValue:(double)maxProgressValue statusText:(NSString *)statusText SPU_OBJC_DIRECT; // If isDefault is YES, the button's key equivalent will be \r. -- (void)setButtonTitle:(NSString *)buttonTitle target:(id)target action:(SEL)action isDefault:(BOOL)isDefault; +- (void)setButtonTitle:(NSString *)buttonTitle target:(id)target action:(SEL)action isDefault:(BOOL)isDefault SPU_OBJC_DIRECT; @end diff --git a/Sparkle/SUStatusController.m b/Sparkle/SUStatusController.m index a1d1faf2..9921b2cb 100644 --- a/Sparkle/SUStatusController.m +++ b/Sparkle/SUStatusController.m @@ -12,43 +12,47 @@ #import "SUHost.h" #import "SUApplicationInfo.h" #import "SULocalizations.h" -#import "SUOperatingSystem.h" #import "SUTouchBarButtonGroup.h" static NSString *const SUStatusControllerTouchBarIndentifier = @"" SPARKLE_BUNDLE_IDENTIFIER ".SUStatusController"; @interface SUStatusController () <NSTouchBarDelegate> -@property (copy) NSString *title, *buttonTitle; -@property (strong) SUHost *host; -@property NSButton *touchBarButton; -@property (nonatomic, readonly) BOOL minimizable; + +// These properties are used for bindings +@property (nonatomic, copy) NSString *title; +@property (nonatomic, copy) NSString *buttonTitle; + @end @implementation SUStatusController { NSString *_windowTitle; NSValue *_centerPointValue; + NSString *_title; + NSString *_buttonTitle; + SUHost *_host; + NSButton *_touchBarButton; + + IBOutlet NSButton *_actionButton; + IBOutlet NSTextField *_statusTextField; + IBOutlet NSProgressIndicator *_progressBar; + + BOOL _minimizable; BOOL _closable; } -@synthesize progressValue; -@synthesize maxProgressValue; -@synthesize statusText; -@synthesize title; -@synthesize buttonTitle; -@synthesize host; -@synthesize actionButton; -@synthesize progressBar; -@synthesize statusTextField; -@synthesize touchBarButton; -@synthesize minimizable = _minimizable; +@synthesize title = _title; +@synthesize buttonTitle = _buttonTitle; +@synthesize progressValue = _progressValue; +@synthesize maxProgressValue = _maxProgressValue; +@synthesize statusText = _statusText; - (instancetype)initWithHost:(SUHost *)aHost windowTitle:(NSString *)windowTitle centerPointValue:(NSValue *)centerPointValue minimizable:(BOOL)minimizable closable:(BOOL)closable { self = [super initWithWindowNibName:@"SUStatus" owner:self]; if (self) { - self.host = aHost; + _host = aHost; _centerPointValue = centerPointValue; _minimizable = minimizable; _closable = closable; @@ -58,34 +62,38 @@ static NSString *const SUStatusControllerTouchBarIndentifier = @"" SPARKLE_BUNDL return self; } -- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], [self.host bundlePath]]; } - -- (void)windowDidLoad +- (NSString *)description { - NSRect windowFrame = self.window.frame; + return [NSString stringWithFormat:@"%@ <%@>", [self class], _host.bundlePath]; +} + +- (void)windowDidLoad +{ + NSWindow *window = self.window; + NSRect windowFrame = window.frame; if (_centerPointValue != nil) { NSPoint centerPoint = _centerPointValue.pointValue; - [self.window setFrameOrigin:NSMakePoint(centerPoint.x - windowFrame.size.width / 2.0, centerPoint.y - windowFrame.size.height / 2.0)]; + [window setFrameOrigin:NSMakePoint(centerPoint.x - windowFrame.size.width / 2.0, centerPoint.y - windowFrame.size.height / 2.0)]; } else { - [self.window center]; + [window center]; } - if (self.minimizable) { - self.window.styleMask |= NSWindowStyleMaskMiniaturizable; + if (_minimizable) { + window.styleMask |= NSWindowStyleMaskMiniaturizable; } if (_closable) { - self.window.styleMask |= NSWindowStyleMaskClosable; + window.styleMask |= NSWindowStyleMaskClosable; } - [self.progressBar setUsesThreadedAnimation:YES]; - [self.statusTextField setFont:[NSFont monospacedDigitSystemFontOfSize:0 weight:NSFontWeightRegular]]; + [_progressBar setUsesThreadedAnimation:YES]; + [_statusTextField setFont:[NSFont monospacedDigitSystemFontOfSize:0 weight:NSFontWeightRegular]]; - self.window.title = _windowTitle; + window.title = _windowTitle; } - (NSImage *)applicationIcon { - return [SUApplicationInfo bestIconForHost:self.host]; + return [SUApplicationInfo bestIconForHost:_host]; } - (void)beginActionWithTitle:(NSString *)aTitle maxProgressValue:(double)aMaxProgressValue statusText:(NSString *)aStatusText @@ -101,21 +109,25 @@ static NSString *const SUStatusControllerTouchBarIndentifier = @"" SPARKLE_BUNDL self.buttonTitle = aButtonTitle; [self window]; - [self.actionButton sizeToFit]; + [_actionButton sizeToFit]; // Except we're going to add 15 px for padding. - [self.actionButton setFrameSize:NSMakeSize([self.actionButton frame].size.width + 15, [self.actionButton frame].size.height)]; + [_actionButton setFrameSize:NSMakeSize(_actionButton.frame.size.width + 15, _actionButton.frame.size.height)]; // Now we have to move it over so that it's always 15px from the side of the window. - [self.actionButton setFrameOrigin:NSMakePoint([[self window] frame].size.width - 15 - [self.actionButton frame].size.width, [self.actionButton frame].origin.y)]; + [_actionButton setFrameOrigin:NSMakePoint([[self window] frame].size.width - 15 - _actionButton.frame.size.width, _actionButton.frame.origin.y)]; // Redisplay superview to clean up artifacts - [[self.actionButton superview] display]; + [[_actionButton superview] display]; - [self.actionButton setTarget:target]; - [self.actionButton setAction:action]; - [self.actionButton setKeyEquivalent:isDefault ? @"\r" : @""]; + [_actionButton setTarget:target]; + [_actionButton setAction:action]; + [_actionButton setKeyEquivalent:isDefault ? @"\r" : @""]; - self.touchBarButton.target = self.actionButton.target; - self.touchBarButton.action = self.actionButton.action; - self.touchBarButton.keyEquivalent = self.actionButton.keyEquivalent; + // False warning +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-repeated-use-of-weak" + _touchBarButton.target = _actionButton.target; +#pragma clang diagnostic pop + _touchBarButton.action = _actionButton.action; + _touchBarButton.keyEquivalent = _actionButton.keyEquivalent; // 06/05/2008 Alex: Avoid a crash when cancelling during the extraction [self setButtonEnabled:(target != nil)]; @@ -128,22 +140,22 @@ static NSString *const SUStatusControllerTouchBarIndentifier = @"" SPARKLE_BUNDL - (void)setButtonEnabled:(BOOL)enabled { - [self.actionButton setEnabled:enabled]; + [_actionButton setEnabled:enabled]; } - (BOOL)isButtonEnabled { - return [self.actionButton isEnabled]; + return [_actionButton isEnabled]; } - (void)setMaxProgressValue:(double)value { if (value < 0.0) value = 0.0; - maxProgressValue = value; + _maxProgressValue = value; [self setProgressValue:0.0]; - [self.progressBar setIndeterminate:(value == 0.0)]; - [self.progressBar startAnimation:self]; - [self.progressBar setUsesThreadedAnimation:YES]; + [_progressBar setIndeterminate:(value == 0.0)]; + [_progressBar startAnimation:self]; + [_progressBar setUsesThreadedAnimation:YES]; } @@ -160,11 +172,11 @@ static NSString *const SUStatusControllerTouchBarIndentifier = @"" SPARKLE_BUNDL { if ([identifier isEqualToString:SUStatusControllerTouchBarIndentifier]) { NSCustomTouchBarItem *item = [[NSCustomTouchBarItem alloc] initWithIdentifier:identifier]; - SUTouchBarButtonGroup *group = [[SUTouchBarButtonGroup alloc] initByReferencingButtons:@[self.actionButton,]]; + SUTouchBarButtonGroup *group = [[SUTouchBarButtonGroup alloc] initByReferencingButtons:@[_actionButton,]]; item.viewController = group; - self.touchBarButton = group.buttons.firstObject; - [self.touchBarButton bind:@"title" toObject:self.actionButton withKeyPath:@"title" options:nil]; - [self.touchBarButton bind:@"enabled" toObject:self.actionButton withKeyPath:@"enabled" options:nil]; + _touchBarButton = group.buttons.firstObject; + [_touchBarButton bind:@"title" toObject:_actionButton withKeyPath:@"title" options:nil]; + [_touchBarButton bind:@"enabled" toObject:_actionButton withKeyPath:@"enabled" options:nil]; return item; } return nil; diff --git a/Sparkle/SUSystemProfiler.h b/Sparkle/SUSystemProfiler.h index 4bf05472..6cc64781 100644 --- a/Sparkle/SUSystemProfiler.h +++ b/Sparkle/SUSystemProfiler.h @@ -14,7 +14,7 @@ NS_ASSUME_NONNULL_BEGIN @class SUHost; -@interface SUSystemProfiler : NSObject +SPU_OBJC_DIRECT_MEMBERS @interface SUSystemProfiler : NSObject + (NSArray<NSDictionary<NSString *, NSString *> *> *)systemProfileArrayForHost:(SUHost *)host; diff --git a/Sparkle/SUTouchBarButtonGroup.h b/Sparkle/SUTouchBarButtonGroup.h index d027a9b5..0c61603b 100644 --- a/Sparkle/SUTouchBarButtonGroup.h +++ b/Sparkle/SUTouchBarButtonGroup.h @@ -12,7 +12,7 @@ NS_ASSUME_NONNULL_BEGIN -@interface SUTouchBarButtonGroup : NSViewController +SPU_OBJC_DIRECT_MEMBERS @interface SUTouchBarButtonGroup : NSViewController @property (nonatomic, readonly, copy) NSArray<NSButton *> *buttons; diff --git a/Sparkle/SUUpdateAlert.h b/Sparkle/SUUpdateAlert.h index bb124a13..432540f3 100644 --- a/Sparkle/SUUpdateAlert.h +++ b/Sparkle/SUUpdateAlert.h @@ -18,19 +18,13 @@ @protocol SUUpdateAlertDelegate; @class SUAppcastItem, SPUDownloadData, SUHost; -@interface SUUpdateAlert : NSWindowController - -@property (nonatomic, weak, readonly) id <SUVersionDisplay> versionDisplayer; +SPU_OBJC_DIRECT_MEMBERS @interface SUUpdateAlert : NSWindowController - (instancetype)initWithAppcastItem:(SUAppcastItem *)item state:(SPUUserUpdateState *)state host:(SUHost *)aHost versionDisplayer:(id <SUVersionDisplay>)aVersionDisplayer completionBlock:(void (^)(SPUUserUpdateChoice, NSRect, BOOL))completionBlock didBecomeKeyBlock:(void (^)(void))didBecomeKeyBlock; - (void)showUpdateReleaseNotesWithDownloadData:(SPUDownloadData *)downloadData; - (void)showReleaseNotesFailedToDownload; -- (IBAction)installUpdate:sender; -- (IBAction)skipThisVersion:sender; -- (IBAction)remindMeLater:sender; - - (void)setInstallButtonFocus:(BOOL)focus; @end diff --git a/Sparkle/SUUpdateAlert.m b/Sparkle/SUUpdateAlert.m index 96d32158..92338043 100644 --- a/Sparkle/SUUpdateAlert.m +++ b/Sparkle/SUUpdateAlert.m @@ -33,71 +33,47 @@ static NSString *const SUUpdateAlertTouchBarIndentifier = @"" SPARKLE_BUNDLE_IDENTIFIER ".SUUpdateAlert"; @interface SUUpdateAlert () <NSTouchBarDelegate> - -@property (strong) SUAppcastItem *updateItem; -@property (strong) SUHost *host; -@property (nonatomic) BOOL allowsAutomaticUpdates; -@property (nonatomic, copy, nullable) void(^completionBlock)(SPUUserUpdateChoice, NSRect, BOOL); -@property (nonatomic) SPUUserUpdateState *state; - -@property (strong) NSProgressIndicator *releaseNotesSpinner; - -@property (weak) IBOutlet NSView *releaseNotesContainerView; -@property (weak) IBOutlet NSBox *releaseNotesBoxView; -@property (weak) IBOutlet NSTextField *descriptionField; -@property (weak) IBOutlet NSButton *automaticallyInstallUpdatesButton; -@property (weak) IBOutlet NSButton *installButton; -@property (weak) IBOutlet NSButton *skipButton; -@property (weak) IBOutlet NSButton *laterButton; - -@property (strong) NSBox *darkBackgroundView; -@property (assign) BOOL observingAppearance; - -@property (nonatomic) id<SUWebView> webView; - @end @implementation SUUpdateAlert { + SUAppcastItem *_updateItem; + SUHost *_host; + SPUUserUpdateState *_state; + NSProgressIndicator *_releaseNotesSpinner; + NSBox *_darkBackgroundView; + id<SUWebView> _webView; + + __weak id <SUVersionDisplay> _versionDisplayer; + + IBOutlet NSButton *_installButton; + IBOutlet NSButton *_laterButton; + IBOutlet NSButton *_skipButton; + IBOutlet NSBox *_releaseNotesBoxView; + IBOutlet NSTextField *_descriptionField; + IBOutlet NSView *_releaseNotesContainerView; + IBOutlet NSButton *_automaticallyInstallUpdatesButton; + void (^_didBecomeKeyBlock)(void); + void(^_completionBlock)(SPUUserUpdateChoice, NSRect, BOOL); + + BOOL _allowsAutomaticUpdates; + BOOL _observingAppearance; } -@synthesize completionBlock = _completionBlock; -@synthesize state = _state; -@synthesize versionDisplayer; - -@synthesize updateItem; -@synthesize host; -@synthesize allowsAutomaticUpdates = _allowsAutomaticUpdates; - -@synthesize releaseNotesSpinner; - -@synthesize releaseNotesContainerView; -@synthesize releaseNotesBoxView = _releaseNotesBoxView; -@synthesize descriptionField; -@synthesize automaticallyInstallUpdatesButton; -@synthesize installButton; -@synthesize skipButton; -@synthesize laterButton; - -@synthesize darkBackgroundView = _darkBackgroundView; -@synthesize observingAppearance; - -@synthesize webView = _webView; - - (instancetype)initWithAppcastItem:(SUAppcastItem *)item state:(SPUUserUpdateState *)state host:(SUHost *)aHost versionDisplayer:(id <SUVersionDisplay>)aVersionDisplayer completionBlock:(void (^)(SPUUserUpdateChoice, NSRect, BOOL))completionBlock didBecomeKeyBlock:(void (^)(void))didBecomeKeyBlock { self = [super initWithWindowNibName:@"SUUpdateAlert"]; if (self != nil) { - host = aHost; - updateItem = item; - versionDisplayer = aVersionDisplayer; + _host = aHost; + _updateItem = item; + _versionDisplayer = aVersionDisplayer; _state = state; _completionBlock = [completionBlock copy]; _didBecomeKeyBlock = [didBecomeKeyBlock copy]; - SPUUpdaterSettings *updaterSettings = [[SPUUpdaterSettings alloc] initWithHostBundle:host.bundle]; + SPUUpdaterSettings *updaterSettings = [[SPUUpdaterSettings alloc] initWithHostBundle:aHost.bundle]; BOOL allowsAutomaticUpdates; NSNumber *allowsAutomaticUpdatesOption = updaterSettings.allowsAutomaticUpdatesOption; @@ -117,30 +93,34 @@ static NSString *const SUUpdateAlertTouchBarIndentifier = @"" SPARKLE_BUNDLE_IDE return self; } -- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], [self.host bundlePath]]; } +- (NSString *)description +{ + return [NSString stringWithFormat:@"%@ <%@>", [self class], _host.bundlePath]; +} - (void)setInstallButtonFocus:(BOOL)focus { if (focus) { - self.installButton.keyEquivalent = @"\r"; + _installButton.keyEquivalent = @"\r"; } else { - self.installButton.keyEquivalent = @""; + _installButton.keyEquivalent = @""; } } -- (void)endWithSelection:(SPUUserUpdateChoice)choice +- (void)endWithSelection:(SPUUserUpdateChoice)choice SPU_OBJC_DIRECT { - [self.webView stopLoading]; - [self.webView.view removeFromSuperview]; // Otherwise it gets sent Esc presses (why?!) and gets very confused. + [_webView stopLoading]; + [_webView.view removeFromSuperview]; // Otherwise it gets sent Esc presses (why?!) and gets very confused. - BOOL wasKeyWindow = self.window.keyWindow; - NSRect windowFrame = self.window.frame; + NSWindow *window = self.window; + BOOL wasKeyWindow = window.keyWindow; + NSRect windowFrame = window.frame; [self close]; - if (self.completionBlock != nil) { - self.completionBlock(choice, windowFrame, wasKeyWindow); - self.completionBlock = nil; + if (_completionBlock != nil) { + _completionBlock(choice, windowFrame, wasKeyWindow); + _completionBlock = nil; } } @@ -151,7 +131,7 @@ static NSString *const SUUpdateAlertTouchBarIndentifier = @"" SPARKLE_BUNDLE_IDE - (IBAction)openInfoURL:(id)__unused sender { - NSURL *infoURL = self.updateItem.infoURL; + NSURL *infoURL = _updateItem.infoURL; assert(infoURL); [[NSWorkspace sharedWorkspace] openURL:infoURL]; @@ -169,32 +149,35 @@ static NSString *const SUUpdateAlertTouchBarIndentifier = @"" SPARKLE_BUNDLE_IDE [self endWithSelection:SPUUserUpdateChoiceDismiss]; } -- (void)displayReleaseNotes +- (void)displayReleaseNotes SPU_OBJC_DIRECT { [self adaptReleaseNotesAppearance]; - if (@available(macOS 10.14, *)) { - if (!self.observingAppearance) { - [self.webView.view addObserver:self forKeyPath:@"effectiveAppearance" options:0 context:nil]; - self.observingAppearance = YES; +#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_14 + if (@available(macOS 10.14, *)) +#endif + { + if (!_observingAppearance) { + [_webView.view addObserver:self forKeyPath:@"effectiveAppearance" options:0 context:nil]; + _observingAppearance = YES; } } // Stick a nice big spinner in the middle of the web view until the page is loaded. - NSRect frame = [[self.webView.view superview] frame]; - self.releaseNotesSpinner = [[NSProgressIndicator alloc] initWithFrame:NSMakeRect(NSMidX(frame) - 16, NSMidY(frame) - 16, 32, 32)]; - [self.releaseNotesSpinner setStyle:NSProgressIndicatorStyleSpinning]; - [self.releaseNotesSpinner startAnimation:self]; - [[self.webView.view superview] addSubview:self.releaseNotesSpinner]; + NSRect frame = [[_webView.view superview] frame]; + _releaseNotesSpinner = [[NSProgressIndicator alloc] initWithFrame:NSMakeRect(NSMidX(frame) - 16, NSMidY(frame) - 16, 32, 32)]; + [_releaseNotesSpinner setStyle:NSProgressIndicatorStyleSpinning]; + [_releaseNotesSpinner startAnimation:self]; + [[_webView.view superview] addSubview:_releaseNotesSpinner]; // If there's no release notes URL, just stick the contents of the description into the web view // Otherwise we'll wait until the client wants us to show release notes - if (self.updateItem.releaseNotesURL == nil) + if (_updateItem.releaseNotesURL == nil) { - NSString *itemDescription = self.updateItem.itemDescription; + NSString *itemDescription = _updateItem.itemDescription; if (itemDescription != nil) { __weak __typeof__(self) weakSelf = self; - [self.webView loadHTMLString:itemDescription baseURL:nil completionHandler:^(NSError * _Nullable error) { + [_webView loadHTMLString:itemDescription baseURL:nil completionHandler:^(NSError * _Nullable error) { if (error != nil) { SULog(SULogLevelError, @"Failed to load HTML string from web view: %@", error); } @@ -205,67 +188,75 @@ static NSString *const SUUpdateAlertTouchBarIndentifier = @"" SPARKLE_BUNDLE_IDE } - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(__attribute__((unused)) NSDictionary<NSKeyValueChangeKey,id> *)change context:(__attribute__((unused)) void *)context { - if (@available(macOS 10.14, *)) { - if (object == self.webView.view && [keyPath isEqualToString:@"effectiveAppearance"]) { +#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_14 + if (@available(macOS 10.14, *)) +#endif + { + if (object == _webView.view && [keyPath isEqualToString:@"effectiveAppearance"]) { [self adaptReleaseNotesAppearance]; } } } - (void)dealloc { - if (@available(macOS 10.14, *)) { - if (self.observingAppearance) { - [self.webView.view removeObserver:self forKeyPath:@"effectiveAppearance"]; - self.observingAppearance = NO; +#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_14 + if (@available(macOS 10.14, *)) +#endif + { + if (_observingAppearance) { + [_webView.view removeObserver:self forKeyPath:@"effectiveAppearance"]; + _observingAppearance = NO; } } } -- (void)adaptReleaseNotesAppearance +- (void)adaptReleaseNotesAppearance SPU_OBJC_DIRECT { +#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_14 if (@available(macOS 10.14, *)) +#endif { - NSAppearanceName bestAppearance = [self.webView.view.effectiveAppearance bestMatchFromAppearancesWithNames:@[NSAppearanceNameAqua, NSAppearanceNameDarkAqua]]; + NSAppearanceName bestAppearance = [_webView.view.effectiveAppearance bestMatchFromAppearancesWithNames:@[NSAppearanceNameAqua, NSAppearanceNameDarkAqua]]; if ([bestAppearance isEqualToString:NSAppearanceNameDarkAqua]) { // Remove web view background... - [self.webView setDrawsBackground:NO]; + [_webView setDrawsBackground:NO]; // ... and use NSBox to get the dynamically colored background - if (self.darkBackgroundView == nil) + if (_darkBackgroundView == nil) { - self.darkBackgroundView = [[NSBox alloc] initWithFrame:self.webView.view.frame]; - self.darkBackgroundView.boxType = NSBoxCustom; - self.darkBackgroundView.fillColor = [NSColor textBackgroundColor]; - self.darkBackgroundView.borderColor = [NSColor clearColor]; + _darkBackgroundView = [[NSBox alloc] initWithFrame:_webView.view.frame]; + _darkBackgroundView.boxType = NSBoxCustom; + _darkBackgroundView.fillColor = [NSColor textBackgroundColor]; + _darkBackgroundView.borderColor = [NSColor clearColor]; // Using auto-resizing mask instead of contraints works well enough - self.darkBackgroundView.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable; - [self.webView.view.superview addSubview:self.darkBackgroundView positioned:NSWindowBelow relativeTo:self.webView.view]; + _darkBackgroundView.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable; + [_webView.view.superview addSubview:_darkBackgroundView positioned:NSWindowBelow relativeTo:_webView.view]; // The release note user stylesheet will not adjust to the user changing the theme until adaptReleaseNoteAppearance is called again. // So lock the appearance of the background to keep the text readable if the system theme changes. - self.darkBackgroundView.appearance = self.darkBackgroundView.effectiveAppearance; + _darkBackgroundView.appearance = _darkBackgroundView.effectiveAppearance; } } else { // Restore standard dark on light appearance - [self.darkBackgroundView removeFromSuperview]; - self.darkBackgroundView = nil; - [self.webView setDrawsBackground:YES]; + [_darkBackgroundView removeFromSuperview]; + _darkBackgroundView = nil; + [_webView setDrawsBackground:YES]; } } } - (void)showUpdateReleaseNotesWithDownloadData:(SPUDownloadData *)downloadData { - NSURL *baseURL = self.updateItem.releaseNotesURL.URLByDeletingLastPathComponent; + NSURL *baseURL = _updateItem.releaseNotesURL.URLByDeletingLastPathComponent; // If a MIME type isn't provided, we will pick html as the default, as opposed to plain text. Questionable decision.. NSString *chosenMIMEType = (downloadData.MIMEType != nil) ? downloadData.MIMEType : @"text/html"; // We'll pick utf-8 as the default text encoding name if one isn't provided which I think is reasonable NSString *chosenTextEncodingName = (downloadData.textEncodingName != nil) ? downloadData.textEncodingName : @"utf-8"; __weak __typeof__(self) weakSelf = self; - [self.webView loadData:downloadData.data MIMEType:chosenMIMEType textEncodingName:chosenTextEncodingName baseURL:baseURL completionHandler:^(NSError * _Nullable error) { + [_webView loadData:downloadData.data MIMEType:chosenMIMEType textEncodingName:chosenTextEncodingName baseURL:baseURL completionHandler:^(NSError * _Nullable error) { if (error != nil) { SULog(SULogLevelError, @"Failed to load data from web view: %@", error); } @@ -278,21 +269,21 @@ static NSString *const SUUpdateAlertTouchBarIndentifier = @"" SPARKLE_BUNDLE_IDE [self stopReleaseNotesSpinner]; } -- (void)stopReleaseNotesSpinner +- (void)stopReleaseNotesSpinner SPU_OBJC_DIRECT { - [self.releaseNotesSpinner stopAnimation:self]; - [self.releaseNotesSpinner setHidden:YES]; + [_releaseNotesSpinner stopAnimation:self]; + [_releaseNotesSpinner setHidden:YES]; } - (BOOL)showsReleaseNotes { - NSNumber *shouldShowReleaseNotes = [self.host objectForInfoDictionaryKey:SUShowReleaseNotesKey]; + NSNumber *shouldShowReleaseNotes = [_host objectForInfoDictionaryKey:SUShowReleaseNotesKey]; if (shouldShowReleaseNotes == nil) { // Don't show release notes if RSS item contains no description and no release notes URL: - return (([self.updateItem itemDescription] != nil - && [[[self.updateItem itemDescription] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] > 0) - || [self.updateItem releaseNotesURL] != nil); + return (([_updateItem itemDescription] != nil + && [[[_updateItem itemDescription] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] > 0) + || [_updateItem releaseNotesURL] != nil); } else return [shouldShowReleaseNotes boolValue]; @@ -300,10 +291,12 @@ static NSString *const SUUpdateAlertTouchBarIndentifier = @"" SPARKLE_BUNDLE_IDE - (void)windowDidLoad { + NSWindow *window = self.window; + BOOL showReleaseNotes = [self showsReleaseNotes]; if (showReleaseNotes) { - self.window.frameAutosaveName = @"SUUpdateAlert"; + window.frameAutosaveName = @"SUUpdateAlert"; NSURL *colorStyleURL = [[NSBundle bundleForClass:[self class]] URLForResource:@"ReleaseNotesColorStyle" withExtension:@"css"]; @@ -311,37 +304,39 @@ static NSString *const SUUpdateAlertTouchBarIndentifier = @"" SPARKLE_BUNDLE_IDE NSString *defaultFontFamily = @"-apple-system-font"; int defaultFontSize = (int)[NSFont systemFontSize]; - BOOL javaScriptEnabled = [self.host boolForInfoDictionaryKey:SUEnableJavaScriptKey]; + BOOL javaScriptEnabled = [_host boolForInfoDictionaryKey:SUEnableJavaScriptKey]; +#if DOWNLOADER_XPC_SERVICE_EMBEDDED // WKWebView has a bug where it won't work in loading local HTML content in sandboxed apps that do not have an outgoing network entitlement // FB6993802: https://twitter.com/sindresorhus/status/1160577243929878528 | https://github.com/feedback-assistant/reports/issues/1 // If the developer is using the downloader XPC service, they are very most likely are a) sandboxed b) do not use outgoing network entitlement. // In this case, fall back to legacy WebKit view. // (In theory it is possible for a non-sandboxed app or sandboxed app with outgoing network entitlement to use the XPC service, it's just pretty unlikely. And falling back to a legacy web view would not be too harmful in those cases). - BOOL useWKWebView = !SPUXPCServiceIsEnabled(SUEnableDownloaderServiceKey); - if (useWKWebView) { - self.webView = [[SUWKWebView alloc] initWithColorStyleSheetLocation:colorStyleURL fontFamily:defaultFontFamily fontPointSize:defaultFontSize javaScriptEnabled:javaScriptEnabled]; - } else { - self.webView = [[SULegacyWebView alloc] initWithColorStyleSheetLocation:colorStyleURL fontFamily:defaultFontFamily fontPointSize:defaultFontSize javaScriptEnabled:javaScriptEnabled]; + if (SPUXPCServiceIsEnabled(SUEnableDownloaderServiceKey)) { + _webView = [[SULegacyWebView alloc] initWithColorStyleSheetLocation:colorStyleURL fontFamily:defaultFontFamily fontPointSize:defaultFontSize javaScriptEnabled:javaScriptEnabled]; + } else +#endif + { + _webView = [[SUWKWebView alloc] initWithColorStyleSheetLocation:colorStyleURL fontFamily:defaultFontFamily fontPointSize:defaultFontSize javaScriptEnabled:javaScriptEnabled]; } - NSView *boxContentView = self.releaseNotesBoxView.contentView; - [boxContentView addSubview:self.webView.view]; + NSView *boxContentView = _releaseNotesBoxView.contentView; + [boxContentView addSubview:_webView.view]; - self.webView.view.frame = boxContentView.bounds; - self.webView.view.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable; + _webView.view.frame = boxContentView.bounds; + _webView.view.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable; } else { // Update alert should not be resizable when no release notes are available - self.window.styleMask &= ~NSWindowStyleMaskResizable; + window.styleMask &= ~NSWindowStyleMaskResizable; } - if (self.updateItem.informationOnlyUpdate) { - [self.installButton setTitle:SULocalizedString(@"Learn More…", @"Alternate title for 'Install Update' button when there's no download in RSS feed.")]; - [self.installButton setAction:@selector(openInfoURL:)]; + if (_updateItem.informationOnlyUpdate) { + [_installButton setTitle:SULocalizedStringFromTableInBundle(@"Learn More…", SPARKLE_TABLE, SUSparkleBundle(), @"Alternate title for 'Install Update' button when there's no download in RSS feed.")]; + [_installButton setAction:@selector(openInfoURL:)]; } - BOOL allowsAutomaticUpdates = self.allowsAutomaticUpdates; + BOOL allowsAutomaticUpdates = _allowsAutomaticUpdates; if (showReleaseNotes) { [self displayReleaseNotes]; @@ -349,12 +344,12 @@ static NSString *const SUUpdateAlertTouchBarIndentifier = @"" SPARKLE_BUNDLE_IDE // When automatic updates aren't allowed we won't show the automatic install updates button // This button is removed later below if (allowsAutomaticUpdates) { - NSLayoutConstraint *automaticallyInstallUpdatesButtonToDescriptionFieldConstraint = [NSLayoutConstraint constraintWithItem:self.automaticallyInstallUpdatesButton attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.descriptionField attribute:NSLayoutAttributeBottom multiplier:1.0 constant:8.0]; + NSLayoutConstraint *automaticallyInstallUpdatesButtonToDescriptionFieldConstraint = [NSLayoutConstraint constraintWithItem:_automaticallyInstallUpdatesButton attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:_descriptionField attribute:NSLayoutAttributeBottom multiplier:1.0 constant:8.0]; - [self.window.contentView addConstraint:automaticallyInstallUpdatesButtonToDescriptionFieldConstraint]; + [window.contentView addConstraint:automaticallyInstallUpdatesButtonToDescriptionFieldConstraint]; } - [self.releaseNotesContainerView removeFromSuperview]; + [_releaseNotesContainerView removeFromSuperview]; } // NOTE: The code below for deciding what buttons to hide is complex! Due to array of feature configurations :) @@ -364,36 +359,40 @@ static NSString *const SUUpdateAlertTouchBarIndentifier = @"" SPARKLE_BUNDLE_IDE if (!allowsAutomaticUpdates) { if (showReleaseNotes) { // Fix constraints so that buttons aren't far away from web view when we hide the automatic updates check box - NSLayoutConstraint *skipButtonToReleaseNotesContainerConstraint = [NSLayoutConstraint constraintWithItem:self.skipButton attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.releaseNotesContainerView attribute:NSLayoutAttributeBottom multiplier:1.0 constant:12.0]; + NSLayoutConstraint *skipButtonToReleaseNotesContainerConstraint = [NSLayoutConstraint constraintWithItem:_skipButton attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:_releaseNotesContainerView attribute:NSLayoutAttributeBottom multiplier:1.0 constant:12.0]; - [self.window.contentView addConstraint:skipButtonToReleaseNotesContainerConstraint]; + [window.contentView addConstraint:skipButtonToReleaseNotesContainerConstraint]; } else { - NSLayoutConstraint *skipButtonToDescriptionConstraint = [NSLayoutConstraint constraintWithItem:self.skipButton attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.descriptionField attribute:NSLayoutAttributeBottom multiplier:1.0 constant:20.0]; + NSLayoutConstraint *skipButtonToDescriptionConstraint = [NSLayoutConstraint constraintWithItem:_skipButton attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:_descriptionField attribute:NSLayoutAttributeBottom multiplier:1.0 constant:20.0]; - [self.window.contentView addConstraint:skipButtonToDescriptionConstraint]; + [window.contentView addConstraint:skipButtonToDescriptionConstraint]; } - [self.automaticallyInstallUpdatesButton removeFromSuperview]; + [_automaticallyInstallUpdatesButton removeFromSuperview]; } - if (self.state.stage == SPUUserUpdateStageInstalling) { + if (_state.stage == SPUUserUpdateStageInstalling) { +#if SPARKLE_COPY_LOCALIZATIONS + NSBundle *sparkleBundle = SUSparkleBundle(); +#endif + // We're going to be relaunching pretty instantaneously - self.installButton.title = SULocalizedString(@"Install and Relaunch", nil); + _installButton.title = SULocalizedStringFromTableInBundle(@"Install and Relaunch", SPARKLE_TABLE, sparkleBundle, nil); // We should be explicit that the update will be installed on quit - self.laterButton.title = SULocalizedString(@"Install on Quit", @"Alternate title for 'Remind Me Later' button when downloaded updates can be resumed"); + _laterButton.title = SULocalizedStringFromTableInBundle(@"Install on Quit", SPARKLE_TABLE, sparkleBundle, @"Alternate title for 'Remind Me Later' button when downloaded updates can be resumed"); } - if (self.updateItem.criticalUpdate && !self.updateItem.majorUpgrade) { - self.skipButton.hidden = YES; - self.laterButton.hidden = YES; + if (_updateItem.criticalUpdate && !_updateItem.majorUpgrade) { + _skipButton.hidden = YES; + _laterButton.hidden = YES; } // Reminding user later doesn't make sense when automatic update checks are off - if (![self.host boolForKey:SUEnableAutomaticChecksKey]) { - self.laterButton.hidden = YES; + if (![_host boolForKey:SUEnableAutomaticChecksKey]) { + _laterButton.hidden = YES; } - [self.window center]; + [window center]; } - (void)windowDidBecomeKey:(NSNotification *)__unused note @@ -411,53 +410,62 @@ static NSString *const SUUpdateAlertTouchBarIndentifier = @"" SPARKLE_BUNDLE_IDE - (NSImage *)applicationIcon { - return [SUApplicationInfo bestIconForHost:self.host]; + return [SUApplicationInfo bestIconForHost:_host]; } - (NSString *)titleText { - if (self.updateItem.criticalUpdate) +#if SPARKLE_COPY_LOCALIZATIONS + NSBundle *sparkleBundle = SUSparkleBundle(); +#endif + + if (_updateItem.criticalUpdate) { - return [NSString stringWithFormat:SULocalizedString(@"An important update to %@ is ready to install", nil), [self.host name]]; + return [NSString stringWithFormat:SULocalizedStringFromTableInBundle(@"An important update to %@ is ready to install", SPARKLE_TABLE, sparkleBundle, nil), _host.name]; } - else if (self.state.stage == SPUUserUpdateStageDownloaded || self.state.stage == SPUUserUpdateStageInstalling) + else if (_state.stage == SPUUserUpdateStageDownloaded || _state.stage == SPUUserUpdateStageInstalling) { - return [NSString stringWithFormat:SULocalizedString(@"A new version of %@ is ready to install!", nil), [self.host name]]; + return [NSString stringWithFormat:SULocalizedStringFromTableInBundle(@"A new version of %@ is ready to install!", SPARKLE_TABLE, sparkleBundle, nil), _host.name]; } else { - return [NSString stringWithFormat:SULocalizedString(@"A new version of %@ is available!", nil), [self.host name]]; + return [NSString stringWithFormat:SULocalizedStringFromTableInBundle(@"A new version of %@ is available!", SPARKLE_TABLE, sparkleBundle, nil), _host.name]; } } - (NSString *)descriptionText { - NSString *updateItemVersion = [self.updateItem displayVersionString]; - NSString *hostVersion = [self.host displayVersion]; + NSString *updateItemVersion = [_updateItem displayVersionString]; + NSString *hostVersion = [_host displayVersion]; // Display more info if the version strings are the same; useful for betas. - if (!self.versionDisplayer && [updateItemVersion isEqualToString:hostVersion] ) { - updateItemVersion = [updateItemVersion stringByAppendingFormat:@" (%@)", [self.updateItem versionString]]; - hostVersion = [hostVersion stringByAppendingFormat:@" (%@)", self.host.version]; + id<SUVersionDisplay> versionDisplayer = _versionDisplayer; + if (versionDisplayer == nil && [updateItemVersion isEqualToString:hostVersion] ) { + updateItemVersion = [updateItemVersion stringByAppendingFormat:@" (%@)", [_updateItem versionString]]; + hostVersion = [hostVersion stringByAppendingFormat:@" (%@)", _host.version]; } else { - [self.versionDisplayer formatVersion:&updateItemVersion andVersion:&hostVersion]; + [versionDisplayer formatVersion:&updateItemVersion andVersion:&hostVersion]; } // We display a different summary depending on if it's an "info-only" item, or a "critical update" item, or if we've already downloaded the update and just need to relaunch NSString *finalString = nil; - if (self.updateItem.informationOnlyUpdate) { - finalString = [NSString stringWithFormat:SULocalizedString(@"%@ %@ is now available—you have %@. Would you like to learn more about this update on the web?", @"Description text for SUUpdateAlert when the update informational with no download."), self.host.name, updateItemVersion, hostVersion]; - } else if (self.updateItem.criticalUpdate) { - if (self.state.stage == SPUUserUpdateStageNotDownloaded) { - finalString = [NSString stringWithFormat:SULocalizedString(@"%@ %@ is now available—you have %@. This is an important update; would you like to download it now?", @"Description text for SUUpdateAlert when the critical update is downloadable."), self.host.name, updateItemVersion, hostVersion]; +#if SPARKLE_COPY_LOCALIZATIONS + NSBundle *sparkleBundle = SUSparkleBundle(); +#endif + + if (_updateItem.informationOnlyUpdate) { + finalString = [NSString stringWithFormat:SULocalizedStringFromTableInBundle(@"%@ %@ is now available—you have %@. Would you like to learn more about this update on the web?", SPARKLE_TABLE, sparkleBundle, @"Description text for SUUpdateAlert when the update informational with no download."), _host.name, updateItemVersion, hostVersion]; + } else if (_updateItem.criticalUpdate) { + if (_state.stage == SPUUserUpdateStageNotDownloaded) { + finalString = [NSString stringWithFormat:SULocalizedStringFromTableInBundle(@"%@ %@ is now available—you have %@. This is an important update; would you like to download it now?", SPARKLE_TABLE, sparkleBundle, @"Description text for SUUpdateAlert when the critical update is downloadable."), _host.name, updateItemVersion, hostVersion]; } else { - finalString = [NSString stringWithFormat:SULocalizedString(@"%1$@ %2$@ has been downloaded and is ready to use! This is an important update; would you like to install it and relaunch %1$@ now?", @"Description text for SUUpdateAlert when the critical update has already been downloaded and ready to install."), self.host.name, updateItemVersion]; + finalString = [NSString stringWithFormat:SULocalizedStringFromTableInBundle(@"%1$@ %2$@ has been downloaded and is ready to use! This is an important update; would you like to install it and relaunch %1$@ now?", SPARKLE_TABLE, sparkleBundle, @"Description text for SUUpdateAlert when the critical update has already been downloaded and ready to install."), _host.name, updateItemVersion]; } } else { - if (self.state.stage == SPUUserUpdateStageNotDownloaded) { - finalString = [NSString stringWithFormat:SULocalizedString(@"%@ %@ is now available—you have %@. Would you like to download it now?", @"Description text for SUUpdateAlert when the update is downloadable."), self.host.name, updateItemVersion, hostVersion]; + if (_state.stage == SPUUserUpdateStageNotDownloaded) { + finalString = [NSString stringWithFormat:SULocalizedStringFromTableInBundle(@"%@ %@ is now available—you have %@. Would you like to download it now?", SPARKLE_TABLE, sparkleBundle, @"Description text for SUUpdateAlert when the update is downloadable."), _host.name, updateItemVersion, hostVersion]; } else { - finalString = [NSString stringWithFormat:SULocalizedString(@"%1$@ %2$@ has been downloaded and is ready to use! Would you like to install it and relaunch %1$@ now?", @"Description text for SUUpdateAlert when the update has already been downloaded and ready to install."), self.host.name, updateItemVersion]; + finalString = [NSString stringWithFormat:SULocalizedStringFromTableInBundle(@"%1$@ %2$@ has been downloaded and is ready to use! Would you like to install it and relaunch %1$@ now?", SPARKLE_TABLE, sparkleBundle, @"Description text for SUUpdateAlert when the update has already been downloaded and ready to install."), _host.name, updateItemVersion]; } } return finalString; @@ -476,7 +484,7 @@ static NSString *const SUUpdateAlertTouchBarIndentifier = @"" SPARKLE_BUNDLE_IDE { if ([identifier isEqualToString:SUUpdateAlertTouchBarIndentifier]) { NSCustomTouchBarItem* item = [[NSCustomTouchBarItem alloc] initWithIdentifier:identifier]; - item.viewController = [[SUTouchBarButtonGroup alloc] initByReferencingButtons:@[self.installButton, self.laterButton, self.skipButton]]; + item.viewController = [[SUTouchBarButtonGroup alloc] initByReferencingButtons:@[_installButton, _laterButton, _skipButton]]; return item; } return nil; diff --git a/Sparkle/SUUpdatePermissionPrompt.h b/Sparkle/SUUpdatePermissionPrompt.h index afd7c9ef..b359ad9f 100644 --- a/Sparkle/SUUpdatePermissionPrompt.h +++ b/Sparkle/SUUpdatePermissionPrompt.h @@ -15,7 +15,7 @@ @class SUHost, SPUUpdatePermissionRequest, SUUpdatePermissionResponse; -@interface SUUpdatePermissionPrompt : NSWindowController +SPU_OBJC_DIRECT_MEMBERS @interface SUUpdatePermissionPrompt : NSWindowController - (instancetype)initPromptWithHost:(SUHost *)theHost request:(SPUUpdatePermissionRequest *)request reply:(void (^)(SUUpdatePermissionResponse *))reply; diff --git a/Sparkle/SUUpdatePermissionPrompt.m b/Sparkle/SUUpdatePermissionPrompt.m index 141f4c9d..d1ea3cd8 100644 --- a/Sparkle/SUUpdatePermissionPrompt.m +++ b/Sparkle/SUUpdatePermissionPrompt.m @@ -22,55 +22,42 @@ static NSString *const SUUpdatePermissionPromptTouchBarIndentifier = @"" SPARKLE @interface SUUpdatePermissionPrompt () <NSTouchBarDelegate> +// These properties are used for bindings +@property (nonatomic, readonly) NSArray *systemProfileInformationArray; @property (nonatomic) BOOL shouldSendProfile; @property (nonatomic) BOOL automaticallyDownloadUpdates; -@property (nonatomic) SUHost *host; -@property (nonatomic) NSArray *systemProfileInformationArray; - -@property (nonatomic) IBOutlet NSStackView *stackView; -@property (nonatomic) IBOutlet NSView *promptView; -@property (nonatomic) IBOutlet NSView *moreInfoView; -@property (nonatomic) IBOutlet NSView *placeholderView; -@property (nonatomic) IBOutlet NSView *responseView; -@property (nonatomic) IBOutlet NSView *infoChoiceView; -@property (nonatomic) IBOutlet NSView *automaticallyDownloadUpdatesView; - -@property (nonatomic) IBOutlet NSButton *cancelButton; -@property (nonatomic) IBOutlet NSButton *checkButton; -@property (nonatomic) IBOutlet NSButton *anonymousInfoDisclosureButton; - -@property (nonatomic) IBOutlet NSLayoutConstraint *placeholderHeightLayoutConstraint; - -@property (nonatomic, readonly) void (^reply)(SUUpdatePermissionResponse *); - @end @implementation SUUpdatePermissionPrompt +{ + SUHost *_host; + + IBOutlet NSStackView *_stackView; + IBOutlet NSView *_promptView; + IBOutlet NSView *_moreInfoView; + IBOutlet NSView *_placeholderView; + IBOutlet NSView *_responseView; + IBOutlet NSView *_infoChoiceView; + IBOutlet NSView *_automaticallyDownloadUpdatesView; + IBOutlet NSButton *_cancelButton; + IBOutlet NSButton *_checkButton; + IBOutlet NSButton *_anonymousInfoDisclosureButton; + IBOutlet NSLayoutConstraint *_placeholderHeightLayoutConstraint; + + void (^_reply)(SUUpdatePermissionResponse *); +} -@synthesize reply = _reply; @synthesize shouldSendProfile = _shouldSendProfile; @synthesize automaticallyDownloadUpdates = _automaticallyDownloadUpdates; -@synthesize host = _host; @synthesize systemProfileInformationArray = _systemProfileInformationArray; -@synthesize stackView = _stackView; -@synthesize promptView = _promtView; -@synthesize moreInfoView = _moreInfoView; -@synthesize placeholderView = _placeholderView; -@synthesize responseView = _responseView; -@synthesize infoChoiceView = _infoChoiceView; -@synthesize automaticallyDownloadUpdatesView = _automaticallyDownloadUpdatesView; -@synthesize cancelButton = _cancelButton; -@synthesize checkButton = _checkButton; -@synthesize anonymousInfoDisclosureButton = _anonymousInfoDisclosureButton; -@synthesize placeholderHeightLayoutConstraint = _placeholderHeightLayoutConstraint; - (instancetype)initPromptWithHost:(SUHost *)theHost request:(SPUUpdatePermissionRequest *)request reply:(void (^)(SUUpdatePermissionResponse *))reply { self = [super initWithWindowNibName:@"SUUpdatePermissionPrompt"]; if (self) { - _reply = reply; + _reply = [reply copy]; _host = theHost; _shouldSendProfile = [self shouldAskAboutProfile]; _systemProfileInformationArray = request.systemProfile; @@ -84,30 +71,30 @@ static NSString *const SUUpdatePermissionPromptTouchBarIndentifier = @"" SPARKLE - (BOOL)shouldAskAboutProfile { - return [(NSNumber *)[self.host objectForInfoDictionaryKey:SUEnableSystemProfilingKey] boolValue]; + return [(NSNumber *)[_host objectForInfoDictionaryKey:SUEnableSystemProfilingKey] boolValue]; } - (BOOL)allowsAutomaticUpdates { - NSNumber *allowsAutomaticUpdates = [self.host objectForInfoDictionaryKey:SUAllowsAutomaticUpdatesKey]; + NSNumber *allowsAutomaticUpdates = [_host objectForInfoDictionaryKey:SUAllowsAutomaticUpdatesKey]; return (allowsAutomaticUpdates == nil || allowsAutomaticUpdates.boolValue); } -- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], [self.host bundlePath]]; } +- (NSString *)description { return [NSString stringWithFormat:@"%@ <%@>", [self class], _host.bundlePath]; } - (void)windowDidLoad { [self.window center]; - self.infoChoiceView.hidden = ![self shouldAskAboutProfile]; - self.automaticallyDownloadUpdatesView.hidden = ![self allowsAutomaticUpdates]; + _infoChoiceView.hidden = ![self shouldAskAboutProfile]; + _automaticallyDownloadUpdatesView.hidden = ![self allowsAutomaticUpdates]; - [self.stackView addArrangedSubview:self.promptView]; - [self.stackView addArrangedSubview:self.automaticallyDownloadUpdatesView]; - [self.stackView addArrangedSubview:self.infoChoiceView]; - [self.stackView addArrangedSubview:self.placeholderView]; - [self.stackView addArrangedSubview:self.moreInfoView]; - [self.stackView addArrangedSubview:self.responseView]; + [_stackView addArrangedSubview:_promptView]; + [_stackView addArrangedSubview:_automaticallyDownloadUpdatesView]; + [_stackView addArrangedSubview:_infoChoiceView]; + [_stackView addArrangedSubview:_placeholderView]; + [_stackView addArrangedSubview:_moreInfoView]; + [_stackView addArrangedSubview:_responseView]; } - (BOOL)tableView:(NSTableView *) __unused tableView shouldSelectRow:(NSInteger) __unused row { return NO; } @@ -115,12 +102,12 @@ static NSString *const SUUpdatePermissionPromptTouchBarIndentifier = @"" SPARKLE - (NSImage *)icon { - return [SUApplicationInfo bestIconForHost:self.host]; + return [SUApplicationInfo bestIconForHost:_host]; } - (NSString *)promptDescription { - return [NSString stringWithFormat:SULocalizedString(@"Should %1$@ automatically check for updates? You can always check for updates manually from the %1$@ menu.", nil), [self.host name]]; + return [NSString stringWithFormat:SULocalizedStringFromTableInBundle(@"Should %1$@ automatically check for updates? You can always check for updates manually from the %1$@ menu.", SPARKLE_TABLE, SUSparkleBundle(), nil), _host.name]; } - (IBAction)toggleMoreInfo:(id)__unused sender @@ -130,31 +117,31 @@ static NSString *const SUUpdatePermissionPromptTouchBarIndentifier = @"" SPARKLE static const CGFloat TOGGLE_INFO_ANIMATION_DURATION = 0.2; - BOOL disclosingInfo = (self.anonymousInfoDisclosureButton.state == NSControlStateValueOn); + BOOL disclosingInfo = (_anonymousInfoDisclosureButton.state == NSControlStateValueOn); if (disclosingInfo) { - self.placeholderHeightLayoutConstraint.constant = 0.0; - self.placeholderView.hidden = NO; + _placeholderHeightLayoutConstraint.constant = 0.0; + _placeholderView.hidden = NO; [NSAnimationContext runAnimationGroup:^(NSAnimationContext * _Nonnull context) { context.duration = TOGGLE_INFO_ANIMATION_DURATION; - self.placeholderHeightLayoutConstraint.animator.constant = self.moreInfoView.frame.size.height; + self->_placeholderHeightLayoutConstraint.animator.constant = _moreInfoView.frame.size.height; } completionHandler:^{ - self.placeholderView.hidden = YES; - self.moreInfoView.hidden = NO; + self->_placeholderView.hidden = YES; + self->_moreInfoView.hidden = NO; }]; } else { - self.placeholderHeightLayoutConstraint.constant = self.moreInfoView.frame.size.height; - self.moreInfoView.hidden = YES; - self.placeholderView.hidden = NO; + _placeholderHeightLayoutConstraint.constant = _moreInfoView.frame.size.height; + _moreInfoView.hidden = YES; + _placeholderView.hidden = NO; [NSAnimationContext runAnimationGroup:^(NSAnimationContext * _Nonnull context) { context.duration = TOGGLE_INFO_ANIMATION_DURATION; - self.placeholderHeightLayoutConstraint.animator.constant = 0.0; + self->_placeholderHeightLayoutConstraint.animator.constant = 0.0; } completionHandler:^{ - self.placeholderView.hidden = YES; + self->_placeholderView.hidden = YES; }]; } } @@ -165,13 +152,13 @@ static NSString *const SUUpdatePermissionPromptTouchBarIndentifier = @"" SPARKLE NSNumber *automaticUpdateDownloading; if ([self allowsAutomaticUpdates]) { - automaticUpdateDownloading = @(automaticUpdateChecksEnabled && self.automaticallyDownloadUpdates); + automaticUpdateDownloading = @(automaticUpdateChecksEnabled && _automaticallyDownloadUpdates); } else { automaticUpdateDownloading = nil; } - SUUpdatePermissionResponse *response = [[SUUpdatePermissionResponse alloc] initWithAutomaticUpdateChecks:automaticUpdateChecksEnabled automaticUpdateDownloading:automaticUpdateDownloading sendSystemProfile:self.shouldSendProfile]; - self.reply(response); + SUUpdatePermissionResponse *response = [[SUUpdatePermissionResponse alloc] initWithAutomaticUpdateChecks:automaticUpdateChecksEnabled automaticUpdateDownloading:automaticUpdateDownloading sendSystemProfile:_shouldSendProfile]; + _reply(response); [self close]; } @@ -189,7 +176,7 @@ static NSString *const SUUpdatePermissionPromptTouchBarIndentifier = @"" SPARKLE { if ([identifier isEqualToString:SUUpdatePermissionPromptTouchBarIndentifier]) { NSCustomTouchBarItem* item = [[NSCustomTouchBarItem alloc] initWithIdentifier:identifier]; - item.viewController = [[SUTouchBarButtonGroup alloc] initByReferencingButtons:@[self.checkButton, self.cancelButton]]; + item.viewController = [[SUTouchBarButtonGroup alloc] initByReferencingButtons:@[_checkButton, _cancelButton]]; return item; } return nil; diff --git a/Sparkle/SUUpdatePermissionResponse.h b/Sparkle/SUUpdatePermissionResponse.h index 990f8e07..d2a50ae0 100644 --- a/Sparkle/SUUpdatePermissionResponse.h +++ b/Sparkle/SUUpdatePermissionResponse.h @@ -7,7 +7,16 @@ // #import <Foundation/Foundation.h> + +#if defined(BUILDING_SPARKLE_SOURCES_EXTERNALLY) +// Ignore incorrect warning +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wquoted-include-in-framework-header" +#import "SUExport.h" +#pragma clang diagnostic pop +#else #import <Sparkle/SUExport.h> +#endif NS_ASSUME_NONNULL_BEGIN diff --git a/Sparkle/SUUpdatePermissionResponse.m b/Sparkle/SUUpdatePermissionResponse.m index 27d9e79d..d94a9636 100644 --- a/Sparkle/SUUpdatePermissionResponse.m +++ b/Sparkle/SUUpdatePermissionResponse.m @@ -36,13 +36,13 @@ static NSString *SUUpdatePermissionSendSystemProfileKey = @"SUUpdatePermissionSe - (void)encodeWithCoder:(NSCoder *)encoder { - [encoder encodeBool:self.automaticUpdateChecks forKey:SUUpdatePermissionAutomaticUpdateChecksKey]; + [encoder encodeBool:_automaticUpdateChecks forKey:SUUpdatePermissionAutomaticUpdateChecksKey]; - if (self.automaticUpdateDownloading != nil) { - [encoder encodeObject:self.automaticUpdateDownloading forKey:SUUpdatePermissionAutomaticUpdateDownloadingKey]; + if (_automaticUpdateDownloading != nil) { + [encoder encodeObject:_automaticUpdateDownloading forKey:SUUpdatePermissionAutomaticUpdateDownloadingKey]; } - [encoder encodeBool:self.sendSystemProfile forKey:SUUpdatePermissionSendSystemProfileKey]; + [encoder encodeBool:_sendSystemProfile forKey:SUUpdatePermissionSendSystemProfileKey]; } - (instancetype)initWithAutomaticUpdateChecks:(BOOL)automaticUpdateChecks automaticUpdateDownloading:(NSNumber * _Nullable)automaticUpdateDownloading sendSystemProfile:(BOOL)sendSystemProfile diff --git a/Sparkle/SUUpdateValidator.h b/Sparkle/SUUpdateValidator.h index c1b93951..534084f2 100644 --- a/Sparkle/SUUpdateValidator.h +++ b/Sparkle/SUUpdateValidator.h @@ -13,6 +13,9 @@ NS_ASSUME_NONNULL_BEGIN +#ifndef BUILDING_SPARKLE_TESTS +SPU_OBJC_DIRECT_MEMBERS +#endif @interface SUUpdateValidator : NSObject - (instancetype)initWithDownloadPath:(NSString *)downloadPath signatures:(SUSignatures *)signatures host:(SUHost *)host; diff --git a/Sparkle/SUUpdateValidator.m b/Sparkle/SUUpdateValidator.m index 4d66ae6e..a4f4597f 100644 --- a/Sparkle/SUUpdateValidator.m +++ b/Sparkle/SUUpdateValidator.m @@ -18,21 +18,14 @@ #include "AppKitPrevention.h" -@interface SUUpdateValidator () - -@property (nonatomic, readonly) SUHost *host; -@property (nonatomic) BOOL prevalidatedSignature; -@property (strong, nonatomic, readonly) SUSignatures *signatures; -@property (nonatomic, readonly) NSString *downloadPath; - -@end - @implementation SUUpdateValidator - -@synthesize host = _host; -@synthesize prevalidatedSignature = _prevalidatedSignature; -@synthesize signatures = _signatures; -@synthesize downloadPath = _downloadPath; +{ + SUHost *_host; + SUSignatures *_signatures; + NSString *_downloadPath; + + BOOL _prevalidatedSignature; +} - (instancetype)initWithDownloadPath:(NSString *)downloadPath signatures:(SUSignatures *)signatures host:(SUHost *)host { @@ -47,8 +40,8 @@ - (BOOL)validateDownloadPathWithError:(NSError * __autoreleasing *)error { - SUPublicKeys *publicKeys = self.host.publicKeys; - SUSignatures *signatures = self.signatures; + SUPublicKeys *publicKeys = _host.publicKeys; + SUSignatures *signatures = _signatures; if (!publicKeys.hasAnyKeys) { if (error != NULL) { @@ -56,12 +49,12 @@ } } else { NSError *innerError = nil; - if ([SUSignatureVerifier validatePath:self.downloadPath withSignatures:signatures withPublicKeys:publicKeys error:&innerError]) { - self.prevalidatedSignature = YES; + if ([SUSignatureVerifier validatePath:_downloadPath withSignatures:signatures withPublicKeys:publicKeys error:&innerError]) { + _prevalidatedSignature = YES; return YES; } if (error != NULL) { - *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"(Ed)DSA signature validation before unarchiving failed for update %@", self.downloadPath], NSUnderlyingErrorKey: innerError }]; + *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUInstallationError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"(Ed)DSA signature validation before unarchiving failed for update %@", _downloadPath], NSUnderlyingErrorKey: innerError }]; } } return NO; @@ -69,15 +62,21 @@ - (BOOL)validateWithUpdateDirectory:(NSString *)updateDirectory error:(NSError * __autoreleasing *)error { - SUSignatures *signatures = self.signatures; - SUPublicKeys *publicKeys = self.host.publicKeys; - NSString *downloadPath = self.downloadPath; - SUHost *host = self.host; + SUSignatures *signatures = _signatures; + NSString *downloadPath = _downloadPath; + SUHost *host = _host; +#if SPARKLE_BUILD_PACKAGE_SUPPORT BOOL isPackage = NO; +#endif // install source could point to a new bundle or a package - NSString *installSource = [SUInstaller installSourcePathInUpdateFolder:updateDirectory forHost:host isPackage:&isPackage isGuided:NULL]; + NSString *installSource = [SUInstaller installSourcePathInUpdateFolder:updateDirectory forHost:host +#if SPARKLE_BUILD_PACKAGE_SUPPORT + isPackage:&isPackage isGuided:NULL +#endif + ]; + if (installSource == nil) { if (error != NULL) { *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUValidationError userInfo:@{ NSLocalizedDescriptionKey: @"No suitable install is found in the update. The update will be rejected." }]; @@ -87,12 +86,14 @@ NSURL *installSourceURL = [NSURL fileURLWithPath:installSource]; - if (!self.prevalidatedSignature) { + if (!_prevalidatedSignature) { +#if SPARKLE_BUILD_PACKAGE_SUPPORT // Check to see if we have a package or bundle to validate if (isPackage) { // If we get here, then the appcast installation type was lying to us.. This error will be caught later when starting the installer. // For package type updates, all we do is check if the EdDSA signature is valid NSError *innerError = nil; + SUPublicKeys *publicKeys = host.publicKeys; BOOL validationCheckSuccess = [SUSignatureVerifier validatePath:downloadPath withSignatures:signatures withPublicKeys:publicKeys error:&innerError]; if (!validationCheckSuccess) { if (error != NULL) { @@ -100,14 +101,21 @@ } } return validationCheckSuccess; - } else { + } else +#endif + { // For application bundle updates, we check both the EdDSA and Apple code signing signatures return [self validateUpdateForHost:host downloadedToPath:downloadPath newBundleURL:installSourceURL signatures:signatures error:error]; } - } else if (isPackage) { + } +#if SPARKLE_BUILD_PACKAGE_SUPPORT + else if (isPackage) { // We already prevalidated the package and nothing else needs to be done return YES; - } else { + } +#endif + else + { // Because we already validated the EdDSA signature, this is just a consistency check to see // if the developer signed their application properly with their Apple ID // Currently, this case only gets hit for binary delta updates @@ -132,7 +140,7 @@ * * old and new Code Signing identity are the same and valid * */ -- (BOOL)validateUpdateForHost:(SUHost *)host downloadedToPath:(NSString *)downloadedPath newBundleURL:(NSURL *)newBundleURL signatures:(SUSignatures *)signatures error:(NSError * __autoreleasing *)error +- (BOOL)validateUpdateForHost:(SUHost *)host downloadedToPath:(NSString *)downloadedPath newBundleURL:(NSURL *)newBundleURL signatures:(SUSignatures *)signatures error:(NSError * __autoreleasing *)error SPU_OBJC_DIRECT { NSBundle *newBundle = [NSBundle bundleWithURL:newBundleURL]; if (newBundle == nil) { @@ -146,13 +154,29 @@ SUHost *newHost = [[SUHost alloc] initWithBundle:newBundle]; SUPublicKeys *newPublicKeys = newHost.publicKeys; +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT BOOL oldHasLegacyDSAKey = publicKeys.dsaPubKeyStatus != SUSigningInputStatusAbsent; +#endif BOOL oldHasEdDSAKey = publicKeys.ed25519PubKeyStatus != SUSigningInputStatusAbsent; +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT BOOL oldHasAnyDSAKey = oldHasLegacyDSAKey || oldHasEdDSAKey; +#else + BOOL oldHasAnyDSAKey = oldHasEdDSAKey; +#endif +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT BOOL newHasLegacyDSAKey = newPublicKeys.dsaPubKeyStatus != SUSigningInputStatusAbsent; +#endif BOOL newHasEdDSAKey = newPublicKeys.ed25519PubKeyStatus != SUSigningInputStatusAbsent; +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT BOOL newHasAnyDSAKey = newHasLegacyDSAKey || newHasEdDSAKey; +#else + BOOL newHasAnyDSAKey = newHasEdDSAKey; +#endif +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT BOOL migratesDSAKeys = oldHasLegacyDSAKey && !oldHasEdDSAKey && newHasEdDSAKey && !newHasLegacyDSAKey; +#else + BOOL migratesDSAKeys = NO; +#endif BOOL updateIsCodeSigned = [SUCodeSigningVerifier bundleAtURLIsCodeSigned:newHost.bundle.bundleURL]; BOOL hostIsCodeSigned = [SUCodeSigningVerifier bundleAtURLIsCodeSigned:host.bundle.bundleURL]; diff --git a/Sparkle/SUUpdater.h b/Sparkle/SUUpdater.h index f2683245..5bc7d68b 100644 --- a/Sparkle/SUUpdater.h +++ b/Sparkle/SUUpdater.h @@ -10,10 +10,22 @@ #define SUUPDATER_H #import <Foundation/Foundation.h> + +#if defined(BUILDING_SPARKLE_SOURCES_EXTERNALLY) +// Ignore incorrect warning +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wquoted-include-in-framework-header" +#import "SUExport.h" +#import "SUVersionComparisonProtocol.h" +#import "SUVersionDisplayProtocol.h" +#import "SUUpdaterDelegate.h" +#pragma clang diagnostic pop +#else #import <Sparkle/SUExport.h> #import <Sparkle/SUVersionComparisonProtocol.h> #import <Sparkle/SUVersionDisplayProtocol.h> #import <Sparkle/SUUpdaterDelegate.h> +#endif @class SUAppcastItem, SUAppcast, NSMenuItem; @@ -157,7 +169,7 @@ SU_EXPORT @interface SUUpdater : NSObject The keys of this dictionary are HTTP header fields (NSString) and values are corresponding values (NSString) */ -@property (copy) NSDictionary<NSString *, NSString *> *httpHeaders; +@property (copy, nonatomic) NSDictionary<NSString *, NSString *> *httpHeaders; /*! A property indicating whether or not the user's system profile information is sent when checking for updates. diff --git a/Sparkle/SUUpdater.m b/Sparkle/SUUpdater.m index 5a9a1670..774756b5 100644 --- a/Sparkle/SUUpdater.m +++ b/Sparkle/SUUpdater.m @@ -6,7 +6,7 @@ // Copyright 2006 Andy Matuschak. All rights reserved. // -#if SPARKLE_BUILD_UI_BITS +#if SPARKLE_BUILD_UI_BITS && SPARKLE_BUILD_LEGACY_SUUPDATER #import "SUUpdater.h" #import "SPUUpdater.h" @@ -17,15 +17,6 @@ #import <AppKit/AppKit.h> @interface SUUpdater () <SPUUpdaterDelegate, SPUStandardUserDriverDelegate> - -@property (nonatomic, readonly) SPUUpdater *updater; -@property (nonatomic, readonly) SPUStandardUserDriver *userDriver; - -@property (nonatomic, copy) void(^postponedInstallHandler)(void); -@property (nonatomic, copy) void(^silentInstallHandler)(void); - -@property (nonatomic) BOOL loggedInstallUpdatesIfAvailableWarning; - @end #pragma clang diagnostic push @@ -33,16 +24,18 @@ @implementation SUUpdater #pragma clang diagnostic pop { + SPUUpdater *_updater; + SPUStandardUserDriver *_userDriver; + + void(^_postponedInstallHandler)(void); + void(^_silentInstallHandler)(void); + BOOL _delayShowingUserUpdate; + BOOL _loggedInstallUpdatesIfAvailableWarning; } -@synthesize updater = _updater; @synthesize delegate = _delegate; -@synthesize userDriver = _userDriver; -@synthesize postponedInstallHandler = _postponedInstallHandler; -@synthesize silentInstallHandler = _silentInstallHandler; @synthesize decryptionPassword = _decryptionPassword; -@synthesize loggedInstallUpdatesIfAvailableWarning = _loggedInstallUpdatesIfAvailableWarning; static NSMutableDictionary *sharedUpdaters = nil; @@ -87,7 +80,7 @@ static NSMutableDictionary *sharedUpdaters = nil; _updater = [[SPUUpdater alloc] initWithHostBundle:bundle applicationBundle:bundle userDriver:_userDriver delegate:self]; NSError *updaterError = nil; - if (![self.updater startUpdater:&updaterError]) { + if (![_updater startUpdater:&updaterError]) { SULog(SULogLevelError, @"Error: Failed to start updater with error: %@", updaterError); } } @@ -102,12 +95,12 @@ static NSMutableDictionary *sharedUpdaters = nil; - (void)resetUpdateCycle { - [self.updater resetUpdateCycle]; + [_updater resetUpdateCycle]; } - (NSBundle *)hostBundle { - return self.updater.hostBundle; + return _updater.hostBundle; } - (NSBundle *)sparkleBundle @@ -118,83 +111,83 @@ static NSMutableDictionary *sharedUpdaters = nil; - (BOOL)automaticallyChecksForUpdates { - return self.updater.automaticallyChecksForUpdates; + return _updater.automaticallyChecksForUpdates; } - (void)setAutomaticallyChecksForUpdates:(BOOL)automaticallyChecksForUpdates { - [self.updater setAutomaticallyChecksForUpdates:automaticallyChecksForUpdates]; + [_updater setAutomaticallyChecksForUpdates:automaticallyChecksForUpdates]; } - (NSTimeInterval)updateCheckInterval { - return self.updater.updateCheckInterval; + return _updater.updateCheckInterval; } - (void)setUpdateCheckInterval:(NSTimeInterval)updateCheckInterval { - [self.updater setUpdateCheckInterval:updateCheckInterval]; + [_updater setUpdateCheckInterval:updateCheckInterval]; } - (NSURL *)feedURL { - return self.updater.feedURL; + return _updater.feedURL; } - (void)setFeedURL:(NSURL *)feedURL { - [self.updater setFeedURL:feedURL]; + [_updater setFeedURL:feedURL]; } - (NSString *)userAgentString { - return self.updater.userAgentString; + return _updater.userAgentString; } - (void)setUserAgentString:(NSString *)userAgentString { - [self.updater setUserAgentString:userAgentString]; + [_updater setUserAgentString:userAgentString]; } - (NSDictionary *)httpHeaders { - return self.updater.httpHeaders; + return _updater.httpHeaders; } - (void)setHttpHeaders:(NSDictionary *)httpHeaders { - [self.updater setHttpHeaders:httpHeaders]; + [_updater setHttpHeaders:httpHeaders]; } - (BOOL)sendsSystemProfile { - return self.updater.sendsSystemProfile; + return _updater.sendsSystemProfile; } - (void)setSendsSystemProfile:(BOOL)sendsSystemProfile { - [self.updater setSendsSystemProfile:sendsSystemProfile]; + [_updater setSendsSystemProfile:sendsSystemProfile]; } - (BOOL)automaticallyDownloadsUpdates { - return self.updater.automaticallyDownloadsUpdates; + return _updater.automaticallyDownloadsUpdates; } - (void)setAutomaticallyDownloadsUpdates:(BOOL)automaticallyDownloadsUpdates { - [self.updater setAutomaticallyDownloadsUpdates:automaticallyDownloadsUpdates]; + [_updater setAutomaticallyDownloadsUpdates:automaticallyDownloadsUpdates]; } - (IBAction)checkForUpdates:(id)__unused sender { - [self.updater checkForUpdates]; + [_updater checkForUpdates]; } - (BOOL)validateMenuItem:(NSMenuItem *)item { if ([item action] == @selector(checkForUpdates:)) { - return self.updater.canCheckForUpdates; + return _updater.canCheckForUpdates; } return YES; } @@ -207,25 +200,25 @@ static NSMutableDictionary *sharedUpdaters = nil; // So if checkForUpdatesInBackground is called we will bring the update back in focus [self checkForUpdates:nil]; } else { - [self.updater checkForUpdatesInBackground]; + [_updater checkForUpdatesInBackground]; } } - (NSDate *)lastUpdateCheckDate { - return self.updater.lastUpdateCheckDate; + return _updater.lastUpdateCheckDate; } - (void)checkForUpdateInformation { - [self.updater checkForUpdateInformation]; + [_updater checkForUpdateInformation]; } - (BOOL)updateInProgress { // This is not quite true -- we may be able to check / resume an update if one is in progress // But this is a close enough approximation for 1.x updater API - return self.updater.sessionInProgress; + return _updater.sessionInProgress; } // Not implemented properly at the moment - leaning towards it not be in the future @@ -234,10 +227,10 @@ static NSMutableDictionary *sharedUpdaters = nil; // For now, just invoke the regular background update process if this is invoked. Could change our minds on this later. - (void)installUpdatesIfAvailable { - if (!self.loggedInstallUpdatesIfAvailableWarning) { + if (!_loggedInstallUpdatesIfAvailableWarning) { SULog(SULogLevelError, @"-[%@ installUpdatesIfAvailable] does not function anymore.. Instead a background scheduled update check will be done.", NSStringFromClass([self class])); - self.loggedInstallUpdatesIfAvailableWarning = YES; + _loggedInstallUpdatesIfAvailableWarning = YES; } [self checkForUpdatesInBackground]; @@ -245,23 +238,23 @@ static NSMutableDictionary *sharedUpdaters = nil; - (void)standardUserDriverWillShowModalAlert { - if ([self.delegate respondsToSelector:@selector(updaterWillShowModalAlert:)]) { - [self.delegate updaterWillShowModalAlert:self]; + if ([_delegate respondsToSelector:@selector(updaterWillShowModalAlert:)]) { + [_delegate updaterWillShowModalAlert:self]; } } - (void)standardUserDriverDidShowModalAlert { - if ([self.delegate respondsToSelector:@selector(updaterDidShowModalAlert:)]) { - [self.delegate updaterDidShowModalAlert:self]; + if ([_delegate respondsToSelector:@selector(updaterDidShowModalAlert:)]) { + [_delegate updaterDidShowModalAlert:self]; } } - (_Nullable id <SUVersionDisplay>)standardUserDriverRequestsVersionDisplayer { id <SUVersionDisplay> versionDisplayer = nil; - if ([self.delegate respondsToSelector:@selector(versionDisplayerForUpdater:)]) { - versionDisplayer = [self.delegate versionDisplayerForUpdater:self]; + if ([_delegate respondsToSelector:@selector(versionDisplayerForUpdater:)]) { + versionDisplayer = [_delegate versionDisplayerForUpdater:self]; } return versionDisplayer; } @@ -269,8 +262,8 @@ static NSMutableDictionary *sharedUpdaters = nil; - (BOOL)updater:(SPUUpdater *)__unused updater mayPerformUpdateCheck:(SPUUpdateCheck)__unused updateCheck error:(NSError *__autoreleasing _Nullable *)error { BOOL updaterMayCheck = YES; - if ([self.delegate respondsToSelector:@selector(updaterMayCheckForUpdates:)]) { - updaterMayCheck = [self.delegate updaterMayCheckForUpdates:self]; + if ([_delegate respondsToSelector:@selector(updaterMayCheckForUpdates:)]) { + updaterMayCheck = [_delegate updaterMayCheckForUpdates:self]; } return updaterMayCheck; } @@ -278,8 +271,8 @@ static NSMutableDictionary *sharedUpdaters = nil; - (NSArray *)feedParametersForUpdater:(SPUUpdater *)__unused updater sendingSystemProfile:(BOOL)sendingProfile { NSArray *feedParameters; - if ([self.delegate respondsToSelector:@selector(feedParametersForUpdater:sendingSystemProfile:)]) { - feedParameters = [self.delegate feedParametersForUpdater:self sendingSystemProfile:sendingProfile]; + if ([_delegate respondsToSelector:@selector(feedParametersForUpdater:sendingSystemProfile:)]) { + feedParameters = [_delegate feedParametersForUpdater:self sendingSystemProfile:sendingProfile]; } else { feedParameters = [NSArray array]; } @@ -290,8 +283,8 @@ static NSMutableDictionary *sharedUpdaters = nil; { // Be really careful not to call [self feedURL] here. That might lead us into infinite recursion. NSString *feedURL = nil; - if ([self.delegate respondsToSelector:@selector(feedURLStringForUpdater:)]) { - feedURL = [self.delegate feedURLStringForUpdater:self]; + if ([_delegate respondsToSelector:@selector(feedURLStringForUpdater:)]) { + feedURL = [_delegate feedURLStringForUpdater:self]; } return feedURL; } @@ -299,61 +292,61 @@ static NSMutableDictionary *sharedUpdaters = nil; - (BOOL)updaterShouldPromptForPermissionToCheckForUpdates:(SPUUpdater *)__unused updater { BOOL shouldPrompt = YES; - if ([self.delegate respondsToSelector:@selector(updater:didFinishLoadingAppcast:)]) { - shouldPrompt = [self.delegate updaterShouldPromptForPermissionToCheckForUpdates:self]; + if ([_delegate respondsToSelector:@selector(updater:didFinishLoadingAppcast:)]) { + shouldPrompt = [_delegate updaterShouldPromptForPermissionToCheckForUpdates:self]; } return shouldPrompt; } - (void)updater:(SPUUpdater *)__unused updater didFinishLoadingAppcast:(SUAppcast *)appcast { - if ([self.delegate respondsToSelector:@selector(updater:didFinishLoadingAppcast:)]) { - [self.delegate updater:self didFinishLoadingAppcast:appcast]; + if ([_delegate respondsToSelector:@selector(updater:didFinishLoadingAppcast:)]) { + [_delegate updater:self didFinishLoadingAppcast:appcast]; } } - (SUAppcastItem *)bestValidUpdateInAppcast:(SUAppcast *)appcast forUpdater:(SPUUpdater *)__unused updater { SUAppcastItem *bestValidUpdate = nil; - if ([self.delegate respondsToSelector:@selector(bestValidUpdateInAppcast:forUpdater:)]) { - bestValidUpdate = [self.delegate bestValidUpdateInAppcast:appcast forUpdater:self]; + if ([_delegate respondsToSelector:@selector(bestValidUpdateInAppcast:forUpdater:)]) { + bestValidUpdate = [_delegate bestValidUpdateInAppcast:appcast forUpdater:self]; } return bestValidUpdate; } - (void)updater:(SPUUpdater *)__unused updater didFindValidUpdate:(SUAppcastItem *)item { - if ([self.delegate respondsToSelector:@selector(updater:didFindValidUpdate:)]) { - [self.delegate updater:self didFindValidUpdate:item]; + if ([_delegate respondsToSelector:@selector(updater:didFindValidUpdate:)]) { + [_delegate updater:self didFindValidUpdate:item]; } } - (void)updaterDidNotFindUpdate:(SPUUpdater *)__unused updater { - if ([self.delegate respondsToSelector:@selector(updaterDidNotFindUpdate:)]) { - [self.delegate updaterDidNotFindUpdate:self]; + if ([_delegate respondsToSelector:@selector(updaterDidNotFindUpdate:)]) { + [_delegate updaterDidNotFindUpdate:self]; } } - (void)updater:(SPUUpdater *)__unused updater userDidMakeChoice:(SPUUserUpdateChoice)choice forUpdate:(SUAppcastItem *)updateItem state:(SPUUserUpdateState *)__unused state { // This delegate callback matches 1.x behavior (even though -standardUserDriverWillFinishUpdateSession might be a better place for it) - if ([self.delegate respondsToSelector:@selector(updater:didDismissUpdateAlertPermanently:forItem:)]) { - [self.delegate updater:self didDismissUpdateAlertPermanently:(choice == SPUUserUpdateChoiceSkip) forItem:updateItem]; + if ([_delegate respondsToSelector:@selector(updater:didDismissUpdateAlertPermanently:forItem:)]) { + [_delegate updater:self didDismissUpdateAlertPermanently:(choice == SPUUserUpdateChoiceSkip) forItem:updateItem]; } - if (choice == SPUUserUpdateChoiceSkip && [self.delegate respondsToSelector:@selector(updater:userDidSkipThisVersion:)]) { - [self.delegate updater:self userDidSkipThisVersion:updateItem]; + if (choice == SPUUserUpdateChoiceSkip && [_delegate respondsToSelector:@selector(updater:userDidSkipThisVersion:)]) { + [_delegate updater:self userDidSkipThisVersion:updateItem]; } } - (BOOL)standardUserDriverShouldHandleShowingScheduledUpdate:(SUAppcastItem *)update andInImmediateFocus:(BOOL)immediateFocus { - if ([self.delegate respondsToSelector:@selector(updaterShouldShowUpdateAlertForScheduledUpdate:forItem:)]) { + if ([_delegate respondsToSelector:@selector(updaterShouldShowUpdateAlertForScheduledUpdate:forItem:)]) { // If the delegate returns NO and tries to show the update before // -standardUserDriverWillHandleShowingUpdate:forUpdate:state: is called, this is technically // a violation. However it is also unlikely to happen. - return [self.delegate updaterShouldShowUpdateAlertForScheduledUpdate:self forItem:update]; + return [_delegate updaterShouldShowUpdateAlertForScheduledUpdate:self forItem:update]; } else { return YES; } @@ -373,58 +366,58 @@ static NSMutableDictionary *sharedUpdaters = nil; - (void)updater:(SPUUpdater *)__unused updater willDownloadUpdate:(SUAppcastItem *)item withRequest:(NSMutableURLRequest *)request { - if ([self.delegate respondsToSelector:@selector(updater:willDownloadUpdate:withRequest:)]) { - [self.delegate updater:self willDownloadUpdate:item withRequest:request]; + if ([_delegate respondsToSelector:@selector(updater:willDownloadUpdate:withRequest:)]) { + [_delegate updater:self willDownloadUpdate:item withRequest:request]; } } - (void)updater:(SPUUpdater *)__unused updater didDownloadUpdate:(SUAppcastItem *)item { - if ([self.delegate respondsToSelector:@selector(updater:didDownloadUpdate:)]) { - [self.delegate updater:self didDownloadUpdate:item]; + if ([_delegate respondsToSelector:@selector(updater:didDownloadUpdate:)]) { + [_delegate updater:self didDownloadUpdate:item]; } } - (void)updater:(SPUUpdater *)__unused updater failedToDownloadUpdate:(SUAppcastItem *)item error:(NSError *)error { - if ([self.delegate respondsToSelector:@selector(updater:failedToDownloadUpdate:error:)]) { - [self.delegate updater:self failedToDownloadUpdate:item error:error]; + if ([_delegate respondsToSelector:@selector(updater:failedToDownloadUpdate:error:)]) { + [_delegate updater:self failedToDownloadUpdate:item error:error]; } } - (void)userDidCancelDownload:(SPUUpdater *)__unused updater { - if ([self.delegate respondsToSelector:@selector(userDidCancelDownload:)]) { - [self.delegate userDidCancelDownload:self]; + if ([_delegate respondsToSelector:@selector(userDidCancelDownload:)]) { + [_delegate userDidCancelDownload:self]; } } - (void)updater:(SPUUpdater *)updater willExtractUpdate:(SUAppcastItem *)item { - if ([self.delegate respondsToSelector:@selector(updater:willExtractUpdate:)]) { - [self.delegate updater:self willExtractUpdate:item]; + if ([_delegate respondsToSelector:@selector(updater:willExtractUpdate:)]) { + [_delegate updater:self willExtractUpdate:item]; } } - (void)updater:(SPUUpdater *)updater didExtractUpdate:(SUAppcastItem *)item { - if ([self.delegate respondsToSelector:@selector(updater:didExtractUpdate:)]) { - [self.delegate updater:self didExtractUpdate:item]; + if ([_delegate respondsToSelector:@selector(updater:didExtractUpdate:)]) { + [_delegate updater:self didExtractUpdate:item]; } } - (void)updater:(SPUUpdater *)__unused updater willInstallUpdate:(SUAppcastItem *)item { - if ([self.delegate respondsToSelector:@selector(updater:willInstallUpdate:)]) { - [self.delegate updater:self willInstallUpdate:item]; + if ([_delegate respondsToSelector:@selector(updater:willInstallUpdate:)]) { + [_delegate updater:self willInstallUpdate:item]; } } - (void)installPostponedUpdate { - if (self.postponedInstallHandler != nil) { - self.postponedInstallHandler(); - self.postponedInstallHandler = nil; + if (_postponedInstallHandler != nil) { + _postponedInstallHandler(); + _postponedInstallHandler = nil; } } @@ -432,7 +425,7 @@ static NSMutableDictionary *sharedUpdaters = nil; { BOOL shouldPostponeRelaunch = NO; - if ([self.delegate respondsToSelector:@selector(updater:shouldPostponeRelaunchForUpdate:untilInvoking:)]) { + if ([_delegate respondsToSelector:@selector(updater:shouldPostponeRelaunchForUpdate:untilInvoking:)]) { NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[[self class] instanceMethodSignatureForSelector:@selector(installPostponedUpdate)]]; [invocation setSelector:@selector(installPostponedUpdate)]; @@ -440,12 +433,12 @@ static NSMutableDictionary *sharedUpdaters = nil; // This invocation will retain self, but this instance is kept alive forever by our singleton pattern anyway [invocation setTarget:self]; - self.postponedInstallHandler = installHandler; + _postponedInstallHandler = installHandler; - shouldPostponeRelaunch = [self.delegate updater:self shouldPostponeRelaunchForUpdate:item untilInvoking:invocation]; - } else if ([self.delegate respondsToSelector:@selector(updater:shouldPostponeRelaunchForUpdate:)]) { + shouldPostponeRelaunch = [_delegate updater:self shouldPostponeRelaunchForUpdate:item untilInvoking:invocation]; + } else if ([_delegate respondsToSelector:@selector(updater:shouldPostponeRelaunchForUpdate:)]) { // This API should really take a block, but not fixing a 1.x mishap now - shouldPostponeRelaunch = [self.delegate updater:self shouldPostponeRelaunchForUpdate:item]; + shouldPostponeRelaunch = [_delegate updater:self shouldPostponeRelaunchForUpdate:item]; } return shouldPostponeRelaunch; @@ -454,24 +447,24 @@ static NSMutableDictionary *sharedUpdaters = nil; - (BOOL)updaterShouldRelaunchApplication:(SPUUpdater *)__unused updater { BOOL shouldRestart = YES; - if ([self.delegate respondsToSelector:@selector(updaterShouldRelaunchApplication:)]) { - shouldRestart = [self.delegate updaterShouldRelaunchApplication:self]; + if ([_delegate respondsToSelector:@selector(updaterShouldRelaunchApplication:)]) { + shouldRestart = [_delegate updaterShouldRelaunchApplication:self]; } return shouldRestart; } - (void)updaterWillRelaunchApplication:(SPUUpdater *)__unused updater { - if ([self.delegate respondsToSelector:@selector(updaterWillRelaunchApplication:)]) { - [self.delegate updaterWillRelaunchApplication:self]; + if ([_delegate respondsToSelector:@selector(updaterWillRelaunchApplication:)]) { + [_delegate updaterWillRelaunchApplication:self]; } } - (id<SUVersionComparison>)versionComparatorForUpdater:(SPUUpdater *)__unused updater { id<SUVersionComparison> versionComparator; - if ([self.delegate respondsToSelector:@selector(versionComparatorForUpdater:)]) { - versionComparator = [self.delegate versionComparatorForUpdater:self]; + if ([_delegate respondsToSelector:@selector(versionComparatorForUpdater:)]) { + versionComparator = [_delegate versionComparatorForUpdater:self]; } return versionComparator; } @@ -480,22 +473,22 @@ static NSMutableDictionary *sharedUpdaters = nil; - (NSString * _Nullable)_pathToRelaunchForUpdater:(SPUUpdater *)__unused updater { NSString *relaunchPath = nil; - if ([self.delegate respondsToSelector:@selector(pathToRelaunchForUpdater:)]) { - relaunchPath = [self.delegate pathToRelaunchForUpdater:self]; + if ([_delegate respondsToSelector:@selector(pathToRelaunchForUpdater:)]) { + relaunchPath = [_delegate pathToRelaunchForUpdater:self]; } return relaunchPath; } - (NSString *)decryptionPasswordForUpdater:(SPUUpdater *)__unused updater { - return self.decryptionPassword; + return _decryptionPassword; } - (void)finishSilentInstallation { - if (self.silentInstallHandler != nil) { - self.silentInstallHandler(); - self.silentInstallHandler = nil; + if (_silentInstallHandler != nil) { + _silentInstallHandler(); + _silentInstallHandler = nil; } } @@ -503,21 +496,21 @@ static NSMutableDictionary *sharedUpdaters = nil; { BOOL installationHandledByDelegate = NO; - if ([self.delegate respondsToSelector:@selector((updater:willInstallUpdateOnQuit:immediateInstallationBlock:))]) { - [self.delegate updater:self willInstallUpdateOnQuit:item immediateInstallationBlock:immediateInstallHandler]; + if ([_delegate respondsToSelector:@selector((updater:willInstallUpdateOnQuit:immediateInstallationBlock:))]) { + [_delegate updater:self willInstallUpdateOnQuit:item immediateInstallationBlock:immediateInstallHandler]; // We have to assume they will handle the installation since they implement this method // Not ideal, but this is why this delegate callback is deprecated installationHandledByDelegate = YES; - } else if ([self.delegate respondsToSelector:@selector(updater:willInstallUpdateOnQuit:immediateInstallationInvocation:)]) { + } else if ([_delegate respondsToSelector:@selector(updater:willInstallUpdateOnQuit:immediateInstallationInvocation:)]) { NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[[self class] instanceMethodSignatureForSelector:@selector(finishSilentInstallation)]]; // This invocation will retain self, but this instance is kept alive forever by our singleton pattern anyway [invocation setTarget:self]; - self.silentInstallHandler = immediateInstallHandler; + _silentInstallHandler = immediateInstallHandler; - [self.delegate updater:self willInstallUpdateOnQuit:item immediateInstallationInvocation:invocation]; + [_delegate updater:self willInstallUpdateOnQuit:item immediateInstallationInvocation:invocation]; // We have to assume they will handle the installation since they implement this method // Not ideal, but this is why this delegate callback is deprecated @@ -529,8 +522,8 @@ static NSMutableDictionary *sharedUpdaters = nil; - (void)updater:(SPUUpdater *)__unused updater didAbortWithError:(NSError *)error { - if ([self.delegate respondsToSelector:@selector(updater:didAbortWithError:)]) { - [self.delegate updater:self didAbortWithError:error]; + if ([_delegate respondsToSelector:@selector(updater:didAbortWithError:)]) { + [_delegate updater:self didAbortWithError:error]; } } diff --git a/Sparkle/SUUpdaterDelegate.h b/Sparkle/SUUpdaterDelegate.h index 466a92a4..42edf332 100644 --- a/Sparkle/SUUpdaterDelegate.h +++ b/Sparkle/SUUpdaterDelegate.h @@ -7,7 +7,16 @@ // #import <Foundation/Foundation.h> + +#if defined(BUILDING_SPARKLE_SOURCES_EXTERNALLY) +// Ignore incorrect warning +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wquoted-include-in-framework-header" +#import "SUExport.h" +#pragma clang diagnostic pop +#else #import <Sparkle/SUExport.h> +#endif @protocol SUVersionComparison, SUVersionDisplay; @class SUUpdater, SUAppcast, SUAppcastItem; diff --git a/Sparkle/SUVersionComparisonProtocol.h b/Sparkle/SUVersionComparisonProtocol.h index b21e90df..8d22d7a9 100644 --- a/Sparkle/SUVersionComparisonProtocol.h +++ b/Sparkle/SUVersionComparisonProtocol.h @@ -11,7 +11,7 @@ #import <Foundation/Foundation.h> -#ifdef BUILDING_SPARKLE_TOOL +#if defined(BUILDING_SPARKLE_SOURCES_EXTERNALLY) // Ignore incorrect warning #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wquoted-include-in-framework-header" diff --git a/Sparkle/SUVersionDisplayProtocol.h b/Sparkle/SUVersionDisplayProtocol.h index 736a28a8..598526be 100644 --- a/Sparkle/SUVersionDisplayProtocol.h +++ b/Sparkle/SUVersionDisplayProtocol.h @@ -7,7 +7,16 @@ // #import <Foundation/Foundation.h> + +#if defined(BUILDING_SPARKLE_SOURCES_EXTERNALLY) +// Ignore incorrect warning +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wquoted-include-in-framework-header" +#import "SUExport.h" +#pragma clang diagnostic pop +#else #import <Sparkle/SUExport.h> +#endif /** Applies special display formatting to version numbers. diff --git a/Sparkle/SUWKWebView.h b/Sparkle/SUWKWebView.h index fe818c35..413b7766 100644 --- a/Sparkle/SUWKWebView.h +++ b/Sparkle/SUWKWebView.h @@ -13,7 +13,7 @@ NS_ASSUME_NONNULL_BEGIN -@interface SUWKWebView : NSObject <SUWebView> +SPU_OBJC_DIRECT_MEMBERS @interface SUWKWebView : NSObject <SUWebView> - (instancetype)initWithColorStyleSheetLocation:(NSURL *)colorStyleSheetLocation fontFamily:(NSString *)fontFamily fontPointSize:(int)fontPointSize javaScriptEnabled:(BOOL)javaScriptEnabled; diff --git a/Sparkle/SUWKWebView.m b/Sparkle/SUWKWebView.m index 8b1fc8a0..2159f04f 100644 --- a/Sparkle/SUWKWebView.m +++ b/Sparkle/SUWKWebView.m @@ -22,20 +22,17 @@ @end @interface SUWKWebView () <WKNavigationDelegate> - -@property (nonatomic, readonly) WKWebView *webView; -@property (nonatomic) WKNavigation *currentNavigation; -@property (nonatomic) void (^completionHandler)(NSError * _Nullable); -@property (nonatomic) BOOL drawsWebViewBackground; - @end @implementation SUWKWebView - -@synthesize webView = _webView; -@synthesize currentNavigation = _currentNavigation; -@synthesize completionHandler = _completionHandler; -@synthesize drawsWebViewBackground = _drawsWebViewBackground; +{ + WKWebView *_webView; + WKNavigation *_currentNavigation; + + void (^_completionHandler)(NSError * _Nullable); + + BOOL _drawsWebViewBackground; +} static WKUserScript *_userScriptWithInjectedStyleSource(NSString *styleSource) { @@ -105,75 +102,75 @@ static WKUserScript *_userScriptWithInjectedStyleSource(NSString *styleSource) - (NSView *)view { - return self.webView; + return _webView; } - (void)loadHTMLString:(NSString *)htmlString baseURL:(NSURL * _Nullable)baseURL completionHandler:(void (^)(NSError * _Nullable))completionHandler { - self.completionHandler = [completionHandler copy]; + _completionHandler = [completionHandler copy]; - self.currentNavigation = [self.webView loadHTMLString:htmlString baseURL:baseURL]; + _currentNavigation = [_webView loadHTMLString:htmlString baseURL:baseURL]; } - (void)loadData:(NSData *)data MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)textEncodingName baseURL:(NSURL *)baseURL completionHandler:(void (^)(NSError * _Nullable))completionHandler { - self.completionHandler = [completionHandler copy]; + _completionHandler = [completionHandler copy]; - self.currentNavigation = [self.webView loadData:data MIMEType:MIMEType characterEncodingName:textEncodingName baseURL:baseURL]; + _currentNavigation = [_webView loadData:data MIMEType:MIMEType characterEncodingName:textEncodingName baseURL:baseURL]; } - (void)setDrawsBackground:(BOOL)drawsBackground { - if (self.drawsWebViewBackground != drawsBackground) { + if (_drawsWebViewBackground != drawsBackground) { // Unfortunately we have to rely on a private API // FB7539179: https://github.com/feedback-assistant/reports/issues/81 | https://bugs.webkit.org/show_bug.cgi?id=155550 // But it seems like others are already relying on it, passed App Review, and apps couldn't be broken due to compatibility // Note: before we were using _setDrawsTransparentBackground < macOS 10.12 - if ([self.webView respondsToSelector:@selector(_setDrawsBackground:)]) { - [self.webView _setDrawsBackground:drawsBackground]; + if ([_webView respondsToSelector:@selector(_setDrawsBackground:)]) { + [_webView _setDrawsBackground:drawsBackground]; } - self.drawsWebViewBackground = drawsBackground; + _drawsWebViewBackground = drawsBackground; } } - (void)stopLoading { - self.completionHandler = nil; - [self.webView stopLoading]; + _completionHandler = nil; + [_webView stopLoading]; } - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation { - if (navigation == self.currentNavigation) { - if (self.completionHandler != nil) { - self.completionHandler(nil); - self.completionHandler = nil; + if (navigation == _currentNavigation) { + if (_completionHandler != nil) { + _completionHandler(nil); + _completionHandler = nil; } - self.currentNavigation = nil; + _currentNavigation = nil; } } - (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error { - if (navigation == self.currentNavigation) { - if (self.completionHandler != nil) { - self.completionHandler(error); - self.completionHandler = nil; + if (navigation == _currentNavigation) { + if (_completionHandler != nil) { + _completionHandler(error); + _completionHandler = nil; } - self.currentNavigation = nil; + _currentNavigation = nil; } } - (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView { - if (self.currentNavigation != nil) { - if (self.completionHandler != nil) { - self.completionHandler([NSError errorWithDomain:SUSparkleErrorDomain code:SUWebKitTerminationError userInfo:nil]); - self.completionHandler = nil; + if (_currentNavigation != nil) { + if (_completionHandler != nil) { + _completionHandler([NSError errorWithDomain:SUSparkleErrorDomain code:SUWebKitTerminationError userInfo:nil]); + _completionHandler = nil; } - self.currentNavigation = nil; + _currentNavigation = nil; } } @@ -190,7 +187,7 @@ static WKUserScript *_userScriptWithInjectedStyleSource(NSString *styleSource) decisionHandler(WKNavigationActionPolicyCancel); } else { // Ensure we're finished loading - if (self.completionHandler == nil) { + if (_completionHandler == nil) { if (!isAboutBlank) { [[NSWorkspace sharedWorkspace] openURL:requestURL]; } diff --git a/TestApplication/SUAdHocCodeSigning.h b/TestApplication/SUAdHocCodeSigning.h index 377fb74a..3e944883 100644 --- a/TestApplication/SUAdHocCodeSigning.h +++ b/TestApplication/SUAdHocCodeSigning.h @@ -8,7 +8,7 @@ #import <Foundation/Foundation.h> -@interface SUAdHocCodeSigning : NSObject +SPU_OBJC_DIRECT_MEMBERS @interface SUAdHocCodeSigning : NSObject + (BOOL)codeSignApplicationAtPath:(NSString *)applicationPath; diff --git a/TestApplication/SUInstallUpdateViewController.h b/TestApplication/SUInstallUpdateViewController.h index a0cfc475..c3a6683c 100644 --- a/TestApplication/SUInstallUpdateViewController.h +++ b/TestApplication/SUInstallUpdateViewController.h @@ -9,7 +9,7 @@ #import <Cocoa/Cocoa.h> #import <Sparkle/Sparkle.h> -@interface SUInstallUpdateViewController : NSViewController +SPU_OBJC_DIRECT_MEMBERS @interface SUInstallUpdateViewController : NSViewController - (instancetype)initWithAppcastItem:(SUAppcastItem *)appcastItem reply:(void (^)(SPUUserUpdateChoice))reply; diff --git a/TestApplication/SUInstallUpdateViewController.m b/TestApplication/SUInstallUpdateViewController.m index ba22b103..b6ecbc46 100644 --- a/TestApplication/SUInstallUpdateViewController.m +++ b/TestApplication/SUInstallUpdateViewController.m @@ -8,30 +8,23 @@ #import "SUInstallUpdateViewController.h" -@interface SUInstallUpdateViewController () - -@property (nonatomic) IBOutlet NSButton *skipUpdatesButton; -@property (nonatomic) IBOutlet NSTextView *textView; -@property (nonatomic, readonly) SUAppcastItem *appcastItem; -@property (nonatomic, nullable) NSAttributedString *preloadedReleaseNotes; -@property (nonatomic, copy) void (^reply)(SPUUserUpdateChoice); - -@end - @implementation SUInstallUpdateViewController - -@synthesize skipUpdatesButton = _skipUpdatesButton; -@synthesize textView = _textView; -@synthesize preloadedReleaseNotes = _preloadedReleaseNotes; -@synthesize appcastItem = _appcastItem; -@synthesize reply = _reply; +{ + void (^_reply)(SPUUserUpdateChoice); + + SUAppcastItem *_appcastItem; + NSAttributedString *_preloadedReleaseNotes; + + IBOutlet NSTextView *_textView; + IBOutlet NSButton *_skipUpdatesButton; +} - (instancetype)initWithAppcastItem:(SUAppcastItem *)appcastItem reply:(void (^)(SPUUserUpdateChoice))reply { self = [super initWithNibName:@"SUInstallUpdateViewController" bundle:nil]; if (self != nil) { _appcastItem = appcastItem; - self.reply = reply; + _reply = [reply copy]; } else { assert(false); } @@ -42,14 +35,14 @@ { [super viewDidLoad]; - [[self.textView enclosingScrollView] setDrawsBackground:NO]; - [self.textView setDrawsBackground:NO]; + [[_textView enclosingScrollView] setDrawsBackground:NO]; + [_textView setDrawsBackground:NO]; - if (self.preloadedReleaseNotes != nil) { - [self displayReleaseNotes:self.preloadedReleaseNotes]; - self.preloadedReleaseNotes = nil; - } else if (self.appcastItem.releaseNotesURL == nil) { - NSString *descriptionHTML = self.appcastItem.itemDescription; + if (_preloadedReleaseNotes != nil) { + [self displayReleaseNotes:_preloadedReleaseNotes]; + _preloadedReleaseNotes = nil; + } else if (_appcastItem.releaseNotesURL == nil) { + NSString *descriptionHTML = _appcastItem.itemDescription; if (descriptionHTML != nil) { NSData *htmlData = [descriptionHTML dataUsingEncoding:NSUTF8StringEncoding]; NSAttributedString *attributedString = [[NSAttributedString alloc] initWithHTML:htmlData documentAttributes:NULL]; @@ -58,22 +51,22 @@ } } -- (void)displayReleaseNotes:(NSAttributedString *)releaseNotes +- (void)displayReleaseNotes:(NSAttributedString *)releaseNotes SPU_OBJC_DIRECT { - if (self.textView == nil) { - self.preloadedReleaseNotes = releaseNotes; + if (_textView == nil) { + _preloadedReleaseNotes = releaseNotes; } else { - [self.textView.textStorage setAttributedString:releaseNotes]; + [_textView.textStorage setAttributedString:releaseNotes]; } } -- (void)displayHTMLReleaseNotes:(NSData *)releaseNotes +- (void)displayHTMLReleaseNotes:(NSData *)releaseNotes SPU_OBJC_DIRECT { NSAttributedString *attributedString = [[NSAttributedString alloc] initWithHTML:releaseNotes documentAttributes:NULL]; [self displayReleaseNotes:attributedString]; } -- (void)displayPlainTextReleaseNotes:(NSData *)releaseNotes encoding:(NSStringEncoding)encoding +- (void)displayPlainTextReleaseNotes:(NSData *)releaseNotes encoding:(NSStringEncoding)encoding SPU_OBJC_DIRECT { NSString *string = [[NSString alloc] initWithData:releaseNotes encoding:encoding]; NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:string attributes:nil]; @@ -105,25 +98,25 @@ - (IBAction)installUpdate:(id)__unused sender { - if (self.reply != nil) { - self.reply(SPUUserUpdateChoiceInstall); - self.reply = nil; + if (_reply != nil) { + _reply(SPUUserUpdateChoiceInstall); + _reply = nil; } } - (IBAction)installUpdateLater:(id)__unused sender { - if (self.reply != nil) { - self.reply(SPUUserUpdateChoiceDismiss); - self.reply = nil; + if (_reply != nil) { + _reply(SPUUserUpdateChoiceDismiss); + _reply = nil; } } - (IBAction)skipUpdate:(id)__unused sender { - if (self.reply != nil) { - self.reply(SPUUserUpdateChoiceSkip); - self.reply = nil; + if (_reply != nil) { + _reply(SPUUserUpdateChoiceSkip); + _reply = nil; } } diff --git a/TestApplication/SUInstallUpdateViewController.xib b/TestApplication/SUInstallUpdateViewController.xib index cfb5947a..78af328e 100644 --- a/TestApplication/SUInstallUpdateViewController.xib +++ b/TestApplication/SUInstallUpdateViewController.xib @@ -1,14 +1,15 @@ -<?xml version="1.0" encoding="UTF-8" standalone="no"?> -<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="9532" systemVersion="15D21" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> +<?xml version="1.0" encoding="UTF-8"?> +<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="21507" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES"> <dependencies> <deployment identifier="macosx"/> - <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="9532"/> + <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="21507"/> + <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> </dependencies> <objects> <customObject id="-2" userLabel="File's Owner" customClass="SUInstallUpdateViewController"> <connections> - <outlet property="skipUpdatesButton" destination="GnO-99-FrA" id="3lg-83-oGn"/> - <outlet property="textView" destination="hvq-rZ-gUG" id="U5Y-SK-7E5"/> + <outlet property="_skipUpdatesButton" destination="GnO-99-FrA" id="WO4-cT-KGm"/> + <outlet property="_textView" destination="hvq-rZ-gUG" id="x7h-XU-cqB"/> <outlet property="view" destination="Hz6-mo-xeY" id="0bl-1N-x8E"/> </connections> </customObject> @@ -20,6 +21,7 @@ <subviews> <button verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="JaG-xU-cSv"> <rect key="frame" x="128" y="6" width="114" height="32"/> + <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <buttonCell key="cell" type="push" title="Install Later" bezelStyle="rounded" alignment="center" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="vGh-C9-cmI"> <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> <font key="font" metaFont="system"/> @@ -33,6 +35,7 @@ Gw </button> <button verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="GnO-99-FrA"> <rect key="frame" x="14" y="6" width="114" height="32"/> + <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <buttonCell key="cell" type="push" title="Skip Update" bezelStyle="rounded" alignment="center" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="Q9S-re-mYe"> <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> <font key="font" metaFont="system"/> @@ -43,34 +46,34 @@ Gw </button> <scrollView fixedFrame="YES" horizontalLineScroll="10" horizontalPageScroll="10" verticalLineScroll="10" verticalPageScroll="10" hasHorizontalScroller="NO" usesPredominantAxisScrolling="NO" translatesAutoresizingMaskIntoConstraints="NO" id="3Cj-JW-f43"> <rect key="frame" x="0.0" y="46" width="370" height="136"/> - <clipView key="contentView" ambiguous="YES" id="CIT-u4-hRg"> + <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> + <clipView key="contentView" drawsBackground="NO" id="CIT-u4-hRg"> <rect key="frame" x="1" y="1" width="368" height="134"/> <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> <subviews> - <textView ambiguous="YES" editable="NO" importsGraphics="NO" findStyle="panel" verticallyResizable="YES" allowsNonContiguousLayout="YES" id="hvq-rZ-gUG"> + <textView editable="NO" importsGraphics="NO" verticallyResizable="YES" findStyle="panel" allowsNonContiguousLayout="YES" id="hvq-rZ-gUG"> <rect key="frame" x="0.0" y="0.0" width="368" height="134"/> <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> - <color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/> + <color key="textColor" name="textColor" catalog="System" colorSpace="catalog"/> + <color key="backgroundColor" name="textBackgroundColor" catalog="System" colorSpace="catalog"/> <size key="minSize" width="368" height="134"/> <size key="maxSize" width="463" height="10000000"/> <color key="insertionPointColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> - <size key="minSize" width="368" height="134"/> - <size key="maxSize" width="463" height="10000000"/> </textView> </subviews> - <color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/> </clipView> - <scroller key="horizontalScroller" hidden="YES" verticalHuggingPriority="750" doubleValue="1" horizontal="YES" id="t2X-nw-Cy5"> + <scroller key="horizontalScroller" hidden="YES" wantsLayer="YES" verticalHuggingPriority="750" doubleValue="1" horizontal="YES" id="t2X-nw-Cy5"> <rect key="frame" x="-100" y="-100" width="87" height="18"/> <autoresizingMask key="autoresizingMask"/> </scroller> - <scroller key="verticalScroller" verticalHuggingPriority="750" horizontal="NO" id="dth-jh-Csr"> + <scroller key="verticalScroller" wantsLayer="YES" verticalHuggingPriority="750" horizontal="NO" id="dth-jh-Csr"> <rect key="frame" x="353" y="1" width="16" height="134"/> <autoresizingMask key="autoresizingMask"/> </scroller> </scrollView> <button verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="cYY-dW-0o8"> <rect key="frame" x="242" y="6" width="114" height="32"/> + <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <buttonCell key="cell" type="push" title="Install Update" bezelStyle="rounded" alignment="center" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="AoI-0t-LLU"> <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> <font key="font" metaFont="system"/> diff --git a/TestApplication/SUPopUpTitlebarUserDriver.h b/TestApplication/SUPopUpTitlebarUserDriver.h index f00602a8..63d4fa3c 100644 --- a/TestApplication/SUPopUpTitlebarUserDriver.h +++ b/TestApplication/SUPopUpTitlebarUserDriver.h @@ -11,7 +11,7 @@ @class NSWindow; -@interface SUPopUpTitlebarUserDriver : NSObject <SPUUserDriver> +SPU_OBJC_DIRECT_MEMBERS @interface SUPopUpTitlebarUserDriver : NSObject <SPUUserDriver> - (instancetype)initWithWindow:(NSWindow *)window; diff --git a/TestApplication/SUPopUpTitlebarUserDriver.m b/TestApplication/SUPopUpTitlebarUserDriver.m index 9942736e..d703adcb 100644 --- a/TestApplication/SUPopUpTitlebarUserDriver.m +++ b/TestApplication/SUPopUpTitlebarUserDriver.m @@ -10,29 +10,20 @@ #import "SUInstallUpdateViewController.h" #import <AppKit/AppKit.h> -@interface SUPopUpTitlebarUserDriver() - -@property (nonatomic, readonly) NSWindow *window; -@property (nonatomic, nullable) SUInstallUpdateViewController *installUpdateViewController; -@property (nonatomic) NSTitlebarAccessoryViewController *accessoryViewController; -@property (nonatomic) BOOL addedAccessory; -@property (nonatomic) NSButton *updateButton; -@property (nonatomic, copy) void (^updateButtonAction)(NSButton *); -@property (nonatomic) uint64_t expectedContentLength; -@property (nonatomic) uint64_t contentLengthDownloaded; - -@end - @implementation SUPopUpTitlebarUserDriver - -@synthesize window = _window; -@synthesize installUpdateViewController = _installUpdateViewController; -@synthesize accessoryViewController = _accessoryViewController; -@synthesize addedAccessory = _addedAccessory; -@synthesize updateButton = _updateButton; -@synthesize updateButtonAction = _updateButtonAction; -@synthesize expectedContentLength = _expectedContentLength; -@synthesize contentLengthDownloaded = _contentLengthDownloaded; +{ + void (^_updateButtonAction)(NSButton *); + + NSWindow *_window; + SUInstallUpdateViewController *_installUpdateViewController; + NSTitlebarAccessoryViewController *_accessoryViewController; + NSButton *_updateButton; + + uint64_t _expectedContentLength; + uint64_t _contentLengthDownloaded; + + BOOL _addedAccessory; +} - (instancetype)initWithWindow:(NSWindow *)window { @@ -43,58 +34,58 @@ return self; } -- (void)addUpdateButtonWithTitle:(NSString *)title +- (void)addUpdateButtonWithTitle:(NSString *)title SPU_OBJC_DIRECT { [self addUpdateButtonWithTitle:title action:nil]; } -- (void)addUpdateButtonWithTitle:(NSString *)title action:(void (^)(NSButton *button))action +- (void)addUpdateButtonWithTitle:(NSString *)title action:(void (^)(NSButton *button))action SPU_OBJC_DIRECT { - if (self.updateButton == nil) { + if (_updateButton == nil) { NSButton *updateButton = [[NSButton alloc] initWithFrame:NSMakeRect(0, 0, 160, 100)]; updateButton.title = title; updateButton.bezelStyle = NSBezelStyleRecessed; - self.updateButton = updateButton; + _updateButton = updateButton; } else { - self.updateButton.title = title; + _updateButton.title = title; } if (action != nil) { - self.updateButton.target = self; - self.updateButton.action = @selector(updateButtonAction:); - self.updateButtonAction = action; - self.updateButton.enabled = YES; + _updateButton.target = self; + _updateButton.action = @selector(updateButtonAction:); + _updateButtonAction = action; + _updateButton.enabled = YES; } else { - self.updateButton.enabled = NO; - self.updateButton.target = nil; - self.updateButtonAction = nil; + _updateButton.enabled = NO; + _updateButton.target = nil; + _updateButtonAction = nil; } - if (self.accessoryViewController == nil) { - self.accessoryViewController = [[NSTitlebarAccessoryViewController alloc] init]; - self.accessoryViewController.layoutAttribute = NSLayoutAttributeRight; - self.accessoryViewController.view = self.updateButton; + if (_accessoryViewController == nil) { + _accessoryViewController = [[NSTitlebarAccessoryViewController alloc] init]; + _accessoryViewController.layoutAttribute = NSLayoutAttributeRight; + _accessoryViewController.view = _updateButton; } - if (!self.addedAccessory) { - [self.window addTitlebarAccessoryViewController:self.accessoryViewController]; - self.addedAccessory = YES; + if (!_addedAccessory) { + [_window addTitlebarAccessoryViewController:_accessoryViewController]; + _addedAccessory = YES; } } - (void)updateButtonAction:(NSButton *)sender { - if (self.updateButtonAction != nil) { - self.updateButtonAction(sender); + if (_updateButtonAction != nil) { + _updateButtonAction(sender); } } -- (void)removeUpdateButton +- (void)removeUpdateButton SPU_OBJC_DIRECT { - [self.accessoryViewController removeFromParentViewController]; - self.addedAccessory = NO; - self.updateButtonAction = nil; + [_accessoryViewController removeFromParentViewController]; + _addedAccessory = NO; + _updateButtonAction = nil; } #pragma mark Update Permission @@ -113,7 +104,7 @@ NSPopover *popover = [[NSPopover alloc] init]; popover.behavior = NSPopoverBehaviorTransient; - __weak SUPopUpTitlebarUserDriver *weakSelf = self; + __weak __typeof__(self) weakSelf = self; __block NSButton *actionButton = nil; SUInstallUpdateViewController *viewController = [[SUInstallUpdateViewController alloc] initWithAppcastItem:appcastItem reply:^(SPUUserUpdateChoice choice) { @@ -122,10 +113,13 @@ [popover close]; actionButton.enabled = NO; - weakSelf.installUpdateViewController = nil; + __typeof__(self) strongSelf = weakSelf; + if (strongSelf != nil) { + strongSelf->_installUpdateViewController = nil; + } }]; - self.installUpdateViewController = viewController; + _installUpdateViewController = viewController; [self addUpdateButtonWithTitle:@"Update Available" action:^(NSButton *button) { actionButton = button; @@ -151,7 +145,7 @@ - (void)showUpdateReleaseNotesWithDownloadData:(SPUDownloadData *)downloadData { - [self.installUpdateViewController showReleaseNotesWithDownloadData:downloadData]; + [_installUpdateViewController showReleaseNotesWithDownloadData:downloadData]; } - (void)showUpdateReleaseNotesFailedToDownloadWithError:(NSError *)__unused error @@ -160,14 +154,14 @@ - (void)showUpdateInFocus { - [self.window makeKeyAndOrderFront:nil]; + [_window makeKeyAndOrderFront:nil]; - if (self.updateButton.enabled) { + if (_updateButton.enabled) { // Not the proper way to do things but ignoring warnings in Test App. #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wobjc-messaging-id" #pragma clang diagnostic ignored "-Warc-performSelector-leaks" - [self.updateButton.target performSelector:self.updateButton.action withObject:self.updateButton]; + [_updateButton.target performSelector:_updateButton.action withObject:_updateButton]; #pragma clang diagnostic pop } } @@ -222,21 +216,21 @@ - (void)showDownloadDidReceiveExpectedContentLength:(uint64_t)expectedContentLength { [self addUpdateButtonWithTitle:@"Downloading…"]; - self.contentLengthDownloaded = 0; - self.expectedContentLength = expectedContentLength; + _contentLengthDownloaded = 0; + _expectedContentLength = expectedContentLength; } - (void)showDownloadDidReceiveDataOfLength:(uint64_t)length { - self.contentLengthDownloaded += length; + _contentLengthDownloaded += length; // In case our expected content length was incorrect - if (self.contentLengthDownloaded > self.expectedContentLength) { - self.expectedContentLength = self.contentLengthDownloaded; + if (_contentLengthDownloaded > _expectedContentLength) { + _expectedContentLength = _contentLengthDownloaded; } - if (self.expectedContentLength > 0) { - double progress = (double)self.contentLengthDownloaded / self.expectedContentLength; + if (_expectedContentLength > 0) { + double progress = (double)_contentLengthDownloaded / _expectedContentLength; [self addUpdateButtonWithTitle:[NSString stringWithFormat:@"Downloading (%0.0f%%)", progress * 100] action:nil]; } } diff --git a/TestApplication/SUTestApplicationDelegate.m b/TestApplication/SUTestApplicationDelegate.m index dd719796..1bf3d5e9 100644 --- a/TestApplication/SUTestApplicationDelegate.m +++ b/TestApplication/SUTestApplicationDelegate.m @@ -17,20 +17,15 @@ #import "SUBinaryDeltaCreate.h" @interface SUTestApplicationDelegate () <NSMenuItemValidation, SPUUpdaterDelegate> - -@property (nonatomic) SPUUpdater *updater; -@property (nonatomic) SUUpdateSettingsWindowController *updateSettingsWindowController; -@property (nonatomic) SUTestWebServer *webServer; -@property (nonatomic, copy) NSString *testMode; - @end @implementation SUTestApplicationDelegate - -@synthesize updater = _updater; -@synthesize updateSettingsWindowController = _updateSettingsWindowController; -@synthesize webServer = _webServer; -@synthesize testMode = _testMode; +{ + SPUUpdater *_updater; + SUUpdateSettingsWindowController *_updateSettingsWindowController; + SUTestWebServer *_webServer; + NSString *_testMode; +} - (void)applicationDidFinishLaunching:(NSNotification * __unused)notification { @@ -44,7 +39,7 @@ testMode = testModeEnv; } - self.testMode = testMode; + _testMode = testMode; // Check if we are already up to date NSString *mainBundleVersion = (NSString *)[mainBundle objectForInfoDictionaryKey:(__bridge NSString *)kCFBundleVersionKey]; @@ -283,13 +278,13 @@ NSLog(@"Failed to create the web server"); abort(); } - self.webServer = webServer; + self->_webServer = webServer; // Set up updater and the updater settings window { - self.updateSettingsWindowController = [[SUUpdateSettingsWindowController alloc] init]; + self->_updateSettingsWindowController = [[SUUpdateSettingsWindowController alloc] init]; - NSWindow *settingsWindow = self.updateSettingsWindowController.window; + NSWindow *settingsWindow = self->_updateSettingsWindowController.window; NSBundle *hostBundle = [NSBundle mainBundle]; NSBundle *applicationBundle = hostBundle; @@ -307,8 +302,8 @@ SPUUpdater *updater = [[SPUUpdater alloc] initWithHostBundle:hostBundle applicationBundle:applicationBundle userDriver:userDriver delegate:self]; - self.updater = updater; - self.updateSettingsWindowController.updater = updater; + self->_updater = updater; + self->_updateSettingsWindowController.updater = updater; NSError *updaterError = nil; if (![updater startUpdater:&updaterError]) { @@ -321,7 +316,7 @@ [alert runModal]; } - [self.updateSettingsWindowController showWindow:nil]; + [self->_updateSettingsWindowController showWindow:nil]; } }); }]; @@ -329,16 +324,16 @@ - (NSSet<NSString *> *)allowedChannelsForUpdater:(SPUUpdater *)updater { - if ([self.testMode isEqualToString:@"DELTA"]) { + if ([_testMode isEqualToString:@"DELTA"]) { return [NSSet setWithObject:@"delta"]; - } else if ([self.testMode isEqualToString:@"AUTOMATIC"]) { + } else if ([_testMode isEqualToString:@"AUTOMATIC"]) { return [NSSet setWithObject:@"automatic"]; } else { return [NSSet set]; } } -- (void)signApplicationIfRequiredAtPath:(NSString *)applicationPath completion:(void (^)(void))completionBlock +- (void)signApplicationIfRequiredAtPath:(NSString *)applicationPath completion:(void (^)(void))completionBlock SPU_OBJC_DIRECT { // This is unfortunately necessary for testing sandboxing NSXPCConnection *codeSignConnection = [[NSXPCConnection alloc] initWithServiceName:@"org.sparkle-project.TestAppHelper"]; @@ -355,18 +350,18 @@ - (void)applicationWillTerminate:(NSNotification * __unused)notification { - [self.webServer close]; + [_webServer close]; } - (IBAction)checkForUpdates:(id __unused)sender { - [self.updater checkForUpdates]; + [_updater checkForUpdates]; } - (BOOL)validateMenuItem:(NSMenuItem *)menuItem { if (menuItem.action == @selector(checkForUpdates:)) { - return self.updater.canCheckForUpdates; + return _updater.canCheckForUpdates; } return YES; } diff --git a/TestApplication/SUTestWebServer.h b/TestApplication/SUTestWebServer.h index 2c61c565..7404704b 100644 --- a/TestApplication/SUTestWebServer.h +++ b/TestApplication/SUTestWebServer.h @@ -8,7 +8,7 @@ #import <Foundation/Foundation.h> -@interface SUTestWebServer : NSObject +SPU_OBJC_DIRECT_MEMBERS @interface SUTestWebServer : NSObject - (instancetype)initWithPort:(int)port workingDirectory:(NSString*)workingDirectory; diff --git a/TestApplication/SUTestWebServer.m b/TestApplication/SUTestWebServer.m index 47a4ab09..fb33e756 100644 --- a/TestApplication/SUTestWebServer.m +++ b/TestApplication/SUTestWebServer.m @@ -18,26 +18,21 @@ @end @interface SUTestWebServerConnection : NSObject <NSStreamDelegate> - -@property (nonatomic) NSString* workingDirectory; -@property (nonatomic, weak) id<SUTestWebServerConnectionDelegate> delegate; -@property (nonatomic) NSInputStream *inputStream; -@property (nonatomic) NSOutputStream *outputStream; -@property (nonatomic) NSData *dataToWrite; -@property (nonatomic) NSInteger numBytesToWrite; - @end @implementation SUTestWebServerConnection +{ + NSString* _workingDirectory; + NSInputStream *_inputStream; + NSOutputStream *_outputStream; + NSData *_dataToWrite; + NSInteger _numBytesToWrite; + + __weak id<SUTestWebServerConnectionDelegate> _delegate; +} -@synthesize workingDirectory = _workingDirectory; -@synthesize delegate = _delegate; -@synthesize inputStream = _inputStream; -@synthesize outputStream = _outputStream; -@synthesize dataToWrite = _dataToWrite; -@synthesize numBytesToWrite = _numBytesToWrite; - -- (instancetype)initWithNativeHandle:(CFSocketNativeHandle)handle workingDirectory:(NSString*)workingDirectory delegate:(id<SUTestWebServerConnectionDelegate>)delegate { +- (instancetype)initWithNativeHandle:(CFSocketNativeHandle)handle workingDirectory:(NSString*)workingDirectory delegate:(id<SUTestWebServerConnectionDelegate>)delegate SPU_OBJC_DIRECT +{ self = [super init]; assert(self != nil); @@ -66,9 +61,10 @@ return self; } -- (void)close { - NSInputStream *inputStream = self.inputStream; - NSOutputStream *outputStream = self.outputStream; +- (void)close SPU_OBJC_DIRECT +{ + NSInputStream *inputStream = _inputStream; + NSOutputStream *outputStream = _outputStream; if (inputStream == nil) { assert(outputStream == nil); return; @@ -77,19 +73,20 @@ [outputStream close]; [inputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [outputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; - self.inputStream = nil; - self.outputStream = nil; - [self.delegate connectionDidClose:self]; + _inputStream = nil; + _outputStream = nil; + [_delegate connectionDidClose:self]; } -- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode { +- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode +{ if (eventCode == NSStreamEventEndEncountered) { [self close]; return; } - if (aStream == self.inputStream && eventCode == NSStreamEventHasBytesAvailable) { + if (aStream == _inputStream && eventCode == NSStreamEventHasBytesAvailable) { uint8_t buffer[8096]; - const NSInteger numBytes = [self.inputStream read:buffer maxLength:sizeof(buffer)]; + const NSInteger numBytes = [_inputStream read:buffer maxLength:sizeof(buffer)]; if (numBytes > 0) { NSString *request = [[NSString alloc] initWithBytes:buffer length:(NSUInteger)numBytes encoding:NSUTF8StringEncoding]; NSArray *lines = [request componentsSeparatedByString:@"\r\n"]; @@ -99,7 +96,7 @@ if ([(NSString *)[parts objectAtIndex:0] isEqualToString:@"GET"]) { // Use NSURL to strip out query parameters NSString *path = [NSURL URLWithString:[parts objectAtIndex:1] relativeToURL:nil].path; - NSString *filePath = [self.workingDirectory stringByAppendingString:path]; + NSString *filePath = [_workingDirectory stringByAppendingString:path]; BOOL isDir = NO; if (![[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:&isDir] || isDir) { NSLog(@"%@ - 404", requestLine); @@ -113,17 +110,19 @@ [self write404]; } } - } else if (aStream == self.outputStream && eventCode == NSStreamEventHasSpaceAvailable && self.dataToWrite != nil) { + } else if (aStream == _outputStream && eventCode == NSStreamEventHasSpaceAvailable && _dataToWrite != nil) { [self checkIfCanWriteNow]; } } -- (void)write404 { +- (void)write404 SPU_OBJC_DIRECT +{ NSString *body = @"<html><head><title>404 Not Found

Not Found

"; [self write:[body dataUsingEncoding:NSUTF8StringEncoding] status:NO]; } -- (void)write:(NSData*)body status:(BOOL)status { +- (void)write:(NSData*)body status:(BOOL)status SPU_OBJC_DIRECT +{ NSString *state = status ? @"200 OK" : @"404 Not Found"; NSString *header = [NSString stringWithFormat:@"HTTP/1.0 %@\r\nContent-Length: %lu\r\n\r\n", state, body.length]; NSMutableData *response = [[header dataUsingEncoding:NSUTF8StringEncoding] mutableCopy]; @@ -131,37 +130,40 @@ [self queueWrite:response]; } -- (void)queueWrite:(NSData*)data { - assert(self.dataToWrite == nil); +- (void)queueWrite:(NSData*)data SPU_OBJC_DIRECT +{ + assert(_dataToWrite == nil); assert(data != nil); assert(data.length > 0); - self.dataToWrite = data; - self.numBytesToWrite = (NSInteger)data.length; + _dataToWrite = data; + _numBytesToWrite = (NSInteger)data.length; [self checkIfCanWriteNow]; } -- (void)checkIfCanWriteNow { - assert(self.dataToWrite != nil); - if (self.numBytesToWrite == 0) { +- (void)checkIfCanWriteNow SPU_OBJC_DIRECT +{ + assert(_dataToWrite != nil); + if (_numBytesToWrite == 0) { // nothing more to write, we're done. - self.dataToWrite = nil; - self.numBytesToWrite = -1; - } else if (self.outputStream.hasSpaceAvailable) { + _dataToWrite = nil; + _numBytesToWrite = -1; + } else if (_outputStream.hasSpaceAvailable) { [self writeNow]; } // otherwise wait for space available event } -- (void)writeNow { - assert(self.outputStream != nil); - assert(self.outputStream.hasSpaceAvailable); - assert(self.dataToWrite != nil); - NSData *dataToWrite = self.dataToWrite; - const uint8_t *bytesOffset = (const uint8_t*)dataToWrite.bytes + ((NSInteger)dataToWrite.length - self.numBytesToWrite); - const NSInteger bytesWritten = [self.outputStream write:bytesOffset maxLength:(NSUInteger)self.numBytesToWrite]; +- (void)writeNow SPU_OBJC_DIRECT +{ + assert(_outputStream != nil); + assert(_outputStream.hasSpaceAvailable); + assert(_dataToWrite != nil); + NSData *dataToWrite = _dataToWrite; + const uint8_t *bytesOffset = (const uint8_t*)dataToWrite.bytes + ((NSInteger)dataToWrite.length - _numBytesToWrite); + const NSInteger bytesWritten = [_outputStream write:bytesOffset maxLength:(NSUInteger)_numBytesToWrite]; if (bytesWritten > 0) { - self.numBytesToWrite = self.numBytesToWrite - bytesWritten; - assert(self.numBytesToWrite >= 0); + _numBytesToWrite = _numBytesToWrite - bytesWritten; + assert(_numBytesToWrite >= 0); // wait for next space available event to write more } else { NSLog(@"Error: bytes written = %ld (%@)", bytesWritten, [NSString stringWithUTF8String:strerror(errno)]); @@ -170,7 +172,7 @@ @end -@interface SUTestWebServer () { +SPU_OBJC_DIRECT_MEMBERS @interface SUTestWebServer () { CFSocketRef _socket; } @@ -181,7 +183,8 @@ @end -static void connectCallback(CFSocketRef __unused s, CFSocketCallBackType type, CFDataRef __unused address, const void *data, void *info) { +static void connectCallback(CFSocketRef __unused s, CFSocketCallBackType type, CFDataRef __unused address, const void *data, void *info) +{ if (type == kCFSocketAcceptCallBack) { assert(data != NULL); assert(info != NULL); @@ -196,7 +199,8 @@ static void connectCallback(CFSocketRef __unused s, CFSocketCallBackType type, C @synthesize connections = _connections; @synthesize workingDirectory = _workingDirectory; -- (instancetype)initWithPort:(int)port workingDirectory:(NSString*)workingDirectory { +- (instancetype)initWithPort:(int)port workingDirectory:(NSString*)workingDirectory +{ self = [super init]; assert(self != nil); @@ -231,33 +235,33 @@ static void connectCallback(CFSocketRef __unused s, CFSocketCallBackType type, C return self; } -- (void)connectionDidClose:(SUTestWebServerConnection *)sender { - assert(self.connections != nil); - assert([self.connections containsObject:sender]); - [self.connections removeObject:sender]; +- (void)connectionDidClose:(SUTestWebServerConnection *)sender +{ + assert(_connections != nil); + assert([_connections containsObject:sender]); + [_connections removeObject:sender]; } -- (void)accept:(CFSocketNativeHandle)address { - SUTestWebServerConnection *conn = [[SUTestWebServerConnection alloc] initWithNativeHandle:address workingDirectory:self.workingDirectory delegate:self]; +- (void)accept:(CFSocketNativeHandle)address +{ + SUTestWebServerConnection *conn = [[SUTestWebServerConnection alloc] initWithNativeHandle:address workingDirectory:_workingDirectory delegate:self]; assert(conn != nil); if (conn) { - assert(self.connections != nil); - [self.connections addObject:conn]; + assert(_connections != nil); + [_connections addObject:conn]; } } -- (void)close { - for (SUTestWebServerConnection *conn in self.connections) { +- (void)close +{ + for (SUTestWebServerConnection *conn in _connections) { [conn close]; } -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdirect-ivar-access" if (_socket) { CFSocketInvalidate(_socket); CFRelease(_socket); _socket = NULL; } -#pragma clang diagnostic pop } @end diff --git a/Tests/SUAppcastTest.swift b/Tests/SUAppcastTest.swift index 07dac6c4..be98819a 100644 --- a/Tests/SUAppcastTest.swift +++ b/Tests/SUAppcastTest.swift @@ -7,7 +7,6 @@ // import XCTest -import Sparkle class SUAppcastTest: XCTestCase { diff --git a/Tests/SUBinaryDeltaTest.m b/Tests/SUBinaryDeltaTest.m index a4591b22..8f616bb3 100644 --- a/Tests/SUBinaryDeltaTest.m +++ b/Tests/SUBinaryDeltaTest.m @@ -96,7 +96,12 @@ typedef void (^SUDeltaHandler)(NSFileManager *fileManager, NSString *sourceDirec - (BOOL)createAndApplyPatchWithBeforeDiffHandler:(SUDeltaHandler)beforeDiffHandler afterDiffHandler:(SUDeltaHandler)afterDiffHandler afterPatchHandler:(SUDeltaHandler)afterPatchHandler { - return [self createAndApplyPatchWithBeforeDiffHandler:beforeDiffHandler afterDiffHandler:afterDiffHandler afterPatchHandler:afterPatchHandler testingVersion2Delta:YES]; +#if SPARKLE_BUILD_LEGACY_DELTA_SUPPORT + BOOL testingVersion2Delta = YES; +#else + BOOL testingVersion2Delta = NO; +#endif + return [self createAndApplyPatchWithBeforeDiffHandler:beforeDiffHandler afterDiffHandler:afterDiffHandler afterPatchHandler:afterPatchHandler testingVersion2Delta:testingVersion2Delta]; } - (BOOL)createAndApplyPatchWithBeforeDiffHandler:(SUDeltaHandler)beforeDiffHandler afterDiffHandler:(SUDeltaHandler)afterDiffHandler afterPatchHandler:(SUDeltaHandler)afterPatchHandler testingVersion2Delta:(BOOL)testingVersion2Delta @@ -105,13 +110,22 @@ typedef void (^SUDeltaHandler)(NSFileManager *fileManager, NSString *sourceDirec BOOL version3DeltaFormatWithLZMASuccess = [self createAndApplyPatchUsingVersion:SUBinaryDeltaMajorVersion3 compressionMode:SPUDeltaCompressionModeLZMA beforeDiffHandler:beforeDiffHandler afterDiffHandler:afterDiffHandler afterPatchHandler:afterPatchHandler]; +#if SPARKLE_BUILD_BZIP2_DELTA_SUPPORT BOOL version3DeltaFormatWithBZIP2Success = [self createAndApplyPatchUsingVersion:SUBinaryDeltaMajorVersion3 compressionMode:SPUDeltaCompressionModeBzip2 beforeDiffHandler:beforeDiffHandler afterDiffHandler:afterDiffHandler afterPatchHandler:afterPatchHandler]; +#endif BOOL version3DeltaFormatWithZLIBSuccess = [self createAndApplyPatchUsingVersion:SUBinaryDeltaMajorVersion3 compressionMode:SPUDeltaCompressionModeZLIB beforeDiffHandler:beforeDiffHandler afterDiffHandler:afterDiffHandler afterPatchHandler:afterPatchHandler]; BOOL version2FormatSuccess = !testingVersion2Delta || [self createAndApplyPatchUsingVersion:SUBinaryDeltaMajorVersion2 compressionMode:SPUDeltaCompressionModeDefault beforeDiffHandler:beforeDiffHandler afterDiffHandler:afterDiffHandler afterPatchHandler:afterPatchHandler]; - return (version3DeltaFormatWithLZMASuccess && version3DeltaFormatWithBZIP2Success && version3DeltaFormatWithZLIBSuccess && version2FormatSuccess); + return ( + version3DeltaFormatWithLZMASuccess && +#if SPARKLE_BUILD_BZIP2_DELTA_SUPPORT + version3DeltaFormatWithBZIP2Success && +#endif + version3DeltaFormatWithZLIBSuccess && + version2FormatSuccess + ); } - (void)createAndApplyPatchWithHandler:(SUDeltaHandler)handler diff --git a/Tests/SUCodeSigningVerifierTest.m b/Tests/SUCodeSigningVerifierTest.m index 82700375..ce6e0b43 100644 --- a/Tests/SUCodeSigningVerifierTest.m +++ b/Tests/SUCodeSigningVerifierTest.m @@ -20,20 +20,15 @@ #endif @interface SUCodeSigningVerifierTest : XCTestCase - -@property (copy) NSURL *notSignedAppURL; -@property (copy) NSURL *validSignedAppURL; -@property (copy) NSURL *invalidSignedAppURL; -@property (copy) NSURL *calculatorCopyURL; - @end @implementation SUCodeSigningVerifierTest - -@synthesize notSignedAppURL = _notSignedAppURL; -@synthesize validSignedAppURL = _validSignedAppURL; -@synthesize invalidSignedAppURL = _invalidSignedAppURL; -@synthesize calculatorCopyURL = _calculatorCopyURL; +{ + NSURL *_notSignedAppURL; + NSURL *_validSignedAppURL; + NSURL *_invalidSignedAppURL; + NSURL *_calculatorCopyURL; +} + (NSString *)calculatorApplicationPath { @@ -62,7 +57,7 @@ NSError *error = nil; if ([[NSFileManager defaultManager] createDirectoryAtURL:tempDir withIntermediateDirectories:YES attributes:nil error:&error]) { if ([self unzip:zippedAppURL toPath:tempDir.path]) { - self.notSignedAppURL = [tempDir URLByAppendingPathComponent:@"SparkleTestCodeSignApp.app"]; + _notSignedAppURL = [tempDir URLByAppendingPathComponent:@"SparkleTestCodeSignApp.app"]; [self setupValidSignedApp]; [self setupCalculatorCopy]; [self setupInvalidSignedApp]; @@ -80,8 +75,8 @@ { [super tearDown]; - if (self.notSignedAppURL) { - NSURL *tempDir = [self.notSignedAppURL URLByDeletingLastPathComponent]; + if (_notSignedAppURL != nil) { + NSURL *tempDir = [_notSignedAppURL URLByDeletingLastPathComponent]; [[NSFileManager defaultManager] removeItemAtURL:tempDir error:nil]; } } @@ -89,24 +84,24 @@ - (void)setupValidSignedApp { NSError *error = nil; - NSURL *tempDir = [self.notSignedAppURL URLByDeletingLastPathComponent]; + NSURL *tempDir = [_notSignedAppURL URLByDeletingLastPathComponent]; NSURL *signedAndValid = [tempDir URLByAppendingPathComponent:@"valid-signed.app"]; [[NSFileManager defaultManager] removeItemAtURL:signedAndValid error:NULL]; - if (![[NSFileManager defaultManager] copyItemAtURL:self.notSignedAppURL toURL:signedAndValid error:&error]) { - XCTFail("Failed to copy %@ to %@ with error: %@", self.notSignedAppURL, signedAndValid, error); + if (![[NSFileManager defaultManager] copyItemAtURL:_notSignedAppURL toURL:signedAndValid error:&error]) { + XCTFail("Failed to copy %@ to %@ with error: %@", _notSignedAppURL, signedAndValid, error); } - self.validSignedAppURL = signedAndValid; + _validSignedAppURL = signedAndValid; - if (![self codesignAppURL:self.validSignedAppURL]) { - XCTFail(@"Failed to codesign %@", self.validSignedAppURL); + if (![self codesignAppURL:_validSignedAppURL]) { + XCTFail(@"Failed to codesign %@", _validSignedAppURL); } } - (void)setupCalculatorCopy { - NSURL *tempDir = [self.notSignedAppURL URLByDeletingLastPathComponent]; + NSURL *tempDir = [_notSignedAppURL URLByDeletingLastPathComponent]; NSURL *calculatorCopy = [tempDir URLByAppendingPathComponent:@"calc.app"]; [[NSFileManager defaultManager] removeItemAtURL:calculatorCopy error:NULL]; @@ -132,30 +127,30 @@ XCTFail(@"Failed to remove file in calculator copy with error: %@", removeError); } - self.calculatorCopyURL = calculatorCopy; + _calculatorCopyURL = calculatorCopy; } - (void)setupInvalidSignedApp { NSError *error = nil; - NSURL *tempDir = [self.notSignedAppURL URLByDeletingLastPathComponent]; + NSURL *tempDir = [_notSignedAppURL URLByDeletingLastPathComponent]; NSURL *signedAndInvalid = [tempDir URLByAppendingPathComponent:@"invalid-signed.app"]; [[NSFileManager defaultManager] removeItemAtURL:signedAndInvalid error:NULL]; - if ([[NSFileManager defaultManager] copyItemAtURL:self.notSignedAppURL toURL:signedAndInvalid error:&error]) { - self.invalidSignedAppURL = signedAndInvalid; - if ([self codesignAppURL:self.invalidSignedAppURL]) { - NSURL *fileInAppBundleToRemove = [self.invalidSignedAppURL URLByAppendingPathComponent:@"Contents/Resources/test_app_only_dsa_pub.pem"]; + if ([[NSFileManager defaultManager] copyItemAtURL:_notSignedAppURL toURL:signedAndInvalid error:&error]) { + _invalidSignedAppURL = signedAndInvalid; + if ([self codesignAppURL:_invalidSignedAppURL]) { + NSURL *fileInAppBundleToRemove = [_invalidSignedAppURL URLByAppendingPathComponent:@"Contents/Resources/test_app_only_dsa_pub.pem"]; if (![[NSFileManager defaultManager] removeItemAtURL:fileInAppBundleToRemove error:&error]) { NSLog(@"Failed to remove %@ with error %@", fileInAppBundleToRemove, error); } } else { - NSLog(@"Failed to codesign %@", self.invalidSignedAppURL); + NSLog(@"Failed to codesign %@", _invalidSignedAppURL); } } else { - NSLog(@"Failed to copy %@ to %@ with error %@", self.notSignedAppURL, signedAndInvalid, error); + NSLog(@"Failed to copy %@ to %@ with error %@", _notSignedAppURL, signedAndInvalid, error); } } @@ -187,19 +182,19 @@ - (void)testUnsignedApp { - XCTAssertFalse([SUCodeSigningVerifier bundleAtURLIsCodeSigned:self.notSignedAppURL], @"App not expected to be code signed"); + XCTAssertFalse([SUCodeSigningVerifier bundleAtURLIsCodeSigned:_notSignedAppURL], @"App not expected to be code signed"); NSError *error = nil; - XCTAssertFalse([SUCodeSigningVerifier codeSignatureIsValidAtBundleURL:self.notSignedAppURL error:&error], @"signature should not be valid as it's not code signed"); + XCTAssertFalse([SUCodeSigningVerifier codeSignatureIsValidAtBundleURL:_notSignedAppURL error:&error], @"signature should not be valid as it's not code signed"); XCTAssertNotNil(error, @"error should not be nil"); } - (void)testValidSignedApp { - XCTAssertTrue([SUCodeSigningVerifier bundleAtURLIsCodeSigned:self.validSignedAppURL], @"App expected to be code signed"); + XCTAssertTrue([SUCodeSigningVerifier bundleAtURLIsCodeSigned:_validSignedAppURL], @"App expected to be code signed"); NSError *error = nil; - XCTAssertTrue([SUCodeSigningVerifier codeSignatureIsValidAtBundleURL:self.validSignedAppURL error:&error], @"signature should be valid"); + XCTAssertTrue([SUCodeSigningVerifier codeSignatureIsValidAtBundleURL:_validSignedAppURL error:&error], @"signature should be valid"); XCTAssertNil(error, @"error should be nil"); } @@ -229,7 +224,7 @@ // We can't test our own app because matching with ad-hoc signed apps understandably does not succeed NSError *error = nil; NSURL *appPath = [NSURL fileURLWithPath:calculatorPath]; - XCTAssertTrue([SUCodeSigningVerifier codeSignatureAtBundleURL:appPath matchesSignatureAtBundleURL:self.calculatorCopyURL error:&error], @"The calculator app is expected to have matching identity signature to its altered copy"); + XCTAssertTrue([SUCodeSigningVerifier codeSignatureAtBundleURL:appPath matchesSignatureAtBundleURL:_calculatorCopyURL error:&error], @"The calculator app is expected to have matching identity signature to its altered copy"); } - (void)testInvalidMatching @@ -237,15 +232,15 @@ NSString *calculatorPath = [SUCodeSigningVerifierTest calculatorApplicationPath]; NSURL *appPath = [NSURL fileURLWithPath:calculatorPath]; NSError *error = nil; - XCTAssertFalse([SUCodeSigningVerifier codeSignatureAtBundleURL:appPath matchesSignatureAtBundleURL:self.validSignedAppURL error:&error], @"Calculator app bundle expected to have different signature than our valid signed app"); + XCTAssertFalse([SUCodeSigningVerifier codeSignatureAtBundleURL:appPath matchesSignatureAtBundleURL:_validSignedAppURL error:&error], @"Calculator app bundle expected to have different signature than our valid signed app"); } - (void)testInvalidSignedApp { - XCTAssertTrue([SUCodeSigningVerifier bundleAtURLIsCodeSigned:self.invalidSignedAppURL], @"App expected to be code signed, but signature is invalid"); + XCTAssertTrue([SUCodeSigningVerifier bundleAtURLIsCodeSigned:_invalidSignedAppURL], @"App expected to be code signed, but signature is invalid"); NSError *error = nil; - XCTAssertFalse([SUCodeSigningVerifier codeSignatureIsValidAtBundleURL:self.invalidSignedAppURL error:&error], @"signature should not be valid"); + XCTAssertFalse([SUCodeSigningVerifier codeSignatureIsValidAtBundleURL:_invalidSignedAppURL error:&error], @"signature should not be valid"); XCTAssertNotNil(error, @"error should not be nil"); } diff --git a/Tests/SUInstallerTest.m b/Tests/SUInstallerTest.m index deaa9c29..9c953008 100644 --- a/Tests/SUInstallerTest.m +++ b/Tests/SUInstallerTest.m @@ -32,7 +32,7 @@ [super tearDown]; } -#if __clang_major__ >= 6 +#if SPARKLE_BUILD_PACKAGE_SUPPORT - (void)testInstallIfRoot { uid_t uid = getuid(); diff --git a/Tests/SUSignatureVerifierTest.m b/Tests/SUSignatureVerifierTest.m index c2a03021..f0465a83 100644 --- a/Tests/SUSignatureVerifierTest.m +++ b/Tests/SUSignatureVerifierTest.m @@ -12,66 +12,71 @@ #import "SUSignatures.h" @interface SUSignatureVerifierTest : XCTestCase -@property NSString *testFile, *pubDSAKeyFile, *pubEdKey; @end @implementation SUSignatureVerifierTest -@synthesize testFile, pubDSAKeyFile, pubEdKey; +{ + NSString *_testFile; + NSString *_pubDSAKeyFile; + NSString *_pubEdKey; +} - (void)setUp { [super setUp]; - self.testFile = [[NSBundle bundleForClass:[self class]] pathForResource:@"signed-test-file" ofType:@"txt"]; - self.pubDSAKeyFile = [[NSBundle bundleForClass:[self class]] pathForResource:@"test-pubkey" ofType:@"pem"]; - self.pubEdKey = @"rhHib+w769W2/6/t+oM1ZxgjBB93BfBKMLO0Qo1etQs="; + _testFile = [[NSBundle bundleForClass:[self class]] pathForResource:@"signed-test-file" ofType:@"txt"]; + _pubDSAKeyFile = [[NSBundle bundleForClass:[self class]] pathForResource:@"test-pubkey" ofType:@"pem"]; + _pubEdKey = @"rhHib+w769W2/6/t+oM1ZxgjBB93BfBKMLO0Qo1etQs="; } +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT - (void)testVerifyFileAtPathUsingDSA { - NSString *pubKey = [NSString stringWithContentsOfFile:self.pubDSAKeyFile encoding:NSASCIIStringEncoding error:nil]; + NSString *pubKey = [NSString stringWithContentsOfFile:_pubDSAKeyFile encoding:NSASCIIStringEncoding error:nil]; XCTAssertNotNil(pubKey, @"Public key must be readable"); NSString *validSig = @"MCwCFCIHCIYYkfZavNzTitTW5tlRp/k5AhQ40poFytqcVhIYdCxQznaXeJPJDQ=="; NSError *error = nil; - XCTAssertTrue([self checkFile:self.testFile + XCTAssertTrue([self checkFile:_testFile withDSAKey:pubKey signature:validSig error:&error], @"Expected valid signature: %@", error); - XCTAssertFalse([self checkFile:self.testFile + XCTAssertFalse([self checkFile:_testFile withDSAKey:@"lol" signature:validSig error:&error], @"Invalid pubkey: %@", error); - XCTAssertFalse([self checkFile:self.pubDSAKeyFile + XCTAssertFalse([self checkFile:_pubDSAKeyFile withDSAKey:pubKey signature:validSig error:&error], @"Wrong file checked: %@", error); - XCTAssertFalse([self checkFile:self.testFile + XCTAssertFalse([self checkFile:_testFile withDSAKey:pubKey signature:@"MCwCFCIHCiYYkfZavNzTitTW5tlRp/k5AhQ40poFytqcVhIYdCxQznaXeJPJDQ==" error:&error], @"Expected invalid signature: %@", error); - XCTAssertTrue([self checkFile:self.testFile + XCTAssertTrue([self checkFile:_testFile withDSAKey:pubKey signature:@"MC0CFAsKO7cq2q7L5/FWe6ybVIQkwAwSAhUA2Q8GKsE309eugi/v3Kh1W3w3N8c=" error:&error], @"Expected valid signature: %@", error); - XCTAssertFalse([self checkFile:self.testFile + XCTAssertFalse([self checkFile:_testFile withDSAKey:pubKey signature:@"MC0CFAsKO7cq2q7L5/FWe6ybVIQkwAwSAhUA2Q8GKsE309eugi/v3Kh1W3w3N8" error:&error], @"Expected invalid signature: %@", error); } +#endif - (void)testVerifyFileAtPathUsingED25519 { @@ -79,71 +84,83 @@ NSError *error = nil; - XCTAssertTrue([self checkFile:self.testFile - withEdKey:self.pubEdKey + XCTAssertTrue([self checkFile:_testFile + withEdKey:_pubEdKey signature:validSig error:&error], @"Expected valid signature: %@", error); - XCTAssertFalse([self checkFile:self.testFile + XCTAssertFalse([self checkFile:_testFile withEdKey:@"lol" signature:validSig error:&error], @"Invalid pubkey: %@", error); - XCTAssertFalse([self checkFile:self.pubDSAKeyFile - withEdKey:self.pubEdKey + XCTAssertFalse([self checkFile:_pubDSAKeyFile + withEdKey:_pubEdKey signature:validSig error:&error], @"Wrong file checked: %@", error); - XCTAssertFalse([self checkFile:self.testFile - withEdKey:self.pubEdKey + XCTAssertFalse([self checkFile:_testFile + withEdKey:_pubEdKey signature:@"wTcpXCgWoa4NrJpsfzS61FXJIbv963//12U2ef9xstzVOLPHYK2N4/ojgpDV5N1/NGG1uWMBgK+kEWp0Z5zMDQ==" error:&error], @"Expected wrong signature: %@", error); - XCTAssertFalse([self checkFile:self.testFile - withEdKey:self.pubEdKey + XCTAssertFalse([self checkFile:_testFile + withEdKey:_pubEdKey signature:@"lol" error:&error], @"Invalid signature: %@", error); } +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT - (BOOL)checkFile:(NSString *)aFile withDSAKey:(NSString *)pubKey signature:(NSString *)sigString error:(NSError * __autoreleasing *)error { - SUPublicKeys *pubKeys = [[SUPublicKeys alloc] initWithDsa:pubKey ed:nil]; + SUPublicKeys *pubKeys = [[SUPublicKeys alloc] initWithEd:nil dsa:pubKey]; SUSignatureVerifier *v = [[SUSignatureVerifier alloc] initWithPublicKeys:pubKeys]; - SUSignatures *sig = [[SUSignatures alloc] initWithDsa:sigString ed:nil]; + SUSignatures *sig = [[SUSignatures alloc] initWithEd:nil dsa:sigString]; return [v verifyFileAtPath:aFile signatures:sig error:error]; } +#endif - (BOOL)checkFile:(NSString *)aFile withEdKey:(NSString *)pubKey signature:(NSString *)sigString error:(NSError * __autoreleasing *)error { - SUPublicKeys *pubKeys = [[SUPublicKeys alloc] initWithDsa:nil ed:pubKey]; + SUPublicKeys *pubKeys = [[SUPublicKeys alloc] initWithEd:pubKey +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT + dsa:nil +#endif + ]; + SUSignatureVerifier *v = [[SUSignatureVerifier alloc] initWithPublicKeys:pubKeys]; - SUSignatures *sig = [[SUSignatures alloc] initWithDsa:nil ed:sigString]; + SUSignatures *sig = [[SUSignatures alloc] initWithEd:sigString +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT + dsa:nil +#endif + ]; return [v verifyFileAtPath:aFile signatures:sig error:error]; } +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT - (void)testVerifyFileWithBothKeys { - NSString *dsaKey = [NSString stringWithContentsOfFile:self.pubDSAKeyFile encoding:NSASCIIStringEncoding error:nil]; + NSString *dsaKey = [NSString stringWithContentsOfFile:_pubDSAKeyFile encoding:NSASCIIStringEncoding error:nil]; XCTAssertNotNil(dsaKey, @"Public key must be readable"); - SUPublicKeys *pubKeys = [[SUPublicKeys alloc] initWithDsa:dsaKey ed:self.pubEdKey]; + SUPublicKeys *pubKeys = [[SUPublicKeys alloc] initWithEd:_pubEdKey dsa:dsaKey]; SUSignatureVerifier *v = [[SUSignatureVerifier alloc] initWithPublicKeys:pubKeys]; NSError *error = nil; - XCTAssertFalse([v verifyFileAtPath:self.testFile - signatures:[[SUSignatures alloc] initWithDsa:nil ed:nil] error:&error], + XCTAssertFalse([v verifyFileAtPath:_testFile + signatures:[[SUSignatures alloc] initWithEd:nil dsa:nil] error:&error], @"Fail if no signatures are provided: %@", error); - XCTAssertFalse([v verifyFileAtPath:self.testFile - signatures:[[SUSignatures alloc] initWithDsa:@"lol" ed:@"lol"] error:&error], + XCTAssertFalse([v verifyFileAtPath:_testFile + signatures:[[SUSignatures alloc] initWithEd:@"lol" dsa:@"lol"] error:&error], @"Fail if both signatures are invalid: %@", error); NSString *dsaSig = @"MCwCFCIHCIYYkfZavNzTitTW5tlRp/k5AhQ40poFytqcVhIYdCxQznaXeJPJDQ=="; @@ -151,72 +168,90 @@ NSString *edSig = @"EIawm2YkDZ2gBfkEMF2+1VuuTeXnCGZOdnMdVgPPvDZioq7bvDayXqKkIIzSjKMmeFdcFJOHdnba5ZV60+gPBw=="; NSString *wrongEdSig = @"wTcpXCgWoa4NrJpsfzS61FXJIbv963//12U2ef9xstzVOLPHYK2N4/ojgpDV5N1/NGG1uWMBgK+kEWp0Z5zMDQ=="; - XCTAssertFalse([v verifyFileAtPath:self.testFile - signatures:[[SUSignatures alloc] initWithDsa:dsaSig ed:nil] error:&error], + XCTAssertFalse([v verifyFileAtPath:_testFile + signatures:[[SUSignatures alloc] initWithEd:nil dsa:dsaSig] error:&error], @"EdDSA signature must be present if app has EdDSA key: %@", error); - XCTAssertTrue([v verifyFileAtPath:self.testFile - signatures:[[SUSignatures alloc] initWithDsa:nil ed:edSig] error:&error], + XCTAssertTrue([v verifyFileAtPath:_testFile + signatures:[[SUSignatures alloc] initWithEd:edSig dsa:nil] error:&error], @"Allow just an EdDSA signature if that's all that's available: %@", error); - XCTAssertFalse([v verifyFileAtPath:self.testFile - signatures:[[SUSignatures alloc] initWithDsa:dsaSig ed:wrongEdSig] error:&error], + XCTAssertFalse([v verifyFileAtPath:_testFile + signatures:[[SUSignatures alloc] initWithEd:wrongEdSig dsa:dsaSig] error:&error], @"Fail on a bad Ed25519 signature regardless: %@", error); - XCTAssertTrue([v verifyFileAtPath:self.testFile - signatures:[[SUSignatures alloc] initWithDsa:wrongDSASig ed:edSig] error:&error], + XCTAssertTrue([v verifyFileAtPath:_testFile + signatures:[[SUSignatures alloc] initWithEd:edSig dsa:wrongDSASig] error:&error], @"Allow bad DSA signature if EdDSA signature is good: %@", error); - XCTAssertFalse([v verifyFileAtPath:self.testFile - signatures:[[SUSignatures alloc] initWithDsa:dsaSig ed:@"lol"] error:&error], + XCTAssertFalse([v verifyFileAtPath:_testFile + signatures:[[SUSignatures alloc] initWithEd:@"lol" dsa:dsaSig] error:&error], @"Fail if the Ed25519 signature is invalid: %@", error); - XCTAssertFalse([v verifyFileAtPath:self.testFile - signatures:[[SUSignatures alloc] initWithDsa:@"lol" ed:edSig] error:&error], + XCTAssertFalse([v verifyFileAtPath:_testFile + signatures:[[SUSignatures alloc] initWithEd:edSig dsa:@"lol"] error:&error], @"Fail if invalid DSA signature is used even if EdDSA signature is good: %@", error); - XCTAssertTrue([v verifyFileAtPath:self.testFile - signatures:[[SUSignatures alloc] initWithDsa:dsaSig ed:edSig] error:&error], + XCTAssertTrue([v verifyFileAtPath:_testFile + signatures:[[SUSignatures alloc] initWithEd:edSig dsa:dsaSig] error:&error], @"Pass if both are valid: %@", error); } +#endif - (void)testVerifyFileWithWrongKey { + NSError *error = nil; + +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT NSString *dsaSig = @"MCwCFCIHCIYYkfZavNzTitTW5tlRp/k5AhQ40poFytqcVhIYdCxQznaXeJPJDQ=="; NSString *edSig = @"EIawm2YkDZ2gBfkEMF2+1VuuTeXnCGZOdnMdVgPPvDZioq7bvDayXqKkIIzSjKMmeFdcFJOHdnba5ZV60+gPBw=="; - - NSString *dsaKey = [NSString stringWithContentsOfFile:self.pubDSAKeyFile encoding:NSASCIIStringEncoding error:nil]; + + NSString *dsaKey = [NSString stringWithContentsOfFile:_pubDSAKeyFile encoding:NSASCIIStringEncoding error:nil]; XCTAssertNotNil(dsaKey, @"Public key must be readable"); - - SUPublicKeys *dsaOnlyKeys = [[SUPublicKeys alloc] initWithDsa:dsaKey ed:nil]; + + SUPublicKeys *dsaOnlyKeys = [[SUPublicKeys alloc] initWithEd:nil dsa:dsaKey]; SUSignatureVerifier *dsaOnlyVerifier = [[SUSignatureVerifier alloc] initWithPublicKeys:dsaOnlyKeys]; - NSError *error = nil; - XCTAssertFalse([dsaOnlyVerifier verifyFileAtPath:self.testFile - signatures:[[SUSignatures alloc] initWithDsa:nil ed:edSig] error:&error], + XCTAssertFalse([dsaOnlyVerifier verifyFileAtPath:_testFile + signatures:[[SUSignatures alloc] initWithEd:edSig dsa:nil] error:&error], @"DSA cannot verify an Ed signature: %@", error); - - SUPublicKeys *edOnlyKeys = [[SUPublicKeys alloc] initWithDsa:nil ed:self.pubEdKey]; +#endif + + SUPublicKeys *edOnlyKeys = [[SUPublicKeys alloc] initWithEd:_pubEdKey +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT + dsa:nil +#endif + ]; SUSignatureVerifier *edOnlyVerifier = [[SUSignatureVerifier alloc] initWithPublicKeys:edOnlyKeys]; - XCTAssertFalse([edOnlyVerifier verifyFileAtPath:self.testFile - signatures:[[SUSignatures alloc] initWithDsa:dsaSig ed:nil] error:&error], - @"Ed cannot verify an DSA signature: %@", error); + { + SUSignatures *signatures = [[SUSignatures alloc] initWithEd:nil +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT + dsa:dsaSig +#endif + ]; + XCTAssertFalse([edOnlyVerifier verifyFileAtPath:_testFile + signatures:signatures + error:&error], + @"Ed cannot verify an DSA signature: %@", error); + } } +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT - (void)testValidatePath { - NSString *dsaStr = [NSString stringWithContentsOfFile:self.pubDSAKeyFile encoding:NSASCIIStringEncoding error:nil]; + NSString *dsaStr = [NSString stringWithContentsOfFile:_pubDSAKeyFile encoding:NSASCIIStringEncoding error:nil]; XCTAssertNotNil(dsaStr); - SUPublicKeys *pubkeys = [[SUPublicKeys alloc] initWithDsa:dsaStr ed:nil]; + SUPublicKeys *pubkeys = [[SUPublicKeys alloc] initWithEd:nil dsa:dsaStr]; XCTAssertNotNil(pubkeys); XCTAssertNotNil(pubkeys.dsaPubKey); - SUSignatures *sig = [[SUSignatures alloc] initWithDsa:@"MC0CFFMF3ha5kjvrJ9JTpTR8BenPN9QUAhUAzY06JRdtP17MJewxhK0twhvbKIE=" ed:nil]; + SUSignatures *sig = [[SUSignatures alloc] initWithEd:nil dsa:@"MC0CFFMF3ha5kjvrJ9JTpTR8BenPN9QUAhUAzY06JRdtP17MJewxhK0twhvbKIE="]; XCTAssertNotNil(sig); XCTAssertNotNil(sig.dsaSignature); NSError *error = nil; - XCTAssertTrue([SUSignatureVerifier validatePath:self.testFile withSignatures:sig withPublicKeys:pubkeys error:&error], @"Expected valid signature: %@", error); + XCTAssertTrue([SUSignatureVerifier validatePath:_testFile withSignatures:sig withPublicKeys:pubkeys error:&error], @"Expected valid signature: %@", error); } +#endif @end diff --git a/Tests/SUUnarchiverTest.swift b/Tests/SUUnarchiverTest.swift index 019b34f3..183072fd 100644 --- a/Tests/SUUnarchiverTest.swift +++ b/Tests/SUUnarchiverTest.swift @@ -115,6 +115,7 @@ class SUUnarchiverTest: XCTestCase self.unarchiveTestAppWithExtension("tar.xz") } +#if SPARKLE_BUILD_DMG_SUPPORT func testUnarchivingHFSDmgWithLicenseAgreement() { self.unarchiveTestAppWithExtension("dmg") @@ -129,7 +130,9 @@ class SUUnarchiverTest: XCTestCase { self.unarchiveTestAppWithExtension("dmg", resourceName: "SparkleTestCodeSign_apfs") } +#endif +#if SPARKLE_BUILD_PACKAGE_SUPPORT func testUnarchivingFlatPackage() { self.unarchiveTestAppWithExtension("pkg", resourceName: "test", expectingInstallationType: SPUInstallationTypeGuidedPackage) @@ -138,4 +141,5 @@ class SUUnarchiverTest: XCTestCase self.unarchiveTestAppWithExtension("pkg", resourceName: "test", expectingInstallationType: SPUInstallationTypeApplication, expectingSuccess: false) } +#endif } diff --git a/Tests/SUUpdateValidatorTest.swift b/Tests/SUUpdateValidatorTest.swift index be4d8da7..d8d990a5 100644 --- a/Tests/SUUpdateValidatorTest.swift +++ b/Tests/SUUpdateValidatorTest.swift @@ -12,7 +12,9 @@ import XCTest class SUUpdateValidatorTest: XCTestCase { enum BundleConfig: String, CaseIterable, Equatable { case none = "None" +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT case dsaOnly = "DSAOnly" +#endif case edOnly = "EDOnly" case both = "Both" case codeSignedOnly = "CodeSignedOnly" @@ -27,8 +29,12 @@ class SUUpdateValidatorTest: XCTestCase { switch self { case .none, .codeSignedOnly, .codeSignedOnlyNew, .codeSignedInvalidOnly: return false - case .dsaOnly, .edOnly, .both, .codeSignedBoth, .codeSignedBothNew, .codeSignedOldED, .codeSignedInvalid: + case .edOnly, .both, .codeSignedBoth, .codeSignedBothNew, .codeSignedOldED, .codeSignedInvalid: return true +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT + case .dsaOnly: + return true +#endif } } } @@ -38,17 +44,27 @@ class SUUpdateValidatorTest: XCTestCase { case none, invalid, invalidFormat, valid } - var dsa: State var ed: State +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT + var dsa: State +#endif static let allCases: [SignatureConfig] = State.allCases.flatMap { dsaState in State.allCases.map { edState in - SignatureConfig(dsa: dsaState, ed: edState) +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT + SignatureConfig(ed: edState, dsa: dsaState) +#else + SignatureConfig(ed: edState) +#endif } } var debugDescription: String { - return "(dsa: \(self.dsa), ed: \(self.ed))" +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT + return "(ed: \(self.ed), dsa: \(self.dsa))" +#else + return "(ed: \(self.ed))" +#endif } } @@ -59,6 +75,7 @@ class SUUpdateValidatorTest: XCTestCase { } func signatures(_ config: SignatureConfig) -> SUSignatures { +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT let dsaSig: String? switch config.dsa { case .none: dsaSig = nil @@ -67,6 +84,7 @@ class SUUpdateValidatorTest: XCTestCase { case .invalidFormat: dsaSig = "%%wCFCIHCIYYkfZavNzTitTW5tlRp/k5AhQ40poFytqcVhIYdCxQznaXeJPJDQ==" case .valid: dsaSig = "MCwCFCIHCIYYkfZavNzTitTW5tlRp/k5AhQ40poFytqcVhIYdCxQznaXeJPJDQ==" } +#endif let edSig: String? switch config.ed { @@ -77,7 +95,11 @@ class SUUpdateValidatorTest: XCTestCase { case .valid: edSig = "EIawm2YkDZ2gBfkEMF2+1VuuTeXnCGZOdnMdVgPPvDZioq7bvDayXqKkIIzSjKMmeFdcFJOHdnba5ZV60+gPBw==" } - return SUSignatures(dsa: dsaSig, ed: edSig) +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT + return SUSignatures(ed: edSig, dsa: dsaSig) +#else + return SUSignatures(ed: edSig) +#endif } var signedTestFilePath: String { @@ -97,9 +119,17 @@ class SUUpdateValidatorTest: XCTestCase { func testPrevalidation() { for signatureConfig in SignatureConfig.allCases { testPrevalidation(bundle: .none, signatures: signatureConfig, expectedResult: false) +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT testPrevalidation(bundle: .dsaOnly, signatures: signatureConfig, expectedResult: signatureConfig.dsa == .valid) +#endif +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT testPrevalidation(bundle: .edOnly, signatures: signatureConfig, expectedResult: signatureConfig.ed == .valid && signatureConfig.dsa != .invalidFormat) +#else + testPrevalidation(bundle: .edOnly, signatures: signatureConfig, expectedResult: signatureConfig.ed == .valid) +#endif +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT testPrevalidation(bundle: .both, signatures: signatureConfig, expectedResult: signatureConfig.ed == .valid && signatureConfig.dsa != .invalidFormat) +#endif } } @@ -126,16 +156,28 @@ class SUUpdateValidatorTest: XCTestCase { func testPostValidationWithoutCodeSigning() { for signatureConfig in SignatureConfig.allCases { testPostValidation(bundle: .none, signatures: signatureConfig, expectedResult: false) +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT testPostValidation(bundle: .dsaOnly, signatures: signatureConfig, expectedResult: signatureConfig.dsa == .valid) +#endif +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT testPostValidation(bundle: .edOnly, signatures: signatureConfig, expectedResult: signatureConfig.ed == .valid && signatureConfig.dsa != .invalidFormat) +#else + testPostValidation(bundle: .edOnly, signatures: signatureConfig, expectedResult: signatureConfig.ed == .valid) +#endif +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT testPostValidation(bundle: .both, signatures: signatureConfig, expectedResult: signatureConfig.ed == .valid && signatureConfig.dsa != .invalidFormat) +#endif } } func testPostValidationWithCodeSigning() { for signatureConfig in SignatureConfig.allCases { testPostValidation(bundle: .codeSignedOnly, signatures: signatureConfig, expectedResult: true) +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT testPostValidation(bundle: .codeSignedBoth, signatures: signatureConfig, expectedResult: signatureConfig.ed == .valid && signatureConfig.dsa != .invalidFormat) +#else + testPostValidation(bundle: .codeSignedBoth, signatures: signatureConfig, expectedResult: signatureConfig.ed == .valid) +#endif testPostValidation(bundle: .codeSignedInvalidOnly, signatures: signatureConfig, expectedResult: false) testPostValidation(bundle: .codeSignedInvalid, signatures: signatureConfig, expectedResult: false) @@ -144,16 +186,38 @@ class SUUpdateValidatorTest: XCTestCase { func testPostValidationWithKeyRemoval() { for bundleConfig in BundleConfig.allCases { - testPostValidation(oldBundle: .dsaOnly, newBundle: bundleConfig, signatures: SignatureConfig(dsa: .valid, ed: .valid), expectedResult: bundleConfig.hasAnyKeys && bundleConfig != .codeSignedInvalid) - testPostValidation(oldBundle: .edOnly, newBundle: bundleConfig, signatures: SignatureConfig(dsa: .valid, ed: .valid), expectedResult: bundleConfig.hasAnyKeys && bundleConfig != .codeSignedInvalid) - testPostValidation(oldBundle: .both, newBundle: bundleConfig, signatures: SignatureConfig(dsa: .valid, ed: .valid), expectedResult: bundleConfig.hasAnyKeys && bundleConfig != .codeSignedInvalid) - testPostValidation(oldBundle: .codeSignedBoth, newBundle: bundleConfig, signatures: SignatureConfig(dsa: .valid, ed: .valid), expectedResult: bundleConfig.hasAnyKeys && bundleConfig != .codeSignedInvalid) +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT + testPostValidation(oldBundle: .dsaOnly, newBundle: bundleConfig, signatures: SignatureConfig(ed: .valid, dsa: .valid), expectedResult: bundleConfig.hasAnyKeys && bundleConfig != .codeSignedInvalid) +#endif + do { +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT + let signatureConfig = SignatureConfig(ed: .valid, dsa: .valid) +#else + let signatureConfig = SignatureConfig(ed: .valid) +#endif + testPostValidation(oldBundle: .edOnly, newBundle: bundleConfig, signatures: signatureConfig, expectedResult: bundleConfig.hasAnyKeys && bundleConfig != .codeSignedInvalid) + } +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT + testPostValidation(oldBundle: .both, newBundle: bundleConfig, signatures: SignatureConfig(ed: .valid, dsa: .valid), expectedResult: bundleConfig.hasAnyKeys && bundleConfig != .codeSignedInvalid) +#endif + do { +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT + let signatureConfig = SignatureConfig(ed: .valid, dsa: .valid) +#else + let signatureConfig = SignatureConfig(ed: .valid) +#endif + testPostValidation(oldBundle: .codeSignedBoth, newBundle: bundleConfig, signatures: signatureConfig, expectedResult: bundleConfig.hasAnyKeys && bundleConfig != .codeSignedInvalid) + } } } func testPostValidationWithKeyRotation() { for signatureConfig in SignatureConfig.allCases { +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT let signatureIsValid = (signatureConfig.ed == .valid && signatureConfig.dsa != .invalidFormat) +#else + let signatureIsValid = (signatureConfig.ed == .valid) +#endif // It's okay to add DSA keys or add code signing. testPostValidation(oldBundle: .codeSignedOnly, newBundle: .codeSignedBoth, signatures: signatureConfig, expectedResult: signatureIsValid) diff --git a/Tests/SUUpdaterTest.m b/Tests/SUUpdaterTest.m index 6ded7404..18bf6e71 100644 --- a/Tests/SUUpdaterTest.m +++ b/Tests/SUUpdaterTest.m @@ -13,12 +13,12 @@ #import "SPUUpdaterDelegate.h" @interface SUUpdaterTest : XCTestCase -@property (strong) SPUUpdater *updater; @end @implementation SUUpdaterTest - -@synthesize updater; +{ + SPUUpdater *_updater; +} - (void)setUp { @@ -29,19 +29,21 @@ #pragma clang diagnostic ignored "-Wnonnull" // We really want a useless / not really functional user driver so we will pass nil here // For real world applications we should pass a valid user driver which is why this is not a nullable parameter - self.updater = [[SPUUpdater alloc] initWithHostBundle:bundle applicationBundle:bundle userDriver:nil delegate:self]; + _updater = [[SPUUpdater alloc] initWithHostBundle:bundle applicationBundle:bundle userDriver:nil delegate:self]; #pragma clang diagnostic pop NSError *error = nil; - if (![self.updater startUpdater:&error]) { + if (![_updater startUpdater:&error]) { NSLog(@"Updater error: %@", error); abort(); } + + [_updater clearFeedURLFromUserDefaults]; } - (void)tearDown { - self.updater = nil; + _updater = nil; [super tearDown]; } @@ -52,14 +54,17 @@ - (void)testFeedURL { - [self.updater feedURL]; // this WON'T throw + [_updater feedURL]; // this WON'T throw } - (void)testSetTestFeedURL { NSURL *emptyURL = [NSURL URLWithString:@""]; XCTAssertNotNil(emptyURL); - [self.updater setFeedURL:emptyURL]; // this WON'T throw +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + [_updater setFeedURL:emptyURL]; // this WON'T throw +#pragma clang diagnostic pop } @end diff --git a/Tests/SUVersionComparisonTest.m b/Tests/SUVersionComparisonTest.m index da015fb4..6259262e 100644 --- a/Tests/SUVersionComparisonTest.m +++ b/Tests/SUVersionComparisonTest.m @@ -6,8 +6,7 @@ // Copyright 2008 Andy Matuschak. All rights reserved. // -#import - +#import "SUStandardVersionComparator.h" #import @interface SUVersionComparisonTestCase : XCTestCase { diff --git a/Tests/Sparkle Unit Tests-Bridging-Header.h b/Tests/Sparkle Unit Tests-Bridging-Header.h index c6b9976b..543bd2b7 100644 --- a/Tests/Sparkle Unit Tests-Bridging-Header.h +++ b/Tests/Sparkle Unit Tests-Bridging-Header.h @@ -29,8 +29,6 @@ static const char *SUAppleQuarantineIdentifier = "com.apple.quarantine"; @interface SUFileManager (Private) -- (BOOL)_acquireAuthorizationWithError:(NSError *_Nullable __autoreleasing *_Nullable)error; - - (BOOL)_itemExistsAtURL:(NSURL *)fileURL; - (BOOL)_itemExistsAtURL:(NSURL *)fileURL isDirectory:(nullable BOOL *)isDirectory; diff --git a/generate_appcast/Appcast.swift b/generate_appcast/Appcast.swift index 69e4421a..ddf236c8 100644 --- a/generate_appcast/Appcast.swift +++ b/generate_appcast/Appcast.swift @@ -176,6 +176,7 @@ func makeAppcasts(archivesSourceDir: URL, outputPathURL: URL?, cacheDirectory ca group.enter() DispatchQueue.global().async { +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT if let privateDSAKey = keys.privateDSAKey { do { update.dsaSignature = try dsaSignature(path: update.archivePath, privateDSAKey: privateDSAKey) @@ -185,6 +186,7 @@ func makeAppcasts(archivesSourceDir: URL, outputPathURL: URL?, cacheDirectory ca } else if update.supportsDSA { print("Note: did not sign with legacy DSA \(update.archivePath.path) because private DSA key file was not specified") } +#endif if let publicEdKey = update.publicEdKey { if let privateEdKey = keys.privateEdKey, let expectedPublicKey = keys.publicEdKey { if publicEdKey == expectedPublicKey { @@ -334,6 +336,7 @@ func makeAppcasts(archivesSourceDir: URL, outputPathURL: URL?, cacheDirectory ca group.enter() DispatchQueue.global().async { +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT if item.supportsDSA, let privateDSAKey = keys.privateDSAKey { do { delta.dsaSignature = try dsaSignature(path: deltaPath, privateDSAKey: privateDSAKey) @@ -341,6 +344,7 @@ func makeAppcasts(archivesSourceDir: URL, outputPathURL: URL?, cacheDirectory ca print(delta.archivePath.lastPathComponent, error) } } +#endif if let publicEdKey = item.publicEdKey, let privateEdKey = keys.privateEdKey { do { delta.edSignature = try edSignature(path: deltaPath, publicEdKey: publicEdKey, privateEdKey: privateEdKey) @@ -348,11 +352,17 @@ func makeAppcasts(archivesSourceDir: URL, outputPathURL: URL?, cacheDirectory ca print(delta.archivePath.lastPathComponent, error) } } - if delta.dsaSignature != nil || delta.edSignature != nil { - latestItem.deltas.append(delta) - } else { - markDeltaAsIgnored(delta: delta, markerPath: ignoreMarkerPath) - print("Delta \(delta.archivePath.path) ignored, because it could not be signed") + do { + var hasAnyDSASignature = (delta.edSignature != nil) +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT + hasAnyDSASignature = hasAnyDSASignature || (delta.dsaSignature != nil) +#endif + if hasAnyDSASignature { + latestItem.deltas.append(delta) + } else { + markDeltaAsIgnored(delta: delta, markerPath: ignoreMarkerPath) + print("Delta \(delta.archivePath.path) ignored, because it could not be signed") + } } group.leave() } diff --git a/generate_appcast/ArchiveItem.swift b/generate_appcast/ArchiveItem.swift index df3f4437..400c9c12 100644 --- a/generate_appcast/ArchiveItem.swift +++ b/generate_appcast/ArchiveItem.swift @@ -16,7 +16,9 @@ struct UpdateBranch: Hashable { class DeltaUpdate { let fromVersion: String let archivePath: URL +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT var dsaSignature: String? +#endif var edSignature: String? let sparkleExecutableFileSize: Int? let sparkleLocales: String? @@ -75,7 +77,9 @@ class ArchiveItem: CustomStringConvertible { let archiveFileAttributes: [FileAttributeKey: Any] var deltas: [DeltaUpdate] +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT var dsaSignature: String? +#endif var edSignature: String? var downloadUrlPrefix: URL? var releaseNotesURLPrefix: URL? @@ -141,7 +145,11 @@ class ArchiveItem: CustomStringConvertible { } let shortVersion = infoPlist["CFBundleShortVersionString"] as? String let publicEdKey = infoPlist[SUPublicEDKeyKey] as? String +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT let supportsDSA = infoPlist[SUPublicDSAKeyKey] != nil || infoPlist[SUPublicDSAKeyFileKey] != nil +#else + let supportsDSA = false +#endif var feedURL: URL? if let feedURLStr = infoPlist["SUFeedURL"] as? String { diff --git a/generate_appcast/FeedXML.swift b/generate_appcast/FeedXML.swift index 28f5af35..43991cd1 100644 --- a/generate_appcast/FeedXML.swift +++ b/generate_appcast/FeedXML.swift @@ -435,9 +435,11 @@ func writeAppcast(appcastDestPath: URL, appcast: Appcast, fullReleaseNotesLink: if let sig = update.edSignature { attributes.append(XMLNode.attribute(withName: SUAppcastAttributeEDSignature, uri: sparkleNS, stringValue: sig) as! XMLNode) } +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT if let sig = update.dsaSignature { attributes.append(XMLNode.attribute(withName: SUAppcastAttributeDSASignature, uri: sparkleNS, stringValue: sig) as! XMLNode) } +#endif enclosure!.attributes = attributes if update.deltas.count > 0 { @@ -467,9 +469,11 @@ func writeAppcast(appcastDestPath: URL, appcast: Appcast, fullReleaseNotesLink: if let sig = delta.edSignature { attributes.append(XMLNode.attribute(withName: SUAppcastAttributeEDSignature, uri: sparkleNS, stringValue: sig) as! XMLNode) } +#if SPARKLE_BUILD_LEGACY_DSA_SUPPORT if let sig = delta.dsaSignature { attributes.append(XMLNode.attribute(withName: SUAppcastAttributeDSASignature, uri: sparkleNS, stringValue: sig) as! XMLNode) } +#endif deltas!.addChild(XMLNode.element(withName: "enclosure", children: nil, attributes: attributes) as! XMLElement) } } diff --git a/sparkle-cli/SPUCommandLineDriver.h b/sparkle-cli/SPUCommandLineDriver.h index c9f398ee..efdaac5f 100644 --- a/sparkle-cli/SPUCommandLineDriver.h +++ b/sparkle-cli/SPUCommandLineDriver.h @@ -12,7 +12,7 @@ NS_ASSUME_NONNULL_BEGIN @class SUUpdatePermissionResponse; -@interface SPUCommandLineDriver : NSObject +SPU_OBJC_DIRECT_MEMBERS @interface SPUCommandLineDriver : NSObject - (nullable instancetype)initWithUpdateBundlePath:(NSString *)updateBundlePath applicationBundlePath:(nullable NSString *)applicationBundlePath allowedChannels:(NSSet *)allowedChannels customFeedURL:(nullable NSString *)customFeedURL userAgentName:(nullable NSString *)userAgentName updatePermissionResponse:(nullable SUUpdatePermissionResponse *)updatePermissionResponse deferInstallation:(BOOL)deferInstallation interactiveInstallation:(BOOL)interactiveInstallation allowMajorUpgrades:(BOOL)allowMajorUpgrades verbose:(BOOL)verbose; diff --git a/sparkle-cli/SPUCommandLineDriver.m b/sparkle-cli/SPUCommandLineDriver.m index 4da83648..ac6c16f4 100644 --- a/sparkle-cli/SPUCommandLineDriver.m +++ b/sparkle-cli/SPUCommandLineDriver.m @@ -31,28 +31,20 @@ typedef NS_ENUM(int, CLIErrorExitStatus) { }; @interface SPUCommandLineDriver () - -@property (nonatomic, readonly) SPUUpdater *updater; -@property (nonatomic, readonly) BOOL verbose; -@property (nonatomic) BOOL probingForUpdates; -@property (nonatomic, readonly) BOOL interactive; -@property (nonatomic, readonly) BOOL allowMajorUpgrades; -@property (nonatomic, readonly) NSSet *allowedChannels; -@property (nonatomic, copy, readonly, nullable) NSString *customFeedURL; -@property (nonatomic, readonly) SUUpdatePermissionResponse *updatePermissionResponse; - @end @implementation SPUCommandLineDriver - -@synthesize updater = _updater; -@synthesize verbose = _verbose; -@synthesize probingForUpdates = _probingForUpdates; -@synthesize interactive = _interactive; -@synthesize allowMajorUpgrades = _allowMajorUpgrades; -@synthesize allowedChannels = _allowedChannels; -@synthesize customFeedURL = _customFeedURL; -@synthesize updatePermissionResponse = _updatePermissionResponse; +{ + SPUUpdater *_updater; + SUUpdatePermissionResponse *_updatePermissionResponse; + NSSet *_allowedChannels; + NSString *_customFeedURL; + + BOOL _verbose; + BOOL _probingForUpdates; + BOOL _interactive; + BOOL _allowMajorUpgrades; +} - (instancetype)initWithUpdateBundlePath:(NSString *)updateBundlePath applicationBundlePath:(nullable NSString *)applicationBundlePath allowedChannels:(NSSet *)allowedChannels customFeedURL:(nullable NSString *)customFeedURL userAgentName:(nullable NSString *)customUserAgentName updatePermissionResponse:(nullable SUUpdatePermissionResponse *)updatePermissionResponse deferInstallation:(BOOL)deferInstallation interactiveInstallation:(BOOL)interactiveInstallation allowMajorUpgrades:(BOOL)allowMajorUpgrades verbose:(BOOL)verbose { @@ -116,7 +108,7 @@ typedef NS_ENUM(int, CLIErrorExitStatus) { - (void)updater:(SPUUpdater *)__unused updater willScheduleUpdateCheckAfterDelay:(NSTimeInterval)delay __attribute__((noreturn)) { - if (self.verbose) { + if (_verbose) { fprintf(stderr, "Last update check occurred too soon. Try again after %0.0f second(s).", delay); } exit(EXIT_SUCCESS); @@ -124,7 +116,7 @@ typedef NS_ENUM(int, CLIErrorExitStatus) { - (void)updaterWillNotScheduleUpdateCheck:(SPUUpdater *)__unused updater __attribute__((noreturn)) { - if (self.verbose) { + if (_verbose) { fprintf(stderr, "Automatic update checks are disabled. Exiting.\n"); } exit(EXIT_SUCCESS); @@ -132,7 +124,7 @@ typedef NS_ENUM(int, CLIErrorExitStatus) { - (BOOL)updaterShouldPromptForPermissionToCheckForUpdates:(SPUUpdater *)__unused updater { - if (self.updatePermissionResponse == nil) { + if (_updatePermissionResponse == nil) { // We don't want to make this decision on behalf of the user. fprintf(stderr, "Error: Asked to grant update permission and --grant-automatic-checks is not specified. Exiting.\n"); exit(CLIErrorExitStatusUpdatePermissionRequested); @@ -147,7 +139,7 @@ typedef NS_ENUM(int, CLIErrorExitStatus) { switch (updateCheck) { case SPUUpdateCheckUpdates: case SPUUpdateCheckUpdatesInBackground: - if (self.interactive || !SPUSystemNeedsAuthorizationAccessForBundlePath(self.updater.hostBundle.bundlePath)) { + if (_interactive || !SPUSystemNeedsAuthorizationAccessForBundlePath(_updater.hostBundle.bundlePath)) { return YES; } @@ -170,7 +162,7 @@ typedef NS_ENUM(int, CLIErrorExitStatus) { } // If we encounter a major upgrade and not allowed to act on it, then error - if (updateItem.majorUpgrade && !self.allowMajorUpgrades) { + if (updateItem.majorUpgrade && !_allowMajorUpgrades) { if (error != NULL) { *error = [NSError errorWithDomain:SPARKLE_CLI_ERROR_DOMAIN code:CLIErrorCodeCannotInstallMajorUpgrade userInfo:@{ NSLocalizedDescriptionKey: @"Major upgrade available but not allowed to install it. Pass --allow-major-upgrades to allow this." }]; } @@ -178,7 +170,7 @@ typedef NS_ENUM(int, CLIErrorExitStatus) { return NO; } - if (!self.interactive && geteuid() != 0) { // applicable for non-root only + if (!_interactive && geteuid() != 0) { // applicable for non-root only if (![updateItem.installationType isEqualToString:SPUInstallationTypeApplication]) { // Any package based updates will require authorization and therefore interaction if (error != NULL) { @@ -193,19 +185,19 @@ typedef NS_ENUM(int, CLIErrorExitStatus) { - (NSSet *)allowedChannelsForUpdater:(SPUUpdater *)__unused updater { - return self.allowedChannels; + return _allowedChannels; } - (nullable NSString *)feedURLStringForUpdater:(SPUUpdater *)__unused updater { - return self.customFeedURL; + return _customFeedURL; } // In case we find an update during probing - (void)updater:(SPUUpdater *)__unused updater didFindValidUpdate:(SUAppcastItem *)item { - if (self.probingForUpdates) { - if (self.verbose) { + if (_probingForUpdates) { + if (_verbose) { if (item.majorUpgrade) { fprintf(stderr, "Major upgrade available.\n"); } else { @@ -218,7 +210,7 @@ typedef NS_ENUM(int, CLIErrorExitStatus) { - (void)updater:(SPUUpdater *)updater didFinishUpdateCycleForUpdateCheck:(SPUUpdateCheck)__unused updateCheck error:(nullable NSError *)error __attribute__((noreturn)) { if (error == nil) { - if (self.verbose) { + if (_verbose) { fprintf(stderr, "Exiting.\n"); } exit(EXIT_SUCCESS); @@ -233,14 +225,14 @@ typedef NS_ENUM(int, CLIErrorExitStatus) { exit(CLIErrorExitStatusInstallerInteractionNotAllowed); } } else if (error.code == SUNoUpdateError) { - if (self.verbose) { + if (_verbose) { fprintf(stderr, "No new update available!\n"); } exit(CLIErrorExitStatusUpdateNotFound); } else if (error.code == SUInstallationCanceledError) { // User canceled authorization themselves - assert(self.interactive); - if (self.verbose) { + assert(_interactive); + if (_verbose) { fprintf(stderr, "Update was cancelled.\n"); } exit(CLIErrorExitStatusUpdateCancelledAuthorization); @@ -262,13 +254,13 @@ typedef NS_ENUM(int, CLIErrorExitStatus) { - (BOOL)updater:(SPUUpdater *)updater shouldDownloadReleaseNotesForUpdate:(nonnull SUAppcastItem *)__unused item { - return self.verbose; + return _verbose; } -- (void)startUpdater +- (void)startUpdater SPU_OBJC_DIRECT { NSError *updaterError = nil; - if (![self.updater startUpdater:&updaterError]) { + if (![_updater startUpdater:&updaterError]) { fprintf(stderr, "Error: Failed to initialize updater with error (%ld): %s\n", updaterError.code, updaterError.localizedDescription.UTF8String); exit(EXIT_FAILURE); } @@ -280,7 +272,7 @@ typedef NS_ENUM(int, CLIErrorExitStatus) { if (checkForUpdatesNow) { // When we start the updater, this scheduled check will start afterwards too - [self.updater checkForUpdates]; + [_updater checkForUpdates]; } } @@ -289,8 +281,8 @@ typedef NS_ENUM(int, CLIErrorExitStatus) { [self startUpdater]; // When we start the updater, this info check will start afterwards too - self.probingForUpdates = YES; - [self.updater checkForUpdateInformation]; + _probingForUpdates = YES; + [_updater checkForUpdateInformation]; } @end diff --git a/sparkle-cli/SPUCommandLineUserDriver.h b/sparkle-cli/SPUCommandLineUserDriver.h index a54e2957..8131fe4d 100644 --- a/sparkle-cli/SPUCommandLineUserDriver.h +++ b/sparkle-cli/SPUCommandLineUserDriver.h @@ -11,7 +11,7 @@ NS_ASSUME_NONNULL_BEGIN -@interface SPUCommandLineUserDriver : NSObject +SPU_OBJC_DIRECT_MEMBERS @interface SPUCommandLineUserDriver : NSObject - (instancetype)initWithUpdatePermissionResponse:(nullable SUUpdatePermissionResponse *)updatePermissionResponse deferInstallation:(BOOL)deferInstallation verbose:(BOOL)verbose; diff --git a/sparkle-cli/SPUCommandLineUserDriver.m b/sparkle-cli/SPUCommandLineUserDriver.m index d58534a2..8f5cd7dc 100644 --- a/sparkle-cli/SPUCommandLineUserDriver.m +++ b/sparkle-cli/SPUCommandLineUserDriver.m @@ -10,23 +10,16 @@ #import #import -@interface SPUCommandLineUserDriver () - -@property (nonatomic, nullable, readonly) SUUpdatePermissionResponse *updatePermissionResponse; -@property (nonatomic, readonly) BOOL deferInstallation; -@property (nonatomic, readonly) BOOL verbose; -@property (nonatomic) uint64_t bytesDownloaded; -@property (nonatomic) uint64_t bytesToDownload; - -@end - @implementation SPUCommandLineUserDriver - -@synthesize updatePermissionResponse = _updatePermissionResponse; -@synthesize deferInstallation = _deferInstallation; -@synthesize verbose = _verbose; -@synthesize bytesDownloaded = _bytesDownloaded; -@synthesize bytesToDownload = _bytesToDownload; +{ + SUUpdatePermissionResponse *_updatePermissionResponse; + + uint64_t _bytesDownloaded; + uint64_t _bytesToDownload; + + BOOL _deferInstallation; + BOOL _verbose; +} - (instancetype)initWithUpdatePermissionResponse:(nullable SUUpdatePermissionResponse *)updatePermissionResponse deferInstallation:(BOOL)deferInstallation verbose:(BOOL)verbose { @@ -41,20 +34,20 @@ - (void)showUpdatePermissionRequest:(SPUUpdatePermissionRequest *)__unused request reply:(void (^)(SUUpdatePermissionResponse *))reply { - if (self.verbose) { - fprintf(stderr, "Granting permission for automatic update checks with sending system profile %s...\n", self.updatePermissionResponse.sendSystemProfile ? "enabled" : "disabled"); + if (_verbose) { + fprintf(stderr, "Granting permission for automatic update checks with sending system profile %s...\n", _updatePermissionResponse.sendSystemProfile ? "enabled" : "disabled"); } - reply(self.updatePermissionResponse); + reply(_updatePermissionResponse); } - (void)showUserInitiatedUpdateCheckWithCancellation:(void (^)(void))__unused cancellation { - if (self.verbose) { + if (_verbose) { fprintf(stderr, "Checking for Updates...\n"); } } -- (void)displayReleaseNotes:(const char * _Nullable)releaseNotes +- (void)displayReleaseNotes:(const char * _Nullable)releaseNotes SPU_OBJC_DIRECT { if (releaseNotes != NULL) { fprintf(stderr, "Release notes:\n"); @@ -62,7 +55,7 @@ } } -- (void)displayHTMLReleaseNotes:(NSData *)releaseNotes +- (void)displayHTMLReleaseNotes:(NSData *)releaseNotes SPU_OBJC_DIRECT { // Note: this is the only API we rely on here that references AppKit // We shouldn't invoke it when the calling process is ran under root. @@ -73,7 +66,7 @@ } } -- (void)displayPlainTextReleaseNotes:(NSData *)releaseNotes encoding:(NSStringEncoding)encoding +- (void)displayPlainTextReleaseNotes:(NSData *)releaseNotes encoding:(NSStringEncoding)encoding SPU_OBJC_DIRECT { NSString *string = [[NSString alloc] initWithData:releaseNotes encoding:encoding]; [self displayReleaseNotes:string.UTF8String]; @@ -81,7 +74,7 @@ - (void)showUpdateWithAppcastItem:(SUAppcastItem *)appcastItem updateAdjective:(NSString *)updateAdjective { - if (self.verbose) { + if (_verbose) { fprintf(stderr, "Found %s update! (%s)\n", updateAdjective.UTF8String, appcastItem.displayVersionString.UTF8String); if (appcastItem.itemDescription != nil) { @@ -109,8 +102,8 @@ reply(SPUUserUpdateChoiceInstall); break; case SPUUserUpdateStageInstalling: - if (self.deferInstallation) { - if (self.verbose) { + if (_deferInstallation) { + if (_verbose) { fprintf(stderr, "Deferring Installation.\n"); } reply(SPUUserUpdateChoiceDismiss); @@ -128,7 +121,7 @@ - (void)showUpdateReleaseNotesWithDownloadData:(SPUDownloadData *)downloadData { - if (self.verbose) { + if (_verbose) { if (downloadData.MIMEType != nil && [downloadData.MIMEType isEqualToString:@"text/plain"]) { NSStringEncoding encoding; if (downloadData.textEncodingName == nil) { @@ -150,7 +143,7 @@ - (void)showUpdateReleaseNotesFailedToDownloadWithError:(NSError *)error { - if (self.verbose) { + if (_verbose) { fprintf(stderr, "Error: Unable to download release notes: %s\n", error.localizedDescription.UTF8String); } } @@ -167,52 +160,52 @@ - (void)showDownloadInitiatedWithCancellation:(void (^)(void))__unused cancellation { - if (self.verbose) { + if (_verbose) { fprintf(stderr, "Downloading Update...\n"); } } - (void)showDownloadDidReceiveExpectedContentLength:(uint64_t)expectedContentLength { - if (self.verbose) { + if (_verbose) { fprintf(stderr, "Downloading %llu bytes...\n", expectedContentLength); } - self.bytesDownloaded = 0; - self.bytesToDownload = expectedContentLength; + _bytesDownloaded = 0; + _bytesToDownload = expectedContentLength; } - (void)showDownloadDidReceiveDataOfLength:(uint64_t)length { - self.bytesDownloaded += length; + _bytesDownloaded += length; // In case our expected content length was incorrect - if (self.bytesDownloaded > self.bytesToDownload) { - self.bytesToDownload = self.bytesDownloaded; + if (_bytesDownloaded > _bytesToDownload) { + _bytesToDownload = _bytesDownloaded; } - if (self.bytesToDownload > 0 && self.verbose) { - fprintf(stderr, "Downloaded %llu out of %llu bytes (%.0f%%)\n", self.bytesDownloaded, self.bytesToDownload, (self.bytesDownloaded * 100.0 / self.bytesToDownload)); + if (_bytesToDownload > 0 && _verbose) { + fprintf(stderr, "Downloaded %llu out of %llu bytes (%.0f%%)\n", _bytesDownloaded, _bytesToDownload, (_bytesDownloaded * 100.0 / _bytesToDownload)); } } - (void)showDownloadDidStartExtractingUpdate { - if (self.verbose) { + if (_verbose) { fprintf(stderr, "Extracting Update...\n"); } } - (void)showExtractionReceivedProgress:(double)progress { - if (self.verbose) { + if (_verbose) { fprintf(stderr, "Extracting Update (%.0f%%)\n", progress * 100); } } - (void)showReadyToInstallAndRelaunch:(void (^)(SPUUserUpdateChoice))installUpdateHandler { - if (self.deferInstallation) { - if (self.verbose) { + if (_deferInstallation) { + if (_verbose) { fprintf(stderr, "Deferring Installation.\n"); } installUpdateHandler(SPUUserUpdateChoiceDismiss); @@ -223,14 +216,14 @@ - (void)showInstallingUpdateWithApplicationTerminated:(BOOL)__unused applicationTerminated retryTerminatingApplication:(void (^)(void))__unused retryTerminatingApplication { - if (self.verbose) { + if (_verbose) { fprintf(stderr, "Installing Update...\n"); } } - (void)showUpdateInstalledAndRelaunched:(BOOL)__unused relaunched acknowledgement:(void (^)(void))acknowledgement { - if (self.verbose) { + if (_verbose) { fprintf(stderr, "Installation Finished.\n"); }