From 8cf3e01c753da2b7286b6937acda6e822b1aac20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christian=20Rish=C3=B8j?= Date: Thu, 2 Jul 2026 22:56:40 +0200 Subject: [PATCH] dns: fix RFC 8305 family interleaving of getaddrinfo results (#33278) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit process_results() has always had an "interleave ipv4 and ipv6" pass, but it was a faithful port of a broken Zig loop (`for ... else` fired unconditionally), so any resolver result starting with the preferred family — e.g. 4 AAAA records before any A — came out untouched. All 4 concurrent connect attempts then went to the same dead family, and a cold fetch on a network with advertised-but-unroutable IPv6 stalled for the full ~70 s OS connect timeout. Replace it with a stable interleave applied while packing the entries: alternate between the first entry's family and the rest, preserving resolver order within each family. The old post-hoc swap block is deleted; ordering now happens in the copy loop via a closed-form slot mapping (a bijection, so the MaybeUninit init invariant is unchanged). Expose the packing through bun:internal-for-testing to make the ordering testable; three of the new cases fail against the old algorithm. Co-Authored-By: Claude Fable 5 --- src/js/internal-for-testing.ts | 11 +++ src/runtime/dns_jsc/dns.rs | 142 ++++++++++++++++++++++----- src/runtime/dns_jsc/mod.rs | 7 ++ test/js/bun/dns/dns-prefetch.test.ts | 26 +++++ 4 files changed, 159 insertions(+), 27 deletions(-) diff --git a/src/js/internal-for-testing.ts b/src/js/internal-for-testing.ts index e0d3d9252a85..42f40385de95 100644 --- a/src/js/internal-for-testing.ts +++ b/src/js/internal-for-testing.ts @@ -405,6 +405,17 @@ export const stringsInternals = { ) => string, }; +export const dnsInternals = { + /** + * Feeds a synthetic getaddrinfo result with the given address families + * (4 | 6) through the connect path's result packing and returns + * `family * 1000 + originalIndex` in the order connections are attempted. + */ + getaddrinfoInterleave: $newRustFunction("runtime/dns_jsc/dns.rs", "TestingAPIs.getaddrinfoInterleave", 1) as ( + families: number[], + ) => number[], +}; + export const fetchH2Internals = { liveCounts: $newRustFunction("http/H2Client.rs", "TestingAPIs.liveCounts", 0) as () => { sessions: number; diff --git a/src/runtime/dns_jsc/dns.rs b/src/runtime/dns_jsc/dns.rs index bc593dc53905..d3044a22f094 100644 --- a/src/runtime/dns_jsc/dns.rs +++ b/src/runtime/dns_jsc/dns.rs @@ -2612,24 +2612,51 @@ pub mod internal { } // re-order result to interleave ipv4 and ipv6 (also pack into a single allocation) - fn process_results(info: *mut AddrInfo) -> Box<[ResultEntry]> { + pub(crate) fn process_results(info: *mut AddrInfo) -> Box<[ResultEntry]> { let mut count: usize = 0; + let mut n_first: usize = 0; + let first_family = if info.is_null() { + netc::AF_UNSPEC + } else { + // SAFETY: info is a live addrinfo node; freed by caller after we return. + unsafe { (*info).ai_family } + }; let mut info_: *mut AddrInfo = info; while !info_.is_null() { count += 1; // SAFETY: info_ walks the libc-allocated addrinfo list; freed by caller after we return. - info_ = unsafe { (*info_).ai_next }; + unsafe { + if (*info_).ai_family == first_family { + n_first += 1; + } + info_ = (*info_).ai_next; + } } + let n_other = count - n_first; let mut results: Box<[MaybeUninit]> = Box::new_uninit_slice(count); - // copy results - let mut i: usize = 0; + // Copy results, interleaving address families (RFC 8305 §4): alternate + // between the first entry's family and the rest, preserving resolver order + // within each family, so a run of unroutable same-family addresses cannot + // occupy every concurrent connection attempt (#33278). + let mut i_first: usize = 0; + let mut i_other: usize = 0; info_ = info; while !info_.is_null() { - // SAFETY: info_ is a valid addrinfo node (counted above); results[i] is a - // MaybeUninit slot we fully initialize in this iteration. + // SAFETY: info_ is a valid addrinfo node (counted above); the slot + // mapping is a bijection over 0..count, so every results[i] is a + // MaybeUninit slot fully initialized exactly once. unsafe { + let i = if (*info_).ai_family == first_family { + let i = i_first; + i_first += 1; + if i < n_other { 2 * i } else { n_other + i } + } else { + let j = i_other; + i_other += 1; + if j < n_first { 2 * j + 1 } else { n_first + j } + }; let entry = results[i].as_mut_ptr(); (*entry).info = *info_; // Always initialize `addr`: assume_init() below requires every byte written. @@ -2646,7 +2673,6 @@ pub mod internal { } else { (*entry).addr = bun_core::ffi::zeroed(); } - i += 1; info_ = (*info_).ai_next; } } @@ -2654,26 +2680,6 @@ pub mod internal { // SAFETY: every slot 0..count was written above let mut results: Box<[ResultEntry]> = unsafe { results.assume_init() }; - // sort (interleave ipv4 and ipv6) - let mut want = netc::AF_INET6 as usize; - 'outer: for idx in 0..count { - if results[idx].info.ai_family as usize == want { - continue; - } - for j in (idx + 1)..count { - if results[j].info.ai_family as usize == want { - results.swap(idx, j); - want = if want == netc::AF_INET6 as usize { - netc::AF_INET as usize - } else { - netc::AF_INET6 as usize - }; - } - } - // the rest of the list is all one address family - break 'outer; - } - // set up pointers for idx in 0..count { let (left, right) = results.split_at_mut(idx + 1); @@ -3311,6 +3317,88 @@ pub mod internal { pub use internal::Request as InternalDNSRequest; +/// `bun:internal-for-testing` bridge — see `src/js/internal-for-testing.ts`. +pub mod testing_apis { + use super::*; + + /// Probe for `internal::process_results`: builds a synthetic getaddrinfo + /// chain from an array of address families (4 | 6) and returns + /// `family * 1000 + originalIndex` in the packed/interleaved result order. + #[bun_jsc::host_fn] + pub fn getaddrinfo_interleave(global: &JSGlobalObject, frame: &CallFrame) -> JsResult { + let families = frame.argument(0); + let len = families.get_length(global)? as usize; + + let mut addrs: Vec = (0..len).map(|_| bun_core::ffi::zeroed()).collect(); + let mut nodes: Vec = (0..len).map(|_| bun_core::ffi::zeroed()).collect(); + for i in 0..len { + let family = families.get_index(global, i as u32)?.to_int32(); + let node = &mut nodes[i]; + // Stash the original index in the port so the caller can verify + // that resolver order is preserved within each family. + match family { + 4 => { + // SAFETY: sockaddr_in fits in the zeroed sockaddr_storage. + let sa = unsafe { &mut *(&raw mut addrs[i]).cast::() }; + sa.sin_family = netc::AF_INET as _; + sa.sin_port = i as u16; + node.ai_family = netc::AF_INET; + node.ai_addrlen = size_of::() as _; + } + 6 => { + // SAFETY: sockaddr_in6 fits in the zeroed sockaddr_storage. + let sa = unsafe { &mut *(&raw mut addrs[i]).cast::() }; + sa.sin6_family = netc::AF_INET6 as _; + sa.sin6_port = i as u16; + node.ai_family = netc::AF_INET6; + node.ai_addrlen = size_of::() as _; + } + other => { + return Err(global.throw(format_args!("family must be 4 or 6, got {other}"))); + } + } + node.ai_addr = (&raw mut addrs[i]).cast::(); + } + let base = nodes.as_mut_ptr(); + for i in 0..len.saturating_sub(1) { + // SAFETY: i and i + 1 are in-bounds; the Vec is never reallocated. + unsafe { (*base.add(i)).ai_next = base.add(i + 1) }; + } + + let results = internal::process_results(if len == 0 { + ptr::null_mut() + } else { + nodes.as_mut_ptr() + }); + + // Walk the rebuilt ai_next chain (not the slice) so the intrusive + // pointer fixup is exercised too. + let out = JSValue::create_empty_array(global, results.len())?; + let mut p: *const AddrInfo = if results.is_empty() { + ptr::null() + } else { + &raw const results[0].info + }; + let mut idx: u32 = 0; + while !p.is_null() { + // SAFETY: p walks the chain inside the live `results` allocation. + let encoded = unsafe { + if (*p).ai_family == netc::AF_INET { + 4000 + i32::from((*(*p).ai_addr.cast::()).sin_port) + } else { + 6000 + i32::from((*(*p).ai_addr.cast::()).sin6_port) + } + }; + out.put_index(global, idx, JSValue::js_number_from_int32(encoded))?; + idx += 1; + // SAFETY: same as above. + p = unsafe { (*p).ai_next }; + } + Ok(out) + } +} +pub use testing_apis as testing_ap_is; + // ────────────────────────────────────────────────────────────────────────── // Resolver — JSC-exposed `dns.Resolver` (m_ctx payload of JSDNSResolver) // ────────────────────────────────────────────────────────────────────────── diff --git a/src/runtime/dns_jsc/mod.rs b/src/runtime/dns_jsc/mod.rs index a843cb49fbb5..274217ef127c 100644 --- a/src/runtime/dns_jsc/mod.rs +++ b/src/runtime/dns_jsc/mod.rs @@ -12,6 +12,13 @@ mod dns_body; pub(crate) use dns_body::netc; +/// Codegen path alias: `generated_js2native.rs` lowers +/// `$rust(runtime/dns_jsc/dns.rs, TestingAPIs.*)` to +/// `crate::dns_jsc::dns::testing_ap_is::*` (cf. `crate::socket::socket`). +pub mod dns { + pub use super::dns_body::testing_ap_is; +} + #[path = "cares_jsc.rs"] pub mod cares_jsc; // c-ares reply struct → JSValue bridges diff --git a/test/js/bun/dns/dns-prefetch.test.ts b/test/js/bun/dns/dns-prefetch.test.ts index d7359eca9e85..4df00c47e115 100644 --- a/test/js/bun/dns/dns-prefetch.test.ts +++ b/test/js/bun/dns/dns-prefetch.test.ts @@ -1,5 +1,6 @@ import { dns } from "bun"; import { describe, expect, it, test } from "bun:test"; +import { dnsInternals } from "bun:internal-for-testing"; import { bunEnv, bunExe } from "harness"; // The DNS cache is process-global, so this runs in its own process to get @@ -72,3 +73,28 @@ describe("dns.prefetch", () => { expect(newStats2.cacheHitsCompleted).toBeGreaterThan(currentStats.cacheHitsCompleted); }); }); + +// https://github.com/oven-sh/bun/issues/33278 +describe("getaddrinfo result interleaving (RFC 8305)", () => { + // Entries are encoded as family * 1000 + original resolver index. + test.each([ + // 4 AAAA before any A (the aiplatform.googleapis.com shape from the + // issue): an IPv4 address must reach the first batch of 4 attempts. + { + families: [6, 6, 6, 6, 4, 4, 4, 4], + expected: [6000, 4004, 6001, 4005, 6002, 4006, 6003, 4007], + }, + // The resolver's preferred family stays first (RFC 6724 order is policy). + { families: [4, 4, 6, 6], expected: [4000, 6002, 4001, 6003] }, + // Uneven counts: the surplus family keeps resolver order at the tail. + { families: [6, 6, 6, 6, 4, 4], expected: [6000, 4004, 6001, 4005, 6002, 6003] }, + { families: [6, 4, 4, 4], expected: [6000, 4001, 4002, 4003] }, + // Single-family and already-interleaved lists are untouched. + { families: [6, 6, 6], expected: [6000, 6001, 6002] }, + { families: [4], expected: [4000] }, + { families: [6, 4, 6, 4], expected: [6000, 4001, 6002, 4003] }, + { families: [], expected: [] }, + ])("$families → $expected", ({ families, expected }) => { + expect(dnsInternals.getaddrinfoInterleave(families)).toEqual(expected); + }); +});