blob: 92694af19ad259b0014f3b30f3a57d8c937a0aa3 [file] [log] [blame]
[email protected]a2730882012-01-21 00:56:271// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]b59ff372009-07-15 22:04:322// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
[email protected]f2cb3cf2013-03-21 01:40:535#include "net/dns/host_resolver_impl.h"
[email protected]b59ff372009-07-15 22:04:326
[email protected]21526002010-05-16 19:42:467#if defined(OS_WIN)
8#include <Winsock2.h>
9#elif defined(OS_POSIX)
10#include <netdb.h>
11#endif
12
[email protected]68ad3ee2010-01-30 03:45:3913#include <cmath>
[email protected]0f292de02012-02-01 22:28:2014#include <utility>
[email protected]21526002010-05-16 19:42:4615#include <vector>
[email protected]68ad3ee2010-01-30 03:45:3916
17#include "base/basictypes.h"
[email protected]33152acc2011-10-20 23:37:1218#include "base/bind.h"
[email protected]aa22b242011-11-16 18:58:2919#include "base/bind_helpers.h"
[email protected]0f292de02012-02-01 22:28:2020#include "base/callback.h"
[email protected]b59ff372009-07-15 22:04:3221#include "base/compiler_specific.h"
[email protected]58580352010-10-26 04:07:5022#include "base/debug/debugger.h"
23#include "base/debug/stack_trace.h"
[email protected]7ccb7072013-06-10 20:56:2824#include "base/message_loop/message_loop_proxy.h"
[email protected]1e9bbd22010-10-15 16:42:4525#include "base/metrics/field_trial.h"
[email protected]835d7c82010-10-14 04:38:3826#include "base/metrics/histogram.h"
[email protected]7286e3fc2011-07-19 22:13:2427#include "base/stl_util.h"
[email protected]be528af2013-06-11 07:39:4828#include "base/strings/string_util.h"
[email protected]750b2f3c2013-06-07 18:41:0529#include "base/strings/utf_string_conversions.h"
[email protected]ac9ba8fe2010-12-30 18:08:3630#include "base/threading/worker_pool.h"
[email protected]66e96c42013-06-28 15:20:3131#include "base/time/time.h"
[email protected]21526002010-05-16 19:42:4632#include "base/values.h"
[email protected]b3601bc22012-02-21 21:23:2033#include "net/base/address_family.h"
[email protected]b59ff372009-07-15 22:04:3234#include "net/base/address_list.h"
[email protected]46018c9d2011-09-06 03:42:3435#include "net/base/dns_reloader.h"
[email protected]e806cd72013-05-17 02:08:4336#include "net/base/dns_util.h"
[email protected]ee094b82010-08-24 15:55:5137#include "net/base/host_port_pair.h"
[email protected]2bb04442010-08-18 18:01:1538#include "net/base/net_errors.h"
[email protected]ee094b82010-08-24 15:55:5139#include "net/base/net_log.h"
[email protected]0f8f1b432010-03-16 19:06:0340#include "net/base/net_util.h"
[email protected]0adcb2b2012-08-15 21:30:4641#include "net/dns/address_sorter.h"
[email protected]78eac2a2012-03-14 19:09:2742#include "net/dns/dns_client.h"
[email protected]b3601bc22012-02-21 21:23:2043#include "net/dns/dns_config_service.h"
44#include "net/dns/dns_protocol.h"
45#include "net/dns/dns_response.h"
[email protected]b3601bc22012-02-21 21:23:2046#include "net/dns/dns_transaction.h"
[email protected]f2cb3cf2013-03-21 01:40:5347#include "net/dns/host_resolver_proc.h"
[email protected]9db6f702013-04-10 18:10:5148#include "net/socket/client_socket_factory.h"
49#include "net/udp/datagram_client_socket.h"
[email protected]b59ff372009-07-15 22:04:3250
51#if defined(OS_WIN)
52#include "net/base/winsock_init.h"
53#endif
54
55namespace net {
56
[email protected]e95d3aca2010-01-11 22:47:4357namespace {
58
[email protected]6e78dfb2011-07-28 21:34:4759// Limit the size of hostnames that will be resolved to combat issues in
60// some platform's resolvers.
61const size_t kMaxHostLength = 4096;
62
[email protected]a2730882012-01-21 00:56:2763// Default TTL for successful resolutions with ProcTask.
64const unsigned kCacheEntryTTLSeconds = 60;
65
[email protected]b3601bc22012-02-21 21:23:2066// Default TTL for unsuccessful resolutions with ProcTask.
67const unsigned kNegativeCacheEntryTTLSeconds = 0;
68
[email protected]895123222012-10-25 15:21:1769// Minimum TTL for successful resolutions with DnsTask.
70const unsigned kMinimumTTLSeconds = kCacheEntryTTLSeconds;
71
[email protected]f0f602bd2012-11-15 18:01:0272// Number of consecutive failures of DnsTask (with successful fallback) before
73// the DnsClient is disabled until the next DNS change.
74const unsigned kMaximumDnsFailures = 16;
75
[email protected]24f4bab2010-10-15 01:27:1176// We use a separate histogram name for each platform to facilitate the
77// display of error codes by their symbolic name (since each platform has
78// different mappings).
79const char kOSErrorsForGetAddrinfoHistogramName[] =
80#if defined(OS_WIN)
81 "Net.OSErrorsForGetAddrinfo_Win";
82#elif defined(OS_MACOSX)
83 "Net.OSErrorsForGetAddrinfo_Mac";
84#elif defined(OS_LINUX)
85 "Net.OSErrorsForGetAddrinfo_Linux";
86#else
87 "Net.OSErrorsForGetAddrinfo";
88#endif
89
[email protected]c89b2442011-05-26 14:28:2790// Gets a list of the likely error codes that getaddrinfo() can return
91// (non-exhaustive). These are the error codes that we will track via
92// a histogram.
93std::vector<int> GetAllGetAddrinfoOSErrors() {
94 int os_errors[] = {
95#if defined(OS_POSIX)
[email protected]23f771162011-06-02 18:37:5196#if !defined(OS_FREEBSD)
[email protected]39588992011-07-11 19:54:3797#if !defined(OS_ANDROID)
[email protected]c48aef92011-11-22 23:41:4598 // EAI_ADDRFAMILY has been declared obsolete in Android's and
99 // FreeBSD's netdb.h.
[email protected]c89b2442011-05-26 14:28:27100 EAI_ADDRFAMILY,
[email protected]39588992011-07-11 19:54:37101#endif
[email protected]c48aef92011-11-22 23:41:45102 // EAI_NODATA has been declared obsolete in FreeBSD's netdb.h.
[email protected]23f771162011-06-02 18:37:51103 EAI_NODATA,
104#endif
[email protected]c89b2442011-05-26 14:28:27105 EAI_AGAIN,
106 EAI_BADFLAGS,
107 EAI_FAIL,
108 EAI_FAMILY,
109 EAI_MEMORY,
[email protected]c89b2442011-05-26 14:28:27110 EAI_NONAME,
111 EAI_SERVICE,
112 EAI_SOCKTYPE,
113 EAI_SYSTEM,
114#elif defined(OS_WIN)
115 // See: http://msdn.microsoft.com/en-us/library/ms738520(VS.85).aspx
116 WSA_NOT_ENOUGH_MEMORY,
117 WSAEAFNOSUPPORT,
118 WSAEINVAL,
119 WSAESOCKTNOSUPPORT,
120 WSAHOST_NOT_FOUND,
121 WSANO_DATA,
122 WSANO_RECOVERY,
123 WSANOTINITIALISED,
124 WSATRY_AGAIN,
125 WSATYPE_NOT_FOUND,
126 // The following are not in doc, but might be to appearing in results :-(.
127 WSA_INVALID_HANDLE,
128#endif
129 };
130
131 // Ensure all errors are positive, as histogram only tracks positive values.
132 for (size_t i = 0; i < arraysize(os_errors); ++i) {
133 os_errors[i] = std::abs(os_errors[i]);
134 }
135
136 return base::CustomHistogram::ArrayToCustomRanges(os_errors,
137 arraysize(os_errors));
138}
139
[email protected]1def74c2012-03-22 20:07:00140enum DnsResolveStatus {
141 RESOLVE_STATUS_DNS_SUCCESS = 0,
142 RESOLVE_STATUS_PROC_SUCCESS,
143 RESOLVE_STATUS_FAIL,
[email protected]1d932852012-06-19 19:40:33144 RESOLVE_STATUS_SUSPECT_NETBIOS,
[email protected]1def74c2012-03-22 20:07:00145 RESOLVE_STATUS_MAX
146};
147
148void UmaAsyncDnsResolveStatus(DnsResolveStatus result) {
149 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ResolveStatus",
150 result,
151 RESOLVE_STATUS_MAX);
152}
153
[email protected]1d932852012-06-19 19:40:33154bool ResemblesNetBIOSName(const std::string& hostname) {
155 return (hostname.size() < 16) && (hostname.find('.') == std::string::npos);
156}
157
158// True if |hostname| ends with either ".local" or ".local.".
159bool ResemblesMulticastDNSName(const std::string& hostname) {
160 DCHECK(!hostname.empty());
161 const char kSuffix[] = ".local.";
162 const size_t kSuffixLen = sizeof(kSuffix) - 1;
163 const size_t kSuffixLenTrimmed = kSuffixLen - 1;
164 if (hostname[hostname.size() - 1] == '.') {
165 return hostname.size() > kSuffixLen &&
166 !hostname.compare(hostname.size() - kSuffixLen, kSuffixLen, kSuffix);
167 }
168 return hostname.size() > kSuffixLenTrimmed &&
169 !hostname.compare(hostname.size() - kSuffixLenTrimmed, kSuffixLenTrimmed,
170 kSuffix, kSuffixLenTrimmed);
171}
172
[email protected]9db6f702013-04-10 18:10:51173// Attempts to connect a UDP socket to |dest|:80.
[email protected]2b74a2f2013-07-23 19:37:38174bool IsGloballyReachable(const IPAddressNumber& dest,
175 const BoundNetLog& net_log) {
[email protected]9db6f702013-04-10 18:10:51176 scoped_ptr<DatagramClientSocket> socket(
177 ClientSocketFactory::GetDefaultFactory()->CreateDatagramClientSocket(
178 DatagramSocket::DEFAULT_BIND,
179 RandIntCallback(),
[email protected]2b74a2f2013-07-23 19:37:38180 net_log.net_log(),
181 net_log.source()));
[email protected]e9051722013-04-12 21:58:18182 int rv = socket->Connect(IPEndPoint(dest, 80));
183 if (rv != OK)
184 return false;
185 IPEndPoint endpoint;
186 rv = socket->GetLocalAddress(&endpoint);
187 if (rv != OK)
188 return false;
189 DCHECK(endpoint.GetFamily() == ADDRESS_FAMILY_IPV6);
190 const IPAddressNumber& address = endpoint.address();
191 bool is_link_local = (address[0] == 0xFE) && ((address[1] & 0xC0) == 0x80);
192 if (is_link_local)
193 return false;
194 const uint8 kTeredoPrefix[] = { 0x20, 0x01, 0, 0 };
195 bool is_teredo = std::equal(kTeredoPrefix,
196 kTeredoPrefix + arraysize(kTeredoPrefix),
197 address.begin());
198 if (is_teredo)
199 return false;
200 return true;
[email protected]9db6f702013-04-10 18:10:51201}
202
[email protected]51b9a6b2012-06-25 21:50:29203// Provide a common macro to simplify code and readability. We must use a
204// macro as the underlying HISTOGRAM macro creates static variables.
205#define DNS_HISTOGRAM(name, time) UMA_HISTOGRAM_CUSTOM_TIMES(name, time, \
206 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromHours(1), 100)
207
208// A macro to simplify code and readability.
209#define DNS_HISTOGRAM_BY_PRIORITY(basename, priority, time) \
210 do { \
211 switch (priority) { \
212 case HIGHEST: DNS_HISTOGRAM(basename "_HIGHEST", time); break; \
213 case MEDIUM: DNS_HISTOGRAM(basename "_MEDIUM", time); break; \
214 case LOW: DNS_HISTOGRAM(basename "_LOW", time); break; \
215 case LOWEST: DNS_HISTOGRAM(basename "_LOWEST", time); break; \
216 case IDLE: DNS_HISTOGRAM(basename "_IDLE", time); break; \
217 default: NOTREACHED(); break; \
218 } \
219 DNS_HISTOGRAM(basename, time); \
220 } while (0)
221
222// Record time from Request creation until a valid DNS response.
223void RecordTotalTime(bool had_dns_config,
224 bool speculative,
225 base::TimeDelta duration) {
226 if (had_dns_config) {
227 if (speculative) {
228 DNS_HISTOGRAM("AsyncDNS.TotalTime_speculative", duration);
229 } else {
230 DNS_HISTOGRAM("AsyncDNS.TotalTime", duration);
231 }
232 } else {
233 if (speculative) {
234 DNS_HISTOGRAM("DNS.TotalTime_speculative", duration);
235 } else {
236 DNS_HISTOGRAM("DNS.TotalTime", duration);
237 }
238 }
239}
240
[email protected]1339a2a22012-10-17 08:39:43241void RecordTTL(base::TimeDelta ttl) {
242 UMA_HISTOGRAM_CUSTOM_TIMES("AsyncDNS.TTL", ttl,
243 base::TimeDelta::FromSeconds(1),
244 base::TimeDelta::FromDays(1), 100);
245}
246
[email protected]16c2bd72013-06-28 01:19:22247bool ConfigureAsyncDnsNoFallbackFieldTrial() {
248 const bool kDefault = false;
249
250 // Configure the AsyncDns field trial as follows:
251 // groups AsyncDnsNoFallbackA and AsyncDnsNoFallbackB: return true,
252 // groups AsyncDnsA and AsyncDnsB: return false,
253 // groups SystemDnsA and SystemDnsB: return false,
254 // otherwise (trial absent): return default.
255 std::string group_name = base::FieldTrialList::FindFullName("AsyncDns");
256 if (!group_name.empty())
257 return StartsWithASCII(group_name, "AsyncDnsNoFallback", false);
258 return kDefault;
259}
260
[email protected]d7b9a2b2012-05-31 22:31:19261//-----------------------------------------------------------------------------
262
[email protected]895123222012-10-25 15:21:17263AddressList EnsurePortOnAddressList(const AddressList& list, uint16 port) {
264 if (list.empty() || list.front().port() == port)
265 return list;
266 return AddressList::CopyWithPort(list, port);
[email protected]7054e78f2012-05-07 21:44:56267}
268
[email protected]ec666ab22013-04-17 20:05:59269// Returns true if |addresses| contains only IPv4 loopback addresses.
270bool IsAllIPv4Loopback(const AddressList& addresses) {
271 for (unsigned i = 0; i < addresses.size(); ++i) {
272 const IPAddressNumber& address = addresses[i].address();
273 switch (addresses[i].GetFamily()) {
274 case ADDRESS_FAMILY_IPV4:
275 if (address[0] != 127)
276 return false;
277 break;
278 case ADDRESS_FAMILY_IPV6:
279 return false;
280 default:
281 NOTREACHED();
282 return false;
283 }
284 }
285 return true;
286}
287
[email protected]cd565142012-06-12 16:21:45288// Creates NetLog parameters when the resolve failed.
289base::Value* NetLogProcTaskFailedCallback(uint32 attempt_number,
290 int net_error,
291 int os_error,
292 NetLog::LogLevel /* log_level */) {
[email protected]ea5ef4c2013-06-13 22:50:27293 base::DictionaryValue* dict = new base::DictionaryValue();
[email protected]cd565142012-06-12 16:21:45294 if (attempt_number)
295 dict->SetInteger("attempt_number", attempt_number);
[email protected]21526002010-05-16 19:42:46296
[email protected]cd565142012-06-12 16:21:45297 dict->SetInteger("net_error", net_error);
[email protected]13024882011-05-18 23:19:16298
[email protected]cd565142012-06-12 16:21:45299 if (os_error) {
300 dict->SetInteger("os_error", os_error);
[email protected]21526002010-05-16 19:42:46301#if defined(OS_POSIX)
[email protected]cd565142012-06-12 16:21:45302 dict->SetString("os_error_string", gai_strerror(os_error));
[email protected]21526002010-05-16 19:42:46303#elif defined(OS_WIN)
[email protected]cd565142012-06-12 16:21:45304 // Map the error code to a human-readable string.
305 LPWSTR error_string = NULL;
306 int size = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
307 FORMAT_MESSAGE_FROM_SYSTEM,
308 0, // Use the internal message table.
309 os_error,
310 0, // Use default language.
311 (LPWSTR)&error_string,
312 0, // Buffer size.
313 0); // Arguments (unused).
314 dict->SetString("os_error_string", WideToUTF8(error_string));
315 LocalFree(error_string);
[email protected]21526002010-05-16 19:42:46316#endif
[email protected]21526002010-05-16 19:42:46317 }
318
[email protected]cd565142012-06-12 16:21:45319 return dict;
320}
[email protected]a9813302012-04-28 09:29:28321
[email protected]cd565142012-06-12 16:21:45322// Creates NetLog parameters when the DnsTask failed.
323base::Value* NetLogDnsTaskFailedCallback(int net_error,
324 int dns_error,
325 NetLog::LogLevel /* log_level */) {
[email protected]ea5ef4c2013-06-13 22:50:27326 base::DictionaryValue* dict = new base::DictionaryValue();
[email protected]cd565142012-06-12 16:21:45327 dict->SetInteger("net_error", net_error);
328 if (dns_error)
329 dict->SetInteger("dns_error", dns_error);
330 return dict;
[email protected]ee094b82010-08-24 15:55:51331};
332
[email protected]cd565142012-06-12 16:21:45333// Creates NetLog parameters containing the information in a RequestInfo object,
334// along with the associated NetLog::Source.
335base::Value* NetLogRequestInfoCallback(const NetLog::Source& source,
336 const HostResolver::RequestInfo* info,
337 NetLog::LogLevel /* log_level */) {
[email protected]ea5ef4c2013-06-13 22:50:27338 base::DictionaryValue* dict = new base::DictionaryValue();
[email protected]cd565142012-06-12 16:21:45339 source.AddToEventParameters(dict);
[email protected]b3601bc22012-02-21 21:23:20340
[email protected]cd565142012-06-12 16:21:45341 dict->SetString("host", info->host_port_pair().ToString());
342 dict->SetInteger("address_family",
343 static_cast<int>(info->address_family()));
344 dict->SetBoolean("allow_cached_response", info->allow_cached_response());
345 dict->SetBoolean("is_speculative", info->is_speculative());
346 dict->SetInteger("priority", info->priority());
347 return dict;
348}
[email protected]b3601bc22012-02-21 21:23:20349
[email protected]cd565142012-06-12 16:21:45350// Creates NetLog parameters for the creation of a HostResolverImpl::Job.
351base::Value* NetLogJobCreationCallback(const NetLog::Source& source,
352 const std::string* host,
353 NetLog::LogLevel /* log_level */) {
[email protected]ea5ef4c2013-06-13 22:50:27354 base::DictionaryValue* dict = new base::DictionaryValue();
[email protected]cd565142012-06-12 16:21:45355 source.AddToEventParameters(dict);
356 dict->SetString("host", *host);
357 return dict;
358}
[email protected]a9813302012-04-28 09:29:28359
[email protected]cd565142012-06-12 16:21:45360// Creates NetLog parameters for HOST_RESOLVER_IMPL_JOB_ATTACH/DETACH events.
361base::Value* NetLogJobAttachCallback(const NetLog::Source& source,
362 RequestPriority priority,
363 NetLog::LogLevel /* log_level */) {
[email protected]ea5ef4c2013-06-13 22:50:27364 base::DictionaryValue* dict = new base::DictionaryValue();
[email protected]cd565142012-06-12 16:21:45365 source.AddToEventParameters(dict);
366 dict->SetInteger("priority", priority);
367 return dict;
368}
[email protected]b3601bc22012-02-21 21:23:20369
[email protected]cd565142012-06-12 16:21:45370// Creates NetLog parameters for the DNS_CONFIG_CHANGED event.
371base::Value* NetLogDnsConfigCallback(const DnsConfig* config,
372 NetLog::LogLevel /* log_level */) {
373 return config->ToValue();
374}
[email protected]b4481b222012-03-16 17:13:11375
[email protected]0f292de02012-02-01 22:28:20376// The logging routines are defined here because some requests are resolved
377// without a Request object.
378
379// Logs when a request has just been started.
380void LogStartRequest(const BoundNetLog& source_net_log,
381 const BoundNetLog& request_net_log,
382 const HostResolver::RequestInfo& info) {
383 source_net_log.BeginEvent(
384 NetLog::TYPE_HOST_RESOLVER_IMPL,
[email protected]cd565142012-06-12 16:21:45385 request_net_log.source().ToEventParametersCallback());
[email protected]0f292de02012-02-01 22:28:20386
387 request_net_log.BeginEvent(
388 NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST,
[email protected]cd565142012-06-12 16:21:45389 base::Bind(&NetLogRequestInfoCallback, source_net_log.source(), &info));
[email protected]0f292de02012-02-01 22:28:20390}
391
392// Logs when a request has just completed (before its callback is run).
393void LogFinishRequest(const BoundNetLog& source_net_log,
394 const BoundNetLog& request_net_log,
395 const HostResolver::RequestInfo& info,
[email protected]b3601bc22012-02-21 21:23:20396 int net_error) {
397 request_net_log.EndEventWithNetErrorCode(
398 NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST, net_error);
[email protected]4da911f2012-06-14 19:45:20399 source_net_log.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL);
[email protected]0f292de02012-02-01 22:28:20400}
401
402// Logs when a request has been cancelled.
403void LogCancelRequest(const BoundNetLog& source_net_log,
404 const BoundNetLog& request_net_log,
405 const HostResolverImpl::RequestInfo& info) {
[email protected]4da911f2012-06-14 19:45:20406 request_net_log.AddEvent(NetLog::TYPE_CANCELLED);
407 request_net_log.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST);
408 source_net_log.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL);
[email protected]0f292de02012-02-01 22:28:20409}
410
[email protected]b59ff372009-07-15 22:04:32411//-----------------------------------------------------------------------------
412
[email protected]0f292de02012-02-01 22:28:20413// Keeps track of the highest priority.
414class PriorityTracker {
415 public:
[email protected]8c98d002012-07-18 19:02:27416 explicit PriorityTracker(RequestPriority initial_priority)
417 : highest_priority_(initial_priority), total_count_(0) {
[email protected]0f292de02012-02-01 22:28:20418 memset(counts_, 0, sizeof(counts_));
419 }
420
421 RequestPriority highest_priority() const {
422 return highest_priority_;
423 }
424
425 size_t total_count() const {
426 return total_count_;
427 }
428
429 void Add(RequestPriority req_priority) {
430 ++total_count_;
431 ++counts_[req_priority];
[email protected]31ae7ab2012-04-24 21:09:05432 if (highest_priority_ < req_priority)
[email protected]0f292de02012-02-01 22:28:20433 highest_priority_ = req_priority;
434 }
435
436 void Remove(RequestPriority req_priority) {
437 DCHECK_GT(total_count_, 0u);
438 DCHECK_GT(counts_[req_priority], 0u);
439 --total_count_;
440 --counts_[req_priority];
441 size_t i;
[email protected]31ae7ab2012-04-24 21:09:05442 for (i = highest_priority_; i > MINIMUM_PRIORITY && !counts_[i]; --i);
[email protected]0f292de02012-02-01 22:28:20443 highest_priority_ = static_cast<RequestPriority>(i);
444
[email protected]31ae7ab2012-04-24 21:09:05445 // In absence of requests, default to MINIMUM_PRIORITY.
446 if (total_count_ == 0)
447 DCHECK_EQ(MINIMUM_PRIORITY, highest_priority_);
[email protected]0f292de02012-02-01 22:28:20448 }
449
450 private:
451 RequestPriority highest_priority_;
452 size_t total_count_;
453 size_t counts_[NUM_PRIORITIES];
454};
455
[email protected]c54a8912012-10-22 22:09:43456} // namespace
[email protected]0f292de02012-02-01 22:28:20457
458//-----------------------------------------------------------------------------
459
460// Holds the data for a request that could not be completed synchronously.
461// It is owned by a Job. Canceled Requests are only marked as canceled rather
462// than removed from the Job's |requests_| list.
[email protected]b59ff372009-07-15 22:04:32463class HostResolverImpl::Request {
464 public:
[email protected]ee094b82010-08-24 15:55:51465 Request(const BoundNetLog& source_net_log,
466 const BoundNetLog& request_net_log,
[email protected]54e13772009-08-14 03:01:09467 const RequestInfo& info,
[email protected]aa22b242011-11-16 18:58:29468 const CompletionCallback& callback,
[email protected]b59ff372009-07-15 22:04:32469 AddressList* addresses)
[email protected]ee094b82010-08-24 15:55:51470 : source_net_log_(source_net_log),
471 request_net_log_(request_net_log),
[email protected]54e13772009-08-14 03:01:09472 info_(info),
473 job_(NULL),
474 callback_(callback),
[email protected]51b9a6b2012-06-25 21:50:29475 addresses_(addresses),
476 request_time_(base::TimeTicks::Now()) {
[email protected]54e13772009-08-14 03:01:09477 }
[email protected]b59ff372009-07-15 22:04:32478
[email protected]0f292de02012-02-01 22:28:20479 // Mark the request as canceled.
480 void MarkAsCanceled() {
[email protected]b59ff372009-07-15 22:04:32481 job_ = NULL;
[email protected]b59ff372009-07-15 22:04:32482 addresses_ = NULL;
[email protected]aa22b242011-11-16 18:58:29483 callback_.Reset();
[email protected]b59ff372009-07-15 22:04:32484 }
485
[email protected]0f292de02012-02-01 22:28:20486 bool was_canceled() const {
[email protected]aa22b242011-11-16 18:58:29487 return callback_.is_null();
[email protected]b59ff372009-07-15 22:04:32488 }
489
490 void set_job(Job* job) {
[email protected]0f292de02012-02-01 22:28:20491 DCHECK(job);
[email protected]b59ff372009-07-15 22:04:32492 // Identify which job the request is waiting on.
493 job_ = job;
494 }
495
[email protected]0f292de02012-02-01 22:28:20496 // Prepare final AddressList and call completion callback.
[email protected]b3601bc22012-02-21 21:23:20497 void OnComplete(int error, const AddressList& addr_list) {
[email protected]51b9a6b2012-06-25 21:50:29498 DCHECK(!was_canceled());
[email protected]895123222012-10-25 15:21:17499 if (error == OK)
500 *addresses_ = EnsurePortOnAddressList(addr_list, info_.port());
[email protected]aa22b242011-11-16 18:58:29501 CompletionCallback callback = callback_;
[email protected]0f292de02012-02-01 22:28:20502 MarkAsCanceled();
[email protected]aa22b242011-11-16 18:58:29503 callback.Run(error);
[email protected]b59ff372009-07-15 22:04:32504 }
505
[email protected]b59ff372009-07-15 22:04:32506 Job* job() const {
507 return job_;
508 }
509
[email protected]0f292de02012-02-01 22:28:20510 // NetLog for the source, passed in HostResolver::Resolve.
[email protected]ee094b82010-08-24 15:55:51511 const BoundNetLog& source_net_log() {
512 return source_net_log_;
513 }
514
[email protected]0f292de02012-02-01 22:28:20515 // NetLog for this request.
[email protected]ee094b82010-08-24 15:55:51516 const BoundNetLog& request_net_log() {
517 return request_net_log_;
[email protected]54e13772009-08-14 03:01:09518 }
519
[email protected]b59ff372009-07-15 22:04:32520 const RequestInfo& info() const {
521 return info_;
522 }
523
[email protected]51b9a6b2012-06-25 21:50:29524 base::TimeTicks request_time() const {
525 return request_time_;
526 }
527
[email protected]b59ff372009-07-15 22:04:32528 private:
[email protected]ee094b82010-08-24 15:55:51529 BoundNetLog source_net_log_;
530 BoundNetLog request_net_log_;
[email protected]54e13772009-08-14 03:01:09531
[email protected]b59ff372009-07-15 22:04:32532 // The request info that started the request.
533 RequestInfo info_;
534
[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
[email protected]189163e2011-05-11 01:48:54677 origin_loop_->PostTask(
678 FROM_HERE,
[email protected]0f292de02012-02-01 22:28:20679 base::Bind(&ProcTask::OnLookupComplete, this, results, start_time,
[email protected]33152acc2011-10-20 23:37:12680 attempt_number, error, os_error));
[email protected]189163e2011-05-11 01:48:54681 }
682
[email protected]0f292de02012-02-01 22:28:20683 // Makes next attempt if DoLookup() has not finished (runs on origin thread).
684 void RetryIfNotComplete() {
[email protected]189163e2011-05-11 01:48:54685 DCHECK(origin_loop_->BelongsToCurrentThread());
686
[email protected]0f292de02012-02-01 22:28:20687 if (was_completed() || was_canceled())
[email protected]189163e2011-05-11 01:48:54688 return;
689
[email protected]0f292de02012-02-01 22:28:20690 params_.unresponsive_delay *= params_.retry_factor;
[email protected]189163e2011-05-11 01:48:54691 StartLookupAttempt();
[email protected]b59ff372009-07-15 22:04:32692 }
693
694 // Callback for when DoLookup() completes (runs on origin thread).
[email protected]189163e2011-05-11 01:48:54695 void OnLookupComplete(const AddressList& results,
696 const base::TimeTicks& start_time,
697 const uint32 attempt_number,
698 int error,
699 const int os_error) {
[email protected]3e9d9cc2011-05-03 21:08:15700 DCHECK(origin_loop_->BelongsToCurrentThread());
[email protected]49b70b222013-05-07 21:24:23701 // If results are empty, we should return an error.
702 bool empty_list_on_ok = (error == OK && results.empty());
703 UMA_HISTOGRAM_BOOLEAN("DNS.EmptyAddressListAndNoError", empty_list_on_ok);
704 if (empty_list_on_ok)
705 error = ERR_NAME_NOT_RESOLVED;
[email protected]189163e2011-05-11 01:48:54706
707 bool was_retry_attempt = attempt_number > 1;
708
[email protected]2d3b7762010-10-09 00:35:47709 // Ideally the following code would be part of host_resolver_proc.cc,
[email protected]b3601bc22012-02-21 21:23:20710 // however it isn't safe to call NetworkChangeNotifier from worker threads.
711 // So we do it here on the IO thread instead.
[email protected]189163e2011-05-11 01:48:54712 if (error != OK && NetworkChangeNotifier::IsOffline())
713 error = ERR_INTERNET_DISCONNECTED;
[email protected]2d3b7762010-10-09 00:35:47714
[email protected]b3601bc22012-02-21 21:23:20715 // If this is the first attempt that is finishing later, then record data
716 // for the first attempt. Won't contaminate with retry attempt's data.
[email protected]189163e2011-05-11 01:48:54717 if (!was_retry_attempt)
718 RecordPerformanceHistograms(start_time, error, os_error);
719
720 RecordAttemptHistograms(start_time, attempt_number, error, os_error);
[email protected]f2d8c4212010-02-02 00:56:35721
[email protected]0f292de02012-02-01 22:28:20722 if (was_canceled())
[email protected]b59ff372009-07-15 22:04:32723 return;
724
[email protected]cd565142012-06-12 16:21:45725 NetLog::ParametersCallback net_log_callback;
[email protected]0f292de02012-02-01 22:28:20726 if (error != OK) {
[email protected]cd565142012-06-12 16:21:45727 net_log_callback = base::Bind(&NetLogProcTaskFailedCallback,
728 attempt_number,
729 error,
730 os_error);
[email protected]0f292de02012-02-01 22:28:20731 } else {
[email protected]cd565142012-06-12 16:21:45732 net_log_callback = NetLog::IntegerCallback("attempt_number",
733 attempt_number);
[email protected]0f292de02012-02-01 22:28:20734 }
[email protected]cd565142012-06-12 16:21:45735 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_ATTEMPT_FINISHED,
736 net_log_callback);
[email protected]0f292de02012-02-01 22:28:20737
738 if (was_completed())
739 return;
740
741 // Copy the results from the first worker thread that resolves the host.
742 results_ = results;
743 completed_attempt_number_ = attempt_number;
744 completed_attempt_error_ = error;
745
[email protected]e87b8b512011-06-14 22:12:52746 if (was_retry_attempt) {
747 // If retry attempt finishes before 1st attempt, then get stats on how
748 // much time is saved by having spawned an extra attempt.
749 retry_attempt_finished_time_ = base::TimeTicks::Now();
750 }
751
[email protected]189163e2011-05-11 01:48:54752 if (error != OK) {
[email protected]cd565142012-06-12 16:21:45753 net_log_callback = base::Bind(&NetLogProcTaskFailedCallback,
754 0, error, os_error);
[email protected]ee094b82010-08-24 15:55:51755 } else {
[email protected]cd565142012-06-12 16:21:45756 net_log_callback = results_.CreateNetLogCallback();
[email protected]ee094b82010-08-24 15:55:51757 }
[email protected]cd565142012-06-12 16:21:45758 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK,
759 net_log_callback);
[email protected]ee094b82010-08-24 15:55:51760
[email protected]b3601bc22012-02-21 21:23:20761 callback_.Run(error, results_);
[email protected]b59ff372009-07-15 22:04:32762 }
763
[email protected]189163e2011-05-11 01:48:54764 void RecordPerformanceHistograms(const base::TimeTicks& start_time,
765 const int error,
766 const int os_error) const {
[email protected]3e9d9cc2011-05-03 21:08:15767 DCHECK(origin_loop_->BelongsToCurrentThread());
[email protected]1e9bbd22010-10-15 16:42:45768 enum Category { // Used in HISTOGRAM_ENUMERATION.
769 RESOLVE_SUCCESS,
770 RESOLVE_FAIL,
771 RESOLVE_SPECULATIVE_SUCCESS,
772 RESOLVE_SPECULATIVE_FAIL,
773 RESOLVE_MAX, // Bounding value.
774 };
775 int category = RESOLVE_MAX; // Illegal value for later DCHECK only.
776
[email protected]189163e2011-05-11 01:48:54777 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
778 if (error == OK) {
[email protected]1e9bbd22010-10-15 16:42:45779 if (had_non_speculative_request_) {
780 category = RESOLVE_SUCCESS;
781 DNS_HISTOGRAM("DNS.ResolveSuccess", duration);
782 } else {
783 category = RESOLVE_SPECULATIVE_SUCCESS;
784 DNS_HISTOGRAM("DNS.ResolveSpeculativeSuccess", duration);
785 }
[email protected]7e96d792011-06-10 17:08:23786
[email protected]78eac2a2012-03-14 19:09:27787 // Log DNS lookups based on |address_family|. This will help us determine
[email protected]7e96d792011-06-10 17:08:23788 // if IPv4 or IPv4/6 lookups are faster or slower.
789 switch(key_.address_family) {
790 case ADDRESS_FAMILY_IPV4:
791 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_IPV4", duration);
792 break;
793 case ADDRESS_FAMILY_IPV6:
794 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_IPV6", duration);
795 break;
796 case ADDRESS_FAMILY_UNSPECIFIED:
797 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_UNSPEC", duration);
798 break;
799 }
[email protected]1e9bbd22010-10-15 16:42:45800 } else {
801 if (had_non_speculative_request_) {
802 category = RESOLVE_FAIL;
803 DNS_HISTOGRAM("DNS.ResolveFail", duration);
804 } else {
805 category = RESOLVE_SPECULATIVE_FAIL;
806 DNS_HISTOGRAM("DNS.ResolveSpeculativeFail", duration);
807 }
[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.ResolveFail_FAMILY_IPV4", duration);
813 break;
814 case ADDRESS_FAMILY_IPV6:
815 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_IPV6", duration);
816 break;
817 case ADDRESS_FAMILY_UNSPECIFIED:
818 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_UNSPEC", duration);
819 break;
820 }
[email protected]c833e322010-10-16 23:51:36821 UMA_HISTOGRAM_CUSTOM_ENUMERATION(kOSErrorsForGetAddrinfoHistogramName,
[email protected]189163e2011-05-11 01:48:54822 std::abs(os_error),
[email protected]1e9bbd22010-10-15 16:42:45823 GetAllGetAddrinfoOSErrors());
824 }
[email protected]051b6ab2010-10-18 16:50:46825 DCHECK_LT(category, static_cast<int>(RESOLVE_MAX)); // Be sure it was set.
[email protected]1e9bbd22010-10-15 16:42:45826
827 UMA_HISTOGRAM_ENUMERATION("DNS.ResolveCategory", category, RESOLVE_MAX);
[email protected]1e9bbd22010-10-15 16:42:45828 }
829
[email protected]189163e2011-05-11 01:48:54830 void RecordAttemptHistograms(const base::TimeTicks& start_time,
831 const uint32 attempt_number,
832 const int error,
833 const int os_error) const {
[email protected]0f292de02012-02-01 22:28:20834 DCHECK(origin_loop_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54835 bool first_attempt_to_complete =
836 completed_attempt_number_ == attempt_number;
[email protected]e87b8b512011-06-14 22:12:52837 bool is_first_attempt = (attempt_number == 1);
[email protected]1e9bbd22010-10-15 16:42:45838
[email protected]189163e2011-05-11 01:48:54839 if (first_attempt_to_complete) {
840 // If this was first attempt to complete, then record the resolution
841 // status of the attempt.
842 if (completed_attempt_error_ == OK) {
843 UMA_HISTOGRAM_ENUMERATION(
844 "DNS.AttemptFirstSuccess", attempt_number, 100);
845 } else {
846 UMA_HISTOGRAM_ENUMERATION(
847 "DNS.AttemptFirstFailure", attempt_number, 100);
848 }
849 }
850
851 if (error == OK)
852 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptSuccess", attempt_number, 100);
853 else
854 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptFailure", attempt_number, 100);
855
[email protected]e87b8b512011-06-14 22:12:52856 // If first attempt didn't finish before retry attempt, then calculate stats
857 // on how much time is saved by having spawned an extra attempt.
[email protected]0f292de02012-02-01 22:28:20858 if (!first_attempt_to_complete && is_first_attempt && !was_canceled()) {
[email protected]e87b8b512011-06-14 22:12:52859 DNS_HISTOGRAM("DNS.AttemptTimeSavedByRetry",
860 base::TimeTicks::Now() - retry_attempt_finished_time_);
861 }
862
[email protected]0f292de02012-02-01 22:28:20863 if (was_canceled() || !first_attempt_to_complete) {
[email protected]189163e2011-05-11 01:48:54864 // Count those attempts which completed after the job was already canceled
865 // OR after the job was already completed by an earlier attempt (so in
866 // effect).
867 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptDiscarded", attempt_number, 100);
868
[email protected]0f292de02012-02-01 22:28:20869 // Record if job is canceled.
870 if (was_canceled())
[email protected]189163e2011-05-11 01:48:54871 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptCancelled", attempt_number, 100);
872 }
873
874 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
875 if (error == OK)
876 DNS_HISTOGRAM("DNS.AttemptSuccessDuration", duration);
877 else
878 DNS_HISTOGRAM("DNS.AttemptFailDuration", duration);
879 }
[email protected]1e9bbd22010-10-15 16:42:45880
[email protected]b59ff372009-07-15 22:04:32881 // Set on the origin thread, read on the worker thread.
[email protected]123ab1e32009-10-21 19:12:57882 Key key_;
[email protected]b59ff372009-07-15 22:04:32883
[email protected]0f292de02012-02-01 22:28:20884 // Holds an owning reference to the HostResolverProc that we are going to use.
[email protected]b59ff372009-07-15 22:04:32885 // This may not be the current resolver procedure by the time we call
886 // ResolveAddrInfo, but that's OK... we'll use it anyways, and the owning
887 // reference ensures that it remains valid until we are done.
[email protected]0f292de02012-02-01 22:28:20888 ProcTaskParams params_;
[email protected]b59ff372009-07-15 22:04:32889
[email protected]0f292de02012-02-01 22:28:20890 // The listener to the results of this ProcTask.
891 Callback callback_;
892
893 // Used to post ourselves onto the origin thread.
894 scoped_refptr<base::MessageLoopProxy> origin_loop_;
[email protected]189163e2011-05-11 01:48:54895
896 // Keeps track of the number of attempts we have made so far to resolve the
897 // host. Whenever we start an attempt to resolve the host, we increase this
898 // number.
899 uint32 attempt_number_;
900
901 // The index of the attempt which finished first (or 0 if the job is still in
902 // progress).
903 uint32 completed_attempt_number_;
904
905 // The result (a net error code) from the first attempt to complete.
906 int completed_attempt_error_;
[email protected]252b699b2010-02-05 21:38:06907
[email protected]e87b8b512011-06-14 22:12:52908 // The time when retry attempt was finished.
909 base::TimeTicks retry_attempt_finished_time_;
910
[email protected]252b699b2010-02-05 21:38:06911 // True if a non-speculative request was ever attached to this job
[email protected]0f292de02012-02-01 22:28:20912 // (regardless of whether or not it was later canceled.
[email protected]252b699b2010-02-05 21:38:06913 // This boolean is used for histogramming the duration of jobs used to
914 // service non-speculative requests.
915 bool had_non_speculative_request_;
916
[email protected]b59ff372009-07-15 22:04:32917 AddressList results_;
918
[email protected]ee094b82010-08-24 15:55:51919 BoundNetLog net_log_;
920
[email protected]0f292de02012-02-01 22:28:20921 DISALLOW_COPY_AND_ASSIGN(ProcTask);
[email protected]b59ff372009-07-15 22:04:32922};
923
924//-----------------------------------------------------------------------------
925
[email protected]12faa4c2012-11-06 04:44:18926// Wraps a call to HaveOnlyLoopbackAddresses to be executed on the WorkerPool as
927// it takes 40-100ms and should not block initialization.
928class HostResolverImpl::LoopbackProbeJob {
929 public:
930 explicit LoopbackProbeJob(const base::WeakPtr<HostResolverImpl>& resolver)
931 : resolver_(resolver),
932 result_(false) {
[email protected]11fbca0b2013-06-02 23:37:21933 DCHECK(resolver.get());
[email protected]12faa4c2012-11-06 04:44:18934 const bool kIsSlow = true;
935 base::WorkerPool::PostTaskAndReply(
936 FROM_HERE,
937 base::Bind(&LoopbackProbeJob::DoProbe, base::Unretained(this)),
938 base::Bind(&LoopbackProbeJob::OnProbeComplete, base::Owned(this)),
939 kIsSlow);
940 }
941
942 virtual ~LoopbackProbeJob() {}
943
944 private:
945 // Runs on worker thread.
946 void DoProbe() {
947 result_ = HaveOnlyLoopbackAddresses();
948 }
949
950 void OnProbeComplete() {
[email protected]11fbca0b2013-06-02 23:37:21951 if (!resolver_.get())
[email protected]12faa4c2012-11-06 04:44:18952 return;
953 resolver_->SetHaveOnlyLoopbackAddresses(result_);
954 }
955
956 // Used/set only on origin thread.
957 base::WeakPtr<HostResolverImpl> resolver_;
958
959 bool result_;
960
961 DISALLOW_COPY_AND_ASSIGN(LoopbackProbeJob);
962};
963
[email protected]0f8f1b432010-03-16 19:06:03964//-----------------------------------------------------------------------------
965
[email protected]b3601bc22012-02-21 21:23:20966// Resolves the hostname using DnsTransaction.
967// TODO(szym): This could be moved to separate source file as well.
[email protected]0adcb2b2012-08-15 21:30:46968class HostResolverImpl::DnsTask : public base::SupportsWeakPtr<DnsTask> {
[email protected]b3601bc22012-02-21 21:23:20969 public:
970 typedef base::Callback<void(int net_error,
971 const AddressList& addr_list,
972 base::TimeDelta ttl)> Callback;
973
[email protected]0adcb2b2012-08-15 21:30:46974 DnsTask(DnsClient* client,
[email protected]b3601bc22012-02-21 21:23:20975 const Key& key,
976 const Callback& callback,
977 const BoundNetLog& job_net_log)
[email protected]0adcb2b2012-08-15 21:30:46978 : client_(client),
979 family_(key.address_family),
980 callback_(callback),
981 net_log_(job_net_log) {
982 DCHECK(client);
[email protected]b3601bc22012-02-21 21:23:20983 DCHECK(!callback.is_null());
984
[email protected]0adcb2b2012-08-15 21:30:46985 // If unspecified, do IPv4 first, because suffix search will be faster.
986 uint16 qtype = (family_ == ADDRESS_FAMILY_IPV6) ?
987 dns_protocol::kTypeAAAA :
988 dns_protocol::kTypeA;
989 transaction_ = client_->GetTransactionFactory()->CreateTransaction(
[email protected]b3601bc22012-02-21 21:23:20990 key.hostname,
991 qtype,
[email protected]1def74c2012-03-22 20:07:00992 base::Bind(&DnsTask::OnTransactionComplete, base::Unretained(this),
[email protected]0adcb2b2012-08-15 21:30:46993 true /* first_query */, base::TimeTicks::Now()),
[email protected]b3601bc22012-02-21 21:23:20994 net_log_);
[email protected]b3601bc22012-02-21 21:23:20995 }
996
[email protected]a210eef92013-07-19 19:06:12997 void Start() {
[email protected]4da911f2012-06-14 19:45:20998 net_log_.BeginEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK);
[email protected]a210eef92013-07-19 19:06:12999 transaction_->Start();
[email protected]b3601bc22012-02-21 21:23:201000 }
1001
[email protected]0adcb2b2012-08-15 21:30:461002 private:
1003 void OnTransactionComplete(bool first_query,
1004 const base::TimeTicks& start_time,
[email protected]1def74c2012-03-22 20:07:001005 DnsTransaction* transaction,
[email protected]b3601bc22012-02-21 21:23:201006 int net_error,
1007 const DnsResponse* response) {
[email protected]add76532012-03-30 14:47:471008 DCHECK(transaction);
[email protected]02cd6982013-01-10 20:12:511009 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]b3601bc22012-02-21 21:23:201010 // Run |callback_| last since the owning Job will then delete this DnsTask.
[email protected]0adcb2b2012-08-15 21:30:461011 if (net_error != OK) {
[email protected]02cd6982013-01-10 20:12:511012 DNS_HISTOGRAM("AsyncDNS.TransactionFailure", duration);
[email protected]0adcb2b2012-08-15 21:30:461013 OnFailure(net_error, DnsResponse::DNS_PARSE_OK);
1014 return;
[email protected]6c411902012-08-14 22:36:361015 }
[email protected]0adcb2b2012-08-15 21:30:461016
1017 CHECK(response);
[email protected]02cd6982013-01-10 20:12:511018 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess", duration);
1019 switch (transaction->GetType()) {
1020 case dns_protocol::kTypeA:
1021 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess_A", duration);
1022 break;
1023 case dns_protocol::kTypeAAAA:
1024 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess_AAAA", duration);
1025 break;
1026 }
[email protected]0adcb2b2012-08-15 21:30:461027 AddressList addr_list;
1028 base::TimeDelta ttl;
1029 DnsResponse::Result result = response->ParseToAddressList(&addr_list, &ttl);
1030 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ParseToAddressList",
1031 result,
1032 DnsResponse::DNS_PARSE_RESULT_MAX);
1033 if (result != DnsResponse::DNS_PARSE_OK) {
1034 // Fail even if the other query succeeds.
1035 OnFailure(ERR_DNS_MALFORMED_RESPONSE, result);
1036 return;
1037 }
1038
1039 bool needs_sort = false;
1040 if (first_query) {
1041 DCHECK(client_->GetConfig()) <<
1042 "Transaction should have been aborted when config changed!";
1043 if (family_ == ADDRESS_FAMILY_IPV6) {
1044 needs_sort = (addr_list.size() > 1);
1045 } else if (family_ == ADDRESS_FAMILY_UNSPECIFIED) {
1046 first_addr_list_ = addr_list;
1047 first_ttl_ = ttl;
1048 // Use fully-qualified domain name to avoid search.
1049 transaction_ = client_->GetTransactionFactory()->CreateTransaction(
1050 response->GetDottedName() + ".",
1051 dns_protocol::kTypeAAAA,
1052 base::Bind(&DnsTask::OnTransactionComplete, base::Unretained(this),
1053 false /* first_query */, base::TimeTicks::Now()),
1054 net_log_);
[email protected]a210eef92013-07-19 19:06:121055 transaction_->Start();
[email protected]0adcb2b2012-08-15 21:30:461056 return;
1057 }
1058 } else {
1059 DCHECK_EQ(ADDRESS_FAMILY_UNSPECIFIED, family_);
1060 bool has_ipv6_addresses = !addr_list.empty();
1061 if (!first_addr_list_.empty()) {
1062 ttl = std::min(ttl, first_ttl_);
1063 // Place IPv4 addresses after IPv6.
1064 addr_list.insert(addr_list.end(), first_addr_list_.begin(),
1065 first_addr_list_.end());
1066 }
1067 needs_sort = (has_ipv6_addresses && addr_list.size() > 1);
1068 }
1069
1070 if (addr_list.empty()) {
1071 // TODO(szym): Don't fallback to ProcTask in this case.
1072 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
1073 return;
1074 }
1075
1076 if (needs_sort) {
1077 // Sort could complete synchronously.
1078 client_->GetAddressSorter()->Sort(
1079 addr_list,
[email protected]4589a3a2012-09-20 20:57:071080 base::Bind(&DnsTask::OnSortComplete,
1081 AsWeakPtr(),
[email protected]0adcb2b2012-08-15 21:30:461082 base::TimeTicks::Now(),
1083 ttl));
1084 } else {
1085 OnSuccess(addr_list, ttl);
1086 }
1087 }
1088
1089 void OnSortComplete(base::TimeTicks start_time,
1090 base::TimeDelta ttl,
1091 bool success,
1092 const AddressList& addr_list) {
1093 if (!success) {
1094 DNS_HISTOGRAM("AsyncDNS.SortFailure",
1095 base::TimeTicks::Now() - start_time);
1096 OnFailure(ERR_DNS_SORT_ERROR, DnsResponse::DNS_PARSE_OK);
1097 return;
1098 }
1099
1100 DNS_HISTOGRAM("AsyncDNS.SortSuccess",
1101 base::TimeTicks::Now() - start_time);
1102
1103 // AddressSorter prunes unusable destinations.
1104 if (addr_list.empty()) {
1105 LOG(WARNING) << "Address list empty after RFC3484 sort";
1106 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
1107 return;
1108 }
1109
1110 OnSuccess(addr_list, ttl);
1111 }
1112
1113 void OnFailure(int net_error, DnsResponse::Result result) {
1114 DCHECK_NE(OK, net_error);
[email protected]cd565142012-06-12 16:21:451115 net_log_.EndEvent(
1116 NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK,
1117 base::Bind(&NetLogDnsTaskFailedCallback, net_error, result));
[email protected]b3601bc22012-02-21 21:23:201118 callback_.Run(net_error, AddressList(), base::TimeDelta());
1119 }
1120
[email protected]0adcb2b2012-08-15 21:30:461121 void OnSuccess(const AddressList& addr_list, base::TimeDelta ttl) {
1122 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK,
1123 addr_list.CreateNetLogCallback());
1124 callback_.Run(OK, addr_list, ttl);
1125 }
1126
1127 DnsClient* client_;
1128 AddressFamily family_;
[email protected]b3601bc22012-02-21 21:23:201129 // The listener to the results of this DnsTask.
1130 Callback callback_;
[email protected]b3601bc22012-02-21 21:23:201131 const BoundNetLog net_log_;
1132
1133 scoped_ptr<DnsTransaction> transaction_;
[email protected]0adcb2b2012-08-15 21:30:461134
1135 // Results from the first transaction. Used only if |family_| is unspecified.
1136 AddressList first_addr_list_;
1137 base::TimeDelta first_ttl_;
1138
1139 DISALLOW_COPY_AND_ASSIGN(DnsTask);
[email protected]b3601bc22012-02-21 21:23:201140};
1141
1142//-----------------------------------------------------------------------------
1143
[email protected]0f292de02012-02-01 22:28:201144// Aggregates all Requests for the same Key. Dispatched via PriorityDispatch.
[email protected]0f292de02012-02-01 22:28:201145class HostResolverImpl::Job : public PrioritizedDispatcher::Job {
[email protected]68ad3ee2010-01-30 03:45:391146 public:
[email protected]0f292de02012-02-01 22:28:201147 // Creates new job for |key| where |request_net_log| is bound to the
[email protected]16ee26d2012-03-08 03:34:351148 // request that spawned it.
[email protected]12faa4c2012-11-06 04:44:181149 Job(const base::WeakPtr<HostResolverImpl>& resolver,
[email protected]0f292de02012-02-01 22:28:201150 const Key& key,
[email protected]8c98d002012-07-18 19:02:271151 RequestPriority priority,
[email protected]16ee26d2012-03-08 03:34:351152 const BoundNetLog& request_net_log)
[email protected]12faa4c2012-11-06 04:44:181153 : resolver_(resolver),
[email protected]0f292de02012-02-01 22:28:201154 key_(key),
[email protected]8c98d002012-07-18 19:02:271155 priority_tracker_(priority),
[email protected]0f292de02012-02-01 22:28:201156 had_non_speculative_request_(false),
[email protected]51b9a6b2012-06-25 21:50:291157 had_dns_config_(false),
[email protected]1d932852012-06-19 19:40:331158 dns_task_error_(OK),
[email protected]51b9a6b2012-06-25 21:50:291159 creation_time_(base::TimeTicks::Now()),
1160 priority_change_time_(creation_time_),
[email protected]0f292de02012-02-01 22:28:201161 net_log_(BoundNetLog::Make(request_net_log.net_log(),
[email protected]b3601bc22012-02-21 21:23:201162 NetLog::SOURCE_HOST_RESOLVER_IMPL_JOB)) {
[email protected]4da911f2012-06-14 19:45:201163 request_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_CREATE_JOB);
[email protected]0f292de02012-02-01 22:28:201164
1165 net_log_.BeginEvent(
1166 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
[email protected]cd565142012-06-12 16:21:451167 base::Bind(&NetLogJobCreationCallback,
1168 request_net_log.source(),
1169 &key_.hostname));
[email protected]68ad3ee2010-01-30 03:45:391170 }
1171
[email protected]0f292de02012-02-01 22:28:201172 virtual ~Job() {
[email protected]b3601bc22012-02-21 21:23:201173 if (is_running()) {
1174 // |resolver_| was destroyed with this Job still in flight.
1175 // Clean-up, record in the log, but don't run any callbacks.
1176 if (is_proc_running()) {
[email protected]0f292de02012-02-01 22:28:201177 proc_task_->Cancel();
1178 proc_task_ = NULL;
[email protected]0f292de02012-02-01 22:28:201179 }
[email protected]16ee26d2012-03-08 03:34:351180 // Clean up now for nice NetLog.
1181 dns_task_.reset(NULL);
[email protected]b3601bc22012-02-21 21:23:201182 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
1183 ERR_ABORTED);
1184 } else if (is_queued()) {
[email protected]57a48d32012-03-03 00:04:551185 // |resolver_| was destroyed without running this Job.
[email protected]16ee26d2012-03-08 03:34:351186 // TODO(szym): is there any benefit in having this distinction?
[email protected]4da911f2012-06-14 19:45:201187 net_log_.AddEvent(NetLog::TYPE_CANCELLED);
1188 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB);
[email protected]68ad3ee2010-01-30 03:45:391189 }
[email protected]b3601bc22012-02-21 21:23:201190 // else CompleteRequests logged EndEvent.
[email protected]68ad3ee2010-01-30 03:45:391191
[email protected]b3601bc22012-02-21 21:23:201192 // Log any remaining Requests as cancelled.
1193 for (RequestsList::const_iterator it = requests_.begin();
1194 it != requests_.end(); ++it) {
1195 Request* req = *it;
1196 if (req->was_canceled())
1197 continue;
1198 DCHECK_EQ(this, req->job());
1199 LogCancelRequest(req->source_net_log(), req->request_net_log(),
1200 req->info());
1201 }
[email protected]68ad3ee2010-01-30 03:45:391202 }
1203
[email protected]16ee26d2012-03-08 03:34:351204 // Add this job to the dispatcher.
[email protected]8c98d002012-07-18 19:02:271205 void Schedule() {
1206 handle_ = resolver_->dispatcher_.Add(this, priority());
[email protected]16ee26d2012-03-08 03:34:351207 }
1208
[email protected]b3601bc22012-02-21 21:23:201209 void AddRequest(scoped_ptr<Request> req) {
[email protected]0f292de02012-02-01 22:28:201210 DCHECK_EQ(key_.hostname, req->info().hostname());
1211
1212 req->set_job(this);
[email protected]0f292de02012-02-01 22:28:201213 priority_tracker_.Add(req->info().priority());
1214
1215 req->request_net_log().AddEvent(
1216 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_ATTACH,
[email protected]cd565142012-06-12 16:21:451217 net_log_.source().ToEventParametersCallback());
[email protected]0f292de02012-02-01 22:28:201218
1219 net_log_.AddEvent(
1220 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_REQUEST_ATTACH,
[email protected]cd565142012-06-12 16:21:451221 base::Bind(&NetLogJobAttachCallback,
1222 req->request_net_log().source(),
1223 priority()));
[email protected]0f292de02012-02-01 22:28:201224
1225 // TODO(szym): Check if this is still needed.
1226 if (!req->info().is_speculative()) {
1227 had_non_speculative_request_ = true;
[email protected]90499482013-06-01 00:39:501228 if (proc_task_.get())
[email protected]0f292de02012-02-01 22:28:201229 proc_task_->set_had_non_speculative_request();
[email protected]68ad3ee2010-01-30 03:45:391230 }
[email protected]b3601bc22012-02-21 21:23:201231
1232 requests_.push_back(req.release());
1233
[email protected]51b9a6b2012-06-25 21:50:291234 UpdatePriority();
[email protected]68ad3ee2010-01-30 03:45:391235 }
1236
[email protected]16ee26d2012-03-08 03:34:351237 // Marks |req| as cancelled. If it was the last active Request, also finishes
[email protected]0adcb2b2012-08-15 21:30:461238 // this Job, marking it as cancelled, and deletes it.
[email protected]0f292de02012-02-01 22:28:201239 void CancelRequest(Request* req) {
1240 DCHECK_EQ(key_.hostname, req->info().hostname());
1241 DCHECK(!req->was_canceled());
[email protected]16ee26d2012-03-08 03:34:351242
[email protected]0f292de02012-02-01 22:28:201243 // Don't remove it from |requests_| just mark it canceled.
1244 req->MarkAsCanceled();
1245 LogCancelRequest(req->source_net_log(), req->request_net_log(),
1246 req->info());
[email protected]16ee26d2012-03-08 03:34:351247
[email protected]0f292de02012-02-01 22:28:201248 priority_tracker_.Remove(req->info().priority());
1249 net_log_.AddEvent(
1250 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_REQUEST_DETACH,
[email protected]cd565142012-06-12 16:21:451251 base::Bind(&NetLogJobAttachCallback,
1252 req->request_net_log().source(),
1253 priority()));
[email protected]b3601bc22012-02-21 21:23:201254
[email protected]16ee26d2012-03-08 03:34:351255 if (num_active_requests() > 0) {
[email protected]51b9a6b2012-06-25 21:50:291256 UpdatePriority();
[email protected]16ee26d2012-03-08 03:34:351257 } else {
1258 // If we were called from a Request's callback within CompleteRequests,
1259 // that Request could not have been cancelled, so num_active_requests()
1260 // could not be 0. Therefore, we are not in CompleteRequests().
[email protected]1339a2a22012-10-17 08:39:431261 CompleteRequestsWithError(OK /* cancelled */);
[email protected]b3601bc22012-02-21 21:23:201262 }
[email protected]68ad3ee2010-01-30 03:45:391263 }
1264
[email protected]7af985a2012-12-14 22:40:421265 // Called from AbortAllInProgressJobs. Completes all requests and destroys
1266 // the job. This currently assumes the abort is due to a network change.
[email protected]0f292de02012-02-01 22:28:201267 void Abort() {
[email protected]0f292de02012-02-01 22:28:201268 DCHECK(is_running());
[email protected]7af985a2012-12-14 22:40:421269 CompleteRequestsWithError(ERR_NETWORK_CHANGED);
[email protected]b3601bc22012-02-21 21:23:201270 }
1271
[email protected]f0f602bd2012-11-15 18:01:021272 // If DnsTask present, abort it and fall back to ProcTask.
1273 void AbortDnsTask() {
1274 if (dns_task_) {
1275 dns_task_.reset();
1276 dns_task_error_ = OK;
1277 StartProcTask();
1278 }
1279 }
1280
[email protected]16ee26d2012-03-08 03:34:351281 // Called by HostResolverImpl when this job is evicted due to queue overflow.
1282 // Completes all requests and destroys the job.
1283 void OnEvicted() {
1284 DCHECK(!is_running());
1285 DCHECK(is_queued());
1286 handle_.Reset();
1287
[email protected]4da911f2012-06-14 19:45:201288 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_EVICTED);
[email protected]16ee26d2012-03-08 03:34:351289
1290 // This signals to CompleteRequests that this job never ran.
[email protected]1339a2a22012-10-17 08:39:431291 CompleteRequestsWithError(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
[email protected]16ee26d2012-03-08 03:34:351292 }
1293
[email protected]78eac2a2012-03-14 19:09:271294 // Attempts to serve the job from HOSTS. Returns true if succeeded and
1295 // this Job was destroyed.
1296 bool ServeFromHosts() {
1297 DCHECK_GT(num_active_requests(), 0u);
1298 AddressList addr_list;
1299 if (resolver_->ServeFromHosts(key(),
[email protected]3cb676a12012-06-30 15:46:031300 requests_.front()->info(),
[email protected]78eac2a2012-03-14 19:09:271301 &addr_list)) {
1302 // This will destroy the Job.
[email protected]895123222012-10-25 15:21:171303 CompleteRequests(
1304 HostCache::Entry(OK, MakeAddressListForRequest(addr_list)),
1305 base::TimeDelta());
[email protected]78eac2a2012-03-14 19:09:271306 return true;
1307 }
1308 return false;
1309 }
1310
[email protected]b4481b222012-03-16 17:13:111311 const Key key() const {
1312 return key_;
1313 }
1314
1315 bool is_queued() const {
1316 return !handle_.is_null();
1317 }
1318
1319 bool is_running() const {
1320 return is_dns_running() || is_proc_running();
1321 }
1322
[email protected]16ee26d2012-03-08 03:34:351323 private:
[email protected]51b9a6b2012-06-25 21:50:291324 void UpdatePriority() {
1325 if (is_queued()) {
1326 if (priority() != static_cast<RequestPriority>(handle_.priority()))
1327 priority_change_time_ = base::TimeTicks::Now();
1328 handle_ = resolver_->dispatcher_.ChangePriority(handle_, priority());
1329 }
1330 }
1331
[email protected]895123222012-10-25 15:21:171332 AddressList MakeAddressListForRequest(const AddressList& list) const {
1333 if (requests_.empty())
1334 return list;
1335 return AddressList::CopyWithPort(list, requests_.front()->info().port());
1336 }
1337
[email protected]16ee26d2012-03-08 03:34:351338 // PriorityDispatch::Job:
[email protected]0f292de02012-02-01 22:28:201339 virtual void Start() OVERRIDE {
1340 DCHECK(!is_running());
[email protected]b3601bc22012-02-21 21:23:201341 handle_.Reset();
[email protected]0f292de02012-02-01 22:28:201342
[email protected]4da911f2012-06-14 19:45:201343 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_STARTED);
[email protected]0f292de02012-02-01 22:28:201344
[email protected]51b9a6b2012-06-25 21:50:291345 had_dns_config_ = resolver_->HaveDnsConfig();
1346
1347 base::TimeTicks now = base::TimeTicks::Now();
1348 base::TimeDelta queue_time = now - creation_time_;
1349 base::TimeDelta queue_time_after_change = now - priority_change_time_;
1350
1351 if (had_dns_config_) {
1352 DNS_HISTOGRAM_BY_PRIORITY("AsyncDNS.JobQueueTime", priority(),
1353 queue_time);
1354 DNS_HISTOGRAM_BY_PRIORITY("AsyncDNS.JobQueueTimeAfterChange", priority(),
1355 queue_time_after_change);
1356 } else {
1357 DNS_HISTOGRAM_BY_PRIORITY("DNS.JobQueueTime", priority(), queue_time);
1358 DNS_HISTOGRAM_BY_PRIORITY("DNS.JobQueueTimeAfterChange", priority(),
1359 queue_time_after_change);
1360 }
1361
[email protected]1d932852012-06-19 19:40:331362 // Caution: Job::Start must not complete synchronously.
[email protected]51b9a6b2012-06-25 21:50:291363 if (had_dns_config_ && !ResemblesMulticastDNSName(key_.hostname)) {
[email protected]b3601bc22012-02-21 21:23:201364 StartDnsTask();
1365 } else {
1366 StartProcTask();
1367 }
1368 }
1369
[email protected]b3601bc22012-02-21 21:23:201370 // TODO(szym): Since DnsTransaction does not consume threads, we can increase
1371 // the limits on |dispatcher_|. But in order to keep the number of WorkerPool
1372 // threads low, we will need to use an "inner" PrioritizedDispatcher with
1373 // tighter limits.
1374 void StartProcTask() {
[email protected]16ee26d2012-03-08 03:34:351375 DCHECK(!is_dns_running());
[email protected]0f292de02012-02-01 22:28:201376 proc_task_ = new ProcTask(
1377 key_,
1378 resolver_->proc_params_,
[email protected]e3bd4822012-10-23 18:01:371379 base::Bind(&Job::OnProcTaskComplete, base::Unretained(this),
1380 base::TimeTicks::Now()),
[email protected]0f292de02012-02-01 22:28:201381 net_log_);
1382
1383 if (had_non_speculative_request_)
1384 proc_task_->set_had_non_speculative_request();
1385 // Start() could be called from within Resolve(), hence it must NOT directly
1386 // call OnProcTaskComplete, for example, on synchronous failure.
1387 proc_task_->Start();
[email protected]68ad3ee2010-01-30 03:45:391388 }
1389
[email protected]0f292de02012-02-01 22:28:201390 // Called by ProcTask when it completes.
[email protected]e3bd4822012-10-23 18:01:371391 void OnProcTaskComplete(base::TimeTicks start_time,
1392 int net_error,
1393 const AddressList& addr_list) {
[email protected]b3601bc22012-02-21 21:23:201394 DCHECK(is_proc_running());
[email protected]68ad3ee2010-01-30 03:45:391395
[email protected]62e86ba2013-01-29 18:59:161396 if (!resolver_->resolved_known_ipv6_hostname_ &&
1397 net_error == OK &&
1398 key_.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
1399 if (key_.hostname == "www.google.com") {
1400 resolver_->resolved_known_ipv6_hostname_ = true;
1401 bool got_ipv6_address = false;
1402 for (size_t i = 0; i < addr_list.size(); ++i) {
1403 if (addr_list[i].GetFamily() == ADDRESS_FAMILY_IPV6)
1404 got_ipv6_address = true;
1405 }
1406 UMA_HISTOGRAM_BOOLEAN("Net.UnspecResolvedIPv6", got_ipv6_address);
1407 }
1408 }
1409
[email protected]1d932852012-06-19 19:40:331410 if (dns_task_error_ != OK) {
[email protected]e3bd4822012-10-23 18:01:371411 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]1def74c2012-03-22 20:07:001412 if (net_error == OK) {
[email protected]e3bd4822012-10-23 18:01:371413 DNS_HISTOGRAM("AsyncDNS.FallbackSuccess", duration);
[email protected]1d932852012-06-19 19:40:331414 if ((dns_task_error_ == ERR_NAME_NOT_RESOLVED) &&
1415 ResemblesNetBIOSName(key_.hostname)) {
1416 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_SUSPECT_NETBIOS);
1417 } else {
1418 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_PROC_SUCCESS);
1419 }
1420 UMA_HISTOGRAM_CUSTOM_ENUMERATION("AsyncDNS.ResolveError",
1421 std::abs(dns_task_error_),
1422 GetAllErrorCodesForUma());
[email protected]1ffdda82012-12-12 23:04:221423 resolver_->OnDnsTaskResolve(dns_task_error_);
[email protected]1def74c2012-03-22 20:07:001424 } else {
[email protected]e3bd4822012-10-23 18:01:371425 DNS_HISTOGRAM("AsyncDNS.FallbackFail", duration);
[email protected]1def74c2012-03-22 20:07:001426 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
1427 }
1428 }
1429
[email protected]1339a2a22012-10-17 08:39:431430 base::TimeDelta ttl =
1431 base::TimeDelta::FromSeconds(kNegativeCacheEntryTTLSeconds);
[email protected]b3601bc22012-02-21 21:23:201432 if (net_error == OK)
1433 ttl = base::TimeDelta::FromSeconds(kCacheEntryTTLSeconds);
[email protected]68ad3ee2010-01-30 03:45:391434
[email protected]895123222012-10-25 15:21:171435 // Don't store the |ttl| in cache since it's not obtained from the server.
1436 CompleteRequests(
1437 HostCache::Entry(net_error, MakeAddressListForRequest(addr_list)),
1438 ttl);
[email protected]b3601bc22012-02-21 21:23:201439 }
1440
1441 void StartDnsTask() {
[email protected]78eac2a2012-03-14 19:09:271442 DCHECK(resolver_->HaveDnsConfig());
[email protected]16c2bd72013-06-28 01:19:221443 base::TimeTicks start_time = base::TimeTicks::Now();
[email protected]b3601bc22012-02-21 21:23:201444 dns_task_.reset(new DnsTask(
[email protected]0adcb2b2012-08-15 21:30:461445 resolver_->dns_client_.get(),
[email protected]b3601bc22012-02-21 21:23:201446 key_,
[email protected]16c2bd72013-06-28 01:19:221447 base::Bind(&Job::OnDnsTaskComplete, base::Unretained(this), start_time),
[email protected]b3601bc22012-02-21 21:23:201448 net_log_));
1449
[email protected]a210eef92013-07-19 19:06:121450 dns_task_->Start();
[email protected]16c2bd72013-06-28 01:19:221451 }
1452
1453 // Called if DnsTask fails. It is posted from StartDnsTask, so Job may be
1454 // deleted before this callback. In this case dns_task is deleted as well,
1455 // so we use it as indicator whether Job is still valid.
1456 void OnDnsTaskFailure(const base::WeakPtr<DnsTask>& dns_task,
1457 base::TimeDelta duration,
1458 int net_error) {
1459 DNS_HISTOGRAM("AsyncDNS.ResolveFail", duration);
1460
1461 if (dns_task == NULL)
1462 return;
1463
1464 dns_task_error_ = net_error;
1465
1466 // TODO(szym): Run ServeFromHosts now if nsswitch.conf says so.
1467 // http://crbug.com/117655
1468
1469 // TODO(szym): Some net errors indicate lack of connectivity. Starting
1470 // ProcTask in that case is a waste of time.
1471 if (resolver_->fallback_to_proctask_) {
1472 dns_task_.reset();
1473 StartProcTask();
1474 } else {
1475 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
1476 CompleteRequestsWithError(net_error);
[email protected]b3601bc22012-02-21 21:23:201477 }
1478 }
1479
1480 // Called by DnsTask when it completes.
[email protected]e3bd4822012-10-23 18:01:371481 void OnDnsTaskComplete(base::TimeTicks start_time,
1482 int net_error,
[email protected]b3601bc22012-02-21 21:23:201483 const AddressList& addr_list,
1484 base::TimeDelta ttl) {
1485 DCHECK(is_dns_running());
[email protected]b3601bc22012-02-21 21:23:201486
[email protected]e3bd4822012-10-23 18:01:371487 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]b3601bc22012-02-21 21:23:201488 if (net_error != OK) {
[email protected]16c2bd72013-06-28 01:19:221489 OnDnsTaskFailure(dns_task_->AsWeakPtr(), duration, net_error);
[email protected]b3601bc22012-02-21 21:23:201490 return;
1491 }
[email protected]e3bd4822012-10-23 18:01:371492 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess", duration);
[email protected]02cd6982013-01-10 20:12:511493 // Log DNS lookups based on |address_family|.
1494 switch(key_.address_family) {
1495 case ADDRESS_FAMILY_IPV4:
1496 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_IPV4", duration);
1497 break;
1498 case ADDRESS_FAMILY_IPV6:
1499 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_IPV6", duration);
1500 break;
1501 case ADDRESS_FAMILY_UNSPECIFIED:
1502 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_UNSPEC", duration);
1503 break;
1504 }
[email protected]b3601bc22012-02-21 21:23:201505
[email protected]1def74c2012-03-22 20:07:001506 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_DNS_SUCCESS);
[email protected]1339a2a22012-10-17 08:39:431507 RecordTTL(ttl);
[email protected]0adcb2b2012-08-15 21:30:461508
[email protected]1ffdda82012-12-12 23:04:221509 resolver_->OnDnsTaskResolve(OK);
[email protected]f0f602bd2012-11-15 18:01:021510
[email protected]895123222012-10-25 15:21:171511 base::TimeDelta bounded_ttl =
1512 std::max(ttl, base::TimeDelta::FromSeconds(kMinimumTTLSeconds));
1513
1514 CompleteRequests(
1515 HostCache::Entry(net_error, MakeAddressListForRequest(addr_list), ttl),
1516 bounded_ttl);
[email protected]b3601bc22012-02-21 21:23:201517 }
1518
[email protected]16ee26d2012-03-08 03:34:351519 // Performs Job's last rites. Completes all Requests. Deletes this.
[email protected]895123222012-10-25 15:21:171520 void CompleteRequests(const HostCache::Entry& entry,
1521 base::TimeDelta ttl) {
[email protected]11fbca0b2013-06-02 23:37:211522 CHECK(resolver_.get());
[email protected]b3601bc22012-02-21 21:23:201523
[email protected]16ee26d2012-03-08 03:34:351524 // This job must be removed from resolver's |jobs_| now to make room for a
1525 // new job with the same key in case one of the OnComplete callbacks decides
1526 // to spawn one. Consequently, the job deletes itself when CompleteRequests
1527 // is done.
1528 scoped_ptr<Job> self_deleter(this);
1529
1530 resolver_->RemoveJob(this);
1531
[email protected]16ee26d2012-03-08 03:34:351532 if (is_running()) {
1533 DCHECK(!is_queued());
1534 if (is_proc_running()) {
1535 proc_task_->Cancel();
1536 proc_task_ = NULL;
1537 }
1538 dns_task_.reset();
1539
1540 // Signal dispatcher that a slot has opened.
1541 resolver_->dispatcher_.OnJobFinished();
1542 } else if (is_queued()) {
1543 resolver_->dispatcher_.Cancel(handle_);
1544 handle_.Reset();
1545 }
1546
1547 if (num_active_requests() == 0) {
[email protected]4da911f2012-06-14 19:45:201548 net_log_.AddEvent(NetLog::TYPE_CANCELLED);
[email protected]16ee26d2012-03-08 03:34:351549 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
1550 OK);
1551 return;
1552 }
[email protected]b3601bc22012-02-21 21:23:201553
1554 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
[email protected]895123222012-10-25 15:21:171555 entry.error);
[email protected]68ad3ee2010-01-30 03:45:391556
[email protected]78eac2a2012-03-14 19:09:271557 DCHECK(!requests_.empty());
1558
[email protected]895123222012-10-25 15:21:171559 if (entry.error == OK) {
[email protected]d7b9a2b2012-05-31 22:31:191560 // Record this histogram here, when we know the system has a valid DNS
1561 // configuration.
[email protected]539df6c2012-06-19 21:21:291562 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.HaveDnsConfig",
1563 resolver_->received_dns_config_);
[email protected]d7b9a2b2012-05-31 22:31:191564 }
[email protected]16ee26d2012-03-08 03:34:351565
[email protected]7af985a2012-12-14 22:40:421566 bool did_complete = (entry.error != ERR_NETWORK_CHANGED) &&
[email protected]895123222012-10-25 15:21:171567 (entry.error != ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
1568 if (did_complete)
[email protected]1339a2a22012-10-17 08:39:431569 resolver_->CacheResult(key_, entry, ttl);
[email protected]16ee26d2012-03-08 03:34:351570
[email protected]0f292de02012-02-01 22:28:201571 // Complete all of the requests that were attached to the job.
1572 for (RequestsList::const_iterator it = requests_.begin();
1573 it != requests_.end(); ++it) {
1574 Request* req = *it;
1575
1576 if (req->was_canceled())
1577 continue;
1578
1579 DCHECK_EQ(this, req->job());
1580 // Update the net log and notify registered observers.
1581 LogFinishRequest(req->source_net_log(), req->request_net_log(),
[email protected]895123222012-10-25 15:21:171582 req->info(), entry.error);
[email protected]51b9a6b2012-06-25 21:50:291583 if (did_complete) {
1584 // Record effective total time from creation to completion.
1585 RecordTotalTime(had_dns_config_, req->info().is_speculative(),
1586 base::TimeTicks::Now() - req->request_time());
1587 }
[email protected]895123222012-10-25 15:21:171588 req->OnComplete(entry.error, entry.addrlist);
[email protected]0f292de02012-02-01 22:28:201589
1590 // Check if the resolver was destroyed as a result of running the
1591 // callback. If it was, we could continue, but we choose to bail.
[email protected]11fbca0b2013-06-02 23:37:211592 if (!resolver_.get())
[email protected]0f292de02012-02-01 22:28:201593 return;
1594 }
1595 }
1596
[email protected]1339a2a22012-10-17 08:39:431597 // Convenience wrapper for CompleteRequests in case of failure.
1598 void CompleteRequestsWithError(int net_error) {
[email protected]895123222012-10-25 15:21:171599 CompleteRequests(HostCache::Entry(net_error, AddressList()),
1600 base::TimeDelta());
[email protected]1339a2a22012-10-17 08:39:431601 }
1602
[email protected]b4481b222012-03-16 17:13:111603 RequestPriority priority() const {
1604 return priority_tracker_.highest_priority();
1605 }
1606
1607 // Number of non-canceled requests in |requests_|.
1608 size_t num_active_requests() const {
1609 return priority_tracker_.total_count();
1610 }
1611
1612 bool is_dns_running() const {
1613 return dns_task_.get() != NULL;
1614 }
1615
1616 bool is_proc_running() const {
1617 return proc_task_.get() != NULL;
1618 }
1619
[email protected]0f292de02012-02-01 22:28:201620 base::WeakPtr<HostResolverImpl> resolver_;
1621
1622 Key key_;
1623
1624 // Tracks the highest priority across |requests_|.
1625 PriorityTracker priority_tracker_;
1626
1627 bool had_non_speculative_request_;
1628
[email protected]51b9a6b2012-06-25 21:50:291629 // Distinguishes measurements taken while DnsClient was fully configured.
1630 bool had_dns_config_;
1631
[email protected]1d932852012-06-19 19:40:331632 // Result of DnsTask.
1633 int dns_task_error_;
[email protected]1def74c2012-03-22 20:07:001634
[email protected]51b9a6b2012-06-25 21:50:291635 const base::TimeTicks creation_time_;
1636 base::TimeTicks priority_change_time_;
1637
[email protected]0f292de02012-02-01 22:28:201638 BoundNetLog net_log_;
1639
[email protected]b3601bc22012-02-21 21:23:201640 // Resolves the host using a HostResolverProc.
[email protected]0f292de02012-02-01 22:28:201641 scoped_refptr<ProcTask> proc_task_;
1642
[email protected]b3601bc22012-02-21 21:23:201643 // Resolves the host using a DnsTransaction.
1644 scoped_ptr<DnsTask> dns_task_;
1645
[email protected]0f292de02012-02-01 22:28:201646 // All Requests waiting for the result of this Job. Some can be canceled.
1647 RequestsList requests_;
1648
[email protected]16ee26d2012-03-08 03:34:351649 // A handle used in |HostResolverImpl::dispatcher_|.
[email protected]0f292de02012-02-01 22:28:201650 PrioritizedDispatcher::Handle handle_;
[email protected]68ad3ee2010-01-30 03:45:391651};
1652
1653//-----------------------------------------------------------------------------
1654
[email protected]0f292de02012-02-01 22:28:201655HostResolverImpl::ProcTaskParams::ProcTaskParams(
[email protected]e95d3aca2010-01-11 22:47:431656 HostResolverProc* resolver_proc,
[email protected]0f292de02012-02-01 22:28:201657 size_t max_retry_attempts)
1658 : resolver_proc(resolver_proc),
1659 max_retry_attempts(max_retry_attempts),
1660 unresponsive_delay(base::TimeDelta::FromMilliseconds(6000)),
1661 retry_factor(2) {
1662}
1663
1664HostResolverImpl::ProcTaskParams::~ProcTaskParams() {}
1665
1666HostResolverImpl::HostResolverImpl(
[email protected]c54a8912012-10-22 22:09:431667 scoped_ptr<HostCache> cache,
[email protected]0f292de02012-02-01 22:28:201668 const PrioritizedDispatcher::Limits& job_limits,
1669 const ProcTaskParams& proc_params,
[email protected]ee094b82010-08-24 15:55:511670 NetLog* net_log)
[email protected]c54a8912012-10-22 22:09:431671 : cache_(cache.Pass()),
[email protected]0f292de02012-02-01 22:28:201672 dispatcher_(job_limits),
1673 max_queued_jobs_(job_limits.total_jobs * 100u),
1674 proc_params_(proc_params),
[email protected]62e86ba2013-01-29 18:59:161675 net_log_(net_log),
[email protected]0c7798452009-10-26 17:59:511676 default_address_family_(ADDRESS_FAMILY_UNSPECIFIED),
[email protected]4589a3a2012-09-20 20:57:071677 weak_ptr_factory_(this),
[email protected]12faa4c2012-11-06 04:44:181678 probe_weak_ptr_factory_(this),
[email protected]d7b9a2b2012-05-31 22:31:191679 received_dns_config_(false),
[email protected]f0f602bd2012-11-15 18:01:021680 num_dns_failures_(0),
[email protected]23330db72013-07-18 03:32:111681 probe_ipv6_support_(true),
[email protected]62e86ba2013-01-29 18:59:161682 resolved_known_ipv6_hostname_(false),
[email protected]16c2bd72013-06-28 01:19:221683 additional_resolver_flags_(0),
1684 fallback_to_proctask_(true) {
[email protected]0f292de02012-02-01 22:28:201685
1686 DCHECK_GE(dispatcher_.num_priorities(), static_cast<size_t>(NUM_PRIORITIES));
[email protected]68ad3ee2010-01-30 03:45:391687
[email protected]06ef6d92011-05-19 04:24:581688 // Maximum of 4 retry attempts for host resolution.
1689 static const size_t kDefaultMaxRetryAttempts = 4u;
1690
[email protected]0f292de02012-02-01 22:28:201691 if (proc_params_.max_retry_attempts == HostResolver::kDefaultRetryAttempts)
1692 proc_params_.max_retry_attempts = kDefaultMaxRetryAttempts;
[email protected]68ad3ee2010-01-30 03:45:391693
[email protected]b59ff372009-07-15 22:04:321694#if defined(OS_WIN)
1695 EnsureWinsockInit();
1696#endif
[email protected]7c466e92013-07-20 01:44:481697#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
[email protected]12faa4c2012-11-06 04:44:181698 new LoopbackProbeJob(weak_ptr_factory_.GetWeakPtr());
[email protected]2f3bc65c2010-07-23 17:47:101699#endif
[email protected]232a5812011-03-04 22:42:081700 NetworkChangeNotifier::AddIPAddressObserver(this);
[email protected]bb0e34542012-08-31 19:52:401701 NetworkChangeNotifier::AddDNSObserver(this);
[email protected]d7b9a2b2012-05-31 22:31:191702#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD) && \
1703 !defined(OS_ANDROID)
[email protected]d7b9a2b2012-05-31 22:31:191704 EnsureDnsReloaderInit();
[email protected]46018c9d2011-09-06 03:42:341705#endif
[email protected]2ac22db2012-11-28 19:50:041706
1707 // TODO(szym): Remove when received_dns_config_ is removed, once
1708 // http://crbug.com/137914 is resolved.
1709 {
1710 DnsConfig dns_config;
1711 NetworkChangeNotifier::GetDnsConfig(&dns_config);
1712 received_dns_config_ = dns_config.IsValid();
1713 }
[email protected]16c2bd72013-06-28 01:19:221714
1715 fallback_to_proctask_ = !ConfigureAsyncDnsNoFallbackFieldTrial();
[email protected]b59ff372009-07-15 22:04:321716}
1717
1718HostResolverImpl::~HostResolverImpl() {
[email protected]0f292de02012-02-01 22:28:201719 // This will also cancel all outstanding requests.
1720 STLDeleteValues(&jobs_);
[email protected]e95d3aca2010-01-11 22:47:431721
[email protected]232a5812011-03-04 22:42:081722 NetworkChangeNotifier::RemoveIPAddressObserver(this);
[email protected]bb0e34542012-08-31 19:52:401723 NetworkChangeNotifier::RemoveDNSObserver(this);
[email protected]b59ff372009-07-15 22:04:321724}
1725
[email protected]0f292de02012-02-01 22:28:201726void HostResolverImpl::SetMaxQueuedJobs(size_t value) {
1727 DCHECK_EQ(0u, dispatcher_.num_queued_jobs());
1728 DCHECK_GT(value, 0u);
1729 max_queued_jobs_ = value;
[email protected]be1a48b2011-01-20 00:12:131730}
1731
[email protected]684970b2009-08-14 04:54:461732int HostResolverImpl::Resolve(const RequestInfo& info,
[email protected]b59ff372009-07-15 22:04:321733 AddressList* addresses,
[email protected]aa22b242011-11-16 18:58:291734 const CompletionCallback& callback,
[email protected]684970b2009-08-14 04:54:461735 RequestHandle* out_req,
[email protected]ee094b82010-08-24 15:55:511736 const BoundNetLog& source_net_log) {
[email protected]95a214c2011-08-04 21:50:401737 DCHECK(addresses);
[email protected]1ac6af92010-06-03 21:00:141738 DCHECK(CalledOnValidThread());
[email protected]aa22b242011-11-16 18:58:291739 DCHECK_EQ(false, callback.is_null());
[email protected]1ac6af92010-06-03 21:00:141740
[email protected]e806cd72013-05-17 02:08:431741 // Check that the caller supplied a valid hostname to resolve.
1742 std::string labeled_hostname;
1743 if (!DNSDomainFromDot(info.hostname(), &labeled_hostname))
1744 return ERR_NAME_NOT_RESOLVED;
1745
[email protected]ee094b82010-08-24 15:55:511746 // Make a log item for the request.
1747 BoundNetLog request_net_log = BoundNetLog::Make(net_log_,
1748 NetLog::SOURCE_HOST_RESOLVER_IMPL_REQUEST);
1749
[email protected]0f292de02012-02-01 22:28:201750 LogStartRequest(source_net_log, request_net_log, info);
[email protected]b59ff372009-07-15 22:04:321751
[email protected]123ab1e32009-10-21 19:12:571752 // Build a key that identifies the request in the cache and in the
1753 // outstanding jobs map.
[email protected]2b74a2f2013-07-23 19:37:381754 Key key = GetEffectiveKeyForRequest(info, request_net_log);
[email protected]123ab1e32009-10-21 19:12:571755
[email protected]287d7c22011-11-15 17:34:251756 int rv = ResolveHelper(key, info, addresses, request_net_log);
[email protected]95a214c2011-08-04 21:50:401757 if (rv != ERR_DNS_CACHE_MISS) {
[email protected]b3601bc22012-02-21 21:23:201758 LogFinishRequest(source_net_log, request_net_log, info, rv);
[email protected]51b9a6b2012-06-25 21:50:291759 RecordTotalTime(HaveDnsConfig(), info.is_speculative(), base::TimeDelta());
[email protected]95a214c2011-08-04 21:50:401760 return rv;
[email protected]38368712011-03-02 08:09:401761 }
1762
[email protected]0f292de02012-02-01 22:28:201763 // Next we need to attach our request to a "job". This job is responsible for
1764 // calling "getaddrinfo(hostname)" on a worker thread.
1765
1766 JobMap::iterator jobit = jobs_.find(key);
1767 Job* job;
1768 if (jobit == jobs_.end()) {
[email protected]12faa4c2012-11-06 04:44:181769 job = new Job(weak_ptr_factory_.GetWeakPtr(), key, info.priority(),
1770 request_net_log);
[email protected]8c98d002012-07-18 19:02:271771 job->Schedule();
[email protected]0f292de02012-02-01 22:28:201772
1773 // Check for queue overflow.
1774 if (dispatcher_.num_queued_jobs() > max_queued_jobs_) {
1775 Job* evicted = static_cast<Job*>(dispatcher_.EvictOldestLowest());
1776 DCHECK(evicted);
[email protected]16ee26d2012-03-08 03:34:351777 evicted->OnEvicted(); // Deletes |evicted|.
[email protected]0f292de02012-02-01 22:28:201778 if (evicted == job) {
[email protected]0f292de02012-02-01 22:28:201779 rv = ERR_HOST_RESOLVER_QUEUE_TOO_LARGE;
[email protected]b3601bc22012-02-21 21:23:201780 LogFinishRequest(source_net_log, request_net_log, info, rv);
[email protected]0f292de02012-02-01 22:28:201781 return rv;
1782 }
[email protected]0f292de02012-02-01 22:28:201783 }
[email protected]0f292de02012-02-01 22:28:201784 jobs_.insert(jobit, std::make_pair(key, job));
1785 } else {
1786 job = jobit->second;
1787 }
1788
1789 // Can't complete synchronously. Create and attach request.
[email protected]b3601bc22012-02-21 21:23:201790 scoped_ptr<Request> req(new Request(source_net_log,
1791 request_net_log,
1792 info,
1793 callback,
1794 addresses));
[email protected]b59ff372009-07-15 22:04:321795 if (out_req)
[email protected]b3601bc22012-02-21 21:23:201796 *out_req = reinterpret_cast<RequestHandle>(req.get());
[email protected]b59ff372009-07-15 22:04:321797
[email protected]b3601bc22012-02-21 21:23:201798 job->AddRequest(req.Pass());
[email protected]0f292de02012-02-01 22:28:201799 // Completion happens during Job::CompleteRequests().
[email protected]b59ff372009-07-15 22:04:321800 return ERR_IO_PENDING;
1801}
1802
[email protected]287d7c22011-11-15 17:34:251803int HostResolverImpl::ResolveHelper(const Key& key,
[email protected]95a214c2011-08-04 21:50:401804 const RequestInfo& info,
1805 AddressList* addresses,
[email protected]20cd5332011-10-12 22:38:001806 const BoundNetLog& request_net_log) {
[email protected]95a214c2011-08-04 21:50:401807 // The result of |getaddrinfo| for empty hosts is inconsistent across systems.
1808 // On Windows it gives the default interface's address, whereas on Linux it
1809 // gives an error. We will make it fail on all platforms for consistency.
1810 if (info.hostname().empty() || info.hostname().size() > kMaxHostLength)
1811 return ERR_NAME_NOT_RESOLVED;
1812
1813 int net_error = ERR_UNEXPECTED;
1814 if (ResolveAsIP(key, info, &net_error, addresses))
1815 return net_error;
[email protected]78eac2a2012-03-14 19:09:271816 if (ServeFromCache(key, info, &net_error, addresses)) {
[email protected]4da911f2012-06-14 19:45:201817 request_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_CACHE_HIT);
[email protected]78eac2a2012-03-14 19:09:271818 return net_error;
1819 }
1820 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
1821 // http://crbug.com/117655
1822 if (ServeFromHosts(key, info, addresses)) {
[email protected]4da911f2012-06-14 19:45:201823 request_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_HOSTS_HIT);
[email protected]78eac2a2012-03-14 19:09:271824 return OK;
1825 }
1826 return ERR_DNS_CACHE_MISS;
[email protected]95a214c2011-08-04 21:50:401827}
1828
1829int HostResolverImpl::ResolveFromCache(const RequestInfo& info,
1830 AddressList* addresses,
1831 const BoundNetLog& source_net_log) {
1832 DCHECK(CalledOnValidThread());
1833 DCHECK(addresses);
1834
[email protected]95a214c2011-08-04 21:50:401835 // Make a log item for the request.
1836 BoundNetLog request_net_log = BoundNetLog::Make(net_log_,
1837 NetLog::SOURCE_HOST_RESOLVER_IMPL_REQUEST);
1838
1839 // Update the net log and notify registered observers.
[email protected]0f292de02012-02-01 22:28:201840 LogStartRequest(source_net_log, request_net_log, info);
[email protected]95a214c2011-08-04 21:50:401841
[email protected]2b74a2f2013-07-23 19:37:381842 Key key = GetEffectiveKeyForRequest(info, request_net_log);
[email protected]95a214c2011-08-04 21:50:401843
[email protected]287d7c22011-11-15 17:34:251844 int rv = ResolveHelper(key, info, addresses, request_net_log);
[email protected]b3601bc22012-02-21 21:23:201845 LogFinishRequest(source_net_log, request_net_log, info, rv);
[email protected]95a214c2011-08-04 21:50:401846 return rv;
1847}
1848
[email protected]b59ff372009-07-15 22:04:321849void HostResolverImpl::CancelRequest(RequestHandle req_handle) {
[email protected]1ac6af92010-06-03 21:00:141850 DCHECK(CalledOnValidThread());
[email protected]b59ff372009-07-15 22:04:321851 Request* req = reinterpret_cast<Request*>(req_handle);
1852 DCHECK(req);
[email protected]0f292de02012-02-01 22:28:201853 Job* job = req->job();
1854 DCHECK(job);
[email protected]0f292de02012-02-01 22:28:201855 job->CancelRequest(req);
[email protected]b59ff372009-07-15 22:04:321856}
1857
[email protected]0f8f1b432010-03-16 19:06:031858void HostResolverImpl::SetDefaultAddressFamily(AddressFamily address_family) {
[email protected]1ac6af92010-06-03 21:00:141859 DCHECK(CalledOnValidThread());
[email protected]0f8f1b432010-03-16 19:06:031860 default_address_family_ = address_family;
[email protected]23330db72013-07-18 03:32:111861 probe_ipv6_support_ = false;
[email protected]0f8f1b432010-03-16 19:06:031862}
1863
[email protected]f7d310e2010-10-07 16:25:111864AddressFamily HostResolverImpl::GetDefaultAddressFamily() const {
1865 return default_address_family_;
1866}
1867
[email protected]a8883e452012-11-17 05:58:061868void HostResolverImpl::SetDnsClientEnabled(bool enabled) {
1869 DCHECK(CalledOnValidThread());
1870#if defined(ENABLE_BUILT_IN_DNS)
1871 if (enabled && !dns_client_) {
1872 SetDnsClient(DnsClient::CreateClient(net_log_));
1873 } else if (!enabled && dns_client_) {
1874 SetDnsClient(scoped_ptr<DnsClient>());
1875 }
1876#endif
1877}
1878
[email protected]489d1a82011-10-12 03:09:111879HostCache* HostResolverImpl::GetHostCache() {
1880 return cache_.get();
1881}
[email protected]95a214c2011-08-04 21:50:401882
[email protected]17e92032012-03-29 00:56:241883base::Value* HostResolverImpl::GetDnsConfigAsValue() const {
1884 // Check if async DNS is disabled.
1885 if (!dns_client_.get())
1886 return NULL;
1887
1888 // Check if async DNS is enabled, but we currently have no configuration
1889 // for it.
1890 const DnsConfig* dns_config = dns_client_->GetConfig();
1891 if (dns_config == NULL)
[email protected]ea5ef4c2013-06-13 22:50:271892 return new base::DictionaryValue();
[email protected]17e92032012-03-29 00:56:241893
1894 return dns_config->ToValue();
1895}
1896
[email protected]95a214c2011-08-04 21:50:401897bool HostResolverImpl::ResolveAsIP(const Key& key,
1898 const RequestInfo& info,
1899 int* net_error,
1900 AddressList* addresses) {
1901 DCHECK(addresses);
1902 DCHECK(net_error);
1903 IPAddressNumber ip_number;
1904 if (!ParseIPLiteralToNumber(key.hostname, &ip_number))
1905 return false;
1906
1907 DCHECK_EQ(key.host_resolver_flags &
1908 ~(HOST_RESOLVER_CANONNAME | HOST_RESOLVER_LOOPBACK_ONLY |
1909 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6),
1910 0) << " Unhandled flag";
[email protected]0f292de02012-02-01 22:28:201911 bool ipv6_disabled = (default_address_family_ == ADDRESS_FAMILY_IPV4) &&
[email protected]23330db72013-07-18 03:32:111912 !probe_ipv6_support_;
[email protected]95a214c2011-08-04 21:50:401913 *net_error = OK;
[email protected]0f292de02012-02-01 22:28:201914 if ((ip_number.size() == kIPv6AddressSize) && ipv6_disabled) {
[email protected]95a214c2011-08-04 21:50:401915 *net_error = ERR_NAME_NOT_RESOLVED;
1916 } else {
[email protected]7054e78f2012-05-07 21:44:561917 *addresses = AddressList::CreateFromIPAddress(ip_number, info.port());
1918 if (key.host_resolver_flags & HOST_RESOLVER_CANONNAME)
1919 addresses->SetDefaultCanonicalName();
[email protected]95a214c2011-08-04 21:50:401920 }
1921 return true;
1922}
1923
1924bool HostResolverImpl::ServeFromCache(const Key& key,
1925 const RequestInfo& info,
[email protected]95a214c2011-08-04 21:50:401926 int* net_error,
1927 AddressList* addresses) {
1928 DCHECK(addresses);
1929 DCHECK(net_error);
1930 if (!info.allow_cached_response() || !cache_.get())
1931 return false;
1932
[email protected]407a30ab2012-08-15 17:16:101933 const HostCache::Entry* cache_entry = cache_->Lookup(
1934 key, base::TimeTicks::Now());
[email protected]95a214c2011-08-04 21:50:401935 if (!cache_entry)
1936 return false;
1937
[email protected]95a214c2011-08-04 21:50:401938 *net_error = cache_entry->error;
[email protected]7054e78f2012-05-07 21:44:561939 if (*net_error == OK) {
[email protected]1339a2a22012-10-17 08:39:431940 if (cache_entry->has_ttl())
1941 RecordTTL(cache_entry->ttl);
[email protected]895123222012-10-25 15:21:171942 *addresses = EnsurePortOnAddressList(cache_entry->addrlist, info.port());
[email protected]7054e78f2012-05-07 21:44:561943 }
[email protected]95a214c2011-08-04 21:50:401944 return true;
1945}
1946
[email protected]78eac2a2012-03-14 19:09:271947bool HostResolverImpl::ServeFromHosts(const Key& key,
1948 const RequestInfo& info,
1949 AddressList* addresses) {
1950 DCHECK(addresses);
1951 if (!HaveDnsConfig())
1952 return false;
[email protected]05a79d42013-03-28 07:30:091953 addresses->clear();
1954
[email protected]cb507622012-03-23 16:17:061955 // HOSTS lookups are case-insensitive.
1956 std::string hostname = StringToLowerASCII(key.hostname);
1957
[email protected]05a79d42013-03-28 07:30:091958 const DnsHosts& hosts = dns_client_->GetConfig()->hosts;
1959
[email protected]78eac2a2012-03-14 19:09:271960 // If |address_family| is ADDRESS_FAMILY_UNSPECIFIED other implementations
1961 // (glibc and c-ares) return the first matching line. We have more
1962 // flexibility, but lose implicit ordering.
[email protected]05a79d42013-03-28 07:30:091963 // We prefer IPv6 because "happy eyeballs" will fall back to IPv4 if
1964 // necessary.
1965 if (key.address_family == ADDRESS_FAMILY_IPV6 ||
1966 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
1967 DnsHosts::const_iterator it = hosts.find(
1968 DnsHostsKey(hostname, ADDRESS_FAMILY_IPV6));
1969 if (it != hosts.end())
1970 addresses->push_back(IPEndPoint(it->second, info.port()));
[email protected]78eac2a2012-03-14 19:09:271971 }
1972
[email protected]05a79d42013-03-28 07:30:091973 if (key.address_family == ADDRESS_FAMILY_IPV4 ||
1974 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
1975 DnsHosts::const_iterator it = hosts.find(
1976 DnsHostsKey(hostname, ADDRESS_FAMILY_IPV4));
1977 if (it != hosts.end())
1978 addresses->push_back(IPEndPoint(it->second, info.port()));
1979 }
1980
[email protected]ec666ab22013-04-17 20:05:591981 // If got only loopback addresses and the family was restricted, resolve
1982 // again, without restrictions. See SystemHostResolverCall for rationale.
1983 if ((key.host_resolver_flags &
1984 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6) &&
1985 IsAllIPv4Loopback(*addresses)) {
1986 Key new_key(key);
1987 new_key.address_family = ADDRESS_FAMILY_UNSPECIFIED;
1988 new_key.host_resolver_flags &=
1989 ~HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
1990 return ServeFromHosts(new_key, info, addresses);
1991 }
[email protected]05a79d42013-03-28 07:30:091992 return !addresses->empty();
[email protected]78eac2a2012-03-14 19:09:271993}
1994
[email protected]16ee26d2012-03-08 03:34:351995void HostResolverImpl::CacheResult(const Key& key,
[email protected]1339a2a22012-10-17 08:39:431996 const HostCache::Entry& entry,
[email protected]16ee26d2012-03-08 03:34:351997 base::TimeDelta ttl) {
1998 if (cache_.get())
[email protected]1339a2a22012-10-17 08:39:431999 cache_->Set(key, entry, base::TimeTicks::Now(), ttl);
[email protected]ef4c40c2010-09-01 14:42:032000}
2001
[email protected]0f292de02012-02-01 22:28:202002void HostResolverImpl::RemoveJob(Job* job) {
2003 DCHECK(job);
[email protected]16ee26d2012-03-08 03:34:352004 JobMap::iterator it = jobs_.find(job->key());
2005 if (it != jobs_.end() && it->second == job)
2006 jobs_.erase(it);
[email protected]b59ff372009-07-15 22:04:322007}
2008
[email protected]9936a7862012-10-26 04:44:022009void HostResolverImpl::SetHaveOnlyLoopbackAddresses(bool result) {
2010 if (result) {
2011 additional_resolver_flags_ |= HOST_RESOLVER_LOOPBACK_ONLY;
2012 } else {
2013 additional_resolver_flags_ &= ~HOST_RESOLVER_LOOPBACK_ONLY;
2014 }
2015}
2016
[email protected]137af622010-02-05 02:14:352017HostResolverImpl::Key HostResolverImpl::GetEffectiveKeyForRequest(
[email protected]2b74a2f2013-07-23 19:37:382018 const RequestInfo& info, const BoundNetLog& net_log) const {
[email protected]eaf3a3b2010-09-03 20:34:272019 HostResolverFlags effective_flags =
2020 info.host_resolver_flags() | additional_resolver_flags_;
[email protected]137af622010-02-05 02:14:352021 AddressFamily effective_address_family = info.address_family();
[email protected]9db6f702013-04-10 18:10:512022
2023 if (info.address_family() == ADDRESS_FAMILY_UNSPECIFIED) {
[email protected]23330db72013-07-18 03:32:112024 if (probe_ipv6_support_) {
[email protected]ac0b52e2013-04-21 01:26:162025 base::TimeTicks start_time = base::TimeTicks::Now();
2026 // Google DNS address.
2027 const uint8 kIPv6Address[] =
2028 { 0x20, 0x01, 0x48, 0x60, 0x48, 0x60, 0x00, 0x00,
2029 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x88 };
2030 IPAddressNumber address(kIPv6Address,
2031 kIPv6Address + arraysize(kIPv6Address));
[email protected]2b74a2f2013-07-23 19:37:382032 bool rv6 = IsGloballyReachable(address, net_log);
2033 if (rv6)
2034 net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_IPV6_SUPPORTED);
[email protected]9db6f702013-04-10 18:10:512035
[email protected]ac0b52e2013-04-21 01:26:162036 UMA_HISTOGRAM_TIMES("Net.IPv6ConnectDuration",
2037 base::TimeTicks::Now() - start_time);
2038 if (rv6) {
2039 UMA_HISTOGRAM_BOOLEAN("Net.IPv6ConnectSuccessMatch",
2040 default_address_family_ == ADDRESS_FAMILY_UNSPECIFIED);
2041 } else {
2042 UMA_HISTOGRAM_BOOLEAN("Net.IPv6ConnectFailureMatch",
2043 default_address_family_ != ADDRESS_FAMILY_UNSPECIFIED);
2044
2045 effective_address_family = ADDRESS_FAMILY_IPV4;
2046 effective_flags |= HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
2047 }
[email protected]9db6f702013-04-10 18:10:512048 } else {
[email protected]ac0b52e2013-04-21 01:26:162049 effective_address_family = default_address_family_;
[email protected]9db6f702013-04-10 18:10:512050 }
2051 }
2052
[email protected]eaf3a3b2010-09-03 20:34:272053 return Key(info.hostname(), effective_address_family, effective_flags);
[email protected]137af622010-02-05 02:14:352054}
2055
[email protected]35ddc282010-09-21 23:42:062056void HostResolverImpl::AbortAllInProgressJobs() {
[email protected]b3601bc22012-02-21 21:23:202057 // In Abort, a Request callback could spawn new Jobs with matching keys, so
2058 // first collect and remove all running jobs from |jobs_|.
[email protected]c143d892012-04-06 07:56:542059 ScopedVector<Job> jobs_to_abort;
[email protected]0f292de02012-02-01 22:28:202060 for (JobMap::iterator it = jobs_.begin(); it != jobs_.end(); ) {
2061 Job* job = it->second;
[email protected]0f292de02012-02-01 22:28:202062 if (job->is_running()) {
[email protected]b3601bc22012-02-21 21:23:202063 jobs_to_abort.push_back(job);
2064 jobs_.erase(it++);
[email protected]0f292de02012-02-01 22:28:202065 } else {
[email protected]b3601bc22012-02-21 21:23:202066 DCHECK(job->is_queued());
2067 ++it;
[email protected]0f292de02012-02-01 22:28:202068 }
[email protected]ef4c40c2010-09-01 14:42:032069 }
[email protected]b3601bc22012-02-21 21:23:202070
[email protected]57a48d32012-03-03 00:04:552071 // Check if no dispatcher slots leaked out.
2072 DCHECK_EQ(dispatcher_.num_running_jobs(), jobs_to_abort.size());
2073
2074 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072075 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]57a48d32012-03-03 00:04:552076
[email protected]16ee26d2012-03-08 03:34:352077 // Then Abort them.
[email protected]11fbca0b2013-06-02 23:37:212078 for (size_t i = 0; self.get() && i < jobs_to_abort.size(); ++i) {
[email protected]57a48d32012-03-03 00:04:552079 jobs_to_abort[i]->Abort();
[email protected]c143d892012-04-06 07:56:542080 jobs_to_abort[i] = NULL;
[email protected]b3601bc22012-02-21 21:23:202081 }
[email protected]ef4c40c2010-09-01 14:42:032082}
2083
[email protected]78eac2a2012-03-14 19:09:272084void HostResolverImpl::TryServingAllJobsFromHosts() {
2085 if (!HaveDnsConfig())
2086 return;
2087
2088 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2089 // http://crbug.com/117655
2090
2091 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072092 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]78eac2a2012-03-14 19:09:272093
[email protected]11fbca0b2013-06-02 23:37:212094 for (JobMap::iterator it = jobs_.begin(); self.get() && it != jobs_.end();) {
[email protected]78eac2a2012-03-14 19:09:272095 Job* job = it->second;
2096 ++it;
2097 // This could remove |job| from |jobs_|, but iterator will remain valid.
2098 job->ServeFromHosts();
2099 }
2100}
2101
[email protected]be1a48b2011-01-20 00:12:132102void HostResolverImpl::OnIPAddressChanged() {
[email protected]62e86ba2013-01-29 18:59:162103 resolved_known_ipv6_hostname_ = false;
[email protected]12faa4c2012-11-06 04:44:182104 // Abandon all ProbeJobs.
2105 probe_weak_ptr_factory_.InvalidateWeakPtrs();
[email protected]be1a48b2011-01-20 00:12:132106 if (cache_.get())
2107 cache_->clear();
[email protected]7c466e92013-07-20 01:44:482108#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
[email protected]12faa4c2012-11-06 04:44:182109 new LoopbackProbeJob(probe_weak_ptr_factory_.GetWeakPtr());
[email protected]be1a48b2011-01-20 00:12:132110#endif
2111 AbortAllInProgressJobs();
2112 // |this| may be deleted inside AbortAllInProgressJobs().
2113}
2114
[email protected]bb0e34542012-08-31 19:52:402115void HostResolverImpl::OnDNSChanged() {
2116 DnsConfig dns_config;
2117 NetworkChangeNotifier::GetDnsConfig(&dns_config);
[email protected]ec666ab22013-04-17 20:05:592118
[email protected]b4481b222012-03-16 17:13:112119 if (net_log_) {
2120 net_log_->AddGlobalEntry(
2121 NetLog::TYPE_DNS_CONFIG_CHANGED,
[email protected]cd565142012-06-12 16:21:452122 base::Bind(&NetLogDnsConfigCallback, &dns_config));
[email protected]b4481b222012-03-16 17:13:112123 }
2124
[email protected]01b3b9d2012-08-13 16:18:142125 // TODO(szym): Remove once http://crbug.com/137914 is resolved.
[email protected]d7b9a2b2012-05-31 22:31:192126 received_dns_config_ = dns_config.IsValid();
[email protected]78eac2a2012-03-14 19:09:272127
[email protected]a8883e452012-11-17 05:58:062128 num_dns_failures_ = 0;
2129
[email protected]01b3b9d2012-08-13 16:18:142130 // We want a new DnsSession in place, before we Abort running Jobs, so that
2131 // the newly started jobs use the new config.
[email protected]f0f602bd2012-11-15 18:01:022132 if (dns_client_.get()) {
[email protected]d7b9a2b2012-05-31 22:31:192133 dns_client_->SetConfig(dns_config);
[email protected]a8883e452012-11-17 05:58:062134 if (dns_config.IsValid())
[email protected]f0f602bd2012-11-15 18:01:022135 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
[email protected]f0f602bd2012-11-15 18:01:022136 }
[email protected]01b3b9d2012-08-13 16:18:142137
2138 // If the DNS server has changed, existing cached info could be wrong so we
2139 // have to drop our internal cache :( Note that OS level DNS caches, such
2140 // as NSCD's cache should be dropped automatically by the OS when
2141 // resolv.conf changes so we don't need to do anything to clear that cache.
2142 if (cache_.get())
2143 cache_->clear();
2144
[email protected]f0f602bd2012-11-15 18:01:022145 // Life check to bail once |this| is deleted.
2146 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
2147
[email protected]01b3b9d2012-08-13 16:18:142148 // Existing jobs will have been sent to the original server so they need to
2149 // be aborted.
2150 AbortAllInProgressJobs();
2151
2152 // |this| may be deleted inside AbortAllInProgressJobs().
[email protected]11fbca0b2013-06-02 23:37:212153 if (self.get())
[email protected]01b3b9d2012-08-13 16:18:142154 TryServingAllJobsFromHosts();
[email protected]78eac2a2012-03-14 19:09:272155}
2156
2157bool HostResolverImpl::HaveDnsConfig() const {
[email protected]32b1dbcf2013-01-26 03:48:252158 // Use DnsClient only if it's fully configured and there is no override by
2159 // ScopedDefaultHostResolverProc.
2160 // The alternative is to use NetworkChangeNotifier to override DnsConfig,
2161 // but that would introduce construction order requirements for NCN and SDHRP.
[email protected]90499482013-06-01 00:39:502162 return (dns_client_.get() != NULL) && (dns_client_->GetConfig() != NULL) &&
2163 !(proc_params_.resolver_proc.get() == NULL &&
[email protected]32b1dbcf2013-01-26 03:48:252164 HostResolverProc::GetDefault() != NULL);
[email protected]b3601bc22012-02-21 21:23:202165}
2166
[email protected]1ffdda82012-12-12 23:04:222167void HostResolverImpl::OnDnsTaskResolve(int net_error) {
[email protected]f0f602bd2012-11-15 18:01:022168 DCHECK(dns_client_);
[email protected]1ffdda82012-12-12 23:04:222169 if (net_error == OK) {
[email protected]f0f602bd2012-11-15 18:01:022170 num_dns_failures_ = 0;
2171 return;
2172 }
2173 ++num_dns_failures_;
2174 if (num_dns_failures_ < kMaximumDnsFailures)
2175 return;
2176 // Disable DnsClient until the next DNS change.
2177 for (JobMap::iterator it = jobs_.begin(); it != jobs_.end(); ++it)
2178 it->second->AbortDnsTask();
2179 dns_client_->SetConfig(DnsConfig());
2180 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", false);
[email protected]1ffdda82012-12-12 23:04:222181 UMA_HISTOGRAM_CUSTOM_ENUMERATION("AsyncDNS.DnsClientDisabledReason",
2182 std::abs(net_error),
2183 GetAllErrorCodesForUma());
[email protected]f0f602bd2012-11-15 18:01:022184}
2185
[email protected]a8883e452012-11-17 05:58:062186void HostResolverImpl::SetDnsClient(scoped_ptr<DnsClient> dns_client) {
2187 if (HaveDnsConfig()) {
2188 for (JobMap::iterator it = jobs_.begin(); it != jobs_.end(); ++it)
2189 it->second->AbortDnsTask();
2190 }
2191 dns_client_ = dns_client.Pass();
2192 if (!dns_client_ || dns_client_->GetConfig() ||
2193 num_dns_failures_ >= kMaximumDnsFailures) {
2194 return;
2195 }
2196 DnsConfig dns_config;
2197 NetworkChangeNotifier::GetDnsConfig(&dns_config);
2198 dns_client_->SetConfig(dns_config);
2199 num_dns_failures_ = 0;
2200 if (dns_config.IsValid())
2201 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
2202}
2203
[email protected]b59ff372009-07-15 22:04:322204} // namespace net