blob: 3ca7ba1841c24adf61e6241b377396ead6df2b6c [file] [log] [blame]
[email protected]a2730882012-01-21 00:56:271// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]b59ff372009-07-15 22:04:322// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
[email protected]f2cb3cf2013-03-21 01:40:535#include "net/dns/host_resolver_impl.h"
[email protected]b59ff372009-07-15 22:04:326
[email protected]21526002010-05-16 19:42:467#if defined(OS_WIN)
8#include <Winsock2.h>
Fabrice de Gans-Riberi7de47372018-05-08 20:23:479#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]21526002010-05-16 19:42:4610#include <netdb.h>
tfarinada9e1362017-03-14 16:49:0611#include <netinet/in.h>
12#if !defined(OS_NACL)
13#include <net/if.h>
14#if !defined(OS_ANDROID)
15#include <ifaddrs.h>
16#endif // !defined(OS_ANDROID)
17#endif // !defined(OS_NACL)
Fabrice de Gans-Riberi7de47372018-05-08 20:23:4718#endif // defined(OS_WIN)
tfarinada9e1362017-03-14 16:49:0619
Eric Orth70992982018-07-24 00:25:0020#include <algorithm>
[email protected]68ad3ee2010-01-30 03:45:3921#include <cmath>
Eric Orth70992982018-07-24 00:25:0022#include <limits>
thestiga74ad2b2016-07-11 20:52:3623#include <memory>
Eric Orth192e3bb2018-11-14 19:30:3224#include <unordered_set>
[email protected]0f292de02012-02-01 22:28:2025#include <utility>
[email protected]21526002010-05-16 19:42:4626#include <vector>
[email protected]68ad3ee2010-01-30 03:45:3927
[email protected]33152acc2011-10-20 23:37:1228#include "base/bind.h"
[email protected]aa22b242011-11-16 18:58:2929#include "base/bind_helpers.h"
[email protected]0f292de02012-02-01 22:28:2030#include "base/callback.h"
maksim.sisov31452af2016-07-27 06:38:1031#include "base/callback_helpers.h"
[email protected]b59ff372009-07-15 22:04:3232#include "base/compiler_specific.h"
David Benjamina5677192018-04-23 23:25:4233#include "base/containers/linked_list.h"
[email protected]58580352010-10-26 04:07:5034#include "base/debug/debugger.h"
35#include "base/debug/stack_trace.h"
Avi Drissman13fc8932015-12-20 04:40:4636#include "base/macros.h"
mmenke91c17162016-06-02 16:03:2337#include "base/memory/ptr_util.h"
[email protected]1e9bbd22010-10-15 16:42:4538#include "base/metrics/field_trial.h"
Maks Orlovich5393c8682018-02-26 16:17:5039#include "base/metrics/field_trial_params.h"
Ilya Sherman0eb39802017-12-08 20:58:1840#include "base/metrics/histogram_functions.h"
davidbenad6fc442015-05-18 20:59:1341#include "base/metrics/histogram_macros.h"
Paul Jensen41dc3e9f2018-11-06 22:10:1042#include "base/no_destructor.h"
anujk.sharma7c907f02015-05-29 02:55:4443#include "base/single_thread_task_runner.h"
[email protected]be528af2013-06-11 07:39:4844#include "base/strings/string_util.h"
[email protected]750b2f3c2013-06-07 18:41:0545#include "base/strings/utf_string_conversions.h"
Gabriel Charette44db1422018-08-06 11:19:3346#include "base/task/post_task.h"
Francois Doraya2d01ba2017-09-25 19:17:4047#include "base/threading/scoped_blocking_call.h"
gabf767595f2016-05-11 18:50:3548#include "base/threading/thread_task_runner_handle.h"
Misha Efimovb99e7da2018-05-30 16:59:0249#include "base/time/default_tick_clock.h"
[email protected]66e96c42013-06-28 15:20:3150#include "base/time/time.h"
ssid6d6b40102016-04-05 18:59:5651#include "base/trace_event/trace_event.h"
[email protected]21526002010-05-16 19:42:4652#include "base/values.h"
Fabrice de Gans-Riberi7de47372018-05-08 20:23:4753#include "build/build_config.h"
[email protected]b3601bc22012-02-21 21:23:2054#include "net/base/address_family.h"
[email protected]b59ff372009-07-15 22:04:3255#include "net/base/address_list.h"
[email protected]ee094b82010-08-24 15:55:5156#include "net/base/host_port_pair.h"
martijna23c8962016-03-04 18:18:5157#include "net/base/ip_address.h"
[email protected]1c7cf3f82014-08-07 21:33:4858#include "net/base/ip_endpoint.h"
[email protected]2bb04442010-08-18 18:01:1559#include "net/base/net_errors.h"
xunjieli0b7f5b62016-12-06 20:43:4860#include "net/base/trace_constants.h"
tfarina9ed7f8c52016-02-19 17:50:1861#include "net/base/url_util.h"
[email protected]0adcb2b2012-08-15 21:30:4662#include "net/dns/address_sorter.h"
[email protected]78eac2a2012-03-14 19:09:2763#include "net/dns/dns_client.h"
tfarina47598f042015-10-07 23:08:3564#include "net/dns/dns_reloader.h"
[email protected]b3601bc22012-02-21 21:23:2065#include "net/dns/dns_response.h"
[email protected]b3601bc22012-02-21 21:23:2066#include "net/dns/dns_transaction.h"
tfarina77021d62015-10-11 20:19:0367#include "net/dns/dns_util.h"
Eric Orth9871aafa2018-10-02 19:59:1868#include "net/dns/host_resolver_mdns_task.h"
[email protected]f2cb3cf2013-03-21 01:40:5369#include "net/dns/host_resolver_proc.h"
Eric Orth9871aafa2018-10-02 19:59:1870#include "net/dns/mdns_client.h"
Eric Orth8afaf152018-11-07 21:01:2671#include "net/dns/public/dns_protocol.h"
eroman87c53d62015-04-02 06:51:0772#include "net/log/net_log.h"
mikecironef22f9812016-10-04 03:40:1973#include "net/log/net_log_capture_mode.h"
mikecirone8b85c432016-09-08 19:11:0074#include "net/log/net_log_event_type.h"
mikecironef22f9812016-10-04 03:40:1975#include "net/log/net_log_parameters_callback.h"
76#include "net/log/net_log_source.h"
mikecirone8b85c432016-09-08 19:11:0077#include "net/log/net_log_source_type.h"
mikecironef22f9812016-10-04 03:40:1978#include "net/log/net_log_with_source.h"
[email protected]9db6f702013-04-10 18:10:5179#include "net/socket/client_socket_factory.h"
tfarina5dd13c22016-11-16 12:08:2680#include "net/socket/datagram_client_socket.h"
pauljensen370f1c72015-02-17 16:59:1481#include "url/url_canon_ip.h"
[email protected]b59ff372009-07-15 22:04:3282
Eric Orth9871aafa2018-10-02 19:59:1883#if BUILDFLAG(ENABLE_MDNS)
84#include "net/dns/mdns_client_impl.h"
85#endif
86
[email protected]b59ff372009-07-15 22:04:3287#if defined(OS_WIN)
88#include "net/base/winsock_init.h"
89#endif
90
tfarinada9e1362017-03-14 16:49:0691#if defined(OS_ANDROID)
Paul Jensen41dc3e9f2018-11-06 22:10:1092#include "base/android/build_info.h"
tfarinada9e1362017-03-14 16:49:0693#include "net/android/network_library.h"
94#endif
95
[email protected]b59ff372009-07-15 22:04:3296namespace net {
97
[email protected]e95d3aca2010-01-11 22:47:4398namespace {
99
ttuttlecf1158bf2016-03-18 16:37:44100// Default delay between calls to the system resolver for the same hostname.
101// (Can be overridden by field trial.)
102const int64_t kDnsDefaultUnresponsiveDelayMs = 6000;
103
[email protected]6e78dfb2011-07-28 21:34:47104// Limit the size of hostnames that will be resolved to combat issues in
105// some platform's resolvers.
106const size_t kMaxHostLength = 4096;
107
[email protected]a2730882012-01-21 00:56:27108// Default TTL for successful resolutions with ProcTask.
109const unsigned kCacheEntryTTLSeconds = 60;
110
[email protected]b3601bc22012-02-21 21:23:20111// Default TTL for unsuccessful resolutions with ProcTask.
112const unsigned kNegativeCacheEntryTTLSeconds = 0;
113
[email protected]895123222012-10-25 15:21:17114// Minimum TTL for successful resolutions with DnsTask.
115const unsigned kMinimumTTLSeconds = kCacheEntryTTLSeconds;
116
sergeyub8cdc212015-05-14 18:50:37117// Time between IPv6 probes, i.e. for how long results of each IPv6 probe are
118// cached.
119const int kIPv6ProbePeriodMs = 1000;
120
121// Google DNS address used for IPv6 probes.
122const uint8_t kIPv6ProbeAddress[] =
123 { 0x20, 0x01, 0x48, 0x60, 0x48, 0x60, 0x00, 0x00,
124 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x88 };
125
[email protected]1def74c2012-03-22 20:07:00126enum DnsResolveStatus {
127 RESOLVE_STATUS_DNS_SUCCESS = 0,
128 RESOLVE_STATUS_PROC_SUCCESS,
129 RESOLVE_STATUS_FAIL,
[email protected]1d932852012-06-19 19:40:33130 RESOLVE_STATUS_SUSPECT_NETBIOS,
[email protected]1def74c2012-03-22 20:07:00131 RESOLVE_STATUS_MAX
132};
133
eroman91dd3602015-03-26 03:46:33134// ICANN uses this localhost address to indicate a name collision.
135//
136// The policy in Chromium is to fail host resolving if it resolves to
137// this special address.
138//
139// Not however that IP literals are exempt from this policy, so it is still
140// possible to navigate to http://127.0.53.53/ directly.
141//
142// For more details: https://www.icann.org/news/announcement-2-2014-08-01-en
martijna23c8962016-03-04 18:18:51143const uint8_t kIcanNameCollisionIp[] = {127, 0, 53, 53};
eroman91dd3602015-03-26 03:46:33144
eroman1efc237c2016-12-14 00:00:45145bool ContainsIcannNameCollisionIp(const AddressList& addr_list) {
146 for (const auto& endpoint : addr_list) {
147 const IPAddress& addr = endpoint.address();
148 if (addr.IsIPv4() && IPAddressStartsWith(addr, kIcanNameCollisionIp)) {
149 return true;
150 }
151 }
152 return false;
153}
154
[email protected]1d932852012-06-19 19:40:33155// True if |hostname| ends with either ".local" or ".local.".
156bool ResemblesMulticastDNSName(const std::string& hostname) {
157 DCHECK(!hostname.empty());
158 const char kSuffix[] = ".local.";
159 const size_t kSuffixLen = sizeof(kSuffix) - 1;
160 const size_t kSuffixLenTrimmed = kSuffixLen - 1;
thestiga74ad2b2016-07-11 20:52:36161 if (hostname.back() == '.') {
[email protected]1d932852012-06-19 19:40:33162 return hostname.size() > kSuffixLen &&
163 !hostname.compare(hostname.size() - kSuffixLen, kSuffixLen, kSuffix);
164 }
165 return hostname.size() > kSuffixLenTrimmed &&
166 !hostname.compare(hostname.size() - kSuffixLenTrimmed, kSuffixLenTrimmed,
167 kSuffix, kSuffixLenTrimmed);
168}
169
[email protected]16c2bd72013-06-28 01:19:22170bool ConfigureAsyncDnsNoFallbackFieldTrial() {
171 const bool kDefault = false;
172
173 // Configure the AsyncDns field trial as follows:
174 // groups AsyncDnsNoFallbackA and AsyncDnsNoFallbackB: return true,
175 // groups AsyncDnsA and AsyncDnsB: return false,
176 // groups SystemDnsA and SystemDnsB: return false,
177 // otherwise (trial absent): return default.
178 std::string group_name = base::FieldTrialList::FindFullName("AsyncDns");
brettw3a2c6902015-07-06 19:43:29179 if (!group_name.empty()) {
180 return base::StartsWith(group_name, "AsyncDnsNoFallback",
181 base::CompareCase::INSENSITIVE_ASCII);
182 }
[email protected]16c2bd72013-06-28 01:19:22183 return kDefault;
184}
185
Maks Orlovich5393c8682018-02-26 16:17:50186const base::FeatureParam<base::TaskPriority>::Option prio_modes[] = {
187 {base::TaskPriority::USER_VISIBLE, "default"},
188 {base::TaskPriority::USER_BLOCKING, "user_blocking"}};
189const base::Feature kSystemResolverPriorityExperiment = {
190 "SystemResolverPriorityExperiment", base::FEATURE_DISABLED_BY_DEFAULT};
191const base::FeatureParam<base::TaskPriority> priority_mode{
192 &kSystemResolverPriorityExperiment, "mode",
193 base::TaskPriority::USER_VISIBLE, &prio_modes};
194
[email protected]d7b9a2b2012-05-31 22:31:19195//-----------------------------------------------------------------------------
196
Matt Menkec35d1632018-11-29 12:43:49197// Creates a copy of |results| with the port of all address and hostname values
198// set to |port| if the current port is 0. Preserves any non-zero ports.
199HostCache::Entry SetPortOnResults(HostCache::Entry results, uint16_t port) {
200 if (results.addresses() &&
201 std::any_of(results.addresses().value().begin(),
202 results.addresses().value().end(),
203 [](const IPEndPoint& e) { return e.port() == 0; })) {
204 AddressList addresses_with_port;
205 addresses_with_port.set_canonical_name(
206 results.addresses().value().canonical_name());
207 for (const IPEndPoint& endpoint : results.addresses().value()) {
208 if (endpoint.port() == 0)
209 addresses_with_port.push_back(IPEndPoint(endpoint.address(), port));
210 else
211 addresses_with_port.push_back(endpoint);
212 }
213 results.set_addresses(addresses_with_port);
214 }
215
216 if (results.hostnames() &&
217 std::any_of(results.hostnames().value().begin(),
218 results.hostnames().value().end(),
219 [](const HostPortPair& h) { return h.port() == 0; })) {
220 std::vector<HostPortPair> hostnames_with_port;
221 for (const HostPortPair& hostname : results.hostnames().value()) {
222 if (hostname.port() == 0)
223 hostnames_with_port.push_back(HostPortPair(hostname.host(), port));
224 else
225 hostnames_with_port.push_back(hostname);
226 }
227 results.set_hostnames(std::move(hostnames_with_port));
228 }
229
230 return results;
[email protected]7054e78f2012-05-07 21:44:56231}
232
[email protected]ec666ab22013-04-17 20:05:59233// Returns true if |addresses| contains only IPv4 loopback addresses.
234bool IsAllIPv4Loopback(const AddressList& addresses) {
235 for (unsigned i = 0; i < addresses.size(); ++i) {
martijna23c8962016-03-04 18:18:51236 const IPAddress& address = addresses[i].address();
[email protected]ec666ab22013-04-17 20:05:59237 switch (addresses[i].GetFamily()) {
238 case ADDRESS_FAMILY_IPV4:
martijna23c8962016-03-04 18:18:51239 if (address.bytes()[0] != 127)
[email protected]ec666ab22013-04-17 20:05:59240 return false;
241 break;
242 case ADDRESS_FAMILY_IPV6:
243 return false;
244 default:
245 NOTREACHED();
246 return false;
247 }
248 }
249 return true;
250}
251
tfarinada9e1362017-03-14 16:49:06252// Returns true if it can determine that only loopback addresses are configured.
253// i.e. if only 127.0.0.1 and ::1 are routable.
254// Also returns false if it cannot determine this.
255bool HaveOnlyLoopbackAddresses() {
Francois Doraya2d01ba2017-09-25 19:17:40256 base::ScopedBlockingCall scoped_blocking_call(base::BlockingType::WILL_BLOCK);
Fabrice de Gans-Riberi7de47372018-05-08 20:23:47257#if defined(OS_WIN)
258 // TODO(wtc): implement with the GetAdaptersAddresses function.
259 NOTIMPLEMENTED();
260 return false;
261#elif defined(OS_ANDROID)
tfarinada9e1362017-03-14 16:49:06262 return android::HaveOnlyLoopbackAddresses();
263#elif defined(OS_NACL)
264 NOTIMPLEMENTED();
265 return false;
Fabrice de Gans-Riberi7de47372018-05-08 20:23:47266#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
tfarinada9e1362017-03-14 16:49:06267 struct ifaddrs* interface_addr = NULL;
268 int rv = getifaddrs(&interface_addr);
269 if (rv != 0) {
Wezeba21492018-12-05 18:24:17270 DVPLOG(1) << "getifaddrs() failed";
tfarinada9e1362017-03-14 16:49:06271 return false;
272 }
273
274 bool result = true;
275 for (struct ifaddrs* interface = interface_addr;
276 interface != NULL;
277 interface = interface->ifa_next) {
278 if (!(IFF_UP & interface->ifa_flags))
279 continue;
280 if (IFF_LOOPBACK & interface->ifa_flags)
281 continue;
282 const struct sockaddr* addr = interface->ifa_addr;
283 if (!addr)
284 continue;
285 if (addr->sa_family == AF_INET6) {
286 // Safe cast since this is AF_INET6.
287 const struct sockaddr_in6* addr_in6 =
288 reinterpret_cast<const struct sockaddr_in6*>(addr);
289 const struct in6_addr* sin6_addr = &addr_in6->sin6_addr;
290 if (IN6_IS_ADDR_LOOPBACK(sin6_addr) || IN6_IS_ADDR_LINKLOCAL(sin6_addr))
291 continue;
292 }
293 if (addr->sa_family != AF_INET6 && addr->sa_family != AF_INET)
294 continue;
295
296 result = false;
297 break;
298 }
299 freeifaddrs(interface_addr);
300 return result;
tfarinada9e1362017-03-14 16:49:06301#endif // defined(various platforms)
302}
303
[email protected]cd565142012-06-12 16:21:45304// Creates NetLog parameters when the resolve failed.
danakj22f90e72016-04-16 01:55:40305std::unique_ptr<base::Value> NetLogProcTaskFailedCallback(
Avi Drissman13fc8932015-12-20 04:40:46306 uint32_t attempt_number,
eroman001c3742015-04-23 03:11:17307 int net_error,
308 int os_error,
309 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40310 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]cd565142012-06-12 16:21:45311 if (attempt_number)
312 dict->SetInteger("attempt_number", attempt_number);
[email protected]21526002010-05-16 19:42:46313
[email protected]cd565142012-06-12 16:21:45314 dict->SetInteger("net_error", net_error);
[email protected]13024882011-05-18 23:19:16315
[email protected]cd565142012-06-12 16:21:45316 if (os_error) {
317 dict->SetInteger("os_error", os_error);
Fabrice de Gans-Riberi7de47372018-05-08 20:23:47318#if defined(OS_WIN)
[email protected]cd565142012-06-12 16:21:45319 // Map the error code to a human-readable string.
wezb9820d42016-06-22 23:41:04320 LPWSTR error_string = nullptr;
Peter Kastingbe940e92014-11-20 23:14:08321 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
322 0, // Use the internal message table.
323 os_error,
324 0, // Use default language.
325 (LPWSTR)&error_string,
326 0, // Buffer size.
327 0); // Arguments (unused).
[email protected]ad65a3e2013-12-25 18:18:01328 dict->SetString("os_error_string", base::WideToUTF8(error_string));
[email protected]cd565142012-06-12 16:21:45329 LocalFree(error_string);
Fabrice de Gans-Riberi7de47372018-05-08 20:23:47330#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
331 dict->SetString("os_error_string", gai_strerror(os_error));
[email protected]21526002010-05-16 19:42:46332#endif
[email protected]21526002010-05-16 19:42:46333 }
334
dchengc7eeda422015-12-26 03:56:48335 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45336}
[email protected]a9813302012-04-28 09:29:28337
[email protected]cd565142012-06-12 16:21:45338// Creates NetLog parameters when the DnsTask failed.
danakj22f90e72016-04-16 01:55:40339std::unique_ptr<base::Value> NetLogDnsTaskFailedCallback(
estade5e5529d2015-05-21 20:59:11340 int net_error,
341 int dns_error,
Matt Menkec35d1632018-11-29 12:43:49342 NetLogParametersCallback results_callback,
343 NetLogCaptureMode capture_mode) {
danakj22f90e72016-04-16 01:55:40344 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]cd565142012-06-12 16:21:45345 dict->SetInteger("net_error", net_error);
346 if (dns_error)
347 dict->SetInteger("dns_error", dns_error);
Matt Menkec35d1632018-11-29 12:43:49348 if (results_callback)
349 dict->Set("resolve_results", results_callback.Run(capture_mode));
dchengc7eeda422015-12-26 03:56:48350 return std::move(dict);
thestiga74ad2b2016-07-11 20:52:36351}
[email protected]ee094b82010-08-24 15:55:51352
[email protected]cd565142012-06-12 16:21:45353// Creates NetLog parameters containing the information in a RequestInfo object,
Eric Orth70992982018-07-24 00:25:00354// along with the associated NetLogSource. Use NetLogRequestCallback() if the
355// request information is not specified via RequestInfo.
danakj22f90e72016-04-16 01:55:40356std::unique_ptr<base::Value> NetLogRequestInfoCallback(
estade5e5529d2015-05-21 20:59:11357 const HostResolver::RequestInfo* info,
358 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40359 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]b3601bc22012-02-21 21:23:20360
[email protected]cd565142012-06-12 16:21:45361 dict->SetString("host", info->host_port_pair().ToString());
362 dict->SetInteger("address_family",
363 static_cast<int>(info->address_family()));
364 dict->SetBoolean("allow_cached_response", info->allow_cached_response());
365 dict->SetBoolean("is_speculative", info->is_speculative());
dchengc7eeda422015-12-26 03:56:48366 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45367}
[email protected]b3601bc22012-02-21 21:23:20368
Eric Orth70992982018-07-24 00:25:00369// Creates NetLog parameters containing the information of the request. Use
370// NetLogRequestInfoCallback if the request is specified via RequestInfo.
371std::unique_ptr<base::Value> NetLogRequestCallback(
372 const HostPortPair& host,
373 NetLogCaptureMode /* capture_mode */) {
374 auto dict = std::make_unique<base::DictionaryValue>();
375
376 dict->SetString("host", host.ToString());
377 dict->SetInteger("address_family",
378 static_cast<int>(ADDRESS_FAMILY_UNSPECIFIED));
379 dict->SetBoolean("allow_cached_response", true);
380 dict->SetBoolean("is_speculative", false);
381 return std::move(dict);
382}
383
[email protected]cd565142012-06-12 16:21:45384// Creates NetLog parameters for the creation of a HostResolverImpl::Job.
danakj22f90e72016-04-16 01:55:40385std::unique_ptr<base::Value> NetLogJobCreationCallback(
mikecironef22f9812016-10-04 03:40:19386 const NetLogSource& source,
estade5e5529d2015-05-21 20:59:11387 const std::string* host,
388 NetLogCaptureMode /* capture_mode */) {
Eric Orth70992982018-07-24 00:25:00389 auto dict = std::make_unique<base::DictionaryValue>();
estade5e5529d2015-05-21 20:59:11390 source.AddToEventParameters(dict.get());
[email protected]cd565142012-06-12 16:21:45391 dict->SetString("host", *host);
dchengc7eeda422015-12-26 03:56:48392 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45393}
[email protected]a9813302012-04-28 09:29:28394
[email protected]cd565142012-06-12 16:21:45395// Creates NetLog parameters for HOST_RESOLVER_IMPL_JOB_ATTACH/DETACH events.
danakj22f90e72016-04-16 01:55:40396std::unique_ptr<base::Value> NetLogJobAttachCallback(
mikecironef22f9812016-10-04 03:40:19397 const NetLogSource& source,
estade5e5529d2015-05-21 20:59:11398 RequestPriority priority,
399 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40400 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
estade5e5529d2015-05-21 20:59:11401 source.AddToEventParameters(dict.get());
[email protected]3b04d1f22013-10-16 00:23:56402 dict->SetString("priority", RequestPriorityToString(priority));
dchengc7eeda422015-12-26 03:56:48403 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45404}
[email protected]b3601bc22012-02-21 21:23:20405
[email protected]cd565142012-06-12 16:21:45406// Creates NetLog parameters for the DNS_CONFIG_CHANGED event.
danakj22f90e72016-04-16 01:55:40407std::unique_ptr<base::Value> NetLogDnsConfigCallback(
estade5e5529d2015-05-21 20:59:11408 const DnsConfig* config,
409 NetLogCaptureMode /* capture_mode */) {
tfhef3618f2016-01-11 23:07:08410 return config->ToValue();
[email protected]cd565142012-06-12 16:21:45411}
[email protected]b4481b222012-03-16 17:13:11412
danakj22f90e72016-04-16 01:55:40413std::unique_ptr<base::Value> NetLogIPv6AvailableCallback(
estade5e5529d2015-05-21 20:59:11414 bool ipv6_available,
415 bool cached,
416 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40417 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
sergeyub8cdc212015-05-14 18:50:37418 dict->SetBoolean("ipv6_available", ipv6_available);
419 dict->SetBoolean("cached", cached);
dchengc7eeda422015-12-26 03:56:48420 return std::move(dict);
sergeyub8cdc212015-05-14 18:50:37421}
422
[email protected]0f292de02012-02-01 22:28:20423// The logging routines are defined here because some requests are resolved
424// without a Request object.
425
Eric Orth70992982018-07-24 00:25:00426// Logs when a request has just been started. Overloads for whether or not the
427// request information is specified via a RequestInfo object.
tfarina428341112016-09-22 13:38:20428void LogStartRequest(const NetLogWithSource& source_net_log,
[email protected]0f292de02012-02-01 22:28:20429 const HostResolver::RequestInfo& info) {
mikecirone8b85c432016-09-08 19:11:00430 source_net_log.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_REQUEST,
431 base::Bind(&NetLogRequestInfoCallback, &info));
[email protected]0f292de02012-02-01 22:28:20432}
Eric Orth70992982018-07-24 00:25:00433void LogStartRequest(const NetLogWithSource& source_net_log,
434 const HostPortPair& host) {
435 source_net_log.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_REQUEST,
436 base::BindRepeating(&NetLogRequestCallback, host));
437}
[email protected]0f292de02012-02-01 22:28:20438
439// Logs when a request has just completed (before its callback is run).
Eric Orth70992982018-07-24 00:25:00440void LogFinishRequest(const NetLogWithSource& source_net_log, int net_error) {
xunjieli26f90452014-11-10 16:23:02441 source_net_log.EndEventWithNetErrorCode(
mikecirone8b85c432016-09-08 19:11:00442 NetLogEventType::HOST_RESOLVER_IMPL_REQUEST, net_error);
[email protected]0f292de02012-02-01 22:28:20443}
444
445// Logs when a request has been cancelled.
Eric Orth70992982018-07-24 00:25:00446void LogCancelRequest(const NetLogWithSource& source_net_log) {
mikecirone8b85c432016-09-08 19:11:00447 source_net_log.AddEvent(NetLogEventType::CANCELLED);
448 source_net_log.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_REQUEST);
[email protected]0f292de02012-02-01 22:28:20449}
450
[email protected]b59ff372009-07-15 22:04:32451//-----------------------------------------------------------------------------
452
[email protected]0f292de02012-02-01 22:28:20453// Keeps track of the highest priority.
454class PriorityTracker {
455 public:
[email protected]8c98d002012-07-18 19:02:27456 explicit PriorityTracker(RequestPriority initial_priority)
457 : highest_priority_(initial_priority), total_count_(0) {
[email protected]0f292de02012-02-01 22:28:20458 memset(counts_, 0, sizeof(counts_));
459 }
460
461 RequestPriority highest_priority() const {
462 return highest_priority_;
463 }
464
465 size_t total_count() const {
466 return total_count_;
467 }
468
469 void Add(RequestPriority req_priority) {
470 ++total_count_;
471 ++counts_[req_priority];
[email protected]31ae7ab2012-04-24 21:09:05472 if (highest_priority_ < req_priority)
[email protected]0f292de02012-02-01 22:28:20473 highest_priority_ = req_priority;
474 }
475
476 void Remove(RequestPriority req_priority) {
477 DCHECK_GT(total_count_, 0u);
478 DCHECK_GT(counts_[req_priority], 0u);
479 --total_count_;
480 --counts_[req_priority];
481 size_t i;
thestiga74ad2b2016-07-11 20:52:36482 for (i = highest_priority_; i > MINIMUM_PRIORITY && !counts_[i]; --i) {
483 }
[email protected]0f292de02012-02-01 22:28:20484 highest_priority_ = static_cast<RequestPriority>(i);
485
[email protected]31ae7ab2012-04-24 21:09:05486 // In absence of requests, default to MINIMUM_PRIORITY.
487 if (total_count_ == 0)
488 DCHECK_EQ(MINIMUM_PRIORITY, highest_priority_);
[email protected]0f292de02012-02-01 22:28:20489 }
490
491 private:
492 RequestPriority highest_priority_;
493 size_t total_count_;
494 size_t counts_[NUM_PRIORITIES];
495};
496
juliatuttle9fb7aeb2016-06-06 20:16:33497void MakeNotStale(HostCache::EntryStaleness* stale_info) {
498 if (!stale_info)
499 return;
500 stale_info->expired_by = base::TimeDelta::FromSeconds(-1);
501 stale_info->network_changes = 0;
502 stale_info->stale_hits = 0;
503}
504
Paul Jensen41dc3e9f2018-11-06 22:10:10505// Is |dns_server| within the list of known DNS servers that also support
506// DNS-over-HTTPS?
507bool DnsServerSupportsDoh(const IPAddress& dns_server) {
Eric Orth192e3bb2018-11-14 19:30:32508 static const base::NoDestructor<std::unordered_set<std::string>>
Raphael Kubo da Costa6e73ad42018-11-28 08:04:57509 upgradable_servers(std::initializer_list<std::string>({
Paul Jensen41dc3e9f2018-11-06 22:10:10510 // Google Public DNS
Raphael Kubo da Costa6e73ad42018-11-28 08:04:57511 "8.8.8.8",
512 "8.8.4.4",
513 "2001:4860:4860::8888",
514 "2001:4860:4860::8844",
Paul Jensen41dc3e9f2018-11-06 22:10:10515 // Cloudflare DNS
Raphael Kubo da Costa6e73ad42018-11-28 08:04:57516 "1.1.1.1",
517 "1.0.0.1",
518 "2606:4700:4700::1111",
519 "2606:4700:4700::1001",
Paul Jensen41dc3e9f2018-11-06 22:10:10520 // Quad9 DNS
Raphael Kubo da Costa6e73ad42018-11-28 08:04:57521 "9.9.9.9",
522 "149.112.112.112",
523 "2620:fe::fe",
524 "2620:fe::9",
525 }));
Paul Jensen41dc3e9f2018-11-06 22:10:10526 return upgradable_servers->find(dns_server.ToString()) !=
527 upgradable_servers->end();
528}
529
[email protected]c54a8912012-10-22 22:09:43530} // namespace
[email protected]0f292de02012-02-01 22:28:20531
532//-----------------------------------------------------------------------------
533
Matt Menkec35d1632018-11-29 12:43:49534bool ResolveLocalHostname(base::StringPiece host, AddressList* address_list) {
tfarina9ed7f8c52016-02-19 17:50:18535 address_list->clear();
536
537 bool is_local6;
538 if (!IsLocalHostname(host, &is_local6))
539 return false;
540
Matt Menkec35d1632018-11-29 12:43:49541 address_list->push_back(IPEndPoint(IPAddress::IPv6Localhost(), 0));
tfarina9ed7f8c52016-02-19 17:50:18542 if (!is_local6) {
Matt Menkec35d1632018-11-29 12:43:49543 address_list->push_back(IPEndPoint(IPAddress::IPv4Localhost(), 0));
tfarina9ed7f8c52016-02-19 17:50:18544 }
545
546 return true;
547}
548
[email protected]daae1322013-09-05 18:26:50549const unsigned HostResolverImpl::kMaximumDnsFailures = 16;
550
Eric Roman91aab1e62018-04-24 20:31:32551// Holds the callback and request parameters for an outstanding request.
552//
553// The RequestImpl is owned by the end user of host resolution. Deletion prior
554// to the request having completed means the request was cancelled by the
555// caller.
556//
557// Both the RequestImpl and its associated Job hold non-owning pointers to each
558// other. Care must be taken to clear the corresponding pointer when
559// cancellation is initiated by the Job (OnJobCancelled) vs by the end user
560// (~RequestImpl).
David Benjamina5677192018-04-23 23:25:42561class HostResolverImpl::RequestImpl
Eric Orth70992982018-07-24 00:25:00562 : public HostResolver::ResolveHostRequest,
David Benjamina5677192018-04-23 23:25:42563 public base::LinkNode<HostResolverImpl::RequestImpl> {
[email protected]b59ff372009-07-15 22:04:32564 public:
tfarina428341112016-09-22 13:38:20565 RequestImpl(const NetLogWithSource& source_net_log,
Eric Orth70992982018-07-24 00:25:00566 const HostPortPair& request_host,
Eric Orth00fe5a62018-08-15 22:20:00567 const base::Optional<ResolveHostParameters>& optional_parameters,
Eric Orth70992982018-07-24 00:25:00568 base::WeakPtr<HostResolverImpl> resolver)
[email protected]ee094b82010-08-24 15:55:51569 : source_net_log_(source_net_log),
Eric Orth70992982018-07-24 00:25:00570 request_host_(request_host),
Eric Orth00fe5a62018-08-15 22:20:00571 parameters_(optional_parameters ? optional_parameters.value()
572 : ResolveHostParameters()),
Eric Orthdc35748e2018-08-23 22:41:48573 host_resolver_flags_(ParametersToHostResolverFlags(parameters_)),
Eric Orth00fe5a62018-08-15 22:20:00574 priority_(parameters_.initial_priority),
Eric Orth70992982018-07-24 00:25:00575 job_(nullptr),
576 resolver_(resolver),
577 complete_(false) {}
[email protected]b59ff372009-07-15 22:04:32578
maksim.sisov31452af2016-07-27 06:38:10579 ~RequestImpl() override;
580
Eric Orth70992982018-07-24 00:25:00581 int Start(CompletionOnceCallback callback) override {
582 DCHECK(callback);
583 // Start() may only be called once per request.
584 DCHECK(!job_);
585 DCHECK(!complete_);
586 DCHECK(!callback_);
587 // Parent HostResolver must still be alive to call Start().
588 DCHECK(resolver_);
maksim.sisov31452af2016-07-27 06:38:10589
Eric Orth70992982018-07-24 00:25:00590 int rv = resolver_->Resolve(this);
591 DCHECK(!complete_);
592 if (rv == ERR_IO_PENDING) {
593 DCHECK(job_);
594 callback_ = std::move(callback);
595 } else {
596 DCHECK(!job_);
597 complete_ = true;
598 }
599 resolver_ = nullptr;
600
601 return rv;
602 }
603
604 const base::Optional<AddressList>& GetAddressResults() const override {
605 DCHECK(complete_);
Matt Menkec35d1632018-11-29 12:43:49606 static const base::NoDestructor<base::Optional<AddressList>> nullopt_result;
607 return results_ ? results_.value().addresses() : *nullopt_result;
Eric Orth70992982018-07-24 00:25:00608 }
609
Matt Menkec35d1632018-11-29 12:43:49610 const base::Optional<std::vector<std::string>>& GetTextResults()
611 const override {
612 DCHECK(complete_);
613 static const base::NoDestructor<base::Optional<std::vector<std::string>>>
614 nullopt_result;
615 return results_ ? results_.value().text_records() : *nullopt_result;
616 }
617
618 const base::Optional<std::vector<HostPortPair>>& GetHostnameResults()
619 const override {
620 DCHECK(complete_);
621 static const base::NoDestructor<base::Optional<std::vector<HostPortPair>>>
622 nullopt_result;
623 return results_ ? results_.value().hostnames() : *nullopt_result;
624 }
625
626 void set_results(HostCache::Entry results) {
Eric Orth70992982018-07-24 00:25:00627 // Should only be called at most once and before request is marked
628 // completed.
629 DCHECK(!complete_);
Matt Menkec35d1632018-11-29 12:43:49630 DCHECK(!results_);
Eric Orthb30bc172018-08-17 21:09:57631 DCHECK(!parameters_.is_speculative);
Eric Orth70992982018-07-24 00:25:00632
Matt Menkec35d1632018-11-29 12:43:49633 results_ = std::move(results);
Eric Orth70992982018-07-24 00:25:00634 }
635
636 void ChangeRequestPriority(RequestPriority priority);
637
638 void AssignJob(Job* job) {
639 DCHECK(job);
640 DCHECK(!job_);
641
642 job_ = job;
643 }
644
645 // Unassigns the Job without calling completion callback.
maksim.sisov31452af2016-07-27 06:38:10646 void OnJobCancelled(Job* job) {
647 DCHECK_EQ(job_, job);
wezb9820d42016-06-22 23:41:04648 job_ = nullptr;
Eric Orth70992982018-07-24 00:25:00649 DCHECK(!complete_);
650 DCHECK(callback_);
[email protected]aa22b242011-11-16 18:58:29651 callback_.Reset();
Eric Orth70992982018-07-24 00:25:00652
653 // No results should be set.
Matt Menkec35d1632018-11-29 12:43:49654 DCHECK(!results_);
[email protected]b59ff372009-07-15 22:04:32655 }
656
Eric Orth70992982018-07-24 00:25:00657 // Cleans up Job assignment, marks request completed, and calls the completion
658 // callback.
659 void OnJobCompleted(Job* job, int error) {
maksim.sisov31452af2016-07-27 06:38:10660 DCHECK_EQ(job_, job);
maksim.sisov31452af2016-07-27 06:38:10661 job_ = nullptr;
Eric Orth70992982018-07-24 00:25:00662
663 DCHECK(!complete_);
664 complete_ = true;
665
666 DCHECK(callback_);
Bence Béky0f26a5812018-06-13 03:18:40667 std::move(callback_).Run(error);
[email protected]b59ff372009-07-15 22:04:32668 }
669
Eric Orth70992982018-07-24 00:25:00670 Job* job() const { return job_; }
[email protected]b59ff372009-07-15 22:04:32671
[email protected]0f292de02012-02-01 22:28:20672 // NetLog for the source, passed in HostResolver::Resolve.
tfarina428341112016-09-22 13:38:20673 const NetLogWithSource& source_net_log() { return source_net_log_; }
[email protected]ee094b82010-08-24 15:55:51674
Eric Orth70992982018-07-24 00:25:00675 const HostPortPair& request_host() const { return request_host_; }
676
Eric Orth00fe5a62018-08-15 22:20:00677 const ResolveHostParameters& parameters() const { return parameters_; }
678
Eric Orth322af3e42018-08-20 18:12:59679 HostResolverFlags host_resolver_flags() const { return host_resolver_flags_; }
680
[email protected]5109c1952013-08-20 18:44:10681 RequestPriority priority() const { return priority_; }
juliatuttlec53b19a72016-05-05 13:51:31682 void set_priority(RequestPriority priority) { priority_ = priority; }
[email protected]5109c1952013-08-20 18:44:10683
Eric Orth70992982018-07-24 00:25:00684 bool complete() const { return complete_; }
685
686 base::TimeTicks request_time() const {
687 DCHECK(!request_time_.is_null());
688 return request_time_;
689 }
690 void set_request_time(base::TimeTicks request_time) {
691 DCHECK(request_time_.is_null());
692 DCHECK(!request_time.is_null());
693 request_time_ = request_time;
694 }
[email protected]51b9a6b2012-06-25 21:50:29695
[email protected]b59ff372009-07-15 22:04:32696 private:
tfarina428341112016-09-22 13:38:20697 const NetLogWithSource source_net_log_;
[email protected]54e13772009-08-14 03:01:09698
Eric Orth70992982018-07-24 00:25:00699 const HostPortPair request_host_;
Eric Orth00fe5a62018-08-15 22:20:00700 const ResolveHostParameters parameters_;
Eric Orth322af3e42018-08-20 18:12:59701 const HostResolverFlags host_resolver_flags_;
[email protected]5109c1952013-08-20 18:44:10702
juliatuttlec53b19a72016-05-05 13:51:31703 RequestPriority priority_;
[email protected]b59ff372009-07-15 22:04:32704
[email protected]0f292de02012-02-01 22:28:20705 // The resolve job that this request is dependent on.
[email protected]b59ff372009-07-15 22:04:32706 Job* job_;
Eric Orth70992982018-07-24 00:25:00707 base::WeakPtr<HostResolverImpl> resolver_;
[email protected]b59ff372009-07-15 22:04:32708
709 // The user's callback to invoke when the request completes.
Bence Béky0f26a5812018-06-13 03:18:40710 CompletionOnceCallback callback_;
[email protected]b59ff372009-07-15 22:04:32711
Eric Orth70992982018-07-24 00:25:00712 bool complete_;
Matt Menkec35d1632018-11-29 12:43:49713 base::Optional<HostCache::Entry> results_;
[email protected]b59ff372009-07-15 22:04:32714
Eric Orth70992982018-07-24 00:25:00715 base::TimeTicks request_time_;
[email protected]51b9a6b2012-06-25 21:50:29716
maksim.sisov31452af2016-07-27 06:38:10717 DISALLOW_COPY_AND_ASSIGN(RequestImpl);
[email protected]b59ff372009-07-15 22:04:32718};
719
Eric Orth70992982018-07-24 00:25:00720// Wraps a RequestImpl to implement Request objects from the legacy Resolve()
721// API. The wrapped request must not yet have been started.
722//
723// TODO(crbug.com/821021): Delete this class once all usage has been
724// converted to the new CreateRequest() API.
725class HostResolverImpl::LegacyRequestImpl : public HostResolver::Request {
726 public:
727 explicit LegacyRequestImpl(std::unique_ptr<RequestImpl> inner_request)
728 : inner_request_(std::move(inner_request)) {
729 DCHECK(!inner_request_->job());
730 DCHECK(!inner_request_->complete());
731 }
732
733 ~LegacyRequestImpl() override {}
734
735 void ChangeRequestPriority(RequestPriority priority) override {
736 inner_request_->ChangeRequestPriority(priority);
737 }
738
739 int Start() {
740 return inner_request_->Start(base::BindOnce(
741 &LegacyRequestImpl::LegacyApiCallback, base::Unretained(this)));
742 }
743
744 // Do not call to assign the callback until we are running an async job (after
745 // Start() returns ERR_IO_PENDING) and before completion. Until then, the
746 // legacy HostResolverImpl::Resolve() needs to hang onto |callback| to ensure
747 // it stays alive for the duration of the method call, as some callers may be
748 // binding objects, eg the AddressList, with the callback.
749 void AssignCallback(CompletionOnceCallback callback,
750 AddressList* addresses_result_ptr) {
751 DCHECK(callback);
752 DCHECK(addresses_result_ptr);
753 DCHECK(inner_request_->job());
754 DCHECK(!inner_request_->complete());
755
756 callback_ = std::move(callback);
757 addresses_result_ptr_ = addresses_result_ptr;
758 }
759
760 const RequestImpl& inner_request() const { return *inner_request_; }
761
762 private:
763 // Result callback to bridge results handled entirely via ResolveHostRequest
764 // to legacy API styles where AddressList was a separate method out parameter.
765 void LegacyApiCallback(int error) {
766 // Must call AssignCallback() before async results.
767 DCHECK(callback_);
768
Eric Orthb30bc172018-08-17 21:09:57769 if (error == OK && !inner_request_->parameters().is_speculative) {
Eric Orth70992982018-07-24 00:25:00770 // Legacy API does not allow non-address results (eg TXT), so AddressList
771 // is always expected to be present on OK.
772 DCHECK(inner_request_->GetAddressResults());
773 *addresses_result_ptr_ = inner_request_->GetAddressResults().value();
774 }
775 addresses_result_ptr_ = nullptr;
776 std::move(callback_).Run(error);
777 }
778
779 const std::unique_ptr<RequestImpl> inner_request_;
780
781 CompletionOnceCallback callback_;
782 // This is a caller-provided pointer and should not be used once |callback_|
783 // is invoked.
784 AddressList* addresses_result_ptr_;
785
786 DISALLOW_COPY_AND_ASSIGN(LegacyRequestImpl);
787};
788
[email protected]1e9bbd22010-10-15 16:42:45789//------------------------------------------------------------------------------
790
Francois Doraya2d01ba2017-09-25 19:17:40791// Calls HostResolverProc in TaskScheduler. Performs retries if necessary.
[email protected]0f292de02012-02-01 22:28:20792//
Miriam Gershenson02592182018-03-22 17:42:37793// In non-test code, the HostResolverProc is always SystemHostResolverProc,
794// which calls a platform API that implements host resolution.
795//
[email protected]0f292de02012-02-01 22:28:20796// Whenever we try to resolve the host, we post a delayed task to check if host
797// resolution (OnLookupComplete) is completed or not. If the original attempt
798// hasn't completed, then we start another attempt for host resolution. We take
799// the results from the first attempt that finishes and ignore the results from
800// all other attempts.
801//
802// TODO(szym): Move to separate source file for testing and mocking.
803//
Eric Orth9a037562018-07-03 21:24:38804class HostResolverImpl::ProcTask {
[email protected]b59ff372009-07-15 22:04:32805 public:
Eric Orth9a037562018-07-03 21:24:38806 typedef base::OnceCallback<void(int net_error, const AddressList& addr_list)>
807 Callback;
[email protected]b59ff372009-07-15 22:04:32808
[email protected]0f292de02012-02-01 22:28:20809 ProcTask(const Key& key,
810 const ProcTaskParams& params,
Eric Orth9a037562018-07-03 21:24:38811 Callback callback,
Miriam Gershensone42adb22017-10-16 16:19:38812 scoped_refptr<base::TaskRunner> proc_task_runner,
Misha Efimovb99e7da2018-05-30 16:59:02813 const NetLogWithSource& job_net_log,
814 const base::TickClock* tick_clock)
[email protected]0f292de02012-02-01 22:28:20815 : key_(key),
816 params_(params),
Eric Orth9a037562018-07-03 21:24:38817 callback_(std::move(callback)),
mmenke91c17162016-06-02 16:03:23818 network_task_runner_(base::ThreadTaskRunnerHandle::Get()),
Miriam Gershensone42adb22017-10-16 16:19:38819 proc_task_runner_(std::move(proc_task_runner)),
[email protected]0f292de02012-02-01 22:28:20820 attempt_number_(0),
Misha Efimovb99e7da2018-05-30 16:59:02821 net_log_(job_net_log),
Eric Orth9a037562018-07-03 21:24:38822 tick_clock_(tick_clock),
823 weak_ptr_factory_(this) {
Eric Orth192e3bb2018-11-14 19:30:32824 // ProcTask only supports resolving addresses.
825 DCHECK(IsAddressType(key_.dns_query_type));
826
Eric Orth9a037562018-07-03 21:24:38827 DCHECK(callback_);
[email protected]90499482013-06-01 00:39:50828 if (!params_.resolver_proc.get())
[email protected]0f292de02012-02-01 22:28:20829 params_.resolver_proc = HostResolverProc::GetDefault();
830 // If default is unset, use the system proc.
[email protected]90499482013-06-01 00:39:50831 if (!params_.resolver_proc.get())
[email protected]1ee9afa12013-04-16 14:18:06832 params_.resolver_proc = new SystemHostResolverProc();
[email protected]b59ff372009-07-15 22:04:32833 }
834
Eric Orth9a037562018-07-03 21:24:38835 // Cancels this ProcTask. Any outstanding resolve attempts running on worker
836 // thread will continue running, but they will post back to the network thread
837 // before checking their WeakPtrs to find that this task is cancelled.
838 ~ProcTask() {
839 DCHECK(network_task_runner_->BelongsToCurrentThread());
840
841 // If this is cancellation, log the EndEvent (otherwise this was logged in
842 // OnLookupComplete()).
843 if (!was_completed())
844 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_PROC_TASK);
845 }
846
[email protected]b59ff372009-07-15 22:04:32847 void Start() {
mmenke91c17162016-06-02 16:03:23848 DCHECK(network_task_runner_->BelongsToCurrentThread());
Eric Orth9a037562018-07-03 21:24:38849 DCHECK(!was_completed());
mikecirone8b85c432016-09-08 19:11:00850 net_log_.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_PROC_TASK);
[email protected]189163e2011-05-11 01:48:54851 StartLookupAttempt();
852 }
[email protected]252b699b2010-02-05 21:38:06853
Eric Orth9a037562018-07-03 21:24:38854 bool was_completed() const {
mmenke91c17162016-06-02 16:03:23855 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20856 return callback_.is_null();
857 }
858
[email protected]0f292de02012-02-01 22:28:20859 private:
Eric Orth9a037562018-07-03 21:24:38860 using AttemptCompletionCallback = base::OnceCallback<
861 void(const AddressList& results, int error, const int os_error)>;
[email protected]a9813302012-04-28 09:29:28862
[email protected]189163e2011-05-11 01:48:54863 void StartLookupAttempt() {
mmenke91c17162016-06-02 16:03:23864 DCHECK(network_task_runner_->BelongsToCurrentThread());
Eric Orth9a037562018-07-03 21:24:38865 DCHECK(!was_completed());
Misha Efimovb99e7da2018-05-30 16:59:02866 base::TimeTicks start_time = tick_clock_->NowTicks();
[email protected]189163e2011-05-11 01:48:54867 ++attempt_number_;
868 // Dispatch the lookup attempt to a worker thread.
Eric Orth9a037562018-07-03 21:24:38869 AttemptCompletionCallback completion_callback = base::BindOnce(
870 &ProcTask::OnLookupAttemptComplete, weak_ptr_factory_.GetWeakPtr(),
871 start_time, attempt_number_, tick_clock_);
Miriam Gershensone42adb22017-10-16 16:19:38872 proc_task_runner_->PostTask(
Francois Doraya2d01ba2017-09-25 19:17:40873 FROM_HERE,
Eric Orth9a037562018-07-03 21:24:38874 base::BindOnce(&ProcTask::DoLookup, key_, params_.resolver_proc,
875 network_task_runner_, std::move(completion_callback)));
[email protected]13024882011-05-18 23:19:16876
mikecirone8b85c432016-09-08 19:11:00877 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_ATTEMPT_STARTED,
tfarina5e24b242015-10-27 13:11:28878 NetLog::IntCallback("attempt_number", attempt_number_));
[email protected]13024882011-05-18 23:19:16879
mmenke91c17162016-06-02 16:03:23880 // If the results aren't received within a given time, RetryIfNotComplete
881 // will start a new attempt if none of the outstanding attempts have
882 // completed yet.
Eric Orth9a037562018-07-03 21:24:38883 // Use a WeakPtr to avoid keeping the ProcTask alive after completion or
884 // cancellation.
[email protected]0f292de02012-02-01 22:28:20885 if (attempt_number_ <= params_.max_retry_attempts) {
mmenke91c17162016-06-02 16:03:23886 network_task_runner_->PostDelayedTask(
Eric Orth9a037562018-07-03 21:24:38887 FROM_HERE,
888 base::BindOnce(&ProcTask::StartLookupAttempt,
889 weak_ptr_factory_.GetWeakPtr()),
890 params_.unresponsive_delay *
891 std::pow(params_.retry_factor, attempt_number_ - 1));
[email protected]06ef6d92011-05-19 04:24:58892 }
[email protected]b59ff372009-07-15 22:04:32893 }
894
Francois Doraya2d01ba2017-09-25 19:17:40895 // WARNING: This code runs in TaskScheduler with CONTINUE_ON_SHUTDOWN. The
896 // shutdown code cannot wait for it to finish, so this code must be very
897 // careful about using other objects (like MessageLoops, Singletons, etc).
Eric Orth9a037562018-07-03 21:24:38898 // During shutdown these objects may no longer exist.
899 static void DoLookup(
900 Key key,
901 scoped_refptr<HostResolverProc> resolver_proc,
902 scoped_refptr<base::SingleThreadTaskRunner> network_task_runner,
903 AttemptCompletionCallback completion_callback) {
[email protected]189163e2011-05-11 01:48:54904 AddressList results;
905 int os_error = 0;
Eric Orth192e3bb2018-11-14 19:30:32906 int error = resolver_proc->Resolve(
907 key.hostname, DnsQueryTypeToAddressFamily(key.dns_query_type),
908 key.host_resolver_flags, &results, &os_error);
[email protected]b59ff372009-07-15 22:04:32909
Eric Orth9a037562018-07-03 21:24:38910 network_task_runner->PostTask(
911 FROM_HERE, base::BindOnce(std::move(completion_callback), results,
912 error, os_error));
[email protected]189163e2011-05-11 01:48:54913 }
914
Eric Orth9a037562018-07-03 21:24:38915 // Callback for when DoLookup() completes (runs on task runner thread). Now
916 // that we're back in the network thread, checks that |proc_task| is still
917 // valid, and if so, passes back to the object.
918 static void OnLookupAttemptComplete(base::WeakPtr<ProcTask> proc_task,
919 const base::TimeTicks& start_time,
920 const uint32_t attempt_number,
921 const base::TickClock* tick_clock,
922 const AddressList& results,
923 int error,
924 const int os_error) {
Alexandr Ilin33126632018-11-14 14:48:17925 TRACE_EVENT0(NetTracingCategory(), "ProcTask::OnLookupComplete");
Eric Orth9a037562018-07-03 21:24:38926
[email protected]49b70b222013-05-07 21:24:23927 // If results are empty, we should return an error.
928 bool empty_list_on_ok = (error == OK && results.empty());
[email protected]49b70b222013-05-07 21:24:23929 if (empty_list_on_ok)
930 error = ERR_NAME_NOT_RESOLVED;
[email protected]189163e2011-05-11 01:48:54931
[email protected]2d3b7762010-10-09 00:35:47932 // Ideally the following code would be part of host_resolver_proc.cc,
[email protected]b3601bc22012-02-21 21:23:20933 // however it isn't safe to call NetworkChangeNotifier from worker threads.
mmenke91c17162016-06-02 16:03:23934 // So do it here on the IO thread instead.
[email protected]189163e2011-05-11 01:48:54935 if (error != OK && NetworkChangeNotifier::IsOffline())
936 error = ERR_INTERNET_DISCONNECTED;
[email protected]2d3b7762010-10-09 00:35:47937
Paul Jensenb7352f92018-11-08 00:02:49938 if (!proc_task)
Luciano Pachecob4426082018-07-02 08:04:18939 return;
Eric Orth9a037562018-07-03 21:24:38940
941 proc_task->OnLookupComplete(results, start_time, attempt_number, error,
942 os_error);
943 }
944
945 void OnLookupComplete(const AddressList& results,
946 const base::TimeTicks& start_time,
947 const uint32_t attempt_number,
948 int error,
949 const int os_error) {
950 DCHECK(network_task_runner_->BelongsToCurrentThread());
951 DCHECK(!was_completed());
952
953 // Invalidate WeakPtrs to cancel handling of all outstanding lookup attempts
954 // and retries.
955 weak_ptr_factory_.InvalidateWeakPtrs();
956
Eric Orthcb8862f2018-06-27 18:08:35957 NetLogParametersCallback net_log_callback;
Eric Orth9a037562018-07-03 21:24:38958 NetLogParametersCallback attempt_net_log_callback;
[email protected]0f292de02012-02-01 22:28:20959 if (error != OK) {
Eric Orth70992982018-07-24 00:25:00960 net_log_callback = base::BindRepeating(&NetLogProcTaskFailedCallback, 0,
961 error, os_error);
962 attempt_net_log_callback = base::BindRepeating(
963 &NetLogProcTaskFailedCallback, attempt_number, error, os_error);
[email protected]ee094b82010-08-24 15:55:51964 } else {
Eric Orth9a037562018-07-03 21:24:38965 net_log_callback = results.CreateNetLogCallback();
966 attempt_net_log_callback =
967 NetLog::IntCallback("attempt_number", attempt_number);
[email protected]ee094b82010-08-24 15:55:51968 }
mikecirone8b85c432016-09-08 19:11:00969 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_PROC_TASK,
[email protected]cd565142012-06-12 16:21:45970 net_log_callback);
Eric Orth9a037562018-07-03 21:24:38971 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_ATTEMPT_FINISHED,
972 attempt_net_log_callback);
[email protected]ee094b82010-08-24 15:55:51973
Eric Orth9a037562018-07-03 21:24:38974 std::move(callback_).Run(error, results);
[email protected]b59ff372009-07-15 22:04:32975 }
976
[email protected]123ab1e32009-10-21 19:12:57977 Key key_;
[email protected]b59ff372009-07-15 22:04:32978
[email protected]0f292de02012-02-01 22:28:20979 // Holds an owning reference to the HostResolverProc that we are going to use.
[email protected]b59ff372009-07-15 22:04:32980 // This may not be the current resolver procedure by the time we call
981 // ResolveAddrInfo, but that's OK... we'll use it anyways, and the owning
982 // reference ensures that it remains valid until we are done.
[email protected]0f292de02012-02-01 22:28:20983 ProcTaskParams params_;
[email protected]b59ff372009-07-15 22:04:32984
[email protected]0f292de02012-02-01 22:28:20985 // The listener to the results of this ProcTask.
986 Callback callback_;
987
mmenke91c17162016-06-02 16:03:23988 // Used to post events onto the network thread.
989 scoped_refptr<base::SingleThreadTaskRunner> network_task_runner_;
Miriam Gershensone42adb22017-10-16 16:19:38990 // Used to post blocking HostResolverProc tasks.
991 scoped_refptr<base::TaskRunner> proc_task_runner_;
[email protected]189163e2011-05-11 01:48:54992
993 // Keeps track of the number of attempts we have made so far to resolve the
994 // host. Whenever we start an attempt to resolve the host, we increase this
995 // number.
Avi Drissman13fc8932015-12-20 04:40:46996 uint32_t attempt_number_;
[email protected]189163e2011-05-11 01:48:54997
tfarina428341112016-09-22 13:38:20998 NetLogWithSource net_log_;
[email protected]ee094b82010-08-24 15:55:51999
Misha Efimovb99e7da2018-05-30 16:59:021000 const base::TickClock* tick_clock_;
1001
Eric Orth9a037562018-07-03 21:24:381002 // Used to loop back from the blocking lookup attempt tasks as well as from
1003 // delayed retry tasks. Invalidate WeakPtrs on completion and cancellation to
1004 // cancel handling of such posted tasks.
1005 base::WeakPtrFactory<ProcTask> weak_ptr_factory_;
1006
[email protected]0f292de02012-02-01 22:28:201007 DISALLOW_COPY_AND_ASSIGN(ProcTask);
[email protected]b59ff372009-07-15 22:04:321008};
1009
1010//-----------------------------------------------------------------------------
1011
Miriam Gershenson02592182018-03-22 17:42:371012// Resolves the hostname using DnsTransaction, which is a full implementation of
1013// a DNS stub resolver. One DnsTransaction is created for each resolution
1014// needed, which for AF_UNSPEC resolutions includes both A and AAAA. The
1015// transactions are scheduled separately and started separately.
1016//
[email protected]b3601bc22012-02-21 21:23:201017// TODO(szym): This could be moved to separate source file as well.
[email protected]0adcb2b2012-08-15 21:30:461018class HostResolverImpl::DnsTask : public base::SupportsWeakPtr<DnsTask> {
[email protected]b3601bc22012-02-21 21:23:201019 public:
[email protected]daae1322013-09-05 18:26:501020 class Delegate {
1021 public:
1022 virtual void OnDnsTaskComplete(base::TimeTicks start_time,
Matt Menkec35d1632018-11-29 12:43:491023 const HostCache::Entry& results) = 0;
[email protected]daae1322013-09-05 18:26:501024
1025 // Called when the first of two jobs succeeds. If the first completed
1026 // transaction fails, this is not called. Also not called when the DnsTask
1027 // only needs to run one transaction.
1028 virtual void OnFirstDnsTransactionComplete() = 0;
1029
Brad Lassey786929ad2018-02-21 20:54:271030 virtual URLRequestContext* url_request_context() = 0;
1031 virtual RequestPriority priority() const = 0;
1032
[email protected]daae1322013-09-05 18:26:501033 protected:
Chris Watkins68b15032017-12-01 03:07:131034 Delegate() = default;
1035 virtual ~Delegate() = default;
[email protected]daae1322013-09-05 18:26:501036 };
[email protected]b3601bc22012-02-21 21:23:201037
[email protected]0adcb2b2012-08-15 21:30:461038 DnsTask(DnsClient* client,
[email protected]b3601bc22012-02-21 21:23:201039 const Key& key,
Eric Orth60931742018-11-05 23:40:571040 bool allow_fallback_resolution,
[email protected]daae1322013-09-05 18:26:501041 Delegate* delegate,
Misha Efimovb99e7da2018-05-30 16:59:021042 const NetLogWithSource& job_net_log,
1043 const base::TickClock* tick_clock)
[email protected]0adcb2b2012-08-15 21:30:461044 : client_(client),
[email protected]daae1322013-09-05 18:26:501045 key_(key),
Eric Orth60931742018-11-05 23:40:571046 allow_fallback_resolution_(allow_fallback_resolution),
[email protected]daae1322013-09-05 18:26:501047 delegate_(delegate),
1048 net_log_(job_net_log),
1049 num_completed_transactions_(0),
Misha Efimovb99e7da2018-05-30 16:59:021050 tick_clock_(tick_clock),
1051 task_start_time_(tick_clock_->NowTicks()) {
[email protected]0adcb2b2012-08-15 21:30:461052 DCHECK(client);
[email protected]daae1322013-09-05 18:26:501053 DCHECK(delegate_);
[email protected]1affed62013-08-21 03:24:501054 }
1055
Eric Orth60931742018-11-05 23:40:571056 bool allow_fallback_resolution() const { return allow_fallback_resolution_; }
1057
[email protected]daae1322013-09-05 18:26:501058 bool needs_two_transactions() const {
Eric Orth192e3bb2018-11-14 19:30:321059 return key_.dns_query_type == DnsQueryType::UNSPECIFIED;
[email protected]daae1322013-09-05 18:26:501060 }
1061
1062 bool needs_another_transaction() const {
Eric Orth192e3bb2018-11-14 19:30:321063 return needs_two_transactions() && !transaction2_;
[email protected]daae1322013-09-05 18:26:501064 }
1065
1066 void StartFirstTransaction() {
1067 DCHECK_EQ(0u, num_completed_transactions_);
Eric Orth192e3bb2018-11-14 19:30:321068 DCHECK(!transaction1_);
1069
mikecirone8b85c432016-09-08 19:11:001070 net_log_.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_DNS_TASK);
Eric Orth192e3bb2018-11-14 19:30:321071 if (key_.dns_query_type == DnsQueryType::UNSPECIFIED) {
1072 transaction1_ = CreateTransaction(DnsQueryType::A);
[email protected]daae1322013-09-05 18:26:501073 } else {
Eric Orth192e3bb2018-11-14 19:30:321074 transaction1_ = CreateTransaction(key_.dns_query_type);
[email protected]daae1322013-09-05 18:26:501075 }
Eric Orth192e3bb2018-11-14 19:30:321076 transaction1_->Start();
[email protected]daae1322013-09-05 18:26:501077 }
1078
1079 void StartSecondTransaction() {
Eric Orth192e3bb2018-11-14 19:30:321080 DCHECK(needs_another_transaction());
1081 transaction2_ = CreateTransaction(DnsQueryType::AAAA);
1082 transaction2_->Start();
[email protected]70c04ab2013-08-22 16:05:121083 }
1084
1085 private:
Eric Orth192e3bb2018-11-14 19:30:321086 std::unique_ptr<DnsTransaction> CreateTransaction(
1087 DnsQueryType dns_query_type) {
1088 DCHECK_NE(DnsQueryType::UNSPECIFIED, dns_query_type);
Brad Lassey786929ad2018-02-21 20:54:271089 std::unique_ptr<DnsTransaction> trans =
1090 client_->GetTransactionFactory()->CreateTransaction(
Eric Orth192e3bb2018-11-14 19:30:321091 key_.hostname, DnsQueryTypeToQtype(dns_query_type),
Brad Lasseydba0a84b2018-02-23 22:18:531092 base::BindOnce(&DnsTask::OnTransactionComplete,
Matt Menkec35d1632018-11-29 12:43:491093 base::Unretained(this), tick_clock_->NowTicks(),
1094 dns_query_type),
Brad Lassey786929ad2018-02-21 20:54:271095 net_log_);
1096 trans->SetRequestContext(delegate_->url_request_context());
1097 trans->SetRequestPriority(delegate_->priority());
1098 return trans;
[email protected]daae1322013-09-05 18:26:501099 }
1100
1101 void OnTransactionComplete(const base::TimeTicks& start_time,
Matt Menkec35d1632018-11-29 12:43:491102 DnsQueryType dns_query_type,
[email protected]1def74c2012-03-22 20:07:001103 DnsTransaction* transaction,
[email protected]b3601bc22012-02-21 21:23:201104 int net_error,
1105 const DnsResponse* response) {
[email protected]add76532012-03-30 14:47:471106 DCHECK(transaction);
Brad Lassey2e8f185d2018-05-21 22:25:211107 if (net_error != OK && !(net_error == ERR_NAME_NOT_RESOLVED && response &&
1108 response->IsValid())) {
Matt Menkec35d1632018-11-29 12:43:491109 OnFailure(net_error, DnsResponse::DNS_PARSE_OK, base::nullopt);
[email protected]0adcb2b2012-08-15 21:30:461110 return;
[email protected]6c411902012-08-14 22:36:361111 }
[email protected]0adcb2b2012-08-15 21:30:461112
Matt Menkec35d1632018-11-29 12:43:491113 DnsResponse::Result parse_result = DnsResponse::DNS_PARSE_RESULT_MAX;
1114 HostCache::Entry results(ERR_FAILED, HostCache::Entry::SOURCE_UNKNOWN);
1115 switch (dns_query_type) {
1116 case DnsQueryType::UNSPECIFIED:
1117 // Should create two separate transactions with specified type.
1118 NOTREACHED();
1119 break;
1120 case DnsQueryType::A:
1121 case DnsQueryType::AAAA:
1122 parse_result = ParseAddressDnsResponse(response, &results);
1123 break;
1124 }
1125 DCHECK_LT(parse_result, DnsResponse::DNS_PARSE_RESULT_MAX);
1126
1127 if (results.error() != OK && results.error() != ERR_NAME_NOT_RESOLVED) {
1128 OnFailure(results.error(), parse_result, results.GetOptionalTtl());
[email protected]0adcb2b2012-08-15 21:30:461129 return;
1130 }
1131
Matt Menkec35d1632018-11-29 12:43:491132 // Merge results with saved results from previous transactions.
1133 if (saved_results_) {
1134 DCHECK(needs_two_transactions());
1135 DCHECK_GE(1u, num_completed_transactions_);
1136
1137 switch (dns_query_type) {
1138 case DnsQueryType::A:
1139 // A results in |results| go after other results in |saved_results_|,
1140 // so merge |saved_results_| to the front.
1141 results = HostCache::Entry::MergeEntries(
1142 std::move(saved_results_).value(), std::move(results));
1143 break;
1144 case DnsQueryType::AAAA:
1145 // AAAA results in |results| go before other results in
1146 // |saved_results_|, so merge |saved_results_| to the back.
1147 results = HostCache::Entry::MergeEntries(
1148 std::move(results), std::move(saved_results_).value());
1149 break;
1150 default:
1151 // Only expect address query types with multiple transactions.
1152 NOTREACHED();
1153 }
1154 }
1155
1156 // If not all transactions are complete, the task cannot yet be completed
1157 // and the results so far must be saved to merge with additional results.
Giovanni Ortuño Urquidie369ab32018-11-29 05:23:261158 ++num_completed_transactions_;
[email protected]daae1322013-09-05 18:26:501159 if (needs_two_transactions() && num_completed_transactions_ == 1) {
Matt Menkec35d1632018-11-29 12:43:491160 saved_results_ = std::move(results);
[email protected]daae1322013-09-05 18:26:501161 // No need to repeat the suffix search.
1162 key_.hostname = transaction->GetHostname();
1163 delegate_->OnFirstDnsTransactionComplete();
1164 return;
1165 }
1166
Giovanni Ortuño Urquidie369ab32018-11-29 05:23:261167 // If there are multiple addresses, and at least one is IPv6, need to sort
1168 // them. Note that IPv6 addresses are always put before IPv4 ones, so it's
1169 // sufficient to just check the family of the first address.
Matt Menkec35d1632018-11-29 12:43:491170 if (results.addresses() && results.addresses().value().size() > 1 &&
1171 results.addresses().value()[0].GetFamily() == ADDRESS_FAMILY_IPV6) {
Giovanni Ortuño Urquidie369ab32018-11-29 05:23:261172 // Sort addresses if needed. Sort could complete synchronously.
1173 client_->GetAddressSorter()->Sort(
Matt Menkec35d1632018-11-29 12:43:491174 results.addresses().value(),
1175 base::BindOnce(&DnsTask::OnSortComplete, AsWeakPtr(),
1176 tick_clock_->NowTicks(), std::move(results)));
1177 return;
Eric Orth07ee5f02018-11-29 00:42:031178 }
Matt Menkec35d1632018-11-29 12:43:491179
1180 OnSuccess(results);
Eric Orth07ee5f02018-11-29 00:42:031181 }
1182
Matt Menkec35d1632018-11-29 12:43:491183 DnsResponse::Result ParseAddressDnsResponse(const DnsResponse* response,
1184 HostCache::Entry* out_results) {
1185 AddressList addresses;
1186 base::TimeDelta ttl;
1187 DnsResponse::Result parse_result =
1188 response->ParseToAddressList(&addresses, &ttl);
Matt Menkec35d1632018-11-29 12:43:491189
1190 if (parse_result != DnsResponse::DNS_PARSE_OK) {
1191 *out_results = HostCache::Entry(ERR_DNS_MALFORMED_RESPONSE, AddressList(),
1192 HostCache::Entry::SOURCE_DNS);
1193 } else if (addresses.empty()) {
1194 *out_results = HostCache::Entry(ERR_NAME_NOT_RESOLVED, AddressList(),
1195 HostCache::Entry::SOURCE_DNS, ttl);
1196 } else {
1197 *out_results = HostCache::Entry(OK, std::move(addresses),
1198 HostCache::Entry::SOURCE_DNS, ttl);
1199 }
1200 return parse_result;
1201 }
1202
1203 void OnSortComplete(base::TimeTicks sort_start_time,
1204 HostCache::Entry results,
[email protected]0adcb2b2012-08-15 21:30:461205 bool success,
1206 const AddressList& addr_list) {
Matt Menkec35d1632018-11-29 12:43:491207 results.set_addresses(addr_list);
1208
[email protected]0adcb2b2012-08-15 21:30:461209 if (!success) {
Matt Menkec35d1632018-11-29 12:43:491210 OnFailure(ERR_DNS_SORT_ERROR, DnsResponse::DNS_PARSE_OK,
1211 results.GetOptionalTtl());
[email protected]0adcb2b2012-08-15 21:30:461212 return;
1213 }
1214
[email protected]0adcb2b2012-08-15 21:30:461215 // AddressSorter prunes unusable destinations.
Matt Menkec35d1632018-11-29 12:43:491216 if (addr_list.empty() &&
1217 results.text_records().value_or(std::vector<std::string>()).empty() &&
1218 results.hostnames().value_or(std::vector<HostPortPair>()).empty()) {
[email protected]0adcb2b2012-08-15 21:30:461219 LOG(WARNING) << "Address list empty after RFC3484 sort";
Matt Menkec35d1632018-11-29 12:43:491220 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK,
1221 results.GetOptionalTtl());
[email protected]0adcb2b2012-08-15 21:30:461222 return;
1223 }
1224
Matt Menkec35d1632018-11-29 12:43:491225 OnSuccess(results);
[email protected]0adcb2b2012-08-15 21:30:461226 }
1227
Matt Menkec35d1632018-11-29 12:43:491228 void OnFailure(int net_error,
1229 DnsResponse::Result parse_result,
1230 base::Optional<base::TimeDelta> ttl) {
[email protected]0adcb2b2012-08-15 21:30:461231 DCHECK_NE(OK, net_error);
Matt Menkec35d1632018-11-29 12:43:491232
1233 HostCache::Entry results(net_error, HostCache::Entry::SOURCE_UNKNOWN);
1234
1235 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_DNS_TASK,
1236 base::Bind(&NetLogDnsTaskFailedCallback, results.error(),
1237 parse_result, results.CreateNetLogCallback()));
1238
1239 // If we have a TTL from a previously completed transaction, use it.
1240 base::TimeDelta previous_transaction_ttl;
1241 if (saved_results_ && saved_results_.value().has_ttl() &&
1242 saved_results_.value().ttl() <
1243 base::TimeDelta::FromSeconds(
1244 std::numeric_limits<uint32_t>::max())) {
1245 previous_transaction_ttl = saved_results_.value().ttl();
1246 if (ttl)
1247 results.set_ttl(std::min(ttl.value(), previous_transaction_ttl));
1248 else
1249 results.set_ttl(previous_transaction_ttl);
1250 } else if (ttl) {
1251 results.set_ttl(ttl.value());
1252 }
1253
1254 delegate_->OnDnsTaskComplete(task_start_time_, results);
[email protected]b3601bc22012-02-21 21:23:201255 }
1256
Matt Menkec35d1632018-11-29 12:43:491257 void OnSuccess(const HostCache::Entry& results) {
mikecirone8b85c432016-09-08 19:11:001258 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_DNS_TASK,
Matt Menkec35d1632018-11-29 12:43:491259 results.CreateNetLogCallback());
1260 delegate_->OnDnsTaskComplete(task_start_time_, results);
[email protected]0adcb2b2012-08-15 21:30:461261 }
1262
1263 DnsClient* client_;
[email protected]daae1322013-09-05 18:26:501264 Key key_;
1265
Eric Orth60931742018-11-05 23:40:571266 // Whether resolution may fallback to other task types (e.g. ProcTask) on
1267 // failure of this task.
1268 bool allow_fallback_resolution_;
1269
[email protected]b3601bc22012-02-21 21:23:201270 // The listener to the results of this DnsTask.
[email protected]daae1322013-09-05 18:26:501271 Delegate* delegate_;
tfarina428341112016-09-22 13:38:201272 const NetLogWithSource net_log_;
[email protected]b3601bc22012-02-21 21:23:201273
Eric Orth192e3bb2018-11-14 19:30:321274 std::unique_ptr<DnsTransaction> transaction1_;
1275 std::unique_ptr<DnsTransaction> transaction2_;
[email protected]0adcb2b2012-08-15 21:30:461276
[email protected]daae1322013-09-05 18:26:501277 unsigned num_completed_transactions_;
1278
Matt Menkec35d1632018-11-29 12:43:491279 // Result from previously completed transactions. Only set if a transaction
1280 // has completed while others are still in progress.
1281 base::Optional<HostCache::Entry> saved_results_;
[email protected]daae1322013-09-05 18:26:501282
Misha Efimovb99e7da2018-05-30 16:59:021283 const base::TickClock* tick_clock_;
[email protected]daae1322013-09-05 18:26:501284 base::TimeTicks task_start_time_;
[email protected]0adcb2b2012-08-15 21:30:461285
1286 DISALLOW_COPY_AND_ASSIGN(DnsTask);
[email protected]b3601bc22012-02-21 21:23:201287};
1288
1289//-----------------------------------------------------------------------------
1290
[email protected]0f292de02012-02-01 22:28:201291// Aggregates all Requests for the same Key. Dispatched via PriorityDispatch.
[email protected]daae1322013-09-05 18:26:501292class HostResolverImpl::Job : public PrioritizedDispatcher::Job,
1293 public HostResolverImpl::DnsTask::Delegate {
[email protected]68ad3ee2010-01-30 03:45:391294 public:
[email protected]0f292de02012-02-01 22:28:201295 // Creates new job for |key| where |request_net_log| is bound to the
[email protected]16ee26d2012-03-08 03:34:351296 // request that spawned it.
[email protected]12faa4c2012-11-06 04:44:181297 Job(const base::WeakPtr<HostResolverImpl>& resolver,
[email protected]0f292de02012-02-01 22:28:201298 const Key& key,
[email protected]8c98d002012-07-18 19:02:271299 RequestPriority priority,
Miriam Gershensone42adb22017-10-16 16:19:381300 scoped_refptr<base::TaskRunner> proc_task_runner,
Misha Efimovb99e7da2018-05-30 16:59:021301 const NetLogWithSource& source_net_log,
1302 const base::TickClock* tick_clock)
[email protected]12faa4c2012-11-06 04:44:181303 : resolver_(resolver),
[email protected]0f292de02012-02-01 22:28:201304 key_(key),
[email protected]8c98d002012-07-18 19:02:271305 priority_tracker_(priority),
Miriam Gershensone42adb22017-10-16 16:19:381306 proc_task_runner_(std::move(proc_task_runner)),
[email protected]0f292de02012-02-01 22:28:201307 had_non_speculative_request_(false),
[email protected]daae1322013-09-05 18:26:501308 num_occupied_job_slots_(0),
[email protected]1d932852012-06-19 19:40:331309 dns_task_error_(OK),
Misha Efimovb99e7da2018-05-30 16:59:021310 tick_clock_(tick_clock),
tfarina428341112016-09-22 13:38:201311 net_log_(
1312 NetLogWithSource::Make(source_net_log.net_log(),
Eric Orth60931742018-11-05 23:40:571313 NetLogSourceType::HOST_RESOLVER_IMPL_JOB)),
1314 weak_ptr_factory_(this) {
mikecirone8b85c432016-09-08 19:11:001315 source_net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_CREATE_JOB);
[email protected]0f292de02012-02-01 22:28:201316
mikecirone8b85c432016-09-08 19:11:001317 net_log_.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
1318 base::Bind(&NetLogJobCreationCallback,
1319 source_net_log.source(), &key_.hostname));
[email protected]68ad3ee2010-01-30 03:45:391320 }
1321
dchengb03027d2014-10-21 12:00:201322 ~Job() override {
[email protected]b3601bc22012-02-21 21:23:201323 if (is_running()) {
1324 // |resolver_| was destroyed with this Job still in flight.
1325 // Clean-up, record in the log, but don't run any callbacks.
Eric Orth9a037562018-07-03 21:24:381326 proc_task_ = nullptr;
[email protected]16ee26d2012-03-08 03:34:351327 // Clean up now for nice NetLog.
[email protected]daae1322013-09-05 18:26:501328 KillDnsTask();
mikecirone8b85c432016-09-08 19:11:001329 net_log_.EndEventWithNetErrorCode(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
[email protected]b3601bc22012-02-21 21:23:201330 ERR_ABORTED);
1331 } else if (is_queued()) {
[email protected]57a48d32012-03-03 00:04:551332 // |resolver_| was destroyed without running this Job.
[email protected]16ee26d2012-03-08 03:34:351333 // TODO(szym): is there any benefit in having this distinction?
mikecirone8b85c432016-09-08 19:11:001334 net_log_.AddEvent(NetLogEventType::CANCELLED);
1335 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB);
[email protected]68ad3ee2010-01-30 03:45:391336 }
[email protected]b3601bc22012-02-21 21:23:201337 // else CompleteRequests logged EndEvent.
David Benjamina5677192018-04-23 23:25:421338 while (!requests_.empty()) {
maksim.sisov31452af2016-07-27 06:38:101339 // Log any remaining Requests as cancelled.
David Benjamina5677192018-04-23 23:25:421340 RequestImpl* req = requests_.head()->value();
1341 req->RemoveFromList();
1342 DCHECK_EQ(this, req->job());
Eric Orth70992982018-07-24 00:25:001343 LogCancelRequest(req->source_net_log());
David Benjamina5677192018-04-23 23:25:421344 req->OnJobCancelled(this);
[email protected]b3601bc22012-02-21 21:23:201345 }
[email protected]68ad3ee2010-01-30 03:45:391346 }
1347
[email protected]daae1322013-09-05 18:26:501348 // Add this job to the dispatcher. If "at_head" is true, adds at the front
1349 // of the queue.
1350 void Schedule(bool at_head) {
1351 DCHECK(!is_queued());
1352 PrioritizedDispatcher::Handle handle;
1353 if (!at_head) {
[email protected]106ccd2c2014-06-17 09:21:001354 handle = resolver_->dispatcher_->Add(this, priority());
[email protected]daae1322013-09-05 18:26:501355 } else {
[email protected]106ccd2c2014-06-17 09:21:001356 handle = resolver_->dispatcher_->AddAtHead(this, priority());
[email protected]daae1322013-09-05 18:26:501357 }
1358 // The dispatcher could have started |this| in the above call to Add, which
1359 // could have called Schedule again. In that case |handle| will be null,
1360 // but |handle_| may have been set by the other nested call to Schedule.
1361 if (!handle.is_null()) {
1362 DCHECK(handle_.is_null());
1363 handle_ = handle;
1364 }
[email protected]16ee26d2012-03-08 03:34:351365 }
1366
maksim.sisov31452af2016-07-27 06:38:101367 void AddRequest(RequestImpl* request) {
Eric Orth70992982018-07-24 00:25:001368 DCHECK_EQ(key_.hostname, request->request_host().host());
1369
1370 request->AssignJob(this);
[email protected]0f292de02012-02-01 22:28:201371
maksim.sisov31452af2016-07-27 06:38:101372 priority_tracker_.Add(request->priority());
[email protected]0f292de02012-02-01 22:28:201373
maksim.sisov31452af2016-07-27 06:38:101374 request->source_net_log().AddEvent(
mikecirone8b85c432016-09-08 19:11:001375 NetLogEventType::HOST_RESOLVER_IMPL_JOB_ATTACH,
[email protected]cd565142012-06-12 16:21:451376 net_log_.source().ToEventParametersCallback());
[email protected]0f292de02012-02-01 22:28:201377
1378 net_log_.AddEvent(
mikecirone8b85c432016-09-08 19:11:001379 NetLogEventType::HOST_RESOLVER_IMPL_JOB_REQUEST_ATTACH,
maksim.sisov31452af2016-07-27 06:38:101380 base::Bind(&NetLogJobAttachCallback, request->source_net_log().source(),
[email protected]cd565142012-06-12 16:21:451381 priority()));
[email protected]0f292de02012-02-01 22:28:201382
Eric Orthb30bc172018-08-17 21:09:571383 if (!request->parameters().is_speculative)
[email protected]0f292de02012-02-01 22:28:201384 had_non_speculative_request_ = true;
[email protected]b3601bc22012-02-21 21:23:201385
David Benjamina5677192018-04-23 23:25:421386 requests_.Append(request);
[email protected]b3601bc22012-02-21 21:23:201387
[email protected]51b9a6b2012-06-25 21:50:291388 UpdatePriority();
[email protected]68ad3ee2010-01-30 03:45:391389 }
1390
maksim.sisov31452af2016-07-27 06:38:101391 void ChangeRequestPriority(RequestImpl* req, RequestPriority priority) {
Eric Orth70992982018-07-24 00:25:001392 DCHECK_EQ(key_.hostname, req->request_host().host());
juliatuttlec53b19a72016-05-05 13:51:311393
1394 priority_tracker_.Remove(req->priority());
1395 req->set_priority(priority);
1396 priority_tracker_.Add(req->priority());
1397 UpdatePriority();
1398 }
1399
maksim.sisov31452af2016-07-27 06:38:101400 // Detach cancelled request. If it was the last active Request, also finishes
1401 // this Job.
1402 void CancelRequest(RequestImpl* request) {
Eric Orth70992982018-07-24 00:25:001403 DCHECK_EQ(key_.hostname, request->request_host().host());
maksim.sisov31452af2016-07-27 06:38:101404 DCHECK(!requests_.empty());
[email protected]16ee26d2012-03-08 03:34:351405
Eric Orth70992982018-07-24 00:25:001406 LogCancelRequest(request->source_net_log());
[email protected]16ee26d2012-03-08 03:34:351407
maksim.sisov31452af2016-07-27 06:38:101408 priority_tracker_.Remove(request->priority());
1409 net_log_.AddEvent(
mikecirone8b85c432016-09-08 19:11:001410 NetLogEventType::HOST_RESOLVER_IMPL_JOB_REQUEST_DETACH,
maksim.sisov31452af2016-07-27 06:38:101411 base::Bind(&NetLogJobAttachCallback, request->source_net_log().source(),
1412 priority()));
[email protected]b3601bc22012-02-21 21:23:201413
[email protected]16ee26d2012-03-08 03:34:351414 if (num_active_requests() > 0) {
[email protected]51b9a6b2012-06-25 21:50:291415 UpdatePriority();
David Benjamina5677192018-04-23 23:25:421416 request->RemoveFromList();
[email protected]16ee26d2012-03-08 03:34:351417 } else {
1418 // If we were called from a Request's callback within CompleteRequests,
1419 // that Request could not have been cancelled, so num_active_requests()
1420 // could not be 0. Therefore, we are not in CompleteRequests().
Matt Menkec35d1632018-11-29 12:43:491421 CompleteRequestsWithError(ERR_FAILED /* cancelled */);
[email protected]b3601bc22012-02-21 21:23:201422 }
[email protected]68ad3ee2010-01-30 03:45:391423 }
1424
[email protected]7af985a2012-12-14 22:40:421425 // Called from AbortAllInProgressJobs. Completes all requests and destroys
1426 // the job. This currently assumes the abort is due to a network change.
olli.raulaa21e9eb72015-12-17 08:18:111427 // TODO This should not delete |this|.
[email protected]0f292de02012-02-01 22:28:201428 void Abort() {
[email protected]0f292de02012-02-01 22:28:201429 DCHECK(is_running());
[email protected]7af985a2012-12-14 22:40:421430 CompleteRequestsWithError(ERR_NETWORK_CHANGED);
[email protected]b3601bc22012-02-21 21:23:201431 }
1432
Eric Orth60931742018-11-05 23:40:571433 // Gets a closure that will abort a DnsTask (see AbortDnsTask()) iff |this| is
1434 // still valid. Useful if aborting a list of Jobs as some may be cancelled
1435 // while aborting others.
1436 base::OnceClosure GetAbortDnsTaskClosure(int error, bool fallback_only) {
1437 return base::BindOnce(&Job::AbortDnsTask, weak_ptr_factory_.GetWeakPtr(),
1438 error, fallback_only);
1439 }
1440
1441 // If DnsTask present, abort it. Depending on task settings, either fall back
1442 // to ProcTask or abort the job entirely. Warning, aborting a job may cause
1443 // other jobs to be aborted, thus |jobs_| may be unpredictably changed by
1444 // calling this method.
1445 //
1446 // |error| is the net error that will be returned to requests if this method
1447 // results in completely aborting the job.
1448 void AbortDnsTask(int error, bool fallback_only) {
[email protected]f0f602bd2012-11-15 18:01:021449 if (dns_task_) {
Eric Orth60931742018-11-05 23:40:571450 if (dns_task_->allow_fallback_resolution()) {
1451 KillDnsTask();
1452 dns_task_error_ = OK;
1453 StartProcTask();
1454 } else if (!fallback_only) {
1455 CompleteRequestsWithError(error);
1456 }
[email protected]f0f602bd2012-11-15 18:01:021457 }
1458 }
1459
[email protected]16ee26d2012-03-08 03:34:351460 // Called by HostResolverImpl when this job is evicted due to queue overflow.
1461 // Completes all requests and destroys the job.
1462 void OnEvicted() {
1463 DCHECK(!is_running());
1464 DCHECK(is_queued());
1465 handle_.Reset();
1466
mikecirone8b85c432016-09-08 19:11:001467 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB_EVICTED);
[email protected]16ee26d2012-03-08 03:34:351468
1469 // This signals to CompleteRequests that this job never ran.
[email protected]1339a2a22012-10-17 08:39:431470 CompleteRequestsWithError(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
[email protected]16ee26d2012-03-08 03:34:351471 }
1472
[email protected]78eac2a2012-03-14 19:09:271473 // Attempts to serve the job from HOSTS. Returns true if succeeded and
1474 // this Job was destroyed.
1475 bool ServeFromHosts() {
1476 DCHECK_GT(num_active_requests(), 0u);
Matt Menkec35d1632018-11-29 12:43:491477 base::Optional<HostCache::Entry> results = resolver_->ServeFromHosts(key());
1478 if (results) {
[email protected]78eac2a2012-03-14 19:09:271479 // This will destroy the Job.
Matt Menkec35d1632018-11-29 12:43:491480 CompleteRequests(results.value(), base::TimeDelta(),
1481 true /* allow_cache */);
[email protected]78eac2a2012-03-14 19:09:271482 return true;
1483 }
1484 return false;
1485 }
1486
tanay.c6ddd5f6f2015-08-25 06:34:571487 const Key& key() const { return key_; }
[email protected]b4481b222012-03-16 17:13:111488
1489 bool is_queued() const {
1490 return !handle_.is_null();
1491 }
1492
1493 bool is_running() const {
Eric Orth9871aafa2018-10-02 19:59:181494 return is_dns_running() || is_mdns_running() || is_proc_running();
[email protected]b4481b222012-03-16 17:13:111495 }
1496
[email protected]16ee26d2012-03-08 03:34:351497 private:
[email protected]daae1322013-09-05 18:26:501498 void KillDnsTask() {
1499 if (dns_task_) {
1500 ReduceToOneJobSlot();
1501 dns_task_.reset();
1502 }
1503 }
1504
1505 // Reduce the number of job slots occupied and queued in the dispatcher
1506 // to one. If the second Job slot is queued in the dispatcher, cancels the
1507 // queued job. Otherwise, the second Job has been started by the
1508 // PrioritizedDispatcher, so signals it is complete.
1509 void ReduceToOneJobSlot() {
1510 DCHECK_GE(num_occupied_job_slots_, 1u);
1511 if (is_queued()) {
[email protected]106ccd2c2014-06-17 09:21:001512 resolver_->dispatcher_->Cancel(handle_);
[email protected]daae1322013-09-05 18:26:501513 handle_.Reset();
1514 } else if (num_occupied_job_slots_ > 1) {
[email protected]106ccd2c2014-06-17 09:21:001515 resolver_->dispatcher_->OnJobFinished();
[email protected]daae1322013-09-05 18:26:501516 --num_occupied_job_slots_;
1517 }
1518 DCHECK_EQ(1u, num_occupied_job_slots_);
1519 }
1520
[email protected]51b9a6b2012-06-25 21:50:291521 void UpdatePriority() {
Paul Jensenb7352f92018-11-08 00:02:491522 if (is_queued())
[email protected]106ccd2c2014-06-17 09:21:001523 handle_ = resolver_->dispatcher_->ChangePriority(handle_, priority());
[email protected]51b9a6b2012-06-25 21:50:291524 }
1525
[email protected]16ee26d2012-03-08 03:34:351526 // PriorityDispatch::Job:
dchengb03027d2014-10-21 12:00:201527 void Start() override {
[email protected]daae1322013-09-05 18:26:501528 DCHECK_LE(num_occupied_job_slots_, 1u);
1529
[email protected]70c04ab2013-08-22 16:05:121530 handle_.Reset();
[email protected]daae1322013-09-05 18:26:501531 ++num_occupied_job_slots_;
1532
1533 if (num_occupied_job_slots_ == 2) {
1534 StartSecondDnsTransaction();
1535 return;
1536 }
1537
1538 DCHECK(!is_running());
[email protected]0f292de02012-02-01 22:28:201539
mikecirone8b85c432016-09-08 19:11:001540 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB_STARTED);
[email protected]0f292de02012-02-01 22:28:201541
Misha Efimovb99e7da2018-05-30 16:59:021542 start_time_ = tick_clock_->NowTicks();
[email protected]51b9a6b2012-06-25 21:50:291543
Eric Orthdc35748e2018-08-23 22:41:481544 switch (key_.host_resolver_source) {
1545 case HostResolverSource::ANY:
Eric Orth60931742018-11-05 23:40:571546 if (!ResemblesMulticastDNSName(key_.hostname)) {
1547 StartDnsTask(true /* allow_fallback_resolution */);
Eric Orthdc35748e2018-08-23 22:41:481548 } else {
1549 StartProcTask();
1550 }
1551 break;
1552 case HostResolverSource::SYSTEM:
1553 StartProcTask();
1554 break;
1555 case HostResolverSource::DNS:
Eric Orth60931742018-11-05 23:40:571556 StartDnsTask(false /* allow_fallback_resolution */);
Eric Orthdc35748e2018-08-23 22:41:481557 break;
Eric Orth9871aafa2018-10-02 19:59:181558 case HostResolverSource::MULTICAST_DNS:
1559 StartMdnsTask();
1560 break;
Eric Orthdc35748e2018-08-23 22:41:481561 }
[email protected]443714fad2013-09-19 04:52:011562
[email protected]1d932852012-06-19 19:40:331563 // Caution: Job::Start must not complete synchronously.
[email protected]b3601bc22012-02-21 21:23:201564 }
1565
[email protected]b3601bc22012-02-21 21:23:201566 // TODO(szym): Since DnsTransaction does not consume threads, we can increase
Francois Doraya2d01ba2017-09-25 19:17:401567 // the limits on |dispatcher_|. But in order to keep the number of
1568 // TaskScheduler threads low, we will need to use an "inner"
1569 // PrioritizedDispatcher with tighter limits.
[email protected]b3601bc22012-02-21 21:23:201570 void StartProcTask() {
Eric Orth9871aafa2018-10-02 19:59:181571 DCHECK(!is_running());
Eric Orth9a037562018-07-03 21:24:381572 proc_task_ = std::make_unique<ProcTask>(
Misha Efimovb99e7da2018-05-30 16:59:021573 key_, resolver_->proc_params_,
Eric Orth70992982018-07-24 00:25:001574 base::BindOnce(&Job::OnProcTaskComplete, base::Unretained(this),
1575 tick_clock_->NowTicks()),
Misha Efimovb99e7da2018-05-30 16:59:021576 proc_task_runner_, net_log_, tick_clock_);
[email protected]0f292de02012-02-01 22:28:201577
[email protected]0f292de02012-02-01 22:28:201578 // Start() could be called from within Resolve(), hence it must NOT directly
1579 // call OnProcTaskComplete, for example, on synchronous failure.
1580 proc_task_->Start();
[email protected]68ad3ee2010-01-30 03:45:391581 }
1582
[email protected]0f292de02012-02-01 22:28:201583 // Called by ProcTask when it completes.
[email protected]e3bd4822012-10-23 18:01:371584 void OnProcTaskComplete(base::TimeTicks start_time,
1585 int net_error,
1586 const AddressList& addr_list) {
[email protected]b3601bc22012-02-21 21:23:201587 DCHECK(is_proc_running());
[email protected]68ad3ee2010-01-30 03:45:391588
[email protected]1d932852012-06-19 19:40:331589 if (dns_task_error_ != OK) {
Eric Orth60931742018-11-05 23:40:571590 // This ProcTask was a fallback resolution after a failed DnsTask.
[email protected]1def74c2012-03-22 20:07:001591 if (net_error == OK) {
Eric Orth60931742018-11-05 23:40:571592 resolver_->OnFallbackResolve(dns_task_error_);
[email protected]1def74c2012-03-22 20:07:001593 }
1594 }
1595
eroman1efc237c2016-12-14 00:00:451596 if (ContainsIcannNameCollisionIp(addr_list))
1597 net_error = ERR_ICANN_NAME_COLLISION;
1598
[email protected]1339a2a22012-10-17 08:39:431599 base::TimeDelta ttl =
1600 base::TimeDelta::FromSeconds(kNegativeCacheEntryTTLSeconds);
[email protected]b3601bc22012-02-21 21:23:201601 if (net_error == OK)
1602 ttl = base::TimeDelta::FromSeconds(kCacheEntryTTLSeconds);
[email protected]68ad3ee2010-01-30 03:45:391603
Rob Percival94f21ad2017-11-14 10:20:241604 // Source unknown because the system resolver could have gotten it from a
1605 // hosts file, its own cache, a DNS lookup or somewhere else.
[email protected]895123222012-10-25 15:21:171606 // Don't store the |ttl| in cache since it's not obtained from the server.
Rob Percival94f21ad2017-11-14 10:20:241607 CompleteRequests(
Matt Menkec35d1632018-11-29 12:43:491608 HostCache::Entry(net_error,
1609 net_error == OK
1610 ? AddressList::CopyWithPort(addr_list, 0)
1611 : AddressList(),
1612 HostCache::Entry::SOURCE_UNKNOWN),
Eric Orth9871aafa2018-10-02 19:59:181613 ttl, true /* allow_cache */);
[email protected]b3601bc22012-02-21 21:23:201614 }
1615
Eric Orth60931742018-11-05 23:40:571616 void StartDnsTask(bool allow_fallback_resolution) {
1617 if ((!resolver_->HaveDnsConfig() || resolver_->use_proctask_by_default_) &&
1618 allow_fallback_resolution) {
1619 // DnsClient or config is not available, but we're allowed to switch to
1620 // ProcTask instead.
1621 StartProcTask();
1622 return;
1623 }
[email protected]b3601bc22012-02-21 21:23:201624
Eric Orth60931742018-11-05 23:40:571625 // Need to create the task even if we're going to post a failure instead of
1626 // running it, as a "started" job needs a task to be properly cleaned up.
1627 dns_task_.reset(new DnsTask(resolver_->dns_client_.get(), key_,
1628 allow_fallback_resolution, this, net_log_,
1629 tick_clock_));
1630
1631 if (resolver_->HaveDnsConfig()) {
1632 dns_task_->StartFirstTransaction();
1633 // Schedule a second transaction, if needed.
1634 if (dns_task_->needs_two_transactions())
1635 Schedule(true);
1636 } else {
1637 // Cannot start a DNS task when DnsClient or config is not available.
1638 // Since we cannot complete synchronously from here, post a failure.
1639 base::SequencedTaskRunnerHandle::Get()->PostTask(
1640 FROM_HERE,
Matt Menkec35d1632018-11-29 12:43:491641 base::BindOnce(
1642 &Job::OnDnsTaskFailure, weak_ptr_factory_.GetWeakPtr(),
1643 dns_task_->AsWeakPtr(), base::TimeDelta(),
1644 HostCache::Entry(ERR_FAILED, HostCache::Entry::SOURCE_UNKNOWN)));
Eric Orth60931742018-11-05 23:40:571645 }
[email protected]daae1322013-09-05 18:26:501646 }
1647
1648 void StartSecondDnsTransaction() {
1649 DCHECK(dns_task_->needs_two_transactions());
1650 dns_task_->StartSecondTransaction();
[email protected]16c2bd72013-06-28 01:19:221651 }
1652
1653 // Called if DnsTask fails. It is posted from StartDnsTask, so Job may be
1654 // deleted before this callback. In this case dns_task is deleted as well,
1655 // so we use it as indicator whether Job is still valid.
1656 void OnDnsTaskFailure(const base::WeakPtr<DnsTask>& dns_task,
1657 base::TimeDelta duration,
Matt Menkec35d1632018-11-29 12:43:491658 const HostCache::Entry& failure_results) {
1659 DCHECK_NE(OK, failure_results.error());
1660
Miriam Gershenson61604662017-09-28 23:51:111661 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.DnsTask.FailureTime", duration);
[email protected]16c2bd72013-06-28 01:19:221662
wezb9820d42016-06-22 23:41:041663 if (!dns_task)
[email protected]16c2bd72013-06-28 01:19:221664 return;
1665
Miriam Gershenson19faef812018-02-07 23:56:441666 if (duration < base::TimeDelta::FromMilliseconds(10)) {
1667 base::UmaHistogramSparse("Net.DNS.DnsTask.ErrorBeforeFallback.Fast",
Matt Menkec35d1632018-11-29 12:43:491668 std::abs(failure_results.error()));
Miriam Gershenson19faef812018-02-07 23:56:441669 } else {
1670 base::UmaHistogramSparse("Net.DNS.DnsTask.ErrorBeforeFallback.Slow",
Matt Menkec35d1632018-11-29 12:43:491671 std::abs(failure_results.error()));
Miriam Gershenson19faef812018-02-07 23:56:441672 }
Matt Menkec35d1632018-11-29 12:43:491673 dns_task_error_ = failure_results.error();
[email protected]16c2bd72013-06-28 01:19:221674
1675 // TODO(szym): Run ServeFromHosts now if nsswitch.conf says so.
1676 // http://crbug.com/117655
1677
1678 // TODO(szym): Some net errors indicate lack of connectivity. Starting
1679 // ProcTask in that case is a waste of time.
Eric Orth60931742018-11-05 23:40:571680 if (resolver_->allow_fallback_to_proctask_ &&
1681 dns_task->allow_fallback_resolution()) {
[email protected]daae1322013-09-05 18:26:501682 KillDnsTask();
[email protected]16c2bd72013-06-28 01:19:221683 StartProcTask();
1684 } else {
Matt Menkec35d1632018-11-29 12:43:491685 base::TimeDelta ttl = failure_results.has_ttl()
1686 ? failure_results.ttl()
1687 : base::TimeDelta::FromSeconds(0);
1688 CompleteRequests(failure_results, ttl, true /* allow_cache */);
[email protected]b3601bc22012-02-21 21:23:201689 }
1690 }
1691
[email protected]daae1322013-09-05 18:26:501692 // HostResolverImpl::DnsTask::Delegate implementation:
1693
dchengb03027d2014-10-21 12:00:201694 void OnDnsTaskComplete(base::TimeTicks start_time,
Matt Menkec35d1632018-11-29 12:43:491695 const HostCache::Entry& results) override {
[email protected]b3601bc22012-02-21 21:23:201696 DCHECK(is_dns_running());
[email protected]b3601bc22012-02-21 21:23:201697
Misha Efimovb99e7da2018-05-30 16:59:021698 base::TimeDelta duration = tick_clock_->NowTicks() - start_time;
Matt Menkec35d1632018-11-29 12:43:491699 if (results.error() != OK) {
1700 OnDnsTaskFailure(dns_task_->AsWeakPtr(), duration, results);
[email protected]b3601bc22012-02-21 21:23:201701 return;
1702 }
Miriam Gershenson61604662017-09-28 23:51:111703
1704 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.DnsTask.SuccessTime", duration);
[email protected]b3601bc22012-02-21 21:23:201705
Eric Orth60931742018-11-05 23:40:571706 resolver_->OnDnsTaskResolve();
[email protected]f0f602bd2012-11-15 18:01:021707
Matt Menkec35d1632018-11-29 12:43:491708 base::TimeDelta bounded_ttl = std::max(
1709 results.ttl(), base::TimeDelta::FromSeconds(kMinimumTTLSeconds));
[email protected]895123222012-10-25 15:21:171710
Matt Menkec35d1632018-11-29 12:43:491711 if (results.addresses() &&
1712 ContainsIcannNameCollisionIp(results.addresses().value())) {
eroman0cd87b62016-12-14 19:13:451713 CompleteRequestsWithError(ERR_ICANN_NAME_COLLISION);
Matt Menkec35d1632018-11-29 12:43:491714 return;
eroman0cd87b62016-12-14 19:13:451715 }
Matt Menkec35d1632018-11-29 12:43:491716
1717 CompleteRequests(results, bounded_ttl, true /* allow_cache */);
[email protected]b3601bc22012-02-21 21:23:201718 }
1719
dchengb03027d2014-10-21 12:00:201720 void OnFirstDnsTransactionComplete() override {
[email protected]daae1322013-09-05 18:26:501721 DCHECK(dns_task_->needs_two_transactions());
1722 DCHECK_EQ(dns_task_->needs_another_transaction(), is_queued());
1723 // No longer need to occupy two dispatcher slots.
1724 ReduceToOneJobSlot();
1725
1726 // We already have a job slot at the dispatcher, so if the second
1727 // transaction hasn't started, reuse it now instead of waiting in the queue
1728 // for the second slot.
1729 if (dns_task_->needs_another_transaction())
1730 dns_task_->StartSecondTransaction();
1731 }
1732
Eric Orth9871aafa2018-10-02 19:59:181733 void StartMdnsTask() {
1734 DCHECK(!is_running());
1735
1736 // No flags are supported for MDNS except
1737 // HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6 (which is not actually an
1738 // input flag).
1739 DCHECK_EQ(0, key_.host_resolver_flags &
1740 ~HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6);
1741
Eric Orth192e3bb2018-11-14 19:30:321742 std::vector<DnsQueryType> query_types;
1743 if (key_.dns_query_type == DnsQueryType::UNSPECIFIED) {
1744 query_types.push_back(DnsQueryType::A);
1745 query_types.push_back(DnsQueryType::AAAA);
1746 } else {
1747 query_types.push_back(key_.dns_query_type);
Eric Orth9871aafa2018-10-02 19:59:181748 }
1749
1750 mdns_task_ = std::make_unique<HostResolverMdnsTask>(
1751 resolver_->GetOrCreateMdnsClient(), key_.hostname, query_types);
1752 mdns_task_->Start(
1753 base::BindOnce(&Job::OnMdnsTaskComplete, base::Unretained(this)));
1754 }
1755
Matt Menkec35d1632018-11-29 12:43:491756 void OnMdnsTaskComplete() {
Eric Orth9871aafa2018-10-02 19:59:181757 DCHECK(is_mdns_running());
1758 // TODO(crbug.com/846423): Consider adding MDNS-specific logging.
1759
Matt Menkec35d1632018-11-29 12:43:491760 HostCache::Entry results = mdns_task_->GetResults();
1761 if (results.addresses() &&
1762 ContainsIcannNameCollisionIp(results.addresses().value())) {
Eric Orth9871aafa2018-10-02 19:59:181763 CompleteRequestsWithError(ERR_ICANN_NAME_COLLISION);
1764 } else {
1765 // MDNS uses a separate cache, so skip saving result to cache.
1766 // TODO(crbug.com/846423): Consider merging caches.
Matt Menkec35d1632018-11-29 12:43:491767 CompleteRequestsWithoutCache(results);
Eric Orth9871aafa2018-10-02 19:59:181768 }
1769 }
1770
Brad Lassey786929ad2018-02-21 20:54:271771 URLRequestContext* url_request_context() override {
1772 return resolver_->url_request_context_;
1773 }
1774
Miriam Gershenson61604662017-09-28 23:51:111775 void RecordJobHistograms(int error) {
Miriam Gershensonc282ab42017-11-20 23:19:581776 // Used in UMA_HISTOGRAM_ENUMERATION. Do not renumber entries or reuse
1777 // deprecated values.
1778 enum Category {
1779 RESOLVE_SUCCESS = 0,
1780 RESOLVE_FAIL = 1,
1781 RESOLVE_SPECULATIVE_SUCCESS = 2,
1782 RESOLVE_SPECULATIVE_FAIL = 3,
1783 RESOLVE_ABORT = 4,
1784 RESOLVE_SPECULATIVE_ABORT = 5,
Miriam Gershenson61604662017-09-28 23:51:111785 RESOLVE_MAX, // Bounding value.
1786 };
1787 Category category = RESOLVE_MAX; // Illegal value for later DCHECK only.
1788
Misha Efimovb99e7da2018-05-30 16:59:021789 base::TimeDelta duration = tick_clock_->NowTicks() - start_time_;
Miriam Gershenson61604662017-09-28 23:51:111790 if (error == OK) {
1791 if (had_non_speculative_request_) {
1792 category = RESOLVE_SUCCESS;
1793 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime", duration);
Eric Orth192e3bb2018-11-14 19:30:321794 switch (key_.dns_query_type) {
1795 case DnsQueryType::A:
Miriam Gershenson61604662017-09-28 23:51:111796 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime.IPV4",
1797 duration);
1798 break;
Eric Orth192e3bb2018-11-14 19:30:321799 case DnsQueryType::AAAA:
Miriam Gershenson61604662017-09-28 23:51:111800 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime.IPV6",
1801 duration);
1802 break;
Eric Orth192e3bb2018-11-14 19:30:321803 case DnsQueryType::UNSPECIFIED:
Miriam Gershenson61604662017-09-28 23:51:111804 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime.UNSPEC",
1805 duration);
1806 break;
Eric Orth192e3bb2018-11-14 19:30:321807 default:
1808 // No histogram for other query types.
1809 break;
Miriam Gershenson61604662017-09-28 23:51:111810 }
1811 } else {
1812 category = RESOLVE_SPECULATIVE_SUCCESS;
Miriam Gershenson61604662017-09-28 23:51:111813 }
Miriam Gershensonc282ab42017-11-20 23:19:581814 } else if (error == ERR_NETWORK_CHANGED ||
1815 error == ERR_HOST_RESOLVER_QUEUE_TOO_LARGE) {
1816 category = had_non_speculative_request_ ? RESOLVE_ABORT
1817 : RESOLVE_SPECULATIVE_ABORT;
Miriam Gershenson61604662017-09-28 23:51:111818 } else {
1819 if (had_non_speculative_request_) {
1820 category = RESOLVE_FAIL;
1821 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveFailureTime", duration);
Eric Orth192e3bb2018-11-14 19:30:321822 switch (key_.dns_query_type) {
1823 case DnsQueryType::A:
Miriam Gershensonc282ab42017-11-20 23:19:581824 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveFailureTime.IPV4",
Miriam Gershenson61604662017-09-28 23:51:111825 duration);
1826 break;
Eric Orth192e3bb2018-11-14 19:30:321827 case DnsQueryType::AAAA:
Miriam Gershensonc282ab42017-11-20 23:19:581828 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveFailureTime.IPV6",
Miriam Gershenson61604662017-09-28 23:51:111829 duration);
1830 break;
Eric Orth192e3bb2018-11-14 19:30:321831 case DnsQueryType::UNSPECIFIED:
Miriam Gershensonc282ab42017-11-20 23:19:581832 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveFailureTime.UNSPEC",
Miriam Gershenson61604662017-09-28 23:51:111833 duration);
1834 break;
Eric Orth192e3bb2018-11-14 19:30:321835 default:
1836 // No histogram for other query types.
1837 break;
Miriam Gershenson61604662017-09-28 23:51:111838 }
1839 } else {
1840 category = RESOLVE_SPECULATIVE_FAIL;
Miriam Gershenson61604662017-09-28 23:51:111841 }
1842 }
1843 DCHECK_LT(static_cast<int>(category),
1844 static_cast<int>(RESOLVE_MAX)); // Be sure it was set.
1845 UMA_HISTOGRAM_ENUMERATION("Net.DNS.ResolveCategory", category, RESOLVE_MAX);
Miriam Gershensonaaf139582017-11-27 16:06:061846
1847 if (category == RESOLVE_FAIL || category == RESOLVE_ABORT) {
1848 if (duration < base::TimeDelta::FromMilliseconds(10))
Ilya Sherman0eb39802017-12-08 20:58:181849 base::UmaHistogramSparse("Net.DNS.ResolveError.Fast", std::abs(error));
Miriam Gershensonaaf139582017-11-27 16:06:061850 else
Ilya Sherman0eb39802017-12-08 20:58:181851 base::UmaHistogramSparse("Net.DNS.ResolveError.Slow", std::abs(error));
Miriam Gershensonaaf139582017-11-27 16:06:061852 }
Miriam Gershenson61604662017-09-28 23:51:111853 }
1854
[email protected]16ee26d2012-03-08 03:34:351855 // Performs Job's last rites. Completes all Requests. Deletes this.
Eric Orth9871aafa2018-10-02 19:59:181856 //
1857 // If not |allow_cache|, result will not be stored in the host cache, even if
1858 // result would otherwise allow doing so.
Matt Menkec35d1632018-11-29 12:43:491859 void CompleteRequests(const HostCache::Entry& results,
Eric Orth9871aafa2018-10-02 19:59:181860 base::TimeDelta ttl,
1861 bool allow_cache) {
[email protected]11fbca0b2013-06-02 23:37:211862 CHECK(resolver_.get());
[email protected]b3601bc22012-02-21 21:23:201863
[email protected]16ee26d2012-03-08 03:34:351864 // This job must be removed from resolver's |jobs_| now to make room for a
1865 // new job with the same key in case one of the OnComplete callbacks decides
Eric Orth18544ae2018-06-11 22:57:161866 // to spawn one. Consequently, if the job was owned by |jobs_|, the job
1867 // deletes itself when CompleteRequests is done.
1868 std::unique_ptr<Job> self_deleter = resolver_->RemoveJob(this);
[email protected]16ee26d2012-03-08 03:34:351869
[email protected]16ee26d2012-03-08 03:34:351870 if (is_running()) {
Eric Orth9a037562018-07-03 21:24:381871 proc_task_ = nullptr;
[email protected]daae1322013-09-05 18:26:501872 KillDnsTask();
Eric Orth9871aafa2018-10-02 19:59:181873 mdns_task_ = nullptr;
[email protected]16ee26d2012-03-08 03:34:351874
1875 // Signal dispatcher that a slot has opened.
[email protected]106ccd2c2014-06-17 09:21:001876 resolver_->dispatcher_->OnJobFinished();
[email protected]16ee26d2012-03-08 03:34:351877 } else if (is_queued()) {
[email protected]106ccd2c2014-06-17 09:21:001878 resolver_->dispatcher_->Cancel(handle_);
[email protected]16ee26d2012-03-08 03:34:351879 handle_.Reset();
1880 }
1881
1882 if (num_active_requests() == 0) {
mikecirone8b85c432016-09-08 19:11:001883 net_log_.AddEvent(NetLogEventType::CANCELLED);
1884 net_log_.EndEventWithNetErrorCode(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
[email protected]16ee26d2012-03-08 03:34:351885 OK);
1886 return;
1887 }
[email protected]b3601bc22012-02-21 21:23:201888
mikecirone8b85c432016-09-08 19:11:001889 net_log_.EndEventWithNetErrorCode(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
Matt Menkec35d1632018-11-29 12:43:491890 results.error());
[email protected]68ad3ee2010-01-30 03:45:391891
[email protected]78eac2a2012-03-14 19:09:271892 DCHECK(!requests_.empty());
1893
Matt Menkec35d1632018-11-29 12:43:491894 bool did_complete = (results.error() != ERR_NETWORK_CHANGED) &&
1895 (results.error() != ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
Eric Orth9871aafa2018-10-02 19:59:181896 if (did_complete && allow_cache)
Matt Menkec35d1632018-11-29 12:43:491897 resolver_->CacheResult(key_, results, ttl);
Miriam Gershensonc282ab42017-11-20 23:19:581898
Matt Menkec35d1632018-11-29 12:43:491899 RecordJobHistograms(results.error());
[email protected]16ee26d2012-03-08 03:34:351900
maksim.sisov31452af2016-07-27 06:38:101901 // Complete all of the requests that were attached to the job and
1902 // detach them.
1903 while (!requests_.empty()) {
David Benjamina5677192018-04-23 23:25:421904 RequestImpl* req = requests_.head()->value();
1905 req->RemoveFromList();
[email protected]0f292de02012-02-01 22:28:201906 DCHECK_EQ(this, req->job());
1907 // Update the net log and notify registered observers.
Matt Menkec35d1632018-11-29 12:43:491908 LogFinishRequest(req->source_net_log(), results.error());
[email protected]51b9a6b2012-06-25 21:50:291909 if (did_complete) {
1910 // Record effective total time from creation to completion.
Paul Jensen41dc3e9f2018-11-06 22:10:101911 resolver_->RecordTotalTime(
1912 req->parameters().is_speculative, false /* from_cache */,
1913 tick_clock_->NowTicks() - req->request_time());
[email protected]51b9a6b2012-06-25 21:50:291914 }
Matt Menkec35d1632018-11-29 12:43:491915 if (results.error() == OK && !req->parameters().is_speculative) {
1916 req->set_results(SetPortOnResults(results, req->request_host().port()));
Eric Orth70992982018-07-24 00:25:001917 }
Matt Menkec35d1632018-11-29 12:43:491918 req->OnJobCompleted(this, results.error());
[email protected]0f292de02012-02-01 22:28:201919
1920 // Check if the resolver was destroyed as a result of running the
1921 // callback. If it was, we could continue, but we choose to bail.
[email protected]11fbca0b2013-06-02 23:37:211922 if (!resolver_.get())
[email protected]0f292de02012-02-01 22:28:201923 return;
1924 }
1925 }
1926
Matt Menkec35d1632018-11-29 12:43:491927 void CompleteRequestsWithoutCache(const HostCache::Entry& results) {
1928 CompleteRequests(results, base::TimeDelta(), false /* allow_cache */);
Eric Orth9871aafa2018-10-02 19:59:181929 }
1930
[email protected]1339a2a22012-10-17 08:39:431931 // Convenience wrapper for CompleteRequests in case of failure.
1932 void CompleteRequestsWithError(int net_error) {
Matt Menkec35d1632018-11-29 12:43:491933 DCHECK_NE(OK, net_error);
1934 CompleteRequests(
1935 HostCache::Entry(net_error, HostCache::Entry::SOURCE_UNKNOWN),
1936 base::TimeDelta(), true /* allow_cache */);
[email protected]1339a2a22012-10-17 08:39:431937 }
1938
Brad Lassey786929ad2018-02-21 20:54:271939 RequestPriority priority() const override {
[email protected]b4481b222012-03-16 17:13:111940 return priority_tracker_.highest_priority();
1941 }
1942
1943 // Number of non-canceled requests in |requests_|.
1944 size_t num_active_requests() const {
1945 return priority_tracker_.total_count();
1946 }
1947
wezb9820d42016-06-22 23:41:041948 bool is_dns_running() const { return !!dns_task_; }
[email protected]b4481b222012-03-16 17:13:111949
Eric Orth9871aafa2018-10-02 19:59:181950 bool is_mdns_running() const { return !!mdns_task_; }
1951
wezb9820d42016-06-22 23:41:041952 bool is_proc_running() const { return !!proc_task_; }
[email protected]b4481b222012-03-16 17:13:111953
[email protected]0f292de02012-02-01 22:28:201954 base::WeakPtr<HostResolverImpl> resolver_;
1955
1956 Key key_;
1957
1958 // Tracks the highest priority across |requests_|.
1959 PriorityTracker priority_tracker_;
1960
Miriam Gershensone42adb22017-10-16 16:19:381961 // Task runner used for HostResolverProc.
1962 scoped_refptr<base::TaskRunner> proc_task_runner_;
1963
[email protected]0f292de02012-02-01 22:28:201964 bool had_non_speculative_request_;
1965
[email protected]daae1322013-09-05 18:26:501966 // Number of slots occupied by this Job in resolver's PrioritizedDispatcher.
1967 unsigned num_occupied_job_slots_;
1968
[email protected]1d932852012-06-19 19:40:331969 // Result of DnsTask.
1970 int dns_task_error_;
[email protected]1def74c2012-03-22 20:07:001971
Misha Efimovb99e7da2018-05-30 16:59:021972 const base::TickClock* tick_clock_;
Miriam Gershenson61604662017-09-28 23:51:111973 base::TimeTicks start_time_;
[email protected]51b9a6b2012-06-25 21:50:291974
tfarina428341112016-09-22 13:38:201975 NetLogWithSource net_log_;
[email protected]0f292de02012-02-01 22:28:201976
[email protected]b3601bc22012-02-21 21:23:201977 // Resolves the host using a HostResolverProc.
Eric Orth9a037562018-07-03 21:24:381978 std::unique_ptr<ProcTask> proc_task_;
[email protected]0f292de02012-02-01 22:28:201979
[email protected]b3601bc22012-02-21 21:23:201980 // Resolves the host using a DnsTransaction.
danakj22f90e72016-04-16 01:55:401981 std::unique_ptr<DnsTask> dns_task_;
[email protected]b3601bc22012-02-21 21:23:201982
Eric Orth9871aafa2018-10-02 19:59:181983 // Resolves the host using MDnsClient.
1984 std::unique_ptr<HostResolverMdnsTask> mdns_task_;
1985
[email protected]0f292de02012-02-01 22:28:201986 // All Requests waiting for the result of this Job. Some can be canceled.
David Benjamina5677192018-04-23 23:25:421987 base::LinkedList<RequestImpl> requests_;
[email protected]0f292de02012-02-01 22:28:201988
[email protected]16ee26d2012-03-08 03:34:351989 // A handle used in |HostResolverImpl::dispatcher_|.
[email protected]0f292de02012-02-01 22:28:201990 PrioritizedDispatcher::Handle handle_;
Eric Orth60931742018-11-05 23:40:571991
1992 base::WeakPtrFactory<Job> weak_ptr_factory_;
[email protected]68ad3ee2010-01-30 03:45:391993};
1994
1995//-----------------------------------------------------------------------------
1996
[email protected]0f292de02012-02-01 22:28:201997HostResolverImpl::ProcTaskParams::ProcTaskParams(
[email protected]e95d3aca2010-01-11 22:47:431998 HostResolverProc* resolver_proc,
[email protected]0f292de02012-02-01 22:28:201999 size_t max_retry_attempts)
2000 : resolver_proc(resolver_proc),
2001 max_retry_attempts(max_retry_attempts),
ttuttlecf1158bf2016-03-18 16:37:442002 unresponsive_delay(
2003 base::TimeDelta::FromMilliseconds(kDnsDefaultUnresponsiveDelayMs)),
[email protected]0f292de02012-02-01 22:28:202004 retry_factor(2) {
[email protected]106ccd2c2014-06-17 09:21:002005 // Maximum of 4 retry attempts for host resolution.
2006 static const size_t kDefaultMaxRetryAttempts = 4u;
2007 if (max_retry_attempts == HostResolver::kDefaultRetryAttempts)
2008 max_retry_attempts = kDefaultMaxRetryAttempts;
[email protected]0f292de02012-02-01 22:28:202009}
2010
vmpstracd23b72016-02-26 21:08:552011HostResolverImpl::ProcTaskParams::ProcTaskParams(const ProcTaskParams& other) =
2012 default;
2013
Chris Watkins68b15032017-12-01 03:07:132014HostResolverImpl::ProcTaskParams::~ProcTaskParams() = default;
[email protected]0f292de02012-02-01 22:28:202015
Francois Doraya2d01ba2017-09-25 19:17:402016HostResolverImpl::HostResolverImpl(const Options& options, NetLog* net_log)
mmenke91c17162016-06-02 16:03:232017 : max_queued_jobs_(0),
2018 proc_params_(NULL, options.max_retry_attempts),
2019 net_log_(net_log),
2020 received_dns_config_(false),
2021 num_dns_failures_(0),
mgershaf9a9232017-04-13 20:19:032022 assume_ipv6_failure_on_wifi_(false),
mmenke91c17162016-06-02 16:03:232023 use_local_ipv6_(false),
2024 last_ipv6_probe_result_(true),
mmenke91c17162016-06-02 16:03:232025 additional_resolver_flags_(0),
Eric Orth60931742018-11-05 23:40:572026 use_proctask_by_default_(false),
2027 allow_fallback_to_proctask_(true),
Brad Lassey73e67ee2018-05-31 00:11:592028 url_request_context_(nullptr),
Misha Efimovb99e7da2018-05-30 16:59:022029 tick_clock_(base::DefaultTickClock::GetInstance()),
mmenke91c17162016-06-02 16:03:232030 weak_ptr_factory_(this),
2031 probe_weak_ptr_factory_(this) {
2032 if (options.enable_caching)
2033 cache_ = HostCache::CreateDefaultCache();
2034
2035 PrioritizedDispatcher::Limits job_limits = options.GetDispatcherLimits();
2036 dispatcher_.reset(new PrioritizedDispatcher(job_limits));
2037 max_queued_jobs_ = job_limits.total_jobs * 100u;
2038
2039 DCHECK_GE(dispatcher_->num_priorities(), static_cast<size_t>(NUM_PRIORITIES));
2040
Miriam Gershensone42adb22017-10-16 16:19:382041 proc_task_runner_ = base::CreateTaskRunnerWithTraits(
Maks Orlovich5393c8682018-02-26 16:17:502042 {base::MayBlock(), priority_mode.Get(),
2043 base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN});
Miriam Gershensone42adb22017-10-16 16:19:382044
mmenke91c17162016-06-02 16:03:232045#if defined(OS_WIN)
2046 EnsureWinsockInit();
2047#endif
Fabrice de Gans-Riberi7de47372018-05-08 20:23:472048#if (defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)) || \
2049 defined(OS_FUCHSIA)
mmenke91c17162016-06-02 16:03:232050 RunLoopbackProbeJob();
2051#endif
Paul Jensenf47bbab2018-09-14 16:34:042052 NetworkChangeNotifier::AddIPAddressObserver(this);
2053 NetworkChangeNotifier::AddConnectionTypeObserver(this);
mmenke91c17162016-06-02 16:03:232054 NetworkChangeNotifier::AddDNSObserver(this);
2055#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD) && \
Fabrice de Gans-Riberi65421f62018-05-22 23:16:182056 !defined(OS_ANDROID)
mmenke91c17162016-06-02 16:03:232057 EnsureDnsReloaderInit();
2058#endif
2059
Paul Jensenf47bbab2018-09-14 16:34:042060 OnConnectionTypeChanged(NetworkChangeNotifier::GetConnectionType());
mmenke91c17162016-06-02 16:03:232061
2062 {
Paul Jensen1e501e32018-11-29 20:38:482063 DnsConfig dns_config = GetBaseDnsConfig(false);
mmenke91c17162016-06-02 16:03:232064 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
2065 use_local_ipv6_ = !dns_config.IsValid() || dns_config.use_local_ipv6;
Paul Jensen41dc3e9f2018-11-06 22:10:102066 UpdateModeForHistogram(dns_config);
mmenke91c17162016-06-02 16:03:232067 }
2068
Eric Orth60931742018-11-05 23:40:572069 allow_fallback_to_proctask_ = !ConfigureAsyncDnsNoFallbackFieldTrial();
mmenke91c17162016-06-02 16:03:232070}
2071
Eric Orth70992982018-07-24 00:25:002072HostResolverImpl::~HostResolverImpl() {
2073 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
2074 // Prevent the dispatcher from starting new jobs.
2075 dispatcher_->SetLimitsToZero();
2076 // It's now safe for Jobs to call KillDnsTask on destruction, because
2077 // OnJobComplete will not start any new jobs.
2078 jobs_.clear();
2079
Paul Jensenf47bbab2018-09-14 16:34:042080 NetworkChangeNotifier::RemoveIPAddressObserver(this);
2081 NetworkChangeNotifier::RemoveConnectionTypeObserver(this);
Eric Orth70992982018-07-24 00:25:002082 NetworkChangeNotifier::RemoveDNSObserver(this);
mmenke91c17162016-06-02 16:03:232083}
2084
Eric Orth70992982018-07-24 00:25:002085void HostResolverImpl::SetDnsClient(std::unique_ptr<DnsClient> dns_client) {
2086 // DnsClient and config must be updated before aborting DnsTasks, since doing
2087 // so may start new jobs.
2088 dns_client_ = std::move(dns_client);
2089 if (dns_client_ && !dns_client_->GetConfig() &&
2090 num_dns_failures_ < kMaximumDnsFailures) {
Paul Jensen1e501e32018-11-29 20:38:482091 dns_client_->SetConfig(GetBaseDnsConfig(false));
Eric Orth70992982018-07-24 00:25:002092 num_dns_failures_ = 0;
Eric Orth70992982018-07-24 00:25:002093 }
2094
Eric Orth60931742018-11-05 23:40:572095 AbortDnsTasks(ERR_NETWORK_CHANGED, false /* fallback_only */);
Paul Jensen1e501e32018-11-29 20:38:482096 DnsConfig dns_config;
2097 if (!HaveDnsConfig())
2098 // UpdateModeForHistogram() needs to know the DnsConfig when
2099 // !HaveDnsConfig()
2100 dns_config = GetBaseDnsConfig(false);
2101 UpdateModeForHistogram(dns_config);
Findite5a94e02018-07-13 21:56:212102}
2103
Eric Orth70992982018-07-24 00:25:002104std::unique_ptr<HostResolver::ResolveHostRequest>
Eric Orth00fe5a62018-08-15 22:20:002105HostResolverImpl::CreateRequest(
2106 const HostPortPair& host,
2107 const NetLogWithSource& net_log,
2108 const base::Optional<ResolveHostParameters>& optional_parameters) {
2109 return std::make_unique<RequestImpl>(net_log, host, optional_parameters,
Eric Orth00fe5a62018-08-15 22:20:002110 weak_ptr_factory_.GetWeakPtr());
Eric Orth70992982018-07-24 00:25:002111}
2112
2113int HostResolverImpl::Resolve(const RequestInfo& info,
2114 RequestPriority priority,
2115 AddressList* addresses,
2116 CompletionOnceCallback callback,
2117 std::unique_ptr<Request>* out_req,
2118 const NetLogWithSource& source_net_log) {
2119 DCHECK(addresses);
2120 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
2121 DCHECK(callback);
2122 DCHECK(out_req);
2123
2124 auto request = std::make_unique<RequestImpl>(
Eric Orth00fe5a62018-08-15 22:20:002125 source_net_log, info.host_port_pair(),
2126 RequestInfoToResolveHostParameters(info, priority),
Eric Orthb30bc172018-08-17 21:09:572127 weak_ptr_factory_.GetWeakPtr());
Eric Orth70992982018-07-24 00:25:002128 auto wrapped_request =
2129 std::make_unique<LegacyRequestImpl>(std::move(request));
2130
2131 int rv = wrapped_request->Start();
2132
Eric Orthb30bc172018-08-17 21:09:572133 if (rv == OK && !info.is_speculative()) {
Eric Orth70992982018-07-24 00:25:002134 DCHECK(wrapped_request->inner_request().GetAddressResults());
2135 *addresses = wrapped_request->inner_request().GetAddressResults().value();
2136 } else if (rv == ERR_IO_PENDING) {
2137 wrapped_request->AssignCallback(std::move(callback), addresses);
2138 *out_req = std::move(wrapped_request);
Eric Orthfac527992018-07-13 21:11:162139 }
2140
Eric Orth70992982018-07-24 00:25:002141 return rv;
[email protected]95a214c2011-08-04 21:50:402142}
2143
2144int HostResolverImpl::ResolveFromCache(const RequestInfo& info,
2145 AddressList* addresses,
tfarina428341112016-09-22 13:38:202146 const NetLogWithSource& source_net_log) {
gab47aa7da2017-06-02 16:09:432147 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
[email protected]95a214c2011-08-04 21:50:402148 DCHECK(addresses);
2149
[email protected]95a214c2011-08-04 21:50:402150 // Update the net log and notify registered observers.
xunjieli26f90452014-11-10 16:23:022151 LogStartRequest(source_net_log, info);
[email protected]95a214c2011-08-04 21:50:402152
Matt Menke23b4bbf82017-07-20 19:11:292153 Key key;
Matt Menkec35d1632018-11-29 12:43:492154 HostCache::Entry results = ResolveLocally(
2155 info.host_port_pair().host(),
2156 AddressFamilyToDnsQueryType(info.address_family()),
Eric Orthdc35748e2018-08-23 22:41:482157 FlagsToSource(info.host_resolver_flags()), info.host_resolver_flags(),
2158 info.allow_cached_response(), false /* allow_stale */,
Matt Menkec35d1632018-11-29 12:43:492159 nullptr /* stale_info */, source_net_log, &key);
[email protected]95a214c2011-08-04 21:50:402160
Matt Menkec35d1632018-11-29 12:43:492161 if (results.addresses()) {
2162 *addresses = AddressList::CopyWithPort(results.addresses().value(),
2163 info.host_port_pair().port());
2164 }
2165
2166 LogFinishRequest(source_net_log, results.error());
2167 return results.error();
Eric Orth70992982018-07-24 00:25:002168}
2169
2170int HostResolverImpl::ResolveStaleFromCache(
2171 const RequestInfo& info,
2172 AddressList* addresses,
2173 HostCache::EntryStaleness* stale_info,
2174 const NetLogWithSource& source_net_log) {
2175 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
2176 DCHECK(addresses);
2177 DCHECK(stale_info);
2178
2179 // Update the net log and notify registered observers.
2180 LogStartRequest(source_net_log, info);
2181
2182 Key key;
Matt Menkec35d1632018-11-29 12:43:492183 HostCache::Entry results =
2184 ResolveLocally(info.host_port_pair().host(),
2185 AddressFamilyToDnsQueryType(info.address_family()),
2186 FlagsToSource(info.host_resolver_flags()),
2187 info.host_resolver_flags(), info.allow_cached_response(),
2188 true /* allow_stale */, stale_info, source_net_log, &key);
2189
2190 if (results.addresses()) {
2191 *addresses = AddressList::CopyWithPort(results.addresses().value(),
2192 info.host_port_pair().port());
2193 }
2194
2195 LogFinishRequest(source_net_log, results.error());
2196 return results.error();
[email protected]95a214c2011-08-04 21:50:402197}
2198
[email protected]a8883e452012-11-17 05:58:062199void HostResolverImpl::SetDnsClientEnabled(bool enabled) {
gab47aa7da2017-06-02 16:09:432200 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
[email protected]a8883e452012-11-17 05:58:062201#if defined(ENABLE_BUILT_IN_DNS)
2202 if (enabled && !dns_client_) {
2203 SetDnsClient(DnsClient::CreateClient(net_log_));
2204 } else if (!enabled && dns_client_) {
danakj22f90e72016-04-16 01:55:402205 SetDnsClient(std::unique_ptr<DnsClient>());
[email protected]a8883e452012-11-17 05:58:062206 }
2207#endif
2208}
2209
[email protected]489d1a82011-10-12 03:09:112210HostCache* HostResolverImpl::GetHostCache() {
2211 return cache_.get();
2212}
[email protected]95a214c2011-08-04 21:50:402213
Rob Percivalbc658a22017-12-13 08:24:422214bool HostResolverImpl::HasCached(base::StringPiece hostname,
2215 HostCache::Entry::Source* source_out,
2216 HostCache::EntryStaleness* stale_out) const {
2217 if (!cache_)
2218 return false;
2219
2220 return cache_->HasEntry(hostname, source_out, stale_out);
2221}
2222
danakj22f90e72016-04-16 01:55:402223std::unique_ptr<base::Value> HostResolverImpl::GetDnsConfigAsValue() const {
[email protected]17e92032012-03-29 00:56:242224 // Check if async DNS is disabled.
2225 if (!dns_client_.get())
tfhef3618f2016-01-11 23:07:082226 return nullptr;
[email protected]17e92032012-03-29 00:56:242227
2228 // Check if async DNS is enabled, but we currently have no configuration
2229 // for it.
2230 const DnsConfig* dns_config = dns_client_->GetConfig();
wezb9820d42016-06-22 23:41:042231 if (!dns_config)
Jeremy Roman0579ed62017-08-29 15:56:192232 return std::make_unique<base::DictionaryValue>();
[email protected]17e92032012-03-29 00:56:242233
2234 return dns_config->ToValue();
2235}
2236
Miriam Gershenson2839ef112017-08-30 03:25:372237size_t HostResolverImpl::LastRestoredCacheSize() const {
2238 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
2239
2240 return cache_ ? cache_->last_restore_size() : 0;
2241}
2242
2243size_t HostResolverImpl::CacheSize() const {
2244 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
2245
2246 return cache_ ? cache_->size() : 0;
2247}
2248
mgershaf9a9232017-04-13 20:19:032249void HostResolverImpl::SetNoIPv6OnWifi(bool no_ipv6_on_wifi) {
gab47aa7da2017-06-02 16:09:432250 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
mgershaf9a9232017-04-13 20:19:032251 assume_ipv6_failure_on_wifi_ = no_ipv6_on_wifi;
2252}
2253
2254bool HostResolverImpl::GetNoIPv6OnWifi() {
2255 return assume_ipv6_failure_on_wifi_;
2256}
2257
Eric Orthc1eb1292018-10-09 22:07:072258void HostResolverImpl::SetDnsConfigOverrides(
2259 const DnsConfigOverrides& overrides) {
2260 if (dns_config_overrides_ == overrides)
2261 return;
2262
2263 dns_config_overrides_ = overrides;
Eric Orthc823a23d2018-10-30 22:12:482264 if (dns_client_.get())
Eric Orthc1eb1292018-10-09 22:07:072265 UpdateDNSConfig(true);
2266}
2267
Brad Lassey786929ad2018-02-21 20:54:272268void HostResolverImpl::SetRequestContext(URLRequestContext* context) {
2269 if (context != url_request_context_) {
2270 url_request_context_ = context;
2271 }
2272}
2273
Matt Menkeb67c0a8e2018-06-14 22:41:042274const std::vector<DnsConfig::DnsOverHttpsServerConfig>*
2275HostResolverImpl::GetDnsOverHttpsServersForTesting() const {
Eric Orthc1eb1292018-10-09 22:07:072276 if (!dns_config_overrides_.dns_over_https_servers ||
2277 dns_config_overrides_.dns_over_https_servers.value().empty()) {
Matt Menkeb67c0a8e2018-06-14 22:41:042278 return nullptr;
Eric Orthc1eb1292018-10-09 22:07:072279 }
2280 return &dns_config_overrides_.dns_over_https_servers.value();
Matt Menkeb67c0a8e2018-06-14 22:41:042281}
2282
Eric Orth70992982018-07-24 00:25:002283void HostResolverImpl::SetTickClockForTesting(
2284 const base::TickClock* tick_clock) {
2285 tick_clock_ = tick_clock;
2286 cache_->set_tick_clock_for_testing(tick_clock);
2287}
2288
2289void HostResolverImpl::SetMaxQueuedJobsForTesting(size_t value) {
2290 DCHECK_EQ(0u, dispatcher_->num_queued_jobs());
2291 DCHECK_GE(value, 0u);
2292 max_queued_jobs_ = value;
2293}
2294
2295void HostResolverImpl::SetHaveOnlyLoopbackAddresses(bool result) {
2296 if (result) {
2297 additional_resolver_flags_ |= HOST_RESOLVER_LOOPBACK_ONLY;
2298 } else {
2299 additional_resolver_flags_ &= ~HOST_RESOLVER_LOOPBACK_ONLY;
2300 }
2301}
2302
Eric Orth9871aafa2018-10-02 19:59:182303void HostResolverImpl::SetMdnsSocketFactoryForTesting(
2304 std::unique_ptr<MDnsSocketFactory> socket_factory) {
2305 DCHECK(!mdns_client_);
2306 mdns_socket_factory_ = std::move(socket_factory);
2307}
2308
2309void HostResolverImpl::SetMdnsClientForTesting(
2310 std::unique_ptr<MDnsClient> client) {
2311 mdns_client_ = std::move(client);
2312}
2313
Eric Orthe366fe62018-10-24 16:38:312314void HostResolverImpl::SetBaseDnsConfigForTesting(
2315 const DnsConfig& base_config) {
2316 test_base_config_ = base_config;
2317 UpdateDNSConfig(true);
2318}
2319
Eric Orth70992982018-07-24 00:25:002320void HostResolverImpl::SetTaskRunnerForTesting(
2321 scoped_refptr<base::TaskRunner> task_runner) {
2322 proc_task_runner_ = std::move(task_runner);
2323}
2324
2325int HostResolverImpl::Resolve(RequestImpl* request) {
2326 // Request should not yet have a scheduled Job.
2327 DCHECK(!request->job());
2328 // Request may only be resolved once.
2329 DCHECK(!request->complete());
Eric Orth9871aafa2018-10-02 19:59:182330 // MDNS requests do not support skipping cache.
2331 // TODO(crbug.com/846423): Either add support for skipping the MDNS cache, or
2332 // merge to use the normal host cache for MDNS requests.
2333 DCHECK(request->parameters().source != HostResolverSource::MULTICAST_DNS ||
2334 request->parameters().allow_cached_response);
Eric Orth70992982018-07-24 00:25:002335
2336 request->set_request_time(tick_clock_->NowTicks());
2337
2338 LogStartRequest(request->source_net_log(), request->request_host());
2339
Eric Orth70992982018-07-24 00:25:002340 Key key;
Matt Menkec35d1632018-11-29 12:43:492341 HostCache::Entry results = ResolveLocally(
2342 request->request_host().host(), request->parameters().dns_query_type,
Eric Orthdc35748e2018-08-23 22:41:482343 request->parameters().source, request->host_resolver_flags(),
2344 request->parameters().allow_cached_response, false /* allow_stale */,
Matt Menkec35d1632018-11-29 12:43:492345 nullptr /* stale_info */, request->source_net_log(), &key);
2346 if (results.error() == OK && !request->parameters().is_speculative) {
2347 request->set_results(
2348 SetPortOnResults(results, request->request_host().port()));
Eric Orth70992982018-07-24 00:25:002349 }
Matt Menkec35d1632018-11-29 12:43:492350 if (results.error() != ERR_DNS_CACHE_MISS) {
2351 LogFinishRequest(request->source_net_log(), results.error());
Eric Orthb30bc172018-08-17 21:09:572352 RecordTotalTime(request->parameters().is_speculative, true /* from_cache */,
Eric Orth70992982018-07-24 00:25:002353 base::TimeDelta());
Matt Menkec35d1632018-11-29 12:43:492354 return results.error();
Eric Orth70992982018-07-24 00:25:002355 }
2356
Matt Menkec35d1632018-11-29 12:43:492357 int rv = CreateAndStartJob(key, request);
Eric Orth70992982018-07-24 00:25:002358 // At this point, expect only async or errors.
2359 DCHECK_NE(OK, rv);
2360
2361 return rv;
2362}
2363
Matt Menkec35d1632018-11-29 12:43:492364HostCache::Entry HostResolverImpl::ResolveLocally(
2365 const std::string& hostname,
2366 DnsQueryType dns_query_type,
2367 HostResolverSource source,
2368 HostResolverFlags flags,
2369 bool allow_cache,
2370 bool allow_stale,
2371 HostCache::EntryStaleness* stale_info,
2372 const NetLogWithSource& source_net_log,
2373 Key* out_key) {
Eric Orth70992982018-07-24 00:25:002374 IPAddress ip_address;
2375 IPAddress* ip_address_ptr = nullptr;
Matt Menkec35d1632018-11-29 12:43:492376 if (ip_address.AssignFromIPLiteral(hostname)) {
Eric Orth70992982018-07-24 00:25:002377 ip_address_ptr = &ip_address;
2378 } else {
2379 // Check that the caller supplied a valid hostname to resolve.
Matt Menkec35d1632018-11-29 12:43:492380 if (!IsValidDNSDomain(hostname)) {
2381 return HostCache::Entry(ERR_NAME_NOT_RESOLVED,
2382 HostCache::Entry::SOURCE_UNKNOWN);
2383 }
Eric Orth70992982018-07-24 00:25:002384 }
2385
2386 // Build a key that identifies the request in the cache and in the
2387 // outstanding jobs map.
Matt Menkec35d1632018-11-29 12:43:492388 *out_key = GetEffectiveKeyForRequest(hostname, dns_query_type, source, flags,
2389 ip_address_ptr, source_net_log);
Eric Orth70992982018-07-24 00:25:002390
2391 DCHECK(allow_stale == !!stale_info);
2392 // The result of |getaddrinfo| for empty hosts is inconsistent across systems.
2393 // On Windows it gives the default interface's address, whereas on Linux it
2394 // gives an error. We will make it fail on all platforms for consistency.
Matt Menkec35d1632018-11-29 12:43:492395 if (hostname.empty() || hostname.size() > kMaxHostLength) {
Eric Orth70992982018-07-24 00:25:002396 MakeNotStale(stale_info);
Matt Menkec35d1632018-11-29 12:43:492397 return HostCache::Entry(ERR_NAME_NOT_RESOLVED,
2398 HostCache::Entry::SOURCE_UNKNOWN);
Eric Orth70992982018-07-24 00:25:002399 }
2400
Matt Menkec35d1632018-11-29 12:43:492401 base::Optional<HostCache::Entry> resolved =
2402 ResolveAsIP(*out_key, ip_address_ptr);
2403 if (resolved) {
Eric Orth70992982018-07-24 00:25:002404 MakeNotStale(stale_info);
Matt Menkec35d1632018-11-29 12:43:492405 return resolved.value();
Eric Orth70992982018-07-24 00:25:002406 }
2407
2408 // Special-case localhost names, as per the recommendations in
2409 // https://tools.ietf.org/html/draft-west-let-localhost-be-localhost.
Matt Menkec35d1632018-11-29 12:43:492410 resolved = ServeLocalhost(*out_key);
2411 if (resolved) {
Eric Orth70992982018-07-24 00:25:002412 MakeNotStale(stale_info);
Matt Menkec35d1632018-11-29 12:43:492413 return resolved.value();
Eric Orth70992982018-07-24 00:25:002414 }
2415
Matt Menkec35d1632018-11-29 12:43:492416 if (allow_cache) {
2417 resolved = ServeFromCache(*out_key, allow_stale, stale_info);
2418 if (resolved) {
2419 source_net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_CACHE_HIT,
2420 resolved.value().CreateNetLogCallback());
2421 // |ServeFromCache()| will update |*stale_info| as needed.
2422 return resolved.value();
2423 }
Eric Orth70992982018-07-24 00:25:002424 }
2425
2426 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2427 // http://crbug.com/117655
Matt Menkec35d1632018-11-29 12:43:492428 resolved = ServeFromHosts(*out_key);
2429 if (resolved) {
Eric Orth70992982018-07-24 00:25:002430 source_net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_HOSTS_HIT,
Matt Menkec35d1632018-11-29 12:43:492431 resolved.value().CreateNetLogCallback());
Eric Orth70992982018-07-24 00:25:002432 MakeNotStale(stale_info);
Matt Menkec35d1632018-11-29 12:43:492433 return resolved.value();
Eric Orth70992982018-07-24 00:25:002434 }
2435
Matt Menkec35d1632018-11-29 12:43:492436 return HostCache::Entry(ERR_DNS_CACHE_MISS, HostCache::Entry::SOURCE_UNKNOWN);
Eric Orth70992982018-07-24 00:25:002437}
2438
2439int HostResolverImpl::CreateAndStartJob(const Key& key, RequestImpl* request) {
2440 auto jobit = jobs_.find(key);
2441 Job* job;
2442 if (jobit == jobs_.end()) {
2443 auto new_job = std::make_unique<Job>(
2444 weak_ptr_factory_.GetWeakPtr(), key, request->priority(),
2445 proc_task_runner_, request->source_net_log(), tick_clock_);
2446 job = new_job.get();
2447 new_job->Schedule(false);
2448
2449 // Check for queue overflow.
2450 if (dispatcher_->num_queued_jobs() > max_queued_jobs_) {
2451 Job* evicted = static_cast<Job*>(dispatcher_->EvictOldestLowest());
2452 DCHECK(evicted);
2453 evicted->OnEvicted();
2454 if (evicted == new_job.get()) {
2455 LogFinishRequest(request->source_net_log(),
2456 ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
2457 return ERR_HOST_RESOLVER_QUEUE_TOO_LARGE;
2458 }
2459 }
2460 jobs_[key] = std::move(new_job);
2461 } else {
2462 job = jobit->second.get();
2463 }
2464
2465 // Can't complete synchronously. Attach request and job to each other.
2466 job->AddRequest(request);
2467 return ERR_IO_PENDING;
2468}
2469
Matt Menkec35d1632018-11-29 12:43:492470base::Optional<HostCache::Entry> HostResolverImpl::ResolveAsIP(
2471 const Key& key,
2472 const IPAddress* ip_address) {
Eric Orth192e3bb2018-11-14 19:30:322473 if (ip_address == nullptr || !IsAddressType(key.dns_query_type))
Matt Menkec35d1632018-11-29 12:43:492474 return base::nullopt;
[email protected]95a214c2011-08-04 21:50:402475
martijna23c8962016-03-04 18:18:512476 AddressFamily family = GetAddressFamily(*ip_address);
Eric Orth192e3bb2018-11-14 19:30:322477 if (key.dns_query_type != DnsQueryType::UNSPECIFIED &&
2478 key.dns_query_type != AddressFamilyToDnsQueryType(family)) {
[email protected]1c7cf3f82014-08-07 21:33:482479 // Don't return IPv6 addresses for IPv4 queries, and vice versa.
Matt Menkec35d1632018-11-29 12:43:492480 return HostCache::Entry(ERR_NAME_NOT_RESOLVED,
2481 HostCache::Entry::SOURCE_UNKNOWN);
[email protected]95a214c2011-08-04 21:50:402482 }
Matt Menkec35d1632018-11-29 12:43:492483
2484 AddressList addresses = AddressList::CreateFromIPAddress(*ip_address, 0);
2485 if (key.host_resolver_flags & HOST_RESOLVER_CANONNAME)
2486 addresses.SetDefaultCanonicalName();
2487 return HostCache::Entry(OK, std::move(addresses),
2488 HostCache::Entry::SOURCE_UNKNOWN);
[email protected]95a214c2011-08-04 21:50:402489}
2490
Matt Menkec35d1632018-11-29 12:43:492491base::Optional<HostCache::Entry> HostResolverImpl::ServeFromCache(
2492 const Key& key,
2493 bool allow_stale,
2494 HostCache::EntryStaleness* stale_info) {
juliatuttle9fb7aeb2016-06-06 20:16:332495 DCHECK(allow_stale == !!stale_info);
Eric Orth70992982018-07-24 00:25:002496 if (!cache_.get())
Matt Menkec35d1632018-11-29 12:43:492497 return base::nullopt;
[email protected]95a214c2011-08-04 21:50:402498
juliatuttle9fb7aeb2016-06-06 20:16:332499 const HostCache::Entry* cache_entry;
2500 if (allow_stale)
Misha Efimovb99e7da2018-05-30 16:59:022501 cache_entry = cache_->LookupStale(key, tick_clock_->NowTicks(), stale_info);
juliatuttle9fb7aeb2016-06-06 20:16:332502 else
Misha Efimovb99e7da2018-05-30 16:59:022503 cache_entry = cache_->Lookup(key, tick_clock_->NowTicks());
[email protected]95a214c2011-08-04 21:50:402504 if (!cache_entry)
Matt Menkec35d1632018-11-29 12:43:492505 return base::nullopt;
[email protected]95a214c2011-08-04 21:50:402506
Matt Menkec35d1632018-11-29 12:43:492507 return *cache_entry;
[email protected]95a214c2011-08-04 21:50:402508}
2509
Matt Menkec35d1632018-11-29 12:43:492510base::Optional<HostCache::Entry> HostResolverImpl::ServeFromHosts(
2511 const Key& key) {
2512 if (!HaveDnsConfig() || !IsAddressType(key.dns_query_type))
2513 return base::nullopt;
[email protected]05a79d42013-03-28 07:30:092514
[email protected]cb507622012-03-23 16:17:062515 // HOSTS lookups are case-insensitive.
brettw8e2106d2015-08-11 19:30:222516 std::string hostname = base::ToLowerASCII(key.hostname);
[email protected]cb507622012-03-23 16:17:062517
[email protected]05a79d42013-03-28 07:30:092518 const DnsHosts& hosts = dns_client_->GetConfig()->hosts;
2519
[email protected]78eac2a2012-03-14 19:09:272520 // If |address_family| is ADDRESS_FAMILY_UNSPECIFIED other implementations
2521 // (glibc and c-ares) return the first matching line. We have more
2522 // flexibility, but lose implicit ordering.
[email protected]05a79d42013-03-28 07:30:092523 // We prefer IPv6 because "happy eyeballs" will fall back to IPv4 if
2524 // necessary.
Matt Menkec35d1632018-11-29 12:43:492525 AddressList addresses;
Eric Orth192e3bb2018-11-14 19:30:322526 if (key.dns_query_type == DnsQueryType::AAAA ||
2527 key.dns_query_type == DnsQueryType::UNSPECIFIED) {
jdoerrie22a91d8b92018-10-05 08:43:262528 auto it = hosts.find(DnsHostsKey(hostname, ADDRESS_FAMILY_IPV6));
[email protected]05a79d42013-03-28 07:30:092529 if (it != hosts.end())
Matt Menkec35d1632018-11-29 12:43:492530 addresses.push_back(IPEndPoint(it->second, 0));
[email protected]78eac2a2012-03-14 19:09:272531 }
2532
Eric Orth192e3bb2018-11-14 19:30:322533 if (key.dns_query_type == DnsQueryType::A ||
2534 key.dns_query_type == DnsQueryType::UNSPECIFIED) {
jdoerrie22a91d8b92018-10-05 08:43:262535 auto it = hosts.find(DnsHostsKey(hostname, ADDRESS_FAMILY_IPV4));
[email protected]05a79d42013-03-28 07:30:092536 if (it != hosts.end())
Matt Menkec35d1632018-11-29 12:43:492537 addresses.push_back(IPEndPoint(it->second, 0));
[email protected]05a79d42013-03-28 07:30:092538 }
2539
[email protected]ec666ab22013-04-17 20:05:592540 // If got only loopback addresses and the family was restricted, resolve
2541 // again, without restrictions. See SystemHostResolverCall for rationale.
2542 if ((key.host_resolver_flags &
Matt Menkec35d1632018-11-29 12:43:492543 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6) &&
2544 IsAllIPv4Loopback(addresses)) {
[email protected]ec666ab22013-04-17 20:05:592545 Key new_key(key);
Eric Orth192e3bb2018-11-14 19:30:322546 new_key.dns_query_type = DnsQueryType::UNSPECIFIED;
[email protected]ec666ab22013-04-17 20:05:592547 new_key.host_resolver_flags &=
2548 ~HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
Matt Menkec35d1632018-11-29 12:43:492549 return ServeFromHosts(new_key);
[email protected]ec666ab22013-04-17 20:05:592550 }
Matt Menkec35d1632018-11-29 12:43:492551
2552 if (!addresses.empty()) {
2553 return HostCache::Entry(OK, std::move(addresses),
2554 HostCache::Entry::SOURCE_HOSTS);
2555 }
2556
2557 return base::nullopt;
[email protected]78eac2a2012-03-14 19:09:272558}
2559
Matt Menkec35d1632018-11-29 12:43:492560base::Optional<HostCache::Entry> HostResolverImpl::ServeLocalhost(
2561 const Key& key) {
estarkd1bc206e2015-06-20 00:44:392562 AddressList resolved_addresses;
Matt Menkec35d1632018-11-29 12:43:492563 if (!IsAddressType(key.dns_query_type) ||
2564 !ResolveLocalHostname(key.hostname, &resolved_addresses)) {
2565 return base::nullopt;
2566 }
estarkd1bc206e2015-06-20 00:44:392567
Matt Menkec35d1632018-11-29 12:43:492568 AddressList filtered_addresses;
2569 for (const auto& address : resolved_addresses) {
2570 // Include the address if:
2571 // - caller didn't specify an address family, or
2572 // - caller specifically asked for the address family of this address, or
2573 // - this is an IPv6 address and caller specifically asked for IPv4 due
2574 // to lack of detected IPv6 support. (See SystemHostResolverCall for
2575 // rationale).
2576 if (key.dns_query_type == DnsQueryType::UNSPECIFIED ||
2577 DnsQueryTypeToAddressFamily(key.dns_query_type) ==
2578 address.GetFamily() ||
2579 (address.GetFamily() == ADDRESS_FAMILY_IPV6 &&
2580 key.dns_query_type == DnsQueryType::A &&
2581 (key.host_resolver_flags &
2582 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6))) {
2583 filtered_addresses.push_back(address);
estarkd1bc206e2015-06-20 00:44:392584 }
2585 }
2586
Matt Menkec35d1632018-11-29 12:43:492587 return HostCache::Entry(OK, std::move(filtered_addresses),
2588 HostCache::Entry::SOURCE_UNKNOWN);
estarkd1bc206e2015-06-20 00:44:392589}
2590
[email protected]16ee26d2012-03-08 03:34:352591void HostResolverImpl::CacheResult(const Key& key,
[email protected]1339a2a22012-10-17 08:39:432592 const HostCache::Entry& entry,
[email protected]16ee26d2012-03-08 03:34:352593 base::TimeDelta ttl) {
Miriam Gershensone3bc63022017-10-09 19:57:052594 // Don't cache an error unless it has a positive TTL.
2595 if (cache_.get() && (entry.error() == OK || ttl > base::TimeDelta()))
Misha Efimovb99e7da2018-05-30 16:59:022596 cache_->Set(key, entry, tick_clock_->NowTicks(), ttl);
[email protected]ef4c40c2010-09-01 14:42:032597}
2598
Paul Jensen41dc3e9f2018-11-06 22:10:102599// Record time from Request creation until a valid DNS response.
2600void HostResolverImpl::RecordTotalTime(bool speculative,
2601 bool from_cache,
2602 base::TimeDelta duration) const {
2603 if (!speculative) {
2604 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.TotalTime", duration);
2605
2606 switch (mode_for_histogram_) {
2607 case MODE_FOR_HISTOGRAM_SYSTEM:
2608 UMA_HISTOGRAM_MEDIUM_TIMES("Net.DNS.TotalTimeTyped.System", duration);
2609 break;
2610 case MODE_FOR_HISTOGRAM_SYSTEM_SUPPORTS_DOH:
2611 UMA_HISTOGRAM_MEDIUM_TIMES("Net.DNS.TotalTimeTyped.SystemSupportsDoh",
2612 duration);
2613 break;
2614 case MODE_FOR_HISTOGRAM_SYSTEM_PRIVATE_DNS:
2615 UMA_HISTOGRAM_MEDIUM_TIMES("Net.DNS.TotalTimeTyped.SystemPrivate",
2616 duration);
2617 break;
2618 case MODE_FOR_HISTOGRAM_ASYNC_DNS:
2619 UMA_HISTOGRAM_MEDIUM_TIMES("Net.DNS.TotalTimeTyped.Async", duration);
2620 break;
2621 case MODE_FOR_HISTOGRAM_ASYNC_DNS_PRIVATE_SUPPORTS_DOH:
2622 UMA_HISTOGRAM_MEDIUM_TIMES(
2623 "Net.DNS.TotalTimeTyped.AsyncPrivateSupportsDoh", duration);
2624 break;
2625 }
2626
2627 if (!from_cache)
2628 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.TotalTimeNotCached", duration);
2629 }
2630}
2631
Eric Orth18544ae2018-06-11 22:57:162632std::unique_ptr<HostResolverImpl::Job> HostResolverImpl::RemoveJob(Job* job) {
[email protected]0f292de02012-02-01 22:28:202633 DCHECK(job);
Eric Orth18544ae2018-06-11 22:57:162634 std::unique_ptr<Job> retval;
avi9e72eb482016-12-09 21:10:542635 auto it = jobs_.find(job->key());
2636 if (it != jobs_.end() && it->second.get() == job) {
Eric Orth18544ae2018-06-11 22:57:162637 it->second.swap(retval);
[email protected]16ee26d2012-03-08 03:34:352638 jobs_.erase(it);
avi9e72eb482016-12-09 21:10:542639 }
Eric Orth18544ae2018-06-11 22:57:162640 return retval;
[email protected]b59ff372009-07-15 22:04:322641}
2642
[email protected]137af622010-02-05 02:14:352643HostResolverImpl::Key HostResolverImpl::GetEffectiveKeyForRequest(
Eric Orth70992982018-07-24 00:25:002644 const std::string& hostname,
Eric Orth00fe5a62018-08-15 22:20:002645 DnsQueryType dns_query_type,
Eric Orthdc35748e2018-08-23 22:41:482646 HostResolverSource source,
Eric Orth70992982018-07-24 00:25:002647 HostResolverFlags flags,
martijna23c8962016-03-04 18:18:512648 const IPAddress* ip_address,
tfarina428341112016-09-22 13:38:202649 const NetLogWithSource& net_log) {
Eric Orth70992982018-07-24 00:25:002650 HostResolverFlags effective_flags = flags | additional_resolver_flags_;
Eric Orth00fe5a62018-08-15 22:20:002651
Eric Orth192e3bb2018-11-14 19:30:322652 DnsQueryType effective_query_type = dns_query_type;
[email protected]9db6f702013-04-10 18:10:512653
Eric Orth192e3bb2018-11-14 19:30:322654 if (effective_query_type == DnsQueryType::UNSPECIFIED &&
mgersh3eba057d2017-02-28 18:50:562655 // When resolving IPv4 literals, there's no need to probe for IPv6.
2656 // When resolving IPv6 literals, there's no benefit to artificially
2657 // limiting our resolution based on a probe. Prior logic ensures
Eric Orth192e3bb2018-11-14 19:30:322658 // that this query is UNSPECIFIED (see effective_query_type check above)
2659 // so the code requesting the resolution should be amenable to receiving a
2660 // IPv6 resolution.
mgersh3eba057d2017-02-28 18:50:562661 !use_local_ipv6_ && ip_address == nullptr && !IsIPv6Reachable(net_log)) {
Eric Orth192e3bb2018-11-14 19:30:322662 effective_query_type = DnsQueryType::A;
mgersh3eba057d2017-02-28 18:50:562663 effective_flags |= HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
[email protected]9db6f702013-04-10 18:10:512664 }
2665
Eric Orth192e3bb2018-11-14 19:30:322666 return Key(hostname, effective_query_type, effective_flags, source);
[email protected]137af622010-02-05 02:14:352667}
2668
tfarina428341112016-09-22 13:38:202669bool HostResolverImpl::IsIPv6Reachable(const NetLogWithSource& net_log) {
mgershaf9a9232017-04-13 20:19:032670 // Don't bother checking if the device is on WiFi and IPv6 is assumed to not
2671 // work on WiFi.
2672 if (assume_ipv6_failure_on_wifi_ &&
2673 NetworkChangeNotifier::GetConnectionType() ==
2674 NetworkChangeNotifier::CONNECTION_WIFI) {
2675 return false;
2676 }
2677
eroman1a17ef32016-12-14 01:06:092678 // Cache the result for kIPv6ProbePeriodMs (measured from after
2679 // IsGloballyReachable() completes).
sergeyub8cdc212015-05-14 18:50:372680 bool cached = true;
Misha Efimovb99e7da2018-05-30 16:59:022681 if ((tick_clock_->NowTicks() - last_ipv6_probe_time_).InMilliseconds() >
eroman1a17ef32016-12-14 01:06:092682 kIPv6ProbePeriodMs) {
martijna23c8962016-03-04 18:18:512683 last_ipv6_probe_result_ =
2684 IsGloballyReachable(IPAddress(kIPv6ProbeAddress), net_log);
Misha Efimovb99e7da2018-05-30 16:59:022685 last_ipv6_probe_time_ = tick_clock_->NowTicks();
sergeyub8cdc212015-05-14 18:50:372686 cached = false;
2687 }
mikecirone8b85c432016-09-08 19:11:002688 net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_IPV6_REACHABILITY_CHECK,
sergeyub8cdc212015-05-14 18:50:372689 base::Bind(&NetLogIPv6AvailableCallback,
2690 last_ipv6_probe_result_, cached));
2691 return last_ipv6_probe_result_;
2692}
2693
mgershaf9a9232017-04-13 20:19:032694bool HostResolverImpl::IsGloballyReachable(const IPAddress& dest,
2695 const NetLogWithSource& net_log) {
mgershaf9a9232017-04-13 20:19:032696 std::unique_ptr<DatagramClientSocket> socket(
2697 ClientSocketFactory::GetDefaultFactory()->CreateDatagramClientSocket(
Sergey Ulanovcbdfc8852018-03-16 20:13:282698 DatagramSocket::DEFAULT_BIND, net_log.net_log(), net_log.source()));
mgershaf9a9232017-04-13 20:19:032699 int rv = socket->Connect(IPEndPoint(dest, 53));
2700 if (rv != OK)
2701 return false;
2702 IPEndPoint endpoint;
2703 rv = socket->GetLocalAddress(&endpoint);
2704 if (rv != OK)
2705 return false;
2706 DCHECK_EQ(ADDRESS_FAMILY_IPV6, endpoint.GetFamily());
2707 const IPAddress& address = endpoint.address();
2708
2709 bool is_link_local =
2710 (address.bytes()[0] == 0xFE) && ((address.bytes()[1] & 0xC0) == 0x80);
2711 if (is_link_local)
2712 return false;
2713
2714 const uint8_t kTeredoPrefix[] = {0x20, 0x01, 0, 0};
2715 if (IPAddressStartsWith(address, kTeredoPrefix))
2716 return false;
2717
2718 return true;
2719}
2720
mmenke91c17162016-06-02 16:03:232721void HostResolverImpl::RunLoopbackProbeJob() {
Francois Doraya2d01ba2017-09-25 19:17:402722 // Run this asynchronously as it can take 40-100ms and should not block
2723 // initialization.
2724 base::PostTaskWithTraitsAndReplyWithResult(
2725 FROM_HERE,
2726 {base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
2727 base::BindOnce(&HaveOnlyLoopbackAddresses),
2728 base::BindOnce(&HostResolverImpl::SetHaveOnlyLoopbackAddresses,
2729 weak_ptr_factory_.GetWeakPtr()));
mmenke91c17162016-06-02 16:03:232730}
2731
[email protected]35ddc282010-09-21 23:42:062732void HostResolverImpl::AbortAllInProgressJobs() {
[email protected]b3601bc22012-02-21 21:23:202733 // In Abort, a Request callback could spawn new Jobs with matching keys, so
2734 // first collect and remove all running jobs from |jobs_|.
danakj22f90e72016-04-16 01:55:402735 std::vector<std::unique_ptr<Job>> jobs_to_abort;
avi9e72eb482016-12-09 21:10:542736 for (auto it = jobs_.begin(); it != jobs_.end();) {
2737 Job* job = it->second.get();
[email protected]0f292de02012-02-01 22:28:202738 if (job->is_running()) {
avi9e72eb482016-12-09 21:10:542739 jobs_to_abort.push_back(std::move(it->second));
[email protected]b3601bc22012-02-21 21:23:202740 jobs_.erase(it++);
[email protected]0f292de02012-02-01 22:28:202741 } else {
[email protected]b3601bc22012-02-21 21:23:202742 DCHECK(job->is_queued());
2743 ++it;
[email protected]0f292de02012-02-01 22:28:202744 }
[email protected]ef4c40c2010-09-01 14:42:032745 }
[email protected]b3601bc22012-02-21 21:23:202746
[email protected]daae1322013-09-05 18:26:502747 // Pause the dispatcher so it won't start any new dispatcher jobs while
2748 // aborting the old ones. This is needed so that it won't start the second
2749 // DnsTransaction for a job in |jobs_to_abort| if the DnsConfig just became
2750 // invalid.
[email protected]106ccd2c2014-06-17 09:21:002751 PrioritizedDispatcher::Limits limits = dispatcher_->GetLimits();
2752 dispatcher_->SetLimits(
[email protected]daae1322013-09-05 18:26:502753 PrioritizedDispatcher::Limits(limits.reserved_slots.size(), 0));
[email protected]70c04ab2013-08-22 16:05:122754
[email protected]57a48d32012-03-03 00:04:552755 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072756 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]57a48d32012-03-03 00:04:552757
[email protected]16ee26d2012-03-08 03:34:352758 // Then Abort them.
[email protected]11fbca0b2013-06-02 23:37:212759 for (size_t i = 0; self.get() && i < jobs_to_abort.size(); ++i) {
[email protected]57a48d32012-03-03 00:04:552760 jobs_to_abort[i]->Abort();
[email protected]b3601bc22012-02-21 21:23:202761 }
[email protected]daae1322013-09-05 18:26:502762
2763 if (self)
[email protected]106ccd2c2014-06-17 09:21:002764 dispatcher_->SetLimits(limits);
[email protected]daae1322013-09-05 18:26:502765}
2766
Eric Orth60931742018-11-05 23:40:572767void HostResolverImpl::AbortDnsTasks(int error, bool fallback_only) {
2768 // Aborting jobs potentially modifies |jobs_| and may even delete some jobs.
2769 // Create safe closures of all current jobs.
2770 std::vector<base::OnceClosure> job_abort_closures;
2771 for (auto& job : jobs_) {
2772 job_abort_closures.push_back(
2773 job.second->GetAbortDnsTaskClosure(error, fallback_only));
2774 }
2775
[email protected]daae1322013-09-05 18:26:502776 // Pause the dispatcher so it won't start any new dispatcher jobs while
2777 // aborting the old ones. This is needed so that it won't start the second
2778 // DnsTransaction for a job if the DnsConfig just changed.
[email protected]106ccd2c2014-06-17 09:21:002779 PrioritizedDispatcher::Limits limits = dispatcher_->GetLimits();
2780 dispatcher_->SetLimits(
[email protected]daae1322013-09-05 18:26:502781 PrioritizedDispatcher::Limits(limits.reserved_slots.size(), 0));
2782
Eric Orth60931742018-11-05 23:40:572783 for (base::OnceClosure& closure : job_abort_closures)
2784 std::move(closure).Run();
2785
[email protected]106ccd2c2014-06-17 09:21:002786 dispatcher_->SetLimits(limits);
[email protected]ef4c40c2010-09-01 14:42:032787}
2788
[email protected]78eac2a2012-03-14 19:09:272789void HostResolverImpl::TryServingAllJobsFromHosts() {
2790 if (!HaveDnsConfig())
2791 return;
2792
2793 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2794 // http://crbug.com/117655
2795
2796 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072797 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]78eac2a2012-03-14 19:09:272798
avi9e72eb482016-12-09 21:10:542799 for (auto it = jobs_.begin(); self.get() && it != jobs_.end();) {
2800 Job* job = it->second.get();
[email protected]78eac2a2012-03-14 19:09:272801 ++it;
2802 // This could remove |job| from |jobs_|, but iterator will remain valid.
2803 job->ServeFromHosts();
2804 }
2805}
2806
Paul Jensenf47bbab2018-09-14 16:34:042807void HostResolverImpl::OnIPAddressChanged() {
sergeyub8cdc212015-05-14 18:50:372808 last_ipv6_probe_time_ = base::TimeTicks();
[email protected]12faa4c2012-11-06 04:44:182809 // Abandon all ProbeJobs.
2810 probe_weak_ptr_factory_.InvalidateWeakPtrs();
Matt Menkeef8f5cf82017-07-20 22:50:172811 if (cache_.get())
mgersh5bb3b9d2017-02-13 21:27:102812 cache_->OnNetworkChange();
Fabrice de Gans-Riberi7de47372018-05-08 20:23:472813#if (defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)) || \
2814 defined(OS_FUCHSIA)
mmenke91c17162016-06-02 16:03:232815 RunLoopbackProbeJob();
[email protected]be1a48b2011-01-20 00:12:132816#endif
2817 AbortAllInProgressJobs();
2818 // |this| may be deleted inside AbortAllInProgressJobs().
2819}
2820
Paul Jensenf47bbab2018-09-14 16:34:042821void HostResolverImpl::OnConnectionTypeChanged(
ttuttlecf1158bf2016-03-18 16:37:442822 NetworkChangeNotifier::ConnectionType type) {
2823 proc_params_.unresponsive_delay =
2824 GetTimeDeltaForConnectionTypeFromFieldTrialOrDefault(
2825 "DnsUnresponsiveDelayMsByConnectionType",
2826 base::TimeDelta::FromMilliseconds(kDnsDefaultUnresponsiveDelayMs),
2827 type);
2828}
2829
pauljensen101ed372015-04-17 00:11:422830void HostResolverImpl::OnInitialDNSConfigRead() {
2831 UpdateDNSConfig(false);
2832}
2833
[email protected]bb0e34542012-08-31 19:52:402834void HostResolverImpl::OnDNSChanged() {
Eric Orthc823a23d2018-10-30 22:12:482835 // Ignore changes if we're using a test config or if we have overriding
2836 // configuration that overrides everything from the base config.
2837 if (test_base_config_ || dns_config_overrides_.OverridesEverything())
Eric Orthe366fe62018-10-24 16:38:312838 return;
2839
pauljensen101ed372015-04-17 00:11:422840 UpdateDNSConfig(true);
2841}
2842
Paul Jensen1e501e32018-11-29 20:38:482843DnsConfig HostResolverImpl::GetBaseDnsConfig(bool log_to_net_log) {
Eric Orthc823a23d2018-10-30 22:12:482844 DnsConfig dns_config;
[email protected]ec666ab22013-04-17 20:05:592845
Eric Orthc823a23d2018-10-30 22:12:482846 // Skip retrieving the base config if all values will be overridden.
2847 if (!dns_config_overrides_.OverridesEverything()) {
Paul Jensen1e501e32018-11-29 20:38:482848 if (test_base_config_) {
2849 dns_config = test_base_config_.value();
2850 } else {
2851 NetworkChangeNotifier::GetDnsConfig(&dns_config);
2852 }
Eric Orthc823a23d2018-10-30 22:12:482853
Paul Jensen1e501e32018-11-29 20:38:482854 if (log_to_net_log && net_log_) {
Eric Orthc823a23d2018-10-30 22:12:482855 net_log_->AddGlobalEntry(
2856 NetLogEventType::DNS_CONFIG_CHANGED,
2857 base::BindRepeating(&NetLogDnsConfigCallback, &dns_config));
2858 }
2859
2860 // TODO(szym): Remove once http://crbug.com/137914 is resolved.
2861 received_dns_config_ = dns_config.IsValid();
[email protected]b4481b222012-03-16 17:13:112862 }
2863
Paul Jensen1e501e32018-11-29 20:38:482864 return dns_config_overrides_.ApplyOverrides(dns_config);
2865}
2866
2867void HostResolverImpl::UpdateDNSConfig(bool config_changed) {
2868 DnsConfig dns_config = GetBaseDnsConfig(true);
Eric Orthc1eb1292018-10-09 22:07:072869
[email protected]c9fa8f312013-09-17 12:24:522870 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
2871 use_local_ipv6_ = !dns_config.IsValid() || dns_config.use_local_ipv6;
[email protected]78eac2a2012-03-14 19:09:272872
[email protected]a8883e452012-11-17 05:58:062873 num_dns_failures_ = 0;
2874
[email protected]01b3b9d2012-08-13 16:18:142875 // We want a new DnsSession in place, before we Abort running Jobs, so that
2876 // the newly started jobs use the new config.
[email protected]f0f602bd2012-11-15 18:01:022877 if (dns_client_.get()) {
Miriam Gershenson44aafc122017-10-18 19:29:252878 // Make sure that if the update is an initial read, not a change, there
Miriam Gershenson668e8442017-10-31 20:31:532879 // wasn't already a DnsConfig or it's the same one.
2880 DCHECK(config_changed || !dns_client_->GetConfig() ||
2881 dns_client_->GetConfig()->Equals(dns_config));
[email protected]d7b9a2b2012-05-31 22:31:192882 dns_client_->SetConfig(dns_config);
[email protected]f0f602bd2012-11-15 18:01:022883 }
Eric Orth60931742018-11-05 23:40:572884 use_proctask_by_default_ = false;
[email protected]01b3b9d2012-08-13 16:18:142885
pauljensen101ed372015-04-17 00:11:422886 if (config_changed) {
2887 // If the DNS server has changed, existing cached info could be wrong so we
mgersh92b1af12017-03-29 15:49:232888 // have to expire our internal cache :( Note that OS level DNS caches, such
pauljensen101ed372015-04-17 00:11:422889 // as NSCD's cache should be dropped automatically by the OS when
2890 // resolv.conf changes so we don't need to do anything to clear that cache.
Matt Menkeef8f5cf82017-07-20 22:50:172891 if (cache_.get())
mgersh92b1af12017-03-29 15:49:232892 cache_->OnNetworkChange();
[email protected]01b3b9d2012-08-13 16:18:142893
pauljensen101ed372015-04-17 00:11:422894 // Life check to bail once |this| is deleted.
2895 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]f0f602bd2012-11-15 18:01:022896
pauljensen101ed372015-04-17 00:11:422897 // Existing jobs will have been sent to the original server so they need to
2898 // be aborted.
2899 AbortAllInProgressJobs();
[email protected]01b3b9d2012-08-13 16:18:142900
pauljensen101ed372015-04-17 00:11:422901 // |this| may be deleted inside AbortAllInProgressJobs().
2902 if (self.get())
2903 TryServingAllJobsFromHosts();
2904 }
Paul Jensen41dc3e9f2018-11-06 22:10:102905
2906 UpdateModeForHistogram(dns_config);
[email protected]78eac2a2012-03-14 19:09:272907}
2908
2909bool HostResolverImpl::HaveDnsConfig() const {
[email protected]32b1dbcf2013-01-26 03:48:252910 // Use DnsClient only if it's fully configured and there is no override by
2911 // ScopedDefaultHostResolverProc.
2912 // The alternative is to use NetworkChangeNotifier to override DnsConfig,
2913 // but that would introduce construction order requirements for NCN and SDHRP.
wezb9820d42016-06-22 23:41:042914 return dns_client_ && dns_client_->GetConfig() &&
2915 (proc_params_.resolver_proc || !HostResolverProc::GetDefault());
[email protected]b3601bc22012-02-21 21:23:202916}
2917
Eric Orth60931742018-11-05 23:40:572918void HostResolverImpl::OnDnsTaskResolve() {
[email protected]f0f602bd2012-11-15 18:01:022919 DCHECK(dns_client_);
Eric Orth60931742018-11-05 23:40:572920 num_dns_failures_ = 0;
2921}
2922
2923void HostResolverImpl::OnFallbackResolve(int dns_task_error) {
2924 DCHECK(dns_client_);
2925 DCHECK_NE(OK, dns_task_error);
2926
[email protected]f0f602bd2012-11-15 18:01:022927 ++num_dns_failures_;
2928 if (num_dns_failures_ < kMaximumDnsFailures)
2929 return;
[email protected]daae1322013-09-05 18:26:502930
Eric Orth60931742018-11-05 23:40:572931 // Force fallback until the next DNS change. Must be done before aborting
2932 // DnsTasks, since doing so may start new jobs. Do not fully clear out or
2933 // disable the DnsClient as some requests (e.g. those specifying DNS source)
2934 // are not allowed to fallback and will continue using DnsTask.
2935 use_proctask_by_default_ = true;
[email protected]daae1322013-09-05 18:26:502936
Eric Orth60931742018-11-05 23:40:572937 // Fallback all fallback-allowed DnsTasks to ProcTasks.
2938 AbortDnsTasks(ERR_FAILED, true /* fallback_only */);
[email protected]f0f602bd2012-11-15 18:01:022939}
2940
Eric Orth9871aafa2018-10-02 19:59:182941MDnsClient* HostResolverImpl::GetOrCreateMdnsClient() {
2942#if BUILDFLAG(ENABLE_MDNS)
2943 if (!mdns_client_) {
2944 if (!mdns_socket_factory_)
2945 mdns_socket_factory_ = std::make_unique<MDnsSocketFactoryImpl>(net_log_);
2946
2947 mdns_client_ = MDnsClient::CreateDefault();
2948 mdns_client_->StartListening(mdns_socket_factory_.get());
2949 }
2950
2951 DCHECK(mdns_client_->IsListening());
2952 return mdns_client_.get();
2953#else
2954 // Should not request MDNS resoltuion unless MDNS is enabled.
2955 NOTREACHED();
2956 return nullptr;
2957#endif
2958}
2959
Paul Jensen41dc3e9f2018-11-06 22:10:102960void HostResolverImpl::UpdateModeForHistogram(const DnsConfig& dns_config) {
2961 // Resolving with Async DNS resolver?
2962 if (HaveDnsConfig()) {
2963 mode_for_histogram_ = MODE_FOR_HISTOGRAM_ASYNC_DNS;
2964 for (const auto& dns_server : dns_client_->GetConfig()->nameservers) {
2965 if (DnsServerSupportsDoh(dns_server.address())) {
2966 mode_for_histogram_ = MODE_FOR_HISTOGRAM_ASYNC_DNS_PRIVATE_SUPPORTS_DOH;
2967 break;
2968 }
2969 }
2970 } else {
2971 mode_for_histogram_ = MODE_FOR_HISTOGRAM_SYSTEM;
2972 for (const auto& dns_server : dns_config.nameservers) {
2973 if (DnsServerSupportsDoh(dns_server.address())) {
2974 mode_for_histogram_ = MODE_FOR_HISTOGRAM_SYSTEM_SUPPORTS_DOH;
2975 break;
2976 }
2977 }
2978#if defined(OS_ANDROID)
2979 if (base::android::BuildInfo::GetInstance()->sdk_int() >=
2980 base::android::SDK_VERSION_P) {
2981 std::vector<IPEndPoint> dns_servers;
2982 if (net::android::GetDnsServers(&dns_servers) ==
2983 internal::CONFIG_PARSE_POSIX_PRIVATE_DNS_ACTIVE) {
2984 mode_for_histogram_ = MODE_FOR_HISTOGRAM_SYSTEM_PRIVATE_DNS;
2985 }
2986 }
2987#endif // defined(OS_ANDROID)
2988 }
2989}
2990
maksim.sisov31452af2016-07-27 06:38:102991HostResolverImpl::RequestImpl::~RequestImpl() {
2992 if (job_)
2993 job_->CancelRequest(this);
2994}
2995
2996void HostResolverImpl::RequestImpl::ChangeRequestPriority(
2997 RequestPriority priority) {
2998 job_->ChangeRequestPriority(this, priority);
2999}
3000
[email protected]b59ff372009-07-15 22:04:323001} // namespace net