Open History to see the last commit
1import { listensOnLoopback } from "@t3tools/shared/hostClassification";
2import * as NetService from "@t3tools/shared/Net";
3import * as Duration from "effect/Duration";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as CliError from "effect/cli/CliError";
7
8import { queryWindowsTcpListeners } from "../process/windowsTcpListeners.ts";
9import * as ProcessRunner from "../processRunner.ts";
10
11const KERNEL_RELEASE_PATH = "/proc/sys/kernel/osrelease";
12const WINDOWS_NETSTAT_PATH = String.raw`C:\Windows\System32\netstat.exe`;
13const FALLBACK_ATTEMPTS = 8;
14
15/**
16 * Picks the startup port when none was configured. Under WSL's default NAT networking, Windows
17 * reaches the server through localhost forwarding, which fails for a port a Windows process
18 * already listens on even though WSL can bind it.
19 */
20export const make = Effect.gen(function* () {
21 const net = yield* NetService.NetService;
22 const fs = yield* FileSystem.FileSystem;
23 const processRunner = yield* ProcessRunner.ProcessRunner;
24
25 // Services started by systemd lack WSL_DISTRO_NAME and WSL_INTEROP; the kernel release does not.
26 // Hosts without this file (macOS, Windows) are not WSL.
27 const isWsl = fs.readFileString(KERNEL_RELEASE_PATH).pipe(
28 Effect.map((release) => release.toLowerCase().includes("microsoft")),
29 Effect.orElseSucceed(() => false),
30 );
31
32 const readWindowsHostListeners = Effect.gen(function* () {
33 // The automount root is configurable, so `/mnt/c` is not guaranteed.
34 const netstat = yield* processRunner.run({
35 command: "wslpath",
36 args: ["-u", WINDOWS_NETSTAT_PATH],
37 timeout: Duration.seconds(5),
38 });
39 const netstatPath = netstat.stdout.trim();
40 if ((netstat.code !== null && netstat.code !== 0) || netstatPath.length === 0) {
41 return null;
42 }
43 const listeners = yield* queryWindowsTcpListeners(processRunner, netstatPath);
44 if (listeners === null) return null;
45 return new Set(listeners.map((listener) => listener.port));
46 }).pipe(Effect.orElseSucceed(() => null));
47
48 return Effect.fn("automaticPort.select")(function* (preferred: number, host: string | undefined) {
49 // Windows localhost forwarding reaches only WSL listeners on loopback or a wildcard address.
50 if (!listensOnLoopback(host) || !(yield* isWsl)) {
51 return yield* net.findAvailablePort(preferred, host);
52 }
53 const windows = yield* readWindowsHostListeners;
54 if (windows === null) {
55 yield* Effect.logWarning(
56 "Could not list Windows TCP listeners from WSL; Windows may be unable to reach the selected port. Pass --port to choose one.",
57 );
58 return yield* net.findAvailablePort(preferred, host);
59 }
60 if (!windows.has(preferred) && (yield* net.isPortAvailableOnLoopback(preferred))) {
61 return preferred;
62 }
63 // Linux and Windows ephemeral ranges overlap, so fallback ports can collide too.
64 for (let attempt = 0; attempt < FALLBACK_ATTEMPTS; attempt += 1) {
65 const port = yield* net.reserveLoopbackPort();
66 if (!windows.has(port)) return port;
67 }
68 return yield* new CliError.UserError({
69 cause:
70 "Windows is already using every port T3 Code tried. Pass --port or set T3CODE_PORT to a port Windows is not using.",
71 });
72 });
73});