Skip to content

Commit 0e53038

Browse files
fix(server): skip Windows-owned ports when starting in WSL
Under WSL's default NAT networking, Windows reaches the server through localhost forwarding, which fails for a port a Windows process already listens on even though WSL can bind it. Automatic startup now reads one Windows TCP/TCPv6 listener snapshot and skips ports in it, including fallback candidates. Explicit ports, bootstrap ports, and desktop mode are unchanged. If the snapshot cannot be read, startup keeps the local choice and logs a warning.
1 parent 30a9d32 commit 0e53038

5 files changed

Lines changed: 274 additions & 2 deletions

File tree

Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
1+
import { describe, expect, it } from "@effect/vitest";
2+
import * as NetService from "@t3tools/shared/Net";
3+
import * as Effect from "effect/Effect";
4+
import * as FileSystem from "effect/FileSystem";
5+
import * as Layer from "effect/Layer";
6+
import * as PlatformError from "effect/PlatformError";
7+
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
8+
9+
import * as ProcessRunner from "../processRunner.ts";
10+
import * as AutomaticPort from "./automaticPort.ts";
11+
12+
const WSL_KERNEL = "6.6.87.2-microsoft-standard-WSL2\n";
13+
const NETSTAT_PATH = "/windows/c/Windows/System32/netstat.exe";
14+
15+
const output = (stdout: string, code: number | null = null): ProcessRunner.ProcessRunOutput => ({
16+
stdout,
17+
stderr: "",
18+
code: code === null ? null : ChildProcessSpawner.ExitCode(code),
19+
timedOut: false,
20+
stdoutTruncated: false,
21+
stderrTruncated: false,
22+
stdoutInvalidUtf8: false,
23+
stderrInvalidUtf8: false,
24+
});
25+
26+
const listening = (ports: ReadonlyArray<number>, host = "127.0.0.1", foreign = "0.0.0.0:0") =>
27+
ports.map((port) => ` TCP ${host}:${port} ${foreign} ABHÖREN 4242`).join("\r\n");
28+
29+
interface Scenario {
30+
readonly kernelRelease?: string;
31+
readonly windowsPorts?: ReadonlyArray<number>;
32+
readonly windowsPortsV6?: ReadonlyArray<number>;
33+
readonly tcpv6ExitCode?: number;
34+
readonly wslpathMissing?: boolean;
35+
readonly reservedPorts?: ReadonlyArray<number>;
36+
}
37+
38+
const select = (scenario: Scenario) => {
39+
const commands: string[] = [];
40+
const reserved = [...(scenario.reservedPorts ?? [50_001])];
41+
const net: NetService.NetServiceShape = {
42+
canListenOnHost: () => Effect.succeed(true),
43+
hasListenerOnHost: () => Effect.succeed(false),
44+
isPortAvailableOnLoopback: () => Effect.succeed(true),
45+
reserveLoopbackPort: () => Effect.sync(() => reserved.shift() ?? 60_000),
46+
findAvailablePort: Effect.succeed,
47+
};
48+
const run: ProcessRunner.ProcessRunner["Service"]["run"] = (input) => {
49+
commands.push(input.command);
50+
if (input.command === "wslpath") {
51+
if (scenario.wslpathMissing) {
52+
return Effect.fail(
53+
new ProcessRunner.ProcessSpawnError({
54+
command: input.command,
55+
argumentCount: input.args.length,
56+
cause: PlatformError.systemError({
57+
_tag: "NotFound",
58+
module: "ChildProcess",
59+
method: "spawn",
60+
}),
61+
}),
62+
);
63+
}
64+
return Effect.succeed(output(`${NETSTAT_PATH}\n`));
65+
}
66+
if (input.args.includes("tcpv6")) {
67+
return Effect.succeed(
68+
output(
69+
listening(scenario.windowsPortsV6 ?? [], "[::1]", "[::]:0"),
70+
scenario.tcpv6ExitCode ?? null,
71+
),
72+
);
73+
}
74+
return Effect.succeed(output(listening(scenario.windowsPorts ?? [])));
75+
};
76+
const layer = Layer.mergeAll(
77+
Layer.succeed(NetService.NetService, net),
78+
Layer.succeed(ProcessRunner.ProcessRunner, { run }),
79+
FileSystem.layerNoop({
80+
readFileString: (path) =>
81+
path === "/proc/sys/kernel/osrelease" && scenario.kernelRelease !== undefined
82+
? Effect.succeed(scenario.kernelRelease)
83+
: Effect.fail(
84+
PlatformError.systemError({
85+
_tag: "NotFound",
86+
module: "FileSystem",
87+
method: "readFileString",
88+
}),
89+
),
90+
}),
91+
);
92+
return Effect.gen(function* () {
93+
const selectAutomaticPort = yield* AutomaticPort.make;
94+
const port = yield* selectAutomaticPort(3773);
95+
return { port, commands };
96+
}).pipe(Effect.provide(layer));
97+
};
98+
99+
describe("automatic port selection", () => {
100+
it.effect("moves off the default port only when Windows already listens on it", () =>
101+
Effect.gen(function* () {
102+
const free = yield* select({ kernelRelease: WSL_KERNEL, windowsPorts: [8080] });
103+
expect(free.port).toBe(3773);
104+
expect(free.commands).toEqual(["wslpath", NETSTAT_PATH, NETSTAT_PATH]);
105+
106+
const owned = yield* select({ kernelRelease: WSL_KERNEL, windowsPorts: [3773] });
107+
expect(owned.port).toBe(50_001);
108+
}),
109+
);
110+
111+
it.effect("retries a fallback port that Windows already listens on", () =>
112+
Effect.gen(function* () {
113+
const result = yield* select({
114+
kernelRelease: WSL_KERNEL,
115+
windowsPorts: [3773],
116+
windowsPortsV6: [50_001],
117+
reservedPorts: [50_001, 50_002],
118+
});
119+
expect(result.port).toBe(50_002);
120+
}),
121+
);
122+
123+
it.effect("keeps the local choice when the Windows snapshot is unavailable", () =>
124+
Effect.gen(function* () {
125+
const partial = yield* select({
126+
kernelRelease: WSL_KERNEL,
127+
windowsPorts: [3773],
128+
tcpv6ExitCode: 1,
129+
});
130+
expect(partial.port).toBe(3773);
131+
132+
const noInterop = yield* select({ kernelRelease: WSL_KERNEL, wslpathMissing: true });
133+
expect(noInterop.port).toBe(3773);
134+
}),
135+
);
136+
137+
it.effect("never queries Windows outside WSL", () =>
138+
Effect.gen(function* () {
139+
for (const scenario of [
140+
{ kernelRelease: "6.8.0-45-generic\n" },
141+
// macOS and Windows have no kernel release file.
142+
{},
143+
] satisfies ReadonlyArray<Scenario>) {
144+
const result = yield* select(scenario);
145+
expect(result.port).toBe(3773);
146+
expect(result.commands).toEqual([]);
147+
}
148+
}),
149+
);
150+
});
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
import * as NetService from "@t3tools/shared/Net";
2+
import * as Duration from "effect/Duration";
3+
import * as Effect from "effect/Effect";
4+
import * as FileSystem from "effect/FileSystem";
5+
import * as CliError from "effect/cli/CliError";
6+
7+
import { queryWindowsTcpListeners } from "../process/windowsTcpListeners.ts";
8+
import * as ProcessRunner from "../processRunner.ts";
9+
10+
const KERNEL_RELEASE_PATH = "/proc/sys/kernel/osrelease";
11+
const WINDOWS_NETSTAT_PATH = String.raw`C:\Windows\System32\netstat.exe`;
12+
const FALLBACK_ATTEMPTS = 8;
13+
14+
export type WindowsHostListeners =
15+
| { readonly kind: "known"; readonly ports: ReadonlySet<number> }
16+
| { readonly kind: "unavailable" };
17+
18+
const UNAVAILABLE: WindowsHostListeners = { kind: "unavailable" };
19+
20+
/**
21+
* Picks the startup port when none was configured. Under WSL's default NAT networking, Windows
22+
* reaches the server through localhost forwarding, which fails for a port a Windows process
23+
* already listens on even though WSL can bind it.
24+
*/
25+
export const make = Effect.gen(function* () {
26+
const net = yield* NetService.NetService;
27+
const fs = yield* FileSystem.FileSystem;
28+
const processRunner = yield* ProcessRunner.ProcessRunner;
29+
30+
// Services started by systemd lack WSL_DISTRO_NAME and WSL_INTEROP; the kernel release does not.
31+
// Hosts without this file (macOS, Windows) are not WSL.
32+
const isWsl = fs.readFileString(KERNEL_RELEASE_PATH).pipe(
33+
Effect.map((release) => release.toLowerCase().includes("microsoft")),
34+
Effect.orElseSucceed(() => false),
35+
);
36+
37+
const readWindowsHostListeners = Effect.gen(function* () {
38+
// The automount root is configurable, so `/mnt/c` is not guaranteed.
39+
const netstat = yield* processRunner.run({
40+
command: "wslpath",
41+
args: ["-u", WINDOWS_NETSTAT_PATH],
42+
timeout: Duration.seconds(5),
43+
});
44+
const netstatPath = netstat.stdout.trim();
45+
if ((netstat.code !== null && netstat.code !== 0) || netstatPath.length === 0) {
46+
return UNAVAILABLE;
47+
}
48+
const listeners = yield* queryWindowsTcpListeners(processRunner, netstatPath);
49+
if (listeners === null) return UNAVAILABLE;
50+
return {
51+
kind: "known",
52+
ports: new Set(listeners.map((listener) => listener.port)),
53+
} satisfies WindowsHostListeners;
54+
}).pipe(Effect.orElseSucceed(() => UNAVAILABLE));
55+
56+
return Effect.fn("automaticPort.select")(function* (preferred: number) {
57+
if (!(yield* isWsl)) return yield* net.findAvailablePort(preferred);
58+
const windows = yield* readWindowsHostListeners;
59+
if (windows.kind === "unavailable") {
60+
yield* Effect.logWarning(
61+
"Could not list Windows TCP listeners from WSL; Windows may be unable to reach the selected port. Pass --port to choose one.",
62+
);
63+
return yield* net.findAvailablePort(preferred);
64+
}
65+
if (!windows.ports.has(preferred) && (yield* net.isPortAvailableOnLoopback(preferred))) {
66+
return preferred;
67+
}
68+
// Linux and Windows ephemeral ranges overlap, so fallback ports can collide too.
69+
for (let attempt = 0; attempt < FALLBACK_ATTEMPTS; attempt += 1) {
70+
const port = yield* net.reserveLoopbackPort();
71+
if (!windows.ports.has(port)) return port;
72+
}
73+
return yield* new CliError.UserError({
74+
cause:
75+
"Windows is already using every port T3 Code tried. Pass --port or set T3CODE_PORT to a port Windows is not using.",
76+
});
77+
});
78+
});

