blob: 9a082fb11c9a4c265f90381251d00e0308e9848e [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.
173int AttemptRoute(const IPAddressNumber& dest) {
174 scoped_ptr<DatagramClientSocket> socket(
175 ClientSocketFactory::GetDefaultFactory()->CreateDatagramClientSocket(
176 DatagramSocket::DEFAULT_BIND,
177 RandIntCallback(),
178 NULL,
179 NetLog::Source()));
180 return socket->Connect(IPEndPoint(dest, 80));
181}
182
[email protected]51b9a6b2012-06-25 21:50:29183// Provide a common macro to simplify code and readability. We must use a
184// macro as the underlying HISTOGRAM macro creates static variables.
185#define DNS_HISTOGRAM(name, time) UMA_HISTOGRAM_CUSTOM_TIMES(name, time, \
186 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromHours(1), 100)
187
188// A macro to simplify code and readability.
189#define DNS_HISTOGRAM_BY_PRIORITY(basename, priority, time) \
190 do { \
191 switch (priority) { \
192 case HIGHEST: DNS_HISTOGRAM(basename "_HIGHEST", time); break; \
193 case MEDIUM: DNS_HISTOGRAM(basename "_MEDIUM", time); break; \
194 case LOW: DNS_HISTOGRAM(basename "_LOW", time); break; \
195 case LOWEST: DNS_HISTOGRAM(basename "_LOWEST", time); break; \
196 case IDLE: DNS_HISTOGRAM(basename "_IDLE", time); break; \
197 default: NOTREACHED(); break; \
198 } \
199 DNS_HISTOGRAM(basename, time); \
200 } while (0)
201
202// Record time from Request creation until a valid DNS response.
203void RecordTotalTime(bool had_dns_config,
204 bool speculative,
205 base::TimeDelta duration) {
206 if (had_dns_config) {
207 if (speculative) {
208 DNS_HISTOGRAM("AsyncDNS.TotalTime_speculative", duration);
209 } else {
210 DNS_HISTOGRAM("AsyncDNS.TotalTime", duration);
211 }
212 } else {
213 if (speculative) {
214 DNS_HISTOGRAM("DNS.TotalTime_speculative", duration);
215 } else {
216 DNS_HISTOGRAM("DNS.TotalTime", duration);
217 }
218 }
219}
220
[email protected]1339a2a22012-10-17 08:39:43221void RecordTTL(base::TimeDelta ttl) {
222 UMA_HISTOGRAM_CUSTOM_TIMES("AsyncDNS.TTL", ttl,
223 base::TimeDelta::FromSeconds(1),
224 base::TimeDelta::FromDays(1), 100);
225}
226
[email protected]d7b9a2b2012-05-31 22:31:19227//-----------------------------------------------------------------------------
228
[email protected]0f292de02012-02-01 22:28:20229// Wraps call to SystemHostResolverProc as an instance of HostResolverProc.
230// TODO(szym): This should probably be declared in host_resolver_proc.h.
231class CallSystemHostResolverProc : public HostResolverProc {
232 public:
233 CallSystemHostResolverProc() : HostResolverProc(NULL) {}
234 virtual int Resolve(const std::string& hostname,
235 AddressFamily address_family,
236 HostResolverFlags host_resolver_flags,
[email protected]b3601bc22012-02-21 21:23:20237 AddressList* addr_list,
[email protected]0f292de02012-02-01 22:28:20238 int* os_error) OVERRIDE {
239 return SystemHostResolverProc(hostname,
240 address_family,
241 host_resolver_flags,
[email protected]b3601bc22012-02-21 21:23:20242 addr_list,
[email protected]0f292de02012-02-01 22:28:20243 os_error);
[email protected]b59ff372009-07-15 22:04:32244 }
[email protected]a9813302012-04-28 09:29:28245
246 protected:
247 virtual ~CallSystemHostResolverProc() {}
[email protected]0f292de02012-02-01 22:28:20248};
[email protected]b59ff372009-07-15 22:04:32249
[email protected]895123222012-10-25 15:21:17250AddressList EnsurePortOnAddressList(const AddressList& list, uint16 port) {
251 if (list.empty() || list.front().port() == port)
252 return list;
253 return AddressList::CopyWithPort(list, port);
[email protected]7054e78f2012-05-07 21:44:56254}
255
[email protected]cd565142012-06-12 16:21:45256// Creates NetLog parameters when the resolve failed.
257base::Value* NetLogProcTaskFailedCallback(uint32 attempt_number,
258 int net_error,
259 int os_error,
260 NetLog::LogLevel /* log_level */) {
261 DictionaryValue* dict = new DictionaryValue();
262 if (attempt_number)
263 dict->SetInteger("attempt_number", attempt_number);
[email protected]21526002010-05-16 19:42:46264
[email protected]cd565142012-06-12 16:21:45265 dict->SetInteger("net_error", net_error);
[email protected]13024882011-05-18 23:19:16266
[email protected]cd565142012-06-12 16:21:45267 if (os_error) {
268 dict->SetInteger("os_error", os_error);
[email protected]21526002010-05-16 19:42:46269#if defined(OS_POSIX)
[email protected]cd565142012-06-12 16:21:45270 dict->SetString("os_error_string", gai_strerror(os_error));
[email protected]21526002010-05-16 19:42:46271#elif defined(OS_WIN)
[email protected]cd565142012-06-12 16:21:45272 // Map the error code to a human-readable string.
273 LPWSTR error_string = NULL;
274 int size = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
275 FORMAT_MESSAGE_FROM_SYSTEM,
276 0, // Use the internal message table.
277 os_error,
278 0, // Use default language.
279 (LPWSTR)&error_string,
280 0, // Buffer size.
281 0); // Arguments (unused).
282 dict->SetString("os_error_string", WideToUTF8(error_string));
283 LocalFree(error_string);
[email protected]21526002010-05-16 19:42:46284#endif
[email protected]21526002010-05-16 19:42:46285 }
286
[email protected]cd565142012-06-12 16:21:45287 return dict;
288}
[email protected]a9813302012-04-28 09:29:28289
[email protected]cd565142012-06-12 16:21:45290// Creates NetLog parameters when the DnsTask failed.
291base::Value* NetLogDnsTaskFailedCallback(int net_error,
292 int dns_error,
293 NetLog::LogLevel /* log_level */) {
294 DictionaryValue* dict = new DictionaryValue();
295 dict->SetInteger("net_error", net_error);
296 if (dns_error)
297 dict->SetInteger("dns_error", dns_error);
298 return dict;
[email protected]ee094b82010-08-24 15:55:51299};
300
[email protected]cd565142012-06-12 16:21:45301// Creates NetLog parameters containing the information in a RequestInfo object,
302// along with the associated NetLog::Source.
303base::Value* NetLogRequestInfoCallback(const NetLog::Source& source,
304 const HostResolver::RequestInfo* info,
305 NetLog::LogLevel /* log_level */) {
306 DictionaryValue* dict = new DictionaryValue();
307 source.AddToEventParameters(dict);
[email protected]b3601bc22012-02-21 21:23:20308
[email protected]cd565142012-06-12 16:21:45309 dict->SetString("host", info->host_port_pair().ToString());
310 dict->SetInteger("address_family",
311 static_cast<int>(info->address_family()));
312 dict->SetBoolean("allow_cached_response", info->allow_cached_response());
313 dict->SetBoolean("is_speculative", info->is_speculative());
314 dict->SetInteger("priority", info->priority());
315 return dict;
316}
[email protected]b3601bc22012-02-21 21:23:20317
[email protected]cd565142012-06-12 16:21:45318// Creates NetLog parameters for the creation of a HostResolverImpl::Job.
319base::Value* NetLogJobCreationCallback(const NetLog::Source& source,
320 const std::string* host,
321 NetLog::LogLevel /* log_level */) {
322 DictionaryValue* dict = new DictionaryValue();
323 source.AddToEventParameters(dict);
324 dict->SetString("host", *host);
325 return dict;
326}
[email protected]a9813302012-04-28 09:29:28327
[email protected]cd565142012-06-12 16:21:45328// Creates NetLog parameters for HOST_RESOLVER_IMPL_JOB_ATTACH/DETACH events.
329base::Value* NetLogJobAttachCallback(const NetLog::Source& source,
330 RequestPriority priority,
331 NetLog::LogLevel /* log_level */) {
332 DictionaryValue* dict = new DictionaryValue();
333 source.AddToEventParameters(dict);
334 dict->SetInteger("priority", priority);
335 return dict;
336}
[email protected]b3601bc22012-02-21 21:23:20337
[email protected]cd565142012-06-12 16:21:45338// Creates NetLog parameters for the DNS_CONFIG_CHANGED event.
339base::Value* NetLogDnsConfigCallback(const DnsConfig* config,
340 NetLog::LogLevel /* log_level */) {
341 return config->ToValue();
342}
[email protected]b4481b222012-03-16 17:13:11343
[email protected]0f292de02012-02-01 22:28:20344// The logging routines are defined here because some requests are resolved
345// without a Request object.
346
347// Logs when a request has just been started.
348void LogStartRequest(const BoundNetLog& source_net_log,
349 const BoundNetLog& request_net_log,
350 const HostResolver::RequestInfo& info) {
351 source_net_log.BeginEvent(
352 NetLog::TYPE_HOST_RESOLVER_IMPL,
[email protected]cd565142012-06-12 16:21:45353 request_net_log.source().ToEventParametersCallback());
[email protected]0f292de02012-02-01 22:28:20354
355 request_net_log.BeginEvent(
356 NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST,
[email protected]cd565142012-06-12 16:21:45357 base::Bind(&NetLogRequestInfoCallback, source_net_log.source(), &info));
[email protected]0f292de02012-02-01 22:28:20358}
359
360// Logs when a request has just completed (before its callback is run).
361void LogFinishRequest(const BoundNetLog& source_net_log,
362 const BoundNetLog& request_net_log,
363 const HostResolver::RequestInfo& info,
[email protected]b3601bc22012-02-21 21:23:20364 int net_error) {
365 request_net_log.EndEventWithNetErrorCode(
366 NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST, net_error);
[email protected]4da911f2012-06-14 19:45:20367 source_net_log.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL);
[email protected]0f292de02012-02-01 22:28:20368}
369
370// Logs when a request has been cancelled.
371void LogCancelRequest(const BoundNetLog& source_net_log,
372 const BoundNetLog& request_net_log,
373 const HostResolverImpl::RequestInfo& info) {
[email protected]4da911f2012-06-14 19:45:20374 request_net_log.AddEvent(NetLog::TYPE_CANCELLED);
375 request_net_log.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST);
376 source_net_log.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL);
[email protected]0f292de02012-02-01 22:28:20377}
378
[email protected]b59ff372009-07-15 22:04:32379//-----------------------------------------------------------------------------
380
[email protected]0f292de02012-02-01 22:28:20381// Keeps track of the highest priority.
382class PriorityTracker {
383 public:
[email protected]8c98d002012-07-18 19:02:27384 explicit PriorityTracker(RequestPriority initial_priority)
385 : highest_priority_(initial_priority), total_count_(0) {
[email protected]0f292de02012-02-01 22:28:20386 memset(counts_, 0, sizeof(counts_));
387 }
388
389 RequestPriority highest_priority() const {
390 return highest_priority_;
391 }
392
393 size_t total_count() const {
394 return total_count_;
395 }
396
397 void Add(RequestPriority req_priority) {
398 ++total_count_;
399 ++counts_[req_priority];
[email protected]31ae7ab2012-04-24 21:09:05400 if (highest_priority_ < req_priority)
[email protected]0f292de02012-02-01 22:28:20401 highest_priority_ = req_priority;
402 }
403
404 void Remove(RequestPriority req_priority) {
405 DCHECK_GT(total_count_, 0u);
406 DCHECK_GT(counts_[req_priority], 0u);
407 --total_count_;
408 --counts_[req_priority];
409 size_t i;
[email protected]31ae7ab2012-04-24 21:09:05410 for (i = highest_priority_; i > MINIMUM_PRIORITY && !counts_[i]; --i);
[email protected]0f292de02012-02-01 22:28:20411 highest_priority_ = static_cast<RequestPriority>(i);
412
[email protected]31ae7ab2012-04-24 21:09:05413 // In absence of requests, default to MINIMUM_PRIORITY.
414 if (total_count_ == 0)
415 DCHECK_EQ(MINIMUM_PRIORITY, highest_priority_);
[email protected]0f292de02012-02-01 22:28:20416 }
417
418 private:
419 RequestPriority highest_priority_;
420 size_t total_count_;
421 size_t counts_[NUM_PRIORITIES];
422};
423
[email protected]c54a8912012-10-22 22:09:43424} // namespace
[email protected]0f292de02012-02-01 22:28:20425
426//-----------------------------------------------------------------------------
427
428// Holds the data for a request that could not be completed synchronously.
429// It is owned by a Job. Canceled Requests are only marked as canceled rather
430// than removed from the Job's |requests_| list.
[email protected]b59ff372009-07-15 22:04:32431class HostResolverImpl::Request {
432 public:
[email protected]ee094b82010-08-24 15:55:51433 Request(const BoundNetLog& source_net_log,
434 const BoundNetLog& request_net_log,
[email protected]54e13772009-08-14 03:01:09435 const RequestInfo& info,
[email protected]aa22b242011-11-16 18:58:29436 const CompletionCallback& callback,
[email protected]b59ff372009-07-15 22:04:32437 AddressList* addresses)
[email protected]ee094b82010-08-24 15:55:51438 : source_net_log_(source_net_log),
439 request_net_log_(request_net_log),
[email protected]54e13772009-08-14 03:01:09440 info_(info),
441 job_(NULL),
442 callback_(callback),
[email protected]51b9a6b2012-06-25 21:50:29443 addresses_(addresses),
444 request_time_(base::TimeTicks::Now()) {
[email protected]54e13772009-08-14 03:01:09445 }
[email protected]b59ff372009-07-15 22:04:32446
[email protected]0f292de02012-02-01 22:28:20447 // Mark the request as canceled.
448 void MarkAsCanceled() {
[email protected]b59ff372009-07-15 22:04:32449 job_ = NULL;
[email protected]b59ff372009-07-15 22:04:32450 addresses_ = NULL;
[email protected]aa22b242011-11-16 18:58:29451 callback_.Reset();
[email protected]b59ff372009-07-15 22:04:32452 }
453
[email protected]0f292de02012-02-01 22:28:20454 bool was_canceled() const {
[email protected]aa22b242011-11-16 18:58:29455 return callback_.is_null();
[email protected]b59ff372009-07-15 22:04:32456 }
457
458 void set_job(Job* job) {
[email protected]0f292de02012-02-01 22:28:20459 DCHECK(job);
[email protected]b59ff372009-07-15 22:04:32460 // Identify which job the request is waiting on.
461 job_ = job;
462 }
463
[email protected]0f292de02012-02-01 22:28:20464 // Prepare final AddressList and call completion callback.
[email protected]b3601bc22012-02-21 21:23:20465 void OnComplete(int error, const AddressList& addr_list) {
[email protected]51b9a6b2012-06-25 21:50:29466 DCHECK(!was_canceled());
[email protected]895123222012-10-25 15:21:17467 if (error == OK)
468 *addresses_ = EnsurePortOnAddressList(addr_list, info_.port());
[email protected]aa22b242011-11-16 18:58:29469 CompletionCallback callback = callback_;
[email protected]0f292de02012-02-01 22:28:20470 MarkAsCanceled();
[email protected]aa22b242011-11-16 18:58:29471 callback.Run(error);
[email protected]b59ff372009-07-15 22:04:32472 }
473
[email protected]b59ff372009-07-15 22:04:32474 Job* job() const {
475 return job_;
476 }
477
[email protected]0f292de02012-02-01 22:28:20478 // NetLog for the source, passed in HostResolver::Resolve.
[email protected]ee094b82010-08-24 15:55:51479 const BoundNetLog& source_net_log() {
480 return source_net_log_;
481 }
482
[email protected]0f292de02012-02-01 22:28:20483 // NetLog for this request.
[email protected]ee094b82010-08-24 15:55:51484 const BoundNetLog& request_net_log() {
485 return request_net_log_;
[email protected]54e13772009-08-14 03:01:09486 }
487
[email protected]b59ff372009-07-15 22:04:32488 const RequestInfo& info() const {
489 return info_;
490 }
491
[email protected]51b9a6b2012-06-25 21:50:29492 base::TimeTicks request_time() const {
493 return request_time_;
494 }
495
[email protected]b59ff372009-07-15 22:04:32496 private:
[email protected]ee094b82010-08-24 15:55:51497 BoundNetLog source_net_log_;
498 BoundNetLog request_net_log_;
[email protected]54e13772009-08-14 03:01:09499
[email protected]b59ff372009-07-15 22:04:32500 // The request info that started the request.
501 RequestInfo info_;
502
[email protected]0f292de02012-02-01 22:28:20503 // The resolve job that this request is dependent on.
[email protected]b59ff372009-07-15 22:04:32504 Job* job_;
505
506 // The user's callback to invoke when the request completes.
[email protected]aa22b242011-11-16 18:58:29507 CompletionCallback callback_;
[email protected]b59ff372009-07-15 22:04:32508
509 // The address list to save result into.
510 AddressList* addresses_;
511
[email protected]51b9a6b2012-06-25 21:50:29512 const base::TimeTicks request_time_;
513
[email protected]b59ff372009-07-15 22:04:32514 DISALLOW_COPY_AND_ASSIGN(Request);
515};
516
[email protected]1e9bbd22010-10-15 16:42:45517//------------------------------------------------------------------------------
518
[email protected]0f292de02012-02-01 22:28:20519// Calls HostResolverProc on the WorkerPool. Performs retries if necessary.
520//
521// Whenever we try to resolve the host, we post a delayed task to check if host
522// resolution (OnLookupComplete) is completed or not. If the original attempt
523// hasn't completed, then we start another attempt for host resolution. We take
524// the results from the first attempt that finishes and ignore the results from
525// all other attempts.
526//
527// TODO(szym): Move to separate source file for testing and mocking.
528//
529class HostResolverImpl::ProcTask
530 : public base::RefCountedThreadSafe<HostResolverImpl::ProcTask> {
[email protected]b59ff372009-07-15 22:04:32531 public:
[email protected]b3601bc22012-02-21 21:23:20532 typedef base::Callback<void(int net_error,
533 const AddressList& addr_list)> Callback;
[email protected]b59ff372009-07-15 22:04:32534
[email protected]0f292de02012-02-01 22:28:20535 ProcTask(const Key& key,
536 const ProcTaskParams& params,
537 const Callback& callback,
538 const BoundNetLog& job_net_log)
539 : key_(key),
540 params_(params),
541 callback_(callback),
542 origin_loop_(base::MessageLoopProxy::current()),
543 attempt_number_(0),
544 completed_attempt_number_(0),
545 completed_attempt_error_(ERR_UNEXPECTED),
546 had_non_speculative_request_(false),
[email protected]b3601bc22012-02-21 21:23:20547 net_log_(job_net_log) {
[email protected]0f292de02012-02-01 22:28:20548 if (!params_.resolver_proc)
549 params_.resolver_proc = HostResolverProc::GetDefault();
550 // If default is unset, use the system proc.
551 if (!params_.resolver_proc)
552 params_.resolver_proc = new CallSystemHostResolverProc();
[email protected]b59ff372009-07-15 22:04:32553 }
554
[email protected]b59ff372009-07-15 22:04:32555 void Start() {
[email protected]3e9d9cc2011-05-03 21:08:15556 DCHECK(origin_loop_->BelongsToCurrentThread());
[email protected]4da911f2012-06-14 19:45:20557 net_log_.BeginEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK);
[email protected]189163e2011-05-11 01:48:54558 StartLookupAttempt();
559 }
[email protected]252b699b2010-02-05 21:38:06560
[email protected]0f292de02012-02-01 22:28:20561 // Cancels this ProcTask. It will be orphaned. Any outstanding resolve
562 // attempts running on worker threads will continue running. Only once all the
563 // attempts complete will the final reference to this ProcTask be released.
564 void Cancel() {
565 DCHECK(origin_loop_->BelongsToCurrentThread());
566
[email protected]0adcb2b2012-08-15 21:30:46567 if (was_canceled() || was_completed())
[email protected]0f292de02012-02-01 22:28:20568 return;
569
[email protected]0f292de02012-02-01 22:28:20570 callback_.Reset();
[email protected]4da911f2012-06-14 19:45:20571 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK);
[email protected]0f292de02012-02-01 22:28:20572 }
573
574 void set_had_non_speculative_request() {
575 DCHECK(origin_loop_->BelongsToCurrentThread());
576 had_non_speculative_request_ = true;
577 }
578
579 bool was_canceled() const {
580 DCHECK(origin_loop_->BelongsToCurrentThread());
581 return callback_.is_null();
582 }
583
584 bool was_completed() const {
585 DCHECK(origin_loop_->BelongsToCurrentThread());
586 return completed_attempt_number_ > 0;
587 }
588
589 private:
[email protected]a9813302012-04-28 09:29:28590 friend class base::RefCountedThreadSafe<ProcTask>;
591 ~ProcTask() {}
592
[email protected]189163e2011-05-11 01:48:54593 void StartLookupAttempt() {
594 DCHECK(origin_loop_->BelongsToCurrentThread());
595 base::TimeTicks start_time = base::TimeTicks::Now();
596 ++attempt_number_;
597 // Dispatch the lookup attempt to a worker thread.
598 if (!base::WorkerPool::PostTask(
599 FROM_HERE,
[email protected]0f292de02012-02-01 22:28:20600 base::Bind(&ProcTask::DoLookup, this, start_time, attempt_number_),
[email protected]189163e2011-05-11 01:48:54601 true)) {
[email protected]b59ff372009-07-15 22:04:32602 NOTREACHED();
603
604 // Since we could be running within Resolve() right now, we can't just
605 // call OnLookupComplete(). Instead we must wait until Resolve() has
606 // returned (IO_PENDING).
[email protected]3e9d9cc2011-05-03 21:08:15607 origin_loop_->PostTask(
[email protected]189163e2011-05-11 01:48:54608 FROM_HERE,
[email protected]0f292de02012-02-01 22:28:20609 base::Bind(&ProcTask::OnLookupComplete, this, AddressList(),
[email protected]33152acc2011-10-20 23:37:12610 start_time, attempt_number_, ERR_UNEXPECTED, 0));
[email protected]189163e2011-05-11 01:48:54611 return;
[email protected]b59ff372009-07-15 22:04:32612 }
[email protected]13024882011-05-18 23:19:16613
614 net_log_.AddEvent(
615 NetLog::TYPE_HOST_RESOLVER_IMPL_ATTEMPT_STARTED,
[email protected]cd565142012-06-12 16:21:45616 NetLog::IntegerCallback("attempt_number", attempt_number_));
[email protected]13024882011-05-18 23:19:16617
[email protected]0f292de02012-02-01 22:28:20618 // If we don't get the results within a given time, RetryIfNotComplete
619 // will start a new attempt on a different worker thread if none of our
620 // outstanding attempts have completed yet.
621 if (attempt_number_ <= params_.max_retry_attempts) {
[email protected]06ef6d92011-05-19 04:24:58622 origin_loop_->PostDelayedTask(
623 FROM_HERE,
[email protected]0f292de02012-02-01 22:28:20624 base::Bind(&ProcTask::RetryIfNotComplete, this),
[email protected]7e560102012-03-08 20:58:42625 params_.unresponsive_delay);
[email protected]06ef6d92011-05-19 04:24:58626 }
[email protected]b59ff372009-07-15 22:04:32627 }
628
[email protected]6c710ee2010-05-07 07:51:16629 // WARNING: This code runs inside a worker pool. The shutdown code cannot
630 // wait for it to finish, so we must be very careful here about using other
631 // objects (like MessageLoops, Singletons, etc). During shutdown these objects
[email protected]189163e2011-05-11 01:48:54632 // may no longer exist. Multiple DoLookups() could be running in parallel, so
633 // any state inside of |this| must not mutate .
634 void DoLookup(const base::TimeTicks& start_time,
635 const uint32 attempt_number) {
636 AddressList results;
637 int os_error = 0;
[email protected]b59ff372009-07-15 22:04:32638 // Running on the worker thread
[email protected]0f292de02012-02-01 22:28:20639 int error = params_.resolver_proc->Resolve(key_.hostname,
640 key_.address_family,
641 key_.host_resolver_flags,
642 &results,
643 &os_error);
[email protected]b59ff372009-07-15 22:04:32644
[email protected]189163e2011-05-11 01:48:54645 origin_loop_->PostTask(
646 FROM_HERE,
[email protected]0f292de02012-02-01 22:28:20647 base::Bind(&ProcTask::OnLookupComplete, this, results, start_time,
[email protected]33152acc2011-10-20 23:37:12648 attempt_number, error, os_error));
[email protected]189163e2011-05-11 01:48:54649 }
650
[email protected]0f292de02012-02-01 22:28:20651 // Makes next attempt if DoLookup() has not finished (runs on origin thread).
652 void RetryIfNotComplete() {
[email protected]189163e2011-05-11 01:48:54653 DCHECK(origin_loop_->BelongsToCurrentThread());
654
[email protected]0f292de02012-02-01 22:28:20655 if (was_completed() || was_canceled())
[email protected]189163e2011-05-11 01:48:54656 return;
657
[email protected]0f292de02012-02-01 22:28:20658 params_.unresponsive_delay *= params_.retry_factor;
[email protected]189163e2011-05-11 01:48:54659 StartLookupAttempt();
[email protected]b59ff372009-07-15 22:04:32660 }
661
662 // Callback for when DoLookup() completes (runs on origin thread).
[email protected]189163e2011-05-11 01:48:54663 void OnLookupComplete(const AddressList& results,
664 const base::TimeTicks& start_time,
665 const uint32 attempt_number,
666 int error,
667 const int os_error) {
[email protected]3e9d9cc2011-05-03 21:08:15668 DCHECK(origin_loop_->BelongsToCurrentThread());
[email protected]7054e78f2012-05-07 21:44:56669 DCHECK(error || !results.empty());
[email protected]189163e2011-05-11 01:48:54670
671 bool was_retry_attempt = attempt_number > 1;
672
[email protected]2d3b7762010-10-09 00:35:47673 // Ideally the following code would be part of host_resolver_proc.cc,
[email protected]b3601bc22012-02-21 21:23:20674 // however it isn't safe to call NetworkChangeNotifier from worker threads.
675 // So we do it here on the IO thread instead.
[email protected]189163e2011-05-11 01:48:54676 if (error != OK && NetworkChangeNotifier::IsOffline())
677 error = ERR_INTERNET_DISCONNECTED;
[email protected]2d3b7762010-10-09 00:35:47678
[email protected]b3601bc22012-02-21 21:23:20679 // If this is the first attempt that is finishing later, then record data
680 // for the first attempt. Won't contaminate with retry attempt's data.
[email protected]189163e2011-05-11 01:48:54681 if (!was_retry_attempt)
682 RecordPerformanceHistograms(start_time, error, os_error);
683
684 RecordAttemptHistograms(start_time, attempt_number, error, os_error);
[email protected]f2d8c4212010-02-02 00:56:35685
[email protected]0f292de02012-02-01 22:28:20686 if (was_canceled())
[email protected]b59ff372009-07-15 22:04:32687 return;
688
[email protected]cd565142012-06-12 16:21:45689 NetLog::ParametersCallback net_log_callback;
[email protected]0f292de02012-02-01 22:28:20690 if (error != OK) {
[email protected]cd565142012-06-12 16:21:45691 net_log_callback = base::Bind(&NetLogProcTaskFailedCallback,
692 attempt_number,
693 error,
694 os_error);
[email protected]0f292de02012-02-01 22:28:20695 } else {
[email protected]cd565142012-06-12 16:21:45696 net_log_callback = NetLog::IntegerCallback("attempt_number",
697 attempt_number);
[email protected]0f292de02012-02-01 22:28:20698 }
[email protected]cd565142012-06-12 16:21:45699 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_ATTEMPT_FINISHED,
700 net_log_callback);
[email protected]0f292de02012-02-01 22:28:20701
702 if (was_completed())
703 return;
704
705 // Copy the results from the first worker thread that resolves the host.
706 results_ = results;
707 completed_attempt_number_ = attempt_number;
708 completed_attempt_error_ = error;
709
[email protected]e87b8b512011-06-14 22:12:52710 if (was_retry_attempt) {
711 // If retry attempt finishes before 1st attempt, then get stats on how
712 // much time is saved by having spawned an extra attempt.
713 retry_attempt_finished_time_ = base::TimeTicks::Now();
714 }
715
[email protected]189163e2011-05-11 01:48:54716 if (error != OK) {
[email protected]cd565142012-06-12 16:21:45717 net_log_callback = base::Bind(&NetLogProcTaskFailedCallback,
718 0, error, os_error);
[email protected]ee094b82010-08-24 15:55:51719 } else {
[email protected]cd565142012-06-12 16:21:45720 net_log_callback = results_.CreateNetLogCallback();
[email protected]ee094b82010-08-24 15:55:51721 }
[email protected]cd565142012-06-12 16:21:45722 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK,
723 net_log_callback);
[email protected]ee094b82010-08-24 15:55:51724
[email protected]b3601bc22012-02-21 21:23:20725 callback_.Run(error, results_);
[email protected]b59ff372009-07-15 22:04:32726 }
727
[email protected]189163e2011-05-11 01:48:54728 void RecordPerformanceHistograms(const base::TimeTicks& start_time,
729 const int error,
730 const int os_error) const {
[email protected]3e9d9cc2011-05-03 21:08:15731 DCHECK(origin_loop_->BelongsToCurrentThread());
[email protected]1e9bbd22010-10-15 16:42:45732 enum Category { // Used in HISTOGRAM_ENUMERATION.
733 RESOLVE_SUCCESS,
734 RESOLVE_FAIL,
735 RESOLVE_SPECULATIVE_SUCCESS,
736 RESOLVE_SPECULATIVE_FAIL,
737 RESOLVE_MAX, // Bounding value.
738 };
739 int category = RESOLVE_MAX; // Illegal value for later DCHECK only.
740
[email protected]189163e2011-05-11 01:48:54741 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
742 if (error == OK) {
[email protected]1e9bbd22010-10-15 16:42:45743 if (had_non_speculative_request_) {
744 category = RESOLVE_SUCCESS;
745 DNS_HISTOGRAM("DNS.ResolveSuccess", duration);
746 } else {
747 category = RESOLVE_SPECULATIVE_SUCCESS;
748 DNS_HISTOGRAM("DNS.ResolveSpeculativeSuccess", duration);
749 }
[email protected]7e96d792011-06-10 17:08:23750
[email protected]78eac2a2012-03-14 19:09:27751 // Log DNS lookups based on |address_family|. This will help us determine
[email protected]7e96d792011-06-10 17:08:23752 // if IPv4 or IPv4/6 lookups are faster or slower.
753 switch(key_.address_family) {
754 case ADDRESS_FAMILY_IPV4:
755 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_IPV4", duration);
756 break;
757 case ADDRESS_FAMILY_IPV6:
758 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_IPV6", duration);
759 break;
760 case ADDRESS_FAMILY_UNSPECIFIED:
761 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_UNSPEC", duration);
762 break;
763 }
[email protected]1e9bbd22010-10-15 16:42:45764 } else {
765 if (had_non_speculative_request_) {
766 category = RESOLVE_FAIL;
767 DNS_HISTOGRAM("DNS.ResolveFail", duration);
768 } else {
769 category = RESOLVE_SPECULATIVE_FAIL;
770 DNS_HISTOGRAM("DNS.ResolveSpeculativeFail", duration);
771 }
[email protected]78eac2a2012-03-14 19:09:27772 // Log DNS lookups based on |address_family|. This will help us determine
[email protected]7e96d792011-06-10 17:08:23773 // if IPv4 or IPv4/6 lookups are faster or slower.
774 switch(key_.address_family) {
775 case ADDRESS_FAMILY_IPV4:
776 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_IPV4", duration);
777 break;
778 case ADDRESS_FAMILY_IPV6:
779 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_IPV6", duration);
780 break;
781 case ADDRESS_FAMILY_UNSPECIFIED:
782 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_UNSPEC", duration);
783 break;
784 }
[email protected]c833e322010-10-16 23:51:36785 UMA_HISTOGRAM_CUSTOM_ENUMERATION(kOSErrorsForGetAddrinfoHistogramName,
[email protected]189163e2011-05-11 01:48:54786 std::abs(os_error),
[email protected]1e9bbd22010-10-15 16:42:45787 GetAllGetAddrinfoOSErrors());
788 }
[email protected]051b6ab2010-10-18 16:50:46789 DCHECK_LT(category, static_cast<int>(RESOLVE_MAX)); // Be sure it was set.
[email protected]1e9bbd22010-10-15 16:42:45790
791 UMA_HISTOGRAM_ENUMERATION("DNS.ResolveCategory", category, RESOLVE_MAX);
792
[email protected]edafd4c2011-05-10 17:18:53793 static const bool show_parallelism_experiment_histograms =
794 base::FieldTrialList::TrialExists("DnsParallelism");
[email protected]ecd95ae2010-10-20 23:58:17795 if (show_parallelism_experiment_histograms) {
796 UMA_HISTOGRAM_ENUMERATION(
797 base::FieldTrial::MakeName("DNS.ResolveCategory", "DnsParallelism"),
798 category, RESOLVE_MAX);
799 if (RESOLVE_SUCCESS == category) {
800 DNS_HISTOGRAM(base::FieldTrial::MakeName("DNS.ResolveSuccess",
801 "DnsParallelism"), duration);
802 }
803 }
[email protected]1e9bbd22010-10-15 16:42:45804 }
805
[email protected]189163e2011-05-11 01:48:54806 void RecordAttemptHistograms(const base::TimeTicks& start_time,
807 const uint32 attempt_number,
808 const int error,
809 const int os_error) const {
[email protected]0f292de02012-02-01 22:28:20810 DCHECK(origin_loop_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54811 bool first_attempt_to_complete =
812 completed_attempt_number_ == attempt_number;
[email protected]e87b8b512011-06-14 22:12:52813 bool is_first_attempt = (attempt_number == 1);
[email protected]1e9bbd22010-10-15 16:42:45814
[email protected]189163e2011-05-11 01:48:54815 if (first_attempt_to_complete) {
816 // If this was first attempt to complete, then record the resolution
817 // status of the attempt.
818 if (completed_attempt_error_ == OK) {
819 UMA_HISTOGRAM_ENUMERATION(
820 "DNS.AttemptFirstSuccess", attempt_number, 100);
821 } else {
822 UMA_HISTOGRAM_ENUMERATION(
823 "DNS.AttemptFirstFailure", attempt_number, 100);
824 }
825 }
826
827 if (error == OK)
828 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptSuccess", attempt_number, 100);
829 else
830 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptFailure", attempt_number, 100);
831
[email protected]e87b8b512011-06-14 22:12:52832 // If first attempt didn't finish before retry attempt, then calculate stats
833 // on how much time is saved by having spawned an extra attempt.
[email protected]0f292de02012-02-01 22:28:20834 if (!first_attempt_to_complete && is_first_attempt && !was_canceled()) {
[email protected]e87b8b512011-06-14 22:12:52835 DNS_HISTOGRAM("DNS.AttemptTimeSavedByRetry",
836 base::TimeTicks::Now() - retry_attempt_finished_time_);
837 }
838
[email protected]0f292de02012-02-01 22:28:20839 if (was_canceled() || !first_attempt_to_complete) {
[email protected]189163e2011-05-11 01:48:54840 // Count those attempts which completed after the job was already canceled
841 // OR after the job was already completed by an earlier attempt (so in
842 // effect).
843 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptDiscarded", attempt_number, 100);
844
[email protected]0f292de02012-02-01 22:28:20845 // Record if job is canceled.
846 if (was_canceled())
[email protected]189163e2011-05-11 01:48:54847 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptCancelled", attempt_number, 100);
848 }
849
850 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
851 if (error == OK)
852 DNS_HISTOGRAM("DNS.AttemptSuccessDuration", duration);
853 else
854 DNS_HISTOGRAM("DNS.AttemptFailDuration", duration);
855 }
[email protected]1e9bbd22010-10-15 16:42:45856
[email protected]b59ff372009-07-15 22:04:32857 // Set on the origin thread, read on the worker thread.
[email protected]123ab1e32009-10-21 19:12:57858 Key key_;
[email protected]b59ff372009-07-15 22:04:32859
[email protected]0f292de02012-02-01 22:28:20860 // Holds an owning reference to the HostResolverProc that we are going to use.
[email protected]b59ff372009-07-15 22:04:32861 // This may not be the current resolver procedure by the time we call
862 // ResolveAddrInfo, but that's OK... we'll use it anyways, and the owning
863 // reference ensures that it remains valid until we are done.
[email protected]0f292de02012-02-01 22:28:20864 ProcTaskParams params_;
[email protected]b59ff372009-07-15 22:04:32865
[email protected]0f292de02012-02-01 22:28:20866 // The listener to the results of this ProcTask.
867 Callback callback_;
868
869 // Used to post ourselves onto the origin thread.
870 scoped_refptr<base::MessageLoopProxy> origin_loop_;
[email protected]189163e2011-05-11 01:48:54871
872 // Keeps track of the number of attempts we have made so far to resolve the
873 // host. Whenever we start an attempt to resolve the host, we increase this
874 // number.
875 uint32 attempt_number_;
876
877 // The index of the attempt which finished first (or 0 if the job is still in
878 // progress).
879 uint32 completed_attempt_number_;
880
881 // The result (a net error code) from the first attempt to complete.
882 int completed_attempt_error_;
[email protected]252b699b2010-02-05 21:38:06883
[email protected]e87b8b512011-06-14 22:12:52884 // The time when retry attempt was finished.
885 base::TimeTicks retry_attempt_finished_time_;
886
[email protected]252b699b2010-02-05 21:38:06887 // True if a non-speculative request was ever attached to this job
[email protected]0f292de02012-02-01 22:28:20888 // (regardless of whether or not it was later canceled.
[email protected]252b699b2010-02-05 21:38:06889 // This boolean is used for histogramming the duration of jobs used to
890 // service non-speculative requests.
891 bool had_non_speculative_request_;
892
[email protected]b59ff372009-07-15 22:04:32893 AddressList results_;
894
[email protected]ee094b82010-08-24 15:55:51895 BoundNetLog net_log_;
896
[email protected]0f292de02012-02-01 22:28:20897 DISALLOW_COPY_AND_ASSIGN(ProcTask);
[email protected]b59ff372009-07-15 22:04:32898};
899
900//-----------------------------------------------------------------------------
901
[email protected]12faa4c2012-11-06 04:44:18902// Wraps a call to TestIPv6Support to be executed on the WorkerPool as it takes
903// 40-100ms.
[email protected]9db6f702013-04-10 18:10:51904// TODO(szym): Remove altogether, if IPv6ActiveProbe works.
[email protected]12faa4c2012-11-06 04:44:18905class HostResolverImpl::IPv6ProbeJob {
[email protected]0f8f1b432010-03-16 19:06:03906 public:
[email protected]12faa4c2012-11-06 04:44:18907 IPv6ProbeJob(const base::WeakPtr<HostResolverImpl>& resolver, NetLog* net_log)
[email protected]0f8f1b432010-03-16 19:06:03908 : resolver_(resolver),
[email protected]12faa4c2012-11-06 04:44:18909 net_log_(BoundNetLog::Make(net_log, NetLog::SOURCE_IPV6_PROBE_JOB)),
910 result_(false, IPV6_SUPPORT_MAX, OK) {
[email protected]3e9d9cc2011-05-03 21:08:15911 DCHECK(resolver);
[email protected]ae8e80f2012-07-19 21:08:33912 net_log_.BeginEvent(NetLog::TYPE_IPV6_PROBE_RUNNING);
[email protected]f092e64b2010-03-17 00:39:18913 const bool kIsSlow = true;
[email protected]12faa4c2012-11-06 04:44:18914 base::WorkerPool::PostTaskAndReply(
915 FROM_HERE,
916 base::Bind(&IPv6ProbeJob::DoProbe, base::Unretained(this)),
917 base::Bind(&IPv6ProbeJob::OnProbeComplete, base::Owned(this)),
918 kIsSlow);
[email protected]0f8f1b432010-03-16 19:06:03919 }
920
[email protected]12faa4c2012-11-06 04:44:18921 virtual ~IPv6ProbeJob() {}
[email protected]0f8f1b432010-03-16 19:06:03922
[email protected]0f8f1b432010-03-16 19:06:03923 private:
[email protected]12faa4c2012-11-06 04:44:18924 // Runs on worker thread.
[email protected]0f8f1b432010-03-16 19:06:03925 void DoProbe() {
[email protected]12faa4c2012-11-06 04:44:18926 result_ = TestIPv6Support();
[email protected]0f8f1b432010-03-16 19:06:03927 }
928
[email protected]12faa4c2012-11-06 04:44:18929 void OnProbeComplete() {
930 net_log_.EndEvent(NetLog::TYPE_IPV6_PROBE_RUNNING,
931 base::Bind(&IPv6SupportResult::ToNetLogValue,
932 base::Unretained(&result_)));
933 if (!resolver_)
[email protected]a9af7112010-05-08 00:56:01934 return;
[email protected]12faa4c2012-11-06 04:44:18935 resolver_->IPv6ProbeSetDefaultAddressFamily(
936 result_.ipv6_supported ? ADDRESS_FAMILY_UNSPECIFIED
[email protected]ae8e80f2012-07-19 21:08:33937 : ADDRESS_FAMILY_IPV4);
[email protected]0f8f1b432010-03-16 19:06:03938 }
939
[email protected]0f8f1b432010-03-16 19:06:03940 // Used/set only on origin thread.
[email protected]12faa4c2012-11-06 04:44:18941 base::WeakPtr<HostResolverImpl> resolver_;
[email protected]0f8f1b432010-03-16 19:06:03942
[email protected]ae8e80f2012-07-19 21:08:33943 BoundNetLog net_log_;
944
[email protected]12faa4c2012-11-06 04:44:18945 IPv6SupportResult result_;
946
[email protected]0f8f1b432010-03-16 19:06:03947 DISALLOW_COPY_AND_ASSIGN(IPv6ProbeJob);
948};
949
[email protected]12faa4c2012-11-06 04:44:18950// Wraps a call to HaveOnlyLoopbackAddresses to be executed on the WorkerPool as
951// it takes 40-100ms and should not block initialization.
952class HostResolverImpl::LoopbackProbeJob {
953 public:
954 explicit LoopbackProbeJob(const base::WeakPtr<HostResolverImpl>& resolver)
955 : resolver_(resolver),
956 result_(false) {
957 DCHECK(resolver);
958 const bool kIsSlow = true;
959 base::WorkerPool::PostTaskAndReply(
960 FROM_HERE,
961 base::Bind(&LoopbackProbeJob::DoProbe, base::Unretained(this)),
962 base::Bind(&LoopbackProbeJob::OnProbeComplete, base::Owned(this)),
963 kIsSlow);
964 }
965
966 virtual ~LoopbackProbeJob() {}
967
968 private:
969 // Runs on worker thread.
970 void DoProbe() {
971 result_ = HaveOnlyLoopbackAddresses();
972 }
973
974 void OnProbeComplete() {
975 if (!resolver_)
976 return;
977 resolver_->SetHaveOnlyLoopbackAddresses(result_);
978 }
979
980 // Used/set only on origin thread.
981 base::WeakPtr<HostResolverImpl> resolver_;
982
983 bool result_;
984
985 DISALLOW_COPY_AND_ASSIGN(LoopbackProbeJob);
986};
987
[email protected]0f8f1b432010-03-16 19:06:03988//-----------------------------------------------------------------------------
989
[email protected]b3601bc22012-02-21 21:23:20990// Resolves the hostname using DnsTransaction.
991// TODO(szym): This could be moved to separate source file as well.
[email protected]0adcb2b2012-08-15 21:30:46992class HostResolverImpl::DnsTask : public base::SupportsWeakPtr<DnsTask> {
[email protected]b3601bc22012-02-21 21:23:20993 public:
994 typedef base::Callback<void(int net_error,
995 const AddressList& addr_list,
996 base::TimeDelta ttl)> Callback;
997
[email protected]0adcb2b2012-08-15 21:30:46998 DnsTask(DnsClient* client,
[email protected]b3601bc22012-02-21 21:23:20999 const Key& key,
1000 const Callback& callback,
1001 const BoundNetLog& job_net_log)
[email protected]0adcb2b2012-08-15 21:30:461002 : client_(client),
1003 family_(key.address_family),
1004 callback_(callback),
1005 net_log_(job_net_log) {
1006 DCHECK(client);
[email protected]b3601bc22012-02-21 21:23:201007 DCHECK(!callback.is_null());
1008
[email protected]0adcb2b2012-08-15 21:30:461009 // If unspecified, do IPv4 first, because suffix search will be faster.
1010 uint16 qtype = (family_ == ADDRESS_FAMILY_IPV6) ?
1011 dns_protocol::kTypeAAAA :
1012 dns_protocol::kTypeA;
1013 transaction_ = client_->GetTransactionFactory()->CreateTransaction(
[email protected]b3601bc22012-02-21 21:23:201014 key.hostname,
1015 qtype,
[email protected]1def74c2012-03-22 20:07:001016 base::Bind(&DnsTask::OnTransactionComplete, base::Unretained(this),
[email protected]0adcb2b2012-08-15 21:30:461017 true /* first_query */, base::TimeTicks::Now()),
[email protected]b3601bc22012-02-21 21:23:201018 net_log_);
[email protected]b3601bc22012-02-21 21:23:201019 }
1020
1021 int Start() {
[email protected]4da911f2012-06-14 19:45:201022 net_log_.BeginEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK);
[email protected]b3601bc22012-02-21 21:23:201023 return transaction_->Start();
1024 }
1025
[email protected]0adcb2b2012-08-15 21:30:461026 private:
1027 void OnTransactionComplete(bool first_query,
1028 const base::TimeTicks& start_time,
[email protected]1def74c2012-03-22 20:07:001029 DnsTransaction* transaction,
[email protected]b3601bc22012-02-21 21:23:201030 int net_error,
1031 const DnsResponse* response) {
[email protected]add76532012-03-30 14:47:471032 DCHECK(transaction);
[email protected]02cd6982013-01-10 20:12:511033 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]b3601bc22012-02-21 21:23:201034 // Run |callback_| last since the owning Job will then delete this DnsTask.
[email protected]0adcb2b2012-08-15 21:30:461035 if (net_error != OK) {
[email protected]02cd6982013-01-10 20:12:511036 DNS_HISTOGRAM("AsyncDNS.TransactionFailure", duration);
[email protected]0adcb2b2012-08-15 21:30:461037 OnFailure(net_error, DnsResponse::DNS_PARSE_OK);
1038 return;
[email protected]6c411902012-08-14 22:36:361039 }
[email protected]0adcb2b2012-08-15 21:30:461040
1041 CHECK(response);
[email protected]02cd6982013-01-10 20:12:511042 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess", duration);
1043 switch (transaction->GetType()) {
1044 case dns_protocol::kTypeA:
1045 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess_A", duration);
1046 break;
1047 case dns_protocol::kTypeAAAA:
1048 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess_AAAA", duration);
1049 break;
1050 }
[email protected]0adcb2b2012-08-15 21:30:461051 AddressList addr_list;
1052 base::TimeDelta ttl;
1053 DnsResponse::Result result = response->ParseToAddressList(&addr_list, &ttl);
1054 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ParseToAddressList",
1055 result,
1056 DnsResponse::DNS_PARSE_RESULT_MAX);
1057 if (result != DnsResponse::DNS_PARSE_OK) {
1058 // Fail even if the other query succeeds.
1059 OnFailure(ERR_DNS_MALFORMED_RESPONSE, result);
1060 return;
1061 }
1062
1063 bool needs_sort = false;
1064 if (first_query) {
1065 DCHECK(client_->GetConfig()) <<
1066 "Transaction should have been aborted when config changed!";
1067 if (family_ == ADDRESS_FAMILY_IPV6) {
1068 needs_sort = (addr_list.size() > 1);
1069 } else if (family_ == ADDRESS_FAMILY_UNSPECIFIED) {
1070 first_addr_list_ = addr_list;
1071 first_ttl_ = ttl;
1072 // Use fully-qualified domain name to avoid search.
1073 transaction_ = client_->GetTransactionFactory()->CreateTransaction(
1074 response->GetDottedName() + ".",
1075 dns_protocol::kTypeAAAA,
1076 base::Bind(&DnsTask::OnTransactionComplete, base::Unretained(this),
1077 false /* first_query */, base::TimeTicks::Now()),
1078 net_log_);
1079 net_error = transaction_->Start();
1080 if (net_error != ERR_IO_PENDING)
1081 OnFailure(net_error, DnsResponse::DNS_PARSE_OK);
1082 return;
1083 }
1084 } else {
1085 DCHECK_EQ(ADDRESS_FAMILY_UNSPECIFIED, family_);
1086 bool has_ipv6_addresses = !addr_list.empty();
1087 if (!first_addr_list_.empty()) {
1088 ttl = std::min(ttl, first_ttl_);
1089 // Place IPv4 addresses after IPv6.
1090 addr_list.insert(addr_list.end(), first_addr_list_.begin(),
1091 first_addr_list_.end());
1092 }
1093 needs_sort = (has_ipv6_addresses && addr_list.size() > 1);
1094 }
1095
1096 if (addr_list.empty()) {
1097 // TODO(szym): Don't fallback to ProcTask in this case.
1098 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
1099 return;
1100 }
1101
1102 if (needs_sort) {
1103 // Sort could complete synchronously.
1104 client_->GetAddressSorter()->Sort(
1105 addr_list,
[email protected]4589a3a2012-09-20 20:57:071106 base::Bind(&DnsTask::OnSortComplete,
1107 AsWeakPtr(),
[email protected]0adcb2b2012-08-15 21:30:461108 base::TimeTicks::Now(),
1109 ttl));
1110 } else {
1111 OnSuccess(addr_list, ttl);
1112 }
1113 }
1114
1115 void OnSortComplete(base::TimeTicks start_time,
1116 base::TimeDelta ttl,
1117 bool success,
1118 const AddressList& addr_list) {
1119 if (!success) {
1120 DNS_HISTOGRAM("AsyncDNS.SortFailure",
1121 base::TimeTicks::Now() - start_time);
1122 OnFailure(ERR_DNS_SORT_ERROR, DnsResponse::DNS_PARSE_OK);
1123 return;
1124 }
1125
1126 DNS_HISTOGRAM("AsyncDNS.SortSuccess",
1127 base::TimeTicks::Now() - start_time);
1128
1129 // AddressSorter prunes unusable destinations.
1130 if (addr_list.empty()) {
1131 LOG(WARNING) << "Address list empty after RFC3484 sort";
1132 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
1133 return;
1134 }
1135
1136 OnSuccess(addr_list, ttl);
1137 }
1138
1139 void OnFailure(int net_error, DnsResponse::Result result) {
1140 DCHECK_NE(OK, net_error);
[email protected]cd565142012-06-12 16:21:451141 net_log_.EndEvent(
1142 NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK,
1143 base::Bind(&NetLogDnsTaskFailedCallback, net_error, result));
[email protected]b3601bc22012-02-21 21:23:201144 callback_.Run(net_error, AddressList(), base::TimeDelta());
1145 }
1146
[email protected]0adcb2b2012-08-15 21:30:461147 void OnSuccess(const AddressList& addr_list, base::TimeDelta ttl) {
1148 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK,
1149 addr_list.CreateNetLogCallback());
1150 callback_.Run(OK, addr_list, ttl);
1151 }
1152
1153 DnsClient* client_;
1154 AddressFamily family_;
[email protected]b3601bc22012-02-21 21:23:201155 // The listener to the results of this DnsTask.
1156 Callback callback_;
[email protected]b3601bc22012-02-21 21:23:201157 const BoundNetLog net_log_;
1158
1159 scoped_ptr<DnsTransaction> transaction_;
[email protected]0adcb2b2012-08-15 21:30:461160
1161 // Results from the first transaction. Used only if |family_| is unspecified.
1162 AddressList first_addr_list_;
1163 base::TimeDelta first_ttl_;
1164
1165 DISALLOW_COPY_AND_ASSIGN(DnsTask);
[email protected]b3601bc22012-02-21 21:23:201166};
1167
1168//-----------------------------------------------------------------------------
1169
[email protected]0f292de02012-02-01 22:28:201170// Aggregates all Requests for the same Key. Dispatched via PriorityDispatch.
[email protected]0f292de02012-02-01 22:28:201171class HostResolverImpl::Job : public PrioritizedDispatcher::Job {
[email protected]68ad3ee2010-01-30 03:45:391172 public:
[email protected]0f292de02012-02-01 22:28:201173 // Creates new job for |key| where |request_net_log| is bound to the
[email protected]16ee26d2012-03-08 03:34:351174 // request that spawned it.
[email protected]12faa4c2012-11-06 04:44:181175 Job(const base::WeakPtr<HostResolverImpl>& resolver,
[email protected]0f292de02012-02-01 22:28:201176 const Key& key,
[email protected]8c98d002012-07-18 19:02:271177 RequestPriority priority,
[email protected]16ee26d2012-03-08 03:34:351178 const BoundNetLog& request_net_log)
[email protected]12faa4c2012-11-06 04:44:181179 : resolver_(resolver),
[email protected]0f292de02012-02-01 22:28:201180 key_(key),
[email protected]8c98d002012-07-18 19:02:271181 priority_tracker_(priority),
[email protected]0f292de02012-02-01 22:28:201182 had_non_speculative_request_(false),
[email protected]51b9a6b2012-06-25 21:50:291183 had_dns_config_(false),
[email protected]1d932852012-06-19 19:40:331184 dns_task_error_(OK),
[email protected]51b9a6b2012-06-25 21:50:291185 creation_time_(base::TimeTicks::Now()),
1186 priority_change_time_(creation_time_),
[email protected]0f292de02012-02-01 22:28:201187 net_log_(BoundNetLog::Make(request_net_log.net_log(),
[email protected]b3601bc22012-02-21 21:23:201188 NetLog::SOURCE_HOST_RESOLVER_IMPL_JOB)) {
[email protected]4da911f2012-06-14 19:45:201189 request_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_CREATE_JOB);
[email protected]0f292de02012-02-01 22:28:201190
1191 net_log_.BeginEvent(
1192 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
[email protected]cd565142012-06-12 16:21:451193 base::Bind(&NetLogJobCreationCallback,
1194 request_net_log.source(),
1195 &key_.hostname));
[email protected]68ad3ee2010-01-30 03:45:391196 }
1197
[email protected]0f292de02012-02-01 22:28:201198 virtual ~Job() {
[email protected]b3601bc22012-02-21 21:23:201199 if (is_running()) {
1200 // |resolver_| was destroyed with this Job still in flight.
1201 // Clean-up, record in the log, but don't run any callbacks.
1202 if (is_proc_running()) {
[email protected]0f292de02012-02-01 22:28:201203 proc_task_->Cancel();
1204 proc_task_ = NULL;
[email protected]0f292de02012-02-01 22:28:201205 }
[email protected]16ee26d2012-03-08 03:34:351206 // Clean up now for nice NetLog.
1207 dns_task_.reset(NULL);
[email protected]b3601bc22012-02-21 21:23:201208 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
1209 ERR_ABORTED);
1210 } else if (is_queued()) {
[email protected]57a48d32012-03-03 00:04:551211 // |resolver_| was destroyed without running this Job.
[email protected]16ee26d2012-03-08 03:34:351212 // TODO(szym): is there any benefit in having this distinction?
[email protected]4da911f2012-06-14 19:45:201213 net_log_.AddEvent(NetLog::TYPE_CANCELLED);
1214 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB);
[email protected]68ad3ee2010-01-30 03:45:391215 }
[email protected]b3601bc22012-02-21 21:23:201216 // else CompleteRequests logged EndEvent.
[email protected]68ad3ee2010-01-30 03:45:391217
[email protected]b3601bc22012-02-21 21:23:201218 // Log any remaining Requests as cancelled.
1219 for (RequestsList::const_iterator it = requests_.begin();
1220 it != requests_.end(); ++it) {
1221 Request* req = *it;
1222 if (req->was_canceled())
1223 continue;
1224 DCHECK_EQ(this, req->job());
1225 LogCancelRequest(req->source_net_log(), req->request_net_log(),
1226 req->info());
1227 }
[email protected]68ad3ee2010-01-30 03:45:391228 }
1229
[email protected]16ee26d2012-03-08 03:34:351230 // Add this job to the dispatcher.
[email protected]8c98d002012-07-18 19:02:271231 void Schedule() {
1232 handle_ = resolver_->dispatcher_.Add(this, priority());
[email protected]16ee26d2012-03-08 03:34:351233 }
1234
[email protected]b3601bc22012-02-21 21:23:201235 void AddRequest(scoped_ptr<Request> req) {
[email protected]0f292de02012-02-01 22:28:201236 DCHECK_EQ(key_.hostname, req->info().hostname());
1237
1238 req->set_job(this);
[email protected]0f292de02012-02-01 22:28:201239 priority_tracker_.Add(req->info().priority());
1240
1241 req->request_net_log().AddEvent(
1242 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_ATTACH,
[email protected]cd565142012-06-12 16:21:451243 net_log_.source().ToEventParametersCallback());
[email protected]0f292de02012-02-01 22:28:201244
1245 net_log_.AddEvent(
1246 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_REQUEST_ATTACH,
[email protected]cd565142012-06-12 16:21:451247 base::Bind(&NetLogJobAttachCallback,
1248 req->request_net_log().source(),
1249 priority()));
[email protected]0f292de02012-02-01 22:28:201250
1251 // TODO(szym): Check if this is still needed.
1252 if (!req->info().is_speculative()) {
1253 had_non_speculative_request_ = true;
1254 if (proc_task_)
1255 proc_task_->set_had_non_speculative_request();
[email protected]68ad3ee2010-01-30 03:45:391256 }
[email protected]b3601bc22012-02-21 21:23:201257
1258 requests_.push_back(req.release());
1259
[email protected]51b9a6b2012-06-25 21:50:291260 UpdatePriority();
[email protected]68ad3ee2010-01-30 03:45:391261 }
1262
[email protected]16ee26d2012-03-08 03:34:351263 // Marks |req| as cancelled. If it was the last active Request, also finishes
[email protected]0adcb2b2012-08-15 21:30:461264 // this Job, marking it as cancelled, and deletes it.
[email protected]0f292de02012-02-01 22:28:201265 void CancelRequest(Request* req) {
1266 DCHECK_EQ(key_.hostname, req->info().hostname());
1267 DCHECK(!req->was_canceled());
[email protected]16ee26d2012-03-08 03:34:351268
[email protected]0f292de02012-02-01 22:28:201269 // Don't remove it from |requests_| just mark it canceled.
1270 req->MarkAsCanceled();
1271 LogCancelRequest(req->source_net_log(), req->request_net_log(),
1272 req->info());
[email protected]16ee26d2012-03-08 03:34:351273
[email protected]0f292de02012-02-01 22:28:201274 priority_tracker_.Remove(req->info().priority());
1275 net_log_.AddEvent(
1276 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_REQUEST_DETACH,
[email protected]cd565142012-06-12 16:21:451277 base::Bind(&NetLogJobAttachCallback,
1278 req->request_net_log().source(),
1279 priority()));
[email protected]b3601bc22012-02-21 21:23:201280
[email protected]16ee26d2012-03-08 03:34:351281 if (num_active_requests() > 0) {
[email protected]51b9a6b2012-06-25 21:50:291282 UpdatePriority();
[email protected]16ee26d2012-03-08 03:34:351283 } else {
1284 // If we were called from a Request's callback within CompleteRequests,
1285 // that Request could not have been cancelled, so num_active_requests()
1286 // could not be 0. Therefore, we are not in CompleteRequests().
[email protected]1339a2a22012-10-17 08:39:431287 CompleteRequestsWithError(OK /* cancelled */);
[email protected]b3601bc22012-02-21 21:23:201288 }
[email protected]68ad3ee2010-01-30 03:45:391289 }
1290
[email protected]7af985a2012-12-14 22:40:421291 // Called from AbortAllInProgressJobs. Completes all requests and destroys
1292 // the job. This currently assumes the abort is due to a network change.
[email protected]0f292de02012-02-01 22:28:201293 void Abort() {
[email protected]0f292de02012-02-01 22:28:201294 DCHECK(is_running());
[email protected]7af985a2012-12-14 22:40:421295 CompleteRequestsWithError(ERR_NETWORK_CHANGED);
[email protected]b3601bc22012-02-21 21:23:201296 }
1297
[email protected]f0f602bd2012-11-15 18:01:021298 // If DnsTask present, abort it and fall back to ProcTask.
1299 void AbortDnsTask() {
1300 if (dns_task_) {
1301 dns_task_.reset();
1302 dns_task_error_ = OK;
1303 StartProcTask();
1304 }
1305 }
1306
[email protected]16ee26d2012-03-08 03:34:351307 // Called by HostResolverImpl when this job is evicted due to queue overflow.
1308 // Completes all requests and destroys the job.
1309 void OnEvicted() {
1310 DCHECK(!is_running());
1311 DCHECK(is_queued());
1312 handle_.Reset();
1313
[email protected]4da911f2012-06-14 19:45:201314 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_EVICTED);
[email protected]16ee26d2012-03-08 03:34:351315
1316 // This signals to CompleteRequests that this job never ran.
[email protected]1339a2a22012-10-17 08:39:431317 CompleteRequestsWithError(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
[email protected]16ee26d2012-03-08 03:34:351318 }
1319
[email protected]78eac2a2012-03-14 19:09:271320 // Attempts to serve the job from HOSTS. Returns true if succeeded and
1321 // this Job was destroyed.
1322 bool ServeFromHosts() {
1323 DCHECK_GT(num_active_requests(), 0u);
1324 AddressList addr_list;
1325 if (resolver_->ServeFromHosts(key(),
[email protected]3cb676a12012-06-30 15:46:031326 requests_.front()->info(),
[email protected]78eac2a2012-03-14 19:09:271327 &addr_list)) {
1328 // This will destroy the Job.
[email protected]895123222012-10-25 15:21:171329 CompleteRequests(
1330 HostCache::Entry(OK, MakeAddressListForRequest(addr_list)),
1331 base::TimeDelta());
[email protected]78eac2a2012-03-14 19:09:271332 return true;
1333 }
1334 return false;
1335 }
1336
[email protected]b4481b222012-03-16 17:13:111337 const Key key() const {
1338 return key_;
1339 }
1340
1341 bool is_queued() const {
1342 return !handle_.is_null();
1343 }
1344
1345 bool is_running() const {
1346 return is_dns_running() || is_proc_running();
1347 }
1348
[email protected]16ee26d2012-03-08 03:34:351349 private:
[email protected]51b9a6b2012-06-25 21:50:291350 void UpdatePriority() {
1351 if (is_queued()) {
1352 if (priority() != static_cast<RequestPriority>(handle_.priority()))
1353 priority_change_time_ = base::TimeTicks::Now();
1354 handle_ = resolver_->dispatcher_.ChangePriority(handle_, priority());
1355 }
1356 }
1357
[email protected]895123222012-10-25 15:21:171358 AddressList MakeAddressListForRequest(const AddressList& list) const {
1359 if (requests_.empty())
1360 return list;
1361 return AddressList::CopyWithPort(list, requests_.front()->info().port());
1362 }
1363
[email protected]16ee26d2012-03-08 03:34:351364 // PriorityDispatch::Job:
[email protected]0f292de02012-02-01 22:28:201365 virtual void Start() OVERRIDE {
1366 DCHECK(!is_running());
[email protected]b3601bc22012-02-21 21:23:201367 handle_.Reset();
[email protected]0f292de02012-02-01 22:28:201368
[email protected]4da911f2012-06-14 19:45:201369 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_STARTED);
[email protected]0f292de02012-02-01 22:28:201370
[email protected]51b9a6b2012-06-25 21:50:291371 had_dns_config_ = resolver_->HaveDnsConfig();
1372
1373 base::TimeTicks now = base::TimeTicks::Now();
1374 base::TimeDelta queue_time = now - creation_time_;
1375 base::TimeDelta queue_time_after_change = now - priority_change_time_;
1376
1377 if (had_dns_config_) {
1378 DNS_HISTOGRAM_BY_PRIORITY("AsyncDNS.JobQueueTime", priority(),
1379 queue_time);
1380 DNS_HISTOGRAM_BY_PRIORITY("AsyncDNS.JobQueueTimeAfterChange", priority(),
1381 queue_time_after_change);
1382 } else {
1383 DNS_HISTOGRAM_BY_PRIORITY("DNS.JobQueueTime", priority(), queue_time);
1384 DNS_HISTOGRAM_BY_PRIORITY("DNS.JobQueueTimeAfterChange", priority(),
1385 queue_time_after_change);
1386 }
1387
[email protected]1d932852012-06-19 19:40:331388 // Caution: Job::Start must not complete synchronously.
[email protected]51b9a6b2012-06-25 21:50:291389 if (had_dns_config_ && !ResemblesMulticastDNSName(key_.hostname)) {
[email protected]b3601bc22012-02-21 21:23:201390 StartDnsTask();
1391 } else {
1392 StartProcTask();
1393 }
1394 }
1395
[email protected]b3601bc22012-02-21 21:23:201396 // TODO(szym): Since DnsTransaction does not consume threads, we can increase
1397 // the limits on |dispatcher_|. But in order to keep the number of WorkerPool
1398 // threads low, we will need to use an "inner" PrioritizedDispatcher with
1399 // tighter limits.
1400 void StartProcTask() {
[email protected]16ee26d2012-03-08 03:34:351401 DCHECK(!is_dns_running());
[email protected]0f292de02012-02-01 22:28:201402 proc_task_ = new ProcTask(
1403 key_,
1404 resolver_->proc_params_,
[email protected]e3bd4822012-10-23 18:01:371405 base::Bind(&Job::OnProcTaskComplete, base::Unretained(this),
1406 base::TimeTicks::Now()),
[email protected]0f292de02012-02-01 22:28:201407 net_log_);
1408
1409 if (had_non_speculative_request_)
1410 proc_task_->set_had_non_speculative_request();
1411 // Start() could be called from within Resolve(), hence it must NOT directly
1412 // call OnProcTaskComplete, for example, on synchronous failure.
1413 proc_task_->Start();
[email protected]68ad3ee2010-01-30 03:45:391414 }
1415
[email protected]0f292de02012-02-01 22:28:201416 // Called by ProcTask when it completes.
[email protected]e3bd4822012-10-23 18:01:371417 void OnProcTaskComplete(base::TimeTicks start_time,
1418 int net_error,
1419 const AddressList& addr_list) {
[email protected]b3601bc22012-02-21 21:23:201420 DCHECK(is_proc_running());
[email protected]68ad3ee2010-01-30 03:45:391421
[email protected]62e86ba2013-01-29 18:59:161422 if (!resolver_->resolved_known_ipv6_hostname_ &&
1423 net_error == OK &&
1424 key_.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
1425 if (key_.hostname == "www.google.com") {
1426 resolver_->resolved_known_ipv6_hostname_ = true;
1427 bool got_ipv6_address = false;
1428 for (size_t i = 0; i < addr_list.size(); ++i) {
1429 if (addr_list[i].GetFamily() == ADDRESS_FAMILY_IPV6)
1430 got_ipv6_address = true;
1431 }
1432 UMA_HISTOGRAM_BOOLEAN("Net.UnspecResolvedIPv6", got_ipv6_address);
1433 }
1434 }
1435
[email protected]1d932852012-06-19 19:40:331436 if (dns_task_error_ != OK) {
[email protected]e3bd4822012-10-23 18:01:371437 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]1def74c2012-03-22 20:07:001438 if (net_error == OK) {
[email protected]e3bd4822012-10-23 18:01:371439 DNS_HISTOGRAM("AsyncDNS.FallbackSuccess", duration);
[email protected]1d932852012-06-19 19:40:331440 if ((dns_task_error_ == ERR_NAME_NOT_RESOLVED) &&
1441 ResemblesNetBIOSName(key_.hostname)) {
1442 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_SUSPECT_NETBIOS);
1443 } else {
1444 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_PROC_SUCCESS);
1445 }
1446 UMA_HISTOGRAM_CUSTOM_ENUMERATION("AsyncDNS.ResolveError",
1447 std::abs(dns_task_error_),
1448 GetAllErrorCodesForUma());
[email protected]1ffdda82012-12-12 23:04:221449 resolver_->OnDnsTaskResolve(dns_task_error_);
[email protected]1def74c2012-03-22 20:07:001450 } else {
[email protected]e3bd4822012-10-23 18:01:371451 DNS_HISTOGRAM("AsyncDNS.FallbackFail", duration);
[email protected]1def74c2012-03-22 20:07:001452 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
1453 }
1454 }
1455
[email protected]1339a2a22012-10-17 08:39:431456 base::TimeDelta ttl =
1457 base::TimeDelta::FromSeconds(kNegativeCacheEntryTTLSeconds);
[email protected]b3601bc22012-02-21 21:23:201458 if (net_error == OK)
1459 ttl = base::TimeDelta::FromSeconds(kCacheEntryTTLSeconds);
[email protected]68ad3ee2010-01-30 03:45:391460
[email protected]895123222012-10-25 15:21:171461 // Don't store the |ttl| in cache since it's not obtained from the server.
1462 CompleteRequests(
1463 HostCache::Entry(net_error, MakeAddressListForRequest(addr_list)),
1464 ttl);
[email protected]b3601bc22012-02-21 21:23:201465 }
1466
1467 void StartDnsTask() {
[email protected]78eac2a2012-03-14 19:09:271468 DCHECK(resolver_->HaveDnsConfig());
[email protected]b3601bc22012-02-21 21:23:201469 dns_task_.reset(new DnsTask(
[email protected]0adcb2b2012-08-15 21:30:461470 resolver_->dns_client_.get(),
[email protected]b3601bc22012-02-21 21:23:201471 key_,
[email protected]e3bd4822012-10-23 18:01:371472 base::Bind(&Job::OnDnsTaskComplete, base::Unretained(this),
1473 base::TimeTicks::Now()),
[email protected]b3601bc22012-02-21 21:23:201474 net_log_));
1475
1476 int rv = dns_task_->Start();
1477 if (rv != ERR_IO_PENDING) {
1478 DCHECK_NE(OK, rv);
[email protected]51b9a6b2012-06-25 21:50:291479 dns_task_error_ = rv;
[email protected]b3601bc22012-02-21 21:23:201480 dns_task_.reset();
1481 StartProcTask();
1482 }
1483 }
1484
1485 // Called by DnsTask when it completes.
[email protected]e3bd4822012-10-23 18:01:371486 void OnDnsTaskComplete(base::TimeTicks start_time,
1487 int net_error,
[email protected]b3601bc22012-02-21 21:23:201488 const AddressList& addr_list,
1489 base::TimeDelta ttl) {
1490 DCHECK(is_dns_running());
[email protected]b3601bc22012-02-21 21:23:201491
[email protected]e3bd4822012-10-23 18:01:371492 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]b3601bc22012-02-21 21:23:201493 if (net_error != OK) {
[email protected]e3bd4822012-10-23 18:01:371494 DNS_HISTOGRAM("AsyncDNS.ResolveFail", duration);
1495
[email protected]1d932852012-06-19 19:40:331496 dns_task_error_ = net_error;
[email protected]16ee26d2012-03-08 03:34:351497 dns_task_.reset();
[email protected]78eac2a2012-03-14 19:09:271498
1499 // TODO(szym): Run ServeFromHosts now if nsswitch.conf says so.
1500 // http://crbug.com/117655
1501
[email protected]b3601bc22012-02-21 21:23:201502 // TODO(szym): Some net errors indicate lack of connectivity. Starting
1503 // ProcTask in that case is a waste of time.
1504 StartProcTask();
1505 return;
1506 }
[email protected]e3bd4822012-10-23 18:01:371507 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess", duration);
[email protected]02cd6982013-01-10 20:12:511508 // Log DNS lookups based on |address_family|.
1509 switch(key_.address_family) {
1510 case ADDRESS_FAMILY_IPV4:
1511 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_IPV4", duration);
1512 break;
1513 case ADDRESS_FAMILY_IPV6:
1514 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_IPV6", duration);
1515 break;
1516 case ADDRESS_FAMILY_UNSPECIFIED:
1517 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_UNSPEC", duration);
1518 break;
1519 }
[email protected]b3601bc22012-02-21 21:23:201520
[email protected]1def74c2012-03-22 20:07:001521 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_DNS_SUCCESS);
[email protected]1339a2a22012-10-17 08:39:431522 RecordTTL(ttl);
[email protected]0adcb2b2012-08-15 21:30:461523
[email protected]1ffdda82012-12-12 23:04:221524 resolver_->OnDnsTaskResolve(OK);
[email protected]f0f602bd2012-11-15 18:01:021525
[email protected]895123222012-10-25 15:21:171526 base::TimeDelta bounded_ttl =
1527 std::max(ttl, base::TimeDelta::FromSeconds(kMinimumTTLSeconds));
1528
1529 CompleteRequests(
1530 HostCache::Entry(net_error, MakeAddressListForRequest(addr_list), ttl),
1531 bounded_ttl);
[email protected]b3601bc22012-02-21 21:23:201532 }
1533
[email protected]16ee26d2012-03-08 03:34:351534 // Performs Job's last rites. Completes all Requests. Deletes this.
[email protected]895123222012-10-25 15:21:171535 void CompleteRequests(const HostCache::Entry& entry,
1536 base::TimeDelta ttl) {
[email protected]b3601bc22012-02-21 21:23:201537 CHECK(resolver_);
[email protected]b3601bc22012-02-21 21:23:201538
[email protected]16ee26d2012-03-08 03:34:351539 // This job must be removed from resolver's |jobs_| now to make room for a
1540 // new job with the same key in case one of the OnComplete callbacks decides
1541 // to spawn one. Consequently, the job deletes itself when CompleteRequests
1542 // is done.
1543 scoped_ptr<Job> self_deleter(this);
1544
1545 resolver_->RemoveJob(this);
1546
[email protected]16ee26d2012-03-08 03:34:351547 if (is_running()) {
1548 DCHECK(!is_queued());
1549 if (is_proc_running()) {
1550 proc_task_->Cancel();
1551 proc_task_ = NULL;
1552 }
1553 dns_task_.reset();
1554
1555 // Signal dispatcher that a slot has opened.
1556 resolver_->dispatcher_.OnJobFinished();
1557 } else if (is_queued()) {
1558 resolver_->dispatcher_.Cancel(handle_);
1559 handle_.Reset();
1560 }
1561
1562 if (num_active_requests() == 0) {
[email protected]4da911f2012-06-14 19:45:201563 net_log_.AddEvent(NetLog::TYPE_CANCELLED);
[email protected]16ee26d2012-03-08 03:34:351564 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
1565 OK);
1566 return;
1567 }
[email protected]b3601bc22012-02-21 21:23:201568
1569 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
[email protected]895123222012-10-25 15:21:171570 entry.error);
[email protected]68ad3ee2010-01-30 03:45:391571
[email protected]78eac2a2012-03-14 19:09:271572 DCHECK(!requests_.empty());
1573
[email protected]895123222012-10-25 15:21:171574 if (entry.error == OK) {
[email protected]d7b9a2b2012-05-31 22:31:191575 // Record this histogram here, when we know the system has a valid DNS
1576 // configuration.
[email protected]539df6c2012-06-19 21:21:291577 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.HaveDnsConfig",
1578 resolver_->received_dns_config_);
[email protected]d7b9a2b2012-05-31 22:31:191579 }
[email protected]16ee26d2012-03-08 03:34:351580
[email protected]7af985a2012-12-14 22:40:421581 bool did_complete = (entry.error != ERR_NETWORK_CHANGED) &&
[email protected]895123222012-10-25 15:21:171582 (entry.error != ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
1583 if (did_complete)
[email protected]1339a2a22012-10-17 08:39:431584 resolver_->CacheResult(key_, entry, ttl);
[email protected]16ee26d2012-03-08 03:34:351585
[email protected]0f292de02012-02-01 22:28:201586 // Complete all of the requests that were attached to the job.
1587 for (RequestsList::const_iterator it = requests_.begin();
1588 it != requests_.end(); ++it) {
1589 Request* req = *it;
1590
1591 if (req->was_canceled())
1592 continue;
1593
1594 DCHECK_EQ(this, req->job());
1595 // Update the net log and notify registered observers.
1596 LogFinishRequest(req->source_net_log(), req->request_net_log(),
[email protected]895123222012-10-25 15:21:171597 req->info(), entry.error);
[email protected]51b9a6b2012-06-25 21:50:291598 if (did_complete) {
1599 // Record effective total time from creation to completion.
1600 RecordTotalTime(had_dns_config_, req->info().is_speculative(),
1601 base::TimeTicks::Now() - req->request_time());
1602 }
[email protected]895123222012-10-25 15:21:171603 req->OnComplete(entry.error, entry.addrlist);
[email protected]0f292de02012-02-01 22:28:201604
1605 // Check if the resolver was destroyed as a result of running the
1606 // callback. If it was, we could continue, but we choose to bail.
1607 if (!resolver_)
1608 return;
1609 }
1610 }
1611
[email protected]1339a2a22012-10-17 08:39:431612 // Convenience wrapper for CompleteRequests in case of failure.
1613 void CompleteRequestsWithError(int net_error) {
[email protected]895123222012-10-25 15:21:171614 CompleteRequests(HostCache::Entry(net_error, AddressList()),
1615 base::TimeDelta());
[email protected]1339a2a22012-10-17 08:39:431616 }
1617
[email protected]b4481b222012-03-16 17:13:111618 RequestPriority priority() const {
1619 return priority_tracker_.highest_priority();
1620 }
1621
1622 // Number of non-canceled requests in |requests_|.
1623 size_t num_active_requests() const {
1624 return priority_tracker_.total_count();
1625 }
1626
1627 bool is_dns_running() const {
1628 return dns_task_.get() != NULL;
1629 }
1630
1631 bool is_proc_running() const {
1632 return proc_task_.get() != NULL;
1633 }
1634
[email protected]0f292de02012-02-01 22:28:201635 base::WeakPtr<HostResolverImpl> resolver_;
1636
1637 Key key_;
1638
1639 // Tracks the highest priority across |requests_|.
1640 PriorityTracker priority_tracker_;
1641
1642 bool had_non_speculative_request_;
1643
[email protected]51b9a6b2012-06-25 21:50:291644 // Distinguishes measurements taken while DnsClient was fully configured.
1645 bool had_dns_config_;
1646
[email protected]1d932852012-06-19 19:40:331647 // Result of DnsTask.
1648 int dns_task_error_;
[email protected]1def74c2012-03-22 20:07:001649
[email protected]51b9a6b2012-06-25 21:50:291650 const base::TimeTicks creation_time_;
1651 base::TimeTicks priority_change_time_;
1652
[email protected]0f292de02012-02-01 22:28:201653 BoundNetLog net_log_;
1654
[email protected]b3601bc22012-02-21 21:23:201655 // Resolves the host using a HostResolverProc.
[email protected]0f292de02012-02-01 22:28:201656 scoped_refptr<ProcTask> proc_task_;
1657
[email protected]b3601bc22012-02-21 21:23:201658 // Resolves the host using a DnsTransaction.
1659 scoped_ptr<DnsTask> dns_task_;
1660
[email protected]0f292de02012-02-01 22:28:201661 // All Requests waiting for the result of this Job. Some can be canceled.
1662 RequestsList requests_;
1663
[email protected]16ee26d2012-03-08 03:34:351664 // A handle used in |HostResolverImpl::dispatcher_|.
[email protected]0f292de02012-02-01 22:28:201665 PrioritizedDispatcher::Handle handle_;
[email protected]68ad3ee2010-01-30 03:45:391666};
1667
1668//-----------------------------------------------------------------------------
1669
[email protected]0f292de02012-02-01 22:28:201670HostResolverImpl::ProcTaskParams::ProcTaskParams(
[email protected]e95d3aca2010-01-11 22:47:431671 HostResolverProc* resolver_proc,
[email protected]0f292de02012-02-01 22:28:201672 size_t max_retry_attempts)
1673 : resolver_proc(resolver_proc),
1674 max_retry_attempts(max_retry_attempts),
1675 unresponsive_delay(base::TimeDelta::FromMilliseconds(6000)),
1676 retry_factor(2) {
1677}
1678
1679HostResolverImpl::ProcTaskParams::~ProcTaskParams() {}
1680
1681HostResolverImpl::HostResolverImpl(
[email protected]c54a8912012-10-22 22:09:431682 scoped_ptr<HostCache> cache,
[email protected]0f292de02012-02-01 22:28:201683 const PrioritizedDispatcher::Limits& job_limits,
1684 const ProcTaskParams& proc_params,
[email protected]ee094b82010-08-24 15:55:511685 NetLog* net_log)
[email protected]c54a8912012-10-22 22:09:431686 : cache_(cache.Pass()),
[email protected]0f292de02012-02-01 22:28:201687 dispatcher_(job_limits),
1688 max_queued_jobs_(job_limits.total_jobs * 100u),
1689 proc_params_(proc_params),
[email protected]62e86ba2013-01-29 18:59:161690 net_log_(net_log),
[email protected]0c7798452009-10-26 17:59:511691 default_address_family_(ADDRESS_FAMILY_UNSPECIFIED),
[email protected]4589a3a2012-09-20 20:57:071692 weak_ptr_factory_(this),
[email protected]12faa4c2012-11-06 04:44:181693 probe_weak_ptr_factory_(this),
[email protected]d7b9a2b2012-05-31 22:31:191694 received_dns_config_(false),
[email protected]f0f602bd2012-11-15 18:01:021695 num_dns_failures_(0),
[email protected]2f3bc65c2010-07-23 17:47:101696 ipv6_probe_monitoring_(false),
[email protected]62e86ba2013-01-29 18:59:161697 resolved_known_ipv6_hostname_(false),
1698 additional_resolver_flags_(0) {
[email protected]0f292de02012-02-01 22:28:201699
1700 DCHECK_GE(dispatcher_.num_priorities(), static_cast<size_t>(NUM_PRIORITIES));
[email protected]68ad3ee2010-01-30 03:45:391701
[email protected]06ef6d92011-05-19 04:24:581702 // Maximum of 4 retry attempts for host resolution.
1703 static const size_t kDefaultMaxRetryAttempts = 4u;
1704
[email protected]0f292de02012-02-01 22:28:201705 if (proc_params_.max_retry_attempts == HostResolver::kDefaultRetryAttempts)
1706 proc_params_.max_retry_attempts = kDefaultMaxRetryAttempts;
[email protected]68ad3ee2010-01-30 03:45:391707
[email protected]b59ff372009-07-15 22:04:321708#if defined(OS_WIN)
1709 EnsureWinsockInit();
1710#endif
[email protected]23f771162011-06-02 18:37:511711#if defined(OS_POSIX) && !defined(OS_MACOSX)
[email protected]12faa4c2012-11-06 04:44:181712 new LoopbackProbeJob(weak_ptr_factory_.GetWeakPtr());
[email protected]2f3bc65c2010-07-23 17:47:101713#endif
[email protected]232a5812011-03-04 22:42:081714 NetworkChangeNotifier::AddIPAddressObserver(this);
[email protected]bb0e34542012-08-31 19:52:401715 NetworkChangeNotifier::AddDNSObserver(this);
[email protected]d7b9a2b2012-05-31 22:31:191716#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD) && \
1717 !defined(OS_ANDROID)
[email protected]d7b9a2b2012-05-31 22:31:191718 EnsureDnsReloaderInit();
[email protected]46018c9d2011-09-06 03:42:341719#endif
[email protected]2ac22db2012-11-28 19:50:041720
1721 // TODO(szym): Remove when received_dns_config_ is removed, once
1722 // http://crbug.com/137914 is resolved.
1723 {
1724 DnsConfig dns_config;
1725 NetworkChangeNotifier::GetDnsConfig(&dns_config);
1726 received_dns_config_ = dns_config.IsValid();
1727 }
[email protected]b59ff372009-07-15 22:04:321728}
1729
1730HostResolverImpl::~HostResolverImpl() {
[email protected]0f292de02012-02-01 22:28:201731 // This will also cancel all outstanding requests.
1732 STLDeleteValues(&jobs_);
[email protected]e95d3aca2010-01-11 22:47:431733
[email protected]232a5812011-03-04 22:42:081734 NetworkChangeNotifier::RemoveIPAddressObserver(this);
[email protected]bb0e34542012-08-31 19:52:401735 NetworkChangeNotifier::RemoveDNSObserver(this);
[email protected]b59ff372009-07-15 22:04:321736}
1737
[email protected]0f292de02012-02-01 22:28:201738void HostResolverImpl::SetMaxQueuedJobs(size_t value) {
1739 DCHECK_EQ(0u, dispatcher_.num_queued_jobs());
1740 DCHECK_GT(value, 0u);
1741 max_queued_jobs_ = value;
[email protected]be1a48b2011-01-20 00:12:131742}
1743
[email protected]684970b2009-08-14 04:54:461744int HostResolverImpl::Resolve(const RequestInfo& info,
[email protected]b59ff372009-07-15 22:04:321745 AddressList* addresses,
[email protected]aa22b242011-11-16 18:58:291746 const CompletionCallback& callback,
[email protected]684970b2009-08-14 04:54:461747 RequestHandle* out_req,
[email protected]ee094b82010-08-24 15:55:511748 const BoundNetLog& source_net_log) {
[email protected]95a214c2011-08-04 21:50:401749 DCHECK(addresses);
[email protected]1ac6af92010-06-03 21:00:141750 DCHECK(CalledOnValidThread());
[email protected]aa22b242011-11-16 18:58:291751 DCHECK_EQ(false, callback.is_null());
[email protected]1ac6af92010-06-03 21:00:141752
[email protected]ee094b82010-08-24 15:55:511753 // Make a log item for the request.
1754 BoundNetLog request_net_log = BoundNetLog::Make(net_log_,
1755 NetLog::SOURCE_HOST_RESOLVER_IMPL_REQUEST);
1756
[email protected]0f292de02012-02-01 22:28:201757 LogStartRequest(source_net_log, request_net_log, info);
[email protected]b59ff372009-07-15 22:04:321758
[email protected]123ab1e32009-10-21 19:12:571759 // Build a key that identifies the request in the cache and in the
1760 // outstanding jobs map.
[email protected]137af622010-02-05 02:14:351761 Key key = GetEffectiveKeyForRequest(info);
[email protected]123ab1e32009-10-21 19:12:571762
[email protected]287d7c22011-11-15 17:34:251763 int rv = ResolveHelper(key, info, addresses, request_net_log);
[email protected]95a214c2011-08-04 21:50:401764 if (rv != ERR_DNS_CACHE_MISS) {
[email protected]b3601bc22012-02-21 21:23:201765 LogFinishRequest(source_net_log, request_net_log, info, rv);
[email protected]51b9a6b2012-06-25 21:50:291766 RecordTotalTime(HaveDnsConfig(), info.is_speculative(), base::TimeDelta());
[email protected]95a214c2011-08-04 21:50:401767 return rv;
[email protected]38368712011-03-02 08:09:401768 }
1769
[email protected]0f292de02012-02-01 22:28:201770 // Next we need to attach our request to a "job". This job is responsible for
1771 // calling "getaddrinfo(hostname)" on a worker thread.
1772
1773 JobMap::iterator jobit = jobs_.find(key);
1774 Job* job;
1775 if (jobit == jobs_.end()) {
[email protected]12faa4c2012-11-06 04:44:181776 job = new Job(weak_ptr_factory_.GetWeakPtr(), key, info.priority(),
1777 request_net_log);
[email protected]8c98d002012-07-18 19:02:271778 job->Schedule();
[email protected]0f292de02012-02-01 22:28:201779
1780 // Check for queue overflow.
1781 if (dispatcher_.num_queued_jobs() > max_queued_jobs_) {
1782 Job* evicted = static_cast<Job*>(dispatcher_.EvictOldestLowest());
1783 DCHECK(evicted);
[email protected]16ee26d2012-03-08 03:34:351784 evicted->OnEvicted(); // Deletes |evicted|.
[email protected]0f292de02012-02-01 22:28:201785 if (evicted == job) {
[email protected]0f292de02012-02-01 22:28:201786 rv = ERR_HOST_RESOLVER_QUEUE_TOO_LARGE;
[email protected]b3601bc22012-02-21 21:23:201787 LogFinishRequest(source_net_log, request_net_log, info, rv);
[email protected]0f292de02012-02-01 22:28:201788 return rv;
1789 }
[email protected]0f292de02012-02-01 22:28:201790 }
[email protected]0f292de02012-02-01 22:28:201791 jobs_.insert(jobit, std::make_pair(key, job));
1792 } else {
1793 job = jobit->second;
1794 }
1795
1796 // Can't complete synchronously. Create and attach request.
[email protected]b3601bc22012-02-21 21:23:201797 scoped_ptr<Request> req(new Request(source_net_log,
1798 request_net_log,
1799 info,
1800 callback,
1801 addresses));
[email protected]b59ff372009-07-15 22:04:321802 if (out_req)
[email protected]b3601bc22012-02-21 21:23:201803 *out_req = reinterpret_cast<RequestHandle>(req.get());
[email protected]b59ff372009-07-15 22:04:321804
[email protected]b3601bc22012-02-21 21:23:201805 job->AddRequest(req.Pass());
[email protected]0f292de02012-02-01 22:28:201806 // Completion happens during Job::CompleteRequests().
[email protected]b59ff372009-07-15 22:04:321807 return ERR_IO_PENDING;
1808}
1809
[email protected]287d7c22011-11-15 17:34:251810int HostResolverImpl::ResolveHelper(const Key& key,
[email protected]95a214c2011-08-04 21:50:401811 const RequestInfo& info,
1812 AddressList* addresses,
[email protected]20cd5332011-10-12 22:38:001813 const BoundNetLog& request_net_log) {
[email protected]95a214c2011-08-04 21:50:401814 // The result of |getaddrinfo| for empty hosts is inconsistent across systems.
1815 // On Windows it gives the default interface's address, whereas on Linux it
1816 // gives an error. We will make it fail on all platforms for consistency.
1817 if (info.hostname().empty() || info.hostname().size() > kMaxHostLength)
1818 return ERR_NAME_NOT_RESOLVED;
1819
1820 int net_error = ERR_UNEXPECTED;
1821 if (ResolveAsIP(key, info, &net_error, addresses))
1822 return net_error;
[email protected]78eac2a2012-03-14 19:09:271823 if (ServeFromCache(key, info, &net_error, addresses)) {
[email protected]4da911f2012-06-14 19:45:201824 request_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_CACHE_HIT);
[email protected]78eac2a2012-03-14 19:09:271825 return net_error;
1826 }
1827 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
1828 // http://crbug.com/117655
1829 if (ServeFromHosts(key, info, addresses)) {
[email protected]4da911f2012-06-14 19:45:201830 request_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_HOSTS_HIT);
[email protected]78eac2a2012-03-14 19:09:271831 return OK;
1832 }
1833 return ERR_DNS_CACHE_MISS;
[email protected]95a214c2011-08-04 21:50:401834}
1835
1836int HostResolverImpl::ResolveFromCache(const RequestInfo& info,
1837 AddressList* addresses,
1838 const BoundNetLog& source_net_log) {
1839 DCHECK(CalledOnValidThread());
1840 DCHECK(addresses);
1841
[email protected]95a214c2011-08-04 21:50:401842 // Make a log item for the request.
1843 BoundNetLog request_net_log = BoundNetLog::Make(net_log_,
1844 NetLog::SOURCE_HOST_RESOLVER_IMPL_REQUEST);
1845
1846 // Update the net log and notify registered observers.
[email protected]0f292de02012-02-01 22:28:201847 LogStartRequest(source_net_log, request_net_log, info);
[email protected]95a214c2011-08-04 21:50:401848
[email protected]95a214c2011-08-04 21:50:401849 Key key = GetEffectiveKeyForRequest(info);
1850
[email protected]287d7c22011-11-15 17:34:251851 int rv = ResolveHelper(key, info, addresses, request_net_log);
[email protected]b3601bc22012-02-21 21:23:201852 LogFinishRequest(source_net_log, request_net_log, info, rv);
[email protected]95a214c2011-08-04 21:50:401853 return rv;
1854}
1855
[email protected]b59ff372009-07-15 22:04:321856void HostResolverImpl::CancelRequest(RequestHandle req_handle) {
[email protected]1ac6af92010-06-03 21:00:141857 DCHECK(CalledOnValidThread());
[email protected]b59ff372009-07-15 22:04:321858 Request* req = reinterpret_cast<Request*>(req_handle);
1859 DCHECK(req);
[email protected]0f292de02012-02-01 22:28:201860 Job* job = req->job();
1861 DCHECK(job);
[email protected]0f292de02012-02-01 22:28:201862 job->CancelRequest(req);
[email protected]b59ff372009-07-15 22:04:321863}
1864
[email protected]0f8f1b432010-03-16 19:06:031865void HostResolverImpl::SetDefaultAddressFamily(AddressFamily address_family) {
[email protected]1ac6af92010-06-03 21:00:141866 DCHECK(CalledOnValidThread());
[email protected]0f8f1b432010-03-16 19:06:031867 default_address_family_ = address_family;
[email protected]12faa4c2012-11-06 04:44:181868 ipv6_probe_monitoring_ = false;
[email protected]0f8f1b432010-03-16 19:06:031869}
1870
[email protected]f7d310e2010-10-07 16:25:111871AddressFamily HostResolverImpl::GetDefaultAddressFamily() const {
1872 return default_address_family_;
1873}
1874
[email protected]9db6f702013-04-10 18:10:511875// TODO(szym): Remove this API altogether if IPv6ActiveProbe works.
[email protected]a78f4272011-10-21 19:16:331876void HostResolverImpl::ProbeIPv6Support() {
1877 DCHECK(CalledOnValidThread());
1878 DCHECK(!ipv6_probe_monitoring_);
1879 ipv6_probe_monitoring_ = true;
[email protected]12faa4c2012-11-06 04:44:181880 OnIPAddressChanged();
[email protected]ddb1e5a2010-12-13 20:10:451881}
1882
[email protected]a8883e452012-11-17 05:58:061883void HostResolverImpl::SetDnsClientEnabled(bool enabled) {
1884 DCHECK(CalledOnValidThread());
1885#if defined(ENABLE_BUILT_IN_DNS)
1886 if (enabled && !dns_client_) {
1887 SetDnsClient(DnsClient::CreateClient(net_log_));
1888 } else if (!enabled && dns_client_) {
1889 SetDnsClient(scoped_ptr<DnsClient>());
1890 }
1891#endif
1892}
1893
[email protected]489d1a82011-10-12 03:09:111894HostCache* HostResolverImpl::GetHostCache() {
1895 return cache_.get();
1896}
[email protected]95a214c2011-08-04 21:50:401897
[email protected]17e92032012-03-29 00:56:241898base::Value* HostResolverImpl::GetDnsConfigAsValue() const {
1899 // Check if async DNS is disabled.
1900 if (!dns_client_.get())
1901 return NULL;
1902
1903 // Check if async DNS is enabled, but we currently have no configuration
1904 // for it.
1905 const DnsConfig* dns_config = dns_client_->GetConfig();
1906 if (dns_config == NULL)
1907 return new DictionaryValue();
1908
1909 return dns_config->ToValue();
1910}
1911
[email protected]95a214c2011-08-04 21:50:401912bool HostResolverImpl::ResolveAsIP(const Key& key,
1913 const RequestInfo& info,
1914 int* net_error,
1915 AddressList* addresses) {
1916 DCHECK(addresses);
1917 DCHECK(net_error);
1918 IPAddressNumber ip_number;
1919 if (!ParseIPLiteralToNumber(key.hostname, &ip_number))
1920 return false;
1921
1922 DCHECK_EQ(key.host_resolver_flags &
1923 ~(HOST_RESOLVER_CANONNAME | HOST_RESOLVER_LOOPBACK_ONLY |
1924 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6),
1925 0) << " Unhandled flag";
[email protected]0f292de02012-02-01 22:28:201926 bool ipv6_disabled = (default_address_family_ == ADDRESS_FAMILY_IPV4) &&
1927 !ipv6_probe_monitoring_;
[email protected]95a214c2011-08-04 21:50:401928 *net_error = OK;
[email protected]0f292de02012-02-01 22:28:201929 if ((ip_number.size() == kIPv6AddressSize) && ipv6_disabled) {
[email protected]95a214c2011-08-04 21:50:401930 *net_error = ERR_NAME_NOT_RESOLVED;
1931 } else {
[email protected]7054e78f2012-05-07 21:44:561932 *addresses = AddressList::CreateFromIPAddress(ip_number, info.port());
1933 if (key.host_resolver_flags & HOST_RESOLVER_CANONNAME)
1934 addresses->SetDefaultCanonicalName();
[email protected]95a214c2011-08-04 21:50:401935 }
1936 return true;
1937}
1938
1939bool HostResolverImpl::ServeFromCache(const Key& key,
1940 const RequestInfo& info,
[email protected]95a214c2011-08-04 21:50:401941 int* net_error,
1942 AddressList* addresses) {
1943 DCHECK(addresses);
1944 DCHECK(net_error);
1945 if (!info.allow_cached_response() || !cache_.get())
1946 return false;
1947
[email protected]407a30ab2012-08-15 17:16:101948 const HostCache::Entry* cache_entry = cache_->Lookup(
1949 key, base::TimeTicks::Now());
[email protected]95a214c2011-08-04 21:50:401950 if (!cache_entry)
1951 return false;
1952
[email protected]95a214c2011-08-04 21:50:401953 *net_error = cache_entry->error;
[email protected]7054e78f2012-05-07 21:44:561954 if (*net_error == OK) {
[email protected]1339a2a22012-10-17 08:39:431955 if (cache_entry->has_ttl())
1956 RecordTTL(cache_entry->ttl);
[email protected]895123222012-10-25 15:21:171957 *addresses = EnsurePortOnAddressList(cache_entry->addrlist, info.port());
[email protected]7054e78f2012-05-07 21:44:561958 }
[email protected]95a214c2011-08-04 21:50:401959 return true;
1960}
1961
[email protected]78eac2a2012-03-14 19:09:271962bool HostResolverImpl::ServeFromHosts(const Key& key,
1963 const RequestInfo& info,
1964 AddressList* addresses) {
1965 DCHECK(addresses);
1966 if (!HaveDnsConfig())
1967 return false;
1968
[email protected]05a79d42013-03-28 07:30:091969 addresses->clear();
1970
[email protected]cb507622012-03-23 16:17:061971 // HOSTS lookups are case-insensitive.
1972 std::string hostname = StringToLowerASCII(key.hostname);
1973
[email protected]05a79d42013-03-28 07:30:091974 const DnsHosts& hosts = dns_client_->GetConfig()->hosts;
1975
[email protected]78eac2a2012-03-14 19:09:271976 // If |address_family| is ADDRESS_FAMILY_UNSPECIFIED other implementations
1977 // (glibc and c-ares) return the first matching line. We have more
1978 // flexibility, but lose implicit ordering.
[email protected]05a79d42013-03-28 07:30:091979 // We prefer IPv6 because "happy eyeballs" will fall back to IPv4 if
1980 // necessary.
1981 if (key.address_family == ADDRESS_FAMILY_IPV6 ||
1982 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
1983 DnsHosts::const_iterator it = hosts.find(
1984 DnsHostsKey(hostname, ADDRESS_FAMILY_IPV6));
1985 if (it != hosts.end())
1986 addresses->push_back(IPEndPoint(it->second, info.port()));
[email protected]78eac2a2012-03-14 19:09:271987 }
1988
[email protected]05a79d42013-03-28 07:30:091989 if (key.address_family == ADDRESS_FAMILY_IPV4 ||
1990 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
1991 DnsHosts::const_iterator it = hosts.find(
1992 DnsHostsKey(hostname, ADDRESS_FAMILY_IPV4));
1993 if (it != hosts.end())
1994 addresses->push_back(IPEndPoint(it->second, info.port()));
1995 }
1996
1997 return !addresses->empty();
[email protected]78eac2a2012-03-14 19:09:271998}
1999
[email protected]16ee26d2012-03-08 03:34:352000void HostResolverImpl::CacheResult(const Key& key,
[email protected]1339a2a22012-10-17 08:39:432001 const HostCache::Entry& entry,
[email protected]16ee26d2012-03-08 03:34:352002 base::TimeDelta ttl) {
2003 if (cache_.get())
[email protected]1339a2a22012-10-17 08:39:432004 cache_->Set(key, entry, base::TimeTicks::Now(), ttl);
[email protected]ef4c40c2010-09-01 14:42:032005}
2006
[email protected]0f292de02012-02-01 22:28:202007void HostResolverImpl::RemoveJob(Job* job) {
2008 DCHECK(job);
[email protected]16ee26d2012-03-08 03:34:352009 JobMap::iterator it = jobs_.find(job->key());
2010 if (it != jobs_.end() && it->second == job)
2011 jobs_.erase(it);
[email protected]b59ff372009-07-15 22:04:322012}
2013
[email protected]0f8f1b432010-03-16 19:06:032014void HostResolverImpl::IPv6ProbeSetDefaultAddressFamily(
2015 AddressFamily address_family) {
2016 DCHECK(address_family == ADDRESS_FAMILY_UNSPECIFIED ||
2017 address_family == ADDRESS_FAMILY_IPV4);
[email protected]12faa4c2012-11-06 04:44:182018 if (!ipv6_probe_monitoring_)
2019 return;
[email protected]f092e64b2010-03-17 00:39:182020 if (default_address_family_ != address_family) {
[email protected]b30a3f52010-10-16 01:05:462021 VLOG(1) << "IPv6Probe forced AddressFamily setting to "
2022 << ((address_family == ADDRESS_FAMILY_UNSPECIFIED) ?
2023 "ADDRESS_FAMILY_UNSPECIFIED" : "ADDRESS_FAMILY_IPV4");
[email protected]f092e64b2010-03-17 00:39:182024 }
[email protected]0f8f1b432010-03-16 19:06:032025 default_address_family_ = address_family;
[email protected]e95d3aca2010-01-11 22:47:432026}
2027
[email protected]9936a7862012-10-26 04:44:022028void HostResolverImpl::SetHaveOnlyLoopbackAddresses(bool result) {
2029 if (result) {
2030 additional_resolver_flags_ |= HOST_RESOLVER_LOOPBACK_ONLY;
2031 } else {
2032 additional_resolver_flags_ &= ~HOST_RESOLVER_LOOPBACK_ONLY;
2033 }
2034}
2035
[email protected]137af622010-02-05 02:14:352036HostResolverImpl::Key HostResolverImpl::GetEffectiveKeyForRequest(
2037 const RequestInfo& info) const {
[email protected]eaf3a3b2010-09-03 20:34:272038 HostResolverFlags effective_flags =
2039 info.host_resolver_flags() | additional_resolver_flags_;
[email protected]137af622010-02-05 02:14:352040 AddressFamily effective_address_family = info.address_family();
[email protected]9db6f702013-04-10 18:10:512041
2042 if (info.address_family() == ADDRESS_FAMILY_UNSPECIFIED) {
2043 base::TimeTicks start_time = base::TimeTicks::Now();
2044 // Google DNS address.
2045 const uint8 kIPv6Address[] =
2046 { 0x20, 0x01, 0x48, 0x60, 0x48, 0x60, 0x00, 0x00,
2047 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x88 };
2048 int rv6 = AttemptRoute(
2049 IPAddressNumber(kIPv6Address, kIPv6Address + arraysize(kIPv6Address)));
2050
2051 UMA_HISTOGRAM_TIMES("Net.IPv6ConnectDuration",
2052 base::TimeTicks::Now() - start_time);
2053 if (rv6 == OK) {
2054 UMA_HISTOGRAM_BOOLEAN("Net.IPv6ConnectSuccessMatch",
2055 default_address_family_ == ADDRESS_FAMILY_UNSPECIFIED);
2056 } else {
2057 UMA_HISTOGRAM_BOOLEAN("Net.IPv6ConnectFailureMatch",
2058 default_address_family_ != ADDRESS_FAMILY_UNSPECIFIED);
2059 }
2060 }
2061
[email protected]eaf3a3b2010-09-03 20:34:272062 if (effective_address_family == ADDRESS_FAMILY_UNSPECIFIED &&
2063 default_address_family_ != ADDRESS_FAMILY_UNSPECIFIED) {
[email protected]137af622010-02-05 02:14:352064 effective_address_family = default_address_family_;
[email protected]eaf3a3b2010-09-03 20:34:272065 if (ipv6_probe_monitoring_)
2066 effective_flags |= HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
2067 }
[email protected]9db6f702013-04-10 18:10:512068
[email protected]eaf3a3b2010-09-03 20:34:272069 return Key(info.hostname(), effective_address_family, effective_flags);
[email protected]137af622010-02-05 02:14:352070}
2071
[email protected]35ddc282010-09-21 23:42:062072void HostResolverImpl::AbortAllInProgressJobs() {
[email protected]b3601bc22012-02-21 21:23:202073 // In Abort, a Request callback could spawn new Jobs with matching keys, so
2074 // first collect and remove all running jobs from |jobs_|.
[email protected]c143d892012-04-06 07:56:542075 ScopedVector<Job> jobs_to_abort;
[email protected]0f292de02012-02-01 22:28:202076 for (JobMap::iterator it = jobs_.begin(); it != jobs_.end(); ) {
2077 Job* job = it->second;
[email protected]0f292de02012-02-01 22:28:202078 if (job->is_running()) {
[email protected]b3601bc22012-02-21 21:23:202079 jobs_to_abort.push_back(job);
2080 jobs_.erase(it++);
[email protected]0f292de02012-02-01 22:28:202081 } else {
[email protected]b3601bc22012-02-21 21:23:202082 DCHECK(job->is_queued());
2083 ++it;
[email protected]0f292de02012-02-01 22:28:202084 }
[email protected]ef4c40c2010-09-01 14:42:032085 }
[email protected]b3601bc22012-02-21 21:23:202086
[email protected]57a48d32012-03-03 00:04:552087 // Check if no dispatcher slots leaked out.
2088 DCHECK_EQ(dispatcher_.num_running_jobs(), jobs_to_abort.size());
2089
2090 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072091 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]57a48d32012-03-03 00:04:552092
[email protected]16ee26d2012-03-08 03:34:352093 // Then Abort them.
[email protected]57a48d32012-03-03 00:04:552094 for (size_t i = 0; self && i < jobs_to_abort.size(); ++i) {
[email protected]57a48d32012-03-03 00:04:552095 jobs_to_abort[i]->Abort();
[email protected]c143d892012-04-06 07:56:542096 jobs_to_abort[i] = NULL;
[email protected]b3601bc22012-02-21 21:23:202097 }
[email protected]ef4c40c2010-09-01 14:42:032098}
2099
[email protected]78eac2a2012-03-14 19:09:272100void HostResolverImpl::TryServingAllJobsFromHosts() {
2101 if (!HaveDnsConfig())
2102 return;
2103
2104 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2105 // http://crbug.com/117655
2106
2107 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072108 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]78eac2a2012-03-14 19:09:272109
2110 for (JobMap::iterator it = jobs_.begin(); self && it != jobs_.end(); ) {
2111 Job* job = it->second;
2112 ++it;
2113 // This could remove |job| from |jobs_|, but iterator will remain valid.
2114 job->ServeFromHosts();
2115 }
2116}
2117
[email protected]be1a48b2011-01-20 00:12:132118void HostResolverImpl::OnIPAddressChanged() {
[email protected]62e86ba2013-01-29 18:59:162119 resolved_known_ipv6_hostname_ = false;
[email protected]12faa4c2012-11-06 04:44:182120 // Abandon all ProbeJobs.
2121 probe_weak_ptr_factory_.InvalidateWeakPtrs();
[email protected]be1a48b2011-01-20 00:12:132122 if (cache_.get())
2123 cache_->clear();
[email protected]12faa4c2012-11-06 04:44:182124 if (ipv6_probe_monitoring_)
2125 new IPv6ProbeJob(probe_weak_ptr_factory_.GetWeakPtr(), net_log_);
[email protected]23f771162011-06-02 18:37:512126#if defined(OS_POSIX) && !defined(OS_MACOSX)
[email protected]12faa4c2012-11-06 04:44:182127 new LoopbackProbeJob(probe_weak_ptr_factory_.GetWeakPtr());
[email protected]be1a48b2011-01-20 00:12:132128#endif
2129 AbortAllInProgressJobs();
2130 // |this| may be deleted inside AbortAllInProgressJobs().
2131}
2132
[email protected]bb0e34542012-08-31 19:52:402133void HostResolverImpl::OnDNSChanged() {
2134 DnsConfig dns_config;
2135 NetworkChangeNotifier::GetDnsConfig(&dns_config);
[email protected]b4481b222012-03-16 17:13:112136 if (net_log_) {
2137 net_log_->AddGlobalEntry(
2138 NetLog::TYPE_DNS_CONFIG_CHANGED,
[email protected]cd565142012-06-12 16:21:452139 base::Bind(&NetLogDnsConfigCallback, &dns_config));
[email protected]b4481b222012-03-16 17:13:112140 }
2141
[email protected]01b3b9d2012-08-13 16:18:142142 // TODO(szym): Remove once http://crbug.com/137914 is resolved.
[email protected]d7b9a2b2012-05-31 22:31:192143 received_dns_config_ = dns_config.IsValid();
[email protected]78eac2a2012-03-14 19:09:272144
[email protected]a8883e452012-11-17 05:58:062145 num_dns_failures_ = 0;
2146
[email protected]01b3b9d2012-08-13 16:18:142147 // We want a new DnsSession in place, before we Abort running Jobs, so that
2148 // the newly started jobs use the new config.
[email protected]f0f602bd2012-11-15 18:01:022149 if (dns_client_.get()) {
[email protected]d7b9a2b2012-05-31 22:31:192150 dns_client_->SetConfig(dns_config);
[email protected]a8883e452012-11-17 05:58:062151 if (dns_config.IsValid())
[email protected]f0f602bd2012-11-15 18:01:022152 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
[email protected]f0f602bd2012-11-15 18:01:022153 }
[email protected]01b3b9d2012-08-13 16:18:142154
2155 // If the DNS server has changed, existing cached info could be wrong so we
2156 // have to drop our internal cache :( Note that OS level DNS caches, such
2157 // as NSCD's cache should be dropped automatically by the OS when
2158 // resolv.conf changes so we don't need to do anything to clear that cache.
2159 if (cache_.get())
2160 cache_->clear();
2161
[email protected]f0f602bd2012-11-15 18:01:022162 // Life check to bail once |this| is deleted.
2163 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
2164
[email protected]01b3b9d2012-08-13 16:18:142165 // Existing jobs will have been sent to the original server so they need to
2166 // be aborted.
2167 AbortAllInProgressJobs();
2168
2169 // |this| may be deleted inside AbortAllInProgressJobs().
2170 if (self)
2171 TryServingAllJobsFromHosts();
[email protected]78eac2a2012-03-14 19:09:272172}
2173
2174bool HostResolverImpl::HaveDnsConfig() const {
[email protected]32b1dbcf2013-01-26 03:48:252175 // Use DnsClient only if it's fully configured and there is no override by
2176 // ScopedDefaultHostResolverProc.
2177 // The alternative is to use NetworkChangeNotifier to override DnsConfig,
2178 // but that would introduce construction order requirements for NCN and SDHRP.
2179 return (dns_client_.get() != NULL) &&
2180 (dns_client_->GetConfig() != NULL) &&
2181 !(proc_params_.resolver_proc == NULL &&
2182 HostResolverProc::GetDefault() != NULL);
[email protected]b3601bc22012-02-21 21:23:202183}
2184
[email protected]1ffdda82012-12-12 23:04:222185void HostResolverImpl::OnDnsTaskResolve(int net_error) {
[email protected]f0f602bd2012-11-15 18:01:022186 DCHECK(dns_client_);
[email protected]1ffdda82012-12-12 23:04:222187 if (net_error == OK) {
[email protected]f0f602bd2012-11-15 18:01:022188 num_dns_failures_ = 0;
2189 return;
2190 }
2191 ++num_dns_failures_;
2192 if (num_dns_failures_ < kMaximumDnsFailures)
2193 return;
2194 // Disable DnsClient until the next DNS change.
2195 for (JobMap::iterator it = jobs_.begin(); it != jobs_.end(); ++it)
2196 it->second->AbortDnsTask();
2197 dns_client_->SetConfig(DnsConfig());
2198 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", false);
[email protected]1ffdda82012-12-12 23:04:222199 UMA_HISTOGRAM_CUSTOM_ENUMERATION("AsyncDNS.DnsClientDisabledReason",
2200 std::abs(net_error),
2201 GetAllErrorCodesForUma());
[email protected]f0f602bd2012-11-15 18:01:022202}
2203
[email protected]a8883e452012-11-17 05:58:062204void HostResolverImpl::SetDnsClient(scoped_ptr<DnsClient> dns_client) {
2205 if (HaveDnsConfig()) {
2206 for (JobMap::iterator it = jobs_.begin(); it != jobs_.end(); ++it)
2207 it->second->AbortDnsTask();
2208 }
2209 dns_client_ = dns_client.Pass();
2210 if (!dns_client_ || dns_client_->GetConfig() ||
2211 num_dns_failures_ >= kMaximumDnsFailures) {
2212 return;
2213 }
2214 DnsConfig dns_config;
2215 NetworkChangeNotifier::GetDnsConfig(&dns_config);
2216 dns_client_->SetConfig(dns_config);
2217 num_dns_failures_ = 0;
2218 if (dns_config.IsValid())
2219 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
2220}
2221
[email protected]b59ff372009-07-15 22:04:322222} // namespace net