Skip to content

fix(http): report actual errno instead of EADDRINUSE in Bun.serve - #27411

Closed
robobun wants to merge 1 commit into
mainfrom
claude/fix-serve-listen-error-code
Closed

robobun wants to merge 1 commit into
mainfrom
claude/fix-serve-listen-error-code

Conversation

@robobun

@robobun robobun commented Feb 24, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • When Bun.serve fails to bind/listen, the error handler previously only checked for EACCES on Linux and defaulted to EADDRINUSE for all other errors on all platforms
  • Now reads the actual errno on all platforms and maps it to the correct error code (e.g. EADDRNOTAVAIL, EACCES, EPERM), only falling back to EADDRINUSE when errno is SUCCESS or actually ADDRINUSE

Closes #27410

Test plan

  • Added regression test that binds to non-local address 192.0.2.1 and verifies EADDRNOTAVAIL is reported (not EADDRINUSE)
  • Test fails with USE_SYSTEM_BUN=1 (confirms bug exists in released bun)
  • Test passes with bun bd test (confirms fix works)

🤖 Generated with Claude Code

Mintlify

0 threads from 0 users in Mintlify

  • No unresolved comments

Open in Mintlify Editor

When Bun.serve fails to bind/listen, the error handler previously only
checked for EACCES on Linux and defaulted to EADDRINUSE for all other
errors on all platforms. This caused permission errors (EACCES, EPERM)
and other bind failures (EADDRNOTAVAIL) to be incorrectly reported as
"address already in use".

Now reads the actual errno on all platforms and maps it to the correct
error code, only falling back to EADDRINUSE when errno is SUCCESS or
actually EADDRINUSE.

Closes #27410

Co-Authored-By: Claude <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Feb 24, 2026

Copy link
Copy Markdown
Contributor

Walkthrough

Refactors server startup error handling to consolidate errno-based switching in TCP and UNIX paths, improving error propagation from bind/listen failures. Adds regression test verifying correct errno reporting for non-local address binding attempts.

Changes

Cohort / File(s) Summary
Server error handling refactor
src/bun.js/api/server.zig
Consolidates errno-based switching for TCP and UNIX listener startup failures, replacing Linux-specific error-sets approach to properly propagate system errors with attached path information instead of defaulting to EADDRINUSE.
Regression test for errno reporting
test/regression/issue/27410.test.ts
New test verifying Bun.serve reports correct errno when binding to non-local addresses, spawning child process with port 0 and hostname 192.0.2.1 to assert EADDRNOTAVAIL error code.
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: fixing errno reporting in Bun.serve to report actual errno instead of defaulting to EADDRINUSE.
Description check ✅ Passed The PR description covers both required sections: What the PR does (Summary section) and how it was verified (Test plan section with explicit checkmarks).
Linked Issues check ✅ Passed The PR addresses issue #27410 by modifying error handling to map actual errno values (EADDRNOTAVAIL, EACCES, EPERM) instead of defaulting to EADDRINUSE, and includes a regression test.
Out of Scope Changes check ✅ Passed All changes are in-scope: server.zig refactors error handling for the stated objective, and the regression test directly validates the fix for issue #27410.

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


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

@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 the current code and only fix it if needed.

Inline comments:
In `@src/bun.js/api/server.zig`:
- Around line 1755-1767: The TCP listen error branch currently calls
Sys.getErrno(`@as`(i32, -1)) directly; change this to use bun.sys.getErrno to
match the UNIX branch and the rest of the codebase. Update the reference where
errno is set (the variable used to build error_instance) so it calls
bun.sys.getErrno(`@as`(i32, -1)) and ensure downstream usage (e.g.,
bun.sys.Error.fromCode and the assignment to error_instance) remains unchanged.

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 38e4340 and ea38a6e.

📒 Files selected for processing (2)
  • src/bun.js/api/server.zig
  • test/regression/issue/27410.test.ts

