blob: 8913f17fd762c61e6d709cc497521764fe3cd2c0 [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"
[email protected]835d7c82010-10-14 04:38:3826#include "base/metrics/histogram.h"
[email protected]7286e3fc2011-07-19 22:13:2427#include "base/stl_util.h"
[email protected]be528af2013-06-11 07:39:4828#include "base/strings/string_util.h"
[email protected]750b2f3c2013-06-07 18:41:0529#include "base/strings/utf_string_conversions.h"
[email protected]ac9ba8fe2010-12-30 18:08:3630#include "base/threading/worker_pool.h"
[email protected]66e96c42013-06-28 15:20:3131#include "base/time/time.h"
[email protected]21526002010-05-16 19:42:4632#include "base/values.h"
[email protected]b3601bc22012-02-21 21:23:2033#include "net/base/address_family.h"
[email protected]b59ff372009-07-15 22:04:3234#include "net/base/address_list.h"
[email protected]46018c9d2011-09-06 03:42:3435#include "net/base/dns_reloader.h"
[email protected]e806cd72013-05-17 02:08:4336#include "net/base/dns_util.h"
[email protected]ee094b82010-08-24 15:55:5137#include "net/base/host_port_pair.h"
[email protected]1c7cf3f82014-08-07 21:33:4838#include "net/base/ip_endpoint.h"
[email protected]2bb04442010-08-18 18:01:1539#include "net/base/net_errors.h"
[email protected]ee094b82010-08-24 15:55:5140#include "net/base/net_log.h"
[email protected]0f8f1b432010-03-16 19:06:0341#include "net/base/net_util.h"
[email protected]0adcb2b2012-08-15 21:30:4642#include "net/dns/address_sorter.h"
[email protected]78eac2a2012-03-14 19:09:2743#include "net/dns/dns_client.h"
[email protected]b3601bc22012-02-21 21:23:2044#include "net/dns/dns_config_service.h"
45#include "net/dns/dns_protocol.h"
46#include "net/dns/dns_response.h"
[email protected]b3601bc22012-02-21 21:23:2047#include "net/dns/dns_transaction.h"
[email protected]f2cb3cf2013-03-21 01:40:5348#include "net/dns/host_resolver_proc.h"
[email protected]9db6f702013-04-10 18:10:5149#include "net/socket/client_socket_factory.h"
50#include "net/udp/datagram_client_socket.h"
[email protected]b59ff372009-07-15 22:04:3251
52#if defined(OS_WIN)
53#include "net/base/winsock_init.h"
54#endif
55
56namespace net {
57
[email protected]e95d3aca2010-01-11 22:47:4358namespace {
59
[email protected]6e78dfb2011-07-28 21:34:4760// Limit the size of hostnames that will be resolved to combat issues in
61// some platform's resolvers.
62const size_t kMaxHostLength = 4096;
63
[email protected]a2730882012-01-21 00:56:2764// Default TTL for successful resolutions with ProcTask.
65const unsigned kCacheEntryTTLSeconds = 60;
66
[email protected]b3601bc22012-02-21 21:23:2067// Default TTL for unsuccessful resolutions with ProcTask.
68const unsigned kNegativeCacheEntryTTLSeconds = 0;
69
[email protected]895123222012-10-25 15:21:1770// Minimum TTL for successful resolutions with DnsTask.
71const unsigned kMinimumTTLSeconds = kCacheEntryTTLSeconds;
72
[email protected]24f4bab2010-10-15 01:27:1173// We use a separate histogram name for each platform to facilitate the
74// display of error codes by their symbolic name (since each platform has
75// different mappings).
76const char kOSErrorsForGetAddrinfoHistogramName[] =
77#if defined(OS_WIN)
78 "Net.OSErrorsForGetAddrinfo_Win";
79#elif defined(OS_MACOSX)
80 "Net.OSErrorsForGetAddrinfo_Mac";
81#elif defined(OS_LINUX)
82 "Net.OSErrorsForGetAddrinfo_Linux";
83#else
84 "Net.OSErrorsForGetAddrinfo";
85#endif
86
[email protected]c89b2442011-05-26 14:28:2787// Gets a list of the likely error codes that getaddrinfo() can return
88// (non-exhaustive). These are the error codes that we will track via
89// a histogram.
90std::vector<int> GetAllGetAddrinfoOSErrors() {
91 int os_errors[] = {
92#if defined(OS_POSIX)
[email protected]23f771162011-06-02 18:37:5193#if !defined(OS_FREEBSD)
[email protected]39588992011-07-11 19:54:3794#if !defined(OS_ANDROID)
[email protected]c48aef92011-11-22 23:41:4595 // EAI_ADDRFAMILY has been declared obsolete in Android's and
96 // FreeBSD's netdb.h.
[email protected]c89b2442011-05-26 14:28:2797 EAI_ADDRFAMILY,
[email protected]39588992011-07-11 19:54:3798#endif
[email protected]c48aef92011-11-22 23:41:4599 // EAI_NODATA has been declared obsolete in FreeBSD's netdb.h.
[email protected]23f771162011-06-02 18:37:51100 EAI_NODATA,
101#endif
[email protected]c89b2442011-05-26 14:28:27102 EAI_AGAIN,
103 EAI_BADFLAGS,
104 EAI_FAIL,
105 EAI_FAMILY,
106 EAI_MEMORY,
[email protected]c89b2442011-05-26 14:28:27107 EAI_NONAME,
108 EAI_SERVICE,
109 EAI_SOCKTYPE,
110 EAI_SYSTEM,
111#elif defined(OS_WIN)
112 // See: http://msdn.microsoft.com/en-us/library/ms738520(VS.85).aspx
113 WSA_NOT_ENOUGH_MEMORY,
114 WSAEAFNOSUPPORT,
115 WSAEINVAL,
116 WSAESOCKTNOSUPPORT,
117 WSAHOST_NOT_FOUND,
118 WSANO_DATA,
119 WSANO_RECOVERY,
120 WSANOTINITIALISED,
121 WSATRY_AGAIN,
122 WSATYPE_NOT_FOUND,
123 // The following are not in doc, but might be to appearing in results :-(.
124 WSA_INVALID_HANDLE,
125#endif
126 };
127
128 // Ensure all errors are positive, as histogram only tracks positive values.
129 for (size_t i = 0; i < arraysize(os_errors); ++i) {
130 os_errors[i] = std::abs(os_errors[i]);
131 }
132
133 return base::CustomHistogram::ArrayToCustomRanges(os_errors,
134 arraysize(os_errors));
135}
136
[email protected]1def74c2012-03-22 20:07:00137enum DnsResolveStatus {
138 RESOLVE_STATUS_DNS_SUCCESS = 0,
139 RESOLVE_STATUS_PROC_SUCCESS,
140 RESOLVE_STATUS_FAIL,
[email protected]1d932852012-06-19 19:40:33141 RESOLVE_STATUS_SUSPECT_NETBIOS,
[email protected]1def74c2012-03-22 20:07:00142 RESOLVE_STATUS_MAX
143};
144
145void UmaAsyncDnsResolveStatus(DnsResolveStatus result) {
146 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ResolveStatus",
147 result,
148 RESOLVE_STATUS_MAX);
149}
150
[email protected]1d932852012-06-19 19:40:33151bool ResemblesNetBIOSName(const std::string& hostname) {
152 return (hostname.size() < 16) && (hostname.find('.') == std::string::npos);
153}
154
155// True if |hostname| ends with either ".local" or ".local.".
156bool ResemblesMulticastDNSName(const std::string& hostname) {
157 DCHECK(!hostname.empty());
158 const char kSuffix[] = ".local.";
159 const size_t kSuffixLen = sizeof(kSuffix) - 1;
160 const size_t kSuffixLenTrimmed = kSuffixLen - 1;
161 if (hostname[hostname.size() - 1] == '.') {
162 return hostname.size() > kSuffixLen &&
163 !hostname.compare(hostname.size() - kSuffixLen, kSuffixLen, kSuffix);
164 }
165 return hostname.size() > kSuffixLenTrimmed &&
166 !hostname.compare(hostname.size() - kSuffixLenTrimmed, kSuffixLenTrimmed,
167 kSuffix, kSuffixLenTrimmed);
168}
169
[email protected]34e61362013-07-24 20:41:56170// Attempts to connect a UDP socket to |dest|:53.
[email protected]2b74a2f2013-07-23 19:37:38171bool IsGloballyReachable(const IPAddressNumber& dest,
172 const BoundNetLog& net_log) {
[email protected]9db6f702013-04-10 18:10:51173 scoped_ptr<DatagramClientSocket> socket(
174 ClientSocketFactory::GetDefaultFactory()->CreateDatagramClientSocket(
175 DatagramSocket::DEFAULT_BIND,
176 RandIntCallback(),
[email protected]2b74a2f2013-07-23 19:37:38177 net_log.net_log(),
178 net_log.source()));
[email protected]34e61362013-07-24 20:41:56179 int rv = socket->Connect(IPEndPoint(dest, 53));
[email protected]e9051722013-04-12 21:58:18180 if (rv != OK)
181 return false;
182 IPEndPoint endpoint;
183 rv = socket->GetLocalAddress(&endpoint);
184 if (rv != OK)
185 return false;
[email protected]1c7cf3f82014-08-07 21:33:48186 DCHECK_EQ(ADDRESS_FAMILY_IPV6, endpoint.GetFamily());
[email protected]e9051722013-04-12 21:58:18187 const IPAddressNumber& address = endpoint.address();
188 bool is_link_local = (address[0] == 0xFE) && ((address[1] & 0xC0) == 0x80);
189 if (is_link_local)
190 return false;
191 const uint8 kTeredoPrefix[] = { 0x20, 0x01, 0, 0 };
192 bool is_teredo = std::equal(kTeredoPrefix,
193 kTeredoPrefix + arraysize(kTeredoPrefix),
194 address.begin());
195 if (is_teredo)
196 return false;
197 return true;
[email protected]9db6f702013-04-10 18:10:51198}
199
[email protected]51b9a6b2012-06-25 21:50:29200// Provide a common macro to simplify code and readability. We must use a
201// macro as the underlying HISTOGRAM macro creates static variables.
202#define DNS_HISTOGRAM(name, time) UMA_HISTOGRAM_CUSTOM_TIMES(name, time, \
203 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromHours(1), 100)
204
205// A macro to simplify code and readability.
206#define DNS_HISTOGRAM_BY_PRIORITY(basename, priority, time) \
207 do { \
208 switch (priority) { \
209 case HIGHEST: DNS_HISTOGRAM(basename "_HIGHEST", time); break; \
210 case MEDIUM: DNS_HISTOGRAM(basename "_MEDIUM", time); break; \
211 case LOW: DNS_HISTOGRAM(basename "_LOW", time); break; \
212 case LOWEST: DNS_HISTOGRAM(basename "_LOWEST", time); break; \
213 case IDLE: DNS_HISTOGRAM(basename "_IDLE", time); break; \
214 default: NOTREACHED(); break; \
215 } \
216 DNS_HISTOGRAM(basename, time); \
217 } while (0)
218
219// Record time from Request creation until a valid DNS response.
220void RecordTotalTime(bool had_dns_config,
221 bool speculative,
222 base::TimeDelta duration) {
223 if (had_dns_config) {
224 if (speculative) {
225 DNS_HISTOGRAM("AsyncDNS.TotalTime_speculative", duration);
226 } else {
227 DNS_HISTOGRAM("AsyncDNS.TotalTime", duration);
228 }
229 } else {
230 if (speculative) {
231 DNS_HISTOGRAM("DNS.TotalTime_speculative", duration);
232 } else {
233 DNS_HISTOGRAM("DNS.TotalTime", duration);
234 }
235 }
236}
237
[email protected]1339a2a22012-10-17 08:39:43238void RecordTTL(base::TimeDelta ttl) {
239 UMA_HISTOGRAM_CUSTOM_TIMES("AsyncDNS.TTL", ttl,
240 base::TimeDelta::FromSeconds(1),
241 base::TimeDelta::FromDays(1), 100);
242}
243
[email protected]16c2bd72013-06-28 01:19:22244bool ConfigureAsyncDnsNoFallbackFieldTrial() {
245 const bool kDefault = false;
246
247 // Configure the AsyncDns field trial as follows:
248 // groups AsyncDnsNoFallbackA and AsyncDnsNoFallbackB: return true,
249 // groups AsyncDnsA and AsyncDnsB: return false,
250 // groups SystemDnsA and SystemDnsB: return false,
251 // otherwise (trial absent): return default.
252 std::string group_name = base::FieldTrialList::FindFullName("AsyncDns");
253 if (!group_name.empty())
254 return StartsWithASCII(group_name, "AsyncDnsNoFallback", false);
255 return kDefault;
256}
257
[email protected]d7b9a2b2012-05-31 22:31:19258//-----------------------------------------------------------------------------
259
[email protected]895123222012-10-25 15:21:17260AddressList EnsurePortOnAddressList(const AddressList& list, uint16 port) {
261 if (list.empty() || list.front().port() == port)
262 return list;
263 return AddressList::CopyWithPort(list, port);
[email protected]7054e78f2012-05-07 21:44:56264}
265
[email protected]ec666ab22013-04-17 20:05:59266// Returns true if |addresses| contains only IPv4 loopback addresses.
267bool IsAllIPv4Loopback(const AddressList& addresses) {
268 for (unsigned i = 0; i < addresses.size(); ++i) {
269 const IPAddressNumber& address = addresses[i].address();
270 switch (addresses[i].GetFamily()) {
271 case ADDRESS_FAMILY_IPV4:
272 if (address[0] != 127)
273 return false;
274 break;
275 case ADDRESS_FAMILY_IPV6:
276 return false;
277 default:
278 NOTREACHED();
279 return false;
280 }
281 }
282 return true;
283}
284
[email protected]cd565142012-06-12 16:21:45285// Creates NetLog parameters when the resolve failed.
286base::Value* NetLogProcTaskFailedCallback(uint32 attempt_number,
287 int net_error,
288 int os_error,
289 NetLog::LogLevel /* log_level */) {
[email protected]ea5ef4c2013-06-13 22:50:27290 base::DictionaryValue* dict = new base::DictionaryValue();
[email protected]cd565142012-06-12 16:21:45291 if (attempt_number)
292 dict->SetInteger("attempt_number", attempt_number);
[email protected]21526002010-05-16 19:42:46293
[email protected]cd565142012-06-12 16:21:45294 dict->SetInteger("net_error", net_error);
[email protected]13024882011-05-18 23:19:16295
[email protected]cd565142012-06-12 16:21:45296 if (os_error) {
297 dict->SetInteger("os_error", os_error);
[email protected]21526002010-05-16 19:42:46298#if defined(OS_POSIX)
[email protected]cd565142012-06-12 16:21:45299 dict->SetString("os_error_string", gai_strerror(os_error));
[email protected]21526002010-05-16 19:42:46300#elif defined(OS_WIN)
[email protected]cd565142012-06-12 16:21:45301 // Map the error code to a human-readable string.
302 LPWSTR error_string = NULL;
303 int size = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
304 FORMAT_MESSAGE_FROM_SYSTEM,
305 0, // Use the internal message table.
306 os_error,
307 0, // Use default language.
308 (LPWSTR)&error_string,
309 0, // Buffer size.
310 0); // Arguments (unused).
[email protected]ad65a3e2013-12-25 18:18:01311 dict->SetString("os_error_string", base::WideToUTF8(error_string));
[email protected]cd565142012-06-12 16:21:45312 LocalFree(error_string);
[email protected]21526002010-05-16 19:42:46313#endif
[email protected]21526002010-05-16 19:42:46314 }
315
[email protected]cd565142012-06-12 16:21:45316 return dict;
317}
[email protected]a9813302012-04-28 09:29:28318
[email protected]cd565142012-06-12 16:21:45319// Creates NetLog parameters when the DnsTask failed.
320base::Value* NetLogDnsTaskFailedCallback(int net_error,
321 int dns_error,
322 NetLog::LogLevel /* log_level */) {
[email protected]ea5ef4c2013-06-13 22:50:27323 base::DictionaryValue* dict = new base::DictionaryValue();
[email protected]cd565142012-06-12 16:21:45324 dict->SetInteger("net_error", net_error);
325 if (dns_error)
326 dict->SetInteger("dns_error", dns_error);
327 return dict;
[email protected]ee094b82010-08-24 15:55:51328};
329
[email protected]cd565142012-06-12 16:21:45330// Creates NetLog parameters containing the information in a RequestInfo object,
331// along with the associated NetLog::Source.
332base::Value* NetLogRequestInfoCallback(const NetLog::Source& source,
333 const HostResolver::RequestInfo* info,
334 NetLog::LogLevel /* log_level */) {
[email protected]ea5ef4c2013-06-13 22:50:27335 base::DictionaryValue* dict = new base::DictionaryValue();
[email protected]cd565142012-06-12 16:21:45336 source.AddToEventParameters(dict);
[email protected]b3601bc22012-02-21 21:23:20337
[email protected]cd565142012-06-12 16:21:45338 dict->SetString("host", info->host_port_pair().ToString());
339 dict->SetInteger("address_family",
340 static_cast<int>(info->address_family()));
341 dict->SetBoolean("allow_cached_response", info->allow_cached_response());
342 dict->SetBoolean("is_speculative", info->is_speculative());
[email protected]cd565142012-06-12 16:21:45343 return dict;
344}
[email protected]b3601bc22012-02-21 21:23:20345
[email protected]cd565142012-06-12 16:21:45346// Creates NetLog parameters for the creation of a HostResolverImpl::Job.
347base::Value* NetLogJobCreationCallback(const NetLog::Source& source,
348 const std::string* host,
349 NetLog::LogLevel /* log_level */) {
[email protected]ea5ef4c2013-06-13 22:50:27350 base::DictionaryValue* dict = new base::DictionaryValue();
[email protected]cd565142012-06-12 16:21:45351 source.AddToEventParameters(dict);
352 dict->SetString("host", *host);
353 return dict;
354}
[email protected]a9813302012-04-28 09:29:28355
[email protected]cd565142012-06-12 16:21:45356// Creates NetLog parameters for HOST_RESOLVER_IMPL_JOB_ATTACH/DETACH events.
357base::Value* NetLogJobAttachCallback(const NetLog::Source& source,
358 RequestPriority priority,
359 NetLog::LogLevel /* log_level */) {
[email protected]ea5ef4c2013-06-13 22:50:27360 base::DictionaryValue* dict = new base::DictionaryValue();
[email protected]cd565142012-06-12 16:21:45361 source.AddToEventParameters(dict);
[email protected]3b04d1f22013-10-16 00:23:56362 dict->SetString("priority", RequestPriorityToString(priority));
[email protected]cd565142012-06-12 16:21:45363 return dict;
364}
[email protected]b3601bc22012-02-21 21:23:20365
[email protected]cd565142012-06-12 16:21:45366// Creates NetLog parameters for the DNS_CONFIG_CHANGED event.
367base::Value* NetLogDnsConfigCallback(const DnsConfig* config,
368 NetLog::LogLevel /* log_level */) {
369 return config->ToValue();
370}
[email protected]b4481b222012-03-16 17:13:11371
[email protected]0f292de02012-02-01 22:28:20372// The logging routines are defined here because some requests are resolved
373// without a Request object.
374
375// Logs when a request has just been started.
376void LogStartRequest(const BoundNetLog& source_net_log,
377 const BoundNetLog& request_net_log,
378 const HostResolver::RequestInfo& info) {
379 source_net_log.BeginEvent(
380 NetLog::TYPE_HOST_RESOLVER_IMPL,
[email protected]cd565142012-06-12 16:21:45381 request_net_log.source().ToEventParametersCallback());
[email protected]0f292de02012-02-01 22:28:20382
383 request_net_log.BeginEvent(
384 NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST,
[email protected]cd565142012-06-12 16:21:45385 base::Bind(&NetLogRequestInfoCallback, source_net_log.source(), &info));
[email protected]0f292de02012-02-01 22:28:20386}
387
388// Logs when a request has just completed (before its callback is run).
389void LogFinishRequest(const BoundNetLog& source_net_log,
390 const BoundNetLog& request_net_log,
391 const HostResolver::RequestInfo& info,
[email protected]b3601bc22012-02-21 21:23:20392 int net_error) {
393 request_net_log.EndEventWithNetErrorCode(
394 NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST, net_error);
[email protected]4da911f2012-06-14 19:45:20395 source_net_log.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL);
[email protected]0f292de02012-02-01 22:28:20396}
397
398// Logs when a request has been cancelled.
399void LogCancelRequest(const BoundNetLog& source_net_log,
400 const BoundNetLog& request_net_log,
401 const HostResolverImpl::RequestInfo& info) {
[email protected]4da911f2012-06-14 19:45:20402 request_net_log.AddEvent(NetLog::TYPE_CANCELLED);
403 request_net_log.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST);
404 source_net_log.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL);
[email protected]0f292de02012-02-01 22:28:20405}
406
[email protected]b59ff372009-07-15 22:04:32407//-----------------------------------------------------------------------------
408
[email protected]0f292de02012-02-01 22:28:20409// Keeps track of the highest priority.
410class PriorityTracker {
411 public:
[email protected]8c98d002012-07-18 19:02:27412 explicit PriorityTracker(RequestPriority initial_priority)
413 : highest_priority_(initial_priority), total_count_(0) {
[email protected]0f292de02012-02-01 22:28:20414 memset(counts_, 0, sizeof(counts_));
415 }
416
417 RequestPriority highest_priority() const {
418 return highest_priority_;
419 }
420
421 size_t total_count() const {
422 return total_count_;
423 }
424
425 void Add(RequestPriority req_priority) {
426 ++total_count_;
427 ++counts_[req_priority];
[email protected]31ae7ab2012-04-24 21:09:05428 if (highest_priority_ < req_priority)
[email protected]0f292de02012-02-01 22:28:20429 highest_priority_ = req_priority;
430 }
431
432 void Remove(RequestPriority req_priority) {
433 DCHECK_GT(total_count_, 0u);
434 DCHECK_GT(counts_[req_priority], 0u);
435 --total_count_;
436 --counts_[req_priority];
437 size_t i;
[email protected]31ae7ab2012-04-24 21:09:05438 for (i = highest_priority_; i > MINIMUM_PRIORITY && !counts_[i]; --i);
[email protected]0f292de02012-02-01 22:28:20439 highest_priority_ = static_cast<RequestPriority>(i);
440
[email protected]31ae7ab2012-04-24 21:09:05441 // In absence of requests, default to MINIMUM_PRIORITY.
442 if (total_count_ == 0)
443 DCHECK_EQ(MINIMUM_PRIORITY, highest_priority_);
[email protected]0f292de02012-02-01 22:28:20444 }
445
446 private:
447 RequestPriority highest_priority_;
448 size_t total_count_;
449 size_t counts_[NUM_PRIORITIES];
450};
451
[email protected]c54a8912012-10-22 22:09:43452} // namespace
[email protected]0f292de02012-02-01 22:28:20453
454//-----------------------------------------------------------------------------
455
[email protected]daae1322013-09-05 18:26:50456const unsigned HostResolverImpl::kMaximumDnsFailures = 16;
457
[email protected]0f292de02012-02-01 22:28:20458// Holds the data for a request that could not be completed synchronously.
459// It is owned by a Job. Canceled Requests are only marked as canceled rather
460// than removed from the Job's |requests_| list.
[email protected]b59ff372009-07-15 22:04:32461class HostResolverImpl::Request {
462 public:
[email protected]ee094b82010-08-24 15:55:51463 Request(const BoundNetLog& source_net_log,
464 const BoundNetLog& request_net_log,
[email protected]54e13772009-08-14 03:01:09465 const RequestInfo& info,
[email protected]5109c1952013-08-20 18:44:10466 RequestPriority priority,
[email protected]aa22b242011-11-16 18:58:29467 const CompletionCallback& callback,
[email protected]b59ff372009-07-15 22:04:32468 AddressList* addresses)
[email protected]ee094b82010-08-24 15:55:51469 : source_net_log_(source_net_log),
470 request_net_log_(request_net_log),
[email protected]54e13772009-08-14 03:01:09471 info_(info),
[email protected]5109c1952013-08-20 18:44:10472 priority_(priority),
[email protected]54e13772009-08-14 03:01:09473 job_(NULL),
474 callback_(callback),
[email protected]51b9a6b2012-06-25 21:50:29475 addresses_(addresses),
[email protected]5109c1952013-08-20 18:44:10476 request_time_(base::TimeTicks::Now()) {}
[email protected]b59ff372009-07-15 22:04:32477
[email protected]0f292de02012-02-01 22:28:20478 // Mark the request as canceled.
479 void MarkAsCanceled() {
[email protected]b59ff372009-07-15 22:04:32480 job_ = NULL;
[email protected]b59ff372009-07-15 22:04:32481 addresses_ = NULL;
[email protected]aa22b242011-11-16 18:58:29482 callback_.Reset();
[email protected]b59ff372009-07-15 22:04:32483 }
484
[email protected]0f292de02012-02-01 22:28:20485 bool was_canceled() const {
[email protected]aa22b242011-11-16 18:58:29486 return callback_.is_null();
[email protected]b59ff372009-07-15 22:04:32487 }
488
489 void set_job(Job* job) {
[email protected]0f292de02012-02-01 22:28:20490 DCHECK(job);
[email protected]b59ff372009-07-15 22:04:32491 // Identify which job the request is waiting on.
492 job_ = job;
493 }
494
[email protected]0f292de02012-02-01 22:28:20495 // Prepare final AddressList and call completion callback.
[email protected]b3601bc22012-02-21 21:23:20496 void OnComplete(int error, const AddressList& addr_list) {
[email protected]51b9a6b2012-06-25 21:50:29497 DCHECK(!was_canceled());
[email protected]895123222012-10-25 15:21:17498 if (error == OK)
499 *addresses_ = EnsurePortOnAddressList(addr_list, info_.port());
[email protected]aa22b242011-11-16 18:58:29500 CompletionCallback callback = callback_;
[email protected]0f292de02012-02-01 22:28:20501 MarkAsCanceled();
[email protected]aa22b242011-11-16 18:58:29502 callback.Run(error);
[email protected]b59ff372009-07-15 22:04:32503 }
504
[email protected]b59ff372009-07-15 22:04:32505 Job* job() const {
506 return job_;
507 }
508
[email protected]0f292de02012-02-01 22:28:20509 // NetLog for the source, passed in HostResolver::Resolve.
[email protected]ee094b82010-08-24 15:55:51510 const BoundNetLog& source_net_log() {
511 return source_net_log_;
512 }
513
[email protected]0f292de02012-02-01 22:28:20514 // NetLog for this request.
[email protected]ee094b82010-08-24 15:55:51515 const BoundNetLog& request_net_log() {
516 return request_net_log_;
[email protected]54e13772009-08-14 03:01:09517 }
518
[email protected]b59ff372009-07-15 22:04:32519 const RequestInfo& info() const {
520 return info_;
521 }
522
[email protected]5109c1952013-08-20 18:44:10523 RequestPriority priority() const { return priority_; }
524
525 base::TimeTicks request_time() const { return request_time_; }
[email protected]51b9a6b2012-06-25 21:50:29526
[email protected]b59ff372009-07-15 22:04:32527 private:
[email protected]ee094b82010-08-24 15:55:51528 BoundNetLog source_net_log_;
529 BoundNetLog request_net_log_;
[email protected]54e13772009-08-14 03:01:09530
[email protected]b59ff372009-07-15 22:04:32531 // The request info that started the request.
[email protected]5109c1952013-08-20 18:44:10532 const RequestInfo info_;
533
534 // TODO(akalin): Support reprioritization.
535 const RequestPriority priority_;
[email protected]b59ff372009-07-15 22:04:32536
[email protected]0f292de02012-02-01 22:28:20537 // The resolve job that this request is dependent on.
[email protected]b59ff372009-07-15 22:04:32538 Job* job_;
539
540 // The user's callback to invoke when the request completes.
[email protected]aa22b242011-11-16 18:58:29541 CompletionCallback callback_;
[email protected]b59ff372009-07-15 22:04:32542
543 // The address list to save result into.
544 AddressList* addresses_;
545
[email protected]51b9a6b2012-06-25 21:50:29546 const base::TimeTicks request_time_;
547
[email protected]b59ff372009-07-15 22:04:32548 DISALLOW_COPY_AND_ASSIGN(Request);
549};
550
[email protected]1e9bbd22010-10-15 16:42:45551//------------------------------------------------------------------------------
552
[email protected]0f292de02012-02-01 22:28:20553// Calls HostResolverProc on the WorkerPool. Performs retries if necessary.
554//
555// Whenever we try to resolve the host, we post a delayed task to check if host
556// resolution (OnLookupComplete) is completed or not. If the original attempt
557// hasn't completed, then we start another attempt for host resolution. We take
558// the results from the first attempt that finishes and ignore the results from
559// all other attempts.
560//
561// TODO(szym): Move to separate source file for testing and mocking.
562//
563class HostResolverImpl::ProcTask
564 : public base::RefCountedThreadSafe<HostResolverImpl::ProcTask> {
[email protected]b59ff372009-07-15 22:04:32565 public:
[email protected]b3601bc22012-02-21 21:23:20566 typedef base::Callback<void(int net_error,
567 const AddressList& addr_list)> Callback;
[email protected]b59ff372009-07-15 22:04:32568
[email protected]0f292de02012-02-01 22:28:20569 ProcTask(const Key& key,
570 const ProcTaskParams& params,
571 const Callback& callback,
572 const BoundNetLog& job_net_log)
573 : key_(key),
574 params_(params),
575 callback_(callback),
576 origin_loop_(base::MessageLoopProxy::current()),
577 attempt_number_(0),
578 completed_attempt_number_(0),
579 completed_attempt_error_(ERR_UNEXPECTED),
580 had_non_speculative_request_(false),
[email protected]b3601bc22012-02-21 21:23:20581 net_log_(job_net_log) {
[email protected]90499482013-06-01 00:39:50582 if (!params_.resolver_proc.get())
[email protected]0f292de02012-02-01 22:28:20583 params_.resolver_proc = HostResolverProc::GetDefault();
584 // If default is unset, use the system proc.
[email protected]90499482013-06-01 00:39:50585 if (!params_.resolver_proc.get())
[email protected]1ee9afa12013-04-16 14:18:06586 params_.resolver_proc = new SystemHostResolverProc();
[email protected]b59ff372009-07-15 22:04:32587 }
588
[email protected]b59ff372009-07-15 22:04:32589 void Start() {
[email protected]3e9d9cc2011-05-03 21:08:15590 DCHECK(origin_loop_->BelongsToCurrentThread());
[email protected]4da911f2012-06-14 19:45:20591 net_log_.BeginEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK);
[email protected]189163e2011-05-11 01:48:54592 StartLookupAttempt();
593 }
[email protected]252b699b2010-02-05 21:38:06594
[email protected]0f292de02012-02-01 22:28:20595 // Cancels this ProcTask. It will be orphaned. Any outstanding resolve
596 // attempts running on worker threads will continue running. Only once all the
597 // attempts complete will the final reference to this ProcTask be released.
598 void Cancel() {
599 DCHECK(origin_loop_->BelongsToCurrentThread());
600
[email protected]0adcb2b2012-08-15 21:30:46601 if (was_canceled() || was_completed())
[email protected]0f292de02012-02-01 22:28:20602 return;
603
[email protected]0f292de02012-02-01 22:28:20604 callback_.Reset();
[email protected]4da911f2012-06-14 19:45:20605 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK);
[email protected]0f292de02012-02-01 22:28:20606 }
607
608 void set_had_non_speculative_request() {
609 DCHECK(origin_loop_->BelongsToCurrentThread());
610 had_non_speculative_request_ = true;
611 }
612
613 bool was_canceled() const {
614 DCHECK(origin_loop_->BelongsToCurrentThread());
615 return callback_.is_null();
616 }
617
618 bool was_completed() const {
619 DCHECK(origin_loop_->BelongsToCurrentThread());
620 return completed_attempt_number_ > 0;
621 }
622
623 private:
[email protected]a9813302012-04-28 09:29:28624 friend class base::RefCountedThreadSafe<ProcTask>;
625 ~ProcTask() {}
626
[email protected]189163e2011-05-11 01:48:54627 void StartLookupAttempt() {
628 DCHECK(origin_loop_->BelongsToCurrentThread());
629 base::TimeTicks start_time = base::TimeTicks::Now();
630 ++attempt_number_;
631 // Dispatch the lookup attempt to a worker thread.
632 if (!base::WorkerPool::PostTask(
633 FROM_HERE,
[email protected]0f292de02012-02-01 22:28:20634 base::Bind(&ProcTask::DoLookup, this, start_time, attempt_number_),
[email protected]189163e2011-05-11 01:48:54635 true)) {
[email protected]b59ff372009-07-15 22:04:32636 NOTREACHED();
637
638 // Since we could be running within Resolve() right now, we can't just
639 // call OnLookupComplete(). Instead we must wait until Resolve() has
640 // returned (IO_PENDING).
[email protected]3e9d9cc2011-05-03 21:08:15641 origin_loop_->PostTask(
[email protected]189163e2011-05-11 01:48:54642 FROM_HERE,
[email protected]0f292de02012-02-01 22:28:20643 base::Bind(&ProcTask::OnLookupComplete, this, AddressList(),
[email protected]33152acc2011-10-20 23:37:12644 start_time, attempt_number_, ERR_UNEXPECTED, 0));
[email protected]189163e2011-05-11 01:48:54645 return;
[email protected]b59ff372009-07-15 22:04:32646 }
[email protected]13024882011-05-18 23:19:16647
648 net_log_.AddEvent(
649 NetLog::TYPE_HOST_RESOLVER_IMPL_ATTEMPT_STARTED,
[email protected]cd565142012-06-12 16:21:45650 NetLog::IntegerCallback("attempt_number", attempt_number_));
[email protected]13024882011-05-18 23:19:16651
[email protected]0f292de02012-02-01 22:28:20652 // If we don't get the results within a given time, RetryIfNotComplete
653 // will start a new attempt on a different worker thread if none of our
654 // outstanding attempts have completed yet.
655 if (attempt_number_ <= params_.max_retry_attempts) {
[email protected]06ef6d92011-05-19 04:24:58656 origin_loop_->PostDelayedTask(
657 FROM_HERE,
[email protected]0f292de02012-02-01 22:28:20658 base::Bind(&ProcTask::RetryIfNotComplete, this),
[email protected]7e560102012-03-08 20:58:42659 params_.unresponsive_delay);
[email protected]06ef6d92011-05-19 04:24:58660 }
[email protected]b59ff372009-07-15 22:04:32661 }
662
[email protected]6c710ee2010-05-07 07:51:16663 // WARNING: This code runs inside a worker pool. The shutdown code cannot
664 // wait for it to finish, so we must be very careful here about using other
665 // objects (like MessageLoops, Singletons, etc). During shutdown these objects
[email protected]189163e2011-05-11 01:48:54666 // may no longer exist. Multiple DoLookups() could be running in parallel, so
667 // any state inside of |this| must not mutate .
668 void DoLookup(const base::TimeTicks& start_time,
669 const uint32 attempt_number) {
670 AddressList results;
671 int os_error = 0;
[email protected]b59ff372009-07-15 22:04:32672 // Running on the worker thread
[email protected]0f292de02012-02-01 22:28:20673 int error = params_.resolver_proc->Resolve(key_.hostname,
674 key_.address_family,
675 key_.host_resolver_flags,
676 &results,
677 &os_error);
[email protected]b59ff372009-07-15 22:04:32678
[email protected]189163e2011-05-11 01:48:54679 origin_loop_->PostTask(
680 FROM_HERE,
[email protected]0f292de02012-02-01 22:28:20681 base::Bind(&ProcTask::OnLookupComplete, this, results, start_time,
[email protected]33152acc2011-10-20 23:37:12682 attempt_number, error, os_error));
[email protected]189163e2011-05-11 01:48:54683 }
684
[email protected]0f292de02012-02-01 22:28:20685 // Makes next attempt if DoLookup() has not finished (runs on origin thread).
686 void RetryIfNotComplete() {
[email protected]189163e2011-05-11 01:48:54687 DCHECK(origin_loop_->BelongsToCurrentThread());
688
[email protected]0f292de02012-02-01 22:28:20689 if (was_completed() || was_canceled())
[email protected]189163e2011-05-11 01:48:54690 return;
691
[email protected]0f292de02012-02-01 22:28:20692 params_.unresponsive_delay *= params_.retry_factor;
[email protected]189163e2011-05-11 01:48:54693 StartLookupAttempt();
[email protected]b59ff372009-07-15 22:04:32694 }
695
696 // Callback for when DoLookup() completes (runs on origin thread).
[email protected]189163e2011-05-11 01:48:54697 void OnLookupComplete(const AddressList& results,
698 const base::TimeTicks& start_time,
699 const uint32 attempt_number,
700 int error,
701 const int os_error) {
[email protected]3e9d9cc2011-05-03 21:08:15702 DCHECK(origin_loop_->BelongsToCurrentThread());
[email protected]49b70b222013-05-07 21:24:23703 // If results are empty, we should return an error.
704 bool empty_list_on_ok = (error == OK && results.empty());
705 UMA_HISTOGRAM_BOOLEAN("DNS.EmptyAddressListAndNoError", empty_list_on_ok);
706 if (empty_list_on_ok)
707 error = ERR_NAME_NOT_RESOLVED;
[email protected]189163e2011-05-11 01:48:54708
709 bool was_retry_attempt = attempt_number > 1;
710
[email protected]2d3b7762010-10-09 00:35:47711 // Ideally the following code would be part of host_resolver_proc.cc,
[email protected]b3601bc22012-02-21 21:23:20712 // however it isn't safe to call NetworkChangeNotifier from worker threads.
713 // So we do it here on the IO thread instead.
[email protected]189163e2011-05-11 01:48:54714 if (error != OK && NetworkChangeNotifier::IsOffline())
715 error = ERR_INTERNET_DISCONNECTED;
[email protected]2d3b7762010-10-09 00:35:47716
[email protected]b3601bc22012-02-21 21:23:20717 // If this is the first attempt that is finishing later, then record data
718 // for the first attempt. Won't contaminate with retry attempt's data.
[email protected]189163e2011-05-11 01:48:54719 if (!was_retry_attempt)
720 RecordPerformanceHistograms(start_time, error, os_error);
721
722 RecordAttemptHistograms(start_time, attempt_number, error, os_error);
[email protected]f2d8c4212010-02-02 00:56:35723
[email protected]0f292de02012-02-01 22:28:20724 if (was_canceled())
[email protected]b59ff372009-07-15 22:04:32725 return;
726
[email protected]cd565142012-06-12 16:21:45727 NetLog::ParametersCallback net_log_callback;
[email protected]0f292de02012-02-01 22:28:20728 if (error != OK) {
[email protected]cd565142012-06-12 16:21:45729 net_log_callback = base::Bind(&NetLogProcTaskFailedCallback,
730 attempt_number,
731 error,
732 os_error);
[email protected]0f292de02012-02-01 22:28:20733 } else {
[email protected]cd565142012-06-12 16:21:45734 net_log_callback = NetLog::IntegerCallback("attempt_number",
735 attempt_number);
[email protected]0f292de02012-02-01 22:28:20736 }
[email protected]cd565142012-06-12 16:21:45737 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_ATTEMPT_FINISHED,
738 net_log_callback);
[email protected]0f292de02012-02-01 22:28:20739
740 if (was_completed())
741 return;
742
743 // Copy the results from the first worker thread that resolves the host.
744 results_ = results;
745 completed_attempt_number_ = attempt_number;
746 completed_attempt_error_ = error;
747
[email protected]e87b8b512011-06-14 22:12:52748 if (was_retry_attempt) {
749 // If retry attempt finishes before 1st attempt, then get stats on how
750 // much time is saved by having spawned an extra attempt.
751 retry_attempt_finished_time_ = base::TimeTicks::Now();
752 }
753
[email protected]189163e2011-05-11 01:48:54754 if (error != OK) {
[email protected]cd565142012-06-12 16:21:45755 net_log_callback = base::Bind(&NetLogProcTaskFailedCallback,
756 0, error, os_error);
[email protected]ee094b82010-08-24 15:55:51757 } else {
[email protected]cd565142012-06-12 16:21:45758 net_log_callback = results_.CreateNetLogCallback();
[email protected]ee094b82010-08-24 15:55:51759 }
[email protected]cd565142012-06-12 16:21:45760 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK,
761 net_log_callback);
[email protected]ee094b82010-08-24 15:55:51762
[email protected]b3601bc22012-02-21 21:23:20763 callback_.Run(error, results_);
[email protected]b59ff372009-07-15 22:04:32764 }
765
[email protected]189163e2011-05-11 01:48:54766 void RecordPerformanceHistograms(const base::TimeTicks& start_time,
767 const int error,
768 const int os_error) const {
[email protected]3e9d9cc2011-05-03 21:08:15769 DCHECK(origin_loop_->BelongsToCurrentThread());
asvitkinec0fb8022014-08-26 04:39:35770 enum Category { // Used in UMA_HISTOGRAM_ENUMERATION.
[email protected]1e9bbd22010-10-15 16:42:45771 RESOLVE_SUCCESS,
772 RESOLVE_FAIL,
773 RESOLVE_SPECULATIVE_SUCCESS,
774 RESOLVE_SPECULATIVE_FAIL,
775 RESOLVE_MAX, // Bounding value.
776 };
777 int category = RESOLVE_MAX; // Illegal value for later DCHECK only.
778
[email protected]189163e2011-05-11 01:48:54779 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
780 if (error == OK) {
[email protected]1e9bbd22010-10-15 16:42:45781 if (had_non_speculative_request_) {
782 category = RESOLVE_SUCCESS;
783 DNS_HISTOGRAM("DNS.ResolveSuccess", duration);
784 } else {
785 category = RESOLVE_SPECULATIVE_SUCCESS;
786 DNS_HISTOGRAM("DNS.ResolveSpeculativeSuccess", duration);
787 }
[email protected]7e96d792011-06-10 17:08:23788
[email protected]78eac2a2012-03-14 19:09:27789 // Log DNS lookups based on |address_family|. This will help us determine
[email protected]7e96d792011-06-10 17:08:23790 // if IPv4 or IPv4/6 lookups are faster or slower.
791 switch(key_.address_family) {
792 case ADDRESS_FAMILY_IPV4:
793 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_IPV4", duration);
794 break;
795 case ADDRESS_FAMILY_IPV6:
796 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_IPV6", duration);
797 break;
798 case ADDRESS_FAMILY_UNSPECIFIED:
799 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_UNSPEC", duration);
800 break;
801 }
[email protected]1e9bbd22010-10-15 16:42:45802 } else {
803 if (had_non_speculative_request_) {
804 category = RESOLVE_FAIL;
805 DNS_HISTOGRAM("DNS.ResolveFail", duration);
806 } else {
807 category = RESOLVE_SPECULATIVE_FAIL;
808 DNS_HISTOGRAM("DNS.ResolveSpeculativeFail", duration);
809 }
[email protected]78eac2a2012-03-14 19:09:27810 // Log DNS lookups based on |address_family|. This will help us determine
[email protected]7e96d792011-06-10 17:08:23811 // if IPv4 or IPv4/6 lookups are faster or slower.
812 switch(key_.address_family) {
813 case ADDRESS_FAMILY_IPV4:
814 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_IPV4", duration);
815 break;
816 case ADDRESS_FAMILY_IPV6:
817 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_IPV6", duration);
818 break;
819 case ADDRESS_FAMILY_UNSPECIFIED:
820 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_UNSPEC", duration);
821 break;
822 }
[email protected]c833e322010-10-16 23:51:36823 UMA_HISTOGRAM_CUSTOM_ENUMERATION(kOSErrorsForGetAddrinfoHistogramName,
[email protected]189163e2011-05-11 01:48:54824 std::abs(os_error),
[email protected]1e9bbd22010-10-15 16:42:45825 GetAllGetAddrinfoOSErrors());
826 }
[email protected]051b6ab2010-10-18 16:50:46827 DCHECK_LT(category, static_cast<int>(RESOLVE_MAX)); // Be sure it was set.
[email protected]1e9bbd22010-10-15 16:42:45828
829 UMA_HISTOGRAM_ENUMERATION("DNS.ResolveCategory", category, RESOLVE_MAX);
[email protected]1e9bbd22010-10-15 16:42:45830 }
831
[email protected]189163e2011-05-11 01:48:54832 void RecordAttemptHistograms(const base::TimeTicks& start_time,
833 const uint32 attempt_number,
834 const int error,
835 const int os_error) const {
[email protected]0f292de02012-02-01 22:28:20836 DCHECK(origin_loop_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54837 bool first_attempt_to_complete =
838 completed_attempt_number_ == attempt_number;
[email protected]e87b8b512011-06-14 22:12:52839 bool is_first_attempt = (attempt_number == 1);
[email protected]1e9bbd22010-10-15 16:42:45840
[email protected]189163e2011-05-11 01:48:54841 if (first_attempt_to_complete) {
842 // If this was first attempt to complete, then record the resolution
843 // status of the attempt.
844 if (completed_attempt_error_ == OK) {
845 UMA_HISTOGRAM_ENUMERATION(
846 "DNS.AttemptFirstSuccess", attempt_number, 100);
847 } else {
848 UMA_HISTOGRAM_ENUMERATION(
849 "DNS.AttemptFirstFailure", attempt_number, 100);
850 }
851 }
852
853 if (error == OK)
854 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptSuccess", attempt_number, 100);
855 else
856 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptFailure", attempt_number, 100);
857
[email protected]e87b8b512011-06-14 22:12:52858 // If first attempt didn't finish before retry attempt, then calculate stats
859 // on how much time is saved by having spawned an extra attempt.
[email protected]0f292de02012-02-01 22:28:20860 if (!first_attempt_to_complete && is_first_attempt && !was_canceled()) {
[email protected]e87b8b512011-06-14 22:12:52861 DNS_HISTOGRAM("DNS.AttemptTimeSavedByRetry",
862 base::TimeTicks::Now() - retry_attempt_finished_time_);
863 }
864
[email protected]0f292de02012-02-01 22:28:20865 if (was_canceled() || !first_attempt_to_complete) {
[email protected]189163e2011-05-11 01:48:54866 // Count those attempts which completed after the job was already canceled
867 // OR after the job was already completed by an earlier attempt (so in
868 // effect).
869 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptDiscarded", attempt_number, 100);
870
[email protected]0f292de02012-02-01 22:28:20871 // Record if job is canceled.
872 if (was_canceled())
[email protected]189163e2011-05-11 01:48:54873 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptCancelled", attempt_number, 100);
874 }
875
876 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
877 if (error == OK)
878 DNS_HISTOGRAM("DNS.AttemptSuccessDuration", duration);
879 else
880 DNS_HISTOGRAM("DNS.AttemptFailDuration", duration);
881 }
[email protected]1e9bbd22010-10-15 16:42:45882
[email protected]b59ff372009-07-15 22:04:32883 // Set on the origin thread, read on the worker thread.
[email protected]123ab1e32009-10-21 19:12:57884 Key key_;
[email protected]b59ff372009-07-15 22:04:32885
[email protected]0f292de02012-02-01 22:28:20886 // Holds an owning reference to the HostResolverProc that we are going to use.
[email protected]b59ff372009-07-15 22:04:32887 // This may not be the current resolver procedure by the time we call
888 // ResolveAddrInfo, but that's OK... we'll use it anyways, and the owning
889 // reference ensures that it remains valid until we are done.
[email protected]0f292de02012-02-01 22:28:20890 ProcTaskParams params_;
[email protected]b59ff372009-07-15 22:04:32891
[email protected]0f292de02012-02-01 22:28:20892 // The listener to the results of this ProcTask.
893 Callback callback_;
894
895 // Used to post ourselves onto the origin thread.
896 scoped_refptr<base::MessageLoopProxy> origin_loop_;
[email protected]189163e2011-05-11 01:48:54897
898 // Keeps track of the number of attempts we have made so far to resolve the
899 // host. Whenever we start an attempt to resolve the host, we increase this
900 // number.
901 uint32 attempt_number_;
902
903 // The index of the attempt which finished first (or 0 if the job is still in
904 // progress).
905 uint32 completed_attempt_number_;
906
907 // The result (a net error code) from the first attempt to complete.
908 int completed_attempt_error_;
[email protected]252b699b2010-02-05 21:38:06909
[email protected]e87b8b512011-06-14 22:12:52910 // The time when retry attempt was finished.
911 base::TimeTicks retry_attempt_finished_time_;
912
[email protected]252b699b2010-02-05 21:38:06913 // True if a non-speculative request was ever attached to this job
[email protected]0f292de02012-02-01 22:28:20914 // (regardless of whether or not it was later canceled.
[email protected]252b699b2010-02-05 21:38:06915 // This boolean is used for histogramming the duration of jobs used to
916 // service non-speculative requests.
917 bool had_non_speculative_request_;
918
[email protected]b59ff372009-07-15 22:04:32919 AddressList results_;
920
[email protected]ee094b82010-08-24 15:55:51921 BoundNetLog net_log_;
922
[email protected]0f292de02012-02-01 22:28:20923 DISALLOW_COPY_AND_ASSIGN(ProcTask);
[email protected]b59ff372009-07-15 22:04:32924};
925
926//-----------------------------------------------------------------------------
927
[email protected]12faa4c2012-11-06 04:44:18928// Wraps a call to HaveOnlyLoopbackAddresses to be executed on the WorkerPool as
929// it takes 40-100ms and should not block initialization.
930class HostResolverImpl::LoopbackProbeJob {
931 public:
932 explicit LoopbackProbeJob(const base::WeakPtr<HostResolverImpl>& resolver)
933 : resolver_(resolver),
934 result_(false) {
[email protected]11fbca0b2013-06-02 23:37:21935 DCHECK(resolver.get());
[email protected]12faa4c2012-11-06 04:44:18936 const bool kIsSlow = true;
937 base::WorkerPool::PostTaskAndReply(
938 FROM_HERE,
939 base::Bind(&LoopbackProbeJob::DoProbe, base::Unretained(this)),
940 base::Bind(&LoopbackProbeJob::OnProbeComplete, base::Owned(this)),
941 kIsSlow);
942 }
943
944 virtual ~LoopbackProbeJob() {}
945
946 private:
947 // Runs on worker thread.
948 void DoProbe() {
949 result_ = HaveOnlyLoopbackAddresses();
950 }
951
952 void OnProbeComplete() {
[email protected]11fbca0b2013-06-02 23:37:21953 if (!resolver_.get())
[email protected]12faa4c2012-11-06 04:44:18954 return;
955 resolver_->SetHaveOnlyLoopbackAddresses(result_);
956 }
957
958 // Used/set only on origin thread.
959 base::WeakPtr<HostResolverImpl> resolver_;
960
961 bool result_;
962
963 DISALLOW_COPY_AND_ASSIGN(LoopbackProbeJob);
964};
965
[email protected]0f8f1b432010-03-16 19:06:03966//-----------------------------------------------------------------------------
967
[email protected]b3601bc22012-02-21 21:23:20968// Resolves the hostname using DnsTransaction.
969// TODO(szym): This could be moved to separate source file as well.
[email protected]0adcb2b2012-08-15 21:30:46970class HostResolverImpl::DnsTask : public base::SupportsWeakPtr<DnsTask> {
[email protected]b3601bc22012-02-21 21:23:20971 public:
[email protected]daae1322013-09-05 18:26:50972 class Delegate {
973 public:
974 virtual void OnDnsTaskComplete(base::TimeTicks start_time,
975 int net_error,
976 const AddressList& addr_list,
977 base::TimeDelta ttl) = 0;
978
979 // Called when the first of two jobs succeeds. If the first completed
980 // transaction fails, this is not called. Also not called when the DnsTask
981 // only needs to run one transaction.
982 virtual void OnFirstDnsTransactionComplete() = 0;
983
984 protected:
985 Delegate() {}
986 virtual ~Delegate() {}
987 };
[email protected]b3601bc22012-02-21 21:23:20988
[email protected]0adcb2b2012-08-15 21:30:46989 DnsTask(DnsClient* client,
[email protected]b3601bc22012-02-21 21:23:20990 const Key& key,
[email protected]daae1322013-09-05 18:26:50991 Delegate* delegate,
[email protected]b3601bc22012-02-21 21:23:20992 const BoundNetLog& job_net_log)
[email protected]0adcb2b2012-08-15 21:30:46993 : client_(client),
[email protected]daae1322013-09-05 18:26:50994 key_(key),
995 delegate_(delegate),
996 net_log_(job_net_log),
997 num_completed_transactions_(0),
998 task_start_time_(base::TimeTicks::Now()) {
[email protected]0adcb2b2012-08-15 21:30:46999 DCHECK(client);
[email protected]daae1322013-09-05 18:26:501000 DCHECK(delegate_);
[email protected]1affed62013-08-21 03:24:501001 }
1002
[email protected]daae1322013-09-05 18:26:501003 bool needs_two_transactions() const {
1004 return key_.address_family == ADDRESS_FAMILY_UNSPECIFIED;
1005 }
1006
1007 bool needs_another_transaction() const {
1008 return needs_two_transactions() && !transaction_aaaa_;
1009 }
1010
1011 void StartFirstTransaction() {
1012 DCHECK_EQ(0u, num_completed_transactions_);
[email protected]70c04ab2013-08-22 16:05:121013 net_log_.BeginEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK);
[email protected]daae1322013-09-05 18:26:501014 if (key_.address_family == ADDRESS_FAMILY_IPV6) {
1015 StartAAAA();
1016 } else {
1017 StartA();
1018 }
1019 }
1020
1021 void StartSecondTransaction() {
1022 DCHECK(needs_two_transactions());
1023 StartAAAA();
[email protected]70c04ab2013-08-22 16:05:121024 }
1025
1026 private:
[email protected]daae1322013-09-05 18:26:501027 void StartA() {
1028 DCHECK(!transaction_a_);
1029 DCHECK_NE(ADDRESS_FAMILY_IPV6, key_.address_family);
1030 transaction_a_ = CreateTransaction(ADDRESS_FAMILY_IPV4);
1031 transaction_a_->Start();
1032 }
1033
1034 void StartAAAA() {
1035 DCHECK(!transaction_aaaa_);
1036 DCHECK_NE(ADDRESS_FAMILY_IPV4, key_.address_family);
1037 transaction_aaaa_ = CreateTransaction(ADDRESS_FAMILY_IPV6);
1038 transaction_aaaa_->Start();
1039 }
1040
1041 scoped_ptr<DnsTransaction> CreateTransaction(AddressFamily family) {
1042 DCHECK_NE(ADDRESS_FAMILY_UNSPECIFIED, family);
1043 return client_->GetTransactionFactory()->CreateTransaction(
1044 key_.hostname,
1045 family == ADDRESS_FAMILY_IPV6 ? dns_protocol::kTypeAAAA :
1046 dns_protocol::kTypeA,
1047 base::Bind(&DnsTask::OnTransactionComplete, base::Unretained(this),
1048 base::TimeTicks::Now()),
1049 net_log_);
1050 }
1051
1052 void OnTransactionComplete(const base::TimeTicks& start_time,
[email protected]1def74c2012-03-22 20:07:001053 DnsTransaction* transaction,
[email protected]b3601bc22012-02-21 21:23:201054 int net_error,
1055 const DnsResponse* response) {
[email protected]add76532012-03-30 14:47:471056 DCHECK(transaction);
[email protected]02cd6982013-01-10 20:12:511057 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]0adcb2b2012-08-15 21:30:461058 if (net_error != OK) {
[email protected]02cd6982013-01-10 20:12:511059 DNS_HISTOGRAM("AsyncDNS.TransactionFailure", duration);
[email protected]0adcb2b2012-08-15 21:30:461060 OnFailure(net_error, DnsResponse::DNS_PARSE_OK);
1061 return;
[email protected]6c411902012-08-14 22:36:361062 }
[email protected]0adcb2b2012-08-15 21:30:461063
[email protected]02cd6982013-01-10 20:12:511064 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess", duration);
1065 switch (transaction->GetType()) {
1066 case dns_protocol::kTypeA:
1067 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess_A", duration);
1068 break;
1069 case dns_protocol::kTypeAAAA:
1070 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess_AAAA", duration);
1071 break;
1072 }
[email protected]daae1322013-09-05 18:26:501073
[email protected]0adcb2b2012-08-15 21:30:461074 AddressList addr_list;
1075 base::TimeDelta ttl;
1076 DnsResponse::Result result = response->ParseToAddressList(&addr_list, &ttl);
1077 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ParseToAddressList",
1078 result,
1079 DnsResponse::DNS_PARSE_RESULT_MAX);
1080 if (result != DnsResponse::DNS_PARSE_OK) {
1081 // Fail even if the other query succeeds.
1082 OnFailure(ERR_DNS_MALFORMED_RESPONSE, result);
1083 return;
1084 }
1085
[email protected]daae1322013-09-05 18:26:501086 ++num_completed_transactions_;
1087 if (num_completed_transactions_ == 1) {
1088 ttl_ = ttl;
[email protected]0adcb2b2012-08-15 21:30:461089 } else {
[email protected]daae1322013-09-05 18:26:501090 ttl_ = std::min(ttl_, ttl);
[email protected]0adcb2b2012-08-15 21:30:461091 }
1092
[email protected]daae1322013-09-05 18:26:501093 if (transaction->GetType() == dns_protocol::kTypeA) {
1094 DCHECK_EQ(transaction_a_.get(), transaction);
1095 // Place IPv4 addresses after IPv6.
1096 addr_list_.insert(addr_list_.end(), addr_list.begin(), addr_list.end());
1097 } else {
1098 DCHECK_EQ(transaction_aaaa_.get(), transaction);
1099 // Place IPv6 addresses before IPv4.
1100 addr_list_.insert(addr_list_.begin(), addr_list.begin(), addr_list.end());
1101 }
1102
1103 if (needs_two_transactions() && num_completed_transactions_ == 1) {
1104 // No need to repeat the suffix search.
1105 key_.hostname = transaction->GetHostname();
1106 delegate_->OnFirstDnsTransactionComplete();
1107 return;
1108 }
1109
1110 if (addr_list_.empty()) {
[email protected]70c04ab2013-08-22 16:05:121111 // TODO(szym): Don't fallback to ProcTask in this case.
1112 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
[email protected]0adcb2b2012-08-15 21:30:461113 return;
1114 }
1115
[email protected]daae1322013-09-05 18:26:501116 // If there are multiple addresses, and at least one is IPv6, need to sort
1117 // them. Note that IPv6 addresses are always put before IPv4 ones, so it's
1118 // sufficient to just check the family of the first address.
1119 if (addr_list_.size() > 1 &&
1120 addr_list_[0].GetFamily() == ADDRESS_FAMILY_IPV6) {
1121 // Sort addresses if needed. Sort could complete synchronously.
[email protected]0adcb2b2012-08-15 21:30:461122 client_->GetAddressSorter()->Sort(
[email protected]daae1322013-09-05 18:26:501123 addr_list_,
[email protected]4589a3a2012-09-20 20:57:071124 base::Bind(&DnsTask::OnSortComplete,
1125 AsWeakPtr(),
[email protected]daae1322013-09-05 18:26:501126 base::TimeTicks::Now()));
[email protected]0adcb2b2012-08-15 21:30:461127 } else {
[email protected]daae1322013-09-05 18:26:501128 OnSuccess(addr_list_);
[email protected]0adcb2b2012-08-15 21:30:461129 }
1130 }
1131
1132 void OnSortComplete(base::TimeTicks start_time,
[email protected]0adcb2b2012-08-15 21:30:461133 bool success,
1134 const AddressList& addr_list) {
1135 if (!success) {
1136 DNS_HISTOGRAM("AsyncDNS.SortFailure",
1137 base::TimeTicks::Now() - start_time);
1138 OnFailure(ERR_DNS_SORT_ERROR, DnsResponse::DNS_PARSE_OK);
1139 return;
1140 }
1141
1142 DNS_HISTOGRAM("AsyncDNS.SortSuccess",
1143 base::TimeTicks::Now() - start_time);
1144
1145 // AddressSorter prunes unusable destinations.
1146 if (addr_list.empty()) {
1147 LOG(WARNING) << "Address list empty after RFC3484 sort";
1148 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
1149 return;
1150 }
1151
[email protected]daae1322013-09-05 18:26:501152 OnSuccess(addr_list);
[email protected]0adcb2b2012-08-15 21:30:461153 }
1154
1155 void OnFailure(int net_error, DnsResponse::Result result) {
1156 DCHECK_NE(OK, net_error);
[email protected]cd565142012-06-12 16:21:451157 net_log_.EndEvent(
1158 NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK,
1159 base::Bind(&NetLogDnsTaskFailedCallback, net_error, result));
[email protected]daae1322013-09-05 18:26:501160 delegate_->OnDnsTaskComplete(task_start_time_, net_error, AddressList(),
1161 base::TimeDelta());
[email protected]b3601bc22012-02-21 21:23:201162 }
1163
[email protected]daae1322013-09-05 18:26:501164 void OnSuccess(const AddressList& addr_list) {
[email protected]0adcb2b2012-08-15 21:30:461165 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK,
1166 addr_list.CreateNetLogCallback());
[email protected]daae1322013-09-05 18:26:501167 delegate_->OnDnsTaskComplete(task_start_time_, OK, addr_list, ttl_);
[email protected]0adcb2b2012-08-15 21:30:461168 }
1169
1170 DnsClient* client_;
[email protected]daae1322013-09-05 18:26:501171 Key key_;
1172
[email protected]b3601bc22012-02-21 21:23:201173 // The listener to the results of this DnsTask.
[email protected]daae1322013-09-05 18:26:501174 Delegate* delegate_;
[email protected]b3601bc22012-02-21 21:23:201175 const BoundNetLog net_log_;
1176
[email protected]daae1322013-09-05 18:26:501177 scoped_ptr<DnsTransaction> transaction_a_;
1178 scoped_ptr<DnsTransaction> transaction_aaaa_;
[email protected]0adcb2b2012-08-15 21:30:461179
[email protected]daae1322013-09-05 18:26:501180 unsigned num_completed_transactions_;
1181
1182 // These are updated as each transaction completes.
1183 base::TimeDelta ttl_;
1184 // IPv6 addresses must appear first in the list.
1185 AddressList addr_list_;
1186
1187 base::TimeTicks task_start_time_;
[email protected]0adcb2b2012-08-15 21:30:461188
1189 DISALLOW_COPY_AND_ASSIGN(DnsTask);
[email protected]b3601bc22012-02-21 21:23:201190};
1191
1192//-----------------------------------------------------------------------------
1193
[email protected]0f292de02012-02-01 22:28:201194// Aggregates all Requests for the same Key. Dispatched via PriorityDispatch.
[email protected]daae1322013-09-05 18:26:501195class HostResolverImpl::Job : public PrioritizedDispatcher::Job,
1196 public HostResolverImpl::DnsTask::Delegate {
[email protected]68ad3ee2010-01-30 03:45:391197 public:
[email protected]0f292de02012-02-01 22:28:201198 // Creates new job for |key| where |request_net_log| is bound to the
[email protected]16ee26d2012-03-08 03:34:351199 // request that spawned it.
[email protected]12faa4c2012-11-06 04:44:181200 Job(const base::WeakPtr<HostResolverImpl>& resolver,
[email protected]0f292de02012-02-01 22:28:201201 const Key& key,
[email protected]8c98d002012-07-18 19:02:271202 RequestPriority priority,
[email protected]16ee26d2012-03-08 03:34:351203 const BoundNetLog& request_net_log)
[email protected]12faa4c2012-11-06 04:44:181204 : resolver_(resolver),
[email protected]0f292de02012-02-01 22:28:201205 key_(key),
[email protected]8c98d002012-07-18 19:02:271206 priority_tracker_(priority),
[email protected]0f292de02012-02-01 22:28:201207 had_non_speculative_request_(false),
[email protected]51b9a6b2012-06-25 21:50:291208 had_dns_config_(false),
[email protected]daae1322013-09-05 18:26:501209 num_occupied_job_slots_(0),
[email protected]1d932852012-06-19 19:40:331210 dns_task_error_(OK),
[email protected]51b9a6b2012-06-25 21:50:291211 creation_time_(base::TimeTicks::Now()),
1212 priority_change_time_(creation_time_),
[email protected]0f292de02012-02-01 22:28:201213 net_log_(BoundNetLog::Make(request_net_log.net_log(),
[email protected]b3601bc22012-02-21 21:23:201214 NetLog::SOURCE_HOST_RESOLVER_IMPL_JOB)) {
[email protected]4da911f2012-06-14 19:45:201215 request_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_CREATE_JOB);
[email protected]0f292de02012-02-01 22:28:201216
1217 net_log_.BeginEvent(
1218 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
[email protected]cd565142012-06-12 16:21:451219 base::Bind(&NetLogJobCreationCallback,
1220 request_net_log.source(),
1221 &key_.hostname));
[email protected]68ad3ee2010-01-30 03:45:391222 }
1223
dchengb03027d2014-10-21 12:00:201224 ~Job() override {
[email protected]b3601bc22012-02-21 21:23:201225 if (is_running()) {
1226 // |resolver_| was destroyed with this Job still in flight.
1227 // Clean-up, record in the log, but don't run any callbacks.
1228 if (is_proc_running()) {
[email protected]0f292de02012-02-01 22:28:201229 proc_task_->Cancel();
1230 proc_task_ = NULL;
[email protected]0f292de02012-02-01 22:28:201231 }
[email protected]16ee26d2012-03-08 03:34:351232 // Clean up now for nice NetLog.
[email protected]daae1322013-09-05 18:26:501233 KillDnsTask();
[email protected]b3601bc22012-02-21 21:23:201234 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
1235 ERR_ABORTED);
1236 } else if (is_queued()) {
[email protected]57a48d32012-03-03 00:04:551237 // |resolver_| was destroyed without running this Job.
[email protected]16ee26d2012-03-08 03:34:351238 // TODO(szym): is there any benefit in having this distinction?
[email protected]4da911f2012-06-14 19:45:201239 net_log_.AddEvent(NetLog::TYPE_CANCELLED);
1240 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB);
[email protected]68ad3ee2010-01-30 03:45:391241 }
[email protected]b3601bc22012-02-21 21:23:201242 // else CompleteRequests logged EndEvent.
[email protected]68ad3ee2010-01-30 03:45:391243
[email protected]b3601bc22012-02-21 21:23:201244 // Log any remaining Requests as cancelled.
1245 for (RequestsList::const_iterator it = requests_.begin();
1246 it != requests_.end(); ++it) {
1247 Request* req = *it;
1248 if (req->was_canceled())
1249 continue;
1250 DCHECK_EQ(this, req->job());
1251 LogCancelRequest(req->source_net_log(), req->request_net_log(),
1252 req->info());
1253 }
[email protected]68ad3ee2010-01-30 03:45:391254 }
1255
[email protected]daae1322013-09-05 18:26:501256 // Add this job to the dispatcher. If "at_head" is true, adds at the front
1257 // of the queue.
1258 void Schedule(bool at_head) {
1259 DCHECK(!is_queued());
1260 PrioritizedDispatcher::Handle handle;
1261 if (!at_head) {
[email protected]106ccd2c2014-06-17 09:21:001262 handle = resolver_->dispatcher_->Add(this, priority());
[email protected]daae1322013-09-05 18:26:501263 } else {
[email protected]106ccd2c2014-06-17 09:21:001264 handle = resolver_->dispatcher_->AddAtHead(this, priority());
[email protected]daae1322013-09-05 18:26:501265 }
1266 // The dispatcher could have started |this| in the above call to Add, which
1267 // could have called Schedule again. In that case |handle| will be null,
1268 // but |handle_| may have been set by the other nested call to Schedule.
1269 if (!handle.is_null()) {
1270 DCHECK(handle_.is_null());
1271 handle_ = handle;
1272 }
[email protected]16ee26d2012-03-08 03:34:351273 }
1274
[email protected]b3601bc22012-02-21 21:23:201275 void AddRequest(scoped_ptr<Request> req) {
[email protected]0f292de02012-02-01 22:28:201276 DCHECK_EQ(key_.hostname, req->info().hostname());
1277
1278 req->set_job(this);
[email protected]5109c1952013-08-20 18:44:101279 priority_tracker_.Add(req->priority());
[email protected]0f292de02012-02-01 22:28:201280
1281 req->request_net_log().AddEvent(
1282 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_ATTACH,
[email protected]cd565142012-06-12 16:21:451283 net_log_.source().ToEventParametersCallback());
[email protected]0f292de02012-02-01 22:28:201284
1285 net_log_.AddEvent(
1286 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_REQUEST_ATTACH,
[email protected]cd565142012-06-12 16:21:451287 base::Bind(&NetLogJobAttachCallback,
1288 req->request_net_log().source(),
1289 priority()));
[email protected]0f292de02012-02-01 22:28:201290
1291 // TODO(szym): Check if this is still needed.
1292 if (!req->info().is_speculative()) {
1293 had_non_speculative_request_ = true;
[email protected]90499482013-06-01 00:39:501294 if (proc_task_.get())
[email protected]0f292de02012-02-01 22:28:201295 proc_task_->set_had_non_speculative_request();
[email protected]68ad3ee2010-01-30 03:45:391296 }
[email protected]b3601bc22012-02-21 21:23:201297
1298 requests_.push_back(req.release());
1299
[email protected]51b9a6b2012-06-25 21:50:291300 UpdatePriority();
[email protected]68ad3ee2010-01-30 03:45:391301 }
1302
[email protected]16ee26d2012-03-08 03:34:351303 // Marks |req| as cancelled. If it was the last active Request, also finishes
[email protected]0adcb2b2012-08-15 21:30:461304 // this Job, marking it as cancelled, and deletes it.
[email protected]0f292de02012-02-01 22:28:201305 void CancelRequest(Request* req) {
1306 DCHECK_EQ(key_.hostname, req->info().hostname());
1307 DCHECK(!req->was_canceled());
[email protected]16ee26d2012-03-08 03:34:351308
[email protected]0f292de02012-02-01 22:28:201309 // Don't remove it from |requests_| just mark it canceled.
1310 req->MarkAsCanceled();
1311 LogCancelRequest(req->source_net_log(), req->request_net_log(),
1312 req->info());
[email protected]16ee26d2012-03-08 03:34:351313
[email protected]5109c1952013-08-20 18:44:101314 priority_tracker_.Remove(req->priority());
1315 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_REQUEST_DETACH,
1316 base::Bind(&NetLogJobAttachCallback,
1317 req->request_net_log().source(),
1318 priority()));
[email protected]b3601bc22012-02-21 21:23:201319
[email protected]16ee26d2012-03-08 03:34:351320 if (num_active_requests() > 0) {
[email protected]51b9a6b2012-06-25 21:50:291321 UpdatePriority();
[email protected]16ee26d2012-03-08 03:34:351322 } else {
1323 // If we were called from a Request's callback within CompleteRequests,
1324 // that Request could not have been cancelled, so num_active_requests()
1325 // could not be 0. Therefore, we are not in CompleteRequests().
[email protected]1339a2a22012-10-17 08:39:431326 CompleteRequestsWithError(OK /* cancelled */);
[email protected]b3601bc22012-02-21 21:23:201327 }
[email protected]68ad3ee2010-01-30 03:45:391328 }
1329
[email protected]7af985a2012-12-14 22:40:421330 // Called from AbortAllInProgressJobs. Completes all requests and destroys
1331 // the job. This currently assumes the abort is due to a network change.
[email protected]0f292de02012-02-01 22:28:201332 void Abort() {
[email protected]0f292de02012-02-01 22:28:201333 DCHECK(is_running());
[email protected]7af985a2012-12-14 22:40:421334 CompleteRequestsWithError(ERR_NETWORK_CHANGED);
[email protected]b3601bc22012-02-21 21:23:201335 }
1336
[email protected]f0f602bd2012-11-15 18:01:021337 // If DnsTask present, abort it and fall back to ProcTask.
1338 void AbortDnsTask() {
1339 if (dns_task_) {
[email protected]daae1322013-09-05 18:26:501340 KillDnsTask();
[email protected]f0f602bd2012-11-15 18:01:021341 dns_task_error_ = OK;
1342 StartProcTask();
1343 }
1344 }
1345
[email protected]16ee26d2012-03-08 03:34:351346 // Called by HostResolverImpl when this job is evicted due to queue overflow.
1347 // Completes all requests and destroys the job.
1348 void OnEvicted() {
1349 DCHECK(!is_running());
1350 DCHECK(is_queued());
1351 handle_.Reset();
1352
[email protected]4da911f2012-06-14 19:45:201353 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_EVICTED);
[email protected]16ee26d2012-03-08 03:34:351354
1355 // This signals to CompleteRequests that this job never ran.
[email protected]1339a2a22012-10-17 08:39:431356 CompleteRequestsWithError(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
[email protected]16ee26d2012-03-08 03:34:351357 }
1358
[email protected]78eac2a2012-03-14 19:09:271359 // Attempts to serve the job from HOSTS. Returns true if succeeded and
1360 // this Job was destroyed.
1361 bool ServeFromHosts() {
1362 DCHECK_GT(num_active_requests(), 0u);
1363 AddressList addr_list;
1364 if (resolver_->ServeFromHosts(key(),
[email protected]3cb676a12012-06-30 15:46:031365 requests_.front()->info(),
[email protected]78eac2a2012-03-14 19:09:271366 &addr_list)) {
1367 // This will destroy the Job.
[email protected]895123222012-10-25 15:21:171368 CompleteRequests(
1369 HostCache::Entry(OK, MakeAddressListForRequest(addr_list)),
1370 base::TimeDelta());
[email protected]78eac2a2012-03-14 19:09:271371 return true;
1372 }
1373 return false;
1374 }
1375
[email protected]b4481b222012-03-16 17:13:111376 const Key key() const {
1377 return key_;
1378 }
1379
1380 bool is_queued() const {
1381 return !handle_.is_null();
1382 }
1383
1384 bool is_running() const {
1385 return is_dns_running() || is_proc_running();
1386 }
1387
[email protected]16ee26d2012-03-08 03:34:351388 private:
[email protected]daae1322013-09-05 18:26:501389 void KillDnsTask() {
1390 if (dns_task_) {
1391 ReduceToOneJobSlot();
1392 dns_task_.reset();
1393 }
1394 }
1395
1396 // Reduce the number of job slots occupied and queued in the dispatcher
1397 // to one. If the second Job slot is queued in the dispatcher, cancels the
1398 // queued job. Otherwise, the second Job has been started by the
1399 // PrioritizedDispatcher, so signals it is complete.
1400 void ReduceToOneJobSlot() {
1401 DCHECK_GE(num_occupied_job_slots_, 1u);
1402 if (is_queued()) {
[email protected]106ccd2c2014-06-17 09:21:001403 resolver_->dispatcher_->Cancel(handle_);
[email protected]daae1322013-09-05 18:26:501404 handle_.Reset();
1405 } else if (num_occupied_job_slots_ > 1) {
[email protected]106ccd2c2014-06-17 09:21:001406 resolver_->dispatcher_->OnJobFinished();
[email protected]daae1322013-09-05 18:26:501407 --num_occupied_job_slots_;
1408 }
1409 DCHECK_EQ(1u, num_occupied_job_slots_);
1410 }
1411
[email protected]51b9a6b2012-06-25 21:50:291412 void UpdatePriority() {
1413 if (is_queued()) {
1414 if (priority() != static_cast<RequestPriority>(handle_.priority()))
1415 priority_change_time_ = base::TimeTicks::Now();
[email protected]106ccd2c2014-06-17 09:21:001416 handle_ = resolver_->dispatcher_->ChangePriority(handle_, priority());
[email protected]51b9a6b2012-06-25 21:50:291417 }
1418 }
1419
[email protected]895123222012-10-25 15:21:171420 AddressList MakeAddressListForRequest(const AddressList& list) const {
1421 if (requests_.empty())
1422 return list;
1423 return AddressList::CopyWithPort(list, requests_.front()->info().port());
1424 }
1425
[email protected]16ee26d2012-03-08 03:34:351426 // PriorityDispatch::Job:
dchengb03027d2014-10-21 12:00:201427 void Start() override {
[email protected]daae1322013-09-05 18:26:501428 DCHECK_LE(num_occupied_job_slots_, 1u);
1429
[email protected]70c04ab2013-08-22 16:05:121430 handle_.Reset();
[email protected]daae1322013-09-05 18:26:501431 ++num_occupied_job_slots_;
1432
1433 if (num_occupied_job_slots_ == 2) {
1434 StartSecondDnsTransaction();
1435 return;
1436 }
1437
1438 DCHECK(!is_running());
[email protected]0f292de02012-02-01 22:28:201439
[email protected]4da911f2012-06-14 19:45:201440 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_STARTED);
[email protected]0f292de02012-02-01 22:28:201441
[email protected]51b9a6b2012-06-25 21:50:291442 had_dns_config_ = resolver_->HaveDnsConfig();
1443
1444 base::TimeTicks now = base::TimeTicks::Now();
1445 base::TimeDelta queue_time = now - creation_time_;
1446 base::TimeDelta queue_time_after_change = now - priority_change_time_;
1447
1448 if (had_dns_config_) {
1449 DNS_HISTOGRAM_BY_PRIORITY("AsyncDNS.JobQueueTime", priority(),
1450 queue_time);
1451 DNS_HISTOGRAM_BY_PRIORITY("AsyncDNS.JobQueueTimeAfterChange", priority(),
1452 queue_time_after_change);
1453 } else {
1454 DNS_HISTOGRAM_BY_PRIORITY("DNS.JobQueueTime", priority(), queue_time);
1455 DNS_HISTOGRAM_BY_PRIORITY("DNS.JobQueueTimeAfterChange", priority(),
1456 queue_time_after_change);
1457 }
1458
[email protected]443714fad2013-09-19 04:52:011459 bool system_only =
1460 (key_.host_resolver_flags & HOST_RESOLVER_SYSTEM_ONLY) != 0;
1461
[email protected]1d932852012-06-19 19:40:331462 // Caution: Job::Start must not complete synchronously.
[email protected]443714fad2013-09-19 04:52:011463 if (!system_only && had_dns_config_ &&
1464 !ResemblesMulticastDNSName(key_.hostname)) {
[email protected]b3601bc22012-02-21 21:23:201465 StartDnsTask();
1466 } else {
1467 StartProcTask();
1468 }
1469 }
1470
[email protected]b3601bc22012-02-21 21:23:201471 // TODO(szym): Since DnsTransaction does not consume threads, we can increase
1472 // the limits on |dispatcher_|. But in order to keep the number of WorkerPool
1473 // threads low, we will need to use an "inner" PrioritizedDispatcher with
1474 // tighter limits.
1475 void StartProcTask() {
[email protected]16ee26d2012-03-08 03:34:351476 DCHECK(!is_dns_running());
[email protected]0f292de02012-02-01 22:28:201477 proc_task_ = new ProcTask(
1478 key_,
1479 resolver_->proc_params_,
[email protected]e3bd4822012-10-23 18:01:371480 base::Bind(&Job::OnProcTaskComplete, base::Unretained(this),
1481 base::TimeTicks::Now()),
[email protected]0f292de02012-02-01 22:28:201482 net_log_);
1483
1484 if (had_non_speculative_request_)
1485 proc_task_->set_had_non_speculative_request();
1486 // Start() could be called from within Resolve(), hence it must NOT directly
1487 // call OnProcTaskComplete, for example, on synchronous failure.
1488 proc_task_->Start();
[email protected]68ad3ee2010-01-30 03:45:391489 }
1490
[email protected]0f292de02012-02-01 22:28:201491 // Called by ProcTask when it completes.
[email protected]e3bd4822012-10-23 18:01:371492 void OnProcTaskComplete(base::TimeTicks start_time,
1493 int net_error,
1494 const AddressList& addr_list) {
[email protected]b3601bc22012-02-21 21:23:201495 DCHECK(is_proc_running());
[email protected]68ad3ee2010-01-30 03:45:391496
[email protected]62e86ba2013-01-29 18:59:161497 if (!resolver_->resolved_known_ipv6_hostname_ &&
1498 net_error == OK &&
1499 key_.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
1500 if (key_.hostname == "www.google.com") {
1501 resolver_->resolved_known_ipv6_hostname_ = true;
1502 bool got_ipv6_address = false;
1503 for (size_t i = 0; i < addr_list.size(); ++i) {
[email protected]5134c22a2013-08-06 18:09:021504 if (addr_list[i].GetFamily() == ADDRESS_FAMILY_IPV6) {
[email protected]62e86ba2013-01-29 18:59:161505 got_ipv6_address = true;
[email protected]5134c22a2013-08-06 18:09:021506 break;
1507 }
[email protected]62e86ba2013-01-29 18:59:161508 }
1509 UMA_HISTOGRAM_BOOLEAN("Net.UnspecResolvedIPv6", got_ipv6_address);
1510 }
1511 }
1512
[email protected]1d932852012-06-19 19:40:331513 if (dns_task_error_ != OK) {
[email protected]e3bd4822012-10-23 18:01:371514 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]1def74c2012-03-22 20:07:001515 if (net_error == OK) {
[email protected]e3bd4822012-10-23 18:01:371516 DNS_HISTOGRAM("AsyncDNS.FallbackSuccess", duration);
[email protected]1d932852012-06-19 19:40:331517 if ((dns_task_error_ == ERR_NAME_NOT_RESOLVED) &&
1518 ResemblesNetBIOSName(key_.hostname)) {
1519 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_SUSPECT_NETBIOS);
1520 } else {
1521 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_PROC_SUCCESS);
1522 }
1523 UMA_HISTOGRAM_CUSTOM_ENUMERATION("AsyncDNS.ResolveError",
1524 std::abs(dns_task_error_),
1525 GetAllErrorCodesForUma());
[email protected]1ffdda82012-12-12 23:04:221526 resolver_->OnDnsTaskResolve(dns_task_error_);
[email protected]1def74c2012-03-22 20:07:001527 } else {
[email protected]e3bd4822012-10-23 18:01:371528 DNS_HISTOGRAM("AsyncDNS.FallbackFail", duration);
[email protected]1def74c2012-03-22 20:07:001529 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
1530 }
1531 }
1532
[email protected]1339a2a22012-10-17 08:39:431533 base::TimeDelta ttl =
1534 base::TimeDelta::FromSeconds(kNegativeCacheEntryTTLSeconds);
[email protected]b3601bc22012-02-21 21:23:201535 if (net_error == OK)
1536 ttl = base::TimeDelta::FromSeconds(kCacheEntryTTLSeconds);
[email protected]68ad3ee2010-01-30 03:45:391537
[email protected]895123222012-10-25 15:21:171538 // Don't store the |ttl| in cache since it's not obtained from the server.
1539 CompleteRequests(
1540 HostCache::Entry(net_error, MakeAddressListForRequest(addr_list)),
1541 ttl);
[email protected]b3601bc22012-02-21 21:23:201542 }
1543
1544 void StartDnsTask() {
[email protected]78eac2a2012-03-14 19:09:271545 DCHECK(resolver_->HaveDnsConfig());
[email protected]daae1322013-09-05 18:26:501546 dns_task_.reset(new DnsTask(resolver_->dns_client_.get(), key_, this,
1547 net_log_));
[email protected]b3601bc22012-02-21 21:23:201548
[email protected]daae1322013-09-05 18:26:501549 dns_task_->StartFirstTransaction();
1550 // Schedule a second transaction, if needed.
1551 if (dns_task_->needs_two_transactions())
1552 Schedule(true);
1553 }
1554
1555 void StartSecondDnsTransaction() {
1556 DCHECK(dns_task_->needs_two_transactions());
1557 dns_task_->StartSecondTransaction();
[email protected]16c2bd72013-06-28 01:19:221558 }
1559
1560 // Called if DnsTask fails. It is posted from StartDnsTask, so Job may be
1561 // deleted before this callback. In this case dns_task is deleted as well,
1562 // so we use it as indicator whether Job is still valid.
1563 void OnDnsTaskFailure(const base::WeakPtr<DnsTask>& dns_task,
1564 base::TimeDelta duration,
1565 int net_error) {
1566 DNS_HISTOGRAM("AsyncDNS.ResolveFail", duration);
1567
1568 if (dns_task == NULL)
1569 return;
1570
1571 dns_task_error_ = net_error;
1572
1573 // TODO(szym): Run ServeFromHosts now if nsswitch.conf says so.
1574 // http://crbug.com/117655
1575
1576 // TODO(szym): Some net errors indicate lack of connectivity. Starting
1577 // ProcTask in that case is a waste of time.
1578 if (resolver_->fallback_to_proctask_) {
[email protected]daae1322013-09-05 18:26:501579 KillDnsTask();
[email protected]16c2bd72013-06-28 01:19:221580 StartProcTask();
1581 } else {
1582 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
1583 CompleteRequestsWithError(net_error);
[email protected]b3601bc22012-02-21 21:23:201584 }
1585 }
1586
[email protected]daae1322013-09-05 18:26:501587
1588 // HostResolverImpl::DnsTask::Delegate implementation:
1589
dchengb03027d2014-10-21 12:00:201590 void OnDnsTaskComplete(base::TimeTicks start_time,
1591 int net_error,
1592 const AddressList& addr_list,
1593 base::TimeDelta ttl) override {
[email protected]b3601bc22012-02-21 21:23:201594 DCHECK(is_dns_running());
[email protected]b3601bc22012-02-21 21:23:201595
[email protected]e3bd4822012-10-23 18:01:371596 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]b3601bc22012-02-21 21:23:201597 if (net_error != OK) {
[email protected]16c2bd72013-06-28 01:19:221598 OnDnsTaskFailure(dns_task_->AsWeakPtr(), duration, net_error);
[email protected]b3601bc22012-02-21 21:23:201599 return;
1600 }
[email protected]e3bd4822012-10-23 18:01:371601 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess", duration);
[email protected]02cd6982013-01-10 20:12:511602 // Log DNS lookups based on |address_family|.
1603 switch(key_.address_family) {
1604 case ADDRESS_FAMILY_IPV4:
1605 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_IPV4", duration);
1606 break;
1607 case ADDRESS_FAMILY_IPV6:
1608 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_IPV6", duration);
1609 break;
1610 case ADDRESS_FAMILY_UNSPECIFIED:
1611 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_UNSPEC", duration);
1612 break;
1613 }
[email protected]b3601bc22012-02-21 21:23:201614
[email protected]1def74c2012-03-22 20:07:001615 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_DNS_SUCCESS);
[email protected]1339a2a22012-10-17 08:39:431616 RecordTTL(ttl);
[email protected]0adcb2b2012-08-15 21:30:461617
[email protected]1ffdda82012-12-12 23:04:221618 resolver_->OnDnsTaskResolve(OK);
[email protected]f0f602bd2012-11-15 18:01:021619
[email protected]895123222012-10-25 15:21:171620 base::TimeDelta bounded_ttl =
1621 std::max(ttl, base::TimeDelta::FromSeconds(kMinimumTTLSeconds));
1622
1623 CompleteRequests(
1624 HostCache::Entry(net_error, MakeAddressListForRequest(addr_list), ttl),
1625 bounded_ttl);
[email protected]b3601bc22012-02-21 21:23:201626 }
1627
dchengb03027d2014-10-21 12:00:201628 void OnFirstDnsTransactionComplete() override {
[email protected]daae1322013-09-05 18:26:501629 DCHECK(dns_task_->needs_two_transactions());
1630 DCHECK_EQ(dns_task_->needs_another_transaction(), is_queued());
1631 // No longer need to occupy two dispatcher slots.
1632 ReduceToOneJobSlot();
1633
1634 // We already have a job slot at the dispatcher, so if the second
1635 // transaction hasn't started, reuse it now instead of waiting in the queue
1636 // for the second slot.
1637 if (dns_task_->needs_another_transaction())
1638 dns_task_->StartSecondTransaction();
1639 }
1640
[email protected]16ee26d2012-03-08 03:34:351641 // Performs Job's last rites. Completes all Requests. Deletes this.
[email protected]895123222012-10-25 15:21:171642 void CompleteRequests(const HostCache::Entry& entry,
1643 base::TimeDelta ttl) {
[email protected]11fbca0b2013-06-02 23:37:211644 CHECK(resolver_.get());
[email protected]b3601bc22012-02-21 21:23:201645
[email protected]16ee26d2012-03-08 03:34:351646 // This job must be removed from resolver's |jobs_| now to make room for a
1647 // new job with the same key in case one of the OnComplete callbacks decides
1648 // to spawn one. Consequently, the job deletes itself when CompleteRequests
1649 // is done.
1650 scoped_ptr<Job> self_deleter(this);
1651
1652 resolver_->RemoveJob(this);
1653
[email protected]16ee26d2012-03-08 03:34:351654 if (is_running()) {
[email protected]16ee26d2012-03-08 03:34:351655 if (is_proc_running()) {
[email protected]daae1322013-09-05 18:26:501656 DCHECK(!is_queued());
[email protected]16ee26d2012-03-08 03:34:351657 proc_task_->Cancel();
1658 proc_task_ = NULL;
1659 }
[email protected]daae1322013-09-05 18:26:501660 KillDnsTask();
[email protected]16ee26d2012-03-08 03:34:351661
1662 // Signal dispatcher that a slot has opened.
[email protected]106ccd2c2014-06-17 09:21:001663 resolver_->dispatcher_->OnJobFinished();
[email protected]16ee26d2012-03-08 03:34:351664 } else if (is_queued()) {
[email protected]106ccd2c2014-06-17 09:21:001665 resolver_->dispatcher_->Cancel(handle_);
[email protected]16ee26d2012-03-08 03:34:351666 handle_.Reset();
1667 }
1668
1669 if (num_active_requests() == 0) {
[email protected]4da911f2012-06-14 19:45:201670 net_log_.AddEvent(NetLog::TYPE_CANCELLED);
[email protected]16ee26d2012-03-08 03:34:351671 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
1672 OK);
1673 return;
1674 }
[email protected]b3601bc22012-02-21 21:23:201675
1676 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
[email protected]895123222012-10-25 15:21:171677 entry.error);
[email protected]68ad3ee2010-01-30 03:45:391678
[email protected]78eac2a2012-03-14 19:09:271679 DCHECK(!requests_.empty());
1680
[email protected]895123222012-10-25 15:21:171681 if (entry.error == OK) {
[email protected]d7b9a2b2012-05-31 22:31:191682 // Record this histogram here, when we know the system has a valid DNS
1683 // configuration.
[email protected]539df6c2012-06-19 21:21:291684 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.HaveDnsConfig",
1685 resolver_->received_dns_config_);
[email protected]d7b9a2b2012-05-31 22:31:191686 }
[email protected]16ee26d2012-03-08 03:34:351687
[email protected]7af985a2012-12-14 22:40:421688 bool did_complete = (entry.error != ERR_NETWORK_CHANGED) &&
[email protected]895123222012-10-25 15:21:171689 (entry.error != ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
1690 if (did_complete)
[email protected]1339a2a22012-10-17 08:39:431691 resolver_->CacheResult(key_, entry, ttl);
[email protected]16ee26d2012-03-08 03:34:351692
[email protected]0f292de02012-02-01 22:28:201693 // Complete all of the requests that were attached to the job.
1694 for (RequestsList::const_iterator it = requests_.begin();
1695 it != requests_.end(); ++it) {
1696 Request* req = *it;
1697
1698 if (req->was_canceled())
1699 continue;
1700
1701 DCHECK_EQ(this, req->job());
1702 // Update the net log and notify registered observers.
1703 LogFinishRequest(req->source_net_log(), req->request_net_log(),
[email protected]895123222012-10-25 15:21:171704 req->info(), entry.error);
[email protected]51b9a6b2012-06-25 21:50:291705 if (did_complete) {
1706 // Record effective total time from creation to completion.
1707 RecordTotalTime(had_dns_config_, req->info().is_speculative(),
1708 base::TimeTicks::Now() - req->request_time());
1709 }
[email protected]895123222012-10-25 15:21:171710 req->OnComplete(entry.error, entry.addrlist);
[email protected]0f292de02012-02-01 22:28:201711
1712 // Check if the resolver was destroyed as a result of running the
1713 // callback. If it was, we could continue, but we choose to bail.
[email protected]11fbca0b2013-06-02 23:37:211714 if (!resolver_.get())
[email protected]0f292de02012-02-01 22:28:201715 return;
1716 }
1717 }
1718
[email protected]1339a2a22012-10-17 08:39:431719 // Convenience wrapper for CompleteRequests in case of failure.
1720 void CompleteRequestsWithError(int net_error) {
[email protected]895123222012-10-25 15:21:171721 CompleteRequests(HostCache::Entry(net_error, AddressList()),
1722 base::TimeDelta());
[email protected]1339a2a22012-10-17 08:39:431723 }
1724
[email protected]b4481b222012-03-16 17:13:111725 RequestPriority priority() const {
1726 return priority_tracker_.highest_priority();
1727 }
1728
1729 // Number of non-canceled requests in |requests_|.
1730 size_t num_active_requests() const {
1731 return priority_tracker_.total_count();
1732 }
1733
1734 bool is_dns_running() const {
1735 return dns_task_.get() != NULL;
1736 }
1737
1738 bool is_proc_running() const {
1739 return proc_task_.get() != NULL;
1740 }
1741
[email protected]0f292de02012-02-01 22:28:201742 base::WeakPtr<HostResolverImpl> resolver_;
1743
1744 Key key_;
1745
1746 // Tracks the highest priority across |requests_|.
1747 PriorityTracker priority_tracker_;
1748
1749 bool had_non_speculative_request_;
1750
[email protected]51b9a6b2012-06-25 21:50:291751 // Distinguishes measurements taken while DnsClient was fully configured.
1752 bool had_dns_config_;
1753
[email protected]daae1322013-09-05 18:26:501754 // Number of slots occupied by this Job in resolver's PrioritizedDispatcher.
1755 unsigned num_occupied_job_slots_;
1756
[email protected]1d932852012-06-19 19:40:331757 // Result of DnsTask.
1758 int dns_task_error_;
[email protected]1def74c2012-03-22 20:07:001759
[email protected]51b9a6b2012-06-25 21:50:291760 const base::TimeTicks creation_time_;
1761 base::TimeTicks priority_change_time_;
1762
[email protected]0f292de02012-02-01 22:28:201763 BoundNetLog net_log_;
1764
[email protected]b3601bc22012-02-21 21:23:201765 // Resolves the host using a HostResolverProc.
[email protected]0f292de02012-02-01 22:28:201766 scoped_refptr<ProcTask> proc_task_;
1767
[email protected]b3601bc22012-02-21 21:23:201768 // Resolves the host using a DnsTransaction.
1769 scoped_ptr<DnsTask> dns_task_;
1770
[email protected]0f292de02012-02-01 22:28:201771 // All Requests waiting for the result of this Job. Some can be canceled.
1772 RequestsList requests_;
1773
[email protected]16ee26d2012-03-08 03:34:351774 // A handle used in |HostResolverImpl::dispatcher_|.
[email protected]0f292de02012-02-01 22:28:201775 PrioritizedDispatcher::Handle handle_;
[email protected]68ad3ee2010-01-30 03:45:391776};
1777
1778//-----------------------------------------------------------------------------
1779
[email protected]0f292de02012-02-01 22:28:201780HostResolverImpl::ProcTaskParams::ProcTaskParams(
[email protected]e95d3aca2010-01-11 22:47:431781 HostResolverProc* resolver_proc,
[email protected]0f292de02012-02-01 22:28:201782 size_t max_retry_attempts)
1783 : resolver_proc(resolver_proc),
1784 max_retry_attempts(max_retry_attempts),
1785 unresponsive_delay(base::TimeDelta::FromMilliseconds(6000)),
1786 retry_factor(2) {
[email protected]106ccd2c2014-06-17 09:21:001787 // Maximum of 4 retry attempts for host resolution.
1788 static const size_t kDefaultMaxRetryAttempts = 4u;
1789 if (max_retry_attempts == HostResolver::kDefaultRetryAttempts)
1790 max_retry_attempts = kDefaultMaxRetryAttempts;
[email protected]0f292de02012-02-01 22:28:201791}
1792
1793HostResolverImpl::ProcTaskParams::~ProcTaskParams() {}
1794
[email protected]106ccd2c2014-06-17 09:21:001795HostResolverImpl::HostResolverImpl(const Options& options, NetLog* net_log)
1796 : max_queued_jobs_(0),
1797 proc_params_(NULL, options.max_retry_attempts),
[email protected]62e86ba2013-01-29 18:59:161798 net_log_(net_log),
[email protected]0c7798452009-10-26 17:59:511799 default_address_family_(ADDRESS_FAMILY_UNSPECIFIED),
[email protected]d7b9a2b2012-05-31 22:31:191800 received_dns_config_(false),
[email protected]f0f602bd2012-11-15 18:01:021801 num_dns_failures_(0),
[email protected]23330db72013-07-18 03:32:111802 probe_ipv6_support_(true),
[email protected]c9fa8f312013-09-17 12:24:521803 use_local_ipv6_(false),
[email protected]62e86ba2013-01-29 18:59:161804 resolved_known_ipv6_hostname_(false),
[email protected]16c2bd72013-06-28 01:19:221805 additional_resolver_flags_(0),
[email protected]0a30cf512014-05-27 20:55:181806 fallback_to_proctask_(true),
1807 weak_ptr_factory_(this),
1808 probe_weak_ptr_factory_(this) {
[email protected]106ccd2c2014-06-17 09:21:001809 if (options.enable_caching)
1810 cache_ = HostCache::CreateDefaultCache();
[email protected]0f292de02012-02-01 22:28:201811
[email protected]106ccd2c2014-06-17 09:21:001812 PrioritizedDispatcher::Limits job_limits = options.GetDispatcherLimits();
1813 dispatcher_.reset(new PrioritizedDispatcher(job_limits));
1814 max_queued_jobs_ = job_limits.total_jobs * 100u;
[email protected]68ad3ee2010-01-30 03:45:391815
[email protected]106ccd2c2014-06-17 09:21:001816 DCHECK_GE(dispatcher_->num_priorities(), static_cast<size_t>(NUM_PRIORITIES));
[email protected]68ad3ee2010-01-30 03:45:391817
[email protected]b59ff372009-07-15 22:04:321818#if defined(OS_WIN)
1819 EnsureWinsockInit();
1820#endif
[email protected]7c466e92013-07-20 01:44:481821#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
[email protected]12faa4c2012-11-06 04:44:181822 new LoopbackProbeJob(weak_ptr_factory_.GetWeakPtr());
[email protected]2f3bc65c2010-07-23 17:47:101823#endif
[email protected]232a5812011-03-04 22:42:081824 NetworkChangeNotifier::AddIPAddressObserver(this);
[email protected]bb0e34542012-08-31 19:52:401825 NetworkChangeNotifier::AddDNSObserver(this);
[email protected]d7b9a2b2012-05-31 22:31:191826#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD) && \
1827 !defined(OS_ANDROID)
[email protected]d7b9a2b2012-05-31 22:31:191828 EnsureDnsReloaderInit();
[email protected]46018c9d2011-09-06 03:42:341829#endif
[email protected]2ac22db2012-11-28 19:50:041830
[email protected]2ac22db2012-11-28 19:50:041831 {
1832 DnsConfig dns_config;
1833 NetworkChangeNotifier::GetDnsConfig(&dns_config);
1834 received_dns_config_ = dns_config.IsValid();
[email protected]c9fa8f312013-09-17 12:24:521835 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
1836 use_local_ipv6_ = !dns_config.IsValid() || dns_config.use_local_ipv6;
[email protected]2ac22db2012-11-28 19:50:041837 }
[email protected]16c2bd72013-06-28 01:19:221838
1839 fallback_to_proctask_ = !ConfigureAsyncDnsNoFallbackFieldTrial();
[email protected]b59ff372009-07-15 22:04:321840}
1841
1842HostResolverImpl::~HostResolverImpl() {
[email protected]daae1322013-09-05 18:26:501843 // Prevent the dispatcher from starting new jobs.
[email protected]106ccd2c2014-06-17 09:21:001844 dispatcher_->SetLimitsToZero();
[email protected]daae1322013-09-05 18:26:501845 // It's now safe for Jobs to call KillDsnTask on destruction, because
1846 // OnJobComplete will not start any new jobs.
[email protected]0f292de02012-02-01 22:28:201847 STLDeleteValues(&jobs_);
[email protected]e95d3aca2010-01-11 22:47:431848
[email protected]232a5812011-03-04 22:42:081849 NetworkChangeNotifier::RemoveIPAddressObserver(this);
[email protected]bb0e34542012-08-31 19:52:401850 NetworkChangeNotifier::RemoveDNSObserver(this);
[email protected]b59ff372009-07-15 22:04:321851}
1852
[email protected]0f292de02012-02-01 22:28:201853void HostResolverImpl::SetMaxQueuedJobs(size_t value) {
[email protected]106ccd2c2014-06-17 09:21:001854 DCHECK_EQ(0u, dispatcher_->num_queued_jobs());
[email protected]0f292de02012-02-01 22:28:201855 DCHECK_GT(value, 0u);
1856 max_queued_jobs_ = value;
[email protected]be1a48b2011-01-20 00:12:131857}
1858
[email protected]684970b2009-08-14 04:54:461859int HostResolverImpl::Resolve(const RequestInfo& info,
[email protected]5109c1952013-08-20 18:44:101860 RequestPriority priority,
[email protected]b59ff372009-07-15 22:04:321861 AddressList* addresses,
[email protected]aa22b242011-11-16 18:58:291862 const CompletionCallback& callback,
[email protected]684970b2009-08-14 04:54:461863 RequestHandle* out_req,
[email protected]ee094b82010-08-24 15:55:511864 const BoundNetLog& source_net_log) {
[email protected]95a214c2011-08-04 21:50:401865 DCHECK(addresses);
[email protected]1ac6af92010-06-03 21:00:141866 DCHECK(CalledOnValidThread());
[email protected]aa22b242011-11-16 18:58:291867 DCHECK_EQ(false, callback.is_null());
[email protected]1ac6af92010-06-03 21:00:141868
[email protected]e806cd72013-05-17 02:08:431869 // Check that the caller supplied a valid hostname to resolve.
1870 std::string labeled_hostname;
1871 if (!DNSDomainFromDot(info.hostname(), &labeled_hostname))
1872 return ERR_NAME_NOT_RESOLVED;
1873
[email protected]ee094b82010-08-24 15:55:511874 // Make a log item for the request.
1875 BoundNetLog request_net_log = BoundNetLog::Make(net_log_,
1876 NetLog::SOURCE_HOST_RESOLVER_IMPL_REQUEST);
1877
[email protected]0f292de02012-02-01 22:28:201878 LogStartRequest(source_net_log, request_net_log, info);
[email protected]b59ff372009-07-15 22:04:321879
[email protected]123ab1e32009-10-21 19:12:571880 // Build a key that identifies the request in the cache and in the
1881 // outstanding jobs map.
[email protected]2b74a2f2013-07-23 19:37:381882 Key key = GetEffectiveKeyForRequest(info, request_net_log);
[email protected]123ab1e32009-10-21 19:12:571883
[email protected]287d7c22011-11-15 17:34:251884 int rv = ResolveHelper(key, info, addresses, request_net_log);
[email protected]95a214c2011-08-04 21:50:401885 if (rv != ERR_DNS_CACHE_MISS) {
[email protected]b3601bc22012-02-21 21:23:201886 LogFinishRequest(source_net_log, request_net_log, info, rv);
[email protected]51b9a6b2012-06-25 21:50:291887 RecordTotalTime(HaveDnsConfig(), info.is_speculative(), base::TimeDelta());
[email protected]95a214c2011-08-04 21:50:401888 return rv;
[email protected]38368712011-03-02 08:09:401889 }
1890
[email protected]0f292de02012-02-01 22:28:201891 // Next we need to attach our request to a "job". This job is responsible for
1892 // calling "getaddrinfo(hostname)" on a worker thread.
1893
1894 JobMap::iterator jobit = jobs_.find(key);
1895 Job* job;
1896 if (jobit == jobs_.end()) {
[email protected]5109c1952013-08-20 18:44:101897 job =
1898 new Job(weak_ptr_factory_.GetWeakPtr(), key, priority, request_net_log);
[email protected]daae1322013-09-05 18:26:501899 job->Schedule(false);
[email protected]0f292de02012-02-01 22:28:201900
1901 // Check for queue overflow.
[email protected]106ccd2c2014-06-17 09:21:001902 if (dispatcher_->num_queued_jobs() > max_queued_jobs_) {
1903 Job* evicted = static_cast<Job*>(dispatcher_->EvictOldestLowest());
[email protected]0f292de02012-02-01 22:28:201904 DCHECK(evicted);
[email protected]16ee26d2012-03-08 03:34:351905 evicted->OnEvicted(); // Deletes |evicted|.
[email protected]0f292de02012-02-01 22:28:201906 if (evicted == job) {
[email protected]0f292de02012-02-01 22:28:201907 rv = ERR_HOST_RESOLVER_QUEUE_TOO_LARGE;
[email protected]b3601bc22012-02-21 21:23:201908 LogFinishRequest(source_net_log, request_net_log, info, rv);
[email protected]0f292de02012-02-01 22:28:201909 return rv;
1910 }
[email protected]0f292de02012-02-01 22:28:201911 }
[email protected]0f292de02012-02-01 22:28:201912 jobs_.insert(jobit, std::make_pair(key, job));
1913 } else {
1914 job = jobit->second;
1915 }
1916
1917 // Can't complete synchronously. Create and attach request.
[email protected]5109c1952013-08-20 18:44:101918 scoped_ptr<Request> req(new Request(
1919 source_net_log, request_net_log, info, priority, callback, addresses));
[email protected]b59ff372009-07-15 22:04:321920 if (out_req)
[email protected]b3601bc22012-02-21 21:23:201921 *out_req = reinterpret_cast<RequestHandle>(req.get());
[email protected]b59ff372009-07-15 22:04:321922
[email protected]b3601bc22012-02-21 21:23:201923 job->AddRequest(req.Pass());
[email protected]0f292de02012-02-01 22:28:201924 // Completion happens during Job::CompleteRequests().
[email protected]b59ff372009-07-15 22:04:321925 return ERR_IO_PENDING;
1926}
1927
[email protected]287d7c22011-11-15 17:34:251928int HostResolverImpl::ResolveHelper(const Key& key,
[email protected]95a214c2011-08-04 21:50:401929 const RequestInfo& info,
1930 AddressList* addresses,
[email protected]20cd5332011-10-12 22:38:001931 const BoundNetLog& request_net_log) {
[email protected]95a214c2011-08-04 21:50:401932 // The result of |getaddrinfo| for empty hosts is inconsistent across systems.
1933 // On Windows it gives the default interface's address, whereas on Linux it
1934 // gives an error. We will make it fail on all platforms for consistency.
1935 if (info.hostname().empty() || info.hostname().size() > kMaxHostLength)
1936 return ERR_NAME_NOT_RESOLVED;
1937
1938 int net_error = ERR_UNEXPECTED;
1939 if (ResolveAsIP(key, info, &net_error, addresses))
1940 return net_error;
[email protected]78eac2a2012-03-14 19:09:271941 if (ServeFromCache(key, info, &net_error, addresses)) {
[email protected]4da911f2012-06-14 19:45:201942 request_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_CACHE_HIT);
[email protected]78eac2a2012-03-14 19:09:271943 return net_error;
1944 }
1945 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
1946 // http://crbug.com/117655
1947 if (ServeFromHosts(key, info, addresses)) {
[email protected]4da911f2012-06-14 19:45:201948 request_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_HOSTS_HIT);
[email protected]78eac2a2012-03-14 19:09:271949 return OK;
1950 }
1951 return ERR_DNS_CACHE_MISS;
[email protected]95a214c2011-08-04 21:50:401952}
1953
1954int HostResolverImpl::ResolveFromCache(const RequestInfo& info,
1955 AddressList* addresses,
1956 const BoundNetLog& source_net_log) {
1957 DCHECK(CalledOnValidThread());
1958 DCHECK(addresses);
1959
[email protected]95a214c2011-08-04 21:50:401960 // Make a log item for the request.
1961 BoundNetLog request_net_log = BoundNetLog::Make(net_log_,
1962 NetLog::SOURCE_HOST_RESOLVER_IMPL_REQUEST);
1963
1964 // Update the net log and notify registered observers.
[email protected]0f292de02012-02-01 22:28:201965 LogStartRequest(source_net_log, request_net_log, info);
[email protected]95a214c2011-08-04 21:50:401966
[email protected]2b74a2f2013-07-23 19:37:381967 Key key = GetEffectiveKeyForRequest(info, request_net_log);
[email protected]95a214c2011-08-04 21:50:401968
[email protected]287d7c22011-11-15 17:34:251969 int rv = ResolveHelper(key, info, addresses, request_net_log);
[email protected]b3601bc22012-02-21 21:23:201970 LogFinishRequest(source_net_log, request_net_log, info, rv);
[email protected]95a214c2011-08-04 21:50:401971 return rv;
1972}
1973
[email protected]b59ff372009-07-15 22:04:321974void HostResolverImpl::CancelRequest(RequestHandle req_handle) {
[email protected]1ac6af92010-06-03 21:00:141975 DCHECK(CalledOnValidThread());
[email protected]b59ff372009-07-15 22:04:321976 Request* req = reinterpret_cast<Request*>(req_handle);
1977 DCHECK(req);
[email protected]0f292de02012-02-01 22:28:201978 Job* job = req->job();
1979 DCHECK(job);
[email protected]0f292de02012-02-01 22:28:201980 job->CancelRequest(req);
[email protected]b59ff372009-07-15 22:04:321981}
1982
[email protected]0f8f1b432010-03-16 19:06:031983void HostResolverImpl::SetDefaultAddressFamily(AddressFamily address_family) {
[email protected]1ac6af92010-06-03 21:00:141984 DCHECK(CalledOnValidThread());
[email protected]0f8f1b432010-03-16 19:06:031985 default_address_family_ = address_family;
[email protected]23330db72013-07-18 03:32:111986 probe_ipv6_support_ = false;
[email protected]0f8f1b432010-03-16 19:06:031987}
1988
[email protected]f7d310e2010-10-07 16:25:111989AddressFamily HostResolverImpl::GetDefaultAddressFamily() const {
1990 return default_address_family_;
1991}
1992
[email protected]a8883e452012-11-17 05:58:061993void HostResolverImpl::SetDnsClientEnabled(bool enabled) {
1994 DCHECK(CalledOnValidThread());
1995#if defined(ENABLE_BUILT_IN_DNS)
1996 if (enabled && !dns_client_) {
1997 SetDnsClient(DnsClient::CreateClient(net_log_));
1998 } else if (!enabled && dns_client_) {
1999 SetDnsClient(scoped_ptr<DnsClient>());
2000 }
2001#endif
2002}
2003
[email protected]489d1a82011-10-12 03:09:112004HostCache* HostResolverImpl::GetHostCache() {
2005 return cache_.get();
2006}
[email protected]95a214c2011-08-04 21:50:402007
[email protected]17e92032012-03-29 00:56:242008base::Value* HostResolverImpl::GetDnsConfigAsValue() const {
2009 // Check if async DNS is disabled.
2010 if (!dns_client_.get())
2011 return NULL;
2012
2013 // Check if async DNS is enabled, but we currently have no configuration
2014 // for it.
2015 const DnsConfig* dns_config = dns_client_->GetConfig();
2016 if (dns_config == NULL)
[email protected]ea5ef4c2013-06-13 22:50:272017 return new base::DictionaryValue();
[email protected]17e92032012-03-29 00:56:242018
2019 return dns_config->ToValue();
2020}
2021
[email protected]95a214c2011-08-04 21:50:402022bool HostResolverImpl::ResolveAsIP(const Key& key,
2023 const RequestInfo& info,
2024 int* net_error,
2025 AddressList* addresses) {
2026 DCHECK(addresses);
2027 DCHECK(net_error);
2028 IPAddressNumber ip_number;
2029 if (!ParseIPLiteralToNumber(key.hostname, &ip_number))
2030 return false;
2031
2032 DCHECK_EQ(key.host_resolver_flags &
2033 ~(HOST_RESOLVER_CANONNAME | HOST_RESOLVER_LOOPBACK_ONLY |
2034 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6),
2035 0) << " Unhandled flag";
[email protected]1c7cf3f82014-08-07 21:33:482036
[email protected]95a214c2011-08-04 21:50:402037 *net_error = OK;
[email protected]1c7cf3f82014-08-07 21:33:482038 AddressFamily family = GetAddressFamily(ip_number);
2039 if (family == ADDRESS_FAMILY_IPV6 &&
2040 !probe_ipv6_support_ &&
2041 default_address_family_ == ADDRESS_FAMILY_IPV4) {
2042 // Don't return IPv6 addresses if default address family is set to IPv4,
2043 // and probes are disabled.
2044 *net_error = ERR_NAME_NOT_RESOLVED;
2045 } else if (key.address_family != ADDRESS_FAMILY_UNSPECIFIED &&
2046 key.address_family != family) {
2047 // Don't return IPv6 addresses for IPv4 queries, and vice versa.
[email protected]95a214c2011-08-04 21:50:402048 *net_error = ERR_NAME_NOT_RESOLVED;
2049 } else {
[email protected]7054e78f2012-05-07 21:44:562050 *addresses = AddressList::CreateFromIPAddress(ip_number, info.port());
2051 if (key.host_resolver_flags & HOST_RESOLVER_CANONNAME)
2052 addresses->SetDefaultCanonicalName();
[email protected]95a214c2011-08-04 21:50:402053 }
2054 return true;
2055}
2056
2057bool HostResolverImpl::ServeFromCache(const Key& key,
2058 const RequestInfo& info,
[email protected]95a214c2011-08-04 21:50:402059 int* net_error,
2060 AddressList* addresses) {
2061 DCHECK(addresses);
2062 DCHECK(net_error);
2063 if (!info.allow_cached_response() || !cache_.get())
2064 return false;
2065
[email protected]407a30ab2012-08-15 17:16:102066 const HostCache::Entry* cache_entry = cache_->Lookup(
2067 key, base::TimeTicks::Now());
[email protected]95a214c2011-08-04 21:50:402068 if (!cache_entry)
2069 return false;
2070
[email protected]95a214c2011-08-04 21:50:402071 *net_error = cache_entry->error;
[email protected]7054e78f2012-05-07 21:44:562072 if (*net_error == OK) {
[email protected]1339a2a22012-10-17 08:39:432073 if (cache_entry->has_ttl())
2074 RecordTTL(cache_entry->ttl);
[email protected]895123222012-10-25 15:21:172075 *addresses = EnsurePortOnAddressList(cache_entry->addrlist, info.port());
[email protected]7054e78f2012-05-07 21:44:562076 }
[email protected]95a214c2011-08-04 21:50:402077 return true;
2078}
2079
[email protected]78eac2a2012-03-14 19:09:272080bool HostResolverImpl::ServeFromHosts(const Key& key,
2081 const RequestInfo& info,
2082 AddressList* addresses) {
2083 DCHECK(addresses);
2084 if (!HaveDnsConfig())
2085 return false;
[email protected]05a79d42013-03-28 07:30:092086 addresses->clear();
2087
[email protected]cb507622012-03-23 16:17:062088 // HOSTS lookups are case-insensitive.
[email protected]cb1f4ac2014-08-07 16:55:422089 std::string hostname = base::StringToLowerASCII(key.hostname);
[email protected]cb507622012-03-23 16:17:062090
[email protected]05a79d42013-03-28 07:30:092091 const DnsHosts& hosts = dns_client_->GetConfig()->hosts;
2092
[email protected]78eac2a2012-03-14 19:09:272093 // If |address_family| is ADDRESS_FAMILY_UNSPECIFIED other implementations
2094 // (glibc and c-ares) return the first matching line. We have more
2095 // flexibility, but lose implicit ordering.
[email protected]05a79d42013-03-28 07:30:092096 // We prefer IPv6 because "happy eyeballs" will fall back to IPv4 if
2097 // necessary.
2098 if (key.address_family == ADDRESS_FAMILY_IPV6 ||
2099 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
2100 DnsHosts::const_iterator it = hosts.find(
2101 DnsHostsKey(hostname, ADDRESS_FAMILY_IPV6));
2102 if (it != hosts.end())
2103 addresses->push_back(IPEndPoint(it->second, info.port()));
[email protected]78eac2a2012-03-14 19:09:272104 }
2105
[email protected]05a79d42013-03-28 07:30:092106 if (key.address_family == ADDRESS_FAMILY_IPV4 ||
2107 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
2108 DnsHosts::const_iterator it = hosts.find(
2109 DnsHostsKey(hostname, ADDRESS_FAMILY_IPV4));
2110 if (it != hosts.end())
2111 addresses->push_back(IPEndPoint(it->second, info.port()));
2112 }
2113
[email protected]ec666ab22013-04-17 20:05:592114 // If got only loopback addresses and the family was restricted, resolve
2115 // again, without restrictions. See SystemHostResolverCall for rationale.
2116 if ((key.host_resolver_flags &
2117 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6) &&
2118 IsAllIPv4Loopback(*addresses)) {
2119 Key new_key(key);
2120 new_key.address_family = ADDRESS_FAMILY_UNSPECIFIED;
2121 new_key.host_resolver_flags &=
2122 ~HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
2123 return ServeFromHosts(new_key, info, addresses);
2124 }
[email protected]05a79d42013-03-28 07:30:092125 return !addresses->empty();
[email protected]78eac2a2012-03-14 19:09:272126}
2127
[email protected]16ee26d2012-03-08 03:34:352128void HostResolverImpl::CacheResult(const Key& key,
[email protected]1339a2a22012-10-17 08:39:432129 const HostCache::Entry& entry,
[email protected]16ee26d2012-03-08 03:34:352130 base::TimeDelta ttl) {
2131 if (cache_.get())
[email protected]1339a2a22012-10-17 08:39:432132 cache_->Set(key, entry, base::TimeTicks::Now(), ttl);
[email protected]ef4c40c2010-09-01 14:42:032133}
2134
[email protected]0f292de02012-02-01 22:28:202135void HostResolverImpl::RemoveJob(Job* job) {
2136 DCHECK(job);
[email protected]16ee26d2012-03-08 03:34:352137 JobMap::iterator it = jobs_.find(job->key());
2138 if (it != jobs_.end() && it->second == job)
2139 jobs_.erase(it);
[email protected]b59ff372009-07-15 22:04:322140}
2141
[email protected]9936a7862012-10-26 04:44:022142void HostResolverImpl::SetHaveOnlyLoopbackAddresses(bool result) {
2143 if (result) {
2144 additional_resolver_flags_ |= HOST_RESOLVER_LOOPBACK_ONLY;
2145 } else {
2146 additional_resolver_flags_ &= ~HOST_RESOLVER_LOOPBACK_ONLY;
2147 }
2148}
2149
[email protected]137af622010-02-05 02:14:352150HostResolverImpl::Key HostResolverImpl::GetEffectiveKeyForRequest(
[email protected]2b74a2f2013-07-23 19:37:382151 const RequestInfo& info, const BoundNetLog& net_log) const {
[email protected]eaf3a3b2010-09-03 20:34:272152 HostResolverFlags effective_flags =
2153 info.host_resolver_flags() | additional_resolver_flags_;
[email protected]137af622010-02-05 02:14:352154 AddressFamily effective_address_family = info.address_family();
[email protected]9db6f702013-04-10 18:10:512155
2156 if (info.address_family() == ADDRESS_FAMILY_UNSPECIFIED) {
[email protected]c9fa8f312013-09-17 12:24:522157 if (probe_ipv6_support_ && !use_local_ipv6_) {
[email protected]ac0b52e2013-04-21 01:26:162158 base::TimeTicks start_time = base::TimeTicks::Now();
2159 // Google DNS address.
2160 const uint8 kIPv6Address[] =
2161 { 0x20, 0x01, 0x48, 0x60, 0x48, 0x60, 0x00, 0x00,
2162 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x88 };
2163 IPAddressNumber address(kIPv6Address,
2164 kIPv6Address + arraysize(kIPv6Address));
[email protected]967d1b52014-01-16 21:43:172165 BoundNetLog probe_net_log = BoundNetLog::Make(
2166 net_log.net_log(), NetLog::SOURCE_IPV6_REACHABILITY_CHECK);
2167 probe_net_log.BeginEvent(NetLog::TYPE_IPV6_REACHABILITY_CHECK,
2168 net_log.source().ToEventParametersCallback());
2169 bool rv6 = IsGloballyReachable(address, probe_net_log);
2170 probe_net_log.EndEvent(NetLog::TYPE_IPV6_REACHABILITY_CHECK);
[email protected]2b74a2f2013-07-23 19:37:382171 if (rv6)
2172 net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_IPV6_SUPPORTED);
[email protected]9db6f702013-04-10 18:10:512173
[email protected]ac0b52e2013-04-21 01:26:162174 UMA_HISTOGRAM_TIMES("Net.IPv6ConnectDuration",
2175 base::TimeTicks::Now() - start_time);
2176 if (rv6) {
2177 UMA_HISTOGRAM_BOOLEAN("Net.IPv6ConnectSuccessMatch",
2178 default_address_family_ == ADDRESS_FAMILY_UNSPECIFIED);
2179 } else {
2180 UMA_HISTOGRAM_BOOLEAN("Net.IPv6ConnectFailureMatch",
2181 default_address_family_ != ADDRESS_FAMILY_UNSPECIFIED);
2182
2183 effective_address_family = ADDRESS_FAMILY_IPV4;
2184 effective_flags |= HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
2185 }
[email protected]9db6f702013-04-10 18:10:512186 } else {
[email protected]ac0b52e2013-04-21 01:26:162187 effective_address_family = default_address_family_;
[email protected]9db6f702013-04-10 18:10:512188 }
2189 }
2190
[email protected]eaf3a3b2010-09-03 20:34:272191 return Key(info.hostname(), effective_address_family, effective_flags);
[email protected]137af622010-02-05 02:14:352192}
2193
[email protected]35ddc282010-09-21 23:42:062194void HostResolverImpl::AbortAllInProgressJobs() {
[email protected]b3601bc22012-02-21 21:23:202195 // In Abort, a Request callback could spawn new Jobs with matching keys, so
2196 // first collect and remove all running jobs from |jobs_|.
[email protected]c143d892012-04-06 07:56:542197 ScopedVector<Job> jobs_to_abort;
[email protected]0f292de02012-02-01 22:28:202198 for (JobMap::iterator it = jobs_.begin(); it != jobs_.end(); ) {
2199 Job* job = it->second;
[email protected]0f292de02012-02-01 22:28:202200 if (job->is_running()) {
[email protected]b3601bc22012-02-21 21:23:202201 jobs_to_abort.push_back(job);
2202 jobs_.erase(it++);
[email protected]0f292de02012-02-01 22:28:202203 } else {
[email protected]b3601bc22012-02-21 21:23:202204 DCHECK(job->is_queued());
2205 ++it;
[email protected]0f292de02012-02-01 22:28:202206 }
[email protected]ef4c40c2010-09-01 14:42:032207 }
[email protected]b3601bc22012-02-21 21:23:202208
[email protected]daae1322013-09-05 18:26:502209 // Pause the dispatcher so it won't start any new dispatcher jobs while
2210 // aborting the old ones. This is needed so that it won't start the second
2211 // DnsTransaction for a job in |jobs_to_abort| if the DnsConfig just became
2212 // invalid.
[email protected]106ccd2c2014-06-17 09:21:002213 PrioritizedDispatcher::Limits limits = dispatcher_->GetLimits();
2214 dispatcher_->SetLimits(
[email protected]daae1322013-09-05 18:26:502215 PrioritizedDispatcher::Limits(limits.reserved_slots.size(), 0));
[email protected]70c04ab2013-08-22 16:05:122216
[email protected]57a48d32012-03-03 00:04:552217 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072218 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]57a48d32012-03-03 00:04:552219
[email protected]16ee26d2012-03-08 03:34:352220 // Then Abort them.
[email protected]11fbca0b2013-06-02 23:37:212221 for (size_t i = 0; self.get() && i < jobs_to_abort.size(); ++i) {
[email protected]57a48d32012-03-03 00:04:552222 jobs_to_abort[i]->Abort();
[email protected]c143d892012-04-06 07:56:542223 jobs_to_abort[i] = NULL;
[email protected]b3601bc22012-02-21 21:23:202224 }
[email protected]daae1322013-09-05 18:26:502225
2226 if (self)
[email protected]106ccd2c2014-06-17 09:21:002227 dispatcher_->SetLimits(limits);
[email protected]daae1322013-09-05 18:26:502228}
2229
2230void HostResolverImpl::AbortDnsTasks() {
2231 // Pause the dispatcher so it won't start any new dispatcher jobs while
2232 // aborting the old ones. This is needed so that it won't start the second
2233 // DnsTransaction for a job if the DnsConfig just changed.
[email protected]106ccd2c2014-06-17 09:21:002234 PrioritizedDispatcher::Limits limits = dispatcher_->GetLimits();
2235 dispatcher_->SetLimits(
[email protected]daae1322013-09-05 18:26:502236 PrioritizedDispatcher::Limits(limits.reserved_slots.size(), 0));
2237
2238 for (JobMap::iterator it = jobs_.begin(); it != jobs_.end(); ++it)
2239 it->second->AbortDnsTask();
[email protected]106ccd2c2014-06-17 09:21:002240 dispatcher_->SetLimits(limits);
[email protected]ef4c40c2010-09-01 14:42:032241}
2242
[email protected]78eac2a2012-03-14 19:09:272243void HostResolverImpl::TryServingAllJobsFromHosts() {
2244 if (!HaveDnsConfig())
2245 return;
2246
2247 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2248 // http://crbug.com/117655
2249
2250 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072251 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]78eac2a2012-03-14 19:09:272252
[email protected]11fbca0b2013-06-02 23:37:212253 for (JobMap::iterator it = jobs_.begin(); self.get() && it != jobs_.end();) {
[email protected]78eac2a2012-03-14 19:09:272254 Job* job = it->second;
2255 ++it;
2256 // This could remove |job| from |jobs_|, but iterator will remain valid.
2257 job->ServeFromHosts();
2258 }
2259}
2260
[email protected]be1a48b2011-01-20 00:12:132261void HostResolverImpl::OnIPAddressChanged() {
[email protected]62e86ba2013-01-29 18:59:162262 resolved_known_ipv6_hostname_ = false;
[email protected]12faa4c2012-11-06 04:44:182263 // Abandon all ProbeJobs.
2264 probe_weak_ptr_factory_.InvalidateWeakPtrs();
[email protected]be1a48b2011-01-20 00:12:132265 if (cache_.get())
2266 cache_->clear();
[email protected]7c466e92013-07-20 01:44:482267#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
[email protected]12faa4c2012-11-06 04:44:182268 new LoopbackProbeJob(probe_weak_ptr_factory_.GetWeakPtr());
[email protected]be1a48b2011-01-20 00:12:132269#endif
2270 AbortAllInProgressJobs();
2271 // |this| may be deleted inside AbortAllInProgressJobs().
2272}
2273
[email protected]bb0e34542012-08-31 19:52:402274void HostResolverImpl::OnDNSChanged() {
2275 DnsConfig dns_config;
2276 NetworkChangeNotifier::GetDnsConfig(&dns_config);
[email protected]ec666ab22013-04-17 20:05:592277
[email protected]b4481b222012-03-16 17:13:112278 if (net_log_) {
2279 net_log_->AddGlobalEntry(
2280 NetLog::TYPE_DNS_CONFIG_CHANGED,
[email protected]cd565142012-06-12 16:21:452281 base::Bind(&NetLogDnsConfigCallback, &dns_config));
[email protected]b4481b222012-03-16 17:13:112282 }
2283
[email protected]01b3b9d2012-08-13 16:18:142284 // TODO(szym): Remove once http://crbug.com/137914 is resolved.
[email protected]d7b9a2b2012-05-31 22:31:192285 received_dns_config_ = dns_config.IsValid();
[email protected]c9fa8f312013-09-17 12:24:522286 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
2287 use_local_ipv6_ = !dns_config.IsValid() || dns_config.use_local_ipv6;
[email protected]78eac2a2012-03-14 19:09:272288
[email protected]a8883e452012-11-17 05:58:062289 num_dns_failures_ = 0;
2290
[email protected]01b3b9d2012-08-13 16:18:142291 // We want a new DnsSession in place, before we Abort running Jobs, so that
2292 // the newly started jobs use the new config.
[email protected]f0f602bd2012-11-15 18:01:022293 if (dns_client_.get()) {
[email protected]d7b9a2b2012-05-31 22:31:192294 dns_client_->SetConfig(dns_config);
[email protected]3d164772013-08-21 03:25:192295 if (dns_client_->GetConfig())
[email protected]f0f602bd2012-11-15 18:01:022296 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
[email protected]f0f602bd2012-11-15 18:01:022297 }
[email protected]01b3b9d2012-08-13 16:18:142298
2299 // If the DNS server has changed, existing cached info could be wrong so we
2300 // have to drop our internal cache :( Note that OS level DNS caches, such
2301 // as NSCD's cache should be dropped automatically by the OS when
2302 // resolv.conf changes so we don't need to do anything to clear that cache.
2303 if (cache_.get())
2304 cache_->clear();
2305
[email protected]f0f602bd2012-11-15 18:01:022306 // Life check to bail once |this| is deleted.
2307 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
2308
[email protected]01b3b9d2012-08-13 16:18:142309 // Existing jobs will have been sent to the original server so they need to
2310 // be aborted.
2311 AbortAllInProgressJobs();
2312
2313 // |this| may be deleted inside AbortAllInProgressJobs().
[email protected]11fbca0b2013-06-02 23:37:212314 if (self.get())
[email protected]01b3b9d2012-08-13 16:18:142315 TryServingAllJobsFromHosts();
[email protected]78eac2a2012-03-14 19:09:272316}
2317
2318bool HostResolverImpl::HaveDnsConfig() const {
[email protected]32b1dbcf2013-01-26 03:48:252319 // Use DnsClient only if it's fully configured and there is no override by
2320 // ScopedDefaultHostResolverProc.
2321 // The alternative is to use NetworkChangeNotifier to override DnsConfig,
2322 // but that would introduce construction order requirements for NCN and SDHRP.
[email protected]90499482013-06-01 00:39:502323 return (dns_client_.get() != NULL) && (dns_client_->GetConfig() != NULL) &&
2324 !(proc_params_.resolver_proc.get() == NULL &&
[email protected]32b1dbcf2013-01-26 03:48:252325 HostResolverProc::GetDefault() != NULL);
[email protected]b3601bc22012-02-21 21:23:202326}
2327
[email protected]1ffdda82012-12-12 23:04:222328void HostResolverImpl::OnDnsTaskResolve(int net_error) {
[email protected]f0f602bd2012-11-15 18:01:022329 DCHECK(dns_client_);
[email protected]1ffdda82012-12-12 23:04:222330 if (net_error == OK) {
[email protected]f0f602bd2012-11-15 18:01:022331 num_dns_failures_ = 0;
2332 return;
2333 }
2334 ++num_dns_failures_;
2335 if (num_dns_failures_ < kMaximumDnsFailures)
2336 return;
[email protected]daae1322013-09-05 18:26:502337
2338 // Disable DnsClient until the next DNS change. Must be done before aborting
2339 // DnsTasks, since doing so may start new jobs.
[email protected]f0f602bd2012-11-15 18:01:022340 dns_client_->SetConfig(DnsConfig());
[email protected]daae1322013-09-05 18:26:502341
2342 // Switch jobs with active DnsTasks over to using ProcTasks.
2343 AbortDnsTasks();
2344
[email protected]f0f602bd2012-11-15 18:01:022345 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", false);
[email protected]1ffdda82012-12-12 23:04:222346 UMA_HISTOGRAM_CUSTOM_ENUMERATION("AsyncDNS.DnsClientDisabledReason",
2347 std::abs(net_error),
2348 GetAllErrorCodesForUma());
[email protected]f0f602bd2012-11-15 18:01:022349}
2350
[email protected]a8883e452012-11-17 05:58:062351void HostResolverImpl::SetDnsClient(scoped_ptr<DnsClient> dns_client) {
[email protected]daae1322013-09-05 18:26:502352 // DnsClient and config must be updated before aborting DnsTasks, since doing
2353 // so may start new jobs.
[email protected]a8883e452012-11-17 05:58:062354 dns_client_ = dns_client.Pass();
[email protected]daae1322013-09-05 18:26:502355 if (dns_client_ && !dns_client_->GetConfig() &&
2356 num_dns_failures_ < kMaximumDnsFailures) {
2357 DnsConfig dns_config;
2358 NetworkChangeNotifier::GetDnsConfig(&dns_config);
2359 dns_client_->SetConfig(dns_config);
2360 num_dns_failures_ = 0;
2361 if (dns_client_->GetConfig())
2362 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
[email protected]a8883e452012-11-17 05:58:062363 }
[email protected]daae1322013-09-05 18:26:502364
2365 AbortDnsTasks();
[email protected]a8883e452012-11-17 05:58:062366}
2367
[email protected]b59ff372009-07-15 22:04:322368} // namespace net