Skip to content

Truly independent web browser

LibDNS: Wait for IPv4 addresses when IPv6 addresses resolve first

Andreas Klingf6454c4ffd27
diff --git a/Libraries/LibCore/Socket.cpp b/Libraries/LibCore/Socket.cpp
index 3c244a3f55e..2e4df5a825f 100644
--- a/Libraries/LibCore/Socket.cpp
+++ b/Libraries/LibCore/Socket.cpp
@@ -5,7 +5,9 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <AK/ScopeGuard.h>
#include <LibCore/Socket.h>
+#include <LibCore/SocketAddress.h>
#include <LibCore/System.h>
namespace Core {
@@ -108,6 +110,36 @@ ErrorOr<Vector<Variant<IPv4Address, IPv6Address>>> Socket::resolve_host(ByteStri
return addresses;
}
+// Connecting a datagram socket sends nothing, but has the system choose the local address it would send from.
+bool Socket::is_ipv6_globally_reachable()
+{
+ auto fd_or_error = create_fd(SocketDomain::Inet6, SocketType::Datagram);
+ if (fd_or_error.is_error())
+ return false;
+ auto fd = fd_or_error.release_value();
+ ScopeGuard close_fd = [fd] { (void)System::close(fd); };
+
+ // 2001:4860:4860::8888, a public DNS server.
+ static constexpr Array<u16, 8> probe_address { 0x2001, 0x4860, 0x4860, 0, 0, 0, 0, 0x8888 };
+ auto destination = SocketAddress { IPv6Address { probe_address }, 443 }.to_sockaddr_in6();
+ if (System::connect(fd, bit_cast<struct sockaddr const*>(&destination), sizeof(destination)).is_error())
+ return false;
+
+ struct sockaddr_in6 local_socket_address {};
+ socklen_t local_socket_address_size = sizeof(local_socket_address);
+ if (System::getsockname(fd, bit_cast<struct sockaddr*>(&local_socket_address), &local_socket_address_size).is_error())
+ return false;
+ IPv6Address local_address { local_socket_address.sin6_addr.s6_addr };
+
+ // A link-local address (fe80::/10) reaches no further than the link, and a Teredo address (2001::/32) tunnels
+ // IPv6 over IPv4 too unreliably to prefer it.
+ if ((local_address[0] & 0xffc0) == 0xfe80)
+ return false;
+ if (local_address[0] == 0x2001 && local_address[1] == 0)
+ return false;
+ return true;
+}
+
ErrorOr<void> Socket::connect_local(int fd, ByteString const& path)
{
auto address = SocketAddress::local(path);
diff --git a/Libraries/LibCore/Socket.h b/Libraries/LibCore/Socket.h
index c73a4204239..7e4f4a38477 100644
--- a/Libraries/LibCore/Socket.h
+++ b/Libraries/LibCore/Socket.h
@@ -71,6 +71,9 @@ public:
// base class for all address types is appropriate.
static ErrorOr<Vector<Variant<IPv4Address, IPv6Address>>> resolve_host(ByteString const&, SocketType, AddressFamily = AddressFamily::Unspecified);
+ // Whether this host has a route to the IPv6 internet, from an address that can reach it.
+ static bool is_ipv6_globally_reachable();
+
Function<void()> on_ready_to_read;
protected:
diff --git a/Libraries/LibCore/SocketWindows.cpp b/Libraries/LibCore/SocketWindows.cpp
index 31181bccc5f..4e555fb82db 100644
--- a/Libraries/LibCore/SocketWindows.cpp
+++ b/Libraries/LibCore/SocketWindows.cpp
@@ -7,7 +7,9 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <AK/ScopeGuard.h>
#include <LibCore/Socket.h>
+#include <LibCore/SocketAddress.h>
#include <LibCore/System.h>
#include <AK/Windows.h>
@@ -286,6 +288,36 @@ ErrorOr<Vector<Variant<IPv4Address, IPv6Address>>> Socket::resolve_host(ByteStri
return addresses;
}
+// Connecting a datagram socket sends nothing, but has the system choose the local address it would send from.
+bool Socket::is_ipv6_globally_reachable()
+{
+ auto fd_or_error = create_fd(SocketDomain::Inet6, SocketType::Datagram);
+ if (fd_or_error.is_error())
+ return false;
+ auto fd = fd_or_error.release_value();
+ ScopeGuard close_fd = [fd] { (void)System::close(fd); };
+
+ // 2001:4860:4860::8888, a public DNS server.
+ static constexpr Array<u16, 8> probe_address { 0x2001, 0x4860, 0x4860, 0, 0, 0, 0, 0x8888 };
+ auto destination = SocketAddress { IPv6Address { probe_address }, 443 }.to_sockaddr_in6();
+ if (System::connect(fd, bit_cast<struct sockaddr const*>(&destination), sizeof(destination)).is_error())
+ return false;
+
+ struct sockaddr_in6 local_socket_address {};
+ socklen_t local_socket_address_size = sizeof(local_socket_address);
+ if (System::getsockname(fd, bit_cast<struct sockaddr*>(&local_socket_address), &local_socket_address_size).is_error())
+ return false;
+ IPv6Address local_address { local_socket_address.sin6_addr.s6_addr };
+
+ // A link-local address (fe80::/10) reaches no further than the link, and a Teredo address (2001::/32) tunnels
+ // IPv6 over IPv4 too unreliably to prefer it.
+ if ((local_address[0] & 0xffc0) == 0xfe80)
+ return false;
+ if (local_address[0] == 0x2001 && local_address[1] == 0)
+ return false;
+ return true;
+}
+
ErrorOr<void> Socket::connect_inet(int fd, SocketAddress const& address)
{
if (address.type() == SocketAddress::Type::IPv6) {
diff --git a/Libraries/LibDNS/Resolver.h b/Libraries/LibDNS/Resolver.h
index 54bdf6f4937..846438f25eb 100644
--- a/Libraries/LibDNS/Resolver.h
+++ b/Libraries/LibDNS/Resolver.h
@@ -11,6 +11,7 @@
#include <AK/HashTable.h>
#include <AK/MaybeOwned.h>
#include <AK/MemoryStream.h>
+#include <AK/QuickSort.h>
#include <AK/RWLockProtected.h>
#include <AK/Random.h>
#include <AK/StringView.h>
@@ -199,10 +200,18 @@ public:
using ResultPromise = Core::Promise<NonnullRefPtr<LookupResult const>>;
using MessagePromise = Core::Promise<Messages::Message>;
+ // Stand-ins for the system resolver and the network it reaches, for tests. Each one left empty is the real one.
+ struct SystemResolverForTesting {
+ // Resolves a name to the addresses of one family. It runs on a thread pool worker.
+ Function<ErrorOr<Vector<Variant<IPv4Address, IPv6Address>>>(ByteString const&, Core::Socket::AddressFamily)> resolve_host;
+ Function<bool()> is_ipv6_globally_reachable;
+ };
+
// An empty result means no server is configured and the system resolver should be used instead.
- Resolver(Function<ErrorOr<Optional<SocketResult>>()> create_socket)
+ Resolver(Function<ErrorOr<Optional<SocketResult>>()> create_socket, SystemResolverForTesting system_resolver_for_testing = {})
: m_receive_buffer(MUST(ByteBuffer::create_uninitialized(NumericLimits<u16>::max())))
, m_create_socket(move(create_socket))
+ , m_system_resolver_for_testing(move(system_resolver_for_testing))
, m_validator([this](Messages::DomainName const& name, Messages::ResourceType type) {
return query(name, type, Messages::Class::IN, true);
})
@@ -412,8 +421,23 @@ public:
// 224.0.0.251 (or its IPv6 equivalent FF02::FB).
// The system resolver takes care of that, so these never go to the configured server.
auto is_link_local_name = is_within_domain(name, "local"sv);
-
- if (auto result = lookup_in_cache(name, class_, desired_types)) {
+ auto uses_system_resolver = is_link_local_name || !has_connection();
+
+ // NB: IPv6 addresses are no use to a host that cannot reach the IPv6 internet, so the system resolver skips
+ // the AAAA side there. Link-local IPv6 addresses work without that, so ".local" names keep the AAAA side,
+ // as they do in Firefox, WebKitGTK (glibc's AI_ADDRCONFIG counts link-local addresses) and on Apple
+ // platforms (mDNSResponder never suppresses multicast queries). Like Chromium's host cache, which keys a
+ // lookup without AAAA apart from one with it, a cached result without AAAA only serves while IPv6 stays
+ // unreachable.
+ auto skips_aaaa = uses_system_resolver && !is_link_local_name
+ && desired_types.contains_slow(Messages::ResourceType::A)
+ && desired_types.contains_slow(Messages::ResourceType::AAAA)
+ && !is_ipv6_globally_reachable();
+ auto queried_types = desired_types;
+ if (skips_aaaa)
+ queried_types.remove_first_matching([](auto type) { return type == Messages::ResourceType::AAAA; });
+
+ if (auto result = lookup_in_cache(name, class_, queried_types)) {
dbgln_if(DNS_DEBUG, "DNS: Resolving {} from cache...", name);
if (!options.validate_dnssec_locally || result->was_dnssec_validated()) {
dbgln_if(DNS_DEBUG, "DNS: Resolved {} from cache", name);
@@ -424,7 +448,7 @@ public:
dbgln_if(DNS_DEBUG, "DNS: Cache entry for {} is not DNSSEC validated (and we expect that), re-resolving", name);
}
- if (is_link_local_name || !has_connection()) {
+ if (uses_system_resolver) {
if (!is_link_local_name && !m_use_system_resolver) {
promise->reject(Error::from_string_literal("No connection to the configured DNS server"));
lookup_path = "no-conn-rejected"sv;
@@ -441,11 +465,21 @@ public:
// PendingSystemResolution for why we split into two parallel workers.
dbgln_if(DNS_DEBUG, "Not ready to resolve, dispatching system resolver to ThreadPool for {}", name);
+ // NB: A resolution only serves callers that query the same types, so that a caller wanting AAAA never
+ // joins one that skips it, and one that skips AAAA never joins one that went ahead without A.
+ auto sorted_queried_types = queried_types;
+ quick_sort(sorted_queried_types, [](auto a, auto b) { return to_underlying(a) < to_underlying(b); });
+ StringBuilder pending_key_builder;
+ pending_key_builder.append(name);
+ for (auto type : sorted_queried_types)
+ pending_key_builder.appendff("|{}", to_underlying(type));
+ auto pending_key = pending_key_builder.to_byte_string();
+
RefPtr<PendingSystemResolution> our_state;
RefPtr<LookupResult> already_finalized_result;
m_pending_system_resolutions.with_write_locked(
[&](auto& pending) {
- if (auto it = pending.find(name); it != pending.end()) {
+ if (auto it = pending.find(pending_key); it != pending.end()) {
auto& existing = *it->value;
// Grace timer may have already finalized the resolution while AAAA is still in
// flight; serve the join-pending caller from the existing result. We resolve the
@@ -459,11 +493,11 @@ public:
return;
}
auto result = make_ref_counted<LookupResult>(domain_name);
- for (auto const& type : desired_types)
+ for (auto const& type : queried_types)
result->will_add_record_of_type(type);
auto state = adopt_ref(*new PendingSystemResolution(result));
state->waiting_promises.append(promise);
- pending.set(name, state);
+ pending.set(pending_key, state);
our_state = state;
});
@@ -487,10 +521,12 @@ public:
auto submit_worker = [&, this](Core::Socket::AddressFamily family) {
Threading::ThreadPool::the().submit(
- [this, name, state = our_state, family,
+ [this, name, pending_key, state = our_state, family,
&main_thread_event_loop]() mutable {
auto worker_started_at = MonotonicTime::now();
- auto record_or_error = Core::Socket::resolve_host(name, Core::Socket::SocketType::Stream, family);
+ auto record_or_error = m_system_resolver_for_testing.resolve_host
+ ? m_system_resolver_for_testing.resolve_host(name, family)
+ : Core::Socket::resolve_host(name, Core::Socket::SocketType::Stream, family);
auto worker_finished_at = MonotonicTime::now();
PendingSystemResolution::SideTiming timing {
.queue_ms = (worker_started_at - state->dispatched_at).to_milliseconds(),
@@ -498,16 +534,20 @@ public:
};
main_thread_event_loop.deferred_invoke(
- [this, name, state, family,
+ [this, name, pending_key, state, family,
record_or_error = move(record_or_error),
timing]() mutable {
- handle_system_resolver_completion(name, *state, family, move(record_or_error), timing);
+ handle_system_resolver_completion(name, pending_key, *state, family, move(record_or_error), timing);
});
});
};
+ if (skips_aaaa)
+ our_state->aaaa = PendingSystemResolution::SideTiming {};
+
submit_worker(Core::Socket::AddressFamily::IPv4Only);
- submit_worker(Core::Socket::AddressFamily::IPv6Only);
+ if (!skips_aaaa)
+ submit_worker(Core::Socket::AddressFamily::IPv6Only);
return promise;
}
@@ -813,15 +853,34 @@ private:
return result;
}
+ // Whether the host can reach the IPv6 internet, checked again at most once a second.
+ bool is_ipv6_globally_reachable()
+ {
+ static constexpr auto IPV6_REACHABILITY_CHECK_INTERVAL = AK::Duration::from_seconds(1);
+ auto now = MonotonicTime::now();
+ if (!m_ipv6_reachability_checked_at.has_value() || now - *m_ipv6_reachability_checked_at >= IPV6_REACHABILITY_CHECK_INTERVAL) {
+ m_ipv6_is_globally_reachable = m_system_resolver_for_testing.is_ipv6_globally_reachable
+ ? m_system_resolver_for_testing.is_ipv6_globally_reachable()
+ : Core::Socket::is_ipv6_globally_reachable();
+ m_ipv6_reachability_checked_at = now;
+ }
+ return m_ipv6_is_globally_reachable;
+ }
+
// Per-name state for an in-flight system-resolver lookup. We split the
// single AF_UNSPEC `getaddrinfo` call into two parallel calls (AF_INET +
// AF_INET6) so that buggy stub resolvers (notably systemd-resolved under
- // load) can't drop the AAAA half of a coupled query and stall us on it.
- // The promise resolves as soon as one side returns records, with a small
- // 50 ms grace window for the other side (Happy Eyeballs v2's Resolution
- // Delay, RFC 8305) so curl can prefer IPv6 when both are available. The
- // slower side keeps running and merges its records into the cached
- // LookupResult so subsequent lookups see the full set.
+ // load) can't drop one half of a coupled query and stall us on it. The
+ // AAAA half is only made for ".local" names or when the host can reach the
+ // IPv6 internet.
+ // When the A side returns records first, the promise resolves after a small
+ // 50 ms grace window for the AAAA side (Happy Eyeballs v2's Resolution
+ // Delay, RFC 8305) so curl can prefer IPv6 when both are available. When
+ // the AAAA side returns first, the A side gets a longer 1 s window: curl
+ // only connects to the addresses it is given, so IPv4 records that come
+ // later never reach a request that went ahead with IPv6 alone. The slower
+ // side keeps running and merges its records into the cached LookupResult
+ // so subsequent lookups see the full set.
//
// `waiting_promises` holds one Promise per `lookup()` caller that joined
// this resolution. Each caller MUST get their own Promise — Core::Promise
@@ -875,6 +934,7 @@ private:
// Runs on the main thread (deferred-invoked from a ThreadPool worker).
void handle_system_resolver_completion(
ByteString const& name,
+ ByteString const& pending_key,
PendingSystemResolution& state,
Core::Socket::AddressFamily family,
ErrorOr<Vector<Variant<IPv4Address, IPv6Address>>> record_or_error,
@@ -909,7 +969,7 @@ private:
cache.set(name, state.result);
});
m_pending_system_resolutions.with_write_locked([&](auto& pending) {
- pending.remove(name);
+ pending.remove(pending_key);
});
auto total_ms = (MonotonicTime::now() - state.dispatched_at).to_milliseconds();
@@ -930,13 +990,16 @@ private:
if (!got_records_this_side)
return;
- // First side has records. Wait briefly so the other side gets a chance to add its records too
- // (RFC 8305 Resolution Delay, 50 ms).
+ // First side has records. Wait so the other side gets a chance to add its records too: briefly for the AAAA
+ // side (RFC 8305 Resolution Delay, 50 ms), and longer for the A side, since curl never learns of IPv4 records
+ // that come after it went ahead with IPv6 records that turn out to be unreachable.
if (state.grace_timer)
return;
- constexpr int RESOLUTION_DELAY_MS = 50;
+ constexpr int IPV6_RESOLUTION_DELAY_MS = 50;
+ constexpr int IPV4_RESOLUTION_DELAY_MS = 1000;
+ auto resolution_delay_ms = family == Core::Socket::AddressFamily::IPv4Only ? IPV6_RESOLUTION_DELAY_MS : IPV4_RESOLUTION_DELAY_MS;
auto weak_state = state.make_weak_ptr();
- state.grace_timer = Core::Timer::create_single_shot(AK::Duration::from_milliseconds(RESOLUTION_DELAY_MS), [weak_state] {
+ state.grace_timer = Core::Timer::create_single_shot(AK::Duration::from_milliseconds(resolution_delay_ms), [weak_state] {
if (auto state = weak_state.strong_ref())
try_finalize_pending_system_resolution(*state);
});
@@ -1179,6 +1242,9 @@ private:
Function<ErrorOr<Optional<SocketResult>>()> m_create_socket;
bool m_attempting_restart { false };
bool m_use_system_resolver { false };
+ SystemResolverForTesting m_system_resolver_for_testing;
+ Optional<MonotonicTime> m_ipv6_reachability_checked_at;
+ bool m_ipv6_is_globally_reachable { false };
Vector<ByteString> m_loopback_domains;
ConnectionMode m_mode { ConnectionMode::UDP };
Vector<NonnullRefPtr<Core::Promise<Empty>>> m_socket_ready_promises;
diff --git a/Tests/LibDNS/TestDNSResolver.cpp b/Tests/LibDNS/TestDNSResolver.cpp
index 5648e280a08..f7fbeb4b065 100644
--- a/Tests/LibDNS/TestDNSResolver.cpp
+++ b/Tests/LibDNS/TestDNSResolver.cpp
@@ -4,7 +4,10 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <AK/AnyOf.h>
+#include <AK/Atomic.h>
#include <AK/ByteBuffer.h>
+#include <AK/ConditionVariable.h>
#include <AK/Endian.h>
#include <AK/IPv4Address.h>
#include <AK/IPv6Address.h>
@@ -898,3 +901,239 @@ TEST_CASE(test_expired_addresses_are_not_mistaken_for_a_negative_answer)
EXPECT_EQ(second->cached_addresses().size(), 1u);
EXPECT(queries > queries_for_first_lookup);
}
+
+namespace {
+
+// A system resolver that answers for IPv6 right away, and for IPv4 only once the test lets it.
+class SystemResolverWithHeldBackIPv4 {
+public:
+ DNS::Resolver::SystemResolverForTesting system_resolver(bool is_ipv6_globally_reachable = true)
+ {
+ m_ipv6_is_globally_reachable.store(is_ipv6_globally_reachable);
+ return {
+ .resolve_host = [this](ByteString const&, Core::Socket::AddressFamily family) -> ErrorOr<Vector<Variant<IPv4Address, IPv6Address>>> {
+ if (family == Core::Socket::AddressFamily::IPv6Only) {
+ m_ipv6_answered.store(true);
+ return Vector<Variant<IPv4Address, IPv6Address>> { IPv6Address::loopback() };
+ }
+ MutexLocker locker { m_mutex };
+ m_condition.wait_while([&] { return !m_ipv4_may_answer; });
+ return Vector<Variant<IPv4Address, IPv6Address>> { IPv4Address { 192, 0, 2, 1 } };
+ },
+ .is_ipv6_globally_reachable = [this] { return m_ipv6_is_globally_reachable.load(); },
+ };
+ }
+
+ bool ipv6_answered() const { return m_ipv6_answered.load(); }
+ void set_ipv6_is_globally_reachable(bool reachable) { m_ipv6_is_globally_reachable.store(reachable); }
+
+ void let_ipv4_answer()
+ {
+ MutexLocker locker { m_mutex };
+ m_ipv4_may_answer = true;
+ m_condition.broadcast();
+ }
+
+private:
+ Mutex m_mutex;
+ ConditionVariable m_condition { m_mutex };
+ bool m_ipv4_may_answer { false };
+ Atomic<bool> m_ipv6_answered { false };
+ Atomic<bool> m_ipv6_is_globally_reachable { true };
+};
+
+bool has_address_of_family(DNS::LookupResult const& result, bool ipv6)
+{
+ return any_of(result.cached_addresses(), [ipv6](auto const& address) { return address.template has<IPv6Address>() == ipv6; });
+}
+
+}
+
+TEST_CASE(test_system_resolver_waits_for_ipv4_addresses_after_ipv6_addresses)
+{
+ Core::EventLoop loop;
+ SystemResolverWithHeldBackIPv4 system_resolver;
+ DNS::Resolver resolver {
+ [] -> ErrorOr<Optional<DNS::Resolver::SocketResult>> { return OptionalNone {}; },
+ system_resolver.system_resolver(),
+ };
+
+ auto promise = resolver.lookup("example.com"sv, DNS::Messages::Class::IN, { DNS::Messages::ResourceType::A, DNS::Messages::ResourceType::AAAA });
+ loop.spin_until([&] { return system_resolver.ipv6_answered(); });
+
+ // Well past the 50 ms that the AAAA side gets after the A side, and well short of the 1 s the A side gets.
+ auto timer = Core::Timer::create_single_shot(AK::Duration::from_milliseconds(200), [&] { loop.quit(0); });
+ timer->start();
+ loop.exec();
+
+ // IPv6 addresses alone are no use if they turn out to be unreachable, so the lookup waits for the IPv4 addresses.
+ EXPECT(!promise->is_resolved());
+ EXPECT(!promise->is_rejected());
+
+ system_resolver.let_ipv4_answer();
+ auto result = TRY_OR_FAIL(promise->await());
+ EXPECT_EQ(result->cached_addresses().size(), 2u);
+ EXPECT(has_address_of_family(*result, false));
+ EXPECT(has_address_of_family(*result, true));
+}
+
+TEST_CASE(test_system_resolver_goes_ahead_with_ipv6_addresses_when_ipv4_addresses_take_too_long)
+{
+ Core::EventLoop loop;
+ SystemResolverWithHeldBackIPv4 system_resolver;
+ DNS::Resolver resolver {
+ [] -> ErrorOr<Optional<DNS::Resolver::SocketResult>> { return OptionalNone {}; },
+ system_resolver.system_resolver(),
+ };
+
+ auto result = TRY_OR_FAIL(resolver.lookup("example.com"sv, DNS::Messages::Class::IN, { DNS::Messages::ResourceType::A, DNS::Messages::ResourceType::AAAA })->await());
+ EXPECT_EQ(result->cached_addresses().size(), 1u);
+ EXPECT(has_address_of_family(*result, true));
+
+ // The IPv4 addresses that come later are still cached for later lookups.
+ system_resolver.let_ipv4_answer();
+ loop.spin_until([&] { return resolver.lookup_in_cache("example.com"sv); });
+ EXPECT_EQ(resolver.expect_cached("example.com"sv)->cached_addresses().size(), 2u);
+}
+
+TEST_CASE(test_system_resolver_skips_ipv6_addresses_when_ipv6_is_unreachable)
+{
+ Core::EventLoop loop;
+ SystemResolverWithHeldBackIPv4 system_resolver;
+ DNS::Resolver resolver {
+ [] -> ErrorOr<Optional<DNS::Resolver::SocketResult>> { return OptionalNone {}; },
+ system_resolver.system_resolver(false),
+ };
+
+ system_resolver.let_ipv4_answer();
+ auto result = TRY_OR_FAIL(resolver.lookup("example.com"sv, DNS::Messages::Class::IN, { DNS::Messages::ResourceType::A, DNS::Messages::ResourceType::AAAA })->await());
+ EXPECT_EQ(result->cached_addresses().size(), 1u);
+ EXPECT(has_address_of_family(*result, false));
+ EXPECT(!system_resolver.ipv6_answered());
+}
+
+TEST_CASE(test_system_resolver_resolves_ipv6_addresses_of_local_names_when_ipv6_is_unreachable)
+{
+ Core::EventLoop loop;
+ SystemResolverWithHeldBackIPv4 system_resolver;
+ DNS::Resolver resolver {
+ [] -> ErrorOr<Optional<DNS::Resolver::SocketResult>> { return OptionalNone {}; },
+ system_resolver.system_resolver(false),
+ };
+
+ // Link-local IPv6 addresses work without a route to the IPv6 internet, so ".local" names keep the AAAA side.
+ system_resolver.let_ipv4_answer();
+ auto result = TRY_OR_FAIL(resolver.lookup("printer.local"sv, DNS::Messages::Class::IN, { DNS::Messages::ResourceType::A, DNS::Messages::ResourceType::AAAA })->await());
+ EXPECT(system_resolver.ipv6_answered());
+ EXPECT(has_address_of_family(*result, true));
+}
+
+TEST_CASE(test_system_resolver_looks_up_ipv6_addresses_again_once_ipv6_is_reachable)
+{
+ Core::EventLoop loop;
+ SystemResolverWithHeldBackIPv4 system_resolver;
+ DNS::Resolver resolver {
+ [] -> ErrorOr<Optional<DNS::Resolver::SocketResult>> { return OptionalNone {}; },
+ system_resolver.system_resolver(false),
+ };
+
+ system_resolver.let_ipv4_answer();
+ auto lookup = [&] {
+ return resolver.lookup("example.com"sv, DNS::Messages::Class::IN, { DNS::Messages::ResourceType::A, DNS::Messages::ResourceType::AAAA })->await();
+ };
+
+ auto first = TRY_OR_FAIL(lookup());
+ EXPECT_EQ(first->cached_addresses().size(), 1u);
+ EXPECT(!system_resolver.ipv6_answered());
+
+ // While IPv6 stays unreachable, the cached result without IPv6 addresses is used.
+ auto second = TRY_OR_FAIL(lookup());
+ EXPECT_EQ(second.ptr(), first.ptr());
+
+ // Reachability is checked again at most once a second.
+ system_resolver.set_ipv6_is_globally_reachable(true);
+ auto timer = Core::Timer::create_single_shot(AK::Duration::from_milliseconds(1100), [&] { loop.quit(0); });
+ timer->start();
+ loop.exec();
+
+ // The cached result never asked for IPv6 addresses, so it does not answer for them now that IPv6 is reachable.
+ auto third = TRY_OR_FAIL(lookup());
+ EXPECT(system_resolver.ipv6_answered());
+ EXPECT_EQ(third->cached_addresses().size(), 2u);
+ EXPECT(has_address_of_family(*third, false));
+ EXPECT(has_address_of_family(*third, true));
+}
+
+TEST_CASE(test_system_resolver_does_not_join_a_lookup_without_ipv6_addresses_once_ipv6_is_reachable)
+{
+ Core::EventLoop loop;
+ SystemResolverWithHeldBackIPv4 system_resolver;
+ DNS::Resolver resolver {
+ [] -> ErrorOr<Optional<DNS::Resolver::SocketResult>> { return OptionalNone {}; },
+ system_resolver.system_resolver(false),
+ };
+
+ auto lookup = [&] {
+ return resolver.lookup("example.com"sv, DNS::Messages::Class::IN, { DNS::Messages::ResourceType::A, DNS::Messages::ResourceType::AAAA });
+ };
+
+ auto first = lookup();
+
+ // Reachability is checked again at most once a second.
+ system_resolver.set_ipv6_is_globally_reachable(true);
+ auto timer = Core::Timer::create_single_shot(AK::Duration::from_milliseconds(1100), [&] { loop.quit(0); });
+ timer->start();
+ loop.exec();
+
+ // The first lookup is still waiting for IPv4 addresses, but it never asked for IPv6 addresses.
+ auto second = lookup();
+ bool gave_up = false;
+ timer = Core::Timer::create_single_shot(AK::Duration::from_milliseconds(500), [&] { gave_up = true; });
+ timer->start();
+ loop.spin_until([&] { return system_resolver.ipv6_answered() || gave_up; });
+ EXPECT(system_resolver.ipv6_answered());
+
+ system_resolver.let_ipv4_answer();
+ auto first_result = TRY_OR_FAIL(first->await());
+ EXPECT_EQ(first_result->cached_addresses().size(), 1u);
+ EXPECT(has_address_of_family(*first_result, false));
+
+ auto second_result = TRY_OR_FAIL(second->await());
+ EXPECT_EQ(second_result->cached_addresses().size(), 2u);
+ EXPECT(has_address_of_family(*second_result, false));
+ EXPECT(has_address_of_family(*second_result, true));
+}
+
+TEST_CASE(test_system_resolver_does_not_join_a_lookup_without_ipv4_addresses_once_ipv6_is_unreachable)
+{
+ Core::EventLoop loop;
+ SystemResolverWithHeldBackIPv4 system_resolver;
+ DNS::Resolver resolver {
+ [] -> ErrorOr<Optional<DNS::Resolver::SocketResult>> { return OptionalNone {}; },
+ system_resolver.system_resolver(),
+ };
+
+ auto lookup = [&] {
+ return resolver.lookup("example.com"sv, DNS::Messages::Class::IN, { DNS::Messages::ResourceType::A, DNS::Messages::ResourceType::AAAA });
+ };
+
+ // The first lookup goes ahead with IPv6 addresses alone while it keeps waiting for IPv4 addresses.
+ auto first = TRY_OR_FAIL(lookup()->await());
+ EXPECT_EQ(first->cached_addresses().size(), 1u);
+ EXPECT(has_address_of_family(*first, true));
+
+ // Reachability is checked again at most once a second.
+ system_resolver.set_ipv6_is_globally_reachable(false);
+ auto timer = Core::Timer::create_single_shot(AK::Duration::from_milliseconds(1100), [&] { loop.quit(0); });
+ timer->start();
+ loop.exec();
+
+ // IPv6 addresses are of no use now, so the second lookup waits for its own IPv4 addresses.
+ auto second = lookup();
+ system_resolver.let_ipv4_answer();
+ auto second_result = TRY_OR_FAIL(second->await());
+ EXPECT_EQ(second_result->cached_addresses().size(), 1u);
+ EXPECT(has_address_of_family(*second_result, false));
+
+ loop.spin_until([&] { return has_address_of_family(*first, false); });
+}