From 0e978e3fafb70939360e34be760ddbcdaec4d1c4 Mon Sep 17 00:00:00 2001 From: Zorg Date: Mon, 16 Jan 2017 22:48:32 -0500 Subject: [PATCH 1/2] Add kqueue based termination listener Note this termination listener is not polling or timer based and will work on processes that aren't GUI applications. --- Sparkle.xcodeproj/project.pbxproj | 6 ++ Sparkle/Autoupdate/Autoupdate.m | 72 +++---------- Sparkle/Autoupdate/TerminationListener.h | 24 +++++ Sparkle/Autoupdate/TerminationListener.m | 131 +++++++++++++++++++++++ 4 files changed, 173 insertions(+), 60 deletions(-) create mode 100644 Sparkle/Autoupdate/TerminationListener.h create mode 100644 Sparkle/Autoupdate/TerminationListener.m diff --git a/Sparkle.xcodeproj/project.pbxproj b/Sparkle.xcodeproj/project.pbxproj index 28ff1914..26c269c9 100644 --- a/Sparkle.xcodeproj/project.pbxproj +++ b/Sparkle.xcodeproj/project.pbxproj @@ -190,6 +190,7 @@ 61FA52880E2D9EA400EF58AD /* Sparkle.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8DC2EF5B0486A6940098B216 /* Sparkle.framework */; settings = {ATTRIBUTES = (Required, ); }; }; 7205C4311E1215AD00E370AE /* SUUpdatePermissionResponse.h in Headers */ = {isa = PBXBuildFile; fileRef = 7205C42F1E1215AD00E370AE /* SUUpdatePermissionResponse.h */; }; 7205C4321E1215AD00E370AE /* SUUpdatePermissionResponse.m in Sources */ = {isa = PBXBuildFile; fileRef = 7205C4301E1215AD00E370AE /* SUUpdatePermissionResponse.m */; }; + 720767CF1E2DC37400F9A850 /* TerminationListener.m in Sources */ = {isa = PBXBuildFile; fileRef = 720767CE1E2DC37400F9A850 /* TerminationListener.m */; }; 720B16451C66433D006985FB /* SUTestApplicationTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 720B16431C66433D006985FB /* SUTestApplicationTest.swift */; }; 7210C7681B9A9A1500EB90AC /* SUUnarchiverTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7210C7671B9A9A1500EB90AC /* SUUnarchiverTest.swift */; }; 721BC2111D1DFF05002BC71E /* SUFileOperationConstants.m in Sources */ = {isa = PBXBuildFile; fileRef = 722954C31D04E66F00ECF9CA /* SUFileOperationConstants.m */; }; @@ -736,6 +737,8 @@ 7205C4331E12C23C00E370AE /* ConfigGenerateAppcast.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = ConfigGenerateAppcast.xcconfig; sourceTree = ""; }; 7205C4341E12C66D00E370AE /* ConfigGenerateAppcastRelease.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = ConfigGenerateAppcastRelease.xcconfig; sourceTree = ""; }; 7205C4351E12CA7000E370AE /* ConfigGenerateAppcastDebug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = ConfigGenerateAppcastDebug.xcconfig; sourceTree = ""; }; + 720767CD1E2DC37400F9A850 /* TerminationListener.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TerminationListener.h; sourceTree = ""; }; + 720767CE1E2DC37400F9A850 /* TerminationListener.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = TerminationListener.m; sourceTree = ""; }; 720B16421C66433D006985FB /* UITests-Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = "UITests-Info.plist"; path = "UITests/UITests-Info.plist"; sourceTree = SOURCE_ROOT; }; 720B16431C66433D006985FB /* SUTestApplicationTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SUTestApplicationTest.swift; path = UITests/SUTestApplicationTest.swift; sourceTree = SOURCE_ROOT; }; 7210C7671B9A9A1500EB90AC /* SUUnarchiverTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SUUnarchiverTest.swift; sourceTree = ""; }; @@ -1079,6 +1082,8 @@ 722954B51D04ADAF00ECF9CA /* fileop */, 55C14BB9136EEF1500649790 /* Autoupdate-Info.plist */, 55C14BD3136EEFCE00649790 /* Autoupdate.m */, + 720767CD1E2DC37400F9A850 /* TerminationListener.h */, + 720767CE1E2DC37400F9A850 /* TerminationListener.m */, ); path = Autoupdate; sourceTree = ""; @@ -1870,6 +1875,7 @@ 55C14F22136EF86000649790 /* SUStandardVersionComparator.m in Sources */, 55C14F20136EF84300649790 /* SUStatusController.m in Sources */, 55C14F23136EF86700649790 /* SUSystemProfiler.m in Sources */, + 720767CF1E2DC37400F9A850 /* TerminationListener.m in Sources */, E1EC2A301E21667000245715 /* SUTouchBarButtonGroup.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; diff --git a/Sparkle/Autoupdate/Autoupdate.m b/Sparkle/Autoupdate/Autoupdate.m index 06099eae..23f5dd58 100644 --- a/Sparkle/Autoupdate/Autoupdate.m +++ b/Sparkle/Autoupdate/Autoupdate.m @@ -7,67 +7,10 @@ #import "SUStatusController.h" #import "SULog.h" #import "SUInstallerProtocol.h" +#import "TerminationListener.h" #include -/*! - * Time this app uses to recheck if the parent has already died. - */ -static const NSTimeInterval SUParentQuitCheckInterval = .25; - -@interface TerminationListener : NSObject - -- (instancetype)initWithProcessId:(pid_t)pid; - -@end - -@interface TerminationListener () - -@property (nonatomic, assign) pid_t processIdentifier; -@property (nonatomic, strong) NSTimer *watchdogTimer; - -@end - -@implementation TerminationListener - -@synthesize processIdentifier = _processIdentifier; -@synthesize watchdogTimer = _watchdogTimer; - -- (instancetype)initWithProcessId:(pid_t)pid -{ - if (!(self = [super init])) { - return nil; - } - - self.processIdentifier = pid; - - return self; -} - -- (void)cleanupWithCompletion:(void (^)(void))completionBlock -{ - [self.watchdogTimer invalidate]; - completionBlock(); -} - -- (void)startListeningWithCompletion:(void (^)(void))completionBlock -{ - BOOL alreadyTerminated = (getppid() == 1); // ppid is launchd (1) => parent terminated already - if (alreadyTerminated) - [self cleanupWithCompletion:completionBlock]; - else - self.watchdogTimer = [NSTimer scheduledTimerWithTimeInterval:SUParentQuitCheckInterval target:self selector:@selector(watchdog:) userInfo:completionBlock repeats:YES]; -} - -- (void)watchdog:(NSTimer *)timer -{ - if (![NSRunningApplication runningApplicationWithProcessIdentifier:self.processIdentifier]) { - [self cleanupWithCompletion:timer.userInfo]; - } -} - -@end - /*! * If the Installation takes longer than this time the Application Icon is shown in the Dock so that the user has some feedback. */ @@ -128,7 +71,8 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.5; self.hostPath = hostPath; self.relaunchPath = relaunchPath; - self.terminationListener = [[TerminationListener alloc] initWithProcessId:parentProcessId]; + SULog(SULogLevelDefault, @"PID to listen: %d", parentProcessId); + self.terminationListener = [[TerminationListener alloc] initWithProcessIdentifier:@(parentProcessId)]; self.updateFolderPath = updateFolderPath; self.shouldRelaunch = shouldRelaunch; self.shouldShowUI = shouldShowUI; @@ -138,8 +82,16 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.5; - (void)applicationDidFinishLaunching:(NSNotification __unused *)notification { - [self.terminationListener startListeningWithCompletion:^{ + SULog(SULogLevelDefault, @"GONNA PID LISTEN"); + [self.terminationListener startListeningWithCompletion:^(BOOL terminationSuccess) { + SULog(SULogLevelDefault, @"LISTENING COMPLETION RESUME"); + self.terminationListener = nil; + + if (!terminationSuccess) { + SULog(SULogLevelError, @"Failed to listen for application termination"); + // Continue on with the installation anyway.. + } if (self.shouldShowUI) { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(SUInstallationTimeLimit * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ diff --git a/Sparkle/Autoupdate/TerminationListener.h b/Sparkle/Autoupdate/TerminationListener.h new file mode 100644 index 00000000..f097e941 --- /dev/null +++ b/Sparkle/Autoupdate/TerminationListener.h @@ -0,0 +1,24 @@ +// +// TerminationListener.h +// Sparkle +// +// Created by Mayur Pawashe on 3/7/16. +// Copyright © 2016 Sparkle Project. All rights reserved. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface TerminationListener : NSObject + +- (instancetype)initWithProcessIdentifier:(NSNumber * _Nullable)processIdentifier; + +@property (nonatomic, readonly) BOOL terminated; + +// If the process identifier provided was nil, then the completion block will invoke immediately with a YES success +- (void)startListeningWithCompletion:(void (^)(BOOL success))completionBlock; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Sparkle/Autoupdate/TerminationListener.m b/Sparkle/Autoupdate/TerminationListener.m new file mode 100644 index 00000000..8c20fd07 --- /dev/null +++ b/Sparkle/Autoupdate/TerminationListener.m @@ -0,0 +1,131 @@ +// +// TerminationListener.m +// Sparkle +// +// Created by Mayur Pawashe on 3/7/16. +// Copyright © 2016 Sparkle Project. All rights reserved. +// + +#import "TerminationListener.h" +#import "SULog.h" + +#include +#include +#include + + +#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; + +- (instancetype)initWithProcessIdentifier:(NSNumber * _Nullable)processIdentifier +{ + self = [super init]; + if (self != nil) { + _processIdentifier = processIdentifier; + } + + return self; +} + +- (BOOL)terminated +{ + return (self.watchedTermination || self.processIdentifier == nil) ? YES : (kill(self.processIdentifier.intValue, 0) != 0); +} + +- (void)invokeCompletionWithSuccess:(BOOL)success +{ + if (self.completionBlock != nil) { + self.completionBlock(success); + self.completionBlock = nil; + } +} + +- (void)startListeningWithCompletion:(void (^)(BOOL))completionBlock +{ + self.completionBlock = completionBlock; + + if (self.processIdentifier == nil) { + [self invokeCompletionWithSuccess:YES]; + return; + } + + // Use kqueues to determine when the process will terminate + // 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; + int queue = kqueue(); + if (queue == -1) { + SULog(SULogLevelError, @"Failed to create kqueue() due to error %d: %@", errno, @(strerror(errno))); + [self invokeCompletionWithSuccess:NO]; + return; + } + + struct kevent changes; + EV_SET(&changes, processIdentifier, EVFILT_PROC, EV_ADD | EV_RECEIPT, NOTE_EXIT, 0, NULL); + + if (kevent(queue, &changes, 1, &changes, 1, NULL) == -1) { + SULog(SULogLevelError, @"Failed to invoke kevent() due to error %d: %@", errno, @(strerror(errno))); + [self invokeCompletionWithSuccess:NO]; + return; + } + + // We will assume this terminationListener will never be deallocated +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wcast-qual" + CFFileDescriptorContext context = { 0, (void *)CFBridgingRetain(self), NULL, NULL, NULL }; +#pragma clang diagnostic pop + CFFileDescriptorRef noteExitKQueueRef = CFFileDescriptorCreate(NULL, queue, true, noteExitKQueueCallback, &context); + if (noteExitKQueueRef == NULL) { + SULog(SULogLevelError, @"Failed to create file descriptor via CFFileDescriptorCreate()"); + CFRelease((__bridge CFTypeRef)(self)); + [self invokeCompletionWithSuccess:NO]; + return; + } + + CFRunLoopSourceRef runLoopSource = CFFileDescriptorCreateRunLoopSource(NULL, noteExitKQueueRef, 0); + if (runLoopSource == NULL) { + SULog(SULogLevelError, @"Failed to create runLoopSource via CFFileDescriptorCreateRunLoopSource()"); + CFRelease((__bridge CFTypeRef)(self)); + [self invokeCompletionWithSuccess:NO]; + return; + } + + CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopDefaultMode); + CFRelease(runLoopSource); + + CFFileDescriptorEnableCallBacks(noteExitKQueueRef, kCFFileDescriptorReadCallBack); + + // Make sure we didn't set the listener callback to a dead PID + // If we did, we could hang forever. To avoid this, we check if the process has terminated *after* we set up the callback + // If we tried to do this check before setting the callback, we could run into an issue where the process can terminate after our check + // but before setting the callback + if ([self terminated]) { + [self invokeCompletionWithSuccess:YES]; + } +} + +static void noteExitKQueueCallback(CFFileDescriptorRef file, CFOptionFlags __unused callBackTypes, void *info) +{ + struct kevent event; + kevent(CFFileDescriptorGetNativeDescriptor(file), NULL, 0, &event, 1, NULL); + + TerminationListener *self = CFBridgingRelease(info); + self.watchedTermination = YES; + [self invokeCompletionWithSuccess:YES]; +} + +@end From 5c71eebf596689bd5e4ee3858422b65981da8057 Mon Sep 17 00:00:00 2001 From: Zorg Date: Thu, 19 Jan 2017 23:28:56 -0500 Subject: [PATCH 2/2] Remove nonsense logging I had for debugging purposes --- Sparkle/Autoupdate/Autoupdate.m | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/Sparkle/Autoupdate/Autoupdate.m b/Sparkle/Autoupdate/Autoupdate.m index 23f5dd58..0849ba0d 100644 --- a/Sparkle/Autoupdate/Autoupdate.m +++ b/Sparkle/Autoupdate/Autoupdate.m @@ -82,15 +82,12 @@ static const NSTimeInterval SUTerminationTimeDelay = 0.5; - (void)applicationDidFinishLaunching:(NSNotification __unused *)notification { - SULog(SULogLevelDefault, @"GONNA PID LISTEN"); [self.terminationListener startListeningWithCompletion:^(BOOL terminationSuccess) { - SULog(SULogLevelDefault, @"LISTENING COMPLETION RESUME"); - self.terminationListener = nil; if (!terminationSuccess) { SULog(SULogLevelError, @"Failed to listen for application termination"); - // Continue on with the installation anyway.. + // Continue on with the installation anyway? } if (self.shouldShowUI) {