blob: 11f2ed5bf74ce2971b6a033c912d9c5fc2b4b46c [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>
9#elif defined(OS_POSIX)
10#include <netdb.h>
11#endif
12
tfarinada9e1362017-03-14 16:49:0613#if defined(OS_POSIX)
14#include <netinet/in.h>
15#if !defined(OS_NACL)
16#include <net/if.h>
17#if !defined(OS_ANDROID)
18#include <ifaddrs.h>
19#endif // !defined(OS_ANDROID)
20#endif // !defined(OS_NACL)
21#endif // defined(OS_POSIX)
22
[email protected]68ad3ee2010-01-30 03:45:3923#include <cmath>
thestiga74ad2b2016-07-11 20:52:3624#include <memory>
[email protected]0f292de02012-02-01 22:28:2025#include <utility>
[email protected]21526002010-05-16 19:42:4626#include <vector>
[email protected]68ad3ee2010-01-30 03:45:3927
[email protected]33152acc2011-10-20 23:37:1228#include "base/bind.h"
[email protected]aa22b242011-11-16 18:58:2929#include "base/bind_helpers.h"
[email protected]0f292de02012-02-01 22:28:2030#include "base/callback.h"
maksim.sisov31452af2016-07-27 06:38:1031#include "base/callback_helpers.h"
[email protected]b59ff372009-07-15 22:04:3232#include "base/compiler_specific.h"
Brett Wilsonc6a0c822017-09-12 00:04:2933#include "base/containers/circular_deque.h"
[email protected]58580352010-10-26 04:07:5034#include "base/debug/debugger.h"
[email protected]58580352010-10-26 04:07:5035#include "base/debug/stack_trace.h"
Avi Drissman13fc8932015-12-20 04:40:4636#include "base/macros.h"
mmenke91c17162016-06-02 16:03:2337#include "base/memory/ptr_util.h"
[email protected]1e9bbd22010-10-15 16:42:4538#include "base/metrics/field_trial.h"
Ilya Sherman0eb39802017-12-08 20:58:1839#include "base/metrics/histogram_functions.h"
davidbenad6fc442015-05-18 20:59:1340#include "base/metrics/histogram_macros.h"
anujk.sharma7c907f02015-05-29 02:55:4441#include "base/single_thread_task_runner.h"
[email protected]be528af2013-06-11 07:39:4842#include "base/strings/string_util.h"
[email protected]750b2f3c2013-06-07 18:41:0543#include "base/strings/utf_string_conversions.h"
Francois Doraya2d01ba2017-09-25 19:17:4044#include "base/task_scheduler/post_task.h"
45#include "base/threading/scoped_blocking_call.h"
gabf767595f2016-05-11 18:50:3546#include "base/threading/thread_task_runner_handle.h"
[email protected]66e96c42013-06-28 15:20:3147#include "base/time/time.h"
ssid6d6b40102016-04-05 18:59:5648#include "base/trace_event/trace_event.h"
[email protected]21526002010-05-16 19:42:4649#include "base/values.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";
126#else
127 "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[] = {
135#if defined(OS_POSIX)
[email protected]23f771162011-06-02 18:37:51136#if !defined(OS_FREEBSD)
[email protected]39588992011-07-11 19:54:37137#if !defined(OS_ANDROID)
[email protected]c48aef92011-11-22 23:41:45138 // EAI_ADDRFAMILY has been declared obsolete in Android's and
139 // FreeBSD's netdb.h.
[email protected]c89b2442011-05-26 14:28:27140 EAI_ADDRFAMILY,
[email protected]39588992011-07-11 19:54:37141#endif
[email protected]c48aef92011-11-22 23:41:45142 // EAI_NODATA has been declared obsolete in FreeBSD's netdb.h.
[email protected]23f771162011-06-02 18:37:51143 EAI_NODATA,
144#endif
[email protected]c89b2442011-05-26 14:28:27145 EAI_AGAIN,
146 EAI_BADFLAGS,
147 EAI_FAIL,
148 EAI_FAMILY,
149 EAI_MEMORY,
[email protected]c89b2442011-05-26 14:28:27150 EAI_NONAME,
151 EAI_SERVICE,
152 EAI_SOCKTYPE,
153 EAI_SYSTEM,
154#elif defined(OS_WIN)
155 // See: http://msdn.microsoft.com/en-us/library/ms738520(VS.85).aspx
156 WSA_NOT_ENOUGH_MEMORY,
157 WSAEAFNOSUPPORT,
158 WSAEINVAL,
159 WSAESOCKTNOSUPPORT,
160 WSAHOST_NOT_FOUND,
161 WSANO_DATA,
162 WSANO_RECOVERY,
163 WSANOTINITIALISED,
164 WSATRY_AGAIN,
165 WSATYPE_NOT_FOUND,
166 // The following are not in doc, but might be to appearing in results :-(.
167 WSA_INVALID_HANDLE,
168#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
176 return base::CustomHistogram::ArrayToCustomRanges(os_errors,
177 arraysize(os_errors));
178}
179
[email protected]1def74c2012-03-22 20:07:00180enum DnsResolveStatus {
181 RESOLVE_STATUS_DNS_SUCCESS = 0,
182 RESOLVE_STATUS_PROC_SUCCESS,
183 RESOLVE_STATUS_FAIL,
[email protected]1d932852012-06-19 19:40:33184 RESOLVE_STATUS_SUSPECT_NETBIOS,
[email protected]1def74c2012-03-22 20:07:00185 RESOLVE_STATUS_MAX
186};
187
eroman91dd3602015-03-26 03:46:33188// ICANN uses this localhost address to indicate a name collision.
189//
190// The policy in Chromium is to fail host resolving if it resolves to
191// this special address.
192//
193// Not however that IP literals are exempt from this policy, so it is still
194// possible to navigate to http://127.0.53.53/ directly.
195//
196// For more details: https://www.icann.org/news/announcement-2-2014-08-01-en
martijna23c8962016-03-04 18:18:51197const uint8_t kIcanNameCollisionIp[] = {127, 0, 53, 53};
eroman91dd3602015-03-26 03:46:33198
eroman1efc237c2016-12-14 00:00:45199bool ContainsIcannNameCollisionIp(const AddressList& addr_list) {
200 for (const auto& endpoint : addr_list) {
201 const IPAddress& addr = endpoint.address();
202 if (addr.IsIPv4() && IPAddressStartsWith(addr, kIcanNameCollisionIp)) {
203 return true;
204 }
205 }
206 return false;
207}
208
[email protected]1def74c2012-03-22 20:07:00209void UmaAsyncDnsResolveStatus(DnsResolveStatus result) {
210 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ResolveStatus",
211 result,
212 RESOLVE_STATUS_MAX);
213}
214
[email protected]1d932852012-06-19 19:40:33215bool ResemblesNetBIOSName(const std::string& hostname) {
216 return (hostname.size() < 16) && (hostname.find('.') == std::string::npos);
217}
218
219// True if |hostname| ends with either ".local" or ".local.".
220bool ResemblesMulticastDNSName(const std::string& hostname) {
221 DCHECK(!hostname.empty());
222 const char kSuffix[] = ".local.";
223 const size_t kSuffixLen = sizeof(kSuffix) - 1;
224 const size_t kSuffixLenTrimmed = kSuffixLen - 1;
thestiga74ad2b2016-07-11 20:52:36225 if (hostname.back() == '.') {
[email protected]1d932852012-06-19 19:40:33226 return hostname.size() > kSuffixLen &&
227 !hostname.compare(hostname.size() - kSuffixLen, kSuffixLen, kSuffix);
228 }
229 return hostname.size() > kSuffixLenTrimmed &&
230 !hostname.compare(hostname.size() - kSuffixLenTrimmed, kSuffixLenTrimmed,
231 kSuffix, kSuffixLenTrimmed);
232}
233
[email protected]51b9a6b2012-06-25 21:50:29234// A macro to simplify code and readability.
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21235#define DNS_HISTOGRAM_BY_PRIORITY(basename, priority, time) \
236 do { \
237 switch (priority) { \
238 case HIGHEST: \
Miriam Gershenson90d05e02017-09-28 19:29:28239 UMA_HISTOGRAM_LONG_TIMES_100(basename ".HIGHEST", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21240 break; \
241 case MEDIUM: \
Miriam Gershenson90d05e02017-09-28 19:29:28242 UMA_HISTOGRAM_LONG_TIMES_100(basename ".MEDIUM", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21243 break; \
244 case LOW: \
Miriam Gershenson90d05e02017-09-28 19:29:28245 UMA_HISTOGRAM_LONG_TIMES_100(basename ".LOW", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21246 break; \
247 case LOWEST: \
Miriam Gershenson90d05e02017-09-28 19:29:28248 UMA_HISTOGRAM_LONG_TIMES_100(basename ".LOWEST", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21249 break; \
250 case IDLE: \
Miriam Gershenson90d05e02017-09-28 19:29:28251 UMA_HISTOGRAM_LONG_TIMES_100(basename ".IDLE", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21252 break; \
253 case THROTTLED: \
Miriam Gershenson90d05e02017-09-28 19:29:28254 UMA_HISTOGRAM_LONG_TIMES_100(basename ".THROTTLED", time); \
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21255 break; \
256 } \
257 UMA_HISTOGRAM_LONG_TIMES_100(basename, time); \
[email protected]51b9a6b2012-06-25 21:50:29258 } while (0)
259
260// Record time from Request creation until a valid DNS response.
Miriam Gershenson90d05e02017-09-28 19:29:28261void RecordTotalTime(bool speculative,
262 bool from_cache,
[email protected]51b9a6b2012-06-25 21:50:29263 base::TimeDelta duration) {
Miriam Gershenson7ba03e12018-02-07 22:48:24264 if (!speculative) {
Miriam Gershenson90d05e02017-09-28 19:29:28265 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.TotalTime", duration);
Miriam Gershenson90d05e02017-09-28 19:29:28266
Miriam Gershenson7ba03e12018-02-07 22:48:24267 if (!from_cache)
Miriam Gershenson90d05e02017-09-28 19:29:28268 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.TotalTimeNotCached", duration);
[email protected]51b9a6b2012-06-25 21:50:29269 }
270}
271
[email protected]1339a2a22012-10-17 08:39:43272void RecordTTL(base::TimeDelta ttl) {
273 UMA_HISTOGRAM_CUSTOM_TIMES("AsyncDNS.TTL", ttl,
274 base::TimeDelta::FromSeconds(1),
275 base::TimeDelta::FromDays(1), 100);
276}
277
[email protected]16c2bd72013-06-28 01:19:22278bool ConfigureAsyncDnsNoFallbackFieldTrial() {
279 const bool kDefault = false;
280
281 // Configure the AsyncDns field trial as follows:
282 // groups AsyncDnsNoFallbackA and AsyncDnsNoFallbackB: return true,
283 // groups AsyncDnsA and AsyncDnsB: return false,
284 // groups SystemDnsA and SystemDnsB: return false,
285 // otherwise (trial absent): return default.
286 std::string group_name = base::FieldTrialList::FindFullName("AsyncDns");
brettw3a2c6902015-07-06 19:43:29287 if (!group_name.empty()) {
288 return base::StartsWith(group_name, "AsyncDnsNoFallback",
289 base::CompareCase::INSENSITIVE_ASCII);
290 }
[email protected]16c2bd72013-06-28 01:19:22291 return kDefault;
292}
293
[email protected]d7b9a2b2012-05-31 22:31:19294//-----------------------------------------------------------------------------
295
Avi Drissman13fc8932015-12-20 04:40:46296AddressList EnsurePortOnAddressList(const AddressList& list, uint16_t port) {
[email protected]895123222012-10-25 15:21:17297 if (list.empty() || list.front().port() == port)
298 return list;
299 return AddressList::CopyWithPort(list, port);
[email protected]7054e78f2012-05-07 21:44:56300}
301
[email protected]ec666ab22013-04-17 20:05:59302// Returns true if |addresses| contains only IPv4 loopback addresses.
303bool IsAllIPv4Loopback(const AddressList& addresses) {
304 for (unsigned i = 0; i < addresses.size(); ++i) {
martijna23c8962016-03-04 18:18:51305 const IPAddress& address = addresses[i].address();
[email protected]ec666ab22013-04-17 20:05:59306 switch (addresses[i].GetFamily()) {
307 case ADDRESS_FAMILY_IPV4:
martijna23c8962016-03-04 18:18:51308 if (address.bytes()[0] != 127)
[email protected]ec666ab22013-04-17 20:05:59309 return false;
310 break;
311 case ADDRESS_FAMILY_IPV6:
312 return false;
313 default:
314 NOTREACHED();
315 return false;
316 }
317 }
318 return true;
319}
320
tfarinada9e1362017-03-14 16:49:06321// Returns true if it can determine that only loopback addresses are configured.
322// i.e. if only 127.0.0.1 and ::1 are routable.
323// Also returns false if it cannot determine this.
324bool HaveOnlyLoopbackAddresses() {
Francois Doraya2d01ba2017-09-25 19:17:40325 base::ScopedBlockingCall scoped_blocking_call(base::BlockingType::WILL_BLOCK);
tfarinada9e1362017-03-14 16:49:06326#if defined(OS_ANDROID)
327 return android::HaveOnlyLoopbackAddresses();
328#elif defined(OS_NACL)
329 NOTIMPLEMENTED();
330 return false;
331#elif defined(OS_POSIX)
332 struct ifaddrs* interface_addr = NULL;
333 int rv = getifaddrs(&interface_addr);
334 if (rv != 0) {
335 DVLOG(1) << "getifaddrs() failed with errno = " << errno;
336 return false;
337 }
338
339 bool result = true;
340 for (struct ifaddrs* interface = interface_addr;
341 interface != NULL;
342 interface = interface->ifa_next) {
343 if (!(IFF_UP & interface->ifa_flags))
344 continue;
345 if (IFF_LOOPBACK & interface->ifa_flags)
346 continue;
347 const struct sockaddr* addr = interface->ifa_addr;
348 if (!addr)
349 continue;
350 if (addr->sa_family == AF_INET6) {
351 // Safe cast since this is AF_INET6.
352 const struct sockaddr_in6* addr_in6 =
353 reinterpret_cast<const struct sockaddr_in6*>(addr);
354 const struct in6_addr* sin6_addr = &addr_in6->sin6_addr;
355 if (IN6_IS_ADDR_LOOPBACK(sin6_addr) || IN6_IS_ADDR_LINKLOCAL(sin6_addr))
356 continue;
357 }
358 if (addr->sa_family != AF_INET6 && addr->sa_family != AF_INET)
359 continue;
360
361 result = false;
362 break;
363 }
364 freeifaddrs(interface_addr);
365 return result;
366#elif defined(OS_WIN)
367 // TODO(wtc): implement with the GetAdaptersAddresses function.
368 NOTIMPLEMENTED();
369 return false;
370#else
371 NOTIMPLEMENTED();
372 return false;
373#endif // defined(various platforms)
374}
375
[email protected]cd565142012-06-12 16:21:45376// Creates NetLog parameters when the resolve failed.
danakj22f90e72016-04-16 01:55:40377std::unique_ptr<base::Value> NetLogProcTaskFailedCallback(
Avi Drissman13fc8932015-12-20 04:40:46378 uint32_t attempt_number,
eroman001c3742015-04-23 03:11:17379 int net_error,
380 int os_error,
381 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40382 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]cd565142012-06-12 16:21:45383 if (attempt_number)
384 dict->SetInteger("attempt_number", attempt_number);
[email protected]21526002010-05-16 19:42:46385
[email protected]cd565142012-06-12 16:21:45386 dict->SetInteger("net_error", net_error);
[email protected]13024882011-05-18 23:19:16387
[email protected]cd565142012-06-12 16:21:45388 if (os_error) {
389 dict->SetInteger("os_error", os_error);
[email protected]21526002010-05-16 19:42:46390#if defined(OS_POSIX)
[email protected]cd565142012-06-12 16:21:45391 dict->SetString("os_error_string", gai_strerror(os_error));
[email protected]21526002010-05-16 19:42:46392#elif defined(OS_WIN)
[email protected]cd565142012-06-12 16:21:45393 // Map the error code to a human-readable string.
wezb9820d42016-06-22 23:41:04394 LPWSTR error_string = nullptr;
Peter Kastingbe940e92014-11-20 23:14:08395 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
396 0, // Use the internal message table.
397 os_error,
398 0, // Use default language.
399 (LPWSTR)&error_string,
400 0, // Buffer size.
401 0); // Arguments (unused).
[email protected]ad65a3e2013-12-25 18:18:01402 dict->SetString("os_error_string", base::WideToUTF8(error_string));
[email protected]cd565142012-06-12 16:21:45403 LocalFree(error_string);
[email protected]21526002010-05-16 19:42:46404#endif
[email protected]21526002010-05-16 19:42:46405 }
406
dchengc7eeda422015-12-26 03:56:48407 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45408}
[email protected]a9813302012-04-28 09:29:28409
[email protected]cd565142012-06-12 16:21:45410// Creates NetLog parameters when the DnsTask failed.
danakj22f90e72016-04-16 01:55:40411std::unique_ptr<base::Value> NetLogDnsTaskFailedCallback(
estade5e5529d2015-05-21 20:59:11412 int net_error,
413 int dns_error,
414 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40415 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]cd565142012-06-12 16:21:45416 dict->SetInteger("net_error", net_error);
417 if (dns_error)
418 dict->SetInteger("dns_error", dns_error);
dchengc7eeda422015-12-26 03:56:48419 return std::move(dict);
thestiga74ad2b2016-07-11 20:52:36420}
[email protected]ee094b82010-08-24 15:55:51421
[email protected]cd565142012-06-12 16:21:45422// Creates NetLog parameters containing the information in a RequestInfo object,
mikecironef22f9812016-10-04 03:40:19423// along with the associated NetLogSource.
danakj22f90e72016-04-16 01:55:40424std::unique_ptr<base::Value> NetLogRequestInfoCallback(
estade5e5529d2015-05-21 20:59:11425 const HostResolver::RequestInfo* info,
426 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40427 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]b3601bc22012-02-21 21:23:20428
[email protected]cd565142012-06-12 16:21:45429 dict->SetString("host", info->host_port_pair().ToString());
430 dict->SetInteger("address_family",
431 static_cast<int>(info->address_family()));
432 dict->SetBoolean("allow_cached_response", info->allow_cached_response());
433 dict->SetBoolean("is_speculative", info->is_speculative());
dchengc7eeda422015-12-26 03:56:48434 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45435}
[email protected]b3601bc22012-02-21 21:23:20436
[email protected]cd565142012-06-12 16:21:45437// Creates NetLog parameters for the creation of a HostResolverImpl::Job.
danakj22f90e72016-04-16 01:55:40438std::unique_ptr<base::Value> NetLogJobCreationCallback(
mikecironef22f9812016-10-04 03:40:19439 const NetLogSource& source,
estade5e5529d2015-05-21 20:59:11440 const std::string* host,
441 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40442 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
estade5e5529d2015-05-21 20:59:11443 source.AddToEventParameters(dict.get());
[email protected]cd565142012-06-12 16:21:45444 dict->SetString("host", *host);
dchengc7eeda422015-12-26 03:56:48445 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45446}
[email protected]a9813302012-04-28 09:29:28447
[email protected]cd565142012-06-12 16:21:45448// Creates NetLog parameters for HOST_RESOLVER_IMPL_JOB_ATTACH/DETACH events.
danakj22f90e72016-04-16 01:55:40449std::unique_ptr<base::Value> NetLogJobAttachCallback(
mikecironef22f9812016-10-04 03:40:19450 const NetLogSource& source,
estade5e5529d2015-05-21 20:59:11451 RequestPriority priority,
452 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40453 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
estade5e5529d2015-05-21 20:59:11454 source.AddToEventParameters(dict.get());
[email protected]3b04d1f22013-10-16 00:23:56455 dict->SetString("priority", RequestPriorityToString(priority));
dchengc7eeda422015-12-26 03:56:48456 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45457}
[email protected]b3601bc22012-02-21 21:23:20458
[email protected]cd565142012-06-12 16:21:45459// Creates NetLog parameters for the DNS_CONFIG_CHANGED event.
danakj22f90e72016-04-16 01:55:40460std::unique_ptr<base::Value> NetLogDnsConfigCallback(
estade5e5529d2015-05-21 20:59:11461 const DnsConfig* config,
462 NetLogCaptureMode /* capture_mode */) {
tfhef3618f2016-01-11 23:07:08463 return config->ToValue();
[email protected]cd565142012-06-12 16:21:45464}
[email protected]b4481b222012-03-16 17:13:11465
danakj22f90e72016-04-16 01:55:40466std::unique_ptr<base::Value> NetLogIPv6AvailableCallback(
estade5e5529d2015-05-21 20:59:11467 bool ipv6_available,
468 bool cached,
469 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40470 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
sergeyub8cdc212015-05-14 18:50:37471 dict->SetBoolean("ipv6_available", ipv6_available);
472 dict->SetBoolean("cached", cached);
dchengc7eeda422015-12-26 03:56:48473 return std::move(dict);
sergeyub8cdc212015-05-14 18:50:37474}
475
[email protected]0f292de02012-02-01 22:28:20476// The logging routines are defined here because some requests are resolved
477// without a Request object.
478
479// Logs when a request has just been started.
tfarina428341112016-09-22 13:38:20480void LogStartRequest(const NetLogWithSource& source_net_log,
[email protected]0f292de02012-02-01 22:28:20481 const HostResolver::RequestInfo& info) {
mikecirone8b85c432016-09-08 19:11:00482 source_net_log.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_REQUEST,
483 base::Bind(&NetLogRequestInfoCallback, &info));
[email protected]0f292de02012-02-01 22:28:20484}
485
486// Logs when a request has just completed (before its callback is run).
tfarina428341112016-09-22 13:38:20487void LogFinishRequest(const NetLogWithSource& source_net_log,
[email protected]0f292de02012-02-01 22:28:20488 const HostResolver::RequestInfo& info,
[email protected]b3601bc22012-02-21 21:23:20489 int net_error) {
xunjieli26f90452014-11-10 16:23:02490 source_net_log.EndEventWithNetErrorCode(
mikecirone8b85c432016-09-08 19:11:00491 NetLogEventType::HOST_RESOLVER_IMPL_REQUEST, net_error);
[email protected]0f292de02012-02-01 22:28:20492}
493
494// Logs when a request has been cancelled.
tfarina428341112016-09-22 13:38:20495void LogCancelRequest(const NetLogWithSource& source_net_log,
[email protected]0f292de02012-02-01 22:28:20496 const HostResolverImpl::RequestInfo& info) {
mikecirone8b85c432016-09-08 19:11:00497 source_net_log.AddEvent(NetLogEventType::CANCELLED);
498 source_net_log.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_REQUEST);
[email protected]0f292de02012-02-01 22:28:20499}
500
[email protected]b59ff372009-07-15 22:04:32501//-----------------------------------------------------------------------------
502
[email protected]0f292de02012-02-01 22:28:20503// Keeps track of the highest priority.
504class PriorityTracker {
505 public:
[email protected]8c98d002012-07-18 19:02:27506 explicit PriorityTracker(RequestPriority initial_priority)
507 : highest_priority_(initial_priority), total_count_(0) {
[email protected]0f292de02012-02-01 22:28:20508 memset(counts_, 0, sizeof(counts_));
509 }
510
511 RequestPriority highest_priority() const {
512 return highest_priority_;
513 }
514
515 size_t total_count() const {
516 return total_count_;
517 }
518
519 void Add(RequestPriority req_priority) {
520 ++total_count_;
521 ++counts_[req_priority];
[email protected]31ae7ab2012-04-24 21:09:05522 if (highest_priority_ < req_priority)
[email protected]0f292de02012-02-01 22:28:20523 highest_priority_ = req_priority;
524 }
525
526 void Remove(RequestPriority req_priority) {
527 DCHECK_GT(total_count_, 0u);
528 DCHECK_GT(counts_[req_priority], 0u);
529 --total_count_;
530 --counts_[req_priority];
531 size_t i;
thestiga74ad2b2016-07-11 20:52:36532 for (i = highest_priority_; i > MINIMUM_PRIORITY && !counts_[i]; --i) {
533 }
[email protected]0f292de02012-02-01 22:28:20534 highest_priority_ = static_cast<RequestPriority>(i);
535
[email protected]31ae7ab2012-04-24 21:09:05536 // In absence of requests, default to MINIMUM_PRIORITY.
537 if (total_count_ == 0)
538 DCHECK_EQ(MINIMUM_PRIORITY, highest_priority_);
[email protected]0f292de02012-02-01 22:28:20539 }
540
541 private:
542 RequestPriority highest_priority_;
543 size_t total_count_;
544 size_t counts_[NUM_PRIORITIES];
545};
546
juliatuttle9fb7aeb2016-06-06 20:16:33547void MakeNotStale(HostCache::EntryStaleness* stale_info) {
548 if (!stale_info)
549 return;
550 stale_info->expired_by = base::TimeDelta::FromSeconds(-1);
551 stale_info->network_changes = 0;
552 stale_info->stale_hits = 0;
553}
554
juliatuttled7fa5852016-07-29 13:16:57555// Persist data every five minutes (potentially, cache and learned RTT).
556const int64_t kPersistDelaySec = 300;
557
[email protected]c54a8912012-10-22 22:09:43558} // namespace
[email protected]0f292de02012-02-01 22:28:20559
560//-----------------------------------------------------------------------------
561
tfarina9ed7f8c52016-02-19 17:50:18562bool ResolveLocalHostname(base::StringPiece host,
563 uint16_t port,
564 AddressList* address_list) {
tfarina9ed7f8c52016-02-19 17:50:18565 address_list->clear();
566
567 bool is_local6;
568 if (!IsLocalHostname(host, &is_local6))
569 return false;
570
martijna23c8962016-03-04 18:18:51571 address_list->push_back(IPEndPoint(IPAddress::IPv6Localhost(), port));
tfarina9ed7f8c52016-02-19 17:50:18572 if (!is_local6) {
martijna23c8962016-03-04 18:18:51573 address_list->push_back(IPEndPoint(IPAddress::IPv4Localhost(), port));
tfarina9ed7f8c52016-02-19 17:50:18574 }
575
576 return true;
577}
578
[email protected]daae1322013-09-05 18:26:50579const unsigned HostResolverImpl::kMaximumDnsFailures = 16;
580
[email protected]0f292de02012-02-01 22:28:20581// Holds the data for a request that could not be completed synchronously.
582// It is owned by a Job. Canceled Requests are only marked as canceled rather
583// than removed from the Job's |requests_| list.
maksim.sisov31452af2016-07-27 06:38:10584class HostResolverImpl::RequestImpl : public HostResolver::Request {
[email protected]b59ff372009-07-15 22:04:32585 public:
tfarina428341112016-09-22 13:38:20586 RequestImpl(const NetLogWithSource& source_net_log,
maksim.sisov31452af2016-07-27 06:38:10587 const RequestInfo& info,
588 RequestPriority priority,
589 const CompletionCallback& callback,
590 AddressList* addresses,
591 Job* job)
[email protected]ee094b82010-08-24 15:55:51592 : source_net_log_(source_net_log),
[email protected]54e13772009-08-14 03:01:09593 info_(info),
[email protected]5109c1952013-08-20 18:44:10594 priority_(priority),
maksim.sisov31452af2016-07-27 06:38:10595 job_(job),
[email protected]54e13772009-08-14 03:01:09596 callback_(callback),
[email protected]51b9a6b2012-06-25 21:50:29597 addresses_(addresses),
[email protected]5109c1952013-08-20 18:44:10598 request_time_(base::TimeTicks::Now()) {}
[email protected]b59ff372009-07-15 22:04:32599
maksim.sisov31452af2016-07-27 06:38:10600 ~RequestImpl() override;
601
602 void ChangeRequestPriority(RequestPriority priority) override;
603
604 void OnJobCancelled(Job* job) {
605 DCHECK_EQ(job_, job);
wezb9820d42016-06-22 23:41:04606 job_ = nullptr;
607 addresses_ = nullptr;
[email protected]aa22b242011-11-16 18:58:29608 callback_.Reset();
[email protected]b59ff372009-07-15 22:04:32609 }
610
[email protected]0f292de02012-02-01 22:28:20611 // Prepare final AddressList and call completion callback.
maksim.sisov31452af2016-07-27 06:38:10612 void OnJobCompleted(Job* job, int error, const AddressList& addr_list) {
613 DCHECK_EQ(job_, job);
[email protected]895123222012-10-25 15:21:17614 if (error == OK)
615 *addresses_ = EnsurePortOnAddressList(addr_list, info_.port());
maksim.sisov31452af2016-07-27 06:38:10616 job_ = nullptr;
617 addresses_ = nullptr;
618 base::ResetAndReturn(&callback_).Run(error);
[email protected]b59ff372009-07-15 22:04:32619 }
620
[email protected]b59ff372009-07-15 22:04:32621 Job* job() const {
622 return job_;
623 }
624
[email protected]0f292de02012-02-01 22:28:20625 // NetLog for the source, passed in HostResolver::Resolve.
tfarina428341112016-09-22 13:38:20626 const NetLogWithSource& source_net_log() { return source_net_log_; }
[email protected]ee094b82010-08-24 15:55:51627
[email protected]b59ff372009-07-15 22:04:32628 const RequestInfo& info() const {
629 return info_;
630 }
631
[email protected]5109c1952013-08-20 18:44:10632 RequestPriority priority() const { return priority_; }
juliatuttlec53b19a72016-05-05 13:51:31633 void set_priority(RequestPriority priority) { priority_ = priority; }
[email protected]5109c1952013-08-20 18:44:10634
635 base::TimeTicks request_time() const { return request_time_; }
[email protected]51b9a6b2012-06-25 21:50:29636
[email protected]b59ff372009-07-15 22:04:32637 private:
tfarina428341112016-09-22 13:38:20638 const NetLogWithSource source_net_log_;
[email protected]54e13772009-08-14 03:01:09639
[email protected]b59ff372009-07-15 22:04:32640 // The request info that started the request.
[email protected]5109c1952013-08-20 18:44:10641 const RequestInfo info_;
642
juliatuttlec53b19a72016-05-05 13:51:31643 RequestPriority priority_;
[email protected]b59ff372009-07-15 22:04:32644
[email protected]0f292de02012-02-01 22:28:20645 // The resolve job that this request is dependent on.
[email protected]b59ff372009-07-15 22:04:32646 Job* job_;
647
648 // The user's callback to invoke when the request completes.
[email protected]aa22b242011-11-16 18:58:29649 CompletionCallback callback_;
[email protected]b59ff372009-07-15 22:04:32650
651 // The address list to save result into.
652 AddressList* addresses_;
653
[email protected]51b9a6b2012-06-25 21:50:29654 const base::TimeTicks request_time_;
655
maksim.sisov31452af2016-07-27 06:38:10656 DISALLOW_COPY_AND_ASSIGN(RequestImpl);
[email protected]b59ff372009-07-15 22:04:32657};
658
[email protected]1e9bbd22010-10-15 16:42:45659//------------------------------------------------------------------------------
660
Francois Doraya2d01ba2017-09-25 19:17:40661// Calls HostResolverProc in TaskScheduler. Performs retries if necessary.
[email protected]0f292de02012-02-01 22:28:20662//
663// Whenever we try to resolve the host, we post a delayed task to check if host
664// resolution (OnLookupComplete) is completed or not. If the original attempt
665// hasn't completed, then we start another attempt for host resolution. We take
666// the results from the first attempt that finishes and ignore the results from
667// all other attempts.
668//
669// TODO(szym): Move to separate source file for testing and mocking.
670//
671class HostResolverImpl::ProcTask
672 : public base::RefCountedThreadSafe<HostResolverImpl::ProcTask> {
[email protected]b59ff372009-07-15 22:04:32673 public:
[email protected]b3601bc22012-02-21 21:23:20674 typedef base::Callback<void(int net_error,
675 const AddressList& addr_list)> Callback;
[email protected]b59ff372009-07-15 22:04:32676
[email protected]0f292de02012-02-01 22:28:20677 ProcTask(const Key& key,
678 const ProcTaskParams& params,
679 const Callback& callback,
Miriam Gershensone42adb22017-10-16 16:19:38680 scoped_refptr<base::TaskRunner> proc_task_runner,
tfarina428341112016-09-22 13:38:20681 const NetLogWithSource& job_net_log)
[email protected]0f292de02012-02-01 22:28:20682 : key_(key),
683 params_(params),
684 callback_(callback),
mmenke91c17162016-06-02 16:03:23685 network_task_runner_(base::ThreadTaskRunnerHandle::Get()),
Miriam Gershensone42adb22017-10-16 16:19:38686 proc_task_runner_(std::move(proc_task_runner)),
[email protected]0f292de02012-02-01 22:28:20687 attempt_number_(0),
688 completed_attempt_number_(0),
689 completed_attempt_error_(ERR_UNEXPECTED),
[email protected]b3601bc22012-02-21 21:23:20690 net_log_(job_net_log) {
[email protected]90499482013-06-01 00:39:50691 if (!params_.resolver_proc.get())
[email protected]0f292de02012-02-01 22:28:20692 params_.resolver_proc = HostResolverProc::GetDefault();
693 // If default is unset, use the system proc.
[email protected]90499482013-06-01 00:39:50694 if (!params_.resolver_proc.get())
[email protected]1ee9afa12013-04-16 14:18:06695 params_.resolver_proc = new SystemHostResolverProc();
[email protected]b59ff372009-07-15 22:04:32696 }
697
[email protected]b59ff372009-07-15 22:04:32698 void Start() {
mmenke91c17162016-06-02 16:03:23699 DCHECK(network_task_runner_->BelongsToCurrentThread());
mikecirone8b85c432016-09-08 19:11:00700 net_log_.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_PROC_TASK);
[email protected]189163e2011-05-11 01:48:54701 StartLookupAttempt();
702 }
[email protected]252b699b2010-02-05 21:38:06703
[email protected]0f292de02012-02-01 22:28:20704 // Cancels this ProcTask. It will be orphaned. Any outstanding resolve
mmenke91c17162016-06-02 16:03:23705 // attempts running on worker thread will continue running. Only once all the
[email protected]0f292de02012-02-01 22:28:20706 // attempts complete will the final reference to this ProcTask be released.
707 void Cancel() {
mmenke91c17162016-06-02 16:03:23708 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20709
[email protected]0adcb2b2012-08-15 21:30:46710 if (was_canceled() || was_completed())
[email protected]0f292de02012-02-01 22:28:20711 return;
712
[email protected]0f292de02012-02-01 22:28:20713 callback_.Reset();
mikecirone8b85c432016-09-08 19:11:00714 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_PROC_TASK);
[email protected]0f292de02012-02-01 22:28:20715 }
716
[email protected]0f292de02012-02-01 22:28:20717 bool was_canceled() const {
mmenke91c17162016-06-02 16:03:23718 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20719 return callback_.is_null();
720 }
721
722 bool was_completed() const {
mmenke91c17162016-06-02 16:03:23723 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20724 return completed_attempt_number_ > 0;
725 }
726
727 private:
[email protected]a9813302012-04-28 09:29:28728 friend class base::RefCountedThreadSafe<ProcTask>;
Chris Watkins68b15032017-12-01 03:07:13729 ~ProcTask() = default;
[email protected]a9813302012-04-28 09:29:28730
[email protected]189163e2011-05-11 01:48:54731 void StartLookupAttempt() {
mmenke91c17162016-06-02 16:03:23732 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54733 base::TimeTicks start_time = base::TimeTicks::Now();
734 ++attempt_number_;
735 // Dispatch the lookup attempt to a worker thread.
Miriam Gershensone42adb22017-10-16 16:19:38736 proc_task_runner_->PostTask(
Francois Doraya2d01ba2017-09-25 19:17:40737 FROM_HERE,
Francois Doraya2d01ba2017-09-25 19:17:40738 base::Bind(&ProcTask::DoLookup, this, start_time, attempt_number_));
[email protected]13024882011-05-18 23:19:16739
mikecirone8b85c432016-09-08 19:11:00740 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_ATTEMPT_STARTED,
tfarina5e24b242015-10-27 13:11:28741 NetLog::IntCallback("attempt_number", attempt_number_));
[email protected]13024882011-05-18 23:19:16742
mmenke91c17162016-06-02 16:03:23743 // If the results aren't received within a given time, RetryIfNotComplete
744 // will start a new attempt if none of the outstanding attempts have
745 // completed yet.
[email protected]0f292de02012-02-01 22:28:20746 if (attempt_number_ <= params_.max_retry_attempts) {
mmenke91c17162016-06-02 16:03:23747 network_task_runner_->PostDelayedTask(
748 FROM_HERE, base::Bind(&ProcTask::RetryIfNotComplete, this),
[email protected]7e560102012-03-08 20:58:42749 params_.unresponsive_delay);
[email protected]06ef6d92011-05-19 04:24:58750 }
[email protected]b59ff372009-07-15 22:04:32751 }
752
Francois Doraya2d01ba2017-09-25 19:17:40753 // WARNING: This code runs in TaskScheduler with CONTINUE_ON_SHUTDOWN. The
754 // shutdown code cannot wait for it to finish, so this code must be very
755 // careful about using other objects (like MessageLoops, Singletons, etc).
756 // During shutdown these objects may no longer exist. Multiple DoLookups()
757 // could be running in parallel, so any state inside of |this| must not
758 // mutate.
[email protected]189163e2011-05-11 01:48:54759 void DoLookup(const base::TimeTicks& start_time,
Avi Drissman13fc8932015-12-20 04:40:46760 const uint32_t attempt_number) {
[email protected]189163e2011-05-11 01:48:54761 AddressList results;
762 int os_error = 0;
[email protected]0f292de02012-02-01 22:28:20763 int error = params_.resolver_proc->Resolve(key_.hostname,
764 key_.address_family,
765 key_.host_resolver_flags,
766 &results,
767 &os_error);
[email protected]b59ff372009-07-15 22:04:32768
mmenke91c17162016-06-02 16:03:23769 network_task_runner_->PostTask(
770 FROM_HERE, base::Bind(&ProcTask::OnLookupComplete, this, results,
771 start_time, attempt_number, error, os_error));
[email protected]189163e2011-05-11 01:48:54772 }
773
mmenke91c17162016-06-02 16:03:23774 // Makes next attempt if DoLookup() has not finished.
[email protected]0f292de02012-02-01 22:28:20775 void RetryIfNotComplete() {
mmenke91c17162016-06-02 16:03:23776 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54777
[email protected]0f292de02012-02-01 22:28:20778 if (was_completed() || was_canceled())
[email protected]189163e2011-05-11 01:48:54779 return;
780
[email protected]0f292de02012-02-01 22:28:20781 params_.unresponsive_delay *= params_.retry_factor;
[email protected]189163e2011-05-11 01:48:54782 StartLookupAttempt();
[email protected]b59ff372009-07-15 22:04:32783 }
784
anujk.sharma7c907f02015-05-29 02:55:44785 // Callback for when DoLookup() completes (runs on task runner thread).
[email protected]189163e2011-05-11 01:48:54786 void OnLookupComplete(const AddressList& results,
787 const base::TimeTicks& start_time,
Avi Drissman13fc8932015-12-20 04:40:46788 const uint32_t attempt_number,
[email protected]189163e2011-05-11 01:48:54789 int error,
790 const int os_error) {
xunjieli0b7f5b62016-12-06 20:43:48791 TRACE_EVENT0(kNetTracingCategory, "ProcTask::OnLookupComplete");
mmenke91c17162016-06-02 16:03:23792 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]49b70b222013-05-07 21:24:23793 // If results are empty, we should return an error.
794 bool empty_list_on_ok = (error == OK && results.empty());
[email protected]49b70b222013-05-07 21:24:23795 if (empty_list_on_ok)
796 error = ERR_NAME_NOT_RESOLVED;
[email protected]189163e2011-05-11 01:48:54797
798 bool was_retry_attempt = attempt_number > 1;
799
[email protected]2d3b7762010-10-09 00:35:47800 // Ideally the following code would be part of host_resolver_proc.cc,
[email protected]b3601bc22012-02-21 21:23:20801 // however it isn't safe to call NetworkChangeNotifier from worker threads.
mmenke91c17162016-06-02 16:03:23802 // So do it here on the IO thread instead.
[email protected]189163e2011-05-11 01:48:54803 if (error != OK && NetworkChangeNotifier::IsOffline())
804 error = ERR_INTERNET_DISCONNECTED;
[email protected]2d3b7762010-10-09 00:35:47805
[email protected]189163e2011-05-11 01:48:54806 RecordAttemptHistograms(start_time, attempt_number, error, os_error);
[email protected]f2d8c4212010-02-02 00:56:35807
[email protected]0f292de02012-02-01 22:28:20808 if (was_canceled())
[email protected]b59ff372009-07-15 22:04:32809 return;
810
mikecironef22f9812016-10-04 03:40:19811 NetLogParametersCallback net_log_callback;
[email protected]0f292de02012-02-01 22:28:20812 if (error != OK) {
[email protected]cd565142012-06-12 16:21:45813 net_log_callback = base::Bind(&NetLogProcTaskFailedCallback,
814 attempt_number,
815 error,
816 os_error);
[email protected]0f292de02012-02-01 22:28:20817 } else {
tfarina5e24b242015-10-27 13:11:28818 net_log_callback = NetLog::IntCallback("attempt_number", attempt_number);
[email protected]0f292de02012-02-01 22:28:20819 }
mikecirone8b85c432016-09-08 19:11:00820 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_ATTEMPT_FINISHED,
[email protected]cd565142012-06-12 16:21:45821 net_log_callback);
[email protected]0f292de02012-02-01 22:28:20822
823 if (was_completed())
824 return;
825
Miriam Gershenson61604662017-09-28 23:51:11826 RecordTaskHistograms(start_time, error, os_error);
827
[email protected]0f292de02012-02-01 22:28:20828 // Copy the results from the first worker thread that resolves the host.
829 results_ = results;
830 completed_attempt_number_ = attempt_number;
831 completed_attempt_error_ = error;
832
[email protected]e87b8b512011-06-14 22:12:52833 if (was_retry_attempt) {
834 // If retry attempt finishes before 1st attempt, then get stats on how
835 // much time is saved by having spawned an extra attempt.
836 retry_attempt_finished_time_ = base::TimeTicks::Now();
837 }
838
[email protected]189163e2011-05-11 01:48:54839 if (error != OK) {
[email protected]cd565142012-06-12 16:21:45840 net_log_callback = base::Bind(&NetLogProcTaskFailedCallback,
841 0, error, os_error);
[email protected]ee094b82010-08-24 15:55:51842 } else {
[email protected]cd565142012-06-12 16:21:45843 net_log_callback = results_.CreateNetLogCallback();
[email protected]ee094b82010-08-24 15:55:51844 }
mikecirone8b85c432016-09-08 19:11:00845 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_PROC_TASK,
[email protected]cd565142012-06-12 16:21:45846 net_log_callback);
[email protected]ee094b82010-08-24 15:55:51847
[email protected]b3601bc22012-02-21 21:23:20848 callback_.Run(error, results_);
[email protected]b59ff372009-07-15 22:04:32849 }
850
Miriam Gershenson61604662017-09-28 23:51:11851 void RecordTaskHistograms(const base::TimeTicks& start_time,
852 const int error,
853 const int os_error) const {
mmenke91c17162016-06-02 16:03:23854 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54855 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
Miriam Gershenson61604662017-09-28 23:51:11856 if (error == OK)
857 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ProcTask.SuccessTime", duration);
858 else
859 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ProcTask.FailureTime", duration);
[email protected]7e96d792011-06-10 17:08:23860
Miriam Gershenson61604662017-09-28 23:51:11861 UMA_HISTOGRAM_CUSTOM_ENUMERATION(kOSErrorsForGetAddrinfoHistogramName,
862 std::abs(os_error),
863 GetAllGetAddrinfoOSErrors());
[email protected]1e9bbd22010-10-15 16:42:45864 }
865
[email protected]189163e2011-05-11 01:48:54866 void RecordAttemptHistograms(const base::TimeTicks& start_time,
Avi Drissman13fc8932015-12-20 04:40:46867 const uint32_t attempt_number,
[email protected]189163e2011-05-11 01:48:54868 const int error,
869 const int os_error) const {
mmenke91c17162016-06-02 16:03:23870 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54871 bool first_attempt_to_complete =
872 completed_attempt_number_ == attempt_number;
[email protected]e87b8b512011-06-14 22:12:52873 bool is_first_attempt = (attempt_number == 1);
[email protected]1e9bbd22010-10-15 16:42:45874
[email protected]189163e2011-05-11 01:48:54875 if (first_attempt_to_complete) {
876 // If this was first attempt to complete, then record the resolution
877 // status of the attempt.
878 if (completed_attempt_error_ == OK) {
879 UMA_HISTOGRAM_ENUMERATION(
880 "DNS.AttemptFirstSuccess", attempt_number, 100);
881 } else {
882 UMA_HISTOGRAM_ENUMERATION(
883 "DNS.AttemptFirstFailure", attempt_number, 100);
884 }
885 }
886
887 if (error == OK)
888 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptSuccess", attempt_number, 100);
889 else
890 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptFailure", attempt_number, 100);
891
[email protected]e87b8b512011-06-14 22:12:52892 // If first attempt didn't finish before retry attempt, then calculate stats
893 // on how much time is saved by having spawned an extra attempt.
[email protected]0f292de02012-02-01 22:28:20894 if (!first_attempt_to_complete && is_first_attempt && !was_canceled()) {
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21895 UMA_HISTOGRAM_LONG_TIMES_100(
896 "DNS.AttemptTimeSavedByRetry",
897 base::TimeTicks::Now() - retry_attempt_finished_time_);
[email protected]e87b8b512011-06-14 22:12:52898 }
899
[email protected]0f292de02012-02-01 22:28:20900 if (was_canceled() || !first_attempt_to_complete) {
[email protected]189163e2011-05-11 01:48:54901 // Count those attempts which completed after the job was already canceled
902 // OR after the job was already completed by an earlier attempt (so in
903 // effect).
904 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptDiscarded", attempt_number, 100);
905
[email protected]0f292de02012-02-01 22:28:20906 // Record if job is canceled.
907 if (was_canceled())
[email protected]189163e2011-05-11 01:48:54908 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptCancelled", attempt_number, 100);
909 }
910
911 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
912 if (error == OK)
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21913 UMA_HISTOGRAM_LONG_TIMES_100("DNS.AttemptSuccessDuration", duration);
[email protected]189163e2011-05-11 01:48:54914 else
Miriam Gershenson4e7c9ecf2017-09-26 23:17:21915 UMA_HISTOGRAM_LONG_TIMES_100("DNS.AttemptFailDuration", duration);
[email protected]189163e2011-05-11 01:48:54916 }
[email protected]1e9bbd22010-10-15 16:42:45917
anujk.sharma7c907f02015-05-29 02:55:44918 // Set on the task runner thread, read on the worker thread.
[email protected]123ab1e32009-10-21 19:12:57919 Key key_;
[email protected]b59ff372009-07-15 22:04:32920
[email protected]0f292de02012-02-01 22:28:20921 // Holds an owning reference to the HostResolverProc that we are going to use.
[email protected]b59ff372009-07-15 22:04:32922 // This may not be the current resolver procedure by the time we call
923 // ResolveAddrInfo, but that's OK... we'll use it anyways, and the owning
924 // reference ensures that it remains valid until we are done.
[email protected]0f292de02012-02-01 22:28:20925 ProcTaskParams params_;
[email protected]b59ff372009-07-15 22:04:32926
[email protected]0f292de02012-02-01 22:28:20927 // The listener to the results of this ProcTask.
928 Callback callback_;
929
mmenke91c17162016-06-02 16:03:23930 // Used to post events onto the network thread.
931 scoped_refptr<base::SingleThreadTaskRunner> network_task_runner_;
Miriam Gershensone42adb22017-10-16 16:19:38932 // Used to post blocking HostResolverProc tasks.
933 scoped_refptr<base::TaskRunner> proc_task_runner_;
[email protected]189163e2011-05-11 01:48:54934
935 // Keeps track of the number of attempts we have made so far to resolve the
936 // host. Whenever we start an attempt to resolve the host, we increase this
937 // number.
Avi Drissman13fc8932015-12-20 04:40:46938 uint32_t attempt_number_;
[email protected]189163e2011-05-11 01:48:54939
940 // The index of the attempt which finished first (or 0 if the job is still in
941 // progress).
Avi Drissman13fc8932015-12-20 04:40:46942 uint32_t completed_attempt_number_;
[email protected]189163e2011-05-11 01:48:54943
944 // The result (a net error code) from the first attempt to complete.
945 int completed_attempt_error_;
[email protected]252b699b2010-02-05 21:38:06946
[email protected]e87b8b512011-06-14 22:12:52947 // The time when retry attempt was finished.
948 base::TimeTicks retry_attempt_finished_time_;
949
[email protected]b59ff372009-07-15 22:04:32950 AddressList results_;
951
tfarina428341112016-09-22 13:38:20952 NetLogWithSource net_log_;
[email protected]ee094b82010-08-24 15:55:51953
[email protected]0f292de02012-02-01 22:28:20954 DISALLOW_COPY_AND_ASSIGN(ProcTask);
[email protected]b59ff372009-07-15 22:04:32955};
956
957//-----------------------------------------------------------------------------
958
[email protected]b3601bc22012-02-21 21:23:20959// Resolves the hostname using DnsTransaction.
960// TODO(szym): This could be moved to separate source file as well.
[email protected]0adcb2b2012-08-15 21:30:46961class HostResolverImpl::DnsTask : public base::SupportsWeakPtr<DnsTask> {
[email protected]b3601bc22012-02-21 21:23:20962 public:
[email protected]daae1322013-09-05 18:26:50963 class Delegate {
964 public:
965 virtual void OnDnsTaskComplete(base::TimeTicks start_time,
966 int net_error,
967 const AddressList& addr_list,
968 base::TimeDelta ttl) = 0;
969
970 // Called when the first of two jobs succeeds. If the first completed
971 // transaction fails, this is not called. Also not called when the DnsTask
972 // only needs to run one transaction.
973 virtual void OnFirstDnsTransactionComplete() = 0;
974
975 protected:
Chris Watkins68b15032017-12-01 03:07:13976 Delegate() = default;
977 virtual ~Delegate() = default;
[email protected]daae1322013-09-05 18:26:50978 };
[email protected]b3601bc22012-02-21 21:23:20979
[email protected]0adcb2b2012-08-15 21:30:46980 DnsTask(DnsClient* client,
[email protected]b3601bc22012-02-21 21:23:20981 const Key& key,
[email protected]daae1322013-09-05 18:26:50982 Delegate* delegate,
tfarina428341112016-09-22 13:38:20983 const NetLogWithSource& job_net_log)
[email protected]0adcb2b2012-08-15 21:30:46984 : client_(client),
[email protected]daae1322013-09-05 18:26:50985 key_(key),
986 delegate_(delegate),
987 net_log_(job_net_log),
988 num_completed_transactions_(0),
989 task_start_time_(base::TimeTicks::Now()) {
[email protected]0adcb2b2012-08-15 21:30:46990 DCHECK(client);
[email protected]daae1322013-09-05 18:26:50991 DCHECK(delegate_);
[email protected]1affed62013-08-21 03:24:50992 }
993
[email protected]daae1322013-09-05 18:26:50994 bool needs_two_transactions() const {
995 return key_.address_family == ADDRESS_FAMILY_UNSPECIFIED;
996 }
997
998 bool needs_another_transaction() const {
999 return needs_two_transactions() && !transaction_aaaa_;
1000 }
1001
1002 void StartFirstTransaction() {
1003 DCHECK_EQ(0u, num_completed_transactions_);
mikecirone8b85c432016-09-08 19:11:001004 net_log_.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_DNS_TASK);
[email protected]daae1322013-09-05 18:26:501005 if (key_.address_family == ADDRESS_FAMILY_IPV6) {
1006 StartAAAA();
1007 } else {
1008 StartA();
1009 }
1010 }
1011
1012 void StartSecondTransaction() {
1013 DCHECK(needs_two_transactions());
1014 StartAAAA();
[email protected]70c04ab2013-08-22 16:05:121015 }
1016
1017 private:
[email protected]daae1322013-09-05 18:26:501018 void StartA() {
1019 DCHECK(!transaction_a_);
1020 DCHECK_NE(ADDRESS_FAMILY_IPV6, key_.address_family);
1021 transaction_a_ = CreateTransaction(ADDRESS_FAMILY_IPV4);
1022 transaction_a_->Start();
1023 }
1024
1025 void StartAAAA() {
1026 DCHECK(!transaction_aaaa_);
1027 DCHECK_NE(ADDRESS_FAMILY_IPV4, key_.address_family);
1028 transaction_aaaa_ = CreateTransaction(ADDRESS_FAMILY_IPV6);
1029 transaction_aaaa_->Start();
1030 }
1031
danakj22f90e72016-04-16 01:55:401032 std::unique_ptr<DnsTransaction> CreateTransaction(AddressFamily family) {
[email protected]daae1322013-09-05 18:26:501033 DCHECK_NE(ADDRESS_FAMILY_UNSPECIFIED, family);
1034 return client_->GetTransactionFactory()->CreateTransaction(
1035 key_.hostname,
1036 family == ADDRESS_FAMILY_IPV6 ? dns_protocol::kTypeAAAA :
1037 dns_protocol::kTypeA,
1038 base::Bind(&DnsTask::OnTransactionComplete, base::Unretained(this),
1039 base::TimeTicks::Now()),
1040 net_log_);
1041 }
1042
1043 void OnTransactionComplete(const base::TimeTicks& start_time,
[email protected]1def74c2012-03-22 20:07:001044 DnsTransaction* transaction,
[email protected]b3601bc22012-02-21 21:23:201045 int net_error,
1046 const DnsResponse* response) {
[email protected]add76532012-03-30 14:47:471047 DCHECK(transaction);
[email protected]02cd6982013-01-10 20:12:511048 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
Miriam Gershenson66024d72017-12-05 04:30:321049 if (net_error != OK) {
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211050 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.TransactionFailure", duration);
[email protected]0adcb2b2012-08-15 21:30:461051 OnFailure(net_error, DnsResponse::DNS_PARSE_OK);
1052 return;
[email protected]6c411902012-08-14 22:36:361053 }
[email protected]0adcb2b2012-08-15 21:30:461054
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211055 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.TransactionSuccess", duration);
[email protected]02cd6982013-01-10 20:12:511056 switch (transaction->GetType()) {
1057 case dns_protocol::kTypeA:
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211058 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.TransactionSuccess_A", duration);
[email protected]02cd6982013-01-10 20:12:511059 break;
1060 case dns_protocol::kTypeAAAA:
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211061 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.TransactionSuccess_AAAA",
1062 duration);
[email protected]02cd6982013-01-10 20:12:511063 break;
1064 }
[email protected]daae1322013-09-05 18:26:501065
[email protected]0adcb2b2012-08-15 21:30:461066 AddressList addr_list;
1067 base::TimeDelta ttl;
1068 DnsResponse::Result result = response->ParseToAddressList(&addr_list, &ttl);
1069 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ParseToAddressList",
1070 result,
1071 DnsResponse::DNS_PARSE_RESULT_MAX);
1072 if (result != DnsResponse::DNS_PARSE_OK) {
1073 // Fail even if the other query succeeds.
1074 OnFailure(ERR_DNS_MALFORMED_RESPONSE, result);
1075 return;
1076 }
1077
[email protected]daae1322013-09-05 18:26:501078 ++num_completed_transactions_;
1079 if (num_completed_transactions_ == 1) {
1080 ttl_ = ttl;
[email protected]0adcb2b2012-08-15 21:30:461081 } else {
[email protected]daae1322013-09-05 18:26:501082 ttl_ = std::min(ttl_, ttl);
[email protected]0adcb2b2012-08-15 21:30:461083 }
1084
[email protected]daae1322013-09-05 18:26:501085 if (transaction->GetType() == dns_protocol::kTypeA) {
1086 DCHECK_EQ(transaction_a_.get(), transaction);
1087 // Place IPv4 addresses after IPv6.
1088 addr_list_.insert(addr_list_.end(), addr_list.begin(), addr_list.end());
1089 } else {
1090 DCHECK_EQ(transaction_aaaa_.get(), transaction);
1091 // Place IPv6 addresses before IPv4.
1092 addr_list_.insert(addr_list_.begin(), addr_list.begin(), addr_list.end());
1093 }
1094
1095 if (needs_two_transactions() && num_completed_transactions_ == 1) {
1096 // No need to repeat the suffix search.
1097 key_.hostname = transaction->GetHostname();
1098 delegate_->OnFirstDnsTransactionComplete();
1099 return;
1100 }
1101
1102 if (addr_list_.empty()) {
[email protected]70c04ab2013-08-22 16:05:121103 // TODO(szym): Don't fallback to ProcTask in this case.
1104 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
[email protected]0adcb2b2012-08-15 21:30:461105 return;
1106 }
1107
[email protected]daae1322013-09-05 18:26:501108 // If there are multiple addresses, and at least one is IPv6, need to sort
1109 // them. Note that IPv6 addresses are always put before IPv4 ones, so it's
1110 // sufficient to just check the family of the first address.
1111 if (addr_list_.size() > 1 &&
1112 addr_list_[0].GetFamily() == ADDRESS_FAMILY_IPV6) {
1113 // Sort addresses if needed. Sort could complete synchronously.
[email protected]0adcb2b2012-08-15 21:30:461114 client_->GetAddressSorter()->Sort(
[email protected]daae1322013-09-05 18:26:501115 addr_list_,
[email protected]4589a3a2012-09-20 20:57:071116 base::Bind(&DnsTask::OnSortComplete,
1117 AsWeakPtr(),
[email protected]daae1322013-09-05 18:26:501118 base::TimeTicks::Now()));
[email protected]0adcb2b2012-08-15 21:30:461119 } else {
[email protected]daae1322013-09-05 18:26:501120 OnSuccess(addr_list_);
[email protected]0adcb2b2012-08-15 21:30:461121 }
1122 }
1123
1124 void OnSortComplete(base::TimeTicks start_time,
[email protected]0adcb2b2012-08-15 21:30:461125 bool success,
1126 const AddressList& addr_list) {
1127 if (!success) {
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211128 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.SortFailure",
1129 base::TimeTicks::Now() - start_time);
[email protected]0adcb2b2012-08-15 21:30:461130 OnFailure(ERR_DNS_SORT_ERROR, DnsResponse::DNS_PARSE_OK);
1131 return;
1132 }
1133
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211134 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.SortSuccess",
1135 base::TimeTicks::Now() - start_time);
[email protected]0adcb2b2012-08-15 21:30:461136
1137 // AddressSorter prunes unusable destinations.
1138 if (addr_list.empty()) {
1139 LOG(WARNING) << "Address list empty after RFC3484 sort";
1140 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
1141 return;
1142 }
1143
[email protected]daae1322013-09-05 18:26:501144 OnSuccess(addr_list);
[email protected]0adcb2b2012-08-15 21:30:461145 }
1146
1147 void OnFailure(int net_error, DnsResponse::Result result) {
1148 DCHECK_NE(OK, net_error);
[email protected]cd565142012-06-12 16:21:451149 net_log_.EndEvent(
mikecirone8b85c432016-09-08 19:11:001150 NetLogEventType::HOST_RESOLVER_IMPL_DNS_TASK,
[email protected]cd565142012-06-12 16:21:451151 base::Bind(&NetLogDnsTaskFailedCallback, net_error, result));
Miriam Gershenson66024d72017-12-05 04:30:321152 delegate_->OnDnsTaskComplete(task_start_time_, net_error, AddressList(),
1153 base::TimeDelta());
[email protected]b3601bc22012-02-21 21:23:201154 }
1155
[email protected]daae1322013-09-05 18:26:501156 void OnSuccess(const AddressList& addr_list) {
mikecirone8b85c432016-09-08 19:11:001157 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_DNS_TASK,
[email protected]0adcb2b2012-08-15 21:30:461158 addr_list.CreateNetLogCallback());
[email protected]daae1322013-09-05 18:26:501159 delegate_->OnDnsTaskComplete(task_start_time_, OK, addr_list, ttl_);
[email protected]0adcb2b2012-08-15 21:30:461160 }
1161
1162 DnsClient* client_;
[email protected]daae1322013-09-05 18:26:501163 Key key_;
1164
[email protected]b3601bc22012-02-21 21:23:201165 // The listener to the results of this DnsTask.
[email protected]daae1322013-09-05 18:26:501166 Delegate* delegate_;
tfarina428341112016-09-22 13:38:201167 const NetLogWithSource net_log_;
[email protected]b3601bc22012-02-21 21:23:201168
danakj22f90e72016-04-16 01:55:401169 std::unique_ptr<DnsTransaction> transaction_a_;
1170 std::unique_ptr<DnsTransaction> transaction_aaaa_;
[email protected]0adcb2b2012-08-15 21:30:461171
[email protected]daae1322013-09-05 18:26:501172 unsigned num_completed_transactions_;
1173
1174 // These are updated as each transaction completes.
1175 base::TimeDelta ttl_;
1176 // IPv6 addresses must appear first in the list.
1177 AddressList addr_list_;
1178
1179 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,
tfarina428341112016-09-22 13:38:201196 const NetLogWithSource& source_net_log)
[email protected]12faa4c2012-11-06 04:44:181197 : resolver_(resolver),
[email protected]0f292de02012-02-01 22:28:201198 key_(key),
[email protected]8c98d002012-07-18 19:02:271199 priority_tracker_(priority),
Miriam Gershensone42adb22017-10-16 16:19:381200 proc_task_runner_(std::move(proc_task_runner)),
[email protected]0f292de02012-02-01 22:28:201201 had_non_speculative_request_(false),
[email protected]51b9a6b2012-06-25 21:50:291202 had_dns_config_(false),
[email protected]daae1322013-09-05 18:26:501203 num_occupied_job_slots_(0),
[email protected]1d932852012-06-19 19:40:331204 dns_task_error_(OK),
[email protected]51b9a6b2012-06-25 21:50:291205 creation_time_(base::TimeTicks::Now()),
1206 priority_change_time_(creation_time_),
tfarina428341112016-09-22 13:38:201207 net_log_(
1208 NetLogWithSource::Make(source_net_log.net_log(),
mikecirone8b85c432016-09-08 19:11:001209 NetLogSourceType::HOST_RESOLVER_IMPL_JOB)) {
1210 source_net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_CREATE_JOB);
[email protected]0f292de02012-02-01 22:28:201211
mikecirone8b85c432016-09-08 19:11:001212 net_log_.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
1213 base::Bind(&NetLogJobCreationCallback,
1214 source_net_log.source(), &key_.hostname));
[email protected]68ad3ee2010-01-30 03:45:391215 }
1216
dchengb03027d2014-10-21 12:00:201217 ~Job() override {
[email protected]b3601bc22012-02-21 21:23:201218 if (is_running()) {
1219 // |resolver_| was destroyed with this Job still in flight.
1220 // Clean-up, record in the log, but don't run any callbacks.
1221 if (is_proc_running()) {
[email protected]0f292de02012-02-01 22:28:201222 proc_task_->Cancel();
wezb9820d42016-06-22 23:41:041223 proc_task_ = nullptr;
[email protected]0f292de02012-02-01 22:28:201224 }
[email protected]16ee26d2012-03-08 03:34:351225 // Clean up now for nice NetLog.
[email protected]daae1322013-09-05 18:26:501226 KillDnsTask();
mikecirone8b85c432016-09-08 19:11:001227 net_log_.EndEventWithNetErrorCode(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
[email protected]b3601bc22012-02-21 21:23:201228 ERR_ABORTED);
1229 } else if (is_queued()) {
[email protected]57a48d32012-03-03 00:04:551230 // |resolver_| was destroyed without running this Job.
[email protected]16ee26d2012-03-08 03:34:351231 // TODO(szym): is there any benefit in having this distinction?
mikecirone8b85c432016-09-08 19:11:001232 net_log_.AddEvent(NetLogEventType::CANCELLED);
1233 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB);
[email protected]68ad3ee2010-01-30 03:45:391234 }
[email protected]b3601bc22012-02-21 21:23:201235 // else CompleteRequests logged EndEvent.
maksim.sisov31452af2016-07-27 06:38:101236 if (!requests_.empty()) {
1237 // Log any remaining Requests as cancelled.
1238 for (RequestImpl* req : requests_) {
1239 DCHECK_EQ(this, req->job());
maksim.sisov31452af2016-07-27 06:38:101240 LogCancelRequest(req->source_net_log(), req->info());
maksim.sisov320d5962016-08-15 18:02:511241 req->OnJobCancelled(this);
maksim.sisov31452af2016-07-27 06:38:101242 }
1243 requests_.clear();
[email protected]b3601bc22012-02-21 21:23:201244 }
[email protected]68ad3ee2010-01-30 03:45:391245 }
1246
[email protected]daae1322013-09-05 18:26:501247 // Add this job to the dispatcher. If "at_head" is true, adds at the front
1248 // of the queue.
1249 void Schedule(bool at_head) {
1250 DCHECK(!is_queued());
1251 PrioritizedDispatcher::Handle handle;
1252 if (!at_head) {
[email protected]106ccd2c2014-06-17 09:21:001253 handle = resolver_->dispatcher_->Add(this, priority());
[email protected]daae1322013-09-05 18:26:501254 } else {
[email protected]106ccd2c2014-06-17 09:21:001255 handle = resolver_->dispatcher_->AddAtHead(this, priority());
[email protected]daae1322013-09-05 18:26:501256 }
1257 // The dispatcher could have started |this| in the above call to Add, which
1258 // could have called Schedule again. In that case |handle| will be null,
1259 // but |handle_| may have been set by the other nested call to Schedule.
1260 if (!handle.is_null()) {
1261 DCHECK(handle_.is_null());
1262 handle_ = handle;
1263 }
[email protected]16ee26d2012-03-08 03:34:351264 }
1265
maksim.sisov31452af2016-07-27 06:38:101266 void AddRequest(RequestImpl* request) {
1267 DCHECK_EQ(key_.hostname, request->info().hostname());
[email protected]0f292de02012-02-01 22:28:201268
maksim.sisov31452af2016-07-27 06:38:101269 priority_tracker_.Add(request->priority());
[email protected]0f292de02012-02-01 22:28:201270
maksim.sisov31452af2016-07-27 06:38:101271 request->source_net_log().AddEvent(
mikecirone8b85c432016-09-08 19:11:001272 NetLogEventType::HOST_RESOLVER_IMPL_JOB_ATTACH,
[email protected]cd565142012-06-12 16:21:451273 net_log_.source().ToEventParametersCallback());
[email protected]0f292de02012-02-01 22:28:201274
1275 net_log_.AddEvent(
mikecirone8b85c432016-09-08 19:11:001276 NetLogEventType::HOST_RESOLVER_IMPL_JOB_REQUEST_ATTACH,
maksim.sisov31452af2016-07-27 06:38:101277 base::Bind(&NetLogJobAttachCallback, request->source_net_log().source(),
[email protected]cd565142012-06-12 16:21:451278 priority()));
[email protected]0f292de02012-02-01 22:28:201279
Miriam Gershenson61604662017-09-28 23:51:111280 if (!request->info().is_speculative())
[email protected]0f292de02012-02-01 22:28:201281 had_non_speculative_request_ = true;
[email protected]b3601bc22012-02-21 21:23:201282
maksim.sisov31452af2016-07-27 06:38:101283 requests_.push_back(request);
[email protected]b3601bc22012-02-21 21:23:201284
[email protected]51b9a6b2012-06-25 21:50:291285 UpdatePriority();
[email protected]68ad3ee2010-01-30 03:45:391286 }
1287
maksim.sisov31452af2016-07-27 06:38:101288 void ChangeRequestPriority(RequestImpl* req, RequestPriority priority) {
juliatuttlec53b19a72016-05-05 13:51:311289 DCHECK_EQ(key_.hostname, req->info().hostname());
juliatuttlec53b19a72016-05-05 13:51:311290
1291 priority_tracker_.Remove(req->priority());
1292 req->set_priority(priority);
1293 priority_tracker_.Add(req->priority());
1294 UpdatePriority();
1295 }
1296
maksim.sisov31452af2016-07-27 06:38:101297 // Detach cancelled request. If it was the last active Request, also finishes
1298 // this Job.
1299 void CancelRequest(RequestImpl* request) {
1300 DCHECK_EQ(key_.hostname, request->info().hostname());
1301 DCHECK(!requests_.empty());
[email protected]16ee26d2012-03-08 03:34:351302
maksim.sisov31452af2016-07-27 06:38:101303 LogCancelRequest(request->source_net_log(), request->info());
[email protected]16ee26d2012-03-08 03:34:351304
maksim.sisov31452af2016-07-27 06:38:101305 priority_tracker_.Remove(request->priority());
1306 net_log_.AddEvent(
mikecirone8b85c432016-09-08 19:11:001307 NetLogEventType::HOST_RESOLVER_IMPL_JOB_REQUEST_DETACH,
maksim.sisov31452af2016-07-27 06:38:101308 base::Bind(&NetLogJobAttachCallback, request->source_net_log().source(),
1309 priority()));
[email protected]b3601bc22012-02-21 21:23:201310
[email protected]16ee26d2012-03-08 03:34:351311 if (num_active_requests() > 0) {
[email protected]51b9a6b2012-06-25 21:50:291312 UpdatePriority();
maksim.sisov31452af2016-07-27 06:38:101313 RemoveRequest(request);
[email protected]16ee26d2012-03-08 03:34:351314 } else {
1315 // If we were called from a Request's callback within CompleteRequests,
1316 // that Request could not have been cancelled, so num_active_requests()
1317 // could not be 0. Therefore, we are not in CompleteRequests().
[email protected]1339a2a22012-10-17 08:39:431318 CompleteRequestsWithError(OK /* cancelled */);
[email protected]b3601bc22012-02-21 21:23:201319 }
[email protected]68ad3ee2010-01-30 03:45:391320 }
1321
maksim.sisov31452af2016-07-27 06:38:101322 void RemoveRequest(RequestImpl* request) {
1323 auto it = std::find(requests_.begin(), requests_.end(), request);
1324 DCHECK(it != requests_.end());
1325 requests_.erase(it);
1326 }
1327
[email protected]7af985a2012-12-14 22:40:421328 // Called from AbortAllInProgressJobs. Completes all requests and destroys
1329 // the job. This currently assumes the abort is due to a network change.
olli.raulaa21e9eb72015-12-17 08:18:111330 // TODO This should not delete |this|.
[email protected]0f292de02012-02-01 22:28:201331 void Abort() {
[email protected]0f292de02012-02-01 22:28:201332 DCHECK(is_running());
[email protected]7af985a2012-12-14 22:40:421333 CompleteRequestsWithError(ERR_NETWORK_CHANGED);
[email protected]b3601bc22012-02-21 21:23:201334 }
1335
[email protected]f0f602bd2012-11-15 18:01:021336 // If DnsTask present, abort it and fall back to ProcTask.
1337 void AbortDnsTask() {
1338 if (dns_task_) {
[email protected]daae1322013-09-05 18:26:501339 KillDnsTask();
[email protected]f0f602bd2012-11-15 18:01:021340 dns_task_error_ = OK;
1341 StartProcTask();
1342 }
1343 }
1344
[email protected]16ee26d2012-03-08 03:34:351345 // Called by HostResolverImpl when this job is evicted due to queue overflow.
1346 // Completes all requests and destroys the job.
1347 void OnEvicted() {
1348 DCHECK(!is_running());
1349 DCHECK(is_queued());
1350 handle_.Reset();
1351
mikecirone8b85c432016-09-08 19:11:001352 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB_EVICTED);
[email protected]16ee26d2012-03-08 03:34:351353
1354 // This signals to CompleteRequests that this job never ran.
[email protected]1339a2a22012-10-17 08:39:431355 CompleteRequestsWithError(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
[email protected]16ee26d2012-03-08 03:34:351356 }
1357
[email protected]78eac2a2012-03-14 19:09:271358 // Attempts to serve the job from HOSTS. Returns true if succeeded and
1359 // this Job was destroyed.
1360 bool ServeFromHosts() {
1361 DCHECK_GT(num_active_requests(), 0u);
1362 AddressList addr_list;
1363 if (resolver_->ServeFromHosts(key(),
[email protected]3cb676a12012-06-30 15:46:031364 requests_.front()->info(),
[email protected]78eac2a2012-03-14 19:09:271365 &addr_list)) {
1366 // This will destroy the Job.
Rob Percival94f21ad2017-11-14 10:20:241367 CompleteRequests(
1368 MakeCacheEntry(OK, addr_list, HostCache::Entry::SOURCE_HOSTS),
1369 base::TimeDelta());
[email protected]78eac2a2012-03-14 19:09:271370 return true;
1371 }
1372 return false;
1373 }
1374
tanay.c6ddd5f6f2015-08-25 06:34:571375 const Key& key() const { return key_; }
[email protected]b4481b222012-03-16 17:13:111376
1377 bool is_queued() const {
1378 return !handle_.is_null();
1379 }
1380
1381 bool is_running() const {
1382 return is_dns_running() || is_proc_running();
1383 }
1384
[email protected]16ee26d2012-03-08 03:34:351385 private:
[email protected]daae1322013-09-05 18:26:501386 void KillDnsTask() {
1387 if (dns_task_) {
1388 ReduceToOneJobSlot();
1389 dns_task_.reset();
1390 }
1391 }
1392
1393 // Reduce the number of job slots occupied and queued in the dispatcher
1394 // to one. If the second Job slot is queued in the dispatcher, cancels the
1395 // queued job. Otherwise, the second Job has been started by the
1396 // PrioritizedDispatcher, so signals it is complete.
1397 void ReduceToOneJobSlot() {
1398 DCHECK_GE(num_occupied_job_slots_, 1u);
1399 if (is_queued()) {
[email protected]106ccd2c2014-06-17 09:21:001400 resolver_->dispatcher_->Cancel(handle_);
[email protected]daae1322013-09-05 18:26:501401 handle_.Reset();
1402 } else if (num_occupied_job_slots_ > 1) {
[email protected]106ccd2c2014-06-17 09:21:001403 resolver_->dispatcher_->OnJobFinished();
[email protected]daae1322013-09-05 18:26:501404 --num_occupied_job_slots_;
1405 }
1406 DCHECK_EQ(1u, num_occupied_job_slots_);
1407 }
1408
eroman0cd87b62016-12-14 19:13:451409 // MakeCacheEntry() and MakeCacheEntryWithTTL() are helpers to build a
1410 // HostCache::Entry(). The address list is omited from the cache entry
1411 // for errors.
1412 HostCache::Entry MakeCacheEntry(int net_error,
Rob Percival94f21ad2017-11-14 10:20:241413 const AddressList& addr_list,
1414 HostCache::Entry::Source source) const {
eroman0cd87b62016-12-14 19:13:451415 return HostCache::Entry(
1416 net_error,
Rob Percival94f21ad2017-11-14 10:20:241417 net_error == OK ? MakeAddressListForRequest(addr_list) : AddressList(),
1418 source);
eroman0cd87b62016-12-14 19:13:451419 }
1420
1421 HostCache::Entry MakeCacheEntryWithTTL(int net_error,
1422 const AddressList& addr_list,
Rob Percival94f21ad2017-11-14 10:20:241423 HostCache::Entry::Source source,
eroman0cd87b62016-12-14 19:13:451424 base::TimeDelta ttl) const {
1425 return HostCache::Entry(
1426 net_error,
1427 net_error == OK ? MakeAddressListForRequest(addr_list) : AddressList(),
Rob Percival94f21ad2017-11-14 10:20:241428 source, ttl);
eroman0cd87b62016-12-14 19:13:451429 }
1430
juliatuttlec53b19a72016-05-05 13:51:311431 AddressList MakeAddressListForRequest(const AddressList& list) const {
1432 if (requests_.empty())
1433 return list;
1434 return AddressList::CopyWithPort(list, requests_.front()->info().port());
1435 }
1436
[email protected]51b9a6b2012-06-25 21:50:291437 void UpdatePriority() {
1438 if (is_queued()) {
1439 if (priority() != static_cast<RequestPriority>(handle_.priority()))
1440 priority_change_time_ = base::TimeTicks::Now();
[email protected]106ccd2c2014-06-17 09:21:001441 handle_ = resolver_->dispatcher_->ChangePriority(handle_, priority());
[email protected]51b9a6b2012-06-25 21:50:291442 }
1443 }
1444
[email protected]16ee26d2012-03-08 03:34:351445 // PriorityDispatch::Job:
dchengb03027d2014-10-21 12:00:201446 void Start() override {
[email protected]daae1322013-09-05 18:26:501447 DCHECK_LE(num_occupied_job_slots_, 1u);
1448
[email protected]70c04ab2013-08-22 16:05:121449 handle_.Reset();
[email protected]daae1322013-09-05 18:26:501450 ++num_occupied_job_slots_;
1451
1452 if (num_occupied_job_slots_ == 2) {
1453 StartSecondDnsTransaction();
1454 return;
1455 }
1456
1457 DCHECK(!is_running());
[email protected]0f292de02012-02-01 22:28:201458
mikecirone8b85c432016-09-08 19:11:001459 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB_STARTED);
[email protected]0f292de02012-02-01 22:28:201460
[email protected]51b9a6b2012-06-25 21:50:291461 had_dns_config_ = resolver_->HaveDnsConfig();
1462
Miriam Gershenson61604662017-09-28 23:51:111463 start_time_ = base::TimeTicks::Now();
1464 base::TimeDelta queue_time = start_time_ - creation_time_;
1465 base::TimeDelta queue_time_after_change =
1466 start_time_ - priority_change_time_;
[email protected]51b9a6b2012-06-25 21:50:291467
Miriam Gershenson90d05e02017-09-28 19:29:281468 DNS_HISTOGRAM_BY_PRIORITY("Net.DNS.JobQueueTime", priority(), queue_time);
1469 DNS_HISTOGRAM_BY_PRIORITY("Net.DNS.JobQueueTimeAfterChange", priority(),
1470 queue_time_after_change);
[email protected]51b9a6b2012-06-25 21:50:291471
[email protected]443714fad2013-09-19 04:52:011472 bool system_only =
1473 (key_.host_resolver_flags & HOST_RESOLVER_SYSTEM_ONLY) != 0;
1474
[email protected]1d932852012-06-19 19:40:331475 // Caution: Job::Start must not complete synchronously.
[email protected]443714fad2013-09-19 04:52:011476 if (!system_only && had_dns_config_ &&
1477 !ResemblesMulticastDNSName(key_.hostname)) {
[email protected]b3601bc22012-02-21 21:23:201478 StartDnsTask();
1479 } else {
1480 StartProcTask();
1481 }
1482 }
1483
[email protected]b3601bc22012-02-21 21:23:201484 // TODO(szym): Since DnsTransaction does not consume threads, we can increase
Francois Doraya2d01ba2017-09-25 19:17:401485 // the limits on |dispatcher_|. But in order to keep the number of
1486 // TaskScheduler threads low, we will need to use an "inner"
1487 // PrioritizedDispatcher with tighter limits.
[email protected]b3601bc22012-02-21 21:23:201488 void StartProcTask() {
[email protected]16ee26d2012-03-08 03:34:351489 DCHECK(!is_dns_running());
mmenke91c17162016-06-02 16:03:231490 proc_task_ =
1491 new ProcTask(key_, resolver_->proc_params_,
1492 base::Bind(&Job::OnProcTaskComplete,
1493 base::Unretained(this), base::TimeTicks::Now()),
Miriam Gershensone42adb22017-10-16 16:19:381494 proc_task_runner_, net_log_);
[email protected]0f292de02012-02-01 22:28:201495
[email protected]0f292de02012-02-01 22:28:201496 // Start() could be called from within Resolve(), hence it must NOT directly
1497 // call OnProcTaskComplete, for example, on synchronous failure.
1498 proc_task_->Start();
[email protected]68ad3ee2010-01-30 03:45:391499 }
1500
[email protected]0f292de02012-02-01 22:28:201501 // Called by ProcTask when it completes.
[email protected]e3bd4822012-10-23 18:01:371502 void OnProcTaskComplete(base::TimeTicks start_time,
1503 int net_error,
1504 const AddressList& addr_list) {
[email protected]b3601bc22012-02-21 21:23:201505 DCHECK(is_proc_running());
[email protected]68ad3ee2010-01-30 03:45:391506
[email protected]1d932852012-06-19 19:40:331507 if (dns_task_error_ != OK) {
[email protected]e3bd4822012-10-23 18:01:371508 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]1def74c2012-03-22 20:07:001509 if (net_error == OK) {
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211510 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.FallbackSuccess", duration);
[email protected]1d932852012-06-19 19:40:331511 if ((dns_task_error_ == ERR_NAME_NOT_RESOLVED) &&
1512 ResemblesNetBIOSName(key_.hostname)) {
1513 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_SUSPECT_NETBIOS);
1514 } else {
1515 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_PROC_SUCCESS);
1516 }
Ilya Sherman0eb39802017-12-08 20:58:181517 base::UmaHistogramSparse("Net.DNS.DnsTask.Errors",
1518 std::abs(dns_task_error_));
[email protected]1ffdda82012-12-12 23:04:221519 resolver_->OnDnsTaskResolve(dns_task_error_);
[email protected]1def74c2012-03-22 20:07:001520 } else {
Miriam Gershenson4e7c9ecf2017-09-26 23:17:211521 UMA_HISTOGRAM_LONG_TIMES_100("AsyncDNS.FallbackFail", duration);
[email protected]1def74c2012-03-22 20:07:001522 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
1523 }
1524 }
1525
eroman1efc237c2016-12-14 00:00:451526 if (ContainsIcannNameCollisionIp(addr_list))
1527 net_error = ERR_ICANN_NAME_COLLISION;
1528
[email protected]1339a2a22012-10-17 08:39:431529 base::TimeDelta ttl =
1530 base::TimeDelta::FromSeconds(kNegativeCacheEntryTTLSeconds);
[email protected]b3601bc22012-02-21 21:23:201531 if (net_error == OK)
1532 ttl = base::TimeDelta::FromSeconds(kCacheEntryTTLSeconds);
[email protected]68ad3ee2010-01-30 03:45:391533
Rob Percival94f21ad2017-11-14 10:20:241534 // Source unknown because the system resolver could have gotten it from a
1535 // hosts file, its own cache, a DNS lookup or somewhere else.
[email protected]895123222012-10-25 15:21:171536 // Don't store the |ttl| in cache since it's not obtained from the server.
Rob Percival94f21ad2017-11-14 10:20:241537 CompleteRequests(
1538 MakeCacheEntry(net_error, addr_list, HostCache::Entry::SOURCE_UNKNOWN),
1539 ttl);
[email protected]b3601bc22012-02-21 21:23:201540 }
1541
1542 void StartDnsTask() {
[email protected]78eac2a2012-03-14 19:09:271543 DCHECK(resolver_->HaveDnsConfig());
[email protected]daae1322013-09-05 18:26:501544 dns_task_.reset(new DnsTask(resolver_->dns_client_.get(), key_, this,
1545 net_log_));
[email protected]b3601bc22012-02-21 21:23:201546
[email protected]daae1322013-09-05 18:26:501547 dns_task_->StartFirstTransaction();
1548 // Schedule a second transaction, if needed.
1549 if (dns_task_->needs_two_transactions())
1550 Schedule(true);
1551 }
1552
1553 void StartSecondDnsTransaction() {
1554 DCHECK(dns_task_->needs_two_transactions());
1555 dns_task_->StartSecondTransaction();
[email protected]16c2bd72013-06-28 01:19:221556 }
1557
1558 // Called if DnsTask fails. It is posted from StartDnsTask, so Job may be
1559 // deleted before this callback. In this case dns_task is deleted as well,
1560 // so we use it as indicator whether Job is still valid.
1561 void OnDnsTaskFailure(const base::WeakPtr<DnsTask>& dns_task,
1562 base::TimeDelta duration,
1563 int net_error) {
Miriam Gershenson61604662017-09-28 23:51:111564 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.DnsTask.FailureTime", duration);
[email protected]16c2bd72013-06-28 01:19:221565
wezb9820d42016-06-22 23:41:041566 if (!dns_task)
[email protected]16c2bd72013-06-28 01:19:221567 return;
1568
1569 dns_task_error_ = net_error;
1570
1571 // TODO(szym): Run ServeFromHosts now if nsswitch.conf says so.
1572 // http://crbug.com/117655
1573
1574 // TODO(szym): Some net errors indicate lack of connectivity. Starting
1575 // ProcTask in that case is a waste of time.
1576 if (resolver_->fallback_to_proctask_) {
[email protected]daae1322013-09-05 18:26:501577 KillDnsTask();
[email protected]16c2bd72013-06-28 01:19:221578 StartProcTask();
1579 } else {
1580 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
Miriam Gershenson66024d72017-12-05 04:30:321581 CompleteRequestsWithError(net_error);
[email protected]b3601bc22012-02-21 21:23:201582 }
1583 }
1584
[email protected]daae1322013-09-05 18:26:501585
1586 // HostResolverImpl::DnsTask::Delegate implementation:
1587
dchengb03027d2014-10-21 12:00:201588 void OnDnsTaskComplete(base::TimeTicks start_time,
1589 int net_error,
1590 const AddressList& addr_list,
1591 base::TimeDelta ttl) override {
[email protected]b3601bc22012-02-21 21:23:201592 DCHECK(is_dns_running());
[email protected]b3601bc22012-02-21 21:23:201593
[email protected]e3bd4822012-10-23 18:01:371594 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]b3601bc22012-02-21 21:23:201595 if (net_error != OK) {
[email protected]16c2bd72013-06-28 01:19:221596 OnDnsTaskFailure(dns_task_->AsWeakPtr(), duration, net_error);
[email protected]b3601bc22012-02-21 21:23:201597 return;
1598 }
Miriam Gershenson61604662017-09-28 23:51:111599
1600 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.DnsTask.SuccessTime", duration);
[email protected]b3601bc22012-02-21 21:23:201601
[email protected]1def74c2012-03-22 20:07:001602 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_DNS_SUCCESS);
[email protected]1339a2a22012-10-17 08:39:431603 RecordTTL(ttl);
[email protected]0adcb2b2012-08-15 21:30:461604
[email protected]1ffdda82012-12-12 23:04:221605 resolver_->OnDnsTaskResolve(OK);
[email protected]f0f602bd2012-11-15 18:01:021606
[email protected]895123222012-10-25 15:21:171607 base::TimeDelta bounded_ttl =
1608 std::max(ttl, base::TimeDelta::FromSeconds(kMinimumTTLSeconds));
1609
eroman0cd87b62016-12-14 19:13:451610 if (ContainsIcannNameCollisionIp(addr_list)) {
1611 CompleteRequestsWithError(ERR_ICANN_NAME_COLLISION);
1612 } else {
Rob Percival94f21ad2017-11-14 10:20:241613 CompleteRequests(MakeCacheEntryWithTTL(net_error, addr_list,
1614 HostCache::Entry::SOURCE_DNS, ttl),
eroman0cd87b62016-12-14 19:13:451615 bounded_ttl);
1616 }
[email protected]b3601bc22012-02-21 21:23:201617 }
1618
dchengb03027d2014-10-21 12:00:201619 void OnFirstDnsTransactionComplete() override {
[email protected]daae1322013-09-05 18:26:501620 DCHECK(dns_task_->needs_two_transactions());
1621 DCHECK_EQ(dns_task_->needs_another_transaction(), is_queued());
1622 // No longer need to occupy two dispatcher slots.
1623 ReduceToOneJobSlot();
1624
1625 // We already have a job slot at the dispatcher, so if the second
1626 // transaction hasn't started, reuse it now instead of waiting in the queue
1627 // for the second slot.
1628 if (dns_task_->needs_another_transaction())
1629 dns_task_->StartSecondTransaction();
1630 }
1631
Miriam Gershenson61604662017-09-28 23:51:111632 void RecordJobHistograms(int error) {
Miriam Gershensonc282ab42017-11-20 23:19:581633 // Used in UMA_HISTOGRAM_ENUMERATION. Do not renumber entries or reuse
1634 // deprecated values.
1635 enum Category {
1636 RESOLVE_SUCCESS = 0,
1637 RESOLVE_FAIL = 1,
1638 RESOLVE_SPECULATIVE_SUCCESS = 2,
1639 RESOLVE_SPECULATIVE_FAIL = 3,
1640 RESOLVE_ABORT = 4,
1641 RESOLVE_SPECULATIVE_ABORT = 5,
Miriam Gershenson61604662017-09-28 23:51:111642 RESOLVE_MAX, // Bounding value.
1643 };
1644 Category category = RESOLVE_MAX; // Illegal value for later DCHECK only.
1645
1646 base::TimeDelta duration = base::TimeTicks::Now() - start_time_;
1647 if (error == OK) {
1648 if (had_non_speculative_request_) {
1649 category = RESOLVE_SUCCESS;
1650 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime", duration);
1651 switch (key_.address_family) {
1652 case ADDRESS_FAMILY_IPV4:
1653 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime.IPV4",
1654 duration);
1655 break;
1656 case ADDRESS_FAMILY_IPV6:
1657 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime.IPV6",
1658 duration);
1659 break;
1660 case ADDRESS_FAMILY_UNSPECIFIED:
1661 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime.UNSPEC",
1662 duration);
1663 break;
1664 }
1665 } else {
1666 category = RESOLVE_SPECULATIVE_SUCCESS;
Miriam Gershenson61604662017-09-28 23:51:111667 }
Miriam Gershensonc282ab42017-11-20 23:19:581668 } else if (error == ERR_NETWORK_CHANGED ||
1669 error == ERR_HOST_RESOLVER_QUEUE_TOO_LARGE) {
1670 category = had_non_speculative_request_ ? RESOLVE_ABORT
1671 : RESOLVE_SPECULATIVE_ABORT;
Miriam Gershenson61604662017-09-28 23:51:111672 } else {
1673 if (had_non_speculative_request_) {
1674 category = RESOLVE_FAIL;
1675 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveFailureTime", duration);
1676 switch (key_.address_family) {
1677 case ADDRESS_FAMILY_IPV4:
Miriam Gershensonc282ab42017-11-20 23:19:581678 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveFailureTime.IPV4",
Miriam Gershenson61604662017-09-28 23:51:111679 duration);
1680 break;
1681 case ADDRESS_FAMILY_IPV6:
Miriam Gershensonc282ab42017-11-20 23:19:581682 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveFailureTime.IPV6",
Miriam Gershenson61604662017-09-28 23:51:111683 duration);
1684 break;
1685 case ADDRESS_FAMILY_UNSPECIFIED:
Miriam Gershensonc282ab42017-11-20 23:19:581686 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveFailureTime.UNSPEC",
Miriam Gershenson61604662017-09-28 23:51:111687 duration);
1688 break;
1689 }
1690 } else {
1691 category = RESOLVE_SPECULATIVE_FAIL;
Miriam Gershenson61604662017-09-28 23:51:111692 }
1693 }
1694 DCHECK_LT(static_cast<int>(category),
1695 static_cast<int>(RESOLVE_MAX)); // Be sure it was set.
1696 UMA_HISTOGRAM_ENUMERATION("Net.DNS.ResolveCategory", category, RESOLVE_MAX);
Miriam Gershensonaaf139582017-11-27 16:06:061697
1698 if (category == RESOLVE_FAIL || category == RESOLVE_ABORT) {
1699 if (duration < base::TimeDelta::FromMilliseconds(10))
Ilya Sherman0eb39802017-12-08 20:58:181700 base::UmaHistogramSparse("Net.DNS.ResolveError.Fast", std::abs(error));
Miriam Gershensonaaf139582017-11-27 16:06:061701 else
Ilya Sherman0eb39802017-12-08 20:58:181702 base::UmaHistogramSparse("Net.DNS.ResolveError.Slow", std::abs(error));
Miriam Gershensonaaf139582017-11-27 16:06:061703 }
Miriam Gershenson61604662017-09-28 23:51:111704 }
1705
[email protected]16ee26d2012-03-08 03:34:351706 // Performs Job's last rites. Completes all Requests. Deletes this.
[email protected]895123222012-10-25 15:21:171707 void CompleteRequests(const HostCache::Entry& entry,
1708 base::TimeDelta ttl) {
[email protected]11fbca0b2013-06-02 23:37:211709 CHECK(resolver_.get());
[email protected]b3601bc22012-02-21 21:23:201710
[email protected]16ee26d2012-03-08 03:34:351711 // This job must be removed from resolver's |jobs_| now to make room for a
1712 // new job with the same key in case one of the OnComplete callbacks decides
1713 // to spawn one. Consequently, the job deletes itself when CompleteRequests
1714 // is done.
danakj22f90e72016-04-16 01:55:401715 std::unique_ptr<Job> self_deleter(this);
[email protected]16ee26d2012-03-08 03:34:351716
1717 resolver_->RemoveJob(this);
1718
[email protected]16ee26d2012-03-08 03:34:351719 if (is_running()) {
[email protected]16ee26d2012-03-08 03:34:351720 if (is_proc_running()) {
[email protected]daae1322013-09-05 18:26:501721 DCHECK(!is_queued());
[email protected]16ee26d2012-03-08 03:34:351722 proc_task_->Cancel();
wezb9820d42016-06-22 23:41:041723 proc_task_ = nullptr;
[email protected]16ee26d2012-03-08 03:34:351724 }
[email protected]daae1322013-09-05 18:26:501725 KillDnsTask();
[email protected]16ee26d2012-03-08 03:34:351726
1727 // Signal dispatcher that a slot has opened.
[email protected]106ccd2c2014-06-17 09:21:001728 resolver_->dispatcher_->OnJobFinished();
[email protected]16ee26d2012-03-08 03:34:351729 } else if (is_queued()) {
[email protected]106ccd2c2014-06-17 09:21:001730 resolver_->dispatcher_->Cancel(handle_);
[email protected]16ee26d2012-03-08 03:34:351731 handle_.Reset();
1732 }
1733
1734 if (num_active_requests() == 0) {
mikecirone8b85c432016-09-08 19:11:001735 net_log_.AddEvent(NetLogEventType::CANCELLED);
1736 net_log_.EndEventWithNetErrorCode(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
[email protected]16ee26d2012-03-08 03:34:351737 OK);
1738 return;
1739 }
[email protected]b3601bc22012-02-21 21:23:201740
mikecirone8b85c432016-09-08 19:11:001741 net_log_.EndEventWithNetErrorCode(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
juliatuttle317860e2016-05-12 14:47:221742 entry.error());
[email protected]68ad3ee2010-01-30 03:45:391743
juliatuttled7fa5852016-07-29 13:16:571744 resolver_->SchedulePersist();
1745
[email protected]78eac2a2012-03-14 19:09:271746 DCHECK(!requests_.empty());
1747
eroman1efc237c2016-12-14 00:00:451748 if (entry.error() == OK || entry.error() == ERR_ICANN_NAME_COLLISION) {
[email protected]d7b9a2b2012-05-31 22:31:191749 // Record this histogram here, when we know the system has a valid DNS
1750 // configuration.
[email protected]539df6c2012-06-19 21:21:291751 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.HaveDnsConfig",
1752 resolver_->received_dns_config_);
[email protected]d7b9a2b2012-05-31 22:31:191753 }
[email protected]16ee26d2012-03-08 03:34:351754
juliatuttle317860e2016-05-12 14:47:221755 bool did_complete = (entry.error() != ERR_NETWORK_CHANGED) &&
1756 (entry.error() != ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
Miriam Gershensonc282ab42017-11-20 23:19:581757 if (did_complete)
[email protected]1339a2a22012-10-17 08:39:431758 resolver_->CacheResult(key_, entry, ttl);
Miriam Gershensonc282ab42017-11-20 23:19:581759
1760 RecordJobHistograms(entry.error());
[email protected]16ee26d2012-03-08 03:34:351761
maksim.sisov31452af2016-07-27 06:38:101762 // Complete all of the requests that were attached to the job and
1763 // detach them.
1764 while (!requests_.empty()) {
1765 RequestImpl* req = requests_.front();
1766 requests_.pop_front();
[email protected]0f292de02012-02-01 22:28:201767 DCHECK_EQ(this, req->job());
1768 // Update the net log and notify registered observers.
juliatuttle317860e2016-05-12 14:47:221769 LogFinishRequest(req->source_net_log(), req->info(), entry.error());
[email protected]51b9a6b2012-06-25 21:50:291770 if (did_complete) {
[email protected]51b9a6b2012-06-25 21:50:291771 // Record effective total time from creation to completion.
Miriam Gershenson90d05e02017-09-28 19:29:281772 RecordTotalTime(req->info().is_speculative(), false,
[email protected]51b9a6b2012-06-25 21:50:291773 base::TimeTicks::Now() - req->request_time());
1774 }
maksim.sisov31452af2016-07-27 06:38:101775 req->OnJobCompleted(this, entry.error(), entry.addresses());
[email protected]0f292de02012-02-01 22:28:201776
1777 // Check if the resolver was destroyed as a result of running the
1778 // callback. If it was, we could continue, but we choose to bail.
[email protected]11fbca0b2013-06-02 23:37:211779 if (!resolver_.get())
[email protected]0f292de02012-02-01 22:28:201780 return;
1781 }
1782 }
1783
[email protected]1339a2a22012-10-17 08:39:431784 // Convenience wrapper for CompleteRequests in case of failure.
1785 void CompleteRequestsWithError(int net_error) {
Rob Percival94f21ad2017-11-14 10:20:241786 CompleteRequests(HostCache::Entry(net_error, AddressList(),
1787 HostCache::Entry::SOURCE_UNKNOWN),
[email protected]895123222012-10-25 15:21:171788 base::TimeDelta());
[email protected]1339a2a22012-10-17 08:39:431789 }
1790
[email protected]b4481b222012-03-16 17:13:111791 RequestPriority priority() const {
1792 return priority_tracker_.highest_priority();
1793 }
1794
1795 // Number of non-canceled requests in |requests_|.
1796 size_t num_active_requests() const {
1797 return priority_tracker_.total_count();
1798 }
1799
wezb9820d42016-06-22 23:41:041800 bool is_dns_running() const { return !!dns_task_; }
[email protected]b4481b222012-03-16 17:13:111801
wezb9820d42016-06-22 23:41:041802 bool is_proc_running() const { return !!proc_task_; }
[email protected]b4481b222012-03-16 17:13:111803
[email protected]0f292de02012-02-01 22:28:201804 base::WeakPtr<HostResolverImpl> resolver_;
1805
1806 Key key_;
1807
1808 // Tracks the highest priority across |requests_|.
1809 PriorityTracker priority_tracker_;
1810
Miriam Gershensone42adb22017-10-16 16:19:381811 // Task runner used for HostResolverProc.
1812 scoped_refptr<base::TaskRunner> proc_task_runner_;
1813
[email protected]0f292de02012-02-01 22:28:201814 bool had_non_speculative_request_;
1815
[email protected]51b9a6b2012-06-25 21:50:291816 // Distinguishes measurements taken while DnsClient was fully configured.
1817 bool had_dns_config_;
1818
[email protected]daae1322013-09-05 18:26:501819 // Number of slots occupied by this Job in resolver's PrioritizedDispatcher.
1820 unsigned num_occupied_job_slots_;
1821
[email protected]1d932852012-06-19 19:40:331822 // Result of DnsTask.
1823 int dns_task_error_;
[email protected]1def74c2012-03-22 20:07:001824
[email protected]51b9a6b2012-06-25 21:50:291825 const base::TimeTicks creation_time_;
1826 base::TimeTicks priority_change_time_;
Miriam Gershenson61604662017-09-28 23:51:111827 base::TimeTicks start_time_;
[email protected]51b9a6b2012-06-25 21:50:291828
tfarina428341112016-09-22 13:38:201829 NetLogWithSource net_log_;
[email protected]0f292de02012-02-01 22:28:201830
[email protected]b3601bc22012-02-21 21:23:201831 // Resolves the host using a HostResolverProc.
[email protected]0f292de02012-02-01 22:28:201832 scoped_refptr<ProcTask> proc_task_;
1833
[email protected]b3601bc22012-02-21 21:23:201834 // Resolves the host using a DnsTransaction.
danakj22f90e72016-04-16 01:55:401835 std::unique_ptr<DnsTask> dns_task_;
[email protected]b3601bc22012-02-21 21:23:201836
[email protected]0f292de02012-02-01 22:28:201837 // All Requests waiting for the result of this Job. Some can be canceled.
Brett Wilsonc6a0c822017-09-12 00:04:291838 base::circular_deque<RequestImpl*> requests_;
[email protected]0f292de02012-02-01 22:28:201839
[email protected]16ee26d2012-03-08 03:34:351840 // A handle used in |HostResolverImpl::dispatcher_|.
[email protected]0f292de02012-02-01 22:28:201841 PrioritizedDispatcher::Handle handle_;
[email protected]68ad3ee2010-01-30 03:45:391842};
1843
1844//-----------------------------------------------------------------------------
1845
[email protected]0f292de02012-02-01 22:28:201846HostResolverImpl::ProcTaskParams::ProcTaskParams(
[email protected]e95d3aca2010-01-11 22:47:431847 HostResolverProc* resolver_proc,
[email protected]0f292de02012-02-01 22:28:201848 size_t max_retry_attempts)
1849 : resolver_proc(resolver_proc),
1850 max_retry_attempts(max_retry_attempts),
ttuttlecf1158bf2016-03-18 16:37:441851 unresponsive_delay(
1852 base::TimeDelta::FromMilliseconds(kDnsDefaultUnresponsiveDelayMs)),
[email protected]0f292de02012-02-01 22:28:201853 retry_factor(2) {
[email protected]106ccd2c2014-06-17 09:21:001854 // Maximum of 4 retry attempts for host resolution.
1855 static const size_t kDefaultMaxRetryAttempts = 4u;
1856 if (max_retry_attempts == HostResolver::kDefaultRetryAttempts)
1857 max_retry_attempts = kDefaultMaxRetryAttempts;
[email protected]0f292de02012-02-01 22:28:201858}
1859
vmpstracd23b72016-02-26 21:08:551860HostResolverImpl::ProcTaskParams::ProcTaskParams(const ProcTaskParams& other) =
1861 default;
1862
Chris Watkins68b15032017-12-01 03:07:131863HostResolverImpl::ProcTaskParams::~ProcTaskParams() = default;
[email protected]0f292de02012-02-01 22:28:201864
[email protected]b59ff372009-07-15 22:04:321865HostResolverImpl::~HostResolverImpl() {
gab47aa7da2017-06-02 16:09:431866 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
[email protected]daae1322013-09-05 18:26:501867 // Prevent the dispatcher from starting new jobs.
[email protected]106ccd2c2014-06-17 09:21:001868 dispatcher_->SetLimitsToZero();
avi9e72eb482016-12-09 21:10:541869 // It's now safe for Jobs to call KillDnsTask on destruction, because
[email protected]daae1322013-09-05 18:26:501870 // OnJobComplete will not start any new jobs.
avi9e72eb482016-12-09 21:10:541871 jobs_.clear();
[email protected]e95d3aca2010-01-11 22:47:431872
[email protected]232a5812011-03-04 22:42:081873 NetworkChangeNotifier::RemoveIPAddressObserver(this);
ttuttlecf1158bf2016-03-18 16:37:441874 NetworkChangeNotifier::RemoveConnectionTypeObserver(this);
[email protected]bb0e34542012-08-31 19:52:401875 NetworkChangeNotifier::RemoveDNSObserver(this);
[email protected]b59ff372009-07-15 22:04:321876}
1877
[email protected]0f292de02012-02-01 22:28:201878void HostResolverImpl::SetMaxQueuedJobs(size_t value) {
[email protected]106ccd2c2014-06-17 09:21:001879 DCHECK_EQ(0u, dispatcher_->num_queued_jobs());
[email protected]0f292de02012-02-01 22:28:201880 DCHECK_GT(value, 0u);
1881 max_queued_jobs_ = value;
[email protected]be1a48b2011-01-20 00:12:131882}
1883
[email protected]684970b2009-08-14 04:54:461884int HostResolverImpl::Resolve(const RequestInfo& info,
[email protected]5109c1952013-08-20 18:44:101885 RequestPriority priority,
[email protected]b59ff372009-07-15 22:04:321886 AddressList* addresses,
[email protected]aa22b242011-11-16 18:58:291887 const CompletionCallback& callback,
maksim.sisov31452af2016-07-27 06:38:101888 std::unique_ptr<Request>* out_req,
tfarina428341112016-09-22 13:38:201889 const NetLogWithSource& source_net_log) {
[email protected]95a214c2011-08-04 21:50:401890 DCHECK(addresses);
gab47aa7da2017-06-02 16:09:431891 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
[email protected]aa22b242011-11-16 18:58:291892 DCHECK_EQ(false, callback.is_null());
maksim.sisov31452af2016-07-27 06:38:101893 DCHECK(out_req);
[email protected]1ac6af92010-06-03 21:00:141894
Chris Palmer9cbf4212017-07-19 01:54:551895 LogStartRequest(source_net_log, info);
pauljensen19eb73422015-04-15 23:20:061896
Matt Menke23b4bbf82017-07-20 19:11:291897 Key key;
1898 int rv = ResolveHelper(info, false, nullptr, source_net_log, addresses, &key);
[email protected]95a214c2011-08-04 21:50:401899 if (rv != ERR_DNS_CACHE_MISS) {
xunjieli26f90452014-11-10 16:23:021900 LogFinishRequest(source_net_log, info, rv);
Miriam Gershenson90d05e02017-09-28 19:29:281901 RecordTotalTime(info.is_speculative(), true, base::TimeDelta());
[email protected]95a214c2011-08-04 21:50:401902 return rv;
[email protected]38368712011-03-02 08:09:401903 }
1904
[email protected]0f292de02012-02-01 22:28:201905 // Next we need to attach our request to a "job". This job is responsible for
1906 // calling "getaddrinfo(hostname)" on a worker thread.
1907
avi9e72eb482016-12-09 21:10:541908 auto jobit = jobs_.find(key);
[email protected]0f292de02012-02-01 22:28:201909 Job* job;
1910 if (jobit == jobs_.end()) {
Miriam Gershensone42adb22017-10-16 16:19:381911 job = new Job(weak_ptr_factory_.GetWeakPtr(), key, priority,
1912 proc_task_runner_, source_net_log);
[email protected]daae1322013-09-05 18:26:501913 job->Schedule(false);
[email protected]0f292de02012-02-01 22:28:201914
1915 // Check for queue overflow.
[email protected]106ccd2c2014-06-17 09:21:001916 if (dispatcher_->num_queued_jobs() > max_queued_jobs_) {
1917 Job* evicted = static_cast<Job*>(dispatcher_->EvictOldestLowest());
[email protected]0f292de02012-02-01 22:28:201918 DCHECK(evicted);
[email protected]16ee26d2012-03-08 03:34:351919 evicted->OnEvicted(); // Deletes |evicted|.
[email protected]0f292de02012-02-01 22:28:201920 if (evicted == job) {
[email protected]0f292de02012-02-01 22:28:201921 rv = ERR_HOST_RESOLVER_QUEUE_TOO_LARGE;
xunjieli26f90452014-11-10 16:23:021922 LogFinishRequest(source_net_log, info, rv);
[email protected]0f292de02012-02-01 22:28:201923 return rv;
1924 }
[email protected]0f292de02012-02-01 22:28:201925 }
avi9e72eb482016-12-09 21:10:541926 jobs_[key] = base::WrapUnique(job);
[email protected]0f292de02012-02-01 22:28:201927 } else {
avi9e72eb482016-12-09 21:10:541928 job = jobit->second.get();
[email protected]0f292de02012-02-01 22:28:201929 }
1930
1931 // Can't complete synchronously. Create and attach request.
Jeremy Roman0579ed62017-08-29 15:56:191932 auto req = std::make_unique<RequestImpl>(source_net_log, info, priority,
avi9e72eb482016-12-09 21:10:541933 callback, addresses, job);
maksim.sisov31452af2016-07-27 06:38:101934 job->AddRequest(req.get());
1935 *out_req = std::move(req);
[email protected]b59ff372009-07-15 22:04:321936
[email protected]0f292de02012-02-01 22:28:201937 // Completion happens during Job::CompleteRequests().
[email protected]b59ff372009-07-15 22:04:321938 return ERR_IO_PENDING;
1939}
1940
Francois Doraya2d01ba2017-09-25 19:17:401941HostResolverImpl::HostResolverImpl(const Options& options, NetLog* net_log)
mmenke91c17162016-06-02 16:03:231942 : max_queued_jobs_(0),
1943 proc_params_(NULL, options.max_retry_attempts),
1944 net_log_(net_log),
1945 received_dns_config_(false),
1946 num_dns_failures_(0),
mgershaf9a9232017-04-13 20:19:031947 assume_ipv6_failure_on_wifi_(false),
mmenke91c17162016-06-02 16:03:231948 use_local_ipv6_(false),
1949 last_ipv6_probe_result_(true),
mmenke91c17162016-06-02 16:03:231950 additional_resolver_flags_(0),
1951 fallback_to_proctask_(true),
juliatuttled7fa5852016-07-29 13:16:571952 persist_initialized_(false),
mmenke91c17162016-06-02 16:03:231953 weak_ptr_factory_(this),
1954 probe_weak_ptr_factory_(this) {
1955 if (options.enable_caching)
1956 cache_ = HostCache::CreateDefaultCache();
1957
1958 PrioritizedDispatcher::Limits job_limits = options.GetDispatcherLimits();
1959 dispatcher_.reset(new PrioritizedDispatcher(job_limits));
1960 max_queued_jobs_ = job_limits.total_jobs * 100u;
1961
1962 DCHECK_GE(dispatcher_->num_priorities(), static_cast<size_t>(NUM_PRIORITIES));
1963
Miriam Gershensone42adb22017-10-16 16:19:381964 proc_task_runner_ = base::CreateTaskRunnerWithTraits(
1965 {base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN});
1966
mmenke91c17162016-06-02 16:03:231967#if defined(OS_WIN)
1968 EnsureWinsockInit();
1969#endif
1970#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
1971 RunLoopbackProbeJob();
1972#endif
1973 NetworkChangeNotifier::AddIPAddressObserver(this);
1974 NetworkChangeNotifier::AddConnectionTypeObserver(this);
1975 NetworkChangeNotifier::AddDNSObserver(this);
1976#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD) && \
Sergey Ulanov49085572017-07-10 23:25:461977 !defined(OS_ANDROID) && !defined(OS_FUCHSIA)
mmenke91c17162016-06-02 16:03:231978 EnsureDnsReloaderInit();
1979#endif
1980
1981 OnConnectionTypeChanged(NetworkChangeNotifier::GetConnectionType());
1982
1983 {
1984 DnsConfig dns_config;
1985 NetworkChangeNotifier::GetDnsConfig(&dns_config);
1986 received_dns_config_ = dns_config.IsValid();
1987 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
1988 use_local_ipv6_ = !dns_config.IsValid() || dns_config.use_local_ipv6;
1989 }
1990
1991 fallback_to_proctask_ = !ConfigureAsyncDnsNoFallbackFieldTrial();
1992}
1993
1994void HostResolverImpl::SetHaveOnlyLoopbackAddresses(bool result) {
1995 if (result) {
1996 additional_resolver_flags_ |= HOST_RESOLVER_LOOPBACK_ONLY;
1997 } else {
1998 additional_resolver_flags_ &= ~HOST_RESOLVER_LOOPBACK_ONLY;
1999 }
2000}
2001
Miriam Gershensone42adb22017-10-16 16:19:382002void HostResolverImpl::SetTaskRunnerForTesting(
2003 scoped_refptr<base::TaskRunner> task_runner) {
2004 proc_task_runner_ = std::move(task_runner);
2005}
2006
Matt Menke23b4bbf82017-07-20 19:11:292007int HostResolverImpl::ResolveHelper(const RequestInfo& info,
juliatuttle9fb7aeb2016-06-06 20:16:332008 bool allow_stale,
2009 HostCache::EntryStaleness* stale_info,
Matt Menke23b4bbf82017-07-20 19:11:292010 const NetLogWithSource& source_net_log,
2011 AddressList* addresses,
2012 Key* key) {
2013 IPAddress ip_address;
2014 IPAddress* ip_address_ptr = nullptr;
2015 if (ip_address.AssignFromIPLiteral(info.hostname())) {
2016 ip_address_ptr = &ip_address;
2017 } else {
2018 // Check that the caller supplied a valid hostname to resolve.
2019 if (!IsValidDNSDomain(info.hostname()))
2020 return ERR_NAME_NOT_RESOLVED;
2021 }
2022
2023 // Build a key that identifies the request in the cache and in the
2024 // outstanding jobs map.
2025 *key = GetEffectiveKeyForRequest(info, ip_address_ptr, source_net_log);
2026
juliatuttle9fb7aeb2016-06-06 20:16:332027 DCHECK(allow_stale == !!stale_info);
[email protected]95a214c2011-08-04 21:50:402028 // The result of |getaddrinfo| for empty hosts is inconsistent across systems.
2029 // On Windows it gives the default interface's address, whereas on Linux it
2030 // gives an error. We will make it fail on all platforms for consistency.
juliatuttle9fb7aeb2016-06-06 20:16:332031 if (info.hostname().empty() || info.hostname().size() > kMaxHostLength) {
2032 MakeNotStale(stale_info);
[email protected]95a214c2011-08-04 21:50:402033 return ERR_NAME_NOT_RESOLVED;
juliatuttle9fb7aeb2016-06-06 20:16:332034 }
[email protected]95a214c2011-08-04 21:50:402035
2036 int net_error = ERR_UNEXPECTED;
Matt Menke23b4bbf82017-07-20 19:11:292037 if (ResolveAsIP(*key, info, ip_address_ptr, &net_error, addresses)) {
juliatuttle9fb7aeb2016-06-06 20:16:332038 MakeNotStale(stale_info);
[email protected]95a214c2011-08-04 21:50:402039 return net_error;
juliatuttle9fb7aeb2016-06-06 20:16:332040 }
Mike Westda1c690e2017-08-12 05:57:162041
2042 // Special-case localhost names, as per the recommendations in
2043 // https://tools.ietf.org/html/draft-west-let-localhost-be-localhost.
2044 if (ServeLocalhost(*key, info, addresses)) {
2045 MakeNotStale(stale_info);
2046 return OK;
2047 }
2048
Matt Menke23b4bbf82017-07-20 19:11:292049 if (ServeFromCache(*key, info, &net_error, addresses, allow_stale,
juliatuttle9fb7aeb2016-06-06 20:16:332050 stale_info)) {
mgersh33d23c02017-03-29 20:24:252051 source_net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_CACHE_HIT,
2052 addresses->CreateNetLogCallback());
juliatuttle9fb7aeb2016-06-06 20:16:332053 // |ServeFromCache()| will set |*stale_info| as needed.
[email protected]78eac2a2012-03-14 19:09:272054 return net_error;
2055 }
Mike Westda1c690e2017-08-12 05:57:162056
[email protected]78eac2a2012-03-14 19:09:272057 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2058 // http://crbug.com/117655
Matt Menke23b4bbf82017-07-20 19:11:292059 if (ServeFromHosts(*key, info, addresses)) {
mgersh33d23c02017-03-29 20:24:252060 source_net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_HOSTS_HIT,
2061 addresses->CreateNetLogCallback());
juliatuttle9fb7aeb2016-06-06 20:16:332062 MakeNotStale(stale_info);
[email protected]78eac2a2012-03-14 19:09:272063 return OK;
2064 }
estarkd1bc206e2015-06-20 00:44:392065
[email protected]78eac2a2012-03-14 19:09:272066 return ERR_DNS_CACHE_MISS;
[email protected]95a214c2011-08-04 21:50:402067}
2068
2069int HostResolverImpl::ResolveFromCache(const RequestInfo& info,
2070 AddressList* addresses,
tfarina428341112016-09-22 13:38:202071 const NetLogWithSource& source_net_log) {
gab47aa7da2017-06-02 16:09:432072 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
[email protected]95a214c2011-08-04 21:50:402073 DCHECK(addresses);
2074
[email protected]95a214c2011-08-04 21:50:402075 // Update the net log and notify registered observers.
xunjieli26f90452014-11-10 16:23:022076 LogStartRequest(source_net_log, info);
[email protected]95a214c2011-08-04 21:50:402077
Matt Menke23b4bbf82017-07-20 19:11:292078 Key key;
2079 int rv = ResolveHelper(info, false, nullptr, source_net_log, addresses, &key);
[email protected]95a214c2011-08-04 21:50:402080
xunjieli26f90452014-11-10 16:23:022081 LogFinishRequest(source_net_log, info, rv);
[email protected]95a214c2011-08-04 21:50:402082 return rv;
2083}
2084
[email protected]a8883e452012-11-17 05:58:062085void HostResolverImpl::SetDnsClientEnabled(bool enabled) {
gab47aa7da2017-06-02 16:09:432086 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
[email protected]a8883e452012-11-17 05:58:062087#if defined(ENABLE_BUILT_IN_DNS)
2088 if (enabled && !dns_client_) {
2089 SetDnsClient(DnsClient::CreateClient(net_log_));
2090 } else if (!enabled && dns_client_) {
danakj22f90e72016-04-16 01:55:402091 SetDnsClient(std::unique_ptr<DnsClient>());
[email protected]a8883e452012-11-17 05:58:062092 }
2093#endif
2094}
2095
[email protected]489d1a82011-10-12 03:09:112096HostCache* HostResolverImpl::GetHostCache() {
2097 return cache_.get();
2098}
[email protected]95a214c2011-08-04 21:50:402099
Rob Percivalbc658a22017-12-13 08:24:422100bool HostResolverImpl::HasCached(base::StringPiece hostname,
2101 HostCache::Entry::Source* source_out,
2102 HostCache::EntryStaleness* stale_out) const {
2103 if (!cache_)
2104 return false;
2105
2106 return cache_->HasEntry(hostname, source_out, stale_out);
2107}
2108
danakj22f90e72016-04-16 01:55:402109std::unique_ptr<base::Value> HostResolverImpl::GetDnsConfigAsValue() const {
[email protected]17e92032012-03-29 00:56:242110 // Check if async DNS is disabled.
2111 if (!dns_client_.get())
tfhef3618f2016-01-11 23:07:082112 return nullptr;
[email protected]17e92032012-03-29 00:56:242113
2114 // Check if async DNS is enabled, but we currently have no configuration
2115 // for it.
2116 const DnsConfig* dns_config = dns_client_->GetConfig();
wezb9820d42016-06-22 23:41:042117 if (!dns_config)
Jeremy Roman0579ed62017-08-29 15:56:192118 return std::make_unique<base::DictionaryValue>();
[email protected]17e92032012-03-29 00:56:242119
2120 return dns_config->ToValue();
2121}
2122
juliatuttle9fb7aeb2016-06-06 20:16:332123int HostResolverImpl::ResolveStaleFromCache(
2124 const RequestInfo& info,
2125 AddressList* addresses,
2126 HostCache::EntryStaleness* stale_info,
tfarina428341112016-09-22 13:38:202127 const NetLogWithSource& source_net_log) {
gab47aa7da2017-06-02 16:09:432128 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
juliatuttle9fb7aeb2016-06-06 20:16:332129 DCHECK(addresses);
2130 DCHECK(stale_info);
2131
2132 // Update the net log and notify registered observers.
2133 LogStartRequest(source_net_log, info);
2134
Matt Menke23b4bbf82017-07-20 19:11:292135 Key key;
2136 int rv =
2137 ResolveHelper(info, true, stale_info, source_net_log, addresses, &key);
juliatuttle9fb7aeb2016-06-06 20:16:332138 LogFinishRequest(source_net_log, info, rv);
2139 return rv;
2140}
2141
Miriam Gershenson2839ef112017-08-30 03:25:372142size_t HostResolverImpl::LastRestoredCacheSize() const {
2143 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
2144
2145 return cache_ ? cache_->last_restore_size() : 0;
2146}
2147
2148size_t HostResolverImpl::CacheSize() const {
2149 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
2150
2151 return cache_ ? cache_->size() : 0;
2152}
2153
mgershaf9a9232017-04-13 20:19:032154void HostResolverImpl::SetNoIPv6OnWifi(bool no_ipv6_on_wifi) {
gab47aa7da2017-06-02 16:09:432155 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
mgershaf9a9232017-04-13 20:19:032156 assume_ipv6_failure_on_wifi_ = no_ipv6_on_wifi;
2157}
2158
2159bool HostResolverImpl::GetNoIPv6OnWifi() {
2160 return assume_ipv6_failure_on_wifi_;
2161}
2162
[email protected]95a214c2011-08-04 21:50:402163bool HostResolverImpl::ResolveAsIP(const Key& key,
2164 const RequestInfo& info,
martijna23c8962016-03-04 18:18:512165 const IPAddress* ip_address,
[email protected]95a214c2011-08-04 21:50:402166 int* net_error,
2167 AddressList* addresses) {
2168 DCHECK(addresses);
2169 DCHECK(net_error);
martijna23c8962016-03-04 18:18:512170 if (ip_address == nullptr)
[email protected]95a214c2011-08-04 21:50:402171 return false;
2172
[email protected]95a214c2011-08-04 21:50:402173 *net_error = OK;
martijna23c8962016-03-04 18:18:512174 AddressFamily family = GetAddressFamily(*ip_address);
cbentzel1906f872015-06-05 16:25:252175 if (key.address_family != ADDRESS_FAMILY_UNSPECIFIED &&
2176 key.address_family != family) {
[email protected]1c7cf3f82014-08-07 21:33:482177 // Don't return IPv6 addresses for IPv4 queries, and vice versa.
[email protected]95a214c2011-08-04 21:50:402178 *net_error = ERR_NAME_NOT_RESOLVED;
2179 } else {
martijna23c8962016-03-04 18:18:512180 *addresses = AddressList::CreateFromIPAddress(*ip_address, info.port());
[email protected]7054e78f2012-05-07 21:44:562181 if (key.host_resolver_flags & HOST_RESOLVER_CANONNAME)
2182 addresses->SetDefaultCanonicalName();
[email protected]95a214c2011-08-04 21:50:402183 }
2184 return true;
2185}
2186
2187bool HostResolverImpl::ServeFromCache(const Key& key,
2188 const RequestInfo& info,
[email protected]95a214c2011-08-04 21:50:402189 int* net_error,
juliatuttle9fb7aeb2016-06-06 20:16:332190 AddressList* addresses,
2191 bool allow_stale,
2192 HostCache::EntryStaleness* stale_info) {
[email protected]95a214c2011-08-04 21:50:402193 DCHECK(addresses);
2194 DCHECK(net_error);
juliatuttle9fb7aeb2016-06-06 20:16:332195 DCHECK(allow_stale == !!stale_info);
[email protected]95a214c2011-08-04 21:50:402196 if (!info.allow_cached_response() || !cache_.get())
2197 return false;
2198
juliatuttle9fb7aeb2016-06-06 20:16:332199 const HostCache::Entry* cache_entry;
2200 if (allow_stale)
2201 cache_entry = cache_->LookupStale(key, base::TimeTicks::Now(), stale_info);
2202 else
2203 cache_entry = cache_->Lookup(key, base::TimeTicks::Now());
[email protected]95a214c2011-08-04 21:50:402204 if (!cache_entry)
2205 return false;
2206
juliatuttle317860e2016-05-12 14:47:222207 *net_error = cache_entry->error();
[email protected]7054e78f2012-05-07 21:44:562208 if (*net_error == OK) {
[email protected]1339a2a22012-10-17 08:39:432209 if (cache_entry->has_ttl())
juliatuttle317860e2016-05-12 14:47:222210 RecordTTL(cache_entry->ttl());
2211 *addresses = EnsurePortOnAddressList(cache_entry->addresses(), info.port());
[email protected]7054e78f2012-05-07 21:44:562212 }
[email protected]95a214c2011-08-04 21:50:402213 return true;
2214}
2215
[email protected]78eac2a2012-03-14 19:09:272216bool HostResolverImpl::ServeFromHosts(const Key& key,
2217 const RequestInfo& info,
2218 AddressList* addresses) {
2219 DCHECK(addresses);
2220 if (!HaveDnsConfig())
2221 return false;
[email protected]05a79d42013-03-28 07:30:092222 addresses->clear();
2223
[email protected]cb507622012-03-23 16:17:062224 // HOSTS lookups are case-insensitive.
brettw8e2106d2015-08-11 19:30:222225 std::string hostname = base::ToLowerASCII(key.hostname);
[email protected]cb507622012-03-23 16:17:062226
[email protected]05a79d42013-03-28 07:30:092227 const DnsHosts& hosts = dns_client_->GetConfig()->hosts;
2228
[email protected]78eac2a2012-03-14 19:09:272229 // If |address_family| is ADDRESS_FAMILY_UNSPECIFIED other implementations
2230 // (glibc and c-ares) return the first matching line. We have more
2231 // flexibility, but lose implicit ordering.
[email protected]05a79d42013-03-28 07:30:092232 // We prefer IPv6 because "happy eyeballs" will fall back to IPv4 if
2233 // necessary.
2234 if (key.address_family == ADDRESS_FAMILY_IPV6 ||
2235 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
2236 DnsHosts::const_iterator it = hosts.find(
2237 DnsHostsKey(hostname, ADDRESS_FAMILY_IPV6));
2238 if (it != hosts.end())
2239 addresses->push_back(IPEndPoint(it->second, info.port()));
[email protected]78eac2a2012-03-14 19:09:272240 }
2241
[email protected]05a79d42013-03-28 07:30:092242 if (key.address_family == ADDRESS_FAMILY_IPV4 ||
2243 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
2244 DnsHosts::const_iterator it = hosts.find(
2245 DnsHostsKey(hostname, ADDRESS_FAMILY_IPV4));
2246 if (it != hosts.end())
2247 addresses->push_back(IPEndPoint(it->second, info.port()));
2248 }
2249
[email protected]ec666ab22013-04-17 20:05:592250 // If got only loopback addresses and the family was restricted, resolve
2251 // again, without restrictions. See SystemHostResolverCall for rationale.
2252 if ((key.host_resolver_flags &
2253 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6) &&
2254 IsAllIPv4Loopback(*addresses)) {
2255 Key new_key(key);
2256 new_key.address_family = ADDRESS_FAMILY_UNSPECIFIED;
2257 new_key.host_resolver_flags &=
2258 ~HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
2259 return ServeFromHosts(new_key, info, addresses);
2260 }
[email protected]05a79d42013-03-28 07:30:092261 return !addresses->empty();
[email protected]78eac2a2012-03-14 19:09:272262}
2263
estarkd1bc206e2015-06-20 00:44:392264bool HostResolverImpl::ServeLocalhost(const Key& key,
2265 const RequestInfo& info,
2266 AddressList* addresses) {
2267 AddressList resolved_addresses;
2268 if (!ResolveLocalHostname(key.hostname, info.port(), &resolved_addresses))
2269 return false;
2270
2271 addresses->clear();
2272
2273 for (const auto& address : resolved_addresses) {
2274 // Include the address if:
2275 // - caller didn't specify an address family, or
2276 // - caller specifically asked for the address family of this address, or
2277 // - this is an IPv6 address and caller specifically asked for IPv4 due
2278 // to lack of detected IPv6 support. (See SystemHostResolverCall for
2279 // rationale).
2280 if (key.address_family == ADDRESS_FAMILY_UNSPECIFIED ||
2281 key.address_family == address.GetFamily() ||
2282 (address.GetFamily() == ADDRESS_FAMILY_IPV6 &&
2283 key.address_family == ADDRESS_FAMILY_IPV4 &&
2284 (key.host_resolver_flags &
2285 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6))) {
2286 addresses->push_back(address);
2287 }
2288 }
2289
2290 return true;
2291}
2292
[email protected]16ee26d2012-03-08 03:34:352293void HostResolverImpl::CacheResult(const Key& key,
[email protected]1339a2a22012-10-17 08:39:432294 const HostCache::Entry& entry,
[email protected]16ee26d2012-03-08 03:34:352295 base::TimeDelta ttl) {
Miriam Gershensone3bc63022017-10-09 19:57:052296 // Don't cache an error unless it has a positive TTL.
2297 if (cache_.get() && (entry.error() == OK || ttl > base::TimeDelta()))
[email protected]1339a2a22012-10-17 08:39:432298 cache_->Set(key, entry, base::TimeTicks::Now(), ttl);
[email protected]ef4c40c2010-09-01 14:42:032299}
2300
[email protected]0f292de02012-02-01 22:28:202301void HostResolverImpl::RemoveJob(Job* job) {
2302 DCHECK(job);
avi9e72eb482016-12-09 21:10:542303 auto it = jobs_.find(job->key());
2304 if (it != jobs_.end() && it->second.get() == job) {
2305 it->second.release();
[email protected]16ee26d2012-03-08 03:34:352306 jobs_.erase(it);
avi9e72eb482016-12-09 21:10:542307 }
[email protected]b59ff372009-07-15 22:04:322308}
2309
[email protected]137af622010-02-05 02:14:352310HostResolverImpl::Key HostResolverImpl::GetEffectiveKeyForRequest(
pauljensen19eb73422015-04-15 23:20:062311 const RequestInfo& info,
martijna23c8962016-03-04 18:18:512312 const IPAddress* ip_address,
tfarina428341112016-09-22 13:38:202313 const NetLogWithSource& net_log) {
[email protected]eaf3a3b2010-09-03 20:34:272314 HostResolverFlags effective_flags =
2315 info.host_resolver_flags() | additional_resolver_flags_;
[email protected]137af622010-02-05 02:14:352316 AddressFamily effective_address_family = info.address_family();
[email protected]9db6f702013-04-10 18:10:512317
mgersh3eba057d2017-02-28 18:50:562318 if (effective_address_family == ADDRESS_FAMILY_UNSPECIFIED &&
2319 // When resolving IPv4 literals, there's no need to probe for IPv6.
2320 // When resolving IPv6 literals, there's no benefit to artificially
2321 // limiting our resolution based on a probe. Prior logic ensures
2322 // that this query is UNSPECIFIED (see effective_address_family
2323 // check above) so the code requesting the resolution should be amenable
2324 // to receiving a IPv6 resolution.
2325 !use_local_ipv6_ && ip_address == nullptr && !IsIPv6Reachable(net_log)) {
2326 effective_address_family = ADDRESS_FAMILY_IPV4;
2327 effective_flags |= HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
[email protected]9db6f702013-04-10 18:10:512328 }
2329
estarkd1bc206e2015-06-20 00:44:392330 return Key(info.hostname(), effective_address_family, effective_flags);
[email protected]137af622010-02-05 02:14:352331}
2332
tfarina428341112016-09-22 13:38:202333bool HostResolverImpl::IsIPv6Reachable(const NetLogWithSource& net_log) {
mgershaf9a9232017-04-13 20:19:032334 // Don't bother checking if the device is on WiFi and IPv6 is assumed to not
2335 // work on WiFi.
2336 if (assume_ipv6_failure_on_wifi_ &&
2337 NetworkChangeNotifier::GetConnectionType() ==
2338 NetworkChangeNotifier::CONNECTION_WIFI) {
2339 return false;
2340 }
2341
eroman1a17ef32016-12-14 01:06:092342 // Cache the result for kIPv6ProbePeriodMs (measured from after
2343 // IsGloballyReachable() completes).
sergeyub8cdc212015-05-14 18:50:372344 bool cached = true;
eroman1a17ef32016-12-14 01:06:092345 if ((base::TimeTicks::Now() - last_ipv6_probe_time_).InMilliseconds() >
2346 kIPv6ProbePeriodMs) {
martijna23c8962016-03-04 18:18:512347 last_ipv6_probe_result_ =
2348 IsGloballyReachable(IPAddress(kIPv6ProbeAddress), net_log);
eroman1a17ef32016-12-14 01:06:092349 last_ipv6_probe_time_ = base::TimeTicks::Now();
sergeyub8cdc212015-05-14 18:50:372350 cached = false;
2351 }
mikecirone8b85c432016-09-08 19:11:002352 net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_IPV6_REACHABILITY_CHECK,
sergeyub8cdc212015-05-14 18:50:372353 base::Bind(&NetLogIPv6AvailableCallback,
2354 last_ipv6_probe_result_, cached));
2355 return last_ipv6_probe_result_;
2356}
2357
mgershaf9a9232017-04-13 20:19:032358bool HostResolverImpl::IsGloballyReachable(const IPAddress& dest,
2359 const NetLogWithSource& net_log) {
mgershaf9a9232017-04-13 20:19:032360 std::unique_ptr<DatagramClientSocket> socket(
2361 ClientSocketFactory::GetDefaultFactory()->CreateDatagramClientSocket(
2362 DatagramSocket::DEFAULT_BIND, RandIntCallback(), net_log.net_log(),
2363 net_log.source()));
2364 int rv = socket->Connect(IPEndPoint(dest, 53));
2365 if (rv != OK)
2366 return false;
2367 IPEndPoint endpoint;
2368 rv = socket->GetLocalAddress(&endpoint);
2369 if (rv != OK)
2370 return false;
2371 DCHECK_EQ(ADDRESS_FAMILY_IPV6, endpoint.GetFamily());
2372 const IPAddress& address = endpoint.address();
2373
2374 bool is_link_local =
2375 (address.bytes()[0] == 0xFE) && ((address.bytes()[1] & 0xC0) == 0x80);
2376 if (is_link_local)
2377 return false;
2378
2379 const uint8_t kTeredoPrefix[] = {0x20, 0x01, 0, 0};
2380 if (IPAddressStartsWith(address, kTeredoPrefix))
2381 return false;
2382
2383 return true;
2384}
2385
mmenke91c17162016-06-02 16:03:232386void HostResolverImpl::RunLoopbackProbeJob() {
Francois Doraya2d01ba2017-09-25 19:17:402387 // Run this asynchronously as it can take 40-100ms and should not block
2388 // initialization.
2389 base::PostTaskWithTraitsAndReplyWithResult(
2390 FROM_HERE,
2391 {base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
2392 base::BindOnce(&HaveOnlyLoopbackAddresses),
2393 base::BindOnce(&HostResolverImpl::SetHaveOnlyLoopbackAddresses,
2394 weak_ptr_factory_.GetWeakPtr()));
mmenke91c17162016-06-02 16:03:232395}
2396
[email protected]35ddc282010-09-21 23:42:062397void HostResolverImpl::AbortAllInProgressJobs() {
[email protected]b3601bc22012-02-21 21:23:202398 // In Abort, a Request callback could spawn new Jobs with matching keys, so
2399 // first collect and remove all running jobs from |jobs_|.
danakj22f90e72016-04-16 01:55:402400 std::vector<std::unique_ptr<Job>> jobs_to_abort;
avi9e72eb482016-12-09 21:10:542401 for (auto it = jobs_.begin(); it != jobs_.end();) {
2402 Job* job = it->second.get();
[email protected]0f292de02012-02-01 22:28:202403 if (job->is_running()) {
avi9e72eb482016-12-09 21:10:542404 jobs_to_abort.push_back(std::move(it->second));
[email protected]b3601bc22012-02-21 21:23:202405 jobs_.erase(it++);
[email protected]0f292de02012-02-01 22:28:202406 } else {
[email protected]b3601bc22012-02-21 21:23:202407 DCHECK(job->is_queued());
2408 ++it;
[email protected]0f292de02012-02-01 22:28:202409 }
[email protected]ef4c40c2010-09-01 14:42:032410 }
[email protected]b3601bc22012-02-21 21:23:202411
[email protected]daae1322013-09-05 18:26:502412 // Pause the dispatcher so it won't start any new dispatcher jobs while
2413 // aborting the old ones. This is needed so that it won't start the second
2414 // DnsTransaction for a job in |jobs_to_abort| if the DnsConfig just became
2415 // invalid.
[email protected]106ccd2c2014-06-17 09:21:002416 PrioritizedDispatcher::Limits limits = dispatcher_->GetLimits();
2417 dispatcher_->SetLimits(
[email protected]daae1322013-09-05 18:26:502418 PrioritizedDispatcher::Limits(limits.reserved_slots.size(), 0));
[email protected]70c04ab2013-08-22 16:05:122419
[email protected]57a48d32012-03-03 00:04:552420 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072421 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]57a48d32012-03-03 00:04:552422
[email protected]16ee26d2012-03-08 03:34:352423 // Then Abort them.
[email protected]11fbca0b2013-06-02 23:37:212424 for (size_t i = 0; self.get() && i < jobs_to_abort.size(); ++i) {
[email protected]57a48d32012-03-03 00:04:552425 jobs_to_abort[i]->Abort();
olli.raulaa21e9eb72015-12-17 08:18:112426 ignore_result(jobs_to_abort[i].release());
[email protected]b3601bc22012-02-21 21:23:202427 }
[email protected]daae1322013-09-05 18:26:502428
2429 if (self)
[email protected]106ccd2c2014-06-17 09:21:002430 dispatcher_->SetLimits(limits);
[email protected]daae1322013-09-05 18:26:502431}
2432
2433void HostResolverImpl::AbortDnsTasks() {
2434 // Pause the dispatcher so it won't start any new dispatcher jobs while
2435 // aborting the old ones. This is needed so that it won't start the second
2436 // DnsTransaction for a job if the DnsConfig just changed.
[email protected]106ccd2c2014-06-17 09:21:002437 PrioritizedDispatcher::Limits limits = dispatcher_->GetLimits();
2438 dispatcher_->SetLimits(
[email protected]daae1322013-09-05 18:26:502439 PrioritizedDispatcher::Limits(limits.reserved_slots.size(), 0));
2440
avi9e72eb482016-12-09 21:10:542441 for (auto it = jobs_.begin(); it != jobs_.end(); ++it)
[email protected]daae1322013-09-05 18:26:502442 it->second->AbortDnsTask();
[email protected]106ccd2c2014-06-17 09:21:002443 dispatcher_->SetLimits(limits);
[email protected]ef4c40c2010-09-01 14:42:032444}
2445
[email protected]78eac2a2012-03-14 19:09:272446void HostResolverImpl::TryServingAllJobsFromHosts() {
2447 if (!HaveDnsConfig())
2448 return;
2449
2450 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2451 // http://crbug.com/117655
2452
2453 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072454 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]78eac2a2012-03-14 19:09:272455
avi9e72eb482016-12-09 21:10:542456 for (auto it = jobs_.begin(); self.get() && it != jobs_.end();) {
2457 Job* job = it->second.get();
[email protected]78eac2a2012-03-14 19:09:272458 ++it;
2459 // This could remove |job| from |jobs_|, but iterator will remain valid.
2460 job->ServeFromHosts();
2461 }
2462}
2463
[email protected]be1a48b2011-01-20 00:12:132464void HostResolverImpl::OnIPAddressChanged() {
sergeyub8cdc212015-05-14 18:50:372465 last_ipv6_probe_time_ = base::TimeTicks();
[email protected]12faa4c2012-11-06 04:44:182466 // Abandon all ProbeJobs.
2467 probe_weak_ptr_factory_.InvalidateWeakPtrs();
Matt Menkeef8f5cf82017-07-20 22:50:172468 if (cache_.get())
mgersh5bb3b9d2017-02-13 21:27:102469 cache_->OnNetworkChange();
[email protected]7c466e92013-07-20 01:44:482470#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
mmenke91c17162016-06-02 16:03:232471 RunLoopbackProbeJob();
[email protected]be1a48b2011-01-20 00:12:132472#endif
2473 AbortAllInProgressJobs();
2474 // |this| may be deleted inside AbortAllInProgressJobs().
2475}
2476
ttuttlecf1158bf2016-03-18 16:37:442477void HostResolverImpl::OnConnectionTypeChanged(
2478 NetworkChangeNotifier::ConnectionType type) {
2479 proc_params_.unresponsive_delay =
2480 GetTimeDeltaForConnectionTypeFromFieldTrialOrDefault(
2481 "DnsUnresponsiveDelayMsByConnectionType",
2482 base::TimeDelta::FromMilliseconds(kDnsDefaultUnresponsiveDelayMs),
2483 type);
2484}
2485
pauljensen101ed372015-04-17 00:11:422486void HostResolverImpl::OnInitialDNSConfigRead() {
2487 UpdateDNSConfig(false);
2488}
2489
[email protected]bb0e34542012-08-31 19:52:402490void HostResolverImpl::OnDNSChanged() {
pauljensen101ed372015-04-17 00:11:422491 UpdateDNSConfig(true);
2492}
2493
2494void HostResolverImpl::UpdateDNSConfig(bool config_changed) {
[email protected]bb0e34542012-08-31 19:52:402495 DnsConfig dns_config;
2496 NetworkChangeNotifier::GetDnsConfig(&dns_config);
[email protected]ec666ab22013-04-17 20:05:592497
[email protected]b4481b222012-03-16 17:13:112498 if (net_log_) {
mikecirone8b85c432016-09-08 19:11:002499 net_log_->AddGlobalEntry(NetLogEventType::DNS_CONFIG_CHANGED,
2500 base::Bind(&NetLogDnsConfigCallback, &dns_config));
[email protected]b4481b222012-03-16 17:13:112501 }
2502
[email protected]01b3b9d2012-08-13 16:18:142503 // TODO(szym): Remove once http://crbug.com/137914 is resolved.
[email protected]d7b9a2b2012-05-31 22:31:192504 received_dns_config_ = dns_config.IsValid();
[email protected]c9fa8f312013-09-17 12:24:522505 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
2506 use_local_ipv6_ = !dns_config.IsValid() || dns_config.use_local_ipv6;
[email protected]78eac2a2012-03-14 19:09:272507
[email protected]a8883e452012-11-17 05:58:062508 num_dns_failures_ = 0;
2509
[email protected]01b3b9d2012-08-13 16:18:142510 // We want a new DnsSession in place, before we Abort running Jobs, so that
2511 // the newly started jobs use the new config.
[email protected]f0f602bd2012-11-15 18:01:022512 if (dns_client_.get()) {
Miriam Gershenson44aafc122017-10-18 19:29:252513 // Make sure that if the update is an initial read, not a change, there
Miriam Gershenson668e8442017-10-31 20:31:532514 // wasn't already a DnsConfig or it's the same one.
2515 DCHECK(config_changed || !dns_client_->GetConfig() ||
2516 dns_client_->GetConfig()->Equals(dns_config));
[email protected]d7b9a2b2012-05-31 22:31:192517 dns_client_->SetConfig(dns_config);
Miriam Gershenson44aafc122017-10-18 19:29:252518 if (dns_client_->GetConfig())
[email protected]f0f602bd2012-11-15 18:01:022519 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
[email protected]f0f602bd2012-11-15 18:01:022520 }
[email protected]01b3b9d2012-08-13 16:18:142521
pauljensen101ed372015-04-17 00:11:422522 if (config_changed) {
2523 // If the DNS server has changed, existing cached info could be wrong so we
mgersh92b1af12017-03-29 15:49:232524 // have to expire our internal cache :( Note that OS level DNS caches, such
pauljensen101ed372015-04-17 00:11:422525 // as NSCD's cache should be dropped automatically by the OS when
2526 // resolv.conf changes so we don't need to do anything to clear that cache.
Matt Menkeef8f5cf82017-07-20 22:50:172527 if (cache_.get())
mgersh92b1af12017-03-29 15:49:232528 cache_->OnNetworkChange();
[email protected]01b3b9d2012-08-13 16:18:142529
pauljensen101ed372015-04-17 00:11:422530 // Life check to bail once |this| is deleted.
2531 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]f0f602bd2012-11-15 18:01:022532
pauljensen101ed372015-04-17 00:11:422533 // Existing jobs will have been sent to the original server so they need to
2534 // be aborted.
2535 AbortAllInProgressJobs();
[email protected]01b3b9d2012-08-13 16:18:142536
pauljensen101ed372015-04-17 00:11:422537 // |this| may be deleted inside AbortAllInProgressJobs().
2538 if (self.get())
2539 TryServingAllJobsFromHosts();
2540 }
[email protected]78eac2a2012-03-14 19:09:272541}
2542
2543bool HostResolverImpl::HaveDnsConfig() const {
[email protected]32b1dbcf2013-01-26 03:48:252544 // Use DnsClient only if it's fully configured and there is no override by
2545 // ScopedDefaultHostResolverProc.
2546 // The alternative is to use NetworkChangeNotifier to override DnsConfig,
2547 // but that would introduce construction order requirements for NCN and SDHRP.
wezb9820d42016-06-22 23:41:042548 return dns_client_ && dns_client_->GetConfig() &&
2549 (proc_params_.resolver_proc || !HostResolverProc::GetDefault());
[email protected]b3601bc22012-02-21 21:23:202550}
2551
[email protected]1ffdda82012-12-12 23:04:222552void HostResolverImpl::OnDnsTaskResolve(int net_error) {
[email protected]f0f602bd2012-11-15 18:01:022553 DCHECK(dns_client_);
[email protected]1ffdda82012-12-12 23:04:222554 if (net_error == OK) {
[email protected]f0f602bd2012-11-15 18:01:022555 num_dns_failures_ = 0;
2556 return;
2557 }
2558 ++num_dns_failures_;
2559 if (num_dns_failures_ < kMaximumDnsFailures)
2560 return;
[email protected]daae1322013-09-05 18:26:502561
2562 // Disable DnsClient until the next DNS change. Must be done before aborting
2563 // DnsTasks, since doing so may start new jobs.
[email protected]f0f602bd2012-11-15 18:01:022564 dns_client_->SetConfig(DnsConfig());
[email protected]daae1322013-09-05 18:26:502565
2566 // Switch jobs with active DnsTasks over to using ProcTasks.
2567 AbortDnsTasks();
2568
[email protected]f0f602bd2012-11-15 18:01:022569 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", false);
Ilya Sherman0eb39802017-12-08 20:58:182570 base::UmaHistogramSparse("AsyncDNS.DnsClientDisabledReason",
2571 std::abs(net_error));
[email protected]f0f602bd2012-11-15 18:01:022572}
2573
danakj22f90e72016-04-16 01:55:402574void HostResolverImpl::SetDnsClient(std::unique_ptr<DnsClient> dns_client) {
[email protected]daae1322013-09-05 18:26:502575 // DnsClient and config must be updated before aborting DnsTasks, since doing
2576 // so may start new jobs.
dchengc7eeda422015-12-26 03:56:482577 dns_client_ = std::move(dns_client);
[email protected]daae1322013-09-05 18:26:502578 if (dns_client_ && !dns_client_->GetConfig() &&
2579 num_dns_failures_ < kMaximumDnsFailures) {
2580 DnsConfig dns_config;
2581 NetworkChangeNotifier::GetDnsConfig(&dns_config);
2582 dns_client_->SetConfig(dns_config);
2583 num_dns_failures_ = 0;
2584 if (dns_client_->GetConfig())
2585 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
[email protected]a8883e452012-11-17 05:58:062586 }
[email protected]daae1322013-09-05 18:26:502587
2588 AbortDnsTasks();
[email protected]a8883e452012-11-17 05:58:062589}
2590
juliatuttled7fa5852016-07-29 13:16:572591void HostResolverImpl::InitializePersistence(
2592 const PersistCallback& persist_callback,
2593 std::unique_ptr<const base::Value> old_data) {
2594 DCHECK(!persist_initialized_);
2595 persist_callback_ = persist_callback;
2596 persist_initialized_ = true;
2597 if (old_data)
2598 ApplyPersistentData(std::move(old_data));
2599}
2600
juliatuttle7e8bf1c2016-08-02 19:09:092601void HostResolverImpl::ApplyPersistentData(
2602 std::unique_ptr<const base::Value> data) {}
2603
2604std::unique_ptr<const base::Value> HostResolverImpl::GetPersistentData() {
2605 return std::unique_ptr<const base::Value>();
2606}
2607
juliatuttled7fa5852016-07-29 13:16:572608void HostResolverImpl::SchedulePersist() {
2609 if (!persist_initialized_ || persist_timer_.IsRunning())
2610 return;
2611 persist_timer_.Start(
2612 FROM_HERE, base::TimeDelta::FromSeconds(kPersistDelaySec),
2613 base::Bind(&HostResolverImpl::DoPersist, weak_ptr_factory_.GetWeakPtr()));
2614}
2615
2616void HostResolverImpl::DoPersist() {
2617 DCHECK(persist_initialized_);
2618 persist_callback_.Run(GetPersistentData());
2619}
2620
maksim.sisov31452af2016-07-27 06:38:102621HostResolverImpl::RequestImpl::~RequestImpl() {
2622 if (job_)
2623 job_->CancelRequest(this);
2624}
2625
2626void HostResolverImpl::RequestImpl::ChangeRequestPriority(
2627 RequestPriority priority) {
2628 job_->ChangeRequestPriority(this, priority);
2629}
2630
[email protected]b59ff372009-07-15 22:04:322631} // namespace net