mirror of
https://github.com/pithings/unkernel.git
synced 2026-12-02 02:59:39 +08:00
With net.tailscale.exitNode (--tailscale-exit-node, setExitNode() at run time) a tailnet device that offers 0.0.0.0/0 takes all the guest's other IPv4 traffic and its DNS in place of the backend; while it is not usable that traffic is refused. WireGuard's source check is now the longest prefix across peers. The page lists the tailnet's devices, picks the exit node from a select box in Settings and the top bar panel, and shows a set-up node's status and live controls apart from the setup form. The README gains a section on joining a tailnet.
1206 lines
45 KiB
TypeScript
1206 lines
45 KiB
TypeScript
// SPDX-License-Identifier: MIT
|
|
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
|
|
// unkernel user-mode network stack ("slirp-lite"), shared by Node and the
|
|
// browser.
|
|
//
|
|
// The guest's kwnet device exchanges raw Ethernet frames with the host. This
|
|
// module terminates them: it answers ARP for the virtual subnet, runs a tiny
|
|
// DHCP server and DNS server, answers pings to the gateway and DNS address
|
|
// (other echo requests go to the backend's optional ping, which neither
|
|
// built-in backend has; without it they get ICMP administratively
|
|
// prohibited), terminates TCP connections and forwards UDP flows, bridging
|
|
// each one to a pluggable backend (NetBackend: real sockets in Node,
|
|
// node/net.ts; a Wisp server, net-wisp.ts; or any other transport).
|
|
//
|
|
// 10.0.2.0/24 virtual subnet
|
|
// 10.0.2.2 gateway (TCP and UDP to it go to the host's loopback
|
|
// with hostLoopback)
|
|
// 10.0.2.3 DNS server (A queries resolved by the backend)
|
|
// 10.0.2.15 the guest (handed out by DHCP)
|
|
//
|
|
// UDP other than DHCP and DNS goes to the backend's udp() as flows (guest
|
|
// port, remote address and port), each closed after UDP_IDLE_MS without a
|
|
// datagram either way; a backend without udp(), or a destination it cannot
|
|
// reach (the subnet, the gateway without hostLoopback), gets ICMP port
|
|
// unreachable. Replies come only from the flow's remote address and port.
|
|
//
|
|
// With a tunnel (NetTunnel, e.g. a Tailscale node), IPv4 packets from the
|
|
// guest to destinations the tunnel routes bypass all of this and go to the
|
|
// tunnel, so the guest's own stack serves inbound connections, UDP and
|
|
// ping there. Once the guest owns the tunnel address itself
|
|
// (NetTunnel.guestAddress: the Tailscale node gives it a tailscale0 and
|
|
// routes, tailscale/guest.ts) packets from and to that address pass
|
|
// unrewritten; packets from 10.0.2.15 have it rewritten to the tunnel's
|
|
// address and back (net-tunnel.ts), always before that and for the flows
|
|
// that started so. Packets from any other source are dropped. The stack's own ranges (ownRange: its subnet, loopback,
|
|
// multicast, the backends' name ranges) never go to the tunnel nor come
|
|
// from it; what the tunnel claims while it has no address gets ICMP host
|
|
// unreachable. DNS asks the tunnel's names first (also at
|
|
// 100.100.100.100, Tailscale's resolver address), and a name the tunnel
|
|
// owns never reaches the backend. With an exit node (NetTunnel.exitDNS
|
|
// set; the tunnel then routes everything beyond the stack's own ranges)
|
|
// no name does: the others (but AAAA) are forwarded as they are through
|
|
// the tunnel to its DNS servers, and fail (SERVFAIL) while it has none;
|
|
// the backends' name addresses (198.18.0.0/15, 198.51.100.0/24) handed
|
|
// out before are refused then.
|
|
//
|
|
// Not implemented: IPv6, IP fragments (so no datagram larger than the MTU
|
|
// leaves the guest; the tunnel passes them), ICMP other than echo, TCP
|
|
// options beyond MSS and window scale (no SACK, no timestamps), inbound
|
|
// connections and datagrams (except through a tunnel).
|
|
|
|
import type { Kernel, NetDevice } from "./kernel.ts";
|
|
import { FRAG_NEEDED, RewrittenFlows, TUNNEL_MTU, newTunnelStats, tunnelEgress, tunnelIngress, tunnelPass, type NetTunnelStats } from "./net-tunnel.ts";
|
|
import { errorText } from "./output.ts";
|
|
|
|
/** Events a backend reports for one TCP connection. */
|
|
export interface NetConnectionEvents {
|
|
onConnect(): void;
|
|
onData(data: Uint8Array): void;
|
|
/** The remote side half-closed (no more data). */
|
|
onEnd(): void;
|
|
/** Data written earlier has been sent; `buffered` went down. */
|
|
onDrain(): void;
|
|
/** Called once, last; null for a clean close. */
|
|
onClose(error: Error | null): void;
|
|
}
|
|
|
|
/** The host side of one TCP connection. */
|
|
export interface NetConnection {
|
|
write(data: Uint8Array): void;
|
|
/** Half-close (the guest sent FIN). */
|
|
end(): void;
|
|
/** Abort; no events follow. */
|
|
destroy(): void;
|
|
/** Stop delivering onData until resume(). */
|
|
pause(): void;
|
|
resume(): void;
|
|
/** Bytes written but not yet sent. */
|
|
readonly buffered: number;
|
|
}
|
|
|
|
/** Events a backend reports for one UDP flow. */
|
|
export interface NetDatagramEvents {
|
|
/** One datagram from the flow's remote address and port. */
|
|
onMessage(data: Uint8Array): void;
|
|
/**
|
|
* Called once, last (possibly during udp()); the flow is gone. An error
|
|
* whose `code` is "ECONNREFUSED" (the remote port is closed) reaches the
|
|
* guest as ICMP port unreachable.
|
|
*/
|
|
onClose(error: Error | null): void;
|
|
}
|
|
|
|
/** The host side of one UDP flow: datagrams to and from one remote address and port. */
|
|
export interface NetDatagramSocket {
|
|
/** Send one datagram; `data` stays valid (the backend may keep it). */
|
|
send(data: Uint8Array): void;
|
|
/** Drop the flow; no events follow. */
|
|
close(): void;
|
|
}
|
|
|
|
/**
|
|
* Transport for the guest's TCP connections, UDP flows and DNS lookups.
|
|
*
|
|
* connect({ host, port }, events) -> NetConnection
|
|
* udp({ host, port }, events) (optional) -> NetDatagramSocket; without
|
|
* it, UDP other than DHCP and DNS gets ICMP port unreachable
|
|
* lookup(name) -> IPv4 dotted quads; reject with { code: "ENOTFOUND" }
|
|
* for NXDOMAIN, anything else becomes SERVFAIL
|
|
* ping(host, timeoutMs) (optional) -> true if the IPv4 dotted quad
|
|
* answered one ICMP echo within timeoutMs; false or a rejection is no
|
|
* answer. A hook for other backends: directBackend() and wispBackend()
|
|
* have none, and without it the guest's echo requests to hosts beyond
|
|
* the gateway get ICMP "administratively prohibited"
|
|
* close() (optional) drops every connection and the transport
|
|
*/
|
|
export interface NetBackend {
|
|
connect(addr: { host: string; port: number }, ev: NetConnectionEvents): NetConnection;
|
|
udp?(addr: { host: string; port: number }, ev: NetDatagramEvents): NetDatagramSocket;
|
|
lookup(name: string): Promise<string[]>;
|
|
ping?(host: string, timeoutMs: number): Promise<boolean>;
|
|
close?(): void;
|
|
}
|
|
|
|
/**
|
|
* A layer-3 tunnel beside the backend (e.g. a Tailscale node, loaded only
|
|
* when asked for): IPv4 packets from the guest to destinations it routes
|
|
* skip the TCP terminator and go to sendPacket() with the guest's
|
|
* 10.0.2.15 rewritten to `ipv4`; its packets for `ipv4` reach the guest
|
|
* rewritten back (net-tunnel.ts).
|
|
*/
|
|
export interface NetTunnel {
|
|
/** The guest's address on the tunnel (IPv4 as a number), 0 while it has none (nothing is routed then). */
|
|
readonly ipv4: number;
|
|
/** Whether packets to this IPv4 destination (a number) belong to the tunnel. */
|
|
routesIPv4(dst: number): boolean;
|
|
/** One IPv4 packet for the tunnel; false when it has no route for it (the guest gets ICMP host unreachable). */
|
|
sendPacket(ip: Uint8Array): boolean;
|
|
/** Set by NetStack: packets from the tunnel for `ipv4`. */
|
|
onPacket: ((ip: Uint8Array) => void) | null;
|
|
/**
|
|
* A name (lower case) the tunnel answers (MagicDNS): its addresses; []
|
|
* for one of its names that does not exist (NXDOMAIN); null for one it
|
|
* cannot answer yet (SERVFAIL); undefined to ask the backend.
|
|
*/
|
|
resolve?(name: string): string[] | null | undefined;
|
|
/**
|
|
* The address the guest itself owns (`ipv4`, configured in the guest;
|
|
* 0 or absent when it does not): packets from it go to the tunnel and
|
|
* packets for it reach the guest unrewritten, except those of flows
|
|
* that were rewritten before.
|
|
*/
|
|
readonly guestAddress?: number;
|
|
/** NetStack saw the guest set its network up again (a DHCP discover): whatever configured the address must do it again. */
|
|
guestReset?(): void;
|
|
/** The tunnel's MTU, default 1280: TCP MSS is clamped to fit, larger packets are segmented, fragmented or refused. */
|
|
readonly mtu?: number;
|
|
/**
|
|
* With an exit node selected (the tunnel then routes every destination
|
|
* beyond the stack's own ranges): the DNS servers that a name the
|
|
* tunnel does not answer itself (resolve() undefined) is asked through
|
|
* it, in order, DNS_FORWARD_MS each, as UDP from `ipv4`; [] while it
|
|
* cannot carry them (SERVFAIL, never the backend). Absent or null: no
|
|
* exit node, the backend resolves.
|
|
*/
|
|
readonly exitDNS?: readonly NetTunnelResolver[] | null;
|
|
close?(): void | Promise<void>;
|
|
}
|
|
|
|
/** A DNS server reached through a tunnel (NetTunnel.exitDNS): an IPv4 address as a number, and its port. */
|
|
export interface NetTunnelResolver {
|
|
ip: number;
|
|
port: number;
|
|
}
|
|
|
|
export interface NetStackOptions {
|
|
backend: NetBackend;
|
|
/** A layer-3 tunnel beside the backend (NetTunnel). */
|
|
tunnel?: NetTunnel;
|
|
log?: (msg: string) => void;
|
|
/** TCP and UDP to the gateway (10.0.2.2) go to 127.0.0.1. Default false. */
|
|
hostLoopback?: boolean;
|
|
/** MTU advertised by DHCP (option 26). */
|
|
mtu?: number;
|
|
/** The guest's MAC address, default 52:54:00:12:34:56. */
|
|
mac?: string;
|
|
}
|
|
|
|
export interface NetStats {
|
|
rx: number;
|
|
tx: number;
|
|
tcpOpened: number;
|
|
/** UDP flows opened (DHCP and DNS are not flows). */
|
|
udpOpened: number;
|
|
dns: number;
|
|
/** With a tunnel: its path's counters. */
|
|
tunnel?: NetTunnelStats;
|
|
}
|
|
|
|
const ETH_ARP = 0x0806, ETH_IP = 0x0800;
|
|
const PROTO_ICMP = 1, PROTO_TCP = 6, PROTO_UDP = 17;
|
|
const FIN = 1, SYN = 2, RST = 4, PSH = 8, ACK = 16;
|
|
|
|
export const ip4 = (s: string): number => s.split(".").reduce((a, b) => ((a << 8) | Number(b)) >>> 0, 0);
|
|
export const ip4str = (n: number): string => `${n >>> 24}.${(n >>> 16) & 255}.${(n >>> 8) & 255}.${n & 255}`;
|
|
|
|
function parseMac(s: string): Uint8Array {
|
|
return Uint8Array.from(s.split(":").map((h) => parseInt(h, 16)));
|
|
}
|
|
|
|
// Internet checksum helpers.
|
|
function sum16(u8: Uint8Array, off: number, len: number, s = 0): number {
|
|
const end = off + len;
|
|
let i = off;
|
|
for (; i + 1 < end; i += 2) s += (u8[i]! << 8) | u8[i + 1]!;
|
|
if (i < end) s += u8[i]! << 8;
|
|
return s;
|
|
}
|
|
function fold(s: number): number {
|
|
while (s > 0xffff) s = (s & 0xffff) + Math.floor(s / 65536);
|
|
return ~s & 0xffff;
|
|
}
|
|
|
|
const seqLt = (a: number, b: number) => ((a - b) | 0) < 0;
|
|
const seqLe = (a: number, b: number) => ((a - b) | 0) <= 0;
|
|
const seqAdd = (a: number, n: number) => (a + n) >>> 0;
|
|
const seqDiff = (a: number, b: number) => (a - b) | 0;
|
|
|
|
/** FIFO of bytes with random-access reads from the front. */
|
|
class ByteQueue {
|
|
chunks: Uint8Array[] = [];
|
|
/** Offset into chunks[0]. */
|
|
head = 0;
|
|
length = 0;
|
|
push(u8: Uint8Array): void {
|
|
if (!u8.length) return;
|
|
this.chunks.push(u8);
|
|
this.length += u8.length;
|
|
}
|
|
drop(n: number): void {
|
|
this.length -= n;
|
|
while (n > 0) {
|
|
const c = this.chunks[0]!;
|
|
const avail = c.length - this.head;
|
|
if (n < avail) { this.head += n; return; }
|
|
n -= avail;
|
|
this.chunks.shift();
|
|
this.head = 0;
|
|
}
|
|
}
|
|
copyTo(dst: Uint8Array, dstOff: number, offset: number, len: number): void {
|
|
let i = 0, pos = this.head + offset;
|
|
while (pos >= this.chunks[i]!.length) pos -= this.chunks[i++]!.length;
|
|
while (len > 0) {
|
|
const c = this.chunks[i++]!;
|
|
const take = Math.min(len, c.length - pos);
|
|
dst.set(c.subarray(pos, pos + take), dstOff);
|
|
dstOff += take;
|
|
len -= take;
|
|
pos = 0;
|
|
}
|
|
}
|
|
}
|
|
|
|
const RCVBUF = 256 * 1024; // guest -> backend bytes we accept before closing the window
|
|
const SNDBUF_HIGH = 512 * 1024; // backend -> guest bytes queued before pausing the backend
|
|
const RTO_MS = 1000, RTO_MAX_MS = 8000, MAX_RETRIES = 8;
|
|
/** A UDP flow without a datagram either way for this long is closed. */
|
|
export const UDP_IDLE_MS = 60_000;
|
|
/** At most this many UDP flows; a new one closes the least recently used. */
|
|
const UDP_MAX_FLOWS = 256;
|
|
/** Datagrams a backend queues for a UDP flow until it can send them (more are dropped). */
|
|
export const UDP_QUEUE = 64;
|
|
/** Tailscale's resolver address: DNS to it is answered like DNS to 10.0.2.3 while a tunnel is attached. */
|
|
const QUAD100 = 0x64646464;
|
|
const PING_TIMEOUT_MS = 3000, MAX_PINGS = 64; // echo requests through the backend; more in flight are dropped
|
|
/** How long a DNS query forwarded through the tunnel (NetTunnel.exitDNS) waits for one server before it asks the next. */
|
|
export const DNS_FORWARD_MS = 2000;
|
|
/** At most this many forwarded queries in flight (more get SERVFAIL); their tunnel-side ports are above the guest's ephemeral range (Linux: up to 60999). */
|
|
const DNS_FORWARD_MAX = 256, DNS_FORWARD_PORT = 61000;
|
|
|
|
/** A DNS query forwarded through the tunnel, by its tunnel-side port. */
|
|
interface DnsForward {
|
|
id: number;
|
|
servers: readonly NetTunnelResolver[];
|
|
timer: ReturnType<typeof setTimeout> | undefined;
|
|
done: (reply: Uint8Array | null) => void;
|
|
}
|
|
|
|
interface Segment {
|
|
sport: number;
|
|
dport: number;
|
|
seq: number;
|
|
ack: number;
|
|
flags: number;
|
|
win: number;
|
|
mss?: number;
|
|
wscale?: number;
|
|
}
|
|
|
|
/** What sendTcp needs of a connection (a TcpConn, or a stand-in for a reset). */
|
|
interface TcpEndpoint {
|
|
ip: number;
|
|
port: number;
|
|
gport: number;
|
|
rcvNxt: number;
|
|
sndUna: number;
|
|
sendq: ByteQueue | null;
|
|
}
|
|
|
|
class TcpConn implements TcpEndpoint {
|
|
stack: NetStack;
|
|
key: string;
|
|
gport: number;
|
|
ip: number;
|
|
port: number;
|
|
irs: number;
|
|
rcvNxt: number;
|
|
iss: number;
|
|
sndUna: number;
|
|
sndNxt: number;
|
|
mss: number;
|
|
sndWscale: number;
|
|
rcvWscale: number;
|
|
sndWl: number;
|
|
sendq: ByteQueue;
|
|
state: "connecting" | "synrcvd" | "established" | "closed";
|
|
remoteEof: boolean;
|
|
finSent: boolean;
|
|
guestFin: boolean;
|
|
paused: boolean;
|
|
rto: number;
|
|
retries: number;
|
|
timer: ReturnType<typeof setTimeout> | null;
|
|
lastWnd: number;
|
|
handle: NetConnection | undefined;
|
|
|
|
constructor(stack: NetStack, key: string, gport: number, ip: number, port: number, seg: Segment) {
|
|
this.stack = stack;
|
|
this.key = key;
|
|
this.gport = gport; // guest port
|
|
this.ip = ip; // remote (as seen by the guest)
|
|
this.port = port;
|
|
this.irs = seg.seq;
|
|
this.rcvNxt = seqAdd(seg.seq, 1);
|
|
this.iss = (Math.random() * 0x100000000) >>> 0;
|
|
this.sndUna = this.iss;
|
|
this.sndNxt = this.iss; // SYN not sent yet
|
|
this.mss = seg.mss ?? 536;
|
|
this.sndWscale = seg.wscale ?? 0;
|
|
this.rcvWscale = seg.wscale !== undefined ? 4 : 0;
|
|
this.sndWl = seqAdd(this.iss + 1, seg.win); // right edge of the guest's window
|
|
this.sendq = new ByteQueue(); // from sndUna: in flight, then unsent
|
|
this.state = "connecting"; // -> "synrcvd" -> "established" -> "closed"
|
|
this.remoteEof = false; // backend ended: send FIN after the data
|
|
this.finSent = false;
|
|
this.guestFin = false;
|
|
this.paused = false;
|
|
this.rto = RTO_MS;
|
|
this.retries = 0;
|
|
this.timer = null;
|
|
this.lastWnd = 0;
|
|
this.handle = undefined;
|
|
}
|
|
|
|
inFlight(): number { return seqDiff(this.sndNxt, this.sndUna) - (this.finSent ? 1 : 0); }
|
|
|
|
rcvWnd(): number {
|
|
const free = Math.max(0, RCVBUF - (this.handle?.buffered ?? 0));
|
|
return Math.min(free >> this.rcvWscale, 0xffff);
|
|
}
|
|
|
|
send(flags: number, seq: number, payloadLen = 0, opts: Uint8Array | null = null): void {
|
|
const wnd = this.rcvWnd();
|
|
this.lastWnd = wnd << this.rcvWscale;
|
|
this.stack.sendTcp(this, flags, seq, payloadLen, opts, wnd);
|
|
}
|
|
|
|
ack(): void { this.send(ACK, this.sndNxt); }
|
|
|
|
synAck(): void {
|
|
const o = [2, 4, 0x05, 0xb4]; // MSS 1460 (TSO frames from the guest may be larger)
|
|
if (this.sndWscale || this.rcvWscale) o.push(1, 3, 3, this.rcvWscale);
|
|
this.send(SYN | ACK, this.iss, 0, Uint8Array.from(o));
|
|
this.sndNxt = seqAdd(this.iss, 1);
|
|
this.armTimer();
|
|
}
|
|
|
|
/** Send whatever the guest's window allows, then FIN if due. */
|
|
flush(): void {
|
|
if (this.state !== "established") return;
|
|
let sent = false;
|
|
for (;;) {
|
|
const off = seqDiff(this.sndNxt, this.sndUna);
|
|
const unsent = this.sendq.length - off;
|
|
const room = seqDiff(this.sndWl, this.sndNxt);
|
|
if (unsent <= 0 || room <= 0) break;
|
|
const n = Math.min(unsent, room, this.mss);
|
|
this.send(ACK | PSH, this.sndNxt, n);
|
|
this.sndNxt = seqAdd(this.sndNxt, n);
|
|
sent = true;
|
|
}
|
|
if (this.remoteEof && !this.finSent && seqDiff(this.sndNxt, this.sndUna) === this.sendq.length) {
|
|
this.send(FIN | ACK, this.sndNxt);
|
|
this.sndNxt = seqAdd(this.sndNxt, 1);
|
|
this.finSent = true;
|
|
sent = true;
|
|
}
|
|
if (sent || (this.sendq.length && seqDiff(this.sndWl, this.sndNxt) <= 0)) this.armTimer();
|
|
if (this.paused && this.sendq.length < SNDBUF_HIGH / 2) {
|
|
this.paused = false;
|
|
this.handle?.resume();
|
|
}
|
|
}
|
|
|
|
armTimer(): void {
|
|
if (this.timer) return;
|
|
this.timer = setTimeout(() => this.onTimer(), this.rto);
|
|
}
|
|
|
|
clearTimer(): void {
|
|
if (this.timer) clearTimeout(this.timer);
|
|
this.timer = null;
|
|
}
|
|
|
|
onTimer(): void {
|
|
this.timer = null;
|
|
if (this.state === "closed") return;
|
|
if (++this.retries > MAX_RETRIES) {
|
|
this.stack.log?.(`[net] tcp ${ip4str(this.ip)}:${this.port}: guest unresponsive, resetting`);
|
|
this.send(RST | ACK, this.sndNxt);
|
|
this.close();
|
|
return;
|
|
}
|
|
this.rto = Math.min(this.rto * 2, RTO_MAX_MS);
|
|
if (this.state === "synrcvd") {
|
|
this.sndNxt = this.iss;
|
|
this.synAck();
|
|
} else if (seqDiff(this.sndNxt, this.sndUna) > 0) {
|
|
// Go back N (the link is lossless; this only happens when the guest
|
|
// dropped frames, e.g. under memory pressure).
|
|
this.sndNxt = this.sndUna;
|
|
this.finSent = false;
|
|
this.flush();
|
|
} else if (this.sendq.length) {
|
|
// Zero window probe: an out-of-window segment makes the guest ACK.
|
|
this.send(ACK, seqAdd(this.sndUna, -1));
|
|
this.armTimer();
|
|
}
|
|
}
|
|
|
|
connect(): void {
|
|
const host = this.stack.backendHost(this.ip);
|
|
if (host === null) return this.refuse();
|
|
this.handle = this.stack.backend.connect({ host, port: this.port }, {
|
|
onConnect: () => {
|
|
if (this.state !== "connecting") return;
|
|
this.state = "synrcvd";
|
|
this.synAck();
|
|
},
|
|
onData: (u8) => {
|
|
if (this.state === "closed") return;
|
|
this.sendq.push(u8);
|
|
if (!this.paused && this.sendq.length >= SNDBUF_HIGH) {
|
|
this.paused = true;
|
|
this.handle!.pause();
|
|
}
|
|
this.flush();
|
|
},
|
|
onEnd: () => {
|
|
if (this.state === "closed") return;
|
|
this.remoteEof = true;
|
|
this.flush();
|
|
},
|
|
onDrain: () => {
|
|
if (this.state === "established" && this.lastWnd < RCVBUF / 2) this.ack();
|
|
},
|
|
onClose: (err) => {
|
|
if (this.state === "closed") return;
|
|
if (this.state === "connecting") return this.refuse(err);
|
|
if (err) {
|
|
this.stack.log?.(`[net] tcp ${ip4str(this.ip)}:${this.port}: ${err.message ?? err}`);
|
|
this.send(RST | ACK, this.sndNxt);
|
|
this.close();
|
|
} else {
|
|
this.remoteEof = true;
|
|
this.flush();
|
|
}
|
|
},
|
|
});
|
|
}
|
|
|
|
refuse(err?: Error | null): void {
|
|
if (err) this.stack.log?.(`[net] tcp connect ${ip4str(this.ip)}:${this.port}: ${err.message ?? err}`);
|
|
this.stack.sendTcp(this, RST | ACK, 0, 0, null, 0);
|
|
this.close();
|
|
}
|
|
|
|
close(): void {
|
|
if (this.state === "closed") return;
|
|
this.state = "closed";
|
|
this.clearTimer();
|
|
this.stack.tcp.delete(this.key);
|
|
this.handle?.destroy();
|
|
}
|
|
|
|
maybeDone(): void {
|
|
if (this.guestFin && this.finSent && this.sndUna === this.sndNxt) this.close();
|
|
}
|
|
|
|
/** A segment from the guest for this connection. */
|
|
input(seg: Segment, payload: Uint8Array): void {
|
|
if (seg.flags & RST) return this.close();
|
|
if (seg.flags & SYN) {
|
|
// Retransmitted SYN: answer again once we have something to say.
|
|
if (this.state === "synrcvd") { this.sndNxt = this.iss; this.clearTimer(); this.synAck(); }
|
|
return;
|
|
}
|
|
if (!(seg.flags & ACK) || this.state === "connecting") return;
|
|
|
|
// ACK processing.
|
|
const ack = seg.ack;
|
|
if (seqLt(this.sndUna, ack) && seqLe(ack, this.sndNxt)) {
|
|
let n = seqDiff(ack, this.sndUna);
|
|
if (this.state === "synrcvd") { this.state = "established"; n--; }
|
|
if (this.finSent && ack === this.sndNxt) n--;
|
|
if (n > 0) this.sendq.drop(n);
|
|
this.sndUna = ack;
|
|
this.retries = 0;
|
|
this.rto = RTO_MS;
|
|
this.clearTimer();
|
|
if (this.sndUna !== this.sndNxt) this.armTimer();
|
|
}
|
|
if (this.state === "synrcvd") return;
|
|
if (seqLe(this.sndUna, ack)) this.sndWl = seqAdd(ack, seg.win << this.sndWscale);
|
|
if (this.sndUna === this.sndNxt) this.retries = 0; // answered a window probe
|
|
|
|
// Data and FIN, in order only (anything else gets a duplicate ACK).
|
|
const len = payload.length;
|
|
let seq = seg.seq;
|
|
let data = payload;
|
|
let needAck = false;
|
|
if (len || seg.flags & FIN) {
|
|
const skip = seqDiff(this.rcvNxt, seq);
|
|
if (skip > 0) {
|
|
if (skip >= len + (seg.flags & FIN ? 1 : 0)) { this.ack(); return; }
|
|
data = data.subarray(Math.min(skip, len));
|
|
seq = this.rcvNxt;
|
|
} else if (skip < 0) {
|
|
this.ack();
|
|
return;
|
|
}
|
|
if (data.length && !this.guestFin) {
|
|
this.handle!.write(data);
|
|
this.rcvNxt = seqAdd(this.rcvNxt, data.length);
|
|
}
|
|
if (seg.flags & FIN && !this.guestFin) {
|
|
this.guestFin = true;
|
|
this.rcvNxt = seqAdd(this.rcvNxt, 1);
|
|
this.handle!.end();
|
|
}
|
|
needAck = true;
|
|
}
|
|
const before = this.sndNxt;
|
|
this.flush();
|
|
if (needAck && this.sndNxt === before) this.ack();
|
|
this.maybeDone();
|
|
}
|
|
}
|
|
|
|
/** One UDP flow: a guest port and a remote address and port. */
|
|
interface UdpFlow {
|
|
key: string;
|
|
gport: number;
|
|
ip: number;
|
|
port: number;
|
|
sock: NetDatagramSocket | undefined;
|
|
/** The IP header and first 8 bytes of the last datagram (ICMP errors quote it). */
|
|
quote: Uint8Array;
|
|
lastActive: number;
|
|
closed: boolean;
|
|
}
|
|
|
|
/**
|
|
* The host end of the guest's network: pass it as the kernel's `net`
|
|
* (kwnet) device. Terminates the guest's frames and bridges TCP, UDP and
|
|
* DNS to `opts.backend`.
|
|
*/
|
|
export class NetStack implements NetDevice {
|
|
backend: NetBackend;
|
|
/** The layer-3 tunnel beside the backend, if any. */
|
|
tunnel: NetTunnel | undefined;
|
|
/** The tunnel flows whose guest side is 10.0.2.15 (they stay rewritten once the guest owns the tunnel address). */
|
|
rewritten = new RewrittenFlows();
|
|
log: ((msg: string) => void) | undefined;
|
|
hostLoopback: boolean;
|
|
mtu: number | undefined;
|
|
/** The guest's MAC. */
|
|
mac: Uint8Array;
|
|
gwMac: Uint8Array;
|
|
guestMac: Uint8Array;
|
|
net: number;
|
|
mask: number;
|
|
gw: number;
|
|
dns: number;
|
|
guest: number;
|
|
tcp: Map<string, TcpConn>;
|
|
/** UDP flows, least recently used first. */
|
|
udp: Map<string, UdpFlow>;
|
|
udpSweep: ReturnType<typeof setInterval> | null;
|
|
/** The last UDP error logged; the same one again is not (each datagram may open a flow that fails). */
|
|
udpError: string | null;
|
|
/** Echo requests waiting for backend.ping. */
|
|
pings: number;
|
|
/** DNS queries forwarded through the tunnel (NetTunnel.exitDNS), by their tunnel-side port. */
|
|
dnsForwards = new Map<number, DnsForward>();
|
|
ipId: number;
|
|
/** Where frames for the guest go (set by attach()). */
|
|
output: (frame: Uint8Array) => void;
|
|
stats: NetStats;
|
|
|
|
constructor(opts: NetStackOptions) {
|
|
this.backend = opts.backend;
|
|
this.tunnel = opts.tunnel;
|
|
this.log = opts.log;
|
|
this.hostLoopback = opts.hostLoopback ?? false;
|
|
this.mtu = opts.mtu;
|
|
this.mac = parseMac(opts.mac ?? "52:54:00:12:34:56"); // the guest's
|
|
this.gwMac = parseMac("52:55:0a:00:02:02");
|
|
this.guestMac = this.mac;
|
|
this.net = ip4("10.0.2.0");
|
|
this.mask = ip4("255.255.255.0");
|
|
this.gw = ip4("10.0.2.2");
|
|
this.dns = ip4("10.0.2.3");
|
|
this.guest = ip4("10.0.2.15");
|
|
this.tcp = new Map();
|
|
this.udp = new Map();
|
|
this.udpSweep = null;
|
|
this.udpError = null;
|
|
this.pings = 0;
|
|
this.ipId = 1;
|
|
this.output = () => {};
|
|
this.stats = { rx: 0, tx: 0, tcpOpened: 0, udpOpened: 0, dns: 0 };
|
|
if (this.tunnel) {
|
|
this.stats.tunnel = newTunnelStats();
|
|
this.tunnel.onPacket = (ip) => this.tunnelInput(ip);
|
|
}
|
|
}
|
|
|
|
/** Hook up to a Kernel (core/kernel.ts); called when the guest's driver initialises. */
|
|
attach(kernel: Kernel): void {
|
|
this.output = (frame) => kernel.receiveFrame(frame);
|
|
}
|
|
|
|
/** Frame from the guest. */
|
|
send(frame: Uint8Array): void {
|
|
this.stats.rx++;
|
|
try {
|
|
this.input(frame);
|
|
} catch (e) {
|
|
this.log?.(`[net] dropped malformed frame: ${errorText(e)}`);
|
|
}
|
|
}
|
|
|
|
/** Reset every TCP connection and drop every UDP flow (the backend and the tunnel stay usable; the tunnel's packets are no longer taken). */
|
|
close(): void {
|
|
if (this.tunnel?.onPacket) this.tunnel.onPacket = null;
|
|
for (const fw of this.dnsForwards.values()) clearTimeout(fw.timer);
|
|
this.dnsForwards.clear();
|
|
for (const c of [...this.tcp.values()]) c.close();
|
|
for (const fl of [...this.udp.values()]) this.udpClose(fl);
|
|
}
|
|
|
|
emit(frame: Uint8Array): void {
|
|
this.stats.tx++;
|
|
this.output(frame);
|
|
}
|
|
|
|
/**
|
|
* Addresses this stack serves or that are never remote: its subnet (the
|
|
* gateway, DNS and the guest; with hostLoopback the gateway is the
|
|
* host), 0/8, loopback, multicast and above, Tailscale's resolver
|
|
* address, and the backends' name ranges (Wisp's 198.18.0.0/15,
|
|
* fetchRoutes' 198.51.100.0/24). None goes into a tunnel or comes out
|
|
* of one.
|
|
*/
|
|
ownRange(ip: number): boolean {
|
|
return ((ip & this.mask) >>> 0) === this.net || ip >>> 24 === 0 || ip >>> 24 === 127 || ip >>> 28 >= 14
|
|
|| ip === QUAD100 || ip >>> 17 === 0x6309 || ip >>> 8 === 0xc63364;
|
|
}
|
|
|
|
backendHost(ip: number): string | null {
|
|
if (ip === this.gw) return this.hostLoopback ? "127.0.0.1" : null;
|
|
if (ip === QUAD100 && this.tunnel) return null; // the tunnel's resolver: DNS only, answered here
|
|
if (((ip & this.mask) >>> 0) === this.net) return null;
|
|
if (ip === 0xffffffff || ip >>> 28 === 14 || ip >>> 24 === 0 || ip >>> 24 === 127) return null;
|
|
return ip4str(ip);
|
|
}
|
|
|
|
input(f: Uint8Array): void {
|
|
if (f.length < 14) return;
|
|
const type = (f[12]! << 8) | f[13]!;
|
|
if (type === ETH_ARP) this.arp(f);
|
|
else if (type === ETH_IP) this.ipv4(f);
|
|
}
|
|
|
|
arp(f: Uint8Array): void {
|
|
const dv = new DataView(f.buffer, f.byteOffset, f.byteLength);
|
|
if (f.length < 42 || dv.getUint16(20) !== 1) return; // requests only
|
|
const tip = dv.getUint32(38);
|
|
const sip = dv.getUint32(28);
|
|
if (tip === sip || tip === this.guest || ((tip & this.mask) >>> 0) !== this.net) return;
|
|
this.guestMac = f.slice(22, 28);
|
|
const r = new Uint8Array(42);
|
|
r.set(this.guestMac, 0);
|
|
r.set(this.gwMac, 6);
|
|
const o = new DataView(r.buffer);
|
|
o.setUint16(12, ETH_ARP);
|
|
o.setUint16(14, 1); o.setUint16(16, ETH_IP); r[18] = 6; r[19] = 4; o.setUint16(20, 2);
|
|
r.set(this.gwMac, 22); o.setUint32(28, tip);
|
|
r.set(f.subarray(22, 28), 32); o.setUint32(38, sip);
|
|
this.emit(r);
|
|
}
|
|
|
|
ipv4(f: Uint8Array): void {
|
|
const dv = new DataView(f.buffer, f.byteOffset, f.byteLength);
|
|
if (f.length < 34 || f[14]! >> 4 !== 4) return;
|
|
const ihl = (f[14]! & 15) * 4;
|
|
const total = dv.getUint16(16);
|
|
const proto = f[23];
|
|
const src = dv.getUint32(26), dst = dv.getUint32(30);
|
|
const l4 = 14 + ihl;
|
|
const end = Math.min(f.length, total ? 14 + total : f.length);
|
|
if (end < l4) return;
|
|
const t = this.tunnel;
|
|
// The stack's own ranges never go to the tunnel; the rest it claims does, up or not, from
|
|
// 10.0.2.15 (rewritten) or from the tunnel address itself (as it is), and from nothing else.
|
|
if (t && !this.ownRange(dst) && t.routesIPv4(dst)) {
|
|
this.guestMac = f.slice(6, 12);
|
|
if (src === this.guest) return this.tunnelOutput(t, f, l4, end, src);
|
|
if (t.ipv4 && src === t.ipv4) return this.tunnelOutput(t, f, l4, end, src);
|
|
this.stats.tunnel!.badSource++;
|
|
return;
|
|
}
|
|
// An exit node chosen: the backends' name addresses (handed out before it was) are refused too.
|
|
if ((dst >>> 17 === 0x6309 || dst >>> 8 === 0xc63364) && t?.exitDNS) {
|
|
this.stats.tunnel!.noRoute++;
|
|
if (proto === PROTO_TCP && end - l4 >= 20 && (f[l4 + 13]! & (SYN | ACK)) !== SYN) {
|
|
// A connection opened before: closed, and the guest gets a reset (tcpInput finds none).
|
|
this.tcp.get(`${dv.getUint16(l4)}/${dst}/${dv.getUint16(l4 + 2)}`)?.close();
|
|
return this.tcpInput(f, dv, src, dst, l4, end);
|
|
}
|
|
return this.icmpUnreachable(f.subarray(14, Math.min(end, l4 + 8)), src, this.gw, 1);
|
|
}
|
|
if ((dv.getUint16(20) & 0x3fff) !== 0) return; // fragments: unsupported
|
|
this.guestMac = f.slice(6, 12);
|
|
if (proto === PROTO_TCP) this.tcpInput(f, dv, src, dst, l4, end);
|
|
else if (proto === PROTO_UDP) this.udpInput(f, dv, src, dst, l4, end);
|
|
else if (proto === PROTO_ICMP) this.icmpInput(f, dv, src, dst, l4, end);
|
|
}
|
|
|
|
// --- the tunnel ---------------------------------------------------------------
|
|
|
|
/** A guest packet for the tunnel (net-tunnel.ts tunnelEgress). */
|
|
/**
|
|
* A guest packet for the tunnel (net-tunnel.ts tunnelEgress), from
|
|
* `src`: 10.0.2.15, rewritten to the tunnel address (and its flow
|
|
* remembered), or the tunnel address itself, sent as it is (checksums,
|
|
* MSS and size are dealt with alike).
|
|
*/
|
|
tunnelOutput(t: NetTunnel, f: Uint8Array, l4: number, end: number, src: number): void {
|
|
const st = this.stats.tunnel!;
|
|
const mtu = t.mtu ?? TUNNEL_MTU;
|
|
const quote = f.subarray(14, Math.min(end, l4 + 8));
|
|
if (!t.ipv4) {
|
|
// Claimed but not up (before its first netmap, after a logout): host unreachable, not the backend.
|
|
st.noRoute++;
|
|
return this.icmpUnreachable(quote, src, this.gw, 1);
|
|
}
|
|
const rewrite = src === this.guest;
|
|
const out = tunnelEgress(f.slice(14, end), t.ipv4, mtu, st);
|
|
if (out === null) return;
|
|
if (out === FRAG_NEEDED) {
|
|
st.fragNeeded++;
|
|
return this.icmpUnreachable(quote, src, this.gw, 4, mtu);
|
|
}
|
|
// The guest's own tunnel address from 10.0.2.15: back to the guest, from that address (a hairpin).
|
|
const self = rewrite && (f[30]! << 24 | f[31]! << 16 | f[32]! << 8 | f[33]!) >>> 0 === t.ipv4;
|
|
if (rewrite && !self) this.rewritten.note(out[0]!);
|
|
else if (!rewrite) st.passed += out.length;
|
|
for (const p of out) {
|
|
if (self) {
|
|
this.tunnelInput(p, true);
|
|
continue;
|
|
}
|
|
if (!t.sendPacket(p)) {
|
|
st.noRoute++;
|
|
return this.icmpUnreachable(quote, src, this.gw, 1); // host unreachable
|
|
}
|
|
st.tx++;
|
|
st.txBytes += p.length;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* A packet from the tunnel: to the guest, if it is for the tunnel's
|
|
* address and from a remote one (not the stack's own ranges, not the
|
|
* tunnel address itself unless `hairpin`).
|
|
*/
|
|
tunnelInput(ip: Uint8Array, hairpin = false): void {
|
|
const t = this.tunnel!, st = this.stats.tunnel!;
|
|
const total = ip.length >= 4 ? Math.min(ip.length, (ip[2]! << 8) | ip[3]!) : 0;
|
|
const src = total >= 20 ? ((ip[12]! << 24) | (ip[13]! << 16) | (ip[14]! << 8) | ip[15]!) >>> 0 : 0;
|
|
if (total < 20 || this.ownRange(src) || (src === t.ipv4 && !hairpin)) {
|
|
st.dropped++;
|
|
return;
|
|
}
|
|
if (this.dnsForwards.size && ip[9] === PROTO_UDP && this.dnsReply(ip.subarray(0, total), src)) return;
|
|
const f = new Uint8Array(14 + total);
|
|
f.set(this.guestMac, 0);
|
|
f.set(this.gwMac, 6);
|
|
f[12] = 0x08; f[13] = 0x00;
|
|
f.set(ip.subarray(0, total), 14);
|
|
// Explicit state: the guest owns the tunnel address (configured from the host) or it does not.
|
|
const owned = !!t.ipv4 && t.guestAddress === t.ipv4;
|
|
st.mode = owned ? "address" : "rewrite";
|
|
// Flows rewritten before the guest had the address stay rewritten; new ones pass as they are.
|
|
const pass = owned && !hairpin && !this.rewritten.has(ip);
|
|
const mtu = t.mtu ?? TUNNEL_MTU;
|
|
if (!t.ipv4 || !(pass ? tunnelPass(f.subarray(14), t.ipv4, mtu) : tunnelIngress(f.subarray(14), t.ipv4, this.guest, mtu))) {
|
|
st.dropped++;
|
|
return;
|
|
}
|
|
if (pass) st.passed++;
|
|
st.rx++;
|
|
st.rxBytes += total;
|
|
this.emit(f);
|
|
}
|
|
|
|
/**
|
|
* A guest's DNS query through the tunnel (an exit node: NetTunnel.exitDNS),
|
|
* from the tunnel address and a port of its own: the first server's
|
|
* reply, or null once each has had DNS_FORWARD_MS (or none can be sent to).
|
|
*/
|
|
dnsForward(q: Uint8Array, servers: readonly NetTunnelResolver[]): Promise<Uint8Array | null> {
|
|
const t = this.tunnel!, st = this.stats.tunnel!;
|
|
if (!servers.length || !t.ipv4 || this.dnsForwards.size >= DNS_FORWARD_MAX) return Promise.resolve(null);
|
|
let port = 0;
|
|
for (let i = 0; i < 32 && (!port || this.dnsForwards.has(port)); i++) port = DNS_FORWARD_PORT + Math.floor(Math.random() * (65536 - DNS_FORWARD_PORT));
|
|
if (this.dnsForwards.has(port)) return Promise.resolve(null);
|
|
return new Promise((resolve) => {
|
|
let i = -1;
|
|
const fw: DnsForward = {
|
|
id: (q[0]! << 8) | q[1]!, servers, timer: undefined,
|
|
done: (r) => {
|
|
clearTimeout(fw.timer);
|
|
if (this.dnsForwards.get(port) === fw) this.dnsForwards.delete(port);
|
|
resolve(r);
|
|
},
|
|
};
|
|
this.dnsForwards.set(port, fw);
|
|
const next = () => {
|
|
while (++i < servers.length && this.dnsForwards.get(port) === fw) {
|
|
const s = servers[i]!;
|
|
const [f, dv] = this.ipFrame(t.ipv4, s.ip, PROTO_UDP, 8 + q.length);
|
|
dv.setUint16(34, port); dv.setUint16(36, s.port); dv.setUint16(38, 8 + q.length);
|
|
f.set(q, 42);
|
|
dv.setUint16(40, this.l4csum(f, t.ipv4, s.ip, PROTO_UDP, 34, 8 + q.length) || 0xffff);
|
|
const p = f.slice(14);
|
|
if (!t.sendPacket(p)) continue;
|
|
st.tx++;
|
|
st.txBytes += p.length;
|
|
fw.timer = setTimeout(next, DNS_FORWARD_MS);
|
|
return;
|
|
}
|
|
if (this.dnsForwards.get(port) === fw) fw.done(null);
|
|
};
|
|
next();
|
|
});
|
|
}
|
|
|
|
/** Whether a UDP packet from the tunnel (trimmed) is for a forwarded DNS query (it is taken then: a reply from one of its servers answers it). */
|
|
dnsReply(ip: Uint8Array, src: number): boolean {
|
|
const ihl = (ip[0]! & 15) * 4;
|
|
if (ip.length < ihl + 8 || ((ip[6]! << 8 | ip[7]!) & 0x3fff) !== 0) return false;
|
|
const sport = (ip[ihl]! << 8) | ip[ihl + 1]!, dport = (ip[ihl + 2]! << 8) | ip[ihl + 3]!;
|
|
const fw = this.dnsForwards.get(dport);
|
|
const dst = ((ip[16]! << 24) | (ip[17]! << 16) | (ip[18]! << 8) | ip[19]!) >>> 0;
|
|
if (!fw || dst !== this.tunnel!.ipv4) return false;
|
|
const len = Math.min(ip.length, ihl + ((ip[ihl + 4]! << 8) | ip[ihl + 5]!));
|
|
const msg = ip.subarray(ihl + 8, len);
|
|
if (msg.length >= 12 && ((msg[0]! << 8) | msg[1]!) === fw.id && msg[2]! & 0x80 && fw.servers.some((s) => s.ip === src && s.port === sport)) {
|
|
this.stats.tunnel!.rx++;
|
|
this.stats.tunnel!.rxBytes += ip.length;
|
|
fw.done(msg.slice());
|
|
}
|
|
return true;
|
|
}
|
|
|
|
// --- frame builders -----------------------------------------------------
|
|
|
|
/** Ethernet + IPv4 header for a reply to the guest; returns [frame, view]. */
|
|
ipFrame(src: number, dst: number, proto: number, l4len: number, dstMac: Uint8Array = this.guestMac): [Uint8Array, DataView] {
|
|
const f = new Uint8Array(34 + l4len);
|
|
f.set(dstMac, 0);
|
|
f.set(this.gwMac, 6);
|
|
f[12] = 0x08; f[13] = 0x00;
|
|
const dv = new DataView(f.buffer);
|
|
f[14] = 0x45;
|
|
dv.setUint16(16, 20 + l4len);
|
|
dv.setUint16(18, this.ipId = (this.ipId + 1) & 0xffff);
|
|
dv.setUint16(20, 0x4000); // DF
|
|
f[22] = 64; f[23] = proto;
|
|
dv.setUint32(26, src); dv.setUint32(30, dst);
|
|
dv.setUint16(24, fold(sum16(f, 14, 20)));
|
|
return [f, dv];
|
|
}
|
|
|
|
l4csum(f: Uint8Array, src: number, dst: number, proto: number, off: number, len: number): number {
|
|
const s = (src >>> 16) + (src & 0xffff) + (dst >>> 16) + (dst & 0xffff) + proto + len;
|
|
return fold(sum16(f, off, len, s));
|
|
}
|
|
|
|
sendUdp(src: number, sport: number, dst: number, dport: number, payload: Uint8Array, dstMac?: Uint8Array): void {
|
|
const [f, dv] = this.ipFrame(src, dst, PROTO_UDP, 8 + payload.length, dstMac);
|
|
dv.setUint16(34, sport); dv.setUint16(36, dport); dv.setUint16(38, 8 + payload.length);
|
|
f.set(payload, 42);
|
|
dv.setUint16(40, this.l4csum(f, src, dst, PROTO_UDP, 34, 8 + payload.length) || 0xffff);
|
|
this.emit(f);
|
|
}
|
|
|
|
sendTcp(c: TcpEndpoint, flags: number, seq: number, payloadLen: number, opts: Uint8Array | null, wnd: number): void {
|
|
const olen = opts ? opts.length : 0;
|
|
const hl = 20 + olen;
|
|
const [f, dv] = this.ipFrame(c.ip, this.guest, PROTO_TCP, hl + payloadLen);
|
|
dv.setUint16(34, c.port); dv.setUint16(36, c.gport);
|
|
dv.setUint32(38, seq); dv.setUint32(42, flags & ACK ? c.rcvNxt : 0);
|
|
f[46] = (hl / 4) << 4; f[47] = flags;
|
|
dv.setUint16(48, wnd);
|
|
if (opts) f.set(opts, 54);
|
|
if (payloadLen) c.sendq!.copyTo(f, 34 + hl, seqDiff(seq, c.sndUna), payloadLen);
|
|
dv.setUint16(50, this.l4csum(f, c.ip, this.guest, PROTO_TCP, 34, hl + payloadLen));
|
|
this.emit(f);
|
|
}
|
|
|
|
// --- ICMP ------------------------------------------------------------------
|
|
|
|
icmpInput(f: Uint8Array, _dv: DataView, src: number, dst: number, l4: number, end: number): void {
|
|
if (f[l4] !== 8 || end - l4 < 8) return; // echo requests only
|
|
if (dst === this.gw || dst === this.dns) return this.echoReply(f.subarray(l4, end), dst, src);
|
|
const host = this.backendHost(dst);
|
|
if (host === null) return;
|
|
const ping = this.backend.ping;
|
|
if (!ping) return this.icmpUnreachable(f.subarray(14, l4 + 8), src, this.gw, 13); // administratively prohibited
|
|
if (this.pings >= MAX_PINGS) return;
|
|
this.pings++;
|
|
const msg = f.slice(l4, end);
|
|
new Promise<boolean>((r) => r(ping.call(this.backend, host, PING_TIMEOUT_MS))).then(
|
|
(ok) => { this.pings--; if (ok) this.echoReply(msg, dst, src); },
|
|
() => { this.pings--; },
|
|
);
|
|
}
|
|
|
|
/** Echo reply from `src` to `dst` carrying the request's id, sequence and data. */
|
|
echoReply(msg: Uint8Array, src: number, dst: number): void {
|
|
const len = msg.length;
|
|
const [r, rv] = this.ipFrame(src, dst, PROTO_ICMP, len);
|
|
r.set(msg, 34);
|
|
r[34] = 0; rv.setUint16(36, 0);
|
|
rv.setUint16(36, fold(sum16(r, 34, len)));
|
|
this.emit(r);
|
|
}
|
|
|
|
/** Destination unreachable for a packet from `src` to `dst`; `quote` is its IP header and first 8 bytes; `mtu` the next hop's for code 4 (fragmentation needed). */
|
|
icmpUnreachable(quote: Uint8Array, src: number, dst: number, code: number, mtu = 0): void {
|
|
const [r, rv] = this.ipFrame(dst, src, PROTO_ICMP, 8 + quote.length);
|
|
r[34] = 3; r[35] = code;
|
|
rv.setUint16(40, mtu);
|
|
r.set(quote, 42);
|
|
rv.setUint16(36, fold(sum16(r, 34, 8 + quote.length)));
|
|
this.emit(r);
|
|
}
|
|
|
|
// --- UDP: DHCP, DNS and flows to the backend -------------------------------
|
|
|
|
udpInput(f: Uint8Array, dv: DataView, src: number, dst: number, l4: number, end: number): void {
|
|
if (end - l4 < 8) return;
|
|
const sport = dv.getUint16(l4), dport = dv.getUint16(l4 + 2);
|
|
const payload = f.subarray(l4 + 8, Math.min(end, l4 + dv.getUint16(l4 + 4)));
|
|
if (dport === 67) return this.dhcp(payload);
|
|
if (dport === 53 && (dst === this.dns || dst === this.gw || (dst === QUAD100 && this.tunnel))) {
|
|
void this.dnsQuery(payload, src, sport, dst);
|
|
return;
|
|
}
|
|
if (dst === 0xffffffff || dst >>> 28 === 14) return;
|
|
const quote = f.subarray(14, l4 + 8);
|
|
const host = this.backend.udp ? this.backendHost(dst) : null;
|
|
if (host === null) return this.icmpUnreachable(quote, src, dst, 3);
|
|
this.udpForward(quote, sport, dst, dport, host, payload);
|
|
}
|
|
|
|
/** A datagram from guest port `sport` to `dst`:`dport`, through its flow (opened if new). */
|
|
udpForward(quote: Uint8Array, sport: number, dst: number, dport: number, host: string, payload: Uint8Array): void {
|
|
const fl = this.udp.get(`${sport}/${dst}/${dport}`) ?? this.udpOpen(sport, dst, dport, host, quote);
|
|
if (!fl) return; // the backend refused it at once
|
|
fl.quote = quote;
|
|
this.udpTouch(fl);
|
|
fl.sock!.send(payload);
|
|
}
|
|
|
|
udpOpen(gport: number, ip: number, port: number, host: string, quote: Uint8Array): UdpFlow | undefined {
|
|
if (this.udp.size >= UDP_MAX_FLOWS) this.udpClose(this.udp.values().next().value!);
|
|
const flow: UdpFlow = { key: `${gport}/${ip}/${port}`, gport, ip, port, sock: undefined, quote, lastActive: 0, closed: false };
|
|
this.stats.udpOpened++;
|
|
flow.sock = this.backend.udp!({ host, port }, {
|
|
onMessage: (u8) => {
|
|
if (flow.closed) return;
|
|
this.udpError = null;
|
|
this.udpTouch(flow);
|
|
this.sendUdp(ip, port, this.guest, gport, u8);
|
|
},
|
|
onClose: (err) => {
|
|
if (flow.closed) return;
|
|
this.udpClose(flow);
|
|
if ((err as { code?: string } | null)?.code === "ECONNREFUSED") {
|
|
this.icmpUnreachable(flow.quote, this.guest, ip, 3);
|
|
} else if (err && (err.message ?? String(err)) !== this.udpError) {
|
|
this.udpError = err.message ?? String(err);
|
|
this.log?.(`[net] udp ${ip4str(ip)}:${port}: ${this.udpError}`);
|
|
}
|
|
},
|
|
});
|
|
if (flow.closed) return undefined;
|
|
if (!this.udpSweep) {
|
|
this.udpSweep = setInterval(() => this.udpExpire(), UDP_IDLE_MS / 4);
|
|
(this.udpSweep as { unref?: () => void }).unref?.();
|
|
}
|
|
return flow;
|
|
}
|
|
|
|
/** A datagram either way: the flow moves to the end of the map, which stays in least recently used order. */
|
|
udpTouch(fl: UdpFlow): void {
|
|
this.udp.delete(fl.key);
|
|
this.udp.set(fl.key, fl);
|
|
fl.lastActive = performance.now();
|
|
}
|
|
|
|
udpExpire(): void {
|
|
const old = performance.now() - UDP_IDLE_MS;
|
|
for (const fl of this.udp.values()) {
|
|
if (fl.lastActive >= old) break;
|
|
this.udpClose(fl);
|
|
}
|
|
}
|
|
|
|
udpClose(fl: UdpFlow): void {
|
|
if (fl.closed) return;
|
|
fl.closed = true;
|
|
if (this.udp.get(fl.key) === fl) this.udp.delete(fl.key);
|
|
fl.sock?.close();
|
|
if (!this.udp.size && this.udpSweep) {
|
|
clearInterval(this.udpSweep);
|
|
this.udpSweep = null;
|
|
}
|
|
}
|
|
|
|
dhcp(p: Uint8Array): void {
|
|
if (p.length < 240 || p[0] !== 1) return;
|
|
const dv = new DataView(p.buffer, p.byteOffset, p.byteLength);
|
|
if (dv.getUint32(236) !== 0x63825363) return;
|
|
let type = 0;
|
|
for (let i = 240; i < p.length && p[i] !== 255;) {
|
|
if (p[i] === 0) { i++; continue; }
|
|
if (p[i] === 53) type = p[i + 2]!;
|
|
i += 2 + p[i + 1]!;
|
|
}
|
|
const reply = ({ 1: 2, 3: 5, 8: 5 } as Record<number, number>)[type]; // DISCOVER->OFFER, REQUEST->ACK, INFORM->ACK
|
|
if (!reply) return;
|
|
// A DISCOVER: the guest sets its network up anew, and whatever it was given on top (a tunnel address) is gone.
|
|
if (type === 1) this.tunnel?.guestReset?.();
|
|
const opts = [53, 1, reply, 54, 4, ...this.bytes4(this.gw)];
|
|
if (type !== 8) opts.push(51, 4, ...this.bytes4(86400));
|
|
opts.push(1, 4, ...this.bytes4(this.mask), 3, 4, ...this.bytes4(this.gw),
|
|
6, 4, ...this.bytes4(this.dns), 28, 4, ...this.bytes4((this.net | ~this.mask) >>> 0));
|
|
if (this.mtu) opts.push(26, 2, this.mtu >> 8, this.mtu & 255);
|
|
opts.push(255);
|
|
const r = new Uint8Array(240 + opts.length);
|
|
const rv = new DataView(r.buffer);
|
|
r[0] = 2; r[1] = 1; r[2] = 6;
|
|
r.set(p.subarray(4, 8), 4); // xid
|
|
r.set(p.subarray(10, 12), 10); // flags
|
|
r.set(p.subarray(12, 16), 12); // ciaddr
|
|
if (type !== 8) rv.setUint32(16, this.guest); // yiaddr
|
|
rv.setUint32(20, this.gw); // siaddr
|
|
r.set(p.subarray(28, 44), 28); // chaddr
|
|
rv.setUint32(236, 0x63825363);
|
|
r.set(opts, 240);
|
|
const chaddr = p.slice(28, 34);
|
|
this.sendUdp(this.gw, 67, 0xffffffff, 68, r, Uint8Array.of(255, 255, 255, 255, 255, 255));
|
|
if (reply === 5) this.guestMac = chaddr;
|
|
}
|
|
|
|
bytes4(n: number): number[] { return [n >>> 24, (n >>> 16) & 255, (n >>> 8) & 255, n & 255]; }
|
|
|
|
async dnsQuery(q: Uint8Array, src: number, sport: number, dst: number): Promise<void> {
|
|
if (q.length < 12) return;
|
|
const dv = new DataView(q.buffer, q.byteOffset, q.byteLength);
|
|
if (q[2]! & 0x80 || dv.getUint16(4) !== 1) return; // one question, queries only
|
|
const labels: string[] = [];
|
|
let i = 12;
|
|
while (i < q.length && q[i] !== 0) {
|
|
if (q[i]! & 0xc0) return;
|
|
labels.push(new TextDecoder().decode(q.subarray(i + 1, i + 1 + q[i]!)));
|
|
i += 1 + q[i]!;
|
|
}
|
|
if (i + 5 > q.length) return;
|
|
const qtype = dv.getUint16(i + 1), qclass = dv.getUint16(i + 3);
|
|
const qend = i + 5;
|
|
const name = labels.join(".");
|
|
this.stats.dns++;
|
|
let rcode = 0, addrs: string[] = [];
|
|
const own = qclass === 1 ? this.tunnel?.resolve?.(name.toLowerCase()) : undefined;
|
|
// An exit node: other names (not AAAA: the guest has no IPv6) go through the tunnel to real servers, never to the backend.
|
|
const exit = own === undefined && qtype !== 28 ? this.tunnel?.exitDNS : undefined;
|
|
if (exit) {
|
|
const r = await this.dnsForward(q.slice(), exit);
|
|
const st = this.stats.tunnel!;
|
|
if (r) {
|
|
st.dnsForwarded++;
|
|
return this.sendUdp(dst, 53, src, sport, r);
|
|
}
|
|
st.dnsFailed++;
|
|
rcode = 2;
|
|
} else if (own === null) rcode = 2; // the tunnel's, not known yet: never the backend's
|
|
else if (own) {
|
|
if (!own.length) rcode = 3;
|
|
else if (qtype === 1) addrs = own.filter((a) => /^\d+\.\d+\.\d+\.\d+$/.test(a));
|
|
} else if (qtype === 1 && qclass === 1) {
|
|
try {
|
|
addrs = await this.backend.lookup(name);
|
|
addrs = addrs.filter((a) => /^\d+\.\d+\.\d+\.\d+$/.test(a));
|
|
if (!addrs.length) rcode = 3;
|
|
} catch (e) {
|
|
const err = e as { code?: string; message?: string };
|
|
rcode = err?.code === "ENOTFOUND" || err?.code === "ENODATA" ? 3 : 2;
|
|
if (rcode === 2) this.log?.(`[net] dns ${name}: ${err?.message ?? e}`);
|
|
}
|
|
}
|
|
// Other types (AAAA, ...): NOERROR without answers.
|
|
const r = new Uint8Array(qend + addrs.length * 16);
|
|
r.set(q.subarray(0, qend));
|
|
const rv = new DataView(r.buffer);
|
|
rv.setUint16(2, 0x8000 | (q[2]! & 1) << 8 | 0x80 | rcode); // QR, RD copied, RA
|
|
rv.setUint16(6, addrs.length); rv.setUint16(8, 0); rv.setUint16(10, 0);
|
|
let o = qend;
|
|
for (const a of addrs) {
|
|
rv.setUint16(o, 0xc00c); rv.setUint16(o + 2, 1); rv.setUint16(o + 4, 1);
|
|
rv.setUint32(o + 6, 60); rv.setUint16(o + 10, 4); rv.setUint32(o + 12, ip4(a));
|
|
o += 16;
|
|
}
|
|
this.sendUdp(dst, 53, src, sport, r);
|
|
}
|
|
|
|
// --- TCP ---------------------------------------------------------------------
|
|
|
|
tcpInput(f: Uint8Array, dv: DataView, _src: number, dst: number, l4: number, end: number): void {
|
|
if (end - l4 < 20) return;
|
|
const hl = (f[l4 + 12]! >> 4) * 4;
|
|
const seg: Segment = {
|
|
sport: dv.getUint16(l4), dport: dv.getUint16(l4 + 2),
|
|
seq: dv.getUint32(l4 + 4), ack: dv.getUint32(l4 + 8),
|
|
flags: f[l4 + 13]!, win: dv.getUint16(l4 + 14),
|
|
};
|
|
const payload = f.subarray(l4 + hl, end);
|
|
const key = `${seg.sport}/${dst}/${seg.dport}`;
|
|
let c = this.tcp.get(key);
|
|
if ((seg.flags & (SYN | ACK)) === SYN) {
|
|
if (c && c.irs === seg.seq) return c.input(seg, payload);
|
|
c?.close();
|
|
for (let i = l4 + 20; i < l4 + hl;) {
|
|
const kind = f[i];
|
|
if (kind === 0) break;
|
|
if (kind === 1) { i++; continue; }
|
|
if (kind === 2) seg.mss = dv.getUint16(i + 2);
|
|
if (kind === 3) seg.wscale = Math.min(f[i + 2]!, 14);
|
|
i += Math.max(2, f[i + 1]!);
|
|
}
|
|
c = new TcpConn(this, key, seg.sport, dst, seg.dport, seg);
|
|
this.tcp.set(key, c);
|
|
this.stats.tcpOpened++;
|
|
c.connect();
|
|
return;
|
|
}
|
|
if (c) return c.input(seg, payload);
|
|
if (seg.flags & RST) return;
|
|
// No such connection: reset.
|
|
const fake: TcpEndpoint = { ip: dst, port: seg.dport, gport: seg.sport, rcvNxt: 0, sndUna: 0, sendq: null };
|
|
if (seg.flags & ACK) {
|
|
this.sendTcp(fake, RST, seg.ack, 0, null, 0);
|
|
} else {
|
|
fake.rcvNxt = seqAdd(seg.seq, payload.length + (seg.flags & FIN ? 1 : 0));
|
|
this.sendTcp(fake, RST | ACK, 0, 0, null, 0);
|
|
}
|
|
}
|
|
}
|