Files
unkernel/js/core/tailscale/client.ts
Pooya Parsa d382f7fa9b js: add a pure-JS Tailscale network device (work in progress)
The guest joins a tailnet from Node or the page: ts2021 control over
WebSocket, DERP relays, WireGuard and the packet filter in JS, loaded as
a separate chunk only when the option is used. SDK net option, CLI
--tailscale* flags and a page panel. Relay only; exit nodes, IPv6 and
real peer traffic are not covered yet.
2026-11-28 22:06:18 +00:00

990 lines
39 KiB
TypeScript

// SPDX-License-Identifier: MIT
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
// A Tailscale node in pure JS, relayed only: control (control.ts) for
// login and the netmap, WireGuard (wireguard.ts) to the peers, every
// datagram carried by DERP over WebSockets (derp.ts), since a browser has
// no UDP. It never advertises endpoints, so peers always send through
// DERP too.
//
// const ts = new TailscaleClient({ hostname: "box", authKey, state, onState: save });
// ts.onPacket = (ip) => ...; // IPv4 packets for this node, filtered
// ts.start();
// await ts.ready();
// ts.sendPacket(ip); // an IPv4 packet from ts.addresses[0]
//
// DERP: the home region is the one control already has for this node or,
// since Tailscale's control never shows a node its own region, the one it
// last reported (ControlState.homeDERP): a node that comes back keeps it
// with no probe unless it does not connect within 4 s. Otherwise it is the
// only region, or the nearest of those not marked Avoid or
// NoMeasureNoHome: all are probed at once with a DERP ping, the best of
// those answering within 250 ms of the first wins, and the other probe
// connections close. Its server is told it is preferred, and control
// (NetInfo.PreferredDERP) so that peers send to it; the node is "running"
// once its netmap shows the region (headscale's does), or 1.5 s after
// control answered that report (Tailscale's never shows it). A datagram for a peer
// goes to the peer's home region (HomeDERP; ours when it has none),
// connected on demand: up to 64 datagrams wait for the login, and a
// region other than ours closes after 60 s without traffic. A region's
// servers are tried in the map's order until one logs us in. Datagrams
// arrive on every open region. Disco pings that arrive over DERP from a
// peer of the netmap (its node key and disco key) get a pong naming the
// region (127.3.3.40:<region>), so peers see the node as reachable (at
// most 8 a second per peer; a packet naming another disco key is dropped
// before any key is computed); CallMeMaybe is ignored (there is no UDP to
// try). A DERP map that changes during the probe starts it over.
//
// Routes (peers.ts): each peer's own addresses, and with acceptRoutes
// (off by default, as on Linux) its subnet routes; a prefix two peers
// list goes to the lower node ID. The tailnet range 100.64.0.0/10 is
// claimed even before the first netmap and after close() (packets there
// then have no route), and the local stack's ranges (`reserved`) are never
// routed nor taken as sources. MagicDNS: the netmap's names, short and
// full; other names under its domains, and single labels, do not exist,
// and before the first netmap those (and names under ts.net) cannot be
// answered yet; any other name is not the tailnet's.
//
// Inbound packets pass the netmap's packet filter (filter.ts) before
// onPacket. TSMP pings (IP protocol 99, `tailscale ping --tsmp`) are
// answered here. ICMP echo requests to this node are answered here while
// nothing consumes packets (onPacket null) or with answerPings: true;
// once a consumer is attached (the guest, through NetStack's tunnel) they
// go to it and it answers them (the guest's own Linux stack).
//
// The guest gets the node's IPv4 address itself once attachGuest() is
// called (createKernel does, unless net.tailscale.guestAddress is false or
// there is no kwtty): guest.ts puts it on a dummy tailscale0 with routes
// through NetStack's gateway, and guestAddress tells NetStack to stop
// rewriting. It is set up again when the address or routes change or the
// guest's DHCP starts over (guestReset), and removed by close().
//
// IPv4 only is routed (the guest kernel has no IPv6): IPv6 addresses (and
// routes) of the netmap are kept for WireGuard's source checks, but IPv6
// packets are not sent and are dropped when they arrive. Exit nodes
// (0.0.0.0/0, ::/0) are not used.
import { ControlClient, DEFAULT_CONTROL_URL, type ControlState, type ControlStatus, type DERPMap, type DERPNode, type DERPRegion, type MapResponse, type NetMap, type TailNode } from "./control.ts";
import { DerpClient, type DerpState, type DerpWebSocketConstructor } from "./derp.ts";
import { DiscoKey, derpMagicAddr, discoSender, looksLikeDisco } from "./disco.ts";
import { PacketFilter, parseIp4, parseRange4 } from "./filter.ts";
import { DEFAULT_RESERVED, PeerTable, hex, type PeerEntry, type Route4 } from "./peers.ts";
import { WgDevice } from "./wireguard.ts";
import { GuestAddress, type GuestExec, type TailscaleGuestStatus } from "./guest.ts";
import type { NetTunnel } from "../net.ts";
import { resolveTunnelName, type NetTunnelConfig } from "../net-tunnel.ts";
import type { TailscaleSpec } from "../devices.ts";
export type { ControlState, ControlStatus, NetMap } from "./control.ts";
export type { GuestExec, TailscaleGuestStatus } from "./guest.ts";
/** Tailscale's tunnel MTU: packets to and from peers are at most this large. */
export const TAILSCALE_MTU = 1280;
/** The CGNAT range Tailscale addresses come from: routed to the tunnel even before a peer has an address in it. */
export const TAILNET_RANGE = "100.64.0.0/10";
const QUEUE_PER_REGION = 64;
const REGION_IDLE_MS = 60_000;
const PROBE_TIMEOUT_MS = 4000;
/** After the first region answers the home probe, how long others may still answer. */
const PROBE_GRACE_MS = 250;
/** After control took the home region, how long its netmap may take to show it before the node counts as running anyway. */
const HOME_ECHO_MS = 1500;
const PROTO_ICMP = 1, PROTO_TSMP = 99;
/** Disco pongs per peer per second; more pings in that second get none (a peer pings each path every few seconds). */
const PONGS_PER_SECOND = 8;
/** MagicDNS's domain on Tailscale's own control: before the first netmap, names under it wait for it. */
const TS_NET = "ts.net";
export interface TailscaleClientOptions {
/** Coordination server, default https://controlplane.tailscale.com (headscale: its server_url). */
controlURL?: string;
/** Pre-auth key; without one, login is interactive (onAuthURL). */
authKey?: string;
/** The node's host name (its MagicDNS name's first label). */
hostname: string;
/** Saved state (onState); new keys are made without it. */
state?: ControlState;
/** The control server's Noise key ("mkey:<hex>"), to skip GET /key (headscale serves it without CORS). */
controlPublicKey?: string;
/** Register as an ephemeral node. */
ephemeral?: boolean;
/** ACL tags to request. */
tags?: string[];
/**
* Route the peers' advertised subnet routes too (default false, as
* tailscaled on Linux: `--accept-routes`); their own addresses always
* are. Without it WireGuard takes from a peer only its own addresses as
* sources.
*/
acceptRoutes?: boolean;
/** IPv4 ranges never routed to a peer nor taken as a source from one (default DEFAULT_RESERVED: the local stack's own ranges, loopback, multicast, ...). */
reserved?: string[];
/** Answer ICMP echo requests to this node here, default: while onPacket is null. */
answerPings?: boolean;
/** The state changed (keys, registration): persist it, it is the node's identity. */
onState?: (state: ControlState) => void;
/** Interactive login: open this URL. */
onAuthURL?: (url: string) => void;
/** Any change of status() other than packet counters. */
onStatus?: (status: TailscaleStatus) => void;
/** Inbound IPv4 packets (after the filter); also settable as the onPacket property. */
onPacket?: (ip: Uint8Array) => void;
/** WebSocket constructor for control and DERP, default globalThis.WebSocket. */
WebSocket?: new (url: string, protocols?: string | string[]) => WebSocket;
/** fetch for GET /key, default globalThis.fetch. */
fetch?: typeof fetch;
log?: (msg: string) => void;
/** The WebSocket URL of a DERP node, default wss://HostName[:DERPPort]/derp (ws:// for the embedded DERP of a plain-http control URL). */
derpURL?: (node: DERPNode, region: DERPRegion) => string;
/** Every map message from control as it arrives (diagnostics). */
onMapResponse?: (resp: MapResponse) => void;
}
export type TailscaleState = "idle" | "starting" | "needs-login" | "needs-machine-auth" | "connecting" | "running" | "stopped" | "logged-out";
export interface TailscalePeerStatus {
id: number;
/** MagicDNS name, without the trailing dot. */
name: string;
addresses: string[];
online: boolean | null;
homeDERP: number;
/** Date.now() of the last WireGuard handshake, 0 if none. */
lastHandshake: number;
txBytes: number;
rxBytes: number;
}
export interface TailscaleRegionStatus {
region: number;
state: DerpState;
home: boolean;
/** DERP ping round trip at the home probe, ms. */
rttMs?: number;
}
export interface TailscaleStats {
/** IPv4 packets sent to peers and their bytes. */
txPackets: number;
txBytes: number;
/** Packets from peers (before the filter) and their bytes. */
rxPackets: number;
rxBytes: number;
/** Inbound packets the filter dropped. */
filtered: number;
/** Outbound packets with no peer to go to (or not from this node's address). */
noRoute: number;
/** Inbound IPv6 packets (dropped). */
ipv6Dropped: number;
/** WireGuard datagrams dropped on the way to DERP (queue full, region unknown, too much buffered). */
derpDropped: number;
discoPongs: number;
tsmpPongs: number;
echoReplies: number;
}
export interface TailscaleStatus {
state: TailscaleState;
control: ControlStatus;
/** The pending interactive login's URL. */
authURL?: string;
/** This node's MagicDNS name. */
name: string;
/** This node's addresses, without prefix lengths. */
addresses: string[];
homeDERP: number;
derp: TailscaleRegionStatus[];
peers: TailscalePeerStatus[];
stats: TailscaleStats;
/** The last error control or DERP reported. */
error?: string;
/** Why the filter dropped its last packet. */
lastFiltered?: string;
/** Problems control reports with this node (MapResponse.Health), e.g. a key about to expire. */
health?: string[];
/** The tailnet address in the guest: "address" (on tailscale0, packets unrewritten) or "rewrite" (NetStack maps 10.0.2.15). */
guest: TailscaleGuestStatus;
}
/** What createKernel's `onTailscale` gets from the node of a `net.tailscale` spec. */
export type TailscaleEvent =
/** Save this (it replaces the spec's `state` next time). */
| { type: "state"; state: ControlState }
/** Interactive login: open this URL. */
| { type: "authurl"; url: string }
| { type: "status"; status: TailscaleStatus };
/** The client of a `net.tailscale` spec, started; its events go to `onEvent`. */
export function tailscaleFromSpec(spec: TailscaleSpec, o: { onEvent?: (e: TailscaleEvent) => void; log?: (msg: string) => void }): TailscaleClient {
const emit = (e: TailscaleEvent) => { try { o.onEvent?.(e); } catch {} };
const client = new TailscaleClient({
...spec,
hostname: spec.hostname ?? "unkernel",
log: o.log,
onState: (state) => emit({ type: "state", state }),
onAuthURL: (url) => emit({ type: "authurl", url }),
onStatus: (status) => emit({ type: "status", status }),
});
client.start();
return client;
}
interface Region {
id: number;
client: DerpClient;
lastUsed: number;
queue: [Uint8Array, Uint8Array][];
rtt?: number;
}
/** The default DERP WebSocket URL of a node (see TailscaleClientOptions.derpURL). */
export function defaultDerpURL(node: DERPNode, controlURL: string): string {
const cu = new URL(controlURL);
const plain = cu.protocol === "http:" && (node.HostName === cu.hostname || node.IPv4 === cu.hostname);
const host = node.HostName.includes(":") ? `[${node.HostName}]` : node.HostName;
const port = node.DERPPort && node.DERPPort !== (plain ? 80 : 443) ? `:${node.DERPPort}` : "";
return `${plain ? "ws" : "wss"}://${host}${port}/derp`;
}
export class TailscaleClient implements NetTunnel {
readonly controlURL: string;
/** Inbound IPv4 packets, after the filter (NetStack sets this when the tunnel is attached). */
onPacket: ((ip: Uint8Array) => void) | null;
readonly mtu = TAILSCALE_MTU;
readonly #opts: TailscaleClientOptions;
readonly #log: (msg: string) => void;
readonly #control: ControlClient;
readonly #filter = new PacketFilter();
readonly #listeners = new Set<(s: TailscaleStatus) => void>();
#wg: WgDevice | null = null;
#wgKey = "";
#nodePriv: Uint8Array | null = null;
#disco: DiscoKey | null = null;
#regions = new Map<number, Region>();
#derpMap: DERPMap | null = null;
#home = 0;
#choosing: Promise<void> | null = null;
/** The home region control accepted from us (its netmap need not show it back). */
#reported = 0;
#retry: ReturnType<typeof setTimeout> | undefined;
readonly #table: PeerTable;
#claims: { lo: number; hi: number }[] = [parseRange4(TAILNET_RANGE)!];
#names = new Map<string, string[]>();
/** MagicDNS domains (lower case): names under them are answered from the netmap only. */
#suffixes: string[] = [TS_NET];
#netmap: NetMap | null = null;
#ipv4 = 0;
#addresses: string[] = [];
#state: TailscaleState = "idle";
#authURL: string | undefined;
#error: string | undefined;
#sweep: ReturnType<typeof setInterval> | null = null;
#statusQueued = false;
#closed = false;
#offs: (() => void)[] = [];
#guest: GuestAddress | null = null;
readonly stats: TailscaleStats = {
txPackets: 0, txBytes: 0, rxPackets: 0, rxBytes: 0, filtered: 0, noRoute: 0, ipv6Dropped: 0,
derpDropped: 0, discoPongs: 0, tsmpPongs: 0, echoReplies: 0,
};
constructor(opts: TailscaleClientOptions) {
this.#opts = opts;
this.#log = opts.log ?? (() => {});
this.onPacket = opts.onPacket ?? null;
this.#table = new PeerTable({ acceptRoutes: opts.acceptRoutes, reserved: opts.reserved ?? DEFAULT_RESERVED });
this.controlURL = (opts.controlURL ?? DEFAULT_CONTROL_URL).replace(/\/+$/, "");
this.#control = new ControlClient({
controlURL: this.controlURL,
hostname: opts.hostname,
authKey: opts.authKey,
state: opts.state,
ephemeral: opts.ephemeral,
tags: opts.tags,
controlPublicKey: opts.controlPublicKey,
WebSocket: opts.WebSocket,
fetch: opts.fetch,
logger: (m) => this.#log(`[tailscale] ${m}`),
hostinfo: { Userspace: true, UserspaceRouter: true, App: "unkernel" },
onMapResponse: opts.onMapResponse,
});
const c = this.#control;
this.#offs.push(
c.on("state", (s) => { try { opts.onState?.(s); } catch {} }),
c.on("authurl", (url) => {
this.#authURL = url;
this.#log(`[tailscale] log in at ${url}`);
try { opts.onAuthURL?.(url); } catch {}
this.#changed();
}),
c.on("status", () => this.#changed()),
c.on("error", (e) => { this.#error = e.message; this.#changed(); }),
c.on("netmap", (nm) => this.#onNetMap(nm)),
);
}
// ---- Public surface ----
/** The state to persist (also sent to onState on every change). */
get state(): ControlState {
return this.#control.state;
}
/** The latest netmap, null before the first. */
get netmap(): NetMap | null {
return this.#netmap;
}
/** This node's addresses (IPv4 first), without prefix lengths; empty before the first netmap. */
get addresses(): string[] {
return [...this.#addresses];
}
/** NetTunnel: this node's IPv4 address as a number, 0 before it has one. */
get ipv4(): number {
return this.#ipv4;
}
/** Starts logging in and following the netmap (once). */
start(): void {
if (this.#closed || this.#state !== "idle") return;
this.#setState("starting");
this.#control.start();
this.#sweep = setInterval(() => this.#sweepRegions(), REGION_IDLE_MS / 4);
(this.#sweep as { unref?: () => void }).unref?.();
}
/** Resolves once the node has a netmap and its home DERP is connected. */
ready(timeoutMs = 0): Promise<void> {
if (this.#state === "running") return Promise.resolve();
return new Promise((resolve, reject) => {
let timer: ReturnType<typeof setTimeout> | undefined;
const off = this.on("status", (s) => {
if (s.state === "running") {
done();
resolve();
} else if (s.state === "stopped" || s.state === "logged-out") {
done();
reject(new Error(`tailscale: ${s.state}`));
}
});
const done = () => {
off();
clearTimeout(timer);
};
if (timeoutMs > 0) timer = setTimeout(() => {
done();
reject(new Error(`tailscale: not running after ${timeoutMs} ms (${this.#state}${this.#error ? `: ${this.#error}` : ""})`));
}, timeoutMs);
});
}
/** Listens to status changes; returns the function that removes the listener. */
on(event: "status", fn: (s: TailscaleStatus) => void): () => void {
void event;
this.#listeners.add(fn);
return () => void this.#listeners.delete(fn);
}
/**
* Sends an IPv4 packet whose source is this node's address to the peer
* that routes its destination. False when it cannot go (no route, wrong
* source, not IPv4, not up).
*/
sendPacket(ip: Uint8Array): boolean {
const wg = this.#wg;
if (!wg || ip.length < 20 || ip[0]! >> 4 !== 4 || !this.#ipv4 || u32(ip, 12) !== this.#ipv4 || !this.#lookup(u32(ip, 16))) {
this.stats.noRoute++;
return false;
}
this.#filter.noteOutbound(ip);
this.stats.txPackets++;
this.stats.txBytes += ip.length;
return wg.sendPacket(ip);
}
/** NetTunnel: whether an IPv4 destination (as a number) goes into the tunnel (the tailnet range or a peer's route). */
routesIPv4(dst: number): boolean {
if (this.#table.reserved(dst)) return false;
return this.#claims.some((r) => dst >= r.lo && dst <= r.hi) || this.#lookup(dst) !== null;
}
/** The peer and prefix that route an IPv4 address, or undefined. */
route(dst: string): { prefix: string; peer: string; nodeKey: string } | undefined {
const n = parseIp4(dst);
const r = n === null ? null : this.#lookupRoute(n);
return r ? { prefix: fmtRange(r), peer: nodeName(r.peer.node), nodeKey: r.peer.node.Key } : undefined;
}
/** Every IPv4 route: the peers' addresses and, with acceptRoutes, their subnet routes; longest prefix first. */
routeTable(): { prefix: string; peer: string; nodeKey: string }[] {
return this.#table.routes.map((r) => ({ prefix: fmtRange(r), peer: nodeName(r.peer.node), nodeKey: r.peer.node.Key }));
}
/**
* A MagicDNS name (a node's full name, or without the tailnet suffix;
* case and a trailing dot do not matter): its addresses, IPv4 first.
* [] for another name under a MagicDNS domain or a single label (no
* such host), null for those before the first netmap (not known yet),
* undefined for any other name (not the tailnet's).
*/
resolve(name: string): string[] | null | undefined {
const r = resolveTunnelName(this.#names, this.#suffixes, !!this.#netmap && !this.#closed, name);
return r ? [...r] : r;
}
/**
* Gives the guest the node's IPv4 address (guest.ts: tailscale0 and
* routes, by running scripts through `exec`), from now on and whenever
* the address or routes change; close() takes it away. Until a script
* succeeded, and whenever one fails, NetStack keeps rewriting.
*/
attachGuest(exec: GuestExec): void {
if (this.#closed || this.#guest) return;
this.#guest = new GuestAddress({ exec, log: this.#log, onChange: () => this.#changed() });
this.#updateGuest();
}
/** NetTunnel: the address the guest owns itself (its packets pass unrewritten), 0 when none or not this node's. */
get guestAddress(): number {
const a = this.#guest?.address;
const n = a ? parseIp4(a) ?? 0 : 0;
return n === this.#ipv4 ? n : 0;
}
/** NetTunnel: the guest set its network up again (a DHCP discover): it has to be given the address again. */
guestReset(): void {
this.#guest?.reset();
}
#updateGuest(): void {
const g = this.#guest;
if (!g) return;
g.set(this.#ipv4 && !this.#closed ? { ipv4: ip4str(this.#ipv4), routes: this.tunnelConfig().claims } : null);
}
/** What a NetStack elsewhere (a kernel worker) needs to act as this tunnel (RemoteTunnel in net-tunnel.ts). */
tunnelConfig(): NetTunnelConfig {
const names: Record<string, string[]> = {};
for (const [k, v] of this.#names) {
const v4 = v.filter((a) => !a.includes(":"));
if (v4.length) names[k] = v4;
}
const routes = this.#table.routes;
return {
ipv4: this.#ipv4 ? ip4str(this.#ipv4) : "",
claims: [TAILNET_RANGE, ...routes.filter((r) => !this.#claims.some((c) => r.lo >= c.lo && r.hi <= c.hi)).map(fmtRange)],
routes: routes.map(fmtRange),
names,
suffixes: [...this.#suffixes],
known: !!this.#netmap && !this.#closed,
guest: this.guestAddress ? ip4str(this.guestAddress) : "",
mtu: TAILSCALE_MTU,
};
}
status(): TailscaleStatus {
const wgPeers = new Map((this.#wg?.peers() ?? []).map((p) => [hex(p.publicKey), p]));
const s: TailscaleStatus = {
state: this.#state,
control: this.#control.status,
name: this.#closed ? "" : this.#netmap?.name ?? "",
addresses: this.addresses,
homeDERP: this.#home,
derp: [...this.#regions.values()].map((r) => ({ region: r.id, state: r.client.state, home: r.id === this.#home, ...(r.rtt !== undefined ? { rttMs: r.rtt } : {}) })),
peers: [...this.#table.peers.entries()].map(([id, p]) => {
const w = wgPeers.get(id);
return {
id: p.node.ID, name: nodeName(p.node), addresses: p.node.Addresses.map(stripLen), online: p.node.Online ?? null,
homeDERP: p.node.HomeDERP, lastHandshake: w?.lastHandshake ?? 0, txBytes: w?.txBytes ?? 0, rxBytes: w?.rxBytes ?? 0,
};
}),
stats: { ...this.stats, filtered: this.stats.filtered + this.#filter.stats.dropped },
guest: this.#guest?.status() ?? { mode: "rewrite", enabled: false, busy: false },
};
if (this.#authURL && (this.#state === "needs-login" || this.#state === "starting")) s.authURL = this.#authURL;
if (this.#error) s.error = this.#error;
if (this.#filter.stats.lastDrop) s.lastFiltered = this.#filter.stats.lastDrop;
if (this.#netmap?.health.length) s.health = [...this.#netmap.health];
return s;
}
/** Expires the node key at control and closes; the saved state then needs a new login. */
async logout(): Promise<void> {
await this.#control.logout();
await this.close();
this.#setState("logged-out");
}
/** Stops control, every DERP connection, WireGuard and every timer. */
async close(): Promise<void> {
if (this.#closed) return;
// The guest loses the address first (a script in the guest; it fails fast once the kernel is gone).
const guest = this.#guest?.close();
this.#closed = true;
if (this.#sweep) clearInterval(this.#sweep);
clearTimeout(this.#retry);
this.#sweep = null;
for (const off of this.#offs.splice(0)) off();
this.#teardown();
// No address, routes or names any more (a worker's RemoteTunnel hears it with the status).
this.#ipv4 = 0;
this.#addresses = [];
this.#names = new Map();
this.onPacket = null;
this.#setState("stopped");
await Promise.all([this.#control.stop(), guest && Promise.race([guest, new Promise((r) => setTimeout(r, 10_000))])]);
}
// ---- Netmap ----
/** @internal Takes a netmap as if control had sent it (tests). */
applyNetMap(nm: NetMap): void {
this.#onNetMap(nm);
}
#onNetMap(nm: NetMap): void {
if (this.#closed) return;
if (nm.health.join("\n") !== (this.#netmap?.health ?? []).join("\n")) for (const h of nm.health) this.#log(`[tailscale] control: ${h}`);
this.#netmap = nm;
this.#authURL = undefined;
this.#error = undefined;
if (this.#wgKey !== this.#control.nodeKey) this.#rekey();
const addrs = nm.addresses.map(stripLen);
this.#addresses = [...addrs.filter((a) => !a.includes(":")), ...addrs.filter((a) => a.includes(":"))];
this.#ipv4 = parseIp4(this.#addresses[0] ?? "") ?? 0;
this.#filter.setRules(nm.packetFilter);
this.#filter.setLocal(this.#ipv4 ? [this.#ipv4] : []);
this.#syncPeers(nm);
this.#buildNames(nm);
this.#updateGuest();
if (nm.derpMap) {
this.#derpMap = nm.derpMap;
for (const id of [...this.#regions.keys()]) if (!nm.derpMap.Regions[String(id)]) this.#closeRegion(id);
if (!this.#home || !nm.derpMap.Regions[String(this.#home)]) {
this.#home = 0;
this.#choosing ??= this.#chooseHome().catch((e) => {
this.#error = `derp: ${(e as Error)?.message ?? e}`;
this.#log(`[tailscale] ${this.#error}`);
}).finally(() => { this.#choosing = null; this.#changed(); });
}
}
this.#changed();
}
/** A new node key (control rotated it): a new WireGuard device and DERP connections. */
#rekey(): void {
this.#teardown();
this.#wgKey = this.#control.nodeKey;
this.#nodePriv = this.#control.nodePrivateKey;
this.#disco = new DiscoKey(this.#control.discoPrivateKey);
this.#wg = new WgDevice({
privateKey: this.#nodePriv,
mtu: TAILSCALE_MTU,
send: (peer, dg) => this.#toDerp(peer, dg),
onPacket: (_peer, ip) => this.#fromPeer(ip),
log: (m) => this.#log(`[tailscale] ${m}`),
});
}
#teardown(): void {
for (const id of [...this.#regions.keys()]) this.#closeRegion(id);
this.#home = 0;
this.#wg?.close();
this.#wg = null;
this.#table.clear();
}
#syncPeers(nm: NetMap): void {
this.#table.sync(nm.peers, this.#wg!, this.#log);
}
#buildNames(nm: NetMap): void {
const names = new Map<string, string[]>();
const suffixes = (nm.dns?.Domains ?? []).map((d) => d.toLowerCase().replace(/\.$/, "")).filter(Boolean);
const add = (name: string, addrs: string[]) => {
if (name && !names.has(name)) names.set(name, addrs);
};
for (const node of [nm.self, ...nm.peers]) {
const fqdn = (node.Name ?? "").toLowerCase().replace(/\.$/, "");
if (!fqdn) continue;
const addrs = node.Addresses.map(stripLen);
const v4first = [...addrs.filter((a) => !a.includes(":")), ...addrs.filter((a) => a.includes(":"))];
add(fqdn, v4first);
}
// Short names after the full ones, so a full name always wins.
for (const node of [nm.self, ...nm.peers]) {
const fqdn = (node.Name ?? "").toLowerCase().replace(/\.$/, "");
if (!fqdn) continue;
const addrs = names.get(fqdn)!;
for (const s of suffixes) if (fqdn.endsWith(`.${s}`)) add(fqdn.slice(0, -s.length - 1), addrs);
add(fqdn.split(".")[0]!, addrs);
}
for (const r of nm.dns?.ExtraRecords ?? []) {
if (r.Type && r.Type !== "A" && r.Type !== "AAAA") continue;
const n = r.Name.toLowerCase().replace(/\.$/, "");
names.set(n, [...(names.get(n) ?? []), r.Value]);
}
this.#names = names;
// The MagicDNS domains: this node's own (its name less the first label) and the search domains.
const self = (nm.self.Name ?? "").toLowerCase().replace(/\.$/, "");
const own = self.includes(".") ? [self.slice(self.indexOf(".") + 1)] : [];
this.#suffixes = [...new Set([...own, ...suffixes])];
}
#lookupRoute(dst: number): Route4 | null {
return this.#table.lookup(dst);
}
#lookup(dst: number): PeerEntry | null {
return this.#lookupRoute(dst)?.peer ?? null;
}
// ---- DERP ----
async #chooseHome(): Promise<void> {
// A DERP map that changes during the probe starts it over.
for (;;) {
const dm = this.#derpMap;
if (!dm || this.#closed) return;
if (await this.#probeHome(dm)) return;
}
}
/** Probes `dm`'s regions and takes the best as home; false when the DERP map changed meanwhile. */
async #probeHome(dm: DERPMap): Promise<boolean> {
const ids = Object.values(dm.Regions)
.filter((r) => !r.Avoid && !r.NoMeasureNoHome && r.Nodes?.some((n) => !n.STUNOnly))
.map((r) => r.RegionID)
.sort((a, b) => a - b);
if (!ids.length) throw new Error("no DERP region to use");
let best = ids[0]!;
/** Regions this probe opened -> their lastUsed then (unchanged: nothing else used them). */
const opened = new Map<number, number>();
const latency: Record<string, number> = {};
let probe = ids;
// The home of a node that comes back (its netmap's, else the one it last
// reported: Tailscale's control does not show it back): kept with no
// probe, unless it does not connect within PROBE_TIMEOUT_MS.
const prev = this.#netmap?.self.HomeDERP || this.#control.state.homeDERP || 0;
if (prev && ids.includes(prev)) {
const had = this.#regions.has(prev);
const r = this.#region(prev);
const up = r ? await r.client.ready(PROBE_TIMEOUT_MS).then(() => true, () => false) : false;
if (this.#closed) return true;
if (up || ids.length === 1) {
best = prev;
probe = [];
} else {
this.#log(`[tailscale] the previous home DERP region ${prev} does not connect; probing the others`);
if (!had && r && !r.queue.length) this.#closeRegion(prev);
probe = ids.filter((id) => id !== prev);
best = probe[0]!;
}
}
if (probe.length > 1) {
// Every probe starts now and takes a few round trips, so the first
// answers are the nearest regions: take the best of those that
// answer within PROBE_GRACE_MS of the first, not waiting for the rest.
let min = Infinity;
let first!: () => void;
const answered = new Promise<void>((ok) => { first = ok; });
const all = Promise.all(probe.map(async (id) => {
const had = this.#regions.has(id);
const r = this.#region(id);
if (!r) return;
if (!had) opened.set(id, r.lastUsed);
try {
await r.client.ready(PROBE_TIMEOUT_MS);
const rtt = await r.client.ping(PROBE_TIMEOUT_MS);
r.rtt = rtt;
latency[`${id}-v4`] = rtt / 1000;
if (rtt < min) { min = rtt; best = id; }
first();
} catch {
// no answer: not a candidate
}
}));
await Promise.race([answered, all]);
if (min !== Infinity) {
let timer: ReturnType<typeof setTimeout> | undefined;
await Promise.race([all, new Promise<void>((ok) => { timer = setTimeout(ok, PROBE_GRACE_MS); })]);
clearTimeout(timer);
}
if (this.#closed) return true;
if (min === Infinity) this.#log("[tailscale] no DERP region answered a ping; using the first");
}
if (this.#closed) return true;
if (this.#derpMap !== dm) return false;
this.#home = best;
const home = this.#region(best);
if (!home) throw new Error(`DERP region ${best} has no node`);
for (const r of [...this.#regions.values()]) {
// A connection the probe opened and nothing has used: closed (a peer's region reopens on demand).
if (r.id !== best && !r.queue.length && opened.get(r.id) === r.lastUsed) this.#closeRegion(r.id);
else r.client.notePreferred(r.id === best);
}
this.#log(`[tailscale] home DERP region ${best} (${dm.Regions[String(best)]?.RegionCode ?? "?"})`);
this.#changed();
// Control is told, retried while this stays the home: peers send to the region it has for us.
for (let delay = 1000; !this.#closed && this.#home === best && this.#derpMap === dm; delay = Math.min(delay * 2, 30_000)) {
try {
await this.#control.setPreferredDERP(best, Object.keys(latency).length ? latency : undefined);
// Peers learn it with their next netmap update, after control answered: headscale's
// netmap shows the region back with that update, Tailscale's never does, so a short
// wait stands in for it (headscale's peers were not reachable yet right at the answer).
if (this.#netmap?.self.HomeDERP !== best) {
await new Promise<void>((ok) => {
this.#retry = setTimeout(ok, HOME_ECHO_MS);
(this.#retry as { unref?: () => void }).unref?.();
});
}
if (this.#home === best) this.#reported = best;
break;
} catch (e) {
this.#log(`[tailscale] reporting the home DERP: ${(e as Error)?.message ?? e}`);
await new Promise<void>((ok) => {
this.#retry = setTimeout(ok, delay);
(this.#retry as { unref?: () => void }).unref?.();
});
}
}
this.#changed();
return this.#derpMap === dm || this.#closed;
}
/** The connection to a region, opened when needed; undefined for a region the DERP map lacks. */
#region(id: number): Region | undefined {
let r = this.#regions.get(id);
if (r) return r;
const reg = this.#derpMap?.Regions[String(id)];
const nodes = (reg?.Nodes ?? []).filter((n) => !n.STUNOnly);
if (!reg || !nodes.length || !this.#nodePriv) return undefined;
// The region's servers in order: one that does not log us in gives way to the next.
const [url, ...fallbackURLs] = nodes.map((node) => this.#opts.derpURL?.(node, reg) ?? defaultDerpURL(node, this.controlURL));
const region: Region = { id, client: null as unknown as DerpClient, lastUsed: Date.now(), queue: [] };
region.client = new DerpClient({
url: url!,
fallbackURLs,
privateKey: this.#nodePriv,
WebSocket: this.#opts.WebSocket as unknown as DerpWebSocketConstructor | undefined,
preferred: id === this.#home,
appName: "unkernel",
log: (m) => this.#log(`[tailscale] ${m}`),
onPacket: (src, data) => this.#fromDerp(region, src, data),
onState: (s, detail) => {
if (s === "connected") {
for (const [dst, dg] of region.queue.splice(0)) if (!region.client.send(dst, dg)) this.stats.derpDropped++;
// The home region's last loss is over.
if (this.#error?.startsWith(`derp ${id}: `)) this.#error = undefined;
} else if (s === "disconnected" && detail && region.id === this.#home) this.#error = `derp ${id}: ${detail}`;
this.#changed();
},
});
this.#regions.set(id, region);
region.client.start();
this.#changed();
return region;
}
#closeRegion(id: number): void {
const r = this.#regions.get(id);
if (!r) return;
this.#regions.delete(id);
r.client.close();
r.queue.length = 0;
}
#sweepRegions(): void {
const old = Date.now() - REGION_IDLE_MS;
let closed = false;
for (const r of [...this.#regions.values()]) {
if (r.id === this.#home || !this.#home || r.lastUsed >= old) continue;
this.#log(`[tailscale] closing idle DERP region ${r.id}`);
this.#closeRegion(r.id);
closed = true;
}
if (closed) this.#changed();
}
/** A WireGuard datagram for a peer: through its home region (ours when it has none). */
#toDerp(peerKey: Uint8Array, dg: Uint8Array): void {
const peer = this.#table.peers.get(hex(peerKey));
const id = peer?.node.HomeDERP || this.#home;
const r = id ? this.#region(id) ?? (this.#home ? this.#region(this.#home) : undefined) : undefined;
if (!r) {
this.stats.derpDropped++;
return;
}
r.lastUsed = Date.now();
if (r.client.state === "connected") {
if (!r.client.send(peerKey, dg)) this.stats.derpDropped++;
return;
}
if (r.queue.length >= QUEUE_PER_REGION) {
r.queue.shift();
this.stats.derpDropped++;
}
r.queue.push([peerKey.slice(), dg]);
}
#fromDerp(region: Region, src: Uint8Array, data: Uint8Array): void {
region.lastUsed = Date.now();
if (looksLikeDisco(data)) return this.#onDisco(region, src, data);
this.#wg?.receive(src, data);
}
/**
* A disco ping from a peer of the netmap: a pong through the same
* region. The packet must name the disco key the netmap gives the peer
* DERP says sent it (checked before any key is computed; the box key is
* computed once per peer), and a peer gets at most PONGS_PER_SECOND.
*/
#onDisco(region: Region, src: Uint8Array, data: Uint8Array): void {
const peer = this.#table.peers.get(hex(src));
const sender = discoSender(data);
if (!peer?.disco || !this.#disco || !sender || hex(sender) !== hex(peer.disco)) return;
const now = Date.now();
if (now - peer.pongWindow >= 1000) {
peer.pongWindow = now;
peer.pongs = 0;
}
if (peer.pongs >= PONGS_PER_SECOND) return;
const r = this.#disco.answerPing(data, derpMagicAddr(region.id), peer.disco);
if (!r) return;
peer.pongs++;
if (region.client.send(src, r.pong)) this.stats.discoPongs++;
}
// ---- Packets from peers ----
#fromPeer(ip: Uint8Array): void {
this.stats.rxPackets++;
this.stats.rxBytes += ip.length;
if (ip[0]! >> 4 !== 4) {
this.stats.ipv6Dropped++;
return;
}
const ihl = (ip[0]! & 15) * 4;
// A source in the local stack's ranges (its gateway, loopback, ...) is never a peer's.
if (this.#table.reserved(u32(ip, 12))) {
this.stats.filtered++;
return;
}
if (ip[9] === PROTO_TSMP && u32(ip, 16) === this.#ipv4) return this.#tsmp(ip, ihl);
if (!this.#filter.allowIn(ip)) return;
const consumer = this.onPacket;
if (ip[9] === PROTO_ICMP && ip[ihl] === 8 && (this.#opts.answerPings ?? !consumer)) return this.#echoReply(ip, ihl);
consumer?.(ip);
}
/** TSMP (net/packet/tsmp.go): a ping ('p' + 8 bytes) gets a pong ('o' + the 8 bytes + peerapi port 0). */
#tsmp(ip: Uint8Array, ihl: number): void {
if (ip.length < ihl + 9 || ip[ihl] !== 0x70) return;
const r = ipv4Packet(this.#ipv4, u32(ip, 12), PROTO_TSMP, 11);
r[20] = 0x6f;
r.set(ip.subarray(ihl + 1, ihl + 9), 21);
if (this.#wg?.sendPacket(r)) this.stats.tsmpPongs++;
}
#echoReply(ip: Uint8Array, ihl: number): void {
const total = Math.min(ip.length, (ip[2]! << 8) | ip[3]!);
if (total < ihl + 8) return;
const msg = ip.subarray(ihl, total);
const r = ipv4Packet(this.#ipv4, u32(ip, 12), PROTO_ICMP, msg.length);
r.set(msg, 20);
r[20] = 0;
r[22] = r[23] = 0;
const c = checksum(r, 20, msg.length);
r[22] = c >> 8;
r[23] = c & 255;
if (this.#wg?.sendPacket(r)) this.stats.echoReplies++;
}
// ---- Status ----
#setState(s: TailscaleState): void {
if (this.#state === s) return;
this.#state = s;
this.#changed();
}
#changed(): void {
if (!this.#closed && this.#state !== "stopped" && this.#state !== "logged-out" && this.#state !== "idle") {
const cs = this.#control.status;
const home = this.#regions.get(this.#home);
const next: TailscaleState = cs === "needs-login" ? "needs-login"
: cs === "needs-machine-auth" ? "needs-machine-auth"
: !this.#netmap ? "starting"
// Running once control has our home region too (peers learn it with the same update):
// it took our report, or its netmap shows the region.
: home?.client.state === "connected" && this.#ipv4 && (this.#reported === this.#home || this.#netmap.self.HomeDERP === this.#home) ? "running" : "connecting";
if (next !== this.#state) {
this.#state = next;
this.#log(`[tailscale] ${next}${next === "running" ? `: ${this.#addresses.join(", ")} (${this.#netmap?.name})` : ""}`);
}
}
if (this.#statusQueued) return;
this.#statusQueued = true;
queueMicrotask(() => {
this.#statusQueued = false;
const s = this.status();
try { this.#opts.onStatus?.(s); } catch {}
for (const fn of [...this.#listeners]) {
try { fn(s); } catch {}
}
});
}
}
// ---- helpers ----
function u32(b: Uint8Array, o: number): number {
return ((b[o]! << 24) | (b[o + 1]! << 16) | (b[o + 2]! << 8) | b[o + 3]!) >>> 0;
}
function ip4str(n: number): string {
return `${n >>> 24}.${(n >>> 16) & 255}.${(n >>> 8) & 255}.${n & 255}`;
}
const stripLen = (p: string) => p.replace(/\/\d+$/, "");
function fmtRange(r: { lo: number; hi: number }): string {
const size = r.hi - r.lo + 1;
const bits = 32 - Math.log2(size);
return Number.isInteger(bits) ? `${ip4str(r.lo)}/${bits}` : `${ip4str(r.lo)}-${ip4str(r.hi)}`;
}
function nodeName(n: TailNode): string {
return (n.Name ?? "").replace(/\.$/, "") || n.ComputedName || n.Hostinfo?.Hostname || String(n.ID);
}
function checksum(b: Uint8Array, off: number, len: number): number {
let s = 0;
const end = off + len;
let i = off;
for (; i + 1 < end; i += 2) s += (b[i]! << 8) | b[i + 1]!;
if (i < end) s += b[i]! << 8;
while (s > 0xffff) s = (s & 0xffff) + (s >>> 16);
return ~s & 0xffff;
}
/** An IPv4 header (20 bytes, TTL 64, checksum set) and room for `len` bytes of payload. */
function ipv4Packet(src: number, dst: number, proto: number, len: number): Uint8Array {
const r = new Uint8Array(20 + len);
r[0] = 0x45;
r[2] = (20 + len) >> 8;
r[3] = (20 + len) & 255;
r[8] = 64;
r[9] = proto;
for (let i = 0; i < 4; i++) {
r[12 + i] = (src >>> (24 - 8 * i)) & 255;
r[16 + i] = (dst >>> (24 - 8 * i)) & 255;
}
const c = checksum(r, 0, 20);
r[10] = c >> 8;
r[11] = c & 255;
return r;
}