Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
29 changes: 25 additions & 4 deletions src/runtime/dns_jsc/dns.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2398,6 +2398,19 @@ pub mod internal {
hints_copy
}

/// "localhost" or a name under it (RFC 6761 §6.3), the same set `normalize_dns_name`
/// special-cases for `dns.lookup`.
Comment thread
robobun marked this conversation as resolved.
Resolved
#[cfg(not(windows))]
fn is_localhost_name(host: &[u8]) -> bool {
const LOCALHOST: &[u8] = b"localhost";
let Some(prefix_len) = host.len().checked_sub(LOCALHOST.len()) else {
return false;
};
let (prefix, label) = host.split_at(prefix_len);
strings::eql_case_insensitive_ascii(label, LOCALHOST, true)
&& (prefix.is_empty() || prefix.ends_with(b"."))
}
Comment thread
robobun marked this conversation as resolved.
Resolved

// `Request` is passed opaquely to usockets and round-tripped back into
// Rust; the C side never dereferences fields, so layout is irrelevant.
#[allow(improper_ctypes)]
Expand Down Expand Up @@ -2653,11 +2666,19 @@ pub mod internal {
unsafe {
let mut addrinfo: *mut AddrInfo = ptr::null_mut();
let mut hints = get_hints();
let host = (*req).key.host.as_ref();

// glibc's AI_ADDRCONFIG only counts non-loopback interface addresses, so on
// a machine whose only IPv6 address is ::1 (a container, typically) it drops
// the `::1 localhost` line of /etc/hosts even though ::1 is up, while a
// listener bound to the name (bsd_create_listen_socket prefers that line)
// sits exactly there. Loopback names get the unfiltered answer, which is
// what macOS libinfo and musl already return for them.
if host.is_some_and(|h| is_localhost_name(h.as_bytes())) {
hints.ai_flags &= !netc::AI_ADDRCONFIG;
}

let host_ptr = (*req)
.key
.host
.as_ref()
let host_ptr = host
.map(|h| h.as_ptr().cast::<c_char>())
.unwrap_or(ptr::null());
let mut err = libc::getaddrinfo(host_ptr, service, &raw const hints, &raw mut addrinfo);
Expand Down
64 changes: 64 additions & 0 deletions test/js/bun/dns/dns-prefetch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,70 @@
});
});

// A listener given a hostname binds one of the name's addresses (the `::1
// localhost` line of /etc/hosts when there is one), so a connect to the same name
// has to try every address the name has. The connect side resolves through the
// internal DNS cache, which used to pass AI_ADDRCONFIG for every name; glibc's
// AI_ADDRCONFIG ignores loopback when deciding which families are configured, so
// on a machine whose only IPv6 address is ::1 (a container) "localhost" resolved
// to 127.0.0.1 alone and the listener on ::1 was unreachable by name.
describe.concurrent("connecting to the hostname a listener was bound to", () => {
test("fetch()", async () => {
await using server = Bun.serve({ port: 0, hostname: "localhost", fetch: () => new Response("ok") });
const response = await fetch(`http://localhost:${server.port}/`);
expect(await response.text()).toBe("ok");
});

// getaddrinfo() is case-insensitive, so the exemption has to be too.
test.each(["localhost", "LOCALHOST"])("Bun.connect({ hostname: %j })", async hostname => {
using listener = Bun.listen({
port: 0,
hostname: "localhost",
socket: {
open(socket) {
socket.end("hello");
},
data() {},
},
});
const { promise, resolve } = Promise.withResolvers<string>();
using socket = await Bun.connect({
hostname,
port: listener.port,
socket: {
data(_socket, data) {
resolve(data.toString());
},
},
});

Check warning on line 78 in test/js/bun/dns/dns-prefetch.test.ts

View check run for this annotation

Claude / Claude Code Review

Bun.connect test does not wire error/close to reject the awaited promise

The client socket only defines a `data` handler and `Promise.withResolvers` only destructures `resolve`, so if the socket opens but then errors or closes before data arrives, `await promise` never settles and the test hangs to the harness timeout. Destructure `reject` and add `error`/`close` handlers on the client — the sibling `new WebSocket()` test just below already does this (`ws.onclose = event => reject(...)`).
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
expect(await promise).toBe("hello");
expect(socket.remoteAddress).toBeOneOf(["127.0.0.1", "::1"]);
});

test("new WebSocket()", async () => {
await using server = Bun.serve({
port: 0,
hostname: "localhost",
fetch(request, server) {
return server.upgrade(request) ? undefined : new Response(null, { status: 400 });
},
websocket: {
open(ws) {
ws.send("hello");
},
message() {},
},
});
const { promise, resolve, reject } = Promise.withResolvers<string>();
const ws = new WebSocket(`ws://localhost:${server.port}/`);
ws.onmessage = event => resolve(String(event.data));
ws.onclose = event => reject(new Error(`closed before any message: ${event.code} ${event.reason}`));
expect(await promise).toBe("hello");
ws.onclose = null;
ws.close();
});
});

describe("dns.prefetch", () => {
it("should prefetch", async () => {
// A local server keeps the test off the external network. "localhost" is a
Expand Down