mirror of
https://github.com/pithings/unkernel.git
synced 2026-12-02 04:41:10 +08:00
226 lines
10 KiB
TypeScript
226 lines
10 KiB
TypeScript
// SPDX-License-Identifier: MIT
|
|
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
|
|
// WebUSB (navigator.usb: Chromium-based browsers, in a secure context) as
|
|
// a UsbBackend (js/core/usb.ts) for the guest's kwusb root hub.
|
|
//
|
|
// const device = await navigator.usb.requestDevice({ filters: [] }); // in a click handler
|
|
// await vm.usb.attach(webUsbBackend(device));
|
|
//
|
|
// The backend is a thin adapter: the translation of the guest's requests
|
|
// (SET_ADDRESS, SET_CONFIGURATION, SET_INTERFACE, CLEAR_FEATURE, resets,
|
|
// hidden interfaces, parked reads, the speed) is UsbHost's. DataViews
|
|
// become Uint8Array views of the same bytes, and the device's "disconnect"
|
|
// event on navigator.usb is listen()'s loss.
|
|
//
|
|
// Worker mode: the spec exposes WebUSB in workers (USB is
|
|
// [Exposed=(Worker,Window)]; requestDevice() is the window's only), and
|
|
// getDevices() there lists the devices the origin was granted (Chromium
|
|
// gates dedicated workers behind its WebUSBOnDedicatedWorkers feature;
|
|
// where a worker has no navigator.usb the device stays on this thread). A USBDevice
|
|
// cannot be posted, so the kernel's worker opens the same device itself:
|
|
// workerKey() gives its ids when no other granted device has the same
|
|
// ones (vendor and product ids, serial number, names, version), and
|
|
// openWebUsbByKey() (the web worker entry's openUsb) finds it there. Then
|
|
// every transfer runs in the kernel's worker with no hop to this thread.
|
|
// A device without such ids (two identical boards without serial numbers)
|
|
// stays on this thread and is driven over messages. The page must not
|
|
// claim the device's interfaces itself (a second context's claim fails).
|
|
|
|
import type { UsbBackend, UsbBackendInfo, UsbControlSetup, UsbDeviceKey, UsbInResult, UsbIsoInResult, UsbIsoOutResult, UsbOutResult } from "../core/usb.ts";
|
|
|
|
/** The parts of WebUSB's USBDevice this uses (TypeScript's DOM library has no WebUSB). */
|
|
export interface WebUsbDevice {
|
|
readonly vendorId: number;
|
|
readonly productId: number;
|
|
readonly serialNumber?: string | null;
|
|
readonly manufacturerName?: string | null;
|
|
readonly productName?: string | null;
|
|
readonly deviceVersionMajor?: number;
|
|
readonly deviceVersionMinor?: number;
|
|
readonly deviceVersionSubminor?: number;
|
|
readonly opened: boolean;
|
|
readonly configuration: { configurationValue: number } | null;
|
|
open(): Promise<void>;
|
|
close(): Promise<void>;
|
|
reset(): Promise<void>;
|
|
selectConfiguration(value: number): Promise<void>;
|
|
claimInterface(n: number): Promise<void>;
|
|
releaseInterface(n: number): Promise<void>;
|
|
selectAlternateInterface(n: number, alt: number): Promise<void>;
|
|
clearHalt(direction: "in" | "out", endpoint: number): Promise<void>;
|
|
controlTransferIn(setup: UsbControlSetup, length: number): Promise<{ status: string; data?: DataView | null }>;
|
|
controlTransferOut(setup: UsbControlSetup, data?: BufferSource): Promise<{ status: string; bytesWritten: number }>;
|
|
transferIn(endpoint: number, length: number): Promise<{ status: string; data?: DataView | null }>;
|
|
transferOut(endpoint: number, data: BufferSource): Promise<{ status: string; bytesWritten: number }>;
|
|
isochronousTransferIn(endpoint: number, packetLengths: number[]): Promise<{ packets: Array<{ status: string; data?: DataView | null }> }>;
|
|
isochronousTransferOut(endpoint: number, data: BufferSource, packetLengths: number[]): Promise<{ packets: Array<{ status: string; bytesWritten: number }> }>;
|
|
}
|
|
|
|
/** navigator.usb. */
|
|
export interface WebUsb extends EventTarget {
|
|
requestDevice(options: { filters: Array<{ vendorId?: number; productId?: number; classCode?: number; serialNumber?: string }> }): Promise<WebUsbDevice>;
|
|
getDevices(): Promise<WebUsbDevice[]>;
|
|
}
|
|
|
|
/** navigator.usb where there is one (a window or a dedicated worker). */
|
|
export function webUsb(): WebUsb | undefined {
|
|
const nav = (globalThis as { navigator?: { usb?: WebUsb } }).navigator;
|
|
return nav?.usb ?? undefined;
|
|
}
|
|
|
|
/**
|
|
* Why WebUSB cannot be used here, or undefined: no navigator.usb (browsers
|
|
* other than Chromium-based ones), not a secure context, or a permissions
|
|
* policy that blocks `usb`.
|
|
*/
|
|
export function webUsbBlocker(): string | undefined {
|
|
const g = globalThis as { isSecureContext?: boolean; document?: { featurePolicy?: { allowsFeature(f: string): boolean }; permissionsPolicy?: { allowsFeature(f: string): boolean } } };
|
|
if (g.isSecureContext === false) return "WebUSB needs a secure context (https, or http://localhost)";
|
|
if (!webUsb()) return "this browser has no WebUSB (Chrome, Edge and other Chromium-based browsers have it)";
|
|
const policy = g.document?.permissionsPolicy ?? g.document?.featurePolicy;
|
|
try {
|
|
if (policy && !policy.allowsFeature("usb")) return "the page's permissions policy does not allow usb";
|
|
} catch {}
|
|
return undefined;
|
|
}
|
|
|
|
const hex = (n: number) => n.toString(16).padStart(4, "0");
|
|
|
|
function versionOf(d: WebUsbDevice): string | undefined {
|
|
return d.deviceVersionMajor === undefined ? undefined : `${d.deviceVersionMajor}.${d.deviceVersionMinor ?? 0}.${d.deviceVersionSubminor ?? 0}`;
|
|
}
|
|
|
|
/** The ids that tell `d` from other devices. */
|
|
export function webUsbKey(d: WebUsbDevice): UsbDeviceKey {
|
|
return {
|
|
vendorId: d.vendorId, productId: d.productId, serialNumber: d.serialNumber ?? undefined,
|
|
manufacturerName: d.manufacturerName ?? undefined, productName: d.productName ?? undefined, deviceVersion: versionOf(d),
|
|
};
|
|
}
|
|
|
|
function sameKey(a: UsbDeviceKey, b: UsbDeviceKey): boolean {
|
|
return a.vendorId === b.vendorId && a.productId === b.productId && a.serialNumber === b.serialNumber && a.manufacturerName === b.manufacturerName && a.productName === b.productName && a.deviceVersion === b.deviceVersion;
|
|
}
|
|
|
|
/** "USB 2e8a:000a Pico" from a device's ids. */
|
|
export function usbDeviceLabel(d: { vendorId: number; productId: number; productName?: string | null }): string {
|
|
return `USB ${hex(d.vendorId)}:${hex(d.productId)}${d.productName ? ` ${d.productName}` : ""}`;
|
|
}
|
|
|
|
const view = (v: DataView | null | undefined): Uint8Array | undefined => (v ? new Uint8Array(v.buffer, v.byteOffset, v.byteLength) : undefined);
|
|
const status = (s: string) => (s === "stall" || s === "babble" ? s : "ok") as UsbInResult["status"];
|
|
/** WebUSB copies the data during the call; a view of a shared memory is copied first. */
|
|
const source = (d: Uint8Array): BufferSource => (d.buffer instanceof ArrayBuffer ? d as Uint8Array<ArrayBuffer> : d.slice());
|
|
|
|
/** A WebUSB USBDevice as a UsbBackend: attach it with vm.usb.attach(). */
|
|
export class WebUsbBackend implements UsbBackend {
|
|
readonly device: WebUsbDevice;
|
|
readonly info: UsbBackendInfo;
|
|
|
|
constructor(device: WebUsbDevice) {
|
|
this.device = device;
|
|
this.info = {
|
|
vendorId: device.vendorId, productId: device.productId, serialNumber: device.serialNumber ?? undefined,
|
|
manufacturerName: device.manufacturerName ?? undefined, productName: device.productName ?? undefined, label: usbDeviceLabel(device),
|
|
};
|
|
}
|
|
|
|
async open(): Promise<void> {
|
|
if (!this.device.opened) await this.device.open();
|
|
}
|
|
|
|
async close(): Promise<void> {
|
|
if (this.device.opened) await this.device.close();
|
|
}
|
|
|
|
reset(): Promise<void> {
|
|
return this.device.reset();
|
|
}
|
|
|
|
async selectConfiguration(value: number): Promise<void> {
|
|
if (this.device.configuration?.configurationValue !== value) await this.device.selectConfiguration(value);
|
|
}
|
|
|
|
claimInterface(n: number): Promise<void> {
|
|
return this.device.claimInterface(n);
|
|
}
|
|
|
|
releaseInterface(n: number): Promise<void> {
|
|
return this.device.releaseInterface(n);
|
|
}
|
|
|
|
selectAlternateInterface(n: number, alt: number): Promise<void> {
|
|
return this.device.selectAlternateInterface(n, alt);
|
|
}
|
|
|
|
clearHalt(direction: "in" | "out", endpoint: number): Promise<void> {
|
|
return this.device.clearHalt(direction, endpoint);
|
|
}
|
|
|
|
async controlTransferIn(setup: UsbControlSetup, length: number): Promise<UsbInResult> {
|
|
const r = await this.device.controlTransferIn(setup, length);
|
|
return { status: status(r.status), data: view(r.data) };
|
|
}
|
|
|
|
async controlTransferOut(setup: UsbControlSetup, data?: Uint8Array): Promise<UsbOutResult> {
|
|
const r = await (data?.length ? this.device.controlTransferOut(setup, source(data)) : this.device.controlTransferOut(setup));
|
|
return { status: status(r.status), bytesWritten: r.bytesWritten };
|
|
}
|
|
|
|
async transferIn(endpoint: number, length: number): Promise<UsbInResult> {
|
|
const r = await this.device.transferIn(endpoint, length);
|
|
return { status: status(r.status), data: view(r.data) };
|
|
}
|
|
|
|
async transferOut(endpoint: number, data: Uint8Array): Promise<UsbOutResult> {
|
|
const r = await this.device.transferOut(endpoint, source(data));
|
|
return { status: status(r.status), bytesWritten: r.bytesWritten };
|
|
}
|
|
|
|
async isochronousTransferIn(endpoint: number, packetLengths: number[]): Promise<UsbIsoInResult> {
|
|
const r = await this.device.isochronousTransferIn(endpoint, packetLengths);
|
|
return { packets: r.packets.map((p) => ({ status: status(p.status), data: view(p.data) })) };
|
|
}
|
|
|
|
async isochronousTransferOut(endpoint: number, data: Uint8Array, packetLengths: number[]): Promise<UsbIsoOutResult> {
|
|
const r = await this.device.isochronousTransferOut(endpoint, source(data), packetLengths);
|
|
return { packets: r.packets.map((p) => ({ status: status(p.status), bytesWritten: p.bytesWritten })) };
|
|
}
|
|
|
|
listen(lost: () => void): () => void {
|
|
const usb = webUsb();
|
|
if (!usb) return () => {};
|
|
const on = (e: Event) => {
|
|
if ((e as Event & { device?: WebUsbDevice }).device === this.device) lost();
|
|
};
|
|
usb.addEventListener("disconnect", on);
|
|
return () => usb.removeEventListener("disconnect", on);
|
|
}
|
|
|
|
/** The ids by which the kernel's worker can open this device itself, when no other granted device has them. */
|
|
async workerKey(): Promise<UsbDeviceKey | undefined> {
|
|
const usb = webUsb();
|
|
if (!usb) return undefined;
|
|
const key = webUsbKey(this.device);
|
|
const same = (await usb.getDevices()).filter((d) => sameKey(webUsbKey(d), key));
|
|
return same.length === 1 ? key : undefined;
|
|
}
|
|
}
|
|
|
|
/** A WebUSB USBDevice as a UsbBackend (see WebUsbBackend). */
|
|
export function webUsbBackend(device: WebUsbDevice): WebUsbBackend {
|
|
return new WebUsbBackend(device);
|
|
}
|
|
|
|
/**
|
|
* In the kernel's worker: the granted device with these ids, as a
|
|
* backend, or undefined when there is none, or more than one, or no
|
|
* navigator.usb here.
|
|
*/
|
|
export async function openWebUsbByKey(key: UsbDeviceKey): Promise<UsbBackend | undefined> {
|
|
const usb = webUsb();
|
|
if (!usb) return undefined;
|
|
const same = (await usb.getDevices()).filter((d) => sameKey(webUsbKey(d), key));
|
|
return same.length === 1 ? new WebUsbBackend(same[0]!) : undefined;
|
|
}
|