blob: 7ca99ef4e9a7c71af3f4192004b1e33b3cfc58de [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]3e9d9cc2011-05-03 21:08:1524#include "base/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]b59ff372009-07-15 22:04:3228#include "base/string_util.h"
[email protected]ac9ba8fe2010-12-30 18:08:3629#include "base/threading/worker_pool.h"
[email protected]b59ff372009-07-15 22:04:3230#include "base/time.h"
[email protected]ccaff652010-07-31 06:28:2031#include "base/utf_string_conversions.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]ee094b82010-08-24 15:55:5136#include "net/base/host_port_pair.h"
[email protected]2bb04442010-08-18 18:01:1537#include "net/base/net_errors.h"
[email protected]ee094b82010-08-24 15:55:5138#include "net/base/net_log.h"
[email protected]0f8f1b432010-03-16 19:06:0339#include "net/base/net_util.h"
[email protected]0adcb2b2012-08-15 21:30:4640#include "net/dns/address_sorter.h"
[email protected]78eac2a2012-03-14 19:09:2741#include "net/dns/dns_client.h"
[email protected]b3601bc22012-02-21 21:23:2042#include "net/dns/dns_config_service.h"
43#include "net/dns/dns_protocol.h"
44#include "net/dns/dns_response.h"
[email protected]b3601bc22012-02-21 21:23:2045#include "net/dns/dns_transaction.h"
[email protected]f2cb3cf2013-03-21 01:40:5346#include "net/dns/host_resolver_proc.h"
[email protected]9db6f702013-04-10 18:10:5147#include "net/socket/client_socket_factory.h"
48#include "net/udp/datagram_client_socket.h"
[email protected]b59ff372009-07-15 22:04:3249
50#if defined(OS_WIN)
51#include "net/base/winsock_init.h"
52#endif
53
54namespace net {
55
[email protected]e95d3aca2010-01-11 22:47:4356namespace {
57
[email protected]6e78dfb2011-07-28 21:34:4758// Limit the size of hostnames that will be resolved to combat issues in
59// some platform's resolvers.
60const size_t kMaxHostLength = 4096;
61
[email protected]a2730882012-01-21 00:56:2762// Default TTL for successful resolutions with ProcTask.
63const unsigned kCacheEntryTTLSeconds = 60;
64
[email protected]b3601bc22012-02-21 21:23:2065// Default TTL for unsuccessful resolutions with ProcTask.
66const unsigned kNegativeCacheEntryTTLSeconds = 0;
67
[email protected]895123222012-10-25 15:21:1768// Minimum TTL for successful resolutions with DnsTask.
69const unsigned kMinimumTTLSeconds = kCacheEntryTTLSeconds;
70
[email protected]f0f602bd2012-11-15 18:01:0271// Number of consecutive failures of DnsTask (with successful fallback) before
72// the DnsClient is disabled until the next DNS change.
73const unsigned kMaximumDnsFailures = 16;
74
[email protected]24f4bab2010-10-15 01:27:1175// We use a separate histogram name for each platform to facilitate the
76// display of error codes by their symbolic name (since each platform has
77// different mappings).
78const char kOSErrorsForGetAddrinfoHistogramName[] =
79#if defined(OS_WIN)
80 "Net.OSErrorsForGetAddrinfo_Win";
81#elif defined(OS_MACOSX)
82 "Net.OSErrorsForGetAddrinfo_Mac";
83#elif defined(OS_LINUX)
84 "Net.OSErrorsForGetAddrinfo_Linux";
85#else
86 "Net.OSErrorsForGetAddrinfo";
87#endif
88
[email protected]c89b2442011-05-26 14:28:2789// Gets a list of the likely error codes that getaddrinfo() can return
90// (non-exhaustive). These are the error codes that we will track via
91// a histogram.
92std::vector<int> GetAllGetAddrinfoOSErrors() {
93 int os_errors[] = {
94#if defined(OS_POSIX)
[email protected]23f771162011-06-02 18:37:5195#if !defined(OS_FREEBSD)
[email protected]39588992011-07-11 19:54:3796#if !defined(OS_ANDROID)
[email protected]c48aef92011-11-22 23:41:4597 // EAI_ADDRFAMILY has been declared obsolete in Android's and
98 // FreeBSD's netdb.h.
[email protected]c89b2442011-05-26 14:28:2799 EAI_ADDRFAMILY,
[email protected]39588992011-07-11 19:54:37100#endif
[email protected]c48aef92011-11-22 23:41:45101 // EAI_NODATA has been declared obsolete in FreeBSD's netdb.h.
[email protected]23f771162011-06-02 18:37:51102 EAI_NODATA,
103#endif
[email protected]c89b2442011-05-26 14:28:27104 EAI_AGAIN,
105 EAI_BADFLAGS,
106 EAI_FAIL,
107 EAI_FAMILY,
108 EAI_MEMORY,
[email protected]c89b2442011-05-26 14:28:27109 EAI_NONAME,
110 EAI_SERVICE,
111 EAI_SOCKTYPE,
112 EAI_SYSTEM,
113#elif defined(OS_WIN)
114 // See: http://msdn.microsoft.com/en-us/library/ms738520(VS.85).aspx
115 WSA_NOT_ENOUGH_MEMORY,
116 WSAEAFNOSUPPORT,
117 WSAEINVAL,
118 WSAESOCKTNOSUPPORT,
119 WSAHOST_NOT_FOUND,
120 WSANO_DATA,
121 WSANO_RECOVERY,
122 WSANOTINITIALISED,
123 WSATRY_AGAIN,
124 WSATYPE_NOT_FOUND,
125 // The following are not in doc, but might be to appearing in results :-(.
126 WSA_INVALID_HANDLE,
127#endif
128 };
129
130 // Ensure all errors are positive, as histogram only tracks positive values.
131 for (size_t i = 0; i < arraysize(os_errors); ++i) {
132 os_errors[i] = std::abs(os_errors[i]);
133 }
134
135 return base::CustomHistogram::ArrayToCustomRanges(os_errors,
136 arraysize(os_errors));
137}
138
[email protected]1def74c2012-03-22 20:07:00139enum DnsResolveStatus {
140 RESOLVE_STATUS_DNS_SUCCESS = 0,
141 RESOLVE_STATUS_PROC_SUCCESS,
142 RESOLVE_STATUS_FAIL,
[email protected]1d932852012-06-19 19:40:33143 RESOLVE_STATUS_SUSPECT_NETBIOS,
[email protected]1def74c2012-03-22 20:07:00144 RESOLVE_STATUS_MAX
145};
146
147void UmaAsyncDnsResolveStatus(DnsResolveStatus result) {
148 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ResolveStatus",
149 result,
150 RESOLVE_STATUS_MAX);
151}
152
[email protected]1d932852012-06-19 19:40:33153bool ResemblesNetBIOSName(const std::string& hostname) {
154 return (hostname.size() < 16) && (hostname.find('.') == std::string::npos);
155}
156
157// True if |hostname| ends with either ".local" or ".local.".
158bool ResemblesMulticastDNSName(const std::string& hostname) {
159 DCHECK(!hostname.empty());
160 const char kSuffix[] = ".local.";
161 const size_t kSuffixLen = sizeof(kSuffix) - 1;
162 const size_t kSuffixLenTrimmed = kSuffixLen - 1;
163 if (hostname[hostname.size() - 1] == '.') {
164 return hostname.size() > kSuffixLen &&
165 !hostname.compare(hostname.size() - kSuffixLen, kSuffixLen, kSuffix);
166 }
167 return hostname.size() > kSuffixLenTrimmed &&
168 !hostname.compare(hostname.size() - kSuffixLenTrimmed, kSuffixLenTrimmed,
169 kSuffix, kSuffixLenTrimmed);
170}
171
[email protected]9db6f702013-04-10 18:10:51172// Attempts to connect a UDP socket to |dest|:80.
[email protected]e9051722013-04-12 21:58:18173bool IsGloballyReachable(const IPAddressNumber& dest) {
[email protected]9db6f702013-04-10 18:10:51174 scoped_ptr<DatagramClientSocket> socket(
175 ClientSocketFactory::GetDefaultFactory()->CreateDatagramClientSocket(
176 DatagramSocket::DEFAULT_BIND,
177 RandIntCallback(),
178 NULL,
179 NetLog::Source()));
[email protected]e9051722013-04-12 21:58:18180 int rv = socket->Connect(IPEndPoint(dest, 80));
181 if (rv != OK)
182 return false;
183 IPEndPoint endpoint;
184 rv = socket->GetLocalAddress(&endpoint);
185 if (rv != OK)
186 return false;
187 DCHECK(endpoint.GetFamily() == ADDRESS_FAMILY_IPV6);
188 const IPAddressNumber& address = endpoint.address();
189 bool is_link_local = (address[0] == 0xFE) && ((address[1] & 0xC0) == 0x80);
190 if (is_link_local)
191 return false;
192 const uint8 kTeredoPrefix[] = { 0x20, 0x01, 0, 0 };
193 bool is_teredo = std::equal(kTeredoPrefix,
194 kTeredoPrefix + arraysize(kTeredoPrefix),
195 address.begin());
196 if (is_teredo)
197 return false;
198 return true;
[email protected]9db6f702013-04-10 18:10:51199}
200
[email protected]51b9a6b2012-06-25 21:50:29201// Provide a common macro to simplify code and readability. We must use a
202// macro as the underlying HISTOGRAM macro creates static variables.
203#define DNS_HISTOGRAM(name, time) UMA_HISTOGRAM_CUSTOM_TIMES(name, time, \
204 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromHours(1), 100)
205
206// A macro to simplify code and readability.
207#define DNS_HISTOGRAM_BY_PRIORITY(basename, priority, time) \
208 do { \
209 switch (priority) { \
210 case HIGHEST: DNS_HISTOGRAM(basename "_HIGHEST", time); break; \
211 case MEDIUM: DNS_HISTOGRAM(basename "_MEDIUM", time); break; \
212 case LOW: DNS_HISTOGRAM(basename "_LOW", time); break; \
213 case LOWEST: DNS_HISTOGRAM(basename "_LOWEST", time); break; \
214 case IDLE: DNS_HISTOGRAM(basename "_IDLE", time); break; \
215 default: NOTREACHED(); break; \
216 } \
217 DNS_HISTOGRAM(basename, time); \
218 } while (0)
219
220// Record time from Request creation until a valid DNS response.
221void RecordTotalTime(bool had_dns_config,
222 bool speculative,
223 base::TimeDelta duration) {
224 if (had_dns_config) {
225 if (speculative) {
226 DNS_HISTOGRAM("AsyncDNS.TotalTime_speculative", duration);
227 } else {
228 DNS_HISTOGRAM("AsyncDNS.TotalTime", duration);
229 }
230 } else {
231 if (speculative) {
232 DNS_HISTOGRAM("DNS.TotalTime_speculative", duration);
233 } else {
234 DNS_HISTOGRAM("DNS.TotalTime", duration);
235 }
236 }
237}
238
[email protected]1339a2a22012-10-17 08:39:43239void RecordTTL(base::TimeDelta ttl) {
240 UMA_HISTOGRAM_CUSTOM_TIMES("AsyncDNS.TTL", ttl,
241 base::TimeDelta::FromSeconds(1),
242 base::TimeDelta::FromDays(1), 100);
243}
244
[email protected]d7b9a2b2012-05-31 22:31:19245//-----------------------------------------------------------------------------
246
[email protected]0f292de02012-02-01 22:28:20247// Wraps call to SystemHostResolverProc as an instance of HostResolverProc.
248// TODO(szym): This should probably be declared in host_resolver_proc.h.
249class CallSystemHostResolverProc : public HostResolverProc {
250 public:
251 CallSystemHostResolverProc() : HostResolverProc(NULL) {}
252 virtual int Resolve(const std::string& hostname,
253 AddressFamily address_family,
254 HostResolverFlags host_resolver_flags,
[email protected]b3601bc22012-02-21 21:23:20255 AddressList* addr_list,
[email protected]0f292de02012-02-01 22:28:20256 int* os_error) OVERRIDE {
257 return SystemHostResolverProc(hostname,
258 address_family,
259 host_resolver_flags,
[email protected]b3601bc22012-02-21 21:23:20260 addr_list,
[email protected]0f292de02012-02-01 22:28:20261 os_error);
[email protected]b59ff372009-07-15 22:04:32262 }
[email protected]a9813302012-04-28 09:29:28263
264 protected:
265 virtual ~CallSystemHostResolverProc() {}
[email protected]0f292de02012-02-01 22:28:20266};
[email protected]b59ff372009-07-15 22:04:32267
[email protected]895123222012-10-25 15:21:17268AddressList EnsurePortOnAddressList(const AddressList& list, uint16 port) {
269 if (list.empty() || list.front().port() == port)
270 return list;
271 return AddressList::CopyWithPort(list, port);
[email protected]7054e78f2012-05-07 21:44:56272}
273
[email protected]cd565142012-06-12 16:21:45274// Creates NetLog parameters when the resolve failed.
275base::Value* NetLogProcTaskFailedCallback(uint32 attempt_number,
276 int net_error,
277 int os_error,
278 NetLog::LogLevel /* log_level */) {
279 DictionaryValue* dict = new DictionaryValue();
280 if (attempt_number)
281 dict->SetInteger("attempt_number", attempt_number);
[email protected]21526002010-05-16 19:42:46282
[email protected]cd565142012-06-12 16:21:45283 dict->SetInteger("net_error", net_error);
[email protected]13024882011-05-18 23:19:16284
[email protected]cd565142012-06-12 16:21:45285 if (os_error) {
286 dict->SetInteger("os_error", os_error);
[email protected]21526002010-05-16 19:42:46287#if defined(OS_POSIX)
[email protected]cd565142012-06-12 16:21:45288 dict->SetString("os_error_string", gai_strerror(os_error));
[email protected]21526002010-05-16 19:42:46289#elif defined(OS_WIN)
[email protected]cd565142012-06-12 16:21:45290 // Map the error code to a human-readable string.
291 LPWSTR error_string = NULL;
292 int size = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
293 FORMAT_MESSAGE_FROM_SYSTEM,
294 0, // Use the internal message table.
295 os_error,
296 0, // Use default language.
297 (LPWSTR)&error_string,
298 0, // Buffer size.
299 0); // Arguments (unused).
300 dict->SetString("os_error_string", WideToUTF8(error_string));
301 LocalFree(error_string);
[email protected]21526002010-05-16 19:42:46302#endif
[email protected]21526002010-05-16 19:42:46303 }
304
[email protected]cd565142012-06-12 16:21:45305 return dict;
306}
[email protected]a9813302012-04-28 09:29:28307
[email protected]cd565142012-06-12 16:21:45308// Creates NetLog parameters when the DnsTask failed.
309base::Value* NetLogDnsTaskFailedCallback(int net_error,
310 int dns_error,
311 NetLog::LogLevel /* log_level */) {
312 DictionaryValue* dict = new DictionaryValue();
313 dict->SetInteger("net_error", net_error);
314 if (dns_error)
315 dict->SetInteger("dns_error", dns_error);
316 return dict;
[email protected]ee094b82010-08-24 15:55:51317};
318
[email protected]cd565142012-06-12 16:21:45319// Creates NetLog parameters containing the information in a RequestInfo object,
320// along with the associated NetLog::Source.
321base::Value* NetLogRequestInfoCallback(const NetLog::Source& source,
322 const HostResolver::RequestInfo* info,
323 NetLog::LogLevel /* log_level */) {
324 DictionaryValue* dict = new DictionaryValue();
325 source.AddToEventParameters(dict);
[email protected]b3601bc22012-02-21 21:23:20326
[email protected]cd565142012-06-12 16:21:45327 dict->SetString("host", info->host_port_pair().ToString());
328 dict->SetInteger("address_family",
329 static_cast<int>(info->address_family()));
330 dict->SetBoolean("allow_cached_response", info->allow_cached_response());
331 dict->SetBoolean("is_speculative", info->is_speculative());
332 dict->SetInteger("priority", info->priority());
333 return dict;
334}
[email protected]b3601bc22012-02-21 21:23:20335
[email protected]cd565142012-06-12 16:21:45336// Creates NetLog parameters for the creation of a HostResolverImpl::Job.
337base::Value* NetLogJobCreationCallback(const NetLog::Source& source,
338 const std::string* host,
339 NetLog::LogLevel /* log_level */) {
340 DictionaryValue* dict = new DictionaryValue();
341 source.AddToEventParameters(dict);
342 dict->SetString("host", *host);
343 return dict;
344}
[email protected]a9813302012-04-28 09:29:28345
[email protected]cd565142012-06-12 16:21:45346// Creates NetLog parameters for HOST_RESOLVER_IMPL_JOB_ATTACH/DETACH events.
347base::Value* NetLogJobAttachCallback(const NetLog::Source& source,
348 RequestPriority priority,
349 NetLog::LogLevel /* log_level */) {
350 DictionaryValue* dict = new DictionaryValue();
351 source.AddToEventParameters(dict);
352 dict->SetInteger("priority", priority);
353 return dict;
354}
[email protected]b3601bc22012-02-21 21:23:20355
[email protected]cd565142012-06-12 16:21:45356// Creates NetLog parameters for the DNS_CONFIG_CHANGED event.
357base::Value* NetLogDnsConfigCallback(const DnsConfig* config,
358 NetLog::LogLevel /* log_level */) {
359 return config->ToValue();
360}
[email protected]b4481b222012-03-16 17:13:11361
[email protected]0f292de02012-02-01 22:28:20362// The logging routines are defined here because some requests are resolved
363// without a Request object.
364
365// Logs when a request has just been started.
366void LogStartRequest(const BoundNetLog& source_net_log,
367 const BoundNetLog& request_net_log,
368 const HostResolver::RequestInfo& info) {
369 source_net_log.BeginEvent(
370 NetLog::TYPE_HOST_RESOLVER_IMPL,
[email protected]cd565142012-06-12 16:21:45371 request_net_log.source().ToEventParametersCallback());
[email protected]0f292de02012-02-01 22:28:20372
373 request_net_log.BeginEvent(
374 NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST,
[email protected]cd565142012-06-12 16:21:45375 base::Bind(&NetLogRequestInfoCallback, source_net_log.source(), &info));
[email protected]0f292de02012-02-01 22:28:20376}
377
378// Logs when a request has just completed (before its callback is run).
379void LogFinishRequest(const BoundNetLog& source_net_log,
380 const BoundNetLog& request_net_log,
381 const HostResolver::RequestInfo& info,
[email protected]b3601bc22012-02-21 21:23:20382 int net_error) {
383 request_net_log.EndEventWithNetErrorCode(
384 NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST, net_error);
[email protected]4da911f2012-06-14 19:45:20385 source_net_log.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL);
[email protected]0f292de02012-02-01 22:28:20386}
387
388// Logs when a request has been cancelled.
389void LogCancelRequest(const BoundNetLog& source_net_log,
390 const BoundNetLog& request_net_log,
391 const HostResolverImpl::RequestInfo& info) {
[email protected]4da911f2012-06-14 19:45:20392 request_net_log.AddEvent(NetLog::TYPE_CANCELLED);
393 request_net_log.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST);
394 source_net_log.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL);
[email protected]0f292de02012-02-01 22:28:20395}
396
[email protected]b59ff372009-07-15 22:04:32397//-----------------------------------------------------------------------------
398
[email protected]0f292de02012-02-01 22:28:20399// Keeps track of the highest priority.
400class PriorityTracker {
401 public:
[email protected]8c98d002012-07-18 19:02:27402 explicit PriorityTracker(RequestPriority initial_priority)
403 : highest_priority_(initial_priority), total_count_(0) {
[email protected]0f292de02012-02-01 22:28:20404 memset(counts_, 0, sizeof(counts_));
405 }
406
407 RequestPriority highest_priority() const {
408 return highest_priority_;
409 }
410
411 size_t total_count() const {
412 return total_count_;
413 }
414
415 void Add(RequestPriority req_priority) {
416 ++total_count_;
417 ++counts_[req_priority];
[email protected]31ae7ab2012-04-24 21:09:05418 if (highest_priority_ < req_priority)
[email protected]0f292de02012-02-01 22:28:20419 highest_priority_ = req_priority;
420 }
421
422 void Remove(RequestPriority req_priority) {
423 DCHECK_GT(total_count_, 0u);
424 DCHECK_GT(counts_[req_priority], 0u);
425 --total_count_;
426 --counts_[req_priority];
427 size_t i;
[email protected]31ae7ab2012-04-24 21:09:05428 for (i = highest_priority_; i > MINIMUM_PRIORITY && !counts_[i]; --i);
[email protected]0f292de02012-02-01 22:28:20429 highest_priority_ = static_cast<RequestPriority>(i);
430
[email protected]31ae7ab2012-04-24 21:09:05431 // In absence of requests, default to MINIMUM_PRIORITY.
432 if (total_count_ == 0)
433 DCHECK_EQ(MINIMUM_PRIORITY, highest_priority_);
[email protected]0f292de02012-02-01 22:28:20434 }
435
436 private:
437 RequestPriority highest_priority_;
438 size_t total_count_;
439 size_t counts_[NUM_PRIORITIES];
440};
441
[email protected]c54a8912012-10-22 22:09:43442} // namespace
[email protected]0f292de02012-02-01 22:28:20443
444//-----------------------------------------------------------------------------
445
446// Holds the data for a request that could not be completed synchronously.
447// It is owned by a Job. Canceled Requests are only marked as canceled rather
448// than removed from the Job's |requests_| list.
[email protected]b59ff372009-07-15 22:04:32449class HostResolverImpl::Request {
450 public:
[email protected]ee094b82010-08-24 15:55:51451 Request(const BoundNetLog& source_net_log,
452 const BoundNetLog& request_net_log,
[email protected]54e13772009-08-14 03:01:09453 const RequestInfo& info,
[email protected]aa22b242011-11-16 18:58:29454 const CompletionCallback& callback,
[email protected]b59ff372009-07-15 22:04:32455 AddressList* addresses)
[email protected]ee094b82010-08-24 15:55:51456 : source_net_log_(source_net_log),
457 request_net_log_(request_net_log),
[email protected]54e13772009-08-14 03:01:09458 info_(info),
459 job_(NULL),
460 callback_(callback),
[email protected]51b9a6b2012-06-25 21:50:29461 addresses_(addresses),
462 request_time_(base::TimeTicks::Now()) {
[email protected]54e13772009-08-14 03:01:09463 }
[email protected]b59ff372009-07-15 22:04:32464
[email protected]0f292de02012-02-01 22:28:20465 // Mark the request as canceled.
466 void MarkAsCanceled() {
[email protected]b59ff372009-07-15 22:04:32467 job_ = NULL;
[email protected]b59ff372009-07-15 22:04:32468 addresses_ = NULL;
[email protected]aa22b242011-11-16 18:58:29469 callback_.Reset();
[email protected]b59ff372009-07-15 22:04:32470 }
471
[email protected]0f292de02012-02-01 22:28:20472 bool was_canceled() const {
[email protected]aa22b242011-11-16 18:58:29473 return callback_.is_null();
[email protected]b59ff372009-07-15 22:04:32474 }
475
476 void set_job(Job* job) {
[email protected]0f292de02012-02-01 22:28:20477 DCHECK(job);
[email protected]b59ff372009-07-15 22:04:32478 // Identify which job the request is waiting on.
479 job_ = job;
480 }
481
[email protected]0f292de02012-02-01 22:28:20482 // Prepare final AddressList and call completion callback.
[email protected]b3601bc22012-02-21 21:23:20483 void OnComplete(int error, const AddressList& addr_list) {
[email protected]51b9a6b2012-06-25 21:50:29484 DCHECK(!was_canceled());
[email protected]895123222012-10-25 15:21:17485 if (error == OK)
486 *addresses_ = EnsurePortOnAddressList(addr_list, info_.port());
[email protected]aa22b242011-11-16 18:58:29487 CompletionCallback callback = callback_;
[email protected]0f292de02012-02-01 22:28:20488 MarkAsCanceled();
[email protected]aa22b242011-11-16 18:58:29489 callback.Run(error);
[email protected]b59ff372009-07-15 22:04:32490 }
491
[email protected]b59ff372009-07-15 22:04:32492 Job* job() const {
493 return job_;
494 }
495
[email protected]0f292de02012-02-01 22:28:20496 // NetLog for the source, passed in HostResolver::Resolve.
[email protected]ee094b82010-08-24 15:55:51497 const BoundNetLog& source_net_log() {
498 return source_net_log_;
499 }
500
[email protected]0f292de02012-02-01 22:28:20501 // NetLog for this request.
[email protected]ee094b82010-08-24 15:55:51502 const BoundNetLog& request_net_log() {
503 return request_net_log_;
[email protected]54e13772009-08-14 03:01:09504 }
505
[email protected]b59ff372009-07-15 22:04:32506 const RequestInfo& info() const {
507 return info_;
508 }
509
[email protected]51b9a6b2012-06-25 21:50:29510 base::TimeTicks request_time() const {
511 return request_time_;
512 }
513
[email protected]b59ff372009-07-15 22:04:32514 private:
[email protected]ee094b82010-08-24 15:55:51515 BoundNetLog source_net_log_;
516 BoundNetLog request_net_log_;
[email protected]54e13772009-08-14 03:01:09517
[email protected]b59ff372009-07-15 22:04:32518 // The request info that started the request.
519 RequestInfo info_;
520
[email protected]0f292de02012-02-01 22:28:20521 // The resolve job that this request is dependent on.
[email protected]b59ff372009-07-15 22:04:32522 Job* job_;
523
524 // The user's callback to invoke when the request completes.
[email protected]aa22b242011-11-16 18:58:29525 CompletionCallback callback_;
[email protected]b59ff372009-07-15 22:04:32526
527 // The address list to save result into.
528 AddressList* addresses_;
529
[email protected]51b9a6b2012-06-25 21:50:29530 const base::TimeTicks request_time_;
531
[email protected]b59ff372009-07-15 22:04:32532 DISALLOW_COPY_AND_ASSIGN(Request);
533};
534
[email protected]1e9bbd22010-10-15 16:42:45535//------------------------------------------------------------------------------
536
[email protected]0f292de02012-02-01 22:28:20537// Calls HostResolverProc on the WorkerPool. Performs retries if necessary.
538//
539// Whenever we try to resolve the host, we post a delayed task to check if host
540// resolution (OnLookupComplete) is completed or not. If the original attempt
541// hasn't completed, then we start another attempt for host resolution. We take
542// the results from the first attempt that finishes and ignore the results from
543// all other attempts.
544//
545// TODO(szym): Move to separate source file for testing and mocking.
546//
547class HostResolverImpl::ProcTask
548 : public base::RefCountedThreadSafe<HostResolverImpl::ProcTask> {
[email protected]b59ff372009-07-15 22:04:32549 public:
[email protected]b3601bc22012-02-21 21:23:20550 typedef base::Callback<void(int net_error,
551 const AddressList& addr_list)> Callback;
[email protected]b59ff372009-07-15 22:04:32552
[email protected]0f292de02012-02-01 22:28:20553 ProcTask(const Key& key,
554 const ProcTaskParams& params,
555 const Callback& callback,
556 const BoundNetLog& job_net_log)
557 : key_(key),
558 params_(params),
559 callback_(callback),
560 origin_loop_(base::MessageLoopProxy::current()),
561 attempt_number_(0),
562 completed_attempt_number_(0),
563 completed_attempt_error_(ERR_UNEXPECTED),
564 had_non_speculative_request_(false),
[email protected]b3601bc22012-02-21 21:23:20565 net_log_(job_net_log) {
[email protected]0f292de02012-02-01 22:28:20566 if (!params_.resolver_proc)
567 params_.resolver_proc = HostResolverProc::GetDefault();
568 // If default is unset, use the system proc.
569 if (!params_.resolver_proc)
570 params_.resolver_proc = new CallSystemHostResolverProc();
[email protected]b59ff372009-07-15 22:04:32571 }
572
[email protected]b59ff372009-07-15 22:04:32573 void Start() {
[email protected]3e9d9cc2011-05-03 21:08:15574 DCHECK(origin_loop_->BelongsToCurrentThread());
[email protected]4da911f2012-06-14 19:45:20575 net_log_.BeginEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK);
[email protected]189163e2011-05-11 01:48:54576 StartLookupAttempt();
577 }
[email protected]252b699b2010-02-05 21:38:06578
[email protected]0f292de02012-02-01 22:28:20579 // Cancels this ProcTask. It will be orphaned. Any outstanding resolve
580 // attempts running on worker threads will continue running. Only once all the
581 // attempts complete will the final reference to this ProcTask be released.
582 void Cancel() {
583 DCHECK(origin_loop_->BelongsToCurrentThread());
584
[email protected]0adcb2b2012-08-15 21:30:46585 if (was_canceled() || was_completed())
[email protected]0f292de02012-02-01 22:28:20586 return;
587
[email protected]0f292de02012-02-01 22:28:20588 callback_.Reset();
[email protected]4da911f2012-06-14 19:45:20589 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK);
[email protected]0f292de02012-02-01 22:28:20590 }
591
592 void set_had_non_speculative_request() {
593 DCHECK(origin_loop_->BelongsToCurrentThread());
594 had_non_speculative_request_ = true;
595 }
596
597 bool was_canceled() const {
598 DCHECK(origin_loop_->BelongsToCurrentThread());
599 return callback_.is_null();
600 }
601
602 bool was_completed() const {
603 DCHECK(origin_loop_->BelongsToCurrentThread());
604 return completed_attempt_number_ > 0;
605 }
606
607 private:
[email protected]a9813302012-04-28 09:29:28608 friend class base::RefCountedThreadSafe<ProcTask>;
609 ~ProcTask() {}
610
[email protected]189163e2011-05-11 01:48:54611 void StartLookupAttempt() {
612 DCHECK(origin_loop_->BelongsToCurrentThread());
613 base::TimeTicks start_time = base::TimeTicks::Now();
614 ++attempt_number_;
615 // Dispatch the lookup attempt to a worker thread.
616 if (!base::WorkerPool::PostTask(
617 FROM_HERE,
[email protected]0f292de02012-02-01 22:28:20618 base::Bind(&ProcTask::DoLookup, this, start_time, attempt_number_),
[email protected]189163e2011-05-11 01:48:54619 true)) {
[email protected]b59ff372009-07-15 22:04:32620 NOTREACHED();
621
622 // Since we could be running within Resolve() right now, we can't just
623 // call OnLookupComplete(). Instead we must wait until Resolve() has
624 // returned (IO_PENDING).
[email protected]3e9d9cc2011-05-03 21:08:15625 origin_loop_->PostTask(
[email protected]189163e2011-05-11 01:48:54626 FROM_HERE,
[email protected]0f292de02012-02-01 22:28:20627 base::Bind(&ProcTask::OnLookupComplete, this, AddressList(),
[email protected]33152acc2011-10-20 23:37:12628 start_time, attempt_number_, ERR_UNEXPECTED, 0));
[email protected]189163e2011-05-11 01:48:54629 return;
[email protected]b59ff372009-07-15 22:04:32630 }
[email protected]13024882011-05-18 23:19:16631
632 net_log_.AddEvent(
633 NetLog::TYPE_HOST_RESOLVER_IMPL_ATTEMPT_STARTED,
[email protected]cd565142012-06-12 16:21:45634 NetLog::IntegerCallback("attempt_number", attempt_number_));
[email protected]13024882011-05-18 23:19:16635
[email protected]0f292de02012-02-01 22:28:20636 // If we don't get the results within a given time, RetryIfNotComplete
637 // will start a new attempt on a different worker thread if none of our
638 // outstanding attempts have completed yet.
639 if (attempt_number_ <= params_.max_retry_attempts) {
[email protected]06ef6d92011-05-19 04:24:58640 origin_loop_->PostDelayedTask(
641 FROM_HERE,
[email protected]0f292de02012-02-01 22:28:20642 base::Bind(&ProcTask::RetryIfNotComplete, this),
[email protected]7e560102012-03-08 20:58:42643 params_.unresponsive_delay);
[email protected]06ef6d92011-05-19 04:24:58644 }
[email protected]b59ff372009-07-15 22:04:32645 }
646
[email protected]6c710ee2010-05-07 07:51:16647 // WARNING: This code runs inside a worker pool. The shutdown code cannot
648 // wait for it to finish, so we must be very careful here about using other
649 // objects (like MessageLoops, Singletons, etc). During shutdown these objects
[email protected]189163e2011-05-11 01:48:54650 // may no longer exist. Multiple DoLookups() could be running in parallel, so
651 // any state inside of |this| must not mutate .
652 void DoLookup(const base::TimeTicks& start_time,
653 const uint32 attempt_number) {
654 AddressList results;
655 int os_error = 0;
[email protected]b59ff372009-07-15 22:04:32656 // Running on the worker thread
[email protected]0f292de02012-02-01 22:28:20657 int error = params_.resolver_proc->Resolve(key_.hostname,
658 key_.address_family,
659 key_.host_resolver_flags,
660 &results,
661 &os_error);
[email protected]b59ff372009-07-15 22:04:32662
[email protected]189163e2011-05-11 01:48:54663 origin_loop_->PostTask(
664 FROM_HERE,
[email protected]0f292de02012-02-01 22:28:20665 base::Bind(&ProcTask::OnLookupComplete, this, results, start_time,
[email protected]33152acc2011-10-20 23:37:12666 attempt_number, error, os_error));
[email protected]189163e2011-05-11 01:48:54667 }
668
[email protected]0f292de02012-02-01 22:28:20669 // Makes next attempt if DoLookup() has not finished (runs on origin thread).
670 void RetryIfNotComplete() {
[email protected]189163e2011-05-11 01:48:54671 DCHECK(origin_loop_->BelongsToCurrentThread());
672
[email protected]0f292de02012-02-01 22:28:20673 if (was_completed() || was_canceled())
[email protected]189163e2011-05-11 01:48:54674 return;
675
[email protected]0f292de02012-02-01 22:28:20676 params_.unresponsive_delay *= params_.retry_factor;
[email protected]189163e2011-05-11 01:48:54677 StartLookupAttempt();
[email protected]b59ff372009-07-15 22:04:32678 }
679
680 // Callback for when DoLookup() completes (runs on origin thread).
[email protected]189163e2011-05-11 01:48:54681 void OnLookupComplete(const AddressList& results,
682 const base::TimeTicks& start_time,
683 const uint32 attempt_number,
684 int error,
685 const int os_error) {
[email protected]3e9d9cc2011-05-03 21:08:15686 DCHECK(origin_loop_->BelongsToCurrentThread());
[email protected]7054e78f2012-05-07 21:44:56687 DCHECK(error || !results.empty());
[email protected]189163e2011-05-11 01:48:54688
689 bool was_retry_attempt = attempt_number > 1;
690
[email protected]2d3b7762010-10-09 00:35:47691 // Ideally the following code would be part of host_resolver_proc.cc,
[email protected]b3601bc22012-02-21 21:23:20692 // however it isn't safe to call NetworkChangeNotifier from worker threads.
693 // So we do it here on the IO thread instead.
[email protected]189163e2011-05-11 01:48:54694 if (error != OK && NetworkChangeNotifier::IsOffline())
695 error = ERR_INTERNET_DISCONNECTED;
[email protected]2d3b7762010-10-09 00:35:47696
[email protected]b3601bc22012-02-21 21:23:20697 // If this is the first attempt that is finishing later, then record data
698 // for the first attempt. Won't contaminate with retry attempt's data.
[email protected]189163e2011-05-11 01:48:54699 if (!was_retry_attempt)
700 RecordPerformanceHistograms(start_time, error, os_error);
701
702 RecordAttemptHistograms(start_time, attempt_number, error, os_error);
[email protected]f2d8c4212010-02-02 00:56:35703
[email protected]0f292de02012-02-01 22:28:20704 if (was_canceled())
[email protected]b59ff372009-07-15 22:04:32705 return;
706
[email protected]cd565142012-06-12 16:21:45707 NetLog::ParametersCallback net_log_callback;
[email protected]0f292de02012-02-01 22:28:20708 if (error != OK) {
[email protected]cd565142012-06-12 16:21:45709 net_log_callback = base::Bind(&NetLogProcTaskFailedCallback,
710 attempt_number,
711 error,
712 os_error);
[email protected]0f292de02012-02-01 22:28:20713 } else {
[email protected]cd565142012-06-12 16:21:45714 net_log_callback = NetLog::IntegerCallback("attempt_number",
715 attempt_number);
[email protected]0f292de02012-02-01 22:28:20716 }
[email protected]cd565142012-06-12 16:21:45717 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_ATTEMPT_FINISHED,
718 net_log_callback);
[email protected]0f292de02012-02-01 22:28:20719
720 if (was_completed())
721 return;
722
723 // Copy the results from the first worker thread that resolves the host.
724 results_ = results;
725 completed_attempt_number_ = attempt_number;
726 completed_attempt_error_ = error;
727
[email protected]e87b8b512011-06-14 22:12:52728 if (was_retry_attempt) {
729 // If retry attempt finishes before 1st attempt, then get stats on how
730 // much time is saved by having spawned an extra attempt.
731 retry_attempt_finished_time_ = base::TimeTicks::Now();
732 }
733
[email protected]189163e2011-05-11 01:48:54734 if (error != OK) {
[email protected]cd565142012-06-12 16:21:45735 net_log_callback = base::Bind(&NetLogProcTaskFailedCallback,
736 0, error, os_error);
[email protected]ee094b82010-08-24 15:55:51737 } else {
[email protected]cd565142012-06-12 16:21:45738 net_log_callback = results_.CreateNetLogCallback();
[email protected]ee094b82010-08-24 15:55:51739 }
[email protected]cd565142012-06-12 16:21:45740 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK,
741 net_log_callback);
[email protected]ee094b82010-08-24 15:55:51742
[email protected]b3601bc22012-02-21 21:23:20743 callback_.Run(error, results_);
[email protected]b59ff372009-07-15 22:04:32744 }
745
[email protected]189163e2011-05-11 01:48:54746 void RecordPerformanceHistograms(const base::TimeTicks& start_time,
747 const int error,
748 const int os_error) const {
[email protected]3e9d9cc2011-05-03 21:08:15749 DCHECK(origin_loop_->BelongsToCurrentThread());
[email protected]1e9bbd22010-10-15 16:42:45750 enum Category { // Used in HISTOGRAM_ENUMERATION.
751 RESOLVE_SUCCESS,
752 RESOLVE_FAIL,
753 RESOLVE_SPECULATIVE_SUCCESS,
754 RESOLVE_SPECULATIVE_FAIL,
755 RESOLVE_MAX, // Bounding value.
756 };
757 int category = RESOLVE_MAX; // Illegal value for later DCHECK only.
758
[email protected]189163e2011-05-11 01:48:54759 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
760 if (error == OK) {
[email protected]1e9bbd22010-10-15 16:42:45761 if (had_non_speculative_request_) {
762 category = RESOLVE_SUCCESS;
763 DNS_HISTOGRAM("DNS.ResolveSuccess", duration);
764 } else {
765 category = RESOLVE_SPECULATIVE_SUCCESS;
766 DNS_HISTOGRAM("DNS.ResolveSpeculativeSuccess", duration);
767 }
[email protected]7e96d792011-06-10 17:08:23768
[email protected]78eac2a2012-03-14 19:09:27769 // Log DNS lookups based on |address_family|. This will help us determine
[email protected]7e96d792011-06-10 17:08:23770 // if IPv4 or IPv4/6 lookups are faster or slower.
771 switch(key_.address_family) {
772 case ADDRESS_FAMILY_IPV4:
773 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_IPV4", duration);
774 break;
775 case ADDRESS_FAMILY_IPV6:
776 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_IPV6", duration);
777 break;
778 case ADDRESS_FAMILY_UNSPECIFIED:
779 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_UNSPEC", duration);
780 break;
781 }
[email protected]1e9bbd22010-10-15 16:42:45782 } else {
783 if (had_non_speculative_request_) {
784 category = RESOLVE_FAIL;
785 DNS_HISTOGRAM("DNS.ResolveFail", duration);
786 } else {
787 category = RESOLVE_SPECULATIVE_FAIL;
788 DNS_HISTOGRAM("DNS.ResolveSpeculativeFail", duration);
789 }
[email protected]78eac2a2012-03-14 19:09:27790 // Log DNS lookups based on |address_family|. This will help us determine
[email protected]7e96d792011-06-10 17:08:23791 // if IPv4 or IPv4/6 lookups are faster or slower.
792 switch(key_.address_family) {
793 case ADDRESS_FAMILY_IPV4:
794 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_IPV4", duration);
795 break;
796 case ADDRESS_FAMILY_IPV6:
797 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_IPV6", duration);
798 break;
799 case ADDRESS_FAMILY_UNSPECIFIED:
800 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_UNSPEC", duration);
801 break;
802 }
[email protected]c833e322010-10-16 23:51:36803 UMA_HISTOGRAM_CUSTOM_ENUMERATION(kOSErrorsForGetAddrinfoHistogramName,
[email protected]189163e2011-05-11 01:48:54804 std::abs(os_error),
[email protected]1e9bbd22010-10-15 16:42:45805 GetAllGetAddrinfoOSErrors());
806 }
[email protected]051b6ab2010-10-18 16:50:46807 DCHECK_LT(category, static_cast<int>(RESOLVE_MAX)); // Be sure it was set.
[email protected]1e9bbd22010-10-15 16:42:45808
809 UMA_HISTOGRAM_ENUMERATION("DNS.ResolveCategory", category, RESOLVE_MAX);
[email protected]1e9bbd22010-10-15 16:42:45810 }
811
[email protected]189163e2011-05-11 01:48:54812 void RecordAttemptHistograms(const base::TimeTicks& start_time,
813 const uint32 attempt_number,
814 const int error,
815 const int os_error) const {
[email protected]0f292de02012-02-01 22:28:20816 DCHECK(origin_loop_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54817 bool first_attempt_to_complete =
818 completed_attempt_number_ == attempt_number;
[email protected]e87b8b512011-06-14 22:12:52819 bool is_first_attempt = (attempt_number == 1);
[email protected]1e9bbd22010-10-15 16:42:45820
[email protected]189163e2011-05-11 01:48:54821 if (first_attempt_to_complete) {
822 // If this was first attempt to complete, then record the resolution
823 // status of the attempt.
824 if (completed_attempt_error_ == OK) {
825 UMA_HISTOGRAM_ENUMERATION(
826 "DNS.AttemptFirstSuccess", attempt_number, 100);
827 } else {
828 UMA_HISTOGRAM_ENUMERATION(
829 "DNS.AttemptFirstFailure", attempt_number, 100);
830 }
831 }
832
833 if (error == OK)
834 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptSuccess", attempt_number, 100);
835 else
836 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptFailure", attempt_number, 100);
837
[email protected]e87b8b512011-06-14 22:12:52838 // If first attempt didn't finish before retry attempt, then calculate stats
839 // on how much time is saved by having spawned an extra attempt.
[email protected]0f292de02012-02-01 22:28:20840 if (!first_attempt_to_complete && is_first_attempt && !was_canceled()) {
[email protected]e87b8b512011-06-14 22:12:52841 DNS_HISTOGRAM("DNS.AttemptTimeSavedByRetry",
842 base::TimeTicks::Now() - retry_attempt_finished_time_);
843 }
844
[email protected]0f292de02012-02-01 22:28:20845 if (was_canceled() || !first_attempt_to_complete) {
[email protected]189163e2011-05-11 01:48:54846 // Count those attempts which completed after the job was already canceled
847 // OR after the job was already completed by an earlier attempt (so in
848 // effect).
849 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptDiscarded", attempt_number, 100);
850
[email protected]0f292de02012-02-01 22:28:20851 // Record if job is canceled.
852 if (was_canceled())
[email protected]189163e2011-05-11 01:48:54853 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptCancelled", attempt_number, 100);
854 }
855
856 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
857 if (error == OK)
858 DNS_HISTOGRAM("DNS.AttemptSuccessDuration", duration);
859 else
860 DNS_HISTOGRAM("DNS.AttemptFailDuration", duration);
861 }
[email protected]1e9bbd22010-10-15 16:42:45862
[email protected]b59ff372009-07-15 22:04:32863 // Set on the origin thread, read on the worker thread.
[email protected]123ab1e32009-10-21 19:12:57864 Key key_;
[email protected]b59ff372009-07-15 22:04:32865
[email protected]0f292de02012-02-01 22:28:20866 // Holds an owning reference to the HostResolverProc that we are going to use.
[email protected]b59ff372009-07-15 22:04:32867 // This may not be the current resolver procedure by the time we call
868 // ResolveAddrInfo, but that's OK... we'll use it anyways, and the owning
869 // reference ensures that it remains valid until we are done.
[email protected]0f292de02012-02-01 22:28:20870 ProcTaskParams params_;
[email protected]b59ff372009-07-15 22:04:32871
[email protected]0f292de02012-02-01 22:28:20872 // The listener to the results of this ProcTask.
873 Callback callback_;
874
875 // Used to post ourselves onto the origin thread.
876 scoped_refptr<base::MessageLoopProxy> origin_loop_;
[email protected]189163e2011-05-11 01:48:54877
878 // Keeps track of the number of attempts we have made so far to resolve the
879 // host. Whenever we start an attempt to resolve the host, we increase this
880 // number.
881 uint32 attempt_number_;
882
883 // The index of the attempt which finished first (or 0 if the job is still in
884 // progress).
885 uint32 completed_attempt_number_;
886
887 // The result (a net error code) from the first attempt to complete.
888 int completed_attempt_error_;
[email protected]252b699b2010-02-05 21:38:06889
[email protected]e87b8b512011-06-14 22:12:52890 // The time when retry attempt was finished.
891 base::TimeTicks retry_attempt_finished_time_;
892
[email protected]252b699b2010-02-05 21:38:06893 // True if a non-speculative request was ever attached to this job
[email protected]0f292de02012-02-01 22:28:20894 // (regardless of whether or not it was later canceled.
[email protected]252b699b2010-02-05 21:38:06895 // This boolean is used for histogramming the duration of jobs used to
896 // service non-speculative requests.
897 bool had_non_speculative_request_;
898
[email protected]b59ff372009-07-15 22:04:32899 AddressList results_;
900
[email protected]ee094b82010-08-24 15:55:51901 BoundNetLog net_log_;
902
[email protected]0f292de02012-02-01 22:28:20903 DISALLOW_COPY_AND_ASSIGN(ProcTask);
[email protected]b59ff372009-07-15 22:04:32904};
905
906//-----------------------------------------------------------------------------
907
[email protected]12faa4c2012-11-06 04:44:18908// Wraps a call to TestIPv6Support to be executed on the WorkerPool as it takes
909// 40-100ms.
[email protected]9db6f702013-04-10 18:10:51910// TODO(szym): Remove altogether, if IPv6ActiveProbe works.
[email protected]12faa4c2012-11-06 04:44:18911class HostResolverImpl::IPv6ProbeJob {
[email protected]0f8f1b432010-03-16 19:06:03912 public:
[email protected]12faa4c2012-11-06 04:44:18913 IPv6ProbeJob(const base::WeakPtr<HostResolverImpl>& resolver, NetLog* net_log)
[email protected]0f8f1b432010-03-16 19:06:03914 : resolver_(resolver),
[email protected]12faa4c2012-11-06 04:44:18915 net_log_(BoundNetLog::Make(net_log, NetLog::SOURCE_IPV6_PROBE_JOB)),
916 result_(false, IPV6_SUPPORT_MAX, OK) {
[email protected]3e9d9cc2011-05-03 21:08:15917 DCHECK(resolver);
[email protected]ae8e80f2012-07-19 21:08:33918 net_log_.BeginEvent(NetLog::TYPE_IPV6_PROBE_RUNNING);
[email protected]f092e64b2010-03-17 00:39:18919 const bool kIsSlow = true;
[email protected]12faa4c2012-11-06 04:44:18920 base::WorkerPool::PostTaskAndReply(
921 FROM_HERE,
922 base::Bind(&IPv6ProbeJob::DoProbe, base::Unretained(this)),
923 base::Bind(&IPv6ProbeJob::OnProbeComplete, base::Owned(this)),
924 kIsSlow);
[email protected]0f8f1b432010-03-16 19:06:03925 }
926
[email protected]12faa4c2012-11-06 04:44:18927 virtual ~IPv6ProbeJob() {}
[email protected]0f8f1b432010-03-16 19:06:03928
[email protected]0f8f1b432010-03-16 19:06:03929 private:
[email protected]12faa4c2012-11-06 04:44:18930 // Runs on worker thread.
[email protected]0f8f1b432010-03-16 19:06:03931 void DoProbe() {
[email protected]12faa4c2012-11-06 04:44:18932 result_ = TestIPv6Support();
[email protected]0f8f1b432010-03-16 19:06:03933 }
934
[email protected]12faa4c2012-11-06 04:44:18935 void OnProbeComplete() {
936 net_log_.EndEvent(NetLog::TYPE_IPV6_PROBE_RUNNING,
937 base::Bind(&IPv6SupportResult::ToNetLogValue,
938 base::Unretained(&result_)));
939 if (!resolver_)
[email protected]a9af7112010-05-08 00:56:01940 return;
[email protected]12faa4c2012-11-06 04:44:18941 resolver_->IPv6ProbeSetDefaultAddressFamily(
942 result_.ipv6_supported ? ADDRESS_FAMILY_UNSPECIFIED
[email protected]ae8e80f2012-07-19 21:08:33943 : ADDRESS_FAMILY_IPV4);
[email protected]0f8f1b432010-03-16 19:06:03944 }
945
[email protected]0f8f1b432010-03-16 19:06:03946 // Used/set only on origin thread.
[email protected]12faa4c2012-11-06 04:44:18947 base::WeakPtr<HostResolverImpl> resolver_;
[email protected]0f8f1b432010-03-16 19:06:03948
[email protected]ae8e80f2012-07-19 21:08:33949 BoundNetLog net_log_;
950
[email protected]12faa4c2012-11-06 04:44:18951 IPv6SupportResult result_;
952
[email protected]0f8f1b432010-03-16 19:06:03953 DISALLOW_COPY_AND_ASSIGN(IPv6ProbeJob);
954};
955
[email protected]12faa4c2012-11-06 04:44:18956// Wraps a call to HaveOnlyLoopbackAddresses to be executed on the WorkerPool as
957// it takes 40-100ms and should not block initialization.
958class HostResolverImpl::LoopbackProbeJob {
959 public:
960 explicit LoopbackProbeJob(const base::WeakPtr<HostResolverImpl>& resolver)
961 : resolver_(resolver),
962 result_(false) {
963 DCHECK(resolver);
964 const bool kIsSlow = true;
965 base::WorkerPool::PostTaskAndReply(
966 FROM_HERE,
967 base::Bind(&LoopbackProbeJob::DoProbe, base::Unretained(this)),
968 base::Bind(&LoopbackProbeJob::OnProbeComplete, base::Owned(this)),
969 kIsSlow);
970 }
971
972 virtual ~LoopbackProbeJob() {}
973
974 private:
975 // Runs on worker thread.
976 void DoProbe() {
977 result_ = HaveOnlyLoopbackAddresses();
978 }
979
980 void OnProbeComplete() {
981 if (!resolver_)
982 return;
983 resolver_->SetHaveOnlyLoopbackAddresses(result_);
984 }
985
986 // Used/set only on origin thread.
987 base::WeakPtr<HostResolverImpl> resolver_;
988
989 bool result_;
990
991 DISALLOW_COPY_AND_ASSIGN(LoopbackProbeJob);
992};
993
[email protected]0f8f1b432010-03-16 19:06:03994//-----------------------------------------------------------------------------
995
[email protected]b3601bc22012-02-21 21:23:20996// Resolves the hostname using DnsTransaction.
997// TODO(szym): This could be moved to separate source file as well.
[email protected]0adcb2b2012-08-15 21:30:46998class HostResolverImpl::DnsTask : public base::SupportsWeakPtr<DnsTask> {
[email protected]b3601bc22012-02-21 21:23:20999 public:
1000 typedef base::Callback<void(int net_error,
1001 const AddressList& addr_list,
1002 base::TimeDelta ttl)> Callback;
1003
[email protected]0adcb2b2012-08-15 21:30:461004 DnsTask(DnsClient* client,
[email protected]b3601bc22012-02-21 21:23:201005 const Key& key,
1006 const Callback& callback,
1007 const BoundNetLog& job_net_log)
[email protected]0adcb2b2012-08-15 21:30:461008 : client_(client),
1009 family_(key.address_family),
1010 callback_(callback),
1011 net_log_(job_net_log) {
1012 DCHECK(client);
[email protected]b3601bc22012-02-21 21:23:201013 DCHECK(!callback.is_null());
1014
[email protected]0adcb2b2012-08-15 21:30:461015 // If unspecified, do IPv4 first, because suffix search will be faster.
1016 uint16 qtype = (family_ == ADDRESS_FAMILY_IPV6) ?
1017 dns_protocol::kTypeAAAA :
1018 dns_protocol::kTypeA;
1019 transaction_ = client_->GetTransactionFactory()->CreateTransaction(
[email protected]b3601bc22012-02-21 21:23:201020 key.hostname,
1021 qtype,
[email protected]1def74c2012-03-22 20:07:001022 base::Bind(&DnsTask::OnTransactionComplete, base::Unretained(this),
[email protected]0adcb2b2012-08-15 21:30:461023 true /* first_query */, base::TimeTicks::Now()),
[email protected]b3601bc22012-02-21 21:23:201024 net_log_);
[email protected]b3601bc22012-02-21 21:23:201025 }
1026
1027 int Start() {
[email protected]4da911f2012-06-14 19:45:201028 net_log_.BeginEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK);
[email protected]b3601bc22012-02-21 21:23:201029 return transaction_->Start();
1030 }
1031
[email protected]0adcb2b2012-08-15 21:30:461032 private:
1033 void OnTransactionComplete(bool first_query,
1034 const base::TimeTicks& start_time,
[email protected]1def74c2012-03-22 20:07:001035 DnsTransaction* transaction,
[email protected]b3601bc22012-02-21 21:23:201036 int net_error,
1037 const DnsResponse* response) {
[email protected]add76532012-03-30 14:47:471038 DCHECK(transaction);
[email protected]02cd6982013-01-10 20:12:511039 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]b3601bc22012-02-21 21:23:201040 // Run |callback_| last since the owning Job will then delete this DnsTask.
[email protected]0adcb2b2012-08-15 21:30:461041 if (net_error != OK) {
[email protected]02cd6982013-01-10 20:12:511042 DNS_HISTOGRAM("AsyncDNS.TransactionFailure", duration);
[email protected]0adcb2b2012-08-15 21:30:461043 OnFailure(net_error, DnsResponse::DNS_PARSE_OK);
1044 return;
[email protected]6c411902012-08-14 22:36:361045 }
[email protected]0adcb2b2012-08-15 21:30:461046
1047 CHECK(response);
[email protected]02cd6982013-01-10 20:12:511048 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess", duration);
1049 switch (transaction->GetType()) {
1050 case dns_protocol::kTypeA:
1051 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess_A", duration);
1052 break;
1053 case dns_protocol::kTypeAAAA:
1054 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess_AAAA", duration);
1055 break;
1056 }
[email protected]0adcb2b2012-08-15 21:30:461057 AddressList addr_list;
1058 base::TimeDelta ttl;
1059 DnsResponse::Result result = response->ParseToAddressList(&addr_list, &ttl);
1060 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ParseToAddressList",
1061 result,
1062 DnsResponse::DNS_PARSE_RESULT_MAX);
1063 if (result != DnsResponse::DNS_PARSE_OK) {
1064 // Fail even if the other query succeeds.
1065 OnFailure(ERR_DNS_MALFORMED_RESPONSE, result);
1066 return;
1067 }
1068
1069 bool needs_sort = false;
1070 if (first_query) {
1071 DCHECK(client_->GetConfig()) <<
1072 "Transaction should have been aborted when config changed!";
1073 if (family_ == ADDRESS_FAMILY_IPV6) {
1074 needs_sort = (addr_list.size() > 1);
1075 } else if (family_ == ADDRESS_FAMILY_UNSPECIFIED) {
1076 first_addr_list_ = addr_list;
1077 first_ttl_ = ttl;
1078 // Use fully-qualified domain name to avoid search.
1079 transaction_ = client_->GetTransactionFactory()->CreateTransaction(
1080 response->GetDottedName() + ".",
1081 dns_protocol::kTypeAAAA,
1082 base::Bind(&DnsTask::OnTransactionComplete, base::Unretained(this),
1083 false /* first_query */, base::TimeTicks::Now()),
1084 net_log_);
1085 net_error = transaction_->Start();
1086 if (net_error != ERR_IO_PENDING)
1087 OnFailure(net_error, DnsResponse::DNS_PARSE_OK);
1088 return;
1089 }
1090 } else {
1091 DCHECK_EQ(ADDRESS_FAMILY_UNSPECIFIED, family_);
1092 bool has_ipv6_addresses = !addr_list.empty();
1093 if (!first_addr_list_.empty()) {
1094 ttl = std::min(ttl, first_ttl_);
1095 // Place IPv4 addresses after IPv6.
1096 addr_list.insert(addr_list.end(), first_addr_list_.begin(),
1097 first_addr_list_.end());
1098 }
1099 needs_sort = (has_ipv6_addresses && addr_list.size() > 1);
1100 }
1101
1102 if (addr_list.empty()) {
1103 // TODO(szym): Don't fallback to ProcTask in this case.
1104 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
1105 return;
1106 }
1107
1108 if (needs_sort) {
1109 // Sort could complete synchronously.
1110 client_->GetAddressSorter()->Sort(
1111 addr_list,
[email protected]4589a3a2012-09-20 20:57:071112 base::Bind(&DnsTask::OnSortComplete,
1113 AsWeakPtr(),
[email protected]0adcb2b2012-08-15 21:30:461114 base::TimeTicks::Now(),
1115 ttl));
1116 } else {
1117 OnSuccess(addr_list, ttl);
1118 }
1119 }
1120
1121 void OnSortComplete(base::TimeTicks start_time,
1122 base::TimeDelta ttl,
1123 bool success,
1124 const AddressList& addr_list) {
1125 if (!success) {
1126 DNS_HISTOGRAM("AsyncDNS.SortFailure",
1127 base::TimeTicks::Now() - start_time);
1128 OnFailure(ERR_DNS_SORT_ERROR, DnsResponse::DNS_PARSE_OK);
1129 return;
1130 }
1131
1132 DNS_HISTOGRAM("AsyncDNS.SortSuccess",
1133 base::TimeTicks::Now() - start_time);
1134
1135 // AddressSorter prunes unusable destinations.
1136 if (addr_list.empty()) {
1137 LOG(WARNING) << "Address list empty after RFC3484 sort";
1138 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
1139 return;
1140 }
1141
1142 OnSuccess(addr_list, ttl);
1143 }
1144
1145 void OnFailure(int net_error, DnsResponse::Result result) {
1146 DCHECK_NE(OK, net_error);
[email protected]cd565142012-06-12 16:21:451147 net_log_.EndEvent(
1148 NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK,
1149 base::Bind(&NetLogDnsTaskFailedCallback, net_error, result));
[email protected]b3601bc22012-02-21 21:23:201150 callback_.Run(net_error, AddressList(), base::TimeDelta());
1151 }
1152
[email protected]0adcb2b2012-08-15 21:30:461153 void OnSuccess(const AddressList& addr_list, base::TimeDelta ttl) {
1154 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK,
1155 addr_list.CreateNetLogCallback());
1156 callback_.Run(OK, addr_list, ttl);
1157 }
1158
1159 DnsClient* client_;
1160 AddressFamily family_;
[email protected]b3601bc22012-02-21 21:23:201161 // The listener to the results of this DnsTask.
1162 Callback callback_;
[email protected]b3601bc22012-02-21 21:23:201163 const BoundNetLog net_log_;
1164
1165 scoped_ptr<DnsTransaction> transaction_;
[email protected]0adcb2b2012-08-15 21:30:461166
1167 // Results from the first transaction. Used only if |family_| is unspecified.
1168 AddressList first_addr_list_;
1169 base::TimeDelta first_ttl_;
1170
1171 DISALLOW_COPY_AND_ASSIGN(DnsTask);
[email protected]b3601bc22012-02-21 21:23:201172};
1173
1174//-----------------------------------------------------------------------------
1175
[email protected]0f292de02012-02-01 22:28:201176// Aggregates all Requests for the same Key. Dispatched via PriorityDispatch.
[email protected]0f292de02012-02-01 22:28:201177class HostResolverImpl::Job : public PrioritizedDispatcher::Job {
[email protected]68ad3ee2010-01-30 03:45:391178 public:
[email protected]0f292de02012-02-01 22:28:201179 // Creates new job for |key| where |request_net_log| is bound to the
[email protected]16ee26d2012-03-08 03:34:351180 // request that spawned it.
[email protected]12faa4c2012-11-06 04:44:181181 Job(const base::WeakPtr<HostResolverImpl>& resolver,
[email protected]0f292de02012-02-01 22:28:201182 const Key& key,
[email protected]8c98d002012-07-18 19:02:271183 RequestPriority priority,
[email protected]16ee26d2012-03-08 03:34:351184 const BoundNetLog& request_net_log)
[email protected]12faa4c2012-11-06 04:44:181185 : resolver_(resolver),
[email protected]0f292de02012-02-01 22:28:201186 key_(key),
[email protected]8c98d002012-07-18 19:02:271187 priority_tracker_(priority),
[email protected]0f292de02012-02-01 22:28:201188 had_non_speculative_request_(false),
[email protected]51b9a6b2012-06-25 21:50:291189 had_dns_config_(false),
[email protected]1d932852012-06-19 19:40:331190 dns_task_error_(OK),
[email protected]51b9a6b2012-06-25 21:50:291191 creation_time_(base::TimeTicks::Now()),
1192 priority_change_time_(creation_time_),
[email protected]0f292de02012-02-01 22:28:201193 net_log_(BoundNetLog::Make(request_net_log.net_log(),
[email protected]b3601bc22012-02-21 21:23:201194 NetLog::SOURCE_HOST_RESOLVER_IMPL_JOB)) {
[email protected]4da911f2012-06-14 19:45:201195 request_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_CREATE_JOB);
[email protected]0f292de02012-02-01 22:28:201196
1197 net_log_.BeginEvent(
1198 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
[email protected]cd565142012-06-12 16:21:451199 base::Bind(&NetLogJobCreationCallback,
1200 request_net_log.source(),
1201 &key_.hostname));
[email protected]68ad3ee2010-01-30 03:45:391202 }
1203
[email protected]0f292de02012-02-01 22:28:201204 virtual ~Job() {
[email protected]b3601bc22012-02-21 21:23:201205 if (is_running()) {
1206 // |resolver_| was destroyed with this Job still in flight.
1207 // Clean-up, record in the log, but don't run any callbacks.
1208 if (is_proc_running()) {
[email protected]0f292de02012-02-01 22:28:201209 proc_task_->Cancel();
1210 proc_task_ = NULL;
[email protected]0f292de02012-02-01 22:28:201211 }
[email protected]16ee26d2012-03-08 03:34:351212 // Clean up now for nice NetLog.
1213 dns_task_.reset(NULL);
[email protected]b3601bc22012-02-21 21:23:201214 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
1215 ERR_ABORTED);
1216 } else if (is_queued()) {
[email protected]57a48d32012-03-03 00:04:551217 // |resolver_| was destroyed without running this Job.
[email protected]16ee26d2012-03-08 03:34:351218 // TODO(szym): is there any benefit in having this distinction?
[email protected]4da911f2012-06-14 19:45:201219 net_log_.AddEvent(NetLog::TYPE_CANCELLED);
1220 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB);
[email protected]68ad3ee2010-01-30 03:45:391221 }
[email protected]b3601bc22012-02-21 21:23:201222 // else CompleteRequests logged EndEvent.
[email protected]68ad3ee2010-01-30 03:45:391223
[email protected]b3601bc22012-02-21 21:23:201224 // Log any remaining Requests as cancelled.
1225 for (RequestsList::const_iterator it = requests_.begin();
1226 it != requests_.end(); ++it) {
1227 Request* req = *it;
1228 if (req->was_canceled())
1229 continue;
1230 DCHECK_EQ(this, req->job());
1231 LogCancelRequest(req->source_net_log(), req->request_net_log(),
1232 req->info());
1233 }
[email protected]68ad3ee2010-01-30 03:45:391234 }
1235
[email protected]16ee26d2012-03-08 03:34:351236 // Add this job to the dispatcher.
[email protected]8c98d002012-07-18 19:02:271237 void Schedule() {
1238 handle_ = resolver_->dispatcher_.Add(this, priority());
[email protected]16ee26d2012-03-08 03:34:351239 }
1240
[email protected]b3601bc22012-02-21 21:23:201241 void AddRequest(scoped_ptr<Request> req) {
[email protected]0f292de02012-02-01 22:28:201242 DCHECK_EQ(key_.hostname, req->info().hostname());
1243
1244 req->set_job(this);
[email protected]0f292de02012-02-01 22:28:201245 priority_tracker_.Add(req->info().priority());
1246
1247 req->request_net_log().AddEvent(
1248 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_ATTACH,
[email protected]cd565142012-06-12 16:21:451249 net_log_.source().ToEventParametersCallback());
[email protected]0f292de02012-02-01 22:28:201250
1251 net_log_.AddEvent(
1252 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_REQUEST_ATTACH,
[email protected]cd565142012-06-12 16:21:451253 base::Bind(&NetLogJobAttachCallback,
1254 req->request_net_log().source(),
1255 priority()));
[email protected]0f292de02012-02-01 22:28:201256
1257 // TODO(szym): Check if this is still needed.
1258 if (!req->info().is_speculative()) {
1259 had_non_speculative_request_ = true;
1260 if (proc_task_)
1261 proc_task_->set_had_non_speculative_request();
[email protected]68ad3ee2010-01-30 03:45:391262 }
[email protected]b3601bc22012-02-21 21:23:201263
1264 requests_.push_back(req.release());
1265
[email protected]51b9a6b2012-06-25 21:50:291266 UpdatePriority();
[email protected]68ad3ee2010-01-30 03:45:391267 }
1268
[email protected]16ee26d2012-03-08 03:34:351269 // Marks |req| as cancelled. If it was the last active Request, also finishes
[email protected]0adcb2b2012-08-15 21:30:461270 // this Job, marking it as cancelled, and deletes it.
[email protected]0f292de02012-02-01 22:28:201271 void CancelRequest(Request* req) {
1272 DCHECK_EQ(key_.hostname, req->info().hostname());
1273 DCHECK(!req->was_canceled());
[email protected]16ee26d2012-03-08 03:34:351274
[email protected]0f292de02012-02-01 22:28:201275 // Don't remove it from |requests_| just mark it canceled.
1276 req->MarkAsCanceled();
1277 LogCancelRequest(req->source_net_log(), req->request_net_log(),
1278 req->info());
[email protected]16ee26d2012-03-08 03:34:351279
[email protected]0f292de02012-02-01 22:28:201280 priority_tracker_.Remove(req->info().priority());
1281 net_log_.AddEvent(
1282 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_REQUEST_DETACH,
[email protected]cd565142012-06-12 16:21:451283 base::Bind(&NetLogJobAttachCallback,
1284 req->request_net_log().source(),
1285 priority()));
[email protected]b3601bc22012-02-21 21:23:201286
[email protected]16ee26d2012-03-08 03:34:351287 if (num_active_requests() > 0) {
[email protected]51b9a6b2012-06-25 21:50:291288 UpdatePriority();
[email protected]16ee26d2012-03-08 03:34:351289 } else {
1290 // If we were called from a Request's callback within CompleteRequests,
1291 // that Request could not have been cancelled, so num_active_requests()
1292 // could not be 0. Therefore, we are not in CompleteRequests().
[email protected]1339a2a22012-10-17 08:39:431293 CompleteRequestsWithError(OK /* cancelled */);
[email protected]b3601bc22012-02-21 21:23:201294 }
[email protected]68ad3ee2010-01-30 03:45:391295 }
1296
[email protected]7af985a2012-12-14 22:40:421297 // Called from AbortAllInProgressJobs. Completes all requests and destroys
1298 // the job. This currently assumes the abort is due to a network change.
[email protected]0f292de02012-02-01 22:28:201299 void Abort() {
[email protected]0f292de02012-02-01 22:28:201300 DCHECK(is_running());
[email protected]7af985a2012-12-14 22:40:421301 CompleteRequestsWithError(ERR_NETWORK_CHANGED);
[email protected]b3601bc22012-02-21 21:23:201302 }
1303
[email protected]f0f602bd2012-11-15 18:01:021304 // If DnsTask present, abort it and fall back to ProcTask.
1305 void AbortDnsTask() {
1306 if (dns_task_) {
1307 dns_task_.reset();
1308 dns_task_error_ = OK;
1309 StartProcTask();
1310 }
1311 }
1312
[email protected]16ee26d2012-03-08 03:34:351313 // Called by HostResolverImpl when this job is evicted due to queue overflow.
1314 // Completes all requests and destroys the job.
1315 void OnEvicted() {
1316 DCHECK(!is_running());
1317 DCHECK(is_queued());
1318 handle_.Reset();
1319
[email protected]4da911f2012-06-14 19:45:201320 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_EVICTED);
[email protected]16ee26d2012-03-08 03:34:351321
1322 // This signals to CompleteRequests that this job never ran.
[email protected]1339a2a22012-10-17 08:39:431323 CompleteRequestsWithError(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
[email protected]16ee26d2012-03-08 03:34:351324 }
1325
[email protected]78eac2a2012-03-14 19:09:271326 // Attempts to serve the job from HOSTS. Returns true if succeeded and
1327 // this Job was destroyed.
1328 bool ServeFromHosts() {
1329 DCHECK_GT(num_active_requests(), 0u);
1330 AddressList addr_list;
1331 if (resolver_->ServeFromHosts(key(),
[email protected]3cb676a12012-06-30 15:46:031332 requests_.front()->info(),
[email protected]78eac2a2012-03-14 19:09:271333 &addr_list)) {
1334 // This will destroy the Job.
[email protected]895123222012-10-25 15:21:171335 CompleteRequests(
1336 HostCache::Entry(OK, MakeAddressListForRequest(addr_list)),
1337 base::TimeDelta());
[email protected]78eac2a2012-03-14 19:09:271338 return true;
1339 }
1340 return false;
1341 }
1342
[email protected]b4481b222012-03-16 17:13:111343 const Key key() const {
1344 return key_;
1345 }
1346
1347 bool is_queued() const {
1348 return !handle_.is_null();
1349 }
1350
1351 bool is_running() const {
1352 return is_dns_running() || is_proc_running();
1353 }
1354
[email protected]16ee26d2012-03-08 03:34:351355 private:
[email protected]51b9a6b2012-06-25 21:50:291356 void UpdatePriority() {
1357 if (is_queued()) {
1358 if (priority() != static_cast<RequestPriority>(handle_.priority()))
1359 priority_change_time_ = base::TimeTicks::Now();
1360 handle_ = resolver_->dispatcher_.ChangePriority(handle_, priority());
1361 }
1362 }
1363
[email protected]895123222012-10-25 15:21:171364 AddressList MakeAddressListForRequest(const AddressList& list) const {
1365 if (requests_.empty())
1366 return list;
1367 return AddressList::CopyWithPort(list, requests_.front()->info().port());
1368 }
1369
[email protected]16ee26d2012-03-08 03:34:351370 // PriorityDispatch::Job:
[email protected]0f292de02012-02-01 22:28:201371 virtual void Start() OVERRIDE {
1372 DCHECK(!is_running());
[email protected]b3601bc22012-02-21 21:23:201373 handle_.Reset();
[email protected]0f292de02012-02-01 22:28:201374
[email protected]4da911f2012-06-14 19:45:201375 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_STARTED);
[email protected]0f292de02012-02-01 22:28:201376
[email protected]51b9a6b2012-06-25 21:50:291377 had_dns_config_ = resolver_->HaveDnsConfig();
1378
1379 base::TimeTicks now = base::TimeTicks::Now();
1380 base::TimeDelta queue_time = now - creation_time_;
1381 base::TimeDelta queue_time_after_change = now - priority_change_time_;
1382
1383 if (had_dns_config_) {
1384 DNS_HISTOGRAM_BY_PRIORITY("AsyncDNS.JobQueueTime", priority(),
1385 queue_time);
1386 DNS_HISTOGRAM_BY_PRIORITY("AsyncDNS.JobQueueTimeAfterChange", priority(),
1387 queue_time_after_change);
1388 } else {
1389 DNS_HISTOGRAM_BY_PRIORITY("DNS.JobQueueTime", priority(), queue_time);
1390 DNS_HISTOGRAM_BY_PRIORITY("DNS.JobQueueTimeAfterChange", priority(),
1391 queue_time_after_change);
1392 }
1393
[email protected]1d932852012-06-19 19:40:331394 // Caution: Job::Start must not complete synchronously.
[email protected]51b9a6b2012-06-25 21:50:291395 if (had_dns_config_ && !ResemblesMulticastDNSName(key_.hostname)) {
[email protected]b3601bc22012-02-21 21:23:201396 StartDnsTask();
1397 } else {
1398 StartProcTask();
1399 }
1400 }
1401
[email protected]b3601bc22012-02-21 21:23:201402 // TODO(szym): Since DnsTransaction does not consume threads, we can increase
1403 // the limits on |dispatcher_|. But in order to keep the number of WorkerPool
1404 // threads low, we will need to use an "inner" PrioritizedDispatcher with
1405 // tighter limits.
1406 void StartProcTask() {
[email protected]16ee26d2012-03-08 03:34:351407 DCHECK(!is_dns_running());
[email protected]0f292de02012-02-01 22:28:201408 proc_task_ = new ProcTask(
1409 key_,
1410 resolver_->proc_params_,
[email protected]e3bd4822012-10-23 18:01:371411 base::Bind(&Job::OnProcTaskComplete, base::Unretained(this),
1412 base::TimeTicks::Now()),
[email protected]0f292de02012-02-01 22:28:201413 net_log_);
1414
1415 if (had_non_speculative_request_)
1416 proc_task_->set_had_non_speculative_request();
1417 // Start() could be called from within Resolve(), hence it must NOT directly
1418 // call OnProcTaskComplete, for example, on synchronous failure.
1419 proc_task_->Start();
[email protected]68ad3ee2010-01-30 03:45:391420 }
1421
[email protected]0f292de02012-02-01 22:28:201422 // Called by ProcTask when it completes.
[email protected]e3bd4822012-10-23 18:01:371423 void OnProcTaskComplete(base::TimeTicks start_time,
1424 int net_error,
1425 const AddressList& addr_list) {
[email protected]b3601bc22012-02-21 21:23:201426 DCHECK(is_proc_running());
[email protected]68ad3ee2010-01-30 03:45:391427
[email protected]62e86ba2013-01-29 18:59:161428 if (!resolver_->resolved_known_ipv6_hostname_ &&
1429 net_error == OK &&
1430 key_.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
1431 if (key_.hostname == "www.google.com") {
1432 resolver_->resolved_known_ipv6_hostname_ = true;
1433 bool got_ipv6_address = false;
1434 for (size_t i = 0; i < addr_list.size(); ++i) {
1435 if (addr_list[i].GetFamily() == ADDRESS_FAMILY_IPV6)
1436 got_ipv6_address = true;
1437 }
1438 UMA_HISTOGRAM_BOOLEAN("Net.UnspecResolvedIPv6", got_ipv6_address);
1439 }
1440 }
1441
[email protected]1d932852012-06-19 19:40:331442 if (dns_task_error_ != OK) {
[email protected]e3bd4822012-10-23 18:01:371443 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]1def74c2012-03-22 20:07:001444 if (net_error == OK) {
[email protected]e3bd4822012-10-23 18:01:371445 DNS_HISTOGRAM("AsyncDNS.FallbackSuccess", duration);
[email protected]1d932852012-06-19 19:40:331446 if ((dns_task_error_ == ERR_NAME_NOT_RESOLVED) &&
1447 ResemblesNetBIOSName(key_.hostname)) {
1448 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_SUSPECT_NETBIOS);
1449 } else {
1450 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_PROC_SUCCESS);
1451 }
1452 UMA_HISTOGRAM_CUSTOM_ENUMERATION("AsyncDNS.ResolveError",
1453 std::abs(dns_task_error_),
1454 GetAllErrorCodesForUma());
[email protected]1ffdda82012-12-12 23:04:221455 resolver_->OnDnsTaskResolve(dns_task_error_);
[email protected]1def74c2012-03-22 20:07:001456 } else {
[email protected]e3bd4822012-10-23 18:01:371457 DNS_HISTOGRAM("AsyncDNS.FallbackFail", duration);
[email protected]1def74c2012-03-22 20:07:001458 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
1459 }
1460 }
1461
[email protected]1339a2a22012-10-17 08:39:431462 base::TimeDelta ttl =
1463 base::TimeDelta::FromSeconds(kNegativeCacheEntryTTLSeconds);
[email protected]b3601bc22012-02-21 21:23:201464 if (net_error == OK)
1465 ttl = base::TimeDelta::FromSeconds(kCacheEntryTTLSeconds);
[email protected]68ad3ee2010-01-30 03:45:391466
[email protected]895123222012-10-25 15:21:171467 // Don't store the |ttl| in cache since it's not obtained from the server.
1468 CompleteRequests(
1469 HostCache::Entry(net_error, MakeAddressListForRequest(addr_list)),
1470 ttl);
[email protected]b3601bc22012-02-21 21:23:201471 }
1472
1473 void StartDnsTask() {
[email protected]78eac2a2012-03-14 19:09:271474 DCHECK(resolver_->HaveDnsConfig());
[email protected]b3601bc22012-02-21 21:23:201475 dns_task_.reset(new DnsTask(
[email protected]0adcb2b2012-08-15 21:30:461476 resolver_->dns_client_.get(),
[email protected]b3601bc22012-02-21 21:23:201477 key_,
[email protected]e3bd4822012-10-23 18:01:371478 base::Bind(&Job::OnDnsTaskComplete, base::Unretained(this),
1479 base::TimeTicks::Now()),
[email protected]b3601bc22012-02-21 21:23:201480 net_log_));
1481
1482 int rv = dns_task_->Start();
1483 if (rv != ERR_IO_PENDING) {
1484 DCHECK_NE(OK, rv);
[email protected]51b9a6b2012-06-25 21:50:291485 dns_task_error_ = rv;
[email protected]b3601bc22012-02-21 21:23:201486 dns_task_.reset();
1487 StartProcTask();
1488 }
1489 }
1490
1491 // Called by DnsTask when it completes.
[email protected]e3bd4822012-10-23 18:01:371492 void OnDnsTaskComplete(base::TimeTicks start_time,
1493 int net_error,
[email protected]b3601bc22012-02-21 21:23:201494 const AddressList& addr_list,
1495 base::TimeDelta ttl) {
1496 DCHECK(is_dns_running());
[email protected]b3601bc22012-02-21 21:23:201497
[email protected]e3bd4822012-10-23 18:01:371498 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]b3601bc22012-02-21 21:23:201499 if (net_error != OK) {
[email protected]e3bd4822012-10-23 18:01:371500 DNS_HISTOGRAM("AsyncDNS.ResolveFail", duration);
1501
[email protected]1d932852012-06-19 19:40:331502 dns_task_error_ = net_error;
[email protected]16ee26d2012-03-08 03:34:351503 dns_task_.reset();
[email protected]78eac2a2012-03-14 19:09:271504
1505 // TODO(szym): Run ServeFromHosts now if nsswitch.conf says so.
1506 // http://crbug.com/117655
1507
[email protected]b3601bc22012-02-21 21:23:201508 // TODO(szym): Some net errors indicate lack of connectivity. Starting
1509 // ProcTask in that case is a waste of time.
1510 StartProcTask();
1511 return;
1512 }
[email protected]e3bd4822012-10-23 18:01:371513 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess", duration);
[email protected]02cd6982013-01-10 20:12:511514 // Log DNS lookups based on |address_family|.
1515 switch(key_.address_family) {
1516 case ADDRESS_FAMILY_IPV4:
1517 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_IPV4", duration);
1518 break;
1519 case ADDRESS_FAMILY_IPV6:
1520 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_IPV6", duration);
1521 break;
1522 case ADDRESS_FAMILY_UNSPECIFIED:
1523 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_UNSPEC", duration);
1524 break;
1525 }
[email protected]b3601bc22012-02-21 21:23:201526
[email protected]1def74c2012-03-22 20:07:001527 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_DNS_SUCCESS);
[email protected]1339a2a22012-10-17 08:39:431528 RecordTTL(ttl);
[email protected]0adcb2b2012-08-15 21:30:461529
[email protected]1ffdda82012-12-12 23:04:221530 resolver_->OnDnsTaskResolve(OK);
[email protected]f0f602bd2012-11-15 18:01:021531
[email protected]895123222012-10-25 15:21:171532 base::TimeDelta bounded_ttl =
1533 std::max(ttl, base::TimeDelta::FromSeconds(kMinimumTTLSeconds));
1534
1535 CompleteRequests(
1536 HostCache::Entry(net_error, MakeAddressListForRequest(addr_list), ttl),
1537 bounded_ttl);
[email protected]b3601bc22012-02-21 21:23:201538 }
1539
[email protected]16ee26d2012-03-08 03:34:351540 // Performs Job's last rites. Completes all Requests. Deletes this.
[email protected]895123222012-10-25 15:21:171541 void CompleteRequests(const HostCache::Entry& entry,
1542 base::TimeDelta ttl) {
[email protected]b3601bc22012-02-21 21:23:201543 CHECK(resolver_);
[email protected]b3601bc22012-02-21 21:23:201544
[email protected]16ee26d2012-03-08 03:34:351545 // This job must be removed from resolver's |jobs_| now to make room for a
1546 // new job with the same key in case one of the OnComplete callbacks decides
1547 // to spawn one. Consequently, the job deletes itself when CompleteRequests
1548 // is done.
1549 scoped_ptr<Job> self_deleter(this);
1550
1551 resolver_->RemoveJob(this);
1552
[email protected]16ee26d2012-03-08 03:34:351553 if (is_running()) {
1554 DCHECK(!is_queued());
1555 if (is_proc_running()) {
1556 proc_task_->Cancel();
1557 proc_task_ = NULL;
1558 }
1559 dns_task_.reset();
1560
1561 // Signal dispatcher that a slot has opened.
1562 resolver_->dispatcher_.OnJobFinished();
1563 } else if (is_queued()) {
1564 resolver_->dispatcher_.Cancel(handle_);
1565 handle_.Reset();
1566 }
1567
1568 if (num_active_requests() == 0) {
[email protected]4da911f2012-06-14 19:45:201569 net_log_.AddEvent(NetLog::TYPE_CANCELLED);
[email protected]16ee26d2012-03-08 03:34:351570 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
1571 OK);
1572 return;
1573 }
[email protected]b3601bc22012-02-21 21:23:201574
1575 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
[email protected]895123222012-10-25 15:21:171576 entry.error);
[email protected]68ad3ee2010-01-30 03:45:391577
[email protected]78eac2a2012-03-14 19:09:271578 DCHECK(!requests_.empty());
1579
[email protected]895123222012-10-25 15:21:171580 if (entry.error == OK) {
[email protected]d7b9a2b2012-05-31 22:31:191581 // Record this histogram here, when we know the system has a valid DNS
1582 // configuration.
[email protected]539df6c2012-06-19 21:21:291583 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.HaveDnsConfig",
1584 resolver_->received_dns_config_);
[email protected]d7b9a2b2012-05-31 22:31:191585 }
[email protected]16ee26d2012-03-08 03:34:351586
[email protected]7af985a2012-12-14 22:40:421587 bool did_complete = (entry.error != ERR_NETWORK_CHANGED) &&
[email protected]895123222012-10-25 15:21:171588 (entry.error != ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
1589 if (did_complete)
[email protected]1339a2a22012-10-17 08:39:431590 resolver_->CacheResult(key_, entry, ttl);
[email protected]16ee26d2012-03-08 03:34:351591
[email protected]0f292de02012-02-01 22:28:201592 // Complete all of the requests that were attached to the job.
1593 for (RequestsList::const_iterator it = requests_.begin();
1594 it != requests_.end(); ++it) {
1595 Request* req = *it;
1596
1597 if (req->was_canceled())
1598 continue;
1599
1600 DCHECK_EQ(this, req->job());
1601 // Update the net log and notify registered observers.
1602 LogFinishRequest(req->source_net_log(), req->request_net_log(),
[email protected]895123222012-10-25 15:21:171603 req->info(), entry.error);
[email protected]51b9a6b2012-06-25 21:50:291604 if (did_complete) {
1605 // Record effective total time from creation to completion.
1606 RecordTotalTime(had_dns_config_, req->info().is_speculative(),
1607 base::TimeTicks::Now() - req->request_time());
1608 }
[email protected]895123222012-10-25 15:21:171609 req->OnComplete(entry.error, entry.addrlist);
[email protected]0f292de02012-02-01 22:28:201610
1611 // Check if the resolver was destroyed as a result of running the
1612 // callback. If it was, we could continue, but we choose to bail.
1613 if (!resolver_)
1614 return;
1615 }
1616 }
1617
[email protected]1339a2a22012-10-17 08:39:431618 // Convenience wrapper for CompleteRequests in case of failure.
1619 void CompleteRequestsWithError(int net_error) {
[email protected]895123222012-10-25 15:21:171620 CompleteRequests(HostCache::Entry(net_error, AddressList()),
1621 base::TimeDelta());
[email protected]1339a2a22012-10-17 08:39:431622 }
1623
[email protected]b4481b222012-03-16 17:13:111624 RequestPriority priority() const {
1625 return priority_tracker_.highest_priority();
1626 }
1627
1628 // Number of non-canceled requests in |requests_|.
1629 size_t num_active_requests() const {
1630 return priority_tracker_.total_count();
1631 }
1632
1633 bool is_dns_running() const {
1634 return dns_task_.get() != NULL;
1635 }
1636
1637 bool is_proc_running() const {
1638 return proc_task_.get() != NULL;
1639 }
1640
[email protected]0f292de02012-02-01 22:28:201641 base::WeakPtr<HostResolverImpl> resolver_;
1642
1643 Key key_;
1644
1645 // Tracks the highest priority across |requests_|.
1646 PriorityTracker priority_tracker_;
1647
1648 bool had_non_speculative_request_;
1649
[email protected]51b9a6b2012-06-25 21:50:291650 // Distinguishes measurements taken while DnsClient was fully configured.
1651 bool had_dns_config_;
1652
[email protected]1d932852012-06-19 19:40:331653 // Result of DnsTask.
1654 int dns_task_error_;
[email protected]1def74c2012-03-22 20:07:001655
[email protected]51b9a6b2012-06-25 21:50:291656 const base::TimeTicks creation_time_;
1657 base::TimeTicks priority_change_time_;
1658
[email protected]0f292de02012-02-01 22:28:201659 BoundNetLog net_log_;
1660
[email protected]b3601bc22012-02-21 21:23:201661 // Resolves the host using a HostResolverProc.
[email protected]0f292de02012-02-01 22:28:201662 scoped_refptr<ProcTask> proc_task_;
1663
[email protected]b3601bc22012-02-21 21:23:201664 // Resolves the host using a DnsTransaction.
1665 scoped_ptr<DnsTask> dns_task_;
1666
[email protected]0f292de02012-02-01 22:28:201667 // All Requests waiting for the result of this Job. Some can be canceled.
1668 RequestsList requests_;
1669
[email protected]16ee26d2012-03-08 03:34:351670 // A handle used in |HostResolverImpl::dispatcher_|.
[email protected]0f292de02012-02-01 22:28:201671 PrioritizedDispatcher::Handle handle_;
[email protected]68ad3ee2010-01-30 03:45:391672};
1673
1674//-----------------------------------------------------------------------------
1675
[email protected]0f292de02012-02-01 22:28:201676HostResolverImpl::ProcTaskParams::ProcTaskParams(
[email protected]e95d3aca2010-01-11 22:47:431677 HostResolverProc* resolver_proc,
[email protected]0f292de02012-02-01 22:28:201678 size_t max_retry_attempts)
1679 : resolver_proc(resolver_proc),
1680 max_retry_attempts(max_retry_attempts),
1681 unresponsive_delay(base::TimeDelta::FromMilliseconds(6000)),
1682 retry_factor(2) {
1683}
1684
1685HostResolverImpl::ProcTaskParams::~ProcTaskParams() {}
1686
1687HostResolverImpl::HostResolverImpl(
[email protected]c54a8912012-10-22 22:09:431688 scoped_ptr<HostCache> cache,
[email protected]0f292de02012-02-01 22:28:201689 const PrioritizedDispatcher::Limits& job_limits,
1690 const ProcTaskParams& proc_params,
[email protected]ee094b82010-08-24 15:55:511691 NetLog* net_log)
[email protected]c54a8912012-10-22 22:09:431692 : cache_(cache.Pass()),
[email protected]0f292de02012-02-01 22:28:201693 dispatcher_(job_limits),
1694 max_queued_jobs_(job_limits.total_jobs * 100u),
1695 proc_params_(proc_params),
[email protected]62e86ba2013-01-29 18:59:161696 net_log_(net_log),
[email protected]0c7798452009-10-26 17:59:511697 default_address_family_(ADDRESS_FAMILY_UNSPECIFIED),
[email protected]4589a3a2012-09-20 20:57:071698 weak_ptr_factory_(this),
[email protected]12faa4c2012-11-06 04:44:181699 probe_weak_ptr_factory_(this),
[email protected]d7b9a2b2012-05-31 22:31:191700 received_dns_config_(false),
[email protected]f0f602bd2012-11-15 18:01:021701 num_dns_failures_(0),
[email protected]2f3bc65c2010-07-23 17:47:101702 ipv6_probe_monitoring_(false),
[email protected]62e86ba2013-01-29 18:59:161703 resolved_known_ipv6_hostname_(false),
1704 additional_resolver_flags_(0) {
[email protected]0f292de02012-02-01 22:28:201705
1706 DCHECK_GE(dispatcher_.num_priorities(), static_cast<size_t>(NUM_PRIORITIES));
[email protected]68ad3ee2010-01-30 03:45:391707
[email protected]06ef6d92011-05-19 04:24:581708 // Maximum of 4 retry attempts for host resolution.
1709 static const size_t kDefaultMaxRetryAttempts = 4u;
1710
[email protected]0f292de02012-02-01 22:28:201711 if (proc_params_.max_retry_attempts == HostResolver::kDefaultRetryAttempts)
1712 proc_params_.max_retry_attempts = kDefaultMaxRetryAttempts;
[email protected]68ad3ee2010-01-30 03:45:391713
[email protected]b59ff372009-07-15 22:04:321714#if defined(OS_WIN)
1715 EnsureWinsockInit();
1716#endif
[email protected]23f771162011-06-02 18:37:511717#if defined(OS_POSIX) && !defined(OS_MACOSX)
[email protected]12faa4c2012-11-06 04:44:181718 new LoopbackProbeJob(weak_ptr_factory_.GetWeakPtr());
[email protected]2f3bc65c2010-07-23 17:47:101719#endif
[email protected]232a5812011-03-04 22:42:081720 NetworkChangeNotifier::AddIPAddressObserver(this);
[email protected]bb0e34542012-08-31 19:52:401721 NetworkChangeNotifier::AddDNSObserver(this);
[email protected]d7b9a2b2012-05-31 22:31:191722#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD) && \
1723 !defined(OS_ANDROID)
[email protected]d7b9a2b2012-05-31 22:31:191724 EnsureDnsReloaderInit();
[email protected]46018c9d2011-09-06 03:42:341725#endif
[email protected]2ac22db2012-11-28 19:50:041726
1727 // TODO(szym): Remove when received_dns_config_ is removed, once
1728 // http://crbug.com/137914 is resolved.
1729 {
1730 DnsConfig dns_config;
1731 NetworkChangeNotifier::GetDnsConfig(&dns_config);
1732 received_dns_config_ = dns_config.IsValid();
1733 }
[email protected]b59ff372009-07-15 22:04:321734}
1735
1736HostResolverImpl::~HostResolverImpl() {
[email protected]0f292de02012-02-01 22:28:201737 // This will also cancel all outstanding requests.
1738 STLDeleteValues(&jobs_);
[email protected]e95d3aca2010-01-11 22:47:431739
[email protected]232a5812011-03-04 22:42:081740 NetworkChangeNotifier::RemoveIPAddressObserver(this);
[email protected]bb0e34542012-08-31 19:52:401741 NetworkChangeNotifier::RemoveDNSObserver(this);
[email protected]b59ff372009-07-15 22:04:321742}
1743
[email protected]0f292de02012-02-01 22:28:201744void HostResolverImpl::SetMaxQueuedJobs(size_t value) {
1745 DCHECK_EQ(0u, dispatcher_.num_queued_jobs());
1746 DCHECK_GT(value, 0u);
1747 max_queued_jobs_ = value;
[email protected]be1a48b2011-01-20 00:12:131748}
1749
[email protected]684970b2009-08-14 04:54:461750int HostResolverImpl::Resolve(const RequestInfo& info,
[email protected]b59ff372009-07-15 22:04:321751 AddressList* addresses,
[email protected]aa22b242011-11-16 18:58:291752 const CompletionCallback& callback,
[email protected]684970b2009-08-14 04:54:461753 RequestHandle* out_req,
[email protected]ee094b82010-08-24 15:55:511754 const BoundNetLog& source_net_log) {
[email protected]95a214c2011-08-04 21:50:401755 DCHECK(addresses);
[email protected]1ac6af92010-06-03 21:00:141756 DCHECK(CalledOnValidThread());
[email protected]aa22b242011-11-16 18:58:291757 DCHECK_EQ(false, callback.is_null());
[email protected]1ac6af92010-06-03 21:00:141758
[email protected]ee094b82010-08-24 15:55:511759 // Make a log item for the request.
1760 BoundNetLog request_net_log = BoundNetLog::Make(net_log_,
1761 NetLog::SOURCE_HOST_RESOLVER_IMPL_REQUEST);
1762
[email protected]0f292de02012-02-01 22:28:201763 LogStartRequest(source_net_log, request_net_log, info);
[email protected]b59ff372009-07-15 22:04:321764
[email protected]123ab1e32009-10-21 19:12:571765 // Build a key that identifies the request in the cache and in the
1766 // outstanding jobs map.
[email protected]137af622010-02-05 02:14:351767 Key key = GetEffectiveKeyForRequest(info);
[email protected]123ab1e32009-10-21 19:12:571768
[email protected]287d7c22011-11-15 17:34:251769 int rv = ResolveHelper(key, info, addresses, request_net_log);
[email protected]95a214c2011-08-04 21:50:401770 if (rv != ERR_DNS_CACHE_MISS) {
[email protected]b3601bc22012-02-21 21:23:201771 LogFinishRequest(source_net_log, request_net_log, info, rv);
[email protected]51b9a6b2012-06-25 21:50:291772 RecordTotalTime(HaveDnsConfig(), info.is_speculative(), base::TimeDelta());
[email protected]95a214c2011-08-04 21:50:401773 return rv;
[email protected]38368712011-03-02 08:09:401774 }
1775
[email protected]0f292de02012-02-01 22:28:201776 // Next we need to attach our request to a "job". This job is responsible for
1777 // calling "getaddrinfo(hostname)" on a worker thread.
1778
1779 JobMap::iterator jobit = jobs_.find(key);
1780 Job* job;
1781 if (jobit == jobs_.end()) {
[email protected]12faa4c2012-11-06 04:44:181782 job = new Job(weak_ptr_factory_.GetWeakPtr(), key, info.priority(),
1783 request_net_log);
[email protected]8c98d002012-07-18 19:02:271784 job->Schedule();
[email protected]0f292de02012-02-01 22:28:201785
1786 // Check for queue overflow.
1787 if (dispatcher_.num_queued_jobs() > max_queued_jobs_) {
1788 Job* evicted = static_cast<Job*>(dispatcher_.EvictOldestLowest());
1789 DCHECK(evicted);
[email protected]16ee26d2012-03-08 03:34:351790 evicted->OnEvicted(); // Deletes |evicted|.
[email protected]0f292de02012-02-01 22:28:201791 if (evicted == job) {
[email protected]0f292de02012-02-01 22:28:201792 rv = ERR_HOST_RESOLVER_QUEUE_TOO_LARGE;
[email protected]b3601bc22012-02-21 21:23:201793 LogFinishRequest(source_net_log, request_net_log, info, rv);
[email protected]0f292de02012-02-01 22:28:201794 return rv;
1795 }
[email protected]0f292de02012-02-01 22:28:201796 }
[email protected]0f292de02012-02-01 22:28:201797 jobs_.insert(jobit, std::make_pair(key, job));
1798 } else {
1799 job = jobit->second;
1800 }
1801
1802 // Can't complete synchronously. Create and attach request.
[email protected]b3601bc22012-02-21 21:23:201803 scoped_ptr<Request> req(new Request(source_net_log,
1804 request_net_log,
1805 info,
1806 callback,
1807 addresses));
[email protected]b59ff372009-07-15 22:04:321808 if (out_req)
[email protected]b3601bc22012-02-21 21:23:201809 *out_req = reinterpret_cast<RequestHandle>(req.get());
[email protected]b59ff372009-07-15 22:04:321810
[email protected]b3601bc22012-02-21 21:23:201811 job->AddRequest(req.Pass());
[email protected]0f292de02012-02-01 22:28:201812 // Completion happens during Job::CompleteRequests().
[email protected]b59ff372009-07-15 22:04:321813 return ERR_IO_PENDING;
1814}
1815
[email protected]287d7c22011-11-15 17:34:251816int HostResolverImpl::ResolveHelper(const Key& key,
[email protected]95a214c2011-08-04 21:50:401817 const RequestInfo& info,
1818 AddressList* addresses,
[email protected]20cd5332011-10-12 22:38:001819 const BoundNetLog& request_net_log) {
[email protected]95a214c2011-08-04 21:50:401820 // The result of |getaddrinfo| for empty hosts is inconsistent across systems.
1821 // On Windows it gives the default interface's address, whereas on Linux it
1822 // gives an error. We will make it fail on all platforms for consistency.
1823 if (info.hostname().empty() || info.hostname().size() > kMaxHostLength)
1824 return ERR_NAME_NOT_RESOLVED;
1825
1826 int net_error = ERR_UNEXPECTED;
1827 if (ResolveAsIP(key, info, &net_error, addresses))
1828 return net_error;
[email protected]78eac2a2012-03-14 19:09:271829 if (ServeFromCache(key, info, &net_error, addresses)) {
[email protected]4da911f2012-06-14 19:45:201830 request_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_CACHE_HIT);
[email protected]78eac2a2012-03-14 19:09:271831 return net_error;
1832 }
1833 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
1834 // http://crbug.com/117655
1835 if (ServeFromHosts(key, info, addresses)) {
[email protected]4da911f2012-06-14 19:45:201836 request_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_HOSTS_HIT);
[email protected]78eac2a2012-03-14 19:09:271837 return OK;
1838 }
1839 return ERR_DNS_CACHE_MISS;
[email protected]95a214c2011-08-04 21:50:401840}
1841
1842int HostResolverImpl::ResolveFromCache(const RequestInfo& info,
1843 AddressList* addresses,
1844 const BoundNetLog& source_net_log) {
1845 DCHECK(CalledOnValidThread());
1846 DCHECK(addresses);
1847
[email protected]95a214c2011-08-04 21:50:401848 // Make a log item for the request.
1849 BoundNetLog request_net_log = BoundNetLog::Make(net_log_,
1850 NetLog::SOURCE_HOST_RESOLVER_IMPL_REQUEST);
1851
1852 // Update the net log and notify registered observers.
[email protected]0f292de02012-02-01 22:28:201853 LogStartRequest(source_net_log, request_net_log, info);
[email protected]95a214c2011-08-04 21:50:401854
[email protected]95a214c2011-08-04 21:50:401855 Key key = GetEffectiveKeyForRequest(info);
1856
[email protected]287d7c22011-11-15 17:34:251857 int rv = ResolveHelper(key, info, addresses, request_net_log);
[email protected]b3601bc22012-02-21 21:23:201858 LogFinishRequest(source_net_log, request_net_log, info, rv);
[email protected]95a214c2011-08-04 21:50:401859 return rv;
1860}
1861
[email protected]b59ff372009-07-15 22:04:321862void HostResolverImpl::CancelRequest(RequestHandle req_handle) {
[email protected]1ac6af92010-06-03 21:00:141863 DCHECK(CalledOnValidThread());
[email protected]b59ff372009-07-15 22:04:321864 Request* req = reinterpret_cast<Request*>(req_handle);
1865 DCHECK(req);
[email protected]0f292de02012-02-01 22:28:201866 Job* job = req->job();
1867 DCHECK(job);
[email protected]0f292de02012-02-01 22:28:201868 job->CancelRequest(req);
[email protected]b59ff372009-07-15 22:04:321869}
1870
[email protected]0f8f1b432010-03-16 19:06:031871void HostResolverImpl::SetDefaultAddressFamily(AddressFamily address_family) {
[email protected]1ac6af92010-06-03 21:00:141872 DCHECK(CalledOnValidThread());
[email protected]0f8f1b432010-03-16 19:06:031873 default_address_family_ = address_family;
[email protected]12faa4c2012-11-06 04:44:181874 ipv6_probe_monitoring_ = false;
[email protected]0f8f1b432010-03-16 19:06:031875}
1876
[email protected]f7d310e2010-10-07 16:25:111877AddressFamily HostResolverImpl::GetDefaultAddressFamily() const {
1878 return default_address_family_;
1879}
1880
[email protected]9db6f702013-04-10 18:10:511881// TODO(szym): Remove this API altogether if IPv6ActiveProbe works.
[email protected]a78f4272011-10-21 19:16:331882void HostResolverImpl::ProbeIPv6Support() {
1883 DCHECK(CalledOnValidThread());
1884 DCHECK(!ipv6_probe_monitoring_);
1885 ipv6_probe_monitoring_ = true;
[email protected]12faa4c2012-11-06 04:44:181886 OnIPAddressChanged();
[email protected]ddb1e5a2010-12-13 20:10:451887}
1888
[email protected]a8883e452012-11-17 05:58:061889void HostResolverImpl::SetDnsClientEnabled(bool enabled) {
1890 DCHECK(CalledOnValidThread());
1891#if defined(ENABLE_BUILT_IN_DNS)
1892 if (enabled && !dns_client_) {
1893 SetDnsClient(DnsClient::CreateClient(net_log_));
1894 } else if (!enabled && dns_client_) {
1895 SetDnsClient(scoped_ptr<DnsClient>());
1896 }
1897#endif
1898}
1899
[email protected]489d1a82011-10-12 03:09:111900HostCache* HostResolverImpl::GetHostCache() {
1901 return cache_.get();
1902}
[email protected]95a214c2011-08-04 21:50:401903
[email protected]17e92032012-03-29 00:56:241904base::Value* HostResolverImpl::GetDnsConfigAsValue() const {
1905 // Check if async DNS is disabled.
1906 if (!dns_client_.get())
1907 return NULL;
1908
1909 // Check if async DNS is enabled, but we currently have no configuration
1910 // for it.
1911 const DnsConfig* dns_config = dns_client_->GetConfig();
1912 if (dns_config == NULL)
1913 return new DictionaryValue();
1914
1915 return dns_config->ToValue();
1916}
1917
[email protected]95a214c2011-08-04 21:50:401918bool HostResolverImpl::ResolveAsIP(const Key& key,
1919 const RequestInfo& info,
1920 int* net_error,
1921 AddressList* addresses) {
1922 DCHECK(addresses);
1923 DCHECK(net_error);
1924 IPAddressNumber ip_number;
1925 if (!ParseIPLiteralToNumber(key.hostname, &ip_number))
1926 return false;
1927
1928 DCHECK_EQ(key.host_resolver_flags &
1929 ~(HOST_RESOLVER_CANONNAME | HOST_RESOLVER_LOOPBACK_ONLY |
1930 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6),
1931 0) << " Unhandled flag";
[email protected]0f292de02012-02-01 22:28:201932 bool ipv6_disabled = (default_address_family_ == ADDRESS_FAMILY_IPV4) &&
1933 !ipv6_probe_monitoring_;
[email protected]95a214c2011-08-04 21:50:401934 *net_error = OK;
[email protected]0f292de02012-02-01 22:28:201935 if ((ip_number.size() == kIPv6AddressSize) && ipv6_disabled) {
[email protected]95a214c2011-08-04 21:50:401936 *net_error = ERR_NAME_NOT_RESOLVED;
1937 } else {
[email protected]7054e78f2012-05-07 21:44:561938 *addresses = AddressList::CreateFromIPAddress(ip_number, info.port());
1939 if (key.host_resolver_flags & HOST_RESOLVER_CANONNAME)
1940 addresses->SetDefaultCanonicalName();
[email protected]95a214c2011-08-04 21:50:401941 }
1942 return true;
1943}
1944
1945bool HostResolverImpl::ServeFromCache(const Key& key,
1946 const RequestInfo& info,
[email protected]95a214c2011-08-04 21:50:401947 int* net_error,
1948 AddressList* addresses) {
1949 DCHECK(addresses);
1950 DCHECK(net_error);
1951 if (!info.allow_cached_response() || !cache_.get())
1952 return false;
1953
[email protected]407a30ab2012-08-15 17:16:101954 const HostCache::Entry* cache_entry = cache_->Lookup(
1955 key, base::TimeTicks::Now());
[email protected]95a214c2011-08-04 21:50:401956 if (!cache_entry)
1957 return false;
1958
[email protected]95a214c2011-08-04 21:50:401959 *net_error = cache_entry->error;
[email protected]7054e78f2012-05-07 21:44:561960 if (*net_error == OK) {
[email protected]1339a2a22012-10-17 08:39:431961 if (cache_entry->has_ttl())
1962 RecordTTL(cache_entry->ttl);
[email protected]895123222012-10-25 15:21:171963 *addresses = EnsurePortOnAddressList(cache_entry->addrlist, info.port());
[email protected]7054e78f2012-05-07 21:44:561964 }
[email protected]95a214c2011-08-04 21:50:401965 return true;
1966}
1967
[email protected]78eac2a2012-03-14 19:09:271968bool HostResolverImpl::ServeFromHosts(const Key& key,
1969 const RequestInfo& info,
1970 AddressList* addresses) {
1971 DCHECK(addresses);
1972 if (!HaveDnsConfig())
1973 return false;
1974
[email protected]05a79d42013-03-28 07:30:091975 addresses->clear();
1976
[email protected]cb507622012-03-23 16:17:061977 // HOSTS lookups are case-insensitive.
1978 std::string hostname = StringToLowerASCII(key.hostname);
1979
[email protected]05a79d42013-03-28 07:30:091980 const DnsHosts& hosts = dns_client_->GetConfig()->hosts;
1981
[email protected]78eac2a2012-03-14 19:09:271982 // If |address_family| is ADDRESS_FAMILY_UNSPECIFIED other implementations
1983 // (glibc and c-ares) return the first matching line. We have more
1984 // flexibility, but lose implicit ordering.
[email protected]05a79d42013-03-28 07:30:091985 // We prefer IPv6 because "happy eyeballs" will fall back to IPv4 if
1986 // necessary.
1987 if (key.address_family == ADDRESS_FAMILY_IPV6 ||
1988 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
1989 DnsHosts::const_iterator it = hosts.find(
1990 DnsHostsKey(hostname, ADDRESS_FAMILY_IPV6));
1991 if (it != hosts.end())
1992 addresses->push_back(IPEndPoint(it->second, info.port()));
[email protected]78eac2a2012-03-14 19:09:271993 }
1994
[email protected]05a79d42013-03-28 07:30:091995 if (key.address_family == ADDRESS_FAMILY_IPV4 ||
1996 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
1997 DnsHosts::const_iterator it = hosts.find(
1998 DnsHostsKey(hostname, ADDRESS_FAMILY_IPV4));
1999 if (it != hosts.end())
2000 addresses->push_back(IPEndPoint(it->second, info.port()));
2001 }
2002
2003 return !addresses->empty();
[email protected]78eac2a2012-03-14 19:09:272004}
2005
[email protected]16ee26d2012-03-08 03:34:352006void HostResolverImpl::CacheResult(const Key& key,
[email protected]1339a2a22012-10-17 08:39:432007 const HostCache::Entry& entry,
[email protected]16ee26d2012-03-08 03:34:352008 base::TimeDelta ttl) {
2009 if (cache_.get())
[email protected]1339a2a22012-10-17 08:39:432010 cache_->Set(key, entry, base::TimeTicks::Now(), ttl);
[email protected]ef4c40c2010-09-01 14:42:032011}
2012
[email protected]0f292de02012-02-01 22:28:202013void HostResolverImpl::RemoveJob(Job* job) {
2014 DCHECK(job);
[email protected]16ee26d2012-03-08 03:34:352015 JobMap::iterator it = jobs_.find(job->key());
2016 if (it != jobs_.end() && it->second == job)
2017 jobs_.erase(it);
[email protected]b59ff372009-07-15 22:04:322018}
2019
[email protected]0f8f1b432010-03-16 19:06:032020void HostResolverImpl::IPv6ProbeSetDefaultAddressFamily(
2021 AddressFamily address_family) {
2022 DCHECK(address_family == ADDRESS_FAMILY_UNSPECIFIED ||
2023 address_family == ADDRESS_FAMILY_IPV4);
[email protected]12faa4c2012-11-06 04:44:182024 if (!ipv6_probe_monitoring_)
2025 return;
[email protected]f092e64b2010-03-17 00:39:182026 if (default_address_family_ != address_family) {
[email protected]b30a3f52010-10-16 01:05:462027 VLOG(1) << "IPv6Probe forced AddressFamily setting to "
2028 << ((address_family == ADDRESS_FAMILY_UNSPECIFIED) ?
2029 "ADDRESS_FAMILY_UNSPECIFIED" : "ADDRESS_FAMILY_IPV4");
[email protected]f092e64b2010-03-17 00:39:182030 }
[email protected]0f8f1b432010-03-16 19:06:032031 default_address_family_ = address_family;
[email protected]e95d3aca2010-01-11 22:47:432032}
2033
[email protected]9936a7862012-10-26 04:44:022034void HostResolverImpl::SetHaveOnlyLoopbackAddresses(bool result) {
2035 if (result) {
2036 additional_resolver_flags_ |= HOST_RESOLVER_LOOPBACK_ONLY;
2037 } else {
2038 additional_resolver_flags_ &= ~HOST_RESOLVER_LOOPBACK_ONLY;
2039 }
2040}
2041
[email protected]137af622010-02-05 02:14:352042HostResolverImpl::Key HostResolverImpl::GetEffectiveKeyForRequest(
2043 const RequestInfo& info) const {
[email protected]eaf3a3b2010-09-03 20:34:272044 HostResolverFlags effective_flags =
2045 info.host_resolver_flags() | additional_resolver_flags_;
[email protected]137af622010-02-05 02:14:352046 AddressFamily effective_address_family = info.address_family();
[email protected]9db6f702013-04-10 18:10:512047
2048 if (info.address_family() == ADDRESS_FAMILY_UNSPECIFIED) {
2049 base::TimeTicks start_time = base::TimeTicks::Now();
2050 // Google DNS address.
2051 const uint8 kIPv6Address[] =
2052 { 0x20, 0x01, 0x48, 0x60, 0x48, 0x60, 0x00, 0x00,
2053 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x88 };
[email protected]e9051722013-04-12 21:58:182054 bool rv6 = IsGloballyReachable(
[email protected]9db6f702013-04-10 18:10:512055 IPAddressNumber(kIPv6Address, kIPv6Address + arraysize(kIPv6Address)));
2056
2057 UMA_HISTOGRAM_TIMES("Net.IPv6ConnectDuration",
2058 base::TimeTicks::Now() - start_time);
[email protected]e9051722013-04-12 21:58:182059 if (rv6) {
[email protected]9db6f702013-04-10 18:10:512060 UMA_HISTOGRAM_BOOLEAN("Net.IPv6ConnectSuccessMatch",
2061 default_address_family_ == ADDRESS_FAMILY_UNSPECIFIED);
2062 } else {
2063 UMA_HISTOGRAM_BOOLEAN("Net.IPv6ConnectFailureMatch",
2064 default_address_family_ != ADDRESS_FAMILY_UNSPECIFIED);
2065 }
2066 }
2067
[email protected]eaf3a3b2010-09-03 20:34:272068 if (effective_address_family == ADDRESS_FAMILY_UNSPECIFIED &&
2069 default_address_family_ != ADDRESS_FAMILY_UNSPECIFIED) {
[email protected]137af622010-02-05 02:14:352070 effective_address_family = default_address_family_;
[email protected]eaf3a3b2010-09-03 20:34:272071 if (ipv6_probe_monitoring_)
2072 effective_flags |= HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
2073 }
[email protected]9db6f702013-04-10 18:10:512074
[email protected]eaf3a3b2010-09-03 20:34:272075 return Key(info.hostname(), effective_address_family, effective_flags);
[email protected]137af622010-02-05 02:14:352076}
2077
[email protected]35ddc282010-09-21 23:42:062078void HostResolverImpl::AbortAllInProgressJobs() {
[email protected]b3601bc22012-02-21 21:23:202079 // In Abort, a Request callback could spawn new Jobs with matching keys, so
2080 // first collect and remove all running jobs from |jobs_|.
[email protected]c143d892012-04-06 07:56:542081 ScopedVector<Job> jobs_to_abort;
[email protected]0f292de02012-02-01 22:28:202082 for (JobMap::iterator it = jobs_.begin(); it != jobs_.end(); ) {
2083 Job* job = it->second;
[email protected]0f292de02012-02-01 22:28:202084 if (job->is_running()) {
[email protected]b3601bc22012-02-21 21:23:202085 jobs_to_abort.push_back(job);
2086 jobs_.erase(it++);
[email protected]0f292de02012-02-01 22:28:202087 } else {
[email protected]b3601bc22012-02-21 21:23:202088 DCHECK(job->is_queued());
2089 ++it;
[email protected]0f292de02012-02-01 22:28:202090 }
[email protected]ef4c40c2010-09-01 14:42:032091 }
[email protected]b3601bc22012-02-21 21:23:202092
[email protected]57a48d32012-03-03 00:04:552093 // Check if no dispatcher slots leaked out.
2094 DCHECK_EQ(dispatcher_.num_running_jobs(), jobs_to_abort.size());
2095
2096 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072097 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]57a48d32012-03-03 00:04:552098
[email protected]16ee26d2012-03-08 03:34:352099 // Then Abort them.
[email protected]57a48d32012-03-03 00:04:552100 for (size_t i = 0; self && i < jobs_to_abort.size(); ++i) {
[email protected]57a48d32012-03-03 00:04:552101 jobs_to_abort[i]->Abort();
[email protected]c143d892012-04-06 07:56:542102 jobs_to_abort[i] = NULL;
[email protected]b3601bc22012-02-21 21:23:202103 }
[email protected]ef4c40c2010-09-01 14:42:032104}
2105
[email protected]78eac2a2012-03-14 19:09:272106void HostResolverImpl::TryServingAllJobsFromHosts() {
2107 if (!HaveDnsConfig())
2108 return;
2109
2110 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2111 // http://crbug.com/117655
2112
2113 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072114 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]78eac2a2012-03-14 19:09:272115
2116 for (JobMap::iterator it = jobs_.begin(); self && it != jobs_.end(); ) {
2117 Job* job = it->second;
2118 ++it;
2119 // This could remove |job| from |jobs_|, but iterator will remain valid.
2120 job->ServeFromHosts();
2121 }
2122}
2123
[email protected]be1a48b2011-01-20 00:12:132124void HostResolverImpl::OnIPAddressChanged() {
[email protected]62e86ba2013-01-29 18:59:162125 resolved_known_ipv6_hostname_ = false;
[email protected]12faa4c2012-11-06 04:44:182126 // Abandon all ProbeJobs.
2127 probe_weak_ptr_factory_.InvalidateWeakPtrs();
[email protected]be1a48b2011-01-20 00:12:132128 if (cache_.get())
2129 cache_->clear();
[email protected]12faa4c2012-11-06 04:44:182130 if (ipv6_probe_monitoring_)
2131 new IPv6ProbeJob(probe_weak_ptr_factory_.GetWeakPtr(), net_log_);
[email protected]23f771162011-06-02 18:37:512132#if defined(OS_POSIX) && !defined(OS_MACOSX)
[email protected]12faa4c2012-11-06 04:44:182133 new LoopbackProbeJob(probe_weak_ptr_factory_.GetWeakPtr());
[email protected]be1a48b2011-01-20 00:12:132134#endif
2135 AbortAllInProgressJobs();
2136 // |this| may be deleted inside AbortAllInProgressJobs().
2137}
2138
[email protected]bb0e34542012-08-31 19:52:402139void HostResolverImpl::OnDNSChanged() {
2140 DnsConfig dns_config;
2141 NetworkChangeNotifier::GetDnsConfig(&dns_config);
[email protected]b4481b222012-03-16 17:13:112142 if (net_log_) {
2143 net_log_->AddGlobalEntry(
2144 NetLog::TYPE_DNS_CONFIG_CHANGED,
[email protected]cd565142012-06-12 16:21:452145 base::Bind(&NetLogDnsConfigCallback, &dns_config));
[email protected]b4481b222012-03-16 17:13:112146 }
2147
[email protected]01b3b9d2012-08-13 16:18:142148 // TODO(szym): Remove once http://crbug.com/137914 is resolved.
[email protected]d7b9a2b2012-05-31 22:31:192149 received_dns_config_ = dns_config.IsValid();
[email protected]78eac2a2012-03-14 19:09:272150
[email protected]a8883e452012-11-17 05:58:062151 num_dns_failures_ = 0;
2152
[email protected]01b3b9d2012-08-13 16:18:142153 // We want a new DnsSession in place, before we Abort running Jobs, so that
2154 // the newly started jobs use the new config.
[email protected]f0f602bd2012-11-15 18:01:022155 if (dns_client_.get()) {
[email protected]d7b9a2b2012-05-31 22:31:192156 dns_client_->SetConfig(dns_config);
[email protected]a8883e452012-11-17 05:58:062157 if (dns_config.IsValid())
[email protected]f0f602bd2012-11-15 18:01:022158 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
[email protected]f0f602bd2012-11-15 18:01:022159 }
[email protected]01b3b9d2012-08-13 16:18:142160
2161 // If the DNS server has changed, existing cached info could be wrong so we
2162 // have to drop our internal cache :( Note that OS level DNS caches, such
2163 // as NSCD's cache should be dropped automatically by the OS when
2164 // resolv.conf changes so we don't need to do anything to clear that cache.
2165 if (cache_.get())
2166 cache_->clear();
2167
[email protected]f0f602bd2012-11-15 18:01:022168 // Life check to bail once |this| is deleted.
2169 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
2170
[email protected]01b3b9d2012-08-13 16:18:142171 // Existing jobs will have been sent to the original server so they need to
2172 // be aborted.
2173 AbortAllInProgressJobs();
2174
2175 // |this| may be deleted inside AbortAllInProgressJobs().
2176 if (self)
2177 TryServingAllJobsFromHosts();
[email protected]78eac2a2012-03-14 19:09:272178}
2179
2180bool HostResolverImpl::HaveDnsConfig() const {
[email protected]32b1dbcf2013-01-26 03:48:252181 // Use DnsClient only if it's fully configured and there is no override by
2182 // ScopedDefaultHostResolverProc.
2183 // The alternative is to use NetworkChangeNotifier to override DnsConfig,
2184 // but that would introduce construction order requirements for NCN and SDHRP.
2185 return (dns_client_.get() != NULL) &&
2186 (dns_client_->GetConfig() != NULL) &&
2187 !(proc_params_.resolver_proc == NULL &&
2188 HostResolverProc::GetDefault() != NULL);
[email protected]b3601bc22012-02-21 21:23:202189}
2190
[email protected]1ffdda82012-12-12 23:04:222191void HostResolverImpl::OnDnsTaskResolve(int net_error) {
[email protected]f0f602bd2012-11-15 18:01:022192 DCHECK(dns_client_);
[email protected]1ffdda82012-12-12 23:04:222193 if (net_error == OK) {
[email protected]f0f602bd2012-11-15 18:01:022194 num_dns_failures_ = 0;
2195 return;
2196 }
2197 ++num_dns_failures_;
2198 if (num_dns_failures_ < kMaximumDnsFailures)
2199 return;
2200 // Disable DnsClient until the next DNS change.
2201 for (JobMap::iterator it = jobs_.begin(); it != jobs_.end(); ++it)
2202 it->second->AbortDnsTask();
2203 dns_client_->SetConfig(DnsConfig());
2204 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", false);
[email protected]1ffdda82012-12-12 23:04:222205 UMA_HISTOGRAM_CUSTOM_ENUMERATION("AsyncDNS.DnsClientDisabledReason",
2206 std::abs(net_error),
2207 GetAllErrorCodesForUma());
[email protected]f0f602bd2012-11-15 18:01:022208}
2209
[email protected]a8883e452012-11-17 05:58:062210void HostResolverImpl::SetDnsClient(scoped_ptr<DnsClient> dns_client) {
2211 if (HaveDnsConfig()) {
2212 for (JobMap::iterator it = jobs_.begin(); it != jobs_.end(); ++it)
2213 it->second->AbortDnsTask();
2214 }
2215 dns_client_ = dns_client.Pass();
2216 if (!dns_client_ || dns_client_->GetConfig() ||
2217 num_dns_failures_ >= kMaximumDnsFailures) {
2218 return;
2219 }
2220 DnsConfig dns_config;
2221 NetworkChangeNotifier::GetDnsConfig(&dns_config);
2222 dns_client_->SetConfig(dns_config);
2223 num_dns_failures_ = 0;
2224 if (dns_config.IsValid())
2225 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
2226}
2227
[email protected]b59ff372009-07-15 22:04:322228} // namespace net