blob: 30a4e64243877ff1dab0a606f1a2a57c7bf17049 [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
[email protected]68ad3ee2010-01-30 03:45:3913#include <cmath>
thestiga74ad2b2016-07-11 20:52:3614#include <memory>
[email protected]0f292de02012-02-01 22:28:2015#include <utility>
[email protected]21526002010-05-16 19:42:4616#include <vector>
[email protected]68ad3ee2010-01-30 03:45:3917
[email protected]33152acc2011-10-20 23:37:1218#include "base/bind.h"
[email protected]aa22b242011-11-16 18:58:2919#include "base/bind_helpers.h"
[email protected]0f292de02012-02-01 22:28:2020#include "base/callback.h"
maksim.sisov31452af2016-07-27 06:38:1021#include "base/callback_helpers.h"
[email protected]b59ff372009-07-15 22:04:3222#include "base/compiler_specific.h"
[email protected]58580352010-10-26 04:07:5023#include "base/debug/debugger.h"
mmenke91c17162016-06-02 16:03:2324#include "base/debug/leak_annotations.h"
[email protected]58580352010-10-26 04:07:5025#include "base/debug/stack_trace.h"
Avi Drissman13fc8932015-12-20 04:40:4626#include "base/macros.h"
mmenke91c17162016-06-02 16:03:2327#include "base/memory/ptr_util.h"
[email protected]1e9bbd22010-10-15 16:42:4528#include "base/metrics/field_trial.h"
davidbenad6fc442015-05-18 20:59:1329#include "base/metrics/histogram_macros.h"
30#include "base/metrics/sparse_histogram.h"
eromane1867242015-04-23 23:07:4431#include "base/profiler/scoped_tracker.h"
anujk.sharma7c907f02015-05-29 02:55:4432#include "base/single_thread_task_runner.h"
[email protected]be528af2013-06-11 07:39:4833#include "base/strings/string_util.h"
[email protected]750b2f3c2013-06-07 18:41:0534#include "base/strings/utf_string_conversions.h"
gabf767595f2016-05-11 18:50:3535#include "base/threading/thread_task_runner_handle.h"
[email protected]ac9ba8fe2010-12-30 18:08:3636#include "base/threading/worker_pool.h"
[email protected]66e96c42013-06-28 15:20:3137#include "base/time/time.h"
ssid6d6b40102016-04-05 18:59:5638#include "base/trace_event/trace_event.h"
[email protected]21526002010-05-16 19:42:4639#include "base/values.h"
[email protected]b3601bc22012-02-21 21:23:2040#include "net/base/address_family.h"
[email protected]b59ff372009-07-15 22:04:3241#include "net/base/address_list.h"
[email protected]ee094b82010-08-24 15:55:5142#include "net/base/host_port_pair.h"
martijna23c8962016-03-04 18:18:5143#include "net/base/ip_address.h"
[email protected]1c7cf3f82014-08-07 21:33:4844#include "net/base/ip_endpoint.h"
[email protected]2bb04442010-08-18 18:01:1545#include "net/base/net_errors.h"
xunjieli0b7f5b62016-12-06 20:43:4846#include "net/base/trace_constants.h"
tfarina9ed7f8c52016-02-19 17:50:1847#include "net/base/url_util.h"
[email protected]0adcb2b2012-08-15 21:30:4648#include "net/dns/address_sorter.h"
[email protected]78eac2a2012-03-14 19:09:2749#include "net/dns/dns_client.h"
[email protected]b3601bc22012-02-21 21:23:2050#include "net/dns/dns_config_service.h"
51#include "net/dns/dns_protocol.h"
tfarina47598f042015-10-07 23:08:3552#include "net/dns/dns_reloader.h"
[email protected]b3601bc22012-02-21 21:23:2053#include "net/dns/dns_response.h"
[email protected]b3601bc22012-02-21 21:23:2054#include "net/dns/dns_transaction.h"
tfarina77021d62015-10-11 20:19:0355#include "net/dns/dns_util.h"
[email protected]f2cb3cf2013-03-21 01:40:5356#include "net/dns/host_resolver_proc.h"
eroman87c53d62015-04-02 06:51:0757#include "net/log/net_log.h"
mikecironef22f9812016-10-04 03:40:1958#include "net/log/net_log_capture_mode.h"
mikecirone8b85c432016-09-08 19:11:0059#include "net/log/net_log_event_type.h"
mikecironef22f9812016-10-04 03:40:1960#include "net/log/net_log_parameters_callback.h"
61#include "net/log/net_log_source.h"
mikecirone8b85c432016-09-08 19:11:0062#include "net/log/net_log_source_type.h"
mikecironef22f9812016-10-04 03:40:1963#include "net/log/net_log_with_source.h"
[email protected]9db6f702013-04-10 18:10:5164#include "net/socket/client_socket_factory.h"
tfarina5dd13c22016-11-16 12:08:2665#include "net/socket/datagram_client_socket.h"
pauljensen370f1c72015-02-17 16:59:1466#include "url/url_canon_ip.h"
[email protected]b59ff372009-07-15 22:04:3267
68#if defined(OS_WIN)
69#include "net/base/winsock_init.h"
70#endif
71
72namespace net {
73
[email protected]e95d3aca2010-01-11 22:47:4374namespace {
75
ttuttlecf1158bf2016-03-18 16:37:4476// Default delay between calls to the system resolver for the same hostname.
77// (Can be overridden by field trial.)
78const int64_t kDnsDefaultUnresponsiveDelayMs = 6000;
79
[email protected]6e78dfb2011-07-28 21:34:4780// Limit the size of hostnames that will be resolved to combat issues in
81// some platform's resolvers.
82const size_t kMaxHostLength = 4096;
83
[email protected]a2730882012-01-21 00:56:2784// Default TTL for successful resolutions with ProcTask.
85const unsigned kCacheEntryTTLSeconds = 60;
86
[email protected]b3601bc22012-02-21 21:23:2087// Default TTL for unsuccessful resolutions with ProcTask.
88const unsigned kNegativeCacheEntryTTLSeconds = 0;
89
[email protected]895123222012-10-25 15:21:1790// Minimum TTL for successful resolutions with DnsTask.
91const unsigned kMinimumTTLSeconds = kCacheEntryTTLSeconds;
92
sergeyub8cdc212015-05-14 18:50:3793// Time between IPv6 probes, i.e. for how long results of each IPv6 probe are
94// cached.
95const int kIPv6ProbePeriodMs = 1000;
96
97// Google DNS address used for IPv6 probes.
98const uint8_t kIPv6ProbeAddress[] =
99 { 0x20, 0x01, 0x48, 0x60, 0x48, 0x60, 0x00, 0x00,
100 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x88 };
101
[email protected]24f4bab2010-10-15 01:27:11102// We use a separate histogram name for each platform to facilitate the
103// display of error codes by their symbolic name (since each platform has
104// different mappings).
105const char kOSErrorsForGetAddrinfoHistogramName[] =
106#if defined(OS_WIN)
107 "Net.OSErrorsForGetAddrinfo_Win";
108#elif defined(OS_MACOSX)
109 "Net.OSErrorsForGetAddrinfo_Mac";
110#elif defined(OS_LINUX)
111 "Net.OSErrorsForGetAddrinfo_Linux";
112#else
113 "Net.OSErrorsForGetAddrinfo";
114#endif
115
[email protected]c89b2442011-05-26 14:28:27116// Gets a list of the likely error codes that getaddrinfo() can return
117// (non-exhaustive). These are the error codes that we will track via
118// a histogram.
119std::vector<int> GetAllGetAddrinfoOSErrors() {
120 int os_errors[] = {
121#if defined(OS_POSIX)
[email protected]23f771162011-06-02 18:37:51122#if !defined(OS_FREEBSD)
[email protected]39588992011-07-11 19:54:37123#if !defined(OS_ANDROID)
[email protected]c48aef92011-11-22 23:41:45124 // EAI_ADDRFAMILY has been declared obsolete in Android's and
125 // FreeBSD's netdb.h.
[email protected]c89b2442011-05-26 14:28:27126 EAI_ADDRFAMILY,
[email protected]39588992011-07-11 19:54:37127#endif
[email protected]c48aef92011-11-22 23:41:45128 // EAI_NODATA has been declared obsolete in FreeBSD's netdb.h.
[email protected]23f771162011-06-02 18:37:51129 EAI_NODATA,
130#endif
[email protected]c89b2442011-05-26 14:28:27131 EAI_AGAIN,
132 EAI_BADFLAGS,
133 EAI_FAIL,
134 EAI_FAMILY,
135 EAI_MEMORY,
[email protected]c89b2442011-05-26 14:28:27136 EAI_NONAME,
137 EAI_SERVICE,
138 EAI_SOCKTYPE,
139 EAI_SYSTEM,
140#elif defined(OS_WIN)
141 // See: http://msdn.microsoft.com/en-us/library/ms738520(VS.85).aspx
142 WSA_NOT_ENOUGH_MEMORY,
143 WSAEAFNOSUPPORT,
144 WSAEINVAL,
145 WSAESOCKTNOSUPPORT,
146 WSAHOST_NOT_FOUND,
147 WSANO_DATA,
148 WSANO_RECOVERY,
149 WSANOTINITIALISED,
150 WSATRY_AGAIN,
151 WSATYPE_NOT_FOUND,
152 // The following are not in doc, but might be to appearing in results :-(.
153 WSA_INVALID_HANDLE,
154#endif
155 };
156
157 // Ensure all errors are positive, as histogram only tracks positive values.
158 for (size_t i = 0; i < arraysize(os_errors); ++i) {
159 os_errors[i] = std::abs(os_errors[i]);
160 }
161
162 return base::CustomHistogram::ArrayToCustomRanges(os_errors,
163 arraysize(os_errors));
164}
165
[email protected]1def74c2012-03-22 20:07:00166enum DnsResolveStatus {
167 RESOLVE_STATUS_DNS_SUCCESS = 0,
168 RESOLVE_STATUS_PROC_SUCCESS,
169 RESOLVE_STATUS_FAIL,
[email protected]1d932852012-06-19 19:40:33170 RESOLVE_STATUS_SUSPECT_NETBIOS,
[email protected]1def74c2012-03-22 20:07:00171 RESOLVE_STATUS_MAX
172};
173
eroman91dd3602015-03-26 03:46:33174// ICANN uses this localhost address to indicate a name collision.
175//
176// The policy in Chromium is to fail host resolving if it resolves to
177// this special address.
178//
179// Not however that IP literals are exempt from this policy, so it is still
180// possible to navigate to http://127.0.53.53/ directly.
181//
182// For more details: https://www.icann.org/news/announcement-2-2014-08-01-en
martijna23c8962016-03-04 18:18:51183const uint8_t kIcanNameCollisionIp[] = {127, 0, 53, 53};
eroman91dd3602015-03-26 03:46:33184
eroman1efc237c2016-12-14 00:00:45185bool ContainsIcannNameCollisionIp(const AddressList& addr_list) {
186 for (const auto& endpoint : addr_list) {
187 const IPAddress& addr = endpoint.address();
188 if (addr.IsIPv4() && IPAddressStartsWith(addr, kIcanNameCollisionIp)) {
189 return true;
190 }
191 }
192 return false;
193}
194
[email protected]1def74c2012-03-22 20:07:00195void UmaAsyncDnsResolveStatus(DnsResolveStatus result) {
196 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ResolveStatus",
197 result,
198 RESOLVE_STATUS_MAX);
199}
200
[email protected]1d932852012-06-19 19:40:33201bool ResemblesNetBIOSName(const std::string& hostname) {
202 return (hostname.size() < 16) && (hostname.find('.') == std::string::npos);
203}
204
205// True if |hostname| ends with either ".local" or ".local.".
206bool ResemblesMulticastDNSName(const std::string& hostname) {
207 DCHECK(!hostname.empty());
208 const char kSuffix[] = ".local.";
209 const size_t kSuffixLen = sizeof(kSuffix) - 1;
210 const size_t kSuffixLenTrimmed = kSuffixLen - 1;
thestiga74ad2b2016-07-11 20:52:36211 if (hostname.back() == '.') {
[email protected]1d932852012-06-19 19:40:33212 return hostname.size() > kSuffixLen &&
213 !hostname.compare(hostname.size() - kSuffixLen, kSuffixLen, kSuffix);
214 }
215 return hostname.size() > kSuffixLenTrimmed &&
216 !hostname.compare(hostname.size() - kSuffixLenTrimmed, kSuffixLenTrimmed,
217 kSuffix, kSuffixLenTrimmed);
218}
219
[email protected]34e61362013-07-24 20:41:56220// Attempts to connect a UDP socket to |dest|:53.
tfarina428341112016-09-22 13:38:20221bool IsGloballyReachable(const IPAddress& dest,
222 const NetLogWithSource& net_log) {
eroman0eb394e2015-04-30 23:25:46223 // TODO(eroman): Remove ScopedTracker below once crbug.com/455942 is fixed.
224 tracked_objects::ScopedTracker tracking_profile_1(
eroman2734a9d2015-05-05 19:24:38225 FROM_HERE_WITH_EXPLICIT_FUNCTION("455942 IsGloballyReachable"));
eroman0eb394e2015-04-30 23:25:46226
danakj22f90e72016-04-16 01:55:40227 std::unique_ptr<DatagramClientSocket> socket(
[email protected]9db6f702013-04-10 18:10:51228 ClientSocketFactory::GetDefaultFactory()->CreateDatagramClientSocket(
danakj22f90e72016-04-16 01:55:40229 DatagramSocket::DEFAULT_BIND, RandIntCallback(), net_log.net_log(),
[email protected]2b74a2f2013-07-23 19:37:38230 net_log.source()));
[email protected]34e61362013-07-24 20:41:56231 int rv = socket->Connect(IPEndPoint(dest, 53));
[email protected]e9051722013-04-12 21:58:18232 if (rv != OK)
233 return false;
234 IPEndPoint endpoint;
235 rv = socket->GetLocalAddress(&endpoint);
236 if (rv != OK)
237 return false;
[email protected]1c7cf3f82014-08-07 21:33:48238 DCHECK_EQ(ADDRESS_FAMILY_IPV6, endpoint.GetFamily());
martijna23c8962016-03-04 18:18:51239 const IPAddress& address = endpoint.address();
240
241 bool is_link_local =
242 (address.bytes()[0] == 0xFE) && ((address.bytes()[1] & 0xC0) == 0x80);
[email protected]e9051722013-04-12 21:58:18243 if (is_link_local)
244 return false;
martijna23c8962016-03-04 18:18:51245
Avi Drissman13fc8932015-12-20 04:40:46246 const uint8_t kTeredoPrefix[] = {0x20, 0x01, 0, 0};
martijna23c8962016-03-04 18:18:51247 if (IPAddressStartsWith(address, kTeredoPrefix))
[email protected]e9051722013-04-12 21:58:18248 return false;
martijna23c8962016-03-04 18:18:51249
[email protected]e9051722013-04-12 21:58:18250 return true;
[email protected]9db6f702013-04-10 18:10:51251}
252
[email protected]51b9a6b2012-06-25 21:50:29253// Provide a common macro to simplify code and readability. We must use a
254// macro as the underlying HISTOGRAM macro creates static variables.
255#define DNS_HISTOGRAM(name, time) UMA_HISTOGRAM_CUSTOM_TIMES(name, time, \
256 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromHours(1), 100)
257
258// A macro to simplify code and readability.
259#define DNS_HISTOGRAM_BY_PRIORITY(basename, priority, time) \
260 do { \
261 switch (priority) { \
262 case HIGHEST: DNS_HISTOGRAM(basename "_HIGHEST", time); break; \
263 case MEDIUM: DNS_HISTOGRAM(basename "_MEDIUM", time); break; \
264 case LOW: DNS_HISTOGRAM(basename "_LOW", time); break; \
265 case LOWEST: DNS_HISTOGRAM(basename "_LOWEST", time); break; \
266 case IDLE: DNS_HISTOGRAM(basename "_IDLE", time); break; \
mmenke2f23b70292016-10-26 23:26:42267 case THROTTLED: DNS_HISTOGRAM(basename "_THROTTLED", time); break; \
[email protected]51b9a6b2012-06-25 21:50:29268 } \
269 DNS_HISTOGRAM(basename, time); \
270 } while (0)
271
272// Record time from Request creation until a valid DNS response.
273void RecordTotalTime(bool had_dns_config,
274 bool speculative,
275 base::TimeDelta duration) {
276 if (had_dns_config) {
277 if (speculative) {
278 DNS_HISTOGRAM("AsyncDNS.TotalTime_speculative", duration);
279 } else {
280 DNS_HISTOGRAM("AsyncDNS.TotalTime", duration);
281 }
282 } else {
283 if (speculative) {
284 DNS_HISTOGRAM("DNS.TotalTime_speculative", duration);
285 } else {
286 DNS_HISTOGRAM("DNS.TotalTime", duration);
287 }
288 }
289}
290
[email protected]1339a2a22012-10-17 08:39:43291void RecordTTL(base::TimeDelta ttl) {
292 UMA_HISTOGRAM_CUSTOM_TIMES("AsyncDNS.TTL", ttl,
293 base::TimeDelta::FromSeconds(1),
294 base::TimeDelta::FromDays(1), 100);
295}
296
[email protected]16c2bd72013-06-28 01:19:22297bool ConfigureAsyncDnsNoFallbackFieldTrial() {
298 const bool kDefault = false;
299
300 // Configure the AsyncDns field trial as follows:
301 // groups AsyncDnsNoFallbackA and AsyncDnsNoFallbackB: return true,
302 // groups AsyncDnsA and AsyncDnsB: return false,
303 // groups SystemDnsA and SystemDnsB: return false,
304 // otherwise (trial absent): return default.
305 std::string group_name = base::FieldTrialList::FindFullName("AsyncDns");
brettw3a2c6902015-07-06 19:43:29306 if (!group_name.empty()) {
307 return base::StartsWith(group_name, "AsyncDnsNoFallback",
308 base::CompareCase::INSENSITIVE_ASCII);
309 }
[email protected]16c2bd72013-06-28 01:19:22310 return kDefault;
311}
312
[email protected]d7b9a2b2012-05-31 22:31:19313//-----------------------------------------------------------------------------
314
Avi Drissman13fc8932015-12-20 04:40:46315AddressList EnsurePortOnAddressList(const AddressList& list, uint16_t port) {
[email protected]895123222012-10-25 15:21:17316 if (list.empty() || list.front().port() == port)
317 return list;
318 return AddressList::CopyWithPort(list, port);
[email protected]7054e78f2012-05-07 21:44:56319}
320
[email protected]ec666ab22013-04-17 20:05:59321// Returns true if |addresses| contains only IPv4 loopback addresses.
322bool IsAllIPv4Loopback(const AddressList& addresses) {
323 for (unsigned i = 0; i < addresses.size(); ++i) {
martijna23c8962016-03-04 18:18:51324 const IPAddress& address = addresses[i].address();
[email protected]ec666ab22013-04-17 20:05:59325 switch (addresses[i].GetFamily()) {
326 case ADDRESS_FAMILY_IPV4:
martijna23c8962016-03-04 18:18:51327 if (address.bytes()[0] != 127)
[email protected]ec666ab22013-04-17 20:05:59328 return false;
329 break;
330 case ADDRESS_FAMILY_IPV6:
331 return false;
332 default:
333 NOTREACHED();
334 return false;
335 }
336 }
337 return true;
338}
339
[email protected]cd565142012-06-12 16:21:45340// Creates NetLog parameters when the resolve failed.
danakj22f90e72016-04-16 01:55:40341std::unique_ptr<base::Value> NetLogProcTaskFailedCallback(
Avi Drissman13fc8932015-12-20 04:40:46342 uint32_t attempt_number,
eroman001c3742015-04-23 03:11:17343 int net_error,
344 int os_error,
345 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40346 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]cd565142012-06-12 16:21:45347 if (attempt_number)
348 dict->SetInteger("attempt_number", attempt_number);
[email protected]21526002010-05-16 19:42:46349
[email protected]cd565142012-06-12 16:21:45350 dict->SetInteger("net_error", net_error);
[email protected]13024882011-05-18 23:19:16351
[email protected]cd565142012-06-12 16:21:45352 if (os_error) {
353 dict->SetInteger("os_error", os_error);
[email protected]21526002010-05-16 19:42:46354#if defined(OS_POSIX)
[email protected]cd565142012-06-12 16:21:45355 dict->SetString("os_error_string", gai_strerror(os_error));
[email protected]21526002010-05-16 19:42:46356#elif defined(OS_WIN)
[email protected]cd565142012-06-12 16:21:45357 // Map the error code to a human-readable string.
wezb9820d42016-06-22 23:41:04358 LPWSTR error_string = nullptr;
Peter Kastingbe940e92014-11-20 23:14:08359 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
360 0, // Use the internal message table.
361 os_error,
362 0, // Use default language.
363 (LPWSTR)&error_string,
364 0, // Buffer size.
365 0); // Arguments (unused).
[email protected]ad65a3e2013-12-25 18:18:01366 dict->SetString("os_error_string", base::WideToUTF8(error_string));
[email protected]cd565142012-06-12 16:21:45367 LocalFree(error_string);
[email protected]21526002010-05-16 19:42:46368#endif
[email protected]21526002010-05-16 19:42:46369 }
370
dchengc7eeda422015-12-26 03:56:48371 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45372}
[email protected]a9813302012-04-28 09:29:28373
[email protected]cd565142012-06-12 16:21:45374// Creates NetLog parameters when the DnsTask failed.
danakj22f90e72016-04-16 01:55:40375std::unique_ptr<base::Value> NetLogDnsTaskFailedCallback(
estade5e5529d2015-05-21 20:59:11376 int net_error,
377 int dns_error,
378 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40379 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]cd565142012-06-12 16:21:45380 dict->SetInteger("net_error", net_error);
381 if (dns_error)
382 dict->SetInteger("dns_error", dns_error);
dchengc7eeda422015-12-26 03:56:48383 return std::move(dict);
thestiga74ad2b2016-07-11 20:52:36384}
[email protected]ee094b82010-08-24 15:55:51385
[email protected]cd565142012-06-12 16:21:45386// Creates NetLog parameters containing the information in a RequestInfo object,
mikecironef22f9812016-10-04 03:40:19387// along with the associated NetLogSource.
danakj22f90e72016-04-16 01:55:40388std::unique_ptr<base::Value> NetLogRequestInfoCallback(
estade5e5529d2015-05-21 20:59:11389 const HostResolver::RequestInfo* info,
390 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40391 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]b3601bc22012-02-21 21:23:20392
[email protected]cd565142012-06-12 16:21:45393 dict->SetString("host", info->host_port_pair().ToString());
394 dict->SetInteger("address_family",
395 static_cast<int>(info->address_family()));
396 dict->SetBoolean("allow_cached_response", info->allow_cached_response());
397 dict->SetBoolean("is_speculative", info->is_speculative());
dchengc7eeda422015-12-26 03:56:48398 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45399}
[email protected]b3601bc22012-02-21 21:23:20400
[email protected]cd565142012-06-12 16:21:45401// Creates NetLog parameters for the creation of a HostResolverImpl::Job.
danakj22f90e72016-04-16 01:55:40402std::unique_ptr<base::Value> NetLogJobCreationCallback(
mikecironef22f9812016-10-04 03:40:19403 const NetLogSource& source,
estade5e5529d2015-05-21 20:59:11404 const std::string* host,
405 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40406 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
estade5e5529d2015-05-21 20:59:11407 source.AddToEventParameters(dict.get());
[email protected]cd565142012-06-12 16:21:45408 dict->SetString("host", *host);
dchengc7eeda422015-12-26 03:56:48409 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45410}
[email protected]a9813302012-04-28 09:29:28411
[email protected]cd565142012-06-12 16:21:45412// Creates NetLog parameters for HOST_RESOLVER_IMPL_JOB_ATTACH/DETACH events.
danakj22f90e72016-04-16 01:55:40413std::unique_ptr<base::Value> NetLogJobAttachCallback(
mikecironef22f9812016-10-04 03:40:19414 const NetLogSource& source,
estade5e5529d2015-05-21 20:59:11415 RequestPriority priority,
416 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40417 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
estade5e5529d2015-05-21 20:59:11418 source.AddToEventParameters(dict.get());
[email protected]3b04d1f22013-10-16 00:23:56419 dict->SetString("priority", RequestPriorityToString(priority));
dchengc7eeda422015-12-26 03:56:48420 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45421}
[email protected]b3601bc22012-02-21 21:23:20422
[email protected]cd565142012-06-12 16:21:45423// Creates NetLog parameters for the DNS_CONFIG_CHANGED event.
danakj22f90e72016-04-16 01:55:40424std::unique_ptr<base::Value> NetLogDnsConfigCallback(
estade5e5529d2015-05-21 20:59:11425 const DnsConfig* config,
426 NetLogCaptureMode /* capture_mode */) {
tfhef3618f2016-01-11 23:07:08427 return config->ToValue();
[email protected]cd565142012-06-12 16:21:45428}
[email protected]b4481b222012-03-16 17:13:11429
danakj22f90e72016-04-16 01:55:40430std::unique_ptr<base::Value> NetLogIPv6AvailableCallback(
estade5e5529d2015-05-21 20:59:11431 bool ipv6_available,
432 bool cached,
433 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40434 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
sergeyub8cdc212015-05-14 18:50:37435 dict->SetBoolean("ipv6_available", ipv6_available);
436 dict->SetBoolean("cached", cached);
dchengc7eeda422015-12-26 03:56:48437 return std::move(dict);
sergeyub8cdc212015-05-14 18:50:37438}
439
[email protected]0f292de02012-02-01 22:28:20440// The logging routines are defined here because some requests are resolved
441// without a Request object.
442
443// Logs when a request has just been started.
tfarina428341112016-09-22 13:38:20444void LogStartRequest(const NetLogWithSource& source_net_log,
[email protected]0f292de02012-02-01 22:28:20445 const HostResolver::RequestInfo& info) {
mikecirone8b85c432016-09-08 19:11:00446 source_net_log.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_REQUEST,
447 base::Bind(&NetLogRequestInfoCallback, &info));
[email protected]0f292de02012-02-01 22:28:20448}
449
450// Logs when a request has just completed (before its callback is run).
tfarina428341112016-09-22 13:38:20451void LogFinishRequest(const NetLogWithSource& source_net_log,
[email protected]0f292de02012-02-01 22:28:20452 const HostResolver::RequestInfo& info,
[email protected]b3601bc22012-02-21 21:23:20453 int net_error) {
xunjieli26f90452014-11-10 16:23:02454 source_net_log.EndEventWithNetErrorCode(
mikecirone8b85c432016-09-08 19:11:00455 NetLogEventType::HOST_RESOLVER_IMPL_REQUEST, net_error);
[email protected]0f292de02012-02-01 22:28:20456}
457
458// Logs when a request has been cancelled.
tfarina428341112016-09-22 13:38:20459void LogCancelRequest(const NetLogWithSource& source_net_log,
[email protected]0f292de02012-02-01 22:28:20460 const HostResolverImpl::RequestInfo& info) {
mikecirone8b85c432016-09-08 19:11:00461 source_net_log.AddEvent(NetLogEventType::CANCELLED);
462 source_net_log.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_REQUEST);
[email protected]0f292de02012-02-01 22:28:20463}
464
[email protected]b59ff372009-07-15 22:04:32465//-----------------------------------------------------------------------------
466
[email protected]0f292de02012-02-01 22:28:20467// Keeps track of the highest priority.
468class PriorityTracker {
469 public:
[email protected]8c98d002012-07-18 19:02:27470 explicit PriorityTracker(RequestPriority initial_priority)
471 : highest_priority_(initial_priority), total_count_(0) {
[email protected]0f292de02012-02-01 22:28:20472 memset(counts_, 0, sizeof(counts_));
473 }
474
475 RequestPriority highest_priority() const {
476 return highest_priority_;
477 }
478
479 size_t total_count() const {
480 return total_count_;
481 }
482
483 void Add(RequestPriority req_priority) {
484 ++total_count_;
485 ++counts_[req_priority];
[email protected]31ae7ab2012-04-24 21:09:05486 if (highest_priority_ < req_priority)
[email protected]0f292de02012-02-01 22:28:20487 highest_priority_ = req_priority;
488 }
489
490 void Remove(RequestPriority req_priority) {
491 DCHECK_GT(total_count_, 0u);
492 DCHECK_GT(counts_[req_priority], 0u);
493 --total_count_;
494 --counts_[req_priority];
495 size_t i;
thestiga74ad2b2016-07-11 20:52:36496 for (i = highest_priority_; i > MINIMUM_PRIORITY && !counts_[i]; --i) {
497 }
[email protected]0f292de02012-02-01 22:28:20498 highest_priority_ = static_cast<RequestPriority>(i);
499
[email protected]31ae7ab2012-04-24 21:09:05500 // In absence of requests, default to MINIMUM_PRIORITY.
501 if (total_count_ == 0)
502 DCHECK_EQ(MINIMUM_PRIORITY, highest_priority_);
[email protected]0f292de02012-02-01 22:28:20503 }
504
505 private:
506 RequestPriority highest_priority_;
507 size_t total_count_;
508 size_t counts_[NUM_PRIORITIES];
509};
510
juliatuttle9fb7aeb2016-06-06 20:16:33511void MakeNotStale(HostCache::EntryStaleness* stale_info) {
512 if (!stale_info)
513 return;
514 stale_info->expired_by = base::TimeDelta::FromSeconds(-1);
515 stale_info->network_changes = 0;
516 stale_info->stale_hits = 0;
517}
518
juliatuttled7fa5852016-07-29 13:16:57519// Persist data every five minutes (potentially, cache and learned RTT).
520const int64_t kPersistDelaySec = 300;
521
[email protected]c54a8912012-10-22 22:09:43522} // namespace
[email protected]0f292de02012-02-01 22:28:20523
524//-----------------------------------------------------------------------------
525
tfarina9ed7f8c52016-02-19 17:50:18526bool ResolveLocalHostname(base::StringPiece host,
527 uint16_t port,
528 AddressList* address_list) {
tfarina9ed7f8c52016-02-19 17:50:18529 address_list->clear();
530
531 bool is_local6;
532 if (!IsLocalHostname(host, &is_local6))
533 return false;
534
martijna23c8962016-03-04 18:18:51535 address_list->push_back(IPEndPoint(IPAddress::IPv6Localhost(), port));
tfarina9ed7f8c52016-02-19 17:50:18536 if (!is_local6) {
martijna23c8962016-03-04 18:18:51537 address_list->push_back(IPEndPoint(IPAddress::IPv4Localhost(), port));
tfarina9ed7f8c52016-02-19 17:50:18538 }
539
540 return true;
541}
542
[email protected]daae1322013-09-05 18:26:50543const unsigned HostResolverImpl::kMaximumDnsFailures = 16;
544
[email protected]0f292de02012-02-01 22:28:20545// Holds the data for a request that could not be completed synchronously.
546// It is owned by a Job. Canceled Requests are only marked as canceled rather
547// than removed from the Job's |requests_| list.
maksim.sisov31452af2016-07-27 06:38:10548class HostResolverImpl::RequestImpl : public HostResolver::Request {
[email protected]b59ff372009-07-15 22:04:32549 public:
tfarina428341112016-09-22 13:38:20550 RequestImpl(const NetLogWithSource& source_net_log,
maksim.sisov31452af2016-07-27 06:38:10551 const RequestInfo& info,
552 RequestPriority priority,
553 const CompletionCallback& callback,
554 AddressList* addresses,
555 Job* job)
[email protected]ee094b82010-08-24 15:55:51556 : source_net_log_(source_net_log),
[email protected]54e13772009-08-14 03:01:09557 info_(info),
[email protected]5109c1952013-08-20 18:44:10558 priority_(priority),
maksim.sisov31452af2016-07-27 06:38:10559 job_(job),
[email protected]54e13772009-08-14 03:01:09560 callback_(callback),
[email protected]51b9a6b2012-06-25 21:50:29561 addresses_(addresses),
[email protected]5109c1952013-08-20 18:44:10562 request_time_(base::TimeTicks::Now()) {}
[email protected]b59ff372009-07-15 22:04:32563
maksim.sisov31452af2016-07-27 06:38:10564 ~RequestImpl() override;
565
566 void ChangeRequestPriority(RequestPriority priority) override;
567
568 void OnJobCancelled(Job* job) {
569 DCHECK_EQ(job_, job);
wezb9820d42016-06-22 23:41:04570 job_ = nullptr;
571 addresses_ = nullptr;
[email protected]aa22b242011-11-16 18:58:29572 callback_.Reset();
[email protected]b59ff372009-07-15 22:04:32573 }
574
[email protected]0f292de02012-02-01 22:28:20575 // Prepare final AddressList and call completion callback.
maksim.sisov31452af2016-07-27 06:38:10576 void OnJobCompleted(Job* job, int error, const AddressList& addr_list) {
577 DCHECK_EQ(job_, job);
[email protected]895123222012-10-25 15:21:17578 if (error == OK)
579 *addresses_ = EnsurePortOnAddressList(addr_list, info_.port());
maksim.sisov31452af2016-07-27 06:38:10580 job_ = nullptr;
581 addresses_ = nullptr;
582 base::ResetAndReturn(&callback_).Run(error);
[email protected]b59ff372009-07-15 22:04:32583 }
584
[email protected]b59ff372009-07-15 22:04:32585 Job* job() const {
586 return job_;
587 }
588
[email protected]0f292de02012-02-01 22:28:20589 // NetLog for the source, passed in HostResolver::Resolve.
tfarina428341112016-09-22 13:38:20590 const NetLogWithSource& source_net_log() { return source_net_log_; }
[email protected]ee094b82010-08-24 15:55:51591
[email protected]b59ff372009-07-15 22:04:32592 const RequestInfo& info() const {
593 return info_;
594 }
595
[email protected]5109c1952013-08-20 18:44:10596 RequestPriority priority() const { return priority_; }
juliatuttlec53b19a72016-05-05 13:51:31597 void set_priority(RequestPriority priority) { priority_ = priority; }
[email protected]5109c1952013-08-20 18:44:10598
599 base::TimeTicks request_time() const { return request_time_; }
[email protected]51b9a6b2012-06-25 21:50:29600
[email protected]b59ff372009-07-15 22:04:32601 private:
tfarina428341112016-09-22 13:38:20602 const NetLogWithSource source_net_log_;
[email protected]54e13772009-08-14 03:01:09603
[email protected]b59ff372009-07-15 22:04:32604 // The request info that started the request.
[email protected]5109c1952013-08-20 18:44:10605 const RequestInfo info_;
606
juliatuttlec53b19a72016-05-05 13:51:31607 RequestPriority priority_;
[email protected]b59ff372009-07-15 22:04:32608
[email protected]0f292de02012-02-01 22:28:20609 // The resolve job that this request is dependent on.
[email protected]b59ff372009-07-15 22:04:32610 Job* job_;
611
612 // The user's callback to invoke when the request completes.
[email protected]aa22b242011-11-16 18:58:29613 CompletionCallback callback_;
[email protected]b59ff372009-07-15 22:04:32614
615 // The address list to save result into.
616 AddressList* addresses_;
617
[email protected]51b9a6b2012-06-25 21:50:29618 const base::TimeTicks request_time_;
619
maksim.sisov31452af2016-07-27 06:38:10620 DISALLOW_COPY_AND_ASSIGN(RequestImpl);
[email protected]b59ff372009-07-15 22:04:32621};
622
[email protected]1e9bbd22010-10-15 16:42:45623//------------------------------------------------------------------------------
624
mmenke91c17162016-06-02 16:03:23625// Calls HostResolverProc using a worker task runner. Performs retries if
626// necessary.
[email protected]0f292de02012-02-01 22:28:20627//
628// Whenever we try to resolve the host, we post a delayed task to check if host
629// resolution (OnLookupComplete) is completed or not. If the original attempt
630// hasn't completed, then we start another attempt for host resolution. We take
631// the results from the first attempt that finishes and ignore the results from
632// all other attempts.
633//
634// TODO(szym): Move to separate source file for testing and mocking.
635//
636class HostResolverImpl::ProcTask
637 : public base::RefCountedThreadSafe<HostResolverImpl::ProcTask> {
[email protected]b59ff372009-07-15 22:04:32638 public:
[email protected]b3601bc22012-02-21 21:23:20639 typedef base::Callback<void(int net_error,
640 const AddressList& addr_list)> Callback;
[email protected]b59ff372009-07-15 22:04:32641
[email protected]0f292de02012-02-01 22:28:20642 ProcTask(const Key& key,
643 const ProcTaskParams& params,
644 const Callback& callback,
mmenke91c17162016-06-02 16:03:23645 scoped_refptr<base::TaskRunner> worker_task_runner,
tfarina428341112016-09-22 13:38:20646 const NetLogWithSource& job_net_log)
[email protected]0f292de02012-02-01 22:28:20647 : key_(key),
648 params_(params),
649 callback_(callback),
mmenke91c17162016-06-02 16:03:23650 worker_task_runner_(std::move(worker_task_runner)),
651 network_task_runner_(base::ThreadTaskRunnerHandle::Get()),
[email protected]0f292de02012-02-01 22:28:20652 attempt_number_(0),
653 completed_attempt_number_(0),
654 completed_attempt_error_(ERR_UNEXPECTED),
655 had_non_speculative_request_(false),
[email protected]b3601bc22012-02-21 21:23:20656 net_log_(job_net_log) {
[email protected]90499482013-06-01 00:39:50657 if (!params_.resolver_proc.get())
[email protected]0f292de02012-02-01 22:28:20658 params_.resolver_proc = HostResolverProc::GetDefault();
659 // If default is unset, use the system proc.
[email protected]90499482013-06-01 00:39:50660 if (!params_.resolver_proc.get())
[email protected]1ee9afa12013-04-16 14:18:06661 params_.resolver_proc = new SystemHostResolverProc();
[email protected]b59ff372009-07-15 22:04:32662 }
663
[email protected]b59ff372009-07-15 22:04:32664 void Start() {
mmenke91c17162016-06-02 16:03:23665 DCHECK(network_task_runner_->BelongsToCurrentThread());
mikecirone8b85c432016-09-08 19:11:00666 net_log_.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_PROC_TASK);
[email protected]189163e2011-05-11 01:48:54667 StartLookupAttempt();
668 }
[email protected]252b699b2010-02-05 21:38:06669
[email protected]0f292de02012-02-01 22:28:20670 // Cancels this ProcTask. It will be orphaned. Any outstanding resolve
mmenke91c17162016-06-02 16:03:23671 // attempts running on worker thread will continue running. Only once all the
[email protected]0f292de02012-02-01 22:28:20672 // attempts complete will the final reference to this ProcTask be released.
673 void Cancel() {
mmenke91c17162016-06-02 16:03:23674 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20675
[email protected]0adcb2b2012-08-15 21:30:46676 if (was_canceled() || was_completed())
[email protected]0f292de02012-02-01 22:28:20677 return;
678
[email protected]0f292de02012-02-01 22:28:20679 callback_.Reset();
mikecirone8b85c432016-09-08 19:11:00680 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_PROC_TASK);
[email protected]0f292de02012-02-01 22:28:20681 }
682
683 void set_had_non_speculative_request() {
mmenke91c17162016-06-02 16:03:23684 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20685 had_non_speculative_request_ = true;
686 }
687
688 bool was_canceled() const {
mmenke91c17162016-06-02 16:03:23689 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20690 return callback_.is_null();
691 }
692
693 bool was_completed() const {
mmenke91c17162016-06-02 16:03:23694 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20695 return completed_attempt_number_ > 0;
696 }
697
698 private:
[email protected]a9813302012-04-28 09:29:28699 friend class base::RefCountedThreadSafe<ProcTask>;
700 ~ProcTask() {}
701
[email protected]189163e2011-05-11 01:48:54702 void StartLookupAttempt() {
mmenke91c17162016-06-02 16:03:23703 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54704 base::TimeTicks start_time = base::TimeTicks::Now();
705 ++attempt_number_;
706 // Dispatch the lookup attempt to a worker thread.
mmenke91c17162016-06-02 16:03:23707 if (!worker_task_runner_->PostTask(
708 FROM_HERE, base::Bind(&ProcTask::DoLookup, this, start_time,
709 attempt_number_))) {
[email protected]b59ff372009-07-15 22:04:32710 NOTREACHED();
711
mmenke91c17162016-06-02 16:03:23712 // Since this method may have been called from Resolve(), can't just call
713 // OnLookupComplete(). Instead, must wait until Resolve() has returned
714 // (IO_PENDING).
715 network_task_runner_->PostTask(
716 FROM_HERE,
717 base::Bind(&ProcTask::OnLookupComplete, this, AddressList(),
718 start_time, attempt_number_, ERR_UNEXPECTED, 0));
[email protected]189163e2011-05-11 01:48:54719 return;
[email protected]b59ff372009-07-15 22:04:32720 }
[email protected]13024882011-05-18 23:19:16721
mikecirone8b85c432016-09-08 19:11:00722 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_ATTEMPT_STARTED,
tfarina5e24b242015-10-27 13:11:28723 NetLog::IntCallback("attempt_number", attempt_number_));
[email protected]13024882011-05-18 23:19:16724
mmenke91c17162016-06-02 16:03:23725 // If the results aren't received within a given time, RetryIfNotComplete
726 // will start a new attempt if none of the outstanding attempts have
727 // completed yet.
[email protected]0f292de02012-02-01 22:28:20728 if (attempt_number_ <= params_.max_retry_attempts) {
mmenke91c17162016-06-02 16:03:23729 network_task_runner_->PostDelayedTask(
730 FROM_HERE, base::Bind(&ProcTask::RetryIfNotComplete, this),
[email protected]7e560102012-03-08 20:58:42731 params_.unresponsive_delay);
[email protected]06ef6d92011-05-19 04:24:58732 }
[email protected]b59ff372009-07-15 22:04:32733 }
734
mmenke91c17162016-06-02 16:03:23735 // WARNING: In production, this code runs on a worker pool. The shutdown code
736 // cannot wait for it to finish, so this code must be very careful about using
737 // other objects (like MessageLoops, Singletons, etc). During shutdown these
738 // objects may no longer exist. Multiple DoLookups() could be running in
739 // parallel, so any state inside of |this| must not mutate .
[email protected]189163e2011-05-11 01:48:54740 void DoLookup(const base::TimeTicks& start_time,
Avi Drissman13fc8932015-12-20 04:40:46741 const uint32_t attempt_number) {
[email protected]189163e2011-05-11 01:48:54742 AddressList results;
743 int os_error = 0;
mmenke91c17162016-06-02 16:03:23744 // Running on a worker task runner.
[email protected]0f292de02012-02-01 22:28:20745 int error = params_.resolver_proc->Resolve(key_.hostname,
746 key_.address_family,
747 key_.host_resolver_flags,
748 &results,
749 &os_error);
[email protected]b59ff372009-07-15 22:04:32750
mmenke91c17162016-06-02 16:03:23751 network_task_runner_->PostTask(
752 FROM_HERE, base::Bind(&ProcTask::OnLookupComplete, this, results,
753 start_time, attempt_number, error, os_error));
[email protected]189163e2011-05-11 01:48:54754 }
755
mmenke91c17162016-06-02 16:03:23756 // Makes next attempt if DoLookup() has not finished.
[email protected]0f292de02012-02-01 22:28:20757 void RetryIfNotComplete() {
mmenke91c17162016-06-02 16:03:23758 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54759
[email protected]0f292de02012-02-01 22:28:20760 if (was_completed() || was_canceled())
[email protected]189163e2011-05-11 01:48:54761 return;
762
[email protected]0f292de02012-02-01 22:28:20763 params_.unresponsive_delay *= params_.retry_factor;
[email protected]189163e2011-05-11 01:48:54764 StartLookupAttempt();
[email protected]b59ff372009-07-15 22:04:32765 }
766
anujk.sharma7c907f02015-05-29 02:55:44767 // Callback for when DoLookup() completes (runs on task runner thread).
[email protected]189163e2011-05-11 01:48:54768 void OnLookupComplete(const AddressList& results,
769 const base::TimeTicks& start_time,
Avi Drissman13fc8932015-12-20 04:40:46770 const uint32_t attempt_number,
[email protected]189163e2011-05-11 01:48:54771 int error,
772 const int os_error) {
xunjieli0b7f5b62016-12-06 20:43:48773 TRACE_EVENT0(kNetTracingCategory, "ProcTask::OnLookupComplete");
mmenke91c17162016-06-02 16:03:23774 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]49b70b222013-05-07 21:24:23775 // If results are empty, we should return an error.
776 bool empty_list_on_ok = (error == OK && results.empty());
777 UMA_HISTOGRAM_BOOLEAN("DNS.EmptyAddressListAndNoError", empty_list_on_ok);
778 if (empty_list_on_ok)
779 error = ERR_NAME_NOT_RESOLVED;
[email protected]189163e2011-05-11 01:48:54780
781 bool was_retry_attempt = attempt_number > 1;
782
[email protected]2d3b7762010-10-09 00:35:47783 // Ideally the following code would be part of host_resolver_proc.cc,
[email protected]b3601bc22012-02-21 21:23:20784 // however it isn't safe to call NetworkChangeNotifier from worker threads.
mmenke91c17162016-06-02 16:03:23785 // So do it here on the IO thread instead.
[email protected]189163e2011-05-11 01:48:54786 if (error != OK && NetworkChangeNotifier::IsOffline())
787 error = ERR_INTERNET_DISCONNECTED;
[email protected]2d3b7762010-10-09 00:35:47788
[email protected]b3601bc22012-02-21 21:23:20789 // If this is the first attempt that is finishing later, then record data
790 // for the first attempt. Won't contaminate with retry attempt's data.
[email protected]189163e2011-05-11 01:48:54791 if (!was_retry_attempt)
792 RecordPerformanceHistograms(start_time, error, os_error);
793
794 RecordAttemptHistograms(start_time, attempt_number, error, os_error);
[email protected]f2d8c4212010-02-02 00:56:35795
[email protected]0f292de02012-02-01 22:28:20796 if (was_canceled())
[email protected]b59ff372009-07-15 22:04:32797 return;
798
mikecironef22f9812016-10-04 03:40:19799 NetLogParametersCallback net_log_callback;
[email protected]0f292de02012-02-01 22:28:20800 if (error != OK) {
[email protected]cd565142012-06-12 16:21:45801 net_log_callback = base::Bind(&NetLogProcTaskFailedCallback,
802 attempt_number,
803 error,
804 os_error);
[email protected]0f292de02012-02-01 22:28:20805 } else {
tfarina5e24b242015-10-27 13:11:28806 net_log_callback = NetLog::IntCallback("attempt_number", attempt_number);
[email protected]0f292de02012-02-01 22:28:20807 }
mikecirone8b85c432016-09-08 19:11:00808 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_ATTEMPT_FINISHED,
[email protected]cd565142012-06-12 16:21:45809 net_log_callback);
[email protected]0f292de02012-02-01 22:28:20810
811 if (was_completed())
812 return;
813
814 // Copy the results from the first worker thread that resolves the host.
815 results_ = results;
816 completed_attempt_number_ = attempt_number;
817 completed_attempt_error_ = error;
818
[email protected]e87b8b512011-06-14 22:12:52819 if (was_retry_attempt) {
820 // If retry attempt finishes before 1st attempt, then get stats on how
821 // much time is saved by having spawned an extra attempt.
822 retry_attempt_finished_time_ = base::TimeTicks::Now();
823 }
824
[email protected]189163e2011-05-11 01:48:54825 if (error != OK) {
[email protected]cd565142012-06-12 16:21:45826 net_log_callback = base::Bind(&NetLogProcTaskFailedCallback,
827 0, error, os_error);
[email protected]ee094b82010-08-24 15:55:51828 } else {
[email protected]cd565142012-06-12 16:21:45829 net_log_callback = results_.CreateNetLogCallback();
[email protected]ee094b82010-08-24 15:55:51830 }
mikecirone8b85c432016-09-08 19:11:00831 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_PROC_TASK,
[email protected]cd565142012-06-12 16:21:45832 net_log_callback);
[email protected]ee094b82010-08-24 15:55:51833
[email protected]b3601bc22012-02-21 21:23:20834 callback_.Run(error, results_);
[email protected]b59ff372009-07-15 22:04:32835 }
836
[email protected]189163e2011-05-11 01:48:54837 void RecordPerformanceHistograms(const base::TimeTicks& start_time,
838 const int error,
839 const int os_error) const {
mmenke91c17162016-06-02 16:03:23840 DCHECK(network_task_runner_->BelongsToCurrentThread());
asvitkinec0fb8022014-08-26 04:39:35841 enum Category { // Used in UMA_HISTOGRAM_ENUMERATION.
[email protected]1e9bbd22010-10-15 16:42:45842 RESOLVE_SUCCESS,
843 RESOLVE_FAIL,
844 RESOLVE_SPECULATIVE_SUCCESS,
845 RESOLVE_SPECULATIVE_FAIL,
846 RESOLVE_MAX, // Bounding value.
847 };
848 int category = RESOLVE_MAX; // Illegal value for later DCHECK only.
849
[email protected]189163e2011-05-11 01:48:54850 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
851 if (error == OK) {
[email protected]1e9bbd22010-10-15 16:42:45852 if (had_non_speculative_request_) {
853 category = RESOLVE_SUCCESS;
854 DNS_HISTOGRAM("DNS.ResolveSuccess", duration);
855 } else {
856 category = RESOLVE_SPECULATIVE_SUCCESS;
857 DNS_HISTOGRAM("DNS.ResolveSpeculativeSuccess", duration);
858 }
[email protected]7e96d792011-06-10 17:08:23859
[email protected]78eac2a2012-03-14 19:09:27860 // Log DNS lookups based on |address_family|. This will help us determine
[email protected]7e96d792011-06-10 17:08:23861 // if IPv4 or IPv4/6 lookups are faster or slower.
thestiga74ad2b2016-07-11 20:52:36862 switch (key_.address_family) {
[email protected]7e96d792011-06-10 17:08:23863 case ADDRESS_FAMILY_IPV4:
864 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_IPV4", duration);
865 break;
866 case ADDRESS_FAMILY_IPV6:
867 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_IPV6", duration);
868 break;
869 case ADDRESS_FAMILY_UNSPECIFIED:
870 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_UNSPEC", duration);
871 break;
872 }
[email protected]1e9bbd22010-10-15 16:42:45873 } else {
874 if (had_non_speculative_request_) {
875 category = RESOLVE_FAIL;
876 DNS_HISTOGRAM("DNS.ResolveFail", duration);
877 } else {
878 category = RESOLVE_SPECULATIVE_FAIL;
879 DNS_HISTOGRAM("DNS.ResolveSpeculativeFail", duration);
880 }
[email protected]78eac2a2012-03-14 19:09:27881 // Log DNS lookups based on |address_family|. This will help us determine
[email protected]7e96d792011-06-10 17:08:23882 // if IPv4 or IPv4/6 lookups are faster or slower.
thestiga74ad2b2016-07-11 20:52:36883 switch (key_.address_family) {
[email protected]7e96d792011-06-10 17:08:23884 case ADDRESS_FAMILY_IPV4:
885 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_IPV4", duration);
886 break;
887 case ADDRESS_FAMILY_IPV6:
888 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_IPV6", duration);
889 break;
890 case ADDRESS_FAMILY_UNSPECIFIED:
891 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_UNSPEC", duration);
892 break;
893 }
[email protected]c833e322010-10-16 23:51:36894 UMA_HISTOGRAM_CUSTOM_ENUMERATION(kOSErrorsForGetAddrinfoHistogramName,
[email protected]189163e2011-05-11 01:48:54895 std::abs(os_error),
[email protected]1e9bbd22010-10-15 16:42:45896 GetAllGetAddrinfoOSErrors());
897 }
[email protected]051b6ab2010-10-18 16:50:46898 DCHECK_LT(category, static_cast<int>(RESOLVE_MAX)); // Be sure it was set.
[email protected]1e9bbd22010-10-15 16:42:45899
900 UMA_HISTOGRAM_ENUMERATION("DNS.ResolveCategory", category, RESOLVE_MAX);
[email protected]1e9bbd22010-10-15 16:42:45901 }
902
[email protected]189163e2011-05-11 01:48:54903 void RecordAttemptHistograms(const base::TimeTicks& start_time,
Avi Drissman13fc8932015-12-20 04:40:46904 const uint32_t attempt_number,
[email protected]189163e2011-05-11 01:48:54905 const int error,
906 const int os_error) const {
mmenke91c17162016-06-02 16:03:23907 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54908 bool first_attempt_to_complete =
909 completed_attempt_number_ == attempt_number;
[email protected]e87b8b512011-06-14 22:12:52910 bool is_first_attempt = (attempt_number == 1);
[email protected]1e9bbd22010-10-15 16:42:45911
[email protected]189163e2011-05-11 01:48:54912 if (first_attempt_to_complete) {
913 // If this was first attempt to complete, then record the resolution
914 // status of the attempt.
915 if (completed_attempt_error_ == OK) {
916 UMA_HISTOGRAM_ENUMERATION(
917 "DNS.AttemptFirstSuccess", attempt_number, 100);
918 } else {
919 UMA_HISTOGRAM_ENUMERATION(
920 "DNS.AttemptFirstFailure", attempt_number, 100);
921 }
922 }
923
924 if (error == OK)
925 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptSuccess", attempt_number, 100);
926 else
927 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptFailure", attempt_number, 100);
928
[email protected]e87b8b512011-06-14 22:12:52929 // If first attempt didn't finish before retry attempt, then calculate stats
930 // on how much time is saved by having spawned an extra attempt.
[email protected]0f292de02012-02-01 22:28:20931 if (!first_attempt_to_complete && is_first_attempt && !was_canceled()) {
[email protected]e87b8b512011-06-14 22:12:52932 DNS_HISTOGRAM("DNS.AttemptTimeSavedByRetry",
933 base::TimeTicks::Now() - retry_attempt_finished_time_);
934 }
935
[email protected]0f292de02012-02-01 22:28:20936 if (was_canceled() || !first_attempt_to_complete) {
[email protected]189163e2011-05-11 01:48:54937 // Count those attempts which completed after the job was already canceled
938 // OR after the job was already completed by an earlier attempt (so in
939 // effect).
940 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptDiscarded", attempt_number, 100);
941
[email protected]0f292de02012-02-01 22:28:20942 // Record if job is canceled.
943 if (was_canceled())
[email protected]189163e2011-05-11 01:48:54944 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptCancelled", attempt_number, 100);
945 }
946
947 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
948 if (error == OK)
949 DNS_HISTOGRAM("DNS.AttemptSuccessDuration", duration);
950 else
951 DNS_HISTOGRAM("DNS.AttemptFailDuration", duration);
952 }
[email protected]1e9bbd22010-10-15 16:42:45953
anujk.sharma7c907f02015-05-29 02:55:44954 // Set on the task runner thread, read on the worker thread.
[email protected]123ab1e32009-10-21 19:12:57955 Key key_;
[email protected]b59ff372009-07-15 22:04:32956
[email protected]0f292de02012-02-01 22:28:20957 // Holds an owning reference to the HostResolverProc that we are going to use.
[email protected]b59ff372009-07-15 22:04:32958 // This may not be the current resolver procedure by the time we call
959 // ResolveAddrInfo, but that's OK... we'll use it anyways, and the owning
960 // reference ensures that it remains valid until we are done.
[email protected]0f292de02012-02-01 22:28:20961 ProcTaskParams params_;
[email protected]b59ff372009-07-15 22:04:32962
[email protected]0f292de02012-02-01 22:28:20963 // The listener to the results of this ProcTask.
964 Callback callback_;
965
mmenke91c17162016-06-02 16:03:23966 // Task runner for the call to the HostResolverProc.
967 scoped_refptr<base::TaskRunner> worker_task_runner_;
968
969 // Used to post events onto the network thread.
970 scoped_refptr<base::SingleThreadTaskRunner> network_task_runner_;
[email protected]189163e2011-05-11 01:48:54971
972 // Keeps track of the number of attempts we have made so far to resolve the
973 // host. Whenever we start an attempt to resolve the host, we increase this
974 // number.
Avi Drissman13fc8932015-12-20 04:40:46975 uint32_t attempt_number_;
[email protected]189163e2011-05-11 01:48:54976
977 // The index of the attempt which finished first (or 0 if the job is still in
978 // progress).
Avi Drissman13fc8932015-12-20 04:40:46979 uint32_t completed_attempt_number_;
[email protected]189163e2011-05-11 01:48:54980
981 // The result (a net error code) from the first attempt to complete.
982 int completed_attempt_error_;
[email protected]252b699b2010-02-05 21:38:06983
[email protected]e87b8b512011-06-14 22:12:52984 // The time when retry attempt was finished.
985 base::TimeTicks retry_attempt_finished_time_;
986
[email protected]252b699b2010-02-05 21:38:06987 // True if a non-speculative request was ever attached to this job
[email protected]0f292de02012-02-01 22:28:20988 // (regardless of whether or not it was later canceled.
[email protected]252b699b2010-02-05 21:38:06989 // This boolean is used for histogramming the duration of jobs used to
990 // service non-speculative requests.
991 bool had_non_speculative_request_;
992
[email protected]b59ff372009-07-15 22:04:32993 AddressList results_;
994
tfarina428341112016-09-22 13:38:20995 NetLogWithSource net_log_;
[email protected]ee094b82010-08-24 15:55:51996
[email protected]0f292de02012-02-01 22:28:20997 DISALLOW_COPY_AND_ASSIGN(ProcTask);
[email protected]b59ff372009-07-15 22:04:32998};
999
1000//-----------------------------------------------------------------------------
1001
mmenke91c17162016-06-02 16:03:231002// Wraps a call to HaveOnlyLoopbackAddresses to be executed on a
1003// |worker_task_runner|, as it takes 40-100ms and should not block
1004// initialization.
[email protected]12faa4c2012-11-06 04:44:181005class HostResolverImpl::LoopbackProbeJob {
1006 public:
mmenke91c17162016-06-02 16:03:231007 LoopbackProbeJob(const base::WeakPtr<HostResolverImpl>& resolver,
1008 base::TaskRunner* worker_task_runner)
1009 : resolver_(resolver), result_(false) {
[email protected]11fbca0b2013-06-02 23:37:211010 DCHECK(resolver.get());
mmenke91c17162016-06-02 16:03:231011
1012 // |worker_task_runner| may posts tasks to the WorkerPool, so need this to
1013 // avoid reporting worker pool leaks in tests. The WorkerPool doesn't have a
1014 // flushing API, so can't do anything about them, other than using another
1015 // task runner.
1016 // http://crbug.com/248513
1017 ANNOTATE_SCOPED_MEMORY_LEAK;
1018
1019 worker_task_runner->PostTaskAndReply(
[email protected]12faa4c2012-11-06 04:44:181020 FROM_HERE,
1021 base::Bind(&LoopbackProbeJob::DoProbe, base::Unretained(this)),
mmenke91c17162016-06-02 16:03:231022 base::Bind(&LoopbackProbeJob::OnProbeComplete, base::Owned(this)));
[email protected]12faa4c2012-11-06 04:44:181023 }
1024
1025 virtual ~LoopbackProbeJob() {}
1026
1027 private:
1028 // Runs on worker thread.
1029 void DoProbe() {
1030 result_ = HaveOnlyLoopbackAddresses();
1031 }
1032
1033 void OnProbeComplete() {
[email protected]11fbca0b2013-06-02 23:37:211034 if (!resolver_.get())
[email protected]12faa4c2012-11-06 04:44:181035 return;
1036 resolver_->SetHaveOnlyLoopbackAddresses(result_);
1037 }
1038
anujk.sharma7c907f02015-05-29 02:55:441039 // Used/set only on task runner thread.
[email protected]12faa4c2012-11-06 04:44:181040 base::WeakPtr<HostResolverImpl> resolver_;
1041
1042 bool result_;
1043
1044 DISALLOW_COPY_AND_ASSIGN(LoopbackProbeJob);
1045};
1046
[email protected]0f8f1b432010-03-16 19:06:031047//-----------------------------------------------------------------------------
1048
[email protected]b3601bc22012-02-21 21:23:201049// Resolves the hostname using DnsTransaction.
1050// TODO(szym): This could be moved to separate source file as well.
[email protected]0adcb2b2012-08-15 21:30:461051class HostResolverImpl::DnsTask : public base::SupportsWeakPtr<DnsTask> {
[email protected]b3601bc22012-02-21 21:23:201052 public:
[email protected]daae1322013-09-05 18:26:501053 class Delegate {
1054 public:
1055 virtual void OnDnsTaskComplete(base::TimeTicks start_time,
1056 int net_error,
1057 const AddressList& addr_list,
1058 base::TimeDelta ttl) = 0;
1059
1060 // Called when the first of two jobs succeeds. If the first completed
1061 // transaction fails, this is not called. Also not called when the DnsTask
1062 // only needs to run one transaction.
1063 virtual void OnFirstDnsTransactionComplete() = 0;
1064
1065 protected:
1066 Delegate() {}
1067 virtual ~Delegate() {}
1068 };
[email protected]b3601bc22012-02-21 21:23:201069
[email protected]0adcb2b2012-08-15 21:30:461070 DnsTask(DnsClient* client,
[email protected]b3601bc22012-02-21 21:23:201071 const Key& key,
[email protected]daae1322013-09-05 18:26:501072 Delegate* delegate,
tfarina428341112016-09-22 13:38:201073 const NetLogWithSource& job_net_log)
[email protected]0adcb2b2012-08-15 21:30:461074 : client_(client),
[email protected]daae1322013-09-05 18:26:501075 key_(key),
1076 delegate_(delegate),
1077 net_log_(job_net_log),
1078 num_completed_transactions_(0),
1079 task_start_time_(base::TimeTicks::Now()) {
[email protected]0adcb2b2012-08-15 21:30:461080 DCHECK(client);
[email protected]daae1322013-09-05 18:26:501081 DCHECK(delegate_);
[email protected]1affed62013-08-21 03:24:501082 }
1083
[email protected]daae1322013-09-05 18:26:501084 bool needs_two_transactions() const {
1085 return key_.address_family == ADDRESS_FAMILY_UNSPECIFIED;
1086 }
1087
1088 bool needs_another_transaction() const {
1089 return needs_two_transactions() && !transaction_aaaa_;
1090 }
1091
1092 void StartFirstTransaction() {
1093 DCHECK_EQ(0u, num_completed_transactions_);
mikecirone8b85c432016-09-08 19:11:001094 net_log_.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_DNS_TASK);
[email protected]daae1322013-09-05 18:26:501095 if (key_.address_family == ADDRESS_FAMILY_IPV6) {
1096 StartAAAA();
1097 } else {
1098 StartA();
1099 }
1100 }
1101
1102 void StartSecondTransaction() {
1103 DCHECK(needs_two_transactions());
1104 StartAAAA();
[email protected]70c04ab2013-08-22 16:05:121105 }
1106
1107 private:
[email protected]daae1322013-09-05 18:26:501108 void StartA() {
1109 DCHECK(!transaction_a_);
1110 DCHECK_NE(ADDRESS_FAMILY_IPV6, key_.address_family);
1111 transaction_a_ = CreateTransaction(ADDRESS_FAMILY_IPV4);
1112 transaction_a_->Start();
1113 }
1114
1115 void StartAAAA() {
1116 DCHECK(!transaction_aaaa_);
1117 DCHECK_NE(ADDRESS_FAMILY_IPV4, key_.address_family);
1118 transaction_aaaa_ = CreateTransaction(ADDRESS_FAMILY_IPV6);
1119 transaction_aaaa_->Start();
1120 }
1121
danakj22f90e72016-04-16 01:55:401122 std::unique_ptr<DnsTransaction> CreateTransaction(AddressFamily family) {
[email protected]daae1322013-09-05 18:26:501123 DCHECK_NE(ADDRESS_FAMILY_UNSPECIFIED, family);
1124 return client_->GetTransactionFactory()->CreateTransaction(
1125 key_.hostname,
1126 family == ADDRESS_FAMILY_IPV6 ? dns_protocol::kTypeAAAA :
1127 dns_protocol::kTypeA,
1128 base::Bind(&DnsTask::OnTransactionComplete, base::Unretained(this),
1129 base::TimeTicks::Now()),
1130 net_log_);
1131 }
1132
1133 void OnTransactionComplete(const base::TimeTicks& start_time,
[email protected]1def74c2012-03-22 20:07:001134 DnsTransaction* transaction,
[email protected]b3601bc22012-02-21 21:23:201135 int net_error,
1136 const DnsResponse* response) {
[email protected]add76532012-03-30 14:47:471137 DCHECK(transaction);
[email protected]02cd6982013-01-10 20:12:511138 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]0adcb2b2012-08-15 21:30:461139 if (net_error != OK) {
[email protected]02cd6982013-01-10 20:12:511140 DNS_HISTOGRAM("AsyncDNS.TransactionFailure", duration);
[email protected]0adcb2b2012-08-15 21:30:461141 OnFailure(net_error, DnsResponse::DNS_PARSE_OK);
1142 return;
[email protected]6c411902012-08-14 22:36:361143 }
[email protected]0adcb2b2012-08-15 21:30:461144
[email protected]02cd6982013-01-10 20:12:511145 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess", duration);
1146 switch (transaction->GetType()) {
1147 case dns_protocol::kTypeA:
1148 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess_A", duration);
1149 break;
1150 case dns_protocol::kTypeAAAA:
1151 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess_AAAA", duration);
1152 break;
1153 }
[email protected]daae1322013-09-05 18:26:501154
[email protected]0adcb2b2012-08-15 21:30:461155 AddressList addr_list;
1156 base::TimeDelta ttl;
1157 DnsResponse::Result result = response->ParseToAddressList(&addr_list, &ttl);
1158 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ParseToAddressList",
1159 result,
1160 DnsResponse::DNS_PARSE_RESULT_MAX);
1161 if (result != DnsResponse::DNS_PARSE_OK) {
1162 // Fail even if the other query succeeds.
1163 OnFailure(ERR_DNS_MALFORMED_RESPONSE, result);
1164 return;
1165 }
1166
[email protected]daae1322013-09-05 18:26:501167 ++num_completed_transactions_;
1168 if (num_completed_transactions_ == 1) {
1169 ttl_ = ttl;
[email protected]0adcb2b2012-08-15 21:30:461170 } else {
[email protected]daae1322013-09-05 18:26:501171 ttl_ = std::min(ttl_, ttl);
[email protected]0adcb2b2012-08-15 21:30:461172 }
1173
[email protected]daae1322013-09-05 18:26:501174 if (transaction->GetType() == dns_protocol::kTypeA) {
1175 DCHECK_EQ(transaction_a_.get(), transaction);
1176 // Place IPv4 addresses after IPv6.
1177 addr_list_.insert(addr_list_.end(), addr_list.begin(), addr_list.end());
1178 } else {
1179 DCHECK_EQ(transaction_aaaa_.get(), transaction);
1180 // Place IPv6 addresses before IPv4.
1181 addr_list_.insert(addr_list_.begin(), addr_list.begin(), addr_list.end());
1182 }
1183
1184 if (needs_two_transactions() && num_completed_transactions_ == 1) {
1185 // No need to repeat the suffix search.
1186 key_.hostname = transaction->GetHostname();
1187 delegate_->OnFirstDnsTransactionComplete();
1188 return;
1189 }
1190
1191 if (addr_list_.empty()) {
[email protected]70c04ab2013-08-22 16:05:121192 // TODO(szym): Don't fallback to ProcTask in this case.
1193 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
[email protected]0adcb2b2012-08-15 21:30:461194 return;
1195 }
1196
[email protected]daae1322013-09-05 18:26:501197 // If there are multiple addresses, and at least one is IPv6, need to sort
1198 // them. Note that IPv6 addresses are always put before IPv4 ones, so it's
1199 // sufficient to just check the family of the first address.
1200 if (addr_list_.size() > 1 &&
1201 addr_list_[0].GetFamily() == ADDRESS_FAMILY_IPV6) {
1202 // Sort addresses if needed. Sort could complete synchronously.
[email protected]0adcb2b2012-08-15 21:30:461203 client_->GetAddressSorter()->Sort(
[email protected]daae1322013-09-05 18:26:501204 addr_list_,
[email protected]4589a3a2012-09-20 20:57:071205 base::Bind(&DnsTask::OnSortComplete,
1206 AsWeakPtr(),
[email protected]daae1322013-09-05 18:26:501207 base::TimeTicks::Now()));
[email protected]0adcb2b2012-08-15 21:30:461208 } else {
[email protected]daae1322013-09-05 18:26:501209 OnSuccess(addr_list_);
[email protected]0adcb2b2012-08-15 21:30:461210 }
1211 }
1212
1213 void OnSortComplete(base::TimeTicks start_time,
[email protected]0adcb2b2012-08-15 21:30:461214 bool success,
1215 const AddressList& addr_list) {
1216 if (!success) {
1217 DNS_HISTOGRAM("AsyncDNS.SortFailure",
1218 base::TimeTicks::Now() - start_time);
1219 OnFailure(ERR_DNS_SORT_ERROR, DnsResponse::DNS_PARSE_OK);
1220 return;
1221 }
1222
1223 DNS_HISTOGRAM("AsyncDNS.SortSuccess",
1224 base::TimeTicks::Now() - start_time);
1225
1226 // AddressSorter prunes unusable destinations.
1227 if (addr_list.empty()) {
1228 LOG(WARNING) << "Address list empty after RFC3484 sort";
1229 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
1230 return;
1231 }
1232
[email protected]daae1322013-09-05 18:26:501233 OnSuccess(addr_list);
[email protected]0adcb2b2012-08-15 21:30:461234 }
1235
1236 void OnFailure(int net_error, DnsResponse::Result result) {
1237 DCHECK_NE(OK, net_error);
[email protected]cd565142012-06-12 16:21:451238 net_log_.EndEvent(
mikecirone8b85c432016-09-08 19:11:001239 NetLogEventType::HOST_RESOLVER_IMPL_DNS_TASK,
[email protected]cd565142012-06-12 16:21:451240 base::Bind(&NetLogDnsTaskFailedCallback, net_error, result));
[email protected]daae1322013-09-05 18:26:501241 delegate_->OnDnsTaskComplete(task_start_time_, net_error, AddressList(),
1242 base::TimeDelta());
[email protected]b3601bc22012-02-21 21:23:201243 }
1244
[email protected]daae1322013-09-05 18:26:501245 void OnSuccess(const AddressList& addr_list) {
mikecirone8b85c432016-09-08 19:11:001246 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_DNS_TASK,
[email protected]0adcb2b2012-08-15 21:30:461247 addr_list.CreateNetLogCallback());
[email protected]daae1322013-09-05 18:26:501248 delegate_->OnDnsTaskComplete(task_start_time_, OK, addr_list, ttl_);
[email protected]0adcb2b2012-08-15 21:30:461249 }
1250
1251 DnsClient* client_;
[email protected]daae1322013-09-05 18:26:501252 Key key_;
1253
[email protected]b3601bc22012-02-21 21:23:201254 // The listener to the results of this DnsTask.
[email protected]daae1322013-09-05 18:26:501255 Delegate* delegate_;
tfarina428341112016-09-22 13:38:201256 const NetLogWithSource net_log_;
[email protected]b3601bc22012-02-21 21:23:201257
danakj22f90e72016-04-16 01:55:401258 std::unique_ptr<DnsTransaction> transaction_a_;
1259 std::unique_ptr<DnsTransaction> transaction_aaaa_;
[email protected]0adcb2b2012-08-15 21:30:461260
[email protected]daae1322013-09-05 18:26:501261 unsigned num_completed_transactions_;
1262
1263 // These are updated as each transaction completes.
1264 base::TimeDelta ttl_;
1265 // IPv6 addresses must appear first in the list.
1266 AddressList addr_list_;
1267
1268 base::TimeTicks task_start_time_;
[email protected]0adcb2b2012-08-15 21:30:461269
1270 DISALLOW_COPY_AND_ASSIGN(DnsTask);
[email protected]b3601bc22012-02-21 21:23:201271};
1272
1273//-----------------------------------------------------------------------------
1274
[email protected]0f292de02012-02-01 22:28:201275// Aggregates all Requests for the same Key. Dispatched via PriorityDispatch.
[email protected]daae1322013-09-05 18:26:501276class HostResolverImpl::Job : public PrioritizedDispatcher::Job,
1277 public HostResolverImpl::DnsTask::Delegate {
[email protected]68ad3ee2010-01-30 03:45:391278 public:
[email protected]0f292de02012-02-01 22:28:201279 // Creates new job for |key| where |request_net_log| is bound to the
[email protected]16ee26d2012-03-08 03:34:351280 // request that spawned it.
[email protected]12faa4c2012-11-06 04:44:181281 Job(const base::WeakPtr<HostResolverImpl>& resolver,
[email protected]0f292de02012-02-01 22:28:201282 const Key& key,
[email protected]8c98d002012-07-18 19:02:271283 RequestPriority priority,
mmenke91c17162016-06-02 16:03:231284 scoped_refptr<base::TaskRunner> worker_task_runner,
tfarina428341112016-09-22 13:38:201285 const NetLogWithSource& source_net_log)
[email protected]12faa4c2012-11-06 04:44:181286 : resolver_(resolver),
[email protected]0f292de02012-02-01 22:28:201287 key_(key),
[email protected]8c98d002012-07-18 19:02:271288 priority_tracker_(priority),
mmenke91c17162016-06-02 16:03:231289 worker_task_runner_(std::move(worker_task_runner)),
[email protected]0f292de02012-02-01 22:28:201290 had_non_speculative_request_(false),
[email protected]51b9a6b2012-06-25 21:50:291291 had_dns_config_(false),
[email protected]daae1322013-09-05 18:26:501292 num_occupied_job_slots_(0),
[email protected]1d932852012-06-19 19:40:331293 dns_task_error_(OK),
[email protected]51b9a6b2012-06-25 21:50:291294 creation_time_(base::TimeTicks::Now()),
1295 priority_change_time_(creation_time_),
tfarina428341112016-09-22 13:38:201296 net_log_(
1297 NetLogWithSource::Make(source_net_log.net_log(),
mikecirone8b85c432016-09-08 19:11:001298 NetLogSourceType::HOST_RESOLVER_IMPL_JOB)) {
1299 source_net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_CREATE_JOB);
[email protected]0f292de02012-02-01 22:28:201300
mikecirone8b85c432016-09-08 19:11:001301 net_log_.BeginEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
1302 base::Bind(&NetLogJobCreationCallback,
1303 source_net_log.source(), &key_.hostname));
[email protected]68ad3ee2010-01-30 03:45:391304 }
1305
dchengb03027d2014-10-21 12:00:201306 ~Job() override {
[email protected]b3601bc22012-02-21 21:23:201307 if (is_running()) {
1308 // |resolver_| was destroyed with this Job still in flight.
1309 // Clean-up, record in the log, but don't run any callbacks.
1310 if (is_proc_running()) {
[email protected]0f292de02012-02-01 22:28:201311 proc_task_->Cancel();
wezb9820d42016-06-22 23:41:041312 proc_task_ = nullptr;
[email protected]0f292de02012-02-01 22:28:201313 }
[email protected]16ee26d2012-03-08 03:34:351314 // Clean up now for nice NetLog.
[email protected]daae1322013-09-05 18:26:501315 KillDnsTask();
mikecirone8b85c432016-09-08 19:11:001316 net_log_.EndEventWithNetErrorCode(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
[email protected]b3601bc22012-02-21 21:23:201317 ERR_ABORTED);
1318 } else if (is_queued()) {
[email protected]57a48d32012-03-03 00:04:551319 // |resolver_| was destroyed without running this Job.
[email protected]16ee26d2012-03-08 03:34:351320 // TODO(szym): is there any benefit in having this distinction?
mikecirone8b85c432016-09-08 19:11:001321 net_log_.AddEvent(NetLogEventType::CANCELLED);
1322 net_log_.EndEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB);
[email protected]68ad3ee2010-01-30 03:45:391323 }
[email protected]b3601bc22012-02-21 21:23:201324 // else CompleteRequests logged EndEvent.
maksim.sisov31452af2016-07-27 06:38:101325 if (!requests_.empty()) {
1326 // Log any remaining Requests as cancelled.
1327 for (RequestImpl* req : requests_) {
1328 DCHECK_EQ(this, req->job());
maksim.sisov31452af2016-07-27 06:38:101329 LogCancelRequest(req->source_net_log(), req->info());
maksim.sisov320d5962016-08-15 18:02:511330 req->OnJobCancelled(this);
maksim.sisov31452af2016-07-27 06:38:101331 }
1332 requests_.clear();
[email protected]b3601bc22012-02-21 21:23:201333 }
[email protected]68ad3ee2010-01-30 03:45:391334 }
1335
[email protected]daae1322013-09-05 18:26:501336 // Add this job to the dispatcher. If "at_head" is true, adds at the front
1337 // of the queue.
1338 void Schedule(bool at_head) {
1339 DCHECK(!is_queued());
1340 PrioritizedDispatcher::Handle handle;
1341 if (!at_head) {
[email protected]106ccd2c2014-06-17 09:21:001342 handle = resolver_->dispatcher_->Add(this, priority());
[email protected]daae1322013-09-05 18:26:501343 } else {
[email protected]106ccd2c2014-06-17 09:21:001344 handle = resolver_->dispatcher_->AddAtHead(this, priority());
[email protected]daae1322013-09-05 18:26:501345 }
1346 // The dispatcher could have started |this| in the above call to Add, which
1347 // could have called Schedule again. In that case |handle| will be null,
1348 // but |handle_| may have been set by the other nested call to Schedule.
1349 if (!handle.is_null()) {
1350 DCHECK(handle_.is_null());
1351 handle_ = handle;
1352 }
[email protected]16ee26d2012-03-08 03:34:351353 }
1354
maksim.sisov31452af2016-07-27 06:38:101355 void AddRequest(RequestImpl* request) {
1356 DCHECK_EQ(key_.hostname, request->info().hostname());
[email protected]0f292de02012-02-01 22:28:201357
maksim.sisov31452af2016-07-27 06:38:101358 priority_tracker_.Add(request->priority());
[email protected]0f292de02012-02-01 22:28:201359
maksim.sisov31452af2016-07-27 06:38:101360 request->source_net_log().AddEvent(
mikecirone8b85c432016-09-08 19:11:001361 NetLogEventType::HOST_RESOLVER_IMPL_JOB_ATTACH,
[email protected]cd565142012-06-12 16:21:451362 net_log_.source().ToEventParametersCallback());
[email protected]0f292de02012-02-01 22:28:201363
1364 net_log_.AddEvent(
mikecirone8b85c432016-09-08 19:11:001365 NetLogEventType::HOST_RESOLVER_IMPL_JOB_REQUEST_ATTACH,
maksim.sisov31452af2016-07-27 06:38:101366 base::Bind(&NetLogJobAttachCallback, request->source_net_log().source(),
[email protected]cd565142012-06-12 16:21:451367 priority()));
[email protected]0f292de02012-02-01 22:28:201368
1369 // TODO(szym): Check if this is still needed.
maksim.sisov31452af2016-07-27 06:38:101370 if (!request->info().is_speculative()) {
[email protected]0f292de02012-02-01 22:28:201371 had_non_speculative_request_ = true;
[email protected]90499482013-06-01 00:39:501372 if (proc_task_.get())
[email protected]0f292de02012-02-01 22:28:201373 proc_task_->set_had_non_speculative_request();
[email protected]68ad3ee2010-01-30 03:45:391374 }
[email protected]b3601bc22012-02-21 21:23:201375
maksim.sisov31452af2016-07-27 06:38:101376 requests_.push_back(request);
[email protected]b3601bc22012-02-21 21:23:201377
[email protected]51b9a6b2012-06-25 21:50:291378 UpdatePriority();
[email protected]68ad3ee2010-01-30 03:45:391379 }
1380
maksim.sisov31452af2016-07-27 06:38:101381 void ChangeRequestPriority(RequestImpl* req, RequestPriority priority) {
juliatuttlec53b19a72016-05-05 13:51:311382 DCHECK_EQ(key_.hostname, req->info().hostname());
juliatuttlec53b19a72016-05-05 13:51:311383
1384 priority_tracker_.Remove(req->priority());
1385 req->set_priority(priority);
1386 priority_tracker_.Add(req->priority());
1387 UpdatePriority();
1388 }
1389
maksim.sisov31452af2016-07-27 06:38:101390 // Detach cancelled request. If it was the last active Request, also finishes
1391 // this Job.
1392 void CancelRequest(RequestImpl* request) {
1393 DCHECK_EQ(key_.hostname, request->info().hostname());
1394 DCHECK(!requests_.empty());
[email protected]16ee26d2012-03-08 03:34:351395
maksim.sisov31452af2016-07-27 06:38:101396 LogCancelRequest(request->source_net_log(), request->info());
[email protected]16ee26d2012-03-08 03:34:351397
maksim.sisov31452af2016-07-27 06:38:101398 priority_tracker_.Remove(request->priority());
1399 net_log_.AddEvent(
mikecirone8b85c432016-09-08 19:11:001400 NetLogEventType::HOST_RESOLVER_IMPL_JOB_REQUEST_DETACH,
maksim.sisov31452af2016-07-27 06:38:101401 base::Bind(&NetLogJobAttachCallback, request->source_net_log().source(),
1402 priority()));
[email protected]b3601bc22012-02-21 21:23:201403
[email protected]16ee26d2012-03-08 03:34:351404 if (num_active_requests() > 0) {
[email protected]51b9a6b2012-06-25 21:50:291405 UpdatePriority();
maksim.sisov31452af2016-07-27 06:38:101406 RemoveRequest(request);
[email protected]16ee26d2012-03-08 03:34:351407 } else {
1408 // If we were called from a Request's callback within CompleteRequests,
1409 // that Request could not have been cancelled, so num_active_requests()
1410 // could not be 0. Therefore, we are not in CompleteRequests().
[email protected]1339a2a22012-10-17 08:39:431411 CompleteRequestsWithError(OK /* cancelled */);
[email protected]b3601bc22012-02-21 21:23:201412 }
[email protected]68ad3ee2010-01-30 03:45:391413 }
1414
maksim.sisov31452af2016-07-27 06:38:101415 void RemoveRequest(RequestImpl* request) {
1416 auto it = std::find(requests_.begin(), requests_.end(), request);
1417 DCHECK(it != requests_.end());
1418 requests_.erase(it);
1419 }
1420
[email protected]7af985a2012-12-14 22:40:421421 // Called from AbortAllInProgressJobs. Completes all requests and destroys
1422 // the job. This currently assumes the abort is due to a network change.
olli.raulaa21e9eb72015-12-17 08:18:111423 // TODO This should not delete |this|.
[email protected]0f292de02012-02-01 22:28:201424 void Abort() {
[email protected]0f292de02012-02-01 22:28:201425 DCHECK(is_running());
[email protected]7af985a2012-12-14 22:40:421426 CompleteRequestsWithError(ERR_NETWORK_CHANGED);
[email protected]b3601bc22012-02-21 21:23:201427 }
1428
[email protected]f0f602bd2012-11-15 18:01:021429 // If DnsTask present, abort it and fall back to ProcTask.
1430 void AbortDnsTask() {
1431 if (dns_task_) {
[email protected]daae1322013-09-05 18:26:501432 KillDnsTask();
[email protected]f0f602bd2012-11-15 18:01:021433 dns_task_error_ = OK;
1434 StartProcTask();
1435 }
1436 }
1437
[email protected]16ee26d2012-03-08 03:34:351438 // Called by HostResolverImpl when this job is evicted due to queue overflow.
1439 // Completes all requests and destroys the job.
1440 void OnEvicted() {
1441 DCHECK(!is_running());
1442 DCHECK(is_queued());
1443 handle_.Reset();
1444
mikecirone8b85c432016-09-08 19:11:001445 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB_EVICTED);
[email protected]16ee26d2012-03-08 03:34:351446
1447 // This signals to CompleteRequests that this job never ran.
[email protected]1339a2a22012-10-17 08:39:431448 CompleteRequestsWithError(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
[email protected]16ee26d2012-03-08 03:34:351449 }
1450
[email protected]78eac2a2012-03-14 19:09:271451 // Attempts to serve the job from HOSTS. Returns true if succeeded and
1452 // this Job was destroyed.
1453 bool ServeFromHosts() {
1454 DCHECK_GT(num_active_requests(), 0u);
1455 AddressList addr_list;
1456 if (resolver_->ServeFromHosts(key(),
[email protected]3cb676a12012-06-30 15:46:031457 requests_.front()->info(),
[email protected]78eac2a2012-03-14 19:09:271458 &addr_list)) {
1459 // This will destroy the Job.
[email protected]895123222012-10-25 15:21:171460 CompleteRequests(
1461 HostCache::Entry(OK, MakeAddressListForRequest(addr_list)),
1462 base::TimeDelta());
[email protected]78eac2a2012-03-14 19:09:271463 return true;
1464 }
1465 return false;
1466 }
1467
tanay.c6ddd5f6f2015-08-25 06:34:571468 const Key& key() const { return key_; }
[email protected]b4481b222012-03-16 17:13:111469
1470 bool is_queued() const {
1471 return !handle_.is_null();
1472 }
1473
1474 bool is_running() const {
1475 return is_dns_running() || is_proc_running();
1476 }
1477
[email protected]16ee26d2012-03-08 03:34:351478 private:
[email protected]daae1322013-09-05 18:26:501479 void KillDnsTask() {
1480 if (dns_task_) {
1481 ReduceToOneJobSlot();
1482 dns_task_.reset();
1483 }
1484 }
1485
1486 // Reduce the number of job slots occupied and queued in the dispatcher
1487 // to one. If the second Job slot is queued in the dispatcher, cancels the
1488 // queued job. Otherwise, the second Job has been started by the
1489 // PrioritizedDispatcher, so signals it is complete.
1490 void ReduceToOneJobSlot() {
1491 DCHECK_GE(num_occupied_job_slots_, 1u);
1492 if (is_queued()) {
[email protected]106ccd2c2014-06-17 09:21:001493 resolver_->dispatcher_->Cancel(handle_);
[email protected]daae1322013-09-05 18:26:501494 handle_.Reset();
1495 } else if (num_occupied_job_slots_ > 1) {
[email protected]106ccd2c2014-06-17 09:21:001496 resolver_->dispatcher_->OnJobFinished();
[email protected]daae1322013-09-05 18:26:501497 --num_occupied_job_slots_;
1498 }
1499 DCHECK_EQ(1u, num_occupied_job_slots_);
1500 }
1501
juliatuttlec53b19a72016-05-05 13:51:311502 AddressList MakeAddressListForRequest(const AddressList& list) const {
1503 if (requests_.empty())
1504 return list;
1505 return AddressList::CopyWithPort(list, requests_.front()->info().port());
1506 }
1507
[email protected]51b9a6b2012-06-25 21:50:291508 void UpdatePriority() {
1509 if (is_queued()) {
1510 if (priority() != static_cast<RequestPriority>(handle_.priority()))
1511 priority_change_time_ = base::TimeTicks::Now();
[email protected]106ccd2c2014-06-17 09:21:001512 handle_ = resolver_->dispatcher_->ChangePriority(handle_, priority());
[email protected]51b9a6b2012-06-25 21:50:291513 }
1514 }
1515
[email protected]16ee26d2012-03-08 03:34:351516 // PriorityDispatch::Job:
dchengb03027d2014-10-21 12:00:201517 void Start() override {
[email protected]daae1322013-09-05 18:26:501518 DCHECK_LE(num_occupied_job_slots_, 1u);
1519
[email protected]70c04ab2013-08-22 16:05:121520 handle_.Reset();
[email protected]daae1322013-09-05 18:26:501521 ++num_occupied_job_slots_;
1522
1523 if (num_occupied_job_slots_ == 2) {
1524 StartSecondDnsTransaction();
1525 return;
1526 }
1527
1528 DCHECK(!is_running());
[email protected]0f292de02012-02-01 22:28:201529
mikecirone8b85c432016-09-08 19:11:001530 net_log_.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_JOB_STARTED);
[email protected]0f292de02012-02-01 22:28:201531
[email protected]51b9a6b2012-06-25 21:50:291532 had_dns_config_ = resolver_->HaveDnsConfig();
1533
1534 base::TimeTicks now = base::TimeTicks::Now();
1535 base::TimeDelta queue_time = now - creation_time_;
1536 base::TimeDelta queue_time_after_change = now - priority_change_time_;
1537
1538 if (had_dns_config_) {
1539 DNS_HISTOGRAM_BY_PRIORITY("AsyncDNS.JobQueueTime", priority(),
1540 queue_time);
1541 DNS_HISTOGRAM_BY_PRIORITY("AsyncDNS.JobQueueTimeAfterChange", priority(),
1542 queue_time_after_change);
1543 } else {
1544 DNS_HISTOGRAM_BY_PRIORITY("DNS.JobQueueTime", priority(), queue_time);
1545 DNS_HISTOGRAM_BY_PRIORITY("DNS.JobQueueTimeAfterChange", priority(),
1546 queue_time_after_change);
1547 }
1548
[email protected]443714fad2013-09-19 04:52:011549 bool system_only =
1550 (key_.host_resolver_flags & HOST_RESOLVER_SYSTEM_ONLY) != 0;
1551
[email protected]1d932852012-06-19 19:40:331552 // Caution: Job::Start must not complete synchronously.
[email protected]443714fad2013-09-19 04:52:011553 if (!system_only && had_dns_config_ &&
1554 !ResemblesMulticastDNSName(key_.hostname)) {
[email protected]b3601bc22012-02-21 21:23:201555 StartDnsTask();
1556 } else {
1557 StartProcTask();
1558 }
1559 }
1560
[email protected]b3601bc22012-02-21 21:23:201561 // TODO(szym): Since DnsTransaction does not consume threads, we can increase
1562 // the limits on |dispatcher_|. But in order to keep the number of WorkerPool
1563 // threads low, we will need to use an "inner" PrioritizedDispatcher with
1564 // tighter limits.
1565 void StartProcTask() {
[email protected]16ee26d2012-03-08 03:34:351566 DCHECK(!is_dns_running());
mmenke91c17162016-06-02 16:03:231567 proc_task_ =
1568 new ProcTask(key_, resolver_->proc_params_,
1569 base::Bind(&Job::OnProcTaskComplete,
1570 base::Unretained(this), base::TimeTicks::Now()),
1571 worker_task_runner_, net_log_);
[email protected]0f292de02012-02-01 22:28:201572
1573 if (had_non_speculative_request_)
1574 proc_task_->set_had_non_speculative_request();
1575 // Start() could be called from within Resolve(), hence it must NOT directly
1576 // call OnProcTaskComplete, for example, on synchronous failure.
1577 proc_task_->Start();
[email protected]68ad3ee2010-01-30 03:45:391578 }
1579
[email protected]0f292de02012-02-01 22:28:201580 // Called by ProcTask when it completes.
[email protected]e3bd4822012-10-23 18:01:371581 void OnProcTaskComplete(base::TimeTicks start_time,
1582 int net_error,
1583 const AddressList& addr_list) {
[email protected]b3601bc22012-02-21 21:23:201584 DCHECK(is_proc_running());
[email protected]68ad3ee2010-01-30 03:45:391585
[email protected]62e86ba2013-01-29 18:59:161586 if (!resolver_->resolved_known_ipv6_hostname_ &&
1587 net_error == OK &&
1588 key_.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
1589 if (key_.hostname == "www.google.com") {
1590 resolver_->resolved_known_ipv6_hostname_ = true;
1591 bool got_ipv6_address = false;
1592 for (size_t i = 0; i < addr_list.size(); ++i) {
[email protected]5134c22a2013-08-06 18:09:021593 if (addr_list[i].GetFamily() == ADDRESS_FAMILY_IPV6) {
[email protected]62e86ba2013-01-29 18:59:161594 got_ipv6_address = true;
[email protected]5134c22a2013-08-06 18:09:021595 break;
1596 }
[email protected]62e86ba2013-01-29 18:59:161597 }
1598 UMA_HISTOGRAM_BOOLEAN("Net.UnspecResolvedIPv6", got_ipv6_address);
1599 }
1600 }
1601
[email protected]1d932852012-06-19 19:40:331602 if (dns_task_error_ != OK) {
[email protected]e3bd4822012-10-23 18:01:371603 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]1def74c2012-03-22 20:07:001604 if (net_error == OK) {
[email protected]e3bd4822012-10-23 18:01:371605 DNS_HISTOGRAM("AsyncDNS.FallbackSuccess", duration);
[email protected]1d932852012-06-19 19:40:331606 if ((dns_task_error_ == ERR_NAME_NOT_RESOLVED) &&
1607 ResemblesNetBIOSName(key_.hostname)) {
1608 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_SUSPECT_NETBIOS);
1609 } else {
1610 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_PROC_SUCCESS);
1611 }
davidbenad6fc442015-05-18 20:59:131612 UMA_HISTOGRAM_SPARSE_SLOWLY("AsyncDNS.ResolveError",
1613 std::abs(dns_task_error_));
[email protected]1ffdda82012-12-12 23:04:221614 resolver_->OnDnsTaskResolve(dns_task_error_);
[email protected]1def74c2012-03-22 20:07:001615 } else {
[email protected]e3bd4822012-10-23 18:01:371616 DNS_HISTOGRAM("AsyncDNS.FallbackFail", duration);
[email protected]1def74c2012-03-22 20:07:001617 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
1618 }
1619 }
1620
eroman1efc237c2016-12-14 00:00:451621 if (ContainsIcannNameCollisionIp(addr_list))
1622 net_error = ERR_ICANN_NAME_COLLISION;
1623
[email protected]1339a2a22012-10-17 08:39:431624 base::TimeDelta ttl =
1625 base::TimeDelta::FromSeconds(kNegativeCacheEntryTTLSeconds);
[email protected]b3601bc22012-02-21 21:23:201626 if (net_error == OK)
1627 ttl = base::TimeDelta::FromSeconds(kCacheEntryTTLSeconds);
[email protected]68ad3ee2010-01-30 03:45:391628
[email protected]895123222012-10-25 15:21:171629 // Don't store the |ttl| in cache since it's not obtained from the server.
1630 CompleteRequests(
1631 HostCache::Entry(net_error, MakeAddressListForRequest(addr_list)),
1632 ttl);
[email protected]b3601bc22012-02-21 21:23:201633 }
1634
1635 void StartDnsTask() {
[email protected]78eac2a2012-03-14 19:09:271636 DCHECK(resolver_->HaveDnsConfig());
[email protected]daae1322013-09-05 18:26:501637 dns_task_.reset(new DnsTask(resolver_->dns_client_.get(), key_, this,
1638 net_log_));
[email protected]b3601bc22012-02-21 21:23:201639
[email protected]daae1322013-09-05 18:26:501640 dns_task_->StartFirstTransaction();
1641 // Schedule a second transaction, if needed.
1642 if (dns_task_->needs_two_transactions())
1643 Schedule(true);
1644 }
1645
1646 void StartSecondDnsTransaction() {
1647 DCHECK(dns_task_->needs_two_transactions());
1648 dns_task_->StartSecondTransaction();
[email protected]16c2bd72013-06-28 01:19:221649 }
1650
1651 // Called if DnsTask fails. It is posted from StartDnsTask, so Job may be
1652 // deleted before this callback. In this case dns_task is deleted as well,
1653 // so we use it as indicator whether Job is still valid.
1654 void OnDnsTaskFailure(const base::WeakPtr<DnsTask>& dns_task,
1655 base::TimeDelta duration,
1656 int net_error) {
1657 DNS_HISTOGRAM("AsyncDNS.ResolveFail", duration);
1658
wezb9820d42016-06-22 23:41:041659 if (!dns_task)
[email protected]16c2bd72013-06-28 01:19:221660 return;
1661
1662 dns_task_error_ = net_error;
1663
1664 // TODO(szym): Run ServeFromHosts now if nsswitch.conf says so.
1665 // http://crbug.com/117655
1666
1667 // TODO(szym): Some net errors indicate lack of connectivity. Starting
1668 // ProcTask in that case is a waste of time.
1669 if (resolver_->fallback_to_proctask_) {
[email protected]daae1322013-09-05 18:26:501670 KillDnsTask();
[email protected]16c2bd72013-06-28 01:19:221671 StartProcTask();
1672 } else {
1673 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
1674 CompleteRequestsWithError(net_error);
[email protected]b3601bc22012-02-21 21:23:201675 }
1676 }
1677
[email protected]daae1322013-09-05 18:26:501678
1679 // HostResolverImpl::DnsTask::Delegate implementation:
1680
dchengb03027d2014-10-21 12:00:201681 void OnDnsTaskComplete(base::TimeTicks start_time,
1682 int net_error,
1683 const AddressList& addr_list,
1684 base::TimeDelta ttl) override {
[email protected]b3601bc22012-02-21 21:23:201685 DCHECK(is_dns_running());
[email protected]b3601bc22012-02-21 21:23:201686
[email protected]e3bd4822012-10-23 18:01:371687 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]b3601bc22012-02-21 21:23:201688 if (net_error != OK) {
[email protected]16c2bd72013-06-28 01:19:221689 OnDnsTaskFailure(dns_task_->AsWeakPtr(), duration, net_error);
[email protected]b3601bc22012-02-21 21:23:201690 return;
1691 }
[email protected]e3bd4822012-10-23 18:01:371692 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess", duration);
[email protected]02cd6982013-01-10 20:12:511693 // Log DNS lookups based on |address_family|.
thestiga74ad2b2016-07-11 20:52:361694 switch (key_.address_family) {
[email protected]02cd6982013-01-10 20:12:511695 case ADDRESS_FAMILY_IPV4:
1696 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_IPV4", duration);
1697 break;
1698 case ADDRESS_FAMILY_IPV6:
1699 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_IPV6", duration);
1700 break;
1701 case ADDRESS_FAMILY_UNSPECIFIED:
1702 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_UNSPEC", duration);
1703 break;
1704 }
[email protected]b3601bc22012-02-21 21:23:201705
[email protected]1def74c2012-03-22 20:07:001706 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_DNS_SUCCESS);
[email protected]1339a2a22012-10-17 08:39:431707 RecordTTL(ttl);
[email protected]0adcb2b2012-08-15 21:30:461708
[email protected]1ffdda82012-12-12 23:04:221709 resolver_->OnDnsTaskResolve(OK);
[email protected]f0f602bd2012-11-15 18:01:021710
[email protected]895123222012-10-25 15:21:171711 base::TimeDelta bounded_ttl =
1712 std::max(ttl, base::TimeDelta::FromSeconds(kMinimumTTLSeconds));
1713
eroman1efc237c2016-12-14 00:00:451714 if (ContainsIcannNameCollisionIp(addr_list))
1715 net_error = ERR_ICANN_NAME_COLLISION;
1716
[email protected]895123222012-10-25 15:21:171717 CompleteRequests(
1718 HostCache::Entry(net_error, MakeAddressListForRequest(addr_list), ttl),
1719 bounded_ttl);
[email protected]b3601bc22012-02-21 21:23:201720 }
1721
dchengb03027d2014-10-21 12:00:201722 void OnFirstDnsTransactionComplete() override {
[email protected]daae1322013-09-05 18:26:501723 DCHECK(dns_task_->needs_two_transactions());
1724 DCHECK_EQ(dns_task_->needs_another_transaction(), is_queued());
1725 // No longer need to occupy two dispatcher slots.
1726 ReduceToOneJobSlot();
1727
1728 // We already have a job slot at the dispatcher, so if the second
1729 // transaction hasn't started, reuse it now instead of waiting in the queue
1730 // for the second slot.
1731 if (dns_task_->needs_another_transaction())
1732 dns_task_->StartSecondTransaction();
1733 }
1734
[email protected]16ee26d2012-03-08 03:34:351735 // Performs Job's last rites. Completes all Requests. Deletes this.
[email protected]895123222012-10-25 15:21:171736 void CompleteRequests(const HostCache::Entry& entry,
1737 base::TimeDelta ttl) {
[email protected]11fbca0b2013-06-02 23:37:211738 CHECK(resolver_.get());
[email protected]b3601bc22012-02-21 21:23:201739
[email protected]16ee26d2012-03-08 03:34:351740 // This job must be removed from resolver's |jobs_| now to make room for a
1741 // new job with the same key in case one of the OnComplete callbacks decides
1742 // to spawn one. Consequently, the job deletes itself when CompleteRequests
1743 // is done.
danakj22f90e72016-04-16 01:55:401744 std::unique_ptr<Job> self_deleter(this);
[email protected]16ee26d2012-03-08 03:34:351745
1746 resolver_->RemoveJob(this);
1747
[email protected]16ee26d2012-03-08 03:34:351748 if (is_running()) {
[email protected]16ee26d2012-03-08 03:34:351749 if (is_proc_running()) {
[email protected]daae1322013-09-05 18:26:501750 DCHECK(!is_queued());
[email protected]16ee26d2012-03-08 03:34:351751 proc_task_->Cancel();
wezb9820d42016-06-22 23:41:041752 proc_task_ = nullptr;
[email protected]16ee26d2012-03-08 03:34:351753 }
[email protected]daae1322013-09-05 18:26:501754 KillDnsTask();
[email protected]16ee26d2012-03-08 03:34:351755
1756 // Signal dispatcher that a slot has opened.
[email protected]106ccd2c2014-06-17 09:21:001757 resolver_->dispatcher_->OnJobFinished();
[email protected]16ee26d2012-03-08 03:34:351758 } else if (is_queued()) {
[email protected]106ccd2c2014-06-17 09:21:001759 resolver_->dispatcher_->Cancel(handle_);
[email protected]16ee26d2012-03-08 03:34:351760 handle_.Reset();
1761 }
1762
1763 if (num_active_requests() == 0) {
mikecirone8b85c432016-09-08 19:11:001764 net_log_.AddEvent(NetLogEventType::CANCELLED);
1765 net_log_.EndEventWithNetErrorCode(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
[email protected]16ee26d2012-03-08 03:34:351766 OK);
1767 return;
1768 }
[email protected]b3601bc22012-02-21 21:23:201769
mikecirone8b85c432016-09-08 19:11:001770 net_log_.EndEventWithNetErrorCode(NetLogEventType::HOST_RESOLVER_IMPL_JOB,
juliatuttle317860e2016-05-12 14:47:221771 entry.error());
[email protected]68ad3ee2010-01-30 03:45:391772
juliatuttled7fa5852016-07-29 13:16:571773 resolver_->SchedulePersist();
1774
[email protected]78eac2a2012-03-14 19:09:271775 DCHECK(!requests_.empty());
1776
eroman1efc237c2016-12-14 00:00:451777 if (entry.error() == OK || entry.error() == ERR_ICANN_NAME_COLLISION) {
[email protected]d7b9a2b2012-05-31 22:31:191778 // Record this histogram here, when we know the system has a valid DNS
1779 // configuration.
[email protected]539df6c2012-06-19 21:21:291780 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.HaveDnsConfig",
1781 resolver_->received_dns_config_);
[email protected]d7b9a2b2012-05-31 22:31:191782 }
[email protected]16ee26d2012-03-08 03:34:351783
juliatuttle317860e2016-05-12 14:47:221784 bool did_complete = (entry.error() != ERR_NETWORK_CHANGED) &&
1785 (entry.error() != ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
juliatuttle7e8bf1c2016-08-02 19:09:091786 if (did_complete) {
[email protected]1339a2a22012-10-17 08:39:431787 resolver_->CacheResult(key_, entry, ttl);
juliatuttle7e8bf1c2016-08-02 19:09:091788 // Erase any previous cache hit callbacks, since a new DNS request went
1789 // out since they were set.
1790 resolver_->cache_hit_callbacks_.erase(key_);
1791 }
[email protected]16ee26d2012-03-08 03:34:351792
maksim.sisov31452af2016-07-27 06:38:101793 // Complete all of the requests that were attached to the job and
1794 // detach them.
1795 while (!requests_.empty()) {
1796 RequestImpl* req = requests_.front();
1797 requests_.pop_front();
[email protected]0f292de02012-02-01 22:28:201798 DCHECK_EQ(this, req->job());
1799 // Update the net log and notify registered observers.
juliatuttle317860e2016-05-12 14:47:221800 LogFinishRequest(req->source_net_log(), req->info(), entry.error());
[email protected]51b9a6b2012-06-25 21:50:291801 if (did_complete) {
juliatuttle7e8bf1c2016-08-02 19:09:091802 resolver_->MaybeAddCacheHitCallback(key_, req->info());
[email protected]51b9a6b2012-06-25 21:50:291803 // Record effective total time from creation to completion.
1804 RecordTotalTime(had_dns_config_, req->info().is_speculative(),
1805 base::TimeTicks::Now() - req->request_time());
1806 }
maksim.sisov31452af2016-07-27 06:38:101807 req->OnJobCompleted(this, entry.error(), entry.addresses());
[email protected]0f292de02012-02-01 22:28:201808
1809 // Check if the resolver was destroyed as a result of running the
1810 // callback. If it was, we could continue, but we choose to bail.
[email protected]11fbca0b2013-06-02 23:37:211811 if (!resolver_.get())
[email protected]0f292de02012-02-01 22:28:201812 return;
1813 }
1814 }
1815
[email protected]1339a2a22012-10-17 08:39:431816 // Convenience wrapper for CompleteRequests in case of failure.
1817 void CompleteRequestsWithError(int net_error) {
[email protected]895123222012-10-25 15:21:171818 CompleteRequests(HostCache::Entry(net_error, AddressList()),
1819 base::TimeDelta());
[email protected]1339a2a22012-10-17 08:39:431820 }
1821
[email protected]b4481b222012-03-16 17:13:111822 RequestPriority priority() const {
1823 return priority_tracker_.highest_priority();
1824 }
1825
1826 // Number of non-canceled requests in |requests_|.
1827 size_t num_active_requests() const {
1828 return priority_tracker_.total_count();
1829 }
1830
wezb9820d42016-06-22 23:41:041831 bool is_dns_running() const { return !!dns_task_; }
[email protected]b4481b222012-03-16 17:13:111832
wezb9820d42016-06-22 23:41:041833 bool is_proc_running() const { return !!proc_task_; }
[email protected]b4481b222012-03-16 17:13:111834
[email protected]0f292de02012-02-01 22:28:201835 base::WeakPtr<HostResolverImpl> resolver_;
1836
1837 Key key_;
1838
1839 // Tracks the highest priority across |requests_|.
1840 PriorityTracker priority_tracker_;
1841
mmenke91c17162016-06-02 16:03:231842 // Task runner where the HostResolverProc is invoked.
1843 scoped_refptr<base::TaskRunner> worker_task_runner_;
1844
[email protected]0f292de02012-02-01 22:28:201845 bool had_non_speculative_request_;
1846
[email protected]51b9a6b2012-06-25 21:50:291847 // Distinguishes measurements taken while DnsClient was fully configured.
1848 bool had_dns_config_;
1849
[email protected]daae1322013-09-05 18:26:501850 // Number of slots occupied by this Job in resolver's PrioritizedDispatcher.
1851 unsigned num_occupied_job_slots_;
1852
[email protected]1d932852012-06-19 19:40:331853 // Result of DnsTask.
1854 int dns_task_error_;
[email protected]1def74c2012-03-22 20:07:001855
[email protected]51b9a6b2012-06-25 21:50:291856 const base::TimeTicks creation_time_;
1857 base::TimeTicks priority_change_time_;
1858
tfarina428341112016-09-22 13:38:201859 NetLogWithSource net_log_;
[email protected]0f292de02012-02-01 22:28:201860
[email protected]b3601bc22012-02-21 21:23:201861 // Resolves the host using a HostResolverProc.
[email protected]0f292de02012-02-01 22:28:201862 scoped_refptr<ProcTask> proc_task_;
1863
[email protected]b3601bc22012-02-21 21:23:201864 // Resolves the host using a DnsTransaction.
danakj22f90e72016-04-16 01:55:401865 std::unique_ptr<DnsTask> dns_task_;
[email protected]b3601bc22012-02-21 21:23:201866
[email protected]0f292de02012-02-01 22:28:201867 // All Requests waiting for the result of this Job. Some can be canceled.
maksim.sisov31452af2016-07-27 06:38:101868 std::deque<RequestImpl*> requests_;
[email protected]0f292de02012-02-01 22:28:201869
[email protected]16ee26d2012-03-08 03:34:351870 // A handle used in |HostResolverImpl::dispatcher_|.
[email protected]0f292de02012-02-01 22:28:201871 PrioritizedDispatcher::Handle handle_;
[email protected]68ad3ee2010-01-30 03:45:391872};
1873
1874//-----------------------------------------------------------------------------
1875
[email protected]0f292de02012-02-01 22:28:201876HostResolverImpl::ProcTaskParams::ProcTaskParams(
[email protected]e95d3aca2010-01-11 22:47:431877 HostResolverProc* resolver_proc,
[email protected]0f292de02012-02-01 22:28:201878 size_t max_retry_attempts)
1879 : resolver_proc(resolver_proc),
1880 max_retry_attempts(max_retry_attempts),
ttuttlecf1158bf2016-03-18 16:37:441881 unresponsive_delay(
1882 base::TimeDelta::FromMilliseconds(kDnsDefaultUnresponsiveDelayMs)),
[email protected]0f292de02012-02-01 22:28:201883 retry_factor(2) {
[email protected]106ccd2c2014-06-17 09:21:001884 // Maximum of 4 retry attempts for host resolution.
1885 static const size_t kDefaultMaxRetryAttempts = 4u;
1886 if (max_retry_attempts == HostResolver::kDefaultRetryAttempts)
1887 max_retry_attempts = kDefaultMaxRetryAttempts;
[email protected]0f292de02012-02-01 22:28:201888}
1889
vmpstracd23b72016-02-26 21:08:551890HostResolverImpl::ProcTaskParams::ProcTaskParams(const ProcTaskParams& other) =
1891 default;
1892
[email protected]0f292de02012-02-01 22:28:201893HostResolverImpl::ProcTaskParams::~ProcTaskParams() {}
1894
[email protected]106ccd2c2014-06-17 09:21:001895HostResolverImpl::HostResolverImpl(const Options& options, NetLog* net_log)
mmenke91c17162016-06-02 16:03:231896 : HostResolverImpl(
1897 options,
1898 net_log,
1899 base::WorkerPool::GetTaskRunner(true /* task_is_slow */)) {}
[email protected]b59ff372009-07-15 22:04:321900
1901HostResolverImpl::~HostResolverImpl() {
[email protected]daae1322013-09-05 18:26:501902 // Prevent the dispatcher from starting new jobs.
[email protected]106ccd2c2014-06-17 09:21:001903 dispatcher_->SetLimitsToZero();
avi9e72eb482016-12-09 21:10:541904 // It's now safe for Jobs to call KillDnsTask on destruction, because
[email protected]daae1322013-09-05 18:26:501905 // OnJobComplete will not start any new jobs.
avi9e72eb482016-12-09 21:10:541906 jobs_.clear();
[email protected]e95d3aca2010-01-11 22:47:431907
[email protected]232a5812011-03-04 22:42:081908 NetworkChangeNotifier::RemoveIPAddressObserver(this);
ttuttlecf1158bf2016-03-18 16:37:441909 NetworkChangeNotifier::RemoveConnectionTypeObserver(this);
[email protected]bb0e34542012-08-31 19:52:401910 NetworkChangeNotifier::RemoveDNSObserver(this);
[email protected]b59ff372009-07-15 22:04:321911}
1912
[email protected]0f292de02012-02-01 22:28:201913void HostResolverImpl::SetMaxQueuedJobs(size_t value) {
[email protected]106ccd2c2014-06-17 09:21:001914 DCHECK_EQ(0u, dispatcher_->num_queued_jobs());
[email protected]0f292de02012-02-01 22:28:201915 DCHECK_GT(value, 0u);
1916 max_queued_jobs_ = value;
[email protected]be1a48b2011-01-20 00:12:131917}
1918
[email protected]684970b2009-08-14 04:54:461919int HostResolverImpl::Resolve(const RequestInfo& info,
[email protected]5109c1952013-08-20 18:44:101920 RequestPriority priority,
[email protected]b59ff372009-07-15 22:04:321921 AddressList* addresses,
[email protected]aa22b242011-11-16 18:58:291922 const CompletionCallback& callback,
maksim.sisov31452af2016-07-27 06:38:101923 std::unique_ptr<Request>* out_req,
tfarina428341112016-09-22 13:38:201924 const NetLogWithSource& source_net_log) {
[email protected]95a214c2011-08-04 21:50:401925 DCHECK(addresses);
[email protected]1ac6af92010-06-03 21:00:141926 DCHECK(CalledOnValidThread());
[email protected]aa22b242011-11-16 18:58:291927 DCHECK_EQ(false, callback.is_null());
maksim.sisov31452af2016-07-27 06:38:101928 DCHECK(out_req);
[email protected]1ac6af92010-06-03 21:00:141929
[email protected]e806cd72013-05-17 02:08:431930 // Check that the caller supplied a valid hostname to resolve.
mmenked6e9161aff2016-09-09 21:55:441931 if (!IsValidDNSDomain(info.hostname()))
[email protected]e806cd72013-05-17 02:08:431932 return ERR_NAME_NOT_RESOLVED;
1933
xunjieli26f90452014-11-10 16:23:021934 LogStartRequest(source_net_log, info);
[email protected]b59ff372009-07-15 22:04:321935
martijna23c8962016-03-04 18:18:511936 IPAddress ip_address;
1937 IPAddress* ip_address_ptr = nullptr;
1938 if (ip_address.AssignFromIPLiteral(info.hostname()))
1939 ip_address_ptr = &ip_address;
pauljensen19eb73422015-04-15 23:20:061940
[email protected]123ab1e32009-10-21 19:12:571941 // Build a key that identifies the request in the cache and in the
1942 // outstanding jobs map.
martijna23c8962016-03-04 18:18:511943 Key key = GetEffectiveKeyForRequest(info, ip_address_ptr, source_net_log);
[email protected]123ab1e32009-10-21 19:12:571944
juliatuttle9fb7aeb2016-06-06 20:16:331945 int rv = ResolveHelper(key, info, ip_address_ptr, addresses, false, nullptr,
1946 source_net_log);
[email protected]95a214c2011-08-04 21:50:401947 if (rv != ERR_DNS_CACHE_MISS) {
juliatuttle7e8bf1c2016-08-02 19:09:091948 MaybeAddCacheHitCallback(key, info);
xunjieli26f90452014-11-10 16:23:021949 LogFinishRequest(source_net_log, info, rv);
[email protected]51b9a6b2012-06-25 21:50:291950 RecordTotalTime(HaveDnsConfig(), info.is_speculative(), base::TimeDelta());
[email protected]95a214c2011-08-04 21:50:401951 return rv;
[email protected]38368712011-03-02 08:09:401952 }
1953
[email protected]0f292de02012-02-01 22:28:201954 // Next we need to attach our request to a "job". This job is responsible for
1955 // calling "getaddrinfo(hostname)" on a worker thread.
1956
avi9e72eb482016-12-09 21:10:541957 auto jobit = jobs_.find(key);
[email protected]0f292de02012-02-01 22:28:201958 Job* job;
1959 if (jobit == jobs_.end()) {
mmenke91c17162016-06-02 16:03:231960 job = new Job(weak_ptr_factory_.GetWeakPtr(), key, priority,
1961 worker_task_runner_, source_net_log);
[email protected]daae1322013-09-05 18:26:501962 job->Schedule(false);
[email protected]0f292de02012-02-01 22:28:201963
1964 // Check for queue overflow.
[email protected]106ccd2c2014-06-17 09:21:001965 if (dispatcher_->num_queued_jobs() > max_queued_jobs_) {
1966 Job* evicted = static_cast<Job*>(dispatcher_->EvictOldestLowest());
[email protected]0f292de02012-02-01 22:28:201967 DCHECK(evicted);
[email protected]16ee26d2012-03-08 03:34:351968 evicted->OnEvicted(); // Deletes |evicted|.
[email protected]0f292de02012-02-01 22:28:201969 if (evicted == job) {
[email protected]0f292de02012-02-01 22:28:201970 rv = ERR_HOST_RESOLVER_QUEUE_TOO_LARGE;
xunjieli26f90452014-11-10 16:23:021971 LogFinishRequest(source_net_log, info, rv);
[email protected]0f292de02012-02-01 22:28:201972 return rv;
1973 }
[email protected]0f292de02012-02-01 22:28:201974 }
avi9e72eb482016-12-09 21:10:541975 jobs_[key] = base::WrapUnique(job);
[email protected]0f292de02012-02-01 22:28:201976 } else {
avi9e72eb482016-12-09 21:10:541977 job = jobit->second.get();
[email protected]0f292de02012-02-01 22:28:201978 }
1979
1980 // Can't complete synchronously. Create and attach request.
avi9e72eb482016-12-09 21:10:541981 auto req = base::MakeUnique<RequestImpl>(source_net_log, info, priority,
1982 callback, addresses, job);
maksim.sisov31452af2016-07-27 06:38:101983 job->AddRequest(req.get());
1984 *out_req = std::move(req);
[email protected]b59ff372009-07-15 22:04:321985
[email protected]0f292de02012-02-01 22:28:201986 // Completion happens during Job::CompleteRequests().
[email protected]b59ff372009-07-15 22:04:321987 return ERR_IO_PENDING;
1988}
1989
mmenke91c17162016-06-02 16:03:231990HostResolverImpl::HostResolverImpl(
1991 const Options& options,
1992 NetLog* net_log,
1993 scoped_refptr<base::TaskRunner> worker_task_runner)
1994 : max_queued_jobs_(0),
1995 proc_params_(NULL, options.max_retry_attempts),
1996 net_log_(net_log),
1997 received_dns_config_(false),
1998 num_dns_failures_(0),
1999 use_local_ipv6_(false),
2000 last_ipv6_probe_result_(true),
2001 resolved_known_ipv6_hostname_(false),
2002 additional_resolver_flags_(0),
2003 fallback_to_proctask_(true),
2004 worker_task_runner_(std::move(worker_task_runner)),
juliatuttled7fa5852016-07-29 13:16:572005 persist_initialized_(false),
mmenke91c17162016-06-02 16:03:232006 weak_ptr_factory_(this),
2007 probe_weak_ptr_factory_(this) {
2008 if (options.enable_caching)
2009 cache_ = HostCache::CreateDefaultCache();
2010
2011 PrioritizedDispatcher::Limits job_limits = options.GetDispatcherLimits();
2012 dispatcher_.reset(new PrioritizedDispatcher(job_limits));
2013 max_queued_jobs_ = job_limits.total_jobs * 100u;
2014
2015 DCHECK_GE(dispatcher_->num_priorities(), static_cast<size_t>(NUM_PRIORITIES));
2016
2017#if defined(OS_WIN)
2018 EnsureWinsockInit();
2019#endif
2020#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
2021 RunLoopbackProbeJob();
2022#endif
2023 NetworkChangeNotifier::AddIPAddressObserver(this);
2024 NetworkChangeNotifier::AddConnectionTypeObserver(this);
2025 NetworkChangeNotifier::AddDNSObserver(this);
2026#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD) && \
2027 !defined(OS_ANDROID)
2028 EnsureDnsReloaderInit();
2029#endif
2030
2031 OnConnectionTypeChanged(NetworkChangeNotifier::GetConnectionType());
2032
2033 {
2034 DnsConfig dns_config;
2035 NetworkChangeNotifier::GetDnsConfig(&dns_config);
2036 received_dns_config_ = dns_config.IsValid();
2037 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
2038 use_local_ipv6_ = !dns_config.IsValid() || dns_config.use_local_ipv6;
2039 }
2040
2041 fallback_to_proctask_ = !ConfigureAsyncDnsNoFallbackFieldTrial();
2042}
2043
2044void HostResolverImpl::SetHaveOnlyLoopbackAddresses(bool result) {
2045 if (result) {
2046 additional_resolver_flags_ |= HOST_RESOLVER_LOOPBACK_ONLY;
2047 } else {
2048 additional_resolver_flags_ &= ~HOST_RESOLVER_LOOPBACK_ONLY;
2049 }
2050}
2051
[email protected]287d7c22011-11-15 17:34:252052int HostResolverImpl::ResolveHelper(const Key& key,
[email protected]95a214c2011-08-04 21:50:402053 const RequestInfo& info,
martijna23c8962016-03-04 18:18:512054 const IPAddress* ip_address,
[email protected]95a214c2011-08-04 21:50:402055 AddressList* addresses,
juliatuttle9fb7aeb2016-06-06 20:16:332056 bool allow_stale,
2057 HostCache::EntryStaleness* stale_info,
tfarina428341112016-09-22 13:38:202058 const NetLogWithSource& source_net_log) {
juliatuttle9fb7aeb2016-06-06 20:16:332059 DCHECK(allow_stale == !!stale_info);
[email protected]95a214c2011-08-04 21:50:402060 // The result of |getaddrinfo| for empty hosts is inconsistent across systems.
2061 // On Windows it gives the default interface's address, whereas on Linux it
2062 // gives an error. We will make it fail on all platforms for consistency.
juliatuttle9fb7aeb2016-06-06 20:16:332063 if (info.hostname().empty() || info.hostname().size() > kMaxHostLength) {
2064 MakeNotStale(stale_info);
[email protected]95a214c2011-08-04 21:50:402065 return ERR_NAME_NOT_RESOLVED;
juliatuttle9fb7aeb2016-06-06 20:16:332066 }
[email protected]95a214c2011-08-04 21:50:402067
2068 int net_error = ERR_UNEXPECTED;
juliatuttle9fb7aeb2016-06-06 20:16:332069 if (ResolveAsIP(key, info, ip_address, &net_error, addresses)) {
2070 MakeNotStale(stale_info);
[email protected]95a214c2011-08-04 21:50:402071 return net_error;
juliatuttle9fb7aeb2016-06-06 20:16:332072 }
2073 if (ServeFromCache(key, info, &net_error, addresses, allow_stale,
2074 stale_info)) {
mikecirone8b85c432016-09-08 19:11:002075 source_net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_CACHE_HIT);
juliatuttle9fb7aeb2016-06-06 20:16:332076 // |ServeFromCache()| will set |*stale_info| as needed.
juliatuttle7e8bf1c2016-08-02 19:09:092077 RunCacheHitCallbacks(key, info);
[email protected]78eac2a2012-03-14 19:09:272078 return net_error;
2079 }
2080 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2081 // http://crbug.com/117655
2082 if (ServeFromHosts(key, info, addresses)) {
mikecirone8b85c432016-09-08 19:11:002083 source_net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_HOSTS_HIT);
juliatuttle9fb7aeb2016-06-06 20:16:332084 MakeNotStale(stale_info);
[email protected]78eac2a2012-03-14 19:09:272085 return OK;
2086 }
estarkd1bc206e2015-06-20 00:44:392087
juliatuttle9fb7aeb2016-06-06 20:16:332088 if (ServeLocalhost(key, info, addresses)) {
2089 MakeNotStale(stale_info);
estarkd1bc206e2015-06-20 00:44:392090 return OK;
juliatuttle9fb7aeb2016-06-06 20:16:332091 }
estarkd1bc206e2015-06-20 00:44:392092
[email protected]78eac2a2012-03-14 19:09:272093 return ERR_DNS_CACHE_MISS;
[email protected]95a214c2011-08-04 21:50:402094}
2095
2096int HostResolverImpl::ResolveFromCache(const RequestInfo& info,
2097 AddressList* addresses,
tfarina428341112016-09-22 13:38:202098 const NetLogWithSource& source_net_log) {
[email protected]95a214c2011-08-04 21:50:402099 DCHECK(CalledOnValidThread());
2100 DCHECK(addresses);
2101
[email protected]95a214c2011-08-04 21:50:402102 // Update the net log and notify registered observers.
xunjieli26f90452014-11-10 16:23:022103 LogStartRequest(source_net_log, info);
[email protected]95a214c2011-08-04 21:50:402104
martijna23c8962016-03-04 18:18:512105 IPAddress ip_address;
2106 IPAddress* ip_address_ptr = nullptr;
2107 if (ip_address.AssignFromIPLiteral(info.hostname()))
2108 ip_address_ptr = &ip_address;
[email protected]95a214c2011-08-04 21:50:402109
martijna23c8962016-03-04 18:18:512110 Key key = GetEffectiveKeyForRequest(info, ip_address_ptr, source_net_log);
pauljensen19eb73422015-04-15 23:20:062111
juliatuttle9fb7aeb2016-06-06 20:16:332112 int rv = ResolveHelper(key, info, ip_address_ptr, addresses, false, nullptr,
2113 source_net_log);
xunjieli26f90452014-11-10 16:23:022114 LogFinishRequest(source_net_log, info, rv);
[email protected]95a214c2011-08-04 21:50:402115 return rv;
2116}
2117
[email protected]a8883e452012-11-17 05:58:062118void HostResolverImpl::SetDnsClientEnabled(bool enabled) {
2119 DCHECK(CalledOnValidThread());
2120#if defined(ENABLE_BUILT_IN_DNS)
2121 if (enabled && !dns_client_) {
2122 SetDnsClient(DnsClient::CreateClient(net_log_));
2123 } else if (!enabled && dns_client_) {
danakj22f90e72016-04-16 01:55:402124 SetDnsClient(std::unique_ptr<DnsClient>());
[email protected]a8883e452012-11-17 05:58:062125 }
2126#endif
2127}
2128
[email protected]489d1a82011-10-12 03:09:112129HostCache* HostResolverImpl::GetHostCache() {
2130 return cache_.get();
2131}
[email protected]95a214c2011-08-04 21:50:402132
danakj22f90e72016-04-16 01:55:402133std::unique_ptr<base::Value> HostResolverImpl::GetDnsConfigAsValue() const {
[email protected]17e92032012-03-29 00:56:242134 // Check if async DNS is disabled.
2135 if (!dns_client_.get())
tfhef3618f2016-01-11 23:07:082136 return nullptr;
[email protected]17e92032012-03-29 00:56:242137
2138 // Check if async DNS is enabled, but we currently have no configuration
2139 // for it.
2140 const DnsConfig* dns_config = dns_client_->GetConfig();
wezb9820d42016-06-22 23:41:042141 if (!dns_config)
ricea2deef682016-09-09 08:04:072142 return base::MakeUnique<base::DictionaryValue>();
[email protected]17e92032012-03-29 00:56:242143
2144 return dns_config->ToValue();
2145}
2146
juliatuttle9fb7aeb2016-06-06 20:16:332147int HostResolverImpl::ResolveStaleFromCache(
2148 const RequestInfo& info,
2149 AddressList* addresses,
2150 HostCache::EntryStaleness* stale_info,
tfarina428341112016-09-22 13:38:202151 const NetLogWithSource& source_net_log) {
juliatuttle9fb7aeb2016-06-06 20:16:332152 DCHECK(CalledOnValidThread());
2153 DCHECK(addresses);
2154 DCHECK(stale_info);
2155
2156 // Update the net log and notify registered observers.
2157 LogStartRequest(source_net_log, info);
2158
2159 IPAddress ip_address;
2160 IPAddress* ip_address_ptr = nullptr;
2161 if (ip_address.AssignFromIPLiteral(info.hostname()))
2162 ip_address_ptr = &ip_address;
2163
2164 Key key = GetEffectiveKeyForRequest(info, ip_address_ptr, source_net_log);
2165
2166 int rv = ResolveHelper(key, info, ip_address_ptr, addresses, true, stale_info,
2167 source_net_log);
2168 LogFinishRequest(source_net_log, info, rv);
2169 return rv;
2170}
2171
[email protected]95a214c2011-08-04 21:50:402172bool HostResolverImpl::ResolveAsIP(const Key& key,
2173 const RequestInfo& info,
martijna23c8962016-03-04 18:18:512174 const IPAddress* ip_address,
[email protected]95a214c2011-08-04 21:50:402175 int* net_error,
2176 AddressList* addresses) {
2177 DCHECK(addresses);
2178 DCHECK(net_error);
martijna23c8962016-03-04 18:18:512179 if (ip_address == nullptr)
[email protected]95a214c2011-08-04 21:50:402180 return false;
2181
[email protected]95a214c2011-08-04 21:50:402182 *net_error = OK;
martijna23c8962016-03-04 18:18:512183 AddressFamily family = GetAddressFamily(*ip_address);
cbentzel1906f872015-06-05 16:25:252184 if (key.address_family != ADDRESS_FAMILY_UNSPECIFIED &&
2185 key.address_family != family) {
[email protected]1c7cf3f82014-08-07 21:33:482186 // Don't return IPv6 addresses for IPv4 queries, and vice versa.
[email protected]95a214c2011-08-04 21:50:402187 *net_error = ERR_NAME_NOT_RESOLVED;
2188 } else {
martijna23c8962016-03-04 18:18:512189 *addresses = AddressList::CreateFromIPAddress(*ip_address, info.port());
[email protected]7054e78f2012-05-07 21:44:562190 if (key.host_resolver_flags & HOST_RESOLVER_CANONNAME)
2191 addresses->SetDefaultCanonicalName();
[email protected]95a214c2011-08-04 21:50:402192 }
2193 return true;
2194}
2195
2196bool HostResolverImpl::ServeFromCache(const Key& key,
2197 const RequestInfo& info,
[email protected]95a214c2011-08-04 21:50:402198 int* net_error,
juliatuttle9fb7aeb2016-06-06 20:16:332199 AddressList* addresses,
2200 bool allow_stale,
2201 HostCache::EntryStaleness* stale_info) {
[email protected]95a214c2011-08-04 21:50:402202 DCHECK(addresses);
2203 DCHECK(net_error);
juliatuttle9fb7aeb2016-06-06 20:16:332204 DCHECK(allow_stale == !!stale_info);
[email protected]95a214c2011-08-04 21:50:402205 if (!info.allow_cached_response() || !cache_.get())
2206 return false;
2207
juliatuttle9fb7aeb2016-06-06 20:16:332208 const HostCache::Entry* cache_entry;
2209 if (allow_stale)
2210 cache_entry = cache_->LookupStale(key, base::TimeTicks::Now(), stale_info);
2211 else
2212 cache_entry = cache_->Lookup(key, base::TimeTicks::Now());
[email protected]95a214c2011-08-04 21:50:402213 if (!cache_entry)
2214 return false;
2215
juliatuttle317860e2016-05-12 14:47:222216 *net_error = cache_entry->error();
[email protected]7054e78f2012-05-07 21:44:562217 if (*net_error == OK) {
[email protected]1339a2a22012-10-17 08:39:432218 if (cache_entry->has_ttl())
juliatuttle317860e2016-05-12 14:47:222219 RecordTTL(cache_entry->ttl());
2220 *addresses = EnsurePortOnAddressList(cache_entry->addresses(), info.port());
[email protected]7054e78f2012-05-07 21:44:562221 }
[email protected]95a214c2011-08-04 21:50:402222 return true;
2223}
2224
[email protected]78eac2a2012-03-14 19:09:272225bool HostResolverImpl::ServeFromHosts(const Key& key,
2226 const RequestInfo& info,
2227 AddressList* addresses) {
2228 DCHECK(addresses);
2229 if (!HaveDnsConfig())
2230 return false;
[email protected]05a79d42013-03-28 07:30:092231 addresses->clear();
2232
[email protected]cb507622012-03-23 16:17:062233 // HOSTS lookups are case-insensitive.
brettw8e2106d2015-08-11 19:30:222234 std::string hostname = base::ToLowerASCII(key.hostname);
[email protected]cb507622012-03-23 16:17:062235
[email protected]05a79d42013-03-28 07:30:092236 const DnsHosts& hosts = dns_client_->GetConfig()->hosts;
2237
[email protected]78eac2a2012-03-14 19:09:272238 // If |address_family| is ADDRESS_FAMILY_UNSPECIFIED other implementations
2239 // (glibc and c-ares) return the first matching line. We have more
2240 // flexibility, but lose implicit ordering.
[email protected]05a79d42013-03-28 07:30:092241 // We prefer IPv6 because "happy eyeballs" will fall back to IPv4 if
2242 // necessary.
2243 if (key.address_family == ADDRESS_FAMILY_IPV6 ||
2244 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
2245 DnsHosts::const_iterator it = hosts.find(
2246 DnsHostsKey(hostname, ADDRESS_FAMILY_IPV6));
2247 if (it != hosts.end())
2248 addresses->push_back(IPEndPoint(it->second, info.port()));
[email protected]78eac2a2012-03-14 19:09:272249 }
2250
[email protected]05a79d42013-03-28 07:30:092251 if (key.address_family == ADDRESS_FAMILY_IPV4 ||
2252 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
2253 DnsHosts::const_iterator it = hosts.find(
2254 DnsHostsKey(hostname, ADDRESS_FAMILY_IPV4));
2255 if (it != hosts.end())
2256 addresses->push_back(IPEndPoint(it->second, info.port()));
2257 }
2258
[email protected]ec666ab22013-04-17 20:05:592259 // If got only loopback addresses and the family was restricted, resolve
2260 // again, without restrictions. See SystemHostResolverCall for rationale.
2261 if ((key.host_resolver_flags &
2262 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6) &&
2263 IsAllIPv4Loopback(*addresses)) {
2264 Key new_key(key);
2265 new_key.address_family = ADDRESS_FAMILY_UNSPECIFIED;
2266 new_key.host_resolver_flags &=
2267 ~HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
2268 return ServeFromHosts(new_key, info, addresses);
2269 }
[email protected]05a79d42013-03-28 07:30:092270 return !addresses->empty();
[email protected]78eac2a2012-03-14 19:09:272271}
2272
estarkd1bc206e2015-06-20 00:44:392273bool HostResolverImpl::ServeLocalhost(const Key& key,
2274 const RequestInfo& info,
2275 AddressList* addresses) {
2276 AddressList resolved_addresses;
2277 if (!ResolveLocalHostname(key.hostname, info.port(), &resolved_addresses))
2278 return false;
2279
2280 addresses->clear();
2281
2282 for (const auto& address : resolved_addresses) {
2283 // Include the address if:
2284 // - caller didn't specify an address family, or
2285 // - caller specifically asked for the address family of this address, or
2286 // - this is an IPv6 address and caller specifically asked for IPv4 due
2287 // to lack of detected IPv6 support. (See SystemHostResolverCall for
2288 // rationale).
2289 if (key.address_family == ADDRESS_FAMILY_UNSPECIFIED ||
2290 key.address_family == address.GetFamily() ||
2291 (address.GetFamily() == ADDRESS_FAMILY_IPV6 &&
2292 key.address_family == ADDRESS_FAMILY_IPV4 &&
2293 (key.host_resolver_flags &
2294 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6))) {
2295 addresses->push_back(address);
2296 }
2297 }
2298
2299 return true;
2300}
2301
[email protected]16ee26d2012-03-08 03:34:352302void HostResolverImpl::CacheResult(const Key& key,
[email protected]1339a2a22012-10-17 08:39:432303 const HostCache::Entry& entry,
[email protected]16ee26d2012-03-08 03:34:352304 base::TimeDelta ttl) {
2305 if (cache_.get())
[email protected]1339a2a22012-10-17 08:39:432306 cache_->Set(key, entry, base::TimeTicks::Now(), ttl);
[email protected]ef4c40c2010-09-01 14:42:032307}
2308
[email protected]0f292de02012-02-01 22:28:202309void HostResolverImpl::RemoveJob(Job* job) {
2310 DCHECK(job);
avi9e72eb482016-12-09 21:10:542311 auto it = jobs_.find(job->key());
2312 if (it != jobs_.end() && it->second.get() == job) {
2313 it->second.release();
[email protected]16ee26d2012-03-08 03:34:352314 jobs_.erase(it);
avi9e72eb482016-12-09 21:10:542315 }
[email protected]b59ff372009-07-15 22:04:322316}
2317
[email protected]137af622010-02-05 02:14:352318HostResolverImpl::Key HostResolverImpl::GetEffectiveKeyForRequest(
pauljensen19eb73422015-04-15 23:20:062319 const RequestInfo& info,
martijna23c8962016-03-04 18:18:512320 const IPAddress* ip_address,
tfarina428341112016-09-22 13:38:202321 const NetLogWithSource& net_log) {
[email protected]eaf3a3b2010-09-03 20:34:272322 HostResolverFlags effective_flags =
2323 info.host_resolver_flags() | additional_resolver_flags_;
[email protected]137af622010-02-05 02:14:352324 AddressFamily effective_address_family = info.address_family();
[email protected]9db6f702013-04-10 18:10:512325
2326 if (info.address_family() == ADDRESS_FAMILY_UNSPECIFIED) {
cbentzel1906f872015-06-05 16:25:252327 if (!use_local_ipv6_ &&
pauljensen19eb73422015-04-15 23:20:062328 // When resolving IPv4 literals, there's no need to probe for IPv6.
2329 // When resolving IPv6 literals, there's no benefit to artificially
2330 // limiting our resolution based on a probe. Prior logic ensures
2331 // that this query is UNSPECIFIED (see info.address_family()
cbentzel1906f872015-06-05 16:25:252332 // check above) so the code requesting the resolution should be amenable
2333 // to receiving a IPv6 resolution.
martijna23c8962016-03-04 18:18:512334 ip_address == nullptr) {
sergeyub8cdc212015-05-14 18:50:372335 if (!IsIPv6Reachable(net_log)) {
[email protected]ac0b52e2013-04-21 01:26:162336 effective_address_family = ADDRESS_FAMILY_IPV4;
2337 effective_flags |= HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
2338 }
[email protected]9db6f702013-04-10 18:10:512339 }
2340 }
2341
estarkd1bc206e2015-06-20 00:44:392342 return Key(info.hostname(), effective_address_family, effective_flags);
[email protected]137af622010-02-05 02:14:352343}
2344
tfarina428341112016-09-22 13:38:202345bool HostResolverImpl::IsIPv6Reachable(const NetLogWithSource& net_log) {
eroman1a17ef32016-12-14 01:06:092346 // Cache the result for kIPv6ProbePeriodMs (measured from after
2347 // IsGloballyReachable() completes).
sergeyub8cdc212015-05-14 18:50:372348 bool cached = true;
eroman1a17ef32016-12-14 01:06:092349 if ((base::TimeTicks::Now() - last_ipv6_probe_time_).InMilliseconds() >
2350 kIPv6ProbePeriodMs) {
martijna23c8962016-03-04 18:18:512351 last_ipv6_probe_result_ =
2352 IsGloballyReachable(IPAddress(kIPv6ProbeAddress), net_log);
eroman1a17ef32016-12-14 01:06:092353 last_ipv6_probe_time_ = base::TimeTicks::Now();
sergeyub8cdc212015-05-14 18:50:372354 cached = false;
2355 }
mikecirone8b85c432016-09-08 19:11:002356 net_log.AddEvent(NetLogEventType::HOST_RESOLVER_IMPL_IPV6_REACHABILITY_CHECK,
sergeyub8cdc212015-05-14 18:50:372357 base::Bind(&NetLogIPv6AvailableCallback,
2358 last_ipv6_probe_result_, cached));
2359 return last_ipv6_probe_result_;
2360}
2361
mmenke91c17162016-06-02 16:03:232362void HostResolverImpl::RunLoopbackProbeJob() {
2363 new LoopbackProbeJob(weak_ptr_factory_.GetWeakPtr(),
2364 worker_task_runner_.get());
2365}
2366
[email protected]35ddc282010-09-21 23:42:062367void HostResolverImpl::AbortAllInProgressJobs() {
[email protected]b3601bc22012-02-21 21:23:202368 // In Abort, a Request callback could spawn new Jobs with matching keys, so
2369 // first collect and remove all running jobs from |jobs_|.
danakj22f90e72016-04-16 01:55:402370 std::vector<std::unique_ptr<Job>> jobs_to_abort;
avi9e72eb482016-12-09 21:10:542371 for (auto it = jobs_.begin(); it != jobs_.end();) {
2372 Job* job = it->second.get();
[email protected]0f292de02012-02-01 22:28:202373 if (job->is_running()) {
avi9e72eb482016-12-09 21:10:542374 jobs_to_abort.push_back(std::move(it->second));
[email protected]b3601bc22012-02-21 21:23:202375 jobs_.erase(it++);
[email protected]0f292de02012-02-01 22:28:202376 } else {
[email protected]b3601bc22012-02-21 21:23:202377 DCHECK(job->is_queued());
2378 ++it;
[email protected]0f292de02012-02-01 22:28:202379 }
[email protected]ef4c40c2010-09-01 14:42:032380 }
[email protected]b3601bc22012-02-21 21:23:202381
[email protected]daae1322013-09-05 18:26:502382 // Pause the dispatcher so it won't start any new dispatcher jobs while
2383 // aborting the old ones. This is needed so that it won't start the second
2384 // DnsTransaction for a job in |jobs_to_abort| if the DnsConfig just became
2385 // invalid.
[email protected]106ccd2c2014-06-17 09:21:002386 PrioritizedDispatcher::Limits limits = dispatcher_->GetLimits();
2387 dispatcher_->SetLimits(
[email protected]daae1322013-09-05 18:26:502388 PrioritizedDispatcher::Limits(limits.reserved_slots.size(), 0));
[email protected]70c04ab2013-08-22 16:05:122389
[email protected]57a48d32012-03-03 00:04:552390 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072391 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]57a48d32012-03-03 00:04:552392
[email protected]16ee26d2012-03-08 03:34:352393 // Then Abort them.
[email protected]11fbca0b2013-06-02 23:37:212394 for (size_t i = 0; self.get() && i < jobs_to_abort.size(); ++i) {
[email protected]57a48d32012-03-03 00:04:552395 jobs_to_abort[i]->Abort();
olli.raulaa21e9eb72015-12-17 08:18:112396 ignore_result(jobs_to_abort[i].release());
[email protected]b3601bc22012-02-21 21:23:202397 }
[email protected]daae1322013-09-05 18:26:502398
2399 if (self)
[email protected]106ccd2c2014-06-17 09:21:002400 dispatcher_->SetLimits(limits);
[email protected]daae1322013-09-05 18:26:502401}
2402
2403void HostResolverImpl::AbortDnsTasks() {
2404 // Pause the dispatcher so it won't start any new dispatcher jobs while
2405 // aborting the old ones. This is needed so that it won't start the second
2406 // DnsTransaction for a job if the DnsConfig just changed.
[email protected]106ccd2c2014-06-17 09:21:002407 PrioritizedDispatcher::Limits limits = dispatcher_->GetLimits();
2408 dispatcher_->SetLimits(
[email protected]daae1322013-09-05 18:26:502409 PrioritizedDispatcher::Limits(limits.reserved_slots.size(), 0));
2410
avi9e72eb482016-12-09 21:10:542411 for (auto it = jobs_.begin(); it != jobs_.end(); ++it)
[email protected]daae1322013-09-05 18:26:502412 it->second->AbortDnsTask();
[email protected]106ccd2c2014-06-17 09:21:002413 dispatcher_->SetLimits(limits);
[email protected]ef4c40c2010-09-01 14:42:032414}
2415
[email protected]78eac2a2012-03-14 19:09:272416void HostResolverImpl::TryServingAllJobsFromHosts() {
2417 if (!HaveDnsConfig())
2418 return;
2419
2420 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2421 // http://crbug.com/117655
2422
2423 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072424 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]78eac2a2012-03-14 19:09:272425
avi9e72eb482016-12-09 21:10:542426 for (auto it = jobs_.begin(); self.get() && it != jobs_.end();) {
2427 Job* job = it->second.get();
[email protected]78eac2a2012-03-14 19:09:272428 ++it;
2429 // This could remove |job| from |jobs_|, but iterator will remain valid.
2430 job->ServeFromHosts();
2431 }
2432}
2433
[email protected]be1a48b2011-01-20 00:12:132434void HostResolverImpl::OnIPAddressChanged() {
[email protected]62e86ba2013-01-29 18:59:162435 resolved_known_ipv6_hostname_ = false;
sergeyub8cdc212015-05-14 18:50:372436 last_ipv6_probe_time_ = base::TimeTicks();
[email protected]12faa4c2012-11-06 04:44:182437 // Abandon all ProbeJobs.
2438 probe_weak_ptr_factory_.InvalidateWeakPtrs();
juliatuttle7e8bf1c2016-08-02 19:09:092439 if (cache_.get()) {
[email protected]be1a48b2011-01-20 00:12:132440 cache_->clear();
juliatuttle7e8bf1c2016-08-02 19:09:092441 cache_hit_callbacks_.clear();
2442 }
[email protected]7c466e92013-07-20 01:44:482443#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
mmenke91c17162016-06-02 16:03:232444 RunLoopbackProbeJob();
[email protected]be1a48b2011-01-20 00:12:132445#endif
2446 AbortAllInProgressJobs();
2447 // |this| may be deleted inside AbortAllInProgressJobs().
2448}
2449
ttuttlecf1158bf2016-03-18 16:37:442450void HostResolverImpl::OnConnectionTypeChanged(
2451 NetworkChangeNotifier::ConnectionType type) {
2452 proc_params_.unresponsive_delay =
2453 GetTimeDeltaForConnectionTypeFromFieldTrialOrDefault(
2454 "DnsUnresponsiveDelayMsByConnectionType",
2455 base::TimeDelta::FromMilliseconds(kDnsDefaultUnresponsiveDelayMs),
2456 type);
2457}
2458
pauljensen101ed372015-04-17 00:11:422459void HostResolverImpl::OnInitialDNSConfigRead() {
2460 UpdateDNSConfig(false);
2461}
2462
[email protected]bb0e34542012-08-31 19:52:402463void HostResolverImpl::OnDNSChanged() {
pauljensen101ed372015-04-17 00:11:422464 UpdateDNSConfig(true);
2465}
2466
2467void HostResolverImpl::UpdateDNSConfig(bool config_changed) {
[email protected]bb0e34542012-08-31 19:52:402468 DnsConfig dns_config;
2469 NetworkChangeNotifier::GetDnsConfig(&dns_config);
[email protected]ec666ab22013-04-17 20:05:592470
[email protected]b4481b222012-03-16 17:13:112471 if (net_log_) {
mikecirone8b85c432016-09-08 19:11:002472 net_log_->AddGlobalEntry(NetLogEventType::DNS_CONFIG_CHANGED,
2473 base::Bind(&NetLogDnsConfigCallback, &dns_config));
[email protected]b4481b222012-03-16 17:13:112474 }
2475
[email protected]01b3b9d2012-08-13 16:18:142476 // TODO(szym): Remove once http://crbug.com/137914 is resolved.
[email protected]d7b9a2b2012-05-31 22:31:192477 received_dns_config_ = dns_config.IsValid();
[email protected]c9fa8f312013-09-17 12:24:522478 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
2479 use_local_ipv6_ = !dns_config.IsValid() || dns_config.use_local_ipv6;
[email protected]78eac2a2012-03-14 19:09:272480
[email protected]a8883e452012-11-17 05:58:062481 num_dns_failures_ = 0;
2482
[email protected]01b3b9d2012-08-13 16:18:142483 // We want a new DnsSession in place, before we Abort running Jobs, so that
2484 // the newly started jobs use the new config.
[email protected]f0f602bd2012-11-15 18:01:022485 if (dns_client_.get()) {
[email protected]d7b9a2b2012-05-31 22:31:192486 dns_client_->SetConfig(dns_config);
pauljensen101ed372015-04-17 00:11:422487 if (dns_client_->GetConfig()) {
[email protected]f0f602bd2012-11-15 18:01:022488 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
pauljensen101ed372015-04-17 00:11:422489 // If we just switched DnsClients, restart jobs using new resolver.
2490 // TODO(pauljensen): Is this necessary?
2491 config_changed = true;
2492 }
[email protected]f0f602bd2012-11-15 18:01:022493 }
[email protected]01b3b9d2012-08-13 16:18:142494
pauljensen101ed372015-04-17 00:11:422495 if (config_changed) {
2496 // If the DNS server has changed, existing cached info could be wrong so we
2497 // have to drop our internal cache :( Note that OS level DNS caches, such
2498 // as NSCD's cache should be dropped automatically by the OS when
2499 // resolv.conf changes so we don't need to do anything to clear that cache.
juliatuttle7e8bf1c2016-08-02 19:09:092500 if (cache_.get()) {
pauljensen101ed372015-04-17 00:11:422501 cache_->clear();
juliatuttle7e8bf1c2016-08-02 19:09:092502 cache_hit_callbacks_.clear();
2503 }
[email protected]01b3b9d2012-08-13 16:18:142504
pauljensen101ed372015-04-17 00:11:422505 // Life check to bail once |this| is deleted.
2506 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]f0f602bd2012-11-15 18:01:022507
pauljensen101ed372015-04-17 00:11:422508 // Existing jobs will have been sent to the original server so they need to
2509 // be aborted.
2510 AbortAllInProgressJobs();
[email protected]01b3b9d2012-08-13 16:18:142511
pauljensen101ed372015-04-17 00:11:422512 // |this| may be deleted inside AbortAllInProgressJobs().
2513 if (self.get())
2514 TryServingAllJobsFromHosts();
2515 }
[email protected]78eac2a2012-03-14 19:09:272516}
2517
2518bool HostResolverImpl::HaveDnsConfig() const {
[email protected]32b1dbcf2013-01-26 03:48:252519 // Use DnsClient only if it's fully configured and there is no override by
2520 // ScopedDefaultHostResolverProc.
2521 // The alternative is to use NetworkChangeNotifier to override DnsConfig,
2522 // but that would introduce construction order requirements for NCN and SDHRP.
wezb9820d42016-06-22 23:41:042523 return dns_client_ && dns_client_->GetConfig() &&
2524 (proc_params_.resolver_proc || !HostResolverProc::GetDefault());
[email protected]b3601bc22012-02-21 21:23:202525}
2526
[email protected]1ffdda82012-12-12 23:04:222527void HostResolverImpl::OnDnsTaskResolve(int net_error) {
[email protected]f0f602bd2012-11-15 18:01:022528 DCHECK(dns_client_);
[email protected]1ffdda82012-12-12 23:04:222529 if (net_error == OK) {
[email protected]f0f602bd2012-11-15 18:01:022530 num_dns_failures_ = 0;
2531 return;
2532 }
2533 ++num_dns_failures_;
2534 if (num_dns_failures_ < kMaximumDnsFailures)
2535 return;
[email protected]daae1322013-09-05 18:26:502536
2537 // Disable DnsClient until the next DNS change. Must be done before aborting
2538 // DnsTasks, since doing so may start new jobs.
[email protected]f0f602bd2012-11-15 18:01:022539 dns_client_->SetConfig(DnsConfig());
[email protected]daae1322013-09-05 18:26:502540
2541 // Switch jobs with active DnsTasks over to using ProcTasks.
2542 AbortDnsTasks();
2543
[email protected]f0f602bd2012-11-15 18:01:022544 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", false);
davidbenad6fc442015-05-18 20:59:132545 UMA_HISTOGRAM_SPARSE_SLOWLY("AsyncDNS.DnsClientDisabledReason",
2546 std::abs(net_error));
[email protected]f0f602bd2012-11-15 18:01:022547}
2548
juliatuttle7e8bf1c2016-08-02 19:09:092549void HostResolverImpl::OnCacheEntryEvicted(const HostCache::Key& key,
2550 const HostCache::Entry& entry) {
2551 cache_hit_callbacks_.erase(key);
2552}
2553
2554void HostResolverImpl::MaybeAddCacheHitCallback(const HostCache::Key& key,
2555 const RequestInfo& info) {
2556 const RequestInfo::CacheHitCallback& callback = info.cache_hit_callback();
2557 if (callback.is_null())
2558 return;
2559 cache_hit_callbacks_[key].push_back(callback);
2560}
2561
2562void HostResolverImpl::RunCacheHitCallbacks(const HostCache::Key& key,
2563 const RequestInfo& info) {
2564 auto it = cache_hit_callbacks_.find(key);
2565 if (it == cache_hit_callbacks_.end())
2566 return;
2567 for (auto& callback : it->second)
2568 callback.Run(info);
2569}
2570
danakj22f90e72016-04-16 01:55:402571void HostResolverImpl::SetDnsClient(std::unique_ptr<DnsClient> dns_client) {
[email protected]daae1322013-09-05 18:26:502572 // DnsClient and config must be updated before aborting DnsTasks, since doing
2573 // so may start new jobs.
dchengc7eeda422015-12-26 03:56:482574 dns_client_ = std::move(dns_client);
[email protected]daae1322013-09-05 18:26:502575 if (dns_client_ && !dns_client_->GetConfig() &&
2576 num_dns_failures_ < kMaximumDnsFailures) {
2577 DnsConfig dns_config;
2578 NetworkChangeNotifier::GetDnsConfig(&dns_config);
2579 dns_client_->SetConfig(dns_config);
2580 num_dns_failures_ = 0;
2581 if (dns_client_->GetConfig())
2582 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
[email protected]a8883e452012-11-17 05:58:062583 }
[email protected]daae1322013-09-05 18:26:502584
2585 AbortDnsTasks();
[email protected]a8883e452012-11-17 05:58:062586}
2587
juliatuttled7fa5852016-07-29 13:16:572588void HostResolverImpl::InitializePersistence(
2589 const PersistCallback& persist_callback,
2590 std::unique_ptr<const base::Value> old_data) {
2591 DCHECK(!persist_initialized_);
2592 persist_callback_ = persist_callback;
2593 persist_initialized_ = true;
2594 if (old_data)
2595 ApplyPersistentData(std::move(old_data));
2596}
2597
juliatuttle7e8bf1c2016-08-02 19:09:092598void HostResolverImpl::ApplyPersistentData(
2599 std::unique_ptr<const base::Value> data) {}
2600
2601std::unique_ptr<const base::Value> HostResolverImpl::GetPersistentData() {
2602 return std::unique_ptr<const base::Value>();
2603}
2604
juliatuttled7fa5852016-07-29 13:16:572605void HostResolverImpl::SchedulePersist() {
2606 if (!persist_initialized_ || persist_timer_.IsRunning())
2607 return;
2608 persist_timer_.Start(
2609 FROM_HERE, base::TimeDelta::FromSeconds(kPersistDelaySec),
2610 base::Bind(&HostResolverImpl::DoPersist, weak_ptr_factory_.GetWeakPtr()));
2611}
2612
2613void HostResolverImpl::DoPersist() {
2614 DCHECK(persist_initialized_);
2615 persist_callback_.Run(GetPersistentData());
2616}
2617
maksim.sisov31452af2016-07-27 06:38:102618HostResolverImpl::RequestImpl::~RequestImpl() {
2619 if (job_)
2620 job_->CancelRequest(this);
2621}
2622
2623void HostResolverImpl::RequestImpl::ChangeRequestPriority(
2624 RequestPriority priority) {
2625 job_->ChangeRequestPriority(this, priority);
2626}
2627
[email protected]b59ff372009-07-15 22:04:322628} // namespace net