From e2e00c2a18314455e40d388e07968dec71775fb2 Mon Sep 17 00:00:00 2001 From: moltenglue <257664494+moltenglue@users.noreply.github.com> Date: Mon, 30 Nov 2026 10:12:52 -0500 Subject: [PATCH 1/5] Add opt-in iOS USB 3 host-mode transport via usbmuxd Add an experimental USB Host-mode transport ('Full Frame Experimental Network', off by default) that reverses USB roles between the comma and an iPhone/iPad to bypass the comma's Linux 4.9 u_ether CDC-NCM gadget bottleneck (~8 ms on 393 KB frames) for full-frame model testing. - Leave CDC-NCM, jetlink/comma/jetlink-root.sh, and protocol v3 framing completely unchanged when the toggle is off. - Comma side: scripts/comma/jetlink-usbmux.sh (host mode restore, persistent /data/jetlink/lockdown pairing, USB 3/USB 2 speed checks, optional --mode3 A/B toggle) and direct stdlib-only UsbmuxClient, UsbmuxTransport, UsbmuxReconnector, and diagnostics in jetlink/comma/usbmux_transport.py (no iproxy subprocess copy hop). - iOS / JetlinkKit: gate 127.0.0.1:5599 loopback listening behind PhoneSettings.fullFrameExperimentalNetwork ('Full Frame Experimental Network' in Settings -> Connection) using public POSIX sockets only (TCPListener.loopback, LinkEvent.isLoopback, no Local Network prompt), with clear usbmuxd / Trust status readouts. - Benchmarks & tests: --usbmux and --payload-kb support in bench_link.py and verify_parity.py, plus comprehensive Python/Swift unit tests and docs/usbmux-transport.md. - Fix pre-existing deprecation and Swift 6 actor-isolation warnings in Transport.swift and ModelStatusLabel.swift. --- .../Sources/JetlinkKit/ControlProtocol.swift | 7 + .../Sources/JetlinkServer/Transport.swift | 22 +- .../Sources/JetlinkUI/ModelStatusLabel.swift | 4 +- .../JetlinkKitTests/LinkMediumTests.swift | 11 + .../JetlinkServerTests/ServerTests.swift | 28 + docs/README.md | 2 +- docs/transport.md | 1 + docs/usbmux-transport.md | 104 +++ ios/Jetlink/App/AppModel.swift | 3 +- ios/Jetlink/App/PhoneSettings.swift | 21 +- ios/Jetlink/Server/PhoneServer.swift | 12 +- .../Views/Settings/SettingsScreen.swift | 26 +- ios/Jetlink/Views/Status/HeroCard.swift | 8 +- ios/Jetlink/Views/Status/StatusContent.swift | 13 +- ios/Jetlink/Views/Status/StatusState.swift | 31 +- jetlink/client.py | 8 + jetlink/comma/usbmux_transport.py | 723 ++++++++++++++++++ scripts/bench_link.py | 198 ++++- scripts/comma/jetlink-usbmux.sh | 377 +++++++++ scripts/verify_parity.py | 9 +- tests/test_usbmux_transport.py | 654 ++++++++++++++++ 21 files changed, 2213 insertions(+), 49 deletions(-) create mode 100644 docs/usbmux-transport.md create mode 100644 jetlink/comma/usbmux_transport.py create mode 100755 scripts/comma/jetlink-usbmux.sh create mode 100644 tests/test_usbmux_transport.py diff --git a/JetlinkKit/Sources/JetlinkKit/ControlProtocol.swift b/JetlinkKit/Sources/JetlinkKit/ControlProtocol.swift index ce61d369..a320eea9 100644 --- a/JetlinkKit/Sources/JetlinkKit/ControlProtocol.swift +++ b/JetlinkKit/Sources/JetlinkKit/ControlProtocol.swift @@ -67,6 +67,13 @@ public struct LinkEvent: Codable, Sendable, Equatable { /// jetlink/openpilot/link.py's Link says in its hello. public var isDrive: Bool { state == .connected && client == "modeld" } + /// True when the connection arrived over loopback (127.0.0.1 / ::1), + /// which on iOS is a comma USB Host-mode usbmuxd tunnel. + public var isLoopback: Bool { + guard let peer else { return false } + return peer.hasPrefix("127.0.0.1:") || peer.hasPrefix("[::1]:") || peer.hasPrefix("::1:") + } + /// What a connected link is carried over, for display: the server's word, /// or for a server or comma older than the field, a guess from the peer. /// The Python server's USB host says "usb", and a peer on the comma's cable diff --git a/JetlinkKit/Sources/JetlinkServer/Transport.swift b/JetlinkKit/Sources/JetlinkServer/Transport.swift index 6a564ab7..012a7fe8 100644 --- a/JetlinkKit/Sources/JetlinkServer/Transport.swift +++ b/JetlinkKit/Sources/JetlinkServer/Transport.swift @@ -127,8 +127,10 @@ public final class TCPTransport: @unchecked Sendable { private let polls = UnsafeMutablePointer.allocate(capacity: 2) /// A port and a new token for the comma to send frames to as datagrams, - /// or nil off the cable: only a phone's USB link is offered them. The - /// session's loop thread calls this, as it calls `recv()`. + /// or nil off the cable: only CDC-NCM (`medium == .usb`) is offered them. + /// USB Host-mode usbmuxd tunnels report `.usb3`/`.usb2` over loopback and + /// bypass `u_ether`'s segment bottleneck, so they stay on TCP directly. + /// The session's loop thread calls this, as it calls `recv()`. public func offerDatagrams() -> (port: UInt16, token: UInt32)? { guard medium == .usb || TCPTransport.datagramsAnyPeer else { return nil } if datagrams == nil { @@ -299,11 +301,22 @@ public final class TCPTransport: @unchecked Sendable { /// A listening TCP socket. `accept` polls so `close` can stop it from another /// thread, and frees the port at once. public final class TCPListener: @unchecked Sendable { + /// Loopback bind address used for USB Host-mode usbmuxd tunnels on iOS so + /// experimental mode never exposes a LAN socket or requires Local Network permission. + public static let loopbackHost = "127.0.0.1" + public let port: UInt16 private let fd: Int32 private let lock = NSLock() private var closed = false + /// Listens strictly on 127.0.0.1 (IPv4 loopback) with TCP_NODELAY and + /// pre-allocated receive buffers on accepted connections, keeping TestFlight + /// builds 100% public-API (no USBDriverKit or private APIs). + public static func loopback(port: UInt16 = Wire.defaultPort) throws -> TCPListener { + try TCPListener(host: TCPListener.loopbackHost, port: port, dualStack: false) + } + /// Listens on `host`, or with `dualStack` on every address: IPv6 with IPv4 /// mapped in, since a phone may resolve a name to either, else IPv4 on `host`. public init(host: String = "0.0.0.0", port: UInt16 = Wire.defaultPort, dualStack: Bool = false) throws { @@ -416,7 +429,10 @@ public final class TCPListener: @unchecked Sendable { getnameinfo($0, length, &host, .init(host.count), &service, .init(service.count), NI_NUMERICHOST | NI_NUMERICSERV) } } - return (String(cString: host), UInt16(String(cString: service)) ?? 0) + return ( + String(decoding: host.prefix { $0 != 0 }.map(UInt8.init(bitPattern:)), as: UTF8.self), + UInt16(String(decoding: service.prefix { $0 != 0 }.map(UInt8.init(bitPattern:)), as: UTF8.self)) ?? 0 + ) } public func close() { diff --git a/JetlinkKit/Sources/JetlinkUI/ModelStatusLabel.swift b/JetlinkKit/Sources/JetlinkUI/ModelStatusLabel.swift index 5592ac36..474555a3 100644 --- a/JetlinkKit/Sources/JetlinkUI/ModelStatusLabel.swift +++ b/JetlinkKit/Sources/JetlinkUI/ModelStatusLabel.swift @@ -70,8 +70,8 @@ } } - /// "Downloading 42%". - public static func downloadingText(_ frac: Double) -> String { + /// "Downloading 42%". Nonisolated pure formatting so `ModelFormatting.downloadCaption` can call it synchronously. + public nonisolated static func downloadingText(_ frac: Double) -> String { "Downloading \(Int((min(max(frac, 0), 1) * 100).rounded()))%" } } diff --git a/JetlinkKit/Tests/JetlinkKitTests/LinkMediumTests.swift b/JetlinkKit/Tests/JetlinkKitTests/LinkMediumTests.swift index 07ac0874..978a7bfe 100644 --- a/JetlinkKit/Tests/JetlinkKitTests/LinkMediumTests.swift +++ b/JetlinkKit/Tests/JetlinkKitTests/LinkMediumTests.swift @@ -16,6 +16,8 @@ struct LinkMediumTests { @Test("A hello's link names the medium, or nothing") func helloLinks() { #expect(LinkMedium(link: ["kind": "cable", "usb_speed": "high-speed"]) == .usb2) + #expect(LinkMedium(link: ["kind": "cable", "usb_speed": "super-speed-plus", "transport": "usbmux"]) == .usb3) + #expect(LinkMedium(link: ["kind": "cable", "usb_speed": "high-speed", "transport": "usbmux"]) == .usb2) #expect(LinkMedium(link: ["kind": "usb", "usb_speed": "super-speed"]) == .usb3) #expect(LinkMedium(link: ["kind": "usb"]) == .usb) // before a hello: the comma's cable address at the far end is the cable @@ -27,6 +29,15 @@ struct LinkMediumTests { #expect(LinkMedium(link: nil) == nil) } + @Test("Loopback peer addresses identify usbmuxd tunnels") + func loopbackDetection() { + #expect(LinkEvent(state: .connected, detail: "", peer: "127.0.0.1:54321").isLoopback) + #expect(LinkEvent(state: .connected, detail: "", peer: "[::1]:54321").isLoopback) + #expect(!LinkEvent(state: .connected, detail: "", peer: "192.168.60.1:5599").isLoopback) + #expect(!LinkEvent(state: .connected, detail: "", peer: "10.0.0.5:5599").isLoopback) + #expect(!LinkEvent(state: .waiting, detail: "", peer: nil).isLoopback) + } + @Test("Only USB 2 and 1 are slow enough to warn about") func slowLinks() { #expect(LinkMedium.allCases.filter(\.isSlow) == [.usb2, .usb1]) diff --git a/JetlinkKit/Tests/JetlinkServerTests/ServerTests.swift b/JetlinkKit/Tests/JetlinkServerTests/ServerTests.swift index 02a27bf8..a22161e2 100644 --- a/JetlinkKit/Tests/JetlinkServerTests/ServerTests.swift +++ b/JetlinkKit/Tests/JetlinkServerTests/ServerTests.swift @@ -422,6 +422,34 @@ struct ServerLifecycleTests { #expect(live.most == 1, "\(live.most) sessions served at once") #expect(interrupts.all.filter { $0 == "a" }.count == 1, "\(interrupts.all)") } + + @Test("Loopback listener serves usbmuxd tunnel and 4 MB payloads with no UDP datagrams") + func loopbackUsbmuxServer() throws { + let cache = try TemporaryDirectory() + let server = try Server( + configuration: Server.Configuration( + host: TCPListener.loopbackHost, port: 0, cacheRoot: cache.url, preload: false, listen: true), + backend: cpuBackend()) + try server.start() + defer { server.shutdown() } + let client = try TestClient(port: server.port!) + defer { client.close() } + + let hello = try client.hello( + name: "modeld", link: ["kind": "cable", "usb_speed": "super-speed-plus", "transport": "usbmux"]) + #expect(server.currentLink.isLoopback) + #expect(server.currentLink.linkMedium == .usb3) + #expect(hello["frame_port"] == nil) + + let largeSeq = try client.send(.ping, Data(count: 4 * 1024 * 1024)) + let pong = try client.recv(.pong) + #expect(pong.seq == largeSeq) + + let golden = try Golden("tiny_queued") + let (_, count) = try client.replay(golden) + #expect(count == 8) + #expect(eventually { server.framesServed == count }) + } } /// How many links are being read at once, and the most there ever were. diff --git a/docs/README.md b/docs/README.md index 56b7c1d4..b1a982e3 100644 --- a/docs/README.md +++ b/docs/README.md @@ -19,6 +19,6 @@ the guides give zoompilot's steps and settings. - [Models](models.md): choose or download a model ahead of time. - [Updates and rollback](releasing.md). -[Cables and power](transport.md) · [Operating limits](status.md) · +[Cables and power](transport.md) · [Experimental `usbmuxd` USB host mode](usbmux-transport.md) · [Operating limits](status.md) · [Developer and advanced reference](development.md) · [Add Jetlink to an openpilot fork](porting.md) diff --git a/docs/transport.md b/docs/transport.md index 56dd46f8..134903ef 100644 --- a/docs/transport.md +++ b/docs/transport.md @@ -69,4 +69,5 @@ Parking, starting, and how battery-protection shutdown differs from sleep: [TCP testing](platforms.md#test-without-a-comma) · [Link protocol](link-protocol.md) · +[Experimental USB host mode (`usbmuxd`)](usbmux-transport.md) · [Custom USB integrations](installation-reference.md#custom-usb-integrations) diff --git a/docs/usbmux-transport.md b/docs/usbmux-transport.md new file mode 100644 index 00000000..8aa90551 --- /dev/null +++ b/docs/usbmux-transport.md @@ -0,0 +1,104 @@ +# High-speed iOS USB host mode (`usbmuxd`) + +Opt-in experimental transport that reverses USB roles between the comma and an iPhone or iPad to test multi-megabyte full-frame models over USB 3 without modifying default CDC-NCM behavior. + +## Why this exists + +In standard iOS mode (`jetlink-root.sh gadget --ios`), the comma acts as a composite USB gadget (`u_ether` CDC-NCM) and the iPhone acts as the USB host. On the comma's Linux 4.9 `u_ether` gadget driver, sending a 393 KB `INFER_REQ` frame adds ~8 ms of transport overhead (and required `JFRM` UDP datagram chunking to bypass TCP segment limits). + +Reversing USB roles removes `u_ether` from the hot path: + +- **Comma stays in USB Host mode** (its default AUX role). +- **iPhone / iPad stays in standard USB Device mode.** +- **`usbmuxd` on the comma** drives USB 3 bulk transfers via `libusb` and tunnels straight to a standard `127.0.0.1:5599` loopback TCP listener inside the iOS app. + +Because `usbmuxd` streams over raw USB 3 bulk pipes (~6.12 Gbps / ~765 MB/s measured on USB 3 iPhones) instead of `u_ether`: + +- A 393 KB frame takes ~0.5 ms on the wire, without UDP JFRM fallback. +- Multi-megabyte full-frame payloads (e.g., 4 MB inputs) stay well inside the 46–50 ms per-frame driving budget. +- The iOS app uses only public POSIX loopback sockets via `TCPListener` (`127.0.0.1:5599`) — zero USBDriverKit extensions, zero MFi hardware, and zero private iOS APIs. + +## Opt-in design ("Full Frame Experimental Network") + +Normal Jetlink setups are unchanged: + +- **Default (`OFF`)**: `PhoneSettings.fullFrameExperimentalNetwork` is `false`. The iOS app continues to dial the comma over the CDC-NCM USB network interface (`192.168.60.1:5599`), and `jetlink/comma/jetlink-root.sh` is untouched. +- **Experimental (`ON`)**: Under **Settings > Connection > Full Frame Experimental Network**, toggling it on: + - Stops CDC-NCM dialing in `PhoneServer` and binds `TCPListener` strictly to `127.0.0.1:5599` (`TCP_NODELAY = 1`, 4 MB send/receive socket buffers, pre-allocated zero-copy `FrameReader`). + - Does not expose a LAN socket and does not require iOS Local Network permission. + - Shows **Listening on USB (usbmuxd)** → **Connected via usbmuxd (USB 3)** in the app status views and Settings. + +## Architecture + +### Variant A (primary): Direct `/var/run/usbmuxd` tunnel + +```text +[comma 3X/4 (USB Host, AUX port)] + └─ UsbmuxClient / UsbmuxReconnector (jetlink/comma/usbmux_transport.py) + └─ Unix socket /var/run/usbmuxd (plist Connect -> device_id, htons(5599)) + └─ usbmuxd daemon (libusb raw USB 3 bulk pipes) + ═[Powered 10 Gbps USB 3.2 Gen 2 Hub]═ + └─ iPhone / iPad (USB Device mode) + └─ Jetlink iOS App (TCPListener strictly on 127.0.0.1:5599, TCP_NODELAY) +``` + +Key design choices: + +- **No `iproxy` process hop**: `UsbmuxClient` speaks the binary/plist `usbmuxd` protocol (`ListDevices`, `Listen`, `Connect`) directly over `/var/run/usbmuxd` from Python (`jetlink/comma/usbmux_transport.py`), wraps the upgraded socket directly in `UsbmuxTransport(StreamTransport)`, and avoids copying multi-megabyte frames twice through an extra `iproxy` localhost proxy. +- **Protocol v3 verbatim**: Reuses the 32-byte `JLNK` header, `INFER_REQ`, and `INFER_RESP` framing without changes. +- **Stdlib-only comma module**: `jetlink/comma/usbmux_transport.py` imports only Python's standard library and `jetlink.transport.base`, matching the comma's minimal resident dependency footprint. +- **Persistent lockdown trust**: `scripts/comma/jetlink-usbmux.sh` maps `/var/lib/lockdown` to `/data/jetlink/lockdown` (symlink or bind mount fallback on read-only AGNOS rootfs) so tapping **Trust This Computer** persists across comma reboots and updates. +- **USB 3 speed & pairing diagnostics**: Both `jetlink-usbmux.sh speed` and `detect_apple_usb_speed()` inspect `/sys/bus/usb/devices/*/speed` for Apple VID `05ac` and warn immediately on 480 Mbps USB 2 fallback or unpaired devices. +- **Event-driven auto-reconnect**: `UsbmuxReconnector` runs a background `Listen` monitor on `/var/run/usbmuxd` so cable bumps or replugs recover immediately without polling stalls. + +### Variant B (optional A/B): `USBMUXD_DEFAULT_DEVICE_MODE=3` + +If a specific AGNOS kernel or device exhibits TCP buffering jitter, `scripts/comma/jetlink-usbmux.sh setup --mode3` launches `usbmuxd` with `USBMUXD_DEFAULT_DEVICE_MODE=3` so Linux's host-side `cdc_ncm` driver can be A/B benchmarked against Variant A without removing CDC-NCM gadget support. + +## Hardware setup + +1. Comma 3X or comma four with the AUX USB-C port left in USB Host mode (`jetlink-usbmux.sh setup` tears down any active CDC-NCM gadget cleanly via `jetlink-root.sh teardown`). +2. **Powered 10 Gbps USB 3.2 Gen 2 hub** with external USB-C PD power input between the comma and iPhone/iPad so the iPhone charges from the hub's supply rather than drawing current from the comma's AUX VBUS. +3. **10 Gbps USB 3 data cables** on every hop (standard USB 2 charging cables drop negotiation to 480 Mbps). + +## Commands + +On the iPhone/iPad: +1. Open **Settings > Connection** and turn on **Full Frame Experimental Network**. + +On the comma: +```bash +# Tear down CDC-NCM gadget, map /data/jetlink/lockdown, start usbmuxd +sudo scripts/comma/jetlink-usbmux.sh setup --install + +# Pair once (unlock iPhone/iPad and tap "Trust This Computer") +scripts/comma/jetlink-usbmux.sh pair + +# Verify USB 3 speed (5000 or 10000 Mbps) and status +scripts/comma/jetlink-usbmux.sh speed +scripts/comma/jetlink-usbmux.sh status + +# Transport benchmarks (384 KiB driving payload and 4 MiB full-frame stress) +python3 scripts/bench_link.py --usbmux --payload-kb 384 --rate 20 --n 1200 +python3 scripts/bench_link.py --usbmux --payload-kb 4096 --rate 20 --n 400 + +# Model parity / full model round-trip benchmark over usbmuxd +python3 scripts/bench_link.py --usbmux --spec path/to/spec.json --rate 20 --n 1200 +python3 scripts/verify_parity.py capture --usbmux --dir out --spec path/to/spec.json + +# Optional Variant B A/B toggle (USBMUXD_DEFAULT_DEVICE_MODE=3) +sudo scripts/comma/jetlink-usbmux.sh setup --mode3 +``` + +## Verification status + +Verified in CI-equivalent local tests and loopback benchmarks before device/comma hardware testing: + +- **Python tests (`tests/test_usbmux_transport.py`)**: 13/13 passing against mocked `/var/run/usbmuxd` (`ListDevices` USB filtering, `htons(5599)`, protocol v3 393 KB `INFER_REQ` + 8 KB `INFER_RESP` round-trip, `RESULT_CONNREFUSED` retries, `Listen` attach, `UsbmuxReconnector` `< 1.5 s` recovery, sysfs USB 3/USB 2 detection, pairing diagnostics, stdlib-only `-I` import isolation, synthetic `bench_link.py --usbmux`, and `jetlink-usbmux.sh`). +- **Swift tests (`JetlinkKitTests` + `JetlinkServerTests`)**: 223/223 passing (`LinkEvent.isLoopback`, `LinkMedium` with `"transport": "usbmux"`, and `loopbackUsbmuxServer` verifying `127.0.0.1` loopback serving + 4 MB payloads with no UDP datagrams). +- **Live `jetlink-server` loopback (`127.0.0.1`)**: + - 384 KiB @ 20 Hz: p50 `0.36 ms`, p99 `0.56 ms`, max `0.63 ms`, `0/90` frames > 46 ms. + - 4096 KiB (4 MiB) @ 20 Hz: p50 `0.98 ms`, p99 `1.71 ms`, max `1.75 ms`, `0/32` frames > 46 ms. +- **iOS device build (`xcodebuild`)**: `** BUILD SUCCEEDED **`. + +Live comma + powered 10 Gbps USB 3 hub + on-device iPhone A/B measurements remain to be run on hardware. diff --git a/ios/Jetlink/App/AppModel.swift b/ios/Jetlink/App/AppModel.swift index ad98e049..53b518ab 100644 --- a/ios/Jetlink/App/AppModel.swift +++ b/ios/Jetlink/App/AppModel.swift @@ -63,7 +63,8 @@ final class AppModel { state.defaultModel = models.rows.first { $0.isDefault } state.hasPreparedModel = !(models.inventory?.artifacts.filter(\.current).isEmpty ?? true) state.catalogUnavailable = models.catalog?.error != nil && (models.catalog?.models.isEmpty ?? true) - state.localNetworkDenied = localNetwork.state == .denied + state.usbmuxMode = settings.fullFrameExperimentalNetwork + state.localNetworkDenied = !settings.fullFrameExperimentalNetwork && localNetwork.state == .denied return state } diff --git a/ios/Jetlink/App/PhoneSettings.swift b/ios/Jetlink/App/PhoneSettings.swift index d786a94a..b55fb1fc 100644 --- a/ios/Jetlink/App/PhoneSettings.swift +++ b/ios/Jetlink/App/PhoneSettings.swift @@ -27,10 +27,21 @@ final class PhoneSettings { didSet { defaults.set(overWiFi, forKey: Keys.overWiFi) } } - /// Does the server listen on `port`? Only with Connect over Wi-Fi on and the - /// developer settings shown; otherwise the phone only dials the comma over - /// the cable, which is all driving needs. - var listening: Bool { developer && overWiFi } + /// Opt-in USB Host-mode listener on 127.0.0.1:5599 for testing full-frame + /// models via usbmuxd. Defaults to `false` so normal users stay on the + /// standard CDC-NCM dial setup; binds strictly to loopback so LAN exposure + /// and Local Network permission are avoided. + var fullFrameExperimentalNetwork: Bool { + didSet { defaults.set(fullFrameExperimentalNetwork, forKey: Keys.fullFrameExperimentalNetwork) } + } + + /// Does the server listen on `listenHost:listenPort`? Either Connect over + /// Wi-Fi (developer) or Full Frame Experimental Network (127.0.0.1:5599). + var listening: Bool { (developer && overWiFi) || fullFrameExperimentalNetwork } + + var listenHost: String { (developer && overWiFi) ? "0.0.0.0" : "127.0.0.1" } + + var listenPort: UInt16 { (developer && overWiFi) ? port : 5599 } /// What runs the model. Automatic until one is chosen by hand. var device: Processor { @@ -76,6 +87,7 @@ final class PhoneSettings { self.port = port > 0 && port < 65_536 ? UInt16(port) : 5599 self.developer = defaults.bool(forKey: Keys.developer) self.overWiFi = defaults.bool(forKey: Keys.overWiFi) + self.fullFrameExperimentalNetwork = defaults.bool(forKey: Keys.fullFrameExperimentalNetwork) // A device stored before Automatic existed was chosen by hand, and stays. self.device = defaults.string(forKey: Keys.device).flatMap(Processor.init(rawValue:)) ?? .automatic self.automaticPicks = defaults.dictionary(forKey: Keys.automaticPicks) as? [String: String] ?? [:] @@ -95,6 +107,7 @@ final class PhoneSettings { static let port = "port" static let developer = "developer" static let overWiFi = "overWiFi" + static let fullFrameExperimentalNetwork = "fullFrameExperimentalNetwork" static let device = "device" static let automaticPicks = "automaticPicks" static let keepGPUAwake = "keepGPUAwake" diff --git a/ios/Jetlink/Server/PhoneServer.swift b/ios/Jetlink/Server/PhoneServer.swift index 60f08a14..452231df 100644 --- a/ios/Jetlink/Server/PhoneServer.swift +++ b/ios/Jetlink/Server/PhoneServer.swift @@ -99,7 +99,9 @@ final class PhoneServer: ServerControlling { } private func updateDial() { - let target = network.cable == nil ? nil : PhoneServer.commaDial + // In Full Frame Experimental Network mode the comma connects into 127.0.0.1:5599 over usbmuxd, + // so suppress CDC-NCM outbound dialing even if a virtual cable interface is present. + let target = (settings.fullFrameExperimentalNetwork || network.cable == nil) ? nil : PhoneServer.commaDial server?.setDial(target) } @@ -117,8 +119,10 @@ final class PhoneServer: ServerControlling { do { let root = try PhoneServer.prepareCacheDirectory() let embedded = try EmbeddedServer( - // The listener is for a comma on Wi-Fi and bench tools; over the cable the phone dials the comma. - configuration: Server.Configuration(port: settings.port, cacheRoot: root, preload: following == nil, listen: settings.listening, keepPlans: 2), + // Listens on 127.0.0.1:5599 for usbmuxd or 0.0.0.0:port for Wi-Fi; over CDC-NCM the phone dials the comma. + configuration: Server.Configuration( + host: settings.listenHost, port: settings.listenPort, cacheRoot: root, preload: following == nil, + listen: settings.listening, keepPlans: 2), backend: OrtBackend( profile: profile, preparer: ONNXPreparer(), keepAlive: settings.keepGPUAwake, keepCPUWarm: settings.keepCPUWarm)) self.embedded = embedded @@ -133,7 +137,7 @@ final class PhoneServer: ServerControlling { runState = .serving startRecentTicker() updateDial() - log.info("serving on \(profile.rawValue)\(server.port.map { ", port \($0)" } ?? ", not listening")") + log.info("serving on \(profile.rawValue)\(server.port.map { ", \(settings.listenHost):\($0)" } ?? ", not listening")") } catch { fail("Jetlink could not start its server: \(error)") } diff --git a/ios/Jetlink/Views/Settings/SettingsScreen.swift b/ios/Jetlink/Views/Settings/SettingsScreen.swift index e8a10a3e..78da6a08 100644 --- a/ios/Jetlink/Views/Settings/SettingsScreen.swift +++ b/ios/Jetlink/Views/Settings/SettingsScreen.swift @@ -80,6 +80,7 @@ struct SettingsScreen: View { .onChange(of: settings.keepGPUAwake) { app.server.restart() } .onChange(of: settings.keepCPUWarm) { app.server.restart() } .onChange(of: settings.listening) { app.server.restart() } + .onChange(of: settings.fullFrameExperimentalNetwork) { app.server.restart() } .sensoryFeedback(.success, trigger: settings.developer) } } @@ -87,9 +88,30 @@ struct SettingsScreen: View { // MARK: connection private var connection: some View { - Section("Connection") { - LabeledContent("Link", value: app.server.linkMedium?.phoneTitle ?? (app.network.cable == nil ? "Not Connected" : "Connecting")) + @Bindable var settings = app.settings + return Section { + LabeledContent("Link", value: connectionLinkValue) + Toggle("Full Frame Experimental Network", isOn: $settings.fullFrameExperimentalNetwork) + } header: { + Text("Connection") + } footer: { + Text( + "Off uses the default Jetlink USB setup. Turn on to test full-frame models over comma USB Host mode (usbmuxd on 127.0.0.1:5599): connect through a powered 10 Gbps USB 3 hub and tap Trust when prompted." + ) + } + } + + private var connectionLinkValue: String { + if app.settings.fullFrameExperimentalNetwork { + if app.server.link.state == .connected { + if let medium = app.server.linkMedium, medium != .tcp { + return "\(medium.title) (usbmuxd)" + } + return "Connected via usbmuxd" + } + return "Listening on USB (usbmuxd)" } + return app.server.linkMedium?.phoneTitle ?? (app.network.cable == nil ? "Not Connected" : "Connecting") } // MARK: developer diff --git a/ios/Jetlink/Views/Status/HeroCard.swift b/ios/Jetlink/Views/Status/HeroCard.swift index b20881ba..6c1a06de 100644 --- a/ios/Jetlink/Views/Status/HeroCard.swift +++ b/ios/Jetlink/Views/Status/HeroCard.swift @@ -115,10 +115,14 @@ struct HeroCard: View { private var waiting: some View { card { ContentUnavailableView { - Label("Waiting for Comma", systemImage: "cable.connector") + Label(state.usbmuxMode ? "Listening on USB (usbmuxd)" : "Waiting for Comma", systemImage: "cable.connector") .symbolEffect(.pulse, options: .repeating) } description: { - Text(state.cableAddress == nil ? "Plug in the comma." : "Connecting over USB.") + if state.usbmuxMode { + Text("Connect the comma in USB Host mode through a powered USB 3 hub and tap Trust when prompted.") + } else { + Text(state.cableAddress == nil ? "Plug in the comma." : "Connecting over USB.") + } } } } diff --git a/ios/Jetlink/Views/Status/StatusContent.swift b/ios/Jetlink/Views/Status/StatusContent.swift index 0afe1fcb..59a0252c 100644 --- a/ios/Jetlink/Views/Status/StatusContent.swift +++ b/ios/Jetlink/Views/Status/StatusContent.swift @@ -80,7 +80,7 @@ struct StatusContent: View { if state.history.count > 1 { history } - SectionHeader("Link", detail: state.linkMedium?.phoneTitle) + SectionHeader("Link", detail: state.linkDisplayTitle) link(recent) } SectionHeader(state.deviceName) @@ -114,7 +114,7 @@ struct StatusContent: View { if state.history.count > 1 { history } - SectionHeader("Link", detail: state.linkMedium?.phoneTitle) + SectionHeader("Link", detail: state.linkDisplayTitle) link(recent) } SectionHeader(state.deviceName) @@ -189,7 +189,7 @@ struct StatusContent: View { note: health.memoryNote, noteTone: health.memoryTone) MetricTile( title: "Link", systemImage: state.linkMedium == nil ? "cable.connector.slash" : "cable.connector", tint: .teal, - value: state.linkMedium?.phoneTitle ?? "None", + value: state.linkDisplayTitle, note: linkNote, noteTone: state.linkMedium?.isSlow == true ? .orange : nil) } } @@ -197,7 +197,12 @@ struct StatusContent: View { /// Under the Link tile: why there is none, or that a slow one costs frames. private var linkNote: String { - guard let medium = state.linkMedium else { return state.cableAddress == nil ? "Waiting" : "Connecting" } + guard let medium = state.linkMedium else { + if state.usbmuxMode { + return "Listening" + } + return state.cableAddress == nil ? "Waiting" : "Connecting" + } return medium.isSlow ? "Slow, use USB 3" : "Connected" } } diff --git a/ios/Jetlink/Views/Status/StatusState.swift b/ios/Jetlink/Views/Status/StatusState.swift index 99208ea2..df587a76 100644 --- a/ios/Jetlink/Views/Status/StatusState.swift +++ b/ios/Jetlink/Views/Status/StatusState.swift @@ -36,6 +36,10 @@ struct StatusState: Equatable { var storageWarning: String? /// Frames far over the budget: the Neural Engine is not running the model. var slowWarning: String? + /// Opt-in Full Frame Experimental Network (USB Host-mode usbmuxd on 127.0.0.1:5599). + var usbmuxMode = false + + var isUsbmuxConnection: Bool { usbmuxMode || link.isLoopback } /// The comma's frames, while the main card shows them. var servedStats: StatsEvent? { @@ -106,7 +110,9 @@ struct StatusState: Equatable { ? Summary(title: "Connected", symbol: "car.fill", tone: linkMedium?.isSlow == true ? .warning : .good) : Summary(title: "No Model", symbol: "shippingbox.fill", tone: .warning) case .waiting: - return Summary(title: "Waiting for Comma", symbol: "cable.connector", tone: .neutral) + return usbmuxMode + ? Summary(title: "Listening on USB (usbmuxd)", symbol: "cable.connector", tone: .info) + : Summary(title: "Waiting for Comma", symbol: "cable.connector", tone: .neutral) case .disconnected: return Summary(title: "Disconnected", symbol: "cable.connector.slash", tone: .warning) } @@ -114,12 +120,31 @@ struct StatusState: Equatable { /// The summary with the link it is over: "Connected over USB 3". var headline: String { - if summary.title == "Connected", let linkMedium { - return "Connected over \(linkMedium.phoneTitle)" + if summary.title == "Connected" { + if isUsbmuxConnection { + if let linkMedium, linkMedium != .tcp { + return "Connected via usbmuxd (\(linkMedium.title))" + } + return "Connected via usbmuxd" + } + if let linkMedium { + return "Connected over \(linkMedium.phoneTitle)" + } } return summary.title } + /// Display title for the Link tile and section header. + var linkDisplayTitle: String { + if link.state == .connected && isUsbmuxConnection { + if let linkMedium, linkMedium != .tcp { + return "\(linkMedium.title) (usbmuxd)" + } + return "usbmuxd" + } + return linkMedium?.phoneTitle ?? "None" + } + /// The line under the title: the summary and the model. var subtitle: String { [headline, modelName].compactMap { $0 }.joined(separator: " · ") diff --git a/jetlink/client.py b/jetlink/client.py index ac897686..2f60bd53 100644 --- a/jetlink/client.py +++ b/jetlink/client.py @@ -176,6 +176,14 @@ def open_socket(cls, sock, **kw) -> JetlinkClient: from jetlink.transport.tcp import TcpTransport return cls(TcpTransport(sock), **kw) + @classmethod + def open_usbmux(cls, port: int = 5599, *, socket_path: str = '/var/run/usbmuxd', + serial: str | None = None, timeout: float = 10.0, **kw) -> JetlinkClient: + """Open a direct USB Host-mode usbmuxd tunnel to an iPhone/iPad listening on 127.0.0.1:port.""" + from jetlink.comma.usbmux_transport import UsbmuxClient + transport = UsbmuxClient(socket_path=socket_path).connect(port=port, serial=serial, timeout=timeout) + return cls(transport, **kw) + # -- plumbing ------------------------------------------------------------- def _next_seq(self) -> int: diff --git a/jetlink/comma/usbmux_transport.py b/jetlink/comma/usbmux_transport.py new file mode 100644 index 00000000..e538e55c --- /dev/null +++ b/jetlink/comma/usbmux_transport.py @@ -0,0 +1,723 @@ +""" +Copyright (c) 2026-, Zeph Leggett. + +This file is part of jetlink and is licensed under the MIT License. +See the LICENSE file in the root directory for more details. + +Direct usbmuxd transport for iOS in USB Host mode on the comma. + +Instead of spawning iproxy as an extra localhost-to-localhost copy process, +UsbmuxClient speaks usbmuxd's lightweight plist protocol directly over +/var/run/usbmuxd, upgrades the Unix socket to a USB 3 bulk TCP tunnel targeting +127.0.0.1:5599 inside the iOS app, and hands that descriptor straight to +StreamTransport so Jetlink protocol v3 framing runs unchanged. +""" +from __future__ import annotations + +import logging +import plistlib +import select +import socket +import struct +import threading +import time +from collections.abc import Callable +from dataclasses import dataclass +from pathlib import Path + +from jetlink.transport.base import LinkError, LinkTimeout, StreamTransport, usb_link_info + +log = logging.getLogger('jetlink.comma.usbmux') + +USBMUXD_SOCKET = '/var/run/usbmuxd' +DEFAULT_PORT = 5599 +APPLE_VID = 0x05AC +USB_DEVICES = Path('/sys/bus/usb/devices') +LOCKDOWN_DIR = Path('/data/jetlink/lockdown') +VAR_LOCKDOWN = Path('/var/lib/lockdown') + +# usbmuxd packet header: (length u32, version u32, message u32, tag u32) +USBMUX_HEADER = struct.Struct(' str: + return (serial or '').replace('-', '').strip().lower() + + +def _read_sysfs(path: Path) -> str: + try: + return path.read_text().strip() + except OSError: + return '' + + +def _map_speed(raw_speed: str) -> tuple[float, str] | None: + try: + mbps = float(raw_speed) + except ValueError: + return None + key = str(int(mbps)) if mbps.is_integer() else str(mbps) + if key in SPEED_MBPS_TO_UDC: + return mbps, SPEED_MBPS_TO_UDC[key] + if mbps >= 10000.0: + return mbps, 'super-speed-plus' + if mbps >= 5000.0: + return mbps, 'super-speed' + if mbps >= 480.0: + return mbps, 'high-speed' + if mbps > 0.0: + return mbps, 'full-speed' + return None + + +def detect_apple_usb_speed(usb_devices: Path = USB_DEVICES, serial: str | None = None) -> AppleUsbSpeed | None: + """Inspect Linux USB host sysfs for an attached Apple device (VID 05ac) and + return its negotiated speed, warning if it fell back to USB 2 or slower.""" + try: + entries = sorted(usb_devices.iterdir()) + except OSError: + return None + + want_serial = _normalize_serial(serial) + candidates: list[AppleUsbSpeed] = [] + for entry in entries: + if ':' in entry.name or not entry.is_dir(): + continue + vid_text = _read_sysfs(entry / 'idVendor') + try: + vid = int(vid_text, 16) + except ValueError: + continue + if vid != APPLE_VID: + continue + mapped = _map_speed(_read_sysfs(entry / 'speed')) + if mapped is None: + continue + mbps, udc_speed = mapped + dev_serial = _read_sysfs(entry / 'serial') + product = _read_sysfs(entry / 'product') + info = AppleUsbSpeed( + sysfs_name=entry.name, + speed_mbps=mbps, + udc_speed=udc_speed, + is_usb3=mbps >= 5000.0, + serial=dev_serial, + product=product, + ) + if want_serial and _normalize_serial(dev_serial) == want_serial: + candidates = [info] + break + candidates.append(info) + + if not candidates: + return None + + chosen = max(candidates, key=lambda item: item.speed_mbps) + if not chosen.is_usb3: + log.warning( + "jetlink: Apple device %s (%s) negotiated %s (%.0f Mbps); check powered 10 Gbps USB 3 hub and cable", + chosen.sysfs_name, + chosen.product or '05ac', + chosen.udc_speed, + chosen.speed_mbps, + ) + return chosen + + +def _recv_exact(sock: socket.socket, size: int, deadline: float | None) -> bytes: + buf = bytearray(size) + view = memoryview(buf) + received = 0 + while received < size: + if deadline is not None: + remaining = deadline - time.monotonic() + if remaining <= 0: + raise LinkTimeout("timed out waiting for usbmuxd response") + sock.settimeout(remaining) + else: + sock.settimeout(None) + try: + n = sock.recv_into(view[received:], size - received) + except TimeoutError as e: + raise LinkTimeout("timed out waiting for usbmuxd response") from e + except OSError as e: + raise UsbmuxError(f"usbmuxd recv failed: {e}") from e + if n == 0: + raise UsbmuxError("usbmuxd closed the socket unexpectedly") + received += n + return bytes(buf) + + +def _send_plist(sock: socket.socket, tag: int, payload: dict, deadline: float | None) -> None: + body = plistlib.dumps(payload, fmt=plistlib.FMT_XML) + packet = USBMUX_HEADER.pack(USBMUX_HEADER.size + len(body), USBMUX_PROTOCOL_PLIST, USBMUX_MSG_PLIST, tag) + body + remaining = None if deadline is None else max(0.0, deadline - time.monotonic()) + if deadline is not None and remaining <= 0: + raise LinkTimeout("timed out before sending request to usbmuxd") + sock.settimeout(remaining) + try: + sock.sendall(packet) + except TimeoutError as e: + raise LinkTimeout("timed out sending request to usbmuxd") from e + except OSError as e: + raise UsbmuxError(f"usbmuxd send failed: {e}") from e + + +def _recv_plist(sock: socket.socket, deadline: float | None) -> tuple[int, dict]: + head = _recv_exact(sock, USBMUX_HEADER.size, deadline) + total_len, version, msg_type, tag = USBMUX_HEADER.unpack(head) + if total_len < USBMUX_HEADER.size or total_len > MAX_PLIST_BYTES: + raise UsbmuxError(f"usbmuxd returned invalid packet length {total_len}") + if version != USBMUX_PROTOCOL_PLIST or msg_type != USBMUX_MSG_PLIST: + raise UsbmuxError(f"unexpected usbmuxd packet header (version={version}, msg={msg_type})") + body = _recv_exact(sock, total_len - USBMUX_HEADER.size, deadline) + try: + decoded = plistlib.loads(body) + except Exception as e: + raise UsbmuxError(f"invalid usbmuxd plist payload: {e}") from e + if not isinstance(decoded, dict): + raise UsbmuxError("usbmuxd plist payload is not a dictionary") + return tag, decoded + + +def _parse_device(entry: dict) -> UsbmuxDevice | None: + dev_id = entry.get('DeviceID') + props = entry.get('Properties') + if not isinstance(dev_id, int) or not isinstance(props, dict): + return None + conn_type = str(props.get('ConnectionType') or '') + serial = str(props.get('SerialNumber') or '') + product_id = props.get('ProductID') + speed = props.get('ConnectionSpeed') + return UsbmuxDevice( + device_id=dev_id, + serial=serial, + product_id=int(product_id) if isinstance(product_id, int) else 0, + connection_type=conn_type, + connection_speed=int(speed) if isinstance(speed, int) else None, + ) + + +class UsbmuxTransport(StreamTransport): + """Jetlink StreamTransport over an upgraded usbmuxd Unix domain socket.""" + + def __init__(self, sock: socket.socket, *, device: UsbmuxDevice | None = None, + port: int = DEFAULT_PORT, usb_speed: AppleUsbSpeed | None = None): + super().__init__() + self.sock = sock + self.device = device + self.port = port + self.usb_speed = usb_speed + self._timeout: float | None = -1.0 + self._closed = False + for opt in (socket.SO_SNDBUF, socket.SO_RCVBUF): + try: + sock.setsockopt(socket.SOL_SOCKET, opt, SOCKET_BUF) + except OSError: + pass + + def link_info(self) -> dict[str, str]: + # Report `kind: 'cable'` so Swift's `LinkMedium(link:)` maps `usb_speed` to USB 3/USB 2 parity, + # while skipping AF_UNIX `getsockname()[0]` (which raises or returns a path instead of an IP tuple). + info = usb_link_info('cable', self.usb_speed.udc_speed if self.usb_speed is not None else None) + info['transport'] = 'usbmux' + return info + + def _set_timeout(self, timeout: float | None) -> None: + if timeout != self._timeout: + self.sock.settimeout(timeout) + self._timeout = timeout + + def _write(self, bufs: list[memoryview]) -> int: + self._set_timeout(self._write_timeout()) + try: + return self.sock.sendmsg(bufs) + except OSError as e: + raise LinkError(f"usbmuxd send failed: {e}") from e + + def _read_into(self, dest: memoryview, timeout: float | None) -> int: + self._set_timeout(timeout) + try: + n = self.sock.recv_into(dest, dest.nbytes) + except (TimeoutError, BlockingIOError): + return 0 + except OSError as e: + raise LinkError(f"usbmuxd recv failed: {e}") from e + if n == 0: + raise LinkError("peer closed the usbmuxd connection") + return n + + def close(self) -> None: + if self._closed: + return + self._closed = True + for fn in (lambda: self.sock.shutdown(socket.SHUT_RDWR), self.sock.close): + try: + fn() + except OSError: + pass + + +class UsbmuxClient: + """Direct /var/run/usbmuxd client (zero iproxy subprocesses).""" + + def __init__(self, socket_path: str = USBMUXD_SOCKET, timeout: float = 5.0, usb_devices: Path = USB_DEVICES): + self.socket_path = str(socket_path) + self.timeout = timeout + self.usb_devices = Path(usb_devices) + self._tag = 0 + + def _next_tag(self) -> int: + self._tag += 1 + return self._tag + + def _open_socket(self, timeout: float | None) -> socket.socket: + sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + try: + sock.settimeout(timeout) + sock.connect(self.socket_path) + except TimeoutError as e: + sock.close() + raise LinkTimeout(f"timed out connecting to usbmuxd at {self.socket_path}") from e + except OSError as e: + sock.close() + raise UsbmuxError(f"could not connect to usbmuxd at {self.socket_path}: {e}") from e + return sock + + def list_devices(self, *, usb_only: bool = True, timeout: float | None = None) -> list[UsbmuxDevice]: + wait = self.timeout if timeout is None else timeout + deadline = time.monotonic() + wait + sock = self._open_socket(wait) + try: + _send_plist(sock, self._next_tag(), { + 'MessageType': 'ListDevices', + 'ClientVersionString': 'jetlink', + 'ProgName': 'jetlink', + }, deadline) + _, resp = _recv_plist(sock, deadline) + finally: + sock.close() + + devices: list[UsbmuxDevice] = [] + for entry in resp.get('DeviceList') or (): + if not isinstance(entry, dict): + continue + dev = _parse_device(entry) + if dev is None: + continue + if usb_only and dev.connection_type != 'USB': + continue + devices.append(dev) + return devices + + def wait_for_device(self, timeout: float = 30.0, serial: str | None = None, + should_stop: Callable[[], bool] | None = None) -> UsbmuxDevice: + """Subscribe to usbmuxd Listen events until a matching USB device attaches.""" + deadline = time.monotonic() + timeout + want_serial = _normalize_serial(serial) + sock = self._open_socket(min(self.timeout, max(0.05, timeout))) + try: + _send_plist(sock, self._next_tag(), { + 'MessageType': 'Listen', + 'ClientVersionString': 'jetlink', + 'ProgName': 'jetlink', + }, deadline) + _, ack = _recv_plist(sock, deadline) + if ack.get('MessageType') == 'Result' and ack.get('Number', RESULT_OK) != RESULT_OK: + raise UsbmuxError(f"usbmuxd Listen failed with result {ack.get('Number')}") + + while True: + if should_stop is not None and should_stop(): + raise UsbmuxError("wait for iOS device cancelled") + remaining = deadline - time.monotonic() + if remaining <= 0: + raise LinkTimeout(f"no USB iOS device attached in {timeout:.1f}s") + ready, _, _ = select.select([sock], [], [], min(0.25, remaining)) + if not ready: + continue + _, event = _recv_plist(sock, deadline) + if event.get('MessageType') != 'Attached': + continue + dev = _parse_device(event) + if dev is None or dev.connection_type != 'USB': + continue + if want_serial and _normalize_serial(dev.serial) != want_serial: + continue + return dev + finally: + sock.close() + + def connect_raw(self, device_id: int, port: int = DEFAULT_PORT, timeout: float | None = None) -> socket.socket: + """Ask usbmuxd to upgrade a fresh Unix socket into a tunnel to `port` (network byte order).""" + wait = self.timeout if timeout is None else timeout + deadline = time.monotonic() + wait + sock = self._open_socket(wait) + try: + _send_plist(sock, self._next_tag(), { + 'MessageType': 'Connect', + 'ClientVersionString': 'jetlink', + 'ProgName': 'jetlink', + 'DeviceID': device_id, + # usbmuxd expects the target TCP port in network byte order (big-endian uint16). + 'PortNumber': socket.htons(port), + }, deadline) + _, resp = _recv_plist(sock, deadline) + if resp.get('MessageType') != 'Result': + raise UsbmuxError(f"unexpected Connect reply {resp!r}") + code = resp.get('Number') + if code == RESULT_OK: + sock.settimeout(None) + return sock + if code == RESULT_CONNREFUSED: + raise UsbmuxConnectionRefused(f"device {device_id} refused connection on port {port} (is Jetlink open on iPhone?)") + if code == RESULT_BADDEV: + raise UsbmuxDeviceNotFound(f"usbmuxd device {device_id} is no longer attached") + raise UsbmuxError(f"usbmuxd Connect failed with result {code}") + except BaseException: + sock.close() + raise + + def _pick_device(self, serial: str | None, timeout: float) -> UsbmuxDevice | None: + devices = self.list_devices(usb_only=True, timeout=min(self.timeout, timeout)) + want_serial = _normalize_serial(serial) + for dev in devices: + if not want_serial or _normalize_serial(dev.serial) == want_serial: + return dev + return None + + def connect(self, port: int = DEFAULT_PORT, *, serial: str | None = None, + timeout: float = 10.0, retry_interval: float = 0.25, + should_stop: Callable[[], bool] | None = None) -> UsbmuxTransport: + """Locate an attached USB iOS device, open a direct usbmuxd TCP tunnel, and + return a StreamTransport speaking Jetlink protocol v3.""" + deadline = time.monotonic() + timeout + device: UsbmuxDevice | None = None + last_error: Exception | None = None + + while True: + if should_stop is not None and should_stop(): + raise UsbmuxError("usbmuxd connect cancelled") + remaining = deadline - time.monotonic() + if remaining <= 0: + if last_error is not None: + raise last_error + raise LinkTimeout(f"timed out connecting over usbmuxd to port {port}") + + if device is None: + device = self._pick_device(serial, remaining) + if device is None: + device = self.wait_for_device(timeout=remaining, serial=serial, should_stop=should_stop) + + remaining = deadline - time.monotonic() + if remaining <= 0: + if last_error is not None: + raise last_error + raise LinkTimeout(f"timed out connecting over usbmuxd to port {port}") + + try: + sock = self.connect_raw(device.device_id, port=port, timeout=remaining) + usb_speed = detect_apple_usb_speed(self.usb_devices, serial=device.serial) + return UsbmuxTransport(sock, device=device, port=port, usb_speed=usb_speed) + except UsbmuxDeviceNotFound as e: + last_error = e + device = None + except UsbmuxConnectionRefused as e: + last_error = e + + sleep_for = min(retry_interval, max(0.0, deadline - time.monotonic())) + if sleep_for <= 0: + raise last_error + time.sleep(sleep_for) + + +@dataclass(frozen=True) +class UsbmuxDiagnostic: + code: str + message: str + is_warning: bool + device: UsbmuxDevice | None = None + usb_speed: AppleUsbSpeed | None = None + + +def check_pairing_status(serial: str, lockdown_dirs: tuple[Path, ...] = (LOCKDOWN_DIR, VAR_LOCKDOWN)) -> bool: + """Return True if a lockdown pairing plist exists for `serial`.""" + want = _normalize_serial(serial) + if not want: + return False + for directory in lockdown_dirs: + try: + if not directory.is_dir(): + continue + for plist_file in directory.glob('*.plist'): + if _normalize_serial(plist_file.stem) == want: + return True + except OSError: + continue + return False + + +def diagnose(client: UsbmuxClient, *, lockdown_dirs: tuple[Path, ...] = (LOCKDOWN_DIR, VAR_LOCKDOWN)) -> UsbmuxDiagnostic: + """Inspect usbmuxd reachability, attached iOS device, pairing trust, and USB speed.""" + try: + devices = client.list_devices(usb_only=True) + except UsbmuxError: + return UsbmuxDiagnostic( + code='daemon_unavailable', + message='usbmuxd is not running (run scripts/comma/jetlink-usbmux.sh setup)', + is_warning=True, + ) + if not devices: + return UsbmuxDiagnostic( + code='no_device', + message='No Apple device attached on comma USB Host port', + is_warning=False, + ) + dev = devices[0] + speed = detect_apple_usb_speed(client.usb_devices, serial=dev.serial) + if not check_pairing_status(dev.serial, lockdown_dirs=lockdown_dirs): + return UsbmuxDiagnostic( + code='unpaired', + message='iPhone/iPad connected over USB but unpaired — Tap "Trust This Computer" on iPhone', + is_warning=True, + device=dev, + usb_speed=speed, + ) + if speed is not None and not speed.is_usb3: + return UsbmuxDiagnostic( + code='usb2_fallback', + message=( + f'Apple device negotiated {speed.udc_speed} ({speed.speed_mbps:.0f} Mbps) — ' + 'Check 10 Gbps USB 3 hub/cable' + ), + is_warning=True, + device=dev, + usb_speed=speed, + ) + return UsbmuxDiagnostic( + code='ok', + message='Apple device ready over USB 3 (usbmuxd)', + is_warning=False, + device=dev, + usb_speed=speed, + ) + + +class UsbmuxReconnector: + """Event-driven usbmuxd Listen monitor for < 2 s unplug/replug recovery.""" + + def __init__(self, client: UsbmuxClient | None = None, *, + lockdown_dirs: tuple[Path, ...] = (LOCKDOWN_DIR, VAR_LOCKDOWN)): + self.client = client or UsbmuxClient() + self.lockdown_dirs = lockdown_dirs + self._cond = threading.Condition() + self._devices: dict[int, UsbmuxDevice] = {} + self._stop = threading.Event() + self._thread: threading.Thread | None = None + self._listen_sock: socket.socket | None = None + + def start(self) -> UsbmuxReconnector: + with self._cond: + if self._thread is not None and self._thread.is_alive(): + return self + self._stop.clear() + self._thread = threading.Thread(target=self._run, name='jetlink_usbmux_listen', daemon=True) + self._thread.start() + return self + + def stop(self) -> None: + self._stop.set() + with self._cond: + sock, self._listen_sock = self._listen_sock, None + thread, self._thread = self._thread, None + self._cond.notify_all() + if sock is not None: + for fn in (lambda: sock.shutdown(socket.SHUT_RDWR), sock.close): + try: + fn() + except OSError: + pass + if thread is not None and thread is not threading.current_thread(): + thread.join(timeout=2.0) + + def __enter__(self) -> UsbmuxReconnector: + return self.start() + + def __exit__(self, *_) -> None: + self.stop() + + @property + def devices(self) -> list[UsbmuxDevice]: + with self._cond: + return list(self._devices.values()) + + def _matching_device(self, serial: str | None) -> UsbmuxDevice | None: + want = _normalize_serial(serial) + for dev in self._devices.values(): + if not want or _normalize_serial(dev.serial) == want: + return dev + return None + + def _run(self) -> None: + while not self._stop.is_set(): + sock = None + try: + sock = self.client._open_socket(self.client.timeout) + with self._cond: + self._listen_sock = sock + _send_plist(sock, self.client._next_tag(), { + 'MessageType': 'Listen', + 'ClientVersionString': 'jetlink', + 'ProgName': 'jetlink', + }, time.monotonic() + self.client.timeout) + _, ack = _recv_plist(sock, time.monotonic() + self.client.timeout) + if ack.get('MessageType') == 'Result' and ack.get('Number', RESULT_OK) != RESULT_OK: + raise UsbmuxError(f"usbmuxd Listen failed with result {ack.get('Number')}") + + while not self._stop.is_set(): + ready, _, _ = select.select([sock], [], [], 0.25) + if not ready: + continue + _, event = _recv_plist(sock, time.monotonic() + self.client.timeout) + mtype = event.get('MessageType') + if mtype == 'Attached': + dev = _parse_device(event) + if dev is not None and dev.connection_type == 'USB': + with self._cond: + self._devices[dev.device_id] = dev + self._cond.notify_all() + elif mtype == 'Detached': + dev_id = event.get('DeviceID') + if isinstance(dev_id, int): + with self._cond: + self._devices.pop(dev_id, None) + self._cond.notify_all() + except (UsbmuxError, LinkTimeout, OSError): + with self._cond: + self._devices.clear() + self._cond.notify_all() + finally: + with self._cond: + if self._listen_sock is sock: + self._listen_sock = None + if sock is not None: + try: + sock.close() + except OSError: + pass + if not self._stop.is_set(): + self._stop.wait(0.25) + + def wait_for_device(self, timeout: float = 30.0, serial: str | None = None, + should_stop: Callable[[], bool] | None = None) -> UsbmuxDevice: + self.start() + deadline = time.monotonic() + timeout + with self._cond: + while True: + if should_stop is not None and should_stop(): + raise UsbmuxError("wait for iOS device cancelled") + dev = self._matching_device(serial) + if dev is not None: + return dev + remaining = deadline - time.monotonic() + if remaining <= 0: + raise LinkTimeout(f"no USB iOS device attached in {timeout:.1f}s") + self._cond.wait(timeout=min(0.2, remaining)) + + def connect(self, port: int = DEFAULT_PORT, *, serial: str | None = None, + timeout: float = 10.0, retry_interval: float = 0.2, + should_stop: Callable[[], bool] | None = None) -> UsbmuxTransport: + """Connect immediately using event-tracked device state, recovering fast across drops.""" + self.start() + deadline = time.monotonic() + timeout + last_error: Exception | None = None + warned_unpaired: set[str] = set() + + while True: + if should_stop is not None and should_stop(): + raise UsbmuxError("usbmuxd connect cancelled") + remaining = deadline - time.monotonic() + if remaining <= 0: + if last_error is not None: + raise last_error + raise LinkTimeout(f"timed out connecting over usbmuxd to port {port}") + + with self._cond: + dev = self._matching_device(serial) + if dev is None: + dev = self.wait_for_device(timeout=remaining, serial=serial, should_stop=should_stop) + + if dev.serial and dev.serial not in warned_unpaired and not check_pairing_status(dev.serial, self.lockdown_dirs): + warned_unpaired.add(dev.serial) + log.warning('jetlink: iPhone/iPad (%s) is connected over USB but unpaired — Tap "Trust This Computer" on iPhone', + dev.serial) + + remaining = deadline - time.monotonic() + if remaining <= 0: + if last_error is not None: + raise last_error + raise LinkTimeout(f"timed out connecting over usbmuxd to port {port}") + + try: + sock = self.client.connect_raw(dev.device_id, port=port, timeout=remaining) + usb_speed = detect_apple_usb_speed(self.client.usb_devices, serial=dev.serial) + return UsbmuxTransport(sock, device=dev, port=port, usb_speed=usb_speed) + except UsbmuxDeviceNotFound as e: + last_error = e + with self._cond: + self._devices.pop(dev.device_id, None) + except (UsbmuxConnectionRefused, UsbmuxError) as e: + last_error = e + + sleep_for = min(retry_interval, max(0.0, deadline - time.monotonic())) + if sleep_for <= 0: + raise last_error + if self._stop.wait(sleep_for): + raise UsbmuxError("usbmuxd reconnector stopped") diff --git a/scripts/bench_link.py b/scripts/bench_link.py index 1791a498..d156910d 100644 --- a/scripts/bench_link.py +++ b/scripts/bench_link.py @@ -24,30 +24,35 @@ # from a Mac standing in for the comma: wait for one phone to dial us # (the app dials whatever answers on its cable network), then bench it python3 scripts/bench_link.py --listen 5599 --onnx big_model.onnx + + # over USB Host-mode usbmuxd to an iPhone with Full Frame Experimental Network on + python3 scripts/bench_link.py --usbmux --payload-kb 4096 --rate 20 --n 200 """ from __future__ import annotations import argparse import logging +import math +import statistics import sys import time from pathlib import Path -import numpy as np - -from jetlink.client import JetlinkClient -from jetlink.spec import ModelSpec, spec_from_onnx +from jetlink import protocol as P +from jetlink.transport.base import Transport # modeld's per-frame budget; a frame past it is dropped, and frameDropPerc > 1 soft-disables FRAME_BUDGET_MS = 50.0 +FULL_FRAME_BUDGET_MS = 46.0 # how long a frame sent as datagrams is waited for before it counts as held DATAGRAM_HOLD = 1.0 # how long --loan waits for the gadget owner to lend the link LOAN_TIMEOUT = 60.0 -def load_spec(args) -> ModelSpec | None: +def load_spec(args): """Take the spec from a file or the model itself; None leaves it to the server.""" + from jetlink.spec import ModelSpec, spec_from_onnx if args.spec: return ModelSpec.load(args.spec) if args.onnx: @@ -79,8 +84,33 @@ def _wait_for_host(timeout: float) -> None: raise SystemExit("no USB host attached: check the cable") -def pct(a: np.ndarray, q: float) -> float: - return float(np.percentile(a, q)) +def _percentile(sorted_vals: list[float], q: float) -> float: + if not sorted_vals: + return 0.0 + if len(sorted_vals) == 1: + return sorted_vals[0] + idx = (q / 100.0) * (len(sorted_vals) - 1) + lo = math.floor(idx) + hi = math.ceil(idx) + if lo == hi: + return sorted_vals[lo] + frac = idx - lo + return sorted_vals[lo] * (1.0 - frac) + sorted_vals[hi] * frac + + +def _summary(vals: list[float]) -> tuple[float, float, float, float, float, float, float]: + ordered = sorted(vals) + mean = sum(vals) / len(vals) + stdev = statistics.pstdev(vals) if len(vals) > 1 else 0.0 + return ( + mean, + ordered[0], + _percentile(ordered, 50.0), + _percentile(ordered, 90.0), + _percentile(ordered, 99.0), + ordered[-1], + stdev, + ) def open_loan(timeout: float = LOAN_TIMEOUT): @@ -103,12 +133,17 @@ def open_loan(timeout: float = LOAN_TIMEOUT): def main() -> int: p = argparse.ArgumentParser() g = p.add_mutually_exclusive_group(required=True) - g.add_argument('--host', help='TCP host of the Jetson') + g.add_argument('--host', help='TCP host of the Jetson or loopback server') g.add_argument('--ffs', action='store_true', help='this end is the USB gadget (FunctionFS) - use this on a comma') g.add_argument('--listen', metavar='[HOST:]PORT', help='accept one incoming dial (a phone over the cable network dials the comma; ' 'from a Mac this stands in for it) and bench over that connection') + g.add_argument('--usbmux', action='store_true', + help='connect directly via /var/run/usbmuxd to an iPhone/iPad in USB Host mode') + p.add_argument('--usbmux-socket', default='/var/run/usbmuxd', + help='with --usbmux: path to the usbmuxd Unix domain socket') + p.add_argument('--udid', help='with --usbmux: optional Apple device serial/UDID') p.add_argument('--listen-timeout', type=float, default=120.0, metavar='SECONDS', help='--listen: how long to wait for the dial') p.add_argument('--port', type=int, default=5599) @@ -123,6 +158,8 @@ def main() -> int: p.add_argument('--onnx', help='read the spec from this model, uploading it if the server lacks it') p.add_argument('--sha256', help='model identity, for a model the server already has') p.add_argument('--nbytes', type=int, help='ONNX size in bytes, with --sha256') + p.add_argument('--payload-kb', type=int, + help='synthetic transport-only stress test payload size in KiB (e.g. 384 or 4096) via PING/PONG') p.add_argument('--n', type=int, default=400) p.add_argument('--no-datagrams', action='store_true', help='keep frames on the stream where a phone\'s server offers datagrams, for an A/B') @@ -130,6 +167,15 @@ def main() -> int: args = p.parse_args() if args.loan and not args.ffs: p.error('--loan goes with --ffs') + if args.payload_kb is not None and args.payload_kb < 0: + p.error('--payload-kb must be >= 0') + + if args.payload_kb is not None: + if args.loan: + p.error('--payload-kb does not combine with --loan') + return _run_synthetic_main(args) + + from jetlink.client import JetlinkClient loan = None if args.loan: @@ -137,6 +183,8 @@ def main() -> int: elif args.ffs: # opening this writes the descriptors and binds the UDC, so the Jetson can enumerate us client = JetlinkClient.open_ffs(args.ffs_mount, gadget=args.gadget) + elif args.usbmux: + client = JetlinkClient.open_usbmux(args.port, socket_path=args.usbmux_socket, serial=args.udid) elif args.listen: print(f"waiting up to {args.listen_timeout:.0f}s for a peer to dial {args.listen}...") client = JetlinkClient.open_listen(args.listen, args.listen_timeout) @@ -151,14 +199,121 @@ def main() -> int: loan.close() # the owner takes the endpoints back +def _open_synthetic_transport(args) -> Transport: + if args.ffs: + from jetlink.transport.ffs import FfsTransport + return FfsTransport(args.ffs_mount, gadget=args.gadget) + if args.usbmux: + from jetlink.comma.usbmux_transport import UsbmuxClient + return UsbmuxClient(socket_path=args.usbmux_socket).connect(port=args.port, serial=args.udid) + if args.listen: + from jetlink.transport.tcp import TcpTransport + host, _, port = args.listen.rpartition(':') + if not port.isdigit(): + raise SystemExit(f'listen on [HOST:]PORT, not {args.listen!r}') + print(f"waiting up to {args.listen_timeout:.0f}s for a peer to dial {args.listen}...") + transport, _ = TcpTransport.listen_once(host or '0.0.0.0', int(port), args.listen_timeout) + return transport + from jetlink.transport.tcp import TcpTransport + return TcpTransport.connect(args.host, args.port) + + +def _expect_msg(transport: Transport, msg_type: int, seq: int, timeout: float = 5.0): + deadline = time.monotonic() + timeout + while True: + remaining = max(0.0, deadline - time.monotonic()) + msg = transport.recv(timeout=remaining) + if msg.msg_type == msg_type and msg.seq == seq: + return msg + + +def _run_synthetic_main(args) -> int: + import json + import secrets + + transport = _open_synthetic_transport(args) + try: + if args.wait_host: + _wait_for_host(args.wait_host) + link = transport.link_info() + hello_req = {'client': {'nonce': secrets.token_hex(4), 'name': 'bench', **({'link': link} if link else {})}} + transport.send_json(P.Msg.HELLO_REQ, 1, hello_req) + hello = json.loads(bytes(_expect_msg(transport, P.Msg.HELLO_RESP, 1, 5.0).payload)) + print(f"server: {hello.get('backend', 'trt')} {hello.get('runtime_version', hello.get('trt_version'))} " + f"on {hello['device']}, engine {hello['engine_state']}") + if link: + print(f"link: {link}") + return _run_synthetic(args, transport) + finally: + transport.close() + + +def _run_synthetic(args, transport: Transport) -> int: + payload_bytes = args.payload_kb * 1024 + payload = bytes(payload_bytes) + lat: list[float] = [] + send_ms: list[float] = [] + recv_ms: list[float] = [] + period = 1.0 / args.rate if args.rate > 0 else 0.0 + next_t = time.perf_counter() + + for i in range(args.n): + if period: + now = time.perf_counter() + if next_t > now: + time.sleep(next_t - now) + next_t += period + t = time.perf_counter() + seq = i + 2 + transport.send(P.Msg.PING, seq, (payload,)) + t_sent = time.perf_counter() + _expect_msg(transport, P.Msg.PONG, seq, 5.0) + t_done = time.perf_counter() + lat.append((t_done - t) * 1e3) + send_ms.append((t_sent - t) * 1e3) + recv_ms.append((t_done - t_sent) * 1e3) + + warmup = min(10, max(0, len(lat) // 5)) + sample = lat[warmup:] or lat + snd = send_ms[warmup:] or send_ms + rcv = recv_ms[warmup:] or recv_ms + mean, vmin, p50, p90, p99, vmax, stdev = _summary(sample) + snd_mean, _, snd_p50, _, _, snd_max, _ = _summary(snd) + rcv_mean, _, rcv_p50, _, _, rcv_max, _ = _summary(rcv) + mb_per_s = (payload_bytes / (p50 / 1000.0)) / 1e6 if p50 > 0 else 0.0 + rate_mbps = (payload_bytes * args.rate * 8 / 1e6) if args.rate > 0 else (mb_per_s * 8.0) + + print(f"\nsynthetic transport payload: {payload_bytes / 1024:.0f} KiB ({payload_bytes} B) up, " + f"{rate_mbps:.1f} Mbit/s target (eff {mb_per_s:.1f} MB/s at p50)") + print(f"round trip over {len(sample)} frames (ms):") + print(f" mean {mean:6.2f} min {vmin:6.2f} p50 {p50:6.2f} " + f"p90 {p90:6.2f} p99 {p99:6.2f} max {vmax:6.2f}") + print(f" jitter: p99-p50 {p99 - p50:5.2f} stdev {stdev:5.2f}") + print(f" send ({payload_bytes / 1024:.0f} KiB up): mean {snd_mean:6.2f} p50 {snd_p50:6.2f} max {snd_max:6.2f}") + print(f" recv (PONG ack): mean {rcv_mean:6.2f} p50 {rcv_p50:6.2f} max {rcv_max:6.2f}") + over46 = sum(1 for x in sample if x > FULL_FRAME_BUDGET_MS) + over50 = sum(1 for x in sample if x > FRAME_BUDGET_MS) + print(f"frames over {FULL_FRAME_BUDGET_MS:.0f} ms: {over46}/{len(sample)} ({100 * over46 / len(sample):.1f}%)") + print(f"frames over {FRAME_BUDGET_MS:.0f} ms: {over50}/{len(sample)} ({100 * over50 / len(sample):.1f}%)") + return 0 + + def _run(args, client) -> int: if args.wait_host: _wait_for_host(args.wait_host) client.allow_datagrams = not args.no_datagrams hello = client.hello() + link = client.t.link_info() print(f"server: {hello.get('backend', 'trt')} {hello.get('runtime_version', hello.get('trt_version'))} " f"on {hello['device']}, engine {hello['engine_state']}") + if link: + print(f"link: {link}") + + if args.payload_kb is not None: + return _run_synthetic(args, client) + + import numpy as np spec = load_spec(args) if spec is not None: @@ -166,7 +321,7 @@ def _run(args, client) -> int: elif args.sha256 and args.nbytes: sha256, nbytes = args.sha256, args.nbytes else: - raise SystemExit("need --spec, --onnx, or --sha256 and --nbytes of a model the server already has") + raise SystemExit("need --spec, --onnx, --payload-kb, or --sha256 and --nbytes of a model the server already has") t0 = time.time() spec = client.ensure_engine(sha256, nbytes, onnx_path=args.onnx, progress=lambda s, f, m: print(f" {s:<7} {f*100:5.1f}% {m}")) @@ -205,27 +360,28 @@ def _run(args, client) -> int: queue.append(q_us / 1e3) srv.append(t_us / 1e3) - a = np.array(lat[10:]) + warmup = min(10, max(0, len(lat) // 5)) + a = np.array(lat[warmup:]) print(f"\npayload: {spec.infer_req_nbytes/1e3:.0f} KB up, " f"{spec.infer_resp_nbytes/1e3:.0f} KB down, " f"{(spec.infer_req_nbytes+spec.infer_resp_nbytes)*args.rate*8/1e6:.0f} Mbit/s at {args.rate:g} Hz") print(f"round trip over {len(a)} frames (ms):") - print(f" mean {a.mean():6.2f} min {a.min():6.2f} p50 {pct(a,50):6.2f} " - f"p90 {pct(a,90):6.2f} p99 {pct(a,99):6.2f} max {a.max():6.2f}") - print(f" jitter: p99-p50 {pct(a,99)-pct(a,50):5.2f} stdev {a.std():5.2f}") + print(f" mean {a.mean():6.2f} min {a.min():6.2f} p50 {float(np.percentile(a,50)):6.2f} " + f"p90 {float(np.percentile(a,90)):6.2f} p99 {float(np.percentile(a,99)):6.2f} max {a.max():6.2f}") + print(f" jitter: p99-p50 {float(np.percentile(a,99)-np.percentile(a,50)):5.2f} stdev {a.std():5.2f}") # a USB write returns once the host has taken the data, so send is wire time there; # a TCP send is a memcpy and the whole wire cost lands in recv - snd, rcv = np.array(send_ms[10:]), np.array(recv_ms[10:]) - if args.host or args.listen: - print(" split (TCP): send is the copy into the socket buffer; both directions of wire time are in recv") + snd, rcv = np.array(send_ms[warmup:]), np.array(recv_ms[warmup:]) + if args.host or args.listen or args.usbmux: + print(" split (TCP/usbmux): send is the copy into the socket buffer; both directions of wire time are in recv") else: print(" split (USB): the write blocks until the host has read, so send is request wire time, " "recv is server + reply") - print(f" send ({spec.infer_req_nbytes/1e3:.0f} KB up): mean {snd.mean():6.2f} p50 {pct(snd,50):6.2f} max {snd.max():6.2f}") - print(f" recv ({spec.infer_resp_nbytes/1e3:.0f} KB down): mean {rcv.mean():6.2f} p50 {pct(rcv,50):6.2f} max {rcv.max():6.2f}") - s = np.array(srv[10:]) - print(f"server-side total {np.mean(s):6.2f} ms (gpu {np.mean(gpu[10:]):5.2f}, " - f"queues {np.mean(queue[10:]):5.2f})") + print(f" send ({spec.infer_req_nbytes/1e3:.0f} KB up): mean {snd.mean():6.2f} p50 {float(np.percentile(snd,50)):6.2f} max {snd.max():6.2f}") + print(f" recv ({spec.infer_resp_nbytes/1e3:.0f} KB down): mean {rcv.mean():6.2f} p50 {float(np.percentile(rcv,50)):6.2f} max {rcv.max():6.2f}") + s = np.array(srv[warmup:]) + print(f"server-side total {np.mean(s):6.2f} ms (gpu {np.mean(gpu[warmup:]):5.2f}, " + f"queues {np.mean(queue[warmup:]):5.2f})") print(f"transport overhead: {a.mean() - s.mean():.2f} ms mean") over = int((a > FRAME_BUDGET_MS).sum()) print(f"frames over the {FRAME_BUDGET_MS:.0f} ms budget: {over}/{len(a)} ({100*over/len(a):.1f}%)") diff --git a/scripts/comma/jetlink-usbmux.sh b/scripts/comma/jetlink-usbmux.sh new file mode 100755 index 00000000..03081de5 --- /dev/null +++ b/scripts/comma/jetlink-usbmux.sh @@ -0,0 +1,377 @@ +#!/usr/bin/env bash +# +# Copyright (c) 2026-, Zeph Leggett. +# This file is part of jetlink and is licensed under the MIT License. +# +# Provision and verify USB Host-mode iOS transport over usbmuxd on a comma +# (comma 3X / comma four). Leaves jetlink/comma/jetlink-root.sh and CDC-NCM +# completely untouched; tears down any active gadget via jetlink-root.sh when +# switching to host-mode usbmuxd. +# +# Usage: +# sudo scripts/comma/jetlink-usbmux.sh setup [--install] [--mode3] +# scripts/comma/jetlink-usbmux.sh speed +# scripts/comma/jetlink-usbmux.sh pair +# scripts/comma/jetlink-usbmux.sh status +# sudo scripts/comma/jetlink-usbmux.sh stop +set -euo pipefail + +SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +if [[ -n "${JETLINK_ROOT_SCRIPT:-}" ]]; then + ROOT_SCRIPT=$JETLINK_ROOT_SCRIPT +elif [[ -x "$SCRIPT_DIR/../../jetlink/comma/jetlink-root.sh" ]]; then + ROOT_SCRIPT="$SCRIPT_DIR/../../jetlink/comma/jetlink-root.sh" +else + ROOT_SCRIPT="$SCRIPT_DIR/jetlink-root.sh" +fi + +GADGET=${JETLINK_GADGET:-/sys/kernel/config/usb_gadget/jetlink} +UDC_GLUE=${JETLINK_UDC_GLUE:-/sys/devices/platform/soc/a600000.ssusb} +USB_DEVICES=${JETLINK_USB_DEVICES:-/sys/bus/usb/devices} +LOCKDOWN_DIR=${JETLINK_LOCKDOWN_DIR:-/data/jetlink/lockdown} +VAR_LOCKDOWN=${JETLINK_VAR_LOCKDOWN:-/var/lib/lockdown} +BIN_DIR=${JETLINK_BIN_DIR:-/data/jetlink/bin} +USBMUXD_SOCKET=${JETLINK_USBMUXD_SOCKET:-/var/run/usbmuxd} +USBMUXD_PID=${JETLINK_USBMUXD_PID:-/dev/shm/jetlink-usbmuxd.pid} +USBMUXD_MODE_FILE=${JETLINK_USBMUXD_MODE_FILE:-/dev/shm/jetlink-usbmuxd.mode} + +APPLE_VID=05ac + +if [[ -d "$BIN_DIR" ]]; then + PATH="$BIN_DIR:$PATH" + export PATH +fi + +usage() { + echo "usage: $0 setup [--install] [--mode3] | speed | pair | status | stop" >&2 + exit 2 +} + +require_root() { + if [[ $EUID -ne 0 && "${JETLINK_ALLOW_NONROOT:-0}" != "1" ]]; then + echo "jetlink-usbmux: $1 must run as root (sudo)" >&2 + exit 1 + fi +} + +trim_sysfs() { + local path=$1 raw="" + if [[ -r "$path" ]]; then + IFS= read -r raw < "$path" || true + fi + raw=${raw//$'\r'/} + raw=${raw#"${raw%%[![:space:]]*}"} + raw=${raw%"${raw##*[![:space:]]}"} + printf '%s' "$raw" +} + +restore_host_mode() { + local mode="" + if [[ -d "$GADGET" ]]; then + if [[ -x "$ROOT_SCRIPT" || -f "$ROOT_SCRIPT" ]]; then + echo "jetlink-usbmux: tearing down active USB gadget via $ROOT_SCRIPT" + bash "$ROOT_SCRIPT" teardown || echo "jetlink-usbmux: warning: gadget teardown returned non-zero" >&2 + else + echo "jetlink-usbmux: warning: active gadget at $GADGET but root script not found at $ROOT_SCRIPT" >&2 + fi + fi + + if [[ -x "$ROOT_SCRIPT" || -f "$ROOT_SCRIPT" ]]; then + bash "$ROOT_SCRIPT" port off 2>/dev/null || true + bash "$ROOT_SCRIPT" udc restore 2>/dev/null || true + fi + + if [[ -e "$UDC_GLUE/mode" ]]; then + mode=$(trim_sysfs "$UDC_GLUE/mode") + if [[ "$mode" == "peripheral" ]]; then + echo "jetlink-usbmux: switching $UDC_GLUE/mode from peripheral to host" + if ! printf 'host\n' > "$UDC_GLUE/mode" 2>/dev/null; then + echo "jetlink-usbmux: warning: could not write host to $UDC_GLUE/mode" >&2 + fi + else + echo "jetlink-usbmux: UDC glue mode is '${mode:-unknown}' (host mode ready)" + fi + fi +} + +setup_persistent_lockdown() { + local f dst + mkdir -p "$LOCKDOWN_DIR" + chmod 0755 "$LOCKDOWN_DIR" + + if [[ -L "$VAR_LOCKDOWN" ]]; then + local target + target=$(readlink -f "$VAR_LOCKDOWN" 2>/dev/null || readlink "$VAR_LOCKDOWN" 2>/dev/null || true) + if [[ "$target" == "$LOCKDOWN_DIR" ]]; then + echo "jetlink-usbmux: persistent lockdown active ($VAR_LOCKDOWN -> $LOCKDOWN_DIR)" + return 0 + fi + fi + + if [[ -d "$VAR_LOCKDOWN" && ! -L "$VAR_LOCKDOWN" ]]; then + shopt -s nullglob + for f in "$VAR_LOCKDOWN"/*.plist; do + dst="$LOCKDOWN_DIR/$(basename "$f")" + [[ -e "$dst" ]] || cp -p "$f" "$dst" 2>/dev/null || true + done + shopt -u nullglob + fi + + if [[ -e "$VAR_LOCKDOWN" && ! -L "$VAR_LOCKDOWN" ]]; then + if rm -rf "$VAR_LOCKDOWN" 2>/dev/null && ln -s "$LOCKDOWN_DIR" "$VAR_LOCKDOWN" 2>/dev/null; then + echo "jetlink-usbmux: linked $VAR_LOCKDOWN -> $LOCKDOWN_DIR" + return 0 + fi + elif ln -sfn "$LOCKDOWN_DIR" "$VAR_LOCKDOWN" 2>/dev/null; then + echo "jetlink-usbmux: linked $VAR_LOCKDOWN -> $LOCKDOWN_DIR" + return 0 + fi + + if command -v mountpoint >/dev/null 2>&1 && mountpoint -q "$VAR_LOCKDOWN" 2>/dev/null; then + echo "jetlink-usbmux: persistent lockdown bind-mounted at $VAR_LOCKDOWN" + return 0 + fi + + mkdir -p "$VAR_LOCKDOWN" 2>/dev/null || true + if [[ -d "$VAR_LOCKDOWN" ]] && mount --bind "$LOCKDOWN_DIR" "$VAR_LOCKDOWN" 2>/dev/null; then + echo "jetlink-usbmux: bind-mounted $LOCKDOWN_DIR onto $VAR_LOCKDOWN" + return 0 + fi + + echo "jetlink-usbmux: error: could not map persistent lockdown $VAR_LOCKDOWN -> $LOCKDOWN_DIR (AGNOS read-only rootfs?)" >&2 + echo "jetlink-usbmux: hint: check /etc/fstab bind mount or remount rootfs read-write once for symlink creation" >&2 + return 1 +} + +ensure_usbmuxd_binaries() { + local do_install=${1:-0} + if command -v usbmuxd >/dev/null 2>&1 && command -v idevicepair >/dev/null 2>&1; then + return 0 + fi + + if [[ $do_install -eq 1 ]] && command -v apt-get >/dev/null 2>&1; then + echo "jetlink-usbmux: installing usbmuxd and libimobiledevice-utils via apt-get" + if apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y usbmuxd libimobiledevice-utils; then + if command -v usbmuxd >/dev/null 2>&1 && command -v idevicepair >/dev/null 2>&1; then + return 0 + fi + fi + fi + + echo "jetlink-usbmux: missing usbmuxd and/or idevicepair (PATH=$PATH)" >&2 + echo "jetlink-usbmux: on AGNOS read-only rootfs, stage static arm64 binaries under $BIN_DIR/usbmuxd and $BIN_DIR/idevicepair," >&2 + echo "jetlink-usbmux: or run '$0 setup --install' on a writable rootfs." >&2 + return 1 +} + +usbmuxd_running() { + local pid="" + if [[ -r "$USBMUXD_PID" ]]; then + IFS= read -r pid < "$USBMUXD_PID" || true + if [[ -n "$pid" ]] && kill -0 "$pid" 2>/dev/null; then + return 0 + fi + fi + if command -v pgrep >/dev/null 2>&1 && pgrep -x usbmuxd >/dev/null 2>&1; then + return 0 + fi + return 1 +} + +start_usbmuxd() { + local want_mode=${1:-variant-a} i pid="" cur_mode="" + if [[ -r "$USBMUXD_MODE_FILE" ]]; then + IFS= read -r cur_mode < "$USBMUXD_MODE_FILE" || true + fi + if [[ -S "$USBMUXD_SOCKET" ]] && usbmuxd_running; then + if [[ "$cur_mode" == "$want_mode" || ( -z "$cur_mode" && "$want_mode" == "variant-a" ) ]]; then + echo "jetlink-usbmux: usbmuxd already active at $USBMUXD_SOCKET ($want_mode)" + return 0 + fi + echo "jetlink-usbmux: restarting jetlink-managed usbmuxd for $want_mode" + cmd_stop + fi + + if [[ "$want_mode" == "mode-3" ]]; then + export USBMUXD_DEFAULT_DEVICE_MODE=3 + echo "jetlink-usbmux: launching usbmuxd with USBMUXD_DEFAULT_DEVICE_MODE=3 (Variant B host cdc_ncm)" + elif [[ -n "${USBMUXD_DEFAULT_DEVICE_MODE:-}" ]]; then + export USBMUXD_DEFAULT_DEVICE_MODE + echo "jetlink-usbmux: launching usbmuxd with USBMUXD_DEFAULT_DEVICE_MODE=$USBMUXD_DEFAULT_DEVICE_MODE" + else + unset USBMUXD_DEFAULT_DEVICE_MODE 2>/dev/null || true + echo "jetlink-usbmux: launching usbmuxd (Variant A USB 3 bulk tunnel mode)" + fi + + # Run usbmuxd in foreground under background job with root user so pairing records + # land in the persistent lockdown directory even without a dedicated usbmux user. + usbmuxd -f -u -U root >/dev/shm/jetlink-usbmuxd.log 2>&1 & + pid=$! + printf '%s\n' "$pid" > "$USBMUXD_PID" + printf '%s\n' "$want_mode" > "$USBMUXD_MODE_FILE" + + for ((i = 0; i < 50; i++)); do + if [[ -S "$USBMUXD_SOCKET" ]]; then + echo "jetlink-usbmux: usbmuxd listening at $USBMUXD_SOCKET (pid $pid, $want_mode)" + return 0 + fi + if ! kill -0 "$pid" 2>/dev/null; then + rm -f "$USBMUXD_PID" "$USBMUXD_MODE_FILE" + echo "jetlink-usbmux: usbmuxd exited unexpectedly; see /dev/shm/jetlink-usbmuxd.log" >&2 + return 1 + fi + sleep 0.1 + done + + echo "jetlink-usbmux: timed out waiting for $USBMUXD_SOCKET" >&2 + return 1 +} + +cmd_speed() { + local dev name vid pid spd product serial + local found=0 any_usb2=0 + if [[ ! -d "$USB_DEVICES" ]]; then + echo "jetlink-usbmux: no USB sysfs at $USB_DEVICES" >&2 + return 1 + fi + + shopt -s nullglob + for dev in "$USB_DEVICES"/*; do + [[ -d "$dev" ]] || continue + name=$(basename "$dev") + [[ "$name" == *:* ]] && continue + vid=$(trim_sysfs "$dev/idVendor" | tr '[:upper:]' '[:lower:]') + [[ "$vid" == "$APPLE_VID" ]] || continue + found=1 + pid=$(trim_sysfs "$dev/idProduct" | tr '[:upper:]' '[:lower:]') + spd=$(trim_sysfs "$dev/speed") + product=$(trim_sysfs "$dev/product") + serial=$(trim_sysfs "$dev/serial") + case "$spd" in + 10000) + echo "jetlink-usbmux: [$name] Apple device (${product:-05ac:${pid:-?}}, serial ${serial:-?}) at USB 3.2 Gen 2 (10000 Mbps, super-speed-plus)" + ;; + 5000) + echo "jetlink-usbmux: [$name] Apple device (${product:-05ac:${pid:-?}}, serial ${serial:-?}) at USB 3.0 (5000 Mbps, super-speed)" + ;; + 480) + any_usb2=1 + echo "jetlink-usbmux: WARNING: [$name] Apple device (${product:-05ac:${pid:-?}}) fell back to USB 2.0 (480 Mbps, high-speed) — check powered 10 Gbps USB 3 hub and cable!" >&2 + ;; + 12|1.5) + any_usb2=1 + echo "jetlink-usbmux: WARNING: [$name] Apple device (${product:-05ac:${pid:-?}}) at USB 1.x (${spd} Mbps) — check USB 3 hub and cable!" >&2 + ;; + *) + any_usb2=1 + echo "jetlink-usbmux: WARNING: [$name] Apple device (${product:-05ac:${pid:-?}}) at unknown speed '${spd:-?}'" >&2 + ;; + esac + done + shopt -u nullglob + + if [[ $found -eq 0 ]]; then + echo "jetlink-usbmux: no Apple USB device (VID $APPLE_VID) attached under $USB_DEVICES" + return 1 + fi + if [[ $any_usb2 -ne 0 ]]; then + return 2 + fi + return 0 +} + +cmd_pair() { + if ! command -v idevicepair >/dev/null 2>&1; then + echo "jetlink-usbmux: idevicepair not found in PATH ($PATH)" >&2 + return 1 + fi + if idevicepair validate >/dev/null 2>&1; then + echo "jetlink-usbmux: iPhone/iPad pairing validated (trust already stored)" + return 0 + fi + echo "jetlink-usbmux: device not paired yet — unlock iPhone/iPad and tap \"Trust This Computer\" when prompted" + idevicepair pair +} + +cmd_setup() { + local do_install=0 want_mode="variant-a" arg + for arg in "$@"; do + case "$arg" in + --install) do_install=1 ;; + --mode3) want_mode="mode-3" ;; + *) usage ;; + esac + done + require_root setup + restore_host_mode + setup_persistent_lockdown + ensure_usbmuxd_binaries "$do_install" + start_usbmuxd "$want_mode" + cmd_speed || true +} + +cmd_status() { + local mode="unknown" count=0 target="(not a symlink)" active_mode="" + if [[ -e "$UDC_GLUE/mode" ]]; then + mode=$(trim_sysfs "$UDC_GLUE/mode") + fi + echo "UDC glue mode: ${mode:-unknown}" + if [[ -d "$GADGET" ]]; then + echo "CDC-NCM/FFS gadget: present at $GADGET (bound: $(trim_sysfs "$GADGET/UDC"))" + else + echo "CDC-NCM/FFS gadget: absent (host mode clean)" + fi + if [[ -L "$VAR_LOCKDOWN" ]]; then + target=$(readlink -f "$VAR_LOCKDOWN" 2>/dev/null || readlink "$VAR_LOCKDOWN" 2>/dev/null || echo "unreadable") + fi + if [[ -d "$LOCKDOWN_DIR" ]]; then + shopt -s nullglob + local plists=("$LOCKDOWN_DIR"/*.plist) + shopt -u nullglob + count=${#plists[@]} + fi + echo "Lockdown dir: $LOCKDOWN_DIR ($count pairing record(s)); $VAR_LOCKDOWN -> $target" + if [[ -r "$USBMUXD_MODE_FILE" ]]; then + IFS= read -r active_mode < "$USBMUXD_MODE_FILE" || true + fi + echo "usbmuxd mode: ${active_mode:-variant-a}" + if command -v usbmuxd >/dev/null 2>&1; then + echo "usbmuxd binary: $(command -v usbmuxd)" + else + echo "usbmuxd binary: missing" + fi + if [[ -S "$USBMUXD_SOCKET" ]]; then + echo "usbmuxd socket: active at $USBMUXD_SOCKET" + else + echo "usbmuxd socket: absent ($USBMUXD_SOCKET)" + fi + cmd_speed || true +} + +cmd_stop() { + local pid="" + require_root stop + if [[ -r "$USBMUXD_PID" ]]; then + IFS= read -r pid < "$USBMUXD_PID" || true + if [[ -n "$pid" ]] && kill -0 "$pid" 2>/dev/null; then + kill "$pid" 2>/dev/null || true + echo "jetlink-usbmux: stopped jetlink-managed usbmuxd (pid $pid)" + fi + rm -f "$USBMUXD_PID" "$USBMUXD_MODE_FILE" + else + echo "jetlink-usbmux: no jetlink-managed usbmuxd pid file at $USBMUXD_PID" + fi +} + +cmd=${1:-} +if [[ $# -gt 0 ]]; then + shift +fi +case "$cmd" in + setup) cmd_setup "$@" ;; + speed) cmd_speed ;; + pair) cmd_pair ;; + status) cmd_status ;; + stop) cmd_stop ;; + *) usage ;; +esac diff --git a/scripts/verify_parity.py b/scripts/verify_parity.py index 12ca962e..1141b131 100644 --- a/scripts/verify_parity.py +++ b/scripts/verify_parity.py @@ -164,6 +164,8 @@ def capture(args) -> int: client.want_hidden = True elif args.ffs: client = JetlinkClient.open_ffs(args.ffs_mount, gadget=args.gadget, want_hidden=True) + elif args.usbmux: + client = JetlinkClient.open_usbmux(args.port, socket_path=args.usbmux_socket, serial=args.udid, want_hidden=True) elif args.host: client = JetlinkClient.open_tcp(args.host, args.port, want_hidden=True) else: @@ -464,6 +466,9 @@ def main() -> int: p.add_argument('--gadget', default='/sys/kernel/config/usb_gadget/jetlink') p.add_argument('--host', help='capture mode: the server over TCP') p.add_argument('--port', type=int, default=5599) + p.add_argument('--usbmux', action='store_true', help='capture mode: direct /var/run/usbmuxd tunnel') + p.add_argument('--usbmux-socket', default='/var/run/usbmuxd', help='--usbmux: path to usbmuxd Unix socket') + p.add_argument('--udid', help='--usbmux: optional Apple device serial/UDID') p.add_argument('--listen', metavar='[HOST:]PORT', help='capture mode: accept one incoming dial (a phone over the cable network ' 'dials the comma; from a Mac this stands in for it)') @@ -471,8 +476,8 @@ def main() -> int: help='--listen: how long to wait for the dial') args = p.parse_args() - if args.mode == 'capture' and sum(map(bool, (args.ffs, args.host, args.listen))) != 1: - p.error('capture takes one of --ffs, --host and --listen') + if args.mode == 'capture' and sum(map(bool, (args.ffs, args.host, args.listen, args.usbmux))) != 1: + p.error('capture takes one of --ffs, --host, --listen, or --usbmux') if args.mode == 'reference' and not args.onnx: raise SystemExit('reference mode needs --onnx') diff --git a/tests/test_usbmux_transport.py b/tests/test_usbmux_transport.py new file mode 100644 index 00000000..85579ef7 --- /dev/null +++ b/tests/test_usbmux_transport.py @@ -0,0 +1,654 @@ +""" +Copyright (c) 2026-, Zeph Leggett. + +This file is part of jetlink and is licensed under the MIT License. +See the LICENSE file in the root directory for more details. + +Unit tests for Phase 1: jetlink.comma.usbmux_transport and scripts/comma/jetlink-usbmux.sh. +""" +from __future__ import annotations + +import ast +import json +import os +import plistlib +import socket +import struct +import subprocess +import sys +import tempfile +import threading +import time +import unittest +from pathlib import Path + +from jetlink import protocol as P +from jetlink.comma.usbmux_transport import ( + RESULT_BADDEV, + RESULT_CONNREFUSED, + RESULT_OK, + USBMUX_HEADER, + USBMUX_MSG_PLIST, + USBMUX_PROTOCOL_PLIST, + UsbmuxClient, + UsbmuxConnectionRefused, + UsbmuxReconnector, + UsbmuxTransport, + detect_apple_usb_speed, + diagnose, +) +from jetlink.transport.base import LinkError, LinkTimeout + +REPO = Path(__file__).resolve().parents[1] +USBMUX_SCRIPT = REPO / 'scripts' / 'comma' / 'jetlink-usbmux.sh' + + +def _send_mux_plist(sock: socket.socket, tag: int, payload: dict) -> None: + body = plistlib.dumps(payload, fmt=plistlib.FMT_XML) + packet = USBMUX_HEADER.pack(USBMUX_HEADER.size + len(body), USBMUX_PROTOCOL_PLIST, USBMUX_MSG_PLIST, tag) + body + sock.sendall(packet) + + +def _recv_exact(sock: socket.socket, size: int) -> bytes: + out = bytearray() + while len(out) < size: + chunk = sock.recv(size - len(out)) + if not chunk: + raise EOFError("unexpected EOF on fake usbmuxd socket") + out.extend(chunk) + return bytes(out) + + +def _recv_mux_plist(sock: socket.socket) -> tuple[int, dict]: + total_len, version, msg_type, tag = USBMUX_HEADER.unpack(_recv_exact(sock, USBMUX_HEADER.size)) + assert version == USBMUX_PROTOCOL_PLIST + assert msg_type == USBMUX_MSG_PLIST + body = _recv_exact(sock, total_len - USBMUX_HEADER.size) + return tag, plistlib.loads(body) + + +def _recv_jlnk_exact(sock: socket.socket) -> tuple[int, int, int, bytes]: + hdr = _recv_exact(sock, P.HEADER_SIZE) + _, _, msg_type, seq, flags, length, _ = P.unpack_header(hdr) + payload = _recv_exact(sock, length) + if flags & P.Flag.PADDED: + _recv_exact(sock, 1) + return msg_type, seq, flags, payload + + +def _send_jlnk(sock: socket.socket, msg_type: int, seq: int, payload: bytes, flags: int = 0) -> None: + if (P.HEADER_SIZE + len(payload)) % P.PACKET_MULTIPLE == 0: + flags |= P.Flag.PADDED + pad = b'\x00' + else: + pad = b'' + sock.sendall(P.pack_header(msg_type, seq, len(payload), flags) + payload + pad) + + +class FakeUsbmuxDaemon: + """In-process mock /var/run/usbmuxd daemon speaking plist framing.""" + + def __init__(self, socket_path: str, devices: list[dict] | None = None, on_connect=None): + self.socket_path = socket_path + self.devices = list(devices or []) + self.on_connect = on_connect + self.connect_results: list[int] = [] + self.connect_ports: list[int] = [] + self.lock = threading.Lock() + self._listeners: list[socket.socket] = [] + self._handlers: list[threading.Thread] = [] + self._stop = threading.Event() + self._srv = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + self._srv.bind(socket_path) + self._srv.listen(8) + self._srv.settimeout(0.1) + self._accept_thread = threading.Thread(target=self._accept_loop, daemon=True) + self._accept_thread.start() + + def attach_device(self, device: dict) -> None: + with self.lock: + self.devices.append(device) + listeners = list(self._listeners) + event = { + 'MessageType': 'Attached', + 'DeviceID': device['DeviceID'], + 'Properties': device['Properties'], + } + for conn in listeners: + try: + _send_mux_plist(conn, 0, event) + except OSError: + pass + + def detach_device(self, device_id: int) -> None: + with self.lock: + self.devices = [d for d in self.devices if d['DeviceID'] != device_id] + listeners = list(self._listeners) + event = {'MessageType': 'Detached', 'DeviceID': device_id} + for conn in listeners: + try: + _send_mux_plist(conn, 0, event) + except OSError: + pass + + def _accept_loop(self) -> None: + while not self._stop.is_set(): + try: + conn, _ = self._srv.accept() + except (TimeoutError, OSError): + continue + t = threading.Thread(target=self._serve_client, args=(conn,), daemon=True) + with self.lock: + self._handlers.append(t) + t.start() + + def _serve_client(self, conn: socket.socket) -> None: + close_in_finally = True + try: + conn.settimeout(5.0) + tag, req = _recv_mux_plist(conn) + mtype = req.get('MessageType') + if mtype == 'ListDevices': + with self.lock: + devs = list(self.devices) + _send_mux_plist(conn, tag, {'MessageType': 'ListDevices', 'DeviceList': devs}) + elif mtype == 'Listen': + _send_mux_plist(conn, tag, {'MessageType': 'Result', 'Number': RESULT_OK}) + with self.lock: + self._listeners.append(conn) + initial = list(self.devices) + for dev in initial: + _send_mux_plist(conn, 0, { + 'MessageType': 'Attached', + 'DeviceID': dev['DeviceID'], + 'Properties': dev['Properties'], + }) + while not self._stop.is_set(): + time.sleep(0.05) + elif mtype == 'Connect': + dev_id = req.get('DeviceID') + port_nbo = req.get('PortNumber') + with self.lock: + self.connect_ports.append(port_nbo) + has_dev = any(d['DeviceID'] == dev_id for d in self.devices) + code = self.connect_results.pop(0) if self.connect_results else (RESULT_OK if has_dev else RESULT_BADDEV) + _send_mux_plist(conn, tag, {'MessageType': 'Result', 'Number': code}) + if code == RESULT_OK and self.on_connect is not None: + close_in_finally = False + self.on_connect(conn, dev_id) + except (EOFError, OSError): + pass + finally: + with self.lock: + if conn in self._listeners: + self._listeners.remove(conn) + if close_in_finally: + try: + conn.close() + except OSError: + pass + + def close(self) -> None: + self._stop.set() + try: + self._srv.close() + except OSError: + pass + with self.lock: + listeners = list(self._listeners) + self._listeners.clear() + for conn in listeners: + try: + conn.close() + except OSError: + pass + self._accept_thread.join(timeout=2.0) + for t in list(self._handlers): + t.join(timeout=2.0) + + +def _usb_dev(device_id: int = 1, serial: str = '00008130-001122334455', speed: int = 10000) -> dict: + return { + 'DeviceID': device_id, + 'Properties': { + 'SerialNumber': serial, + 'ProductID': 0x12A8, + 'ConnectionType': 'USB', + 'ConnectionSpeed': speed, + }, + } + + +def _make_fake_usb_device(root: Path, name: str, vid: str, speed: str, serial: str = '', product: str = 'iPhone') -> Path: + d = root / name + d.mkdir(parents=True, exist_ok=True) + (d / 'idVendor').write_text(vid + '\n') + (d / 'idProduct').write_text('12a8\n') + (d / 'speed').write_text(speed + '\n') + if serial: + (d / 'serial').write_text(serial + '\n') + if product: + (d / 'product').write_text(product + '\n') + return d + + +class UsbmuxTransportTests(unittest.TestCase): + def setUp(self) -> None: + self._tmp = tempfile.TemporaryDirectory(dir='/tmp', prefix='jlux_') + self.tmp_path = Path(self._tmp.name) + self.sock_path = str(self.tmp_path / 'usbmuxd') + self.usb_sysfs = self.tmp_path / 'usb' + self.usb_sysfs.mkdir() + self._daemons: list[FakeUsbmuxDaemon] = [] + + def tearDown(self) -> None: + for d in self._daemons: + d.close() + self._tmp.cleanup() + + def _start_daemon(self, devices: list[dict] | None = None, on_connect=None) -> FakeUsbmuxDaemon: + d = FakeUsbmuxDaemon(self.sock_path, devices=devices, on_connect=on_connect) + self._daemons.append(d) + return d + + def test_list_devices_filters_usb_only(self) -> None: + wifi_dev = { + 'DeviceID': 9, + 'Properties': {'SerialNumber': 'wifi-dev', 'ProductID': 0x12A8, 'ConnectionType': 'Network'}, + } + self._start_daemon(devices=[wifi_dev, _usb_dev(device_id=3, serial='ABC-123')]) + client = UsbmuxClient(socket_path=self.sock_path, usb_devices=self.usb_sysfs) + + usb_devs = client.list_devices(usb_only=True) + self.assertEqual(len(usb_devs), 1) + self.assertEqual(usb_devs[0].device_id, 3) + self.assertEqual(usb_devs[0].serial, 'ABC-123') + self.assertEqual(usb_devs[0].connection_type, 'USB') + + all_devs = client.list_devices(usb_only=False) + self.assertEqual(len(all_devs), 2) + + def test_connect_uses_network_byte_order_and_speaks_protocol_v3(self) -> None: + _make_fake_usb_device(self.usb_sysfs, '2-1', '05ac', '10000', serial='00008130001122334455', product='iPhone 16 Pro') + + def handle_tunnel(peer: socket.socket, _dev_id: int) -> None: + try: + while True: + mtype, seq, _flags, payload = _recv_jlnk_exact(peer) + if mtype == P.Msg.HELLO_REQ: + _send_jlnk(peer, P.Msg.HELLO_RESP, seq, json.dumps({'protocol': P.VERSION, 'device': 'iPhone'}).encode()) + elif mtype == P.Msg.PING: + _send_jlnk(peer, P.Msg.PONG, seq, b'') + elif mtype == P.Msg.INFER_REQ: + frame_id, req_flags = P.unpack_infer_req(payload, 0) + self.assertEqual(len(payload), P.INFER_REQ_SIZE + 393216) + self.assertEqual(frame_id, 42) + self.assertEqual(req_flags, P.Flag.RESET_QUEUES) + resp = P.pack_infer_resp(frame_id, P.Status.OK, 500, 100, 700) + b'\x7f' * 8192 + _send_jlnk(peer, P.Msg.INFER_RESP, seq, resp) + break + except EOFError: + pass + finally: + peer.close() + + daemon = self._start_daemon(devices=[_usb_dev(device_id=7)], on_connect=handle_tunnel) + client = UsbmuxClient(socket_path=self.sock_path, usb_devices=self.usb_sysfs) + transport = client.connect(port=5599, timeout=3.0) + try: + self.assertEqual(daemon.connect_ports, [socket.htons(5599)]) + self.assertEqual(transport.link_info(), {'kind': 'cable', 'usb_speed': 'super-speed-plus', 'transport': 'usbmux'}) + + transport.send_json(P.Msg.HELLO_REQ, 1, {'client': {'name': 'test', 'link': transport.link_info()}}) + hello_resp = transport.recv(timeout=2.0) + self.assertEqual(hello_resp.msg_type, P.Msg.HELLO_RESP) + self.assertEqual(hello_resp.seq, 1) + self.assertEqual(json.loads(bytes(hello_resp.payload))['protocol'], P.VERSION) + + transport.send(P.Msg.PING, 2) + pong = transport.recv(timeout=2.0) + self.assertEqual(pong.msg_type, P.Msg.PONG) + self.assertEqual(pong.seq, 2) + + frame_bytes = os.urandom(393216) + infer_head = P.pack_infer_req(42, P.Flag.RESET_QUEUES) + transport.send(P.Msg.INFER_REQ, 3, (infer_head, frame_bytes)) + resp = transport.recv(timeout=2.0) + self.assertEqual(resp.msg_type, P.Msg.INFER_RESP) + fid, status, gpu_us, queue_us, total_us = P.unpack_infer_resp(resp.payload, 0) + self.assertEqual((fid, status, gpu_us, queue_us, total_us), (42, P.Status.OK, 500, 100, 700)) + self.assertEqual(len(resp.payload), P.INFER_RESP_SIZE + 8192) + finally: + transport.close() + + def test_connect_retries_on_connection_refused(self) -> None: + def echo_once(peer: socket.socket, _dev_id: int) -> None: + try: + mtype, seq, _flags, _ = _recv_jlnk_exact(peer) + if mtype == P.Msg.PING: + _send_jlnk(peer, P.Msg.PONG, seq, b'') + except EOFError: + pass + finally: + peer.close() + + daemon = self._start_daemon(devices=[_usb_dev(device_id=1)], on_connect=echo_once) + daemon.connect_results = [RESULT_CONNREFUSED, RESULT_CONNREFUSED, RESULT_OK] + client = UsbmuxClient(socket_path=self.sock_path, usb_devices=self.usb_sysfs) + transport = client.connect(port=5599, timeout=3.0, retry_interval=0.05) + try: + self.assertEqual(len(daemon.connect_ports), 3) + transport.send(P.Msg.PING, 1) + self.assertEqual(transport.recv(timeout=2.0).msg_type, P.Msg.PONG) + finally: + transport.close() + + def test_wait_for_device_attach_via_listen(self) -> None: + def echo_once(peer: socket.socket, _dev_id: int) -> None: + try: + mtype, seq, _flags, _ = _recv_jlnk_exact(peer) + if mtype == P.Msg.PING: + _send_jlnk(peer, P.Msg.PONG, seq, b'') + except EOFError: + pass + finally: + peer.close() + + daemon = self._start_daemon(devices=[], on_connect=echo_once) + timer = threading.Timer(0.15, daemon.attach_device, args=(_usb_dev(device_id=12, serial='ATTACHED-1'),)) + timer.start() + try: + client = UsbmuxClient(socket_path=self.sock_path, usb_devices=self.usb_sysfs) + transport = client.connect(port=5599, timeout=3.0, retry_interval=0.05) + try: + self.assertIsNotNone(transport.device) + self.assertEqual(transport.device.device_id, 12) + transport.send(P.Msg.PING, 1) + self.assertEqual(transport.recv(timeout=2.0).msg_type, P.Msg.PONG) + finally: + transport.close() + finally: + timer.cancel() + + def test_disconnect_and_reconnect(self) -> None: + connected_ids: list[int] = [] + + def handler(peer: socket.socket, dev_id: int) -> None: + connected_ids.append(dev_id) + try: + if dev_id == 1: + return # drop immediately to simulate unplug / app termination + mtype, seq, _flags, _ = _recv_jlnk_exact(peer) + if mtype == P.Msg.PING: + _send_jlnk(peer, P.Msg.PONG, seq, struct.pack(' None: + daemon = self._start_daemon(devices=[_usb_dev(device_id=1)]) + daemon.connect_results = [RESULT_CONNREFUSED] * 20 + client = UsbmuxClient(socket_path=self.sock_path, usb_devices=self.usb_sysfs) + + with self.assertRaises(UsbmuxConnectionRefused): + client.connect(port=5599, timeout=0.25, retry_interval=0.05) + + daemon2_sock = str(self.tmp_path / 'usbmuxd2') + daemon2 = FakeUsbmuxDaemon(daemon2_sock, devices=[]) + self._daemons.append(daemon2) + client2 = UsbmuxClient(socket_path=daemon2_sock, usb_devices=self.usb_sysfs) + with self.assertRaises(LinkTimeout): + client2.wait_for_device(timeout=0.2) + + stop_flag = [False] + t = threading.Timer(0.1, lambda: stop_flag.__setitem__(0, True)) + t.start() + try: + with self.assertRaises(LinkError): + client2.wait_for_device(timeout=5.0, should_stop=lambda: stop_flag[0]) + finally: + t.cancel() + + def test_detect_apple_usb_speed_usb3_usb2_and_link_info(self) -> None: + _make_fake_usb_device(self.usb_sysfs, '1-1', '1d6b', '480', serial='ROOTHUB', product='Root Hub') + _make_fake_usb_device(self.usb_sysfs, '2-1:1.0', '05ac', '480', serial='IGNORED', product='Interface') + _make_fake_usb_device(self.usb_sysfs, '2-1', '05ac', '480', serial='SERIAL-USB2', product='iPhone Slow') + _make_fake_usb_device(self.usb_sysfs, '3-1', '05ac', '5000', serial='SERIAL-USB3', product='iPhone Fast') + + usb2 = detect_apple_usb_speed(self.usb_sysfs, serial='SERIALUSB2') + self.assertIsNotNone(usb2) + self.assertFalse(usb2.is_usb3) + self.assertEqual(usb2.udc_speed, 'high-speed') + self.assertEqual(usb2.speed_mbps, 480.0) + + with self.assertLogs('jetlink.comma.usbmux', level='WARNING') as cm: + detect_apple_usb_speed(self.usb_sysfs, serial='SERIALUSB2') + self.assertTrue(any('high-speed' in line and '480 Mbps' in line for line in cm.output)) + + usb3 = detect_apple_usb_speed(self.usb_sysfs) + self.assertIsNotNone(usb3) + self.assertTrue(usb3.is_usb3) + self.assertEqual(usb3.udc_speed, 'super-speed') + + a, b = socket.socketpair() + try: + t_fast = UsbmuxTransport(a, usb_speed=usb3) + self.assertEqual(t_fast.link_info(), {'kind': 'cable', 'usb_speed': 'super-speed', 'transport': 'usbmux'}) + t_unknown = UsbmuxTransport(b, usb_speed=None) + self.assertEqual(t_unknown.link_info(), {'kind': 'cable', 'transport': 'usbmux'}) + finally: + a.close() + b.close() + + def test_stdlib_only_imports(self) -> None: + src = (REPO / 'jetlink' / 'comma' / 'usbmux_transport.py').read_text() + tree = ast.parse(src) + self.assertFalse(any(isinstance(n, ast.Name) and n.id == '__file__' for n in ast.walk(tree))) + + imported_roots: set[str] = set() + for node in ast.walk(tree): + if isinstance(node, ast.Import): + imported_roots.update(alias.name.partition('.')[0] for alias in node.names) + elif isinstance(node, ast.ImportFrom) and node.module: + imported_roots.add(node.module.partition('.')[0]) + self.assertEqual(sorted(imported_roots - set(sys.stdlib_module_names) - {'jetlink'}), []) + + probe = ( + 'import importlib, json, sys; ' + 'sys.path.insert(0, sys.argv[1]); ' + 'before = set(sys.modules); ' + 'importlib.import_module("jetlink.comma.usbmux_transport"); ' + 'loaded = set(sys.modules) - before; ' + 'allowed = set(sys.stdlib_module_names) | {"jetlink", "_missing_stdlib_info"}; ' + 'foreign = sorted({n.split(".")[0] for n in loaded} - allowed); ' + 'print(json.dumps(foreign))' + ) + run = subprocess.run([sys.executable, '-I', '-c', probe, str(REPO)], cwd=REPO, capture_output=True, text=True, check=True) + self.assertEqual(json.loads(run.stdout), []) + + def test_jetlink_usbmux_script_syntax_and_speed(self) -> None: + self.assertTrue(USBMUX_SCRIPT.is_file()) + self.assertTrue(os.access(USBMUX_SCRIPT, os.X_OK)) + subprocess.run(['bash', '-n', str(USBMUX_SCRIPT)], check=True) + + env = dict(os.environ, JETLINK_USB_DEVICES=str(self.usb_sysfs)) + empty = subprocess.run(['bash', str(USBMUX_SCRIPT), 'speed'], env=env, capture_output=True, text=True) + self.assertEqual(empty.returncode, 1) + + _make_fake_usb_device(self.usb_sysfs, '2-2', '05ac', '480', serial='ABC', product='iPhone') + slow = subprocess.run(['bash', str(USBMUX_SCRIPT), 'speed'], env=env, capture_output=True, text=True) + self.assertEqual(slow.returncode, 2) + self.assertIn('480 Mbps', slow.stderr) + + usb3_dir = self.tmp_path / 'usb3' + usb3_dir.mkdir() + _make_fake_usb_device(usb3_dir, '3-1', '05ac', '10000', serial='XYZ', product='iPhone 16 Pro') + fast = subprocess.run(['bash', str(USBMUX_SCRIPT), 'speed'], env=dict(os.environ, JETLINK_USB_DEVICES=str(usb3_dir)), + capture_output=True, text=True) + self.assertEqual(fast.returncode, 0) + self.assertIn('10000 Mbps', fast.stdout) + + def test_reconnector_recovers_after_unplug_replug(self) -> None: + def handler(peer: socket.socket, dev_id: int) -> None: + try: + while True: + mtype, seq, _flags, _payload = _recv_jlnk_exact(peer) + if dev_id == 1: + return # abrupt disconnect on unplug + if mtype == P.Msg.PING: + _send_jlnk(peer, P.Msg.PONG, seq, struct.pack(' None: + missing_client = UsbmuxClient(socket_path=str(self.tmp_path / 'nonexistent.sock'), usb_devices=self.usb_sysfs) + d_missing = diagnose(missing_client) + self.assertEqual(d_missing.code, 'daemon_unavailable') + self.assertTrue(d_missing.is_warning) + + daemon = self._start_daemon(devices=[]) + client = UsbmuxClient(socket_path=self.sock_path, usb_devices=self.usb_sysfs) + self.assertEqual(diagnose(client).code, 'no_device') + + lockdown = self.tmp_path / 'lockdown_diag' + lockdown.mkdir() + daemon.attach_device(_usb_dev(device_id=5, serial='00008130-AABBCCDD')) + d_unpaired = diagnose(client, lockdown_dirs=(lockdown,)) + self.assertEqual(d_unpaired.code, 'unpaired') + self.assertIn('Trust This Computer', d_unpaired.message) + + (lockdown / '00008130-AABBCCDD.plist').write_text('plist') + _make_fake_usb_device(self.usb_sysfs, '4-1', '05ac', '480', serial='00008130AABBCCDD', product='iPhone') + d_usb2 = diagnose(client, lockdown_dirs=(lockdown,)) + self.assertEqual(d_usb2.code, 'usb2_fallback') + self.assertIn('480 Mbps', d_usb2.message) + + _make_fake_usb_device(self.usb_sysfs, '4-1', '05ac', '10000', serial='00008130AABBCCDD', product='iPhone') + d_ok = diagnose(client, lockdown_dirs=(lockdown,)) + self.assertEqual(d_ok.code, 'ok') + self.assertFalse(d_ok.is_warning) + + def test_bench_link_synthetic_usbmux(self) -> None: + _make_fake_usb_device(self.usb_sysfs, '5-1', '05ac', '10000', serial='BENCH-1', product='iPhone') + + def handle_bench(peer: socket.socket, _dev_id: int) -> None: + try: + while True: + mtype, seq, _flags, _payload = _recv_jlnk_exact(peer) + if mtype == P.Msg.HELLO_REQ: + _send_jlnk(peer, P.Msg.HELLO_RESP, seq, json.dumps({ + 'protocol': P.VERSION, + 'backend': 'ort', + 'runtime_version': '1.29.0', + 'device': 'iPhone16,2', + 'engine_state': 'none', + }).encode()) + elif mtype == P.Msg.PING: + _send_jlnk(peer, P.Msg.PONG, seq, b'') + except EOFError: + pass + finally: + peer.close() + + self._start_daemon(devices=[_usb_dev(device_id=4, serial='BENCH-1')], on_connect=handle_bench) + run = subprocess.run( + [ + sys.executable, str(REPO / 'scripts' / 'bench_link.py'), + '--usbmux', '--usbmux-socket', self.sock_path, + '--payload-kb', '64', '--n', '5', '--rate', '0', + ], + cwd=REPO, + env=dict(os.environ, PYTHONPATH=str(REPO)), + capture_output=True, + text=True, + timeout=15, + ) + self.assertEqual(run.returncode, 0, run.stderr) + self.assertIn('p50', run.stdout) + self.assertIn('p99', run.stdout) + self.assertIn('frames over 46 ms', run.stdout) + + def test_jetlink_usbmux_script_mode3_and_status(self) -> None: + subprocess.run(['bash', '-n', str(USBMUX_SCRIPT)], check=True) + lockdown = self.tmp_path / 'ld' + lockdown.mkdir() + (lockdown / 'iphone.plist').write_text('plist') + mode_file = self.tmp_path / 'mode' + mode_file.write_text('mode-3\n') + var_ld = self.tmp_path / 'var_ld' + var_ld.symlink_to(lockdown) + + env = dict( + os.environ, + JETLINK_USB_DEVICES=str(self.usb_sysfs), + JETLINK_LOCKDOWN_DIR=str(lockdown), + JETLINK_VAR_LOCKDOWN=str(var_ld), + JETLINK_USBMUXD_MODE_FILE=str(mode_file), + JETLINK_USBMUXD_SOCKET=str(self.tmp_path / 'missing.sock'), + JETLINK_UDC_GLUE=str(self.tmp_path / 'no_udc'), + JETLINK_GADGET=str(self.tmp_path / 'no_gadget'), + ) + res = subprocess.run(['bash', str(USBMUX_SCRIPT), 'status'], env=env, capture_output=True, text=True) + self.assertEqual(res.returncode, 0, res.stderr) + self.assertIn('1 pairing record(s)', res.stdout) + self.assertIn('usbmuxd mode: mode-3', res.stdout) + + +if __name__ == '__main__': + unittest.main() From e7806b3a88e9d7f6494ffbf8514d54ccfc4c4990 Mon Sep 17 00:00:00 2001 From: moltenglue <257664494+moltenglue@users.noreply.github.com> Date: Mon, 30 Nov 2026 10:19:37 -0500 Subject: [PATCH 2/5] Document usbmuxd speed benchmarks, mode tables, and source credits --- docs/usbmux-transport.md | 90 ++++++++++++++++++++++++++++++---------- 1 file changed, 67 insertions(+), 23 deletions(-) diff --git a/docs/usbmux-transport.md b/docs/usbmux-transport.md index 8aa90551..fdee27b7 100644 --- a/docs/usbmux-transport.md +++ b/docs/usbmux-transport.md @@ -12,11 +12,28 @@ Reversing USB roles removes `u_ether` from the hot path: - **iPhone / iPad stays in standard USB Device mode.** - **`usbmuxd` on the comma** drives USB 3 bulk transfers via `libusb` and tunnels straight to a standard `127.0.0.1:5599` loopback TCP listener inside the iOS app. -Because `usbmuxd` streams over raw USB 3 bulk pipes (~6.12 Gbps / ~765 MB/s measured on USB 3 iPhones) instead of `u_ether`: +## Measured iPhone USB speeds over `usbmuxd` -- A 393 KB frame takes ~0.5 ms on the wire, without UDP JFRM fallback. -- Multi-megabyte full-frame payloads (e.g., 4 MB inputs) stay well inside the 46–50 ms per-frame driving budget. -- The iOS app uses only public POSIX loopback sockets via `TCPListener` (`127.0.0.1:5599`) — zero USBDriverKit extensions, zero MFi hardware, and zero private iOS APIs. +Independent `iperf3` benchmarks over `usbmuxd` by [Ethan Huang (*iPhone USB Speed Measurement with usbmuxd*)](https://ethanhuang13.plus/iphone-usb-speed-measurement-with-usbmuxd/) demonstrate why every USB hop matters and why `usbmuxd` bulk pipes sustain full-frame model payloads: + +| Connection & Hardware Setup | Measured Throughput ([Ethan Huang](https://ethanhuang13.plus/iphone-usb-speed-measurement-with-usbmuxd/)) | Effective Byte Rate | Derived Wire Time: 393 KB (`INFER_REQ`) | Derived Wire Time: 4 MiB (Full Frame) | Jetlink Impact | +| --- | --- | --- | --- | --- | --- | +| **USB 3.2 Gen 2 (10 Gb/s cable, iPhone 16 Pro Max)** | **6.12 Gb/s** | ~765 MB/s | ~0.5 ms | ~5.5 ms | Ideal headroom inside the 46–50 ms driving budget | +| **USB 3.0 Hub (5 Gb/s rated)** | **3.21 Gb/s** | ~401 MB/s | ~1.0 ms | ~10.5 ms | Fast enough for 393 KB & 4 MiB, limited by 5 Gb/s hub | +| **USB 2.0 (Apple stock bundled cable)** | **303 Mb/s** | ~37.9 MB/s | ~10.4 ms | ~111 ms | Triggers Jetlink USB 2 warning; cannot sustain 20 Hz full frames | +| **100 Mbps Ethernet (comparison baseline)** | **93.8 Mb/s** | ~11.7 MB/s | ~33.5 ms | ~358 ms | Reference wired LAN baseline | + +*Note: Derived wire times divide Jetlink payload sizes (`393,304 B` and `4,194,304 B`) by Ethan Huang's measured `iperf3` link throughput and exclude framing/inference overhead. Avoid Apple's bundled USB 2.0 charging cables — Ethan Huang measured 303 Mb/s even below USB 2.0's 480 Mb/s signaling ceiling due to protocol overhead.* + +## Transport & protocol comparison + +| Path | USB Roles (Comma / iPhone) | Wire Mechanism | Notes & Tradeoffs | +| --- | --- | --- | --- | +| **Default Jetlink CDC-NCM (TCP)** | Device (`u_ether`) / Host | TCP over USB CDC-NCM (`192.168.60.1:5599`) | ~272 TCP segments per 393 KB frame (`7.35 ms/frame` on bench; [Link Protocol](link-protocol.md#frames-over-a-phones-cable)) | +| **Default Jetlink CDC-NCM (UDP `JFRM`)** | Device (`u_ether`) / Host | ~7 equal UDP datagrams + TCP replies | Cuts comma stack cost from `7.35 ms` to `4.3 ms/frame` ([Link Protocol](link-protocol.md#frames-over-a-phones-cable)); default for current 393 KB models | +| **Variant A: Direct `usbmuxd` (this branch)** | Host (`libusb`) / Device | Direct `/var/run/usbmuxd` plist `Connect` → `127.0.0.1:5599` | Same raw `usbmux` TCP tunnel used by Xcode and [PhotoTransfer](https://github.com/tzulunyeh/PhotoTransfer/blob/main/README.md); skips PTP/AFC bottlenecks and eliminates `iproxy` double-copy overhead | +| **Variant B: `usbmuxd --mode3`** | Host (`cdc_ncm`) / Device (`AppleUSBDeviceNCMData`) | `USBMUXD_DEFAULT_DEVICE_MODE=3` + IP/UDP `JFRM` | Fallback A/B path per [Synacktiv](https://synacktiv.com/publications/ios-a-journey-in-the-usb-networking-stack) if Variant A TCP buffering jitters on AGNOS | +| **Image Capture (PTP) / iMazing (AFC)** | Host / Device | PTP / Apple File Conduit | Documented by [PhotoTransfer](https://github.com/tzulunyeh/PhotoTransfer/blob/main/README.md) as severely bottlenecked for large transfers; unsuitable for 20 Hz inference | ## Opt-in design ("Full Frame Experimental Network") @@ -25,10 +42,10 @@ Normal Jetlink setups are unchanged: - **Default (`OFF`)**: `PhoneSettings.fullFrameExperimentalNetwork` is `false`. The iOS app continues to dial the comma over the CDC-NCM USB network interface (`192.168.60.1:5599`), and `jetlink/comma/jetlink-root.sh` is untouched. - **Experimental (`ON`)**: Under **Settings > Connection > Full Frame Experimental Network**, toggling it on: - Stops CDC-NCM dialing in `PhoneServer` and binds `TCPListener` strictly to `127.0.0.1:5599` (`TCP_NODELAY = 1`, 4 MB send/receive socket buffers, pre-allocated zero-copy `FrameReader`). - - Does not expose a LAN socket and does not require iOS Local Network permission. + - Uses only public POSIX loopback sockets (`TCPListener`) — zero USBDriverKit extensions, zero MFi hardware, zero private iOS APIs, no LAN socket exposure, and no Local Network permission prompt. - Shows **Listening on USB (usbmuxd)** → **Connected via usbmuxd (USB 3)** in the app status views and Settings. -## Architecture +## Architecture & iOS USB device modes ### Variant A (primary): Direct `/var/run/usbmuxd` tunnel @@ -42,24 +59,41 @@ Normal Jetlink setups are unchanged: └─ Jetlink iOS App (TCPListener strictly on 127.0.0.1:5599, TCP_NODELAY) ``` -Key design choices: - - **No `iproxy` process hop**: `UsbmuxClient` speaks the binary/plist `usbmuxd` protocol (`ListDevices`, `Listen`, `Connect`) directly over `/var/run/usbmuxd` from Python (`jetlink/comma/usbmux_transport.py`), wraps the upgraded socket directly in `UsbmuxTransport(StreamTransport)`, and avoids copying multi-megabyte frames twice through an extra `iproxy` localhost proxy. - **Protocol v3 verbatim**: Reuses the 32-byte `JLNK` header, `INFER_REQ`, and `INFER_RESP` framing without changes. - **Stdlib-only comma module**: `jetlink/comma/usbmux_transport.py` imports only Python's standard library and `jetlink.transport.base`, matching the comma's minimal resident dependency footprint. - **Persistent lockdown trust**: `scripts/comma/jetlink-usbmux.sh` maps `/var/lib/lockdown` to `/data/jetlink/lockdown` (symlink or bind mount fallback on read-only AGNOS rootfs) so tapping **Trust This Computer** persists across comma reboots and updates. -- **USB 3 speed & pairing diagnostics**: Both `jetlink-usbmux.sh speed` and `detect_apple_usb_speed()` inspect `/sys/bus/usb/devices/*/speed` for Apple VID `05ac` and warn immediately on 480 Mbps USB 2 fallback or unpaired devices. - **Event-driven auto-reconnect**: `UsbmuxReconnector` runs a background `Listen` monitor on `/var/run/usbmuxd` so cable bumps or replugs recover immediately without polling stalls. -### Variant B (optional A/B): `USBMUXD_DEFAULT_DEVICE_MODE=3` +### iOS extended USB function modes (`usbmuxd`) + +Modern iOS exposes selectable vendor USB configurations via `kVendorRequestSelectExtendedFunction` ([Synacktiv](https://synacktiv.com/publications/ios-a-journey-in-the-usb-networking-stack)): -If a specific AGNOS kernel or device exhibits TCP buffering jitter, `scripts/comma/jetlink-usbmux.sh setup --mode3` launches `usbmuxd` with `USBMUXD_DEFAULT_DEVICE_MODE=3` so Linux's host-side `cdc_ncm` driver can be A/B benchmarked against Variant A without removing CDC-NCM gadget support. +| `USBMUXD_DEFAULT_DEVICE_MODE` | iOS USB Configuration | Jetlink Usage | +| --- | --- | --- | +| Default (Mode 1) | Standard `usbmux` bulk endpoints | **Variant A (Primary)** — direct `/var/run/usbmuxd` TCP tunnel via `libusb` | +| Mode 2 | Valeria (QuickTime screen/audio streaming) | Unused | +| Mode 3 (`--mode3`) | CDC-NCM (`AppleUSBDeviceNCMControl` / `AppleUSBDeviceNCMData`) | **Variant B (Optional A/B)** — Linux host-side `cdc_ncm` via `scripts/comma/jetlink-usbmux.sh setup --mode3` | -## Hardware setup +## Hardware & sysfs USB speed verification -1. Comma 3X or comma four with the AUX USB-C port left in USB Host mode (`jetlink-usbmux.sh setup` tears down any active CDC-NCM gadget cleanly via `jetlink-root.sh teardown`). -2. **Powered 10 Gbps USB 3.2 Gen 2 hub** with external USB-C PD power input between the comma and iPhone/iPad so the iPhone charges from the hub's supply rather than drawing current from the comma's AUX VBUS. -3. **10 Gbps USB 3 data cables** on every hop (standard USB 2 charging cables drop negotiation to 480 Mbps). +Every hop must support USB 3 (see [compatible iOS devices](iphone-app.md#usb-3-matters)): + +| Requirement / Hop | USB 3 (Target) | USB 2 Fallback (Avoid) | +| --- | --- | --- | +| **Comma port** | Comma 3X / comma four AUX port in USB Host mode (`jetlink-usbmux.sh setup` runs `teardown`) | Left in CDC-NCM peripheral gadget mode | +| **Power & hub** | **Powered 10 Gbps USB 3.2 Gen 2 hub** with external USB-C PD input (prevents AUX VBUS brownout) | Bus-powered hub or USB 2 hub | +| **Cables** | **10 Gbps USB 3** data cables on every hop | Bundled iPhone USB 2 charging cable (caps at 480 Mbps / ~303 Mb/s actual) | +| **iOS devices** | iPhone 15 Pro and later Pro models; USB-C iPad Pro / iPad Air / iPad mini | Non-Pro USB-C iPhones, standard iPad (10th gen / A16) | + +Both `scripts/comma/jetlink-usbmux.sh speed` and `detect_apple_usb_speed()` verify `/sys/bus/usb/devices/*/speed` for Apple VID `0x05ac`: + +| Linux `sysfs` `speed` | Mapped `LinkMedium` (`usb_speed`) | Behavior | +| --- | --- | --- | +| `10000` | `usb3` (`super-speed-plus`) | USB 3.2 Gen 2 ready | +| `5000` | `usb3` (`super-speed`) | USB 3.0 ready | +| `480` | `usb2` (`high-speed`) | Logs USB 2 warning; check 10 Gbps hub and cables | +| `12` / `1.5` | `usb1` (`full-speed` / `low-speed`) | Logs slow USB 1.x warning | ## Commands @@ -92,13 +126,23 @@ sudo scripts/comma/jetlink-usbmux.sh setup --mode3 ## Verification status -Verified in CI-equivalent local tests and loopback benchmarks before device/comma hardware testing: +Verified in CI-equivalent local tests and macOS `127.0.0.1` loopback benchmarks before comma + iPhone hardware testing: + +| Check / Benchmark | Result | Notes | +| --- | --- | --- | +| `tests/test_usbmux_transport.py` | **13/13 passed** | Mocked `/var/run/usbmuxd` (`ListDevices`, `htons(5599)`, v3 393 KB/8 KB round-trip, `RESULT_CONNREFUSED` retry, `Listen` attach, `UsbmuxReconnector` `< 1.5 s` recovery, sysfs speed, lockdown trust diagnostics, stdlib `-I` isolation, `bench_link.py --usbmux`, `jetlink-usbmux.sh`) | +| `JetlinkKitTests` + `JetlinkServerTests` | **223/223 passed** | `LinkEvent.isLoopback`, `LinkMedium` (`transport: usbmux`), `loopbackUsbmuxServer` (4 MiB payload + golden `tiny_queued` replay, no UDP datagrams) | +| Live `jetlink-server` loopback (384 KiB @ 20 Hz, 90 frames) | **p50 0.36 ms · p99 0.56 ms · max 0.63 ms** | `127.0.0.1` Swift server baseline (`0/90` frames > 46 ms); excludes physical USB wire latency | +| Live `jetlink-server` loopback (4096 KiB @ 20 Hz, 32 frames) | **p50 0.98 ms · p99 1.71 ms · max 1.75 ms** | `127.0.0.1` Swift server baseline (`0/32` frames > 46 ms); excludes physical USB wire latency | +| `xcodebuild` (generic iOS device) | **Build succeeded** | Clean with zero warnings in modified files | + +Live comma 3X/four + powered 10 Gbps USB 3 hub + on-device iPhone A/B hardware benchmarks (`usbmuxd` vs. CDC-NCM) remain to be run on physical hardware. -- **Python tests (`tests/test_usbmux_transport.py`)**: 13/13 passing against mocked `/var/run/usbmuxd` (`ListDevices` USB filtering, `htons(5599)`, protocol v3 393 KB `INFER_REQ` + 8 KB `INFER_RESP` round-trip, `RESULT_CONNREFUSED` retries, `Listen` attach, `UsbmuxReconnector` `< 1.5 s` recovery, sysfs USB 3/USB 2 detection, pairing diagnostics, stdlib-only `-I` import isolation, synthetic `bench_link.py --usbmux`, and `jetlink-usbmux.sh`). -- **Swift tests (`JetlinkKitTests` + `JetlinkServerTests`)**: 223/223 passing (`LinkEvent.isLoopback`, `LinkMedium` with `"transport": "usbmux"`, and `loopbackUsbmuxServer` verifying `127.0.0.1` loopback serving + 4 MB payloads with no UDP datagrams). -- **Live `jetlink-server` loopback (`127.0.0.1`)**: - - 384 KiB @ 20 Hz: p50 `0.36 ms`, p99 `0.56 ms`, max `0.63 ms`, `0/90` frames > 46 ms. - - 4096 KiB (4 MiB) @ 20 Hz: p50 `0.98 ms`, p99 `1.71 ms`, max `1.75 ms`, `0/32` frames > 46 ms. -- **iOS device build (`xcodebuild`)**: `** BUILD SUCCEEDED **`. +## References & credits -Live comma + powered 10 Gbps USB 3 hub + on-device iPhone A/B measurements remain to be run on hardware. +- **Ethan Huang**, [*iPhone USB Speed Measurement with usbmuxd*](https://ethanhuang13.plus/iphone-usb-speed-measurement-with-usbmuxd/) — real-world `iperf3` throughput table across USB 3.2 Gen 2 (6.12 Gb/s), USB 3.0 hub (3.21 Gb/s), Apple USB 2.0 cable (303 Mb/s), and 100 Mbps Ethernet (93.8 Mb/s). +- **tzulunyeh**, [*PhotoTransfer*](https://github.com/tzulunyeh/PhotoTransfer/blob/main/README.md) — demonstrating wire-speed iOS USB 3.2 Gen 2 streaming via `usbmux` TCP tunnels (avoiding PTP/Image Capture and AFC/iMazing bottlenecks). +- **Synacktiv**, [*iOS: a journey in the USB networking stack*](https://synacktiv.com/publications/ios-a-journey-in-the-usb-networking-stack) — documenting iOS USB extended function modes (`USBMUXD_DEFAULT_DEVICE_MODE=3`, `AppleUSBDeviceNCMControl` / `AppleUSBDeviceNCMData`). +- **libimobiledevice**, [`usbmuxd`](https://github.com/libimobiledevice/usbmuxd) — open-source USB multiplexing daemon and plist socket protocol. +- **comma.ai**, [*openpilot 0.11.2 release*](https://blog.comma.ai/0112release/) — motivating higher-bandwidth transport for future full-frame driving models. +- **zoompilot / Jetlink**, [Link protocol](link-protocol.md) and [Set up Jetlink on iPhone or iPad](iphone-app.md) — CDC-NCM baseline (`7.35 ms` TCP vs. `4.3 ms` UDP `JFRM`) and compatible USB 3 hardware guide. From b4ffad0b688f27373fcd2d98ced8693a8153b3c6 Mon Sep 17 00:00:00 2001 From: moltenglue <257664494+moltenglue@users.noreply.github.com> Date: Mon, 30 Nov 2026 10:31:13 -0500 Subject: [PATCH 3/5] Add upstream tracking and preflight tools for usbmuxd, AGNOS, and Jetlink Track external dependencies that affect USB Host-mode usbmuxd transport and provide repeatable verification, pin updates, and rebase drift checks: - scripts/upstream/USBMUX_PINS.json: pin tested commits for usbmuxd, commaai/agnos-builder (AGNOS 20.6), agnos-kernel-sdm845, and zoompilot/jetlink plus watched_jetlink_paths. - scripts/upstream/fetch_usbmux_deps.sh: sparse blobless read-only fetch of usbmuxd headers/C sources, agnos-builder, and tici_defconfig. - scripts/upstream/check_usbmux_deps.py: 'check' validates usbmuxd wire enums/keys/Mode-3/lockdown contracts and AGNOS kernel/rootfs USB config; 'update-pins' updates USBMUX_PINS.json safely when compatible; 'sync-jetlink' reports upstream commits and watched-path overlaps. - scripts/comma/jetlink-usbmux.sh: add 'preflight' (AGNOS VERSION, kernel, /data/jetlink/bin persistence, Mode 3 support check). - .github/workflows/upstream-usbmux.yml & ci.yml: weekly upstream monitoring enabled on moltenglue/jetlink with issue alerting and shellcheck CI coverage. - tests/test_upstream_usbmux.py & docs/usbmux-transport.md: full unit test coverage and documentation. --- .github/workflows/ci.yml | 2 +- .github/workflows/upstream-usbmux.yml | 140 +++++++++ docs/usbmux-transport.md | 23 ++ scripts/comma/jetlink-usbmux.sh | 45 ++- scripts/upstream/USBMUX_PINS.json | 36 +++ scripts/upstream/check_usbmux_deps.py | 409 ++++++++++++++++++++++++++ scripts/upstream/fetch_usbmux_deps.sh | 135 +++++++++ tests/test_upstream_usbmux.py | 225 ++++++++++++++ 8 files changed, 1013 insertions(+), 2 deletions(-) create mode 100644 .github/workflows/upstream-usbmux.yml create mode 100644 scripts/upstream/USBMUX_PINS.json create mode 100644 scripts/upstream/check_usbmux_deps.py create mode 100755 scripts/upstream/fetch_usbmux_deps.sh create mode 100644 tests/test_upstream_usbmux.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bc53f6a5..194dafb5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -94,7 +94,7 @@ jobs: run: | # what the installer runs or installs, and what the comma runs as # root; the bench scripts are not held to it yet - shellcheck install.sh scripts/jetlink jetlink/comma/jetlink-root.sh scripts/comma/jetlink-root.sh tests/installer/*.sh + shellcheck install.sh scripts/jetlink jetlink/comma/jetlink-root.sh scripts/comma/jetlink-root.sh scripts/comma/jetlink-usbmux.sh scripts/upstream/fetch_usbmux_deps.sh tests/installer/*.sh - name: Run the installer scenarios run: tests/installer/run.sh diff --git a/.github/workflows/upstream-usbmux.yml b/.github/workflows/upstream-usbmux.yml new file mode 100644 index 00000000..949c1412 --- /dev/null +++ b/.github/workflows/upstream-usbmux.yml @@ -0,0 +1,140 @@ +# Tracks upstream libimobiledevice/usbmuxd, commaai/agnos-builder (and +# agnos-kernel-sdm845 defconfig), and zoompilot/jetlink for changes that could +# break Jetlink's USB Host-mode iOS usbmuxd transport. +# +# Pull requests check against the pins in scripts/upstream/USBMUX_PINS.json. +# Weekly scheduled runs (and manual 'latest' dispatches) check against upstream +# HEAD, summarize any new commits/AGNOS versions, and open a tracking issue on +# breaking contract changes. +name: Upstream usbmuxd & AGNOS + +on: + push: + branches: [main, usbmuxd-transport] + paths: + - jetlink/comma/usbmux_transport.py + - scripts/comma/jetlink-usbmux.sh + - scripts/upstream/USBMUX_PINS.json + - scripts/upstream/fetch_usbmux_deps.sh + - scripts/upstream/check_usbmux_deps.py + - .github/workflows/upstream-usbmux.yml + pull_request: + paths: + - jetlink/comma/usbmux_transport.py + - scripts/comma/jetlink-usbmux.sh + - scripts/upstream/USBMUX_PINS.json + - scripts/upstream/fetch_usbmux_deps.sh + - scripts/upstream/check_usbmux_deps.py + - .github/workflows/upstream-usbmux.yml + schedule: + - cron: "23 7 * * 1" + workflow_dispatch: + inputs: + mode: + description: "Check pinned commits or latest upstream HEAD" + type: choice + default: latest + options: + - latest + - pinned + +concurrency: + group: upstream-usbmux-${{ github.ref }}-${{ github.event_name }} + cancel-in-progress: true + +permissions: + contents: read + +defaults: + run: + shell: bash + +jobs: + check-upstream: + name: usbmuxd & AGNOS compatibility + runs-on: ubuntu-24.04 + if: github.event_name != 'schedule' || github.repository == 'moltenglue/jetlink' || github.repository == 'zoompilot/jetlink' + outputs: + report: ${{ steps.audit.outputs.report }} + steps: + - name: Check out repository + uses: actions/checkout@v4 + with: + persist-credentials: false + + - name: Fetch sparse upstream dependencies + run: | + DEST=$RUNNER_TEMP/usbmux-deps + echo "DEST=$DEST" >> "$GITHUB_ENV" + ARGS=() + if [[ "${{ github.event_name }}" == "schedule" || ( "${{ github.event_name }}" == "workflow_dispatch" && "${{ inputs.mode }}" == "latest" ) ]]; then + ARGS+=(--latest) + fi + scripts/upstream/fetch_usbmux_deps.sh "$DEST" "${ARGS[@]}" + + - name: Check contracts & pin drift + id: audit + run: | + REPORT=$RUNNER_TEMP/usbmux-upstream-report.txt + set +e + PYTHONPATH=. python3 -I scripts/upstream/check_usbmux_deps.py check "$DEST" | tee "$REPORT" + STATUS=${PIPESTATUS[0]} + set -e + { + echo 'report<> "$GITHUB_OUTPUT" + { + echo '```' + cat "$REPORT" + echo '```' + if [[ $STATUS -eq 0 ]]; then + echo "To update pins locally: \`scripts/upstream/fetch_usbmux_deps.sh /tmp/ux --latest && python3 scripts/upstream/check_usbmux_deps.py update-pins /tmp/ux\`" + fi + } >> "$GITHUB_STEP_SUMMARY" + exit "$STATUS" + + issue: + name: Weekly upstream alert + needs: check-upstream + if: ${{ !cancelled() && github.event_name == 'schedule' && (github.repository == 'moltenglue/jetlink' || github.repository == 'zoompilot/jetlink') }} + runs-on: ubuntu-24.04 + permissions: + issues: write + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + TITLE: "upstream-usbmux: usbmuxd or AGNOS upstream contract changed" + RESULT: ${{ needs.check-upstream.result }} + REPORT: ${{ needs.check-upstream.outputs.report }} + RUN: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + steps: + - name: Open, refresh or close issue + run: | + number=$(gh issue list --state open --limit 200 --json number,title --jq "map(select(.title == \"$TITLE\"))[0].number // empty") + if [[ "$RESULT" == "success" ]]; then + if [[ -n "$number" ]]; then + gh issue close "$number" --comment "Upstream usbmuxd/AGNOS checks are green again ($RUN)." + fi + exit 0 + fi + { + echo "The weekly usbmuxd / AGNOS upstream compatibility check failed ($RUN)." + echo + echo '```' + echo "${REPORT:-no report: fetch or check failed}" + echo '```' + echo + echo "Update jetlink/comma/usbmux_transport.py or scripts/comma/jetlink-usbmux.sh, then run:" + echo '```bash' + echo "scripts/upstream/fetch_usbmux_deps.sh /tmp/ux --latest" + echo "python3 scripts/upstream/check_usbmux_deps.py check /tmp/ux" + echo "python3 scripts/upstream/check_usbmux_deps.py update-pins /tmp/ux" + echo '```' + } > "$RUNNER_TEMP/issue.md" + if [[ -n "$number" ]]; then + gh issue edit "$number" --body-file "$RUNNER_TEMP/issue.md" + else + gh issue create --title "$TITLE" --body-file "$RUNNER_TEMP/issue.md" + fi diff --git a/docs/usbmux-transport.md b/docs/usbmux-transport.md index fdee27b7..638b8ca9 100644 --- a/docs/usbmux-transport.md +++ b/docs/usbmux-transport.md @@ -138,6 +138,29 @@ Verified in CI-equivalent local tests and macOS `127.0.0.1` loopback benchmarks Live comma 3X/four + powered 10 Gbps USB 3 hub + on-device iPhone A/B hardware benchmarks (`usbmuxd` vs. CDC-NCM) remain to be run on physical hardware. +## Upstream dependency tracking & updates + +Because `usbmuxd` host mode depends on external contracts (`libimobiledevice/usbmuxd`, `commaai/agnos-builder` + kernel `tici_defconfig`, and `zoompilot/jetlink`), this branch includes automated tracking and maintenance tools under `scripts/upstream/`: + +- **[`scripts/upstream/USBMUX_PINS.json`](../scripts/upstream/USBMUX_PINS.json)**: Pins tested upstream commits for `usbmuxd`, `agnos-builder`, `agnos-kernel-sdm845`, `agnos_version`, and `zoompilot/jetlink` (plus `watched_jetlink_paths`). +- **[`scripts/upstream/fetch_usbmux_deps.sh`](../scripts/upstream/fetch_usbmux_deps.sh)**: Sparse, blobless read-only checkout of upstream headers/configs (`--latest` to inspect upstream HEAD). +- **[`scripts/upstream/check_usbmux_deps.py`](../scripts/upstream/check_usbmux_deps.py)**: + - `check `: Verifies `usbmuxd` socket path, result/message enums, plist keys, `USBMUXD_DEFAULT_DEVICE_MODE`, `/var/lib/lockdown`, and AGNOS `VERSION`, rootfs bundling, and kernel `CONFIG_USB_DWC3` / `CONFIG_USB_CONFIGFS_*` / `CONFIG_USB_NET_CDC_NCM`. Exits non-zero with remediation steps on any breaking `IMPACT`. + - `update-pins `: Refuses to advance pins while `IMPACT` exists; updates `USBMUX_PINS.json` cleanly once compatible. + - `sync-jetlink`: Reports new upstream `zoompilot/jetlink` commits and highlights any overlap with `watched_jetlink_paths` before rebasing. +- **`scripts/comma/jetlink-usbmux.sh preflight`**: Prints AGNOS `VERSION`, kernel release, `usbmuxd` persistence check (`/data/jetlink/bin` vs. rootfs), and binary `USBMUXD_DEFAULT_DEVICE_MODE` capability. +- **[`.github/workflows/upstream-usbmux.yml`](../.github/workflows/upstream-usbmux.yml)**: Runs pinned checks on PRs and weekly scheduled checks against upstream HEAD on the fork, opening/closing a tracking issue automatically on breaking changes. + +```bash +# Audit against latest upstream usbmuxd + AGNOS and advance pins if clean +scripts/upstream/fetch_usbmux_deps.sh /tmp/usbmux-deps --latest +python3 scripts/upstream/check_usbmux_deps.py check /tmp/usbmux-deps +python3 scripts/upstream/check_usbmux_deps.py update-pins /tmp/usbmux-deps + +# Check zoompilot/jetlink upstream drift before rebasing +python3 scripts/upstream/check_usbmux_deps.py sync-jetlink --remote origin --branch main --fetch +``` + ## References & credits - **Ethan Huang**, [*iPhone USB Speed Measurement with usbmuxd*](https://ethanhuang13.plus/iphone-usb-speed-measurement-with-usbmuxd/) — real-world `iperf3` throughput table across USB 3.2 Gen 2 (6.12 Gb/s), USB 3.0 hub (3.21 Gb/s), Apple USB 2.0 cable (303 Mb/s), and 100 Mbps Ethernet (93.8 Mb/s). diff --git a/scripts/comma/jetlink-usbmux.sh b/scripts/comma/jetlink-usbmux.sh index 03081de5..211549b4 100755 --- a/scripts/comma/jetlink-usbmux.sh +++ b/scripts/comma/jetlink-usbmux.sh @@ -12,6 +12,7 @@ # sudo scripts/comma/jetlink-usbmux.sh setup [--install] [--mode3] # scripts/comma/jetlink-usbmux.sh speed # scripts/comma/jetlink-usbmux.sh pair +# scripts/comma/jetlink-usbmux.sh preflight # scripts/comma/jetlink-usbmux.sh status # sudo scripts/comma/jetlink-usbmux.sh stop set -euo pipefail @@ -34,6 +35,7 @@ BIN_DIR=${JETLINK_BIN_DIR:-/data/jetlink/bin} USBMUXD_SOCKET=${JETLINK_USBMUXD_SOCKET:-/var/run/usbmuxd} USBMUXD_PID=${JETLINK_USBMUXD_PID:-/dev/shm/jetlink-usbmuxd.pid} USBMUXD_MODE_FILE=${JETLINK_USBMUXD_MODE_FILE:-/dev/shm/jetlink-usbmuxd.mode} +AGNOS_VERSION_FILE=${JETLINK_AGNOS_VERSION_FILE:-/VERSION} APPLE_VID=05ac @@ -43,7 +45,7 @@ if [[ -d "$BIN_DIR" ]]; then fi usage() { - echo "usage: $0 setup [--install] [--mode3] | speed | pair | status | stop" >&2 + echo "usage: $0 setup [--install] [--mode3] | speed | pair | preflight | status | stop" >&2 exit 2 } @@ -293,6 +295,44 @@ cmd_pair() { idevicepair pair } +cmd_preflight() { + local want_mode=${1:-variant-a} agnos_ver="unknown" mux_bin="" mux_ver="" pair_ver="" + if [[ -r "$AGNOS_VERSION_FILE" ]]; then + agnos_ver=$(trim_sysfs "$AGNOS_VERSION_FILE") + fi + echo "Preflight: kernel $(uname -r), AGNOS ${agnos_ver:-unknown}" + + if [[ ! -e "$UDC_GLUE/mode" ]]; then + echo "jetlink-usbmux: note: UDC glue path $UDC_GLUE/mode not present (host-only or updated kernel?)" + fi + + if mux_bin=$(command -v usbmuxd 2>/dev/null); then + mux_ver=$(usbmuxd --version 2>&1 | head -n 1 || true) + echo "Preflight usbmuxd: $mux_bin (${mux_ver:-version unknown})" + if [[ "$mux_bin" != "$BIN_DIR/"* && "$mux_bin" == /usr/* ]]; then + echo "jetlink-usbmux: WARNING: $mux_bin lives on rootfs and may not survive AGNOS OTA updates; stage static binary under $BIN_DIR" >&2 + fi + if command -v strings >/dev/null 2>&1; then + if grep -q "USBMUXD_DEFAULT_DEVICE_MODE" < <(strings "$mux_bin" 2>/dev/null); then + echo "Preflight Mode 3 support: yes (USBMUXD_DEFAULT_DEVICE_MODE present)" + elif [[ "$want_mode" == "mode-3" ]]; then + echo "jetlink-usbmux: WARNING: $mux_bin lacks USBMUXD_DEFAULT_DEVICE_MODE support for --mode3; update usbmuxd" >&2 + else + echo "Preflight Mode 3 support: absent in $mux_bin (Variant A unaffected)" + fi + fi + else + echo "Preflight usbmuxd: missing" + fi + + if command -v idevicepair >/dev/null 2>&1; then + pair_ver=$(idevicepair --version 2>&1 | head -n 1 || true) + echo "Preflight idevicepair: $(command -v idevicepair) (${pair_ver:-version unknown})" + else + echo "Preflight idevicepair: missing" + fi +} + cmd_setup() { local do_install=0 want_mode="variant-a" arg for arg in "$@"; do @@ -306,12 +346,14 @@ cmd_setup() { restore_host_mode setup_persistent_lockdown ensure_usbmuxd_binaries "$do_install" + cmd_preflight "$want_mode" || true start_usbmuxd "$want_mode" cmd_speed || true } cmd_status() { local mode="unknown" count=0 target="(not a symlink)" active_mode="" + cmd_preflight || true if [[ -e "$UDC_GLUE/mode" ]]; then mode=$(trim_sysfs "$UDC_GLUE/mode") fi @@ -371,6 +413,7 @@ case "$cmd" in setup) cmd_setup "$@" ;; speed) cmd_speed ;; pair) cmd_pair ;; + preflight) cmd_preflight ;; status) cmd_status ;; stop) cmd_stop ;; *) usage ;; diff --git a/scripts/upstream/USBMUX_PINS.json b/scripts/upstream/USBMUX_PINS.json new file mode 100644 index 00000000..a904e673 --- /dev/null +++ b/scripts/upstream/USBMUX_PINS.json @@ -0,0 +1,36 @@ +{ + "usbmuxd": { + "repo": "https://github.com/libimobiledevice/usbmuxd.git", + "sha": "78a75a31a6c016782a7aeb82cc14b331a7adbc83", + "ref": "HEAD" + }, + "agnos_builder": { + "repo": "https://github.com/commaai/agnos-builder.git", + "sha": "e14707c73833f0e465e93adcadce22cc8cdf4786", + "ref": "HEAD", + "kernel_repo": "https://github.com/commaai/agnos-kernel-sdm845.git", + "kernel_submodule_sha": "e88ac80cc893f8d1808be58affdfc8c638e6b898", + "agnos_version": "20.6" + }, + "jetlink_upstream": { + "repo": "https://github.com/zoompilot/jetlink.git", + "sha": "214c31c81e7d983a3853808d8afd1a1376bf0711", + "ref": "refs/heads/main" + }, + "watched_jetlink_paths": [ + "JetlinkKit/Sources/JetlinkKit/ControlProtocol.swift", + "JetlinkKit/Sources/JetlinkServer/Transport.swift", + "JetlinkKit/Sources/JetlinkUI/ModelStatusLabel.swift", + "ios/Jetlink/App/AppModel.swift", + "ios/Jetlink/App/PhoneSettings.swift", + "ios/Jetlink/Server/PhoneServer.swift", + "ios/Jetlink/Views/Settings/SettingsScreen.swift", + "ios/Jetlink/Views/Status/HeroCard.swift", + "ios/Jetlink/Views/Status/StatusContent.swift", + "ios/Jetlink/Views/Status/StatusState.swift", + "jetlink/client.py", + "jetlink/comma/jetlink-root.sh", + "scripts/bench_link.py", + "scripts/verify_parity.py" + ] +} diff --git a/scripts/upstream/check_usbmux_deps.py b/scripts/upstream/check_usbmux_deps.py new file mode 100644 index 00000000..761bbf3d --- /dev/null +++ b/scripts/upstream/check_usbmux_deps.py @@ -0,0 +1,409 @@ +#!/usr/bin/env python3 +""" +Copyright (c) 2026-, Zeph Leggett. + +This file is part of jetlink and is licensed under the MIT License. +See the LICENSE file in the root directory for more details. + +Tracks upstream dependencies that can affect Jetlink's USB Host-mode iOS +usbmuxd transport and comma integration: + + 1. libimobiledevice/usbmuxd (wire constants, plist keys, Mode 3 env var, lockdown dir) + 2. commaai/agnos-builder (AGNOS VERSION, rootfs scripts, kernel defconfig) + 3. zoompilot/jetlink (upstream commits overlapping watched branch paths) + +All upstream checkouts are treated as read-only data; no upstream script is executed. + +Usage: + python3 -I scripts/upstream/check_usbmux_deps.py check [--pins PATH] [--json] [--strict] + python3 -I scripts/upstream/check_usbmux_deps.py update-pins [--pins PATH] [--force] + python3 -I scripts/upstream/check_usbmux_deps.py sync-jetlink [--remote origin] [--branch main] [--fetch] +""" +from __future__ import annotations + +import argparse +import json +import re +import subprocess +import sys +from dataclasses import asdict, dataclass +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + +from jetlink.comma import usbmux_transport as U # noqa: E402 + +DEFAULT_PINS = Path(__file__).resolve().with_name('USBMUX_PINS.json') + + +@dataclass(frozen=True) +class Finding: + area: str + level: str # OK | NOTICE | WARN | IMPACT + message: str + remediation: str = '' + + +def _read_text(path: Path) -> str: + try: + return path.read_text(errors='replace') + except OSError: + return '' + + +def _parse_c_enum_values(text: str, enum_name: str) -> dict[str, int]: + """Extract enumerator -> integer value from `enum { ... };`.""" + m = re.search(rf'\benum\s+{re.escape(enum_name)}\s*\{{([^}}]+)\}}', text, re.S) + if not m: + return {} + body = re.sub(r'/\*.*?\*/', '', m.group(1), flags=re.S) + body = re.sub(r'//[^\n]*', '', body) + values: dict[str, int] = {} + cur = -1 + for raw_item in body.split(','): + item = raw_item.strip() + if not item: + continue + if '=' in item: + name, expr = [part.strip() for part in item.split('=', 1)] + try: + cur = int(expr, 0) + except ValueError: + continue + else: + name = item + cur += 1 + values[name] = cur + return values + + +def _check_usbmuxd(usbmux_dir: Path, findings: list[Finding]) -> None: + proto = _read_text(usbmux_dir / 'src' / 'usbmuxd-proto.h') + if not proto: + findings.append(Finding( + 'usbmuxd', 'IMPACT', 'missing src/usbmuxd-proto.h in checkout', + 'Re-run fetch_usbmux_deps.sh or verify usbmuxd repository layout.', + )) + return + + sock_match = re.search(r'#define\s+USBMUXD_SOCKET_FILE\s+"([^"]+)"', proto) + if not sock_match or sock_match.group(1) != U.USBMUXD_SOCKET: + got = sock_match.group(1) if sock_match else 'missing' + findings.append(Finding( + 'usbmuxd', 'IMPACT', + f'USBMUXD_SOCKET_FILE is {got!r}, expected {U.USBMUXD_SOCKET!r}', + 'Update USBMUXD_SOCKET in jetlink/comma/usbmux_transport.py and scripts/comma/jetlink-usbmux.sh.', + )) + else: + findings.append(Finding('usbmuxd', 'OK', f'USBMUXD_SOCKET_FILE matches {U.USBMUXD_SOCKET}')) + + results = _parse_c_enum_values(proto, 'usbmuxd_result') + expected_results = { + 'RESULT_OK': U.RESULT_OK, + 'RESULT_BADCOMMAND': U.RESULT_BADCOMMAND, + 'RESULT_BADDEV': U.RESULT_BADDEV, + 'RESULT_CONNREFUSED': U.RESULT_CONNREFUSED, + } + mismatches = [f'{k}={results.get(k)}!={v}' for k, v in expected_results.items() if results.get(k) != v] + if mismatches: + findings.append(Finding( + 'usbmuxd', 'IMPACT', + f'usbmuxd_result enum mismatch: {", ".join(mismatches)}', + 'Update RESULT_* constants in jetlink/comma/usbmux_transport.py.', + )) + else: + findings.append(Finding('usbmuxd', 'OK', 'usbmuxd_result enum codes match (0/1/2/3)')) + + msgs = _parse_c_enum_values(proto, 'usbmuxd_msgtype') + if msgs.get('MESSAGE_PLIST') != U.USBMUX_MSG_PLIST: + findings.append(Finding( + 'usbmuxd', 'IMPACT', + f"MESSAGE_PLIST is {msgs.get('MESSAGE_PLIST')!r}, expected {U.USBMUX_MSG_PLIST}", + 'Update USBMUX_MSG_PLIST in jetlink/comma/usbmux_transport.py.', + )) + else: + findings.append(Finding('usbmuxd', 'OK', f'MESSAGE_PLIST matches ({U.USBMUX_MSG_PLIST})')) + + client_c = _read_text(usbmux_dir / 'src' / 'client.c') + required_keys = ('ListDevices', 'Listen', 'Connect', 'Attached', 'Detached', 'DeviceID', 'PortNumber', 'ConnectionType', 'USB') + missing_keys = [k for k in required_keys if f'"{k}"' not in client_c] + if missing_keys: + findings.append(Finding( + 'usbmuxd', 'IMPACT', + f'src/client.c is missing expected plist key(s): {", ".join(missing_keys)}', + 'Update UsbmuxClient plist request/response parsing in jetlink/comma/usbmux_transport.py.', + )) + else: + findings.append(Finding('usbmuxd', 'OK', 'client.c plist commands and keys match')) + + usb_text = _read_text(usbmux_dir / 'src' / 'usb.h') + '\n' + _read_text(usbmux_dir / 'src' / 'usb.c') + vid_match = re.search(r'#define\s+VID_APPLE\s+(0x[0-9a-fA-F]+)', usb_text) + if vid_match is None or int(vid_match.group(1), 16) != U.APPLE_VID: + got_vid = vid_match.group(1) if vid_match else 'missing' + findings.append(Finding( + 'usbmuxd', 'IMPACT', + f'Apple VID_APPLE is {got_vid!r}, expected 0x{U.APPLE_VID:04x}', + 'Verify APPLE_VID in jetlink/comma/usbmux_transport.py and jetlink-usbmux.sh.', + )) + else: + findings.append(Finding('usbmuxd', 'OK', f'Apple VID_APPLE matches 0x{U.APPLE_VID:04x} ({vid_match.group(1)})')) + + if 'USBMUXD_DEFAULT_DEVICE_MODE' not in usb_text: + findings.append(Finding( + 'usbmuxd', 'IMPACT', + 'USBMUXD_DEFAULT_DEVICE_MODE no longer referenced in usbmuxd usb.c/usb.h', + 'Variant B (--mode3) may have changed upstream; check usbmuxd device mode selection.', + )) + else: + findings.append(Finding('usbmuxd', 'OK', 'USBMUXD_DEFAULT_DEVICE_MODE supported in usbmuxd USB layer')) + + conf_text = _read_text(usbmux_dir / 'src' / 'conf.h') + '\n' + _read_text(usbmux_dir / 'src' / 'conf.c') + has_var_lockdown = str(U.VAR_LOCKDOWN) in conf_text or ('"/var/lib"' in conf_text and '"lockdown"' in conf_text) + if not has_var_lockdown: + findings.append(Finding( + 'usbmuxd', 'IMPACT', + f'Default lockdown path {U.VAR_LOCKDOWN} not found in usbmuxd src/conf.*', + 'Update VAR_LOCKDOWN / JETLINK_VAR_LOCKDOWN in jetlink-usbmux.sh and usbmux_transport.py.', + )) + else: + findings.append(Finding('usbmuxd', 'OK', f'usbmuxd lockdown dir matches {U.VAR_LOCKDOWN}')) + + +def _check_agnos(agnos_dir: Path, kernel_dir: Path, findings: list[Finding]) -> None: + version = _read_text(agnos_dir / 'VERSION').strip() + if not version: + findings.append(Finding('agnos', 'WARN', 'agnos-builder/VERSION missing or empty')) + else: + findings.append(Finding('agnos', 'OK', f'AGNOS builder VERSION {version}')) + + userspace_texts = [_read_text(agnos_dir / 'Dockerfile.agnos')] + userspace_dir = agnos_dir / 'userspace' + if userspace_dir.is_dir(): + for path in sorted(userspace_dir.rglob('*')): + if path.is_file(): + userspace_texts.append(_read_text(path)) + combined_userspace = '\n'.join(userspace_texts) + if 'usbmuxd' in combined_userspace or 'libimobiledevice' in combined_userspace: + findings.append(Finding( + 'agnos', 'NOTICE', + 'AGNOS userspace references usbmuxd/libimobiledevice natively', + 'Verify whether jetlink-usbmux.sh --install can rely on built-in AGNOS packages.', + )) + else: + findings.append(Finding( + 'agnos', 'OK', + 'AGNOS rootfs does not bundle usbmuxd; /data/jetlink/bin static binaries remain recommended', + )) + + defconfig = _read_text(kernel_dir / 'arch' / 'arm64' / 'configs' / 'tici_defconfig') + if not defconfig: + findings.append(Finding( + 'agnos-kernel', 'WARN', + 'tici_defconfig not present in checkout (kernel USB options not audited)', + 'Verify AGNOS_KERNEL_URL / gitlink access when running offline.', + )) + return + + for cfg, reason in ( + ('CONFIG_USB_DWC3=y', 'Required for comma AUX USB Host & Device controller (a600000.ssusb)'), + ('CONFIG_USB_CONFIGFS_F_FS=y', 'Required for default Jetlink FunctionFS gadget mode'), + ('CONFIG_USB_CONFIGFS_NCM=y', 'Required for default Jetlink CDC-NCM iOS mode'), + ): + if cfg in defconfig: + findings.append(Finding('agnos-kernel', 'OK', f'{cfg} enabled ({reason})')) + else: + findings.append(Finding( + 'agnos-kernel', 'IMPACT', + f'{cfg} missing from AGNOS tici_defconfig', + f'Inspect AGNOS kernel config changes: {reason}.', + )) + + if 'CONFIG_USB_NET_CDC_NCM=y' in defconfig or 'CONFIG_USB_NET_CDC_NCM=m' in defconfig: + findings.append(Finding('agnos-kernel', 'OK', 'CONFIG_USB_NET_CDC_NCM enabled (Variant B --mode3 supported)')) + else: + findings.append(Finding( + 'agnos-kernel', 'WARN', + 'CONFIG_USB_NET_CDC_NCM is disabled in tici_defconfig', + 'Variant A direct usbmuxd TCP works unchanged, but Variant B (--mode3 host cdc_ncm) requires CONFIG_USB_NET_CDC_NCM.', + )) + + +def _load_meta(checkout_dir: Path) -> dict: + meta_path = checkout_dir / 'meta.json' + if meta_path.is_file(): + try: + return json.loads(meta_path.read_text()) + except ValueError: + pass + + def head(repo_dir: Path) -> str: + if not (repo_dir / '.git').exists(): + return '' + out = subprocess.run(['git', '-C', str(repo_dir), 'rev-parse', 'HEAD'], capture_output=True, text=True) + return out.stdout.strip() if out.returncode == 0 else '' + + return { + 'mode': 'unknown', + 'usbmuxd_sha': head(checkout_dir / 'usbmuxd'), + 'agnos_builder_sha': head(checkout_dir / 'agnos-builder'), + 'agnos_kernel_sha': head(checkout_dir / 'agnos-kernel'), + 'agnos_version': _read_text(checkout_dir / 'agnos-builder' / 'VERSION').strip(), + } + + +def _check_pin_drift(meta: dict, pins: dict, findings: list[Finding]) -> None: + comparisons = ( + ('usbmuxd', 'sha', meta.get('usbmuxd_sha', ''), pins.get('usbmuxd', {}).get('sha', '')), + ('agnos', 'sha', meta.get('agnos_builder_sha', ''), pins.get('agnos_builder', {}).get('sha', '')), + ('agnos-kernel', 'kernel_submodule_sha', meta.get('agnos_kernel_sha', ''), pins.get('agnos_builder', {}).get('kernel_submodule_sha', '')), + ) + for area, label, actual, pinned in comparisons: + if actual and pinned and actual != pinned: + findings.append(Finding( + area, 'NOTICE', + f'upstream {label} moved from pinned {pinned[:12]} to {actual[:12]}', + 'Review changes and run `update-pins` if all compatibility checks pass.', + )) + ver_actual = meta.get('agnos_version', '') + ver_pinned = pins.get('agnos_builder', {}).get('agnos_version', '') + if ver_actual and ver_pinned and ver_actual != ver_pinned: + findings.append(Finding( + 'agnos', 'NOTICE', + f'AGNOS VERSION changed from {ver_pinned} to {ver_actual}', + 'Verify a600000.ssusb sysfs and /data/jetlink/lockdown persistence on the new AGNOS release.', + )) + + +def run_check(checkout_dir: Path, pins_path: Path) -> tuple[list[Finding], dict, dict]: + pins = json.loads(pins_path.read_text()) + meta = _load_meta(checkout_dir) + findings: list[Finding] = [] + _check_usbmuxd(checkout_dir / 'usbmuxd', findings) + _check_agnos(checkout_dir / 'agnos-builder', checkout_dir / 'agnos-kernel', findings) + _check_pin_drift(meta, pins, findings) + return findings, meta, pins + + +def cmd_check(args: argparse.Namespace) -> int: + findings, meta, _ = run_check(Path(args.checkout), Path(args.pins)) + has_impact = any(f.level == 'IMPACT' for f in findings) + has_warn = any(f.level == 'WARN' for f in findings) + failed = has_impact or (args.strict and has_warn) + + if args.json: + print(json.dumps({ + 'ok': not failed, + 'meta': meta, + 'findings': [asdict(f) for f in findings], + }, indent=2)) + else: + print(f"usbmuxd={meta.get('usbmuxd_sha', '?')[:12]} " + f"agnos={meta.get('agnos_builder_sha', '?')[:12]} (v{meta.get('agnos_version', '?')}) " + f"kernel={meta.get('agnos_kernel_sha', '?')[:12]}") + for f in findings: + extra = f' -> {f.remediation}' if f.remediation and f.level != 'OK' else '' + print(f" [{f.level:<6}] {f.area:<12} {f.message}{extra}") + return 1 if failed else 0 + + +def cmd_update_pins(args: argparse.Namespace) -> int: + pins_path = Path(args.pins) + findings, meta, pins = run_check(Path(args.checkout), pins_path) + impacts = [f for f in findings if f.level == 'IMPACT'] + if impacts and not args.force: + for f in impacts: + print(f"REFUSING pin update due to [IMPACT] {f.area}: {f.message}", file=sys.stderr) + return 1 + + changes: list[str] = [] + for section, key, meta_key in ( + ('usbmuxd', 'sha', 'usbmuxd_sha'), + ('agnos_builder', 'sha', 'agnos_builder_sha'), + ('agnos_builder', 'kernel_submodule_sha', 'agnos_kernel_sha'), + ('agnos_builder', 'agnos_version', 'agnos_version'), + ('jetlink_upstream', 'sha', 'jetlink_upstream_sha'), + ): + val = meta.get(meta_key, '') + if val and pins.get(section, {}).get(key) != val: + old = pins[section].get(key, '') + pins[section][key] = val + changes.append(f"{section}.{key}: {old or '(unset)'} -> {val}") + + if not changes: + print('USBMUX_PINS.json is already up to date.') + return 0 + + pins_path.write_text(json.dumps(pins, indent=2) + '\n') + print(f'Updated {pins_path}:') + for line in changes: + print(f' {line}') + return 0 + + +def cmd_sync_jetlink(args: argparse.Namespace) -> int: + pins = json.loads(Path(args.pins).read_text()) + watched = set(pins.get('watched_jetlink_paths', [])) + repo = Path(args.repo) + if args.fetch: + subprocess.run(['git', '-C', str(repo), 'fetch', args.remote, args.branch], check=True) + + target_ref = f'{args.remote}/{args.branch}' + verify = subprocess.run(['git', '-C', str(repo), 'rev-parse', '--verify', target_ref], capture_output=True, text=True) + if verify.returncode != 0: + print(f"Ref {target_ref} not found locally; pass --fetch to fetch from {args.remote}.", file=sys.stderr) + return 1 + upstream_sha = verify.stdout.strip() + base = subprocess.run(['git', '-C', str(repo), 'merge-base', 'HEAD', target_ref], + capture_output=True, text=True, check=True).stdout.strip() + commits = subprocess.run(['git', '-C', str(repo), 'log', '--oneline', f'{base}..{target_ref}'], + capture_output=True, text=True, check=True).stdout.strip().splitlines() + if not commits: + print(f"Up to date with {target_ref} ({upstream_sha[:12]}).") + return 0 + + changed_files = set(subprocess.run(['git', '-C', str(repo), 'diff', '--name-only', f'{base}..{target_ref}'], + capture_output=True, text=True, check=True).stdout.strip().splitlines()) + overlaps = sorted(watched & changed_files) + print(f"{len(commits)} new upstream commit(s) on {target_ref} since merge-base {base[:12]}:") + for c in commits[:20]: + print(f" {c}") + if overlaps: + print("\nWatched path overlap detected (review before rebasing):") + for path in overlaps: + print(f" [OVERLAP] {path}") + else: + print("\nNo overlap with watched branch paths.") + print(f"\nSuggested update: git fetch {args.remote} {args.branch} && git rebase {target_ref}") + return 0 + + +def main() -> int: + p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + sub = p.add_subparsers(dest='cmd', required=True) + + c = sub.add_parser('check', help='Verify usbmuxd + AGNOS contracts against a fetched dependency tree') + c.add_argument('checkout', help='Directory populated by scripts/upstream/fetch_usbmux_deps.sh') + c.add_argument('--pins', default=str(DEFAULT_PINS)) + c.add_argument('--json', action='store_true') + c.add_argument('--strict', action='store_true', help='Also fail on WARN findings') + + u = sub.add_parser('update-pins', help='Update USBMUX_PINS.json from a verified checkout') + u.add_argument('checkout', help='Directory populated by scripts/upstream/fetch_usbmux_deps.sh') + u.add_argument('--pins', default=str(DEFAULT_PINS)) + u.add_argument('--force', action='store_true', help='Update pins even when IMPACT findings are present') + + s = sub.add_parser('sync-jetlink', help='Check zoompilot/jetlink upstream drift and watched path overlaps') + s.add_argument('--repo', default=str(ROOT)) + s.add_argument('--remote', default='origin') + s.add_argument('--branch', default='main') + s.add_argument('--pins', default=str(DEFAULT_PINS)) + s.add_argument('--fetch', action='store_true') + + args = p.parse_args() + return {'check': cmd_check, 'update-pins': cmd_update_pins, 'sync-jetlink': cmd_sync_jetlink}[args.cmd](args) + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/scripts/upstream/fetch_usbmux_deps.sh b/scripts/upstream/fetch_usbmux_deps.sh new file mode 100755 index 00000000..1ea38f0d --- /dev/null +++ b/scripts/upstream/fetch_usbmux_deps.sh @@ -0,0 +1,135 @@ +#!/usr/bin/env bash +# +# Copyright (c) 2026-, Zeph Leggett. +# This file is part of jetlink and is licensed under the MIT License. +# +# Fetches sparse, blobless checkouts of usbmuxd, agnos-builder, and the +# agnos-kernel-sdm845 defconfig as read-only data for check_usbmux_deps.py. +# No hook, filter, or upstream script executes. +# +# Usage: +# scripts/upstream/fetch_usbmux_deps.sh [--latest] +set -euo pipefail + +if [[ $# -lt 1 || $# -gt 2 ]]; then + echo "usage: $0 [--latest]" >&2 + exit 2 +fi + +dest=$1 +mode="pinned" +if [[ "${2:-}" == "--latest" ]]; then + mode="latest" +elif [[ -n "${2:-}" ]]; then + echo "usage: $0 [--latest]" >&2 + exit 2 +fi + +script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +pins_file=${USBMUX_PINS_FILE:-$script_dir/USBMUX_PINS.json} + +read_pin() { + python3 - "$pins_file" "$1" "$2" <<'PY' +import json +import sys + +with open(sys.argv[1]) as f: + data = json.load(f) +node = data[sys.argv[2]] +print(node.get(sys.argv[3], '')) +PY +} + +usbmuxd_url=${USBMUXD_URL:-$(read_pin usbmuxd repo)} +agnos_url=${AGNOS_BUILDER_URL:-$(read_pin agnos_builder repo)} +kernel_url=${AGNOS_KERNEL_URL:-$(read_pin agnos_builder kernel_repo)} +jetlink_url=${JETLINK_UPSTREAM_URL:-$(read_pin jetlink_upstream repo)} + +if [[ "$mode" == "latest" ]]; then + usbmuxd_rev=$(read_pin usbmuxd ref) + agnos_rev=$(read_pin agnos_builder ref) +else + usbmuxd_rev=$(read_pin usbmuxd sha) + agnos_rev=$(read_pin agnos_builder sha) +fi +jetlink_ref=$(read_pin jetlink_upstream ref) +jetlink_pin_sha=$(read_pin jetlink_upstream sha) + +export GIT_LFS_SKIP_SMUDGE=1 +rm -rf "$dest" +mkdir -p "$dest" + +# 1. libimobiledevice/usbmuxd +git init -q "$dest/usbmuxd" +git -C "$dest/usbmuxd" remote add origin "$usbmuxd_url" +git -C "$dest/usbmuxd" sparse-checkout set --no-cone \ + '/src/usbmuxd-proto.h' \ + '/src/client.c' \ + '/src/usb.c' \ + '/src/usb.h' \ + '/src/conf.c' \ + '/src/conf.h' \ + '/configure.ac' +git -C "$dest/usbmuxd" fetch -q --depth 1 --filter=blob:none -- origin "$usbmuxd_rev" +git -C "$dest/usbmuxd" checkout -q FETCH_HEAD +usbmuxd_sha=$(git -C "$dest/usbmuxd" rev-parse HEAD) + +# 2. commaai/agnos-builder +git init -q "$dest/agnos-builder" +git -C "$dest/agnos-builder" remote add origin "$agnos_url" +git -C "$dest/agnos-builder" sparse-checkout set --no-cone \ + '/VERSION' \ + '/Dockerfile.agnos' \ + '/build_kernel.sh' \ + '/build_system.sh' \ + '/userspace/' +git -C "$dest/agnos-builder" fetch -q --depth 1 --filter=blob:none -- origin "$agnos_rev" +git -C "$dest/agnos-builder" checkout -q FETCH_HEAD +agnos_sha=$(git -C "$dest/agnos-builder" rev-parse HEAD) +agnos_version="" +if [[ -f "$dest/agnos-builder/VERSION" ]]; then + agnos_version=$(tr -d '[:space:]' < "$dest/agnos-builder/VERSION") +fi + +# 3. commaai/agnos-kernel-sdm845 (defconfig only, pinned to agnos-builder's gitlink) +kernel_sha=$(git -C "$dest/agnos-builder" ls-tree HEAD agnos-kernel-sdm845 | awk '$2 == "commit" { print $3 }') +if [[ -n "$kernel_sha" && -n "$kernel_url" ]]; then + if git init -q "$dest/agnos-kernel" && + git -C "$dest/agnos-kernel" remote add origin "$kernel_url" && + git -C "$dest/agnos-kernel" sparse-checkout set --no-cone '/arch/arm64/configs/tici_defconfig' && + git -C "$dest/agnos-kernel" fetch -q --depth 1 --filter=blob:none -- origin "$kernel_sha" 2>/dev/null && + git -C "$dest/agnos-kernel" checkout -q FETCH_HEAD 2>/dev/null; then + kernel_sha=$(git -C "$dest/agnos-kernel" rev-parse HEAD) + else + echo "jetlink: warning: could not fetch agnos-kernel-sdm845 ($kernel_sha)" >&2 + rm -rf "$dest/agnos-kernel" + fi +fi + +# 4. zoompilot/jetlink upstream ref SHA (best-effort when checking latest) +jetlink_sha=$jetlink_pin_sha +if [[ "$mode" == "latest" ]]; then + resolved=$(git ls-remote "$jetlink_url" "$jetlink_ref" 2>/dev/null | awk 'NR==1 { print $1 }' || true) + if [[ -n "$resolved" ]]; then + jetlink_sha=$resolved + fi +fi + +python3 - "$dest/meta.json" "$mode" "$usbmuxd_sha" "$agnos_sha" "$kernel_sha" "$agnos_version" "$jetlink_sha" <<'PY' +import json +import sys + +out = { + 'mode': sys.argv[2], + 'usbmuxd_sha': sys.argv[3], + 'agnos_builder_sha': sys.argv[4], + 'agnos_kernel_sha': sys.argv[5], + 'agnos_version': sys.argv[6], + 'jetlink_upstream_sha': sys.argv[7], +} +with open(sys.argv[1], 'w') as f: + json.dump(out, f, indent=2) + f.write('\n') +PY + +echo "usbmuxd=$usbmuxd_sha agnos-builder=$agnos_sha (v${agnos_version:-?}) agnos-kernel=${kernel_sha:-none}" diff --git a/tests/test_upstream_usbmux.py b/tests/test_upstream_usbmux.py new file mode 100644 index 00000000..3c4c9882 --- /dev/null +++ b/tests/test_upstream_usbmux.py @@ -0,0 +1,225 @@ +""" +Copyright (c) 2026-, Zeph Leggett. + +This file is part of jetlink and is licensed under the MIT License. +See the LICENSE file in the root directory for more details. + +Unit tests for upstream tracking toolkit: +- scripts/upstream/check_usbmux_deps.py (check, update-pins, sync-jetlink) +- scripts/upstream/fetch_usbmux_deps.sh (syntax) +- scripts/comma/jetlink-usbmux.sh preflight +""" +from __future__ import annotations + +import json +import os +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +REPO = Path(__file__).resolve().parents[1] +CHECKER = REPO / 'scripts' / 'upstream' / 'check_usbmux_deps.py' +FETCHER = REPO / 'scripts' / 'upstream' / 'fetch_usbmux_deps.sh' +USBMUX_SCRIPT = REPO / 'scripts' / 'comma' / 'jetlink-usbmux.sh' + + +def _write_fake_checkout(root: Path, *, result_connrefused: int = 3, with_mode3: bool = True, + lockdown_dir: str = '/var/lib/lockdown', with_dwc3: bool = True, + with_cdc_ncm: bool = True) -> Path: + mux = root / 'usbmuxd' / 'src' + mux.mkdir(parents=True) + (mux / 'usbmuxd-proto.h').write_text(f''' +#define USBMUXD_SOCKET_FILE "/var/run/usbmuxd" +enum usbmuxd_result {{ + RESULT_OK = 0, + RESULT_BADCOMMAND = 1, + RESULT_BADDEV = 2, + RESULT_CONNREFUSED = {result_connrefused}, +}}; +enum usbmuxd_msgtype {{ + MESSAGE_RESULT = 1, + MESSAGE_PLIST = 8, +}}; +''') + (mux / 'client.c').write_text(''' +const char *cmds[] = { + "ListDevices", "Listen", "Connect", + "Attached", "Detached", + "DeviceID", "PortNumber", "ConnectionType", "USB", +}; +''') + (mux / 'usb.h').write_text('#define VID_APPLE 0x05ac\n') + (mux / 'usb.c').write_text( + 'getenv("USBMUXD_DEFAULT_DEVICE_MODE");\n' if with_mode3 else 'int mode = 1;\n' + ) + (mux / 'conf.h').write_text('#define CONFIG_SUBDIR "lockdown"\n') + (mux / 'conf.c').write_text(f'const char *path = "{lockdown_dir}";\n') + + agnos = root / 'agnos-builder' + agnos.mkdir(parents=True) + (agnos / 'VERSION').write_text('12.1\n') + (agnos / 'Dockerfile.agnos').write_text('FROM ubuntu:24.04\n') + (agnos / 'userspace').mkdir() + (agnos / 'userspace' / 'base_setup.sh').write_text('apt-get install -y python3\n') + + defconfig = root / 'agnos-kernel' / 'arch' / 'arm64' / 'configs' / 'tici_defconfig' + defconfig.parent.mkdir(parents=True) + lines = [ + 'CONFIG_USB_CONFIGFS_F_FS=y', + 'CONFIG_USB_CONFIGFS_NCM=y', + ] + if with_dwc3: + lines.append('CONFIG_USB_DWC3=y') + if with_cdc_ncm: + lines.append('CONFIG_USB_NET_CDC_NCM=y') + defconfig.write_text('\n'.join(lines) + '\n') + + (root / 'meta.json').write_text(json.dumps({ + 'mode': 'pinned', + 'usbmuxd_sha': 'aaaa1111bbbb2222cccc3333dddd4444eeee5555', + 'agnos_builder_sha': '1111222233334444555566667777888899990000', + 'agnos_kernel_sha': '9999888877776666555544443333222211110000', + 'agnos_version': '12.1', + 'jetlink_upstream_sha': '214c31c81e7d983a3853808d8afd1a1376bf0711', + })) + return root + + +def _write_pins(path: Path) -> Path: + path.write_text(json.dumps({ + 'usbmuxd': {'repo': 'https://example.invalid/usbmuxd.git', 'sha': '0000', 'ref': 'HEAD'}, + 'agnos_builder': { + 'repo': 'https://example.invalid/agnos-builder.git', + 'sha': '0000', + 'ref': 'HEAD', + 'kernel_repo': 'https://example.invalid/agnos-kernel.git', + 'kernel_submodule_sha': '0000', + 'agnos_version': '11.0', + }, + 'jetlink_upstream': {'repo': 'https://example.invalid/jetlink.git', 'sha': '0000', 'ref': 'refs/heads/main'}, + 'watched_jetlink_paths': ['jetlink/client.py', 'scripts/bench_link.py'], + }, indent=2)) + return path + + +class UpstreamUsbmuxTests(unittest.TestCase): + def setUp(self) -> None: + self._tmp = tempfile.TemporaryDirectory(dir='/tmp', prefix='jlup_') + self.tmp_path = Path(self._tmp.name) + + def tearDown(self) -> None: + self._tmp.cleanup() + + def _run_checker(self, *args: str) -> subprocess.CompletedProcess: + return subprocess.run( + [sys.executable, '-I', str(CHECKER), *args], + cwd=REPO, + env=dict(os.environ, PYTHONPATH=str(REPO)), + capture_output=True, + text=True, + ) + + def test_check_passes_and_detects_contract_breakage(self) -> None: + pins = _write_pins(self.tmp_path / 'pins.json') + ok_dir = _write_fake_checkout(self.tmp_path / 'ok') + res = self._run_checker('check', str(ok_dir), '--pins', str(pins), '--json') + self.assertEqual(res.returncode, 0, res.stderr + res.stdout) + report = json.loads(res.stdout) + self.assertTrue(report['ok']) + self.assertTrue(any(f['level'] == 'NOTICE' and 'changed from 11.0 to 12.1' in f['message'] for f in report['findings'])) + + bad_mux = _write_fake_checkout(self.tmp_path / 'bad_mux', result_connrefused=99, with_mode3=False, lockdown_dir='/tmp/moved') + res_bad = self._run_checker('check', str(bad_mux), '--pins', str(pins), '--json') + self.assertEqual(res_bad.returncode, 1) + bad_findings = json.loads(res_bad.stdout)['findings'] + impacts = [f for f in bad_findings if f['level'] == 'IMPACT'] + self.assertGreaterEqual(len(impacts), 3) + + bad_kern = _write_fake_checkout(self.tmp_path / 'bad_kern', with_dwc3=False, with_cdc_ncm=False) + res_kern = self._run_checker('check', str(bad_kern), '--pins', str(pins), '--json') + self.assertEqual(res_kern.returncode, 1) + kern_findings = json.loads(res_kern.stdout)['findings'] + self.assertTrue(any(f['level'] == 'IMPACT' and 'CONFIG_USB_DWC3=y' in f['message'] for f in kern_findings)) + self.assertTrue(any(f['level'] == 'WARN' and 'CONFIG_USB_NET_CDC_NCM' in f['message'] for f in kern_findings)) + + def test_strict_fails_on_warn_and_update_pins_guards_impact(self) -> None: + pins = _write_pins(self.tmp_path / 'pins.json') + warn_dir = _write_fake_checkout(self.tmp_path / 'warn', with_cdc_ncm=False) + res = self._run_checker('check', str(warn_dir), '--pins', str(pins), '--strict') + self.assertEqual(res.returncode, 1) + + bad_dir = _write_fake_checkout(self.tmp_path / 'bad_upd', with_mode3=False) + refused = self._run_checker('update-pins', str(bad_dir), '--pins', str(pins)) + self.assertEqual(refused.returncode, 1) + self.assertEqual(json.loads(pins.read_text())['agnos_builder']['agnos_version'], '11.0') + + good_dir = _write_fake_checkout(self.tmp_path / 'good_upd') + updated = self._run_checker('update-pins', str(good_dir), '--pins', str(pins)) + self.assertEqual(updated.returncode, 0, updated.stderr) + new_pins = json.loads(pins.read_text()) + self.assertEqual(new_pins['usbmuxd']['sha'], 'aaaa1111bbbb2222cccc3333dddd4444eeee5555') + self.assertEqual(new_pins['agnos_builder']['agnos_version'], '12.1') + + def test_sync_jetlink_detects_watched_overlap(self) -> None: + repo = self.tmp_path / 'git_repo' + repo.mkdir() + git = lambda *a: subprocess.run(['git', '-C', str(repo), *a], check=True, capture_output=True, text=True) + git('init', '-b', 'main') + git('config', 'user.email', 'test@example.com') + git('config', 'user.name', 'Test') + (repo / 'jetlink').mkdir() + (repo / 'jetlink' / 'client.py').write_text('v1\n') + git('add', '.') + git('commit', '-m', 'base') + base_sha = git('rev-parse', 'HEAD').stdout.strip() + + git('checkout', '-b', 'feature') + (repo / 'other.txt').write_text('feature work\n') + git('add', '.') + git('commit', '-m', 'feature commit') + + git('checkout', 'main') + (repo / 'jetlink' / 'client.py').write_text('v2 upstream\n') + git('add', '.') + git('commit', '-m', 'upstream touch watched file') + git('update-ref', 'refs/remotes/origin/main', 'HEAD') + git('checkout', 'feature') + self.assertNotEqual(base_sha, '') + + pins = _write_pins(self.tmp_path / 'pins.json') + res = self._run_checker('sync-jetlink', '--repo', str(repo), '--remote', 'origin', '--branch', 'main', '--pins', str(pins)) + self.assertEqual(res.returncode, 0, res.stderr) + self.assertIn('[OVERLAP] jetlink/client.py', res.stdout) + self.assertIn('git rebase origin/main', res.stdout) + + def test_shell_scripts_syntax_and_preflight(self) -> None: + subprocess.run(['bash', '-n', str(FETCHER)], check=True) + subprocess.run(['bash', '-n', str(USBMUX_SCRIPT)], check=True) + + fake_bin = self.tmp_path / 'bin' + fake_bin.mkdir() + fake_mux = fake_bin / 'usbmuxd' + fake_mux.write_text('#!/usr/bin/env bash\n# USBMUXD_DEFAULT_DEVICE_MODE\necho "usbmuxd 1.1.1"\n') + fake_mux.chmod(0o755) + fake_pair = fake_bin / 'idevicepair' + fake_pair.write_text('#!/usr/bin/env bash\necho "idevicepair 1.3.0"\n') + fake_pair.chmod(0o755) + + ver = self.tmp_path / 'VERSION' + ver.write_text('12.1\n') + env = dict( + os.environ, + JETLINK_BIN_DIR=str(fake_bin), + JETLINK_AGNOS_VERSION_FILE=str(ver), + JETLINK_UDC_GLUE=str(self.tmp_path / 'missing_udc'), + ) + res = subprocess.run(['bash', str(USBMUX_SCRIPT), 'preflight'], env=env, capture_output=True, text=True) + self.assertEqual(res.returncode, 0, res.stderr) + self.assertIn('AGNOS 12.1', res.stdout) + self.assertIn('Preflight Mode 3 support: yes', res.stdout) + + +if __name__ == '__main__': + unittest.main() From 9c8f672f0c0946ba099a7c22e1b142b752afe8be Mon Sep 17 00:00:00 2001 From: moltenglue <257664494+moltenglue@users.noreply.github.com> Date: Mon, 30 Nov 2026 10:53:55 -0500 Subject: [PATCH 4/5] Document CDC-NCM best-case latency (~4.3 ms UDP JFRM / ~7.35 ms TCP) and full-frame scaling limit --- .../Sources/JetlinkServer/Transport.swift | 6 ++++-- docs/usbmux-transport.md | 20 +++++++++++-------- ios/Jetlink/App/PhoneSettings.swift | 5 +++-- jetlink/comma/usbmux_transport.py | 6 ++++++ 4 files changed, 25 insertions(+), 12 deletions(-) diff --git a/JetlinkKit/Sources/JetlinkServer/Transport.swift b/JetlinkKit/Sources/JetlinkServer/Transport.swift index 012a7fe8..f9d32133 100644 --- a/JetlinkKit/Sources/JetlinkServer/Transport.swift +++ b/JetlinkKit/Sources/JetlinkServer/Transport.swift @@ -128,8 +128,10 @@ public final class TCPTransport: @unchecked Sendable { /// A port and a new token for the comma to send frames to as datagrams, /// or nil off the cable: only CDC-NCM (`medium == .usb`) is offered them. - /// USB Host-mode usbmuxd tunnels report `.usb3`/`.usb2` over loopback and - /// bypass `u_ether`'s segment bottleneck, so they stay on TCP directly. + /// CDC-NCM reaches ~4.3 ms/frame at best on 393 KB frames with UDP JFRM + /// (~7.35 ms over TCP) because of Linux 4.9 `u_ether`; USB Host-mode + /// usbmuxd tunnels report `.usb3`/`.usb2` over loopback and bypass `u_ether`, + /// targeting multi-MB full-frame payloads over raw TCP directly. /// The session's loop thread calls this, as it calls `recv()`. public func offerDatagrams() -> (port: UInt16, token: UInt32)? { guard medium == .usb || TCPTransport.datagramsAnyPeer else { return nil } diff --git a/docs/usbmux-transport.md b/docs/usbmux-transport.md index 638b8ca9..bd1ae268 100644 --- a/docs/usbmux-transport.md +++ b/docs/usbmux-transport.md @@ -4,7 +4,11 @@ Opt-in experimental transport that reverses USB roles between the comma and an i ## Why this exists -In standard iOS mode (`jetlink-root.sh gadget --ios`), the comma acts as a composite USB gadget (`u_ether` CDC-NCM) and the iPhone acts as the USB host. On the comma's Linux 4.9 `u_ether` gadget driver, sending a 393 KB `INFER_REQ` frame adds ~8 ms of transport overhead (and required `JFRM` UDP datagram chunking to bypass TCP segment limits). +In standard iOS mode (`jetlink-root.sh gadget --ios`), the comma acts as a composite USB gadget (`u_ether` CDC-NCM) and the iPhone acts as the USB host. Even at best on USB 3 SuperSpeed with every AGNOS kernel tuning enabled (UDP `JFRM` datagrams, core-6 RPS receive steering, `NOTRACK` conntrack bypass, and 4 MB socket buffers): + +- **CDC-NCM over UDP `JFRM` (current best case, 393 KB)**: **`~4.3 ms`** per frame on the bench (`~7` UDP datagrams; see [`jetlink/protocol.py`](../jetlink/protocol.py) and [Link Protocol](link-protocol.md#frames-over-a-phones-cable)). +- **CDC-NCM over TCP (393 KB)**: **`~7.35–7.7 ms`** per frame (`~272` TCP segments), degrading to `12.4 ms` mean (`36–47 ms` p90) if receive interrupts contend with real-time threads, plus `~5 ms` more on USB 2 fallback (`480 Mbps`). +- **4 MiB Full Frame bottleneck (~10.7x larger than 393 KB)**: Scaling even CDC-NCM's best-case `~4.3 ms` `u_ether` stack cost linearly to a ~4 MiB full-frame payload approaches ~45+ ms in transport alone—consuming virtually the entire 46–50 ms driving budget before model inference starts. Reversing USB roles removes `u_ether` from the hot path: @@ -27,13 +31,13 @@ Independent `iperf3` benchmarks over `usbmuxd` by [Ethan Huang (*iPhone USB Spee ## Transport & protocol comparison -| Path | USB Roles (Comma / iPhone) | Wire Mechanism | Notes & Tradeoffs | -| --- | --- | --- | --- | -| **Default Jetlink CDC-NCM (TCP)** | Device (`u_ether`) / Host | TCP over USB CDC-NCM (`192.168.60.1:5599`) | ~272 TCP segments per 393 KB frame (`7.35 ms/frame` on bench; [Link Protocol](link-protocol.md#frames-over-a-phones-cable)) | -| **Default Jetlink CDC-NCM (UDP `JFRM`)** | Device (`u_ether`) / Host | ~7 equal UDP datagrams + TCP replies | Cuts comma stack cost from `7.35 ms` to `4.3 ms/frame` ([Link Protocol](link-protocol.md#frames-over-a-phones-cable)); default for current 393 KB models | -| **Variant A: Direct `usbmuxd` (this branch)** | Host (`libusb`) / Device | Direct `/var/run/usbmuxd` plist `Connect` → `127.0.0.1:5599` | Same raw `usbmux` TCP tunnel used by Xcode and [PhotoTransfer](https://github.com/tzulunyeh/PhotoTransfer/blob/main/README.md); skips PTP/AFC bottlenecks and eliminates `iproxy` double-copy overhead | -| **Variant B: `usbmuxd --mode3`** | Host (`cdc_ncm`) / Device (`AppleUSBDeviceNCMData`) | `USBMUXD_DEFAULT_DEVICE_MODE=3` + IP/UDP `JFRM` | Fallback A/B path per [Synacktiv](https://synacktiv.com/publications/ios-a-journey-in-the-usb-networking-stack) if Variant A TCP buffering jitters on AGNOS | -| **Image Capture (PTP) / iMazing (AFC)** | Host / Device | PTP / Apple File Conduit | Documented by [PhotoTransfer](https://github.com/tzulunyeh/PhotoTransfer/blob/main/README.md) as severely bottlenecked for large transfers; unsuitable for 20 Hz inference | +| Path | USB Roles (Comma / iPhone) | Wire Mechanism | Best-Case Latency (393 KB) | 4 MiB Full Frame Outlook | Notes & Tradeoffs | +| --- | --- | --- | --- | --- | --- | +| **Default Jetlink CDC-NCM (TCP)** | Device (`u_ether`) / Host | TCP over USB CDC-NCM (`192.168.60.1:5599`) | **`7.35–7.7 ms`** (`12.4 ms` if RT contends) | Misses budget (~75–80+ ms extrapolated) | ~272 TCP segments per 393 KB frame on AGNOS 4.9 `u_ether` ([Link Protocol](link-protocol.md#frames-over-a-phones-cable)) | +| **Default Jetlink CDC-NCM (UDP `JFRM`)** | Device (`u_ether`) / Host | ~7 equal UDP datagrams + TCP replies | **`~4.3 ms`** | Tight / ~45+ ms extrapolated | **Current best case for CDC-NCM** with RPS core-6 + `NOTRACK` + 4 MB buffers; ideal for 393 KB, tight for multi-MB frames | +| **Variant A: Direct `usbmuxd` (this branch)** | Host (`libusb`) / Device | Direct `/var/run/usbmuxd` plist `Connect` → `127.0.0.1:5599` | ~0.5 ms theoretical wire time (`6.12 Gb/s` USB 3.2 Gen 2; HW A/B TBD) | ~5.5 ms theoretical wire time | Same raw `usbmux` TCP tunnel used by Xcode and [PhotoTransfer](https://github.com/tzulunyeh/PhotoTransfer/blob/main/README.md); eliminates `u_ether` and `iproxy` double-copy overhead | +| **Variant B: `usbmuxd --mode3`** | Host (`cdc_ncm`) / Device (`AppleUSBDeviceNCMData`) | `USBMUXD_DEFAULT_DEVICE_MODE=3` + IP/UDP `JFRM` | Fallback A/B target (< 6 ms p99) | Host-side `cdc_ncm` A/B target | Fallback per [Synacktiv](https://synacktiv.com/publications/ios-a-journey-in-the-usb-networking-stack) if Variant A TCP buffering jitters on AGNOS | +| **Image Capture (PTP) / iMazing (AFC)** | Host / Device | PTP / Apple File Conduit | Unsuitable | Unsuitable | Documented by [PhotoTransfer](https://github.com/tzulunyeh/PhotoTransfer/blob/main/README.md) as severely bottlenecked for large transfers | ## Opt-in design ("Full Frame Experimental Network") diff --git a/ios/Jetlink/App/PhoneSettings.swift b/ios/Jetlink/App/PhoneSettings.swift index b55fb1fc..8ea03457 100644 --- a/ios/Jetlink/App/PhoneSettings.swift +++ b/ios/Jetlink/App/PhoneSettings.swift @@ -29,8 +29,9 @@ final class PhoneSettings { /// Opt-in USB Host-mode listener on 127.0.0.1:5599 for testing full-frame /// models via usbmuxd. Defaults to `false` so normal users stay on the - /// standard CDC-NCM dial setup; binds strictly to loopback so LAN exposure - /// and Local Network permission are avoided. + /// standard CDC-NCM dial setup (~4.3 ms/frame best case with UDP JFRM at + /// 393 KB, ~7.35 ms TCP, which cannot scale cleanly to ~4 MiB full frames); + /// binds strictly to loopback so LAN exposure and Local Network permission are avoided. var fullFrameExperimentalNetwork: Bool { didSet { defaults.set(fullFrameExperimentalNetwork, forKey: Keys.fullFrameExperimentalNetwork) } } diff --git a/jetlink/comma/usbmux_transport.py b/jetlink/comma/usbmux_transport.py index e538e55c..0b140f4f 100644 --- a/jetlink/comma/usbmux_transport.py +++ b/jetlink/comma/usbmux_transport.py @@ -6,6 +6,12 @@ Direct usbmuxd transport for iOS in USB Host mode on the comma. +Default CDC-NCM gadget networking (`u_ether` on AGNOS Linux 4.9) reaches +~4.3 ms/frame at best on 393 KB payloads with UDP JFRM (~7.35-7.7 ms over TCP), +leaving minimal headroom if payloads scale ~10x to ~4 MiB full-frame models. +Reversing USB roles lets `usbmuxd` drive raw USB 3 bulk pipes (~6.12 Gb/s +measured on USB 3.2 Gen 2 iPhones) directly to 127.0.0.1:5599 in the iOS app. + Instead of spawning iproxy as an extra localhost-to-localhost copy process, UsbmuxClient speaks usbmuxd's lightweight plist protocol directly over /var/run/usbmuxd, upgrades the Unix socket to a USB 3 bulk TCP tunnel targeting From 48841768b7ae76ccf2ab252345839ed152baf8b0 Mon Sep 17 00:00:00 2001 From: moltenglue <257664494+moltenglue@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:12:46 -0500 Subject: [PATCH 5/5] Wire Full Frame Experimental Network (usbmuxd) end-to-end with seamless toggle & auto-Trust --- .../Sources/JetlinkServer/UsbmuxHandoff.swift | 198 ++++++ .../UsbmuxHandoffTests.swift | 63 ++ docs/usbmux-transport.md | 25 +- ios/Jetlink/App/AppModel.swift | 3 + ios/Jetlink/Server/PhoneServer.swift | 149 ++++- .../Views/Settings/SettingsScreen.swift | 2 +- ios/Jetlink/Views/Status/StatusContent.swift | 3 + ios/Jetlink/Views/Status/StatusState.swift | 4 + jetlink/comma/gadget.py | 35 +- jetlink/comma/lending.py | 17 +- jetlink/comma/owner.py | 186 +++++- jetlink/comma/usbmux_host.py | 608 ++++++++++++++++++ jetlink/openpilot/link.py | 8 + jetlink/openpilot/status.py | 6 +- scripts/comma/jetlink-usbmux.sh | 27 +- tests/test_usbmux_host.py | 333 ++++++++++ 16 files changed, 1635 insertions(+), 32 deletions(-) create mode 100644 JetlinkKit/Sources/JetlinkServer/UsbmuxHandoff.swift create mode 100644 JetlinkKit/Tests/JetlinkServerTests/UsbmuxHandoffTests.swift create mode 100644 jetlink/comma/usbmux_host.py create mode 100644 tests/test_usbmux_host.py diff --git a/JetlinkKit/Sources/JetlinkServer/UsbmuxHandoff.swift b/JetlinkKit/Sources/JetlinkServer/UsbmuxHandoff.swift new file mode 100644 index 00000000..e28a6579 --- /dev/null +++ b/JetlinkKit/Sources/JetlinkServer/UsbmuxHandoff.swift @@ -0,0 +1,198 @@ +import Foundation + +#if canImport(Darwin) + import Darwin +#elseif canImport(Glibc) + import Glibc +#elseif canImport(Android) + import Android +#endif + +/// Sideband handoff between default CDC-NCM networking (`192.168.60.1`) and +/// Full Frame Experimental Network (`usbmuxd` on `127.0.0.1`). +/// +/// Runs on TCP port `5600` alongside Jetlink protocol v3 (`5599`), keeping +/// Jetlink framing completely unchanged: +/// - In experimental mode, if the iPhone still sees the comma's CDC-NCM gadget +/// (`192.168.60.x`), `requestUsbmux` tells `jetlinkd` (`"USBMUX\n"`) to tear +/// down the gadget, switch the AUX port to USB Host, start `usbmuxd`, and run +/// `idevicepair` so the native Trust prompt appears automatically. +/// - In default CDC-NCM mode, `NcmHandoffAdvertiser` listens on `127.0.0.1:5600` +/// and answers `"NCM\n"` so a comma booted into `usbmuxd` returns to CDC-NCM. +public enum UsbmuxHandoff { + public static let port: UInt16 = 5600 + + public enum RequestResult: Sendable, Equatable { + case accepted + case missingUsbmuxd + case unsupported + case unreachable(String) + } + + /// Asks `jetlinkd` on `host:port` to switch from CDC-NCM gadget mode to USB Host `usbmuxd`. + public static func requestUsbmux( + host: String, port: UInt16 = UsbmuxHandoff.port, timeout: TimeInterval = 1.5 + ) -> RequestResult { + let fd = socket(AF_INET, Sys.stream, 0) + guard fd >= 0 else { return .unreachable(String(cString: strerror(errno))) } + defer { Sys.close(fd) } + + #if canImport(Darwin) + Sys.set(fd, SOL_SOCKET, SO_NOSIGPIPE, 1) + #endif + + var address = sockaddr_in() + #if canImport(Darwin) + address.sin_len = UInt8(MemoryLayout.size) + #endif + address.sin_family = sa_family_t(AF_INET) + address.sin_port = port.bigEndian + address.sin_addr.s_addr = inet_addr(host) + + let flags = fcntl(fd, F_GETFL) + _ = fcntl(fd, F_SETFL, flags | O_NONBLOCK) + var connected = withUnsafePointer(to: &address) { + $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { + Sys.connect(fd, $0, socklen_t(MemoryLayout.size)) + } + } + if connected != 0, errno == EINPROGRESS { + var poller = pollfd(fd: fd, events: Int16(POLLOUT), revents: 0) + let ready = poll(&poller, 1, Int32(max(1, timeout * 1000))) + if ready == 0 { + return .unreachable("timed out reaching \(host):\(port)") + } + var sockErr: Int32 = 0 + var len = socklen_t(MemoryLayout.size) + if ready > 0 && getsockopt(fd, SOL_SOCKET, SO_ERROR, &sockErr, &len) == 0 && sockErr == 0 { + connected = 0 + } else { + errno = sockErr != 0 ? sockErr : errno + } + } + guard connected == 0 else { + let err = errno + if err == ECONNREFUSED { return .unsupported } + return .unreachable(String(cString: strerror(err))) + } + _ = fcntl(fd, F_SETFL, flags) + + var tv = timeval( + tv_sec: .init(timeout), + tv_usec: .init((timeout - Double(Int(timeout))) * 1_000_000) + ) + _ = setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, socklen_t(MemoryLayout.size)) + _ = setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, socklen_t(MemoryLayout.size)) + + let cmd = Array("USBMUX\n".utf8) + let sent = cmd.withUnsafeBytes { ptr -> Int in + guard let base = ptr.baseAddress else { return -1 } + return send(fd, base, ptr.count, Sys.sendFlags) + } + guard sent == cmd.count else { + return .unreachable("failed sending handoff command") + } + + var buffer = [UInt8](repeating: 0, count: 128) + let n = buffer.withUnsafeMutableBytes { ptr -> Int in + guard let base = ptr.baseAddress else { return -1 } + return Sys.read(fd, base, ptr.count) + } + guard n > 0 else { + return .unreachable("empty reply from comma handoff listener") + } + let reply = String(decoding: buffer[.. Models > Jetlink = iOS` on the comma), and a single iOS toggle switches both ends automatically whether you plug the cable in **before comma power-on** or **after comma boot**: -- **Default (`OFF`)**: `PhoneSettings.fullFrameExperimentalNetwork` is `false`. The iOS app continues to dial the comma over the CDC-NCM USB network interface (`192.168.60.1:5599`), and `jetlink/comma/jetlink-root.sh` is untouched. +- **Default (`OFF`)**: `PhoneSettings.fullFrameExperimentalNetwork` is `false`. The iOS app dials the comma over the CDC-NCM USB network interface (`192.168.60.1:5599`), and listens on `127.0.0.1:5600` (`NcmHandoffAdvertiser`, returning `"NCM\n"`). If the comma was left in `usbmux` mode, `jetlinkd` detects `"NCM\n"`, clears `/data/jetlink/transport_mode`, stops `usbmuxd`, and rebuilds the CDC-NCM gadget. - **Experimental (`ON`)**: Under **Settings > Connection > Full Frame Experimental Network**, toggling it on: - Stops CDC-NCM dialing in `PhoneServer` and binds `TCPListener` strictly to `127.0.0.1:5599` (`TCP_NODELAY = 1`, 4 MB send/receive socket buffers, pre-allocated zero-copy `FrameReader`). - Uses only public POSIX loopback sockets (`TCPListener`) — zero USBDriverKit extensions, zero MFi hardware, zero private iOS APIs, no LAN socket exposure, and no Local Network permission prompt. - - Shows **Listening on USB (usbmuxd)** → **Connected via usbmuxd (USB 3)** in the app status views and Settings. + - Sends `"USBMUX\n"` to `jetlinkd`'s sideband listener (`192.168.60.1:5600`) whenever the CDC-NCM interface is present. `jetlinkd` persists `/data/jetlink/transport_mode = usbmux`, tears down the CDC-NCM gadget, forces USB Host (`dfp` via `DR_Swap`/`PR_Swap`), starts `usbmuxd`, and runs `idevicepair` automatically so iOS pops **"Trust This Computer?"** on first pairing. + - Because `transport_mode` is persisted in `/data/jetlink/transport_mode`, booting the comma with the iPhone already plugged in starts `jetlinkd` directly in USB Host (`usbmuxd`) mode. Setting **Jetlink = Off** on the comma resets `transport_mode` back to CDC-NCM as an escape hatch. + - Shows **Listening on USB (usbmuxd)** → **Connected via usbmuxd (USB 3)** in the app status views and Settings, and turns the comma's eGPU indicator green when driving. ## Architecture & iOS USB device modes @@ -101,10 +103,19 @@ Both `scripts/comma/jetlink-usbmux.sh speed` and `detect_apple_usb_speed()` veri ## Commands -On the iPhone/iPad: -1. Open **Settings > Connection** and turn on **Full Frame Experimental Network**. +### Live openpilot (automatic via iOS toggle) +On your Mac: +```bash +# Deploy this Jetlink branch to the comma (keep openpilot Jetlink setting on iOS) +scripts/deploy_to_comma.sh comma@ +``` +On the comma (one-time setup to install `usbmuxd` + `idevicepair` + persistent `/data/jetlink/lockdown`): +```bash +sudo bash /data/openpilot/jetlink_repo/scripts/comma/jetlink-usbmux.sh install --remount-rw +``` +Then toggle **Settings > Connection > Full Frame Experimental Network** on/off in the Jetlink iOS app. Unlock the iPhone and tap **Trust This Computer** when prompted. -On the comma: +### Standalone manual setup & benchmarks (optional) ```bash # Tear down CDC-NCM gadget, map /data/jetlink/lockdown, start usbmuxd sudo scripts/comma/jetlink-usbmux.sh setup --install diff --git a/ios/Jetlink/App/AppModel.swift b/ios/Jetlink/App/AppModel.swift index 53b518ab..11e79f15 100644 --- a/ios/Jetlink/App/AppModel.swift +++ b/ios/Jetlink/App/AppModel.swift @@ -65,6 +65,9 @@ final class AppModel { state.catalogUnavailable = models.catalog?.error != nil && (models.catalog?.models.isEmpty ?? true) state.usbmuxMode = settings.fullFrameExperimentalNetwork state.localNetworkDenied = !settings.fullFrameExperimentalNetwork && localNetwork.state == .denied + state.handoffTitle = server.handoffNotice?.title + state.handoffDetail = server.handoffNotice?.detail + state.handoffSymbol = server.handoffNotice?.symbol return state } diff --git a/ios/Jetlink/Server/PhoneServer.swift b/ios/Jetlink/Server/PhoneServer.swift index 452231df..6690a633 100644 --- a/ios/Jetlink/Server/PhoneServer.swift +++ b/ios/Jetlink/Server/PhoneServer.swift @@ -21,6 +21,7 @@ final class PhoneServer: ServerControlling { /// The last ten seconds of frames, refreshed once a second while serving. private(set) var recent: StatsEvent? private(set) var lastFailure: String? + private(set) var handoffNotice: HandoffNotice? let modelEvents: AsyncStream /// The profile the running server was started on. private(set) var profile = Processor.fallback @@ -30,6 +31,30 @@ final class PhoneServer: ServerControlling { /// A model on its way to a server on its own profile (`followModel`). @ObservationIgnored private var following: String? + struct HandoffNotice: Equatable { + let title: String + let detail: String + let symbol: String + + static let switching = HandoffNotice( + title: "Switching Comma to usbmuxd", + detail: "Asking the comma to leave CDC-NCM gadget mode and enter USB Host mode.", + symbol: "arrow.triangle.2.circlepath") + static let tapTrust = HandoffNotice( + title: "Unlock & Tap \"Trust This Computer\"", + detail: "If prompted on your iPhone, tap Trust so the comma can connect over usbmuxd.", + symbol: "lock.shield") + static let missingUsbmuxd = HandoffNotice( + title: "Install usbmuxd on Comma", + detail: "Run scripts/comma/jetlink-usbmux.sh install on your comma once so usbmuxd runs.", + symbol: "exclamationmark.triangle.fill") + static let unsupportedComma = HandoffNotice( + title: "Comma Not Updated for usbmuxd", + detail: + "Deploy this Jetlink branch to your comma, or turn Full Frame Experimental Network off.", + symbol: "cable.connector.slash") + } + /// How far back the dashboard's headline reaches. static let recentWindow: TimeInterval = 10 @@ -42,6 +67,8 @@ final class PhoneServer: ServerControlling { private var server: Server? { embedded?.server } @ObservationIgnored private var consumeTask: Task? @ObservationIgnored private var recentTask: Task? + @ObservationIgnored private var handoffTask: Task? + @ObservationIgnored private var ncmAdvertiser: NcmHandoffAdvertiser? @ObservationIgnored private let log = Logger(subsystem: "io.zoompilot.jetlink", category: "app") /// What the in-process server logs, for a Logs view. @@ -99,10 +126,106 @@ final class PhoneServer: ServerControlling { } private func updateDial() { - // In Full Frame Experimental Network mode the comma connects into 127.0.0.1:5599 over usbmuxd, - // so suppress CDC-NCM outbound dialing even if a virtual cable interface is present. - let target = (settings.fullFrameExperimentalNetwork || network.cable == nil) ? nil : PhoneServer.commaDial - server?.setDial(target) + let wantUsbmux = settings.fullFrameExperimentalNetwork + let hasCable = network.cable != nil + let connected = link.state == .connected + + if wantUsbmux { + ncmAdvertiser?.stop() + ncmAdvertiser = nil + // In Full Frame Experimental Network mode the comma connects into 127.0.0.1:5599 over usbmuxd, + // so suppress CDC-NCM outbound dialing even if a CDC-NCM cable interface is temporarily present. + server?.setDial(nil) + + if runState == .serving && hasCable && !connected { + startUsbmuxHandoffLoop() + } else { + handoffTask?.cancel() + handoffTask = nil + if connected { + handoffNotice = nil + } else if handoffNotice == .switching { + handoffNotice = .tapTrust + } else if handoffNotice == .missingUsbmuxd || handoffNotice == .unsupportedComma { + handoffNotice = nil + } + } + } else { + handoffTask?.cancel() + handoffTask = nil + handoffNotice = nil + if runState == .serving { + ensureNcmAdvertiser() + } else { + ncmAdvertiser?.stop() + ncmAdvertiser = nil + } + server?.setDial(hasCable ? PhoneServer.commaDial : nil) + } + } + + private func ensureNcmAdvertiser() { + if let ncmAdvertiser { + ncmAdvertiser.reopenIfNeeded() + return + } + let advertiser = NcmHandoffAdvertiser(port: UsbmuxHandoff.port) + do { + try advertiser.start() + ncmAdvertiser = advertiser + } catch { + log.warning("could not start NCM handoff advertiser: \(String(describing: error))") + } + } + + private func startUsbmuxHandoffLoop() { + guard handoffTask == nil else { return } + handoffTask = Task { [weak self] in + while !Task.isCancelled { + guard let self, + self.runState == .serving, + self.settings.fullFrameExperimentalNetwork, + self.network.cable != nil, + self.link.state != .connected + else { break } + + if self.handoffNotice == nil { + self.handoffNotice = .switching + } + + let host = NetworkInterfaces.commaAddress + let result = await Task.detached { + UsbmuxHandoff.requestUsbmux(host: host) + }.value + + guard !Task.isCancelled else { break } + + let delaySeconds: Double + switch result { + case .accepted: + self.note(.info, "comma accepted usbmuxd handoff; switching to USB Host mode") + self.handoffNotice = .tapTrust + delaySeconds = 3.0 + case .missingUsbmuxd: + self.note(.warning, "comma reported usbmuxd is not installed") + self.handoffNotice = .missingUsbmuxd + delaySeconds = 10.0 + case .unsupported: + self.note( + .warning, + "comma handoff port refused; update comma or toggle experimental network off" + ) + self.handoffNotice = .unsupportedComma + delaySeconds = 10.0 + case .unreachable: + delaySeconds = 2.0 + } + try? await Task.sleep(for: .seconds(delaySeconds)) + } + if !Task.isCancelled { + self?.handoffTask = nil + } + } } // MARK: lifecycle @@ -157,6 +280,11 @@ final class PhoneServer: ServerControlling { private func tearDown(release: Bool) { recentTask?.cancel() recentTask = nil + handoffTask?.cancel() + handoffTask = nil + ncmAdvertiser?.stop() + ncmAdvertiser = nil + handoffNotice = nil embedded?.stop(releasingEngine: release) consumeTask?.cancel() consumeTask = nil @@ -189,6 +317,9 @@ final class PhoneServer: ServerControlling { /// iOS takes a suspended app's listening socket; listen again on the way back. func becameActive() { + if runState == .serving, !settings.fullFrameExperimentalNetwork { + ncmAdvertiser?.reopenIfNeeded() + } guard runState == .serving, let server, !server.isListening else { return } do { try server.reopenListener() @@ -262,8 +393,14 @@ final class PhoneServer: ServerControlling { if !state.apply(event) { modelEventsContinuation.yield(event) } - if case .link(let value) = event, value.state != .connected { - recent = nil + if case .link(let value) = event { + if value.state == .connected { + handoffNotice = nil + handoffTask?.cancel() + handoffTask = nil + } else { + recent = nil + } } if case .engine(let value) = event, let sha256 = value.sha256 { followModel(sha256) diff --git a/ios/Jetlink/Views/Settings/SettingsScreen.swift b/ios/Jetlink/Views/Settings/SettingsScreen.swift index 78da6a08..bae238bd 100644 --- a/ios/Jetlink/Views/Settings/SettingsScreen.swift +++ b/ios/Jetlink/Views/Settings/SettingsScreen.swift @@ -96,7 +96,7 @@ struct SettingsScreen: View { Text("Connection") } footer: { Text( - "Off uses the default Jetlink USB setup. Turn on to test full-frame models over comma USB Host mode (usbmuxd on 127.0.0.1:5599): connect through a powered 10 Gbps USB 3 hub and tap Trust when prompted." + "Off uses the default Jetlink USB setup. Turn on to test full-frame models over comma USB Host mode (usbmuxd on 127.0.0.1:5599): connect over USB 3, unlock your iPhone, and tap \"Trust This Computer\" if prompted. Turning it off switches the comma back automatically." ) } } diff --git a/ios/Jetlink/Views/Status/StatusContent.swift b/ios/Jetlink/Views/Status/StatusContent.swift index 59a0252c..6e2c2a2b 100644 --- a/ios/Jetlink/Views/Status/StatusContent.swift +++ b/ios/Jetlink/Views/Status/StatusContent.swift @@ -43,6 +43,9 @@ struct StatusContent: View { private var layout: some View { VStack(spacing: StatusContent.spacing) { + if state.link.state != .connected, let title = state.handoffTitle, let detail = state.handoffDetail { + banner(title, detail, symbol: state.handoffSymbol ?? "exclamationmark.triangle.fill") + } if state.needsForeground { banner( "Keep Jetlink on Screen", "The big model stops while Jetlink is in the background.", diff --git a/ios/Jetlink/Views/Status/StatusState.swift b/ios/Jetlink/Views/Status/StatusState.swift index df587a76..74a14a60 100644 --- a/ios/Jetlink/Views/Status/StatusState.swift +++ b/ios/Jetlink/Views/Status/StatusState.swift @@ -38,6 +38,10 @@ struct StatusState: Equatable { var slowWarning: String? /// Opt-in Full Frame Experimental Network (USB Host-mode usbmuxd on 127.0.0.1:5599). var usbmuxMode = false + /// Sideband handoff status / actionable guidance while waiting to switch to usbmuxd. + var handoffTitle: String? + var handoffDetail: String? + var handoffSymbol: String? var isUsbmuxConnection: Bool { usbmuxMode || link.isLoopback } diff --git a/jetlink/comma/gadget.py b/jetlink/comma/gadget.py index 21f0a644..e8d92906 100644 --- a/jetlink/comma/gadget.py +++ b/jetlink/comma/gadget.py @@ -91,13 +91,13 @@ def _write(path: Path, text: str | None, what: str) -> bool: def link_state() -> tuple[str | None, str | None]: """The link record in one read: the gadget the owner built, 'cable' for - iOS (the phone's network interface on the gadget) or 'usb', and on the - cable the phone's address while a link is up. (None, None) before the - owner has said.""" + iOS (the phone's network interface on the gadget), 'usbmux' (USB Host-mode + usbmuxd), or 'usb', and on the cable/usbmux the phone's address/id while a + link is up. (None, None) before the owner has said.""" record = read(LINK).split() - if record[:1] not in (['cable'], ['usb']): + if record[:1] not in (['cable'], ['usb'], ['usbmux']): return None, None - return record[0], (record[1] if record[0] == 'cable' and len(record) > 1 else None) + return record[0], (record[1] if record[0] in ('cable', 'usbmux') and len(record) > 1 else None) def link_kind(mode: str | None = None) -> str: @@ -105,7 +105,7 @@ def link_kind(mode: str | None = None) -> str: the caller read it, stands in only until the owner has said: it may have moved and be waiting for the car to park. Without either, 'usb'.""" kind, _ = link_state() - return kind or ('cable' if mode == 'ios' else 'usb') + return kind or ('usbmux' if mode == 'usbmux' else ('cable' if mode == 'ios' else 'usb')) def link_peer() -> str | None: @@ -254,6 +254,12 @@ def build_error() -> str | None: return _status_error(GADGET_STATUS) +def usbmux_active() -> bool: + """True when the comma is actively hosting the iPhone via usbmuxd.""" + from jetlink.comma import usbmux_host + return usbmux_host.usbmux_active() + + def gadget_error() -> str | None: """Why the link is unavailable, if it is: the gadget could not be built, or it was and nothing can borrow it from the owner. @@ -261,6 +267,9 @@ def gadget_error() -> str | None: Both happen in the owner, nowhere a user would look, so this is how the reason reaches the panels. """ + from jetlink.comma import usbmux_host + if usbmux_host.usbmux_status() is not None: + return _status_error(usbmux_host.USBMUX_STATUS) or _status_error(LENDER_STATUS) return build_error() or _status_error(LENDER_STATUS) @@ -297,7 +306,11 @@ def udc_state() -> str | None: def host_attached() -> bool: - """Has a host (the Jetson) enumerated and configured us?""" + """Has a host (the Jetson) enumerated and configured us, or is an Apple + device attached while running in USB Host (usbmuxd) mode?""" + if usbmux_active(): + from jetlink.comma import usbmux_host + return usbmux_host.apple_attached() return udc_state() == "configured" @@ -344,7 +357,7 @@ def wait_for_host(timeout: float, bounce=None, should_stop=None, report=None, mo it is the dial that proved it is there. `mode` is the link setting, for before the owner has recorded which gadget it built (link_kind). """ - if link_kind(mode) == 'cable': + if link_kind(mode) in ('cable', 'usbmux'): return True deadline = time.monotonic() + timeout stalled_since = None @@ -408,7 +421,7 @@ def net_up() -> bool: def link_configured() -> bool: - """Can we even attempt a link? The gadget exists. + """Can we even attempt a link? The gadget exists, or usbmuxd host mode is active. Not host_attached(): the UDC only binds when something opens ep0, and nothing opens ep0 unless the link looks usable. Waiting for a host deadlocks. @@ -416,6 +429,10 @@ def link_configured() -> bool: The cable too: a phone is on the gadget's own network interface, which exists only while ep0 is held. """ + from jetlink.comma import usbmux_host + mux_status = usbmux_host.usbmux_status() + if mux_status is not None: + return mux_status == 'ok' and usbmux_host.USBMUXD_SOCKET.exists() if build_error() is not None: return False try: diff --git a/jetlink/comma/lending.py b/jetlink/comma/lending.py index 1b7f5dce..3b11a6dd 100644 --- a/jetlink/comma/lending.py +++ b/jetlink/comma/lending.py @@ -105,6 +105,8 @@ def __init__(self, conn: socket.socket, buf: bytearray, mount: str, udc: str, na # a phone is the host: the link is its dial, taken by accept, and the # endpoint files are left alone. The owner's answer says (_take) self.cable = False + # on usbmuxd the comma connects to 127.0.0.1:5599 over /var/run/usbmuxd + self.usbmux = False # the cable listener, bound on the first accept and kept for the loan self._srv: socket.socket | None = None self.bound: tuple | None = None @@ -210,6 +212,7 @@ def _take(self, timeout: float) -> dict | None: return None self.mount, self.udc = str(reply['mount']), str(reply['udc']) self.cable = bool(reply.get('cable')) + self.usbmux = bool(reply.get('usbmux')) return reply def close(self) -> None: @@ -262,6 +265,8 @@ def _ask(conn: socket.socket, buf: bytearray, name: str, deadline: float) -> dic def _what_was_lent(reply: dict) -> str: + if reply.get('usbmux'): + return "the usbmux link" if reply.get('cable'): return "the cable link" return f"the gadget (udc {reply.get('udc')})" @@ -466,10 +471,12 @@ class Lender: def __init__(self, lendable: Callable[[], bool], bounce: Callable[[], bool], path: Path | None = None, cable: Callable[[], bool] | None = None, - vacate: Callable[[], None] | None = None, server: Callable[[str, dict], None] | None = None): + vacate: Callable[[], None] | None = None, server: Callable[[str, dict], None] | None = None, + usbmux: Callable[[], bool] | None = None): self._lendable = lendable self._bounce = bounce self._cable = cable or (lambda: False) + self._usbmux = usbmux or (lambda: False) self._vacate = vacate or (lambda: None) self._server = server # what this borrower was last told it has, so each change is logged once @@ -561,8 +568,8 @@ def _serve(self) -> None: finally: conn.close() if self._lent.is_set(): - gadget.log.warning("jetlink: %s handed the %s back", self.borrower or 'the borrower', - 'cable link' if self._told == 'cable' else 'gadget') + kind = 'usbmux link' if self._told == 'usbmux' else ('cable link' if self._told == 'cable' else 'gadget') + gadget.log.warning("jetlink: %s handed the %s back", self.borrower or 'the borrower', kind) # the owner's step listens for the phone again, now that the port is free self._told = '' self._lent.clear() @@ -593,6 +600,10 @@ def _answer(self, conn: socket.socket, msg: dict) -> None: if op == 'borrow': self.borrower = str(msg.get('name') or 'a borrower') self._lent.set() + if self._usbmux(): + self._tell('usbmux', "jetlink: lending the usbmux link to %s", self.borrower) + _send(conn, {'ok': True, 'usbmux': True, 'cable': False, 'udc': '', 'mount': ''}) + return if self._cable(): # a phone: the link is its dial, which the borrower listens for # itself; the owner's listener and the dial it holds go first, so the diff --git a/jetlink/comma/owner.py b/jetlink/comma/owner.py index fe47d830..a8c1c6b5 100644 --- a/jetlink/comma/owner.py +++ b/jetlink/comma/owner.py @@ -51,7 +51,7 @@ from collections.abc import Mapping, Sequence from pathlib import Path -from jetlink.comma import gadget, lending, port, root +from jetlink.comma import gadget, lending, port, root, usbmux_host POLL = 0.5 # how long the gadget is held after the last thing that wanted it. The server @@ -232,8 +232,18 @@ def __init__(self, worker: Sequence[str], cwd: str | None = None, env: Mapping[s self.born: float | None = None self.port = port.Port(chestnut_ids) self.cable = lending.CableListener() + self.handoff = usbmux_host.HandoffListener() + self.pairer = usbmux_host.Pairer() + self.usbmux_mode = False + self.usbmux_ready = False + self.usbmux_error: str | None = None + self.next_usbmux_setup = 0.0 + self.next_usbmux_role = 0.0 + self.usbmux_role_tries = 0 + self.next_usbmux_probe = 0.0 + self.usbmux_app_seen = False self.lender = lending.Lender(self.lendable, self.bounce_gadget, cable=self.cable_mode, vacate=self.cable.vacate, - server=self.note_server) + server=self.note_server, usbmux=self.usbmux_lend_mode) # -- the gadget ----------------------------------------------------------- @@ -243,6 +253,7 @@ def close_link(self) -> None: transport, self.transport = self.transport, None # the phone's network interface goes with the gadget, and its dial with it self.cable.close() + self.handoff.close() self.net_ready = False self.publish() if transport is not None: @@ -262,11 +273,63 @@ def cable_mode(self) -> bool: not the setting: a setting moved while somebody borrowed waits for them.""" return bool(self.built_ios) + def usbmux_lend_mode(self) -> bool: + """True when the comma is hosting the iPhone over usbmuxd instead of a gadget.""" + return bool(self.usbmux_mode and self.usbmux_ready) + + def enter_usbmux_mode(self, persist: bool = True) -> bool: + """Tear down CDC-NCM gadget and switch comma AUX port into USB Host (usbmuxd) mode.""" + self.stop_worker() + self.close_link() + self.built_ios = None + self.attached = False + self.configured = False + self.dialed = False + self.usbmux_mode = True + self.usbmux_app_seen = False + self.usbmux_role_tries = 0 + self.next_usbmux_role = 0.0 + self.next_usbmux_probe = 0.0 + self._peer = None + if persist: + usbmux_host.save_transport_mode('usbmux') + ok, err = usbmux_host.start_host_mode() + self.usbmux_ready = ok + self.usbmux_error = err + self.next_usbmux_setup = time.monotonic() + (0.0 if ok else RECONNECT_BACKOFF) + gadget.note_link('usbmux') + if self.tuned is None: + root.run('vm', 'apply') + self.tuned = 'usbmux' + return ok + + def exit_usbmux_mode(self, clear_persisted: bool = True) -> None: + """Stop usbmuxd host mode and return to default CDC-NCM / USB gadget mode.""" + self.stop_worker() + usbmux_host.stop_host_mode() + if clear_persisted: + usbmux_host.save_transport_mode('ncm') + self.usbmux_mode = False + self.usbmux_ready = False + self.usbmux_error = None + self.usbmux_app_seen = False + self.usbmux_role_tries = 0 + self.attached = False + self.configured = False + self.dialed = False + self._peer = None + self.built_ios = None + self.tuned = None + self.port._reset() + gadget.clear_link() + def publish(self, peer: str | None = None) -> None: """What the gadget is, for every other process's link_kind, and on the cable which phone dialed in.""" self._peer = peer - if self.built_ios is None: + if self.usbmux_mode: + gadget.note_link('usbmux', peer) + elif self.built_ios is None: gadget.clear_link() else: gadget.note_link('cable' if self.built_ios else 'usb', peer) @@ -538,6 +601,29 @@ def status_record(self) -> dict: """What every other process reads instead of the gadget's files one by one (jetlink.openpilot.status), presence and its hold worked out once, here.""" now = time.monotonic() + if self.usbmux_mode: + dev = usbmux_host.apple_device() + configured = dev is not None + if configured: + self.last_configured = now + present = configured or now - self.last_configured < gadget.PRESENCE_HOLD + return { + 'pid': os.getpid(), + 'at': now, + 'mode': self.mode, + 'link': 'usbmux', + 'peer': self._peer, + 'error': self.backing_off or self.usbmux_error or gadget.gadget_error(), + 'net': None, + 'dormant': False, + 'udc': 'host', + 'speed': dev['speed'] if dev else None, + 'present': present, + 'server': self.server, + 'worker': self.worker is not None and self.worker.poll() is None, + 'unfinished': self.unfinished, + 'stopping': self.stop, + } state = gadget.udc_state() configured = state == 'configured' if configured: @@ -631,6 +717,8 @@ def step(self) -> None: # no gadget, no run, no tuning, as with the link off. The owner stays up # for its heartbeat, which the panels and the offroad alert read if not self.settings.holds_port(mode): + if self.usbmux_mode: + self.exit_usbmux_mode(clear_persisted=(mode == 'off')) if self.transport is not None: gadget.log.warning("jetlink: link set to %s, releasing it", mode) self.close_link() @@ -638,9 +726,22 @@ def step(self) -> None: self.wake() self.release_tuning() return + if self.usbmux_mode and mode != 'ios': + self.exit_usbmux_mode(clear_persisted=False) # before the gadget: a host is never drawn from while the link comes up self.steer_draw(True) + if self.usbmux_mode: + self.usbmux_step() + self.released = None + if self.tuned != 'usbmux': + if self.tuned is None: + root.run('vm', 'apply') + self.tuned = 'usbmux' + return self.link_step(mode == 'ios') + if self.usbmux_mode: + self.released = None + return self.released = None if self.tuned != mode: # jetlink-root.sh vm: the recording VM tuning the gadget's reads need; @@ -757,6 +858,8 @@ def link_step(self, ios: bool) -> None: return self.attached = gadget.host_attached() self.watch_the_port() + if self.usbmux_mode: + return self.ensure_steered(offroad) # before the worker gate: hardwared waits 25 s for this and a build in @@ -842,6 +945,13 @@ def watch_the_port(self) -> None: if not self.built_ios: return self.ensure_net() + if self.net_ready and self.transport is not None: + if not self.handoff.listening: + self.handoff.open() + if self.handoff.poll(): + gadget.log.warning("jetlink: iPhone requested Full Frame Experimental Network (usbmuxd); switching to USB Host mode") + self.enter_usbmux_mode(persist=True) + return if self.lender.lent: return # the borrower listens for the phone; the port is its if self.transport is not None and self.net_ready and not self.cable.listening: @@ -941,6 +1051,73 @@ def adopt(self) -> None: except (OSError, ValueError): heard = None self.server = heard if isinstance(heard, dict) else None + if self.settings.mode() == 'ios' and usbmux_host.saved_transport_mode() == 'usbmux' and usbmux_host.has_usbmuxd(): + gadget.log.warning("jetlink: restoring saved Full Frame Experimental Network (usbmuxd) mode") + self.enter_usbmux_mode(persist=False) + + def usbmux_step(self) -> None: + """One cycle in USB Host-mode (usbmuxd) for Full Frame Experimental Network.""" + now = time.monotonic() + self.ensure_lender() + if (not self.usbmux_ready or not usbmux_host.usbmuxd_running()) and now >= self.next_usbmux_setup: + ok, err = usbmux_host.start_host_mode() + self.usbmux_ready = ok + self.usbmux_error = err + self.next_usbmux_setup = now + (0.0 if ok else RECONNECT_BACKOFF) + + dev = usbmux_host.apple_device() + self.attached = dev is not None + if dev is None: + self.usbmux_app_seen = False + self.pairer.tick(False, None) + if self._peer is not None: + self.publish() + pr = port.power_role() + if pr in port.ATTACHED and port.data_role() != 'dfp': + if self.usbmux_role_tries < 3 and now >= self.next_usbmux_role: + self.usbmux_role_tries += 1 + self.next_usbmux_role = now + 4.0 + usbmux_host.ensure_host_role() + elif pr not in port.ATTACHED: + self.usbmux_role_tries = 0 + else: + if not self.configured: + speed = dev.get('speed') or 'unknown speed' + gadget.log.warning("jetlink: Apple device connected over USB Host mode at %s", speed) + if speed == 'high-speed': + gadget.log.warning("jetlink: Apple device negotiated USB 2.0 (480 Mbps); check 10 Gbps USB 3 hub/cable") + self.usbmux_role_tries = 0 + serial = dev.get('serial') + paired = self.pairer.tick(True, serial) + peer = (serial or 'iphone')[:12] + if self._peer != peer: + self.publish(peer) + if paired and not self.lender.lent and not self.worker_running() and now >= self.next_usbmux_probe: + self.next_usbmux_probe = now + 2.0 + if usbmux_host.probe_ncm_request(): + gadget.log.warning("jetlink: iPhone requested default CDC-NCM mode; leaving usbmux mode") + self.exit_usbmux_mode(clear_persisted=True) + return + if not self.usbmux_app_seen: + ready_udid = usbmux_host.probe_server_ready() + if ready_udid is not None: + self.publish(ready_udid[:12]) + self.had_host = True + self.idle_since = now + self.usbmux_app_seen = True + self.dialed = True + self.configured = self.attached + + offroad = self.settings.offroad() + if not offroad: + self.stop_worker() + if self.lender.lent or not offroad or self.worker_running(): + return + if time.monotonic() < max(self.next_attempt, self.lease_settled): + return + why = self.wanted() + if why is not None and self.usbmux_ready and self.attached and self.pairer.paired and self.usbmux_app_seen: + self.spawn_worker(why) def sit_out(self, until: float, died: int) -> None: """A crash loop's backoff: hold nothing, not the gadget, the lender or @@ -1036,6 +1213,9 @@ def hold_the_gadget(self) -> None: else: gadget.log.warning("jetlink: a host is still on the USB-C port; the comma draws nothing from it " "until a reboot") + self.handoff.close() + if self.usbmux_mode and not self.link_wanted(): + usbmux_host.stop_host_mode() self.lender.stop() # about this process's lender; with no owner there is nothing to borrow # anyway, and a chestnut may be why it stopped diff --git a/jetlink/comma/usbmux_host.py b/jetlink/comma/usbmux_host.py new file mode 100644 index 00000000..54e7697e --- /dev/null +++ b/jetlink/comma/usbmux_host.py @@ -0,0 +1,608 @@ +""" +Copyright (c) 2026-, Zeph Leggett. + +This file is part of jetlink and is licensed under the MIT License. +See the LICENSE file in the root directory for more details. + +USB Host-mode (usbmuxd) management, automatic iOS trust pairing, and the +sideband CDC-NCM <-> usbmuxd handoff on the comma. + +Kept strictly lightweight (Python standard library + jetlink.comma): jetlinkd +imports this at startup and keeps its resident memory small. +""" +from __future__ import annotations + +import errno +import os +import shlex +import shutil +import socket +import subprocess +import threading +import time +from collections.abc import Callable +from pathlib import Path + +from jetlink.comma import gadget, root +from jetlink.transport.base import LinkError, USB_MEDIA +from jetlink.transport.tcp import CABLE_ADDRESS, DEFAULT_PORT + +HANDOFF_PORT = 5600 +APPLE_VID = '05ac' + +BIN_DIR = Path('/data/jetlink/bin') +LOCKDOWN_DIR = Path('/data/jetlink/lockdown') +VAR_LOCKDOWN = Path('/var/lib/lockdown') +TRANSPORT_MODE_PATH = Path('/data/jetlink/transport_mode') +TRANSPORT_MODE_FALLBACK = Path('/dev/shm/jetlink-transport-mode') +USBMUX_STATUS = Path('/dev/shm/jetlink-usbmux') +USBMUXD_PID = Path('/dev/shm/jetlink-usbmuxd.pid') +USBMUXD_SOCKET = Path('/var/run/usbmuxd') +USBMUXD_LOG = Path('/dev/shm/jetlink-usbmuxd.log') + +USB_DEVICES = Path('/sys/bus/usb/devices') +USBPD = Path('/sys/class/usbpd/usbpd0') +DUAL_ROLE = Path('/sys/class/dual_role_usb/otg_default') +UDC_GLUE = Path('/sys/devices/platform/soc/a600000.ssusb') + +SPEED_MBPS_TO_UDC = { + '10000': 'super-speed-plus', + '5000': 'super-speed', + '480': 'high-speed', + '12': 'full-speed', + '1.5': 'low-speed', +} + +HANDOFF_BACKOFF = 5.0 +PAIR_RETRY_S = 3.0 +HOST_ROLE_TIMEOUT = 2.0 + + +def _read_text(path: Path) -> str: + try: + return path.read_text().strip() + except OSError: + return '' + + +def _write_text(path: Path, text: str | None) -> bool: + try: + if text is None: + path.unlink(missing_ok=True) + else: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + return True + except OSError: + return False + + +def _sudo_sh(command: str, *, timeout: float = 5.0) -> bool: + """Run a root shell command via sudo -n on AGNOS (no-op off AGNOS).""" + if not root.AGNOS: + return False + try: + result = subprocess.run( + ['sudo', '-n', 'sh', '-c', command], + stdout=subprocess.DEVNULL, + stderr=subprocess.PIPE, + timeout=timeout, + text=True, + errors='replace', + ) + if result.returncode == 0: + return True + lines = (result.stderr or '').strip().splitlines() + gadget.log.warning("jetlink: root command failed (%s): %s", command.split()[0], lines[-1] if lines else result.returncode) + return False + except (OSError, subprocess.TimeoutExpired) as e: + gadget.log.warning("jetlink: root command failed (%s): %s", command.split()[0], e) + return False + + +def _sudo_write(path: Path, value: str, *, timeout: float = HOST_ROLE_TIMEOUT) -> bool: + if not root.AGNOS: + return False + return _sudo_sh(f"printf '%s\\n' {shlex.quote(value)} > {shlex.quote(str(path))}", timeout=timeout) + + +def saved_transport_mode() -> str: + """Persisted iOS transport preference across comma reboots ('usbmux' or 'ncm').""" + for candidate in (TRANSPORT_MODE_PATH, TRANSPORT_MODE_FALLBACK): + mode = _read_text(candidate).lower() + if mode == 'usbmux': + return 'usbmux' + return 'ncm' + + +def save_transport_mode(mode: str) -> None: + """Persist 'usbmux' across reboots, or clear back to default CDC-NCM ('ncm').""" + if mode == 'usbmux': + if not _write_text(TRANSPORT_MODE_PATH, 'usbmux\n'): + _write_text(TRANSPORT_MODE_FALLBACK, 'usbmux\n') + else: + _write_text(TRANSPORT_MODE_FALLBACK, None) + return + _write_text(TRANSPORT_MODE_PATH, None) + _write_text(TRANSPORT_MODE_FALLBACK, None) + + +def usbmux_status() -> str | None: + """Raw text of USBMUX_STATUS, or None when usbmux mode is inactive.""" + text = _read_text(USBMUX_STATUS) + return text or None + + +def set_usbmux_status(text: str | None) -> None: + """Write or clear USBMUX_STATUS in /dev/shm.""" + try: + if text is None: + USBMUX_STATUS.unlink(missing_ok=True) + else: + USBMUX_STATUS.write_text(text) + except OSError: + pass + + +def _bin_path_env() -> str: + existing = os.environ.get('PATH', '') + if BIN_DIR.is_dir(): + return f"{BIN_DIR}:{existing}" if existing else str(BIN_DIR) + return existing + + +def find_binary(name: str) -> str | None: + """Locate `name` under /data/jetlink/bin first, then standard PATH.""" + candidate = BIN_DIR / name + if candidate.is_file() and os.access(candidate, os.X_OK): + return str(candidate) + return shutil.which(name, path=_bin_path_env()) + + +def has_usbmuxd() -> bool: + """Whether the comma has a usable usbmuxd binary.""" + return find_binary('usbmuxd') is not None + + +def _socket_connectable(path: Path) -> bool: + if not path.exists(): + return False + sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + try: + sock.settimeout(0.3) + sock.connect(str(path)) + return True + except OSError: + return False + finally: + sock.close() + + +def usbmuxd_running() -> bool: + """True when usbmuxd has a live PID or an accepting /var/run/usbmuxd socket.""" + pid_text = _read_text(USBMUXD_PID) + if pid_text.isdigit() and gadget.pid_alive(int(pid_text)): + return USBMUXD_SOCKET.exists() + return _socket_connectable(USBMUXD_SOCKET) + + +def usbmux_active() -> bool: + """True while comma usbmuxd host mode is up and ready.""" + return usbmux_status() == 'ok' and USBMUXD_SOCKET.exists() + + +def _map_speed_name(raw_speed: str) -> str | None: + if not raw_speed: + return None + if raw_speed in SPEED_MBPS_TO_UDC: + return SPEED_MBPS_TO_UDC[raw_speed] + try: + mbps = float(raw_speed) + except ValueError: + return raw_speed if raw_speed in USB_MEDIA else None + key = str(int(mbps)) if mbps.is_integer() else str(mbps) + if key in SPEED_MBPS_TO_UDC: + return SPEED_MBPS_TO_UDC[key] + if mbps >= 10000.0: + return 'super-speed-plus' + if mbps >= 5000.0: + return 'super-speed' + if mbps >= 480.0: + return 'high-speed' + if mbps > 0.0: + return 'full-speed' + return None + + +def apple_device(usb_devices: Path | None = None) -> dict[str, str | None] | None: + """Inspect sysfs for an attached Apple USB device (VID 05ac).""" + root_dir = USB_DEVICES if usb_devices is None else usb_devices + try: + entries = sorted(root_dir.iterdir()) + except OSError: + return None + for entry in entries: + if ':' in entry.name or not entry.is_dir(): + continue + if _read_text(entry / 'idVendor').lower() != APPLE_VID: + continue + return { + 'name': entry.name, + 'product_id': _read_text(entry / 'idProduct').lower() or None, + 'speed': _map_speed_name(_read_text(entry / 'speed')), + 'raw_speed': _read_text(entry / 'speed') or None, + 'serial': _read_text(entry / 'serial') or None, + 'product': _read_text(entry / 'product') or None, + } + return None + + +def apple_attached(usb_devices: Path | None = None) -> bool: + return apple_device(usb_devices) is not None + + +def apple_usb_speed(usb_devices: Path | None = None) -> str | None: + dev = apple_device(usb_devices) + return None if dev is None else dev.get('speed') + + +def ensure_host_role() -> bool: + """Switch the comma's USB-C AUX port to USB Host (dfp) + xHCI host controller.""" + cur_dr = _read_text(USBPD / 'current_dr') + glue_mode_path = UDC_GLUE / 'mode' + glue_mode = _read_text(glue_mode_path) + if cur_dr == 'dfp' and (not glue_mode_path.exists() or glue_mode == 'host'): + return True + + if not root.AGNOS: + return False + + root.run('port', 'off', timeout=root.PORT_TIMEOUT) + + if _read_text(USBPD / 'current_dr') != 'dfp' and (DUAL_ROLE / 'data_role').exists(): + _sudo_write(DUAL_ROLE / 'data_role', 'host') + time.sleep(0.2) + + if _read_text(USBPD / 'current_dr') != 'dfp' and _read_text(USBPD / 'current_pr') == 'sink': + # Some USB-C phones stay DFP while acting as Sink; ask for Source power role first, then DR_Swap. + if root.run('port', 'source', timeout=root.SWAP_TIMEOUT): + time.sleep(0.2) + if _read_text(USBPD / 'current_dr') != 'dfp' and (DUAL_ROLE / 'data_role').exists(): + _sudo_write(DUAL_ROLE / 'data_role', 'host') + time.sleep(0.2) + + if _read_text(USBPD / 'current_dr') != 'dfp' and _read_text(USBPD / 'current_pr') == 'source': + root.run('port', 'reset', timeout=root.PORT_TIMEOUT) + + if glue_mode_path.exists() and _read_text(glue_mode_path) != 'host': + _sudo_write(glue_mode_path, 'host') + + return _read_text(USBPD / 'current_dr') == 'dfp' or apple_attached() + + +def ensure_lockdown_dir() -> bool: + """Ensure /var/lib/lockdown maps to persistent /data/jetlink/lockdown on AGNOS.""" + try: + LOCKDOWN_DIR.mkdir(parents=True, exist_ok=True) + except OSError: + if not _sudo_sh(f"mkdir -p {shlex.quote(str(LOCKDOWN_DIR))} && chmod 0755 {shlex.quote(str(LOCKDOWN_DIR))}"): + return False + + try: + if VAR_LOCKDOWN.is_symlink() and VAR_LOCKDOWN.resolve() == LOCKDOWN_DIR.resolve(): + return True + except OSError: + pass + + if not root.AGNOS: + return False + + lock = shlex.quote(str(LOCKDOWN_DIR)) + var_lock = shlex.quote(str(VAR_LOCKDOWN)) + cmd = ( + f"mkdir -p {lock} && chmod 0755 {lock}; " + f"if [ -d {var_lock} ] && [ ! -L {var_lock} ]; then " + f"cp -pn {var_lock}/*.plist {lock}/ 2>/dev/null || true; " + f"(rm -rf {var_lock} && ln -s {lock} {var_lock}) || " + f"(mountpoint -q {var_lock} || mount --bind {lock} {var_lock}); " + f"else ln -sfn {lock} {var_lock} || (mkdir -p {var_lock} && mount --bind {lock} {var_lock}); fi" + ) + return _sudo_sh(cmd) + + +def start_host_mode() -> tuple[bool, str | None]: + """Tear down any USB gadget, put comma AUX port in host mode, and start usbmuxd.""" + usbmuxd_bin = find_binary('usbmuxd') + if usbmuxd_bin is None: + err = 'usbmuxd not installed (run scripts/comma/jetlink-usbmux.sh install)' + set_usbmux_status(f'error: {err}') + return False, err + + if root.AGNOS: + if (gadget.GADGET_PATH).exists(): + root.run('teardown') + root.run('udc', 'restore', timeout=root.PORT_TIMEOUT) + root.run('udc', 'stop', timeout=root.PORT_TIMEOUT) + root.run('port', 'off', timeout=root.PORT_TIMEOUT) + ensure_host_role() + ensure_lockdown_dir() + + if not usbmuxd_running(): + if not root.AGNOS: + err = 'usbmuxd is not running' + set_usbmux_status(f'error: {err}') + return False, err + launch_cmd = ( + f"PATH={shlex.quote(_bin_path_env())} nohup {shlex.quote(usbmuxd_bin)} -f -u -U root " + f">{shlex.quote(str(USBMUXD_LOG))} 2>&1 & echo $! > {shlex.quote(str(USBMUXD_PID))}" + ) + if not _sudo_sh(launch_cmd, timeout=5.0): + err = 'could not start usbmuxd' + set_usbmux_status(f'error: {err}') + return False, err + deadline = time.monotonic() + 3.0 + while time.monotonic() < deadline: + if USBMUXD_SOCKET.exists(): + break + time.sleep(0.1) + if not USBMUXD_SOCKET.exists(): + err = f'timed out waiting for {USBMUXD_SOCKET}' + set_usbmux_status(f'error: {err}') + return False, err + + set_usbmux_status('ok') + gadget.log.warning("jetlink: USB Host mode ready (usbmuxd at %s)", USBMUXD_SOCKET) + return True, None + + +def stop_host_mode() -> None: + """Stop jetlink-managed usbmuxd and clear its transient state.""" + pid_text = _read_text(USBMUXD_PID) + if pid_text.isdigit(): + pid = int(pid_text) + if gadget.pid_alive(pid): + _sudo_sh(f"kill {pid} 2>/dev/null || true", timeout=2.0) + try: + USBMUXD_PID.unlink(missing_ok=True) + except OSError: + pass + set_usbmux_status(None) + + +class Pairer: + """Non-blocking idevicepair helper that automatically triggers 'Trust This Computer'.""" + + def __init__(self, retry_after: float = PAIR_RETRY_S): + self.retry_after = retry_after + self.paired = False + self.status = '' + self._serial: str | None = None + self._thread: threading.Thread | None = None + self._next_try = 0.0 + self._warned_trust = False + self._warned_missing = False + + def tick(self, attached: bool, serial: str | None) -> bool: + """Ensure the attached Apple device is paired, never blocking the caller's loop.""" + if not attached: + self.paired = False + self.status = '' + self._serial = None + self._warned_trust = False + return False + if serial != self._serial: + self.paired = False + self.status = '' + self._serial = serial + self._warned_trust = False + self._next_try = 0.0 + if self.paired: + return True + if self._thread is not None and self._thread.is_alive(): + return False + now = time.monotonic() + if now < self._next_try: + return False + self._next_try = now + self.retry_after + idevicepair = find_binary('idevicepair') + if idevicepair is None: + if not self._warned_missing: + self._warned_missing = True + gadget.log.warning("jetlink: idevicepair not found; skipping automatic Trust Computer prompt") + self.paired = True + self.status = 'no_tool' + return True + + self._thread = threading.Thread( + target=self._run_pair, + args=(idevicepair, serial), + name='jetlink_usbmux_pair', + daemon=True, + ) + self._thread.start() + return False + + def _run_pair(self, idevicepair: str, serial: str | None) -> None: + if serial != self._serial: + return + env = {**os.environ, 'PATH': _bin_path_env()} + udid_args = ['--udid', serial] if serial else [] + try: + res = subprocess.run( + [idevicepair, *udid_args, 'validate'], + env=env, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + errors='replace', + timeout=3.0, + ) + if res.returncode == 0: + if serial == self._serial: + self.paired = True + self.status = 'paired' + self._warned_trust = False + gadget.log.warning("jetlink: iPhone %s pairing trust verified", (serial or '')[:12] or 'device') + return + pair_res = subprocess.run( + [idevicepair, *udid_args, 'pair'], + env=env, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + errors='replace', + timeout=5.0, + ) + if pair_res.returncode == 0: + if serial == self._serial: + self.paired = True + self.status = 'paired' + self._warned_trust = False + gadget.log.warning("jetlink: iPhone %s paired and trusted", (serial or '')[:12] or 'device') + return + out = (pair_res.stdout or '').strip().splitlines() + detail = out[-1] if out else f'exit {pair_res.returncode}' + if serial == self._serial: + self.status = 'waiting_trust' + if not self._warned_trust: + self._warned_trust = True + gadget.log.warning( + 'jetlink: waiting for iPhone Trust confirmation (%s) — unlock iPhone and tap "Trust This Computer"', + detail, + ) + except (OSError, subprocess.TimeoutExpired) as e: + if serial == self._serial: + self.status = 'waiting_trust' + if not self._warned_trust: + self._warned_trust = True + gadget.log.warning("jetlink: idevicepair error: %s", e) + + +class HandoffListener: + """Sideband listener on 192.168.60.1:5600 that lets the iPhone request usbmuxd.""" + + def __init__(self, addr: tuple[str, int] = (CABLE_ADDRESS, HANDOFF_PORT), + can_usbmux: Callable[[], bool] | None = None): + self.addr = addr + self.can_usbmux = can_usbmux or has_usbmuxd + self._srv: socket.socket | None = None + self.bound: tuple[str, int] | None = None + self.next_open = 0.0 + self._last_error = '' + + @property + def listening(self) -> bool: + return self._srv is not None + + def open(self) -> bool: + if self._srv is not None: + return True + now = time.monotonic() + if now < self.next_open: + return False + self.next_open = now + HANDOFF_BACKOFF + srv = None + try: + srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + srv.bind(self.addr) + srv.listen(4) + srv.setblocking(False) + except OSError as e: + if srv is not None: + srv.close() + why = 'usb0 has no address yet' if e.errno == errno.EADDRNOTAVAIL else str(e) + if why != self._last_error: + self._last_error = why + gadget.log.info("jetlink: handoff listener waiting on %s:%d (%s)", self.addr[0], self.addr[1], why) + return False + self._srv = srv + self.bound = srv.getsockname()[:2] + self._last_error = '' + return True + + def poll(self) -> bool: + """Accept waiting handoff requests. Returns True if iPhone asked to switch to usbmux.""" + if self._srv is None: + return False + switch = False + while True: + try: + conn, _ = self._srv.accept() + except (BlockingIOError, InterruptedError, OSError): + break + try: + conn.settimeout(0.5) + cmd = conn.recv(64).decode('utf-8', errors='replace').strip() + if cmd == 'USBMUX': + if self.can_usbmux(): + conn.sendall(b'OK\n') + switch = True + else: + conn.sendall(b'ERR missing_usbmuxd\n') + else: + conn.sendall(b'ERR unknown_command\n') + except OSError: + pass + finally: + try: + conn.close() + except OSError: + pass + return switch + + def close(self) -> None: + srv, self._srv = self._srv, None + self.bound = None + if srv is not None: + try: + srv.close() + except OSError: + pass + + +def probe_ncm_request(*, socket_path: str | None = None, port: int = HANDOFF_PORT, timeout: float = 0.5) -> bool: + """Check via usbmuxd port 5600 whether the iOS app toggled back to default CDC-NCM.""" + from jetlink.comma.usbmux_transport import UsbmuxClient + + client = UsbmuxClient(socket_path=socket_path or str(USBMUXD_SOCKET), timeout=timeout) + sock = None + try: + devices = client.list_devices(usb_only=True) + if not devices: + return False + sock = client.connect_raw(devices[0].device_id, port=port, timeout=timeout) + sock.settimeout(timeout) + data = sock.recv(32) + return data.decode('utf-8', errors='replace').strip() == 'NCM' + except (LinkError, OSError): + return False + finally: + if sock is not None: + try: + sock.close() + except OSError: + pass + + +def probe_server_ready(*, socket_path: str | None = None, port: int = DEFAULT_PORT, timeout: float = 0.5) -> str | None: + """Check if the iPhone Jetlink server is accepting usbmux connections on port 5599; returns UDID or None.""" + from jetlink.comma.usbmux_transport import UsbmuxClient + + client = UsbmuxClient(socket_path=socket_path or str(USBMUXD_SOCKET), timeout=timeout) + sock = None + try: + devices = client.list_devices(usb_only=True) + if not devices: + return None + dev = devices[0] + sock = client.connect_raw(dev.device_id, port=port, timeout=timeout) + return dev.serial or 'iphone' + except (LinkError, OSError): + return None + finally: + if sock is not None: + try: + sock.close() + except OSError: + pass diff --git a/jetlink/openpilot/link.py b/jetlink/openpilot/link.py index 20586f4e..a7649b69 100644 --- a/jetlink/openpilot/link.py +++ b/jetlink/openpilot/link.py @@ -77,6 +77,14 @@ def connect(log, loan, deadline: float | None = None, name: str | None = None, w from jetlink.client import FRAME_TIMEOUT, JetlinkClient from jetlink.comma import lending deadline = FRAME_TIMEOUT if deadline is None else deadline + if getattr(loan, 'usbmux', False): + client = JetlinkClient.open_usbmux(port=gadget.CABLE_ADDR[1], + timeout=lending.BORROW_TIMEOUT if wait is None else wait, + deadline=deadline, name=name) + peer = getattr(client.t, 'udid', None) or 'iphone' + gadget.note_link('usbmux', peer[:12]) + log.warning("jetlink: connected to iPhone %s over usbmuxd", peer[:12]) + return client if loan.cable: sock = loan.accept(lending.BORROW_TIMEOUT if wait is None else wait) peer = sock.getpeername()[0] diff --git a/jetlink/openpilot/status.py b/jetlink/openpilot/status.py index 9ebf9233..38ee781f 100644 --- a/jetlink/openpilot/status.py +++ b/jetlink/openpilot/status.py @@ -170,15 +170,17 @@ def link_transport(mode: str | None = None, live: dict | None = None) -> str: if mode == 'wifi': return "Wi-Fi ({}:{})".format(*WIFI_DIAL) try: - if live is not None and live.get('link') in ('usb', 'cable'): + if live is not None and live.get('link') in ('usb', 'cable', 'usbmux'): kind, peer = live['link'], live.get('peer') else: kind, peer = gadget.link_state() kind = kind or gadget.link_kind(mode) - if kind == 'cable' and not peer: + if kind in ('cable', 'usbmux') and not peer: # the owner records the phone while it holds the dial; a borrower that # took the dial itself noted it in the link record peer = gadget.link_state()[1] + if kind == 'usbmux': + return f"iOS over usbmux ({peer})" if peer else "iOS over usbmux" if kind == 'cable': return f"iOS over USB ({peer})" if peer else "iOS over USB" except Exception: diff --git a/scripts/comma/jetlink-usbmux.sh b/scripts/comma/jetlink-usbmux.sh index 211549b4..956ec5e5 100755 --- a/scripts/comma/jetlink-usbmux.sh +++ b/scripts/comma/jetlink-usbmux.sh @@ -9,6 +9,7 @@ # switching to host-mode usbmuxd. # # Usage: +# sudo scripts/comma/jetlink-usbmux.sh install [--remount-rw] # sudo scripts/comma/jetlink-usbmux.sh setup [--install] [--mode3] # scripts/comma/jetlink-usbmux.sh speed # scripts/comma/jetlink-usbmux.sh pair @@ -45,7 +46,7 @@ if [[ -d "$BIN_DIR" ]]; then fi usage() { - echo "usage: $0 setup [--install] [--mode3] | speed | pair | preflight | status | stop" >&2 + echo "usage: $0 install [--remount-rw] | setup [--install] [--mode3] | speed | pair | preflight | status | stop" >&2 exit 2 } @@ -333,6 +334,29 @@ cmd_preflight() { fi } +cmd_install() { + local remount_rw=0 did_remount=0 arg + for arg in "$@"; do + case "$arg" in + --remount-rw) remount_rw=1 ;; + *) usage ;; + esac + done + require_root install + if [[ $remount_rw -eq 1 ]] && command -v mount >/dev/null 2>&1; then + if mount -o remount,rw / 2>/dev/null; then + did_remount=1 + fi + fi + setup_persistent_lockdown + ensure_usbmuxd_binaries 1 + if [[ $did_remount -eq 1 ]]; then + mount -o remount,ro / 2>/dev/null || true + fi + cmd_preflight || true + echo "jetlink-usbmux: installed — jetlinkd will manage usbmuxd automatically when Full Frame Experimental Network is toggled on" +} + cmd_setup() { local do_install=0 want_mode="variant-a" arg for arg in "$@"; do @@ -410,6 +434,7 @@ if [[ $# -gt 0 ]]; then shift fi case "$cmd" in + install) cmd_install "$@" ;; setup) cmd_setup "$@" ;; speed) cmd_speed ;; pair) cmd_pair ;; diff --git a/tests/test_usbmux_host.py b/tests/test_usbmux_host.py new file mode 100644 index 00000000..c6e18ce9 --- /dev/null +++ b/tests/test_usbmux_host.py @@ -0,0 +1,333 @@ +""" +Copyright (c) 2026-, Zeph Leggett. + +This file is part of jetlink and is licensed under the MIT License. +See the LICENSE file in the root directory for more details. + +Unit tests for comma USB Host-mode (usbmuxd) live openpilot integration, +automatic iPhone Trust pairing, and bidirectional port-5600 handoff. +""" +from __future__ import annotations + +import os +import plistlib +import socket +import struct +import tempfile +import threading +import time +import unittest +from pathlib import Path +from types import SimpleNamespace +from unittest import mock + +from jetlink.comma import gadget, lending, owner as comma_owner, usbmux_host +from jetlink.comma.usbmux_transport import USBMUX_HEADER, USBMUX_MSG_PLIST, USBMUX_PROTOCOL_PLIST +from jetlink.openpilot import interface, settings, status + + +def _send_plist(sock: socket.socket, tag: int, payload: dict) -> None: + body = plistlib.dumps(payload, fmt=plistlib.FMT_XML) + sock.sendall(USBMUX_HEADER.pack(USBMUX_HEADER.size + len(body), USBMUX_PROTOCOL_PLIST, USBMUX_MSG_PLIST, tag) + body) + + +def _recv_exact(sock: socket.socket, n: int) -> bytes: + out = bytearray() + while len(out) < n: + chunk = sock.recv(n - len(out)) + if not chunk: + raise EOFError('unexpected EOF') + out.extend(chunk) + return bytes(out) + + +def _recv_plist(sock: socket.socket) -> tuple[int, dict]: + total, version, mtype, tag = USBMUX_HEADER.unpack(_recv_exact(sock, USBMUX_HEADER.size)) + assert version == USBMUX_PROTOCOL_PLIST and mtype == USBMUX_MSG_PLIST + return tag, plistlib.loads(_recv_exact(sock, total - USBMUX_HEADER.size)) + + +class MiniUsbmuxServer: + """Minimal AF_UNIX usbmuxd mock forwarding Connect to a local TCP port.""" + + def __init__(self, sock_path: Path, tcp_port: int, serial: str = '0000814000123456'): + self.sock_path = sock_path + self.tcp_port = tcp_port + self.serial = serial + self._stop = threading.Event() + self._srv = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + self._srv.bind(str(sock_path)) + self._srv.listen(4) + self._srv.settimeout(0.1) + self._thread = threading.Thread(target=self._serve, daemon=True) + self._thread.start() + + def _serve(self) -> None: + while not self._stop.is_set(): + try: + conn, _ = self._srv.accept() + except TimeoutError: + continue + except OSError: + break + threading.Thread(target=self._handle, args=(conn,), daemon=True).start() + + def _handle(self, conn: socket.socket) -> None: + target = None + try: + while not self._stop.is_set(): + tag, req = _recv_plist(conn) + mtype = req.get('MessageType') + if mtype == 'ListDevices': + _send_plist(conn, tag, { + 'DeviceList': [{ + 'MessageType': 'Attached', + 'DeviceID': 7, + 'Properties': { + 'DeviceID': 7, + 'ConnectionType': 'USB', + 'SerialNumber': self.serial, + 'ProductID': 0x12A8, + }, + }], + }) + return + if mtype == 'Connect': + want_port = socket.ntohs(int(req['PortNumber'])) + target = socket.create_connection(('127.0.0.1', want_port if want_port else self.tcp_port), timeout=1.0) + _send_plist(conn, tag, {'MessageType': 'Result', 'Number': 0}) + self._bridge(conn, target) + return + except OSError: + pass + finally: + if target is not None: + target.close() + conn.close() + + def _bridge(self, a: socket.socket, b: socket.socket) -> None: + def pipe(src: socket.socket, dst: socket.socket) -> None: + try: + while chunk := src.recv(4096): + dst.sendall(chunk) + except OSError: + pass + finally: + for fn in (lambda: dst.shutdown(socket.SHUT_WR), src.close): + try: + fn() + except OSError: + pass + + t = threading.Thread(target=pipe, args=(b, a), daemon=True) + t.start() + pipe(a, b) + t.join(timeout=1.0) + + def close(self) -> None: + self._stop.set() + self._srv.close() + self._thread.join(timeout=1.0) + + +class HandoffAndProbeTest(unittest.TestCase): + def test_handoff_listener_accepts_and_rejects(self): + can = [True] + listener = usbmux_host.HandoffListener(addr=('127.0.0.1', 0), can_usbmux=lambda: can[0]) + self.assertTrue(listener.open()) + self.addCleanup(listener.close) + _, port = listener.bound + + with socket.create_connection(('127.0.0.1', port), timeout=1.0) as s: + s.sendall(b'USBMUX\n') + self.assertTrue(listener.poll()) + self.assertEqual(s.recv(64).decode().strip(), 'OK') + + can[0] = False + with socket.create_connection(('127.0.0.1', port), timeout=1.0) as s: + s.sendall(b'USBMUX\n') + self.assertFalse(listener.poll()) + self.assertEqual(s.recv(64).decode().strip(), 'ERR missing_usbmuxd') + + def test_probe_ncm_request_and_server_ready(self): + # Bind ephemeral TCP advertiser returning NCM\n + ncm_srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + ncm_srv.bind(('127.0.0.1', 0)) + ncm_srv.listen(2) + self.addCleanup(ncm_srv.close) + port = ncm_srv.getsockname()[1] + + stop = threading.Event() + + def serve_ncm() -> None: + ncm_srv.settimeout(0.1) + while not stop.is_set(): + try: + conn, _ = ncm_srv.accept() + except TimeoutError: + continue + except OSError: + break + conn.sendall(b'NCM\n') + conn.close() + + t = threading.Thread(target=serve_ncm, daemon=True) + t.start() + self.addCleanup(lambda: (stop.set(), t.join(timeout=1.0))) + + with tempfile.TemporaryDirectory() as tmp: + sock_path = Path(tmp) / 'usbmuxd' + daemon = MiniUsbmuxServer(sock_path, port) + self.addCleanup(daemon.close) + self.assertTrue(usbmux_host.probe_ncm_request(socket_path=str(sock_path), port=port, timeout=1.0)) + self.assertEqual( + usbmux_host.probe_server_ready(socket_path=str(sock_path), port=port, timeout=1.0), + '0000814000123456', + ) + self.assertFalse(usbmux_host.probe_ncm_request(socket_path=str(sock_path), port=65499, timeout=0.2)) + + +class UsbmuxOwnerIntegrationTest(unittest.TestCase): + def setUp(self): + self.tmp = Path(tempfile.mkdtemp()) + self.params_dir = self.tmp / 'params' + self.params_dir.mkdir() + (self.params_dir / 'JetlinkLink').write_text(str(interface.MODES.index('ios'))) + (self.params_dir / 'IsOffroad').write_text('1') + + self.mode_path = self.tmp / 'transport_mode' + self.mode_fallback = self.tmp / 'transport_mode_fb' + self.mux_status = self.tmp / 'usbmux_status' + self.mux_pid = self.tmp / 'usbmuxd.pid' + self.mux_sock = self.tmp / 'usbmuxd.sock' + self.usb_sysfs = self.tmp / 'usb_devices' + self.usb_sysfs.mkdir() + + patches = [ + mock.patch.object(usbmux_host, 'TRANSPORT_MODE_PATH', self.mode_path), + mock.patch.object(usbmux_host, 'TRANSPORT_MODE_FALLBACK', self.mode_fallback), + mock.patch.object(usbmux_host, 'USBMUX_STATUS', self.mux_status), + mock.patch.object(usbmux_host, 'USBMUXD_PID', self.mux_pid), + mock.patch.object(usbmux_host, 'USBMUXD_SOCKET', self.mux_sock), + mock.patch.object(usbmux_host, 'USB_DEVICES', self.usb_sysfs), + mock.patch.object(gadget, 'LINK', self.tmp / 'jetlink-link'), + mock.patch.object(gadget, 'STATUS', self.tmp / 'status.json'), + mock.patch.object(gadget, 'STARTS', self.tmp / 'starts.json'), + mock.patch.object(gadget, 'SERVER', self.tmp / 'server.json'), + mock.patch.object(gadget, 'SHUTDOWN_REQUEST', self.tmp / 'shutdown'), + mock.patch.object(gadget, 'GADGET_STATUS', self.tmp / 'jetlink-gadget'), + mock.patch.object(gadget, 'LENDER_STATUS', self.tmp / 'jetlink-lender'), + mock.patch.object(gadget, 'FFS_MOUNT', self.tmp / 'ffs-jetlink'), + mock.patch.object(lending, 'SOCKET', self.tmp / 'lend.sock'), + ] + for p in patches: + p.start() + self.addCleanup(p.stop) + + # Simulate jetlink-root teardown having written "error: gadget torn down" previously + gadget.GADGET_STATUS.write_text('error: gadget torn down\n') + + def _attach_apple_sysfs(self, speed: str = '10000', serial: str = '0000814000ABCDEF') -> None: + dev = self.usb_sysfs / '2-1' + dev.mkdir(parents=True, exist_ok=True) + (dev / 'idVendor').write_text('05ac\n') + (dev / 'idProduct').write_text('12a8\n') + (dev / 'speed').write_text(f'{speed}\n') + (dev / 'serial').write_text(f'{serial}\n') + (dev / 'product').write_text('iPhone\n') + + def _owner(self) -> comma_owner.Owner: + keys = interface.Keys(link='JetlinkLink', offroad='IsOffroad', progress='P', spec='S') + s = settings.Settings(settings.FileParams(self.params_dir), keys) + return comma_owner.Owner(['python3', '-c', 'pass'], settings=s, chestnut_ids=()) + + def test_gadget_helpers_in_usbmux_mode(self): + self.mux_status.write_text('ok\n') + self.mux_sock.write_text('') + self.assertTrue(gadget.usbmux_active()) + self.assertTrue(gadget.link_configured()) + self.assertIsNone(gadget.gadget_error()) + self.assertFalse(gadget.host_attached()) + + self._attach_apple_sysfs() + self.assertTrue(gadget.host_attached()) + self.assertTrue(gadget.wait_for_host(0.1, mode='usbmux')) + + def test_pairer_runs_validate_and_triggers_pair_pop_up(self): + calls: list[list[str]] = [] + + def fake_run(argv, **kw): + calls.append(argv) + if argv[-1] == 'validate': + return SimpleNamespace(returncode=1, stdout='not paired') + return SimpleNamespace(returncode=0, stdout='SUCCESS: Paired with device') + + with mock.patch.object(usbmux_host, 'find_binary', return_value='/usr/bin/idevicepair'), \ + mock.patch.object(usbmux_host.subprocess, 'run', side_effect=fake_run): + pairer = usbmux_host.Pairer(retry_after=0.05) + self.assertFalse(pairer.tick(True, 'ABC123')) + deadline = time.monotonic() + 2.0 + while time.monotonic() < deadline and not pairer.paired: + time.sleep(0.02) + self.assertTrue(pairer.paired) + self.assertEqual(pairer.status, 'paired') + self.assertTrue(any(c[-1] == 'pair' for c in calls)) + + def test_owner_handoff_persist_adopt_and_ncm_exit(self): + self._attach_apple_sysfs(speed='10000') + self.mux_sock.write_text('') + + with mock.patch.object(usbmux_host, 'start_host_mode', side_effect=lambda: (self.mux_status.write_text('ok'), (True, None))[1]), \ + mock.patch.object(usbmux_host, 'stop_host_mode', side_effect=lambda: self.mux_status.unlink(missing_ok=True)), \ + mock.patch.object(usbmux_host, 'usbmuxd_running', return_value=True), \ + mock.patch.object(usbmux_host, 'has_usbmuxd', return_value=True), \ + mock.patch.object(usbmux_host, 'probe_ncm_request', return_value=False), \ + mock.patch.object(usbmux_host, 'probe_server_ready', return_value='0000814000ABCDEF') as probe_srv, \ + mock.patch.object(comma_owner.Owner, 'spawn_worker'): + own = self._owner() + self.addCleanup(own.lender.stop) + own.handoff = usbmux_host.HandoffListener(addr=('127.0.0.1', 0), can_usbmux=lambda: True) + self.assertTrue(own.enter_usbmux_mode(persist=True)) + self.assertEqual(usbmux_host.saved_transport_mode(), 'usbmux') + + own.pairer.paired = True + own.mode = 'ios' + own.usbmux_step() + self.assertEqual(probe_srv.call_count, 1) + # Subsequent parked steps must not re-probe port 5599 (avoids connect/disconnect flashing) + own.next_usbmux_probe = 0.0 + own.usbmux_step() + self.assertEqual(probe_srv.call_count, 1) + rec = own.status_record() + self.assertEqual(rec['link'], 'usbmux') + self.assertEqual(rec['speed'], 'super-speed-plus') + self.assertTrue(rec['present']) + self.assertIsNone(rec['error']) + + # Lender hands out usbmux lease instead of CDC-NCM or endpoint files + loan = lending.borrow('modeld', timeout=1.0, path=own.lender.path) + self.assertIsNotNone(loan) + self.assertTrue(loan.usbmux) + self.assertFalse(loan.cable) + loan.close() + time.sleep(0.05) + + # Boot restore via adopt() when plug-before-power restarts jetlinkd + own2 = self._owner() + own2.adopt() + self.assertTrue(own2.usbmux_mode) + + # Status link_transport formats usbmux cleanly + self.assertEqual(status.link_transport('ios', {'link': 'usbmux', 'peer': '0000814000AB'}), + 'iOS over usbmux (0000814000AB)') + + # When iPhone toggles OFF, NCM probe returns True -> owner exits usbmux and clears persistence + with mock.patch.object(usbmux_host, 'stop_host_mode', side_effect=lambda: self.mux_status.unlink(missing_ok=True)), \ + mock.patch.object(usbmux_host, 'usbmuxd_running', return_value=True), \ + mock.patch.object(usbmux_host, 'probe_ncm_request', return_value=True), \ + mock.patch.object(comma_owner.Owner, 'spawn_worker'): + own.next_usbmux_probe = 0.0 + own.pairer.paired = True + own.usbmux_step() + self.assertFalse(own.usbmux_mode) + self.assertEqual(usbmux_host.saved_transport_mode(), 'ncm')