Skip to content

fix(serve): propagate real errno from listen failure (EACCES, EADDRNOTAVAIL, …) - #30364

Closed
robobun wants to merge 1 commit into
mainfrom
farm/26bff18f/serve-listen-errno
Closed

robobun wants to merge 1 commit into
mainfrom
farm/26bff18f/serve-listen-errno

Conversation

@robobun

@robobun robobun commented May 7, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #30363
Fixes #10318
Fixes #25765
Closes #27410

Repro

On macOS, binding Bun.serve to a privileged port as a non-root user should report EACCES:

$ bun -e "Bun.serve({ hostname: '127.0.0.1', port: 80, fetch() { return new Response('ok') } })"
error: Failed to start server. Is port 80 in use?
 syscall: "listen",
   errno: 0,
    code: "EADDRINUSE"

Node reports EACCES with errno: -13 for the same bind. Bun falsely reported EADDRINUSE (and errno: 0) for every listen failure on macOS, and for everything except EACCES on Linux.

Cause

on_listen_failed (src/runtime/server/mod.rs) read errno after the fact via bun_sys::get_errno(-1), but:

  1. The EACCES mapping was gated behind cfg(target_os = "linux").
  2. Even on Linux, errno is not guaranteed to still hold the bind/listen failure by the time the uSockets on_listen(null) callback fires: intermediate close / setsockopt calls can clobber it. On macOS it's clobbered much more reliably.

Net effect: EADDRINUSE for every listen failure on macOS, and for EADDRNOTAVAIL / EPERM / etc. everywhere.

Fix

Plumb the actual errno from the bind/listen syscall up through the uSockets layer the same way Bun.listen already does:

  • HttpContext::listen / listen_unix now accept an optional int *error out-param (default nullptr, backwards-compatible for any out-of-tree caller).
  • uWS::TemplatedApp::listen handler signature is now void(us_listen_socket_t*, int error); on failure the second argument is the errno captured by the bind/listen path.
  • The C shim (uws_app_listen, uws_app_listen_with_config, uws_app_listen_domain_with_options) forwards the errno via the handler typedefs (uws_listen_handler, uws_listen_domain_handler in _libusockets.h).
  • src/uws_sys/App.rs's listen / listen_with_config / listen_on_unix_socket bindings match the new c_int error callback ABI.
  • src/runtime/server/mod.rs's on_listen / on_listen_failed trampolines now receive the errno. on_listen_failed translates it via bun_sys::SystemErrno::init (WSA to errno on Windows, a range validator on POSIX) and maps:
    • EADDRINUSE or an unresolved code -> EADDRINUSE with the "is port in use?" message
    • EACCES -> EACCES with "permission denied host:port" and errno: -13
    • anything else -> bun_sys::Error::new(e, listen).to_system_error() (so EADDRNOTAVAIL, EPERM, etc. surface correctly on both platforms)
  • TCP listen errors now also carry address and port, matching Node and Bun.listen.

The unix-socket branch already used this pattern; it just takes the errno from the handler now instead of sniffing errno at the callsite. The H3 listen path is untouched (separate handler type, unrelated to this bug).

Note: this PR was rebased onto main after the HTTP server was ported from Zig to Rust. The original change targeted server.zig / App.zig; those files are now reference-only (not compiled), so the fix was re-applied to the compiled mod.rs / App.rs. The C/C++ ABI plumbing (bsd.c, App.h, HttpContext.h, libuwsockets.cpp, _libusockets.h) is unchanged from the original approach.

Test

test/js/bun/http/serve.test.ts:

  • Replaces the old Linux-only #7187 test with two cross-platform ones:
    • EACCES test uses ip_unprivileged_port_start - 1 (1023 by default) to avoid picking up a real EADDRINUSE from whatever is already on :80, and skips when running as root or when the Linux sysctl makes that port unprivileged.
    • EADDRNOTAVAIL test binds to 192.0.2.1 (TEST-NET-1, RFC 5737), which returns EADDRNOTAVAIL on every POSIX platform with no privilege required.
  • New regression test for Bun.serve failed to start on localhost subdomain #25765: EADDRINUSE must now carry a non-zero errno (previously the field defaulted to 0 on this branch).

Fail-before/after verified against main (bun bd test test/js/bun/http/serve.test.ts): without the fix the EADDRNOTAVAIL case reports code: "EADDRINUSE" and the EADDRINUSE case reports errno: 0; with the fix both report the correct code and a non-zero errno.

@robobun

robobun commented May 7, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 5:19 PM PT - Jun 28th, 2026

❌ @robobun, your commit 406a94c has 1 failures in Build #66508 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 30364

That installs a local version of the PR into your bun-30364 executable, so you can run:

bun-30364 --bun

@github-actions

github-actions Bot commented May 7, 2026

Copy link
Copy Markdown
Contributor

Found 2 issues this PR may fix:

  1. Attempting to bind to an IP not available returns an incorrect error #10318 - Binding to an unavailable IP (e.g. 172.16.0.1) returns EADDRINUSE instead of EADDRNOTAVAIL; this PR propagates the real errno so the correct error is reported.
  2. Bun.serve failed to start on localhost subdomain #25765 - Bun.serve on a localhost subdomain shows EADDRINUSE with errno: 0; this PR fixes the lost errno so the real bind failure reason is surfaced.

If this is helpful, copy the block below into the PR description to auto-close these issues on merge.

Fixes #10318
Fixes #25765

🤖 Generated with Claude Code

@coderabbitai

coderabbitai Bot commented May 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

Listen socket creation errors are now propagated with precise errno values through the entire callback chain, from C syscall failures up through C++ bindings, Zig FFI, and into the Bun runtime. Tests verify that EACCES and EADDRNOTAVAIL are reported correctly instead of always returning a generic error code.

Changes

Listen error reporting propagation

Layer / File(s) Summary
C API contract
src/uws_sys/_libusockets.h
uws_listen_handler and uws_listen_domain_handler callback signatures now include an int error parameter (errno on bind/listen failure, 0 on success).
C++ libuwsockets bindings
src/uws_sys/libuwsockets.cpp
uws_app_listen, uws_app_listen_with_config, uws_app_listen_domain, and uws_app_listen_domain_with_options forward the errno from libuWSockets into user handlers via the updated callback signature.
uWSockets HttpContext
packages/bun-uws/src/HttpContext.h
listen() and listen_unix() accept an optional int *error out-parameter and write syscall errno to it when provided.
TemplatedApp listen overloads
packages/bun-uws/src/App.h
Six listen() overloads call HttpContext::listen() / listen_unix() with error out-parameter and invoke handlers with (socket, errno) signature.
Zig FFI binding
src/uws_sys/App.zig
Updated uws_listen_handler type alias and listen() / listenWithConfig() / listenOnUnixSocket() to match new C callback ABI with c_int error parameter.
Bun runtime server
src/runtime/server/server.zig
onListen() and onListenFailed() callbacks receive errno, enabling error-specific SystemError creation (EACCES for privileged ports, EADDRNOTAVAIL for non-local addresses, EADDRINUSE as fallback).
BSD socket helpers
packages/bun-usockets/src/bsd.c
BSD helper functions now preserve or explicitly set *error for getaddrinfo and Unix-socket early-failure paths (e.g., LIBUS_ERR, ENAMETOOLONG) so callers receive specific failure codes.
Error reporting tests
test/js/bun/http/serve.test.ts
Tests verify EACCES for non-root privileged port binding (gated by privilege check) and EADDRNOTAVAIL for non-local address binding; an older hardcoded privileged-port test was removed.
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately and concisely summarizes the main change: propagating the actual errno from listen failures through the Bun.serve error reporting layer, fixing incorrect error codes like EACCES and EADDRNOTAVAIL.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description check ✅ Passed Pull request provides comprehensive description covering what it fixes, root cause, solution approach, and test coverage.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/uws_sys/App.zig (1)

306-335: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Fix ABI mismatch: make domain-listen callback socket parameter nullable.

Line 453 declares the domain-listen handler callback with a non-nullable *ListenSocket socket parameter, but the C header (_libusockets.h:126–127) explicitly documents that the socket is NULL on bind/listen failure. The Zig wrapper at line 315 already casts the result to ?*ThisApp.ListenSocket, confirming the callback expects a nullable socket. This mismatch breaks the Unix-socket error path you're adding.

