Skip to content
Closed
Show file tree
Hide file tree
Changes from 18 commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
6f01385
Expose socket fd for Bun.serve and node:http server sockets
robobun Apr 22, 2026
1f88a30
Fix HTTPS fd, address review feedback
robobun Apr 22, 2026
6feac5d
Address review: musl libc, fd>=0, doc accuracy
robobun Apr 22, 2026
43edc1d
test: deduplicate requestFD/socket.fd test setup
robobun Apr 22, 2026
159d57f
ci: retrigger darwin aarch64 (flaky grpc-js resolver test)
robobun Apr 22, 2026
ce5dcea
ci: retrigger (3 pre-existing flakes)
robobun Apr 22, 2026
a959ca5
fix(build): drop duplicate us_socket_get_fd decl, use uncheckedDowncast
robobun May 4, 2026
ddd9df8
fix(serve): requestFD must not panic on HTTP/3 requests
robobun May 4, 2026
b5b45fb
docs: note HTTP/3 always returns null; tighten FFI test gates
robobun May 4, 2026
2df2d8f
fix(rust): add do_request_fd / get_fd Rust bindings for new codegen
robobun May 24, 2026
8c73ffa
fix(node-http): use dynamicDowncast in fd getter for arbitrary receivers
robobun May 24, 2026
8dfb02c
[autofix.ci] apply automated fixes
autofix-ci[bot] May 24, 2026
a7af30b
test(node-http): surface stderr in fd-getter regression diff
robobun Jun 25, 2026
a92c250
address review: explicit us_socket_get_fd decl, S008 deref in Respons…
robobun Jun 25, 2026
61e4350
adapt do_request_fd to new CallFrame::arguments API
robobun Aug 13, 2026
a199c8d
tighten fd getter comments
robobun Aug 13, 2026
2d7ff2a
pub(crate) visibility for fd helpers; drop comments restating file de…
robobun Aug 13, 2026
6c281cd
guard get_fd with live_resp to avoid freed-socket deref after streame…
robobun Aug 22, 2026
a85fd16
drop stale libcPathForDlopen gate comments
robobun Aug 22, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions packages/bun-types/serve.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1114,6 +1114,33 @@ 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. 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.
*
* 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.
*
* 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;
Comment thread
robobun marked this conversation as resolved.
Resolved