Comment thread src/bun.js/api/server.zig
Comment on lines +1755 to +1767
const errno = Sys.getErrno(@as(i32, -1));
switch (errno) {
.SUCCESS, .ADDRINUSE => {
error_instance = (jsc.SystemError{
.message = bun.String.init(std.fmt.bufPrint(&output_buf, "Failed to start server. Is port {d} in use?", .{tcp.port}) catch "Failed to start server"),
.code = bun.String.static("EADDRINUSE"),
.syscall = bun.String.static("listen"),
}).toErrorInstance(globalThis);
},
else => {
var sys_err = bun.sys.Error.fromCode(errno, .listen);
sys_err.path = if (tcp.hostname) |h| std.mem.span(h) else "0.0.0.0";
error_instance = sys_err.toJS(globalThis) catch return;

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.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

# First, let's examine the file around the specified lines
sed -n '1745,1775p' src/bun.js/api/server.zig

Repository: oven-sh/bun

Length of output: 1930


🏁 Script executed:

# Search for where Sys is imported or defined in this file
head -100 src/bun.js/api/server.zig | grep -n "Sys\|import"

Repository: oven-sh/bun

Length of output: 843


🏁 Script executed:

# Check for bun.sys.getErrno usage in the file
rg -n 'bun\.sys\.getErrno' src/bun.js/api/server.zig

Repository: oven-sh/bun

Length of output: 125


🏁 Script executed:

# Search for Sys.getErrno usage to understand the pattern
rg -n 'Sys\.getErrno' src/bun.js/api/server.zig

Repository: oven-sh/bun

Length of output: 125


🏁 Script executed:

# Search for Sys import/definition in the entire file
rg -n 'Sys\s*=' src/bun.js/api/server.zig | head -20

Repository: oven-sh/bun

Length of output: 97


🏁 Script executed:

# Search for where Sys is defined - check for imports and const declarations
grep -n 'const Sys\|pub const Sys\|import.*Sys' src/bun.js/api/server.zig

Repository: oven-sh/bun

Length of output: 97


🏁 Script executed:

# Check the very beginning of the file for imports
head -50 src/bun.js/api/server.zig | cat -n

Repository: oven-sh/bun

Length of output: 2313


🏁 Script executed:

# Look for Sys definition in entire bun codebase
rg -n 'pub const Sys\s*=' src/ | head -10

Repository: oven-sh/bun

Length of output: 37


🏁 Script executed:

# Check what's in sys.zig (2 levels up from server.zig)
ls -la src/sys.zig 2>/dev/null || echo "Not found at src/sys.zig"

Repository: oven-sh/bun

Length of output: 117


🏁 Script executed:

# Find sys.zig in the codebase
fd -t f 'sys\.zig$' src/ | head -10

Repository: oven-sh/bun

Length of output: 66


🏁 Script executed:

# Check if bun.sys is an import of sys.zig by looking at the main bun module
grep -n 'pub const sys' src/bun.zig 2>/dev/null || rg -n 'pub const sys' src/bun.zig

Repository: oven-sh/bun

Length of output: 96


🏁 Script executed:

# Look at the relationship between Sys and bun.sys by checking bun root
head -100 src/bun.zig | grep -n 'sys\|Sys'

Repository: oven-sh/bun

Length of output: 37


🏁 Script executed:

# Check sys.zig getErrno function signature
rg -A 5 'pub fn getErrno' src/sys.zig | head -20

Repository: oven-sh/bun

Length of output: 37


🏁 Script executed:

# Look at getErrno in sys.zig
rg -B 2 -A 10 'pub fn getErrno' src/sys.zig

Repository: oven-sh/bun

Length of output: 37


🏁 Script executed:

# Check if getErrno is exported at module level or if there are multiple versions
rg -n 'getErrno' src/sys.zig

Repository: oven-sh/bun

Length of output: 5222


🏁 Script executed:

# Verify the coding guideline about bun.* vs direct imports
grep -r 'Always use.*bun\.\*' src/ 2>/dev/null | head -5

Repository: oven-sh/bun

Length of output: 322


🏁 Script executed:

# Check if Sys is used elsewhere in server.zig in a similar way
rg -n 'Sys\.' src/bun.js/api/server.zig

Repository: oven-sh/bun

Length of output: 125


🏁 Script executed:

# Verify that bun.sys and Sys are the same by checking imports
grep -n 'const Sys\|const bun' src/bun.js/api/server.zig | head -20

Repository: oven-sh/bun

Length of output: 425


🏁 Script executed:

# Check if the coding guideline document mentions direct imports vs bun namespace
cat src/CLAUDE.md | grep -A 5 -B 5 'bun\.\*'

Repository: oven-sh/bun

Length of output: 1008


Use bun.sys.getErrno to align with the TCP and UNIX branches.

The TCP branch calls Sys.getErrno while the UNIX branch uses bun.sys.getErrno. To maintain consistency across both error-handling paths and follow the guideline to use the bun.* namespace for API access, replace the direct import access with the bun namespace:

Proposed fix
-                        const errno = Sys.getErrno(`@as`(i32, -1));
+                        const errno = bun.sys.getErrno(`@as`(i32, -1));
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const errno = Sys.getErrno(@as(i32, -1));
switch (errno) {
.SUCCESS, .ADDRINUSE => {
error_instance = (jsc.SystemError{
.message = bun.String.init(std.fmt.bufPrint(&output_buf, "Failed to start server. Is port {d} in use?", .{tcp.port}) catch "Failed to start server"),
.code = bun.String.static("EADDRINUSE"),
.syscall = bun.String.static("listen"),
}).toErrorInstance(globalThis);
},
else => {
var sys_err = bun.sys.Error.fromCode(errno, .listen);
sys_err.path = if (tcp.hostname) |h| std.mem.span(h) else "0.0.0.0";
error_instance = sys_err.toJS(globalThis) catch return;
const errno = bun.sys.getErrno(`@as`(i32, -1));
switch (errno) {
.SUCCESS, .ADDRINUSE => {
error_instance = (jsc.SystemError{
.message = bun.String.init(std.fmt.bufPrint(&output_buf, "Failed to start server. Is port {d} in use?", .{tcp.port}) catch "Failed to start server"),
.code = bun.String.static("EADDRINUSE"),
.syscall = bun.String.static("listen"),
}).toErrorInstance(globalThis);
},
else => {
var sys_err = bun.sys.Error.fromCode(errno, .listen);
sys_err.path = if (tcp.hostname) |h| std.mem.span(h) else "0.0.0.0";
error_instance = sys_err.toJS(globalThis) catch return;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/bun.js/api/server.zig` around lines 1755 - 1767, The TCP listen error
branch currently calls Sys.getErrno(`@as`(i32, -1)) directly; change this to use
bun.sys.getErrno to match the UNIX branch and the rest of the codebase. Update
the reference where errno is set (the variable used to build error_instance) so
it calls bun.sys.getErrno(`@as`(i32, -1)) and ensure downstream usage (e.g.,
bun.sys.Error.fromCode and the assignment to error_instance) remains unchanged.

@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.

LGTM — small, correct fix that reads the actual errno; the else branch follows the same pattern as the existing unix error path.

Extended reasoning...

Overview

This PR fixes a bug where Bun.serve always reported EADDRINUSE for any listen failure. The fix reads the actual errno via Sys.getErrno(@as(i32, -1)) and switches on it: SUCCESS/ADDRINUSE still produce the original EADDRINUSE error, while all other errnos now create a proper system error with bun.sys.Error.fromCode. A regression test verifies EADDRNOTAVAIL is reported when binding to a non-local address (192.0.2.1).

Security risks

No security concerns. The change only affects error reporting, not the listen/bind logic itself.

Level of scrutiny

This is production server code, but the change is minimal and mechanical. The else branch (lines 1764-1768) follows the exact same pattern as the existing unix error branch (lines 1780-1783), which already uses bun.sys.Error.fromCode + .path for non-ADDRINUSE errors. The getErrno(@as(i32, -1)) call to read the thread-local errno is the same technique the old code used. The nit about .hostname vs .path is valid but consistent with the unix branch, and the old EACCES branch also did not set .hostname.

Other factors

  • The PR also removes a Linux-only guard (if (comptime Environment.isLinux)), making proper errno reporting work on all platforms — an improvement over the old code which only checked EACCES on Linux.
  • The test follows all CLAUDE.md conventions: uses issue-number file path, bunExe/bunEnv, port: 0, checks stdout before exitCode.
  • The inline nit about missing port in the error message and .path vs .hostname is a minor UX regression, but it is consistent with the existing codebase pattern (unix branch) and does not affect correctness.

Comment thread src/bun.js/api/server.zig
Comment on lines +1764 to +1768
else => {
var sys_err = bun.sys.Error.fromCode(errno, .listen);
sys_err.path = if (tcp.hostname) |h| std.mem.span(h) else "0.0.0.0";
error_instance = sys_err.toJS(globalThis) catch return;
},

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.

🟡 In the else branch (lines 1764-1768), non-ADDRINUSE errors like EACCES lose the port number from the error message (previously "permission denied 0.0.0.0:80", now "EACCES: permission denied, listen '0.0.0.0'") and store the hostname in error.path instead of error.hostname because bun.sys.Error has no hostname field. Constructing a jsc.SystemError directly (like the EADDRINUSE branch does) would fix both issues, allowing .hostname and .port to be set and the port to appear in the message.

Extended reasoning...

What the bug is

The new else branch at lines 1764-1768 handles all non-ADDRINUSE/SUCCESS errno values by creating the error via bun.sys.Error.fromCode(errno, .listen) and setting sys_err.path = hostname. This introduces two minor regressions compared to the old code:

  1. Port number lost from error message: The old EACCES branch formatted the message as "permission denied {s}:{d}" including both hostname and port. The new code sets only the hostname as sys_err.path, and when toSystemError() formats it (Error.zig:270-297), the result is something like "EACCES: permission denied, listen '0.0.0.0'" with no port number.

  2. Hostname in wrong error property: The TCP hostname ends up in error.path on the JS error object, because bun.sys.Error only has path and dest fields. The jsc.SystemError struct does have a .hostname field (SystemError.zig:8), but there is no way to reach it through the bun.sys.Error intermediary.

Concrete example

Consider a user running Bun.serve({ port: 80, hostname: "0.0.0.0", fetch() { return new Response("ok") } }) without root privileges on Linux:

  • Before this PR: Error message was "permission denied 0.0.0.0:80" with code EACCES.
  • After this PR: Error message becomes "EACCES: permission denied, listen '0.0.0.0'" — the port 80 is gone. Additionally, in JS err.path === "0.0.0.0" but err.hostname === undefined, whereas network errors conventionally use .hostname/.address rather than .path.

Why existing code does not prevent it

The bun.sys.Error struct is designed for filesystem syscalls where .path makes sense. It has no .hostname or .port fields. The EADDRINUSE branch correctly avoids this by constructing a jsc.SystemError directly, but the else branch takes the bun.sys.Error shortcut.

Impact

This is a minor UX regression. The correct error code (the PR's main goal) is properly reported, and users typically know which port they configured. The hostname is still available, just on the wrong property. The old code also never set .hostname — it embedded everything in the message string.

Suggested fix

Construct a jsc.SystemError directly in the else branch (matching the EADDRINUSE branch's pattern), setting .hostname, and including the port in the message. This ensures the port appears in the human-readable message and the hostname is on the correct JS error property.

@robobun

robobun commented Feb 24, 2026

Copy link
Copy Markdown
Collaborator Author
Updated 3:38 PM PT - Feb 24th, 2026

❌ Your commit ea38a6e2 has 8 failures in Build #38067 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 27411

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

bun-27411 --bun

@robobun

robobun commented May 7, 2026

Copy link
Copy Markdown
Collaborator Author

Superseded by #30364 — same bug, but #30364 plumbs the real errno out of the uSockets listen callback instead of sniffing Sys.getErrno(-1) after the fact. The getErrno(-1) approach is unreliable (the close/setsockopt calls that run before the callback can clobber errno), which is why the EACCES branch was originally Linux-only and why this PR's test fails on macOS + some Linux lanes.

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bun.serve reports EADDRINUSE when bind is denied (expected EPERM/EACCES)

1 participant