Suggested fix
-        *const (fn (*ListenSocket, domain: [*:0]const u8, i32, err: c_int, *anyopaque) callconv(.c) void),
+        *const (fn (?*ListenSocket, domain: [*:0]const u8, i32, err: c_int, ?*anyopaque) callconv(.c) void),
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/uws_sys/App.zig` around lines 306 - 335, The domain-listen callback
signature currently uses a non-nullable socket pointer which mismatches the C
ABI; change the Wrapper.handle parameter type from *uws.ListenSocket (or
*ThisApp.ListenSocket) to a nullable pointer (?*uws.ListenSocket or
?*ThisApp.ListenSocket) so it can be NULL on bind/listen failure, and update the
call sites that forward to the user handler (the `@call` invocation that casts
socket to `@as`(?*ThisApp.ListenSocket, `@ptrCast`(socket))) to match that nullable
type; ensure the function retains callconv(.c) and that the
c.uws_app_listen_domain_with_options invocation still passes Wrapper.handle and
user_data.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@test/js/bun/http/serve.test.ts`:
- Around line 1595-1607: The privileged-bind regression test currently assumes
port 80 which can be legitimately in use; update the logic in the
canReproducePrivilegedBindEACCES initializer (the IIFE) to avoid hard-coding
port 80: on Linux read /proc/sys/net/ipv4/ip_unprivileged_port_start and compute
a target privileged port as start - 1 (or otherwise choose a rarely-used
privileged port >0 and < start) and use that for the repro check so the only
expected failure is EACCES; ensure the non-Linux branch also picks a rarely-used
privileged port instead of 80 so the test is not flaky.

---

Outside diff comments:
In `@src/uws_sys/App.zig`:
- Around line 306-335: The domain-listen callback signature currently uses a
non-nullable socket pointer which mismatches the C ABI; change the
Wrapper.handle parameter type from *uws.ListenSocket (or *ThisApp.ListenSocket)
to a nullable pointer (?*uws.ListenSocket or ?*ThisApp.ListenSocket) so it can
be NULL on bind/listen failure, and update the call sites that forward to the
user handler (the `@call` invocation that casts socket to
`@as`(?*ThisApp.ListenSocket, `@ptrCast`(socket))) to match that nullable type;
ensure the function retains callconv(.c) and that the
c.uws_app_listen_domain_with_options invocation still passes Wrapper.handle and
user_data.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: db7e0ecb-0959-4a75-b962-06d591b70021

📥 Commits

Reviewing files that changed from the base of the PR and between c5a2f8f and 5fb262f.

📒 Files selected for processing (7)
  • packages/bun-uws/src/App.h
  • packages/bun-uws/src/HttpContext.h
  • src/runtime/server/server.zig
  • src/uws_sys/App.zig
  • src/uws_sys/_libusockets.h
  • src/uws_sys/libuwsockets.cpp
  • test/js/bun/http/serve.test.ts

Comment thread test/js/bun/http/serve.test.ts Resolved
@github-actions

github-actions Bot commented May 7, 2026

Copy link
Copy Markdown
Contributor

This PR may be a duplicate of:

  1. fix(http): report actual errno instead of EADDRINUSE in Bun.serve #27411 - Also fixes errno reporting in Bun.serve listen failures (same fix: propagate real errno instead of always reporting EADDRINUSE), also closes Bun.serve reports EADDRINUSE when bind is denied (expected EPERM/EACCES) #27410.

🤖 Generated with Claude Code

Comment thread src/runtime/server/server.zig Resolved
Comment thread src/runtime/server/server.zig Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@test/js/bun/http/serve.test.ts`:
- Around line 1634-1653: The test that expects Bun.serve binding to 192.0.2.1 to
fail should be guarded so it is skipped when the kernel allows non-local binds;
update the skipped test (the it.skipIf block that calls Bun.serve with hostname
"192.0.2.1") to first detect whether net.ipv4.ip_nonlocal_bind is enabled (e.g.
read /proc/sys/net/ipv4/ip_nonlocal_bind or query sysctl) and skip the test when
its value is "1"/true; keep the existing assertions about the thrown error
intact for the case where non-local binds are disabled.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: db11d908-1cfb-41ea-b15d-afb8dc41e777

📥 Commits

Reviewing files that changed from the base of the PR and between 5fb262f and 59a7e21.

📒 Files selected for processing (2)
  • src/runtime/server/server.zig
  • test/js/bun/http/serve.test.ts

Comment thread test/js/bun/http/serve.test.ts Resolved
Comment thread test/js/bun/http/serve.test.ts Resolved
Comment thread src/runtime/server/server.zig Resolved
Comment thread src/runtime/server/server.zig Resolved
robobun added a commit that referenced this pull request May 7, 2026
Three claude[bot] review findings on #30364:

- 🔴 macOS Mojave (10.14, 2018) lets non-root processes bind ports < 1024
  (nodejs/node#21679). The EACCES privileged-bind test would hard-fail on
  a macOS CI runner since bind() succeeds. Bun's vendored node tests
  already skip macOS for this; now the IIFE is Linux-only.

- 🟡 TCP listen errors used to set sys_err.path = hostname. .path is the
  unix-socket/filesystem field; Node sets .address and .port for TCP
  errors. Drop the .path assignment and .put() address + port directly on
  the JS error (matches Bun's own Listener.zig). Test asserts the new
  shape.

- 🟡 Dedup the WSA→POSIX comment block (old + new paragraphs both said
  the same thing).

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/runtime/server/server.zig`:
- Around line 1928-1953: The .ADDRINUSE and .ACCES switch arms create a
jsc.SystemError and set error_instance but do not attach the Node-style TCP
fields address/port like the generic branch does; update the .ADDRINUSE and
.ACCES handling (the cases in the switch where error_instance is assigned) to
add the same address and port properties to the resulting JS error instance (use
error_instance.put with jsc.ZigString.static("address") /
jsc.ZigString.static("port") or equivalent, mirroring the logic in the else
branch) so EADDRINUSE and EACCES errors have the same shape as other listen
errors.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 8624ad24-967d-4124-ac29-b7c64f0d17a4

📥 Commits

Reviewing files that changed from the base of the PR and between b7e54b2 and 3efa9aa.

📒 Files selected for processing (2)
  • src/runtime/server/server.zig
  • test/js/bun/http/serve.test.ts

Comment thread src/runtime/server/server.zig Resolved
@coderabbitai

coderabbitai Bot commented May 7, 2026

Copy link
Copy Markdown
Contributor

Caution

Failed to replace (edit) comment. This is likely due to insufficient permissions or the comment being deleted.

