blob: 8d609552e4deeebe381bffba3c2e8bd55ddac8e9 [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"
Misha Efimovb99e7da2018-05-30 16:59:0245#include "base/time/default_tick_clock.h"
[email protected]66e96c42013-06-28 15:20:3146#include "base/time/time.h"
ssid6d6b40102016-04-05 18:59:5647#include "base/trace_event/trace_event.h"
[email protected]21526002010-05-16 19:42:4648#include "base/values.h"
Fabrice de Gans-Riberi7de47372018-05-08 20:23:4749#include "build/build_config.h"
[email protected]b3601bc22012-02-21 21:23:2050#include "net/base/address_family.h"
[email protected]b59ff372009-07-15 22:04:3251#include "net/base/address_list.h"
[email protected]ee094b82010-08-24 15:55:5152#include "net/base/host_port_pair.h"
martijna23c8962016-03-04 18:18:5153#include "net/base/ip_address.h"
[email protected]1c7cf3f82014-08-07 21:33:4854#include "net/base/ip_endpoint.h"
[email protected]2bb04442010-08-18 18:01:1555#include "net/base/net_errors.h"
xunjieli0b7f5b62016-12-06 20:43:4856#include "net/base/trace_constants.h"
tfarina9ed7f8c52016-02-19 17:50:1857#include "net/base/url_util.h"
[email protected]0adcb2b2012-08-15 21:30:4658#include "net/dns/address_sorter.h"
[email protected]78eac2a2012-03-14 19:09:2759#include "net/dns/dns_client.h"
[email protected]b3601bc22012-02-21 21:23:2060#include "net/dns/dns_config_service.h"
61#include "net/dns/dns_protocol.h"
tfarina47598f042015-10-07 23:08:3562#include "net/dns/dns_reloader.h"
[email protected]b3601bc22012-02-21 21:23:2063#include "net/dns/dns_response.h"
[email protected]b3601bc22012-02-21 21:23:2064#include "net/dns/dns_transaction.h"
tfarina77021d62015-10-11 20:19:0365#include "net/dns/dns_util.h"
[email protected]f2cb3cf2013-03-21 01:40:5366#include "net/dns/host_resolver_proc.h"
eroman87c53d62015-04-02 06:51:0767#include "net/log/net_log.h"
mikecironef22f9812016-10-04 03:40:1968#include "net/log/net_log_capture_mode.h"
mikecirone8b85c432016-09-08 19:11:0069#include "net/log/net_log_event_type.h"
mikecironef22f9812016-10-04 03:40:1970#include "net/log/net_log_parameters_callback.h"
71#include "net/log/net_log_source.h"
mikecirone8b85c432016-09-08 19:11:0072#include "net/log/net_log_source_type.h"
mikecironef22f9812016-10-04 03:40:1973#include "net/log/net_log_with_source.h"
[email protected]9db6f702013-04-10 18:10:5174#include "net/socket/client_socket_factory.h"
tfarina5dd13c22016-11-16 12:08:2675#include "net/socket/datagram_client_socket.h"
pauljensen370f1c72015-02-17 16:59:1476#include "url/url_canon_ip.h"
[email protected]b59ff372009-07-15 22:04:3277
78#if defined(OS_WIN)
79#include "net/base/winsock_init.h"
80#endif
81
tfarinada9e1362017-03-14 16:49:0682#if defined(OS_ANDROID)
83#include "net/android/network_library.h"
84#endif
85
[email protected]b59ff372009-07-15 22:04:3286namespace net {
87
[email protected]e95d3aca2010-01-11 22:47:4388namespace {
89
ttuttlecf1158bf2016-03-18 16:37:4490// Default delay between calls to the system resolver for the same hostname.
91// (Can be overridden by field trial.)
92const int64_t kDnsDefaultUnresponsiveDelayMs = 6000;
93
[email protected]6e78dfb2011-07-28 21:34:4794// Limit the size of hostnames that will be resolved to combat issues in
95// some platform's resolvers.
96const size_t kMaxHostLength = 4096;
97
[email protected]a2730882012-01-21 00:56:2798// Default TTL for successful resolutions with ProcTask.
99const unsigned kCacheEntryTTLSeconds = 60;
100
[email protected]b3601bc22012-02-21 21:23:20101// Default TTL for unsuccessful resolutions with ProcTask.
102const unsigned kNegativeCacheEntryTTLSeconds = 0;
103
[email protected]895123222012-10-25 15:21:17104// Minimum TTL for successful resolutions with DnsTask.
105const unsigned kMinimumTTLSeconds = kCacheEntryTTLSeconds;
106
sergeyub8cdc212015-05-14 18:50:37107// Time between IPv6 probes, i.e. for how long results of each IPv6 probe are
108// cached.
109const int kIPv6ProbePeriodMs = 1000;
110
111// Google DNS address used for IPv6 probes.
112const uint8_t kIPv6ProbeAddress[] =
113 { 0x20, 0x01, 0x48, 0x60, 0x48, 0x60, 0x00, 0x00,
114 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x88 };
115
[email protected]24f4bab2010-10-15 01:27:11116// We use a separate histogram name for each platform to facilitate the
117// display of error codes by their symbolic name (since each platform has
118// different mappings).
119const char kOSErrorsForGetAddrinfoHistogramName[] =
120#if defined(OS_WIN)
121 "Net.OSErrorsForGetAddrinfo_Win";
122#elif defined(OS_MACOSX)
123 "Net.OSErrorsForGetAddrinfo_Mac";
124#elif defined(OS_LINUX)
125 "Net.OSErrorsForGetAddrinfo_Linux";
Fabrice de Gans-Riberi7de47372018-05-08 20:23:47126#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]24f4bab2010-10-15 01:27:11127 "Net.OSErrorsForGetAddrinfo";
128#endif
129
[email protected]c89b2442011-05-26 14:28:27130// Gets a list of the likely error codes that getaddrinfo() can return
131// (non-exhaustive). These are the error codes that we will track via
132// a histogram.
133std::vector<int> GetAllGetAddrinfoOSErrors() {
134 int os_errors[] = {
Fabrice de Gans-Riberi7de47372018-05-08 20:23:47135#if defined(OS_WIN)
136 // See: http://msdn.microsoft.com/en-us/library/ms738520(VS.85).aspx
137 WSA_NOT_ENOUGH_MEMORY,
138 WSAEAFNOSUPPORT,
139 WSAEINVAL,
140 WSAESOCKTNOSUPPORT,
141 WSAHOST_NOT_FOUND,
142 WSANO_DATA,
143 WSANO_RECOVERY,
144 WSANOTINITIALISED,
145 WSATRY_AGAIN,
146 WSATYPE_NOT_FOUND,
147 // The following are not in doc, but might be to appearing in results :-(.
148 WSA_INVALID_HANDLE,
149#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
[email protected]23f771162011-06-02 18:37:51150#if !defined(OS_FREEBSD)
[email protected]39588992011-07-11 19:54:37151#if !defined(OS_ANDROID)
[email protected]c48aef92011-11-22 23:41:45152 // EAI_ADDRFAMILY has been declared obsolete in Android's and
153 // FreeBSD's netdb.h.
[email protected]c89b2442011-05-26 14:28:27154 EAI_ADDRFAMILY,
[email protected]39588992011-07-11 19:54:37155#endif
[email protected]c48aef92011-11-22 23:41:45156 // EAI_NODATA has been declared obsolete in FreeBSD's netdb.h.
[email protected]23f771162011-06-02 18:37:51157 EAI_NODATA,
158#endif
[email protected]c89b2442011-05-26 14:28:27159 EAI_AGAIN,
160 EAI_BADFLAGS,
161 EAI_FAIL,
162 EAI_FAMILY,
163 EAI_MEMORY,
[email protected]c89b2442011-05-26 14:28:27164 EAI_NONAME,
165 EAI_SERVICE,
166 EAI_SOCKTYPE,
167 EAI_SYSTEM,
[email protected]c89b2442011-05-26 14:28:27168#endif
169 };
170
171 // Ensure all errors are positive, as histogram only tracks positive values.
172 for (size_t i = 0; i < arraysize(os_errors); ++i) {
173 os_errors[i] = std::abs(os_errors[i]);
174 }
175
Ryan Sleevi9c79c3542018-05-12 01:38:09176 return base::CustomHistogram::ArrayToCustomEnumRanges(os_errors);
[email protected]c89b2442011-05-26 14:28:27177}
178
[email protected]1def74c2012-03-22 20:07:00179enum DnsResolveStatus {
180 RESOLVE_STATUS_DNS_SUCCESS = 0,
181 RESOLVE_STATUS_PROC_SUCCESS,
182 RESOLVE_STATUS_FAIL,
[email protected]1d932852012-06-19 19:40:33183 RESOLVE_STATUS_SUSPECT_NETBIOS,
[email protected]1def74c2012-03-22 20:07:00184 RESOLVE_STATUS_MAX
185};
186
eroman91dd3602015-03-26 03:46:33187// ICANN uses this localhost address to indicate a name collision.
188//
189// The policy in Chromium is to fail host resolving if it resolves to
190// this special address.
191//
192// Not however that IP literals are exempt from this policy, so it is still
193// possible to navigate to http://127.0.53.53/ directly.
194//
195// For more details: https://www.icann.org/news/announcement-2-2014-08-01-en
martijna23c8962016-03-04 18:18:51196const uint8_t kIcanNameCollisionIp[] = {127, 0, 53, 53};
eroman91dd3602015-03-26 03:46:33197
eroman1efc237c2016-12-14 00:00:45198bool ContainsIcannNameCollisionIp(const AddressList& addr_list) {
199 for (const auto& endpoint : addr_list) {
200 const IPAddress& addr = endpoint.address();
201 if (addr.IsIPv4() && IPAddressStartsWith(addr, kIcanNameCollisionIp)) {
202 return true;
203 }
204 }
205 return false;
206}
207
[email protected]1def74c2012-03-22 20:07:00208void UmaAsyncDnsResolveStatus(DnsResolveStatus result) {
209 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ResolveStatus",
210 result,
211 RESOLVE_STATUS_MAX);
212}
213
[email protected]1d932852012-06-19 19:40:33214bool ResemblesNetBIOSName(const std::string& hostname) {
215 return (hostname.size() < 16) && (hostname.find('.') == std::string::npos);
216}
217
218// True if |hostname| ends with either ".local" or ".local.".
219bool ResemblesMulticastDNSName(const std::string& hostname) {
220 DCHECK(!hostname.empty());
221 const char kSuffix[] = ".local.";
222 const size_t kSuffixLen = sizeof(kSuffix) - 1;
223 const size_t kSuffixLenTrimmed = kSuffixLen - 1;
thestiga74ad2b2016-07-11 20:52:36224 if (hostname.back() == '.') {
[email protected]1d932852012-06-19 19:40:33225 return hostname.size() > kSuffixLen &&
226 !hostname.compare(hostname.size() - kSuffixLen, kSuffixLen, kSuffix);
227 }
228 return hostname.size() > kSuffixLenTrimmed &&
229 !hostname.compare(hostname.size() - kSuffixLenTrimmed, kSuffixLenTrimmed,
230 kSuffix, kSuffixLenTrimmed);
231}
232
[email protected]51b9a6b2012-06-25 21:50:29233// A macro to simplify code and readability.
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21234#define DNS_HISTOGRAM_BY_PRIORITY(basename, priority, time) \
235 do { \
236 switch (priority) { \
237 case HIGHEST: \
Miriam Gershenson90d05e02017-09-28 19:29:28238 UMA_HISTOGRAM_LONG_TIMES_100(basename ".HIGHEST", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21239 break; \
240 case MEDIUM: \
Miriam Gershenson90d05e02017-09-28 19:29:28241 UMA_HISTOGRAM_LONG_TIMES_100(basename ".MEDIUM", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21242 break; \
243 case LOW: \
Miriam Gershenson90d05e02017-09-28 19:29:28244 UMA_HISTOGRAM_LONG_TIMES_100(basename ".LOW", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21245 break; \
246 case LOWEST: \
Miriam Gershenson90d05e02017-09-28 19:29:28247 UMA_HISTOGRAM_LONG_TIMES_100(basename ".LOWEST", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21248 break; \
249 case IDLE: \
Miriam Gershenson90d05e02017-09-28 19:29:28250 UMA_HISTOGRAM_LONG_TIMES_100(basename ".IDLE", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21251 break; \
252 case THROTTLED: \
Miriam Gershenson90d05e02017-09-28 19:29:28253 UMA_HISTOGRAM_LONG_TIMES_100(basename ".THROTTLED", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21254 break; \
255 } \
256 UMA_HISTOGRAM_LONG_TIMES_100(basename, time); \
[email protected]51b9a6b2012-06-25 21:50:29257 } while (0)
258
259// Record time from Request creation until a valid DNS response.
Miriam Gershenson90d05e02017-09-28 19:29:28260void RecordTotalTime(bool speculative,
261 bool from_cache,
[email protected]51b9a6b2012-06-25 21:50:29262 base::TimeDelta duration) {
Miriam Gershenson7ba03e12018-02-07 22:48:24263 if (!speculative) {
Miriam Gershenson90d05e02017-09-28 19:29:28264 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.TotalTime", duration);
Miriam Gershenson90d05e02017-09-28 19:29:28265
Miriam Gershenson7ba03e12018-02-07 22:48:24266 if (!from_cache)
Miriam Gershenson90d05e02017-09-28 19:29:28267 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.TotalTimeNotCached", duration);
[email protected]51b9a6b2012-06-25 21:50:29268 }
269}
270
[email protected]1339a2a22012-10-17 08:39:43271void RecordTTL(base::TimeDelta ttl) {
272 UMA_HISTOGRAM_CUSTOM_TIMES("AsyncDNS.TTL", ttl,
273 base::TimeDelta::FromSeconds(1),
274 base::TimeDelta::FromDays(1), 100);
275}
276
[email protected]16c2bd72013-06-28 01:19:22277bool ConfigureAsyncDnsNoFallbackFieldTrial() {
278 const bool kDefault = false;
279
280 // Configure the AsyncDns field trial as follows:
281 // groups AsyncDnsNoFallbackA and AsyncDnsNoFallbackB: return true,
282 // groups AsyncDnsA and AsyncDnsB: return false,
283 // groups SystemDnsA and SystemDnsB: return false,
284 // otherwise (trial absent): return default.
285 std::string group_name = base::FieldTrialList::FindFullName("AsyncDns");
brettw3a2c6902015-07-06 19:43:29286 if (!group_name.empty()) {
287 return base::StartsWith(group_name, "AsyncDnsNoFallback",
288 base::CompareCase::INSENSITIVE_ASCII);
289 }
[email protected]16c2bd72013-06-28 01:19:22290 return kDefault;
291}
292
Maks Orlovich5393c8682018-02-26 16:17:50293const base::FeatureParam<base::TaskPriority>::Option prio_modes[] = {
294 {base::TaskPriority::USER_VISIBLE, "default"},
295 {base::TaskPriority::USER_BLOCKING, "user_blocking"}};
296const base::Feature kSystemResolverPriorityExperiment = {
297 "SystemResolverPriorityExperiment", base::FEATURE_DISABLED_BY_DEFAULT};
298const base::FeatureParam<base::TaskPriority> priority_mode{
299 &kSystemResolverPriorityExperiment, "mode",
300 base::TaskPriority::USER_VISIBLE, &prio_modes};
301
[email protected]d7b9a2b2012-05-31 22:31:19302//-----------------------------------------------------------------------------
303
Avi Drissman13fc8932015-12-20 04:40:46304AddressList EnsurePortOnAddressList(const AddressList& list, uint16_t port) {
[email protected]895123222012-10-25 15:21:17305 if (list.empty() || list.front().port() == port)
306 return list;
307 return AddressList::CopyWithPort(list, port);
[email protected]7054e78f2012-05-07 21:44:56308}
309
[email protected]ec666ab22013-04-17 20:05:59310// Returns true if |addresses| contains only IPv4 loopback addresses.
311bool IsAllIPv4Loopback(const AddressList& addresses) {
312 for (unsigned i = 0; i < addresses.size(); ++i) {
martijna23c8962016-03-04 18:18:51313 const IPAddress& address = addresses[i].address();
[email protected]ec666ab22013-04-17 20:05:59314 switch (addresses[i].GetFamily()) {
315 case ADDRESS_FAMILY_IPV4:
martijna23c8962016-03-04 18:18:51316 if (address.bytes()[0] != 127)
[email protected]ec666ab22013-04-17 20:05:59317 return false;
318 break;
319 case ADDRESS_FAMILY_IPV6:
320 return false;
321 default:
322 NOTREACHED();
323 return false;
324 }
325 }
326 return true;
327}
328
tfarinada9e1362017-03-14 16:49:06329// Returns true if it can determine that only loopback addresses are configured.
330// i.e. if only 127.0.0.1 and ::1 are routable.
331// Also returns false if it cannot determine this.
332bool HaveOnlyLoopbackAddresses() {
Francois Doraya2d01ba2017-09-25 19:17:40333 base::ScopedBlockingCall scoped_blocking_call(base::BlockingType::WILL_BLOCK);
Fabrice de Gans-Riberi7de47372018-05-08 20:23:47334#if defined(OS_WIN)
335 // TODO(wtc): implement with the GetAdaptersAddresses function.
336 NOTIMPLEMENTED();
337 return false;
338#elif defined(OS_ANDROID)
tfarinada9e1362017-03-14 16:49:06339 return android::HaveOnlyLoopbackAddresses();
340#elif defined(OS_NACL)
341 NOTIMPLEMENTED();
342 return false;
Fabrice de Gans-Riberi7de47372018-05-08 20:23:47343#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
tfarinada9e1362017-03-14 16:49:06344 struct ifaddrs* interface_addr = NULL;
345 int rv = getifaddrs(&interface_addr);
346 if (rv != 0) {
347 DVLOG(1) << "getifaddrs() failed with errno = " << errno;
348 return false;
349 }
350
351 bool result = true;
352 for (struct ifaddrs* interface = interface_addr;
353 interface != NULL;
354 interface = interface->ifa_next) {
355 if (!(IFF_UP & interface->ifa_flags))
356 continue;
357 if (IFF_LOOPBACK & interface->ifa_flags)
358 continue;
359 const struct sockaddr* addr = interface->ifa_addr;
360 if (!addr)
361 continue;
362 if (addr->sa_family == AF_INET6) {
363 // Safe cast since this is AF_INET6.
364 const struct sockaddr_in6* addr_in6 =
365 reinterpret_cast<const struct sockaddr_in6*>(addr);
366 const struct in6_addr* sin6_addr = &addr_in6->sin6_addr;
367 if (IN6_IS_ADDR_LOOPBACK(sin6_addr) || IN6_IS_ADDR_LINKLOCAL(sin6_addr))
368 continue;
369 }
370 if (addr->sa_family != AF_INET6 && addr->sa_family != AF_INET)
371 continue;
372
373 result = false;
374 break;
375 }
376 freeifaddrs(interface_addr);
377 return result;
tfarinada9e1362017-03-14 16:49:06378#endif // defined(various platforms)
379}
380
[email protected]cd565142012-06-12 16:21:45381// Creates NetLog parameters when the resolve failed.
danakj22f90e72016-04-16 01:55:40382std::unique_ptr<base::Value> NetLogProcTaskFailedCallback(
Avi Drissman13fc8932015-12-20 04:40:46383 uint32_t attempt_number,
eroman001c3742015-04-23 03:11:17384 int net_error,
385 int os_error,
386 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40387 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]cd565142012-06-12 16:21:45388 if (attempt_number)
389 dict->SetInteger("attempt_number", attempt_number);
[email protected]21526002010-05-16 19:42:46390
[email protected]cd565142012-06-12 16:21:45391 dict->SetInteger("net_error", net_error);
[email protected]13024882011-05-18 23:19:16392
[email protected]cd565142012-06-12 16:21:45393 if (os_error) {
394 dict->SetInteger("os_error", os_error);
Fabrice de Gans-Riberi7de47372018-05-08 20:23:47395#if defined(OS_WIN)
[email protected]cd565142012-06-12 16:21:45396 // Map the error code to a human-readable string.
wezb9820d42016-06-22 23:41:04397 LPWSTR error_string = nullptr;
Peter Kastingbe940e92014-11-20 23:14:08398 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
399 0, // Use the internal message table.
400 os_error,
401 0, // Use default language.
402 (LPWSTR)&error_string,
403 0, // Buffer size.
404 0); // Arguments (unused).
[email protected]ad65a3e2013-12-25 18:18:01405 dict->SetString("os_error_string", base::WideToUTF8(error_string));
[email protected]cd565142012-06-12 16:21:45406 LocalFree(error_string);
Fabrice de Gans-Riberi7de47372018-05-08 20:23:47407#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
408 dict->SetString("os_error_string", gai_strerror(os_error));
[email protected]21526002010-05-16 19:42:46409#endif
[email protected]21526002010-05-16 19:42:46410 }
411
dchengc7eeda422015-12-26 03:56:48412 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45413}
[email protected]a9813302012-04-28 09:29:28414
[email protected]cd565142012-06-12 16:21:45415// Creates NetLog parameters when the DnsTask failed.
danakj22f90e72016-04-16 01:55:40416std::unique_ptr<base::Value> NetLogDnsTaskFailedCallback(
estade5e5529d2015-05-21 20:59:11417 int net_error,
418 int dns_error,
419 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40420 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]cd565142012-06-12 16:21:45421 dict->SetInteger("net_error", net_error);
422 if (dns_error)
423 dict->SetInteger("dns_error", dns_error);
dchengc7eeda422015-12-26 03:56:48424 return std::move(dict);
thestiga74ad2b2016-07-11 20:52:36425}
[email protected]ee094b82010-08-24 15:55:51426
[email protected]cd565142012-06-12 16:21:45427// Creates NetLog parameters containing the information in a RequestInfo object,
mikecironef22f9812016-10-04 03:40:19428// along with the associated NetLogSource.
danakj22f90e72016-04-16 01:55:40429std::unique_ptr<base::Value> NetLogRequestInfoCallback(
estade5e5529d2015-05-21 20:59:11430 const HostResolver::RequestInfo* info,
431 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40432 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]b3601bc22012-02-21 21:23:20433
[email protected]cd565142012-06-12 16:21:45434 dict->SetString("host", info->host_port_pair().ToString());
435 dict->SetInteger("address_family",
436 static_cast<int>(info->address_family()));
437 dict->SetBoolean("allow_cached_response", info->allow_cached_response());
438 dict->SetBoolean("is_speculative", info->is_speculative());
dchengc7eeda422015-12-26 03:56:48439 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45440}
[email protected]b3601bc22012-02-21 21:23:20441
[email protected]cd565142012-06-12 16:21:45442// Creates NetLog parameters for the creation of a HostResolverImpl::Job.
danakj22f90e72016-04-16 01:55:40443std::unique_ptr<base::Value> NetLogJobCreationCallback(
mikecironef22f9812016-10-04 03:40:19444 const NetLogSource& source,
estade5e5529d2015-05-21 20:59:11445 const std::string* host,
446 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40447 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
estade5e5529d2015-05-21 20:59:11448 source.AddToEventParameters(dict.get());
[email protected]cd565142012-06-12 16:21:45449 dict->SetString("host", *host);
dchengc7eeda422015-12-26 03:56:48450 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45451}
[email protected]a9813302012-04-28 09:29:28452
[email protected]cd565142012-06-12 16:21:45453// Creates NetLog parameters for HOST_RESOLVER_IMPL_JOB_ATTACH/DETACH events.
danakj22f90e72016-04-16 01:55:40454std::unique_ptr<base::Value> NetLogJobAttachCallback(
mikecironef22f9812016-10-04 03:40:19455 const NetLogSource& source,
estade5e5529d2015-05-21 20:59:11456 RequestPriority priority,
457 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40458 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
estade5e5529d2015-05-21 20:59:11459 source.AddToEventParameters(dict.get());
[email protected]3b04d1f22013-10-16 00:23:56460 dict->SetString("priority", RequestPriorityToString(priority));
dchengc7eeda422015-12-26 03:56:48461 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45462}
[email protected]b3601bc22012-02-21 21:23:20463
[email protected]cd565142012-06-12 16:21:45464// Creates NetLog parameters for the DNS_CONFIG_CHANGED event.
danakj22f90e72016-04-16 01:55:40465std::unique_ptr<base::Value> NetLogDnsConfigCallback(
estade5e5529d2015-05-21 20:59:11466 const DnsConfig* config,
467 NetLogCaptureMode /* capture_mode */) {
tfhef3618f2016-01-11 23:07:08468 return config->ToValue();
[email protected]cd565142012-06-12 16:21:45469}
[email protected]b4481b222012-03-16 17:13:11470
danakj22f90e72016-04-16 01:55:40471std::unique_ptr<base::Value> NetLogIPv6AvailableCallback(
estade5e5529d2015-05-21 20:59:11472 bool ipv6_available,
473 bool cached,
474 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40475 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
sergeyub8cdc212015-05-14 18:50:37476 dict->SetBoolean("ipv6_available", ipv6_available);
477 dict->SetBoolean("cached", cached);
dchengc7eeda422015-12-26 03:56:48478 return std::move(dict);
sergeyub8cdc212015-05-14 18:50:37479}
480
[email protected]0f292de02012-02-01 22:28:20481// The logging routines are defined here because some requests are resolved
482// without a Request object.
483
484// Logs when a request has just been started.
tfarina428341112016-09-22 13:38:20485void LogStartRequest(const NetLogWithSource& source_net_log,
[email protected]0f292de02012-02-01 22:28:20486 const HostResolver::RequestInfo& info) {
mikecirone8b85c432016-09-08 19:11:00487 source_net_log.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_REQUEST,
488 base::Bind(&NetLogRequestInfoCallback, &info));
[email protected]0f292de02012-02-01 22:28:20489}
490
491// Logs when a request has just completed (before its callback is run).
tfarina428341112016-09-22 13:38:20492void LogFinishRequest(const NetLogWithSource& source_net_log,
[email protected]0f292de02012-02-01 22:28:20493 const HostResolver::RequestInfo& info,
[email protected]b3601bc22012-02-21 21:23:20494 int net_error) {
xunjieli26f90452014-11-10 16:23:02495 source_net_log.EndEventWithNetErrorCode(
mikecirone8b85c432016-09-08 19:11:00496 NetLogEventType::HOST_RESOLVER_IMPL_REQUEST, net_error);
[email protected]0f292de02012-02-01 22:28:20497}
498
499// Logs when a request has been cancelled.
tfarina428341112016-09-22 13:38:20500void LogCancelRequest(const NetLogWithSource& source_net_log,
[email protected]0f292de02012-02-01 22:28:20501 const HostResolverImpl::RequestInfo& info) {
mikecirone8b85c432016-09-08 19:11:00502 source_net_log.AddEvent(NetLogEventType::CANCELLED);
503 source_net_log.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_REQUEST);
[email protected]0f292de02012-02-01 22:28:20504}
505
[email protected]b59ff372009-07-15 22:04:32506//-----------------------------------------------------------------------------
507
[email protected]0f292de02012-02-01 22:28:20508// Keeps track of the highest priority.
509class PriorityTracker {
510 public:
[email protected]8c98d002012-07-18 19:02:27511 explicit PriorityTracker(RequestPriority initial_priority)
512 : highest_priority_(initial_priority), total_count_(0) {
[email protected]0f292de02012-02-01 22:28:20513 memset(counts_, 0, sizeof(counts_));
514 }
515
516 RequestPriority highest_priority() const {
517 return highest_priority_;
518 }
519
520 size_t total_count() const {
521 return total_count_;
522 }
523
524 void Add(RequestPriority req_priority) {
525 ++total_count_;
526 ++counts_[req_priority];
[email protected]31ae7ab2012-04-24 21:09:05527 if (highest_priority_ < req_priority)
[email protected]0f292de02012-02-01 22:28:20528 highest_priority_ = req_priority;
529 }
530
531 void Remove(RequestPriority req_priority) {
532 DCHECK_GT(total_count_, 0u);
533 DCHECK_GT(counts_[req_priority], 0u);
534 --total_count_;
535 --counts_[req_priority];
536 size_t i;
thestiga74ad2b2016-07-11 20:52:36537 for (i = highest_priority_; i > MINIMUM_PRIORITY && !counts_[i]; --i) {
538 }
[email protected]0f292de02012-02-01 22:28:20539 highest_priority_ = static_cast<RequestPriority>(i);
540
[email protected]31ae7ab2012-04-24 21:09:05541 // In absence of requests, default to MINIMUM_PRIORITY.
542 if (total_count_ == 0)
543 DCHECK_EQ(MINIMUM_PRIORITY, highest_priority_);
[email protected]0f292de02012-02-01 22:28:20544 }
545
546 private:
547 RequestPriority highest_priority_;
548 size_t total_count_;
549 size_t counts_[NUM_PRIORITIES];
550};
551
juliatuttle9fb7aeb2016-06-06 20:16:33552void MakeNotStale(HostCache::EntryStaleness* stale_info) {
553 if (!stale_info)
554 return;
555 stale_info->expired_by = base::TimeDelta::FromSeconds(-1);
556 stale_info->network_changes = 0;
557 stale_info->stale_hits = 0;
558}
559
[email protected]c54a8912012-10-22 22:09:43560} // namespace
[email protected]0f292de02012-02-01 22:28:20561
562//-----------------------------------------------------------------------------
563
tfarina9ed7f8c52016-02-19 17:50:18564bool ResolveLocalHostname(base::StringPiece host,
565 uint16_t port,
566 AddressList* address_list) {
tfarina9ed7f8c52016-02-19 17:50:18567 address_list->clear();
568
569 bool is_local6;
570 if (!IsLocalHostname(host, &is_local6))
571 return false;
572
martijna23c8962016-03-04 18:18:51573 address_list->push_back(IPEndPoint(IPAddress::IPv6Localhost(), port));
tfarina9ed7f8c52016-02-19 17:50:18574 if (!is_local6) {
martijna23c8962016-03-04 18:18:51575 address_list->push_back(IPEndPoint(IPAddress::IPv4Localhost(), port));
tfarina9ed7f8c52016-02-19 17:50:18576 }
577
578 return true;
579}
580
[email protected]daae1322013-09-05 18:26:50581const unsigned HostResolverImpl::kMaximumDnsFailures = 16;
582
Eric Roman91aab1e62018-04-24 20:31:32583// Holds the callback and request parameters for an outstanding request.
584//
585// The RequestImpl is owned by the end user of host resolution. Deletion prior
586// to the request having completed means the request was cancelled by the
587// caller.
588//
589// Both the RequestImpl and its associated Job hold non-owning pointers to each
590// other. Care must be taken to clear the corresponding pointer when
591// cancellation is initiated by the Job (OnJobCancelled) vs by the end user
592// (~RequestImpl).
David Benjamina5677192018-04-23 23:25:42593class HostResolverImpl::RequestImpl
594 : public HostResolver::Request,
595 public base::LinkNode<HostResolverImpl::RequestImpl> {
[email protected]b59ff372009-07-15 22:04:32596 public:
tfarina428341112016-09-22 13:38:20597 RequestImpl(const NetLogWithSource& source_net_log,
maksim.sisov31452af2016-07-27 06:38:10598 const RequestInfo& info,
599 RequestPriority priority,
Bence Béky0f26a5812018-06-13 03:18:40600 CompletionOnceCallback callback,
maksim.sisov31452af2016-07-27 06:38:10601 AddressList* addresses,
Misha Efimovb99e7da2018-05-30 16:59:02602 Job* job,
603 base::TimeTicks request_time)
[email protected]ee094b82010-08-24 15:55:51604 : source_net_log_(source_net_log),
[email protected]54e13772009-08-14 03:01:09605 info_(info),
[email protected]5109c1952013-08-20 18:44:10606 priority_(priority),
maksim.sisov31452af2016-07-27 06:38:10607 job_(job),
Bence Béky0f26a5812018-06-13 03:18:40608 callback_(std::move(callback)),
[email protected]51b9a6b2012-06-25 21:50:29609 addresses_(addresses),
Misha Efimovb99e7da2018-05-30 16:59:02610 request_time_(request_time) {}
[email protected]b59ff372009-07-15 22:04:32611
maksim.sisov31452af2016-07-27 06:38:10612 ~RequestImpl() override;
613
614 void ChangeRequestPriority(RequestPriority priority) override;
615
616 void OnJobCancelled(Job* job) {
617 DCHECK_EQ(job_, job);
wezb9820d42016-06-22 23:41:04618 job_ = nullptr;
619 addresses_ = nullptr;
[email protected]aa22b242011-11-16 18:58:29620 callback_.Reset();
[email protected]b59ff372009-07-15 22:04:32621 }
622
[email protected]0f292de02012-02-01 22:28:20623 // Prepare final AddressList and call completion callback.
maksim.sisov31452af2016-07-27 06:38:10624 void OnJobCompleted(Job* job, int error, const AddressList& addr_list) {
625 DCHECK_EQ(job_, job);
[email protected]895123222012-10-25 15:21:17626 if (error == OK)
627 *addresses_ = EnsurePortOnAddressList(addr_list, info_.port());
maksim.sisov31452af2016-07-27 06:38:10628 job_ = nullptr;
629 addresses_ = nullptr;
Bence Béky0f26a5812018-06-13 03:18:40630 std::move(callback_).Run(error);
[email protected]b59ff372009-07-15 22:04:32631 }
632
[email protected]b59ff372009-07-15 22:04:32633 Job* job() const {
634 return job_;
635 }
636
[email protected]0f292de02012-02-01 22:28:20637 // NetLog for the source, passed in HostResolver::Resolve.
tfarina428341112016-09-22 13:38:20638 const NetLogWithSource& source_net_log() { return source_net_log_; }
[email protected]ee094b82010-08-24 15:55:51639
[email protected]b59ff372009-07-15 22:04:32640 const RequestInfo& info() const {
641 return info_;
642 }
643
[email protected]5109c1952013-08-20 18:44:10644 RequestPriority priority() const { return priority_; }
juliatuttlec53b19a72016-05-05 13:51:31645 void set_priority(RequestPriority priority) { priority_ = priority; }
[email protected]5109c1952013-08-20 18:44:10646
647 base::TimeTicks request_time() const { return request_time_; }
[email protected]51b9a6b2012-06-25 21:50:29648
[email protected]b59ff372009-07-15 22:04:32649 private:
tfarina428341112016-09-22 13:38:20650 const NetLogWithSource source_net_log_;
[email protected]54e13772009-08-14 03:01:09651
[email protected]b59ff372009-07-15 22:04:32652 // The request info that started the request.
[email protected]5109c1952013-08-20 18:44:10653 const RequestInfo info_;
654
juliatuttlec53b19a72016-05-05 13:51:31655 RequestPriority priority_;
[email protected]b59ff372009-07-15 22:04:32656
[email protected]0f292de02012-02-01 22:28:20657 // The resolve job that this request is dependent on.
[email protected]b59ff372009-07-15 22:04:32658 Job* job_;
659
660 // The user's callback to invoke when the request completes.
Bence Béky0f26a5812018-06-13 03:18:40661 CompletionOnceCallback callback_;
[email protected]b59ff372009-07-15 22:04:32662
663 // The address list to save result into.
664 AddressList* addresses_;
665
[email protected]51b9a6b2012-06-25 21:50:29666 const base::TimeTicks request_time_;
667
maksim.sisov31452af2016-07-27 06:38:10668 DISALLOW_COPY_AND_ASSIGN(RequestImpl);
[email protected]b59ff372009-07-15 22:04:32669};
670
[email protected]1e9bbd22010-10-15 16:42:45671//------------------------------------------------------------------------------
672
Francois Doraya2d01ba2017-09-25 19:17:40673// Calls HostResolverProc in TaskScheduler. Performs retries if necessary.
[email protected]0f292de02012-02-01 22:28:20674//
Miriam Gershenson02592182018-03-22 17:42:37675// In non-test code, the HostResolverProc is always SystemHostResolverProc,
676// which calls a platform API that implements host resolution.
677//
[email protected]0f292de02012-02-01 22:28:20678// Whenever we try to resolve the host, we post a delayed task to check if host
679// resolution (OnLookupComplete) is completed or not. If the original attempt
680// hasn't completed, then we start another attempt for host resolution. We take
681// the results from the first attempt that finishes and ignore the results from
682// all other attempts.
683//
684// TODO(szym): Move to separate source file for testing and mocking.
685//
Eric Orth9a037562018-07-03 21:24:38686class HostResolverImpl::ProcTask {
[email protected]b59ff372009-07-15 22:04:32687 public:
Eric Orth9a037562018-07-03 21:24:38688 typedef base::OnceCallback<void(int net_error, const AddressList& addr_list)>
689 Callback;
[email protected]b59ff372009-07-15 22:04:32690
[email protected]0f292de02012-02-01 22:28:20691 ProcTask(const Key& key,
692 const ProcTaskParams& params,
Eric Orth9a037562018-07-03 21:24:38693 Callback callback,
Miriam Gershensone42adb22017-10-16 16:19:38694 scoped_refptr<base::TaskRunner> proc_task_runner,
Misha Efimovb99e7da2018-05-30 16:59:02695 const NetLogWithSource& job_net_log,
696 const base::TickClock* tick_clock)
[email protected]0f292de02012-02-01 22:28:20697 : key_(key),
698 params_(params),
Eric Orth9a037562018-07-03 21:24:38699 callback_(std::move(callback)),
mmenke91c17162016-06-02 16:03:23700 network_task_runner_(base::ThreadTaskRunnerHandle::Get()),
Miriam Gershensone42adb22017-10-16 16:19:38701 proc_task_runner_(std::move(proc_task_runner)),
[email protected]0f292de02012-02-01 22:28:20702 attempt_number_(0),
Misha Efimovb99e7da2018-05-30 16:59:02703 net_log_(job_net_log),
Eric Orth9a037562018-07-03 21:24:38704 tick_clock_(tick_clock),
705 weak_ptr_factory_(this) {
706 DCHECK(callback_);
[email protected]90499482013-06-01 00:39:50707 if (!params_.resolver_proc.get())
[email protected]0f292de02012-02-01 22:28:20708 params_.resolver_proc = HostResolverProc::GetDefault();
709 // If default is unset, use the system proc.
[email protected]90499482013-06-01 00:39:50710 if (!params_.resolver_proc.get())
[email protected]1ee9afa12013-04-16 14:18:06711 params_.resolver_proc = new SystemHostResolverProc();
[email protected]b59ff372009-07-15 22:04:32712 }
713
Eric Orth9a037562018-07-03 21:24:38714 // Cancels this ProcTask. Any outstanding resolve attempts running on worker
715 // thread will continue running, but they will post back to the network thread
716 // before checking their WeakPtrs to find that this task is cancelled.
717 ~ProcTask() {
718 DCHECK(network_task_runner_->BelongsToCurrentThread());
719
720 // If this is cancellation, log the EndEvent (otherwise this was logged in
721 // OnLookupComplete()).
722 if (!was_completed())
723 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_PROC_TASK);
724 }
725
[email protected]b59ff372009-07-15 22:04:32726 void Start() {
mmenke91c17162016-06-02 16:03:23727 DCHECK(network_task_runner_->BelongsToCurrentThread());
Eric Orth9a037562018-07-03 21:24:38728 DCHECK(!was_completed());
mikecirone8b85c432016-09-08 19:11:00729 net_log_.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_PROC_TASK);
[email protected]189163e2011-05-11 01:48:54730 StartLookupAttempt();
731 }
[email protected]252b699b2010-02-05 21:38:06732
Eric Orth9a037562018-07-03 21:24:38733 bool was_completed() const {
mmenke91c17162016-06-02 16:03:23734 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20735 return callback_.is_null();
736 }
737
[email protected]0f292de02012-02-01 22:28:20738 private:
Eric Orth9a037562018-07-03 21:24:38739 using AttemptCompletionCallback = base::OnceCallback<
740 void(const AddressList& results, int error, const int os_error)>;
[email protected]a9813302012-04-28 09:29:28741
[email protected]189163e2011-05-11 01:48:54742 void StartLookupAttempt() {
mmenke91c17162016-06-02 16:03:23743 DCHECK(network_task_runner_->BelongsToCurrentThread());
Eric Orth9a037562018-07-03 21:24:38744 DCHECK(!was_completed());
Misha Efimovb99e7da2018-05-30 16:59:02745 base::TimeTicks start_time = tick_clock_->NowTicks();
[email protected]189163e2011-05-11 01:48:54746 ++attempt_number_;
747 // Dispatch the lookup attempt to a worker thread.
Eric Orth9a037562018-07-03 21:24:38748 AttemptCompletionCallback completion_callback = base::BindOnce(
749 &ProcTask::OnLookupAttemptComplete, weak_ptr_factory_.GetWeakPtr(),
750 start_time, attempt_number_, tick_clock_);
Miriam Gershensone42adb22017-10-16 16:19:38751 proc_task_runner_->PostTask(
Francois Doraya2d01ba2017-09-25 19:17:40752 FROM_HERE,
Eric Orth9a037562018-07-03 21:24:38753 base::BindOnce(&ProcTask::DoLookup, key_, params_.resolver_proc,
754 network_task_runner_, std::move(completion_callback)));
[email protected]13024882011-05-18 23:19:16755
mikecirone8b85c432016-09-08 19:11:00756 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_ATTEMPT_STARTED,
tfarina5e24b242015-10-27 13:11:28757 NetLog::IntCallback("attempt_number", attempt_number_));
[email protected]13024882011-05-18 23:19:16758
mmenke91c17162016-06-02 16:03:23759 // If the results aren't received within a given time, RetryIfNotComplete
760 // will start a new attempt if none of the outstanding attempts have
761 // completed yet.
Eric Orth9a037562018-07-03 21:24:38762 // Use a WeakPtr to avoid keeping the ProcTask alive after completion or
763 // cancellation.
[email protected]0f292de02012-02-01 22:28:20764 if (attempt_number_ <= params_.max_retry_attempts) {
mmenke91c17162016-06-02 16:03:23765 network_task_runner_->PostDelayedTask(
Eric Orth9a037562018-07-03 21:24:38766 FROM_HERE,
767 base::BindOnce(&ProcTask::StartLookupAttempt,
768 weak_ptr_factory_.GetWeakPtr()),
769 params_.unresponsive_delay *
770 std::pow(params_.retry_factor, attempt_number_ - 1));
[email protected]06ef6d92011-05-19 04:24:58771 }
[email protected]b59ff372009-07-15 22:04:32772 }
773
Francois Doraya2d01ba2017-09-25 19:17:40774 // WARNING: This code runs in TaskScheduler with CONTINUE_ON_SHUTDOWN. The
775 // shutdown code cannot wait for it to finish, so this code must be very
776 // careful about using other objects (like MessageLoops, Singletons, etc).
Eric Orth9a037562018-07-03 21:24:38777 // During shutdown these objects may no longer exist.
778 static void DoLookup(
779 Key key,
780 scoped_refptr<HostResolverProc> resolver_proc,
781 scoped_refptr<base::SingleThreadTaskRunner> network_task_runner,
782 AttemptCompletionCallback completion_callback) {
[email protected]189163e2011-05-11 01:48:54783 AddressList results;
784 int os_error = 0;
Eric Orth9a037562018-07-03 21:24:38785 int error =
786 resolver_proc->Resolve(key.hostname, key.address_family,
787 key.host_resolver_flags, &results, &os_error);
[email protected]b59ff372009-07-15 22:04:32788
Eric Orth9a037562018-07-03 21:24:38789 network_task_runner->PostTask(
790 FROM_HERE, base::BindOnce(std::move(completion_callback), results,
791 error, os_error));
[email protected]189163e2011-05-11 01:48:54792 }
793
Eric Orth9a037562018-07-03 21:24:38794 // Callback for when DoLookup() completes (runs on task runner thread). Now
795 // that we're back in the network thread, checks that |proc_task| is still
796 // valid, and if so, passes back to the object.
797 static void OnLookupAttemptComplete(base::WeakPtr<ProcTask> proc_task,
798 const base::TimeTicks& start_time,
799 const uint32_t attempt_number,
800 const base::TickClock* tick_clock,
801 const AddressList& results,
802 int error,
803 const int os_error) {
Luciano Pachecob4426082018-07-02 08:04:18804 TRACE_EVENT0(kNetTracingCategory, "ProcTask::OnLookupComplete");
Eric Orth9a037562018-07-03 21:24:38805
[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
[email protected]2d3b7762010-10-09 00:35:47811 // Ideally the following code would be part of host_resolver_proc.cc,
[email protected]b3601bc22012-02-21 21:23:20812 // however it isn't safe to call NetworkChangeNotifier from worker threads.
mmenke91c17162016-06-02 16:03:23813 // So do it here on the IO thread instead.
[email protected]189163e2011-05-11 01:48:54814 if (error != OK && NetworkChangeNotifier::IsOffline())
815 error = ERR_INTERNET_DISCONNECTED;
[email protected]2d3b7762010-10-09 00:35:47816
Eric Orth9a037562018-07-03 21:24:38817 RecordAttemptHistograms(start_time, attempt_number, error, os_error,
818 tick_clock);
Luciano Pachecob4426082018-07-02 08:04:18819
Eric Orth9a037562018-07-03 21:24:38820 if (!proc_task) {
821 RecordDiscardedAttemptHistograms(attempt_number);
Luciano Pachecob4426082018-07-02 08:04:18822 return;
Eric Orth9a037562018-07-03 21:24:38823 }
824
825 proc_task->OnLookupComplete(results, start_time, attempt_number, error,
826 os_error);
827 }
828
829 void OnLookupComplete(const AddressList& results,
830 const base::TimeTicks& start_time,
831 const uint32_t attempt_number,
832 int error,
833 const int os_error) {
834 DCHECK(network_task_runner_->BelongsToCurrentThread());
835 DCHECK(!was_completed());
836
837 // Invalidate WeakPtrs to cancel handling of all outstanding lookup attempts
838 // and retries.
839 weak_ptr_factory_.InvalidateWeakPtrs();
840
841 RecordTaskHistograms(start_time, error, os_error, attempt_number);
Luciano Pachecob4426082018-07-02 08:04:18842
Eric Orthcb8862f2018-06-27 18:08:35843 NetLogParametersCallback net_log_callback;
Eric Orth9a037562018-07-03 21:24:38844 NetLogParametersCallback attempt_net_log_callback;
[email protected]0f292de02012-02-01 22:28:20845 if (error != OK) {
[email protected]cd565142012-06-12 16:21:45846 net_log_callback = base::Bind(&NetLogProcTaskFailedCallback,
[email protected]cd565142012-06-12 16:21:45847 0, error, os_error);
Eric Orth9a037562018-07-03 21:24:38848 attempt_net_log_callback = base::Bind(&NetLogProcTaskFailedCallback,
849 attempt_number, error, os_error);
[email protected]ee094b82010-08-24 15:55:51850 } else {
Eric Orth9a037562018-07-03 21:24:38851 net_log_callback = results.CreateNetLogCallback();
852 attempt_net_log_callback =
853 NetLog::IntCallback("attempt_number", attempt_number);
[email protected]ee094b82010-08-24 15:55:51854 }
mikecirone8b85c432016-09-08 19:11:00855 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_PROC_TASK,
[email protected]cd565142012-06-12 16:21:45856 net_log_callback);
Eric Orth9a037562018-07-03 21:24:38857 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_ATTEMPT_FINISHED,
858 attempt_net_log_callback);
[email protected]ee094b82010-08-24 15:55:51859
Eric Orth9a037562018-07-03 21:24:38860 std::move(callback_).Run(error, results);
[email protected]b59ff372009-07-15 22:04:32861 }
862
Miriam Gershenson61604662017-09-28 23:51:11863 void RecordTaskHistograms(const base::TimeTicks& start_time,
864 const int error,
Eric Orth9a037562018-07-03 21:24:38865 const int os_error,
866 const uint32_t attempt_number) const {
mmenke91c17162016-06-02 16:03:23867 DCHECK(network_task_runner_->BelongsToCurrentThread());
Misha Efimovb99e7da2018-05-30 16:59:02868 base::TimeDelta duration = tick_clock_->NowTicks() - start_time;
Eric Orth9a037562018-07-03 21:24:38869 if (error == OK) {
Miriam Gershenson61604662017-09-28 23:51:11870 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ProcTask.SuccessTime", duration);
Eric Orth9a037562018-07-03 21:24:38871 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptFirstSuccess", attempt_number, 100);
872 } else {
Miriam Gershenson61604662017-09-28 23:51:11873 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ProcTask.FailureTime", duration);
Eric Orth9a037562018-07-03 21:24:38874 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptFirstFailure", attempt_number, 100);
875 }
[email protected]7e96d792011-06-10 17:08:23876
Miriam Gershenson61604662017-09-28 23:51:11877 UMA_HISTOGRAM_CUSTOM_ENUMERATION(kOSErrorsForGetAddrinfoHistogramName,
878 std::abs(os_error),
879 GetAllGetAddrinfoOSErrors());
[email protected]1e9bbd22010-10-15 16:42:45880 }
881
Eric Orth9a037562018-07-03 21:24:38882 static void RecordAttemptHistograms(const base::TimeTicks& start_time,
883 const uint32_t attempt_number,
884 const int error,
885 const int os_error,
886 const base::TickClock* tick_clock) {
887 base::TimeDelta duration = tick_clock->NowTicks() - start_time;
888 if (error == OK) {
Luciano Pachecob4426082018-07-02 08:04:18889 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptSuccess", attempt_number, 100);
Luciano Pachecob4426082018-07-02 08:04:18890 UMA_HISTOGRAM_LONG_TIMES_100("DNS.AttemptSuccessDuration", duration);
Eric Orth9a037562018-07-03 21:24:38891 } else {
892 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptFailure", attempt_number, 100);
Luciano Pachecob4426082018-07-02 08:04:18893 UMA_HISTOGRAM_LONG_TIMES_100("DNS.AttemptFailDuration", duration);
Eric Orth9a037562018-07-03 21:24:38894 }
[email protected]189163e2011-05-11 01:48:54895 }
[email protected]1e9bbd22010-10-15 16:42:45896
Eric Orth9a037562018-07-03 21:24:38897 static void RecordDiscardedAttemptHistograms(const uint32_t attempt_number) {
898 // Count those attempts which completed after the job was already canceled
899 // OR after the job was already completed by an earlier attempt (so
900 // cancelled in effect).
901 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptDiscarded", attempt_number, 100);
902 }
903
[email protected]123ab1e32009-10-21 19:12:57904 Key key_;
[email protected]b59ff372009-07-15 22:04:32905
[email protected]0f292de02012-02-01 22:28:20906 // Holds an owning reference to the HostResolverProc that we are going to use.
[email protected]b59ff372009-07-15 22:04:32907 // This may not be the current resolver procedure by the time we call
908 // ResolveAddrInfo, but that's OK... we'll use it anyways, and the owning
909 // reference ensures that it remains valid until we are done.
[email protected]0f292de02012-02-01 22:28:20910 ProcTaskParams params_;
[email protected]b59ff372009-07-15 22:04:32911
[email protected]0f292de02012-02-01 22:28:20912 // The listener to the results of this ProcTask.
913 Callback callback_;
914
mmenke91c17162016-06-02 16:03:23915 // Used to post events onto the network thread.
916 scoped_refptr<base::SingleThreadTaskRunner> network_task_runner_;
Miriam Gershensone42adb22017-10-16 16:19:38917 // Used to post blocking HostResolverProc tasks.
918 scoped_refptr<base::TaskRunner> proc_task_runner_;
[email protected]189163e2011-05-11 01:48:54919
920 // Keeps track of the number of attempts we have made so far to resolve the
921 // host. Whenever we start an attempt to resolve the host, we increase this
922 // number.
Avi Drissman13fc8932015-12-20 04:40:46923 uint32_t attempt_number_;
[email protected]189163e2011-05-11 01:48:54924
tfarina428341112016-09-22 13:38:20925 NetLogWithSource net_log_;
[email protected]ee094b82010-08-24 15:55:51926
Misha Efimovb99e7da2018-05-30 16:59:02927 const base::TickClock* tick_clock_;
928
Eric Orth9a037562018-07-03 21:24:38929 // Used to loop back from the blocking lookup attempt tasks as well as from
930 // delayed retry tasks. Invalidate WeakPtrs on completion and cancellation to
931 // cancel handling of such posted tasks.
932 base::WeakPtrFactory<ProcTask> weak_ptr_factory_;
933
[email protected]0f292de02012-02-01 22:28:20934 DISALLOW_COPY_AND_ASSIGN(ProcTask);
[email protected]b59ff372009-07-15 22:04:32935};
936
937//-----------------------------------------------------------------------------
938
Miriam Gershenson02592182018-03-22 17:42:37939// Resolves the hostname using DnsTransaction, which is a full implementation of
940// a DNS stub resolver. One DnsTransaction is created for each resolution
941// needed, which for AF_UNSPEC resolutions includes both A and AAAA. The
942// transactions are scheduled separately and started separately.
943//
[email protected]b3601bc22012-02-21 21:23:20944// TODO(szym): This could be moved to separate source file as well.
[email protected]0adcb2b2012-08-15 21:30:46945class HostResolverImpl::DnsTask : public base::SupportsWeakPtr<DnsTask> {
[email protected]b3601bc22012-02-21 21:23:20946 public:
[email protected]daae1322013-09-05 18:26:50947 class Delegate {
948 public:
949 virtual void OnDnsTaskComplete(base::TimeTicks start_time,
950 int net_error,
951 const AddressList& addr_list,
952 base::TimeDelta ttl) = 0;
953
954 // Called when the first of two jobs succeeds. If the first completed
955 // transaction fails, this is not called. Also not called when the DnsTask
956 // only needs to run one transaction.
957 virtual void OnFirstDnsTransactionComplete() = 0;
958
Brad Lassey786929ad2018-02-21 20:54:27959 virtual URLRequestContext* url_request_context() = 0;
960 virtual RequestPriority priority() const = 0;
961
[email protected]daae1322013-09-05 18:26:50962 protected:
Chris Watkins68b15032017-12-01 03:07:13963 Delegate() = default;
964 virtual ~Delegate() = default;
[email protected]daae1322013-09-05 18:26:50965 };
[email protected]b3601bc22012-02-21 21:23:20966
[email protected]0adcb2b2012-08-15 21:30:46967 DnsTask(DnsClient* client,
[email protected]b3601bc22012-02-21 21:23:20968 const Key& key,
[email protected]daae1322013-09-05 18:26:50969 Delegate* delegate,
Misha Efimovb99e7da2018-05-30 16:59:02970 const NetLogWithSource& job_net_log,
971 const base::TickClock* tick_clock)
[email protected]0adcb2b2012-08-15 21:30:46972 : client_(client),
[email protected]daae1322013-09-05 18:26:50973 key_(key),
974 delegate_(delegate),
975 net_log_(job_net_log),
976 num_completed_transactions_(0),
Misha Efimovb99e7da2018-05-30 16:59:02977 tick_clock_(tick_clock),
978 task_start_time_(tick_clock_->NowTicks()) {
[email protected]0adcb2b2012-08-15 21:30:46979 DCHECK(client);
[email protected]daae1322013-09-05 18:26:50980 DCHECK(delegate_);
[email protected]1affed62013-08-21 03:24:50981 }
982
[email protected]daae1322013-09-05 18:26:50983 bool needs_two_transactions() const {
984 return key_.address_family == ADDRESS_FAMILY_UNSPECIFIED;
985 }
986
987 bool needs_another_transaction() const {
988 return needs_two_transactions() && !transaction_aaaa_;
989 }
990
991 void StartFirstTransaction() {
992 DCHECK_EQ(0u, num_completed_transactions_);
mikecirone8b85c432016-09-08 19:11:00993 net_log_.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_DNS_TASK);
[email protected]daae1322013-09-05 18:26:50994 if (key_.address_family == ADDRESS_FAMILY_IPV6) {
995 StartAAAA();
996 } else {
997 StartA();
998 }
999 }
1000
1001 void StartSecondTransaction() {
1002 DCHECK(needs_two_transactions());
1003 StartAAAA();
[email protected]70c04ab2013-08-22 16:05:121004 }
1005
Brad Lassey2e8f185d2018-05-21 22:25:211006 base::TimeDelta ttl() { return ttl_; }
1007
[email protected]70c04ab2013-08-22 16:05:121008 private:
[email protected]daae1322013-09-05 18:26:501009 void StartA() {
1010 DCHECK(!transaction_a_);
1011 DCHECK_NE(ADDRESS_FAMILY_IPV6, key_.address_family);
1012 transaction_a_ = CreateTransaction(ADDRESS_FAMILY_IPV4);
1013 transaction_a_->Start();
1014 }
1015
1016 void StartAAAA() {
1017 DCHECK(!transaction_aaaa_);
1018 DCHECK_NE(ADDRESS_FAMILY_IPV4, key_.address_family);
1019 transaction_aaaa_ = CreateTransaction(ADDRESS_FAMILY_IPV6);
1020 transaction_aaaa_->Start();
1021 }
1022
danakj22f90e72016-04-16 01:55:401023 std::unique_ptr<DnsTransaction> CreateTransaction(AddressFamily family) {
[email protected]daae1322013-09-05 18:26:501024 DCHECK_NE(ADDRESS_FAMILY_UNSPECIFIED, family);
Brad Lassey786929ad2018-02-21 20:54:271025 std::unique_ptr<DnsTransaction> trans =
1026 client_->GetTransactionFactory()->CreateTransaction(
1027 key_.hostname,
1028 family == ADDRESS_FAMILY_IPV6 ? dns_protocol::kTypeAAAA
1029 : dns_protocol::kTypeA,
Brad Lasseydba0a84b2018-02-23 22:18:531030 base::BindOnce(&DnsTask::OnTransactionComplete,
Misha Efimovb99e7da2018-05-30 16:59:021031 base::Unretained(this), tick_clock_->NowTicks()),
Brad Lassey786929ad2018-02-21 20:54:271032 net_log_);
1033 trans->SetRequestContext(delegate_->url_request_context());
1034 trans->SetRequestPriority(delegate_->priority());
1035 return trans;
[email protected]daae1322013-09-05 18:26:501036 }
1037
1038 void OnTransactionComplete(const base::TimeTicks& start_time,
[email protected]1def74c2012-03-22 20:07:001039 DnsTransaction* transaction,
[email protected]b3601bc22012-02-21 21:23:201040 int net_error,
1041 const DnsResponse* response) {
[email protected]add76532012-03-30 14:47:471042 DCHECK(transaction);
Misha Efimovb99e7da2018-05-30 16:59:021043 base::TimeDelta duration = tick_clock_->NowTicks() - start_time;
Brad Lassey2e8f185d2018-05-21 22:25:211044 if (net_error != OK && !(net_error == ERR_NAME_NOT_RESOLVED && response &&
1045 response->IsValid())) {
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211046 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.TransactionFailure", duration);
[email protected]0adcb2b2012-08-15 21:30:461047 OnFailure(net_error, DnsResponse::DNS_PARSE_OK);
1048 return;
[email protected]6c411902012-08-14 22:36:361049 }
[email protected]0adcb2b2012-08-15 21:30:461050
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211051 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.TransactionSuccess", duration);
[email protected]02cd6982013-01-10 20:12:511052 switch (transaction->GetType()) {
1053 case dns_protocol::kTypeA:
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211054 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.TransactionSuccess_A", duration);
[email protected]02cd6982013-01-10 20:12:511055 break;
1056 case dns_protocol::kTypeAAAA:
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211057 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.TransactionSuccess_AAAA",
1058 duration);
[email protected]02cd6982013-01-10 20:12:511059 break;
1060 }
[email protected]daae1322013-09-05 18:26:501061
[email protected]0adcb2b2012-08-15 21:30:461062 AddressList addr_list;
1063 base::TimeDelta ttl;
1064 DnsResponse::Result result = response->ParseToAddressList(&addr_list, &ttl);
1065 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ParseToAddressList",
1066 result,
1067 DnsResponse::DNS_PARSE_RESULT_MAX);
1068 if (result != DnsResponse::DNS_PARSE_OK) {
1069 // Fail even if the other query succeeds.
1070 OnFailure(ERR_DNS_MALFORMED_RESPONSE, result);
1071 return;
1072 }
1073
[email protected]daae1322013-09-05 18:26:501074 ++num_completed_transactions_;
1075 if (num_completed_transactions_ == 1) {
1076 ttl_ = ttl;
[email protected]0adcb2b2012-08-15 21:30:461077 } else {
[email protected]daae1322013-09-05 18:26:501078 ttl_ = std::min(ttl_, ttl);
[email protected]0adcb2b2012-08-15 21:30:461079 }
1080
[email protected]daae1322013-09-05 18:26:501081 if (transaction->GetType() == dns_protocol::kTypeA) {
1082 DCHECK_EQ(transaction_a_.get(), transaction);
1083 // Place IPv4 addresses after IPv6.
1084 addr_list_.insert(addr_list_.end(), addr_list.begin(), addr_list.end());
1085 } else {
1086 DCHECK_EQ(transaction_aaaa_.get(), transaction);
1087 // Place IPv6 addresses before IPv4.
1088 addr_list_.insert(addr_list_.begin(), addr_list.begin(), addr_list.end());
1089 }
1090
1091 if (needs_two_transactions() && num_completed_transactions_ == 1) {
1092 // No need to repeat the suffix search.
1093 key_.hostname = transaction->GetHostname();
1094 delegate_->OnFirstDnsTransactionComplete();
1095 return;
1096 }
1097
1098 if (addr_list_.empty()) {
[email protected]70c04ab2013-08-22 16:05:121099 // TODO(szym): Don't fallback to ProcTask in this case.
1100 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
[email protected]0adcb2b2012-08-15 21:30:461101 return;
1102 }
1103
[email protected]daae1322013-09-05 18:26:501104 // If there are multiple addresses, and at least one is IPv6, need to sort
1105 // them. Note that IPv6 addresses are always put before IPv4 ones, so it's
1106 // sufficient to just check the family of the first address.
1107 if (addr_list_.size() > 1 &&
1108 addr_list_[0].GetFamily() == ADDRESS_FAMILY_IPV6) {
1109 // Sort addresses if needed. Sort could complete synchronously.
[email protected]0adcb2b2012-08-15 21:30:461110 client_->GetAddressSorter()->Sort(
Misha Efimovb99e7da2018-05-30 16:59:021111 addr_list_, base::Bind(&DnsTask::OnSortComplete, AsWeakPtr(),
1112 tick_clock_->NowTicks()));
[email protected]0adcb2b2012-08-15 21:30:461113 } else {
[email protected]daae1322013-09-05 18:26:501114 OnSuccess(addr_list_);
[email protected]0adcb2b2012-08-15 21:30:461115 }
1116 }
1117
1118 void OnSortComplete(base::TimeTicks start_time,
[email protected]0adcb2b2012-08-15 21:30:461119 bool success,
1120 const AddressList& addr_list) {
1121 if (!success) {
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211122 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.SortFailure",
Misha Efimovb99e7da2018-05-30 16:59:021123 tick_clock_->NowTicks() - start_time);
[email protected]0adcb2b2012-08-15 21:30:461124 OnFailure(ERR_DNS_SORT_ERROR, DnsResponse::DNS_PARSE_OK);
1125 return;
1126 }
1127
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211128 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.SortSuccess",
Misha Efimovb99e7da2018-05-30 16:59:021129 tick_clock_->NowTicks() - start_time);
[email protected]0adcb2b2012-08-15 21:30:461130
1131 // AddressSorter prunes unusable destinations.
1132 if (addr_list.empty()) {
1133 LOG(WARNING) << "Address list empty after RFC3484 sort";
1134 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
1135 return;
1136 }
1137
[email protected]daae1322013-09-05 18:26:501138 OnSuccess(addr_list);
[email protected]0adcb2b2012-08-15 21:30:461139 }
1140
1141 void OnFailure(int net_error, DnsResponse::Result result) {
1142 DCHECK_NE(OK, net_error);
[email protected]cd565142012-06-12 16:21:451143 net_log_.EndEvent(
mikecirone8b85c432016-09-08 19:11:001144 NetLogEventType::HOST_RESOLVER_IMPL_DNS_TASK,
[email protected]cd565142012-06-12 16:21:451145 base::Bind(&NetLogDnsTaskFailedCallback, net_error, result));
Brad Lassey2e8f185d2018-05-21 22:25:211146 base::TimeDelta ttl = ttl_ < base::TimeDelta::FromSeconds(
1147 std::numeric_limits<uint32_t>::max()) &&
1148 num_completed_transactions_ > 0
1149 ? ttl_
1150 : base::TimeDelta::FromSeconds(0);
Miriam Gershenson66024d72017-12-05 04:30:321151 delegate_->OnDnsTaskComplete(task_start_time_, net_error, AddressList(),
Brad Lassey2e8f185d2018-05-21 22:25:211152 ttl);
[email protected]b3601bc22012-02-21 21:23:201153 }
1154
[email protected]daae1322013-09-05 18:26:501155 void OnSuccess(const AddressList& addr_list) {
mikecirone8b85c432016-09-08 19:11:001156 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_DNS_TASK,
[email protected]0adcb2b2012-08-15 21:30:461157 addr_list.CreateNetLogCallback());
[email protected]daae1322013-09-05 18:26:501158 delegate_->OnDnsTaskComplete(task_start_time_, OK, addr_list, ttl_);
[email protected]0adcb2b2012-08-15 21:30:461159 }
1160
1161 DnsClient* client_;
[email protected]daae1322013-09-05 18:26:501162 Key key_;
1163
[email protected]b3601bc22012-02-21 21:23:201164 // The listener to the results of this DnsTask.
[email protected]daae1322013-09-05 18:26:501165 Delegate* delegate_;
tfarina428341112016-09-22 13:38:201166 const NetLogWithSource net_log_;
[email protected]b3601bc22012-02-21 21:23:201167
danakj22f90e72016-04-16 01:55:401168 std::unique_ptr<DnsTransaction> transaction_a_;
1169 std::unique_ptr<DnsTransaction> transaction_aaaa_;
[email protected]0adcb2b2012-08-15 21:30:461170
[email protected]daae1322013-09-05 18:26:501171 unsigned num_completed_transactions_;
1172
1173 // These are updated as each transaction completes.
1174 base::TimeDelta ttl_;
1175 // IPv6 addresses must appear first in the list.
1176 AddressList addr_list_;
1177
Misha Efimovb99e7da2018-05-30 16:59:021178 const base::TickClock* tick_clock_;
[email protected]daae1322013-09-05 18:26:501179 base::TimeTicks task_start_time_;
[email protected]0adcb2b2012-08-15 21:30:461180
1181 DISALLOW_COPY_AND_ASSIGN(DnsTask);
[email protected]b3601bc22012-02-21 21:23:201182};
1183
1184//-----------------------------------------------------------------------------
1185
[email protected]0f292de02012-02-01 22:28:201186// Aggregates all Requests for the same Key. Dispatched via PriorityDispatch.
[email protected]daae1322013-09-05 18:26:501187class HostResolverImpl::Job : public PrioritizedDispatcher::Job,
1188 public HostResolverImpl::DnsTask::Delegate {
[email protected]68ad3ee2010-01-30 03:45:391189 public:
[email protected]0f292de02012-02-01 22:28:201190 // Creates new job for |key| where |request_net_log| is bound to the
[email protected]16ee26d2012-03-08 03:34:351191 // request that spawned it.
[email protected]12faa4c2012-11-06 04:44:181192 Job(const base::WeakPtr<HostResolverImpl>& resolver,
[email protected]0f292de02012-02-01 22:28:201193 const Key& key,
[email protected]8c98d002012-07-18 19:02:271194 RequestPriority priority,
Miriam Gershensone42adb22017-10-16 16:19:381195 scoped_refptr<base::TaskRunner> proc_task_runner,
Misha Efimovb99e7da2018-05-30 16:59:021196 const NetLogWithSource& source_net_log,
1197 const base::TickClock* tick_clock)
[email protected]12faa4c2012-11-06 04:44:181198 : resolver_(resolver),
[email protected]0f292de02012-02-01 22:28:201199 key_(key),
[email protected]8c98d002012-07-18 19:02:271200 priority_tracker_(priority),
Miriam Gershensone42adb22017-10-16 16:19:381201 proc_task_runner_(std::move(proc_task_runner)),
[email protected]0f292de02012-02-01 22:28:201202 had_non_speculative_request_(false),
[email protected]51b9a6b2012-06-25 21:50:291203 had_dns_config_(false),
[email protected]daae1322013-09-05 18:26:501204 num_occupied_job_slots_(0),
[email protected]1d932852012-06-19 19:40:331205 dns_task_error_(OK),
Misha Efimovb99e7da2018-05-30 16:59:021206 tick_clock_(tick_clock),
1207 creation_time_(tick_clock_->NowTicks()),
[email protected]51b9a6b2012-06-25 21:50:291208 priority_change_time_(creation_time_),
tfarina428341112016-09-22 13:38:201209 net_log_(
1210 NetLogWithSource::Make(source_net_log.net_log(),
mikecirone8b85c432016-09-08 19:11:001211 NetLogSourceType::HOST_RESOLVER_IMPL_JOB)) {
1212 source_net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_CREATE_JOB);
[email protected]0f292de02012-02-01 22:28:201213
mikecirone8b85c432016-09-08 19:11:001214 net_log_.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
1215 base::Bind(&NetLogJobCreationCallback,
1216 source_net_log.source(), &key_.hostname));
[email protected]68ad3ee2010-01-30 03:45:391217 }
1218
dchengb03027d2014-10-21 12:00:201219 ~Job() override {
[email protected]b3601bc22012-02-21 21:23:201220 if (is_running()) {
1221 // |resolver_| was destroyed with this Job still in flight.
1222 // Clean-up, record in the log, but don't run any callbacks.
Eric Orth9a037562018-07-03 21:24:381223 proc_task_ = nullptr;
[email protected]16ee26d2012-03-08 03:34:351224 // Clean up now for nice NetLog.
[email protected]daae1322013-09-05 18:26:501225 KillDnsTask();
mikecirone8b85c432016-09-08 19:11:001226 net_log_.EndEventWithNetErrorCode(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
[email protected]b3601bc22012-02-21 21:23:201227 ERR_ABORTED);
1228 } else if (is_queued()) {
[email protected]57a48d32012-03-03 00:04:551229 // |resolver_| was destroyed without running this Job.
[email protected]16ee26d2012-03-08 03:34:351230 // TODO(szym): is there any benefit in having this distinction?
mikecirone8b85c432016-09-08 19:11:001231 net_log_.AddEvent(NetLogEventType::CANCELLED);
1232 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB);
[email protected]68ad3ee2010-01-30 03:45:391233 }
[email protected]b3601bc22012-02-21 21:23:201234 // else CompleteRequests logged EndEvent.
David Benjamina5677192018-04-23 23:25:421235 while (!requests_.empty()) {
maksim.sisov31452af2016-07-27 06:38:101236 // Log any remaining Requests as cancelled.
David Benjamina5677192018-04-23 23:25:421237 RequestImpl* req = requests_.head()->value();
1238 req->RemoveFromList();
1239 DCHECK_EQ(this, req->job());
1240 LogCancelRequest(req->source_net_log(), req->info());
1241 req->OnJobCancelled(this);
[email protected]b3601bc22012-02-21 21:23:201242 }
[email protected]68ad3ee2010-01-30 03:45:391243 }
1244
[email protected]daae1322013-09-05 18:26:501245 // Add this job to the dispatcher. If "at_head" is true, adds at the front
1246 // of the queue.
1247 void Schedule(bool at_head) {
1248 DCHECK(!is_queued());
1249 PrioritizedDispatcher::Handle handle;
1250 if (!at_head) {
[email protected]106ccd2c2014-06-17 09:21:001251 handle = resolver_->dispatcher_->Add(this, priority());
[email protected]daae1322013-09-05 18:26:501252 } else {
[email protected]106ccd2c2014-06-17 09:21:001253 handle = resolver_->dispatcher_->AddAtHead(this, priority());
[email protected]daae1322013-09-05 18:26:501254 }
1255 // The dispatcher could have started |this| in the above call to Add, which
1256 // could have called Schedule again. In that case |handle| will be null,
1257 // but |handle_| may have been set by the other nested call to Schedule.
1258 if (!handle.is_null()) {
1259 DCHECK(handle_.is_null());
1260 handle_ = handle;
1261 }
[email protected]16ee26d2012-03-08 03:34:351262 }
1263
maksim.sisov31452af2016-07-27 06:38:101264 void AddRequest(RequestImpl* request) {
1265 DCHECK_EQ(key_.hostname, request->info().hostname());
[email protected]0f292de02012-02-01 22:28:201266
maksim.sisov31452af2016-07-27 06:38:101267 priority_tracker_.Add(request->priority());
[email protected]0f292de02012-02-01 22:28:201268
maksim.sisov31452af2016-07-27 06:38:101269 request->source_net_log().AddEvent(
mikecirone8b85c432016-09-08 19:11:001270 NetLogEventType::HOST_RESOLVER_IMPL_JOB_ATTACH,
[email protected]cd565142012-06-12 16:21:451271 net_log_.source().ToEventParametersCallback());
[email protected]0f292de02012-02-01 22:28:201272
1273 net_log_.AddEvent(
mikecirone8b85c432016-09-08 19:11:001274 NetLogEventType::HOST_RESOLVER_IMPL_JOB_REQUEST_ATTACH,
maksim.sisov31452af2016-07-27 06:38:101275 base::Bind(&NetLogJobAttachCallback, request->source_net_log().source(),
[email protected]cd565142012-06-12 16:21:451276 priority()));
[email protected]0f292de02012-02-01 22:28:201277
Miriam Gershenson61604662017-09-28 23:51:111278 if (!request->info().is_speculative())
[email protected]0f292de02012-02-01 22:28:201279 had_non_speculative_request_ = true;
[email protected]b3601bc22012-02-21 21:23:201280
David Benjamina5677192018-04-23 23:25:421281 requests_.Append(request);
[email protected]b3601bc22012-02-21 21:23:201282
[email protected]51b9a6b2012-06-25 21:50:291283 UpdatePriority();
[email protected]68ad3ee2010-01-30 03:45:391284 }
1285
maksim.sisov31452af2016-07-27 06:38:101286 void ChangeRequestPriority(RequestImpl* req, RequestPriority priority) {
juliatuttlec53b19a72016-05-05 13:51:311287 DCHECK_EQ(key_.hostname, req->info().hostname());
juliatuttlec53b19a72016-05-05 13:51:311288
1289 priority_tracker_.Remove(req->priority());
1290 req->set_priority(priority);
1291 priority_tracker_.Add(req->priority());
1292 UpdatePriority();
1293 }
1294
maksim.sisov31452af2016-07-27 06:38:101295 // Detach cancelled request. If it was the last active Request, also finishes
1296 // this Job.
1297 void CancelRequest(RequestImpl* request) {
1298 DCHECK_EQ(key_.hostname, request->info().hostname());
1299 DCHECK(!requests_.empty());
[email protected]16ee26d2012-03-08 03:34:351300
maksim.sisov31452af2016-07-27 06:38:101301 LogCancelRequest(request->source_net_log(), request->info());
[email protected]16ee26d2012-03-08 03:34:351302
maksim.sisov31452af2016-07-27 06:38:101303 priority_tracker_.Remove(request->priority());
1304 net_log_.AddEvent(
mikecirone8b85c432016-09-08 19:11:001305 NetLogEventType::HOST_RESOLVER_IMPL_JOB_REQUEST_DETACH,
maksim.sisov31452af2016-07-27 06:38:101306 base::Bind(&NetLogJobAttachCallback, request->source_net_log().source(),
1307 priority()));
[email protected]b3601bc22012-02-21 21:23:201308
[email protected]16ee26d2012-03-08 03:34:351309 if (num_active_requests() > 0) {
[email protected]51b9a6b2012-06-25 21:50:291310 UpdatePriority();
David Benjamina5677192018-04-23 23:25:421311 request->RemoveFromList();
[email protected]16ee26d2012-03-08 03:34:351312 } else {
1313 // If we were called from a Request's callback within CompleteRequests,
1314 // that Request could not have been cancelled, so num_active_requests()
1315 // could not be 0. Therefore, we are not in CompleteRequests().
[email protected]1339a2a22012-10-17 08:39:431316 CompleteRequestsWithError(OK /* cancelled */);
[email protected]b3601bc22012-02-21 21:23:201317 }
[email protected]68ad3ee2010-01-30 03:45:391318 }
1319
[email protected]7af985a2012-12-14 22:40:421320 // Called from AbortAllInProgressJobs. Completes all requests and destroys
1321 // the job. This currently assumes the abort is due to a network change.
olli.raulaa21e9eb72015-12-17 08:18:111322 // TODO This should not delete |this|.
[email protected]0f292de02012-02-01 22:28:201323 void Abort() {
[email protected]0f292de02012-02-01 22:28:201324 DCHECK(is_running());
[email protected]7af985a2012-12-14 22:40:421325 CompleteRequestsWithError(ERR_NETWORK_CHANGED);
[email protected]b3601bc22012-02-21 21:23:201326 }
1327
[email protected]f0f602bd2012-11-15 18:01:021328 // If DnsTask present, abort it and fall back to ProcTask.
1329 void AbortDnsTask() {
1330 if (dns_task_) {
[email protected]daae1322013-09-05 18:26:501331 KillDnsTask();
[email protected]f0f602bd2012-11-15 18:01:021332 dns_task_error_ = OK;
1333 StartProcTask();
1334 }
1335 }
1336
[email protected]16ee26d2012-03-08 03:34:351337 // Called by HostResolverImpl when this job is evicted due to queue overflow.
1338 // Completes all requests and destroys the job.
1339 void OnEvicted() {
1340 DCHECK(!is_running());
1341 DCHECK(is_queued());
1342 handle_.Reset();
1343
mikecirone8b85c432016-09-08 19:11:001344 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB_EVICTED);
[email protected]16ee26d2012-03-08 03:34:351345
1346 // This signals to CompleteRequests that this job never ran.
[email protected]1339a2a22012-10-17 08:39:431347 CompleteRequestsWithError(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
[email protected]16ee26d2012-03-08 03:34:351348 }
1349
[email protected]78eac2a2012-03-14 19:09:271350 // Attempts to serve the job from HOSTS. Returns true if succeeded and
1351 // this Job was destroyed.
1352 bool ServeFromHosts() {
1353 DCHECK_GT(num_active_requests(), 0u);
1354 AddressList addr_list;
David Benjamina5677192018-04-23 23:25:421355 if (resolver_->ServeFromHosts(key(), requests_.head()->value()->info(),
[email protected]78eac2a2012-03-14 19:09:271356 &addr_list)) {
1357 // This will destroy the Job.
Rob Percival94f21ad2017-11-14 10:20:241358 CompleteRequests(
1359 MakeCacheEntry(OK, addr_list, HostCache::Entry::SOURCE_HOSTS),
1360 base::TimeDelta());
[email protected]78eac2a2012-03-14 19:09:271361 return true;
1362 }
1363 return false;
1364 }
1365
tanay.c6ddd5f6f2015-08-25 06:34:571366 const Key& key() const { return key_; }
[email protected]b4481b222012-03-16 17:13:111367
1368 bool is_queued() const {
1369 return !handle_.is_null();
1370 }
1371
1372 bool is_running() const {
1373 return is_dns_running() || is_proc_running();
1374 }
1375
[email protected]16ee26d2012-03-08 03:34:351376 private:
[email protected]daae1322013-09-05 18:26:501377 void KillDnsTask() {
1378 if (dns_task_) {
1379 ReduceToOneJobSlot();
1380 dns_task_.reset();
1381 }
1382 }
1383
1384 // Reduce the number of job slots occupied and queued in the dispatcher
1385 // to one. If the second Job slot is queued in the dispatcher, cancels the
1386 // queued job. Otherwise, the second Job has been started by the
1387 // PrioritizedDispatcher, so signals it is complete.
1388 void ReduceToOneJobSlot() {
1389 DCHECK_GE(num_occupied_job_slots_, 1u);
1390 if (is_queued()) {
[email protected]106ccd2c2014-06-17 09:21:001391 resolver_->dispatcher_->Cancel(handle_);
[email protected]daae1322013-09-05 18:26:501392 handle_.Reset();
1393 } else if (num_occupied_job_slots_ > 1) {
[email protected]106ccd2c2014-06-17 09:21:001394 resolver_->dispatcher_->OnJobFinished();
[email protected]daae1322013-09-05 18:26:501395 --num_occupied_job_slots_;
1396 }
1397 DCHECK_EQ(1u, num_occupied_job_slots_);
1398 }
1399
eroman0cd87b62016-12-14 19:13:451400 // MakeCacheEntry() and MakeCacheEntryWithTTL() are helpers to build a
1401 // HostCache::Entry(). The address list is omited from the cache entry
1402 // for errors.
1403 HostCache::Entry MakeCacheEntry(int net_error,
Rob Percival94f21ad2017-11-14 10:20:241404 const AddressList& addr_list,
1405 HostCache::Entry::Source source) const {
eroman0cd87b62016-12-14 19:13:451406 return HostCache::Entry(
1407 net_error,
Rob Percival94f21ad2017-11-14 10:20:241408 net_error == OK ? MakeAddressListForRequest(addr_list) : AddressList(),
1409 source);
eroman0cd87b62016-12-14 19:13:451410 }
1411
1412 HostCache::Entry MakeCacheEntryWithTTL(int net_error,
1413 const AddressList& addr_list,
Rob Percival94f21ad2017-11-14 10:20:241414 HostCache::Entry::Source source,
eroman0cd87b62016-12-14 19:13:451415 base::TimeDelta ttl) const {
1416 return HostCache::Entry(
1417 net_error,
1418 net_error == OK ? MakeAddressListForRequest(addr_list) : AddressList(),
Rob Percival94f21ad2017-11-14 10:20:241419 source, ttl);
eroman0cd87b62016-12-14 19:13:451420 }
1421
juliatuttlec53b19a72016-05-05 13:51:311422 AddressList MakeAddressListForRequest(const AddressList& list) const {
1423 if (requests_.empty())
1424 return list;
David Benjamina5677192018-04-23 23:25:421425 return AddressList::CopyWithPort(list,
1426 requests_.head()->value()->info().port());
juliatuttlec53b19a72016-05-05 13:51:311427 }
1428
[email protected]51b9a6b2012-06-25 21:50:291429 void UpdatePriority() {
1430 if (is_queued()) {
1431 if (priority() != static_cast<RequestPriority>(handle_.priority()))
Misha Efimovb99e7da2018-05-30 16:59:021432 priority_change_time_ = tick_clock_->NowTicks();
[email protected]106ccd2c2014-06-17 09:21:001433 handle_ = resolver_->dispatcher_->ChangePriority(handle_, priority());
[email protected]51b9a6b2012-06-25 21:50:291434 }
1435 }
1436
[email protected]16ee26d2012-03-08 03:34:351437 // PriorityDispatch::Job:
dchengb03027d2014-10-21 12:00:201438 void Start() override {
[email protected]daae1322013-09-05 18:26:501439 DCHECK_LE(num_occupied_job_slots_, 1u);
1440
[email protected]70c04ab2013-08-22 16:05:121441 handle_.Reset();
[email protected]daae1322013-09-05 18:26:501442 ++num_occupied_job_slots_;
1443
1444 if (num_occupied_job_slots_ == 2) {
1445 StartSecondDnsTransaction();
1446 return;
1447 }
1448
1449 DCHECK(!is_running());
[email protected]0f292de02012-02-01 22:28:201450
mikecirone8b85c432016-09-08 19:11:001451 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB_STARTED);
[email protected]0f292de02012-02-01 22:28:201452
[email protected]51b9a6b2012-06-25 21:50:291453 had_dns_config_ = resolver_->HaveDnsConfig();
1454
Misha Efimovb99e7da2018-05-30 16:59:021455 start_time_ = tick_clock_->NowTicks();
Miriam Gershenson61604662017-09-28 23:51:111456 base::TimeDelta queue_time = start_time_ - creation_time_;
1457 base::TimeDelta queue_time_after_change =
1458 start_time_ - priority_change_time_;
[email protected]51b9a6b2012-06-25 21:50:291459
Miriam Gershenson90d05e02017-09-28 19:29:281460 DNS_HISTOGRAM_BY_PRIORITY("Net.DNS.JobQueueTime", priority(), queue_time);
1461 DNS_HISTOGRAM_BY_PRIORITY("Net.DNS.JobQueueTimeAfterChange", priority(),
1462 queue_time_after_change);
[email protected]51b9a6b2012-06-25 21:50:291463
[email protected]443714fad2013-09-19 04:52:011464 bool system_only =
1465 (key_.host_resolver_flags & HOST_RESOLVER_SYSTEM_ONLY) != 0;
1466
[email protected]1d932852012-06-19 19:40:331467 // Caution: Job::Start must not complete synchronously.
[email protected]443714fad2013-09-19 04:52:011468 if (!system_only && had_dns_config_ &&
1469 !ResemblesMulticastDNSName(key_.hostname)) {
[email protected]b3601bc22012-02-21 21:23:201470 StartDnsTask();
1471 } else {
1472 StartProcTask();
1473 }
1474 }
1475
[email protected]b3601bc22012-02-21 21:23:201476 // TODO(szym): Since DnsTransaction does not consume threads, we can increase
Francois Doraya2d01ba2017-09-25 19:17:401477 // the limits on |dispatcher_|. But in order to keep the number of
1478 // TaskScheduler threads low, we will need to use an "inner"
1479 // PrioritizedDispatcher with tighter limits.
[email protected]b3601bc22012-02-21 21:23:201480 void StartProcTask() {
[email protected]16ee26d2012-03-08 03:34:351481 DCHECK(!is_dns_running());
Eric Orth9a037562018-07-03 21:24:381482 proc_task_ = std::make_unique<ProcTask>(
Misha Efimovb99e7da2018-05-30 16:59:021483 key_, resolver_->proc_params_,
1484 base::Bind(&Job::OnProcTaskComplete, base::Unretained(this),
1485 tick_clock_->NowTicks()),
1486 proc_task_runner_, net_log_, tick_clock_);
[email protected]0f292de02012-02-01 22:28:201487
[email protected]0f292de02012-02-01 22:28:201488 // Start() could be called from within Resolve(), hence it must NOT directly
1489 // call OnProcTaskComplete, for example, on synchronous failure.
1490 proc_task_->Start();
[email protected]68ad3ee2010-01-30 03:45:391491 }
1492
[email protected]0f292de02012-02-01 22:28:201493 // Called by ProcTask when it completes.
[email protected]e3bd4822012-10-23 18:01:371494 void OnProcTaskComplete(base::TimeTicks start_time,
1495 int net_error,
1496 const AddressList& addr_list) {
[email protected]b3601bc22012-02-21 21:23:201497 DCHECK(is_proc_running());
[email protected]68ad3ee2010-01-30 03:45:391498
[email protected]1d932852012-06-19 19:40:331499 if (dns_task_error_ != OK) {
Misha Efimovb99e7da2018-05-30 16:59:021500 base::TimeDelta duration = tick_clock_->NowTicks() - start_time;
[email protected]1def74c2012-03-22 20:07:001501 if (net_error == OK) {
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211502 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.FallbackSuccess", duration);
[email protected]1d932852012-06-19 19:40:331503 if ((dns_task_error_ == ERR_NAME_NOT_RESOLVED) &&
1504 ResemblesNetBIOSName(key_.hostname)) {
1505 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_SUSPECT_NETBIOS);
1506 } else {
1507 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_PROC_SUCCESS);
1508 }
Ilya Sherman0eb39802017-12-08 20:58:181509 base::UmaHistogramSparse("Net.DNS.DnsTask.Errors",
1510 std::abs(dns_task_error_));
[email protected]1ffdda82012-12-12 23:04:221511 resolver_->OnDnsTaskResolve(dns_task_error_);
[email protected]1def74c2012-03-22 20:07:001512 } else {
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211513 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.FallbackFail", duration);
[email protected]1def74c2012-03-22 20:07:001514 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
1515 }
1516 }
1517
eroman1efc237c2016-12-14 00:00:451518 if (ContainsIcannNameCollisionIp(addr_list))
1519 net_error = ERR_ICANN_NAME_COLLISION;
1520
[email protected]1339a2a22012-10-17 08:39:431521 base::TimeDelta ttl =
1522 base::TimeDelta::FromSeconds(kNegativeCacheEntryTTLSeconds);
[email protected]b3601bc22012-02-21 21:23:201523 if (net_error == OK)
1524 ttl = base::TimeDelta::FromSeconds(kCacheEntryTTLSeconds);
[email protected]68ad3ee2010-01-30 03:45:391525
Rob Percival94f21ad2017-11-14 10:20:241526 // Source unknown because the system resolver could have gotten it from a
1527 // hosts file, its own cache, a DNS lookup or somewhere else.
[email protected]895123222012-10-25 15:21:171528 // Don't store the |ttl| in cache since it's not obtained from the server.
Rob Percival94f21ad2017-11-14 10:20:241529 CompleteRequests(
1530 MakeCacheEntry(net_error, addr_list, HostCache::Entry::SOURCE_UNKNOWN),
1531 ttl);
[email protected]b3601bc22012-02-21 21:23:201532 }
1533
1534 void StartDnsTask() {
[email protected]78eac2a2012-03-14 19:09:271535 DCHECK(resolver_->HaveDnsConfig());
[email protected]daae1322013-09-05 18:26:501536 dns_task_.reset(new DnsTask(resolver_->dns_client_.get(), key_, this,
Misha Efimovb99e7da2018-05-30 16:59:021537 net_log_, tick_clock_));
[email protected]b3601bc22012-02-21 21:23:201538
[email protected]daae1322013-09-05 18:26:501539 dns_task_->StartFirstTransaction();
1540 // Schedule a second transaction, if needed.
1541 if (dns_task_->needs_two_transactions())
1542 Schedule(true);
1543 }
1544
1545 void StartSecondDnsTransaction() {
1546 DCHECK(dns_task_->needs_two_transactions());
1547 dns_task_->StartSecondTransaction();
[email protected]16c2bd72013-06-28 01:19:221548 }
1549
1550 // Called if DnsTask fails. It is posted from StartDnsTask, so Job may be
1551 // deleted before this callback. In this case dns_task is deleted as well,
1552 // so we use it as indicator whether Job is still valid.
1553 void OnDnsTaskFailure(const base::WeakPtr<DnsTask>& dns_task,
1554 base::TimeDelta duration,
1555 int net_error) {
Miriam Gershenson61604662017-09-28 23:51:111556 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.DnsTask.FailureTime", duration);
[email protected]16c2bd72013-06-28 01:19:221557
wezb9820d42016-06-22 23:41:041558 if (!dns_task)
[email protected]16c2bd72013-06-28 01:19:221559 return;
1560
Miriam Gershenson19faef812018-02-07 23:56:441561 if (duration < base::TimeDelta::FromMilliseconds(10)) {
1562 base::UmaHistogramSparse("Net.DNS.DnsTask.ErrorBeforeFallback.Fast",
1563 std::abs(net_error));
1564 } else {
1565 base::UmaHistogramSparse("Net.DNS.DnsTask.ErrorBeforeFallback.Slow",
1566 std::abs(net_error));
1567 }
[email protected]16c2bd72013-06-28 01:19:221568 dns_task_error_ = net_error;
1569
1570 // TODO(szym): Run ServeFromHosts now if nsswitch.conf says so.
1571 // http://crbug.com/117655
1572
1573 // TODO(szym): Some net errors indicate lack of connectivity. Starting
1574 // ProcTask in that case is a waste of time.
1575 if (resolver_->fallback_to_proctask_) {
[email protected]daae1322013-09-05 18:26:501576 KillDnsTask();
[email protected]16c2bd72013-06-28 01:19:221577 StartProcTask();
1578 } else {
1579 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
Brad Lassey2e8f185d2018-05-21 22:25:211580 // If the ttl is max, we didn't get one from the record, so set it to 0
1581 base::TimeDelta ttl =
1582 dns_task->ttl() < base::TimeDelta::FromSeconds(
1583 std::numeric_limits<uint32_t>::max())
1584 ? dns_task->ttl()
1585 : base::TimeDelta::FromSeconds(0);
1586 CompleteRequests(
1587 HostCache::Entry(net_error, AddressList(),
1588 HostCache::Entry::Source::SOURCE_UNKNOWN, ttl),
1589 ttl);
[email protected]b3601bc22012-02-21 21:23:201590 }
1591 }
1592
[email protected]daae1322013-09-05 18:26:501593
1594 // HostResolverImpl::DnsTask::Delegate implementation:
1595
dchengb03027d2014-10-21 12:00:201596 void OnDnsTaskComplete(base::TimeTicks start_time,
1597 int net_error,
1598 const AddressList& addr_list,
1599 base::TimeDelta ttl) override {
[email protected]b3601bc22012-02-21 21:23:201600 DCHECK(is_dns_running());
[email protected]b3601bc22012-02-21 21:23:201601
Misha Efimovb99e7da2018-05-30 16:59:021602 base::TimeDelta duration = tick_clock_->NowTicks() - start_time;
[email protected]b3601bc22012-02-21 21:23:201603 if (net_error != OK) {
[email protected]16c2bd72013-06-28 01:19:221604 OnDnsTaskFailure(dns_task_->AsWeakPtr(), duration, net_error);
[email protected]b3601bc22012-02-21 21:23:201605 return;
1606 }
Miriam Gershenson61604662017-09-28 23:51:111607
1608 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.DnsTask.SuccessTime", duration);
[email protected]b3601bc22012-02-21 21:23:201609
[email protected]1def74c2012-03-22 20:07:001610 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_DNS_SUCCESS);
[email protected]1339a2a22012-10-17 08:39:431611 RecordTTL(ttl);
[email protected]0adcb2b2012-08-15 21:30:461612
[email protected]1ffdda82012-12-12 23:04:221613 resolver_->OnDnsTaskResolve(OK);
[email protected]f0f602bd2012-11-15 18:01:021614
[email protected]895123222012-10-25 15:21:171615 base::TimeDelta bounded_ttl =
1616 std::max(ttl, base::TimeDelta::FromSeconds(kMinimumTTLSeconds));
1617
eroman0cd87b62016-12-14 19:13:451618 if (ContainsIcannNameCollisionIp(addr_list)) {
1619 CompleteRequestsWithError(ERR_ICANN_NAME_COLLISION);
1620 } else {
Rob Percival94f21ad2017-11-14 10:20:241621 CompleteRequests(MakeCacheEntryWithTTL(net_error, addr_list,
1622 HostCache::Entry::SOURCE_DNS, ttl),
eroman0cd87b62016-12-14 19:13:451623 bounded_ttl);
1624 }
[email protected]b3601bc22012-02-21 21:23:201625 }
1626
dchengb03027d2014-10-21 12:00:201627 void OnFirstDnsTransactionComplete() override {
[email protected]daae1322013-09-05 18:26:501628 DCHECK(dns_task_->needs_two_transactions());
1629 DCHECK_EQ(dns_task_->needs_another_transaction(), is_queued());
1630 // No longer need to occupy two dispatcher slots.
1631 ReduceToOneJobSlot();
1632
1633 // We already have a job slot at the dispatcher, so if the second
1634 // transaction hasn't started, reuse it now instead of waiting in the queue
1635 // for the second slot.
1636 if (dns_task_->needs_another_transaction())
1637 dns_task_->StartSecondTransaction();
1638 }
1639
Brad Lassey786929ad2018-02-21 20:54:271640 URLRequestContext* url_request_context() override {
1641 return resolver_->url_request_context_;
1642 }
1643
Miriam Gershenson61604662017-09-28 23:51:111644 void RecordJobHistograms(int error) {
Miriam Gershensonc282ab42017-11-20 23:19:581645 // Used in UMA_HISTOGRAM_ENUMERATION. Do not renumber entries or reuse
1646 // deprecated values.
1647 enum Category {
1648 RESOLVE_SUCCESS = 0,
1649 RESOLVE_FAIL = 1,
1650 RESOLVE_SPECULATIVE_SUCCESS = 2,
1651 RESOLVE_SPECULATIVE_FAIL = 3,
1652 RESOLVE_ABORT = 4,
1653 RESOLVE_SPECULATIVE_ABORT = 5,
Miriam Gershenson61604662017-09-28 23:51:111654 RESOLVE_MAX, // Bounding value.
1655 };
1656 Category category = RESOLVE_MAX; // Illegal value for later DCHECK only.
1657
Misha Efimovb99e7da2018-05-30 16:59:021658 base::TimeDelta duration = tick_clock_->NowTicks() - start_time_;
Miriam Gershenson61604662017-09-28 23:51:111659 if (error == OK) {
1660 if (had_non_speculative_request_) {
1661 category = RESOLVE_SUCCESS;
1662 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime", duration);
1663 switch (key_.address_family) {
1664 case ADDRESS_FAMILY_IPV4:
1665 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime.IPV4",
1666 duration);
1667 break;
1668 case ADDRESS_FAMILY_IPV6:
1669 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime.IPV6",
1670 duration);
1671 break;
1672 case ADDRESS_FAMILY_UNSPECIFIED:
1673 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime.UNSPEC",
1674 duration);
1675 break;
1676 }
1677 } else {
1678 category = RESOLVE_SPECULATIVE_SUCCESS;
Miriam Gershenson61604662017-09-28 23:51:111679 }
Miriam Gershensonc282ab42017-11-20 23:19:581680 } else if (error == ERR_NETWORK_CHANGED ||
1681 error == ERR_HOST_RESOLVER_QUEUE_TOO_LARGE) {
1682 category = had_non_speculative_request_ ? RESOLVE_ABORT
1683 : RESOLVE_SPECULATIVE_ABORT;
Miriam Gershenson61604662017-09-28 23:51:111684 } else {
1685 if (had_non_speculative_request_) {
1686 category = RESOLVE_FAIL;
1687 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveFailureTime", duration);
1688 switch (key_.address_family) {
1689 case ADDRESS_FAMILY_IPV4:
Miriam Gershensonc282ab42017-11-20 23:19:581690 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveFailureTime.IPV4",
Miriam Gershenson61604662017-09-28 23:51:111691 duration);
1692 break;
1693 case ADDRESS_FAMILY_IPV6:
Miriam Gershensonc282ab42017-11-20 23:19:581694 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveFailureTime.IPV6",
Miriam Gershenson61604662017-09-28 23:51:111695 duration);
1696 break;
1697 case ADDRESS_FAMILY_UNSPECIFIED:
Miriam Gershensonc282ab42017-11-20 23:19:581698 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveFailureTime.UNSPEC",
Miriam Gershenson61604662017-09-28 23:51:111699 duration);
1700 break;
1701 }
1702 } else {
1703 category = RESOLVE_SPECULATIVE_FAIL;
Miriam Gershenson61604662017-09-28 23:51:111704 }
1705 }
1706 DCHECK_LT(static_cast<int>(category),
1707 static_cast<int>(RESOLVE_MAX)); // Be sure it was set.
1708 UMA_HISTOGRAM_ENUMERATION("Net.DNS.ResolveCategory", category, RESOLVE_MAX);
Miriam Gershensonaaf139582017-11-27 16:06:061709
1710 if (category == RESOLVE_FAIL || category == RESOLVE_ABORT) {
1711 if (duration < base::TimeDelta::FromMilliseconds(10))
Ilya Sherman0eb39802017-12-08 20:58:181712 base::UmaHistogramSparse("Net.DNS.ResolveError.Fast", std::abs(error));
Miriam Gershensonaaf139582017-11-27 16:06:061713 else
Ilya Sherman0eb39802017-12-08 20:58:181714 base::UmaHistogramSparse("Net.DNS.ResolveError.Slow", std::abs(error));
Miriam Gershensonaaf139582017-11-27 16:06:061715 }
Miriam Gershenson61604662017-09-28 23:51:111716 }
1717
[email protected]16ee26d2012-03-08 03:34:351718 // Performs Job's last rites. Completes all Requests. Deletes this.
[email protected]895123222012-10-25 15:21:171719 void CompleteRequests(const HostCache::Entry& entry,
1720 base::TimeDelta ttl) {
[email protected]11fbca0b2013-06-02 23:37:211721 CHECK(resolver_.get());
[email protected]b3601bc22012-02-21 21:23:201722
[email protected]16ee26d2012-03-08 03:34:351723 // This job must be removed from resolver's |jobs_| now to make room for a
1724 // new job with the same key in case one of the OnComplete callbacks decides
Eric Orth18544ae2018-06-11 22:57:161725 // to spawn one. Consequently, if the job was owned by |jobs_|, the job
1726 // deletes itself when CompleteRequests is done.
1727 std::unique_ptr<Job> self_deleter = resolver_->RemoveJob(this);
[email protected]16ee26d2012-03-08 03:34:351728
[email protected]16ee26d2012-03-08 03:34:351729 if (is_running()) {
Eric Orth9a037562018-07-03 21:24:381730 proc_task_ = nullptr;
[email protected]daae1322013-09-05 18:26:501731 KillDnsTask();
[email protected]16ee26d2012-03-08 03:34:351732
1733 // Signal dispatcher that a slot has opened.
[email protected]106ccd2c2014-06-17 09:21:001734 resolver_->dispatcher_->OnJobFinished();
[email protected]16ee26d2012-03-08 03:34:351735 } else if (is_queued()) {
[email protected]106ccd2c2014-06-17 09:21:001736 resolver_->dispatcher_->Cancel(handle_);
[email protected]16ee26d2012-03-08 03:34:351737 handle_.Reset();
1738 }
1739
1740 if (num_active_requests() == 0) {
mikecirone8b85c432016-09-08 19:11:001741 net_log_.AddEvent(NetLogEventType::CANCELLED);
1742 net_log_.EndEventWithNetErrorCode(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
[email protected]16ee26d2012-03-08 03:34:351743 OK);
1744 return;
1745 }
[email protected]b3601bc22012-02-21 21:23:201746
mikecirone8b85c432016-09-08 19:11:001747 net_log_.EndEventWithNetErrorCode(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
juliatuttle317860e2016-05-12 14:47:221748 entry.error());
[email protected]68ad3ee2010-01-30 03:45:391749
[email protected]78eac2a2012-03-14 19:09:271750 DCHECK(!requests_.empty());
1751
eroman1efc237c2016-12-14 00:00:451752 if (entry.error() == OK || entry.error() == ERR_ICANN_NAME_COLLISION) {
[email protected]d7b9a2b2012-05-31 22:31:191753 // Record this histogram here, when we know the system has a valid DNS
1754 // configuration.
[email protected]539df6c2012-06-19 21:21:291755 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.HaveDnsConfig",
1756 resolver_->received_dns_config_);
[email protected]d7b9a2b2012-05-31 22:31:191757 }
[email protected]16ee26d2012-03-08 03:34:351758
juliatuttle317860e2016-05-12 14:47:221759 bool did_complete = (entry.error() != ERR_NETWORK_CHANGED) &&
1760 (entry.error() != ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
Miriam Gershensonc282ab42017-11-20 23:19:581761 if (did_complete)
[email protected]1339a2a22012-10-17 08:39:431762 resolver_->CacheResult(key_, entry, ttl);
Miriam Gershensonc282ab42017-11-20 23:19:581763
1764 RecordJobHistograms(entry.error());
[email protected]16ee26d2012-03-08 03:34:351765
maksim.sisov31452af2016-07-27 06:38:101766 // Complete all of the requests that were attached to the job and
1767 // detach them.
1768 while (!requests_.empty()) {
David Benjamina5677192018-04-23 23:25:421769 RequestImpl* req = requests_.head()->value();
1770 req->RemoveFromList();
[email protected]0f292de02012-02-01 22:28:201771 DCHECK_EQ(this, req->job());
1772 // Update the net log and notify registered observers.
juliatuttle317860e2016-05-12 14:47:221773 LogFinishRequest(req->source_net_log(), req->info(), entry.error());
[email protected]51b9a6b2012-06-25 21:50:291774 if (did_complete) {
1775 // Record effective total time from creation to completion.
Miriam Gershenson90d05e02017-09-28 19:29:281776 RecordTotalTime(req->info().is_speculative(), false,
Misha Efimovb99e7da2018-05-30 16:59:021777 tick_clock_->NowTicks() - req->request_time());
[email protected]51b9a6b2012-06-25 21:50:291778 }
maksim.sisov31452af2016-07-27 06:38:101779 req->OnJobCompleted(this, entry.error(), entry.addresses());
[email protected]0f292de02012-02-01 22:28:201780
1781 // Check if the resolver was destroyed as a result of running the
1782 // callback. If it was, we could continue, but we choose to bail.
[email protected]11fbca0b2013-06-02 23:37:211783 if (!resolver_.get())
[email protected]0f292de02012-02-01 22:28:201784 return;
1785 }
1786 }
1787
[email protected]1339a2a22012-10-17 08:39:431788 // Convenience wrapper for CompleteRequests in case of failure.
1789 void CompleteRequestsWithError(int net_error) {
Rob Percival94f21ad2017-11-14 10:20:241790 CompleteRequests(HostCache::Entry(net_error, AddressList(),
1791 HostCache::Entry::SOURCE_UNKNOWN),
[email protected]895123222012-10-25 15:21:171792 base::TimeDelta());
[email protected]1339a2a22012-10-17 08:39:431793 }
1794
Brad Lassey786929ad2018-02-21 20:54:271795 RequestPriority priority() const override {
[email protected]b4481b222012-03-16 17:13:111796 return priority_tracker_.highest_priority();
1797 }
1798
1799 // Number of non-canceled requests in |requests_|.
1800 size_t num_active_requests() const {
1801 return priority_tracker_.total_count();
1802 }
1803
wezb9820d42016-06-22 23:41:041804 bool is_dns_running() const { return !!dns_task_; }
[email protected]b4481b222012-03-16 17:13:111805
wezb9820d42016-06-22 23:41:041806 bool is_proc_running() const { return !!proc_task_; }
[email protected]b4481b222012-03-16 17:13:111807
[email protected]0f292de02012-02-01 22:28:201808 base::WeakPtr<HostResolverImpl> resolver_;
1809
1810 Key key_;
1811
1812 // Tracks the highest priority across |requests_|.
1813 PriorityTracker priority_tracker_;
1814
Miriam Gershensone42adb22017-10-16 16:19:381815 // Task runner used for HostResolverProc.
1816 scoped_refptr<base::TaskRunner> proc_task_runner_;
1817
[email protected]0f292de02012-02-01 22:28:201818 bool had_non_speculative_request_;
1819
[email protected]51b9a6b2012-06-25 21:50:291820 // Distinguishes measurements taken while DnsClient was fully configured.
1821 bool had_dns_config_;
1822
[email protected]daae1322013-09-05 18:26:501823 // Number of slots occupied by this Job in resolver's PrioritizedDispatcher.
1824 unsigned num_occupied_job_slots_;
1825
[email protected]1d932852012-06-19 19:40:331826 // Result of DnsTask.
1827 int dns_task_error_;
[email protected]1def74c2012-03-22 20:07:001828
Misha Efimovb99e7da2018-05-30 16:59:021829 const base::TickClock* tick_clock_;
[email protected]51b9a6b2012-06-25 21:50:291830 const base::TimeTicks creation_time_;
1831 base::TimeTicks priority_change_time_;
Miriam Gershenson61604662017-09-28 23:51:111832 base::TimeTicks start_time_;
[email protected]51b9a6b2012-06-25 21:50:291833
tfarina428341112016-09-22 13:38:201834 NetLogWithSource net_log_;
[email protected]0f292de02012-02-01 22:28:201835
[email protected]b3601bc22012-02-21 21:23:201836 // Resolves the host using a HostResolverProc.
Eric Orth9a037562018-07-03 21:24:381837 std::unique_ptr<ProcTask> proc_task_;
[email protected]0f292de02012-02-01 22:28:201838
[email protected]b3601bc22012-02-21 21:23:201839 // Resolves the host using a DnsTransaction.
danakj22f90e72016-04-16 01:55:401840 std::unique_ptr<DnsTask> dns_task_;
[email protected]b3601bc22012-02-21 21:23:201841
[email protected]0f292de02012-02-01 22:28:201842 // All Requests waiting for the result of this Job. Some can be canceled.
David Benjamina5677192018-04-23 23:25:421843 base::LinkedList<RequestImpl> requests_;
[email protected]0f292de02012-02-01 22:28:201844
[email protected]16ee26d2012-03-08 03:34:351845 // A handle used in |HostResolverImpl::dispatcher_|.
[email protected]0f292de02012-02-01 22:28:201846 PrioritizedDispatcher::Handle handle_;
[email protected]68ad3ee2010-01-30 03:45:391847};
1848
1849//-----------------------------------------------------------------------------
1850
[email protected]0f292de02012-02-01 22:28:201851HostResolverImpl::ProcTaskParams::ProcTaskParams(
[email protected]e95d3aca2010-01-11 22:47:431852 HostResolverProc* resolver_proc,
[email protected]0f292de02012-02-01 22:28:201853 size_t max_retry_attempts)
1854 : resolver_proc(resolver_proc),
1855 max_retry_attempts(max_retry_attempts),
ttuttlecf1158bf2016-03-18 16:37:441856 unresponsive_delay(
1857 base::TimeDelta::FromMilliseconds(kDnsDefaultUnresponsiveDelayMs)),
[email protected]0f292de02012-02-01 22:28:201858 retry_factor(2) {
[email protected]106ccd2c2014-06-17 09:21:001859 // Maximum of 4 retry attempts for host resolution.
1860 static const size_t kDefaultMaxRetryAttempts = 4u;
1861 if (max_retry_attempts == HostResolver::kDefaultRetryAttempts)
1862 max_retry_attempts = kDefaultMaxRetryAttempts;
[email protected]0f292de02012-02-01 22:28:201863}
1864
vmpstracd23b72016-02-26 21:08:551865HostResolverImpl::ProcTaskParams::ProcTaskParams(const ProcTaskParams& other) =
1866 default;
1867
Chris Watkins68b15032017-12-01 03:07:131868HostResolverImpl::ProcTaskParams::~ProcTaskParams() = default;
[email protected]0f292de02012-02-01 22:28:201869
[email protected]b59ff372009-07-15 22:04:321870HostResolverImpl::~HostResolverImpl() {
gab47aa7da2017-06-02 16:09:431871 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
[email protected]daae1322013-09-05 18:26:501872 // Prevent the dispatcher from starting new jobs.
[email protected]106ccd2c2014-06-17 09:21:001873 dispatcher_->SetLimitsToZero();
avi9e72eb482016-12-09 21:10:541874 // It's now safe for Jobs to call KillDnsTask on destruction, because
[email protected]daae1322013-09-05 18:26:501875 // OnJobComplete will not start any new jobs.
avi9e72eb482016-12-09 21:10:541876 jobs_.clear();
[email protected]e95d3aca2010-01-11 22:47:431877
[email protected]232a5812011-03-04 22:42:081878 NetworkChangeNotifier::RemoveIPAddressObserver(this);
ttuttlecf1158bf2016-03-18 16:37:441879 NetworkChangeNotifier::RemoveConnectionTypeObserver(this);
[email protected]bb0e34542012-08-31 19:52:401880 NetworkChangeNotifier::RemoveDNSObserver(this);
[email protected]b59ff372009-07-15 22:04:321881}
1882
[email protected]0f292de02012-02-01 22:28:201883void HostResolverImpl::SetMaxQueuedJobs(size_t value) {
[email protected]106ccd2c2014-06-17 09:21:001884 DCHECK_EQ(0u, dispatcher_->num_queued_jobs());
[email protected]0f292de02012-02-01 22:28:201885 DCHECK_GT(value, 0u);
1886 max_queued_jobs_ = value;
[email protected]be1a48b2011-01-20 00:12:131887}
1888
[email protected]684970b2009-08-14 04:54:461889int HostResolverImpl::Resolve(const RequestInfo& info,
[email protected]5109c1952013-08-20 18:44:101890 RequestPriority priority,
[email protected]b59ff372009-07-15 22:04:321891 AddressList* addresses,
Bence Béky0f26a5812018-06-13 03:18:401892 CompletionOnceCallback callback,
maksim.sisov31452af2016-07-27 06:38:101893 std::unique_ptr<Request>* out_req,
tfarina428341112016-09-22 13:38:201894 const NetLogWithSource& source_net_log) {
[email protected]95a214c2011-08-04 21:50:401895 DCHECK(addresses);
gab47aa7da2017-06-02 16:09:431896 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
[email protected]aa22b242011-11-16 18:58:291897 DCHECK_EQ(false, callback.is_null());
maksim.sisov31452af2016-07-27 06:38:101898 DCHECK(out_req);
[email protected]1ac6af92010-06-03 21:00:141899
Chris Palmer9cbf4212017-07-19 01:54:551900 LogStartRequest(source_net_log, info);
pauljensen19eb73422015-04-15 23:20:061901
Matt Menke23b4bbf82017-07-20 19:11:291902 Key key;
1903 int rv = ResolveHelper(info, false, nullptr, source_net_log, addresses, &key);
[email protected]95a214c2011-08-04 21:50:401904 if (rv != ERR_DNS_CACHE_MISS) {
xunjieli26f90452014-11-10 16:23:021905 LogFinishRequest(source_net_log, info, rv);
Miriam Gershenson90d05e02017-09-28 19:29:281906 RecordTotalTime(info.is_speculative(), true, base::TimeDelta());
[email protected]95a214c2011-08-04 21:50:401907 return rv;
[email protected]38368712011-03-02 08:09:401908 }
1909
[email protected]0f292de02012-02-01 22:28:201910 // Next we need to attach our request to a "job". This job is responsible for
1911 // calling "getaddrinfo(hostname)" on a worker thread.
1912
avi9e72eb482016-12-09 21:10:541913 auto jobit = jobs_.find(key);
[email protected]0f292de02012-02-01 22:28:201914 Job* job;
1915 if (jobit == jobs_.end()) {
Eric Orth18544ae2018-06-11 22:57:161916 auto new_job =
1917 std::make_unique<Job>(weak_ptr_factory_.GetWeakPtr(), key, priority,
1918 proc_task_runner_, source_net_log, tick_clock_);
1919 job = new_job.get();
1920 new_job->Schedule(false);
[email protected]0f292de02012-02-01 22:28:201921
1922 // Check for queue overflow.
[email protected]106ccd2c2014-06-17 09:21:001923 if (dispatcher_->num_queued_jobs() > max_queued_jobs_) {
1924 Job* evicted = static_cast<Job*>(dispatcher_->EvictOldestLowest());
[email protected]0f292de02012-02-01 22:28:201925 DCHECK(evicted);
Eric Orth18544ae2018-06-11 22:57:161926 evicted->OnEvicted();
1927 if (evicted == new_job.get()) {
[email protected]0f292de02012-02-01 22:28:201928 rv = ERR_HOST_RESOLVER_QUEUE_TOO_LARGE;
xunjieli26f90452014-11-10 16:23:021929 LogFinishRequest(source_net_log, info, rv);
[email protected]0f292de02012-02-01 22:28:201930 return rv;
1931 }
[email protected]0f292de02012-02-01 22:28:201932 }
Eric Orth18544ae2018-06-11 22:57:161933 jobs_[key] = std::move(new_job);
[email protected]0f292de02012-02-01 22:28:201934 } else {
avi9e72eb482016-12-09 21:10:541935 job = jobit->second.get();
[email protected]0f292de02012-02-01 22:28:201936 }
1937
1938 // Can't complete synchronously. Create and attach request.
Bence Béky0f26a5812018-06-13 03:18:401939 auto req = std::make_unique<RequestImpl>(source_net_log, info, priority,
1940 std::move(callback), addresses, job,
1941 tick_clock_->NowTicks());
maksim.sisov31452af2016-07-27 06:38:101942 job->AddRequest(req.get());
1943 *out_req = std::move(req);
[email protected]b59ff372009-07-15 22:04:321944
[email protected]0f292de02012-02-01 22:28:201945 // Completion happens during Job::CompleteRequests().
[email protected]b59ff372009-07-15 22:04:321946 return ERR_IO_PENDING;
1947}
1948
Francois Doraya2d01ba2017-09-25 19:17:401949HostResolverImpl::HostResolverImpl(const Options& options, NetLog* net_log)
mmenke91c17162016-06-02 16:03:231950 : max_queued_jobs_(0),
1951 proc_params_(NULL, options.max_retry_attempts),
1952 net_log_(net_log),
1953 received_dns_config_(false),
1954 num_dns_failures_(0),
mgershaf9a9232017-04-13 20:19:031955 assume_ipv6_failure_on_wifi_(false),
mmenke91c17162016-06-02 16:03:231956 use_local_ipv6_(false),
1957 last_ipv6_probe_result_(true),
mmenke91c17162016-06-02 16:03:231958 additional_resolver_flags_(0),
1959 fallback_to_proctask_(true),
Brad Lassey73e67ee2018-05-31 00:11:591960 url_request_context_(nullptr),
Misha Efimovb99e7da2018-05-30 16:59:021961 tick_clock_(base::DefaultTickClock::GetInstance()),
mmenke91c17162016-06-02 16:03:231962 weak_ptr_factory_(this),
1963 probe_weak_ptr_factory_(this) {
1964 if (options.enable_caching)
1965 cache_ = HostCache::CreateDefaultCache();
1966
1967 PrioritizedDispatcher::Limits job_limits = options.GetDispatcherLimits();
1968 dispatcher_.reset(new PrioritizedDispatcher(job_limits));
1969 max_queued_jobs_ = job_limits.total_jobs * 100u;
1970
1971 DCHECK_GE(dispatcher_->num_priorities(), static_cast<size_t>(NUM_PRIORITIES));
1972
Miriam Gershensone42adb22017-10-16 16:19:381973 proc_task_runner_ = base::CreateTaskRunnerWithTraits(
Maks Orlovich5393c8682018-02-26 16:17:501974 {base::MayBlock(), priority_mode.Get(),
1975 base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN});
Miriam Gershensone42adb22017-10-16 16:19:381976
mmenke91c17162016-06-02 16:03:231977#if defined(OS_WIN)
1978 EnsureWinsockInit();
1979#endif
Fabrice de Gans-Riberi7de47372018-05-08 20:23:471980#if (defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)) || \
1981 defined(OS_FUCHSIA)
mmenke91c17162016-06-02 16:03:231982 RunLoopbackProbeJob();
1983#endif
1984 NetworkChangeNotifier::AddIPAddressObserver(this);
1985 NetworkChangeNotifier::AddConnectionTypeObserver(this);
1986 NetworkChangeNotifier::AddDNSObserver(this);
1987#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD) && \
Fabrice de Gans-Riberi65421f62018-05-22 23:16:181988 !defined(OS_ANDROID)
mmenke91c17162016-06-02 16:03:231989 EnsureDnsReloaderInit();
1990#endif
1991
1992 OnConnectionTypeChanged(NetworkChangeNotifier::GetConnectionType());
1993
1994 {
1995 DnsConfig dns_config;
1996 NetworkChangeNotifier::GetDnsConfig(&dns_config);
1997 received_dns_config_ = dns_config.IsValid();
1998 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
1999 use_local_ipv6_ = !dns_config.IsValid() || dns_config.use_local_ipv6;
2000 }
2001
2002 fallback_to_proctask_ = !ConfigureAsyncDnsNoFallbackFieldTrial();
2003}
2004
2005void HostResolverImpl::SetHaveOnlyLoopbackAddresses(bool result) {
2006 if (result) {
2007 additional_resolver_flags_ |= HOST_RESOLVER_LOOPBACK_ONLY;
2008 } else {
2009 additional_resolver_flags_ &= ~HOST_RESOLVER_LOOPBACK_ONLY;
2010 }
2011}
2012
Miriam Gershensone42adb22017-10-16 16:19:382013void HostResolverImpl::SetTaskRunnerForTesting(
2014 scoped_refptr<base::TaskRunner> task_runner) {
2015 proc_task_runner_ = std::move(task_runner);
2016}
2017
Matt Menke23b4bbf82017-07-20 19:11:292018int HostResolverImpl::ResolveHelper(const RequestInfo& info,
juliatuttle9fb7aeb2016-06-06 20:16:332019 bool allow_stale,
2020 HostCache::EntryStaleness* stale_info,
Matt Menke23b4bbf82017-07-20 19:11:292021 const NetLogWithSource& source_net_log,
2022 AddressList* addresses,
2023 Key* key) {
2024 IPAddress ip_address;
2025 IPAddress* ip_address_ptr = nullptr;
2026 if (ip_address.AssignFromIPLiteral(info.hostname())) {
2027 ip_address_ptr = &ip_address;
2028 } else {
2029 // Check that the caller supplied a valid hostname to resolve.
2030 if (!IsValidDNSDomain(info.hostname()))
2031 return ERR_NAME_NOT_RESOLVED;
2032 }
2033
2034 // Build a key that identifies the request in the cache and in the
2035 // outstanding jobs map.
2036 *key = GetEffectiveKeyForRequest(info, ip_address_ptr, source_net_log);
2037
juliatuttle9fb7aeb2016-06-06 20:16:332038 DCHECK(allow_stale == !!stale_info);
[email protected]95a214c2011-08-04 21:50:402039 // The result of |getaddrinfo| for empty hosts is inconsistent across systems.
2040 // On Windows it gives the default interface's address, whereas on Linux it
2041 // gives an error. We will make it fail on all platforms for consistency.
juliatuttle9fb7aeb2016-06-06 20:16:332042 if (info.hostname().empty() || info.hostname().size() > kMaxHostLength) {
2043 MakeNotStale(stale_info);
[email protected]95a214c2011-08-04 21:50:402044 return ERR_NAME_NOT_RESOLVED;
juliatuttle9fb7aeb2016-06-06 20:16:332045 }
[email protected]95a214c2011-08-04 21:50:402046
2047 int net_error = ERR_UNEXPECTED;
Matt Menke23b4bbf82017-07-20 19:11:292048 if (ResolveAsIP(*key, info, ip_address_ptr, &net_error, addresses)) {
juliatuttle9fb7aeb2016-06-06 20:16:332049 MakeNotStale(stale_info);
[email protected]95a214c2011-08-04 21:50:402050 return net_error;
juliatuttle9fb7aeb2016-06-06 20:16:332051 }
Mike Westda1c690e2017-08-12 05:57:162052
2053 // Special-case localhost names, as per the recommendations in
2054 // https://tools.ietf.org/html/draft-west-let-localhost-be-localhost.
2055 if (ServeLocalhost(*key, info, addresses)) {
2056 MakeNotStale(stale_info);
2057 return OK;
2058 }
2059
Matt Menke23b4bbf82017-07-20 19:11:292060 if (ServeFromCache(*key, info, &net_error, addresses, allow_stale,
juliatuttle9fb7aeb2016-06-06 20:16:332061 stale_info)) {
mgersh33d23c02017-03-29 20:24:252062 source_net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_CACHE_HIT,
2063 addresses->CreateNetLogCallback());
juliatuttle9fb7aeb2016-06-06 20:16:332064 // |ServeFromCache()| will set |*stale_info| as needed.
[email protected]78eac2a2012-03-14 19:09:272065 return net_error;
2066 }
Mike Westda1c690e2017-08-12 05:57:162067
[email protected]78eac2a2012-03-14 19:09:272068 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2069 // http://crbug.com/117655
Matt Menke23b4bbf82017-07-20 19:11:292070 if (ServeFromHosts(*key, info, addresses)) {
mgersh33d23c02017-03-29 20:24:252071 source_net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_HOSTS_HIT,
2072 addresses->CreateNetLogCallback());
juliatuttle9fb7aeb2016-06-06 20:16:332073 MakeNotStale(stale_info);
[email protected]78eac2a2012-03-14 19:09:272074 return OK;
2075 }
estarkd1bc206e2015-06-20 00:44:392076
[email protected]78eac2a2012-03-14 19:09:272077 return ERR_DNS_CACHE_MISS;
[email protected]95a214c2011-08-04 21:50:402078}
2079
2080int HostResolverImpl::ResolveFromCache(const RequestInfo& info,
2081 AddressList* addresses,
tfarina428341112016-09-22 13:38:202082 const NetLogWithSource& source_net_log) {
gab47aa7da2017-06-02 16:09:432083 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
[email protected]95a214c2011-08-04 21:50:402084 DCHECK(addresses);
2085
[email protected]95a214c2011-08-04 21:50:402086 // Update the net log and notify registered observers.
xunjieli26f90452014-11-10 16:23:022087 LogStartRequest(source_net_log, info);
[email protected]95a214c2011-08-04 21:50:402088
Matt Menke23b4bbf82017-07-20 19:11:292089 Key key;
2090 int rv = ResolveHelper(info, false, nullptr, source_net_log, addresses, &key);
[email protected]95a214c2011-08-04 21:50:402091
xunjieli26f90452014-11-10 16:23:022092 LogFinishRequest(source_net_log, info, rv);
[email protected]95a214c2011-08-04 21:50:402093 return rv;
2094}
2095
[email protected]a8883e452012-11-17 05:58:062096void HostResolverImpl::SetDnsClientEnabled(bool enabled) {
gab47aa7da2017-06-02 16:09:432097 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
[email protected]a8883e452012-11-17 05:58:062098#if defined(ENABLE_BUILT_IN_DNS)
2099 if (enabled && !dns_client_) {
2100 SetDnsClient(DnsClient::CreateClient(net_log_));
2101 } else if (!enabled && dns_client_) {
danakj22f90e72016-04-16 01:55:402102 SetDnsClient(std::unique_ptr<DnsClient>());
[email protected]a8883e452012-11-17 05:58:062103 }
2104#endif
2105}
2106
[email protected]489d1a82011-10-12 03:09:112107HostCache* HostResolverImpl::GetHostCache() {
2108 return cache_.get();
2109}
[email protected]95a214c2011-08-04 21:50:402110
Rob Percivalbc658a22017-12-13 08:24:422111bool HostResolverImpl::HasCached(base::StringPiece hostname,
2112 HostCache::Entry::Source* source_out,
2113 HostCache::EntryStaleness* stale_out) const {
2114 if (!cache_)
2115 return false;
2116
2117 return cache_->HasEntry(hostname, source_out, stale_out);
2118}
2119
danakj22f90e72016-04-16 01:55:402120std::unique_ptr<base::Value> HostResolverImpl::GetDnsConfigAsValue() const {
[email protected]17e92032012-03-29 00:56:242121 // Check if async DNS is disabled.
2122 if (!dns_client_.get())
tfhef3618f2016-01-11 23:07:082123 return nullptr;
[email protected]17e92032012-03-29 00:56:242124
2125 // Check if async DNS is enabled, but we currently have no configuration
2126 // for it.
2127 const DnsConfig* dns_config = dns_client_->GetConfig();
wezb9820d42016-06-22 23:41:042128 if (!dns_config)
Jeremy Roman0579ed62017-08-29 15:56:192129 return std::make_unique<base::DictionaryValue>();
[email protected]17e92032012-03-29 00:56:242130
2131 return dns_config->ToValue();
2132}
2133
juliatuttle9fb7aeb2016-06-06 20:16:332134int HostResolverImpl::ResolveStaleFromCache(
2135 const RequestInfo& info,
2136 AddressList* addresses,
2137 HostCache::EntryStaleness* stale_info,
tfarina428341112016-09-22 13:38:202138 const NetLogWithSource& source_net_log) {
gab47aa7da2017-06-02 16:09:432139 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
juliatuttle9fb7aeb2016-06-06 20:16:332140 DCHECK(addresses);
2141 DCHECK(stale_info);
2142
2143 // Update the net log and notify registered observers.
2144 LogStartRequest(source_net_log, info);
2145
Matt Menke23b4bbf82017-07-20 19:11:292146 Key key;
2147 int rv =
2148 ResolveHelper(info, true, stale_info, source_net_log, addresses, &key);
juliatuttle9fb7aeb2016-06-06 20:16:332149 LogFinishRequest(source_net_log, info, rv);
2150 return rv;
2151}
2152
Miriam Gershenson2839ef112017-08-30 03:25:372153size_t HostResolverImpl::LastRestoredCacheSize() const {
2154 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
2155
2156 return cache_ ? cache_->last_restore_size() : 0;
2157}
2158
2159size_t HostResolverImpl::CacheSize() const {
2160 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
2161
2162 return cache_ ? cache_->size() : 0;
2163}
2164
mgershaf9a9232017-04-13 20:19:032165void HostResolverImpl::SetNoIPv6OnWifi(bool no_ipv6_on_wifi) {
gab47aa7da2017-06-02 16:09:432166 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
mgershaf9a9232017-04-13 20:19:032167 assume_ipv6_failure_on_wifi_ = no_ipv6_on_wifi;
2168}
2169
2170bool HostResolverImpl::GetNoIPv6OnWifi() {
2171 return assume_ipv6_failure_on_wifi_;
2172}
2173
Brad Lassey786929ad2018-02-21 20:54:272174void HostResolverImpl::SetRequestContext(URLRequestContext* context) {
2175 if (context != url_request_context_) {
2176 url_request_context_ = context;
2177 }
2178}
2179
Misha Efimovb99e7da2018-05-30 16:59:022180void HostResolverImpl::SetTickClockForTesting(
2181 const base::TickClock* tick_clock) {
2182 tick_clock_ = tick_clock;
2183 cache_->set_tick_clock_for_testing(tick_clock);
2184}
2185
Brad Lassey786929ad2018-02-21 20:54:272186void HostResolverImpl::ClearDnsOverHttpsServers() {
2187 if (dns_over_https_servers_.size() == 0)
2188 return;
2189
2190 dns_over_https_servers_.clear();
2191
2192 if (dns_client_.get() && dns_client_->GetConfig())
2193 UpdateDNSConfig(true);
2194}
2195
2196void HostResolverImpl::AddDnsOverHttpsServer(std::string spec, bool use_post) {
2197 GURL url(spec);
2198 if (!url.SchemeIs("https"))
2199 return;
2200
2201 dns_over_https_servers_.emplace_back(url, use_post);
2202
2203 if (dns_client_.get() && dns_client_->GetConfig())
2204 UpdateDNSConfig(true);
2205}
2206
Matt Menkeb67c0a8e2018-06-14 22:41:042207const std::vector<DnsConfig::DnsOverHttpsServerConfig>*
2208HostResolverImpl::GetDnsOverHttpsServersForTesting() const {
2209 if (dns_over_https_servers_.empty())
2210 return nullptr;
2211 return &dns_over_https_servers_;
2212}
2213
[email protected]95a214c2011-08-04 21:50:402214bool HostResolverImpl::ResolveAsIP(const Key& key,
2215 const RequestInfo& info,
martijna23c8962016-03-04 18:18:512216 const IPAddress* ip_address,
[email protected]95a214c2011-08-04 21:50:402217 int* net_error,
2218 AddressList* addresses) {
2219 DCHECK(addresses);
2220 DCHECK(net_error);
martijna23c8962016-03-04 18:18:512221 if (ip_address == nullptr)
[email protected]95a214c2011-08-04 21:50:402222 return false;
2223
[email protected]95a214c2011-08-04 21:50:402224 *net_error = OK;
martijna23c8962016-03-04 18:18:512225 AddressFamily family = GetAddressFamily(*ip_address);
cbentzel1906f872015-06-05 16:25:252226 if (key.address_family != ADDRESS_FAMILY_UNSPECIFIED &&
2227 key.address_family != family) {
[email protected]1c7cf3f82014-08-07 21:33:482228 // Don't return IPv6 addresses for IPv4 queries, and vice versa.
[email protected]95a214c2011-08-04 21:50:402229 *net_error = ERR_NAME_NOT_RESOLVED;
2230 } else {
martijna23c8962016-03-04 18:18:512231 *addresses = AddressList::CreateFromIPAddress(*ip_address, info.port());
[email protected]7054e78f2012-05-07 21:44:562232 if (key.host_resolver_flags & HOST_RESOLVER_CANONNAME)
2233 addresses->SetDefaultCanonicalName();
[email protected]95a214c2011-08-04 21:50:402234 }
2235 return true;
2236}
2237
2238bool HostResolverImpl::ServeFromCache(const Key& key,
2239 const RequestInfo& info,
[email protected]95a214c2011-08-04 21:50:402240 int* net_error,
juliatuttle9fb7aeb2016-06-06 20:16:332241 AddressList* addresses,
2242 bool allow_stale,
2243 HostCache::EntryStaleness* stale_info) {
[email protected]95a214c2011-08-04 21:50:402244 DCHECK(addresses);
2245 DCHECK(net_error);
juliatuttle9fb7aeb2016-06-06 20:16:332246 DCHECK(allow_stale == !!stale_info);
[email protected]95a214c2011-08-04 21:50:402247 if (!info.allow_cached_response() || !cache_.get())
2248 return false;
2249
juliatuttle9fb7aeb2016-06-06 20:16:332250 const HostCache::Entry* cache_entry;
2251 if (allow_stale)
Misha Efimovb99e7da2018-05-30 16:59:022252 cache_entry = cache_->LookupStale(key, tick_clock_->NowTicks(), stale_info);
juliatuttle9fb7aeb2016-06-06 20:16:332253 else
Misha Efimovb99e7da2018-05-30 16:59:022254 cache_entry = cache_->Lookup(key, tick_clock_->NowTicks());
[email protected]95a214c2011-08-04 21:50:402255 if (!cache_entry)
2256 return false;
2257
juliatuttle317860e2016-05-12 14:47:222258 *net_error = cache_entry->error();
[email protected]7054e78f2012-05-07 21:44:562259 if (*net_error == OK) {
[email protected]1339a2a22012-10-17 08:39:432260 if (cache_entry->has_ttl())
juliatuttle317860e2016-05-12 14:47:222261 RecordTTL(cache_entry->ttl());
2262 *addresses = EnsurePortOnAddressList(cache_entry->addresses(), info.port());
[email protected]7054e78f2012-05-07 21:44:562263 }
[email protected]95a214c2011-08-04 21:50:402264 return true;
2265}
2266
[email protected]78eac2a2012-03-14 19:09:272267bool HostResolverImpl::ServeFromHosts(const Key& key,
2268 const RequestInfo& info,
2269 AddressList* addresses) {
2270 DCHECK(addresses);
2271 if (!HaveDnsConfig())
2272 return false;
[email protected]05a79d42013-03-28 07:30:092273 addresses->clear();
2274
[email protected]cb507622012-03-23 16:17:062275 // HOSTS lookups are case-insensitive.
brettw8e2106d2015-08-11 19:30:222276 std::string hostname = base::ToLowerASCII(key.hostname);
[email protected]cb507622012-03-23 16:17:062277
[email protected]05a79d42013-03-28 07:30:092278 const DnsHosts& hosts = dns_client_->GetConfig()->hosts;
2279
[email protected]78eac2a2012-03-14 19:09:272280 // If |address_family| is ADDRESS_FAMILY_UNSPECIFIED other implementations
2281 // (glibc and c-ares) return the first matching line. We have more
2282 // flexibility, but lose implicit ordering.
[email protected]05a79d42013-03-28 07:30:092283 // We prefer IPv6 because "happy eyeballs" will fall back to IPv4 if
2284 // necessary.
2285 if (key.address_family == ADDRESS_FAMILY_IPV6 ||
2286 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
2287 DnsHosts::const_iterator it = hosts.find(
2288 DnsHostsKey(hostname, ADDRESS_FAMILY_IPV6));
2289 if (it != hosts.end())
2290 addresses->push_back(IPEndPoint(it->second, info.port()));
[email protected]78eac2a2012-03-14 19:09:272291 }
2292
[email protected]05a79d42013-03-28 07:30:092293 if (key.address_family == ADDRESS_FAMILY_IPV4 ||
2294 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
2295 DnsHosts::const_iterator it = hosts.find(
2296 DnsHostsKey(hostname, ADDRESS_FAMILY_IPV4));
2297 if (it != hosts.end())
2298 addresses->push_back(IPEndPoint(it->second, info.port()));
2299 }
2300
[email protected]ec666ab22013-04-17 20:05:592301 // If got only loopback addresses and the family was restricted, resolve
2302 // again, without restrictions. See SystemHostResolverCall for rationale.
2303 if ((key.host_resolver_flags &
2304 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6) &&
2305 IsAllIPv4Loopback(*addresses)) {
2306 Key new_key(key);
2307 new_key.address_family = ADDRESS_FAMILY_UNSPECIFIED;
2308 new_key.host_resolver_flags &=
2309 ~HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
2310 return ServeFromHosts(new_key, info, addresses);
2311 }
[email protected]05a79d42013-03-28 07:30:092312 return !addresses->empty();
[email protected]78eac2a2012-03-14 19:09:272313}
2314
estarkd1bc206e2015-06-20 00:44:392315bool HostResolverImpl::ServeLocalhost(const Key& key,
2316 const RequestInfo& info,
2317 AddressList* addresses) {
2318 AddressList resolved_addresses;
2319 if (!ResolveLocalHostname(key.hostname, info.port(), &resolved_addresses))
2320 return false;
2321
2322 addresses->clear();
2323
2324 for (const auto& address : resolved_addresses) {
2325 // Include the address if:
2326 // - caller didn't specify an address family, or
2327 // - caller specifically asked for the address family of this address, or
2328 // - this is an IPv6 address and caller specifically asked for IPv4 due
2329 // to lack of detected IPv6 support. (See SystemHostResolverCall for
2330 // rationale).
2331 if (key.address_family == ADDRESS_FAMILY_UNSPECIFIED ||
2332 key.address_family == address.GetFamily() ||
2333 (address.GetFamily() == ADDRESS_FAMILY_IPV6 &&
2334 key.address_family == ADDRESS_FAMILY_IPV4 &&
2335 (key.host_resolver_flags &
2336 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6))) {
2337 addresses->push_back(address);
2338 }
2339 }
2340
2341 return true;
2342}
2343
[email protected]16ee26d2012-03-08 03:34:352344void HostResolverImpl::CacheResult(const Key& key,
[email protected]1339a2a22012-10-17 08:39:432345 const HostCache::Entry& entry,
[email protected]16ee26d2012-03-08 03:34:352346 base::TimeDelta ttl) {
Miriam Gershensone3bc63022017-10-09 19:57:052347 // Don't cache an error unless it has a positive TTL.
2348 if (cache_.get() && (entry.error() == OK || ttl > base::TimeDelta()))
Misha Efimovb99e7da2018-05-30 16:59:022349 cache_->Set(key, entry, tick_clock_->NowTicks(), ttl);
[email protected]ef4c40c2010-09-01 14:42:032350}
2351
Eric Orth18544ae2018-06-11 22:57:162352std::unique_ptr<HostResolverImpl::Job> HostResolverImpl::RemoveJob(Job* job) {
[email protected]0f292de02012-02-01 22:28:202353 DCHECK(job);
Eric Orth18544ae2018-06-11 22:57:162354 std::unique_ptr<Job> retval;
avi9e72eb482016-12-09 21:10:542355 auto it = jobs_.find(job->key());
2356 if (it != jobs_.end() && it->second.get() == job) {
Eric Orth18544ae2018-06-11 22:57:162357 it->second.swap(retval);
[email protected]16ee26d2012-03-08 03:34:352358 jobs_.erase(it);
avi9e72eb482016-12-09 21:10:542359 }
Eric Orth18544ae2018-06-11 22:57:162360 return retval;
[email protected]b59ff372009-07-15 22:04:322361}
2362
[email protected]137af622010-02-05 02:14:352363HostResolverImpl::Key HostResolverImpl::GetEffectiveKeyForRequest(
pauljensen19eb73422015-04-15 23:20:062364 const RequestInfo& info,
martijna23c8962016-03-04 18:18:512365 const IPAddress* ip_address,
tfarina428341112016-09-22 13:38:202366 const NetLogWithSource& net_log) {
[email protected]eaf3a3b2010-09-03 20:34:272367 HostResolverFlags effective_flags =
2368 info.host_resolver_flags() | additional_resolver_flags_;
[email protected]137af622010-02-05 02:14:352369 AddressFamily effective_address_family = info.address_family();
[email protected]9db6f702013-04-10 18:10:512370
mgersh3eba057d2017-02-28 18:50:562371 if (effective_address_family == ADDRESS_FAMILY_UNSPECIFIED &&
2372 // When resolving IPv4 literals, there's no need to probe for IPv6.
2373 // When resolving IPv6 literals, there's no benefit to artificially
2374 // limiting our resolution based on a probe. Prior logic ensures
2375 // that this query is UNSPECIFIED (see effective_address_family
2376 // check above) so the code requesting the resolution should be amenable
2377 // to receiving a IPv6 resolution.
2378 !use_local_ipv6_ && ip_address == nullptr && !IsIPv6Reachable(net_log)) {
2379 effective_address_family = ADDRESS_FAMILY_IPV4;
2380 effective_flags |= HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
[email protected]9db6f702013-04-10 18:10:512381 }
2382
estarkd1bc206e2015-06-20 00:44:392383 return Key(info.hostname(), effective_address_family, effective_flags);
[email protected]137af622010-02-05 02:14:352384}
2385
tfarina428341112016-09-22 13:38:202386bool HostResolverImpl::IsIPv6Reachable(const NetLogWithSource& net_log) {
mgershaf9a9232017-04-13 20:19:032387 // Don't bother checking if the device is on WiFi and IPv6 is assumed to not
2388 // work on WiFi.
2389 if (assume_ipv6_failure_on_wifi_ &&
2390 NetworkChangeNotifier::GetConnectionType() ==
2391 NetworkChangeNotifier::CONNECTION_WIFI) {
2392 return false;
2393 }
2394
eroman1a17ef32016-12-14 01:06:092395 // Cache the result for kIPv6ProbePeriodMs (measured from after
2396 // IsGloballyReachable() completes).
sergeyub8cdc212015-05-14 18:50:372397 bool cached = true;
Misha Efimovb99e7da2018-05-30 16:59:022398 if ((tick_clock_->NowTicks() - last_ipv6_probe_time_).InMilliseconds() >
eroman1a17ef32016-12-14 01:06:092399 kIPv6ProbePeriodMs) {
martijna23c8962016-03-04 18:18:512400 last_ipv6_probe_result_ =
2401 IsGloballyReachable(IPAddress(kIPv6ProbeAddress), net_log);
Misha Efimovb99e7da2018-05-30 16:59:022402 last_ipv6_probe_time_ = tick_clock_->NowTicks();
sergeyub8cdc212015-05-14 18:50:372403 cached = false;
2404 }
mikecirone8b85c432016-09-08 19:11:002405 net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_IPV6_REACHABILITY_CHECK,
sergeyub8cdc212015-05-14 18:50:372406 base::Bind(&NetLogIPv6AvailableCallback,
2407 last_ipv6_probe_result_, cached));
2408 return last_ipv6_probe_result_;
2409}
2410
mgershaf9a9232017-04-13 20:19:032411bool HostResolverImpl::IsGloballyReachable(const IPAddress& dest,
2412 const NetLogWithSource& net_log) {
mgershaf9a9232017-04-13 20:19:032413 std::unique_ptr<DatagramClientSocket> socket(
2414 ClientSocketFactory::GetDefaultFactory()->CreateDatagramClientSocket(
Sergey Ulanovcbdfc8852018-03-16 20:13:282415 DatagramSocket::DEFAULT_BIND, net_log.net_log(), net_log.source()));
mgershaf9a9232017-04-13 20:19:032416 int rv = socket->Connect(IPEndPoint(dest, 53));
2417 if (rv != OK)
2418 return false;
2419 IPEndPoint endpoint;
2420 rv = socket->GetLocalAddress(&endpoint);
2421 if (rv != OK)
2422 return false;
2423 DCHECK_EQ(ADDRESS_FAMILY_IPV6, endpoint.GetFamily());
2424 const IPAddress& address = endpoint.address();
2425
2426 bool is_link_local =
2427 (address.bytes()[0] == 0xFE) && ((address.bytes()[1] & 0xC0) == 0x80);
2428 if (is_link_local)
2429 return false;
2430
2431 const uint8_t kTeredoPrefix[] = {0x20, 0x01, 0, 0};
2432 if (IPAddressStartsWith(address, kTeredoPrefix))
2433 return false;
2434
2435 return true;
2436}
2437
mmenke91c17162016-06-02 16:03:232438void HostResolverImpl::RunLoopbackProbeJob() {
Francois Doraya2d01ba2017-09-25 19:17:402439 // Run this asynchronously as it can take 40-100ms and should not block
2440 // initialization.
2441 base::PostTaskWithTraitsAndReplyWithResult(
2442 FROM_HERE,
2443 {base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
2444 base::BindOnce(&HaveOnlyLoopbackAddresses),
2445 base::BindOnce(&HostResolverImpl::SetHaveOnlyLoopbackAddresses,
2446 weak_ptr_factory_.GetWeakPtr()));
mmenke91c17162016-06-02 16:03:232447}
2448
[email protected]35ddc282010-09-21 23:42:062449void HostResolverImpl::AbortAllInProgressJobs() {
[email protected]b3601bc22012-02-21 21:23:202450 // In Abort, a Request callback could spawn new Jobs with matching keys, so
2451 // first collect and remove all running jobs from |jobs_|.
danakj22f90e72016-04-16 01:55:402452 std::vector<std::unique_ptr<Job>> jobs_to_abort;
avi9e72eb482016-12-09 21:10:542453 for (auto it = jobs_.begin(); it != jobs_.end();) {
2454 Job* job = it->second.get();
[email protected]0f292de02012-02-01 22:28:202455 if (job->is_running()) {
avi9e72eb482016-12-09 21:10:542456 jobs_to_abort.push_back(std::move(it->second));
[email protected]b3601bc22012-02-21 21:23:202457 jobs_.erase(it++);
[email protected]0f292de02012-02-01 22:28:202458 } else {
[email protected]b3601bc22012-02-21 21:23:202459 DCHECK(job->is_queued());
2460 ++it;
[email protected]0f292de02012-02-01 22:28:202461 }
[email protected]ef4c40c2010-09-01 14:42:032462 }
[email protected]b3601bc22012-02-21 21:23:202463
[email protected]daae1322013-09-05 18:26:502464 // Pause the dispatcher so it won't start any new dispatcher jobs while
2465 // aborting the old ones. This is needed so that it won't start the second
2466 // DnsTransaction for a job in |jobs_to_abort| if the DnsConfig just became
2467 // invalid.
[email protected]106ccd2c2014-06-17 09:21:002468 PrioritizedDispatcher::Limits limits = dispatcher_->GetLimits();
2469 dispatcher_->SetLimits(
[email protected]daae1322013-09-05 18:26:502470 PrioritizedDispatcher::Limits(limits.reserved_slots.size(), 0));
[email protected]70c04ab2013-08-22 16:05:122471
[email protected]57a48d32012-03-03 00:04:552472 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072473 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]57a48d32012-03-03 00:04:552474
[email protected]16ee26d2012-03-08 03:34:352475 // Then Abort them.
[email protected]11fbca0b2013-06-02 23:37:212476 for (size_t i = 0; self.get() && i < jobs_to_abort.size(); ++i) {
[email protected]57a48d32012-03-03 00:04:552477 jobs_to_abort[i]->Abort();
[email protected]b3601bc22012-02-21 21:23:202478 }
[email protected]daae1322013-09-05 18:26:502479
2480 if (self)
[email protected]106ccd2c2014-06-17 09:21:002481 dispatcher_->SetLimits(limits);
[email protected]daae1322013-09-05 18:26:502482}
2483
2484void HostResolverImpl::AbortDnsTasks() {
2485 // Pause the dispatcher so it won't start any new dispatcher jobs while
2486 // aborting the old ones. This is needed so that it won't start the second
2487 // DnsTransaction for a job if the DnsConfig just changed.
[email protected]106ccd2c2014-06-17 09:21:002488 PrioritizedDispatcher::Limits limits = dispatcher_->GetLimits();
2489 dispatcher_->SetLimits(
[email protected]daae1322013-09-05 18:26:502490 PrioritizedDispatcher::Limits(limits.reserved_slots.size(), 0));
2491
avi9e72eb482016-12-09 21:10:542492 for (auto it = jobs_.begin(); it != jobs_.end(); ++it)
[email protected]daae1322013-09-05 18:26:502493 it->second->AbortDnsTask();
[email protected]106ccd2c2014-06-17 09:21:002494 dispatcher_->SetLimits(limits);
[email protected]ef4c40c2010-09-01 14:42:032495}
2496
[email protected]78eac2a2012-03-14 19:09:272497void HostResolverImpl::TryServingAllJobsFromHosts() {
2498 if (!HaveDnsConfig())
2499 return;
2500
2501 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2502 // http://crbug.com/117655
2503
2504 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072505 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]78eac2a2012-03-14 19:09:272506
avi9e72eb482016-12-09 21:10:542507 for (auto it = jobs_.begin(); self.get() && it != jobs_.end();) {
2508 Job* job = it->second.get();
[email protected]78eac2a2012-03-14 19:09:272509 ++it;
2510 // This could remove |job| from |jobs_|, but iterator will remain valid.
2511 job->ServeFromHosts();
2512 }
2513}
2514
[email protected]be1a48b2011-01-20 00:12:132515void HostResolverImpl::OnIPAddressChanged() {
sergeyub8cdc212015-05-14 18:50:372516 last_ipv6_probe_time_ = base::TimeTicks();
[email protected]12faa4c2012-11-06 04:44:182517 // Abandon all ProbeJobs.
2518 probe_weak_ptr_factory_.InvalidateWeakPtrs();
Matt Menkeef8f5cf82017-07-20 22:50:172519 if (cache_.get())
mgersh5bb3b9d2017-02-13 21:27:102520 cache_->OnNetworkChange();
Fabrice de Gans-Riberi7de47372018-05-08 20:23:472521#if (defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)) || \
2522 defined(OS_FUCHSIA)
mmenke91c17162016-06-02 16:03:232523 RunLoopbackProbeJob();
[email protected]be1a48b2011-01-20 00:12:132524#endif
2525 AbortAllInProgressJobs();
2526 // |this| may be deleted inside AbortAllInProgressJobs().
2527}
2528
ttuttlecf1158bf2016-03-18 16:37:442529void HostResolverImpl::OnConnectionTypeChanged(
2530 NetworkChangeNotifier::ConnectionType type) {
2531 proc_params_.unresponsive_delay =
2532 GetTimeDeltaForConnectionTypeFromFieldTrialOrDefault(
2533 "DnsUnresponsiveDelayMsByConnectionType",
2534 base::TimeDelta::FromMilliseconds(kDnsDefaultUnresponsiveDelayMs),
2535 type);
2536}
2537
pauljensen101ed372015-04-17 00:11:422538void HostResolverImpl::OnInitialDNSConfigRead() {
2539 UpdateDNSConfig(false);
2540}
2541
[email protected]bb0e34542012-08-31 19:52:402542void HostResolverImpl::OnDNSChanged() {
pauljensen101ed372015-04-17 00:11:422543 UpdateDNSConfig(true);
2544}
2545
2546void HostResolverImpl::UpdateDNSConfig(bool config_changed) {
[email protected]bb0e34542012-08-31 19:52:402547 DnsConfig dns_config;
2548 NetworkChangeNotifier::GetDnsConfig(&dns_config);
[email protected]ec666ab22013-04-17 20:05:592549
[email protected]b4481b222012-03-16 17:13:112550 if (net_log_) {
mikecirone8b85c432016-09-08 19:11:002551 net_log_->AddGlobalEntry(NetLogEventType::DNS_CONFIG_CHANGED,
2552 base::Bind(&NetLogDnsConfigCallback, &dns_config));
[email protected]b4481b222012-03-16 17:13:112553 }
2554
[email protected]01b3b9d2012-08-13 16:18:142555 // TODO(szym): Remove once http://crbug.com/137914 is resolved.
[email protected]d7b9a2b2012-05-31 22:31:192556 received_dns_config_ = dns_config.IsValid();
[email protected]c9fa8f312013-09-17 12:24:522557 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
2558 use_local_ipv6_ = !dns_config.IsValid() || dns_config.use_local_ipv6;
[email protected]78eac2a2012-03-14 19:09:272559
[email protected]a8883e452012-11-17 05:58:062560 num_dns_failures_ = 0;
2561
[email protected]01b3b9d2012-08-13 16:18:142562 // We want a new DnsSession in place, before we Abort running Jobs, so that
2563 // the newly started jobs use the new config.
[email protected]f0f602bd2012-11-15 18:01:022564 if (dns_client_.get()) {
Miriam Gershenson44aafc122017-10-18 19:29:252565 // Make sure that if the update is an initial read, not a change, there
Miriam Gershenson668e8442017-10-31 20:31:532566 // wasn't already a DnsConfig or it's the same one.
2567 DCHECK(config_changed || !dns_client_->GetConfig() ||
2568 dns_client_->GetConfig()->Equals(dns_config));
Brad Lassey786929ad2018-02-21 20:54:272569 dns_config.dns_over_https_servers = dns_over_https_servers_;
[email protected]d7b9a2b2012-05-31 22:31:192570 dns_client_->SetConfig(dns_config);
Miriam Gershenson44aafc122017-10-18 19:29:252571 if (dns_client_->GetConfig())
[email protected]f0f602bd2012-11-15 18:01:022572 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
[email protected]f0f602bd2012-11-15 18:01:022573 }
[email protected]01b3b9d2012-08-13 16:18:142574
pauljensen101ed372015-04-17 00:11:422575 if (config_changed) {
2576 // If the DNS server has changed, existing cached info could be wrong so we
mgersh92b1af12017-03-29 15:49:232577 // have to expire our internal cache :( Note that OS level DNS caches, such
pauljensen101ed372015-04-17 00:11:422578 // as NSCD's cache should be dropped automatically by the OS when
2579 // resolv.conf changes so we don't need to do anything to clear that cache.
Matt Menkeef8f5cf82017-07-20 22:50:172580 if (cache_.get())
mgersh92b1af12017-03-29 15:49:232581 cache_->OnNetworkChange();
[email protected]01b3b9d2012-08-13 16:18:142582
pauljensen101ed372015-04-17 00:11:422583 // Life check to bail once |this| is deleted.
2584 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]f0f602bd2012-11-15 18:01:022585
pauljensen101ed372015-04-17 00:11:422586 // Existing jobs will have been sent to the original server so they need to
2587 // be aborted.
2588 AbortAllInProgressJobs();
[email protected]01b3b9d2012-08-13 16:18:142589
pauljensen101ed372015-04-17 00:11:422590 // |this| may be deleted inside AbortAllInProgressJobs().
2591 if (self.get())
2592 TryServingAllJobsFromHosts();
2593 }
[email protected]78eac2a2012-03-14 19:09:272594}
2595
2596bool HostResolverImpl::HaveDnsConfig() const {
[email protected]32b1dbcf2013-01-26 03:48:252597 // Use DnsClient only if it's fully configured and there is no override by
2598 // ScopedDefaultHostResolverProc.
2599 // The alternative is to use NetworkChangeNotifier to override DnsConfig,
2600 // but that would introduce construction order requirements for NCN and SDHRP.
wezb9820d42016-06-22 23:41:042601 return dns_client_ && dns_client_->GetConfig() &&
2602 (proc_params_.resolver_proc || !HostResolverProc::GetDefault());
[email protected]b3601bc22012-02-21 21:23:202603}
2604
[email protected]1ffdda82012-12-12 23:04:222605void HostResolverImpl::OnDnsTaskResolve(int net_error) {
[email protected]f0f602bd2012-11-15 18:01:022606 DCHECK(dns_client_);
[email protected]1ffdda82012-12-12 23:04:222607 if (net_error == OK) {
[email protected]f0f602bd2012-11-15 18:01:022608 num_dns_failures_ = 0;
2609 return;
2610 }
2611 ++num_dns_failures_;
2612 if (num_dns_failures_ < kMaximumDnsFailures)
2613 return;
[email protected]daae1322013-09-05 18:26:502614
2615 // Disable DnsClient until the next DNS change. Must be done before aborting
2616 // DnsTasks, since doing so may start new jobs.
[email protected]f0f602bd2012-11-15 18:01:022617 dns_client_->SetConfig(DnsConfig());
[email protected]daae1322013-09-05 18:26:502618
2619 // Switch jobs with active DnsTasks over to using ProcTasks.
2620 AbortDnsTasks();
2621
[email protected]f0f602bd2012-11-15 18:01:022622 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", false);
Ilya Sherman0eb39802017-12-08 20:58:182623 base::UmaHistogramSparse("AsyncDNS.DnsClientDisabledReason",
2624 std::abs(net_error));
[email protected]f0f602bd2012-11-15 18:01:022625}
2626
danakj22f90e72016-04-16 01:55:402627void HostResolverImpl::SetDnsClient(std::unique_ptr<DnsClient> dns_client) {
[email protected]daae1322013-09-05 18:26:502628 // DnsClient and config must be updated before aborting DnsTasks, since doing
2629 // so may start new jobs.
dchengc7eeda422015-12-26 03:56:482630 dns_client_ = std::move(dns_client);
[email protected]daae1322013-09-05 18:26:502631 if (dns_client_ && !dns_client_->GetConfig() &&
2632 num_dns_failures_ < kMaximumDnsFailures) {
2633 DnsConfig dns_config;
2634 NetworkChangeNotifier::GetDnsConfig(&dns_config);
Brad Lassey786929ad2018-02-21 20:54:272635 dns_config.dns_over_https_servers = dns_over_https_servers_;
[email protected]daae1322013-09-05 18:26:502636 dns_client_->SetConfig(dns_config);
2637 num_dns_failures_ = 0;
2638 if (dns_client_->GetConfig())
2639 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
[email protected]a8883e452012-11-17 05:58:062640 }
[email protected]daae1322013-09-05 18:26:502641
2642 AbortDnsTasks();
[email protected]a8883e452012-11-17 05:58:062643}
2644
maksim.sisov31452af2016-07-27 06:38:102645HostResolverImpl::RequestImpl::~RequestImpl() {
2646 if (job_)
2647 job_->CancelRequest(this);
2648}
2649
2650void HostResolverImpl::RequestImpl::ChangeRequestPriority(
2651 RequestPriority priority) {
2652 job_->ChangeRequestPriority(this, priority);
2653}
2654
[email protected]b59ff372009-07-15 22:04:322655} // namespace net