‎apps/server/src/cli/config.test.ts‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -652,6 +652,43 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
652652
tailscaleServePort: Option.none<number>(),
653653
});
654654

655+
it.effect("uses the automatic port selector only when no port is configured", () =>
656+
Effect.gen(function* () {
657+
const baseDir = yield* FileSystem.FileSystem.pipe(
658+
Effect.flatMap((fs) => fs.makeTempDirectoryScoped({ prefix: "t3-cli-auto-port-" })),
659+
);
660+
const selected: number[] = [];
661+
const selectAutomaticPort = (preferred: number) =>
662+
Effect.sync(() => {
663+
selected.push(preferred);
664+
return 50_123;
665+
});
666+
const resolvePort = (flags: {
667+
readonly mode?: Option.Option<"web" | "desktop">;
668+
readonly port: Option.Option<number>;
669+
}) =>
670+
resolveServerConfig({ ...minimalWebFlags(baseDir), ...flags }, Option.none(), {
671+
selectAutomaticPort,
672+
}).pipe(
673+
Effect.map((config) => config.port),
674+
Effect.provide(
675+
Layer.merge(
676+
NetService.layer,
677+
ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
678+
),
679+
),
680+
);
681+
682+
expect(yield* resolvePort({ port: Option.none() })).toBe(50_123);
683+
expect(selected).toEqual([3773]);
684+
expect(yield* resolvePort({ port: Option.some(8788) })).toBe(8788);
685+
expect(
686+
yield* resolvePort({ mode: Option.some("desktop" as const), port: Option.none() }),
687+
).toBe(3773);
688+
expect(selected).toEqual([3773]);
689+
}),
690+
);
691+
655692
it.effect(
656693
"resolves each signal's endpoint through T3CODE_OTLP_*_URL, an OTEL endpoint, the bootstrap envelope, and persisted Settings, in that order",
657694
() =>

‎apps/server/src/cli/config.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -256,9 +256,13 @@ export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(funct
256256
readonly startupPresentation?: ServerConfig.StartupPresentation;
257257
readonly forceAutoBootstrapProjectFromCwd?: boolean;
258258
readonly rejectRunningServer?: boolean;
259+
readonly selectAutomaticPort?: (
260+
preferred: number,
261+
) => Effect.Effect<number, NetService.NetError | CliError.UserError>;
259262
},
260263
) {
261264
const { findAvailablePort } = yield* NetService.NetService;
265+
const selectAutomaticPort = options?.selectAutomaticPort ?? findAvailablePort;
262266
const path = yield* Path.Path;
263267
const fs = yield* FileSystem.FileSystem;
264268
const env = yield* EnvServerConfig;
@@ -304,7 +308,7 @@ export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(funct
304308
if (mode === "desktop") {
305309
return Effect.succeed(ServerConfig.DEFAULT_PORT);
306310
}
307-
return findAvailablePort(ServerConfig.DEFAULT_PORT);
311+
return selectAutomaticPort(ServerConfig.DEFAULT_PORT);
308312
},
309313
},
310314
);

