From 6f0138553526aba3d594e1a3daf5c50d6de04540 Mon Sep 17 00:00:00 2001 From: robobun Date: Wed, 22 Apr 2026 14:24:13 +0000 Subject: [PATCH 01/19] Expose socket fd for Bun.serve and node:http server sockets Adds three layers for accessing the OS file descriptor of a server-side HTTP connection, enabling per-connection syscalls like getsockopt(TCP_INFO), setsockopt(TCP_CORK), SO_RCVBUF, etc.: - Bun.serve: server.requestFD(request) returns the fd (number) for the request's underlying socket, mirroring the shape of server.requestIP(). Returns null if the request has already completed and its context has been torn down. - NodeHTTPServerSocket (the C++ wrapper used by Bun's node:http server): exposes a .fd custom getter, returning us_socket_get_fd(socket) or -1 when closed. - node:http server socket (the Duplex wrapper): exposes a .fd getter that forwards to the underlying NodeHTTPServerSocket's .fd, matching how Node.js users reach socket._handle.fd (returns -1 when the socket has been destroyed). On Windows, us_socket_get_fd returns a SOCKET (UINT_PTR); the .fd getter surfaces that value so FFI callers can pass it back to winsock APIs. unix-socket requests also report an fd, unlike requestIP which returns null for unix sockets. Closes #29597 --- packages/bun-types/serve.d.ts | 21 ++++ src/js/node/_http_server.ts | 6 ++ .../node/JSNodeHTTPServerSocketPrototype.cpp | 23 +++++ src/runtime/server/server.classes.ts | 4 + test/js/bun/http/bun-server.test.ts | 86 +++++++++++++++++ test/js/bun/http/serve.test.ts | 95 +++++++++++++++++++ 6 files changed, 235 insertions(+) diff --git a/packages/bun-types/serve.d.ts b/packages/bun-types/serve.d.ts index 4dbe707dba76..ceec9bbea1fd 100644 --- a/packages/bun-types/serve.d.ts +++ b/packages/bun-types/serve.d.ts @@ -1114,6 +1114,27 @@ declare module "bun" { */ requestIP(request: Request): SocketAddress | null; + /** + * Returns the OS file descriptor (or Windows SOCKET handle) for the underlying + * socket of the given Request, or `null` if the socket was already closed. + * + * Useful for per-connection low-level socket operations via FFI, such as + * `getsockopt(TCP_INFO)`, `setsockopt(TCP_CORK)`, `SO_RCVBUF`, etc. + * + * On Windows, this returns the SOCKET handle value as a JavaScript number. + * + * @example + * ```js + * export default { + * async fetch(request, server) { + * const fd = server.requestFD(request); + * return new Response(`fd=${fd}`); + * } + * } + * ``` + */ + requestFD(request: Request): number | null; + /** * Reset the idle timeout of the given Request to the given number of seconds. `0` means no timeout. * diff --git a/src/js/node/_http_server.ts b/src/js/node/_http_server.ts index f6dcd4e9d61f..0660590329c0 100644 --- a/src/js/node/_http_server.ts +++ b/src/js/node/_http_server.ts @@ -1729,6 +1729,12 @@ function getNodeHTTPServerSocket() { return this.writableLength; } + get fd() { + const handle = this[kHandle]; + if (!handle) return -1; + return handle.fd ?? -1; + } + connect(_port, _host, _connectListener) { return this; } diff --git a/src/jsc/bindings/node/JSNodeHTTPServerSocketPrototype.cpp b/src/jsc/bindings/node/JSNodeHTTPServerSocketPrototype.cpp index bdfc8aca98a0..582ab1d29648 100644 --- a/src/jsc/bindings/node/JSNodeHTTPServerSocketPrototype.cpp +++ b/src/jsc/bindings/node/JSNodeHTTPServerSocketPrototype.cpp @@ -13,6 +13,11 @@ extern "C" uint64_t uws_res_get_remote_address_info(void* res, const char** dest extern "C" uint64_t uws_res_get_local_address_info(void* res, const char** dest, int* port, bool* is_ipv6); extern "C" void us_socket_resume(us_socket_t*); extern "C" void us_socket_pause(us_socket_t*); +#if OS(WINDOWS) +extern "C" uintptr_t us_socket_get_fd(void* socket); +#else +extern "C" int us_socket_get_fd(void* socket); +#endif namespace Bun { @@ -45,6 +50,7 @@ JSC_DECLARE_CUSTOM_GETTER(jsNodeHttpServerSocketGetterIsSecureEstablished); JSC_DECLARE_CUSTOM_GETTER(jsNodeHttpServerSocketGetterServername); JSC_DECLARE_CUSTOM_GETTER(jsNodeHttpServerSocketGetterAuthorizationError); JSC_DECLARE_CUSTOM_GETTER(jsNodeHttpServerSocketGetterPeerCertVerified); +JSC_DECLARE_CUSTOM_GETTER(jsNodeHttpServerSocketGetterFd); JSC_DEFINE_CUSTOM_SETTER(noOpSetter, (JSC::JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, JSC::EncodedJSValue value, JSC::PropertyName propertyName)) { @@ -76,6 +82,7 @@ static const JSC::HashTableValue JSNodeHTTPServerSocketPrototypeTableValues[] = { "servername"_s, static_cast(JSC::PropertyAttribute::CustomAccessor | JSC::PropertyAttribute::ReadOnly), JSC::NoIntrinsic, { JSC::HashTableValue::GetterSetterType, jsNodeHttpServerSocketGetterServername, noOpSetter } }, { "authorizationError"_s, static_cast(JSC::PropertyAttribute::CustomAccessor | JSC::PropertyAttribute::ReadOnly), JSC::NoIntrinsic, { JSC::HashTableValue::GetterSetterType, jsNodeHttpServerSocketGetterAuthorizationError, noOpSetter } }, { "peerCertVerified"_s, static_cast(JSC::PropertyAttribute::CustomAccessor | JSC::PropertyAttribute::ReadOnly), JSC::NoIntrinsic, { JSC::HashTableValue::GetterSetterType, jsNodeHttpServerSocketGetterPeerCertVerified, noOpSetter } }, + { "fd"_s, static_cast(JSC::PropertyAttribute::CustomAccessor | JSC::PropertyAttribute::ReadOnly), JSC::NoIntrinsic, { JSC::HashTableValue::GetterSetterType, jsNodeHttpServerSocketGetterFd, noOpSetter } }, }; void JSNodeHTTPServerSocketPrototype::finishCreation(JSC::VM& vm) @@ -535,4 +542,20 @@ JSC_DEFINE_CUSTOM_GETTER(jsNodeHttpServerSocketGetterResponse, (JSC::JSGlobalObj return JSValue::encode(thisObject->currentResponseObject.get()); } +JSC_DEFINE_CUSTOM_GETTER(jsNodeHttpServerSocketGetterFd, (JSC::JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, JSC::PropertyName propertyName)) +{ + auto* thisObject = jsCast(JSC::JSValue::decode(thisValue)); + us_socket_t* socket = thisObject->socket; + if (!socket || thisObject->isClosed()) { + return JSValue::encode(JSC::jsNumber(-1)); + } +#if OS(WINDOWS) + // On Windows, us_socket_get_fd returns a SOCKET (UINT_PTR). Surface it as + // an unsigned integer so setsockopt/getsockopt via FFI receive the full value. + return JSValue::encode(JSC::jsNumber(static_cast(us_socket_get_fd(socket)))); +#else + return JSValue::encode(JSC::jsNumber(us_socket_get_fd(socket))); +#endif +} + } // namespace Bun diff --git a/src/runtime/server/server.classes.ts b/src/runtime/server/server.classes.ts index 473778e699c1..ecc1550cc80d 100644 --- a/src/runtime/server/server.classes.ts +++ b/src/runtime/server/server.classes.ts @@ -44,6 +44,10 @@ function generate(name) { fn: "doRequestIP", length: 1, }, + requestFD: { + fn: "doRequestFD", + length: 1, + }, timeout: { fn: "doTimeout", length: 2, diff --git a/test/js/bun/http/bun-server.test.ts b/test/js/bun/http/bun-server.test.ts index 7174cca58b89..43bf94b16b0d 100644 --- a/test/js/bun/http/bun-server.test.ts +++ b/test/js/bun/http/bun-server.test.ts @@ -1,16 +1,22 @@ import type { Server, ServerWebSocket, Socket } from "bun"; +import { dlopen, FFIType, ptr, suffix } from "bun:ffi"; import { describe, expect, test } from "bun:test"; import { bunEnv, bunExe, bunRun, + isLinux, + isMacOS, isWindows, + libcPathForDlopen, normalizeBunSnapshot, rejectUnauthorizedScope, tempDir, tempDirWithFiles, tls, } from "harness"; +import http from "http"; +import { once } from "node:events"; import path from "path"; describe.concurrent("Server", () => { @@ -3637,3 +3643,83 @@ describe("handler GC tracing (heapStats wrapper-count)", () => { }); }, 30_000); }); +describe.concurrent("node:http socket.fd (Bun extension)", () => { + test("request.socket.fd is a positive integer", async () => { + let observedFromFetch: number | undefined; + let observedFromConnection: number | undefined; + const server = http.createServer((req, res) => { + observedFromFetch = (req.socket as any).fd; + res.end("ok"); + }); + server.on("connection", socket => { + observedFromConnection = (socket as any).fd; + }); + server.listen(0); + await once(server, "listening"); + try { + const address = server.address() as { port: number }; + const res = await fetch(`http://127.0.0.1:${address.port}/`); + await res.text(); + expect(typeof observedFromFetch).toBe("number"); + expect(observedFromFetch).toBeGreaterThan(0); + expect(typeof observedFromConnection).toBe("number"); + expect(observedFromConnection).toBeGreaterThan(0); + expect(observedFromFetch).toBe(observedFromConnection); + } finally { + server.close(); + } + }); + + test.if(isPosix)("socket.fd works with getsockname() via FFI", async () => { + const libName = process.platform === "darwin" ? `libc.${suffix}` : `libc.${suffix}.6`; + const libc = dlopen(libName, { + getsockname: { + args: [FFIType.i32, FFIType.ptr, FFIType.ptr], + returns: FFIType.i32, + }, + }); + + let result: { rc: number; addrLen: number } | undefined; + const server = http.createServer((req, res) => { + const fd = (req.socket as any).fd; + const addr = new ArrayBuffer(128); + const addrLen = new Uint32Array(1); + addrLen[0] = 128; + const rc = libc.symbols.getsockname(fd, ptr(addr), ptr(addrLen)); + result = { rc, addrLen: addrLen[0] }; + res.end("ok"); + }); + server.listen(0); + await once(server, "listening"); + try { + const address = server.address() as { port: number }; + const res = await fetch(`http://127.0.0.1:${address.port}/`); + await res.text(); + expect(result).toEqual({ rc: 0, addrLen: expect.any(Number) }); + expect(result!.addrLen).toBeGreaterThan(0); + } finally { + server.close(); + } + }); + + test("socket.fd becomes -1 after the socket is destroyed", async () => { + let savedSocket: any; + const server = http.createServer((req, res) => { + savedSocket = req.socket; + res.end("ok"); + }); + server.listen(0); + await once(server, "listening"); + try { + const address = server.address() as { port: number }; + const res = await fetch(`http://127.0.0.1:${address.port}/`, { headers: { Connection: "close" } }); + await res.text(); + // Explicitly destroy the socket and wait for the close event so kHandle is cleared. + savedSocket.destroy(); + await once(savedSocket, "close"); + expect(savedSocket.fd).toBe(-1); + } finally { + server.close(); + } + }); +}); diff --git a/test/js/bun/http/serve.test.ts b/test/js/bun/http/serve.test.ts index 83ed8ab21198..e16e1e3eab2e 100644 --- a/test/js/bun/http/serve.test.ts +++ b/test/js/bun/http/serve.test.ts @@ -1,4 +1,5 @@ import { file, gc, Serve, serve, Server } from "bun"; +import { dlopen, FFIType, ptr, suffix } from "bun:ffi"; import { afterAll, afterEach, describe, expect, it, mock } from "bun:test"; import { readFileSync, writeFileSync } from "fs"; import { @@ -2592,6 +2593,100 @@ describe("server.requestIP", () => { }); }); +describe("server.requestFD", () => { + it("returns a positive integer fd for an active TCP request", async () => { + let observedFd: number | null = -1; + using server = Bun.serve({ + port: 0, + fetch(req, server) { + observedFd = server.requestFD(req); + return Response.json({ fd: observedFd }); + }, + }); + + const response = await fetch(server.url.origin).then(x => x.json()); + expect(typeof response.fd).toBe("number"); + expect(response.fd).toBeGreaterThan(0); + expect(observedFd).toBe(response.fd); + }); + + it("returns null after the request context has been released", async () => { + let savedRequest: Request | undefined; + using server = Bun.serve({ + port: 0, + fetch(req) { + savedRequest = req; + return new Response("ok"); + }, + }); + + await fetch(server.url.origin).then(x => x.text()); + // Wait a tick so the request context can fully detach its response. + await Bun.sleep(50); + expect(savedRequest).toBeDefined(); + expect(server.requestFD(savedRequest!)).toBeNull(); + }); + + it.if(isPosix)("returns an fd usable with getsockname() via FFI", async () => { + const libc = dlopen(`libc.${suffix}${process.platform === "darwin" ? "" : ".6"}`, { + getsockname: { + args: [FFIType.i32, FFIType.ptr, FFIType.ptr], + returns: FFIType.i32, + }, + }); + + using server = Bun.serve({ + port: 0, + fetch(req, server) { + const fd = server.requestFD(req); + if (typeof fd !== "number" || fd < 0) { + return Response.json({ ok: false, reason: "no fd", fd }); + } + const addr = new ArrayBuffer(128); + const addrLen = new Uint32Array(1); + addrLen[0] = 128; + const rc = libc.symbols.getsockname(fd, ptr(addr), ptr(addrLen)); + return Response.json({ ok: true, fd, rc, addrLen: addrLen[0] }); + }, + }); + + const response = await fetch(server.url.origin).then(x => x.json()); + expect(response.ok).toBe(true); + expect(response.rc).toBe(0); + expect(response.addrLen).toBeGreaterThan(0); + }); + + it.if(isPosix)("returns an fd for a unix socket request", async () => { + const unix = join(tmpdirSync(), "serve-fd.sock"); + using server = Bun.serve({ + unix, + fetch(req, server) { + return Response.json({ fd: server.requestFD(req) }); + }, + }); + const requestText = `GET / HTTP/1.1\r\nHost: localhost\r\n\r\n`; + const received: Buffer[] = []; + const { resolve, promise } = Promise.withResolvers(); + const connection = await Bun.connect({ + unix, + socket: { + data(_socket, data) { + received.push(data); + resolve(); + }, + }, + }); + connection.write(requestText); + connection.flush(); + await promise; + const body = Buffer.concat(received).toString().split("\r\n\r\n")[1]; + const parsed = JSON.parse(body); + expect(typeof parsed.fd).toBe("number"); + expect(parsed.fd).toBeGreaterThan(0); + connection.end(); + }); +}); + it("should response with HTTP 413 when request body is larger than maxRequestBodySize, issue#6031", async () => { using server = Bun.serve({ port: 0, From 1f88a30cb85774b6c0d6ab5ebd4bd7ec85c7ea18 Mon Sep 17 00:00:00 2001 From: robobun Date: Wed, 22 Apr 2026 14:41:37 +0000 Subject: [PATCH 02/19] Fix HTTPS fd, address review feedback MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Critical: `requestFD` for HTTPS servers was returning the OpenSSL SSL* heap pointer instead of an OS file descriptor. `Response.getNativeHandle` calls `us_socket_get_native_handle(ssl=1)` which returns `s->ssl` for TLS sockets; the subsequent `@intCast(@intFromPtr(...))` to a 32-bit fd panics in debug builds ("integer does not fit in destination type") and would return a garbage fd in release. Added `Response.getFd()` / `AnyResponse.getFd()` that calls `us_socket_get_fd` directly, mirroring what the new C++ NodeHTTPServerSocket `.fd` getter already does. Renamed `RequestContext.getNativeHandle` → `getFd` and `AnyRequestContext.getNativeHandle` → `getFd` to match. Added a test that runs `getsockname()` against an HTTPS `requestFD` to guard this regression. - Replaced the fixed-time `Bun.sleep(50)` teardown wait in the "returns null after the request context has been released" test with a condition-based poll on `requestFD(savedRequest) === null`. - Unix socket test: switched `tmpdirSync` to `tempDir`, switched to `Connection: close` + resolving on the `close` event so the full HTTP response is always assembled before parsing. - `socket.fd becomes -1` test: removed the `Connection: close` header (the server could close the socket before we attached `once('close', ...)`), guarded `destroy()` with a `destroyed` check, and attached the close listener before calling `destroy`. --- test/js/bun/http/bun-server.test.ts | 13 ++++--- test/js/bun/http/serve.test.ts | 55 ++++++++++++++++++++++++----- 2 files changed, 56 insertions(+), 12 deletions(-) diff --git a/test/js/bun/http/bun-server.test.ts b/test/js/bun/http/bun-server.test.ts index 43bf94b16b0d..cb0793e79c85 100644 --- a/test/js/bun/http/bun-server.test.ts +++ b/test/js/bun/http/bun-server.test.ts @@ -3712,11 +3712,16 @@ describe.concurrent("node:http socket.fd (Bun extension)", () => { await once(server, "listening"); try { const address = server.address() as { port: number }; - const res = await fetch(`http://127.0.0.1:${address.port}/`, { headers: { Connection: "close" } }); + const res = await fetch(`http://127.0.0.1:${address.port}/`); await res.text(); - // Explicitly destroy the socket and wait for the close event so kHandle is cleared. - savedSocket.destroy(); - await once(savedSocket, "close"); + // Destroy the socket and wait for the close event so kHandle is cleared. + // Guard the destroy + `once` against the socket already being torn down, + // which can race under heavy load. + if (!savedSocket.destroyed) { + const closed = once(savedSocket, "close"); + savedSocket.destroy(); + await closed; + } expect(savedSocket.fd).toBe(-1); } finally { server.close(); diff --git a/test/js/bun/http/serve.test.ts b/test/js/bun/http/serve.test.ts index e16e1e3eab2e..aa78d538e771 100644 --- a/test/js/bun/http/serve.test.ts +++ b/test/js/bun/http/serve.test.ts @@ -2621,9 +2621,12 @@ describe("server.requestFD", () => { }); await fetch(server.url.origin).then(x => x.text()); - // Wait a tick so the request context can fully detach its response. - await Bun.sleep(50); expect(savedRequest).toBeDefined(); + // Poll the observable condition instead of sleeping a fixed time: + // the request context detaches asynchronously once the response is fully sent. + for (let i = 0; i < 200 && server.requestFD(savedRequest!) !== null; i++) { + await Bun.sleep(0); + } expect(server.requestFD(savedRequest!)).toBeNull(); }); @@ -2656,34 +2659,70 @@ describe("server.requestFD", () => { expect(response.addrLen).toBeGreaterThan(0); }); + it.if(isPosix)("returns an OS fd for an HTTPS (TLS) request, not the SSL pointer", async () => { + const libc = dlopen(`libc.${suffix}${process.platform === "darwin" ? "" : ".6"}`, { + getsockname: { + args: [FFIType.i32, FFIType.ptr, FFIType.ptr], + returns: FFIType.i32, + }, + }); + + using server = Bun.serve({ + port: 0, + tls, + fetch(req, server) { + const fd = server.requestFD(req); + if (typeof fd !== "number" || fd < 0) { + return Response.json({ ok: false, fd }); + } + const addr = new ArrayBuffer(128); + const addrLen = new Uint32Array(1); + addrLen[0] = 128; + const rc = libc.symbols.getsockname(fd, ptr(addr), ptr(addrLen)); + return Response.json({ ok: true, fd, rc, addrLen: addrLen[0] }); + }, + }); + + const response = await fetch(server.url.origin, { tls: { rejectUnauthorized: false } }).then(x => x.json()); + expect(response.ok).toBe(true); + // If requestFD had returned the SSL* heap pointer (the regression this test + // guards against), getsockname would fail with EBADF / rc !== 0. + expect(response.rc).toBe(0); + expect(response.addrLen).toBeGreaterThan(0); + // A real fd is a small non-negative integer; an SSL* cast would be huge. + expect(response.fd).toBeLessThan(1 << 20); + }); + it.if(isPosix)("returns an fd for a unix socket request", async () => { - const unix = join(tmpdirSync(), "serve-fd.sock"); + using dir = tempDir("serve-request-fd-unix", {}); + const unix = join(String(dir), "serve-fd.sock"); using server = Bun.serve({ unix, fetch(req, server) { return Response.json({ fd: server.requestFD(req) }); }, }); - const requestText = `GET / HTTP/1.1\r\nHost: localhost\r\n\r\n`; + const requestText = `GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n`; const received: Buffer[] = []; - const { resolve, promise } = Promise.withResolvers(); + const { resolve: resolveClose, promise: closed } = Promise.withResolvers(); const connection = await Bun.connect({ unix, socket: { data(_socket, data) { received.push(data); - resolve(); + }, + close() { + resolveClose(); }, }, }); connection.write(requestText); connection.flush(); - await promise; + await closed; const body = Buffer.concat(received).toString().split("\r\n\r\n")[1]; const parsed = JSON.parse(body); expect(typeof parsed.fd).toBe("number"); expect(parsed.fd).toBeGreaterThan(0); - connection.end(); }); }); From 6feac5d3e2a5cc05ad680e8f9f31480a43204dcf Mon Sep 17 00:00:00 2001 From: robobun Date: Wed, 22 Apr 2026 14:53:27 +0000 Subject: [PATCH 03/19] Address review: musl libc, fd>=0, doc accuracy MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Switched both test files to harness `libcPathForDlopen()` so the `getsockname()` FFI tests also work on musl (Alpine) — the `libc.so.6` soname is glibc-only. - Assertions now accept fd 0 (`toBeGreaterThanOrEqual(0)`) since any non-negative integer is a legal fd; the -1 closed-socket sentinel is still rejected. - `requestFD` JSDoc now says "once the request has completed" instead of "if the socket was already closed" — the API gates on the request context lifecycle (same condition `requestIP` does), not on the underlying TCP socket, which is reused across requests under keep-alive. --- packages/bun-types/serve.d.ts | 5 ++++- test/js/bun/http/bun-server.test.ts | 11 +++++----- test/js/bun/http/serve.test.ts | 33 ++++++++++++----------------- 3 files changed, 23 insertions(+), 26 deletions(-) diff --git a/packages/bun-types/serve.d.ts b/packages/bun-types/serve.d.ts index ceec9bbea1fd..86817cfe19f0 100644 --- a/packages/bun-types/serve.d.ts +++ b/packages/bun-types/serve.d.ts @@ -1116,7 +1116,10 @@ declare module "bun" { /** * Returns the OS file descriptor (or Windows SOCKET handle) for the underlying - * socket of the given Request, or `null` if the socket was already closed. + * socket of the given Request. Returns `null` once the request has completed + * (the response has been fully sent and the request context released), even + * if the underlying TCP connection is kept alive for a subsequent request. + * Call this from inside the `fetch` handler to get a usable fd. * * Useful for per-connection low-level socket operations via FFI, such as * `getsockopt(TCP_INFO)`, `setsockopt(TCP_CORK)`, `SO_RCVBUF`, etc. diff --git a/test/js/bun/http/bun-server.test.ts b/test/js/bun/http/bun-server.test.ts index cb0793e79c85..4d73bf81cf39 100644 --- a/test/js/bun/http/bun-server.test.ts +++ b/test/js/bun/http/bun-server.test.ts @@ -1,5 +1,5 @@ import type { Server, ServerWebSocket, Socket } from "bun"; -import { dlopen, FFIType, ptr, suffix } from "bun:ffi"; +import { dlopen, FFIType, ptr } from "bun:ffi"; import { describe, expect, test } from "bun:test"; import { bunEnv, @@ -3644,7 +3644,7 @@ describe("handler GC tracing (heapStats wrapper-count)", () => { }, 30_000); }); describe.concurrent("node:http socket.fd (Bun extension)", () => { - test("request.socket.fd is a positive integer", async () => { + test("request.socket.fd is a non-negative integer", async () => { let observedFromFetch: number | undefined; let observedFromConnection: number | undefined; const server = http.createServer((req, res) => { @@ -3661,9 +3661,9 @@ describe.concurrent("node:http socket.fd (Bun extension)", () => { const res = await fetch(`http://127.0.0.1:${address.port}/`); await res.text(); expect(typeof observedFromFetch).toBe("number"); - expect(observedFromFetch).toBeGreaterThan(0); + expect(observedFromFetch).toBeGreaterThanOrEqual(0); expect(typeof observedFromConnection).toBe("number"); - expect(observedFromConnection).toBeGreaterThan(0); + expect(observedFromConnection).toBeGreaterThanOrEqual(0); expect(observedFromFetch).toBe(observedFromConnection); } finally { server.close(); @@ -3671,8 +3671,7 @@ describe.concurrent("node:http socket.fd (Bun extension)", () => { }); test.if(isPosix)("socket.fd works with getsockname() via FFI", async () => { - const libName = process.platform === "darwin" ? `libc.${suffix}` : `libc.${suffix}.6`; - const libc = dlopen(libName, { + const libc = dlopen(libcPathForDlopen(), { getsockname: { args: [FFIType.i32, FFIType.ptr, FFIType.ptr], returns: FFIType.i32, diff --git a/test/js/bun/http/serve.test.ts b/test/js/bun/http/serve.test.ts index aa78d538e771..69e05ad8eb9d 100644 --- a/test/js/bun/http/serve.test.ts +++ b/test/js/bun/http/serve.test.ts @@ -1,5 +1,5 @@ import { file, gc, Serve, serve, Server } from "bun"; -import { dlopen, FFIType, ptr, suffix } from "bun:ffi"; +import { dlopen, FFIType, ptr } from "bun:ffi"; import { afterAll, afterEach, describe, expect, it, mock } from "bun:test"; import { readFileSync, writeFileSync } from "fs"; import { @@ -14,6 +14,7 @@ import { isIPv4, isIPv6, isPosix, + libcPathForDlopen, runFixtureMaxRSS, tempDir, tls, @@ -2594,8 +2595,8 @@ describe("server.requestIP", () => { }); describe("server.requestFD", () => { - it("returns a positive integer fd for an active TCP request", async () => { - let observedFd: number | null = -1; + it("returns a non-negative integer fd for an active TCP request", async () => { + let observedFd: number | null = null; using server = Bun.serve({ port: 0, fetch(req, server) { @@ -2606,7 +2607,7 @@ describe("server.requestFD", () => { const response = await fetch(server.url.origin).then(x => x.json()); expect(typeof response.fd).toBe("number"); - expect(response.fd).toBeGreaterThan(0); + expect(response.fd).toBeGreaterThanOrEqual(0); expect(observedFd).toBe(response.fd); }); @@ -2631,7 +2632,7 @@ describe("server.requestFD", () => { }); it.if(isPosix)("returns an fd usable with getsockname() via FFI", async () => { - const libc = dlopen(`libc.${suffix}${process.platform === "darwin" ? "" : ".6"}`, { + const libc = dlopen(libcPathForDlopen(), { getsockname: { args: [FFIType.i32, FFIType.ptr, FFIType.ptr], returns: FFIType.i32, @@ -2641,26 +2642,23 @@ describe("server.requestFD", () => { using server = Bun.serve({ port: 0, fetch(req, server) { - const fd = server.requestFD(req); - if (typeof fd !== "number" || fd < 0) { - return Response.json({ ok: false, reason: "no fd", fd }); - } + const fd = server.requestFD(req) as number; const addr = new ArrayBuffer(128); const addrLen = new Uint32Array(1); addrLen[0] = 128; const rc = libc.symbols.getsockname(fd, ptr(addr), ptr(addrLen)); - return Response.json({ ok: true, fd, rc, addrLen: addrLen[0] }); + return Response.json({ fd, rc, addrLen: addrLen[0] }); }, }); const response = await fetch(server.url.origin).then(x => x.json()); - expect(response.ok).toBe(true); + expect(response.fd).toBeGreaterThanOrEqual(0); expect(response.rc).toBe(0); expect(response.addrLen).toBeGreaterThan(0); }); it.if(isPosix)("returns an OS fd for an HTTPS (TLS) request, not the SSL pointer", async () => { - const libc = dlopen(`libc.${suffix}${process.platform === "darwin" ? "" : ".6"}`, { + const libc = dlopen(libcPathForDlopen(), { getsockname: { args: [FFIType.i32, FFIType.ptr, FFIType.ptr], returns: FFIType.i32, @@ -2671,23 +2669,20 @@ describe("server.requestFD", () => { port: 0, tls, fetch(req, server) { - const fd = server.requestFD(req); - if (typeof fd !== "number" || fd < 0) { - return Response.json({ ok: false, fd }); - } + const fd = server.requestFD(req) as number; const addr = new ArrayBuffer(128); const addrLen = new Uint32Array(1); addrLen[0] = 128; const rc = libc.symbols.getsockname(fd, ptr(addr), ptr(addrLen)); - return Response.json({ ok: true, fd, rc, addrLen: addrLen[0] }); + return Response.json({ fd, rc, addrLen: addrLen[0] }); }, }); const response = await fetch(server.url.origin, { tls: { rejectUnauthorized: false } }).then(x => x.json()); - expect(response.ok).toBe(true); // If requestFD had returned the SSL* heap pointer (the regression this test // guards against), getsockname would fail with EBADF / rc !== 0. expect(response.rc).toBe(0); + expect(response.fd).toBeGreaterThanOrEqual(0); expect(response.addrLen).toBeGreaterThan(0); // A real fd is a small non-negative integer; an SSL* cast would be huge. expect(response.fd).toBeLessThan(1 << 20); @@ -2722,7 +2717,7 @@ describe("server.requestFD", () => { const body = Buffer.concat(received).toString().split("\r\n\r\n")[1]; const parsed = JSON.parse(body); expect(typeof parsed.fd).toBe("number"); - expect(parsed.fd).toBeGreaterThan(0); + expect(parsed.fd).toBeGreaterThanOrEqual(0); }); }); From 43edc1ded80f7ec4fb2e42874d2564554969e859 Mon Sep 17 00:00:00 2001 From: robobun Date: Wed, 22 Apr 2026 15:05:11 +0000 Subject: [PATCH 04/19] test: deduplicate requestFD/socket.fd test setup --- test/js/bun/http/bun-server.test.ts | 113 ++++++++++++---------------- test/js/bun/http/serve.test.ts | 76 +++++-------------- 2 files changed, 66 insertions(+), 123 deletions(-) diff --git a/test/js/bun/http/bun-server.test.ts b/test/js/bun/http/bun-server.test.ts index 4d73bf81cf39..fced264e2248 100644 --- a/test/js/bun/http/bun-server.test.ts +++ b/test/js/bun/http/bun-server.test.ts @@ -3644,86 +3644,71 @@ describe("handler GC tracing (heapStats wrapper-count)", () => { }, 30_000); }); describe.concurrent("node:http socket.fd (Bun extension)", () => { - test("request.socket.fd is a non-negative integer", async () => { - let observedFromFetch: number | undefined; - let observedFromConnection: number | undefined; - const server = http.createServer((req, res) => { - observedFromFetch = (req.socket as any).fd; - res.end("ok"); - }); - server.on("connection", socket => { - observedFromConnection = (socket as any).fd; - }); + // Start `server` on an ephemeral port, hit it once with fetch, then close — + // used by all three tests below. `onConnection` runs before the request. + async function runFetchOnce(server: http.Server, onConnection?: (s: any) => void) { + if (onConnection) server.on("connection", onConnection); server.listen(0); await once(server, "listening"); try { - const address = server.address() as { port: number }; - const res = await fetch(`http://127.0.0.1:${address.port}/`); - await res.text(); - expect(typeof observedFromFetch).toBe("number"); - expect(observedFromFetch).toBeGreaterThanOrEqual(0); - expect(typeof observedFromConnection).toBe("number"); - expect(observedFromConnection).toBeGreaterThanOrEqual(0); - expect(observedFromFetch).toBe(observedFromConnection); + const { port } = server.address() as { port: number }; + await (await fetch(`http://127.0.0.1:${port}/`)).text(); } finally { server.close(); } + } + + test("request.socket.fd is a non-negative integer", async () => { + let observedFromFetch: number | undefined; + let observedFromConnection: number | undefined; + await runFetchOnce( + http.createServer((req, res) => { + observedFromFetch = (req.socket as any).fd; + res.end("ok"); + }), + socket => { + observedFromConnection = socket.fd; + }, + ); + expect(typeof observedFromFetch).toBe("number"); + expect(observedFromFetch).toBeGreaterThanOrEqual(0); + expect(observedFromConnection).toBe(observedFromFetch); }); test.if(isPosix)("socket.fd works with getsockname() via FFI", async () => { const libc = dlopen(libcPathForDlopen(), { - getsockname: { - args: [FFIType.i32, FFIType.ptr, FFIType.ptr], - returns: FFIType.i32, - }, + getsockname: { args: [FFIType.i32, FFIType.ptr, FFIType.ptr], returns: FFIType.i32 }, }); - let result: { rc: number; addrLen: number } | undefined; - const server = http.createServer((req, res) => { - const fd = (req.socket as any).fd; - const addr = new ArrayBuffer(128); - const addrLen = new Uint32Array(1); - addrLen[0] = 128; - const rc = libc.symbols.getsockname(fd, ptr(addr), ptr(addrLen)); - result = { rc, addrLen: addrLen[0] }; - res.end("ok"); - }); - server.listen(0); - await once(server, "listening"); - try { - const address = server.address() as { port: number }; - const res = await fetch(`http://127.0.0.1:${address.port}/`); - await res.text(); - expect(result).toEqual({ rc: 0, addrLen: expect.any(Number) }); - expect(result!.addrLen).toBeGreaterThan(0); - } finally { - server.close(); - } + await runFetchOnce( + http.createServer((req, res) => { + const fd = (req.socket as any).fd; + const addr = new ArrayBuffer(128); + const addrLen = new Uint32Array([128]); + const rc = libc.symbols.getsockname(fd, ptr(addr), ptr(addrLen)); + result = { rc, addrLen: addrLen[0] }; + res.end("ok"); + }), + ); + expect(result).toEqual({ rc: 0, addrLen: expect.any(Number) }); + expect(result!.addrLen).toBeGreaterThan(0); }); test("socket.fd becomes -1 after the socket is destroyed", async () => { let savedSocket: any; - const server = http.createServer((req, res) => { - savedSocket = req.socket; - res.end("ok"); - }); - server.listen(0); - await once(server, "listening"); - try { - const address = server.address() as { port: number }; - const res = await fetch(`http://127.0.0.1:${address.port}/`); - await res.text(); - // Destroy the socket and wait for the close event so kHandle is cleared. - // Guard the destroy + `once` against the socket already being torn down, - // which can race under heavy load. - if (!savedSocket.destroyed) { - const closed = once(savedSocket, "close"); - savedSocket.destroy(); - await closed; - } - expect(savedSocket.fd).toBe(-1); - } finally { - server.close(); + await runFetchOnce( + http.createServer((req, res) => { + savedSocket = req.socket; + res.end("ok"); + }), + ); + // Destroy the socket and wait for `close` so `kHandle` is cleared. Guard + // against the socket already being torn down, which can race under load. + if (!savedSocket.destroyed) { + const closed = once(savedSocket, "close"); + savedSocket.destroy(); + await closed; } + expect(savedSocket.fd).toBe(-1); }); }); diff --git a/test/js/bun/http/serve.test.ts b/test/js/bun/http/serve.test.ts index 69e05ad8eb9d..bc560bf47547 100644 --- a/test/js/bun/http/serve.test.ts +++ b/test/js/bun/http/serve.test.ts @@ -2631,26 +2631,21 @@ describe("server.requestFD", () => { expect(server.requestFD(savedRequest!)).toBeNull(); }); - it.if(isPosix)("returns an fd usable with getsockname() via FFI", async () => { + // Handler shared by the two getsockname() FFI tests below; calls + // getsockname(fd) on whatever `requestFD` returns and echoes rc/addrLen. + const getsocknameHandler = (req: Request, server: Server) => { const libc = dlopen(libcPathForDlopen(), { - getsockname: { - args: [FFIType.i32, FFIType.ptr, FFIType.ptr], - returns: FFIType.i32, - }, - }); - - using server = Bun.serve({ - port: 0, - fetch(req, server) { - const fd = server.requestFD(req) as number; - const addr = new ArrayBuffer(128); - const addrLen = new Uint32Array(1); - addrLen[0] = 128; - const rc = libc.symbols.getsockname(fd, ptr(addr), ptr(addrLen)); - return Response.json({ fd, rc, addrLen: addrLen[0] }); - }, + getsockname: { args: [FFIType.i32, FFIType.ptr, FFIType.ptr], returns: FFIType.i32 }, }); + const fd = server.requestFD(req) as number; + const addr = new ArrayBuffer(128); + const addrLen = new Uint32Array([128]); + const rc = libc.symbols.getsockname(fd, ptr(addr), ptr(addrLen)); + return Response.json({ fd, rc, addrLen: addrLen[0] }); + }; + it.if(isPosix)("returns an fd usable with getsockname() via FFI", async () => { + using server = Bun.serve({ port: 0, fetch: getsocknameHandler }); const response = await fetch(server.url.origin).then(x => x.json()); expect(response.fd).toBeGreaterThanOrEqual(0); expect(response.rc).toBe(0); @@ -2658,26 +2653,7 @@ describe("server.requestFD", () => { }); it.if(isPosix)("returns an OS fd for an HTTPS (TLS) request, not the SSL pointer", async () => { - const libc = dlopen(libcPathForDlopen(), { - getsockname: { - args: [FFIType.i32, FFIType.ptr, FFIType.ptr], - returns: FFIType.i32, - }, - }); - - using server = Bun.serve({ - port: 0, - tls, - fetch(req, server) { - const fd = server.requestFD(req) as number; - const addr = new ArrayBuffer(128); - const addrLen = new Uint32Array(1); - addrLen[0] = 128; - const rc = libc.symbols.getsockname(fd, ptr(addr), ptr(addrLen)); - return Response.json({ fd, rc, addrLen: addrLen[0] }); - }, - }); - + using server = Bun.serve({ port: 0, tls, fetch: getsocknameHandler }); const response = await fetch(server.url.origin, { tls: { rejectUnauthorized: false } }).then(x => x.json()); // If requestFD had returned the SSL* heap pointer (the regression this test // guards against), getsockname would fail with EBADF / rc !== 0. @@ -2691,33 +2667,15 @@ describe("server.requestFD", () => { it.if(isPosix)("returns an fd for a unix socket request", async () => { using dir = tempDir("serve-request-fd-unix", {}); const unix = join(String(dir), "serve-fd.sock"); - using server = Bun.serve({ + using _server = Bun.serve({ unix, fetch(req, server) { return Response.json({ fd: server.requestFD(req) }); }, }); - const requestText = `GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n`; - const received: Buffer[] = []; - const { resolve: resolveClose, promise: closed } = Promise.withResolvers(); - const connection = await Bun.connect({ - unix, - socket: { - data(_socket, data) { - received.push(data); - }, - close() { - resolveClose(); - }, - }, - }); - connection.write(requestText); - connection.flush(); - await closed; - const body = Buffer.concat(received).toString().split("\r\n\r\n")[1]; - const parsed = JSON.parse(body); - expect(typeof parsed.fd).toBe("number"); - expect(parsed.fd).toBeGreaterThanOrEqual(0); + const response = await fetch("http://localhost/", { unix }).then(r => r.json()); + expect(typeof response.fd).toBe("number"); + expect(response.fd).toBeGreaterThanOrEqual(0); }); }); From 159d57f6a4b2864a910138ec25759c832a142f3d Mon Sep 17 00:00:00 2001 From: robobun Date: Wed, 22 Apr 2026 21:05:15 +0000 Subject: [PATCH 05/19] ci: retrigger darwin aarch64 (flaky grpc-js resolver test) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The previous build had a flaky failure in test/js/third_party/grpc-js/test-resolver.test.ts on darwin-13-aarch64 (unrelated to this PR — the retry of the same job passed). Pushing this empty commit to retrigger CI. From ce5dcea8a43d5cc4b356957aa9d58f536cd1f458 Mon Sep 17 00:00:00 2001 From: robobun Date: Wed, 22 Apr 2026 23:07:38 +0000 Subject: [PATCH 06/19] ci: retrigger (3 pre-existing flakes) Build 47337 had 3 unrelated flakes, all in pre-existing tests: - test/js/valkey/integration/complex-operations.test.ts (timeout, valkey service flake) - test/js/bun/net/socket.test.ts (windows aarch64, known-flaky file with multiple skipIf(isWindows) guards already) - test/js/sql/sql.test.ts (sql service flake) None of these test files are touched by this PR. All 5 shards of windows-11-aarch64-test-bun that did NOT hit socket.test.ts passed, confirming my tests work. Retriggering. From a959ca5d8646b811c7eae224034d8b577a52caaf Mon Sep 17 00:00:00 2001 From: robobun Date: Mon, 4 May 2026 01:32:35 +0000 Subject: [PATCH 07/19] fix(build): drop duplicate us_socket_get_fd decl, use uncheckedDowncast After the rebase onto main, two small tweaks are needed for the .fd getter to build against current API: - us_socket_get_fd is now declared in , transitively included here, so my local forward declaration conflicted. Removed. - Use uncheckedDowncast for the prototype getter's thisValue (matching sibling getters like jsNodeHttpServerSocketGetterClosed after the recent casting refactor) instead of jsCast, which is no longer the idiomatic accessor here. Release build now succeeds; all 8 tests still pass. --- .../bindings/node/JSNodeHTTPServerSocketPrototype.cpp | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/src/jsc/bindings/node/JSNodeHTTPServerSocketPrototype.cpp b/src/jsc/bindings/node/JSNodeHTTPServerSocketPrototype.cpp index 582ab1d29648..4792809df5a6 100644 --- a/src/jsc/bindings/node/JSNodeHTTPServerSocketPrototype.cpp +++ b/src/jsc/bindings/node/JSNodeHTTPServerSocketPrototype.cpp @@ -13,11 +13,8 @@ extern "C" uint64_t uws_res_get_remote_address_info(void* res, const char** dest extern "C" uint64_t uws_res_get_local_address_info(void* res, const char** dest, int* port, bool* is_ipv6); extern "C" void us_socket_resume(us_socket_t*); extern "C" void us_socket_pause(us_socket_t*); -#if OS(WINDOWS) -extern "C" uintptr_t us_socket_get_fd(void* socket); -#else -extern "C" int us_socket_get_fd(void* socket); -#endif +// us_socket_get_fd is declared in , transitively included via +// JSNodeHTTPServerSocket.h / the uSockets headers. namespace Bun { @@ -544,7 +541,7 @@ JSC_DEFINE_CUSTOM_GETTER(jsNodeHttpServerSocketGetterResponse, (JSC::JSGlobalObj JSC_DEFINE_CUSTOM_GETTER(jsNodeHttpServerSocketGetterFd, (JSC::JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, JSC::PropertyName propertyName)) { - auto* thisObject = jsCast(JSC::JSValue::decode(thisValue)); + auto* thisObject = uncheckedDowncast(JSC::JSValue::decode(thisValue)); us_socket_t* socket = thisObject->socket; if (!socket || thisObject->isClosed()) { return JSValue::encode(JSC::jsNumber(-1)); From ddd9df897d3a26b5233484c06d2f74cf00e3a00d Mon Sep 17 00:00:00 2001 From: robobun Date: Mon, 4 May 2026 01:42:55 +0000 Subject: [PATCH 08/19] fix(serve): requestFD must not panic on HTTP/3 requests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit AnyRequestContext.getFd was a hand-rolled 4-arm switch with an `else => @panic` fallthrough. Main's Pointer union has 6 tags, not 4: HTTPSServer.H3RequestContext and DebugHTTPSServer.H3RequestContext. Calling server.requestFD(req) from an H3 fetch handler tripped the else branch and aborted the process. - Rewrote getFd to use the existing `dispatch()` helper that every sibling accessor in this file uses (it iterates Pointer.type_map so new tags are covered automatically). H3 branches out early via the same `if (comptime T.is_h3) return null;` idiom used by setRequest / getRequest — HTTP/3 multiplexes streams over one UDP socket, so there is no per-request OS fd to hand back. - Added the matching `.H3 => bun.invalid_fd` arm to AnyResponse.getFd, mirroring the adjacent AnyResponse.getNativeHandle. This was dead code via lazy comptime analysis, but it would fail to compile the first time anything routed through it. - New test in serve-http3.test.ts asserts requestFD returns null for an H3 request instead of crashing. --- test/js/bun/http/serve-http3.test.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/test/js/bun/http/serve-http3.test.ts b/test/js/bun/http/serve-http3.test.ts index d0ce2e64e30c..1ae54d2d2808 100644 --- a/test/js/bun/http/serve-http3.test.ts +++ b/test/js/bun/http/serve-http3.test.ts @@ -157,6 +157,11 @@ const server = serve({ if (url.pathname === "/remote") { return Response.json(server.requestIP(req)); } + if (url.pathname === "/fd") { + // H3 multiplexes streams over one UDP socket, so there is no per-request + // OS fd. This must return null rather than panicking. + return Response.json({ fd: server.requestFD(req) }); + } return new Response("not found: " + url.pathname, { status: 404 }); }, }); @@ -776,6 +781,15 @@ describe("Bun.serve HTTP/3 adversarial", () => { }); }); + // bughunt: server.requestFD(req) must return null for H3 (no per-request fd) + // instead of panicking through AnyRequestContext.getFd's else branch. + test("server.requestFD(req) returns null for HTTP/3 requests", async () => { + await withServer(async port => { + const res = (await fetchH3(port, "/fd").then(r => r.json())) as { fd: number | null }; + expect(res.fd).toBeNull(); + }); + }); + // bughunt #6: H3 bodies are FIN-terminated; Content-Length is optional. // A ReadableStream body uploads without Content-Length. test("POST body without Content-Length still reaches the handler", async () => { From b5b45fb5f0a95520a45f53fcdd3ed2c65999bbb9 Mon Sep 17 00:00:00 2001 From: robobun Date: Mon, 4 May 2026 02:21:41 +0000 Subject: [PATCH 09/19] docs: note HTTP/3 always returns null; tighten FFI test gates Two review nits addressed: - `requestFD` JSDoc now documents that HTTP/3 requests always return `null` (they multiplex over a single UDP socket). The H3 behavior was added in 8357c4f2 but the docstring wasn't updated to match. - The three `getsockname()` FFI tests are now gated on `isLinux || isMacOS` instead of `isPosix`. `libcPathForDlopen()` only handles linux/darwin today and throws on FreeBSD, so the tighter gate stops the tests from being enabled on a platform where they would fail immediately. --- packages/bun-types/serve.d.ts | 3 +++ test/js/bun/http/bun-server.test.ts | 4 +++- test/js/bun/http/serve.test.ts | 9 +++++++-- 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/packages/bun-types/serve.d.ts b/packages/bun-types/serve.d.ts index 86817cfe19f0..fa972ce9055a 100644 --- a/packages/bun-types/serve.d.ts +++ b/packages/bun-types/serve.d.ts @@ -1121,6 +1121,9 @@ declare module "bun" { * if the underlying TCP connection is kept alive for a subsequent request. * Call this from inside the `fetch` handler to get a usable fd. * + * Always returns `null` for HTTP/3 requests: HTTP/3 multiplexes streams over + * a single shared UDP socket, so there is no meaningful per-request fd. + * * Useful for per-connection low-level socket operations via FFI, such as * `getsockopt(TCP_INFO)`, `setsockopt(TCP_CORK)`, `SO_RCVBUF`, etc. * diff --git a/test/js/bun/http/bun-server.test.ts b/test/js/bun/http/bun-server.test.ts index fced264e2248..3ec429ff68f3 100644 --- a/test/js/bun/http/bun-server.test.ts +++ b/test/js/bun/http/bun-server.test.ts @@ -3675,7 +3675,9 @@ describe.concurrent("node:http socket.fd (Bun extension)", () => { expect(observedFromConnection).toBe(observedFromFetch); }); - test.if(isPosix)("socket.fd works with getsockname() via FFI", async () => { + // Gate on linux/macOS only: `isPosix` also includes FreeBSD, but + // `libcPathForDlopen()` only handles linux/darwin today. + test.if(isLinux || isMacOS)("socket.fd works with getsockname() via FFI", async () => { const libc = dlopen(libcPathForDlopen(), { getsockname: { args: [FFIType.i32, FFIType.ptr, FFIType.ptr], returns: FFIType.i32 }, }); diff --git a/test/js/bun/http/serve.test.ts b/test/js/bun/http/serve.test.ts index bc560bf47547..a490068996e4 100644 --- a/test/js/bun/http/serve.test.ts +++ b/test/js/bun/http/serve.test.ts @@ -13,6 +13,8 @@ import { isIntelMacOS, isIPv4, isIPv6, + isLinux, + isMacOS, isPosix, libcPathForDlopen, runFixtureMaxRSS, @@ -2644,7 +2646,10 @@ describe("server.requestFD", () => { return Response.json({ fd, rc, addrLen: addrLen[0] }); }; - it.if(isPosix)("returns an fd usable with getsockname() via FFI", async () => { + // Gate FFI tests on linux/macOS only: `isPosix` also includes FreeBSD, but + // `libcPathForDlopen()` only handles linux/darwin today and would throw on + // any other POSIX platform. + it.if(isLinux || isMacOS)("returns an fd usable with getsockname() via FFI", async () => { using server = Bun.serve({ port: 0, fetch: getsocknameHandler }); const response = await fetch(server.url.origin).then(x => x.json()); expect(response.fd).toBeGreaterThanOrEqual(0); @@ -2652,7 +2657,7 @@ describe("server.requestFD", () => { expect(response.addrLen).toBeGreaterThan(0); }); - it.if(isPosix)("returns an OS fd for an HTTPS (TLS) request, not the SSL pointer", async () => { + it.if(isLinux || isMacOS)("returns an OS fd for an HTTPS (TLS) request, not the SSL pointer", async () => { using server = Bun.serve({ port: 0, tls, fetch: getsocknameHandler }); const response = await fetch(server.url.origin, { tls: { rejectUnauthorized: false } }).then(x => x.json()); // If requestFD had returned the SSL* heap pointer (the regression this test From 2df2d8f85adeba50c390b941a1fab9d81e0a94ee Mon Sep 17 00:00:00 2001 From: robobun Date: Sun, 24 May 2026 04:16:26 +0000 Subject: [PATCH 10/19] fix(rust): add do_request_fd / get_fd Rust bindings for new codegen MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Main migrated `Bun.serve` host-fn bindings to Rust (bun_runtime crate). The codegen in `server.classes.ts` emits a Rust dispatch that expects `NewServer::do_request_fd`, but only the Zig `doRequestFD` existed on this branch — build failed with: error[E0599]: no associated function or constant named `do_request_fd` found for struct `server::NewServer` Added the matching Rust methods, mirroring the existing Rust `request_ip` path: - `uws_sys::Response::get_fd` — calls `us_socket_get_fd` via `downcast_socket` (same pattern as the Zig side). - `uws_sys::AnyResponse::get_fd` — `.H3 => Fd::INVALID`, matches `get_native_handle`. - `RequestContext::get_fd` — null when `resp` is absent or fd invalid. - `AnyRequestContext::get_fd` — uses the `dispatch!` helper with `if T::IS_H3` returning None (same pattern as set_request). - `server_body::do_request_fd` + `request_fd` — thin wrappers that decode the Request arg and return JSValue::NULL or the fd via `FdJsc::to_js_without_making_lib_uv_owned`. --- src/runtime/server/AnyRequestContext.rs | 10 ++++++++++ src/runtime/server/RequestContext.rs | 6 ++++++ src/runtime/server/server_body.rs | 26 +++++++++++++++++++++++++ src/uws_sys/Response.rs | 22 +++++++++++++++++++++ 4 files changed, 64 insertions(+) diff --git a/src/runtime/server/AnyRequestContext.rs b/src/runtime/server/AnyRequestContext.rs index 96d62cef1346..a077acbbde73 100644 --- a/src/runtime/server/AnyRequestContext.rs +++ b/src/runtime/server/AnyRequestContext.rs @@ -180,6 +180,16 @@ impl AnyRequestContext { dispatch!(self, None, |_T, ctx| ctx.get_remote_socket_info()) } + pub fn get_fd(self) -> Option { + dispatch!(self, None, |T, ctx| { + // HTTP/3 multiplexes streams over one UDP socket — no per-request fd. + if T::IS_H3 { + return None; + } + ctx.get_fd() + }) + } + pub(crate) fn detach_request(self) { dispatch!(self, (), |_T, ctx| { ctx.req.set(None); diff --git a/src/runtime/server/RequestContext.rs b/src/runtime/server/RequestContext.rs index a5454542d838..5edc780a6d33 100644 --- a/src/runtime/server/RequestContext.rs +++ b/src/runtime/server/RequestContext.rs @@ -4384,6 +4384,12 @@ where }) } + pub fn get_fd(&self) -> Option { + let resp = self.resp.get()?; + let fd = resp.get_fd(); + if fd.is_valid() { Some(fd) } else { None } + } + pub(crate) fn set_timeout(&self, seconds: c_uint) -> bool { if let Some(resp) = self.live_resp() { // SAFETY: FFI handle diff --git a/src/runtime/server/server_body.rs b/src/runtime/server/server_body.rs index 1c88ca0d2691..b0c26a30bc0e 100644 --- a/src/runtime/server/server_body.rs +++ b/src/runtime/server/server_body.rs @@ -1571,6 +1571,24 @@ where self.request_ip(request) } + /// `pub const doRequestFD = host_fn.wrapInstanceMethod(ThisServer, "requestFD", false)` + #[bun_jsc::host_fn(method)] + pub fn do_request_fd( + &mut self, + global: &JSGlobalObject, + callframe: &CallFrame, + ) -> JsResult { + let args = callframe.arguments_old::<2>(); + let mut iter = jsc::ArgumentsSlice::init(global.bun_vm_ref(), args.slice()); + let arg = iter.next_eat().ok_or_else(|| { + global.throw_invalid_arguments(format_args!("Missing Request object")) + })?; + let request = arg.as_class_ref::().ok_or_else(|| { + global.throw_invalid_arguments(format_args!("Expected Request object")) + })?; + self.request_fd(request) + } + /// `pub const doReload = onReload` #[inline] pub(crate) fn do_reload( @@ -1616,6 +1634,14 @@ where ) } + pub fn request_fd(&self, request: &Request) -> JsResult { + use bun_sys_jsc::FdJsc as _; + let Some(fd) = request.request_context.get_fd() else { + return Ok(JSValue::NULL); + }; + Ok(fd.to_js_without_making_lib_uv_owned()) + } + #[bun_jsc::host_fn(method)] pub(crate) fn timeout( &mut self, diff --git a/src/uws_sys/Response.rs b/src/uws_sys/Response.rs index e70180e69f5b..c972e371afda 100644 --- a/src/uws_sys/Response.rs +++ b/src/uws_sys/Response.rs @@ -352,6 +352,17 @@ impl Response { } } + /// Returns the underlying OS file descriptor (or Windows SOCKET) for this + /// response's socket, regardless of SSL. Unlike `get_native_handle`, which + /// returns the OpenSSL `SSL*` pointer for TLS connections, this always + /// goes straight to `us_socket_get_fd` so the value is a real descriptor + /// suitable for `getsockopt`/`setsockopt`. + pub fn get_fd(&mut self) -> Fd { + // SAFETY: `downcast_socket` reinterprets the response handle as + // `*mut us_socket_t`; uWS lays these out as the same opaque handle. + unsafe { (*self.downcast_socket()).get_fd() } + } + pub fn get_remote_socket_info(&mut self) -> Option { let mut ip_ptr: *const u8 = core::ptr::null(); let mut port: i32 = 0; @@ -878,6 +889,17 @@ impl AnyResponse { } } + /// Returns the underlying OS file descriptor for this response's socket, + /// bypassing SSL so the result is a real `us_socket_get_fd` value. + /// HTTP/3 multiplexes streams over one UDP socket — no per-response fd. + pub fn get_fd(self) -> Fd { + match self { + AnyResponse::H3(_) => bun_core::Fd::INVALID, + AnyResponse::SSL(ptr) => TLSResponse::as_handle(ptr).get_fd(), + AnyResponse::TCP(ptr) => TCPResponse::as_handle(ptr).get_fd(), + } + } + pub fn prepare_for_sendfile(self) { any_dispatch!(self, |r| r.prepare_for_sendfile()) } From 8c73ffa56e1315a07aaba96d74573c001c64a7b8 Mon Sep 17 00:00:00 2001 From: robobun Date: Sun, 24 May 2026 04:49:26 +0000 Subject: [PATCH 11/19] fix(node-http): use dynamicDowncast in fd getter for arbitrary receivers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The `fd` property is registered on JSNodeHTTPServerSocketPrototype as a CustomAccessor without DOMAttribute, which means JSC does not validate the receiver before invoking the getter. Using `uncheckedDowncast` asserts in debug and type-confuses in release when called via e.g. `Object.getOwnPropertyDescriptor(proto, 'fd').get.call({})` — confirmed to abort (core dump) on the existing debug build. Switch to `dynamicDowncast` + `if (!thisObject) return -1` so an unrelated receiver gets -1 instead of tripping the security assertion at `thisObject->socket`. Same defensive pattern I would expect from any CustomAccessor on a hand-written prototype without DOMAttribute. The sibling getters in this file share the same underlying defect; limiting the change to `fd` keeps the fix scoped to what this PR adds. Regression test added in bun-server.test.ts — runs in a subprocess so an assertion abort surfaces as exit code 134 rather than killing the test runner. Verified: the new test fails without this patch, passes with it. --- .../node/JSNodeHTTPServerSocketPrototype.cpp | 9 +++- test/js/bun/http/bun-server.test.ts | 52 +++++++++++++++++++ 2 files changed, 60 insertions(+), 1 deletion(-) diff --git a/src/jsc/bindings/node/JSNodeHTTPServerSocketPrototype.cpp b/src/jsc/bindings/node/JSNodeHTTPServerSocketPrototype.cpp index 4792809df5a6..00aaf3845d93 100644 --- a/src/jsc/bindings/node/JSNodeHTTPServerSocketPrototype.cpp +++ b/src/jsc/bindings/node/JSNodeHTTPServerSocketPrototype.cpp @@ -541,7 +541,14 @@ JSC_DEFINE_CUSTOM_GETTER(jsNodeHttpServerSocketGetterResponse, (JSC::JSGlobalObj JSC_DEFINE_CUSTOM_GETTER(jsNodeHttpServerSocketGetterFd, (JSC::JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, JSC::PropertyName propertyName)) { - auto* thisObject = uncheckedDowncast(JSC::JSValue::decode(thisValue)); + // `fd` is a CustomAccessor without DOMAttribute, so JSC calls this getter + // with an arbitrary receiver. Validate before dereferencing instead of + // uncheckedDowncast so e.g. `Object.getOwnPropertyDescriptor(proto, 'fd').get.call({})` + // returns -1 rather than asserting through `thisObject->socket`. + auto* thisObject = dynamicDowncast(JSC::JSValue::decode(thisValue)); + if (!thisObject) [[unlikely]] { + return JSValue::encode(JSC::jsNumber(-1)); + } us_socket_t* socket = thisObject->socket; if (!socket || thisObject->isClosed()) { return JSValue::encode(JSC::jsNumber(-1)); diff --git a/test/js/bun/http/bun-server.test.ts b/test/js/bun/http/bun-server.test.ts index 3ec429ff68f3..03713ba17838 100644 --- a/test/js/bun/http/bun-server.test.ts +++ b/test/js/bun/http/bun-server.test.ts @@ -3713,4 +3713,56 @@ describe.concurrent("node:http socket.fd (Bun extension)", () => { } expect(savedSocket.fd).toBe(-1); }); + + // Regression: the `fd` prototype getter is a CustomAccessor without + // DOMAttribute, so JSC hands the getter an arbitrary receiver. Reaching + // the getter via `Object.getOwnPropertyDescriptor` and calling with a + // plain object used to hit `uncheckedDowncast`'s security assertion in + // debug builds (and type-confused reads in release). It must return -1. + test("socket.fd getter rejects unrelated receivers instead of asserting", async () => { + const src = /* js */ ` + const http = require("http"); + const server = http.createServer((req, res) => { + const socket = req.socket; + const handleSym = Object.getOwnPropertySymbols(socket) + .find(s => s.description === "handle"); + const nativeHandle = socket[handleSym]; + const proto = Object.getPrototypeOf(nativeHandle); + const desc = Object.getOwnPropertyDescriptor(proto, "fd"); + if (typeof desc?.get !== "function") { + console.error("fd getter missing"); + process.exit(1); + } + const got = desc.get.call({}); + if (got !== -1) { + console.error("expected -1, got", got); + process.exit(1); + } + res.end("ok"); + }); + server.listen(0, async () => { + const { port } = server.address(); + const r = await fetch("http://127.0.0.1:" + port + "/"); + await r.text(); + server.close(); + console.log("OK"); + }); + `; + await using proc = Bun.spawn({ + cmd: [bunExe(), "-e", src], + env: bunEnv, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([ + proc.stdout.text(), + proc.stderr.text(), + proc.exited, + ]); + expect({ stdout: stdout.trim(), signalCode: proc.signalCode ?? null, exitCode }).toMatchObject({ + stdout: "OK", + signalCode: null, + exitCode: 0, + }); + }); }); From 8dfb02c0255920cd81ab97d566152d863e9e6261 Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Sun, 24 May 2026 04:51:03 +0000 Subject: [PATCH 12/19] [autofix.ci] apply automated fixes --- test/js/bun/http/bun-server.test.ts | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/test/js/bun/http/bun-server.test.ts b/test/js/bun/http/bun-server.test.ts index 03713ba17838..6a3981a2e5ea 100644 --- a/test/js/bun/http/bun-server.test.ts +++ b/test/js/bun/http/bun-server.test.ts @@ -3754,11 +3754,7 @@ describe.concurrent("node:http socket.fd (Bun extension)", () => { stdout: "pipe", stderr: "pipe", }); - const [stdout, stderr, exitCode] = await Promise.all([ - proc.stdout.text(), - proc.stderr.text(), - proc.exited, - ]); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); expect({ stdout: stdout.trim(), signalCode: proc.signalCode ?? null, exitCode }).toMatchObject({ stdout: "OK", signalCode: null, From a7af30bf46b5bb3873e02f50443daa2f7e556c5d Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 25 Jun 2026 15:38:04 +0000 Subject: [PATCH 13/19] test(node-http): surface stderr in fd-getter regression diff --- test/js/bun/http/bun-server.test.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/test/js/bun/http/bun-server.test.ts b/test/js/bun/http/bun-server.test.ts index 6a3981a2e5ea..244c6b9f6314 100644 --- a/test/js/bun/http/bun-server.test.ts +++ b/test/js/bun/http/bun-server.test.ts @@ -3755,7 +3755,10 @@ describe.concurrent("node:http socket.fd (Bun extension)", () => { stderr: "pipe", }); const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); - expect({ stdout: stdout.trim(), signalCode: proc.signalCode ?? null, exitCode }).toMatchObject({ + // stderr is diagnostic-only here: toMatchObject ignores keys absent from the + // expected object, so a future assertion-abort backtrace surfaces in the diff + // without asserting on (noisy) stderr content. + expect({ stdout: stdout.trim(), stderr, signalCode: proc.signalCode ?? null, exitCode }).toMatchObject({ stdout: "OK", signalCode: null, exitCode: 0, From a92c250aa76d851c0df05b839ed1905e802607b5 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 25 Jun 2026 16:09:17 +0000 Subject: [PATCH 14/19] address review: explicit us_socket_get_fd decl, S008 deref in Response::get_fd --- src/jsc/bindings/node/JSNodeHTTPServerSocketPrototype.cpp | 8 ++++++-- src/uws_sys/Response.rs | 5 ++--- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/jsc/bindings/node/JSNodeHTTPServerSocketPrototype.cpp b/src/jsc/bindings/node/JSNodeHTTPServerSocketPrototype.cpp index 00aaf3845d93..f4acc6105ff0 100644 --- a/src/jsc/bindings/node/JSNodeHTTPServerSocketPrototype.cpp +++ b/src/jsc/bindings/node/JSNodeHTTPServerSocketPrototype.cpp @@ -13,8 +13,12 @@ extern "C" uint64_t uws_res_get_remote_address_info(void* res, const char** dest extern "C" uint64_t uws_res_get_local_address_info(void* res, const char** dest, int* port, bool* is_ipv6); extern "C" void us_socket_resume(us_socket_t*); extern "C" void us_socket_pause(us_socket_t*); -// us_socket_get_fd is declared in , transitively included via -// JSNodeHTTPServerSocket.h / the uSockets headers. +// LIBUS_SOCKET_DESCRIPTOR is SOCKET (uintptr_t) on Windows, int elsewhere. +#if OS(WINDOWS) +extern "C" uintptr_t us_socket_get_fd(struct us_socket_t* s); +#else +extern "C" int us_socket_get_fd(struct us_socket_t* s); +#endif namespace Bun { diff --git a/src/uws_sys/Response.rs b/src/uws_sys/Response.rs index c972e371afda..57fc07f1cebd 100644 --- a/src/uws_sys/Response.rs +++ b/src/uws_sys/Response.rs @@ -358,9 +358,8 @@ impl Response { /// goes straight to `us_socket_get_fd` so the value is a real descriptor /// suitable for `getsockopt`/`setsockopt`. pub fn get_fd(&mut self) -> Fd { - // SAFETY: `downcast_socket` reinterprets the response handle as - // `*mut us_socket_t`; uWS lays these out as the same opaque handle. - unsafe { (*self.downcast_socket()).get_fd() } + // S008: `us_socket_t` is an `opaque_ffi!` ZST — safe deref. + us_socket_t::opaque_mut(self.downcast_socket()).get_fd() } pub fn get_remote_socket_info(&mut self) -> Option { From 61e435028178526414e5f19f045b677b85d5b80a Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 13 Aug 2026 21:53:04 +0000 Subject: [PATCH 15/19] adapt do_request_fd to new CallFrame::arguments API --- src/runtime/server/server_body.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/runtime/server/server_body.rs b/src/runtime/server/server_body.rs index b0c26a30bc0e..569a4833c73c 100644 --- a/src/runtime/server/server_body.rs +++ b/src/runtime/server/server_body.rs @@ -1578,8 +1578,7 @@ where global: &JSGlobalObject, callframe: &CallFrame, ) -> JsResult { - let args = callframe.arguments_old::<2>(); - let mut iter = jsc::ArgumentsSlice::init(global.bun_vm_ref(), args.slice()); + let mut iter = jsc::ArgumentsSlice::init(global.bun_vm_ref(), callframe.arguments()); let arg = iter.next_eat().ok_or_else(|| { global.throw_invalid_arguments(format_args!("Missing Request object")) })?; From a199c8d535ec12d87be10d27be79888a7df21db0 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 13 Aug 2026 21:55:54 +0000 Subject: [PATCH 16/19] tighten fd getter comments --- .../bindings/node/JSNodeHTTPServerSocketPrototype.cpp | 9 +++------ src/uws_sys/Response.rs | 11 +++-------- 2 files changed, 6 insertions(+), 14 deletions(-) diff --git a/src/jsc/bindings/node/JSNodeHTTPServerSocketPrototype.cpp b/src/jsc/bindings/node/JSNodeHTTPServerSocketPrototype.cpp index f4acc6105ff0..cd038a9d12a3 100644 --- a/src/jsc/bindings/node/JSNodeHTTPServerSocketPrototype.cpp +++ b/src/jsc/bindings/node/JSNodeHTTPServerSocketPrototype.cpp @@ -545,10 +545,8 @@ JSC_DEFINE_CUSTOM_GETTER(jsNodeHttpServerSocketGetterResponse, (JSC::JSGlobalObj JSC_DEFINE_CUSTOM_GETTER(jsNodeHttpServerSocketGetterFd, (JSC::JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, JSC::PropertyName propertyName)) { - // `fd` is a CustomAccessor without DOMAttribute, so JSC calls this getter - // with an arbitrary receiver. Validate before dereferencing instead of - // uncheckedDowncast so e.g. `Object.getOwnPropertyDescriptor(proto, 'fd').get.call({})` - // returns -1 rather than asserting through `thisObject->socket`. + // No DOMAttribute on this CustomAccessor, so JSC may pass an arbitrary + // receiver: dynamicDowncast, not uncheckedDowncast, and -1 for foreign receivers. auto* thisObject = dynamicDowncast(JSC::JSValue::decode(thisValue)); if (!thisObject) [[unlikely]] { return JSValue::encode(JSC::jsNumber(-1)); @@ -558,8 +556,7 @@ JSC_DEFINE_CUSTOM_GETTER(jsNodeHttpServerSocketGetterFd, (JSC::JSGlobalObject * return JSValue::encode(JSC::jsNumber(-1)); } #if OS(WINDOWS) - // On Windows, us_socket_get_fd returns a SOCKET (UINT_PTR). Surface it as - // an unsigned integer so setsockopt/getsockopt via FFI receive the full value. + // SOCKET is UINT_PTR; widen via double so FFI callers get the full value. return JSValue::encode(JSC::jsNumber(static_cast(us_socket_get_fd(socket)))); #else return JSValue::encode(JSC::jsNumber(us_socket_get_fd(socket))); diff --git a/src/uws_sys/Response.rs b/src/uws_sys/Response.rs index 57fc07f1cebd..c690cb8e80b7 100644 --- a/src/uws_sys/Response.rs +++ b/src/uws_sys/Response.rs @@ -352,11 +352,8 @@ impl Response { } } - /// Returns the underlying OS file descriptor (or Windows SOCKET) for this - /// response's socket, regardless of SSL. Unlike `get_native_handle`, which - /// returns the OpenSSL `SSL*` pointer for TLS connections, this always - /// goes straight to `us_socket_get_fd` so the value is a real descriptor - /// suitable for `getsockopt`/`setsockopt`. + /// Real OS fd (Windows: SOCKET) via `us_socket_get_fd`, unlike + /// `get_native_handle`, which returns the `SSL*` pointer for TLS. pub fn get_fd(&mut self) -> Fd { // S008: `us_socket_t` is an `opaque_ffi!` ZST — safe deref. us_socket_t::opaque_mut(self.downcast_socket()).get_fd() @@ -888,9 +885,7 @@ impl AnyResponse { } } - /// Returns the underlying OS file descriptor for this response's socket, - /// bypassing SSL so the result is a real `us_socket_get_fd` value. - /// HTTP/3 multiplexes streams over one UDP socket — no per-response fd. + /// Real OS fd, bypassing SSL. H3 has no per-response fd (one UDP socket). pub fn get_fd(self) -> Fd { match self { AnyResponse::H3(_) => bun_core::Fd::INVALID, From 2d7ff2ad1f333d8f6e3b5cbd42f5e646f36b9372 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 13 Aug 2026 22:17:13 +0000 Subject: [PATCH 17/19] pub(crate) visibility for fd helpers; drop comments restating file defaults --- src/jsc/bindings/node/JSNodeHTTPServerSocketPrototype.cpp | 3 --- src/runtime/server/AnyRequestContext.rs | 2 +- src/runtime/server/RequestContext.rs | 2 +- src/runtime/server/server_body.rs | 4 ++-- src/uws_sys/Response.rs | 3 +-- 5 files changed, 5 insertions(+), 9 deletions(-) diff --git a/src/jsc/bindings/node/JSNodeHTTPServerSocketPrototype.cpp b/src/jsc/bindings/node/JSNodeHTTPServerSocketPrototype.cpp index cd038a9d12a3..0f8d66fcf760 100644 --- a/src/jsc/bindings/node/JSNodeHTTPServerSocketPrototype.cpp +++ b/src/jsc/bindings/node/JSNodeHTTPServerSocketPrototype.cpp @@ -545,8 +545,6 @@ JSC_DEFINE_CUSTOM_GETTER(jsNodeHttpServerSocketGetterResponse, (JSC::JSGlobalObj JSC_DEFINE_CUSTOM_GETTER(jsNodeHttpServerSocketGetterFd, (JSC::JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, JSC::PropertyName propertyName)) { - // No DOMAttribute on this CustomAccessor, so JSC may pass an arbitrary - // receiver: dynamicDowncast, not uncheckedDowncast, and -1 for foreign receivers. auto* thisObject = dynamicDowncast(JSC::JSValue::decode(thisValue)); if (!thisObject) [[unlikely]] { return JSValue::encode(JSC::jsNumber(-1)); @@ -556,7 +554,6 @@ JSC_DEFINE_CUSTOM_GETTER(jsNodeHttpServerSocketGetterFd, (JSC::JSGlobalObject * return JSValue::encode(JSC::jsNumber(-1)); } #if OS(WINDOWS) - // SOCKET is UINT_PTR; widen via double so FFI callers get the full value. return JSValue::encode(JSC::jsNumber(static_cast(us_socket_get_fd(socket)))); #else return JSValue::encode(JSC::jsNumber(us_socket_get_fd(socket))); diff --git a/src/runtime/server/AnyRequestContext.rs b/src/runtime/server/AnyRequestContext.rs index a077acbbde73..ccd9474d1db2 100644 --- a/src/runtime/server/AnyRequestContext.rs +++ b/src/runtime/server/AnyRequestContext.rs @@ -180,7 +180,7 @@ impl AnyRequestContext { dispatch!(self, None, |_T, ctx| ctx.get_remote_socket_info()) } - pub fn get_fd(self) -> Option { + pub(crate) fn get_fd(self) -> Option { dispatch!(self, None, |T, ctx| { // HTTP/3 multiplexes streams over one UDP socket — no per-request fd. if T::IS_H3 { diff --git a/src/runtime/server/RequestContext.rs b/src/runtime/server/RequestContext.rs index 5edc780a6d33..5899b596663a 100644 --- a/src/runtime/server/RequestContext.rs +++ b/src/runtime/server/RequestContext.rs @@ -4384,7 +4384,7 @@ where }) } - pub fn get_fd(&self) -> Option { + pub(crate) fn get_fd(&self) -> Option { let resp = self.resp.get()?; let fd = resp.get_fd(); if fd.is_valid() { Some(fd) } else { None } diff --git a/src/runtime/server/server_body.rs b/src/runtime/server/server_body.rs index 569a4833c73c..3674099972b8 100644 --- a/src/runtime/server/server_body.rs +++ b/src/runtime/server/server_body.rs @@ -1573,7 +1573,7 @@ where /// `pub const doRequestFD = host_fn.wrapInstanceMethod(ThisServer, "requestFD", false)` #[bun_jsc::host_fn(method)] - pub fn do_request_fd( + pub(crate) fn do_request_fd( &mut self, global: &JSGlobalObject, callframe: &CallFrame, @@ -1633,7 +1633,7 @@ where ) } - pub fn request_fd(&self, request: &Request) -> JsResult { + pub(crate) fn request_fd(&self, request: &Request) -> JsResult { use bun_sys_jsc::FdJsc as _; let Some(fd) = request.request_context.get_fd() else { return Ok(JSValue::NULL); diff --git a/src/uws_sys/Response.rs b/src/uws_sys/Response.rs index c690cb8e80b7..da803a72c120 100644 --- a/src/uws_sys/Response.rs +++ b/src/uws_sys/Response.rs @@ -352,8 +352,7 @@ impl Response { } } - /// Real OS fd (Windows: SOCKET) via `us_socket_get_fd`, unlike - /// `get_native_handle`, which returns the `SSL*` pointer for TLS. + /// Real OS fd via `us_socket_get_fd`, unlike `get_native_handle` (SSL* for TLS). pub fn get_fd(&mut self) -> Fd { // S008: `us_socket_t` is an `opaque_ffi!` ZST — safe deref. us_socket_t::opaque_mut(self.downcast_socket()).get_fd() From 6c281cd2bc17141ff44747f71f98392e47588e04 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 22 Aug 2026 00:30:56 +0000 Subject: [PATCH 18/19] guard get_fd with live_resp to avoid freed-socket deref after streamed response end --- src/runtime/server/RequestContext.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/runtime/server/RequestContext.rs b/src/runtime/server/RequestContext.rs index 5899b596663a..eaac6cc66237 100644 --- a/src/runtime/server/RequestContext.rs +++ b/src/runtime/server/RequestContext.rs @@ -4385,7 +4385,7 @@ where } pub(crate) fn get_fd(&self) -> Option { - let resp = self.resp.get()?; + let resp = self.live_resp()?; let fd = resp.get_fd(); if fd.is_valid() { Some(fd) } else { None } } From a85fd16187319d2781c25113d726df83562cb01f Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 22 Aug 2026 00:54:08 +0000 Subject: [PATCH 19/19] drop stale libcPathForDlopen gate comments --- test/js/bun/http/bun-server.test.ts | 2 -- test/js/bun/http/serve.test.ts | 3 --- 2 files changed, 5 deletions(-) diff --git a/test/js/bun/http/bun-server.test.ts b/test/js/bun/http/bun-server.test.ts index 244c6b9f6314..586b97f9824d 100644 --- a/test/js/bun/http/bun-server.test.ts +++ b/test/js/bun/http/bun-server.test.ts @@ -3675,8 +3675,6 @@ describe.concurrent("node:http socket.fd (Bun extension)", () => { expect(observedFromConnection).toBe(observedFromFetch); }); - // Gate on linux/macOS only: `isPosix` also includes FreeBSD, but - // `libcPathForDlopen()` only handles linux/darwin today. test.if(isLinux || isMacOS)("socket.fd works with getsockname() via FFI", async () => { const libc = dlopen(libcPathForDlopen(), { getsockname: { args: [FFIType.i32, FFIType.ptr, FFIType.ptr], returns: FFIType.i32 }, diff --git a/test/js/bun/http/serve.test.ts b/test/js/bun/http/serve.test.ts index a490068996e4..fa3300ec586b 100644 --- a/test/js/bun/http/serve.test.ts +++ b/test/js/bun/http/serve.test.ts @@ -2646,9 +2646,6 @@ describe("server.requestFD", () => { return Response.json({ fd, rc, addrLen: addrLen[0] }); }; - // Gate FFI tests on linux/macOS only: `isPosix` also includes FreeBSD, but - // `libcPathForDlopen()` only handles linux/darwin today and would throw on - // any other POSIX platform. it.if(isLinux || isMacOS)("returns an fd usable with getsockname() via FFI", async () => { using server = Bun.serve({ port: 0, fetch: getsocknameHandler }); const response = await fetch(server.url.origin).then(x => x.json());