|
| 1 | +import AppKit |
| 2 | +import Foundation |
| 3 | + |
| 4 | +// Diagnostic owner only: the separate, unchanged controller performs hide/activate. |
| 5 | +let arguments = CommandLine.arguments |
| 6 | +guard arguments.count == 5, arguments.dropFirst().allSatisfy({ $0.hasPrefix("/") }) else { |
| 7 | + fputs("Expected bundle, fixture ready, launch receipt and stop receipt paths\n", stderr) |
| 8 | + exit(64) |
| 9 | +} |
| 10 | +let bundleURL = URL(fileURLWithPath: arguments[1]).standardizedFileURL |
| 11 | +let readyURL = URL(fileURLWithPath: arguments[2]).standardizedFileURL |
| 12 | +let launchReceiptURL = URL(fileURLWithPath: arguments[3]).standardizedFileURL |
| 13 | +let stopReceiptURL = URL(fileURLWithPath: arguments[4]).standardizedFileURL |
| 14 | +let directory = bundleURL.deletingLastPathComponent() |
| 15 | +let files = FileManager.default |
| 16 | +guard bundleURL.pathExtension == "app", |
| 17 | + [bundleURL, readyURL, launchReceiptURL, stopReceiptURL].allSatisfy({ |
| 18 | + $0.resolvingSymlinksInPath() == $0 |
| 19 | + }), |
| 20 | + [readyURL, launchReceiptURL, stopReceiptURL].allSatisfy({ |
| 21 | + $0.deletingLastPathComponent() == directory && !files.fileExists(atPath: $0.path) |
| 22 | + }), |
| 23 | + Set([readyURL.path, launchReceiptURL.path, stopReceiptURL.path]).count == 3, |
| 24 | + let bundle = Bundle(url: bundleURL), |
| 25 | + let bundleIdentifier = bundle.bundleIdentifier, |
| 26 | + bundleIdentifier == "org.otzaria.identitycontrol", |
| 27 | + let executableURL = bundle.executableURL?.standardizedFileURL, |
| 28 | + files.isExecutableFile(atPath: executableURL.path) else { |
| 29 | + fputs("Initial launch requires the owned fixture bundle and fresh sibling receipts\n", stderr) |
| 30 | + exit(64) |
| 31 | +} |
| 32 | + |
| 33 | +let ownerApplication = NSApplication.shared |
| 34 | +_ = ownerApplication.setActivationPolicy(.accessory) |
| 35 | +let ownerPid = ProcessInfo.processInfo.processIdentifier |
| 36 | +let sessionToken = UUID().uuidString |
| 37 | +let configuration: [String: Any] = [ |
| 38 | + "createsNewApplicationInstance": true, "allowsRunningApplicationSubstitution": false, |
| 39 | + "hides": false, "hidesOthers": false, "activates": true, |
| 40 | + "addsToRecentItems": false, "promptsUserIfNeeded": false, "arguments": [readyURL.path] |
| 41 | +] |
| 42 | +var retainedApplication: NSRunningApplication? |
| 43 | +var identity: [String: Any] = [:] |
| 44 | +var identityEstablished = false |
| 45 | +var primaryError: [String: Any]? |
| 46 | +var cleanupErrors: [String] = [] |
| 47 | +var identityChecks: [[String: Any]] = [] |
| 48 | +var targetStateBeforeCleanup: [String: Any] = [:] |
| 49 | +var terminateReturnValue: Bool? |
| 50 | +var forceTerminateReturnValue: Bool? |
| 51 | +var launchPending = false |
| 52 | +var launchReceiptWritten = false |
| 53 | +var launchObserved = false |
| 54 | +var stopRequested = false |
| 55 | +var stopReason = "" |
| 56 | +var cleanupStarted = false |
| 57 | +var finished = false |
| 58 | +var cleanupTimer: Timer? |
| 59 | + |
| 60 | +func nullableBool(_ value: Bool?) -> Any { |
| 61 | + if let value = value { return value } |
| 62 | + return NSNull() |
| 63 | +} |
| 64 | + |
| 65 | +func recordError(_ stage: String, _ message: String, cleanup: Bool = false, |
| 66 | + nativeError: NSError? = nil) { |
| 67 | + var details: [String: Any] = [ |
| 68 | + "stage": stage, "message": message, "atMs": Date().timeIntervalSince1970 * 1000 |
| 69 | + ] |
| 70 | + if let nativeError = nativeError { |
| 71 | + details["domain"] = nativeError.domain |
| 72 | + details["code"] = nativeError.code |
| 73 | + details["description"] = nativeError.localizedDescription |
| 74 | + } |
| 75 | + if primaryError == nil { primaryError = details } |
| 76 | + if cleanup { cleanupErrors.append("\(stage): \(message)") } |
| 77 | + if let data = try? JSONSerialization.data(withJSONObject: details, options: [.sortedKeys]) { |
| 78 | + fputs(String(decoding: data, as: UTF8.self) + "\n", stderr) |
| 79 | + } |
| 80 | +} |
| 81 | + |
| 82 | +func snapshot(_ application: NSRunningApplication) -> [String: Any] { |
| 83 | + var launchMs: Any = NSNull() |
| 84 | + if let date = application.launchDate { launchMs = date.timeIntervalSince1970 * 1000 } |
| 85 | + return [ |
| 86 | + "pid": application.processIdentifier, "executable": application.executableURL?.path ?? "unavailable", |
| 87 | + "bundleURL": application.bundleURL?.path ?? "unavailable", |
| 88 | + "bundleIdentifier": application.bundleIdentifier ?? "unavailable", |
| 89 | + "launchMs": launchMs, |
| 90 | + "launchDateAvailability": application.launchDate == nil ? "unavailable" : "available", |
| 91 | + "isTerminated": application.isTerminated, "isFinishedLaunching": application.isFinishedLaunching, |
| 92 | + "activationPolicy": application.activationPolicy.rawValue |
| 93 | + ] |
| 94 | +} |
| 95 | + |
| 96 | +func verifyIdentity(_ stage: String) -> Bool { |
| 97 | + guard let application = retainedApplication else { return false } |
| 98 | + var check = snapshot(application) |
| 99 | + check["stage"] = stage |
| 100 | + let current = NSRunningApplication(processIdentifier: application.processIdentifier) |
| 101 | + let matches = !application.isTerminated |
| 102 | + && application.bundleURL?.standardizedFileURL == bundleURL |
| 103 | + && application.executableURL?.standardizedFileURL == executableURL |
| 104 | + && application.bundleIdentifier == bundleIdentifier |
| 105 | + && current.map({ application.isEqual($0) |
| 106 | + && $0.executableURL?.standardizedFileURL == executableURL |
| 107 | + && $0.bundleURL?.standardizedFileURL == bundleURL }) == true |
| 108 | + check["sameApplication"] = matches |
| 109 | + identityChecks.append(check) |
| 110 | + return matches |
| 111 | +} |
| 112 | + |
| 113 | +func commonReceipt() -> [String: Any] { |
| 114 | + var result = identity |
| 115 | + result["schemaVersion"] = 1 |
| 116 | + result["scope"] = "Owned fixture LaunchServices launch and cleanup; not an app quiet measurement" |
| 117 | + result["source"] = "NSWorkspace.openApplication" |
| 118 | + result["ownerPid"] = ownerPid |
| 119 | + result["sessionToken"] = sessionToken |
| 120 | + result["configuration"] = configuration |
| 121 | + result["identityMethod"] = "Retained NSWorkspace completion object and NSRunningApplication.isEqual" |
| 122 | + return result |
| 123 | +} |
| 124 | + |
| 125 | +func saveReceipt(_ result: [String: Any], at url: URL) throws { |
| 126 | + let data = try JSONSerialization.data(withJSONObject: result, options: [.sortedKeys]) |
| 127 | + guard data.count <= 65536 else { |
| 128 | + throw NSError(domain: "OwnedLaunchControl", code: 1, |
| 129 | + userInfo: [NSLocalizedDescriptionKey: "The ownership receipt exceeds 64 KiB"]) |
| 130 | + } |
| 131 | + try data.write(to: url, options: .atomic) |
| 132 | +} |
| 133 | + |
| 134 | +func recordFixtureLaunchId() { |
| 135 | + guard files.fileExists(atPath: readyURL.path), let pid = identity["pid"] as? Int32 else { return } |
| 136 | + do { |
| 137 | + let size = (try files.attributesOfItem(atPath: readyURL.path)[.size] as? NSNumber)?.intValue ?? 65537 |
| 138 | + guard size <= 65536, |
| 139 | + let value = try JSONSerialization.jsonObject(with: Data(contentsOf: readyURL)) as? [String: Any], |
| 140 | + (value["pid"] as? NSNumber)?.int32Value == pid, |
| 141 | + let launchId = value["launchId"] as? String, UUID(uuidString: launchId) != nil else { |
| 142 | + throw NSError(domain: "OwnedLaunchControl", code: 2, |
| 143 | + userInfo: [NSLocalizedDescriptionKey: "Fixture ready does not identify the retained launch"]) |
| 144 | + } |
| 145 | + identity["launchId"] = launchId |
| 146 | + } catch { |
| 147 | + recordError("fixtureReady", String(describing: error), cleanup: true) |
| 148 | + } |
| 149 | +} |
| 150 | + |
| 151 | +func finish() { |
| 152 | + guard !finished else { return } |
| 153 | + finished = true |
| 154 | + cleanupTimer?.invalidate() |
| 155 | + let exited = retainedApplication?.isTerminated == true |
| 156 | + if !exited && primaryError == nil { |
| 157 | + recordError("cleanup", "The retained target has not exited", cleanup: true) |
| 158 | + } |
| 159 | + recordFixtureLaunchId() |
| 160 | + var result = commonReceipt() |
| 161 | + let passed = primaryError == nil && cleanupErrors.isEmpty && exited && launchReceiptWritten |
| 162 | + result["status"] = passed ? "passed" : "failed" |
| 163 | + result["targetExited"] = exited |
| 164 | + result["stopReason"] = stopReason |
| 165 | + result["launchReceiptWritten"] = launchReceiptWritten |
| 166 | + result["targetStateBeforeCleanup"] = targetStateBeforeCleanup |
| 167 | + result["identityChecks"] = identityChecks |
| 168 | + result["terminateReturnValue"] = nullableBool(terminateReturnValue) |
| 169 | + result["forceTerminateReturnValue"] = nullableBool(forceTerminateReturnValue) |
| 170 | + result["cleanupErrors"] = cleanupErrors |
| 171 | + result["finishedAtMs"] = Date().timeIntervalSince1970 * 1000 |
| 172 | + if let error = primaryError { result["error"] = error } else { result["error"] = NSNull() } |
| 173 | + do { try saveReceipt(result, at: stopReceiptURL) } |
| 174 | + catch { |
| 175 | + recordError("stopReceipt", String(describing: error), cleanup: true) |
| 176 | + exit(1) |
| 177 | + } |
| 178 | + exit(passed ? 0 : 1) |
| 179 | +} |
| 180 | + |
| 181 | +func cleanUpRetainedTarget() { |
| 182 | + guard !finished, !cleanupStarted else { return } |
| 183 | + guard let application = retainedApplication else { |
| 184 | + if !launchPending { finish() } |
| 185 | + return |
| 186 | + } |
| 187 | + cleanupStarted = true |
| 188 | + targetStateBeforeCleanup = snapshot(application) |
| 189 | + if application.isTerminated { finish(); return } |
| 190 | + guard identityEstablished, verifyIdentity("beforeTerminate") else { |
| 191 | + recordError("cleanupIdentity", "The completion object no longer identifies the owned target", cleanup: true) |
| 192 | + finish() |
| 193 | + return |
| 194 | + } |
| 195 | + terminateReturnValue = application.terminate() |
| 196 | + if terminateReturnValue != true { |
| 197 | + recordError("terminate", "The retained target refused normal termination", cleanup: true) |
| 198 | + } |
| 199 | + let deadline = ProcessInfo.processInfo.systemUptime + 5 |
| 200 | + var forceDeadline: TimeInterval? |
| 201 | + let timer = Timer(timeInterval: 0.05, repeats: true) { timer in |
| 202 | + if application.isTerminated { timer.invalidate(); finish(); return } |
| 203 | + if let forceDeadline = forceDeadline { |
| 204 | + if ProcessInfo.processInfo.systemUptime >= forceDeadline { |
| 205 | + recordError("forceTerminate", "The retained target did not exit within two seconds", cleanup: true) |
| 206 | + timer.invalidate() |
| 207 | + finish() |
| 208 | + } |
| 209 | + return |
| 210 | + } |
| 211 | + if ProcessInfo.processInfo.systemUptime >= deadline { |
| 212 | + recordError("terminate", "Normal target cleanup exceeded five seconds", cleanup: true) |
| 213 | + guard verifyIdentity("beforeForceTerminate") else { |
| 214 | + recordError("cleanupIdentity", "Identity changed before forced owned-target cleanup", cleanup: true) |
| 215 | + timer.invalidate() |
| 216 | + finish() |
| 217 | + return |
| 218 | + } |
| 219 | + forceTerminateReturnValue = application.forceTerminate() |
| 220 | + if forceTerminateReturnValue != true { |
| 221 | + recordError("forceTerminate", "The retained target refused forced cleanup", cleanup: true) |
| 222 | + } |
| 223 | + forceDeadline = ProcessInfo.processInfo.systemUptime + 2 |
| 224 | + } |
| 225 | + } |
| 226 | + cleanupTimer = timer |
| 227 | + RunLoop.main.add(timer, forMode: .common) |
| 228 | +} |
| 229 | + |
| 230 | +func requestStop(_ reason: String) { |
| 231 | + guard !finished else { return } |
| 232 | + if !stopRequested { |
| 233 | + stopRequested = true |
| 234 | + stopReason = reason |
| 235 | + if launchPending { |
| 236 | + // A late completion still belongs to us and must be cleaned up before exit. |
| 237 | + DispatchQueue.main.asyncAfter(deadline: .now() + 5) { |
| 238 | + if launchPending && !finished { |
| 239 | + recordError("cleanup", "Launch completion never supplied an owned object", cleanup: true) |
| 240 | + finish() |
| 241 | + } |
| 242 | + } |
| 243 | + } |
| 244 | + } |
| 245 | + cleanUpRetainedTarget() |
| 246 | +} |
| 247 | + |
| 248 | +func launchTarget() { |
| 249 | + let existing = NSRunningApplication.runningApplications(withBundleIdentifier: bundleIdentifier) |
| 250 | + .filter { !$0.isTerminated && $0.bundleURL?.standardizedFileURL == bundleURL } |
| 251 | + guard existing.isEmpty else { |
| 252 | + recordError("launch", "An instance of the owned fixture was already running") |
| 253 | + requestStop("preexistingTarget") |
| 254 | + return |
| 255 | + } |
| 256 | + let options = NSWorkspace.OpenConfiguration() |
| 257 | + options.createsNewApplicationInstance = true |
| 258 | + options.allowsRunningApplicationSubstitution = false |
| 259 | + options.hides = false |
| 260 | + options.hidesOthers = false |
| 261 | + options.activates = true |
| 262 | + options.addsToRecentItems = false |
| 263 | + options.promptsUserIfNeeded = false |
| 264 | + options.arguments = [readyURL.path] |
| 265 | + launchPending = true |
| 266 | + NSWorkspace.shared.openApplication(at: bundleURL, configuration: options) { application, error in |
| 267 | + // AppKit invokes this completion on a concurrent queue. |
| 268 | + DispatchQueue.main.async { |
| 269 | + launchPending = false |
| 270 | + if let error = error { |
| 271 | + recordError("launch", "LaunchServices returned an error", nativeError: error as NSError) |
| 272 | + } |
| 273 | + if let application = application { |
| 274 | + retainedApplication = application |
| 275 | + if verifyIdentity("launchCompletion") { |
| 276 | + identityEstablished = true |
| 277 | + identity = snapshot(application) |
| 278 | + identity["sameApplication"] = true |
| 279 | + } else { |
| 280 | + recordError("launchIdentity", "The completion object does not identify the requested live fixture") |
| 281 | + } |
| 282 | + } else if error == nil { |
| 283 | + recordError("launch", "LaunchServices returned neither an application nor an error") |
| 284 | + } |
| 285 | + guard error == nil, identityEstablished else { |
| 286 | + requestStop("launchError") |
| 287 | + return |
| 288 | + } |
| 289 | + var result = commonReceipt() |
| 290 | + result["status"] = "launched" |
| 291 | + result["observedAtMs"] = Date().timeIntervalSince1970 * 1000 |
| 292 | + do { |
| 293 | + try saveReceipt(result, at: launchReceiptURL) |
| 294 | + launchReceiptWritten = true |
| 295 | + } catch { |
| 296 | + recordError("launchReceipt", String(describing: error)) |
| 297 | + requestStop("launchReceipt") |
| 298 | + return |
| 299 | + } |
| 300 | + if stopRequested { cleanUpRetainedTarget() } |
| 301 | + } |
| 302 | + } |
| 303 | + DispatchQueue.main.asyncAfter(deadline: .now() + 15) { |
| 304 | + if launchPending && !finished { |
| 305 | + recordError("launch", "Initial LaunchServices launch exceeded 15 seconds") |
| 306 | + requestStop("launchTimeout") |
| 307 | + } |
| 308 | + } |
| 309 | +} |
| 310 | + |
| 311 | +let observer = NotificationCenter.default.addObserver( |
| 312 | + forName: NSApplication.didFinishLaunchingNotification, object: ownerApplication, queue: nil |
| 313 | +) { _ in |
| 314 | + guard !launchObserved else { return } |
| 315 | + launchObserved = true |
| 316 | + DispatchQueue.main.async { |
| 317 | + guard Thread.isMainThread, ownerApplication.isRunning, |
| 318 | + ownerApplication.activationPolicy() == .accessory else { |
| 319 | + recordError("startup", "The ownership helper requires a running AppKit main loop") |
| 320 | + requestStop("startup") |
| 321 | + return |
| 322 | + } |
| 323 | + launchTarget() |
| 324 | + Thread.detachNewThread { |
| 325 | + let line = readLine() |
| 326 | + DispatchQueue.main.async { |
| 327 | + if let line = line, line != "stop" { |
| 328 | + recordError("command", "The ownership helper accepts only stop or EOF") |
| 329 | + } |
| 330 | + requestStop(line == nil ? "EOF" : "stop") |
| 331 | + } |
| 332 | + } |
| 333 | + } |
| 334 | +} |
| 335 | +DispatchQueue.main.asyncAfter(deadline: .now() + 5) { |
| 336 | + if !launchObserved { |
| 337 | + recordError("startup", "The ownership helper did not finish launching") |
| 338 | + requestStop("startupTimeout") |
| 339 | + } |
| 340 | +} |
| 341 | +DispatchQueue.main.asyncAfter(deadline: .now() + 60) { |
| 342 | + if !finished { |
| 343 | + recordError("lifetime", "The diagnostic ownership lifetime exceeded 60 seconds") |
| 344 | + requestStop("lifetimeTimeout") |
| 345 | + } |
| 346 | +} |
| 347 | +ownerApplication.run() |
0 commit comments