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:
+18
-9
@@ -8,6 +8,7 @@ import (
|
||||
"net/http"
|
||||
|
||||
"github.com/duffy/usb-server/internal/config"
|
||||
"github.com/duffy/usb-server/internal/protocol"
|
||||
"github.com/duffy/usb-server/internal/token"
|
||||
)
|
||||
|
||||
@@ -16,16 +17,16 @@ var staticFiles embed.FS
|
||||
|
||||
// Handler provides the web UI and API
|
||||
type Handler struct {
|
||||
cfg *config.Config
|
||||
cfgPath string
|
||||
mux *http.ServeMux
|
||||
cfg *config.Config
|
||||
cfgPath string
|
||||
mux *http.ServeMux
|
||||
|
||||
// Callbacks for device operations
|
||||
GetDevices func() interface{}
|
||||
AttachDevice func(clientID, busID string) error
|
||||
DetachDevice func(clientID, busID string) error
|
||||
SetAutoConnect func(vendorID, productID string, enabled bool) error
|
||||
IsAutoConnect func(vendorID, productID string) bool
|
||||
GetDevices func() interface{}
|
||||
AttachDevice func(clientID, busID string) error
|
||||
DetachDevice func(clientID, busID string) error
|
||||
SetAutoConnect func(vendorID, productID string, enabled bool) error
|
||||
IsAutoConnect func(vendorID, productID string) bool
|
||||
ForceDetachDevice func(clientID, busID string) error
|
||||
InstallService func() error
|
||||
UninstallService func() error
|
||||
@@ -171,6 +172,8 @@ func (h *Handler) handleConfig(w http.ResponseWriter, r *http.Request) {
|
||||
Name string `json:"name"`
|
||||
WebPort int `json:"web_port"`
|
||||
AllowForceDetach *bool `json:"allow_force_detach,omitempty"`
|
||||
DirectPort *int `json:"direct_port,omitempty"`
|
||||
DisableDirect *bool `json:"disable_direct,omitempty"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&updates); err != nil {
|
||||
writeJSON(w, map[string]interface{}{"ok": false, "error": "invalid request"})
|
||||
@@ -180,7 +183,7 @@ func (h *Handler) handleConfig(w http.ResponseWriter, r *http.Request) {
|
||||
if updates.RelayAddr != "" {
|
||||
h.cfg.RelayAddr = updates.RelayAddr
|
||||
}
|
||||
if updates.Mode == "share" || updates.Mode == "use" {
|
||||
if protocol.ValidMode(updates.Mode) {
|
||||
h.cfg.Mode = updates.Mode
|
||||
}
|
||||
if updates.Name != "" {
|
||||
@@ -192,6 +195,12 @@ func (h *Handler) handleConfig(w http.ResponseWriter, r *http.Request) {
|
||||
if updates.AllowForceDetach != nil {
|
||||
h.cfg.AllowForceDetach = *updates.AllowForceDetach
|
||||
}
|
||||
if updates.DirectPort != nil && *updates.DirectPort >= 0 && *updates.DirectPort <= 65535 {
|
||||
h.cfg.DirectPort = *updates.DirectPort
|
||||
}
|
||||
if updates.DisableDirect != nil {
|
||||
h.cfg.DisableDirect = *updates.DisableDirect
|
||||
}
|
||||
|
||||
if err := h.cfg.Save(h.cfgPath); err != nil {
|
||||
writeJSON(w, map[string]interface{}{"ok": false, "error": err.Error()})
|
||||
|
||||
+66
-28
@@ -27,10 +27,17 @@ async function updateStatus() {
|
||||
el.className = 'status disconnected';
|
||||
}
|
||||
|
||||
const modeNames = {
|
||||
share: 'Freigeben',
|
||||
use: 'Empfangen',
|
||||
both: 'Freigeben und Empfangen',
|
||||
};
|
||||
document.getElementById('mode-info').innerHTML =
|
||||
`<strong>Modus:</strong> ${data.mode === 'share' ? 'Freigeben' : 'Empfangen'} | ` +
|
||||
`<strong>Name:</strong> ${data.name} | ` +
|
||||
`<strong>Client ID:</strong> ${data.client_id ? data.client_id.substring(0, 8) + '...' : '-'}`;
|
||||
`<strong>Modus:</strong> ${escapeHtml(modeNames[data.mode] || data.mode)} | ` +
|
||||
`<strong>Name:</strong> ${escapeHtml(data.name)} | ` +
|
||||
`<strong>Client ID:</strong> ${data.client_id ? escapeHtml(data.client_id.substring(0, 8)) + '...' : '-'}` +
|
||||
(data.encrypted ? ' | <strong>Tunnel:</strong> verschluesselt'
|
||||
: ' | <strong>Tunnel:</strong> unverschluesselt (keine Tokens)');
|
||||
} catch (e) {
|
||||
const el = document.getElementById('status');
|
||||
el.textContent = 'Fehler';
|
||||
@@ -53,26 +60,34 @@ async function updateDevices() {
|
||||
function renderDevices(data) {
|
||||
const container = document.getElementById('device-list');
|
||||
|
||||
if (data.mode === 'share') {
|
||||
renderShareDevices(container, data.local_devices || []);
|
||||
} else {
|
||||
renderUseDevices(container, data.available_devices || [], data.attached_devices || []);
|
||||
// In "both" mode show remote devices first — those are the ones you act
|
||||
// on — then the local devices this machine offers.
|
||||
let html = '';
|
||||
if (data.available_devices || data.attached_devices) {
|
||||
html += renderUseSection(data.available_devices || [], data.attached_devices || []);
|
||||
}
|
||||
if (data.local_devices) {
|
||||
if (html) {
|
||||
html += '<div class="client-header">Eigene Geraete (freigegeben)</div>';
|
||||
}
|
||||
html += renderShareSection(data.local_devices);
|
||||
}
|
||||
|
||||
container.innerHTML = html || '<p class="no-devices">Keine Geraete</p>';
|
||||
}
|
||||
|
||||
function renderShareDevices(container, devices) {
|
||||
function renderShareSection(devices) {
|
||||
if (!devices || devices.length === 0) {
|
||||
container.innerHTML = '<p class="no-devices">Keine USB-Geraete gefunden</p>';
|
||||
return;
|
||||
return '<p class="no-devices">Keine USB-Geraete gefunden</p>';
|
||||
}
|
||||
|
||||
container.innerHTML = devices.map(dev => `
|
||||
return devices.map(dev => `
|
||||
<div class="device-card">
|
||||
<div class="device-info">
|
||||
<div class="device-name">${escapeHtml(dev.name)}</div>
|
||||
<div class="device-details">
|
||||
<span>Bus: ${dev.bus_id}</span>
|
||||
<span>VID:PID: ${dev.vendor_id}:${dev.product_id}</span>
|
||||
<span>Bus: ${escapeHtml(dev.bus_id)}</span>
|
||||
<span>VID:PID: ${escapeHtml(dev.vendor_id)}:${escapeHtml(dev.product_id)}</span>
|
||||
<span>Speed: ${speedName(dev.speed)}</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -85,7 +100,7 @@ function renderShareDevices(container, devices) {
|
||||
`).join('');
|
||||
}
|
||||
|
||||
function renderUseDevices(container, available, attached) {
|
||||
function renderUseSection(available, attached) {
|
||||
let html = '';
|
||||
|
||||
// Attached devices first
|
||||
@@ -97,18 +112,18 @@ function renderUseDevices(container, available, attached) {
|
||||
<div class="device-name">${escapeHtml(dev.name || dev.bus_id)}</div>
|
||||
<div class="device-details">
|
||||
<span>Von: ${escapeHtml(dev.client_name || dev.client_id)}</span>
|
||||
${dev.vendor_id ? `<span>VID:PID: ${dev.vendor_id}:${dev.product_id}</span>` : ''}
|
||||
<span>VHCI Port: ${dev.vhci_port}</span>
|
||||
${dev.vendor_id ? `<span>VID:PID: ${escapeHtml(dev.vendor_id)}:${escapeHtml(dev.product_id)}</span>` : ''}
|
||||
<span>VHCI Port: ${escapeHtml(dev.vhci_port)}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="device-status">
|
||||
<label class="auto-connect-label" title="Beim Start automatisch verbinden">
|
||||
<input type="checkbox" ${dev.auto_connect ? 'checked' : ''}
|
||||
onchange="toggleAutoConnect('${dev.vendor_id}', '${dev.product_id}', this.checked)">
|
||||
onchange="toggleAutoConnect('${jsArg(dev.vendor_id)}', '${jsArg(dev.product_id)}', this.checked)">
|
||||
Autostart
|
||||
</label>
|
||||
<span class="badge attached">Verbunden</span>
|
||||
<button class="btn small danger" onclick="detachDevice('${dev.client_id}', '${dev.bus_id}')">Trennen</button>
|
||||
<button class="btn small danger" onclick="detachDevice('${jsArg(dev.client_id)}', '${jsArg(dev.bus_id)}')">Trennen</button>
|
||||
</div>
|
||||
</div>
|
||||
`).join('');
|
||||
@@ -125,12 +140,11 @@ function renderUseDevices(container, available, attached) {
|
||||
});
|
||||
|
||||
if (Object.keys(byClient).length === 0 && (!attached || attached.length === 0)) {
|
||||
container.innerHTML = '<p class="no-devices">Keine Geraete verfuegbar. Warte auf Share-Clients...</p>';
|
||||
return;
|
||||
return '<p class="no-devices">Keine fremden Geraete verfuegbar. Warte auf Share-Clients...</p>';
|
||||
}
|
||||
|
||||
for (const [clientId, info] of Object.entries(byClient)) {
|
||||
html += `<div class="client-header">${escapeHtml(info.name)} (${clientId.substring(0, 8)}...)</div>`;
|
||||
html += `<div class="client-header">${escapeHtml(info.name)} (${escapeHtml(clientId.substring(0, 8))}...)</div>`;
|
||||
html += info.devices.map(dev => {
|
||||
const isAttached = (attached || []).some(a =>
|
||||
a.bus_id === dev.bus_id && a.client_id === clientId
|
||||
@@ -140,19 +154,19 @@ function renderUseDevices(container, available, attached) {
|
||||
<div class="device-info">
|
||||
<div class="device-name">${escapeHtml(dev.name)}</div>
|
||||
<div class="device-details">
|
||||
<span>Bus: ${dev.bus_id}</span>
|
||||
<span>VID:PID: ${dev.vendor_id}:${dev.product_id}</span>
|
||||
<span>Bus: ${escapeHtml(dev.bus_id)}</span>
|
||||
<span>VID:PID: ${escapeHtml(dev.vendor_id)}:${escapeHtml(dev.product_id)}</span>
|
||||
<span>Speed: ${speedName(dev.speed)}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="device-status">
|
||||
${dev.status === 'in_use'
|
||||
? `<span class="badge in-use">In Benutzung</span>
|
||||
${dev.allow_force_detach ? `<button class="btn small danger" onclick="forceDetach('${clientId}', '${dev.bus_id}')">Trennen</button>` : ''}`
|
||||
${dev.allow_force_detach ? `<button class="btn small danger" onclick="forceDetach('${jsArg(clientId)}', '${jsArg(dev.bus_id)}')">Trennen</button>` : ''}`
|
||||
: isAttached
|
||||
? '<span class="badge attached">Verbunden</span>'
|
||||
: `<span class="badge available">Verfuegbar</span>
|
||||
<button class="btn small primary" onclick="attachDevice('${clientId}', '${dev.bus_id}')">Verbinden</button>`
|
||||
<button class="btn small primary" onclick="attachDevice('${jsArg(clientId)}', '${jsArg(dev.bus_id)}')">Verbinden</button>`
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
@@ -160,7 +174,7 @@ function renderUseDevices(container, available, attached) {
|
||||
}).join('');
|
||||
}
|
||||
|
||||
container.innerHTML = html || '<p class="no-devices">Keine Geraete verfuegbar</p>';
|
||||
return html;
|
||||
}
|
||||
|
||||
// Attach/Detach
|
||||
@@ -246,6 +260,8 @@ async function loadSettings() {
|
||||
document.getElementById('client-name').value = cfg.name || '';
|
||||
document.getElementById('web-port').value = cfg.web_port || 8080;
|
||||
document.getElementById('allow-force-detach').checked = cfg.allow_force_detach || false;
|
||||
document.getElementById('direct-port').value = cfg.direct_port || 0;
|
||||
document.getElementById('disable-direct').checked = cfg.disable_direct || false;
|
||||
document.getElementById('token1').value = cfg.token1 || '';
|
||||
document.getElementById('token2').value = cfg.token2 || '';
|
||||
document.getElementById('token3').value = cfg.token3 || '';
|
||||
@@ -269,6 +285,8 @@ document.getElementById('settings-form').addEventListener('submit', async (e) =>
|
||||
name: document.getElementById('client-name').value,
|
||||
web_port: parseInt(document.getElementById('web-port').value),
|
||||
allow_force_detach: document.getElementById('allow-force-detach').checked,
|
||||
direct_port: parseInt(document.getElementById('direct-port').value) || 0,
|
||||
disable_direct: document.getElementById('disable-direct').checked,
|
||||
})
|
||||
});
|
||||
const data = await resp.json();
|
||||
@@ -354,8 +372,28 @@ function speedName(speed) {
|
||||
}
|
||||
|
||||
function escapeHtml(str) {
|
||||
if (!str) return '';
|
||||
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
||||
if (str === null || str === undefined) return '';
|
||||
return String(str)
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
// jsArg escapes a value for use inside a single-quoted JavaScript string that
|
||||
// itself sits in an HTML attribute. Bus IDs, client IDs and vendor strings all
|
||||
// arrive from remote peers, so interpolating them raw would let another client
|
||||
// in the group inject script into this UI.
|
||||
function jsArg(str) {
|
||||
if (str === null || str === undefined) return '';
|
||||
return String(str)
|
||||
.replace(/\\/g, '\\\\')
|
||||
.replace(/'/g, "\\'")
|
||||
.replace(/"/g, '"')
|
||||
.replace(/</g, '\\x3c')
|
||||
.replace(/>/g, '\\x3e')
|
||||
.replace(/&/g, '\\x26');
|
||||
}
|
||||
|
||||
// Init
|
||||
|
||||
@@ -43,9 +43,11 @@
|
||||
<div class="form-group">
|
||||
<label for="mode">Modus</label>
|
||||
<select id="mode">
|
||||
<option value="share">Freigeben (Share)</option>
|
||||
<option value="use">Empfangen (Use)</option>
|
||||
<option value="both">Beides (Freigeben und Empfangen)</option>
|
||||
<option value="share">Nur Freigeben (Share)</option>
|
||||
<option value="use">Nur Empfangen (Use)</option>
|
||||
</select>
|
||||
<small>Nach dem Speichern neu starten, damit der Modus wirkt</small>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="client-name">Client Name</label>
|
||||
@@ -62,6 +64,20 @@
|
||||
</label>
|
||||
<small>Erlaubt Use-Clients, Geraete die von anderen benutzt werden zu trennen</small>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="direct-port">Port fuer Direktverbindungen</label>
|
||||
<input type="number" id="direct-port" min="0" max="65535" value="0">
|
||||
<small>0 = zufaelliger Port. Fest setzen, wenn der Port durch eine Firewall
|
||||
oder NAT weitergeleitet werden muss.</small>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="auto-connect-label">
|
||||
<input type="checkbox" id="disable-direct">
|
||||
Direktverbindungen deaktivieren
|
||||
</label>
|
||||
<small>Erzwingt, dass aller USB-Verkehr ueber den Relay laeuft. Normalerweise
|
||||
verbinden sich Clients direkt, was Latenz spart und den Relay entlastet.</small>
|
||||
</div>
|
||||
<button type="submit" class="btn primary">Speichern</button>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
Reference in New Issue
Block a user