diff --git a/packages/bun-uws/src/HttpContext.h b/packages/bun-uws/src/HttpContext.h index 5800f01ce62f..9de8ca11e757 100644 --- a/packages/bun-uws/src/HttpContext.h +++ b/packages/bun-uws/src/HttpContext.h @@ -1138,29 +1138,30 @@ struct HttpContext { group.vtable = &httpVTable; } - /* 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; - /* 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, socketExtSize(), &error); + /* HTTP clients always send first (the request, or ClientHello for TLS), so defer + * accept() until data arrives and dispatch the read immediately after accept. */ + static int tcpListenOptions(int options) { + return options | LIBUS_LISTEN_DEFER_ACCEPT; + } + + static us_listen_socket_t *unrefListenSocket(us_listen_socket_t *socket) { // we dont depend on libuv ref for keeping it alive if (socket) { - us_socket_unref(&socket->s); + us_socket_unref(&socket->s); } return socket; } + /* 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; + return unrefListenSocket(us_socket_group_listen(&group, socketKind(), sslCtx, host, port, tcpListenOptions(options), socketExtSize(), &error)); + } + /* 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, socketExtSize(), &error); - // we dont depend on libuv ref for keeping it alive - if (socket) { - us_socket_unref(&socket->s); - } - - return socket; + return unrefListenSocket(us_socket_group_listen_unix(&group, socketKind(), sslCtx, path, pathlen, options, socketExtSize(), &error)); } }; diff --git a/src/runtime/bake/DevServer.rs b/src/runtime/bake/DevServer.rs index 38d2804a430f..ee669d078cd0 100644 --- a/src/runtime/bake/DevServer.rs +++ b/src/runtime/bake/DevServer.rs @@ -1391,13 +1391,13 @@ pub(crate) fn is_allowed_host_header( { return true; } - if let Some(crate::server::server_config::Address::Tcp { - hostname: Some(h), .. - }) = address - { - return strings::eql_case_insensitive_ascii(host, h.as_bytes(), true); + use crate::server::server_config::Address; + match address { + Some(Address::Tcp { + hostname: Some(h), .. + }) => strings::eql_case_insensitive_ascii(host, h.as_bytes(), true), + Some(Address::Tcp { hostname: None, .. }) | Some(Address::Unix(_)) | None => false, } - false } /// `host[":" port]` / `"[" v6 "]" [":" port]` → host (brackets retained for IPv6). diff --git a/src/runtime/server/ServerConfig.rs b/src/runtime/server/ServerConfig.rs index d0fb2922071d..5bc6608c78cc 100644 --- a/src/runtime/server/ServerConfig.rs +++ b/src/runtime/server/ServerConfig.rs @@ -127,6 +127,16 @@ impl Default for Address { } } +impl Address { + #[inline] + pub(crate) fn is_unix(&self) -> bool { + match self { + Address::Unix(_) => true, + Address::Tcp { .. } => false, + } + } +} + // ZBox frees on Drop; resetting is `*self = Address::default()`. #[derive(Clone, Copy, PartialEq, Eq)] @@ -615,10 +625,6 @@ impl ServerConfig { let env = vm.env_loader(); let mut args = ServerConfig { - address: Address::Tcp { - port: 3000, - hostname: None, - }, development: if let Some(hmr) = vm.transpiler.options.transform_options.serve_hmr { if !hmr { DevelopmentOption::DevelopmentWithoutHmr @@ -634,7 +640,8 @@ impl ServerConfig { reuse_port: env.get(b"NODE_UNIQUE_ID").is_some(), ..ServerConfig::default() }; - let mut has_hostname = false; + let mut hostname: Option = None; + let mut unix: Option = None; if env.get(b"NODE_ENV").unwrap_or(b"") == b"production" { args.development = DevelopmentOption::Production; @@ -645,34 +652,22 @@ impl ServerConfig { } // Set tcp port from env / options - { - let port = 'brk: { - const PORT_ENV: [&[u8]; 3] = [b"BUN_PORT", b"PORT", b"NODE_PORT"]; + let mut port: u16 = 'brk: { + const PORT_ENV: [&[u8]; 3] = [b"BUN_PORT", b"PORT", b"NODE_PORT"]; - for port_env in PORT_ENV { - if let Some(port) = env.get(port_env) { - if let Ok(_port) = bun_core::strings::parse_int::(port, 10) { - break 'brk _port; - } + for port_env in PORT_ENV { + if let Some(port) = env.get(port_env) { + if let Ok(_port) = bun_core::strings::parse_int::(port, 10) { + break 'brk _port; } } + } - if let Some(port) = arguments.vm.transpiler.options.transform_options.port { - break 'brk port; - } - - match &args.address { - Address::Tcp { port, .. } => *port, - _ => unreachable!(), - } - }; - if let Address::Tcp { port: p, .. } = &mut args.address { - *p = port; + if let Some(port) = arguments.vm.transpiler.options.transform_options.port { + break 'brk port; } - } - let mut port = match &args.address { - Address::Tcp { port, .. } => *port, - _ => unreachable!(), + + 3000 }; if let Some(origin) = &arguments.vm.transpiler.options.transform_options.origin { @@ -1078,11 +1073,7 @@ impl ServerConfig { }, )); } - let p = number as u16; - if let Address::Tcp { port: tp, .. } = &mut args.address { - *tp = p; - } - port = p; + port = number as u16; } if let Some(base_uri) = arg.get_truthy(global, "baseURI")? { @@ -1104,24 +1095,20 @@ impl ServerConfig { if !host_str.slice().is_empty() { // Does not reject interior // NUL; the C `bind()` consumer will simply truncate at it. - let hostname = ZBox::from_bytes(host_str.slice()); - if let Address::Tcp { hostname: h, .. } = &mut args.address { - *h = Some(hostname); - } - has_hostname = true; + hostname = Some(ZBox::from_bytes(host_str.slice())); } } - if let Some(unix) = arg.get_stringish(global, "unix")? { - let unix_str = unix.to_utf8(); + if let Some(unix_value) = arg.get_stringish(global, "unix")? { + let unix_str = unix_value.to_utf8(); if !unix_str.slice().is_empty() { - if has_hostname { + if hostname.is_some() { return Err(global.throw_invalid_arguments(format_args!( "Cannot specify both hostname and unix", ))); } - args.address = Address::Unix(bun_core::ZBox::from_bytes(unix_str.slice())); + unix = Some(ZBox::from_bytes(unix_str.slice())); } } @@ -1296,7 +1283,12 @@ impl ServerConfig { "Cannot disable http1 without enabling http2 or http3" ))); } - if !args.http1 && !args.http2 && matches!(args.address, Address::Unix(_)) { + args.address = match unix { + Some(path) => Address::Unix(path), + None => Address::Tcp { port, hostname }, + }; + + if !args.http1 && !args.http2 && args.address.is_unix() { return Err(global.throw_invalid_arguments(format_args!( "Cannot disable http1 with a unix socket — HTTP/3 over AF_UNIX is not supported", ))); @@ -1379,13 +1371,12 @@ impl ServerConfig { args.base_uri = buf.into_boxed_slice(); } } else { - let hostname: &[u8] = if has_hostname { - match &args.address { - Address::Tcp { hostname, .. } => hostname.as_ref().unwrap().as_bytes(), - _ => unreachable!(), - } - } else { - b"0.0.0.0" + let hostname: &[u8] = match &args.address { + Address::Tcp { + hostname: Some(hostname), + .. + } => hostname.as_bytes(), + Address::Tcp { hostname: None, .. } | Address::Unix(_) => b"0.0.0.0", }; let needs_brackets: bool = diff --git a/src/runtime/server/mod.rs b/src/runtime/server/mod.rs index cc938de0a9dd..bb342c0ee90e 100644 --- a/src/runtime/server/mod.rs +++ b/src/runtime/server/mod.rs @@ -1752,11 +1752,14 @@ impl NewServer { } self.notify_inspector_server_stopped(); - if let server_config::Address::Unix(path) = &self.config.address { - let bytes = path.as_bytes(); - if !bytes.is_empty() && bytes[0] != 0 { - let _ = bun_sys::unlink(path.as_zstr()); + match &self.config.address { + server_config::Address::Unix(path) => { + let bytes = path.as_bytes(); + if !bytes.is_empty() && bytes[0] != 0 { + let _ = bun_sys::unlink(path.as_zstr()); + } } + server_config::Address::Tcp { .. } => {} } if !abrupt { @@ -2831,20 +2834,24 @@ impl NewServer { // not `*this`. let global = this_ref.global_this(); - if let server_config::Address::Tcp { - hostname: Some(hostname), - .. - } = &this_ref.config.address - { - let hostname = hostname.as_bytes(); - if !bun_dns::is_valid_hostname(bun_core::ip_address::strip_ipv6_brackets(hostname)) { - let _ = global.throw_value(crate::dns_jsc::cares_jsc::not_a_hostname_error( - global, hostname, - )); - // SAFETY: caller contract — `this` is the live boxed server from `init()`. - Self::deinit(this); - return JSValue::ZERO; + match &this_ref.config.address { + server_config::Address::Tcp { + hostname: Some(hostname), + .. + } => { + let hostname = hostname.as_bytes(); + if !bun_dns::is_valid_hostname(bun_core::ip_address::strip_ipv6_brackets(hostname)) + { + let _ = global.throw_value(crate::dns_jsc::cares_jsc::not_a_hostname_error( + global, hostname, + )); + // SAFETY: caller contract — `this` is the live boxed server from `init()`. + Self::deinit(this); + return JSValue::ZERO; + } } + server_config::Address::Tcp { hostname: None, .. } + | server_config::Address::Unix(_) => {} } let app: *mut uws_sys::NewApp; diff --git a/src/runtime/server/server_body.rs b/src/runtime/server/server_body.rs index 600bf58a69c0..44c9a0c894c8 100644 --- a/src/runtime/server/server_body.rs +++ b/src/runtime/server/server_body.rs @@ -1523,7 +1523,7 @@ where } pub(crate) fn request_ip(&self, request: &Request) -> JsResult { - if matches!(self.config.address, server_config::Address::Unix(_)) { + if self.config.address.is_unix() { return Ok(JSValue::NULL); } let Some(info) = request.request_context.get_remote_socket_info() else { @@ -1550,7 +1550,7 @@ where let seconds = arguments[1]; - if matches!(self.config.address, server_config::Address::Unix(_)) { + if self.config.address.is_unix() { return Ok(JSValue::NULL); } @@ -2492,54 +2492,51 @@ where #[bun_jsc::host_fn(getter)] pub(crate) fn get_address(&self, global: &JSGlobalObject) -> JsResult { - match &self.config.address { + let mut port: u16 = match &self.config.address { server_config::Address::Unix(unix) => { - bun_string_jsc::create_utf8_for_js(global, unix.as_bytes()) + return bun_string_jsc::create_utf8_for_js(global, unix.as_bytes()); } - server_config::Address::Tcp { port: tcp_port, .. } => { - let mut port: u16 = *tcp_port; + server_config::Address::Tcp { port, .. } => *port, + }; - if let Some(listener) = self.listener { - // S008: `app::ListenSocket` is a ZST opaque — safe deref. - let listener = bun_opaque::opaque_deref_mut(listener); - port = listener.get_local_port().unwrap_or(port); + if let Some(listener) = self.listener { + // S008: `app::ListenSocket` is a ZST opaque — safe deref. + let listener = bun_opaque::opaque_deref_mut(listener); + port = listener.get_local_port().unwrap_or(port); - let mut buf = [0u8; 64]; - let Some(address_bytes) = listener.socket().local_address(&mut buf) else { - return Ok(JSValue::NULL); - }; - let addr = match SocketAddress::init(address_bytes, port) { - Ok(a) => a, - Err(_) => { - bun_core::hint::cold(); - return Ok(JSValue::NULL); - } - }; - return addr.into_dto(&self.global()); + let mut buf = [0u8; 64]; + let Some(address_bytes) = listener.socket().local_address(&mut buf) else { + return Ok(JSValue::NULL); + }; + let addr = match SocketAddress::init(address_bytes, port) { + Ok(a) => a, + Err(_) => { + bun_core::hint::cold(); + return Ok(JSValue::NULL); } - if Self::HAS_H3 { - if let Some(h3l) = self.h3_listener { - // S008: `h3::ListenSocket` is an `opaque_ffi!` ZST — safe deref. - let h3l = bun_opaque::opaque_deref_mut(h3l); - port = h3l.get_local_port().unwrap_or(port); - let mut buf = [0u8; 64]; - let Some(address_bytes) = h3l.get_local_address(&mut buf) else { - return Ok(JSValue::NULL); - }; - let addr = match SocketAddress::init(address_bytes, port) { - Ok(a) => a, - Err(_) => { - bun_core::hint::cold(); - return Ok(JSValue::NULL); - } - }; - return addr.into_dto(&self.global()); + }; + return addr.into_dto(&self.global()); + } + if Self::HAS_H3 { + if let Some(h3l) = self.h3_listener { + // S008: `h3::ListenSocket` is an `opaque_ffi!` ZST — safe deref. + let h3l = bun_opaque::opaque_deref_mut(h3l); + port = h3l.get_local_port().unwrap_or(port); + let mut buf = [0u8; 64]; + let Some(address_bytes) = h3l.get_local_address(&mut buf) else { + return Ok(JSValue::NULL); + }; + let addr = match SocketAddress::init(address_bytes, port) { + Ok(a) => a, + Err(_) => { + bun_core::hint::cold(); + return Ok(JSValue::NULL); } - } - let _ = port; - Ok(JSValue::NULL) + }; + return addr.into_dto(&self.global()); } } + Ok(JSValue::NULL) } #[bun_jsc::host_fn(getter)] @@ -2552,36 +2549,27 @@ where #[bun_jsc::host_fn(getter)] pub(crate) fn get_hostname(&self, global: &JSGlobalObject) -> JsResult { - match &self.config.address { + let hostname = match &self.config.address { server_config::Address::Unix(_) => return Ok(JSValue::UNDEFINED), - server_config::Address::Tcp { .. } => {} - } - { - if let Some(listener) = self.listener { - let mut buf = [0u8; 1024]; - // S008: `app::ListenSocket` is a ZST opaque — safe deref. - if let Some(addr) = bun_opaque::opaque_deref_mut(listener) - .socket() - .remote_address(&mut buf[..1024]) - { - if !addr.is_empty() { - return bun_string_jsc::create_utf8_for_js(global, addr); - } - } - } + server_config::Address::Tcp { hostname, .. } => hostname, + }; + if let Some(listener) = self.listener { + let mut buf = [0u8; 1024]; + // S008: `app::ListenSocket` is a ZST opaque — safe deref. + if let Some(addr) = bun_opaque::opaque_deref_mut(listener) + .socket() + .remote_address(&mut buf[..1024]) { - match &self.config.address { - server_config::Address::Tcp { hostname, .. } => { - if let Some(hostname) = hostname { - return bun_string_jsc::create_utf8_for_js(global, hostname.as_bytes()); - } else { - return BunString::static_("localhost").to_js(global); - } - } - server_config::Address::Unix(_) => unreachable!(), + if !addr.is_empty() { + return bun_string_jsc::create_utf8_for_js(global, addr); } } } + if let Some(hostname) = hostname { + bun_string_jsc::create_utf8_for_js(global, hostname.as_bytes()) + } else { + BunString::static_("localhost").to_js(global) + } } #[bun_jsc::host_fn(getter)] @@ -2692,7 +2680,7 @@ where resp: &mut uws_sys::NewAppResponse, ) { jsc::mark_binding!(); - if !matches!(self.config.address, server_config::Address::Unix(_)) + if !self.config.address.is_unix() && (!bake::is_allowed_host_header(req, Some(&self.config.address)) || !resp .get_remote_socket_info() diff --git a/src/uws_sys/libuwsockets.cpp b/src/uws_sys/libuwsockets.cpp index bfb08927d4c0..783938ae7a1d 100644 --- a/src/uws_sys/libuwsockets.cpp +++ b/src/uws_sys/libuwsockets.cpp @@ -412,31 +412,6 @@ extern "C" } } - void uws_app_listen(int ssl, uws_app_t *app, int port, - uws_listen_handler handler, void *user_data) - { - uws_app_listen_config_t config; - config.port = port; - config.host = nullptr; - config.options = 0; - - if (ssl) - { - 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); }); - } - 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); }); - } - } - void uws_app_listen_with_config(int ssl, uws_app_t *app, const char *host, uint16_t port, int32_t options, uws_listen_handler handler, void *user_data) diff --git a/test/js/bun/http/bun-serve-args.test.ts b/test/js/bun/http/bun-serve-args.test.ts index a37874d579da..0821196759d7 100644 --- a/test/js/bun/http/bun-serve-args.test.ts +++ b/test/js/bun/http/bun-serve-args.test.ts @@ -1,6 +1,6 @@ import { serve } from "bun"; import { describe, expect, test } from "bun:test"; -import { isWindows, tmpdirSync } from "../../../harness"; +import { isWindows, tls, tmpdirSync } from "../../../harness"; const defaultHostname = "localhost"; @@ -342,7 +342,7 @@ describe("Bun.serve hostname and port validation", () => { return new Response("ok"); }, }), - ).toThrow(); + ).toThrow("Cannot specify both hostname and unix"); }); test("unix with no hostname/port is valid", () => { @@ -660,7 +660,23 @@ describe("Bun.serve unix socket validation", () => { return new Response("ok"); }, }), - ).toThrow(); + ).toThrow("Cannot specify both hostname and unix"); + }); + + // HTTP/3 is the only protocol left, and it needs a UDP socket. + test("unix socket with http3 and no http1 or http2 should throw", () => { + expect(() => + // @ts-expect-error - Testing invalid combination + serve({ + unix: "bun-serve-args-http3-only.sock", + http1: false, + http3: true, + tls, + fetch() { + return new Response("ok"); + }, + }), + ).toThrow("Cannot disable http1 with a unix socket"); }); describe("invalid unix socket paths should throw", () => {