blob: c8b37f73b30011007d989d4ca18493357d1c7332 [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"
vadimt7ecc40e2014-11-26 00:53:4027#include "base/profiler/scoped_tracker.h"
[email protected]7286e3fc2011-07-19 22:13:2428#include "base/stl_util.h"
[email protected]be528af2013-06-11 07:39:4829#include "base/strings/string_util.h"
[email protected]750b2f3c2013-06-07 18:41:0530#include "base/strings/utf_string_conversions.h"
[email protected]ac9ba8fe2010-12-30 18:08:3631#include "base/threading/worker_pool.h"
[email protected]66e96c42013-06-28 15:20:3132#include "base/time/time.h"
[email protected]21526002010-05-16 19:42:4633#include "base/values.h"
[email protected]b3601bc22012-02-21 21:23:2034#include "net/base/address_family.h"
[email protected]b59ff372009-07-15 22:04:3235#include "net/base/address_list.h"
[email protected]46018c9d2011-09-06 03:42:3436#include "net/base/dns_reloader.h"
[email protected]e806cd72013-05-17 02:08:4337#include "net/base/dns_util.h"
[email protected]ee094b82010-08-24 15:55:5138#include "net/base/host_port_pair.h"
[email protected]1c7cf3f82014-08-07 21:33:4839#include "net/base/ip_endpoint.h"
[email protected]2bb04442010-08-18 18:01:1540#include "net/base/net_errors.h"
[email protected]ee094b82010-08-24 15:55:5141#include "net/base/net_log.h"
[email protected]0f8f1b432010-03-16 19:06:0342#include "net/base/net_util.h"
[email protected]0adcb2b2012-08-15 21:30:4643#include "net/dns/address_sorter.h"
[email protected]78eac2a2012-03-14 19:09:2744#include "net/dns/dns_client.h"
[email protected]b3601bc22012-02-21 21:23:2045#include "net/dns/dns_config_service.h"
46#include "net/dns/dns_protocol.h"
47#include "net/dns/dns_response.h"
[email protected]b3601bc22012-02-21 21:23:2048#include "net/dns/dns_transaction.h"
[email protected]f2cb3cf2013-03-21 01:40:5349#include "net/dns/host_resolver_proc.h"
[email protected]9db6f702013-04-10 18:10:5150#include "net/socket/client_socket_factory.h"
51#include "net/udp/datagram_client_socket.h"
pauljensen370f1c72015-02-17 16:59:1452#include "url/url_canon_ip.h"
[email protected]b59ff372009-07-15 22:04:3253
54#if defined(OS_WIN)
55#include "net/base/winsock_init.h"
56#endif
57
58namespace net {
59
[email protected]e95d3aca2010-01-11 22:47:4360namespace {
61
[email protected]6e78dfb2011-07-28 21:34:4762// Limit the size of hostnames that will be resolved to combat issues in
63// some platform's resolvers.
64const size_t kMaxHostLength = 4096;
65
[email protected]a2730882012-01-21 00:56:2766// Default TTL for successful resolutions with ProcTask.
67const unsigned kCacheEntryTTLSeconds = 60;
68
[email protected]b3601bc22012-02-21 21:23:2069// Default TTL for unsuccessful resolutions with ProcTask.
70const unsigned kNegativeCacheEntryTTLSeconds = 0;
71
[email protected]895123222012-10-25 15:21:1772// Minimum TTL for successful resolutions with DnsTask.
73const unsigned kMinimumTTLSeconds = kCacheEntryTTLSeconds;
74
[email protected]24f4bab2010-10-15 01:27:1175// We use a separate histogram name for each platform to facilitate the
76// display of error codes by their symbolic name (since each platform has
77// different mappings).
78const char kOSErrorsForGetAddrinfoHistogramName[] =
79#if defined(OS_WIN)
80 "Net.OSErrorsForGetAddrinfo_Win";
81#elif defined(OS_MACOSX)
82 "Net.OSErrorsForGetAddrinfo_Mac";
83#elif defined(OS_LINUX)
84 "Net.OSErrorsForGetAddrinfo_Linux";
85#else
86 "Net.OSErrorsForGetAddrinfo";
87#endif
88
[email protected]c89b2442011-05-26 14:28:2789// Gets a list of the likely error codes that getaddrinfo() can return
90// (non-exhaustive). These are the error codes that we will track via
91// a histogram.
92std::vector<int> GetAllGetAddrinfoOSErrors() {
93 int os_errors[] = {
94#if defined(OS_POSIX)
[email protected]23f771162011-06-02 18:37:5195#if !defined(OS_FREEBSD)
[email protected]39588992011-07-11 19:54:3796#if !defined(OS_ANDROID)
[email protected]c48aef92011-11-22 23:41:4597 // EAI_ADDRFAMILY has been declared obsolete in Android's and
98 // FreeBSD's netdb.h.
[email protected]c89b2442011-05-26 14:28:2799 EAI_ADDRFAMILY,
[email protected]39588992011-07-11 19:54:37100#endif
[email protected]c48aef92011-11-22 23:41:45101 // EAI_NODATA has been declared obsolete in FreeBSD's netdb.h.
[email protected]23f771162011-06-02 18:37:51102 EAI_NODATA,
103#endif
[email protected]c89b2442011-05-26 14:28:27104 EAI_AGAIN,
105 EAI_BADFLAGS,
106 EAI_FAIL,
107 EAI_FAMILY,
108 EAI_MEMORY,
[email protected]c89b2442011-05-26 14:28:27109 EAI_NONAME,
110 EAI_SERVICE,
111 EAI_SOCKTYPE,
112 EAI_SYSTEM,
113#elif defined(OS_WIN)
114 // See: http://msdn.microsoft.com/en-us/library/ms738520(VS.85).aspx
115 WSA_NOT_ENOUGH_MEMORY,
116 WSAEAFNOSUPPORT,
117 WSAEINVAL,
118 WSAESOCKTNOSUPPORT,
119 WSAHOST_NOT_FOUND,
120 WSANO_DATA,
121 WSANO_RECOVERY,
122 WSANOTINITIALISED,
123 WSATRY_AGAIN,
124 WSATYPE_NOT_FOUND,
125 // The following are not in doc, but might be to appearing in results :-(.
126 WSA_INVALID_HANDLE,
127#endif
128 };
129
130 // Ensure all errors are positive, as histogram only tracks positive values.
131 for (size_t i = 0; i < arraysize(os_errors); ++i) {
132 os_errors[i] = std::abs(os_errors[i]);
133 }
134
135 return base::CustomHistogram::ArrayToCustomRanges(os_errors,
136 arraysize(os_errors));
137}
138
[email protected]1def74c2012-03-22 20:07:00139enum DnsResolveStatus {
140 RESOLVE_STATUS_DNS_SUCCESS = 0,
141 RESOLVE_STATUS_PROC_SUCCESS,
142 RESOLVE_STATUS_FAIL,
[email protected]1d932852012-06-19 19:40:33143 RESOLVE_STATUS_SUSPECT_NETBIOS,
[email protected]1def74c2012-03-22 20:07:00144 RESOLVE_STATUS_MAX
145};
146
eroman91dd3602015-03-26 03:46:33147// ICANN uses this localhost address to indicate a name collision.
148//
149// The policy in Chromium is to fail host resolving if it resolves to
150// this special address.
151//
152// Not however that IP literals are exempt from this policy, so it is still
153// possible to navigate to http://127.0.53.53/ directly.
154//
155// For more details: https://www.icann.org/news/announcement-2-2014-08-01-en
156const unsigned char kIcanNameCollisionIp[] = {127, 0, 53, 53};
157
[email protected]1def74c2012-03-22 20:07:00158void UmaAsyncDnsResolveStatus(DnsResolveStatus result) {
159 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ResolveStatus",
160 result,
161 RESOLVE_STATUS_MAX);
162}
163
[email protected]1d932852012-06-19 19:40:33164bool ResemblesNetBIOSName(const std::string& hostname) {
165 return (hostname.size() < 16) && (hostname.find('.') == std::string::npos);
166}
167
168// True if |hostname| ends with either ".local" or ".local.".
169bool ResemblesMulticastDNSName(const std::string& hostname) {
170 DCHECK(!hostname.empty());
171 const char kSuffix[] = ".local.";
172 const size_t kSuffixLen = sizeof(kSuffix) - 1;
173 const size_t kSuffixLenTrimmed = kSuffixLen - 1;
174 if (hostname[hostname.size() - 1] == '.') {
175 return hostname.size() > kSuffixLen &&
176 !hostname.compare(hostname.size() - kSuffixLen, kSuffixLen, kSuffix);
177 }
178 return hostname.size() > kSuffixLenTrimmed &&
179 !hostname.compare(hostname.size() - kSuffixLenTrimmed, kSuffixLenTrimmed,
180 kSuffix, kSuffixLenTrimmed);
181}
182
[email protected]34e61362013-07-24 20:41:56183// Attempts to connect a UDP socket to |dest|:53.
[email protected]2b74a2f2013-07-23 19:37:38184bool IsGloballyReachable(const IPAddressNumber& dest,
185 const BoundNetLog& net_log) {
[email protected]9db6f702013-04-10 18:10:51186 scoped_ptr<DatagramClientSocket> socket(
187 ClientSocketFactory::GetDefaultFactory()->CreateDatagramClientSocket(
188 DatagramSocket::DEFAULT_BIND,
189 RandIntCallback(),
[email protected]2b74a2f2013-07-23 19:37:38190 net_log.net_log(),
191 net_log.source()));
[email protected]34e61362013-07-24 20:41:56192 int rv = socket->Connect(IPEndPoint(dest, 53));
[email protected]e9051722013-04-12 21:58:18193 if (rv != OK)
194 return false;
195 IPEndPoint endpoint;
196 rv = socket->GetLocalAddress(&endpoint);
197 if (rv != OK)
198 return false;
[email protected]1c7cf3f82014-08-07 21:33:48199 DCHECK_EQ(ADDRESS_FAMILY_IPV6, endpoint.GetFamily());
[email protected]e9051722013-04-12 21:58:18200 const IPAddressNumber& address = endpoint.address();
201 bool is_link_local = (address[0] == 0xFE) && ((address[1] & 0xC0) == 0x80);
202 if (is_link_local)
203 return false;
204 const uint8 kTeredoPrefix[] = { 0x20, 0x01, 0, 0 };
205 bool is_teredo = std::equal(kTeredoPrefix,
206 kTeredoPrefix + arraysize(kTeredoPrefix),
207 address.begin());
208 if (is_teredo)
209 return false;
210 return true;
[email protected]9db6f702013-04-10 18:10:51211}
212
[email protected]51b9a6b2012-06-25 21:50:29213// Provide a common macro to simplify code and readability. We must use a
214// macro as the underlying HISTOGRAM macro creates static variables.
215#define DNS_HISTOGRAM(name, time) UMA_HISTOGRAM_CUSTOM_TIMES(name, time, \
216 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromHours(1), 100)
217
218// A macro to simplify code and readability.
219#define DNS_HISTOGRAM_BY_PRIORITY(basename, priority, time) \
220 do { \
221 switch (priority) { \
222 case HIGHEST: DNS_HISTOGRAM(basename "_HIGHEST", time); break; \
223 case MEDIUM: DNS_HISTOGRAM(basename "_MEDIUM", time); break; \
224 case LOW: DNS_HISTOGRAM(basename "_LOW", time); break; \
225 case LOWEST: DNS_HISTOGRAM(basename "_LOWEST", time); break; \
226 case IDLE: DNS_HISTOGRAM(basename "_IDLE", time); break; \
227 default: NOTREACHED(); break; \
228 } \
229 DNS_HISTOGRAM(basename, time); \
230 } while (0)
231
232// Record time from Request creation until a valid DNS response.
233void RecordTotalTime(bool had_dns_config,
234 bool speculative,
235 base::TimeDelta duration) {
236 if (had_dns_config) {
237 if (speculative) {
238 DNS_HISTOGRAM("AsyncDNS.TotalTime_speculative", duration);
239 } else {
240 DNS_HISTOGRAM("AsyncDNS.TotalTime", duration);
241 }
242 } else {
243 if (speculative) {
244 DNS_HISTOGRAM("DNS.TotalTime_speculative", duration);
245 } else {
246 DNS_HISTOGRAM("DNS.TotalTime", duration);
247 }
248 }
249}
250
[email protected]1339a2a22012-10-17 08:39:43251void RecordTTL(base::TimeDelta ttl) {
252 UMA_HISTOGRAM_CUSTOM_TIMES("AsyncDNS.TTL", ttl,
253 base::TimeDelta::FromSeconds(1),
254 base::TimeDelta::FromDays(1), 100);
255}
256
[email protected]16c2bd72013-06-28 01:19:22257bool ConfigureAsyncDnsNoFallbackFieldTrial() {
258 const bool kDefault = false;
259
260 // Configure the AsyncDns field trial as follows:
261 // groups AsyncDnsNoFallbackA and AsyncDnsNoFallbackB: return true,
262 // groups AsyncDnsA and AsyncDnsB: return false,
263 // groups SystemDnsA and SystemDnsB: return false,
264 // otherwise (trial absent): return default.
265 std::string group_name = base::FieldTrialList::FindFullName("AsyncDns");
266 if (!group_name.empty())
267 return StartsWithASCII(group_name, "AsyncDnsNoFallback", false);
268 return kDefault;
269}
270
[email protected]d7b9a2b2012-05-31 22:31:19271//-----------------------------------------------------------------------------
272
[email protected]895123222012-10-25 15:21:17273AddressList EnsurePortOnAddressList(const AddressList& list, uint16 port) {
274 if (list.empty() || list.front().port() == port)
275 return list;
276 return AddressList::CopyWithPort(list, port);
[email protected]7054e78f2012-05-07 21:44:56277}
278
[email protected]ec666ab22013-04-17 20:05:59279// Returns true if |addresses| contains only IPv4 loopback addresses.
280bool IsAllIPv4Loopback(const AddressList& addresses) {
281 for (unsigned i = 0; i < addresses.size(); ++i) {
282 const IPAddressNumber& address = addresses[i].address();
283 switch (addresses[i].GetFamily()) {
284 case ADDRESS_FAMILY_IPV4:
285 if (address[0] != 127)
286 return false;
287 break;
288 case ADDRESS_FAMILY_IPV6:
289 return false;
290 default:
291 NOTREACHED();
292 return false;
293 }
294 }
295 return true;
296}
297
[email protected]cd565142012-06-12 16:21:45298// Creates NetLog parameters when the resolve failed.
299base::Value* NetLogProcTaskFailedCallback(uint32 attempt_number,
300 int net_error,
301 int os_error,
302 NetLog::LogLevel /* log_level */) {
[email protected]ea5ef4c2013-06-13 22:50:27303 base::DictionaryValue* dict = new base::DictionaryValue();
[email protected]cd565142012-06-12 16:21:45304 if (attempt_number)
305 dict->SetInteger("attempt_number", attempt_number);
[email protected]21526002010-05-16 19:42:46306
[email protected]cd565142012-06-12 16:21:45307 dict->SetInteger("net_error", net_error);
[email protected]13024882011-05-18 23:19:16308
[email protected]cd565142012-06-12 16:21:45309 if (os_error) {
310 dict->SetInteger("os_error", os_error);
[email protected]21526002010-05-16 19:42:46311#if defined(OS_POSIX)
[email protected]cd565142012-06-12 16:21:45312 dict->SetString("os_error_string", gai_strerror(os_error));
[email protected]21526002010-05-16 19:42:46313#elif defined(OS_WIN)
[email protected]cd565142012-06-12 16:21:45314 // Map the error code to a human-readable string.
315 LPWSTR error_string = NULL;
Peter Kastingbe940e92014-11-20 23:14:08316 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
317 0, // Use the internal message table.
318 os_error,
319 0, // Use default language.
320 (LPWSTR)&error_string,
321 0, // Buffer size.
322 0); // Arguments (unused).
[email protected]ad65a3e2013-12-25 18:18:01323 dict->SetString("os_error_string", base::WideToUTF8(error_string));
[email protected]cd565142012-06-12 16:21:45324 LocalFree(error_string);
[email protected]21526002010-05-16 19:42:46325#endif
[email protected]21526002010-05-16 19:42:46326 }
327
[email protected]cd565142012-06-12 16:21:45328 return dict;
329}
[email protected]a9813302012-04-28 09:29:28330
[email protected]cd565142012-06-12 16:21:45331// Creates NetLog parameters when the DnsTask failed.
332base::Value* NetLogDnsTaskFailedCallback(int net_error,
333 int dns_error,
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 dict->SetInteger("net_error", net_error);
337 if (dns_error)
338 dict->SetInteger("dns_error", dns_error);
339 return dict;
[email protected]ee094b82010-08-24 15:55:51340};
341
[email protected]cd565142012-06-12 16:21:45342// Creates NetLog parameters containing the information in a RequestInfo object,
343// along with the associated NetLog::Source.
xunjieli26f90452014-11-10 16:23:02344base::Value* NetLogRequestInfoCallback(const HostResolver::RequestInfo* info,
[email protected]cd565142012-06-12 16:21:45345 NetLog::LogLevel /* log_level */) {
[email protected]ea5ef4c2013-06-13 22:50:27346 base::DictionaryValue* dict = new base::DictionaryValue();
[email protected]b3601bc22012-02-21 21:23:20347
[email protected]cd565142012-06-12 16:21:45348 dict->SetString("host", info->host_port_pair().ToString());
349 dict->SetInteger("address_family",
350 static_cast<int>(info->address_family()));
351 dict->SetBoolean("allow_cached_response", info->allow_cached_response());
352 dict->SetBoolean("is_speculative", info->is_speculative());
[email protected]cd565142012-06-12 16:21:45353 return dict;
354}
[email protected]b3601bc22012-02-21 21:23:20355
[email protected]cd565142012-06-12 16:21:45356// Creates NetLog parameters for the creation of a HostResolverImpl::Job.
357base::Value* NetLogJobCreationCallback(const NetLog::Source& source,
358 const std::string* host,
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);
362 dict->SetString("host", *host);
363 return dict;
364}
[email protected]a9813302012-04-28 09:29:28365
[email protected]cd565142012-06-12 16:21:45366// Creates NetLog parameters for HOST_RESOLVER_IMPL_JOB_ATTACH/DETACH events.
367base::Value* NetLogJobAttachCallback(const NetLog::Source& source,
368 RequestPriority priority,
369 NetLog::LogLevel /* log_level */) {
[email protected]ea5ef4c2013-06-13 22:50:27370 base::DictionaryValue* dict = new base::DictionaryValue();
[email protected]cd565142012-06-12 16:21:45371 source.AddToEventParameters(dict);
[email protected]3b04d1f22013-10-16 00:23:56372 dict->SetString("priority", RequestPriorityToString(priority));
[email protected]cd565142012-06-12 16:21:45373 return dict;
374}
[email protected]b3601bc22012-02-21 21:23:20375
[email protected]cd565142012-06-12 16:21:45376// Creates NetLog parameters for the DNS_CONFIG_CHANGED event.
377base::Value* NetLogDnsConfigCallback(const DnsConfig* config,
378 NetLog::LogLevel /* log_level */) {
379 return config->ToValue();
380}
[email protected]b4481b222012-03-16 17:13:11381
[email protected]0f292de02012-02-01 22:28:20382// The logging routines are defined here because some requests are resolved
383// without a Request object.
384
385// Logs when a request has just been started.
386void LogStartRequest(const BoundNetLog& source_net_log,
[email protected]0f292de02012-02-01 22:28:20387 const HostResolver::RequestInfo& info) {
388 source_net_log.BeginEvent(
[email protected]0f292de02012-02-01 22:28:20389 NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST,
xunjieli26f90452014-11-10 16:23:02390 base::Bind(&NetLogRequestInfoCallback, &info));
[email protected]0f292de02012-02-01 22:28:20391}
392
393// Logs when a request has just completed (before its callback is run).
394void LogFinishRequest(const BoundNetLog& source_net_log,
[email protected]0f292de02012-02-01 22:28:20395 const HostResolver::RequestInfo& info,
[email protected]b3601bc22012-02-21 21:23:20396 int net_error) {
xunjieli26f90452014-11-10 16:23:02397 source_net_log.EndEventWithNetErrorCode(
[email protected]b3601bc22012-02-21 21:23:20398 NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST, net_error);
[email protected]0f292de02012-02-01 22:28:20399}
400
401// Logs when a request has been cancelled.
402void LogCancelRequest(const BoundNetLog& source_net_log,
[email protected]0f292de02012-02-01 22:28:20403 const HostResolverImpl::RequestInfo& info) {
xunjieli26f90452014-11-10 16:23:02404 source_net_log.AddEvent(NetLog::TYPE_CANCELLED);
405 source_net_log.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST);
[email protected]0f292de02012-02-01 22:28:20406}
407
[email protected]b59ff372009-07-15 22:04:32408//-----------------------------------------------------------------------------
409
[email protected]0f292de02012-02-01 22:28:20410// Keeps track of the highest priority.
411class PriorityTracker {
412 public:
[email protected]8c98d002012-07-18 19:02:27413 explicit PriorityTracker(RequestPriority initial_priority)
414 : highest_priority_(initial_priority), total_count_(0) {
[email protected]0f292de02012-02-01 22:28:20415 memset(counts_, 0, sizeof(counts_));
416 }
417
418 RequestPriority highest_priority() const {
419 return highest_priority_;
420 }
421
422 size_t total_count() const {
423 return total_count_;
424 }
425
426 void Add(RequestPriority req_priority) {
427 ++total_count_;
428 ++counts_[req_priority];
[email protected]31ae7ab2012-04-24 21:09:05429 if (highest_priority_ < req_priority)
[email protected]0f292de02012-02-01 22:28:20430 highest_priority_ = req_priority;
431 }
432
433 void Remove(RequestPriority req_priority) {
434 DCHECK_GT(total_count_, 0u);
435 DCHECK_GT(counts_[req_priority], 0u);
436 --total_count_;
437 --counts_[req_priority];
438 size_t i;
[email protected]31ae7ab2012-04-24 21:09:05439 for (i = highest_priority_; i > MINIMUM_PRIORITY && !counts_[i]; --i);
[email protected]0f292de02012-02-01 22:28:20440 highest_priority_ = static_cast<RequestPriority>(i);
441
[email protected]31ae7ab2012-04-24 21:09:05442 // In absence of requests, default to MINIMUM_PRIORITY.
443 if (total_count_ == 0)
444 DCHECK_EQ(MINIMUM_PRIORITY, highest_priority_);
[email protected]0f292de02012-02-01 22:28:20445 }
446
447 private:
448 RequestPriority highest_priority_;
449 size_t total_count_;
450 size_t counts_[NUM_PRIORITIES];
451};
452
[email protected]c54a8912012-10-22 22:09:43453} // namespace
[email protected]0f292de02012-02-01 22:28:20454
455//-----------------------------------------------------------------------------
456
[email protected]daae1322013-09-05 18:26:50457const unsigned HostResolverImpl::kMaximumDnsFailures = 16;
458
[email protected]0f292de02012-02-01 22:28:20459// Holds the data for a request that could not be completed synchronously.
460// It is owned by a Job. Canceled Requests are only marked as canceled rather
461// than removed from the Job's |requests_| list.
[email protected]b59ff372009-07-15 22:04:32462class HostResolverImpl::Request {
463 public:
[email protected]ee094b82010-08-24 15:55:51464 Request(const BoundNetLog& source_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),
[email protected]54e13772009-08-14 03:01:09470 info_(info),
[email protected]5109c1952013-08-20 18:44:10471 priority_(priority),
[email protected]54e13772009-08-14 03:01:09472 job_(NULL),
473 callback_(callback),
[email protected]51b9a6b2012-06-25 21:50:29474 addresses_(addresses),
[email protected]5109c1952013-08-20 18:44:10475 request_time_(base::TimeTicks::Now()) {}
[email protected]b59ff372009-07-15 22:04:32476
[email protected]0f292de02012-02-01 22:28:20477 // Mark the request as canceled.
478 void MarkAsCanceled() {
[email protected]b59ff372009-07-15 22:04:32479 job_ = NULL;
[email protected]b59ff372009-07-15 22:04:32480 addresses_ = NULL;
[email protected]aa22b242011-11-16 18:58:29481 callback_.Reset();
[email protected]b59ff372009-07-15 22:04:32482 }
483
[email protected]0f292de02012-02-01 22:28:20484 bool was_canceled() const {
[email protected]aa22b242011-11-16 18:58:29485 return callback_.is_null();
[email protected]b59ff372009-07-15 22:04:32486 }
487
488 void set_job(Job* job) {
[email protected]0f292de02012-02-01 22:28:20489 DCHECK(job);
[email protected]b59ff372009-07-15 22:04:32490 // Identify which job the request is waiting on.
491 job_ = job;
492 }
493
[email protected]0f292de02012-02-01 22:28:20494 // Prepare final AddressList and call completion callback.
[email protected]b3601bc22012-02-21 21:23:20495 void OnComplete(int error, const AddressList& addr_list) {
vadimt7ecc40e2014-11-26 00:53:40496 // TODO(vadimt): Remove ScopedTracker below once crbug.com/436634 is fixed.
497 tracked_objects::ScopedTracker tracking_profile(
498 FROM_HERE_WITH_EXPLICIT_FUNCTION(
499 "436634 HostResolverImpl::Request::OnComplete"));
500
[email protected]51b9a6b2012-06-25 21:50:29501 DCHECK(!was_canceled());
[email protected]895123222012-10-25 15:21:17502 if (error == OK)
503 *addresses_ = EnsurePortOnAddressList(addr_list, info_.port());
[email protected]aa22b242011-11-16 18:58:29504 CompletionCallback callback = callback_;
[email protected]0f292de02012-02-01 22:28:20505 MarkAsCanceled();
[email protected]aa22b242011-11-16 18:58:29506 callback.Run(error);
[email protected]b59ff372009-07-15 22:04:32507 }
508
[email protected]b59ff372009-07-15 22:04:32509 Job* job() const {
510 return job_;
511 }
512
[email protected]0f292de02012-02-01 22:28:20513 // NetLog for the source, passed in HostResolver::Resolve.
[email protected]ee094b82010-08-24 15:55:51514 const BoundNetLog& source_net_log() {
515 return source_net_log_;
516 }
517
[email protected]b59ff372009-07-15 22:04:32518 const RequestInfo& info() const {
519 return info_;
520 }
521
[email protected]5109c1952013-08-20 18:44:10522 RequestPriority priority() const { return priority_; }
523
524 base::TimeTicks request_time() const { return request_time_; }
[email protected]51b9a6b2012-06-25 21:50:29525
[email protected]b59ff372009-07-15 22:04:32526 private:
xunjieli26f90452014-11-10 16:23:02527 const BoundNetLog source_net_log_;
[email protected]54e13772009-08-14 03:01:09528
[email protected]b59ff372009-07-15 22:04:32529 // The request info that started the request.
[email protected]5109c1952013-08-20 18:44:10530 const RequestInfo info_;
531
532 // TODO(akalin): Support reprioritization.
533 const RequestPriority priority_;
[email protected]b59ff372009-07-15 22:04:32534
[email protected]0f292de02012-02-01 22:28:20535 // The resolve job that this request is dependent on.
[email protected]b59ff372009-07-15 22:04:32536 Job* job_;
537
538 // The user's callback to invoke when the request completes.
[email protected]aa22b242011-11-16 18:58:29539 CompletionCallback callback_;
[email protected]b59ff372009-07-15 22:04:32540
541 // The address list to save result into.
542 AddressList* addresses_;
543
[email protected]51b9a6b2012-06-25 21:50:29544 const base::TimeTicks request_time_;
545
[email protected]b59ff372009-07-15 22:04:32546 DISALLOW_COPY_AND_ASSIGN(Request);
547};
548
[email protected]1e9bbd22010-10-15 16:42:45549//------------------------------------------------------------------------------
550
[email protected]0f292de02012-02-01 22:28:20551// Calls HostResolverProc on the WorkerPool. Performs retries if necessary.
552//
553// Whenever we try to resolve the host, we post a delayed task to check if host
554// resolution (OnLookupComplete) is completed or not. If the original attempt
555// hasn't completed, then we start another attempt for host resolution. We take
556// the results from the first attempt that finishes and ignore the results from
557// all other attempts.
558//
559// TODO(szym): Move to separate source file for testing and mocking.
560//
561class HostResolverImpl::ProcTask
562 : public base::RefCountedThreadSafe<HostResolverImpl::ProcTask> {
[email protected]b59ff372009-07-15 22:04:32563 public:
[email protected]b3601bc22012-02-21 21:23:20564 typedef base::Callback<void(int net_error,
565 const AddressList& addr_list)> Callback;
[email protected]b59ff372009-07-15 22:04:32566
[email protected]0f292de02012-02-01 22:28:20567 ProcTask(const Key& key,
568 const ProcTaskParams& params,
569 const Callback& callback,
570 const BoundNetLog& job_net_log)
571 : key_(key),
572 params_(params),
573 callback_(callback),
574 origin_loop_(base::MessageLoopProxy::current()),
575 attempt_number_(0),
576 completed_attempt_number_(0),
577 completed_attempt_error_(ERR_UNEXPECTED),
578 had_non_speculative_request_(false),
[email protected]b3601bc22012-02-21 21:23:20579 net_log_(job_net_log) {
[email protected]90499482013-06-01 00:39:50580 if (!params_.resolver_proc.get())
[email protected]0f292de02012-02-01 22:28:20581 params_.resolver_proc = HostResolverProc::GetDefault();
582 // If default is unset, use the system proc.
[email protected]90499482013-06-01 00:39:50583 if (!params_.resolver_proc.get())
[email protected]1ee9afa12013-04-16 14:18:06584 params_.resolver_proc = new SystemHostResolverProc();
[email protected]b59ff372009-07-15 22:04:32585 }
586
[email protected]b59ff372009-07-15 22:04:32587 void Start() {
[email protected]3e9d9cc2011-05-03 21:08:15588 DCHECK(origin_loop_->BelongsToCurrentThread());
[email protected]4da911f2012-06-14 19:45:20589 net_log_.BeginEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK);
[email protected]189163e2011-05-11 01:48:54590 StartLookupAttempt();
591 }
[email protected]252b699b2010-02-05 21:38:06592
[email protected]0f292de02012-02-01 22:28:20593 // Cancels this ProcTask. It will be orphaned. Any outstanding resolve
594 // attempts running on worker threads will continue running. Only once all the
595 // attempts complete will the final reference to this ProcTask be released.
596 void Cancel() {
597 DCHECK(origin_loop_->BelongsToCurrentThread());
598
[email protected]0adcb2b2012-08-15 21:30:46599 if (was_canceled() || was_completed())
[email protected]0f292de02012-02-01 22:28:20600 return;
601
[email protected]0f292de02012-02-01 22:28:20602 callback_.Reset();
[email protected]4da911f2012-06-14 19:45:20603 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK);
[email protected]0f292de02012-02-01 22:28:20604 }
605
606 void set_had_non_speculative_request() {
607 DCHECK(origin_loop_->BelongsToCurrentThread());
608 had_non_speculative_request_ = true;
609 }
610
611 bool was_canceled() const {
612 DCHECK(origin_loop_->BelongsToCurrentThread());
613 return callback_.is_null();
614 }
615
616 bool was_completed() const {
617 DCHECK(origin_loop_->BelongsToCurrentThread());
618 return completed_attempt_number_ > 0;
619 }
620
621 private:
[email protected]a9813302012-04-28 09:29:28622 friend class base::RefCountedThreadSafe<ProcTask>;
623 ~ProcTask() {}
624
[email protected]189163e2011-05-11 01:48:54625 void StartLookupAttempt() {
626 DCHECK(origin_loop_->BelongsToCurrentThread());
627 base::TimeTicks start_time = base::TimeTicks::Now();
628 ++attempt_number_;
629 // Dispatch the lookup attempt to a worker thread.
630 if (!base::WorkerPool::PostTask(
631 FROM_HERE,
[email protected]0f292de02012-02-01 22:28:20632 base::Bind(&ProcTask::DoLookup, this, start_time, attempt_number_),
[email protected]189163e2011-05-11 01:48:54633 true)) {
[email protected]b59ff372009-07-15 22:04:32634 NOTREACHED();
635
636 // Since we could be running within Resolve() right now, we can't just
637 // call OnLookupComplete(). Instead we must wait until Resolve() has
638 // returned (IO_PENDING).
[email protected]3e9d9cc2011-05-03 21:08:15639 origin_loop_->PostTask(
[email protected]189163e2011-05-11 01:48:54640 FROM_HERE,
[email protected]0f292de02012-02-01 22:28:20641 base::Bind(&ProcTask::OnLookupComplete, this, AddressList(),
[email protected]33152acc2011-10-20 23:37:12642 start_time, attempt_number_, ERR_UNEXPECTED, 0));
[email protected]189163e2011-05-11 01:48:54643 return;
[email protected]b59ff372009-07-15 22:04:32644 }
[email protected]13024882011-05-18 23:19:16645
646 net_log_.AddEvent(
647 NetLog::TYPE_HOST_RESOLVER_IMPL_ATTEMPT_STARTED,
[email protected]cd565142012-06-12 16:21:45648 NetLog::IntegerCallback("attempt_number", attempt_number_));
[email protected]13024882011-05-18 23:19:16649
[email protected]0f292de02012-02-01 22:28:20650 // If we don't get the results within a given time, RetryIfNotComplete
651 // will start a new attempt on a different worker thread if none of our
652 // outstanding attempts have completed yet.
653 if (attempt_number_ <= params_.max_retry_attempts) {
[email protected]06ef6d92011-05-19 04:24:58654 origin_loop_->PostDelayedTask(
655 FROM_HERE,
[email protected]0f292de02012-02-01 22:28:20656 base::Bind(&ProcTask::RetryIfNotComplete, this),
[email protected]7e560102012-03-08 20:58:42657 params_.unresponsive_delay);
[email protected]06ef6d92011-05-19 04:24:58658 }
[email protected]b59ff372009-07-15 22:04:32659 }
660
[email protected]6c710ee2010-05-07 07:51:16661 // WARNING: This code runs inside a worker pool. The shutdown code cannot
662 // wait for it to finish, so we must be very careful here about using other
663 // objects (like MessageLoops, Singletons, etc). During shutdown these objects
[email protected]189163e2011-05-11 01:48:54664 // may no longer exist. Multiple DoLookups() could be running in parallel, so
665 // any state inside of |this| must not mutate .
666 void DoLookup(const base::TimeTicks& start_time,
667 const uint32 attempt_number) {
668 AddressList results;
669 int os_error = 0;
[email protected]b59ff372009-07-15 22:04:32670 // Running on the worker thread
[email protected]0f292de02012-02-01 22:28:20671 int error = params_.resolver_proc->Resolve(key_.hostname,
672 key_.address_family,
673 key_.host_resolver_flags,
674 &results,
675 &os_error);
[email protected]b59ff372009-07-15 22:04:32676
eroman91dd3602015-03-26 03:46:33677 // Fail the resolution if the result contains 127.0.53.53. See the comment
678 // block of kIcanNameCollisionIp for details on why.
679 for (const auto& it : results) {
680 const IPAddressNumber& cur = it.address();
681 if (cur.size() == arraysize(kIcanNameCollisionIp) &&
682 0 == memcmp(&cur.front(), kIcanNameCollisionIp, cur.size())) {
683 error = ERR_ICANN_NAME_COLLISION;
684 break;
685 }
686 }
687
[email protected]189163e2011-05-11 01:48:54688 origin_loop_->PostTask(
689 FROM_HERE,
[email protected]0f292de02012-02-01 22:28:20690 base::Bind(&ProcTask::OnLookupComplete, this, results, start_time,
[email protected]33152acc2011-10-20 23:37:12691 attempt_number, error, os_error));
[email protected]189163e2011-05-11 01:48:54692 }
693
[email protected]0f292de02012-02-01 22:28:20694 // Makes next attempt if DoLookup() has not finished (runs on origin thread).
695 void RetryIfNotComplete() {
[email protected]189163e2011-05-11 01:48:54696 DCHECK(origin_loop_->BelongsToCurrentThread());
697
[email protected]0f292de02012-02-01 22:28:20698 if (was_completed() || was_canceled())
[email protected]189163e2011-05-11 01:48:54699 return;
700
[email protected]0f292de02012-02-01 22:28:20701 params_.unresponsive_delay *= params_.retry_factor;
[email protected]189163e2011-05-11 01:48:54702 StartLookupAttempt();
[email protected]b59ff372009-07-15 22:04:32703 }
704
705 // Callback for when DoLookup() completes (runs on origin thread).
[email protected]189163e2011-05-11 01:48:54706 void OnLookupComplete(const AddressList& results,
707 const base::TimeTicks& start_time,
708 const uint32 attempt_number,
709 int error,
710 const int os_error) {
vadimt7ecc40e2014-11-26 00:53:40711 // TODO(vadimt): Remove ScopedTracker below once crbug.com/436634 is fixed.
712 tracked_objects::ScopedTracker tracking_profile1(
713 FROM_HERE_WITH_EXPLICIT_FUNCTION(
714 "436634 HostResolverImpl::ProcTask::OnLookupComplete1"));
715
[email protected]3e9d9cc2011-05-03 21:08:15716 DCHECK(origin_loop_->BelongsToCurrentThread());
[email protected]49b70b222013-05-07 21:24:23717 // If results are empty, we should return an error.
718 bool empty_list_on_ok = (error == OK && results.empty());
719 UMA_HISTOGRAM_BOOLEAN("DNS.EmptyAddressListAndNoError", empty_list_on_ok);
720 if (empty_list_on_ok)
721 error = ERR_NAME_NOT_RESOLVED;
[email protected]189163e2011-05-11 01:48:54722
723 bool was_retry_attempt = attempt_number > 1;
724
[email protected]2d3b7762010-10-09 00:35:47725 // Ideally the following code would be part of host_resolver_proc.cc,
[email protected]b3601bc22012-02-21 21:23:20726 // however it isn't safe to call NetworkChangeNotifier from worker threads.
727 // So we do it here on the IO thread instead.
[email protected]189163e2011-05-11 01:48:54728 if (error != OK && NetworkChangeNotifier::IsOffline())
729 error = ERR_INTERNET_DISCONNECTED;
[email protected]2d3b7762010-10-09 00:35:47730
[email protected]b3601bc22012-02-21 21:23:20731 // If this is the first attempt that is finishing later, then record data
732 // for the first attempt. Won't contaminate with retry attempt's data.
[email protected]189163e2011-05-11 01:48:54733 if (!was_retry_attempt)
734 RecordPerformanceHistograms(start_time, error, os_error);
735
736 RecordAttemptHistograms(start_time, attempt_number, error, os_error);
[email protected]f2d8c4212010-02-02 00:56:35737
[email protected]0f292de02012-02-01 22:28:20738 if (was_canceled())
[email protected]b59ff372009-07-15 22:04:32739 return;
740
[email protected]cd565142012-06-12 16:21:45741 NetLog::ParametersCallback net_log_callback;
[email protected]0f292de02012-02-01 22:28:20742 if (error != OK) {
[email protected]cd565142012-06-12 16:21:45743 net_log_callback = base::Bind(&NetLogProcTaskFailedCallback,
744 attempt_number,
745 error,
746 os_error);
[email protected]0f292de02012-02-01 22:28:20747 } else {
[email protected]cd565142012-06-12 16:21:45748 net_log_callback = NetLog::IntegerCallback("attempt_number",
749 attempt_number);
[email protected]0f292de02012-02-01 22:28:20750 }
[email protected]cd565142012-06-12 16:21:45751 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_ATTEMPT_FINISHED,
752 net_log_callback);
[email protected]0f292de02012-02-01 22:28:20753
754 if (was_completed())
755 return;
756
757 // Copy the results from the first worker thread that resolves the host.
758 results_ = results;
759 completed_attempt_number_ = attempt_number;
760 completed_attempt_error_ = error;
761
[email protected]e87b8b512011-06-14 22:12:52762 if (was_retry_attempt) {
763 // If retry attempt finishes before 1st attempt, then get stats on how
764 // much time is saved by having spawned an extra attempt.
765 retry_attempt_finished_time_ = base::TimeTicks::Now();
766 }
767
[email protected]189163e2011-05-11 01:48:54768 if (error != OK) {
[email protected]cd565142012-06-12 16:21:45769 net_log_callback = base::Bind(&NetLogProcTaskFailedCallback,
770 0, error, os_error);
[email protected]ee094b82010-08-24 15:55:51771 } else {
[email protected]cd565142012-06-12 16:21:45772 net_log_callback = results_.CreateNetLogCallback();
[email protected]ee094b82010-08-24 15:55:51773 }
[email protected]cd565142012-06-12 16:21:45774 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK,
775 net_log_callback);
[email protected]ee094b82010-08-24 15:55:51776
vadimt7ecc40e2014-11-26 00:53:40777 // TODO(vadimt): Remove ScopedTracker below once crbug.com/436634 is fixed.
778 tracked_objects::ScopedTracker tracking_profile2(
779 FROM_HERE_WITH_EXPLICIT_FUNCTION(
780 "436634 HostResolverImpl::ProcTask::OnLookupComplete2"));
781
[email protected]b3601bc22012-02-21 21:23:20782 callback_.Run(error, results_);
[email protected]b59ff372009-07-15 22:04:32783 }
784
[email protected]189163e2011-05-11 01:48:54785 void RecordPerformanceHistograms(const base::TimeTicks& start_time,
786 const int error,
787 const int os_error) const {
[email protected]3e9d9cc2011-05-03 21:08:15788 DCHECK(origin_loop_->BelongsToCurrentThread());
asvitkinec0fb8022014-08-26 04:39:35789 enum Category { // Used in UMA_HISTOGRAM_ENUMERATION.
[email protected]1e9bbd22010-10-15 16:42:45790 RESOLVE_SUCCESS,
791 RESOLVE_FAIL,
792 RESOLVE_SPECULATIVE_SUCCESS,
793 RESOLVE_SPECULATIVE_FAIL,
794 RESOLVE_MAX, // Bounding value.
795 };
796 int category = RESOLVE_MAX; // Illegal value for later DCHECK only.
797
[email protected]189163e2011-05-11 01:48:54798 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
799 if (error == OK) {
[email protected]1e9bbd22010-10-15 16:42:45800 if (had_non_speculative_request_) {
801 category = RESOLVE_SUCCESS;
802 DNS_HISTOGRAM("DNS.ResolveSuccess", duration);
803 } else {
804 category = RESOLVE_SPECULATIVE_SUCCESS;
805 DNS_HISTOGRAM("DNS.ResolveSpeculativeSuccess", duration);
806 }
[email protected]7e96d792011-06-10 17:08:23807
[email protected]78eac2a2012-03-14 19:09:27808 // Log DNS lookups based on |address_family|. This will help us determine
[email protected]7e96d792011-06-10 17:08:23809 // if IPv4 or IPv4/6 lookups are faster or slower.
810 switch(key_.address_family) {
811 case ADDRESS_FAMILY_IPV4:
812 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_IPV4", duration);
813 break;
814 case ADDRESS_FAMILY_IPV6:
815 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_IPV6", duration);
816 break;
817 case ADDRESS_FAMILY_UNSPECIFIED:
818 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_UNSPEC", duration);
819 break;
820 }
[email protected]1e9bbd22010-10-15 16:42:45821 } else {
822 if (had_non_speculative_request_) {
823 category = RESOLVE_FAIL;
824 DNS_HISTOGRAM("DNS.ResolveFail", duration);
825 } else {
826 category = RESOLVE_SPECULATIVE_FAIL;
827 DNS_HISTOGRAM("DNS.ResolveSpeculativeFail", duration);
828 }
[email protected]78eac2a2012-03-14 19:09:27829 // Log DNS lookups based on |address_family|. This will help us determine
[email protected]7e96d792011-06-10 17:08:23830 // if IPv4 or IPv4/6 lookups are faster or slower.
831 switch(key_.address_family) {
832 case ADDRESS_FAMILY_IPV4:
833 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_IPV4", duration);
834 break;
835 case ADDRESS_FAMILY_IPV6:
836 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_IPV6", duration);
837 break;
838 case ADDRESS_FAMILY_UNSPECIFIED:
839 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_UNSPEC", duration);
840 break;
841 }
[email protected]c833e322010-10-16 23:51:36842 UMA_HISTOGRAM_CUSTOM_ENUMERATION(kOSErrorsForGetAddrinfoHistogramName,
[email protected]189163e2011-05-11 01:48:54843 std::abs(os_error),
[email protected]1e9bbd22010-10-15 16:42:45844 GetAllGetAddrinfoOSErrors());
845 }
[email protected]051b6ab2010-10-18 16:50:46846 DCHECK_LT(category, static_cast<int>(RESOLVE_MAX)); // Be sure it was set.
[email protected]1e9bbd22010-10-15 16:42:45847
848 UMA_HISTOGRAM_ENUMERATION("DNS.ResolveCategory", category, RESOLVE_MAX);
[email protected]1e9bbd22010-10-15 16:42:45849 }
850
[email protected]189163e2011-05-11 01:48:54851 void RecordAttemptHistograms(const base::TimeTicks& start_time,
852 const uint32 attempt_number,
853 const int error,
854 const int os_error) const {
[email protected]0f292de02012-02-01 22:28:20855 DCHECK(origin_loop_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54856 bool first_attempt_to_complete =
857 completed_attempt_number_ == attempt_number;
[email protected]e87b8b512011-06-14 22:12:52858 bool is_first_attempt = (attempt_number == 1);
[email protected]1e9bbd22010-10-15 16:42:45859
[email protected]189163e2011-05-11 01:48:54860 if (first_attempt_to_complete) {
861 // If this was first attempt to complete, then record the resolution
862 // status of the attempt.
863 if (completed_attempt_error_ == OK) {
864 UMA_HISTOGRAM_ENUMERATION(
865 "DNS.AttemptFirstSuccess", attempt_number, 100);
866 } else {
867 UMA_HISTOGRAM_ENUMERATION(
868 "DNS.AttemptFirstFailure", attempt_number, 100);
869 }
870 }
871
872 if (error == OK)
873 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptSuccess", attempt_number, 100);
874 else
875 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptFailure", attempt_number, 100);
876
[email protected]e87b8b512011-06-14 22:12:52877 // If first attempt didn't finish before retry attempt, then calculate stats
878 // on how much time is saved by having spawned an extra attempt.
[email protected]0f292de02012-02-01 22:28:20879 if (!first_attempt_to_complete && is_first_attempt && !was_canceled()) {
[email protected]e87b8b512011-06-14 22:12:52880 DNS_HISTOGRAM("DNS.AttemptTimeSavedByRetry",
881 base::TimeTicks::Now() - retry_attempt_finished_time_);
882 }
883
[email protected]0f292de02012-02-01 22:28:20884 if (was_canceled() || !first_attempt_to_complete) {
[email protected]189163e2011-05-11 01:48:54885 // Count those attempts which completed after the job was already canceled
886 // OR after the job was already completed by an earlier attempt (so in
887 // effect).
888 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptDiscarded", attempt_number, 100);
889
[email protected]0f292de02012-02-01 22:28:20890 // Record if job is canceled.
891 if (was_canceled())
[email protected]189163e2011-05-11 01:48:54892 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptCancelled", attempt_number, 100);
893 }
894
895 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
896 if (error == OK)
897 DNS_HISTOGRAM("DNS.AttemptSuccessDuration", duration);
898 else
899 DNS_HISTOGRAM("DNS.AttemptFailDuration", duration);
900 }
[email protected]1e9bbd22010-10-15 16:42:45901
[email protected]b59ff372009-07-15 22:04:32902 // Set on the origin thread, read on the worker thread.
[email protected]123ab1e32009-10-21 19:12:57903 Key key_;
[email protected]b59ff372009-07-15 22:04:32904
[email protected]0f292de02012-02-01 22:28:20905 // Holds an owning reference to the HostResolverProc that we are going to use.
[email protected]b59ff372009-07-15 22:04:32906 // This may not be the current resolver procedure by the time we call
907 // ResolveAddrInfo, but that's OK... we'll use it anyways, and the owning
908 // reference ensures that it remains valid until we are done.
[email protected]0f292de02012-02-01 22:28:20909 ProcTaskParams params_;
[email protected]b59ff372009-07-15 22:04:32910
[email protected]0f292de02012-02-01 22:28:20911 // The listener to the results of this ProcTask.
912 Callback callback_;
913
914 // Used to post ourselves onto the origin thread.
915 scoped_refptr<base::MessageLoopProxy> origin_loop_;
[email protected]189163e2011-05-11 01:48:54916
917 // Keeps track of the number of attempts we have made so far to resolve the
918 // host. Whenever we start an attempt to resolve the host, we increase this
919 // number.
920 uint32 attempt_number_;
921
922 // The index of the attempt which finished first (or 0 if the job is still in
923 // progress).
924 uint32 completed_attempt_number_;
925
926 // The result (a net error code) from the first attempt to complete.
927 int completed_attempt_error_;
[email protected]252b699b2010-02-05 21:38:06928
[email protected]e87b8b512011-06-14 22:12:52929 // The time when retry attempt was finished.
930 base::TimeTicks retry_attempt_finished_time_;
931
[email protected]252b699b2010-02-05 21:38:06932 // True if a non-speculative request was ever attached to this job
[email protected]0f292de02012-02-01 22:28:20933 // (regardless of whether or not it was later canceled.
[email protected]252b699b2010-02-05 21:38:06934 // This boolean is used for histogramming the duration of jobs used to
935 // service non-speculative requests.
936 bool had_non_speculative_request_;
937
[email protected]b59ff372009-07-15 22:04:32938 AddressList results_;
939
[email protected]ee094b82010-08-24 15:55:51940 BoundNetLog net_log_;
941
[email protected]0f292de02012-02-01 22:28:20942 DISALLOW_COPY_AND_ASSIGN(ProcTask);
[email protected]b59ff372009-07-15 22:04:32943};
944
945//-----------------------------------------------------------------------------
946
[email protected]12faa4c2012-11-06 04:44:18947// Wraps a call to HaveOnlyLoopbackAddresses to be executed on the WorkerPool as
948// it takes 40-100ms and should not block initialization.
949class HostResolverImpl::LoopbackProbeJob {
950 public:
951 explicit LoopbackProbeJob(const base::WeakPtr<HostResolverImpl>& resolver)
952 : resolver_(resolver),
953 result_(false) {
[email protected]11fbca0b2013-06-02 23:37:21954 DCHECK(resolver.get());
[email protected]12faa4c2012-11-06 04:44:18955 const bool kIsSlow = true;
956 base::WorkerPool::PostTaskAndReply(
957 FROM_HERE,
958 base::Bind(&LoopbackProbeJob::DoProbe, base::Unretained(this)),
959 base::Bind(&LoopbackProbeJob::OnProbeComplete, base::Owned(this)),
960 kIsSlow);
961 }
962
963 virtual ~LoopbackProbeJob() {}
964
965 private:
966 // Runs on worker thread.
967 void DoProbe() {
968 result_ = HaveOnlyLoopbackAddresses();
969 }
970
971 void OnProbeComplete() {
[email protected]11fbca0b2013-06-02 23:37:21972 if (!resolver_.get())
[email protected]12faa4c2012-11-06 04:44:18973 return;
974 resolver_->SetHaveOnlyLoopbackAddresses(result_);
975 }
976
977 // Used/set only on origin thread.
978 base::WeakPtr<HostResolverImpl> resolver_;
979
980 bool result_;
981
982 DISALLOW_COPY_AND_ASSIGN(LoopbackProbeJob);
983};
984
[email protected]0f8f1b432010-03-16 19:06:03985//-----------------------------------------------------------------------------
986
[email protected]b3601bc22012-02-21 21:23:20987// Resolves the hostname using DnsTransaction.
988// TODO(szym): This could be moved to separate source file as well.
[email protected]0adcb2b2012-08-15 21:30:46989class HostResolverImpl::DnsTask : public base::SupportsWeakPtr<DnsTask> {
[email protected]b3601bc22012-02-21 21:23:20990 public:
[email protected]daae1322013-09-05 18:26:50991 class Delegate {
992 public:
993 virtual void OnDnsTaskComplete(base::TimeTicks start_time,
994 int net_error,
995 const AddressList& addr_list,
996 base::TimeDelta ttl) = 0;
997
998 // Called when the first of two jobs succeeds. If the first completed
999 // transaction fails, this is not called. Also not called when the DnsTask
1000 // only needs to run one transaction.
1001 virtual void OnFirstDnsTransactionComplete() = 0;
1002
1003 protected:
1004 Delegate() {}
1005 virtual ~Delegate() {}
1006 };
[email protected]b3601bc22012-02-21 21:23:201007
[email protected]0adcb2b2012-08-15 21:30:461008 DnsTask(DnsClient* client,
[email protected]b3601bc22012-02-21 21:23:201009 const Key& key,
[email protected]daae1322013-09-05 18:26:501010 Delegate* delegate,
[email protected]b3601bc22012-02-21 21:23:201011 const BoundNetLog& job_net_log)
[email protected]0adcb2b2012-08-15 21:30:461012 : client_(client),
[email protected]daae1322013-09-05 18:26:501013 key_(key),
1014 delegate_(delegate),
1015 net_log_(job_net_log),
1016 num_completed_transactions_(0),
1017 task_start_time_(base::TimeTicks::Now()) {
[email protected]0adcb2b2012-08-15 21:30:461018 DCHECK(client);
[email protected]daae1322013-09-05 18:26:501019 DCHECK(delegate_);
[email protected]1affed62013-08-21 03:24:501020 }
1021
[email protected]daae1322013-09-05 18:26:501022 bool needs_two_transactions() const {
1023 return key_.address_family == ADDRESS_FAMILY_UNSPECIFIED;
1024 }
1025
1026 bool needs_another_transaction() const {
1027 return needs_two_transactions() && !transaction_aaaa_;
1028 }
1029
1030 void StartFirstTransaction() {
1031 DCHECK_EQ(0u, num_completed_transactions_);
[email protected]70c04ab2013-08-22 16:05:121032 net_log_.BeginEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK);
[email protected]daae1322013-09-05 18:26:501033 if (key_.address_family == ADDRESS_FAMILY_IPV6) {
1034 StartAAAA();
1035 } else {
1036 StartA();
1037 }
1038 }
1039
1040 void StartSecondTransaction() {
1041 DCHECK(needs_two_transactions());
1042 StartAAAA();
[email protected]70c04ab2013-08-22 16:05:121043 }
1044
1045 private:
[email protected]daae1322013-09-05 18:26:501046 void StartA() {
1047 DCHECK(!transaction_a_);
1048 DCHECK_NE(ADDRESS_FAMILY_IPV6, key_.address_family);
1049 transaction_a_ = CreateTransaction(ADDRESS_FAMILY_IPV4);
1050 transaction_a_->Start();
1051 }
1052
1053 void StartAAAA() {
1054 DCHECK(!transaction_aaaa_);
1055 DCHECK_NE(ADDRESS_FAMILY_IPV4, key_.address_family);
1056 transaction_aaaa_ = CreateTransaction(ADDRESS_FAMILY_IPV6);
1057 transaction_aaaa_->Start();
1058 }
1059
1060 scoped_ptr<DnsTransaction> CreateTransaction(AddressFamily family) {
1061 DCHECK_NE(ADDRESS_FAMILY_UNSPECIFIED, family);
1062 return client_->GetTransactionFactory()->CreateTransaction(
1063 key_.hostname,
1064 family == ADDRESS_FAMILY_IPV6 ? dns_protocol::kTypeAAAA :
1065 dns_protocol::kTypeA,
1066 base::Bind(&DnsTask::OnTransactionComplete, base::Unretained(this),
1067 base::TimeTicks::Now()),
1068 net_log_);
1069 }
1070
1071 void OnTransactionComplete(const base::TimeTicks& start_time,
[email protected]1def74c2012-03-22 20:07:001072 DnsTransaction* transaction,
[email protected]b3601bc22012-02-21 21:23:201073 int net_error,
1074 const DnsResponse* response) {
[email protected]add76532012-03-30 14:47:471075 DCHECK(transaction);
[email protected]02cd6982013-01-10 20:12:511076 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]0adcb2b2012-08-15 21:30:461077 if (net_error != OK) {
[email protected]02cd6982013-01-10 20:12:511078 DNS_HISTOGRAM("AsyncDNS.TransactionFailure", duration);
[email protected]0adcb2b2012-08-15 21:30:461079 OnFailure(net_error, DnsResponse::DNS_PARSE_OK);
1080 return;
[email protected]6c411902012-08-14 22:36:361081 }
[email protected]0adcb2b2012-08-15 21:30:461082
[email protected]02cd6982013-01-10 20:12:511083 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess", duration);
1084 switch (transaction->GetType()) {
1085 case dns_protocol::kTypeA:
1086 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess_A", duration);
1087 break;
1088 case dns_protocol::kTypeAAAA:
1089 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess_AAAA", duration);
1090 break;
1091 }
[email protected]daae1322013-09-05 18:26:501092
[email protected]0adcb2b2012-08-15 21:30:461093 AddressList addr_list;
1094 base::TimeDelta ttl;
1095 DnsResponse::Result result = response->ParseToAddressList(&addr_list, &ttl);
1096 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ParseToAddressList",
1097 result,
1098 DnsResponse::DNS_PARSE_RESULT_MAX);
1099 if (result != DnsResponse::DNS_PARSE_OK) {
1100 // Fail even if the other query succeeds.
1101 OnFailure(ERR_DNS_MALFORMED_RESPONSE, result);
1102 return;
1103 }
1104
[email protected]daae1322013-09-05 18:26:501105 ++num_completed_transactions_;
1106 if (num_completed_transactions_ == 1) {
1107 ttl_ = ttl;
[email protected]0adcb2b2012-08-15 21:30:461108 } else {
[email protected]daae1322013-09-05 18:26:501109 ttl_ = std::min(ttl_, ttl);
[email protected]0adcb2b2012-08-15 21:30:461110 }
1111
[email protected]daae1322013-09-05 18:26:501112 if (transaction->GetType() == dns_protocol::kTypeA) {
1113 DCHECK_EQ(transaction_a_.get(), transaction);
1114 // Place IPv4 addresses after IPv6.
1115 addr_list_.insert(addr_list_.end(), addr_list.begin(), addr_list.end());
1116 } else {
1117 DCHECK_EQ(transaction_aaaa_.get(), transaction);
1118 // Place IPv6 addresses before IPv4.
1119 addr_list_.insert(addr_list_.begin(), addr_list.begin(), addr_list.end());
1120 }
1121
1122 if (needs_two_transactions() && num_completed_transactions_ == 1) {
1123 // No need to repeat the suffix search.
1124 key_.hostname = transaction->GetHostname();
1125 delegate_->OnFirstDnsTransactionComplete();
1126 return;
1127 }
1128
1129 if (addr_list_.empty()) {
[email protected]70c04ab2013-08-22 16:05:121130 // TODO(szym): Don't fallback to ProcTask in this case.
1131 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
[email protected]0adcb2b2012-08-15 21:30:461132 return;
1133 }
1134
[email protected]daae1322013-09-05 18:26:501135 // If there are multiple addresses, and at least one is IPv6, need to sort
1136 // them. Note that IPv6 addresses are always put before IPv4 ones, so it's
1137 // sufficient to just check the family of the first address.
1138 if (addr_list_.size() > 1 &&
1139 addr_list_[0].GetFamily() == ADDRESS_FAMILY_IPV6) {
1140 // Sort addresses if needed. Sort could complete synchronously.
[email protected]0adcb2b2012-08-15 21:30:461141 client_->GetAddressSorter()->Sort(
[email protected]daae1322013-09-05 18:26:501142 addr_list_,
[email protected]4589a3a2012-09-20 20:57:071143 base::Bind(&DnsTask::OnSortComplete,
1144 AsWeakPtr(),
[email protected]daae1322013-09-05 18:26:501145 base::TimeTicks::Now()));
[email protected]0adcb2b2012-08-15 21:30:461146 } else {
[email protected]daae1322013-09-05 18:26:501147 OnSuccess(addr_list_);
[email protected]0adcb2b2012-08-15 21:30:461148 }
1149 }
1150
1151 void OnSortComplete(base::TimeTicks start_time,
[email protected]0adcb2b2012-08-15 21:30:461152 bool success,
1153 const AddressList& addr_list) {
1154 if (!success) {
1155 DNS_HISTOGRAM("AsyncDNS.SortFailure",
1156 base::TimeTicks::Now() - start_time);
1157 OnFailure(ERR_DNS_SORT_ERROR, DnsResponse::DNS_PARSE_OK);
1158 return;
1159 }
1160
1161 DNS_HISTOGRAM("AsyncDNS.SortSuccess",
1162 base::TimeTicks::Now() - start_time);
1163
1164 // AddressSorter prunes unusable destinations.
1165 if (addr_list.empty()) {
1166 LOG(WARNING) << "Address list empty after RFC3484 sort";
1167 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
1168 return;
1169 }
1170
[email protected]daae1322013-09-05 18:26:501171 OnSuccess(addr_list);
[email protected]0adcb2b2012-08-15 21:30:461172 }
1173
1174 void OnFailure(int net_error, DnsResponse::Result result) {
1175 DCHECK_NE(OK, net_error);
[email protected]cd565142012-06-12 16:21:451176 net_log_.EndEvent(
1177 NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK,
1178 base::Bind(&NetLogDnsTaskFailedCallback, net_error, result));
[email protected]daae1322013-09-05 18:26:501179 delegate_->OnDnsTaskComplete(task_start_time_, net_error, AddressList(),
1180 base::TimeDelta());
[email protected]b3601bc22012-02-21 21:23:201181 }
1182
[email protected]daae1322013-09-05 18:26:501183 void OnSuccess(const AddressList& addr_list) {
[email protected]0adcb2b2012-08-15 21:30:461184 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK,
1185 addr_list.CreateNetLogCallback());
[email protected]daae1322013-09-05 18:26:501186 delegate_->OnDnsTaskComplete(task_start_time_, OK, addr_list, ttl_);
[email protected]0adcb2b2012-08-15 21:30:461187 }
1188
1189 DnsClient* client_;
[email protected]daae1322013-09-05 18:26:501190 Key key_;
1191
[email protected]b3601bc22012-02-21 21:23:201192 // The listener to the results of this DnsTask.
[email protected]daae1322013-09-05 18:26:501193 Delegate* delegate_;
[email protected]b3601bc22012-02-21 21:23:201194 const BoundNetLog net_log_;
1195
[email protected]daae1322013-09-05 18:26:501196 scoped_ptr<DnsTransaction> transaction_a_;
1197 scoped_ptr<DnsTransaction> transaction_aaaa_;
[email protected]0adcb2b2012-08-15 21:30:461198
[email protected]daae1322013-09-05 18:26:501199 unsigned num_completed_transactions_;
1200
1201 // These are updated as each transaction completes.
1202 base::TimeDelta ttl_;
1203 // IPv6 addresses must appear first in the list.
1204 AddressList addr_list_;
1205
1206 base::TimeTicks task_start_time_;
[email protected]0adcb2b2012-08-15 21:30:461207
1208 DISALLOW_COPY_AND_ASSIGN(DnsTask);
[email protected]b3601bc22012-02-21 21:23:201209};
1210
1211//-----------------------------------------------------------------------------
1212
[email protected]0f292de02012-02-01 22:28:201213// Aggregates all Requests for the same Key. Dispatched via PriorityDispatch.
[email protected]daae1322013-09-05 18:26:501214class HostResolverImpl::Job : public PrioritizedDispatcher::Job,
1215 public HostResolverImpl::DnsTask::Delegate {
[email protected]68ad3ee2010-01-30 03:45:391216 public:
[email protected]0f292de02012-02-01 22:28:201217 // Creates new job for |key| where |request_net_log| is bound to the
[email protected]16ee26d2012-03-08 03:34:351218 // request that spawned it.
[email protected]12faa4c2012-11-06 04:44:181219 Job(const base::WeakPtr<HostResolverImpl>& resolver,
[email protected]0f292de02012-02-01 22:28:201220 const Key& key,
[email protected]8c98d002012-07-18 19:02:271221 RequestPriority priority,
xunjieli26f90452014-11-10 16:23:021222 const BoundNetLog& source_net_log)
[email protected]12faa4c2012-11-06 04:44:181223 : resolver_(resolver),
[email protected]0f292de02012-02-01 22:28:201224 key_(key),
[email protected]8c98d002012-07-18 19:02:271225 priority_tracker_(priority),
[email protected]0f292de02012-02-01 22:28:201226 had_non_speculative_request_(false),
[email protected]51b9a6b2012-06-25 21:50:291227 had_dns_config_(false),
[email protected]daae1322013-09-05 18:26:501228 num_occupied_job_slots_(0),
[email protected]1d932852012-06-19 19:40:331229 dns_task_error_(OK),
[email protected]51b9a6b2012-06-25 21:50:291230 creation_time_(base::TimeTicks::Now()),
1231 priority_change_time_(creation_time_),
xunjieli26f90452014-11-10 16:23:021232 net_log_(BoundNetLog::Make(source_net_log.net_log(),
[email protected]b3601bc22012-02-21 21:23:201233 NetLog::SOURCE_HOST_RESOLVER_IMPL_JOB)) {
xunjieli26f90452014-11-10 16:23:021234 source_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_CREATE_JOB);
[email protected]0f292de02012-02-01 22:28:201235
1236 net_log_.BeginEvent(
1237 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
[email protected]cd565142012-06-12 16:21:451238 base::Bind(&NetLogJobCreationCallback,
xunjieli26f90452014-11-10 16:23:021239 source_net_log.source(),
[email protected]cd565142012-06-12 16:21:451240 &key_.hostname));
[email protected]68ad3ee2010-01-30 03:45:391241 }
1242
dchengb03027d2014-10-21 12:00:201243 ~Job() override {
[email protected]b3601bc22012-02-21 21:23:201244 if (is_running()) {
1245 // |resolver_| was destroyed with this Job still in flight.
1246 // Clean-up, record in the log, but don't run any callbacks.
1247 if (is_proc_running()) {
[email protected]0f292de02012-02-01 22:28:201248 proc_task_->Cancel();
1249 proc_task_ = NULL;
[email protected]0f292de02012-02-01 22:28:201250 }
[email protected]16ee26d2012-03-08 03:34:351251 // Clean up now for nice NetLog.
[email protected]daae1322013-09-05 18:26:501252 KillDnsTask();
[email protected]b3601bc22012-02-21 21:23:201253 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
1254 ERR_ABORTED);
1255 } else if (is_queued()) {
[email protected]57a48d32012-03-03 00:04:551256 // |resolver_| was destroyed without running this Job.
[email protected]16ee26d2012-03-08 03:34:351257 // TODO(szym): is there any benefit in having this distinction?
[email protected]4da911f2012-06-14 19:45:201258 net_log_.AddEvent(NetLog::TYPE_CANCELLED);
1259 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB);
[email protected]68ad3ee2010-01-30 03:45:391260 }
[email protected]b3601bc22012-02-21 21:23:201261 // else CompleteRequests logged EndEvent.
[email protected]68ad3ee2010-01-30 03:45:391262
[email protected]b3601bc22012-02-21 21:23:201263 // Log any remaining Requests as cancelled.
1264 for (RequestsList::const_iterator it = requests_.begin();
1265 it != requests_.end(); ++it) {
1266 Request* req = *it;
1267 if (req->was_canceled())
1268 continue;
1269 DCHECK_EQ(this, req->job());
xunjieli26f90452014-11-10 16:23:021270 LogCancelRequest(req->source_net_log(), req->info());
[email protected]b3601bc22012-02-21 21:23:201271 }
[email protected]68ad3ee2010-01-30 03:45:391272 }
1273
[email protected]daae1322013-09-05 18:26:501274 // Add this job to the dispatcher. If "at_head" is true, adds at the front
1275 // of the queue.
1276 void Schedule(bool at_head) {
1277 DCHECK(!is_queued());
1278 PrioritizedDispatcher::Handle handle;
1279 if (!at_head) {
[email protected]106ccd2c2014-06-17 09:21:001280 handle = resolver_->dispatcher_->Add(this, priority());
[email protected]daae1322013-09-05 18:26:501281 } else {
[email protected]106ccd2c2014-06-17 09:21:001282 handle = resolver_->dispatcher_->AddAtHead(this, priority());
[email protected]daae1322013-09-05 18:26:501283 }
1284 // The dispatcher could have started |this| in the above call to Add, which
1285 // could have called Schedule again. In that case |handle| will be null,
1286 // but |handle_| may have been set by the other nested call to Schedule.
1287 if (!handle.is_null()) {
1288 DCHECK(handle_.is_null());
1289 handle_ = handle;
1290 }
[email protected]16ee26d2012-03-08 03:34:351291 }
1292
[email protected]b3601bc22012-02-21 21:23:201293 void AddRequest(scoped_ptr<Request> req) {
[email protected]0f292de02012-02-01 22:28:201294 DCHECK_EQ(key_.hostname, req->info().hostname());
1295
1296 req->set_job(this);
[email protected]5109c1952013-08-20 18:44:101297 priority_tracker_.Add(req->priority());
[email protected]0f292de02012-02-01 22:28:201298
xunjieli26f90452014-11-10 16:23:021299 req->source_net_log().AddEvent(
[email protected]0f292de02012-02-01 22:28:201300 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_ATTACH,
[email protected]cd565142012-06-12 16:21:451301 net_log_.source().ToEventParametersCallback());
[email protected]0f292de02012-02-01 22:28:201302
1303 net_log_.AddEvent(
1304 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_REQUEST_ATTACH,
[email protected]cd565142012-06-12 16:21:451305 base::Bind(&NetLogJobAttachCallback,
xunjieli26f90452014-11-10 16:23:021306 req->source_net_log().source(),
[email protected]cd565142012-06-12 16:21:451307 priority()));
[email protected]0f292de02012-02-01 22:28:201308
1309 // TODO(szym): Check if this is still needed.
1310 if (!req->info().is_speculative()) {
1311 had_non_speculative_request_ = true;
[email protected]90499482013-06-01 00:39:501312 if (proc_task_.get())
[email protected]0f292de02012-02-01 22:28:201313 proc_task_->set_had_non_speculative_request();
[email protected]68ad3ee2010-01-30 03:45:391314 }
[email protected]b3601bc22012-02-21 21:23:201315
1316 requests_.push_back(req.release());
1317
[email protected]51b9a6b2012-06-25 21:50:291318 UpdatePriority();
[email protected]68ad3ee2010-01-30 03:45:391319 }
1320
[email protected]16ee26d2012-03-08 03:34:351321 // Marks |req| as cancelled. If it was the last active Request, also finishes
[email protected]0adcb2b2012-08-15 21:30:461322 // this Job, marking it as cancelled, and deletes it.
[email protected]0f292de02012-02-01 22:28:201323 void CancelRequest(Request* req) {
1324 DCHECK_EQ(key_.hostname, req->info().hostname());
1325 DCHECK(!req->was_canceled());
[email protected]16ee26d2012-03-08 03:34:351326
[email protected]0f292de02012-02-01 22:28:201327 // Don't remove it from |requests_| just mark it canceled.
1328 req->MarkAsCanceled();
xunjieli26f90452014-11-10 16:23:021329 LogCancelRequest(req->source_net_log(), req->info());
[email protected]16ee26d2012-03-08 03:34:351330
[email protected]5109c1952013-08-20 18:44:101331 priority_tracker_.Remove(req->priority());
1332 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_REQUEST_DETACH,
1333 base::Bind(&NetLogJobAttachCallback,
xunjieli26f90452014-11-10 16:23:021334 req->source_net_log().source(),
[email protected]5109c1952013-08-20 18:44:101335 priority()));
[email protected]b3601bc22012-02-21 21:23:201336
[email protected]16ee26d2012-03-08 03:34:351337 if (num_active_requests() > 0) {
[email protected]51b9a6b2012-06-25 21:50:291338 UpdatePriority();
[email protected]16ee26d2012-03-08 03:34:351339 } else {
1340 // If we were called from a Request's callback within CompleteRequests,
1341 // that Request could not have been cancelled, so num_active_requests()
1342 // could not be 0. Therefore, we are not in CompleteRequests().
[email protected]1339a2a22012-10-17 08:39:431343 CompleteRequestsWithError(OK /* cancelled */);
[email protected]b3601bc22012-02-21 21:23:201344 }
[email protected]68ad3ee2010-01-30 03:45:391345 }
1346
[email protected]7af985a2012-12-14 22:40:421347 // Called from AbortAllInProgressJobs. Completes all requests and destroys
1348 // the job. This currently assumes the abort is due to a network change.
[email protected]0f292de02012-02-01 22:28:201349 void Abort() {
[email protected]0f292de02012-02-01 22:28:201350 DCHECK(is_running());
[email protected]7af985a2012-12-14 22:40:421351 CompleteRequestsWithError(ERR_NETWORK_CHANGED);
[email protected]b3601bc22012-02-21 21:23:201352 }
1353
[email protected]f0f602bd2012-11-15 18:01:021354 // If DnsTask present, abort it and fall back to ProcTask.
1355 void AbortDnsTask() {
1356 if (dns_task_) {
[email protected]daae1322013-09-05 18:26:501357 KillDnsTask();
[email protected]f0f602bd2012-11-15 18:01:021358 dns_task_error_ = OK;
1359 StartProcTask();
1360 }
1361 }
1362
[email protected]16ee26d2012-03-08 03:34:351363 // Called by HostResolverImpl when this job is evicted due to queue overflow.
1364 // Completes all requests and destroys the job.
1365 void OnEvicted() {
1366 DCHECK(!is_running());
1367 DCHECK(is_queued());
1368 handle_.Reset();
1369
[email protected]4da911f2012-06-14 19:45:201370 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_EVICTED);
[email protected]16ee26d2012-03-08 03:34:351371
1372 // This signals to CompleteRequests that this job never ran.
[email protected]1339a2a22012-10-17 08:39:431373 CompleteRequestsWithError(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
[email protected]16ee26d2012-03-08 03:34:351374 }
1375
[email protected]78eac2a2012-03-14 19:09:271376 // Attempts to serve the job from HOSTS. Returns true if succeeded and
1377 // this Job was destroyed.
1378 bool ServeFromHosts() {
1379 DCHECK_GT(num_active_requests(), 0u);
1380 AddressList addr_list;
1381 if (resolver_->ServeFromHosts(key(),
[email protected]3cb676a12012-06-30 15:46:031382 requests_.front()->info(),
[email protected]78eac2a2012-03-14 19:09:271383 &addr_list)) {
1384 // This will destroy the Job.
[email protected]895123222012-10-25 15:21:171385 CompleteRequests(
1386 HostCache::Entry(OK, MakeAddressListForRequest(addr_list)),
1387 base::TimeDelta());
[email protected]78eac2a2012-03-14 19:09:271388 return true;
1389 }
1390 return false;
1391 }
1392
[email protected]b4481b222012-03-16 17:13:111393 const Key key() const {
1394 return key_;
1395 }
1396
1397 bool is_queued() const {
1398 return !handle_.is_null();
1399 }
1400
1401 bool is_running() const {
1402 return is_dns_running() || is_proc_running();
1403 }
1404
[email protected]16ee26d2012-03-08 03:34:351405 private:
[email protected]daae1322013-09-05 18:26:501406 void KillDnsTask() {
1407 if (dns_task_) {
1408 ReduceToOneJobSlot();
1409 dns_task_.reset();
1410 }
1411 }
1412
1413 // Reduce the number of job slots occupied and queued in the dispatcher
1414 // to one. If the second Job slot is queued in the dispatcher, cancels the
1415 // queued job. Otherwise, the second Job has been started by the
1416 // PrioritizedDispatcher, so signals it is complete.
1417 void ReduceToOneJobSlot() {
1418 DCHECK_GE(num_occupied_job_slots_, 1u);
1419 if (is_queued()) {
[email protected]106ccd2c2014-06-17 09:21:001420 resolver_->dispatcher_->Cancel(handle_);
[email protected]daae1322013-09-05 18:26:501421 handle_.Reset();
1422 } else if (num_occupied_job_slots_ > 1) {
[email protected]106ccd2c2014-06-17 09:21:001423 resolver_->dispatcher_->OnJobFinished();
[email protected]daae1322013-09-05 18:26:501424 --num_occupied_job_slots_;
1425 }
1426 DCHECK_EQ(1u, num_occupied_job_slots_);
1427 }
1428
[email protected]51b9a6b2012-06-25 21:50:291429 void UpdatePriority() {
1430 if (is_queued()) {
1431 if (priority() != static_cast<RequestPriority>(handle_.priority()))
1432 priority_change_time_ = base::TimeTicks::Now();
[email protected]106ccd2c2014-06-17 09:21:001433 handle_ = resolver_->dispatcher_->ChangePriority(handle_, priority());
[email protected]51b9a6b2012-06-25 21:50:291434 }
1435 }
1436
[email protected]895123222012-10-25 15:21:171437 AddressList MakeAddressListForRequest(const AddressList& list) const {
1438 if (requests_.empty())
1439 return list;
1440 return AddressList::CopyWithPort(list, requests_.front()->info().port());
1441 }
1442
[email protected]16ee26d2012-03-08 03:34:351443 // PriorityDispatch::Job:
dchengb03027d2014-10-21 12:00:201444 void Start() override {
[email protected]daae1322013-09-05 18:26:501445 DCHECK_LE(num_occupied_job_slots_, 1u);
1446
[email protected]70c04ab2013-08-22 16:05:121447 handle_.Reset();
[email protected]daae1322013-09-05 18:26:501448 ++num_occupied_job_slots_;
1449
1450 if (num_occupied_job_slots_ == 2) {
1451 StartSecondDnsTransaction();
1452 return;
1453 }
1454
1455 DCHECK(!is_running());
[email protected]0f292de02012-02-01 22:28:201456
[email protected]4da911f2012-06-14 19:45:201457 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_STARTED);
[email protected]0f292de02012-02-01 22:28:201458
[email protected]51b9a6b2012-06-25 21:50:291459 had_dns_config_ = resolver_->HaveDnsConfig();
1460
1461 base::TimeTicks now = base::TimeTicks::Now();
1462 base::TimeDelta queue_time = now - creation_time_;
1463 base::TimeDelta queue_time_after_change = now - priority_change_time_;
1464
1465 if (had_dns_config_) {
1466 DNS_HISTOGRAM_BY_PRIORITY("AsyncDNS.JobQueueTime", priority(),
1467 queue_time);
1468 DNS_HISTOGRAM_BY_PRIORITY("AsyncDNS.JobQueueTimeAfterChange", priority(),
1469 queue_time_after_change);
1470 } else {
1471 DNS_HISTOGRAM_BY_PRIORITY("DNS.JobQueueTime", priority(), queue_time);
1472 DNS_HISTOGRAM_BY_PRIORITY("DNS.JobQueueTimeAfterChange", priority(),
1473 queue_time_after_change);
1474 }
1475
[email protected]443714fad2013-09-19 04:52:011476 bool system_only =
1477 (key_.host_resolver_flags & HOST_RESOLVER_SYSTEM_ONLY) != 0;
1478
[email protected]1d932852012-06-19 19:40:331479 // Caution: Job::Start must not complete synchronously.
[email protected]443714fad2013-09-19 04:52:011480 if (!system_only && had_dns_config_ &&
1481 !ResemblesMulticastDNSName(key_.hostname)) {
[email protected]b3601bc22012-02-21 21:23:201482 StartDnsTask();
1483 } else {
1484 StartProcTask();
1485 }
1486 }
1487
[email protected]b3601bc22012-02-21 21:23:201488 // TODO(szym): Since DnsTransaction does not consume threads, we can increase
1489 // the limits on |dispatcher_|. But in order to keep the number of WorkerPool
1490 // threads low, we will need to use an "inner" PrioritizedDispatcher with
1491 // tighter limits.
1492 void StartProcTask() {
[email protected]16ee26d2012-03-08 03:34:351493 DCHECK(!is_dns_running());
[email protected]0f292de02012-02-01 22:28:201494 proc_task_ = new ProcTask(
1495 key_,
1496 resolver_->proc_params_,
[email protected]e3bd4822012-10-23 18:01:371497 base::Bind(&Job::OnProcTaskComplete, base::Unretained(this),
1498 base::TimeTicks::Now()),
[email protected]0f292de02012-02-01 22:28:201499 net_log_);
1500
1501 if (had_non_speculative_request_)
1502 proc_task_->set_had_non_speculative_request();
1503 // Start() could be called from within Resolve(), hence it must NOT directly
1504 // call OnProcTaskComplete, for example, on synchronous failure.
1505 proc_task_->Start();
[email protected]68ad3ee2010-01-30 03:45:391506 }
1507
[email protected]0f292de02012-02-01 22:28:201508 // Called by ProcTask when it completes.
[email protected]e3bd4822012-10-23 18:01:371509 void OnProcTaskComplete(base::TimeTicks start_time,
1510 int net_error,
1511 const AddressList& addr_list) {
vadimt7ecc40e2014-11-26 00:53:401512 // TODO(vadimt): Remove ScopedTracker below once crbug.com/436634 is fixed.
1513 tracked_objects::ScopedTracker tracking_profile(
1514 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1515 "436634 HostResolverImpl::Job::OnProcTaskComplete"));
1516
[email protected]b3601bc22012-02-21 21:23:201517 DCHECK(is_proc_running());
[email protected]68ad3ee2010-01-30 03:45:391518
[email protected]62e86ba2013-01-29 18:59:161519 if (!resolver_->resolved_known_ipv6_hostname_ &&
1520 net_error == OK &&
1521 key_.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
1522 if (key_.hostname == "www.google.com") {
1523 resolver_->resolved_known_ipv6_hostname_ = true;
1524 bool got_ipv6_address = false;
1525 for (size_t i = 0; i < addr_list.size(); ++i) {
[email protected]5134c22a2013-08-06 18:09:021526 if (addr_list[i].GetFamily() == ADDRESS_FAMILY_IPV6) {
[email protected]62e86ba2013-01-29 18:59:161527 got_ipv6_address = true;
[email protected]5134c22a2013-08-06 18:09:021528 break;
1529 }
[email protected]62e86ba2013-01-29 18:59:161530 }
1531 UMA_HISTOGRAM_BOOLEAN("Net.UnspecResolvedIPv6", got_ipv6_address);
1532 }
1533 }
1534
[email protected]1d932852012-06-19 19:40:331535 if (dns_task_error_ != OK) {
[email protected]e3bd4822012-10-23 18:01:371536 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]1def74c2012-03-22 20:07:001537 if (net_error == OK) {
[email protected]e3bd4822012-10-23 18:01:371538 DNS_HISTOGRAM("AsyncDNS.FallbackSuccess", duration);
[email protected]1d932852012-06-19 19:40:331539 if ((dns_task_error_ == ERR_NAME_NOT_RESOLVED) &&
1540 ResemblesNetBIOSName(key_.hostname)) {
1541 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_SUSPECT_NETBIOS);
1542 } else {
1543 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_PROC_SUCCESS);
1544 }
1545 UMA_HISTOGRAM_CUSTOM_ENUMERATION("AsyncDNS.ResolveError",
1546 std::abs(dns_task_error_),
1547 GetAllErrorCodesForUma());
[email protected]1ffdda82012-12-12 23:04:221548 resolver_->OnDnsTaskResolve(dns_task_error_);
[email protected]1def74c2012-03-22 20:07:001549 } else {
[email protected]e3bd4822012-10-23 18:01:371550 DNS_HISTOGRAM("AsyncDNS.FallbackFail", duration);
[email protected]1def74c2012-03-22 20:07:001551 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
1552 }
1553 }
1554
[email protected]1339a2a22012-10-17 08:39:431555 base::TimeDelta ttl =
1556 base::TimeDelta::FromSeconds(kNegativeCacheEntryTTLSeconds);
[email protected]b3601bc22012-02-21 21:23:201557 if (net_error == OK)
1558 ttl = base::TimeDelta::FromSeconds(kCacheEntryTTLSeconds);
[email protected]68ad3ee2010-01-30 03:45:391559
[email protected]895123222012-10-25 15:21:171560 // Don't store the |ttl| in cache since it's not obtained from the server.
1561 CompleteRequests(
1562 HostCache::Entry(net_error, MakeAddressListForRequest(addr_list)),
1563 ttl);
[email protected]b3601bc22012-02-21 21:23:201564 }
1565
1566 void StartDnsTask() {
[email protected]78eac2a2012-03-14 19:09:271567 DCHECK(resolver_->HaveDnsConfig());
[email protected]daae1322013-09-05 18:26:501568 dns_task_.reset(new DnsTask(resolver_->dns_client_.get(), key_, this,
1569 net_log_));
[email protected]b3601bc22012-02-21 21:23:201570
[email protected]daae1322013-09-05 18:26:501571 dns_task_->StartFirstTransaction();
1572 // Schedule a second transaction, if needed.
1573 if (dns_task_->needs_two_transactions())
1574 Schedule(true);
1575 }
1576
1577 void StartSecondDnsTransaction() {
1578 DCHECK(dns_task_->needs_two_transactions());
1579 dns_task_->StartSecondTransaction();
[email protected]16c2bd72013-06-28 01:19:221580 }
1581
1582 // Called if DnsTask fails. It is posted from StartDnsTask, so Job may be
1583 // deleted before this callback. In this case dns_task is deleted as well,
1584 // so we use it as indicator whether Job is still valid.
1585 void OnDnsTaskFailure(const base::WeakPtr<DnsTask>& dns_task,
1586 base::TimeDelta duration,
1587 int net_error) {
1588 DNS_HISTOGRAM("AsyncDNS.ResolveFail", duration);
1589
1590 if (dns_task == NULL)
1591 return;
1592
1593 dns_task_error_ = net_error;
1594
1595 // TODO(szym): Run ServeFromHosts now if nsswitch.conf says so.
1596 // http://crbug.com/117655
1597
1598 // TODO(szym): Some net errors indicate lack of connectivity. Starting
1599 // ProcTask in that case is a waste of time.
1600 if (resolver_->fallback_to_proctask_) {
[email protected]daae1322013-09-05 18:26:501601 KillDnsTask();
[email protected]16c2bd72013-06-28 01:19:221602 StartProcTask();
1603 } else {
1604 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
1605 CompleteRequestsWithError(net_error);
[email protected]b3601bc22012-02-21 21:23:201606 }
1607 }
1608
[email protected]daae1322013-09-05 18:26:501609
1610 // HostResolverImpl::DnsTask::Delegate implementation:
1611
dchengb03027d2014-10-21 12:00:201612 void OnDnsTaskComplete(base::TimeTicks start_time,
1613 int net_error,
1614 const AddressList& addr_list,
1615 base::TimeDelta ttl) override {
[email protected]b3601bc22012-02-21 21:23:201616 DCHECK(is_dns_running());
[email protected]b3601bc22012-02-21 21:23:201617
[email protected]e3bd4822012-10-23 18:01:371618 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]b3601bc22012-02-21 21:23:201619 if (net_error != OK) {
[email protected]16c2bd72013-06-28 01:19:221620 OnDnsTaskFailure(dns_task_->AsWeakPtr(), duration, net_error);
[email protected]b3601bc22012-02-21 21:23:201621 return;
1622 }
[email protected]e3bd4822012-10-23 18:01:371623 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess", duration);
[email protected]02cd6982013-01-10 20:12:511624 // Log DNS lookups based on |address_family|.
1625 switch(key_.address_family) {
1626 case ADDRESS_FAMILY_IPV4:
1627 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_IPV4", duration);
1628 break;
1629 case ADDRESS_FAMILY_IPV6:
1630 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_IPV6", duration);
1631 break;
1632 case ADDRESS_FAMILY_UNSPECIFIED:
1633 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_UNSPEC", duration);
1634 break;
1635 }
[email protected]b3601bc22012-02-21 21:23:201636
[email protected]1def74c2012-03-22 20:07:001637 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_DNS_SUCCESS);
[email protected]1339a2a22012-10-17 08:39:431638 RecordTTL(ttl);
[email protected]0adcb2b2012-08-15 21:30:461639
[email protected]1ffdda82012-12-12 23:04:221640 resolver_->OnDnsTaskResolve(OK);
[email protected]f0f602bd2012-11-15 18:01:021641
[email protected]895123222012-10-25 15:21:171642 base::TimeDelta bounded_ttl =
1643 std::max(ttl, base::TimeDelta::FromSeconds(kMinimumTTLSeconds));
1644
1645 CompleteRequests(
1646 HostCache::Entry(net_error, MakeAddressListForRequest(addr_list), ttl),
1647 bounded_ttl);
[email protected]b3601bc22012-02-21 21:23:201648 }
1649
dchengb03027d2014-10-21 12:00:201650 void OnFirstDnsTransactionComplete() override {
[email protected]daae1322013-09-05 18:26:501651 DCHECK(dns_task_->needs_two_transactions());
1652 DCHECK_EQ(dns_task_->needs_another_transaction(), is_queued());
1653 // No longer need to occupy two dispatcher slots.
1654 ReduceToOneJobSlot();
1655
1656 // We already have a job slot at the dispatcher, so if the second
1657 // transaction hasn't started, reuse it now instead of waiting in the queue
1658 // for the second slot.
1659 if (dns_task_->needs_another_transaction())
1660 dns_task_->StartSecondTransaction();
1661 }
1662
[email protected]16ee26d2012-03-08 03:34:351663 // Performs Job's last rites. Completes all Requests. Deletes this.
[email protected]895123222012-10-25 15:21:171664 void CompleteRequests(const HostCache::Entry& entry,
1665 base::TimeDelta ttl) {
vadimt7ecc40e2014-11-26 00:53:401666 // TODO(vadimt): Remove ScopedTracker below once crbug.com/436634 is fixed.
1667 tracked_objects::ScopedTracker tracking_profile1(
1668 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1669 "436634 HostResolverImpl::Job::CompleteRequests1"));
1670
[email protected]11fbca0b2013-06-02 23:37:211671 CHECK(resolver_.get());
[email protected]b3601bc22012-02-21 21:23:201672
[email protected]16ee26d2012-03-08 03:34:351673 // This job must be removed from resolver's |jobs_| now to make room for a
1674 // new job with the same key in case one of the OnComplete callbacks decides
1675 // to spawn one. Consequently, the job deletes itself when CompleteRequests
1676 // is done.
1677 scoped_ptr<Job> self_deleter(this);
1678
1679 resolver_->RemoveJob(this);
1680
[email protected]16ee26d2012-03-08 03:34:351681 if (is_running()) {
[email protected]16ee26d2012-03-08 03:34:351682 if (is_proc_running()) {
[email protected]daae1322013-09-05 18:26:501683 DCHECK(!is_queued());
[email protected]16ee26d2012-03-08 03:34:351684 proc_task_->Cancel();
1685 proc_task_ = NULL;
1686 }
[email protected]daae1322013-09-05 18:26:501687 KillDnsTask();
[email protected]16ee26d2012-03-08 03:34:351688
1689 // Signal dispatcher that a slot has opened.
[email protected]106ccd2c2014-06-17 09:21:001690 resolver_->dispatcher_->OnJobFinished();
[email protected]16ee26d2012-03-08 03:34:351691 } else if (is_queued()) {
[email protected]106ccd2c2014-06-17 09:21:001692 resolver_->dispatcher_->Cancel(handle_);
[email protected]16ee26d2012-03-08 03:34:351693 handle_.Reset();
1694 }
1695
1696 if (num_active_requests() == 0) {
[email protected]4da911f2012-06-14 19:45:201697 net_log_.AddEvent(NetLog::TYPE_CANCELLED);
[email protected]16ee26d2012-03-08 03:34:351698 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
1699 OK);
1700 return;
1701 }
[email protected]b3601bc22012-02-21 21:23:201702
1703 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
[email protected]895123222012-10-25 15:21:171704 entry.error);
[email protected]68ad3ee2010-01-30 03:45:391705
[email protected]78eac2a2012-03-14 19:09:271706 DCHECK(!requests_.empty());
1707
[email protected]895123222012-10-25 15:21:171708 if (entry.error == OK) {
[email protected]d7b9a2b2012-05-31 22:31:191709 // Record this histogram here, when we know the system has a valid DNS
1710 // configuration.
[email protected]539df6c2012-06-19 21:21:291711 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.HaveDnsConfig",
1712 resolver_->received_dns_config_);
[email protected]d7b9a2b2012-05-31 22:31:191713 }
[email protected]16ee26d2012-03-08 03:34:351714
[email protected]7af985a2012-12-14 22:40:421715 bool did_complete = (entry.error != ERR_NETWORK_CHANGED) &&
[email protected]895123222012-10-25 15:21:171716 (entry.error != ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
1717 if (did_complete)
[email protected]1339a2a22012-10-17 08:39:431718 resolver_->CacheResult(key_, entry, ttl);
[email protected]16ee26d2012-03-08 03:34:351719
vadimt7ecc40e2014-11-26 00:53:401720 // TODO(vadimt): Remove ScopedTracker below once crbug.com/436634 is fixed.
1721 tracked_objects::ScopedTracker tracking_profile2(
1722 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1723 "436634 HostResolverImpl::Job::CompleteRequests2"));
1724
[email protected]0f292de02012-02-01 22:28:201725 // Complete all of the requests that were attached to the job.
1726 for (RequestsList::const_iterator it = requests_.begin();
1727 it != requests_.end(); ++it) {
1728 Request* req = *it;
1729
1730 if (req->was_canceled())
1731 continue;
1732
1733 DCHECK_EQ(this, req->job());
1734 // Update the net log and notify registered observers.
xunjieli26f90452014-11-10 16:23:021735 LogFinishRequest(req->source_net_log(), req->info(), entry.error);
[email protected]51b9a6b2012-06-25 21:50:291736 if (did_complete) {
1737 // Record effective total time from creation to completion.
1738 RecordTotalTime(had_dns_config_, req->info().is_speculative(),
1739 base::TimeTicks::Now() - req->request_time());
1740 }
[email protected]895123222012-10-25 15:21:171741 req->OnComplete(entry.error, entry.addrlist);
[email protected]0f292de02012-02-01 22:28:201742
1743 // Check if the resolver was destroyed as a result of running the
1744 // callback. If it was, we could continue, but we choose to bail.
[email protected]11fbca0b2013-06-02 23:37:211745 if (!resolver_.get())
[email protected]0f292de02012-02-01 22:28:201746 return;
1747 }
1748 }
1749
[email protected]1339a2a22012-10-17 08:39:431750 // Convenience wrapper for CompleteRequests in case of failure.
1751 void CompleteRequestsWithError(int net_error) {
[email protected]895123222012-10-25 15:21:171752 CompleteRequests(HostCache::Entry(net_error, AddressList()),
1753 base::TimeDelta());
[email protected]1339a2a22012-10-17 08:39:431754 }
1755
[email protected]b4481b222012-03-16 17:13:111756 RequestPriority priority() const {
1757 return priority_tracker_.highest_priority();
1758 }
1759
1760 // Number of non-canceled requests in |requests_|.
1761 size_t num_active_requests() const {
1762 return priority_tracker_.total_count();
1763 }
1764
1765 bool is_dns_running() const {
1766 return dns_task_.get() != NULL;
1767 }
1768
1769 bool is_proc_running() const {
1770 return proc_task_.get() != NULL;
1771 }
1772
[email protected]0f292de02012-02-01 22:28:201773 base::WeakPtr<HostResolverImpl> resolver_;
1774
1775 Key key_;
1776
1777 // Tracks the highest priority across |requests_|.
1778 PriorityTracker priority_tracker_;
1779
1780 bool had_non_speculative_request_;
1781
[email protected]51b9a6b2012-06-25 21:50:291782 // Distinguishes measurements taken while DnsClient was fully configured.
1783 bool had_dns_config_;
1784
[email protected]daae1322013-09-05 18:26:501785 // Number of slots occupied by this Job in resolver's PrioritizedDispatcher.
1786 unsigned num_occupied_job_slots_;
1787
[email protected]1d932852012-06-19 19:40:331788 // Result of DnsTask.
1789 int dns_task_error_;
[email protected]1def74c2012-03-22 20:07:001790
[email protected]51b9a6b2012-06-25 21:50:291791 const base::TimeTicks creation_time_;
1792 base::TimeTicks priority_change_time_;
1793
[email protected]0f292de02012-02-01 22:28:201794 BoundNetLog net_log_;
1795
[email protected]b3601bc22012-02-21 21:23:201796 // Resolves the host using a HostResolverProc.
[email protected]0f292de02012-02-01 22:28:201797 scoped_refptr<ProcTask> proc_task_;
1798
[email protected]b3601bc22012-02-21 21:23:201799 // Resolves the host using a DnsTransaction.
1800 scoped_ptr<DnsTask> dns_task_;
1801
[email protected]0f292de02012-02-01 22:28:201802 // All Requests waiting for the result of this Job. Some can be canceled.
1803 RequestsList requests_;
1804
[email protected]16ee26d2012-03-08 03:34:351805 // A handle used in |HostResolverImpl::dispatcher_|.
[email protected]0f292de02012-02-01 22:28:201806 PrioritizedDispatcher::Handle handle_;
[email protected]68ad3ee2010-01-30 03:45:391807};
1808
1809//-----------------------------------------------------------------------------
1810
[email protected]0f292de02012-02-01 22:28:201811HostResolverImpl::ProcTaskParams::ProcTaskParams(
[email protected]e95d3aca2010-01-11 22:47:431812 HostResolverProc* resolver_proc,
[email protected]0f292de02012-02-01 22:28:201813 size_t max_retry_attempts)
1814 : resolver_proc(resolver_proc),
1815 max_retry_attempts(max_retry_attempts),
1816 unresponsive_delay(base::TimeDelta::FromMilliseconds(6000)),
1817 retry_factor(2) {
[email protected]106ccd2c2014-06-17 09:21:001818 // Maximum of 4 retry attempts for host resolution.
1819 static const size_t kDefaultMaxRetryAttempts = 4u;
1820 if (max_retry_attempts == HostResolver::kDefaultRetryAttempts)
1821 max_retry_attempts = kDefaultMaxRetryAttempts;
[email protected]0f292de02012-02-01 22:28:201822}
1823
1824HostResolverImpl::ProcTaskParams::~ProcTaskParams() {}
1825
[email protected]106ccd2c2014-06-17 09:21:001826HostResolverImpl::HostResolverImpl(const Options& options, NetLog* net_log)
1827 : max_queued_jobs_(0),
1828 proc_params_(NULL, options.max_retry_attempts),
[email protected]62e86ba2013-01-29 18:59:161829 net_log_(net_log),
[email protected]0c7798452009-10-26 17:59:511830 default_address_family_(ADDRESS_FAMILY_UNSPECIFIED),
[email protected]d7b9a2b2012-05-31 22:31:191831 received_dns_config_(false),
[email protected]f0f602bd2012-11-15 18:01:021832 num_dns_failures_(0),
[email protected]23330db72013-07-18 03:32:111833 probe_ipv6_support_(true),
[email protected]c9fa8f312013-09-17 12:24:521834 use_local_ipv6_(false),
[email protected]62e86ba2013-01-29 18:59:161835 resolved_known_ipv6_hostname_(false),
[email protected]16c2bd72013-06-28 01:19:221836 additional_resolver_flags_(0),
[email protected]0a30cf512014-05-27 20:55:181837 fallback_to_proctask_(true),
1838 weak_ptr_factory_(this),
1839 probe_weak_ptr_factory_(this) {
[email protected]106ccd2c2014-06-17 09:21:001840 if (options.enable_caching)
1841 cache_ = HostCache::CreateDefaultCache();
[email protected]0f292de02012-02-01 22:28:201842
[email protected]106ccd2c2014-06-17 09:21:001843 PrioritizedDispatcher::Limits job_limits = options.GetDispatcherLimits();
1844 dispatcher_.reset(new PrioritizedDispatcher(job_limits));
1845 max_queued_jobs_ = job_limits.total_jobs * 100u;
[email protected]68ad3ee2010-01-30 03:45:391846
[email protected]106ccd2c2014-06-17 09:21:001847 DCHECK_GE(dispatcher_->num_priorities(), static_cast<size_t>(NUM_PRIORITIES));
[email protected]68ad3ee2010-01-30 03:45:391848
[email protected]b59ff372009-07-15 22:04:321849#if defined(OS_WIN)
1850 EnsureWinsockInit();
1851#endif
[email protected]7c466e92013-07-20 01:44:481852#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
[email protected]12faa4c2012-11-06 04:44:181853 new LoopbackProbeJob(weak_ptr_factory_.GetWeakPtr());
[email protected]2f3bc65c2010-07-23 17:47:101854#endif
[email protected]232a5812011-03-04 22:42:081855 NetworkChangeNotifier::AddIPAddressObserver(this);
[email protected]bb0e34542012-08-31 19:52:401856 NetworkChangeNotifier::AddDNSObserver(this);
[email protected]d7b9a2b2012-05-31 22:31:191857#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD) && \
1858 !defined(OS_ANDROID)
[email protected]d7b9a2b2012-05-31 22:31:191859 EnsureDnsReloaderInit();
[email protected]46018c9d2011-09-06 03:42:341860#endif
[email protected]2ac22db2012-11-28 19:50:041861
[email protected]2ac22db2012-11-28 19:50:041862 {
1863 DnsConfig dns_config;
1864 NetworkChangeNotifier::GetDnsConfig(&dns_config);
1865 received_dns_config_ = dns_config.IsValid();
[email protected]c9fa8f312013-09-17 12:24:521866 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
1867 use_local_ipv6_ = !dns_config.IsValid() || dns_config.use_local_ipv6;
[email protected]2ac22db2012-11-28 19:50:041868 }
[email protected]16c2bd72013-06-28 01:19:221869
1870 fallback_to_proctask_ = !ConfigureAsyncDnsNoFallbackFieldTrial();
[email protected]b59ff372009-07-15 22:04:321871}
1872
1873HostResolverImpl::~HostResolverImpl() {
[email protected]daae1322013-09-05 18:26:501874 // Prevent the dispatcher from starting new jobs.
[email protected]106ccd2c2014-06-17 09:21:001875 dispatcher_->SetLimitsToZero();
[email protected]daae1322013-09-05 18:26:501876 // It's now safe for Jobs to call KillDsnTask on destruction, because
1877 // OnJobComplete will not start any new jobs.
[email protected]0f292de02012-02-01 22:28:201878 STLDeleteValues(&jobs_);
[email protected]e95d3aca2010-01-11 22:47:431879
[email protected]232a5812011-03-04 22:42:081880 NetworkChangeNotifier::RemoveIPAddressObserver(this);
[email protected]bb0e34542012-08-31 19:52:401881 NetworkChangeNotifier::RemoveDNSObserver(this);
[email protected]b59ff372009-07-15 22:04:321882}
1883
[email protected]0f292de02012-02-01 22:28:201884void HostResolverImpl::SetMaxQueuedJobs(size_t value) {
[email protected]106ccd2c2014-06-17 09:21:001885 DCHECK_EQ(0u, dispatcher_->num_queued_jobs());
[email protected]0f292de02012-02-01 22:28:201886 DCHECK_GT(value, 0u);
1887 max_queued_jobs_ = value;
[email protected]be1a48b2011-01-20 00:12:131888}
1889
[email protected]684970b2009-08-14 04:54:461890int HostResolverImpl::Resolve(const RequestInfo& info,
[email protected]5109c1952013-08-20 18:44:101891 RequestPriority priority,
[email protected]b59ff372009-07-15 22:04:321892 AddressList* addresses,
[email protected]aa22b242011-11-16 18:58:291893 const CompletionCallback& callback,
[email protected]684970b2009-08-14 04:54:461894 RequestHandle* out_req,
[email protected]ee094b82010-08-24 15:55:511895 const BoundNetLog& source_net_log) {
[email protected]95a214c2011-08-04 21:50:401896 DCHECK(addresses);
[email protected]1ac6af92010-06-03 21:00:141897 DCHECK(CalledOnValidThread());
[email protected]aa22b242011-11-16 18:58:291898 DCHECK_EQ(false, callback.is_null());
[email protected]1ac6af92010-06-03 21:00:141899
[email protected]e806cd72013-05-17 02:08:431900 // Check that the caller supplied a valid hostname to resolve.
1901 std::string labeled_hostname;
1902 if (!DNSDomainFromDot(info.hostname(), &labeled_hostname))
1903 return ERR_NAME_NOT_RESOLVED;
1904
xunjieli26f90452014-11-10 16:23:021905 LogStartRequest(source_net_log, info);
[email protected]b59ff372009-07-15 22:04:321906
[email protected]123ab1e32009-10-21 19:12:571907 // Build a key that identifies the request in the cache and in the
1908 // outstanding jobs map.
xunjieli26f90452014-11-10 16:23:021909 Key key = GetEffectiveKeyForRequest(info, source_net_log);
[email protected]123ab1e32009-10-21 19:12:571910
xunjieli26f90452014-11-10 16:23:021911 int rv = ResolveHelper(key, info, addresses, source_net_log);
[email protected]95a214c2011-08-04 21:50:401912 if (rv != ERR_DNS_CACHE_MISS) {
xunjieli26f90452014-11-10 16:23:021913 LogFinishRequest(source_net_log, info, rv);
[email protected]51b9a6b2012-06-25 21:50:291914 RecordTotalTime(HaveDnsConfig(), info.is_speculative(), base::TimeDelta());
[email protected]95a214c2011-08-04 21:50:401915 return rv;
[email protected]38368712011-03-02 08:09:401916 }
1917
[email protected]0f292de02012-02-01 22:28:201918 // Next we need to attach our request to a "job". This job is responsible for
1919 // calling "getaddrinfo(hostname)" on a worker thread.
1920
1921 JobMap::iterator jobit = jobs_.find(key);
1922 Job* job;
1923 if (jobit == jobs_.end()) {
[email protected]5109c1952013-08-20 18:44:101924 job =
xunjieli26f90452014-11-10 16:23:021925 new Job(weak_ptr_factory_.GetWeakPtr(), key, priority, source_net_log);
[email protected]daae1322013-09-05 18:26:501926 job->Schedule(false);
[email protected]0f292de02012-02-01 22:28:201927
1928 // Check for queue overflow.
[email protected]106ccd2c2014-06-17 09:21:001929 if (dispatcher_->num_queued_jobs() > max_queued_jobs_) {
1930 Job* evicted = static_cast<Job*>(dispatcher_->EvictOldestLowest());
[email protected]0f292de02012-02-01 22:28:201931 DCHECK(evicted);
[email protected]16ee26d2012-03-08 03:34:351932 evicted->OnEvicted(); // Deletes |evicted|.
[email protected]0f292de02012-02-01 22:28:201933 if (evicted == job) {
[email protected]0f292de02012-02-01 22:28:201934 rv = ERR_HOST_RESOLVER_QUEUE_TOO_LARGE;
xunjieli26f90452014-11-10 16:23:021935 LogFinishRequest(source_net_log, info, rv);
[email protected]0f292de02012-02-01 22:28:201936 return rv;
1937 }
[email protected]0f292de02012-02-01 22:28:201938 }
[email protected]0f292de02012-02-01 22:28:201939 jobs_.insert(jobit, std::make_pair(key, job));
1940 } else {
1941 job = jobit->second;
1942 }
1943
1944 // Can't complete synchronously. Create and attach request.
[email protected]5109c1952013-08-20 18:44:101945 scoped_ptr<Request> req(new Request(
xunjieli26f90452014-11-10 16:23:021946 source_net_log, info, priority, callback, addresses));
[email protected]b59ff372009-07-15 22:04:321947 if (out_req)
[email protected]b3601bc22012-02-21 21:23:201948 *out_req = reinterpret_cast<RequestHandle>(req.get());
[email protected]b59ff372009-07-15 22:04:321949
[email protected]b3601bc22012-02-21 21:23:201950 job->AddRequest(req.Pass());
[email protected]0f292de02012-02-01 22:28:201951 // Completion happens during Job::CompleteRequests().
[email protected]b59ff372009-07-15 22:04:321952 return ERR_IO_PENDING;
1953}
1954
[email protected]287d7c22011-11-15 17:34:251955int HostResolverImpl::ResolveHelper(const Key& key,
[email protected]95a214c2011-08-04 21:50:401956 const RequestInfo& info,
1957 AddressList* addresses,
xunjieli26f90452014-11-10 16:23:021958 const BoundNetLog& source_net_log) {
[email protected]95a214c2011-08-04 21:50:401959 // The result of |getaddrinfo| for empty hosts is inconsistent across systems.
1960 // On Windows it gives the default interface's address, whereas on Linux it
1961 // gives an error. We will make it fail on all platforms for consistency.
1962 if (info.hostname().empty() || info.hostname().size() > kMaxHostLength)
1963 return ERR_NAME_NOT_RESOLVED;
1964
1965 int net_error = ERR_UNEXPECTED;
1966 if (ResolveAsIP(key, info, &net_error, addresses))
1967 return net_error;
[email protected]78eac2a2012-03-14 19:09:271968 if (ServeFromCache(key, info, &net_error, addresses)) {
xunjieli26f90452014-11-10 16:23:021969 source_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_CACHE_HIT);
[email protected]78eac2a2012-03-14 19:09:271970 return net_error;
1971 }
1972 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
1973 // http://crbug.com/117655
1974 if (ServeFromHosts(key, info, addresses)) {
xunjieli26f90452014-11-10 16:23:021975 source_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_HOSTS_HIT);
[email protected]78eac2a2012-03-14 19:09:271976 return OK;
1977 }
1978 return ERR_DNS_CACHE_MISS;
[email protected]95a214c2011-08-04 21:50:401979}
1980
1981int HostResolverImpl::ResolveFromCache(const RequestInfo& info,
1982 AddressList* addresses,
1983 const BoundNetLog& source_net_log) {
1984 DCHECK(CalledOnValidThread());
1985 DCHECK(addresses);
1986
[email protected]95a214c2011-08-04 21:50:401987 // Update the net log and notify registered observers.
xunjieli26f90452014-11-10 16:23:021988 LogStartRequest(source_net_log, info);
[email protected]95a214c2011-08-04 21:50:401989
xunjieli26f90452014-11-10 16:23:021990 Key key = GetEffectiveKeyForRequest(info, source_net_log);
[email protected]95a214c2011-08-04 21:50:401991
xunjieli26f90452014-11-10 16:23:021992 int rv = ResolveHelper(key, info, addresses, source_net_log);
1993 LogFinishRequest(source_net_log, info, rv);
[email protected]95a214c2011-08-04 21:50:401994 return rv;
1995}
1996
[email protected]b59ff372009-07-15 22:04:321997void HostResolverImpl::CancelRequest(RequestHandle req_handle) {
[email protected]1ac6af92010-06-03 21:00:141998 DCHECK(CalledOnValidThread());
[email protected]b59ff372009-07-15 22:04:321999 Request* req = reinterpret_cast<Request*>(req_handle);
2000 DCHECK(req);
[email protected]0f292de02012-02-01 22:28:202001 Job* job = req->job();
2002 DCHECK(job);
[email protected]0f292de02012-02-01 22:28:202003 job->CancelRequest(req);
[email protected]b59ff372009-07-15 22:04:322004}
2005
[email protected]0f8f1b432010-03-16 19:06:032006void HostResolverImpl::SetDefaultAddressFamily(AddressFamily address_family) {
[email protected]1ac6af92010-06-03 21:00:142007 DCHECK(CalledOnValidThread());
[email protected]0f8f1b432010-03-16 19:06:032008 default_address_family_ = address_family;
[email protected]23330db72013-07-18 03:32:112009 probe_ipv6_support_ = false;
[email protected]0f8f1b432010-03-16 19:06:032010}
2011
[email protected]f7d310e2010-10-07 16:25:112012AddressFamily HostResolverImpl::GetDefaultAddressFamily() const {
2013 return default_address_family_;
2014}
2015
[email protected]a8883e452012-11-17 05:58:062016void HostResolverImpl::SetDnsClientEnabled(bool enabled) {
2017 DCHECK(CalledOnValidThread());
2018#if defined(ENABLE_BUILT_IN_DNS)
2019 if (enabled && !dns_client_) {
2020 SetDnsClient(DnsClient::CreateClient(net_log_));
2021 } else if (!enabled && dns_client_) {
2022 SetDnsClient(scoped_ptr<DnsClient>());
2023 }
2024#endif
2025}
2026
[email protected]489d1a82011-10-12 03:09:112027HostCache* HostResolverImpl::GetHostCache() {
2028 return cache_.get();
2029}
[email protected]95a214c2011-08-04 21:50:402030
[email protected]17e92032012-03-29 00:56:242031base::Value* HostResolverImpl::GetDnsConfigAsValue() const {
2032 // Check if async DNS is disabled.
2033 if (!dns_client_.get())
2034 return NULL;
2035
2036 // Check if async DNS is enabled, but we currently have no configuration
2037 // for it.
2038 const DnsConfig* dns_config = dns_client_->GetConfig();
2039 if (dns_config == NULL)
[email protected]ea5ef4c2013-06-13 22:50:272040 return new base::DictionaryValue();
[email protected]17e92032012-03-29 00:56:242041
2042 return dns_config->ToValue();
2043}
2044
[email protected]95a214c2011-08-04 21:50:402045bool HostResolverImpl::ResolveAsIP(const Key& key,
2046 const RequestInfo& info,
2047 int* net_error,
2048 AddressList* addresses) {
2049 DCHECK(addresses);
2050 DCHECK(net_error);
2051 IPAddressNumber ip_number;
2052 if (!ParseIPLiteralToNumber(key.hostname, &ip_number))
2053 return false;
2054
2055 DCHECK_EQ(key.host_resolver_flags &
2056 ~(HOST_RESOLVER_CANONNAME | HOST_RESOLVER_LOOPBACK_ONLY |
2057 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6),
2058 0) << " Unhandled flag";
[email protected]1c7cf3f82014-08-07 21:33:482059
[email protected]95a214c2011-08-04 21:50:402060 *net_error = OK;
[email protected]1c7cf3f82014-08-07 21:33:482061 AddressFamily family = GetAddressFamily(ip_number);
2062 if (family == ADDRESS_FAMILY_IPV6 &&
2063 !probe_ipv6_support_ &&
2064 default_address_family_ == ADDRESS_FAMILY_IPV4) {
2065 // Don't return IPv6 addresses if default address family is set to IPv4,
2066 // and probes are disabled.
2067 *net_error = ERR_NAME_NOT_RESOLVED;
2068 } else if (key.address_family != ADDRESS_FAMILY_UNSPECIFIED &&
2069 key.address_family != family) {
2070 // Don't return IPv6 addresses for IPv4 queries, and vice versa.
[email protected]95a214c2011-08-04 21:50:402071 *net_error = ERR_NAME_NOT_RESOLVED;
2072 } else {
[email protected]7054e78f2012-05-07 21:44:562073 *addresses = AddressList::CreateFromIPAddress(ip_number, info.port());
2074 if (key.host_resolver_flags & HOST_RESOLVER_CANONNAME)
2075 addresses->SetDefaultCanonicalName();
[email protected]95a214c2011-08-04 21:50:402076 }
2077 return true;
2078}
2079
2080bool HostResolverImpl::ServeFromCache(const Key& key,
2081 const RequestInfo& info,
[email protected]95a214c2011-08-04 21:50:402082 int* net_error,
2083 AddressList* addresses) {
2084 DCHECK(addresses);
2085 DCHECK(net_error);
2086 if (!info.allow_cached_response() || !cache_.get())
2087 return false;
2088
[email protected]407a30ab2012-08-15 17:16:102089 const HostCache::Entry* cache_entry = cache_->Lookup(
2090 key, base::TimeTicks::Now());
[email protected]95a214c2011-08-04 21:50:402091 if (!cache_entry)
2092 return false;
2093
[email protected]95a214c2011-08-04 21:50:402094 *net_error = cache_entry->error;
[email protected]7054e78f2012-05-07 21:44:562095 if (*net_error == OK) {
[email protected]1339a2a22012-10-17 08:39:432096 if (cache_entry->has_ttl())
2097 RecordTTL(cache_entry->ttl);
[email protected]895123222012-10-25 15:21:172098 *addresses = EnsurePortOnAddressList(cache_entry->addrlist, info.port());
[email protected]7054e78f2012-05-07 21:44:562099 }
[email protected]95a214c2011-08-04 21:50:402100 return true;
2101}
2102
[email protected]78eac2a2012-03-14 19:09:272103bool HostResolverImpl::ServeFromHosts(const Key& key,
2104 const RequestInfo& info,
2105 AddressList* addresses) {
2106 DCHECK(addresses);
2107 if (!HaveDnsConfig())
2108 return false;
[email protected]05a79d42013-03-28 07:30:092109 addresses->clear();
2110
[email protected]cb507622012-03-23 16:17:062111 // HOSTS lookups are case-insensitive.
[email protected]cb1f4ac2014-08-07 16:55:422112 std::string hostname = base::StringToLowerASCII(key.hostname);
[email protected]cb507622012-03-23 16:17:062113
[email protected]05a79d42013-03-28 07:30:092114 const DnsHosts& hosts = dns_client_->GetConfig()->hosts;
2115
[email protected]78eac2a2012-03-14 19:09:272116 // If |address_family| is ADDRESS_FAMILY_UNSPECIFIED other implementations
2117 // (glibc and c-ares) return the first matching line. We have more
2118 // flexibility, but lose implicit ordering.
[email protected]05a79d42013-03-28 07:30:092119 // We prefer IPv6 because "happy eyeballs" will fall back to IPv4 if
2120 // necessary.
2121 if (key.address_family == ADDRESS_FAMILY_IPV6 ||
2122 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
2123 DnsHosts::const_iterator it = hosts.find(
2124 DnsHostsKey(hostname, ADDRESS_FAMILY_IPV6));
2125 if (it != hosts.end())
2126 addresses->push_back(IPEndPoint(it->second, info.port()));
[email protected]78eac2a2012-03-14 19:09:272127 }
2128
[email protected]05a79d42013-03-28 07:30:092129 if (key.address_family == ADDRESS_FAMILY_IPV4 ||
2130 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
2131 DnsHosts::const_iterator it = hosts.find(
2132 DnsHostsKey(hostname, ADDRESS_FAMILY_IPV4));
2133 if (it != hosts.end())
2134 addresses->push_back(IPEndPoint(it->second, info.port()));
2135 }
2136
[email protected]ec666ab22013-04-17 20:05:592137 // If got only loopback addresses and the family was restricted, resolve
2138 // again, without restrictions. See SystemHostResolverCall for rationale.
2139 if ((key.host_resolver_flags &
2140 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6) &&
2141 IsAllIPv4Loopback(*addresses)) {
2142 Key new_key(key);
2143 new_key.address_family = ADDRESS_FAMILY_UNSPECIFIED;
2144 new_key.host_resolver_flags &=
2145 ~HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
2146 return ServeFromHosts(new_key, info, addresses);
2147 }
[email protected]05a79d42013-03-28 07:30:092148 return !addresses->empty();
[email protected]78eac2a2012-03-14 19:09:272149}
2150
[email protected]16ee26d2012-03-08 03:34:352151void HostResolverImpl::CacheResult(const Key& key,
[email protected]1339a2a22012-10-17 08:39:432152 const HostCache::Entry& entry,
[email protected]16ee26d2012-03-08 03:34:352153 base::TimeDelta ttl) {
2154 if (cache_.get())
[email protected]1339a2a22012-10-17 08:39:432155 cache_->Set(key, entry, base::TimeTicks::Now(), ttl);
[email protected]ef4c40c2010-09-01 14:42:032156}
2157
[email protected]0f292de02012-02-01 22:28:202158void HostResolverImpl::RemoveJob(Job* job) {
2159 DCHECK(job);
[email protected]16ee26d2012-03-08 03:34:352160 JobMap::iterator it = jobs_.find(job->key());
2161 if (it != jobs_.end() && it->second == job)
2162 jobs_.erase(it);
[email protected]b59ff372009-07-15 22:04:322163}
2164
[email protected]9936a7862012-10-26 04:44:022165void HostResolverImpl::SetHaveOnlyLoopbackAddresses(bool result) {
2166 if (result) {
2167 additional_resolver_flags_ |= HOST_RESOLVER_LOOPBACK_ONLY;
2168 } else {
2169 additional_resolver_flags_ &= ~HOST_RESOLVER_LOOPBACK_ONLY;
2170 }
2171}
2172
[email protected]137af622010-02-05 02:14:352173HostResolverImpl::Key HostResolverImpl::GetEffectiveKeyForRequest(
[email protected]2b74a2f2013-07-23 19:37:382174 const RequestInfo& info, const BoundNetLog& net_log) const {
[email protected]eaf3a3b2010-09-03 20:34:272175 HostResolverFlags effective_flags =
2176 info.host_resolver_flags() | additional_resolver_flags_;
[email protected]137af622010-02-05 02:14:352177 AddressFamily effective_address_family = info.address_family();
[email protected]9db6f702013-04-10 18:10:512178
2179 if (info.address_family() == ADDRESS_FAMILY_UNSPECIFIED) {
pauljensen370f1c72015-02-17 16:59:142180 unsigned char ip_number[4];
2181 url::Component host_comp(0, info.hostname().size());
2182 int num_components;
2183 if (probe_ipv6_support_ && !use_local_ipv6_ &&
2184 // Don't bother IPv6 probing when resolving IPv4 literals.
2185 url::IPv4AddressToNumber(info.hostname().c_str(), host_comp, ip_number,
2186 &num_components) != url::CanonHostInfo::IPV4) {
[email protected]ac0b52e2013-04-21 01:26:162187 // Google DNS address.
2188 const uint8 kIPv6Address[] =
2189 { 0x20, 0x01, 0x48, 0x60, 0x48, 0x60, 0x00, 0x00,
2190 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x88 };
2191 IPAddressNumber address(kIPv6Address,
2192 kIPv6Address + arraysize(kIPv6Address));
[email protected]967d1b52014-01-16 21:43:172193 BoundNetLog probe_net_log = BoundNetLog::Make(
2194 net_log.net_log(), NetLog::SOURCE_IPV6_REACHABILITY_CHECK);
2195 probe_net_log.BeginEvent(NetLog::TYPE_IPV6_REACHABILITY_CHECK,
2196 net_log.source().ToEventParametersCallback());
2197 bool rv6 = IsGloballyReachable(address, probe_net_log);
2198 probe_net_log.EndEvent(NetLog::TYPE_IPV6_REACHABILITY_CHECK);
[email protected]2b74a2f2013-07-23 19:37:382199 if (rv6)
2200 net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_IPV6_SUPPORTED);
[email protected]9db6f702013-04-10 18:10:512201
[email protected]ac0b52e2013-04-21 01:26:162202 if (rv6) {
2203 UMA_HISTOGRAM_BOOLEAN("Net.IPv6ConnectSuccessMatch",
2204 default_address_family_ == ADDRESS_FAMILY_UNSPECIFIED);
2205 } else {
2206 UMA_HISTOGRAM_BOOLEAN("Net.IPv6ConnectFailureMatch",
2207 default_address_family_ != ADDRESS_FAMILY_UNSPECIFIED);
2208
2209 effective_address_family = ADDRESS_FAMILY_IPV4;
2210 effective_flags |= HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
2211 }
[email protected]9db6f702013-04-10 18:10:512212 } else {
[email protected]ac0b52e2013-04-21 01:26:162213 effective_address_family = default_address_family_;
[email protected]9db6f702013-04-10 18:10:512214 }
2215 }
2216
[email protected]eaf3a3b2010-09-03 20:34:272217 return Key(info.hostname(), effective_address_family, effective_flags);
[email protected]137af622010-02-05 02:14:352218}
2219
[email protected]35ddc282010-09-21 23:42:062220void HostResolverImpl::AbortAllInProgressJobs() {
[email protected]b3601bc22012-02-21 21:23:202221 // In Abort, a Request callback could spawn new Jobs with matching keys, so
2222 // first collect and remove all running jobs from |jobs_|.
[email protected]c143d892012-04-06 07:56:542223 ScopedVector<Job> jobs_to_abort;
[email protected]0f292de02012-02-01 22:28:202224 for (JobMap::iterator it = jobs_.begin(); it != jobs_.end(); ) {
2225 Job* job = it->second;
[email protected]0f292de02012-02-01 22:28:202226 if (job->is_running()) {
[email protected]b3601bc22012-02-21 21:23:202227 jobs_to_abort.push_back(job);
2228 jobs_.erase(it++);
[email protected]0f292de02012-02-01 22:28:202229 } else {
[email protected]b3601bc22012-02-21 21:23:202230 DCHECK(job->is_queued());
2231 ++it;
[email protected]0f292de02012-02-01 22:28:202232 }
[email protected]ef4c40c2010-09-01 14:42:032233 }
[email protected]b3601bc22012-02-21 21:23:202234
[email protected]daae1322013-09-05 18:26:502235 // Pause the dispatcher so it won't start any new dispatcher jobs while
2236 // aborting the old ones. This is needed so that it won't start the second
2237 // DnsTransaction for a job in |jobs_to_abort| if the DnsConfig just became
2238 // invalid.
[email protected]106ccd2c2014-06-17 09:21:002239 PrioritizedDispatcher::Limits limits = dispatcher_->GetLimits();
2240 dispatcher_->SetLimits(
[email protected]daae1322013-09-05 18:26:502241 PrioritizedDispatcher::Limits(limits.reserved_slots.size(), 0));
[email protected]70c04ab2013-08-22 16:05:122242
[email protected]57a48d32012-03-03 00:04:552243 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072244 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]57a48d32012-03-03 00:04:552245
[email protected]16ee26d2012-03-08 03:34:352246 // Then Abort them.
[email protected]11fbca0b2013-06-02 23:37:212247 for (size_t i = 0; self.get() && i < jobs_to_abort.size(); ++i) {
[email protected]57a48d32012-03-03 00:04:552248 jobs_to_abort[i]->Abort();
[email protected]c143d892012-04-06 07:56:542249 jobs_to_abort[i] = NULL;
[email protected]b3601bc22012-02-21 21:23:202250 }
[email protected]daae1322013-09-05 18:26:502251
2252 if (self)
[email protected]106ccd2c2014-06-17 09:21:002253 dispatcher_->SetLimits(limits);
[email protected]daae1322013-09-05 18:26:502254}
2255
2256void HostResolverImpl::AbortDnsTasks() {
2257 // Pause the dispatcher so it won't start any new dispatcher jobs while
2258 // aborting the old ones. This is needed so that it won't start the second
2259 // DnsTransaction for a job if the DnsConfig just changed.
[email protected]106ccd2c2014-06-17 09:21:002260 PrioritizedDispatcher::Limits limits = dispatcher_->GetLimits();
2261 dispatcher_->SetLimits(
[email protected]daae1322013-09-05 18:26:502262 PrioritizedDispatcher::Limits(limits.reserved_slots.size(), 0));
2263
2264 for (JobMap::iterator it = jobs_.begin(); it != jobs_.end(); ++it)
2265 it->second->AbortDnsTask();
[email protected]106ccd2c2014-06-17 09:21:002266 dispatcher_->SetLimits(limits);
[email protected]ef4c40c2010-09-01 14:42:032267}
2268
[email protected]78eac2a2012-03-14 19:09:272269void HostResolverImpl::TryServingAllJobsFromHosts() {
2270 if (!HaveDnsConfig())
2271 return;
2272
2273 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2274 // http://crbug.com/117655
2275
2276 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072277 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]78eac2a2012-03-14 19:09:272278
[email protected]11fbca0b2013-06-02 23:37:212279 for (JobMap::iterator it = jobs_.begin(); self.get() && it != jobs_.end();) {
[email protected]78eac2a2012-03-14 19:09:272280 Job* job = it->second;
2281 ++it;
2282 // This could remove |job| from |jobs_|, but iterator will remain valid.
2283 job->ServeFromHosts();
2284 }
2285}
2286
[email protected]be1a48b2011-01-20 00:12:132287void HostResolverImpl::OnIPAddressChanged() {
[email protected]62e86ba2013-01-29 18:59:162288 resolved_known_ipv6_hostname_ = false;
[email protected]12faa4c2012-11-06 04:44:182289 // Abandon all ProbeJobs.
2290 probe_weak_ptr_factory_.InvalidateWeakPtrs();
[email protected]be1a48b2011-01-20 00:12:132291 if (cache_.get())
2292 cache_->clear();
[email protected]7c466e92013-07-20 01:44:482293#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
[email protected]12faa4c2012-11-06 04:44:182294 new LoopbackProbeJob(probe_weak_ptr_factory_.GetWeakPtr());
[email protected]be1a48b2011-01-20 00:12:132295#endif
2296 AbortAllInProgressJobs();
2297 // |this| may be deleted inside AbortAllInProgressJobs().
2298}
2299
[email protected]bb0e34542012-08-31 19:52:402300void HostResolverImpl::OnDNSChanged() {
2301 DnsConfig dns_config;
2302 NetworkChangeNotifier::GetDnsConfig(&dns_config);
[email protected]ec666ab22013-04-17 20:05:592303
[email protected]b4481b222012-03-16 17:13:112304 if (net_log_) {
2305 net_log_->AddGlobalEntry(
2306 NetLog::TYPE_DNS_CONFIG_CHANGED,
[email protected]cd565142012-06-12 16:21:452307 base::Bind(&NetLogDnsConfigCallback, &dns_config));
[email protected]b4481b222012-03-16 17:13:112308 }
2309
[email protected]01b3b9d2012-08-13 16:18:142310 // TODO(szym): Remove once http://crbug.com/137914 is resolved.
[email protected]d7b9a2b2012-05-31 22:31:192311 received_dns_config_ = dns_config.IsValid();
[email protected]c9fa8f312013-09-17 12:24:522312 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
2313 use_local_ipv6_ = !dns_config.IsValid() || dns_config.use_local_ipv6;
[email protected]78eac2a2012-03-14 19:09:272314
[email protected]a8883e452012-11-17 05:58:062315 num_dns_failures_ = 0;
2316
[email protected]01b3b9d2012-08-13 16:18:142317 // We want a new DnsSession in place, before we Abort running Jobs, so that
2318 // the newly started jobs use the new config.
[email protected]f0f602bd2012-11-15 18:01:022319 if (dns_client_.get()) {
[email protected]d7b9a2b2012-05-31 22:31:192320 dns_client_->SetConfig(dns_config);
[email protected]3d164772013-08-21 03:25:192321 if (dns_client_->GetConfig())
[email protected]f0f602bd2012-11-15 18:01:022322 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
[email protected]f0f602bd2012-11-15 18:01:022323 }
[email protected]01b3b9d2012-08-13 16:18:142324
2325 // If the DNS server has changed, existing cached info could be wrong so we
2326 // have to drop our internal cache :( Note that OS level DNS caches, such
2327 // as NSCD's cache should be dropped automatically by the OS when
2328 // resolv.conf changes so we don't need to do anything to clear that cache.
2329 if (cache_.get())
2330 cache_->clear();
2331
[email protected]f0f602bd2012-11-15 18:01:022332 // Life check to bail once |this| is deleted.
2333 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
2334
[email protected]01b3b9d2012-08-13 16:18:142335 // Existing jobs will have been sent to the original server so they need to
2336 // be aborted.
2337 AbortAllInProgressJobs();
2338
2339 // |this| may be deleted inside AbortAllInProgressJobs().
[email protected]11fbca0b2013-06-02 23:37:212340 if (self.get())
[email protected]01b3b9d2012-08-13 16:18:142341 TryServingAllJobsFromHosts();
[email protected]78eac2a2012-03-14 19:09:272342}
2343
2344bool HostResolverImpl::HaveDnsConfig() const {
[email protected]32b1dbcf2013-01-26 03:48:252345 // Use DnsClient only if it's fully configured and there is no override by
2346 // ScopedDefaultHostResolverProc.
2347 // The alternative is to use NetworkChangeNotifier to override DnsConfig,
2348 // but that would introduce construction order requirements for NCN and SDHRP.
[email protected]90499482013-06-01 00:39:502349 return (dns_client_.get() != NULL) && (dns_client_->GetConfig() != NULL) &&
2350 !(proc_params_.resolver_proc.get() == NULL &&
[email protected]32b1dbcf2013-01-26 03:48:252351 HostResolverProc::GetDefault() != NULL);
[email protected]b3601bc22012-02-21 21:23:202352}
2353
[email protected]1ffdda82012-12-12 23:04:222354void HostResolverImpl::OnDnsTaskResolve(int net_error) {
[email protected]f0f602bd2012-11-15 18:01:022355 DCHECK(dns_client_);
[email protected]1ffdda82012-12-12 23:04:222356 if (net_error == OK) {
[email protected]f0f602bd2012-11-15 18:01:022357 num_dns_failures_ = 0;
2358 return;
2359 }
2360 ++num_dns_failures_;
2361 if (num_dns_failures_ < kMaximumDnsFailures)
2362 return;
[email protected]daae1322013-09-05 18:26:502363
2364 // Disable DnsClient until the next DNS change. Must be done before aborting
2365 // DnsTasks, since doing so may start new jobs.
[email protected]f0f602bd2012-11-15 18:01:022366 dns_client_->SetConfig(DnsConfig());
[email protected]daae1322013-09-05 18:26:502367
2368 // Switch jobs with active DnsTasks over to using ProcTasks.
2369 AbortDnsTasks();
2370
[email protected]f0f602bd2012-11-15 18:01:022371 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", false);
[email protected]1ffdda82012-12-12 23:04:222372 UMA_HISTOGRAM_CUSTOM_ENUMERATION("AsyncDNS.DnsClientDisabledReason",
2373 std::abs(net_error),
2374 GetAllErrorCodesForUma());
[email protected]f0f602bd2012-11-15 18:01:022375}
2376
[email protected]a8883e452012-11-17 05:58:062377void HostResolverImpl::SetDnsClient(scoped_ptr<DnsClient> dns_client) {
[email protected]daae1322013-09-05 18:26:502378 // DnsClient and config must be updated before aborting DnsTasks, since doing
2379 // so may start new jobs.
[email protected]a8883e452012-11-17 05:58:062380 dns_client_ = dns_client.Pass();
[email protected]daae1322013-09-05 18:26:502381 if (dns_client_ && !dns_client_->GetConfig() &&
2382 num_dns_failures_ < kMaximumDnsFailures) {
2383 DnsConfig dns_config;
2384 NetworkChangeNotifier::GetDnsConfig(&dns_config);
2385 dns_client_->SetConfig(dns_config);
2386 num_dns_failures_ = 0;
2387 if (dns_client_->GetConfig())
2388 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
[email protected]a8883e452012-11-17 05:58:062389 }
[email protected]daae1322013-09-05 18:26:502390
2391 AbortDnsTasks();
[email protected]a8883e452012-11-17 05:58:062392}
2393
[email protected]b59ff372009-07-15 22:04:322394} // namespace net