blob: 0e2de328866d4cd3ff8dc8e737962755adfba393 [file] [log] [blame]
[email protected]a2730882012-01-21 00:56:271// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]b59ff372009-07-15 22:04:322// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
[email protected]f2cb3cf2013-03-21 01:40:535#include "net/dns/host_resolver_impl.h"
[email protected]b59ff372009-07-15 22:04:326
[email protected]21526002010-05-16 19:42:467#if defined(OS_WIN)
8#include <Winsock2.h>
9#elif defined(OS_POSIX)
10#include <netdb.h>
11#endif
12
[email protected]68ad3ee2010-01-30 03:45:3913#include <cmath>
[email protected]0f292de02012-02-01 22:28:2014#include <utility>
[email protected]21526002010-05-16 19:42:4615#include <vector>
[email protected]68ad3ee2010-01-30 03:45:3916
17#include "base/basictypes.h"
[email protected]33152acc2011-10-20 23:37:1218#include "base/bind.h"
[email protected]aa22b242011-11-16 18:58:2919#include "base/bind_helpers.h"
[email protected]0f292de02012-02-01 22:28:2020#include "base/callback.h"
[email protected]b59ff372009-07-15 22:04:3221#include "base/compiler_specific.h"
[email protected]58580352010-10-26 04:07:5022#include "base/debug/debugger.h"
23#include "base/debug/stack_trace.h"
[email protected]1e9bbd22010-10-15 16:42:4524#include "base/metrics/field_trial.h"
davidbenad6fc442015-05-18 20:59:1325#include "base/metrics/histogram_macros.h"
26#include "base/metrics/sparse_histogram.h"
eromane1867242015-04-23 23:07:4427#include "base/profiler/scoped_tracker.h"
anujk.sharma7c907f02015-05-29 02:55:4428#include "base/single_thread_task_runner.h"
[email protected]7286e3fc2011-07-19 22:13:2429#include "base/stl_util.h"
[email protected]be528af2013-06-11 07:39:4830#include "base/strings/string_util.h"
[email protected]750b2f3c2013-06-07 18:41:0531#include "base/strings/utf_string_conversions.h"
anujk.sharma7c907f02015-05-29 02:55:4432#include "base/thread_task_runner_handle.h"
[email protected]ac9ba8fe2010-12-30 18:08:3633#include "base/threading/worker_pool.h"
[email protected]66e96c42013-06-28 15:20:3134#include "base/time/time.h"
[email protected]21526002010-05-16 19:42:4635#include "base/values.h"
[email protected]b3601bc22012-02-21 21:23:2036#include "net/base/address_family.h"
[email protected]b59ff372009-07-15 22:04:3237#include "net/base/address_list.h"
[email protected]46018c9d2011-09-06 03:42:3438#include "net/base/dns_reloader.h"
[email protected]e806cd72013-05-17 02:08:4339#include "net/base/dns_util.h"
[email protected]ee094b82010-08-24 15:55:5140#include "net/base/host_port_pair.h"
[email protected]1c7cf3f82014-08-07 21:33:4841#include "net/base/ip_endpoint.h"
[email protected]2bb04442010-08-18 18:01:1542#include "net/base/net_errors.h"
[email protected]0f8f1b432010-03-16 19:06:0343#include "net/base/net_util.h"
[email protected]0adcb2b2012-08-15 21:30:4644#include "net/dns/address_sorter.h"
[email protected]78eac2a2012-03-14 19:09:2745#include "net/dns/dns_client.h"
[email protected]b3601bc22012-02-21 21:23:2046#include "net/dns/dns_config_service.h"
47#include "net/dns/dns_protocol.h"
48#include "net/dns/dns_response.h"
[email protected]b3601bc22012-02-21 21:23:2049#include "net/dns/dns_transaction.h"
[email protected]f2cb3cf2013-03-21 01:40:5350#include "net/dns/host_resolver_proc.h"
eroman87c53d62015-04-02 06:51:0751#include "net/log/net_log.h"
[email protected]9db6f702013-04-10 18:10:5152#include "net/socket/client_socket_factory.h"
53#include "net/udp/datagram_client_socket.h"
pauljensen370f1c72015-02-17 16:59:1454#include "url/url_canon_ip.h"
[email protected]b59ff372009-07-15 22:04:3255
56#if defined(OS_WIN)
57#include "net/base/winsock_init.h"
58#endif
59
60namespace net {
61
[email protected]e95d3aca2010-01-11 22:47:4362namespace {
63
[email protected]6e78dfb2011-07-28 21:34:4764// Limit the size of hostnames that will be resolved to combat issues in
65// some platform's resolvers.
66const size_t kMaxHostLength = 4096;
67
[email protected]a2730882012-01-21 00:56:2768// Default TTL for successful resolutions with ProcTask.
69const unsigned kCacheEntryTTLSeconds = 60;
70
[email protected]b3601bc22012-02-21 21:23:2071// Default TTL for unsuccessful resolutions with ProcTask.
72const unsigned kNegativeCacheEntryTTLSeconds = 0;
73
[email protected]895123222012-10-25 15:21:1774// Minimum TTL for successful resolutions with DnsTask.
75const unsigned kMinimumTTLSeconds = kCacheEntryTTLSeconds;
76
sergeyub8cdc212015-05-14 18:50:3777// Time between IPv6 probes, i.e. for how long results of each IPv6 probe are
78// cached.
79const int kIPv6ProbePeriodMs = 1000;
80
81// Google DNS address used for IPv6 probes.
82const uint8_t kIPv6ProbeAddress[] =
83 { 0x20, 0x01, 0x48, 0x60, 0x48, 0x60, 0x00, 0x00,
84 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x88 };
85
[email protected]24f4bab2010-10-15 01:27:1186// We use a separate histogram name for each platform to facilitate the
87// display of error codes by their symbolic name (since each platform has
88// different mappings).
89const char kOSErrorsForGetAddrinfoHistogramName[] =
90#if defined(OS_WIN)
91 "Net.OSErrorsForGetAddrinfo_Win";
92#elif defined(OS_MACOSX)
93 "Net.OSErrorsForGetAddrinfo_Mac";
94#elif defined(OS_LINUX)
95 "Net.OSErrorsForGetAddrinfo_Linux";
96#else
97 "Net.OSErrorsForGetAddrinfo";
98#endif
99
[email protected]c89b2442011-05-26 14:28:27100// Gets a list of the likely error codes that getaddrinfo() can return
101// (non-exhaustive). These are the error codes that we will track via
102// a histogram.
103std::vector<int> GetAllGetAddrinfoOSErrors() {
104 int os_errors[] = {
105#if defined(OS_POSIX)
[email protected]23f771162011-06-02 18:37:51106#if !defined(OS_FREEBSD)
[email protected]39588992011-07-11 19:54:37107#if !defined(OS_ANDROID)
[email protected]c48aef92011-11-22 23:41:45108 // EAI_ADDRFAMILY has been declared obsolete in Android's and
109 // FreeBSD's netdb.h.
[email protected]c89b2442011-05-26 14:28:27110 EAI_ADDRFAMILY,
[email protected]39588992011-07-11 19:54:37111#endif
[email protected]c48aef92011-11-22 23:41:45112 // EAI_NODATA has been declared obsolete in FreeBSD's netdb.h.
[email protected]23f771162011-06-02 18:37:51113 EAI_NODATA,
114#endif
[email protected]c89b2442011-05-26 14:28:27115 EAI_AGAIN,
116 EAI_BADFLAGS,
117 EAI_FAIL,
118 EAI_FAMILY,
119 EAI_MEMORY,
[email protected]c89b2442011-05-26 14:28:27120 EAI_NONAME,
121 EAI_SERVICE,
122 EAI_SOCKTYPE,
123 EAI_SYSTEM,
124#elif defined(OS_WIN)
125 // See: http://msdn.microsoft.com/en-us/library/ms738520(VS.85).aspx
126 WSA_NOT_ENOUGH_MEMORY,
127 WSAEAFNOSUPPORT,
128 WSAEINVAL,
129 WSAESOCKTNOSUPPORT,
130 WSAHOST_NOT_FOUND,
131 WSANO_DATA,
132 WSANO_RECOVERY,
133 WSANOTINITIALISED,
134 WSATRY_AGAIN,
135 WSATYPE_NOT_FOUND,
136 // The following are not in doc, but might be to appearing in results :-(.
137 WSA_INVALID_HANDLE,
138#endif
139 };
140
141 // Ensure all errors are positive, as histogram only tracks positive values.
142 for (size_t i = 0; i < arraysize(os_errors); ++i) {
143 os_errors[i] = std::abs(os_errors[i]);
144 }
145
146 return base::CustomHistogram::ArrayToCustomRanges(os_errors,
147 arraysize(os_errors));
148}
149
[email protected]1def74c2012-03-22 20:07:00150enum DnsResolveStatus {
151 RESOLVE_STATUS_DNS_SUCCESS = 0,
152 RESOLVE_STATUS_PROC_SUCCESS,
153 RESOLVE_STATUS_FAIL,
[email protected]1d932852012-06-19 19:40:33154 RESOLVE_STATUS_SUSPECT_NETBIOS,
[email protected]1def74c2012-03-22 20:07:00155 RESOLVE_STATUS_MAX
156};
157
eroman91dd3602015-03-26 03:46:33158// ICANN uses this localhost address to indicate a name collision.
159//
160// The policy in Chromium is to fail host resolving if it resolves to
161// this special address.
162//
163// Not however that IP literals are exempt from this policy, so it is still
164// possible to navigate to http://127.0.53.53/ directly.
165//
166// For more details: https://www.icann.org/news/announcement-2-2014-08-01-en
167const unsigned char kIcanNameCollisionIp[] = {127, 0, 53, 53};
168
[email protected]1def74c2012-03-22 20:07:00169void UmaAsyncDnsResolveStatus(DnsResolveStatus result) {
170 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ResolveStatus",
171 result,
172 RESOLVE_STATUS_MAX);
173}
174
[email protected]1d932852012-06-19 19:40:33175bool ResemblesNetBIOSName(const std::string& hostname) {
176 return (hostname.size() < 16) && (hostname.find('.') == std::string::npos);
177}
178
179// True if |hostname| ends with either ".local" or ".local.".
180bool ResemblesMulticastDNSName(const std::string& hostname) {
181 DCHECK(!hostname.empty());
182 const char kSuffix[] = ".local.";
183 const size_t kSuffixLen = sizeof(kSuffix) - 1;
184 const size_t kSuffixLenTrimmed = kSuffixLen - 1;
185 if (hostname[hostname.size() - 1] == '.') {
186 return hostname.size() > kSuffixLen &&
187 !hostname.compare(hostname.size() - kSuffixLen, kSuffixLen, kSuffix);
188 }
189 return hostname.size() > kSuffixLenTrimmed &&
190 !hostname.compare(hostname.size() - kSuffixLenTrimmed, kSuffixLenTrimmed,
191 kSuffix, kSuffixLenTrimmed);
192}
193
[email protected]34e61362013-07-24 20:41:56194// Attempts to connect a UDP socket to |dest|:53.
[email protected]2b74a2f2013-07-23 19:37:38195bool IsGloballyReachable(const IPAddressNumber& dest,
196 const BoundNetLog& net_log) {
eroman0eb394e2015-04-30 23:25:46197 // TODO(eroman): Remove ScopedTracker below once crbug.com/455942 is fixed.
198 tracked_objects::ScopedTracker tracking_profile_1(
eroman2734a9d2015-05-05 19:24:38199 FROM_HERE_WITH_EXPLICIT_FUNCTION("455942 IsGloballyReachable"));
eroman0eb394e2015-04-30 23:25:46200
[email protected]9db6f702013-04-10 18:10:51201 scoped_ptr<DatagramClientSocket> socket(
202 ClientSocketFactory::GetDefaultFactory()->CreateDatagramClientSocket(
203 DatagramSocket::DEFAULT_BIND,
204 RandIntCallback(),
[email protected]2b74a2f2013-07-23 19:37:38205 net_log.net_log(),
206 net_log.source()));
[email protected]34e61362013-07-24 20:41:56207 int rv = socket->Connect(IPEndPoint(dest, 53));
[email protected]e9051722013-04-12 21:58:18208 if (rv != OK)
209 return false;
210 IPEndPoint endpoint;
211 rv = socket->GetLocalAddress(&endpoint);
212 if (rv != OK)
213 return false;
[email protected]1c7cf3f82014-08-07 21:33:48214 DCHECK_EQ(ADDRESS_FAMILY_IPV6, endpoint.GetFamily());
[email protected]e9051722013-04-12 21:58:18215 const IPAddressNumber& address = endpoint.address();
216 bool is_link_local = (address[0] == 0xFE) && ((address[1] & 0xC0) == 0x80);
217 if (is_link_local)
218 return false;
219 const uint8 kTeredoPrefix[] = { 0x20, 0x01, 0, 0 };
220 bool is_teredo = std::equal(kTeredoPrefix,
221 kTeredoPrefix + arraysize(kTeredoPrefix),
222 address.begin());
223 if (is_teredo)
224 return false;
225 return true;
[email protected]9db6f702013-04-10 18:10:51226}
227
[email protected]51b9a6b2012-06-25 21:50:29228// Provide a common macro to simplify code and readability. We must use a
229// macro as the underlying HISTOGRAM macro creates static variables.
230#define DNS_HISTOGRAM(name, time) UMA_HISTOGRAM_CUSTOM_TIMES(name, time, \
231 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromHours(1), 100)
232
233// A macro to simplify code and readability.
234#define DNS_HISTOGRAM_BY_PRIORITY(basename, priority, time) \
235 do { \
236 switch (priority) { \
237 case HIGHEST: DNS_HISTOGRAM(basename "_HIGHEST", time); break; \
238 case MEDIUM: DNS_HISTOGRAM(basename "_MEDIUM", time); break; \
239 case LOW: DNS_HISTOGRAM(basename "_LOW", time); break; \
240 case LOWEST: DNS_HISTOGRAM(basename "_LOWEST", time); break; \
241 case IDLE: DNS_HISTOGRAM(basename "_IDLE", time); break; \
242 default: NOTREACHED(); break; \
243 } \
244 DNS_HISTOGRAM(basename, time); \
245 } while (0)
246
247// Record time from Request creation until a valid DNS response.
248void RecordTotalTime(bool had_dns_config,
249 bool speculative,
250 base::TimeDelta duration) {
251 if (had_dns_config) {
252 if (speculative) {
253 DNS_HISTOGRAM("AsyncDNS.TotalTime_speculative", duration);
254 } else {
255 DNS_HISTOGRAM("AsyncDNS.TotalTime", duration);
256 }
257 } else {
258 if (speculative) {
259 DNS_HISTOGRAM("DNS.TotalTime_speculative", duration);
260 } else {
261 DNS_HISTOGRAM("DNS.TotalTime", duration);
262 }
263 }
264}
265
[email protected]1339a2a22012-10-17 08:39:43266void RecordTTL(base::TimeDelta ttl) {
267 UMA_HISTOGRAM_CUSTOM_TIMES("AsyncDNS.TTL", ttl,
268 base::TimeDelta::FromSeconds(1),
269 base::TimeDelta::FromDays(1), 100);
270}
271
[email protected]16c2bd72013-06-28 01:19:22272bool ConfigureAsyncDnsNoFallbackFieldTrial() {
273 const bool kDefault = false;
274
275 // Configure the AsyncDns field trial as follows:
276 // groups AsyncDnsNoFallbackA and AsyncDnsNoFallbackB: return true,
277 // groups AsyncDnsA and AsyncDnsB: return false,
278 // groups SystemDnsA and SystemDnsB: return false,
279 // otherwise (trial absent): return default.
280 std::string group_name = base::FieldTrialList::FindFullName("AsyncDns");
281 if (!group_name.empty())
brettw44ce0ec52015-06-12 01:57:57282 return base::StartsWithASCII(group_name, "AsyncDnsNoFallback", false);
[email protected]16c2bd72013-06-28 01:19:22283 return kDefault;
284}
285
[email protected]d7b9a2b2012-05-31 22:31:19286//-----------------------------------------------------------------------------
287
[email protected]895123222012-10-25 15:21:17288AddressList EnsurePortOnAddressList(const AddressList& list, uint16 port) {
289 if (list.empty() || list.front().port() == port)
290 return list;
291 return AddressList::CopyWithPort(list, port);
[email protected]7054e78f2012-05-07 21:44:56292}
293
[email protected]ec666ab22013-04-17 20:05:59294// Returns true if |addresses| contains only IPv4 loopback addresses.
295bool IsAllIPv4Loopback(const AddressList& addresses) {
296 for (unsigned i = 0; i < addresses.size(); ++i) {
297 const IPAddressNumber& address = addresses[i].address();
298 switch (addresses[i].GetFamily()) {
299 case ADDRESS_FAMILY_IPV4:
300 if (address[0] != 127)
301 return false;
302 break;
303 case ADDRESS_FAMILY_IPV6:
304 return false;
305 default:
306 NOTREACHED();
307 return false;
308 }
309 }
310 return true;
311}
312
[email protected]cd565142012-06-12 16:21:45313// Creates NetLog parameters when the resolve failed.
estade5e5529d2015-05-21 20:59:11314scoped_ptr<base::Value> NetLogProcTaskFailedCallback(
eroman001c3742015-04-23 03:11:17315 uint32 attempt_number,
316 int net_error,
317 int os_error,
318 NetLogCaptureMode /* capture_mode */) {
estade5e5529d2015-05-21 20:59:11319 scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]cd565142012-06-12 16:21:45320 if (attempt_number)
321 dict->SetInteger("attempt_number", attempt_number);
[email protected]21526002010-05-16 19:42:46322
[email protected]cd565142012-06-12 16:21:45323 dict->SetInteger("net_error", net_error);
[email protected]13024882011-05-18 23:19:16324
[email protected]cd565142012-06-12 16:21:45325 if (os_error) {
326 dict->SetInteger("os_error", os_error);
[email protected]21526002010-05-16 19:42:46327#if defined(OS_POSIX)
[email protected]cd565142012-06-12 16:21:45328 dict->SetString("os_error_string", gai_strerror(os_error));
[email protected]21526002010-05-16 19:42:46329#elif defined(OS_WIN)
[email protected]cd565142012-06-12 16:21:45330 // Map the error code to a human-readable string.
331 LPWSTR error_string = NULL;
Peter Kastingbe940e92014-11-20 23:14:08332 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
333 0, // Use the internal message table.
334 os_error,
335 0, // Use default language.
336 (LPWSTR)&error_string,
337 0, // Buffer size.
338 0); // Arguments (unused).
[email protected]ad65a3e2013-12-25 18:18:01339 dict->SetString("os_error_string", base::WideToUTF8(error_string));
[email protected]cd565142012-06-12 16:21:45340 LocalFree(error_string);
[email protected]21526002010-05-16 19:42:46341#endif
[email protected]21526002010-05-16 19:42:46342 }
343
estade5e5529d2015-05-21 20:59:11344 return dict.Pass();
[email protected]cd565142012-06-12 16:21:45345}
[email protected]a9813302012-04-28 09:29:28346
[email protected]cd565142012-06-12 16:21:45347// Creates NetLog parameters when the DnsTask failed.
estade5e5529d2015-05-21 20:59:11348scoped_ptr<base::Value> NetLogDnsTaskFailedCallback(
349 int net_error,
350 int dns_error,
351 NetLogCaptureMode /* capture_mode */) {
352 scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]cd565142012-06-12 16:21:45353 dict->SetInteger("net_error", net_error);
354 if (dns_error)
355 dict->SetInteger("dns_error", dns_error);
estade5e5529d2015-05-21 20:59:11356 return dict.Pass();
[email protected]ee094b82010-08-24 15:55:51357};
358
[email protected]cd565142012-06-12 16:21:45359// Creates NetLog parameters containing the information in a RequestInfo object,
360// along with the associated NetLog::Source.
estade5e5529d2015-05-21 20:59:11361scoped_ptr<base::Value> NetLogRequestInfoCallback(
362 const HostResolver::RequestInfo* info,
363 NetLogCaptureMode /* capture_mode */) {
364 scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]b3601bc22012-02-21 21:23:20365
[email protected]cd565142012-06-12 16:21:45366 dict->SetString("host", info->host_port_pair().ToString());
367 dict->SetInteger("address_family",
368 static_cast<int>(info->address_family()));
369 dict->SetBoolean("allow_cached_response", info->allow_cached_response());
370 dict->SetBoolean("is_speculative", info->is_speculative());
estade5e5529d2015-05-21 20:59:11371 return dict.Pass();
[email protected]cd565142012-06-12 16:21:45372}
[email protected]b3601bc22012-02-21 21:23:20373
[email protected]cd565142012-06-12 16:21:45374// Creates NetLog parameters for the creation of a HostResolverImpl::Job.
estade5e5529d2015-05-21 20:59:11375scoped_ptr<base::Value> NetLogJobCreationCallback(
376 const NetLog::Source& source,
377 const std::string* host,
378 NetLogCaptureMode /* capture_mode */) {
379 scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
380 source.AddToEventParameters(dict.get());
[email protected]cd565142012-06-12 16:21:45381 dict->SetString("host", *host);
estade5e5529d2015-05-21 20:59:11382 return dict.Pass();
[email protected]cd565142012-06-12 16:21:45383}
[email protected]a9813302012-04-28 09:29:28384
[email protected]cd565142012-06-12 16:21:45385// Creates NetLog parameters for HOST_RESOLVER_IMPL_JOB_ATTACH/DETACH events.
estade5e5529d2015-05-21 20:59:11386scoped_ptr<base::Value> NetLogJobAttachCallback(
387 const NetLog::Source& source,
388 RequestPriority priority,
389 NetLogCaptureMode /* capture_mode */) {
390 scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
391 source.AddToEventParameters(dict.get());
[email protected]3b04d1f22013-10-16 00:23:56392 dict->SetString("priority", RequestPriorityToString(priority));
estade5e5529d2015-05-21 20:59:11393 return dict.Pass();
[email protected]cd565142012-06-12 16:21:45394}
[email protected]b3601bc22012-02-21 21:23:20395
[email protected]cd565142012-06-12 16:21:45396// Creates NetLog parameters for the DNS_CONFIG_CHANGED event.
estade5e5529d2015-05-21 20:59:11397scoped_ptr<base::Value> NetLogDnsConfigCallback(
398 const DnsConfig* config,
399 NetLogCaptureMode /* capture_mode */) {
400 return make_scoped_ptr(config->ToValue());
[email protected]cd565142012-06-12 16:21:45401}
[email protected]b4481b222012-03-16 17:13:11402
estade5e5529d2015-05-21 20:59:11403scoped_ptr<base::Value> NetLogIPv6AvailableCallback(
404 bool ipv6_available,
405 bool cached,
406 NetLogCaptureMode /* capture_mode */) {
407 scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
sergeyub8cdc212015-05-14 18:50:37408 dict->SetBoolean("ipv6_available", ipv6_available);
409 dict->SetBoolean("cached", cached);
estade5e5529d2015-05-21 20:59:11410 return dict.Pass();
sergeyub8cdc212015-05-14 18:50:37411}
412
[email protected]0f292de02012-02-01 22:28:20413// The logging routines are defined here because some requests are resolved
414// without a Request object.
415
416// Logs when a request has just been started.
417void LogStartRequest(const BoundNetLog& source_net_log,
[email protected]0f292de02012-02-01 22:28:20418 const HostResolver::RequestInfo& info) {
419 source_net_log.BeginEvent(
[email protected]0f292de02012-02-01 22:28:20420 NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST,
xunjieli26f90452014-11-10 16:23:02421 base::Bind(&NetLogRequestInfoCallback, &info));
[email protected]0f292de02012-02-01 22:28:20422}
423
424// Logs when a request has just completed (before its callback is run).
425void LogFinishRequest(const BoundNetLog& source_net_log,
[email protected]0f292de02012-02-01 22:28:20426 const HostResolver::RequestInfo& info,
[email protected]b3601bc22012-02-21 21:23:20427 int net_error) {
xunjieli26f90452014-11-10 16:23:02428 source_net_log.EndEventWithNetErrorCode(
[email protected]b3601bc22012-02-21 21:23:20429 NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST, net_error);
[email protected]0f292de02012-02-01 22:28:20430}
431
432// Logs when a request has been cancelled.
433void LogCancelRequest(const BoundNetLog& source_net_log,
[email protected]0f292de02012-02-01 22:28:20434 const HostResolverImpl::RequestInfo& info) {
xunjieli26f90452014-11-10 16:23:02435 source_net_log.AddEvent(NetLog::TYPE_CANCELLED);
436 source_net_log.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST);
[email protected]0f292de02012-02-01 22:28:20437}
438
[email protected]b59ff372009-07-15 22:04:32439//-----------------------------------------------------------------------------
440
[email protected]0f292de02012-02-01 22:28:20441// Keeps track of the highest priority.
442class PriorityTracker {
443 public:
[email protected]8c98d002012-07-18 19:02:27444 explicit PriorityTracker(RequestPriority initial_priority)
445 : highest_priority_(initial_priority), total_count_(0) {
[email protected]0f292de02012-02-01 22:28:20446 memset(counts_, 0, sizeof(counts_));
447 }
448
449 RequestPriority highest_priority() const {
450 return highest_priority_;
451 }
452
453 size_t total_count() const {
454 return total_count_;
455 }
456
457 void Add(RequestPriority req_priority) {
458 ++total_count_;
459 ++counts_[req_priority];
[email protected]31ae7ab2012-04-24 21:09:05460 if (highest_priority_ < req_priority)
[email protected]0f292de02012-02-01 22:28:20461 highest_priority_ = req_priority;
462 }
463
464 void Remove(RequestPriority req_priority) {
465 DCHECK_GT(total_count_, 0u);
466 DCHECK_GT(counts_[req_priority], 0u);
467 --total_count_;
468 --counts_[req_priority];
469 size_t i;
[email protected]31ae7ab2012-04-24 21:09:05470 for (i = highest_priority_; i > MINIMUM_PRIORITY && !counts_[i]; --i);
[email protected]0f292de02012-02-01 22:28:20471 highest_priority_ = static_cast<RequestPriority>(i);
472
[email protected]31ae7ab2012-04-24 21:09:05473 // In absence of requests, default to MINIMUM_PRIORITY.
474 if (total_count_ == 0)
475 DCHECK_EQ(MINIMUM_PRIORITY, highest_priority_);
[email protected]0f292de02012-02-01 22:28:20476 }
477
478 private:
479 RequestPriority highest_priority_;
480 size_t total_count_;
481 size_t counts_[NUM_PRIORITIES];
482};
483
[email protected]c54a8912012-10-22 22:09:43484} // namespace
[email protected]0f292de02012-02-01 22:28:20485
486//-----------------------------------------------------------------------------
487
[email protected]daae1322013-09-05 18:26:50488const unsigned HostResolverImpl::kMaximumDnsFailures = 16;
489
[email protected]0f292de02012-02-01 22:28:20490// Holds the data for a request that could not be completed synchronously.
491// It is owned by a Job. Canceled Requests are only marked as canceled rather
492// than removed from the Job's |requests_| list.
[email protected]b59ff372009-07-15 22:04:32493class HostResolverImpl::Request {
494 public:
[email protected]ee094b82010-08-24 15:55:51495 Request(const BoundNetLog& source_net_log,
[email protected]54e13772009-08-14 03:01:09496 const RequestInfo& info,
[email protected]5109c1952013-08-20 18:44:10497 RequestPriority priority,
[email protected]aa22b242011-11-16 18:58:29498 const CompletionCallback& callback,
[email protected]b59ff372009-07-15 22:04:32499 AddressList* addresses)
[email protected]ee094b82010-08-24 15:55:51500 : source_net_log_(source_net_log),
[email protected]54e13772009-08-14 03:01:09501 info_(info),
[email protected]5109c1952013-08-20 18:44:10502 priority_(priority),
[email protected]54e13772009-08-14 03:01:09503 job_(NULL),
504 callback_(callback),
[email protected]51b9a6b2012-06-25 21:50:29505 addresses_(addresses),
[email protected]5109c1952013-08-20 18:44:10506 request_time_(base::TimeTicks::Now()) {}
[email protected]b59ff372009-07-15 22:04:32507
[email protected]0f292de02012-02-01 22:28:20508 // Mark the request as canceled.
509 void MarkAsCanceled() {
[email protected]b59ff372009-07-15 22:04:32510 job_ = NULL;
[email protected]b59ff372009-07-15 22:04:32511 addresses_ = NULL;
[email protected]aa22b242011-11-16 18:58:29512 callback_.Reset();
[email protected]b59ff372009-07-15 22:04:32513 }
514
[email protected]0f292de02012-02-01 22:28:20515 bool was_canceled() const {
[email protected]aa22b242011-11-16 18:58:29516 return callback_.is_null();
[email protected]b59ff372009-07-15 22:04:32517 }
518
519 void set_job(Job* job) {
[email protected]0f292de02012-02-01 22:28:20520 DCHECK(job);
[email protected]b59ff372009-07-15 22:04:32521 // Identify which job the request is waiting on.
522 job_ = job;
523 }
524
[email protected]0f292de02012-02-01 22:28:20525 // Prepare final AddressList and call completion callback.
[email protected]b3601bc22012-02-21 21:23:20526 void OnComplete(int error, const AddressList& addr_list) {
[email protected]51b9a6b2012-06-25 21:50:29527 DCHECK(!was_canceled());
[email protected]895123222012-10-25 15:21:17528 if (error == OK)
529 *addresses_ = EnsurePortOnAddressList(addr_list, info_.port());
[email protected]aa22b242011-11-16 18:58:29530 CompletionCallback callback = callback_;
[email protected]0f292de02012-02-01 22:28:20531 MarkAsCanceled();
[email protected]aa22b242011-11-16 18:58:29532 callback.Run(error);
[email protected]b59ff372009-07-15 22:04:32533 }
534
[email protected]b59ff372009-07-15 22:04:32535 Job* job() const {
536 return job_;
537 }
538
[email protected]0f292de02012-02-01 22:28:20539 // NetLog for the source, passed in HostResolver::Resolve.
[email protected]ee094b82010-08-24 15:55:51540 const BoundNetLog& source_net_log() {
541 return source_net_log_;
542 }
543
[email protected]b59ff372009-07-15 22:04:32544 const RequestInfo& info() const {
545 return info_;
546 }
547
[email protected]5109c1952013-08-20 18:44:10548 RequestPriority priority() const { return priority_; }
549
550 base::TimeTicks request_time() const { return request_time_; }
[email protected]51b9a6b2012-06-25 21:50:29551
[email protected]b59ff372009-07-15 22:04:32552 private:
xunjieli26f90452014-11-10 16:23:02553 const BoundNetLog source_net_log_;
[email protected]54e13772009-08-14 03:01:09554
[email protected]b59ff372009-07-15 22:04:32555 // The request info that started the request.
[email protected]5109c1952013-08-20 18:44:10556 const RequestInfo info_;
557
558 // TODO(akalin): Support reprioritization.
559 const RequestPriority priority_;
[email protected]b59ff372009-07-15 22:04:32560
[email protected]0f292de02012-02-01 22:28:20561 // The resolve job that this request is dependent on.
[email protected]b59ff372009-07-15 22:04:32562 Job* job_;
563
564 // The user's callback to invoke when the request completes.
[email protected]aa22b242011-11-16 18:58:29565 CompletionCallback callback_;
[email protected]b59ff372009-07-15 22:04:32566
567 // The address list to save result into.
568 AddressList* addresses_;
569
[email protected]51b9a6b2012-06-25 21:50:29570 const base::TimeTicks request_time_;
571
[email protected]b59ff372009-07-15 22:04:32572 DISALLOW_COPY_AND_ASSIGN(Request);
573};
574
[email protected]1e9bbd22010-10-15 16:42:45575//------------------------------------------------------------------------------
576
[email protected]0f292de02012-02-01 22:28:20577// Calls HostResolverProc on the WorkerPool. Performs retries if necessary.
578//
579// Whenever we try to resolve the host, we post a delayed task to check if host
580// resolution (OnLookupComplete) is completed or not. If the original attempt
581// hasn't completed, then we start another attempt for host resolution. We take
582// the results from the first attempt that finishes and ignore the results from
583// all other attempts.
584//
585// TODO(szym): Move to separate source file for testing and mocking.
586//
587class HostResolverImpl::ProcTask
588 : public base::RefCountedThreadSafe<HostResolverImpl::ProcTask> {
[email protected]b59ff372009-07-15 22:04:32589 public:
[email protected]b3601bc22012-02-21 21:23:20590 typedef base::Callback<void(int net_error,
591 const AddressList& addr_list)> Callback;
[email protected]b59ff372009-07-15 22:04:32592
[email protected]0f292de02012-02-01 22:28:20593 ProcTask(const Key& key,
594 const ProcTaskParams& params,
595 const Callback& callback,
596 const BoundNetLog& job_net_log)
597 : key_(key),
598 params_(params),
599 callback_(callback),
anujk.sharma7c907f02015-05-29 02:55:44600 task_runner_(base::ThreadTaskRunnerHandle::Get()),
[email protected]0f292de02012-02-01 22:28:20601 attempt_number_(0),
602 completed_attempt_number_(0),
603 completed_attempt_error_(ERR_UNEXPECTED),
604 had_non_speculative_request_(false),
[email protected]b3601bc22012-02-21 21:23:20605 net_log_(job_net_log) {
[email protected]90499482013-06-01 00:39:50606 if (!params_.resolver_proc.get())
[email protected]0f292de02012-02-01 22:28:20607 params_.resolver_proc = HostResolverProc::GetDefault();
608 // If default is unset, use the system proc.
[email protected]90499482013-06-01 00:39:50609 if (!params_.resolver_proc.get())
[email protected]1ee9afa12013-04-16 14:18:06610 params_.resolver_proc = new SystemHostResolverProc();
[email protected]b59ff372009-07-15 22:04:32611 }
612
[email protected]b59ff372009-07-15 22:04:32613 void Start() {
anujk.sharma7c907f02015-05-29 02:55:44614 DCHECK(task_runner_->BelongsToCurrentThread());
[email protected]4da911f2012-06-14 19:45:20615 net_log_.BeginEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK);
[email protected]189163e2011-05-11 01:48:54616 StartLookupAttempt();
617 }
[email protected]252b699b2010-02-05 21:38:06618
[email protected]0f292de02012-02-01 22:28:20619 // Cancels this ProcTask. It will be orphaned. Any outstanding resolve
620 // attempts running on worker threads will continue running. Only once all the
621 // attempts complete will the final reference to this ProcTask be released.
622 void Cancel() {
anujk.sharma7c907f02015-05-29 02:55:44623 DCHECK(task_runner_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20624
[email protected]0adcb2b2012-08-15 21:30:46625 if (was_canceled() || was_completed())
[email protected]0f292de02012-02-01 22:28:20626 return;
627
[email protected]0f292de02012-02-01 22:28:20628 callback_.Reset();
[email protected]4da911f2012-06-14 19:45:20629 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK);
[email protected]0f292de02012-02-01 22:28:20630 }
631
632 void set_had_non_speculative_request() {
anujk.sharma7c907f02015-05-29 02:55:44633 DCHECK(task_runner_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20634 had_non_speculative_request_ = true;
635 }
636
637 bool was_canceled() const {
anujk.sharma7c907f02015-05-29 02:55:44638 DCHECK(task_runner_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20639 return callback_.is_null();
640 }
641
642 bool was_completed() const {
anujk.sharma7c907f02015-05-29 02:55:44643 DCHECK(task_runner_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20644 return completed_attempt_number_ > 0;
645 }
646
647 private:
[email protected]a9813302012-04-28 09:29:28648 friend class base::RefCountedThreadSafe<ProcTask>;
649 ~ProcTask() {}
650
[email protected]189163e2011-05-11 01:48:54651 void StartLookupAttempt() {
anujk.sharma7c907f02015-05-29 02:55:44652 DCHECK(task_runner_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54653 base::TimeTicks start_time = base::TimeTicks::Now();
654 ++attempt_number_;
655 // Dispatch the lookup attempt to a worker thread.
656 if (!base::WorkerPool::PostTask(
657 FROM_HERE,
[email protected]0f292de02012-02-01 22:28:20658 base::Bind(&ProcTask::DoLookup, this, start_time, attempt_number_),
[email protected]189163e2011-05-11 01:48:54659 true)) {
[email protected]b59ff372009-07-15 22:04:32660 NOTREACHED();
661
662 // Since we could be running within Resolve() right now, we can't just
663 // call OnLookupComplete(). Instead we must wait until Resolve() has
664 // returned (IO_PENDING).
anujk.sharma7c907f02015-05-29 02:55:44665 task_runner_->PostTask(FROM_HERE,
666 base::Bind(&ProcTask::OnLookupComplete,
667 this,
668 AddressList(),
669 start_time,
670 attempt_number_,
671 ERR_UNEXPECTED,
672 0));
[email protected]189163e2011-05-11 01:48:54673 return;
[email protected]b59ff372009-07-15 22:04:32674 }
[email protected]13024882011-05-18 23:19:16675
676 net_log_.AddEvent(
677 NetLog::TYPE_HOST_RESOLVER_IMPL_ATTEMPT_STARTED,
[email protected]cd565142012-06-12 16:21:45678 NetLog::IntegerCallback("attempt_number", attempt_number_));
[email protected]13024882011-05-18 23:19:16679
[email protected]0f292de02012-02-01 22:28:20680 // If we don't get the results within a given time, RetryIfNotComplete
681 // will start a new attempt on a different worker thread if none of our
682 // outstanding attempts have completed yet.
683 if (attempt_number_ <= params_.max_retry_attempts) {
anujk.sharma7c907f02015-05-29 02:55:44684 task_runner_->PostDelayedTask(
[email protected]06ef6d92011-05-19 04:24:58685 FROM_HERE,
[email protected]0f292de02012-02-01 22:28:20686 base::Bind(&ProcTask::RetryIfNotComplete, this),
[email protected]7e560102012-03-08 20:58:42687 params_.unresponsive_delay);
[email protected]06ef6d92011-05-19 04:24:58688 }
[email protected]b59ff372009-07-15 22:04:32689 }
690
[email protected]6c710ee2010-05-07 07:51:16691 // WARNING: This code runs inside a worker pool. The shutdown code cannot
692 // wait for it to finish, so we must be very careful here about using other
693 // objects (like MessageLoops, Singletons, etc). During shutdown these objects
[email protected]189163e2011-05-11 01:48:54694 // may no longer exist. Multiple DoLookups() could be running in parallel, so
695 // any state inside of |this| must not mutate .
696 void DoLookup(const base::TimeTicks& start_time,
697 const uint32 attempt_number) {
698 AddressList results;
699 int os_error = 0;
[email protected]b59ff372009-07-15 22:04:32700 // Running on the worker thread
[email protected]0f292de02012-02-01 22:28:20701 int error = params_.resolver_proc->Resolve(key_.hostname,
702 key_.address_family,
703 key_.host_resolver_flags,
704 &results,
705 &os_error);
[email protected]b59ff372009-07-15 22:04:32706
eroman91dd3602015-03-26 03:46:33707 // Fail the resolution if the result contains 127.0.53.53. See the comment
708 // block of kIcanNameCollisionIp for details on why.
709 for (const auto& it : results) {
710 const IPAddressNumber& cur = it.address();
711 if (cur.size() == arraysize(kIcanNameCollisionIp) &&
712 0 == memcmp(&cur.front(), kIcanNameCollisionIp, cur.size())) {
713 error = ERR_ICANN_NAME_COLLISION;
714 break;
715 }
716 }
717
anujk.sharma7c907f02015-05-29 02:55:44718 task_runner_->PostTask(FROM_HERE,
719 base::Bind(&ProcTask::OnLookupComplete,
720 this,
721 results,
722 start_time,
723 attempt_number,
724 error,
725 os_error));
[email protected]189163e2011-05-11 01:48:54726 }
727
anujk.sharma7c907f02015-05-29 02:55:44728 // Makes next attempt if DoLookup() has not finished (runs on task runner
729 // thread).
[email protected]0f292de02012-02-01 22:28:20730 void RetryIfNotComplete() {
anujk.sharma7c907f02015-05-29 02:55:44731 DCHECK(task_runner_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54732
[email protected]0f292de02012-02-01 22:28:20733 if (was_completed() || was_canceled())
[email protected]189163e2011-05-11 01:48:54734 return;
735
[email protected]0f292de02012-02-01 22:28:20736 params_.unresponsive_delay *= params_.retry_factor;
[email protected]189163e2011-05-11 01:48:54737 StartLookupAttempt();
[email protected]b59ff372009-07-15 22:04:32738 }
739
anujk.sharma7c907f02015-05-29 02:55:44740 // Callback for when DoLookup() completes (runs on task runner thread).
[email protected]189163e2011-05-11 01:48:54741 void OnLookupComplete(const AddressList& results,
742 const base::TimeTicks& start_time,
743 const uint32 attempt_number,
744 int error,
745 const int os_error) {
anujk.sharma7c907f02015-05-29 02:55:44746 DCHECK(task_runner_->BelongsToCurrentThread());
[email protected]49b70b222013-05-07 21:24:23747 // If results are empty, we should return an error.
748 bool empty_list_on_ok = (error == OK && results.empty());
749 UMA_HISTOGRAM_BOOLEAN("DNS.EmptyAddressListAndNoError", empty_list_on_ok);
750 if (empty_list_on_ok)
751 error = ERR_NAME_NOT_RESOLVED;
[email protected]189163e2011-05-11 01:48:54752
753 bool was_retry_attempt = attempt_number > 1;
754
[email protected]2d3b7762010-10-09 00:35:47755 // Ideally the following code would be part of host_resolver_proc.cc,
[email protected]b3601bc22012-02-21 21:23:20756 // however it isn't safe to call NetworkChangeNotifier from worker threads.
757 // So we do it here on the IO thread instead.
[email protected]189163e2011-05-11 01:48:54758 if (error != OK && NetworkChangeNotifier::IsOffline())
759 error = ERR_INTERNET_DISCONNECTED;
[email protected]2d3b7762010-10-09 00:35:47760
[email protected]b3601bc22012-02-21 21:23:20761 // If this is the first attempt that is finishing later, then record data
762 // for the first attempt. Won't contaminate with retry attempt's data.
[email protected]189163e2011-05-11 01:48:54763 if (!was_retry_attempt)
764 RecordPerformanceHistograms(start_time, error, os_error);
765
766 RecordAttemptHistograms(start_time, attempt_number, error, os_error);
[email protected]f2d8c4212010-02-02 00:56:35767
[email protected]0f292de02012-02-01 22:28:20768 if (was_canceled())
[email protected]b59ff372009-07-15 22:04:32769 return;
770
[email protected]cd565142012-06-12 16:21:45771 NetLog::ParametersCallback net_log_callback;
[email protected]0f292de02012-02-01 22:28:20772 if (error != OK) {
[email protected]cd565142012-06-12 16:21:45773 net_log_callback = base::Bind(&NetLogProcTaskFailedCallback,
774 attempt_number,
775 error,
776 os_error);
[email protected]0f292de02012-02-01 22:28:20777 } else {
[email protected]cd565142012-06-12 16:21:45778 net_log_callback = NetLog::IntegerCallback("attempt_number",
779 attempt_number);
[email protected]0f292de02012-02-01 22:28:20780 }
[email protected]cd565142012-06-12 16:21:45781 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_ATTEMPT_FINISHED,
782 net_log_callback);
[email protected]0f292de02012-02-01 22:28:20783
784 if (was_completed())
785 return;
786
787 // Copy the results from the first worker thread that resolves the host.
788 results_ = results;
789 completed_attempt_number_ = attempt_number;
790 completed_attempt_error_ = error;
791
[email protected]e87b8b512011-06-14 22:12:52792 if (was_retry_attempt) {
793 // If retry attempt finishes before 1st attempt, then get stats on how
794 // much time is saved by having spawned an extra attempt.
795 retry_attempt_finished_time_ = base::TimeTicks::Now();
796 }
797
[email protected]189163e2011-05-11 01:48:54798 if (error != OK) {
[email protected]cd565142012-06-12 16:21:45799 net_log_callback = base::Bind(&NetLogProcTaskFailedCallback,
800 0, error, os_error);
[email protected]ee094b82010-08-24 15:55:51801 } else {
[email protected]cd565142012-06-12 16:21:45802 net_log_callback = results_.CreateNetLogCallback();
[email protected]ee094b82010-08-24 15:55:51803 }
[email protected]cd565142012-06-12 16:21:45804 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK,
805 net_log_callback);
[email protected]ee094b82010-08-24 15:55:51806
[email protected]b3601bc22012-02-21 21:23:20807 callback_.Run(error, results_);
[email protected]b59ff372009-07-15 22:04:32808 }
809
[email protected]189163e2011-05-11 01:48:54810 void RecordPerformanceHistograms(const base::TimeTicks& start_time,
811 const int error,
812 const int os_error) const {
anujk.sharma7c907f02015-05-29 02:55:44813 DCHECK(task_runner_->BelongsToCurrentThread());
asvitkinec0fb8022014-08-26 04:39:35814 enum Category { // Used in UMA_HISTOGRAM_ENUMERATION.
[email protected]1e9bbd22010-10-15 16:42:45815 RESOLVE_SUCCESS,
816 RESOLVE_FAIL,
817 RESOLVE_SPECULATIVE_SUCCESS,
818 RESOLVE_SPECULATIVE_FAIL,
819 RESOLVE_MAX, // Bounding value.
820 };
821 int category = RESOLVE_MAX; // Illegal value for later DCHECK only.
822
[email protected]189163e2011-05-11 01:48:54823 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
824 if (error == OK) {
[email protected]1e9bbd22010-10-15 16:42:45825 if (had_non_speculative_request_) {
826 category = RESOLVE_SUCCESS;
827 DNS_HISTOGRAM("DNS.ResolveSuccess", duration);
828 } else {
829 category = RESOLVE_SPECULATIVE_SUCCESS;
830 DNS_HISTOGRAM("DNS.ResolveSpeculativeSuccess", duration);
831 }
[email protected]7e96d792011-06-10 17:08:23832
[email protected]78eac2a2012-03-14 19:09:27833 // Log DNS lookups based on |address_family|. This will help us determine
[email protected]7e96d792011-06-10 17:08:23834 // if IPv4 or IPv4/6 lookups are faster or slower.
835 switch(key_.address_family) {
836 case ADDRESS_FAMILY_IPV4:
837 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_IPV4", duration);
838 break;
839 case ADDRESS_FAMILY_IPV6:
840 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_IPV6", duration);
841 break;
842 case ADDRESS_FAMILY_UNSPECIFIED:
843 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_UNSPEC", duration);
844 break;
845 }
[email protected]1e9bbd22010-10-15 16:42:45846 } else {
847 if (had_non_speculative_request_) {
848 category = RESOLVE_FAIL;
849 DNS_HISTOGRAM("DNS.ResolveFail", duration);
850 } else {
851 category = RESOLVE_SPECULATIVE_FAIL;
852 DNS_HISTOGRAM("DNS.ResolveSpeculativeFail", duration);
853 }
[email protected]78eac2a2012-03-14 19:09:27854 // Log DNS lookups based on |address_family|. This will help us determine
[email protected]7e96d792011-06-10 17:08:23855 // if IPv4 or IPv4/6 lookups are faster or slower.
856 switch(key_.address_family) {
857 case ADDRESS_FAMILY_IPV4:
858 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_IPV4", duration);
859 break;
860 case ADDRESS_FAMILY_IPV6:
861 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_IPV6", duration);
862 break;
863 case ADDRESS_FAMILY_UNSPECIFIED:
864 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_UNSPEC", duration);
865 break;
866 }
[email protected]c833e322010-10-16 23:51:36867 UMA_HISTOGRAM_CUSTOM_ENUMERATION(kOSErrorsForGetAddrinfoHistogramName,
[email protected]189163e2011-05-11 01:48:54868 std::abs(os_error),
[email protected]1e9bbd22010-10-15 16:42:45869 GetAllGetAddrinfoOSErrors());
870 }
[email protected]051b6ab2010-10-18 16:50:46871 DCHECK_LT(category, static_cast<int>(RESOLVE_MAX)); // Be sure it was set.
[email protected]1e9bbd22010-10-15 16:42:45872
873 UMA_HISTOGRAM_ENUMERATION("DNS.ResolveCategory", category, RESOLVE_MAX);
[email protected]1e9bbd22010-10-15 16:42:45874 }
875
[email protected]189163e2011-05-11 01:48:54876 void RecordAttemptHistograms(const base::TimeTicks& start_time,
877 const uint32 attempt_number,
878 const int error,
879 const int os_error) const {
anujk.sharma7c907f02015-05-29 02:55:44880 DCHECK(task_runner_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54881 bool first_attempt_to_complete =
882 completed_attempt_number_ == attempt_number;
[email protected]e87b8b512011-06-14 22:12:52883 bool is_first_attempt = (attempt_number == 1);
[email protected]1e9bbd22010-10-15 16:42:45884
[email protected]189163e2011-05-11 01:48:54885 if (first_attempt_to_complete) {
886 // If this was first attempt to complete, then record the resolution
887 // status of the attempt.
888 if (completed_attempt_error_ == OK) {
889 UMA_HISTOGRAM_ENUMERATION(
890 "DNS.AttemptFirstSuccess", attempt_number, 100);
891 } else {
892 UMA_HISTOGRAM_ENUMERATION(
893 "DNS.AttemptFirstFailure", attempt_number, 100);
894 }
895 }
896
897 if (error == OK)
898 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptSuccess", attempt_number, 100);
899 else
900 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptFailure", attempt_number, 100);
901
[email protected]e87b8b512011-06-14 22:12:52902 // If first attempt didn't finish before retry attempt, then calculate stats
903 // on how much time is saved by having spawned an extra attempt.
[email protected]0f292de02012-02-01 22:28:20904 if (!first_attempt_to_complete && is_first_attempt && !was_canceled()) {
[email protected]e87b8b512011-06-14 22:12:52905 DNS_HISTOGRAM("DNS.AttemptTimeSavedByRetry",
906 base::TimeTicks::Now() - retry_attempt_finished_time_);
907 }
908
[email protected]0f292de02012-02-01 22:28:20909 if (was_canceled() || !first_attempt_to_complete) {
[email protected]189163e2011-05-11 01:48:54910 // Count those attempts which completed after the job was already canceled
911 // OR after the job was already completed by an earlier attempt (so in
912 // effect).
913 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptDiscarded", attempt_number, 100);
914
[email protected]0f292de02012-02-01 22:28:20915 // Record if job is canceled.
916 if (was_canceled())
[email protected]189163e2011-05-11 01:48:54917 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptCancelled", attempt_number, 100);
918 }
919
920 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
921 if (error == OK)
922 DNS_HISTOGRAM("DNS.AttemptSuccessDuration", duration);
923 else
924 DNS_HISTOGRAM("DNS.AttemptFailDuration", duration);
925 }
[email protected]1e9bbd22010-10-15 16:42:45926
anujk.sharma7c907f02015-05-29 02:55:44927 // Set on the task runner thread, read on the worker thread.
[email protected]123ab1e32009-10-21 19:12:57928 Key key_;
[email protected]b59ff372009-07-15 22:04:32929
[email protected]0f292de02012-02-01 22:28:20930 // Holds an owning reference to the HostResolverProc that we are going to use.
[email protected]b59ff372009-07-15 22:04:32931 // This may not be the current resolver procedure by the time we call
932 // ResolveAddrInfo, but that's OK... we'll use it anyways, and the owning
933 // reference ensures that it remains valid until we are done.
[email protected]0f292de02012-02-01 22:28:20934 ProcTaskParams params_;
[email protected]b59ff372009-07-15 22:04:32935
[email protected]0f292de02012-02-01 22:28:20936 // The listener to the results of this ProcTask.
937 Callback callback_;
938
anujk.sharma7c907f02015-05-29 02:55:44939 // Used to post ourselves onto the task runner thread.
940 scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
[email protected]189163e2011-05-11 01:48:54941
942 // Keeps track of the number of attempts we have made so far to resolve the
943 // host. Whenever we start an attempt to resolve the host, we increase this
944 // number.
945 uint32 attempt_number_;
946
947 // The index of the attempt which finished first (or 0 if the job is still in
948 // progress).
949 uint32 completed_attempt_number_;
950
951 // The result (a net error code) from the first attempt to complete.
952 int completed_attempt_error_;
[email protected]252b699b2010-02-05 21:38:06953
[email protected]e87b8b512011-06-14 22:12:52954 // The time when retry attempt was finished.
955 base::TimeTicks retry_attempt_finished_time_;
956
[email protected]252b699b2010-02-05 21:38:06957 // True if a non-speculative request was ever attached to this job
[email protected]0f292de02012-02-01 22:28:20958 // (regardless of whether or not it was later canceled.
[email protected]252b699b2010-02-05 21:38:06959 // This boolean is used for histogramming the duration of jobs used to
960 // service non-speculative requests.
961 bool had_non_speculative_request_;
962
[email protected]b59ff372009-07-15 22:04:32963 AddressList results_;
964
[email protected]ee094b82010-08-24 15:55:51965 BoundNetLog net_log_;
966
[email protected]0f292de02012-02-01 22:28:20967 DISALLOW_COPY_AND_ASSIGN(ProcTask);
[email protected]b59ff372009-07-15 22:04:32968};
969
970//-----------------------------------------------------------------------------
971
[email protected]12faa4c2012-11-06 04:44:18972// Wraps a call to HaveOnlyLoopbackAddresses to be executed on the WorkerPool as
973// it takes 40-100ms and should not block initialization.
974class HostResolverImpl::LoopbackProbeJob {
975 public:
976 explicit LoopbackProbeJob(const base::WeakPtr<HostResolverImpl>& resolver)
977 : resolver_(resolver),
978 result_(false) {
[email protected]11fbca0b2013-06-02 23:37:21979 DCHECK(resolver.get());
[email protected]12faa4c2012-11-06 04:44:18980 const bool kIsSlow = true;
981 base::WorkerPool::PostTaskAndReply(
982 FROM_HERE,
983 base::Bind(&LoopbackProbeJob::DoProbe, base::Unretained(this)),
984 base::Bind(&LoopbackProbeJob::OnProbeComplete, base::Owned(this)),
985 kIsSlow);
986 }
987
988 virtual ~LoopbackProbeJob() {}
989
990 private:
991 // Runs on worker thread.
992 void DoProbe() {
993 result_ = HaveOnlyLoopbackAddresses();
994 }
995
996 void OnProbeComplete() {
[email protected]11fbca0b2013-06-02 23:37:21997 if (!resolver_.get())
[email protected]12faa4c2012-11-06 04:44:18998 return;
999 resolver_->SetHaveOnlyLoopbackAddresses(result_);
1000 }
1001
anujk.sharma7c907f02015-05-29 02:55:441002 // Used/set only on task runner thread.
[email protected]12faa4c2012-11-06 04:44:181003 base::WeakPtr<HostResolverImpl> resolver_;
1004
1005 bool result_;
1006
1007 DISALLOW_COPY_AND_ASSIGN(LoopbackProbeJob);
1008};
1009
[email protected]0f8f1b432010-03-16 19:06:031010//-----------------------------------------------------------------------------
1011
[email protected]b3601bc22012-02-21 21:23:201012// Resolves the hostname using DnsTransaction.
1013// TODO(szym): This could be moved to separate source file as well.
[email protected]0adcb2b2012-08-15 21:30:461014class HostResolverImpl::DnsTask : public base::SupportsWeakPtr<DnsTask> {
[email protected]b3601bc22012-02-21 21:23:201015 public:
[email protected]daae1322013-09-05 18:26:501016 class Delegate {
1017 public:
1018 virtual void OnDnsTaskComplete(base::TimeTicks start_time,
1019 int net_error,
1020 const AddressList& addr_list,
1021 base::TimeDelta ttl) = 0;
1022
1023 // Called when the first of two jobs succeeds. If the first completed
1024 // transaction fails, this is not called. Also not called when the DnsTask
1025 // only needs to run one transaction.
1026 virtual void OnFirstDnsTransactionComplete() = 0;
1027
1028 protected:
1029 Delegate() {}
1030 virtual ~Delegate() {}
1031 };
[email protected]b3601bc22012-02-21 21:23:201032
[email protected]0adcb2b2012-08-15 21:30:461033 DnsTask(DnsClient* client,
[email protected]b3601bc22012-02-21 21:23:201034 const Key& key,
[email protected]daae1322013-09-05 18:26:501035 Delegate* delegate,
[email protected]b3601bc22012-02-21 21:23:201036 const BoundNetLog& job_net_log)
[email protected]0adcb2b2012-08-15 21:30:461037 : client_(client),
[email protected]daae1322013-09-05 18:26:501038 key_(key),
1039 delegate_(delegate),
1040 net_log_(job_net_log),
1041 num_completed_transactions_(0),
1042 task_start_time_(base::TimeTicks::Now()) {
[email protected]0adcb2b2012-08-15 21:30:461043 DCHECK(client);
[email protected]daae1322013-09-05 18:26:501044 DCHECK(delegate_);
[email protected]1affed62013-08-21 03:24:501045 }
1046
[email protected]daae1322013-09-05 18:26:501047 bool needs_two_transactions() const {
1048 return key_.address_family == ADDRESS_FAMILY_UNSPECIFIED;
1049 }
1050
1051 bool needs_another_transaction() const {
1052 return needs_two_transactions() && !transaction_aaaa_;
1053 }
1054
1055 void StartFirstTransaction() {
1056 DCHECK_EQ(0u, num_completed_transactions_);
[email protected]70c04ab2013-08-22 16:05:121057 net_log_.BeginEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK);
[email protected]daae1322013-09-05 18:26:501058 if (key_.address_family == ADDRESS_FAMILY_IPV6) {
1059 StartAAAA();
1060 } else {
1061 StartA();
1062 }
1063 }
1064
1065 void StartSecondTransaction() {
1066 DCHECK(needs_two_transactions());
1067 StartAAAA();
[email protected]70c04ab2013-08-22 16:05:121068 }
1069
1070 private:
[email protected]daae1322013-09-05 18:26:501071 void StartA() {
1072 DCHECK(!transaction_a_);
1073 DCHECK_NE(ADDRESS_FAMILY_IPV6, key_.address_family);
1074 transaction_a_ = CreateTransaction(ADDRESS_FAMILY_IPV4);
1075 transaction_a_->Start();
1076 }
1077
1078 void StartAAAA() {
1079 DCHECK(!transaction_aaaa_);
1080 DCHECK_NE(ADDRESS_FAMILY_IPV4, key_.address_family);
1081 transaction_aaaa_ = CreateTransaction(ADDRESS_FAMILY_IPV6);
1082 transaction_aaaa_->Start();
1083 }
1084
1085 scoped_ptr<DnsTransaction> CreateTransaction(AddressFamily family) {
1086 DCHECK_NE(ADDRESS_FAMILY_UNSPECIFIED, family);
1087 return client_->GetTransactionFactory()->CreateTransaction(
1088 key_.hostname,
1089 family == ADDRESS_FAMILY_IPV6 ? dns_protocol::kTypeAAAA :
1090 dns_protocol::kTypeA,
1091 base::Bind(&DnsTask::OnTransactionComplete, base::Unretained(this),
1092 base::TimeTicks::Now()),
1093 net_log_);
1094 }
1095
1096 void OnTransactionComplete(const base::TimeTicks& start_time,
[email protected]1def74c2012-03-22 20:07:001097 DnsTransaction* transaction,
[email protected]b3601bc22012-02-21 21:23:201098 int net_error,
1099 const DnsResponse* response) {
[email protected]add76532012-03-30 14:47:471100 DCHECK(transaction);
[email protected]02cd6982013-01-10 20:12:511101 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]0adcb2b2012-08-15 21:30:461102 if (net_error != OK) {
[email protected]02cd6982013-01-10 20:12:511103 DNS_HISTOGRAM("AsyncDNS.TransactionFailure", duration);
[email protected]0adcb2b2012-08-15 21:30:461104 OnFailure(net_error, DnsResponse::DNS_PARSE_OK);
1105 return;
[email protected]6c411902012-08-14 22:36:361106 }
[email protected]0adcb2b2012-08-15 21:30:461107
[email protected]02cd6982013-01-10 20:12:511108 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess", duration);
1109 switch (transaction->GetType()) {
1110 case dns_protocol::kTypeA:
1111 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess_A", duration);
1112 break;
1113 case dns_protocol::kTypeAAAA:
1114 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess_AAAA", duration);
1115 break;
1116 }
[email protected]daae1322013-09-05 18:26:501117
[email protected]0adcb2b2012-08-15 21:30:461118 AddressList addr_list;
1119 base::TimeDelta ttl;
1120 DnsResponse::Result result = response->ParseToAddressList(&addr_list, &ttl);
1121 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ParseToAddressList",
1122 result,
1123 DnsResponse::DNS_PARSE_RESULT_MAX);
1124 if (result != DnsResponse::DNS_PARSE_OK) {
1125 // Fail even if the other query succeeds.
1126 OnFailure(ERR_DNS_MALFORMED_RESPONSE, result);
1127 return;
1128 }
1129
[email protected]daae1322013-09-05 18:26:501130 ++num_completed_transactions_;
1131 if (num_completed_transactions_ == 1) {
1132 ttl_ = ttl;
[email protected]0adcb2b2012-08-15 21:30:461133 } else {
[email protected]daae1322013-09-05 18:26:501134 ttl_ = std::min(ttl_, ttl);
[email protected]0adcb2b2012-08-15 21:30:461135 }
1136
[email protected]daae1322013-09-05 18:26:501137 if (transaction->GetType() == dns_protocol::kTypeA) {
1138 DCHECK_EQ(transaction_a_.get(), transaction);
1139 // Place IPv4 addresses after IPv6.
1140 addr_list_.insert(addr_list_.end(), addr_list.begin(), addr_list.end());
1141 } else {
1142 DCHECK_EQ(transaction_aaaa_.get(), transaction);
1143 // Place IPv6 addresses before IPv4.
1144 addr_list_.insert(addr_list_.begin(), addr_list.begin(), addr_list.end());
1145 }
1146
1147 if (needs_two_transactions() && num_completed_transactions_ == 1) {
1148 // No need to repeat the suffix search.
1149 key_.hostname = transaction->GetHostname();
1150 delegate_->OnFirstDnsTransactionComplete();
1151 return;
1152 }
1153
1154 if (addr_list_.empty()) {
[email protected]70c04ab2013-08-22 16:05:121155 // TODO(szym): Don't fallback to ProcTask in this case.
1156 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
[email protected]0adcb2b2012-08-15 21:30:461157 return;
1158 }
1159
[email protected]daae1322013-09-05 18:26:501160 // If there are multiple addresses, and at least one is IPv6, need to sort
1161 // them. Note that IPv6 addresses are always put before IPv4 ones, so it's
1162 // sufficient to just check the family of the first address.
1163 if (addr_list_.size() > 1 &&
1164 addr_list_[0].GetFamily() == ADDRESS_FAMILY_IPV6) {
1165 // Sort addresses if needed. Sort could complete synchronously.
[email protected]0adcb2b2012-08-15 21:30:461166 client_->GetAddressSorter()->Sort(
[email protected]daae1322013-09-05 18:26:501167 addr_list_,
[email protected]4589a3a2012-09-20 20:57:071168 base::Bind(&DnsTask::OnSortComplete,
1169 AsWeakPtr(),
[email protected]daae1322013-09-05 18:26:501170 base::TimeTicks::Now()));
[email protected]0adcb2b2012-08-15 21:30:461171 } else {
[email protected]daae1322013-09-05 18:26:501172 OnSuccess(addr_list_);
[email protected]0adcb2b2012-08-15 21:30:461173 }
1174 }
1175
1176 void OnSortComplete(base::TimeTicks start_time,
[email protected]0adcb2b2012-08-15 21:30:461177 bool success,
1178 const AddressList& addr_list) {
1179 if (!success) {
1180 DNS_HISTOGRAM("AsyncDNS.SortFailure",
1181 base::TimeTicks::Now() - start_time);
1182 OnFailure(ERR_DNS_SORT_ERROR, DnsResponse::DNS_PARSE_OK);
1183 return;
1184 }
1185
1186 DNS_HISTOGRAM("AsyncDNS.SortSuccess",
1187 base::TimeTicks::Now() - start_time);
1188
1189 // AddressSorter prunes unusable destinations.
1190 if (addr_list.empty()) {
1191 LOG(WARNING) << "Address list empty after RFC3484 sort";
1192 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
1193 return;
1194 }
1195
[email protected]daae1322013-09-05 18:26:501196 OnSuccess(addr_list);
[email protected]0adcb2b2012-08-15 21:30:461197 }
1198
1199 void OnFailure(int net_error, DnsResponse::Result result) {
1200 DCHECK_NE(OK, net_error);
[email protected]cd565142012-06-12 16:21:451201 net_log_.EndEvent(
1202 NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK,
1203 base::Bind(&NetLogDnsTaskFailedCallback, net_error, result));
[email protected]daae1322013-09-05 18:26:501204 delegate_->OnDnsTaskComplete(task_start_time_, net_error, AddressList(),
1205 base::TimeDelta());
[email protected]b3601bc22012-02-21 21:23:201206 }
1207
[email protected]daae1322013-09-05 18:26:501208 void OnSuccess(const AddressList& addr_list) {
[email protected]0adcb2b2012-08-15 21:30:461209 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK,
1210 addr_list.CreateNetLogCallback());
[email protected]daae1322013-09-05 18:26:501211 delegate_->OnDnsTaskComplete(task_start_time_, OK, addr_list, ttl_);
[email protected]0adcb2b2012-08-15 21:30:461212 }
1213
1214 DnsClient* client_;
[email protected]daae1322013-09-05 18:26:501215 Key key_;
1216
[email protected]b3601bc22012-02-21 21:23:201217 // The listener to the results of this DnsTask.
[email protected]daae1322013-09-05 18:26:501218 Delegate* delegate_;
[email protected]b3601bc22012-02-21 21:23:201219 const BoundNetLog net_log_;
1220
[email protected]daae1322013-09-05 18:26:501221 scoped_ptr<DnsTransaction> transaction_a_;
1222 scoped_ptr<DnsTransaction> transaction_aaaa_;
[email protected]0adcb2b2012-08-15 21:30:461223
[email protected]daae1322013-09-05 18:26:501224 unsigned num_completed_transactions_;
1225
1226 // These are updated as each transaction completes.
1227 base::TimeDelta ttl_;
1228 // IPv6 addresses must appear first in the list.
1229 AddressList addr_list_;
1230
1231 base::TimeTicks task_start_time_;
[email protected]0adcb2b2012-08-15 21:30:461232
1233 DISALLOW_COPY_AND_ASSIGN(DnsTask);
[email protected]b3601bc22012-02-21 21:23:201234};
1235
1236//-----------------------------------------------------------------------------
1237
[email protected]0f292de02012-02-01 22:28:201238// Aggregates all Requests for the same Key. Dispatched via PriorityDispatch.
[email protected]daae1322013-09-05 18:26:501239class HostResolverImpl::Job : public PrioritizedDispatcher::Job,
1240 public HostResolverImpl::DnsTask::Delegate {
[email protected]68ad3ee2010-01-30 03:45:391241 public:
[email protected]0f292de02012-02-01 22:28:201242 // Creates new job for |key| where |request_net_log| is bound to the
[email protected]16ee26d2012-03-08 03:34:351243 // request that spawned it.
[email protected]12faa4c2012-11-06 04:44:181244 Job(const base::WeakPtr<HostResolverImpl>& resolver,
[email protected]0f292de02012-02-01 22:28:201245 const Key& key,
[email protected]8c98d002012-07-18 19:02:271246 RequestPriority priority,
xunjieli26f90452014-11-10 16:23:021247 const BoundNetLog& source_net_log)
[email protected]12faa4c2012-11-06 04:44:181248 : resolver_(resolver),
[email protected]0f292de02012-02-01 22:28:201249 key_(key),
[email protected]8c98d002012-07-18 19:02:271250 priority_tracker_(priority),
[email protected]0f292de02012-02-01 22:28:201251 had_non_speculative_request_(false),
[email protected]51b9a6b2012-06-25 21:50:291252 had_dns_config_(false),
[email protected]daae1322013-09-05 18:26:501253 num_occupied_job_slots_(0),
[email protected]1d932852012-06-19 19:40:331254 dns_task_error_(OK),
[email protected]51b9a6b2012-06-25 21:50:291255 creation_time_(base::TimeTicks::Now()),
1256 priority_change_time_(creation_time_),
xunjieli26f90452014-11-10 16:23:021257 net_log_(BoundNetLog::Make(source_net_log.net_log(),
[email protected]b3601bc22012-02-21 21:23:201258 NetLog::SOURCE_HOST_RESOLVER_IMPL_JOB)) {
xunjieli26f90452014-11-10 16:23:021259 source_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_CREATE_JOB);
[email protected]0f292de02012-02-01 22:28:201260
1261 net_log_.BeginEvent(
1262 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
[email protected]cd565142012-06-12 16:21:451263 base::Bind(&NetLogJobCreationCallback,
xunjieli26f90452014-11-10 16:23:021264 source_net_log.source(),
[email protected]cd565142012-06-12 16:21:451265 &key_.hostname));
[email protected]68ad3ee2010-01-30 03:45:391266 }
1267
dchengb03027d2014-10-21 12:00:201268 ~Job() override {
[email protected]b3601bc22012-02-21 21:23:201269 if (is_running()) {
1270 // |resolver_| was destroyed with this Job still in flight.
1271 // Clean-up, record in the log, but don't run any callbacks.
1272 if (is_proc_running()) {
[email protected]0f292de02012-02-01 22:28:201273 proc_task_->Cancel();
1274 proc_task_ = NULL;
[email protected]0f292de02012-02-01 22:28:201275 }
[email protected]16ee26d2012-03-08 03:34:351276 // Clean up now for nice NetLog.
[email protected]daae1322013-09-05 18:26:501277 KillDnsTask();
[email protected]b3601bc22012-02-21 21:23:201278 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
1279 ERR_ABORTED);
1280 } else if (is_queued()) {
[email protected]57a48d32012-03-03 00:04:551281 // |resolver_| was destroyed without running this Job.
[email protected]16ee26d2012-03-08 03:34:351282 // TODO(szym): is there any benefit in having this distinction?
[email protected]4da911f2012-06-14 19:45:201283 net_log_.AddEvent(NetLog::TYPE_CANCELLED);
1284 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB);
[email protected]68ad3ee2010-01-30 03:45:391285 }
[email protected]b3601bc22012-02-21 21:23:201286 // else CompleteRequests logged EndEvent.
[email protected]68ad3ee2010-01-30 03:45:391287
[email protected]b3601bc22012-02-21 21:23:201288 // Log any remaining Requests as cancelled.
1289 for (RequestsList::const_iterator it = requests_.begin();
1290 it != requests_.end(); ++it) {
1291 Request* req = *it;
1292 if (req->was_canceled())
1293 continue;
1294 DCHECK_EQ(this, req->job());
xunjieli26f90452014-11-10 16:23:021295 LogCancelRequest(req->source_net_log(), req->info());
[email protected]b3601bc22012-02-21 21:23:201296 }
[email protected]68ad3ee2010-01-30 03:45:391297 }
1298
[email protected]daae1322013-09-05 18:26:501299 // Add this job to the dispatcher. If "at_head" is true, adds at the front
1300 // of the queue.
1301 void Schedule(bool at_head) {
1302 DCHECK(!is_queued());
1303 PrioritizedDispatcher::Handle handle;
1304 if (!at_head) {
[email protected]106ccd2c2014-06-17 09:21:001305 handle = resolver_->dispatcher_->Add(this, priority());
[email protected]daae1322013-09-05 18:26:501306 } else {
[email protected]106ccd2c2014-06-17 09:21:001307 handle = resolver_->dispatcher_->AddAtHead(this, priority());
[email protected]daae1322013-09-05 18:26:501308 }
1309 // The dispatcher could have started |this| in the above call to Add, which
1310 // could have called Schedule again. In that case |handle| will be null,
1311 // but |handle_| may have been set by the other nested call to Schedule.
1312 if (!handle.is_null()) {
1313 DCHECK(handle_.is_null());
1314 handle_ = handle;
1315 }
[email protected]16ee26d2012-03-08 03:34:351316 }
1317
[email protected]b3601bc22012-02-21 21:23:201318 void AddRequest(scoped_ptr<Request> req) {
estarkd1bc206e2015-06-20 00:44:391319 DCHECK_EQ(key_.hostname, req->info().hostname());
[email protected]0f292de02012-02-01 22:28:201320
1321 req->set_job(this);
[email protected]5109c1952013-08-20 18:44:101322 priority_tracker_.Add(req->priority());
[email protected]0f292de02012-02-01 22:28:201323
xunjieli26f90452014-11-10 16:23:021324 req->source_net_log().AddEvent(
[email protected]0f292de02012-02-01 22:28:201325 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_ATTACH,
[email protected]cd565142012-06-12 16:21:451326 net_log_.source().ToEventParametersCallback());
[email protected]0f292de02012-02-01 22:28:201327
1328 net_log_.AddEvent(
1329 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_REQUEST_ATTACH,
[email protected]cd565142012-06-12 16:21:451330 base::Bind(&NetLogJobAttachCallback,
xunjieli26f90452014-11-10 16:23:021331 req->source_net_log().source(),
[email protected]cd565142012-06-12 16:21:451332 priority()));
[email protected]0f292de02012-02-01 22:28:201333
1334 // TODO(szym): Check if this is still needed.
1335 if (!req->info().is_speculative()) {
1336 had_non_speculative_request_ = true;
[email protected]90499482013-06-01 00:39:501337 if (proc_task_.get())
[email protected]0f292de02012-02-01 22:28:201338 proc_task_->set_had_non_speculative_request();
[email protected]68ad3ee2010-01-30 03:45:391339 }
[email protected]b3601bc22012-02-21 21:23:201340
hari.singh1bc615d3872015-05-27 04:26:451341 requests_.push_back(req.Pass());
[email protected]b3601bc22012-02-21 21:23:201342
[email protected]51b9a6b2012-06-25 21:50:291343 UpdatePriority();
[email protected]68ad3ee2010-01-30 03:45:391344 }
1345
[email protected]16ee26d2012-03-08 03:34:351346 // Marks |req| as cancelled. If it was the last active Request, also finishes
[email protected]0adcb2b2012-08-15 21:30:461347 // this Job, marking it as cancelled, and deletes it.
[email protected]0f292de02012-02-01 22:28:201348 void CancelRequest(Request* req) {
1349 DCHECK_EQ(key_.hostname, req->info().hostname());
1350 DCHECK(!req->was_canceled());
[email protected]16ee26d2012-03-08 03:34:351351
[email protected]0f292de02012-02-01 22:28:201352 // Don't remove it from |requests_| just mark it canceled.
1353 req->MarkAsCanceled();
xunjieli26f90452014-11-10 16:23:021354 LogCancelRequest(req->source_net_log(), req->info());
[email protected]16ee26d2012-03-08 03:34:351355
[email protected]5109c1952013-08-20 18:44:101356 priority_tracker_.Remove(req->priority());
1357 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_REQUEST_DETACH,
1358 base::Bind(&NetLogJobAttachCallback,
xunjieli26f90452014-11-10 16:23:021359 req->source_net_log().source(),
[email protected]5109c1952013-08-20 18:44:101360 priority()));
[email protected]b3601bc22012-02-21 21:23:201361
[email protected]16ee26d2012-03-08 03:34:351362 if (num_active_requests() > 0) {
[email protected]51b9a6b2012-06-25 21:50:291363 UpdatePriority();
[email protected]16ee26d2012-03-08 03:34:351364 } else {
1365 // If we were called from a Request's callback within CompleteRequests,
1366 // that Request could not have been cancelled, so num_active_requests()
1367 // could not be 0. Therefore, we are not in CompleteRequests().
[email protected]1339a2a22012-10-17 08:39:431368 CompleteRequestsWithError(OK /* cancelled */);
[email protected]b3601bc22012-02-21 21:23:201369 }
[email protected]68ad3ee2010-01-30 03:45:391370 }
1371
[email protected]7af985a2012-12-14 22:40:421372 // Called from AbortAllInProgressJobs. Completes all requests and destroys
1373 // the job. This currently assumes the abort is due to a network change.
[email protected]0f292de02012-02-01 22:28:201374 void Abort() {
[email protected]0f292de02012-02-01 22:28:201375 DCHECK(is_running());
[email protected]7af985a2012-12-14 22:40:421376 CompleteRequestsWithError(ERR_NETWORK_CHANGED);
[email protected]b3601bc22012-02-21 21:23:201377 }
1378
[email protected]f0f602bd2012-11-15 18:01:021379 // If DnsTask present, abort it and fall back to ProcTask.
1380 void AbortDnsTask() {
1381 if (dns_task_) {
[email protected]daae1322013-09-05 18:26:501382 KillDnsTask();
[email protected]f0f602bd2012-11-15 18:01:021383 dns_task_error_ = OK;
1384 StartProcTask();
1385 }
1386 }
1387
[email protected]16ee26d2012-03-08 03:34:351388 // Called by HostResolverImpl when this job is evicted due to queue overflow.
1389 // Completes all requests and destroys the job.
1390 void OnEvicted() {
1391 DCHECK(!is_running());
1392 DCHECK(is_queued());
1393 handle_.Reset();
1394
[email protected]4da911f2012-06-14 19:45:201395 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_EVICTED);
[email protected]16ee26d2012-03-08 03:34:351396
1397 // This signals to CompleteRequests that this job never ran.
[email protected]1339a2a22012-10-17 08:39:431398 CompleteRequestsWithError(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
[email protected]16ee26d2012-03-08 03:34:351399 }
1400
[email protected]78eac2a2012-03-14 19:09:271401 // Attempts to serve the job from HOSTS. Returns true if succeeded and
1402 // this Job was destroyed.
1403 bool ServeFromHosts() {
1404 DCHECK_GT(num_active_requests(), 0u);
1405 AddressList addr_list;
1406 if (resolver_->ServeFromHosts(key(),
[email protected]3cb676a12012-06-30 15:46:031407 requests_.front()->info(),
[email protected]78eac2a2012-03-14 19:09:271408 &addr_list)) {
1409 // This will destroy the Job.
[email protected]895123222012-10-25 15:21:171410 CompleteRequests(
1411 HostCache::Entry(OK, MakeAddressListForRequest(addr_list)),
1412 base::TimeDelta());
[email protected]78eac2a2012-03-14 19:09:271413 return true;
1414 }
1415 return false;
1416 }
1417
[email protected]b4481b222012-03-16 17:13:111418 const Key key() const {
1419 return key_;
1420 }
1421
1422 bool is_queued() const {
1423 return !handle_.is_null();
1424 }
1425
1426 bool is_running() const {
1427 return is_dns_running() || is_proc_running();
1428 }
1429
[email protected]16ee26d2012-03-08 03:34:351430 private:
[email protected]daae1322013-09-05 18:26:501431 void KillDnsTask() {
1432 if (dns_task_) {
1433 ReduceToOneJobSlot();
1434 dns_task_.reset();
1435 }
1436 }
1437
1438 // Reduce the number of job slots occupied and queued in the dispatcher
1439 // to one. If the second Job slot is queued in the dispatcher, cancels the
1440 // queued job. Otherwise, the second Job has been started by the
1441 // PrioritizedDispatcher, so signals it is complete.
1442 void ReduceToOneJobSlot() {
1443 DCHECK_GE(num_occupied_job_slots_, 1u);
1444 if (is_queued()) {
[email protected]106ccd2c2014-06-17 09:21:001445 resolver_->dispatcher_->Cancel(handle_);
[email protected]daae1322013-09-05 18:26:501446 handle_.Reset();
1447 } else if (num_occupied_job_slots_ > 1) {
[email protected]106ccd2c2014-06-17 09:21:001448 resolver_->dispatcher_->OnJobFinished();
[email protected]daae1322013-09-05 18:26:501449 --num_occupied_job_slots_;
1450 }
1451 DCHECK_EQ(1u, num_occupied_job_slots_);
1452 }
1453
[email protected]51b9a6b2012-06-25 21:50:291454 void UpdatePriority() {
1455 if (is_queued()) {
1456 if (priority() != static_cast<RequestPriority>(handle_.priority()))
1457 priority_change_time_ = base::TimeTicks::Now();
[email protected]106ccd2c2014-06-17 09:21:001458 handle_ = resolver_->dispatcher_->ChangePriority(handle_, priority());
[email protected]51b9a6b2012-06-25 21:50:291459 }
1460 }
1461
[email protected]895123222012-10-25 15:21:171462 AddressList MakeAddressListForRequest(const AddressList& list) const {
1463 if (requests_.empty())
1464 return list;
1465 return AddressList::CopyWithPort(list, requests_.front()->info().port());
1466 }
1467
[email protected]16ee26d2012-03-08 03:34:351468 // PriorityDispatch::Job:
dchengb03027d2014-10-21 12:00:201469 void Start() override {
[email protected]daae1322013-09-05 18:26:501470 DCHECK_LE(num_occupied_job_slots_, 1u);
1471
[email protected]70c04ab2013-08-22 16:05:121472 handle_.Reset();
[email protected]daae1322013-09-05 18:26:501473 ++num_occupied_job_slots_;
1474
1475 if (num_occupied_job_slots_ == 2) {
1476 StartSecondDnsTransaction();
1477 return;
1478 }
1479
1480 DCHECK(!is_running());
[email protected]0f292de02012-02-01 22:28:201481
[email protected]4da911f2012-06-14 19:45:201482 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_STARTED);
[email protected]0f292de02012-02-01 22:28:201483
[email protected]51b9a6b2012-06-25 21:50:291484 had_dns_config_ = resolver_->HaveDnsConfig();
1485
1486 base::TimeTicks now = base::TimeTicks::Now();
1487 base::TimeDelta queue_time = now - creation_time_;
1488 base::TimeDelta queue_time_after_change = now - priority_change_time_;
1489
1490 if (had_dns_config_) {
1491 DNS_HISTOGRAM_BY_PRIORITY("AsyncDNS.JobQueueTime", priority(),
1492 queue_time);
1493 DNS_HISTOGRAM_BY_PRIORITY("AsyncDNS.JobQueueTimeAfterChange", priority(),
1494 queue_time_after_change);
1495 } else {
1496 DNS_HISTOGRAM_BY_PRIORITY("DNS.JobQueueTime", priority(), queue_time);
1497 DNS_HISTOGRAM_BY_PRIORITY("DNS.JobQueueTimeAfterChange", priority(),
1498 queue_time_after_change);
1499 }
1500
[email protected]443714fad2013-09-19 04:52:011501 bool system_only =
1502 (key_.host_resolver_flags & HOST_RESOLVER_SYSTEM_ONLY) != 0;
1503
[email protected]1d932852012-06-19 19:40:331504 // Caution: Job::Start must not complete synchronously.
[email protected]443714fad2013-09-19 04:52:011505 if (!system_only && had_dns_config_ &&
1506 !ResemblesMulticastDNSName(key_.hostname)) {
[email protected]b3601bc22012-02-21 21:23:201507 StartDnsTask();
1508 } else {
1509 StartProcTask();
1510 }
1511 }
1512
[email protected]b3601bc22012-02-21 21:23:201513 // TODO(szym): Since DnsTransaction does not consume threads, we can increase
1514 // the limits on |dispatcher_|. But in order to keep the number of WorkerPool
1515 // threads low, we will need to use an "inner" PrioritizedDispatcher with
1516 // tighter limits.
1517 void StartProcTask() {
[email protected]16ee26d2012-03-08 03:34:351518 DCHECK(!is_dns_running());
[email protected]0f292de02012-02-01 22:28:201519 proc_task_ = new ProcTask(
1520 key_,
1521 resolver_->proc_params_,
[email protected]e3bd4822012-10-23 18:01:371522 base::Bind(&Job::OnProcTaskComplete, base::Unretained(this),
1523 base::TimeTicks::Now()),
[email protected]0f292de02012-02-01 22:28:201524 net_log_);
1525
1526 if (had_non_speculative_request_)
1527 proc_task_->set_had_non_speculative_request();
1528 // Start() could be called from within Resolve(), hence it must NOT directly
1529 // call OnProcTaskComplete, for example, on synchronous failure.
1530 proc_task_->Start();
[email protected]68ad3ee2010-01-30 03:45:391531 }
1532
[email protected]0f292de02012-02-01 22:28:201533 // Called by ProcTask when it completes.
[email protected]e3bd4822012-10-23 18:01:371534 void OnProcTaskComplete(base::TimeTicks start_time,
1535 int net_error,
1536 const AddressList& addr_list) {
[email protected]b3601bc22012-02-21 21:23:201537 DCHECK(is_proc_running());
[email protected]68ad3ee2010-01-30 03:45:391538
[email protected]62e86ba2013-01-29 18:59:161539 if (!resolver_->resolved_known_ipv6_hostname_ &&
1540 net_error == OK &&
1541 key_.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
1542 if (key_.hostname == "www.google.com") {
1543 resolver_->resolved_known_ipv6_hostname_ = true;
1544 bool got_ipv6_address = false;
1545 for (size_t i = 0; i < addr_list.size(); ++i) {
[email protected]5134c22a2013-08-06 18:09:021546 if (addr_list[i].GetFamily() == ADDRESS_FAMILY_IPV6) {
[email protected]62e86ba2013-01-29 18:59:161547 got_ipv6_address = true;
[email protected]5134c22a2013-08-06 18:09:021548 break;
1549 }
[email protected]62e86ba2013-01-29 18:59:161550 }
1551 UMA_HISTOGRAM_BOOLEAN("Net.UnspecResolvedIPv6", got_ipv6_address);
1552 }
1553 }
1554
[email protected]1d932852012-06-19 19:40:331555 if (dns_task_error_ != OK) {
[email protected]e3bd4822012-10-23 18:01:371556 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]1def74c2012-03-22 20:07:001557 if (net_error == OK) {
[email protected]e3bd4822012-10-23 18:01:371558 DNS_HISTOGRAM("AsyncDNS.FallbackSuccess", duration);
[email protected]1d932852012-06-19 19:40:331559 if ((dns_task_error_ == ERR_NAME_NOT_RESOLVED) &&
1560 ResemblesNetBIOSName(key_.hostname)) {
1561 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_SUSPECT_NETBIOS);
1562 } else {
1563 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_PROC_SUCCESS);
1564 }
davidbenad6fc442015-05-18 20:59:131565 UMA_HISTOGRAM_SPARSE_SLOWLY("AsyncDNS.ResolveError",
1566 std::abs(dns_task_error_));
[email protected]1ffdda82012-12-12 23:04:221567 resolver_->OnDnsTaskResolve(dns_task_error_);
[email protected]1def74c2012-03-22 20:07:001568 } else {
[email protected]e3bd4822012-10-23 18:01:371569 DNS_HISTOGRAM("AsyncDNS.FallbackFail", duration);
[email protected]1def74c2012-03-22 20:07:001570 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
1571 }
1572 }
1573
[email protected]1339a2a22012-10-17 08:39:431574 base::TimeDelta ttl =
1575 base::TimeDelta::FromSeconds(kNegativeCacheEntryTTLSeconds);
[email protected]b3601bc22012-02-21 21:23:201576 if (net_error == OK)
1577 ttl = base::TimeDelta::FromSeconds(kCacheEntryTTLSeconds);
[email protected]68ad3ee2010-01-30 03:45:391578
[email protected]895123222012-10-25 15:21:171579 // Don't store the |ttl| in cache since it's not obtained from the server.
1580 CompleteRequests(
1581 HostCache::Entry(net_error, MakeAddressListForRequest(addr_list)),
1582 ttl);
[email protected]b3601bc22012-02-21 21:23:201583 }
1584
1585 void StartDnsTask() {
[email protected]78eac2a2012-03-14 19:09:271586 DCHECK(resolver_->HaveDnsConfig());
[email protected]daae1322013-09-05 18:26:501587 dns_task_.reset(new DnsTask(resolver_->dns_client_.get(), key_, this,
1588 net_log_));
[email protected]b3601bc22012-02-21 21:23:201589
[email protected]daae1322013-09-05 18:26:501590 dns_task_->StartFirstTransaction();
1591 // Schedule a second transaction, if needed.
1592 if (dns_task_->needs_two_transactions())
1593 Schedule(true);
1594 }
1595
1596 void StartSecondDnsTransaction() {
1597 DCHECK(dns_task_->needs_two_transactions());
1598 dns_task_->StartSecondTransaction();
[email protected]16c2bd72013-06-28 01:19:221599 }
1600
1601 // Called if DnsTask fails. It is posted from StartDnsTask, so Job may be
1602 // deleted before this callback. In this case dns_task is deleted as well,
1603 // so we use it as indicator whether Job is still valid.
1604 void OnDnsTaskFailure(const base::WeakPtr<DnsTask>& dns_task,
1605 base::TimeDelta duration,
1606 int net_error) {
1607 DNS_HISTOGRAM("AsyncDNS.ResolveFail", duration);
1608
1609 if (dns_task == NULL)
1610 return;
1611
1612 dns_task_error_ = net_error;
1613
1614 // TODO(szym): Run ServeFromHosts now if nsswitch.conf says so.
1615 // http://crbug.com/117655
1616
1617 // TODO(szym): Some net errors indicate lack of connectivity. Starting
1618 // ProcTask in that case is a waste of time.
1619 if (resolver_->fallback_to_proctask_) {
[email protected]daae1322013-09-05 18:26:501620 KillDnsTask();
[email protected]16c2bd72013-06-28 01:19:221621 StartProcTask();
1622 } else {
1623 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
1624 CompleteRequestsWithError(net_error);
[email protected]b3601bc22012-02-21 21:23:201625 }
1626 }
1627
[email protected]daae1322013-09-05 18:26:501628
1629 // HostResolverImpl::DnsTask::Delegate implementation:
1630
dchengb03027d2014-10-21 12:00:201631 void OnDnsTaskComplete(base::TimeTicks start_time,
1632 int net_error,
1633 const AddressList& addr_list,
1634 base::TimeDelta ttl) override {
[email protected]b3601bc22012-02-21 21:23:201635 DCHECK(is_dns_running());
[email protected]b3601bc22012-02-21 21:23:201636
[email protected]e3bd4822012-10-23 18:01:371637 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]b3601bc22012-02-21 21:23:201638 if (net_error != OK) {
[email protected]16c2bd72013-06-28 01:19:221639 OnDnsTaskFailure(dns_task_->AsWeakPtr(), duration, net_error);
[email protected]b3601bc22012-02-21 21:23:201640 return;
1641 }
[email protected]e3bd4822012-10-23 18:01:371642 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess", duration);
[email protected]02cd6982013-01-10 20:12:511643 // Log DNS lookups based on |address_family|.
1644 switch(key_.address_family) {
1645 case ADDRESS_FAMILY_IPV4:
1646 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_IPV4", duration);
1647 break;
1648 case ADDRESS_FAMILY_IPV6:
1649 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_IPV6", duration);
1650 break;
1651 case ADDRESS_FAMILY_UNSPECIFIED:
1652 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_UNSPEC", duration);
1653 break;
1654 }
[email protected]b3601bc22012-02-21 21:23:201655
[email protected]1def74c2012-03-22 20:07:001656 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_DNS_SUCCESS);
[email protected]1339a2a22012-10-17 08:39:431657 RecordTTL(ttl);
[email protected]0adcb2b2012-08-15 21:30:461658
[email protected]1ffdda82012-12-12 23:04:221659 resolver_->OnDnsTaskResolve(OK);
[email protected]f0f602bd2012-11-15 18:01:021660
[email protected]895123222012-10-25 15:21:171661 base::TimeDelta bounded_ttl =
1662 std::max(ttl, base::TimeDelta::FromSeconds(kMinimumTTLSeconds));
1663
1664 CompleteRequests(
1665 HostCache::Entry(net_error, MakeAddressListForRequest(addr_list), ttl),
1666 bounded_ttl);
[email protected]b3601bc22012-02-21 21:23:201667 }
1668
dchengb03027d2014-10-21 12:00:201669 void OnFirstDnsTransactionComplete() override {
[email protected]daae1322013-09-05 18:26:501670 DCHECK(dns_task_->needs_two_transactions());
1671 DCHECK_EQ(dns_task_->needs_another_transaction(), is_queued());
1672 // No longer need to occupy two dispatcher slots.
1673 ReduceToOneJobSlot();
1674
1675 // We already have a job slot at the dispatcher, so if the second
1676 // transaction hasn't started, reuse it now instead of waiting in the queue
1677 // for the second slot.
1678 if (dns_task_->needs_another_transaction())
1679 dns_task_->StartSecondTransaction();
1680 }
1681
[email protected]16ee26d2012-03-08 03:34:351682 // Performs Job's last rites. Completes all Requests. Deletes this.
[email protected]895123222012-10-25 15:21:171683 void CompleteRequests(const HostCache::Entry& entry,
1684 base::TimeDelta ttl) {
[email protected]11fbca0b2013-06-02 23:37:211685 CHECK(resolver_.get());
[email protected]b3601bc22012-02-21 21:23:201686
[email protected]16ee26d2012-03-08 03:34:351687 // This job must be removed from resolver's |jobs_| now to make room for a
1688 // new job with the same key in case one of the OnComplete callbacks decides
1689 // to spawn one. Consequently, the job deletes itself when CompleteRequests
1690 // is done.
1691 scoped_ptr<Job> self_deleter(this);
1692
1693 resolver_->RemoveJob(this);
1694
[email protected]16ee26d2012-03-08 03:34:351695 if (is_running()) {
[email protected]16ee26d2012-03-08 03:34:351696 if (is_proc_running()) {
[email protected]daae1322013-09-05 18:26:501697 DCHECK(!is_queued());
[email protected]16ee26d2012-03-08 03:34:351698 proc_task_->Cancel();
1699 proc_task_ = NULL;
1700 }
[email protected]daae1322013-09-05 18:26:501701 KillDnsTask();
[email protected]16ee26d2012-03-08 03:34:351702
1703 // Signal dispatcher that a slot has opened.
[email protected]106ccd2c2014-06-17 09:21:001704 resolver_->dispatcher_->OnJobFinished();
[email protected]16ee26d2012-03-08 03:34:351705 } else if (is_queued()) {
[email protected]106ccd2c2014-06-17 09:21:001706 resolver_->dispatcher_->Cancel(handle_);
[email protected]16ee26d2012-03-08 03:34:351707 handle_.Reset();
1708 }
1709
1710 if (num_active_requests() == 0) {
[email protected]4da911f2012-06-14 19:45:201711 net_log_.AddEvent(NetLog::TYPE_CANCELLED);
[email protected]16ee26d2012-03-08 03:34:351712 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
1713 OK);
1714 return;
1715 }
[email protected]b3601bc22012-02-21 21:23:201716
1717 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
[email protected]895123222012-10-25 15:21:171718 entry.error);
[email protected]68ad3ee2010-01-30 03:45:391719
[email protected]78eac2a2012-03-14 19:09:271720 DCHECK(!requests_.empty());
1721
[email protected]895123222012-10-25 15:21:171722 if (entry.error == OK) {
[email protected]d7b9a2b2012-05-31 22:31:191723 // Record this histogram here, when we know the system has a valid DNS
1724 // configuration.
[email protected]539df6c2012-06-19 21:21:291725 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.HaveDnsConfig",
1726 resolver_->received_dns_config_);
[email protected]d7b9a2b2012-05-31 22:31:191727 }
[email protected]16ee26d2012-03-08 03:34:351728
[email protected]7af985a2012-12-14 22:40:421729 bool did_complete = (entry.error != ERR_NETWORK_CHANGED) &&
[email protected]895123222012-10-25 15:21:171730 (entry.error != ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
1731 if (did_complete)
[email protected]1339a2a22012-10-17 08:39:431732 resolver_->CacheResult(key_, entry, ttl);
[email protected]16ee26d2012-03-08 03:34:351733
[email protected]0f292de02012-02-01 22:28:201734 // Complete all of the requests that were attached to the job.
1735 for (RequestsList::const_iterator it = requests_.begin();
1736 it != requests_.end(); ++it) {
1737 Request* req = *it;
1738
1739 if (req->was_canceled())
1740 continue;
1741
1742 DCHECK_EQ(this, req->job());
1743 // Update the net log and notify registered observers.
xunjieli26f90452014-11-10 16:23:021744 LogFinishRequest(req->source_net_log(), req->info(), entry.error);
[email protected]51b9a6b2012-06-25 21:50:291745 if (did_complete) {
1746 // Record effective total time from creation to completion.
1747 RecordTotalTime(had_dns_config_, req->info().is_speculative(),
1748 base::TimeTicks::Now() - req->request_time());
1749 }
[email protected]895123222012-10-25 15:21:171750 req->OnComplete(entry.error, entry.addrlist);
[email protected]0f292de02012-02-01 22:28:201751
1752 // Check if the resolver was destroyed as a result of running the
1753 // callback. If it was, we could continue, but we choose to bail.
[email protected]11fbca0b2013-06-02 23:37:211754 if (!resolver_.get())
[email protected]0f292de02012-02-01 22:28:201755 return;
1756 }
1757 }
1758
[email protected]1339a2a22012-10-17 08:39:431759 // Convenience wrapper for CompleteRequests in case of failure.
1760 void CompleteRequestsWithError(int net_error) {
[email protected]895123222012-10-25 15:21:171761 CompleteRequests(HostCache::Entry(net_error, AddressList()),
1762 base::TimeDelta());
[email protected]1339a2a22012-10-17 08:39:431763 }
1764
[email protected]b4481b222012-03-16 17:13:111765 RequestPriority priority() const {
1766 return priority_tracker_.highest_priority();
1767 }
1768
1769 // Number of non-canceled requests in |requests_|.
1770 size_t num_active_requests() const {
1771 return priority_tracker_.total_count();
1772 }
1773
1774 bool is_dns_running() const {
1775 return dns_task_.get() != NULL;
1776 }
1777
1778 bool is_proc_running() const {
1779 return proc_task_.get() != NULL;
1780 }
1781
[email protected]0f292de02012-02-01 22:28:201782 base::WeakPtr<HostResolverImpl> resolver_;
1783
1784 Key key_;
1785
1786 // Tracks the highest priority across |requests_|.
1787 PriorityTracker priority_tracker_;
1788
1789 bool had_non_speculative_request_;
1790
[email protected]51b9a6b2012-06-25 21:50:291791 // Distinguishes measurements taken while DnsClient was fully configured.
1792 bool had_dns_config_;
1793
[email protected]daae1322013-09-05 18:26:501794 // Number of slots occupied by this Job in resolver's PrioritizedDispatcher.
1795 unsigned num_occupied_job_slots_;
1796
[email protected]1d932852012-06-19 19:40:331797 // Result of DnsTask.
1798 int dns_task_error_;
[email protected]1def74c2012-03-22 20:07:001799
[email protected]51b9a6b2012-06-25 21:50:291800 const base::TimeTicks creation_time_;
1801 base::TimeTicks priority_change_time_;
1802
[email protected]0f292de02012-02-01 22:28:201803 BoundNetLog net_log_;
1804
[email protected]b3601bc22012-02-21 21:23:201805 // Resolves the host using a HostResolverProc.
[email protected]0f292de02012-02-01 22:28:201806 scoped_refptr<ProcTask> proc_task_;
1807
[email protected]b3601bc22012-02-21 21:23:201808 // Resolves the host using a DnsTransaction.
1809 scoped_ptr<DnsTask> dns_task_;
1810
[email protected]0f292de02012-02-01 22:28:201811 // All Requests waiting for the result of this Job. Some can be canceled.
1812 RequestsList requests_;
1813
[email protected]16ee26d2012-03-08 03:34:351814 // A handle used in |HostResolverImpl::dispatcher_|.
[email protected]0f292de02012-02-01 22:28:201815 PrioritizedDispatcher::Handle handle_;
[email protected]68ad3ee2010-01-30 03:45:391816};
1817
1818//-----------------------------------------------------------------------------
1819
[email protected]0f292de02012-02-01 22:28:201820HostResolverImpl::ProcTaskParams::ProcTaskParams(
[email protected]e95d3aca2010-01-11 22:47:431821 HostResolverProc* resolver_proc,
[email protected]0f292de02012-02-01 22:28:201822 size_t max_retry_attempts)
1823 : resolver_proc(resolver_proc),
1824 max_retry_attempts(max_retry_attempts),
1825 unresponsive_delay(base::TimeDelta::FromMilliseconds(6000)),
1826 retry_factor(2) {
[email protected]106ccd2c2014-06-17 09:21:001827 // Maximum of 4 retry attempts for host resolution.
1828 static const size_t kDefaultMaxRetryAttempts = 4u;
1829 if (max_retry_attempts == HostResolver::kDefaultRetryAttempts)
1830 max_retry_attempts = kDefaultMaxRetryAttempts;
[email protected]0f292de02012-02-01 22:28:201831}
1832
1833HostResolverImpl::ProcTaskParams::~ProcTaskParams() {}
1834
[email protected]106ccd2c2014-06-17 09:21:001835HostResolverImpl::HostResolverImpl(const Options& options, NetLog* net_log)
1836 : max_queued_jobs_(0),
1837 proc_params_(NULL, options.max_retry_attempts),
[email protected]62e86ba2013-01-29 18:59:161838 net_log_(net_log),
[email protected]d7b9a2b2012-05-31 22:31:191839 received_dns_config_(false),
[email protected]f0f602bd2012-11-15 18:01:021840 num_dns_failures_(0),
[email protected]c9fa8f312013-09-17 12:24:521841 use_local_ipv6_(false),
sergeyub8cdc212015-05-14 18:50:371842 last_ipv6_probe_result_(true),
[email protected]62e86ba2013-01-29 18:59:161843 resolved_known_ipv6_hostname_(false),
[email protected]16c2bd72013-06-28 01:19:221844 additional_resolver_flags_(0),
[email protected]0a30cf512014-05-27 20:55:181845 fallback_to_proctask_(true),
1846 weak_ptr_factory_(this),
1847 probe_weak_ptr_factory_(this) {
[email protected]106ccd2c2014-06-17 09:21:001848 if (options.enable_caching)
1849 cache_ = HostCache::CreateDefaultCache();
[email protected]0f292de02012-02-01 22:28:201850
[email protected]106ccd2c2014-06-17 09:21:001851 PrioritizedDispatcher::Limits job_limits = options.GetDispatcherLimits();
1852 dispatcher_.reset(new PrioritizedDispatcher(job_limits));
1853 max_queued_jobs_ = job_limits.total_jobs * 100u;
[email protected]68ad3ee2010-01-30 03:45:391854
[email protected]106ccd2c2014-06-17 09:21:001855 DCHECK_GE(dispatcher_->num_priorities(), static_cast<size_t>(NUM_PRIORITIES));
[email protected]68ad3ee2010-01-30 03:45:391856
[email protected]b59ff372009-07-15 22:04:321857#if defined(OS_WIN)
1858 EnsureWinsockInit();
1859#endif
[email protected]7c466e92013-07-20 01:44:481860#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
[email protected]12faa4c2012-11-06 04:44:181861 new LoopbackProbeJob(weak_ptr_factory_.GetWeakPtr());
[email protected]2f3bc65c2010-07-23 17:47:101862#endif
[email protected]232a5812011-03-04 22:42:081863 NetworkChangeNotifier::AddIPAddressObserver(this);
[email protected]bb0e34542012-08-31 19:52:401864 NetworkChangeNotifier::AddDNSObserver(this);
[email protected]d7b9a2b2012-05-31 22:31:191865#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD) && \
1866 !defined(OS_ANDROID)
[email protected]d7b9a2b2012-05-31 22:31:191867 EnsureDnsReloaderInit();
[email protected]46018c9d2011-09-06 03:42:341868#endif
[email protected]2ac22db2012-11-28 19:50:041869
[email protected]2ac22db2012-11-28 19:50:041870 {
1871 DnsConfig dns_config;
1872 NetworkChangeNotifier::GetDnsConfig(&dns_config);
1873 received_dns_config_ = dns_config.IsValid();
[email protected]c9fa8f312013-09-17 12:24:521874 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
1875 use_local_ipv6_ = !dns_config.IsValid() || dns_config.use_local_ipv6;
[email protected]2ac22db2012-11-28 19:50:041876 }
[email protected]16c2bd72013-06-28 01:19:221877
1878 fallback_to_proctask_ = !ConfigureAsyncDnsNoFallbackFieldTrial();
[email protected]b59ff372009-07-15 22:04:321879}
1880
1881HostResolverImpl::~HostResolverImpl() {
[email protected]daae1322013-09-05 18:26:501882 // Prevent the dispatcher from starting new jobs.
[email protected]106ccd2c2014-06-17 09:21:001883 dispatcher_->SetLimitsToZero();
[email protected]daae1322013-09-05 18:26:501884 // It's now safe for Jobs to call KillDsnTask on destruction, because
1885 // OnJobComplete will not start any new jobs.
[email protected]0f292de02012-02-01 22:28:201886 STLDeleteValues(&jobs_);
[email protected]e95d3aca2010-01-11 22:47:431887
[email protected]232a5812011-03-04 22:42:081888 NetworkChangeNotifier::RemoveIPAddressObserver(this);
[email protected]bb0e34542012-08-31 19:52:401889 NetworkChangeNotifier::RemoveDNSObserver(this);
[email protected]b59ff372009-07-15 22:04:321890}
1891
[email protected]0f292de02012-02-01 22:28:201892void HostResolverImpl::SetMaxQueuedJobs(size_t value) {
[email protected]106ccd2c2014-06-17 09:21:001893 DCHECK_EQ(0u, dispatcher_->num_queued_jobs());
[email protected]0f292de02012-02-01 22:28:201894 DCHECK_GT(value, 0u);
1895 max_queued_jobs_ = value;
[email protected]be1a48b2011-01-20 00:12:131896}
1897
[email protected]684970b2009-08-14 04:54:461898int HostResolverImpl::Resolve(const RequestInfo& info,
[email protected]5109c1952013-08-20 18:44:101899 RequestPriority priority,
[email protected]b59ff372009-07-15 22:04:321900 AddressList* addresses,
[email protected]aa22b242011-11-16 18:58:291901 const CompletionCallback& callback,
[email protected]684970b2009-08-14 04:54:461902 RequestHandle* out_req,
[email protected]ee094b82010-08-24 15:55:511903 const BoundNetLog& source_net_log) {
[email protected]95a214c2011-08-04 21:50:401904 DCHECK(addresses);
[email protected]1ac6af92010-06-03 21:00:141905 DCHECK(CalledOnValidThread());
[email protected]aa22b242011-11-16 18:58:291906 DCHECK_EQ(false, callback.is_null());
[email protected]1ac6af92010-06-03 21:00:141907
[email protected]e806cd72013-05-17 02:08:431908 // Check that the caller supplied a valid hostname to resolve.
1909 std::string labeled_hostname;
1910 if (!DNSDomainFromDot(info.hostname(), &labeled_hostname))
1911 return ERR_NAME_NOT_RESOLVED;
1912
xunjieli26f90452014-11-10 16:23:021913 LogStartRequest(source_net_log, info);
[email protected]b59ff372009-07-15 22:04:321914
pauljensen19eb73422015-04-15 23:20:061915 IPAddressNumber ip_number;
1916 IPAddressNumber* ip_number_ptr = nullptr;
1917 if (ParseIPLiteralToNumber(info.hostname(), &ip_number))
1918 ip_number_ptr = &ip_number;
1919
[email protected]123ab1e32009-10-21 19:12:571920 // Build a key that identifies the request in the cache and in the
1921 // outstanding jobs map.
pauljensen19eb73422015-04-15 23:20:061922 Key key = GetEffectiveKeyForRequest(info, ip_number_ptr, source_net_log);
[email protected]123ab1e32009-10-21 19:12:571923
pauljensen19eb73422015-04-15 23:20:061924 int rv = ResolveHelper(key, info, ip_number_ptr, addresses, source_net_log);
[email protected]95a214c2011-08-04 21:50:401925 if (rv != ERR_DNS_CACHE_MISS) {
xunjieli26f90452014-11-10 16:23:021926 LogFinishRequest(source_net_log, info, rv);
[email protected]51b9a6b2012-06-25 21:50:291927 RecordTotalTime(HaveDnsConfig(), info.is_speculative(), base::TimeDelta());
[email protected]95a214c2011-08-04 21:50:401928 return rv;
[email protected]38368712011-03-02 08:09:401929 }
1930
[email protected]0f292de02012-02-01 22:28:201931 // Next we need to attach our request to a "job". This job is responsible for
1932 // calling "getaddrinfo(hostname)" on a worker thread.
1933
1934 JobMap::iterator jobit = jobs_.find(key);
1935 Job* job;
1936 if (jobit == jobs_.end()) {
[email protected]5109c1952013-08-20 18:44:101937 job =
xunjieli26f90452014-11-10 16:23:021938 new Job(weak_ptr_factory_.GetWeakPtr(), key, priority, source_net_log);
[email protected]daae1322013-09-05 18:26:501939 job->Schedule(false);
[email protected]0f292de02012-02-01 22:28:201940
1941 // Check for queue overflow.
[email protected]106ccd2c2014-06-17 09:21:001942 if (dispatcher_->num_queued_jobs() > max_queued_jobs_) {
1943 Job* evicted = static_cast<Job*>(dispatcher_->EvictOldestLowest());
[email protected]0f292de02012-02-01 22:28:201944 DCHECK(evicted);
[email protected]16ee26d2012-03-08 03:34:351945 evicted->OnEvicted(); // Deletes |evicted|.
[email protected]0f292de02012-02-01 22:28:201946 if (evicted == job) {
[email protected]0f292de02012-02-01 22:28:201947 rv = ERR_HOST_RESOLVER_QUEUE_TOO_LARGE;
xunjieli26f90452014-11-10 16:23:021948 LogFinishRequest(source_net_log, info, rv);
[email protected]0f292de02012-02-01 22:28:201949 return rv;
1950 }
[email protected]0f292de02012-02-01 22:28:201951 }
[email protected]0f292de02012-02-01 22:28:201952 jobs_.insert(jobit, std::make_pair(key, job));
1953 } else {
1954 job = jobit->second;
1955 }
1956
1957 // Can't complete synchronously. Create and attach request.
[email protected]5109c1952013-08-20 18:44:101958 scoped_ptr<Request> req(new Request(
xunjieli26f90452014-11-10 16:23:021959 source_net_log, info, priority, callback, addresses));
[email protected]b59ff372009-07-15 22:04:321960 if (out_req)
[email protected]b3601bc22012-02-21 21:23:201961 *out_req = reinterpret_cast<RequestHandle>(req.get());
[email protected]b59ff372009-07-15 22:04:321962
[email protected]b3601bc22012-02-21 21:23:201963 job->AddRequest(req.Pass());
[email protected]0f292de02012-02-01 22:28:201964 // Completion happens during Job::CompleteRequests().
[email protected]b59ff372009-07-15 22:04:321965 return ERR_IO_PENDING;
1966}
1967
[email protected]287d7c22011-11-15 17:34:251968int HostResolverImpl::ResolveHelper(const Key& key,
[email protected]95a214c2011-08-04 21:50:401969 const RequestInfo& info,
pauljensen19eb73422015-04-15 23:20:061970 const IPAddressNumber* ip_number,
[email protected]95a214c2011-08-04 21:50:401971 AddressList* addresses,
xunjieli26f90452014-11-10 16:23:021972 const BoundNetLog& source_net_log) {
[email protected]95a214c2011-08-04 21:50:401973 // The result of |getaddrinfo| for empty hosts is inconsistent across systems.
1974 // On Windows it gives the default interface's address, whereas on Linux it
1975 // gives an error. We will make it fail on all platforms for consistency.
1976 if (info.hostname().empty() || info.hostname().size() > kMaxHostLength)
1977 return ERR_NAME_NOT_RESOLVED;
1978
1979 int net_error = ERR_UNEXPECTED;
pauljensen19eb73422015-04-15 23:20:061980 if (ResolveAsIP(key, info, ip_number, &net_error, addresses))
[email protected]95a214c2011-08-04 21:50:401981 return net_error;
[email protected]78eac2a2012-03-14 19:09:271982 if (ServeFromCache(key, info, &net_error, addresses)) {
xunjieli26f90452014-11-10 16:23:021983 source_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_CACHE_HIT);
[email protected]78eac2a2012-03-14 19:09:271984 return net_error;
1985 }
1986 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
1987 // http://crbug.com/117655
1988 if (ServeFromHosts(key, info, addresses)) {
xunjieli26f90452014-11-10 16:23:021989 source_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_HOSTS_HIT);
[email protected]78eac2a2012-03-14 19:09:271990 return OK;
1991 }
estarkd1bc206e2015-06-20 00:44:391992
1993 if (ServeLocalhost(key, info, addresses))
1994 return OK;
1995
[email protected]78eac2a2012-03-14 19:09:271996 return ERR_DNS_CACHE_MISS;
[email protected]95a214c2011-08-04 21:50:401997}
1998
1999int HostResolverImpl::ResolveFromCache(const RequestInfo& info,
2000 AddressList* addresses,
2001 const BoundNetLog& source_net_log) {
2002 DCHECK(CalledOnValidThread());
2003 DCHECK(addresses);
2004
[email protected]95a214c2011-08-04 21:50:402005 // Update the net log and notify registered observers.
xunjieli26f90452014-11-10 16:23:022006 LogStartRequest(source_net_log, info);
[email protected]95a214c2011-08-04 21:50:402007
pauljensen19eb73422015-04-15 23:20:062008 IPAddressNumber ip_number;
2009 IPAddressNumber* ip_number_ptr = nullptr;
2010 if (ParseIPLiteralToNumber(info.hostname(), &ip_number))
2011 ip_number_ptr = &ip_number;
[email protected]95a214c2011-08-04 21:50:402012
pauljensen19eb73422015-04-15 23:20:062013 Key key = GetEffectiveKeyForRequest(info, ip_number_ptr, source_net_log);
2014
2015 int rv = ResolveHelper(key, info, ip_number_ptr, addresses, source_net_log);
xunjieli26f90452014-11-10 16:23:022016 LogFinishRequest(source_net_log, info, rv);
[email protected]95a214c2011-08-04 21:50:402017 return rv;
2018}
2019
[email protected]b59ff372009-07-15 22:04:322020void HostResolverImpl::CancelRequest(RequestHandle req_handle) {
[email protected]1ac6af92010-06-03 21:00:142021 DCHECK(CalledOnValidThread());
[email protected]b59ff372009-07-15 22:04:322022 Request* req = reinterpret_cast<Request*>(req_handle);
2023 DCHECK(req);
[email protected]0f292de02012-02-01 22:28:202024 Job* job = req->job();
2025 DCHECK(job);
[email protected]0f292de02012-02-01 22:28:202026 job->CancelRequest(req);
[email protected]b59ff372009-07-15 22:04:322027}
2028
[email protected]a8883e452012-11-17 05:58:062029void HostResolverImpl::SetDnsClientEnabled(bool enabled) {
2030 DCHECK(CalledOnValidThread());
2031#if defined(ENABLE_BUILT_IN_DNS)
2032 if (enabled && !dns_client_) {
2033 SetDnsClient(DnsClient::CreateClient(net_log_));
2034 } else if (!enabled && dns_client_) {
2035 SetDnsClient(scoped_ptr<DnsClient>());
2036 }
2037#endif
2038}
2039
[email protected]489d1a82011-10-12 03:09:112040HostCache* HostResolverImpl::GetHostCache() {
2041 return cache_.get();
2042}
[email protected]95a214c2011-08-04 21:50:402043
[email protected]17e92032012-03-29 00:56:242044base::Value* HostResolverImpl::GetDnsConfigAsValue() const {
2045 // Check if async DNS is disabled.
2046 if (!dns_client_.get())
2047 return NULL;
2048
2049 // Check if async DNS is enabled, but we currently have no configuration
2050 // for it.
2051 const DnsConfig* dns_config = dns_client_->GetConfig();
2052 if (dns_config == NULL)
[email protected]ea5ef4c2013-06-13 22:50:272053 return new base::DictionaryValue();
[email protected]17e92032012-03-29 00:56:242054
2055 return dns_config->ToValue();
2056}
2057
[email protected]95a214c2011-08-04 21:50:402058bool HostResolverImpl::ResolveAsIP(const Key& key,
2059 const RequestInfo& info,
pauljensen19eb73422015-04-15 23:20:062060 const IPAddressNumber* ip_number,
[email protected]95a214c2011-08-04 21:50:402061 int* net_error,
2062 AddressList* addresses) {
2063 DCHECK(addresses);
2064 DCHECK(net_error);
pauljensen19eb73422015-04-15 23:20:062065 if (ip_number == nullptr)
[email protected]95a214c2011-08-04 21:50:402066 return false;
2067
2068 DCHECK_EQ(key.host_resolver_flags &
2069 ~(HOST_RESOLVER_CANONNAME | HOST_RESOLVER_LOOPBACK_ONLY |
2070 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6),
2071 0) << " Unhandled flag";
[email protected]1c7cf3f82014-08-07 21:33:482072
[email protected]95a214c2011-08-04 21:50:402073 *net_error = OK;
pauljensen19eb73422015-04-15 23:20:062074 AddressFamily family = GetAddressFamily(*ip_number);
cbentzel1906f872015-06-05 16:25:252075 if (key.address_family != ADDRESS_FAMILY_UNSPECIFIED &&
2076 key.address_family != family) {
[email protected]1c7cf3f82014-08-07 21:33:482077 // Don't return IPv6 addresses for IPv4 queries, and vice versa.
[email protected]95a214c2011-08-04 21:50:402078 *net_error = ERR_NAME_NOT_RESOLVED;
2079 } else {
pauljensen19eb73422015-04-15 23:20:062080 *addresses = AddressList::CreateFromIPAddress(*ip_number, info.port());
[email protected]7054e78f2012-05-07 21:44:562081 if (key.host_resolver_flags & HOST_RESOLVER_CANONNAME)
2082 addresses->SetDefaultCanonicalName();
[email protected]95a214c2011-08-04 21:50:402083 }
2084 return true;
2085}
2086
2087bool HostResolverImpl::ServeFromCache(const Key& key,
2088 const RequestInfo& info,
[email protected]95a214c2011-08-04 21:50:402089 int* net_error,
2090 AddressList* addresses) {
2091 DCHECK(addresses);
2092 DCHECK(net_error);
2093 if (!info.allow_cached_response() || !cache_.get())
2094 return false;
2095
[email protected]407a30ab2012-08-15 17:16:102096 const HostCache::Entry* cache_entry = cache_->Lookup(
2097 key, base::TimeTicks::Now());
[email protected]95a214c2011-08-04 21:50:402098 if (!cache_entry)
2099 return false;
2100
[email protected]95a214c2011-08-04 21:50:402101 *net_error = cache_entry->error;
[email protected]7054e78f2012-05-07 21:44:562102 if (*net_error == OK) {
[email protected]1339a2a22012-10-17 08:39:432103 if (cache_entry->has_ttl())
2104 RecordTTL(cache_entry->ttl);
[email protected]895123222012-10-25 15:21:172105 *addresses = EnsurePortOnAddressList(cache_entry->addrlist, info.port());
[email protected]7054e78f2012-05-07 21:44:562106 }
[email protected]95a214c2011-08-04 21:50:402107 return true;
2108}
2109
[email protected]78eac2a2012-03-14 19:09:272110bool HostResolverImpl::ServeFromHosts(const Key& key,
2111 const RequestInfo& info,
2112 AddressList* addresses) {
2113 DCHECK(addresses);
2114 if (!HaveDnsConfig())
2115 return false;
[email protected]05a79d42013-03-28 07:30:092116 addresses->clear();
2117
[email protected]cb507622012-03-23 16:17:062118 // HOSTS lookups are case-insensitive.
[email protected]cb1f4ac2014-08-07 16:55:422119 std::string hostname = base::StringToLowerASCII(key.hostname);
[email protected]cb507622012-03-23 16:17:062120
[email protected]05a79d42013-03-28 07:30:092121 const DnsHosts& hosts = dns_client_->GetConfig()->hosts;
2122
[email protected]78eac2a2012-03-14 19:09:272123 // If |address_family| is ADDRESS_FAMILY_UNSPECIFIED other implementations
2124 // (glibc and c-ares) return the first matching line. We have more
2125 // flexibility, but lose implicit ordering.
[email protected]05a79d42013-03-28 07:30:092126 // We prefer IPv6 because "happy eyeballs" will fall back to IPv4 if
2127 // necessary.
2128 if (key.address_family == ADDRESS_FAMILY_IPV6 ||
2129 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
2130 DnsHosts::const_iterator it = hosts.find(
2131 DnsHostsKey(hostname, ADDRESS_FAMILY_IPV6));
2132 if (it != hosts.end())
2133 addresses->push_back(IPEndPoint(it->second, info.port()));
[email protected]78eac2a2012-03-14 19:09:272134 }
2135
[email protected]05a79d42013-03-28 07:30:092136 if (key.address_family == ADDRESS_FAMILY_IPV4 ||
2137 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
2138 DnsHosts::const_iterator it = hosts.find(
2139 DnsHostsKey(hostname, ADDRESS_FAMILY_IPV4));
2140 if (it != hosts.end())
2141 addresses->push_back(IPEndPoint(it->second, info.port()));
2142 }
2143
[email protected]ec666ab22013-04-17 20:05:592144 // If got only loopback addresses and the family was restricted, resolve
2145 // again, without restrictions. See SystemHostResolverCall for rationale.
2146 if ((key.host_resolver_flags &
2147 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6) &&
2148 IsAllIPv4Loopback(*addresses)) {
2149 Key new_key(key);
2150 new_key.address_family = ADDRESS_FAMILY_UNSPECIFIED;
2151 new_key.host_resolver_flags &=
2152 ~HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
2153 return ServeFromHosts(new_key, info, addresses);
2154 }
[email protected]05a79d42013-03-28 07:30:092155 return !addresses->empty();
[email protected]78eac2a2012-03-14 19:09:272156}
2157
estarkd1bc206e2015-06-20 00:44:392158bool HostResolverImpl::ServeLocalhost(const Key& key,
2159 const RequestInfo& info,
2160 AddressList* addresses) {
2161 AddressList resolved_addresses;
2162 if (!ResolveLocalHostname(key.hostname, info.port(), &resolved_addresses))
2163 return false;
2164
2165 addresses->clear();
2166
2167 for (const auto& address : resolved_addresses) {
2168 // Include the address if:
2169 // - caller didn't specify an address family, or
2170 // - caller specifically asked for the address family of this address, or
2171 // - this is an IPv6 address and caller specifically asked for IPv4 due
2172 // to lack of detected IPv6 support. (See SystemHostResolverCall for
2173 // rationale).
2174 if (key.address_family == ADDRESS_FAMILY_UNSPECIFIED ||
2175 key.address_family == address.GetFamily() ||
2176 (address.GetFamily() == ADDRESS_FAMILY_IPV6 &&
2177 key.address_family == ADDRESS_FAMILY_IPV4 &&
2178 (key.host_resolver_flags &
2179 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6))) {
2180 addresses->push_back(address);
2181 }
2182 }
2183
2184 return true;
2185}
2186
[email protected]16ee26d2012-03-08 03:34:352187void HostResolverImpl::CacheResult(const Key& key,
[email protected]1339a2a22012-10-17 08:39:432188 const HostCache::Entry& entry,
[email protected]16ee26d2012-03-08 03:34:352189 base::TimeDelta ttl) {
2190 if (cache_.get())
[email protected]1339a2a22012-10-17 08:39:432191 cache_->Set(key, entry, base::TimeTicks::Now(), ttl);
[email protected]ef4c40c2010-09-01 14:42:032192}
2193
[email protected]0f292de02012-02-01 22:28:202194void HostResolverImpl::RemoveJob(Job* job) {
2195 DCHECK(job);
[email protected]16ee26d2012-03-08 03:34:352196 JobMap::iterator it = jobs_.find(job->key());
2197 if (it != jobs_.end() && it->second == job)
2198 jobs_.erase(it);
[email protected]b59ff372009-07-15 22:04:322199}
2200
[email protected]9936a7862012-10-26 04:44:022201void HostResolverImpl::SetHaveOnlyLoopbackAddresses(bool result) {
2202 if (result) {
2203 additional_resolver_flags_ |= HOST_RESOLVER_LOOPBACK_ONLY;
2204 } else {
2205 additional_resolver_flags_ &= ~HOST_RESOLVER_LOOPBACK_ONLY;
2206 }
2207}
2208
[email protected]137af622010-02-05 02:14:352209HostResolverImpl::Key HostResolverImpl::GetEffectiveKeyForRequest(
pauljensen19eb73422015-04-15 23:20:062210 const RequestInfo& info,
2211 const IPAddressNumber* ip_number,
sergeyub8cdc212015-05-14 18:50:372212 const BoundNetLog& net_log) {
[email protected]eaf3a3b2010-09-03 20:34:272213 HostResolverFlags effective_flags =
2214 info.host_resolver_flags() | additional_resolver_flags_;
[email protected]137af622010-02-05 02:14:352215 AddressFamily effective_address_family = info.address_family();
[email protected]9db6f702013-04-10 18:10:512216
2217 if (info.address_family() == ADDRESS_FAMILY_UNSPECIFIED) {
cbentzel1906f872015-06-05 16:25:252218 if (!use_local_ipv6_ &&
pauljensen19eb73422015-04-15 23:20:062219 // When resolving IPv4 literals, there's no need to probe for IPv6.
2220 // When resolving IPv6 literals, there's no benefit to artificially
2221 // limiting our resolution based on a probe. Prior logic ensures
2222 // that this query is UNSPECIFIED (see info.address_family()
cbentzel1906f872015-06-05 16:25:252223 // check above) so the code requesting the resolution should be amenable
2224 // to receiving a IPv6 resolution.
pauljensen19eb73422015-04-15 23:20:062225 ip_number == nullptr) {
sergeyub8cdc212015-05-14 18:50:372226 if (!IsIPv6Reachable(net_log)) {
[email protected]ac0b52e2013-04-21 01:26:162227 effective_address_family = ADDRESS_FAMILY_IPV4;
2228 effective_flags |= HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
2229 }
[email protected]9db6f702013-04-10 18:10:512230 }
2231 }
2232
estarkd1bc206e2015-06-20 00:44:392233 return Key(info.hostname(), effective_address_family, effective_flags);
[email protected]137af622010-02-05 02:14:352234}
2235
sergeyub8cdc212015-05-14 18:50:372236bool HostResolverImpl::IsIPv6Reachable(const BoundNetLog& net_log) {
2237 base::TimeTicks now = base::TimeTicks::Now();
2238 bool cached = true;
2239 if ((now - last_ipv6_probe_time_).InMilliseconds() > kIPv6ProbePeriodMs) {
2240 IPAddressNumber address(kIPv6ProbeAddress,
2241 kIPv6ProbeAddress + arraysize(kIPv6ProbeAddress));
2242 last_ipv6_probe_result_ = IsGloballyReachable(address, net_log);
2243 last_ipv6_probe_time_ = now;
2244 cached = false;
2245 }
2246 net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_IPV6_REACHABILITY_CHECK,
2247 base::Bind(&NetLogIPv6AvailableCallback,
2248 last_ipv6_probe_result_, cached));
2249 return last_ipv6_probe_result_;
2250}
2251
[email protected]35ddc282010-09-21 23:42:062252void HostResolverImpl::AbortAllInProgressJobs() {
[email protected]b3601bc22012-02-21 21:23:202253 // In Abort, a Request callback could spawn new Jobs with matching keys, so
2254 // first collect and remove all running jobs from |jobs_|.
[email protected]c143d892012-04-06 07:56:542255 ScopedVector<Job> jobs_to_abort;
[email protected]0f292de02012-02-01 22:28:202256 for (JobMap::iterator it = jobs_.begin(); it != jobs_.end(); ) {
2257 Job* job = it->second;
[email protected]0f292de02012-02-01 22:28:202258 if (job->is_running()) {
[email protected]b3601bc22012-02-21 21:23:202259 jobs_to_abort.push_back(job);
2260 jobs_.erase(it++);
[email protected]0f292de02012-02-01 22:28:202261 } else {
[email protected]b3601bc22012-02-21 21:23:202262 DCHECK(job->is_queued());
2263 ++it;
[email protected]0f292de02012-02-01 22:28:202264 }
[email protected]ef4c40c2010-09-01 14:42:032265 }
[email protected]b3601bc22012-02-21 21:23:202266
[email protected]daae1322013-09-05 18:26:502267 // Pause the dispatcher so it won't start any new dispatcher jobs while
2268 // aborting the old ones. This is needed so that it won't start the second
2269 // DnsTransaction for a job in |jobs_to_abort| if the DnsConfig just became
2270 // invalid.
[email protected]106ccd2c2014-06-17 09:21:002271 PrioritizedDispatcher::Limits limits = dispatcher_->GetLimits();
2272 dispatcher_->SetLimits(
[email protected]daae1322013-09-05 18:26:502273 PrioritizedDispatcher::Limits(limits.reserved_slots.size(), 0));
[email protected]70c04ab2013-08-22 16:05:122274
[email protected]57a48d32012-03-03 00:04:552275 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072276 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]57a48d32012-03-03 00:04:552277
[email protected]16ee26d2012-03-08 03:34:352278 // Then Abort them.
[email protected]11fbca0b2013-06-02 23:37:212279 for (size_t i = 0; self.get() && i < jobs_to_abort.size(); ++i) {
[email protected]57a48d32012-03-03 00:04:552280 jobs_to_abort[i]->Abort();
[email protected]c143d892012-04-06 07:56:542281 jobs_to_abort[i] = NULL;
[email protected]b3601bc22012-02-21 21:23:202282 }
[email protected]daae1322013-09-05 18:26:502283
2284 if (self)
[email protected]106ccd2c2014-06-17 09:21:002285 dispatcher_->SetLimits(limits);
[email protected]daae1322013-09-05 18:26:502286}
2287
2288void HostResolverImpl::AbortDnsTasks() {
2289 // Pause the dispatcher so it won't start any new dispatcher jobs while
2290 // aborting the old ones. This is needed so that it won't start the second
2291 // DnsTransaction for a job if the DnsConfig just changed.
[email protected]106ccd2c2014-06-17 09:21:002292 PrioritizedDispatcher::Limits limits = dispatcher_->GetLimits();
2293 dispatcher_->SetLimits(
[email protected]daae1322013-09-05 18:26:502294 PrioritizedDispatcher::Limits(limits.reserved_slots.size(), 0));
2295
2296 for (JobMap::iterator it = jobs_.begin(); it != jobs_.end(); ++it)
2297 it->second->AbortDnsTask();
[email protected]106ccd2c2014-06-17 09:21:002298 dispatcher_->SetLimits(limits);
[email protected]ef4c40c2010-09-01 14:42:032299}
2300
[email protected]78eac2a2012-03-14 19:09:272301void HostResolverImpl::TryServingAllJobsFromHosts() {
2302 if (!HaveDnsConfig())
2303 return;
2304
2305 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2306 // http://crbug.com/117655
2307
2308 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072309 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]78eac2a2012-03-14 19:09:272310
[email protected]11fbca0b2013-06-02 23:37:212311 for (JobMap::iterator it = jobs_.begin(); self.get() && it != jobs_.end();) {
[email protected]78eac2a2012-03-14 19:09:272312 Job* job = it->second;
2313 ++it;
2314 // This could remove |job| from |jobs_|, but iterator will remain valid.
2315 job->ServeFromHosts();
2316 }
2317}
2318
[email protected]be1a48b2011-01-20 00:12:132319void HostResolverImpl::OnIPAddressChanged() {
[email protected]62e86ba2013-01-29 18:59:162320 resolved_known_ipv6_hostname_ = false;
sergeyub8cdc212015-05-14 18:50:372321 last_ipv6_probe_time_ = base::TimeTicks();
[email protected]12faa4c2012-11-06 04:44:182322 // Abandon all ProbeJobs.
2323 probe_weak_ptr_factory_.InvalidateWeakPtrs();
[email protected]be1a48b2011-01-20 00:12:132324 if (cache_.get())
2325 cache_->clear();
[email protected]7c466e92013-07-20 01:44:482326#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
[email protected]12faa4c2012-11-06 04:44:182327 new LoopbackProbeJob(probe_weak_ptr_factory_.GetWeakPtr());
[email protected]be1a48b2011-01-20 00:12:132328#endif
2329 AbortAllInProgressJobs();
2330 // |this| may be deleted inside AbortAllInProgressJobs().
2331}
2332
pauljensen101ed372015-04-17 00:11:422333void HostResolverImpl::OnInitialDNSConfigRead() {
2334 UpdateDNSConfig(false);
2335}
2336
[email protected]bb0e34542012-08-31 19:52:402337void HostResolverImpl::OnDNSChanged() {
pauljensen101ed372015-04-17 00:11:422338 UpdateDNSConfig(true);
2339}
2340
2341void HostResolverImpl::UpdateDNSConfig(bool config_changed) {
[email protected]bb0e34542012-08-31 19:52:402342 DnsConfig dns_config;
2343 NetworkChangeNotifier::GetDnsConfig(&dns_config);
[email protected]ec666ab22013-04-17 20:05:592344
[email protected]b4481b222012-03-16 17:13:112345 if (net_log_) {
2346 net_log_->AddGlobalEntry(
2347 NetLog::TYPE_DNS_CONFIG_CHANGED,
[email protected]cd565142012-06-12 16:21:452348 base::Bind(&NetLogDnsConfigCallback, &dns_config));
[email protected]b4481b222012-03-16 17:13:112349 }
2350
[email protected]01b3b9d2012-08-13 16:18:142351 // TODO(szym): Remove once http://crbug.com/137914 is resolved.
[email protected]d7b9a2b2012-05-31 22:31:192352 received_dns_config_ = dns_config.IsValid();
[email protected]c9fa8f312013-09-17 12:24:522353 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
2354 use_local_ipv6_ = !dns_config.IsValid() || dns_config.use_local_ipv6;
[email protected]78eac2a2012-03-14 19:09:272355
[email protected]a8883e452012-11-17 05:58:062356 num_dns_failures_ = 0;
2357
[email protected]01b3b9d2012-08-13 16:18:142358 // We want a new DnsSession in place, before we Abort running Jobs, so that
2359 // the newly started jobs use the new config.
[email protected]f0f602bd2012-11-15 18:01:022360 if (dns_client_.get()) {
[email protected]d7b9a2b2012-05-31 22:31:192361 dns_client_->SetConfig(dns_config);
pauljensen101ed372015-04-17 00:11:422362 if (dns_client_->GetConfig()) {
[email protected]f0f602bd2012-11-15 18:01:022363 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
pauljensen101ed372015-04-17 00:11:422364 // If we just switched DnsClients, restart jobs using new resolver.
2365 // TODO(pauljensen): Is this necessary?
2366 config_changed = true;
2367 }
[email protected]f0f602bd2012-11-15 18:01:022368 }
[email protected]01b3b9d2012-08-13 16:18:142369
pauljensen101ed372015-04-17 00:11:422370 if (config_changed) {
2371 // If the DNS server has changed, existing cached info could be wrong so we
2372 // have to drop our internal cache :( Note that OS level DNS caches, such
2373 // as NSCD's cache should be dropped automatically by the OS when
2374 // resolv.conf changes so we don't need to do anything to clear that cache.
2375 if (cache_.get())
2376 cache_->clear();
[email protected]01b3b9d2012-08-13 16:18:142377
pauljensen101ed372015-04-17 00:11:422378 // Life check to bail once |this| is deleted.
2379 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]f0f602bd2012-11-15 18:01:022380
pauljensen101ed372015-04-17 00:11:422381 // Existing jobs will have been sent to the original server so they need to
2382 // be aborted.
2383 AbortAllInProgressJobs();
[email protected]01b3b9d2012-08-13 16:18:142384
pauljensen101ed372015-04-17 00:11:422385 // |this| may be deleted inside AbortAllInProgressJobs().
2386 if (self.get())
2387 TryServingAllJobsFromHosts();
2388 }
[email protected]78eac2a2012-03-14 19:09:272389}
2390
2391bool HostResolverImpl::HaveDnsConfig() const {
[email protected]32b1dbcf2013-01-26 03:48:252392 // Use DnsClient only if it's fully configured and there is no override by
2393 // ScopedDefaultHostResolverProc.
2394 // The alternative is to use NetworkChangeNotifier to override DnsConfig,
2395 // but that would introduce construction order requirements for NCN and SDHRP.
[email protected]90499482013-06-01 00:39:502396 return (dns_client_.get() != NULL) && (dns_client_->GetConfig() != NULL) &&
2397 !(proc_params_.resolver_proc.get() == NULL &&
[email protected]32b1dbcf2013-01-26 03:48:252398 HostResolverProc::GetDefault() != NULL);
[email protected]b3601bc22012-02-21 21:23:202399}
2400
[email protected]1ffdda82012-12-12 23:04:222401void HostResolverImpl::OnDnsTaskResolve(int net_error) {
[email protected]f0f602bd2012-11-15 18:01:022402 DCHECK(dns_client_);
[email protected]1ffdda82012-12-12 23:04:222403 if (net_error == OK) {
[email protected]f0f602bd2012-11-15 18:01:022404 num_dns_failures_ = 0;
2405 return;
2406 }
2407 ++num_dns_failures_;
2408 if (num_dns_failures_ < kMaximumDnsFailures)
2409 return;
[email protected]daae1322013-09-05 18:26:502410
2411 // Disable DnsClient until the next DNS change. Must be done before aborting
2412 // DnsTasks, since doing so may start new jobs.
[email protected]f0f602bd2012-11-15 18:01:022413 dns_client_->SetConfig(DnsConfig());
[email protected]daae1322013-09-05 18:26:502414
2415 // Switch jobs with active DnsTasks over to using ProcTasks.
2416 AbortDnsTasks();
2417
[email protected]f0f602bd2012-11-15 18:01:022418 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", false);
davidbenad6fc442015-05-18 20:59:132419 UMA_HISTOGRAM_SPARSE_SLOWLY("AsyncDNS.DnsClientDisabledReason",
2420 std::abs(net_error));
[email protected]f0f602bd2012-11-15 18:01:022421}
2422
[email protected]a8883e452012-11-17 05:58:062423void HostResolverImpl::SetDnsClient(scoped_ptr<DnsClient> dns_client) {
[email protected]daae1322013-09-05 18:26:502424 // DnsClient and config must be updated before aborting DnsTasks, since doing
2425 // so may start new jobs.
[email protected]a8883e452012-11-17 05:58:062426 dns_client_ = dns_client.Pass();
[email protected]daae1322013-09-05 18:26:502427 if (dns_client_ && !dns_client_->GetConfig() &&
2428 num_dns_failures_ < kMaximumDnsFailures) {
2429 DnsConfig dns_config;
2430 NetworkChangeNotifier::GetDnsConfig(&dns_config);
2431 dns_client_->SetConfig(dns_config);
2432 num_dns_failures_ = 0;
2433 if (dns_client_->GetConfig())
2434 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
[email protected]a8883e452012-11-17 05:58:062435 }
[email protected]daae1322013-09-05 18:26:502436
2437 AbortDnsTasks();
[email protected]a8883e452012-11-17 05:58:062438}
2439
[email protected]b59ff372009-07-15 22:04:322440} // namespace net