diff --git a/packages/bun-usockets/src/bsd.c b/packages/bun-usockets/src/bsd.c index fd9fb92ed7d0..1a60a6152f28 100644 --- a/packages/bun-usockets/src/bsd.c +++ b/packages/bun-usockets/src/bsd.c @@ -1097,6 +1097,7 @@ inline __attribute__((always_inline)) LIBUS_SOCKET_DESCRIPTOR bsd_bind_listen_fd ) { if (bsd_set_reuse(listenFd, options) != 0) { + *error = LIBUS_ERR; return LIBUS_SOCKET_ERROR; } @@ -1113,12 +1114,24 @@ inline __attribute__((always_inline)) LIBUS_SOCKET_DESCRIPTOR bsd_bind_listen_fd if (listenAddr->ai_family == AF_INET6) { int enabled = (options & LIBUS_SOCKET_IPV6_ONLY) != 0; if (setsockopt(listenFd, IPPROTO_IPV6, IPV6_V6ONLY, &enabled, sizeof(enabled)) != 0) { + *error = LIBUS_ERR; return LIBUS_SOCKET_ERROR; } } #endif if (us_internal_bind_and_listen(listenFd, listenAddr->ai_addr, (socklen_t) listenAddr->ai_addrlen, 512, error)) { + #if defined(_WIN32) + // With SO_EXCLUSIVEADDRUSE set (which Bun does by default when + // LIBUS_LISTEN_EXCLUSIVE_PORT is passed), Windows returns + // WSAEACCES instead of WSAEADDRINUSE when the port is already + // bound. Libuv/Node normalize this to EADDRINUSE — do the same + // so callers get a consistent code cross-platform. + // https://learn.microsoft.com/en-us/windows/win32/winsock/so-exclusiveaddruse + if ((options & LIBUS_LISTEN_EXCLUSIVE_PORT) && *error == WSAEACCES) { + *error = WSAEADDRINUSE; + } + #endif return LIBUS_SOCKET_ERROR; } @@ -1157,6 +1170,9 @@ LIBUS_SOCKET_DESCRIPTOR bsd_create_listen_socket(const char *host, int port, int snprintf(port_string, 16, "%d", port); if (getaddrinfo(host, port_string, &hints, &result)) { + // getaddrinfo returns an EAI_* code, not a regular errno. Leave + // *error at its caller-initialized 0 so the caller falls back to the + // generic "port in use?" message. return LIBUS_SOCKET_ERROR; } @@ -1166,6 +1182,9 @@ LIBUS_SOCKET_DESCRIPTOR bsd_create_listen_socket(const char *host, int port, int if (a->ai_family == AF_INET6) { listenFd = bsd_create_socket(a->ai_family, a->ai_socktype, a->ai_protocol, NULL); if (listenFd == LIBUS_SOCKET_ERROR) { + // Preserve the real errno (EMFILE, ENFILE, EACCES, …) so the + // caller can surface it if all addrinfos exhaust. + *error = LIBUS_ERR; continue; } @@ -1183,6 +1202,7 @@ LIBUS_SOCKET_DESCRIPTOR bsd_create_listen_socket(const char *host, int port, int if (a->ai_family == AF_INET) { listenFd = bsd_create_socket(a->ai_family, a->ai_socktype, a->ai_protocol, NULL); if (listenFd == LIBUS_SOCKET_ERROR) { + *error = LIBUS_ERR; continue; } @@ -1343,6 +1363,7 @@ static LIBUS_SOCKET_DESCRIPTOR internal_bsd_create_listen_socket_unix(const char listenFd = bsd_create_socket(AF_UNIX, SOCK_STREAM, 0, NULL); if (listenFd == LIBUS_SOCKET_ERROR) { + *error = LIBUS_ERR; return LIBUS_SOCKET_ERROR; } @@ -1353,7 +1374,13 @@ static LIBUS_SOCKET_DESCRIPTOR internal_bsd_create_listen_socket_unix(const char bsd_close_socket(listenFd); #if defined(_WIN32) if (shouldSimulateENOENT) { + // Windows' AF_UNIX impl returns the misleading WSAENETDOWN when + // the socket path's parent directory doesn't exist. Translate + // to ERROR_PATH_NOT_FOUND so SystemErrno.init maps to ENOENT. + // Write *error as well — the caller now reads the plumbed value + // instead of thread-local last-error. SetLastError(ERROR_PATH_NOT_FOUND); + *error = ERROR_PATH_NOT_FOUND; } #endif return LIBUS_SOCKET_ERROR; @@ -1368,9 +1395,16 @@ LIBUS_SOCKET_DESCRIPTOR bsd_create_listen_socket_unix(const char *path, size_t l size_t addrlen = 0; if (bsd_create_unix_socket_address(path, len, &dirfd_workaround_for_unix_path_len, &server_address, &addrlen)) { /* The path could not be expressed as a sockaddr_un (the basename - * exceeds sun_path even with the dirfd workaround); surface the errno - * so the caller can report something better than a codeless failure. */ - if (error && errno) *error = errno; + * exceeds sun_path even with the dirfd workaround); surface the error + * so the caller can report something better than a codeless failure. + * bsd_create_unix_socket_address signals failure via SetLastError + * (the Win32 channel, NOT Winsock) on Windows and via errno on POSIX, + * so read GetLastError directly on Windows rather than LIBUS_ERR. */ + #if defined(_WIN32) + *error = (int)GetLastError(); + #else + if (errno) *error = errno; + #endif return LIBUS_SOCKET_ERROR; } @@ -1379,6 +1413,7 @@ LIBUS_SOCKET_DESCRIPTOR bsd_create_listen_socket_unix(const char *path, size_t l if (__pthread_fchdir(dirfd_workaround_for_unix_path_len) != 0) { close(dirfd_workaround_for_unix_path_len); errno = ENAMETOOLONG; + *error = ENAMETOOLONG; return LIBUS_SOCKET_ERROR; } } diff --git a/packages/bun-usockets/src/context.c b/packages/bun-usockets/src/context.c index b81ce74e290d..567d4abeb214 100644 --- a/packages/bun-usockets/src/context.c +++ b/packages/bun-usockets/src/context.c @@ -375,8 +375,8 @@ struct us_listen_socket_t *us_socket_group_listen(struct us_socket_group_t *grou us_poll_init(p, listen_socket_fd, POLL_TYPE_SEMI_SOCKET); if (us_poll_start_rc(p, group->loop, LIBUS_SOCKET_READABLE) != 0) { /* EPOLL_CTL_ADD failed (e.g. ENOSPC at fs.epoll.max_user_watches). - * Report via both the out-param and thread-local errno: Bun.listen - * reads *error, Bun.serve reads errno. */ + * Report via the out-param, which both Bun.listen and Bun.serve read; + * restore errno across the close/free cleanup so it isn't masked. */ int saved_errno = errno; bsd_close_socket(listen_socket_fd); us_poll_free(p, group->loop); diff --git a/packages/bun-uws/src/App.h b/packages/bun-uws/src/App.h index cccd7263ccd9..f68ad389497d 100644 --- a/packages/bun-uws/src/App.h +++ b/packages/bun-uws/src/App.h @@ -697,45 +697,61 @@ struct TemplatedApp { struct ssl_ctx_st *sslCtxOrNull() { return SSL ? sslCtx : nullptr; } public: + /* The handler's second argument is the errno from the bind/listen syscall on + * failure, or 0 on success. Callers that ignore it still get the listen socket + * (or nullptr) as the first argument. */ + /* Host, port, callback */ - TemplatedApp &&listen(const std::string &host, int port, MoveOnlyFunction &&handler) { + TemplatedApp &&listen(const std::string &host, int port, MoveOnlyFunction &&handler) { if (host.empty()) { return listen(port, std::move(handler)); } - handler(httpContext ? trackListenSocket(httpContext->listen(sslCtxOrNull(), host.c_str(), port, 0)) : nullptr); + int error = 0; + auto *ls = httpContext ? trackListenSocket(httpContext->listen(sslCtxOrNull(), host.c_str(), port, 0, &error)) : nullptr; + handler(ls, ls ? 0 : error); return std::move(*this); } /* Host, port, options, callback */ - TemplatedApp &&listen(const std::string &host, int port, int options, MoveOnlyFunction &&handler) { + TemplatedApp &&listen(const std::string &host, int port, int options, MoveOnlyFunction &&handler) { if (host.empty()) { return listen(port, options, std::move(handler)); } - handler(httpContext ? trackListenSocket(httpContext->listen(sslCtxOrNull(), host.c_str(), port, options)) : nullptr); + int error = 0; + auto *ls = httpContext ? trackListenSocket(httpContext->listen(sslCtxOrNull(), host.c_str(), port, options, &error)) : nullptr; + handler(ls, ls ? 0 : error); return std::move(*this); } /* Port, callback */ - TemplatedApp &&listen(int port, MoveOnlyFunction &&handler) { - handler(httpContext ? trackListenSocket(httpContext->listen(sslCtxOrNull(), nullptr, port, 0)) : nullptr); + TemplatedApp &&listen(int port, MoveOnlyFunction &&handler) { + int error = 0; + auto *ls = httpContext ? trackListenSocket(httpContext->listen(sslCtxOrNull(), nullptr, port, 0, &error)) : nullptr; + handler(ls, ls ? 0 : error); return std::move(*this); } /* Port, options, callback */ - TemplatedApp &&listen(int port, int options, MoveOnlyFunction &&handler) { - handler(httpContext ? trackListenSocket(httpContext->listen(sslCtxOrNull(), nullptr, port, options)) : nullptr); + TemplatedApp &&listen(int port, int options, MoveOnlyFunction &&handler) { + int error = 0; + auto *ls = httpContext ? trackListenSocket(httpContext->listen(sslCtxOrNull(), nullptr, port, options, &error)) : nullptr; + handler(ls, ls ? 0 : error); return std::move(*this); } /* options, callback, path to unix domain socket */ - TemplatedApp &&listen(int options, MoveOnlyFunction &&handler, std::string_view path) { - handler(httpContext ? trackListenSocket(httpContext->listen_unix(sslCtxOrNull(), path.data(), path.length(), options)) : nullptr); + TemplatedApp &&listen(int options, MoveOnlyFunction &&handler, std::string_view path) { + int error = 0; + auto *ls = httpContext ? trackListenSocket(httpContext->listen_unix(sslCtxOrNull(), path.data(), path.length(), options, &error)) : nullptr; + handler(ls, ls ? 0 : error); return std::move(*this); } /* callback, path to unix domain socket */ - TemplatedApp &&listen(MoveOnlyFunction &&handler, std::string_view path, int options) { - handler(httpContext ? trackListenSocket(httpContext->listen_unix(sslCtxOrNull(), path.data(), path.length(), options)) : nullptr); + TemplatedApp &&listen(MoveOnlyFunction &&handler, std::string_view path, int options) { + int error = 0; + auto *ls = httpContext ? trackListenSocket(httpContext->listen_unix(sslCtxOrNull(), path.data(), path.length(), options, &error)) : nullptr; + handler(ls, ls ? 0 : error); return std::move(*this); } diff --git a/packages/bun-uws/src/HttpContext.h b/packages/bun-uws/src/HttpContext.h index 75248bed3f5f..72cdcefb15ac 100644 --- a/packages/bun-uws/src/HttpContext.h +++ b/packages/bun-uws/src/HttpContext.h @@ -676,27 +676,31 @@ struct HttpContext { }, priority); } - /* Listen to port using this HttpContext. ssl_ctx may be nullptr for plain HTTP. */ - us_listen_socket_t *listen(struct ssl_ctx_st *sslCtx, const char *host, int port, int options) { - int error = 0; + /* Listen to port using this HttpContext. ssl_ctx may be nullptr for plain HTTP. + * On failure, *error (if non-null) receives the errno from the bind/listen syscall + * so callers can distinguish EADDRINUSE, EACCES, EADDRNOTAVAIL, etc. */ + us_listen_socket_t *listen(struct ssl_ctx_st *sslCtx, const char *host, int port, int options, int *error = nullptr) { + int local_error = 0; /* HTTP clients always send first (the request, or ClientHello for TLS), so defer * accept() until data arrives and dispatch the read immediately after accept. */ - auto socket = us_socket_group_listen(&group, socketKind(), sslCtx, host, port, options | LIBUS_LISTEN_DEFER_ACCEPT, sizeof(HttpResponseData), &error); + auto socket = us_socket_group_listen(&group, socketKind(), sslCtx, host, port, options | LIBUS_LISTEN_DEFER_ACCEPT, sizeof(HttpResponseData), &local_error); // we dont depend on libuv ref for keeping it alive if (socket) { us_socket_unref(&socket->s); } + if (error) *error = local_error; return socket; } /* Listen to unix domain socket using this HttpContext */ - us_listen_socket_t *listen_unix(struct ssl_ctx_st *sslCtx, const char *path, size_t pathlen, int options) { - int error = 0; - auto* socket = us_socket_group_listen_unix(&group, socketKind(), sslCtx, path, pathlen, options, sizeof(HttpResponseData), &error); + us_listen_socket_t *listen_unix(struct ssl_ctx_st *sslCtx, const char *path, size_t pathlen, int options, int *error = nullptr) { + int local_error = 0; + auto* socket = us_socket_group_listen_unix(&group, socketKind(), sslCtx, path, pathlen, options, sizeof(HttpResponseData), &local_error); // we dont depend on libuv ref for keeping it alive if (socket) { us_socket_unref(&socket->s); } + if (error) *error = local_error; return socket; } diff --git a/src/runtime/server/mod.rs b/src/runtime/server/mod.rs index 12e0defe5c89..8eb627506b66 100644 --- a/src/runtime/server/mod.rs +++ b/src/runtime/server/mod.rs @@ -1702,9 +1702,13 @@ impl NewServer { )); } - pub fn on_listen(&mut self, socket: Option<*mut uws_sys::app::ListenSocket>) { + pub fn on_listen( + &mut self, + socket: Option<*mut uws_sys::app::ListenSocket>, + error: c_int, + ) { let Some(socket) = socket else { - return self.on_listen_failed(); + return self.on_listen_failed(error); }; self.listener = Some(socket); // SAFETY: `vm_mut()` is the process-static `*mut VirtualMachine` (non-null @@ -1724,65 +1728,93 @@ impl NewServer { /// error-stack drain is still TODO; the EADDRINUSE/ /// EACCES paths below cover the node:http `server.listen` error contract. #[cold] - pub fn on_listen_failed(&mut self) { + pub fn on_listen_failed(&mut self, error: c_int) { + use bun_jsc::ZigStringJsc as _; + self.listener = None; let global = self.global_this(); + // `error` is the errno from the failed bind/listen syscall, plumbed up + // through the uSockets listen callback (reading errno after the fact is + // unreliable: intermediate close/setsockopt calls clobber it). 0 yields + // `None`, which keeps the historical "is port in use?" fallback message. + // + // On Windows the plumbed value is a Win32/WSA code (WSAGetLastError / + // GetLastError), so it must go through the Win32→errno table via + // `init_c_int`. The cross-platform `init(i64)` takes a discriminant + // fast-path that would mis-read small Win32 codes whose numeric value + // collides with a POSIX errno (e.g. ERROR_PATH_NOT_FOUND 3 → ESRCH + // instead of ENOENT). On POSIX `error` already is a POSIX errno, so the + // direct discriminant path is correct. + let system_errno = match error { + 0 => None, + #[cfg(windows)] + _ => bun_sys::SystemErrno::init_c_int(error), + #[cfg(not(windows))] + _ => bun_sys::SystemErrno::init(error as i64), + }; + // Node/libuv expose the negated POSIX errno on the JS error. This is the + // same value `Error::to_system_error` writes (see fill_system_error_common), + // derived directly to avoid building and leaking a temporary SystemError + // whose formatted `message` string has no Drop. + let js_errno = system_errno + .map(|se| c_int::from(se as u16).wrapping_neg()) + .unwrap_or(0); + let error_instance = match &self.config.address { - server_config::Address::Tcp { - port, - hostname: _hostname, - } => { - // Rust's `target_os = "linux"` excludes - // Android, so match both explicitly. - #[cfg(any(target_os = "linux", target_os = "android"))] - { - let errno = bun_sys::get_errno(-1i32); - if errno == bun_sys::E::EACCES { - let host = _hostname - .as_ref() - .map(|h| h.as_bytes()) - .unwrap_or(b"0.0.0.0"); - let err = jsc::SystemError { - message: bun_core::String::create_format(format_args!( - "permission denied {}:{}", - bstr::BStr::new(host), - port - )), - code: bun_core::String::static_("EACCES"), - syscall: bun_core::String::static_("listen"), - ..Default::default() - }; - let _ = global.throw_value(err.to_error_instance(global)); - return; + server_config::Address::Tcp { port, hostname } => { + let host = hostname + .as_ref() + .map(|h| h.as_bytes()) + .unwrap_or(b"0.0.0.0"); + let err = match system_errno { + Some(bun_sys::SystemErrno::EACCES) => jsc::SystemError { + errno: js_errno, + message: bun_core::String::create_format(format_args!( + "permission denied {}:{}", + bstr::BStr::new(host), + port + )), + code: bun_core::String::static_("EACCES"), + syscall: bun_core::String::static_("listen"), + ..Default::default() } - // e.g. ENOSPC from epoll_ctl(EPOLL_CTL_ADD). Linux-only because - // on other platforms errno is not reliably preserved through - // the C++/callback chain to here; see PR #30364. - if errno != bun_sys::E::SUCCESS && errno != bun_sys::E::EADDRINUSE { - let err = jsc::SystemError::from( - bun_sys::Error::from_code(errno, bun_sys::Tag::listen) - .to_system_error(), - ); - let _ = global.throw_value(err.to_error_instance(global)); - return; + .to_error_instance(global), + // EADDRINUSE (the common case) or an errno uSockets couldn't + // resolve keeps the historical message. + None + | Some(bun_sys::SystemErrno::SUCCESS) + | Some(bun_sys::SystemErrno::EADDRINUSE) => jsc::SystemError { + errno: js_errno, + message: bun_core::String::create_format(format_args!( + "Failed to start server. Is port {} in use?", + port + )), + code: bun_core::String::static_("EADDRINUSE"), + syscall: bun_core::String::static_("listen"), + ..Default::default() } - } - jsc::SystemError { - message: bun_core::String::create_format(format_args!( - "Failed to start server. Is port {} in use?", - port - )), - code: bun_core::String::static_("EADDRINUSE"), - syscall: bun_core::String::static_("listen"), - ..Default::default() - } - .to_error_instance(global) + .to_error_instance(global), + // EADDRNOTAVAIL, EPERM, … surface with their real code/message. + Some(se) => jsc::SystemError::from( + bun_sys::Error::new(se, bun_sys::Tag::listen).to_system_error(), + ) + .to_error_instance(global), + }; + // Node attaches address + port to TCP listen errors regardless of + // errno (matching `Bun.listen` in Listener.rs). + err.put( + global, + b"address", + bun_core::ZigString::init_utf8(host).to_js(global), + ); + err.put(global, b"port", JSValue::js_number(f64::from(*port))); + err } server_config::Address::Unix(unix) => { let unix = unix.as_bytes(); - match bun_sys::get_errno(-1i32) { - bun_sys::E::SUCCESS => jsc::SystemError { + match system_errno { + None | Some(bun_sys::SystemErrno::SUCCESS) => jsc::SystemError { message: bun_core::String::create_format(format_args!( "Failed to listen on unix socket {}", bun_core::fmt::QuotedFormatter { text: unix } @@ -1792,8 +1824,8 @@ impl NewServer { ..Default::default() } .to_error_instance(global), - e => jsc::SystemError::from( - bun_sys::Error::from_code(e, bun_sys::Tag::listen) + Some(se) => jsc::SystemError::from( + bun_sys::Error::new(se, bun_sys::Tag::listen) .with_path(unix) .to_system_error(), ) @@ -2900,6 +2932,7 @@ mod trampoline { pub(super) extern "C" fn on_listen( socket: *mut UwsListenSocket, + error: c_int, user_data: *mut c_void, ) { // SAFETY: user_data is the `*mut NewServer<..>` passed to listen_with_config. @@ -2909,16 +2942,17 @@ mod trampoline { } else { Some(socket.cast::>()) }; - server.on_listen(socket); + server.on_listen(socket, error); } pub(super) extern "C" fn on_listen_unix( socket: *mut UwsListenSocket, _domain: *const c_char, _flags: i32, + error: c_int, user_data: *mut c_void, ) { - on_listen::(socket, user_data); + on_listen::(socket, error, user_data); } pub(super) extern "C" fn on_404( diff --git a/src/uws_sys/App.rs b/src/uws_sys/App.rs index a1d0af41f224..36b4bcd134e4 100644 --- a/src/uws_sys/App.rs +++ b/src/uws_sys/App.rs @@ -239,7 +239,7 @@ impl App { pub fn listen( &mut self, port: i32, - handler: extern "C" fn(*mut UwsListenSocket, *mut c_void), + handler: extern "C" fn(*mut UwsListenSocket, c_int, *mut c_void), user_data: *mut c_void, ) { // Callers supply the C-ABI shim directly (see the RouteHandler note above). @@ -284,7 +284,7 @@ impl App { pub fn listen_on_unix_socket( &mut self, - handler: extern "C" fn(*mut UwsListenSocket, *const c_char, i32, *mut c_void), + handler: extern "C" fn(*mut UwsListenSocket, *const c_char, i32, c_int, *mut c_void), user_data: *mut c_void, domain_name: &ZStr, flags: i32, @@ -488,7 +488,10 @@ pub type uws_app_t = uws_app_s; pub mod c { use super::*; - pub(crate) type uws_listen_handler = Option; + // The second arg is the errno from the bind/listen syscall when the listen + // socket is null (0 on success). See packages/bun-uws/src/App.h. + pub(crate) type uws_listen_handler = + Option; pub(crate) type uws_method_handler = Option; pub(crate) type uws_filter_handler = Option; @@ -676,7 +679,7 @@ pub mod c { domain: *const c_char, pathlen: usize, flags: i32, - handler: extern "C" fn(*mut UwsListenSocket, *const c_char, i32, *mut c_void), + handler: extern "C" fn(*mut UwsListenSocket, *const c_char, i32, c_int, *mut c_void), user_data: *mut c_void, ); diff --git a/src/uws_sys/_libusockets.h b/src/uws_sys/_libusockets.h index 8f49e123ca36..30c3b24ee654 100644 --- a/src/uws_sys/_libusockets.h +++ b/src/uws_sys/_libusockets.h @@ -123,11 +123,13 @@ typedef struct { uws_websocket_close_handler close; } uws_socket_behavior_t; +/* `error` is the errno from the bind/listen syscall when `listen_socket` is NULL, + * or 0 on success. Callers use it to distinguish EADDRINUSE, EACCES, etc. */ typedef void (*uws_listen_handler)(struct us_listen_socket_t* listen_socket, - void* user_data); + int error, void* user_data); typedef void (*uws_listen_domain_handler)( struct us_listen_socket_t* listen_socket, const char* domain, int options, - void* user_data); + int error, void* user_data); typedef void (*uws_method_handler)(uws_res_t* response, uws_req_t* request, void* user_data); diff --git a/src/uws_sys/libuwsockets.cpp b/src/uws_sys/libuwsockets.cpp index b9a49d00bb6c..0ac57950d8f7 100644 --- a/src/uws_sys/libuwsockets.cpp +++ b/src/uws_sys/libuwsockets.cpp @@ -439,16 +439,16 @@ extern "C" { uWS::SSLApp *uwsApp = (uWS::SSLApp *)app; uwsApp->listen(port, [handler, - user_data](struct us_listen_socket_t *listen_socket) - { handler((struct us_listen_socket_t *)listen_socket, user_data); }); + user_data](struct us_listen_socket_t *listen_socket, int error) + { handler((struct us_listen_socket_t *)listen_socket, error, user_data); }); } else { uWS::App *uwsApp = (uWS::App *)app; uwsApp->listen(port, [handler, - user_data](struct us_listen_socket_t *listen_socket) - { handler((struct us_listen_socket_t *)listen_socket, user_data); }); + user_data](struct us_listen_socket_t *listen_socket, int error) + { handler((struct us_listen_socket_t *)listen_socket, error, user_data); }); } } @@ -462,9 +462,9 @@ extern "C" uWS::SSLApp *uwsApp = (uWS::SSLApp *)app; uwsApp->listen( hostname, port, options, - [handler, user_data](struct us_listen_socket_t *listen_socket) + [handler, user_data](struct us_listen_socket_t *listen_socket, int error) { - handler((struct us_listen_socket_t *)listen_socket, user_data); + handler((struct us_listen_socket_t *)listen_socket, error, user_data); }); } else @@ -472,9 +472,9 @@ extern "C" uWS::App *uwsApp = (uWS::App *)app; uwsApp->listen( hostname, port, options, - [handler, user_data](struct us_listen_socket_t *listen_socket) + [handler, user_data](struct us_listen_socket_t *listen_socket, int error) { - handler((struct us_listen_socket_t *)listen_socket, user_data); + handler((struct us_listen_socket_t *)listen_socket, error, user_data); }); } } @@ -485,15 +485,15 @@ extern "C" if (ssl) { uWS::SSLApp *uwsApp = (uWS::SSLApp *)app; - uwsApp->listen(0,[handler, domain, user_data](struct us_listen_socket_t *listen_socket) - { handler((struct us_listen_socket_t *)listen_socket, domain, 0, user_data); }, + uwsApp->listen(0,[handler, domain, user_data](struct us_listen_socket_t *listen_socket, int error) + { handler((struct us_listen_socket_t *)listen_socket, domain, 0, error, user_data); }, {domain, pathlen}); } else { uWS::App *uwsApp = (uWS::App *)app; - uwsApp->listen(0, [handler, domain, user_data](struct us_listen_socket_t *listen_socket) - { handler((struct us_listen_socket_t *)listen_socket, domain, 0, user_data); }, + uwsApp->listen(0, [handler, domain, user_data](struct us_listen_socket_t *listen_socket, int error) + { handler((struct us_listen_socket_t *)listen_socket, domain, 0, error, user_data); }, {domain, pathlen}); } } @@ -505,16 +505,16 @@ extern "C" { uWS::SSLApp *uwsApp = (uWS::SSLApp *)app; uwsApp->listen( - options, [handler, domain, options, user_data](struct us_listen_socket_t *listen_socket) - { handler((struct us_listen_socket_t *)listen_socket, domain, options, user_data); }, + options, [handler, domain, options, user_data](struct us_listen_socket_t *listen_socket, int error) + { handler((struct us_listen_socket_t *)listen_socket, domain, options, error, user_data); }, {domain, pathlen}); } else { uWS::App *uwsApp = (uWS::App *)app; uwsApp->listen( - options, [handler, domain, options, user_data](struct us_listen_socket_t *listen_socket) - { handler((struct us_listen_socket_t *)listen_socket, domain, options, user_data); }, + options, [handler, domain, options, user_data](struct us_listen_socket_t *listen_socket, int error) + { handler((struct us_listen_socket_t *)listen_socket, domain, options, error, user_data); }, {domain, pathlen}); } } diff --git a/test/js/bun/http/serve.test.ts b/test/js/bun/http/serve.test.ts index b030c46a80af..2c24fc20371d 100644 --- a/test/js/bun/http/serve.test.ts +++ b/test/js/bun/http/serve.test.ts @@ -1859,17 +1859,123 @@ it("should support promise returned from error", async () => { subprocess.kill(); }); -if (process.platform === "linux") - it("should use correct error when using a root range port(#7187)", () => { - expect(() => { +// #7187: EACCES must be reported correctly when binding to a privileged port +// as a non-root user. On Linux, ports below ip_unprivileged_port_start +// (default 1024) require CAP_NET_BIND_SERVICE. macOS is skipped: since +// Mojave (10.14, 2018) non-root processes can bind any port, so this +// assertion would hard-fail on a macOS CI runner — see nodejs/node#21679 +// and Bun's own vendored node test-cluster-bind-privileged-port.js:42-44. +// Pick the highest still-privileged port (start - 1) rather than a +// well-known one like 80/443 which may legitimately be in use and would +// mask the bug with a real EADDRINUSE. +const privilegedBindEACCES: { port: number } | null = (() => { + if (process.platform !== "linux") return null; + // @ts-ignore geteuid exists on posix at runtime + const isRoot = typeof process.geteuid === "function" && process.geteuid() === 0; + if (isRoot) return null; + // A non-root process with effective CAP_NET_BIND_SERVICE can still bind + // privileged ports — skip the test in that environment too. CAP_NET_BIND_SERVICE + // is capability bit 10 (see include/uapi/linux/capability.h). + try { + const capEff = readFileSync("/proc/self/status", "utf8").match(/^CapEff:\s*([0-9a-fA-F]+)$/m)?.[1]; + if (capEff && (BigInt(`0x${capEff}`) & (1n << 10n)) !== 0n) return null; + } catch {} + let unprivilegedStart = 1024; + try { + const start = Number(readFileSync("/proc/sys/net/ipv4/ip_unprivileged_port_start", "utf8").trim()); + if (Number.isFinite(start)) unprivilegedStart = start; + } catch {} + if (unprivilegedStart <= 1) return null; + return { port: unprivilegedStart - 1 }; +})(); + +it.if(privilegedBindEACCES !== null)("reports EACCES (not EADDRINUSE) for privileged bind (#7187, #30363)", () => { + try { + using server = Bun.serve({ + hostname: "127.0.0.1", + port: privilegedBindEACCES!.port, + fetch() { + return new Response("ok"); + }, + }); + throw new Error("should have thrown"); + } catch (e: any) { + expect(e.code).toBe("EACCES"); + expect(e.syscall).toBe("listen"); + expect(e.errno).toBe(-13); // matches Node + expect(e.address).toBe("127.0.0.1"); + expect(e.port).toBe(privilegedBindEACCES!.port); + } +}); + +// #27410, #30363, #10318: errno from the bind/listen syscall must be plumbed +// through so Bun.serve reports the real code (EADDRNOTAVAIL, EACCES, etc.) +// instead of always falling back to EADDRINUSE. Works on macOS and Linux with +// no special privileges — 192.0.2.0/24 is TEST-NET-1 (RFC 5737) and bind() +// returns EADDRNOTAVAIL there on both platforms. Skip on Linux when +// ip_nonlocal_bind is enabled, since the kernel then allows the bind to +// succeed (e.g. on hosts that run a load balancer with floating IPs). +const canReproduceEADDRNOTAVAIL = (() => { + if (process.platform === "win32") return false; + if (process.platform === "linux") { + try { + if (readFileSync("/proc/sys/net/ipv4/ip_nonlocal_bind", "utf8").trim() === "1") return false; + } catch {} + } + return true; +})(); +it.if(canReproduceEADDRNOTAVAIL)( + "reports EADDRNOTAVAIL (not EADDRINUSE) for bind to a non-local address (#30363, #10318)", + () => { + try { using server = Bun.serve({ - port: 1003, - fetch(req) { - return new Response("request answered"); + hostname: "192.0.2.1", + port: 0, + fetch() { + return new Response("ok"); }, }); - }).toThrow("permission denied 0.0.0.0:1003"); + throw new Error("should have thrown"); + } catch (e: any) { + expect(e.code).toBe("EADDRNOTAVAIL"); + expect(e.syscall).toBe("listen"); + expect(typeof e.errno).toBe("number"); + expect(e.errno).not.toBe(0); + // Matches Node: TCP listen errors expose address + port, not path. + expect(e.address).toBe("192.0.2.1"); + expect(typeof e.port).toBe("number"); + } + }, +); + +// #30363, #25765: when a listen actually fails with EADDRINUSE (the common +// case) the returned error must still carry a non-zero errno — previously +// `errno` was always 0 on this path because the SystemError literal omitted +// the field. Node sets it to -48 on macOS, -98 on Linux, -4091 via libuv. +it.skipIf(process.platform === "win32")("EADDRINUSE carries a non-zero errno + address/port (#25765)", async () => { + await using server = Bun.serve({ + port: 0, + fetch() { + return new Response("ok"); + }, }); + try { + using second = Bun.serve({ + port: server.port, + fetch() { + return new Response("ok"); + }, + }); + throw new Error("should have thrown"); + } catch (e: any) { + expect(e.code).toBe("EADDRINUSE"); + expect(e.syscall).toBe("listen"); + expect(typeof e.errno).toBe("number"); + expect(e.errno).not.toBe(0); + expect(e.port).toBe(server.port); + expect(typeof e.address).toBe("string"); + } +}); describe.concurrent("should error with invalid options", async () => { it("requestCert", () => {