‎apps/server/src/cli/server.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,9 @@ import * as CliError from "effect/cli/CliError";
88

99
import * as ServerConfig from "../config.ts";
1010
import { awaitLauncherLoss } from "../launcherWatch.ts";
11+
import * as ProcessRunner from "../processRunner.ts";
1112
import { runServer } from "../server.ts";
13+
import * as AutomaticPort from "./automaticPort.ts";
1214
import { type CliServerFlags, resolveServerConfig, sharedServerCommandFlags } from "./config.ts";
1315

1416
const encodeCommand = Schema.encodeEffect(Schema.fromJsonString(Schema.String));
@@ -22,7 +24,8 @@ const runServerCommand = Effect.fn("server.runServerCommand")(function* (
2224
},
2325
) {
2426
const logLevel = yield* GlobalFlag.LogLevel;
25-
const config = yield* resolveServerConfig(flags, logLevel, options);
27+
const selectAutomaticPort = yield* AutomaticPort.make.pipe(Effect.provide(ProcessRunner.layer));
28+
const config = yield* resolveServerConfig(flags, logLevel, { ...options, selectAutomaticPort });
2629
const run = runServer.pipe(Effect.provideService(ServerConfig.ServerConfig, config));
2730
if (config.mode !== "desktop" || config.desktopBootstrapToken === undefined) return yield* run;
2831
return yield* Effect.raceFirst(

0 commit comments

Comments
 (0)