blob: 907a21fa539b6d60769db56a71eb60325589a636 [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
Miriam Gershenson19faef812018-02-07 23:56:441569 if (duration < base::TimeDelta::FromMilliseconds(10)) {
1570 base::UmaHistogramSparse("Net.DNS.DnsTask.ErrorBeforeFallback.Fast",
1571 std::abs(net_error));
1572 } else {
1573 base::UmaHistogramSparse("Net.DNS.DnsTask.ErrorBeforeFallback.Slow",
1574 std::abs(net_error));
1575 }
[email protected]16c2bd72013-06-28 01:19:221576 dns_task_error_ = net_error;
1577
1578 // TODO(szym): Run ServeFromHosts now if nsswitch.conf says so.
1579 // http://crbug.com/117655
1580
1581 // TODO(szym): Some net errors indicate lack of connectivity. Starting
1582 // ProcTask in that case is a waste of time.
1583 if (resolver_->fallback_to_proctask_) {
[email protected]daae1322013-09-05 18:26:501584 KillDnsTask();
[email protected]16c2bd72013-06-28 01:19:221585 StartProcTask();
1586 } else {
1587 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
Miriam Gershenson66024d72017-12-05 04:30:321588 CompleteRequestsWithError(net_error);
[email protected]b3601bc22012-02-21 21:23:201589 }
1590 }
1591
[email protected]daae1322013-09-05 18:26:501592
1593 // HostResolverImpl::DnsTask::Delegate implementation:
1594
dchengb03027d2014-10-21 12:00:201595 void OnDnsTaskComplete(base::TimeTicks start_time,
1596 int net_error,
1597 const AddressList& addr_list,
1598 base::TimeDelta ttl) override {
[email protected]b3601bc22012-02-21 21:23:201599 DCHECK(is_dns_running());
[email protected]b3601bc22012-02-21 21:23:201600
[email protected]e3bd4822012-10-23 18:01:371601 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]b3601bc22012-02-21 21:23:201602 if (net_error != OK) {
[email protected]16c2bd72013-06-28 01:19:221603 OnDnsTaskFailure(dns_task_->AsWeakPtr(), duration, net_error);
[email protected]b3601bc22012-02-21 21:23:201604 return;
1605 }
Miriam Gershenson61604662017-09-28 23:51:111606
1607 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.DnsTask.SuccessTime", duration);
[email protected]b3601bc22012-02-21 21:23:201608
[email protected]1def74c2012-03-22 20:07:001609 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_DNS_SUCCESS);
[email protected]1339a2a22012-10-17 08:39:431610 RecordTTL(ttl);
[email protected]0adcb2b2012-08-15 21:30:461611
[email protected]1ffdda82012-12-12 23:04:221612 resolver_->OnDnsTaskResolve(OK);
[email protected]f0f602bd2012-11-15 18:01:021613
[email protected]895123222012-10-25 15:21:171614 base::TimeDelta bounded_ttl =
1615 std::max(ttl, base::TimeDelta::FromSeconds(kMinimumTTLSeconds));
1616
eroman0cd87b62016-12-14 19:13:451617 if (ContainsIcannNameCollisionIp(addr_list)) {
1618 CompleteRequestsWithError(ERR_ICANN_NAME_COLLISION);
1619 } else {
Rob Percival94f21ad2017-11-14 10:20:241620 CompleteRequests(MakeCacheEntryWithTTL(net_error, addr_list,
1621 HostCache::Entry::SOURCE_DNS, ttl),
eroman0cd87b62016-12-14 19:13:451622 bounded_ttl);
1623 }
[email protected]b3601bc22012-02-21 21:23:201624 }
1625
dchengb03027d2014-10-21 12:00:201626 void OnFirstDnsTransactionComplete() override {
[email protected]daae1322013-09-05 18:26:501627 DCHECK(dns_task_->needs_two_transactions());
1628 DCHECK_EQ(dns_task_->needs_another_transaction(), is_queued());
1629 // No longer need to occupy two dispatcher slots.
1630 ReduceToOneJobSlot();
1631
1632 // We already have a job slot at the dispatcher, so if the second
1633 // transaction hasn't started, reuse it now instead of waiting in the queue
1634 // for the second slot.
1635 if (dns_task_->needs_another_transaction())
1636 dns_task_->StartSecondTransaction();
1637 }
1638
Miriam Gershenson61604662017-09-28 23:51:111639 void RecordJobHistograms(int error) {
Miriam Gershensonc282ab42017-11-20 23:19:581640 // Used in UMA_HISTOGRAM_ENUMERATION. Do not renumber entries or reuse
1641 // deprecated values.
1642 enum Category {
1643 RESOLVE_SUCCESS = 0,
1644 RESOLVE_FAIL = 1,
1645 RESOLVE_SPECULATIVE_SUCCESS = 2,
1646 RESOLVE_SPECULATIVE_FAIL = 3,
1647 RESOLVE_ABORT = 4,
1648 RESOLVE_SPECULATIVE_ABORT = 5,
Miriam Gershenson61604662017-09-28 23:51:111649 RESOLVE_MAX, // Bounding value.
1650 };
1651 Category category = RESOLVE_MAX; // Illegal value for later DCHECK only.
1652
1653 base::TimeDelta duration = base::TimeTicks::Now() - start_time_;
1654 if (error == OK) {
1655 if (had_non_speculative_request_) {
1656 category = RESOLVE_SUCCESS;
1657 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime", duration);
1658 switch (key_.address_family) {
1659 case ADDRESS_FAMILY_IPV4:
1660 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime.IPV4",
1661 duration);
1662 break;
1663 case ADDRESS_FAMILY_IPV6:
1664 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime.IPV6",
1665 duration);
1666 break;
1667 case ADDRESS_FAMILY_UNSPECIFIED:
1668 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveSuccessTime.UNSPEC",
1669 duration);
1670 break;
1671 }
1672 } else {
1673 category = RESOLVE_SPECULATIVE_SUCCESS;
Miriam Gershenson61604662017-09-28 23:51:111674 }
Miriam Gershensonc282ab42017-11-20 23:19:581675 } else if (error == ERR_NETWORK_CHANGED ||
1676 error == ERR_HOST_RESOLVER_QUEUE_TOO_LARGE) {
1677 category = had_non_speculative_request_ ? RESOLVE_ABORT
1678 : RESOLVE_SPECULATIVE_ABORT;
Miriam Gershenson61604662017-09-28 23:51:111679 } else {
1680 if (had_non_speculative_request_) {
1681 category = RESOLVE_FAIL;
1682 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveFailureTime", duration);
1683 switch (key_.address_family) {
1684 case ADDRESS_FAMILY_IPV4:
Miriam Gershensonc282ab42017-11-20 23:19:581685 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveFailureTime.IPV4",
Miriam Gershenson61604662017-09-28 23:51:111686 duration);
1687 break;
1688 case ADDRESS_FAMILY_IPV6:
Miriam Gershensonc282ab42017-11-20 23:19:581689 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveFailureTime.IPV6",
Miriam Gershenson61604662017-09-28 23:51:111690 duration);
1691 break;
1692 case ADDRESS_FAMILY_UNSPECIFIED:
Miriam Gershensonc282ab42017-11-20 23:19:581693 UMA_HISTOGRAM_LONG_TIMES_100("Net.DNS.ResolveFailureTime.UNSPEC",
Miriam Gershenson61604662017-09-28 23:51:111694 duration);
1695 break;
1696 }
1697 } else {
1698 category = RESOLVE_SPECULATIVE_FAIL;
Miriam Gershenson61604662017-09-28 23:51:111699 }
1700 }
1701 DCHECK_LT(static_cast<int>(category),
1702 static_cast<int>(RESOLVE_MAX)); // Be sure it was set.
1703 UMA_HISTOGRAM_ENUMERATION("Net.DNS.ResolveCategory", category, RESOLVE_MAX);
Miriam Gershensonaaf139582017-11-27 16:06:061704
1705 if (category == RESOLVE_FAIL || category == RESOLVE_ABORT) {
1706 if (duration < base::TimeDelta::FromMilliseconds(10))
Ilya Sherman0eb39802017-12-08 20:58:181707 base::UmaHistogramSparse("Net.DNS.ResolveError.Fast", std::abs(error));
Miriam Gershensonaaf139582017-11-27 16:06:061708 else
Ilya Sherman0eb39802017-12-08 20:58:181709 base::UmaHistogramSparse("Net.DNS.ResolveError.Slow", std::abs(error));
Miriam Gershensonaaf139582017-11-27 16:06:061710 }
Miriam Gershenson61604662017-09-28 23:51:111711 }
1712
[email protected]16ee26d2012-03-08 03:34:351713 // Performs Job's last rites. Completes all Requests. Deletes this.
[email protected]895123222012-10-25 15:21:171714 void CompleteRequests(const HostCache::Entry& entry,
1715 base::TimeDelta ttl) {
[email protected]11fbca0b2013-06-02 23:37:211716 CHECK(resolver_.get());
[email protected]b3601bc22012-02-21 21:23:201717
[email protected]16ee26d2012-03-08 03:34:351718 // This job must be removed from resolver's |jobs_| now to make room for a
1719 // new job with the same key in case one of the OnComplete callbacks decides
1720 // to spawn one. Consequently, the job deletes itself when CompleteRequests
1721 // is done.
danakj22f90e72016-04-16 01:55:401722 std::unique_ptr<Job> self_deleter(this);
[email protected]16ee26d2012-03-08 03:34:351723
1724 resolver_->RemoveJob(this);
1725
[email protected]16ee26d2012-03-08 03:34:351726 if (is_running()) {
[email protected]16ee26d2012-03-08 03:34:351727 if (is_proc_running()) {
[email protected]daae1322013-09-05 18:26:501728 DCHECK(!is_queued());
[email protected]16ee26d2012-03-08 03:34:351729 proc_task_->Cancel();
wezb9820d42016-06-22 23:41:041730 proc_task_ = nullptr;
[email protected]16ee26d2012-03-08 03:34:351731 }
[email protected]daae1322013-09-05 18:26:501732 KillDnsTask();
[email protected]16ee26d2012-03-08 03:34:351733
1734 // Signal dispatcher that a slot has opened.
[email protected]106ccd2c2014-06-17 09:21:001735 resolver_->dispatcher_->OnJobFinished();
[email protected]16ee26d2012-03-08 03:34:351736 } else if (is_queued()) {
[email protected]106ccd2c2014-06-17 09:21:001737 resolver_->dispatcher_->Cancel(handle_);
[email protected]16ee26d2012-03-08 03:34:351738 handle_.Reset();
1739 }
1740
1741 if (num_active_requests() == 0) {
mikecirone8b85c432016-09-08 19:11:001742 net_log_.AddEvent(NetLogEventType::CANCELLED);
1743 net_log_.EndEventWithNetErrorCode(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
[email protected]16ee26d2012-03-08 03:34:351744 OK);
1745 return;
1746 }
[email protected]b3601bc22012-02-21 21:23:201747
mikecirone8b85c432016-09-08 19:11:001748 net_log_.EndEventWithNetErrorCode(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
juliatuttle317860e2016-05-12 14:47:221749 entry.error());
[email protected]68ad3ee2010-01-30 03:45:391750
juliatuttled7fa5852016-07-29 13:16:571751 resolver_->SchedulePersist();
1752
[email protected]78eac2a2012-03-14 19:09:271753 DCHECK(!requests_.empty());
1754
eroman1efc237c2016-12-14 00:00:451755 if (entry.error() == OK || entry.error() == ERR_ICANN_NAME_COLLISION) {
[email protected]d7b9a2b2012-05-31 22:31:191756 // Record this histogram here, when we know the system has a valid DNS
1757 // configuration.
[email protected]539df6c2012-06-19 21:21:291758 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.HaveDnsConfig",
1759 resolver_->received_dns_config_);
[email protected]d7b9a2b2012-05-31 22:31:191760 }
[email protected]16ee26d2012-03-08 03:34:351761
juliatuttle317860e2016-05-12 14:47:221762 bool did_complete = (entry.error() != ERR_NETWORK_CHANGED) &&
1763 (entry.error() != ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
Miriam Gershensonc282ab42017-11-20 23:19:581764 if (did_complete)
[email protected]1339a2a22012-10-17 08:39:431765 resolver_->CacheResult(key_, entry, ttl);
Miriam Gershensonc282ab42017-11-20 23:19:581766
1767 RecordJobHistograms(entry.error());
[email protected]16ee26d2012-03-08 03:34:351768
maksim.sisov31452af2016-07-27 06:38:101769 // Complete all of the requests that were attached to the job and
1770 // detach them.
1771 while (!requests_.empty()) {
1772 RequestImpl* req = requests_.front();
1773 requests_.pop_front();
[email protected]0f292de02012-02-01 22:28:201774 DCHECK_EQ(this, req->job());
1775 // Update the net log and notify registered observers.
juliatuttle317860e2016-05-12 14:47:221776 LogFinishRequest(req->source_net_log(), req->info(), entry.error());
[email protected]51b9a6b2012-06-25 21:50:291777 if (did_complete) {
[email protected]51b9a6b2012-06-25 21:50:291778 // Record effective total time from creation to completion.
Miriam Gershenson90d05e02017-09-28 19:29:281779 RecordTotalTime(req->info().is_speculative(), false,
[email protected]51b9a6b2012-06-25 21:50:291780 base::TimeTicks::Now() - req->request_time());
1781 }
maksim.sisov31452af2016-07-27 06:38:101782 req->OnJobCompleted(this, entry.error(), entry.addresses());
[email protected]0f292de02012-02-01 22:28:201783
1784 // Check if the resolver was destroyed as a result of running the
1785 // callback. If it was, we could continue, but we choose to bail.
[email protected]11fbca0b2013-06-02 23:37:211786 if (!resolver_.get())
[email protected]0f292de02012-02-01 22:28:201787 return;
1788 }
1789 }
1790
[email protected]1339a2a22012-10-17 08:39:431791 // Convenience wrapper for CompleteRequests in case of failure.
1792 void CompleteRequestsWithError(int net_error) {
Rob Percival94f21ad2017-11-14 10:20:241793 CompleteRequests(HostCache::Entry(net_error, AddressList(),
1794 HostCache::Entry::SOURCE_UNKNOWN),
[email protected]895123222012-10-25 15:21:171795 base::TimeDelta());
[email protected]1339a2a22012-10-17 08:39:431796 }
1797
[email protected]b4481b222012-03-16 17:13:111798 RequestPriority priority() const {
1799 return priority_tracker_.highest_priority();
1800 }
1801
1802 // Number of non-canceled requests in |requests_|.
1803 size_t num_active_requests() const {
1804 return priority_tracker_.total_count();
1805 }
1806
wezb9820d42016-06-22 23:41:041807 bool is_dns_running() const { return !!dns_task_; }
[email protected]b4481b222012-03-16 17:13:111808
wezb9820d42016-06-22 23:41:041809 bool is_proc_running() const { return !!proc_task_; }
[email protected]b4481b222012-03-16 17:13:111810
[email protected]0f292de02012-02-01 22:28:201811 base::WeakPtr<HostResolverImpl> resolver_;
1812
1813 Key key_;
1814
1815 // Tracks the highest priority across |requests_|.
1816 PriorityTracker priority_tracker_;
1817
Miriam Gershensone42adb22017-10-16 16:19:381818 // Task runner used for HostResolverProc.
1819 scoped_refptr<base::TaskRunner> proc_task_runner_;
1820
[email protected]0f292de02012-02-01 22:28:201821 bool had_non_speculative_request_;
1822
[email protected]51b9a6b2012-06-25 21:50:291823 // Distinguishes measurements taken while DnsClient was fully configured.
1824 bool had_dns_config_;
1825
[email protected]daae1322013-09-05 18:26:501826 // Number of slots occupied by this Job in resolver's PrioritizedDispatcher.
1827 unsigned num_occupied_job_slots_;
1828
[email protected]1d932852012-06-19 19:40:331829 // Result of DnsTask.
1830 int dns_task_error_;
[email protected]1def74c2012-03-22 20:07:001831
[email protected]51b9a6b2012-06-25 21:50:291832 const base::TimeTicks creation_time_;
1833 base::TimeTicks priority_change_time_;
Miriam Gershenson61604662017-09-28 23:51:111834 base::TimeTicks start_time_;
[email protected]51b9a6b2012-06-25 21:50:291835
tfarina428341112016-09-22 13:38:201836 NetLogWithSource net_log_;
[email protected]0f292de02012-02-01 22:28:201837
[email protected]b3601bc22012-02-21 21:23:201838 // Resolves the host using a HostResolverProc.
[email protected]0f292de02012-02-01 22:28:201839 scoped_refptr<ProcTask> proc_task_;
1840
[email protected]b3601bc22012-02-21 21:23:201841 // Resolves the host using a DnsTransaction.
danakj22f90e72016-04-16 01:55:401842 std::unique_ptr<DnsTask> dns_task_;
[email protected]b3601bc22012-02-21 21:23:201843
[email protected]0f292de02012-02-01 22:28:201844 // All Requests waiting for the result of this Job. Some can be canceled.
Brett Wilsonc6a0c822017-09-12 00:04:291845 base::circular_deque<RequestImpl*> requests_;
[email protected]0f292de02012-02-01 22:28:201846
[email protected]16ee26d2012-03-08 03:34:351847 // A handle used in |HostResolverImpl::dispatcher_|.
[email protected]0f292de02012-02-01 22:28:201848 PrioritizedDispatcher::Handle handle_;
[email protected]68ad3ee2010-01-30 03:45:391849};
1850
1851//-----------------------------------------------------------------------------
1852
[email protected]0f292de02012-02-01 22:28:201853HostResolverImpl::ProcTaskParams::ProcTaskParams(
[email protected]e95d3aca2010-01-11 22:47:431854 HostResolverProc* resolver_proc,
[email protected]0f292de02012-02-01 22:28:201855 size_t max_retry_attempts)
1856 : resolver_proc(resolver_proc),
1857 max_retry_attempts(max_retry_attempts),
ttuttlecf1158bf2016-03-18 16:37:441858 unresponsive_delay(
1859 base::TimeDelta::FromMilliseconds(kDnsDefaultUnresponsiveDelayMs)),
[email protected]0f292de02012-02-01 22:28:201860 retry_factor(2) {
[email protected]106ccd2c2014-06-17 09:21:001861 // Maximum of 4 retry attempts for host resolution.
1862 static const size_t kDefaultMaxRetryAttempts = 4u;
1863 if (max_retry_attempts == HostResolver::kDefaultRetryAttempts)
1864 max_retry_attempts = kDefaultMaxRetryAttempts;
[email protected]0f292de02012-02-01 22:28:201865}
1866
vmpstracd23b72016-02-26 21:08:551867HostResolverImpl::ProcTaskParams::ProcTaskParams(const ProcTaskParams& other) =
1868 default;
1869
Chris Watkins68b15032017-12-01 03:07:131870HostResolverImpl::ProcTaskParams::~ProcTaskParams() = default;
[email protected]0f292de02012-02-01 22:28:201871
[email protected]b59ff372009-07-15 22:04:321872HostResolverImpl::~HostResolverImpl() {
gab47aa7da2017-06-02 16:09:431873 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
[email protected]daae1322013-09-05 18:26:501874 // Prevent the dispatcher from starting new jobs.
[email protected]106ccd2c2014-06-17 09:21:001875 dispatcher_->SetLimitsToZero();
avi9e72eb482016-12-09 21:10:541876 // It's now safe for Jobs to call KillDnsTask on destruction, because
[email protected]daae1322013-09-05 18:26:501877 // OnJobComplete will not start any new jobs.
avi9e72eb482016-12-09 21:10:541878 jobs_.clear();
[email protected]e95d3aca2010-01-11 22:47:431879
[email protected]232a5812011-03-04 22:42:081880 NetworkChangeNotifier::RemoveIPAddressObserver(this);
ttuttlecf1158bf2016-03-18 16:37:441881 NetworkChangeNotifier::RemoveConnectionTypeObserver(this);
[email protected]bb0e34542012-08-31 19:52:401882 NetworkChangeNotifier::RemoveDNSObserver(this);
[email protected]b59ff372009-07-15 22:04:321883}
1884
[email protected]0f292de02012-02-01 22:28:201885void HostResolverImpl::SetMaxQueuedJobs(size_t value) {
[email protected]106ccd2c2014-06-17 09:21:001886 DCHECK_EQ(0u, dispatcher_->num_queued_jobs());
[email protected]0f292de02012-02-01 22:28:201887 DCHECK_GT(value, 0u);
1888 max_queued_jobs_ = value;
[email protected]be1a48b2011-01-20 00:12:131889}
1890
[email protected]684970b2009-08-14 04:54:461891int HostResolverImpl::Resolve(const RequestInfo& info,
[email protected]5109c1952013-08-20 18:44:101892 RequestPriority priority,
[email protected]b59ff372009-07-15 22:04:321893 AddressList* addresses,
[email protected]aa22b242011-11-16 18:58:291894 const CompletionCallback& callback,
maksim.sisov31452af2016-07-27 06:38:101895 std::unique_ptr<Request>* out_req,
tfarina428341112016-09-22 13:38:201896 const NetLogWithSource& source_net_log) {
[email protected]95a214c2011-08-04 21:50:401897 DCHECK(addresses);
gab47aa7da2017-06-02 16:09:431898 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
[email protected]aa22b242011-11-16 18:58:291899 DCHECK_EQ(false, callback.is_null());
maksim.sisov31452af2016-07-27 06:38:101900 DCHECK(out_req);
[email protected]1ac6af92010-06-03 21:00:141901
Chris Palmer9cbf4212017-07-19 01:54:551902 LogStartRequest(source_net_log, info);
pauljensen19eb73422015-04-15 23:20:061903
Matt Menke23b4bbf82017-07-20 19:11:291904 Key key;
1905 int rv = ResolveHelper(info, false, nullptr, source_net_log, addresses, &key);
[email protected]95a214c2011-08-04 21:50:401906 if (rv != ERR_DNS_CACHE_MISS) {
xunjieli26f90452014-11-10 16:23:021907 LogFinishRequest(source_net_log, info, rv);
Miriam Gershenson90d05e02017-09-28 19:29:281908 RecordTotalTime(info.is_speculative(), true, base::TimeDelta());
[email protected]95a214c2011-08-04 21:50:401909 return rv;
[email protected]38368712011-03-02 08:09:401910 }
1911
[email protected]0f292de02012-02-01 22:28:201912 // Next we need to attach our request to a "job". This job is responsible for
1913 // calling "getaddrinfo(hostname)" on a worker thread.
1914
avi9e72eb482016-12-09 21:10:541915 auto jobit = jobs_.find(key);
[email protected]0f292de02012-02-01 22:28:201916 Job* job;
1917 if (jobit == jobs_.end()) {
Miriam Gershensone42adb22017-10-16 16:19:381918 job = new Job(weak_ptr_factory_.GetWeakPtr(), key, priority,
1919 proc_task_runner_, source_net_log);
[email protected]daae1322013-09-05 18:26:501920 job->Schedule(false);
[email protected]0f292de02012-02-01 22:28:201921
1922 // Check for queue overflow.
[email protected]106ccd2c2014-06-17 09:21:001923 if (dispatcher_->num_queued_jobs() > max_queued_jobs_) {
1924 Job* evicted = static_cast<Job*>(dispatcher_->EvictOldestLowest());
[email protected]0f292de02012-02-01 22:28:201925 DCHECK(evicted);
[email protected]16ee26d2012-03-08 03:34:351926 evicted->OnEvicted(); // Deletes |evicted|.
[email protected]0f292de02012-02-01 22:28:201927 if (evicted == job) {
[email protected]0f292de02012-02-01 22:28:201928 rv = ERR_HOST_RESOLVER_QUEUE_TOO_LARGE;
xunjieli26f90452014-11-10 16:23:021929 LogFinishRequest(source_net_log, info, rv);
[email protected]0f292de02012-02-01 22:28:201930 return rv;
1931 }
[email protected]0f292de02012-02-01 22:28:201932 }
avi9e72eb482016-12-09 21:10:541933 jobs_[key] = base::WrapUnique(job);
[email protected]0f292de02012-02-01 22:28:201934 } else {
avi9e72eb482016-12-09 21:10:541935 job = jobit->second.get();
[email protected]0f292de02012-02-01 22:28:201936 }
1937
1938 // Can't complete synchronously. Create and attach request.
Jeremy Roman0579ed62017-08-29 15:56:191939 auto req = std::make_unique<RequestImpl>(source_net_log, info, priority,
avi9e72eb482016-12-09 21:10:541940 callback, addresses, job);
maksim.sisov31452af2016-07-27 06:38:101941 job->AddRequest(req.get());
1942 *out_req = std::move(req);
[email protected]b59ff372009-07-15 22:04:321943
[email protected]0f292de02012-02-01 22:28:201944 // Completion happens during Job::CompleteRequests().
[email protected]b59ff372009-07-15 22:04:321945 return ERR_IO_PENDING;
1946}
1947
Francois Doraya2d01ba2017-09-25 19:17:401948HostResolverImpl::HostResolverImpl(const Options& options, NetLog* net_log)
mmenke91c17162016-06-02 16:03:231949 : max_queued_jobs_(0),
1950 proc_params_(NULL, options.max_retry_attempts),
1951 net_log_(net_log),
1952 received_dns_config_(false),
1953 num_dns_failures_(0),
mgershaf9a9232017-04-13 20:19:031954 assume_ipv6_failure_on_wifi_(false),
mmenke91c17162016-06-02 16:03:231955 use_local_ipv6_(false),
1956 last_ipv6_probe_result_(true),
mmenke91c17162016-06-02 16:03:231957 additional_resolver_flags_(0),
1958 fallback_to_proctask_(true),
juliatuttled7fa5852016-07-29 13:16:571959 persist_initialized_(false),
mmenke91c17162016-06-02 16:03:231960 weak_ptr_factory_(this),
1961 probe_weak_ptr_factory_(this) {
1962 if (options.enable_caching)
1963 cache_ = HostCache::CreateDefaultCache();
1964
1965 PrioritizedDispatcher::Limits job_limits = options.GetDispatcherLimits();
1966 dispatcher_.reset(new PrioritizedDispatcher(job_limits));
1967 max_queued_jobs_ = job_limits.total_jobs * 100u;
1968
1969 DCHECK_GE(dispatcher_->num_priorities(), static_cast<size_t>(NUM_PRIORITIES));
1970
Miriam Gershensone42adb22017-10-16 16:19:381971 proc_task_runner_ = base::CreateTaskRunnerWithTraits(
1972 {base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN});
1973
mmenke91c17162016-06-02 16:03:231974#if defined(OS_WIN)
1975 EnsureWinsockInit();
1976#endif
1977#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
1978 RunLoopbackProbeJob();
1979#endif
1980 NetworkChangeNotifier::AddIPAddressObserver(this);
1981 NetworkChangeNotifier::AddConnectionTypeObserver(this);
1982 NetworkChangeNotifier::AddDNSObserver(this);
1983#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD) && \
Sergey Ulanov49085572017-07-10 23:25:461984 !defined(OS_ANDROID) && !defined(OS_FUCHSIA)
mmenke91c17162016-06-02 16:03:231985 EnsureDnsReloaderInit();
1986#endif
1987
1988 OnConnectionTypeChanged(NetworkChangeNotifier::GetConnectionType());
1989
1990 {
1991 DnsConfig dns_config;
1992 NetworkChangeNotifier::GetDnsConfig(&dns_config);
1993 received_dns_config_ = dns_config.IsValid();
1994 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
1995 use_local_ipv6_ = !dns_config.IsValid() || dns_config.use_local_ipv6;
1996 }
1997
1998 fallback_to_proctask_ = !ConfigureAsyncDnsNoFallbackFieldTrial();
1999}
2000
2001void HostResolverImpl::SetHaveOnlyLoopbackAddresses(bool result) {
2002 if (result) {
2003 additional_resolver_flags_ |= HOST_RESOLVER_LOOPBACK_ONLY;
2004 } else {
2005 additional_resolver_flags_ &= ~HOST_RESOLVER_LOOPBACK_ONLY;
2006 }
2007}
2008
Miriam Gershensone42adb22017-10-16 16:19:382009void HostResolverImpl::SetTaskRunnerForTesting(
2010 scoped_refptr<base::TaskRunner> task_runner) {
2011 proc_task_runner_ = std::move(task_runner);
2012}
2013
Matt Menke23b4bbf82017-07-20 19:11:292014int HostResolverImpl::ResolveHelper(const RequestInfo& info,
juliatuttle9fb7aeb2016-06-06 20:16:332015 bool allow_stale,
2016 HostCache::EntryStaleness* stale_info,
Matt Menke23b4bbf82017-07-20 19:11:292017 const NetLogWithSource& source_net_log,
2018 AddressList* addresses,
2019 Key* key) {
2020 IPAddress ip_address;
2021 IPAddress* ip_address_ptr = nullptr;
2022 if (ip_address.AssignFromIPLiteral(info.hostname())) {
2023 ip_address_ptr = &ip_address;
2024 } else {
2025 // Check that the caller supplied a valid hostname to resolve.
2026 if (!IsValidDNSDomain(info.hostname()))
2027 return ERR_NAME_NOT_RESOLVED;
2028 }
2029
2030 // Build a key that identifies the request in the cache and in the
2031 // outstanding jobs map.
2032 *key = GetEffectiveKeyForRequest(info, ip_address_ptr, source_net_log);
2033
juliatuttle9fb7aeb2016-06-06 20:16:332034 DCHECK(allow_stale == !!stale_info);
[email protected]95a214c2011-08-04 21:50:402035 // The result of |getaddrinfo| for empty hosts is inconsistent across systems.
2036 // On Windows it gives the default interface's address, whereas on Linux it
2037 // gives an error. We will make it fail on all platforms for consistency.
juliatuttle9fb7aeb2016-06-06 20:16:332038 if (info.hostname().empty() || info.hostname().size() > kMaxHostLength) {
2039 MakeNotStale(stale_info);
[email protected]95a214c2011-08-04 21:50:402040 return ERR_NAME_NOT_RESOLVED;
juliatuttle9fb7aeb2016-06-06 20:16:332041 }
[email protected]95a214c2011-08-04 21:50:402042
2043 int net_error = ERR_UNEXPECTED;
Matt Menke23b4bbf82017-07-20 19:11:292044 if (ResolveAsIP(*key, info, ip_address_ptr, &net_error, addresses)) {
juliatuttle9fb7aeb2016-06-06 20:16:332045 MakeNotStale(stale_info);
[email protected]95a214c2011-08-04 21:50:402046 return net_error;
juliatuttle9fb7aeb2016-06-06 20:16:332047 }
Mike Westda1c690e2017-08-12 05:57:162048
2049 // Special-case localhost names, as per the recommendations in
2050 // https://tools.ietf.org/html/draft-west-let-localhost-be-localhost.
2051 if (ServeLocalhost(*key, info, addresses)) {
2052 MakeNotStale(stale_info);
2053 return OK;
2054 }
2055
Matt Menke23b4bbf82017-07-20 19:11:292056 if (ServeFromCache(*key, info, &net_error, addresses, allow_stale,
juliatuttle9fb7aeb2016-06-06 20:16:332057 stale_info)) {
mgersh33d23c02017-03-29 20:24:252058 source_net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_CACHE_HIT,
2059 addresses->CreateNetLogCallback());
juliatuttle9fb7aeb2016-06-06 20:16:332060 // |ServeFromCache()| will set |*stale_info| as needed.
[email protected]78eac2a2012-03-14 19:09:272061 return net_error;
2062 }
Mike Westda1c690e2017-08-12 05:57:162063
[email protected]78eac2a2012-03-14 19:09:272064 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2065 // http://crbug.com/117655
Matt Menke23b4bbf82017-07-20 19:11:292066 if (ServeFromHosts(*key, info, addresses)) {
mgersh33d23c02017-03-29 20:24:252067 source_net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_HOSTS_HIT,
2068 addresses->CreateNetLogCallback());
juliatuttle9fb7aeb2016-06-06 20:16:332069 MakeNotStale(stale_info);
[email protected]78eac2a2012-03-14 19:09:272070 return OK;
2071 }
estarkd1bc206e2015-06-20 00:44:392072
[email protected]78eac2a2012-03-14 19:09:272073 return ERR_DNS_CACHE_MISS;
[email protected]95a214c2011-08-04 21:50:402074}
2075
2076int HostResolverImpl::ResolveFromCache(const RequestInfo& info,
2077 AddressList* addresses,
tfarina428341112016-09-22 13:38:202078 const NetLogWithSource& source_net_log) {
gab47aa7da2017-06-02 16:09:432079 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
[email protected]95a214c2011-08-04 21:50:402080 DCHECK(addresses);
2081
[email protected]95a214c2011-08-04 21:50:402082 // Update the net log and notify registered observers.
xunjieli26f90452014-11-10 16:23:022083 LogStartRequest(source_net_log, info);
[email protected]95a214c2011-08-04 21:50:402084
Matt Menke23b4bbf82017-07-20 19:11:292085 Key key;
2086 int rv = ResolveHelper(info, false, nullptr, source_net_log, addresses, &key);
[email protected]95a214c2011-08-04 21:50:402087
xunjieli26f90452014-11-10 16:23:022088 LogFinishRequest(source_net_log, info, rv);
[email protected]95a214c2011-08-04 21:50:402089 return rv;
2090}
2091
[email protected]a8883e452012-11-17 05:58:062092void HostResolverImpl::SetDnsClientEnabled(bool enabled) {
gab47aa7da2017-06-02 16:09:432093 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
[email protected]a8883e452012-11-17 05:58:062094#if defined(ENABLE_BUILT_IN_DNS)
2095 if (enabled && !dns_client_) {
2096 SetDnsClient(DnsClient::CreateClient(net_log_));
2097 } else if (!enabled && dns_client_) {
danakj22f90e72016-04-16 01:55:402098 SetDnsClient(std::unique_ptr<DnsClient>());
[email protected]a8883e452012-11-17 05:58:062099 }
2100#endif
2101}
2102
[email protected]489d1a82011-10-12 03:09:112103HostCache* HostResolverImpl::GetHostCache() {
2104 return cache_.get();
2105}
[email protected]95a214c2011-08-04 21:50:402106
Rob Percivalbc658a22017-12-13 08:24:422107bool HostResolverImpl::HasCached(base::StringPiece hostname,
2108 HostCache::Entry::Source* source_out,
2109 HostCache::EntryStaleness* stale_out) const {
2110 if (!cache_)
2111 return false;
2112
2113 return cache_->HasEntry(hostname, source_out, stale_out);
2114}
2115
danakj22f90e72016-04-16 01:55:402116std::unique_ptr<base::Value> HostResolverImpl::GetDnsConfigAsValue() const {
[email protected]17e92032012-03-29 00:56:242117 // Check if async DNS is disabled.
2118 if (!dns_client_.get())
tfhef3618f2016-01-11 23:07:082119 return nullptr;
[email protected]17e92032012-03-29 00:56:242120
2121 // Check if async DNS is enabled, but we currently have no configuration
2122 // for it.
2123 const DnsConfig* dns_config = dns_client_->GetConfig();
wezb9820d42016-06-22 23:41:042124 if (!dns_config)
Jeremy Roman0579ed62017-08-29 15:56:192125 return std::make_unique<base::DictionaryValue>();
[email protected]17e92032012-03-29 00:56:242126
2127 return dns_config->ToValue();
2128}
2129
juliatuttle9fb7aeb2016-06-06 20:16:332130int HostResolverImpl::ResolveStaleFromCache(
2131 const RequestInfo& info,
2132 AddressList* addresses,
2133 HostCache::EntryStaleness* stale_info,
tfarina428341112016-09-22 13:38:202134 const NetLogWithSource& source_net_log) {
gab47aa7da2017-06-02 16:09:432135 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
juliatuttle9fb7aeb2016-06-06 20:16:332136 DCHECK(addresses);
2137 DCHECK(stale_info);
2138
2139 // Update the net log and notify registered observers.
2140 LogStartRequest(source_net_log, info);
2141
Matt Menke23b4bbf82017-07-20 19:11:292142 Key key;
2143 int rv =
2144 ResolveHelper(info, true, stale_info, source_net_log, addresses, &key);
juliatuttle9fb7aeb2016-06-06 20:16:332145 LogFinishRequest(source_net_log, info, rv);
2146 return rv;
2147}
2148
Miriam Gershenson2839ef112017-08-30 03:25:372149size_t HostResolverImpl::LastRestoredCacheSize() const {
2150 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
2151
2152 return cache_ ? cache_->last_restore_size() : 0;
2153}
2154
2155size_t HostResolverImpl::CacheSize() const {
2156 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
2157
2158 return cache_ ? cache_->size() : 0;
2159}
2160
mgershaf9a9232017-04-13 20:19:032161void HostResolverImpl::SetNoIPv6OnWifi(bool no_ipv6_on_wifi) {
gab47aa7da2017-06-02 16:09:432162 DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
mgershaf9a9232017-04-13 20:19:032163 assume_ipv6_failure_on_wifi_ = no_ipv6_on_wifi;
2164}
2165
2166bool HostResolverImpl::GetNoIPv6OnWifi() {
2167 return assume_ipv6_failure_on_wifi_;
2168}
2169
[email protected]95a214c2011-08-04 21:50:402170bool HostResolverImpl::ResolveAsIP(const Key& key,
2171 const RequestInfo& info,
martijna23c8962016-03-04 18:18:512172 const IPAddress* ip_address,
[email protected]95a214c2011-08-04 21:50:402173 int* net_error,
2174 AddressList* addresses) {
2175 DCHECK(addresses);
2176 DCHECK(net_error);
martijna23c8962016-03-04 18:18:512177 if (ip_address == nullptr)
[email protected]95a214c2011-08-04 21:50:402178 return false;
2179
[email protected]95a214c2011-08-04 21:50:402180 *net_error = OK;
martijna23c8962016-03-04 18:18:512181 AddressFamily family = GetAddressFamily(*ip_address);
cbentzel1906f872015-06-05 16:25:252182 if (key.address_family != ADDRESS_FAMILY_UNSPECIFIED &&
2183 key.address_family != family) {
[email protected]1c7cf3f82014-08-07 21:33:482184 // Don't return IPv6 addresses for IPv4 queries, and vice versa.
[email protected]95a214c2011-08-04 21:50:402185 *net_error = ERR_NAME_NOT_RESOLVED;
2186 } else {
martijna23c8962016-03-04 18:18:512187 *addresses = AddressList::CreateFromIPAddress(*ip_address, info.port());
[email protected]7054e78f2012-05-07 21:44:562188 if (key.host_resolver_flags & HOST_RESOLVER_CANONNAME)
2189 addresses->SetDefaultCanonicalName();
[email protected]95a214c2011-08-04 21:50:402190 }
2191 return true;
2192}
2193
2194bool HostResolverImpl::ServeFromCache(const Key& key,
2195 const RequestInfo& info,
[email protected]95a214c2011-08-04 21:50:402196 int* net_error,
juliatuttle9fb7aeb2016-06-06 20:16:332197 AddressList* addresses,
2198 bool allow_stale,
2199 HostCache::EntryStaleness* stale_info) {
[email protected]95a214c2011-08-04 21:50:402200 DCHECK(addresses);
2201 DCHECK(net_error);
juliatuttle9fb7aeb2016-06-06 20:16:332202 DCHECK(allow_stale == !!stale_info);
[email protected]95a214c2011-08-04 21:50:402203 if (!info.allow_cached_response() || !cache_.get())
2204 return false;
2205
juliatuttle9fb7aeb2016-06-06 20:16:332206 const HostCache::Entry* cache_entry;
2207 if (allow_stale)
2208 cache_entry = cache_->LookupStale(key, base::TimeTicks::Now(), stale_info);
2209 else
2210 cache_entry = cache_->Lookup(key, base::TimeTicks::Now());
[email protected]95a214c2011-08-04 21:50:402211 if (!cache_entry)
2212 return false;
2213
juliatuttle317860e2016-05-12 14:47:222214 *net_error = cache_entry->error();
[email protected]7054e78f2012-05-07 21:44:562215 if (*net_error == OK) {
[email protected]1339a2a22012-10-17 08:39:432216 if (cache_entry->has_ttl())
juliatuttle317860e2016-05-12 14:47:222217 RecordTTL(cache_entry->ttl());
2218 *addresses = EnsurePortOnAddressList(cache_entry->addresses(), info.port());
[email protected]7054e78f2012-05-07 21:44:562219 }
[email protected]95a214c2011-08-04 21:50:402220 return true;
2221}
2222
[email protected]78eac2a2012-03-14 19:09:272223bool HostResolverImpl::ServeFromHosts(const Key& key,
2224 const RequestInfo& info,
2225 AddressList* addresses) {
2226 DCHECK(addresses);
2227 if (!HaveDnsConfig())
2228 return false;
[email protected]05a79d42013-03-28 07:30:092229 addresses->clear();
2230
[email protected]cb507622012-03-23 16:17:062231 // HOSTS lookups are case-insensitive.
brettw8e2106d2015-08-11 19:30:222232 std::string hostname = base::ToLowerASCII(key.hostname);
[email protected]cb507622012-03-23 16:17:062233
[email protected]05a79d42013-03-28 07:30:092234 const DnsHosts& hosts = dns_client_->GetConfig()->hosts;
2235
[email protected]78eac2a2012-03-14 19:09:272236 // If |address_family| is ADDRESS_FAMILY_UNSPECIFIED other implementations
2237 // (glibc and c-ares) return the first matching line. We have more
2238 // flexibility, but lose implicit ordering.
[email protected]05a79d42013-03-28 07:30:092239 // We prefer IPv6 because "happy eyeballs" will fall back to IPv4 if
2240 // necessary.
2241 if (key.address_family == ADDRESS_FAMILY_IPV6 ||
2242 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
2243 DnsHosts::const_iterator it = hosts.find(
2244 DnsHostsKey(hostname, ADDRESS_FAMILY_IPV6));
2245 if (it != hosts.end())
2246 addresses->push_back(IPEndPoint(it->second, info.port()));
[email protected]78eac2a2012-03-14 19:09:272247 }
2248
[email protected]05a79d42013-03-28 07:30:092249 if (key.address_family == ADDRESS_FAMILY_IPV4 ||
2250 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
2251 DnsHosts::const_iterator it = hosts.find(
2252 DnsHostsKey(hostname, ADDRESS_FAMILY_IPV4));
2253 if (it != hosts.end())
2254 addresses->push_back(IPEndPoint(it->second, info.port()));
2255 }
2256
[email protected]ec666ab22013-04-17 20:05:592257 // If got only loopback addresses and the family was restricted, resolve
2258 // again, without restrictions. See SystemHostResolverCall for rationale.
2259 if ((key.host_resolver_flags &
2260 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6) &&
2261 IsAllIPv4Loopback(*addresses)) {
2262 Key new_key(key);
2263 new_key.address_family = ADDRESS_FAMILY_UNSPECIFIED;
2264 new_key.host_resolver_flags &=
2265 ~HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
2266 return ServeFromHosts(new_key, info, addresses);
2267 }
[email protected]05a79d42013-03-28 07:30:092268 return !addresses->empty();
[email protected]78eac2a2012-03-14 19:09:272269}
2270
estarkd1bc206e2015-06-20 00:44:392271bool HostResolverImpl::ServeLocalhost(const Key& key,
2272 const RequestInfo& info,
2273 AddressList* addresses) {
2274 AddressList resolved_addresses;
2275 if (!ResolveLocalHostname(key.hostname, info.port(), &resolved_addresses))
2276 return false;
2277
2278 addresses->clear();
2279
2280 for (const auto& address : resolved_addresses) {
2281 // Include the address if:
2282 // - caller didn't specify an address family, or
2283 // - caller specifically asked for the address family of this address, or
2284 // - this is an IPv6 address and caller specifically asked for IPv4 due
2285 // to lack of detected IPv6 support. (See SystemHostResolverCall for
2286 // rationale).
2287 if (key.address_family == ADDRESS_FAMILY_UNSPECIFIED ||
2288 key.address_family == address.GetFamily() ||
2289 (address.GetFamily() == ADDRESS_FAMILY_IPV6 &&
2290 key.address_family == ADDRESS_FAMILY_IPV4 &&
2291 (key.host_resolver_flags &
2292 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6))) {
2293 addresses->push_back(address);
2294 }
2295 }
2296
2297 return true;
2298}
2299
[email protected]16ee26d2012-03-08 03:34:352300void HostResolverImpl::CacheResult(const Key& key,
[email protected]1339a2a22012-10-17 08:39:432301 const HostCache::Entry& entry,
[email protected]16ee26d2012-03-08 03:34:352302 base::TimeDelta ttl) {
Miriam Gershensone3bc63022017-10-09 19:57:052303 // Don't cache an error unless it has a positive TTL.
2304 if (cache_.get() && (entry.error() == OK || ttl > base::TimeDelta()))
[email protected]1339a2a22012-10-17 08:39:432305 cache_->Set(key, entry, base::TimeTicks::Now(), ttl);
[email protected]ef4c40c2010-09-01 14:42:032306}
2307
[email protected]0f292de02012-02-01 22:28:202308void HostResolverImpl::RemoveJob(Job* job) {
2309 DCHECK(job);
avi9e72eb482016-12-09 21:10:542310 auto it = jobs_.find(job->key());
2311 if (it != jobs_.end() && it->second.get() == job) {
2312 it->second.release();
[email protected]16ee26d2012-03-08 03:34:352313 jobs_.erase(it);
avi9e72eb482016-12-09 21:10:542314 }
[email protected]b59ff372009-07-15 22:04:322315}
2316
[email protected]137af622010-02-05 02:14:352317HostResolverImpl::Key HostResolverImpl::GetEffectiveKeyForRequest(
pauljensen19eb73422015-04-15 23:20:062318 const RequestInfo& info,
martijna23c8962016-03-04 18:18:512319 const IPAddress* ip_address,
tfarina428341112016-09-22 13:38:202320 const NetLogWithSource& net_log) {
[email protected]eaf3a3b2010-09-03 20:34:272321 HostResolverFlags effective_flags =
2322 info.host_resolver_flags() | additional_resolver_flags_;
[email protected]137af622010-02-05 02:14:352323 AddressFamily effective_address_family = info.address_family();
[email protected]9db6f702013-04-10 18:10:512324
mgersh3eba057d2017-02-28 18:50:562325 if (effective_address_family == ADDRESS_FAMILY_UNSPECIFIED &&
2326 // When resolving IPv4 literals, there's no need to probe for IPv6.
2327 // When resolving IPv6 literals, there's no benefit to artificially
2328 // limiting our resolution based on a probe. Prior logic ensures
2329 // that this query is UNSPECIFIED (see effective_address_family
2330 // check above) so the code requesting the resolution should be amenable
2331 // to receiving a IPv6 resolution.
2332 !use_local_ipv6_ && ip_address == nullptr && !IsIPv6Reachable(net_log)) {
2333 effective_address_family = ADDRESS_FAMILY_IPV4;
2334 effective_flags |= HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
[email protected]9db6f702013-04-10 18:10:512335 }
2336
estarkd1bc206e2015-06-20 00:44:392337 return Key(info.hostname(), effective_address_family, effective_flags);
[email protected]137af622010-02-05 02:14:352338}
2339
tfarina428341112016-09-22 13:38:202340bool HostResolverImpl::IsIPv6Reachable(const NetLogWithSource& net_log) {
mgershaf9a9232017-04-13 20:19:032341 // Don't bother checking if the device is on WiFi and IPv6 is assumed to not
2342 // work on WiFi.
2343 if (assume_ipv6_failure_on_wifi_ &&
2344 NetworkChangeNotifier::GetConnectionType() ==
2345 NetworkChangeNotifier::CONNECTION_WIFI) {
2346 return false;
2347 }
2348
eroman1a17ef32016-12-14 01:06:092349 // Cache the result for kIPv6ProbePeriodMs (measured from after
2350 // IsGloballyReachable() completes).
sergeyub8cdc212015-05-14 18:50:372351 bool cached = true;
eroman1a17ef32016-12-14 01:06:092352 if ((base::TimeTicks::Now() - last_ipv6_probe_time_).InMilliseconds() >
2353 kIPv6ProbePeriodMs) {
martijna23c8962016-03-04 18:18:512354 last_ipv6_probe_result_ =
2355 IsGloballyReachable(IPAddress(kIPv6ProbeAddress), net_log);
eroman1a17ef32016-12-14 01:06:092356 last_ipv6_probe_time_ = base::TimeTicks::Now();
sergeyub8cdc212015-05-14 18:50:372357 cached = false;
2358 }
mikecirone8b85c432016-09-08 19:11:002359 net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_IPV6_REACHABILITY_CHECK,
sergeyub8cdc212015-05-14 18:50:372360 base::Bind(&NetLogIPv6AvailableCallback,
2361 last_ipv6_probe_result_, cached));
2362 return last_ipv6_probe_result_;
2363}
2364
mgershaf9a9232017-04-13 20:19:032365bool HostResolverImpl::IsGloballyReachable(const IPAddress& dest,
2366 const NetLogWithSource& net_log) {
mgershaf9a9232017-04-13 20:19:032367 std::unique_ptr<DatagramClientSocket> socket(
2368 ClientSocketFactory::GetDefaultFactory()->CreateDatagramClientSocket(
2369 DatagramSocket::DEFAULT_BIND, RandIntCallback(), net_log.net_log(),
2370 net_log.source()));
2371 int rv = socket->Connect(IPEndPoint(dest, 53));
2372 if (rv != OK)
2373 return false;
2374 IPEndPoint endpoint;
2375 rv = socket->GetLocalAddress(&endpoint);
2376 if (rv != OK)
2377 return false;
2378 DCHECK_EQ(ADDRESS_FAMILY_IPV6, endpoint.GetFamily());
2379 const IPAddress& address = endpoint.address();
2380
2381 bool is_link_local =
2382 (address.bytes()[0] == 0xFE) && ((address.bytes()[1] & 0xC0) == 0x80);
2383 if (is_link_local)
2384 return false;
2385
2386 const uint8_t kTeredoPrefix[] = {0x20, 0x01, 0, 0};
2387 if (IPAddressStartsWith(address, kTeredoPrefix))
2388 return false;
2389
2390 return true;
2391}
2392
mmenke91c17162016-06-02 16:03:232393void HostResolverImpl::RunLoopbackProbeJob() {
Francois Doraya2d01ba2017-09-25 19:17:402394 // Run this asynchronously as it can take 40-100ms and should not block
2395 // initialization.
2396 base::PostTaskWithTraitsAndReplyWithResult(
2397 FROM_HERE,
2398 {base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
2399 base::BindOnce(&HaveOnlyLoopbackAddresses),
2400 base::BindOnce(&HostResolverImpl::SetHaveOnlyLoopbackAddresses,
2401 weak_ptr_factory_.GetWeakPtr()));
mmenke91c17162016-06-02 16:03:232402}
2403
[email protected]35ddc282010-09-21 23:42:062404void HostResolverImpl::AbortAllInProgressJobs() {
[email protected]b3601bc22012-02-21 21:23:202405 // In Abort, a Request callback could spawn new Jobs with matching keys, so
2406 // first collect and remove all running jobs from |jobs_|.
danakj22f90e72016-04-16 01:55:402407 std::vector<std::unique_ptr<Job>> jobs_to_abort;
avi9e72eb482016-12-09 21:10:542408 for (auto it = jobs_.begin(); it != jobs_.end();) {
2409 Job* job = it->second.get();
[email protected]0f292de02012-02-01 22:28:202410 if (job->is_running()) {
avi9e72eb482016-12-09 21:10:542411 jobs_to_abort.push_back(std::move(it->second));
[email protected]b3601bc22012-02-21 21:23:202412 jobs_.erase(it++);
[email protected]0f292de02012-02-01 22:28:202413 } else {
[email protected]b3601bc22012-02-21 21:23:202414 DCHECK(job->is_queued());
2415 ++it;
[email protected]0f292de02012-02-01 22:28:202416 }
[email protected]ef4c40c2010-09-01 14:42:032417 }
[email protected]b3601bc22012-02-21 21:23:202418
[email protected]daae1322013-09-05 18:26:502419 // Pause the dispatcher so it won't start any new dispatcher jobs while
2420 // aborting the old ones. This is needed so that it won't start the second
2421 // DnsTransaction for a job in |jobs_to_abort| if the DnsConfig just became
2422 // invalid.
[email protected]106ccd2c2014-06-17 09:21:002423 PrioritizedDispatcher::Limits limits = dispatcher_->GetLimits();
2424 dispatcher_->SetLimits(
[email protected]daae1322013-09-05 18:26:502425 PrioritizedDispatcher::Limits(limits.reserved_slots.size(), 0));
[email protected]70c04ab2013-08-22 16:05:122426
[email protected]57a48d32012-03-03 00:04:552427 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072428 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]57a48d32012-03-03 00:04:552429
[email protected]16ee26d2012-03-08 03:34:352430 // Then Abort them.
[email protected]11fbca0b2013-06-02 23:37:212431 for (size_t i = 0; self.get() && i < jobs_to_abort.size(); ++i) {
[email protected]57a48d32012-03-03 00:04:552432 jobs_to_abort[i]->Abort();
olli.raulaa21e9eb72015-12-17 08:18:112433 ignore_result(jobs_to_abort[i].release());
[email protected]b3601bc22012-02-21 21:23:202434 }
[email protected]daae1322013-09-05 18:26:502435
2436 if (self)
[email protected]106ccd2c2014-06-17 09:21:002437 dispatcher_->SetLimits(limits);
[email protected]daae1322013-09-05 18:26:502438}
2439
2440void HostResolverImpl::AbortDnsTasks() {
2441 // Pause the dispatcher so it won't start any new dispatcher jobs while
2442 // aborting the old ones. This is needed so that it won't start the second
2443 // DnsTransaction for a job if the DnsConfig just changed.
[email protected]106ccd2c2014-06-17 09:21:002444 PrioritizedDispatcher::Limits limits = dispatcher_->GetLimits();
2445 dispatcher_->SetLimits(
[email protected]daae1322013-09-05 18:26:502446 PrioritizedDispatcher::Limits(limits.reserved_slots.size(), 0));
2447
avi9e72eb482016-12-09 21:10:542448 for (auto it = jobs_.begin(); it != jobs_.end(); ++it)
[email protected]daae1322013-09-05 18:26:502449 it->second->AbortDnsTask();
[email protected]106ccd2c2014-06-17 09:21:002450 dispatcher_->SetLimits(limits);
[email protected]ef4c40c2010-09-01 14:42:032451}
2452
[email protected]78eac2a2012-03-14 19:09:272453void HostResolverImpl::TryServingAllJobsFromHosts() {
2454 if (!HaveDnsConfig())
2455 return;
2456
2457 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2458 // http://crbug.com/117655
2459
2460 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072461 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]78eac2a2012-03-14 19:09:272462
avi9e72eb482016-12-09 21:10:542463 for (auto it = jobs_.begin(); self.get() && it != jobs_.end();) {
2464 Job* job = it->second.get();
[email protected]78eac2a2012-03-14 19:09:272465 ++it;
2466 // This could remove |job| from |jobs_|, but iterator will remain valid.
2467 job->ServeFromHosts();
2468 }
2469}
2470
[email protected]be1a48b2011-01-20 00:12:132471void HostResolverImpl::OnIPAddressChanged() {
sergeyub8cdc212015-05-14 18:50:372472 last_ipv6_probe_time_ = base::TimeTicks();
[email protected]12faa4c2012-11-06 04:44:182473 // Abandon all ProbeJobs.
2474 probe_weak_ptr_factory_.InvalidateWeakPtrs();
Matt Menkeef8f5cf82017-07-20 22:50:172475 if (cache_.get())
mgersh5bb3b9d2017-02-13 21:27:102476 cache_->OnNetworkChange();
[email protected]7c466e92013-07-20 01:44:482477#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
mmenke91c17162016-06-02 16:03:232478 RunLoopbackProbeJob();
[email protected]be1a48b2011-01-20 00:12:132479#endif
2480 AbortAllInProgressJobs();
2481 // |this| may be deleted inside AbortAllInProgressJobs().
2482}
2483
ttuttlecf1158bf2016-03-18 16:37:442484void HostResolverImpl::OnConnectionTypeChanged(
2485 NetworkChangeNotifier::ConnectionType type) {
2486 proc_params_.unresponsive_delay =
2487 GetTimeDeltaForConnectionTypeFromFieldTrialOrDefault(
2488 "DnsUnresponsiveDelayMsByConnectionType",
2489 base::TimeDelta::FromMilliseconds(kDnsDefaultUnresponsiveDelayMs),
2490 type);
2491}
2492
pauljensen101ed372015-04-17 00:11:422493void HostResolverImpl::OnInitialDNSConfigRead() {
2494 UpdateDNSConfig(false);
2495}
2496
[email protected]bb0e34542012-08-31 19:52:402497void HostResolverImpl::OnDNSChanged() {
pauljensen101ed372015-04-17 00:11:422498 UpdateDNSConfig(true);
2499}
2500
2501void HostResolverImpl::UpdateDNSConfig(bool config_changed) {
[email protected]bb0e34542012-08-31 19:52:402502 DnsConfig dns_config;
2503 NetworkChangeNotifier::GetDnsConfig(&dns_config);
[email protected]ec666ab22013-04-17 20:05:592504
[email protected]b4481b222012-03-16 17:13:112505 if (net_log_) {
mikecirone8b85c432016-09-08 19:11:002506 net_log_->AddGlobalEntry(NetLogEventType::DNS_CONFIG_CHANGED,
2507 base::Bind(&NetLogDnsConfigCallback, &dns_config));
[email protected]b4481b222012-03-16 17:13:112508 }
2509
[email protected]01b3b9d2012-08-13 16:18:142510 // TODO(szym): Remove once http://crbug.com/137914 is resolved.
[email protected]d7b9a2b2012-05-31 22:31:192511 received_dns_config_ = dns_config.IsValid();
[email protected]c9fa8f312013-09-17 12:24:522512 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
2513 use_local_ipv6_ = !dns_config.IsValid() || dns_config.use_local_ipv6;
[email protected]78eac2a2012-03-14 19:09:272514
[email protected]a8883e452012-11-17 05:58:062515 num_dns_failures_ = 0;
2516
[email protected]01b3b9d2012-08-13 16:18:142517 // We want a new DnsSession in place, before we Abort running Jobs, so that
2518 // the newly started jobs use the new config.
[email protected]f0f602bd2012-11-15 18:01:022519 if (dns_client_.get()) {
Miriam Gershenson44aafc122017-10-18 19:29:252520 // Make sure that if the update is an initial read, not a change, there
Miriam Gershenson668e8442017-10-31 20:31:532521 // wasn't already a DnsConfig or it's the same one.
2522 DCHECK(config_changed || !dns_client_->GetConfig() ||
2523 dns_client_->GetConfig()->Equals(dns_config));
[email protected]d7b9a2b2012-05-31 22:31:192524 dns_client_->SetConfig(dns_config);
Miriam Gershenson44aafc122017-10-18 19:29:252525 if (dns_client_->GetConfig())
[email protected]f0f602bd2012-11-15 18:01:022526 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
[email protected]f0f602bd2012-11-15 18:01:022527 }
[email protected]01b3b9d2012-08-13 16:18:142528
pauljensen101ed372015-04-17 00:11:422529 if (config_changed) {
2530 // If the DNS server has changed, existing cached info could be wrong so we
mgersh92b1af12017-03-29 15:49:232531 // have to expire our internal cache :( Note that OS level DNS caches, such
pauljensen101ed372015-04-17 00:11:422532 // as NSCD's cache should be dropped automatically by the OS when
2533 // resolv.conf changes so we don't need to do anything to clear that cache.
Matt Menkeef8f5cf82017-07-20 22:50:172534 if (cache_.get())
mgersh92b1af12017-03-29 15:49:232535 cache_->OnNetworkChange();
[email protected]01b3b9d2012-08-13 16:18:142536
pauljensen101ed372015-04-17 00:11:422537 // Life check to bail once |this| is deleted.
2538 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]f0f602bd2012-11-15 18:01:022539
pauljensen101ed372015-04-17 00:11:422540 // Existing jobs will have been sent to the original server so they need to
2541 // be aborted.
2542 AbortAllInProgressJobs();
[email protected]01b3b9d2012-08-13 16:18:142543
pauljensen101ed372015-04-17 00:11:422544 // |this| may be deleted inside AbortAllInProgressJobs().
2545 if (self.get())
2546 TryServingAllJobsFromHosts();
2547 }
[email protected]78eac2a2012-03-14 19:09:272548}
2549
2550bool HostResolverImpl::HaveDnsConfig() const {
[email protected]32b1dbcf2013-01-26 03:48:252551 // Use DnsClient only if it's fully configured and there is no override by
2552 // ScopedDefaultHostResolverProc.
2553 // The alternative is to use NetworkChangeNotifier to override DnsConfig,
2554 // but that would introduce construction order requirements for NCN and SDHRP.
wezb9820d42016-06-22 23:41:042555 return dns_client_ && dns_client_->GetConfig() &&
2556 (proc_params_.resolver_proc || !HostResolverProc::GetDefault());
[email protected]b3601bc22012-02-21 21:23:202557}
2558
[email protected]1ffdda82012-12-12 23:04:222559void HostResolverImpl::OnDnsTaskResolve(int net_error) {
[email protected]f0f602bd2012-11-15 18:01:022560 DCHECK(dns_client_);
[email protected]1ffdda82012-12-12 23:04:222561 if (net_error == OK) {
[email protected]f0f602bd2012-11-15 18:01:022562 num_dns_failures_ = 0;
2563 return;
2564 }
2565 ++num_dns_failures_;
2566 if (num_dns_failures_ < kMaximumDnsFailures)
2567 return;
[email protected]daae1322013-09-05 18:26:502568
2569 // Disable DnsClient until the next DNS change. Must be done before aborting
2570 // DnsTasks, since doing so may start new jobs.
[email protected]f0f602bd2012-11-15 18:01:022571 dns_client_->SetConfig(DnsConfig());
[email protected]daae1322013-09-05 18:26:502572
2573 // Switch jobs with active DnsTasks over to using ProcTasks.
2574 AbortDnsTasks();
2575
[email protected]f0f602bd2012-11-15 18:01:022576 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", false);
Ilya Sherman0eb39802017-12-08 20:58:182577 base::UmaHistogramSparse("AsyncDNS.DnsClientDisabledReason",
2578 std::abs(net_error));
[email protected]f0f602bd2012-11-15 18:01:022579}
2580
danakj22f90e72016-04-16 01:55:402581void HostResolverImpl::SetDnsClient(std::unique_ptr<DnsClient> dns_client) {
[email protected]daae1322013-09-05 18:26:502582 // DnsClient and config must be updated before aborting DnsTasks, since doing
2583 // so may start new jobs.
dchengc7eeda422015-12-26 03:56:482584 dns_client_ = std::move(dns_client);
[email protected]daae1322013-09-05 18:26:502585 if (dns_client_ && !dns_client_->GetConfig() &&
2586 num_dns_failures_ < kMaximumDnsFailures) {
2587 DnsConfig dns_config;
2588 NetworkChangeNotifier::GetDnsConfig(&dns_config);
2589 dns_client_->SetConfig(dns_config);
2590 num_dns_failures_ = 0;
2591 if (dns_client_->GetConfig())
2592 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
[email protected]a8883e452012-11-17 05:58:062593 }
[email protected]daae1322013-09-05 18:26:502594
2595 AbortDnsTasks();
[email protected]a8883e452012-11-17 05:58:062596}
2597
juliatuttled7fa5852016-07-29 13:16:572598void HostResolverImpl::InitializePersistence(
2599 const PersistCallback& persist_callback,
2600 std::unique_ptr<const base::Value> old_data) {
2601 DCHECK(!persist_initialized_);
2602 persist_callback_ = persist_callback;
2603 persist_initialized_ = true;
2604 if (old_data)
2605 ApplyPersistentData(std::move(old_data));
2606}
2607
juliatuttle7e8bf1c2016-08-02 19:09:092608void HostResolverImpl::ApplyPersistentData(
2609 std::unique_ptr<const base::Value> data) {}
2610
2611std::unique_ptr<const base::Value> HostResolverImpl::GetPersistentData() {
2612 return std::unique_ptr<const base::Value>();
2613}
2614
juliatuttled7fa5852016-07-29 13:16:572615void HostResolverImpl::SchedulePersist() {
2616 if (!persist_initialized_ || persist_timer_.IsRunning())
2617 return;
2618 persist_timer_.Start(
2619 FROM_HERE, base::TimeDelta::FromSeconds(kPersistDelaySec),
2620 base::Bind(&HostResolverImpl::DoPersist, weak_ptr_factory_.GetWeakPtr()));
2621}
2622
2623void HostResolverImpl::DoPersist() {
2624 DCHECK(persist_initialized_);
2625 persist_callback_.Run(GetPersistentData());
2626}
2627
maksim.sisov31452af2016-07-27 06:38:102628HostResolverImpl::RequestImpl::~RequestImpl() {
2629 if (job_)
2630 job_->CancelRequest(this);
2631}
2632
2633void HostResolverImpl::RequestImpl::ChangeRequestPriority(
2634 RequestPriority priority) {
2635 job_->ChangeRequestPriority(this, priority);
2636}
2637
[email protected]b59ff372009-07-15 22:04:322638} // namespace net