/**
* Reset the idle timeout of the given Request to the given number of seconds. `0` means no timeout.
*
Expand Down
6 changes: 6 additions & 0 deletions src/js/node/_http_server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
25 changes: 25 additions & 0 deletions src/jsc/bindings/node/JSNodeHTTPServerSocketPrototype.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +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*);
// 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 {

Expand Down Expand Up @@ -45,6 +51,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))
{
Expand Down Expand Up @@ -76,6 +83,7 @@ static const JSC::HashTableValue JSNodeHTTPServerSocketPrototypeTableValues[] =
{ "servername"_s, static_cast<unsigned>(JSC::PropertyAttribute::CustomAccessor | JSC::PropertyAttribute::ReadOnly), JSC::NoIntrinsic, { JSC::HashTableValue::GetterSetterType, jsNodeHttpServerSocketGetterServername, noOpSetter } },
{ "authorizationError"_s, static_cast<unsigned>(JSC::PropertyAttribute::CustomAccessor | JSC::PropertyAttribute::ReadOnly), JSC::NoIntrinsic, { JSC::HashTableValue::GetterSetterType, jsNodeHttpServerSocketGetterAuthorizationError, noOpSetter } },
{ "peerCertVerified"_s, static_cast<unsigned>(JSC::PropertyAttribute::CustomAccessor | JSC::PropertyAttribute::ReadOnly), JSC::NoIntrinsic, { JSC::HashTableValue::GetterSetterType, jsNodeHttpServerSocketGetterPeerCertVerified, noOpSetter } },
{ "fd"_s, static_cast<unsigned>(JSC::PropertyAttribute::CustomAccessor | JSC::PropertyAttribute::ReadOnly), JSC::NoIntrinsic, { JSC::HashTableValue::GetterSetterType, jsNodeHttpServerSocketGetterFd, noOpSetter } },
};

void JSNodeHTTPServerSocketPrototype::finishCreation(JSC::VM& vm)
Expand Down Expand Up @@ -535,4 +543,21 @@ 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 = dynamicDowncast<JSNodeHTTPServerSocket>(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));
}
#if OS(WINDOWS)
return JSValue::encode(JSC::jsNumber(static_cast<double>(us_socket_get_fd(socket))));
#else
return JSValue::encode(JSC::jsNumber(us_socket_get_fd(socket)));
#endif
}
Comment thread
robobun marked this conversation as resolved.
Resolved

} // namespace Bun
10 changes: 10 additions & 0 deletions src/runtime/server/AnyRequestContext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,16 @@ impl AnyRequestContext {
dispatch!(self, None, |_T, ctx| ctx.get_remote_socket_info())
}

pub(crate) fn get_fd(self) -> Option<bun_core::Fd> {
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);
Expand Down
6 changes: 6 additions & 0 deletions src/runtime/server/RequestContext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4384,6 +4384,12 @@ where
})
}

pub(crate) fn get_fd(&self) -> Option<bun_core::Fd> {
let resp = self.live_resp()?;
let fd = resp.get_fd();
if fd.is_valid() { Some(fd) } else { None }
}
Comment thread
robobun marked this conversation as resolved.
Resolved

pub(crate) fn set_timeout(&self, seconds: c_uint) -> bool {
if let Some(resp) = self.live_resp() {
// SAFETY: FFI handle
Expand Down
4 changes: 4 additions & 0 deletions src/runtime/server/server.classes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,10 @@ function generate(name) {
fn: "doRequestIP",
length: 1,
},
requestFD: {
fn: "doRequestFD",
length: 1,
},
timeout: {
fn: "doTimeout",
length: 2,
Expand Down
25 changes: 25 additions & 0 deletions src/runtime/server/server_body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1571,6 +1571,23 @@ where
self.request_ip(request)
}

/// `pub const doRequestFD = host_fn.wrapInstanceMethod(ThisServer, "requestFD", false)`
#[bun_jsc::host_fn(method)]
pub(crate) fn do_request_fd(
&mut self,
global: &JSGlobalObject,
callframe: &CallFrame,
) -> JsResult<JSValue> {
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"))
})?;
let request = arg.as_class_ref::<Request>().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(
Expand Down Expand Up @@ -1616,6 +1633,14 @@ where
)
}

pub(crate) fn request_fd(&self, request: &Request) -> JsResult<JSValue> {
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,
Expand Down
15 changes: 15 additions & 0 deletions src/uws_sys/Response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,12 @@ impl<const SSL: bool> Response<SSL> {
}
}

/// 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()
}
Comment thread
robobun marked this conversation as resolved.
Resolved

pub fn get_remote_socket_info(&mut self) -> Option<SocketAddress> {
let mut ip_ptr: *const u8 = core::ptr::null();
let mut port: i32 = 0;
Expand Down Expand Up @@ -878,6 +884,15 @@ impl AnyResponse {
}
}

/// 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,
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())
}
Expand Down
128 changes: 128 additions & 0 deletions test/js/bun/http/bun-server.test.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,22 @@
import type { Server, ServerWebSocket, Socket } from "bun";
import { dlopen, FFIType, ptr } 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", () => {
Expand Down Expand Up @@ -3637,3 +3643,125 @@ describe("handler GC tracing (heapStats wrapper-count)", () => {
});
}, 30_000);
});
describe.concurrent("node:http socket.fd (Bun extension)", () => {
// 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 { 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);
});

// 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 },
});
let result: { rc: number; addrLen: number } | undefined;
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;
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);
});

// 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]);
// 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,
});
Comment thread
robobun marked this conversation as resolved.
Resolved
});
});
14 changes: 14 additions & 0 deletions test/js/bun/http/serve-http3.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
},
});
Expand Down Expand Up @@ -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 () => {
Expand Down
Loading
Loading