Error details
{}

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@test/js/bun/http/serve.test.ts`:
- Around line 1599-1613: The test's privileged-bind check (privilegedBindEACCES)
only skips when UID is 0 but misses processes with effective
CAP_NET_BIND_SERVICE, causing flakiness; update the IIFE that computes
privilegedBindEACCES to detect effective CAP_NET_BIND_SERVICE and return null if
present by reading /proc/self/status (or similar) and checking the CapEff bit
for CAP_NET_BIND_SERVICE (bit 13 / 0x2000), in addition to the existing geteuid
check, so the test is skipped when the capability is effective.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 33a6f867-a255-4676-bb54-70ad4c1a5d39

📥 Commits

Reviewing files that changed from the base of the PR and between 3efa9aa and 0532cb2.

📒 Files selected for processing (1)
  • test/js/bun/http/serve.test.ts

Comment thread test/js/bun/http/serve.test.ts Resolved
Comment thread src/runtime/server/server.zig Resolved
Comment thread packages/bun-usockets/src/bsd.c Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/bun-usockets/src/bsd.c (1)

1042-1057: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Initialize *error in bsd_create_listen_socket.

This branch now relies on *error already being 0, but the function never establishes that. Reusing a nonzero out-param here can leak a stale errno into the listen callback when getaddrinfo() fails.

Suggested fix
 LIBUS_SOCKET_DESCRIPTOR bsd_create_listen_socket(const char *host, int port, int options, int* error) {
+    if (error != NULL) {
+        *error = 0;
+    }
+
     struct addrinfo hints, *result;
     memset(&hints, 0, sizeof(struct addrinfo));
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/bun-usockets/src/bsd.c` around lines 1042 - 1057, In
bsd_create_listen_socket, the branch handling getaddrinfo failure assumes the
caller's out-param *error is zero; explicitly clear it there to avoid leaking a
stale value—i.e. before returning LIBUS_SOCKET_ERROR in the "if
(getaddrinfo(...))" block set *error = 0 (guarded with a null check: if (error)
*error = 0;). This ensures the listen callback sees a defined error state.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/bun-usockets/src/bsd.c`:
- Around line 1273-1278: When bsd_create_unix_socket_address(...) early-returns,
don’t overwrite the platform error with the generic *error = LIBUS_ERR; instead
read the platform-specific last-error channel and store that into *error so
callers see the real failure: on Windows call the Win32 socket/error getter
(WSAGetLastError() or GetLastError() as appropriate) and assign that to *error,
and on POSIX keep using errno; update the early-return branch in
bsd_create_unix_socket_address call site (the block that currently sets *error =
LIBUS_ERR and returns LIBUS_SOCKET_ERROR) to propagate the OS error into *error.

---

Outside diff comments:
In `@packages/bun-usockets/src/bsd.c`:
- Around line 1042-1057: In bsd_create_listen_socket, the branch handling
getaddrinfo failure assumes the caller's out-param *error is zero; explicitly
clear it there to avoid leaking a stale value—i.e. before returning
LIBUS_SOCKET_ERROR in the "if (getaddrinfo(...))" block set *error = 0 (guarded
with a null check: if (error) *error = 0;). This ensures the listen callback
sees a defined error state.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 3d62e5f0-3a05-40ce-a40d-b027135a4a79

📥 Commits

Reviewing files that changed from the base of the PR and between 3efa9aa and e55a26d.

📒 Files selected for processing (3)
  • packages/bun-usockets/src/bsd.c
  • src/runtime/server/server.zig
  • test/js/bun/http/serve.test.ts

Comment thread packages/bun-usockets/src/bsd.c Resolved

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No issues found on this revision, but this changes the listen-handler ABI across the C/C++/Zig FFI boundary and rewrites the core Bun.serve listen-failure path, so it warrants a human pass before merge.

Extended reasoning...

Overview

This PR plumbs the real errno from bind()/listen() failures up through the uSockets → uWS → C shim → Zig FFI → server.zig chain so that Bun.serve reports accurate error codes (EACCES, EADDRNOTAVAIL, etc.) instead of always falling back to EADDRINUSE. It touches 8 files across four layers: bsd.c (early-return error population), HttpContext.h/App.h (out-param + handler signature change), _libusockets.h/libuwsockets.cpp (C typedef + lambda signature change), App.zig (FFI wrapper signature change), server.zig (onListen/onListenFailed rewrite with SystemErrno.init translation and Node-style .address/.port attachment), plus three new regression tests in serve.test.ts.

Security risks

None identified. This is error-reporting plumbing; it does not change auth, permissions, or any data-handling path. The only behavioral change visible to users is more accurate err.code/err.errno/err.address/err.port on listen failure.

Level of scrutiny

High. The change is conceptually simple but mechanically broad: it alters a callback ABI (uws_listen_handler, uws_listen_domain_handler, six TemplatedApp::listen overloads, three Zig wrapper signatures) that must stay in lockstep across C, C++, and Zig. Bun.serve's listen path is production-critical — a mismatch here would break server startup, and the Windows path (WSA→POSIX translation, GetLastError vs WSAGetLastError channels) is exercised only by CI. The App.zig listen() wrapper also dropped its uws_app_listen_config_t handler argument in favor of c_int, which is a real signature change for any in-tree caller.

Other factors

The PR has been through several review rounds (Windows WSA enum panic, macOS Mojave privileged-port behavior, .path vs .address semantics, ip_nonlocal_bind/CAP_NET_BIND_SERVICE test gating, Win32 vs Winsock error channels) and all inline threads are resolved. The robobun status on f3deb0d showed widespread build-zig/build-cpp failures; a follow-up commit (47a0e56) landed afterward, so CI on the current head should be confirmed green. There is also a noted potential duplicate (#27411) that a maintainer should reconcile.

Comment thread packages/bun-usockets/src/bsd.c Resolved
robobun added a commit that referenced this pull request May 7, 2026
Per claude[bot] nit on PR #30364 (discussion_r3201353767): the
bsd_set_reuse and IPV6_V6ONLY setsockopt early-returns were the last
two listen-path returns that didn't write *error — the other four
(unix-socket paths) were already covered. Impact is near-zero since
those setsockopt calls essentially never fail on a fresh socket, but
this completes the set for consistency.
Comment thread test/js/bun/http/serve.test.ts Resolved
Comment thread src/runtime/server/server.zig Resolved
Comment thread packages/bun-usockets/src/bsd.c Resolved

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No new issues found and all prior review threads are resolved, but this changes the listen-callback ABI across the C/C++/Zig boundary and rewrites Bun.serve's error path with platform-specific (Winsock/POSIX) handling — worth a human pass before merge.

Extended reasoning...

Overview

This PR plumbs the real errno from bind()/listen() failures up through the entire uSockets→uWS→Zig stack so Bun.serve can report EACCES/EADDRNOTAVAIL/etc. instead of always falling back to EADDRINUSE. It touches 8 files across four layers: the C socket layer (bsd.c), the C++ uWS TemplatedApp::listen overloads and HttpContext, the C-ABI shim (_libusockets.h, libuwsockets.cpp), the Zig FFI wrappers (App.zig), and the runtime consumer (server.zig's onListen/onListenFailed), plus three new regression tests in serve.test.ts.

Security risks

None identified. This is error-reporting/diagnostic surface only — no auth, crypto, or input-parsing changes. The new code paths run only on listen failure, so they don't affect request handling.

Level of scrutiny

This warrants human review. It is not a mechanical change: it alters the uws_listen_handler / uws_listen_domain_handler callback signatures (adding an int error parameter) and the C++ MoveOnlyFunction<void(us_listen_socket_t*, int)> handler type, which must stay in lockstep across C, C++, and Zig extern declarations. Bun.serve is one of the most-used APIs in the runtime, and the new onListenFailed logic has platform-specific branches (Winsock→POSIX translation via SystemErrno.init, the SO_EXCLUSIVEADDRUSE WSAEACCES→WSAEADDRINUSE remap in bsd.c, and the Windows AF_UNIX ERROR_PATH_NOT_FOUND simulation) that earlier review rounds already caught one panic-level bug in.

Other factors

The PR went through ~10 rounds of bot review (20 inline threads, all now resolved) covering a Windows @enumFromInt panic, macOS Mojave privileged-port semantics, ip_nonlocal_bind/CAP_NET_BIND_SERVICE test gating, and .address/.port field consistency — all of which the author addressed. The latest CI build still shows musl build failures and a Windows test timeout, though the recent ci: retrigger commits suggest these are pre-existing flakes. A duplicate PR (#27411) was also flagged. Given the cross-language ABI change, the iterative fix history, and the core code path involved, a human reviewer should confirm the final state before merge.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All my prior concerns have been addressed and I found nothing new in the latest revision, but this changes the listen-handler ABI across four layers (bsd.c → uWS → C shim → Zig FFI → server.zig) plus Windows-specific WSA→errno translation, so it's worth a human sign-off — particularly on the Windows path, which the new tests skip.

Extended reasoning...

Overview

This PR plumbs the real errno from bind()/listen() failure up through the uSockets/uWS/C-shim/Zig-FFI stack into Bun.serve's onListenFailed, so users see EACCES/EADDRNOTAVAIL/etc. instead of the historical hard-coded EADDRINUSE. It touches packages/bun-usockets/src/bsd.c (out-param population at ~9 early-return sites, plus a Windows WSAEACCES→WSAEADDRINUSE normalization for SO_EXCLUSIVEADDRUSE), packages/bun-uws/src/{App.h,HttpContext.h} (handler signature gains int error), src/uws_sys/{_libusockets.h,libuwsockets.cpp,App.zig} (C/Zig FFI ABI updated to match), src/runtime/server/server.zig (onListen/onListenFailed consume the errno, translate via SystemErrno.init, build a Node-shaped error with .errno/.address/.port), and three new regression tests in serve.test.ts.

Security risks

None identified. This is error-reporting plumbing on the listen-failure path; no new inputs are parsed, no auth/permissions logic changes, and the only behavioral change on success is passing 0 through an extra handler argument.

Level of scrutiny

Medium-high. The change itself is conceptually simple, but it's a coordinated ABI change across C, C++, a C shim, and Zig FFI in the core Bun.serve listen path. A mismatch in any one layer would corrupt the callback ABI for every server start. The Windows branch adds WSA-code translation (SystemErrno.init, WSAEACCES→WSAEADDRINUSE, WSAENETDOWN→ERROR_PATH_NOT_FOUND, GetLastError vs WSAGetLastError channel selection) that I previously flagged a critical bug in (the @enumFromInt exhaustive-enum panic, since fixed) — and all three new tests skip win32, so Windows coverage relies on the existing EADDRINUSE test paths surviving the ABI change.

Other factors

Over several review rounds I raised one critical (Windows enum panic), several medium (macOS Mojave gate, missing .errno, .path vs .address, WSAENETDOWN out-param, missing *error writes at various early-returns), and a few nits — all addressed by the author and marked resolved. The current bug-hunt pass found nothing. The branch has ~15 consecutive "ci: retrigger" commits citing pre-existing Windows flakes; whether CI is now green is worth a human confirming before merge. There is also an open duplicate PR (#27411) noted by the bot.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No new findings — all prior review comments are addressed. Deferring to a human only because this threads an ABI change (listen-handler signature) through four layers (bsd.c → uWS → C shim → Zig) on the Bun.serve startup path with platform-specific Windows/WSA handling, which is more than I'm comfortable auto-approving.

Extended reasoning...

Overview

This PR plumbs the real errno from bind()/listen() failures up through uSockets → uWS HttpContext::listen/TemplatedApp::listen → the C shim (uws_app_listen*) → App.zig → server.zig's onListen/onListenFailed, so Bun.serve reports EACCES/EADDRNOTAVAIL/etc. instead of always falling back to EADDRINUSE. It changes the uws_listen_handler / uws_listen_domain_handler typedefs and all six TemplatedApp::listen overloads to carry an int error, adds *error = … writes at ~8 early-return sites in bsd.c (including a Windows SO_EXCLUSIVEADDRUSE WSAEACCES→WSAEADDRINUSE normalization and the AF_UNIX WSAENETDOWN→ERROR_PATH_NOT_FOUND simulation), and rewrites onListenFailed to translate via SystemErrno.init (WSA→POSIX on Windows) and attach Node-style .errno/.address/.port to the JS error. Tests replace the old Linux-only privileged-port check with three carefully gated cross-platform regressions.

Security risks

None identified. This is error-reporting plumbing on the listen-failure path; it doesn't change what binds succeed, doesn't touch auth/crypto/permissions, and doesn't introduce new untrusted input parsing.

Level of scrutiny

Moderate-to-high. The change is conceptually a bugfix, but it (a) alters a cross-language callback ABI that every Bun.serve startup goes through, (b) adds Windows-specific errno translation that the test suite skips (the new tests gate out win32), and (c) went through ~10 review iterations during which a real Windows-only panic (@enumFromInt on a WSA code into an exhaustive enum) and a guaranteed macOS CI failure (Mojave allows non-root low-port binds) were caught and fixed. Bun.serve is one of the most-used production entry points, so a regression here would be widely visible.

Other factors

  • All 10+ inline review comments (mine and CodeRabbit's) are resolved; the current diff reflects every fix.
  • The bug-hunting system found nothing on this revision.
  • The last ~16 commits are pure CI retriggers for documented pre-existing Windows/WebKit flakes, not code changes.
  • A human-flagged duplicate (#27411) exists for the same fix.
  • Test gating is now thorough (root/CAP_NET_BIND_SERVICE/ip_unprivileged_port_start/ip_nonlocal_bind/Mojave all handled), but the EACCES test is Linux-only and the EADDRINUSE/EADDRNOTAVAIL tests skip Windows — so the Windows code path relies on the SystemErrno.init mapping being correct without direct test coverage in this PR.

Given the cross-layer ABI change and platform-specific handling on a critical path, this warrants a human sign-off rather than bot auto-approval, even though I have no remaining concerns with the implementation.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All prior automated review comments are resolved and the bug hunter found nothing further on this revision, but this threads an ABI change through five layers (bsd.c → uWS → C shim → Zig FFI → Bun.serve) with platform-specific Windows/WSA handling on a hot production path, so it's worth a human pass before merge.

Extended reasoning...

Overview

This PR plumbs the real errno from bind()/listen() failures up through the uSockets/uWS stack into Bun.serve's onListenFailed, so users see EACCES/EADDRNOTAVAIL/etc. instead of always EADDRINUSE. It touches 8 files: bsd.c (errno capture at every early-return in the listen path), HttpContext.h / App.h (new int *error out-param and handler signature (socket, int error)), _libusockets.h / libuwsockets.cpp (C-shim callback signature change), App.zig (Zig FFI wrapper signature change), server.zig (consume errno, translate WSA→POSIX via SystemErrno.init, build the SystemError with .errno/.address/.port), and serve.test.ts (three new gated regression tests).

Security risks

None identified. This is error-reporting plumbing on an already-failed listen; no new inputs are parsed and no auth/crypto/permission logic is touched. The only user-controlled value reaching the new code is the configured hostname, which was already used in the pre-existing message and is now additionally placed on err.address via ZigString.initUTF8.

Level of scrutiny

High. This is not a mechanical change: it alters the ABI of uws_listen_handler / uws_listen_domain_handler and the TemplatedApp::listen handler signature, requiring every caller across C/C++/Zig to be updated in lockstep. Bun.serve's listen path is production-critical, and the Windows branch (WSA→POSIX translation, SO_EXCLUSIVEADDRUSE WSAEACCES→WSAEADDRINUSE normalization, GetLastError vs WSAGetLastError channel selection in bsd_create_listen_socket_unix) is subtle enough that an earlier revision had a real safety-checked-UB bug (@enumFromInt of a WSA code into an exhaustive enum) that was caught and fixed during review.

Other factors

  • The PR went through ~7 rounds of fixes in response to automated review (Windows enum panic, macOS Mojave port-1023 gate, ip_nonlocal_bind / CAP_NET_BIND_SERVICE test guards, .path vs .address semantics, missing *error writes at several bsd.c early-returns, WSAENETDOWN→ENOENT simulation). All threads are now resolved and the current bug-hunter pass found nothing.
  • The new tests skip Windows entirely, so the Windows-specific translation logic is not exercised in CI.
  • Recent commit history shows ~17 CI retriggers labeled as pre-existing Windows flakes; a human should confirm those are unrelated to this change.
  • The App.zig listen() (port-only) wrapper's handler third-arg changed from uws_app_listen_config_t to c_int — I verified server.zig is the only in-tree Zig caller of these wrappers.

Given the cross-layer ABI change and platform-specific subtlety, this should not be auto-approved.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All prior feedback addressed and I found nothing further, but this changes the listen-handler ABI across the C/C++/Zig boundary for Bun.serve and adds Windows-specific errno translation that the new tests skip — worth a human pass on those two aspects before merge.

Extended reasoning...

Overview

This PR plumbs the real bind()/listen() errno from the uSockets C layer up through uWS C++ (HttpContext/TemplatedApp), the C shim (libuwsockets.cpp/_libusockets.h), the Zig FFI wrapper (App.zig), and into Bun.serve's onListenFailed (server.zig) so that listen failures report EACCES/EADDRNOTAVAIL/etc. instead of always EADDRINUSE. It also patches several early-return paths in bsd.c to write the *error out-param, adds a Windows WSAEACCES→WSAEADDRINUSE normalization for SO_EXCLUSIVEADDRUSE, and replaces/extends the regression tests in serve.test.ts with carefully-gated EACCES/EADDRNOTAVAIL/EADDRINUSE cases.

Security risks

None identified. The change only affects what error code/message is surfaced when a listen fails; it does not alter bind semantics, port selection, privilege handling, or any request-handling path. The new err.address/err.port fields echo user-provided config back to the user.

Level of scrutiny

This warrants human review. It is a coordinated ABI change to a callback signature across four layers and two languages (the uws_listen_handler typedef and every listen overload), in the production-critical Bun.serve startup path. A mismatch between any two layers would manifest as garbage errno values or worse. The Windows branches (SystemErrno.init WSA translation in server.zig, the SO_EXCLUSIVEADDRUSE/ERROR_PATH_NOT_FOUND rewrites in bsd.c) are not exercised by the new tests, which skip win32.

Other factors

All nine of my prior inline findings (including the 🔴 Windows @enumFromInt panic and the 🔴 macOS Mojave EACCES gate) have been addressed across commits 59a7e21 through the current HEAD, as have CodeRabbit's flakiness guards. The bug-hunting system found nothing in this revision. The PR has been through ~22 CI retriggers for what appear to be unrelated ASAN/infra flakes; the latest robobun status still shows musl build failures and an unrelated fetch-http2-client ASAN assertion. There is also a noted potential overlap with PR #27411. Given the cross-layer scope and untested Windows paths, deferring to a human reviewer rather than auto-approving.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All my earlier inline findings have been addressed and the bug-hunting pass is clean, but this threads an ABI change (listen-handler signature) through C → C++ → Zig FFI → Bun.serve with platform-specific Windows/WSA handling, so it's worth a human pass before merge.

Extended reasoning...

Overview

This PR plumbs the real errno from bind()/listen() failures up through the uSockets/uWebSockets layers into Bun.serve's error reporting, replacing the previous behavior of always reporting EADDRINUSE (with errno: 0). It touches eight files across four layers: the vendored bsd.c (early-return error writes, WSAEACCES→WSAEADDRINUSE normalization, AF_UNIX ENOENT simulation), App.h/HttpContext.h (six listen() overloads now pass (socket, int error) to the handler), the C shim and header (_libusockets.h, libuwsockets.cpp), the Zig FFI bindings (App.zig), the runtime (server.zig onListen/onListenFailed), and three new regression tests in serve.test.ts.

Security risks

None identified. This is error-reporting plumbing on the listen-failure path; it doesn't change accept/request handling, auth, or input parsing. The new err.address/err.port fields echo the user's own config back to them.

Level of scrutiny

High. The change is conceptually straightforward but mechanically wide: it alters a callback ABI across a C/C++/Zig boundary, with platform-conditional code for Windows (Winsock vs. Win32 error channels, SO_EXCLUSIVEADDRUSE quirk), macOS (Mojave low-port behavior, __pthread_fchdir), and Linux (ip_unprivileged_port_start, ip_nonlocal_bind, CAP_NET_BIND_SERVICE). The PR went through several review rounds where real issues were caught and fixed (a Windows @enumFromInt panic on WSA codes, a hard-failing macOS test, .path vs .address semantics). All of my prior inline comments and CodeRabbit's are now resolved.

Other factors

  • A bot flagged this as a possible duplicate of #27411, which a maintainer should reconcile.
  • The latest CI status (build #52656) still shows musl build failures alongside known recurring flakes; the last ~20 commits are CI retriggers, so a human should confirm the musl failures are infra and not this change.
  • The remaining open observation from prior runs (bracketed-IPv6 err.address echoing the raw user input) was explicitly acknowledged as a debatable design choice consistent with Bun.listen, not a blocker.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No issues found in the current revision — all prior bug-hunter and CodeRabbit feedback looks addressed. That said, this threads an ABI change through four layers (bsd.c → uWS C++ → C shim → Zig FFI) on the Bun.serve listen path, and the Windows WSA→POSIX translation in onListenFailed isn't exercised by the new tests (all three skip win32), so I'd like a human to sanity-check the Windows behavior before merge.

Extended reasoning...

Overview

This PR plumbs the real errno from bind()/listen() failures up through uSockets so Bun.serve reports the correct error code (EACCES, EADDRNOTAVAIL, …) instead of always falling back to EADDRINUSE. It touches 8 files across four layers: bsd.c (adds *error = writes at ~8 early-return paths and a Windows WSAEACCES→WSAEADDRINUSE normalization), HttpContext.h / App.h (six listen() overloads now pass an int *error out-param and invoke handlers with (socket, errno)), _libusockets.h / libuwsockets.cpp (handler typedefs gain an int error arg), App.zig (FFI signatures updated to match), and server.zig (onListen/onListenFailed restructured to switch on the plumbed errno via SystemErrno.init and attach Node-style .address/.port to the JS error). Three new regression tests replace one old Linux-only test in serve.test.ts.

Security risks

None identified. This is error-reporting plumbing on the listen-failure path; it doesn't change what binds succeed or fail, only how failures are surfaced. No auth, crypto, permissions, or untrusted-input parsing involved.

Level of scrutiny

High. This is a coordinated ABI change across a C → C++ → C-shim → Zig FFI boundary in the Bun.serve startup path — a signature mismatch on any layer would corrupt the stack on every server start. The error-mapping logic in onListenFailed is also platform-divergent (POSIX errno vs. Winsock codes vs. Win32 GetLastError), and the PR's own review history shows the first revision would have panicked on Windows (@enumFromInt on a non-tag WSA value) before being fixed in 59a7e21. The current revision routes through SystemErrno.init which looks correct, but none of the three new tests run on Windows, so that translation and the new WSAEACCES→WSAEADDRINUSE normalization in bsd.c are CI-untested.

Other factors

  • The PR went through ~10 rounds of bot review (CodeRabbit + bug-hunter); every inline comment is marked resolved and the fixes look correct in the final diff.
  • Recent commits are 50+ "ci: retrigger" pushes for unrelated recurring flakes (next-pages, Windows), which suggests the author is still chasing a green run but the failures aren't from this change.
  • The change pattern mirrors existing prior art in Listener.zig (cited in the new comments), which lends confidence to the Zig-side mapping.
  • The HttpContext::listen out-param defaults to nullptr and local_error is zero-initialized, so any out-of-tree caller of the C++ API is unaffected — only the handler signature is a hard break, and all in-tree callers were updated.

Given the cross-language ABI surface and the untested Windows leg, I'm not comfortable approving without a human reviewer.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All my earlier findings have been addressed and the bug hunter found nothing new on this revision — looks correct to me, but the cross-FFI callback-signature change (uws_listen_handler / uws_listen_domain_handler gaining an int error arg across C/C++/Zig) plus the Windows-only WSA translation paths that CI skips are enough that I'd like a human to give it a final look rather than auto-approving.

Extended reasoning...

Overview

This PR plumbs the real errno from bind()/listen() failures up through uSockets → uWS → the C shim → Zig FFI → Bun.serve's onListenFailed, so users see EACCES/EADDRNOTAVAIL/etc. instead of an unconditional EADDRINUSE with errno: 0. It touches 8 files across four languages: bsd.c (writes *error at every early-return in the listen path, plus a Windows WSAEACCES→WSAEADDRINUSE normalization under SO_EXCLUSIVEADDRUSE), HttpContext.h / App.h (add an optional int *error out-param and forward it through six listen() overloads), _libusockets.h / libuwsockets.cpp (extend uws_listen_handler / uws_listen_domain_handler with an int error argument), App.zig (match the new C ABI), server.zig (consume the errno via SystemErrno.init, build the JS error with .errno/.address/.port), and three new tests in serve.test.ts.

Security risks

None identified. This is error-reporting plumbing only — no new syscalls, no auth/permissions logic, no untrusted-input parsing. The added error_instance.put(...) calls write the user-supplied hostname back onto the JS error object, which is the same value the user passed in.

Level of scrutiny

Moderate-to-high. The change itself is conceptually simple, but it alters a C-ABI callback signature that is consumed across three layers (C++ lambda → C function pointer → Zig extern decl). A mismatch on any one side would crash at runtime, not at compile time. It also adds Windows-specific branches (WSAEACCES→WSAEADDRINUSE, GetLastError() vs WSAGetLastError(), ERROR_PATH_NOT_FOUND translation) that the new tests skip on win32, so a human familiar with the Windows build should sanity-check those. Bun.serve listen failure is a high-traffic code path — getting it wrong (as the original Windows-panic finding in this PR's review history showed) breaks every Windows user who hits a port collision.

Other factors

The PR has been through ~10 rounds of bot review; every prior finding (Windows @enumFromInt panic on WSA codes, macOS Mojave privileged-port test failure, missing .errno on the EADDRINUSE/EACCES branches, .path vs .address semantics, several missed *error writes in bsd.c) has been addressed and the corresponding threads are resolved. The current diff matches what those resolutions described. The ~56 CI retriggers in the commit log appear to be unrelated pre-existing flakes (next-pages / Windows), not failures in the new tests. Given the cross-language ABI change and untested Windows paths, deferring rather than auto-approving.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No outstanding issues from my side — everything I flagged has been addressed — but this is a cross-layer ABI change (C → C++ → C-shim → Zig) on the core Bun.serve listen path, and the Windows-specific errno translation it adds (WSAEACCES→WSAEADDRINUSE, GetLastError vs WSAGetLastError, ERROR_PATH_NOT_FOUND) is skipped by all three new tests, so it's worth a human pass before merge.

Extended reasoning...

Overview

This PR plumbs the real errno from bind/listen failures up through the entire uSockets → uWS → C-shim → Zig stack so that Bun.serve reports EACCES, EADDRNOTAVAIL, etc. instead of always falling back to EADDRINUSE with errno: 0. It touches 8 files: bsd.c (adds *error = … at ~10 early-return sites plus a Windows WSAEACCES→WSAEADDRINUSE normalization), HttpContext.h / App.h (new int *error out-param and handler signature change across 6 listen overloads), _libusockets.h / libuwsockets.cpp (C ABI change to uws_listen_handler / uws_listen_domain_handler), App.zig (matching FFI signature change), server.zig (rewritten onListenFailed with SystemErrno.init-based WSA→POSIX mapping and Node-style .address/.port fields), and three new regression tests in serve.test.ts.

Security risks

None identified. This is error-reporting plumbing on the listen-failure path; it doesn't change how sockets are bound, what permissions are checked, or how requests are handled. No user-controlled input reaches the new code beyond the existing hostname/port/unix config fields.

Level of scrutiny

High. This is a coordinated ABI change across four layers in the production HTTP server's listen path — a mismatch in any one layer (handler arity, argument order, calling convention) would break every Bun.serve call. The server.zig rewrite includes a non-trivial Windows-specific SystemErrno.init + @enumFromInt(@intFromEnum(…)) conversion that was added specifically to avoid the safety-checked-illegal-behavior I flagged earlier; that fix looks correct but is only verified by zig check-windows (compilation), since all three new tests skip win32. The bsd.c changes also add Windows-only branches (SO_EXCLUSIVEADDRUSE → WSAEACCES normalization, GetLastError() vs LIBUS_ERR/WSAGetLastError() channel selection, ERROR_PATH_NOT_FOUND simulation) that have no test coverage in this PR.

Other factors

The PR has been through ~10 rounds of bot review and the author addressed every point (Windows WSA panic, macOS Mojave privileged-port gate, CAP_NET_BIND_SERVICE gate, ip_nonlocal_bind gate, .errno field population, .address/.port consistency across all three TCP arms, the orphaned *error writes in bsd.c). All my inline comments are resolved and the current bug-hunt run found nothing. The recent commit history is ~50 ci: retrigger commits for unrelated flakes (next-pages / Windows), suggesting CI hasn't yet produced a clean run on this branch. Given the scope, the untested Windows paths, and the in-flight CI, this should get a human sign-off rather than a bot approval.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No new issues found and all prior review threads are resolved, but this threads an ABI change (extra int error on the listen handler) through C → C++ → Zig in Bun.serve's startup path with platform-specific Windows/macOS branches — worth a human sanity-check on the signature plumbing and the musl/Windows CI status before merge.

Extended reasoning...

Overview

This PR plumbs the real errno from bind()/listen() failures up through the uSockets → uWebSockets → Zig stack so that Bun.serve reports EACCES, EADDRNOTAVAIL, etc. instead of always falling back to EADDRINUSE. It touches 8 files across four languages: bsd.c (writes *error at ~9 early-return sites + a Windows WSAEACCES→WSAEADDRINUSE normalization), HttpContext.h / App.h (adds an optional int *error out-param and changes the listen handler signature to (us_listen_socket_t*, int)), libuwsockets.cpp / _libusockets.h (forwards the new arg through the C shim), App.zig (updates the extern callback typedefs and three wrapper functions), server.zig (rewrites onListenFailed to switch on the plumbed errno via SystemErrno.init, set .errno/.address/.port on the JS error), and serve.test.ts (three new regression tests with extensive Linux-sysctl/capability gating).

Security risks

None identified. This is purely error-reporting/diagnostic plumbing on the listen-failure path; it doesn't change which binds succeed, doesn't touch auth/crypto/permissions, and doesn't expose any new data beyond the errno that Node already surfaces.

Level of scrutiny

Moderate-to-high. While the intent is straightforward, the implementation is a callback-signature/ABI change threaded through C, C++, and Zig FFI in the core HTTP server's listen path. A mismatch between the C typedef, the C++ lambda arity, and the Zig callconv(.c) wrapper would be a silent runtime corruption rather than a compile error. The PR also went through ~10 rounds of review fixes for real correctness issues (the original revision would have panicked on every Windows listen failure via @enumFromInt on a WSA code; the EACCES test would have hard-failed on macOS Mojave+; etc.), which suggests the cross-platform surface here is genuinely tricky.

Other factors

  • All 13 prior inline review threads (mine and CodeRabbit's) are marked resolved, and the current diff incorporates every fix.
  • The bug-hunting pass on the current revision found nothing new.
  • CI on the latest run still shows musl build failures and a Windows test timeout; the author has retriggered ~70 times labeling them as flakes, but a maintainer should confirm those are unrelated before merge.
  • There's a noted duplicate PR (#27411) that a human may want to reconcile.

Given the multi-layer ABI change in a production-critical path and the outstanding CI noise, I'm deferring rather than shadow-approving.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All earlier review feedback has been addressed and I found nothing new this pass, but this is a cross-layer ABI change (C → C++ → Zig FFI → runtime) on the core Bun.serve listen path with Windows-specific translation that the tests skip — worth a human pass before merge.

Extended reasoning...

Overview

This PR plumbs the real errno from bind()/listen() failures up through the entire uSockets → uWS → C shim → Zig FFI → Bun.serve stack so that Bun.serve reports EACCES, EADDRNOTAVAIL, etc. instead of always falling back to EADDRINUSE with errno: 0. It touches 8 files across four languages: bsd.c (uSockets), App.h/HttpContext.h (uWS C++), libuwsockets.cpp/_libusockets.h (C shim), App.zig (Zig FFI), server.zig (runtime), and serve.test.ts. The core change is a callback-signature/ABI change — uws_listen_handler and the six TemplatedApp::listen overloads now pass an int error alongside the listen socket.

Security risks

None identified. This is error-reporting plumbing on the failure path; it doesn't change how sockets are bound, what permissions are checked, or what data is exposed. The new err.address/err.port fields echo user-supplied config back to the user.

Level of scrutiny

High. The listen path is production-critical for every Bun.serve user, and the change is an ABI modification that must stay in lockstep across C, C++, and Zig extern declarations — a mismatch would be a silent miscompile, not a build error. The Windows branches (WSAEACCES→WSAEADDRINUSE normalization in bsd.c, SystemErrno.init WSA translation in server.zig, GetLastError() vs WSAGetLastError() channel selection) are not exercised by the new tests (all three it.skipIf(process.platform === "win32")), so correctness there rests on code review and the existing Windows CI suite.

Other factors

The PR went through ~10 rounds of review iteration (Windows @enumFromInt UB, macOS Mojave privileged-port gate, CAP_NET_BIND_SERVICE, ip_nonlocal_bind, .path vs .address, missing *error writes at several early-returns) — all of which the author addressed and which are reflected in the current diff. All inline comments are resolved. The ~74 ci: retrigger commits indicate the author is fighting unrelated flakes to get a green build rather than making further code changes. Given the cross-language ABI surface and the untested-by-this-PR Windows paths, a human sign-off is appropriate even though the change looks correct to me.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No issues found in the current revision — all prior review comments are addressed. Deferring to a human reviewer since this threads an ABI change (listen handler signature) through the C/C++/Zig FFI boundary and rewrites the Bun.serve listen-failure path, with the Windows-specific normalization (WSAEACCES→WSAEADDRINUSE, SystemErrno.init) not exercised by the new tests.

Extended reasoning...

Overview

This PR plumbs the real errno from bind()/listen() failures up through uSockets → uWS → C shim → Zig FFI → Bun.serve's onListenFailed, so users see EACCES/EADDRNOTAVAIL/etc. instead of a hard-coded EADDRINUSE with errno: 0. It touches 8 files across four layers: bsd.c (write *error at every TCP/unix listen early-return + Windows WSAEACCES normalization), HttpContext.h/App.h (add int *error out-param and second handler arg to six listen overloads), _libusockets.h/libuwsockets.cpp (extend uws_listen_handler typedef), App.zig (match the new C ABI), server.zig (rewrite onListenFailed to map errno → SystemError + attach Node-style .address/.port), and serve.test.ts (three new gated regression tests).

Security risks

None identified. This is error-reporting plumbing on the listen-failure path; no auth, crypto, input parsing, or privilege changes. The only user-controlled inputs that reach the new code are the hostname/port already validated by ServerConfig, and they flow into error message formatting via bufPrint.

Level of scrutiny

Medium-high. The change itself is conceptually straightforward (propagate an int), but it (a) changes a callback signature across a C/C++/Zig FFI boundary where a mismatch is a silent ABI bug, (b) sits on Bun.serve's hot startup path where a regression is highly visible, and (c) carries Windows-specific logic (WSAEACCES→WSAEADDRINUSE in bsd.c, SystemErrno.init Winsock translation in server.zig, GetLastError() vs WSAGetLastError() channel selection) that the three new tests all gate out via skipIf(win32). CI's Windows lane will exercise the happy path and pre-existing listen-failure tests, but the new error-mapping branches on Windows are effectively untested by this PR.

Other factors

This PR went through ~9 rounds of inline review (Windows @enumFromInt panic, macOS Mojave privileged-port assumption, .path vs .address/.port semantics, missing *error writes in bsd.c, etc.) — all resolved, and the current bug-hunt pass found nothing. The recent commit history is ~75 "ci: retrigger" pushes against unrelated flakes. Given the cross-language signature change to a production-critical entrypoint, a human sign-off is warranted even though the diff now looks clean.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No outstanding issues from my side, but this changes the listen-handler C ABI across four layers (bsd.c → uWS → C shim → Zig) and adds Windows-specific errno translation that the new tests skip — worth a human pass before merge, especially given the overlap with #27411.

Extended reasoning...

Overview

This PR plumbs the real errno from bind/listen failures up through the uSockets stack so Bun.serve reports EACCES, EADDRNOTAVAIL, etc. instead of unconditionally reporting EADDRINUSE with errno: 0. It touches 8 files across four layers: bsd.c (C, errno capture + Windows WSAEACCES→WSAEADDRINUSE normalization), HttpContext.h/App.h (C++, new int *error out-param and changed handler signature on six listen overloads), _libusockets.h/libuwsockets.cpp (C shim, callback typedef gains an int error argument), App.zig (Zig FFI to match), and server.zig (onListen/onListenFailed consume the plumbed errno, route through SystemErrno.init for WSA→POSIX, and attach Node-style .address/.port). Three new tests replace the old Linux-only #7187 test.

Security risks

None identified. The change is confined to error-reporting on the listen-failure path; it does not alter request handling, auth, TLS, or any data-plane logic. The new *error writes are to caller-provided locals, not user-controlled buffers.

Level of scrutiny

Medium-high. Bun.serve's listen path is production-critical, and this is an ABI change to a callback signature threaded through C, C++, a C shim, and Zig — any layer mismatch would manifest as garbage arguments or crashes rather than a clean compile error. The PR went through ~10 review iterations that caught real problems (a Windows @enumFromInt panic on WSA codes, a hard-failing macOS test, .path vs .address semantics, several missed *error writes); all are now resolved. However, the Windows-specific paths (WSAEACCES normalization in bsd.c, SystemErrno.init translation in server.zig, the GetLastError vs WSAGetLastError channel split for AF_UNIX) are not exercised by the new tests, which skip win32.

Other factors

  • The recent commit history is ~80 CI retrigger commits, which suggests the build has been flaky on this branch — a human should confirm the suite is actually green.
  • github-actions flagged #27411 as a potential duplicate fixing the same issue; someone should decide which to land.
  • The remaining unresolved-in-spirit nit (bracketed-IPv6 err.address) was explicitly marked non-blocking and is a defensible design choice.

Given the cross-layer ABI change and untested Windows branches, I'm deferring rather than approving.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All prior review feedback has been addressed and I didn't find any new issues, but this changes the listen-handler ABI across four layers (bsd.c → uWS C++ → C shim → Zig FFI → server.zig) on a hot Bun.serve path with platform-specific errno handling, so it deserves a human sanity check before merge.

Extended reasoning...

Overview

This PR plumbs the real errno from bind()/listen() failures up through the uSockets/uWebSockets stack into Bun.serve's onListenFailed, so users see the correct error code (EACCES, EADDRNOTAVAIL, etc.) instead of a hard-coded EADDRINUSE with errno: 0. It touches 8 files: bsd.c (errno capture at early-returns + Windows WSAEACCES→WSAEADDRINUSE normalization), HttpContext.h / App.h (optional int *error out-param + new (socket, int) handler signature across 6 listen() overloads), libuwsockets.cpp / _libusockets.h (C shim handler typedef gains an int error param), App.zig (Zig FFI matches the new ABI), server.zig (onListen/onListenFailed now receive errno, route through SystemErrno.init for WSA→POSIX, and attach Node-style .address/.port), and three new regression tests in serve.test.ts.

Security risks

None identified. The change only affects error-reporting on listen failure; it doesn't alter bind/listen semantics, permissions, or socket options. No user-controlled input reaches new code paths beyond what was already passed to Bun.serve.

Level of scrutiny

High. This is an ABI change to the listen-callback signature threaded through C, C++, a C shim, and Zig FFI — a mismatch in any layer would corrupt the callback args. It runs on every Bun.serve() call (the most-used Bun API) and has platform-specific branches for Windows Winsock vs. Win32 error channels, macOS, and Linux. An earlier revision had a real Windows regression (@enumFromInt on a WSA code → panic) that was caught and fixed during review, which underscores the subtlety here.

Other factors

The PR went through ~8 rounds of inline review (Windows enum safety, macOS Mojave privileged-port behavior, ip_nonlocal_bind/CAP_NET_BIND_SERVICE test gating, .path vs .address semantics, missed *error writes in bsd.c) and the author addressed every point. All inline comments are resolved. The recent commit history is dominated by "ci: retrigger" commits (80+), which suggests either CI flakiness or active stabilization — worth a human glance at the latest CI status. Given the breadth (4 language layers), the criticality of the path, and the cross-platform subtlety, I'm not comfortable auto-approving even though I believe the current diff is correct.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All prior feedback has been addressed and I have nothing further to flag — deferring to a human reviewer given this changes the listen-callback ABI across the C/C++/Zig boundary and the cross-platform errno translation in Bun.serve's core listen path.

Extended reasoning...

Overview

This PR plumbs the real errno from bind()/listen() failures up through uSockets → uWS → the Zig FFI shim → server.zig's onListenFailed, so Bun.serve reports EACCES, EADDRNOTAVAIL, etc. instead of always falling back to EADDRINUSE with errno: 0. It touches 8 files: bsd.c (errno capture at every early-return in the listen path, plus a Windows WSAEACCES→WSAEADDRINUSE normalization for SO_EXCLUSIVEADDRUSE), HttpContext.h / App.h (new int *error out-param and (socket, int) handler signature across six listen() overloads), _libusockets.h / libuwsockets.cpp (C ABI change to uws_listen_handler / uws_listen_domain_handler), App.zig (matching Zig extern + wrapper signatures), server.zig (onListen/onListenFailed now consume the plumbed errno, route it through SystemErrno.init for WSA→POSIX translation, and attach Node-style .address/.port on the JS error), and serve.test.ts (three new gated regression tests replacing the old Linux-only one).

Security risks

None identified. The change is confined to error-reporting on the listen-failure path; it does not alter accept/auth/TLS logic or expose new data. The new .address field on the thrown error echoes back the user-supplied hostname, which is not sensitive.

Level of scrutiny

High. Bun.serve is one of the most-used APIs in the runtime, and this PR changes a callback ABI that must stay in lockstep across four languages (C header, C++ template, C shim, Zig extern). A mismatch would corrupt the stack on every server start. The Windows-specific Winsock→POSIX errno translation in onListenFailed is also subtle (an earlier revision had a panic-in-safe-mode bug there that was caught and fixed during review). This is well beyond "simple/mechanical" and warrants a human reviewer who owns this area.

Other factors

This PR has been through ~10 rounds of inline review (from both me and CodeRabbit), and the author has addressed every comment — including the Windows @enumFromInt panic, the macOS Mojave privileged-port test gate, the CAP_NET_BIND_SERVICE / ip_nonlocal_bind skip guards, the .path vs .address semantics, the missing .errno field on the EADDRINUSE/EACCES branches, and the remaining *error writes in bsd.c. All inline comments are now resolved and the bug-hunting system found nothing on the current revision. The recent commits are CI retriggers only. I'm not approving solely because of the scope and criticality of the touched code, not because of any outstanding concern.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No remaining issues from my side — all prior feedback was addressed. Deferring to a human reviewer given this changes the listen-handler ABI across the C/C++/Zig boundary and reworks cross-platform errno handling in the core Bun.serve path.

Extended reasoning...

Overview

This PR plumbs the real errno from bind()/listen() failures up through uSockets → uWebSockets → the C shim → Zig FFI → Bun.serve's onListenFailed, so users see EACCES/EADDRNOTAVAIL/etc. instead of an unconditional EADDRINUSE with errno: 0. It touches 8 files across four layers: bsd.c (errno capture at every early-return in the listen path, plus a Windows WSAEACCES→WSAEADDRINUSE normalization for SO_EXCLUSIVEADDRUSE), HttpContext.h / App.h (new int *error out-param and a second int error argument on every listen handler overload), _libusockets.h / libuwsockets.cpp (updated uws_listen_handler / uws_listen_domain_handler typedefs and lambda forwarders), App.zig (Zig-side handler signatures), and server.zig (onListen/onListenFailed now consume the plumbed errno via SystemErrno.init and attach Node-style .address/.port). Tests in serve.test.ts replace the old Linux-only assertion with three cross-platform regressions gated on host capability (ip_unprivileged_port_start, CAP_NET_BIND_SERVICE, ip_nonlocal_bind).

Security risks

None identified. This is error-reporting plumbing on an already-failed listen; it doesn't change which binds succeed, only what's reported when they don't. No new user-controlled input reaches a trust boundary.

Level of scrutiny

High. The change is correct as far as I can verify, and every concern raised in earlier review rounds (Windows WSA→bun.sys.E panic, macOS Mojave privileged-port behavior, .errno/.address/.port consistency, missing *error writes at early-returns, test flakiness guards) has been addressed and resolved. But this is an ABI change to callback signatures threaded through C, C++, and Zig in the hot path of Bun.serve, with platform-specific branches for Windows (Winsock vs Win32 error channels), Linux, and macOS. A mismatch between the C typedef and the Zig extern signature would be a silent miscompile, and the Windows path is untested by CI (the new tests skip win32). That combination warrants a human pass.

Other factors

The PR has iterated through ~85 CI retriggers since the last substantive change, suggesting the author has been chasing CI stability rather than making logic changes. All inline comments on the thread (mine and CodeRabbit's) are marked resolved. The recent commits on main are all retrigger commits, so the diff shown here should be current. There is also a noted potential duplicate (#27411) that a human may want to reconcile before merge.

@robobun
robobun force-pushed the farm/26bff18f/serve-listen-errno branch from d03796b to f7015a7 Compare June 18, 2026 21:06
@robobun

robobun commented Jun 18, 2026

Copy link
Copy Markdown
Collaborator Author

Rebased onto main and force-pushed (f7015a78). The branch was ~6 weeks behind.

Two things worth calling out:

Conflict in bsd.c. main independently added errno population to the same unix-socket early-return path (in #31155). I combined both: kept main's null-guard on the error out-param, and kept this PR's Windows channel fix (that path signals via SetLastError, the Win32 channel, so it reads GetLastError() rather than LIBUS_ERR/WSAGetLastError()).

The HTTP server was ported from Zig to Rust while this PR sat. The original change lived in server.zig / App.zig, which are now reference-only (not compiled). The C/C++ ABI change still compiled, though, so the old diff left a 3-arg C call landing in a 2-arg Rust trampoline and crashed on listen. I re-applied the fix to the compiled files:

  • src/uws_sys/App.rs: the uws_listen_handler typedef and listen / listen_with_config / listen_on_unix_socket bindings now match the c_int error ABI.
  • src/runtime/server/mod.rs: the on_listen / on_listen_unix trampolines and on_listen_failed consume the plumbed errno, translate it with bun_sys::SystemErrno::init, and build the EACCES / EADDRINUSE / generic SystemError with the negated errno plus address / port, mirroring Bun.listen in Listener.rs.
  • The dead server.zig / App.zig edits were reverted to main.

The C/C++ plumbing (bsd.c, App.h, HttpContext.h, libuwsockets.cpp, _libusockets.h) is unchanged from the original approach.

Verified with bun bd test test/js/bun/http/serve.test.ts: on main the EADDRNOTAVAIL case reports code: "EADDRINUSE" and the EADDRINUSE case reports errno: 0; with the fix both report the correct code and a non-zero errno. (The EACCES case is privilege-gated and skips when running as root.)

@robobun
robobun force-pushed the farm/26bff18f/serve-listen-errno branch from c10a25a to cd7fcda Compare June 18, 2026 21:39
Comment thread packages/bun-usockets/src/bsd.c Resolved
@robobun
robobun force-pushed the farm/26bff18f/serve-listen-errno branch from cf76125 to 8175ada Compare June 18, 2026 22:42
Comment thread src/runtime/server/mod.rs Resolved
@robobun
robobun force-pushed the farm/26bff18f/serve-listen-errno branch from 8175ada to 16c6226 Compare June 18, 2026 23:13
@robobun

robobun commented Jun 18, 2026 •

Copy link
Copy Markdown
Collaborator Author

The fix is complete and the diff is green (now at 406a94c, rebased onto current main): all build/compile lanes pass, and the Linux, Windows, and the other macOS test lanes are clean. All review feedback is addressed and all 19 review threads are resolved (the Windows ESRCH->ENOENT mapping, the js_errno temporary-SystemError leak, and the stale context.c comment).

The recent CI reds are all unrelated to this diff, each on a single macOS lane and a different subsystem:

  • build 66508 (darwin 26 aarch64): not a test failure at all, a BuildKite infra timeout, artifact download timed out after 120s for step 'darwin-aarch64-build-bun'.
  • build 63396 (darwin 14 x64): terminal.test.ts "Bun.spawn with terminal option" (90s PTY timeout).
  • build 63378 (darwin 14 aarch64): fetch-leak.test.ts "should not leak using readable stream" (RSS measurement varying ~1-3 MB).

None touch the listen/serve error path this PR changes. I've used my one CI re-roll, so I'm not pushing further retriggers. This needs a maintainer to merge or re-run the macOS lane.

robobun added a commit that referenced this pull request Jun 26, 2026
…un.connect assertion

On non-Linux platforms thread-local errno is not reliably preserved
through the C++/callback chain between the failing bind()/listen() and
on_listen_failed, so reading it could surface a stale unrelated code.
Scope the new errno-based branch to Linux (where the epoll_ctl failure
path explicitly restores errno) and keep the previous EADDRINUSE
fallback elsewhere; PR #30364 plumbs the errno through the callback
signature for the cross-platform case.

Also assert the full Bun.connect rejection shape (ECONNREFUSED, errno
-111, syscall 'connect') instead of only settled == 'rejected'.
Jarred-Sumner pushed a commit that referenced this pull request Jun 26, 2026
… silently deaf (#32706)

## Repro

With an `LD_PRELOAD` shim that makes `epoll_ctl(EPOLL_CTL_ADD)` return
`ENOSPC` for the listen socket (what the real kernel does when
`fs.epoll.max_user_watches` is exhausted):

```
Bun.serve returned ok, port 41949        <- no error thrown
TCP handshake COMPLETED (kernel backlog)  <- connect()-based health checks pass
fetch -> TimeoutError                     <- forever, for every client
```

`Bun.serve()` returns a healthy-looking server object; the kernel keeps
completing handshakes into the listen backlog; the event loop never
hears about the listener. No exception, no `error` callback, nothing on
stderr. Accepted and connecting sockets have the same failure mode.

## Cause

`us_poll_start()` in `packages/bun-usockets/src/eventing/epoll_kqueue.c`
discards the `epoll_ctl` return code. `us_poll_start_rc()` exists but
only `us_socket_from_fd` uses it; `us_socket_group_listen`,
`us_socket_group_listen_unix`, the accept loop in `loop.c`, and all
three connect paths (`us_socket_group_connect_resolved_dns`,
`us_socket_group_connect_unix`, `start_connections`) call the void
variant and carry on as if registration succeeded.

## Fix

Check `us_poll_start_rc()` at every listen/accept/connect site:

- `us_socket_group_listen` / `_listen_unix`: close the fd, free the
poll, write the saved errno to `*error` and restore thread-local
`errno`, return `NULL`. Both `Bun.listen` (which reads the out-param)
and `Bun.serve` (which reads `errno` in `on_listen_failed`) now throw.
- accept loop in `loop.c`: close the accepted fd so the peer sees
RST/FIN instead of a connection that never answers; free the poll;
continue draining the backlog.
- connect paths: close the fd, free the poll, return `NULL` /
`continue`. Callers already handle `NULL` as a connect failure.
- `libuv.c` gains a `us_poll_start_rc` that returns `0` so Windows
links; no behaviour change there.
- `on_listen_failed` (TCP) now surfaces the real errno when it is
neither `SUCCESS` nor `EADDRINUSE`, instead of hardcoding `EADDRINUSE`
for everything that is not `EACCES`. `ENOSPC` now shows up as `ENOSPC`.
(#30364 plumbs the errno through the callback signature properly; this
change is the minimal version that works for the new `epoll_ctl` failure
path and will resolve cleanly against that PR.)

## Verification

```
USE_SYSTEM_BUN=1 bun test test/js/bun/http/serve-epoll-add-fail.test.ts
  (fail) Bun.serve throws ...   -> received { ok: true, port: 33517 }
  (fail) Bun.listen throws ...  -> received { ok: true }
  (fail) accepted connection is closed ... -> timed out after 5000ms

