1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
|
// Copyright 2024 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/dns/dns_task_results_manager.h"
#include <algorithm>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <variant>
#include <vector>
#include "base/memory/raw_ptr.h"
#include "base/metrics/field_trial_params.h"
#include "base/strings/string_number_conversions.h"
#include "base/time/time.h"
#include "base/timer/timer.h"
#include "net/base/connection_endpoint_metadata.h"
#include "net/base/features.h"
#include "net/base/ip_endpoint.h"
#include "net/base/net_errors.h"
#include "net/dns/dns_alias_utility.h"
#include "net/dns/host_resolver.h"
#include "net/dns/host_resolver_dns_task.h"
#include "net/dns/host_resolver_internal_result.h"
#include "net/dns/https_record_rdata.h"
#include "net/dns/public/dns_query_type.h"
#include "net/dns/public/host_resolver_results.h"
#include "net/log/net_log_event_type.h"
#include "net/log/net_log_with_source.h"
#include "url/scheme_host_port.h"
namespace net {
namespace {
// Prioritize with-ipv6 over ipv4-only.
bool CompareServiceEndpointAddresses(const ServiceEndpoint& a,
const ServiceEndpoint& b) {
const bool a_has_ipv6 = !a.ipv6_endpoints.empty();
const bool b_has_ipv6 = !b.ipv6_endpoints.empty();
if ((a_has_ipv6 && b_has_ipv6) || (!a_has_ipv6 && !b_has_ipv6)) {
return false;
}
if (b_has_ipv6) {
return false;
}
return true;
}
// Prioritize with-metadata, with-ipv6 over ipv4-only.
// TODO(crbug.com/41493696): Consider which fields should be prioritized. We
// may want to have different sorting algorithms and choose one via config.
bool CompareServiceEndpoint(const ServiceEndpoint& a,
const ServiceEndpoint& b) {
const bool a_has_metadata = a.metadata != ConnectionEndpointMetadata();
const bool b_has_metadata = b.metadata != ConnectionEndpointMetadata();
if (a_has_metadata && b_has_metadata) {
return CompareServiceEndpointAddresses(a, b);
}
if (a_has_metadata) {
return true;
}
if (b_has_metadata) {
return false;
}
return CompareServiceEndpointAddresses(a, b);
}
// https://datatracker.ietf.org/doc/html/draft-pauly-v6ops-happy-eyeballs-v3-02#name-summary-of-configurable-val
constexpr base::FeatureParam<base::TimeDelta> kResolutionDelay{
&features::kHappyEyeballsV3,
"resolution_delay",
base::Milliseconds(50),
};
} // namespace
// Holds service endpoint results per domain name.
struct DnsTaskResultsManager::PerDomainResult {
PerDomainResult() = default;
~PerDomainResult() = default;
PerDomainResult(PerDomainResult&&) = default;
PerDomainResult& operator=(PerDomainResult&&) = default;
PerDomainResult(const PerDomainResult&) = delete;
PerDomainResult& operator=(const PerDomainResult&) = delete;
std::vector<IPEndPoint> ipv4_endpoints;
std::vector<IPEndPoint> ipv6_endpoints;
std::multimap<HttpsRecordPriority, ConnectionEndpointMetadata> metadatas;
};
// static
base::TimeDelta DnsTaskResultsManager::GetResolutionDelay() {
return kResolutionDelay.Get();
}
DnsTaskResultsManager::DnsTaskResultsManager(Delegate* delegate,
HostResolver::Host host,
DnsQueryTypeSet query_types,
const NetLogWithSource& net_log)
: delegate_(delegate),
host_(std::move(host)),
query_types_(query_types),
net_log_(net_log) {
CHECK(delegate_);
}
DnsTaskResultsManager::~DnsTaskResultsManager() = default;
void DnsTaskResultsManager::ProcessDnsTransactionResults(
DnsQueryType query_type,
std::set<const HostResolverInternalResult*> results) {
CHECK(query_types_.Has(query_type));
bool should_update_endpoints = false;
bool should_notify = false;
if (query_type == DnsQueryType::HTTPS) {
// Chrome does not yet support HTTPS follow-up queries so metadata is
// considered ready when the HTTPS response is received.
CHECK(!is_metadata_ready_);
is_metadata_ready_ = true;
should_notify = true;
}
if (query_type == DnsQueryType::AAAA) {
aaaa_response_received_ = true;
if (resolution_delay_timer_.IsRunning()) {
resolution_delay_timer_.Stop();
RecordResolutionDelayResult(/*timedout=*/false);
// Need to update endpoints when there are IPv4 addresses.
if (HasIpv4Addresses()) {
should_update_endpoints = true;
}
}
}
// Track whether new aliases are added.
bool aliases_updated = false;
for (const auto& result : results) {
auto [unused_1_, updated_domain_name] =
aliases_.insert(result->domain_name());
aliases_updated |= updated_domain_name;
switch (result->type()) {
case HostResolverInternalResult::Type::kData: {
PerDomainResult& per_domain_result =
GetOrCreatePerDomainResult(result->domain_name());
for (const auto& ip_endpoint : result->AsData().endpoints()) {
CHECK_EQ(ip_endpoint.port(), 0);
// TODO(crbug.com/41493696): This will eventually need to handle
// DnsQueryType::HTTPS to support getting ipv{4,6}hints.
if (ip_endpoint.address().IsIPv4()) {
per_domain_result.ipv4_endpoints.emplace_back(ip_endpoint.address(),
host_.GetPort());
} else {
CHECK(ip_endpoint.address().IsIPv6());
per_domain_result.ipv6_endpoints.emplace_back(ip_endpoint.address(),
host_.GetPort());
}
}
should_update_endpoints |= !result->AsData().endpoints().empty();
break;
}
case HostResolverInternalResult::Type::kMetadata: {
CHECK_EQ(query_type, DnsQueryType::HTTPS);
for (auto [priority, metadata] : result->AsMetadata().metadatas()) {
// Associate the metadata with the target name instead of the domain
// name since the metadata is for the target name.
PerDomainResult& per_domain_result =
GetOrCreatePerDomainResult(metadata.target_name);
per_domain_result.metadatas.emplace(priority, metadata);
}
should_update_endpoints |= !result->AsMetadata().metadatas().empty();
break;
}
case net::HostResolverInternalResult::Type::kAlias: {
auto [unused_2_, updated_alias] =
aliases_.insert(result->AsAlias().alias_target());
aliases_updated |= updated_alias;
break;
}
case net::HostResolverInternalResult::Type::kError:
// Need to update endpoints when AAAA response is NODATA but A response
// has at least one valid address.
// TODO(crbug.com/41493696): Revisit how to handle errors other than
// NODATA. Currently we just ignore errors here and defer
// HostResolverManager::Job to create an error result and notify the
// error to the corresponding requests. This means that if the
// connection layer has already attempted a connection using an
// intermediate endpoint, the error might not be treated as fatal. We
// may want to have a different semantics.
PerDomainResult& per_domain_result =
GetOrCreatePerDomainResult(result->domain_name());
if (query_type == DnsQueryType::AAAA &&
result->AsError().error() == ERR_NAME_NOT_RESOLVED &&
!per_domain_result.ipv4_endpoints.empty()) {
CHECK(per_domain_result.ipv6_endpoints.empty());
should_update_endpoints = true;
}
break;
}
}
// Only fix up aliases if new ones were added.
if (aliases_updated) {
aliases_ = dns_alias_utility::FixUpDnsAliases(aliases_);
}
const bool waiting_for_aaaa_response =
query_types_.Has(DnsQueryType::AAAA) && !aaaa_response_received_;
if (waiting_for_aaaa_response) {
if (query_type == DnsQueryType::A && should_update_endpoints) {
// A is responded, start the resolution delay timer.
CHECK(!resolution_delay_timer_.IsRunning());
resolution_delay_start_time_ = base::TimeTicks::Now();
net_log_.BeginEvent(
NetLogEventType::HOST_RESOLVER_SERVICE_ENDPOINTS_RESOLUTION_DELAY);
// Safe to unretain since `this` owns the timer.
resolution_delay_timer_.Start(
FROM_HERE, GetResolutionDelay(),
base::BindOnce(&DnsTaskResultsManager::OnAaaaResolutionTimedout,
base::Unretained(this)));
}
return;
}
if (should_update_endpoints) {
UpdateEndpoints();
return;
}
if (should_notify && !current_endpoints_.empty()) {
delegate_->OnServiceEndpointsUpdated();
}
}
const std::vector<ServiceEndpoint>& DnsTaskResultsManager::GetCurrentEndpoints()
const {
return current_endpoints_;
}
const std::set<std::string>& DnsTaskResultsManager::GetAliases() const {
return aliases_;
}
bool DnsTaskResultsManager::IsMetadataReady() const {
return !query_types_.Has(DnsQueryType::HTTPS) || is_metadata_ready_;
}
DnsTaskResultsManager::PerDomainResult&
DnsTaskResultsManager::GetOrCreatePerDomainResult(
const std::string& domain_name) {
auto it = per_domain_results_.find(domain_name);
if (it == per_domain_results_.end()) {
it = per_domain_results_.try_emplace(it, domain_name,
std::make_unique<PerDomainResult>());
}
return *it->second;
}
void DnsTaskResultsManager::OnAaaaResolutionTimedout() {
CHECK(!aaaa_response_received_);
RecordResolutionDelayResult(/*timedout=*/true);
UpdateEndpoints();
}
void DnsTaskResultsManager::UpdateEndpoints() {
std::vector<ServiceEndpoint> new_endpoints;
for (const auto& [domain_name, per_domain_result] : per_domain_results_) {
if (per_domain_result->ipv4_endpoints.empty() &&
per_domain_result->ipv6_endpoints.empty()) {
continue;
}
if (per_domain_result->metadatas.empty()) {
ServiceEndpoint endpoint;
endpoint.ipv4_endpoints = per_domain_result->ipv4_endpoints;
endpoint.ipv6_endpoints = per_domain_result->ipv6_endpoints;
new_endpoints.emplace_back(std::move(endpoint));
} else {
for (const auto& [unused_, metadata] : per_domain_result->metadatas) {
ServiceEndpoint endpoint;
endpoint.ipv4_endpoints = per_domain_result->ipv4_endpoints;
endpoint.ipv6_endpoints = per_domain_result->ipv6_endpoints;
// TODO(crbug.com/41493696): Just adding per-domain metadata does not
// work properly when the target name of HTTPS is an alias, e.g:
// example.com. 60 IN CNAME svc.example.com.
// svc.example.com. 60 IN AAAA 2001:db8::1
// svc.example.com. 60 IN HTTPS 1 example.com alpn="h2"
// In this case, svc.example.com should have metadata with alpn="h2" but
// the current logic doesn't do that. To handle it correctly we need to
// go though an alias tree for the domain name.
endpoint.metadata = metadata;
new_endpoints.emplace_back(std::move(endpoint));
}
}
}
// TODO(crbug.com/41493696): Determine how to handle non-SVCB connection
// fallback. See https://datatracker.ietf.org/doc/html/rfc9460#section-3-8
// HostCache::Entry::GetEndpoints() appends a final non-alternative endpoint
// at the end to ensure that the connection layer can fall back to non-SVCB
// connection. For ServiceEndpoint request API, the current plan is to handle
// non-SVCB connection fallback in the connection layer. The approach might
// not work when Chrome tries to support HTTPS follow-up queries and aliases.
// Stable sort preserves metadata priorities.
std::stable_sort(new_endpoints.begin(), new_endpoints.end(),
CompareServiceEndpoint);
current_endpoints_ = std::move(new_endpoints);
if (current_endpoints_.empty()) {
return;
}
net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_SERVICE_ENDPOINTS_UPDATED,
[&] {
base::Value::Dict dict;
base::Value::List endpoints;
for (const auto& endpoint : current_endpoints_) {
endpoints.Append(endpoint.ToValue());
}
dict.Set("endpoints", std::move(endpoints));
return dict;
});
delegate_->OnServiceEndpointsUpdated();
}
bool DnsTaskResultsManager::HasIpv4Addresses() {
for (const auto& [unused_, per_domain_result] : per_domain_results_) {
if (!per_domain_result->ipv4_endpoints.empty()) {
return true;
}
}
return false;
}
void DnsTaskResultsManager::RecordResolutionDelayResult(bool timedout) {
net_log_.EndEvent(
NetLogEventType::HOST_RESOLVER_SERVICE_ENDPOINTS_RESOLUTION_DELAY, [&]() {
base::TimeDelta elapsed =
base::TimeTicks::Now() - resolution_delay_start_time_;
base::Value::Dict dict;
dict.Set("timedout", timedout);
dict.Set("elapsed", base::NumberToString(elapsed.InMilliseconds()));
return dict;
});
}
} // namespace net
|