Something went wrong. Try again.
An experimental port of NetBSD, FreeBSD, OpenBSD, and XNU to unkernel unkernel.dev
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167// SPDX-License-Identifier: MIT// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>// USB devices for the guest: WebUSB devices (navigator.usb) plugged into// the ports of its kwusb root hub (vm.usb, js/core/usb.ts; the USBDevice// wrapper is js/web/usb.ts). The machine always has the hub (boot.ts// passes `usb: true`, which costs nothing until a device is attached);// nothing here touches WebUSB before the machine runs.// - Connect (Settings > USB devices, Settings.tsx):// requestDevice() from the click, then the device goes to the first// free port. The guest enumerates it as its own (lsusb, /dev/bus/usb,// /dev/ttyUSB* for the serial bridges the kernel has drivers for; the// guest's kwhotplug opens the nodes to the image's user).// - Devices this origin was allowed before (getDevices()) are attached// once the machine runs, and again when plugged in (navigator.usb's// "connect": a board that re-enumerates, as into its bootloader, comes// back by itself when it keeps its ids, and needs Connect again when it// shows up as another device); unplugging one is a disconnect in the// guest and frees the port.// - Disconnect detaches the device and forgets it (USBDevice.forget()),// so the next boot does not attach it again.// The browser keeps some interfaces to itself (HID, mass storage, audio,// video, smart cards, wireless controllers): the guest does not see them// (UsbPortState.hidden), and a device with nothing else is of no use.// Where WebUSB is missing (browsers other than Chromium-based ones, an// insecure context) the section says why and offers nothing.
import { useSyncExternalStore } from "react";import { KW } from "./kw.ts";import { WebUsbBackend, webUsb, webUsbBackend, webUsbBlocker, type KernelHandle, type UsbPortState, type WebUsbDevice } from "./sdk.ts";
export interface UsbView { /** Why there is no WebUSB here, or null. */ why: string | null; /** The machine runs with a USB root hub. */ running: boolean; /** One per root hub port, attached or not. */ ports: UsbPortState[];}
let view: UsbView = { why: null, running: false, ports: [] };let blockerChecked = false;const listeners = new Set<() => void>();let vm: KernelHandle | undefined;const backends = new Map<WebUsbDevice, WebUsbBackend>();/** Devices being attached (attach() is asynchronous: a second Connect or "connect" event must not start another). */const attaching = new Set<WebUsbDevice>();let log: (msg: string) => void = (m) => console.warn(m);
let publishTimer: ReturnType<typeof setTimeout> | undefined;/** The view again, at most every 200 ms (Settings renders all the time). */function publish(): void { publishTimer ??= setTimeout(() => { publishTimer = undefined; const u = vm?.usb; view = { why: view.why, running: !!u, ports: u ? u.states : [] }; for (const l of listeners) l(); }, 200);}
function snapshot(): UsbView { if (!blockerChecked) { blockerChecked = true; view = { ...view, why: webUsbBlocker() ?? null }; } return view;}
/** The USB ports' state, for the Settings section. */export function useUsb(): UsbView { return useSyncExternalStore((l) => { listeners.add(l); return () => listeners.delete(l); }, snapshot);}
/** The machine runs: its ports follow vm.usb, and the devices allowed before are attached. */export function attachUsb(machine: KernelHandle, hostLog: (msg: string) => void): void { const u = machine.usb; if (!u) return; vm = machine; log = hostLog; u.onChange(() => publish()); void machine.exited.then(() => { if (vm === machine) vm = undefined; publish(); }); publish(); const nu = webUsb(); if (webUsbBlocker() || !nu) return; nu.addEventListener("connect", (e) => { const device = (e as Event & { device?: WebUsbDevice }).device; if (!device) return; void attachDevice(device).then((slot) => { if (slot !== undefined) KW.ui?.toast(`${backends.get(device)!.info.label} plugged in: USB port ${slot + 1} of the guest`); }); }); void nu.getDevices().then(async (devices) => { for (const d of devices) { const slot = await attachDevice(d, true); if (slot !== undefined) log(`[usb] ${backends.get(d)!.info.label}, allowed before, is on USB port ${slot + 1}`); } }, (e: unknown) => log(`[usb] getDevices(): ${(e as Error)?.message ?? e}`));}
/** Attach `device` to the first free port; the slot, or undefined when it is attached already or could not be (said in a toast, or only logged when `quiet`). */async function attachDevice(device: WebUsbDevice, quiet = false): Promise<number | undefined> { const u = vm?.usb; if (!u || attaching.has(device)) return undefined; let b = backends.get(device); if (!b) backends.set(device, (b = webUsbBackend(device))); if (u.slotOf(b) >= 0) return undefined; attaching.add(device); try { const slot = await u.attach(b); const st = u.state(slot); log(`[usb] ${b.info.label}: port ${slot + 1}, ${st.speed ?? "?"} speed, runs ${st.runs}${st.hidden.length ? `, interfaces ${st.hidden.join(", ")} hidden` : ""}`); return slot; } catch (e) { backends.delete(device); const msg = `USB: ${b.info.label}: ${(e as Error)?.message ?? e}`; if (quiet) log(`[usb] ${msg}`); else KW.ui?.toast(msg); return undefined; } finally { attaching.delete(device); publish(); }}
/** Connect…: pick a device (Chrome's chooser; call from the click itself) and plug it into the first free port. */export function connectUsb(): void { const nu = webUsb(); const u = vm?.usb; if (!nu || !u) return; nu.requestDevice({ filters: [] }).then(async (device) => { const b = backends.get(device); if (b && u.slotOf(b) >= 0) { KW.ui?.toast(`${b.info.label} is on USB port ${u.slotOf(b) + 1} already`); return; } const slot = await attachDevice(device); if (slot === undefined) return; const st = u.state(slot); const label = backends.get(device)!.info.label; KW.ui?.toast(st.hidden.length ? `${label} is in the guest (lsusb), without the interfaces the browser keeps to itself (${st.hidden.join(", ")})` : `${label} is in the guest (lsusb)`); }, (e: unknown) => { // NotFoundError: the chooser was closed without a device. if ((e as Error)?.name !== "NotFoundError") KW.ui?.toast(`USB: ${(e as Error)?.message ?? e}`); });}
/** Disconnect: unplug the device from the guest (a program using it sees it go) and forget it. */export async function disconnectUsb(slot: number): Promise<void> { const u = vm?.usb; if (!u) return; let device: WebUsbDevice | undefined; for (const [d, b] of backends) if (u.slotOf(b) === slot) device = d; await u.detach(slot).catch((e: unknown) => log(`[usb] detach: ${(e as Error)?.message ?? e}`)); if (device) { backends.delete(device); await (device as WebUsbDevice & { forget?: () => Promise<void> }).forget?.().catch(() => {}); } publish();}