blob: 5fc531bbf46fb8486d335e0fe833efb7fdefff26 [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"
27#include "base/debug/stack_trace.h"
Avi Drissman13fc8932015-12-20 04:40:4628#include "base/macros.h"
[email protected]1e9bbd22010-10-15 16:42:4529#include "base/metrics/field_trial.h"
davidbenad6fc442015-05-18 20:59:1330#include "base/metrics/histogram_macros.h"
31#include "base/metrics/sparse_histogram.h"
eromane1867242015-04-23 23:07:4432#include "base/profiler/scoped_tracker.h"
anujk.sharma7c907f02015-05-29 02:55:4433#include "base/single_thread_task_runner.h"
[email protected]7286e3fc2011-07-19 22:13:2434#include "base/stl_util.h"
[email protected]be528af2013-06-11 07:39:4835#include "base/strings/string_util.h"
[email protected]750b2f3c2013-06-07 18:41:0536#include "base/strings/utf_string_conversions.h"
gabf767595f2016-05-11 18:50:3537#include "base/threading/thread_task_runner_handle.h"
[email protected]ac9ba8fe2010-12-30 18:08:3638#include "base/threading/worker_pool.h"
[email protected]66e96c42013-06-28 15:20:3139#include "base/time/time.h"
ssid6d6b40102016-04-05 18:59:5640#include "base/trace_event/trace_event.h"
[email protected]21526002010-05-16 19:42:4641#include "base/values.h"
[email protected]b3601bc22012-02-21 21:23:2042#include "net/base/address_family.h"
[email protected]b59ff372009-07-15 22:04:3243#include "net/base/address_list.h"
[email protected]ee094b82010-08-24 15:55:5144#include "net/base/host_port_pair.h"
martijna23c8962016-03-04 18:18:5145#include "net/base/ip_address.h"
[email protected]1c7cf3f82014-08-07 21:33:4846#include "net/base/ip_endpoint.h"
[email protected]2bb04442010-08-18 18:01:1547#include "net/base/net_errors.h"
tfarina9ed7f8c52016-02-19 17:50:1848#include "net/base/url_util.h"
[email protected]0adcb2b2012-08-15 21:30:4649#include "net/dns/address_sorter.h"
[email protected]78eac2a2012-03-14 19:09:2750#include "net/dns/dns_client.h"
[email protected]b3601bc22012-02-21 21:23:2051#include "net/dns/dns_config_service.h"
52#include "net/dns/dns_protocol.h"
tfarina47598f042015-10-07 23:08:3553#include "net/dns/dns_reloader.h"
[email protected]b3601bc22012-02-21 21:23:2054#include "net/dns/dns_response.h"
[email protected]b3601bc22012-02-21 21:23:2055#include "net/dns/dns_transaction.h"
tfarina77021d62015-10-11 20:19:0356#include "net/dns/dns_util.h"
[email protected]f2cb3cf2013-03-21 01:40:5357#include "net/dns/host_resolver_proc.h"
eroman87c53d62015-04-02 06:51:0758#include "net/log/net_log.h"
[email protected]9db6f702013-04-10 18:10:5159#include "net/socket/client_socket_factory.h"
60#include "net/udp/datagram_client_socket.h"
pauljensen370f1c72015-02-17 16:59:1461#include "url/url_canon_ip.h"
[email protected]b59ff372009-07-15 22:04:3262
63#if defined(OS_WIN)
64#include "net/base/winsock_init.h"
65#endif
66
67namespace net {
68
[email protected]e95d3aca2010-01-11 22:47:4369namespace {
70
ttuttlecf1158bf2016-03-18 16:37:4471// Default delay between calls to the system resolver for the same hostname.
72// (Can be overridden by field trial.)
73const int64_t kDnsDefaultUnresponsiveDelayMs = 6000;
74
[email protected]6e78dfb2011-07-28 21:34:4775// Limit the size of hostnames that will be resolved to combat issues in
76// some platform's resolvers.
77const size_t kMaxHostLength = 4096;
78
[email protected]a2730882012-01-21 00:56:2779// Default TTL for successful resolutions with ProcTask.
80const unsigned kCacheEntryTTLSeconds = 60;
81
[email protected]b3601bc22012-02-21 21:23:2082// Default TTL for unsuccessful resolutions with ProcTask.
83const unsigned kNegativeCacheEntryTTLSeconds = 0;
84
[email protected]895123222012-10-25 15:21:1785// Minimum TTL for successful resolutions with DnsTask.
86const unsigned kMinimumTTLSeconds = kCacheEntryTTLSeconds;
87
sergeyub8cdc212015-05-14 18:50:3788// Time between IPv6 probes, i.e. for how long results of each IPv6 probe are
89// cached.
90const int kIPv6ProbePeriodMs = 1000;
91
92// Google DNS address used for IPv6 probes.
93const uint8_t kIPv6ProbeAddress[] =
94 { 0x20, 0x01, 0x48, 0x60, 0x48, 0x60, 0x00, 0x00,
95 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x88 };
96
[email protected]24f4bab2010-10-15 01:27:1197// We use a separate histogram name for each platform to facilitate the
98// display of error codes by their symbolic name (since each platform has
99// different mappings).
100const char kOSErrorsForGetAddrinfoHistogramName[] =
101#if defined(OS_WIN)
102 "Net.OSErrorsForGetAddrinfo_Win";
103#elif defined(OS_MACOSX)
104 "Net.OSErrorsForGetAddrinfo_Mac";
105#elif defined(OS_LINUX)
106 "Net.OSErrorsForGetAddrinfo_Linux";
107#else
108 "Net.OSErrorsForGetAddrinfo";
109#endif
110
[email protected]c89b2442011-05-26 14:28:27111// Gets a list of the likely error codes that getaddrinfo() can return
112// (non-exhaustive). These are the error codes that we will track via
113// a histogram.
114std::vector<int> GetAllGetAddrinfoOSErrors() {
115 int os_errors[] = {
116#if defined(OS_POSIX)
[email protected]23f771162011-06-02 18:37:51117#if !defined(OS_FREEBSD)
[email protected]39588992011-07-11 19:54:37118#if !defined(OS_ANDROID)
[email protected]c48aef92011-11-22 23:41:45119 // EAI_ADDRFAMILY has been declared obsolete in Android's and
120 // FreeBSD's netdb.h.
[email protected]c89b2442011-05-26 14:28:27121 EAI_ADDRFAMILY,
[email protected]39588992011-07-11 19:54:37122#endif
[email protected]c48aef92011-11-22 23:41:45123 // EAI_NODATA has been declared obsolete in FreeBSD's netdb.h.
[email protected]23f771162011-06-02 18:37:51124 EAI_NODATA,
125#endif
[email protected]c89b2442011-05-26 14:28:27126 EAI_AGAIN,
127 EAI_BADFLAGS,
128 EAI_FAIL,
129 EAI_FAMILY,
130 EAI_MEMORY,
[email protected]c89b2442011-05-26 14:28:27131 EAI_NONAME,
132 EAI_SERVICE,
133 EAI_SOCKTYPE,
134 EAI_SYSTEM,
135#elif defined(OS_WIN)
136 // See: http://msdn.microsoft.com/en-us/library/ms738520(VS.85).aspx
137 WSA_NOT_ENOUGH_MEMORY,
138 WSAEAFNOSUPPORT,
139 WSAEINVAL,
140 WSAESOCKTNOSUPPORT,
141 WSAHOST_NOT_FOUND,
142 WSANO_DATA,
143 WSANO_RECOVERY,
144 WSANOTINITIALISED,
145 WSATRY_AGAIN,
146 WSATYPE_NOT_FOUND,
147 // The following are not in doc, but might be to appearing in results :-(.
148 WSA_INVALID_HANDLE,
149#endif
150 };
151
152 // Ensure all errors are positive, as histogram only tracks positive values.
153 for (size_t i = 0; i < arraysize(os_errors); ++i) {
154 os_errors[i] = std::abs(os_errors[i]);
155 }
156
157 return base::CustomHistogram::ArrayToCustomRanges(os_errors,
158 arraysize(os_errors));
159}
160
[email protected]1def74c2012-03-22 20:07:00161enum DnsResolveStatus {
162 RESOLVE_STATUS_DNS_SUCCESS = 0,
163 RESOLVE_STATUS_PROC_SUCCESS,
164 RESOLVE_STATUS_FAIL,
[email protected]1d932852012-06-19 19:40:33165 RESOLVE_STATUS_SUSPECT_NETBIOS,
[email protected]1def74c2012-03-22 20:07:00166 RESOLVE_STATUS_MAX
167};
168
eroman91dd3602015-03-26 03:46:33169// ICANN uses this localhost address to indicate a name collision.
170//
171// The policy in Chromium is to fail host resolving if it resolves to
172// this special address.
173//
174// Not however that IP literals are exempt from this policy, so it is still
175// possible to navigate to http://127.0.53.53/ directly.
176//
177// For more details: https://www.icann.org/news/announcement-2-2014-08-01-en
martijna23c8962016-03-04 18:18:51178const uint8_t kIcanNameCollisionIp[] = {127, 0, 53, 53};
eroman91dd3602015-03-26 03:46:33179
[email protected]1def74c2012-03-22 20:07:00180void UmaAsyncDnsResolveStatus(DnsResolveStatus result) {
181 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ResolveStatus",
182 result,
183 RESOLVE_STATUS_MAX);
184}
185
[email protected]1d932852012-06-19 19:40:33186bool ResemblesNetBIOSName(const std::string& hostname) {
187 return (hostname.size() < 16) && (hostname.find('.') == std::string::npos);
188}
189
190// True if |hostname| ends with either ".local" or ".local.".
191bool ResemblesMulticastDNSName(const std::string& hostname) {
192 DCHECK(!hostname.empty());
193 const char kSuffix[] = ".local.";
194 const size_t kSuffixLen = sizeof(kSuffix) - 1;
195 const size_t kSuffixLenTrimmed = kSuffixLen - 1;
196 if (hostname[hostname.size() - 1] == '.') {
197 return hostname.size() > kSuffixLen &&
198 !hostname.compare(hostname.size() - kSuffixLen, kSuffixLen, kSuffix);
199 }
200 return hostname.size() > kSuffixLenTrimmed &&
201 !hostname.compare(hostname.size() - kSuffixLenTrimmed, kSuffixLenTrimmed,
202 kSuffix, kSuffixLenTrimmed);
203}
204
[email protected]34e61362013-07-24 20:41:56205// Attempts to connect a UDP socket to |dest|:53.
martijna23c8962016-03-04 18:18:51206bool IsGloballyReachable(const IPAddress& dest, const BoundNetLog& net_log) {
eroman0eb394e2015-04-30 23:25:46207 // TODO(eroman): Remove ScopedTracker below once crbug.com/455942 is fixed.
208 tracked_objects::ScopedTracker tracking_profile_1(
eroman2734a9d2015-05-05 19:24:38209 FROM_HERE_WITH_EXPLICIT_FUNCTION("455942 IsGloballyReachable"));
eroman0eb394e2015-04-30 23:25:46210
danakj22f90e72016-04-16 01:55:40211 std::unique_ptr<DatagramClientSocket> socket(
[email protected]9db6f702013-04-10 18:10:51212 ClientSocketFactory::GetDefaultFactory()->CreateDatagramClientSocket(
danakj22f90e72016-04-16 01:55:40213 DatagramSocket::DEFAULT_BIND, RandIntCallback(), net_log.net_log(),
[email protected]2b74a2f2013-07-23 19:37:38214 net_log.source()));
[email protected]34e61362013-07-24 20:41:56215 int rv = socket->Connect(IPEndPoint(dest, 53));
[email protected]e9051722013-04-12 21:58:18216 if (rv != OK)
217 return false;
218 IPEndPoint endpoint;
219 rv = socket->GetLocalAddress(&endpoint);
220 if (rv != OK)
221 return false;
[email protected]1c7cf3f82014-08-07 21:33:48222 DCHECK_EQ(ADDRESS_FAMILY_IPV6, endpoint.GetFamily());
martijna23c8962016-03-04 18:18:51223 const IPAddress& address = endpoint.address();
224
225 bool is_link_local =
226 (address.bytes()[0] == 0xFE) && ((address.bytes()[1] & 0xC0) == 0x80);
[email protected]e9051722013-04-12 21:58:18227 if (is_link_local)
228 return false;
martijna23c8962016-03-04 18:18:51229
Avi Drissman13fc8932015-12-20 04:40:46230 const uint8_t kTeredoPrefix[] = {0x20, 0x01, 0, 0};
martijna23c8962016-03-04 18:18:51231 if (IPAddressStartsWith(address, kTeredoPrefix))
[email protected]e9051722013-04-12 21:58:18232 return false;
martijna23c8962016-03-04 18:18:51233
[email protected]e9051722013-04-12 21:58:18234 return true;
[email protected]9db6f702013-04-10 18:10:51235}
236
[email protected]51b9a6b2012-06-25 21:50:29237// Provide a common macro to simplify code and readability. We must use a
238// macro as the underlying HISTOGRAM macro creates static variables.
239#define DNS_HISTOGRAM(name, time) UMA_HISTOGRAM_CUSTOM_TIMES(name, time, \
240 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromHours(1), 100)
241
242// A macro to simplify code and readability.
243#define DNS_HISTOGRAM_BY_PRIORITY(basename, priority, time) \
244 do { \
245 switch (priority) { \
246 case HIGHEST: DNS_HISTOGRAM(basename "_HIGHEST", time); break; \
247 case MEDIUM: DNS_HISTOGRAM(basename "_MEDIUM", time); break; \
248 case LOW: DNS_HISTOGRAM(basename "_LOW", time); break; \
249 case LOWEST: DNS_HISTOGRAM(basename "_LOWEST", time); break; \
250 case IDLE: DNS_HISTOGRAM(basename "_IDLE", time); break; \
251 default: NOTREACHED(); break; \
252 } \
253 DNS_HISTOGRAM(basename, time); \
254 } while (0)
255
256// Record time from Request creation until a valid DNS response.
257void RecordTotalTime(bool had_dns_config,
258 bool speculative,
259 base::TimeDelta duration) {
260 if (had_dns_config) {
261 if (speculative) {
262 DNS_HISTOGRAM("AsyncDNS.TotalTime_speculative", duration);
263 } else {
264 DNS_HISTOGRAM("AsyncDNS.TotalTime", duration);
265 }
266 } else {
267 if (speculative) {
268 DNS_HISTOGRAM("DNS.TotalTime_speculative", duration);
269 } else {
270 DNS_HISTOGRAM("DNS.TotalTime", duration);
271 }
272 }
273}
274
[email protected]1339a2a22012-10-17 08:39:43275void RecordTTL(base::TimeDelta ttl) {
276 UMA_HISTOGRAM_CUSTOM_TIMES("AsyncDNS.TTL", ttl,
277 base::TimeDelta::FromSeconds(1),
278 base::TimeDelta::FromDays(1), 100);
279}
280
[email protected]16c2bd72013-06-28 01:19:22281bool ConfigureAsyncDnsNoFallbackFieldTrial() {
282 const bool kDefault = false;
283
284 // Configure the AsyncDns field trial as follows:
285 // groups AsyncDnsNoFallbackA and AsyncDnsNoFallbackB: return true,
286 // groups AsyncDnsA and AsyncDnsB: return false,
287 // groups SystemDnsA and SystemDnsB: return false,
288 // otherwise (trial absent): return default.
289 std::string group_name = base::FieldTrialList::FindFullName("AsyncDns");
brettw3a2c6902015-07-06 19:43:29290 if (!group_name.empty()) {
291 return base::StartsWith(group_name, "AsyncDnsNoFallback",
292 base::CompareCase::INSENSITIVE_ASCII);
293 }
[email protected]16c2bd72013-06-28 01:19:22294 return kDefault;
295}
296
[email protected]d7b9a2b2012-05-31 22:31:19297//-----------------------------------------------------------------------------
298
Avi Drissman13fc8932015-12-20 04:40:46299AddressList EnsurePortOnAddressList(const AddressList& list, uint16_t port) {
[email protected]895123222012-10-25 15:21:17300 if (list.empty() || list.front().port() == port)
301 return list;
302 return AddressList::CopyWithPort(list, port);
[email protected]7054e78f2012-05-07 21:44:56303}
304
[email protected]ec666ab22013-04-17 20:05:59305// Returns true if |addresses| contains only IPv4 loopback addresses.
306bool IsAllIPv4Loopback(const AddressList& addresses) {
307 for (unsigned i = 0; i < addresses.size(); ++i) {
martijna23c8962016-03-04 18:18:51308 const IPAddress& address = addresses[i].address();
[email protected]ec666ab22013-04-17 20:05:59309 switch (addresses[i].GetFamily()) {
310 case ADDRESS_FAMILY_IPV4:
martijna23c8962016-03-04 18:18:51311 if (address.bytes()[0] != 127)
[email protected]ec666ab22013-04-17 20:05:59312 return false;
313 break;
314 case ADDRESS_FAMILY_IPV6:
315 return false;
316 default:
317 NOTREACHED();
318 return false;
319 }
320 }
321 return true;
322}
323
[email protected]cd565142012-06-12 16:21:45324// Creates NetLog parameters when the resolve failed.
danakj22f90e72016-04-16 01:55:40325std::unique_ptr<base::Value> NetLogProcTaskFailedCallback(
Avi Drissman13fc8932015-12-20 04:40:46326 uint32_t attempt_number,
eroman001c3742015-04-23 03:11:17327 int net_error,
328 int os_error,
329 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40330 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]cd565142012-06-12 16:21:45331 if (attempt_number)
332 dict->SetInteger("attempt_number", attempt_number);
[email protected]21526002010-05-16 19:42:46333
[email protected]cd565142012-06-12 16:21:45334 dict->SetInteger("net_error", net_error);
[email protected]13024882011-05-18 23:19:16335
[email protected]cd565142012-06-12 16:21:45336 if (os_error) {
337 dict->SetInteger("os_error", os_error);
[email protected]21526002010-05-16 19:42:46338#if defined(OS_POSIX)
[email protected]cd565142012-06-12 16:21:45339 dict->SetString("os_error_string", gai_strerror(os_error));
[email protected]21526002010-05-16 19:42:46340#elif defined(OS_WIN)
[email protected]cd565142012-06-12 16:21:45341 // Map the error code to a human-readable string.
342 LPWSTR error_string = NULL;
Peter Kastingbe940e92014-11-20 23:14:08343 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
344 0, // Use the internal message table.
345 os_error,
346 0, // Use default language.
347 (LPWSTR)&error_string,
348 0, // Buffer size.
349 0); // Arguments (unused).
[email protected]ad65a3e2013-12-25 18:18:01350 dict->SetString("os_error_string", base::WideToUTF8(error_string));
[email protected]cd565142012-06-12 16:21:45351 LocalFree(error_string);
[email protected]21526002010-05-16 19:42:46352#endif
[email protected]21526002010-05-16 19:42:46353 }
354
dchengc7eeda422015-12-26 03:56:48355 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45356}
[email protected]a9813302012-04-28 09:29:28357
[email protected]cd565142012-06-12 16:21:45358// Creates NetLog parameters when the DnsTask failed.
danakj22f90e72016-04-16 01:55:40359std::unique_ptr<base::Value> NetLogDnsTaskFailedCallback(
estade5e5529d2015-05-21 20:59:11360 int net_error,
361 int dns_error,
362 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40363 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]cd565142012-06-12 16:21:45364 dict->SetInteger("net_error", net_error);
365 if (dns_error)
366 dict->SetInteger("dns_error", dns_error);
dchengc7eeda422015-12-26 03:56:48367 return std::move(dict);
[email protected]ee094b82010-08-24 15:55:51368};
369
[email protected]cd565142012-06-12 16:21:45370// Creates NetLog parameters containing the information in a RequestInfo object,
371// along with the associated NetLog::Source.
danakj22f90e72016-04-16 01:55:40372std::unique_ptr<base::Value> NetLogRequestInfoCallback(
estade5e5529d2015-05-21 20:59:11373 const HostResolver::RequestInfo* info,
374 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40375 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]b3601bc22012-02-21 21:23:20376
[email protected]cd565142012-06-12 16:21:45377 dict->SetString("host", info->host_port_pair().ToString());
378 dict->SetInteger("address_family",
379 static_cast<int>(info->address_family()));
380 dict->SetBoolean("allow_cached_response", info->allow_cached_response());
381 dict->SetBoolean("is_speculative", info->is_speculative());
dchengc7eeda422015-12-26 03:56:48382 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45383}
[email protected]b3601bc22012-02-21 21:23:20384
[email protected]cd565142012-06-12 16:21:45385// Creates NetLog parameters for the creation of a HostResolverImpl::Job.
danakj22f90e72016-04-16 01:55:40386std::unique_ptr<base::Value> NetLogJobCreationCallback(
estade5e5529d2015-05-21 20:59:11387 const NetLog::Source& source,
388 const std::string* host,
389 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40390 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
estade5e5529d2015-05-21 20:59:11391 source.AddToEventParameters(dict.get());
[email protected]cd565142012-06-12 16:21:45392 dict->SetString("host", *host);
dchengc7eeda422015-12-26 03:56:48393 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45394}
[email protected]a9813302012-04-28 09:29:28395
[email protected]cd565142012-06-12 16:21:45396// Creates NetLog parameters for HOST_RESOLVER_IMPL_JOB_ATTACH/DETACH events.
danakj22f90e72016-04-16 01:55:40397std::unique_ptr<base::Value> NetLogJobAttachCallback(
estade5e5529d2015-05-21 20:59:11398 const NetLog::Source& source,
399 RequestPriority priority,
400 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40401 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
estade5e5529d2015-05-21 20:59:11402 source.AddToEventParameters(dict.get());
[email protected]3b04d1f22013-10-16 00:23:56403 dict->SetString("priority", RequestPriorityToString(priority));
dchengc7eeda422015-12-26 03:56:48404 return std::move(dict);
[email protected]cd565142012-06-12 16:21:45405}
[email protected]b3601bc22012-02-21 21:23:20406
[email protected]cd565142012-06-12 16:21:45407// Creates NetLog parameters for the DNS_CONFIG_CHANGED event.
danakj22f90e72016-04-16 01:55:40408std::unique_ptr<base::Value> NetLogDnsConfigCallback(
estade5e5529d2015-05-21 20:59:11409 const DnsConfig* config,
410 NetLogCaptureMode /* capture_mode */) {
tfhef3618f2016-01-11 23:07:08411 return config->ToValue();
[email protected]cd565142012-06-12 16:21:45412}
[email protected]b4481b222012-03-16 17:13:11413
danakj22f90e72016-04-16 01:55:40414std::unique_ptr<base::Value> NetLogIPv6AvailableCallback(
estade5e5529d2015-05-21 20:59:11415 bool ipv6_available,
416 bool cached,
417 NetLogCaptureMode /* capture_mode */) {
danakj22f90e72016-04-16 01:55:40418 std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
sergeyub8cdc212015-05-14 18:50:37419 dict->SetBoolean("ipv6_available", ipv6_available);
420 dict->SetBoolean("cached", cached);
dchengc7eeda422015-12-26 03:56:48421 return std::move(dict);
sergeyub8cdc212015-05-14 18:50:37422}
423
[email protected]0f292de02012-02-01 22:28:20424// The logging routines are defined here because some requests are resolved
425// without a Request object.
426
427// Logs when a request has just been started.
428void LogStartRequest(const BoundNetLog& source_net_log,
[email protected]0f292de02012-02-01 22:28:20429 const HostResolver::RequestInfo& info) {
430 source_net_log.BeginEvent(
[email protected]0f292de02012-02-01 22:28:20431 NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST,
xunjieli26f90452014-11-10 16:23:02432 base::Bind(&NetLogRequestInfoCallback, &info));
[email protected]0f292de02012-02-01 22:28:20433}
434
435// Logs when a request has just completed (before its callback is run).
436void LogFinishRequest(const BoundNetLog& source_net_log,
[email protected]0f292de02012-02-01 22:28:20437 const HostResolver::RequestInfo& info,
[email protected]b3601bc22012-02-21 21:23:20438 int net_error) {
xunjieli26f90452014-11-10 16:23:02439 source_net_log.EndEventWithNetErrorCode(
[email protected]b3601bc22012-02-21 21:23:20440 NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST, net_error);
[email protected]0f292de02012-02-01 22:28:20441}
442
443// Logs when a request has been cancelled.
444void LogCancelRequest(const BoundNetLog& source_net_log,
[email protected]0f292de02012-02-01 22:28:20445 const HostResolverImpl::RequestInfo& info) {
xunjieli26f90452014-11-10 16:23:02446 source_net_log.AddEvent(NetLog::TYPE_CANCELLED);
447 source_net_log.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST);
[email protected]0f292de02012-02-01 22:28:20448}
449
[email protected]b59ff372009-07-15 22:04:32450//-----------------------------------------------------------------------------
451
[email protected]0f292de02012-02-01 22:28:20452// Keeps track of the highest priority.
453class PriorityTracker {
454 public:
[email protected]8c98d002012-07-18 19:02:27455 explicit PriorityTracker(RequestPriority initial_priority)
456 : highest_priority_(initial_priority), total_count_(0) {
[email protected]0f292de02012-02-01 22:28:20457 memset(counts_, 0, sizeof(counts_));
458 }
459
460 RequestPriority highest_priority() const {
461 return highest_priority_;
462 }
463
464 size_t total_count() const {
465 return total_count_;
466 }
467
468 void Add(RequestPriority req_priority) {
469 ++total_count_;
470 ++counts_[req_priority];
[email protected]31ae7ab2012-04-24 21:09:05471 if (highest_priority_ < req_priority)
[email protected]0f292de02012-02-01 22:28:20472 highest_priority_ = req_priority;
473 }
474
475 void Remove(RequestPriority req_priority) {
476 DCHECK_GT(total_count_, 0u);
477 DCHECK_GT(counts_[req_priority], 0u);
478 --total_count_;
479 --counts_[req_priority];
480 size_t i;
[email protected]31ae7ab2012-04-24 21:09:05481 for (i = highest_priority_; i > MINIMUM_PRIORITY && !counts_[i]; --i);
[email protected]0f292de02012-02-01 22:28:20482 highest_priority_ = static_cast<RequestPriority>(i);
483
[email protected]31ae7ab2012-04-24 21:09:05484 // In absence of requests, default to MINIMUM_PRIORITY.
485 if (total_count_ == 0)
486 DCHECK_EQ(MINIMUM_PRIORITY, highest_priority_);
[email protected]0f292de02012-02-01 22:28:20487 }
488
489 private:
490 RequestPriority highest_priority_;
491 size_t total_count_;
492 size_t counts_[NUM_PRIORITIES];
493};
494
[email protected]c54a8912012-10-22 22:09:43495} // namespace
[email protected]0f292de02012-02-01 22:28:20496
497//-----------------------------------------------------------------------------
498
tfarina9ed7f8c52016-02-19 17:50:18499bool ResolveLocalHostname(base::StringPiece host,
500 uint16_t port,
501 AddressList* address_list) {
tfarina9ed7f8c52016-02-19 17:50:18502 address_list->clear();
503
504 bool is_local6;
505 if (!IsLocalHostname(host, &is_local6))
506 return false;
507
martijna23c8962016-03-04 18:18:51508 address_list->push_back(IPEndPoint(IPAddress::IPv6Localhost(), port));
tfarina9ed7f8c52016-02-19 17:50:18509 if (!is_local6) {
martijna23c8962016-03-04 18:18:51510 address_list->push_back(IPEndPoint(IPAddress::IPv4Localhost(), port));
tfarina9ed7f8c52016-02-19 17:50:18511 }
512
513 return true;
514}
515
[email protected]daae1322013-09-05 18:26:50516const unsigned HostResolverImpl::kMaximumDnsFailures = 16;
517
[email protected]0f292de02012-02-01 22:28:20518// Holds the data for a request that could not be completed synchronously.
519// It is owned by a Job. Canceled Requests are only marked as canceled rather
520// than removed from the Job's |requests_| list.
[email protected]b59ff372009-07-15 22:04:32521class HostResolverImpl::Request {
522 public:
[email protected]ee094b82010-08-24 15:55:51523 Request(const BoundNetLog& source_net_log,
[email protected]54e13772009-08-14 03:01:09524 const RequestInfo& info,
[email protected]5109c1952013-08-20 18:44:10525 RequestPriority priority,
[email protected]aa22b242011-11-16 18:58:29526 const CompletionCallback& callback,
[email protected]b59ff372009-07-15 22:04:32527 AddressList* addresses)
[email protected]ee094b82010-08-24 15:55:51528 : source_net_log_(source_net_log),
[email protected]54e13772009-08-14 03:01:09529 info_(info),
[email protected]5109c1952013-08-20 18:44:10530 priority_(priority),
[email protected]54e13772009-08-14 03:01:09531 job_(NULL),
532 callback_(callback),
[email protected]51b9a6b2012-06-25 21:50:29533 addresses_(addresses),
[email protected]5109c1952013-08-20 18:44:10534 request_time_(base::TimeTicks::Now()) {}
[email protected]b59ff372009-07-15 22:04:32535
[email protected]0f292de02012-02-01 22:28:20536 // Mark the request as canceled.
537 void MarkAsCanceled() {
[email protected]b59ff372009-07-15 22:04:32538 job_ = NULL;
[email protected]b59ff372009-07-15 22:04:32539 addresses_ = NULL;
[email protected]aa22b242011-11-16 18:58:29540 callback_.Reset();
[email protected]b59ff372009-07-15 22:04:32541 }
542
[email protected]0f292de02012-02-01 22:28:20543 bool was_canceled() const {
[email protected]aa22b242011-11-16 18:58:29544 return callback_.is_null();
[email protected]b59ff372009-07-15 22:04:32545 }
546
547 void set_job(Job* job) {
[email protected]0f292de02012-02-01 22:28:20548 DCHECK(job);
[email protected]b59ff372009-07-15 22:04:32549 // Identify which job the request is waiting on.
550 job_ = job;
551 }
552
[email protected]0f292de02012-02-01 22:28:20553 // Prepare final AddressList and call completion callback.
[email protected]b3601bc22012-02-21 21:23:20554 void OnComplete(int error, const AddressList& addr_list) {
[email protected]51b9a6b2012-06-25 21:50:29555 DCHECK(!was_canceled());
[email protected]895123222012-10-25 15:21:17556 if (error == OK)
557 *addresses_ = EnsurePortOnAddressList(addr_list, info_.port());
[email protected]aa22b242011-11-16 18:58:29558 CompletionCallback callback = callback_;
[email protected]0f292de02012-02-01 22:28:20559 MarkAsCanceled();
[email protected]aa22b242011-11-16 18:58:29560 callback.Run(error);
[email protected]b59ff372009-07-15 22:04:32561 }
562
[email protected]b59ff372009-07-15 22:04:32563 Job* job() const {
564 return job_;
565 }
566
[email protected]0f292de02012-02-01 22:28:20567 // NetLog for the source, passed in HostResolver::Resolve.
[email protected]ee094b82010-08-24 15:55:51568 const BoundNetLog& source_net_log() {
569 return source_net_log_;
570 }
571
[email protected]b59ff372009-07-15 22:04:32572 const RequestInfo& info() const {
573 return info_;
574 }
575
[email protected]5109c1952013-08-20 18:44:10576 RequestPriority priority() const { return priority_; }
juliatuttlec53b19a72016-05-05 13:51:31577 void set_priority(RequestPriority priority) { priority_ = priority; }
[email protected]5109c1952013-08-20 18:44:10578
579 base::TimeTicks request_time() const { return request_time_; }
[email protected]51b9a6b2012-06-25 21:50:29580
[email protected]b59ff372009-07-15 22:04:32581 private:
xunjieli26f90452014-11-10 16:23:02582 const BoundNetLog source_net_log_;
[email protected]54e13772009-08-14 03:01:09583
[email protected]b59ff372009-07-15 22:04:32584 // The request info that started the request.
[email protected]5109c1952013-08-20 18:44:10585 const RequestInfo info_;
586
juliatuttlec53b19a72016-05-05 13:51:31587 RequestPriority priority_;
[email protected]b59ff372009-07-15 22:04:32588
[email protected]0f292de02012-02-01 22:28:20589 // The resolve job that this request is dependent on.
[email protected]b59ff372009-07-15 22:04:32590 Job* job_;
591
592 // The user's callback to invoke when the request completes.
[email protected]aa22b242011-11-16 18:58:29593 CompletionCallback callback_;
[email protected]b59ff372009-07-15 22:04:32594
595 // The address list to save result into.
596 AddressList* addresses_;
597
[email protected]51b9a6b2012-06-25 21:50:29598 const base::TimeTicks request_time_;
599
[email protected]b59ff372009-07-15 22:04:32600 DISALLOW_COPY_AND_ASSIGN(Request);
601};
602
[email protected]1e9bbd22010-10-15 16:42:45603//------------------------------------------------------------------------------
604
[email protected]0f292de02012-02-01 22:28:20605// Calls HostResolverProc on the WorkerPool. Performs retries if necessary.
606//
607// Whenever we try to resolve the host, we post a delayed task to check if host
608// resolution (OnLookupComplete) is completed or not. If the original attempt
609// hasn't completed, then we start another attempt for host resolution. We take
610// the results from the first attempt that finishes and ignore the results from
611// all other attempts.
612//
613// TODO(szym): Move to separate source file for testing and mocking.
614//
615class HostResolverImpl::ProcTask
616 : public base::RefCountedThreadSafe<HostResolverImpl::ProcTask> {
[email protected]b59ff372009-07-15 22:04:32617 public:
[email protected]b3601bc22012-02-21 21:23:20618 typedef base::Callback<void(int net_error,
619 const AddressList& addr_list)> Callback;
[email protected]b59ff372009-07-15 22:04:32620
[email protected]0f292de02012-02-01 22:28:20621 ProcTask(const Key& key,
622 const ProcTaskParams& params,
623 const Callback& callback,
624 const BoundNetLog& job_net_log)
625 : key_(key),
626 params_(params),
627 callback_(callback),
anujk.sharma7c907f02015-05-29 02:55:44628 task_runner_(base::ThreadTaskRunnerHandle::Get()),
[email protected]0f292de02012-02-01 22:28:20629 attempt_number_(0),
630 completed_attempt_number_(0),
631 completed_attempt_error_(ERR_UNEXPECTED),
632 had_non_speculative_request_(false),
[email protected]b3601bc22012-02-21 21:23:20633 net_log_(job_net_log) {
[email protected]90499482013-06-01 00:39:50634 if (!params_.resolver_proc.get())
[email protected]0f292de02012-02-01 22:28:20635 params_.resolver_proc = HostResolverProc::GetDefault();
636 // If default is unset, use the system proc.
[email protected]90499482013-06-01 00:39:50637 if (!params_.resolver_proc.get())
[email protected]1ee9afa12013-04-16 14:18:06638 params_.resolver_proc = new SystemHostResolverProc();
[email protected]b59ff372009-07-15 22:04:32639 }
640
[email protected]b59ff372009-07-15 22:04:32641 void Start() {
anujk.sharma7c907f02015-05-29 02:55:44642 DCHECK(task_runner_->BelongsToCurrentThread());
[email protected]4da911f2012-06-14 19:45:20643 net_log_.BeginEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK);
[email protected]189163e2011-05-11 01:48:54644 StartLookupAttempt();
645 }
[email protected]252b699b2010-02-05 21:38:06646
[email protected]0f292de02012-02-01 22:28:20647 // Cancels this ProcTask. It will be orphaned. Any outstanding resolve
648 // attempts running on worker threads will continue running. Only once all the
649 // attempts complete will the final reference to this ProcTask be released.
650 void Cancel() {
anujk.sharma7c907f02015-05-29 02:55:44651 DCHECK(task_runner_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20652
[email protected]0adcb2b2012-08-15 21:30:46653 if (was_canceled() || was_completed())
[email protected]0f292de02012-02-01 22:28:20654 return;
655
[email protected]0f292de02012-02-01 22:28:20656 callback_.Reset();
[email protected]4da911f2012-06-14 19:45:20657 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK);
[email protected]0f292de02012-02-01 22:28:20658 }
659
660 void set_had_non_speculative_request() {
anujk.sharma7c907f02015-05-29 02:55:44661 DCHECK(task_runner_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20662 had_non_speculative_request_ = true;
663 }
664
665 bool was_canceled() const {
anujk.sharma7c907f02015-05-29 02:55:44666 DCHECK(task_runner_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20667 return callback_.is_null();
668 }
669
670 bool was_completed() const {
anujk.sharma7c907f02015-05-29 02:55:44671 DCHECK(task_runner_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20672 return completed_attempt_number_ > 0;
673 }
674
675 private:
[email protected]a9813302012-04-28 09:29:28676 friend class base::RefCountedThreadSafe<ProcTask>;
677 ~ProcTask() {}
678
[email protected]189163e2011-05-11 01:48:54679 void StartLookupAttempt() {
anujk.sharma7c907f02015-05-29 02:55:44680 DCHECK(task_runner_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54681 base::TimeTicks start_time = base::TimeTicks::Now();
682 ++attempt_number_;
683 // Dispatch the lookup attempt to a worker thread.
684 if (!base::WorkerPool::PostTask(
685 FROM_HERE,
[email protected]0f292de02012-02-01 22:28:20686 base::Bind(&ProcTask::DoLookup, this, start_time, attempt_number_),
[email protected]189163e2011-05-11 01:48:54687 true)) {
[email protected]b59ff372009-07-15 22:04:32688 NOTREACHED();
689
690 // Since we could be running within Resolve() right now, we can't just
691 // call OnLookupComplete(). Instead we must wait until Resolve() has
692 // returned (IO_PENDING).
anujk.sharma7c907f02015-05-29 02:55:44693 task_runner_->PostTask(FROM_HERE,
694 base::Bind(&ProcTask::OnLookupComplete,
695 this,
696 AddressList(),
697 start_time,
698 attempt_number_,
699 ERR_UNEXPECTED,
700 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
[email protected]0f292de02012-02-01 22:28:20707 // If we don't get the results within a given time, RetryIfNotComplete
708 // will start a new attempt on a different worker thread if none of our
709 // outstanding attempts have completed yet.
710 if (attempt_number_ <= params_.max_retry_attempts) {
anujk.sharma7c907f02015-05-29 02:55:44711 task_runner_->PostDelayedTask(
[email protected]06ef6d92011-05-19 04:24:58712 FROM_HERE,
[email protected]0f292de02012-02-01 22:28:20713 base::Bind(&ProcTask::RetryIfNotComplete, this),
[email protected]7e560102012-03-08 20:58:42714 params_.unresponsive_delay);
[email protected]06ef6d92011-05-19 04:24:58715 }
[email protected]b59ff372009-07-15 22:04:32716 }
717
[email protected]6c710ee2010-05-07 07:51:16718 // WARNING: This code runs inside a worker pool. The shutdown code cannot
719 // wait for it to finish, so we must be very careful here about using other
720 // objects (like MessageLoops, Singletons, etc). During shutdown these objects
[email protected]189163e2011-05-11 01:48:54721 // may no longer exist. Multiple DoLookups() could be running in parallel, so
722 // any state inside of |this| must not mutate .
723 void DoLookup(const base::TimeTicks& start_time,
Avi Drissman13fc8932015-12-20 04:40:46724 const uint32_t attempt_number) {
[email protected]189163e2011-05-11 01:48:54725 AddressList results;
726 int os_error = 0;
[email protected]b59ff372009-07-15 22:04:32727 // Running on the worker thread
[email protected]0f292de02012-02-01 22:28:20728 int error = params_.resolver_proc->Resolve(key_.hostname,
729 key_.address_family,
730 key_.host_resolver_flags,
731 &results,
732 &os_error);
[email protected]b59ff372009-07-15 22:04:32733
eroman91dd3602015-03-26 03:46:33734 // Fail the resolution if the result contains 127.0.53.53. See the comment
735 // block of kIcanNameCollisionIp for details on why.
736 for (const auto& it : results) {
martijna23c8962016-03-04 18:18:51737 const IPAddress& cur = it.address();
738 if (cur.IsIPv4() && IPAddressStartsWith(cur, kIcanNameCollisionIp)) {
eroman91dd3602015-03-26 03:46:33739 error = ERR_ICANN_NAME_COLLISION;
740 break;
741 }
742 }
743
anujk.sharma7c907f02015-05-29 02:55:44744 task_runner_->PostTask(FROM_HERE,
745 base::Bind(&ProcTask::OnLookupComplete,
746 this,
747 results,
748 start_time,
749 attempt_number,
750 error,
751 os_error));
[email protected]189163e2011-05-11 01:48:54752 }
753
anujk.sharma7c907f02015-05-29 02:55:44754 // Makes next attempt if DoLookup() has not finished (runs on task runner
755 // thread).
[email protected]0f292de02012-02-01 22:28:20756 void RetryIfNotComplete() {
anujk.sharma7c907f02015-05-29 02:55:44757 DCHECK(task_runner_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54758
[email protected]0f292de02012-02-01 22:28:20759 if (was_completed() || was_canceled())
[email protected]189163e2011-05-11 01:48:54760 return;
761
[email protected]0f292de02012-02-01 22:28:20762 params_.unresponsive_delay *= params_.retry_factor;
[email protected]189163e2011-05-11 01:48:54763 StartLookupAttempt();
[email protected]b59ff372009-07-15 22:04:32764 }
765
anujk.sharma7c907f02015-05-29 02:55:44766 // Callback for when DoLookup() completes (runs on task runner thread).
[email protected]189163e2011-05-11 01:48:54767 void OnLookupComplete(const AddressList& results,
768 const base::TimeTicks& start_time,
Avi Drissman13fc8932015-12-20 04:40:46769 const uint32_t attempt_number,
[email protected]189163e2011-05-11 01:48:54770 int error,
771 const int os_error) {
ssid6d6b40102016-04-05 18:59:56772 TRACE_EVENT0("net", "ProcTask::OnLookupComplete");
anujk.sharma7c907f02015-05-29 02:55:44773 DCHECK(task_runner_->BelongsToCurrentThread());
[email protected]49b70b222013-05-07 21:24:23774 // If results are empty, we should return an error.
775 bool empty_list_on_ok = (error == OK && results.empty());
776 UMA_HISTOGRAM_BOOLEAN("DNS.EmptyAddressListAndNoError", empty_list_on_ok);
777 if (empty_list_on_ok)
778 error = ERR_NAME_NOT_RESOLVED;
[email protected]189163e2011-05-11 01:48:54779
780 bool was_retry_attempt = attempt_number > 1;
781
[email protected]2d3b7762010-10-09 00:35:47782 // Ideally the following code would be part of host_resolver_proc.cc,
[email protected]b3601bc22012-02-21 21:23:20783 // however it isn't safe to call NetworkChangeNotifier from worker threads.
784 // So we do it here on the IO thread instead.
[email protected]189163e2011-05-11 01:48:54785 if (error != OK && NetworkChangeNotifier::IsOffline())
786 error = ERR_INTERNET_DISCONNECTED;
[email protected]2d3b7762010-10-09 00:35:47787
[email protected]b3601bc22012-02-21 21:23:20788 // If this is the first attempt that is finishing later, then record data
789 // for the first attempt. Won't contaminate with retry attempt's data.
[email protected]189163e2011-05-11 01:48:54790 if (!was_retry_attempt)
791 RecordPerformanceHistograms(start_time, error, os_error);
792
793 RecordAttemptHistograms(start_time, attempt_number, error, os_error);
[email protected]f2d8c4212010-02-02 00:56:35794
[email protected]0f292de02012-02-01 22:28:20795 if (was_canceled())
[email protected]b59ff372009-07-15 22:04:32796 return;
797
[email protected]cd565142012-06-12 16:21:45798 NetLog::ParametersCallback net_log_callback;
[email protected]0f292de02012-02-01 22:28:20799 if (error != OK) {
[email protected]cd565142012-06-12 16:21:45800 net_log_callback = base::Bind(&NetLogProcTaskFailedCallback,
801 attempt_number,
802 error,
803 os_error);
[email protected]0f292de02012-02-01 22:28:20804 } else {
tfarina5e24b242015-10-27 13:11:28805 net_log_callback = NetLog::IntCallback("attempt_number", attempt_number);
[email protected]0f292de02012-02-01 22:28:20806 }
[email protected]cd565142012-06-12 16:21:45807 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_ATTEMPT_FINISHED,
808 net_log_callback);
[email protected]0f292de02012-02-01 22:28:20809
810 if (was_completed())
811 return;
812
813 // Copy the results from the first worker thread that resolves the host.
814 results_ = results;
815 completed_attempt_number_ = attempt_number;
816 completed_attempt_error_ = error;
817
[email protected]e87b8b512011-06-14 22:12:52818 if (was_retry_attempt) {
819 // If retry attempt finishes before 1st attempt, then get stats on how
820 // much time is saved by having spawned an extra attempt.
821 retry_attempt_finished_time_ = base::TimeTicks::Now();
822 }
823
[email protected]189163e2011-05-11 01:48:54824 if (error != OK) {
[email protected]cd565142012-06-12 16:21:45825 net_log_callback = base::Bind(&NetLogProcTaskFailedCallback,
826 0, error, os_error);
[email protected]ee094b82010-08-24 15:55:51827 } else {
[email protected]cd565142012-06-12 16:21:45828 net_log_callback = results_.CreateNetLogCallback();
[email protected]ee094b82010-08-24 15:55:51829 }
[email protected]cd565142012-06-12 16:21:45830 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK,
831 net_log_callback);
[email protected]ee094b82010-08-24 15:55:51832
[email protected]b3601bc22012-02-21 21:23:20833 callback_.Run(error, results_);
[email protected]b59ff372009-07-15 22:04:32834 }
835
[email protected]189163e2011-05-11 01:48:54836 void RecordPerformanceHistograms(const base::TimeTicks& start_time,
837 const int error,
838 const int os_error) const {
anujk.sharma7c907f02015-05-29 02:55:44839 DCHECK(task_runner_->BelongsToCurrentThread());
asvitkinec0fb8022014-08-26 04:39:35840 enum Category { // Used in UMA_HISTOGRAM_ENUMERATION.
[email protected]1e9bbd22010-10-15 16:42:45841 RESOLVE_SUCCESS,
842 RESOLVE_FAIL,
843 RESOLVE_SPECULATIVE_SUCCESS,
844 RESOLVE_SPECULATIVE_FAIL,
845 RESOLVE_MAX, // Bounding value.
846 };
847 int category = RESOLVE_MAX; // Illegal value for later DCHECK only.
848
[email protected]189163e2011-05-11 01:48:54849 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
850 if (error == OK) {
[email protected]1e9bbd22010-10-15 16:42:45851 if (had_non_speculative_request_) {
852 category = RESOLVE_SUCCESS;
853 DNS_HISTOGRAM("DNS.ResolveSuccess", duration);
854 } else {
855 category = RESOLVE_SPECULATIVE_SUCCESS;
856 DNS_HISTOGRAM("DNS.ResolveSpeculativeSuccess", duration);
857 }
[email protected]7e96d792011-06-10 17:08:23858
[email protected]78eac2a2012-03-14 19:09:27859 // Log DNS lookups based on |address_family|. This will help us determine
[email protected]7e96d792011-06-10 17:08:23860 // if IPv4 or IPv4/6 lookups are faster or slower.
861 switch(key_.address_family) {
862 case ADDRESS_FAMILY_IPV4:
863 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_IPV4", duration);
864 break;
865 case ADDRESS_FAMILY_IPV6:
866 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_IPV6", duration);
867 break;
868 case ADDRESS_FAMILY_UNSPECIFIED:
869 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_UNSPEC", duration);
870 break;
871 }
[email protected]1e9bbd22010-10-15 16:42:45872 } else {
873 if (had_non_speculative_request_) {
874 category = RESOLVE_FAIL;
875 DNS_HISTOGRAM("DNS.ResolveFail", duration);
876 } else {
877 category = RESOLVE_SPECULATIVE_FAIL;
878 DNS_HISTOGRAM("DNS.ResolveSpeculativeFail", duration);
879 }
[email protected]78eac2a2012-03-14 19:09:27880 // Log DNS lookups based on |address_family|. This will help us determine
[email protected]7e96d792011-06-10 17:08:23881 // if IPv4 or IPv4/6 lookups are faster or slower.
882 switch(key_.address_family) {
883 case ADDRESS_FAMILY_IPV4:
884 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_IPV4", duration);
885 break;
886 case ADDRESS_FAMILY_IPV6:
887 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_IPV6", duration);
888 break;
889 case ADDRESS_FAMILY_UNSPECIFIED:
890 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_UNSPEC", duration);
891 break;
892 }
[email protected]c833e322010-10-16 23:51:36893 UMA_HISTOGRAM_CUSTOM_ENUMERATION(kOSErrorsForGetAddrinfoHistogramName,
[email protected]189163e2011-05-11 01:48:54894 std::abs(os_error),
[email protected]1e9bbd22010-10-15 16:42:45895 GetAllGetAddrinfoOSErrors());
896 }
[email protected]051b6ab2010-10-18 16:50:46897 DCHECK_LT(category, static_cast<int>(RESOLVE_MAX)); // Be sure it was set.
[email protected]1e9bbd22010-10-15 16:42:45898
899 UMA_HISTOGRAM_ENUMERATION("DNS.ResolveCategory", category, RESOLVE_MAX);
[email protected]1e9bbd22010-10-15 16:42:45900 }
901
[email protected]189163e2011-05-11 01:48:54902 void RecordAttemptHistograms(const base::TimeTicks& start_time,
Avi Drissman13fc8932015-12-20 04:40:46903 const uint32_t attempt_number,
[email protected]189163e2011-05-11 01:48:54904 const int error,
905 const int os_error) const {
anujk.sharma7c907f02015-05-29 02:55:44906 DCHECK(task_runner_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54907 bool first_attempt_to_complete =
908 completed_attempt_number_ == attempt_number;
[email protected]e87b8b512011-06-14 22:12:52909 bool is_first_attempt = (attempt_number == 1);
[email protected]1e9bbd22010-10-15 16:42:45910
[email protected]189163e2011-05-11 01:48:54911 if (first_attempt_to_complete) {
912 // If this was first attempt to complete, then record the resolution
913 // status of the attempt.
914 if (completed_attempt_error_ == OK) {
915 UMA_HISTOGRAM_ENUMERATION(
916 "DNS.AttemptFirstSuccess", attempt_number, 100);
917 } else {
918 UMA_HISTOGRAM_ENUMERATION(
919 "DNS.AttemptFirstFailure", attempt_number, 100);
920 }
921 }
922
923 if (error == OK)
924 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptSuccess", attempt_number, 100);
925 else
926 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptFailure", attempt_number, 100);
927
[email protected]e87b8b512011-06-14 22:12:52928 // If first attempt didn't finish before retry attempt, then calculate stats
929 // on how much time is saved by having spawned an extra attempt.
[email protected]0f292de02012-02-01 22:28:20930 if (!first_attempt_to_complete && is_first_attempt && !was_canceled()) {
[email protected]e87b8b512011-06-14 22:12:52931 DNS_HISTOGRAM("DNS.AttemptTimeSavedByRetry",
932 base::TimeTicks::Now() - retry_attempt_finished_time_);
933 }
934
[email protected]0f292de02012-02-01 22:28:20935 if (was_canceled() || !first_attempt_to_complete) {
[email protected]189163e2011-05-11 01:48:54936 // Count those attempts which completed after the job was already canceled
937 // OR after the job was already completed by an earlier attempt (so in
938 // effect).
939 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptDiscarded", attempt_number, 100);
940
[email protected]0f292de02012-02-01 22:28:20941 // Record if job is canceled.
942 if (was_canceled())
[email protected]189163e2011-05-11 01:48:54943 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptCancelled", attempt_number, 100);
944 }
945
946 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
947 if (error == OK)
948 DNS_HISTOGRAM("DNS.AttemptSuccessDuration", duration);
949 else
950 DNS_HISTOGRAM("DNS.AttemptFailDuration", duration);
951 }
[email protected]1e9bbd22010-10-15 16:42:45952
anujk.sharma7c907f02015-05-29 02:55:44953 // Set on the task runner thread, read on the worker thread.
[email protected]123ab1e32009-10-21 19:12:57954 Key key_;
[email protected]b59ff372009-07-15 22:04:32955
[email protected]0f292de02012-02-01 22:28:20956 // Holds an owning reference to the HostResolverProc that we are going to use.
[email protected]b59ff372009-07-15 22:04:32957 // This may not be the current resolver procedure by the time we call
958 // ResolveAddrInfo, but that's OK... we'll use it anyways, and the owning
959 // reference ensures that it remains valid until we are done.
[email protected]0f292de02012-02-01 22:28:20960 ProcTaskParams params_;
[email protected]b59ff372009-07-15 22:04:32961
[email protected]0f292de02012-02-01 22:28:20962 // The listener to the results of this ProcTask.
963 Callback callback_;
964
anujk.sharma7c907f02015-05-29 02:55:44965 // Used to post ourselves onto the task runner thread.
966 scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
[email protected]189163e2011-05-11 01:48:54967
968 // Keeps track of the number of attempts we have made so far to resolve the
969 // host. Whenever we start an attempt to resolve the host, we increase this
970 // number.
Avi Drissman13fc8932015-12-20 04:40:46971 uint32_t attempt_number_;
[email protected]189163e2011-05-11 01:48:54972
973 // The index of the attempt which finished first (or 0 if the job is still in
974 // progress).
Avi Drissman13fc8932015-12-20 04:40:46975 uint32_t completed_attempt_number_;
[email protected]189163e2011-05-11 01:48:54976
977 // The result (a net error code) from the first attempt to complete.
978 int completed_attempt_error_;
[email protected]252b699b2010-02-05 21:38:06979
[email protected]e87b8b512011-06-14 22:12:52980 // The time when retry attempt was finished.
981 base::TimeTicks retry_attempt_finished_time_;
982
[email protected]252b699b2010-02-05 21:38:06983 // True if a non-speculative request was ever attached to this job
[email protected]0f292de02012-02-01 22:28:20984 // (regardless of whether or not it was later canceled.
[email protected]252b699b2010-02-05 21:38:06985 // This boolean is used for histogramming the duration of jobs used to
986 // service non-speculative requests.
987 bool had_non_speculative_request_;
988
[email protected]b59ff372009-07-15 22:04:32989 AddressList results_;
990
[email protected]ee094b82010-08-24 15:55:51991 BoundNetLog net_log_;
992
[email protected]0f292de02012-02-01 22:28:20993 DISALLOW_COPY_AND_ASSIGN(ProcTask);
[email protected]b59ff372009-07-15 22:04:32994};
995
996//-----------------------------------------------------------------------------
997
[email protected]12faa4c2012-11-06 04:44:18998// Wraps a call to HaveOnlyLoopbackAddresses to be executed on the WorkerPool as
999// it takes 40-100ms and should not block initialization.
1000class HostResolverImpl::LoopbackProbeJob {
1001 public:
1002 explicit LoopbackProbeJob(const base::WeakPtr<HostResolverImpl>& resolver)
1003 : resolver_(resolver),
1004 result_(false) {
[email protected]11fbca0b2013-06-02 23:37:211005 DCHECK(resolver.get());
[email protected]12faa4c2012-11-06 04:44:181006 const bool kIsSlow = true;
1007 base::WorkerPool::PostTaskAndReply(
1008 FROM_HERE,
1009 base::Bind(&LoopbackProbeJob::DoProbe, base::Unretained(this)),
1010 base::Bind(&LoopbackProbeJob::OnProbeComplete, base::Owned(this)),
1011 kIsSlow);
1012 }
1013
1014 virtual ~LoopbackProbeJob() {}
1015
1016 private:
1017 // Runs on worker thread.
1018 void DoProbe() {
1019 result_ = HaveOnlyLoopbackAddresses();
1020 }
1021
1022 void OnProbeComplete() {
[email protected]11fbca0b2013-06-02 23:37:211023 if (!resolver_.get())
[email protected]12faa4c2012-11-06 04:44:181024 return;
1025 resolver_->SetHaveOnlyLoopbackAddresses(result_);
1026 }
1027
anujk.sharma7c907f02015-05-29 02:55:441028 // Used/set only on task runner thread.
[email protected]12faa4c2012-11-06 04:44:181029 base::WeakPtr<HostResolverImpl> resolver_;
1030
1031 bool result_;
1032
1033 DISALLOW_COPY_AND_ASSIGN(LoopbackProbeJob);
1034};
1035
[email protected]0f8f1b432010-03-16 19:06:031036//-----------------------------------------------------------------------------
1037
[email protected]b3601bc22012-02-21 21:23:201038// Resolves the hostname using DnsTransaction.
1039// TODO(szym): This could be moved to separate source file as well.
[email protected]0adcb2b2012-08-15 21:30:461040class HostResolverImpl::DnsTask : public base::SupportsWeakPtr<DnsTask> {
[email protected]b3601bc22012-02-21 21:23:201041 public:
[email protected]daae1322013-09-05 18:26:501042 class Delegate {
1043 public:
1044 virtual void OnDnsTaskComplete(base::TimeTicks start_time,
1045 int net_error,
1046 const AddressList& addr_list,
1047 base::TimeDelta ttl) = 0;
1048
1049 // Called when the first of two jobs succeeds. If the first completed
1050 // transaction fails, this is not called. Also not called when the DnsTask
1051 // only needs to run one transaction.
1052 virtual void OnFirstDnsTransactionComplete() = 0;
1053
1054 protected:
1055 Delegate() {}
1056 virtual ~Delegate() {}
1057 };
[email protected]b3601bc22012-02-21 21:23:201058
[email protected]0adcb2b2012-08-15 21:30:461059 DnsTask(DnsClient* client,
[email protected]b3601bc22012-02-21 21:23:201060 const Key& key,
[email protected]daae1322013-09-05 18:26:501061 Delegate* delegate,
[email protected]b3601bc22012-02-21 21:23:201062 const BoundNetLog& job_net_log)
[email protected]0adcb2b2012-08-15 21:30:461063 : client_(client),
[email protected]daae1322013-09-05 18:26:501064 key_(key),
1065 delegate_(delegate),
1066 net_log_(job_net_log),
1067 num_completed_transactions_(0),
1068 task_start_time_(base::TimeTicks::Now()) {
[email protected]0adcb2b2012-08-15 21:30:461069 DCHECK(client);
[email protected]daae1322013-09-05 18:26:501070 DCHECK(delegate_);
[email protected]1affed62013-08-21 03:24:501071 }
1072
[email protected]daae1322013-09-05 18:26:501073 bool needs_two_transactions() const {
1074 return key_.address_family == ADDRESS_FAMILY_UNSPECIFIED;
1075 }
1076
1077 bool needs_another_transaction() const {
1078 return needs_two_transactions() && !transaction_aaaa_;
1079 }
1080
1081 void StartFirstTransaction() {
1082 DCHECK_EQ(0u, num_completed_transactions_);
[email protected]70c04ab2013-08-22 16:05:121083 net_log_.BeginEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK);
[email protected]daae1322013-09-05 18:26:501084 if (key_.address_family == ADDRESS_FAMILY_IPV6) {
1085 StartAAAA();
1086 } else {
1087 StartA();
1088 }
1089 }
1090
1091 void StartSecondTransaction() {
1092 DCHECK(needs_two_transactions());
1093 StartAAAA();
[email protected]70c04ab2013-08-22 16:05:121094 }
1095
1096 private:
[email protected]daae1322013-09-05 18:26:501097 void StartA() {
1098 DCHECK(!transaction_a_);
1099 DCHECK_NE(ADDRESS_FAMILY_IPV6, key_.address_family);
1100 transaction_a_ = CreateTransaction(ADDRESS_FAMILY_IPV4);
1101 transaction_a_->Start();
1102 }
1103
1104 void StartAAAA() {
1105 DCHECK(!transaction_aaaa_);
1106 DCHECK_NE(ADDRESS_FAMILY_IPV4, key_.address_family);
1107 transaction_aaaa_ = CreateTransaction(ADDRESS_FAMILY_IPV6);
1108 transaction_aaaa_->Start();
1109 }
1110
danakj22f90e72016-04-16 01:55:401111 std::unique_ptr<DnsTransaction> CreateTransaction(AddressFamily family) {
[email protected]daae1322013-09-05 18:26:501112 DCHECK_NE(ADDRESS_FAMILY_UNSPECIFIED, family);
1113 return client_->GetTransactionFactory()->CreateTransaction(
1114 key_.hostname,
1115 family == ADDRESS_FAMILY_IPV6 ? dns_protocol::kTypeAAAA :
1116 dns_protocol::kTypeA,
1117 base::Bind(&DnsTask::OnTransactionComplete, base::Unretained(this),
1118 base::TimeTicks::Now()),
1119 net_log_);
1120 }
1121
1122 void OnTransactionComplete(const base::TimeTicks& start_time,
[email protected]1def74c2012-03-22 20:07:001123 DnsTransaction* transaction,
[email protected]b3601bc22012-02-21 21:23:201124 int net_error,
1125 const DnsResponse* response) {
[email protected]add76532012-03-30 14:47:471126 DCHECK(transaction);
[email protected]02cd6982013-01-10 20:12:511127 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]0adcb2b2012-08-15 21:30:461128 if (net_error != OK) {
[email protected]02cd6982013-01-10 20:12:511129 DNS_HISTOGRAM("AsyncDNS.TransactionFailure", duration);
[email protected]0adcb2b2012-08-15 21:30:461130 OnFailure(net_error, DnsResponse::DNS_PARSE_OK);
1131 return;
[email protected]6c411902012-08-14 22:36:361132 }
[email protected]0adcb2b2012-08-15 21:30:461133
[email protected]02cd6982013-01-10 20:12:511134 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess", duration);
1135 switch (transaction->GetType()) {
1136 case dns_protocol::kTypeA:
1137 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess_A", duration);
1138 break;
1139 case dns_protocol::kTypeAAAA:
1140 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess_AAAA", duration);
1141 break;
1142 }
[email protected]daae1322013-09-05 18:26:501143
[email protected]0adcb2b2012-08-15 21:30:461144 AddressList addr_list;
1145 base::TimeDelta ttl;
1146 DnsResponse::Result result = response->ParseToAddressList(&addr_list, &ttl);
1147 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ParseToAddressList",
1148 result,
1149 DnsResponse::DNS_PARSE_RESULT_MAX);
1150 if (result != DnsResponse::DNS_PARSE_OK) {
1151 // Fail even if the other query succeeds.
1152 OnFailure(ERR_DNS_MALFORMED_RESPONSE, result);
1153 return;
1154 }
1155
[email protected]daae1322013-09-05 18:26:501156 ++num_completed_transactions_;
1157 if (num_completed_transactions_ == 1) {
1158 ttl_ = ttl;
[email protected]0adcb2b2012-08-15 21:30:461159 } else {
[email protected]daae1322013-09-05 18:26:501160 ttl_ = std::min(ttl_, ttl);
[email protected]0adcb2b2012-08-15 21:30:461161 }
1162
[email protected]daae1322013-09-05 18:26:501163 if (transaction->GetType() == dns_protocol::kTypeA) {
1164 DCHECK_EQ(transaction_a_.get(), transaction);
1165 // Place IPv4 addresses after IPv6.
1166 addr_list_.insert(addr_list_.end(), addr_list.begin(), addr_list.end());
1167 } else {
1168 DCHECK_EQ(transaction_aaaa_.get(), transaction);
1169 // Place IPv6 addresses before IPv4.
1170 addr_list_.insert(addr_list_.begin(), addr_list.begin(), addr_list.end());
1171 }
1172
1173 if (needs_two_transactions() && num_completed_transactions_ == 1) {
1174 // No need to repeat the suffix search.
1175 key_.hostname = transaction->GetHostname();
1176 delegate_->OnFirstDnsTransactionComplete();
1177 return;
1178 }
1179
1180 if (addr_list_.empty()) {
[email protected]70c04ab2013-08-22 16:05:121181 // TODO(szym): Don't fallback to ProcTask in this case.
1182 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
[email protected]0adcb2b2012-08-15 21:30:461183 return;
1184 }
1185
[email protected]daae1322013-09-05 18:26:501186 // If there are multiple addresses, and at least one is IPv6, need to sort
1187 // them. Note that IPv6 addresses are always put before IPv4 ones, so it's
1188 // sufficient to just check the family of the first address.
1189 if (addr_list_.size() > 1 &&
1190 addr_list_[0].GetFamily() == ADDRESS_FAMILY_IPV6) {
1191 // Sort addresses if needed. Sort could complete synchronously.
[email protected]0adcb2b2012-08-15 21:30:461192 client_->GetAddressSorter()->Sort(
[email protected]daae1322013-09-05 18:26:501193 addr_list_,
[email protected]4589a3a2012-09-20 20:57:071194 base::Bind(&DnsTask::OnSortComplete,
1195 AsWeakPtr(),
[email protected]daae1322013-09-05 18:26:501196 base::TimeTicks::Now()));
[email protected]0adcb2b2012-08-15 21:30:461197 } else {
[email protected]daae1322013-09-05 18:26:501198 OnSuccess(addr_list_);
[email protected]0adcb2b2012-08-15 21:30:461199 }
1200 }
1201
1202 void OnSortComplete(base::TimeTicks start_time,
[email protected]0adcb2b2012-08-15 21:30:461203 bool success,
1204 const AddressList& addr_list) {
1205 if (!success) {
1206 DNS_HISTOGRAM("AsyncDNS.SortFailure",
1207 base::TimeTicks::Now() - start_time);
1208 OnFailure(ERR_DNS_SORT_ERROR, DnsResponse::DNS_PARSE_OK);
1209 return;
1210 }
1211
1212 DNS_HISTOGRAM("AsyncDNS.SortSuccess",
1213 base::TimeTicks::Now() - start_time);
1214
1215 // AddressSorter prunes unusable destinations.
1216 if (addr_list.empty()) {
1217 LOG(WARNING) << "Address list empty after RFC3484 sort";
1218 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
1219 return;
1220 }
1221
[email protected]daae1322013-09-05 18:26:501222 OnSuccess(addr_list);
[email protected]0adcb2b2012-08-15 21:30:461223 }
1224
1225 void OnFailure(int net_error, DnsResponse::Result result) {
1226 DCHECK_NE(OK, net_error);
[email protected]cd565142012-06-12 16:21:451227 net_log_.EndEvent(
1228 NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK,
1229 base::Bind(&NetLogDnsTaskFailedCallback, net_error, result));
[email protected]daae1322013-09-05 18:26:501230 delegate_->OnDnsTaskComplete(task_start_time_, net_error, AddressList(),
1231 base::TimeDelta());
[email protected]b3601bc22012-02-21 21:23:201232 }
1233
[email protected]daae1322013-09-05 18:26:501234 void OnSuccess(const AddressList& addr_list) {
[email protected]0adcb2b2012-08-15 21:30:461235 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK,
1236 addr_list.CreateNetLogCallback());
[email protected]daae1322013-09-05 18:26:501237 delegate_->OnDnsTaskComplete(task_start_time_, OK, addr_list, ttl_);
[email protected]0adcb2b2012-08-15 21:30:461238 }
1239
1240 DnsClient* client_;
[email protected]daae1322013-09-05 18:26:501241 Key key_;
1242
[email protected]b3601bc22012-02-21 21:23:201243 // The listener to the results of this DnsTask.
[email protected]daae1322013-09-05 18:26:501244 Delegate* delegate_;
[email protected]b3601bc22012-02-21 21:23:201245 const BoundNetLog net_log_;
1246
danakj22f90e72016-04-16 01:55:401247 std::unique_ptr<DnsTransaction> transaction_a_;
1248 std::unique_ptr<DnsTransaction> transaction_aaaa_;
[email protected]0adcb2b2012-08-15 21:30:461249
[email protected]daae1322013-09-05 18:26:501250 unsigned num_completed_transactions_;
1251
1252 // These are updated as each transaction completes.
1253 base::TimeDelta ttl_;
1254 // IPv6 addresses must appear first in the list.
1255 AddressList addr_list_;
1256
1257 base::TimeTicks task_start_time_;
[email protected]0adcb2b2012-08-15 21:30:461258
1259 DISALLOW_COPY_AND_ASSIGN(DnsTask);
[email protected]b3601bc22012-02-21 21:23:201260};
1261
1262//-----------------------------------------------------------------------------
1263
[email protected]0f292de02012-02-01 22:28:201264// Aggregates all Requests for the same Key. Dispatched via PriorityDispatch.
[email protected]daae1322013-09-05 18:26:501265class HostResolverImpl::Job : public PrioritizedDispatcher::Job,
1266 public HostResolverImpl::DnsTask::Delegate {
[email protected]68ad3ee2010-01-30 03:45:391267 public:
[email protected]0f292de02012-02-01 22:28:201268 // Creates new job for |key| where |request_net_log| is bound to the
[email protected]16ee26d2012-03-08 03:34:351269 // request that spawned it.
[email protected]12faa4c2012-11-06 04:44:181270 Job(const base::WeakPtr<HostResolverImpl>& resolver,
[email protected]0f292de02012-02-01 22:28:201271 const Key& key,
[email protected]8c98d002012-07-18 19:02:271272 RequestPriority priority,
xunjieli26f90452014-11-10 16:23:021273 const BoundNetLog& source_net_log)
[email protected]12faa4c2012-11-06 04:44:181274 : resolver_(resolver),
[email protected]0f292de02012-02-01 22:28:201275 key_(key),
[email protected]8c98d002012-07-18 19:02:271276 priority_tracker_(priority),
[email protected]0f292de02012-02-01 22:28:201277 had_non_speculative_request_(false),
[email protected]51b9a6b2012-06-25 21:50:291278 had_dns_config_(false),
[email protected]daae1322013-09-05 18:26:501279 num_occupied_job_slots_(0),
[email protected]1d932852012-06-19 19:40:331280 dns_task_error_(OK),
[email protected]51b9a6b2012-06-25 21:50:291281 creation_time_(base::TimeTicks::Now()),
1282 priority_change_time_(creation_time_),
xunjieli26f90452014-11-10 16:23:021283 net_log_(BoundNetLog::Make(source_net_log.net_log(),
[email protected]b3601bc22012-02-21 21:23:201284 NetLog::SOURCE_HOST_RESOLVER_IMPL_JOB)) {
xunjieli26f90452014-11-10 16:23:021285 source_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_CREATE_JOB);
[email protected]0f292de02012-02-01 22:28:201286
1287 net_log_.BeginEvent(
1288 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
[email protected]cd565142012-06-12 16:21:451289 base::Bind(&NetLogJobCreationCallback,
xunjieli26f90452014-11-10 16:23:021290 source_net_log.source(),
[email protected]cd565142012-06-12 16:21:451291 &key_.hostname));
[email protected]68ad3ee2010-01-30 03:45:391292 }
1293
dchengb03027d2014-10-21 12:00:201294 ~Job() override {
[email protected]b3601bc22012-02-21 21:23:201295 if (is_running()) {
1296 // |resolver_| was destroyed with this Job still in flight.
1297 // Clean-up, record in the log, but don't run any callbacks.
1298 if (is_proc_running()) {
[email protected]0f292de02012-02-01 22:28:201299 proc_task_->Cancel();
1300 proc_task_ = NULL;
[email protected]0f292de02012-02-01 22:28:201301 }
[email protected]16ee26d2012-03-08 03:34:351302 // Clean up now for nice NetLog.
[email protected]daae1322013-09-05 18:26:501303 KillDnsTask();
[email protected]b3601bc22012-02-21 21:23:201304 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
1305 ERR_ABORTED);
1306 } else if (is_queued()) {
[email protected]57a48d32012-03-03 00:04:551307 // |resolver_| was destroyed without running this Job.
[email protected]16ee26d2012-03-08 03:34:351308 // TODO(szym): is there any benefit in having this distinction?
[email protected]4da911f2012-06-14 19:45:201309 net_log_.AddEvent(NetLog::TYPE_CANCELLED);
1310 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB);
[email protected]68ad3ee2010-01-30 03:45:391311 }
[email protected]b3601bc22012-02-21 21:23:201312 // else CompleteRequests logged EndEvent.
[email protected]68ad3ee2010-01-30 03:45:391313
[email protected]b3601bc22012-02-21 21:23:201314 // Log any remaining Requests as cancelled.
danakj22f90e72016-04-16 01:55:401315 for (const std::unique_ptr<Request>& req : requests_) {
[email protected]b3601bc22012-02-21 21:23:201316 if (req->was_canceled())
1317 continue;
1318 DCHECK_EQ(this, req->job());
xunjieli26f90452014-11-10 16:23:021319 LogCancelRequest(req->source_net_log(), req->info());
[email protected]b3601bc22012-02-21 21:23:201320 }
[email protected]68ad3ee2010-01-30 03:45:391321 }
1322
[email protected]daae1322013-09-05 18:26:501323 // Add this job to the dispatcher. If "at_head" is true, adds at the front
1324 // of the queue.
1325 void Schedule(bool at_head) {
1326 DCHECK(!is_queued());
1327 PrioritizedDispatcher::Handle handle;
1328 if (!at_head) {
[email protected]106ccd2c2014-06-17 09:21:001329 handle = resolver_->dispatcher_->Add(this, priority());
[email protected]daae1322013-09-05 18:26:501330 } else {
[email protected]106ccd2c2014-06-17 09:21:001331 handle = resolver_->dispatcher_->AddAtHead(this, priority());
[email protected]daae1322013-09-05 18:26:501332 }
1333 // The dispatcher could have started |this| in the above call to Add, which
1334 // could have called Schedule again. In that case |handle| will be null,
1335 // but |handle_| may have been set by the other nested call to Schedule.
1336 if (!handle.is_null()) {
1337 DCHECK(handle_.is_null());
1338 handle_ = handle;
1339 }
[email protected]16ee26d2012-03-08 03:34:351340 }
1341
danakj22f90e72016-04-16 01:55:401342 void AddRequest(std::unique_ptr<Request> req) {
estarkd1bc206e2015-06-20 00:44:391343 DCHECK_EQ(key_.hostname, req->info().hostname());
[email protected]0f292de02012-02-01 22:28:201344
1345 req->set_job(this);
[email protected]5109c1952013-08-20 18:44:101346 priority_tracker_.Add(req->priority());
[email protected]0f292de02012-02-01 22:28:201347
xunjieli26f90452014-11-10 16:23:021348 req->source_net_log().AddEvent(
[email protected]0f292de02012-02-01 22:28:201349 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_ATTACH,
[email protected]cd565142012-06-12 16:21:451350 net_log_.source().ToEventParametersCallback());
[email protected]0f292de02012-02-01 22:28:201351
1352 net_log_.AddEvent(
1353 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_REQUEST_ATTACH,
[email protected]cd565142012-06-12 16:21:451354 base::Bind(&NetLogJobAttachCallback,
xunjieli26f90452014-11-10 16:23:021355 req->source_net_log().source(),
[email protected]cd565142012-06-12 16:21:451356 priority()));
[email protected]0f292de02012-02-01 22:28:201357
1358 // TODO(szym): Check if this is still needed.
1359 if (!req->info().is_speculative()) {
1360 had_non_speculative_request_ = true;
[email protected]90499482013-06-01 00:39:501361 if (proc_task_.get())
[email protected]0f292de02012-02-01 22:28:201362 proc_task_->set_had_non_speculative_request();
[email protected]68ad3ee2010-01-30 03:45:391363 }
[email protected]b3601bc22012-02-21 21:23:201364
dchengc7eeda422015-12-26 03:56:481365 requests_.push_back(std::move(req));
[email protected]b3601bc22012-02-21 21:23:201366
[email protected]51b9a6b2012-06-25 21:50:291367 UpdatePriority();
[email protected]68ad3ee2010-01-30 03:45:391368 }
1369
juliatuttlec53b19a72016-05-05 13:51:311370 void ChangeRequestPriority(Request* req, RequestPriority priority) {
1371 DCHECK_EQ(key_.hostname, req->info().hostname());
1372 DCHECK(!req->was_canceled());
1373
1374 priority_tracker_.Remove(req->priority());
1375 req->set_priority(priority);
1376 priority_tracker_.Add(req->priority());
1377 UpdatePriority();
1378 }
1379
[email protected]16ee26d2012-03-08 03:34:351380 // Marks |req| as cancelled. If it was the last active Request, also finishes
[email protected]0adcb2b2012-08-15 21:30:461381 // this Job, marking it as cancelled, and deletes it.
[email protected]0f292de02012-02-01 22:28:201382 void CancelRequest(Request* req) {
1383 DCHECK_EQ(key_.hostname, req->info().hostname());
1384 DCHECK(!req->was_canceled());
[email protected]16ee26d2012-03-08 03:34:351385
[email protected]0f292de02012-02-01 22:28:201386 // Don't remove it from |requests_| just mark it canceled.
1387 req->MarkAsCanceled();
xunjieli26f90452014-11-10 16:23:021388 LogCancelRequest(req->source_net_log(), req->info());
[email protected]16ee26d2012-03-08 03:34:351389
[email protected]5109c1952013-08-20 18:44:101390 priority_tracker_.Remove(req->priority());
1391 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_REQUEST_DETACH,
1392 base::Bind(&NetLogJobAttachCallback,
xunjieli26f90452014-11-10 16:23:021393 req->source_net_log().source(),
[email protected]5109c1952013-08-20 18:44:101394 priority()));
[email protected]b3601bc22012-02-21 21:23:201395
[email protected]16ee26d2012-03-08 03:34:351396 if (num_active_requests() > 0) {
[email protected]51b9a6b2012-06-25 21:50:291397 UpdatePriority();
[email protected]16ee26d2012-03-08 03:34:351398 } else {
1399 // If we were called from a Request's callback within CompleteRequests,
1400 // that Request could not have been cancelled, so num_active_requests()
1401 // could not be 0. Therefore, we are not in CompleteRequests().
[email protected]1339a2a22012-10-17 08:39:431402 CompleteRequestsWithError(OK /* cancelled */);
[email protected]b3601bc22012-02-21 21:23:201403 }
[email protected]68ad3ee2010-01-30 03:45:391404 }
1405
[email protected]7af985a2012-12-14 22:40:421406 // Called from AbortAllInProgressJobs. Completes all requests and destroys
1407 // the job. This currently assumes the abort is due to a network change.
olli.raulaa21e9eb72015-12-17 08:18:111408 // TODO This should not delete |this|.
[email protected]0f292de02012-02-01 22:28:201409 void Abort() {
[email protected]0f292de02012-02-01 22:28:201410 DCHECK(is_running());
[email protected]7af985a2012-12-14 22:40:421411 CompleteRequestsWithError(ERR_NETWORK_CHANGED);
[email protected]b3601bc22012-02-21 21:23:201412 }
1413
[email protected]f0f602bd2012-11-15 18:01:021414 // If DnsTask present, abort it and fall back to ProcTask.
1415 void AbortDnsTask() {
1416 if (dns_task_) {
[email protected]daae1322013-09-05 18:26:501417 KillDnsTask();
[email protected]f0f602bd2012-11-15 18:01:021418 dns_task_error_ = OK;
1419 StartProcTask();
1420 }
1421 }
1422
[email protected]16ee26d2012-03-08 03:34:351423 // Called by HostResolverImpl when this job is evicted due to queue overflow.
1424 // Completes all requests and destroys the job.
1425 void OnEvicted() {
1426 DCHECK(!is_running());
1427 DCHECK(is_queued());
1428 handle_.Reset();
1429
[email protected]4da911f2012-06-14 19:45:201430 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_EVICTED);
[email protected]16ee26d2012-03-08 03:34:351431
1432 // This signals to CompleteRequests that this job never ran.
[email protected]1339a2a22012-10-17 08:39:431433 CompleteRequestsWithError(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
[email protected]16ee26d2012-03-08 03:34:351434 }
1435
[email protected]78eac2a2012-03-14 19:09:271436 // Attempts to serve the job from HOSTS. Returns true if succeeded and
1437 // this Job was destroyed.
1438 bool ServeFromHosts() {
1439 DCHECK_GT(num_active_requests(), 0u);
1440 AddressList addr_list;
1441 if (resolver_->ServeFromHosts(key(),
[email protected]3cb676a12012-06-30 15:46:031442 requests_.front()->info(),
[email protected]78eac2a2012-03-14 19:09:271443 &addr_list)) {
1444 // This will destroy the Job.
[email protected]895123222012-10-25 15:21:171445 CompleteRequests(
1446 HostCache::Entry(OK, MakeAddressListForRequest(addr_list)),
1447 base::TimeDelta());
[email protected]78eac2a2012-03-14 19:09:271448 return true;
1449 }
1450 return false;
1451 }
1452
tanay.c6ddd5f6f2015-08-25 06:34:571453 const Key& key() const { return key_; }
[email protected]b4481b222012-03-16 17:13:111454
1455 bool is_queued() const {
1456 return !handle_.is_null();
1457 }
1458
1459 bool is_running() const {
1460 return is_dns_running() || is_proc_running();
1461 }
1462
[email protected]16ee26d2012-03-08 03:34:351463 private:
[email protected]daae1322013-09-05 18:26:501464 void KillDnsTask() {
1465 if (dns_task_) {
1466 ReduceToOneJobSlot();
1467 dns_task_.reset();
1468 }
1469 }
1470
1471 // Reduce the number of job slots occupied and queued in the dispatcher
1472 // to one. If the second Job slot is queued in the dispatcher, cancels the
1473 // queued job. Otherwise, the second Job has been started by the
1474 // PrioritizedDispatcher, so signals it is complete.
1475 void ReduceToOneJobSlot() {
1476 DCHECK_GE(num_occupied_job_slots_, 1u);
1477 if (is_queued()) {
[email protected]106ccd2c2014-06-17 09:21:001478 resolver_->dispatcher_->Cancel(handle_);
[email protected]daae1322013-09-05 18:26:501479 handle_.Reset();
1480 } else if (num_occupied_job_slots_ > 1) {
[email protected]106ccd2c2014-06-17 09:21:001481 resolver_->dispatcher_->OnJobFinished();
[email protected]daae1322013-09-05 18:26:501482 --num_occupied_job_slots_;
1483 }
1484 DCHECK_EQ(1u, num_occupied_job_slots_);
1485 }
1486
juliatuttlec53b19a72016-05-05 13:51:311487 AddressList MakeAddressListForRequest(const AddressList& list) const {
1488 if (requests_.empty())
1489 return list;
1490 return AddressList::CopyWithPort(list, requests_.front()->info().port());
1491 }
1492
[email protected]51b9a6b2012-06-25 21:50:291493 void UpdatePriority() {
1494 if (is_queued()) {
1495 if (priority() != static_cast<RequestPriority>(handle_.priority()))
1496 priority_change_time_ = base::TimeTicks::Now();
[email protected]106ccd2c2014-06-17 09:21:001497 handle_ = resolver_->dispatcher_->ChangePriority(handle_, priority());
[email protected]51b9a6b2012-06-25 21:50:291498 }
1499 }
1500
[email protected]16ee26d2012-03-08 03:34:351501 // PriorityDispatch::Job:
dchengb03027d2014-10-21 12:00:201502 void Start() override {
[email protected]daae1322013-09-05 18:26:501503 DCHECK_LE(num_occupied_job_slots_, 1u);
1504
[email protected]70c04ab2013-08-22 16:05:121505 handle_.Reset();
[email protected]daae1322013-09-05 18:26:501506 ++num_occupied_job_slots_;
1507
1508 if (num_occupied_job_slots_ == 2) {
1509 StartSecondDnsTransaction();
1510 return;
1511 }
1512
1513 DCHECK(!is_running());
[email protected]0f292de02012-02-01 22:28:201514
[email protected]4da911f2012-06-14 19:45:201515 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_STARTED);
[email protected]0f292de02012-02-01 22:28:201516
[email protected]51b9a6b2012-06-25 21:50:291517 had_dns_config_ = resolver_->HaveDnsConfig();
1518
1519 base::TimeTicks now = base::TimeTicks::Now();
1520 base::TimeDelta queue_time = now - creation_time_;
1521 base::TimeDelta queue_time_after_change = now - priority_change_time_;
1522
1523 if (had_dns_config_) {
1524 DNS_HISTOGRAM_BY_PRIORITY("AsyncDNS.JobQueueTime", priority(),
1525 queue_time);
1526 DNS_HISTOGRAM_BY_PRIORITY("AsyncDNS.JobQueueTimeAfterChange", priority(),
1527 queue_time_after_change);
1528 } else {
1529 DNS_HISTOGRAM_BY_PRIORITY("DNS.JobQueueTime", priority(), queue_time);
1530 DNS_HISTOGRAM_BY_PRIORITY("DNS.JobQueueTimeAfterChange", priority(),
1531 queue_time_after_change);
1532 }
1533
[email protected]443714fad2013-09-19 04:52:011534 bool system_only =
1535 (key_.host_resolver_flags & HOST_RESOLVER_SYSTEM_ONLY) != 0;
1536
[email protected]1d932852012-06-19 19:40:331537 // Caution: Job::Start must not complete synchronously.
[email protected]443714fad2013-09-19 04:52:011538 if (!system_only && had_dns_config_ &&
1539 !ResemblesMulticastDNSName(key_.hostname)) {
[email protected]b3601bc22012-02-21 21:23:201540 StartDnsTask();
1541 } else {
1542 StartProcTask();
1543 }
1544 }
1545
[email protected]b3601bc22012-02-21 21:23:201546 // TODO(szym): Since DnsTransaction does not consume threads, we can increase
1547 // the limits on |dispatcher_|. But in order to keep the number of WorkerPool
1548 // threads low, we will need to use an "inner" PrioritizedDispatcher with
1549 // tighter limits.
1550 void StartProcTask() {
[email protected]16ee26d2012-03-08 03:34:351551 DCHECK(!is_dns_running());
[email protected]0f292de02012-02-01 22:28:201552 proc_task_ = new ProcTask(
1553 key_,
1554 resolver_->proc_params_,
[email protected]e3bd4822012-10-23 18:01:371555 base::Bind(&Job::OnProcTaskComplete, base::Unretained(this),
1556 base::TimeTicks::Now()),
[email protected]0f292de02012-02-01 22:28:201557 net_log_);
1558
1559 if (had_non_speculative_request_)
1560 proc_task_->set_had_non_speculative_request();
1561 // Start() could be called from within Resolve(), hence it must NOT directly
1562 // call OnProcTaskComplete, for example, on synchronous failure.
1563 proc_task_->Start();
[email protected]68ad3ee2010-01-30 03:45:391564 }
1565
[email protected]0f292de02012-02-01 22:28:201566 // Called by ProcTask when it completes.
[email protected]e3bd4822012-10-23 18:01:371567 void OnProcTaskComplete(base::TimeTicks start_time,
1568 int net_error,
1569 const AddressList& addr_list) {
[email protected]b3601bc22012-02-21 21:23:201570 DCHECK(is_proc_running());
[email protected]68ad3ee2010-01-30 03:45:391571
[email protected]62e86ba2013-01-29 18:59:161572 if (!resolver_->resolved_known_ipv6_hostname_ &&
1573 net_error == OK &&
1574 key_.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
1575 if (key_.hostname == "www.google.com") {
1576 resolver_->resolved_known_ipv6_hostname_ = true;
1577 bool got_ipv6_address = false;
1578 for (size_t i = 0; i < addr_list.size(); ++i) {
[email protected]5134c22a2013-08-06 18:09:021579 if (addr_list[i].GetFamily() == ADDRESS_FAMILY_IPV6) {
[email protected]62e86ba2013-01-29 18:59:161580 got_ipv6_address = true;
[email protected]5134c22a2013-08-06 18:09:021581 break;
1582 }
[email protected]62e86ba2013-01-29 18:59:161583 }
1584 UMA_HISTOGRAM_BOOLEAN("Net.UnspecResolvedIPv6", got_ipv6_address);
1585 }
1586 }
1587
[email protected]1d932852012-06-19 19:40:331588 if (dns_task_error_ != OK) {
[email protected]e3bd4822012-10-23 18:01:371589 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]1def74c2012-03-22 20:07:001590 if (net_error == OK) {
[email protected]e3bd4822012-10-23 18:01:371591 DNS_HISTOGRAM("AsyncDNS.FallbackSuccess", duration);
[email protected]1d932852012-06-19 19:40:331592 if ((dns_task_error_ == ERR_NAME_NOT_RESOLVED) &&
1593 ResemblesNetBIOSName(key_.hostname)) {
1594 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_SUSPECT_NETBIOS);
1595 } else {
1596 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_PROC_SUCCESS);
1597 }
davidbenad6fc442015-05-18 20:59:131598 UMA_HISTOGRAM_SPARSE_SLOWLY("AsyncDNS.ResolveError",
1599 std::abs(dns_task_error_));
[email protected]1ffdda82012-12-12 23:04:221600 resolver_->OnDnsTaskResolve(dns_task_error_);
[email protected]1def74c2012-03-22 20:07:001601 } else {
[email protected]e3bd4822012-10-23 18:01:371602 DNS_HISTOGRAM("AsyncDNS.FallbackFail", duration);
[email protected]1def74c2012-03-22 20:07:001603 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
1604 }
1605 }
1606
[email protected]1339a2a22012-10-17 08:39:431607 base::TimeDelta ttl =
1608 base::TimeDelta::FromSeconds(kNegativeCacheEntryTTLSeconds);
[email protected]b3601bc22012-02-21 21:23:201609 if (net_error == OK)
1610 ttl = base::TimeDelta::FromSeconds(kCacheEntryTTLSeconds);
[email protected]68ad3ee2010-01-30 03:45:391611
[email protected]895123222012-10-25 15:21:171612 // Don't store the |ttl| in cache since it's not obtained from the server.
1613 CompleteRequests(
1614 HostCache::Entry(net_error, MakeAddressListForRequest(addr_list)),
1615 ttl);
[email protected]b3601bc22012-02-21 21:23:201616 }
1617
1618 void StartDnsTask() {
[email protected]78eac2a2012-03-14 19:09:271619 DCHECK(resolver_->HaveDnsConfig());
[email protected]daae1322013-09-05 18:26:501620 dns_task_.reset(new DnsTask(resolver_->dns_client_.get(), key_, this,
1621 net_log_));
[email protected]b3601bc22012-02-21 21:23:201622
[email protected]daae1322013-09-05 18:26:501623 dns_task_->StartFirstTransaction();
1624 // Schedule a second transaction, if needed.
1625 if (dns_task_->needs_two_transactions())
1626 Schedule(true);
1627 }
1628
1629 void StartSecondDnsTransaction() {
1630 DCHECK(dns_task_->needs_two_transactions());
1631 dns_task_->StartSecondTransaction();
[email protected]16c2bd72013-06-28 01:19:221632 }
1633
1634 // Called if DnsTask fails. It is posted from StartDnsTask, so Job may be
1635 // deleted before this callback. In this case dns_task is deleted as well,
1636 // so we use it as indicator whether Job is still valid.
1637 void OnDnsTaskFailure(const base::WeakPtr<DnsTask>& dns_task,
1638 base::TimeDelta duration,
1639 int net_error) {
1640 DNS_HISTOGRAM("AsyncDNS.ResolveFail", duration);
1641
1642 if (dns_task == NULL)
1643 return;
1644
1645 dns_task_error_ = net_error;
1646
1647 // TODO(szym): Run ServeFromHosts now if nsswitch.conf says so.
1648 // http://crbug.com/117655
1649
1650 // TODO(szym): Some net errors indicate lack of connectivity. Starting
1651 // ProcTask in that case is a waste of time.
1652 if (resolver_->fallback_to_proctask_) {
[email protected]daae1322013-09-05 18:26:501653 KillDnsTask();
[email protected]16c2bd72013-06-28 01:19:221654 StartProcTask();
1655 } else {
1656 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
1657 CompleteRequestsWithError(net_error);
[email protected]b3601bc22012-02-21 21:23:201658 }
1659 }
1660
[email protected]daae1322013-09-05 18:26:501661
1662 // HostResolverImpl::DnsTask::Delegate implementation:
1663
dchengb03027d2014-10-21 12:00:201664 void OnDnsTaskComplete(base::TimeTicks start_time,
1665 int net_error,
1666 const AddressList& addr_list,
1667 base::TimeDelta ttl) override {
[email protected]b3601bc22012-02-21 21:23:201668 DCHECK(is_dns_running());
[email protected]b3601bc22012-02-21 21:23:201669
[email protected]e3bd4822012-10-23 18:01:371670 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]b3601bc22012-02-21 21:23:201671 if (net_error != OK) {
[email protected]16c2bd72013-06-28 01:19:221672 OnDnsTaskFailure(dns_task_->AsWeakPtr(), duration, net_error);
[email protected]b3601bc22012-02-21 21:23:201673 return;
1674 }
[email protected]e3bd4822012-10-23 18:01:371675 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess", duration);
[email protected]02cd6982013-01-10 20:12:511676 // Log DNS lookups based on |address_family|.
1677 switch(key_.address_family) {
1678 case ADDRESS_FAMILY_IPV4:
1679 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_IPV4", duration);
1680 break;
1681 case ADDRESS_FAMILY_IPV6:
1682 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_IPV6", duration);
1683 break;
1684 case ADDRESS_FAMILY_UNSPECIFIED:
1685 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_UNSPEC", duration);
1686 break;
1687 }
[email protected]b3601bc22012-02-21 21:23:201688
[email protected]1def74c2012-03-22 20:07:001689 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_DNS_SUCCESS);
[email protected]1339a2a22012-10-17 08:39:431690 RecordTTL(ttl);
[email protected]0adcb2b2012-08-15 21:30:461691
[email protected]1ffdda82012-12-12 23:04:221692 resolver_->OnDnsTaskResolve(OK);
[email protected]f0f602bd2012-11-15 18:01:021693
[email protected]895123222012-10-25 15:21:171694 base::TimeDelta bounded_ttl =
1695 std::max(ttl, base::TimeDelta::FromSeconds(kMinimumTTLSeconds));
1696
1697 CompleteRequests(
1698 HostCache::Entry(net_error, MakeAddressListForRequest(addr_list), ttl),
1699 bounded_ttl);
[email protected]b3601bc22012-02-21 21:23:201700 }
1701
dchengb03027d2014-10-21 12:00:201702 void OnFirstDnsTransactionComplete() override {
[email protected]daae1322013-09-05 18:26:501703 DCHECK(dns_task_->needs_two_transactions());
1704 DCHECK_EQ(dns_task_->needs_another_transaction(), is_queued());
1705 // No longer need to occupy two dispatcher slots.
1706 ReduceToOneJobSlot();
1707
1708 // We already have a job slot at the dispatcher, so if the second
1709 // transaction hasn't started, reuse it now instead of waiting in the queue
1710 // for the second slot.
1711 if (dns_task_->needs_another_transaction())
1712 dns_task_->StartSecondTransaction();
1713 }
1714
[email protected]16ee26d2012-03-08 03:34:351715 // Performs Job's last rites. Completes all Requests. Deletes this.
[email protected]895123222012-10-25 15:21:171716 void CompleteRequests(const HostCache::Entry& entry,
1717 base::TimeDelta ttl) {
[email protected]11fbca0b2013-06-02 23:37:211718 CHECK(resolver_.get());
[email protected]b3601bc22012-02-21 21:23:201719
[email protected]16ee26d2012-03-08 03:34:351720 // This job must be removed from resolver's |jobs_| now to make room for a
1721 // new job with the same key in case one of the OnComplete callbacks decides
1722 // to spawn one. Consequently, the job deletes itself when CompleteRequests
1723 // is done.
danakj22f90e72016-04-16 01:55:401724 std::unique_ptr<Job> self_deleter(this);
[email protected]16ee26d2012-03-08 03:34:351725
1726 resolver_->RemoveJob(this);
1727
[email protected]16ee26d2012-03-08 03:34:351728 if (is_running()) {
[email protected]16ee26d2012-03-08 03:34:351729 if (is_proc_running()) {
[email protected]daae1322013-09-05 18:26:501730 DCHECK(!is_queued());
[email protected]16ee26d2012-03-08 03:34:351731 proc_task_->Cancel();
1732 proc_task_ = NULL;
1733 }
[email protected]daae1322013-09-05 18:26:501734 KillDnsTask();
[email protected]16ee26d2012-03-08 03:34:351735
1736 // Signal dispatcher that a slot has opened.
[email protected]106ccd2c2014-06-17 09:21:001737 resolver_->dispatcher_->OnJobFinished();
[email protected]16ee26d2012-03-08 03:34:351738 } else if (is_queued()) {
[email protected]106ccd2c2014-06-17 09:21:001739 resolver_->dispatcher_->Cancel(handle_);
[email protected]16ee26d2012-03-08 03:34:351740 handle_.Reset();
1741 }
1742
1743 if (num_active_requests() == 0) {
[email protected]4da911f2012-06-14 19:45:201744 net_log_.AddEvent(NetLog::TYPE_CANCELLED);
[email protected]16ee26d2012-03-08 03:34:351745 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
1746 OK);
1747 return;
1748 }
[email protected]b3601bc22012-02-21 21:23:201749
1750 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
juliatuttle317860e2016-05-12 14:47:221751 entry.error());
[email protected]68ad3ee2010-01-30 03:45:391752
[email protected]78eac2a2012-03-14 19:09:271753 DCHECK(!requests_.empty());
1754
juliatuttle317860e2016-05-12 14:47:221755 if (entry.error() == OK) {
[email protected]d7b9a2b2012-05-31 22:31:191756 // Record this histogram here, when we know the system has a valid DNS
1757 // configuration.
[email protected]539df6c2012-06-19 21:21:291758 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.HaveDnsConfig",
1759 resolver_->received_dns_config_);
[email protected]d7b9a2b2012-05-31 22:31:191760 }
[email protected]16ee26d2012-03-08 03:34:351761
juliatuttle317860e2016-05-12 14:47:221762 bool did_complete = (entry.error() != ERR_NETWORK_CHANGED) &&
1763 (entry.error() != ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
[email protected]895123222012-10-25 15:21:171764 if (did_complete)
[email protected]1339a2a22012-10-17 08:39:431765 resolver_->CacheResult(key_, entry, ttl);
[email protected]16ee26d2012-03-08 03:34:351766
[email protected]0f292de02012-02-01 22:28:201767 // Complete all of the requests that were attached to the job.
danakj22f90e72016-04-16 01:55:401768 for (const std::unique_ptr<Request>& req : requests_) {
[email protected]0f292de02012-02-01 22:28:201769 if (req->was_canceled())
1770 continue;
1771
1772 DCHECK_EQ(this, req->job());
1773 // Update the net log and notify registered observers.
juliatuttle317860e2016-05-12 14:47:221774 LogFinishRequest(req->source_net_log(), req->info(), entry.error());
[email protected]51b9a6b2012-06-25 21:50:291775 if (did_complete) {
1776 // Record effective total time from creation to completion.
1777 RecordTotalTime(had_dns_config_, req->info().is_speculative(),
1778 base::TimeTicks::Now() - req->request_time());
1779 }
juliatuttle317860e2016-05-12 14:47:221780 req->OnComplete(entry.error(), entry.addresses());
[email protected]0f292de02012-02-01 22:28:201781
1782 // Check if the resolver was destroyed as a result of running the
1783 // callback. If it was, we could continue, but we choose to bail.
[email protected]11fbca0b2013-06-02 23:37:211784 if (!resolver_.get())
[email protected]0f292de02012-02-01 22:28:201785 return;
1786 }
1787 }
1788
[email protected]1339a2a22012-10-17 08:39:431789 // Convenience wrapper for CompleteRequests in case of failure.
1790 void CompleteRequestsWithError(int net_error) {
[email protected]895123222012-10-25 15:21:171791 CompleteRequests(HostCache::Entry(net_error, AddressList()),
1792 base::TimeDelta());
[email protected]1339a2a22012-10-17 08:39:431793 }
1794
[email protected]b4481b222012-03-16 17:13:111795 RequestPriority priority() const {
1796 return priority_tracker_.highest_priority();
1797 }
1798
1799 // Number of non-canceled requests in |requests_|.
1800 size_t num_active_requests() const {
1801 return priority_tracker_.total_count();
1802 }
1803
1804 bool is_dns_running() const {
1805 return dns_task_.get() != NULL;
1806 }
1807
1808 bool is_proc_running() const {
1809 return proc_task_.get() != NULL;
1810 }
1811
[email protected]0f292de02012-02-01 22:28:201812 base::WeakPtr<HostResolverImpl> resolver_;
1813
1814 Key key_;
1815
1816 // Tracks the highest priority across |requests_|.
1817 PriorityTracker priority_tracker_;
1818
1819 bool had_non_speculative_request_;
1820
[email protected]51b9a6b2012-06-25 21:50:291821 // Distinguishes measurements taken while DnsClient was fully configured.
1822 bool had_dns_config_;
1823
[email protected]daae1322013-09-05 18:26:501824 // Number of slots occupied by this Job in resolver's PrioritizedDispatcher.
1825 unsigned num_occupied_job_slots_;
1826
[email protected]1d932852012-06-19 19:40:331827 // Result of DnsTask.
1828 int dns_task_error_;
[email protected]1def74c2012-03-22 20:07:001829
[email protected]51b9a6b2012-06-25 21:50:291830 const base::TimeTicks creation_time_;
1831 base::TimeTicks priority_change_time_;
1832
[email protected]0f292de02012-02-01 22:28:201833 BoundNetLog net_log_;
1834
[email protected]b3601bc22012-02-21 21:23:201835 // Resolves the host using a HostResolverProc.
[email protected]0f292de02012-02-01 22:28:201836 scoped_refptr<ProcTask> proc_task_;
1837
[email protected]b3601bc22012-02-21 21:23:201838 // Resolves the host using a DnsTransaction.
danakj22f90e72016-04-16 01:55:401839 std::unique_ptr<DnsTask> dns_task_;
[email protected]b3601bc22012-02-21 21:23:201840
[email protected]0f292de02012-02-01 22:28:201841 // All Requests waiting for the result of this Job. Some can be canceled.
danakj22f90e72016-04-16 01:55:401842 std::vector<std::unique_ptr<Request>> requests_;
[email protected]0f292de02012-02-01 22:28:201843
[email protected]16ee26d2012-03-08 03:34:351844 // A handle used in |HostResolverImpl::dispatcher_|.
[email protected]0f292de02012-02-01 22:28:201845 PrioritizedDispatcher::Handle handle_;
[email protected]68ad3ee2010-01-30 03:45:391846};
1847
1848//-----------------------------------------------------------------------------
1849
[email protected]0f292de02012-02-01 22:28:201850HostResolverImpl::ProcTaskParams::ProcTaskParams(
[email protected]e95d3aca2010-01-11 22:47:431851 HostResolverProc* resolver_proc,
[email protected]0f292de02012-02-01 22:28:201852 size_t max_retry_attempts)
1853 : resolver_proc(resolver_proc),
1854 max_retry_attempts(max_retry_attempts),
ttuttlecf1158bf2016-03-18 16:37:441855 unresponsive_delay(
1856 base::TimeDelta::FromMilliseconds(kDnsDefaultUnresponsiveDelayMs)),
[email protected]0f292de02012-02-01 22:28:201857 retry_factor(2) {
[email protected]106ccd2c2014-06-17 09:21:001858 // Maximum of 4 retry attempts for host resolution.
1859 static const size_t kDefaultMaxRetryAttempts = 4u;
1860 if (max_retry_attempts == HostResolver::kDefaultRetryAttempts)
1861 max_retry_attempts = kDefaultMaxRetryAttempts;
[email protected]0f292de02012-02-01 22:28:201862}
1863
vmpstracd23b72016-02-26 21:08:551864HostResolverImpl::ProcTaskParams::ProcTaskParams(const ProcTaskParams& other) =
1865 default;
1866
[email protected]0f292de02012-02-01 22:28:201867HostResolverImpl::ProcTaskParams::~ProcTaskParams() {}
1868
[email protected]106ccd2c2014-06-17 09:21:001869HostResolverImpl::HostResolverImpl(const Options& options, NetLog* net_log)
1870 : max_queued_jobs_(0),
1871 proc_params_(NULL, options.max_retry_attempts),
[email protected]62e86ba2013-01-29 18:59:161872 net_log_(net_log),
[email protected]d7b9a2b2012-05-31 22:31:191873 received_dns_config_(false),
[email protected]f0f602bd2012-11-15 18:01:021874 num_dns_failures_(0),
[email protected]c9fa8f312013-09-17 12:24:521875 use_local_ipv6_(false),
sergeyub8cdc212015-05-14 18:50:371876 last_ipv6_probe_result_(true),
[email protected]62e86ba2013-01-29 18:59:161877 resolved_known_ipv6_hostname_(false),
[email protected]16c2bd72013-06-28 01:19:221878 additional_resolver_flags_(0),
[email protected]0a30cf512014-05-27 20:55:181879 fallback_to_proctask_(true),
1880 weak_ptr_factory_(this),
1881 probe_weak_ptr_factory_(this) {
[email protected]106ccd2c2014-06-17 09:21:001882 if (options.enable_caching)
1883 cache_ = HostCache::CreateDefaultCache();
[email protected]0f292de02012-02-01 22:28:201884
[email protected]106ccd2c2014-06-17 09:21:001885 PrioritizedDispatcher::Limits job_limits = options.GetDispatcherLimits();
1886 dispatcher_.reset(new PrioritizedDispatcher(job_limits));
1887 max_queued_jobs_ = job_limits.total_jobs * 100u;
[email protected]68ad3ee2010-01-30 03:45:391888
[email protected]106ccd2c2014-06-17 09:21:001889 DCHECK_GE(dispatcher_->num_priorities(), static_cast<size_t>(NUM_PRIORITIES));
[email protected]68ad3ee2010-01-30 03:45:391890
[email protected]b59ff372009-07-15 22:04:321891#if defined(OS_WIN)
1892 EnsureWinsockInit();
1893#endif
[email protected]7c466e92013-07-20 01:44:481894#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
[email protected]12faa4c2012-11-06 04:44:181895 new LoopbackProbeJob(weak_ptr_factory_.GetWeakPtr());
[email protected]2f3bc65c2010-07-23 17:47:101896#endif
[email protected]232a5812011-03-04 22:42:081897 NetworkChangeNotifier::AddIPAddressObserver(this);
ttuttlecf1158bf2016-03-18 16:37:441898 NetworkChangeNotifier::AddConnectionTypeObserver(this);
[email protected]bb0e34542012-08-31 19:52:401899 NetworkChangeNotifier::AddDNSObserver(this);
[email protected]d7b9a2b2012-05-31 22:31:191900#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD) && \
1901 !defined(OS_ANDROID)
[email protected]d7b9a2b2012-05-31 22:31:191902 EnsureDnsReloaderInit();
[email protected]46018c9d2011-09-06 03:42:341903#endif
[email protected]2ac22db2012-11-28 19:50:041904
ttuttlecf1158bf2016-03-18 16:37:441905 OnConnectionTypeChanged(NetworkChangeNotifier::GetConnectionType());
1906
[email protected]2ac22db2012-11-28 19:50:041907 {
1908 DnsConfig dns_config;
1909 NetworkChangeNotifier::GetDnsConfig(&dns_config);
1910 received_dns_config_ = dns_config.IsValid();
[email protected]c9fa8f312013-09-17 12:24:521911 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
1912 use_local_ipv6_ = !dns_config.IsValid() || dns_config.use_local_ipv6;
[email protected]2ac22db2012-11-28 19:50:041913 }
[email protected]16c2bd72013-06-28 01:19:221914
1915 fallback_to_proctask_ = !ConfigureAsyncDnsNoFallbackFieldTrial();
[email protected]b59ff372009-07-15 22:04:321916}
1917
1918HostResolverImpl::~HostResolverImpl() {
[email protected]daae1322013-09-05 18:26:501919 // Prevent the dispatcher from starting new jobs.
[email protected]106ccd2c2014-06-17 09:21:001920 dispatcher_->SetLimitsToZero();
[email protected]daae1322013-09-05 18:26:501921 // It's now safe for Jobs to call KillDsnTask on destruction, because
1922 // OnJobComplete will not start any new jobs.
[email protected]0f292de02012-02-01 22:28:201923 STLDeleteValues(&jobs_);
[email protected]e95d3aca2010-01-11 22:47:431924
[email protected]232a5812011-03-04 22:42:081925 NetworkChangeNotifier::RemoveIPAddressObserver(this);
ttuttlecf1158bf2016-03-18 16:37:441926 NetworkChangeNotifier::RemoveConnectionTypeObserver(this);
[email protected]bb0e34542012-08-31 19:52:401927 NetworkChangeNotifier::RemoveDNSObserver(this);
[email protected]b59ff372009-07-15 22:04:321928}
1929
[email protected]0f292de02012-02-01 22:28:201930void HostResolverImpl::SetMaxQueuedJobs(size_t value) {
[email protected]106ccd2c2014-06-17 09:21:001931 DCHECK_EQ(0u, dispatcher_->num_queued_jobs());
[email protected]0f292de02012-02-01 22:28:201932 DCHECK_GT(value, 0u);
1933 max_queued_jobs_ = value;
[email protected]be1a48b2011-01-20 00:12:131934}
1935
[email protected]684970b2009-08-14 04:54:461936int HostResolverImpl::Resolve(const RequestInfo& info,
[email protected]5109c1952013-08-20 18:44:101937 RequestPriority priority,
[email protected]b59ff372009-07-15 22:04:321938 AddressList* addresses,
[email protected]aa22b242011-11-16 18:58:291939 const CompletionCallback& callback,
[email protected]684970b2009-08-14 04:54:461940 RequestHandle* out_req,
[email protected]ee094b82010-08-24 15:55:511941 const BoundNetLog& source_net_log) {
[email protected]95a214c2011-08-04 21:50:401942 DCHECK(addresses);
[email protected]1ac6af92010-06-03 21:00:141943 DCHECK(CalledOnValidThread());
[email protected]aa22b242011-11-16 18:58:291944 DCHECK_EQ(false, callback.is_null());
[email protected]1ac6af92010-06-03 21:00:141945
[email protected]e806cd72013-05-17 02:08:431946 // Check that the caller supplied a valid hostname to resolve.
1947 std::string labeled_hostname;
1948 if (!DNSDomainFromDot(info.hostname(), &labeled_hostname))
1949 return ERR_NAME_NOT_RESOLVED;
1950
xunjieli26f90452014-11-10 16:23:021951 LogStartRequest(source_net_log, info);
[email protected]b59ff372009-07-15 22:04:321952
martijna23c8962016-03-04 18:18:511953 IPAddress ip_address;
1954 IPAddress* ip_address_ptr = nullptr;
1955 if (ip_address.AssignFromIPLiteral(info.hostname()))
1956 ip_address_ptr = &ip_address;
pauljensen19eb73422015-04-15 23:20:061957
[email protected]123ab1e32009-10-21 19:12:571958 // Build a key that identifies the request in the cache and in the
1959 // outstanding jobs map.
martijna23c8962016-03-04 18:18:511960 Key key = GetEffectiveKeyForRequest(info, ip_address_ptr, source_net_log);
[email protected]123ab1e32009-10-21 19:12:571961
martijna23c8962016-03-04 18:18:511962 int rv = ResolveHelper(key, info, ip_address_ptr, addresses, source_net_log);
[email protected]95a214c2011-08-04 21:50:401963 if (rv != ERR_DNS_CACHE_MISS) {
xunjieli26f90452014-11-10 16:23:021964 LogFinishRequest(source_net_log, info, rv);
[email protected]51b9a6b2012-06-25 21:50:291965 RecordTotalTime(HaveDnsConfig(), info.is_speculative(), base::TimeDelta());
[email protected]95a214c2011-08-04 21:50:401966 return rv;
[email protected]38368712011-03-02 08:09:401967 }
1968
[email protected]0f292de02012-02-01 22:28:201969 // Next we need to attach our request to a "job". This job is responsible for
1970 // calling "getaddrinfo(hostname)" on a worker thread.
1971
1972 JobMap::iterator jobit = jobs_.find(key);
1973 Job* job;
1974 if (jobit == jobs_.end()) {
[email protected]5109c1952013-08-20 18:44:101975 job =
xunjieli26f90452014-11-10 16:23:021976 new Job(weak_ptr_factory_.GetWeakPtr(), key, priority, source_net_log);
[email protected]daae1322013-09-05 18:26:501977 job->Schedule(false);
[email protected]0f292de02012-02-01 22:28:201978
1979 // Check for queue overflow.
[email protected]106ccd2c2014-06-17 09:21:001980 if (dispatcher_->num_queued_jobs() > max_queued_jobs_) {
1981 Job* evicted = static_cast<Job*>(dispatcher_->EvictOldestLowest());
[email protected]0f292de02012-02-01 22:28:201982 DCHECK(evicted);
[email protected]16ee26d2012-03-08 03:34:351983 evicted->OnEvicted(); // Deletes |evicted|.
[email protected]0f292de02012-02-01 22:28:201984 if (evicted == job) {
[email protected]0f292de02012-02-01 22:28:201985 rv = ERR_HOST_RESOLVER_QUEUE_TOO_LARGE;
xunjieli26f90452014-11-10 16:23:021986 LogFinishRequest(source_net_log, info, rv);
[email protected]0f292de02012-02-01 22:28:201987 return rv;
1988 }
[email protected]0f292de02012-02-01 22:28:201989 }
[email protected]0f292de02012-02-01 22:28:201990 jobs_.insert(jobit, std::make_pair(key, job));
1991 } else {
1992 job = jobit->second;
1993 }
1994
1995 // Can't complete synchronously. Create and attach request.
danakj22f90e72016-04-16 01:55:401996 std::unique_ptr<Request> req(
1997 new Request(source_net_log, info, priority, callback, addresses));
[email protected]b59ff372009-07-15 22:04:321998 if (out_req)
[email protected]b3601bc22012-02-21 21:23:201999 *out_req = reinterpret_cast<RequestHandle>(req.get());
[email protected]b59ff372009-07-15 22:04:322000
dchengc7eeda422015-12-26 03:56:482001 job->AddRequest(std::move(req));
[email protected]0f292de02012-02-01 22:28:202002 // Completion happens during Job::CompleteRequests().
[email protected]b59ff372009-07-15 22:04:322003 return ERR_IO_PENDING;
2004}
2005
[email protected]287d7c22011-11-15 17:34:252006int HostResolverImpl::ResolveHelper(const Key& key,
[email protected]95a214c2011-08-04 21:50:402007 const RequestInfo& info,
martijna23c8962016-03-04 18:18:512008 const IPAddress* ip_address,
[email protected]95a214c2011-08-04 21:50:402009 AddressList* addresses,
xunjieli26f90452014-11-10 16:23:022010 const BoundNetLog& source_net_log) {
[email protected]95a214c2011-08-04 21:50:402011 // The result of |getaddrinfo| for empty hosts is inconsistent across systems.
2012 // On Windows it gives the default interface's address, whereas on Linux it
2013 // gives an error. We will make it fail on all platforms for consistency.
2014 if (info.hostname().empty() || info.hostname().size() > kMaxHostLength)
2015 return ERR_NAME_NOT_RESOLVED;
2016
2017 int net_error = ERR_UNEXPECTED;
martijna23c8962016-03-04 18:18:512018 if (ResolveAsIP(key, info, ip_address, &net_error, addresses))
[email protected]95a214c2011-08-04 21:50:402019 return net_error;
[email protected]78eac2a2012-03-14 19:09:272020 if (ServeFromCache(key, info, &net_error, addresses)) {
xunjieli26f90452014-11-10 16:23:022021 source_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_CACHE_HIT);
[email protected]78eac2a2012-03-14 19:09:272022 return net_error;
2023 }
2024 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2025 // http://crbug.com/117655
2026 if (ServeFromHosts(key, info, addresses)) {
xunjieli26f90452014-11-10 16:23:022027 source_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_HOSTS_HIT);
[email protected]78eac2a2012-03-14 19:09:272028 return OK;
2029 }
estarkd1bc206e2015-06-20 00:44:392030
2031 if (ServeLocalhost(key, info, addresses))
2032 return OK;
2033
[email protected]78eac2a2012-03-14 19:09:272034 return ERR_DNS_CACHE_MISS;
[email protected]95a214c2011-08-04 21:50:402035}
2036
2037int HostResolverImpl::ResolveFromCache(const RequestInfo& info,
2038 AddressList* addresses,
2039 const BoundNetLog& source_net_log) {
2040 DCHECK(CalledOnValidThread());
2041 DCHECK(addresses);
2042
[email protected]95a214c2011-08-04 21:50:402043 // Update the net log and notify registered observers.
xunjieli26f90452014-11-10 16:23:022044 LogStartRequest(source_net_log, info);
[email protected]95a214c2011-08-04 21:50:402045
martijna23c8962016-03-04 18:18:512046 IPAddress ip_address;
2047 IPAddress* ip_address_ptr = nullptr;
2048 if (ip_address.AssignFromIPLiteral(info.hostname()))
2049 ip_address_ptr = &ip_address;
[email protected]95a214c2011-08-04 21:50:402050
martijna23c8962016-03-04 18:18:512051 Key key = GetEffectiveKeyForRequest(info, ip_address_ptr, source_net_log);
pauljensen19eb73422015-04-15 23:20:062052
martijna23c8962016-03-04 18:18:512053 int rv = ResolveHelper(key, info, ip_address_ptr, addresses, source_net_log);
xunjieli26f90452014-11-10 16:23:022054 LogFinishRequest(source_net_log, info, rv);
[email protected]95a214c2011-08-04 21:50:402055 return rv;
2056}
2057
juliatuttlec53b19a72016-05-05 13:51:312058void HostResolverImpl::ChangeRequestPriority(RequestHandle req_handle,
2059 RequestPriority priority) {
2060 DCHECK(CalledOnValidThread());
2061 Request* req = reinterpret_cast<Request*>(req_handle);
2062 DCHECK(req);
2063 Job* job = req->job();
2064 DCHECK(job);
2065 job->ChangeRequestPriority(req, priority);
2066}
2067
[email protected]b59ff372009-07-15 22:04:322068void HostResolverImpl::CancelRequest(RequestHandle req_handle) {
[email protected]1ac6af92010-06-03 21:00:142069 DCHECK(CalledOnValidThread());
[email protected]b59ff372009-07-15 22:04:322070 Request* req = reinterpret_cast<Request*>(req_handle);
2071 DCHECK(req);
[email protected]0f292de02012-02-01 22:28:202072 Job* job = req->job();
2073 DCHECK(job);
[email protected]0f292de02012-02-01 22:28:202074 job->CancelRequest(req);
[email protected]b59ff372009-07-15 22:04:322075}
2076
[email protected]a8883e452012-11-17 05:58:062077void HostResolverImpl::SetDnsClientEnabled(bool enabled) {
2078 DCHECK(CalledOnValidThread());
2079#if defined(ENABLE_BUILT_IN_DNS)
2080 if (enabled && !dns_client_) {
2081 SetDnsClient(DnsClient::CreateClient(net_log_));
2082 } else if (!enabled && dns_client_) {
danakj22f90e72016-04-16 01:55:402083 SetDnsClient(std::unique_ptr<DnsClient>());
[email protected]a8883e452012-11-17 05:58:062084 }
2085#endif
2086}
2087
[email protected]489d1a82011-10-12 03:09:112088HostCache* HostResolverImpl::GetHostCache() {
2089 return cache_.get();
2090}
[email protected]95a214c2011-08-04 21:50:402091
danakj22f90e72016-04-16 01:55:402092std::unique_ptr<base::Value> HostResolverImpl::GetDnsConfigAsValue() const {
[email protected]17e92032012-03-29 00:56:242093 // Check if async DNS is disabled.
2094 if (!dns_client_.get())
tfhef3618f2016-01-11 23:07:082095 return nullptr;
[email protected]17e92032012-03-29 00:56:242096
2097 // Check if async DNS is enabled, but we currently have no configuration
2098 // for it.
2099 const DnsConfig* dns_config = dns_client_->GetConfig();
2100 if (dns_config == NULL)
danakj22f90e72016-04-16 01:55:402101 return base::WrapUnique(new base::DictionaryValue());
[email protected]17e92032012-03-29 00:56:242102
2103 return dns_config->ToValue();
2104}
2105
[email protected]95a214c2011-08-04 21:50:402106bool HostResolverImpl::ResolveAsIP(const Key& key,
2107 const RequestInfo& info,
martijna23c8962016-03-04 18:18:512108 const IPAddress* ip_address,
[email protected]95a214c2011-08-04 21:50:402109 int* net_error,
2110 AddressList* addresses) {
2111 DCHECK(addresses);
2112 DCHECK(net_error);
martijna23c8962016-03-04 18:18:512113 if (ip_address == nullptr)
[email protected]95a214c2011-08-04 21:50:402114 return false;
2115
[email protected]95a214c2011-08-04 21:50:402116 *net_error = OK;
martijna23c8962016-03-04 18:18:512117 AddressFamily family = GetAddressFamily(*ip_address);
cbentzel1906f872015-06-05 16:25:252118 if (key.address_family != ADDRESS_FAMILY_UNSPECIFIED &&
2119 key.address_family != family) {
[email protected]1c7cf3f82014-08-07 21:33:482120 // Don't return IPv6 addresses for IPv4 queries, and vice versa.
[email protected]95a214c2011-08-04 21:50:402121 *net_error = ERR_NAME_NOT_RESOLVED;
2122 } else {
martijna23c8962016-03-04 18:18:512123 *addresses = AddressList::CreateFromIPAddress(*ip_address, info.port());
[email protected]7054e78f2012-05-07 21:44:562124 if (key.host_resolver_flags & HOST_RESOLVER_CANONNAME)
2125 addresses->SetDefaultCanonicalName();
[email protected]95a214c2011-08-04 21:50:402126 }
2127 return true;
2128}
2129
2130bool HostResolverImpl::ServeFromCache(const Key& key,
2131 const RequestInfo& info,
[email protected]95a214c2011-08-04 21:50:402132 int* net_error,
2133 AddressList* addresses) {
2134 DCHECK(addresses);
2135 DCHECK(net_error);
2136 if (!info.allow_cached_response() || !cache_.get())
2137 return false;
2138
[email protected]407a30ab2012-08-15 17:16:102139 const HostCache::Entry* cache_entry = cache_->Lookup(
2140 key, base::TimeTicks::Now());
[email protected]95a214c2011-08-04 21:50:402141 if (!cache_entry)
2142 return false;
2143
juliatuttle317860e2016-05-12 14:47:222144 *net_error = cache_entry->error();
[email protected]7054e78f2012-05-07 21:44:562145 if (*net_error == OK) {
[email protected]1339a2a22012-10-17 08:39:432146 if (cache_entry->has_ttl())
juliatuttle317860e2016-05-12 14:47:222147 RecordTTL(cache_entry->ttl());
2148 *addresses = EnsurePortOnAddressList(cache_entry->addresses(), info.port());
[email protected]7054e78f2012-05-07 21:44:562149 }
[email protected]95a214c2011-08-04 21:50:402150 return true;
2151}
2152
[email protected]78eac2a2012-03-14 19:09:272153bool HostResolverImpl::ServeFromHosts(const Key& key,
2154 const RequestInfo& info,
2155 AddressList* addresses) {
2156 DCHECK(addresses);
2157 if (!HaveDnsConfig())
2158 return false;
[email protected]05a79d42013-03-28 07:30:092159 addresses->clear();
2160
[email protected]cb507622012-03-23 16:17:062161 // HOSTS lookups are case-insensitive.
brettw8e2106d2015-08-11 19:30:222162 std::string hostname = base::ToLowerASCII(key.hostname);
[email protected]cb507622012-03-23 16:17:062163
[email protected]05a79d42013-03-28 07:30:092164 const DnsHosts& hosts = dns_client_->GetConfig()->hosts;
2165
[email protected]78eac2a2012-03-14 19:09:272166 // If |address_family| is ADDRESS_FAMILY_UNSPECIFIED other implementations
2167 // (glibc and c-ares) return the first matching line. We have more
2168 // flexibility, but lose implicit ordering.
[email protected]05a79d42013-03-28 07:30:092169 // We prefer IPv6 because "happy eyeballs" will fall back to IPv4 if
2170 // necessary.
2171 if (key.address_family == ADDRESS_FAMILY_IPV6 ||
2172 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
2173 DnsHosts::const_iterator it = hosts.find(
2174 DnsHostsKey(hostname, ADDRESS_FAMILY_IPV6));
2175 if (it != hosts.end())
2176 addresses->push_back(IPEndPoint(it->second, info.port()));
[email protected]78eac2a2012-03-14 19:09:272177 }
2178
[email protected]05a79d42013-03-28 07:30:092179 if (key.address_family == ADDRESS_FAMILY_IPV4 ||
2180 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
2181 DnsHosts::const_iterator it = hosts.find(
2182 DnsHostsKey(hostname, ADDRESS_FAMILY_IPV4));
2183 if (it != hosts.end())
2184 addresses->push_back(IPEndPoint(it->second, info.port()));
2185 }
2186
[email protected]ec666ab22013-04-17 20:05:592187 // If got only loopback addresses and the family was restricted, resolve
2188 // again, without restrictions. See SystemHostResolverCall for rationale.
2189 if ((key.host_resolver_flags &
2190 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6) &&
2191 IsAllIPv4Loopback(*addresses)) {
2192 Key new_key(key);
2193 new_key.address_family = ADDRESS_FAMILY_UNSPECIFIED;
2194 new_key.host_resolver_flags &=
2195 ~HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
2196 return ServeFromHosts(new_key, info, addresses);
2197 }
[email protected]05a79d42013-03-28 07:30:092198 return !addresses->empty();
[email protected]78eac2a2012-03-14 19:09:272199}
2200
estarkd1bc206e2015-06-20 00:44:392201bool HostResolverImpl::ServeLocalhost(const Key& key,
2202 const RequestInfo& info,
2203 AddressList* addresses) {
2204 AddressList resolved_addresses;
2205 if (!ResolveLocalHostname(key.hostname, info.port(), &resolved_addresses))
2206 return false;
2207
2208 addresses->clear();
2209
2210 for (const auto& address : resolved_addresses) {
2211 // Include the address if:
2212 // - caller didn't specify an address family, or
2213 // - caller specifically asked for the address family of this address, or
2214 // - this is an IPv6 address and caller specifically asked for IPv4 due
2215 // to lack of detected IPv6 support. (See SystemHostResolverCall for
2216 // rationale).
2217 if (key.address_family == ADDRESS_FAMILY_UNSPECIFIED ||
2218 key.address_family == address.GetFamily() ||
2219 (address.GetFamily() == ADDRESS_FAMILY_IPV6 &&
2220 key.address_family == ADDRESS_FAMILY_IPV4 &&
2221 (key.host_resolver_flags &
2222 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6))) {
2223 addresses->push_back(address);
2224 }
2225 }
2226
2227 return true;
2228}
2229
[email protected]16ee26d2012-03-08 03:34:352230void HostResolverImpl::CacheResult(const Key& key,
[email protected]1339a2a22012-10-17 08:39:432231 const HostCache::Entry& entry,
[email protected]16ee26d2012-03-08 03:34:352232 base::TimeDelta ttl) {
2233 if (cache_.get())
[email protected]1339a2a22012-10-17 08:39:432234 cache_->Set(key, entry, base::TimeTicks::Now(), ttl);
[email protected]ef4c40c2010-09-01 14:42:032235}
2236
[email protected]0f292de02012-02-01 22:28:202237void HostResolverImpl::RemoveJob(Job* job) {
2238 DCHECK(job);
[email protected]16ee26d2012-03-08 03:34:352239 JobMap::iterator it = jobs_.find(job->key());
2240 if (it != jobs_.end() && it->second == job)
2241 jobs_.erase(it);
[email protected]b59ff372009-07-15 22:04:322242}
2243
[email protected]9936a7862012-10-26 04:44:022244void HostResolverImpl::SetHaveOnlyLoopbackAddresses(bool result) {
2245 if (result) {
2246 additional_resolver_flags_ |= HOST_RESOLVER_LOOPBACK_ONLY;
2247 } else {
2248 additional_resolver_flags_ &= ~HOST_RESOLVER_LOOPBACK_ONLY;
2249 }
2250}
2251
[email protected]137af622010-02-05 02:14:352252HostResolverImpl::Key HostResolverImpl::GetEffectiveKeyForRequest(
pauljensen19eb73422015-04-15 23:20:062253 const RequestInfo& info,
martijna23c8962016-03-04 18:18:512254 const IPAddress* ip_address,
sergeyub8cdc212015-05-14 18:50:372255 const BoundNetLog& net_log) {
[email protected]eaf3a3b2010-09-03 20:34:272256 HostResolverFlags effective_flags =
2257 info.host_resolver_flags() | additional_resolver_flags_;
[email protected]137af622010-02-05 02:14:352258 AddressFamily effective_address_family = info.address_family();
[email protected]9db6f702013-04-10 18:10:512259
2260 if (info.address_family() == ADDRESS_FAMILY_UNSPECIFIED) {
cbentzel1906f872015-06-05 16:25:252261 if (!use_local_ipv6_ &&
pauljensen19eb73422015-04-15 23:20:062262 // When resolving IPv4 literals, there's no need to probe for IPv6.
2263 // When resolving IPv6 literals, there's no benefit to artificially
2264 // limiting our resolution based on a probe. Prior logic ensures
2265 // that this query is UNSPECIFIED (see info.address_family()
cbentzel1906f872015-06-05 16:25:252266 // check above) so the code requesting the resolution should be amenable
2267 // to receiving a IPv6 resolution.
martijna23c8962016-03-04 18:18:512268 ip_address == nullptr) {
sergeyub8cdc212015-05-14 18:50:372269 if (!IsIPv6Reachable(net_log)) {
[email protected]ac0b52e2013-04-21 01:26:162270 effective_address_family = ADDRESS_FAMILY_IPV4;
2271 effective_flags |= HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
2272 }
[email protected]9db6f702013-04-10 18:10:512273 }
2274 }
2275
estarkd1bc206e2015-06-20 00:44:392276 return Key(info.hostname(), effective_address_family, effective_flags);
[email protected]137af622010-02-05 02:14:352277}
2278
sergeyub8cdc212015-05-14 18:50:372279bool HostResolverImpl::IsIPv6Reachable(const BoundNetLog& net_log) {
2280 base::TimeTicks now = base::TimeTicks::Now();
2281 bool cached = true;
2282 if ((now - last_ipv6_probe_time_).InMilliseconds() > kIPv6ProbePeriodMs) {
martijna23c8962016-03-04 18:18:512283 last_ipv6_probe_result_ =
2284 IsGloballyReachable(IPAddress(kIPv6ProbeAddress), net_log);
sergeyub8cdc212015-05-14 18:50:372285 last_ipv6_probe_time_ = now;
2286 cached = false;
2287 }
2288 net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_IPV6_REACHABILITY_CHECK,
2289 base::Bind(&NetLogIPv6AvailableCallback,
2290 last_ipv6_probe_result_, cached));
2291 return last_ipv6_probe_result_;
2292}
2293
[email protected]35ddc282010-09-21 23:42:062294void HostResolverImpl::AbortAllInProgressJobs() {
[email protected]b3601bc22012-02-21 21:23:202295 // In Abort, a Request callback could spawn new Jobs with matching keys, so
2296 // first collect and remove all running jobs from |jobs_|.
danakj22f90e72016-04-16 01:55:402297 std::vector<std::unique_ptr<Job>> jobs_to_abort;
[email protected]0f292de02012-02-01 22:28:202298 for (JobMap::iterator it = jobs_.begin(); it != jobs_.end(); ) {
2299 Job* job = it->second;
[email protected]0f292de02012-02-01 22:28:202300 if (job->is_running()) {
danakj22f90e72016-04-16 01:55:402301 jobs_to_abort.push_back(base::WrapUnique(job));
[email protected]b3601bc22012-02-21 21:23:202302 jobs_.erase(it++);
[email protected]0f292de02012-02-01 22:28:202303 } else {
[email protected]b3601bc22012-02-21 21:23:202304 DCHECK(job->is_queued());
2305 ++it;
[email protected]0f292de02012-02-01 22:28:202306 }
[email protected]ef4c40c2010-09-01 14:42:032307 }
[email protected]b3601bc22012-02-21 21:23:202308
[email protected]daae1322013-09-05 18:26:502309 // Pause the dispatcher so it won't start any new dispatcher jobs while
2310 // aborting the old ones. This is needed so that it won't start the second
2311 // DnsTransaction for a job in |jobs_to_abort| if the DnsConfig just became
2312 // invalid.
[email protected]106ccd2c2014-06-17 09:21:002313 PrioritizedDispatcher::Limits limits = dispatcher_->GetLimits();
2314 dispatcher_->SetLimits(
[email protected]daae1322013-09-05 18:26:502315 PrioritizedDispatcher::Limits(limits.reserved_slots.size(), 0));
[email protected]70c04ab2013-08-22 16:05:122316
[email protected]57a48d32012-03-03 00:04:552317 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072318 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]57a48d32012-03-03 00:04:552319
[email protected]16ee26d2012-03-08 03:34:352320 // Then Abort them.
[email protected]11fbca0b2013-06-02 23:37:212321 for (size_t i = 0; self.get() && i < jobs_to_abort.size(); ++i) {
[email protected]57a48d32012-03-03 00:04:552322 jobs_to_abort[i]->Abort();
olli.raulaa21e9eb72015-12-17 08:18:112323 ignore_result(jobs_to_abort[i].release());
[email protected]b3601bc22012-02-21 21:23:202324 }
[email protected]daae1322013-09-05 18:26:502325
2326 if (self)
[email protected]106ccd2c2014-06-17 09:21:002327 dispatcher_->SetLimits(limits);
[email protected]daae1322013-09-05 18:26:502328}
2329
2330void HostResolverImpl::AbortDnsTasks() {
2331 // 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 if the DnsConfig just changed.
[email protected]106ccd2c2014-06-17 09:21:002334 PrioritizedDispatcher::Limits limits = dispatcher_->GetLimits();
2335 dispatcher_->SetLimits(
[email protected]daae1322013-09-05 18:26:502336 PrioritizedDispatcher::Limits(limits.reserved_slots.size(), 0));
2337
2338 for (JobMap::iterator it = jobs_.begin(); it != jobs_.end(); ++it)
2339 it->second->AbortDnsTask();
[email protected]106ccd2c2014-06-17 09:21:002340 dispatcher_->SetLimits(limits);
[email protected]ef4c40c2010-09-01 14:42:032341}
2342
[email protected]78eac2a2012-03-14 19:09:272343void HostResolverImpl::TryServingAllJobsFromHosts() {
2344 if (!HaveDnsConfig())
2345 return;
2346
2347 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2348 // http://crbug.com/117655
2349
2350 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072351 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]78eac2a2012-03-14 19:09:272352
[email protected]11fbca0b2013-06-02 23:37:212353 for (JobMap::iterator it = jobs_.begin(); self.get() && it != jobs_.end();) {
[email protected]78eac2a2012-03-14 19:09:272354 Job* job = it->second;
2355 ++it;
2356 // This could remove |job| from |jobs_|, but iterator will remain valid.
2357 job->ServeFromHosts();
2358 }
2359}
2360
[email protected]be1a48b2011-01-20 00:12:132361void HostResolverImpl::OnIPAddressChanged() {
[email protected]62e86ba2013-01-29 18:59:162362 resolved_known_ipv6_hostname_ = false;
sergeyub8cdc212015-05-14 18:50:372363 last_ipv6_probe_time_ = base::TimeTicks();
[email protected]12faa4c2012-11-06 04:44:182364 // Abandon all ProbeJobs.
2365 probe_weak_ptr_factory_.InvalidateWeakPtrs();
[email protected]be1a48b2011-01-20 00:12:132366 if (cache_.get())
2367 cache_->clear();
[email protected]7c466e92013-07-20 01:44:482368#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
[email protected]12faa4c2012-11-06 04:44:182369 new LoopbackProbeJob(probe_weak_ptr_factory_.GetWeakPtr());
[email protected]be1a48b2011-01-20 00:12:132370#endif
2371 AbortAllInProgressJobs();
2372 // |this| may be deleted inside AbortAllInProgressJobs().
2373}
2374
ttuttlecf1158bf2016-03-18 16:37:442375void HostResolverImpl::OnConnectionTypeChanged(
2376 NetworkChangeNotifier::ConnectionType type) {
2377 proc_params_.unresponsive_delay =
2378 GetTimeDeltaForConnectionTypeFromFieldTrialOrDefault(
2379 "DnsUnresponsiveDelayMsByConnectionType",
2380 base::TimeDelta::FromMilliseconds(kDnsDefaultUnresponsiveDelayMs),
2381 type);
2382}
2383
pauljensen101ed372015-04-17 00:11:422384void HostResolverImpl::OnInitialDNSConfigRead() {
2385 UpdateDNSConfig(false);
2386}
2387
[email protected]bb0e34542012-08-31 19:52:402388void HostResolverImpl::OnDNSChanged() {
pauljensen101ed372015-04-17 00:11:422389 UpdateDNSConfig(true);
2390}
2391
2392void HostResolverImpl::UpdateDNSConfig(bool config_changed) {
[email protected]bb0e34542012-08-31 19:52:402393 DnsConfig dns_config;
2394 NetworkChangeNotifier::GetDnsConfig(&dns_config);
[email protected]ec666ab22013-04-17 20:05:592395
[email protected]b4481b222012-03-16 17:13:112396 if (net_log_) {
2397 net_log_->AddGlobalEntry(
2398 NetLog::TYPE_DNS_CONFIG_CHANGED,
[email protected]cd565142012-06-12 16:21:452399 base::Bind(&NetLogDnsConfigCallback, &dns_config));
[email protected]b4481b222012-03-16 17:13:112400 }
2401
[email protected]01b3b9d2012-08-13 16:18:142402 // TODO(szym): Remove once http://crbug.com/137914 is resolved.
[email protected]d7b9a2b2012-05-31 22:31:192403 received_dns_config_ = dns_config.IsValid();
[email protected]c9fa8f312013-09-17 12:24:522404 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
2405 use_local_ipv6_ = !dns_config.IsValid() || dns_config.use_local_ipv6;
[email protected]78eac2a2012-03-14 19:09:272406
[email protected]a8883e452012-11-17 05:58:062407 num_dns_failures_ = 0;
2408
[email protected]01b3b9d2012-08-13 16:18:142409 // We want a new DnsSession in place, before we Abort running Jobs, so that
2410 // the newly started jobs use the new config.
[email protected]f0f602bd2012-11-15 18:01:022411 if (dns_client_.get()) {
[email protected]d7b9a2b2012-05-31 22:31:192412 dns_client_->SetConfig(dns_config);
pauljensen101ed372015-04-17 00:11:422413 if (dns_client_->GetConfig()) {
[email protected]f0f602bd2012-11-15 18:01:022414 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
pauljensen101ed372015-04-17 00:11:422415 // If we just switched DnsClients, restart jobs using new resolver.
2416 // TODO(pauljensen): Is this necessary?
2417 config_changed = true;
2418 }
[email protected]f0f602bd2012-11-15 18:01:022419 }
[email protected]01b3b9d2012-08-13 16:18:142420
pauljensen101ed372015-04-17 00:11:422421 if (config_changed) {
2422 // If the DNS server has changed, existing cached info could be wrong so we
2423 // have to drop our internal cache :( Note that OS level DNS caches, such
2424 // as NSCD's cache should be dropped automatically by the OS when
2425 // resolv.conf changes so we don't need to do anything to clear that cache.
2426 if (cache_.get())
2427 cache_->clear();
[email protected]01b3b9d2012-08-13 16:18:142428
pauljensen101ed372015-04-17 00:11:422429 // Life check to bail once |this| is deleted.
2430 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]f0f602bd2012-11-15 18:01:022431
pauljensen101ed372015-04-17 00:11:422432 // Existing jobs will have been sent to the original server so they need to
2433 // be aborted.
2434 AbortAllInProgressJobs();
[email protected]01b3b9d2012-08-13 16:18:142435
pauljensen101ed372015-04-17 00:11:422436 // |this| may be deleted inside AbortAllInProgressJobs().
2437 if (self.get())
2438 TryServingAllJobsFromHosts();
2439 }
[email protected]78eac2a2012-03-14 19:09:272440}
2441
2442bool HostResolverImpl::HaveDnsConfig() const {
[email protected]32b1dbcf2013-01-26 03:48:252443 // Use DnsClient only if it's fully configured and there is no override by
2444 // ScopedDefaultHostResolverProc.
2445 // The alternative is to use NetworkChangeNotifier to override DnsConfig,
2446 // but that would introduce construction order requirements for NCN and SDHRP.
[email protected]90499482013-06-01 00:39:502447 return (dns_client_.get() != NULL) && (dns_client_->GetConfig() != NULL) &&
2448 !(proc_params_.resolver_proc.get() == NULL &&
[email protected]32b1dbcf2013-01-26 03:48:252449 HostResolverProc::GetDefault() != NULL);
[email protected]b3601bc22012-02-21 21:23:202450}
2451
[email protected]1ffdda82012-12-12 23:04:222452void HostResolverImpl::OnDnsTaskResolve(int net_error) {
[email protected]f0f602bd2012-11-15 18:01:022453 DCHECK(dns_client_);
[email protected]1ffdda82012-12-12 23:04:222454 if (net_error == OK) {
[email protected]f0f602bd2012-11-15 18:01:022455 num_dns_failures_ = 0;
2456 return;
2457 }
2458 ++num_dns_failures_;
2459 if (num_dns_failures_ < kMaximumDnsFailures)
2460 return;
[email protected]daae1322013-09-05 18:26:502461
2462 // Disable DnsClient until the next DNS change. Must be done before aborting
2463 // DnsTasks, since doing so may start new jobs.
[email protected]f0f602bd2012-11-15 18:01:022464 dns_client_->SetConfig(DnsConfig());
[email protected]daae1322013-09-05 18:26:502465
2466 // Switch jobs with active DnsTasks over to using ProcTasks.
2467 AbortDnsTasks();
2468
[email protected]f0f602bd2012-11-15 18:01:022469 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", false);
davidbenad6fc442015-05-18 20:59:132470 UMA_HISTOGRAM_SPARSE_SLOWLY("AsyncDNS.DnsClientDisabledReason",
2471 std::abs(net_error));
[email protected]f0f602bd2012-11-15 18:01:022472}
2473
danakj22f90e72016-04-16 01:55:402474void HostResolverImpl::SetDnsClient(std::unique_ptr<DnsClient> dns_client) {
[email protected]daae1322013-09-05 18:26:502475 // DnsClient and config must be updated before aborting DnsTasks, since doing
2476 // so may start new jobs.
dchengc7eeda422015-12-26 03:56:482477 dns_client_ = std::move(dns_client);
[email protected]daae1322013-09-05 18:26:502478 if (dns_client_ && !dns_client_->GetConfig() &&
2479 num_dns_failures_ < kMaximumDnsFailures) {
2480 DnsConfig dns_config;
2481 NetworkChangeNotifier::GetDnsConfig(&dns_config);
2482 dns_client_->SetConfig(dns_config);
2483 num_dns_failures_ = 0;
2484 if (dns_client_->GetConfig())
2485 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
[email protected]a8883e452012-11-17 05:58:062486 }
[email protected]daae1322013-09-05 18:26:502487
2488 AbortDnsTasks();
[email protected]a8883e452012-11-17 05:58:062489}
2490
[email protected]b59ff372009-07-15 22:04:322491} // namespace net