diff --git a/crates/ide-dap/src/debugpy.rs b/crates/ide-dap/src/debugpy.rs index ee6dced0e9..f65c883897 100644 --- a/crates/ide-dap/src/debugpy.rs +++ b/crates/ide-dap/src/debugpy.rs @@ -25,10 +25,10 @@ pub(crate) async fn require_free_port(arguments: &Value) -> Result<(), IdeError> loop { match std::net::TcpListener::bind((host, port)) { Ok(_) => return Ok(()), - Err(e) if tokio::time::Instant::now() >= deadline => { - return Err(IdeError::unavailable(format!("Cannot listen on {host}:{port}: {e}"))); + Err(e) if e.kind() == std::io::ErrorKind::AddrInUse && tokio::time::Instant::now() < deadline => { + tokio::time::sleep(Duration::from_millis(100)).await; } - Err(_) => tokio::time::sleep(Duration::from_millis(100)).await, + Err(e) => return Err(IdeError::unavailable(format!("Cannot listen on {host}:{port}: {e}"))), } } } @@ -84,6 +84,15 @@ mod tests { assert!(require_free_port(&listen).await.is_ok()); } + #[tokio::test] + async fn an_address_the_machine_lacks_is_reported_at_once() { + // 192.0.2.0/24 is reserved for documentation, never a local address. + let started = std::time::Instant::now(); + let e = require_free_port(&json!({"listen": {"host": "192.0.2.1", "port": 5678}})).await.unwrap_err(); + assert!(e.to_string().contains("Cannot listen on 192.0.2.1:5678"), "{e}"); + assert!(started.elapsed() < Duration::from_secs(1)); + } + #[tokio::test] async fn waits_for_the_previous_adapter_to_release_the_port() { let previous = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap(); diff --git a/docs/en/languages/python.mdx b/docs/en/languages/python.mdx index cbfc0e1e6e..dfe106ea37 100644 --- a/docs/en/languages/python.mdx +++ b/docs/en/languages/python.mdx @@ -142,7 +142,7 @@ Python debugging uses debugpy. If it is missing when you start a debug session, - Debugging `manage.py` enables Django support in debugpy. - **Attach to Process…** (`⌥⇧F5` / `Ctrl+Alt+F5`) lists local Python processes under **Python (debugpy)**. - The **Python Remote Debug (debugpy)** configuration attaches to a process started with `python -m debugpy --listen`, locally or on another machine, with local and remote root mapping. -- The **Python Debug Server** configuration works the other way round: the IDE listens and the program connects with `import debugpy; debugpy.connect(("localhost", 5678)); debugpy.wait_for_client()`, from a container or another machine too. Install the IDE debugger's debugpy version where the program runs; the Debug console warns when they differ. +- The **Python Debug Server** configuration works the other way round: the IDE listens and the program connects with `import debugpy; debugpy.connect(("localhost", 5678)); debugpy.wait_for_client()`, from a container or another machine too. Install the IDE debugger's debugpy version where the program runs; the Debug console warns when they differ. A VS Code `attach` with `"listen"` imports as this configuration; its `listen.host` `0.0.0.0` is where VS Code binds, so it imports as `localhost`. For a program in a container or on another machine, set the IDE host name to an address it can reach, such as `host.docker.internal`. Options: diff --git a/docs/zh/languages/python.mdx b/docs/zh/languages/python.mdx index 47aea6c9b7..d20b7b838a 100644 --- a/docs/zh/languages/python.mdx +++ b/docs/zh/languages/python.mdx @@ -142,7 +142,7 @@ Python 调试使用 debugpy。开始调试时如果缺少 debugpy,OpenIDEA 会 - 调试 `manage.py` 时会开启 debugpy 的 Django 支持。 - **附加到进程…**(`⌥⇧F5` / `Ctrl+Alt+F5`)会在 **Python (debugpy)** 分组下列出本机的 Python 进程。 - **Python 远程调试 (debugpy)** 配置可以附加到用 `python -m debugpy --listen` 启动的进程,本机或远程机器都可以,并支持本地与远程根目录映射。 -- **Python 调试服务器** 配置方向相反:由 IDE 监听,程序用 `import debugpy; debugpy.connect(("localhost", 5678)); debugpy.wait_for_client()` 连接进来,也可以从容器或其他机器连接。程序所在环境要安装与 IDE 调试器相同版本的 debugpy,版本不同时调试控制台会给出警告。 +- **Python 调试服务器** 配置方向相反:由 IDE 监听,程序用 `import debugpy; debugpy.connect(("localhost", 5678)); debugpy.wait_for_client()` 连接进来,也可以从容器或其他机器连接。程序所在环境要安装与 IDE 调试器相同版本的 debugpy,版本不同时调试控制台会给出警告。VS Code 里带 `"listen"` 的 `attach` 会导入成这种配置;其中 `listen.host` 的 `0.0.0.0` 是 VS Code 的绑定地址,所以导入成 `localhost`。程序在容器或其他机器上时,要把 IDE 主机名改成程序能访问到的地址,例如 `host.docker.internal`。 相关选项: diff --git a/src/features/debugger/__tests__/remote.test.ts b/src/features/debugger/__tests__/remote.test.ts index 7298fc2048..7aa9d178bf 100644 --- a/src/features/debugger/__tests__/remote.test.ts +++ b/src/features/debugger/__tests__/remote.test.ts @@ -167,9 +167,14 @@ describe("remote attach requests", () => { redirectOutput: true, justMyCode: expect.any(Boolean), }); - expect(listen({ host: "::1", port: "5679" }).listen).toEqual({ host: "::1", port: 5679 }); - expect(listen({ host: "127.0.0.2" }).listen.host).toBe("127.0.0.1"); + // Every loopback form stays on loopback; IPv6 loopback on 127.0.0.1, which every debugpy listens on. + expect(listen({ host: "::1", port: "5679" }).listen).toEqual({ host: "127.0.0.1", port: 5679 }); + for (const host of ["[::1]", "0:0:0:0:0:0:0:1", "::ffff:127.0.0.1", "LOCALHOST"]) + expect(listen({ host }).listen.host, host).toBe("127.0.0.1"); + expect(listen({ host: "127.0.0.2" }).listen.host).toBe("127.0.0.2"); + expect(listen({ host: "127.1" }).listen.host).toBe("127.0.0.1"); expect(listen({ host: "fd00::5" }).listen.host).toBe("::"); + expect(listen({ host: "a b" }).listen.host).toBe("a b"); expect(listen({ host: "host.docker.internal", remoteRoot: "/app" })).toMatchObject({ listen: { host: "0.0.0.0", port: 5678 }, pathMappings: [{ localRoot: "/p", remoteRoot: "/app" }], @@ -183,8 +188,12 @@ describe("remote attach requests", () => { 'import debugpy; debugpy.connect(("host.docker.internal", 5679)); debugpy.wait_for_client()', ); expect(remote.debugpyConnectLine({ host: 'a"b' })).toContain('connect(("a\\"b", 5678))'); - // Python's connect takes an IPv6 address without brackets. - expect(remote.debugpyConnectLine({ host: "[::1]" })).toContain('connect(("::1", 5678))'); + // Python's connect takes an IPv6 address without brackets; IPv6 loopback connects where the IDE listens. + expect(remote.debugpyConnectLine({ host: "[fd00::5]" })).toContain('connect(("fd00::5", 5678))'); + expect(remote.debugpyConnectLine({ host: "[::1]" })).toContain('connect(("127.0.0.1", 5678))'); + expect(remoteWaitingNote(configOf(remote.pythonDebugServerType, { host: "::1" }), false, true)).toContain( + "connection on 127.0.0.1:5678…", + ); }); it("Python Debug Server says it waits for a connection until the program connects, and listens again", () => { diff --git a/src/features/debugger/remote.ts b/src/features/debugger/remote.ts index a1bad41fd8..a4666946af 100644 --- a/src/features/debugger/remote.ts +++ b/src/features/debugger/remote.ts @@ -199,18 +199,37 @@ export const pythonRemoteType: RunConfigTypeContribution = { /** The line the program runs to connect, in place of PyCharm's `pydevd_pycharm.settrace(...)`. */ export function debugpyConnectLine(p: Params): string { - const host = hostOf(p) - .replace(/^\[(.*)\]$/, "$1") - .replace(/\\/g, "\\\\") - .replace(/"/g, '\\"'); + const host = connectHost(hostOf(p)).replace(/\\/g, "\\\\").replace(/"/g, '\\"'); return `import debugpy; debugpy.connect(("${host}", ${portOf(p, 5678)})); debugpy.wait_for_client()`; } -/** Where the adapter listens: loopback for a local program, every interface (IPv4 or IPv6) otherwise. */ +/** The host as the URL parser normalises it (`127.1`, `0:0:0:0:0:0:0:1`), IPv6 in brackets; null when not a host. */ +function canonicalHost(host: string): string | null { + try { + return new URL(`http://${host.includes(":") && !host.startsWith("[") ? `[${host}]` : host}`).hostname; + } catch { + return null; + } +} + +/** IPv6 loopback, plain or IPv4-mapped. */ +const IPV6_LOOPBACK = /^\[(::1|::ffff:7f[0-9a-f]{2}:[0-9a-f]{1,4})\]$/; + +/** Where the adapter listens: loopback for a local program, every interface (IPv4 or IPv6) otherwise. + * IPv6 loopback listens on 127.0.0.1: debugpy's adapter before 1.8 listens on IPv4 only, and leaves an + * `attach` it cannot listen for unanswered. */ function listenAddress(host: string): string { - if (/^(::1|\[::1\])$/.test(host)) return "::1"; - if (/^(localhost|127(\.\d+){3})$/i.test(host)) return "127.0.0.1"; - return host.includes(":") ? "::" : "0.0.0.0"; + const h = canonicalHost(host); + if (h == null) return host; // Not a host: the port check reports it. + if (h === "localhost" || IPV6_LOOPBACK.test(h)) return "127.0.0.1"; + if (/^127\./.test(h)) return h; + return h.startsWith("[") ? "::" : "0.0.0.0"; +} + +/** The host the program connects to: where the adapter listens for IPv6 loopback, as given otherwise. */ +function connectHost(host: string): string { + const h = canonicalHost(host); + return h != null && IPV6_LOOPBACK.test(h) ? "127.0.0.1" : host.replace(/^\[(.*)\]$/, "$1"); } export const pythonDebugServerType: RunConfigTypeContribution = { @@ -503,7 +522,7 @@ export function remoteWaitingNote( const p = rc?.params ?? {}; if (listensAgain(rc)) { if (!connecting) return null; - const address = serverAddress(hostOf(p), portOf(p, 5678)); + const address = serverAddress(connectHost(hostOf(p)), portOf(p, 5678)); const line = debugpyConnectLine(p); return tx`Waiting for process connection on ${address}…` + "\n" + tx`Add to the program: ${line}`; }