blob: bdf16b8ab349e829d7824674dad7fde7e43d9b74 [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
[email protected]68ad3ee2010-01-30 03:45:3920#include <cmath>
thestiga74ad2b2016-07-11 20:52:3621#include <memory>
[email protected]0f292de02012-02-01 22:28:2022#include <utility>
[email protected]21526002010-05-16 19:42:4623#include <vector>
[email protected]68ad3ee2010-01-30 03:45:3924
[email protected]33152acc2011-10-20 23:37:1225#include "base/bind.h"
[email protected]aa22b242011-11-16 18:58:2926#include "base/bind_helpers.h"
[email protected]0f292de02012-02-01 22:28:2027#include "base/callback.h"
maksim.sisov31452af2016-07-27 06:38:1028#include "base/callback_helpers.h"
[email protected]b59ff372009-07-15 22:04:3229#include "base/compiler_specific.h"
David Benjamina5677192018-04-23 23:25:4230#include "base/containers/linked_list.h"
[email protected]58580352010-10-26 04:07:5031#include "base/debug/debugger.h"
32#include "base/debug/stack_trace.h"
Avi Drissman13fc8932015-12-20 04:40:4633#include "base/macros.h"
mmenke91c17162016-06-02 16:03:2334#include "base/memory/ptr_util.h"
[email protected]1e9bbd22010-10-15 16:42:4535#include "base/metrics/field_trial.h"
Maks Orlovich5393c8682018-02-26 16:17:5036#include "base/metrics/field_trial_params.h"
Ilya Sherman0eb39802017-12-08 20:58:1837#include "base/metrics/histogram_functions.h"
davidbenad6fc442015-05-18 20:59:1338#include "base/metrics/histogram_macros.h"
anujk.sharma7c907f02015-05-29 02:55:4439#include "base/single_thread_task_runner.h"
[email protected]be528af2013-06-11 07:39:4840#include "base/strings/string_util.h"
[email protected]750b2f3c2013-06-07 18:41:0541#include "base/strings/utf_string_conversions.h"
Francois Doraya2d01ba2017-09-25 19:17:4042#include "base/task_scheduler/post_task.h"
43#include "base/threading/scoped_blocking_call.h"
gabf767595f2016-05-11 18:50:3544#include "base/threading/thread_task_runner_handle.h"
[email protected]66e96c42013-06-28 15:20:3145#include "base/time/time.h"
ssid6d6b40102016-04-05 18:59:5646#include "base/trace_event/trace_event.h"
[email protected]21526002010-05-16 19:42:4647#include "base/values.h"
Fabrice de Gans-Riberi7de47372018-05-08 20:23:4748#include "build/build_config.h"
[email protected]b3601bc22012-02-21 21:23:2049#include "net/base/address_family.h"
[email protected]b59ff372009-07-15 22:04:3250#include "net/base/address_list.h"
[email protected]ee094b82010-08-24 15:55:5151#include "net/base/host_port_pair.h"
martijna23c8962016-03-04 18:18:5152#include "net/base/ip_address.h"
[email protected]1c7cf3f82014-08-07 21:33:4853#include "net/base/ip_endpoint.h"
[email protected]2bb04442010-08-18 18:01:1554#include "net/base/net_errors.h"
xunjieli0b7f5b62016-12-06 20:43:4855#include "net/base/trace_constants.h"
tfarina9ed7f8c52016-02-19 17:50:1856#include "net/base/url_util.h"
[email protected]0adcb2b2012-08-15 21:30:4657#include "net/dns/address_sorter.h"
[email protected]78eac2a2012-03-14 19:09:2758#include "net/dns/dns_client.h"
[email protected]b3601bc22012-02-21 21:23:2059#include "net/dns/dns_config_service.h"
60#include "net/dns/dns_protocol.h"
tfarina47598f042015-10-07 23:08:3561#include "net/dns/dns_reloader.h"
[email protected]b3601bc22012-02-21 21:23:2062#include "net/dns/dns_response.h"
[email protected]b3601bc22012-02-21 21:23:2063#include "net/dns/dns_transaction.h"
tfarina77021d62015-10-11 20:19:0364#include "net/dns/dns_util.h"
[email protected]f2cb3cf2013-03-21 01:40:5365#include "net/dns/host_resolver_proc.h"
eroman87c53d62015-04-02 06:51:0766#include "net/log/net_log.h"
mikecironef22f9812016-10-04 03:40:1967#include "net/log/net_log_capture_mode.h"
mikecirone8b85c432016-09-08 19:11:0068#include "net/log/net_log_event_type.h"
mikecironef22f9812016-10-04 03:40:1969#include "net/log/net_log_parameters_callback.h"
70#include "net/log/net_log_source.h"
mikecirone8b85c432016-09-08 19:11:0071#include "net/log/net_log_source_type.h"
mikecironef22f9812016-10-04 03:40:1972#include "net/log/net_log_with_source.h"
[email protected]9db6f702013-04-10 18:10:5173#include "net/socket/client_socket_factory.h"
tfarina5dd13c22016-11-16 12:08:2674#include "net/socket/datagram_client_socket.h"
pauljensen370f1c72015-02-17 16:59:1475#include "url/url_canon_ip.h"
[email protected]b59ff372009-07-15 22:04:3276
77#if defined(OS_WIN)
78#include "net/base/winsock_init.h"
79#endif
80
tfarinada9e1362017-03-14 16:49:0681#if defined(OS_ANDROID)
82#include "net/android/network_library.h"
83#endif
84
[email protected]b59ff372009-07-15 22:04:3285namespace net {
86
[email protected]e95d3aca2010-01-11 22:47:4387namespace {
88
ttuttlecf1158bf2016-03-18 16:37:4489// Default delay between calls to the system resolver for the same hostname.
90// (Can be overridden by field trial.)
91const int64_t kDnsDefaultUnresponsiveDelayMs = 6000;
92
[email protected]6e78dfb2011-07-28 21:34:4793// Limit the size of hostnames that will be resolved to combat issues in
94// some platform's resolvers.
95const size_t kMaxHostLength = 4096;
96
[email protected]a2730882012-01-21 00:56:2797// Default TTL for successful resolutions with ProcTask.
98const unsigned kCacheEntryTTLSeconds = 60;
99
[email protected]b3601bc22012-02-21 21:23:20100// Default TTL for unsuccessful resolutions with ProcTask.
101const unsigned kNegativeCacheEntryTTLSeconds = 0;
102
[email protected]895123222012-10-25 15:21:17103// Minimum TTL for successful resolutions with DnsTask.
104const unsigned kMinimumTTLSeconds = kCacheEntryTTLSeconds;
105
sergeyub8cdc212015-05-14 18:50:37106// Time between IPv6 probes, i.e. for how long results of each IPv6 probe are
107// cached.
108const int kIPv6ProbePeriodMs = 1000;
109
110// Google DNS address used for IPv6 probes.
111const uint8_t kIPv6ProbeAddress[] =
112 { 0x20, 0x01, 0x48, 0x60, 0x48, 0x60, 0x00, 0x00,
113 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x88 };
114
[email protected]24f4bab2010-10-15 01:27:11115// We use a separate histogram name for each platform to facilitate the
116// display of error codes by their symbolic name (since each platform has
117// different mappings).
118const char kOSErrorsForGetAddrinfoHistogramName[] =
119#if defined(OS_WIN)
120 "Net.OSErrorsForGetAddrinfo_Win";
121#elif defined(OS_MACOSX)
122 "Net.OSErrorsForGetAddrinfo_Mac";
123#elif defined(OS_LINUX)
124 "Net.OSErrorsForGetAddrinfo_Linux";
Fabrice de Gans-Riberi7de47372018-05-08 20:23:47125#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]24f4bab2010-10-15 01:27:11126 "Net.OSErrorsForGetAddrinfo";
127#endif
128
[email protected]c89b2442011-05-26 14:28:27129// Gets a list of the likely error codes that getaddrinfo() can return
130// (non-exhaustive). These are the error codes that we will track via
131// a histogram.
132std::vector<int> GetAllGetAddrinfoOSErrors() {
133 int os_errors[] = {
Fabrice de Gans-Riberi7de47372018-05-08 20:23:47134#if defined(OS_WIN)
135 // See: http://msdn.microsoft.com/en-us/library/ms738520(VS.85).aspx
136 WSA_NOT_ENOUGH_MEMORY,
137 WSAEAFNOSUPPORT,
138 WSAEINVAL,
139 WSAESOCKTNOSUPPORT,
140 WSAHOST_NOT_FOUND,
141 WSANO_DATA,
142 WSANO_RECOVERY,
143 WSANOTINITIALISED,
144 WSATRY_AGAIN,
145 WSATYPE_NOT_FOUND,
146 // The following are not in doc, but might be to appearing in results :-(.
147 WSA_INVALID_HANDLE,
148#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]23f771162011-06-02 18:37:51149#if !defined(OS_FREEBSD)
[email protected]39588992011-07-11 19:54:37150#if !defined(OS_ANDROID)
[email protected]c48aef92011-11-22 23:41:45151 // EAI_ADDRFAMILY has been declared obsolete in Android's and
152 // FreeBSD's netdb.h.
[email protected]c89b2442011-05-26 14:28:27153 EAI_ADDRFAMILY,
[email protected]39588992011-07-11 19:54:37154#endif
[email protected]c48aef92011-11-22 23:41:45155 // EAI_NODATA has been declared obsolete in FreeBSD's netdb.h.
[email protected]23f771162011-06-02 18:37:51156 EAI_NODATA,
157#endif
[email protected]c89b2442011-05-26 14:28:27158 EAI_AGAIN,
159 EAI_BADFLAGS,
160 EAI_FAIL,
161 EAI_FAMILY,
162 EAI_MEMORY,
[email protected]c89b2442011-05-26 14:28:27163 EAI_NONAME,
164 EAI_SERVICE,
165 EAI_SOCKTYPE,
166 EAI_SYSTEM,
[email protected]c89b2442011-05-26 14:28:27167#endif
168 };
169
170 // Ensure all errors are positive, as histogram only tracks positive values.
171 for (size_t i = 0; i < arraysize(os_errors); ++i) {
172 os_errors[i] = std::abs(os_errors[i]);
173 }
174
Ryan Sleevi9c79c3542018-05-12 01:38:09175 return base::CustomHistogram::ArrayToCustomEnumRanges(os_errors);
[email protected]c89b2442011-05-26 14:28:27176}
177
[email protected]1def74c2012-03-22 20:07:00178enum DnsResolveStatus {
179 RESOLVE_STATUS_DNS_SUCCESS = 0,
180 RESOLVE_STATUS_PROC_SUCCESS,
181 RESOLVE_STATUS_FAIL,
[email protected]1d932852012-06-19 19:40:33182 RESOLVE_STATUS_SUSPECT_NETBIOS,
[email protected]1def74c2012-03-22 20:07:00183 RESOLVE_STATUS_MAX
184};
185
eroman91dd3602015-03-26 03:46:33186// ICANN uses this localhost address to indicate a name collision.
187//
188// The policy in Chromium is to fail host resolving if it resolves to
189// this special address.
190//
191// Not however that IP literals are exempt from this policy, so it is still
192// possible to navigate to http://127.0.53.53/ directly.
193//
194// For more details: https://www.icann.org/news/announcement-2-2014-08-01-en
martijna23c8962016-03-04 18:18:51195const uint8_t kIcanNameCollisionIp[] = {127, 0, 53, 53};
eroman91dd3602015-03-26 03:46:33196
eroman1efc237c2016-12-14 00:00:45197bool ContainsIcannNameCollisionIp(const AddressList& addr_list) {
198 for (const auto& endpoint : addr_list) {
199 const IPAddress& addr = endpoint.address();
200 if (addr.IsIPv4() && IPAddressStartsWith(addr, kIcanNameCollisionIp)) {
201 return true;
202 }
203 }
204 return false;
205}
206
[email protected]1def74c2012-03-22 20:07:00207void UmaAsyncDnsResolveStatus(DnsResolveStatus result) {
208 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ResolveStatus",
209 result,
210 RESOLVE_STATUS_MAX);
211}
212
[email protected]1d932852012-06-19 19:40:33213bool ResemblesNetBIOSName(const std::string& hostname) {
214 return (hostname.size() < 16) && (hostname.find('.') == std::string::npos);
215}
216
217// True if |hostname| ends with either ".local" or ".local.".
218bool ResemblesMulticastDNSName(const std::string& hostname) {
219 DCHECK(!hostname.empty());
220 const char kSuffix[] = ".local.";
221 const size_t kSuffixLen = sizeof(kSuffix) - 1;
222 const size_t kSuffixLenTrimmed = kSuffixLen - 1;
thestiga74ad2b2016-07-11 20:52:36223 if (hostname.back() == '.') {
[email protected]1d932852012-06-19 19:40:33224 return hostname.size() > kSuffixLen &&
225 !hostname.compare(hostname.size() - kSuffixLen, kSuffixLen, kSuffix);
226 }
227 return hostname.size() > kSuffixLenTrimmed &&
228 !hostname.compare(hostname.size() - kSuffixLenTrimmed, kSuffixLenTrimmed,
229 kSuffix, kSuffixLenTrimmed);
230}
231
[email protected]51b9a6b2012-06-25 21:50:29232// A macro to simplify code and readability.
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21233#define DNS_HISTOGRAM_BY_PRIORITY(basename, priority, time) \
234 do { \
235 switch (priority) { \
236 case HIGHEST: \
Miriam Gershenson90d05e02017-09-28 19:29:28237 UMA_HISTOGRAM_LONG_TIMES_100(basename ".HIGHEST", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21238 break; \
239 case MEDIUM: \
Miriam Gershenson90d05e02017-09-28 19:29:28240 UMA_HISTOGRAM_LONG_TIMES_100(basename ".MEDIUM", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21241 break; \
242 case LOW: \
Miriam Gershenson90d05e02017-09-28 19:29:28243 UMA_HISTOGRAM_LONG_TIMES_100(basename ".LOW", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21244 break; \
245 case LOWEST: \
Miriam Gershenson90d05e02017-09-28 19:29:28246 UMA_HISTOGRAM_LONG_TIMES_100(basename ".LOWEST", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21247 break; \
248 case IDLE: \
Miriam Gershenson90d05e02017-09-28 19:29:28249 UMA_HISTOGRAM_LONG_TIMES_100(basename ".IDLE", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21250 break; \
251 case THROTTLED: \
Miriam Gershenson90d05e02017-09-28 19:29:28252 UMA_HISTOGRAM_LONG_TIMES_100(basename ".THROTTLED", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21253 break; \
254 } \
255 UMA_HISTOGRAM_LONG_TIMES_100(basename, time); \
[email protected]51b9a6b2012-06-25 21:50:29256 } while (0)
257
258// Record time from Request creation until a valid DNS response.
Miriam Gershenson90d05e02017-09-28 19:29:28259void RecordTotalTime(bool speculative,
260 bool from_cache,
[email protected]51b9a6b2012-06-25 21:50:29261 base::TimeDelta duration) {
Miriam Gershenson7ba03e12018-02-07 22:48:24262 if (!speculative) {
Miriam Gershenson90d05e02017-09-28 19:29:28263 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.TotalTime", duration);
Miriam Gershenson90d05e02017-09-28 19:29:28264
Miriam Gershenson7ba03e12018-02-07 22:48:24265 if (!from_cache)
Miriam Gershenson90d05e02017-09-28 19:29:28266 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.TotalTimeNotCached", duration);
[email protected]51b9a6b2012-06-25 21:50:29267 }
268}
269
[email protected]1339a2a22012-10-17 08:39:43270void RecordTTL(base::TimeDelta ttl) {
271 UMA_HISTOGRAM_CUSTOM_TIMES("AsyncDNS.TTL", ttl,
272 base::TimeDelta::FromSeconds(1),
273 base::TimeDelta::FromDays(1), 100);
274}
275
[email protected]16c2bd72013-06-28 01:19:22276bool ConfigureAsyncDnsNoFallbackFieldTrial() {
277 const bool kDefault = false;
278
279 // Configure the AsyncDns field trial as follows:
280 // groups AsyncDnsNoFallbackA and AsyncDnsNoFallbackB: return true,
281 // groups AsyncDnsA and AsyncDnsB: return false,
282 // groups SystemDnsA and SystemDnsB: return false,
283 // otherwise (trial absent): return default.
284 std::string group_name = base::FieldTrialList::FindFullName("AsyncDns");
brettw3a2c6902015-07-06 19:43:29285 if (!group_name.empty()) {
286 return base::StartsWith(group_name, "AsyncDnsNoFallback",
287 base::CompareCase::INSENSITIVE_ASCII);
288 }
[email protected]16c2bd72013-06-28 01:19:22289 return kDefault;
290}
291
Maks Orlovich5393c8682018-02-26 16:17:50292const base::FeatureParam<base::TaskPriority>::Option prio_modes[] = {
293 {base::TaskPriority::USER_VISIBLE, "default"},
294 {base::TaskPriority::USER_BLOCKING, "user_blocking"}};
295const base::Feature kSystemResolverPriorityExperiment = {
296 "SystemResolverPriorityExperiment", base::FEATURE_DISABLED_BY_DEFAULT};
297const base::FeatureParam<base::TaskPriority> priority_mode{
298 &kSystemResolverPriorityExperiment, "mode",
299 base::TaskPriority::USER_VISIBLE, &prio_modes};
300
[email protected]d7b9a2b2012-05-31 22:31:19301//-----------------------------------------------------------------------------
302
Avi Drissman13fc8932015-12-20 04:40:46303AddressList EnsurePortOnAddressList(const AddressList& list, uint16_t port) {
[email protected]895123222012-10-25 15:21:17304 if (list.empty() || list.front().port() == port)
305 return list;
306 return AddressList::CopyWithPort(list, port);
[email protected]7054e78f2012-05-07 21:44:56307}
308
[email protected]ec666ab22013-04-17 20:05:59309// Returns true if |addresses| contains only IPv4 loopback addresses.
310bool IsAllIPv4Loopback(const AddressList& addresses) {
311 for (unsigned i = 0; i < addresses.size(); ++i) {
martijna23c8962016-03-04 18:18:51312 const IPAddress& address = addresses[i].address();
[email protected]ec666ab22013-04-17 20:05:59313 switch (addresses[i].GetFamily()) {
314 case ADDRESS_FAMILY_IPV4:
martijna23c8962016-03-04 18:18:51315 if (address.bytes()[0] != 127)
[email protected]ec666ab22013-04-17 20:05:59316 return false;
317 break;
318 case ADDRESS_FAMILY_IPV6:
319 return false;
320 default:
321 NOTREACHED();
322 return false;
323 }
324 }
325 return true;
326}
327
tfarinada9e1362017-03-14 16:49:06328// Returns true if it can determine that only loopback addresses are configured.
329// i.e. if only 127.0.0.1 and ::1 are routable.
330// Also returns false if it cannot determine this.
331bool HaveOnlyLoopbackAddresses() {
Francois Doraya2d01ba2017-09-25 19:17:40332 base::ScopedBlockingCall scoped_blocking_call(base::BlockingType::WILL_BLOCK);
Fabrice de Gans-Riberi7de47372018-05-08 20:23:47333#if defined(OS_WIN)
334 // TODO(wtc): implement with the GetAdaptersAddresses function.
335 NOTIMPLEMENTED();
336 return false;
337#elif defined(OS_ANDROID)
tfarinada9e1362017-03-14 16:49:06338 return android::HaveOnlyLoopbackAddresses();
339#elif defined(OS_NACL)
340 NOTIMPLEMENTED();
341 return false;
Fabrice de Gans-Riberi7de47372018-05-08 20:23:47342#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
tfarinada9e1362017-03-14 16:49:06343 struct ifaddrs* interface_addr = NULL;
344 int rv = getifaddrs(&interface_addr);
345 if (rv != 0) {
346 DVLOG(1) << "getifaddrs() failed with errno = " << errno;
347 return false;
348 }
349
350 bool result = true;
351 for (struct ifaddrs* interface = interface_addr;
352 interface != NULL;
353 interface = interface->ifa_next) {
354 if (!(IFF_UP & interface->ifa_flags))
355 continue;
356 if (IFF_LOOPBACK & interface->ifa_flags)
357 continue;
358 const struct sockaddr* addr = interface->ifa_addr;
359 if (!addr)
360 continue;
361 if (addr->sa_family == AF_INET6) {
362 // Safe cast since this is AF_INET6.
363 const struct sockaddr_in6* addr_in6 =
364 reinterpret_cast<const struct sockaddr_in6*>(addr);
365 const struct in6_addr* sin6_addr = &addr_in6->sin6_addr;
366 if (IN6_IS_ADDR_LOOPBACK(sin6_addr) || IN6_IS_ADDR_LINKLOCAL(sin6_addr))
367 continue;
368 }
369 if (addr->sa_family != AF_INET6 && addr->sa_family != AF_INET)
370 continue;
371
372 result = false;
373 break;
374 }
375 freeifaddrs(interface_addr);
376 return result;
tfarinada9e1362017-03-14 16:49:06377#endif // defined(various platforms)
378}
379
[email protected]cd565142012-06-12 16:21:45380// Creates NetLog parameters when the resolve failed.
danakj22f90e72016-04-16 01:55:40381std::unique_ptr<base::Value> NetLogProcTaskFailedCallback(
Avi Drissman13fc8932015-12-20 04:40:46382 uint32_t attempt_number,
eroman001c3742015-04-23 03:11:17383 int net_error,
384 int os_error,
385 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40386 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]cd565142012-06-12 16:21:45387 if (attempt_number)
388 dict->SetInteger("attempt_number", attempt_number);
[email protected]21526002010-05-16 19:42:46389
[email protected]cd565142012-06-12 16:21:45390 dict->SetInteger("net_error", net_error);
[email protected]13024882011-05-18 23:19:16391
[email protected]cd565142012-06-12 16:21:45392 if (os_error) {
393 dict->SetInteger("os_error", os_error);
Fabrice de Gans-Riberi7de47372018-05-08 20:23:47394#if defined(OS_WIN)
[email protected]cd565142012-06-12 16:21:45395 // Map the error code to a human-readable string.
wezb9820d42016-06-22 23:41:04396 LPWSTR error_string = nullptr;
Peter Kastingbe940e92014-11-20 23:14:08397 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
398 0, // Use the internal message table.
399 os_error,
400 0, // Use default language.
401 (LPWSTR)&error_string,
402 0, // Buffer size.
403 0); // Arguments (unused).
[email protected]ad65a3e2013-12-25 18:18:01404 dict->SetString("os_error_string", base::WideToUTF8(error_string));
[email protected]cd565142012-06-12 16:21:45405 LocalFree(error_string);
Fabrice de Gans-Riberi7de47372018-05-08 20:23:47406#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
407 dict->SetString("os_error_string", gai_strerror(os_error));
[email protected]21526002010-05-16 19:42:46408#endif
[email protected]21526002010-05-16 19:42:46409 }
410
dchengc7eeda422015-12-26 03:56:48411 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45412}
[email protected]a9813302012-04-28 09:29:28413
[email protected]cd565142012-06-12 16:21:45414// Creates NetLog parameters when the DnsTask failed.
danakj22f90e72016-04-16 01:55:40415std::unique_ptr<base::Value> NetLogDnsTaskFailedCallback(
estade5e5529d2015-05-21 20:59:11416 int net_error,
417 int dns_error,
418 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40419 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]cd565142012-06-12 16:21:45420 dict->SetInteger("net_error", net_error);
421 if (dns_error)
422 dict->SetInteger("dns_error", dns_error);
dchengc7eeda422015-12-26 03:56:48423 return std::move(dict);
thestiga74ad2b2016-07-11 20:52:36424}
[email protected]ee094b82010-08-24 15:55:51425
[email protected]cd565142012-06-12 16:21:45426// Creates NetLog parameters containing the information in a RequestInfo object,
mikecironef22f9812016-10-04 03:40:19427// along with the associated NetLogSource.
danakj22f90e72016-04-16 01:55:40428std::unique_ptr<base::Value> NetLogRequestInfoCallback(
estade5e5529d2015-05-21 20:59:11429 const HostResolver::RequestInfo* info,
430 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40431 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]b3601bc22012-02-21 21:23:20432
[email protected]cd565142012-06-12 16:21:45433 dict->SetString("host", info->host_port_pair().ToString());
434 dict->SetInteger("address_family",
435 static_cast<int>(info->address_family()));
436 dict->SetBoolean("allow_cached_response", info->allow_cached_response());
437 dict->SetBoolean("is_speculative", info->is_speculative());
dchengc7eeda422015-12-26 03:56:48438 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45439}
[email protected]b3601bc22012-02-21 21:23:20440
[email protected]cd565142012-06-12 16:21:45441// Creates NetLog parameters for the creation of a HostResolverImpl::Job.
danakj22f90e72016-04-16 01:55:40442std::unique_ptr<base::Value> NetLogJobCreationCallback(
mikecironef22f9812016-10-04 03:40:19443 const NetLogSource& source,
estade5e5529d2015-05-21 20:59:11444 const std::string* host,
445 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40446 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
estade5e5529d2015-05-21 20:59:11447 source.AddToEventParameters(dict.get());
[email protected]cd565142012-06-12 16:21:45448 dict->SetString("host", *host);
dchengc7eeda422015-12-26 03:56:48449 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45450}
[email protected]a9813302012-04-28 09:29:28451
[email protected]cd565142012-06-12 16:21:45452// Creates NetLog parameters for HOST_RESOLVER_IMPL_JOB_ATTACH/DETACH events.
danakj22f90e72016-04-16 01:55:40453std::unique_ptr<base::Value> NetLogJobAttachCallback(
mikecironef22f9812016-10-04 03:40:19454 const NetLogSource& source,
estade5e5529d2015-05-21 20:59:11455 RequestPriority priority,
456 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40457 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
estade5e5529d2015-05-21 20:59:11458 source.AddToEventParameters(dict.get());
[email protected]3b04d1f22013-10-16 00:23:56459 dict->SetString("priority", RequestPriorityToString(priority));
dchengc7eeda422015-12-26 03:56:48460 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45461}
[email protected]b3601bc22012-02-21 21:23:20462
[email protected]cd565142012-06-12 16:21:45463// Creates NetLog parameters for the DNS_CONFIG_CHANGED event.
danakj22f90e72016-04-16 01:55:40464std::unique_ptr<base::Value> NetLogDnsConfigCallback(
estade5e5529d2015-05-21 20:59:11465 const DnsConfig* config,
466 NetLogCaptureMode /* capture_mode */) {
tfhef3618f2016-01-11 23:07:08467 return config->ToValue();
[email protected]cd565142012-06-12 16:21:45468}
[email protected]b4481b222012-03-16 17:13:11469
danakj22f90e72016-04-16 01:55:40470std::unique_ptr<base::Value> NetLogIPv6AvailableCallback(
estade5e5529d2015-05-21 20:59:11471 bool ipv6_available,
472 bool cached,
473 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40474 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
sergeyub8cdc212015-05-14 18:50:37475 dict->SetBoolean("ipv6_available", ipv6_available);
476 dict->SetBoolean("cached", cached);
dchengc7eeda422015-12-26 03:56:48477 return std::move(dict);
sergeyub8cdc212015-05-14 18:50:37478}
479
[email protected]0f292de02012-02-01 22:28:20480// The logging routines are defined here because some requests are resolved
481// without a Request object.
482
483// Logs when a request has just been started.
tfarina428341112016-09-22 13:38:20484void LogStartRequest(const NetLogWithSource& source_net_log,
[email protected]0f292de02012-02-01 22:28:20485 const HostResolver::RequestInfo& info) {
mikecirone8b85c432016-09-08 19:11:00486 source_net_log.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_REQUEST,
487 base::Bind(&NetLogRequestInfoCallback, &info));
[email protected]0f292de02012-02-01 22:28:20488}
489
490// Logs when a request has just completed (before its callback is run).
tfarina428341112016-09-22 13:38:20491void LogFinishRequest(const NetLogWithSource& source_net_log,
[email protected]0f292de02012-02-01 22:28:20492 const HostResolver::RequestInfo& info,
[email protected]b3601bc22012-02-21 21:23:20493 int net_error) {
xunjieli26f90452014-11-10 16:23:02494 source_net_log.EndEventWithNetErrorCode(
mikecirone8b85c432016-09-08 19:11:00495 NetLogEventType::HOST_RESOLVER_IMPL_REQUEST, net_error);
[email protected]0f292de02012-02-01 22:28:20496}
497
498// Logs when a request has been cancelled.
tfarina428341112016-09-22 13:38:20499void LogCancelRequest(const NetLogWithSource& source_net_log,
[email protected]0f292de02012-02-01 22:28:20500 const HostResolverImpl::RequestInfo& info) {
mikecirone8b85c432016-09-08 19:11:00501 source_net_log.AddEvent(NetLogEventType::CANCELLED);
502 source_net_log.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_REQUEST);
[email protected]0f292de02012-02-01 22:28:20503}
504
[email protected]b59ff372009-07-15 22:04:32505//-----------------------------------------------------------------------------
506
[email protected]0f292de02012-02-01 22:28:20507// Keeps track of the highest priority.
508class PriorityTracker {
509 public:
[email protected]8c98d002012-07-18 19:02:27510 explicit PriorityTracker(RequestPriority initial_priority)
511 : highest_priority_(initial_priority), total_count_(0) {
[email protected]0f292de02012-02-01 22:28:20512 memset(counts_, 0, sizeof(counts_));
513 }
514
515 RequestPriority highest_priority() const {
516 return highest_priority_;
517 }
518
519 size_t total_count() const {
520 return total_count_;
521 }
522
523 void Add(RequestPriority req_priority) {
524 ++total_count_;
525 ++counts_[req_priority];
[email protected]31ae7ab2012-04-24 21:09:05526 if (highest_priority_ < req_priority)
[email protected]0f292de02012-02-01 22:28:20527 highest_priority_ = req_priority;
528 }
529
530 void Remove(RequestPriority req_priority) {
531 DCHECK_GT(total_count_, 0u);
532 DCHECK_GT(counts_[req_priority], 0u);
533 --total_count_;
534 --counts_[req_priority];
535 size_t i;
thestiga74ad2b2016-07-11 20:52:36536 for (i = highest_priority_; i > MINIMUM_PRIORITY && !counts_[i]; --i) {
537 }
[email protected]0f292de02012-02-01 22:28:20538 highest_priority_ = static_cast<RequestPriority>(i);
539
[email protected]31ae7ab2012-04-24 21:09:05540 // In absence of requests, default to MINIMUM_PRIORITY.
541 if (total_count_ == 0)
542 DCHECK_EQ(MINIMUM_PRIORITY, highest_priority_);
[email protected]0f292de02012-02-01 22:28:20543 }
544
545 private:
546 RequestPriority highest_priority_;
547 size_t total_count_;
548 size_t counts_[NUM_PRIORITIES];
549};
550
juliatuttle9fb7aeb2016-06-06 20:16:33551void MakeNotStale(HostCache::EntryStaleness* stale_info) {
552 if (!stale_info)
553 return;
554 stale_info->expired_by = base::TimeDelta::FromSeconds(-1);
555 stale_info->network_changes = 0;
556 stale_info->stale_hits = 0;
557}
558
[email protected]c54a8912012-10-22 22:09:43559} // namespace
[email protected]0f292de02012-02-01 22:28:20560
561//-----------------------------------------------------------------------------
562
tfarina9ed7f8c52016-02-19 17:50:18563bool ResolveLocalHostname(base::StringPiece host,
564 uint16_t port,
565 AddressList* address_list) {
tfarina9ed7f8c52016-02-19 17:50:18566 address_list->clear();
567
568 bool is_local6;
569 if (!IsLocalHostname(host, &is_local6))
570 return false;
571
martijna23c8962016-03-04 18:18:51572 address_list->push_back(IPEndPoint(IPAddress::IPv6Localhost(), port));
tfarina9ed7f8c52016-02-19 17:50:18573 if (!is_local6) {
martijna23c8962016-03-04 18:18:51574 address_list->push_back(IPEndPoint(IPAddress::IPv4Localhost(), port));
tfarina9ed7f8c52016-02-19 17:50:18575 }
576
577 return true;
578}
579
[email protected]daae1322013-09-05 18:26:50580const unsigned HostResolverImpl::kMaximumDnsFailures = 16;
581
Eric Roman91aab1e62018-04-24 20:31:32582// Holds the callback and request parameters for an outstanding request.
583//
584// The RequestImpl is owned by the end user of host resolution. Deletion prior
585// to the request having completed means the request was cancelled by the
586// caller.
587//
588// Both the RequestImpl and its associated Job hold non-owning pointers to each
589// other. Care must be taken to clear the corresponding pointer when
590// cancellation is initiated by the Job (OnJobCancelled) vs by the end user
591// (~RequestImpl).
David Benjamina5677192018-04-23 23:25:42592class HostResolverImpl::RequestImpl
593 : public HostResolver::Request,
594 public base::LinkNode<HostResolverImpl::RequestImpl> {
[email protected]b59ff372009-07-15 22:04:32595 public:
tfarina428341112016-09-22 13:38:20596 RequestImpl(const NetLogWithSource& source_net_log,
maksim.sisov31452af2016-07-27 06:38:10597 const RequestInfo& info,
598 RequestPriority priority,
599 const CompletionCallback& callback,
600 AddressList* addresses,
601 Job* job)
[email protected]ee094b82010-08-24 15:55:51602 : source_net_log_(source_net_log),
[email protected]54e13772009-08-14 03:01:09603 info_(info),
[email protected]5109c1952013-08-20 18:44:10604 priority_(priority),
maksim.sisov31452af2016-07-27 06:38:10605 job_(job),
[email protected]54e13772009-08-14 03:01:09606 callback_(callback),
[email protected]51b9a6b2012-06-25 21:50:29607 addresses_(addresses),
[email protected]5109c1952013-08-20 18:44:10608 request_time_(base::TimeTicks::Now()) {}
[email protected]b59ff372009-07-15 22:04:32609
maksim.sisov31452af2016-07-27 06:38:10610 ~RequestImpl() override;
611
612 void ChangeRequestPriority(RequestPriority priority) override;
613
614 void OnJobCancelled(Job* job) {
615 DCHECK_EQ(job_, job);
wezb9820d42016-06-22 23:41:04616 job_ = nullptr;
617 addresses_ = nullptr;
[email protected]aa22b242011-11-16 18:58:29618 callback_.Reset();
[email protected]b59ff372009-07-15 22:04:32619 }
620
[email protected]0f292de02012-02-01 22:28:20621 // Prepare final AddressList and call completion callback.
maksim.sisov31452af2016-07-27 06:38:10622 void OnJobCompleted(Job* job, int error, const AddressList& addr_list) {
623 DCHECK_EQ(job_, job);
[email protected]895123222012-10-25 15:21:17624 if (error == OK)
625 *addresses_ = EnsurePortOnAddressList(addr_list, info_.port());
maksim.sisov31452af2016-07-27 06:38:10626 job_ = nullptr;
627 addresses_ = nullptr;
628 base::ResetAndReturn(&callback_).Run(error);
[email protected]b59ff372009-07-15 22:04:32629 }
630
[email protected]b59ff372009-07-15 22:04:32631 Job* job() const {
632 return job_;
633 }
634
[email protected]0f292de02012-02-01 22:28:20635 // NetLog for the source, passed in HostResolver::Resolve.
tfarina428341112016-09-22 13:38:20636 const NetLogWithSource& source_net_log() { return source_net_log_; }
[email protected]ee094b82010-08-24 15:55:51637
[email protected]b59ff372009-07-15 22:04:32638 const RequestInfo& info() const {
639 return info_;
640 }
641
[email protected]5109c1952013-08-20 18:44:10642 RequestPriority priority() const { return priority_; }
juliatuttlec53b19a72016-05-05 13:51:31643 void set_priority(RequestPriority priority) { priority_ = priority; }
[email protected]5109c1952013-08-20 18:44:10644
645 base::TimeTicks request_time() const { return request_time_; }
[email protected]51b9a6b2012-06-25 21:50:29646
[email protected]b59ff372009-07-15 22:04:32647 private:
tfarina428341112016-09-22 13:38:20648 const NetLogWithSource source_net_log_;
[email protected]54e13772009-08-14 03:01:09649
[email protected]b59ff372009-07-15 22:04:32650 // The request info that started the request.
[email protected]5109c1952013-08-20 18:44:10651 const RequestInfo info_;
652
juliatuttlec53b19a72016-05-05 13:51:31653 RequestPriority priority_;
[email protected]b59ff372009-07-15 22:04:32654
[email protected]0f292de02012-02-01 22:28:20655 // The resolve job that this request is dependent on.
[email protected]b59ff372009-07-15 22:04:32656 Job* job_;
657
658 // The user's callback to invoke when the request completes.
[email protected]aa22b242011-11-16 18:58:29659 CompletionCallback callback_;
[email protected]b59ff372009-07-15 22:04:32660
661 // The address list to save result into.
662 AddressList* addresses_;
663
[email protected]51b9a6b2012-06-25 21:50:29664 const base::TimeTicks request_time_;
665
maksim.sisov31452af2016-07-27 06:38:10666 DISALLOW_COPY_AND_ASSIGN(RequestImpl);
[email protected]b59ff372009-07-15 22:04:32667};
668
[email protected]1e9bbd22010-10-15 16:42:45669//------------------------------------------------------------------------------
670
Francois Doraya2d01ba2017-09-25 19:17:40671// Calls HostResolverProc in TaskScheduler. Performs retries if necessary.
[email protected]0f292de02012-02-01 22:28:20672//
Miriam Gershenson02592182018-03-22 17:42:37673// In non-test code, the HostResolverProc is always SystemHostResolverProc,
674// which calls a platform API that implements host resolution.
675//
[email protected]0f292de02012-02-01 22:28:20676// Whenever we try to resolve the host, we post a delayed task to check if host
677// resolution (OnLookupComplete) is completed or not. If the original attempt
678// hasn't completed, then we start another attempt for host resolution. We take
679// the results from the first attempt that finishes and ignore the results from
680// all other attempts.
681//
682// TODO(szym): Move to separate source file for testing and mocking.
683//
684class HostResolverImpl::ProcTask
685 : public base::RefCountedThreadSafe<HostResolverImpl::ProcTask> {
[email protected]b59ff372009-07-15 22:04:32686 public:
[email protected]b3601bc22012-02-21 21:23:20687 typedef base::Callback<void(int net_error,
688 const AddressList& addr_list)> Callback;
[email protected]b59ff372009-07-15 22:04:32689
[email protected]0f292de02012-02-01 22:28:20690 ProcTask(const Key& key,
691 const ProcTaskParams& params,
692 const Callback& callback,
Miriam Gershensone42adb22017-10-16 16:19:38693 scoped_refptr<base::TaskRunner> proc_task_runner,
tfarina428341112016-09-22 13:38:20694 const NetLogWithSource& job_net_log)
[email protected]0f292de02012-02-01 22:28:20695 : key_(key),
696 params_(params),
697 callback_(callback),
mmenke91c17162016-06-02 16:03:23698 network_task_runner_(base::ThreadTaskRunnerHandle::Get()),
Miriam Gershensone42adb22017-10-16 16:19:38699 proc_task_runner_(std::move(proc_task_runner)),
[email protected]0f292de02012-02-01 22:28:20700 attempt_number_(0),
701 completed_attempt_number_(0),
702 completed_attempt_error_(ERR_UNEXPECTED),
[email protected]b3601bc22012-02-21 21:23:20703 net_log_(job_net_log) {
[email protected]90499482013-06-01 00:39:50704 if (!params_.resolver_proc.get())
[email protected]0f292de02012-02-01 22:28:20705 params_.resolver_proc = HostResolverProc::GetDefault();
706 // If default is unset, use the system proc.
[email protected]90499482013-06-01 00:39:50707 if (!params_.resolver_proc.get())
[email protected]1ee9afa12013-04-16 14:18:06708 params_.resolver_proc = new SystemHostResolverProc();
[email protected]b59ff372009-07-15 22:04:32709 }
710
[email protected]b59ff372009-07-15 22:04:32711 void Start() {
mmenke91c17162016-06-02 16:03:23712 DCHECK(network_task_runner_->BelongsToCurrentThread());
mikecirone8b85c432016-09-08 19:11:00713 net_log_.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_PROC_TASK);
[email protected]189163e2011-05-11 01:48:54714 StartLookupAttempt();
715 }
[email protected]252b699b2010-02-05 21:38:06716
[email protected]0f292de02012-02-01 22:28:20717 // Cancels this ProcTask. It will be orphaned. Any outstanding resolve
mmenke91c17162016-06-02 16:03:23718 // attempts running on worker thread will continue running. Only once all the
[email protected]0f292de02012-02-01 22:28:20719 // attempts complete will the final reference to this ProcTask be released.
720 void Cancel() {
mmenke91c17162016-06-02 16:03:23721 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20722
[email protected]0adcb2b2012-08-15 21:30:46723 if (was_canceled() || was_completed())
[email protected]0f292de02012-02-01 22:28:20724 return;
725
[email protected]0f292de02012-02-01 22:28:20726 callback_.Reset();
mikecirone8b85c432016-09-08 19:11:00727 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_PROC_TASK);
[email protected]0f292de02012-02-01 22:28:20728 }
729
[email protected]0f292de02012-02-01 22:28:20730 bool was_canceled() const {
mmenke91c17162016-06-02 16:03:23731 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20732 return callback_.is_null();
733 }
734
735 bool was_completed() const {
mmenke91c17162016-06-02 16:03:23736 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20737 return completed_attempt_number_ > 0;
738 }
739
740 private:
[email protected]a9813302012-04-28 09:29:28741 friend class base::RefCountedThreadSafe<ProcTask>;
Chris Watkins68b15032017-12-01 03:07:13742 ~ProcTask() = default;
[email protected]a9813302012-04-28 09:29:28743
[email protected]189163e2011-05-11 01:48:54744 void StartLookupAttempt() {
mmenke91c17162016-06-02 16:03:23745 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54746 base::TimeTicks start_time = base::TimeTicks::Now();
747 ++attempt_number_;
748 // Dispatch the lookup attempt to a worker thread.
Miriam Gershensone42adb22017-10-16 16:19:38749 proc_task_runner_->PostTask(
Francois Doraya2d01ba2017-09-25 19:17:40750 FROM_HERE,
Francois Doraya2d01ba2017-09-25 19:17:40751 base::Bind(&ProcTask::DoLookup, this, start_time, attempt_number_));
[email protected]13024882011-05-18 23:19:16752
mikecirone8b85c432016-09-08 19:11:00753 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_ATTEMPT_STARTED,
tfarina5e24b242015-10-27 13:11:28754 NetLog::IntCallback("attempt_number", attempt_number_));
[email protected]13024882011-05-18 23:19:16755
mmenke91c17162016-06-02 16:03:23756 // If the results aren't received within a given time, RetryIfNotComplete
757 // will start a new attempt if none of the outstanding attempts have
758 // completed yet.
[email protected]0f292de02012-02-01 22:28:20759 if (attempt_number_ <= params_.max_retry_attempts) {
mmenke91c17162016-06-02 16:03:23760 network_task_runner_->PostDelayedTask(
761 FROM_HERE, base::Bind(&ProcTask::RetryIfNotComplete, this),
[email protected]7e560102012-03-08 20:58:42762 params_.unresponsive_delay);
[email protected]06ef6d92011-05-19 04:24:58763 }
[email protected]b59ff372009-07-15 22:04:32764 }
765
Francois Doraya2d01ba2017-09-25 19:17:40766 // WARNING: This code runs in TaskScheduler with CONTINUE_ON_SHUTDOWN. The
767 // shutdown code cannot wait for it to finish, so this code must be very
768 // careful about using other objects (like MessageLoops, Singletons, etc).
769 // During shutdown these objects may no longer exist. Multiple DoLookups()
770 // could be running in parallel, so any state inside of |this| must not
771 // mutate.
[email protected]189163e2011-05-11 01:48:54772 void DoLookup(const base::TimeTicks& start_time,
Avi Drissman13fc8932015-12-20 04:40:46773 const uint32_t attempt_number) {
[email protected]189163e2011-05-11 01:48:54774 AddressList results;
775 int os_error = 0;
[email protected]0f292de02012-02-01 22:28:20776 int error = params_.resolver_proc->Resolve(key_.hostname,
777 key_.address_family,
778 key_.host_resolver_flags,
779 &results,
780 &os_error);
[email protected]b59ff372009-07-15 22:04:32781
mmenke91c17162016-06-02 16:03:23782 network_task_runner_->PostTask(
783 FROM_HERE, base::Bind(&ProcTask::OnLookupComplete, this, results,
784 start_time, attempt_number, error, os_error));
[email protected]189163e2011-05-11 01:48:54785 }
786
mmenke91c17162016-06-02 16:03:23787 // Makes next attempt if DoLookup() has not finished.
[email protected]0f292de02012-02-01 22:28:20788 void RetryIfNotComplete() {
mmenke91c17162016-06-02 16:03:23789 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54790
[email protected]0f292de02012-02-01 22:28:20791 if (was_completed() || was_canceled())
[email protected]189163e2011-05-11 01:48:54792 return;
793
[email protected]0f292de02012-02-01 22:28:20794 params_.unresponsive_delay *= params_.retry_factor;
[email protected]189163e2011-05-11 01:48:54795 StartLookupAttempt();
[email protected]b59ff372009-07-15 22:04:32796 }
797
anujk.sharma7c907f02015-05-29 02:55:44798 // Callback for when DoLookup() completes (runs on task runner thread).
[email protected]189163e2011-05-11 01:48:54799 void OnLookupComplete(const AddressList& results,
800 const base::TimeTicks& start_time,
Avi Drissman13fc8932015-12-20 04:40:46801 const uint32_t attempt_number,
[email protected]189163e2011-05-11 01:48:54802 int error,
803 const int os_error) {
xunjieli0b7f5b62016-12-06 20:43:48804 TRACE_EVENT0(kNetTracingCategory, "ProcTask::OnLookupComplete");
mmenke91c17162016-06-02 16:03:23805 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]49b70b222013-05-07 21:24:23806 // If results are empty, we should return an error.
807 bool empty_list_on_ok = (error == OK && results.empty());
[email protected]49b70b222013-05-07 21:24:23808 if (empty_list_on_ok)
809 error = ERR_NAME_NOT_RESOLVED;
[email protected]189163e2011-05-11 01:48:54810
811 bool was_retry_attempt = attempt_number > 1;
812
[email protected]2d3b7762010-10-09 00:35:47813 // Ideally the following code would be part of host_resolver_proc.cc,
[email protected]b3601bc22012-02-21 21:23:20814 // however it isn't safe to call NetworkChangeNotifier from worker threads.
mmenke91c17162016-06-02 16:03:23815 // So do it here on the IO thread instead.
[email protected]189163e2011-05-11 01:48:54816 if (error != OK && NetworkChangeNotifier::IsOffline())
817 error = ERR_INTERNET_DISCONNECTED;
[email protected]2d3b7762010-10-09 00:35:47818
[email protected]189163e2011-05-11 01:48:54819 RecordAttemptHistograms(start_time, attempt_number, error, os_error);
[email protected]f2d8c4212010-02-02 00:56:35820
[email protected]0f292de02012-02-01 22:28:20821 if (was_canceled())
[email protected]b59ff372009-07-15 22:04:32822 return;
823
mikecironef22f9812016-10-04 03:40:19824 NetLogParametersCallback net_log_callback;
[email protected]0f292de02012-02-01 22:28:20825 if (error != OK) {
[email protected]cd565142012-06-12 16:21:45826 net_log_callback = base::Bind(&NetLogProcTaskFailedCallback,
827 attempt_number,
828 error,
829 os_error);
[email protected]0f292de02012-02-01 22:28:20830 } else {
tfarina5e24b242015-10-27 13:11:28831 net_log_callback = NetLog::IntCallback("attempt_number", attempt_number);
[email protected]0f292de02012-02-01 22:28:20832 }
mikecirone8b85c432016-09-08 19:11:00833 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_ATTEMPT_FINISHED,
[email protected]cd565142012-06-12 16:21:45834 net_log_callback);
[email protected]0f292de02012-02-01 22:28:20835
836 if (was_completed())
837 return;
838
Miriam Gershenson61604662017-09-28 23:51:11839 RecordTaskHistograms(start_time, error, os_error);
840
[email protected]0f292de02012-02-01 22:28:20841 // Copy the results from the first worker thread that resolves the host.
842 results_ = results;
843 completed_attempt_number_ = attempt_number;
844 completed_attempt_error_ = error;
845
[email protected]e87b8b512011-06-14 22:12:52846 if (was_retry_attempt) {
847 // If retry attempt finishes before 1st attempt, then get stats on how
848 // much time is saved by having spawned an extra attempt.
849 retry_attempt_finished_time_ = base::TimeTicks::Now();
850 }
851
[email protected]189163e2011-05-11 01:48:54852 if (error != OK) {
[email protected]cd565142012-06-12 16:21:45853 net_log_callback = base::Bind(&NetLogProcTaskFailedCallback,
854 0, error, os_error);
[email protected]ee094b82010-08-24 15:55:51855 } else {
[email protected]cd565142012-06-12 16:21:45856 net_log_callback = results_.CreateNetLogCallback();
[email protected]ee094b82010-08-24 15:55:51857 }
mikecirone8b85c432016-09-08 19:11:00858 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_PROC_TASK,
[email protected]cd565142012-06-12 16:21:45859 net_log_callback);
[email protected]ee094b82010-08-24 15:55:51860
[email protected]b3601bc22012-02-21 21:23:20861 callback_.Run(error, results_);
[email protected]b59ff372009-07-15 22:04:32862 }
863
Miriam Gershenson61604662017-09-28 23:51:11864 void RecordTaskHistograms(const base::TimeTicks& start_time,
865 const int error,
866 const int os_error) const {
mmenke91c17162016-06-02 16:03:23867 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54868 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
Miriam Gershenson61604662017-09-28 23:51:11869 if (error == OK)
870 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ProcTask.SuccessTime", duration);
871 else
872 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ProcTask.FailureTime", duration);
[email protected]7e96d792011-06-10 17:08:23873
Miriam Gershenson61604662017-09-28 23:51:11874 UMA_HISTOGRAM_CUSTOM_ENUMERATION(kOSErrorsForGetAddrinfoHistogramName,
875 std::abs(os_error),
876 GetAllGetAddrinfoOSErrors());
[email protected]1e9bbd22010-10-15 16:42:45877 }
878
[email protected]189163e2011-05-11 01:48:54879 void RecordAttemptHistograms(const base::TimeTicks& start_time,
Avi Drissman13fc8932015-12-20 04:40:46880 const uint32_t attempt_number,
[email protected]189163e2011-05-11 01:48:54881 const int error,
882 const int os_error) const {
mmenke91c17162016-06-02 16:03:23883 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54884 bool first_attempt_to_complete =
885 completed_attempt_number_ == attempt_number;
[email protected]e87b8b512011-06-14 22:12:52886 bool is_first_attempt = (attempt_number == 1);
[email protected]1e9bbd22010-10-15 16:42:45887
[email protected]189163e2011-05-11 01:48:54888 if (first_attempt_to_complete) {
889 // If this was first attempt to complete, then record the resolution
890 // status of the attempt.
891 if (completed_attempt_error_ == OK) {
892 UMA_HISTOGRAM_ENUMERATION(
893 "DNS.AttemptFirstSuccess", attempt_number, 100);
894 } else {
895 UMA_HISTOGRAM_ENUMERATION(
896 "DNS.AttemptFirstFailure", attempt_number, 100);
897 }
898 }
899
900 if (error == OK)
901 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptSuccess", attempt_number, 100);
902 else
903 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptFailure", attempt_number, 100);
904
[email protected]e87b8b512011-06-14 22:12:52905 // If first attempt didn't finish before retry attempt, then calculate stats
906 // on how much time is saved by having spawned an extra attempt.
[email protected]0f292de02012-02-01 22:28:20907 if (!first_attempt_to_complete && is_first_attempt && !was_canceled()) {
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21908 UMA_HISTOGRAM_LONG_TIMES_100(
909 "DNS.AttemptTimeSavedByRetry",
910 base::TimeTicks::Now() - retry_attempt_finished_time_);
[email protected]e87b8b512011-06-14 22:12:52911 }
912
[email protected]0f292de02012-02-01 22:28:20913 if (was_canceled() || !first_attempt_to_complete) {
[email protected]189163e2011-05-11 01:48:54914 // Count those attempts which completed after the job was already canceled
915 // OR after the job was already completed by an earlier attempt (so in
916 // effect).
917 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptDiscarded", attempt_number, 100);
918
[email protected]0f292de02012-02-01 22:28:20919 // Record if job is canceled.
920 if (was_canceled())
[email protected]189163e2011-05-11 01:48:54921 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptCancelled", attempt_number, 100);
922 }
923
924 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
925 if (error == OK)
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21926 UMA_HISTOGRAM_LONG_TIMES_100("DNS.AttemptSuccessDuration", duration);
[email protected]189163e2011-05-11 01:48:54927 else
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21928 UMA_HISTOGRAM_LONG_TIMES_100("DNS.AttemptFailDuration", duration);
[email protected]189163e2011-05-11 01:48:54929 }
[email protected]1e9bbd22010-10-15 16:42:45930
anujk.sharma7c907f02015-05-29 02:55:44931 // Set on the task runner thread, read on the worker thread.
[email protected]123ab1e32009-10-21 19:12:57932 Key key_;
[email protected]b59ff372009-07-15 22:04:32933
[email protected]0f292de02012-02-01 22:28:20934 // Holds an owning reference to the HostResolverProc that we are going to use.
[email protected]b59ff372009-07-15 22:04:32935 // This may not be the current resolver procedure by the time we call
936 // ResolveAddrInfo, but that's OK... we'll use it anyways, and the owning
937 // reference ensures that it remains valid until we are done.
[email protected]0f292de02012-02-01 22:28:20938 ProcTaskParams params_;
[email protected]b59ff372009-07-15 22:04:32939
[email protected]0f292de02012-02-01 22:28:20940 // The listener to the results of this ProcTask.
941 Callback callback_;
942
mmenke91c17162016-06-02 16:03:23943 // Used to post events onto the network thread.
944 scoped_refptr<base::SingleThreadTaskRunner> network_task_runner_;
Miriam Gershensone42adb22017-10-16 16:19:38945 // Used to post blocking HostResolverProc tasks.
946 scoped_refptr<base::TaskRunner> proc_task_runner_;
[email protected]189163e2011-05-11 01:48:54947
948 // Keeps track of the number of attempts we have made so far to resolve the
949 // host. Whenever we start an attempt to resolve the host, we increase this
950 // number.
Avi Drissman13fc8932015-12-20 04:40:46951 uint32_t attempt_number_;
[email protected]189163e2011-05-11 01:48:54952
953 // The index of the attempt which finished first (or 0 if the job is still in
954 // progress).
Avi Drissman13fc8932015-12-20 04:40:46955 uint32_t completed_attempt_number_;
[email protected]189163e2011-05-11 01:48:54956
957 // The result (a net error code) from the first attempt to complete.
958 int completed_attempt_error_;
[email protected]252b699b2010-02-05 21:38:06959
[email protected]e87b8b512011-06-14 22:12:52960 // The time when retry attempt was finished.
961 base::TimeTicks retry_attempt_finished_time_;
962
[email protected]b59ff372009-07-15 22:04:32963 AddressList results_;
964
tfarina428341112016-09-22 13:38:20965 NetLogWithSource net_log_;
[email protected]ee094b82010-08-24 15:55:51966
[email protected]0f292de02012-02-01 22:28:20967 DISALLOW_COPY_AND_ASSIGN(ProcTask);
[email protected]b59ff372009-07-15 22:04:32968};
969
970//-----------------------------------------------------------------------------
971
Miriam Gershenson02592182018-03-22 17:42:37972// Resolves the hostname using DnsTransaction, which is a full implementation of
973// a DNS stub resolver. One DnsTransaction is created for each resolution
974// needed, which for AF_UNSPEC resolutions includes both A and AAAA. The
975// transactions are scheduled separately and started separately.
976//
[email protected]b3601bc22012-02-21 21:23:20977// TODO(szym): This could be moved to separate source file as well.
[email protected]0adcb2b2012-08-15 21:30:46978class HostResolverImpl::DnsTask : public base::SupportsWeakPtr<DnsTask> {
[email protected]b3601bc22012-02-21 21:23:20979 public:
[email protected]daae1322013-09-05 18:26:50980 class Delegate {
981 public:
982 virtual void OnDnsTaskComplete(base::TimeTicks start_time,
983 int net_error,
984 const AddressList& addr_list,
985 base::TimeDelta ttl) = 0;
986
987 // Called when the first of two jobs succeeds. If the first completed
988 // transaction fails, this is not called. Also not called when the DnsTask
989 // only needs to run one transaction.
990 virtual void OnFirstDnsTransactionComplete() = 0;
991
Brad Lassey786929ad2018-02-21 20:54:27992 virtual URLRequestContext* url_request_context() = 0;
993 virtual RequestPriority priority() const = 0;
994
[email protected]daae1322013-09-05 18:26:50995 protected:
Chris Watkins68b15032017-12-01 03:07:13996 Delegate() = default;
997 virtual ~Delegate() = default;
[email protected]daae1322013-09-05 18:26:50998 };
[email protected]b3601bc22012-02-21 21:23:20999
[email protected]0adcb2b2012-08-15 21:30:461000 DnsTask(DnsClient* client,
[email protected]b3601bc22012-02-21 21:23:201001 const Key& key,
[email protected]daae1322013-09-05 18:26:501002 Delegate* delegate,
tfarina428341112016-09-22 13:38:201003 const NetLogWithSource& job_net_log)
[email protected]0adcb2b2012-08-15 21:30:461004 : client_(client),
[email protected]daae1322013-09-05 18:26:501005 key_(key),
1006 delegate_(delegate),
1007 net_log_(job_net_log),
1008 num_completed_transactions_(0),
1009 task_start_time_(base::TimeTicks::Now()) {
[email protected]0adcb2b2012-08-15 21:30:461010 DCHECK(client);
[email protected]daae1322013-09-05 18:26:501011 DCHECK(delegate_);
[email protected]1affed62013-08-21 03:24:501012 }
1013
[email protected]daae1322013-09-05 18:26:501014 bool needs_two_transactions() const {
1015 return key_.address_family == ADDRESS_FAMILY_UNSPECIFIED;
1016 }
1017
1018 bool needs_another_transaction() const {
1019 return needs_two_transactions() && !transaction_aaaa_;
1020 }
1021
1022 void StartFirstTransaction() {
1023 DCHECK_EQ(0u, num_completed_transactions_);
mikecirone8b85c432016-09-08 19:11:001024 net_log_.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_DNS_TASK);
[email protected]daae1322013-09-05 18:26:501025 if (key_.address_family == ADDRESS_FAMILY_IPV6) {
1026 StartAAAA();
1027 } else {
1028 StartA();
1029 }
1030 }
1031
1032 void StartSecondTransaction() {
1033 DCHECK(needs_two_transactions());
1034 StartAAAA();
[email protected]70c04ab2013-08-22 16:05:121035 }
1036
Brad Lassey2e8f185d2018-05-21 22:25:211037 base::TimeDelta ttl() { return ttl_; }
1038
[email protected]70c04ab2013-08-22 16:05:121039 private:
[email protected]daae1322013-09-05 18:26:501040 void StartA() {
1041 DCHECK(!transaction_a_);
1042 DCHECK_NE(ADDRESS_FAMILY_IPV6, key_.address_family);
1043 transaction_a_ = CreateTransaction(ADDRESS_FAMILY_IPV4);
1044 transaction_a_->Start();
1045 }
1046
1047 void StartAAAA() {
1048 DCHECK(!transaction_aaaa_);
1049 DCHECK_NE(ADDRESS_FAMILY_IPV4, key_.address_family);
1050 transaction_aaaa_ = CreateTransaction(ADDRESS_FAMILY_IPV6);
1051 transaction_aaaa_->Start();
1052 }
1053
danakj22f90e72016-04-16 01:55:401054 std::unique_ptr<DnsTransaction> CreateTransaction(AddressFamily family) {
[email protected]daae1322013-09-05 18:26:501055 DCHECK_NE(ADDRESS_FAMILY_UNSPECIFIED, family);
Brad Lassey786929ad2018-02-21 20:54:271056 std::unique_ptr<DnsTransaction> trans =
1057 client_->GetTransactionFactory()->CreateTransaction(
1058 key_.hostname,
1059 family == ADDRESS_FAMILY_IPV6 ? dns_protocol::kTypeAAAA
1060 : dns_protocol::kTypeA,
Brad Lasseydba0a84b2018-02-23 22:18:531061 base::BindOnce(&DnsTask::OnTransactionComplete,
1062 base::Unretained(this), base::TimeTicks::Now()),
Brad Lassey786929ad2018-02-21 20:54:271063 net_log_);
1064 trans->SetRequestContext(delegate_->url_request_context());
1065 trans->SetRequestPriority(delegate_->priority());
1066 return trans;
[email protected]daae1322013-09-05 18:26:501067 }
1068
1069 void OnTransactionComplete(const base::TimeTicks& start_time,
[email protected]1def74c2012-03-22 20:07:001070 DnsTransaction* transaction,
[email protected]b3601bc22012-02-21 21:23:201071 int net_error,
1072 const DnsResponse* response) {
[email protected]add76532012-03-30 14:47:471073 DCHECK(transaction);
[email protected]02cd6982013-01-10 20:12:511074 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
Brad Lassey2e8f185d2018-05-21 22:25:211075
1076 if (net_error != OK && !(net_error == ERR_NAME_NOT_RESOLVED && response &&
1077 response->IsValid())) {
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211078 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.TransactionFailure", duration);
[email protected]0adcb2b2012-08-15 21:30:461079 OnFailure(net_error, DnsResponse::DNS_PARSE_OK);
1080 return;
[email protected]6c411902012-08-14 22:36:361081 }
[email protected]0adcb2b2012-08-15 21:30:461082
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211083 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.TransactionSuccess", duration);
[email protected]02cd6982013-01-10 20:12:511084 switch (transaction->GetType()) {
1085 case dns_protocol::kTypeA:
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211086 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.TransactionSuccess_A", duration);
[email protected]02cd6982013-01-10 20:12:511087 break;
1088 case dns_protocol::kTypeAAAA:
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211089 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.TransactionSuccess_AAAA",
1090 duration);
[email protected]02cd6982013-01-10 20:12:511091 break;
1092 }
[email protected]daae1322013-09-05 18:26:501093
[email protected]0adcb2b2012-08-15 21:30:461094 AddressList addr_list;
1095 base::TimeDelta ttl;
1096 DnsResponse::Result result = response->ParseToAddressList(&addr_list, &ttl);
1097 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ParseToAddressList",
1098 result,
1099 DnsResponse::DNS_PARSE_RESULT_MAX);
1100 if (result != DnsResponse::DNS_PARSE_OK) {
1101 // Fail even if the other query succeeds.
1102 OnFailure(ERR_DNS_MALFORMED_RESPONSE, result);
1103 return;
1104 }
1105
[email protected]daae1322013-09-05 18:26:501106 ++num_completed_transactions_;
1107 if (num_completed_transactions_ == 1) {
1108 ttl_ = ttl;
[email protected]0adcb2b2012-08-15 21:30:461109 } else {
[email protected]daae1322013-09-05 18:26:501110 ttl_ = std::min(ttl_, ttl);
[email protected]0adcb2b2012-08-15 21:30:461111 }
1112
[email protected]daae1322013-09-05 18:26:501113 if (transaction->GetType() == dns_protocol::kTypeA) {
1114 DCHECK_EQ(transaction_a_.get(), transaction);
1115 // Place IPv4 addresses after IPv6.
1116 addr_list_.insert(addr_list_.end(), addr_list.begin(), addr_list.end());
1117 } else {
1118 DCHECK_EQ(transaction_aaaa_.get(), transaction);
1119 // Place IPv6 addresses before IPv4.
1120 addr_list_.insert(addr_list_.begin(), addr_list.begin(), addr_list.end());
1121 }
1122
1123 if (needs_two_transactions() && num_completed_transactions_ == 1) {
1124 // No need to repeat the suffix search.
1125 key_.hostname = transaction->GetHostname();
1126 delegate_->OnFirstDnsTransactionComplete();
1127 return;
1128 }
1129
1130 if (addr_list_.empty()) {
[email protected]70c04ab2013-08-22 16:05:121131 // TODO(szym): Don't fallback to ProcTask in this case.
1132 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
[email protected]0adcb2b2012-08-15 21:30:461133 return;
1134 }
1135
[email protected]daae1322013-09-05 18:26:501136 // If there are multiple addresses, and at least one is IPv6, need to sort
1137 // them. Note that IPv6 addresses are always put before IPv4 ones, so it's
1138 // sufficient to just check the family of the first address.
1139 if (addr_list_.size() > 1 &&
1140 addr_list_[0].GetFamily() == ADDRESS_FAMILY_IPV6) {
1141 // Sort addresses if needed. Sort could complete synchronously.
[email protected]0adcb2b2012-08-15 21:30:461142 client_->GetAddressSorter()->Sort(
[email protected]daae1322013-09-05 18:26:501143 addr_list_,
[email protected]4589a3a2012-09-20 20:57:071144 base::Bind(&DnsTask::OnSortComplete,
1145 AsWeakPtr(),
[email protected]daae1322013-09-05 18:26:501146 base::TimeTicks::Now()));
[email protected]0adcb2b2012-08-15 21:30:461147 } else {
[email protected]daae1322013-09-05 18:26:501148 OnSuccess(addr_list_);
[email protected]0adcb2b2012-08-15 21:30:461149 }
1150 }
1151
1152 void OnSortComplete(base::TimeTicks start_time,
[email protected]0adcb2b2012-08-15 21:30:461153 bool success,
1154 const AddressList& addr_list) {
1155 if (!success) {
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211156 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.SortFailure",
1157 base::TimeTicks::Now() - start_time);
[email protected]0adcb2b2012-08-15 21:30:461158 OnFailure(ERR_DNS_SORT_ERROR, DnsResponse::DNS_PARSE_OK);
1159 return;
1160 }
1161
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211162 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.SortSuccess",
1163 base::TimeTicks::Now() - start_time);
[email protected]0adcb2b2012-08-15 21:30:461164
1165 // AddressSorter prunes unusable destinations.
1166 if (addr_list.empty()) {
1167 LOG(WARNING) << "Address list empty after RFC3484 sort";
1168 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
1169 return;
1170 }
1171
[email protected]daae1322013-09-05 18:26:501172 OnSuccess(addr_list);
[email protected]0adcb2b2012-08-15 21:30:461173 }
1174
1175 void OnFailure(int net_error, DnsResponse::Result result) {
1176 DCHECK_NE(OK, net_error);
[email protected]cd565142012-06-12 16:21:451177 net_log_.EndEvent(
mikecirone8b85c432016-09-08 19:11:001178 NetLogEventType::HOST_RESOLVER_IMPL_DNS_TASK,
[email protected]cd565142012-06-12 16:21:451179 base::Bind(&NetLogDnsTaskFailedCallback, net_error, result));
Brad Lassey2e8f185d2018-05-21 22:25:211180 base::TimeDelta ttl = ttl_ < base::TimeDelta::FromSeconds(
1181 std::numeric_limits<uint32_t>::max()) &&
1182 num_completed_transactions_ > 0
1183 ? ttl_
1184 : base::TimeDelta::FromSeconds(0);
Miriam Gershenson66024d72017-12-05 04:30:321185 delegate_->OnDnsTaskComplete(task_start_time_, net_error, AddressList(),
Brad Lassey2e8f185d2018-05-21 22:25:211186 ttl);
[email protected]b3601bc22012-02-21 21:23:201187 }
1188
[email protected]daae1322013-09-05 18:26:501189 void OnSuccess(const AddressList& addr_list) {
mikecirone8b85c432016-09-08 19:11:001190 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_DNS_TASK,
[email protected]0adcb2b2012-08-15 21:30:461191 addr_list.CreateNetLogCallback());
[email protected]daae1322013-09-05 18:26:501192 delegate_->OnDnsTaskComplete(task_start_time_, OK, addr_list, ttl_);
[email protected]0adcb2b2012-08-15 21:30:461193 }
1194
1195 DnsClient* client_;
[email protected]daae1322013-09-05 18:26:501196 Key key_;
1197
[email protected]b3601bc22012-02-21 21:23:201198 // The listener to the results of this DnsTask.
[email protected]daae1322013-09-05 18:26:501199 Delegate* delegate_;
tfarina428341112016-09-22 13:38:201200 const NetLogWithSource net_log_;
[email protected]b3601bc22012-02-21 21:23:201201
danakj22f90e72016-04-16 01:55:401202 std::unique_ptr<DnsTransaction> transaction_a_;
1203 std::unique_ptr<DnsTransaction> transaction_aaaa_;
[email protected]0adcb2b2012-08-15 21:30:461204
[email protected]daae1322013-09-05 18:26:501205 unsigned num_completed_transactions_;
1206
1207 // These are updated as each transaction completes.
1208 base::TimeDelta ttl_;
1209 // IPv6 addresses must appear first in the list.
1210 AddressList addr_list_;
1211
1212 base::TimeTicks task_start_time_;
[email protected]0adcb2b2012-08-15 21:30:461213
1214 DISALLOW_COPY_AND_ASSIGN(DnsTask);
[email protected]b3601bc22012-02-21 21:23:201215};
1216
1217//-----------------------------------------------------------------------------
1218
[email protected]0f292de02012-02-01 22:28:201219// Aggregates all Requests for the same Key. Dispatched via PriorityDispatch.
[email protected]daae1322013-09-05 18:26:501220class HostResolverImpl::Job : public PrioritizedDispatcher::Job,
1221 public HostResolverImpl::DnsTask::Delegate {
[email protected]68ad3ee2010-01-30 03:45:391222 public:
[email protected]0f292de02012-02-01 22:28:201223 // Creates new job for |key| where |request_net_log| is bound to the
[email protected]16ee26d2012-03-08 03:34:351224 // request that spawned it.
[email protected]12faa4c2012-11-06 04:44:181225 Job(const base::WeakPtr<HostResolverImpl>& resolver,
[email protected]0f292de02012-02-01 22:28:201226 const Key& key,
[email protected]8c98d002012-07-18 19:02:271227 RequestPriority priority,
Miriam Gershensone42adb22017-10-16 16:19:381228 scoped_refptr<base::TaskRunner> proc_task_runner,
tfarina428341112016-09-22 13:38:201229 const NetLogWithSource& source_net_log)
[email protected]12faa4c2012-11-06 04:44:181230 : resolver_(resolver),
[email protected]0f292de02012-02-01 22:28:201231 key_(key),
[email protected]8c98d002012-07-18 19:02:271232 priority_tracker_(priority),
Miriam Gershensone42adb22017-10-16 16:19:381233 proc_task_runner_(std::move(proc_task_runner)),
[email protected]0f292de02012-02-01 22:28:201234 had_non_speculative_request_(false),
[email protected]51b9a6b2012-06-25 21:50:291235 had_dns_config_(false),
[email protected]daae1322013-09-05 18:26:501236 num_occupied_job_slots_(0),
[email protected]1d932852012-06-19 19:40:331237 dns_task_error_(OK),
[email protected]51b9a6b2012-06-25 21:50:291238 creation_time_(base::TimeTicks::Now()),
1239 priority_change_time_(creation_time_),
tfarina428341112016-09-22 13:38:201240 net_log_(
1241 NetLogWithSource::Make(source_net_log.net_log(),
mikecirone8b85c432016-09-08 19:11:001242 NetLogSourceType::HOST_RESOLVER_IMPL_JOB)) {
1243 source_net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_CREATE_JOB);
[email protected]0f292de02012-02-01 22:28:201244
mikecirone8b85c432016-09-08 19:11:001245 net_log_.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
1246 base::Bind(&NetLogJobCreationCallback,
1247 source_net_log.source(), &key_.hostname));
[email protected]68ad3ee2010-01-30 03:45:391248 }
1249
dchengb03027d2014-10-21 12:00:201250 ~Job() override {
[email protected]b3601bc22012-02-21 21:23:201251 if (is_running()) {
1252 // |resolver_| was destroyed with this Job still in flight.
1253 // Clean-up, record in the log, but don't run any callbacks.
1254 if (is_proc_running()) {
[email protected]0f292de02012-02-01 22:28:201255 proc_task_->Cancel();
wezb9820d42016-06-22 23:41:041256 proc_task_ = nullptr;
[email protected]0f292de02012-02-01 22:28:201257 }
[email protected]16ee26d2012-03-08 03:34:351258 // Clean up now for nice NetLog.
[email protected]daae1322013-09-05 18:26:501259 KillDnsTask();
mikecirone8b85c432016-09-08 19:11:001260 net_log_.EndEventWithNetErrorCode(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
[email protected]b3601bc22012-02-21 21:23:201261 ERR_ABORTED);
1262 } else if (is_queued()) {
[email protected]57a48d32012-03-03 00:04:551263 // |resolver_| was destroyed without running this Job.
[email protected]16ee26d2012-03-08 03:34:351264 // TODO(szym): is there any benefit in having this distinction?
mikecirone8b85c432016-09-08 19:11:001265 net_log_.AddEvent(NetLogEventType::CANCELLED);
1266 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB);
[email protected]68ad3ee2010-01-30 03:45:391267 }
[email protected]b3601bc22012-02-21 21:23:201268 // else CompleteRequests logged EndEvent.
David Benjamina5677192018-04-23 23:25:421269 while (!requests_.empty()) {
maksim.sisov31452af2016-07-27 06:38:101270 // Log any remaining Requests as cancelled.
David Benjamina5677192018-04-23 23:25:421271 RequestImpl* req = requests_.head()->value();
1272 req->RemoveFromList();
1273 DCHECK_EQ(this, req->job());
1274 LogCancelRequest(req->source_net_log(), req->info());
1275 req->OnJobCancelled(this);
[email protected]b3601bc22012-02-21 21:23:201276 }
[email protected]68ad3ee2010-01-30 03:45:391277 }
1278
[email protected]daae1322013-09-05 18:26:501279 // Add this job to the dispatcher. If "at_head" is true, adds at the front
1280 // of the queue.
1281 void Schedule(bool at_head) {
1282 DCHECK(!is_queued());
1283 PrioritizedDispatcher::Handle handle;
1284 if (!at_head) {
[email protected]106ccd2c2014-06-17 09:21:001285 handle = resolver_->dispatcher_->Add(this, priority());
[email protected]daae1322013-09-05 18:26:501286 } else {
[email protected]106ccd2c2014-06-17 09:21:001287 handle = resolver_->dispatcher_->AddAtHead(this, priority());
[email protected]daae1322013-09-05 18:26:501288 }
1289 // The dispatcher could have started |this| in the above call to Add, which
1290 // could have called Schedule again. In that case |handle| will be null,
1291 // but |handle_| may have been set by the other nested call to Schedule.
1292 if (!handle.is_null()) {
1293 DCHECK(handle_.is_null());
1294 handle_ = handle;
1295 }
[email protected]16ee26d2012-03-08 03:34:351296 }
1297
maksim.sisov31452af2016-07-27 06:38:101298 void AddRequest(RequestImpl* request) {
1299 DCHECK_EQ(key_.hostname, request->info().hostname());
[email protected]0f292de02012-02-01 22:28:201300
maksim.sisov31452af2016-07-27 06:38:101301 priority_tracker_.Add(request->priority());
[email protected]0f292de02012-02-01 22:28:201302
maksim.sisov31452af2016-07-27 06:38:101303 request->source_net_log().AddEvent(
mikecirone8b85c432016-09-08 19:11:001304 NetLogEventType::HOST_RESOLVER_IMPL_JOB_ATTACH,
[email protected]cd565142012-06-12 16:21:451305 net_log_.source().ToEventParametersCallback());
[email protected]0f292de02012-02-01 22:28:201306
1307 net_log_.AddEvent(
mikecirone8b85c432016-09-08 19:11:001308 NetLogEventType::HOST_RESOLVER_IMPL_JOB_REQUEST_ATTACH,
maksim.sisov31452af2016-07-27 06:38:101309 base::Bind(&NetLogJobAttachCallback, request->source_net_log().source(),
[email protected]cd565142012-06-12 16:21:451310 priority()));
[email protected]0f292de02012-02-01 22:28:201311
Miriam Gershenson61604662017-09-28 23:51:111312 if (!request->info().is_speculative())
[email protected]0f292de02012-02-01 22:28:201313 had_non_speculative_request_ = true;
[email protected]b3601bc22012-02-21 21:23:201314
David Benjamina5677192018-04-23 23:25:421315 requests_.Append(request);
[email protected]b3601bc22012-02-21 21:23:201316
[email protected]51b9a6b2012-06-25 21:50:291317 UpdatePriority();
[email protected]68ad3ee2010-01-30 03:45:391318 }
1319
maksim.sisov31452af2016-07-27 06:38:101320 void ChangeRequestPriority(RequestImpl* req, RequestPriority priority) {
juliatuttlec53b19a72016-05-05 13:51:311321 DCHECK_EQ(key_.hostname, req->info().hostname());
juliatuttlec53b19a72016-05-05 13:51:311322
1323 priority_tracker_.Remove(req->priority());
1324 req->set_priority(priority);
1325 priority_tracker_.Add(req->priority());
1326 UpdatePriority();
1327 }
1328
maksim.sisov31452af2016-07-27 06:38:101329 // Detach cancelled request. If it was the last active Request, also finishes
1330 // this Job.
1331 void CancelRequest(RequestImpl* request) {
1332 DCHECK_EQ(key_.hostname, request->info().hostname());
1333 DCHECK(!requests_.empty());
[email protected]16ee26d2012-03-08 03:34:351334
maksim.sisov31452af2016-07-27 06:38:101335 LogCancelRequest(request->source_net_log(), request->info());
[email protected]16ee26d2012-03-08 03:34:351336
maksim.sisov31452af2016-07-27 06:38:101337 priority_tracker_.Remove(request->priority());
1338 net_log_.AddEvent(
mikecirone8b85c432016-09-08 19:11:001339 NetLogEventType::HOST_RESOLVER_IMPL_JOB_REQUEST_DETACH,
maksim.sisov31452af2016-07-27 06:38:101340 base::Bind(&NetLogJobAttachCallback, request->source_net_log().source(),
1341 priority()));
[email protected]b3601bc22012-02-21 21:23:201342
[email protected]16ee26d2012-03-08 03:34:351343 if (num_active_requests() > 0) {
[email protected]51b9a6b2012-06-25 21:50:291344 UpdatePriority();
David Benjamina5677192018-04-23 23:25:421345 request->RemoveFromList();
[email protected]16ee26d2012-03-08 03:34:351346 } else {
1347 // If we were called from a Request's callback within CompleteRequests,
1348 // that Request could not have been cancelled, so num_active_requests()
1349 // could not be 0. Therefore, we are not in CompleteRequests().
[email protected]1339a2a22012-10-17 08:39:431350 CompleteRequestsWithError(OK /* cancelled */);
[email protected]b3601bc22012-02-21 21:23:201351 }
[email protected]68ad3ee2010-01-30 03:45:391352 }
1353
[email protected]7af985a2012-12-14 22:40:421354 // Called from AbortAllInProgressJobs. Completes all requests and destroys
1355 // the job. This currently assumes the abort is due to a network change.
olli.raulaa21e9eb72015-12-17 08:18:111356 // TODO This should not delete |this|.
[email protected]0f292de02012-02-01 22:28:201357 void Abort() {
[email protected]0f292de02012-02-01 22:28:201358 DCHECK(is_running());
[email protected]7af985a2012-12-14 22:40:421359 CompleteRequestsWithError(ERR_NETWORK_CHANGED);
[email protected]b3601bc22012-02-21 21:23:201360 }
1361
[email protected]f0f602bd2012-11-15 18:01:021362 // If DnsTask present, abort it and fall back to ProcTask.
1363 void AbortDnsTask() {
1364 if (dns_task_) {
[email protected]daae1322013-09-05 18:26:501365 KillDnsTask();
[email protected]f0f602bd2012-11-15 18:01:021366 dns_task_error_ = OK;
1367 StartProcTask();
1368 }
1369 }
1370
[email protected]16ee26d2012-03-08 03:34:351371 // Called by HostResolverImpl when this job is evicted due to queue overflow.
1372 // Completes all requests and destroys the job.
1373 void OnEvicted() {
1374 DCHECK(!is_running());
1375 DCHECK(is_queued());
1376 handle_.Reset();
1377
mikecirone8b85c432016-09-08 19:11:001378 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB_EVICTED);
[email protected]16ee26d2012-03-08 03:34:351379
1380 // This signals to CompleteRequests that this job never ran.
[email protected]1339a2a22012-10-17 08:39:431381 CompleteRequestsWithError(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
[email protected]16ee26d2012-03-08 03:34:351382 }
1383
[email protected]78eac2a2012-03-14 19:09:271384 // Attempts to serve the job from HOSTS. Returns true if succeeded and
1385 // this Job was destroyed.
1386 bool ServeFromHosts() {
1387 DCHECK_GT(num_active_requests(), 0u);
1388 AddressList addr_list;
David Benjamina5677192018-04-23 23:25:421389 if (resolver_->ServeFromHosts(key(), requests_.head()->value()->info(),
[email protected]78eac2a2012-03-14 19:09:271390 &addr_list)) {
1391 // This will destroy the Job.
Rob Percival94f21ad2017-11-14 10:20:241392 CompleteRequests(
1393 MakeCacheEntry(OK, addr_list, HostCache::Entry::SOURCE_HOSTS),
1394 base::TimeDelta());
[email protected]78eac2a2012-03-14 19:09:271395 return true;
1396 }
1397 return false;
1398 }
1399
tanay.c6ddd5f6f2015-08-25 06:34:571400 const Key& key() const { return key_; }
[email protected]b4481b222012-03-16 17:13:111401
1402 bool is_queued() const {
1403 return !handle_.is_null();
1404 }
1405
1406 bool is_running() const {
1407 return is_dns_running() || is_proc_running();
1408 }
1409
[email protected]16ee26d2012-03-08 03:34:351410 private:
[email protected]daae1322013-09-05 18:26:501411 void KillDnsTask() {
1412 if (dns_task_) {
1413 ReduceToOneJobSlot();
1414 dns_task_.reset();
1415 }
1416 }
1417
1418 // Reduce the number of job slots occupied and queued in the dispatcher
1419 // to one. If the second Job slot is queued in the dispatcher, cancels the
1420 // queued job. Otherwise, the second Job has been started by the
1421 // PrioritizedDispatcher, so signals it is complete.
1422 void ReduceToOneJobSlot() {
1423 DCHECK_GE(num_occupied_job_slots_, 1u);
1424 if (is_queued()) {
[email protected]106ccd2c2014-06-17 09:21:001425 resolver_->dispatcher_->Cancel(handle_);
[email protected]daae1322013-09-05 18:26:501426 handle_.Reset();
1427 } else if (num_occupied_job_slots_ > 1) {
[email protected]106ccd2c2014-06-17 09:21:001428 resolver_->dispatcher_->OnJobFinished();
[email protected]daae1322013-09-05 18:26:501429 --num_occupied_job_slots_;
1430 }
1431 DCHECK_EQ(1u, num_occupied_job_slots_);
1432 }
1433
eroman0cd87b62016-12-14 19:13:451434 // MakeCacheEntry() and MakeCacheEntryWithTTL() are helpers to build a
1435 // HostCache::Entry(). The address list is omited from the cache entry
1436 // for errors.
1437 HostCache::Entry MakeCacheEntry(int net_error,
Rob Percival94f21ad2017-11-14 10:20:241438 const AddressList& addr_list,
1439 HostCache::Entry::Source source) const {
eroman0cd87b62016-12-14 19:13:451440 return HostCache::Entry(
1441 net_error,
Rob Percival94f21ad2017-11-14 10:20:241442 net_error == OK ? MakeAddressListForRequest(addr_list) : AddressList(),
1443 source);
eroman0cd87b62016-12-14 19:13:451444 }
1445
1446 HostCache::Entry MakeCacheEntryWithTTL(int net_error,
1447 const AddressList& addr_list,
Rob Percival94f21ad2017-11-14 10:20:241448 HostCache::Entry::Source source,
eroman0cd87b62016-12-14 19:13:451449 base::TimeDelta ttl) const {
1450 return HostCache::Entry(
1451 net_error,
1452 net_error == OK ? MakeAddressListForRequest(addr_list) : AddressList(),
Rob Percival94f21ad2017-11-14 10:20:241453 source, ttl);
eroman0cd87b62016-12-14 19:13:451454 }
1455
juliatuttlec53b19a72016-05-05 13:51:311456 AddressList MakeAddressListForRequest(const AddressList& list) const {
1457 if (requests_.empty())
1458 return list;
David Benjamina5677192018-04-23 23:25:421459 return AddressList::CopyWithPort(list,
1460 requests_.head()->value()->info().port());
juliatuttlec53b19a72016-05-05 13:51:311461 }
1462
[email protected]51b9a6b2012-06-25 21:50:291463 void UpdatePriority() {
1464 if (is_queued()) {
1465 if (priority() != static_cast<RequestPriority>(handle_.priority()))
1466 priority_change_time_ = base::TimeTicks::Now();
[email protected]106ccd2c2014-06-17 09:21:001467 handle_ = resolver_->dispatcher_->ChangePriority(handle_, priority());
[email protected]51b9a6b2012-06-25 21:50:291468 }
1469 }
1470
[email protected]16ee26d2012-03-08 03:34:351471 // PriorityDispatch::Job:
dchengb03027d2014-10-21 12:00:201472 void Start() override {
[email protected]daae1322013-09-05 18:26:501473 DCHECK_LE(num_occupied_job_slots_, 1u);
1474
[email protected]70c04ab2013-08-22 16:05:121475 handle_.Reset();
[email protected]daae1322013-09-05 18:26:501476 ++num_occupied_job_slots_;
1477
1478 if (num_occupied_job_slots_ == 2) {
1479 StartSecondDnsTransaction();
1480 return;
1481 }
1482
1483 DCHECK(!is_running());
[email protected]0f292de02012-02-01 22:28:201484
mikecirone8b85c432016-09-08 19:11:001485 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB_STARTED);
[email protected]0f292de02012-02-01 22:28:201486
[email protected]51b9a6b2012-06-25 21:50:291487 had_dns_config_ = resolver_->HaveDnsConfig();
1488
Miriam Gershenson61604662017-09-28 23:51:111489 start_time_ = base::TimeTicks::Now();
1490 base::TimeDelta queue_time = start_time_ - creation_time_;
1491 base::TimeDelta queue_time_after_change =
1492 start_time_ - priority_change_time_;
[email protected]51b9a6b2012-06-25 21:50:291493
Miriam Gershenson90d05e02017-09-28 19:29:281494 DNS_HISTOGRAM_BY_PRIORITY("Net.DNS.JobQueueTime", priority(), queue_time);
1495 DNS_HISTOGRAM_BY_PRIORITY("Net.DNS.JobQueueTimeAfterChange", priority(),
1496 queue_time_after_change);
[email protected]51b9a6b2012-06-25 21:50:291497
[email protected]443714fad2013-09-19 04:52:011498 bool system_only =
1499 (key_.host_resolver_flags & HOST_RESOLVER_SYSTEM_ONLY) != 0;
1500
[email protected]1d932852012-06-19 19:40:331501 // Caution: Job::Start must not complete synchronously.
[email protected]443714fad2013-09-19 04:52:011502 if (!system_only && had_dns_config_ &&
1503 !ResemblesMulticastDNSName(key_.hostname)) {
[email protected]b3601bc22012-02-21 21:23:201504 StartDnsTask();
1505 } else {
1506 StartProcTask();
1507 }
1508 }
1509
[email protected]b3601bc22012-02-21 21:23:201510 // TODO(szym): Since DnsTransaction does not consume threads, we can increase
Francois Doraya2d01ba2017-09-25 19:17:401511 // the limits on |dispatcher_|. But in order to keep the number of
1512 // TaskScheduler threads low, we will need to use an "inner"
1513 // PrioritizedDispatcher with tighter limits.
[email protected]b3601bc22012-02-21 21:23:201514 void StartProcTask() {
[email protected]16ee26d2012-03-08 03:34:351515 DCHECK(!is_dns_running());
mmenke91c17162016-06-02 16:03:231516 proc_task_ =
1517 new ProcTask(key_, resolver_->proc_params_,
1518 base::Bind(&Job::OnProcTaskComplete,
1519 base::Unretained(this), base::TimeTicks::Now()),
Miriam Gershensone42adb22017-10-16 16:19:381520 proc_task_runner_, net_log_);
[email protected]0f292de02012-02-01 22:28:201521
[email protected]0f292de02012-02-01 22:28:201522 // Start() could be called from within Resolve(), hence it must NOT directly
1523 // call OnProcTaskComplete, for example, on synchronous failure.
1524 proc_task_->Start();
[email protected]68ad3ee2010-01-30 03:45:391525 }
1526
[email protected]0f292de02012-02-01 22:28:201527 // Called by ProcTask when it completes.
[email protected]e3bd4822012-10-23 18:01:371528 void OnProcTaskComplete(base::TimeTicks start_time,
1529 int net_error,
1530 const AddressList& addr_list) {
[email protected]b3601bc22012-02-21 21:23:201531 DCHECK(is_proc_running());
[email protected]68ad3ee2010-01-30 03:45:391532
[email protected]1d932852012-06-19 19:40:331533 if (dns_task_error_ != OK) {
[email protected]e3bd4822012-10-23 18:01:371534 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]1def74c2012-03-22 20:07:001535 if (net_error == OK) {
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211536 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.FallbackSuccess", duration);
[email protected]1d932852012-06-19 19:40:331537 if ((dns_task_error_ == ERR_NAME_NOT_RESOLVED) &&
1538 ResemblesNetBIOSName(key_.hostname)) {
1539 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_SUSPECT_NETBIOS);
1540 } else {
1541 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_PROC_SUCCESS);
1542 }
Ilya Sherman0eb39802017-12-08 20:58:181543 base::UmaHistogramSparse("Net.DNS.DnsTask.Errors",
1544 std::abs(dns_task_error_));
[email protected]1ffdda82012-12-12 23:04:221545 resolver_->OnDnsTaskResolve(dns_task_error_);
[email protected]1def74c2012-03-22 20:07:001546 } else {
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211547 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.FallbackFail", duration);
[email protected]1def74c2012-03-22 20:07:001548 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
1549 }
1550 }
1551
eroman1efc237c2016-12-14 00:00:451552 if (ContainsIcannNameCollisionIp(addr_list))
1553 net_error = ERR_ICANN_NAME_COLLISION;
1554
[email protected]1339a2a22012-10-17 08:39:431555 base::TimeDelta ttl =
1556 base::TimeDelta::FromSeconds(kNegativeCacheEntryTTLSeconds);
[email protected]b3601bc22012-02-21 21:23:201557 if (net_error == OK)
1558 ttl = base::TimeDelta::FromSeconds(kCacheEntryTTLSeconds);
[email protected]68ad3ee2010-01-30 03:45:391559
Rob Percival94f21ad2017-11-14 10:20:241560 // Source unknown because the system resolver could have gotten it from a
1561 // hosts file, its own cache, a DNS lookup or somewhere else.
[email protected]895123222012-10-25 15:21:171562 // Don't store the |ttl| in cache since it's not obtained from the server.
Rob Percival94f21ad2017-11-14 10:20:241563 CompleteRequests(
1564 MakeCacheEntry(net_error, addr_list, HostCache::Entry::SOURCE_UNKNOWN),
1565 ttl);
[email protected]b3601bc22012-02-21 21:23:201566 }
1567
1568 void StartDnsTask() {
[email protected]78eac2a2012-03-14 19:09:271569 DCHECK(resolver_->HaveDnsConfig());
[email protected]daae1322013-09-05 18:26:501570 dns_task_.reset(new DnsTask(resolver_->dns_client_.get(), key_, this,
1571 net_log_));
[email protected]b3601bc22012-02-21 21:23:201572
[email protected]daae1322013-09-05 18:26:501573 dns_task_->StartFirstTransaction();
1574 // Schedule a second transaction, if needed.
1575 if (dns_task_->needs_two_transactions())
1576 Schedule(true);
1577 }
1578
1579 void StartSecondDnsTransaction() {
1580 DCHECK(dns_task_->needs_two_transactions());
1581 dns_task_->StartSecondTransaction();
[email protected]16c2bd72013-06-28 01:19:221582 }
1583
1584 // Called if DnsTask fails. It is posted from StartDnsTask, so Job may be
1585 // deleted before this callback. In this case dns_task is deleted as well,
1586 // so we use it as indicator whether Job is still valid.
1587 void OnDnsTaskFailure(const base::WeakPtr<DnsTask>& dns_task,
1588 base::TimeDelta duration,
1589 int net_error) {
Miriam Gershenson61604662017-09-28 23:51:111590 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.DnsTask.FailureTime", duration);
[email protected]16c2bd72013-06-28 01:19:221591
wezb9820d42016-06-22 23:41:041592 if (!dns_task)
[email protected]16c2bd72013-06-28 01:19:221593 return;
1594
Miriam Gershenson19faef812018-02-07 23:56:441595 if (duration < base::TimeDelta::FromMilliseconds(10)) {
1596 base::UmaHistogramSparse("Net.DNS.DnsTask.ErrorBeforeFallback.Fast",
1597 std::abs(net_error));
1598 } else {
1599 base::UmaHistogramSparse("Net.DNS.DnsTask.ErrorBeforeFallback.Slow",
1600 std::abs(net_error));
1601 }
[email protected]16c2bd72013-06-28 01:19:221602 dns_task_error_ = net_error;
1603
1604 // TODO(szym): Run ServeFromHosts now if nsswitch.conf says so.
1605 // http://crbug.com/117655
1606
1607 // TODO(szym): Some net errors indicate lack of connectivity. Starting
1608 // ProcTask in that case is a waste of time.
1609 if (resolver_->fallback_to_proctask_) {
[email protected]daae1322013-09-05 18:26:501610 KillDnsTask();
[email protected]16c2bd72013-06-28 01:19:221611 StartProcTask();
1612 } else {
1613 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
Brad Lassey2e8f185d2018-05-21 22:25:211614 // If the ttl is max, we didn't get one from the record, so set it to 0
1615 base::TimeDelta ttl =
1616 dns_task->ttl() < base::TimeDelta::FromSeconds(
1617 std::numeric_limits<uint32_t>::max())
1618 ? dns_task->ttl()
1619 : base::TimeDelta::FromSeconds(0);
1620 CompleteRequests(
1621 HostCache::Entry(net_error, AddressList(),
1622 HostCache::Entry::Source::SOURCE_UNKNOWN, ttl),
1623 ttl);
[email protected]b3601bc22012-02-21 21:23:201624 }
1625 }
1626
[email protected]daae1322013-09-05 18:26:501627
1628 // HostResolverImpl::DnsTask::Delegate implementation:
1629
dchengb03027d2014-10-21 12:00:201630 void OnDnsTaskComplete(base::TimeTicks start_time,
1631 int net_error,
1632 const AddressList& addr_list,
1633 base::TimeDelta ttl) override {
[email protected]b3601bc22012-02-21 21:23:201634 DCHECK(is_dns_running());
[email protected]b3601bc22012-02-21 21:23:201635
[email protected]e3bd4822012-10-23 18:01:371636 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]b3601bc22012-02-21 21:23:201637 if (net_error != OK) {
[email protected]16c2bd72013-06-28 01:19:221638 OnDnsTaskFailure(dns_task_->AsWeakPtr(), duration, net_error);
[email protected]b3601bc22012-02-21 21:23:201639 return;
1640 }
Miriam Gershenson61604662017-09-28 23:51:111641
1642 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.DnsTask.SuccessTime", duration);
[email protected]b3601bc22012-02-21 21:23:201643
[email protected]1def74c2012-03-22 20:07:001644 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_DNS_SUCCESS);
[email protected]1339a2a22012-10-17 08:39:431645 RecordTTL(ttl);
[email protected]0adcb2b2012-08-15 21:30:461646
[email protected]1ffdda82012-12-12 23:04:221647 resolver_->OnDnsTaskResolve(OK);
[email protected]f0f602bd2012-11-15 18:01:021648
[email protected]895123222012-10-25 15:21:171649 base::TimeDelta bounded_ttl =
1650 std::max(ttl, base::TimeDelta::FromSeconds(kMinimumTTLSeconds));
1651
eroman0cd87b62016-12-14 19:13:451652 if (ContainsIcannNameCollisionIp(addr_list)) {
1653 CompleteRequestsWithError(ERR_ICANN_NAME_COLLISION);
1654 } else {
Rob Percival94f21ad2017-11-14 10:20:241655 CompleteRequests(MakeCacheEntryWithTTL(net_error, addr_list,
1656 HostCache::Entry::SOURCE_DNS, ttl),
eroman0cd87b62016-12-14 19:13:451657 bounded_ttl);
1658 }
[email protected]b3601bc22012-02-21 21:23:201659 }
1660
dchengb03027d2014-10-21 12:00:201661 void OnFirstDnsTransactionComplete() override {
[email protected]daae1322013-09-05 18:26:501662 DCHECK(dns_task_->needs_two_transactions());
1663 DCHECK_EQ(dns_task_->needs_another_transaction(), is_queued());
1664 // No longer need to occupy two dispatcher slots.
1665 ReduceToOneJobSlot();
1666
1667 // We already have a job slot at the dispatcher, so if the second
1668 // transaction hasn't started, reuse it now instead of waiting in the queue
1669 // for the second slot.
1670 if (dns_task_->needs_another_transaction())
1671 dns_task_->StartSecondTransaction();
1672 }
1673
Brad Lassey786929ad2018-02-21 20:54:271674 URLRequestContext* url_request_context() override {
1675 return resolver_->url_request_context_;
1676 }
1677
Miriam Gershenson61604662017-09-28 23:51:111678 void RecordJobHistograms(int error) {
Miriam Gershensonc282ab42017-11-20 23:19:581679 // Used in UMA_HISTOGRAM_ENUMERATION. Do not renumber entries or reuse
1680 // deprecated values.
1681 enum Category {
1682 RESOLVE_SUCCESS = 0,
1683 RESOLVE_FAIL = 1,
1684 RESOLVE_SPECULATIVE_SUCCESS = 2,
1685 RESOLVE_SPECULATIVE_FAIL = 3,
1686 RESOLVE_ABORT = 4,
1687 RESOLVE_SPECULATIVE_ABORT = 5,
Miriam Gershenson61604662017-09-28 23:51:111688 RESOLVE_MAX, // Bounding value.
1689 };
1690 Category category = RESOLVE_MAX; // Illegal value for later DCHECK only.
1691
1692 base::TimeDelta duration = base::TimeTicks::Now() - start_time_;
1693 if (error == OK) {
1694 if (had_non_speculative_request_) {
1695 category = RESOLVE_SUCCESS;
1696 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime", duration);
1697 switch (key_.address_family) {
1698 case ADDRESS_FAMILY_IPV4:
1699 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime.IPV4",
1700 duration);
1701 break;
1702 case ADDRESS_FAMILY_IPV6:
1703 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime.IPV6",
1704 duration);
1705 break;
1706 case ADDRESS_FAMILY_UNSPECIFIED:
1707 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime.UNSPEC",
1708 duration);
1709 break;
1710 }
1711 } else {
1712 category = RESOLVE_SPECULATIVE_SUCCESS;
Miriam Gershenson61604662017-09-28 23:51:111713 }
Miriam Gershensonc282ab42017-11-20 23:19:581714 } else if (error == ERR_NETWORK_CHANGED ||
1715 error == ERR_HOST_RESOLVER_QUEUE_TOO_LARGE) {
1716 category = had_non_speculative_request_ ? RESOLVE_ABORT
1717 : RESOLVE_SPECULATIVE_ABORT;
Miriam Gershenson61604662017-09-28 23:51:111718 } else {
1719 if (had_non_speculative_request_) {
1720 category = RESOLVE_FAIL;
1721 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveFailureTime", duration);
1722 switch (key_.address_family) {
1723 case ADDRESS_FAMILY_IPV4:
Miriam Gershensonc282ab42017-11-20 23:19:581724 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveFailureTime.IPV4",
Miriam Gershenson61604662017-09-28 23:51:111725 duration);
1726 break;
1727 case ADDRESS_FAMILY_IPV6:
Miriam Gershensonc282ab42017-11-20 23:19:581728 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveFailureTime.IPV6",
Miriam Gershenson61604662017-09-28 23:51:111729 duration);
1730 break;
1731 case ADDRESS_FAMILY_UNSPECIFIED:
Miriam Gershensonc282ab42017-11-20 23:19:581732 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveFailureTime.UNSPEC",
Miriam Gershenson61604662017-09-28 23:51:111733 duration);
1734 break;
1735 }
1736 } else {
1737 category = RESOLVE_SPECULATIVE_FAIL;
Miriam Gershenson61604662017-09-28 23:51:111738 }
1739 }
1740 DCHECK_LT(static_cast<int>(category),
1741 static_cast<int>(RESOLVE_MAX)); // Be sure it was set.
1742 UMA_HISTOGRAM_ENUMERATION("Net.DNS.ResolveCategory", category, RESOLVE_MAX);
Miriam Gershensonaaf139582017-11-27 16:06:061743
1744 if (category == RESOLVE_FAIL || category == RESOLVE_ABORT) {
1745 if (duration < base::TimeDelta::FromMilliseconds(10))
Ilya Sherman0eb39802017-12-08 20:58:181746 base::UmaHistogramSparse("Net.DNS.ResolveError.Fast", std::abs(error));
Miriam Gershensonaaf139582017-11-27 16:06:061747 else
Ilya Sherman0eb39802017-12-08 20:58:181748 base::UmaHistogramSparse("Net.DNS.ResolveError.Slow", std::abs(error));
Miriam Gershensonaaf139582017-11-27 16:06:061749 }
Miriam Gershenson61604662017-09-28 23:51:111750 }
1751
[email protected]16ee26d2012-03-08 03:34:351752 // Performs Job's last rites. Completes all Requests. Deletes this.
[email protected]895123222012-10-25 15:21:171753 void CompleteRequests(const HostCache::Entry& entry,
1754 base::TimeDelta ttl) {
[email protected]11fbca0b2013-06-02 23:37:211755 CHECK(resolver_.get());
[email protected]b3601bc22012-02-21 21:23:201756
[email protected]16ee26d2012-03-08 03:34:351757 // This job must be removed from resolver's |jobs_| now to make room for a
1758 // new job with the same key in case one of the OnComplete callbacks decides
1759 // to spawn one. Consequently, the job deletes itself when CompleteRequests
1760 // is done.
danakj22f90e72016-04-16 01:55:401761 std::unique_ptr<Job> self_deleter(this);
[email protected]16ee26d2012-03-08 03:34:351762
1763 resolver_->RemoveJob(this);
1764
[email protected]16ee26d2012-03-08 03:34:351765 if (is_running()) {
[email protected]16ee26d2012-03-08 03:34:351766 if (is_proc_running()) {
[email protected]daae1322013-09-05 18:26:501767 DCHECK(!is_queued());
[email protected]16ee26d2012-03-08 03:34:351768 proc_task_->Cancel();
wezb9820d42016-06-22 23:41:041769 proc_task_ = nullptr;
[email protected]16ee26d2012-03-08 03:34:351770 }
[email protected]daae1322013-09-05 18:26:501771 KillDnsTask();
[email protected]16ee26d2012-03-08 03:34:351772
1773 // Signal dispatcher that a slot has opened.
[email protected]106ccd2c2014-06-17 09:21:001774 resolver_->dispatcher_->OnJobFinished();
[email protected]16ee26d2012-03-08 03:34:351775 } else if (is_queued()) {
[email protected]106ccd2c2014-06-17 09:21:001776 resolver_->dispatcher_->Cancel(handle_);
[email protected]16ee26d2012-03-08 03:34:351777 handle_.Reset();
1778 }
1779
1780 if (num_active_requests() == 0) {
mikecirone8b85c432016-09-08 19:11:001781 net_log_.AddEvent(NetLogEventType::CANCELLED);
1782 net_log_.EndEventWithNetErrorCode(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
[email protected]16ee26d2012-03-08 03:34:351783 OK);
1784 return;
1785 }
[email protected]b3601bc22012-02-21 21:23:201786
mikecirone8b85c432016-09-08 19:11:001787 net_log_.EndEventWithNetErrorCode(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
juliatuttle317860e2016-05-12 14:47:221788 entry.error());
[email protected]68ad3ee2010-01-30 03:45:391789
[email protected]78eac2a2012-03-14 19:09:271790 DCHECK(!requests_.empty());
1791
eroman1efc237c2016-12-14 00:00:451792 if (entry.error() == OK || entry.error() == ERR_ICANN_NAME_COLLISION) {
[email protected]d7b9a2b2012-05-31 22:31:191793 // Record this histogram here, when we know the system has a valid DNS
1794 // configuration.
[email protected]539df6c2012-06-19 21:21:291795 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.HaveDnsConfig",
1796 resolver_->received_dns_config_);
[email protected]d7b9a2b2012-05-31 22:31:191797 }
[email protected]16ee26d2012-03-08 03:34:351798
juliatuttle317860e2016-05-12 14:47:221799 bool did_complete = (entry.error() != ERR_NETWORK_CHANGED) &&
1800 (entry.error() != ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
Miriam Gershensonc282ab42017-11-20 23:19:581801 if (did_complete)
[email protected]1339a2a22012-10-17 08:39:431802 resolver_->CacheResult(key_, entry, ttl);
Miriam Gershensonc282ab42017-11-20 23:19:581803
1804 RecordJobHistograms(entry.error());
[email protected]16ee26d2012-03-08 03:34:351805
maksim.sisov31452af2016-07-27 06:38:101806 // Complete all of the requests that were attached to the job and
1807 // detach them.
1808 while (!requests_.empty()) {
David Benjamina5677192018-04-23 23:25:421809 RequestImpl* req = requests_.head()->value();
1810 req->RemoveFromList();
[email protected]0f292de02012-02-01 22:28:201811 DCHECK_EQ(this, req->job());
1812 // Update the net log and notify registered observers.
juliatuttle317860e2016-05-12 14:47:221813 LogFinishRequest(req->source_net_log(), req->info(), entry.error());
[email protected]51b9a6b2012-06-25 21:50:291814 if (did_complete) {
1815 // Record effective total time from creation to completion.
Miriam Gershenson90d05e02017-09-28 19:29:281816 RecordTotalTime(req->info().is_speculative(), false,
[email protected]51b9a6b2012-06-25 21:50:291817 base::TimeTicks::Now() - req->request_time());
1818 }
maksim.sisov31452af2016-07-27 06:38:101819 req->OnJobCompleted(this, entry.error(), entry.addresses());
[email protected]0f292de02012-02-01 22:28:201820
1821 // Check if the resolver was destroyed as a result of running the
1822 // callback. If it was, we could continue, but we choose to bail.
[email protected]11fbca0b2013-06-02 23:37:211823 if (!resolver_.get())
[email protected]0f292de02012-02-01 22:28:201824 return;
1825 }
1826 }
1827
[email protected]1339a2a22012-10-17 08:39:431828 // Convenience wrapper for CompleteRequests in case of failure.
1829 void CompleteRequestsWithError(int net_error) {
Rob Percival94f21ad2017-11-14 10:20:241830 CompleteRequests(HostCache::Entry(net_error, AddressList(),
1831 HostCache::Entry::SOURCE_UNKNOWN),
[email protected]895123222012-10-25 15:21:171832 base::TimeDelta());
[email protected]1339a2a22012-10-17 08:39:431833 }
1834
Brad Lassey786929ad2018-02-21 20:54:271835 RequestPriority priority() const override {
[email protected]b4481b222012-03-16 17:13:111836 return priority_tracker_.highest_priority();
1837 }
1838
1839 // Number of non-canceled requests in |requests_|.
1840 size_t num_active_requests() const {
1841 return priority_tracker_.total_count();
1842 }
1843
wezb9820d42016-06-22 23:41:041844 bool is_dns_running() const { return !!dns_task_; }
[email protected]b4481b222012-03-16 17:13:111845
wezb9820d42016-06-22 23:41:041846 bool is_proc_running() const { return !!proc_task_; }
[email protected]b4481b222012-03-16 17:13:111847
[email protected]0f292de02012-02-01 22:28:201848 base::WeakPtr<HostResolverImpl> resolver_;
1849
1850 Key key_;
1851
1852 // Tracks the highest priority across |requests_|.
1853 PriorityTracker priority_tracker_;
1854
Miriam Gershensone42adb22017-10-16 16:19:381855 // Task runner used for HostResolverProc.
1856 scoped_refptr<base::TaskRunner> proc_task_runner_;
1857
[email protected]0f292de02012-02-01 22:28:201858 bool had_non_speculative_request_;
1859
[email protected]51b9a6b2012-06-25 21:50:291860 // Distinguishes measurements taken while DnsClient was fully configured.
1861 bool had_dns_config_;
1862
[email protected]daae1322013-09-05 18:26:501863 // Number of slots occupied by this Job in resolver's PrioritizedDispatcher.
1864 unsigned num_occupied_job_slots_;
1865
[email protected]1d932852012-06-19 19:40:331866 // Result of DnsTask.
1867 int dns_task_error_;
[email protected]1def74c2012-03-22 20:07:001868
[email protected]51b9a6b2012-06-25 21:50:291869 const base::TimeTicks creation_time_;
1870 base::TimeTicks priority_change_time_;
Miriam Gershenson61604662017-09-28 23:51:111871 base::TimeTicks start_time_;
[email protected]51b9a6b2012-06-25 21:50:291872
tfarina428341112016-09-22 13:38:201873 NetLogWithSource net_log_;
[email protected]0f292de02012-02-01 22:28:201874
[email protected]b3601bc22012-02-21 21:23:201875 // Resolves the host using a HostResolverProc.
[email protected]0f292de02012-02-01 22:28:201876 scoped_refptr<ProcTask> proc_task_;
1877
[email protected]b3601bc22012-02-21 21:23:201878 // Resolves the host using a DnsTransaction.
danakj22f90e72016-04-16 01:55:401879 std::unique_ptr<DnsTask> dns_task_;
[email protected]b3601bc22012-02-21 21:23:201880
[email protected]0f292de02012-02-01 22:28:201881 // All Requests waiting for the result of this Job. Some can be canceled.
David Benjamina5677192018-04-23 23:25:421882 base::LinkedList<RequestImpl> requests_;
[email protected]0f292de02012-02-01 22:28:201883
[email protected]16ee26d2012-03-08 03:34:351884 // A handle used in |HostResolverImpl::dispatcher_|.
[email protected]0f292de02012-02-01 22:28:201885 PrioritizedDispatcher::Handle handle_;
[email protected]68ad3ee2010-01-30 03:45:391886};
1887
1888//-----------------------------------------------------------------------------
1889
[email protected]0f292de02012-02-01 22:28:201890HostResolverImpl::ProcTaskParams::ProcTaskParams(
[email protected]e95d3aca2010-01-11 22:47:431891 HostResolverProc* resolver_proc,
[email protected]0f292de02012-02-01 22:28:201892 size_t max_retry_attempts)
1893 : resolver_proc(resolver_proc),
1894 max_retry_attempts(max_retry_attempts),
ttuttlecf1158bf2016-03-18 16:37:441895 unresponsive_delay(
1896 base::TimeDelta::FromMilliseconds(kDnsDefaultUnresponsiveDelayMs)),
[email protected]0f292de02012-02-01 22:28:201897 retry_factor(2) {
[email protected]106ccd2c2014-06-17 09:21:001898 // Maximum of 4 retry attempts for host resolution.
1899 static const size_t kDefaultMaxRetryAttempts = 4u;
1900 if (max_retry_attempts == HostResolver::kDefaultRetryAttempts)
1901 max_retry_attempts = kDefaultMaxRetryAttempts;
[email protected]0f292de02012-02-01 22:28:201902}
1903
vmpstracd23b72016-02-26 21:08:551904HostResolverImpl::ProcTaskParams::ProcTaskParams(const ProcTaskParams& other) =
1905 default;
1906
Chris Watkins68b15032017-12-01 03:07:131907HostResolverImpl::ProcTaskParams::~ProcTaskParams() = default;
[email protected]0f292de02012-02-01 22:28:201908
[email protected]b59ff372009-07-15 22:04:321909HostResolverImpl::~HostResolverImpl() {
gab47aa7da2017-06-02 16:09:431910 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
[email protected]daae1322013-09-05 18:26:501911 // Prevent the dispatcher from starting new jobs.
[email protected]106ccd2c2014-06-17 09:21:001912 dispatcher_->SetLimitsToZero();
avi9e72eb482016-12-09 21:10:541913 // It's now safe for Jobs to call KillDnsTask on destruction, because
[email protected]daae1322013-09-05 18:26:501914 // OnJobComplete will not start any new jobs.
avi9e72eb482016-12-09 21:10:541915 jobs_.clear();
[email protected]e95d3aca2010-01-11 22:47:431916
[email protected]232a5812011-03-04 22:42:081917 NetworkChangeNotifier::RemoveIPAddressObserver(this);
ttuttlecf1158bf2016-03-18 16:37:441918 NetworkChangeNotifier::RemoveConnectionTypeObserver(this);
[email protected]bb0e34542012-08-31 19:52:401919 NetworkChangeNotifier::RemoveDNSObserver(this);
[email protected]b59ff372009-07-15 22:04:321920}
1921
[email protected]0f292de02012-02-01 22:28:201922void HostResolverImpl::SetMaxQueuedJobs(size_t value) {
[email protected]106ccd2c2014-06-17 09:21:001923 DCHECK_EQ(0u, dispatcher_->num_queued_jobs());
[email protected]0f292de02012-02-01 22:28:201924 DCHECK_GT(value, 0u);
1925 max_queued_jobs_ = value;
[email protected]be1a48b2011-01-20 00:12:131926}
1927
[email protected]684970b2009-08-14 04:54:461928int HostResolverImpl::Resolve(const RequestInfo& info,
[email protected]5109c1952013-08-20 18:44:101929 RequestPriority priority,
[email protected]b59ff372009-07-15 22:04:321930 AddressList* addresses,
[email protected]aa22b242011-11-16 18:58:291931 const CompletionCallback& callback,
maksim.sisov31452af2016-07-27 06:38:101932 std::unique_ptr<Request>* out_req,
tfarina428341112016-09-22 13:38:201933 const NetLogWithSource& source_net_log) {
[email protected]95a214c2011-08-04 21:50:401934 DCHECK(addresses);
gab47aa7da2017-06-02 16:09:431935 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
[email protected]aa22b242011-11-16 18:58:291936 DCHECK_EQ(false, callback.is_null());
maksim.sisov31452af2016-07-27 06:38:101937 DCHECK(out_req);
[email protected]1ac6af92010-06-03 21:00:141938
Chris Palmer9cbf4212017-07-19 01:54:551939 LogStartRequest(source_net_log, info);
pauljensen19eb73422015-04-15 23:20:061940
Matt Menke23b4bbf82017-07-20 19:11:291941 Key key;
1942 int rv = ResolveHelper(info, false, nullptr, source_net_log, addresses, &key);
[email protected]95a214c2011-08-04 21:50:401943 if (rv != ERR_DNS_CACHE_MISS) {
xunjieli26f90452014-11-10 16:23:021944 LogFinishRequest(source_net_log, info, rv);
Miriam Gershenson90d05e02017-09-28 19:29:281945 RecordTotalTime(info.is_speculative(), true, base::TimeDelta());
[email protected]95a214c2011-08-04 21:50:401946 return rv;
[email protected]38368712011-03-02 08:09:401947 }
1948
[email protected]0f292de02012-02-01 22:28:201949 // Next we need to attach our request to a "job". This job is responsible for
1950 // calling "getaddrinfo(hostname)" on a worker thread.
1951
avi9e72eb482016-12-09 21:10:541952 auto jobit = jobs_.find(key);
[email protected]0f292de02012-02-01 22:28:201953 Job* job;
1954 if (jobit == jobs_.end()) {
Miriam Gershensone42adb22017-10-16 16:19:381955 job = new Job(weak_ptr_factory_.GetWeakPtr(), key, priority,
1956 proc_task_runner_, source_net_log);
[email protected]daae1322013-09-05 18:26:501957 job->Schedule(false);
[email protected]0f292de02012-02-01 22:28:201958
1959 // Check for queue overflow.
[email protected]106ccd2c2014-06-17 09:21:001960 if (dispatcher_->num_queued_jobs() > max_queued_jobs_) {
1961 Job* evicted = static_cast<Job*>(dispatcher_->EvictOldestLowest());
[email protected]0f292de02012-02-01 22:28:201962 DCHECK(evicted);
[email protected]16ee26d2012-03-08 03:34:351963 evicted->OnEvicted(); // Deletes |evicted|.
[email protected]0f292de02012-02-01 22:28:201964 if (evicted == job) {
[email protected]0f292de02012-02-01 22:28:201965 rv = ERR_HOST_RESOLVER_QUEUE_TOO_LARGE;
xunjieli26f90452014-11-10 16:23:021966 LogFinishRequest(source_net_log, info, rv);
[email protected]0f292de02012-02-01 22:28:201967 return rv;
1968 }
[email protected]0f292de02012-02-01 22:28:201969 }
avi9e72eb482016-12-09 21:10:541970 jobs_[key] = base::WrapUnique(job);
[email protected]0f292de02012-02-01 22:28:201971 } else {
avi9e72eb482016-12-09 21:10:541972 job = jobit->second.get();
[email protected]0f292de02012-02-01 22:28:201973 }
1974
1975 // Can't complete synchronously. Create and attach request.
Jeremy Roman0579ed62017-08-29 15:56:191976 auto req = std::make_unique<RequestImpl>(source_net_log, info, priority,
avi9e72eb482016-12-09 21:10:541977 callback, addresses, job);
maksim.sisov31452af2016-07-27 06:38:101978 job->AddRequest(req.get());
1979 *out_req = std::move(req);
[email protected]b59ff372009-07-15 22:04:321980
[email protected]0f292de02012-02-01 22:28:201981 // Completion happens during Job::CompleteRequests().
[email protected]b59ff372009-07-15 22:04:321982 return ERR_IO_PENDING;
1983}
1984
Francois Doraya2d01ba2017-09-25 19:17:401985HostResolverImpl::HostResolverImpl(const Options& options, NetLog* net_log)
mmenke91c17162016-06-02 16:03:231986 : max_queued_jobs_(0),
1987 proc_params_(NULL, options.max_retry_attempts),
1988 net_log_(net_log),
1989 received_dns_config_(false),
1990 num_dns_failures_(0),
mgershaf9a9232017-04-13 20:19:031991 assume_ipv6_failure_on_wifi_(false),
mmenke91c17162016-06-02 16:03:231992 use_local_ipv6_(false),
1993 last_ipv6_probe_result_(true),
mmenke91c17162016-06-02 16:03:231994 additional_resolver_flags_(0),
1995 fallback_to_proctask_(true),
mmenke91c17162016-06-02 16:03:231996 weak_ptr_factory_(this),
1997 probe_weak_ptr_factory_(this) {
1998 if (options.enable_caching)
1999 cache_ = HostCache::CreateDefaultCache();
2000
2001 PrioritizedDispatcher::Limits job_limits = options.GetDispatcherLimits();
2002 dispatcher_.reset(new PrioritizedDispatcher(job_limits));
2003 max_queued_jobs_ = job_limits.total_jobs * 100u;
2004
2005 DCHECK_GE(dispatcher_->num_priorities(), static_cast<size_t>(NUM_PRIORITIES));
2006
Miriam Gershensone42adb22017-10-16 16:19:382007 proc_task_runner_ = base::CreateTaskRunnerWithTraits(
Maks Orlovich5393c8682018-02-26 16:17:502008 {base::MayBlock(), priority_mode.Get(),
2009 base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN});
Miriam Gershensone42adb22017-10-16 16:19:382010
mmenke91c17162016-06-02 16:03:232011#if defined(OS_WIN)
2012 EnsureWinsockInit();
2013#endif
Fabrice de Gans-Riberi7de47372018-05-08 20:23:472014#if (defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)) || \
2015 defined(OS_FUCHSIA)
mmenke91c17162016-06-02 16:03:232016 RunLoopbackProbeJob();
2017#endif
2018 NetworkChangeNotifier::AddIPAddressObserver(this);
2019 NetworkChangeNotifier::AddConnectionTypeObserver(this);
2020 NetworkChangeNotifier::AddDNSObserver(this);
mmenke91c17162016-06-02 16:03:232021#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD) && \
Fabrice de Gans-Riberi65421f62018-05-22 23:16:182022 !defined(OS_ANDROID)
mmenke91c17162016-06-02 16:03:232023 EnsureDnsReloaderInit();
2024#endif
2025
2026 OnConnectionTypeChanged(NetworkChangeNotifier::GetConnectionType());
2027
2028 {
2029 DnsConfig dns_config;
2030 NetworkChangeNotifier::GetDnsConfig(&dns_config);
2031 received_dns_config_ = dns_config.IsValid();
2032 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
2033 use_local_ipv6_ = !dns_config.IsValid() || dns_config.use_local_ipv6;
2034 }
2035
2036 fallback_to_proctask_ = !ConfigureAsyncDnsNoFallbackFieldTrial();
2037}
2038
2039void HostResolverImpl::SetHaveOnlyLoopbackAddresses(bool result) {
2040 if (result) {
2041 additional_resolver_flags_ |= HOST_RESOLVER_LOOPBACK_ONLY;
2042 } else {
2043 additional_resolver_flags_ &= ~HOST_RESOLVER_LOOPBACK_ONLY;
2044 }
2045}
2046
Miriam Gershensone42adb22017-10-16 16:19:382047void HostResolverImpl::SetTaskRunnerForTesting(
2048 scoped_refptr<base::TaskRunner> task_runner) {
2049 proc_task_runner_ = std::move(task_runner);
2050}
2051
Matt Menke23b4bbf82017-07-20 19:11:292052int HostResolverImpl::ResolveHelper(const RequestInfo& info,
juliatuttle9fb7aeb2016-06-06 20:16:332053 bool allow_stale,
2054 HostCache::EntryStaleness* stale_info,
Matt Menke23b4bbf82017-07-20 19:11:292055 const NetLogWithSource& source_net_log,
2056 AddressList* addresses,
2057 Key* key) {
2058 IPAddress ip_address;
2059 IPAddress* ip_address_ptr = nullptr;
2060 if (ip_address.AssignFromIPLiteral(info.hostname())) {
2061 ip_address_ptr = &ip_address;
2062 } else {
2063 // Check that the caller supplied a valid hostname to resolve.
2064 if (!IsValidDNSDomain(info.hostname()))
2065 return ERR_NAME_NOT_RESOLVED;
2066 }
2067
2068 // Build a key that identifies the request in the cache and in the
2069 // outstanding jobs map.
2070 *key = GetEffectiveKeyForRequest(info, ip_address_ptr, source_net_log);
2071
juliatuttle9fb7aeb2016-06-06 20:16:332072 DCHECK(allow_stale == !!stale_info);
[email protected]95a214c2011-08-04 21:50:402073 // The result of |getaddrinfo| for empty hosts is inconsistent across systems.
2074 // On Windows it gives the default interface's address, whereas on Linux it
2075 // gives an error. We will make it fail on all platforms for consistency.
juliatuttle9fb7aeb2016-06-06 20:16:332076 if (info.hostname().empty() || info.hostname().size() > kMaxHostLength) {
2077 MakeNotStale(stale_info);
[email protected]95a214c2011-08-04 21:50:402078 return ERR_NAME_NOT_RESOLVED;
juliatuttle9fb7aeb2016-06-06 20:16:332079 }
[email protected]95a214c2011-08-04 21:50:402080
2081 int net_error = ERR_UNEXPECTED;
Matt Menke23b4bbf82017-07-20 19:11:292082 if (ResolveAsIP(*key, info, ip_address_ptr, &net_error, addresses)) {
juliatuttle9fb7aeb2016-06-06 20:16:332083 MakeNotStale(stale_info);
[email protected]95a214c2011-08-04 21:50:402084 return net_error;
juliatuttle9fb7aeb2016-06-06 20:16:332085 }
Mike Westda1c690e2017-08-12 05:57:162086
2087 // Special-case localhost names, as per the recommendations in
2088 // https://tools.ietf.org/html/draft-west-let-localhost-be-localhost.
2089 if (ServeLocalhost(*key, info, addresses)) {
2090 MakeNotStale(stale_info);
2091 return OK;
2092 }
2093
Matt Menke23b4bbf82017-07-20 19:11:292094 if (ServeFromCache(*key, info, &net_error, addresses, allow_stale,
juliatuttle9fb7aeb2016-06-06 20:16:332095 stale_info)) {
mgersh33d23c02017-03-29 20:24:252096 source_net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_CACHE_HIT,
2097 addresses->CreateNetLogCallback());
juliatuttle9fb7aeb2016-06-06 20:16:332098 // |ServeFromCache()| will set |*stale_info| as needed.
[email protected]78eac2a2012-03-14 19:09:272099 return net_error;
2100 }
Mike Westda1c690e2017-08-12 05:57:162101
[email protected]78eac2a2012-03-14 19:09:272102 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2103 // http://crbug.com/117655
Matt Menke23b4bbf82017-07-20 19:11:292104 if (ServeFromHosts(*key, info, addresses)) {
mgersh33d23c02017-03-29 20:24:252105 source_net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_HOSTS_HIT,
2106 addresses->CreateNetLogCallback());
juliatuttle9fb7aeb2016-06-06 20:16:332107 MakeNotStale(stale_info);
[email protected]78eac2a2012-03-14 19:09:272108 return OK;
2109 }
estarkd1bc206e2015-06-20 00:44:392110
[email protected]78eac2a2012-03-14 19:09:272111 return ERR_DNS_CACHE_MISS;
[email protected]95a214c2011-08-04 21:50:402112}
2113
2114int HostResolverImpl::ResolveFromCache(const RequestInfo& info,
2115 AddressList* addresses,
tfarina428341112016-09-22 13:38:202116 const NetLogWithSource& source_net_log) {
gab47aa7da2017-06-02 16:09:432117 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
[email protected]95a214c2011-08-04 21:50:402118 DCHECK(addresses);
2119
[email protected]95a214c2011-08-04 21:50:402120 // Update the net log and notify registered observers.
xunjieli26f90452014-11-10 16:23:022121 LogStartRequest(source_net_log, info);
[email protected]95a214c2011-08-04 21:50:402122
Matt Menke23b4bbf82017-07-20 19:11:292123 Key key;
2124 int rv = ResolveHelper(info, false, nullptr, source_net_log, addresses, &key);
[email protected]95a214c2011-08-04 21:50:402125
xunjieli26f90452014-11-10 16:23:022126 LogFinishRequest(source_net_log, info, rv);
[email protected]95a214c2011-08-04 21:50:402127 return rv;
2128}
2129
[email protected]a8883e452012-11-17 05:58:062130void HostResolverImpl::SetDnsClientEnabled(bool enabled) {
gab47aa7da2017-06-02 16:09:432131 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
[email protected]a8883e452012-11-17 05:58:062132#if defined(ENABLE_BUILT_IN_DNS)
2133 if (enabled && !dns_client_) {
2134 SetDnsClient(DnsClient::CreateClient(net_log_));
2135 } else if (!enabled && dns_client_) {
danakj22f90e72016-04-16 01:55:402136 SetDnsClient(std::unique_ptr<DnsClient>());
[email protected]a8883e452012-11-17 05:58:062137 }
2138#endif
2139}
2140
[email protected]489d1a82011-10-12 03:09:112141HostCache* HostResolverImpl::GetHostCache() {
2142 return cache_.get();
2143}
[email protected]95a214c2011-08-04 21:50:402144
Rob Percivalbc658a22017-12-13 08:24:422145bool HostResolverImpl::HasCached(base::StringPiece hostname,
2146 HostCache::Entry::Source* source_out,
2147 HostCache::EntryStaleness* stale_out) const {
2148 if (!cache_)
2149 return false;
2150
2151 return cache_->HasEntry(hostname, source_out, stale_out);
2152}
2153
danakj22f90e72016-04-16 01:55:402154std::unique_ptr<base::Value> HostResolverImpl::GetDnsConfigAsValue() const {
[email protected]17e92032012-03-29 00:56:242155 // Check if async DNS is disabled.
2156 if (!dns_client_.get())
tfhef3618f2016-01-11 23:07:082157 return nullptr;
[email protected]17e92032012-03-29 00:56:242158
2159 // Check if async DNS is enabled, but we currently have no configuration
2160 // for it.
2161 const DnsConfig* dns_config = dns_client_->GetConfig();
wezb9820d42016-06-22 23:41:042162 if (!dns_config)
Jeremy Roman0579ed62017-08-29 15:56:192163 return std::make_unique<base::DictionaryValue>();
[email protected]17e92032012-03-29 00:56:242164
2165 return dns_config->ToValue();
2166}
2167
juliatuttle9fb7aeb2016-06-06 20:16:332168int HostResolverImpl::ResolveStaleFromCache(
2169 const RequestInfo& info,
2170 AddressList* addresses,
2171 HostCache::EntryStaleness* stale_info,
tfarina428341112016-09-22 13:38:202172 const NetLogWithSource& source_net_log) {
gab47aa7da2017-06-02 16:09:432173 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
juliatuttle9fb7aeb2016-06-06 20:16:332174 DCHECK(addresses);
2175 DCHECK(stale_info);
2176
2177 // Update the net log and notify registered observers.
2178 LogStartRequest(source_net_log, info);
2179
Matt Menke23b4bbf82017-07-20 19:11:292180 Key key;
2181 int rv =
2182 ResolveHelper(info, true, stale_info, source_net_log, addresses, &key);
juliatuttle9fb7aeb2016-06-06 20:16:332183 LogFinishRequest(source_net_log, info, rv);
2184 return rv;
2185}
2186
Miriam Gershenson2839ef112017-08-30 03:25:372187size_t HostResolverImpl::LastRestoredCacheSize() const {
2188 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
2189
2190 return cache_ ? cache_->last_restore_size() : 0;
2191}
2192
2193size_t HostResolverImpl::CacheSize() const {
2194 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
2195
2196 return cache_ ? cache_->size() : 0;
2197}
2198
mgershaf9a9232017-04-13 20:19:032199void HostResolverImpl::SetNoIPv6OnWifi(bool no_ipv6_on_wifi) {
gab47aa7da2017-06-02 16:09:432200 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
mgershaf9a9232017-04-13 20:19:032201 assume_ipv6_failure_on_wifi_ = no_ipv6_on_wifi;
2202}
2203
2204bool HostResolverImpl::GetNoIPv6OnWifi() {
2205 return assume_ipv6_failure_on_wifi_;
2206}
2207
Brad Lassey786929ad2018-02-21 20:54:272208void HostResolverImpl::SetRequestContext(URLRequestContext* context) {
2209 if (context != url_request_context_) {
2210 url_request_context_ = context;
2211 }
2212}
2213
2214void HostResolverImpl::ClearDnsOverHttpsServers() {
2215 if (dns_over_https_servers_.size() == 0)
2216 return;
2217
2218 dns_over_https_servers_.clear();
2219
2220 if (dns_client_.get() && dns_client_->GetConfig())
2221 UpdateDNSConfig(true);
2222}
2223
2224void HostResolverImpl::AddDnsOverHttpsServer(std::string spec, bool use_post) {
2225 GURL url(spec);
2226 if (!url.SchemeIs("https"))
2227 return;
2228
2229 dns_over_https_servers_.emplace_back(url, use_post);
2230
2231 if (dns_client_.get() && dns_client_->GetConfig())
2232 UpdateDNSConfig(true);
2233}
2234
[email protected]95a214c2011-08-04 21:50:402235bool HostResolverImpl::ResolveAsIP(const Key& key,
2236 const RequestInfo& info,
martijna23c8962016-03-04 18:18:512237 const IPAddress* ip_address,
[email protected]95a214c2011-08-04 21:50:402238 int* net_error,
2239 AddressList* addresses) {
2240 DCHECK(addresses);
2241 DCHECK(net_error);
martijna23c8962016-03-04 18:18:512242 if (ip_address == nullptr)
[email protected]95a214c2011-08-04 21:50:402243 return false;
2244
[email protected]95a214c2011-08-04 21:50:402245 *net_error = OK;
martijna23c8962016-03-04 18:18:512246 AddressFamily family = GetAddressFamily(*ip_address);
cbentzel1906f872015-06-05 16:25:252247 if (key.address_family != ADDRESS_FAMILY_UNSPECIFIED &&
2248 key.address_family != family) {
[email protected]1c7cf3f82014-08-07 21:33:482249 // Don't return IPv6 addresses for IPv4 queries, and vice versa.
[email protected]95a214c2011-08-04 21:50:402250 *net_error = ERR_NAME_NOT_RESOLVED;
2251 } else {
martijna23c8962016-03-04 18:18:512252 *addresses = AddressList::CreateFromIPAddress(*ip_address, info.port());
[email protected]7054e78f2012-05-07 21:44:562253 if (key.host_resolver_flags & HOST_RESOLVER_CANONNAME)
2254 addresses->SetDefaultCanonicalName();
[email protected]95a214c2011-08-04 21:50:402255 }
2256 return true;
2257}
2258
2259bool HostResolverImpl::ServeFromCache(const Key& key,
2260 const RequestInfo& info,
[email protected]95a214c2011-08-04 21:50:402261 int* net_error,
juliatuttle9fb7aeb2016-06-06 20:16:332262 AddressList* addresses,
2263 bool allow_stale,
2264 HostCache::EntryStaleness* stale_info) {
[email protected]95a214c2011-08-04 21:50:402265 DCHECK(addresses);
2266 DCHECK(net_error);
juliatuttle9fb7aeb2016-06-06 20:16:332267 DCHECK(allow_stale == !!stale_info);
[email protected]95a214c2011-08-04 21:50:402268 if (!info.allow_cached_response() || !cache_.get())
2269 return false;
2270
juliatuttle9fb7aeb2016-06-06 20:16:332271 const HostCache::Entry* cache_entry;
2272 if (allow_stale)
2273 cache_entry = cache_->LookupStale(key, base::TimeTicks::Now(), stale_info);
2274 else
2275 cache_entry = cache_->Lookup(key, base::TimeTicks::Now());
[email protected]95a214c2011-08-04 21:50:402276 if (!cache_entry)
2277 return false;
2278
juliatuttle317860e2016-05-12 14:47:222279 *net_error = cache_entry->error();
[email protected]7054e78f2012-05-07 21:44:562280 if (*net_error == OK) {
[email protected]1339a2a22012-10-17 08:39:432281 if (cache_entry->has_ttl())
juliatuttle317860e2016-05-12 14:47:222282 RecordTTL(cache_entry->ttl());
2283 *addresses = EnsurePortOnAddressList(cache_entry->addresses(), info.port());
[email protected]7054e78f2012-05-07 21:44:562284 }
[email protected]95a214c2011-08-04 21:50:402285 return true;
2286}
2287
[email protected]78eac2a2012-03-14 19:09:272288bool HostResolverImpl::ServeFromHosts(const Key& key,
2289 const RequestInfo& info,
2290 AddressList* addresses) {
2291 DCHECK(addresses);
2292 if (!HaveDnsConfig())
2293 return false;
[email protected]05a79d42013-03-28 07:30:092294 addresses->clear();
2295
[email protected]cb507622012-03-23 16:17:062296 // HOSTS lookups are case-insensitive.
brettw8e2106d2015-08-11 19:30:222297 std::string hostname = base::ToLowerASCII(key.hostname);
[email protected]cb507622012-03-23 16:17:062298
[email protected]05a79d42013-03-28 07:30:092299 const DnsHosts& hosts = dns_client_->GetConfig()->hosts;
2300
[email protected]78eac2a2012-03-14 19:09:272301 // If |address_family| is ADDRESS_FAMILY_UNSPECIFIED other implementations
2302 // (glibc and c-ares) return the first matching line. We have more
2303 // flexibility, but lose implicit ordering.
[email protected]05a79d42013-03-28 07:30:092304 // We prefer IPv6 because "happy eyeballs" will fall back to IPv4 if
2305 // necessary.
2306 if (key.address_family == ADDRESS_FAMILY_IPV6 ||
2307 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
2308 DnsHosts::const_iterator it = hosts.find(
2309 DnsHostsKey(hostname, ADDRESS_FAMILY_IPV6));
2310 if (it != hosts.end())
2311 addresses->push_back(IPEndPoint(it->second, info.port()));
[email protected]78eac2a2012-03-14 19:09:272312 }
2313
[email protected]05a79d42013-03-28 07:30:092314 if (key.address_family == ADDRESS_FAMILY_IPV4 ||
2315 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
2316 DnsHosts::const_iterator it = hosts.find(
2317 DnsHostsKey(hostname, ADDRESS_FAMILY_IPV4));
2318 if (it != hosts.end())
2319 addresses->push_back(IPEndPoint(it->second, info.port()));
2320 }
2321
[email protected]ec666ab22013-04-17 20:05:592322 // If got only loopback addresses and the family was restricted, resolve
2323 // again, without restrictions. See SystemHostResolverCall for rationale.
2324 if ((key.host_resolver_flags &
2325 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6) &&
2326 IsAllIPv4Loopback(*addresses)) {
2327 Key new_key(key);
2328 new_key.address_family = ADDRESS_FAMILY_UNSPECIFIED;
2329 new_key.host_resolver_flags &=
2330 ~HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
2331 return ServeFromHosts(new_key, info, addresses);
2332 }
[email protected]05a79d42013-03-28 07:30:092333 return !addresses->empty();
[email protected]78eac2a2012-03-14 19:09:272334}
2335
estarkd1bc206e2015-06-20 00:44:392336bool HostResolverImpl::ServeLocalhost(const Key& key,
2337 const RequestInfo& info,
2338 AddressList* addresses) {
2339 AddressList resolved_addresses;
2340 if (!ResolveLocalHostname(key.hostname, info.port(), &resolved_addresses))
2341 return false;
2342
2343 addresses->clear();
2344
2345 for (const auto& address : resolved_addresses) {
2346 // Include the address if:
2347 // - caller didn't specify an address family, or
2348 // - caller specifically asked for the address family of this address, or
2349 // - this is an IPv6 address and caller specifically asked for IPv4 due
2350 // to lack of detected IPv6 support. (See SystemHostResolverCall for
2351 // rationale).
2352 if (key.address_family == ADDRESS_FAMILY_UNSPECIFIED ||
2353 key.address_family == address.GetFamily() ||
2354 (address.GetFamily() == ADDRESS_FAMILY_IPV6 &&
2355 key.address_family == ADDRESS_FAMILY_IPV4 &&
2356 (key.host_resolver_flags &
2357 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6))) {
2358 addresses->push_back(address);
2359 }
2360 }
2361
2362 return true;
2363}
2364
[email protected]16ee26d2012-03-08 03:34:352365void HostResolverImpl::CacheResult(const Key& key,
[email protected]1339a2a22012-10-17 08:39:432366 const HostCache::Entry& entry,
[email protected]16ee26d2012-03-08 03:34:352367 base::TimeDelta ttl) {
Miriam Gershensone3bc63022017-10-09 19:57:052368 // Don't cache an error unless it has a positive TTL.
2369 if (cache_.get() && (entry.error() == OK || ttl > base::TimeDelta()))
[email protected]1339a2a22012-10-17 08:39:432370 cache_->Set(key, entry, base::TimeTicks::Now(), ttl);
[email protected]ef4c40c2010-09-01 14:42:032371}
2372
[email protected]0f292de02012-02-01 22:28:202373void HostResolverImpl::RemoveJob(Job* job) {
2374 DCHECK(job);
avi9e72eb482016-12-09 21:10:542375 auto it = jobs_.find(job->key());
2376 if (it != jobs_.end() && it->second.get() == job) {
2377 it->second.release();
[email protected]16ee26d2012-03-08 03:34:352378 jobs_.erase(it);
avi9e72eb482016-12-09 21:10:542379 }
[email protected]b59ff372009-07-15 22:04:322380}
2381
[email protected]137af622010-02-05 02:14:352382HostResolverImpl::Key HostResolverImpl::GetEffectiveKeyForRequest(
pauljensen19eb73422015-04-15 23:20:062383 const RequestInfo& info,
martijna23c8962016-03-04 18:18:512384 const IPAddress* ip_address,
tfarina428341112016-09-22 13:38:202385 const NetLogWithSource& net_log) {
[email protected]eaf3a3b2010-09-03 20:34:272386 HostResolverFlags effective_flags =
2387 info.host_resolver_flags() | additional_resolver_flags_;
[email protected]137af622010-02-05 02:14:352388 AddressFamily effective_address_family = info.address_family();
[email protected]9db6f702013-04-10 18:10:512389
mgersh3eba057d2017-02-28 18:50:562390 if (effective_address_family == ADDRESS_FAMILY_UNSPECIFIED &&
2391 // When resolving IPv4 literals, there's no need to probe for IPv6.
2392 // When resolving IPv6 literals, there's no benefit to artificially
2393 // limiting our resolution based on a probe. Prior logic ensures
2394 // that this query is UNSPECIFIED (see effective_address_family
2395 // check above) so the code requesting the resolution should be amenable
2396 // to receiving a IPv6 resolution.
2397 !use_local_ipv6_ && ip_address == nullptr && !IsIPv6Reachable(net_log)) {
2398 effective_address_family = ADDRESS_FAMILY_IPV4;
2399 effective_flags |= HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
[email protected]9db6f702013-04-10 18:10:512400 }
2401
estarkd1bc206e2015-06-20 00:44:392402 return Key(info.hostname(), effective_address_family, effective_flags);
[email protected]137af622010-02-05 02:14:352403}
2404
tfarina428341112016-09-22 13:38:202405bool HostResolverImpl::IsIPv6Reachable(const NetLogWithSource& net_log) {
mgershaf9a9232017-04-13 20:19:032406 // Don't bother checking if the device is on WiFi and IPv6 is assumed to not
2407 // work on WiFi.
2408 if (assume_ipv6_failure_on_wifi_ &&
2409 NetworkChangeNotifier::GetConnectionType() ==
2410 NetworkChangeNotifier::CONNECTION_WIFI) {
2411 return false;
2412 }
2413
eroman1a17ef32016-12-14 01:06:092414 // Cache the result for kIPv6ProbePeriodMs (measured from after
2415 // IsGloballyReachable() completes).
sergeyub8cdc212015-05-14 18:50:372416 bool cached = true;
eroman1a17ef32016-12-14 01:06:092417 if ((base::TimeTicks::Now() - last_ipv6_probe_time_).InMilliseconds() >
2418 kIPv6ProbePeriodMs) {
martijna23c8962016-03-04 18:18:512419 last_ipv6_probe_result_ =
2420 IsGloballyReachable(IPAddress(kIPv6ProbeAddress), net_log);
eroman1a17ef32016-12-14 01:06:092421 last_ipv6_probe_time_ = base::TimeTicks::Now();
sergeyub8cdc212015-05-14 18:50:372422 cached = false;
2423 }
mikecirone8b85c432016-09-08 19:11:002424 net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_IPV6_REACHABILITY_CHECK,
sergeyub8cdc212015-05-14 18:50:372425 base::Bind(&NetLogIPv6AvailableCallback,
2426 last_ipv6_probe_result_, cached));
2427 return last_ipv6_probe_result_;
2428}
2429
mgershaf9a9232017-04-13 20:19:032430bool HostResolverImpl::IsGloballyReachable(const IPAddress& dest,
2431 const NetLogWithSource& net_log) {
mgershaf9a9232017-04-13 20:19:032432 std::unique_ptr<DatagramClientSocket> socket(
2433 ClientSocketFactory::GetDefaultFactory()->CreateDatagramClientSocket(
Sergey Ulanovcbdfc8852018-03-16 20:13:282434 DatagramSocket::DEFAULT_BIND, net_log.net_log(), net_log.source()));
mgershaf9a9232017-04-13 20:19:032435 int rv = socket->Connect(IPEndPoint(dest, 53));
2436 if (rv != OK)
2437 return false;
2438 IPEndPoint endpoint;
2439 rv = socket->GetLocalAddress(&endpoint);
2440 if (rv != OK)
2441 return false;
2442 DCHECK_EQ(ADDRESS_FAMILY_IPV6, endpoint.GetFamily());
2443 const IPAddress& address = endpoint.address();
2444
2445 bool is_link_local =
2446 (address.bytes()[0] == 0xFE) && ((address.bytes()[1] & 0xC0) == 0x80);
2447 if (is_link_local)
2448 return false;
2449
2450 const uint8_t kTeredoPrefix[] = {0x20, 0x01, 0, 0};
2451 if (IPAddressStartsWith(address, kTeredoPrefix))
2452 return false;
2453
2454 return true;
2455}
2456
mmenke91c17162016-06-02 16:03:232457void HostResolverImpl::RunLoopbackProbeJob() {
Francois Doraya2d01ba2017-09-25 19:17:402458 // Run this asynchronously as it can take 40-100ms and should not block
2459 // initialization.
2460 base::PostTaskWithTraitsAndReplyWithResult(
2461 FROM_HERE,
2462 {base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
2463 base::BindOnce(&HaveOnlyLoopbackAddresses),
2464 base::BindOnce(&HostResolverImpl::SetHaveOnlyLoopbackAddresses,
2465 weak_ptr_factory_.GetWeakPtr()));
mmenke91c17162016-06-02 16:03:232466}
2467
[email protected]35ddc282010-09-21 23:42:062468void HostResolverImpl::AbortAllInProgressJobs() {
[email protected]b3601bc22012-02-21 21:23:202469 // In Abort, a Request callback could spawn new Jobs with matching keys, so
2470 // first collect and remove all running jobs from |jobs_|.
danakj22f90e72016-04-16 01:55:402471 std::vector<std::unique_ptr<Job>> jobs_to_abort;
avi9e72eb482016-12-09 21:10:542472 for (auto it = jobs_.begin(); it != jobs_.end();) {
2473 Job* job = it->second.get();
[email protected]0f292de02012-02-01 22:28:202474 if (job->is_running()) {
avi9e72eb482016-12-09 21:10:542475 jobs_to_abort.push_back(std::move(it->second));
[email protected]b3601bc22012-02-21 21:23:202476 jobs_.erase(it++);
[email protected]0f292de02012-02-01 22:28:202477 } else {
[email protected]b3601bc22012-02-21 21:23:202478 DCHECK(job->is_queued());
2479 ++it;
[email protected]0f292de02012-02-01 22:28:202480 }
[email protected]ef4c40c2010-09-01 14:42:032481 }
[email protected]b3601bc22012-02-21 21:23:202482
[email protected]daae1322013-09-05 18:26:502483 // Pause the dispatcher so it won't start any new dispatcher jobs while
2484 // aborting the old ones. This is needed so that it won't start the second
2485 // DnsTransaction for a job in |jobs_to_abort| if the DnsConfig just became
2486 // invalid.
[email protected]106ccd2c2014-06-17 09:21:002487 PrioritizedDispatcher::Limits limits = dispatcher_->GetLimits();
2488 dispatcher_->SetLimits(
[email protected]daae1322013-09-05 18:26:502489 PrioritizedDispatcher::Limits(limits.reserved_slots.size(), 0));
[email protected]70c04ab2013-08-22 16:05:122490
[email protected]57a48d32012-03-03 00:04:552491 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072492 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]57a48d32012-03-03 00:04:552493
[email protected]16ee26d2012-03-08 03:34:352494 // Then Abort them.
[email protected]11fbca0b2013-06-02 23:37:212495 for (size_t i = 0; self.get() && i < jobs_to_abort.size(); ++i) {
[email protected]57a48d32012-03-03 00:04:552496 jobs_to_abort[i]->Abort();
olli.raulaa21e9eb72015-12-17 08:18:112497 ignore_result(jobs_to_abort[i].release());
[email protected]b3601bc22012-02-21 21:23:202498 }
[email protected]daae1322013-09-05 18:26:502499
2500 if (self)
[email protected]106ccd2c2014-06-17 09:21:002501 dispatcher_->SetLimits(limits);
[email protected]daae1322013-09-05 18:26:502502}
2503
2504void HostResolverImpl::AbortDnsTasks() {
2505 // Pause the dispatcher so it won't start any new dispatcher jobs while
2506 // aborting the old ones. This is needed so that it won't start the second
2507 // DnsTransaction for a job if the DnsConfig just changed.
[email protected]106ccd2c2014-06-17 09:21:002508 PrioritizedDispatcher::Limits limits = dispatcher_->GetLimits();
2509 dispatcher_->SetLimits(
[email protected]daae1322013-09-05 18:26:502510 PrioritizedDispatcher::Limits(limits.reserved_slots.size(), 0));
2511
avi9e72eb482016-12-09 21:10:542512 for (auto it = jobs_.begin(); it != jobs_.end(); ++it)
[email protected]daae1322013-09-05 18:26:502513 it->second->AbortDnsTask();
[email protected]106ccd2c2014-06-17 09:21:002514 dispatcher_->SetLimits(limits);
[email protected]ef4c40c2010-09-01 14:42:032515}
2516
[email protected]78eac2a2012-03-14 19:09:272517void HostResolverImpl::TryServingAllJobsFromHosts() {
2518 if (!HaveDnsConfig())
2519 return;
2520
2521 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2522 // http://crbug.com/117655
2523
2524 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072525 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]78eac2a2012-03-14 19:09:272526
avi9e72eb482016-12-09 21:10:542527 for (auto it = jobs_.begin(); self.get() && it != jobs_.end();) {
2528 Job* job = it->second.get();
[email protected]78eac2a2012-03-14 19:09:272529 ++it;
2530 // This could remove |job| from |jobs_|, but iterator will remain valid.
2531 job->ServeFromHosts();
2532 }
2533}
2534
[email protected]be1a48b2011-01-20 00:12:132535void HostResolverImpl::OnIPAddressChanged() {
sergeyub8cdc212015-05-14 18:50:372536 last_ipv6_probe_time_ = base::TimeTicks();
[email protected]12faa4c2012-11-06 04:44:182537 // Abandon all ProbeJobs.
2538 probe_weak_ptr_factory_.InvalidateWeakPtrs();
Matt Menkeef8f5cf82017-07-20 22:50:172539 if (cache_.get())
mgersh5bb3b9d2017-02-13 21:27:102540 cache_->OnNetworkChange();
Fabrice de Gans-Riberi7de47372018-05-08 20:23:472541#if (defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)) || \
2542 defined(OS_FUCHSIA)
mmenke91c17162016-06-02 16:03:232543 RunLoopbackProbeJob();
[email protected]be1a48b2011-01-20 00:12:132544#endif
2545 AbortAllInProgressJobs();
2546 // |this| may be deleted inside AbortAllInProgressJobs().
2547}
2548
ttuttlecf1158bf2016-03-18 16:37:442549void HostResolverImpl::OnConnectionTypeChanged(
2550 NetworkChangeNotifier::ConnectionType type) {
2551 proc_params_.unresponsive_delay =
2552 GetTimeDeltaForConnectionTypeFromFieldTrialOrDefault(
2553 "DnsUnresponsiveDelayMsByConnectionType",
2554 base::TimeDelta::FromMilliseconds(kDnsDefaultUnresponsiveDelayMs),
2555 type);
2556}
2557
pauljensen101ed372015-04-17 00:11:422558void HostResolverImpl::OnInitialDNSConfigRead() {
2559 UpdateDNSConfig(false);
2560}
2561
[email protected]bb0e34542012-08-31 19:52:402562void HostResolverImpl::OnDNSChanged() {
pauljensen101ed372015-04-17 00:11:422563 UpdateDNSConfig(true);
2564}
2565
2566void HostResolverImpl::UpdateDNSConfig(bool config_changed) {
[email protected]bb0e34542012-08-31 19:52:402567 DnsConfig dns_config;
2568 NetworkChangeNotifier::GetDnsConfig(&dns_config);
[email protected]ec666ab22013-04-17 20:05:592569
[email protected]b4481b222012-03-16 17:13:112570 if (net_log_) {
mikecirone8b85c432016-09-08 19:11:002571 net_log_->AddGlobalEntry(NetLogEventType::DNS_CONFIG_CHANGED,
2572 base::Bind(&NetLogDnsConfigCallback, &dns_config));
[email protected]b4481b222012-03-16 17:13:112573 }
2574
[email protected]01b3b9d2012-08-13 16:18:142575 // TODO(szym): Remove once http://crbug.com/137914 is resolved.
[email protected]d7b9a2b2012-05-31 22:31:192576 received_dns_config_ = dns_config.IsValid();
[email protected]c9fa8f312013-09-17 12:24:522577 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
2578 use_local_ipv6_ = !dns_config.IsValid() || dns_config.use_local_ipv6;
[email protected]78eac2a2012-03-14 19:09:272579
[email protected]a8883e452012-11-17 05:58:062580 num_dns_failures_ = 0;
2581
[email protected]01b3b9d2012-08-13 16:18:142582 // We want a new DnsSession in place, before we Abort running Jobs, so that
2583 // the newly started jobs use the new config.
[email protected]f0f602bd2012-11-15 18:01:022584 if (dns_client_.get()) {
Miriam Gershenson44aafc122017-10-18 19:29:252585 // Make sure that if the update is an initial read, not a change, there
Miriam Gershenson668e8442017-10-31 20:31:532586 // wasn't already a DnsConfig or it's the same one.
2587 DCHECK(config_changed || !dns_client_->GetConfig() ||
2588 dns_client_->GetConfig()->Equals(dns_config));
Brad Lassey786929ad2018-02-21 20:54:272589 dns_config.dns_over_https_servers = dns_over_https_servers_;
[email protected]d7b9a2b2012-05-31 22:31:192590 dns_client_->SetConfig(dns_config);
Miriam Gershenson44aafc122017-10-18 19:29:252591 if (dns_client_->GetConfig())
[email protected]f0f602bd2012-11-15 18:01:022592 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
[email protected]f0f602bd2012-11-15 18:01:022593 }
[email protected]01b3b9d2012-08-13 16:18:142594
pauljensen101ed372015-04-17 00:11:422595 if (config_changed) {
2596 // If the DNS server has changed, existing cached info could be wrong so we
mgersh92b1af12017-03-29 15:49:232597 // have to expire our internal cache :( Note that OS level DNS caches, such
pauljensen101ed372015-04-17 00:11:422598 // as NSCD's cache should be dropped automatically by the OS when
2599 // resolv.conf changes so we don't need to do anything to clear that cache.
Matt Menkeef8f5cf82017-07-20 22:50:172600 if (cache_.get())
mgersh92b1af12017-03-29 15:49:232601 cache_->OnNetworkChange();
[email protected]01b3b9d2012-08-13 16:18:142602
pauljensen101ed372015-04-17 00:11:422603 // Life check to bail once |this| is deleted.
2604 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]f0f602bd2012-11-15 18:01:022605
pauljensen101ed372015-04-17 00:11:422606 // Existing jobs will have been sent to the original server so they need to
2607 // be aborted.
2608 AbortAllInProgressJobs();
[email protected]01b3b9d2012-08-13 16:18:142609
pauljensen101ed372015-04-17 00:11:422610 // |this| may be deleted inside AbortAllInProgressJobs().
2611 if (self.get())
2612 TryServingAllJobsFromHosts();
2613 }
[email protected]78eac2a2012-03-14 19:09:272614}
2615
2616bool HostResolverImpl::HaveDnsConfig() const {
[email protected]32b1dbcf2013-01-26 03:48:252617 // Use DnsClient only if it's fully configured and there is no override by
2618 // ScopedDefaultHostResolverProc.
2619 // The alternative is to use NetworkChangeNotifier to override DnsConfig,
2620 // but that would introduce construction order requirements for NCN and SDHRP.
wezb9820d42016-06-22 23:41:042621 return dns_client_ && dns_client_->GetConfig() &&
2622 (proc_params_.resolver_proc || !HostResolverProc::GetDefault());
[email protected]b3601bc22012-02-21 21:23:202623}
2624
[email protected]1ffdda82012-12-12 23:04:222625void HostResolverImpl::OnDnsTaskResolve(int net_error) {
[email protected]f0f602bd2012-11-15 18:01:022626 DCHECK(dns_client_);
[email protected]1ffdda82012-12-12 23:04:222627 if (net_error == OK) {
[email protected]f0f602bd2012-11-15 18:01:022628 num_dns_failures_ = 0;
2629 return;
2630 }
2631 ++num_dns_failures_;
2632 if (num_dns_failures_ < kMaximumDnsFailures)
2633 return;
[email protected]daae1322013-09-05 18:26:502634
2635 // Disable DnsClient until the next DNS change. Must be done before aborting
2636 // DnsTasks, since doing so may start new jobs.
[email protected]f0f602bd2012-11-15 18:01:022637 dns_client_->SetConfig(DnsConfig());
[email protected]daae1322013-09-05 18:26:502638
2639 // Switch jobs with active DnsTasks over to using ProcTasks.
2640 AbortDnsTasks();
2641
[email protected]f0f602bd2012-11-15 18:01:022642 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", false);
Ilya Sherman0eb39802017-12-08 20:58:182643 base::UmaHistogramSparse("AsyncDNS.DnsClientDisabledReason",
2644 std::abs(net_error));
[email protected]f0f602bd2012-11-15 18:01:022645}
2646
danakj22f90e72016-04-16 01:55:402647void HostResolverImpl::SetDnsClient(std::unique_ptr<DnsClient> dns_client) {
[email protected]daae1322013-09-05 18:26:502648 // DnsClient and config must be updated before aborting DnsTasks, since doing
2649 // so may start new jobs.
dchengc7eeda422015-12-26 03:56:482650 dns_client_ = std::move(dns_client);
[email protected]daae1322013-09-05 18:26:502651 if (dns_client_ && !dns_client_->GetConfig() &&
2652 num_dns_failures_ < kMaximumDnsFailures) {
2653 DnsConfig dns_config;
2654 NetworkChangeNotifier::GetDnsConfig(&dns_config);
Brad Lassey786929ad2018-02-21 20:54:272655 dns_config.dns_over_https_servers = dns_over_https_servers_;
[email protected]daae1322013-09-05 18:26:502656 dns_client_->SetConfig(dns_config);
2657 num_dns_failures_ = 0;
2658 if (dns_client_->GetConfig())
2659 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
[email protected]a8883e452012-11-17 05:58:062660 }
[email protected]daae1322013-09-05 18:26:502661
2662 AbortDnsTasks();
[email protected]a8883e452012-11-17 05:58:062663}
2664
maksim.sisov31452af2016-07-27 06:38:102665HostResolverImpl::RequestImpl::~RequestImpl() {
2666 if (job_)
2667 job_->CancelRequest(this);
2668}
2669
2670void HostResolverImpl::RequestImpl::ChangeRequestPriority(
2671 RequestPriority priority) {
2672 job_->ChangeRequestPriority(this, priority);
2673}
2674
[email protected]b59ff372009-07-15 22:04:322675} // namespace net