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

120 lines
3.7 KiB
Go

package config
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
)
// AutoConnectRule defines a rule for automatic device connection
type AutoConnectRule struct {
BusID string `json:"bus_id,omitempty"`
VendorID string `json:"vendor_id,omitempty"`
ProductID string `json:"product_id,omitempty"`
ClientName string `json:"client_name,omitempty"`
}
// Config holds the client configuration
type Config struct {
RelayAddr string `json:"relay_addr"` // e.g. "ws://localhost:8443" or "wss://relay.example.com:8443"
Hash string `json:"hash"` // SHA256 hash of 3 tokens
Mode string `json:"mode"` // "share", "use" or "both"
Name string `json:"name"` // friendly name for this client
WebPort int `json:"web_port"` // web UI port (default 8080)
// Tokens (optional, stored for convenience - hash is what matters)
Token1 string `json:"token1,omitempty"`
Token2 string `json:"token2,omitempty"`
Token3 string `json:"token3,omitempty"`
// Auto-connect rules (use mode only)
AutoConnect []AutoConnectRule `json:"auto_connect,omitempty"`
// Share mode: allow other clients to force-detach devices in use
AllowForceDetach bool `json:"allow_force_detach,omitempty"`
// DirectPort is the TCP port to accept direct tunnel connections on.
// 0 picks a free port, which is fine when peers can reach each other
// directly. Set a fixed port when you need to forward it through a
// firewall or NAT.
DirectPort int `json:"direct_port,omitempty"`
// DisableDirect forces every tunnel through the relay. Direct connections
// are preferred otherwise: they cut latency and keep USB traffic away
// from the relay entirely.
DisableDirect bool `json:"disable_direct,omitempty"`
// BridgeSocket is a Unix socket path on which to accept USB devices
// handed in by another process. Needed where this process cannot open
// devices itself — an Android app must obtain the descriptor through the
// framework and pass it in. Empty disables the bridge.
BridgeSocket string `json:"bridge_socket,omitempty"`
}
// HasTokens reports whether the full token set is available.
//
// Tunnel encryption and direct connections both need the tokens themselves;
// a config carrying only the group hash can join a group but not derive the
// keys, because the hash is what the relay is told.
func (c *Config) HasTokens() bool {
return c.Token1 != "" && c.Token2 != "" && c.Token3 != ""
}
// DefaultConfig returns a config with sensible defaults
func DefaultConfig() *Config {
hostname, _ := os.Hostname()
if hostname == "" {
hostname = "unknown"
}
return &Config{
RelayAddr: "ws://localhost:8443",
Mode: "use",
Name: hostname,
WebPort: 8080,
}
}
// DefaultConfigPath returns the default config file path
func DefaultConfigPath() string {
home, err := os.UserHomeDir()
if err != nil {
return "usb-client.json"
}
return filepath.Join(home, ".usb-server", "config.json")
}
// Load reads config from a JSON file
func Load(path string) (*Config, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("reading config: %w", err)
}
cfg := DefaultConfig()
if err := json.Unmarshal(data, cfg); err != nil {
return nil, fmt.Errorf("parsing config: %w", err)
}
return cfg, nil
}
// Save writes config to a JSON file
func (c *Config) Save(path string) error {
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, 0700); err != nil {
return fmt.Errorf("creating config directory: %w", err)
}
data, err := json.MarshalIndent(c, "", " ")
if err != nil {
return fmt.Errorf("encoding config: %w", err)
}
if err := os.WriteFile(path, data, 0600); err != nil {
return fmt.Errorf("writing config: %w", err)
}
return nil
}