bun bd test test/js/bun/http/serve-epoll-add-fail.test.ts
  (pass) Bun.serve throws when epoll_ctl(EPOLL_CTL_ADD) for the listen socket fails
  (pass) Bun.listen throws when epoll_ctl(EPOLL_CTL_ADD) for the listen socket fails
  (pass) accepted connection is closed when epoll_ctl(EPOLL_CTL_ADD) fails for it
  3 pass, 0 fail
```

The test compiles a tiny `LD_PRELOAD` shim that fails
`epoll_ctl(EPOLL_CTL_ADD)` with `ENOSPC` for either listening sockets
(`SO_ACCEPTCONN == 1`) or connected TCP sockets, selected via an env
var; timerfd/eventfd pass through so the event loop itself starts.
Linux-only.

Found by the `bun-sys-fuzz` syscall-level fault injector
(`listener.epoll_add.0:E28`).

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
@robobun
robobun force-pushed the farm/26bff18f/serve-listen-errno branch from 16c6226 to d7a33b2 Compare June 28, 2026 20:05
@robobun

robobun commented Jun 28, 2026

Copy link
Copy Markdown
Collaborator Author

Rebased onto main again (now at e2a69b7) and force-pushed (d7a33b2).

One conflict, in on_listen_failed (src/runtime/server/mod.rs): main had added a stopgap for the TCP branch that still reads bun_sys::get_errno(-1) after the fact, gated Linux-only (its own comment notes "on other platforms errno is not reliably preserved through the C++/callback chain to here; see PR #30364") and handling the ENOSPC-from-epoll_ctl case.

I kept this PR's version, which supersedes that stopgap: it consumes the errno plumbed through the listen callback (reliable on all platforms, not just Linux), and its generic Some(se) arm already covers the ENOSPC case plus EADDRNOTAVAIL/EPERM/etc., with address and port attached. So no capability from main's stopgap is lost.

The other 7 files auto-merged. Verified with bun bd test test/js/web/fetch/fetch.unix.test.ts test/js/bun/http/serve.test.ts: 237 pass (EADDRNOTAVAIL, EADDRINUSE-errno, unix ENOENT/ENAMETOOLONG all green); the 3 failures are pre-existing container-environment flakes (IPv6 requestIP, localhost-TLS ECONNREFUSED, the egress-proxy-gated /bun:info external-address fetch), unrelated to this diff.

Comment thread src/runtime/server/mod.rs Resolved
Bun.serve reported EADDRINUSE with errno 0 for every listen failure on
macOS, and for everything except EACCES on Linux. on_listen_failed read
errno after the fact, which is unreliable by the time the uSockets listen
callback fires: intermediate close/setsockopt calls clobber it, and the
read was gated to Linux-only anyway.

Plumb the real errno from bind/listen out of uSockets through uWS, the C
shim, and the Rust FFI wrapper into Bun.serve, so listen failures surface
the correct code (EACCES/errno -13, EADDRNOTAVAIL, EPERM, ...) matching
Node. Also attaches address and port to the error on all TCP arms.

On Windows the plumbed value is a Win32/WSA code, so it is mapped through
SystemErrno::init_c_int (the Win32->errno table) rather than the
cross-platform init(i64), whose discriminant fast-path would mis-read
small Win32 codes that collide with a POSIX errno (e.g. ERROR_PATH_NOT_FOUND
3 -> ESRCH instead of ENOENT).

Fixes #30363. Also covers #10318 (EADDRNOTAVAIL on an unavailable IP)
and #25765 (EADDRINUSE reported with errno 0).
@robobun
robobun force-pushed the farm/26bff18f/serve-listen-errno branch from d7a33b2 to 406a94c Compare June 28, 2026 20:31
@robobun

robobun commented Jul 25, 2026

Copy link
Copy Markdown
Collaborator Author

Superseded by #32706. #10318 is now closed as fixed on main.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

1 participant