Files
usb-server/internal/client/stream_test.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

213 lines
4.7 KiB
Go

package client
import (
"bytes"
"errors"
"io"
"sync"
"testing"
"time"
)
func TestStreamBufferRoundTrip(t *testing.T) {
s := newStreamBuffer()
want := []byte("usbip frame")
if _, err := s.Write(want); err != nil {
t.Fatalf("Write: %v", err)
}
got := make([]byte, len(want))
if _, err := io.ReadFull(s, got); err != nil {
t.Fatalf("ReadFull: %v", err)
}
if !bytes.Equal(got, want) {
t.Errorf("read %q, want %q", got, want)
}
}
// The whole point of replacing io.Pipe: a write must return immediately even
// when nobody is reading, because it happens on the WebSocket read loop.
func TestStreamBufferWriteNeverBlocks(t *testing.T) {
s := newStreamBuffer()
done := make(chan struct{})
go func() {
defer close(done)
for i := 0; i < 100; i++ {
if _, err := s.Write(make([]byte, 1024)); err != nil {
t.Errorf("Write %d: %v", i, err)
return
}
}
}()
select {
case <-done:
case <-time.After(2 * time.Second):
t.Fatal("writes blocked with no reader — this is what froze the client")
}
if got := s.Buffered(); got != 100*1024 {
t.Errorf("buffered %d bytes, want %d", got, 100*1024)
}
}
func TestStreamBufferReadBlocksUntilData(t *testing.T) {
s := newStreamBuffer()
read := make(chan []byte, 1)
go func() {
buf := make([]byte, 4)
n, err := s.Read(buf)
if err != nil {
t.Errorf("Read: %v", err)
read <- nil
return
}
read <- buf[:n]
}()
// Give the reader time to park in Read before any data exists.
time.Sleep(50 * time.Millisecond)
select {
case <-read:
t.Fatal("Read returned before data was written")
default:
}
s.Write([]byte("ping"))
select {
case got := <-read:
if string(got) != "ping" {
t.Errorf("read %q, want %q", got, "ping")
}
case <-time.After(time.Second):
t.Fatal("Read did not wake up after Write")
}
}
func TestStreamBufferCloseGivesEOFAfterDraining(t *testing.T) {
s := newStreamBuffer()
s.Write([]byte("tail"))
s.Close()
// Buffered data must still be readable after Close.
got := make([]byte, 4)
if _, err := io.ReadFull(s, got); err != nil {
t.Fatalf("reading buffered data after Close: %v", err)
}
if string(got) != "tail" {
t.Errorf("read %q, want %q", got, "tail")
}
if _, err := s.Read(make([]byte, 4)); err != io.EOF {
t.Errorf("Read after drain = %v, want io.EOF", err)
}
}
func TestStreamBufferCloseWakesBlockedReader(t *testing.T) {
s := newStreamBuffer()
errCh := make(chan error, 1)
go func() {
_, err := s.Read(make([]byte, 4))
errCh <- err
}()
time.Sleep(50 * time.Millisecond)
s.Close()
select {
case err := <-errCh:
if err != io.EOF {
t.Errorf("blocked Read woke with %v, want io.EOF", err)
}
case <-time.After(time.Second):
t.Fatal("Close did not wake the blocked reader")
}
}
func TestStreamBufferOverflowFailsInsteadOfGrowing(t *testing.T) {
s := newStreamBufferLimit(1024)
if _, err := s.Write(make([]byte, 1000)); err != nil {
t.Fatalf("first write: %v", err)
}
if _, err := s.Write(make([]byte, 100)); !errors.Is(err, ErrStreamOverflow) {
t.Fatalf("overflowing write = %v, want ErrStreamOverflow", err)
}
// Further writes keep failing rather than silently resuming.
if _, err := s.Write([]byte("x")); !errors.Is(err, ErrStreamOverflow) {
t.Errorf("write after overflow = %v, want ErrStreamOverflow", err)
}
// Buffered data is still drainable, then the error surfaces.
if _, err := io.ReadFull(s, make([]byte, 1000)); err != nil {
t.Fatalf("draining after overflow: %v", err)
}
if _, err := s.Read(make([]byte, 4)); !errors.Is(err, ErrStreamOverflow) {
t.Errorf("Read after drain = %v, want ErrStreamOverflow", err)
}
}
func TestStreamBufferWriteAfterClose(t *testing.T) {
s := newStreamBuffer()
s.Close()
if _, err := s.Write([]byte("late")); err != io.ErrClosedPipe {
t.Errorf("Write after Close = %v, want io.ErrClosedPipe", err)
}
}
// Concurrent writers and one reader, the shape the share path actually has.
func TestStreamBufferConcurrent(t *testing.T) {
s := newStreamBuffer()
const writers = 8
const perWriter = 200
const chunk = 64
var wg sync.WaitGroup
wg.Add(writers)
for i := 0; i < writers; i++ {
go func() {
defer wg.Done()
for j := 0; j < perWriter; j++ {
if _, err := s.Write(make([]byte, chunk)); err != nil {
t.Errorf("Write: %v", err)
return
}
}
}()
}
total := writers * perWriter * chunk
readDone := make(chan int, 1)
go func() {
got := 0
buf := make([]byte, 128)
for got < total {
n, err := s.Read(buf)
if err != nil {
break
}
got += n
}
readDone <- got
}()
wg.Wait()
select {
case got := <-readDone:
if got != total {
t.Errorf("read %d bytes, want %d", got, total)
}
case <-time.After(5 * time.Second):
t.Fatal("concurrent read/write did not finish")
}
}