Files
usb-server/internal/bridge/bridge_linux.go
T
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

295 lines
7.4 KiB
Go

//go:build linux
// Package bridge accepts USB devices handed in from another process.
//
// It exists for hosts where this process cannot open USB devices itself.
// Android is the case that motivated it: apps there have no access to
// /dev/bus/usb, and must ask the framework, which shows a permission dialog
// and returns an already-open file descriptor. A small app-side shim obtains
// that descriptor plus the device's raw descriptors and passes both here over
// a Unix socket, using SCM_RIGHTS to transfer the descriptor itself.
//
// Nothing about this is Android-specific though: any supervising process can
// use it to hand devices to an unprivileged client.
package bridge
import (
"encoding/json"
"fmt"
"log"
"net"
"os"
"path/filepath"
"sync"
"github.com/duffy/usb-server/internal/usb"
"golang.org/x/sys/unix"
)
// maxRequestSize caps one request. Descriptor blobs are a few hundred bytes;
// this leaves plenty of room while bounding what a caller can make us buffer.
const maxRequestSize = 64 * 1024
// Request is one device handover, sent as a single JSON message with the
// device's file descriptor attached as SCM_RIGHTS ancillary data.
type Request struct {
// Action is "add" or "remove".
Action string `json:"action"`
// BusID identifies the device within this client, e.g. "1-2". It must be
// stable for as long as the device is shared: it is what peers request.
BusID string `json:"bus_id"`
// Descriptors is the raw descriptor blob, base64 encoded by encoding/json:
// the device descriptor followed by all configuration descriptors. On
// Android this is UsbDeviceConnection.getRawDescriptors().
Descriptors []byte `json:"descriptors,omitempty"`
BusNum uint32 `json:"bus_num,omitempty"`
DevNum uint32 `json:"dev_num,omitempty"`
Speed uint32 `json:"speed,omitempty"`
ConfigValue uint8 `json:"config_value,omitempty"`
Manufacturer string `json:"manufacturer,omitempty"`
Product string `json:"product,omitempty"`
Serial string `json:"serial,omitempty"`
}
// Response reports the outcome of a request.
type Response struct {
OK bool `json:"ok"`
Error string `json:"error,omitempty"`
}
// Server listens for device handovers on a Unix socket.
type Server struct {
listener net.Listener
path string
// OnChange fires after a device is added or removed, so the share manager
// can refresh and announce its list without waiting for the next poll.
OnChange func()
mu sync.Mutex
closed bool
}
// Listen starts a bridge server on the given Unix socket path.
//
// The socket is created with 0600 permissions: whoever can write to it can
// make this client share arbitrary USB devices.
func Listen(path string) (*Server, error) {
if path == "" {
return nil, fmt.Errorf("socket path is required")
}
if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
return nil, fmt.Errorf("creating socket directory: %w", err)
}
// A leftover socket from a previous run would make Listen fail.
if info, err := os.Stat(path); err == nil && info.Mode()&os.ModeSocket != 0 {
os.Remove(path)
}
ln, err := net.Listen("unix", path)
if err != nil {
return nil, fmt.Errorf("listening on %s: %w", path, err)
}
if err := os.Chmod(path, 0600); err != nil {
ln.Close()
return nil, fmt.Errorf("securing socket: %w", err)
}
s := &Server{listener: ln, path: path}
go s.acceptLoop()
log.Printf("[bridge] listening on %s for device handovers", path)
return s, nil
}
// Close stops the server and removes the socket.
func (s *Server) Close() error {
s.mu.Lock()
s.closed = true
s.mu.Unlock()
err := s.listener.Close()
os.Remove(s.path)
usb.ReleaseAdoptedFDs()
return err
}
func (s *Server) acceptLoop() {
for {
conn, err := s.listener.Accept()
if err != nil {
s.mu.Lock()
closed := s.closed
s.mu.Unlock()
if closed {
return
}
log.Printf("[bridge] accept error: %v", err)
return
}
go s.handleConn(conn.(*net.UnixConn))
}
}
// handleConn processes requests on one connection until it closes.
func (s *Server) handleConn(conn *net.UnixConn) {
defer conn.Close()
for {
req, fd, err := readRequest(conn)
if err != nil {
// A clean disconnect is the normal way a session ends.
return
}
resp := s.apply(req, fd)
if err := writeResponse(conn, resp); err != nil {
return
}
}
}
// apply carries out one request, taking ownership of fd.
func (s *Server) apply(req *Request, fd int) Response {
closeFD := func() {
if fd >= 0 {
unix.Close(fd)
}
}
switch req.Action {
case "add":
if req.BusID == "" {
closeFD()
return Response{Error: "bus_id is required"}
}
if fd < 0 {
return Response{Error: "no file descriptor was attached; " +
"send the open device descriptor as SCM_RIGHTS ancillary data"}
}
if len(req.Descriptors) == 0 {
closeFD()
return Response{Error: "descriptors are required: this process cannot read them itself"}
}
meta := usb.ExternalDeviceMeta{
BusNum: req.BusNum,
DevNum: req.DevNum,
Speed: req.Speed,
ConfigValue: req.ConfigValue,
Manufacturer: req.Manufacturer,
Product: req.Product,
Serial: req.Serial,
}
if err := usb.RegisterExternalDevice(req.BusID, req.Descriptors, meta); err != nil {
closeFD()
return Response{Error: err.Error()}
}
// Register the descriptor only after the device parsed cleanly, so a
// rejected request leaves nothing behind.
if err := usb.AdoptDeviceFD(req.BusID, fd); err != nil {
usb.UnregisterExternalDevice(req.BusID)
closeFD()
return Response{Error: err.Error()}
}
log.Printf("[bridge] device %s registered from outside (%s %s)",
req.BusID, req.Manufacturer, req.Product)
s.notify()
return Response{OK: true}
case "remove":
closeFD()
if req.BusID == "" {
return Response{Error: "bus_id is required"}
}
usb.UnregisterExternalDevice(req.BusID)
log.Printf("[bridge] device %s withdrawn", req.BusID)
s.notify()
return Response{OK: true}
default:
closeFD()
return Response{Error: fmt.Sprintf("unknown action %q (expected add or remove)", req.Action)}
}
}
func (s *Server) notify() {
if s.OnChange != nil {
s.OnChange()
}
}
// readRequest reads one JSON message plus an optional attached descriptor.
// It returns fd = -1 when no descriptor was sent.
func readRequest(conn *net.UnixConn) (*Request, int, error) {
buf := make([]byte, maxRequestSize)
oob := make([]byte, unix.CmsgSpace(4)) // room for exactly one descriptor
n, oobn, _, _, err := conn.ReadMsgUnix(buf, oob)
if err != nil {
return nil, -1, err
}
if n == 0 {
return nil, -1, fmt.Errorf("empty request")
}
fd := extractFD(oob[:oobn])
var req Request
if err := json.Unmarshal(buf[:n], &req); err != nil {
if fd >= 0 {
unix.Close(fd)
}
return nil, -1, fmt.Errorf("parsing request: %w", err)
}
return &req, fd, nil
}
// extractFD pulls a single descriptor out of ancillary data.
// Any extra descriptors are closed rather than leaked.
func extractFD(oob []byte) int {
if len(oob) == 0 {
return -1
}
msgs, err := unix.ParseSocketControlMessage(oob)
if err != nil {
return -1
}
result := -1
for _, msg := range msgs {
fds, err := unix.ParseUnixRights(&msg)
if err != nil {
continue
}
for _, fd := range fds {
if result == -1 {
result = fd
} else {
unix.Close(fd)
}
}
}
return result
}
func writeResponse(conn *net.UnixConn, resp Response) error {
data, err := json.Marshal(resp)
if err != nil {
return err
}
_, err = conn.Write(data)
return err
}