|
| 1 | +import Darwin |
| 2 | +import Dispatch |
| 3 | +import Foundation |
| 4 | +import Observation |
| 5 | +import Security |
| 6 | + |
| 7 | +enum AppInstanceLockAcquisition { |
| 8 | + case acquired(AppInstanceLock) |
| 9 | + case busy |
| 10 | + case failed(String) |
| 11 | +} |
| 12 | + |
| 13 | +final class AppInstanceLock { |
| 14 | + /// Keep the descriptor open for the process lifetime. Never unlink the path: |
| 15 | + /// another opener could then lock a different inode and admit a duplicate. |
| 16 | + private let descriptor: Int32 |
| 17 | + |
| 18 | + private init(descriptor: Int32) { |
| 19 | + self.descriptor = descriptor |
| 20 | + } |
| 21 | + |
| 22 | + static func acquire(url: URL, waitMilliseconds: Int = 0) -> AppInstanceLockAcquisition { |
| 23 | + if let error = self.preparePrivateStateRoot(url.deletingLastPathComponent()) { |
| 24 | + return .failed(error) |
| 25 | + } |
| 26 | + let descriptor = Darwin.open(url.path, O_CREAT | O_RDWR | O_CLOEXEC | O_NOFOLLOW, 0o600) |
| 27 | + guard descriptor >= 0 else { return .failed(String(cString: strerror(errno))) } |
| 28 | + var status = stat() |
| 29 | + guard fstat(descriptor, &status) == 0, |
| 30 | + status.st_mode & mode_t(S_IFMT) == mode_t(S_IFREG), |
| 31 | + status.st_uid == geteuid() |
| 32 | + else { |
| 33 | + Darwin.close(descriptor) |
| 34 | + return .failed("Instance lock is not a safe file owned by the current user.") |
| 35 | + } |
| 36 | + _ = fchmod(descriptor, 0o600) |
| 37 | + let deadline = DispatchTime.now() + .milliseconds(max(0, waitMilliseconds)) |
| 38 | + while flock(descriptor, LOCK_EX | LOCK_NB) != 0 { |
| 39 | + guard errno == EWOULDBLOCK, DispatchTime.now() < deadline else { |
| 40 | + let result: AppInstanceLockAcquisition = errno == EWOULDBLOCK |
| 41 | + ? .busy |
| 42 | + : .failed(String(cString: strerror(errno))) |
| 43 | + Darwin.close(descriptor) |
| 44 | + return result |
| 45 | + } |
| 46 | + usleep(50000) |
| 47 | + } |
| 48 | + return .acquired(AppInstanceLock(descriptor: descriptor)) |
| 49 | + } |
| 50 | + |
| 51 | + private static func preparePrivateStateRoot(_ root: URL) -> String? { |
| 52 | + var status = stat() |
| 53 | + if lstat(root.path, &status) != 0 { |
| 54 | + guard errno == ENOENT else { return String(cString: strerror(errno)) } |
| 55 | + guard mkdir(root.path, 0o700) == 0 else { return String(cString: strerror(errno)) } |
| 56 | + guard lstat(root.path, &status) == 0 else { return String(cString: strerror(errno)) } |
| 57 | + } |
| 58 | + guard status.st_mode & mode_t(S_IFMT) == mode_t(S_IFDIR), |
| 59 | + status.st_uid == geteuid(), |
| 60 | + status.st_mode & 0o777 == 0o700 |
| 61 | + else { |
| 62 | + return "App profile state directory must be an owner-only 0700 directory." |
| 63 | + } |
| 64 | + return nil |
| 65 | + } |
| 66 | + |
| 67 | + deinit { |
| 68 | + _ = flock(self.descriptor, LOCK_UN) |
| 69 | + Darwin.close(self.descriptor) |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +@MainActor |
| 74 | +protocol UpdaterProviding: AnyObject { |
| 75 | + var automaticallyChecksForUpdates: Bool { get set } |
| 76 | + var automaticallyDownloadsUpdates: Bool { get set } |
| 77 | + var isAvailable: Bool { get } |
| 78 | + var updateStatus: UpdateStatus { get } |
| 79 | + func start() |
| 80 | + func startAfterResolvingGatewayUpdateChannel() |
| 81 | + func checkForUpdates(_ sender: Any?) |
| 82 | +} |
| 83 | + |
| 84 | +extension UpdaterProviding { |
| 85 | + func start() {} |
| 86 | + |
| 87 | + func startAfterResolvingGatewayUpdateChannel() { |
| 88 | + self.start() |
| 89 | + } |
| 90 | +} |
| 91 | + |
| 92 | +/// No-op updater used for debug/dev runs to suppress Sparkle dialogs. |
| 93 | +final class DisabledUpdaterController: UpdaterProviding { |
| 94 | + var automaticallyChecksForUpdates: Bool = false |
| 95 | + var automaticallyDownloadsUpdates: Bool = false |
| 96 | + let isAvailable: Bool = false |
| 97 | + let updateStatus = UpdateStatus() |
| 98 | + func checkForUpdates(_: Any?) {} |
| 99 | +} |
| 100 | + |
| 101 | +@MainActor |
| 102 | +@Observable |
| 103 | +final class UpdateStatus { |
| 104 | + var isUpdateReady: Bool |
| 105 | + |
| 106 | + init(isUpdateReady: Bool = false) { |
| 107 | + self.isUpdateReady = isUpdateReady |
| 108 | + } |
| 109 | +} |
| 110 | + |
| 111 | +#if canImport(Sparkle) |
| 112 | +import Sparkle |
| 113 | + |
| 114 | +@MainActor |
| 115 | +final class SparkleUpdaterController: NSObject, UpdaterProviding { |
| 116 | + private lazy var controller = SPUStandardUpdaterController( |
| 117 | + startingUpdater: false, |
| 118 | + updaterDelegate: self, |
| 119 | + userDriverDelegate: nil) |
| 120 | + let updateStatus = UpdateStatus() |
| 121 | + private var started = false |
| 122 | + private var gatewayUpdateChannel: String? |
| 123 | + private var resolvingGatewayUpdateChannel = false |
| 124 | + private let gatewayUpdateChannelResolver: @MainActor @Sendable () async throws -> String? |
| 125 | + private let onStart: (() -> Void)? |
| 126 | + |
| 127 | + init( |
| 128 | + savedAutoUpdate: Bool, |
| 129 | + gatewayUpdateChannelResolver: (@MainActor @Sendable () async throws -> String?)? = nil, |
| 130 | + onStart: (() -> Void)? = nil) |
| 131 | + { |
| 132 | + self.gatewayUpdateChannelResolver = gatewayUpdateChannelResolver ?? { |
| 133 | + struct UpdateStatusResponse: Decodable { |
| 134 | + let effectiveChannel: String? |
| 135 | + } |
| 136 | + guard let data = try? await GatewayConnection.shared.requestRaw( |
| 137 | + method: "update.status", |
| 138 | + timeoutMs: 5000), |
| 139 | + let response = try? JSONDecoder().decode(UpdateStatusResponse.self, from: data) |
| 140 | + else { return nil } |
| 141 | + return OpenClawConfigFile.normalizedGatewayUpdateChannel(response.effectiveChannel) |
| 142 | + } |
| 143 | + self.onStart = onStart |
| 144 | + super.init() |
| 145 | + let updater = self.controller.updater |
| 146 | + updater.automaticallyChecksForUpdates = savedAutoUpdate |
| 147 | + updater.automaticallyDownloadsUpdates = savedAutoUpdate |
| 148 | + } |
| 149 | + |
| 150 | + func start() { |
| 151 | + guard !self.started else { return } |
| 152 | + self.started = true |
| 153 | + if let onStart = self.onStart { |
| 154 | + onStart() |
| 155 | + } else { |
| 156 | + self.controller.startUpdater() |
| 157 | + } |
| 158 | + } |
| 159 | + |
| 160 | + func startAfterResolvingGatewayUpdateChannel() { |
| 161 | + guard !self.started, !self.resolvingGatewayUpdateChannel else { return } |
| 162 | + self.resolvingGatewayUpdateChannel = true |
| 163 | + Task { @MainActor [weak self] in |
| 164 | + guard let self else { return } |
| 165 | + defer { self.resolvingGatewayUpdateChannel = false } |
| 166 | + self.gatewayUpdateChannel = try? await self.gatewayUpdateChannelResolver() |
| 167 | + // Older or unreachable Gateways cannot report effectiveChannel. Preserve |
| 168 | + // their existing stable Sparkle behavior instead of disabling updates. |
| 169 | + self.start() |
| 170 | + } |
| 171 | + } |
| 172 | + |
| 173 | + var automaticallyChecksForUpdates: Bool { |
| 174 | + get { self.controller.updater.automaticallyChecksForUpdates } |
| 175 | + set { self.controller.updater.automaticallyChecksForUpdates = newValue } |
| 176 | + } |
| 177 | + |
| 178 | + var automaticallyDownloadsUpdates: Bool { |
| 179 | + get { self.controller.updater.automaticallyDownloadsUpdates } |
| 180 | + set { self.controller.updater.automaticallyDownloadsUpdates = newValue } |
| 181 | + } |
| 182 | + |
| 183 | + var isAvailable: Bool { |
| 184 | + self.started |
| 185 | + } |
| 186 | + |
| 187 | + func checkForUpdates(_ sender: Any?) { |
| 188 | + guard self.started else { return } |
| 189 | + self.controller.checkForUpdates(sender) |
| 190 | + } |
| 191 | + |
| 192 | + func updater(_: SPUUpdater, didDownloadUpdate _: SUAppcastItem) { |
| 193 | + self.updateStatus.isUpdateReady = true |
| 194 | + } |
| 195 | + |
| 196 | + func updater(_: SPUUpdater, failedToDownloadUpdate _: SUAppcastItem, error _: Error) { |
| 197 | + self.updateStatus.isUpdateReady = false |
| 198 | + } |
| 199 | + |
| 200 | + func userDidCancelDownload(_: SPUUpdater) { |
| 201 | + self.updateStatus.isUpdateReady = false |
| 202 | + } |
| 203 | + |
| 204 | + // periphery:ignore - Sparkle invokes this optional Objective-C delegate callback dynamically. |
| 205 | + func updater( |
| 206 | + _: SPUUpdater, |
| 207 | + userDidMakeChoice choice: SPUUserUpdateChoice, |
| 208 | + forUpdate _: SUAppcastItem, |
| 209 | + state: SPUUserUpdateState) |
| 210 | + { |
| 211 | + switch choice { |
| 212 | + case .install, .skip: |
| 213 | + self.updateStatus.isUpdateReady = false |
| 214 | + case .dismiss: |
| 215 | + self.updateStatus.isUpdateReady = (state.stage == .downloaded) |
| 216 | + @unknown default: |
| 217 | + self.updateStatus.isUpdateReady = false |
| 218 | + } |
| 219 | + } |
| 220 | +} |
| 221 | + |
| 222 | +func allowedSparkleChannels(forGatewayUpdateChannel channel: String?) -> Set<String> { |
| 223 | + switch channel { |
| 224 | + case "beta", "dev": |
| 225 | + ["beta"] |
| 226 | + case "extended-stable": |
| 227 | + ["extended-stable"] |
| 228 | + default: |
| 229 | + [] |
| 230 | + } |
| 231 | +} |
| 232 | + |
| 233 | +func isSparkleUpdateAllowed(itemChannel: String?, forGatewayUpdateChannel channel: String?) -> Bool { |
| 234 | + channel != "extended-stable" || itemChannel == "extended-stable" |
| 235 | +} |
| 236 | + |
| 237 | +extension SparkleUpdaterController: SPUUpdaterDelegate { |
| 238 | + func allowedChannels(for _: SPUUpdater) -> Set<String> { |
| 239 | + allowedSparkleChannels( |
| 240 | + forGatewayUpdateChannel: self.gatewayUpdateChannel ?? OpenClawConfigFile.gatewayUpdateChannel()) |
| 241 | + } |
| 242 | + |
| 243 | + func bestValidUpdate(in appcast: SUAppcast, for _: SPUUpdater) -> SUAppcastItem? { |
| 244 | + guard self.gatewayUpdateChannel ?? OpenClawConfigFile.gatewayUpdateChannel() == "extended-stable" else { |
| 245 | + return nil |
| 246 | + } |
| 247 | + let comparator = SUStandardVersionComparator.default |
| 248 | + let currentVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String |
| 249 | + // Sparkle always admits the default channel. Filter it here so an |
| 250 | + // extended-stable Gateway is never prompted to leave its release train. |
| 251 | + let eligibleItems = appcast.items.filter { |
| 252 | + guard isSparkleUpdateAllowed( |
| 253 | + itemChannel: $0.channel, |
| 254 | + forGatewayUpdateChannel: "extended-stable") |
| 255 | + else { return false } |
| 256 | + guard let currentVersion else { return true } |
| 257 | + return comparator.compareVersion( |
| 258 | + $0.versionString, |
| 259 | + toVersion: currentVersion) == .orderedDescending |
| 260 | + } |
| 261 | + return eligibleItems.max { left, right in |
| 262 | + comparator.compareVersion(left.versionString, toVersion: right.versionString) == .orderedAscending |
| 263 | + } |
| 264 | + } |
| 265 | + |
| 266 | + func updater(_: SPUUpdater, willInstallUpdate item: SUAppcastItem) { |
| 267 | + guard let currentVersion = GatewayEnvironment.appVersionString() else { return } |
| 268 | + PostAppUpdateReceiptStore.record( |
| 269 | + fromVersion: currentVersion, |
| 270 | + toVersion: item.displayVersionString) |
| 271 | + } |
| 272 | +} |
| 273 | + |
| 274 | +private func isDeveloperIDSigned(bundleURL: URL) -> Bool { |
| 275 | + var staticCode: SecStaticCode? |
| 276 | + guard SecStaticCodeCreateWithPath(bundleURL as CFURL, SecCSFlags(), &staticCode) == errSecSuccess, |
| 277 | + let code = staticCode |
| 278 | + else { return false } |
| 279 | + |
| 280 | + var infoCF: CFDictionary? |
| 281 | + guard SecCodeCopySigningInformation(code, SecCSFlags(rawValue: kSecCSSigningInformation), &infoCF) == errSecSuccess, |
| 282 | + let info = infoCF as? [String: Any], |
| 283 | + let certs = info[kSecCodeInfoCertificates as String] as? [SecCertificate], |
| 284 | + let leaf = certs.first |
| 285 | + else { |
| 286 | + return false |
| 287 | + } |
| 288 | + |
| 289 | + if let summary = SecCertificateCopySubjectSummary(leaf) as String? { |
| 290 | + return summary.hasPrefix("Developer ID Application:") |
| 291 | + } |
| 292 | + return false |
| 293 | +} |
| 294 | + |
| 295 | +@MainActor |
| 296 | +func makeUpdaterController() -> UpdaterProviding { |
| 297 | + guard AppProfile.current.validationError == nil, !AppProfile.current.isActive else { |
| 298 | + return DisabledUpdaterController() |
| 299 | + } |
| 300 | + let bundleURL = Bundle.main.bundleURL |
| 301 | + let isBundledApp = bundleURL.pathExtension == "app" |
| 302 | + guard isBundledApp, isDeveloperIDSigned(bundleURL: bundleURL) else { return DisabledUpdaterController() } |
| 303 | + |
| 304 | + let defaults = AppDefaults.standard |
| 305 | + let autoUpdateKey = "autoUpdateEnabled" |
| 306 | + // Default to true; honor the user's last choice otherwise. |
| 307 | + let savedAutoUpdate = (defaults.object(forKey: autoUpdateKey) as? Bool) ?? true |
| 308 | + return SparkleUpdaterController(savedAutoUpdate: savedAutoUpdate) |
| 309 | +} |
| 310 | +#else |
| 311 | +@MainActor |
| 312 | +func makeUpdaterController() -> UpdaterProviding { |
| 313 | + DisabledUpdaterController() |
| 314 | +} |
| 315 | +#endif |
0 commit comments