diff --git a/docs/internal/ARCHITECTURE.md b/docs/internal/ARCHITECTURE.md index c1d5c1c06..0a0541f8f 100644 --- a/docs/internal/ARCHITECTURE.md +++ b/docs/internal/ARCHITECTURE.md @@ -50,7 +50,7 @@ worker daemon ── uplink (WebSocket to /v1/uplink, worker dials) ──┘ | agent-device | Optional edge: the two agent-device daemons (simulators, phones) beside a worker, its HTTP front | [agent-device](../../src/agent-device/AGENTS.md) | | stream | Optional edge: a running device's live screen over HTTP, relayed by a gateway | [stream](../../src/stream/AGENTS.md) | | input | Optional edge: a lease holder's taps and keys over a WebSocket, relayed by a gateway | [input](../../src/input/AGENTS.md) | -| tunnel | Optional edge: a lease holder's reverse tunnels from its Android device over a WebSocket, on a lone worker or through a gateway | [tunnel](../../src/tunnel/AGENTS.md) | +| tunnel | Optional edge: a lease holder's reverse tunnels (device to caller) and forward tunnels (caller to device) on its Android device over a WebSocket, on a lone worker or through a gateway | [tunnel](../../src/tunnel/AGENTS.md) | | auth | Credential → identity: tokens, admin secret, `hello`, uplink join token, HTTP strategies | [auth](../../src/auth/AGENTS.md) | | http | HTTP frontend: routes, SSE | [http](../../src/http/AGENTS.md) | | cli | Operator command surface | [cli](../../src/cli/AGENTS.md) | diff --git a/e2e/slow-android-tunnel.test.ts b/e2e/slow-android-tunnel.test.ts index 3c56e35d9..3f42773c3 100644 --- a/e2e/slow-android-tunnel.test.ts +++ b/e2e/slow-android-tunnel.test.ts @@ -1,10 +1,21 @@ +import { execFile } from "node:child_process"; import { existsSync } from "node:fs"; import { createServer } from "node:http"; +import { connect } from "node:net"; import { homedir } from "node:os"; import { join } from "node:path"; -import { describe, expect, it } from "vitest"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; -import { DEVICE_READY_MS, freeLoopbackPort, waitFor, withHttpDaemon } from "./helpers/index.js"; +import { + DEVICE_READY_MS, + freeLoopbackPort, + openInputSocket, + waitFor, + waitForDeviceState, + withHttpDaemon, + withSharedDaemon, + type SharedTestEnv, +} from "./helpers/index.js"; const ANDROID_HOME = process.env.ANDROID_HOME ?? @@ -15,6 +26,41 @@ const hasAndroidSdk = const BODY = "simlock-tunnel-ok"; +// why: through a gateway an adb call names its lease and runs as the agent that holds it (the gateway refuses `device.exec` for any other requester),. +function leaseAdb( + env: SharedTestEnv, + holder: { readonly agentId: string; readonly leaseId: string }, + args: readonly string[], +): ReturnType { + return env.cli(["adb", "--lease", holder.leaseId, ...args], { + env: { SIMLOCK_AGENT_ID: holder.agentId }, + }); +} + +// why: a lease sent through a gateway before its worker joined with a catalog is refused NO_CAPACITY. +async function waitForWorkerJoined(gateway: SharedTestEnv): Promise { + let observed = "nothing read yet"; + await waitFor( + async () => { + const listed = await gateway.cli(["worker", "list", "--json"], { timeout: 60_000 }); + const workers = + (listed.json as { workers?: { connection: string; catalog: unknown[] }[] } | undefined) + ?.workers ?? []; + observed = JSON.stringify( + workers.map((worker) => [worker.connection, worker.catalog.length]), + ); + return workers.some( + (worker) => worker.connection === "connected" && worker.catalog.length > 0, + ); + }, + { + timeout: 120_000, + interval: 1_000, + label: () => `the worker joined the gateway with a catalog; last observed: ${observed}`, + }, + ); +} + // why: only a real emulator proves that `adb reverse` reaches the caller's loopback listener through the tunnel socket; the fast end-to-end test fakes the device side. describe.skipIf(!hasAndroidSdk)( "simlock tunnel reverse on a real emulator against a lone worker", @@ -106,3 +152,478 @@ describe.skipIf(!hasAndroidSdk)( ); }, ); + +const FORWARD_IN = "/data/local/tmp/simlock-forward-in"; + +// why: through a gateway the holder's socket is relayed to the worker, and only a real emulator proves both directions of the device side there: `adb reverse` reaching the caller, and the host protocol reaching a device server. +describe.skipIf(!hasAndroidSdk)( + "simlock tunnel reverse and forward on a real emulator through a gateway", + { tags: ["slow", "android"] }, + () => { + it( + "serves the caller's page to the emulator through reverse, and a device server's bytes to the caller's loopback port through forward, with the caller's bytes arriving", + { timeout: 480_000 }, + async () => { + const gatewayPort = await freeLoopbackPort(); + const gateway: SharedTestEnv = await withSharedDaemon({ + configOverrides: { + capabilities: { tunnel: { enabled: true } }, + http: { enabled: true, host: "127.0.0.1", port: gatewayPort }, + }, + driver: "none", + role: "gateway", + }); + let worker: SharedTestEnv | undefined; + const page = createServer((_request, response) => { + response.writeHead(200, { "content-type": "text/plain" }).end(BODY); + }); + try { + const joined = await gateway.cli(["token", "create", "--role", "worker"]); + expect(joined.code, joined.stderr).toBe(0); + worker = await withSharedDaemon({ + configOverrides: { + capabilities: { tunnel: { enabled: true } }, + gateway: { + label: "worker", + token: (joined.json as { secret: string }).secret, + url: `ws://127.0.0.1:${String(gatewayPort)}`, + }, + http: { enabled: false, host: "127.0.0.1", port: await freeLoopbackPort() }, + idle: { shutdownAfterMs: 300_000 }, + warmPool: { learn: false }, + }, + driver: "real", + }); + const reversePort = await freeLoopbackPort(); + const forwardPort = await freeLoopbackPort(); + await new Promise((resolve) => page.listen(reversePort, "127.0.0.1", resolve)); + + await waitForWorkerJoined(gateway); + const lease = await gateway.cli( + [ + "lease", + "--platform", + "android", + "--device", + "Pixel 9", + "--agent-id", + "tunnel", + "--detach", + ], + { timeout: DEVICE_READY_MS }, + ); + expect(lease.code, `lease failed: ${lease.stderr}`).toBe(0); + const leaseId = (lease.json as { lease: { id: string } }).lease.id; + const created = await gateway.cli(["token", "create", "--role", "operator"]); + expect(created.code, created.stderr).toBe(0); + const secret = (created.json as { secret: string }).secret; + + const tunnel = gateway.cliBackground([ + "--token", + secret, + "tunnel", + "reverse", + String(reversePort), + "forward", + String(forwardPort), + "--url", + `http://127.0.0.1:${String(gatewayPort)}`, + "--lease", + leaseId, + ]); + await tunnel.firstStdoutLine(60_000); + const lines = [ + `reverse device:${String(reversePort)} -> localhost:${String(reversePort)} (lease ${leaseId})`, + `forward localhost:${String(forwardPort)} -> device:${String(forwardPort)} (lease ${leaseId})`, + ]; + await waitFor(async () => tunnel.stdoutSoFar() === `${lines.join("\n")}\n`, { + interval: 500, + label: "both tunnel lines", + timeout: 30_000, + }); + + let answer = ""; + await waitFor( + async () => { + const fetched = await leaseAdb(gateway, { agentId: "tunnel", leaseId }, [ + "shell", + `(printf 'GET / HTTP/1.0\\r\\n\\r\\n'; sleep 2) | nc 127.0.0.1 ${String(reversePort)}`, + ]); + answer = `${fetched.stdout}${fetched.stderr}`; + return fetched.stdout.includes(BODY); + }, + { + interval: 1_000, + label: () => + `the device reading the caller's page through the gateway, last answer: ${answer}`, + timeout: 60_000, + }, + ); + expect(answer).toContain(BODY); + + const server = gateway.cliBackground( + [ + "adb", + "--lease", + leaseId, + "shell", + `(printf 'device-ok'; sleep 30) | nc -l -p ${String(forwardPort)} > ${FORWARD_IN}`, + ], + { env: { SIMLOCK_AGENT_ID: "tunnel" } }, + ); + const received = await new Promise((resolve, reject) => { + const giveUp = Date.now() + 5_000; + const attempt = (): void => { + const socket = connect({ host: "127.0.0.1", port: forwardPort }); + let heard = ""; + socket.once("connect", () => { + socket.write("from-caller"); + }); + socket.on("data", (chunk) => { + heard += chunk.toString("utf8"); + if (heard.includes("device-ok")) { + socket.destroy(); + resolve(heard); + } + }); + socket.once("close", () => { + if (heard.includes("device-ok")) return; + if (Date.now() > giveUp) { + reject(new Error(`no answer from the device server: ${heard}`)); + } else setTimeout(attempt, 250); + }); + socket.on("error", () => undefined); + }; + attempt(); + }); + expect(received).toBe("device-ok"); + await waitFor( + async () => { + const read = await leaseAdb(gateway, { agentId: "tunnel", leaseId }, [ + "shell", + `cat ${FORWARD_IN}`, + ]); + return read.stdout.includes("from-caller"); + }, + { + interval: 1_000, + label: "the device server receiving the caller's bytes", + timeout: 30_000, + }, + ); + server.kill("SIGINT"); + + tunnel.kill("SIGINT"); + expect((await tunnel.waitForExit(10_000)).code).toBe(0); + } finally { + await new Promise((resolve) => page.close(() => resolve())); + // why: a gateway refuses `nuke` (UNSUPPORTED_IN_GATEWAY_MODE); the worker owns the emulator, and one left running starves the next suite's boot. + await worker + ?.cli(["nuke", "--delete-devices", "--yes"], { timeout: 120_000 }) + .catch(() => undefined); + await Promise.allSettled([worker?.teardown(), gateway.teardown()]); + } + }, + ); + }, +); + +const ADB = join(ANDROID_HOME, "platform-tools", "adb"); + +// why: the worker runs its own adb server (`adbServerPort`), which the user's default server cannot see; the rules a tunnel set live there. +function workerAdb( + serverPort: number, + args: readonly string[], +): Promise<{ code: number; stdout: string }> { + return new Promise((resolve) => { + execFile(ADB, ["-P", String(serverPort), ...args], (error, stdout) => { + resolve({ + code: error === null ? 0 : typeof error.code === "number" ? error.code : 1, + stdout, + }); + }); + }); +} + +// why: a page that says it loaded and, when it is tapped anywhere, says so; each request comes back to the caller only through the reverse tunnel. +const TAP_PAGE = ` + +`; + +const CHROME = "com.android.chrome"; + +// why: a gateway relays a lease's input socket and tunnel socket to its worker side by side, and only a real emulator proves a relayed tap moves its screen and that a request it causes comes back through the relayed tunnel. +describe.skipIf(!hasAndroidSdk)( + "input and tunnel together on a real emulator through a gateway", + { tags: ["slow", "android"] }, + () => { + const gatewayPort = { value: 0 }; + let gateway: SharedTestEnv | undefined; + let worker: SharedTestEnv | undefined; + const lease = { deviceId: "", id: "", secret: "", serial: "" }; + + function onGateway(): SharedTestEnv { + if (gateway === undefined) throw new Error("the gateway did not start"); + return gateway; + } + + function onWorker(): SharedTestEnv { + if (worker === undefined) throw new Error("the worker did not start"); + return worker; + } + + function workerAdbPort(): number { + const port = worker?.adbServerPort; + if (port === undefined) throw new Error("the worker has no adb server of its own"); + return port; + } + + async function resumedActivity(): Promise { + const dump = await leaseAdb(onGateway(), { agentId: "input-tunnel", leaseId: lease.id }, [ + "shell", + "dumpsys activity activities | grep -E 'ResumedActivity'", + ]); + return dump.stdout; + } + + beforeAll(async () => { + gatewayPort.value = await freeLoopbackPort(); + gateway = await withSharedDaemon({ + configOverrides: { + capabilities: { input: { enabled: true }, tunnel: { enabled: true } }, + http: { enabled: true, host: "127.0.0.1", port: gatewayPort.value }, + }, + driver: "none", + role: "gateway", + }); + const joined = await gateway.cli(["token", "create", "--role", "worker"]); + expect(joined.code, joined.stderr).toBe(0); + worker = await withSharedDaemon({ + configOverrides: { + capabilities: { input: { enabled: true }, tunnel: { enabled: true } }, + gateway: { + label: "worker", + token: (joined.json as { secret: string }).secret, + url: `ws://127.0.0.1:${String(gatewayPort.value)}`, + }, + http: { enabled: false, host: "127.0.0.1", port: await freeLoopbackPort() }, + idle: { shutdownAfterMs: 300_000 }, + warmPool: { learn: false }, + }, + driver: "real", + }); + await waitForWorkerJoined(gateway); + const granted = await gateway.cli( + [ + "lease", + "--platform", + "android", + "--device", + "Pixel 9", + "--agent-id", + "input-tunnel", + "--detach", + ], + { timeout: DEVICE_READY_MS }, + ); + expect(granted.code, `lease failed: ${granted.stderr}`).toBe(0); + const grant = granted.json as { device: { driverDeviceId: string }; lease: { id: string } }; + lease.id = grant.lease.id; + lease.deviceId = grant.device.driverDeviceId; + const created = await gateway.cli(["token", "create", "--role", "operator"]); + expect(created.code, created.stderr).toBe(0); + lease.secret = (created.json as { secret: string }).secret; + // why: the worker's adb server can list more emulators than the leased one (a warm spare), so the serial comes from the lease's own passthrough, which aims adb at it. + const serial = await leaseAdb(gateway, { agentId: "input-tunnel", leaseId: lease.id }, [ + "get-serialno", + ]); + expect(serial.code, serial.stderr).toBe(0); + lease.serial = serial.stdout.trim(); + expect(lease.serial, serial.stdout).toMatch(/^emulator-\d+$/); + }, DEVICE_READY_MS + 120_000); + + afterAll(async () => { + await worker + ?.cli(["nuke", "--delete-devices", "--yes"], { timeout: 120_000 }) + .catch(() => undefined); + await Promise.allSettled([worker?.teardown(), gateway?.teardown()]); + }, 240_000); + + it( + "a home button sent on the input socket through a gateway takes a real emulator from Settings to its home screen", + { timeout: 180_000 }, + async () => { + const home = await leaseAdb(onGateway(), { agentId: "input-tunnel", leaseId: lease.id }, [ + "shell", + "cmd package resolve-activity --brief -a android.intent.action.MAIN -c android.intent.category.HOME | tail -n 1", + ]); + const launcher = home.stdout.trim().split("/")[0] ?? ""; + expect(launcher, home.stdout).toMatch(/^[a-z][\w.]+$/); + expect(launcher).not.toBe("com.android.settings"); + + const opened = await leaseAdb(onGateway(), { agentId: "input-tunnel", leaseId: lease.id }, [ + "shell", + "am start -W -a android.settings.SETTINGS", + ]); + expect(opened.code, opened.stderr).toBe(0); + await waitFor(async () => (await resumedActivity()).includes("com.android.settings"), { + interval: 1_000, + label: "Settings in the foreground", + timeout: 30_000, + }); + + const socket = await openInputSocket(gatewayPort.value, lease.id, lease.secret); + try { + await socket.waitForTag(0x83); + const config = (await socket.waitForTag(0x82)) as { + width: number; + inputUnavailable?: true; + }; + expect(config.inputUnavailable).toBeUndefined(); + expect(config.width).toBeGreaterThan(1); + socket.send(0x04, { button: "home" }); + let resumed = ""; + await waitFor( + async () => { + resumed = await resumedActivity(); + return resumed.includes(launcher) && !resumed.includes("com.android.settings"); + }, + { + interval: 1_000, + label: () => `the home screen in the foreground, resumed: ${resumed}`, + timeout: 30_000, + }, + ); + } finally { + socket.close(); + } + }, + ); + + it( + "a tap sent through a gateway on a page the emulator loaded through a reverse tunnel makes the page call the caller back through that tunnel, and once the lease is released under the open tunnel no reverse or forward rule is left for the emulator's serial", + { timeout: 300_000 }, + async () => { + const requests: string[] = []; + const page = createServer((request, response) => { + requests.push(request.url ?? ""); + response.writeHead(200, { "content-type": "text/html" }).end(TAP_PAGE); + }); + const pagePort = await freeLoopbackPort(); + await new Promise((resolve) => page.listen(pagePort, "127.0.0.1", resolve)); + const socket = await openInputSocket(gatewayPort.value, lease.id, lease.secret); + try { + const env = onGateway(); + const chrome = await leaseAdb(env, { agentId: "input-tunnel", leaseId: lease.id }, [ + "shell", + `pm path ${CHROME}`, + ]); + expect(chrome.stdout, "the emulator's image has no Chrome to open the page in").toContain( + "package:", + ); + // why: Chrome's first-run screens would cover the page; on an emulator image Chrome reads its flags from this file once it is the debug app. + for (const step of [ + `echo '_ --disable-fre --no-default-browser-check --no-first-run' > /data/local/tmp/chrome-command-line`, + `am set-debug-app --persistent ${CHROME}`, + `pm grant ${CHROME} android.permission.POST_NOTIFICATIONS`, + `am force-stop ${CHROME}`, + ]) { + await leaseAdb(env, { agentId: "input-tunnel", leaseId: lease.id }, ["shell", step]); + } + + const tunnel = env.cliBackground([ + "--token", + lease.secret, + "tunnel", + "reverse", + String(pagePort), + "--url", + `http://127.0.0.1:${String(gatewayPort.value)}`, + "--lease", + lease.id, + ]); + expect(await tunnel.firstStdoutLine(60_000)).toBe( + `reverse device:${String(pagePort)} -> localhost:${String(pagePort)} (lease ${lease.id})`, + ); + + const view = await leaseAdb(env, { agentId: "input-tunnel", leaseId: lease.id }, [ + "shell", + `am start -a android.intent.action.VIEW -d http://localhost:${String(pagePort)}/ -p ${CHROME}`, + ]); + expect(view.code, view.stderr).toBe(0); + await waitFor(() => requests.includes("/loaded"), { + interval: 500, + label: () => `the page loaded through the tunnel, requests: ${requests.join(" ")}`, + timeout: 90_000, + }); + expect(requests.some((url) => url.startsWith("/tapped"))).toBe(false); + + await socket.waitForTag(0x82); + await waitFor( + () => { + if (requests.some((url) => url.startsWith("/tapped"))) return true; + socket.send(0x03, { type: "begin", x: 0.5, y: 0.6 }); + socket.send(0x03, { type: "end", x: 0.5, y: 0.6 }); + return false; + }, + { + interval: 3_000, + label: () => `a tapped request through the tunnel, requests: ${requests.join(" ")}`, + timeout: 60_000, + }, + ); + + const rules = await workerAdb(workerAdbPort(), ["-s", lease.serial, "reverse", "--list"]); + expect(rules.stdout).toContain(`tcp:${String(pagePort)}`); + const ruleHostPort = await freeLoopbackPort(); + const made = await leaseAdb(env, { agentId: "input-tunnel", leaseId: lease.id }, [ + "forward", + `tcp:${String(ruleHostPort)}`, + `tcp:${String(pagePort)}`, + ]); + expect(made.code, made.stderr).toBe(0); + const listed = await workerAdb(workerAdbPort(), ["forward", "--list"]); + expect(listed.stdout).toContain(`${lease.serial} tcp:${String(ruleHostPort)}`); + const released = await env.cli(["release", lease.id]); + expect(released.code, released.stderr).toBe(0); + const ended = await tunnel.waitForExit(30_000); + expect(ended.code, ended.stderr).toBe(14); + expect(ended.error?.code).toBe("TUNNEL_LEASE_ENDED"); + + // why: release returns before the device's reclaim has run, and adb answers throughout it, so the rules are read once the device is ready again. + await waitForDeviceState(onWorker(), lease.deviceId, "ready", { timeout: 120_000 }); + let left = { forward: "", reverse: "" }; + await waitFor( + async () => { + const reverse = await workerAdb(workerAdbPort(), [ + "-s", + lease.serial, + "reverse", + "--list", + ]); + const forward = await workerAdb(workerAdbPort(), ["forward", "--list"]); + left = { + forward: forward.stdout + .split("\n") + .filter((line) => line.startsWith(`${lease.serial} `)) + .join("\n"), + reverse: reverse.stdout.trim(), + }; + return reverse.code === 0 && forward.code === 0; + }, + { + interval: 2_000, + label: "the emulator answering adb after its reclaim", + timeout: 120_000, + }, + ); + expect(left).toEqual({ forward: "", reverse: "" }); + } finally { + socket.close(); + await new Promise((resolve) => page.close(() => resolve())); + } + }, + ); + }, +); diff --git a/src/cli/AGENTS.md b/src/cli/AGENTS.md index 188504b0a..5df649082 100644 --- a/src/cli/AGENTS.md +++ b/src/cli/AGENTS.md @@ -96,12 +96,12 @@ Surface: [cli.mdx](../../website/src/content/docs/docs/reference/cli.mdx) — ev orientation, an unknown one is a usage error (exit 2); the lease is `--lease` (anywhere on the line) or the requester's only lease (`resolveRemoteLeaseId`); `device.rotate` answers, and the line printed is `Rotated lease to ` from the answer. Worker or gateway alike. - 5b. **`simlock tunnel reverse [:] … [--lease ] [--url ]`** — talks to a worker or gateway over + 5b. **`simlock tunnel reverse|forward [:] … [--lease ] [--url ]`** — talks to a worker or gateway over HTTP and a WebSocket, never the local daemon: `--url`/`SIMLOCK_URL` (`https://`, or `http://` on loopback only; the origin, no path, query or fragment) and `--token`/`SIMLOCK_TOKEN`. Without `--lease`, `GET /v1/identity` and `/v1/leases` pick an agent token's only lease (`selectOnlyLease`; an operator token must name one). One line per tunnel on `READY`; each `OPEN` connects to the caller's loopback port (no listener: `RESET` and a stderr warning per tunnel every 10 s), and `CREDIT` - flows both ways. Failures print one JSON line itself: a refused upgrade or `REFUSED` frame with the worker's code, + flows both ways. A `forward` tunnel binds its caller port (loopback, 1024 and up) through `tcpListeners` before anything else (busy: exit 1 `TUNNEL_CALLER_PORT_IN_USE`), holds accepted connections until `READY` (closed on `REFUSED`), opens each with an even-id `OPEN`, and closes every listener when the command ends. Failures print one JSON line itself: a refused upgrade or `REFUSED` frame with the worker's code, close 4001 exit 14 `TUNNEL_LEASE_ENDED`, a lost socket, 45 s of silence or 90 s without `READY` `TUNNEL_DISCONNECTED`. Ctrl-C and SIGTERM close the socket, wait at most 2 s, exit 0. `ws` loads on the first connect, for this command only. 6. **`simlock events --follow`** — subscribe, then replay, then print buffered pushes not diff --git a/src/cli/commands/tunnel.ts b/src/cli/commands/tunnel.ts index 13c0e3c9d..16dedd321 100644 --- a/src/cli/commands/tunnel.ts +++ b/src/cli/commands/tunnel.ts @@ -10,6 +10,7 @@ import { TUNNEL_WINDOW_BYTES, } from "../../contract/index.js"; import { + type TcpListener, type TcpStream, type TimerHandle, type WebSocketClient, @@ -20,6 +21,7 @@ import { selectOnlyLease } from "../remote-lease.js"; import type { CommandContext } from "../tree.js"; import type { CliEnvironment } from "../types.js"; +const FORWARD_CALLER_PORT_MIN = 1024; const HANDSHAKE_TIMEOUT_MS = 10_000; const CALLER_CONNECT_TIMEOUT_MS = 5_000; const CLOSE_NORMAL = 1000; @@ -28,7 +30,8 @@ const MAX_URL_CHARS = 2048; const MAX_TOKEN_CHARS = 4096; const MAX_LEASE_CHARS = 256; -interface ReverseSpec { +interface TunnelSpec { + readonly kind: "reverse" | "forward"; readonly devicePort: number; readonly callerPort: number; } @@ -41,27 +44,31 @@ function portOf(text: string, what: string): number { return port; } -function parseReverse(words: readonly string[], index: number): ReverseSpec { +function parseTunnel(words: readonly string[], index: number): TunnelSpec { const kind = words[index] as string; - if (kind !== "reverse") { - throw new UsageError(`Unknown tunnel kind "${kind}": only reverse is available`); + if (kind !== "reverse" && kind !== "forward") { + throw new UsageError(`Unknown tunnel kind "${kind}": use reverse or forward`); } const text = words[index + 1] ?? ""; const colon = text.indexOf(":"); const device = colon === -1 ? text : text.slice(0, colon); const devicePort = portOf(device, "device"); - return { - callerPort: portOf(colon === -1 ? device : text.slice(colon + 1), "caller"), - devicePort, - }; + const callerText = colon === -1 ? device : text.slice(colon + 1); + const callerPort = portOf(callerText, "caller"); + if (kind === "forward" && callerPort < FORWARD_CALLER_PORT_MIN) { + throw new UsageError( + `forward caller port "${callerText}" is below ${String(FORWARD_CALLER_PORT_MIN)}`, + ); + } + return { callerPort, devicePort, kind }; } -function parseReverses(words: readonly string[]): readonly ReverseSpec[] { +function parseTunnels(words: readonly string[]): readonly TunnelSpec[] { if (words.length === 0) { - throw new UsageError("Name at least one tunnel: reverse [:]"); + throw new UsageError("Name at least one tunnel: reverse|forward [:]"); } - const specs: ReverseSpec[] = []; - for (let index = 0; index < words.length; index += 2) specs.push(parseReverse(words, index)); + const specs: TunnelSpec[] = []; + for (let index = 0; index < words.length; index += 2) specs.push(parseTunnel(words, index)); if (specs.length > TUNNEL_MAX_TUNNELS) throw new UsageError(`At most ${String(TUNNEL_MAX_TUNNELS)} tunnels`); const callerPorts = specs.map(({ callerPort }) => callerPort); @@ -178,15 +185,7 @@ function relayConnections( new DataView(credit.buffer).setUint32(0, size); socket.send(encodeTunnelFrame(TUNNEL_TAG.credit, conn, credit)); }; - const openConnection = async (spec: ReverseSpec, conn: number): Promise => { - let stream: TcpStream; - try { - stream = await environment.tcpStreams.connect(spec.callerPort, CALLER_CONNECT_TIMEOUT_MS); - } catch { - warn(spec.devicePort, spec.callerPort); - socket.send(encodeTunnelFrame(TUNNEL_TAG.reset, conn)); - return; - } + const adopt = (conn: number, stream: TcpStream): void => { const relayed: Relayed = { stream, wake: undefined, @@ -196,6 +195,17 @@ function relayConnections( streams.set(conn, relayed); void pump(conn, relayed); }; + const openConnection = async (spec: TunnelSpec, conn: number): Promise => { + let stream: TcpStream; + try { + stream = await environment.tcpStreams.connect(spec.callerPort, CALLER_CONNECT_TIMEOUT_MS); + } catch { + warn(spec.devicePort, spec.callerPort); + socket.send(encodeTunnelFrame(TUNNEL_TAG.reset, conn)); + return; + } + adopt(conn, stream); + }; const onFrame = ( connection: Relayed, frame: { tag: number; conn: number; payload: Uint8Array }, @@ -222,7 +232,7 @@ function relayConnections( } }; const handle = async ( - spec: ReverseSpec | undefined, + spec: TunnelSpec | undefined, frame: { tag: number; conn: number; payload: Uint8Array }, ): Promise => { if (frame.tag === TUNNEL_TAG.open) { @@ -240,7 +250,13 @@ function relayConnections( wake?.(); } }; - return { closeAll, handle }; + return { adopt, closeAll, handle }; +} + +// why: a forward listener accepts at bind, before the lease and the socket exist, so its connections wait here until READY and the command closes what is left when it ends. +interface ForwardGate { + open: ((spec: TunnelSpec, stream: TcpStream) => void) | undefined; + readonly held: { spec: TunnelSpec; stream: TcpStream }[]; } const HELLO_TIMEOUT_MS = 90_000; @@ -359,7 +375,8 @@ function frameFailure(frame: { payload: Uint8Array }, leaseId: string): TunnelFa function serve( environment: CliEnvironment, socket: WebSocketClient, - specs: readonly ReverseSpec[], + specs: readonly TunnelSpec[], + gate: ForwardGate, leaseId: string, base: string, ): Promise { @@ -373,6 +390,19 @@ function serve( `reverse ${String(devicePort)}: nothing listening on localhost:${String(callerPort)}\n`, ); }); + let nextCallerConnection = 2; + const announce = (spec: TunnelSpec, stream: TcpStream): void => { + const conn = nextCallerConnection; + nextCallerConnection += 2; + socket.send( + encodeTunnelFrame( + TUNNEL_TAG.open, + conn, + JSON.stringify({ devicePort: spec.devicePort, kind: "forward" }), + ), + ); + relay.adopt(conn, stream); + }; // why: an OPEN waits for its loopback connect, and the DATA behind it must not overtake it, so frames are handled one at a time. let handled = Promise.resolve(); let socketClosed = false; @@ -398,6 +428,7 @@ function serve( environment.clock.cancel(helloTimer); if (silence !== undefined) environment.clock.cancel(silence); if (closeTimer !== undefined) environment.clock.cancel(closeTimer); + gate.open = undefined; relay.closeAll(); if (!socketClosed) { socket.close(CLOSE_NORMAL, ""); @@ -443,17 +474,23 @@ function serve( } if (frame.tag === TUNNEL_TAG.ready) { environment.clock.cancel(helloTimer); - for (const { callerPort, devicePort } of specs) { - environment.stdout.write( - `reverse device:${String(devicePort)} -> localhost:${String(callerPort)} (lease ${leaseId})\n`, - ); + gate.open = announce; + for (const { spec, stream } of gate.held.splice(0)) announce(spec, stream); + for (const { callerPort, devicePort, kind } of specs) { + const route = + kind === "reverse" + ? `reverse device:${String(devicePort)} -> localhost:${String(callerPort)}` + : `forward localhost:${String(callerPort)} -> device:${String(devicePort)}`; + environment.stdout.write(`${route} (lease ${leaseId})\n`); } return; } const opened = frame.tag === TUNNEL_TAG.open ? specs.find( - ({ devicePort }) => field(payloadJson(frame.payload), "devicePort") === devicePort, + ({ devicePort, kind }) => + kind === "reverse" && + field(payloadJson(frame.payload), "devicePort") === devicePort, ) : undefined; handled = handled.then(() => relay.handle(opened, frame)).catch(() => undefined); @@ -463,7 +500,7 @@ function serve( TUNNEL_TAG.hello, 0, JSON.stringify({ - tunnels: specs.map(({ devicePort }) => ({ devicePort, kind: "reverse" })), + tunnels: specs.map(({ devicePort, kind }) => ({ devicePort, kind })), }), ), ); @@ -481,24 +518,45 @@ async function run( }); if (help) { environment.stdout.write( - "Usage: simlock tunnel reverse [:] [reverse ...] [--lease ] [--url ]\n", + "Usage: simlock tunnel reverse|forward [:] [reverse|forward ...] [--lease ] [--url ]\n", ); return 0; } - const specs = parseReverses(positionals); + const specs = parseTunnels(positionals); const base = checkedUrl(typeof url === "string" ? url : environment.tunnelUrl); const secret = checkedToken(token ?? environment.tunnelToken); const named = checkedLease(typeof lease === "string" ? lease : undefined); + const listeners: TcpListener[] = []; + const gate: ForwardGate = { held: [], open: undefined }; try { + for (const spec of specs) { + if (spec.kind !== "forward") continue; + const listener = await environment.tcpListeners.listen(spec.callerPort); + if (listener === undefined) { + throw new TunnelFailure( + "TUNNEL_CALLER_PORT_IN_USE", + `forward ${String(spec.devicePort)}: localhost:${String(spec.callerPort)} is already in use`, + ERROR_TABLE.TUNNEL_CALLER_PORT_IN_USE.cliExitCode, + ); + } + listener.onConnection((stream) => { + if (gate.open === undefined) gate.held.push({ spec, stream }); + else gate.open(spec, stream); + }); + listeners.push(listener); + } const leaseId = await leaseToUse(environment, base, secret, named); const socket = await openSocket(environment, base, secret, leaseId); - return await serve(environment, socket, specs, leaseId, base); + return await serve(environment, socket, specs, gate, leaseId, base); } catch (error) { if (!(error instanceof TunnelFailure)) throw error; environment.stderr.write( `${JSON.stringify({ error: { code: error.code, message: error.message } })}\n`, ); return error.exitCode; + } finally { + await Promise.all(listeners.map((listener) => listener.close())); + for (const { stream } of gate.held.splice(0)) stream.close(); } } diff --git a/src/cli/environment.ts b/src/cli/environment.ts index e9e5b4230..98e1ac53e 100644 --- a/src/cli/environment.ts +++ b/src/cli/environment.ts @@ -282,6 +282,24 @@ function lazyNodeParentWatch(): ParentWatch { }; } +// why: each adapter loads on first use, so a command that never touches a TCP port loads none of them. +function tcpPorts(ports: CliEnvironmentPorts): Pick { + return { + tcpListeners: ports.tcpListeners ?? { + listen: async (port) => { + const { NodeTcpListenerFactory } = await import("../ports/index.js"); + return new NodeTcpListenerFactory().listen(port); + }, + }, + tcpStreams: ports.tcpStreams ?? { + connect: async (port, timeoutMs) => { + const { NodeTcpStreamConnector } = await import("../ports/index.js"); + return new NodeTcpStreamConnector().connect(port, timeoutMs); + }, + }, + }; +} + export function buildCliEnvironment( ports: CliEnvironmentPorts, env: NodeJS.ProcessEnv = process.env, @@ -419,12 +437,7 @@ export function buildCliEnvironment( return new FetchHttpJsonClient().get(url, token); }, }, - tcpStreams: ports.tcpStreams ?? { - connect: async (port, timeoutMs) => { - const { NodeTcpStreamConnector } = await import("../ports/index.js"); - return new NodeTcpStreamConnector().connect(port, timeoutMs); - }, - }, + ...tcpPorts(ports), ...(env.SIMLOCK_URL === undefined ? {} : { tunnelUrl: env.SIMLOCK_URL }), ...(env.SIMLOCK_TOKEN === undefined ? {} : { tunnelToken: env.SIMLOCK_TOKEN }), writeConfigFile: async (contents) => { diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 56a0aae0c..633965b40 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -41,6 +41,7 @@ import { import { FakeHttpJsonClient, FakeSystemStats, + FakeTcpListenerFactory, FakeTcpStreamConnector, FakeWebSocketClientConnector, } from "../ports/index.js"; @@ -8508,6 +8509,7 @@ function outputCapture(ports?: CliEnvironmentPorts, env: NodeJS.ProcessEnv = {}) confirm: async () => true, webSocket: new FakeWebSocketClientConnector(), httpJson: new FakeHttpJsonClient(), + tcpListeners: new FakeTcpListenerFactory(), tcpStreams: new FakeTcpStreamConnector(), ...overrides, }; diff --git a/src/cli/tunnel.test.ts b/src/cli/tunnel.test.ts index f4d0fc609..dd1cd4269 100644 --- a/src/cli/tunnel.test.ts +++ b/src/cli/tunnel.test.ts @@ -12,6 +12,7 @@ import { FakeDaemonLauncher, FakeHttpJsonClient, FakeSystemStats, + FakeTcpListenerFactory, FakeTcpPeer, FakeTcpStreamConnector, FakeWebSocketClientConnector, @@ -48,6 +49,7 @@ function command(env: NodeJS.ProcessEnv) { const httpJson = new FakeHttpJsonClient(); const clock = new FakeClock(0); const tcpStreams = new FakeTcpStreamConnector(); + const tcpListeners = new FakeTcpListenerFactory(); const environment = buildCliEnvironment( { clock, @@ -63,6 +65,7 @@ function command(env: NodeJS.ProcessEnv) { stderr: { write: (value) => err.push(value) }, stdout: { write: (value) => out.push(value) }, systemStats: new FakeSystemStats({ cpuCount: 2, totalRamBytes: 2 ** 30 }), + tcpListeners, tcpStreams, webSocket, workingDirectory: "/work", @@ -76,6 +79,7 @@ function command(env: NodeJS.ProcessEnv) { out, run: (argv: readonly string[]) => runCli(argv, environment), signals, + tcpListeners, tcpStreams, webSocket, }; @@ -110,6 +114,13 @@ describe("simlock tunnel that cannot run", () => { slashed.signals.emit("SIGINT"); expect(await slashedExit).toBe(0); + const floor = command(ENV); + const floorExit = floor.run(["tunnel", "forward", "9229:1024", "--lease", "L1"]); + await vi.waitFor(() => expect(floor.webSocket.connections).toHaveLength(1)); + expect(floor.tcpListeners.listeners.map((listener) => listener.port)).toEqual([1024]); + floor.signals.emit("SIGINT"); + expect(await floorExit).toBe(0); + const cases: readonly { readonly argv: readonly string[]; readonly env?: NodeJS.ProcessEnv; @@ -133,14 +144,29 @@ describe("simlock tunnel that cannot run", () => { argv: ["reverse", "5173:0"], message: 'caller port "0" is not an integer from 1 to 65535', }, - { argv: [], message: "Name at least one tunnel: reverse [:]" }, + { + argv: [], + message: "Name at least one tunnel: reverse|forward [:]", + }, { argv: ["reverse", "5173", "reverse", "6000:5173"], message: "Caller port 5173 is named by two tunnels", }, { - argv: ["forward", "5173"], - message: 'Unknown tunnel kind "forward": only reverse is available', + argv: ["forward", "9229:80"], + message: 'forward caller port "80" is below 1024', + }, + { + argv: ["forward", "9229:1023"], + message: 'forward caller port "1023" is below 1024', + }, + { + argv: ["reverse", "5173", "forward", "5173"], + message: "Caller port 5173 is named by two tunnels", + }, + { + argv: ["sideways", "5173"], + message: 'Unknown tunnel kind "sideways": use reverse or forward', }, { argv: ["--url", "http://10.0.0.5:7300", "reverse", "5173"], @@ -802,3 +828,111 @@ describe("simlock tunnel that is refused or loses its worker", () => { await sigterm(); }); }); + +describe("simlock tunnel forward listening on the caller's loopback", () => { + it("binds each caller port before HELLO, holds connections until READY, announces them with even ids and closes every listener however the command ends, and sends a device's OPEN to the reverse tunnel when a forward names the same device port", async () => { + const busy = command(ENV); + busy.tcpListeners.busy.add(9229); + expect(await busy.run(["tunnel", "forward", "9229", "--lease", "L1"])).toBe(1); + expect(line(busy)).toEqual( + errorBody("TUNNEL_CALLER_PORT_IN_USE", "forward 9229: localhost:9229 is already in use"), + ); + expect(busy.webSocket.connections).toEqual([]); + + const waiting = command(ENV); + const exit = waiting.run([ + "tunnel", + "forward", + "9229:19229", + "reverse", + "9229:5173", + "--lease", + "L1", + ]); + await vi.waitFor(() => expect(waiting.webSocket.connections).toHaveLength(1)); + const peer = firstPeer(waiting); + expect(waiting.tcpListeners.listeners.map((listener) => listener.port)).toEqual([19229]); + const early = waiting.tcpListeners.listeners[0]?.connect(); + await vi.waitFor(() => + expect(sentFrames(waiting).map((f) => f.tag)).toEqual([TUNNEL_TAG.hello]), + ); + expect(early?.closed).toBe(false); + peer.receive(READY); + await vi.waitFor(() => + expect(sentFrames(waiting).map((f) => [f.tag, f.conn])).toEqual([ + [TUNNEL_TAG.hello, 0], + [TUNNEL_TAG.open, 2], + ]), + ); + expect(JSON.parse(new TextDecoder().decode(sentFrames(waiting)[1]?.payload))).toEqual({ + devicePort: 9229, + kind: "forward", + }); + waiting.tcpListeners.listeners[0]?.connect(); + await vi.waitFor(() => expect(sentFrames(waiting).at(-1)?.conn).toBe(4)); + peer.receive(open(1, 9229)); + await vi.waitFor(() => expect(waiting.tcpStreams.connections).toHaveLength(1)); + expect(waiting.tcpStreams.connections[0]?.port).toBe(5173); + waiting.signals.emit("SIGINT"); + expect(await exit).toBe(0); + + const refusedEarly = command(ENV); + const refusedExit = refusedEarly.run(["tunnel", "forward", "9229", "--lease", "L1"]); + await vi.waitFor(() => expect(refusedEarly.webSocket.connections).toHaveLength(1)); + const queued = refusedEarly.tcpListeners.listeners[0]?.connect(); + refusedEarly.webSocket.connections[0]?.peer.receive( + refusedFrame("TUNNEL_BAD_PORT", "Device port 80 is below 1024"), + ); + expect(await refusedExit).toBe(1); + expect(queued?.closed).toBe(true); + expect(sentFrames(refusedEarly).map((f) => f.tag)).toEqual([TUNNEL_TAG.hello]); + + const slow = command(ENV); + let releaseLookup: () => void = () => undefined; + const lookup = new Promise((resolve) => { + releaseLookup = resolve; + }); + slow.httpJson.get = async () => { + await lookup; + throw new Error("the worker is unreachable"); + }; + const slowExit = slow.run(["tunnel", "forward", "9229"]); + await vi.waitFor(() => expect(slow.tcpListeners.listeners).toHaveLength(1)); + const beforeSocket = slow.tcpListeners.listeners[0]?.connect(); + expect(beforeSocket?.closed).toBe(false); + releaseLookup(); + expect(await slowExit).toBe(1); + expect(beforeSocket?.closed).toBe(true); + + const endings: readonly ((cli: ReturnType, peer: Peer) => void)[] = [ + (cli) => cli.signals.emit("SIGINT"), + (_cli, ended) => ended.receive(refusedFrame("TUNNEL_BAD_PORT", "no")), + (_cli, ended) => ended.dropped(4001, "device released"), + (_cli, ended) => ended.dropped(1006, ""), + ]; + for (const ending of endings) await listenersCloseAfter(ending); + }); +}); + +function firstPeer(cli: ReturnType): Peer { + const peer = cli.webSocket.connections[0]?.peer; + if (peer === undefined) throw new Error("no socket"); + return peer; +} + +async function listenersCloseAfter( + ending: (cli: ReturnType, peer: Peer) => void, +): Promise { + const cli = command(ENV); + const run = cli.run(["tunnel", "forward", "9229", "forward", "9230", "--lease", "L1"]); + await vi.waitFor(() => expect(cli.webSocket.connections).toHaveLength(1)); + const connection = firstPeer(cli); + connection.silentOnClose = true; + expect(cli.tcpListeners.listeners.map((listener) => listener.closed)).toEqual([false, false]); + ending(cli, connection); + cli.clock.advance(2_000); + await run; + expect(cli.tcpListeners.listeners.map((listener) => listener.closed)).toEqual([true, true]); +} + +type Peer = ReturnType["webSocket"]["connections"][number]["peer"]; diff --git a/src/cli/types.ts b/src/cli/types.ts index 58416bb7c..726a19680 100644 --- a/src/cli/types.ts +++ b/src/cli/types.ts @@ -16,6 +16,7 @@ import type { ServiceDefinition, ServiceManager, SystemStats, + TcpListenerFactory, TcpStreamConnector, WebSocketClientConnector, } from "../ports/index.js"; @@ -98,6 +99,8 @@ export interface CliEnvironment { readonly webSocket: WebSocketClientConnector; readonly httpJson: HttpJsonClient; readonly tcpStreams: TcpStreamConnector; + /** why: a `forward` tunnel listens on the caller's loopback port; the adapter loads on first use. */ + readonly tcpListeners: TcpListenerFactory; /** why: `SIMLOCK_URL` and `SIMLOCK_TOKEN` name the daemon `simlock tunnel` calls and the credential it sends. */ readonly tunnelUrl?: string; readonly tunnelToken?: string; @@ -128,4 +131,5 @@ export interface CliEnvironmentPorts { readonly webSocket?: WebSocketClientConnector; readonly httpJson?: HttpJsonClient; readonly tcpStreams?: TcpStreamConnector; + readonly tcpListeners?: TcpListenerFactory; } diff --git a/src/core/device-tcp.ts b/src/core/device-tcp.ts index 790f00651..7352d737a 100644 --- a/src/core/device-tcp.ts +++ b/src/core/device-tcp.ts @@ -44,4 +44,10 @@ export interface DeviceTcp { devicePort: number, signal: AbortSignal, ): Promise; + // why: one connection from the worker to a device port, through the host protocol with no `adb forward` rule; a port with nothing listening rejects with a `DeviceTcpError` whose message is the reason the holder's connection is reset. + connect( + device: VirtualDriverDevice | PhysicalDriverDevice, + devicePort: number, + signal: AbortSignal, + ): Promise; } diff --git a/src/core/driver-catalog.ts b/src/core/driver-catalog.ts index 388655493..b97514756 100644 --- a/src/core/driver-catalog.ts +++ b/src/core/driver-catalog.ts @@ -1,4 +1,4 @@ -import { type Logger, NoopLogger } from "../ports/index.js"; +import { type Logger, NoopLogger, type TcpStream } from "../ports/index.js"; import { classCandidates, pairedRuntimes } from "./catalog-match.js"; import { DEVICE_CLASSES, type DeviceClass, type VirtualSpec, type Platform } from "./domain.js"; import type { @@ -126,6 +126,22 @@ export class DriverCatalog { return await deviceTcp.reverse(device, devicePort, signal); } + async connectDevicePort( + platform: Platform, + device: VirtualDriverDevice | PhysicalDriverDevice, + devicePort: number, + signal: AbortSignal, + ): Promise { + const deviceTcp = this.#drivers.get(platform)?.deviceTcp; + if (deviceTcp === undefined) { + throw new DeviceTcpError( + "TUNNEL_UNSUPPORTED", + unsupportedTunnelMessage(platform, device.physical), + ); + } + return await deviceTcp.connect(device, devicePort, signal); + } + async screenAvailability(): Promise { return await Promise.all( [...this.#drivers.values()].flatMap((driver) => diff --git a/src/core/fake-device-tcp.ts b/src/core/fake-device-tcp.ts index b15529e15..d94b1a9c7 100644 --- a/src/core/fake-device-tcp.ts +++ b/src/core/fake-device-tcp.ts @@ -1,5 +1,10 @@ import { FakeTcpPeer, type TcpStream } from "../ports/index.js"; -import type { DeviceReverse, DeviceTcp, SweptDevice } from "./device-tcp.js"; +import { + DeviceTcpError, + type DeviceReverse, + type DeviceTcp, + type SweptDevice, +} from "./device-tcp.js"; class FakeReverse implements DeviceReverse { closed = false; @@ -30,7 +35,8 @@ class FakeReverse implements DeviceReverse { } // why: a driver's `deviceTcp` member for tests: `reversed` holds the device ports whose rule is set, -// and `connect` plays the device opening a connection to one of them. +// `openFromDevice` plays the device opening a connection to one of them, and `listening` holds the +// device ports a `connect` from the worker reaches, each answered by a peer in `connections`. export class FakeDeviceTcp implements DeviceTcp { // why: a test sets this to make every rule removal fail, as an adb that does not answer does. closeFailure: Error | undefined; @@ -46,6 +52,10 @@ export class FakeDeviceTcp implements DeviceTcp { readonly sweeps: (readonly SweptDevice[])[] = []; // why: a test sets this to hold every `sweep` until it settles, as an adb call that is slow to answer does. sweepGate: Promise | undefined; + // why: a test sets a device port's failure to make its `connect` refuse with that error, as a device that never answers does. + readonly connectFailures = new Map(); + readonly listening = new Set(); + readonly connections: { readonly devicePort: number; readonly peer: FakeTcpPeer }[] = []; readonly #reverses = new Map(); #nextHostPort = 47_000; @@ -85,7 +95,16 @@ export class FakeDeviceTcp implements DeviceTcp { return reverse; } - connect(devicePort: number): FakeTcpPeer { + async connect(_device: unknown, devicePort: number, _signal?: AbortSignal): Promise { + const failure = this.connectFailures.get(devicePort); + if (failure !== undefined) throw failure; + if (!this.listening.has(devicePort)) throw new DeviceTcpError("TUNNEL_FAILED", "closed"); + const peer = new FakeTcpPeer(); + this.connections.push({ devicePort, peer }); + return peer.stream; + } + + openFromDevice(devicePort: number): FakeTcpPeer { const peer = new FakeTcpPeer(); this.#reverses.get(devicePort)?.accept(peer.stream); return peer; diff --git a/src/daemon/main.ts b/src/daemon/main.ts index f6aff37ce..fd2cc9366 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -524,6 +524,8 @@ async function composeDaemon( processSupervisor, registry, deviceTcp: { + connect: (platform, device, devicePort, signal) => + catalog.connectDevicePort(platform, device, devicePort, signal), supports: (platform, device) => catalog.supportsDeviceTcp(platform, device), reverse: (platform, device, devicePort, signal) => catalog.reverseDevicePort(platform, device, devicePort, signal), diff --git a/src/daemon/tunnel-cli.e2e.test.ts b/src/daemon/tunnel-cli.e2e.test.ts index 9511c5a77..167025af2 100644 --- a/src/daemon/tunnel-cli.e2e.test.ts +++ b/src/daemon/tunnel-cli.e2e.test.ts @@ -1,5 +1,5 @@ import { mkdtemp, rm } from "node:fs/promises"; -import { createServer, type Server, type Socket } from "node:net"; +import { connect, createServer, type Server, type Socket } from "node:net"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -182,7 +182,7 @@ describe("simlock tunnel against a lone worker", () => { ); expect(lone.deviceTcp.reversed).toEqual([5173]); - const peer = lone.deviceTcp.connect(5173); + const peer = lone.deviceTcp.openFromDevice(5173); peer.send("from-device"); await vi.waitFor(() => expect(received.join("")).toBe("from-device"), { timeout: 10_000 }); await vi.waitFor(() => expect(peer.writtenText()).toBe("from-caller"), { timeout: 10_000 }); @@ -204,4 +204,68 @@ describe("simlock tunnel against a lone worker", () => { }, }); }); + + async function callerClient(port: number, received: string[]): Promise { + const socket = connect({ host: "127.0.0.1", port }); + sockets.push(socket); + socket.on("error", () => undefined); + socket.on("data", (chunk) => received.push(chunk.toString("utf8"))); + await new Promise((resolve, reject) => { + socket.once("connect", resolve); + socket.once("error", reject); + }); + return socket; + } + + it("a user runs simlock tunnel forward and the caller's loopback port reaches the device port", async () => { + const lone = await worker(); + lone.deviceTcp.listening.add(9229); + const callerPort = await freeLoopbackPort(); + const closedPort = await freeLoopbackPort(); + const cli = command({ SIMLOCK_TOKEN: lone.token, SIMLOCK_URL: lone.url }); + + const exit = cli.run([ + "tunnel", + "forward", + `9229:${String(callerPort)}`, + "forward", + `9230:${String(closedPort)}`, + ]); + await vi.waitFor(() => expect(cli.out.join("")).not.toBe(""), { timeout: 10_000 }); + expect(cli.out.join("")).toBe( + `forward localhost:${String(callerPort)} -> device:9229 (lease ${lone.leaseId}) +forward localhost:${String(closedPort)} -> device:9230 (lease ${lone.leaseId}) +`, + ); + + const received: string[] = []; + const client = await callerClient(callerPort, received); + client.write("from-caller"); + await vi.waitFor(() => expect(lone.deviceTcp.connections).toHaveLength(1), { + timeout: 10_000, + }); + const device = lone.deviceTcp.connections[0]; + expect(device?.devicePort).toBe(9229); + await vi.waitFor(() => expect(device?.peer.writtenText()).toBe("from-caller"), { + timeout: 10_000, + }); + device?.peer.send("from-device"); + await vi.waitFor(() => expect(received.join("")).toBe("from-device"), { timeout: 10_000 }); + + expect(device?.peer.writeEnded).toBe(false); + client.end(); + await vi.waitFor(() => expect(device?.peer.writeEnded).toBe(true), { timeout: 10_000 }); + expect(client.readyState).not.toBe("closed"); + device?.peer.end(); + await vi.waitFor(() => expect(client.readyState).toBe("closed"), { timeout: 10_000 }); + + const refused = await callerClient(closedPort, []); + await vi.waitFor(() => expect(refused.readyState).toBe("closed"), { timeout: 10_000 }); + expect(lone.deviceTcp.connections).toHaveLength(1); + + cli.signals.emit("SIGINT"); + expect(await exit).toBe(0); + expect(cli.err.join("")).toBe(""); + await expect(callerClient(callerPort, [])).rejects.toMatchObject({ code: "ECONNREFUSED" }); + }); }); diff --git a/src/daemon/tunnel-lease.e2e.test.ts b/src/daemon/tunnel-lease.e2e.test.ts index d39cb65c4..3a0adb3cf 100644 --- a/src/daemon/tunnel-lease.e2e.test.ts +++ b/src/daemon/tunnel-lease.e2e.test.ts @@ -6,8 +6,14 @@ import { join } from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; import { WebSocket } from "ws"; -import { FakeDeviceTcp, FakeDriver, fakeDeviceDataTables } from "../core/testing.js"; -import { MemoryFilesystem, NoopLogger, SystemClock } from "../ports/index.js"; +import { encodeTunnelFrame, TUNNEL_TAG } from "../contract/index.js"; +import { + FakeDeviceTcp, + FakeDriver, + FakeInputFactory, + fakeDeviceDataTables, +} from "../core/testing.js"; +import { FakeClock, MemoryFilesystem, NoopLogger, SystemClock } from "../ports/index.js"; import type { DispatchSession } from "./dispatch.js"; import { startDaemon } from "./main.js"; import type { DaemonServer } from "./server.js"; @@ -90,6 +96,16 @@ async function openTunnel(url: string, token: string | undefined): Promise { async function fleet(options: { readonly gatewayTunnel: boolean; readonly workerTunnel: boolean; + // why: given, the input module is on at both ends and the worker's device input is this fake. + readonly input?: FakeInputFactory; + readonly clock?: FakeClock; }) { const port = await freeLoopbackPort(); + const input = { enabled: options.input !== undefined }; + const clock = options.clock === undefined ? {} : { clock: options.clock }; const gateway = await startDaemon({ + ...clock, configOverrides: { - capabilities: { tunnel: { enabled: options.gatewayTunnel } }, + capabilities: { input, tunnel: { enabled: options.gatewayTunnel } }, http: { enabled: true, host: "127.0.0.1", port }, }, dataDirectory: await directory("gateway"), @@ -180,14 +202,16 @@ describe("a lease's tunnel socket", () => { .secret; const deviceTcp = new FakeDeviceTcp(); const worker = await startDaemon({ + ...clock, configOverrides: { - capabilities: { tunnel: { enabled: options.workerTunnel } }, + capabilities: { input, tunnel: { enabled: options.workerTunnel } }, gateway: { label: "w", token, url: `ws://127.0.0.1:${String(port)}` }, }, dataDirectory: await directory("worker"), deviceDataTables: fakeDeviceDataTables, drivers: [ new FakeDriver({ + ...(options.input === undefined ? {} : { input: options.input }), availableOsVersions: ["18.0"], clock: new SystemClock(), deviceTcp, @@ -226,6 +250,7 @@ describe("a lease's tunnel socket", () => { deviceTcp, gateway, holder: holder.secret, + inputUrl: `ws://127.0.0.1:${String(port)}/v1/leases/${leaseId}/input`, leaseId, owner: { ...agent, principal: holder.token.id }, url: (id = leaseId) => `ws://127.0.0.1:${String(port)}/v1/leases/${id}/tunnel`, @@ -282,7 +307,7 @@ describe("a lease's tunnel socket", () => { const carried = await openTunnel(through.url(), through.holder); carried.socket.send(hello(5174)); await vi.waitFor(() => expect(carried.messages).toHaveLength(1), { timeout: 10_000 }); - const device = through.deviceTcp.connect(5174); + const device = through.deviceTcp.openFromDevice(5174); await vi.waitFor(() => expect(carried.messages).toHaveLength(2), { timeout: 10_000 }); expect(carried.messages[1]?.[0]).toBe(0x02); device.send(new Uint8Array(65_536).fill(7)); @@ -345,8 +370,156 @@ describe("a lease's tunnel socket", () => { () => expect(viaGateway.closed).toEqual({ code: 1001, reason: "Simlock is stopping" }), { timeout: 10_000 }, ); + }, + ); + + async function inputAdmitted(url: string, token: string): Promise { + const opened = await openTunnel(url, token); + expect(opened.status).toBe(101); + await vi.waitFor(() => expect(opened.messages.map((entry) => entry[0])).toEqual([0x83, 0x82]), { + timeout: 10_000, + }); + return opened; + } + + async function tunnelReady( + url: string, + token: string, + devicePort: number, + ): Promise { + const opened = await openTunnel(url, token); + expect(opened.status).toBe(101); + opened.socket.send(hello(devicePort)); + await vi.waitFor(() => expect(opened.messages.map((entry) => entry[0])).toEqual([0x81]), { + timeout: 10_000, + }); + return opened; + } - const workerOff = await fleet({ gatewayTunnel: true, workerTunnel: false }); + it( + "carries a holder's taps in order and 1 MiB each way through a reverse tunnel intact, on one lease through a gateway at once", + { timeout: 60_000 }, + async () => { + const input = new FakeInputFactory({ height: 2400, orientation: "portrait", width: 1080 }); + const both = await fleet({ gatewayTunnel: true, input, workerTunnel: true }); + const tunnel = await tunnelReady(both.url(), both.holder, 5173); + const taps = await inputAdmitted(both.inputUrl, both.holder); + + const device = both.deviceTcp.openFromDevice(5173); + await vi.waitFor(() => expect(tunnel.messages[1]?.[0]).toBe(TUNNEL_TAG.open), { + timeout: 10_000, + }); + const conn = tunnel.messages[1]?.readUInt32BE(1) ?? 0; + const fromDevice: Buffer[] = []; + const granted = { bytes: 262_144 }; + tunnel.socket.on("message", (data: Buffer) => { + if (data.readUInt32BE(1) !== conn) return; + if (data[0] === TUNNEL_TAG.data) { + fromDevice.push(data.subarray(5)); + const credit = Buffer.alloc(4); + credit.writeUInt32BE(data.length - 5); + tunnel.socket.send(encodeTunnelFrame(TUNNEL_TAG.credit, conn, credit)); + } + if (data[0] === TUNNEL_TAG.credit) granted.bytes += data.readUInt32BE(5); + }); + + const chunk = 65_536; + const toCaller = pattern(16 * chunk, 7); + const toDevice = pattern(16 * chunk, 13); + for (let at = 0; at < toCaller.length; at += chunk) { + device.send(toCaller.subarray(at, at + chunk)); + } + const sentTaps: unknown[] = []; + for (let index = 0; index < 16; index += 1) { + await vi.waitFor(() => expect(granted.bytes).toBeGreaterThanOrEqual(chunk), { + timeout: 10_000, + }); + granted.bytes -= chunk; + const at = index * chunk; + tunnel.socket.send( + encodeTunnelFrame(TUNNEL_TAG.data, conn, toDevice.subarray(at, at + chunk)), + ); + for (const touch of [ + { type: "begin", x: index / 16, y: 0.25 }, + { type: "end", x: index / 16, y: 0.75 }, + ]) { + taps.socket.send(inputMessage(0x03, touch)); + sentTaps.push({ kind: "touch", ...touch }); + } + } + + await vi.waitFor(() => expect(Buffer.concat(fromDevice).length).toBe(toCaller.length), { + timeout: 20_000, + }); + expect(Buffer.concat(fromDevice).equals(toCaller)).toBe(true); + await vi.waitFor(() => expect(Buffer.concat(device.written).length).toBe(toDevice.length), { + timeout: 20_000, + }); + expect(Buffer.concat(device.written).equals(toDevice)).toBe(true); + await vi.waitFor(() => expect(input.opened[0]?.sent).toHaveLength(32), { timeout: 10_000 }); + expect(input.opened[0]?.sent).toEqual(sentTaps); + expect([tunnel.closed, taps.closed]).toEqual([undefined, undefined]); + }, + ); + + it( + "closes a lease's input and tunnel sockets through a gateway 4001 with the worker's reason when it is released, its reverse rule gone when the release returns, and 1011 when the worker stops, with its rule and device input let go", + { timeout: 60_000 }, + async () => { + const endingInput = new FakeInputFactory({ + height: 2400, + orientation: "portrait", + width: 1080, + }); + const ends = await fleet({ gatewayTunnel: true, input: endingInput, workerTunnel: true }); + const endingTunnel = await tunnelReady(ends.url(), ends.holder, 5173); + const endingTaps = await inputAdmitted(ends.inputUrl, ends.holder); + expect(ends.deviceTcp.reversed).toEqual([5173]); + await ends.gateway.dispatch("lease.release", { leaseId: ends.leaseId }, ends.owner); + expect(ends.deviceTcp.reversed).toEqual([]); + for (const socket of [endingTunnel, endingTaps]) { + await vi.waitFor(() => expect(socket.closed).toEqual({ code: 4001, reason: "explicit" }), { + timeout: 10_000, + }); + } + + const stoppingInput = new FakeInputFactory({ + height: 2400, + orientation: "portrait", + width: 1080, + }); + const stopping = await fleet({ + gatewayTunnel: true, + input: stoppingInput, + workerTunnel: true, + }); + const tunnel = await tunnelReady(stopping.url(), stopping.holder, 5173); + const taps = await inputAdmitted(stopping.inputUrl, stopping.holder); + expect(stoppingInput.opened[0]?.closes).toBe(0); + const { workers } = await stopping.gateway.dispatch("worker.list", {}, admin); + await stopping.worker.stop("test"); + expect(stopping.deviceTcp.reversed).toEqual([]); + expect(stoppingInput.opened[0]?.closes).toBe(1); + const gone = { code: 1011, reason: `Worker ${workers[0]?.id ?? ""} stopped answering` }; + for (const socket of [tunnel, taps]) { + await vi.waitFor(() => expect(socket.closed).toEqual(gone), { timeout: 10_000 }); + expect(socket.socket.readyState).toBe(WebSocket.CLOSED); + } + }, + ); + + it( + "carries input through a gateway to a worker with tunnels off, and answers that worker's tunnel upgrade 503 TUNNEL_UNAVAILABLE", + { timeout: 60_000 }, + async () => { + const input = new FakeInputFactory({ height: 2400, orientation: "portrait", width: 1080 }); + const workerOff = await fleet({ gatewayTunnel: true, input, workerTunnel: false }); + const taps = await inputAdmitted(workerOff.inputUrl, workerOff.holder); + taps.socket.send(inputMessage(0x04, { button: "home" })); + await vi.waitFor( + () => expect(input.opened[0]?.sent).toEqual([{ button: "home", kind: "button" }]), + { timeout: 10_000 }, + ); const refused = await openTunnel(workerOff.url(), workerOff.holder); expect({ code: refused.code, status: refused.status }).toEqual({ code: "TUNNEL_UNAVAILABLE", @@ -355,6 +528,26 @@ describe("a lease's tunnel socket", () => { }, ); + it( + "keeps a quiet tunnel through a gateway open past the relay's 15 s silence bound, and a device connection still reaches the holder", + { timeout: 60_000 }, + async () => { + const clock = new FakeClock(); + const quiet = await fleet({ clock, gatewayTunnel: true, workerTunnel: true }); + const tunnel = await tunnelReady(quiet.url(), quiet.holder, 5173); + for (let second = 0; second < 20; second += 1) { + clock.advance(1_000); + await new Promise((resolve) => setTimeout(resolve, 20)); + } + expect(tunnel.closed).toBeUndefined(); + quiet.deviceTcp.openFromDevice(5173); + await vi.waitFor(() => expect(tunnel.messages.at(-1)?.[0]).toBe(TUNNEL_TAG.open), { + timeout: 10_000, + }); + expect(tunnel.closed).toBeUndefined(); + }, + ); + it( "sweeps each platform's driver at start with its devices, a leased one marked leased, before any request is served", { timeout: 120_000 }, diff --git a/src/drivers/android/AGENTS.md b/src/drivers/android/AGENTS.md index 6fd3668a0..6da184cae 100644 --- a/src/drivers/android/AGENTS.md +++ b/src/drivers/android/AGENTS.md @@ -114,7 +114,7 @@ Lease environment: virtual `ANDROID_ADB_SERVER_PORT=`; physical `ANDROID_A No slim: `resolveSpec` ignores `mode` and returns a full spec. `fresh` is core's. Screen — `screenCapture` and `input`, only when `create` got `scrcpyServerPath` and `tcpStreamConnector`: [screen](screen/AGENTS.md), [input](input/AGENTS.md). -Tunnels — `deviceTcp` (`device-tcp.ts`), only when `create` got `tcpListener`: `reverse` listens on a free loopback port in 47000-47999 (busy ones skipped; none free → `TUNNEL_FAILED`) and runs `adb reverse --no-rebind tcp: tcp:` on the device's own server (an emulator's on Simlock's port, a phone's on 5037 behind the gate), 10 s per call; `cannot rebind existing socket` → `TUNNEL_PORT_IN_USE`, any other failure → `TUNNEL_FAILED` (message cut to 200 characters). `close` removes the rule, then the listener; a removal that fails keeps the listener, closing every connection at once, and the driver's `reclaim` of that device frees every port still held for it (`release`) once its rules are gone; a phone's reclaim reads its `reverse --list` first and frees only the ports no rule there points to (a failed read frees none). The refusal messages name the call (`reverse : the device port is already reversed; remove that rule first`, `reverse : `). Cleanup: reclaim (with or without `tcpListener`) of an emulator once its ownership probe passed runs `reverse --remove-all` and removes this serial's `forward --list` lines one by one with `forward --remove ` (never `--remove-all`); an emulator not proved its own is left alone, and a phone's reclaim runs neither (safety rule 1: only the tunnel's own `reverse --remove` at socket close touches a phone). `deviceTcp.sweep` (only with `tcpListener`), called by the daemon before any request is served, removes on every present idle owned emulator the `reverse --list` rules whose host side is `tcp:47000`-`tcp:47999`; on a leased emulator it removes nothing and keeps the ports those rules point to from the next `reverse` until its reclaim; on a phone, idle or leased, it only reads the rules and keeps those ports the same way. A failed removal is a `warn`; reclaim and start go on. +Tunnels — `deviceTcp` (`device-tcp.ts`), only when `create` got `tcpListener`: `reverse` listens on a free loopback port in 47000-47999 (busy ones skipped; none free → `TUNNEL_FAILED`) and runs `adb reverse --no-rebind tcp: tcp:` on the device's own server (an emulator's on Simlock's port, a phone's on 5037 behind the gate), 10 s per call; `cannot rebind existing socket` → `TUNNEL_PORT_IN_USE`, any other failure → `TUNNEL_FAILED` (message cut to 200 characters). `connect` (needs `tcpStreamConnector`, else `TUNNEL_FAILED`) opens `tcp:` through `openDeviceSocket` on the screen's target, with no `adb forward`: an emulator's configured server port, a phone's 5037 behind the gate (a closed gate rejects with its message); both answers share 5 s, then `timeout`, and `FAIL` rejects with its reason. `close` removes the rule, then the listener; a removal that fails keeps the listener, closing every connection at once, and the driver's `reclaim` of that device frees every port still held for it (`release`) once its rules are gone; a phone's reclaim reads its `reverse --list` first and frees only the ports no rule there points to (a failed read frees none). The refusal messages name the call (`reverse : the device port is already reversed; remove that rule first`, `reverse : `). Cleanup: reclaim (with or without `tcpListener`) of an emulator once its ownership probe passed runs `reverse --remove-all` and removes this serial's `forward --list` lines one by one with `forward --remove ` (never `--remove-all`); an emulator not proved its own is left alone, and a phone's reclaim runs neither (safety rule 1: only the tunnel's own `reverse --remove` at socket close touches a phone). `deviceTcp.sweep` (only with `tcpListener`), called by the daemon before any request is served, removes on every present idle owned emulator the `reverse --list` rules whose host side is `tcp:47000`-`tcp:47999`; on a leased emulator it removes nothing and keeps the ports those rules point to from the next `reverse` until its reclaim; on a phone, idle or leased, it only reads the rules and keeps those ports the same way. A failed removal is a `warn`; reclaim and start go on. Plain facts: `listCatalog`, a resolve of a model the library lacks and a library provision (seed) share one `AvdmanagerDeviceList`: `avdmanager list device` runs again only when the size or modified time of a file it reads profiles from changed, or one appeared or went: the tools package's `lib/sdklib/sdklib.core.jar` (legacy `tools/lib/sdklib*.jar`) and `source.properties`, the user's devices.xml, `devices.xml` in each `system-images/*/*/*` and `add-ons/*` directory (a new image is a new path), and `devices.xml` and `source.properties` in each `extras/*/*` directory (avdmanager reads an extra whose `source.properties` says `Extra.Path=DeviceProfiles`). Otherwise the last good answer is served; a failed run is not kept; concurrent callers share one run. The sdkmanager catalog is never read. Existing devices are not re-checked for fit. diff --git a/src/drivers/android/device-tcp.ts b/src/drivers/android/device-tcp.ts index 72576fabb..1f391796c 100644 --- a/src/drivers/android/device-tcp.ts +++ b/src/drivers/android/device-tcp.ts @@ -1,3 +1,4 @@ +import { type ChunkReader, openDeviceSocket } from "./screen/index.js"; import { DeviceTcpError, type DeviceReverse, @@ -7,6 +8,7 @@ import { type VirtualDriverDevice, } from "../../core/index.js"; import type { + Clock, ProcessResult, TcpListener, TcpListenerFactory, @@ -18,11 +20,17 @@ const TUNNEL_PORT_FIRST = 47_000; const TUNNEL_PORT_LAST = 47_999; const ADB_TIMEOUT_MS = 10_000; +const CONNECT_TIMEOUT_MS = 5_000; const MESSAGE_LIMIT = 200; const CANNOT_REBIND = "cannot rebind existing socket"; export interface AndroidDeviceTcpOptions { readonly listeners: TcpListenerFactory; + readonly clock: Clock; + // why: the driver decides which adb server a device is reached through, and for a phone which check it passes first; a target without a connector cannot open a device port. + readonly target: + | ((device: VirtualDriverDevice | PhysicalDriverDevice) => Promise) + | undefined; // why: a sweep acts on a device only once the driver proved it Simlock's own; an emulator on a recorded serial may answer as another's (#284). readonly isOwn: (device: VirtualDriverDevice) => Promise; readonly warn: (message: string, detail: Record) => void; @@ -34,6 +42,34 @@ export interface AndroidDeviceTcpOptions { ) => Promise; } +interface DeviceSocketTarget { + readonly serial: string; + connect(timeoutMs: number): Promise; +} + +// why: `openDeviceSocket` read the adb reply through a reader that may already hold the first bytes of the device's answer, so the stream handed on reads through it. +function streamThrough(stream: TcpStream, reader: ChunkReader): TcpStream { + return { + close: () => { + stream.close(); + }, + end: () => { + stream.end(); + }, + readable: new ReadableStream({ + cancel: () => { + stream.close(); + }, + pull: async (controller) => { + const chunk = await reader.read(); + if (chunk === undefined) controller.close(); + else controller.enqueue(chunk); + }, + }), + write: (bytes) => stream.write(bytes), + }; +} + function cut(message: string): string { return message.length > MESSAGE_LIMIT ? message.slice(0, MESSAGE_LIMIT) : message; } @@ -136,6 +172,51 @@ export function createAndroidDeviceTcp(options: AndroidDeviceTcpOptions): Androi new Set([...held.values()].flatMap((mine) => [...mine].map((entry) => entry.port))); return { supports: () => true, + // why: the host protocol reaches a device port through the target's adb server with no `adb forward` rule, so a worker that dies leaves nothing listening; both answers share one 5 s limit. + async connect(device, devicePort, signal): Promise { + if (options.target === undefined) { + throw new DeviceTcpError("TUNNEL_FAILED", "this driver has no adb connection to open"); + } + const target = await options.target(device); + const limit = new AbortController(); + let timedOut = false; + const timer = options.clock.setTimer(CONNECT_TIMEOUT_MS, () => { + timedOut = true; + limit.abort(); + }); + const relay = () => limit.abort(); + signal.addEventListener("abort", relay, { once: true }); + try { + const outcome = await openDeviceSocket({ + connect: (timeoutMs) => target.connect(timeoutMs), + serial: target.serial, + service: `tcp:${String(devicePort)}`, + signal: limit.signal, + timeoutMs: CONNECT_TIMEOUT_MS, + }); + if (timedOut) { + if (outcome.kind === "open") outcome.stream.close(); + throw new DeviceTcpError("TUNNEL_FAILED", "timeout"); + } + if (outcome.kind === "open") return streamThrough(outcome.stream, outcome.reader); + throw new DeviceTcpError( + "TUNNEL_FAILED", + cut( + outcome.kind === "refused" + ? outcome.reason + : `adb cannot reach ${target.serial}: ${outcome.reason}`, + ), + ); + } catch (error) { + if (timedOut && !(error instanceof DeviceTcpError)) { + throw new DeviceTcpError("TUNNEL_FAILED", "timeout"); + } + throw error; + } finally { + options.clock.cancel(timer); + signal.removeEventListener("abort", relay); + } + }, async release(device): Promise { const mine = held.get(device.deviceId); if (mine === undefined) return; diff --git a/src/drivers/android/index.test.ts b/src/drivers/android/index.test.ts index ebd3c6b6a..9dd019c38 100644 --- a/src/drivers/android/index.test.ts +++ b/src/drivers/android/index.test.ts @@ -32,6 +32,7 @@ import { type ProcessRunOptions, type ScriptedProcessExpectation, SystemClock, + type TcpStream, } from "../../ports/index.js"; import { AdbServerUnavailableError, @@ -3564,6 +3565,19 @@ describe("AndroidDriver", () => { }); }); +// why: stands in for adb's server: it answers the host protocol with the bytes a test scripts, and says nothing when there are none. +class RepliesTcpStreamConnector extends FakeTcpStreamConnector { + constructor(private readonly replies: string) { + super(); + } + + override async connect(port: number): Promise { + const stream = await super.connect(port); + if (this.replies !== "") this.connections.at(-1)?.peer.send(this.replies); + return stream; + } +} + describe("AndroidDriver deviceTcp", () => { const emulator = { address: "emulator-5586", @@ -3595,7 +3609,7 @@ describe("AndroidDriver deviceTcp", () => { } // fallow-ignore-next-line complexity -- one Tests line: the driver's reverse, its close and each refusal are the cases of one scenario. - it("sets adb reverse --no-rebind to a loopback listener in 47000-47999 and removes it on close, as an emulator or a phone, keeps the port of a rule that could not be removed until the device's reclaim, and refuses with TUNNEL_PORT_IN_USE when adb cannot rebind and TUNNEL_FAILED for any other adb failure or when every tunnel port is busy", async () => { + it("sets adb reverse --no-rebind to a loopback listener in 47000-47999 and removes it on close, as an emulator or a phone, keeps the port of a rule that could not be removed until the device's reclaim, and refuses with TUNNEL_PORT_IN_USE when adb cannot rebind and TUNNEL_FAILED for any other adb failure or when every tunnel port is busy, and opens a device port for a forward tunnel through the target's adb server (an emulator's configured one, a phone's after its check) with no adb forward rule, and rejects with the check's message when a phone's check is closed, with adb's reason when adb answers FAIL, and with \"timeout\" when adb does not answer in 5 s", async () => { const { driver, listeners, runner } = await driverWith([ { match: adb("-P", "5038", "-s", "emulator-5586", ...reverseArgs(47_002)), result: ok }, { @@ -3720,6 +3734,66 @@ describe("AndroidDriver deviceTcp", () => { }), ); expect(exhausted.runner.calls).toEqual([]); + + const connectWith = async ( + device: typeof emulator | typeof PHYSICAL_DEVICE, + adbReplies: string, + options: { readonly probe?: FakeTcpProbe; readonly port?: number } = {}, + ) => { + const connector = new RepliesTcpStreamConnector(adbReplies); + const clock = new FakeClock(); + const runner = new ScriptedProcessRunner( + options.probe === undefined + ? [] + : [ + { + match: adb("version"), + result: { code: 0, stderr: "", stdout: "Android Debug Bridge version 1.0.41\n" }, + }, + ], + ); + const driver = await createDriver(await androidFilesystem(), runner, { + clock, + ...(options.port === undefined ? {} : { driverConfig: { adbServerPort: options.port } }), + tcpListener: new FakeTcpListenerFactory(), + ...(options.probe === undefined ? {} : { tcpProbe: options.probe }), + tcpStreamConnector: connector, + }); + const connecting = driver.deviceTcp?.connect(device, 8081, signal()); + return { clock, connecting, connector, runner }; + }; + + const opened = await connectWith(emulator, "OKAYOKAY", { port: 5050 }); + await expect(opened.connecting).resolves.toBeDefined(); + expect(opened.connector.connections.map(({ port }) => port)).toEqual([5050]); + expect(opened.connector.connections[0]?.peer.writtenText()).toBe( + "001chost:transport:emulator-55860008tcp:8081", + ); + expect(opened.runner.calls).toEqual([]); + + const closedProbe = new FakeTcpProbe([5038, 5037]); + closedProbe.replyWith("OKAY00040028"); + const gated = await connectWith(PHYSICAL_DEVICE, "OKAYOKAY", { probe: closedProbe }); + await expect(gated.connecting).rejects.toThrow(/speaks protocol 40/); + expect(gated.connector.connections).toEqual([]); + + const refused = await connectWith(emulator, "OKAYFAIL0006closed"); + await expect(refused.connecting).rejects.toEqual( + expect.objectContaining({ code: "TUNNEL_FAILED", message: "closed" }), + ); + + const silent = await connectWith(emulator, ""); + // why: the connect is pending only once the socket is open and waiting for adb's answer; a timer alone is set before that. + await vi.waitFor(() => expect(silent.connector.connections).toHaveLength(1)); + await new Promise((resolve) => setImmediate(resolve)); + expect(silent.clock.pendingTimerCount).toBeGreaterThan(0); + silent.clock.advance(4_999); + await new Promise((resolve) => setImmediate(resolve)); + expect(silent.connector.connections[0]?.peer.closed).toBe(false); + silent.clock.advance(1); + await expect(silent.connecting).rejects.toEqual( + expect.objectContaining({ code: "TUNNEL_FAILED", message: "timeout" }), + ); }); it("sweeps at start only the reverse rules into 47000-47999 on an idle device proved its own, only reads a leased device's rules and keeps their ports from the next reverse until its reclaim, touches nothing on an emulator that answers as another's, and on an idle phone removes nothing and keeps the ports its rules point to from the next reverse", async () => { diff --git a/src/drivers/android/index.ts b/src/drivers/android/index.ts index 1558af24b..9ba50d3ae 100644 --- a/src/drivers/android/index.ts +++ b/src/drivers/android/index.ts @@ -594,14 +594,17 @@ export class AndroidDriver implements Driver { this.#sdk = sdk; this.#tcpProbe = options.tcpProbe; this.componentFootprint = { bytes: ANDROID_SYSTEM_IMAGE_MIN_FREE_BYTES, path: sdk.root }; - const targetFor = this.#screenTargetFor(options, sdk.adb, adbServerPort); + const deviceTarget = this.#deviceTargetFor(options, sdk.adb, adbServerPort); + const targetFor = this.#screenTargetFor(options, deviceTarget); this.screenCapture = this.#screenCaptureFor(options, targetFor); this.input = this.#inputFor(options, targetFor); this.deviceTcp = options.tcpListener === undefined ? undefined : createAndroidDeviceTcp({ + clock: options.clock, listeners: options.tcpListener, + target: deviceTarget, isOwn: (device) => this.#deviceIsOwn(device), runAdb: (device, args, timeoutMs) => this.#runAdbOn(device, args, timeoutMs), warn: (message, detail) => options.logger?.warn(message, detail), @@ -635,13 +638,21 @@ export class AndroidDriver implements Driver { ); } + // why: the screen and the input helper ride on the scrcpy server, so without its path they have no target even when a device port can be opened. #screenTargetFor( + options: AndroidDriverOptions, + deviceTarget: AndroidTargetFor | undefined, + ): AndroidTargetFor | undefined { + return options.scrcpyServerPath === undefined ? undefined : deviceTarget; + } + + #deviceTargetFor( options: AndroidDriverOptions, adb: string, adbServerPort: number, ): AndroidTargetFor | undefined { const tcp = options.tcpStreamConnector; - if (options.scrcpyServerPath === undefined || tcp === undefined) return undefined; + if (tcp === undefined) return undefined; const runner = options.processRunner; return async (device) => isPhysicalDriverDevice(device) diff --git a/src/drivers/android/screen/adb-socket.ts b/src/drivers/android/screen/adb-socket.ts index 26886401b..d85cc0688 100644 --- a/src/drivers/android/screen/adb-socket.ts +++ b/src/drivers/android/screen/adb-socket.ts @@ -55,7 +55,8 @@ interface DeviceSocketRequest { // Simlock's own for an emulator, port 5037 for a physical phone. readonly connect: (timeoutMs: number) => Promise; readonly serial: string; - readonly socketName: string; + // why: the host-protocol service the socket is opened to: `localabstract:` for a device socket, `tcp:` for a device port. + readonly service: string; readonly timeoutMs: number; readonly signal: AbortSignal; } @@ -80,7 +81,7 @@ export async function openDeviceSocket(request: DeviceSocketRequest): Promise target.connect(timeoutMs), serial: target.serial, signal, - socketName: `scrcpy_${request.scidHex}`, + service: `localabstract:scrcpy_${request.scidHex}`, timeoutMs: Math.max(1, request.deadlineAt - request.clock.now()), }); if (outcome.kind === "no-transport") { diff --git a/src/modules/testing.ts b/src/modules/testing.ts index f22bc554f..fe3da8573 100644 --- a/src/modules/testing.ts +++ b/src/modules/testing.ts @@ -192,6 +192,7 @@ export async function fakeWorkerContext(name: string, config: C): Promise Promise.reject(new Error("no device port in a fake context")), reverse: () => Promise.reject(new Error("no device port in a fake context")), supports: () => false, }, diff --git a/src/modules/types.ts b/src/modules/types.ts index bb7353e2d..5885ab727 100644 --- a/src/modules/types.ts +++ b/src/modules/types.ts @@ -30,6 +30,7 @@ import type { ProcessRunner, ProcessSupervisor, TcpProbe, + TcpStream, } from "../ports/index.js"; export interface ModuleConfig { @@ -212,6 +213,12 @@ export interface ModuleDeviceTcp { devicePort: number, signal: AbortSignal, ): Promise; + connect( + platform: Platform, + device: VirtualDriverDevice | PhysicalDriverDevice, + devicePort: number, + signal: AbortSignal, + ): Promise; } export interface WorkerContext { diff --git a/src/tunnel/AGENTS.md b/src/tunnel/AGENTS.md index cab57de0e..01f1798fe 100644 --- a/src/tunnel/AGENTS.md +++ b/src/tunnel/AGENTS.md @@ -1,6 +1,6 @@ # Tunnel -Does: lets a lease's holder (or an operator) reverse device ports of its Android device to its own machine over `WS /v1/leases/{id}/tunnel`, on a lone worker or through a gateway. +Does: lets a lease's holder (or an operator) reverse device ports of its Android device to its own machine, or forward its own loopback ports to the device's, over `WS /v1/leases/{id}/tunnel`, on a lone worker or through a gateway. Entry: `index.ts` -> `tunnelModule`, an optional module (ADR 0054): `worker.ts` `createWorker` and `gateway.ts` `createGateway`, loaded by the module host only when turned on. Uses: contract (`src/contract/tunnel-frames.ts`), core (`DeviceReverse`, `DeviceTcpError`, `closeReason`), modules (the context, socket and relay types, and `modules/relay-channel.ts`: the channel framing, `channelSocket`, the close mapping and the 404, 426 and 503 bodies), ports (`LeaseSocket`, `Clock`). Never imports: http, gateway, drivers, daemon, leasing, `fs`, `child_process`. Imported by: `module-registry` only. @@ -8,22 +8,24 @@ Off unless `capabilities.tunnel.enabled` (false). Off: nothing loaded, and the ` ## Files -| File | Role | -| ----------------- | -------------------------------------------------------------------------------------------- | -| `definition.ts` | `tunnelModule`: name `tunnel`, empty config section, `http` route data, the two loaders | -| `worker.ts` | The worker side from the host's context: capability, hooks, lease route (426), socket, relay | -| `gateway.ts` | The gateway side: lease route (426), socket, `beforeDrain` | -| `gateway-link.ts` | Gateway: the module's path, bounds and 503 texts for `createGatewayChannelLink` | -| `limits.ts` | `MAX_TUNNEL_MESSAGE_BYTES` (65541): the longest message a channel frame carries | -| `sessions.ts` | One session per socket: HELLO, rules, connections, window and credit, lease end, drain | +| File | Role | +| ------------------- | ------------------------------------------------------------------------------------------------------ | +| `definition.ts` | `tunnelModule`: name `tunnel`, empty config section, `http` route data, the two loaders | +| `worker.ts` | The worker side from the host's context: capability, hooks, lease route (426), socket, relay | +| `gateway.ts` | The gateway side: lease route (426), socket, `beforeDrain` | +| `gateway-link.ts` | Gateway: the module's path, bounds and 503 texts for `createGatewayChannelLink` | +| `pending-stream.ts` | A forwarded connection's stream before its device connect settles: writes, END and close wait in order | +| `limits.ts` | `MAX_TUNNEL_MESSAGE_BYTES` (65541): the longest message a channel frame carries | +| `sessions.ts` | One session per socket: HELLO, rules, connections, window and credit, lease end, drain | ## How it works The HTTP layer resolves the lease for the caller, then `socket.open` finds the lease and its device in the worker's registry (404 `UNKNOWN_LEASE` when gone) and attaches a session to the upgraded socket. -1. The first frame must be `HELLO`. It is checked whole: bad port, more than 8 tunnels per lease (counted across sockets), `forward` (not available yet), a platform whose driver has no `deviceTcp` (`supports`). A refusal sends `REFUSED {code, message}` and closes 4003 (the close reason is cut to 123 bytes, the message is whole). -2. Each reverse tunnel is `ctx.deviceTcp.reverse`. A failure removes the tunnels set before it and refuses with the driver's `DeviceTcpError` code (`TUNNEL_PORT_IN_USE`, `TUNNEL_FAILED`), else `TUNNEL_FAILED`. Then `READY`. -3. A device connection is `OPEN` with the next odd id; its bytes go out as `DATA` only while the caller's window allows, and the worker grants `CREDIT` as it writes to the device. `END` half-closes one direction; a connection ends when both have. A 257th open connection is closed at once. +1. The first frame must be `HELLO`. It is checked whole: bad port, more than 8 tunnels per lease (counted across sockets), a platform whose driver has no `deviceTcp` (`supports`). A refusal sends `REFUSED {code, message}` and closes 4003 (the close reason is cut to 123 bytes, the message is whole). +2. Each reverse tunnel is `ctx.deviceTcp.reverse`; a forward tunnel sets nothing on the device. A failure removes the tunnels set before it and refuses with the driver's `DeviceTcpError` code (`TUNNEL_PORT_IN_USE`, `TUNNEL_FAILED`), else `TUNNEL_FAILED`. Then `READY`. +3. A device connection is `OPEN` with the next odd id; its bytes go out as `DATA` only while the caller's window allows, and the worker grants `CREDIT` as it writes to the device. `END` half-closes one direction; a connection ends when both have. A 257th device connection is closed at once, with no frame. + 3a. A forward connection is the caller's `OPEN` with an even id above its last, `{kind:"forward", devicePort}` naming one of the socket's forward tunnels (else `BAD_REQUEST`, close 4003). `ctx.deviceTcp.connect` opens the device port while `pendingStream` holds the caller's `DATA` and `END` in order; a failed connect is `RESET {reason}`, and a caller's `OPEN` as the 257th connection is `RESET` at once. 4. A bad frame (a `CREDIT` that is not 4 bytes, a `DATA` of 0 or over 65536 bytes included) is `BAD_REQUEST`, close 4003, never a throw; a frame for a connection already closed is ignored; a device stream that fails resets its own connection. 5. The socket closing, the lease ending (`beforeDeviceReclaim`, close 4001 with the reason) and a drain (`beforeDrain`, close 1001) close the session's connections and remove its rules, the hook returning when they are done, a removal the socket's close began included (10 s per removal); on an emulator a signal that is aborted, or aborts between removals, skips the rest and reclaim does them; on a phone the removals run anyway, because its reclaim removes no rules. diff --git a/src/tunnel/definition.ts b/src/tunnel/definition.ts index 23bf555ae..3faefb59a 100644 --- a/src/tunnel/definition.ts +++ b/src/tunnel/definition.ts @@ -15,7 +15,7 @@ export const tunnelModule: OptionalModuleDefinition = { method: "get", path: "/v1/leases/{id}/tunnel", description: - "Open a tunnel socket for a lease's device over a WebSocket: the lease's holder or an operator. Each message is one tag byte, a 4-byte big-endian connection number and a payload. The holder sends HELLO with up to 8 tunnels, each {kind, devicePort}; the server answers READY with the same list, or REFUSED {code, message} and close 4003, and then nothing the HELLO named stays set up. Today only reverse tunnels are served: the device's connections to devicePort arrive as OPEN and DATA, under a 262144-byte window per direction. The socket closes 4001 with the lease-end reason when the lease ends, and 1001 when the daemon stops. A lease the caller does not own answers 404, as an unknown one does. A plain GET without an upgrade answers 426. Served only when capabilities.tunnel.enabled is true on the daemon that answers; through a gateway the lease's worker needs it too, and the socket also closes 1011 when that worker stops answering and 1001 when the gateway stops.", + "Open a tunnel socket for a lease's device over a WebSocket: the lease's holder or an operator. Each message is one tag byte, a 4-byte big-endian connection number and a payload. The holder sends HELLO with up to 8 tunnels, each {kind, devicePort}; the server answers READY with the same list, or REFUSED {code, message} and close 4003, and then nothing the HELLO named stays set up. A reverse tunnel's connections from the device to devicePort arrive as OPEN and DATA; for a forward tunnel the holder sends OPEN {kind: forward, devicePort} with an even connection number above its last, and the worker opens that device port. Both run under a 262144-byte window per direction. The socket closes 4001 with the lease-end reason when the lease ends, and 1001 when the daemon stops. A lease the caller does not own answers 404, as an unknown one does. A plain GET without an upgrade answers 426. Served only when capabilities.tunnel.enabled is true on the daemon that answers; through a gateway the lease's worker needs it too, and the socket also closes 1011 when that worker stops answering and 1001 when the gateway stops.", statuses: { 101: { description: "The upgrade to a WebSocket." }, 404: { diff --git a/src/tunnel/pending-stream.ts b/src/tunnel/pending-stream.ts new file mode 100644 index 000000000..63539b2f4 --- /dev/null +++ b/src/tunnel/pending-stream.ts @@ -0,0 +1,35 @@ +import type { TcpStream } from "../ports/index.js"; + +// why: a caller announces a forwarded connection with OPEN and sends its bytes at once, before the device has answered, so the connection exists from the OPEN and its writes, its END and its close wait for the device connect, in the order they came. +export function pendingStream(connecting: Promise): TcpStream { + let reader: ReadableStreamDefaultReader | undefined; + return { + close: () => { + void connecting.then( + (stream) => { + stream.close(); + }, + () => undefined, + ); + }, + end: () => { + void connecting.then( + (stream) => { + stream.end(); + }, + () => undefined, + ); + }, + readable: new ReadableStream({ + pull: async (controller) => { + reader ??= (await connecting).readable.getReader(); + const step = await reader.read(); + if (step.done) controller.close(); + else controller.enqueue(step.value); + }, + }), + write: async (bytes) => { + await (await connecting).write(bytes); + }, + }; +} diff --git a/src/tunnel/sessions.ts b/src/tunnel/sessions.ts index 14ff11f45..357fa7c5e 100644 --- a/src/tunnel/sessions.ts +++ b/src/tunnel/sessions.ts @@ -22,6 +22,7 @@ import { } from "../core/index.js"; import type { ModuleDeviceTcp } from "../modules/index.js"; import type { Clock, LeaseSocket, Logger, TcpStream, TimerHandle } from "../ports/index.js"; +import { pendingStream } from "./pending-stream.js"; const CLOSE_LEASE_ENDED = 4001; const CLOSE_GOING_AWAY = 1001; @@ -109,9 +110,6 @@ function refusal(tunnels: readonly Tunnel[], held: number): Refusal | undefined }; } } - if (tunnels.some(({ kind }) => kind === "forward")) { - return { code: "TUNNEL_UNSUPPORTED", message: "forward tunnels are not available yet" }; - } return undefined; } @@ -138,6 +136,7 @@ export function createTunnelSessions(options: { function attach(leaseId: string, device: DeviceRecord, socket: LeaseSocket): void { let nextConnection = 1; + let lastCallerConnection = 0; let greeted = false; let reserved = 0; let finished: Promise | undefined; @@ -147,6 +146,7 @@ export function createTunnelSessions(options: { | undefined; const connections = new Map(); const reverses: DeviceReverse[] = []; + const forwards = new Set(); // why: a phone's reclaim removes no rules, so an end whose signal is aborted still removes this session's own; only an emulator's reclaim does that for it. const phone = toDriverDevice(device).physical; @@ -212,6 +212,16 @@ export function createTunnelSessions(options: { connections.delete(conn); } + async function windowOpen(connection: Connection): Promise { + while (connection.window === 0) { + await new Promise((wake) => { + connection.wake = wake; + }); + if (connection.closed) return false; + } + return true; + } + // why: a connection a RESET or a failure already closed sends no END for the device's end. function deviceEnded(conn: number, connection: Connection): void { if (connection.closed) return; @@ -225,14 +235,11 @@ export function createTunnelSessions(options: { const reader = connection.stream.readable.getReader(); let pending: Uint8Array | undefined; for (;;) { - while (connection.window === 0) { - await new Promise((wake) => { - connection.wake = wake; - }); - if (connection.closed) return; - } + if (!(await windowOpen(connection))) return; if (pending === undefined) { - const step = await reader.read(); + // why: a forwarded connection whose device connect failed has a readable that errors; the RESET it got is its whole ending. + const step = await reader.read().catch(() => undefined); + if (step === undefined) return; if (step.done) { deviceEnded(conn, connection); return; @@ -246,6 +253,78 @@ export function createTunnelSessions(options: { } } + function register(conn: number, stream: TcpStream): void { + const connection: Connection = { + callerEnded: false, + closed: false, + deviceEnded: false, + inbound: TUNNEL_WINDOW_BYTES, + stream, + wake: undefined, + window: TUNNEL_WINDOW_BYTES, + }; + connections.set(conn, connection); + void pump(conn, connection).catch(() => drop(conn, connection)); + } + + // why: the OPEN is wire input from the caller, so its JSON may be anything; the port it names is trusted only when it is one of this socket's forward tunnels. + function forwardPortOf(payload: Uint8Array): number | undefined { + let parsed: unknown; + try { + parsed = JSON.parse(new TextDecoder().decode(payload)); + } catch { + return undefined; + } + const devicePort = field(parsed, "devicePort"); + const named = field(parsed, "kind") === "forward" && typeof devicePort === "number"; + return named && forwards.has(devicePort) ? devicePort : undefined; + } + + function openForward(conn: number, payload: Uint8Array): void { + if (finished !== undefined) return; + if (conn % 2 !== 0 || conn <= lastCallerConnection) { + badRequest("OPEN needs an even connection id above the last"); + return; + } + const devicePort = forwardPortOf(payload); + if (devicePort === undefined) { + badRequest("OPEN must name a forward tunnel of this socket"); + return; + } + lastCallerConnection = conn; + if (connections.size >= MAX_CONNECTIONS) { + socket.send( + encodeTunnelFrame( + TUNNEL_TAG.reset, + conn, + JSON.stringify({ reason: "too many connections" }), + ), + ); + return; + } + const connecting = options.deviceTcp.connect( + device.spec.platform, + toDriverDevice(device), + devicePort, + new AbortController().signal, + ); + register(conn, pendingStream(connecting)); + connecting.catch((error: unknown) => { + const connection = connections.get(conn); + if (connection === undefined) return; + connection.closed = true; + connection.wake?.(); + connections.delete(conn); + socket.send( + encodeTunnelFrame( + TUNNEL_TAG.reset, + conn, + JSON.stringify({ reason: error instanceof Error ? error.message : String(error) }), + ), + ); + }); + } + function refuse(refused: Refusal): void { socket.send(encodeTunnelFrame(TUNNEL_TAG.refused, 0, JSON.stringify(refused))); socket.close(TUNNEL_REFUSED_CLOSE, closeReason(refused.message)); @@ -310,9 +389,12 @@ export function createTunnelSessions(options: { }); return; } + for (const { devicePort, kind } of tunnels) if (kind === "forward") forwards.add(devicePort); counts.set(leaseId, held + tunnels.length); reserved = tunnels.length; for (const tunnel of tunnels) { + // why: a forward tunnel sets nothing on the device; each caller connection opens its own device socket. + if (tunnel.kind === "forward") continue; let reverse: DeviceReverse; try { reverse = await options.deviceTcp.reverse( @@ -350,17 +432,7 @@ export function createTunnelSessions(options: { const conn = nextConnection; nextConnection += 2; socket.send(encodeTunnelFrame(TUNNEL_TAG.open, conn, JSON.stringify(tunnel))); - const connection: Connection = { - callerEnded: false, - closed: false, - deviceEnded: false, - inbound: TUNNEL_WINDOW_BYTES, - stream, - wake: undefined, - window: TUNNEL_WINDOW_BYTES, - }; - connections.set(conn, connection); - void pump(conn, connection).catch(() => drop(conn, connection)); + register(conn, stream); }); } socket.send(encodeTunnelFrame(TUNNEL_TAG.ready, 0, JSON.stringify({ tunnels }))); @@ -412,6 +484,10 @@ export function createTunnelSessions(options: { badRequest("HELLO came twice"); return; } + if (frame.tag === TUNNEL_TAG.open) { + openForward(frame.conn, frame.payload); + return; + } if ( frame.tag !== TUNNEL_TAG.data && frame.tag !== TUNNEL_TAG.credit && @@ -421,8 +497,9 @@ export function createTunnelSessions(options: { badRequest(`unknown frame tag ${String(frame.tag)}`); return; } - // why: the worker opens odd ids, rising from 1, so an even id or one above the last it opened was never a connection; one it opened and closed is ignored. - if (frame.conn % 2 === 0 || frame.conn > nextConnection - 2) { + // why: the worker opens odd ids and the caller even ones, each rising, so an id above the last of its side was never a connection; one opened and closed is ignored. + const last = frame.conn % 2 === 0 ? lastCallerConnection : nextConnection - 2; + if (frame.conn === 0 || frame.conn > last) { badRequest(`connection ${String(frame.conn)} was never opened`); return; } diff --git a/src/tunnel/worker.test.ts b/src/tunnel/worker.test.ts index 2def5ac31..d0df91c6f 100644 --- a/src/tunnel/worker.test.ts +++ b/src/tunnel/worker.test.ts @@ -87,6 +87,7 @@ async function setup( const worker = loaded.createWorker({ ...ctx, deviceTcp: { + connect: (_platform, device, port, signal) => deviceTcp.connect(device, port, signal), supports: (named) => named === "android", reverse: (_platform, device, port, signal) => deviceTcp.reverse(device, port, signal), }, @@ -118,7 +119,7 @@ async function carriesOneTunnel(): Promise { ); expect(deviceTcp.reversed).toEqual([5173]); - const device = deviceTcp.connect(5173); + const device = deviceTcp.openFromDevice(5173); await vi.waitFor(() => expect(frames(socket).at(-1)).toEqual({ body: '{"kind":"reverse","devicePort":5173}', @@ -147,8 +148,8 @@ async function halfClosesAndLimitsConnections(): Promise { }, ]), ); - const first = deviceTcp.connect(1024); - const second = deviceTcp.connect(65535); + const first = deviceTcp.openFromDevice(1024); + const second = deviceTcp.openFromDevice(65535); await vi.waitFor(() => expect(frames(socket).slice(1)).toEqual([ { body: '{"kind":"reverse","devicePort":1024}', conn: 1, tag: 0x02 }, @@ -176,16 +177,16 @@ async function halfClosesAndLimitsConnections(): Promise { ); const opens = () => frames(socket).filter((sent) => sent.tag === 0x02).length; - const peers = Array.from({ length: 255 }, () => deviceTcp.connect(1024)); + const peers = Array.from({ length: 255 }, () => deviceTcp.openFromDevice(1024)); await vi.waitFor(() => expect(opens()).toBe(257)); expect(peers.every((peer) => !peer.closed)).toBe(true); - const past = deviceTcp.connect(1024); + const past = deviceTcp.openFromDevice(1024); await vi.waitFor(() => expect(past.closed).toBe(true)); expect(opens()).toBe(257); socket.receive(frame(0x06, 3, '{"reason":"done"}')); await vi.waitFor(() => expect(second.closed).toBe(true)); - const after = deviceTcp.connect(1024); + const after = deviceTcp.openFromDevice(1024); await vi.waitFor(() => expect(opens()).toBe(258)); expect(after.closed).toBe(false); } @@ -195,8 +196,8 @@ async function pausesOnlyTheConnectionWithoutCredit(): Promise { const socket = await attach(worker); socket.receive(hello({ devicePort: 5173, kind: "reverse" })); await vi.waitFor(() => expect(frames(socket)).toHaveLength(1)); - const first = deviceTcp.connect(5173); - const second = deviceTcp.connect(5173); + const first = deviceTcp.openFromDevice(5173); + const second = deviceTcp.openFromDevice(5173); await vi.waitFor(() => expect(frames(socket).map((sent) => sent.tag)).toEqual([0x81, 0x02, 0x02]), ); @@ -265,8 +266,9 @@ describe("a worker's tunnel socket", () => { }, { code: "TUNNEL_UNSUPPORTED", - message: "forward tunnels are not available yet", - tunnels: [reverse(5173), { devicePort: 9229, kind: "forward" }], + message: "the lease is on an iOS simulator; tunnels need an Android emulator or phone", + platform: "ios", + tunnels: [{ devicePort: 9229, kind: "forward" }], }, { code: "TUNNEL_UNSUPPORTED", @@ -487,6 +489,11 @@ describe("a worker's tunnel socket", () => { ready: true, send: (socket) => socket.receive(credit(2, 1)), }, + { + message: "connection 0 was never opened", + ready: true, + send: (socket) => socket.receive(frame(0x03, 0, "x")), + }, { message: "the window is above 2147483648", ready: true, @@ -503,8 +510,8 @@ describe("a worker's tunnel socket", () => { if (bad.ready) { socket.receive(hello(tunnel)); await vi.waitFor(() => expect(frames(socket)).toHaveLength(1)); - deviceTcp.connect(5173); - deviceTcp.connect(5173); + deviceTcp.openFromDevice(5173); + deviceTcp.openFromDevice(5173); await vi.waitFor(() => expect(frames(socket)).toHaveLength(3)); } expect(socket.closed).toBeUndefined(); @@ -521,8 +528,8 @@ describe("a worker's tunnel socket", () => { const socket = await attach(worker); socket.receive(hello(tunnel)); await vi.waitFor(() => expect(frames(socket)).toHaveLength(1)); - const closing = deviceTcp.connect(5173); - const going = deviceTcp.connect(5173); + const closing = deviceTcp.openFromDevice(5173); + const going = deviceTcp.openFromDevice(5173); await vi.waitFor(() => expect(frames(socket)).toHaveLength(3)); socket.receive(frame(0x06, 1, '{"reason":"caller closed"}')); await vi.waitFor(() => expect(closing.closed).toBe(true)); @@ -554,13 +561,13 @@ describe("a worker's tunnel socket", () => { readonly deviceTcp: FakeDeviceTcp; readonly worker: WorkerModule; readonly socket: MemoryLeaseSocket; - readonly device: ReturnType; + readonly device: ReturnType; }> { const { clock, deviceTcp, worker } = await setup(); const socket = await attach(worker); socket.receive(hello(tunnel)); await vi.waitFor(() => expect(frames(socket)).toHaveLength(1)); - const device = deviceTcp.connect(5173); + const device = deviceTcp.openFromDevice(5173); await vi.waitFor(() => expect(frames(socket)).toHaveLength(2)); return { clock, device, deviceTcp, socket, worker }; } @@ -710,7 +717,7 @@ describe("a worker's tunnel socket", () => { ); expect(reclaimed.socket.closed).toEqual({ code: 4001, reason: "device-lost" }); expect(reclaimed.deviceTcp.reversed).toEqual([5173]); - expect(reclaimed.deviceTcp.connect(5173).closed).toBe(true); + expect(reclaimed.deviceTcp.openFromDevice(5173).closed).toBe(true); // why: a phone's reclaim removes no rules, so an aborted end still removes the tunnel's own. const phone = await setup("android", true); @@ -808,3 +815,113 @@ describe("a worker's tunnel socket", () => { expect(clock.pendingTimerCount).toBe(idleTimers); }); }); + +describe("a worker's tunnel socket with forward tunnels", () => { + const tunnels = [ + { devicePort: 9229, kind: "forward" }, + { devicePort: 5173, kind: "reverse" }, + ]; + const open = (conn: number, devicePort: number, kind = "forward"): Uint8Array => + frame(0x02, conn, JSON.stringify({ devicePort, kind })); + + async function ready() { + const { deviceTcp, worker } = await setup(); + deviceTcp.listening.add(9229); + const socket = await attach(worker); + socket.receive(hello(...tunnels)); + await vi.waitFor(() => expect(frames(socket)).toHaveLength(1)); + expect(deviceTcp.reversed).toEqual([5173]); + return { deviceTcp, socket, worker }; + } + + it("refuses a caller OPEN that is not an even rising id for a forward tunnel of the socket with BAD_REQUEST and close 4003, and counts caller and device connections together toward 256", async () => { + const accepted = await ready(); + accepted.socket.receive(open(2, 9229)); + await vi.waitFor(() => expect(accepted.deviceTcp.connections).toHaveLength(1)); + expect(accepted.socket.closed).toBeUndefined(); + + const cases = [ + { frames: [open(2, 9230)], message: "OPEN must name a forward tunnel of this socket" }, + { frames: [open(2, 5173)], message: "OPEN must name a forward tunnel of this socket" }, + { + frames: [open(2, 9229, "reverse")], + message: "OPEN must name a forward tunnel of this socket", + }, + { frames: [open(1, 9229)], message: "OPEN needs an even connection id above the last" }, + { + frames: [open(2, 9229), open(2, 9229)], + message: "OPEN needs an even connection id above the last", + }, + { + frames: [open(4, 9229), open(2, 9229)], + message: "OPEN needs an even connection id above the last", + }, + { + frames: [frame(0x02, 2, "{nope")], + message: "OPEN must name a forward tunnel of this socket", + }, + ]; + for (const bad of cases) { + const { socket } = await ready(); + for (const sent of bad.frames) socket.receive(sent); + await vi.waitFor(() => expect(socket.closed).toEqual({ code: 4003, reason: bad.message })); + expect(frames(socket).at(-1)).toEqual({ + body: JSON.stringify({ code: "BAD_REQUEST", message: bad.message }), + conn: 0, + tag: 0x82, + }); + } + + const { deviceTcp, socket } = await ready(); + for (let conn = 2; conn <= 512; conn += 2) { + if (conn <= 256) deviceTcp.openFromDevice(5173); + else socket.receive(open(conn, 9229)); + } + await vi.waitFor(() => expect(deviceTcp.connections).toHaveLength(128)); + socket.receive(open(514, 9229)); + await vi.waitFor(() => + expect(frames(socket).at(-1)).toEqual({ + body: '{"reason":"too many connections"}', + conn: 514, + tag: 0x06, + }), + ); + expect(deviceTcp.connections).toHaveLength(128); + const past = deviceTcp.openFromDevice(5173); + await vi.waitFor(() => expect(past.closed).toBe(true)); + expect(socket.closed).toBeUndefined(); + + const failing = await ready(); + failing.deviceTcp.listening.delete(9229); + failing.deviceTcp.connectFailures.set(9231, new DeviceTcpError("TUNNEL_FAILED", "timeout")); + failing.socket.receive(open(2, 9229)); + await vi.waitFor(() => + expect(frames(failing.socket).at(-1)).toEqual({ + body: '{"reason":"closed"}', + conn: 2, + tag: 0x06, + }), + ); + expect(failing.socket.closed).toBeUndefined(); + + const silent = await ready(); + silent.deviceTcp.connectFailures.set(9229, new DeviceTcpError("TUNNEL_FAILED", "timeout")); + silent.socket.receive(open(2, 9229)); + await vi.waitFor(() => + expect(frames(silent.socket).at(-1)).toEqual({ + body: '{"reason":"timeout"}', + conn: 2, + tag: 0x06, + }), + ); + + const ended = await ready(); + await ended.worker.hooks?.beforeDeviceReclaim?.( + ending("expired"), + new AbortController().signal, + ); + ended.socket.receive(open(2, 9229)); + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(ended.deviceTcp.connections).toHaveLength(0); + }); +}); diff --git a/website/src/content/docs/docs/reference/cli.mdx b/website/src/content/docs/docs/reference/cli.mdx index 2429eec41..1d2dbe8a6 100644 --- a/website/src/content/docs/docs/reference/cli.mdx +++ b/website/src/content/docs/docs/reference/cli.mdx @@ -205,20 +205,21 @@ It prints `Rotated lease to `, with the orientation spel ## simlock tunnel -Reach your leased Android emulator back to ports on your own machine, from another machine, while the command runs. It talks to a lone worker or a gateway over HTTP and WebSocket, so it needs no local daemon. +Reach your leased Android emulator back to ports on your own machine, and ports on the device from your machine, from another machine, while the command runs. It talks to a lone worker or a gateway over HTTP and WebSocket, so it needs no local daemon. ```text -simlock tunnel reverse [:] [reverse ...] [--lease ] [--url ] +simlock tunnel reverse|forward [:] [reverse|forward ...] [--lease ] [--url ] ``` | Flag | Meaning | Default | | --- | --- | --- | -| `reverse [:]` | Make the device's `localhost:` reach `localhost:` on this machine. Both are integers 1 to 65535; the worker accepts device ports from 1024. Repeat the word `reverse` for up to 8 tunnels; a caller port may appear once. | The caller port is the device port | +| `reverse [:]` | Make the device's `localhost:` reach `localhost:` on this machine. Both are integers 1 to 65535; the worker accepts device ports from 1024. Repeat the word `reverse` for up to 8 tunnels, counting `forward` ones; a caller port may appear once across both. | The caller port is the device port | +| `forward [:]` | Make `localhost:` on this machine reach `localhost:` on the device, through adb's host protocol with no `adb forward` rule. The caller port is 1024 to 65535 and listens on loopback only; the command binds it before it asks the worker for anything. | The caller port is the device port | | `--lease ` | The lease to reach, 1 to 256 characters. | An agent token's only lease; an operator token must name one | | `--url ` | The worker or gateway: `https://`, or `http://` only for `127.0.0.1`, `[::1]` or `localhost`; the origin only, with no path, query or fragment (a trailing `/` is fine); at most 2048 characters. A `--url` that is not, is a usage error. | `SIMLOCK_URL` | | `--token ` | The bearer token, 1 to 4096 characters. | `SIMLOCK_TOKEN` | -It prints one line per tunnel, `reverse device: -> localhost: (lease )`, and runs until you press Ctrl-C or the process gets SIGTERM, which close the tunnels and exit 0. A tunnel whose caller port has nothing listening writes a warning to stderr at most once every 10 seconds and stays open. A missing `--url`, token or lease, an invalid port, or a repeated caller port is a usage error (exit 2). A refusal exits 1 with its code, for example `TUNNEL_BAD_PORT` for a device port below 1024. A lost connection, 45 seconds with no message or ping, or 90 seconds with no answer to the request exits 1 with `TUNNEL_DISCONNECTED`; the lease ending exits 14 with `TUNNEL_LEASE_ENDED`. +It prints one line per tunnel, `reverse device: -> localhost: (lease )` or `forward localhost: -> device: (lease )`, and runs until you press Ctrl-C or the process gets SIGTERM, which close the tunnels and exit 0. A reverse tunnel whose caller port has nothing listening writes a warning to stderr at most once every 10 seconds and stays open. A connection to a forward tunnel waits until the worker confirms the tunnels, and closes if the worker refuses; one to a device port with nothing listening is closed. A forward caller port already in use exits 1 with `TUNNEL_CALLER_PORT_IN_USE` before anything is set up on the device. Every caller port is closed when the command ends. A missing `--url`, token or lease, an invalid port, a forward caller port below 1024, or a repeated caller port is a usage error (exit 2). A refusal exits 1 with its code, for example `TUNNEL_BAD_PORT` for a device port below 1024. A lost connection, 45 seconds with no message or ping, or 90 seconds with no answer to the request exits 1 with `TUNNEL_DISCONNECTED`; the lease ending exits 14 with `TUNNEL_LEASE_ENDED`. ## simlock catalog diff --git a/website/src/content/docs/docs/reference/errors.mdx b/website/src/content/docs/docs/reference/errors.mdx index 16892501c..b3c76802d 100644 --- a/website/src/content/docs/docs/reference/errors.mdx +++ b/website/src/content/docs/docs/reference/errors.mdx @@ -78,14 +78,14 @@ A lease's tunnel socket (`GET /v1/leases/{id}/tunnel`, on a worker with `capabil | Code | Exit | HTTP | Meaning | What to do | | --- | --- | --- | --- | --- | -| `TUNNEL_UNSUPPORTED` | 1 | 422 | The lease is on an iOS simulator or an iPhone, or the tunnel is a `forward` tunnel, which is not available yet. | Use an Android emulator or phone, and `reverse` tunnels. | +| `TUNNEL_UNSUPPORTED` | 1 | 422 | The lease is on an iOS simulator or an iPhone. | Use an Android emulator or phone. | | `TUNNEL_PORT_IN_USE` | 1 | 409 | The device port is already reversed on the device, for example by an `adb reverse` run through `device.exec`. | Remove that rule first. | | `TUNNEL_BAD_PORT` | 1 | 422 | A device port is an integer outside 1024 to 65535. A port that is not an integer at all is refused `BAD_REQUEST`. | Name a port in that range. | | `TUNNEL_LIMIT` | 1 | 409 | The lease would have more than 8 tunnels across its sockets. | Close a tunnel first. | | `TUNNEL_FAILED` | 1 | 502 | `adb` could not set the tunnel up, or the worker has no free loopback port in its reserved range. The message carries adb's own words. | Read the message; try again. | | `TUNNEL_UNAVAILABLE` | 1 | 503 | A gateway's worker has tunnels off. | Turn on `capabilities.tunnel.enabled` on the worker. | | `TUNNEL_DISCONNECTED` | 1 | 503 | The tunnel client lost its connection. | Open the tunnel again. | -| `TUNNEL_CALLER_PORT_IN_USE` | 1 | 409 | The port the tunnel client listens on is in use on its machine. | Pick another caller port. | +| `TUNNEL_CALLER_PORT_IN_USE` | 1 | 409 | The caller port a `forward` tunnel listens on is in use on your machine. | Pick another caller port. | | `TUNNEL_LEASE_ENDED` | 14 | 410 | The lease ended while the tunnel was open. | Take a new lease. | ## Running commands on a device diff --git a/website/src/content/docs/docs/using-devices/remote-agents.mdx b/website/src/content/docs/docs/using-devices/remote-agents.mdx index 8d4dd7097..0d2185a88 100644 --- a/website/src/content/docs/docs/using-devices/remote-agents.mdx +++ b/website/src/content/docs/docs/using-devices/remote-agents.mdx @@ -179,11 +179,12 @@ Send the same calls to the gateway, with a token created on the gateway. The gat A holder with its own WebSocket client can reach its leased Android device's ports from the worker's side. Open `GET /v1/leases//tunnel` as a WebSocket with your token, on a worker that has `capabilities.tunnel.enabled: true`, or on a gateway whose lease's worker has it (it is off by default; turn it on at the gateway and at the worker, as with input). Through a gateway the socket is relayed to the lease's worker with the same frames, each up to 65541 bytes; a frame longer than that is refused `BAD_REQUEST` and the socket closes with 4003. The lease's holder and an operator may open it; anyone else gets `404`, as for an unknown lease, and a plain `GET` gets `426`. -Each message is one binary frame: a tag byte, a 4-byte big-endian connection number and a payload. The first frame is `HELLO` (tag `0x01`, connection 0) with JSON of at most 4 KiB: `{"tunnels":[{"kind":"reverse","devicePort":5173}]}`. Name 1 to 8 tunnels per lease, across all its sockets, with device ports from 1024 to 65535. Only `reverse` works today. +Each message is one binary frame: a tag byte, a 4-byte big-endian connection number and a payload. The first frame is `HELLO` (tag `0x01`, connection 0) with JSON of at most 4 KiB: `{"tunnels":[{"kind":"reverse","devicePort":5173}]}`. Name 1 to 8 tunnels per lease, across all its sockets, with device ports from 1024 to 65535. A tunnel is `reverse` (the device reaches you) or `forward` (you reach the device). - The worker answers `READY` (`0x81`) with the same list. Each connection the device then makes to `localhost:` arrives as `OPEN` (`0x02`, JSON `{kind, devicePort}`, odd connection numbers), and its bytes flow as `DATA` (`0x03`, up to 65536 bytes) both ways. - Each direction of a connection starts with a 262144-byte window. The reader grants more with `CREDIT` (`0x04`, a 4-byte count); a reader that grants none pauses that connection and no other. -- `END` (`0x05`) closes one direction and leaves the other open. `RESET` (`0x06`) from you closes the connection. A worker closes a device connection at once when 256 are already open on the socket. +- For a `forward` tunnel you open the connection: send `OPEN` with an even connection number above your last one and JSON `{"kind":"forward","devicePort":}` naming a `forward` tunnel of this socket, then `DATA` at once. The worker opens the device port through adb's host protocol, with no `adb forward` rule, and answers `RESET` (JSON `{reason}`) when the device port has nothing listening, does not answer within 5 seconds (reason `timeout`), or 256 connections are already open on the socket (reason `too many connections`). An `OPEN` that breaks these rules is refused `BAD_REQUEST`. +- `END` (`0x05`) closes one direction and leaves the other open. `RESET` (`0x06`) from you closes the connection. A worker closes a device connection at once when 256 are already open on the socket, counting yours and the device's together. - A `HELLO` the worker cannot meet gets `REFUSED` (`0x82`, JSON `{code, message}`) and the socket closes with 4003; nothing it named stays set up. The codes are in the [errors reference](/docs/reference/errors/#tunnels). A frame that breaks the protocol is refused `BAD_REQUEST` the same way. - The socket closes `4001` with the lease-end reason when the lease ends, and `1001` when the daemon stops. Through a gateway it also closes `1011` when the lease's worker stops or stops answering, and `1001` when the gateway stops. A worker with tunnels off answers `503 TUNNEL_UNAVAILABLE` before the upgrade, and one that gives no answer within 10 seconds `503 WORKER_UNREACHABLE`. Closing the socket removes the device's `adb reverse` rule before the lease can end.