blob: fcb0b6ee42b5479bdc5a479f4c61da98f9c42e1b [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
danakj22f90e72016-04-16 01:55:407#include <memory>
dchengc7eeda422015-12-26 03:56:488#include <utility>
9
danakj22f90e72016-04-16 01:55:4010#include "base/memory/ptr_util.h"
11
[email protected]21526002010-05-16 19:42:4612#if defined(OS_WIN)
13#include <Winsock2.h>
14#elif defined(OS_POSIX)
15#include <netdb.h>
16#endif
17
[email protected]68ad3ee2010-01-30 03:45:3918#include <cmath>
[email protected]0f292de02012-02-01 22:28:2019#include <utility>
[email protected]21526002010-05-16 19:42:4620#include <vector>
[email protected]68ad3ee2010-01-30 03:45:3921
[email protected]33152acc2011-10-20 23:37:1222#include "base/bind.h"
[email protected]aa22b242011-11-16 18:58:2923#include "base/bind_helpers.h"
[email protected]0f292de02012-02-01 22:28:2024#include "base/callback.h"
[email protected]b59ff372009-07-15 22:04:3225#include "base/compiler_specific.h"
[email protected]58580352010-10-26 04:07:5026#include "base/debug/debugger.h"
mmenke91c17162016-06-02 16:03:2327#include "base/debug/leak_annotations.h"
[email protected]58580352010-10-26 04:07:5028#include "base/debug/stack_trace.h"
Avi Drissman13fc8932015-12-20 04:40:4629#include "base/macros.h"
mmenke91c17162016-06-02 16:03:2330#include "base/memory/ptr_util.h"
[email protected]1e9bbd22010-10-15 16:42:4531#include "base/metrics/field_trial.h"
davidbenad6fc442015-05-18 20:59:1332#include "base/metrics/histogram_macros.h"
33#include "base/metrics/sparse_histogram.h"
eromane1867242015-04-23 23:07:4434#include "base/profiler/scoped_tracker.h"
anujk.sharma7c907f02015-05-29 02:55:4435#include "base/single_thread_task_runner.h"
[email protected]7286e3fc2011-07-19 22:13:2436#include "base/stl_util.h"
[email protected]be528af2013-06-11 07:39:4837#include "base/strings/string_util.h"
[email protected]750b2f3c2013-06-07 18:41:0538#include "base/strings/utf_string_conversions.h"
gabf767595f2016-05-11 18:50:3539#include "base/threading/thread_task_runner_handle.h"
[email protected]ac9ba8fe2010-12-30 18:08:3640#include "base/threading/worker_pool.h"
[email protected]66e96c42013-06-28 15:20:3141#include "base/time/time.h"
ssid6d6b40102016-04-05 18:59:5642#include "base/trace_event/trace_event.h"
[email protected]21526002010-05-16 19:42:4643#include "base/values.h"
[email protected]b3601bc22012-02-21 21:23:2044#include "net/base/address_family.h"
[email protected]b59ff372009-07-15 22:04:3245#include "net/base/address_list.h"
[email protected]ee094b82010-08-24 15:55:5146#include "net/base/host_port_pair.h"
martijna23c8962016-03-04 18:18:5147#include "net/base/ip_address.h"
[email protected]1c7cf3f82014-08-07 21:33:4848#include "net/base/ip_endpoint.h"
[email protected]2bb04442010-08-18 18:01:1549#include "net/base/net_errors.h"
tfarina9ed7f8c52016-02-19 17:50:1850#include "net/base/url_util.h"
[email protected]0adcb2b2012-08-15 21:30:4651#include "net/dns/address_sorter.h"
[email protected]78eac2a2012-03-14 19:09:2752#include "net/dns/dns_client.h"
[email protected]b3601bc22012-02-21 21:23:2053#include "net/dns/dns_config_service.h"
54#include "net/dns/dns_protocol.h"
tfarina47598f042015-10-07 23:08:3555#include "net/dns/dns_reloader.h"
[email protected]b3601bc22012-02-21 21:23:2056#include "net/dns/dns_response.h"
[email protected]b3601bc22012-02-21 21:23:2057#include "net/dns/dns_transaction.h"
tfarina77021d62015-10-11 20:19:0358#include "net/dns/dns_util.h"
[email protected]f2cb3cf2013-03-21 01:40:5359#include "net/dns/host_resolver_proc.h"
eroman87c53d62015-04-02 06:51:0760#include "net/log/net_log.h"
[email protected]9db6f702013-04-10 18:10:5161#include "net/socket/client_socket_factory.h"
62#include "net/udp/datagram_client_socket.h"
pauljensen370f1c72015-02-17 16:59:1463#include "url/url_canon_ip.h"
[email protected]b59ff372009-07-15 22:04:3264
65#if defined(OS_WIN)
66#include "net/base/winsock_init.h"
67#endif
68
69namespace net {
70
[email protected]e95d3aca2010-01-11 22:47:4371namespace {
72
ttuttlecf1158bf2016-03-18 16:37:4473// Default delay between calls to the system resolver for the same hostname.
74// (Can be overridden by field trial.)
75const int64_t kDnsDefaultUnresponsiveDelayMs = 6000;
76
[email protected]6e78dfb2011-07-28 21:34:4777// Limit the size of hostnames that will be resolved to combat issues in
78// some platform's resolvers.
79const size_t kMaxHostLength = 4096;
80
[email protected]a2730882012-01-21 00:56:2781// Default TTL for successful resolutions with ProcTask.
82const unsigned kCacheEntryTTLSeconds = 60;
83
[email protected]b3601bc22012-02-21 21:23:2084// Default TTL for unsuccessful resolutions with ProcTask.
85const unsigned kNegativeCacheEntryTTLSeconds = 0;
86
[email protected]895123222012-10-25 15:21:1787// Minimum TTL for successful resolutions with DnsTask.
88const unsigned kMinimumTTLSeconds = kCacheEntryTTLSeconds;
89
sergeyub8cdc212015-05-14 18:50:3790// Time between IPv6 probes, i.e. for how long results of each IPv6 probe are
91// cached.
92const int kIPv6ProbePeriodMs = 1000;
93
94// Google DNS address used for IPv6 probes.
95const uint8_t kIPv6ProbeAddress[] =
96 { 0x20, 0x01, 0x48, 0x60, 0x48, 0x60, 0x00, 0x00,
97 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x88 };
98
[email protected]24f4bab2010-10-15 01:27:1199// We use a separate histogram name for each platform to facilitate the
100// display of error codes by their symbolic name (since each platform has
101// different mappings).
102const char kOSErrorsForGetAddrinfoHistogramName[] =
103#if defined(OS_WIN)
104 "Net.OSErrorsForGetAddrinfo_Win";
105#elif defined(OS_MACOSX)
106 "Net.OSErrorsForGetAddrinfo_Mac";
107#elif defined(OS_LINUX)
108 "Net.OSErrorsForGetAddrinfo_Linux";
109#else
110 "Net.OSErrorsForGetAddrinfo";
111#endif
112
[email protected]c89b2442011-05-26 14:28:27113// Gets a list of the likely error codes that getaddrinfo() can return
114// (non-exhaustive). These are the error codes that we will track via
115// a histogram.
116std::vector<int> GetAllGetAddrinfoOSErrors() {
117 int os_errors[] = {
118#if defined(OS_POSIX)
[email protected]23f771162011-06-02 18:37:51119#if !defined(OS_FREEBSD)
[email protected]39588992011-07-11 19:54:37120#if !defined(OS_ANDROID)
[email protected]c48aef92011-11-22 23:41:45121 // EAI_ADDRFAMILY has been declared obsolete in Android's and
122 // FreeBSD's netdb.h.
[email protected]c89b2442011-05-26 14:28:27123 EAI_ADDRFAMILY,
[email protected]39588992011-07-11 19:54:37124#endif
[email protected]c48aef92011-11-22 23:41:45125 // EAI_NODATA has been declared obsolete in FreeBSD's netdb.h.
[email protected]23f771162011-06-02 18:37:51126 EAI_NODATA,
127#endif
[email protected]c89b2442011-05-26 14:28:27128 EAI_AGAIN,
129 EAI_BADFLAGS,
130 EAI_FAIL,
131 EAI_FAMILY,
132 EAI_MEMORY,
[email protected]c89b2442011-05-26 14:28:27133 EAI_NONAME,
134 EAI_SERVICE,
135 EAI_SOCKTYPE,
136 EAI_SYSTEM,
137#elif defined(OS_WIN)
138 // See: http://msdn.microsoft.com/en-us/library/ms738520(VS.85).aspx
139 WSA_NOT_ENOUGH_MEMORY,
140 WSAEAFNOSUPPORT,
141 WSAEINVAL,
142 WSAESOCKTNOSUPPORT,
143 WSAHOST_NOT_FOUND,
144 WSANO_DATA,
145 WSANO_RECOVERY,
146 WSANOTINITIALISED,
147 WSATRY_AGAIN,
148 WSATYPE_NOT_FOUND,
149 // The following are not in doc, but might be to appearing in results :-(.
150 WSA_INVALID_HANDLE,
151#endif
152 };
153
154 // Ensure all errors are positive, as histogram only tracks positive values.
155 for (size_t i = 0; i < arraysize(os_errors); ++i) {
156 os_errors[i] = std::abs(os_errors[i]);
157 }
158
159 return base::CustomHistogram::ArrayToCustomRanges(os_errors,
160 arraysize(os_errors));
161}
162
[email protected]1def74c2012-03-22 20:07:00163enum DnsResolveStatus {
164 RESOLVE_STATUS_DNS_SUCCESS = 0,
165 RESOLVE_STATUS_PROC_SUCCESS,
166 RESOLVE_STATUS_FAIL,
[email protected]1d932852012-06-19 19:40:33167 RESOLVE_STATUS_SUSPECT_NETBIOS,
[email protected]1def74c2012-03-22 20:07:00168 RESOLVE_STATUS_MAX
169};
170
eroman91dd3602015-03-26 03:46:33171// ICANN uses this localhost address to indicate a name collision.
172//
173// The policy in Chromium is to fail host resolving if it resolves to
174// this special address.
175//
176// Not however that IP literals are exempt from this policy, so it is still
177// possible to navigate to http://127.0.53.53/ directly.
178//
179// For more details: https://www.icann.org/news/announcement-2-2014-08-01-en
martijna23c8962016-03-04 18:18:51180const uint8_t kIcanNameCollisionIp[] = {127, 0, 53, 53};
eroman91dd3602015-03-26 03:46:33181
[email protected]1def74c2012-03-22 20:07:00182void UmaAsyncDnsResolveStatus(DnsResolveStatus result) {
183 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ResolveStatus",
184 result,
185 RESOLVE_STATUS_MAX);
186}
187
[email protected]1d932852012-06-19 19:40:33188bool ResemblesNetBIOSName(const std::string& hostname) {
189 return (hostname.size() < 16) && (hostname.find('.') == std::string::npos);
190}
191
192// True if |hostname| ends with either ".local" or ".local.".
193bool ResemblesMulticastDNSName(const std::string& hostname) {
194 DCHECK(!hostname.empty());
195 const char kSuffix[] = ".local.";
196 const size_t kSuffixLen = sizeof(kSuffix) - 1;
197 const size_t kSuffixLenTrimmed = kSuffixLen - 1;
198 if (hostname[hostname.size() - 1] == '.') {
199 return hostname.size() > kSuffixLen &&
200 !hostname.compare(hostname.size() - kSuffixLen, kSuffixLen, kSuffix);
201 }
202 return hostname.size() > kSuffixLenTrimmed &&
203 !hostname.compare(hostname.size() - kSuffixLenTrimmed, kSuffixLenTrimmed,
204 kSuffix, kSuffixLenTrimmed);
205}
206
[email protected]34e61362013-07-24 20:41:56207// Attempts to connect a UDP socket to |dest|:53.
martijna23c8962016-03-04 18:18:51208bool IsGloballyReachable(const IPAddress& dest, const BoundNetLog& net_log) {
eroman0eb394e2015-04-30 23:25:46209 // TODO(eroman): Remove ScopedTracker below once crbug.com/455942 is fixed.
210 tracked_objects::ScopedTracker tracking_profile_1(
eroman2734a9d2015-05-05 19:24:38211 FROM_HERE_WITH_EXPLICIT_FUNCTION("455942 IsGloballyReachable"));
eroman0eb394e2015-04-30 23:25:46212
danakj22f90e72016-04-16 01:55:40213 std::unique_ptr<DatagramClientSocket> socket(
[email protected]9db6f702013-04-10 18:10:51214 ClientSocketFactory::GetDefaultFactory()->CreateDatagramClientSocket(
danakj22f90e72016-04-16 01:55:40215 DatagramSocket::DEFAULT_BIND, RandIntCallback(), net_log.net_log(),
[email protected]2b74a2f2013-07-23 19:37:38216 net_log.source()));
[email protected]34e61362013-07-24 20:41:56217 int rv = socket->Connect(IPEndPoint(dest, 53));
[email protected]e9051722013-04-12 21:58:18218 if (rv != OK)
219 return false;
220 IPEndPoint endpoint;
221 rv = socket->GetLocalAddress(&endpoint);
222 if (rv != OK)
223 return false;
[email protected]1c7cf3f82014-08-07 21:33:48224 DCHECK_EQ(ADDRESS_FAMILY_IPV6, endpoint.GetFamily());
martijna23c8962016-03-04 18:18:51225 const IPAddress& address = endpoint.address();
226
227 bool is_link_local =
228 (address.bytes()[0] == 0xFE) && ((address.bytes()[1] & 0xC0) == 0x80);
[email protected]e9051722013-04-12 21:58:18229 if (is_link_local)
230 return false;
martijna23c8962016-03-04 18:18:51231
Avi Drissman13fc8932015-12-20 04:40:46232 const uint8_t kTeredoPrefix[] = {0x20, 0x01, 0, 0};
martijna23c8962016-03-04 18:18:51233 if (IPAddressStartsWith(address, kTeredoPrefix))
[email protected]e9051722013-04-12 21:58:18234 return false;
martijna23c8962016-03-04 18:18:51235
[email protected]e9051722013-04-12 21:58:18236 return true;
[email protected]9db6f702013-04-10 18:10:51237}
238
[email protected]51b9a6b2012-06-25 21:50:29239// Provide a common macro to simplify code and readability. We must use a
240// macro as the underlying HISTOGRAM macro creates static variables.
241#define DNS_HISTOGRAM(name, time) UMA_HISTOGRAM_CUSTOM_TIMES(name, time, \
242 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromHours(1), 100)
243
244// A macro to simplify code and readability.
245#define DNS_HISTOGRAM_BY_PRIORITY(basename, priority, time) \
246 do { \
247 switch (priority) { \
248 case HIGHEST: DNS_HISTOGRAM(basename "_HIGHEST", time); break; \
249 case MEDIUM: DNS_HISTOGRAM(basename "_MEDIUM", time); break; \
250 case LOW: DNS_HISTOGRAM(basename "_LOW", time); break; \
251 case LOWEST: DNS_HISTOGRAM(basename "_LOWEST", time); break; \
252 case IDLE: DNS_HISTOGRAM(basename "_IDLE", time); break; \
253 default: NOTREACHED(); break; \
254 } \
255 DNS_HISTOGRAM(basename, time); \
256 } while (0)
257
258// Record time from Request creation until a valid DNS response.
259void RecordTotalTime(bool had_dns_config,
260 bool speculative,
261 base::TimeDelta duration) {
262 if (had_dns_config) {
263 if (speculative) {
264 DNS_HISTOGRAM("AsyncDNS.TotalTime_speculative", duration);
265 } else {
266 DNS_HISTOGRAM("AsyncDNS.TotalTime", duration);
267 }
268 } else {
269 if (speculative) {
270 DNS_HISTOGRAM("DNS.TotalTime_speculative", duration);
271 } else {
272 DNS_HISTOGRAM("DNS.TotalTime", duration);
273 }
274 }
275}
276
[email protected]1339a2a22012-10-17 08:39:43277void RecordTTL(base::TimeDelta ttl) {
278 UMA_HISTOGRAM_CUSTOM_TIMES("AsyncDNS.TTL", ttl,
279 base::TimeDelta::FromSeconds(1),
280 base::TimeDelta::FromDays(1), 100);
281}
282
[email protected]16c2bd72013-06-28 01:19:22283bool ConfigureAsyncDnsNoFallbackFieldTrial() {
284 const bool kDefault = false;
285
286 // Configure the AsyncDns field trial as follows:
287 // groups AsyncDnsNoFallbackA and AsyncDnsNoFallbackB: return true,
288 // groups AsyncDnsA and AsyncDnsB: return false,
289 // groups SystemDnsA and SystemDnsB: return false,
290 // otherwise (trial absent): return default.
291 std::string group_name = base::FieldTrialList::FindFullName("AsyncDns");
brettw3a2c6902015-07-06 19:43:29292 if (!group_name.empty()) {
293 return base::StartsWith(group_name, "AsyncDnsNoFallback",
294 base::CompareCase::INSENSITIVE_ASCII);
295 }
[email protected]16c2bd72013-06-28 01:19:22296 return kDefault;
297}
298
[email protected]d7b9a2b2012-05-31 22:31:19299//-----------------------------------------------------------------------------
300
Avi Drissman13fc8932015-12-20 04:40:46301AddressList EnsurePortOnAddressList(const AddressList& list, uint16_t port) {
[email protected]895123222012-10-25 15:21:17302 if (list.empty() || list.front().port() == port)
303 return list;
304 return AddressList::CopyWithPort(list, port);
[email protected]7054e78f2012-05-07 21:44:56305}
306
[email protected]ec666ab22013-04-17 20:05:59307// Returns true if |addresses| contains only IPv4 loopback addresses.
308bool IsAllIPv4Loopback(const AddressList& addresses) {
309 for (unsigned i = 0; i < addresses.size(); ++i) {
martijna23c8962016-03-04 18:18:51310 const IPAddress& address = addresses[i].address();
[email protected]ec666ab22013-04-17 20:05:59311 switch (addresses[i].GetFamily()) {
312 case ADDRESS_FAMILY_IPV4:
martijna23c8962016-03-04 18:18:51313 if (address.bytes()[0] != 127)
[email protected]ec666ab22013-04-17 20:05:59314 return false;
315 break;
316 case ADDRESS_FAMILY_IPV6:
317 return false;
318 default:
319 NOTREACHED();
320 return false;
321 }
322 }
323 return true;
324}
325
[email protected]cd565142012-06-12 16:21:45326// Creates NetLog parameters when the resolve failed.
danakj22f90e72016-04-16 01:55:40327std::unique_ptr<base::Value> NetLogProcTaskFailedCallback(
Avi Drissman13fc8932015-12-20 04:40:46328 uint32_t attempt_number,
eroman001c3742015-04-23 03:11:17329 int net_error,
330 int os_error,
331 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40332 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]cd565142012-06-12 16:21:45333 if (attempt_number)
334 dict->SetInteger("attempt_number", attempt_number);
[email protected]21526002010-05-16 19:42:46335
[email protected]cd565142012-06-12 16:21:45336 dict->SetInteger("net_error", net_error);
[email protected]13024882011-05-18 23:19:16337
[email protected]cd565142012-06-12 16:21:45338 if (os_error) {
339 dict->SetInteger("os_error", os_error);
[email protected]21526002010-05-16 19:42:46340#if defined(OS_POSIX)
[email protected]cd565142012-06-12 16:21:45341 dict->SetString("os_error_string", gai_strerror(os_error));
[email protected]21526002010-05-16 19:42:46342#elif defined(OS_WIN)
[email protected]cd565142012-06-12 16:21:45343 // Map the error code to a human-readable string.
344 LPWSTR error_string = NULL;
Peter Kastingbe940e92014-11-20 23:14:08345 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
346 0, // Use the internal message table.
347 os_error,
348 0, // Use default language.
349 (LPWSTR)&error_string,
350 0, // Buffer size.
351 0); // Arguments (unused).
[email protected]ad65a3e2013-12-25 18:18:01352 dict->SetString("os_error_string", base::WideToUTF8(error_string));
[email protected]cd565142012-06-12 16:21:45353 LocalFree(error_string);
[email protected]21526002010-05-16 19:42:46354#endif
[email protected]21526002010-05-16 19:42:46355 }
356
dchengc7eeda422015-12-26 03:56:48357 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45358}
[email protected]a9813302012-04-28 09:29:28359
[email protected]cd565142012-06-12 16:21:45360// Creates NetLog parameters when the DnsTask failed.
danakj22f90e72016-04-16 01:55:40361std::unique_ptr<base::Value> NetLogDnsTaskFailedCallback(
estade5e5529d2015-05-21 20:59:11362 int net_error,
363 int dns_error,
364 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40365 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]cd565142012-06-12 16:21:45366 dict->SetInteger("net_error", net_error);
367 if (dns_error)
368 dict->SetInteger("dns_error", dns_error);
dchengc7eeda422015-12-26 03:56:48369 return std::move(dict);
[email protected]ee094b82010-08-24 15:55:51370};
371
[email protected]cd565142012-06-12 16:21:45372// Creates NetLog parameters containing the information in a RequestInfo object,
373// along with the associated NetLog::Source.
danakj22f90e72016-04-16 01:55:40374std::unique_ptr<base::Value> NetLogRequestInfoCallback(
estade5e5529d2015-05-21 20:59:11375 const HostResolver::RequestInfo* info,
376 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40377 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]b3601bc22012-02-21 21:23:20378
[email protected]cd565142012-06-12 16:21:45379 dict->SetString("host", info->host_port_pair().ToString());
380 dict->SetInteger("address_family",
381 static_cast<int>(info->address_family()));
382 dict->SetBoolean("allow_cached_response", info->allow_cached_response());
383 dict->SetBoolean("is_speculative", info->is_speculative());
dchengc7eeda422015-12-26 03:56:48384 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45385}
[email protected]b3601bc22012-02-21 21:23:20386
[email protected]cd565142012-06-12 16:21:45387// Creates NetLog parameters for the creation of a HostResolverImpl::Job.
danakj22f90e72016-04-16 01:55:40388std::unique_ptr<base::Value> NetLogJobCreationCallback(
estade5e5529d2015-05-21 20:59:11389 const NetLog::Source& source,
390 const std::string* host,
391 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40392 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
estade5e5529d2015-05-21 20:59:11393 source.AddToEventParameters(dict.get());
[email protected]cd565142012-06-12 16:21:45394 dict->SetString("host", *host);
dchengc7eeda422015-12-26 03:56:48395 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45396}
[email protected]a9813302012-04-28 09:29:28397
[email protected]cd565142012-06-12 16:21:45398// Creates NetLog parameters for HOST_RESOLVER_IMPL_JOB_ATTACH/DETACH events.
danakj22f90e72016-04-16 01:55:40399std::unique_ptr<base::Value> NetLogJobAttachCallback(
estade5e5529d2015-05-21 20:59:11400 const NetLog::Source& source,
401 RequestPriority priority,
402 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40403 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
estade5e5529d2015-05-21 20:59:11404 source.AddToEventParameters(dict.get());
[email protected]3b04d1f22013-10-16 00:23:56405 dict->SetString("priority", RequestPriorityToString(priority));
dchengc7eeda422015-12-26 03:56:48406 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45407}
[email protected]b3601bc22012-02-21 21:23:20408
[email protected]cd565142012-06-12 16:21:45409// Creates NetLog parameters for the DNS_CONFIG_CHANGED event.
danakj22f90e72016-04-16 01:55:40410std::unique_ptr<base::Value> NetLogDnsConfigCallback(
estade5e5529d2015-05-21 20:59:11411 const DnsConfig* config,
412 NetLogCaptureMode /* capture_mode */) {
tfhef3618f2016-01-11 23:07:08413 return config->ToValue();
[email protected]cd565142012-06-12 16:21:45414}
[email protected]b4481b222012-03-16 17:13:11415
danakj22f90e72016-04-16 01:55:40416std::unique_ptr<base::Value> NetLogIPv6AvailableCallback(
estade5e5529d2015-05-21 20:59:11417 bool ipv6_available,
418 bool cached,
419 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40420 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
sergeyub8cdc212015-05-14 18:50:37421 dict->SetBoolean("ipv6_available", ipv6_available);
422 dict->SetBoolean("cached", cached);
dchengc7eeda422015-12-26 03:56:48423 return std::move(dict);
sergeyub8cdc212015-05-14 18:50:37424}
425
[email protected]0f292de02012-02-01 22:28:20426// The logging routines are defined here because some requests are resolved
427// without a Request object.
428
429// Logs when a request has just been started.
430void LogStartRequest(const BoundNetLog& source_net_log,
[email protected]0f292de02012-02-01 22:28:20431 const HostResolver::RequestInfo& info) {
432 source_net_log.BeginEvent(
[email protected]0f292de02012-02-01 22:28:20433 NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST,
xunjieli26f90452014-11-10 16:23:02434 base::Bind(&NetLogRequestInfoCallback, &info));
[email protected]0f292de02012-02-01 22:28:20435}
436
437// Logs when a request has just completed (before its callback is run).
438void LogFinishRequest(const BoundNetLog& source_net_log,
[email protected]0f292de02012-02-01 22:28:20439 const HostResolver::RequestInfo& info,
[email protected]b3601bc22012-02-21 21:23:20440 int net_error) {
xunjieli26f90452014-11-10 16:23:02441 source_net_log.EndEventWithNetErrorCode(
[email protected]b3601bc22012-02-21 21:23:20442 NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST, net_error);
[email protected]0f292de02012-02-01 22:28:20443}
444
445// Logs when a request has been cancelled.
446void LogCancelRequest(const BoundNetLog& source_net_log,
[email protected]0f292de02012-02-01 22:28:20447 const HostResolverImpl::RequestInfo& info) {
xunjieli26f90452014-11-10 16:23:02448 source_net_log.AddEvent(NetLog::TYPE_CANCELLED);
449 source_net_log.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST);
[email protected]0f292de02012-02-01 22:28:20450}
451
[email protected]b59ff372009-07-15 22:04:32452//-----------------------------------------------------------------------------
453
[email protected]0f292de02012-02-01 22:28:20454// Keeps track of the highest priority.
455class PriorityTracker {
456 public:
[email protected]8c98d002012-07-18 19:02:27457 explicit PriorityTracker(RequestPriority initial_priority)
458 : highest_priority_(initial_priority), total_count_(0) {
[email protected]0f292de02012-02-01 22:28:20459 memset(counts_, 0, sizeof(counts_));
460 }
461
462 RequestPriority highest_priority() const {
463 return highest_priority_;
464 }
465
466 size_t total_count() const {
467 return total_count_;
468 }
469
470 void Add(RequestPriority req_priority) {
471 ++total_count_;
472 ++counts_[req_priority];
[email protected]31ae7ab2012-04-24 21:09:05473 if (highest_priority_ < req_priority)
[email protected]0f292de02012-02-01 22:28:20474 highest_priority_ = req_priority;
475 }
476
477 void Remove(RequestPriority req_priority) {
478 DCHECK_GT(total_count_, 0u);
479 DCHECK_GT(counts_[req_priority], 0u);
480 --total_count_;
481 --counts_[req_priority];
482 size_t i;
[email protected]31ae7ab2012-04-24 21:09:05483 for (i = highest_priority_; i > MINIMUM_PRIORITY && !counts_[i]; --i);
[email protected]0f292de02012-02-01 22:28:20484 highest_priority_ = static_cast<RequestPriority>(i);
485
[email protected]31ae7ab2012-04-24 21:09:05486 // In absence of requests, default to MINIMUM_PRIORITY.
487 if (total_count_ == 0)
488 DCHECK_EQ(MINIMUM_PRIORITY, highest_priority_);
[email protected]0f292de02012-02-01 22:28:20489 }
490
491 private:
492 RequestPriority highest_priority_;
493 size_t total_count_;
494 size_t counts_[NUM_PRIORITIES];
495};
496
juliatuttle9fb7aeb2016-06-06 20:16:33497void MakeNotStale(HostCache::EntryStaleness* stale_info) {
498 if (!stale_info)
499 return;
500 stale_info->expired_by = base::TimeDelta::FromSeconds(-1);
501 stale_info->network_changes = 0;
502 stale_info->stale_hits = 0;
503}
504
[email protected]c54a8912012-10-22 22:09:43505} // namespace
[email protected]0f292de02012-02-01 22:28:20506
507//-----------------------------------------------------------------------------
508
tfarina9ed7f8c52016-02-19 17:50:18509bool ResolveLocalHostname(base::StringPiece host,
510 uint16_t port,
511 AddressList* address_list) {
tfarina9ed7f8c52016-02-19 17:50:18512 address_list->clear();
513
514 bool is_local6;
515 if (!IsLocalHostname(host, &is_local6))
516 return false;
517
martijna23c8962016-03-04 18:18:51518 address_list->push_back(IPEndPoint(IPAddress::IPv6Localhost(), port));
tfarina9ed7f8c52016-02-19 17:50:18519 if (!is_local6) {
martijna23c8962016-03-04 18:18:51520 address_list->push_back(IPEndPoint(IPAddress::IPv4Localhost(), port));
tfarina9ed7f8c52016-02-19 17:50:18521 }
522
523 return true;
524}
525
[email protected]daae1322013-09-05 18:26:50526const unsigned HostResolverImpl::kMaximumDnsFailures = 16;
527
[email protected]0f292de02012-02-01 22:28:20528// Holds the data for a request that could not be completed synchronously.
529// It is owned by a Job. Canceled Requests are only marked as canceled rather
530// than removed from the Job's |requests_| list.
[email protected]b59ff372009-07-15 22:04:32531class HostResolverImpl::Request {
532 public:
[email protected]ee094b82010-08-24 15:55:51533 Request(const BoundNetLog& source_net_log,
[email protected]54e13772009-08-14 03:01:09534 const RequestInfo& info,
[email protected]5109c1952013-08-20 18:44:10535 RequestPriority priority,
[email protected]aa22b242011-11-16 18:58:29536 const CompletionCallback& callback,
[email protected]b59ff372009-07-15 22:04:32537 AddressList* addresses)
[email protected]ee094b82010-08-24 15:55:51538 : source_net_log_(source_net_log),
[email protected]54e13772009-08-14 03:01:09539 info_(info),
[email protected]5109c1952013-08-20 18:44:10540 priority_(priority),
[email protected]54e13772009-08-14 03:01:09541 job_(NULL),
542 callback_(callback),
[email protected]51b9a6b2012-06-25 21:50:29543 addresses_(addresses),
[email protected]5109c1952013-08-20 18:44:10544 request_time_(base::TimeTicks::Now()) {}
[email protected]b59ff372009-07-15 22:04:32545
[email protected]0f292de02012-02-01 22:28:20546 // Mark the request as canceled.
547 void MarkAsCanceled() {
[email protected]b59ff372009-07-15 22:04:32548 job_ = NULL;
[email protected]b59ff372009-07-15 22:04:32549 addresses_ = NULL;
[email protected]aa22b242011-11-16 18:58:29550 callback_.Reset();
[email protected]b59ff372009-07-15 22:04:32551 }
552
[email protected]0f292de02012-02-01 22:28:20553 bool was_canceled() const {
[email protected]aa22b242011-11-16 18:58:29554 return callback_.is_null();
[email protected]b59ff372009-07-15 22:04:32555 }
556
557 void set_job(Job* job) {
[email protected]0f292de02012-02-01 22:28:20558 DCHECK(job);
[email protected]b59ff372009-07-15 22:04:32559 // Identify which job the request is waiting on.
560 job_ = job;
561 }
562
[email protected]0f292de02012-02-01 22:28:20563 // Prepare final AddressList and call completion callback.
[email protected]b3601bc22012-02-21 21:23:20564 void OnComplete(int error, const AddressList& addr_list) {
[email protected]51b9a6b2012-06-25 21:50:29565 DCHECK(!was_canceled());
[email protected]895123222012-10-25 15:21:17566 if (error == OK)
567 *addresses_ = EnsurePortOnAddressList(addr_list, info_.port());
[email protected]aa22b242011-11-16 18:58:29568 CompletionCallback callback = callback_;
[email protected]0f292de02012-02-01 22:28:20569 MarkAsCanceled();
[email protected]aa22b242011-11-16 18:58:29570 callback.Run(error);
[email protected]b59ff372009-07-15 22:04:32571 }
572
[email protected]b59ff372009-07-15 22:04:32573 Job* job() const {
574 return job_;
575 }
576
[email protected]0f292de02012-02-01 22:28:20577 // NetLog for the source, passed in HostResolver::Resolve.
[email protected]ee094b82010-08-24 15:55:51578 const BoundNetLog& source_net_log() {
579 return source_net_log_;
580 }
581
[email protected]b59ff372009-07-15 22:04:32582 const RequestInfo& info() const {
583 return info_;
584 }
585
[email protected]5109c1952013-08-20 18:44:10586 RequestPriority priority() const { return priority_; }
juliatuttlec53b19a72016-05-05 13:51:31587 void set_priority(RequestPriority priority) { priority_ = priority; }
[email protected]5109c1952013-08-20 18:44:10588
589 base::TimeTicks request_time() const { return request_time_; }
[email protected]51b9a6b2012-06-25 21:50:29590
[email protected]b59ff372009-07-15 22:04:32591 private:
xunjieli26f90452014-11-10 16:23:02592 const BoundNetLog source_net_log_;
[email protected]54e13772009-08-14 03:01:09593
[email protected]b59ff372009-07-15 22:04:32594 // The request info that started the request.
[email protected]5109c1952013-08-20 18:44:10595 const RequestInfo info_;
596
juliatuttlec53b19a72016-05-05 13:51:31597 RequestPriority priority_;
[email protected]b59ff372009-07-15 22:04:32598
[email protected]0f292de02012-02-01 22:28:20599 // The resolve job that this request is dependent on.
[email protected]b59ff372009-07-15 22:04:32600 Job* job_;
601
602 // The user's callback to invoke when the request completes.
[email protected]aa22b242011-11-16 18:58:29603 CompletionCallback callback_;
[email protected]b59ff372009-07-15 22:04:32604
605 // The address list to save result into.
606 AddressList* addresses_;
607
[email protected]51b9a6b2012-06-25 21:50:29608 const base::TimeTicks request_time_;
609
[email protected]b59ff372009-07-15 22:04:32610 DISALLOW_COPY_AND_ASSIGN(Request);
611};
612
[email protected]1e9bbd22010-10-15 16:42:45613//------------------------------------------------------------------------------
614
mmenke91c17162016-06-02 16:03:23615// Calls HostResolverProc using a worker task runner. Performs retries if
616// necessary.
[email protected]0f292de02012-02-01 22:28:20617//
618// Whenever we try to resolve the host, we post a delayed task to check if host
619// resolution (OnLookupComplete) is completed or not. If the original attempt
620// hasn't completed, then we start another attempt for host resolution. We take
621// the results from the first attempt that finishes and ignore the results from
622// all other attempts.
623//
624// TODO(szym): Move to separate source file for testing and mocking.
625//
626class HostResolverImpl::ProcTask
627 : public base::RefCountedThreadSafe<HostResolverImpl::ProcTask> {
[email protected]b59ff372009-07-15 22:04:32628 public:
[email protected]b3601bc22012-02-21 21:23:20629 typedef base::Callback<void(int net_error,
630 const AddressList& addr_list)> Callback;
[email protected]b59ff372009-07-15 22:04:32631
[email protected]0f292de02012-02-01 22:28:20632 ProcTask(const Key& key,
633 const ProcTaskParams& params,
634 const Callback& callback,
mmenke91c17162016-06-02 16:03:23635 scoped_refptr<base::TaskRunner> worker_task_runner,
[email protected]0f292de02012-02-01 22:28:20636 const BoundNetLog& job_net_log)
637 : key_(key),
638 params_(params),
639 callback_(callback),
mmenke91c17162016-06-02 16:03:23640 worker_task_runner_(std::move(worker_task_runner)),
641 network_task_runner_(base::ThreadTaskRunnerHandle::Get()),
[email protected]0f292de02012-02-01 22:28:20642 attempt_number_(0),
643 completed_attempt_number_(0),
644 completed_attempt_error_(ERR_UNEXPECTED),
645 had_non_speculative_request_(false),
[email protected]b3601bc22012-02-21 21:23:20646 net_log_(job_net_log) {
[email protected]90499482013-06-01 00:39:50647 if (!params_.resolver_proc.get())
[email protected]0f292de02012-02-01 22:28:20648 params_.resolver_proc = HostResolverProc::GetDefault();
649 // If default is unset, use the system proc.
[email protected]90499482013-06-01 00:39:50650 if (!params_.resolver_proc.get())
[email protected]1ee9afa12013-04-16 14:18:06651 params_.resolver_proc = new SystemHostResolverProc();
[email protected]b59ff372009-07-15 22:04:32652 }
653
[email protected]b59ff372009-07-15 22:04:32654 void Start() {
mmenke91c17162016-06-02 16:03:23655 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]4da911f2012-06-14 19:45:20656 net_log_.BeginEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK);
[email protected]189163e2011-05-11 01:48:54657 StartLookupAttempt();
658 }
[email protected]252b699b2010-02-05 21:38:06659
[email protected]0f292de02012-02-01 22:28:20660 // Cancels this ProcTask. It will be orphaned. Any outstanding resolve
mmenke91c17162016-06-02 16:03:23661 // attempts running on worker thread will continue running. Only once all the
[email protected]0f292de02012-02-01 22:28:20662 // attempts complete will the final reference to this ProcTask be released.
663 void Cancel() {
mmenke91c17162016-06-02 16:03:23664 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20665
[email protected]0adcb2b2012-08-15 21:30:46666 if (was_canceled() || was_completed())
[email protected]0f292de02012-02-01 22:28:20667 return;
668
[email protected]0f292de02012-02-01 22:28:20669 callback_.Reset();
[email protected]4da911f2012-06-14 19:45:20670 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK);
[email protected]0f292de02012-02-01 22:28:20671 }
672
673 void set_had_non_speculative_request() {
mmenke91c17162016-06-02 16:03:23674 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20675 had_non_speculative_request_ = true;
676 }
677
678 bool was_canceled() const {
mmenke91c17162016-06-02 16:03:23679 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20680 return callback_.is_null();
681 }
682
683 bool was_completed() const {
mmenke91c17162016-06-02 16:03:23684 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20685 return completed_attempt_number_ > 0;
686 }
687
688 private:
[email protected]a9813302012-04-28 09:29:28689 friend class base::RefCountedThreadSafe<ProcTask>;
690 ~ProcTask() {}
691
[email protected]189163e2011-05-11 01:48:54692 void StartLookupAttempt() {
mmenke91c17162016-06-02 16:03:23693 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54694 base::TimeTicks start_time = base::TimeTicks::Now();
695 ++attempt_number_;
696 // Dispatch the lookup attempt to a worker thread.
mmenke91c17162016-06-02 16:03:23697 if (!worker_task_runner_->PostTask(
698 FROM_HERE, base::Bind(&ProcTask::DoLookup, this, start_time,
699 attempt_number_))) {
[email protected]b59ff372009-07-15 22:04:32700 NOTREACHED();
701
mmenke91c17162016-06-02 16:03:23702 // Since this method may have been called from Resolve(), can't just call
703 // OnLookupComplete(). Instead, must wait until Resolve() has returned
704 // (IO_PENDING).
705 network_task_runner_->PostTask(
706 FROM_HERE,
707 base::Bind(&ProcTask::OnLookupComplete, this, AddressList(),
708 start_time, attempt_number_, ERR_UNEXPECTED, 0));
[email protected]189163e2011-05-11 01:48:54709 return;
[email protected]b59ff372009-07-15 22:04:32710 }
[email protected]13024882011-05-18 23:19:16711
tfarina5e24b242015-10-27 13:11:28712 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_ATTEMPT_STARTED,
713 NetLog::IntCallback("attempt_number", attempt_number_));
[email protected]13024882011-05-18 23:19:16714
mmenke91c17162016-06-02 16:03:23715 // If the results aren't received within a given time, RetryIfNotComplete
716 // will start a new attempt if none of the outstanding attempts have
717 // completed yet.
[email protected]0f292de02012-02-01 22:28:20718 if (attempt_number_ <= params_.max_retry_attempts) {
mmenke91c17162016-06-02 16:03:23719 network_task_runner_->PostDelayedTask(
720 FROM_HERE, base::Bind(&ProcTask::RetryIfNotComplete, this),
[email protected]7e560102012-03-08 20:58:42721 params_.unresponsive_delay);
[email protected]06ef6d92011-05-19 04:24:58722 }
[email protected]b59ff372009-07-15 22:04:32723 }
724
mmenke91c17162016-06-02 16:03:23725 // WARNING: In production, this code runs on a worker pool. The shutdown code
726 // cannot wait for it to finish, so this code must be very careful about using
727 // other objects (like MessageLoops, Singletons, etc). During shutdown these
728 // objects may no longer exist. Multiple DoLookups() could be running in
729 // parallel, so any state inside of |this| must not mutate .
[email protected]189163e2011-05-11 01:48:54730 void DoLookup(const base::TimeTicks& start_time,
Avi Drissman13fc8932015-12-20 04:40:46731 const uint32_t attempt_number) {
[email protected]189163e2011-05-11 01:48:54732 AddressList results;
733 int os_error = 0;
mmenke91c17162016-06-02 16:03:23734 // Running on a worker task runner.
[email protected]0f292de02012-02-01 22:28:20735 int error = params_.resolver_proc->Resolve(key_.hostname,
736 key_.address_family,
737 key_.host_resolver_flags,
738 &results,
739 &os_error);
[email protected]b59ff372009-07-15 22:04:32740
eroman91dd3602015-03-26 03:46:33741 // Fail the resolution if the result contains 127.0.53.53. See the comment
742 // block of kIcanNameCollisionIp for details on why.
743 for (const auto& it : results) {
martijna23c8962016-03-04 18:18:51744 const IPAddress& cur = it.address();
745 if (cur.IsIPv4() && IPAddressStartsWith(cur, kIcanNameCollisionIp)) {
eroman91dd3602015-03-26 03:46:33746 error = ERR_ICANN_NAME_COLLISION;
747 break;
748 }
749 }
750
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) {
ssid6d6b40102016-04-05 18:59:56773 TRACE_EVENT0("net", "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
[email protected]cd565142012-06-12 16:21:45799 NetLog::ParametersCallback 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 }
[email protected]cd565142012-06-12 16:21:45808 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_ATTEMPT_FINISHED,
809 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 }
[email protected]cd565142012-06-12 16:21:45831 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK,
832 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.
862 switch(key_.address_family) {
863 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.
883 switch(key_.address_family) {
884 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
[email protected]ee094b82010-08-24 15:55:51995 BoundNetLog net_log_;
996
[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,
[email protected]b3601bc22012-02-21 21:23:201073 const BoundNetLog& 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_);
[email protected]70c04ab2013-08-22 16:05:121094 net_log_.BeginEvent(NetLog::TYPE_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(
1239 NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK,
1240 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) {
[email protected]0adcb2b2012-08-15 21:30:461246 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK,
1247 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_;
[email protected]b3601bc22012-02-21 21:23:201256 const BoundNetLog net_log_;
1257
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,
xunjieli26f90452014-11-10 16:23:021285 const BoundNetLog& 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_),
xunjieli26f90452014-11-10 16:23:021296 net_log_(BoundNetLog::Make(source_net_log.net_log(),
[email protected]b3601bc22012-02-21 21:23:201297 NetLog::SOURCE_HOST_RESOLVER_IMPL_JOB)) {
xunjieli26f90452014-11-10 16:23:021298 source_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_CREATE_JOB);
[email protected]0f292de02012-02-01 22:28:201299
1300 net_log_.BeginEvent(
1301 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
[email protected]cd565142012-06-12 16:21:451302 base::Bind(&NetLogJobCreationCallback,
xunjieli26f90452014-11-10 16:23:021303 source_net_log.source(),
[email protected]cd565142012-06-12 16:21:451304 &key_.hostname));
[email protected]68ad3ee2010-01-30 03:45:391305 }
1306
dchengb03027d2014-10-21 12:00:201307 ~Job() override {
[email protected]b3601bc22012-02-21 21:23:201308 if (is_running()) {
1309 // |resolver_| was destroyed with this Job still in flight.
1310 // Clean-up, record in the log, but don't run any callbacks.
1311 if (is_proc_running()) {
[email protected]0f292de02012-02-01 22:28:201312 proc_task_->Cancel();
1313 proc_task_ = NULL;
[email protected]0f292de02012-02-01 22:28:201314 }
[email protected]16ee26d2012-03-08 03:34:351315 // Clean up now for nice NetLog.
[email protected]daae1322013-09-05 18:26:501316 KillDnsTask();
[email protected]b3601bc22012-02-21 21:23:201317 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
1318 ERR_ABORTED);
1319 } else if (is_queued()) {
[email protected]57a48d32012-03-03 00:04:551320 // |resolver_| was destroyed without running this Job.
[email protected]16ee26d2012-03-08 03:34:351321 // TODO(szym): is there any benefit in having this distinction?
[email protected]4da911f2012-06-14 19:45:201322 net_log_.AddEvent(NetLog::TYPE_CANCELLED);
1323 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB);
[email protected]68ad3ee2010-01-30 03:45:391324 }
[email protected]b3601bc22012-02-21 21:23:201325 // else CompleteRequests logged EndEvent.
[email protected]68ad3ee2010-01-30 03:45:391326
[email protected]b3601bc22012-02-21 21:23:201327 // Log any remaining Requests as cancelled.
danakj22f90e72016-04-16 01:55:401328 for (const std::unique_ptr<Request>& req : requests_) {
[email protected]b3601bc22012-02-21 21:23:201329 if (req->was_canceled())
1330 continue;
1331 DCHECK_EQ(this, req->job());
xunjieli26f90452014-11-10 16:23:021332 LogCancelRequest(req->source_net_log(), req->info());
[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
danakj22f90e72016-04-16 01:55:401355 void AddRequest(std::unique_ptr<Request> req) {
estarkd1bc206e2015-06-20 00:44:391356 DCHECK_EQ(key_.hostname, req->info().hostname());
[email protected]0f292de02012-02-01 22:28:201357
1358 req->set_job(this);
[email protected]5109c1952013-08-20 18:44:101359 priority_tracker_.Add(req->priority());
[email protected]0f292de02012-02-01 22:28:201360
xunjieli26f90452014-11-10 16:23:021361 req->source_net_log().AddEvent(
[email protected]0f292de02012-02-01 22:28:201362 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_ATTACH,
[email protected]cd565142012-06-12 16:21:451363 net_log_.source().ToEventParametersCallback());
[email protected]0f292de02012-02-01 22:28:201364
1365 net_log_.AddEvent(
1366 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_REQUEST_ATTACH,
[email protected]cd565142012-06-12 16:21:451367 base::Bind(&NetLogJobAttachCallback,
xunjieli26f90452014-11-10 16:23:021368 req->source_net_log().source(),
[email protected]cd565142012-06-12 16:21:451369 priority()));
[email protected]0f292de02012-02-01 22:28:201370
1371 // TODO(szym): Check if this is still needed.
1372 if (!req->info().is_speculative()) {
1373 had_non_speculative_request_ = true;
[email protected]90499482013-06-01 00:39:501374 if (proc_task_.get())
[email protected]0f292de02012-02-01 22:28:201375 proc_task_->set_had_non_speculative_request();
[email protected]68ad3ee2010-01-30 03:45:391376 }
[email protected]b3601bc22012-02-21 21:23:201377
dchengc7eeda422015-12-26 03:56:481378 requests_.push_back(std::move(req));
[email protected]b3601bc22012-02-21 21:23:201379
[email protected]51b9a6b2012-06-25 21:50:291380 UpdatePriority();
[email protected]68ad3ee2010-01-30 03:45:391381 }
1382
juliatuttlec53b19a72016-05-05 13:51:311383 void ChangeRequestPriority(Request* req, RequestPriority priority) {
1384 DCHECK_EQ(key_.hostname, req->info().hostname());
1385 DCHECK(!req->was_canceled());
1386
1387 priority_tracker_.Remove(req->priority());
1388 req->set_priority(priority);
1389 priority_tracker_.Add(req->priority());
1390 UpdatePriority();
1391 }
1392
[email protected]16ee26d2012-03-08 03:34:351393 // Marks |req| as cancelled. If it was the last active Request, also finishes
[email protected]0adcb2b2012-08-15 21:30:461394 // this Job, marking it as cancelled, and deletes it.
[email protected]0f292de02012-02-01 22:28:201395 void CancelRequest(Request* req) {
1396 DCHECK_EQ(key_.hostname, req->info().hostname());
1397 DCHECK(!req->was_canceled());
[email protected]16ee26d2012-03-08 03:34:351398
[email protected]0f292de02012-02-01 22:28:201399 // Don't remove it from |requests_| just mark it canceled.
1400 req->MarkAsCanceled();
xunjieli26f90452014-11-10 16:23:021401 LogCancelRequest(req->source_net_log(), req->info());
[email protected]16ee26d2012-03-08 03:34:351402
[email protected]5109c1952013-08-20 18:44:101403 priority_tracker_.Remove(req->priority());
1404 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_REQUEST_DETACH,
1405 base::Bind(&NetLogJobAttachCallback,
xunjieli26f90452014-11-10 16:23:021406 req->source_net_log().source(),
[email protected]5109c1952013-08-20 18:44:101407 priority()));
[email protected]b3601bc22012-02-21 21:23:201408
[email protected]16ee26d2012-03-08 03:34:351409 if (num_active_requests() > 0) {
[email protected]51b9a6b2012-06-25 21:50:291410 UpdatePriority();
[email protected]16ee26d2012-03-08 03:34:351411 } else {
1412 // If we were called from a Request's callback within CompleteRequests,
1413 // that Request could not have been cancelled, so num_active_requests()
1414 // could not be 0. Therefore, we are not in CompleteRequests().
[email protected]1339a2a22012-10-17 08:39:431415 CompleteRequestsWithError(OK /* cancelled */);
[email protected]b3601bc22012-02-21 21:23:201416 }
[email protected]68ad3ee2010-01-30 03:45:391417 }
1418
[email protected]7af985a2012-12-14 22:40:421419 // Called from AbortAllInProgressJobs. Completes all requests and destroys
1420 // the job. This currently assumes the abort is due to a network change.
olli.raulaa21e9eb72015-12-17 08:18:111421 // TODO This should not delete |this|.
[email protected]0f292de02012-02-01 22:28:201422 void Abort() {
[email protected]0f292de02012-02-01 22:28:201423 DCHECK(is_running());
[email protected]7af985a2012-12-14 22:40:421424 CompleteRequestsWithError(ERR_NETWORK_CHANGED);
[email protected]b3601bc22012-02-21 21:23:201425 }
1426
[email protected]f0f602bd2012-11-15 18:01:021427 // If DnsTask present, abort it and fall back to ProcTask.
1428 void AbortDnsTask() {
1429 if (dns_task_) {
[email protected]daae1322013-09-05 18:26:501430 KillDnsTask();
[email protected]f0f602bd2012-11-15 18:01:021431 dns_task_error_ = OK;
1432 StartProcTask();
1433 }
1434 }
1435
[email protected]16ee26d2012-03-08 03:34:351436 // Called by HostResolverImpl when this job is evicted due to queue overflow.
1437 // Completes all requests and destroys the job.
1438 void OnEvicted() {
1439 DCHECK(!is_running());
1440 DCHECK(is_queued());
1441 handle_.Reset();
1442
[email protected]4da911f2012-06-14 19:45:201443 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_EVICTED);
[email protected]16ee26d2012-03-08 03:34:351444
1445 // This signals to CompleteRequests that this job never ran.
[email protected]1339a2a22012-10-17 08:39:431446 CompleteRequestsWithError(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
[email protected]16ee26d2012-03-08 03:34:351447 }
1448
[email protected]78eac2a2012-03-14 19:09:271449 // Attempts to serve the job from HOSTS. Returns true if succeeded and
1450 // this Job was destroyed.
1451 bool ServeFromHosts() {
1452 DCHECK_GT(num_active_requests(), 0u);
1453 AddressList addr_list;
1454 if (resolver_->ServeFromHosts(key(),
[email protected]3cb676a12012-06-30 15:46:031455 requests_.front()->info(),
[email protected]78eac2a2012-03-14 19:09:271456 &addr_list)) {
1457 // This will destroy the Job.
[email protected]895123222012-10-25 15:21:171458 CompleteRequests(
1459 HostCache::Entry(OK, MakeAddressListForRequest(addr_list)),
1460 base::TimeDelta());
[email protected]78eac2a2012-03-14 19:09:271461 return true;
1462 }
1463 return false;
1464 }
1465
tanay.c6ddd5f6f2015-08-25 06:34:571466 const Key& key() const { return key_; }
[email protected]b4481b222012-03-16 17:13:111467
1468 bool is_queued() const {
1469 return !handle_.is_null();
1470 }
1471
1472 bool is_running() const {
1473 return is_dns_running() || is_proc_running();
1474 }
1475
[email protected]16ee26d2012-03-08 03:34:351476 private:
[email protected]daae1322013-09-05 18:26:501477 void KillDnsTask() {
1478 if (dns_task_) {
1479 ReduceToOneJobSlot();
1480 dns_task_.reset();
1481 }
1482 }
1483
1484 // Reduce the number of job slots occupied and queued in the dispatcher
1485 // to one. If the second Job slot is queued in the dispatcher, cancels the
1486 // queued job. Otherwise, the second Job has been started by the
1487 // PrioritizedDispatcher, so signals it is complete.
1488 void ReduceToOneJobSlot() {
1489 DCHECK_GE(num_occupied_job_slots_, 1u);
1490 if (is_queued()) {
[email protected]106ccd2c2014-06-17 09:21:001491 resolver_->dispatcher_->Cancel(handle_);
[email protected]daae1322013-09-05 18:26:501492 handle_.Reset();
1493 } else if (num_occupied_job_slots_ > 1) {
[email protected]106ccd2c2014-06-17 09:21:001494 resolver_->dispatcher_->OnJobFinished();
[email protected]daae1322013-09-05 18:26:501495 --num_occupied_job_slots_;
1496 }
1497 DCHECK_EQ(1u, num_occupied_job_slots_);
1498 }
1499
juliatuttlec53b19a72016-05-05 13:51:311500 AddressList MakeAddressListForRequest(const AddressList& list) const {
1501 if (requests_.empty())
1502 return list;
1503 return AddressList::CopyWithPort(list, requests_.front()->info().port());
1504 }
1505
[email protected]51b9a6b2012-06-25 21:50:291506 void UpdatePriority() {
1507 if (is_queued()) {
1508 if (priority() != static_cast<RequestPriority>(handle_.priority()))
1509 priority_change_time_ = base::TimeTicks::Now();
[email protected]106ccd2c2014-06-17 09:21:001510 handle_ = resolver_->dispatcher_->ChangePriority(handle_, priority());
[email protected]51b9a6b2012-06-25 21:50:291511 }
1512 }
1513
[email protected]16ee26d2012-03-08 03:34:351514 // PriorityDispatch::Job:
dchengb03027d2014-10-21 12:00:201515 void Start() override {
[email protected]daae1322013-09-05 18:26:501516 DCHECK_LE(num_occupied_job_slots_, 1u);
1517
[email protected]70c04ab2013-08-22 16:05:121518 handle_.Reset();
[email protected]daae1322013-09-05 18:26:501519 ++num_occupied_job_slots_;
1520
1521 if (num_occupied_job_slots_ == 2) {
1522 StartSecondDnsTransaction();
1523 return;
1524 }
1525
1526 DCHECK(!is_running());
[email protected]0f292de02012-02-01 22:28:201527
[email protected]4da911f2012-06-14 19:45:201528 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_STARTED);
[email protected]0f292de02012-02-01 22:28:201529
[email protected]51b9a6b2012-06-25 21:50:291530 had_dns_config_ = resolver_->HaveDnsConfig();
1531
1532 base::TimeTicks now = base::TimeTicks::Now();
1533 base::TimeDelta queue_time = now - creation_time_;
1534 base::TimeDelta queue_time_after_change = now - priority_change_time_;
1535
1536 if (had_dns_config_) {
1537 DNS_HISTOGRAM_BY_PRIORITY("AsyncDNS.JobQueueTime", priority(),
1538 queue_time);
1539 DNS_HISTOGRAM_BY_PRIORITY("AsyncDNS.JobQueueTimeAfterChange", priority(),
1540 queue_time_after_change);
1541 } else {
1542 DNS_HISTOGRAM_BY_PRIORITY("DNS.JobQueueTime", priority(), queue_time);
1543 DNS_HISTOGRAM_BY_PRIORITY("DNS.JobQueueTimeAfterChange", priority(),
1544 queue_time_after_change);
1545 }
1546
[email protected]443714fad2013-09-19 04:52:011547 bool system_only =
1548 (key_.host_resolver_flags & HOST_RESOLVER_SYSTEM_ONLY) != 0;
1549
[email protected]1d932852012-06-19 19:40:331550 // Caution: Job::Start must not complete synchronously.
[email protected]443714fad2013-09-19 04:52:011551 if (!system_only && had_dns_config_ &&
1552 !ResemblesMulticastDNSName(key_.hostname)) {
[email protected]b3601bc22012-02-21 21:23:201553 StartDnsTask();
1554 } else {
1555 StartProcTask();
1556 }
1557 }
1558
[email protected]b3601bc22012-02-21 21:23:201559 // TODO(szym): Since DnsTransaction does not consume threads, we can increase
1560 // the limits on |dispatcher_|. But in order to keep the number of WorkerPool
1561 // threads low, we will need to use an "inner" PrioritizedDispatcher with
1562 // tighter limits.
1563 void StartProcTask() {
[email protected]16ee26d2012-03-08 03:34:351564 DCHECK(!is_dns_running());
mmenke91c17162016-06-02 16:03:231565 proc_task_ =
1566 new ProcTask(key_, resolver_->proc_params_,
1567 base::Bind(&Job::OnProcTaskComplete,
1568 base::Unretained(this), base::TimeTicks::Now()),
1569 worker_task_runner_, net_log_);
[email protected]0f292de02012-02-01 22:28:201570
1571 if (had_non_speculative_request_)
1572 proc_task_->set_had_non_speculative_request();
1573 // Start() could be called from within Resolve(), hence it must NOT directly
1574 // call OnProcTaskComplete, for example, on synchronous failure.
1575 proc_task_->Start();
[email protected]68ad3ee2010-01-30 03:45:391576 }
1577
[email protected]0f292de02012-02-01 22:28:201578 // Called by ProcTask when it completes.
[email protected]e3bd4822012-10-23 18:01:371579 void OnProcTaskComplete(base::TimeTicks start_time,
1580 int net_error,
1581 const AddressList& addr_list) {
[email protected]b3601bc22012-02-21 21:23:201582 DCHECK(is_proc_running());
[email protected]68ad3ee2010-01-30 03:45:391583
[email protected]62e86ba2013-01-29 18:59:161584 if (!resolver_->resolved_known_ipv6_hostname_ &&
1585 net_error == OK &&
1586 key_.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
1587 if (key_.hostname == "www.google.com") {
1588 resolver_->resolved_known_ipv6_hostname_ = true;
1589 bool got_ipv6_address = false;
1590 for (size_t i = 0; i < addr_list.size(); ++i) {
[email protected]5134c22a2013-08-06 18:09:021591 if (addr_list[i].GetFamily() == ADDRESS_FAMILY_IPV6) {
[email protected]62e86ba2013-01-29 18:59:161592 got_ipv6_address = true;
[email protected]5134c22a2013-08-06 18:09:021593 break;
1594 }
[email protected]62e86ba2013-01-29 18:59:161595 }
1596 UMA_HISTOGRAM_BOOLEAN("Net.UnspecResolvedIPv6", got_ipv6_address);
1597 }
1598 }
1599
[email protected]1d932852012-06-19 19:40:331600 if (dns_task_error_ != OK) {
[email protected]e3bd4822012-10-23 18:01:371601 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]1def74c2012-03-22 20:07:001602 if (net_error == OK) {
[email protected]e3bd4822012-10-23 18:01:371603 DNS_HISTOGRAM("AsyncDNS.FallbackSuccess", duration);
[email protected]1d932852012-06-19 19:40:331604 if ((dns_task_error_ == ERR_NAME_NOT_RESOLVED) &&
1605 ResemblesNetBIOSName(key_.hostname)) {
1606 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_SUSPECT_NETBIOS);
1607 } else {
1608 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_PROC_SUCCESS);
1609 }
davidbenad6fc442015-05-18 20:59:131610 UMA_HISTOGRAM_SPARSE_SLOWLY("AsyncDNS.ResolveError",
1611 std::abs(dns_task_error_));
[email protected]1ffdda82012-12-12 23:04:221612 resolver_->OnDnsTaskResolve(dns_task_error_);
[email protected]1def74c2012-03-22 20:07:001613 } else {
[email protected]e3bd4822012-10-23 18:01:371614 DNS_HISTOGRAM("AsyncDNS.FallbackFail", duration);
[email protected]1def74c2012-03-22 20:07:001615 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
1616 }
1617 }
1618
[email protected]1339a2a22012-10-17 08:39:431619 base::TimeDelta ttl =
1620 base::TimeDelta::FromSeconds(kNegativeCacheEntryTTLSeconds);
[email protected]b3601bc22012-02-21 21:23:201621 if (net_error == OK)
1622 ttl = base::TimeDelta::FromSeconds(kCacheEntryTTLSeconds);
[email protected]68ad3ee2010-01-30 03:45:391623
[email protected]895123222012-10-25 15:21:171624 // Don't store the |ttl| in cache since it's not obtained from the server.
1625 CompleteRequests(
1626 HostCache::Entry(net_error, MakeAddressListForRequest(addr_list)),
1627 ttl);
[email protected]b3601bc22012-02-21 21:23:201628 }
1629
1630 void StartDnsTask() {
[email protected]78eac2a2012-03-14 19:09:271631 DCHECK(resolver_->HaveDnsConfig());
[email protected]daae1322013-09-05 18:26:501632 dns_task_.reset(new DnsTask(resolver_->dns_client_.get(), key_, this,
1633 net_log_));
[email protected]b3601bc22012-02-21 21:23:201634
[email protected]daae1322013-09-05 18:26:501635 dns_task_->StartFirstTransaction();
1636 // Schedule a second transaction, if needed.
1637 if (dns_task_->needs_two_transactions())
1638 Schedule(true);
1639 }
1640
1641 void StartSecondDnsTransaction() {
1642 DCHECK(dns_task_->needs_two_transactions());
1643 dns_task_->StartSecondTransaction();
[email protected]16c2bd72013-06-28 01:19:221644 }
1645
1646 // Called if DnsTask fails. It is posted from StartDnsTask, so Job may be
1647 // deleted before this callback. In this case dns_task is deleted as well,
1648 // so we use it as indicator whether Job is still valid.
1649 void OnDnsTaskFailure(const base::WeakPtr<DnsTask>& dns_task,
1650 base::TimeDelta duration,
1651 int net_error) {
1652 DNS_HISTOGRAM("AsyncDNS.ResolveFail", duration);
1653
1654 if (dns_task == NULL)
1655 return;
1656
1657 dns_task_error_ = net_error;
1658
1659 // TODO(szym): Run ServeFromHosts now if nsswitch.conf says so.
1660 // http://crbug.com/117655
1661
1662 // TODO(szym): Some net errors indicate lack of connectivity. Starting
1663 // ProcTask in that case is a waste of time.
1664 if (resolver_->fallback_to_proctask_) {
[email protected]daae1322013-09-05 18:26:501665 KillDnsTask();
[email protected]16c2bd72013-06-28 01:19:221666 StartProcTask();
1667 } else {
1668 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
1669 CompleteRequestsWithError(net_error);
[email protected]b3601bc22012-02-21 21:23:201670 }
1671 }
1672
[email protected]daae1322013-09-05 18:26:501673
1674 // HostResolverImpl::DnsTask::Delegate implementation:
1675
dchengb03027d2014-10-21 12:00:201676 void OnDnsTaskComplete(base::TimeTicks start_time,
1677 int net_error,
1678 const AddressList& addr_list,
1679 base::TimeDelta ttl) override {
[email protected]b3601bc22012-02-21 21:23:201680 DCHECK(is_dns_running());
[email protected]b3601bc22012-02-21 21:23:201681
[email protected]e3bd4822012-10-23 18:01:371682 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]b3601bc22012-02-21 21:23:201683 if (net_error != OK) {
[email protected]16c2bd72013-06-28 01:19:221684 OnDnsTaskFailure(dns_task_->AsWeakPtr(), duration, net_error);
[email protected]b3601bc22012-02-21 21:23:201685 return;
1686 }
[email protected]e3bd4822012-10-23 18:01:371687 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess", duration);
[email protected]02cd6982013-01-10 20:12:511688 // Log DNS lookups based on |address_family|.
1689 switch(key_.address_family) {
1690 case ADDRESS_FAMILY_IPV4:
1691 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_IPV4", duration);
1692 break;
1693 case ADDRESS_FAMILY_IPV6:
1694 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_IPV6", duration);
1695 break;
1696 case ADDRESS_FAMILY_UNSPECIFIED:
1697 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_UNSPEC", duration);
1698 break;
1699 }
[email protected]b3601bc22012-02-21 21:23:201700
[email protected]1def74c2012-03-22 20:07:001701 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_DNS_SUCCESS);
[email protected]1339a2a22012-10-17 08:39:431702 RecordTTL(ttl);
[email protected]0adcb2b2012-08-15 21:30:461703
[email protected]1ffdda82012-12-12 23:04:221704 resolver_->OnDnsTaskResolve(OK);
[email protected]f0f602bd2012-11-15 18:01:021705
[email protected]895123222012-10-25 15:21:171706 base::TimeDelta bounded_ttl =
1707 std::max(ttl, base::TimeDelta::FromSeconds(kMinimumTTLSeconds));
1708
1709 CompleteRequests(
1710 HostCache::Entry(net_error, MakeAddressListForRequest(addr_list), ttl),
1711 bounded_ttl);
[email protected]b3601bc22012-02-21 21:23:201712 }
1713
dchengb03027d2014-10-21 12:00:201714 void OnFirstDnsTransactionComplete() override {
[email protected]daae1322013-09-05 18:26:501715 DCHECK(dns_task_->needs_two_transactions());
1716 DCHECK_EQ(dns_task_->needs_another_transaction(), is_queued());
1717 // No longer need to occupy two dispatcher slots.
1718 ReduceToOneJobSlot();
1719
1720 // We already have a job slot at the dispatcher, so if the second
1721 // transaction hasn't started, reuse it now instead of waiting in the queue
1722 // for the second slot.
1723 if (dns_task_->needs_another_transaction())
1724 dns_task_->StartSecondTransaction();
1725 }
1726
[email protected]16ee26d2012-03-08 03:34:351727 // Performs Job's last rites. Completes all Requests. Deletes this.
[email protected]895123222012-10-25 15:21:171728 void CompleteRequests(const HostCache::Entry& entry,
1729 base::TimeDelta ttl) {
[email protected]11fbca0b2013-06-02 23:37:211730 CHECK(resolver_.get());
[email protected]b3601bc22012-02-21 21:23:201731
[email protected]16ee26d2012-03-08 03:34:351732 // This job must be removed from resolver's |jobs_| now to make room for a
1733 // new job with the same key in case one of the OnComplete callbacks decides
1734 // to spawn one. Consequently, the job deletes itself when CompleteRequests
1735 // is done.
danakj22f90e72016-04-16 01:55:401736 std::unique_ptr<Job> self_deleter(this);
[email protected]16ee26d2012-03-08 03:34:351737
1738 resolver_->RemoveJob(this);
1739
[email protected]16ee26d2012-03-08 03:34:351740 if (is_running()) {
[email protected]16ee26d2012-03-08 03:34:351741 if (is_proc_running()) {
[email protected]daae1322013-09-05 18:26:501742 DCHECK(!is_queued());
[email protected]16ee26d2012-03-08 03:34:351743 proc_task_->Cancel();
1744 proc_task_ = NULL;
1745 }
[email protected]daae1322013-09-05 18:26:501746 KillDnsTask();
[email protected]16ee26d2012-03-08 03:34:351747
1748 // Signal dispatcher that a slot has opened.
[email protected]106ccd2c2014-06-17 09:21:001749 resolver_->dispatcher_->OnJobFinished();
[email protected]16ee26d2012-03-08 03:34:351750 } else if (is_queued()) {
[email protected]106ccd2c2014-06-17 09:21:001751 resolver_->dispatcher_->Cancel(handle_);
[email protected]16ee26d2012-03-08 03:34:351752 handle_.Reset();
1753 }
1754
1755 if (num_active_requests() == 0) {
[email protected]4da911f2012-06-14 19:45:201756 net_log_.AddEvent(NetLog::TYPE_CANCELLED);
[email protected]16ee26d2012-03-08 03:34:351757 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
1758 OK);
1759 return;
1760 }
[email protected]b3601bc22012-02-21 21:23:201761
1762 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
juliatuttle317860e2016-05-12 14:47:221763 entry.error());
[email protected]68ad3ee2010-01-30 03:45:391764
[email protected]78eac2a2012-03-14 19:09:271765 DCHECK(!requests_.empty());
1766
juliatuttle317860e2016-05-12 14:47:221767 if (entry.error() == OK) {
[email protected]d7b9a2b2012-05-31 22:31:191768 // Record this histogram here, when we know the system has a valid DNS
1769 // configuration.
[email protected]539df6c2012-06-19 21:21:291770 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.HaveDnsConfig",
1771 resolver_->received_dns_config_);
[email protected]d7b9a2b2012-05-31 22:31:191772 }
[email protected]16ee26d2012-03-08 03:34:351773
juliatuttle317860e2016-05-12 14:47:221774 bool did_complete = (entry.error() != ERR_NETWORK_CHANGED) &&
1775 (entry.error() != ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
[email protected]895123222012-10-25 15:21:171776 if (did_complete)
[email protected]1339a2a22012-10-17 08:39:431777 resolver_->CacheResult(key_, entry, ttl);
[email protected]16ee26d2012-03-08 03:34:351778
[email protected]0f292de02012-02-01 22:28:201779 // Complete all of the requests that were attached to the job.
danakj22f90e72016-04-16 01:55:401780 for (const std::unique_ptr<Request>& req : requests_) {
[email protected]0f292de02012-02-01 22:28:201781 if (req->was_canceled())
1782 continue;
1783
1784 DCHECK_EQ(this, req->job());
1785 // Update the net log and notify registered observers.
juliatuttle317860e2016-05-12 14:47:221786 LogFinishRequest(req->source_net_log(), req->info(), entry.error());
[email protected]51b9a6b2012-06-25 21:50:291787 if (did_complete) {
1788 // Record effective total time from creation to completion.
1789 RecordTotalTime(had_dns_config_, req->info().is_speculative(),
1790 base::TimeTicks::Now() - req->request_time());
1791 }
juliatuttle317860e2016-05-12 14:47:221792 req->OnComplete(entry.error(), entry.addresses());
[email protected]0f292de02012-02-01 22:28:201793
1794 // Check if the resolver was destroyed as a result of running the
1795 // callback. If it was, we could continue, but we choose to bail.
[email protected]11fbca0b2013-06-02 23:37:211796 if (!resolver_.get())
[email protected]0f292de02012-02-01 22:28:201797 return;
1798 }
1799 }
1800
[email protected]1339a2a22012-10-17 08:39:431801 // Convenience wrapper for CompleteRequests in case of failure.
1802 void CompleteRequestsWithError(int net_error) {
[email protected]895123222012-10-25 15:21:171803 CompleteRequests(HostCache::Entry(net_error, AddressList()),
1804 base::TimeDelta());
[email protected]1339a2a22012-10-17 08:39:431805 }
1806
[email protected]b4481b222012-03-16 17:13:111807 RequestPriority priority() const {
1808 return priority_tracker_.highest_priority();
1809 }
1810
1811 // Number of non-canceled requests in |requests_|.
1812 size_t num_active_requests() const {
1813 return priority_tracker_.total_count();
1814 }
1815
1816 bool is_dns_running() const {
1817 return dns_task_.get() != NULL;
1818 }
1819
1820 bool is_proc_running() const {
1821 return proc_task_.get() != NULL;
1822 }
1823
[email protected]0f292de02012-02-01 22:28:201824 base::WeakPtr<HostResolverImpl> resolver_;
1825
1826 Key key_;
1827
1828 // Tracks the highest priority across |requests_|.
1829 PriorityTracker priority_tracker_;
1830
mmenke91c17162016-06-02 16:03:231831 // Task runner where the HostResolverProc is invoked.
1832 scoped_refptr<base::TaskRunner> worker_task_runner_;
1833
[email protected]0f292de02012-02-01 22:28:201834 bool had_non_speculative_request_;
1835
[email protected]51b9a6b2012-06-25 21:50:291836 // Distinguishes measurements taken while DnsClient was fully configured.
1837 bool had_dns_config_;
1838
[email protected]daae1322013-09-05 18:26:501839 // Number of slots occupied by this Job in resolver's PrioritizedDispatcher.
1840 unsigned num_occupied_job_slots_;
1841
[email protected]1d932852012-06-19 19:40:331842 // Result of DnsTask.
1843 int dns_task_error_;
[email protected]1def74c2012-03-22 20:07:001844
[email protected]51b9a6b2012-06-25 21:50:291845 const base::TimeTicks creation_time_;
1846 base::TimeTicks priority_change_time_;
1847
[email protected]0f292de02012-02-01 22:28:201848 BoundNetLog net_log_;
1849
[email protected]b3601bc22012-02-21 21:23:201850 // Resolves the host using a HostResolverProc.
[email protected]0f292de02012-02-01 22:28:201851 scoped_refptr<ProcTask> proc_task_;
1852
[email protected]b3601bc22012-02-21 21:23:201853 // Resolves the host using a DnsTransaction.
danakj22f90e72016-04-16 01:55:401854 std::unique_ptr<DnsTask> dns_task_;
[email protected]b3601bc22012-02-21 21:23:201855
[email protected]0f292de02012-02-01 22:28:201856 // All Requests waiting for the result of this Job. Some can be canceled.
danakj22f90e72016-04-16 01:55:401857 std::vector<std::unique_ptr<Request>> requests_;
[email protected]0f292de02012-02-01 22:28:201858
[email protected]16ee26d2012-03-08 03:34:351859 // A handle used in |HostResolverImpl::dispatcher_|.
[email protected]0f292de02012-02-01 22:28:201860 PrioritizedDispatcher::Handle handle_;
[email protected]68ad3ee2010-01-30 03:45:391861};
1862
1863//-----------------------------------------------------------------------------
1864
[email protected]0f292de02012-02-01 22:28:201865HostResolverImpl::ProcTaskParams::ProcTaskParams(
[email protected]e95d3aca2010-01-11 22:47:431866 HostResolverProc* resolver_proc,
[email protected]0f292de02012-02-01 22:28:201867 size_t max_retry_attempts)
1868 : resolver_proc(resolver_proc),
1869 max_retry_attempts(max_retry_attempts),
ttuttlecf1158bf2016-03-18 16:37:441870 unresponsive_delay(
1871 base::TimeDelta::FromMilliseconds(kDnsDefaultUnresponsiveDelayMs)),
[email protected]0f292de02012-02-01 22:28:201872 retry_factor(2) {
[email protected]106ccd2c2014-06-17 09:21:001873 // Maximum of 4 retry attempts for host resolution.
1874 static const size_t kDefaultMaxRetryAttempts = 4u;
1875 if (max_retry_attempts == HostResolver::kDefaultRetryAttempts)
1876 max_retry_attempts = kDefaultMaxRetryAttempts;
[email protected]0f292de02012-02-01 22:28:201877}
1878
vmpstracd23b72016-02-26 21:08:551879HostResolverImpl::ProcTaskParams::ProcTaskParams(const ProcTaskParams& other) =
1880 default;
1881
[email protected]0f292de02012-02-01 22:28:201882HostResolverImpl::ProcTaskParams::~ProcTaskParams() {}
1883
[email protected]106ccd2c2014-06-17 09:21:001884HostResolverImpl::HostResolverImpl(const Options& options, NetLog* net_log)
mmenke91c17162016-06-02 16:03:231885 : HostResolverImpl(
1886 options,
1887 net_log,
1888 base::WorkerPool::GetTaskRunner(true /* task_is_slow */)) {}
[email protected]b59ff372009-07-15 22:04:321889
1890HostResolverImpl::~HostResolverImpl() {
[email protected]daae1322013-09-05 18:26:501891 // Prevent the dispatcher from starting new jobs.
[email protected]106ccd2c2014-06-17 09:21:001892 dispatcher_->SetLimitsToZero();
[email protected]daae1322013-09-05 18:26:501893 // It's now safe for Jobs to call KillDsnTask on destruction, because
1894 // OnJobComplete will not start any new jobs.
[email protected]0f292de02012-02-01 22:28:201895 STLDeleteValues(&jobs_);
[email protected]e95d3aca2010-01-11 22:47:431896
[email protected]232a5812011-03-04 22:42:081897 NetworkChangeNotifier::RemoveIPAddressObserver(this);
ttuttlecf1158bf2016-03-18 16:37:441898 NetworkChangeNotifier::RemoveConnectionTypeObserver(this);
[email protected]bb0e34542012-08-31 19:52:401899 NetworkChangeNotifier::RemoveDNSObserver(this);
[email protected]b59ff372009-07-15 22:04:321900}
1901
[email protected]0f292de02012-02-01 22:28:201902void HostResolverImpl::SetMaxQueuedJobs(size_t value) {
[email protected]106ccd2c2014-06-17 09:21:001903 DCHECK_EQ(0u, dispatcher_->num_queued_jobs());
[email protected]0f292de02012-02-01 22:28:201904 DCHECK_GT(value, 0u);
1905 max_queued_jobs_ = value;
[email protected]be1a48b2011-01-20 00:12:131906}
1907
[email protected]684970b2009-08-14 04:54:461908int HostResolverImpl::Resolve(const RequestInfo& info,
[email protected]5109c1952013-08-20 18:44:101909 RequestPriority priority,
[email protected]b59ff372009-07-15 22:04:321910 AddressList* addresses,
[email protected]aa22b242011-11-16 18:58:291911 const CompletionCallback& callback,
[email protected]684970b2009-08-14 04:54:461912 RequestHandle* out_req,
[email protected]ee094b82010-08-24 15:55:511913 const BoundNetLog& source_net_log) {
[email protected]95a214c2011-08-04 21:50:401914 DCHECK(addresses);
[email protected]1ac6af92010-06-03 21:00:141915 DCHECK(CalledOnValidThread());
[email protected]aa22b242011-11-16 18:58:291916 DCHECK_EQ(false, callback.is_null());
[email protected]1ac6af92010-06-03 21:00:141917
[email protected]e806cd72013-05-17 02:08:431918 // Check that the caller supplied a valid hostname to resolve.
1919 std::string labeled_hostname;
1920 if (!DNSDomainFromDot(info.hostname(), &labeled_hostname))
1921 return ERR_NAME_NOT_RESOLVED;
1922
xunjieli26f90452014-11-10 16:23:021923 LogStartRequest(source_net_log, info);
[email protected]b59ff372009-07-15 22:04:321924
martijna23c8962016-03-04 18:18:511925 IPAddress ip_address;
1926 IPAddress* ip_address_ptr = nullptr;
1927 if (ip_address.AssignFromIPLiteral(info.hostname()))
1928 ip_address_ptr = &ip_address;
pauljensen19eb73422015-04-15 23:20:061929
[email protected]123ab1e32009-10-21 19:12:571930 // Build a key that identifies the request in the cache and in the
1931 // outstanding jobs map.
martijna23c8962016-03-04 18:18:511932 Key key = GetEffectiveKeyForRequest(info, ip_address_ptr, source_net_log);
[email protected]123ab1e32009-10-21 19:12:571933
juliatuttle9fb7aeb2016-06-06 20:16:331934 int rv = ResolveHelper(key, info, ip_address_ptr, addresses, false, nullptr,
1935 source_net_log);
[email protected]95a214c2011-08-04 21:50:401936 if (rv != ERR_DNS_CACHE_MISS) {
xunjieli26f90452014-11-10 16:23:021937 LogFinishRequest(source_net_log, info, rv);
[email protected]51b9a6b2012-06-25 21:50:291938 RecordTotalTime(HaveDnsConfig(), info.is_speculative(), base::TimeDelta());
[email protected]95a214c2011-08-04 21:50:401939 return rv;
[email protected]38368712011-03-02 08:09:401940 }
1941
[email protected]0f292de02012-02-01 22:28:201942 // Next we need to attach our request to a "job". This job is responsible for
1943 // calling "getaddrinfo(hostname)" on a worker thread.
1944
1945 JobMap::iterator jobit = jobs_.find(key);
1946 Job* job;
1947 if (jobit == jobs_.end()) {
mmenke91c17162016-06-02 16:03:231948 job = new Job(weak_ptr_factory_.GetWeakPtr(), key, priority,
1949 worker_task_runner_, source_net_log);
[email protected]daae1322013-09-05 18:26:501950 job->Schedule(false);
[email protected]0f292de02012-02-01 22:28:201951
1952 // Check for queue overflow.
[email protected]106ccd2c2014-06-17 09:21:001953 if (dispatcher_->num_queued_jobs() > max_queued_jobs_) {
1954 Job* evicted = static_cast<Job*>(dispatcher_->EvictOldestLowest());
[email protected]0f292de02012-02-01 22:28:201955 DCHECK(evicted);
[email protected]16ee26d2012-03-08 03:34:351956 evicted->OnEvicted(); // Deletes |evicted|.
[email protected]0f292de02012-02-01 22:28:201957 if (evicted == job) {
[email protected]0f292de02012-02-01 22:28:201958 rv = ERR_HOST_RESOLVER_QUEUE_TOO_LARGE;
xunjieli26f90452014-11-10 16:23:021959 LogFinishRequest(source_net_log, info, rv);
[email protected]0f292de02012-02-01 22:28:201960 return rv;
1961 }
[email protected]0f292de02012-02-01 22:28:201962 }
[email protected]0f292de02012-02-01 22:28:201963 jobs_.insert(jobit, std::make_pair(key, job));
1964 } else {
1965 job = jobit->second;
1966 }
1967
1968 // Can't complete synchronously. Create and attach request.
danakj22f90e72016-04-16 01:55:401969 std::unique_ptr<Request> req(
1970 new Request(source_net_log, info, priority, callback, addresses));
[email protected]b59ff372009-07-15 22:04:321971 if (out_req)
[email protected]b3601bc22012-02-21 21:23:201972 *out_req = reinterpret_cast<RequestHandle>(req.get());
[email protected]b59ff372009-07-15 22:04:321973
dchengc7eeda422015-12-26 03:56:481974 job->AddRequest(std::move(req));
[email protected]0f292de02012-02-01 22:28:201975 // Completion happens during Job::CompleteRequests().
[email protected]b59ff372009-07-15 22:04:321976 return ERR_IO_PENDING;
1977}
1978
mmenke91c17162016-06-02 16:03:231979HostResolverImpl::HostResolverImpl(
1980 const Options& options,
1981 NetLog* net_log,
1982 scoped_refptr<base::TaskRunner> worker_task_runner)
1983 : max_queued_jobs_(0),
1984 proc_params_(NULL, options.max_retry_attempts),
1985 net_log_(net_log),
1986 received_dns_config_(false),
1987 num_dns_failures_(0),
1988 use_local_ipv6_(false),
1989 last_ipv6_probe_result_(true),
1990 resolved_known_ipv6_hostname_(false),
1991 additional_resolver_flags_(0),
1992 fallback_to_proctask_(true),
1993 worker_task_runner_(std::move(worker_task_runner)),
1994 weak_ptr_factory_(this),
1995 probe_weak_ptr_factory_(this) {
1996 if (options.enable_caching)
1997 cache_ = HostCache::CreateDefaultCache();
1998
1999 PrioritizedDispatcher::Limits job_limits = options.GetDispatcherLimits();
2000 dispatcher_.reset(new PrioritizedDispatcher(job_limits));
2001 max_queued_jobs_ = job_limits.total_jobs * 100u;
2002
2003 DCHECK_GE(dispatcher_->num_priorities(), static_cast<size_t>(NUM_PRIORITIES));
2004
2005#if defined(OS_WIN)
2006 EnsureWinsockInit();
2007#endif
2008#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
2009 RunLoopbackProbeJob();
2010#endif
2011 NetworkChangeNotifier::AddIPAddressObserver(this);
2012 NetworkChangeNotifier::AddConnectionTypeObserver(this);
2013 NetworkChangeNotifier::AddDNSObserver(this);
2014#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD) && \
2015 !defined(OS_ANDROID)
2016 EnsureDnsReloaderInit();
2017#endif
2018
2019 OnConnectionTypeChanged(NetworkChangeNotifier::GetConnectionType());
2020
2021 {
2022 DnsConfig dns_config;
2023 NetworkChangeNotifier::GetDnsConfig(&dns_config);
2024 received_dns_config_ = dns_config.IsValid();
2025 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
2026 use_local_ipv6_ = !dns_config.IsValid() || dns_config.use_local_ipv6;
2027 }
2028
2029 fallback_to_proctask_ = !ConfigureAsyncDnsNoFallbackFieldTrial();
2030}
2031
2032void HostResolverImpl::SetHaveOnlyLoopbackAddresses(bool result) {
2033 if (result) {
2034 additional_resolver_flags_ |= HOST_RESOLVER_LOOPBACK_ONLY;
2035 } else {
2036 additional_resolver_flags_ &= ~HOST_RESOLVER_LOOPBACK_ONLY;
2037 }
2038}
2039
[email protected]287d7c22011-11-15 17:34:252040int HostResolverImpl::ResolveHelper(const Key& key,
[email protected]95a214c2011-08-04 21:50:402041 const RequestInfo& info,
martijna23c8962016-03-04 18:18:512042 const IPAddress* ip_address,
[email protected]95a214c2011-08-04 21:50:402043 AddressList* addresses,
juliatuttle9fb7aeb2016-06-06 20:16:332044 bool allow_stale,
2045 HostCache::EntryStaleness* stale_info,
xunjieli26f90452014-11-10 16:23:022046 const BoundNetLog& source_net_log) {
juliatuttle9fb7aeb2016-06-06 20:16:332047 DCHECK(allow_stale == !!stale_info);
[email protected]95a214c2011-08-04 21:50:402048 // The result of |getaddrinfo| for empty hosts is inconsistent across systems.
2049 // On Windows it gives the default interface's address, whereas on Linux it
2050 // gives an error. We will make it fail on all platforms for consistency.
juliatuttle9fb7aeb2016-06-06 20:16:332051 if (info.hostname().empty() || info.hostname().size() > kMaxHostLength) {
2052 MakeNotStale(stale_info);
[email protected]95a214c2011-08-04 21:50:402053 return ERR_NAME_NOT_RESOLVED;
juliatuttle9fb7aeb2016-06-06 20:16:332054 }
[email protected]95a214c2011-08-04 21:50:402055
2056 int net_error = ERR_UNEXPECTED;
juliatuttle9fb7aeb2016-06-06 20:16:332057 if (ResolveAsIP(key, info, ip_address, &net_error, addresses)) {
2058 MakeNotStale(stale_info);
[email protected]95a214c2011-08-04 21:50:402059 return net_error;
juliatuttle9fb7aeb2016-06-06 20:16:332060 }
2061 if (ServeFromCache(key, info, &net_error, addresses, allow_stale,
2062 stale_info)) {
xunjieli26f90452014-11-10 16:23:022063 source_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_CACHE_HIT);
juliatuttle9fb7aeb2016-06-06 20:16:332064 // |ServeFromCache()| will set |*stale_info| as needed.
[email protected]78eac2a2012-03-14 19:09:272065 return net_error;
2066 }
2067 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2068 // http://crbug.com/117655
2069 if (ServeFromHosts(key, info, addresses)) {
xunjieli26f90452014-11-10 16:23:022070 source_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_HOSTS_HIT);
juliatuttle9fb7aeb2016-06-06 20:16:332071 MakeNotStale(stale_info);
[email protected]78eac2a2012-03-14 19:09:272072 return OK;
2073 }
estarkd1bc206e2015-06-20 00:44:392074
juliatuttle9fb7aeb2016-06-06 20:16:332075 if (ServeLocalhost(key, info, addresses)) {
2076 MakeNotStale(stale_info);
estarkd1bc206e2015-06-20 00:44:392077 return OK;
juliatuttle9fb7aeb2016-06-06 20:16:332078 }
estarkd1bc206e2015-06-20 00:44:392079
[email protected]78eac2a2012-03-14 19:09:272080 return ERR_DNS_CACHE_MISS;
[email protected]95a214c2011-08-04 21:50:402081}
2082
2083int HostResolverImpl::ResolveFromCache(const RequestInfo& info,
2084 AddressList* addresses,
2085 const BoundNetLog& source_net_log) {
2086 DCHECK(CalledOnValidThread());
2087 DCHECK(addresses);
2088
[email protected]95a214c2011-08-04 21:50:402089 // Update the net log and notify registered observers.
xunjieli26f90452014-11-10 16:23:022090 LogStartRequest(source_net_log, info);
[email protected]95a214c2011-08-04 21:50:402091
martijna23c8962016-03-04 18:18:512092 IPAddress ip_address;
2093 IPAddress* ip_address_ptr = nullptr;
2094 if (ip_address.AssignFromIPLiteral(info.hostname()))
2095 ip_address_ptr = &ip_address;
[email protected]95a214c2011-08-04 21:50:402096
martijna23c8962016-03-04 18:18:512097 Key key = GetEffectiveKeyForRequest(info, ip_address_ptr, source_net_log);
pauljensen19eb73422015-04-15 23:20:062098
juliatuttle9fb7aeb2016-06-06 20:16:332099 int rv = ResolveHelper(key, info, ip_address_ptr, addresses, false, nullptr,
2100 source_net_log);
xunjieli26f90452014-11-10 16:23:022101 LogFinishRequest(source_net_log, info, rv);
[email protected]95a214c2011-08-04 21:50:402102 return rv;
2103}
2104
juliatuttlec53b19a72016-05-05 13:51:312105void HostResolverImpl::ChangeRequestPriority(RequestHandle req_handle,
2106 RequestPriority priority) {
2107 DCHECK(CalledOnValidThread());
2108 Request* req = reinterpret_cast<Request*>(req_handle);
2109 DCHECK(req);
2110 Job* job = req->job();
2111 DCHECK(job);
2112 job->ChangeRequestPriority(req, priority);
2113}
2114
[email protected]b59ff372009-07-15 22:04:322115void HostResolverImpl::CancelRequest(RequestHandle req_handle) {
[email protected]1ac6af92010-06-03 21:00:142116 DCHECK(CalledOnValidThread());
[email protected]b59ff372009-07-15 22:04:322117 Request* req = reinterpret_cast<Request*>(req_handle);
2118 DCHECK(req);
[email protected]0f292de02012-02-01 22:28:202119 Job* job = req->job();
2120 DCHECK(job);
[email protected]0f292de02012-02-01 22:28:202121 job->CancelRequest(req);
[email protected]b59ff372009-07-15 22:04:322122}
2123
[email protected]a8883e452012-11-17 05:58:062124void HostResolverImpl::SetDnsClientEnabled(bool enabled) {
2125 DCHECK(CalledOnValidThread());
2126#if defined(ENABLE_BUILT_IN_DNS)
2127 if (enabled && !dns_client_) {
2128 SetDnsClient(DnsClient::CreateClient(net_log_));
2129 } else if (!enabled && dns_client_) {
danakj22f90e72016-04-16 01:55:402130 SetDnsClient(std::unique_ptr<DnsClient>());
[email protected]a8883e452012-11-17 05:58:062131 }
2132#endif
2133}
2134
[email protected]489d1a82011-10-12 03:09:112135HostCache* HostResolverImpl::GetHostCache() {
2136 return cache_.get();
2137}
[email protected]95a214c2011-08-04 21:50:402138
danakj22f90e72016-04-16 01:55:402139std::unique_ptr<base::Value> HostResolverImpl::GetDnsConfigAsValue() const {
[email protected]17e92032012-03-29 00:56:242140 // Check if async DNS is disabled.
2141 if (!dns_client_.get())
tfhef3618f2016-01-11 23:07:082142 return nullptr;
[email protected]17e92032012-03-29 00:56:242143
2144 // Check if async DNS is enabled, but we currently have no configuration
2145 // for it.
2146 const DnsConfig* dns_config = dns_client_->GetConfig();
2147 if (dns_config == NULL)
danakj22f90e72016-04-16 01:55:402148 return base::WrapUnique(new base::DictionaryValue());
[email protected]17e92032012-03-29 00:56:242149
2150 return dns_config->ToValue();
2151}
2152
juliatuttle9fb7aeb2016-06-06 20:16:332153int HostResolverImpl::ResolveStaleFromCache(
2154 const RequestInfo& info,
2155 AddressList* addresses,
2156 HostCache::EntryStaleness* stale_info,
2157 const BoundNetLog& source_net_log) {
2158 DCHECK(CalledOnValidThread());
2159 DCHECK(addresses);
2160 DCHECK(stale_info);
2161
2162 // Update the net log and notify registered observers.
2163 LogStartRequest(source_net_log, info);
2164
2165 IPAddress ip_address;
2166 IPAddress* ip_address_ptr = nullptr;
2167 if (ip_address.AssignFromIPLiteral(info.hostname()))
2168 ip_address_ptr = &ip_address;
2169
2170 Key key = GetEffectiveKeyForRequest(info, ip_address_ptr, source_net_log);
2171
2172 int rv = ResolveHelper(key, info, ip_address_ptr, addresses, true, stale_info,
2173 source_net_log);
2174 LogFinishRequest(source_net_log, info, rv);
2175 return rv;
2176}
2177
[email protected]95a214c2011-08-04 21:50:402178bool HostResolverImpl::ResolveAsIP(const Key& key,
2179 const RequestInfo& info,
martijna23c8962016-03-04 18:18:512180 const IPAddress* ip_address,
[email protected]95a214c2011-08-04 21:50:402181 int* net_error,
2182 AddressList* addresses) {
2183 DCHECK(addresses);
2184 DCHECK(net_error);
martijna23c8962016-03-04 18:18:512185 if (ip_address == nullptr)
[email protected]95a214c2011-08-04 21:50:402186 return false;
2187
[email protected]95a214c2011-08-04 21:50:402188 *net_error = OK;
martijna23c8962016-03-04 18:18:512189 AddressFamily family = GetAddressFamily(*ip_address);
cbentzel1906f872015-06-05 16:25:252190 if (key.address_family != ADDRESS_FAMILY_UNSPECIFIED &&
2191 key.address_family != family) {
[email protected]1c7cf3f82014-08-07 21:33:482192 // Don't return IPv6 addresses for IPv4 queries, and vice versa.
[email protected]95a214c2011-08-04 21:50:402193 *net_error = ERR_NAME_NOT_RESOLVED;
2194 } else {
martijna23c8962016-03-04 18:18:512195 *addresses = AddressList::CreateFromIPAddress(*ip_address, info.port());
[email protected]7054e78f2012-05-07 21:44:562196 if (key.host_resolver_flags & HOST_RESOLVER_CANONNAME)
2197 addresses->SetDefaultCanonicalName();
[email protected]95a214c2011-08-04 21:50:402198 }
2199 return true;
2200}
2201
2202bool HostResolverImpl::ServeFromCache(const Key& key,
2203 const RequestInfo& info,
[email protected]95a214c2011-08-04 21:50:402204 int* net_error,
juliatuttle9fb7aeb2016-06-06 20:16:332205 AddressList* addresses,
2206 bool allow_stale,
2207 HostCache::EntryStaleness* stale_info) {
[email protected]95a214c2011-08-04 21:50:402208 DCHECK(addresses);
2209 DCHECK(net_error);
juliatuttle9fb7aeb2016-06-06 20:16:332210 DCHECK(allow_stale == !!stale_info);
[email protected]95a214c2011-08-04 21:50:402211 if (!info.allow_cached_response() || !cache_.get())
2212 return false;
2213
juliatuttle9fb7aeb2016-06-06 20:16:332214 const HostCache::Entry* cache_entry;
2215 if (allow_stale)
2216 cache_entry = cache_->LookupStale(key, base::TimeTicks::Now(), stale_info);
2217 else
2218 cache_entry = cache_->Lookup(key, base::TimeTicks::Now());
[email protected]95a214c2011-08-04 21:50:402219 if (!cache_entry)
2220 return false;
2221
juliatuttle317860e2016-05-12 14:47:222222 *net_error = cache_entry->error();
[email protected]7054e78f2012-05-07 21:44:562223 if (*net_error == OK) {
[email protected]1339a2a22012-10-17 08:39:432224 if (cache_entry->has_ttl())
juliatuttle317860e2016-05-12 14:47:222225 RecordTTL(cache_entry->ttl());
2226 *addresses = EnsurePortOnAddressList(cache_entry->addresses(), info.port());
[email protected]7054e78f2012-05-07 21:44:562227 }
[email protected]95a214c2011-08-04 21:50:402228 return true;
2229}
2230
[email protected]78eac2a2012-03-14 19:09:272231bool HostResolverImpl::ServeFromHosts(const Key& key,
2232 const RequestInfo& info,
2233 AddressList* addresses) {
2234 DCHECK(addresses);
2235 if (!HaveDnsConfig())
2236 return false;
[email protected]05a79d42013-03-28 07:30:092237 addresses->clear();
2238
[email protected]cb507622012-03-23 16:17:062239 // HOSTS lookups are case-insensitive.
brettw8e2106d2015-08-11 19:30:222240 std::string hostname = base::ToLowerASCII(key.hostname);
[email protected]cb507622012-03-23 16:17:062241
[email protected]05a79d42013-03-28 07:30:092242 const DnsHosts& hosts = dns_client_->GetConfig()->hosts;
2243
[email protected]78eac2a2012-03-14 19:09:272244 // If |address_family| is ADDRESS_FAMILY_UNSPECIFIED other implementations
2245 // (glibc and c-ares) return the first matching line. We have more
2246 // flexibility, but lose implicit ordering.
[email protected]05a79d42013-03-28 07:30:092247 // We prefer IPv6 because "happy eyeballs" will fall back to IPv4 if
2248 // necessary.
2249 if (key.address_family == ADDRESS_FAMILY_IPV6 ||
2250 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
2251 DnsHosts::const_iterator it = hosts.find(
2252 DnsHostsKey(hostname, ADDRESS_FAMILY_IPV6));
2253 if (it != hosts.end())
2254 addresses->push_back(IPEndPoint(it->second, info.port()));
[email protected]78eac2a2012-03-14 19:09:272255 }
2256
[email protected]05a79d42013-03-28 07:30:092257 if (key.address_family == ADDRESS_FAMILY_IPV4 ||
2258 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
2259 DnsHosts::const_iterator it = hosts.find(
2260 DnsHostsKey(hostname, ADDRESS_FAMILY_IPV4));
2261 if (it != hosts.end())
2262 addresses->push_back(IPEndPoint(it->second, info.port()));
2263 }
2264
[email protected]ec666ab22013-04-17 20:05:592265 // If got only loopback addresses and the family was restricted, resolve
2266 // again, without restrictions. See SystemHostResolverCall for rationale.
2267 if ((key.host_resolver_flags &
2268 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6) &&
2269 IsAllIPv4Loopback(*addresses)) {
2270 Key new_key(key);
2271 new_key.address_family = ADDRESS_FAMILY_UNSPECIFIED;
2272 new_key.host_resolver_flags &=
2273 ~HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
2274 return ServeFromHosts(new_key, info, addresses);
2275 }
[email protected]05a79d42013-03-28 07:30:092276 return !addresses->empty();
[email protected]78eac2a2012-03-14 19:09:272277}
2278
estarkd1bc206e2015-06-20 00:44:392279bool HostResolverImpl::ServeLocalhost(const Key& key,
2280 const RequestInfo& info,
2281 AddressList* addresses) {
2282 AddressList resolved_addresses;
2283 if (!ResolveLocalHostname(key.hostname, info.port(), &resolved_addresses))
2284 return false;
2285
2286 addresses->clear();
2287
2288 for (const auto& address : resolved_addresses) {
2289 // Include the address if:
2290 // - caller didn't specify an address family, or
2291 // - caller specifically asked for the address family of this address, or
2292 // - this is an IPv6 address and caller specifically asked for IPv4 due
2293 // to lack of detected IPv6 support. (See SystemHostResolverCall for
2294 // rationale).
2295 if (key.address_family == ADDRESS_FAMILY_UNSPECIFIED ||
2296 key.address_family == address.GetFamily() ||
2297 (address.GetFamily() == ADDRESS_FAMILY_IPV6 &&
2298 key.address_family == ADDRESS_FAMILY_IPV4 &&
2299 (key.host_resolver_flags &
2300 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6))) {
2301 addresses->push_back(address);
2302 }
2303 }
2304
2305 return true;
2306}
2307
[email protected]16ee26d2012-03-08 03:34:352308void HostResolverImpl::CacheResult(const Key& key,
[email protected]1339a2a22012-10-17 08:39:432309 const HostCache::Entry& entry,
[email protected]16ee26d2012-03-08 03:34:352310 base::TimeDelta ttl) {
2311 if (cache_.get())
[email protected]1339a2a22012-10-17 08:39:432312 cache_->Set(key, entry, base::TimeTicks::Now(), ttl);
[email protected]ef4c40c2010-09-01 14:42:032313}
2314
[email protected]0f292de02012-02-01 22:28:202315void HostResolverImpl::RemoveJob(Job* job) {
2316 DCHECK(job);
[email protected]16ee26d2012-03-08 03:34:352317 JobMap::iterator it = jobs_.find(job->key());
2318 if (it != jobs_.end() && it->second == job)
2319 jobs_.erase(it);
[email protected]b59ff372009-07-15 22:04:322320}
2321
[email protected]137af622010-02-05 02:14:352322HostResolverImpl::Key HostResolverImpl::GetEffectiveKeyForRequest(
pauljensen19eb73422015-04-15 23:20:062323 const RequestInfo& info,
martijna23c8962016-03-04 18:18:512324 const IPAddress* ip_address,
sergeyub8cdc212015-05-14 18:50:372325 const BoundNetLog& net_log) {
[email protected]eaf3a3b2010-09-03 20:34:272326 HostResolverFlags effective_flags =
2327 info.host_resolver_flags() | additional_resolver_flags_;
[email protected]137af622010-02-05 02:14:352328 AddressFamily effective_address_family = info.address_family();
[email protected]9db6f702013-04-10 18:10:512329
2330 if (info.address_family() == ADDRESS_FAMILY_UNSPECIFIED) {
cbentzel1906f872015-06-05 16:25:252331 if (!use_local_ipv6_ &&
pauljensen19eb73422015-04-15 23:20:062332 // When resolving IPv4 literals, there's no need to probe for IPv6.
2333 // When resolving IPv6 literals, there's no benefit to artificially
2334 // limiting our resolution based on a probe. Prior logic ensures
2335 // that this query is UNSPECIFIED (see info.address_family()
cbentzel1906f872015-06-05 16:25:252336 // check above) so the code requesting the resolution should be amenable
2337 // to receiving a IPv6 resolution.
martijna23c8962016-03-04 18:18:512338 ip_address == nullptr) {
sergeyub8cdc212015-05-14 18:50:372339 if (!IsIPv6Reachable(net_log)) {
[email protected]ac0b52e2013-04-21 01:26:162340 effective_address_family = ADDRESS_FAMILY_IPV4;
2341 effective_flags |= HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
2342 }
[email protected]9db6f702013-04-10 18:10:512343 }
2344 }
2345
estarkd1bc206e2015-06-20 00:44:392346 return Key(info.hostname(), effective_address_family, effective_flags);
[email protected]137af622010-02-05 02:14:352347}
2348
sergeyub8cdc212015-05-14 18:50:372349bool HostResolverImpl::IsIPv6Reachable(const BoundNetLog& net_log) {
2350 base::TimeTicks now = base::TimeTicks::Now();
2351 bool cached = true;
2352 if ((now - last_ipv6_probe_time_).InMilliseconds() > kIPv6ProbePeriodMs) {
martijna23c8962016-03-04 18:18:512353 last_ipv6_probe_result_ =
2354 IsGloballyReachable(IPAddress(kIPv6ProbeAddress), net_log);
sergeyub8cdc212015-05-14 18:50:372355 last_ipv6_probe_time_ = now;
2356 cached = false;
2357 }
2358 net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_IPV6_REACHABILITY_CHECK,
2359 base::Bind(&NetLogIPv6AvailableCallback,
2360 last_ipv6_probe_result_, cached));
2361 return last_ipv6_probe_result_;
2362}
2363
mmenke91c17162016-06-02 16:03:232364void HostResolverImpl::RunLoopbackProbeJob() {
2365 new LoopbackProbeJob(weak_ptr_factory_.GetWeakPtr(),
2366 worker_task_runner_.get());
2367}
2368
[email protected]35ddc282010-09-21 23:42:062369void HostResolverImpl::AbortAllInProgressJobs() {
[email protected]b3601bc22012-02-21 21:23:202370 // In Abort, a Request callback could spawn new Jobs with matching keys, so
2371 // first collect and remove all running jobs from |jobs_|.
danakj22f90e72016-04-16 01:55:402372 std::vector<std::unique_ptr<Job>> jobs_to_abort;
[email protected]0f292de02012-02-01 22:28:202373 for (JobMap::iterator it = jobs_.begin(); it != jobs_.end(); ) {
2374 Job* job = it->second;
[email protected]0f292de02012-02-01 22:28:202375 if (job->is_running()) {
danakj22f90e72016-04-16 01:55:402376 jobs_to_abort.push_back(base::WrapUnique(job));
[email protected]b3601bc22012-02-21 21:23:202377 jobs_.erase(it++);
[email protected]0f292de02012-02-01 22:28:202378 } else {
[email protected]b3601bc22012-02-21 21:23:202379 DCHECK(job->is_queued());
2380 ++it;
[email protected]0f292de02012-02-01 22:28:202381 }
[email protected]ef4c40c2010-09-01 14:42:032382 }
[email protected]b3601bc22012-02-21 21:23:202383
[email protected]daae1322013-09-05 18:26:502384 // Pause the dispatcher so it won't start any new dispatcher jobs while
2385 // aborting the old ones. This is needed so that it won't start the second
2386 // DnsTransaction for a job in |jobs_to_abort| if the DnsConfig just became
2387 // invalid.
[email protected]106ccd2c2014-06-17 09:21:002388 PrioritizedDispatcher::Limits limits = dispatcher_->GetLimits();
2389 dispatcher_->SetLimits(
[email protected]daae1322013-09-05 18:26:502390 PrioritizedDispatcher::Limits(limits.reserved_slots.size(), 0));
[email protected]70c04ab2013-08-22 16:05:122391
[email protected]57a48d32012-03-03 00:04:552392 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072393 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]57a48d32012-03-03 00:04:552394
[email protected]16ee26d2012-03-08 03:34:352395 // Then Abort them.
[email protected]11fbca0b2013-06-02 23:37:212396 for (size_t i = 0; self.get() && i < jobs_to_abort.size(); ++i) {
[email protected]57a48d32012-03-03 00:04:552397 jobs_to_abort[i]->Abort();
olli.raulaa21e9eb72015-12-17 08:18:112398 ignore_result(jobs_to_abort[i].release());
[email protected]b3601bc22012-02-21 21:23:202399 }
[email protected]daae1322013-09-05 18:26:502400
2401 if (self)
[email protected]106ccd2c2014-06-17 09:21:002402 dispatcher_->SetLimits(limits);
[email protected]daae1322013-09-05 18:26:502403}
2404
2405void HostResolverImpl::AbortDnsTasks() {
2406 // Pause the dispatcher so it won't start any new dispatcher jobs while
2407 // aborting the old ones. This is needed so that it won't start the second
2408 // DnsTransaction for a job if the DnsConfig just changed.
[email protected]106ccd2c2014-06-17 09:21:002409 PrioritizedDispatcher::Limits limits = dispatcher_->GetLimits();
2410 dispatcher_->SetLimits(
[email protected]daae1322013-09-05 18:26:502411 PrioritizedDispatcher::Limits(limits.reserved_slots.size(), 0));
2412
2413 for (JobMap::iterator it = jobs_.begin(); it != jobs_.end(); ++it)
2414 it->second->AbortDnsTask();
[email protected]106ccd2c2014-06-17 09:21:002415 dispatcher_->SetLimits(limits);
[email protected]ef4c40c2010-09-01 14:42:032416}
2417
[email protected]78eac2a2012-03-14 19:09:272418void HostResolverImpl::TryServingAllJobsFromHosts() {
2419 if (!HaveDnsConfig())
2420 return;
2421
2422 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2423 // http://crbug.com/117655
2424
2425 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072426 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]78eac2a2012-03-14 19:09:272427
[email protected]11fbca0b2013-06-02 23:37:212428 for (JobMap::iterator it = jobs_.begin(); self.get() && it != jobs_.end();) {
[email protected]78eac2a2012-03-14 19:09:272429 Job* job = it->second;
2430 ++it;
2431 // This could remove |job| from |jobs_|, but iterator will remain valid.
2432 job->ServeFromHosts();
2433 }
2434}
2435
[email protected]be1a48b2011-01-20 00:12:132436void HostResolverImpl::OnIPAddressChanged() {
[email protected]62e86ba2013-01-29 18:59:162437 resolved_known_ipv6_hostname_ = false;
sergeyub8cdc212015-05-14 18:50:372438 last_ipv6_probe_time_ = base::TimeTicks();
[email protected]12faa4c2012-11-06 04:44:182439 // Abandon all ProbeJobs.
2440 probe_weak_ptr_factory_.InvalidateWeakPtrs();
[email protected]be1a48b2011-01-20 00:12:132441 if (cache_.get())
2442 cache_->clear();
[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_) {
2472 net_log_->AddGlobalEntry(
2473 NetLog::TYPE_DNS_CONFIG_CHANGED,
[email protected]cd565142012-06-12 16:21:452474 base::Bind(&NetLogDnsConfigCallback, &dns_config));
[email protected]b4481b222012-03-16 17:13:112475 }
2476
[email protected]01b3b9d2012-08-13 16:18:142477 // TODO(szym): Remove once http://crbug.com/137914 is resolved.
[email protected]d7b9a2b2012-05-31 22:31:192478 received_dns_config_ = dns_config.IsValid();
[email protected]c9fa8f312013-09-17 12:24:522479 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
2480 use_local_ipv6_ = !dns_config.IsValid() || dns_config.use_local_ipv6;
[email protected]78eac2a2012-03-14 19:09:272481
[email protected]a8883e452012-11-17 05:58:062482 num_dns_failures_ = 0;
2483
[email protected]01b3b9d2012-08-13 16:18:142484 // We want a new DnsSession in place, before we Abort running Jobs, so that
2485 // the newly started jobs use the new config.
[email protected]f0f602bd2012-11-15 18:01:022486 if (dns_client_.get()) {
[email protected]d7b9a2b2012-05-31 22:31:192487 dns_client_->SetConfig(dns_config);
pauljensen101ed372015-04-17 00:11:422488 if (dns_client_->GetConfig()) {
[email protected]f0f602bd2012-11-15 18:01:022489 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
pauljensen101ed372015-04-17 00:11:422490 // If we just switched DnsClients, restart jobs using new resolver.
2491 // TODO(pauljensen): Is this necessary?
2492 config_changed = true;
2493 }
[email protected]f0f602bd2012-11-15 18:01:022494 }
[email protected]01b3b9d2012-08-13 16:18:142495
pauljensen101ed372015-04-17 00:11:422496 if (config_changed) {
2497 // If the DNS server has changed, existing cached info could be wrong so we
2498 // have to drop our internal cache :( Note that OS level DNS caches, such
2499 // as NSCD's cache should be dropped automatically by the OS when
2500 // resolv.conf changes so we don't need to do anything to clear that cache.
2501 if (cache_.get())
2502 cache_->clear();
[email protected]01b3b9d2012-08-13 16:18:142503
pauljensen101ed372015-04-17 00:11:422504 // Life check to bail once |this| is deleted.
2505 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]f0f602bd2012-11-15 18:01:022506
pauljensen101ed372015-04-17 00:11:422507 // Existing jobs will have been sent to the original server so they need to
2508 // be aborted.
2509 AbortAllInProgressJobs();
[email protected]01b3b9d2012-08-13 16:18:142510
pauljensen101ed372015-04-17 00:11:422511 // |this| may be deleted inside AbortAllInProgressJobs().
2512 if (self.get())
2513 TryServingAllJobsFromHosts();
2514 }
[email protected]78eac2a2012-03-14 19:09:272515}
2516
2517bool HostResolverImpl::HaveDnsConfig() const {
[email protected]32b1dbcf2013-01-26 03:48:252518 // Use DnsClient only if it's fully configured and there is no override by
2519 // ScopedDefaultHostResolverProc.
2520 // The alternative is to use NetworkChangeNotifier to override DnsConfig,
2521 // but that would introduce construction order requirements for NCN and SDHRP.
[email protected]90499482013-06-01 00:39:502522 return (dns_client_.get() != NULL) && (dns_client_->GetConfig() != NULL) &&
2523 !(proc_params_.resolver_proc.get() == NULL &&
[email protected]32b1dbcf2013-01-26 03:48:252524 HostResolverProc::GetDefault() != NULL);
[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
danakj22f90e72016-04-16 01:55:402549void HostResolverImpl::SetDnsClient(std::unique_ptr<DnsClient> dns_client) {
[email protected]daae1322013-09-05 18:26:502550 // DnsClient and config must be updated before aborting DnsTasks, since doing
2551 // so may start new jobs.
dchengc7eeda422015-12-26 03:56:482552 dns_client_ = std::move(dns_client);
[email protected]daae1322013-09-05 18:26:502553 if (dns_client_ && !dns_client_->GetConfig() &&
2554 num_dns_failures_ < kMaximumDnsFailures) {
2555 DnsConfig dns_config;
2556 NetworkChangeNotifier::GetDnsConfig(&dns_config);
2557 dns_client_->SetConfig(dns_config);
2558 num_dns_failures_ = 0;
2559 if (dns_client_->GetConfig())
2560 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
[email protected]a8883e452012-11-17 05:58:062561 }
[email protected]daae1322013-09-05 18:26:502562
2563 AbortDnsTasks();
[email protected]a8883e452012-11-17 05:58:062564}
2565
[email protected]b59ff372009-07-15 22:04:322566} // namespace net