Files
usb-server/internal/usb/descriptors.go
duffyduckandClaude Opus 5 9ed473a965 Fix HID transfers, harden the tunnel, add E2E crypto and direct peers
The HID failure came down to the endpoint type map being indexed by
endpoint number without the direction bit. A composite device can have
endpoint 1 as both interrupt IN (0x81) and bulk OUT (0x01); the last one
read won, so interrupt URBs were submitted as bulk and the kernel rejected
them. The device attached and stayed silent.

Endpoint data now comes from the raw descriptors read from /dev/bus/usb
rather than sysfs, which only ever exposes the active alternate setting —
a webcam's isochronous endpoints are invisible there because they only
exist after SET_INTERFACE. Two sysfs parsing bugs fell out of that too:
the numeric endpoint attributes are hex without a prefix (wMaxPacketSize
"0040" was read as 40, not 64), and bInterval was never read at all.

Reliability: three places could freeze the whole process. The share path
fed io.Pipe from the WebSocket read loop, so one slow USB transfer stalled
every tunnel and the keepalives with them. The relay wrote to client
sockets while holding the hub lock, so one peer that stopped reading
blocked routing and registration for everyone. Control transfers ran
inline in the protocol loop behind a 5s timeout. Also fixed: a use-after-
free where a discarded URB's memory could be collected while the kernel
still owned it, a reap loop that spun at 100% CPU on ioctl errors, a
missing attach timeout, a double close(done) panic, and Hash[:8] in the
relay's log line, which let a client with a short hash take the server
down.

Adds mode "both", so one client can offer and consume devices at once.
The tunnel and client-left callbacks became multicast for it: as plain
fields the second manager to register silently unhooked the first.

Tunnel traffic is now AES-256-GCM end to end, on the relay path as well
as directly. The key is derived from the three tokens, not from the group
hash — the relay is told the hash, so a key derived from it would protect
nothing from the one party in the middle. Group IDs are unchanged, so
existing setups keep working; only clients configured without the tokens
drop to unencrypted, relay-only operation.

Peers now try to connect directly, with the relay supplying the public
address neither side can determine for itself. Candidates are raced
because an unreachable address hangs until timeout rather than refusing.
Falling back to the relay is not an error.

Platform reach: cross-compiled targets for ARM, MIPS and RISC-V (the
Linux client needed no code changes — usbdevfs is not architecture
specific), multi-arch Docker images, an Android bridge that accepts
devices over SCM_RIGHTS because apps cannot open /dev/bus/usb, and macOS
builds via system_profiler enumeration.

Adds a Windows KMDF filter driver under driver/windows with its Go side.
UNTESTED: it has never been compiled or run, needs the WDK to build and
an EV certificate to distribute. Treat it as a starting point.

Adds "usb-client diag": says per machine whether sharing and using are
possible, what stands in the way, and what fixes it. Reports can be
uploaded to a relay to get them off machines that are awkward to copy
from.

96 tests, all green under -race. Builds for linux, windows and darwin on
amd64 and arm64.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-11 22:02:04 +02:00

170 lines
5.0 KiB
Go

