Run a virtual iPhone on an Apple Silicon Mac.
Swift
Expose jailbreak layout and guest port tunnels
Lakr85a6ccc645cd
diff --git a/Research/vphoned_http_api.md b/Research/vphoned_http_api.mdindex 3bf0ab63..7bf03c5c 100644--- a/Research/vphoned_http_api.md+++ b/Research/vphoned_http_api.md@@ -24,7 +24,7 @@ The guest links IcliKit directly. App registration refresh is available throughJPEG with `mime_type`, `width`, and `height`; the current VM produces 1290×2796.The host's Save/Copy Screenshot menu decodes this guest image. It omits thenotch and cutout drawn by the host VM window.-`apps.install` accepts IPA and TIPA archives. IcliKit 0.6.6 validates and+`apps.install` accepts IPA and TIPA archives. IcliKit 0.6.7 validates andextracts the archive, then calls vphone's signer on the temporary app bundlebefore IcliKit copies it into a container, registers it, and owns rollback.`apps.uninstall` delegates removal to IcliKit and requires `force=true`.@@ -39,7 +39,25 @@ directory then renames it after all chunks have been written. JSON bodieshave a 1 MiB limit. Binary transfers stream without loading the entire fileinto memory.-`apps.launch` returns a PID and `frontmost_verified`. IcliKit 0.6.6 checks+`GET /v1/device` includes `jailbreak.layout`, `jailbreak.jbroot`, and+`jailbreak.source`. The layout is `roothide`, `rootless`, or `rootful` when+detected. If there is no bootstrap and `/` is read-only, both `layout` and+`jbroot` are JSON `null`; `/` alone is not evidence of a rootful bootstrap.+The daemon checks a loaded RootHide `systemhook.dylib` export and `/var/jb`+at request time so a bootstrap created after daemon startup can be reported.++For raw guest TCP ports, upgrade `GET /v1/ports/<port>` to WebSocket. Each+binary WebSocket message carries an unmodified chunk of the TCP byte stream+in one direction; the server connects only to `127.0.0.1:<port>` inside the+guest. Ports 1 through 65535 are accepted. Ping/pong and close frames retain+normal WebSocket behavior; text frames close the tunnel. A failed guest+connection closes the WebSocket with code 1011. Each tunnel has its own guest+TCP connection and closes it when the WebSocket closes. For example, with+`--api-listen 127.0.0.1:8765`, `ws://127.0.0.1:8765/v1/ports/22` carries+the guest SSH byte stream. An SSH client still needs a local TCP-to-WebSocket+bridge; SSH cannot use a WebSocket URL directly.++`apps.launch` returns a PID and `frontmost_verified`. IcliKit 0.6.7 checksRunningBoard's live focal assertion and accepts it only when one real app ownsit. iOS 26.6.2 uses `SuspendableRole-UIFocal`; older systems may use`Workspace-ForegroundFocal`. The Home screen's widget renderer can also hold@@ -66,7 +84,7 @@ correlate them by `id`. The socket also sendsreceive pong frames. JSON WebSocket frames are limited to 1 MiB afterfragment reassembly.-SwiftNIO handles parsing, upgrade, masking, and backpressure. IcliKit 0.6.6+SwiftNIO handles parsing, upgrade, masking, and backpressure. IcliKit 0.6.7owns general device operations. Each HTTP or WebSocket request runs independentlyon a concurrent worker queue, so a stalled system service does not block HID,file browsing, or unrelated requests. The host serializes the input events itdiff --git a/VPhone.xcworkspace/xcshareddata/swiftpm/Package.resolved b/VPhone.xcworkspace/xcshareddata/swiftpm/Package.resolvedindex f709cc46..c91c16ff 100644--- a/VPhone.xcworkspace/xcshareddata/swiftpm/Package.resolved+++ b/VPhone.xcworkspace/xcshareddata/swiftpm/Package.resolved@@ -24,8 +24,8 @@"kind" : "remoteSourceControl","location" : "https://github.com/owngoal-dev/icli.git","state" : {- "revision" : "0bc454f61f54d99439e0f8a7f9e1c43f0fb49dc2",- "version" : "0.6.6"+ "revision" : "9dafb92a0a8c24387e19ab90459e8595e523aec9",+ "version" : "0.6.7"}},{diff --git a/VPhoneDaemon/Daemon/GuestAPI.swift b/VPhoneDaemon/Daemon/GuestAPI.swiftindex c7395196..51bac18f 100644--- a/VPhoneDaemon/Daemon/GuestAPI.swift+++ b/VPhoneDaemon/Daemon/GuestAPI.swift@@ -59,6 +59,7 @@ enum GuestAPI {"location","keychain","ipa_install",+ "port_forward","camera","screenshot",],@@ -68,7 +69,9 @@ enum GuestAPI {static func execute(method: String, params: [String: Any]) throws -> [String: Any] {switch method {case "device.snapshot":- return try collectDeviceSnapshot()+ var snapshot = try collectDeviceSnapshot()+ snapshot["jailbreak"] = jailbreakInfo()+ return snapshotcase "device.screen":return screenInfo()case "screen.screenshot":@@ -334,6 +337,41 @@ enum GuestAPI {return result}+ private static func jailbreakInfo() -> [String: Any] {+ func isDirectory(_ path: String) -> Bool {+ var directory: ObjCBool = false+ return FileManager.default.fileExists(atPath: path, isDirectory: &directory) && directory.boolValue+ }++ // RootHide can expose its root through the injected hook even when a+ // system-installed vphoned has no adjacent .jbroot or libroot library.+ if let hook = dlopen("systemhook.dylib", RTLD_NOLOAD) {+ defer { dlclose(hook) }+ if let symbol = dlsym(hook, "get_jbroot") {+ typealias GetRoot = @convention(c) () -> UnsafePointer<CChar>?+ if let prefix = unsafeBitCast(symbol, to: GetRoot.self)() {+ let path = String(cString: prefix)+ if path.hasPrefix("/"), path != "/", isDirectory(path) {+ return ["layout": "roothide", "jbroot": path, "source": "systemhook"]+ }+ }+ }+ }++ let root = JailbreakRoot.current+ if let layout = root.layout, layout != .rootful, isDirectory(root.jbroot) {+ return ["layout": layout.rawValue, "jbroot": root.jbroot, "source": root.source]+ }+ if isDirectory("/var/jb") {+ return ["layout": "rootless", "jbroot": "/var/jb", "source": "filesystem /var/jb"]+ }+ var rootMount = statfs()+ if statfs("/", &rootMount) == 0, rootMount.f_flags & UInt32(MNT_RDONLY) == 0 {+ return ["layout": "rootful", "jbroot": "/", "source": "root mount"]+ }+ return ["layout": NSNull(), "jbroot": NSNull(), "source": "not detected"]+ }+private static func string(_ params: [String: Any], _ key: String) throws -> String {guard let value = params[key] as? String, !value.isEmpty else {throw GuestAPIError.invalidRequest("\(key) is required")diff --git a/VPhoneDaemon/Daemon/GuestHyperTextHandler.swift b/VPhoneDaemon/Daemon/GuestHyperTextHandler.swiftindex 341c8eb2..b8a86a12 100644--- a/VPhoneDaemon/Daemon/GuestHyperTextHandler.swift+++ b/VPhoneDaemon/Daemon/GuestHyperTextHandler.swift@@ -109,7 +109,11 @@ final class GuestHyperTextHandler: ChannelInboundHandler, RemovableChannelHandleSelf.send(.json(GuestAPI.health()), on: channel)return}- if path == "/v1/events" {+ if path.hasPrefix("/v1/ports/"), GuestPortForwardHandler.port(from: head.uri) == nil {+ Self.send(APIWire.error("Port must be a decimal number from 1 to 65535"), on: channel)+ return+ }+ if path == "/v1/events" || path.hasPrefix("/v1/ports/") {Self.send(APIWire.error("WebSocket upgrade required", status: 426), on: channel)return}diff --git a/VPhoneDaemon/Daemon/GuestPortForwardHandler.swift b/VPhoneDaemon/Daemon/GuestPortForwardHandler.swiftnew file mode 100644index 00000000..d2e1b9de--- /dev/null+++ b/VPhoneDaemon/Daemon/GuestPortForwardHandler.swift@@ -0,0 +1,157 @@+import NIOCore+import NIOPosix+import NIOWebSocket++/// A WebSocket binary frame is one chunk of the guest TCP byte stream.+/// Connections are limited to loopback; callers cannot select another host.+final class GuestPortForwardHandler: ChannelInboundHandler, @unchecked Sendable {+ typealias InboundIn = WebSocketFrame+ typealias OutboundOut = WebSocketFrame++ let port: Int+ private var backend: Channel?+ private var pending: [ByteBuffer] = []+ private var pendingBytes = 0+ private let maximumPendingBytes = 1 << 20++ init(port: Int) {+ self.port = port+ }++ static func port(from uri: String) -> Int? {+ let prefix = "/v1/ports/"+ guard uri.hasPrefix(prefix) else { return nil }+ let digits = uri.dropFirst(prefix.count)+ guard !digits.isEmpty, digits.utf8.allSatisfy({ (48 ... 57).contains($0) }),+ let port = Int(digits), (1 ... 65535).contains(port)+ else { return nil }+ return port+ }++ func handlerAdded(context: ChannelHandlerContext) {+ let webSocket = context.channel+ _ = webSocket.setOption(ChannelOptions.autoRead, value: false)+ ClientBootstrap(group: context.eventLoop)+ .connectTimeout(.seconds(5))+ .channelInitializer { backend in+ backend.pipeline.addHandler(GuestPortBackendHandler(webSocket: webSocket))+ }+ .connect(host: "127.0.0.1", port: port)+ .whenComplete { result in+ guard webSocket.isActive else {+ if case let .success(backend) = result { backend.close(promise: nil) }+ return+ }+ switch result {+ case let .success(backend):+ self.backend = backend+ for chunk in self.pending { backend.write(chunk, promise: nil) }+ backend.flush()+ self.pending.removeAll()+ self.pendingBytes = 0+ _ = webSocket.setOption(ChannelOptions.autoRead, value: true)+ case .failure:+ self.closeWithError(on: webSocket)+ }+ }+ }++ func channelRead(context: ChannelHandlerContext, data: NIOAny) {+ let frame = unwrapInboundIn(data)+ switch frame.opcode {+ case .binary:+ let chunk = frame.unmaskedData+ if let backend {+ backend.writeAndFlush(chunk, promise: nil)+ } else {+ pendingBytes += chunk.readableBytes+ guard pendingBytes <= maximumPendingBytes else {+ closeWithError(on: context.channel)+ return+ }+ pending.append(chunk)+ }+ case .ping:+ context.writeAndFlush(wrapOutboundOut(WebSocketFrame(fin: true, opcode: .pong,+ data: frame.unmaskedData)), promise: nil)+ case .connectionClose:+ let webSocket = context.channel+ context.writeAndFlush(wrapOutboundOut(WebSocketFrame(fin: true, opcode: .connectionClose,+ data: frame.unmaskedData))).whenComplete { _ in+ webSocket.close(promise: nil)+ }+ default:+ closeWithError(on: context.channel)+ }+ }++ func channelWritabilityChanged(context: ChannelHandlerContext) {+ _ = backend?.setOption(ChannelOptions.autoRead, value: context.channel.isWritable)+ context.fireChannelWritabilityChanged()+ }++ func channelInactive(context: ChannelHandlerContext) {+ backend?.close(promise: nil)+ backend = nil+ pending.removeAll()+ context.fireChannelInactive()+ }++ func errorCaught(context: ChannelHandlerContext, error _: Error) {+ context.close(promise: nil)+ }++ private func closeWithError(on channel: Channel) {+ var data = channel.allocator.buffer(capacity: 2)+ data.writeInteger(UInt16(1011), endianness: .big)+ channel.writeAndFlush(WebSocketFrame(fin: true, opcode: .connectionClose,+ data: data)).whenComplete { _ in+ channel.close(promise: nil)+ }+ }+}++private final class GuestPortBackendHandler: ChannelInboundHandler, @unchecked Sendable {+ typealias InboundIn = ByteBuffer++ let webSocket: Channel+ private var lastWrite: EventLoopFuture<Void>?++ init(webSocket: Channel) {+ self.webSocket = webSocket+ }++ func channelRead(context _: ChannelHandlerContext, data: NIOAny) {+ guard webSocket.isActive else { return }+ let frame = WebSocketFrame(fin: true, opcode: .binary, data: unwrapInboundIn(data))+ lastWrite = webSocket.writeAndFlush(frame)+ }++ func channelWritabilityChanged(context: ChannelHandlerContext) {+ _ = webSocket.setOption(ChannelOptions.autoRead, value: context.channel.isWritable)+ context.fireChannelWritabilityChanged()+ }++ func channelInactive(context: ChannelHandlerContext) {+ if let lastWrite {+ lastWrite.whenComplete { _ in self.closeWebSocket() }+ } else {+ closeWebSocket()+ }+ context.fireChannelInactive()+ }++ func errorCaught(context: ChannelHandlerContext, error _: Error) {+ context.close(promise: nil)+ }++ private func closeWebSocket() {+ guard webSocket.isActive else { return }+ var data = webSocket.allocator.buffer(capacity: 2)+ data.writeInteger(UInt16(1000), endianness: .big)+ webSocket.writeAndFlush(WebSocketFrame(fin: true, opcode: .connectionClose,+ data: data)).whenComplete { _ in+ self.webSocket.close(promise: nil)+ }+ }+}diff --git a/VPhoneDaemon/Daemon/main.swift b/VPhoneDaemon/Daemon/main.swiftindex 5fbdee43..96229525 100644--- a/VPhoneDaemon/Daemon/main.swift+++ b/VPhoneDaemon/Daemon/main.swift@@ -23,11 +23,22 @@ do {let upgrader = NIOWebSocketServerUpgrader(maxFrameSize: 1 << 20,shouldUpgrade: { channel, request in- channel.eventLoop.makeSucceededFuture(request.uri == "/v1/events" ? HTTPHeaders() : nil)+ let allowed = request.uri == "/v1/events" || GuestPortForwardHandler.port(from: request.uri) != nil+ return channel.eventLoop.makeSucceededFuture(allowed ? HTTPHeaders() : nil)},- upgradePipelineHandler: { channel, _ in+ upgradePipelineHandler: { channel, request inchannel.pipeline.removeHandler(http).flatMap {- channel.pipeline.addHandlers([+ if let port = GuestPortForwardHandler.port(from: request.uri) {+ return channel.pipeline.addHandlers([+ NIOWebSocketFrameAggregator(+ minNonFinalFragmentSize: 1,+ maxAccumulatedFrameCount: 32,+ maxAccumulatedFrameSize: 1 << 20,+ ),+ GuestPortForwardHandler(port: port),+ ])+ }+ return channel.pipeline.addHandlers([NIOWebSocketFrameAggregator(minNonFinalFragmentSize: 1,maxAccumulatedFrameCount: 32,diff --git a/VPhoneDaemon/VPhoneDaemon.xcodeproj/project.pbxproj b/VPhoneDaemon/VPhoneDaemon.xcodeproj/project.pbxprojindex 7a15b8de..ac8311cf 100644--- a/VPhoneDaemon/VPhoneDaemon.xcodeproj/project.pbxproj+++ b/VPhoneDaemon/VPhoneDaemon.xcodeproj/project.pbxproj@@ -345,7 +345,7 @@repositoryURL = "https://github.com/owngoal-dev/icli.git";requirement = {kind = exactVersion;- version = 0.6.6;+ version = 0.6.7;};};C10000000000000000000072 /* XCRemoteSwiftPackageReference "swift-nio" */ = {diff --git a/VPhoneDaemon/VPhoneDaemon.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/VPhoneDaemon/VPhoneDaemon.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolvedindex 248eaf62..d23ad5f7 100644--- a/VPhoneDaemon/VPhoneDaemon.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved+++ b/VPhoneDaemon/VPhoneDaemon.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved@@ -1,13 +1,13 @@{- "originHash" : "00413e50535a5795694962f3fb733b172429718565c2a71af5da825f070189a2",+ "originHash" : "270e2423ac723c2823e7be871230f357e5e4fb1fd3a38e59a92686ff4e48db1f","pins" : [{"identity" : "icli","kind" : "remoteSourceControl","location" : "https://github.com/owngoal-dev/icli.git","state" : {- "revision" : "0bc454f61f54d99439e0f8a7f9e1c43f0fb49dc2",- "version" : "0.6.6"+ "revision" : "9dafb92a0a8c24387e19ab90459e8595e523aec9",+ "version" : "0.6.7"}},{