Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions packages/bun-usockets/src/bsd.c
Original file line number Diff line number Diff line change
Expand Up @@ -1604,10 +1604,13 @@ int bsd_bind_udp_fd(LIBUS_SOCKET_DESCRIPTOR fd, const struct sockaddr *addr, int
return 0;
}

LIBUS_SOCKET_DESCRIPTOR bsd_create_udp_socket(const char *host, int port, int options, int *err) {
LIBUS_SOCKET_DESCRIPTOR bsd_create_udp_socket(const char *host, int port, int options, int *err, int *dns_error) {
if (err != NULL) {
*err = 0;
}
if (dns_error != NULL) {
*dns_error = 0;
}

struct addrinfo hints, *result;
memset(&hints, 0, sizeof(struct addrinfo));
Expand All @@ -1621,8 +1624,10 @@ LIBUS_SOCKET_DESCRIPTOR bsd_create_udp_socket(const char *host, int port, int op

int gai_result = getaddrinfo(host, port_string, &hints, &result);
if (gai_result != 0) {
if (err != NULL) {
*err = -gai_result;
/* An EAI_* code shares its numeric range with errno values (and is negative on
* glibc), so it must not go out through `err`. */
if (dns_error != NULL) {
*dns_error = gai_result;
}
return LIBUS_SOCKET_ERROR;
}
Expand Down
6 changes: 4 additions & 2 deletions packages/bun-usockets/src/internal/networking/bsd.h
Original file line number Diff line number Diff line change
Expand Up @@ -234,8 +234,10 @@ LIBUS_SOCKET_DESCRIPTOR bsd_create_listen_socket(const char *host, int port, int

LIBUS_SOCKET_DESCRIPTOR bsd_create_listen_socket_unix(const char *path, size_t pathlen, int options, int* error);

/* Creates an UDP socket bound to the hostname and port */
LIBUS_SOCKET_DESCRIPTOR bsd_create_udp_socket(const char *host, int port, int options, int *err);
/* Creates an UDP socket bound to the hostname and port. On failure `err` (optional) holds the errno of
* the failing socket call; when `host` itself did not resolve, `dns_error` (optional) holds the
* getaddrinfo(3) return code and `err` is 0. */
LIBUS_SOCKET_DESCRIPTOR bsd_create_udp_socket(const char *host, int port, int options, int *err, int *dns_error);
int bsd_connect_udp_socket(LIBUS_SOCKET_DESCRIPTOR fd, const char *host, int port);
int bsd_disconnect_udp_socket(LIBUS_SOCKET_DESCRIPTOR fd);

Expand Down
4 changes: 3 additions & 1 deletion packages/bun-usockets/src/libusockets.h
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,9 @@ struct us_udp_packet_buffer_t *us_create_udp_packet_buffer();

//struct us_udp_socket_t *us_create_udp_socket(us_loop_r loop, void (*data_cb)(struct us_udp_socket_t *, struct us_udp_packet_buffer_t *, int), void (*drain_cb)(struct us_udp_socket_t *), char *host, unsigned short port);

struct us_udp_socket_t *us_create_udp_socket(us_loop_r loop, void (*data_cb)(struct us_udp_socket_t *, void *, int), void (*drain_cb)(struct us_udp_socket_t *), void (*close_cb)(struct us_udp_socket_t *), void (*recv_error_cb)(struct us_udp_socket_t *, int, int), const char *host, unsigned short port, int flags, int *err, void *user);
/* Returns NULL on failure. `err` (optional) then holds the errno of the failing socket call; when `host`
* itself did not resolve, `dns_error` (optional) holds the getaddrinfo(3) return code and `err` is 0. */
struct us_udp_socket_t *us_create_udp_socket(us_loop_r loop, void (*data_cb)(struct us_udp_socket_t *, void *, int), void (*drain_cb)(struct us_udp_socket_t *), void (*close_cb)(struct us_udp_socket_t *), void (*recv_error_cb)(struct us_udp_socket_t *, int, int), const char *host, unsigned short port, int flags, int *err, int *dns_error, void *user);

void us_udp_socket_close(struct us_udp_socket_t *s);

Expand Down
6 changes: 3 additions & 3 deletions packages/bun-usockets/src/quic.c
Original file line number Diff line number Diff line change
Expand Up @@ -862,7 +862,7 @@ us_quic_listen_socket_t *us_quic_socket_context_listen(
int err = 0;
ls->udp = us_create_udp_socket(ctx->loop,
us_quic_udp_on_data, us_quic_udp_on_drain, us_quic_udp_on_close, NULL,
host, (unsigned short) port, flags, &err, ls);
host, (unsigned short) port, flags, &err, NULL, ls);
if (!ls->udp) { us_free(ls); return NULL; }
us_quic_set_dontfrag(ls->udp);

Expand Down Expand Up @@ -1214,12 +1214,12 @@ static us_quic_listen_socket_t *us_quic_client_endpoint(us_quic_socket_context_t
int err = 0;
ls->udp = us_create_udp_socket(ctx->loop,
us_quic_udp_on_data, us_quic_udp_on_drain, us_quic_udp_on_close, NULL,
"::", 0, 0, &err, ls);
"::", 0, 0, &err, NULL, ls);
if (!ls->udp) {
err = 0;
ls->udp = us_create_udp_socket(ctx->loop,
us_quic_udp_on_data, us_quic_udp_on_drain, us_quic_udp_on_close, NULL,
"0.0.0.0", 0, 0, &err, ls);
"0.0.0.0", 0, 0, &err, NULL, ls);
}
if (!ls->udp) { us_free(ls); return NULL; }
us_quic_set_dontfrag(ls->udp);
Expand Down
3 changes: 2 additions & 1 deletion packages/bun-usockets/src/udp.c
Original file line number Diff line number Diff line change
Expand Up @@ -181,14 +181,15 @@ struct us_udp_socket_t *us_create_udp_socket(
unsigned short port,
int flags,
int *err,
int *dns_error,
void *user
) {

/* IP_RECVERR is only useful when there is an on_recv_error handler to
* drain the error queue; without one it only poisons subsequent sends. */
if (recv_error_cb) flags |= LIBUS_UDP_LINUX_RECVERR;
else flags &= ~LIBUS_UDP_LINUX_RECVERR;
LIBUS_SOCKET_DESCRIPTOR fd = bsd_create_udp_socket(host, port, flags, err);
LIBUS_SOCKET_DESCRIPTOR fd = bsd_create_udp_socket(host, port, flags, err, dns_error);
if (fd == LIBUS_SOCKET_ERROR) {
return 0;
}
Expand Down
7 changes: 6 additions & 1 deletion src/runtime/node/quic/endpoint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1363,6 +1363,7 @@ impl QuicEndpoint {
return Ok(true);
}
let mut err: c_int = 0;
let mut dns_error: c_int = 0;
let cfg = self.bind_config.get();
let socket = uws::udp::Socket::create(
uws::Loop::get(),
Expand All @@ -1374,6 +1375,7 @@ impl QuicEndpoint {
cfg.port,
0,
Some(&mut err),
Some(&mut dns_error),
core::ptr::from_ref(self).cast_mut().cast::<c_void>(),
);
if !socket.is_null() {
Expand All @@ -1386,7 +1388,10 @@ impl QuicEndpoint {
.with_mut(|r| r.set_strong(this_value, global));
self.finish_close();
self.pending_endpoint_close.set(false);
self.deliver_endpoint_close(global, CLOSECONTEXT_BIND_FAILURE, err);
// `host` is always an IP literal, so `dns_error` is at most
// EAI_MEMORY/EAI_SYSTEM; the status only feeds the close message.
let status = if err != 0 { err } else { dns_error };
self.deliver_endpoint_close(global, CLOSECONTEXT_BIND_FAILURE, status);
return Ok(false);
}
self.socket.set(Some(socket));
Expand Down
16 changes: 15 additions & 1 deletion src/runtime/socket/udp_socket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -633,6 +633,7 @@ impl UDPSocket {
.set(UDPSocketConfig::from_js(global_this, options, this_value)?);

let mut err: c_int = 0;
let mut dns_error: c_int = 0;

let config = this.config.get();
let hostname_z = config.hostname.to_owned_slice_z();
Expand Down Expand Up @@ -679,10 +680,10 @@ impl UDPSocket {
config.port,
config.flags,
Some(&mut err),
Some(&mut dns_error),
this_ptr.cast::<c_void>(),
)
};
drop(hostname_z);
this.socket.set(if created.is_null() {
None
} else {
Expand All @@ -698,6 +699,19 @@ impl UDPSocket {
dgram_rollback_adoption(fd, previous);
}
this.closed.set(true);
// The hostname never resolved: `dns_error` is a raw getaddrinfo(3)
// code, not an errno. Report it the way `Bun.connect`/`fetch` do
// (`getaddrinfo ENOTFOUND <hostname>`, with `syscall`/`hostname`).
if let Some(dns_err) = c_ares::Error::init_eai(dns_error).filter(|_| dns_error != 0) {
return Err(global_this.throw_value(
crate::dns_jsc::cares_jsc::system_error_with_syscall_and_hostname(
dns_err,
b"getaddrinfo",
hostname_z.as_bytes(),
)
.to_error_instance(global_this),
));
}
if err != 0 {
let code: &'static str = SystemErrno::init(err as i64)
.map(Into::into)
Expand Down
10 changes: 10 additions & 0 deletions src/uws_sys/udp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ bun_opaque::opaque_ffi! {
}

impl Socket {
/// Returns null on failure. `err` then receives the errno of the failing
/// socket call; if `host` itself did not resolve, `dns_error` receives the
/// raw getaddrinfo(3) return code instead (map it with
/// `c_ares::Error::init_eai`, never as an errno) and `err` stays 0.
pub fn create(
loop_: *mut Loop,
data_cb: extern "C" fn(*mut Socket, *mut PacketBuffer, c_int),
Expand All @@ -24,6 +28,7 @@ impl Socket {
port: c_ushort,
options: c_int,
err: Option<&mut c_int>,
dns_error: Option<&mut c_int>,
user_data: *mut c_void,
) -> *mut Socket {
// SAFETY: thin wrapper over us_create_udp_socket; all pointer args are
Expand All @@ -42,6 +47,10 @@ impl Socket {
Some(e) => std::ptr::from_mut::<c_int>(e),
None => core::ptr::null_mut(),
},
match dns_error {
Some(e) => std::ptr::from_mut::<c_int>(e),
None => core::ptr::null_mut(),
},
user_data,
)
}
Expand Down Expand Up @@ -209,6 +218,7 @@ unsafe extern "C" {
port: c_ushort,
options: c_int,
err: *mut c_int,
dns_error: *mut c_int,
user_data: *mut c_void,
) -> *mut Socket;
fn us_udp_socket_connect(socket: *mut Socket, hostname: *const c_char, port: c_uint) -> c_int;
Expand Down
51 changes: 51 additions & 0 deletions test/js/bun/udp/udp_socket.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,57 @@ describe("udpSocket()", () => {
).toThrow();
});

describe("bind failure errors", () => {
async function bindError(options: Parameters<typeof udpSocket>[0]): Promise<any> {
let socket;
try {
socket = await udpSocket(options);
} catch (error) {
return error;
}
socket.close();
throw new Error("expected udpSocket() to fail");
}

function pick({ name, code, syscall, hostname, address, message }: any) {
return { name, code, syscall, hostname, address, message };
}

// A DNS label longer than 63 bytes is illegal (RFC 1035 section 2.3.4), so
// getaddrinfo rejects it locally without a network round-trip.
const UNRESOLVABLE_HOST = Buffer.alloc(64, "a").toString() + ".com";

test("unresolvable hostname reports the resolver error, not an errno", async () => {
// The getaddrinfo return code used to be handed back through the errno
// channel, so this surfaced as whichever errno happened to share the
// number: `bind ENOENT <host>` on glibc, `bind ENOEXEC <host>` on macOS.
expect(pick(await bindError({ hostname: UNRESOLVABLE_HOST, port: 0 }))).toEqual({
name: "Error",
code: "ENOTFOUND",
syscall: "getaddrinfo",
hostname: UNRESOLVABLE_HOST,
address: undefined,
message: `getaddrinfo ENOTFOUND ${UNRESOLVABLE_HOST}`,
});
});

test("a failing bind() still reports the errno with the address", async () => {
const holder = await udpSocket({ hostname: "127.0.0.1", port: 0 });
try {
expect(pick(await bindError({ hostname: "127.0.0.1", port: holder.port }))).toEqual({
name: "Error",
code: "EADDRINUSE",
syscall: "bind",
hostname: undefined,
address: "127.0.0.1",
message: "bind EADDRINUSE 127.0.0.1",
});
} finally {
holder.close();
}
});
});

// Out-of-range connect.port used to be silently rewritten to 0, so send()
// returned true while every datagram was dropped. The bind path already
// rejected the same values; connect must too. Values beyond the i32 range
Expand Down
Loading