package usb
import (
"encoding/binary"
"fmt"
)
// USB descriptor types
const (
DescTypeDevice = 0x01
DescTypeConfiguration = 0x02
DescTypeInterface = 0x04
DescTypeEndpoint = 0x05
)
// ParsedDescriptors holds everything we extract from a device's raw
// descriptor blob (device descriptor followed by all configuration
// descriptors, as returned by reading a usbdevfs device file).
type ParsedDescriptors struct {
VendorID uint16
ProductID uint16
BcdDevice uint16
DeviceClass uint8
DeviceSubClass uint8
DeviceProtocol uint8
NumConfigs uint8
// Configs holds every configuration, each with every interface
// alternate setting and its endpoints.
Configs []ConfigDescriptor
}
// ConfigDescriptor is one USB configuration
type ConfigDescriptor struct {
Value uint8 // bConfigurationValue
Interfaces []Interface // every alternate setting, in descriptor order
}
// ParseDescriptors parses a raw descriptor blob: an 18-byte device
// descriptor followed by one or more complete configuration descriptors.
//
// Reading a usbdevfs file (/dev/bus/usb/BBB/DDD) from offset 0 yields
// exactly this layout, which is the only way to see interface alternate
// settings — sysfs only exposes the currently active one.
func ParseDescriptors(data []byte) (*ParsedDescriptors, error) {
if len(data) < 18 {
return nil, fmt.Errorf("descriptor blob too short: %d bytes", len(data))
}
if data[1] != DescTypeDevice {
return nil, fmt.Errorf("first descriptor is type 0x%02x, expected device (0x01)", data[1])
}
pd := &ParsedDescriptors{
DeviceClass: data[4],
DeviceSubClass: data[5],
DeviceProtocol: data[6],
VendorID: binary.LittleEndian.Uint16(data[8:10]),
ProductID: binary.LittleEndian.Uint16(data[10:12]),
BcdDevice: binary.LittleEndian.Uint16(data[12:14]),
NumConfigs: data[17],
}
// Walk the remaining descriptors. Configuration descriptors start a new
// config; interface descriptors start a new alternate setting; endpoint
// descriptors attach to the most recent interface. Class-specific
// descriptors (HID, UVC, audio) are skipped by their bLength.
pos := int(data[0]) // skip the device descriptor using its own bLength
if pos < 18 {
pos = 18
}
var curConfig *ConfigDescriptor
var curIface *Interface
for pos+2 <= len(data) {
bLength := int(data[pos])
bType := data[pos+1]
// A zero-length descriptor would loop forever; a descriptor running
// past the end of the blob means the device returned garbage.
if bLength < 2 || pos+bLength > len(data) {
break
}
switch bType {
case DescTypeConfiguration:
if bLength >= 9 {
pd.Configs = append(pd.Configs, ConfigDescriptor{Value: data[pos+5]})
curConfig = &pd.Configs[len(pd.Configs)-1]
curIface = nil
}
case DescTypeInterface:
if bLength >= 9 && curConfig != nil {
curConfig.Interfaces = append(curConfig.Interfaces, Interface{
Number: data[pos+2],
AltSetting: data[pos+3],
Class: data[pos+5],
SubClass: data[pos+6],
Protocol: data[pos+7],
})
curIface = &curConfig.Interfaces[len(curConfig.Interfaces)-1]
}
case DescTypeEndpoint:
if bLength >= 7 && curIface != nil {
curIface.Endpoints = append(curIface.Endpoints, Endpoint{
Address: data[pos+2],
TransferType: data[pos+3] & 0x03,
MaxPacketSize: binary.LittleEndian.Uint16(data[pos+4 : pos+6]),
Interval: data[pos+6],
})
}
}
pos += bLength
}
if len(pd.Configs) == 0 {
return nil, fmt.Errorf("no configuration descriptor found")
}
return pd, nil
}
// FindConfig returns the configuration with the given bConfigurationValue,
// or nil if the device has no such configuration.
func (pd *ParsedDescriptors) FindConfig(value uint8) *ConfigDescriptor {
for i := range pd.Configs {
if pd.Configs[i].Value == value {
return &pd.Configs[i]
}
}
return nil
}
// AllEndpoints returns every endpoint across every alternate setting of the
// given configuration, keyed by full bEndpointAddress (direction bit
// included). Endpoints only present in a non-zero alternate setting — the
// isochronous endpoints of webcams, for example — are included, which is
// what makes the endpoint type map correct after a SET_INTERFACE.
func (c *ConfigDescriptor) AllEndpoints() map[uint8]Endpoint {
eps := make(map[uint8]Endpoint)
for _, iface := range c.Interfaces {
for _, ep := range iface.Endpoints {
// Alternate settings reuse addresses with identical transfer
// types in practice; keep the first one we see so alt 0 wins.
if _, seen := eps[ep.Address]; !seen {
eps[ep.Address] = ep
}
}
}
return eps
}
// ActiveInterfaces returns one Interface per interface number, using
// alternate setting 0 — the set of interfaces that must be claimed.
func (c *ConfigDescriptor) ActiveInterfaces() []Interface {
var result []Interface
seen := make(map[uint8]bool)
for _, iface := range c.Interfaces {
if iface.AltSetting != 0 || seen[iface.Number] {
continue
}
seen[iface.Number] = true
result = append(result, iface)
}
return result
}