From a00216cb23141ff5ee532d0dd5771374e7159392 Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Fri, 20 Nov 2026 21:47:49 +0000 Subject: [PATCH] js: answer chosen plain-http hosts with the host's fetch (fetchRoutes, a NetBackend wrapper with a small HTTP/1.1 server, and routes in the wisp spec); web: route deb.debian.org to a CORS mirror (?routes=0 turns it off) --- .agents/js.md | 14 +++ js/core/devices.ts | 15 ++- js/core/index.ts | 2 + js/core/net-fetch.ts | 281 +++++++++++++++++++++++++++++++++++++++++++ web/src/boot.ts | 4 +- web/src/config.ts | 23 +++- web/src/net.ts | 23 ++-- 7 files changed, 345 insertions(+), 17 deletions(-) create mode 100644 js/core/net-fetch.ts diff --git a/.agents/js.md b/.agents/js.md index 96e16ab..2ca67a8 100644 --- a/.agents/js.md +++ b/.agents/js.md @@ -1249,6 +1249,20 @@ parts that are easy to get wrong. 198.18.0.0/15 and a bad name fails at connect time. It also has no connect acknowledgement (a refused connect becomes a reset), no half-close, and flow control in one direction only. +- `fetchRoutes(inner, routes)` (`net-fetch.ts`) wraps a backend: the host + names in `routes` resolve to reserved addresses in 198.51.100.0/24, and + port 80 on them is a minimal HTTP/1.1 server (GET and HEAD, keep-alive, + pipelined requests answered in order) that answers with `fetch()`: a + string route rewrites the prefix (`http://HOST/p` to `BASE/p`) and + forwards only Range, If-Range, If-Modified-Since and If-None-Match, a + function route gets a `Request`. Other ports on those addresses are refused; everything else + goes to `inner`. In a browser the target's CORS must allow those + four headers, and one that + compresses must expose Content-Encoding (the answer is then chunked; + unseen, the decoded body goes out with the encoded length). The wisp spec + takes the string form as `routes` (`buildNet()`). The page routes + `deb.debian.org` to a CORS mirror (`web/src/config.ts` DEFAULT_ROUTES, + `?routes=0` turns it off). - Not implemented: IPv6, IP fragments, UDP beyond DHCP and DNS, ICMP beyond 10.0.2.2/3, SACK, timestamps and inbound connections. A raw-Ethernet relay backend is not useful: v86's relay gave DHCP but no upstream DNS diff --git a/js/core/devices.ts b/js/core/devices.ts index abf5fe7..90215c1 100644 --- a/js/core/devices.ts +++ b/js/core/devices.ts @@ -23,11 +23,13 @@ // kernel bundle's unkernel.datadisk template or bytes; // the page's /data, openDataDisk()) // net a NetStack over a backend: "direct" (Node: host sockets, the -// CLI's default) or "wisp" (a Wisp server; everywhere) +// CLI's default) or "wisp" (a Wisp server; everywhere, with +// `routes` answered by fetch(), net-fetch.ts) import { BaseDisk, CowDisk, F_RO, HttpBase, type BlockDevice, type CowDiskStats } from "./block.ts"; import { BootError } from "./load.ts"; import { NetStack, type NetBackend } from "./net.ts"; +import { fetchRoutes } from "./net-fetch.ts"; import { wispBackend } from "./net-wisp.ts"; /** The spec format. A spec may carry `v`; a factory refuses other versions. */ @@ -85,7 +87,11 @@ export interface NetSpec extends SpecCommon { kind: "net"; backend: | { kind: "direct" } - | { kind: "wisp"; servers: string | string[]; headers?: Record }; + | { + kind: "wisp"; servers: string | string[]; headers?: Record; + /** Plain HTTP to these host names is answered with fetch() from these base URLs (net-fetch.ts fetchRoutes()). */ + routes?: Record; + }; /** TCP to the gateway (10.0.2.2) goes to the host's 127.0.0.1 (direct only). */ hostLoopback?: boolean; mtu?: number; @@ -189,7 +195,10 @@ export function buildNet(spec: NetSpec, registry: DeviceRegistry | undefined, ct const make = registry?.backends[spec.backend.kind] as ((s: NetBackendSpec, c: DeviceContext) => NetBackend) | undefined; try { if (!make) throw new BootError("support", `network backend "${spec.backend.kind}" is not available on this platform`); - return new NetStack({ backend: make(spec.backend, { ...ctx, index: 0 }), hostLoopback: spec.hostLoopback, mtu: spec.mtu, mac: spec.mac, log: ctx.log }); + const inner = make(spec.backend, { ...ctx, index: 0 }); + const routes = spec.backend.kind === "wisp" ? spec.backend.routes : undefined; + const backend = routes && Object.keys(routes).length ? fetchRoutes(inner, routes, { log: ctx.log }) : inner; + return new NetStack({ backend, hostLoopback: spec.hostLoopback, mtu: spec.mtu, mac: spec.mac, log: ctx.log }); } catch (e) { if (!spec.optional) throw e; ctx.log(`[host] network left out: ${(e as Error)?.message ?? e}`); diff --git a/js/core/index.ts b/js/core/index.ts index b962c6c..a01ed5f 100644 --- a/js/core/index.ts +++ b/js/core/index.ts @@ -14,6 +14,8 @@ export { NetStack, ip4, ip4str } from "./net.ts"; export type { NetBackend, NetConnection, NetConnectionEvents, NetStackOptions, NetStats } from "./net.ts"; export { DEFAULT_WISP_SERVERS, wispBackend } from "./net-wisp.ts"; export type { WispBackend, WispBackendOptions } from "./net-wisp.ts"; +export { fetchRoutes } from "./net-fetch.ts"; +export type { FetchRoute, FetchRoutesBackend, FetchRoutesOptions } from "./net-fetch.ts"; export { ANSI, ConsoleRouter, IMPORTANT, KSTAMP } from "./console.ts"; export type { ConsoleRouterOptions, KernelLineInfo } from "./console.ts"; export { checkJspi, checkSupport } from "./support.ts"; diff --git a/js/core/net-fetch.ts b/js/core/net-fetch.ts new file mode 100644 index 0000000..12e69d2 --- /dev/null +++ b/js/core/net-fetch.ts @@ -0,0 +1,281 @@ +// SPDX-License-Identifier: MIT +// Copyright (C) 2026 Pooya Parsa +// NetStack backend wrapper that answers plain-HTTP connections to chosen +// host names with the host's fetch() instead of the inner backend: a +// minimal HTTP/1.1 server per connection (GET and HEAD, keep-alive with +// pipelining, answered strictly in order). Everything else goes to the +// inner backend. +// +// fetchRoutes(inner, { "example.org": "https://cors.example/base" }) +// +// A routed name resolves to a reserved address of 198.51.100.0/24 +// (TEST-NET-2: outside Wisp's 198.18.0.0/15 and the guest's 10.0.2.0/24, +// and passed through by NetStack.backendHost()). A connection to it on port +// 80 is served here; on another port it is refused. +// +// A string route rewrites the URL's prefix (http://HOST/path?q becomes +// BASE/path?q) and forwards only the headers in FORWARD_HEADERS; a +// function route gets a Request with the guest's headers. + +import type { NetBackend, NetConnection, NetConnectionEvents } from "./net.ts"; + +/** A base URL (prefix rewrite) or a handler. */ +export type FetchRoute = string | ((req: Request) => Response | Promise); + +export interface FetchRoutesOptions { + log?: (msg: string) => void; +} + +/** close() aborts every served request and closes the inner backend. */ +export interface FetchRoutesBackend extends NetBackend { + close(): void; +} + +/** Request headers a string route forwards (in a browser the target's CORS must allow them). */ +const FORWARD_HEADERS = ["range", "if-range", "if-modified-since", "if-none-match"]; +/** Response headers copied into the answer (besides the length and framing). */ +const COPY_HEADERS = ["Content-Range", "ETag", "Last-Modified", "Accept-Ranges", "Content-Type"]; +/** Guest headers not passed to a function route. */ +const HOP_HEADERS = new Set(["host", "connection", "keep-alive", "transfer-encoding", "content-length", "upgrade", "proxy-connection", "te"]); + +const ROUTE_BASE = (198 << 24 | 51 << 16 | 100 << 8) >>> 0; +const MAX_ROUTES = 254; +const MAX_HEAD = 16 * 1024; +const REASONS: Record = { + 200: "OK", 204: "No Content", 206: "Partial Content", 301: "Moved Permanently", 302: "Found", 304: "Not Modified", + 400: "Bad Request", 403: "Forbidden", 404: "Not Found", 405: "Method Not Allowed", 416: "Range Not Satisfiable", + 431: "Request Header Fields Too Large", 500: "Internal Server Error", 502: "Bad Gateway", 503: "Service Unavailable", +}; + +const enc = new TextEncoder(); +const latin1 = new TextDecoder("latin1"); +const ipStr = (ip: number) => `${ip >>> 24}.${(ip >>> 16) & 255}.${(ip >>> 8) & 255}.${ip & 255}`; +const normName = (s: string) => s.toLowerCase().replace(/\.$/, ""); + +interface Req { + method: string; + path: string; + headers: [string, string][]; + /** Close the connection after this answer. */ + close: boolean; + /** Answer this status without fetching (a bad request). */ + status?: number; +} + +/** A refused connection: onClose with an error, asynchronously. */ +function refused(ev: NetConnectionEvents, why: string): NetConnection { + let dead = false; + queueMicrotask(() => { if (!dead) ev.onClose(new Error(why)); }); + return { write() {}, end() {}, destroy() { dead = true; }, pause() {}, resume() {}, buffered: 0 }; +} + +function parseHead(head: string): Req { + const lines = head.split("\r\n"); + const [method = "", target = "", version = "", ...rest] = lines[0]!.split(" "); + const bad = (status: number): Req => ({ method, path: "/", headers: [], close: true, status }); + if (rest.length || !/^HTTP\/1\.[01]$/.test(version)) return bad(400); + const headers: [string, string][] = []; + for (const l of lines.slice(1)) { + const i = l.indexOf(":"); + if (i <= 0) return bad(400); + headers.push([l.slice(0, i).trim().toLowerCase(), l.slice(i + 1).trim()]); + } + const get = (n: string) => headers.find(([k]) => k === n)?.[1]; + const conn = get("connection") ?? ""; + const close = version === "HTTP/1.0" ? !/keep-alive/i.test(conn) : /\bclose\b/i.test(conn); + if (method !== "GET" && method !== "HEAD") return bad(405); + if (get("transfer-encoding") || Number(get("content-length") ?? 0) > 0) return bad(400); + // Absolute form (a proxy request): keep the path. + const path = /^https?:\/\//i.test(target) ? target.replace(/^https?:\/\/[^/]*/i, "") || "/" : target; + if (!path.startsWith("/")) return bad(400); + return { method, path, headers, close }; +} + +/** + * Wrap `inner` (or nothing: other names do not resolve and other + * connections are refused) so that plain HTTP to the host names of + * `routes` is answered with fetch(). + */ +export function fetchRoutes(inner: NetBackend | undefined, routes: Record, opts: FetchRoutesOptions = {}): FetchRoutesBackend { + const log = opts.log; + const byName = new Map(); + const byIp = new Map(); + for (const [name, route] of Object.entries(routes)) { + if (byName.size >= MAX_ROUTES) throw new Error(`fetchRoutes: more than ${MAX_ROUTES} routes`); + const r = { name: normName(name), ip: ipStr(ROUTE_BASE + byName.size + 1), route }; + byName.set(r.name, r); + byIp.set(r.ip, r); + } + const conns = new Set<() => void>(); + + function fetchFor(host: string, route: FetchRoute, req: Req, signal: AbortSignal): Promise { + if (typeof route !== "string") { + const headers = new Headers(); + for (const [k, v] of req.headers) if (!HOP_HEADERS.has(k)) headers.append(k, v); + return Promise.resolve(route(new Request(`http://${host}${req.path}`, { method: req.method, headers, signal }))); + } + const headers: [string, string][] = req.headers.filter(([k]) => FORWARD_HEADERS.includes(k)); + return fetch(route.replace(/\/+$/, "") + req.path, { method: req.method, headers, signal }); + } + + function serve(host: string, route: FetchRoute, ev: NetConnectionEvents): NetConnection { + let text = ""; // unparsed request bytes (latin1) + const queue: Req[] = []; + let guestEnded = false, closing = false, dead = false, running = false, scheduled = false; + let paused = false, wake: (() => void) | null = null; + let ctl: AbortController | null = null; + + const emit = (b: Uint8Array | string) => { if (!dead) ev.onData(typeof b === "string" ? enc.encode(b) : b); }; + const kill = () => { + dead = true; + conns.delete(abortAll); + ctl?.abort(); + wake?.(); + }; + const finish = (err: Error | null) => { + if (dead) return; + kill(); + if (!err) ev.onEnd(); + ev.onClose(err); + }; + const abortAll = () => finish(new Error("backend closed")); + conns.add(abortAll); + queueMicrotask(() => { if (!dead) ev.onConnect(); }); + + function parse(): void { + while (!closing) { + text = text.replace(/^(\r\n)+/, ""); + const i = text.indexOf("\r\n\r\n"); + if (i < 0) { + if (text.length > MAX_HEAD) { queue.push({ method: "GET", path: "/", headers: [], close: true, status: 431 }); closing = true; } + break; + } + const req = parseHead(text.slice(0, i)); + text = text.slice(i + 4); + queue.push(req); + if (req.close) closing = true; + } + if (closing) text = ""; + } + + function schedule(): void { + if (scheduled || running) return; + scheduled = true; + queueMicrotask(() => { scheduled = false; void run(); }); + } + + async function run(): Promise { + if (running || dead) return; + running = true; + try { + while (!dead && queue.length) await answer(queue.shift()!); + } finally { + running = false; + } + if (!dead && !queue.length && (closing || guestEnded)) finish(null); + } + + function simple(req: Req, status: number, body = `${status} ${REASONS[status] ?? ""}\n`): void { + const b = enc.encode(body); + emit(`HTTP/1.1 ${status} ${REASONS[status] ?? ""}\r\nContent-Type: text/plain\r\nContent-Length: ${b.length}\r\n` + + `Connection: ${req.close ? "close" : "keep-alive"}\r\n\r\n`); + if (req.method !== "HEAD") emit(b); + } + + async function answer(req: Req): Promise { + if (req.status) return simple(req, req.status); + const c = (ctl = new AbortController()); + let res: Response; + try { + res = await fetchFor(host, route, req, c.signal); + } catch (e) { + if (dead) return; + const msg = (e as Error)?.message ?? String(e); + log?.(`[net] fetch http://${host}${req.path}: ${msg}`); + return simple(req, 503, `fetch failed: ${msg}\n`); + } + if (dead) { res.body?.cancel().catch(() => {}); return; } + const status = res.status; + const len = res.headers.get("content-length"), coding = res.headers.get("content-encoding"); + const noBody = req.method === "HEAD" || status === 204 || status === 304 || status < 200; + const chunked = !noBody && (len === null || coding !== null); + let head = `HTTP/1.1 ${status} ${res.statusText || REASONS[status] || ""}\r\n`; + if (len !== null && coding === null && status !== 204 && status !== 304) head += `Content-Length: ${len}\r\n`; + else if (chunked) head += "Transfer-Encoding: chunked\r\n"; + for (const h of COPY_HEADERS) { + const v = res.headers.get(h); + if (v !== null) head += `${h}: ${v}\r\n`; + } + head += `Connection: ${req.close ? "close" : "keep-alive"}\r\n\r\n`; + emit(head); + if (noBody || !res.body) { + res.body?.cancel().catch(() => {}); + if (chunked) emit("0\r\n\r\n"); + return; + } + const reader = res.body.getReader(); + try { + for (;;) { + while (paused && !dead) await new Promise((r) => { wake = r; }); + if (dead) break; + const { done, value } = await reader.read(); + if (dead || done) break; + if (!value.length) continue; + if (!chunked) { emit(value); continue; } + const pre = enc.encode(`${value.length.toString(16)}\r\n`); + const b = new Uint8Array(pre.length + value.length + 2); + b.set(pre); b.set(value, pre.length); b[b.length - 2] = 13; b[b.length - 1] = 10; + emit(b); + } + if (!dead && chunked) emit("0\r\n\r\n"); + } catch (e) { + if (dead) return; + log?.(`[net] fetch http://${host}${req.path}: ${(e as Error)?.message ?? e}`); + finish(e instanceof Error ? e : new Error(String(e))); + } finally { + if (dead) reader.cancel().catch(() => {}); + if (ctl === c) ctl = null; + } + } + + return { + write(u8) { + if (dead || closing) return; + text += latin1.decode(u8); + parse(); + schedule(); + }, + end() { + if (dead) return; + guestEnded = true; + schedule(); + }, + destroy() { if (!dead) kill(); }, + pause() { paused = true; }, + resume() { + paused = false; + const w = wake; + wake = null; + w?.(); + }, + buffered: 0, + }; + } + + return { + lookup(name) { + const r = byName.get(normName(name)); + if (r) return Promise.resolve([r.ip]); + return inner ? inner.lookup(name) : Promise.reject({ code: "ENOTFOUND" }); + }, + connect(addr, ev) { + const r = byIp.get(addr.host) ?? byName.get(normName(addr.host)); + if (r) return addr.port === 80 ? serve(r.name, r.route, ev) : refused(ev, `connection refused (${r.name} serves port 80 only)`); + return inner ? inner.connect(addr, ev) : refused(ev, "connection refused"); + }, + close() { + for (const abort of [...conns]) abort(); + inner?.close?.(); + }, + }; +} diff --git a/web/src/boot.ts b/web/src/boot.ts index d0d196b..7f1f4ee 100644 --- a/web/src/boot.ts +++ b/web/src/boot.ts @@ -1347,7 +1347,7 @@ export function start(): void { shared: cfg.shared ? undefined : false, // shared memory where the page is cross-origin isolated (?shared=0: never) disks: dataDisks as DiskSpec[], onDiskError: (_i, e) => saveError(e), distro: distro?.url, // a spec the page makes (relative to the page); the worker opens it - net: browserNetSpec({ enabled: cfg.net, servers: cfg.wisp }), // Wisp, in the worker (net.ts) + net: browserNetSpec({ enabled: cfg.net, servers: cfg.wisp, routes: cfg.routes }), // Wisp, in the worker (net.ts) restore, transferRestore: true, // the snapshot is read for this boot only }); return cfg.worker @@ -1358,7 +1358,7 @@ export function start(): void { }) : createKernel({ ...common, kernel: module, disks: dataDisks as BlockDevice[], restore, distro: distroDisk ?? undefined, - net: browserNet({ enabled: cfg.net, servers: cfg.wisp, log }), // Wisp (net.ts) + net: browserNet({ enabled: cfg.net, servers: cfg.wisp, routes: cfg.routes, log }), // Wisp (net.ts) }); }; if (resume) { diff --git a/web/src/config.ts b/web/src/config.ts index 9d9e440..b0daf82 100644 --- a/web/src/config.ts +++ b/web/src/config.ts @@ -5,12 +5,12 @@ // (virtual:unkernel-kernel's list) attached read-only. // // The settings below are kept in localStorage (SETTINGS_KEY: {name: value}, -// only those that differ from the defaults). Each one except ?simulate and -// ?showcase has a control under Options in the status panel; Reboot saves +// only those that differ from the defaults). Each one except ?simulate, +// ?showcase and ?routes has a control under Options in the status panel; Reboot saves // them there (ui.ts nextSettings()) and loads the page's bare URL. A URL // parameter of the same name overrides the saved one for that load (links, -// the browser tests); the page never writes the URL. ?simulate and -// ?showcase are read from the URL only. +// the browser tests); the page never writes the URL. ?simulate, ?showcase +// and ?routes are read from the URL only. // // ?mem=MiB kernel memory (default: auto, from the SDK's autoMemoryMiB(): // 256 on phones, 512 otherwise, less on low-memory devices) @@ -18,6 +18,9 @@ // ?net=0 no network device (else: the Wisp server(s), default: // the project's) // ?wisp=[,...] | ?wisp=0 Wisp servers to race (0 = no network device) +// ?routes=0 URL only: plain HTTP to the hosts of DEFAULT_ROUTES goes +// through Wisp too (default: answered with fetch() from +// their CORS mirrors, the SDK's fetchRoutes(); net.ts) // ?jit=0 kwemu interprets only (default: its JIT tier compiles hot // guest code to WebAssembly; counters in KW.jitStats()) // ?verbose=1 write every kernel message to the terminal, in gray @@ -111,6 +114,15 @@ export const DISTROS_OFFERED: readonly DistroEntry[] = DISTROS; /** The ?distro= default. */ export const DEFAULT_DISTRO = DISTROS_OFFERED.find((d) => d.name === "debian")?.name ?? DISTROS_OFFERED[0]?.name ?? "none"; +/** + * Plain-HTTP hosts the guest's network answers with fetch() (net.ts), each + * from a CORS-enabled mirror with the same paths under the base: Debian's + * apt sources. ?routes=0 turns them off. + */ +export const DEFAULT_ROUTES: Readonly> = Object.freeze({ + "deb.debian.org": "https://mirror.unkernel.dev/deb", +}); + /** The project's source, linked from About and the boot notes. */ export const REPO = "https://github.com/pithings/unkernel"; @@ -174,6 +186,8 @@ export interface Config { net: boolean; /** ?wisp= servers, or null for the SDK's DEFAULT_WISP_SERVERS. */ wisp: string[] | null; + /** Plain-HTTP hosts answered with fetch(): DEFAULT_ROUTES, or null with ?routes=0. */ + routes: Record | null; /** kwemu's JIT tier (?jit=0 turns it off). */ jit: boolean; /** A display, /dev/fb0 (on unless ?display=0). */ @@ -351,6 +365,7 @@ export function readConfig(search: string = location.search, saved: Record -// The page's guest network: the SDK's NetStack over Wisp servers. -import { DEFAULT_WISP_SERVERS, NetStack, wispBackend, type NetSpec } from "./sdk.ts"; +// The page's guest network: the SDK's NetStack over Wisp servers, with the +// plain-HTTP hosts of the route table (config.ts DEFAULT_ROUTES) answered by +// fetch() (the SDK's fetchRoutes()). +import { DEFAULT_WISP_SERVERS, NetStack, fetchRoutes, wispBackend, type NetSpec } from "./sdk.ts"; + +/** Guest-visible host name to base URL; null or empty: none. */ +type Routes = Record | null; /** * The page's network: a NetStack whose backend is the fastest of the Wisp * servers (default: the SDK's DEFAULT_WISP_SERVERS; the project's server * accepts only page origins on its allow list), or none when `enabled` is - * false (config.ts: `?net=0`, `?wisp=0`; `?wisp=URL[,URL...]` sets `servers`). + * false (config.ts: `?net=0`, `?wisp=0`; `?wisp=URL[,URL...]` sets `servers`; + * `routes` is config.ts DEFAULT_ROUTES unless `?routes=0`). */ -export function browserNet(opts: { enabled: boolean; servers: string[] | null; log?: (m: string) => void }): NetStack | undefined { +export function browserNet(opts: { enabled: boolean; servers: string[] | null; routes: Routes; log?: (m: string) => void }): NetStack | undefined { if (!opts.enabled) return undefined; - const wisp = opts.servers ?? [...DEFAULT_WISP_SERVERS]; - return new NetStack({ backend: wispBackend(wisp, { log: opts.log }), log: opts.log }); + const wisp = wispBackend(opts.servers ?? [...DEFAULT_WISP_SERVERS], { log: opts.log }); + const backend = opts.routes && Object.keys(opts.routes).length ? fetchRoutes(wisp, opts.routes, { log: opts.log }) : wisp; + return new NetStack({ backend, log: opts.log }); } /** The same network as a spec, for worker mode (?worker=1): the worker builds the NetStack and opens the WebSocket. */ -export function browserNetSpec(opts: { enabled: boolean; servers: string[] | null }): NetSpec | undefined { +export function browserNetSpec(opts: { enabled: boolean; servers: string[] | null; routes: Routes }): NetSpec | undefined { if (!opts.enabled) return undefined; - return { kind: "net", backend: { kind: "wisp", servers: opts.servers ?? [...DEFAULT_WISP_SERVERS] } }; + return { kind: "net", backend: { kind: "wisp", servers: opts.servers ?? [...DEFAULT_WISP_SERVERS], routes: opts.routes ?? undefined } }; }