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

164 lines
4.5 KiB
Go

//go:build darwin
package diag
import (
"encoding/json"
"fmt"
"os"
"os/exec"
"strconv"
"strings"
)
func isPrivileged() bool { return os.Geteuid() == 0 }
func collectPlatform(r *Report) {
r.System.OSVersion = macOSVersion()
r.System.KernelVersion = commandOutput("uname", "-r")
collectMacDevices(r)
assessMacCapabilities(r)
}
func macOSVersion() string {
name := commandOutput("sw_vers", "-productName")
version := commandOutput("sw_vers", "-productVersion")
build := commandOutput("sw_vers", "-buildVersion")
parts := []string{}
for _, p := range []string{name, version, build} {
if p != "" {
parts = append(parts, p)
}
}
return strings.Join(parts, " ")
}
func commandOutput(name string, args ...string) string {
out, err := exec.Command(name, args...).Output()
if err != nil {
return ""
}
return strings.TrimSpace(string(out))
}
// system_profiler's JSON output, as much of it as we care about.
type spReport struct {
Items []spUSBItem `json:"SPUSBDataType"`
}
type spUSBItem struct {
Name string `json:"_name"`
VendorID string `json:"vendor_id"`
ProductID string `json:"product_id"`
Speed string `json:"device_speed"`
Manufacturer string `json:"manufacturer"`
SerialNumber string `json:"serial_num"`
LocationID string `json:"location_id"`
Media []spMedia `json:"Media"`
Items []spUSBItem `json:"_items"`
}
type spMedia struct {
Name string `json:"_name"`
}
// collectMacDevices lists USB devices via system_profiler.
//
// Going through the command rather than IOKit keeps this cgo-free, which is
// what lets the tool be cross-compiled from any machine. It is also enough:
// this reports what is present, and on macOS nothing can be shared regardless
// until there is an IOKit backend.
func collectMacDevices(r *Report) {
out, err := exec.Command("system_profiler", "-json", "SPUSBDataType").Output()
if err != nil {
r.note("system_profiler failed: %v", err)
return
}
var report spReport
if err := json.Unmarshal(out, &report); err != nil {
r.note("could not parse system_profiler output: %v", err)
return
}
for _, item := range report.Items {
collectMacItem(r, item)
}
}
// collectMacItem walks the tree; hubs carry their devices in _items.
func collectMacItem(r *Report, item spUSBItem) {
if item.VendorID != "" {
r.Devices = append(r.Devices, DeviceInfo{
BusID: macBusID(item.LocationID),
VendorID: normaliseMacID(item.VendorID),
ProductID: normaliseMacID(item.ProductID),
Name: macDeviceName(item),
Speed: item.Speed,
Shareable: false,
Blocker: "macOS sharing needs an IOKit backend, which does not exist yet",
})
}
for _, child := range item.Items {
collectMacItem(r, child)
}
}
func macDeviceName(item spUSBItem) string {
if item.Manufacturer != "" && item.Name != "" &&
!strings.HasPrefix(item.Name, item.Manufacturer) {
return item.Manufacturer + " " + item.Name
}
return item.Name
}
// normaliseMacID turns "0x046d (Logitech Inc.)" into "046d".
func normaliseMacID(id string) string {
id = strings.TrimSpace(id)
if i := strings.Index(id, " "); i > 0 {
id = id[:i]
}
id = strings.TrimPrefix(id, "0x")
// Pad to four digits so IDs sort and compare like everywhere else.
if v, err := strconv.ParseUint(id, 16, 32); err == nil {
return fmt.Sprintf("%04x", v)
}
return id
}
// macBusID derives an identifier from the location ID, which encodes the
// device's position in the port tree and is stable while it stays plugged in.
func macBusID(locationID string) string {
locationID = strings.TrimSpace(locationID)
if i := strings.Index(locationID, " "); i > 0 {
locationID = locationID[:i]
}
return strings.TrimPrefix(locationID, "0x")
}
func assessMacCapabilities(r *Report) {
r.Sharing = Capability{
Available: false,
Reason: "no IOKit backend — macOS has no usbdevfs equivalent",
Mechanism: "IOKit (not implemented)",
}
r.Using = Capability{
Available: false,
Reason: "no virtual USB host controller — this needs a signed DriverKit driver",
Mechanism: "DriverKit (not implemented)",
}
r.addCheck("macOS sharing", false,
fmt.Sprintf("%d USB device(s) found, but none can be shared yet", len(r.Devices)),
"none — the relay server runs on macOS, the client's USB side does not")
r.note("Docker does not help here: containers share the host kernel, and " +
"on macOS Docker runs in a Linux VM that never sees the host's USB hardware. " +
"A full VM with USB passthrough (UTM, Parallels, VMware) does work.")
}