blob: 3a04df12f751c6d288f678c5dd6b671e44878321 [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]7ccb7072013-06-10 20:56:2824#include "base/message_loop/message_loop_proxy.h"
[email protected]1e9bbd22010-10-15 16:42:4525#include "base/metrics/field_trial.h"
davidbenad6fc442015-05-18 20:59:1326#include "base/metrics/histogram_macros.h"
27#include "base/metrics/sparse_histogram.h"
eromane1867242015-04-23 23:07:4428#include "base/profiler/scoped_tracker.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"
[email protected]ac9ba8fe2010-12-30 18:08:3632#include "base/threading/worker_pool.h"
[email protected]66e96c42013-06-28 15:20:3133#include "base/time/time.h"
[email protected]21526002010-05-16 19:42:4634#include "base/values.h"
[email protected]b3601bc22012-02-21 21:23:2035#include "net/base/address_family.h"
[email protected]b59ff372009-07-15 22:04:3236#include "net/base/address_list.h"
[email protected]46018c9d2011-09-06 03:42:3437#include "net/base/dns_reloader.h"
[email protected]e806cd72013-05-17 02:08:4338#include "net/base/dns_util.h"
[email protected]ee094b82010-08-24 15:55:5139#include "net/base/host_port_pair.h"
[email protected]1c7cf3f82014-08-07 21:33:4840#include "net/base/ip_endpoint.h"
[email protected]2bb04442010-08-18 18:01:1541#include "net/base/net_errors.h"
[email protected]0f8f1b432010-03-16 19:06:0342#include "net/base/net_util.h"
[email protected]0adcb2b2012-08-15 21:30:4643#include "net/dns/address_sorter.h"
[email protected]78eac2a2012-03-14 19:09:2744#include "net/dns/dns_client.h"
[email protected]b3601bc22012-02-21 21:23:2045#include "net/dns/dns_config_service.h"
46#include "net/dns/dns_protocol.h"
47#include "net/dns/dns_response.h"
[email protected]b3601bc22012-02-21 21:23:2048#include "net/dns/dns_transaction.h"
[email protected]f2cb3cf2013-03-21 01:40:5349#include "net/dns/host_resolver_proc.h"
eroman87c53d62015-04-02 06:51:0750#include "net/log/net_log.h"
[email protected]9db6f702013-04-10 18:10:5151#include "net/socket/client_socket_factory.h"
52#include "net/udp/datagram_client_socket.h"
pauljensen370f1c72015-02-17 16:59:1453#include "url/url_canon_ip.h"
[email protected]b59ff372009-07-15 22:04:3254
55#if defined(OS_WIN)
56#include "net/base/winsock_init.h"
57#endif
58
59namespace net {
60
[email protected]e95d3aca2010-01-11 22:47:4361namespace {
62
[email protected]6e78dfb2011-07-28 21:34:4763// Limit the size of hostnames that will be resolved to combat issues in
64// some platform's resolvers.
65const size_t kMaxHostLength = 4096;
66
[email protected]a2730882012-01-21 00:56:2767// Default TTL for successful resolutions with ProcTask.
68const unsigned kCacheEntryTTLSeconds = 60;
69
[email protected]b3601bc22012-02-21 21:23:2070// Default TTL for unsuccessful resolutions with ProcTask.
71const unsigned kNegativeCacheEntryTTLSeconds = 0;
72
[email protected]895123222012-10-25 15:21:1773// Minimum TTL for successful resolutions with DnsTask.
74const unsigned kMinimumTTLSeconds = kCacheEntryTTLSeconds;
75
estark5d131a12015-03-26 19:52:1976const char kLocalhost[] = "localhost.";
77
sergeyub8cdc212015-05-14 18:50:3778// Time between IPv6 probes, i.e. for how long results of each IPv6 probe are
79// cached.
80const int kIPv6ProbePeriodMs = 1000;
81
82// Google DNS address used for IPv6 probes.
83const uint8_t kIPv6ProbeAddress[] =
84 { 0x20, 0x01, 0x48, 0x60, 0x48, 0x60, 0x00, 0x00,
85 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x88 };
86
[email protected]24f4bab2010-10-15 01:27:1187// We use a separate histogram name for each platform to facilitate the
88// display of error codes by their symbolic name (since each platform has
89// different mappings).
90const char kOSErrorsForGetAddrinfoHistogramName[] =
91#if defined(OS_WIN)
92 "Net.OSErrorsForGetAddrinfo_Win";
93#elif defined(OS_MACOSX)
94 "Net.OSErrorsForGetAddrinfo_Mac";
95#elif defined(OS_LINUX)
96 "Net.OSErrorsForGetAddrinfo_Linux";
97#else
98 "Net.OSErrorsForGetAddrinfo";
99#endif
100
[email protected]c89b2442011-05-26 14:28:27101// Gets a list of the likely error codes that getaddrinfo() can return
102// (non-exhaustive). These are the error codes that we will track via
103// a histogram.
104std::vector<int> GetAllGetAddrinfoOSErrors() {
105 int os_errors[] = {
106#if defined(OS_POSIX)
[email protected]23f771162011-06-02 18:37:51107#if !defined(OS_FREEBSD)
[email protected]39588992011-07-11 19:54:37108#if !defined(OS_ANDROID)
[email protected]c48aef92011-11-22 23:41:45109 // EAI_ADDRFAMILY has been declared obsolete in Android's and
110 // FreeBSD's netdb.h.
[email protected]c89b2442011-05-26 14:28:27111 EAI_ADDRFAMILY,
[email protected]39588992011-07-11 19:54:37112#endif
[email protected]c48aef92011-11-22 23:41:45113 // EAI_NODATA has been declared obsolete in FreeBSD's netdb.h.
[email protected]23f771162011-06-02 18:37:51114 EAI_NODATA,
115#endif
[email protected]c89b2442011-05-26 14:28:27116 EAI_AGAIN,
117 EAI_BADFLAGS,
118 EAI_FAIL,
119 EAI_FAMILY,
120 EAI_MEMORY,
[email protected]c89b2442011-05-26 14:28:27121 EAI_NONAME,
122 EAI_SERVICE,
123 EAI_SOCKTYPE,
124 EAI_SYSTEM,
125#elif defined(OS_WIN)
126 // See: http://msdn.microsoft.com/en-us/library/ms738520(VS.85).aspx
127 WSA_NOT_ENOUGH_MEMORY,
128 WSAEAFNOSUPPORT,
129 WSAEINVAL,
130 WSAESOCKTNOSUPPORT,
131 WSAHOST_NOT_FOUND,
132 WSANO_DATA,
133 WSANO_RECOVERY,
134 WSANOTINITIALISED,
135 WSATRY_AGAIN,
136 WSATYPE_NOT_FOUND,
137 // The following are not in doc, but might be to appearing in results :-(.
138 WSA_INVALID_HANDLE,
139#endif
140 };
141
142 // Ensure all errors are positive, as histogram only tracks positive values.
143 for (size_t i = 0; i < arraysize(os_errors); ++i) {
144 os_errors[i] = std::abs(os_errors[i]);
145 }
146
147 return base::CustomHistogram::ArrayToCustomRanges(os_errors,
148 arraysize(os_errors));
149}
150
[email protected]1def74c2012-03-22 20:07:00151enum DnsResolveStatus {
152 RESOLVE_STATUS_DNS_SUCCESS = 0,
153 RESOLVE_STATUS_PROC_SUCCESS,
154 RESOLVE_STATUS_FAIL,
[email protected]1d932852012-06-19 19:40:33155 RESOLVE_STATUS_SUSPECT_NETBIOS,
[email protected]1def74c2012-03-22 20:07:00156 RESOLVE_STATUS_MAX
157};
158
eroman91dd3602015-03-26 03:46:33159// ICANN uses this localhost address to indicate a name collision.
160//
161// The policy in Chromium is to fail host resolving if it resolves to
162// this special address.
163//
164// Not however that IP literals are exempt from this policy, so it is still
165// possible to navigate to http://127.0.53.53/ directly.
166//
167// For more details: https://www.icann.org/news/announcement-2-2014-08-01-en
168const unsigned char kIcanNameCollisionIp[] = {127, 0, 53, 53};
169
[email protected]1def74c2012-03-22 20:07:00170void UmaAsyncDnsResolveStatus(DnsResolveStatus result) {
171 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ResolveStatus",
172 result,
173 RESOLVE_STATUS_MAX);
174}
175
[email protected]1d932852012-06-19 19:40:33176bool ResemblesNetBIOSName(const std::string& hostname) {
177 return (hostname.size() < 16) && (hostname.find('.') == std::string::npos);
178}
179
180// True if |hostname| ends with either ".local" or ".local.".
181bool ResemblesMulticastDNSName(const std::string& hostname) {
182 DCHECK(!hostname.empty());
183 const char kSuffix[] = ".local.";
184 const size_t kSuffixLen = sizeof(kSuffix) - 1;
185 const size_t kSuffixLenTrimmed = kSuffixLen - 1;
186 if (hostname[hostname.size() - 1] == '.') {
187 return hostname.size() > kSuffixLen &&
188 !hostname.compare(hostname.size() - kSuffixLen, kSuffixLen, kSuffix);
189 }
190 return hostname.size() > kSuffixLenTrimmed &&
191 !hostname.compare(hostname.size() - kSuffixLenTrimmed, kSuffixLenTrimmed,
192 kSuffix, kSuffixLenTrimmed);
193}
194
[email protected]34e61362013-07-24 20:41:56195// Attempts to connect a UDP socket to |dest|:53.
[email protected]2b74a2f2013-07-23 19:37:38196bool IsGloballyReachable(const IPAddressNumber& dest,
197 const BoundNetLog& net_log) {
eroman0eb394e2015-04-30 23:25:46198 // TODO(eroman): Remove ScopedTracker below once crbug.com/455942 is fixed.
199 tracked_objects::ScopedTracker tracking_profile_1(
eroman2734a9d2015-05-05 19:24:38200 FROM_HERE_WITH_EXPLICIT_FUNCTION("455942 IsGloballyReachable"));
eroman0eb394e2015-04-30 23:25:46201
[email protected]9db6f702013-04-10 18:10:51202 scoped_ptr<DatagramClientSocket> socket(
203 ClientSocketFactory::GetDefaultFactory()->CreateDatagramClientSocket(
204 DatagramSocket::DEFAULT_BIND,
205 RandIntCallback(),
[email protected]2b74a2f2013-07-23 19:37:38206 net_log.net_log(),
207 net_log.source()));
[email protected]34e61362013-07-24 20:41:56208 int rv = socket->Connect(IPEndPoint(dest, 53));
[email protected]e9051722013-04-12 21:58:18209 if (rv != OK)
210 return false;
[email protected]e9051722013-04-12 21:58:18211 IPEndPoint endpoint;
212 rv = socket->GetLocalAddress(&endpoint);
213 if (rv != OK)
214 return false;
[email protected]1c7cf3f82014-08-07 21:33:48215 DCHECK_EQ(ADDRESS_FAMILY_IPV6, endpoint.GetFamily());
[email protected]e9051722013-04-12 21:58:18216 const IPAddressNumber& address = endpoint.address();
217 bool is_link_local = (address[0] == 0xFE) && ((address[1] & 0xC0) == 0x80);
218 if (is_link_local)
219 return false;
220 const uint8 kTeredoPrefix[] = { 0x20, 0x01, 0, 0 };
221 bool is_teredo = std::equal(kTeredoPrefix,
222 kTeredoPrefix + arraysize(kTeredoPrefix),
223 address.begin());
224 if (is_teredo)
225 return false;
226 return true;
[email protected]9db6f702013-04-10 18:10:51227}
228
[email protected]51b9a6b2012-06-25 21:50:29229// Provide a common macro to simplify code and readability. We must use a
230// macro as the underlying HISTOGRAM macro creates static variables.
231#define DNS_HISTOGRAM(name, time) UMA_HISTOGRAM_CUSTOM_TIMES(name, time, \
232 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromHours(1), 100)
233
234// A macro to simplify code and readability.
235#define DNS_HISTOGRAM_BY_PRIORITY(basename, priority, time) \
236 do { \
237 switch (priority) { \
238 case HIGHEST: DNS_HISTOGRAM(basename "_HIGHEST", time); break; \
239 case MEDIUM: DNS_HISTOGRAM(basename "_MEDIUM", time); break; \
240 case LOW: DNS_HISTOGRAM(basename "_LOW", time); break; \
241 case LOWEST: DNS_HISTOGRAM(basename "_LOWEST", time); break; \
242 case IDLE: DNS_HISTOGRAM(basename "_IDLE", time); break; \
243 default: NOTREACHED(); break; \
244 } \
245 DNS_HISTOGRAM(basename, time); \
246 } while (0)
247
248// Record time from Request creation until a valid DNS response.
249void RecordTotalTime(bool had_dns_config,
250 bool speculative,
251 base::TimeDelta duration) {
252 if (had_dns_config) {
253 if (speculative) {
254 DNS_HISTOGRAM("AsyncDNS.TotalTime_speculative", duration);
255 } else {
256 DNS_HISTOGRAM("AsyncDNS.TotalTime", duration);
257 }
258 } else {
259 if (speculative) {
260 DNS_HISTOGRAM("DNS.TotalTime_speculative", duration);
261 } else {
262 DNS_HISTOGRAM("DNS.TotalTime", duration);
263 }
264 }
265}
266
[email protected]1339a2a22012-10-17 08:39:43267void RecordTTL(base::TimeDelta ttl) {
268 UMA_HISTOGRAM_CUSTOM_TIMES("AsyncDNS.TTL", ttl,
269 base::TimeDelta::FromSeconds(1),
270 base::TimeDelta::FromDays(1), 100);
271}
272
[email protected]16c2bd72013-06-28 01:19:22273bool ConfigureAsyncDnsNoFallbackFieldTrial() {
274 const bool kDefault = false;
275
276 // Configure the AsyncDns field trial as follows:
277 // groups AsyncDnsNoFallbackA and AsyncDnsNoFallbackB: return true,
278 // groups AsyncDnsA and AsyncDnsB: return false,
279 // groups SystemDnsA and SystemDnsB: return false,
280 // otherwise (trial absent): return default.
281 std::string group_name = base::FieldTrialList::FindFullName("AsyncDns");
282 if (!group_name.empty())
283 return StartsWithASCII(group_name, "AsyncDnsNoFallback", false);
284 return kDefault;
285}
286
[email protected]d7b9a2b2012-05-31 22:31:19287//-----------------------------------------------------------------------------
288
[email protected]895123222012-10-25 15:21:17289AddressList EnsurePortOnAddressList(const AddressList& list, uint16 port) {
290 if (list.empty() || list.front().port() == port)
291 return list;
292 return AddressList::CopyWithPort(list, port);
[email protected]7054e78f2012-05-07 21:44:56293}
294
[email protected]ec666ab22013-04-17 20:05:59295// Returns true if |addresses| contains only IPv4 loopback addresses.
296bool IsAllIPv4Loopback(const AddressList& addresses) {
297 for (unsigned i = 0; i < addresses.size(); ++i) {
298 const IPAddressNumber& address = addresses[i].address();
299 switch (addresses[i].GetFamily()) {
300 case ADDRESS_FAMILY_IPV4:
301 if (address[0] != 127)
302 return false;
303 break;
304 case ADDRESS_FAMILY_IPV6:
305 return false;
306 default:
307 NOTREACHED();
308 return false;
309 }
310 }
311 return true;
312}
313
[email protected]cd565142012-06-12 16:21:45314// Creates NetLog parameters when the resolve failed.
estade5e5529d2015-05-21 20:59:11315scoped_ptr<base::Value> NetLogProcTaskFailedCallback(
eroman001c3742015-04-23 03:11:17316 uint32 attempt_number,
317 int net_error,
318 int os_error,
319 NetLogCaptureMode /* capture_mode */) {
estade5e5529d2015-05-21 20:59:11320 scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]cd565142012-06-12 16:21:45321 if (attempt_number)
322 dict->SetInteger("attempt_number", attempt_number);
[email protected]21526002010-05-16 19:42:46323
[email protected]cd565142012-06-12 16:21:45324 dict->SetInteger("net_error", net_error);
[email protected]13024882011-05-18 23:19:16325
[email protected]cd565142012-06-12 16:21:45326 if (os_error) {
327 dict->SetInteger("os_error", os_error);
[email protected]21526002010-05-16 19:42:46328#if defined(OS_POSIX)
[email protected]cd565142012-06-12 16:21:45329 dict->SetString("os_error_string", gai_strerror(os_error));
[email protected]21526002010-05-16 19:42:46330#elif defined(OS_WIN)
[email protected]cd565142012-06-12 16:21:45331 // Map the error code to a human-readable string.
332 LPWSTR error_string = NULL;
Peter Kastingbe940e92014-11-20 23:14:08333 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
334 0, // Use the internal message table.
335 os_error,
336 0, // Use default language.
337 (LPWSTR)&error_string,
338 0, // Buffer size.
339 0); // Arguments (unused).
[email protected]ad65a3e2013-12-25 18:18:01340 dict->SetString("os_error_string", base::WideToUTF8(error_string));
[email protected]cd565142012-06-12 16:21:45341 LocalFree(error_string);
[email protected]21526002010-05-16 19:42:46342#endif
[email protected]21526002010-05-16 19:42:46343 }
344
estade5e5529d2015-05-21 20:59:11345 return dict.Pass();
[email protected]cd565142012-06-12 16:21:45346}
[email protected]a9813302012-04-28 09:29:28347
[email protected]cd565142012-06-12 16:21:45348// Creates NetLog parameters when the DnsTask failed.
estade5e5529d2015-05-21 20:59:11349scoped_ptr<base::Value> NetLogDnsTaskFailedCallback(
350 int net_error,
351 int dns_error,
352 NetLogCaptureMode /* capture_mode */) {
353 scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]cd565142012-06-12 16:21:45354 dict->SetInteger("net_error", net_error);
355 if (dns_error)
356 dict->SetInteger("dns_error", dns_error);
estade5e5529d2015-05-21 20:59:11357 return dict.Pass();
[email protected]ee094b82010-08-24 15:55:51358};
359
[email protected]cd565142012-06-12 16:21:45360// Creates NetLog parameters containing the information in a RequestInfo object,
361// along with the associated NetLog::Source.
estade5e5529d2015-05-21 20:59:11362scoped_ptr<base::Value> NetLogRequestInfoCallback(
363 const HostResolver::RequestInfo* info,
364 NetLogCaptureMode /* capture_mode */) {
365 scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
[email protected]b3601bc22012-02-21 21:23:20366
[email protected]cd565142012-06-12 16:21:45367 dict->SetString("host", info->host_port_pair().ToString());
368 dict->SetInteger("address_family",
369 static_cast<int>(info->address_family()));
370 dict->SetBoolean("allow_cached_response", info->allow_cached_response());
371 dict->SetBoolean("is_speculative", info->is_speculative());
estade5e5529d2015-05-21 20:59:11372 return dict.Pass();
[email protected]cd565142012-06-12 16:21:45373}
[email protected]b3601bc22012-02-21 21:23:20374
[email protected]cd565142012-06-12 16:21:45375// Creates NetLog parameters for the creation of a HostResolverImpl::Job.
estade5e5529d2015-05-21 20:59:11376scoped_ptr<base::Value> NetLogJobCreationCallback(
377 const NetLog::Source& source,
378 const std::string* host,
379 NetLogCaptureMode /* capture_mode */) {
380 scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
381 source.AddToEventParameters(dict.get());
[email protected]cd565142012-06-12 16:21:45382 dict->SetString("host", *host);
estade5e5529d2015-05-21 20:59:11383 return dict.Pass();
[email protected]cd565142012-06-12 16:21:45384}
[email protected]a9813302012-04-28 09:29:28385
[email protected]cd565142012-06-12 16:21:45386// Creates NetLog parameters for HOST_RESOLVER_IMPL_JOB_ATTACH/DETACH events.
estade5e5529d2015-05-21 20:59:11387scoped_ptr<base::Value> NetLogJobAttachCallback(
388 const NetLog::Source& source,
389 RequestPriority priority,
390 NetLogCaptureMode /* capture_mode */) {
391 scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
392 source.AddToEventParameters(dict.get());
[email protected]3b04d1f22013-10-16 00:23:56393 dict->SetString("priority", RequestPriorityToString(priority));
estade5e5529d2015-05-21 20:59:11394 return dict.Pass();
[email protected]cd565142012-06-12 16:21:45395}
[email protected]b3601bc22012-02-21 21:23:20396
[email protected]cd565142012-06-12 16:21:45397// Creates NetLog parameters for the DNS_CONFIG_CHANGED event.
estade5e5529d2015-05-21 20:59:11398scoped_ptr<base::Value> NetLogDnsConfigCallback(
399 const DnsConfig* config,
400 NetLogCaptureMode /* capture_mode */) {
401 return make_scoped_ptr(config->ToValue());
[email protected]cd565142012-06-12 16:21:45402}
[email protected]b4481b222012-03-16 17:13:11403
estade5e5529d2015-05-21 20:59:11404scoped_ptr<base::Value> NetLogIPv6AvailableCallback(
405 bool ipv6_available,
406 bool cached,
407 NetLogCaptureMode /* capture_mode */) {
408 scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
sergeyub8cdc212015-05-14 18:50:37409 dict->SetBoolean("ipv6_available", ipv6_available);
410 dict->SetBoolean("cached", cached);
estade5e5529d2015-05-21 20:59:11411 return dict.Pass();
sergeyub8cdc212015-05-14 18:50:37412}
413
[email protected]0f292de02012-02-01 22:28:20414// The logging routines are defined here because some requests are resolved
415// without a Request object.
416
417// Logs when a request has just been started.
418void LogStartRequest(const BoundNetLog& source_net_log,
[email protected]0f292de02012-02-01 22:28:20419 const HostResolver::RequestInfo& info) {
420 source_net_log.BeginEvent(
[email protected]0f292de02012-02-01 22:28:20421 NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST,
xunjieli26f90452014-11-10 16:23:02422 base::Bind(&NetLogRequestInfoCallback, &info));
[email protected]0f292de02012-02-01 22:28:20423}
424
425// Logs when a request has just completed (before its callback is run).
426void LogFinishRequest(const BoundNetLog& source_net_log,
[email protected]0f292de02012-02-01 22:28:20427 const HostResolver::RequestInfo& info,
[email protected]b3601bc22012-02-21 21:23:20428 int net_error) {
xunjieli26f90452014-11-10 16:23:02429 source_net_log.EndEventWithNetErrorCode(
[email protected]b3601bc22012-02-21 21:23:20430 NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST, net_error);
[email protected]0f292de02012-02-01 22:28:20431}
432
433// Logs when a request has been cancelled.
434void LogCancelRequest(const BoundNetLog& source_net_log,
[email protected]0f292de02012-02-01 22:28:20435 const HostResolverImpl::RequestInfo& info) {
xunjieli26f90452014-11-10 16:23:02436 source_net_log.AddEvent(NetLog::TYPE_CANCELLED);
437 source_net_log.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST);
[email protected]0f292de02012-02-01 22:28:20438}
439
[email protected]b59ff372009-07-15 22:04:32440//-----------------------------------------------------------------------------
441
[email protected]0f292de02012-02-01 22:28:20442// Keeps track of the highest priority.
443class PriorityTracker {
444 public:
[email protected]8c98d002012-07-18 19:02:27445 explicit PriorityTracker(RequestPriority initial_priority)
446 : highest_priority_(initial_priority), total_count_(0) {
[email protected]0f292de02012-02-01 22:28:20447 memset(counts_, 0, sizeof(counts_));
448 }
449
450 RequestPriority highest_priority() const {
451 return highest_priority_;
452 }
453
454 size_t total_count() const {
455 return total_count_;
456 }
457
458 void Add(RequestPriority req_priority) {
459 ++total_count_;
460 ++counts_[req_priority];
[email protected]31ae7ab2012-04-24 21:09:05461 if (highest_priority_ < req_priority)
[email protected]0f292de02012-02-01 22:28:20462 highest_priority_ = req_priority;
463 }
464
465 void Remove(RequestPriority req_priority) {
466 DCHECK_GT(total_count_, 0u);
467 DCHECK_GT(counts_[req_priority], 0u);
468 --total_count_;
469 --counts_[req_priority];
470 size_t i;
[email protected]31ae7ab2012-04-24 21:09:05471 for (i = highest_priority_; i > MINIMUM_PRIORITY && !counts_[i]; --i);
[email protected]0f292de02012-02-01 22:28:20472 highest_priority_ = static_cast<RequestPriority>(i);
473
[email protected]31ae7ab2012-04-24 21:09:05474 // In absence of requests, default to MINIMUM_PRIORITY.
475 if (total_count_ == 0)
476 DCHECK_EQ(MINIMUM_PRIORITY, highest_priority_);
[email protected]0f292de02012-02-01 22:28:20477 }
478
479 private:
480 RequestPriority highest_priority_;
481 size_t total_count_;
482 size_t counts_[NUM_PRIORITIES];
483};
484
[email protected]c54a8912012-10-22 22:09:43485} // namespace
[email protected]0f292de02012-02-01 22:28:20486
487//-----------------------------------------------------------------------------
488
[email protected]daae1322013-09-05 18:26:50489const unsigned HostResolverImpl::kMaximumDnsFailures = 16;
490
[email protected]0f292de02012-02-01 22:28:20491// Holds the data for a request that could not be completed synchronously.
492// It is owned by a Job. Canceled Requests are only marked as canceled rather
493// than removed from the Job's |requests_| list.
[email protected]b59ff372009-07-15 22:04:32494class HostResolverImpl::Request {
495 public:
[email protected]ee094b82010-08-24 15:55:51496 Request(const BoundNetLog& source_net_log,
[email protected]54e13772009-08-14 03:01:09497 const RequestInfo& info,
[email protected]5109c1952013-08-20 18:44:10498 RequestPriority priority,
[email protected]aa22b242011-11-16 18:58:29499 const CompletionCallback& callback,
[email protected]b59ff372009-07-15 22:04:32500 AddressList* addresses)
[email protected]ee094b82010-08-24 15:55:51501 : source_net_log_(source_net_log),
[email protected]54e13772009-08-14 03:01:09502 info_(info),
[email protected]5109c1952013-08-20 18:44:10503 priority_(priority),
[email protected]54e13772009-08-14 03:01:09504 job_(NULL),
505 callback_(callback),
[email protected]51b9a6b2012-06-25 21:50:29506 addresses_(addresses),
[email protected]5109c1952013-08-20 18:44:10507 request_time_(base::TimeTicks::Now()) {}
[email protected]b59ff372009-07-15 22:04:32508
[email protected]0f292de02012-02-01 22:28:20509 // Mark the request as canceled.
510 void MarkAsCanceled() {
[email protected]b59ff372009-07-15 22:04:32511 job_ = NULL;
[email protected]b59ff372009-07-15 22:04:32512 addresses_ = NULL;
[email protected]aa22b242011-11-16 18:58:29513 callback_.Reset();
[email protected]b59ff372009-07-15 22:04:32514 }
515
[email protected]0f292de02012-02-01 22:28:20516 bool was_canceled() const {
[email protected]aa22b242011-11-16 18:58:29517 return callback_.is_null();
[email protected]b59ff372009-07-15 22:04:32518 }
519
520 void set_job(Job* job) {
[email protected]0f292de02012-02-01 22:28:20521 DCHECK(job);
[email protected]b59ff372009-07-15 22:04:32522 // Identify which job the request is waiting on.
523 job_ = job;
524 }
525
[email protected]0f292de02012-02-01 22:28:20526 // Prepare final AddressList and call completion callback.
[email protected]b3601bc22012-02-21 21:23:20527 void OnComplete(int error, const AddressList& addr_list) {
[email protected]51b9a6b2012-06-25 21:50:29528 DCHECK(!was_canceled());
[email protected]895123222012-10-25 15:21:17529 if (error == OK)
530 *addresses_ = EnsurePortOnAddressList(addr_list, info_.port());
[email protected]aa22b242011-11-16 18:58:29531 CompletionCallback callback = callback_;
[email protected]0f292de02012-02-01 22:28:20532 MarkAsCanceled();
[email protected]aa22b242011-11-16 18:58:29533 callback.Run(error);
[email protected]b59ff372009-07-15 22:04:32534 }
535
[email protected]b59ff372009-07-15 22:04:32536 Job* job() const {
537 return job_;
538 }
539
[email protected]0f292de02012-02-01 22:28:20540 // NetLog for the source, passed in HostResolver::Resolve.
[email protected]ee094b82010-08-24 15:55:51541 const BoundNetLog& source_net_log() {
542 return source_net_log_;
543 }
544
[email protected]b59ff372009-07-15 22:04:32545 const RequestInfo& info() const {
546 return info_;
547 }
548
[email protected]5109c1952013-08-20 18:44:10549 RequestPriority priority() const { return priority_; }
550
551 base::TimeTicks request_time() const { return request_time_; }
[email protected]51b9a6b2012-06-25 21:50:29552
[email protected]b59ff372009-07-15 22:04:32553 private:
xunjieli26f90452014-11-10 16:23:02554 const BoundNetLog source_net_log_;
[email protected]54e13772009-08-14 03:01:09555
[email protected]b59ff372009-07-15 22:04:32556 // The request info that started the request.
[email protected]5109c1952013-08-20 18:44:10557 const RequestInfo info_;
558
559 // TODO(akalin): Support reprioritization.
560 const RequestPriority priority_;
[email protected]b59ff372009-07-15 22:04:32561
[email protected]0f292de02012-02-01 22:28:20562 // The resolve job that this request is dependent on.
[email protected]b59ff372009-07-15 22:04:32563 Job* job_;
564
565 // The user's callback to invoke when the request completes.
[email protected]aa22b242011-11-16 18:58:29566 CompletionCallback callback_;
[email protected]b59ff372009-07-15 22:04:32567
568 // The address list to save result into.
569 AddressList* addresses_;
570
[email protected]51b9a6b2012-06-25 21:50:29571 const base::TimeTicks request_time_;
572
[email protected]b59ff372009-07-15 22:04:32573 DISALLOW_COPY_AND_ASSIGN(Request);
574};
575
[email protected]1e9bbd22010-10-15 16:42:45576//------------------------------------------------------------------------------
577
[email protected]0f292de02012-02-01 22:28:20578// Calls HostResolverProc on the WorkerPool. Performs retries if necessary.
579//
580// Whenever we try to resolve the host, we post a delayed task to check if host
581// resolution (OnLookupComplete) is completed or not. If the original attempt
582// hasn't completed, then we start another attempt for host resolution. We take
583// the results from the first attempt that finishes and ignore the results from
584// all other attempts.
585//
586// TODO(szym): Move to separate source file for testing and mocking.
587//
588class HostResolverImpl::ProcTask
589 : public base::RefCountedThreadSafe<HostResolverImpl::ProcTask> {
[email protected]b59ff372009-07-15 22:04:32590 public:
[email protected]b3601bc22012-02-21 21:23:20591 typedef base::Callback<void(int net_error,
592 const AddressList& addr_list)> Callback;
[email protected]b59ff372009-07-15 22:04:32593
[email protected]0f292de02012-02-01 22:28:20594 ProcTask(const Key& key,
595 const ProcTaskParams& params,
596 const Callback& callback,
597 const BoundNetLog& job_net_log)
598 : key_(key),
599 params_(params),
600 callback_(callback),
601 origin_loop_(base::MessageLoopProxy::current()),
602 attempt_number_(0),
603 completed_attempt_number_(0),
604 completed_attempt_error_(ERR_UNEXPECTED),
605 had_non_speculative_request_(false),
[email protected]b3601bc22012-02-21 21:23:20606 net_log_(job_net_log) {
[email protected]90499482013-06-01 00:39:50607 if (!params_.resolver_proc.get())
[email protected]0f292de02012-02-01 22:28:20608 params_.resolver_proc = HostResolverProc::GetDefault();
609 // If default is unset, use the system proc.
[email protected]90499482013-06-01 00:39:50610 if (!params_.resolver_proc.get())
[email protected]1ee9afa12013-04-16 14:18:06611 params_.resolver_proc = new SystemHostResolverProc();
[email protected]b59ff372009-07-15 22:04:32612 }
613
[email protected]b59ff372009-07-15 22:04:32614 void Start() {
[email protected]3e9d9cc2011-05-03 21:08:15615 DCHECK(origin_loop_->BelongsToCurrentThread());
[email protected]4da911f2012-06-14 19:45:20616 net_log_.BeginEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK);
[email protected]189163e2011-05-11 01:48:54617 StartLookupAttempt();
618 }
[email protected]252b699b2010-02-05 21:38:06619
[email protected]0f292de02012-02-01 22:28:20620 // Cancels this ProcTask. It will be orphaned. Any outstanding resolve
621 // attempts running on worker threads will continue running. Only once all the
622 // attempts complete will the final reference to this ProcTask be released.
623 void Cancel() {
624 DCHECK(origin_loop_->BelongsToCurrentThread());
625
[email protected]0adcb2b2012-08-15 21:30:46626 if (was_canceled() || was_completed())
[email protected]0f292de02012-02-01 22:28:20627 return;
628
[email protected]0f292de02012-02-01 22:28:20629 callback_.Reset();
[email protected]4da911f2012-06-14 19:45:20630 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK);
[email protected]0f292de02012-02-01 22:28:20631 }
632
633 void set_had_non_speculative_request() {
634 DCHECK(origin_loop_->BelongsToCurrentThread());
635 had_non_speculative_request_ = true;
636 }
637
638 bool was_canceled() const {
639 DCHECK(origin_loop_->BelongsToCurrentThread());
640 return callback_.is_null();
641 }
642
643 bool was_completed() const {
644 DCHECK(origin_loop_->BelongsToCurrentThread());
645 return completed_attempt_number_ > 0;
646 }
647
648 private:
[email protected]a9813302012-04-28 09:29:28649 friend class base::RefCountedThreadSafe<ProcTask>;
650 ~ProcTask() {}
651
[email protected]189163e2011-05-11 01:48:54652 void StartLookupAttempt() {
653 DCHECK(origin_loop_->BelongsToCurrentThread());
654 base::TimeTicks start_time = base::TimeTicks::Now();
655 ++attempt_number_;
656 // Dispatch the lookup attempt to a worker thread.
657 if (!base::WorkerPool::PostTask(
658 FROM_HERE,
[email protected]0f292de02012-02-01 22:28:20659 base::Bind(&ProcTask::DoLookup, this, start_time, attempt_number_),
[email protected]189163e2011-05-11 01:48:54660 true)) {
[email protected]b59ff372009-07-15 22:04:32661 NOTREACHED();
662
663 // Since we could be running within Resolve() right now, we can't just
664 // call OnLookupComplete(). Instead we must wait until Resolve() has
665 // returned (IO_PENDING).
[email protected]3e9d9cc2011-05-03 21:08:15666 origin_loop_->PostTask(
[email protected]189163e2011-05-11 01:48:54667 FROM_HERE,
[email protected]0f292de02012-02-01 22:28:20668 base::Bind(&ProcTask::OnLookupComplete, this, AddressList(),
[email protected]33152acc2011-10-20 23:37:12669 start_time, attempt_number_, ERR_UNEXPECTED, 0));
[email protected]189163e2011-05-11 01:48:54670 return;
[email protected]b59ff372009-07-15 22:04:32671 }
[email protected]13024882011-05-18 23:19:16672
673 net_log_.AddEvent(
674 NetLog::TYPE_HOST_RESOLVER_IMPL_ATTEMPT_STARTED,
[email protected]cd565142012-06-12 16:21:45675 NetLog::IntegerCallback("attempt_number", attempt_number_));
[email protected]13024882011-05-18 23:19:16676
[email protected]0f292de02012-02-01 22:28:20677 // If we don't get the results within a given time, RetryIfNotComplete
678 // will start a new attempt on a different worker thread if none of our
679 // outstanding attempts have completed yet.
680 if (attempt_number_ <= params_.max_retry_attempts) {
[email protected]06ef6d92011-05-19 04:24:58681 origin_loop_->PostDelayedTask(
682 FROM_HERE,
[email protected]0f292de02012-02-01 22:28:20683 base::Bind(&ProcTask::RetryIfNotComplete, this),
[email protected]7e560102012-03-08 20:58:42684 params_.unresponsive_delay);
[email protected]06ef6d92011-05-19 04:24:58685 }
[email protected]b59ff372009-07-15 22:04:32686 }
687
[email protected]6c710ee2010-05-07 07:51:16688 // WARNING: This code runs inside a worker pool. The shutdown code cannot
689 // wait for it to finish, so we must be very careful here about using other
690 // objects (like MessageLoops, Singletons, etc). During shutdown these objects
[email protected]189163e2011-05-11 01:48:54691 // may no longer exist. Multiple DoLookups() could be running in parallel, so
692 // any state inside of |this| must not mutate .
693 void DoLookup(const base::TimeTicks& start_time,
694 const uint32 attempt_number) {
695 AddressList results;
696 int os_error = 0;
[email protected]b59ff372009-07-15 22:04:32697 // Running on the worker thread
[email protected]0f292de02012-02-01 22:28:20698 int error = params_.resolver_proc->Resolve(key_.hostname,
699 key_.address_family,
700 key_.host_resolver_flags,
701 &results,
702 &os_error);
[email protected]b59ff372009-07-15 22:04:32703
eroman91dd3602015-03-26 03:46:33704 // Fail the resolution if the result contains 127.0.53.53. See the comment
705 // block of kIcanNameCollisionIp for details on why.
706 for (const auto& it : results) {
707 const IPAddressNumber& cur = it.address();
708 if (cur.size() == arraysize(kIcanNameCollisionIp) &&
709 0 == memcmp(&cur.front(), kIcanNameCollisionIp, cur.size())) {
710 error = ERR_ICANN_NAME_COLLISION;
711 break;
712 }
713 }
714
[email protected]189163e2011-05-11 01:48:54715 origin_loop_->PostTask(
716 FROM_HERE,
[email protected]0f292de02012-02-01 22:28:20717 base::Bind(&ProcTask::OnLookupComplete, this, results, start_time,
[email protected]33152acc2011-10-20 23:37:12718 attempt_number, error, os_error));
[email protected]189163e2011-05-11 01:48:54719 }
720
[email protected]0f292de02012-02-01 22:28:20721 // Makes next attempt if DoLookup() has not finished (runs on origin thread).
722 void RetryIfNotComplete() {
[email protected]189163e2011-05-11 01:48:54723 DCHECK(origin_loop_->BelongsToCurrentThread());
724
[email protected]0f292de02012-02-01 22:28:20725 if (was_completed() || was_canceled())
[email protected]189163e2011-05-11 01:48:54726 return;
727
[email protected]0f292de02012-02-01 22:28:20728 params_.unresponsive_delay *= params_.retry_factor;
[email protected]189163e2011-05-11 01:48:54729 StartLookupAttempt();
[email protected]b59ff372009-07-15 22:04:32730 }
731
732 // Callback for when DoLookup() completes (runs on origin thread).
[email protected]189163e2011-05-11 01:48:54733 void OnLookupComplete(const AddressList& results,
734 const base::TimeTicks& start_time,
735 const uint32 attempt_number,
736 int error,
737 const int os_error) {
[email protected]3e9d9cc2011-05-03 21:08:15738 DCHECK(origin_loop_->BelongsToCurrentThread());
[email protected]49b70b222013-05-07 21:24:23739 // If results are empty, we should return an error.
740 bool empty_list_on_ok = (error == OK && results.empty());
741 UMA_HISTOGRAM_BOOLEAN("DNS.EmptyAddressListAndNoError", empty_list_on_ok);
742 if (empty_list_on_ok)
743 error = ERR_NAME_NOT_RESOLVED;
[email protected]189163e2011-05-11 01:48:54744
745 bool was_retry_attempt = attempt_number > 1;
746
[email protected]2d3b7762010-10-09 00:35:47747 // Ideally the following code would be part of host_resolver_proc.cc,
[email protected]b3601bc22012-02-21 21:23:20748 // however it isn't safe to call NetworkChangeNotifier from worker threads.
749 // So we do it here on the IO thread instead.
[email protected]189163e2011-05-11 01:48:54750 if (error != OK && NetworkChangeNotifier::IsOffline())
751 error = ERR_INTERNET_DISCONNECTED;
[email protected]2d3b7762010-10-09 00:35:47752
[email protected]b3601bc22012-02-21 21:23:20753 // If this is the first attempt that is finishing later, then record data
754 // for the first attempt. Won't contaminate with retry attempt's data.
[email protected]189163e2011-05-11 01:48:54755 if (!was_retry_attempt)
756 RecordPerformanceHistograms(start_time, error, os_error);
757
758 RecordAttemptHistograms(start_time, attempt_number, error, os_error);
[email protected]f2d8c4212010-02-02 00:56:35759
[email protected]0f292de02012-02-01 22:28:20760 if (was_canceled())
[email protected]b59ff372009-07-15 22:04:32761 return;
762
[email protected]cd565142012-06-12 16:21:45763 NetLog::ParametersCallback net_log_callback;
[email protected]0f292de02012-02-01 22:28:20764 if (error != OK) {
[email protected]cd565142012-06-12 16:21:45765 net_log_callback = base::Bind(&NetLogProcTaskFailedCallback,
766 attempt_number,
767 error,
768 os_error);
[email protected]0f292de02012-02-01 22:28:20769 } else {
[email protected]cd565142012-06-12 16:21:45770 net_log_callback = NetLog::IntegerCallback("attempt_number",
771 attempt_number);
[email protected]0f292de02012-02-01 22:28:20772 }
[email protected]cd565142012-06-12 16:21:45773 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_ATTEMPT_FINISHED,
774 net_log_callback);
[email protected]0f292de02012-02-01 22:28:20775
776 if (was_completed())
777 return;
778
779 // Copy the results from the first worker thread that resolves the host.
780 results_ = results;
781 completed_attempt_number_ = attempt_number;
782 completed_attempt_error_ = error;
783
[email protected]e87b8b512011-06-14 22:12:52784 if (was_retry_attempt) {
785 // If retry attempt finishes before 1st attempt, then get stats on how
786 // much time is saved by having spawned an extra attempt.
787 retry_attempt_finished_time_ = base::TimeTicks::Now();
788 }
789
[email protected]189163e2011-05-11 01:48:54790 if (error != OK) {
[email protected]cd565142012-06-12 16:21:45791 net_log_callback = base::Bind(&NetLogProcTaskFailedCallback,
792 0, error, os_error);
[email protected]ee094b82010-08-24 15:55:51793 } else {
[email protected]cd565142012-06-12 16:21:45794 net_log_callback = results_.CreateNetLogCallback();
[email protected]ee094b82010-08-24 15:55:51795 }
[email protected]cd565142012-06-12 16:21:45796 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK,
797 net_log_callback);
[email protected]ee094b82010-08-24 15:55:51798
[email protected]b3601bc22012-02-21 21:23:20799 callback_.Run(error, results_);
[email protected]b59ff372009-07-15 22:04:32800 }
801
[email protected]189163e2011-05-11 01:48:54802 void RecordPerformanceHistograms(const base::TimeTicks& start_time,
803 const int error,
804 const int os_error) const {
[email protected]3e9d9cc2011-05-03 21:08:15805 DCHECK(origin_loop_->BelongsToCurrentThread());
asvitkinec0fb8022014-08-26 04:39:35806 enum Category { // Used in UMA_HISTOGRAM_ENUMERATION.
[email protected]1e9bbd22010-10-15 16:42:45807 RESOLVE_SUCCESS,
808 RESOLVE_FAIL,
809 RESOLVE_SPECULATIVE_SUCCESS,
810 RESOLVE_SPECULATIVE_FAIL,
811 RESOLVE_MAX, // Bounding value.
812 };
813 int category = RESOLVE_MAX; // Illegal value for later DCHECK only.
814
[email protected]189163e2011-05-11 01:48:54815 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
816 if (error == OK) {
[email protected]1e9bbd22010-10-15 16:42:45817 if (had_non_speculative_request_) {
818 category = RESOLVE_SUCCESS;
819 DNS_HISTOGRAM("DNS.ResolveSuccess", duration);
820 } else {
821 category = RESOLVE_SPECULATIVE_SUCCESS;
822 DNS_HISTOGRAM("DNS.ResolveSpeculativeSuccess", duration);
823 }
[email protected]7e96d792011-06-10 17:08:23824
[email protected]78eac2a2012-03-14 19:09:27825 // Log DNS lookups based on |address_family|. This will help us determine
[email protected]7e96d792011-06-10 17:08:23826 // if IPv4 or IPv4/6 lookups are faster or slower.
827 switch(key_.address_family) {
828 case ADDRESS_FAMILY_IPV4:
829 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_IPV4", duration);
830 break;
831 case ADDRESS_FAMILY_IPV6:
832 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_IPV6", duration);
833 break;
834 case ADDRESS_FAMILY_UNSPECIFIED:
835 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_UNSPEC", duration);
836 break;
837 }
[email protected]1e9bbd22010-10-15 16:42:45838 } else {
839 if (had_non_speculative_request_) {
840 category = RESOLVE_FAIL;
841 DNS_HISTOGRAM("DNS.ResolveFail", duration);
842 } else {
843 category = RESOLVE_SPECULATIVE_FAIL;
844 DNS_HISTOGRAM("DNS.ResolveSpeculativeFail", duration);
845 }
[email protected]78eac2a2012-03-14 19:09:27846 // Log DNS lookups based on |address_family|. This will help us determine
[email protected]7e96d792011-06-10 17:08:23847 // if IPv4 or IPv4/6 lookups are faster or slower.
848 switch(key_.address_family) {
849 case ADDRESS_FAMILY_IPV4:
850 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_IPV4", duration);
851 break;
852 case ADDRESS_FAMILY_IPV6:
853 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_IPV6", duration);
854 break;
855 case ADDRESS_FAMILY_UNSPECIFIED:
856 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_UNSPEC", duration);
857 break;
858 }
[email protected]c833e322010-10-16 23:51:36859 UMA_HISTOGRAM_CUSTOM_ENUMERATION(kOSErrorsForGetAddrinfoHistogramName,
[email protected]189163e2011-05-11 01:48:54860 std::abs(os_error),
[email protected]1e9bbd22010-10-15 16:42:45861 GetAllGetAddrinfoOSErrors());
862 }
[email protected]051b6ab2010-10-18 16:50:46863 DCHECK_LT(category, static_cast<int>(RESOLVE_MAX)); // Be sure it was set.
[email protected]1e9bbd22010-10-15 16:42:45864
865 UMA_HISTOGRAM_ENUMERATION("DNS.ResolveCategory", category, RESOLVE_MAX);
[email protected]1e9bbd22010-10-15 16:42:45866 }
867
[email protected]189163e2011-05-11 01:48:54868 void RecordAttemptHistograms(const base::TimeTicks& start_time,
869 const uint32 attempt_number,
870 const int error,
871 const int os_error) const {
[email protected]0f292de02012-02-01 22:28:20872 DCHECK(origin_loop_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54873 bool first_attempt_to_complete =
874 completed_attempt_number_ == attempt_number;
[email protected]e87b8b512011-06-14 22:12:52875 bool is_first_attempt = (attempt_number == 1);
[email protected]1e9bbd22010-10-15 16:42:45876
[email protected]189163e2011-05-11 01:48:54877 if (first_attempt_to_complete) {
878 // If this was first attempt to complete, then record the resolution
879 // status of the attempt.
880 if (completed_attempt_error_ == OK) {
881 UMA_HISTOGRAM_ENUMERATION(
882 "DNS.AttemptFirstSuccess", attempt_number, 100);
883 } else {
884 UMA_HISTOGRAM_ENUMERATION(
885 "DNS.AttemptFirstFailure", attempt_number, 100);
886 }
887 }
888
889 if (error == OK)
890 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptSuccess", attempt_number, 100);
891 else
892 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptFailure", attempt_number, 100);
893
[email protected]e87b8b512011-06-14 22:12:52894 // If first attempt didn't finish before retry attempt, then calculate stats
895 // on how much time is saved by having spawned an extra attempt.
[email protected]0f292de02012-02-01 22:28:20896 if (!first_attempt_to_complete && is_first_attempt && !was_canceled()) {
[email protected]e87b8b512011-06-14 22:12:52897 DNS_HISTOGRAM("DNS.AttemptTimeSavedByRetry",
898 base::TimeTicks::Now() - retry_attempt_finished_time_);
899 }
900
[email protected]0f292de02012-02-01 22:28:20901 if (was_canceled() || !first_attempt_to_complete) {
[email protected]189163e2011-05-11 01:48:54902 // Count those attempts which completed after the job was already canceled
903 // OR after the job was already completed by an earlier attempt (so in
904 // effect).
905 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptDiscarded", attempt_number, 100);
906
[email protected]0f292de02012-02-01 22:28:20907 // Record if job is canceled.
908 if (was_canceled())
[email protected]189163e2011-05-11 01:48:54909 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptCancelled", attempt_number, 100);
910 }
911
912 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
913 if (error == OK)
914 DNS_HISTOGRAM("DNS.AttemptSuccessDuration", duration);
915 else
916 DNS_HISTOGRAM("DNS.AttemptFailDuration", duration);
917 }
[email protected]1e9bbd22010-10-15 16:42:45918
[email protected]b59ff372009-07-15 22:04:32919 // Set on the origin thread, read on the worker thread.
[email protected]123ab1e32009-10-21 19:12:57920 Key key_;
[email protected]b59ff372009-07-15 22:04:32921
[email protected]0f292de02012-02-01 22:28:20922 // Holds an owning reference to the HostResolverProc that we are going to use.
[email protected]b59ff372009-07-15 22:04:32923 // This may not be the current resolver procedure by the time we call
924 // ResolveAddrInfo, but that's OK... we'll use it anyways, and the owning
925 // reference ensures that it remains valid until we are done.
[email protected]0f292de02012-02-01 22:28:20926 ProcTaskParams params_;
[email protected]b59ff372009-07-15 22:04:32927
[email protected]0f292de02012-02-01 22:28:20928 // The listener to the results of this ProcTask.
929 Callback callback_;
930
931 // Used to post ourselves onto the origin thread.
932 scoped_refptr<base::MessageLoopProxy> origin_loop_;
[email protected]189163e2011-05-11 01:48:54933
934 // Keeps track of the number of attempts we have made so far to resolve the
935 // host. Whenever we start an attempt to resolve the host, we increase this
936 // number.
937 uint32 attempt_number_;
938
939 // The index of the attempt which finished first (or 0 if the job is still in
940 // progress).
941 uint32 completed_attempt_number_;
942
943 // The result (a net error code) from the first attempt to complete.
944 int completed_attempt_error_;
[email protected]252b699b2010-02-05 21:38:06945
[email protected]e87b8b512011-06-14 22:12:52946 // The time when retry attempt was finished.
947 base::TimeTicks retry_attempt_finished_time_;
948
[email protected]252b699b2010-02-05 21:38:06949 // True if a non-speculative request was ever attached to this job
[email protected]0f292de02012-02-01 22:28:20950 // (regardless of whether or not it was later canceled.
[email protected]252b699b2010-02-05 21:38:06951 // This boolean is used for histogramming the duration of jobs used to
952 // service non-speculative requests.
953 bool had_non_speculative_request_;
954
[email protected]b59ff372009-07-15 22:04:32955 AddressList results_;
956
[email protected]ee094b82010-08-24 15:55:51957 BoundNetLog net_log_;
958
[email protected]0f292de02012-02-01 22:28:20959 DISALLOW_COPY_AND_ASSIGN(ProcTask);
[email protected]b59ff372009-07-15 22:04:32960};
961
962//-----------------------------------------------------------------------------
963
[email protected]12faa4c2012-11-06 04:44:18964// Wraps a call to HaveOnlyLoopbackAddresses to be executed on the WorkerPool as
965// it takes 40-100ms and should not block initialization.
966class HostResolverImpl::LoopbackProbeJob {
967 public:
968 explicit LoopbackProbeJob(const base::WeakPtr<HostResolverImpl>& resolver)
969 : resolver_(resolver),
970 result_(false) {
[email protected]11fbca0b2013-06-02 23:37:21971 DCHECK(resolver.get());
[email protected]12faa4c2012-11-06 04:44:18972 const bool kIsSlow = true;
973 base::WorkerPool::PostTaskAndReply(
974 FROM_HERE,
975 base::Bind(&LoopbackProbeJob::DoProbe, base::Unretained(this)),
976 base::Bind(&LoopbackProbeJob::OnProbeComplete, base::Owned(this)),
977 kIsSlow);
978 }
979
980 virtual ~LoopbackProbeJob() {}
981
982 private:
983 // Runs on worker thread.
984 void DoProbe() {
985 result_ = HaveOnlyLoopbackAddresses();
986 }
987
988 void OnProbeComplete() {
[email protected]11fbca0b2013-06-02 23:37:21989 if (!resolver_.get())
[email protected]12faa4c2012-11-06 04:44:18990 return;
991 resolver_->SetHaveOnlyLoopbackAddresses(result_);
992 }
993
994 // Used/set only on origin thread.
995 base::WeakPtr<HostResolverImpl> resolver_;
996
997 bool result_;
998
999 DISALLOW_COPY_AND_ASSIGN(LoopbackProbeJob);
1000};
1001
[email protected]0f8f1b432010-03-16 19:06:031002//-----------------------------------------------------------------------------
1003
[email protected]b3601bc22012-02-21 21:23:201004// Resolves the hostname using DnsTransaction.
1005// TODO(szym): This could be moved to separate source file as well.
[email protected]0adcb2b2012-08-15 21:30:461006class HostResolverImpl::DnsTask : public base::SupportsWeakPtr<DnsTask> {
[email protected]b3601bc22012-02-21 21:23:201007 public:
[email protected]daae1322013-09-05 18:26:501008 class Delegate {
1009 public:
1010 virtual void OnDnsTaskComplete(base::TimeTicks start_time,
1011 int net_error,
1012 const AddressList& addr_list,
1013 base::TimeDelta ttl) = 0;
1014
1015 // Called when the first of two jobs succeeds. If the first completed
1016 // transaction fails, this is not called. Also not called when the DnsTask
1017 // only needs to run one transaction.
1018 virtual void OnFirstDnsTransactionComplete() = 0;
1019
1020 protected:
1021 Delegate() {}
1022 virtual ~Delegate() {}
1023 };
[email protected]b3601bc22012-02-21 21:23:201024
[email protected]0adcb2b2012-08-15 21:30:461025 DnsTask(DnsClient* client,
[email protected]b3601bc22012-02-21 21:23:201026 const Key& key,
[email protected]daae1322013-09-05 18:26:501027 Delegate* delegate,
[email protected]b3601bc22012-02-21 21:23:201028 const BoundNetLog& job_net_log)
[email protected]0adcb2b2012-08-15 21:30:461029 : client_(client),
[email protected]daae1322013-09-05 18:26:501030 key_(key),
1031 delegate_(delegate),
1032 net_log_(job_net_log),
1033 num_completed_transactions_(0),
1034 task_start_time_(base::TimeTicks::Now()) {
[email protected]0adcb2b2012-08-15 21:30:461035 DCHECK(client);
[email protected]daae1322013-09-05 18:26:501036 DCHECK(delegate_);
[email protected]1affed62013-08-21 03:24:501037 }
1038
[email protected]daae1322013-09-05 18:26:501039 bool needs_two_transactions() const {
1040 return key_.address_family == ADDRESS_FAMILY_UNSPECIFIED;
1041 }
1042
1043 bool needs_another_transaction() const {
1044 return needs_two_transactions() && !transaction_aaaa_;
1045 }
1046
1047 void StartFirstTransaction() {
1048 DCHECK_EQ(0u, num_completed_transactions_);
[email protected]70c04ab2013-08-22 16:05:121049 net_log_.BeginEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK);
[email protected]daae1322013-09-05 18:26:501050 if (key_.address_family == ADDRESS_FAMILY_IPV6) {
1051 StartAAAA();
1052 } else {
1053 StartA();
1054 }
1055 }
1056
1057 void StartSecondTransaction() {
1058 DCHECK(needs_two_transactions());
1059 StartAAAA();
[email protected]70c04ab2013-08-22 16:05:121060 }
1061
1062 private:
[email protected]daae1322013-09-05 18:26:501063 void StartA() {
1064 DCHECK(!transaction_a_);
1065 DCHECK_NE(ADDRESS_FAMILY_IPV6, key_.address_family);
1066 transaction_a_ = CreateTransaction(ADDRESS_FAMILY_IPV4);
1067 transaction_a_->Start();
1068 }
1069
1070 void StartAAAA() {
1071 DCHECK(!transaction_aaaa_);
1072 DCHECK_NE(ADDRESS_FAMILY_IPV4, key_.address_family);
1073 transaction_aaaa_ = CreateTransaction(ADDRESS_FAMILY_IPV6);
1074 transaction_aaaa_->Start();
1075 }
1076
1077 scoped_ptr<DnsTransaction> CreateTransaction(AddressFamily family) {
1078 DCHECK_NE(ADDRESS_FAMILY_UNSPECIFIED, family);
1079 return client_->GetTransactionFactory()->CreateTransaction(
1080 key_.hostname,
1081 family == ADDRESS_FAMILY_IPV6 ? dns_protocol::kTypeAAAA :
1082 dns_protocol::kTypeA,
1083 base::Bind(&DnsTask::OnTransactionComplete, base::Unretained(this),
1084 base::TimeTicks::Now()),
1085 net_log_);
1086 }
1087
1088 void OnTransactionComplete(const base::TimeTicks& start_time,
[email protected]1def74c2012-03-22 20:07:001089 DnsTransaction* transaction,
[email protected]b3601bc22012-02-21 21:23:201090 int net_error,
1091 const DnsResponse* response) {
[email protected]add76532012-03-30 14:47:471092 DCHECK(transaction);
[email protected]02cd6982013-01-10 20:12:511093 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]0adcb2b2012-08-15 21:30:461094 if (net_error != OK) {
[email protected]02cd6982013-01-10 20:12:511095 DNS_HISTOGRAM("AsyncDNS.TransactionFailure", duration);
[email protected]0adcb2b2012-08-15 21:30:461096 OnFailure(net_error, DnsResponse::DNS_PARSE_OK);
1097 return;
[email protected]6c411902012-08-14 22:36:361098 }
[email protected]0adcb2b2012-08-15 21:30:461099
[email protected]02cd6982013-01-10 20:12:511100 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess", duration);
1101 switch (transaction->GetType()) {
1102 case dns_protocol::kTypeA:
1103 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess_A", duration);
1104 break;
1105 case dns_protocol::kTypeAAAA:
1106 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess_AAAA", duration);
1107 break;
1108 }
[email protected]daae1322013-09-05 18:26:501109
[email protected]0adcb2b2012-08-15 21:30:461110 AddressList addr_list;
1111 base::TimeDelta ttl;
1112 DnsResponse::Result result = response->ParseToAddressList(&addr_list, &ttl);
1113 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ParseToAddressList",
1114 result,
1115 DnsResponse::DNS_PARSE_RESULT_MAX);
1116 if (result != DnsResponse::DNS_PARSE_OK) {
1117 // Fail even if the other query succeeds.
1118 OnFailure(ERR_DNS_MALFORMED_RESPONSE, result);
1119 return;
1120 }
1121
[email protected]daae1322013-09-05 18:26:501122 ++num_completed_transactions_;
1123 if (num_completed_transactions_ == 1) {
1124 ttl_ = ttl;
[email protected]0adcb2b2012-08-15 21:30:461125 } else {
[email protected]daae1322013-09-05 18:26:501126 ttl_ = std::min(ttl_, ttl);
[email protected]0adcb2b2012-08-15 21:30:461127 }
1128
[email protected]daae1322013-09-05 18:26:501129 if (transaction->GetType() == dns_protocol::kTypeA) {
1130 DCHECK_EQ(transaction_a_.get(), transaction);
1131 // Place IPv4 addresses after IPv6.
1132 addr_list_.insert(addr_list_.end(), addr_list.begin(), addr_list.end());
1133 } else {
1134 DCHECK_EQ(transaction_aaaa_.get(), transaction);
1135 // Place IPv6 addresses before IPv4.
1136 addr_list_.insert(addr_list_.begin(), addr_list.begin(), addr_list.end());
1137 }
1138
1139 if (needs_two_transactions() && num_completed_transactions_ == 1) {
1140 // No need to repeat the suffix search.
1141 key_.hostname = transaction->GetHostname();
1142 delegate_->OnFirstDnsTransactionComplete();
1143 return;
1144 }
1145
1146 if (addr_list_.empty()) {
[email protected]70c04ab2013-08-22 16:05:121147 // TODO(szym): Don't fallback to ProcTask in this case.
1148 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
[email protected]0adcb2b2012-08-15 21:30:461149 return;
1150 }
1151
[email protected]daae1322013-09-05 18:26:501152 // If there are multiple addresses, and at least one is IPv6, need to sort
1153 // them. Note that IPv6 addresses are always put before IPv4 ones, so it's
1154 // sufficient to just check the family of the first address.
1155 if (addr_list_.size() > 1 &&
1156 addr_list_[0].GetFamily() == ADDRESS_FAMILY_IPV6) {
1157 // Sort addresses if needed. Sort could complete synchronously.
[email protected]0adcb2b2012-08-15 21:30:461158 client_->GetAddressSorter()->Sort(
[email protected]daae1322013-09-05 18:26:501159 addr_list_,
[email protected]4589a3a2012-09-20 20:57:071160 base::Bind(&DnsTask::OnSortComplete,
1161 AsWeakPtr(),
[email protected]daae1322013-09-05 18:26:501162 base::TimeTicks::Now()));
[email protected]0adcb2b2012-08-15 21:30:461163 } else {
[email protected]daae1322013-09-05 18:26:501164 OnSuccess(addr_list_);
[email protected]0adcb2b2012-08-15 21:30:461165 }
1166 }
1167
1168 void OnSortComplete(base::TimeTicks start_time,
[email protected]0adcb2b2012-08-15 21:30:461169 bool success,
1170 const AddressList& addr_list) {
1171 if (!success) {
1172 DNS_HISTOGRAM("AsyncDNS.SortFailure",
1173 base::TimeTicks::Now() - start_time);
1174 OnFailure(ERR_DNS_SORT_ERROR, DnsResponse::DNS_PARSE_OK);
1175 return;
1176 }
1177
1178 DNS_HISTOGRAM("AsyncDNS.SortSuccess",
1179 base::TimeTicks::Now() - start_time);
1180
1181 // AddressSorter prunes unusable destinations.
1182 if (addr_list.empty()) {
1183 LOG(WARNING) << "Address list empty after RFC3484 sort";
1184 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
1185 return;
1186 }
1187
[email protected]daae1322013-09-05 18:26:501188 OnSuccess(addr_list);
[email protected]0adcb2b2012-08-15 21:30:461189 }
1190
1191 void OnFailure(int net_error, DnsResponse::Result result) {
1192 DCHECK_NE(OK, net_error);
[email protected]cd565142012-06-12 16:21:451193 net_log_.EndEvent(
1194 NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK,
1195 base::Bind(&NetLogDnsTaskFailedCallback, net_error, result));
[email protected]daae1322013-09-05 18:26:501196 delegate_->OnDnsTaskComplete(task_start_time_, net_error, AddressList(),
1197 base::TimeDelta());
[email protected]b3601bc22012-02-21 21:23:201198 }
1199
[email protected]daae1322013-09-05 18:26:501200 void OnSuccess(const AddressList& addr_list) {
[email protected]0adcb2b2012-08-15 21:30:461201 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK,
1202 addr_list.CreateNetLogCallback());
[email protected]daae1322013-09-05 18:26:501203 delegate_->OnDnsTaskComplete(task_start_time_, OK, addr_list, ttl_);
[email protected]0adcb2b2012-08-15 21:30:461204 }
1205
1206 DnsClient* client_;
[email protected]daae1322013-09-05 18:26:501207 Key key_;
1208
[email protected]b3601bc22012-02-21 21:23:201209 // The listener to the results of this DnsTask.
[email protected]daae1322013-09-05 18:26:501210 Delegate* delegate_;
[email protected]b3601bc22012-02-21 21:23:201211 const BoundNetLog net_log_;
1212
[email protected]daae1322013-09-05 18:26:501213 scoped_ptr<DnsTransaction> transaction_a_;
1214 scoped_ptr<DnsTransaction> transaction_aaaa_;
[email protected]0adcb2b2012-08-15 21:30:461215
[email protected]daae1322013-09-05 18:26:501216 unsigned num_completed_transactions_;
1217
1218 // These are updated as each transaction completes.
1219 base::TimeDelta ttl_;
1220 // IPv6 addresses must appear first in the list.
1221 AddressList addr_list_;
1222
1223 base::TimeTicks task_start_time_;
[email protected]0adcb2b2012-08-15 21:30:461224
1225 DISALLOW_COPY_AND_ASSIGN(DnsTask);
[email protected]b3601bc22012-02-21 21:23:201226};
1227
1228//-----------------------------------------------------------------------------
1229
[email protected]0f292de02012-02-01 22:28:201230// Aggregates all Requests for the same Key. Dispatched via PriorityDispatch.
[email protected]daae1322013-09-05 18:26:501231class HostResolverImpl::Job : public PrioritizedDispatcher::Job,
1232 public HostResolverImpl::DnsTask::Delegate {
[email protected]68ad3ee2010-01-30 03:45:391233 public:
[email protected]0f292de02012-02-01 22:28:201234 // Creates new job for |key| where |request_net_log| is bound to the
[email protected]16ee26d2012-03-08 03:34:351235 // request that spawned it.
[email protected]12faa4c2012-11-06 04:44:181236 Job(const base::WeakPtr<HostResolverImpl>& resolver,
[email protected]0f292de02012-02-01 22:28:201237 const Key& key,
[email protected]8c98d002012-07-18 19:02:271238 RequestPriority priority,
xunjieli26f90452014-11-10 16:23:021239 const BoundNetLog& source_net_log)
[email protected]12faa4c2012-11-06 04:44:181240 : resolver_(resolver),
[email protected]0f292de02012-02-01 22:28:201241 key_(key),
[email protected]8c98d002012-07-18 19:02:271242 priority_tracker_(priority),
[email protected]0f292de02012-02-01 22:28:201243 had_non_speculative_request_(false),
[email protected]51b9a6b2012-06-25 21:50:291244 had_dns_config_(false),
[email protected]daae1322013-09-05 18:26:501245 num_occupied_job_slots_(0),
[email protected]1d932852012-06-19 19:40:331246 dns_task_error_(OK),
[email protected]51b9a6b2012-06-25 21:50:291247 creation_time_(base::TimeTicks::Now()),
1248 priority_change_time_(creation_time_),
xunjieli26f90452014-11-10 16:23:021249 net_log_(BoundNetLog::Make(source_net_log.net_log(),
[email protected]b3601bc22012-02-21 21:23:201250 NetLog::SOURCE_HOST_RESOLVER_IMPL_JOB)) {
xunjieli26f90452014-11-10 16:23:021251 source_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_CREATE_JOB);
[email protected]0f292de02012-02-01 22:28:201252
1253 net_log_.BeginEvent(
1254 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
[email protected]cd565142012-06-12 16:21:451255 base::Bind(&NetLogJobCreationCallback,
xunjieli26f90452014-11-10 16:23:021256 source_net_log.source(),
[email protected]cd565142012-06-12 16:21:451257 &key_.hostname));
[email protected]68ad3ee2010-01-30 03:45:391258 }
1259
dchengb03027d2014-10-21 12:00:201260 ~Job() override {
[email protected]b3601bc22012-02-21 21:23:201261 if (is_running()) {
1262 // |resolver_| was destroyed with this Job still in flight.
1263 // Clean-up, record in the log, but don't run any callbacks.
1264 if (is_proc_running()) {
[email protected]0f292de02012-02-01 22:28:201265 proc_task_->Cancel();
1266 proc_task_ = NULL;
[email protected]0f292de02012-02-01 22:28:201267 }
[email protected]16ee26d2012-03-08 03:34:351268 // Clean up now for nice NetLog.
[email protected]daae1322013-09-05 18:26:501269 KillDnsTask();
[email protected]b3601bc22012-02-21 21:23:201270 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
1271 ERR_ABORTED);
1272 } else if (is_queued()) {
[email protected]57a48d32012-03-03 00:04:551273 // |resolver_| was destroyed without running this Job.
[email protected]16ee26d2012-03-08 03:34:351274 // TODO(szym): is there any benefit in having this distinction?
[email protected]4da911f2012-06-14 19:45:201275 net_log_.AddEvent(NetLog::TYPE_CANCELLED);
1276 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB);
[email protected]68ad3ee2010-01-30 03:45:391277 }
[email protected]b3601bc22012-02-21 21:23:201278 // else CompleteRequests logged EndEvent.
[email protected]68ad3ee2010-01-30 03:45:391279
[email protected]b3601bc22012-02-21 21:23:201280 // Log any remaining Requests as cancelled.
1281 for (RequestsList::const_iterator it = requests_.begin();
1282 it != requests_.end(); ++it) {
1283 Request* req = *it;
1284 if (req->was_canceled())
1285 continue;
1286 DCHECK_EQ(this, req->job());
xunjieli26f90452014-11-10 16:23:021287 LogCancelRequest(req->source_net_log(), req->info());
[email protected]b3601bc22012-02-21 21:23:201288 }
[email protected]68ad3ee2010-01-30 03:45:391289 }
1290
[email protected]daae1322013-09-05 18:26:501291 // Add this job to the dispatcher. If "at_head" is true, adds at the front
1292 // of the queue.
1293 void Schedule(bool at_head) {
1294 DCHECK(!is_queued());
1295 PrioritizedDispatcher::Handle handle;
1296 if (!at_head) {
[email protected]106ccd2c2014-06-17 09:21:001297 handle = resolver_->dispatcher_->Add(this, priority());
[email protected]daae1322013-09-05 18:26:501298 } else {
[email protected]106ccd2c2014-06-17 09:21:001299 handle = resolver_->dispatcher_->AddAtHead(this, priority());
[email protected]daae1322013-09-05 18:26:501300 }
1301 // The dispatcher could have started |this| in the above call to Add, which
1302 // could have called Schedule again. In that case |handle| will be null,
1303 // but |handle_| may have been set by the other nested call to Schedule.
1304 if (!handle.is_null()) {
1305 DCHECK(handle_.is_null());
1306 handle_ = handle;
1307 }
[email protected]16ee26d2012-03-08 03:34:351308 }
1309
[email protected]b3601bc22012-02-21 21:23:201310 void AddRequest(scoped_ptr<Request> req) {
estark5d131a12015-03-26 19:52:191311 // .localhost queries are redirected to "localhost." to make sure
1312 // that they are never sent out on the network, per RFC 6761.
1313 if (IsLocalhostTLD(req->info().hostname())) {
1314 DCHECK_EQ(key_.hostname, kLocalhost);
1315 } else {
1316 DCHECK_EQ(key_.hostname, req->info().hostname());
1317 }
[email protected]0f292de02012-02-01 22:28:201318
1319 req->set_job(this);
[email protected]5109c1952013-08-20 18:44:101320 priority_tracker_.Add(req->priority());
[email protected]0f292de02012-02-01 22:28:201321
xunjieli26f90452014-11-10 16:23:021322 req->source_net_log().AddEvent(
[email protected]0f292de02012-02-01 22:28:201323 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_ATTACH,
[email protected]cd565142012-06-12 16:21:451324 net_log_.source().ToEventParametersCallback());
[email protected]0f292de02012-02-01 22:28:201325
1326 net_log_.AddEvent(
1327 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_REQUEST_ATTACH,
[email protected]cd565142012-06-12 16:21:451328 base::Bind(&NetLogJobAttachCallback,
xunjieli26f90452014-11-10 16:23:021329 req->source_net_log().source(),
[email protected]cd565142012-06-12 16:21:451330 priority()));
[email protected]0f292de02012-02-01 22:28:201331
1332 // TODO(szym): Check if this is still needed.
1333 if (!req->info().is_speculative()) {
1334 had_non_speculative_request_ = true;
[email protected]90499482013-06-01 00:39:501335 if (proc_task_.get())
[email protected]0f292de02012-02-01 22:28:201336 proc_task_->set_had_non_speculative_request();
[email protected]68ad3ee2010-01-30 03:45:391337 }
[email protected]b3601bc22012-02-21 21:23:201338
1339 requests_.push_back(req.release());
1340
[email protected]51b9a6b2012-06-25 21:50:291341 UpdatePriority();
[email protected]68ad3ee2010-01-30 03:45:391342 }
1343
[email protected]16ee26d2012-03-08 03:34:351344 // Marks |req| as cancelled. If it was the last active Request, also finishes
[email protected]0adcb2b2012-08-15 21:30:461345 // this Job, marking it as cancelled, and deletes it.
[email protected]0f292de02012-02-01 22:28:201346 void CancelRequest(Request* req) {
1347 DCHECK_EQ(key_.hostname, req->info().hostname());
1348 DCHECK(!req->was_canceled());
[email protected]16ee26d2012-03-08 03:34:351349
[email protected]0f292de02012-02-01 22:28:201350 // Don't remove it from |requests_| just mark it canceled.
1351 req->MarkAsCanceled();
xunjieli26f90452014-11-10 16:23:021352 LogCancelRequest(req->source_net_log(), req->info());
[email protected]16ee26d2012-03-08 03:34:351353
[email protected]5109c1952013-08-20 18:44:101354 priority_tracker_.Remove(req->priority());
1355 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_REQUEST_DETACH,
1356 base::Bind(&NetLogJobAttachCallback,
xunjieli26f90452014-11-10 16:23:021357 req->source_net_log().source(),
[email protected]5109c1952013-08-20 18:44:101358 priority()));
[email protected]b3601bc22012-02-21 21:23:201359
[email protected]16ee26d2012-03-08 03:34:351360 if (num_active_requests() > 0) {
[email protected]51b9a6b2012-06-25 21:50:291361 UpdatePriority();
[email protected]16ee26d2012-03-08 03:34:351362 } else {
1363 // If we were called from a Request's callback within CompleteRequests,
1364 // that Request could not have been cancelled, so num_active_requests()
1365 // could not be 0. Therefore, we are not in CompleteRequests().
[email protected]1339a2a22012-10-17 08:39:431366 CompleteRequestsWithError(OK /* cancelled */);
[email protected]b3601bc22012-02-21 21:23:201367 }
[email protected]68ad3ee2010-01-30 03:45:391368 }
1369
[email protected]7af985a2012-12-14 22:40:421370 // Called from AbortAllInProgressJobs. Completes all requests and destroys
1371 // the job. This currently assumes the abort is due to a network change.
[email protected]0f292de02012-02-01 22:28:201372 void Abort() {
[email protected]0f292de02012-02-01 22:28:201373 DCHECK(is_running());
[email protected]7af985a2012-12-14 22:40:421374 CompleteRequestsWithError(ERR_NETWORK_CHANGED);
[email protected]b3601bc22012-02-21 21:23:201375 }
1376
[email protected]f0f602bd2012-11-15 18:01:021377 // If DnsTask present, abort it and fall back to ProcTask.
1378 void AbortDnsTask() {
1379 if (dns_task_) {
[email protected]daae1322013-09-05 18:26:501380 KillDnsTask();
[email protected]f0f602bd2012-11-15 18:01:021381 dns_task_error_ = OK;
1382 StartProcTask();
1383 }
1384 }
1385
[email protected]16ee26d2012-03-08 03:34:351386 // Called by HostResolverImpl when this job is evicted due to queue overflow.
1387 // Completes all requests and destroys the job.
1388 void OnEvicted() {
1389 DCHECK(!is_running());
1390 DCHECK(is_queued());
1391 handle_.Reset();
1392
[email protected]4da911f2012-06-14 19:45:201393 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_EVICTED);
[email protected]16ee26d2012-03-08 03:34:351394
1395 // This signals to CompleteRequests that this job never ran.
[email protected]1339a2a22012-10-17 08:39:431396 CompleteRequestsWithError(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
[email protected]16ee26d2012-03-08 03:34:351397 }
1398
[email protected]78eac2a2012-03-14 19:09:271399 // Attempts to serve the job from HOSTS. Returns true if succeeded and
1400 // this Job was destroyed.
1401 bool ServeFromHosts() {
1402 DCHECK_GT(num_active_requests(), 0u);
1403 AddressList addr_list;
1404 if (resolver_->ServeFromHosts(key(),
[email protected]3cb676a12012-06-30 15:46:031405 requests_.front()->info(),
[email protected]78eac2a2012-03-14 19:09:271406 &addr_list)) {
1407 // This will destroy the Job.
[email protected]895123222012-10-25 15:21:171408 CompleteRequests(
1409 HostCache::Entry(OK, MakeAddressListForRequest(addr_list)),
1410 base::TimeDelta());
[email protected]78eac2a2012-03-14 19:09:271411 return true;
1412 }
1413 return false;
1414 }
1415
[email protected]b4481b222012-03-16 17:13:111416 const Key key() const {
1417 return key_;
1418 }
1419
1420 bool is_queued() const {
1421 return !handle_.is_null();
1422 }
1423
1424 bool is_running() const {
1425 return is_dns_running() || is_proc_running();
1426 }
1427
[email protected]16ee26d2012-03-08 03:34:351428 private:
[email protected]daae1322013-09-05 18:26:501429 void KillDnsTask() {
1430 if (dns_task_) {
1431 ReduceToOneJobSlot();
1432 dns_task_.reset();
1433 }
1434 }
1435
1436 // Reduce the number of job slots occupied and queued in the dispatcher
1437 // to one. If the second Job slot is queued in the dispatcher, cancels the
1438 // queued job. Otherwise, the second Job has been started by the
1439 // PrioritizedDispatcher, so signals it is complete.
1440 void ReduceToOneJobSlot() {
1441 DCHECK_GE(num_occupied_job_slots_, 1u);
1442 if (is_queued()) {
[email protected]106ccd2c2014-06-17 09:21:001443 resolver_->dispatcher_->Cancel(handle_);
[email protected]daae1322013-09-05 18:26:501444 handle_.Reset();
1445 } else if (num_occupied_job_slots_ > 1) {
[email protected]106ccd2c2014-06-17 09:21:001446 resolver_->dispatcher_->OnJobFinished();
[email protected]daae1322013-09-05 18:26:501447 --num_occupied_job_slots_;
1448 }
1449 DCHECK_EQ(1u, num_occupied_job_slots_);
1450 }
1451
[email protected]51b9a6b2012-06-25 21:50:291452 void UpdatePriority() {
1453 if (is_queued()) {
1454 if (priority() != static_cast<RequestPriority>(handle_.priority()))
1455 priority_change_time_ = base::TimeTicks::Now();
[email protected]106ccd2c2014-06-17 09:21:001456 handle_ = resolver_->dispatcher_->ChangePriority(handle_, priority());
[email protected]51b9a6b2012-06-25 21:50:291457 }
1458 }
1459
[email protected]895123222012-10-25 15:21:171460 AddressList MakeAddressListForRequest(const AddressList& list) const {
1461 if (requests_.empty())
1462 return list;
1463 return AddressList::CopyWithPort(list, requests_.front()->info().port());
1464 }
1465
[email protected]16ee26d2012-03-08 03:34:351466 // PriorityDispatch::Job:
dchengb03027d2014-10-21 12:00:201467 void Start() override {
[email protected]daae1322013-09-05 18:26:501468 DCHECK_LE(num_occupied_job_slots_, 1u);
1469
[email protected]70c04ab2013-08-22 16:05:121470 handle_.Reset();
[email protected]daae1322013-09-05 18:26:501471 ++num_occupied_job_slots_;
1472
1473 if (num_occupied_job_slots_ == 2) {
1474 StartSecondDnsTransaction();
1475 return;
1476 }
1477
1478 DCHECK(!is_running());
[email protected]0f292de02012-02-01 22:28:201479
[email protected]4da911f2012-06-14 19:45:201480 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_STARTED);
[email protected]0f292de02012-02-01 22:28:201481
[email protected]51b9a6b2012-06-25 21:50:291482 had_dns_config_ = resolver_->HaveDnsConfig();
1483
1484 base::TimeTicks now = base::TimeTicks::Now();
1485 base::TimeDelta queue_time = now - creation_time_;
1486 base::TimeDelta queue_time_after_change = now - priority_change_time_;
1487
1488 if (had_dns_config_) {
1489 DNS_HISTOGRAM_BY_PRIORITY("AsyncDNS.JobQueueTime", priority(),
1490 queue_time);
1491 DNS_HISTOGRAM_BY_PRIORITY("AsyncDNS.JobQueueTimeAfterChange", priority(),
1492 queue_time_after_change);
1493 } else {
1494 DNS_HISTOGRAM_BY_PRIORITY("DNS.JobQueueTime", priority(), queue_time);
1495 DNS_HISTOGRAM_BY_PRIORITY("DNS.JobQueueTimeAfterChange", priority(),
1496 queue_time_after_change);
1497 }
1498
[email protected]443714fad2013-09-19 04:52:011499 bool system_only =
1500 (key_.host_resolver_flags & HOST_RESOLVER_SYSTEM_ONLY) != 0;
1501
[email protected]1d932852012-06-19 19:40:331502 // Caution: Job::Start must not complete synchronously.
[email protected]443714fad2013-09-19 04:52:011503 if (!system_only && had_dns_config_ &&
1504 !ResemblesMulticastDNSName(key_.hostname)) {
[email protected]b3601bc22012-02-21 21:23:201505 StartDnsTask();
1506 } else {
1507 StartProcTask();
1508 }
1509 }
1510
[email protected]b3601bc22012-02-21 21:23:201511 // TODO(szym): Since DnsTransaction does not consume threads, we can increase
1512 // the limits on |dispatcher_|. But in order to keep the number of WorkerPool
1513 // threads low, we will need to use an "inner" PrioritizedDispatcher with
1514 // tighter limits.
1515 void StartProcTask() {
[email protected]16ee26d2012-03-08 03:34:351516 DCHECK(!is_dns_running());
[email protected]0f292de02012-02-01 22:28:201517 proc_task_ = new ProcTask(
1518 key_,
1519 resolver_->proc_params_,
[email protected]e3bd4822012-10-23 18:01:371520 base::Bind(&Job::OnProcTaskComplete, base::Unretained(this),
1521 base::TimeTicks::Now()),
[email protected]0f292de02012-02-01 22:28:201522 net_log_);
1523
1524 if (had_non_speculative_request_)
1525 proc_task_->set_had_non_speculative_request();
1526 // Start() could be called from within Resolve(), hence it must NOT directly
1527 // call OnProcTaskComplete, for example, on synchronous failure.
1528 proc_task_->Start();
[email protected]68ad3ee2010-01-30 03:45:391529 }
1530
[email protected]0f292de02012-02-01 22:28:201531 // Called by ProcTask when it completes.
[email protected]e3bd4822012-10-23 18:01:371532 void OnProcTaskComplete(base::TimeTicks start_time,
1533 int net_error,
1534 const AddressList& addr_list) {
[email protected]b3601bc22012-02-21 21:23:201535 DCHECK(is_proc_running());
[email protected]68ad3ee2010-01-30 03:45:391536
[email protected]62e86ba2013-01-29 18:59:161537 if (!resolver_->resolved_known_ipv6_hostname_ &&
1538 net_error == OK &&
1539 key_.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
1540 if (key_.hostname == "www.google.com") {
1541 resolver_->resolved_known_ipv6_hostname_ = true;
1542 bool got_ipv6_address = false;
1543 for (size_t i = 0; i < addr_list.size(); ++i) {
[email protected]5134c22a2013-08-06 18:09:021544 if (addr_list[i].GetFamily() == ADDRESS_FAMILY_IPV6) {
[email protected]62e86ba2013-01-29 18:59:161545 got_ipv6_address = true;
[email protected]5134c22a2013-08-06 18:09:021546 break;
1547 }
[email protected]62e86ba2013-01-29 18:59:161548 }
1549 UMA_HISTOGRAM_BOOLEAN("Net.UnspecResolvedIPv6", got_ipv6_address);
1550 }
1551 }
1552
[email protected]1d932852012-06-19 19:40:331553 if (dns_task_error_ != OK) {
[email protected]e3bd4822012-10-23 18:01:371554 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]1def74c2012-03-22 20:07:001555 if (net_error == OK) {
[email protected]e3bd4822012-10-23 18:01:371556 DNS_HISTOGRAM("AsyncDNS.FallbackSuccess", duration);
[email protected]1d932852012-06-19 19:40:331557 if ((dns_task_error_ == ERR_NAME_NOT_RESOLVED) &&
1558 ResemblesNetBIOSName(key_.hostname)) {
1559 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_SUSPECT_NETBIOS);
1560 } else {
1561 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_PROC_SUCCESS);
1562 }
davidbenad6fc442015-05-18 20:59:131563 UMA_HISTOGRAM_SPARSE_SLOWLY("AsyncDNS.ResolveError",
1564 std::abs(dns_task_error_));
[email protected]1ffdda82012-12-12 23:04:221565 resolver_->OnDnsTaskResolve(dns_task_error_);
[email protected]1def74c2012-03-22 20:07:001566 } else {
[email protected]e3bd4822012-10-23 18:01:371567 DNS_HISTOGRAM("AsyncDNS.FallbackFail", duration);
[email protected]1def74c2012-03-22 20:07:001568 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
1569 }
1570 }
1571
[email protected]1339a2a22012-10-17 08:39:431572 base::TimeDelta ttl =
1573 base::TimeDelta::FromSeconds(kNegativeCacheEntryTTLSeconds);
[email protected]b3601bc22012-02-21 21:23:201574 if (net_error == OK)
1575 ttl = base::TimeDelta::FromSeconds(kCacheEntryTTLSeconds);
[email protected]68ad3ee2010-01-30 03:45:391576
[email protected]895123222012-10-25 15:21:171577 // Don't store the |ttl| in cache since it's not obtained from the server.
1578 CompleteRequests(
1579 HostCache::Entry(net_error, MakeAddressListForRequest(addr_list)),
1580 ttl);
[email protected]b3601bc22012-02-21 21:23:201581 }
1582
1583 void StartDnsTask() {
[email protected]78eac2a2012-03-14 19:09:271584 DCHECK(resolver_->HaveDnsConfig());
[email protected]daae1322013-09-05 18:26:501585 dns_task_.reset(new DnsTask(resolver_->dns_client_.get(), key_, this,
1586 net_log_));
[email protected]b3601bc22012-02-21 21:23:201587
[email protected]daae1322013-09-05 18:26:501588 dns_task_->StartFirstTransaction();
1589 // Schedule a second transaction, if needed.
1590 if (dns_task_->needs_two_transactions())
1591 Schedule(true);
1592 }
1593
1594 void StartSecondDnsTransaction() {
1595 DCHECK(dns_task_->needs_two_transactions());
1596 dns_task_->StartSecondTransaction();
[email protected]16c2bd72013-06-28 01:19:221597 }
1598
1599 // Called if DnsTask fails. It is posted from StartDnsTask, so Job may be
1600 // deleted before this callback. In this case dns_task is deleted as well,
1601 // so we use it as indicator whether Job is still valid.
1602 void OnDnsTaskFailure(const base::WeakPtr<DnsTask>& dns_task,
1603 base::TimeDelta duration,
1604 int net_error) {
1605 DNS_HISTOGRAM("AsyncDNS.ResolveFail", duration);
1606
1607 if (dns_task == NULL)
1608 return;
1609
1610 dns_task_error_ = net_error;
1611
1612 // TODO(szym): Run ServeFromHosts now if nsswitch.conf says so.
1613 // http://crbug.com/117655
1614
1615 // TODO(szym): Some net errors indicate lack of connectivity. Starting
1616 // ProcTask in that case is a waste of time.
1617 if (resolver_->fallback_to_proctask_) {
[email protected]daae1322013-09-05 18:26:501618 KillDnsTask();
[email protected]16c2bd72013-06-28 01:19:221619 StartProcTask();
1620 } else {
1621 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
1622 CompleteRequestsWithError(net_error);
[email protected]b3601bc22012-02-21 21:23:201623 }
1624 }
1625
[email protected]daae1322013-09-05 18:26:501626
1627 // HostResolverImpl::DnsTask::Delegate implementation:
1628
dchengb03027d2014-10-21 12:00:201629 void OnDnsTaskComplete(base::TimeTicks start_time,
1630 int net_error,
1631 const AddressList& addr_list,
1632 base::TimeDelta ttl) override {
[email protected]b3601bc22012-02-21 21:23:201633 DCHECK(is_dns_running());
[email protected]b3601bc22012-02-21 21:23:201634
[email protected]e3bd4822012-10-23 18:01:371635 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]b3601bc22012-02-21 21:23:201636 if (net_error != OK) {
[email protected]16c2bd72013-06-28 01:19:221637 OnDnsTaskFailure(dns_task_->AsWeakPtr(), duration, net_error);
[email protected]b3601bc22012-02-21 21:23:201638 return;
1639 }
[email protected]e3bd4822012-10-23 18:01:371640 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess", duration);
[email protected]02cd6982013-01-10 20:12:511641 // Log DNS lookups based on |address_family|.
1642 switch(key_.address_family) {
1643 case ADDRESS_FAMILY_IPV4:
1644 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_IPV4", duration);
1645 break;
1646 case ADDRESS_FAMILY_IPV6:
1647 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_IPV6", duration);
1648 break;
1649 case ADDRESS_FAMILY_UNSPECIFIED:
1650 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_UNSPEC", duration);
1651 break;
1652 }
[email protected]b3601bc22012-02-21 21:23:201653
[email protected]1def74c2012-03-22 20:07:001654 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_DNS_SUCCESS);
[email protected]1339a2a22012-10-17 08:39:431655 RecordTTL(ttl);
[email protected]0adcb2b2012-08-15 21:30:461656
[email protected]1ffdda82012-12-12 23:04:221657 resolver_->OnDnsTaskResolve(OK);
[email protected]f0f602bd2012-11-15 18:01:021658
[email protected]895123222012-10-25 15:21:171659 base::TimeDelta bounded_ttl =
1660 std::max(ttl, base::TimeDelta::FromSeconds(kMinimumTTLSeconds));
1661
1662 CompleteRequests(
1663 HostCache::Entry(net_error, MakeAddressListForRequest(addr_list), ttl),
1664 bounded_ttl);
[email protected]b3601bc22012-02-21 21:23:201665 }
1666
dchengb03027d2014-10-21 12:00:201667 void OnFirstDnsTransactionComplete() override {
[email protected]daae1322013-09-05 18:26:501668 DCHECK(dns_task_->needs_two_transactions());
1669 DCHECK_EQ(dns_task_->needs_another_transaction(), is_queued());
1670 // No longer need to occupy two dispatcher slots.
1671 ReduceToOneJobSlot();
1672
1673 // We already have a job slot at the dispatcher, so if the second
1674 // transaction hasn't started, reuse it now instead of waiting in the queue
1675 // for the second slot.
1676 if (dns_task_->needs_another_transaction())
1677 dns_task_->StartSecondTransaction();
1678 }
1679
[email protected]16ee26d2012-03-08 03:34:351680 // Performs Job's last rites. Completes all Requests. Deletes this.
[email protected]895123222012-10-25 15:21:171681 void CompleteRequests(const HostCache::Entry& entry,
1682 base::TimeDelta ttl) {
[email protected]11fbca0b2013-06-02 23:37:211683 CHECK(resolver_.get());
[email protected]b3601bc22012-02-21 21:23:201684
[email protected]16ee26d2012-03-08 03:34:351685 // This job must be removed from resolver's |jobs_| now to make room for a
1686 // new job with the same key in case one of the OnComplete callbacks decides
1687 // to spawn one. Consequently, the job deletes itself when CompleteRequests
1688 // is done.
1689 scoped_ptr<Job> self_deleter(this);
1690
1691 resolver_->RemoveJob(this);
1692
[email protected]16ee26d2012-03-08 03:34:351693 if (is_running()) {
[email protected]16ee26d2012-03-08 03:34:351694 if (is_proc_running()) {
[email protected]daae1322013-09-05 18:26:501695 DCHECK(!is_queued());
[email protected]16ee26d2012-03-08 03:34:351696 proc_task_->Cancel();
1697 proc_task_ = NULL;
1698 }
[email protected]daae1322013-09-05 18:26:501699 KillDnsTask();
[email protected]16ee26d2012-03-08 03:34:351700
1701 // Signal dispatcher that a slot has opened.
[email protected]106ccd2c2014-06-17 09:21:001702 resolver_->dispatcher_->OnJobFinished();
[email protected]16ee26d2012-03-08 03:34:351703 } else if (is_queued()) {
[email protected]106ccd2c2014-06-17 09:21:001704 resolver_->dispatcher_->Cancel(handle_);
[email protected]16ee26d2012-03-08 03:34:351705 handle_.Reset();
1706 }
1707
1708 if (num_active_requests() == 0) {
[email protected]4da911f2012-06-14 19:45:201709 net_log_.AddEvent(NetLog::TYPE_CANCELLED);
[email protected]16ee26d2012-03-08 03:34:351710 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
1711 OK);
1712 return;
1713 }
[email protected]b3601bc22012-02-21 21:23:201714
1715 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
[email protected]895123222012-10-25 15:21:171716 entry.error);
[email protected]68ad3ee2010-01-30 03:45:391717
[email protected]78eac2a2012-03-14 19:09:271718 DCHECK(!requests_.empty());
1719
[email protected]895123222012-10-25 15:21:171720 if (entry.error == OK) {
[email protected]d7b9a2b2012-05-31 22:31:191721 // Record this histogram here, when we know the system has a valid DNS
1722 // configuration.
[email protected]539df6c2012-06-19 21:21:291723 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.HaveDnsConfig",
1724 resolver_->received_dns_config_);
[email protected]d7b9a2b2012-05-31 22:31:191725 }
[email protected]16ee26d2012-03-08 03:34:351726
[email protected]7af985a2012-12-14 22:40:421727 bool did_complete = (entry.error != ERR_NETWORK_CHANGED) &&
[email protected]895123222012-10-25 15:21:171728 (entry.error != ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
1729 if (did_complete)
[email protected]1339a2a22012-10-17 08:39:431730 resolver_->CacheResult(key_, entry, ttl);
[email protected]16ee26d2012-03-08 03:34:351731
[email protected]0f292de02012-02-01 22:28:201732 // Complete all of the requests that were attached to the job.
1733 for (RequestsList::const_iterator it = requests_.begin();
1734 it != requests_.end(); ++it) {
1735 Request* req = *it;
1736
1737 if (req->was_canceled())
1738 continue;
1739
1740 DCHECK_EQ(this, req->job());
1741 // Update the net log and notify registered observers.
xunjieli26f90452014-11-10 16:23:021742 LogFinishRequest(req->source_net_log(), req->info(), entry.error);
[email protected]51b9a6b2012-06-25 21:50:291743 if (did_complete) {
1744 // Record effective total time from creation to completion.
1745 RecordTotalTime(had_dns_config_, req->info().is_speculative(),
1746 base::TimeTicks::Now() - req->request_time());
1747 }
[email protected]895123222012-10-25 15:21:171748 req->OnComplete(entry.error, entry.addrlist);
[email protected]0f292de02012-02-01 22:28:201749
1750 // Check if the resolver was destroyed as a result of running the
1751 // callback. If it was, we could continue, but we choose to bail.
[email protected]11fbca0b2013-06-02 23:37:211752 if (!resolver_.get())
[email protected]0f292de02012-02-01 22:28:201753 return;
1754 }
1755 }
1756
[email protected]1339a2a22012-10-17 08:39:431757 // Convenience wrapper for CompleteRequests in case of failure.
1758 void CompleteRequestsWithError(int net_error) {
[email protected]895123222012-10-25 15:21:171759 CompleteRequests(HostCache::Entry(net_error, AddressList()),
1760 base::TimeDelta());
[email protected]1339a2a22012-10-17 08:39:431761 }
1762
[email protected]b4481b222012-03-16 17:13:111763 RequestPriority priority() const {
1764 return priority_tracker_.highest_priority();
1765 }
1766
1767 // Number of non-canceled requests in |requests_|.
1768 size_t num_active_requests() const {
1769 return priority_tracker_.total_count();
1770 }
1771
1772 bool is_dns_running() const {
1773 return dns_task_.get() != NULL;
1774 }
1775
1776 bool is_proc_running() const {
1777 return proc_task_.get() != NULL;
1778 }
1779
[email protected]0f292de02012-02-01 22:28:201780 base::WeakPtr<HostResolverImpl> resolver_;
1781
1782 Key key_;
1783
1784 // Tracks the highest priority across |requests_|.
1785 PriorityTracker priority_tracker_;
1786
1787 bool had_non_speculative_request_;
1788
[email protected]51b9a6b2012-06-25 21:50:291789 // Distinguishes measurements taken while DnsClient was fully configured.
1790 bool had_dns_config_;
1791
[email protected]daae1322013-09-05 18:26:501792 // Number of slots occupied by this Job in resolver's PrioritizedDispatcher.
1793 unsigned num_occupied_job_slots_;
1794
[email protected]1d932852012-06-19 19:40:331795 // Result of DnsTask.
1796 int dns_task_error_;
[email protected]1def74c2012-03-22 20:07:001797
[email protected]51b9a6b2012-06-25 21:50:291798 const base::TimeTicks creation_time_;
1799 base::TimeTicks priority_change_time_;
1800
[email protected]0f292de02012-02-01 22:28:201801 BoundNetLog net_log_;
1802
[email protected]b3601bc22012-02-21 21:23:201803 // Resolves the host using a HostResolverProc.
[email protected]0f292de02012-02-01 22:28:201804 scoped_refptr<ProcTask> proc_task_;
1805
[email protected]b3601bc22012-02-21 21:23:201806 // Resolves the host using a DnsTransaction.
1807 scoped_ptr<DnsTask> dns_task_;
1808
[email protected]0f292de02012-02-01 22:28:201809 // All Requests waiting for the result of this Job. Some can be canceled.
1810 RequestsList requests_;
1811
[email protected]16ee26d2012-03-08 03:34:351812 // A handle used in |HostResolverImpl::dispatcher_|.
[email protected]0f292de02012-02-01 22:28:201813 PrioritizedDispatcher::Handle handle_;
[email protected]68ad3ee2010-01-30 03:45:391814};
1815
1816//-----------------------------------------------------------------------------
1817
[email protected]0f292de02012-02-01 22:28:201818HostResolverImpl::ProcTaskParams::ProcTaskParams(
[email protected]e95d3aca2010-01-11 22:47:431819 HostResolverProc* resolver_proc,
[email protected]0f292de02012-02-01 22:28:201820 size_t max_retry_attempts)
1821 : resolver_proc(resolver_proc),
1822 max_retry_attempts(max_retry_attempts),
1823 unresponsive_delay(base::TimeDelta::FromMilliseconds(6000)),
1824 retry_factor(2) {
[email protected]106ccd2c2014-06-17 09:21:001825 // Maximum of 4 retry attempts for host resolution.
1826 static const size_t kDefaultMaxRetryAttempts = 4u;
1827 if (max_retry_attempts == HostResolver::kDefaultRetryAttempts)
1828 max_retry_attempts = kDefaultMaxRetryAttempts;
[email protected]0f292de02012-02-01 22:28:201829}
1830
1831HostResolverImpl::ProcTaskParams::~ProcTaskParams() {}
1832
[email protected]106ccd2c2014-06-17 09:21:001833HostResolverImpl::HostResolverImpl(const Options& options, NetLog* net_log)
1834 : max_queued_jobs_(0),
1835 proc_params_(NULL, options.max_retry_attempts),
[email protected]62e86ba2013-01-29 18:59:161836 net_log_(net_log),
[email protected]0c7798452009-10-26 17:59:511837 default_address_family_(ADDRESS_FAMILY_UNSPECIFIED),
[email protected]d7b9a2b2012-05-31 22:31:191838 received_dns_config_(false),
[email protected]f0f602bd2012-11-15 18:01:021839 num_dns_failures_(0),
[email protected]23330db72013-07-18 03:32:111840 probe_ipv6_support_(true),
[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 }
1992 return ERR_DNS_CACHE_MISS;
[email protected]95a214c2011-08-04 21:50:401993}
1994
1995int HostResolverImpl::ResolveFromCache(const RequestInfo& info,
1996 AddressList* addresses,
1997 const BoundNetLog& source_net_log) {
1998 DCHECK(CalledOnValidThread());
1999 DCHECK(addresses);
2000
[email protected]95a214c2011-08-04 21:50:402001 // Update the net log and notify registered observers.
xunjieli26f90452014-11-10 16:23:022002 LogStartRequest(source_net_log, info);
[email protected]95a214c2011-08-04 21:50:402003
pauljensen19eb73422015-04-15 23:20:062004 IPAddressNumber ip_number;
2005 IPAddressNumber* ip_number_ptr = nullptr;
2006 if (ParseIPLiteralToNumber(info.hostname(), &ip_number))
2007 ip_number_ptr = &ip_number;
[email protected]95a214c2011-08-04 21:50:402008
pauljensen19eb73422015-04-15 23:20:062009 Key key = GetEffectiveKeyForRequest(info, ip_number_ptr, source_net_log);
2010
2011 int rv = ResolveHelper(key, info, ip_number_ptr, addresses, source_net_log);
xunjieli26f90452014-11-10 16:23:022012 LogFinishRequest(source_net_log, info, rv);
[email protected]95a214c2011-08-04 21:50:402013 return rv;
2014}
2015
[email protected]b59ff372009-07-15 22:04:322016void HostResolverImpl::CancelRequest(RequestHandle req_handle) {
[email protected]1ac6af92010-06-03 21:00:142017 DCHECK(CalledOnValidThread());
[email protected]b59ff372009-07-15 22:04:322018 Request* req = reinterpret_cast<Request*>(req_handle);
2019 DCHECK(req);
[email protected]0f292de02012-02-01 22:28:202020 Job* job = req->job();
2021 DCHECK(job);
[email protected]0f292de02012-02-01 22:28:202022 job->CancelRequest(req);
[email protected]b59ff372009-07-15 22:04:322023}
2024
[email protected]0f8f1b432010-03-16 19:06:032025void HostResolverImpl::SetDefaultAddressFamily(AddressFamily address_family) {
[email protected]1ac6af92010-06-03 21:00:142026 DCHECK(CalledOnValidThread());
[email protected]0f8f1b432010-03-16 19:06:032027 default_address_family_ = address_family;
[email protected]23330db72013-07-18 03:32:112028 probe_ipv6_support_ = false;
[email protected]0f8f1b432010-03-16 19:06:032029}
2030
[email protected]f7d310e2010-10-07 16:25:112031AddressFamily HostResolverImpl::GetDefaultAddressFamily() const {
2032 return default_address_family_;
2033}
2034
[email protected]a8883e452012-11-17 05:58:062035void HostResolverImpl::SetDnsClientEnabled(bool enabled) {
2036 DCHECK(CalledOnValidThread());
2037#if defined(ENABLE_BUILT_IN_DNS)
2038 if (enabled && !dns_client_) {
2039 SetDnsClient(DnsClient::CreateClient(net_log_));
2040 } else if (!enabled && dns_client_) {
2041 SetDnsClient(scoped_ptr<DnsClient>());
2042 }
2043#endif
2044}
2045
[email protected]489d1a82011-10-12 03:09:112046HostCache* HostResolverImpl::GetHostCache() {
2047 return cache_.get();
2048}
[email protected]95a214c2011-08-04 21:50:402049
[email protected]17e92032012-03-29 00:56:242050base::Value* HostResolverImpl::GetDnsConfigAsValue() const {
2051 // Check if async DNS is disabled.
2052 if (!dns_client_.get())
2053 return NULL;
2054
2055 // Check if async DNS is enabled, but we currently have no configuration
2056 // for it.
2057 const DnsConfig* dns_config = dns_client_->GetConfig();
2058 if (dns_config == NULL)
[email protected]ea5ef4c2013-06-13 22:50:272059 return new base::DictionaryValue();
[email protected]17e92032012-03-29 00:56:242060
2061 return dns_config->ToValue();
2062}
2063
[email protected]95a214c2011-08-04 21:50:402064bool HostResolverImpl::ResolveAsIP(const Key& key,
2065 const RequestInfo& info,
pauljensen19eb73422015-04-15 23:20:062066 const IPAddressNumber* ip_number,
[email protected]95a214c2011-08-04 21:50:402067 int* net_error,
2068 AddressList* addresses) {
2069 DCHECK(addresses);
2070 DCHECK(net_error);
pauljensen19eb73422015-04-15 23:20:062071 if (ip_number == nullptr)
[email protected]95a214c2011-08-04 21:50:402072 return false;
2073
2074 DCHECK_EQ(key.host_resolver_flags &
2075 ~(HOST_RESOLVER_CANONNAME | HOST_RESOLVER_LOOPBACK_ONLY |
2076 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6),
2077 0) << " Unhandled flag";
[email protected]1c7cf3f82014-08-07 21:33:482078
[email protected]95a214c2011-08-04 21:50:402079 *net_error = OK;
pauljensen19eb73422015-04-15 23:20:062080 AddressFamily family = GetAddressFamily(*ip_number);
[email protected]1c7cf3f82014-08-07 21:33:482081 if (family == ADDRESS_FAMILY_IPV6 &&
2082 !probe_ipv6_support_ &&
2083 default_address_family_ == ADDRESS_FAMILY_IPV4) {
2084 // Don't return IPv6 addresses if default address family is set to IPv4,
2085 // and probes are disabled.
2086 *net_error = ERR_NAME_NOT_RESOLVED;
2087 } else if (key.address_family != ADDRESS_FAMILY_UNSPECIFIED &&
2088 key.address_family != family) {
2089 // Don't return IPv6 addresses for IPv4 queries, and vice versa.
[email protected]95a214c2011-08-04 21:50:402090 *net_error = ERR_NAME_NOT_RESOLVED;
2091 } else {
pauljensen19eb73422015-04-15 23:20:062092 *addresses = AddressList::CreateFromIPAddress(*ip_number, info.port());
[email protected]7054e78f2012-05-07 21:44:562093 if (key.host_resolver_flags & HOST_RESOLVER_CANONNAME)
2094 addresses->SetDefaultCanonicalName();
[email protected]95a214c2011-08-04 21:50:402095 }
2096 return true;
2097}
2098
2099bool HostResolverImpl::ServeFromCache(const Key& key,
2100 const RequestInfo& info,
[email protected]95a214c2011-08-04 21:50:402101 int* net_error,
2102 AddressList* addresses) {
2103 DCHECK(addresses);
2104 DCHECK(net_error);
2105 if (!info.allow_cached_response() || !cache_.get())
2106 return false;
2107
[email protected]407a30ab2012-08-15 17:16:102108 const HostCache::Entry* cache_entry = cache_->Lookup(
2109 key, base::TimeTicks::Now());
[email protected]95a214c2011-08-04 21:50:402110 if (!cache_entry)
2111 return false;
2112
[email protected]95a214c2011-08-04 21:50:402113 *net_error = cache_entry->error;
[email protected]7054e78f2012-05-07 21:44:562114 if (*net_error == OK) {
[email protected]1339a2a22012-10-17 08:39:432115 if (cache_entry->has_ttl())
2116 RecordTTL(cache_entry->ttl);
[email protected]895123222012-10-25 15:21:172117 *addresses = EnsurePortOnAddressList(cache_entry->addrlist, info.port());
[email protected]7054e78f2012-05-07 21:44:562118 }
[email protected]95a214c2011-08-04 21:50:402119 return true;
2120}
2121
[email protected]78eac2a2012-03-14 19:09:272122bool HostResolverImpl::ServeFromHosts(const Key& key,
2123 const RequestInfo& info,
2124 AddressList* addresses) {
2125 DCHECK(addresses);
2126 if (!HaveDnsConfig())
2127 return false;
[email protected]05a79d42013-03-28 07:30:092128 addresses->clear();
2129
[email protected]cb507622012-03-23 16:17:062130 // HOSTS lookups are case-insensitive.
[email protected]cb1f4ac2014-08-07 16:55:422131 std::string hostname = base::StringToLowerASCII(key.hostname);
[email protected]cb507622012-03-23 16:17:062132
[email protected]05a79d42013-03-28 07:30:092133 const DnsHosts& hosts = dns_client_->GetConfig()->hosts;
2134
[email protected]78eac2a2012-03-14 19:09:272135 // If |address_family| is ADDRESS_FAMILY_UNSPECIFIED other implementations
2136 // (glibc and c-ares) return the first matching line. We have more
2137 // flexibility, but lose implicit ordering.
[email protected]05a79d42013-03-28 07:30:092138 // We prefer IPv6 because "happy eyeballs" will fall back to IPv4 if
2139 // necessary.
2140 if (key.address_family == ADDRESS_FAMILY_IPV6 ||
2141 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
2142 DnsHosts::const_iterator it = hosts.find(
2143 DnsHostsKey(hostname, ADDRESS_FAMILY_IPV6));
2144 if (it != hosts.end())
2145 addresses->push_back(IPEndPoint(it->second, info.port()));
[email protected]78eac2a2012-03-14 19:09:272146 }
2147
[email protected]05a79d42013-03-28 07:30:092148 if (key.address_family == ADDRESS_FAMILY_IPV4 ||
2149 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
2150 DnsHosts::const_iterator it = hosts.find(
2151 DnsHostsKey(hostname, ADDRESS_FAMILY_IPV4));
2152 if (it != hosts.end())
2153 addresses->push_back(IPEndPoint(it->second, info.port()));
2154 }
2155
[email protected]ec666ab22013-04-17 20:05:592156 // If got only loopback addresses and the family was restricted, resolve
2157 // again, without restrictions. See SystemHostResolverCall for rationale.
2158 if ((key.host_resolver_flags &
2159 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6) &&
2160 IsAllIPv4Loopback(*addresses)) {
2161 Key new_key(key);
2162 new_key.address_family = ADDRESS_FAMILY_UNSPECIFIED;
2163 new_key.host_resolver_flags &=
2164 ~HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
2165 return ServeFromHosts(new_key, info, addresses);
2166 }
[email protected]05a79d42013-03-28 07:30:092167 return !addresses->empty();
[email protected]78eac2a2012-03-14 19:09:272168}
2169
[email protected]16ee26d2012-03-08 03:34:352170void HostResolverImpl::CacheResult(const Key& key,
[email protected]1339a2a22012-10-17 08:39:432171 const HostCache::Entry& entry,
[email protected]16ee26d2012-03-08 03:34:352172 base::TimeDelta ttl) {
2173 if (cache_.get())
[email protected]1339a2a22012-10-17 08:39:432174 cache_->Set(key, entry, base::TimeTicks::Now(), ttl);
[email protected]ef4c40c2010-09-01 14:42:032175}
2176
[email protected]0f292de02012-02-01 22:28:202177void HostResolverImpl::RemoveJob(Job* job) {
2178 DCHECK(job);
[email protected]16ee26d2012-03-08 03:34:352179 JobMap::iterator it = jobs_.find(job->key());
2180 if (it != jobs_.end() && it->second == job)
2181 jobs_.erase(it);
[email protected]b59ff372009-07-15 22:04:322182}
2183
[email protected]9936a7862012-10-26 04:44:022184void HostResolverImpl::SetHaveOnlyLoopbackAddresses(bool result) {
2185 if (result) {
2186 additional_resolver_flags_ |= HOST_RESOLVER_LOOPBACK_ONLY;
2187 } else {
2188 additional_resolver_flags_ &= ~HOST_RESOLVER_LOOPBACK_ONLY;
2189 }
2190}
2191
[email protected]137af622010-02-05 02:14:352192HostResolverImpl::Key HostResolverImpl::GetEffectiveKeyForRequest(
pauljensen19eb73422015-04-15 23:20:062193 const RequestInfo& info,
2194 const IPAddressNumber* ip_number,
sergeyub8cdc212015-05-14 18:50:372195 const BoundNetLog& net_log) {
[email protected]eaf3a3b2010-09-03 20:34:272196 HostResolverFlags effective_flags =
2197 info.host_resolver_flags() | additional_resolver_flags_;
[email protected]137af622010-02-05 02:14:352198 AddressFamily effective_address_family = info.address_family();
[email protected]9db6f702013-04-10 18:10:512199
2200 if (info.address_family() == ADDRESS_FAMILY_UNSPECIFIED) {
pauljensen370f1c72015-02-17 16:59:142201 if (probe_ipv6_support_ && !use_local_ipv6_ &&
pauljensen19eb73422015-04-15 23:20:062202 // When resolving IPv4 literals, there's no need to probe for IPv6.
2203 // When resolving IPv6 literals, there's no benefit to artificially
2204 // limiting our resolution based on a probe. Prior logic ensures
2205 // that this query is UNSPECIFIED (see info.address_family()
2206 // check above) and that |default_address_family_| is UNSPECIFIED
2207 // (|prove_ipv6_support_| is false if |default_address_family_| is
2208 // set) so the code requesting the resolution should be amenable to
2209 // receiving a IPv6 resolution.
2210 ip_number == nullptr) {
sergeyub8cdc212015-05-14 18:50:372211 if (!IsIPv6Reachable(net_log)) {
[email protected]ac0b52e2013-04-21 01:26:162212 effective_address_family = ADDRESS_FAMILY_IPV4;
2213 effective_flags |= HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
2214 }
[email protected]9db6f702013-04-10 18:10:512215 } else {
[email protected]ac0b52e2013-04-21 01:26:162216 effective_address_family = default_address_family_;
[email protected]9db6f702013-04-10 18:10:512217 }
2218 }
2219
estark5d131a12015-03-26 19:52:192220 std::string hostname = info.hostname();
2221 // Redirect .localhost queries to "localhost." to make sure that they
2222 // are never sent out on the network, per RFC 6761.
2223 if (IsLocalhostTLD(info.hostname()))
2224 hostname = kLocalhost;
2225
2226 return Key(hostname, effective_address_family, effective_flags);
[email protected]137af622010-02-05 02:14:352227}
2228
sergeyub8cdc212015-05-14 18:50:372229bool HostResolverImpl::IsIPv6Reachable(const BoundNetLog& net_log) {
2230 base::TimeTicks now = base::TimeTicks::Now();
2231 bool cached = true;
2232 if ((now - last_ipv6_probe_time_).InMilliseconds() > kIPv6ProbePeriodMs) {
2233 IPAddressNumber address(kIPv6ProbeAddress,
2234 kIPv6ProbeAddress + arraysize(kIPv6ProbeAddress));
2235 last_ipv6_probe_result_ = IsGloballyReachable(address, net_log);
2236 last_ipv6_probe_time_ = now;
2237 cached = false;
2238 }
2239 net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_IPV6_REACHABILITY_CHECK,
2240 base::Bind(&NetLogIPv6AvailableCallback,
2241 last_ipv6_probe_result_, cached));
2242 return last_ipv6_probe_result_;
2243}
2244
[email protected]35ddc282010-09-21 23:42:062245void HostResolverImpl::AbortAllInProgressJobs() {
[email protected]b3601bc22012-02-21 21:23:202246 // In Abort, a Request callback could spawn new Jobs with matching keys, so
2247 // first collect and remove all running jobs from |jobs_|.
[email protected]c143d892012-04-06 07:56:542248 ScopedVector<Job> jobs_to_abort;
[email protected]0f292de02012-02-01 22:28:202249 for (JobMap::iterator it = jobs_.begin(); it != jobs_.end(); ) {
2250 Job* job = it->second;
[email protected]0f292de02012-02-01 22:28:202251 if (job->is_running()) {
[email protected]b3601bc22012-02-21 21:23:202252 jobs_to_abort.push_back(job);
2253 jobs_.erase(it++);
[email protected]0f292de02012-02-01 22:28:202254 } else {
[email protected]b3601bc22012-02-21 21:23:202255 DCHECK(job->is_queued());
2256 ++it;
[email protected]0f292de02012-02-01 22:28:202257 }
[email protected]ef4c40c2010-09-01 14:42:032258 }
[email protected]b3601bc22012-02-21 21:23:202259
[email protected]daae1322013-09-05 18:26:502260 // Pause the dispatcher so it won't start any new dispatcher jobs while
2261 // aborting the old ones. This is needed so that it won't start the second
2262 // DnsTransaction for a job in |jobs_to_abort| if the DnsConfig just became
2263 // invalid.
[email protected]106ccd2c2014-06-17 09:21:002264 PrioritizedDispatcher::Limits limits = dispatcher_->GetLimits();
2265 dispatcher_->SetLimits(
[email protected]daae1322013-09-05 18:26:502266 PrioritizedDispatcher::Limits(limits.reserved_slots.size(), 0));
[email protected]70c04ab2013-08-22 16:05:122267
[email protected]57a48d32012-03-03 00:04:552268 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072269 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]57a48d32012-03-03 00:04:552270
[email protected]16ee26d2012-03-08 03:34:352271 // Then Abort them.
[email protected]11fbca0b2013-06-02 23:37:212272 for (size_t i = 0; self.get() && i < jobs_to_abort.size(); ++i) {
[email protected]57a48d32012-03-03 00:04:552273 jobs_to_abort[i]->Abort();
[email protected]c143d892012-04-06 07:56:542274 jobs_to_abort[i] = NULL;
[email protected]b3601bc22012-02-21 21:23:202275 }
[email protected]daae1322013-09-05 18:26:502276
2277 if (self)
[email protected]106ccd2c2014-06-17 09:21:002278 dispatcher_->SetLimits(limits);
[email protected]daae1322013-09-05 18:26:502279}
2280
2281void HostResolverImpl::AbortDnsTasks() {
2282 // Pause the dispatcher so it won't start any new dispatcher jobs while
2283 // aborting the old ones. This is needed so that it won't start the second
2284 // DnsTransaction for a job if the DnsConfig just changed.
[email protected]106ccd2c2014-06-17 09:21:002285 PrioritizedDispatcher::Limits limits = dispatcher_->GetLimits();
2286 dispatcher_->SetLimits(
[email protected]daae1322013-09-05 18:26:502287 PrioritizedDispatcher::Limits(limits.reserved_slots.size(), 0));
2288
2289 for (JobMap::iterator it = jobs_.begin(); it != jobs_.end(); ++it)
2290 it->second->AbortDnsTask();
[email protected]106ccd2c2014-06-17 09:21:002291 dispatcher_->SetLimits(limits);
[email protected]ef4c40c2010-09-01 14:42:032292}
2293
[email protected]78eac2a2012-03-14 19:09:272294void HostResolverImpl::TryServingAllJobsFromHosts() {
2295 if (!HaveDnsConfig())
2296 return;
2297
2298 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2299 // http://crbug.com/117655
2300
2301 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072302 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]78eac2a2012-03-14 19:09:272303
[email protected]11fbca0b2013-06-02 23:37:212304 for (JobMap::iterator it = jobs_.begin(); self.get() && it != jobs_.end();) {
[email protected]78eac2a2012-03-14 19:09:272305 Job* job = it->second;
2306 ++it;
2307 // This could remove |job| from |jobs_|, but iterator will remain valid.
2308 job->ServeFromHosts();
2309 }
2310}
2311
[email protected]be1a48b2011-01-20 00:12:132312void HostResolverImpl::OnIPAddressChanged() {
[email protected]62e86ba2013-01-29 18:59:162313 resolved_known_ipv6_hostname_ = false;
sergeyub8cdc212015-05-14 18:50:372314 last_ipv6_probe_time_ = base::TimeTicks();
[email protected]12faa4c2012-11-06 04:44:182315 // Abandon all ProbeJobs.
2316 probe_weak_ptr_factory_.InvalidateWeakPtrs();
[email protected]be1a48b2011-01-20 00:12:132317 if (cache_.get())
2318 cache_->clear();
[email protected]7c466e92013-07-20 01:44:482319#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
[email protected]12faa4c2012-11-06 04:44:182320 new LoopbackProbeJob(probe_weak_ptr_factory_.GetWeakPtr());
[email protected]be1a48b2011-01-20 00:12:132321#endif
2322 AbortAllInProgressJobs();
2323 // |this| may be deleted inside AbortAllInProgressJobs().
2324}
2325
pauljensen101ed372015-04-17 00:11:422326void HostResolverImpl::OnInitialDNSConfigRead() {
2327 UpdateDNSConfig(false);
2328}
2329
[email protected]bb0e34542012-08-31 19:52:402330void HostResolverImpl::OnDNSChanged() {
pauljensen101ed372015-04-17 00:11:422331 UpdateDNSConfig(true);
2332}
2333
2334void HostResolverImpl::UpdateDNSConfig(bool config_changed) {
[email protected]bb0e34542012-08-31 19:52:402335 DnsConfig dns_config;
2336 NetworkChangeNotifier::GetDnsConfig(&dns_config);
[email protected]ec666ab22013-04-17 20:05:592337
[email protected]b4481b222012-03-16 17:13:112338 if (net_log_) {
2339 net_log_->AddGlobalEntry(
2340 NetLog::TYPE_DNS_CONFIG_CHANGED,
[email protected]cd565142012-06-12 16:21:452341 base::Bind(&NetLogDnsConfigCallback, &dns_config));
[email protected]b4481b222012-03-16 17:13:112342 }
2343
[email protected]01b3b9d2012-08-13 16:18:142344 // TODO(szym): Remove once http://crbug.com/137914 is resolved.
[email protected]d7b9a2b2012-05-31 22:31:192345 received_dns_config_ = dns_config.IsValid();
[email protected]c9fa8f312013-09-17 12:24:522346 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
2347 use_local_ipv6_ = !dns_config.IsValid() || dns_config.use_local_ipv6;
[email protected]78eac2a2012-03-14 19:09:272348
[email protected]a8883e452012-11-17 05:58:062349 num_dns_failures_ = 0;
2350
[email protected]01b3b9d2012-08-13 16:18:142351 // We want a new DnsSession in place, before we Abort running Jobs, so that
2352 // the newly started jobs use the new config.
[email protected]f0f602bd2012-11-15 18:01:022353 if (dns_client_.get()) {
[email protected]d7b9a2b2012-05-31 22:31:192354 dns_client_->SetConfig(dns_config);
pauljensen101ed372015-04-17 00:11:422355 if (dns_client_->GetConfig()) {
[email protected]f0f602bd2012-11-15 18:01:022356 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
pauljensen101ed372015-04-17 00:11:422357 // If we just switched DnsClients, restart jobs using new resolver.
2358 // TODO(pauljensen): Is this necessary?
2359 config_changed = true;
2360 }
[email protected]f0f602bd2012-11-15 18:01:022361 }
[email protected]01b3b9d2012-08-13 16:18:142362
pauljensen101ed372015-04-17 00:11:422363 if (config_changed) {
2364 // If the DNS server has changed, existing cached info could be wrong so we
2365 // have to drop our internal cache :( Note that OS level DNS caches, such
2366 // as NSCD's cache should be dropped automatically by the OS when
2367 // resolv.conf changes so we don't need to do anything to clear that cache.
2368 if (cache_.get())
2369 cache_->clear();
[email protected]01b3b9d2012-08-13 16:18:142370
pauljensen101ed372015-04-17 00:11:422371 // Life check to bail once |this| is deleted.
2372 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]f0f602bd2012-11-15 18:01:022373
pauljensen101ed372015-04-17 00:11:422374 // Existing jobs will have been sent to the original server so they need to
2375 // be aborted.
2376 AbortAllInProgressJobs();
[email protected]01b3b9d2012-08-13 16:18:142377
pauljensen101ed372015-04-17 00:11:422378 // |this| may be deleted inside AbortAllInProgressJobs().
2379 if (self.get())
2380 TryServingAllJobsFromHosts();
2381 }
[email protected]78eac2a2012-03-14 19:09:272382}
2383
2384bool HostResolverImpl::HaveDnsConfig() const {
[email protected]32b1dbcf2013-01-26 03:48:252385 // Use DnsClient only if it's fully configured and there is no override by
2386 // ScopedDefaultHostResolverProc.
2387 // The alternative is to use NetworkChangeNotifier to override DnsConfig,
2388 // but that would introduce construction order requirements for NCN and SDHRP.
[email protected]90499482013-06-01 00:39:502389 return (dns_client_.get() != NULL) && (dns_client_->GetConfig() != NULL) &&
2390 !(proc_params_.resolver_proc.get() == NULL &&
[email protected]32b1dbcf2013-01-26 03:48:252391 HostResolverProc::GetDefault() != NULL);
[email protected]b3601bc22012-02-21 21:23:202392}
2393
[email protected]1ffdda82012-12-12 23:04:222394void HostResolverImpl::OnDnsTaskResolve(int net_error) {
[email protected]f0f602bd2012-11-15 18:01:022395 DCHECK(dns_client_);
[email protected]1ffdda82012-12-12 23:04:222396 if (net_error == OK) {
[email protected]f0f602bd2012-11-15 18:01:022397 num_dns_failures_ = 0;
2398 return;
2399 }
2400 ++num_dns_failures_;
2401 if (num_dns_failures_ < kMaximumDnsFailures)
2402 return;
[email protected]daae1322013-09-05 18:26:502403
2404 // Disable DnsClient until the next DNS change. Must be done before aborting
2405 // DnsTasks, since doing so may start new jobs.
[email protected]f0f602bd2012-11-15 18:01:022406 dns_client_->SetConfig(DnsConfig());
[email protected]daae1322013-09-05 18:26:502407
2408 // Switch jobs with active DnsTasks over to using ProcTasks.
2409 AbortDnsTasks();
2410
[email protected]f0f602bd2012-11-15 18:01:022411 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", false);
davidbenad6fc442015-05-18 20:59:132412 UMA_HISTOGRAM_SPARSE_SLOWLY("AsyncDNS.DnsClientDisabledReason",
2413 std::abs(net_error));
[email protected]f0f602bd2012-11-15 18:01:022414}
2415
[email protected]a8883e452012-11-17 05:58:062416void HostResolverImpl::SetDnsClient(scoped_ptr<DnsClient> dns_client) {
[email protected]daae1322013-09-05 18:26:502417 // DnsClient and config must be updated before aborting DnsTasks, since doing
2418 // so may start new jobs.
[email protected]a8883e452012-11-17 05:58:062419 dns_client_ = dns_client.Pass();
[email protected]daae1322013-09-05 18:26:502420 if (dns_client_ && !dns_client_->GetConfig() &&
2421 num_dns_failures_ < kMaximumDnsFailures) {
2422 DnsConfig dns_config;
2423 NetworkChangeNotifier::GetDnsConfig(&dns_config);
2424 dns_client_->SetConfig(dns_config);
2425 num_dns_failures_ = 0;
2426 if (dns_client_->GetConfig())
2427 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
[email protected]a8883e452012-11-17 05:58:062428 }
[email protected]daae1322013-09-05 18:26:502429
2430 AbortDnsTasks();
[email protected]a8883e452012-11-17 05:58:062431}
2432
[email protected]b59ff372009-07-15 22:04:322433} // namespace net