xtool.git
Publicgit clone https://git.maproj.org/xtool.gitxtool.git / Sources / XKit / Integration / IntegratedInstaller.swift
IntegratedInstaller.swift327 lines · 10.6 KiBRaw
| 1 | import Foundation |
| 2 | import SwiftyMobileDevice |
| 3 | import ConcurrencyExtras |
| 4 | import Dependencies |
| 5 | import XUtils |
| 6 | |
| 7 | extension LockdownClient { |
| 8 | static let installerLabel = "xtool" |
| 9 | } |
| 10 | |
| 11 | #if !os(iOS) |
| 12 | |
| 13 | public protocol IntegratedInstallerDelegate: AnyObject, Sendable { |
| 14 | func setPresentedMessage(_ message: IntegratedInstaller.Message?) |
| 15 | func installerDidUpdate(toStage stage: String, progress: Double?) |
| 16 | |
| 17 | // defaults to always returning true |
| 18 | func confirmRevocation(of certificates: [DeveloperServicesCertificate]) async -> Bool |
| 19 | } |
| 20 | |
| 21 | extension IntegratedInstallerDelegate { |
| 22 | public func confirmRevocation(of certificates: [DeveloperServicesCertificate]) async -> Bool { |
| 23 | true |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | public actor IntegratedInstaller { |
| 28 | |
| 29 | public enum Error: LocalizedError { |
| 30 | case alreadyInstalling |
| 31 | case deviceInfoFetchFailed |
| 32 | case noTeamFound |
| 33 | case appExtractionFailed |
| 34 | case appCorrupted |
| 35 | case appPackagingFailed |
| 36 | case pairingFailed |
| 37 | |
| 38 | public var errorDescription: String? { |
| 39 | "Installer.Error.\(self)" |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | public enum Message { |
| 44 | case pairDevice |
| 45 | case unlockDevice |
| 46 | } |
| 47 | |
| 48 | let auth: DeveloperAPIAuthData |
| 49 | public weak var delegate: IntegratedInstallerDelegate? |
| 50 | |
| 51 | @Dependency(\.zipCompressor) private var compressor |
| 52 | |
| 53 | private var appInstaller: AppInstaller? |
| 54 | |
| 55 | private var stage: String? |
| 56 | |
| 57 | private nonisolated let updateTask = LockIsolated<Task<Void, Never>?>(nil) |
| 58 | |
| 59 | private nonisolated func queueUpdateTask( |
| 60 | _ perform: @escaping @Sendable (isolated IntegratedInstaller) async -> Void |
| 61 | ) { |
| 62 | updateTask.withValue { task in |
| 63 | task = Task { [prev = task] in |
| 64 | await prev?.value |
| 65 | await perform(self) |
| 66 | } |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | private func updateStage( |
| 71 | to stage: String, |
| 72 | initialProgress: Double? = 0 |
| 73 | ) async throws { |
| 74 | await Task.yield() |
| 75 | try Task.checkCancellation() |
| 76 | updateStageIgnoringCancellation(to: stage, initialProgress: initialProgress) |
| 77 | } |
| 78 | |
| 79 | private func updateStageIgnoringCancellation( |
| 80 | to stage: String, |
| 81 | initialProgress: Double? = 0 |
| 82 | ) { |
| 83 | guard self.stage != stage else { return } |
| 84 | self.stage = stage |
| 85 | delegate?.installerDidUpdate(toStage: stage, progress: initialProgress) |
| 86 | } |
| 87 | |
| 88 | private func updateProgress(to progress: Double?) async throws { |
| 89 | await Task.yield() |
| 90 | try Task.checkCancellation() |
| 91 | updateProgressIgnoringCancellation(to: progress) |
| 92 | } |
| 93 | |
| 94 | private func updateProgressIgnoringCancellation(to progress: Double?) { |
| 95 | guard let stage = stage else { |
| 96 | preconditionFailure("Cannot change progress without setting stage at least once") |
| 97 | } |
| 98 | delegate?.installerDidUpdate(toStage: stage, progress: progress) |
| 99 | } |
| 100 | |
| 101 | public init( |
| 102 | auth: DeveloperAPIAuthData, |
| 103 | delegate: IntegratedInstallerDelegate |
| 104 | ) { |
| 105 | self.auth = auth |
| 106 | self.delegate = delegate |
| 107 | } |
| 108 | |
| 109 | private func performWithRecovery<T>( |
| 110 | repeatAfter: TimeInterval = 0.1, |
| 111 | block: () async throws -> sending T |
| 112 | ) async throws -> sending T { |
| 113 | var currMessage: Message? |
| 114 | |
| 115 | defer { |
| 116 | if currMessage != nil { |
| 117 | delegate?.setPresentedMessage(nil) |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | while true { |
| 122 | let nextMessage: Message |
| 123 | do { |
| 124 | return try await block() |
| 125 | } catch let error as LockdownClient.Error where error == .pairingDialogResponsePending { |
| 126 | nextMessage = .pairDevice |
| 127 | } catch let error as LockdownClient.Error where error == .passwordProtected { |
| 128 | nextMessage = .unlockDevice |
| 129 | } |
| 130 | if currMessage != nextMessage { |
| 131 | delegate?.setPresentedMessage(nextMessage) |
| 132 | currMessage = nextMessage |
| 133 | } |
| 134 | try await Task.sleep(seconds: repeatAfter) |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | private func fetchPairingKeys(with lockdownClient: LockdownClient, udid: String) async throws -> Data { |
| 139 | try lockdownClient.setValue(udid, forDomain: "com.apple.mobile.wireless_lockdown", key: "WirelessBuddyID") |
| 140 | try lockdownClient.setValue(true, forDomain: "com.apple.mobile.wireless_lockdown", key: "EnableWifiConnections") |
| 141 | |
| 142 | try await updateProgress(to: 2/3) |
| 143 | |
| 144 | // now create a new pair record based off the existing one, but replacing the |
| 145 | // SystemBUID and HostID. This is necessary because if two machines with the |
| 146 | // same HostID try accessing lockdown with the same device wirelessly, it'll |
| 147 | // fail during the heartbeat. The SystemBUID also has to be different because |
| 148 | // we can only have one HostID per SystemBUID on iOS 15+ |
| 149 | let oldRecord = try USBMux.pairRecord(forUDID: udid) |
| 150 | |
| 151 | var plistFormat: PropertyListSerialization.PropertyListFormat = .xml |
| 152 | guard var plist = try PropertyListSerialization |
| 153 | .propertyList(from: oldRecord, options: [], format: &plistFormat) |
| 154 | as? [String: Any], |
| 155 | let deviceCert = plist["DeviceCertificate"] as? Data, |
| 156 | let hostCert = plist["HostCertificate"] as? Data, |
| 157 | let rootCert = plist["RootCertificate"] as? Data, |
| 158 | let systemBUIDString = plist["SystemBUID"] as? String, |
| 159 | let systemBUID = UUID(uuidString: systemBUIDString) |
| 160 | else { throw Error.pairingFailed } |
| 161 | |
| 162 | var bytes = systemBUID.uuid |
| 163 | // byte 7 MSBs 4-7 are the uuid version field |
| 164 | // byte 8 MSBs 6-7 are the variant field |
| 165 | // everything else *should* be fair game to modify |
| 166 | // for UUID v4 |
| 167 | bytes.0 = ~bytes.0 |
| 168 | let newSystemBUID = UUID(uuid: bytes).uuidString |
| 169 | plist["SystemBUID"] = newSystemBUID |
| 170 | |
| 171 | let hostID = UUID().uuidString |
| 172 | plist["HostID"] = hostID |
| 173 | |
| 174 | let record = LockdownClient.PairRecord( |
| 175 | deviceCertificate: deviceCert, |
| 176 | hostCertificate: hostCert, |
| 177 | rootCertificate: rootCert, |
| 178 | hostID: hostID, |
| 179 | systemBUID: newSystemBUID |
| 180 | ) |
| 181 | try await performWithRecovery { |
| 182 | try lockdownClient.pair(withRecord: record) |
| 183 | } |
| 184 | |
| 185 | let data = try PropertyListSerialization.data( |
| 186 | fromPropertyList: plist, format: plistFormat, options: 0 |
| 187 | ) |
| 188 | |
| 189 | try await updateProgress(to: 1) |
| 190 | |
| 191 | return data |
| 192 | } |
| 193 | |
| 194 | @discardableResult |
| 195 | public func install( |
| 196 | app: URL, |
| 197 | udid: String, |
| 198 | lookupMode: LookupMode, |
| 199 | configureDevice: Bool, |
| 200 | ) async throws -> String { |
| 201 | try await self.updateStage(to: "Unpacking app", initialProgress: nil) |
| 202 | |
| 203 | let _tempDir = try TemporaryDirectory(name: "staging") |
| 204 | let tempDir = _tempDir.url |
| 205 | defer { withExtendedLifetime(_tempDir) {} } |
| 206 | |
| 207 | switch app.pathExtension { |
| 208 | case "ipa": |
| 209 | try await compressor.decompress( |
| 210 | file: app, |
| 211 | in: tempDir, |
| 212 | progress: { progress in |
| 213 | self.queueUpdateTask { |
| 214 | $0.updateProgressIgnoringCancellation(to: progress) |
| 215 | } |
| 216 | } |
| 217 | ) |
| 218 | case "app": |
| 219 | let payload = tempDir.appendingPathComponent("Payload") |
| 220 | let dest = payload.appendingPathComponent(app.lastPathComponent) |
| 221 | try FileManager.default.createDirectory(at: payload, withIntermediateDirectories: false) |
| 222 | try FileManager.default.copyItem(at: app, to: dest) |
| 223 | default: |
| 224 | throw Error.appExtractionFailed |
| 225 | } |
| 226 | |
| 227 | try await self.updateProgress(to: 1) |
| 228 | |
| 229 | let payload = tempDir.appendingPathComponent("Payload") |
| 230 | guard let appDir = payload.implicitContents.first(where: { $0.pathExtension == "app" }) |
| 231 | else { throw Error.appExtractionFailed } |
| 232 | |
| 233 | try await updateStage(to: "Preparing device") |
| 234 | |
| 235 | // TODO: Maybe use `Connection` here instead of creating the lockdown |
| 236 | // client manually? |
| 237 | let device = try Device(udid: udid, lookupMode: lookupMode) |
| 238 | |
| 239 | try await updateProgress(to: configureDevice ? 1/3 : 1/2) |
| 240 | |
| 241 | // we can't reuse any previously created client because we need to perform a handshake this time |
| 242 | let lockdownClient = try await performWithRecovery { |
| 243 | try LockdownClient( |
| 244 | device: device, |
| 245 | label: LockdownClient.installerLabel, |
| 246 | performHandshake: true |
| 247 | ) |
| 248 | } |
| 249 | |
| 250 | let deviceName = try lockdownClient.deviceName() |
| 251 | |
| 252 | let pairingKeys: Data? = if configureDevice { |
| 253 | try await fetchPairingKeys(with: lockdownClient, udid: udid) |
| 254 | } else { |
| 255 | nil |
| 256 | } |
| 257 | _ = pairingKeys |
| 258 | |
| 259 | try await updateProgress(to: 1) |
| 260 | |
| 261 | let bundleID = try await signInPlace( |
| 262 | app: appDir, |
| 263 | targetDevice: .init(udid: udid, name: deviceName), |
| 264 | ) |
| 265 | |
| 266 | try await self.updateStage(to: "Packaging", initialProgress: nil) |
| 267 | |
| 268 | let ipa = try await compressor.compress( |
| 269 | directory: payload, |
| 270 | progress: { progress in |
| 271 | self.queueUpdateTask { |
| 272 | $0.updateProgressIgnoringCancellation(to: progress) |
| 273 | } |
| 274 | } |
| 275 | ) |
| 276 | |
| 277 | try await self.updateProgress(to: 1) |
| 278 | |
| 279 | let appInstaller = AppInstaller(ipa: ipa, udid: udid, connectionPreferences: .init(lookupMode: lookupMode)) |
| 280 | self.appInstaller = appInstaller |
| 281 | try await appInstaller.install( |
| 282 | progress: { stage in |
| 283 | self.queueUpdateTask { |
| 284 | $0.updateStageIgnoringCancellation(to: stage.displayName) |
| 285 | $0.updateProgressIgnoringCancellation(to: stage.displayProgress) |
| 286 | } |
| 287 | } |
| 288 | ) |
| 289 | return bundleID |
| 290 | } |
| 291 | |
| 292 | @discardableResult |
| 293 | public func signInPlace( |
| 294 | app: URL, |
| 295 | targetDevice: SigningContext.TargetDevice? = nil, |
| 296 | ) async throws -> String { |
| 297 | let context = SigningContext( |
| 298 | auth: auth, |
| 299 | targetDevice: targetDevice, |
| 300 | ) |
| 301 | |
| 302 | let signer = AutoSigner(context: context) { certs in |
| 303 | await self.delegate?.confirmRevocation(of: certs) ?? false |
| 304 | } |
| 305 | |
| 306 | return try await signer.sign( |
| 307 | app: app, |
| 308 | status: { @Sendable status in |
| 309 | self.queueUpdateTask { |
| 310 | $0.updateStageIgnoringCancellation(to: status) |
| 311 | } |
| 312 | }, |
| 313 | progress: { progress in |
| 314 | self.queueUpdateTask { |
| 315 | $0.updateProgressIgnoringCancellation(to: progress) |
| 316 | } |
| 317 | }, |
| 318 | didProvision: { @Sendable [self] in |
| 319 | // TODO: reintroduce Superconfig |
| 320 | _ = self |
| 321 | } |
| 322 | ) |
| 323 | } |
| 324 | |
| 325 | } |
| 326 | |
| 327 | #endif |