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>
This commit is contained in:
@@ -0,0 +1,255 @@
|
||||
// Package diag collects everything needed to work out why USB sharing does
|
||||
// not work on a given machine.
|
||||
//
|
||||
// It exists because the failure modes are platform specific and mostly
|
||||
// invisible from the outside: a missing kernel module, a driver that did not
|
||||
// load, permissions on a device node, a filter that is installed but not
|
||||
// attached. Guessing at those across a chat is slow; a structured report
|
||||
// turns it into a matter of reading.
|
||||
package diag
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Report is the whole diagnostic picture of one machine.
|
||||
type Report struct {
|
||||
// Generated is filled in by the caller, since a report is often written
|
||||
// and read at very different times.
|
||||
Generated string `json:"generated"`
|
||||
|
||||
Tool ToolInfo `json:"tool"`
|
||||
System SystemInfo `json:"system"`
|
||||
Sharing Capability `json:"sharing"`
|
||||
Using Capability `json:"using"`
|
||||
Devices []DeviceInfo `json:"devices"`
|
||||
Checks []Check `json:"checks"`
|
||||
|
||||
// Notes carries anything that did not fit elsewhere, in plain language.
|
||||
Notes []string `json:"notes,omitempty"`
|
||||
}
|
||||
|
||||
// ToolInfo identifies the build that produced the report.
|
||||
type ToolInfo struct {
|
||||
Version string `json:"version"`
|
||||
GoVersion string `json:"go_version"`
|
||||
OS string `json:"os"`
|
||||
Arch string `json:"arch"`
|
||||
}
|
||||
|
||||
// SystemInfo describes the machine.
|
||||
type SystemInfo struct {
|
||||
Hostname string `json:"hostname"`
|
||||
OSVersion string `json:"os_version,omitempty"`
|
||||
KernelVersion string `json:"kernel_version,omitempty"`
|
||||
Privileged bool `json:"privileged"`
|
||||
// Container reports whether we appear to be inside one, which changes
|
||||
// what device access means.
|
||||
Container bool `json:"container,omitempty"`
|
||||
}
|
||||
|
||||
// Capability reports whether one half of the system can work here.
|
||||
type Capability struct {
|
||||
Available bool `json:"available"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
// Mechanism names what would be used: "usbdevfs", "usbshare filter",
|
||||
// "vhci-hcd", "usbip-win2".
|
||||
Mechanism string `json:"mechanism,omitempty"`
|
||||
}
|
||||
|
||||
// DeviceInfo is one USB device as the machine sees it.
|
||||
type DeviceInfo struct {
|
||||
BusID string `json:"bus_id,omitempty"`
|
||||
VendorID string `json:"vendor_id"`
|
||||
ProductID string `json:"product_id"`
|
||||
Name string `json:"name,omitempty"`
|
||||
Class string `json:"class,omitempty"`
|
||||
Driver string `json:"driver,omitempty"`
|
||||
Speed string `json:"speed,omitempty"`
|
||||
|
||||
// Shareable reports whether this device could actually be offered, and
|
||||
// Blocker says what stands in the way when it cannot.
|
||||
Shareable bool `json:"shareable"`
|
||||
Blocker string `json:"blocker,omitempty"`
|
||||
|
||||
// Endpoints matter for diagnosing devices that attach but stay silent:
|
||||
// a wrong transfer type here is exactly that symptom.
|
||||
Endpoints []EndpointInfo `json:"endpoints,omitempty"`
|
||||
}
|
||||
|
||||
// EndpointInfo is one endpoint of a device.
|
||||
type EndpointInfo struct {
|
||||
Address string `json:"address"`
|
||||
Direction string `json:"direction"`
|
||||
TransferType string `json:"transfer_type"`
|
||||
MaxPacket uint16 `json:"max_packet"`
|
||||
Interval uint8 `json:"interval"`
|
||||
}
|
||||
|
||||
// Check is one named test with a verdict.
|
||||
type Check struct {
|
||||
Name string `json:"name"`
|
||||
Passed bool `json:"passed"`
|
||||
Detail string `json:"detail,omitempty"`
|
||||
// Fix is a concrete action, present only when the check failed and there
|
||||
// is something the user can actually do.
|
||||
Fix string `json:"fix,omitempty"`
|
||||
}
|
||||
|
||||
// Collect gathers a report for the current machine.
|
||||
func Collect(version string) *Report {
|
||||
hostname, _ := os.Hostname()
|
||||
|
||||
report := &Report{
|
||||
Generated: time.Now().Format(time.RFC3339),
|
||||
Tool: ToolInfo{
|
||||
Version: version,
|
||||
GoVersion: runtime.Version(),
|
||||
OS: runtime.GOOS,
|
||||
Arch: runtime.GOARCH,
|
||||
},
|
||||
System: SystemInfo{
|
||||
Hostname: hostname,
|
||||
Privileged: isPrivileged(),
|
||||
Container: inContainer(),
|
||||
},
|
||||
}
|
||||
|
||||
collectPlatform(report)
|
||||
|
||||
return report
|
||||
}
|
||||
|
||||
// JSON renders the report for machine consumption.
|
||||
func (r *Report) JSON() ([]byte, error) {
|
||||
return json.MarshalIndent(r, "", " ")
|
||||
}
|
||||
|
||||
// String renders the report for a human reading a terminal.
|
||||
func (r *Report) String() string {
|
||||
var b strings.Builder
|
||||
|
||||
fmt.Fprintf(&b, "USB Server diagnostics\n")
|
||||
fmt.Fprintf(&b, "======================\n\n")
|
||||
fmt.Fprintf(&b, "Host: %s (%s/%s)\n", r.System.Hostname, r.Tool.OS, r.Tool.Arch)
|
||||
if r.System.OSVersion != "" {
|
||||
fmt.Fprintf(&b, "OS: %s\n", r.System.OSVersion)
|
||||
}
|
||||
if r.System.KernelVersion != "" {
|
||||
fmt.Fprintf(&b, "Kernel: %s\n", r.System.KernelVersion)
|
||||
}
|
||||
fmt.Fprintf(&b, "Elevated: %v\n", r.System.Privileged)
|
||||
if r.System.Container {
|
||||
fmt.Fprintf(&b, "Container: yes\n")
|
||||
}
|
||||
fmt.Fprintf(&b, "\n")
|
||||
|
||||
fmt.Fprintf(&b, "Sharing devices: %s\n", capabilityLine(r.Sharing))
|
||||
fmt.Fprintf(&b, "Using devices: %s\n", capabilityLine(r.Using))
|
||||
fmt.Fprintf(&b, "\n")
|
||||
|
||||
if len(r.Checks) > 0 {
|
||||
fmt.Fprintf(&b, "Checks\n------\n")
|
||||
for _, c := range r.Checks {
|
||||
mark := "FAIL"
|
||||
if c.Passed {
|
||||
mark = " ok "
|
||||
}
|
||||
fmt.Fprintf(&b, "[%s] %s\n", mark, c.Name)
|
||||
if c.Detail != "" {
|
||||
fmt.Fprintf(&b, " %s\n", c.Detail)
|
||||
}
|
||||
if !c.Passed && c.Fix != "" {
|
||||
fmt.Fprintf(&b, " fix: %s\n", c.Fix)
|
||||
}
|
||||
}
|
||||
fmt.Fprintf(&b, "\n")
|
||||
}
|
||||
|
||||
fmt.Fprintf(&b, "Devices (%d)\n-----------\n", len(r.Devices))
|
||||
for _, d := range r.Devices {
|
||||
state := "shareable"
|
||||
if !d.Shareable {
|
||||
state = "blocked: " + d.Blocker
|
||||
}
|
||||
fmt.Fprintf(&b, "%-12s %s:%s %-28s %s\n",
|
||||
d.BusID, d.VendorID, d.ProductID, truncate(d.Name, 28), state)
|
||||
if d.Driver != "" {
|
||||
fmt.Fprintf(&b, " driver=%s class=%s speed=%s\n", d.Driver, d.Class, d.Speed)
|
||||
}
|
||||
for _, ep := range d.Endpoints {
|
||||
fmt.Fprintf(&b, " ep %s %-3s %-11s maxpkt=%d interval=%d\n",
|
||||
ep.Address, ep.Direction, ep.TransferType, ep.MaxPacket, ep.Interval)
|
||||
}
|
||||
}
|
||||
|
||||
if len(r.Notes) > 0 {
|
||||
fmt.Fprintf(&b, "\nNotes\n-----\n")
|
||||
for _, n := range r.Notes {
|
||||
fmt.Fprintf(&b, "- %s\n", n)
|
||||
}
|
||||
}
|
||||
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func capabilityLine(c Capability) string {
|
||||
if c.Available {
|
||||
if c.Mechanism != "" {
|
||||
return "yes (" + c.Mechanism + ")"
|
||||
}
|
||||
return "yes"
|
||||
}
|
||||
if c.Reason != "" {
|
||||
return "no — " + c.Reason
|
||||
}
|
||||
return "no"
|
||||
}
|
||||
|
||||
func truncate(s string, max int) string {
|
||||
if len(s) <= max {
|
||||
return s
|
||||
}
|
||||
if max <= 3 {
|
||||
return s[:max]
|
||||
}
|
||||
return s[:max-3] + "..."
|
||||
}
|
||||
|
||||
// addCheck appends a check result.
|
||||
func (r *Report) addCheck(name string, passed bool, detail, fix string) {
|
||||
r.Checks = append(r.Checks, Check{
|
||||
Name: name,
|
||||
Passed: passed,
|
||||
Detail: detail,
|
||||
Fix: fix,
|
||||
})
|
||||
}
|
||||
|
||||
// note appends a free-form observation.
|
||||
func (r *Report) note(format string, args ...interface{}) {
|
||||
r.Notes = append(r.Notes, fmt.Sprintf(format, args...))
|
||||
}
|
||||
|
||||
// inContainer guesses whether this process runs inside a container.
|
||||
//
|
||||
// It matters for diagnosis: inside a container, missing devices usually mean
|
||||
// the container was not given access, not that the host lacks them.
|
||||
func inContainer() bool {
|
||||
if _, err := os.Stat("/.dockerenv"); err == nil {
|
||||
return true
|
||||
}
|
||||
if data, err := os.ReadFile("/proc/1/cgroup"); err == nil {
|
||||
content := string(data)
|
||||
if strings.Contains(content, "docker") || strings.Contains(content, "containerd") ||
|
||||
strings.Contains(content, "lxc") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
//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.")
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
//go:build linux
|
||||
|
||||
package diag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/duffy/usb-server/internal/usb"
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
func isPrivileged() bool { return os.Geteuid() == 0 }
|
||||
|
||||
func collectPlatform(r *Report) {
|
||||
r.System.KernelVersion = kernelVersion()
|
||||
|
||||
checkUsbdevfs(r)
|
||||
checkVHCI(r)
|
||||
collectLinuxDevices(r)
|
||||
assessLinuxCapabilities(r)
|
||||
}
|
||||
|
||||
func kernelVersion() string {
|
||||
var uname unix.Utsname
|
||||
if err := unix.Uname(&uname); err != nil {
|
||||
return ""
|
||||
}
|
||||
return fmt.Sprintf("%s %s",
|
||||
nullTerminated(uname.Sysname[:]), nullTerminated(uname.Release[:]))
|
||||
}
|
||||
|
||||
func nullTerminated(b []byte) string {
|
||||
if i := strings.IndexByte(string(b), 0); i >= 0 {
|
||||
return string(b[:i])
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// checkUsbdevfs verifies that device nodes exist and are usable.
|
||||
//
|
||||
// Being able to list devices through sysfs proves nothing: sharing needs to
|
||||
// open the node under /dev/bus/usb, and that is where permissions bite.
|
||||
func checkUsbdevfs(r *Report) {
|
||||
if _, err := os.Stat("/dev/bus/usb"); err != nil {
|
||||
detail := "/dev/bus/usb is missing"
|
||||
fix := "check that usbcore is loaded and devtmpfs is mounted"
|
||||
if r.System.Container {
|
||||
detail += " — this is a container, so it was probably not passed through"
|
||||
fix = "add - /dev/bus/usb:/dev/bus/usb to the container's volumes, and run it privileged"
|
||||
}
|
||||
r.addCheck("usbdevfs device nodes", false, detail, fix)
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := os.Stat("/sys/bus/usb/devices"); err != nil {
|
||||
r.addCheck("usbdevfs device nodes", false,
|
||||
"/sys/bus/usb is not mounted, so devices cannot be enumerated",
|
||||
"mount sysfs, or in a container add - /sys/bus/usb:/sys/bus/usb")
|
||||
return
|
||||
}
|
||||
|
||||
r.addCheck("usbdevfs device nodes", true, "/dev/bus/usb and /sys/bus/usb are present", "")
|
||||
|
||||
if !isPrivileged() {
|
||||
r.addCheck("privileges", false,
|
||||
"not running as root — devices can be listed but not claimed",
|
||||
"run the client with sudo, or install it as a system service")
|
||||
} else {
|
||||
r.addCheck("privileges", true, "running as root", "")
|
||||
}
|
||||
}
|
||||
|
||||
// checkVHCI verifies the kernel module needed to receive remote devices.
|
||||
func checkVHCI(r *Report) {
|
||||
if _, err := os.Stat("/sys/devices/platform/vhci_hcd.0"); err == nil {
|
||||
r.addCheck("vhci-hcd module", true, "loaded — remote devices can be attached", "")
|
||||
return
|
||||
}
|
||||
|
||||
detail := "not loaded — remote devices cannot be attached"
|
||||
if r.System.Container {
|
||||
detail += " (a container cannot load modules; this must happen on the host)"
|
||||
}
|
||||
|
||||
r.addCheck("vhci-hcd module", false, detail,
|
||||
"sudo modprobe vhci-hcd (persist with: echo vhci-hcd | sudo tee /etc/modules-load.d/vhci-hcd.conf)")
|
||||
}
|
||||
|
||||
func collectLinuxDevices(r *Report) {
|
||||
devices, err := usb.Enumerate()
|
||||
if err != nil {
|
||||
r.note("device enumeration failed: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
for _, dev := range devices {
|
||||
info := DeviceInfo{
|
||||
BusID: dev.BusID,
|
||||
VendorID: fmt.Sprintf("%04x", dev.VendorID),
|
||||
ProductID: fmt.Sprintf("%04x", dev.ProductID),
|
||||
Name: dev.DisplayName(),
|
||||
Class: fmt.Sprintf("%02x", dev.DeviceClass),
|
||||
Speed: speedName(dev.Speed),
|
||||
}
|
||||
|
||||
if len(dev.Interfaces) > 0 {
|
||||
info.Driver = dev.Interfaces[0].Driver
|
||||
}
|
||||
|
||||
// Sharing needs write access to the node, so test exactly that.
|
||||
if err := unix.Access(dev.DevPath, unix.R_OK|unix.W_OK); err != nil {
|
||||
info.Shareable = false
|
||||
info.Blocker = fmt.Sprintf("no write access to %s (%v)", dev.DevPath, err)
|
||||
} else {
|
||||
info.Shareable = true
|
||||
}
|
||||
|
||||
for _, ep := range dev.Endpoints {
|
||||
info.Endpoints = append(info.Endpoints, endpointInfo(ep))
|
||||
}
|
||||
|
||||
// An empty endpoint map means the raw descriptors could not be read,
|
||||
// which is what makes transfer types guesswork later.
|
||||
if len(dev.Endpoints) == 0 {
|
||||
r.note("no endpoint descriptors for %s — could not read %s; "+
|
||||
"transfer types will be guessed from the request interval",
|
||||
dev.BusID, dev.DevPath)
|
||||
}
|
||||
|
||||
r.Devices = append(r.Devices, info)
|
||||
}
|
||||
}
|
||||
|
||||
func assessLinuxCapabilities(r *Report) {
|
||||
shareable := 0
|
||||
for _, d := range r.Devices {
|
||||
if d.Shareable {
|
||||
shareable++
|
||||
}
|
||||
}
|
||||
|
||||
switch {
|
||||
case shareable > 0:
|
||||
r.Sharing = Capability{Available: true, Mechanism: "usbdevfs"}
|
||||
case len(r.Devices) > 0:
|
||||
r.Sharing = Capability{
|
||||
Available: false,
|
||||
Reason: "devices found, but none can be opened (permissions)",
|
||||
Mechanism: "usbdevfs",
|
||||
}
|
||||
default:
|
||||
r.Sharing = Capability{
|
||||
Available: false,
|
||||
Reason: "no USB devices found",
|
||||
Mechanism: "usbdevfs",
|
||||
}
|
||||
}
|
||||
|
||||
if _, err := os.Stat("/sys/devices/platform/vhci_hcd.0"); err == nil {
|
||||
r.Using = Capability{Available: true, Mechanism: "vhci-hcd"}
|
||||
} else {
|
||||
r.Using = Capability{
|
||||
Available: false,
|
||||
Reason: "vhci-hcd is not loaded",
|
||||
Mechanism: "vhci-hcd",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
package diag
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/duffy/usb-server/internal/usb"
|
||||
)
|
||||
|
||||
func TestCollectProducesUsableReport(t *testing.T) {
|
||||
report := Collect("test")
|
||||
|
||||
if report.Generated == "" {
|
||||
t.Error("no timestamp")
|
||||
}
|
||||
if report.Tool.OS == "" || report.Tool.Arch == "" {
|
||||
t.Error("platform not recorded")
|
||||
}
|
||||
if report.System.Hostname == "" {
|
||||
t.Error("hostname not recorded")
|
||||
}
|
||||
|
||||
// A report that says nothing about either capability is useless: the
|
||||
// whole point is answering whether this machine can share or use.
|
||||
if report.Sharing.Mechanism == "" && report.Sharing.Reason == "" {
|
||||
t.Error("sharing capability has neither a mechanism nor a reason")
|
||||
}
|
||||
if report.Using.Mechanism == "" && report.Using.Reason == "" {
|
||||
t.Error("using capability has neither a mechanism nor a reason")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReportRoundTripsThroughJSON(t *testing.T) {
|
||||
report := Collect("test")
|
||||
|
||||
data, err := report.JSON()
|
||||
if err != nil {
|
||||
t.Fatalf("JSON: %v", err)
|
||||
}
|
||||
|
||||
var decoded Report
|
||||
if err := json.Unmarshal(data, &decoded); err != nil {
|
||||
t.Fatalf("decoding the report we just produced: %v", err)
|
||||
}
|
||||
|
||||
if decoded.Tool.OS != report.Tool.OS {
|
||||
t.Errorf("OS survived as %q, want %q", decoded.Tool.OS, report.Tool.OS)
|
||||
}
|
||||
if len(decoded.Devices) != len(report.Devices) {
|
||||
t.Errorf("device count changed: %d -> %d", len(report.Devices), len(decoded.Devices))
|
||||
}
|
||||
}
|
||||
|
||||
// A failed check without a fix leaves the reader stuck, which defeats the
|
||||
// purpose of the report.
|
||||
func TestFailedChecksSuggestAFix(t *testing.T) {
|
||||
report := Collect("test")
|
||||
|
||||
for _, check := range report.Checks {
|
||||
if !check.Passed && check.Fix == "" && check.Detail == "" {
|
||||
t.Errorf("check %q failed but says nothing about why or what to do", check.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestStringOutputMentionsEverything(t *testing.T) {
|
||||
report := &Report{
|
||||
Generated: "2026-01-01T00:00:00Z",
|
||||
Tool: ToolInfo{OS: "linux", Arch: "amd64"},
|
||||
System: SystemInfo{Hostname: "testhost"},
|
||||
Sharing: Capability{Available: true, Mechanism: "usbdevfs"},
|
||||
Using: Capability{Available: false, Reason: "vhci-hcd is not loaded"},
|
||||
Devices: []DeviceInfo{{
|
||||
BusID: "1-2",
|
||||
VendorID: "046d",
|
||||
ProductID: "c52b",
|
||||
Name: "Logitech Receiver",
|
||||
Shareable: true,
|
||||
Endpoints: []EndpointInfo{{
|
||||
Address: "0x81",
|
||||
Direction: "IN",
|
||||
TransferType: "interrupt",
|
||||
MaxPacket: 8,
|
||||
Interval: 10,
|
||||
}},
|
||||
}},
|
||||
Checks: []Check{
|
||||
{Name: "vhci-hcd module", Passed: false,
|
||||
Detail: "not loaded", Fix: "sudo modprobe vhci-hcd"},
|
||||
},
|
||||
}
|
||||
|
||||
out := report.String()
|
||||
|
||||
for _, want := range []string{
|
||||
"testhost", "usbdevfs", "vhci-hcd is not loaded",
|
||||
"1-2", "046d", "c52b", "Logitech Receiver",
|
||||
"0x81", "interrupt",
|
||||
"sudo modprobe vhci-hcd",
|
||||
} {
|
||||
if !strings.Contains(out, want) {
|
||||
t.Errorf("output does not mention %q", want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTransferTypeNames(t *testing.T) {
|
||||
tests := []struct {
|
||||
input uint8
|
||||
want string
|
||||
}{
|
||||
{usb.TransferTypeControl, "control"},
|
||||
{usb.TransferTypeIsochronous, "isochronous"},
|
||||
{usb.TransferTypeBulk, "bulk"},
|
||||
{usb.TransferTypeInterrupt, "interrupt"},
|
||||
{99, "unknown(99)"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
if got := transferTypeName(tt.input); got != tt.want {
|
||||
t.Errorf("transferTypeName(%d) = %q, want %q", tt.input, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEndpointInfoReportsDirection(t *testing.T) {
|
||||
in := endpointInfo(usb.Endpoint{
|
||||
Address: 0x81,
|
||||
TransferType: usb.TransferTypeInterrupt,
|
||||
MaxPacketSize: 8,
|
||||
Interval: 10,
|
||||
})
|
||||
if in.Direction != "IN" {
|
||||
t.Errorf("0x81 reported as %s, want IN", in.Direction)
|
||||
}
|
||||
if in.Address != "0x81" {
|
||||
t.Errorf("address rendered as %q", in.Address)
|
||||
}
|
||||
|
||||
out := endpointInfo(usb.Endpoint{Address: 0x02, TransferType: usb.TransferTypeBulk})
|
||||
if out.Direction != "OUT" {
|
||||
t.Errorf("0x02 reported as %s, want OUT", out.Direction)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiagURLAcceptsEveryRelayForm(t *testing.T) {
|
||||
tests := []struct {
|
||||
relay string
|
||||
want string
|
||||
}{
|
||||
{"ws://relay:8443", "http://relay:8443/diag/abc"},
|
||||
{"wss://relay.example.com", "https://relay.example.com/diag/abc"},
|
||||
{"http://relay:8443", "http://relay:8443/diag/abc"},
|
||||
{"https://relay:8443", "https://relay:8443/diag/abc"},
|
||||
{"relay:8443", "http://relay:8443/diag/abc"},
|
||||
{"ws://relay:8443/ws", "http://relay:8443/diag/abc"},
|
||||
{"ws://relay:8443/", "http://relay:8443/diag/abc"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
got, err := DiagURL(tt.relay, "abc")
|
||||
if err != nil {
|
||||
t.Errorf("DiagURL(%q): %v", tt.relay, err)
|
||||
continue
|
||||
}
|
||||
if got != tt.want {
|
||||
t.Errorf("DiagURL(%q) = %q, want %q", tt.relay, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiagURLRejectsBadIDs(t *testing.T) {
|
||||
for _, id := range []string{"", "a/b", "a?b", "a#b"} {
|
||||
if _, err := DiagURL("ws://relay:8443", id); err == nil {
|
||||
t.Errorf("DiagURL accepted the ID %q", id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTruncate(t *testing.T) {
|
||||
tests := []struct {
|
||||
in string
|
||||
max int
|
||||
want string
|
||||
}{
|
||||
{"short", 10, "short"},
|
||||
{"exactly-10", 10, "exactly-10"},
|
||||
{"this is far too long", 10, "this is..."},
|
||||
{"abc", 2, "ab"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
if got := truncate(tt.in, tt.max); got != tt.want {
|
||||
t.Errorf("truncate(%q, %d) = %q, want %q", tt.in, tt.max, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
//go:build windows
|
||||
|
||||
package diag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os/exec"
|
||||
"strings"
|
||||
|
||||
"github.com/duffy/usb-server/internal/usb"
|
||||
"golang.org/x/sys/windows"
|
||||
"golang.org/x/sys/windows/registry"
|
||||
)
|
||||
|
||||
const usbShareServiceName = "usbshare"
|
||||
|
||||
func isPrivileged() bool {
|
||||
// An elevated process has the administrators group enabled in its token.
|
||||
var sid *windows.SID
|
||||
err := windows.AllocateAndInitializeSid(
|
||||
&windows.SECURITY_NT_AUTHORITY,
|
||||
2,
|
||||
windows.SECURITY_BUILTIN_DOMAIN_RID,
|
||||
windows.DOMAIN_ALIAS_RID_ADMINS,
|
||||
0, 0, 0, 0, 0, 0,
|
||||
&sid,
|
||||
)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
defer windows.FreeSid(sid)
|
||||
|
||||
token := windows.Token(0) // the process token
|
||||
member, err := token.IsMember(sid)
|
||||
return err == nil && member
|
||||
}
|
||||
|
||||
func collectPlatform(r *Report) {
|
||||
r.System.OSVersion = windowsVersion()
|
||||
|
||||
checkTestSigning(r)
|
||||
checkDriverService(r)
|
||||
checkDriverInterface(r)
|
||||
collectWindowsDevices(r)
|
||||
assessWindowsCapabilities(r)
|
||||
}
|
||||
|
||||
// windowsVersion reads the build information from the registry, which does
|
||||
// not lie about the version the way GetVersionEx does for unmanifested
|
||||
// processes.
|
||||
func windowsVersion() string {
|
||||
key, err := registry.OpenKey(registry.LOCAL_MACHINE,
|
||||
`SOFTWARE\Microsoft\Windows NT\CurrentVersion`, registry.QUERY_VALUE)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
defer key.Close()
|
||||
|
||||
productName, _, _ := key.GetStringValue("ProductName")
|
||||
displayVersion, _, _ := key.GetStringValue("DisplayVersion")
|
||||
build, _, _ := key.GetStringValue("CurrentBuildNumber")
|
||||
ubr, _, _ := key.GetIntegerValue("UBR")
|
||||
|
||||
parts := []string{productName}
|
||||
if displayVersion != "" {
|
||||
parts = append(parts, displayVersion)
|
||||
}
|
||||
if build != "" {
|
||||
if ubr > 0 {
|
||||
parts = append(parts, fmt.Sprintf("build %s.%d", build, ubr))
|
||||
} else {
|
||||
parts = append(parts, "build "+build)
|
||||
}
|
||||
}
|
||||
return strings.Join(parts, " ")
|
||||
}
|
||||
|
||||
// checkTestSigning reports whether unsigned drivers may load.
|
||||
//
|
||||
// This is the single most common reason a freshly built driver does nothing:
|
||||
// it is installed, the INF looks fine, and Windows silently refuses to load
|
||||
// it because it is not signed by Microsoft.
|
||||
func checkTestSigning(r *Report) {
|
||||
out, err := exec.Command("bcdedit", "/enum", "{current}").Output()
|
||||
if err != nil {
|
||||
r.addCheck("test signing", false,
|
||||
"could not read the boot configuration: "+err.Error(),
|
||||
"run this from an elevated command prompt")
|
||||
return
|
||||
}
|
||||
|
||||
text := strings.ToLower(string(out))
|
||||
testSigning := strings.Contains(text, "testsigning") && strings.Contains(text, "yes")
|
||||
|
||||
if testSigning {
|
||||
r.addCheck("test signing", true, "enabled — unsigned drivers may load", "")
|
||||
} else {
|
||||
r.addCheck("test signing", false,
|
||||
"disabled — Windows will refuse to load an unsigned driver, usually without any visible error",
|
||||
"bcdedit /set testsigning on (then reboot; only do this on a test machine)")
|
||||
}
|
||||
}
|
||||
|
||||
// checkDriverService reports whether the filter driver is registered and
|
||||
// running.
|
||||
func checkDriverService(r *Report) {
|
||||
manager, err := windows.OpenSCManager(nil, nil, windows.SC_MANAGER_CONNECT)
|
||||
if err != nil {
|
||||
r.addCheck("usbshare driver service", false,
|
||||
"could not open the service manager: "+err.Error(), "")
|
||||
return
|
||||
}
|
||||
defer windows.CloseServiceHandle(manager)
|
||||
|
||||
namePtr, _ := windows.UTF16PtrFromString(usbShareServiceName)
|
||||
service, err := windows.OpenService(manager, namePtr, windows.SERVICE_QUERY_STATUS)
|
||||
if err != nil {
|
||||
r.addCheck("usbshare driver service", false,
|
||||
"not registered — the driver has not been installed",
|
||||
"right-click driver/windows/usbshare.inf and choose Install, then attach it "+
|
||||
"to a device in Device Manager")
|
||||
return
|
||||
}
|
||||
defer windows.CloseServiceHandle(service)
|
||||
|
||||
var status windows.SERVICE_STATUS
|
||||
if err := windows.QueryServiceStatus(service, &status); err != nil {
|
||||
r.addCheck("usbshare driver service", false,
|
||||
"registered, but its status could not be read: "+err.Error(), "")
|
||||
return
|
||||
}
|
||||
|
||||
switch status.CurrentState {
|
||||
case windows.SERVICE_RUNNING:
|
||||
r.addCheck("usbshare driver service", true, "registered and running", "")
|
||||
case windows.SERVICE_STOPPED:
|
||||
// A filter driver only starts when it is attached to a device, so
|
||||
// stopped is expected until then rather than an error in itself.
|
||||
r.addCheck("usbshare driver service", false,
|
||||
"registered but not running — normal until the filter is attached to a device",
|
||||
"attach the filter to a device in Device Manager, then replug it")
|
||||
default:
|
||||
r.addCheck("usbshare driver service", false,
|
||||
fmt.Sprintf("registered, service state %d", status.CurrentState), "")
|
||||
}
|
||||
}
|
||||
|
||||
// checkDriverInterface reports whether any device exposes the filter's
|
||||
// interface, which is what user mode actually needs.
|
||||
func checkDriverInterface(r *Report) {
|
||||
devices, err := usb.Enumerate()
|
||||
if err != nil {
|
||||
r.addCheck("usbshare device interface", false,
|
||||
"no device exposes the interface: "+err.Error(),
|
||||
"the driver must be attached to a specific device, not just installed")
|
||||
return
|
||||
}
|
||||
|
||||
if len(devices) == 0 {
|
||||
r.addCheck("usbshare device interface", false,
|
||||
"the driver is present but no device is attached to it",
|
||||
"in Device Manager, update the driver for the device you want to share")
|
||||
return
|
||||
}
|
||||
|
||||
r.addCheck("usbshare device interface", true,
|
||||
fmt.Sprintf("%d device(s) reachable through the filter", len(devices)), "")
|
||||
}
|
||||
|
||||
func collectWindowsDevices(r *Report) {
|
||||
devices, err := usb.Enumerate()
|
||||
if err != nil {
|
||||
r.note("device enumeration failed: %v", err)
|
||||
collectWindowsDevicesFallback(r)
|
||||
return
|
||||
}
|
||||
|
||||
for _, dev := range devices {
|
||||
info := DeviceInfo{
|
||||
BusID: dev.BusID,
|
||||
VendorID: fmt.Sprintf("%04x", dev.VendorID),
|
||||
ProductID: fmt.Sprintf("%04x", dev.ProductID),
|
||||
Name: dev.DisplayName(),
|
||||
Class: fmt.Sprintf("%02x", dev.DeviceClass),
|
||||
Speed: speedName(dev.Speed),
|
||||
Shareable: true,
|
||||
}
|
||||
|
||||
for _, ep := range dev.Endpoints {
|
||||
info.Endpoints = append(info.Endpoints, endpointInfo(ep))
|
||||
}
|
||||
|
||||
r.Devices = append(r.Devices, info)
|
||||
}
|
||||
|
||||
// Everything the filter cannot see is still worth listing: it explains
|
||||
// why an expected device is absent.
|
||||
collectWindowsDevicesFallback(r)
|
||||
}
|
||||
|
||||
// collectWindowsDevicesFallback lists all USB devices via PowerShell, whether
|
||||
// or not the filter is attached.
|
||||
//
|
||||
// Shelling out is deliberate: reproducing this through SetupAPI would be a
|
||||
// few hundred lines of syscall code for something that only ever runs when a
|
||||
// human is already reading the output.
|
||||
func collectWindowsDevicesFallback(r *Report) {
|
||||
cmd := exec.Command("powershell", "-NoProfile", "-Command",
|
||||
`Get-PnpDevice -Class USB -ErrorAction SilentlyContinue | `+
|
||||
`Select-Object -Property InstanceId,FriendlyName,Status,Service | `+
|
||||
`ForEach-Object { "$($_.InstanceId)|$($_.FriendlyName)|$($_.Status)|$($_.Service)" }`)
|
||||
|
||||
out, err := cmd.Output()
|
||||
if err != nil {
|
||||
r.note("could not list USB devices via PowerShell: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
seen := make(map[string]bool)
|
||||
for _, d := range r.Devices {
|
||||
seen[strings.ToLower(d.VendorID+":"+d.ProductID)] = true
|
||||
}
|
||||
|
||||
for _, line := range strings.Split(string(out), "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
parts := strings.Split(line, "|")
|
||||
if len(parts) < 4 {
|
||||
continue
|
||||
}
|
||||
|
||||
instanceID, friendly, status, service := parts[0], parts[1], parts[2], parts[3]
|
||||
vid, pid := parseVidPid(instanceID)
|
||||
if vid == "" {
|
||||
continue
|
||||
}
|
||||
if seen[strings.ToLower(vid+":"+pid)] {
|
||||
continue // already listed through the filter
|
||||
}
|
||||
|
||||
blocker := "usbshare filter not attached"
|
||||
if !strings.EqualFold(status, "OK") {
|
||||
blocker = "device status: " + status
|
||||
}
|
||||
|
||||
r.Devices = append(r.Devices, DeviceInfo{
|
||||
VendorID: vid,
|
||||
ProductID: pid,
|
||||
Name: friendly,
|
||||
Driver: service,
|
||||
Shareable: false,
|
||||
Blocker: blocker,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// parseVidPid pulls the IDs out of an instance ID such as
|
||||
// USB\VID_046D&PID_C52B\5&1a2b3c4d&0&2.
|
||||
func parseVidPid(instanceID string) (vid, pid string) {
|
||||
upper := strings.ToUpper(instanceID)
|
||||
|
||||
if i := strings.Index(upper, "VID_"); i >= 0 && len(upper) >= i+8 {
|
||||
vid = strings.ToLower(upper[i+4 : i+8])
|
||||
}
|
||||
if i := strings.Index(upper, "PID_"); i >= 0 && len(upper) >= i+8 {
|
||||
pid = strings.ToLower(upper[i+4 : i+8])
|
||||
}
|
||||
return vid, pid
|
||||
}
|
||||
|
||||
func assessWindowsCapabilities(r *Report) {
|
||||
shareable := 0
|
||||
for _, d := range r.Devices {
|
||||
if d.Shareable {
|
||||
shareable++
|
||||
}
|
||||
}
|
||||
|
||||
if shareable > 0 {
|
||||
r.Sharing = Capability{
|
||||
Available: true,
|
||||
Mechanism: "usbshare filter driver",
|
||||
}
|
||||
} else {
|
||||
r.Sharing = Capability{
|
||||
Available: false,
|
||||
Reason: "no device is attached to the usbshare filter driver",
|
||||
Mechanism: "usbshare filter driver",
|
||||
}
|
||||
}
|
||||
|
||||
// The use side needs usbip-win2's VHCI driver, which is a separate
|
||||
// product with its own installer.
|
||||
if _, err := exec.LookPath("usbip"); err == nil {
|
||||
r.Using = Capability{Available: true, Mechanism: "usbip-win2 VHCI"}
|
||||
} else {
|
||||
r.Using = Capability{
|
||||
Available: false,
|
||||
Reason: "usbip.exe not found",
|
||||
Mechanism: "usbip-win2 VHCI",
|
||||
}
|
||||
r.addCheck("usbip-win2", false,
|
||||
"not installed — receiving remote devices needs its VHCI driver",
|
||||
"install from https://github.com/vadimgrn/usbip-win2/releases")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package diag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/duffy/usb-server/internal/usb"
|
||||
)
|
||||
|
||||
// speedName renders a USB/IP speed code.
|
||||
func speedName(speed uint32) string {
|
||||
switch speed {
|
||||
case 1:
|
||||
return "low"
|
||||
case 2:
|
||||
return "full"
|
||||
case 3:
|
||||
return "high"
|
||||
case 5:
|
||||
return "super"
|
||||
case 6:
|
||||
return "super+"
|
||||
default:
|
||||
return "unknown"
|
||||
}
|
||||
}
|
||||
|
||||
// transferTypeName renders an endpoint transfer type.
|
||||
//
|
||||
// This is the field to look at when a device attaches but produces no data:
|
||||
// an interrupt endpoint reported as bulk is exactly that symptom, because the
|
||||
// kernel rejects the transfer.
|
||||
func transferTypeName(t uint8) string {
|
||||
switch t {
|
||||
case usb.TransferTypeControl:
|
||||
return "control"
|
||||
case usb.TransferTypeIsochronous:
|
||||
return "isochronous"
|
||||
case usb.TransferTypeBulk:
|
||||
return "bulk"
|
||||
case usb.TransferTypeInterrupt:
|
||||
return "interrupt"
|
||||
default:
|
||||
return fmt.Sprintf("unknown(%d)", t)
|
||||
}
|
||||
}
|
||||
|
||||
// endpointInfo renders one endpoint for the report.
|
||||
func endpointInfo(ep usb.Endpoint) EndpointInfo {
|
||||
direction := "OUT"
|
||||
if ep.IsIn() {
|
||||
direction = "IN"
|
||||
}
|
||||
|
||||
return EndpointInfo{
|
||||
Address: fmt.Sprintf("0x%02x", ep.Address),
|
||||
Direction: direction,
|
||||
TransferType: transferTypeName(ep.TransferType),
|
||||
MaxPacket: ep.MaxPacketSize,
|
||||
Interval: ep.Interval,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package diag
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// maxReportSize bounds a stored report, on both the sending and the
|
||||
// receiving side.
|
||||
const maxReportSize = 4 << 20 // 4 MB
|
||||
|
||||
// Upload posts a report to a relay's diagnostics endpoint and returns the URL
|
||||
// it can be fetched from.
|
||||
//
|
||||
// The point is getting a report off a machine that is awkward to copy from —
|
||||
// a headless NAS, a Windows box mid-debugging — without pasting thousands of
|
||||
// lines by hand.
|
||||
func Upload(relayURL, reportID string, report *Report) (string, error) {
|
||||
data, err := report.JSON()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("encoding report: %w", err)
|
||||
}
|
||||
if len(data) > maxReportSize {
|
||||
return "", fmt.Errorf("report is %d bytes, over the %d byte limit", len(data), maxReportSize)
|
||||
}
|
||||
|
||||
target, err := DiagURL(relayURL, reportID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
req, err := http.NewRequest(http.MethodPut, target, bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("building request: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
client := &http.Client{Timeout: 30 * time.Second}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("uploading to %s: %w", target, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {
|
||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, 1024))
|
||||
return "", fmt.Errorf("relay refused the report: %s: %s",
|
||||
resp.Status, strings.TrimSpace(string(body)))
|
||||
}
|
||||
|
||||
return target, nil
|
||||
}
|
||||
|
||||
// DiagURL builds the diagnostics URL for a report ID on a relay.
|
||||
//
|
||||
// It accepts the same address forms the client's relay setting does, so the
|
||||
// user does not have to remember a second syntax.
|
||||
func DiagURL(relayURL, reportID string) (string, error) {
|
||||
if reportID == "" {
|
||||
return "", fmt.Errorf("a report ID is required")
|
||||
}
|
||||
if strings.ContainsAny(reportID, "/?#") {
|
||||
return "", fmt.Errorf("report ID must not contain /, ? or #")
|
||||
}
|
||||
|
||||
base := strings.TrimSuffix(strings.TrimSpace(relayURL), "/")
|
||||
base = strings.TrimSuffix(base, "/ws")
|
||||
|
||||
switch {
|
||||
case strings.HasPrefix(base, "ws://"):
|
||||
base = "http://" + strings.TrimPrefix(base, "ws://")
|
||||
case strings.HasPrefix(base, "wss://"):
|
||||
base = "https://" + strings.TrimPrefix(base, "wss://")
|
||||
case strings.HasPrefix(base, "http://"), strings.HasPrefix(base, "https://"):
|
||||
// already fine
|
||||
default:
|
||||
base = "http://" + base
|
||||
}
|
||||
|
||||
return base + "/diag/" + reportID, nil
|
||||
}
|
||||
|
||||
// RetentionNote describes how long an uploaded report survives on the relay.
|
||||
// Kept here so the client can say so without importing the relay package.
|
||||
const RetentionNote = "24 hours"
|
||||
Reference in New Issue
Block a user