Skip to content

armgit / xtool

Public Imported from GitHub
0

Cross-platform Xcode replacement. Build and deploy iOS apps with SwiftPM on Linux, Windows, macOS.

Add support for UPnP port forwarding, rework usbmuxd shim

kabiroberaia61c8fdc0fab
diff --git a/Supersign/Installation/AppInstaller.swift b/Supersign/Installation/AppInstaller.swift
index fdb727d..c11726a 100644
--- a/Supersign/Installation/AppInstaller.swift
+++ b/Supersign/Installation/AppInstaller.swift
@@ -9,7 +9,7 @@
import Foundation
import SwiftyMobileDevice
-public class AppInstaller {
+public final class AppInstaller {
public enum Error: LocalizedError {
case userCancelled
@@ -106,10 +106,9 @@ public class AppInstaller {
defer { needsCancellation = false }
try cancelPoint()
- let connection = try Connection(udid: udid, pairingKeys: pairingKeys) {
+ let connection = try Connection.connection(forUDID: udid, pairingKeys: pairingKeys) {
progress(.connecting($0 * 4/6))
}
- defer { connection.close() }
try cancelPoint()
@@ -135,6 +134,8 @@ public class AppInstaller {
try installer.install(uploaded: uploaded) { currentProgress in
progress(.installing(currentProgress.details, currentProgress.progress))
}
+
+ _ = connection
}
public func install(
diff --git a/Supersign/Installation/Connection.swift b/Supersign/Installation/Connection.swift
index 0e21cbc..c447a28 100644
--- a/Supersign/Installation/Connection.swift
+++ b/Supersign/Installation/Connection.swift
@@ -9,21 +9,70 @@
import Foundation
import SwiftyMobileDevice
+#if os(iOS)
+import libusbmuxd_ios
+
+public typealias PairingKeys = Data
+
+private extension USBMuxSimulator {
+ func performAtomically<T>(_ operation: (USBMuxSimulator) -> T) -> T {
+ var value: T!
+ __performAtomically { value = operation($0) }
+ return value
+ }
+
+ func performAtomically<T>(_ operation: (USBMuxSimulator) throws -> T) throws -> T {
+ var value: Result<T, Error>!
+ __performAtomically { sim in
+ value = Result { try operation(sim) }
+ }
+ return try value.get()
+ }
+}
+#else
+public typealias PairingKeys = Void
+#endif
+
+private class WeakBox<T: AnyObject> {
+ weak var value: T?
+ init(_ value: T) { self.value = value }
+}
+
+// there is guaranteed to be at most one Connection instance per udid
+// at any moment, thanks to Connection.connection(...). Consequently
+// there is at most one device per udid at any moment too.
public class Connection {
private static let label = "supersign"
- public private(set) var isClosed = false
+ private static var connections: [String: WeakBox<Connection>] = [:]
+ private static let connectionsQueue = DispatchQueue(label: "connections-queue")
- private let usbmuxHandler: USBMuxHandler
+ #if os(iOS)
+ private var handle: Int32
+ private let heartbeatHandler: HeartbeatHandler
+ #endif
+ private let udid: String
public let device: Device
public let client: LockdownClient
- private let heartbeatHandler: HeartbeatHandler
- public init(udid: String, pairingKeys: PairingKeys, progress: (Double) -> Void) throws {
+ private init(udid: String, pairingKeys: PairingKeys, progress: (Double) -> Void) throws {
progress(0/4)
- usbmuxHandler = try USBMuxHandler(udid: udid, pairingKeys: pairingKeys)
+ self.udid = udid
+
+ #if os(iOS)
+ let simulatedDevice: USBMuxSimulatedDevice
+ var ip = in_addr()
+ if usbmux_forwarded_ip(&ip) == 0 {
+ NSLog("[SuperUSB] %@", "Using port forwarded device with ip \(String(cString: inet_ntoa(ip)!))")
+ simulatedDevice = PortForwardedDevice(ip: ip, pairingKeys: pairingKeys, udid: udid)
+ } else {
+ NSLog("[SuperUSB] %@", "Using VPN device")
+ simulatedDevice = try VPNDevice(pairingKeys: pairingKeys, udid: udid)
+ }
+ handle = USBMuxSimulator.shared.performAtomically { $0.register(device: simulatedDevice) }
+ #endif
progress(1/4)
device = try Device(udid: udid)
@@ -32,18 +81,40 @@ public class Connection {
client = try LockdownClient(device: device, label: Self.label, performHandshake: true)
progress(3/4)
+ #if os(iOS)
heartbeatHandler = HeartbeatHandler(device: device, client: client)
+ #endif
progress(4/4)
}
- deinit { close() }
-
- public func close() {
- guard !isClosed else { return }
- isClosed = true
+ public static func connection(
+ forUDID udid: String,
+ pairingKeys: PairingKeys,
+ progress: (Double) -> Void
+ ) throws -> Connection {
+ try connectionsQueue.sync {
+ progress(0)
+ if let conn = connections[udid]?.value {
+ progress(1)
+ return conn
+ }
+ let conn = try Connection(udid: udid, pairingKeys: pairingKeys, progress: progress)
+ connections[udid] = WeakBox(conn)
+ return conn
+ }
+ }
+ deinit {
+ // we could nil out connections[udid] here but that might lead to
+ // weird race conditions against Connection.connection that seem
+ // like a nightmare to diagnose, and storing an empty box for a
+ // udid isn't much memory anyway
+ #if os(iOS)
heartbeatHandler.stop()
- usbmuxHandler.stop()
+ _ = USBMuxSimulator.shared.performAtomically {
+ $0.deregisterDevice(forHandle: handle)
+ }
+ #endif
}
public func startClient<T: LockdownService>(_ type: T.Type = T.self, sendEscrowBag: Bool = false) throws -> T {
diff --git a/Supersign/Installation/HeartbeatHandler.swift b/Supersign/Installation/HeartbeatHandler.swift
index 723d1d2..45b22d7 100644
--- a/Supersign/Installation/HeartbeatHandler.swift
+++ b/Supersign/Installation/HeartbeatHandler.swift
@@ -9,23 +9,7 @@
import Foundation
import SwiftyMobileDevice
-#warning("We should have a shared heartbeat internally")
-// because otherwise if two connections are attempted simultaneously,
-// the concurrent heartbeats will fail. Basically, let the interface
-// continue to look like you have multiple HeartbeatHandlers, but
-// internally maintain a refcount to a shared structure that maintains
-// a common heartbeat while the refcount > 0.
-//
-// Or maybe take the abstraction up a layer to `Connection`, or somehow
-// put it in USBMuxHandler? Since in fact that probably needs to be
-// common too. In fact both of those things seem to basically be what
-// the usbmuxd daemon does, so maybe refactor them into a single
-// USBMuxDaemonShim or something, which internally has a single connection
-// for each device. Alternatively, refactor `Connection` to behave like that?
-
-#if os(iOS)
-public class HeartbeatHandler {
-
+public final class HeartbeatHandler {
private struct Error: Swift.Error {}
private struct ReceivedPacket: Decodable {
@@ -135,11 +119,4 @@ public class HeartbeatHandler {
defer { stopLock.unlock() }
isStopped = true
}
-
-}
-#else
-public class HeartbeatHandler {
- public init(device: Device, client: LockdownClient) {}
- public func stop() {}
}
-#endif
diff --git a/Supersign/Installation/IPAInstaller.swift b/Supersign/Installation/IPAInstaller.swift
index a8817ca..9c190ea 100644
--- a/Supersign/Installation/IPAInstaller.swift
+++ b/Supersign/Installation/IPAInstaller.swift
@@ -9,7 +9,7 @@
import Foundation
import SwiftyMobileDevice
-public class IPAInstaller {
+public final class IPAInstaller {
private let client: InstallationProxyClient
public init(connection: Connection) throws {
diff --git a/Supersign/Installation/IPAUploader.swift b/Supersign/Installation/IPAUploader.swift
index 12c9d6d..4c5cbf2 100644
--- a/Supersign/Installation/IPAUploader.swift
+++ b/Supersign/Installation/IPAUploader.swift
@@ -40,25 +40,7 @@ public final class IPAUploader {
self.client = try connection.startClient()
}
- private func uploadSymlink(_ src: URL, to dest: URL, progress: (Double) -> Void) throws {
- let symlinkDest = try FileManager.default.destinationOfSymbolicLink(atPath: src.path)
- try client.linkItem(at: URL(fileURLWithPath: symlinkDest), to: dest, type: .symlink)
- }
-
- private func uploadDir(_ src: URL, to dest: URL, progress: (Double) -> Void) throws {
- try client.createDirectory(at: dest)
- let contents = try src.contents()
- let numFiles = contents.count
- let progressPerFile = 1 / Double(numFiles)
- var baseProgress: Double = 0
- for file in contents {
- let fileDest = dest.appendingPathComponent(file.lastPathComponent)
- try upload(file, to: fileDest) { progress(baseProgress + $0 * progressPerFile) }
- baseProgress += progressPerFile
- }
- }
-
- private func uploadFile(_ src: URL, to dest: URL, progress: (Double) -> Void) throws {
+ private func upload(_ src: URL, to dest: URL, progress: (Double) -> Void) throws {
let srcData = try Data(contentsOf: src)
let size = srcData.count
let sizeDouble = Double(size)
@@ -81,20 +63,6 @@ public final class IPAUploader {
}
}
- private func upload(_ src: URL, to dest: URL, allowSymlinks: Bool = true, progress: (Double) -> Void) throws {
- progress(0)
- let resources = try src.resourceValues(forKeys: [.isSymbolicLinkKey, .isDirectoryKey])
- if resources.isSymbolicLink == true {
- guard allowSymlinks else { throw Error.unexpectedSymlink(at: src) }
- try uploadSymlink(src, to: dest, progress: progress)
- } else if resources.isDirectory == true {
- try uploadDir(src, to: dest, progress: progress)
- } else {
- try uploadFile(src, to: dest, progress: progress)
- }
- progress(1)
- }
-
public func upload(app: URL, progress: (Double) -> Void) throws -> UploadedIPA {
if try !client.fileExists(at: Self.packagePath) {
try client.createDirectory(at: Self.packagePath)
@@ -105,7 +73,7 @@ public final class IPAUploader {
try client.removeItemAndContents(at: dest)
}
- try upload(app, to: dest, allowSymlinks: false, progress: progress)
+ try upload(app, to: dest, progress: progress)
return UploadedIPA(uploader: self, location: dest)
}