blob: 9e6fa68d26c8d87649c1bf5172be40d7bd31a1f7 [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
[email protected]c54a8912012-10-22 22:09:43497} // namespace
[email protected]0f292de02012-02-01 22:28:20498
499//-----------------------------------------------------------------------------
500
tfarina9ed7f8c52016-02-19 17:50:18501bool ResolveLocalHostname(base::StringPiece host,
502 uint16_t port,
503 AddressList* address_list) {
tfarina9ed7f8c52016-02-19 17:50:18504 address_list->clear();
505
506 bool is_local6;
507 if (!IsLocalHostname(host, &is_local6))
508 return false;
509
martijna23c8962016-03-04 18:18:51510 address_list->push_back(IPEndPoint(IPAddress::IPv6Localhost(), port));
tfarina9ed7f8c52016-02-19 17:50:18511 if (!is_local6) {
martijna23c8962016-03-04 18:18:51512 address_list->push_back(IPEndPoint(IPAddress::IPv4Localhost(), port));
tfarina9ed7f8c52016-02-19 17:50:18513 }
514
515 return true;
516}
517
[email protected]daae1322013-09-05 18:26:50518const unsigned HostResolverImpl::kMaximumDnsFailures = 16;
519
[email protected]0f292de02012-02-01 22:28:20520// Holds the data for a request that could not be completed synchronously.
521// It is owned by a Job. Canceled Requests are only marked as canceled rather
522// than removed from the Job's |requests_| list.
[email protected]b59ff372009-07-15 22:04:32523class HostResolverImpl::Request {
524 public:
[email protected]ee094b82010-08-24 15:55:51525 Request(const BoundNetLog& source_net_log,
[email protected]54e13772009-08-14 03:01:09526 const RequestInfo& info,
[email protected]5109c1952013-08-20 18:44:10527 RequestPriority priority,
[email protected]aa22b242011-11-16 18:58:29528 const CompletionCallback& callback,
[email protected]b59ff372009-07-15 22:04:32529 AddressList* addresses)
[email protected]ee094b82010-08-24 15:55:51530 : source_net_log_(source_net_log),
[email protected]54e13772009-08-14 03:01:09531 info_(info),
[email protected]5109c1952013-08-20 18:44:10532 priority_(priority),
[email protected]54e13772009-08-14 03:01:09533 job_(NULL),
534 callback_(callback),
[email protected]51b9a6b2012-06-25 21:50:29535 addresses_(addresses),
[email protected]5109c1952013-08-20 18:44:10536 request_time_(base::TimeTicks::Now()) {}
[email protected]b59ff372009-07-15 22:04:32537
[email protected]0f292de02012-02-01 22:28:20538 // Mark the request as canceled.
539 void MarkAsCanceled() {
[email protected]b59ff372009-07-15 22:04:32540 job_ = NULL;
[email protected]b59ff372009-07-15 22:04:32541 addresses_ = NULL;
[email protected]aa22b242011-11-16 18:58:29542 callback_.Reset();
[email protected]b59ff372009-07-15 22:04:32543 }
544
[email protected]0f292de02012-02-01 22:28:20545 bool was_canceled() const {
[email protected]aa22b242011-11-16 18:58:29546 return callback_.is_null();
[email protected]b59ff372009-07-15 22:04:32547 }
548
549 void set_job(Job* job) {
[email protected]0f292de02012-02-01 22:28:20550 DCHECK(job);
[email protected]b59ff372009-07-15 22:04:32551 // Identify which job the request is waiting on.
552 job_ = job;
553 }
554
[email protected]0f292de02012-02-01 22:28:20555 // Prepare final AddressList and call completion callback.
[email protected]b3601bc22012-02-21 21:23:20556 void OnComplete(int error, const AddressList& addr_list) {
[email protected]51b9a6b2012-06-25 21:50:29557 DCHECK(!was_canceled());
[email protected]895123222012-10-25 15:21:17558 if (error == OK)
559 *addresses_ = EnsurePortOnAddressList(addr_list, info_.port());
[email protected]aa22b242011-11-16 18:58:29560 CompletionCallback callback = callback_;
[email protected]0f292de02012-02-01 22:28:20561 MarkAsCanceled();
[email protected]aa22b242011-11-16 18:58:29562 callback.Run(error);
[email protected]b59ff372009-07-15 22:04:32563 }
564
[email protected]b59ff372009-07-15 22:04:32565 Job* job() const {
566 return job_;
567 }
568
[email protected]0f292de02012-02-01 22:28:20569 // NetLog for the source, passed in HostResolver::Resolve.
[email protected]ee094b82010-08-24 15:55:51570 const BoundNetLog& source_net_log() {
571 return source_net_log_;
572 }
573
[email protected]b59ff372009-07-15 22:04:32574 const RequestInfo& info() const {
575 return info_;
576 }
577
[email protected]5109c1952013-08-20 18:44:10578 RequestPriority priority() const { return priority_; }
juliatuttlec53b19a72016-05-05 13:51:31579 void set_priority(RequestPriority priority) { priority_ = priority; }
[email protected]5109c1952013-08-20 18:44:10580
581 base::TimeTicks request_time() const { return request_time_; }
[email protected]51b9a6b2012-06-25 21:50:29582
[email protected]b59ff372009-07-15 22:04:32583 private:
xunjieli26f90452014-11-10 16:23:02584 const BoundNetLog source_net_log_;
[email protected]54e13772009-08-14 03:01:09585
[email protected]b59ff372009-07-15 22:04:32586 // The request info that started the request.
[email protected]5109c1952013-08-20 18:44:10587 const RequestInfo info_;
588
juliatuttlec53b19a72016-05-05 13:51:31589 RequestPriority priority_;
[email protected]b59ff372009-07-15 22:04:32590
[email protected]0f292de02012-02-01 22:28:20591 // The resolve job that this request is dependent on.
[email protected]b59ff372009-07-15 22:04:32592 Job* job_;
593
594 // The user's callback to invoke when the request completes.
[email protected]aa22b242011-11-16 18:58:29595 CompletionCallback callback_;
[email protected]b59ff372009-07-15 22:04:32596
597 // The address list to save result into.
598 AddressList* addresses_;
599
[email protected]51b9a6b2012-06-25 21:50:29600 const base::TimeTicks request_time_;
601
[email protected]b59ff372009-07-15 22:04:32602 DISALLOW_COPY_AND_ASSIGN(Request);
603};
604
[email protected]1e9bbd22010-10-15 16:42:45605//------------------------------------------------------------------------------
606
mmenke91c17162016-06-02 16:03:23607// Calls HostResolverProc using a worker task runner. Performs retries if
608// necessary.
[email protected]0f292de02012-02-01 22:28:20609//
610// Whenever we try to resolve the host, we post a delayed task to check if host
611// resolution (OnLookupComplete) is completed or not. If the original attempt
612// hasn't completed, then we start another attempt for host resolution. We take
613// the results from the first attempt that finishes and ignore the results from
614// all other attempts.
615//
616// TODO(szym): Move to separate source file for testing and mocking.
617//
618class HostResolverImpl::ProcTask
619 : public base::RefCountedThreadSafe<HostResolverImpl::ProcTask> {
[email protected]b59ff372009-07-15 22:04:32620 public:
[email protected]b3601bc22012-02-21 21:23:20621 typedef base::Callback<void(int net_error,
622 const AddressList& addr_list)> Callback;
[email protected]b59ff372009-07-15 22:04:32623
[email protected]0f292de02012-02-01 22:28:20624 ProcTask(const Key& key,
625 const ProcTaskParams& params,
626 const Callback& callback,
mmenke91c17162016-06-02 16:03:23627 scoped_refptr<base::TaskRunner> worker_task_runner,
[email protected]0f292de02012-02-01 22:28:20628 const BoundNetLog& job_net_log)
629 : key_(key),
630 params_(params),
631 callback_(callback),
mmenke91c17162016-06-02 16:03:23632 worker_task_runner_(std::move(worker_task_runner)),
633 network_task_runner_(base::ThreadTaskRunnerHandle::Get()),
[email protected]0f292de02012-02-01 22:28:20634 attempt_number_(0),
635 completed_attempt_number_(0),
636 completed_attempt_error_(ERR_UNEXPECTED),
637 had_non_speculative_request_(false),
[email protected]b3601bc22012-02-21 21:23:20638 net_log_(job_net_log) {
[email protected]90499482013-06-01 00:39:50639 if (!params_.resolver_proc.get())
[email protected]0f292de02012-02-01 22:28:20640 params_.resolver_proc = HostResolverProc::GetDefault();
641 // If default is unset, use the system proc.
[email protected]90499482013-06-01 00:39:50642 if (!params_.resolver_proc.get())
[email protected]1ee9afa12013-04-16 14:18:06643 params_.resolver_proc = new SystemHostResolverProc();
[email protected]b59ff372009-07-15 22:04:32644 }
645
[email protected]b59ff372009-07-15 22:04:32646 void Start() {
mmenke91c17162016-06-02 16:03:23647 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]4da911f2012-06-14 19:45:20648 net_log_.BeginEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK);
[email protected]189163e2011-05-11 01:48:54649 StartLookupAttempt();
650 }
[email protected]252b699b2010-02-05 21:38:06651
[email protected]0f292de02012-02-01 22:28:20652 // Cancels this ProcTask. It will be orphaned. Any outstanding resolve
mmenke91c17162016-06-02 16:03:23653 // attempts running on worker thread will continue running. Only once all the
[email protected]0f292de02012-02-01 22:28:20654 // attempts complete will the final reference to this ProcTask be released.
655 void Cancel() {
mmenke91c17162016-06-02 16:03:23656 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20657
[email protected]0adcb2b2012-08-15 21:30:46658 if (was_canceled() || was_completed())
[email protected]0f292de02012-02-01 22:28:20659 return;
660
[email protected]0f292de02012-02-01 22:28:20661 callback_.Reset();
[email protected]4da911f2012-06-14 19:45:20662 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK);
[email protected]0f292de02012-02-01 22:28:20663 }
664
665 void set_had_non_speculative_request() {
mmenke91c17162016-06-02 16:03:23666 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20667 had_non_speculative_request_ = true;
668 }
669
670 bool was_canceled() const {
mmenke91c17162016-06-02 16:03:23671 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20672 return callback_.is_null();
673 }
674
675 bool was_completed() const {
mmenke91c17162016-06-02 16:03:23676 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20677 return completed_attempt_number_ > 0;
678 }
679
680 private:
[email protected]a9813302012-04-28 09:29:28681 friend class base::RefCountedThreadSafe<ProcTask>;
682 ~ProcTask() {}
683
[email protected]189163e2011-05-11 01:48:54684 void StartLookupAttempt() {
mmenke91c17162016-06-02 16:03:23685 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54686 base::TimeTicks start_time = base::TimeTicks::Now();
687 ++attempt_number_;
688 // Dispatch the lookup attempt to a worker thread.
mmenke91c17162016-06-02 16:03:23689 if (!worker_task_runner_->PostTask(
690 FROM_HERE, base::Bind(&ProcTask::DoLookup, this, start_time,
691 attempt_number_))) {
[email protected]b59ff372009-07-15 22:04:32692 NOTREACHED();
693
mmenke91c17162016-06-02 16:03:23694 // Since this method may have been called from Resolve(), can't just call
695 // OnLookupComplete(). Instead, must wait until Resolve() has returned
696 // (IO_PENDING).
697 network_task_runner_->PostTask(
698 FROM_HERE,
699 base::Bind(&ProcTask::OnLookupComplete, this, AddressList(),
700 start_time, attempt_number_, ERR_UNEXPECTED, 0));
[email protected]189163e2011-05-11 01:48:54701 return;
[email protected]b59ff372009-07-15 22:04:32702 }
[email protected]13024882011-05-18 23:19:16703
tfarina5e24b242015-10-27 13:11:28704 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_ATTEMPT_STARTED,
705 NetLog::IntCallback("attempt_number", attempt_number_));
[email protected]13024882011-05-18 23:19:16706
mmenke91c17162016-06-02 16:03:23707 // If the results aren't received within a given time, RetryIfNotComplete
708 // will start a new attempt if none of the outstanding attempts have
709 // completed yet.
[email protected]0f292de02012-02-01 22:28:20710 if (attempt_number_ <= params_.max_retry_attempts) {
mmenke91c17162016-06-02 16:03:23711 network_task_runner_->PostDelayedTask(
712 FROM_HERE, base::Bind(&ProcTask::RetryIfNotComplete, this),
[email protected]7e560102012-03-08 20:58:42713 params_.unresponsive_delay);
[email protected]06ef6d92011-05-19 04:24:58714 }
[email protected]b59ff372009-07-15 22:04:32715 }
716
mmenke91c17162016-06-02 16:03:23717 // WARNING: In production, this code runs on a worker pool. The shutdown code
718 // cannot wait for it to finish, so this code must be very careful about using
719 // other objects (like MessageLoops, Singletons, etc). During shutdown these
720 // objects may no longer exist. Multiple DoLookups() could be running in
721 // parallel, so any state inside of |this| must not mutate .
[email protected]189163e2011-05-11 01:48:54722 void DoLookup(const base::TimeTicks& start_time,
Avi Drissman13fc8932015-12-20 04:40:46723 const uint32_t attempt_number) {
[email protected]189163e2011-05-11 01:48:54724 AddressList results;
725 int os_error = 0;
mmenke91c17162016-06-02 16:03:23726 // Running on a worker task runner.
[email protected]0f292de02012-02-01 22:28:20727 int error = params_.resolver_proc->Resolve(key_.hostname,
728 key_.address_family,
729 key_.host_resolver_flags,
730 &results,
731 &os_error);
[email protected]b59ff372009-07-15 22:04:32732
eroman91dd3602015-03-26 03:46:33733 // Fail the resolution if the result contains 127.0.53.53. See the comment
734 // block of kIcanNameCollisionIp for details on why.
735 for (const auto& it : results) {
martijna23c8962016-03-04 18:18:51736 const IPAddress& cur = it.address();
737 if (cur.IsIPv4() && IPAddressStartsWith(cur, kIcanNameCollisionIp)) {
eroman91dd3602015-03-26 03:46:33738 error = ERR_ICANN_NAME_COLLISION;
739 break;
740 }
741 }
742
mmenke91c17162016-06-02 16:03:23743 network_task_runner_->PostTask(
744 FROM_HERE, base::Bind(&ProcTask::OnLookupComplete, this, results,
745 start_time, attempt_number, error, os_error));
[email protected]189163e2011-05-11 01:48:54746 }
747
mmenke91c17162016-06-02 16:03:23748 // Makes next attempt if DoLookup() has not finished.
[email protected]0f292de02012-02-01 22:28:20749 void RetryIfNotComplete() {
mmenke91c17162016-06-02 16:03:23750 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54751
[email protected]0f292de02012-02-01 22:28:20752 if (was_completed() || was_canceled())
[email protected]189163e2011-05-11 01:48:54753 return;
754
[email protected]0f292de02012-02-01 22:28:20755 params_.unresponsive_delay *= params_.retry_factor;
[email protected]189163e2011-05-11 01:48:54756 StartLookupAttempt();
[email protected]b59ff372009-07-15 22:04:32757 }
758
anujk.sharma7c907f02015-05-29 02:55:44759 // Callback for when DoLookup() completes (runs on task runner thread).
[email protected]189163e2011-05-11 01:48:54760 void OnLookupComplete(const AddressList& results,
761 const base::TimeTicks& start_time,
Avi Drissman13fc8932015-12-20 04:40:46762 const uint32_t attempt_number,
[email protected]189163e2011-05-11 01:48:54763 int error,
764 const int os_error) {
ssid6d6b40102016-04-05 18:59:56765 TRACE_EVENT0("net", "ProcTask::OnLookupComplete");
mmenke91c17162016-06-02 16:03:23766 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]49b70b222013-05-07 21:24:23767 // If results are empty, we should return an error.
768 bool empty_list_on_ok = (error == OK && results.empty());
769 UMA_HISTOGRAM_BOOLEAN("DNS.EmptyAddressListAndNoError", empty_list_on_ok);
770 if (empty_list_on_ok)
771 error = ERR_NAME_NOT_RESOLVED;
[email protected]189163e2011-05-11 01:48:54772
773 bool was_retry_attempt = attempt_number > 1;
774
[email protected]2d3b7762010-10-09 00:35:47775 // Ideally the following code would be part of host_resolver_proc.cc,
[email protected]b3601bc22012-02-21 21:23:20776 // however it isn't safe to call NetworkChangeNotifier from worker threads.
mmenke91c17162016-06-02 16:03:23777 // So do it here on the IO thread instead.
[email protected]189163e2011-05-11 01:48:54778 if (error != OK && NetworkChangeNotifier::IsOffline())
779 error = ERR_INTERNET_DISCONNECTED;
[email protected]2d3b7762010-10-09 00:35:47780
[email protected]b3601bc22012-02-21 21:23:20781 // If this is the first attempt that is finishing later, then record data
782 // for the first attempt. Won't contaminate with retry attempt's data.
[email protected]189163e2011-05-11 01:48:54783 if (!was_retry_attempt)
784 RecordPerformanceHistograms(start_time, error, os_error);
785
786 RecordAttemptHistograms(start_time, attempt_number, error, os_error);
[email protected]f2d8c4212010-02-02 00:56:35787
[email protected]0f292de02012-02-01 22:28:20788 if (was_canceled())
[email protected]b59ff372009-07-15 22:04:32789 return;
790
[email protected]cd565142012-06-12 16:21:45791 NetLog::ParametersCallback net_log_callback;
[email protected]0f292de02012-02-01 22:28:20792 if (error != OK) {
[email protected]cd565142012-06-12 16:21:45793 net_log_callback = base::Bind(&NetLogProcTaskFailedCallback,
794 attempt_number,
795 error,
796 os_error);
[email protected]0f292de02012-02-01 22:28:20797 } else {
tfarina5e24b242015-10-27 13:11:28798 net_log_callback = NetLog::IntCallback("attempt_number", attempt_number);
[email protected]0f292de02012-02-01 22:28:20799 }
[email protected]cd565142012-06-12 16:21:45800 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_ATTEMPT_FINISHED,
801 net_log_callback);
[email protected]0f292de02012-02-01 22:28:20802
803 if (was_completed())
804 return;
805
806 // Copy the results from the first worker thread that resolves the host.
807 results_ = results;
808 completed_attempt_number_ = attempt_number;
809 completed_attempt_error_ = error;
810
[email protected]e87b8b512011-06-14 22:12:52811 if (was_retry_attempt) {
812 // If retry attempt finishes before 1st attempt, then get stats on how
813 // much time is saved by having spawned an extra attempt.
814 retry_attempt_finished_time_ = base::TimeTicks::Now();
815 }
816
[email protected]189163e2011-05-11 01:48:54817 if (error != OK) {
[email protected]cd565142012-06-12 16:21:45818 net_log_callback = base::Bind(&NetLogProcTaskFailedCallback,
819 0, error, os_error);
[email protected]ee094b82010-08-24 15:55:51820 } else {
[email protected]cd565142012-06-12 16:21:45821 net_log_callback = results_.CreateNetLogCallback();
[email protected]ee094b82010-08-24 15:55:51822 }
[email protected]cd565142012-06-12 16:21:45823 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK,
824 net_log_callback);
[email protected]ee094b82010-08-24 15:55:51825
[email protected]b3601bc22012-02-21 21:23:20826 callback_.Run(error, results_);
[email protected]b59ff372009-07-15 22:04:32827 }
828
[email protected]189163e2011-05-11 01:48:54829 void RecordPerformanceHistograms(const base::TimeTicks& start_time,
830 const int error,
831 const int os_error) const {
mmenke91c17162016-06-02 16:03:23832 DCHECK(network_task_runner_->BelongsToCurrentThread());
asvitkinec0fb8022014-08-26 04:39:35833 enum Category { // Used in UMA_HISTOGRAM_ENUMERATION.
[email protected]1e9bbd22010-10-15 16:42:45834 RESOLVE_SUCCESS,
835 RESOLVE_FAIL,
836 RESOLVE_SPECULATIVE_SUCCESS,
837 RESOLVE_SPECULATIVE_FAIL,
838 RESOLVE_MAX, // Bounding value.
839 };
840 int category = RESOLVE_MAX; // Illegal value for later DCHECK only.
841
[email protected]189163e2011-05-11 01:48:54842 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
843 if (error == OK) {
[email protected]1e9bbd22010-10-15 16:42:45844 if (had_non_speculative_request_) {
845 category = RESOLVE_SUCCESS;
846 DNS_HISTOGRAM("DNS.ResolveSuccess", duration);
847 } else {
848 category = RESOLVE_SPECULATIVE_SUCCESS;
849 DNS_HISTOGRAM("DNS.ResolveSpeculativeSuccess", duration);
850 }
[email protected]7e96d792011-06-10 17:08:23851
[email protected]78eac2a2012-03-14 19:09:27852 // Log DNS lookups based on |address_family|. This will help us determine
[email protected]7e96d792011-06-10 17:08:23853 // if IPv4 or IPv4/6 lookups are faster or slower.
854 switch(key_.address_family) {
855 case ADDRESS_FAMILY_IPV4:
856 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_IPV4", duration);
857 break;
858 case ADDRESS_FAMILY_IPV6:
859 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_IPV6", duration);
860 break;
861 case ADDRESS_FAMILY_UNSPECIFIED:
862 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_UNSPEC", duration);
863 break;
864 }
[email protected]1e9bbd22010-10-15 16:42:45865 } else {
866 if (had_non_speculative_request_) {
867 category = RESOLVE_FAIL;
868 DNS_HISTOGRAM("DNS.ResolveFail", duration);
869 } else {
870 category = RESOLVE_SPECULATIVE_FAIL;
871 DNS_HISTOGRAM("DNS.ResolveSpeculativeFail", duration);
872 }
[email protected]78eac2a2012-03-14 19:09:27873 // Log DNS lookups based on |address_family|. This will help us determine
[email protected]7e96d792011-06-10 17:08:23874 // if IPv4 or IPv4/6 lookups are faster or slower.
875 switch(key_.address_family) {
876 case ADDRESS_FAMILY_IPV4:
877 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_IPV4", duration);
878 break;
879 case ADDRESS_FAMILY_IPV6:
880 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_IPV6", duration);
881 break;
882 case ADDRESS_FAMILY_UNSPECIFIED:
883 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_UNSPEC", duration);
884 break;
885 }
[email protected]c833e322010-10-16 23:51:36886 UMA_HISTOGRAM_CUSTOM_ENUMERATION(kOSErrorsForGetAddrinfoHistogramName,
[email protected]189163e2011-05-11 01:48:54887 std::abs(os_error),
[email protected]1e9bbd22010-10-15 16:42:45888 GetAllGetAddrinfoOSErrors());
889 }
[email protected]051b6ab2010-10-18 16:50:46890 DCHECK_LT(category, static_cast<int>(RESOLVE_MAX)); // Be sure it was set.
[email protected]1e9bbd22010-10-15 16:42:45891
892 UMA_HISTOGRAM_ENUMERATION("DNS.ResolveCategory", category, RESOLVE_MAX);
[email protected]1e9bbd22010-10-15 16:42:45893 }
894
[email protected]189163e2011-05-11 01:48:54895 void RecordAttemptHistograms(const base::TimeTicks& start_time,
Avi Drissman13fc8932015-12-20 04:40:46896 const uint32_t attempt_number,
[email protected]189163e2011-05-11 01:48:54897 const int error,
898 const int os_error) const {
mmenke91c17162016-06-02 16:03:23899 DCHECK(network_task_runner_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54900 bool first_attempt_to_complete =
901 completed_attempt_number_ == attempt_number;
[email protected]e87b8b512011-06-14 22:12:52902 bool is_first_attempt = (attempt_number == 1);
[email protected]1e9bbd22010-10-15 16:42:45903
[email protected]189163e2011-05-11 01:48:54904 if (first_attempt_to_complete) {
905 // If this was first attempt to complete, then record the resolution
906 // status of the attempt.
907 if (completed_attempt_error_ == OK) {
908 UMA_HISTOGRAM_ENUMERATION(
909 "DNS.AttemptFirstSuccess", attempt_number, 100);
910 } else {
911 UMA_HISTOGRAM_ENUMERATION(
912 "DNS.AttemptFirstFailure", attempt_number, 100);
913 }
914 }
915
916 if (error == OK)
917 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptSuccess", attempt_number, 100);
918 else
919 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptFailure", attempt_number, 100);
920
[email protected]e87b8b512011-06-14 22:12:52921 // If first attempt didn't finish before retry attempt, then calculate stats
922 // on how much time is saved by having spawned an extra attempt.
[email protected]0f292de02012-02-01 22:28:20923 if (!first_attempt_to_complete && is_first_attempt && !was_canceled()) {
[email protected]e87b8b512011-06-14 22:12:52924 DNS_HISTOGRAM("DNS.AttemptTimeSavedByRetry",
925 base::TimeTicks::Now() - retry_attempt_finished_time_);
926 }
927
[email protected]0f292de02012-02-01 22:28:20928 if (was_canceled() || !first_attempt_to_complete) {
[email protected]189163e2011-05-11 01:48:54929 // Count those attempts which completed after the job was already canceled
930 // OR after the job was already completed by an earlier attempt (so in
931 // effect).
932 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptDiscarded", attempt_number, 100);
933
[email protected]0f292de02012-02-01 22:28:20934 // Record if job is canceled.
935 if (was_canceled())
[email protected]189163e2011-05-11 01:48:54936 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptCancelled", attempt_number, 100);
937 }
938
939 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
940 if (error == OK)
941 DNS_HISTOGRAM("DNS.AttemptSuccessDuration", duration);
942 else
943 DNS_HISTOGRAM("DNS.AttemptFailDuration", duration);
944 }
[email protected]1e9bbd22010-10-15 16:42:45945
anujk.sharma7c907f02015-05-29 02:55:44946 // Set on the task runner thread, read on the worker thread.
[email protected]123ab1e32009-10-21 19:12:57947 Key key_;
[email protected]b59ff372009-07-15 22:04:32948
[email protected]0f292de02012-02-01 22:28:20949 // Holds an owning reference to the HostResolverProc that we are going to use.
[email protected]b59ff372009-07-15 22:04:32950 // This may not be the current resolver procedure by the time we call
951 // ResolveAddrInfo, but that's OK... we'll use it anyways, and the owning
952 // reference ensures that it remains valid until we are done.
[email protected]0f292de02012-02-01 22:28:20953 ProcTaskParams params_;
[email protected]b59ff372009-07-15 22:04:32954
[email protected]0f292de02012-02-01 22:28:20955 // The listener to the results of this ProcTask.
956 Callback callback_;
957
mmenke91c17162016-06-02 16:03:23958 // Task runner for the call to the HostResolverProc.
959 scoped_refptr<base::TaskRunner> worker_task_runner_;
960
961 // Used to post events onto the network thread.
962 scoped_refptr<base::SingleThreadTaskRunner> network_task_runner_;
[email protected]189163e2011-05-11 01:48:54963
964 // Keeps track of the number of attempts we have made so far to resolve the
965 // host. Whenever we start an attempt to resolve the host, we increase this
966 // number.
Avi Drissman13fc8932015-12-20 04:40:46967 uint32_t attempt_number_;
[email protected]189163e2011-05-11 01:48:54968
969 // The index of the attempt which finished first (or 0 if the job is still in
970 // progress).
Avi Drissman13fc8932015-12-20 04:40:46971 uint32_t completed_attempt_number_;
[email protected]189163e2011-05-11 01:48:54972
973 // The result (a net error code) from the first attempt to complete.
974 int completed_attempt_error_;
[email protected]252b699b2010-02-05 21:38:06975
[email protected]e87b8b512011-06-14 22:12:52976 // The time when retry attempt was finished.
977 base::TimeTicks retry_attempt_finished_time_;
978
[email protected]252b699b2010-02-05 21:38:06979 // True if a non-speculative request was ever attached to this job
[email protected]0f292de02012-02-01 22:28:20980 // (regardless of whether or not it was later canceled.
[email protected]252b699b2010-02-05 21:38:06981 // This boolean is used for histogramming the duration of jobs used to
982 // service non-speculative requests.
983 bool had_non_speculative_request_;
984
[email protected]b59ff372009-07-15 22:04:32985 AddressList results_;
986
[email protected]ee094b82010-08-24 15:55:51987 BoundNetLog net_log_;
988
[email protected]0f292de02012-02-01 22:28:20989 DISALLOW_COPY_AND_ASSIGN(ProcTask);
[email protected]b59ff372009-07-15 22:04:32990};
991
992//-----------------------------------------------------------------------------
993
mmenke91c17162016-06-02 16:03:23994// Wraps a call to HaveOnlyLoopbackAddresses to be executed on a
995// |worker_task_runner|, as it takes 40-100ms and should not block
996// initialization.
[email protected]12faa4c2012-11-06 04:44:18997class HostResolverImpl::LoopbackProbeJob {
998 public:
mmenke91c17162016-06-02 16:03:23999 LoopbackProbeJob(const base::WeakPtr<HostResolverImpl>& resolver,
1000 base::TaskRunner* worker_task_runner)
1001 : resolver_(resolver), result_(false) {
[email protected]11fbca0b2013-06-02 23:37:211002 DCHECK(resolver.get());
mmenke91c17162016-06-02 16:03:231003
1004 // |worker_task_runner| may posts tasks to the WorkerPool, so need this to
1005 // avoid reporting worker pool leaks in tests. The WorkerPool doesn't have a
1006 // flushing API, so can't do anything about them, other than using another
1007 // task runner.
1008 // http://crbug.com/248513
1009 ANNOTATE_SCOPED_MEMORY_LEAK;
1010
1011 worker_task_runner->PostTaskAndReply(
[email protected]12faa4c2012-11-06 04:44:181012 FROM_HERE,
1013 base::Bind(&LoopbackProbeJob::DoProbe, base::Unretained(this)),
mmenke91c17162016-06-02 16:03:231014 base::Bind(&LoopbackProbeJob::OnProbeComplete, base::Owned(this)));
[email protected]12faa4c2012-11-06 04:44:181015 }
1016
1017 virtual ~LoopbackProbeJob() {}
1018
1019 private:
1020 // Runs on worker thread.
1021 void DoProbe() {
1022 result_ = HaveOnlyLoopbackAddresses();
1023 }
1024
1025 void OnProbeComplete() {
[email protected]11fbca0b2013-06-02 23:37:211026 if (!resolver_.get())
[email protected]12faa4c2012-11-06 04:44:181027 return;
1028 resolver_->SetHaveOnlyLoopbackAddresses(result_);
1029 }
1030
anujk.sharma7c907f02015-05-29 02:55:441031 // Used/set only on task runner thread.
[email protected]12faa4c2012-11-06 04:44:181032 base::WeakPtr<HostResolverImpl> resolver_;
1033
1034 bool result_;
1035
1036 DISALLOW_COPY_AND_ASSIGN(LoopbackProbeJob);
1037};
1038
[email protected]0f8f1b432010-03-16 19:06:031039//-----------------------------------------------------------------------------
1040
[email protected]b3601bc22012-02-21 21:23:201041// Resolves the hostname using DnsTransaction.
1042// TODO(szym): This could be moved to separate source file as well.
[email protected]0adcb2b2012-08-15 21:30:461043class HostResolverImpl::DnsTask : public base::SupportsWeakPtr<DnsTask> {
[email protected]b3601bc22012-02-21 21:23:201044 public:
[email protected]daae1322013-09-05 18:26:501045 class Delegate {
1046 public:
1047 virtual void OnDnsTaskComplete(base::TimeTicks start_time,
1048 int net_error,
1049 const AddressList& addr_list,
1050 base::TimeDelta ttl) = 0;
1051
1052 // Called when the first of two jobs succeeds. If the first completed
1053 // transaction fails, this is not called. Also not called when the DnsTask
1054 // only needs to run one transaction.
1055 virtual void OnFirstDnsTransactionComplete() = 0;
1056
1057 protected:
1058 Delegate() {}
1059 virtual ~Delegate() {}
1060 };
[email protected]b3601bc22012-02-21 21:23:201061
[email protected]0adcb2b2012-08-15 21:30:461062 DnsTask(DnsClient* client,
[email protected]b3601bc22012-02-21 21:23:201063 const Key& key,
[email protected]daae1322013-09-05 18:26:501064 Delegate* delegate,
[email protected]b3601bc22012-02-21 21:23:201065 const BoundNetLog& job_net_log)
[email protected]0adcb2b2012-08-15 21:30:461066 : client_(client),
[email protected]daae1322013-09-05 18:26:501067 key_(key),
1068 delegate_(delegate),
1069 net_log_(job_net_log),
1070 num_completed_transactions_(0),
1071 task_start_time_(base::TimeTicks::Now()) {
[email protected]0adcb2b2012-08-15 21:30:461072 DCHECK(client);
[email protected]daae1322013-09-05 18:26:501073 DCHECK(delegate_);
[email protected]1affed62013-08-21 03:24:501074 }
1075
[email protected]daae1322013-09-05 18:26:501076 bool needs_two_transactions() const {
1077 return key_.address_family == ADDRESS_FAMILY_UNSPECIFIED;
1078 }
1079
1080 bool needs_another_transaction() const {
1081 return needs_two_transactions() && !transaction_aaaa_;
1082 }
1083
1084 void StartFirstTransaction() {
1085 DCHECK_EQ(0u, num_completed_transactions_);
[email protected]70c04ab2013-08-22 16:05:121086 net_log_.BeginEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK);
[email protected]daae1322013-09-05 18:26:501087 if (key_.address_family == ADDRESS_FAMILY_IPV6) {
1088 StartAAAA();
1089 } else {
1090 StartA();
1091 }
1092 }
1093
1094 void StartSecondTransaction() {
1095 DCHECK(needs_two_transactions());
1096 StartAAAA();
[email protected]70c04ab2013-08-22 16:05:121097 }
1098
1099 private:
[email protected]daae1322013-09-05 18:26:501100 void StartA() {
1101 DCHECK(!transaction_a_);
1102 DCHECK_NE(ADDRESS_FAMILY_IPV6, key_.address_family);
1103 transaction_a_ = CreateTransaction(ADDRESS_FAMILY_IPV4);
1104 transaction_a_->Start();
1105 }
1106
1107 void StartAAAA() {
1108 DCHECK(!transaction_aaaa_);
1109 DCHECK_NE(ADDRESS_FAMILY_IPV4, key_.address_family);
1110 transaction_aaaa_ = CreateTransaction(ADDRESS_FAMILY_IPV6);
1111 transaction_aaaa_->Start();
1112 }
1113
danakj22f90e72016-04-16 01:55:401114 std::unique_ptr<DnsTransaction> CreateTransaction(AddressFamily family) {
[email protected]daae1322013-09-05 18:26:501115 DCHECK_NE(ADDRESS_FAMILY_UNSPECIFIED, family);
1116 return client_->GetTransactionFactory()->CreateTransaction(
1117 key_.hostname,
1118 family == ADDRESS_FAMILY_IPV6 ? dns_protocol::kTypeAAAA :
1119 dns_protocol::kTypeA,
1120 base::Bind(&DnsTask::OnTransactionComplete, base::Unretained(this),
1121 base::TimeTicks::Now()),
1122 net_log_);
1123 }
1124
1125 void OnTransactionComplete(const base::TimeTicks& start_time,
[email protected]1def74c2012-03-22 20:07:001126 DnsTransaction* transaction,
[email protected]b3601bc22012-02-21 21:23:201127 int net_error,
1128 const DnsResponse* response) {
[email protected]add76532012-03-30 14:47:471129 DCHECK(transaction);
[email protected]02cd6982013-01-10 20:12:511130 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]0adcb2b2012-08-15 21:30:461131 if (net_error != OK) {
[email protected]02cd6982013-01-10 20:12:511132 DNS_HISTOGRAM("AsyncDNS.TransactionFailure", duration);
[email protected]0adcb2b2012-08-15 21:30:461133 OnFailure(net_error, DnsResponse::DNS_PARSE_OK);
1134 return;
[email protected]6c411902012-08-14 22:36:361135 }
[email protected]0adcb2b2012-08-15 21:30:461136
[email protected]02cd6982013-01-10 20:12:511137 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess", duration);
1138 switch (transaction->GetType()) {
1139 case dns_protocol::kTypeA:
1140 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess_A", duration);
1141 break;
1142 case dns_protocol::kTypeAAAA:
1143 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess_AAAA", duration);
1144 break;
1145 }
[email protected]daae1322013-09-05 18:26:501146
[email protected]0adcb2b2012-08-15 21:30:461147 AddressList addr_list;
1148 base::TimeDelta ttl;
1149 DnsResponse::Result result = response->ParseToAddressList(&addr_list, &ttl);
1150 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ParseToAddressList",
1151 result,
1152 DnsResponse::DNS_PARSE_RESULT_MAX);
1153 if (result != DnsResponse::DNS_PARSE_OK) {
1154 // Fail even if the other query succeeds.
1155 OnFailure(ERR_DNS_MALFORMED_RESPONSE, result);
1156 return;
1157 }
1158
[email protected]daae1322013-09-05 18:26:501159 ++num_completed_transactions_;
1160 if (num_completed_transactions_ == 1) {
1161 ttl_ = ttl;
[email protected]0adcb2b2012-08-15 21:30:461162 } else {
[email protected]daae1322013-09-05 18:26:501163 ttl_ = std::min(ttl_, ttl);
[email protected]0adcb2b2012-08-15 21:30:461164 }
1165
[email protected]daae1322013-09-05 18:26:501166 if (transaction->GetType() == dns_protocol::kTypeA) {
1167 DCHECK_EQ(transaction_a_.get(), transaction);
1168 // Place IPv4 addresses after IPv6.
1169 addr_list_.insert(addr_list_.end(), addr_list.begin(), addr_list.end());
1170 } else {
1171 DCHECK_EQ(transaction_aaaa_.get(), transaction);
1172 // Place IPv6 addresses before IPv4.
1173 addr_list_.insert(addr_list_.begin(), addr_list.begin(), addr_list.end());
1174 }
1175
1176 if (needs_two_transactions() && num_completed_transactions_ == 1) {
1177 // No need to repeat the suffix search.
1178 key_.hostname = transaction->GetHostname();
1179 delegate_->OnFirstDnsTransactionComplete();
1180 return;
1181 }
1182
1183 if (addr_list_.empty()) {
[email protected]70c04ab2013-08-22 16:05:121184 // TODO(szym): Don't fallback to ProcTask in this case.
1185 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
[email protected]0adcb2b2012-08-15 21:30:461186 return;
1187 }
1188
[email protected]daae1322013-09-05 18:26:501189 // If there are multiple addresses, and at least one is IPv6, need to sort
1190 // them. Note that IPv6 addresses are always put before IPv4 ones, so it's
1191 // sufficient to just check the family of the first address.
1192 if (addr_list_.size() > 1 &&
1193 addr_list_[0].GetFamily() == ADDRESS_FAMILY_IPV6) {
1194 // Sort addresses if needed. Sort could complete synchronously.
[email protected]0adcb2b2012-08-15 21:30:461195 client_->GetAddressSorter()->Sort(
[email protected]daae1322013-09-05 18:26:501196 addr_list_,
[email protected]4589a3a2012-09-20 20:57:071197 base::Bind(&DnsTask::OnSortComplete,
1198 AsWeakPtr(),
[email protected]daae1322013-09-05 18:26:501199 base::TimeTicks::Now()));
[email protected]0adcb2b2012-08-15 21:30:461200 } else {
[email protected]daae1322013-09-05 18:26:501201 OnSuccess(addr_list_);
[email protected]0adcb2b2012-08-15 21:30:461202 }
1203 }
1204
1205 void OnSortComplete(base::TimeTicks start_time,
[email protected]0adcb2b2012-08-15 21:30:461206 bool success,
1207 const AddressList& addr_list) {
1208 if (!success) {
1209 DNS_HISTOGRAM("AsyncDNS.SortFailure",
1210 base::TimeTicks::Now() - start_time);
1211 OnFailure(ERR_DNS_SORT_ERROR, DnsResponse::DNS_PARSE_OK);
1212 return;
1213 }
1214
1215 DNS_HISTOGRAM("AsyncDNS.SortSuccess",
1216 base::TimeTicks::Now() - start_time);
1217
1218 // AddressSorter prunes unusable destinations.
1219 if (addr_list.empty()) {
1220 LOG(WARNING) << "Address list empty after RFC3484 sort";
1221 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
1222 return;
1223 }
1224
[email protected]daae1322013-09-05 18:26:501225 OnSuccess(addr_list);
[email protected]0adcb2b2012-08-15 21:30:461226 }
1227
1228 void OnFailure(int net_error, DnsResponse::Result result) {
1229 DCHECK_NE(OK, net_error);
[email protected]cd565142012-06-12 16:21:451230 net_log_.EndEvent(
1231 NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK,
1232 base::Bind(&NetLogDnsTaskFailedCallback, net_error, result));
[email protected]daae1322013-09-05 18:26:501233 delegate_->OnDnsTaskComplete(task_start_time_, net_error, AddressList(),
1234 base::TimeDelta());
[email protected]b3601bc22012-02-21 21:23:201235 }
1236
[email protected]daae1322013-09-05 18:26:501237 void OnSuccess(const AddressList& addr_list) {
[email protected]0adcb2b2012-08-15 21:30:461238 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK,
1239 addr_list.CreateNetLogCallback());
[email protected]daae1322013-09-05 18:26:501240 delegate_->OnDnsTaskComplete(task_start_time_, OK, addr_list, ttl_);
[email protected]0adcb2b2012-08-15 21:30:461241 }
1242
1243 DnsClient* client_;
[email protected]daae1322013-09-05 18:26:501244 Key key_;
1245
[email protected]b3601bc22012-02-21 21:23:201246 // The listener to the results of this DnsTask.
[email protected]daae1322013-09-05 18:26:501247 Delegate* delegate_;
[email protected]b3601bc22012-02-21 21:23:201248 const BoundNetLog net_log_;
1249
danakj22f90e72016-04-16 01:55:401250 std::unique_ptr<DnsTransaction> transaction_a_;
1251 std::unique_ptr<DnsTransaction> transaction_aaaa_;
[email protected]0adcb2b2012-08-15 21:30:461252
[email protected]daae1322013-09-05 18:26:501253 unsigned num_completed_transactions_;
1254
1255 // These are updated as each transaction completes.
1256 base::TimeDelta ttl_;
1257 // IPv6 addresses must appear first in the list.
1258 AddressList addr_list_;
1259
1260 base::TimeTicks task_start_time_;
[email protected]0adcb2b2012-08-15 21:30:461261
1262 DISALLOW_COPY_AND_ASSIGN(DnsTask);
[email protected]b3601bc22012-02-21 21:23:201263};
1264
1265//-----------------------------------------------------------------------------
1266
[email protected]0f292de02012-02-01 22:28:201267// Aggregates all Requests for the same Key. Dispatched via PriorityDispatch.
[email protected]daae1322013-09-05 18:26:501268class HostResolverImpl::Job : public PrioritizedDispatcher::Job,
1269 public HostResolverImpl::DnsTask::Delegate {
[email protected]68ad3ee2010-01-30 03:45:391270 public:
[email protected]0f292de02012-02-01 22:28:201271 // Creates new job for |key| where |request_net_log| is bound to the
[email protected]16ee26d2012-03-08 03:34:351272 // request that spawned it.
[email protected]12faa4c2012-11-06 04:44:181273 Job(const base::WeakPtr<HostResolverImpl>& resolver,
[email protected]0f292de02012-02-01 22:28:201274 const Key& key,
[email protected]8c98d002012-07-18 19:02:271275 RequestPriority priority,
mmenke91c17162016-06-02 16:03:231276 scoped_refptr<base::TaskRunner> worker_task_runner,
xunjieli26f90452014-11-10 16:23:021277 const BoundNetLog& source_net_log)
[email protected]12faa4c2012-11-06 04:44:181278 : resolver_(resolver),
[email protected]0f292de02012-02-01 22:28:201279 key_(key),
[email protected]8c98d002012-07-18 19:02:271280 priority_tracker_(priority),
mmenke91c17162016-06-02 16:03:231281 worker_task_runner_(std::move(worker_task_runner)),
[email protected]0f292de02012-02-01 22:28:201282 had_non_speculative_request_(false),
[email protected]51b9a6b2012-06-25 21:50:291283 had_dns_config_(false),
[email protected]daae1322013-09-05 18:26:501284 num_occupied_job_slots_(0),
[email protected]1d932852012-06-19 19:40:331285 dns_task_error_(OK),
[email protected]51b9a6b2012-06-25 21:50:291286 creation_time_(base::TimeTicks::Now()),
1287 priority_change_time_(creation_time_),
xunjieli26f90452014-11-10 16:23:021288 net_log_(BoundNetLog::Make(source_net_log.net_log(),
[email protected]b3601bc22012-02-21 21:23:201289 NetLog::SOURCE_HOST_RESOLVER_IMPL_JOB)) {
xunjieli26f90452014-11-10 16:23:021290 source_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_CREATE_JOB);
[email protected]0f292de02012-02-01 22:28:201291
1292 net_log_.BeginEvent(
1293 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
[email protected]cd565142012-06-12 16:21:451294 base::Bind(&NetLogJobCreationCallback,
xunjieli26f90452014-11-10 16:23:021295 source_net_log.source(),
[email protected]cd565142012-06-12 16:21:451296 &key_.hostname));
[email protected]68ad3ee2010-01-30 03:45:391297 }
1298
dchengb03027d2014-10-21 12:00:201299 ~Job() override {
[email protected]b3601bc22012-02-21 21:23:201300 if (is_running()) {
1301 // |resolver_| was destroyed with this Job still in flight.
1302 // Clean-up, record in the log, but don't run any callbacks.
1303 if (is_proc_running()) {
[email protected]0f292de02012-02-01 22:28:201304 proc_task_->Cancel();
1305 proc_task_ = NULL;
[email protected]0f292de02012-02-01 22:28:201306 }
[email protected]16ee26d2012-03-08 03:34:351307 // Clean up now for nice NetLog.
[email protected]daae1322013-09-05 18:26:501308 KillDnsTask();
[email protected]b3601bc22012-02-21 21:23:201309 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
1310 ERR_ABORTED);
1311 } else if (is_queued()) {
[email protected]57a48d32012-03-03 00:04:551312 // |resolver_| was destroyed without running this Job.
[email protected]16ee26d2012-03-08 03:34:351313 // TODO(szym): is there any benefit in having this distinction?
[email protected]4da911f2012-06-14 19:45:201314 net_log_.AddEvent(NetLog::TYPE_CANCELLED);
1315 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB);
[email protected]68ad3ee2010-01-30 03:45:391316 }
[email protected]b3601bc22012-02-21 21:23:201317 // else CompleteRequests logged EndEvent.
[email protected]68ad3ee2010-01-30 03:45:391318
[email protected]b3601bc22012-02-21 21:23:201319 // Log any remaining Requests as cancelled.
danakj22f90e72016-04-16 01:55:401320 for (const std::unique_ptr<Request>& req : requests_) {
[email protected]b3601bc22012-02-21 21:23:201321 if (req->was_canceled())
1322 continue;
1323 DCHECK_EQ(this, req->job());
xunjieli26f90452014-11-10 16:23:021324 LogCancelRequest(req->source_net_log(), req->info());
[email protected]b3601bc22012-02-21 21:23:201325 }
[email protected]68ad3ee2010-01-30 03:45:391326 }
1327
[email protected]daae1322013-09-05 18:26:501328 // Add this job to the dispatcher. If "at_head" is true, adds at the front
1329 // of the queue.
1330 void Schedule(bool at_head) {
1331 DCHECK(!is_queued());
1332 PrioritizedDispatcher::Handle handle;
1333 if (!at_head) {
[email protected]106ccd2c2014-06-17 09:21:001334 handle = resolver_->dispatcher_->Add(this, priority());
[email protected]daae1322013-09-05 18:26:501335 } else {
[email protected]106ccd2c2014-06-17 09:21:001336 handle = resolver_->dispatcher_->AddAtHead(this, priority());
[email protected]daae1322013-09-05 18:26:501337 }
1338 // The dispatcher could have started |this| in the above call to Add, which
1339 // could have called Schedule again. In that case |handle| will be null,
1340 // but |handle_| may have been set by the other nested call to Schedule.
1341 if (!handle.is_null()) {
1342 DCHECK(handle_.is_null());
1343 handle_ = handle;
1344 }
[email protected]16ee26d2012-03-08 03:34:351345 }
1346
danakj22f90e72016-04-16 01:55:401347 void AddRequest(std::unique_ptr<Request> req) {
estarkd1bc206e2015-06-20 00:44:391348 DCHECK_EQ(key_.hostname, req->info().hostname());
[email protected]0f292de02012-02-01 22:28:201349
1350 req->set_job(this);
[email protected]5109c1952013-08-20 18:44:101351 priority_tracker_.Add(req->priority());
[email protected]0f292de02012-02-01 22:28:201352
xunjieli26f90452014-11-10 16:23:021353 req->source_net_log().AddEvent(
[email protected]0f292de02012-02-01 22:28:201354 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_ATTACH,
[email protected]cd565142012-06-12 16:21:451355 net_log_.source().ToEventParametersCallback());
[email protected]0f292de02012-02-01 22:28:201356
1357 net_log_.AddEvent(
1358 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_REQUEST_ATTACH,
[email protected]cd565142012-06-12 16:21:451359 base::Bind(&NetLogJobAttachCallback,
xunjieli26f90452014-11-10 16:23:021360 req->source_net_log().source(),
[email protected]cd565142012-06-12 16:21:451361 priority()));
[email protected]0f292de02012-02-01 22:28:201362
1363 // TODO(szym): Check if this is still needed.
1364 if (!req->info().is_speculative()) {
1365 had_non_speculative_request_ = true;
[email protected]90499482013-06-01 00:39:501366 if (proc_task_.get())
[email protected]0f292de02012-02-01 22:28:201367 proc_task_->set_had_non_speculative_request();
[email protected]68ad3ee2010-01-30 03:45:391368 }
[email protected]b3601bc22012-02-21 21:23:201369
dchengc7eeda422015-12-26 03:56:481370 requests_.push_back(std::move(req));
[email protected]b3601bc22012-02-21 21:23:201371
[email protected]51b9a6b2012-06-25 21:50:291372 UpdatePriority();
[email protected]68ad3ee2010-01-30 03:45:391373 }
1374
juliatuttlec53b19a72016-05-05 13:51:311375 void ChangeRequestPriority(Request* req, RequestPriority priority) {
1376 DCHECK_EQ(key_.hostname, req->info().hostname());
1377 DCHECK(!req->was_canceled());
1378
1379 priority_tracker_.Remove(req->priority());
1380 req->set_priority(priority);
1381 priority_tracker_.Add(req->priority());
1382 UpdatePriority();
1383 }
1384
[email protected]16ee26d2012-03-08 03:34:351385 // Marks |req| as cancelled. If it was the last active Request, also finishes
[email protected]0adcb2b2012-08-15 21:30:461386 // this Job, marking it as cancelled, and deletes it.
[email protected]0f292de02012-02-01 22:28:201387 void CancelRequest(Request* req) {
1388 DCHECK_EQ(key_.hostname, req->info().hostname());
1389 DCHECK(!req->was_canceled());
[email protected]16ee26d2012-03-08 03:34:351390
[email protected]0f292de02012-02-01 22:28:201391 // Don't remove it from |requests_| just mark it canceled.
1392 req->MarkAsCanceled();
xunjieli26f90452014-11-10 16:23:021393 LogCancelRequest(req->source_net_log(), req->info());
[email protected]16ee26d2012-03-08 03:34:351394
[email protected]5109c1952013-08-20 18:44:101395 priority_tracker_.Remove(req->priority());
1396 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_REQUEST_DETACH,
1397 base::Bind(&NetLogJobAttachCallback,
xunjieli26f90452014-11-10 16:23:021398 req->source_net_log().source(),
[email protected]5109c1952013-08-20 18:44:101399 priority()));
[email protected]b3601bc22012-02-21 21:23:201400
[email protected]16ee26d2012-03-08 03:34:351401 if (num_active_requests() > 0) {
[email protected]51b9a6b2012-06-25 21:50:291402 UpdatePriority();
[email protected]16ee26d2012-03-08 03:34:351403 } else {
1404 // If we were called from a Request's callback within CompleteRequests,
1405 // that Request could not have been cancelled, so num_active_requests()
1406 // could not be 0. Therefore, we are not in CompleteRequests().
[email protected]1339a2a22012-10-17 08:39:431407 CompleteRequestsWithError(OK /* cancelled */);
[email protected]b3601bc22012-02-21 21:23:201408 }
[email protected]68ad3ee2010-01-30 03:45:391409 }
1410
[email protected]7af985a2012-12-14 22:40:421411 // Called from AbortAllInProgressJobs. Completes all requests and destroys
1412 // the job. This currently assumes the abort is due to a network change.
olli.raulaa21e9eb72015-12-17 08:18:111413 // TODO This should not delete |this|.
[email protected]0f292de02012-02-01 22:28:201414 void Abort() {
[email protected]0f292de02012-02-01 22:28:201415 DCHECK(is_running());
[email protected]7af985a2012-12-14 22:40:421416 CompleteRequestsWithError(ERR_NETWORK_CHANGED);
[email protected]b3601bc22012-02-21 21:23:201417 }
1418
[email protected]f0f602bd2012-11-15 18:01:021419 // If DnsTask present, abort it and fall back to ProcTask.
1420 void AbortDnsTask() {
1421 if (dns_task_) {
[email protected]daae1322013-09-05 18:26:501422 KillDnsTask();
[email protected]f0f602bd2012-11-15 18:01:021423 dns_task_error_ = OK;
1424 StartProcTask();
1425 }
1426 }
1427
[email protected]16ee26d2012-03-08 03:34:351428 // Called by HostResolverImpl when this job is evicted due to queue overflow.
1429 // Completes all requests and destroys the job.
1430 void OnEvicted() {
1431 DCHECK(!is_running());
1432 DCHECK(is_queued());
1433 handle_.Reset();
1434
[email protected]4da911f2012-06-14 19:45:201435 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_EVICTED);
[email protected]16ee26d2012-03-08 03:34:351436
1437 // This signals to CompleteRequests that this job never ran.
[email protected]1339a2a22012-10-17 08:39:431438 CompleteRequestsWithError(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
[email protected]16ee26d2012-03-08 03:34:351439 }
1440
[email protected]78eac2a2012-03-14 19:09:271441 // Attempts to serve the job from HOSTS. Returns true if succeeded and
1442 // this Job was destroyed.
1443 bool ServeFromHosts() {
1444 DCHECK_GT(num_active_requests(), 0u);
1445 AddressList addr_list;
1446 if (resolver_->ServeFromHosts(key(),
[email protected]3cb676a12012-06-30 15:46:031447 requests_.front()->info(),
[email protected]78eac2a2012-03-14 19:09:271448 &addr_list)) {
1449 // This will destroy the Job.
[email protected]895123222012-10-25 15:21:171450 CompleteRequests(
1451 HostCache::Entry(OK, MakeAddressListForRequest(addr_list)),
1452 base::TimeDelta());
[email protected]78eac2a2012-03-14 19:09:271453 return true;
1454 }
1455 return false;
1456 }
1457
tanay.c6ddd5f6f2015-08-25 06:34:571458 const Key& key() const { return key_; }
[email protected]b4481b222012-03-16 17:13:111459
1460 bool is_queued() const {
1461 return !handle_.is_null();
1462 }
1463
1464 bool is_running() const {
1465 return is_dns_running() || is_proc_running();
1466 }
1467
[email protected]16ee26d2012-03-08 03:34:351468 private:
[email protected]daae1322013-09-05 18:26:501469 void KillDnsTask() {
1470 if (dns_task_) {
1471 ReduceToOneJobSlot();
1472 dns_task_.reset();
1473 }
1474 }
1475
1476 // Reduce the number of job slots occupied and queued in the dispatcher
1477 // to one. If the second Job slot is queued in the dispatcher, cancels the
1478 // queued job. Otherwise, the second Job has been started by the
1479 // PrioritizedDispatcher, so signals it is complete.
1480 void ReduceToOneJobSlot() {
1481 DCHECK_GE(num_occupied_job_slots_, 1u);
1482 if (is_queued()) {
[email protected]106ccd2c2014-06-17 09:21:001483 resolver_->dispatcher_->Cancel(handle_);
[email protected]daae1322013-09-05 18:26:501484 handle_.Reset();
1485 } else if (num_occupied_job_slots_ > 1) {
[email protected]106ccd2c2014-06-17 09:21:001486 resolver_->dispatcher_->OnJobFinished();
[email protected]daae1322013-09-05 18:26:501487 --num_occupied_job_slots_;
1488 }
1489 DCHECK_EQ(1u, num_occupied_job_slots_);
1490 }
1491
juliatuttlec53b19a72016-05-05 13:51:311492 AddressList MakeAddressListForRequest(const AddressList& list) const {
1493 if (requests_.empty())
1494 return list;
1495 return AddressList::CopyWithPort(list, requests_.front()->info().port());
1496 }
1497
[email protected]51b9a6b2012-06-25 21:50:291498 void UpdatePriority() {
1499 if (is_queued()) {
1500 if (priority() != static_cast<RequestPriority>(handle_.priority()))
1501 priority_change_time_ = base::TimeTicks::Now();
[email protected]106ccd2c2014-06-17 09:21:001502 handle_ = resolver_->dispatcher_->ChangePriority(handle_, priority());
[email protected]51b9a6b2012-06-25 21:50:291503 }
1504 }
1505
[email protected]16ee26d2012-03-08 03:34:351506 // PriorityDispatch::Job:
dchengb03027d2014-10-21 12:00:201507 void Start() override {
[email protected]daae1322013-09-05 18:26:501508 DCHECK_LE(num_occupied_job_slots_, 1u);
1509
[email protected]70c04ab2013-08-22 16:05:121510 handle_.Reset();
[email protected]daae1322013-09-05 18:26:501511 ++num_occupied_job_slots_;
1512
1513 if (num_occupied_job_slots_ == 2) {
1514 StartSecondDnsTransaction();
1515 return;
1516 }
1517
1518 DCHECK(!is_running());
[email protected]0f292de02012-02-01 22:28:201519
[email protected]4da911f2012-06-14 19:45:201520 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_STARTED);
[email protected]0f292de02012-02-01 22:28:201521
[email protected]51b9a6b2012-06-25 21:50:291522 had_dns_config_ = resolver_->HaveDnsConfig();
1523
1524 base::TimeTicks now = base::TimeTicks::Now();
1525 base::TimeDelta queue_time = now - creation_time_;
1526 base::TimeDelta queue_time_after_change = now - priority_change_time_;
1527
1528 if (had_dns_config_) {
1529 DNS_HISTOGRAM_BY_PRIORITY("AsyncDNS.JobQueueTime", priority(),
1530 queue_time);
1531 DNS_HISTOGRAM_BY_PRIORITY("AsyncDNS.JobQueueTimeAfterChange", priority(),
1532 queue_time_after_change);
1533 } else {
1534 DNS_HISTOGRAM_BY_PRIORITY("DNS.JobQueueTime", priority(), queue_time);
1535 DNS_HISTOGRAM_BY_PRIORITY("DNS.JobQueueTimeAfterChange", priority(),
1536 queue_time_after_change);
1537 }
1538
[email protected]443714fad2013-09-19 04:52:011539 bool system_only =
1540 (key_.host_resolver_flags & HOST_RESOLVER_SYSTEM_ONLY) != 0;
1541
[email protected]1d932852012-06-19 19:40:331542 // Caution: Job::Start must not complete synchronously.
[email protected]443714fad2013-09-19 04:52:011543 if (!system_only && had_dns_config_ &&
1544 !ResemblesMulticastDNSName(key_.hostname)) {
[email protected]b3601bc22012-02-21 21:23:201545 StartDnsTask();
1546 } else {
1547 StartProcTask();
1548 }
1549 }
1550
[email protected]b3601bc22012-02-21 21:23:201551 // TODO(szym): Since DnsTransaction does not consume threads, we can increase
1552 // the limits on |dispatcher_|. But in order to keep the number of WorkerPool
1553 // threads low, we will need to use an "inner" PrioritizedDispatcher with
1554 // tighter limits.
1555 void StartProcTask() {
[email protected]16ee26d2012-03-08 03:34:351556 DCHECK(!is_dns_running());
mmenke91c17162016-06-02 16:03:231557 proc_task_ =
1558 new ProcTask(key_, resolver_->proc_params_,
1559 base::Bind(&Job::OnProcTaskComplete,
1560 base::Unretained(this), base::TimeTicks::Now()),
1561 worker_task_runner_, net_log_);
[email protected]0f292de02012-02-01 22:28:201562
1563 if (had_non_speculative_request_)
1564 proc_task_->set_had_non_speculative_request();
1565 // Start() could be called from within Resolve(), hence it must NOT directly
1566 // call OnProcTaskComplete, for example, on synchronous failure.
1567 proc_task_->Start();
[email protected]68ad3ee2010-01-30 03:45:391568 }
1569
[email protected]0f292de02012-02-01 22:28:201570 // Called by ProcTask when it completes.
[email protected]e3bd4822012-10-23 18:01:371571 void OnProcTaskComplete(base::TimeTicks start_time,
1572 int net_error,
1573 const AddressList& addr_list) {
[email protected]b3601bc22012-02-21 21:23:201574 DCHECK(is_proc_running());
[email protected]68ad3ee2010-01-30 03:45:391575
[email protected]62e86ba2013-01-29 18:59:161576 if (!resolver_->resolved_known_ipv6_hostname_ &&
1577 net_error == OK &&
1578 key_.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
1579 if (key_.hostname == "www.google.com") {
1580 resolver_->resolved_known_ipv6_hostname_ = true;
1581 bool got_ipv6_address = false;
1582 for (size_t i = 0; i < addr_list.size(); ++i) {
[email protected]5134c22a2013-08-06 18:09:021583 if (addr_list[i].GetFamily() == ADDRESS_FAMILY_IPV6) {
[email protected]62e86ba2013-01-29 18:59:161584 got_ipv6_address = true;
[email protected]5134c22a2013-08-06 18:09:021585 break;
1586 }
[email protected]62e86ba2013-01-29 18:59:161587 }
1588 UMA_HISTOGRAM_BOOLEAN("Net.UnspecResolvedIPv6", got_ipv6_address);
1589 }
1590 }
1591
[email protected]1d932852012-06-19 19:40:331592 if (dns_task_error_ != OK) {
[email protected]e3bd4822012-10-23 18:01:371593 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]1def74c2012-03-22 20:07:001594 if (net_error == OK) {
[email protected]e3bd4822012-10-23 18:01:371595 DNS_HISTOGRAM("AsyncDNS.FallbackSuccess", duration);
[email protected]1d932852012-06-19 19:40:331596 if ((dns_task_error_ == ERR_NAME_NOT_RESOLVED) &&
1597 ResemblesNetBIOSName(key_.hostname)) {
1598 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_SUSPECT_NETBIOS);
1599 } else {
1600 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_PROC_SUCCESS);
1601 }
davidbenad6fc442015-05-18 20:59:131602 UMA_HISTOGRAM_SPARSE_SLOWLY("AsyncDNS.ResolveError",
1603 std::abs(dns_task_error_));
[email protected]1ffdda82012-12-12 23:04:221604 resolver_->OnDnsTaskResolve(dns_task_error_);
[email protected]1def74c2012-03-22 20:07:001605 } else {
[email protected]e3bd4822012-10-23 18:01:371606 DNS_HISTOGRAM("AsyncDNS.FallbackFail", duration);
[email protected]1def74c2012-03-22 20:07:001607 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
1608 }
1609 }
1610
[email protected]1339a2a22012-10-17 08:39:431611 base::TimeDelta ttl =
1612 base::TimeDelta::FromSeconds(kNegativeCacheEntryTTLSeconds);
[email protected]b3601bc22012-02-21 21:23:201613 if (net_error == OK)
1614 ttl = base::TimeDelta::FromSeconds(kCacheEntryTTLSeconds);
[email protected]68ad3ee2010-01-30 03:45:391615
[email protected]895123222012-10-25 15:21:171616 // Don't store the |ttl| in cache since it's not obtained from the server.
1617 CompleteRequests(
1618 HostCache::Entry(net_error, MakeAddressListForRequest(addr_list)),
1619 ttl);
[email protected]b3601bc22012-02-21 21:23:201620 }
1621
1622 void StartDnsTask() {
[email protected]78eac2a2012-03-14 19:09:271623 DCHECK(resolver_->HaveDnsConfig());
[email protected]daae1322013-09-05 18:26:501624 dns_task_.reset(new DnsTask(resolver_->dns_client_.get(), key_, this,
1625 net_log_));
[email protected]b3601bc22012-02-21 21:23:201626
[email protected]daae1322013-09-05 18:26:501627 dns_task_->StartFirstTransaction();
1628 // Schedule a second transaction, if needed.
1629 if (dns_task_->needs_two_transactions())
1630 Schedule(true);
1631 }
1632
1633 void StartSecondDnsTransaction() {
1634 DCHECK(dns_task_->needs_two_transactions());
1635 dns_task_->StartSecondTransaction();
[email protected]16c2bd72013-06-28 01:19:221636 }
1637
1638 // Called if DnsTask fails. It is posted from StartDnsTask, so Job may be
1639 // deleted before this callback. In this case dns_task is deleted as well,
1640 // so we use it as indicator whether Job is still valid.
1641 void OnDnsTaskFailure(const base::WeakPtr<DnsTask>& dns_task,
1642 base::TimeDelta duration,
1643 int net_error) {
1644 DNS_HISTOGRAM("AsyncDNS.ResolveFail", duration);
1645
1646 if (dns_task == NULL)
1647 return;
1648
1649 dns_task_error_ = net_error;
1650
1651 // TODO(szym): Run ServeFromHosts now if nsswitch.conf says so.
1652 // http://crbug.com/117655
1653
1654 // TODO(szym): Some net errors indicate lack of connectivity. Starting
1655 // ProcTask in that case is a waste of time.
1656 if (resolver_->fallback_to_proctask_) {
[email protected]daae1322013-09-05 18:26:501657 KillDnsTask();
[email protected]16c2bd72013-06-28 01:19:221658 StartProcTask();
1659 } else {
1660 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
1661 CompleteRequestsWithError(net_error);
[email protected]b3601bc22012-02-21 21:23:201662 }
1663 }
1664
[email protected]daae1322013-09-05 18:26:501665
1666 // HostResolverImpl::DnsTask::Delegate implementation:
1667
dchengb03027d2014-10-21 12:00:201668 void OnDnsTaskComplete(base::TimeTicks start_time,
1669 int net_error,
1670 const AddressList& addr_list,
1671 base::TimeDelta ttl) override {
[email protected]b3601bc22012-02-21 21:23:201672 DCHECK(is_dns_running());
[email protected]b3601bc22012-02-21 21:23:201673
[email protected]e3bd4822012-10-23 18:01:371674 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]b3601bc22012-02-21 21:23:201675 if (net_error != OK) {
[email protected]16c2bd72013-06-28 01:19:221676 OnDnsTaskFailure(dns_task_->AsWeakPtr(), duration, net_error);
[email protected]b3601bc22012-02-21 21:23:201677 return;
1678 }
[email protected]e3bd4822012-10-23 18:01:371679 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess", duration);
[email protected]02cd6982013-01-10 20:12:511680 // Log DNS lookups based on |address_family|.
1681 switch(key_.address_family) {
1682 case ADDRESS_FAMILY_IPV4:
1683 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_IPV4", duration);
1684 break;
1685 case ADDRESS_FAMILY_IPV6:
1686 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_IPV6", duration);
1687 break;
1688 case ADDRESS_FAMILY_UNSPECIFIED:
1689 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_UNSPEC", duration);
1690 break;
1691 }
[email protected]b3601bc22012-02-21 21:23:201692
[email protected]1def74c2012-03-22 20:07:001693 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_DNS_SUCCESS);
[email protected]1339a2a22012-10-17 08:39:431694 RecordTTL(ttl);
[email protected]0adcb2b2012-08-15 21:30:461695
[email protected]1ffdda82012-12-12 23:04:221696 resolver_->OnDnsTaskResolve(OK);
[email protected]f0f602bd2012-11-15 18:01:021697
[email protected]895123222012-10-25 15:21:171698 base::TimeDelta bounded_ttl =
1699 std::max(ttl, base::TimeDelta::FromSeconds(kMinimumTTLSeconds));
1700
1701 CompleteRequests(
1702 HostCache::Entry(net_error, MakeAddressListForRequest(addr_list), ttl),
1703 bounded_ttl);
[email protected]b3601bc22012-02-21 21:23:201704 }
1705
dchengb03027d2014-10-21 12:00:201706 void OnFirstDnsTransactionComplete() override {
[email protected]daae1322013-09-05 18:26:501707 DCHECK(dns_task_->needs_two_transactions());
1708 DCHECK_EQ(dns_task_->needs_another_transaction(), is_queued());
1709 // No longer need to occupy two dispatcher slots.
1710 ReduceToOneJobSlot();
1711
1712 // We already have a job slot at the dispatcher, so if the second
1713 // transaction hasn't started, reuse it now instead of waiting in the queue
1714 // for the second slot.
1715 if (dns_task_->needs_another_transaction())
1716 dns_task_->StartSecondTransaction();
1717 }
1718
[email protected]16ee26d2012-03-08 03:34:351719 // Performs Job's last rites. Completes all Requests. Deletes this.
[email protected]895123222012-10-25 15:21:171720 void CompleteRequests(const HostCache::Entry& entry,
1721 base::TimeDelta ttl) {
[email protected]11fbca0b2013-06-02 23:37:211722 CHECK(resolver_.get());
[email protected]b3601bc22012-02-21 21:23:201723
[email protected]16ee26d2012-03-08 03:34:351724 // This job must be removed from resolver's |jobs_| now to make room for a
1725 // new job with the same key in case one of the OnComplete callbacks decides
1726 // to spawn one. Consequently, the job deletes itself when CompleteRequests
1727 // is done.
danakj22f90e72016-04-16 01:55:401728 std::unique_ptr<Job> self_deleter(this);
[email protected]16ee26d2012-03-08 03:34:351729
1730 resolver_->RemoveJob(this);
1731
[email protected]16ee26d2012-03-08 03:34:351732 if (is_running()) {
[email protected]16ee26d2012-03-08 03:34:351733 if (is_proc_running()) {
[email protected]daae1322013-09-05 18:26:501734 DCHECK(!is_queued());
[email protected]16ee26d2012-03-08 03:34:351735 proc_task_->Cancel();
1736 proc_task_ = NULL;
1737 }
[email protected]daae1322013-09-05 18:26:501738 KillDnsTask();
[email protected]16ee26d2012-03-08 03:34:351739
1740 // Signal dispatcher that a slot has opened.
[email protected]106ccd2c2014-06-17 09:21:001741 resolver_->dispatcher_->OnJobFinished();
[email protected]16ee26d2012-03-08 03:34:351742 } else if (is_queued()) {
[email protected]106ccd2c2014-06-17 09:21:001743 resolver_->dispatcher_->Cancel(handle_);
[email protected]16ee26d2012-03-08 03:34:351744 handle_.Reset();
1745 }
1746
1747 if (num_active_requests() == 0) {
[email protected]4da911f2012-06-14 19:45:201748 net_log_.AddEvent(NetLog::TYPE_CANCELLED);
[email protected]16ee26d2012-03-08 03:34:351749 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
1750 OK);
1751 return;
1752 }
[email protected]b3601bc22012-02-21 21:23:201753
1754 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
juliatuttle317860e2016-05-12 14:47:221755 entry.error());
[email protected]68ad3ee2010-01-30 03:45:391756
[email protected]78eac2a2012-03-14 19:09:271757 DCHECK(!requests_.empty());
1758
juliatuttle317860e2016-05-12 14:47:221759 if (entry.error() == OK) {
[email protected]d7b9a2b2012-05-31 22:31:191760 // Record this histogram here, when we know the system has a valid DNS
1761 // configuration.
[email protected]539df6c2012-06-19 21:21:291762 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.HaveDnsConfig",
1763 resolver_->received_dns_config_);
[email protected]d7b9a2b2012-05-31 22:31:191764 }
[email protected]16ee26d2012-03-08 03:34:351765
juliatuttle317860e2016-05-12 14:47:221766 bool did_complete = (entry.error() != ERR_NETWORK_CHANGED) &&
1767 (entry.error() != ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
[email protected]895123222012-10-25 15:21:171768 if (did_complete)
[email protected]1339a2a22012-10-17 08:39:431769 resolver_->CacheResult(key_, entry, ttl);
[email protected]16ee26d2012-03-08 03:34:351770
[email protected]0f292de02012-02-01 22:28:201771 // Complete all of the requests that were attached to the job.
danakj22f90e72016-04-16 01:55:401772 for (const std::unique_ptr<Request>& req : requests_) {
[email protected]0f292de02012-02-01 22:28:201773 if (req->was_canceled())
1774 continue;
1775
1776 DCHECK_EQ(this, req->job());
1777 // Update the net log and notify registered observers.
juliatuttle317860e2016-05-12 14:47:221778 LogFinishRequest(req->source_net_log(), req->info(), entry.error());
[email protected]51b9a6b2012-06-25 21:50:291779 if (did_complete) {
1780 // Record effective total time from creation to completion.
1781 RecordTotalTime(had_dns_config_, req->info().is_speculative(),
1782 base::TimeTicks::Now() - req->request_time());
1783 }
juliatuttle317860e2016-05-12 14:47:221784 req->OnComplete(entry.error(), entry.addresses());
[email protected]0f292de02012-02-01 22:28:201785
1786 // Check if the resolver was destroyed as a result of running the
1787 // callback. If it was, we could continue, but we choose to bail.
[email protected]11fbca0b2013-06-02 23:37:211788 if (!resolver_.get())
[email protected]0f292de02012-02-01 22:28:201789 return;
1790 }
1791 }
1792
[email protected]1339a2a22012-10-17 08:39:431793 // Convenience wrapper for CompleteRequests in case of failure.
1794 void CompleteRequestsWithError(int net_error) {
[email protected]895123222012-10-25 15:21:171795 CompleteRequests(HostCache::Entry(net_error, AddressList()),
1796 base::TimeDelta());
[email protected]1339a2a22012-10-17 08:39:431797 }
1798
[email protected]b4481b222012-03-16 17:13:111799 RequestPriority priority() const {
1800 return priority_tracker_.highest_priority();
1801 }
1802
1803 // Number of non-canceled requests in |requests_|.
1804 size_t num_active_requests() const {
1805 return priority_tracker_.total_count();
1806 }
1807
1808 bool is_dns_running() const {
1809 return dns_task_.get() != NULL;
1810 }
1811
1812 bool is_proc_running() const {
1813 return proc_task_.get() != NULL;
1814 }
1815
[email protected]0f292de02012-02-01 22:28:201816 base::WeakPtr<HostResolverImpl> resolver_;
1817
1818 Key key_;
1819
1820 // Tracks the highest priority across |requests_|.
1821 PriorityTracker priority_tracker_;
1822
mmenke91c17162016-06-02 16:03:231823 // Task runner where the HostResolverProc is invoked.
1824 scoped_refptr<base::TaskRunner> worker_task_runner_;
1825
[email protected]0f292de02012-02-01 22:28:201826 bool had_non_speculative_request_;
1827
[email protected]51b9a6b2012-06-25 21:50:291828 // Distinguishes measurements taken while DnsClient was fully configured.
1829 bool had_dns_config_;
1830
[email protected]daae1322013-09-05 18:26:501831 // Number of slots occupied by this Job in resolver's PrioritizedDispatcher.
1832 unsigned num_occupied_job_slots_;
1833
[email protected]1d932852012-06-19 19:40:331834 // Result of DnsTask.
1835 int dns_task_error_;
[email protected]1def74c2012-03-22 20:07:001836
[email protected]51b9a6b2012-06-25 21:50:291837 const base::TimeTicks creation_time_;
1838 base::TimeTicks priority_change_time_;
1839
[email protected]0f292de02012-02-01 22:28:201840 BoundNetLog net_log_;
1841
[email protected]b3601bc22012-02-21 21:23:201842 // Resolves the host using a HostResolverProc.
[email protected]0f292de02012-02-01 22:28:201843 scoped_refptr<ProcTask> proc_task_;
1844
[email protected]b3601bc22012-02-21 21:23:201845 // Resolves the host using a DnsTransaction.
danakj22f90e72016-04-16 01:55:401846 std::unique_ptr<DnsTask> dns_task_;
[email protected]b3601bc22012-02-21 21:23:201847
[email protected]0f292de02012-02-01 22:28:201848 // All Requests waiting for the result of this Job. Some can be canceled.
danakj22f90e72016-04-16 01:55:401849 std::vector<std::unique_ptr<Request>> requests_;
[email protected]0f292de02012-02-01 22:28:201850
[email protected]16ee26d2012-03-08 03:34:351851 // A handle used in |HostResolverImpl::dispatcher_|.
[email protected]0f292de02012-02-01 22:28:201852 PrioritizedDispatcher::Handle handle_;
[email protected]68ad3ee2010-01-30 03:45:391853};
1854
1855//-----------------------------------------------------------------------------
1856
[email protected]0f292de02012-02-01 22:28:201857HostResolverImpl::ProcTaskParams::ProcTaskParams(
[email protected]e95d3aca2010-01-11 22:47:431858 HostResolverProc* resolver_proc,
[email protected]0f292de02012-02-01 22:28:201859 size_t max_retry_attempts)
1860 : resolver_proc(resolver_proc),
1861 max_retry_attempts(max_retry_attempts),
ttuttlecf1158bf2016-03-18 16:37:441862 unresponsive_delay(
1863 base::TimeDelta::FromMilliseconds(kDnsDefaultUnresponsiveDelayMs)),
[email protected]0f292de02012-02-01 22:28:201864 retry_factor(2) {
[email protected]106ccd2c2014-06-17 09:21:001865 // Maximum of 4 retry attempts for host resolution.
1866 static const size_t kDefaultMaxRetryAttempts = 4u;
1867 if (max_retry_attempts == HostResolver::kDefaultRetryAttempts)
1868 max_retry_attempts = kDefaultMaxRetryAttempts;
[email protected]0f292de02012-02-01 22:28:201869}
1870
vmpstracd23b72016-02-26 21:08:551871HostResolverImpl::ProcTaskParams::ProcTaskParams(const ProcTaskParams& other) =
1872 default;
1873
[email protected]0f292de02012-02-01 22:28:201874HostResolverImpl::ProcTaskParams::~ProcTaskParams() {}
1875
[email protected]106ccd2c2014-06-17 09:21:001876HostResolverImpl::HostResolverImpl(const Options& options, NetLog* net_log)
mmenke91c17162016-06-02 16:03:231877 : HostResolverImpl(
1878 options,
1879 net_log,
1880 base::WorkerPool::GetTaskRunner(true /* task_is_slow */)) {}
[email protected]b59ff372009-07-15 22:04:321881
1882HostResolverImpl::~HostResolverImpl() {
[email protected]daae1322013-09-05 18:26:501883 // Prevent the dispatcher from starting new jobs.
[email protected]106ccd2c2014-06-17 09:21:001884 dispatcher_->SetLimitsToZero();
[email protected]daae1322013-09-05 18:26:501885 // It's now safe for Jobs to call KillDsnTask on destruction, because
1886 // OnJobComplete will not start any new jobs.
[email protected]0f292de02012-02-01 22:28:201887 STLDeleteValues(&jobs_);
[email protected]e95d3aca2010-01-11 22:47:431888
[email protected]232a5812011-03-04 22:42:081889 NetworkChangeNotifier::RemoveIPAddressObserver(this);
ttuttlecf1158bf2016-03-18 16:37:441890 NetworkChangeNotifier::RemoveConnectionTypeObserver(this);
[email protected]bb0e34542012-08-31 19:52:401891 NetworkChangeNotifier::RemoveDNSObserver(this);
[email protected]b59ff372009-07-15 22:04:321892}
1893
[email protected]0f292de02012-02-01 22:28:201894void HostResolverImpl::SetMaxQueuedJobs(size_t value) {
[email protected]106ccd2c2014-06-17 09:21:001895 DCHECK_EQ(0u, dispatcher_->num_queued_jobs());
[email protected]0f292de02012-02-01 22:28:201896 DCHECK_GT(value, 0u);
1897 max_queued_jobs_ = value;
[email protected]be1a48b2011-01-20 00:12:131898}
1899
[email protected]684970b2009-08-14 04:54:461900int HostResolverImpl::Resolve(const RequestInfo& info,
[email protected]5109c1952013-08-20 18:44:101901 RequestPriority priority,
[email protected]b59ff372009-07-15 22:04:321902 AddressList* addresses,
[email protected]aa22b242011-11-16 18:58:291903 const CompletionCallback& callback,
[email protected]684970b2009-08-14 04:54:461904 RequestHandle* out_req,
[email protected]ee094b82010-08-24 15:55:511905 const BoundNetLog& source_net_log) {
[email protected]95a214c2011-08-04 21:50:401906 DCHECK(addresses);
[email protected]1ac6af92010-06-03 21:00:141907 DCHECK(CalledOnValidThread());
[email protected]aa22b242011-11-16 18:58:291908 DCHECK_EQ(false, callback.is_null());
[email protected]1ac6af92010-06-03 21:00:141909
[email protected]e806cd72013-05-17 02:08:431910 // Check that the caller supplied a valid hostname to resolve.
1911 std::string labeled_hostname;
1912 if (!DNSDomainFromDot(info.hostname(), &labeled_hostname))
1913 return ERR_NAME_NOT_RESOLVED;
1914
xunjieli26f90452014-11-10 16:23:021915 LogStartRequest(source_net_log, info);
[email protected]b59ff372009-07-15 22:04:321916
martijna23c8962016-03-04 18:18:511917 IPAddress ip_address;
1918 IPAddress* ip_address_ptr = nullptr;
1919 if (ip_address.AssignFromIPLiteral(info.hostname()))
1920 ip_address_ptr = &ip_address;
pauljensen19eb73422015-04-15 23:20:061921
[email protected]123ab1e32009-10-21 19:12:571922 // Build a key that identifies the request in the cache and in the
1923 // outstanding jobs map.
martijna23c8962016-03-04 18:18:511924 Key key = GetEffectiveKeyForRequest(info, ip_address_ptr, source_net_log);
[email protected]123ab1e32009-10-21 19:12:571925
martijna23c8962016-03-04 18:18:511926 int rv = ResolveHelper(key, info, ip_address_ptr, addresses, source_net_log);
[email protected]95a214c2011-08-04 21:50:401927 if (rv != ERR_DNS_CACHE_MISS) {
xunjieli26f90452014-11-10 16:23:021928 LogFinishRequest(source_net_log, info, rv);
[email protected]51b9a6b2012-06-25 21:50:291929 RecordTotalTime(HaveDnsConfig(), info.is_speculative(), base::TimeDelta());
[email protected]95a214c2011-08-04 21:50:401930 return rv;
[email protected]38368712011-03-02 08:09:401931 }
1932
[email protected]0f292de02012-02-01 22:28:201933 // Next we need to attach our request to a "job". This job is responsible for
1934 // calling "getaddrinfo(hostname)" on a worker thread.
1935
1936 JobMap::iterator jobit = jobs_.find(key);
1937 Job* job;
1938 if (jobit == jobs_.end()) {
mmenke91c17162016-06-02 16:03:231939 job = new Job(weak_ptr_factory_.GetWeakPtr(), key, priority,
1940 worker_task_runner_, source_net_log);
[email protected]daae1322013-09-05 18:26:501941 job->Schedule(false);
[email protected]0f292de02012-02-01 22:28:201942
1943 // Check for queue overflow.
[email protected]106ccd2c2014-06-17 09:21:001944 if (dispatcher_->num_queued_jobs() > max_queued_jobs_) {
1945 Job* evicted = static_cast<Job*>(dispatcher_->EvictOldestLowest());
[email protected]0f292de02012-02-01 22:28:201946 DCHECK(evicted);
[email protected]16ee26d2012-03-08 03:34:351947 evicted->OnEvicted(); // Deletes |evicted|.
[email protected]0f292de02012-02-01 22:28:201948 if (evicted == job) {
[email protected]0f292de02012-02-01 22:28:201949 rv = ERR_HOST_RESOLVER_QUEUE_TOO_LARGE;
xunjieli26f90452014-11-10 16:23:021950 LogFinishRequest(source_net_log, info, rv);
[email protected]0f292de02012-02-01 22:28:201951 return rv;
1952 }
[email protected]0f292de02012-02-01 22:28:201953 }
[email protected]0f292de02012-02-01 22:28:201954 jobs_.insert(jobit, std::make_pair(key, job));
1955 } else {
1956 job = jobit->second;
1957 }
1958
1959 // Can't complete synchronously. Create and attach request.
danakj22f90e72016-04-16 01:55:401960 std::unique_ptr<Request> req(
1961 new Request(source_net_log, info, priority, callback, addresses));
[email protected]b59ff372009-07-15 22:04:321962 if (out_req)
[email protected]b3601bc22012-02-21 21:23:201963 *out_req = reinterpret_cast<RequestHandle>(req.get());
[email protected]b59ff372009-07-15 22:04:321964
dchengc7eeda422015-12-26 03:56:481965 job->AddRequest(std::move(req));
[email protected]0f292de02012-02-01 22:28:201966 // Completion happens during Job::CompleteRequests().
[email protected]b59ff372009-07-15 22:04:321967 return ERR_IO_PENDING;
1968}
1969
mmenke91c17162016-06-02 16:03:231970HostResolverImpl::HostResolverImpl(
1971 const Options& options,
1972 NetLog* net_log,
1973 scoped_refptr<base::TaskRunner> worker_task_runner)
1974 : max_queued_jobs_(0),
1975 proc_params_(NULL, options.max_retry_attempts),
1976 net_log_(net_log),
1977 received_dns_config_(false),
1978 num_dns_failures_(0),
1979 use_local_ipv6_(false),
1980 last_ipv6_probe_result_(true),
1981 resolved_known_ipv6_hostname_(false),
1982 additional_resolver_flags_(0),
1983 fallback_to_proctask_(true),
1984 worker_task_runner_(std::move(worker_task_runner)),
1985 weak_ptr_factory_(this),
1986 probe_weak_ptr_factory_(this) {
1987 if (options.enable_caching)
1988 cache_ = HostCache::CreateDefaultCache();
1989
1990 PrioritizedDispatcher::Limits job_limits = options.GetDispatcherLimits();
1991 dispatcher_.reset(new PrioritizedDispatcher(job_limits));
1992 max_queued_jobs_ = job_limits.total_jobs * 100u;
1993
1994 DCHECK_GE(dispatcher_->num_priorities(), static_cast<size_t>(NUM_PRIORITIES));
1995
1996#if defined(OS_WIN)
1997 EnsureWinsockInit();
1998#endif
1999#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
2000 RunLoopbackProbeJob();
2001#endif
2002 NetworkChangeNotifier::AddIPAddressObserver(this);
2003 NetworkChangeNotifier::AddConnectionTypeObserver(this);
2004 NetworkChangeNotifier::AddDNSObserver(this);
2005#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD) && \
2006 !defined(OS_ANDROID)
2007 EnsureDnsReloaderInit();
2008#endif
2009
2010 OnConnectionTypeChanged(NetworkChangeNotifier::GetConnectionType());
2011
2012 {
2013 DnsConfig dns_config;
2014 NetworkChangeNotifier::GetDnsConfig(&dns_config);
2015 received_dns_config_ = dns_config.IsValid();
2016 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
2017 use_local_ipv6_ = !dns_config.IsValid() || dns_config.use_local_ipv6;
2018 }
2019
2020 fallback_to_proctask_ = !ConfigureAsyncDnsNoFallbackFieldTrial();
2021}
2022
2023void HostResolverImpl::SetHaveOnlyLoopbackAddresses(bool result) {
2024 if (result) {
2025 additional_resolver_flags_ |= HOST_RESOLVER_LOOPBACK_ONLY;
2026 } else {
2027 additional_resolver_flags_ &= ~HOST_RESOLVER_LOOPBACK_ONLY;
2028 }
2029}
2030
[email protected]287d7c22011-11-15 17:34:252031int HostResolverImpl::ResolveHelper(const Key& key,
[email protected]95a214c2011-08-04 21:50:402032 const RequestInfo& info,
martijna23c8962016-03-04 18:18:512033 const IPAddress* ip_address,
[email protected]95a214c2011-08-04 21:50:402034 AddressList* addresses,
xunjieli26f90452014-11-10 16:23:022035 const BoundNetLog& source_net_log) {
[email protected]95a214c2011-08-04 21:50:402036 // The result of |getaddrinfo| for empty hosts is inconsistent across systems.
2037 // On Windows it gives the default interface's address, whereas on Linux it
2038 // gives an error. We will make it fail on all platforms for consistency.
2039 if (info.hostname().empty() || info.hostname().size() > kMaxHostLength)
2040 return ERR_NAME_NOT_RESOLVED;
2041
2042 int net_error = ERR_UNEXPECTED;
martijna23c8962016-03-04 18:18:512043 if (ResolveAsIP(key, info, ip_address, &net_error, addresses))
[email protected]95a214c2011-08-04 21:50:402044 return net_error;
[email protected]78eac2a2012-03-14 19:09:272045 if (ServeFromCache(key, info, &net_error, addresses)) {
xunjieli26f90452014-11-10 16:23:022046 source_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_CACHE_HIT);
[email protected]78eac2a2012-03-14 19:09:272047 return net_error;
2048 }
2049 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2050 // http://crbug.com/117655
2051 if (ServeFromHosts(key, info, addresses)) {
xunjieli26f90452014-11-10 16:23:022052 source_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_HOSTS_HIT);
[email protected]78eac2a2012-03-14 19:09:272053 return OK;
2054 }
estarkd1bc206e2015-06-20 00:44:392055
2056 if (ServeLocalhost(key, info, addresses))
2057 return OK;
2058
[email protected]78eac2a2012-03-14 19:09:272059 return ERR_DNS_CACHE_MISS;
[email protected]95a214c2011-08-04 21:50:402060}
2061
2062int HostResolverImpl::ResolveFromCache(const RequestInfo& info,
2063 AddressList* addresses,
2064 const BoundNetLog& source_net_log) {
2065 DCHECK(CalledOnValidThread());
2066 DCHECK(addresses);
2067
[email protected]95a214c2011-08-04 21:50:402068 // Update the net log and notify registered observers.
xunjieli26f90452014-11-10 16:23:022069 LogStartRequest(source_net_log, info);
[email protected]95a214c2011-08-04 21:50:402070
martijna23c8962016-03-04 18:18:512071 IPAddress ip_address;
2072 IPAddress* ip_address_ptr = nullptr;
2073 if (ip_address.AssignFromIPLiteral(info.hostname()))
2074 ip_address_ptr = &ip_address;
[email protected]95a214c2011-08-04 21:50:402075
martijna23c8962016-03-04 18:18:512076 Key key = GetEffectiveKeyForRequest(info, ip_address_ptr, source_net_log);
pauljensen19eb73422015-04-15 23:20:062077
martijna23c8962016-03-04 18:18:512078 int rv = ResolveHelper(key, info, ip_address_ptr, addresses, source_net_log);
xunjieli26f90452014-11-10 16:23:022079 LogFinishRequest(source_net_log, info, rv);
[email protected]95a214c2011-08-04 21:50:402080 return rv;
2081}
2082
juliatuttlec53b19a72016-05-05 13:51:312083void HostResolverImpl::ChangeRequestPriority(RequestHandle req_handle,
2084 RequestPriority priority) {
2085 DCHECK(CalledOnValidThread());
2086 Request* req = reinterpret_cast<Request*>(req_handle);
2087 DCHECK(req);
2088 Job* job = req->job();
2089 DCHECK(job);
2090 job->ChangeRequestPriority(req, priority);
2091}
2092
[email protected]b59ff372009-07-15 22:04:322093void HostResolverImpl::CancelRequest(RequestHandle req_handle) {
[email protected]1ac6af92010-06-03 21:00:142094 DCHECK(CalledOnValidThread());
[email protected]b59ff372009-07-15 22:04:322095 Request* req = reinterpret_cast<Request*>(req_handle);
2096 DCHECK(req);
[email protected]0f292de02012-02-01 22:28:202097 Job* job = req->job();
2098 DCHECK(job);
[email protected]0f292de02012-02-01 22:28:202099 job->CancelRequest(req);
[email protected]b59ff372009-07-15 22:04:322100}
2101
[email protected]a8883e452012-11-17 05:58:062102void HostResolverImpl::SetDnsClientEnabled(bool enabled) {
2103 DCHECK(CalledOnValidThread());
2104#if defined(ENABLE_BUILT_IN_DNS)
2105 if (enabled && !dns_client_) {
2106 SetDnsClient(DnsClient::CreateClient(net_log_));
2107 } else if (!enabled && dns_client_) {
danakj22f90e72016-04-16 01:55:402108 SetDnsClient(std::unique_ptr<DnsClient>());
[email protected]a8883e452012-11-17 05:58:062109 }
2110#endif
2111}
2112
[email protected]489d1a82011-10-12 03:09:112113HostCache* HostResolverImpl::GetHostCache() {
2114 return cache_.get();
2115}
[email protected]95a214c2011-08-04 21:50:402116
danakj22f90e72016-04-16 01:55:402117std::unique_ptr<base::Value> HostResolverImpl::GetDnsConfigAsValue() const {
[email protected]17e92032012-03-29 00:56:242118 // Check if async DNS is disabled.
2119 if (!dns_client_.get())
tfhef3618f2016-01-11 23:07:082120 return nullptr;
[email protected]17e92032012-03-29 00:56:242121
2122 // Check if async DNS is enabled, but we currently have no configuration
2123 // for it.
2124 const DnsConfig* dns_config = dns_client_->GetConfig();
2125 if (dns_config == NULL)
danakj22f90e72016-04-16 01:55:402126 return base::WrapUnique(new base::DictionaryValue());
[email protected]17e92032012-03-29 00:56:242127
2128 return dns_config->ToValue();
2129}
2130
[email protected]95a214c2011-08-04 21:50:402131bool HostResolverImpl::ResolveAsIP(const Key& key,
2132 const RequestInfo& info,
martijna23c8962016-03-04 18:18:512133 const IPAddress* ip_address,
[email protected]95a214c2011-08-04 21:50:402134 int* net_error,
2135 AddressList* addresses) {
2136 DCHECK(addresses);
2137 DCHECK(net_error);
martijna23c8962016-03-04 18:18:512138 if (ip_address == nullptr)
[email protected]95a214c2011-08-04 21:50:402139 return false;
2140
[email protected]95a214c2011-08-04 21:50:402141 *net_error = OK;
martijna23c8962016-03-04 18:18:512142 AddressFamily family = GetAddressFamily(*ip_address);
cbentzel1906f872015-06-05 16:25:252143 if (key.address_family != ADDRESS_FAMILY_UNSPECIFIED &&
2144 key.address_family != family) {
[email protected]1c7cf3f82014-08-07 21:33:482145 // Don't return IPv6 addresses for IPv4 queries, and vice versa.
[email protected]95a214c2011-08-04 21:50:402146 *net_error = ERR_NAME_NOT_RESOLVED;
2147 } else {
martijna23c8962016-03-04 18:18:512148 *addresses = AddressList::CreateFromIPAddress(*ip_address, info.port());
[email protected]7054e78f2012-05-07 21:44:562149 if (key.host_resolver_flags & HOST_RESOLVER_CANONNAME)
2150 addresses->SetDefaultCanonicalName();
[email protected]95a214c2011-08-04 21:50:402151 }
2152 return true;
2153}
2154
2155bool HostResolverImpl::ServeFromCache(const Key& key,
2156 const RequestInfo& info,
[email protected]95a214c2011-08-04 21:50:402157 int* net_error,
2158 AddressList* addresses) {
2159 DCHECK(addresses);
2160 DCHECK(net_error);
2161 if (!info.allow_cached_response() || !cache_.get())
2162 return false;
2163
[email protected]407a30ab2012-08-15 17:16:102164 const HostCache::Entry* cache_entry = cache_->Lookup(
2165 key, base::TimeTicks::Now());
[email protected]95a214c2011-08-04 21:50:402166 if (!cache_entry)
2167 return false;
2168
juliatuttle317860e2016-05-12 14:47:222169 *net_error = cache_entry->error();
[email protected]7054e78f2012-05-07 21:44:562170 if (*net_error == OK) {
[email protected]1339a2a22012-10-17 08:39:432171 if (cache_entry->has_ttl())
juliatuttle317860e2016-05-12 14:47:222172 RecordTTL(cache_entry->ttl());
2173 *addresses = EnsurePortOnAddressList(cache_entry->addresses(), info.port());
[email protected]7054e78f2012-05-07 21:44:562174 }
[email protected]95a214c2011-08-04 21:50:402175 return true;
2176}
2177
[email protected]78eac2a2012-03-14 19:09:272178bool HostResolverImpl::ServeFromHosts(const Key& key,
2179 const RequestInfo& info,
2180 AddressList* addresses) {
2181 DCHECK(addresses);
2182 if (!HaveDnsConfig())
2183 return false;
[email protected]05a79d42013-03-28 07:30:092184 addresses->clear();
2185
[email protected]cb507622012-03-23 16:17:062186 // HOSTS lookups are case-insensitive.
brettw8e2106d2015-08-11 19:30:222187 std::string hostname = base::ToLowerASCII(key.hostname);
[email protected]cb507622012-03-23 16:17:062188
[email protected]05a79d42013-03-28 07:30:092189 const DnsHosts& hosts = dns_client_->GetConfig()->hosts;
2190
[email protected]78eac2a2012-03-14 19:09:272191 // If |address_family| is ADDRESS_FAMILY_UNSPECIFIED other implementations
2192 // (glibc and c-ares) return the first matching line. We have more
2193 // flexibility, but lose implicit ordering.
[email protected]05a79d42013-03-28 07:30:092194 // We prefer IPv6 because "happy eyeballs" will fall back to IPv4 if
2195 // necessary.
2196 if (key.address_family == ADDRESS_FAMILY_IPV6 ||
2197 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
2198 DnsHosts::const_iterator it = hosts.find(
2199 DnsHostsKey(hostname, ADDRESS_FAMILY_IPV6));
2200 if (it != hosts.end())
2201 addresses->push_back(IPEndPoint(it->second, info.port()));
[email protected]78eac2a2012-03-14 19:09:272202 }
2203
[email protected]05a79d42013-03-28 07:30:092204 if (key.address_family == ADDRESS_FAMILY_IPV4 ||
2205 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
2206 DnsHosts::const_iterator it = hosts.find(
2207 DnsHostsKey(hostname, ADDRESS_FAMILY_IPV4));
2208 if (it != hosts.end())
2209 addresses->push_back(IPEndPoint(it->second, info.port()));
2210 }
2211
[email protected]ec666ab22013-04-17 20:05:592212 // If got only loopback addresses and the family was restricted, resolve
2213 // again, without restrictions. See SystemHostResolverCall for rationale.
2214 if ((key.host_resolver_flags &
2215 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6) &&
2216 IsAllIPv4Loopback(*addresses)) {
2217 Key new_key(key);
2218 new_key.address_family = ADDRESS_FAMILY_UNSPECIFIED;
2219 new_key.host_resolver_flags &=
2220 ~HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
2221 return ServeFromHosts(new_key, info, addresses);
2222 }
[email protected]05a79d42013-03-28 07:30:092223 return !addresses->empty();
[email protected]78eac2a2012-03-14 19:09:272224}
2225
estarkd1bc206e2015-06-20 00:44:392226bool HostResolverImpl::ServeLocalhost(const Key& key,
2227 const RequestInfo& info,
2228 AddressList* addresses) {
2229 AddressList resolved_addresses;
2230 if (!ResolveLocalHostname(key.hostname, info.port(), &resolved_addresses))
2231 return false;
2232
2233 addresses->clear();
2234
2235 for (const auto& address : resolved_addresses) {
2236 // Include the address if:
2237 // - caller didn't specify an address family, or
2238 // - caller specifically asked for the address family of this address, or
2239 // - this is an IPv6 address and caller specifically asked for IPv4 due
2240 // to lack of detected IPv6 support. (See SystemHostResolverCall for
2241 // rationale).
2242 if (key.address_family == ADDRESS_FAMILY_UNSPECIFIED ||
2243 key.address_family == address.GetFamily() ||
2244 (address.GetFamily() == ADDRESS_FAMILY_IPV6 &&
2245 key.address_family == ADDRESS_FAMILY_IPV4 &&
2246 (key.host_resolver_flags &
2247 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6))) {
2248 addresses->push_back(address);
2249 }
2250 }
2251
2252 return true;
2253}
2254
[email protected]16ee26d2012-03-08 03:34:352255void HostResolverImpl::CacheResult(const Key& key,
[email protected]1339a2a22012-10-17 08:39:432256 const HostCache::Entry& entry,
[email protected]16ee26d2012-03-08 03:34:352257 base::TimeDelta ttl) {
2258 if (cache_.get())
[email protected]1339a2a22012-10-17 08:39:432259 cache_->Set(key, entry, base::TimeTicks::Now(), ttl);
[email protected]ef4c40c2010-09-01 14:42:032260}
2261
[email protected]0f292de02012-02-01 22:28:202262void HostResolverImpl::RemoveJob(Job* job) {
2263 DCHECK(job);
[email protected]16ee26d2012-03-08 03:34:352264 JobMap::iterator it = jobs_.find(job->key());
2265 if (it != jobs_.end() && it->second == job)
2266 jobs_.erase(it);
[email protected]b59ff372009-07-15 22:04:322267}
2268
[email protected]137af622010-02-05 02:14:352269HostResolverImpl::Key HostResolverImpl::GetEffectiveKeyForRequest(
pauljensen19eb73422015-04-15 23:20:062270 const RequestInfo& info,
martijna23c8962016-03-04 18:18:512271 const IPAddress* ip_address,
sergeyub8cdc212015-05-14 18:50:372272 const BoundNetLog& net_log) {
[email protected]eaf3a3b2010-09-03 20:34:272273 HostResolverFlags effective_flags =
2274 info.host_resolver_flags() | additional_resolver_flags_;
[email protected]137af622010-02-05 02:14:352275 AddressFamily effective_address_family = info.address_family();
[email protected]9db6f702013-04-10 18:10:512276
2277 if (info.address_family() == ADDRESS_FAMILY_UNSPECIFIED) {
cbentzel1906f872015-06-05 16:25:252278 if (!use_local_ipv6_ &&
pauljensen19eb73422015-04-15 23:20:062279 // When resolving IPv4 literals, there's no need to probe for IPv6.
2280 // When resolving IPv6 literals, there's no benefit to artificially
2281 // limiting our resolution based on a probe. Prior logic ensures
2282 // that this query is UNSPECIFIED (see info.address_family()
cbentzel1906f872015-06-05 16:25:252283 // check above) so the code requesting the resolution should be amenable
2284 // to receiving a IPv6 resolution.
martijna23c8962016-03-04 18:18:512285 ip_address == nullptr) {
sergeyub8cdc212015-05-14 18:50:372286 if (!IsIPv6Reachable(net_log)) {
[email protected]ac0b52e2013-04-21 01:26:162287 effective_address_family = ADDRESS_FAMILY_IPV4;
2288 effective_flags |= HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
2289 }
[email protected]9db6f702013-04-10 18:10:512290 }
2291 }
2292
estarkd1bc206e2015-06-20 00:44:392293 return Key(info.hostname(), effective_address_family, effective_flags);
[email protected]137af622010-02-05 02:14:352294}
2295
sergeyub8cdc212015-05-14 18:50:372296bool HostResolverImpl::IsIPv6Reachable(const BoundNetLog& net_log) {
2297 base::TimeTicks now = base::TimeTicks::Now();
2298 bool cached = true;
2299 if ((now - last_ipv6_probe_time_).InMilliseconds() > kIPv6ProbePeriodMs) {
martijna23c8962016-03-04 18:18:512300 last_ipv6_probe_result_ =
2301 IsGloballyReachable(IPAddress(kIPv6ProbeAddress), net_log);
sergeyub8cdc212015-05-14 18:50:372302 last_ipv6_probe_time_ = now;
2303 cached = false;
2304 }
2305 net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_IPV6_REACHABILITY_CHECK,
2306 base::Bind(&NetLogIPv6AvailableCallback,
2307 last_ipv6_probe_result_, cached));
2308 return last_ipv6_probe_result_;
2309}
2310
mmenke91c17162016-06-02 16:03:232311void HostResolverImpl::RunLoopbackProbeJob() {
2312 new LoopbackProbeJob(weak_ptr_factory_.GetWeakPtr(),
2313 worker_task_runner_.get());
2314}
2315
[email protected]35ddc282010-09-21 23:42:062316void HostResolverImpl::AbortAllInProgressJobs() {
[email protected]b3601bc22012-02-21 21:23:202317 // In Abort, a Request callback could spawn new Jobs with matching keys, so
2318 // first collect and remove all running jobs from |jobs_|.
danakj22f90e72016-04-16 01:55:402319 std::vector<std::unique_ptr<Job>> jobs_to_abort;
[email protected]0f292de02012-02-01 22:28:202320 for (JobMap::iterator it = jobs_.begin(); it != jobs_.end(); ) {
2321 Job* job = it->second;
[email protected]0f292de02012-02-01 22:28:202322 if (job->is_running()) {
danakj22f90e72016-04-16 01:55:402323 jobs_to_abort.push_back(base::WrapUnique(job));
[email protected]b3601bc22012-02-21 21:23:202324 jobs_.erase(it++);
[email protected]0f292de02012-02-01 22:28:202325 } else {
[email protected]b3601bc22012-02-21 21:23:202326 DCHECK(job->is_queued());
2327 ++it;
[email protected]0f292de02012-02-01 22:28:202328 }
[email protected]ef4c40c2010-09-01 14:42:032329 }
[email protected]b3601bc22012-02-21 21:23:202330
[email protected]daae1322013-09-05 18:26:502331 // Pause the dispatcher so it won't start any new dispatcher jobs while
2332 // aborting the old ones. This is needed so that it won't start the second
2333 // DnsTransaction for a job in |jobs_to_abort| if the DnsConfig just became
2334 // invalid.
[email protected]106ccd2c2014-06-17 09:21:002335 PrioritizedDispatcher::Limits limits = dispatcher_->GetLimits();
2336 dispatcher_->SetLimits(
[email protected]daae1322013-09-05 18:26:502337 PrioritizedDispatcher::Limits(limits.reserved_slots.size(), 0));
[email protected]70c04ab2013-08-22 16:05:122338
[email protected]57a48d32012-03-03 00:04:552339 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072340 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]57a48d32012-03-03 00:04:552341
[email protected]16ee26d2012-03-08 03:34:352342 // Then Abort them.
[email protected]11fbca0b2013-06-02 23:37:212343 for (size_t i = 0; self.get() && i < jobs_to_abort.size(); ++i) {
[email protected]57a48d32012-03-03 00:04:552344 jobs_to_abort[i]->Abort();
olli.raulaa21e9eb72015-12-17 08:18:112345 ignore_result(jobs_to_abort[i].release());
[email protected]b3601bc22012-02-21 21:23:202346 }
[email protected]daae1322013-09-05 18:26:502347
2348 if (self)
[email protected]106ccd2c2014-06-17 09:21:002349 dispatcher_->SetLimits(limits);
[email protected]daae1322013-09-05 18:26:502350}
2351
2352void HostResolverImpl::AbortDnsTasks() {
2353 // Pause the dispatcher so it won't start any new dispatcher jobs while
2354 // aborting the old ones. This is needed so that it won't start the second
2355 // DnsTransaction for a job if the DnsConfig just changed.
[email protected]106ccd2c2014-06-17 09:21:002356 PrioritizedDispatcher::Limits limits = dispatcher_->GetLimits();
2357 dispatcher_->SetLimits(
[email protected]daae1322013-09-05 18:26:502358 PrioritizedDispatcher::Limits(limits.reserved_slots.size(), 0));
2359
2360 for (JobMap::iterator it = jobs_.begin(); it != jobs_.end(); ++it)
2361 it->second->AbortDnsTask();
[email protected]106ccd2c2014-06-17 09:21:002362 dispatcher_->SetLimits(limits);
[email protected]ef4c40c2010-09-01 14:42:032363}
2364
[email protected]78eac2a2012-03-14 19:09:272365void HostResolverImpl::TryServingAllJobsFromHosts() {
2366 if (!HaveDnsConfig())
2367 return;
2368
2369 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2370 // http://crbug.com/117655
2371
2372 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072373 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]78eac2a2012-03-14 19:09:272374
[email protected]11fbca0b2013-06-02 23:37:212375 for (JobMap::iterator it = jobs_.begin(); self.get() && it != jobs_.end();) {
[email protected]78eac2a2012-03-14 19:09:272376 Job* job = it->second;
2377 ++it;
2378 // This could remove |job| from |jobs_|, but iterator will remain valid.
2379 job->ServeFromHosts();
2380 }
2381}
2382
[email protected]be1a48b2011-01-20 00:12:132383void HostResolverImpl::OnIPAddressChanged() {
[email protected]62e86ba2013-01-29 18:59:162384 resolved_known_ipv6_hostname_ = false;
sergeyub8cdc212015-05-14 18:50:372385 last_ipv6_probe_time_ = base::TimeTicks();
[email protected]12faa4c2012-11-06 04:44:182386 // Abandon all ProbeJobs.
2387 probe_weak_ptr_factory_.InvalidateWeakPtrs();
[email protected]be1a48b2011-01-20 00:12:132388 if (cache_.get())
2389 cache_->clear();
[email protected]7c466e92013-07-20 01:44:482390#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
mmenke91c17162016-06-02 16:03:232391 RunLoopbackProbeJob();
[email protected]be1a48b2011-01-20 00:12:132392#endif
2393 AbortAllInProgressJobs();
2394 // |this| may be deleted inside AbortAllInProgressJobs().
2395}
2396
ttuttlecf1158bf2016-03-18 16:37:442397void HostResolverImpl::OnConnectionTypeChanged(
2398 NetworkChangeNotifier::ConnectionType type) {
2399 proc_params_.unresponsive_delay =
2400 GetTimeDeltaForConnectionTypeFromFieldTrialOrDefault(
2401 "DnsUnresponsiveDelayMsByConnectionType",
2402 base::TimeDelta::FromMilliseconds(kDnsDefaultUnresponsiveDelayMs),
2403 type);
2404}
2405
pauljensen101ed372015-04-17 00:11:422406void HostResolverImpl::OnInitialDNSConfigRead() {
2407 UpdateDNSConfig(false);
2408}
2409
[email protected]bb0e34542012-08-31 19:52:402410void HostResolverImpl::OnDNSChanged() {
pauljensen101ed372015-04-17 00:11:422411 UpdateDNSConfig(true);
2412}
2413
2414void HostResolverImpl::UpdateDNSConfig(bool config_changed) {
[email protected]bb0e34542012-08-31 19:52:402415 DnsConfig dns_config;
2416 NetworkChangeNotifier::GetDnsConfig(&dns_config);
[email protected]ec666ab22013-04-17 20:05:592417
[email protected]b4481b222012-03-16 17:13:112418 if (net_log_) {
2419 net_log_->AddGlobalEntry(
2420 NetLog::TYPE_DNS_CONFIG_CHANGED,
[email protected]cd565142012-06-12 16:21:452421 base::Bind(&NetLogDnsConfigCallback, &dns_config));
[email protected]b4481b222012-03-16 17:13:112422 }
2423
[email protected]01b3b9d2012-08-13 16:18:142424 // TODO(szym): Remove once http://crbug.com/137914 is resolved.
[email protected]d7b9a2b2012-05-31 22:31:192425 received_dns_config_ = dns_config.IsValid();
[email protected]c9fa8f312013-09-17 12:24:522426 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
2427 use_local_ipv6_ = !dns_config.IsValid() || dns_config.use_local_ipv6;
[email protected]78eac2a2012-03-14 19:09:272428
[email protected]a8883e452012-11-17 05:58:062429 num_dns_failures_ = 0;
2430
[email protected]01b3b9d2012-08-13 16:18:142431 // We want a new DnsSession in place, before we Abort running Jobs, so that
2432 // the newly started jobs use the new config.
[email protected]f0f602bd2012-11-15 18:01:022433 if (dns_client_.get()) {
[email protected]d7b9a2b2012-05-31 22:31:192434 dns_client_->SetConfig(dns_config);
pauljensen101ed372015-04-17 00:11:422435 if (dns_client_->GetConfig()) {
[email protected]f0f602bd2012-11-15 18:01:022436 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
pauljensen101ed372015-04-17 00:11:422437 // If we just switched DnsClients, restart jobs using new resolver.
2438 // TODO(pauljensen): Is this necessary?
2439 config_changed = true;
2440 }
[email protected]f0f602bd2012-11-15 18:01:022441 }
[email protected]01b3b9d2012-08-13 16:18:142442
pauljensen101ed372015-04-17 00:11:422443 if (config_changed) {
2444 // If the DNS server has changed, existing cached info could be wrong so we
2445 // have to drop our internal cache :( Note that OS level DNS caches, such
2446 // as NSCD's cache should be dropped automatically by the OS when
2447 // resolv.conf changes so we don't need to do anything to clear that cache.
2448 if (cache_.get())
2449 cache_->clear();
[email protected]01b3b9d2012-08-13 16:18:142450
pauljensen101ed372015-04-17 00:11:422451 // Life check to bail once |this| is deleted.
2452 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]f0f602bd2012-11-15 18:01:022453
pauljensen101ed372015-04-17 00:11:422454 // Existing jobs will have been sent to the original server so they need to
2455 // be aborted.
2456 AbortAllInProgressJobs();
[email protected]01b3b9d2012-08-13 16:18:142457
pauljensen101ed372015-04-17 00:11:422458 // |this| may be deleted inside AbortAllInProgressJobs().
2459 if (self.get())
2460 TryServingAllJobsFromHosts();
2461 }
[email protected]78eac2a2012-03-14 19:09:272462}
2463
2464bool HostResolverImpl::HaveDnsConfig() const {
[email protected]32b1dbcf2013-01-26 03:48:252465 // Use DnsClient only if it's fully configured and there is no override by
2466 // ScopedDefaultHostResolverProc.
2467 // The alternative is to use NetworkChangeNotifier to override DnsConfig,
2468 // but that would introduce construction order requirements for NCN and SDHRP.
[email protected]90499482013-06-01 00:39:502469 return (dns_client_.get() != NULL) && (dns_client_->GetConfig() != NULL) &&
2470 !(proc_params_.resolver_proc.get() == NULL &&
[email protected]32b1dbcf2013-01-26 03:48:252471 HostResolverProc::GetDefault() != NULL);
[email protected]b3601bc22012-02-21 21:23:202472}
2473
[email protected]1ffdda82012-12-12 23:04:222474void HostResolverImpl::OnDnsTaskResolve(int net_error) {
[email protected]f0f602bd2012-11-15 18:01:022475 DCHECK(dns_client_);
[email protected]1ffdda82012-12-12 23:04:222476 if (net_error == OK) {
[email protected]f0f602bd2012-11-15 18:01:022477 num_dns_failures_ = 0;
2478 return;
2479 }
2480 ++num_dns_failures_;
2481 if (num_dns_failures_ < kMaximumDnsFailures)
2482 return;
[email protected]daae1322013-09-05 18:26:502483
2484 // Disable DnsClient until the next DNS change. Must be done before aborting
2485 // DnsTasks, since doing so may start new jobs.
[email protected]f0f602bd2012-11-15 18:01:022486 dns_client_->SetConfig(DnsConfig());
[email protected]daae1322013-09-05 18:26:502487
2488 // Switch jobs with active DnsTasks over to using ProcTasks.
2489 AbortDnsTasks();
2490
[email protected]f0f602bd2012-11-15 18:01:022491 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", false);
davidbenad6fc442015-05-18 20:59:132492 UMA_HISTOGRAM_SPARSE_SLOWLY("AsyncDNS.DnsClientDisabledReason",
2493 std::abs(net_error));
[email protected]f0f602bd2012-11-15 18:01:022494}
2495
danakj22f90e72016-04-16 01:55:402496void HostResolverImpl::SetDnsClient(std::unique_ptr<DnsClient> dns_client) {
[email protected]daae1322013-09-05 18:26:502497 // DnsClient and config must be updated before aborting DnsTasks, since doing
2498 // so may start new jobs.
dchengc7eeda422015-12-26 03:56:482499 dns_client_ = std::move(dns_client);
[email protected]daae1322013-09-05 18:26:502500 if (dns_client_ && !dns_client_->GetConfig() &&
2501 num_dns_failures_ < kMaximumDnsFailures) {
2502 DnsConfig dns_config;
2503 NetworkChangeNotifier::GetDnsConfig(&dns_config);
2504 dns_client_->SetConfig(dns_config);
2505 num_dns_failures_ = 0;
2506 if (dns_client_->GetConfig())
2507 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
[email protected]a8883e452012-11-17 05:58:062508 }
[email protected]daae1322013-09-05 18:26:502509
2510 AbortDnsTasks();
[email protected]a8883e452012-11-17 05:58:062511}
2512
[email protected]b59ff372009-07-15 22:04:322513} // namespace net