提交 Haven Android 仓库源码 v5.87.79

This commit is contained in:
ali
2026-09-10 13:45:36 +08:00
parent 87b452c4dc
commit 22f4ca5830
2524 changed files with 599455 additions and 1 deletions
+40
View File
@@ -0,0 +1,40 @@
plugins {
alias(libs.plugins.android.library)
alias(libs.plugins.hilt)
alias(libs.plugins.ksp)
}
android {
namespace = "sh.haven.core.usb"
compileSdk = 37
defaultConfig {
minSdk = 26
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
testOptions {
unitTests.isReturnDefaultValues = true
}
}
dependencies {
implementation(libs.coroutines.core)
implementation(libs.coroutines.android)
implementation(libs.hilt.android)
ksp(libs.hilt.compiler)
testImplementation(libs.junit)
testImplementation(libs.mockk)
testImplementation(libs.coroutines.test)
}
kotlin {
compilerOptions {
jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17)
}
}
@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest />
@@ -0,0 +1,67 @@
package sh.haven.core.usb
import android.util.Log
import java.util.concurrent.locks.ReentrantLock
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.concurrent.withLock
private const val TAG = "UsbAccessGate"
/**
* Coordinates exclusive access to a phone-attached USB device between Haven
* consumers that do **not** share a [UsbDeviceConnection].
*
* The USB/IP export (via [UsbBroker]) and `core:fido`'s `FidoAuthenticator`
* each open their *own* connection to the same physical key and claim the same
* HID interface. Their CTAPHID frames then interleave on the shared interrupt
* endpoints and corrupt each other — the `0xbb` keepalive storm seen when the
* same YubiKey is both the SSH-auth credential and the usbip-export target on a
* flaky link.
*
* While FIDO auth runs it takes a per-device lease ([acquire]); the broker's
* transfer path waits on [awaitClear] so the export isn't transferring on that
* device concurrently. Keyed by `UsbDevice.deviceName` so an export of an
* *unrelated* device is never paused by a FIDO auth on the key.
*/
@Singleton
class UsbAccessGate @Inject constructor() {
private val lock = ReentrantLock()
private val cleared = lock.newCondition()
/** Lease counts by device name; >0 ⇒ a priority consumer holds the device. Guarded by [lock]. */
private val holders = HashMap<String, Int>()
/** Take an exclusive lease on [deviceName]. Re-entrant; balance with [release]. */
fun acquire(deviceName: String) = lock.withLock {
holders[deviceName] = (holders[deviceName] ?: 0) + 1
}
/** Release one lease on [deviceName] and wake any waiting broker transfers. */
fun release(deviceName: String) = lock.withLock {
val n = (holders[deviceName] ?: 0) - 1
if (n <= 0) holders.remove(deviceName) else holders[deviceName] = n
cleared.signalAll()
}
fun isHeld(deviceName: String): Boolean = lock.withLock { (holders[deviceName] ?: 0) > 0 }
/**
* Block until no lease is held on [deviceName], up to [timeoutMs]. Returns
* true if the device is clear, false on timeout — the caller then proceeds
* anyway, since a brief contended transfer is better than wedging the export
* if a lease is never released (e.g. the holder's thread died).
*/
fun awaitClear(deviceName: String, timeoutMs: Long): Boolean = lock.withLock {
if ((holders[deviceName] ?: 0) == 0) return@withLock true
var remaining = timeoutMs * 1_000_000 // nanos
while ((holders[deviceName] ?: 0) > 0) {
if (remaining <= 0) {
Log.w(TAG, "export on $deviceName proceeding despite a FIDO lease (waited ${timeoutMs}ms)")
return@withLock false
}
remaining = cleared.awaitNanos(remaining)
}
true
}
}
@@ -0,0 +1,466 @@
package sh.haven.core.usb
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.hardware.usb.UsbConstants
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbDeviceConnection
import android.hardware.usb.UsbEndpoint
import android.hardware.usb.UsbInterface
import android.hardware.usb.UsbManager
import android.os.Build
import android.util.Log
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeoutOrNull
import java.io.IOException
import java.util.concurrent.ConcurrentHashMap
import javax.inject.Inject
import javax.inject.Singleton
/**
* Broker for the phone's USB devices.
*
* This is the Android side of Haven's USB Layer-B primitive: a non-rooted
* phone denies `/dev/bus/usb` to both the app uid and the proot tracee, so the
* only way a Linux guest (or the agent) can touch a USB device is through an
* Android [UsbManager] app that owns the connection. [UsbBroker] is that owner.
*
* Slice 1 exposes enumeration + runtime permission + raw control/bulk transfers
* directly to the MCP agent. Later slices add a userspace proxy socket that a
* guest shim ([sh.haven.core.usb] over an abstract `LocalSocket`) speaks, so
* unmodified guest apps reach the device through these same transfers.
*
* Permission handling mirrors
* `sh.haven.core.fido.FidoAuthenticator.ensureUsbPermission` — same
* `FLAG_MUTABLE` + explicit-package fix (#15) so the system grant dialog
* round-trips correctly on Android 12+.
*
* Devices are keyed by [UsbDevice.getDeviceName] (the `/dev/bus/usb/BBB/DDD`
* path), which is stable for the life of an attachment and unique per device.
*/
@Singleton
class UsbBroker @Inject constructor(
@ApplicationContext private val context: Context,
private val accessGate: UsbAccessGate,
) {
private val usbManager: UsbManager
get() = context.getSystemService(Context.USB_SERVICE) as UsbManager
/** Open connections keyed by device name, plus the interfaces we claimed. */
private data class OpenHandle(
val device: UsbDevice,
val connection: UsbDeviceConnection,
// Concurrent: per-endpoint export lanes may claim the same interface
// (e.g. a CDC data interface with both bulk endpoints) concurrently.
val claimedInterfaces: MutableSet<Int> = ConcurrentHashMap.newKeySet(),
)
// Concurrent: the detach receiver hands off to [ioScope] so the blocking
// connection.close() never runs on the main thread (a wedged device would
// otherwise ANR the UI); export lanes read/transfer on other threads.
private val open = ConcurrentHashMap<String, OpenHandle>()
// Process-life scope for detach cleanup. closeDevice() blocks on native USB
// calls that a stalled device can hang indefinitely — keep them off the
// broadcast (main) thread.
private val ioScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
private val _detached = MutableSharedFlow<String>(extraBufferCapacity = 8)
/**
* Emits a device name after its handle is torn down on physical detach, so
* higher layers (e.g. the USB-drive VM manager) can unwind their own state
* without this module depending on them. Buffered + non-suspending so the
* detach path is never blocked by a slow collector.
*/
val detached: SharedFlow<String> get() = _detached
init {
// A physical unplug — or an ESP32-S3 re-enumerating when esptool resets it —
// silently invalidates an open connection. Without this, the export server
// keeps issuing transfers on a dead handle and the handle leaks until the
// next openDevice. Mirror FidoAuthenticator's USB receiver registration.
val receiver = object : BroadcastReceiver() {
override fun onReceive(ctx: Context, intent: Intent) {
if (intent.action != UsbManager.ACTION_USB_DEVICE_DETACHED) return
val device = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
intent.getParcelableExtra(UsbManager.EXTRA_DEVICE, UsbDevice::class.java)
} else {
@Suppress("DEPRECATION") intent.getParcelableExtra(UsbManager.EXTRA_DEVICE)
}
val name = device?.deviceName ?: return
if (open.containsKey(name)) {
Log.d(TAG, "USB device $name detached — closing handle")
// Off the main thread: connection.close() on a wedged device
// blocks, and the broadcast is finished the instant onReceive
// returns, so no slow-dispatch ANR can fire.
ioScope.launch {
closeDevice(name)
_detached.tryEmit(name)
}
}
}
}
val filter = IntentFilter(UsbManager.ACTION_USB_DEVICE_DETACHED)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
context.registerReceiver(receiver, filter, Context.RECEIVER_NOT_EXPORTED)
} else {
@Suppress("UnspecifiedRegisterReceiverFlag")
context.registerReceiver(receiver, filter)
}
}
// ---- Enumeration ------------------------------------------------------
/**
* Snapshot every attached USB device. Descriptor strings (manufacturer,
* product, serial) are only populated when permission is already held —
* Android returns null for them otherwise, and reading them must not
* trigger a permission prompt from a read-only listing.
*/
fun listDevices(): List<UsbDeviceInfo> =
usbManager.deviceList.values.map { describe(it) }
private fun describe(device: UsbDevice): UsbDeviceInfo {
val permitted = usbManager.hasPermission(device)
val interfaces = (0 until device.interfaceCount).map { i ->
val iface: UsbInterface = device.getInterface(i)
val endpoints = (0 until iface.endpointCount).map { e ->
val ep: UsbEndpoint = iface.getEndpoint(e)
UsbEndpointInfo(
address = ep.address,
direction = if (ep.direction == UsbConstants.USB_DIR_IN) "in" else "out",
type = endpointTypeName(ep.type),
maxPacketSize = ep.maxPacketSize,
)
}
UsbInterfaceInfo(
id = iface.id,
interfaceClass = iface.interfaceClass,
interfaceSubclass = iface.interfaceSubclass,
interfaceProtocol = iface.interfaceProtocol,
endpoints = endpoints,
)
}
return UsbDeviceInfo(
deviceName = device.deviceName,
vendorId = device.vendorId,
productId = device.productId,
deviceClass = device.deviceClass,
manufacturerName = if (permitted) device.manufacturerName else null,
productName = if (permitted) device.productName else null,
serialNumber = runCatching { if (permitted) device.serialNumber else null }.getOrNull(),
hasPermission = permitted,
isOpen = open.containsKey(device.deviceName),
interfaces = interfaces,
)
}
private fun endpointTypeName(type: Int): String = when (type) {
UsbConstants.USB_ENDPOINT_XFER_CONTROL -> "control"
UsbConstants.USB_ENDPOINT_XFER_ISOC -> "isochronous"
UsbConstants.USB_ENDPOINT_XFER_BULK -> "bulk"
UsbConstants.USB_ENDPOINT_XFER_INT -> "interrupt"
else -> "unknown"
}
private fun findDevice(deviceName: String): UsbDevice =
usbManager.deviceList[deviceName]
?: throw IOException("USB device '$deviceName' not attached")
// ---- Permission -------------------------------------------------------
fun hasPermission(deviceName: String): Boolean =
usbManager.deviceList[deviceName]?.let { usbManager.hasPermission(it) } ?: false
/**
* Request runtime permission for [deviceName], waiting for the system
* dialog. Returns true if granted (or already held). Mirrors the FIDO
* permission flow, including the FLAG_MUTABLE + explicit-package fix.
*/
suspend fun requestPermission(deviceName: String): Boolean {
val device = findDevice(deviceName)
if (usbManager.hasPermission(device)) return true
val deferred = CompletableDeferred<Boolean>()
val receiver = object : BroadcastReceiver() {
override fun onReceive(ctx: Context, intent: Intent) {
if (intent.action == ACTION_USB_PERMISSION) {
deferred.complete(
intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false),
)
}
}
}
val filter = IntentFilter(ACTION_USB_PERMISSION)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
context.registerReceiver(receiver, filter, Context.RECEIVER_NOT_EXPORTED)
} else {
@Suppress("UnspecifiedRegisterReceiverFlag")
context.registerReceiver(receiver, filter)
}
val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S)
PendingIntent.FLAG_MUTABLE else 0
// UsbManager fills the granted-flag extra back into the intent, so it
// must stay MUTABLE; an explicit-by-package intent keeps Android 14+
// from rejecting a mutable PendingIntent around an implicit Intent (#15).
val permIntent = Intent(ACTION_USB_PERMISSION).setPackage(context.packageName)
usbManager.requestPermission(
device,
PendingIntent.getBroadcast(context, 0, permIntent, flags),
)
val granted = try {
withTimeoutOrNull(PERMISSION_TIMEOUT_MS) { deferred.await() }
} finally {
runCatching { context.unregisterReceiver(receiver) }
}
return when (granted) {
null -> throw IOException("USB permission timed out — no response from system dialog")
else -> granted
}
}
// ---- Open / close -----------------------------------------------------
/** Open [deviceName] (requesting permission first if needed) and cache the connection. */
suspend fun openDevice(deviceName: String): UsbDeviceInfo {
val device = findDevice(deviceName)
open[deviceName]?.let {
// A cached connection is only valid while permission is still held.
// A detach/replug (or a revoked grant) silently invalidates the
// connection while leaving our handle behind — after which every
// later openDevice would be a no-op that can never re-prompt, and
// transfers fail with rc=-1. Evict the stale handle and re-open.
if (usbManager.hasPermission(device)) return describe(device)
Log.d(TAG, "Evicting stale handle for $deviceName (permission lost — likely re-enumerated)")
closeDevice(deviceName)
}
if (!requestPermission(deviceName)) throw IOException("USB permission denied for $deviceName")
val connection = usbManager.openDevice(device)
?: throw IOException("Failed to open USB device $deviceName")
open[deviceName] = OpenHandle(device, connection)
Log.d(TAG, "Opened $deviceName (${"%04x".format(device.vendorId)}:${"%04x".format(device.productId)})")
return describe(device)
}
fun closeDevice(deviceName: String) {
open.remove(deviceName)?.let { handle ->
// Serialize against in-flight transfers, which hold the same monitor
// (controlTransfer/bulkTransfer). Each transfer holds it only around
// one timeout-bounded native call, so this waits at most that long;
// removing from `open` first makes new transfers fail fast instead.
synchronized(handle.connection) {
handle.claimedInterfaces.forEach { id ->
runCatching {
handle.connection.releaseInterface(handle.device.getInterface(indexOfInterfaceId(handle.device, id)))
}
}
runCatching { handle.connection.close() }
}
Log.d(TAG, "Closed $deviceName")
}
}
/** Release all open connections — call on broker teardown / app stop. */
fun closeAll() {
open.keys.toList().forEach { closeDevice(it) }
}
/** Whether a handle is currently open for [deviceName] (export servers poll this to stop on device loss). */
fun isOpen(deviceName: String): Boolean = open.containsKey(deviceName)
private fun handleFor(deviceName: String): OpenHandle =
open[deviceName] ?: throw IOException("USB device '$deviceName' not open — call openDevice first")
/**
* The device + active-config descriptors as the kernel would return them
* (the bytes `UsbDeviceConnection.getRawDescriptors()` exposes). The proxy
* server hands these to the guest shim so it can synthesize the HID report
* descriptor / libudev attributes without a real device node.
*/
fun rawDescriptors(deviceName: String): ByteArray =
handleFor(deviceName).connection.rawDescriptors ?: ByteArray(0)
// ---- Transfers --------------------------------------------------------
/**
* Endpoint-0 control transfer. [data] is the OUT payload (ignored for IN
* transfers, where [length] sizes the read buffer). Returns the bytes
* transferred plus, for IN transfers, the data read.
*/
fun controlTransfer(
deviceName: String,
requestType: Int,
request: Int,
value: Int,
index: Int,
data: ByteArray?,
length: Int,
timeoutMs: Int,
): TransferResult {
val handle = handleFor(deviceName)
// Pause while a priority consumer (FIDO auth on its own connection) holds
// the key, so the export isn't transferring on the shared endpoints at the
// same time (#FIDO-storm contention).
accessGate.awaitClear(deviceName, EXPORT_YIELD_MS)
// An interface-recipient request (bmRequestType bits 0-4 == 1) — e.g. the
// HID GET_DESCRIPTOR(REPORT) that usbhid issues at probe time — only
// succeeds on Android once that interface is claimed. Without the claim the
// report-descriptor read stalls, we surface it as -EPIPE, and the remote
// usbhid fails with "can't add hid device: -32" (no hidraw ⇒ FIDO unusable).
// Mirrors bulkTransfer's lazy per-interface claim; wIndex low byte = iface#.
if (requestType and 0x1F == 0x01) claimInterfaceByNumber(handle, index and 0xFF)
val isIn = (requestType and UsbConstants.USB_DIR_IN) != 0
val buffer = if (isIn) ByteArray(length) else (data ?: ByteArray(0))
// A single UsbDeviceConnection has no built-in thread safety — a
// concurrent caller on another thread (e.g. UsbDriveVmManager's
// keep-alive control transfer racing a USB/IP export lane's bulk
// transfer) can corrupt an in-flight USB transaction. Observed live:
// a keep-alive GET_STATUS racing bulk reads reset the device mid-VM-
// boot and it never re-enumerated for the rest of that session.
val transferred = synchronized(handle.connection) {
handle.connection.controlTransfer(
requestType, request, value, index, buffer, if (isIn) length else buffer.size, timeoutMs,
)
}
if (transferred < 0) throw IOException("controlTransfer failed (rc=$transferred)")
val out = if (isIn) buffer.copyOf(transferred) else ByteArray(0)
return TransferResult(transferred, out)
}
/**
* Bulk or interrupt transfer on the endpoint with [endpointAddress]. The
* owning interface is claimed on first use. Direction is taken from the
* endpoint descriptor; [data] is the OUT payload, [length] the IN buffer size.
*/
fun bulkTransfer(
deviceName: String,
endpointAddress: Int,
data: ByteArray?,
length: Int,
timeoutMs: Int,
): TransferResult {
val handle = handleFor(deviceName)
accessGate.awaitClear(deviceName, EXPORT_YIELD_MS) // yield to FIDO auth — see controlTransfer
val (iface, endpoint) = locateEndpoint(handle.device, endpointAddress)
val isIn = endpoint.direction == UsbConstants.USB_DIR_IN
val buffer = if (isIn) ByteArray(length) else (data ?: ByteArray(0))
val total = if (isIn) length else buffer.size
synchronized(handle.connection) {
if (handle.claimedInterfaces.add(iface.id)) {
if (!handle.connection.claimInterface(iface, true)) {
handle.claimedInterfaces.remove(iface.id)
throw IOException("Failed to claim interface ${iface.id} for endpoint $endpointAddress")
}
}
}
// Chunk loop deliberately does NOT hold the lock across the whole
// transfer — a mass-storage device's BULK OUT (data) and BULK IN
// (status) traffic for the SAME command must interleave on separate
// UsbIpServer lane threads (worse with UAS command queuing). Holding
// one lock for an entire multi-chunk write starved the status-read
// lane long enough that the guest's own SCSI command timeout fired
// and reset the device mid-write. Lock only each individual native
// call — see the class-level race this whole scheme guards against.
val transferred = transferInChunks(handle.connection, endpoint, buffer, total, timeoutMs)
if (transferred < 0) throw IOException("bulkTransfer failed (rc=$transferred)")
val out = if (isIn) buffer.copyOf(transferred) else ByteArray(0)
return TransferResult(transferred, out)
}
/**
* A single `UsbDeviceConnection.bulkTransfer` call above [MAX_TRANSFER_CHUNK]
* can silently truncate on Android's legacy synchronous USB API (no kernel
* URB streaming) — observed live as a guest's large multi-segment write
* (cryptsetup wiping a LUKS header, 15KB+ in one URB) desyncing the
* device's USB transaction state machine, which cheap flash controllers
* respond to with a hard reset instead of a clean short-write error.
* Loop in bounded chunks instead of trusting one call to move everything.
*/
private fun transferInChunks(
connection: UsbDeviceConnection,
endpoint: UsbEndpoint,
buffer: ByteArray,
total: Int,
timeoutMs: Int,
): Int {
var offset = 0
while (offset < total) {
val chunkLen = minOf(MAX_TRANSFER_CHUNK, total - offset)
val rc = synchronized(connection) {
connection.bulkTransfer(endpoint, buffer, offset, chunkLen, timeoutMs)
}
if (rc < 0) return if (offset == 0) rc else offset
offset += rc
if (rc < chunkLen) break // short transfer — device signaled end of data
}
return offset
}
private fun locateEndpoint(device: UsbDevice, address: Int): Pair<UsbInterface, UsbEndpoint> {
for (i in 0 until device.interfaceCount) {
val iface = device.getInterface(i)
for (e in 0 until iface.endpointCount) {
val ep = iface.getEndpoint(e)
if (ep.address == address) return iface to ep
}
}
throw IOException("No endpoint with address 0x${"%02x".format(address)} on ${device.deviceName}")
}
private fun indexOfInterfaceId(device: UsbDevice, id: Int): Int =
(0 until device.interfaceCount).first { device.getInterface(it).id == id }
/**
* Claim (once) the interface whose bInterfaceNumber is [number], mirroring
* [bulkTransfer]'s lazy claim. Needed before an interface-recipient control
* transfer (Android routes those to a claimed interface only). No-op if the
* device has no such interface — an unknown wIndex shouldn't fail the request.
*/
private fun claimInterfaceByNumber(handle: OpenHandle, number: Int) {
val iface = (0 until handle.device.interfaceCount)
.map { handle.device.getInterface(it) }
.firstOrNull { it.id == number } ?: return
synchronized(handle.connection) {
if (handle.claimedInterfaces.add(iface.id)) {
if (!handle.connection.claimInterface(iface, true)) {
handle.claimedInterfaces.remove(iface.id)
throw IOException("Failed to claim interface ${iface.id} for control transfer")
}
}
}
}
companion object {
private const val TAG = "UsbBroker"
private const val PERMISSION_TIMEOUT_MS = 30_000L
/**
* Max time an export transfer waits for a FIDO auth lease to clear before
* proceeding anyway. Above FIDO's 30s user-presence USB timeout so a real
* auth finishes first, but bounded so a dead holder can't wedge the export.
*/
private const val EXPORT_YIELD_MS = 35_000L
/**
* Safe per-call size for [transferInChunks] — comfortably under the
* ~16KB threshold where Android's synchronous UsbDeviceConnection.
* bulkTransfer has been observed to silently truncate on some
* devices/API levels.
*/
private const val MAX_TRANSFER_CHUNK = 16 * 1024
/** Broadcast action for the runtime-permission grant callback. */
const val ACTION_USB_PERMISSION = "sh.haven.core.usb.USB_PERMISSION"
}
}
@@ -0,0 +1,237 @@
package sh.haven.core.usb
import java.io.ByteArrayOutputStream
import java.io.DataInputStream
import java.io.DataOutputStream
import java.io.EOFException
/**
* Server side of the USB/IP wire protocol (mirrors the Linux kernel
* `drivers/usb/usbip` structs). Haven speaks this as a *userspace* usbip server
* so a stock `usbip attach` client on a remote Linux host imports a phone-side
* USB device. The Android kernel has no usbip module and the device is owned by
* [UsbBroker] in userspace, so the kernel `usbip-host` path is unavailable — we
* bridge each URB onto [UsbBroker] control/bulk transfers instead.
*
* Two phases on one TCP connection (port 3240):
* 1. op handshake — client sends OP_REQ_IMPORT{busid}; server replies
* OP_REP_IMPORT{usbip_usb_device}.
* 2. URB stream — 48-byte headers, USBIP_CMD_SUBMIT / USBIP_CMD_UNLINK, each
* answered with USBIP_RET_SUBMIT / USBIP_RET_UNLINK.
*
* All multi-byte header fields are big-endian (network order — the DataInput/
* Output default). The 8-byte control `setup` packet stays USB-native
* little-endian and is forwarded verbatim.
*
* DEVLIST (for `usbip list -r`) is omitted: `usbip attach -b <busid>` imports
* directly without it. ponytail: add OP_REQ_DEVLIST when a UI needs remote
* enumeration.
*/
object UsbIpProtocol {
const val VERSION = 0x0111
const val OP_REQ_IMPORT = 0x8003
const val OP_REP_IMPORT = 0x0003
const val CMD_SUBMIT = 0x0001
const val RET_SUBMIT = 0x0003
const val CMD_UNLINK = 0x0002
const val RET_UNLINK = 0x0004
const val DIR_OUT = 0
const val DIR_IN = 1
/** usbip_usb_device, as OP_REP_IMPORT carries it (312 packed bytes on the wire). */
data class Device(
val busid: String,
val busnum: Int,
val devnum: Int,
val speed: Int,
val idVendor: Int,
val idProduct: Int,
val bcdDevice: Int,
val deviceClass: Int,
val deviceSubClass: Int,
val deviceProtocol: Int,
val configurationValue: Int,
val numConfigurations: Int,
val numInterfaces: Int,
)
// ---- Phase 1: op handshake -------------------------------------------
sealed interface OpRequest {
data class Import(val busid: String) : OpRequest
}
/** Read one op handshake request, or null at clean EOF. */
fun readOpRequest(input: DataInputStream): OpRequest? {
val version = try {
input.readUnsignedShort()
} catch (_: EOFException) {
return null
}
val code = input.readUnsignedShort()
input.readInt() // status — unused on requests
return when (code) {
OP_REQ_IMPORT -> OpRequest.Import(readFixedString(input, 32))
else -> throw IllegalArgumentException(
"unsupported op 0x${code.toString(16)} (peer version 0x${version.toString(16)})",
)
}
}
/** OP_REP_IMPORT. [device] null => status=1 (import failed; no device body). */
fun encodeImportReply(device: Device?): ByteArray = buildBytes {
writeShort(VERSION)
writeShort(OP_REP_IMPORT)
writeInt(if (device == null) 1 else 0)
if (device != null) writeDevice(device)
}
private fun DataOutputStream.writeDevice(d: Device) {
writeFixedString("/haven/${d.busid}", 256) // path (cosmetic to the client)
writeFixedString(d.busid, 32)
writeInt(d.busnum)
writeInt(d.devnum)
writeInt(d.speed)
writeShort(d.idVendor)
writeShort(d.idProduct)
writeShort(d.bcdDevice)
writeByte(d.deviceClass)
writeByte(d.deviceSubClass)
writeByte(d.deviceProtocol)
writeByte(d.configurationValue)
writeByte(d.numConfigurations)
writeByte(d.numInterfaces)
}
// ---- Phase 2: URB stream ---------------------------------------------
sealed interface Urb {
/**
* USBIP_CMD_SUBMIT. [out] is the OUT payload (empty for IN). [setup] is
* the 8-byte control packet (all-zero for non-control endpoints).
*/
data class Submit(
val seqnum: Int,
val devid: Int,
val direction: Int,
val ep: Int,
val transferFlags: Int,
val transferBufferLength: Int,
val interval: Int,
val setup: ByteArray,
val out: ByteArray,
) : Urb {
override fun equals(other: Any?) = other is Submit &&
seqnum == other.seqnum && devid == other.devid &&
direction == other.direction && ep == other.ep &&
transferFlags == other.transferFlags &&
transferBufferLength == other.transferBufferLength &&
interval == other.interval &&
setup.contentEquals(other.setup) && out.contentEquals(other.out)
override fun hashCode(): Int {
var h = seqnum
h = 31 * h + devid; h = 31 * h + direction; h = 31 * h + ep
h = 31 * h + transferFlags; h = 31 * h + transferBufferLength
h = 31 * h + interval; h = 31 * h + setup.contentHashCode()
h = 31 * h + out.contentHashCode()
return h
}
}
/** USBIP_CMD_UNLINK — [unlinkSeqnum] is the SUBMIT seqnum to cancel. */
data class Unlink(val seqnum: Int, val unlinkSeqnum: Int) : Urb
}
/** Read one URB command, or null at clean EOF. */
fun readUrb(input: DataInputStream): Urb? {
val command = try {
input.readInt()
} catch (_: EOFException) {
return null
}
val seqnum = input.readInt()
val devid = input.readInt()
val direction = input.readInt()
val ep = input.readInt()
return when (command) {
CMD_SUBMIT -> {
val transferFlags = input.readInt()
val transferBufferLength = input.readInt()
input.readInt() // start_frame
input.readInt() // number_of_packets
val interval = input.readInt()
val setup = ByteArray(8).also { input.readFully(it) }
val out = if (direction == DIR_OUT && transferBufferLength > 0) {
ByteArray(transferBufferLength).also { input.readFully(it) }
} else {
ByteArray(0)
}
Urb.Submit(seqnum, devid, direction, ep, transferFlags, transferBufferLength, interval, setup, out)
}
CMD_UNLINK -> {
val unlinkSeqnum = input.readInt()
repeat(6) { input.readInt() } // rest of the 28-byte cmd area
Urb.Unlink(seqnum, unlinkSeqnum)
}
else -> throw IllegalArgumentException("unknown URB command 0x${command.toString(16)}")
}
}
/**
* USBIP_RET_SUBMIT. [status] 0 = ok, else -errno. [actualLength] is bytes
* transferred (the OUT bytes sent, or the IN bytes read). [inData] is the IN
* payload appended to the reply (empty for OUT; its size must equal
* [actualLength] on an IN success). Both are zeroed on error.
*/
fun encodeSubmitReply(seqnum: Int, status: Int, actualLength: Int, inData: ByteArray): ByteArray = buildBytes {
writeInt(RET_SUBMIT)
writeInt(seqnum)
writeInt(0) // devid (unused in replies)
writeInt(0) // direction
writeInt(0) // ep
writeInt(status)
writeInt(if (status == 0) actualLength else 0)
writeInt(0) // start_frame
writeInt(0) // number_of_packets
writeInt(0) // error_count
write(ByteArray(8)) // setup padding (unused in ret_submit)
if (status == 0 && inData.isNotEmpty()) write(inData)
}
/** USBIP_RET_UNLINK. */
fun encodeUnlinkReply(seqnum: Int, status: Int): ByteArray = buildBytes {
writeInt(RET_UNLINK)
writeInt(seqnum)
writeInt(0) // devid
writeInt(0) // direction
writeInt(0) // ep
writeInt(status)
write(ByteArray(24)) // padding to the 28-byte ret area
}
// ---- helpers ---------------------------------------------------------
private fun readFixedString(input: DataInputStream, len: Int): String {
val buf = ByteArray(len)
input.readFully(buf)
val end = buf.indexOf(0.toByte()).let { if (it < 0) len else it }
return String(buf, 0, end, Charsets.US_ASCII)
}
private fun DataOutputStream.writeFixedString(s: String, len: Int) {
val b = s.toByteArray(Charsets.US_ASCII)
val n = minOf(b.size, len)
write(b, 0, n)
repeat(len - n) { writeByte(0) }
}
private inline fun buildBytes(block: DataOutputStream.() -> Unit): ByteArray {
val bos = ByteArrayOutputStream()
DataOutputStream(bos).use { it.block() }
return bos.toByteArray()
}
}
@@ -0,0 +1,482 @@
package sh.haven.core.usb
import android.util.Log
import java.io.DataInputStream
import java.io.DataOutputStream
import java.net.InetAddress
import java.net.ServerSocket
import java.net.Socket
import java.util.concurrent.Executors
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.concurrent.thread
/**
* Userspace USB/IP server. Exports one [UsbBroker]-owned device over TCP so a
* stock `usbip attach` client on a remote Linux host imports it as a real USB
* device node — no per-app shim, every guest app (ssh, libfido2, browsers) sees
* it, touch happens on the phone.
*
* This is the remote-host counterpart to [UsbProxyServer] (which serves the
* proot guest over a LocalSocket): the proot guest can't be a usbip *client*
* because the Android kernel ships no `vhci-hcd`, so usbip is the over-the-wire
* path and the bespoke proxy stays the local-guest path.
*
* One shared server (one port) can export multiple devices at once, each
* client's IMPORT request selecting one by busid ([export]/[unexport]) —
* e.g. two concurrent on-device USB-drive VMs (#287). [start]/[stop] keep
* the older single-device replace-everything behaviour for the remote-host
* export MCP verbs. URBs are serialized **per (endpoint,
* direction)** lane: same endpoint runs in submission order (a multi-frame
* CTAPHID write — init + continuation frames on interrupt-OUT — must reach the
* device in order or it rejects the whole message as INVALID_LENGTH), while
* different endpoints run concurrently so a blocking interrupt-IN (e.g. the
* composite key's idle CCID status poll, or a FIDO key awaiting touch) never
* starves the FIDO traffic on another endpoint.
*
* UNLINK: Android has no per-transfer cancel, so an unlinked transfer runs to
* completion in its pool thread — but its late RET_SUBMIT MUST be dropped. A
* RET_SUBMIT for a seqnum the client already unlinked makes the vhci client
* tear down the *whole* device ("cannot find a urb of seqnum N"), which is what
* killed forwarding of a composite key (idle CCID/FIDO interrupt-INs get
* unlinked, then their stale completion desynced the stream). We track unlinked
* seqnums and suppress their reply; the thread just exits quietly.
*/
@Singleton
class UsbIpServer @Inject constructor(
private val broker: UsbBroker,
) {
@Volatile private var serverSocket: ServerSocket? = null
// busid -> exported deviceName. One shared ServerSocket serves every export;
// each client's IMPORT request picks a device by busid (the wire protocol
// already carries it — describeForImport looks it up below). This is what
// makes concurrent exports (e.g. two on-device USB-drive VMs) possible on
// one port instead of one device monopolising the whole server (#287
// multi-drive). [start]/[stop] (used by the single-device remote-host export
// MCP verbs) keep their old replace-everything semantics on top of this map.
private val exported = java.util.concurrent.ConcurrentHashMap<String, String>()
val isRunning: Boolean get() = serverSocket != null
val boundPort: Int? get() = serverSocket?.localPort
/** The exported device's `/dev/bus/usb/...` name, when exactly one export is active. */
val exportedDeviceName: String? get() = exported.values.singleOrNull()
private val clients = java.util.concurrent.atomic.AtomicInteger(0)
/** Live client sockets, so [stop] can close them and unblock their serve() threads. */
private val clientSockets = java.util.concurrent.ConcurrentHashMap.newKeySet<Socket>()
/** Remote usbip clients currently connected (>0 ⇒ a host has attached). */
val clientCount: Int get() = clients.get()
/**
* Bind the usbip server for [deviceName] (already opened via
* [UsbBroker.openDevice]), replacing whatever else was exported. [bindAddress]
* null binds all interfaces (LAN + loopback); pass "127.0.0.1" to keep it
* loopback-only behind a tunnel. Returns the bound port. For the
* single-device remote-host export path (MCP `start_usbip_export`); a
* concurrent multi-device export ([export]/[unexport]) collides with this
* on the shared socket exactly like it did before this class supported
* more than one device — not a new limitation.
*/
@Synchronized
fun start(deviceName: String, port: Int = USBIP_PORT, bindAddress: String? = null): Int {
if (serverSocket != null && exported.values.singleOrNull() == deviceName) return serverSocket!!.localPort
stop()
export(deviceName, port, bindAddress)
return serverSocket!!.localPort
}
/**
* Export [deviceName] (already opened via [UsbBroker.openDevice]) over
* USB/IP alongside any other current exports, starting the shared server if
* this is the first one. Returns the busid a `usbip attach -b <busid>`
* client should use to reach it.
*/
@Synchronized
fun export(deviceName: String, port: Int = USBIP_PORT, bindAddress: String? = null): String {
val busid = busidOf(deviceName)
exported[busid] = deviceName
if (serverSocket == null) {
val addr = bindAddress?.let { InetAddress.getByName(it) }
// Build unbound so SO_REUSEADDR is set *before* bind: the immediate-bind
// ServerSocket(port, backlog, addr) ctor binds with REUSEADDR off, so a
// re-export within one app session (after stop(), while the prior port is
// in TIME_WAIT) fails with EADDRINUSE. Enabling it lets the rebind succeed.
val socket = ServerSocket().apply {
reuseAddress = true
bind(java.net.InetSocketAddress(addr, port), BACKLOG)
}
serverSocket = socket
thread(name = "haven-usbip-accept", isDaemon = true) {
Log.i(TAG, "usbip server listening on ${addr ?: "0.0.0.0"}:${socket.localPort}")
while (serverSocket === socket) {
val client = try {
socket.accept()
} catch (e: Exception) {
if (serverSocket === socket) Log.w(TAG, "accept failed: ${e.message}")
break
}
thread(name = "haven-usbip-conn", isDaemon = true) { serve(client) }
}
}
}
Log.i(TAG, "exporting $deviceName as $busid (${exported.size} device(s) total)")
return busid
}
/** Stop exporting just [busid]; stops the whole server once nothing is left exported. */
@Synchronized
fun unexport(busid: String) {
exported.remove(busid)
if (exported.isEmpty()) stop()
}
@Synchronized
fun stop() {
serverSocket?.let { runCatching { it.close() } }
serverSocket = null
exported.clear()
// Closing the server socket doesn't close already-accepted client sockets,
// so without this their serve() threads stay blocked on read/write and
// clientCount lingers >0 until the remote's TCP errors. Close them now so
// they exit and decrement promptly.
clientSockets.forEach { runCatching { it.close() } }
clientSockets.clear()
}
// "/dev/bus/usb/BBB/DDD" -> "B-D", matching describeForImport's own busid.
private fun busidOf(deviceName: String): String {
val parts = deviceName.trimEnd('/').split('/')
val bus = parts.getOrNull(parts.size - 2)?.toIntOrNull() ?: 1
val dev = parts.lastOrNull()?.toIntOrNull() ?: 1
return "$bus-$dev"
}
private fun serve(client: Socket) {
clients.incrementAndGet()
clientSockets.add(client)
try {
serveConnection(client)
} finally {
clientSockets.remove(client)
clients.decrementAndGet()
}
}
private fun serveConnection(client: Socket) {
// One single-thread lane per (endpoint, direction): in-order within a lane,
// concurrent across lanes. Keyed by ep<<1|direction (DIR_IN=1, DIR_OUT=0).
val lanes = java.util.concurrent.ConcurrentHashMap<Int, java.util.concurrent.ExecutorService>()
fun laneFor(ep: Int, direction: Int): java.util.concurrent.ExecutorService =
lanes.getOrPut((ep shl 1) or direction) { Executors.newSingleThreadExecutor() }
// Seqnums the client has unlinked: their (late) RET_SUBMIT must be dropped.
val cancelled = java.util.concurrent.ConcurrentHashMap.newKeySet<Int>()
client.use { sock ->
sock.tcpNoDelay = true
val input = DataInputStream(sock.getInputStream().buffered())
val output = DataOutputStream(sock.getOutputStream())
val writeLock = Any()
// Phase 1: op handshake (expect a single IMPORT).
val op = try {
UsbIpProtocol.readOpRequest(input)
} catch (e: Exception) {
Log.w(TAG, "op handshake failed: ${e.message}"); return
} ?: return
val device: String
when (op) {
is UsbIpProtocol.OpRequest.Import -> {
device = exported[op.busid] ?: run {
Log.w(TAG, "IMPORT of busid ${op.busid} failed — not currently exported")
synchronized(writeLock) {
output.write(UsbIpProtocol.encodeImportReply(null)); output.flush()
}
return
}
val dev = runCatching { describeForImport(device) }.getOrNull()
synchronized(writeLock) {
output.write(UsbIpProtocol.encodeImportReply(dev)); output.flush()
}
if (dev == null) {
Log.w(TAG, "IMPORT of $device failed — no descriptors"); return
}
Log.i(TAG, "IMPORT ${op.busid} -> $device ok; entering URB loop")
}
}
// Phase 2: URB stream.
val backend = BrokerBackend(broker, device)
while (true) {
// Device unplugged / re-enumerated (e.g. esptool resetting an ESP32-S3):
// stop rather than spin replying EPIPE on a dead handle. Exiting the
// client.use block closes the socket and drains the lanes below.
if (!broker.isOpen(device)) {
Log.i(TAG, "device $device no longer open — ending export connection"); break
}
val urb = try {
UsbIpProtocol.readUrb(input)
} catch (e: Exception) {
Log.w(TAG, "URB read failed: ${e.message}"); break
} ?: break
when (urb) {
is UsbIpProtocol.Urb.Submit -> laneFor(urb.ep, urb.direction).execute {
// Interrupt/bulk IN stays pending (short-poll) until data or unlink;
// OUT/control is a single bounded transfer.
val reply = if (urb.direction == UsbIpProtocol.DIR_IN && urb.ep != 0) {
pollIn(urb, backend, cancelled, IN_POLL_MS)
} else {
bridgeSubmit(urb, backend, TRANSFER_TIMEOUT_MS)
}
synchronized(writeLock) {
// Drop the reply if the client unlinked this URB while it ran —
// a stale RET_SUBMIT desyncs vhci and disconnects the device.
val wasCancelled = cancelled.remove(urb.seqnum)
if (reply != null && !wasCancelled) {
runCatching { output.write(reply); output.flush() }
}
}
}
is UsbIpProtocol.Urb.Unlink -> synchronized(writeLock) {
cancelled.add(urb.unlinkSeqnum)
runCatching {
output.write(UsbIpProtocol.encodeUnlinkReply(urb.seqnum, status = 0)); output.flush()
}
}
}
}
}
lanes.values.forEach { it.shutdownNow() }
}
/** Build the OP_REP_IMPORT device record from the brokered descriptors. */
private fun describeForImport(device: String): UsbIpProtocol.Device {
val raw = broker.rawDescriptors(device)
require(raw.size >= 18) { "short device descriptor (${raw.size} bytes)" }
fun u8(i: Int) = raw[i].toInt() and 0xFF
fun u16le(i: Int) = u8(i) or (u8(i + 1) shl 8)
// busnum/devnum from "/dev/bus/usb/BBB/DDD".
val parts = device.trimEnd('/').split('/')
val busnum = parts.getOrNull(parts.size - 2)?.toIntOrNull() ?: 1
val devnum = parts.lastOrNull()?.toIntOrNull() ?: 1
// Active-config descriptor follows the 18-byte device descriptor.
val configValue = if (raw.size >= 18 + 6) u8(18 + 5) else 1
val config = if (raw.size > 18) raw.copyOfRange(18, raw.size) else ByteArray(0)
return UsbIpProtocol.Device(
busid = "$busnum-$devnum",
busnum = busnum,
devnum = devnum,
// Report the device's real speed. It was hardcoded FULL ("cosmetic"
// for full-speed FIDO keys), but a high-speed device (mass storage,
// 512-byte bulk endpoints) imported as full-speed makes the guest's
// vhci_hcd mis-enumerate it — the drive never appears (#287 empty
// mount). Detect from the endpoint packet sizes.
speed = detectSpeed(config, u8(7)),
idVendor = u16le(8),
idProduct = u16le(10),
bcdDevice = u16le(12),
deviceClass = u8(4),
deviceSubClass = u8(5),
deviceProtocol = u8(6),
configurationValue = configValue,
numConfigurations = u8(17),
// FIDO keys export interface 0 only (CCID stripped, see filterToFidoInterface);
// every other device keeps its real count so multi-interface classes
// (e.g. CDC serial: control + data) fully enumerate on the host.
numInterfaces = if (interface0IsHid(config)) 1
else if (config.size >= 5) config[4].toInt() and 0xFF else 1,
)
}
companion object {
/**
* Infer the device's USB speed from its endpoint descriptors. Full-speed
* bulk/interrupt endpoints cap at 64; high-speed bulk carries 512; a
* SuperSpeed bulk carries 1024. So max endpoint size picks HIGH vs FULL,
* and a SuperSpeed-only signal promotes to SUPER:
* - bulk wMaxPacketSize ≥ 1024 (only legal at SuperSpeed), or
* - the device descriptor's bMaxPacketSize0 == 9, which is the encoded
* 512-byte SuperSpeed ep0 size (a kernel accepts 9 only on an SS port).
* Reporting an SS drive as high-speed makes the guest's vhci_hcd reject
* ep0 maxpacket 9 and fail enumeration — "unable to enumerate USB
* device" — so the drive never appears (#506).
* [ep0MaxPacket] is bMaxPacketSize0 from the 18-byte device descriptor.
*/
internal fun detectSpeed(config: ByteArray, ep0MaxPacket: Int): Int {
var i = 0
var maxPkt = 0
while (i + 1 < config.size) {
val len = config[i].toInt() and 0xFF
if (len < 2) break
val type = config[i + 1].toInt() and 0xFF
if (type == 0x05 && i + 5 < config.size) { // ENDPOINT descriptor
val mps = ((config[i + 4].toInt() and 0xFF) or
((config[i + 5].toInt() and 0xFF) shl 8)) and 0x7FF // bits 0-10 = size
if (mps > maxPkt) maxPkt = mps
}
i += len
}
if (maxPkt >= 1024 || ep0MaxPacket == 9) return USB_SPEED_SUPER
return if (maxPkt >= 512) USB_SPEED_HIGH else USB_SPEED_FULL
}
private const val TAG = "UsbIpServer"
const val USBIP_PORT = 3240
private const val BACKLOG = 4
private const val USB_SPEED_FULL = 2
private const val USB_SPEED_HIGH = 3
internal const val USB_SPEED_SUPER = 4
/** Upper bound for a single OUT/control transfer; real ones complete in ms. */
private const val TRANSFER_TIMEOUT_MS = 5_000
/** Slice for polling an interrupt/bulk IN so an idle read never wedges its lane. */
private const val IN_POLL_MS = 250
/**
* Translate one SUBMIT into a backend transfer and encode the
* RET_SUBMIT reply. Pure but for [backend]; unit-tested with a fake.
*/
fun bridgeSubmit(urb: UsbIpProtocol.Urb.Submit, backend: UsbIpBackend, timeoutMs: Int): ByteArray = try {
val isIn = urb.direction == UsbIpProtocol.DIR_IN
val inData = if (urb.ep == 0) {
// Control: the 8-byte setup packet is USB-native little-endian.
val s = urb.setup
fun u8(i: Int) = s[i].toInt() and 0xFF
val rt = u8(0); val req = u8(1)
val wValue = u8(2) or (u8(3) shl 8)
val wIndex = u8(4) or (u8(5) shl 8)
val wLength = u8(6) or (u8(7) shl 8)
if (rt == 0x80 && req == 0x06 && (wValue shr 8) == 0x02) {
// GET_DESCRIPTOR(CONFIGURATION): export only interface 0 (FIDO).
// Fetch the real descriptor in full, strip the CCID/other
// interfaces, then honour the client's requested length.
val full = backend.control(0x80, 0x06, wValue, wIndex, ByteArray(0), 0xFF, timeoutMs)
filterToFidoInterface(full).let { it.copyOf(minOf(it.size, wLength)) }
} else {
backend.control(rt, req, wValue, wIndex, urb.out, wLength, timeoutMs)
}
} else {
val address = urb.ep or if (isIn) 0x80 else 0x00
backend.bulk(address, urb.out, urb.transferBufferLength, timeoutMs)
}
val actualLength = if (isIn) inData.size else urb.transferBufferLength
UsbIpProtocol.encodeSubmitReply(urb.seqnum, status = 0, actualLength = actualLength, inData = if (isIn) inData else ByteArray(0))
} catch (e: Exception) {
Log.w(TAG, "URB seq=${urb.seqnum} ep=${urb.ep} failed: ${e.message}")
UsbIpProtocol.encodeSubmitReply(urb.seqnum, status = -EPIPE, actualLength = 0, inData = ByteArray(0))
}
/**
* Service an interrupt/bulk IN URB by polling in [pollMs] slices, keeping
* it pending (no reply) until data arrives or the client unlinks it. This
* is the correct interrupt-endpoint semantic and, given Android serializes
* transfers per connection, stops an idle standing read (e.g. a composite
* key's CCID status poll, or a FIDO key between commands) from wedging its
* lane or disrupting the endpoint with a long timeout-failure. Returns the
* RET_SUBMIT bytes once data arrives, or null if unlinked/interrupted first.
*/
fun pollIn(urb: UsbIpProtocol.Urb.Submit, backend: UsbIpBackend, cancelled: Set<Int>, pollMs: Int): ByteArray? {
val address = urb.ep or 0x80
// backend.isAlive() guard: a standing interrupt-IN poll on an idle
// connection must exit when the device is unplugged, not spin on
// failing transfers until the client happens to send another URB.
while (urb.seqnum !in cancelled && !Thread.currentThread().isInterrupted && backend.isAlive()) {
val data = try {
backend.bulk(address, urb.out, urb.transferBufferLength, pollMs)
} catch (e: Exception) {
ByteArray(0) // NAK / no data this slice — keep the URB pending
}
if (data.isNotEmpty()) {
return UsbIpProtocol.encodeSubmitReply(urb.seqnum, status = 0, actualLength = data.size, inData = data)
}
}
return null
}
/**
* Reduce a full CONFIGURATION descriptor to just interface 0 (the FIDO
* HID function), dropping a composite key's CCID/other interfaces. The
* remote host then never binds or polls them — their traffic (e.g. pcscd
* hammering the smartcard interface) would otherwise starve FIDO on
* Android's serialized [UsbDeviceConnection]. Left unchanged if [config]
* isn't a configuration descriptor or is too short to parse.
*/
fun filterToFidoInterface(config: ByteArray): ByteArray {
if (config.size < 9 || (config[1].toInt() and 0xFF) != 0x02) return config
// Interface-0-only is the FIDO case (a composite key whose CCID interface
// would starve FIDO on Android's serialized connection). Any other device
// keeps its whole config — e.g. a CDC serial adapter's data interface is
// #1, and stripping it drops the bulk endpoints the host's cdc_acm needs.
if (!interface0IsHid(config)) return config
val body = ArrayList<Byte>()
var i = 9
var keep = false
while (i + 2 <= config.size) {
val len = config[i].toInt() and 0xFF
if (len < 2 || i + len > config.size) break
if ((config[i + 1].toInt() and 0xFF) == 0x04) { // INTERFACE descriptor
keep = (config[i + 2].toInt() and 0xFF) == 0 // keep only interface 0
}
if (keep) for (j in i until i + len) body.add(config[j])
i += len
}
if (body.isEmpty()) return config // no interface 0 found — don't break enumeration
val total = 9 + body.size
val out = ByteArray(total)
System.arraycopy(config, 0, out, 0, 9)
for (k in body.indices) out[9 + k] = body[k]
out[2] = (total and 0xFF).toByte() // wTotalLength lo
out[3] = ((total shr 8) and 0xFF).toByte() // wTotalLength hi
out[4] = 1 // bNumInterfaces
return out
}
/**
* True when the CONFIGURATION descriptor's interface 0 is HID (class 0x03) —
* the only case we strip to interface-0-only (a FIDO key). Walks to the first
* INTERFACE descriptor with bInterfaceNumber 0 and reads its bInterfaceClass.
*/
fun interface0IsHid(config: ByteArray): Boolean {
if (config.size < 9 || (config[1].toInt() and 0xFF) != 0x02) return false
var i = 9
while (i + 2 <= config.size) {
val len = config[i].toInt() and 0xFF
if (len < 2 || i + len > config.size) break
if ((config[i + 1].toInt() and 0xFF) == 0x04 && len >= 6 &&
(config[i + 2].toInt() and 0xFF) == 0
) {
return (config[i + 5].toInt() and 0xFF) == 0x03
}
i += len
}
return false
}
/** -EPIPE: the closest generic "transfer failed" errno the vhci client maps. */
private const val EPIPE = 32
}
}
/** Transfer backend the URB bridge drives — [BrokerBackend] in prod, a fake in tests. */
interface UsbIpBackend {
/** Endpoint-0 control transfer; returns IN data (empty for OUT). Throws on failure. */
fun control(requestType: Int, request: Int, value: Int, index: Int, out: ByteArray, length: Int, timeoutMs: Int): ByteArray
/** Bulk/interrupt on the full endpoint address; returns IN data (empty for OUT). Throws on failure. */
fun bulk(endpointAddress: Int, out: ByteArray, length: Int, timeoutMs: Int): ByteArray
/** False once the device handle is gone (unplug / re-enumeration), so standing polls bail. */
fun isAlive(): Boolean
}
/** [UsbIpBackend] backed by the Android [UsbBroker]. */
class BrokerBackend(private val broker: UsbBroker, private val deviceName: String) : UsbIpBackend {
override fun control(requestType: Int, request: Int, value: Int, index: Int, out: ByteArray, length: Int, timeoutMs: Int): ByteArray =
broker.controlTransfer(deviceName, requestType, request, value, index, out, length, timeoutMs).data
override fun bulk(endpointAddress: Int, out: ByteArray, length: Int, timeoutMs: Int): ByteArray =
broker.bulkTransfer(deviceName, endpointAddress, out, length, timeoutMs).data
override fun isAlive(): Boolean = broker.isOpen(deviceName)
}
@@ -0,0 +1,57 @@
package sh.haven.core.usb
/** Endpoint descriptor as surfaced to the agent. */
data class UsbEndpointInfo(
/** bEndpointAddress (bit 7 = direction). */
val address: Int,
/** "in" or "out". */
val direction: String,
/** "control" | "isochronous" | "bulk" | "interrupt" | "unknown". */
val type: String,
val maxPacketSize: Int,
)
/** Interface descriptor as surfaced to the agent. */
data class UsbInterfaceInfo(
val id: Int,
val interfaceClass: Int,
val interfaceSubclass: Int,
val interfaceProtocol: Int,
val endpoints: List<UsbEndpointInfo>,
)
/**
* A snapshot of one attached USB device. Descriptor strings are null until
* permission is held; [hasPermission] tells the caller whether to request it.
*/
data class UsbDeviceInfo(
/** Stable key for this attachment: the `/dev/bus/usb/BBB/DDD` path. */
val deviceName: String,
val vendorId: Int,
val productId: Int,
val deviceClass: Int,
val manufacturerName: String?,
val productName: String?,
val serialNumber: String?,
val hasPermission: Boolean,
val isOpen: Boolean,
val interfaces: List<UsbInterfaceInfo>,
) {
/** "1234:5678" VID:PID, the conventional lsusb form. */
val vidPid: String get() = "%04x:%04x".format(vendorId, productId)
}
/** Result of a control/bulk transfer: bytes moved, plus data read on IN. */
data class TransferResult(
val bytesTransferred: Int,
/** Data read for IN transfers; empty for OUT. */
val data: ByteArray,
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is TransferResult) return false
return bytesTransferred == other.bytesTransferred && data.contentEquals(other.data)
}
override fun hashCode(): Int = 31 * bytesTransferred + data.contentHashCode()
}
@@ -0,0 +1,189 @@
package sh.haven.core.usb
import java.io.DataInputStream
import java.io.DataOutputStream
import java.io.EOFException
/**
* Wire protocol for the USB proxy socket (Slice 2+).
*
* The guest shim ([libhaven_usb.so], via LD_PRELOAD or Mono DllMap) speaks this
* to the [UsbProxyServer] over an abstract `LocalSocket`; the server fulfils
* each request against the brokered [UsbDeviceConnection]. Keeping all USB I/O
* on the Android side means the shim never needs a real device node or root.
*
* Frame: `u32 length` (of opcode+payload, big-endian) · `u8 opcode` · payload.
* Big-endian throughout for predictable C-side parsing.
*
* Request payloads:
* - GET_DESCRIPTORS: empty.
* - CONTROL: u8 requestType, u8 request, u16 value, u16 index, u16 length,
* u32 timeoutMs, then `length`/data bytes (OUT payload; empty for IN).
* - BULK: u8 endpoint, u32 length, u32 timeoutMs, then data bytes (OUT only).
* - CLOSE: empty.
*
* Response payload: `i32 status` (>=0 = bytes transferred, <0 = error) followed
* by `status` data bytes for IN/descriptor reads (absent on error or OUT).
*/
object UsbProxyProtocol {
const val OP_GET_DESCRIPTORS: Int = 0x02
const val OP_CONTROL: Int = 0x03
const val OP_BULK: Int = 0x04
const val OP_CLOSE: Int = 0x05
/** Max frame payload we'll read, a guard against a desync corrupting length. */
const val MAX_FRAME: Int = 1 shl 20 // 1 MiB
sealed interface Request {
data object GetDescriptors : Request
data class Control(
val requestType: Int,
val request: Int,
val value: Int,
val index: Int,
val length: Int,
val timeoutMs: Int,
val data: ByteArray,
) : Request {
override fun equals(other: Any?) = other is Control &&
requestType == other.requestType && request == other.request &&
value == other.value && index == other.index && length == other.length &&
timeoutMs == other.timeoutMs && data.contentEquals(other.data)
override fun hashCode(): Int {
var h = requestType
h = 31 * h + request; h = 31 * h + value; h = 31 * h + index
h = 31 * h + length; h = 31 * h + timeoutMs; h = 31 * h + data.contentHashCode()
return h
}
}
data class Bulk(
val endpoint: Int,
val length: Int,
val timeoutMs: Int,
val data: ByteArray,
) : Request {
override fun equals(other: Any?) = other is Bulk &&
endpoint == other.endpoint && length == other.length &&
timeoutMs == other.timeoutMs && data.contentEquals(other.data)
override fun hashCode(): Int {
var h = endpoint; h = 31 * h + length; h = 31 * h + timeoutMs
h = 31 * h + data.contentHashCode(); return h
}
}
data object Close : Request
}
data class Response(val status: Int, val data: ByteArray) {
override fun equals(other: Any?) = other is Response &&
status == other.status && data.contentEquals(other.data)
override fun hashCode(): Int = 31 * status + data.contentHashCode()
}
// ---- Request encode/decode -------------------------------------------
fun encodeRequest(req: Request): ByteArray {
val body = when (req) {
Request.GetDescriptors -> byteArrayOf(OP_GET_DESCRIPTORS.toByte())
Request.Close -> byteArrayOf(OP_CLOSE.toByte())
is Request.Control -> buildBytes {
writeByte(OP_CONTROL)
writeByte(req.requestType)
writeByte(req.request)
writeShort(req.value)
writeShort(req.index)
writeShort(req.length)
writeInt(req.timeoutMs)
write(req.data)
}
is Request.Bulk -> buildBytes {
writeByte(OP_BULK)
writeByte(req.endpoint)
writeInt(req.length)
writeInt(req.timeoutMs)
write(req.data)
}
}
return frame(body)
}
/** Read one request frame from [input], or null at clean end-of-stream. */
fun readRequest(input: DataInputStream): Request? {
val body = readFrame(input) ?: return null
val payload = DataInputStream(body.inputStream())
return when (val op = payload.readUnsignedByte()) {
OP_GET_DESCRIPTORS -> Request.GetDescriptors
OP_CLOSE -> Request.Close
OP_CONTROL -> {
val requestType = payload.readUnsignedByte()
val request = payload.readUnsignedByte()
val value = payload.readUnsignedShort()
val index = payload.readUnsignedShort()
val length = payload.readUnsignedShort()
val timeoutMs = payload.readInt()
val data = payload.readBytes()
Request.Control(requestType, request, value, index, length, timeoutMs, data)
}
OP_BULK -> {
val endpoint = payload.readUnsignedByte()
val length = payload.readInt()
val timeoutMs = payload.readInt()
val data = payload.readBytes()
Request.Bulk(endpoint, length, timeoutMs, data)
}
else -> throw IllegalArgumentException("unknown opcode $op")
}
}
// ---- Response encode/decode ------------------------------------------
fun encodeResponse(resp: Response): ByteArray = frame(buildBytes {
writeInt(resp.status)
if (resp.status > 0) write(resp.data)
})
fun readResponse(input: DataInputStream): Response {
val body = readFrame(input) ?: throw EOFException("stream closed before response")
val payload = DataInputStream(body.inputStream())
val status = payload.readInt()
val data = if (status > 0) payload.readBytes() else ByteArray(0)
return Response(status, data)
}
// ---- Framing helpers -------------------------------------------------
private fun frame(body: ByteArray): ByteArray = buildBytes {
writeInt(body.size)
write(body)
}
private fun readFrame(input: DataInputStream): ByteArray? {
val len = try {
input.readInt()
} catch (_: EOFException) {
return null
}
require(len in 1..MAX_FRAME) { "frame length $len out of range" }
val buf = ByteArray(len)
input.readFully(buf)
return buf
}
/** Read all remaining bytes. (Not InputStream.readAllBytes — that's API 33+, minSdk is 26.) */
private fun DataInputStream.readBytes(): ByteArray {
val out = java.io.ByteArrayOutputStream()
val buf = ByteArray(4096)
while (true) {
val n = read(buf)
if (n < 0) break
out.write(buf, 0, n)
}
return out.toByteArray()
}
private inline fun buildBytes(block: DataOutputStream.() -> Unit): ByteArray {
val bos = java.io.ByteArrayOutputStream()
DataOutputStream(bos).use { it.block() }
return bos.toByteArray()
}
}
@@ -0,0 +1,136 @@
package sh.haven.core.usb
import android.net.LocalServerSocket
import android.net.LocalSocket
import android.util.Log
import java.io.DataInputStream
import java.io.DataOutputStream
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.concurrent.thread
/**
* Serves the [UsbProxyProtocol] over an abstract-namespace `LocalSocket` so a
* guest shim inside the proot can drive a brokered USB device.
*
* The socket lives in the abstract namespace (`\0haven-usb`), which is part of
* the network namespace. proot does not isolate the network namespace, so the
* proot tracee shares it with the Android app and can `connect()` to the same
* abstract name — that reachability is the Slice-2 gate. (If it ever fails on
* some device, the fallback is a filesystem-path socket under the cacheDir
* `/tmp` bind; the protocol is transport-agnostic.)
*
* One server instance proxies one opened device, identified by [deviceName].
* Every accepted connection issues requests against that device through
* [UsbBroker]; concurrent guest opens (e.g. udev probe + the app) all multiplex
* onto the same cached [android.hardware.usb.UsbDeviceConnection].
*/
@Singleton
class UsbProxyServer @Inject constructor(
private val broker: UsbBroker,
) {
@Volatile private var serverSocket: LocalServerSocket? = null
@Volatile private var deviceName: String? = null
private var acceptThread: Thread? = null
/** True while a proxy socket is bound. */
val isRunning: Boolean get() = serverSocket != null
/** The abstract socket name a guest connects to. */
val socketName: String get() = SOCKET_NAME
/** The device currently proxied to the guest (`/dev/bus/usb/...`), or null when stopped. */
val proxyDeviceName: String? get() = deviceName
/**
* Bind the proxy for [deviceName] (which must already be opened via
* [UsbBroker.openDevice]). Idempotent for the same device; rebinds for a
* different one. Returns the abstract socket name to hand the guest.
*/
@Synchronized
fun start(deviceName: String): String {
if (serverSocket != null && this.deviceName == deviceName) return SOCKET_NAME
stop()
val socket = LocalServerSocket(SOCKET_NAME)
serverSocket = socket
this.deviceName = deviceName
acceptThread = thread(name = "haven-usb-proxy", isDaemon = true) {
Log.i(TAG, "USB proxy listening on \\0$SOCKET_NAME for $deviceName")
while (serverSocket === socket) {
val client = try {
socket.accept()
} catch (e: Exception) {
if (serverSocket === socket) Log.w(TAG, "accept failed: ${e.message}")
break
}
thread(name = "haven-usb-conn", isDaemon = true) { serve(client, deviceName) }
}
}
return SOCKET_NAME
}
@Synchronized
fun stop() {
serverSocket?.let { runCatching { it.close() } }
serverSocket = null
deviceName = null
acceptThread = null
}
private fun serve(client: LocalSocket, device: String) {
client.use { sock ->
val input = DataInputStream(sock.inputStream)
val output = DataOutputStream(sock.outputStream)
while (true) {
val req = try {
UsbProxyProtocol.readRequest(input)
} catch (e: Exception) {
Log.w(TAG, "read request failed: ${e.message}")
break
} ?: break
val resp = handle(device, req)
if (resp == null) break // CLOSE
try {
output.write(UsbProxyProtocol.encodeResponse(resp))
output.flush()
} catch (e: Exception) {
Log.w(TAG, "write response failed: ${e.message}")
break
}
}
}
}
/** @return the response, or null for CLOSE (ends the connection). */
private fun handle(device: String, req: UsbProxyProtocol.Request): UsbProxyProtocol.Response? =
try {
when (req) {
UsbProxyProtocol.Request.GetDescriptors -> {
val raw = broker.rawDescriptors(device)
UsbProxyProtocol.Response(raw.size, raw)
}
is UsbProxyProtocol.Request.Control -> {
val r = broker.controlTransfer(
device, req.requestType, req.request, req.value, req.index,
req.data, req.length, req.timeoutMs,
)
UsbProxyProtocol.Response(r.bytesTransferred, r.data)
}
is UsbProxyProtocol.Request.Bulk -> {
val r = broker.bulkTransfer(device, req.endpoint, req.data, req.length, req.timeoutMs)
UsbProxyProtocol.Response(r.bytesTransferred, r.data)
}
UsbProxyProtocol.Request.Close -> null
}
} catch (e: Exception) {
// Surface as a negative status the shim maps to errno; -1 is generic.
Log.w(TAG, "request $req failed: ${e.message}")
UsbProxyProtocol.Response(-1, ByteArray(0))
}
companion object {
private const val TAG = "UsbProxyServer"
/** Abstract-namespace socket name (LocalSocket prepends the NUL). */
const val SOCKET_NAME: String = "haven-usb"
}
}
@@ -0,0 +1,71 @@
package sh.haven.core.usb
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class UsbAccessGateTest {
private val dev = "/dev/bus/usb/001/002"
@Test
fun `clear when nothing held`() {
val g = UsbAccessGate()
assertFalse(g.isHeld(dev))
assertTrue(g.awaitClear(dev, 1000))
}
@Test
fun `held after acquire, clear after release`() {
val g = UsbAccessGate()
g.acquire(dev)
assertTrue(g.isHeld(dev))
g.release(dev)
assertFalse(g.isHeld(dev))
}
@Test
fun `awaitClear returns false on timeout while held`() {
val g = UsbAccessGate()
g.acquire(dev)
val t0 = System.currentTimeMillis()
val cleared = g.awaitClear(dev, 80)
val elapsed = System.currentTimeMillis() - t0
assertFalse(cleared)
assertTrue("should wait roughly the timeout, waited ${elapsed}ms", elapsed >= 60)
}
@Test
fun `nested acquire needs matching releases`() {
val g = UsbAccessGate()
g.acquire(dev)
g.acquire(dev)
g.release(dev)
assertTrue(g.isHeld(dev))
g.release(dev)
assertFalse(g.isHeld(dev))
}
@Test
fun `awaitClear unblocks once another thread releases`() {
val g = UsbAccessGate()
g.acquire(dev)
val releaser = Thread {
Thread.sleep(50)
g.release(dev)
}
releaser.start()
val cleared = g.awaitClear(dev, 2000)
releaser.join()
assertTrue(cleared)
assertFalse(g.isHeld(dev))
}
@Test
fun `a lease on one device does not block another`() {
val g = UsbAccessGate()
g.acquire(dev)
// A different device must be clear even while dev is held.
assertTrue(g.awaitClear("/dev/bus/usb/001/003", 1000))
}
}
@@ -0,0 +1,385 @@
package sh.haven.core.usb
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.hardware.usb.UsbConstants
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbDeviceConnection
import android.hardware.usb.UsbEndpoint
import android.hardware.usb.UsbInterface
import android.hardware.usb.UsbManager
import io.mockk.every
import io.mockk.mockk
import io.mockk.slot
import io.mockk.verify
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeout
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* Unit coverage for [UsbBroker.listDevices] / describe(): the parts that run
* without the system permission round-trip or a live connection. Transfer
* dispatch is verified on-device (Slice 1 acceptance) since it routes entirely
* through Android framework objects.
*/
class UsbBrokerTest {
private fun endpoint(address: Int, dir: Int, type: Int): UsbEndpoint = mockk {
every { this@mockk.address } returns address
every { direction } returns dir
every { this@mockk.type } returns type
every { maxPacketSize } returns 64
}
private fun iface(id: Int, cls: Int, eps: List<UsbEndpoint>): UsbInterface = mockk {
every { this@mockk.id } returns id
every { interfaceClass } returns cls
every { interfaceSubclass } returns 0
every { interfaceProtocol } returns 0
every { endpointCount } returns eps.size
eps.forEachIndexed { i, ep -> every { getEndpoint(i) } returns ep }
}
private fun device(
name: String,
vid: Int,
pid: Int,
ifaces: List<UsbInterface>,
): UsbDevice = mockk {
every { deviceName } returns name
every { vendorId } returns vid
every { productId } returns pid
every { deviceClass } returns 0
every { manufacturerName } returns "Evolv"
every { productName } returns "DNA 100C"
every { serialNumber } returns "SN123"
every { interfaceCount } returns ifaces.size
ifaces.forEachIndexed { i, f -> every { getInterface(i) } returns f }
}
private fun broker(usbManager: UsbManager): UsbBroker {
val context: Context = mockk {
every { getSystemService(Context.USB_SERVICE) } returns usbManager
every { registerReceiver(any(), any()) } returns null
every { registerReceiver(any(), any(), any<Int>()) } returns null
}
return UsbBroker(context, UsbAccessGate())
}
@Test
fun `describes endpoints and interfaces`() {
val epIn = endpoint(0x81, UsbConstants.USB_DIR_IN, UsbConstants.USB_ENDPOINT_XFER_INT)
val epOut = endpoint(0x01, UsbConstants.USB_DIR_OUT, UsbConstants.USB_ENDPOINT_XFER_BULK)
val dev = device("/dev/bus/usb/001/004", 0x9999, 0x0001, listOf(
iface(0, UsbConstants.USB_CLASS_HID, listOf(epIn, epOut)),
))
val usb: UsbManager = mockk {
every { deviceList } returns hashMapOf(dev.deviceName to dev)
every { hasPermission(dev) } returns true
}
val info = broker(usb).listDevices().single()
assertEquals("/dev/bus/usb/001/004", info.deviceName)
assertEquals("9999:0001", info.vidPid)
assertTrue(info.hasPermission)
assertFalse(info.isOpen)
assertEquals("Evolv", info.manufacturerName)
assertEquals("DNA 100C", info.productName)
assertEquals("SN123", info.serialNumber)
val iface = info.interfaces.single()
assertEquals(UsbConstants.USB_CLASS_HID, iface.interfaceClass)
assertEquals(2, iface.endpoints.size)
val inEp = iface.endpoints.first { it.direction == "in" }
assertEquals(0x81, inEp.address)
assertEquals("interrupt", inEp.type)
val outEp = iface.endpoints.first { it.direction == "out" }
assertEquals("bulk", outEp.type)
}
@Test
fun `hides descriptor strings without permission`() {
val dev = device("/dev/bus/usb/001/005", 0x1, 0x2, emptyList())
val usb: UsbManager = mockk {
every { deviceList } returns hashMapOf(dev.deviceName to dev)
every { hasPermission(dev) } returns false
}
val info = broker(usb).listDevices().single()
assertFalse(info.hasPermission)
assertNull(info.manufacturerName)
assertNull(info.productName)
assertNull(info.serialNumber)
}
@Test
fun `a USB detach broadcast evicts the open handle`() = runBlocking {
val dev = device("/dev/bus/usb/001/006", 0x1, 0x2, emptyList())
val conn = mockk<UsbDeviceConnection>(relaxed = true)
val usb: UsbManager = mockk {
every { deviceList } returns hashMapOf(dev.deviceName to dev)
every { hasPermission(dev) } returns true
every { openDevice(dev) } returns conn
}
val recvSlot = slot<BroadcastReceiver>()
val context: Context = mockk {
every { getSystemService(Context.USB_SERVICE) } returns usb
every { registerReceiver(capture(recvSlot), any()) } returns null
every { registerReceiver(any(), any(), any<Int>()) } returns null
}
val broker = UsbBroker(context, UsbAccessGate())
broker.openDevice(dev.deviceName)
assertTrue(broker.isOpen(dev.deviceName))
// Fire the detach broadcast the receiver registered for (SDK_INT defaults
// to 0 in unit tests → the deprecated getParcelableExtra path).
val intent: Intent = mockk {
every { action } returns UsbManager.ACTION_USB_DEVICE_DETACHED
every { getParcelableExtra<UsbDevice>(UsbManager.EXTRA_DEVICE) } returns dev
}
recvSlot.captured.onReceive(context, intent)
// closeDevice now runs off the broadcast thread (on Dispatchers.IO) so a
// wedged device can't ANR the UI — await its completion before asserting.
repeat(200) { if (!broker.isOpen(dev.deviceName)) return@repeat; Thread.sleep(10) }
assertFalse(broker.isOpen(dev.deviceName))
verify(timeout = 2000) { conn.close() }
}
@Test
fun `a USB detach emits the device name on the detached flow`() = runBlocking {
val dev = device("/dev/bus/usb/001/011", 0x1, 0x2, emptyList())
val conn = mockk<UsbDeviceConnection>(relaxed = true)
val usb: UsbManager = mockk {
every { deviceList } returns hashMapOf(dev.deviceName to dev)
every { hasPermission(dev) } returns true
every { openDevice(dev) } returns conn
}
val recvSlot = slot<BroadcastReceiver>()
val context: Context = mockk {
every { getSystemService(Context.USB_SERVICE) } returns usb
every { registerReceiver(capture(recvSlot), any()) } returns null
every { registerReceiver(any(), any(), any<Int>()) } returns null
}
val broker = UsbBroker(context, UsbAccessGate())
broker.openDevice(dev.deviceName)
val received = CompletableDeferred<String>()
val collector = launch(Dispatchers.Default) { received.complete(broker.detached.first()) }
delay(100) // let the collector subscribe (SharedFlow replay=0)
val intent: Intent = mockk {
every { action } returns UsbManager.ACTION_USB_DEVICE_DETACHED
every { getParcelableExtra<UsbDevice>(UsbManager.EXTRA_DEVICE) } returns dev
}
recvSlot.captured.onReceive(context, intent)
assertEquals(dev.deviceName, withTimeout(2000) { received.await() })
collector.cancel()
}
@Test
fun `closeDevice serializes against in-flight transfers on the same connection`() = runBlocking {
// closeDevice's releaseInterface/close must hold the same connection
// monitor as the transfer paths, or a detach mid-export corrupts an
// in-flight transaction (and, off the main thread now, a raw close could
// race an export lane).
val epIn = endpoint(0x81, UsbConstants.USB_DIR_IN, UsbConstants.USB_ENDPOINT_XFER_BULK)
val dev = device(
"/dev/bus/usb/001/012", 0x1, 0x2,
listOf(iface(0, UsbConstants.USB_CLASS_MASS_STORAGE, listOf(epIn))),
)
val inCriticalSection = java.util.concurrent.atomic.AtomicBoolean(false)
val raceDetected = java.util.concurrent.atomic.AtomicBoolean(false)
fun <T> enterThenLeave(result: T): T {
if (!inCriticalSection.compareAndSet(false, true)) raceDetected.set(true)
Thread.sleep(15)
inCriticalSection.set(false)
return result
}
val conn: UsbDeviceConnection = mockk(relaxed = true) {
every { claimInterface(any(), any()) } returns true
every { bulkTransfer(any(), any(), any(), any()) } answers { enterThenLeave(8) }
every { close() } answers { enterThenLeave(Unit) }
}
val usb: UsbManager = mockk {
every { deviceList } returns hashMapOf(dev.deviceName to dev)
every { hasPermission(dev) } returns true
every { openDevice(dev) } returns conn
}
val broker = broker(usb)
broker.openDevice(dev.deviceName)
val transferThreads = (1..6).map {
Thread { repeat(8) { runCatching { broker.bulkTransfer(dev.deviceName, 0x81, null, 8, 1000) } } }
}
transferThreads.forEach { it.start() }
Thread.sleep(20) // let some transfers get in flight
val closeThread = Thread { broker.closeDevice(dev.deviceName) }
closeThread.start()
(transferThreads + closeThread).forEach { it.join() }
assertFalse("closeDevice overlapped a transfer on the same connection", raceDetected.get())
verify(exactly = 1) { conn.close() }
}
@Test
fun `controlTransfer and bulkTransfer never run concurrently on the same connection`() = runBlocking {
// Regression test for a real race found live: a keep-alive control
// transfer (UsbDriveVmManager, Dispatchers.IO) and a USB/IP export
// lane's bulk transfer (its own ExecutorService thread) both called
// into the same UsbDeviceConnection with no locking — corrupting an
// in-flight transfer and resetting the device mid-VM-boot.
val epIn = endpoint(0x81, UsbConstants.USB_DIR_IN, UsbConstants.USB_ENDPOINT_XFER_BULK)
val dev = device(
"/dev/bus/usb/001/007", 0x1, 0x2,
listOf(iface(0, UsbConstants.USB_CLASS_MASS_STORAGE, listOf(epIn))),
)
val inCriticalSection = java.util.concurrent.atomic.AtomicBoolean(false)
val raceDetected = java.util.concurrent.atomic.AtomicBoolean(false)
fun enterThenLeave(result: Int): Int {
if (!inCriticalSection.compareAndSet(false, true)) raceDetected.set(true)
Thread.sleep(15)
inCriticalSection.set(false)
return result
}
val conn: UsbDeviceConnection = mockk {
every { claimInterface(any(), any()) } returns true
every { controlTransfer(any(), any(), any(), any(), any(), any(), any()) } answers { enterThenLeave(2) }
every { bulkTransfer(any(), any(), any(), any()) } answers { enterThenLeave(8) }
}
val usb: UsbManager = mockk {
every { deviceList } returns hashMapOf(dev.deviceName to dev)
every { hasPermission(dev) } returns true
every { openDevice(dev) } returns conn
}
val broker = broker(usb)
broker.openDevice(dev.deviceName)
val threads = (1..8).map { i ->
Thread {
if (i % 2 == 0) {
repeat(5) { broker.controlTransfer(dev.deviceName, 0x80, 0, 0, 0, null, 2, 1000) }
} else {
repeat(5) { broker.bulkTransfer(dev.deviceName, 0x81, null, 8, 1000) }
}
}
}
threads.forEach { it.start() }
threads.forEach { it.join() }
assertFalse("controlTransfer and bulkTransfer overlapped on the same connection", raceDetected.get())
}
@Test
fun `a large OUT transfer is split into bounded chunks, not one call`() {
// Regression test for a real failure found live: a single bulkTransfer
// call above ~16KB can silently truncate on Android's synchronous USB
// API, desyncing the device's transaction state — cheap flash sticks
// respond to that by resetting instead of erroring cleanly. Reproduced
// with cryptsetup's LUKS-header wipe (a 15KB+ single write URB).
val epOut = endpoint(0x01, UsbConstants.USB_DIR_OUT, UsbConstants.USB_ENDPOINT_XFER_BULK)
val dev = device(
"/dev/bus/usb/001/008", 0x1, 0x2,
listOf(iface(0, UsbConstants.USB_CLASS_MASS_STORAGE, listOf(epOut))),
)
val callSizes = mutableListOf<Int>()
val conn: UsbDeviceConnection = mockk {
every { claimInterface(any(), any()) } returns true
every { bulkTransfer(any(), any(), any(), any(), any()) } answers {
val length = it.invocation.args[3] as Int
callSizes.add(length)
length
}
}
val usb: UsbManager = mockk {
every { deviceList } returns hashMapOf(dev.deviceName to dev)
every { hasPermission(dev) } returns true
every { openDevice(dev) } returns conn
}
val broker = broker(usb)
runBlocking { broker.openDevice(dev.deviceName) }
val totalSize = 40 * 1024 // well above the 16KB safe-chunk ceiling
val result = broker.bulkTransfer(dev.deviceName, 0x01, ByteArray(totalSize), totalSize, 5000)
assertEquals(totalSize, result.bytesTransferred)
assertTrue("expected multiple chunked calls, got ${callSizes.size}: $callSizes", callSizes.size > 1)
assertTrue("no single call should exceed the safe chunk size", callSizes.all { it <= 16 * 1024 })
}
@Test
fun `an interface-recipient control transfer claims that interface first`() {
// Regression for FIDO-over-USB/IP: usbhid's GET_DESCRIPTOR(REPORT) is an
// interface-recipient control request (bmRequestType 0x81). Android only
// routes those to a *claimed* interface — without the claim it stalls, we
// return -EPIPE, and the remote usbhid fails "can't add hid device: -32"
// (no hidraw ⇒ FIDO unusable). wIndex low byte selects the interface.
val ep = endpoint(0x84, UsbConstants.USB_DIR_IN, UsbConstants.USB_ENDPOINT_XFER_INT)
val if0 = iface(0, UsbConstants.USB_CLASS_HID, listOf(ep))
val dev = device("/dev/bus/usb/001/009", 0x1050, 0x0406, listOf(if0))
val conn: UsbDeviceConnection = mockk {
every { claimInterface(any(), any()) } returns true
every { controlTransfer(any(), any(), any(), any(), any(), any(), any()) } returns 0
}
val usb: UsbManager = mockk {
every { deviceList } returns hashMapOf(dev.deviceName to dev)
every { hasPermission(dev) } returns true
every { openDevice(dev) } returns conn
}
val broker = broker(usb)
runBlocking { broker.openDevice(dev.deviceName) }
// GET_DESCRIPTOR(REPORT) on interface 0: rt=0x81, req=0x06, wValue=0x2200.
broker.controlTransfer(dev.deviceName, 0x81, 0x06, 0x2200, 0, null, 64, 1000)
verify { conn.claimInterface(if0, true) }
}
@Test
fun `a device-recipient control transfer claims no interface`() {
// GET_DESCRIPTOR(DEVICE/CONFIG) is device-recipient (rt=0x80); it must go
// out on ep0 without claiming anything, or config enumeration would stall.
val ep = endpoint(0x84, UsbConstants.USB_DIR_IN, UsbConstants.USB_ENDPOINT_XFER_INT)
val if0 = iface(0, UsbConstants.USB_CLASS_HID, listOf(ep))
val dev = device("/dev/bus/usb/001/010", 0x1050, 0x0406, listOf(if0))
val conn: UsbDeviceConnection = mockk {
every { claimInterface(any(), any()) } returns true
every { controlTransfer(any(), any(), any(), any(), any(), any(), any()) } returns 0
}
val usb: UsbManager = mockk {
every { deviceList } returns hashMapOf(dev.deviceName to dev)
every { hasPermission(dev) } returns true
every { openDevice(dev) } returns conn
}
val broker = broker(usb)
runBlocking { broker.openDevice(dev.deviceName) }
broker.controlTransfer(dev.deviceName, 0x80, 0x06, 0x0200, 0, null, 64, 1000)
verify(exactly = 0) { conn.claimInterface(any(), any()) }
}
@Test
fun `transfer result equality is content-based`() {
val a = TransferResult(3, byteArrayOf(1, 2, 3))
val b = TransferResult(3, byteArrayOf(1, 2, 3))
val c = TransferResult(3, byteArrayOf(1, 2, 4))
assertEquals(a, b)
assertEquals(a.hashCode(), b.hashCode())
assertFalse(a == c)
}
}
@@ -0,0 +1,146 @@
package sh.haven.core.usb
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
import java.io.ByteArrayOutputStream
import java.io.DataInputStream
import java.io.DataOutputStream
/** Wire coverage for the server-side USB/IP protocol (Slice 0). */
class UsbIpProtocolTest {
private fun buildSubmit(
seqnum: Int,
direction: Int,
ep: Int,
transferBufferLength: Int,
setup: ByteArray,
out: ByteArray,
): ByteArray {
val bos = ByteArrayOutputStream()
DataOutputStream(bos).use { o ->
o.writeInt(UsbIpProtocol.CMD_SUBMIT)
o.writeInt(seqnum)
o.writeInt(0) // devid
o.writeInt(direction)
o.writeInt(ep)
o.writeInt(0) // transfer_flags
o.writeInt(transferBufferLength)
o.writeInt(0) // start_frame
o.writeInt(0) // number_of_packets
o.writeInt(0) // interval
o.write(setup)
if (direction == UsbIpProtocol.DIR_OUT) o.write(out)
}
return bos.toByteArray()
}
@Test
fun `import request round-trips busid`() {
val bos = ByteArrayOutputStream()
DataOutputStream(bos).use { o ->
o.writeShort(UsbIpProtocol.VERSION)
o.writeShort(UsbIpProtocol.OP_REQ_IMPORT)
o.writeInt(0)
val busid = "1-1".toByteArray(Charsets.US_ASCII)
o.write(busid); repeat(32 - busid.size) { o.writeByte(0) }
}
val req = UsbIpProtocol.readOpRequest(DataInputStream(bos.toByteArray().inputStream()))
assertEquals(UsbIpProtocol.OpRequest.Import("1-1"), req)
}
@Test
fun `import reply carries 312-byte device, null is bare failure`() {
val d = UsbIpProtocol.Device(
busid = "1-1", busnum = 1, devnum = 2, speed = 3,
idVendor = 0x1050, idProduct = 0x0406, bcdDevice = 0x0543,
deviceClass = 0, deviceSubClass = 0, deviceProtocol = 0,
configurationValue = 1, numConfigurations = 1, numInterfaces = 2,
)
assertEquals(8 + 312, UsbIpProtocol.encodeImportReply(d).size)
assertEquals(8, UsbIpProtocol.encodeImportReply(null).size)
}
@Test
fun `submit control IN round-trips header and setup`() {
// GET_DESCRIPTOR(device), wLength 0x12 — native little-endian setup.
val setup = byteArrayOf(0x80.toByte(), 6, 0x00, 0x01, 0, 0, 0x12, 0)
val frame = buildSubmit(7, UsbIpProtocol.DIR_IN, ep = 0, transferBufferLength = 0x12, setup = setup, out = ByteArray(0))
val urb = UsbIpProtocol.readUrb(DataInputStream(frame.inputStream())) as UsbIpProtocol.Urb.Submit
assertEquals(7, urb.seqnum)
assertEquals(UsbIpProtocol.DIR_IN, urb.direction)
assertEquals(0, urb.ep)
assertEquals(0x12, urb.transferBufferLength)
assertArrayEquals(setup, urb.setup)
assertEquals(0, urb.out.size)
}
@Test
fun `submit bulk OUT carries payload`() {
val payload = byteArrayOf(1, 2, 3, 4, 5)
val frame = buildSubmit(9, UsbIpProtocol.DIR_OUT, ep = 4, transferBufferLength = payload.size, setup = ByteArray(8), out = payload)
val urb = UsbIpProtocol.readUrb(DataInputStream(frame.inputStream())) as UsbIpProtocol.Urb.Submit
assertEquals(4, urb.ep)
assertArrayEquals(payload, urb.out)
}
@Test
fun `unlink parses target seqnum`() {
val bos = ByteArrayOutputStream()
DataOutputStream(bos).use { o ->
o.writeInt(UsbIpProtocol.CMD_UNLINK)
o.writeInt(11) // this command's seqnum
o.writeInt(0); o.writeInt(0); o.writeInt(0) // devid, direction, ep
o.writeInt(7) // unlink seqnum
repeat(6) { o.writeInt(0) } // padding
}
assertEquals(
UsbIpProtocol.Urb.Unlink(seqnum = 11, unlinkSeqnum = 7),
UsbIpProtocol.readUrb(DataInputStream(bos.toByteArray().inputStream())),
)
}
@Test
fun `submit reply appends IN data and sets actual_length`() {
val data = ByteArray(18) { it.toByte() }
val reply = UsbIpProtocol.encodeSubmitReply(seqnum = 7, status = 0, actualLength = data.size, inData = data)
assertEquals(48 + 18, reply.size)
DataInputStream(reply.inputStream()).use { din ->
assertEquals(UsbIpProtocol.RET_SUBMIT, din.readInt())
assertEquals(7, din.readInt())
din.readInt(); din.readInt(); din.readInt() // devid, direction, ep
assertEquals(0, din.readInt()) // status
assertEquals(18, din.readInt()) // actual_length
}
}
@Test
fun `OUT submit reply reports bytes sent with no payload`() {
val reply = UsbIpProtocol.encodeSubmitReply(seqnum = 5, status = 0, actualLength = 64, inData = ByteArray(0))
assertEquals(48, reply.size)
DataInputStream(reply.inputStream()).use { din ->
repeat(5) { din.readInt() } // command, seqnum, devid, direction, ep
assertEquals(0, din.readInt()) // status
assertEquals(64, din.readInt()) // actual_length = bytes sent
}
}
@Test
fun `error submit reply carries no data and zero length`() {
val reply = UsbIpProtocol.encodeSubmitReply(seqnum = 3, status = -32, actualLength = 64, inData = ByteArray(64))
assertEquals(48, reply.size)
DataInputStream(reply.inputStream()).use { din ->
repeat(5) { din.readInt() }
assertEquals(-32, din.readInt()) // status
assertEquals(0, din.readInt()) // actual_length zeroed on error
}
}
@Test
fun `clean end of stream yields null`() {
assertNull(UsbIpProtocol.readUrb(DataInputStream(ByteArray(0).inputStream())))
assertNull(UsbIpProtocol.readOpRequest(DataInputStream(ByteArray(0).inputStream())))
}
}
@@ -0,0 +1,133 @@
package sh.haven.core.usb
import io.mockk.every
import io.mockk.mockk
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import java.io.DataInputStream
import java.io.DataOutputStream
import java.net.InetSocketAddress
import java.net.Socket
/**
* Regression coverage for #287 multi-drive: [UsbIpServer.export] now shares
* one socket across multiple devices, dispatching each client's IMPORT
* request by busid (previously a single fixed device, ignoring the busid the
* wire protocol already carried). This exercises the real op handshake over
* a real socket against two exported devices, and confirms unexporting one
* doesn't affect the other still being served.
*/
class UsbIpServerMultiExportTest {
private val broker = mockk<UsbBroker>()
private val server = UsbIpServer(broker)
@After
fun tearDown() {
server.stop()
}
// 18-byte USB device descriptor: idVendor/idProduct little-endian at
// offsets 8-9 / 10-11 (the fields describeForImport reads).
private fun deviceDescriptor(idVendor: Int, idProduct: Int): ByteArray {
val b = ByteArray(18)
b[8] = (idVendor and 0xFF).toByte(); b[9] = ((idVendor shr 8) and 0xFF).toByte()
b[10] = (idProduct and 0xFF).toByte(); b[11] = ((idProduct shr 8) and 0xFF).toByte()
b[17] = 1 // numConfigurations
return b
}
/**
* Export on an ephemeral port instead of the real 3240. A dev machine that
* is actually using usbip (a live `usbip attach`, or Haven's own export
* forwarded over SSH) already holds 3240, and these tests would then fail
* with `BindException: Address already in use` through no fault of the code.
* Only the first export binds — later ones join the same socket and ignore
* the port — and [UsbIpServer.boundPort] reports whatever we actually got.
*/
private fun export(deviceName: String): String = server.export(deviceName, port = 0)
private fun sendImport(port: Int, busid: String): ImportReply {
Socket().use { sock ->
sock.connect(InetSocketAddress("127.0.0.1", port), 2000)
val out = DataOutputStream(sock.getOutputStream())
out.writeShort(UsbIpProtocol.VERSION)
out.writeShort(UsbIpProtocol.OP_REQ_IMPORT)
out.writeInt(0)
val busidBytes = ByteArray(32); busid.toByteArray(Charsets.US_ASCII).copyInto(busidBytes)
out.write(busidBytes)
out.flush()
val input = DataInputStream(sock.getInputStream())
input.readUnsignedShort() // version
input.readUnsignedShort() // OP_REP_IMPORT
val status = input.readInt()
if (status != 0) return ImportReply(ok = false, busid = null, idVendor = -1)
fun fixedString(len: Int): String {
val buf = ByteArray(len); input.readFully(buf)
val end = buf.indexOf(0.toByte()).let { if (it < 0) len else it }
return String(buf, 0, end, Charsets.US_ASCII)
}
fixedString(256) // path
val replyBusid = fixedString(32)
input.readInt(); input.readInt(); input.readInt() // busnum, devnum, speed
val idVendor = input.readUnsignedShort()
return ImportReply(ok = true, busid = replyBusid, idVendor = idVendor)
}
}
private data class ImportReply(val ok: Boolean, val busid: String?, val idVendor: Int)
@Test
fun `two exported devices dispatch to the right descriptors by busid`() {
every { broker.rawDescriptors("/dev/bus/usb/001/002") } returns deviceDescriptor(idVendor = 0x1111, idProduct = 0x2222)
every { broker.rawDescriptors("/dev/bus/usb/003/004") } returns deviceDescriptor(idVendor = 0x3333, idProduct = 0x4444)
val busid1 = export("/dev/bus/usb/001/002")
val busid2 = export("/dev/bus/usb/003/004")
assertEquals("1-2", busid1)
assertEquals("3-4", busid2)
val port = server.boundPort!!
val reply1 = sendImport(port, busid1)
val reply2 = sendImport(port, busid2)
assertTrue(reply1.ok); assertTrue(reply2.ok)
assertEquals(busid1, reply1.busid); assertEquals(0x1111, reply1.idVendor)
assertEquals(busid2, reply2.busid); assertEquals(0x3333, reply2.idVendor)
}
@Test
fun `unexporting one device leaves the other reachable`() {
every { broker.rawDescriptors("/dev/bus/usb/001/002") } returns deviceDescriptor(idVendor = 0x1111, idProduct = 0x2222)
every { broker.rawDescriptors("/dev/bus/usb/003/004") } returns deviceDescriptor(idVendor = 0x3333, idProduct = 0x4444)
val busid1 = export("/dev/bus/usb/001/002")
val busid2 = export("/dev/bus/usb/003/004")
val port = server.boundPort!!
server.unexport(busid1)
assertTrue("server should stay up — busid2 is still exported", server.isRunning)
val reply1 = sendImport(port, busid1)
val reply2 = sendImport(port, busid2)
assertTrue("unexported busid must fail the IMPORT", !reply1.ok)
assertTrue(reply2.ok); assertEquals(0x3333, reply2.idVendor)
server.unexport(busid2)
assertTrue("server should stop once nothing is exported", !server.isRunning)
}
@Test
fun `an unrequested busid is refused, not silently served`() {
every { broker.rawDescriptors("/dev/bus/usb/001/002") } returns deviceDescriptor(idVendor = 0x1111, idProduct = 0x2222)
export("/dev/bus/usb/001/002")
val port = server.boundPort!!
val reply = sendImport(port, "9-9")
assertTrue("an unexported busid must not get any device back", !reply.ok)
}
}
@@ -0,0 +1,207 @@
package sh.haven.core.usb
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertNotNull
import org.junit.Test
import java.io.DataInputStream
/** Coverage for the URB->transfer bridge (the device-independent half of Slice 0). */
class UsbIpServerTest {
/** Records the last call and returns canned IN data. */
private class FakeBackend(
private val inData: ByteArray = ByteArray(0),
private val fail: Boolean = false,
@Volatile var alive: Boolean = true,
) : UsbIpBackend {
var lastControl: IntArray? = null
var lastBulkEndpoint: Int? = null
var lastOut: ByteArray? = null
override fun isAlive(): Boolean = alive
override fun control(requestType: Int, request: Int, value: Int, index: Int, out: ByteArray, length: Int, timeoutMs: Int): ByteArray {
if (fail) throw java.io.IOException("boom")
lastControl = intArrayOf(requestType, request, value, index, length)
lastOut = out
return inData
}
override fun bulk(endpointAddress: Int, out: ByteArray, length: Int, timeoutMs: Int): ByteArray {
if (fail) throw java.io.IOException("boom")
lastBulkEndpoint = endpointAddress
lastOut = out
return inData
}
}
private fun submit(
seqnum: Int,
direction: Int,
ep: Int,
transferBufferLength: Int,
setup: ByteArray = ByteArray(8),
out: ByteArray = ByteArray(0),
) = UsbIpProtocol.Urb.Submit(
seqnum = seqnum, devid = 0, direction = direction, ep = ep,
transferFlags = 0, transferBufferLength = transferBufferLength, interval = 0,
setup = setup, out = out,
)
private fun replyStatusAndLength(reply: ByteArray): Pair<Int, Int> =
DataInputStream(reply.inputStream()).use { din ->
repeat(5) { din.readInt() } // command, seqnum, devid, direction, ep
din.readInt() to din.readInt() // status, actual_length
}
@Test
fun `control IN parses little-endian setup and returns data`() {
val backend = FakeBackend(inData = ByteArray(18) { it.toByte() })
// GET_DESCRIPTOR(device): bmRequestType 0x80, bRequest 6, wValue 0x0100, wIndex 0, wLength 0x12.
val setup = byteArrayOf(0x80.toByte(), 6, 0x00, 0x01, 0, 0, 0x12, 0)
val reply = UsbIpServer.bridgeSubmit(submit(1, UsbIpProtocol.DIR_IN, ep = 0, transferBufferLength = 0x12, setup = setup), backend, 1000)
assertArrayEquals(intArrayOf(0x80, 6, 0x0100, 0, 0x12), backend.lastControl)
val (status, actualLength) = replyStatusAndLength(reply)
assertEquals(0, status)
assertEquals(18, actualLength)
assertEquals(48 + 18, reply.size)
}
@Test
fun `interrupt IN maps ep to 0x80 address and carries data`() {
val backend = FakeBackend(inData = byteArrayOf(0xAA.toByte(), 0xBB.toByte()))
val reply = UsbIpServer.bridgeSubmit(submit(2, UsbIpProtocol.DIR_IN, ep = 4, transferBufferLength = 64), backend, 1000)
assertEquals(0x84, backend.lastBulkEndpoint)
val (status, actualLength) = replyStatusAndLength(reply)
assertEquals(0, status)
assertEquals(2, actualLength)
}
@Test
fun `interrupt OUT maps ep to plain address and reports bytes sent`() {
val backend = FakeBackend()
val payload = byteArrayOf(1, 2, 3, 4)
val reply = UsbIpServer.bridgeSubmit(submit(3, UsbIpProtocol.DIR_OUT, ep = 4, transferBufferLength = payload.size, out = payload), backend, 1000)
assertEquals(0x04, backend.lastBulkEndpoint)
assertArrayEquals(payload, backend.lastOut)
val (status, actualLength) = replyStatusAndLength(reply)
assertEquals(0, status)
assertEquals(4, actualLength) // bytes sent, no IN payload
assertEquals(48, reply.size)
}
@Test
fun `pollIn returns an IN reply once data arrives`() {
val backend = FakeBackend(inData = byteArrayOf(0xAA.toByte(), 0xBB.toByte()))
val reply = UsbIpServer.pollIn(submit(5, UsbIpProtocol.DIR_IN, ep = 4, transferBufferLength = 64), backend, emptySet(), 10)
assertNotNull(reply)
assertEquals(0x84, backend.lastBulkEndpoint)
val (status, actualLength) = replyStatusAndLength(reply!!)
assertEquals(0, status)
assertEquals(2, actualLength)
}
@Test
fun `pollIn stops without polling once the device is gone`() {
// A standing interrupt-IN poll on an idle connection must bail when the
// device is unplugged / re-enumerated, not spin on failing transfers.
val backend = FakeBackend(inData = byteArrayOf(1), alive = false)
val reply = UsbIpServer.pollIn(submit(7, UsbIpProtocol.DIR_IN, ep = 4, transferBufferLength = 64), backend, emptySet(), 10)
assertNull(reply)
assertNull(backend.lastBulkEndpoint) // never touched the dead device
}
@Test
fun `pollIn drops an already-unlinked URB without polling`() {
val backend = FakeBackend(inData = byteArrayOf(1))
val reply = UsbIpServer.pollIn(submit(6, UsbIpProtocol.DIR_IN, ep = 4, transferBufferLength = 64), backend, setOf(6), 10)
assertNull(reply)
assertNull(backend.lastBulkEndpoint) // never touched the device
}
@Test
fun `filterToFidoInterface keeps only interface 0 and drops CCID`() {
fun bytes(vararg v: Int) = ByteArray(v.size) { v[it].toByte() }
val iface0 = bytes(9, 0x04, 0, 0, 2, 3, 0, 0, 0) + // interface 0, class 3 (HID)
bytes(7, 0x05, 0x04, 0x03, 64, 0, 1) + bytes(7, 0x05, 0x84, 0x03, 64, 0, 1)
val iface1 = bytes(9, 0x04, 1, 0, 2, 11, 0, 0, 0) + // interface 1, class 11 (CCID)
bytes(7, 0x05, 0x02, 0x02, 64, 0, 0) + bytes(7, 0x05, 0x82, 0x02, 64, 0, 0)
val header = bytes(9, 0x02, 0, 0, 2, 1, 0, 0x80, 50)
val full = header + iface0 + iface1
full[2] = (full.size and 0xFF).toByte()
full[3] = ((full.size shr 8) and 0xFF).toByte()
val filtered = UsbIpServer.filterToFidoInterface(full)
assertEquals(1, filtered[4].toInt()) // bNumInterfaces
assertEquals(9 + iface0.size, filtered.size) // header + interface-0 block only
val wTotal = (filtered[2].toInt() and 0xFF) or ((filtered[3].toInt() and 0xFF) shl 8)
assertEquals(filtered.size, wTotal) // corrected wTotalLength
}
@Test
fun `filterToFidoInterface passes a CDC serial config through unchanged`() {
fun bytes(vararg v: Int) = ByteArray(v.size) { v[it].toByte() }
// ESP32-S3 shape: interface 0 = CDC control (class 2), interface 1 = CDC data
// (class 10) with the bulk endpoints. Stripping #1 would kill cdc_acm binding.
val iface0 = bytes(9, 0x04, 0, 0, 1, 2, 2, 0, 0) + // interface 0, class 2 (CDC control)
bytes(7, 0x05, 0x83, 0x03, 64, 0, 1) // interrupt IN
val iface1 = bytes(9, 0x04, 1, 0, 2, 10, 0, 0, 0) + // interface 1, class 10 (CDC data)
bytes(7, 0x05, 0x02, 0x02, 64, 0, 0) + bytes(7, 0x05, 0x82, 0x02, 64, 0, 0)
val header = bytes(9, 0x02, 0, 0, 2, 1, 0, 0x80, 50)
val full = header + iface0 + iface1
full[2] = (full.size and 0xFF).toByte()
full[3] = ((full.size shr 8) and 0xFF).toByte()
val filtered = UsbIpServer.filterToFidoInterface(full)
assertArrayEquals(full, filtered) // untouched: both interfaces kept
assertEquals(2, filtered[4].toInt()) // bNumInterfaces still 2
assertEquals(false, UsbIpServer.interface0IsHid(full))
}
@Test
fun `transfer failure becomes negative-errno reply`() {
val reply = UsbIpServer.bridgeSubmit(submit(4, UsbIpProtocol.DIR_IN, ep = 4, transferBufferLength = 64), FakeBackend(fail = true), 1000)
val (status, actualLength) = replyStatusAndLength(reply)
assertEquals(-32, status) // -EPIPE
assertEquals(0, actualLength)
assertEquals(48, reply.size)
}
// #506: a SuperSpeed flash drive imported as high-speed fails guest
// enumeration ("Invalid ep0 maxpacket: 9"). Speed detection must report SUPER.
private fun configWithBulk(mps: Int): ByteArray {
fun bytes(vararg v: Int) = ByteArray(v.size) { v[it].toByte() }
val iface = bytes(9, 0x04, 0, 0, 2, 8, 6, 50, 0) + // mass-storage interface
bytes(7, 0x05, 0x81, 0x02, mps and 0xFF, (mps shr 8) and 0xFF, 0) +
bytes(7, 0x05, 0x02, 0x02, mps and 0xFF, (mps shr 8) and 0xFF, 0)
val header = bytes(9, 0x02, 0, 0, 1, 1, 0, 0x80, 50)
header[2] = ((header.size + iface.size) and 0xFF).toByte()
header[3] = (((header.size + iface.size) shr 8) and 0xFF).toByte()
return header + iface
}
@Test
fun `detectSpeed full-speed bulk 64 reports FULL`() {
assertEquals(2, UsbIpServer.detectSpeed(configWithBulk(64), ep0MaxPacket = 64))
}
@Test
fun `detectSpeed high-speed bulk 512 reports HIGH`() {
assertEquals(3, UsbIpServer.detectSpeed(configWithBulk(512), ep0MaxPacket = 64))
}
@Test
fun `detectSpeed super-speed bulk 1024 reports SUPER`() {
assertEquals(4, UsbIpServer.detectSpeed(configWithBulk(1024), ep0MaxPacket = 9))
}
@Test
fun `detectSpeed ep0 maxpacket 9 promotes to SUPER even at bulk 512`() {
// SS device whose config only shows 512-byte endpoints; the encoded
// ep0 size 9 (512 @ SuperSpeed) is the decisive signal.
assertEquals(4, UsbIpServer.detectSpeed(configWithBulk(512), ep0MaxPacket = 9))
}
}
@@ -0,0 +1,78 @@
package sh.haven.core.usb
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
import java.io.DataInputStream
/** Round-trip coverage for the USB proxy wire protocol (Slice 2). */
class UsbProxyProtocolTest {
private fun roundTripRequest(req: UsbProxyProtocol.Request): UsbProxyProtocol.Request? {
val bytes = UsbProxyProtocol.encodeRequest(req)
return UsbProxyProtocol.readRequest(DataInputStream(bytes.inputStream()))
}
private fun roundTripResponse(resp: UsbProxyProtocol.Response): UsbProxyProtocol.Response {
val bytes = UsbProxyProtocol.encodeResponse(resp)
return UsbProxyProtocol.readResponse(DataInputStream(bytes.inputStream()))
}
@Test
fun `get descriptors and close round-trip`() {
assertEquals(UsbProxyProtocol.Request.GetDescriptors, roundTripRequest(UsbProxyProtocol.Request.GetDescriptors))
assertEquals(UsbProxyProtocol.Request.Close, roundTripRequest(UsbProxyProtocol.Request.Close))
}
@Test
fun `control request round-trips fields and payload`() {
val req = UsbProxyProtocol.Request.Control(
requestType = 0x21, request = 9, value = 0x0300, index = 0,
length = 0, timeoutMs = 1000, data = byteArrayOf(1, 2, 3, 4, 5),
)
assertEquals(req, roundTripRequest(req))
}
@Test
fun `control IN request preserves wide unsigned fields`() {
// requestType 0x80 (IN), wValue/wIndex at full u16 range.
val req = UsbProxyProtocol.Request.Control(
requestType = 0x80, request = 6, value = 0xFF00, index = 0xFFFF,
length = 64, timeoutMs = 2000, data = ByteArray(0),
)
assertEquals(req, roundTripRequest(req))
}
@Test
fun `bulk request round-trips`() {
val req = UsbProxyProtocol.Request.Bulk(
endpoint = 0x81, length = 64, timeoutMs = 500, data = ByteArray(0),
)
assertEquals(req, roundTripRequest(req))
val out = UsbProxyProtocol.Request.Bulk(
endpoint = 0x01, length = 0, timeoutMs = 500, data = byteArrayOf(9, 8, 7),
)
assertEquals(out, roundTripRequest(out))
}
@Test
fun `response with data round-trips`() {
val descriptor = byteArrayOf(0x12, 0x01, 0x00, 0x02, 0xEF.toByte(), 0x02, 0x01, 0x40)
assertEquals(
UsbProxyProtocol.Response(descriptor.size, descriptor),
roundTripResponse(UsbProxyProtocol.Response(descriptor.size, descriptor)),
)
}
@Test
fun `error response carries no data`() {
val resp = roundTripResponse(UsbProxyProtocol.Response(-110, byteArrayOf(1, 2, 3)))
assertEquals(-110, resp.status)
assertEquals(0, resp.data.size)
}
@Test
fun `clean end of stream yields null request`() {
assertNull(UsbProxyProtocol.readRequest(DataInputStream(ByteArray(0).inputStream())))
}
}