blob: 4b6bb3ad1025b8ec5045e578e77211ef12ef6ea1 [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
5#include "net/base/host_resolver_impl.h"
6
[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]b59ff372009-07-15 22:04:3237#include "net/base/host_resolver_proc.h"
[email protected]2bb04442010-08-18 18:01:1538#include "net/base/net_errors.h"
[email protected]ee094b82010-08-24 15:55:5139#include "net/base/net_log.h"
[email protected]0f8f1b432010-03-16 19:06:0340#include "net/base/net_util.h"
[email protected]0adcb2b2012-08-15 21:30:4641#include "net/dns/address_sorter.h"
[email protected]78eac2a2012-03-14 19:09:2742#include "net/dns/dns_client.h"
[email protected]b3601bc22012-02-21 21:23:2043#include "net/dns/dns_config_service.h"
44#include "net/dns/dns_protocol.h"
45#include "net/dns/dns_response.h"
[email protected]b3601bc22012-02-21 21:23:2046#include "net/dns/dns_transaction.h"
[email protected]b59ff372009-07-15 22:04:3247
48#if defined(OS_WIN)
49#include "net/base/winsock_init.h"
50#endif
51
52namespace net {
53
[email protected]e95d3aca2010-01-11 22:47:4354namespace {
55
[email protected]6e78dfb2011-07-28 21:34:4756// Limit the size of hostnames that will be resolved to combat issues in
57// some platform's resolvers.
58const size_t kMaxHostLength = 4096;
59
[email protected]a2730882012-01-21 00:56:2760// Default TTL for successful resolutions with ProcTask.
61const unsigned kCacheEntryTTLSeconds = 60;
62
[email protected]b3601bc22012-02-21 21:23:2063// Default TTL for unsuccessful resolutions with ProcTask.
64const unsigned kNegativeCacheEntryTTLSeconds = 0;
65
[email protected]895123222012-10-25 15:21:1766// Minimum TTL for successful resolutions with DnsTask.
67const unsigned kMinimumTTLSeconds = kCacheEntryTTLSeconds;
68
[email protected]f0f602bd2012-11-15 18:01:0269// Number of consecutive failures of DnsTask (with successful fallback) before
70// the DnsClient is disabled until the next DNS change.
71const unsigned kMaximumDnsFailures = 16;
72
[email protected]24f4bab2010-10-15 01:27:1173// We use a separate histogram name for each platform to facilitate the
74// display of error codes by their symbolic name (since each platform has
75// different mappings).
76const char kOSErrorsForGetAddrinfoHistogramName[] =
77#if defined(OS_WIN)
78 "Net.OSErrorsForGetAddrinfo_Win";
79#elif defined(OS_MACOSX)
80 "Net.OSErrorsForGetAddrinfo_Mac";
81#elif defined(OS_LINUX)
82 "Net.OSErrorsForGetAddrinfo_Linux";
83#else
84 "Net.OSErrorsForGetAddrinfo";
85#endif
86
[email protected]c89b2442011-05-26 14:28:2787// Gets a list of the likely error codes that getaddrinfo() can return
88// (non-exhaustive). These are the error codes that we will track via
89// a histogram.
90std::vector<int> GetAllGetAddrinfoOSErrors() {
91 int os_errors[] = {
92#if defined(OS_POSIX)
[email protected]23f771162011-06-02 18:37:5193#if !defined(OS_FREEBSD)
[email protected]39588992011-07-11 19:54:3794#if !defined(OS_ANDROID)
[email protected]c48aef92011-11-22 23:41:4595 // EAI_ADDRFAMILY has been declared obsolete in Android's and
96 // FreeBSD's netdb.h.
[email protected]c89b2442011-05-26 14:28:2797 EAI_ADDRFAMILY,
[email protected]39588992011-07-11 19:54:3798#endif
[email protected]c48aef92011-11-22 23:41:4599 // EAI_NODATA has been declared obsolete in FreeBSD's netdb.h.
[email protected]23f771162011-06-02 18:37:51100 EAI_NODATA,
101#endif
[email protected]c89b2442011-05-26 14:28:27102 EAI_AGAIN,
103 EAI_BADFLAGS,
104 EAI_FAIL,
105 EAI_FAMILY,
106 EAI_MEMORY,
[email protected]c89b2442011-05-26 14:28:27107 EAI_NONAME,
108 EAI_SERVICE,
109 EAI_SOCKTYPE,
110 EAI_SYSTEM,
111#elif defined(OS_WIN)
112 // See: http://msdn.microsoft.com/en-us/library/ms738520(VS.85).aspx
113 WSA_NOT_ENOUGH_MEMORY,
114 WSAEAFNOSUPPORT,
115 WSAEINVAL,
116 WSAESOCKTNOSUPPORT,
117 WSAHOST_NOT_FOUND,
118 WSANO_DATA,
119 WSANO_RECOVERY,
120 WSANOTINITIALISED,
121 WSATRY_AGAIN,
122 WSATYPE_NOT_FOUND,
123 // The following are not in doc, but might be to appearing in results :-(.
124 WSA_INVALID_HANDLE,
125#endif
126 };
127
128 // Ensure all errors are positive, as histogram only tracks positive values.
129 for (size_t i = 0; i < arraysize(os_errors); ++i) {
130 os_errors[i] = std::abs(os_errors[i]);
131 }
132
133 return base::CustomHistogram::ArrayToCustomRanges(os_errors,
134 arraysize(os_errors));
135}
136
[email protected]1def74c2012-03-22 20:07:00137enum DnsResolveStatus {
138 RESOLVE_STATUS_DNS_SUCCESS = 0,
139 RESOLVE_STATUS_PROC_SUCCESS,
140 RESOLVE_STATUS_FAIL,
[email protected]1d932852012-06-19 19:40:33141 RESOLVE_STATUS_SUSPECT_NETBIOS,
[email protected]1def74c2012-03-22 20:07:00142 RESOLVE_STATUS_MAX
143};
144
145void UmaAsyncDnsResolveStatus(DnsResolveStatus result) {
146 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ResolveStatus",
147 result,
148 RESOLVE_STATUS_MAX);
149}
150
[email protected]1d932852012-06-19 19:40:33151bool ResemblesNetBIOSName(const std::string& hostname) {
152 return (hostname.size() < 16) && (hostname.find('.') == std::string::npos);
153}
154
155// True if |hostname| ends with either ".local" or ".local.".
156bool ResemblesMulticastDNSName(const std::string& hostname) {
157 DCHECK(!hostname.empty());
158 const char kSuffix[] = ".local.";
159 const size_t kSuffixLen = sizeof(kSuffix) - 1;
160 const size_t kSuffixLenTrimmed = kSuffixLen - 1;
161 if (hostname[hostname.size() - 1] == '.') {
162 return hostname.size() > kSuffixLen &&
163 !hostname.compare(hostname.size() - kSuffixLen, kSuffixLen, kSuffix);
164 }
165 return hostname.size() > kSuffixLenTrimmed &&
166 !hostname.compare(hostname.size() - kSuffixLenTrimmed, kSuffixLenTrimmed,
167 kSuffix, kSuffixLenTrimmed);
168}
169
[email protected]51b9a6b2012-06-25 21:50:29170// Provide a common macro to simplify code and readability. We must use a
171// macro as the underlying HISTOGRAM macro creates static variables.
172#define DNS_HISTOGRAM(name, time) UMA_HISTOGRAM_CUSTOM_TIMES(name, time, \
173 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromHours(1), 100)
174
175// A macro to simplify code and readability.
176#define DNS_HISTOGRAM_BY_PRIORITY(basename, priority, time) \
177 do { \
178 switch (priority) { \
179 case HIGHEST: DNS_HISTOGRAM(basename "_HIGHEST", time); break; \
180 case MEDIUM: DNS_HISTOGRAM(basename "_MEDIUM", time); break; \
181 case LOW: DNS_HISTOGRAM(basename "_LOW", time); break; \
182 case LOWEST: DNS_HISTOGRAM(basename "_LOWEST", time); break; \
183 case IDLE: DNS_HISTOGRAM(basename "_IDLE", time); break; \
184 default: NOTREACHED(); break; \
185 } \
186 DNS_HISTOGRAM(basename, time); \
187 } while (0)
188
189// Record time from Request creation until a valid DNS response.
190void RecordTotalTime(bool had_dns_config,
191 bool speculative,
192 base::TimeDelta duration) {
193 if (had_dns_config) {
194 if (speculative) {
195 DNS_HISTOGRAM("AsyncDNS.TotalTime_speculative", duration);
196 } else {
197 DNS_HISTOGRAM("AsyncDNS.TotalTime", duration);
198 }
199 } else {
200 if (speculative) {
201 DNS_HISTOGRAM("DNS.TotalTime_speculative", duration);
202 } else {
203 DNS_HISTOGRAM("DNS.TotalTime", duration);
204 }
205 }
206}
207
[email protected]1339a2a22012-10-17 08:39:43208void RecordTTL(base::TimeDelta ttl) {
209 UMA_HISTOGRAM_CUSTOM_TIMES("AsyncDNS.TTL", ttl,
210 base::TimeDelta::FromSeconds(1),
211 base::TimeDelta::FromDays(1), 100);
212}
213
[email protected]d7b9a2b2012-05-31 22:31:19214//-----------------------------------------------------------------------------
215
[email protected]0f292de02012-02-01 22:28:20216// Wraps call to SystemHostResolverProc as an instance of HostResolverProc.
217// TODO(szym): This should probably be declared in host_resolver_proc.h.
218class CallSystemHostResolverProc : public HostResolverProc {
219 public:
220 CallSystemHostResolverProc() : HostResolverProc(NULL) {}
221 virtual int Resolve(const std::string& hostname,
222 AddressFamily address_family,
223 HostResolverFlags host_resolver_flags,
[email protected]b3601bc22012-02-21 21:23:20224 AddressList* addr_list,
[email protected]0f292de02012-02-01 22:28:20225 int* os_error) OVERRIDE {
226 return SystemHostResolverProc(hostname,
227 address_family,
228 host_resolver_flags,
[email protected]b3601bc22012-02-21 21:23:20229 addr_list,
[email protected]0f292de02012-02-01 22:28:20230 os_error);
[email protected]b59ff372009-07-15 22:04:32231 }
[email protected]a9813302012-04-28 09:29:28232
233 protected:
234 virtual ~CallSystemHostResolverProc() {}
[email protected]0f292de02012-02-01 22:28:20235};
[email protected]b59ff372009-07-15 22:04:32236
[email protected]895123222012-10-25 15:21:17237AddressList EnsurePortOnAddressList(const AddressList& list, uint16 port) {
238 if (list.empty() || list.front().port() == port)
239 return list;
240 return AddressList::CopyWithPort(list, port);
[email protected]7054e78f2012-05-07 21:44:56241}
242
[email protected]cd565142012-06-12 16:21:45243// Creates NetLog parameters when the resolve failed.
244base::Value* NetLogProcTaskFailedCallback(uint32 attempt_number,
245 int net_error,
246 int os_error,
247 NetLog::LogLevel /* log_level */) {
248 DictionaryValue* dict = new DictionaryValue();
249 if (attempt_number)
250 dict->SetInteger("attempt_number", attempt_number);
[email protected]21526002010-05-16 19:42:46251
[email protected]cd565142012-06-12 16:21:45252 dict->SetInteger("net_error", net_error);
[email protected]13024882011-05-18 23:19:16253
[email protected]cd565142012-06-12 16:21:45254 if (os_error) {
255 dict->SetInteger("os_error", os_error);
[email protected]21526002010-05-16 19:42:46256#if defined(OS_POSIX)
[email protected]cd565142012-06-12 16:21:45257 dict->SetString("os_error_string", gai_strerror(os_error));
[email protected]21526002010-05-16 19:42:46258#elif defined(OS_WIN)
[email protected]cd565142012-06-12 16:21:45259 // Map the error code to a human-readable string.
260 LPWSTR error_string = NULL;
261 int size = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
262 FORMAT_MESSAGE_FROM_SYSTEM,
263 0, // Use the internal message table.
264 os_error,
265 0, // Use default language.
266 (LPWSTR)&error_string,
267 0, // Buffer size.
268 0); // Arguments (unused).
269 dict->SetString("os_error_string", WideToUTF8(error_string));
270 LocalFree(error_string);
[email protected]21526002010-05-16 19:42:46271#endif
[email protected]21526002010-05-16 19:42:46272 }
273
[email protected]cd565142012-06-12 16:21:45274 return dict;
275}
[email protected]a9813302012-04-28 09:29:28276
[email protected]cd565142012-06-12 16:21:45277// Creates NetLog parameters when the DnsTask failed.
278base::Value* NetLogDnsTaskFailedCallback(int net_error,
279 int dns_error,
280 NetLog::LogLevel /* log_level */) {
281 DictionaryValue* dict = new DictionaryValue();
282 dict->SetInteger("net_error", net_error);
283 if (dns_error)
284 dict->SetInteger("dns_error", dns_error);
285 return dict;
[email protected]ee094b82010-08-24 15:55:51286};
287
[email protected]cd565142012-06-12 16:21:45288// Creates NetLog parameters containing the information in a RequestInfo object,
289// along with the associated NetLog::Source.
290base::Value* NetLogRequestInfoCallback(const NetLog::Source& source,
291 const HostResolver::RequestInfo* info,
292 NetLog::LogLevel /* log_level */) {
293 DictionaryValue* dict = new DictionaryValue();
294 source.AddToEventParameters(dict);
[email protected]b3601bc22012-02-21 21:23:20295
[email protected]cd565142012-06-12 16:21:45296 dict->SetString("host", info->host_port_pair().ToString());
297 dict->SetInteger("address_family",
298 static_cast<int>(info->address_family()));
299 dict->SetBoolean("allow_cached_response", info->allow_cached_response());
300 dict->SetBoolean("is_speculative", info->is_speculative());
301 dict->SetInteger("priority", info->priority());
302 return dict;
303}
[email protected]b3601bc22012-02-21 21:23:20304
[email protected]cd565142012-06-12 16:21:45305// Creates NetLog parameters for the creation of a HostResolverImpl::Job.
306base::Value* NetLogJobCreationCallback(const NetLog::Source& source,
307 const std::string* host,
308 NetLog::LogLevel /* log_level */) {
309 DictionaryValue* dict = new DictionaryValue();
310 source.AddToEventParameters(dict);
311 dict->SetString("host", *host);
312 return dict;
313}
[email protected]a9813302012-04-28 09:29:28314
[email protected]cd565142012-06-12 16:21:45315// Creates NetLog parameters for HOST_RESOLVER_IMPL_JOB_ATTACH/DETACH events.
316base::Value* NetLogJobAttachCallback(const NetLog::Source& source,
317 RequestPriority priority,
318 NetLog::LogLevel /* log_level */) {
319 DictionaryValue* dict = new DictionaryValue();
320 source.AddToEventParameters(dict);
321 dict->SetInteger("priority", priority);
322 return dict;
323}
[email protected]b3601bc22012-02-21 21:23:20324
[email protected]cd565142012-06-12 16:21:45325// Creates NetLog parameters for the DNS_CONFIG_CHANGED event.
326base::Value* NetLogDnsConfigCallback(const DnsConfig* config,
327 NetLog::LogLevel /* log_level */) {
328 return config->ToValue();
329}
[email protected]b4481b222012-03-16 17:13:11330
[email protected]0f292de02012-02-01 22:28:20331// The logging routines are defined here because some requests are resolved
332// without a Request object.
333
334// Logs when a request has just been started.
335void LogStartRequest(const BoundNetLog& source_net_log,
336 const BoundNetLog& request_net_log,
337 const HostResolver::RequestInfo& info) {
338 source_net_log.BeginEvent(
339 NetLog::TYPE_HOST_RESOLVER_IMPL,
[email protected]cd565142012-06-12 16:21:45340 request_net_log.source().ToEventParametersCallback());
[email protected]0f292de02012-02-01 22:28:20341
342 request_net_log.BeginEvent(
343 NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST,
[email protected]cd565142012-06-12 16:21:45344 base::Bind(&NetLogRequestInfoCallback, source_net_log.source(), &info));
[email protected]0f292de02012-02-01 22:28:20345}
346
347// Logs when a request has just completed (before its callback is run).
348void LogFinishRequest(const BoundNetLog& source_net_log,
349 const BoundNetLog& request_net_log,
350 const HostResolver::RequestInfo& info,
[email protected]b3601bc22012-02-21 21:23:20351 int net_error) {
352 request_net_log.EndEventWithNetErrorCode(
353 NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST, net_error);
[email protected]4da911f2012-06-14 19:45:20354 source_net_log.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL);
[email protected]0f292de02012-02-01 22:28:20355}
356
357// Logs when a request has been cancelled.
358void LogCancelRequest(const BoundNetLog& source_net_log,
359 const BoundNetLog& request_net_log,
360 const HostResolverImpl::RequestInfo& info) {
[email protected]4da911f2012-06-14 19:45:20361 request_net_log.AddEvent(NetLog::TYPE_CANCELLED);
362 request_net_log.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST);
363 source_net_log.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL);
[email protected]0f292de02012-02-01 22:28:20364}
365
[email protected]b59ff372009-07-15 22:04:32366//-----------------------------------------------------------------------------
367
[email protected]0f292de02012-02-01 22:28:20368// Keeps track of the highest priority.
369class PriorityTracker {
370 public:
[email protected]8c98d002012-07-18 19:02:27371 explicit PriorityTracker(RequestPriority initial_priority)
372 : highest_priority_(initial_priority), total_count_(0) {
[email protected]0f292de02012-02-01 22:28:20373 memset(counts_, 0, sizeof(counts_));
374 }
375
376 RequestPriority highest_priority() const {
377 return highest_priority_;
378 }
379
380 size_t total_count() const {
381 return total_count_;
382 }
383
384 void Add(RequestPriority req_priority) {
385 ++total_count_;
386 ++counts_[req_priority];
[email protected]31ae7ab2012-04-24 21:09:05387 if (highest_priority_ < req_priority)
[email protected]0f292de02012-02-01 22:28:20388 highest_priority_ = req_priority;
389 }
390
391 void Remove(RequestPriority req_priority) {
392 DCHECK_GT(total_count_, 0u);
393 DCHECK_GT(counts_[req_priority], 0u);
394 --total_count_;
395 --counts_[req_priority];
396 size_t i;
[email protected]31ae7ab2012-04-24 21:09:05397 for (i = highest_priority_; i > MINIMUM_PRIORITY && !counts_[i]; --i);
[email protected]0f292de02012-02-01 22:28:20398 highest_priority_ = static_cast<RequestPriority>(i);
399
[email protected]31ae7ab2012-04-24 21:09:05400 // In absence of requests, default to MINIMUM_PRIORITY.
401 if (total_count_ == 0)
402 DCHECK_EQ(MINIMUM_PRIORITY, highest_priority_);
[email protected]0f292de02012-02-01 22:28:20403 }
404
405 private:
406 RequestPriority highest_priority_;
407 size_t total_count_;
408 size_t counts_[NUM_PRIORITIES];
409};
410
[email protected]c54a8912012-10-22 22:09:43411} // namespace
[email protected]0f292de02012-02-01 22:28:20412
413//-----------------------------------------------------------------------------
414
415// Holds the data for a request that could not be completed synchronously.
416// It is owned by a Job. Canceled Requests are only marked as canceled rather
417// than removed from the Job's |requests_| list.
[email protected]b59ff372009-07-15 22:04:32418class HostResolverImpl::Request {
419 public:
[email protected]ee094b82010-08-24 15:55:51420 Request(const BoundNetLog& source_net_log,
421 const BoundNetLog& request_net_log,
[email protected]54e13772009-08-14 03:01:09422 const RequestInfo& info,
[email protected]aa22b242011-11-16 18:58:29423 const CompletionCallback& callback,
[email protected]b59ff372009-07-15 22:04:32424 AddressList* addresses)
[email protected]ee094b82010-08-24 15:55:51425 : source_net_log_(source_net_log),
426 request_net_log_(request_net_log),
[email protected]54e13772009-08-14 03:01:09427 info_(info),
428 job_(NULL),
429 callback_(callback),
[email protected]51b9a6b2012-06-25 21:50:29430 addresses_(addresses),
431 request_time_(base::TimeTicks::Now()) {
[email protected]54e13772009-08-14 03:01:09432 }
[email protected]b59ff372009-07-15 22:04:32433
[email protected]0f292de02012-02-01 22:28:20434 // Mark the request as canceled.
435 void MarkAsCanceled() {
[email protected]b59ff372009-07-15 22:04:32436 job_ = NULL;
[email protected]b59ff372009-07-15 22:04:32437 addresses_ = NULL;
[email protected]aa22b242011-11-16 18:58:29438 callback_.Reset();
[email protected]b59ff372009-07-15 22:04:32439 }
440
[email protected]0f292de02012-02-01 22:28:20441 bool was_canceled() const {
[email protected]aa22b242011-11-16 18:58:29442 return callback_.is_null();
[email protected]b59ff372009-07-15 22:04:32443 }
444
445 void set_job(Job* job) {
[email protected]0f292de02012-02-01 22:28:20446 DCHECK(job);
[email protected]b59ff372009-07-15 22:04:32447 // Identify which job the request is waiting on.
448 job_ = job;
449 }
450
[email protected]0f292de02012-02-01 22:28:20451 // Prepare final AddressList and call completion callback.
[email protected]b3601bc22012-02-21 21:23:20452 void OnComplete(int error, const AddressList& addr_list) {
[email protected]51b9a6b2012-06-25 21:50:29453 DCHECK(!was_canceled());
[email protected]895123222012-10-25 15:21:17454 if (error == OK)
455 *addresses_ = EnsurePortOnAddressList(addr_list, info_.port());
[email protected]aa22b242011-11-16 18:58:29456 CompletionCallback callback = callback_;
[email protected]0f292de02012-02-01 22:28:20457 MarkAsCanceled();
[email protected]aa22b242011-11-16 18:58:29458 callback.Run(error);
[email protected]b59ff372009-07-15 22:04:32459 }
460
[email protected]b59ff372009-07-15 22:04:32461 Job* job() const {
462 return job_;
463 }
464
[email protected]0f292de02012-02-01 22:28:20465 // NetLog for the source, passed in HostResolver::Resolve.
[email protected]ee094b82010-08-24 15:55:51466 const BoundNetLog& source_net_log() {
467 return source_net_log_;
468 }
469
[email protected]0f292de02012-02-01 22:28:20470 // NetLog for this request.
[email protected]ee094b82010-08-24 15:55:51471 const BoundNetLog& request_net_log() {
472 return request_net_log_;
[email protected]54e13772009-08-14 03:01:09473 }
474
[email protected]b59ff372009-07-15 22:04:32475 const RequestInfo& info() const {
476 return info_;
477 }
478
[email protected]51b9a6b2012-06-25 21:50:29479 base::TimeTicks request_time() const {
480 return request_time_;
481 }
482
[email protected]b59ff372009-07-15 22:04:32483 private:
[email protected]ee094b82010-08-24 15:55:51484 BoundNetLog source_net_log_;
485 BoundNetLog request_net_log_;
[email protected]54e13772009-08-14 03:01:09486
[email protected]b59ff372009-07-15 22:04:32487 // The request info that started the request.
488 RequestInfo info_;
489
[email protected]0f292de02012-02-01 22:28:20490 // The resolve job that this request is dependent on.
[email protected]b59ff372009-07-15 22:04:32491 Job* job_;
492
493 // The user's callback to invoke when the request completes.
[email protected]aa22b242011-11-16 18:58:29494 CompletionCallback callback_;
[email protected]b59ff372009-07-15 22:04:32495
496 // The address list to save result into.
497 AddressList* addresses_;
498
[email protected]51b9a6b2012-06-25 21:50:29499 const base::TimeTicks request_time_;
500
[email protected]b59ff372009-07-15 22:04:32501 DISALLOW_COPY_AND_ASSIGN(Request);
502};
503
[email protected]1e9bbd22010-10-15 16:42:45504//------------------------------------------------------------------------------
505
[email protected]0f292de02012-02-01 22:28:20506// Calls HostResolverProc on the WorkerPool. Performs retries if necessary.
507//
508// Whenever we try to resolve the host, we post a delayed task to check if host
509// resolution (OnLookupComplete) is completed or not. If the original attempt
510// hasn't completed, then we start another attempt for host resolution. We take
511// the results from the first attempt that finishes and ignore the results from
512// all other attempts.
513//
514// TODO(szym): Move to separate source file for testing and mocking.
515//
516class HostResolverImpl::ProcTask
517 : public base::RefCountedThreadSafe<HostResolverImpl::ProcTask> {
[email protected]b59ff372009-07-15 22:04:32518 public:
[email protected]b3601bc22012-02-21 21:23:20519 typedef base::Callback<void(int net_error,
520 const AddressList& addr_list)> Callback;
[email protected]b59ff372009-07-15 22:04:32521
[email protected]0f292de02012-02-01 22:28:20522 ProcTask(const Key& key,
523 const ProcTaskParams& params,
524 const Callback& callback,
525 const BoundNetLog& job_net_log)
526 : key_(key),
527 params_(params),
528 callback_(callback),
529 origin_loop_(base::MessageLoopProxy::current()),
530 attempt_number_(0),
531 completed_attempt_number_(0),
532 completed_attempt_error_(ERR_UNEXPECTED),
533 had_non_speculative_request_(false),
[email protected]b3601bc22012-02-21 21:23:20534 net_log_(job_net_log) {
[email protected]0f292de02012-02-01 22:28:20535 if (!params_.resolver_proc)
536 params_.resolver_proc = HostResolverProc::GetDefault();
537 // If default is unset, use the system proc.
538 if (!params_.resolver_proc)
539 params_.resolver_proc = new CallSystemHostResolverProc();
[email protected]b59ff372009-07-15 22:04:32540 }
541
[email protected]b59ff372009-07-15 22:04:32542 void Start() {
[email protected]3e9d9cc2011-05-03 21:08:15543 DCHECK(origin_loop_->BelongsToCurrentThread());
[email protected]4da911f2012-06-14 19:45:20544 net_log_.BeginEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK);
[email protected]189163e2011-05-11 01:48:54545 StartLookupAttempt();
546 }
[email protected]252b699b2010-02-05 21:38:06547
[email protected]0f292de02012-02-01 22:28:20548 // Cancels this ProcTask. It will be orphaned. Any outstanding resolve
549 // attempts running on worker threads will continue running. Only once all the
550 // attempts complete will the final reference to this ProcTask be released.
551 void Cancel() {
552 DCHECK(origin_loop_->BelongsToCurrentThread());
553
[email protected]0adcb2b2012-08-15 21:30:46554 if (was_canceled() || was_completed())
[email protected]0f292de02012-02-01 22:28:20555 return;
556
[email protected]0f292de02012-02-01 22:28:20557 callback_.Reset();
[email protected]4da911f2012-06-14 19:45:20558 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK);
[email protected]0f292de02012-02-01 22:28:20559 }
560
561 void set_had_non_speculative_request() {
562 DCHECK(origin_loop_->BelongsToCurrentThread());
563 had_non_speculative_request_ = true;
564 }
565
566 bool was_canceled() const {
567 DCHECK(origin_loop_->BelongsToCurrentThread());
568 return callback_.is_null();
569 }
570
571 bool was_completed() const {
572 DCHECK(origin_loop_->BelongsToCurrentThread());
573 return completed_attempt_number_ > 0;
574 }
575
576 private:
[email protected]a9813302012-04-28 09:29:28577 friend class base::RefCountedThreadSafe<ProcTask>;
578 ~ProcTask() {}
579
[email protected]189163e2011-05-11 01:48:54580 void StartLookupAttempt() {
581 DCHECK(origin_loop_->BelongsToCurrentThread());
582 base::TimeTicks start_time = base::TimeTicks::Now();
583 ++attempt_number_;
584 // Dispatch the lookup attempt to a worker thread.
585 if (!base::WorkerPool::PostTask(
586 FROM_HERE,
[email protected]0f292de02012-02-01 22:28:20587 base::Bind(&ProcTask::DoLookup, this, start_time, attempt_number_),
[email protected]189163e2011-05-11 01:48:54588 true)) {
[email protected]b59ff372009-07-15 22:04:32589 NOTREACHED();
590
591 // Since we could be running within Resolve() right now, we can't just
592 // call OnLookupComplete(). Instead we must wait until Resolve() has
593 // returned (IO_PENDING).
[email protected]3e9d9cc2011-05-03 21:08:15594 origin_loop_->PostTask(
[email protected]189163e2011-05-11 01:48:54595 FROM_HERE,
[email protected]0f292de02012-02-01 22:28:20596 base::Bind(&ProcTask::OnLookupComplete, this, AddressList(),
[email protected]33152acc2011-10-20 23:37:12597 start_time, attempt_number_, ERR_UNEXPECTED, 0));
[email protected]189163e2011-05-11 01:48:54598 return;
[email protected]b59ff372009-07-15 22:04:32599 }
[email protected]13024882011-05-18 23:19:16600
601 net_log_.AddEvent(
602 NetLog::TYPE_HOST_RESOLVER_IMPL_ATTEMPT_STARTED,
[email protected]cd565142012-06-12 16:21:45603 NetLog::IntegerCallback("attempt_number", attempt_number_));
[email protected]13024882011-05-18 23:19:16604
[email protected]0f292de02012-02-01 22:28:20605 // If we don't get the results within a given time, RetryIfNotComplete
606 // will start a new attempt on a different worker thread if none of our
607 // outstanding attempts have completed yet.
608 if (attempt_number_ <= params_.max_retry_attempts) {
[email protected]06ef6d92011-05-19 04:24:58609 origin_loop_->PostDelayedTask(
610 FROM_HERE,
[email protected]0f292de02012-02-01 22:28:20611 base::Bind(&ProcTask::RetryIfNotComplete, this),
[email protected]7e560102012-03-08 20:58:42612 params_.unresponsive_delay);
[email protected]06ef6d92011-05-19 04:24:58613 }
[email protected]b59ff372009-07-15 22:04:32614 }
615
[email protected]6c710ee2010-05-07 07:51:16616 // WARNING: This code runs inside a worker pool. The shutdown code cannot
617 // wait for it to finish, so we must be very careful here about using other
618 // objects (like MessageLoops, Singletons, etc). During shutdown these objects
[email protected]189163e2011-05-11 01:48:54619 // may no longer exist. Multiple DoLookups() could be running in parallel, so
620 // any state inside of |this| must not mutate .
621 void DoLookup(const base::TimeTicks& start_time,
622 const uint32 attempt_number) {
623 AddressList results;
624 int os_error = 0;
[email protected]b59ff372009-07-15 22:04:32625 // Running on the worker thread
[email protected]0f292de02012-02-01 22:28:20626 int error = params_.resolver_proc->Resolve(key_.hostname,
627 key_.address_family,
628 key_.host_resolver_flags,
629 &results,
630 &os_error);
[email protected]b59ff372009-07-15 22:04:32631
[email protected]189163e2011-05-11 01:48:54632 origin_loop_->PostTask(
633 FROM_HERE,
[email protected]0f292de02012-02-01 22:28:20634 base::Bind(&ProcTask::OnLookupComplete, this, results, start_time,
[email protected]33152acc2011-10-20 23:37:12635 attempt_number, error, os_error));
[email protected]189163e2011-05-11 01:48:54636 }
637
[email protected]0f292de02012-02-01 22:28:20638 // Makes next attempt if DoLookup() has not finished (runs on origin thread).
639 void RetryIfNotComplete() {
[email protected]189163e2011-05-11 01:48:54640 DCHECK(origin_loop_->BelongsToCurrentThread());
641
[email protected]0f292de02012-02-01 22:28:20642 if (was_completed() || was_canceled())
[email protected]189163e2011-05-11 01:48:54643 return;
644
[email protected]0f292de02012-02-01 22:28:20645 params_.unresponsive_delay *= params_.retry_factor;
[email protected]189163e2011-05-11 01:48:54646 StartLookupAttempt();
[email protected]b59ff372009-07-15 22:04:32647 }
648
649 // Callback for when DoLookup() completes (runs on origin thread).
[email protected]189163e2011-05-11 01:48:54650 void OnLookupComplete(const AddressList& results,
651 const base::TimeTicks& start_time,
652 const uint32 attempt_number,
653 int error,
654 const int os_error) {
[email protected]3e9d9cc2011-05-03 21:08:15655 DCHECK(origin_loop_->BelongsToCurrentThread());
[email protected]7054e78f2012-05-07 21:44:56656 DCHECK(error || !results.empty());
[email protected]189163e2011-05-11 01:48:54657
658 bool was_retry_attempt = attempt_number > 1;
659
[email protected]2d3b7762010-10-09 00:35:47660 // Ideally the following code would be part of host_resolver_proc.cc,
[email protected]b3601bc22012-02-21 21:23:20661 // however it isn't safe to call NetworkChangeNotifier from worker threads.
662 // So we do it here on the IO thread instead.
[email protected]189163e2011-05-11 01:48:54663 if (error != OK && NetworkChangeNotifier::IsOffline())
664 error = ERR_INTERNET_DISCONNECTED;
[email protected]2d3b7762010-10-09 00:35:47665
[email protected]b3601bc22012-02-21 21:23:20666 // If this is the first attempt that is finishing later, then record data
667 // for the first attempt. Won't contaminate with retry attempt's data.
[email protected]189163e2011-05-11 01:48:54668 if (!was_retry_attempt)
669 RecordPerformanceHistograms(start_time, error, os_error);
670
671 RecordAttemptHistograms(start_time, attempt_number, error, os_error);
[email protected]f2d8c4212010-02-02 00:56:35672
[email protected]0f292de02012-02-01 22:28:20673 if (was_canceled())
[email protected]b59ff372009-07-15 22:04:32674 return;
675
[email protected]cd565142012-06-12 16:21:45676 NetLog::ParametersCallback net_log_callback;
[email protected]0f292de02012-02-01 22:28:20677 if (error != OK) {
[email protected]cd565142012-06-12 16:21:45678 net_log_callback = base::Bind(&NetLogProcTaskFailedCallback,
679 attempt_number,
680 error,
681 os_error);
[email protected]0f292de02012-02-01 22:28:20682 } else {
[email protected]cd565142012-06-12 16:21:45683 net_log_callback = NetLog::IntegerCallback("attempt_number",
684 attempt_number);
[email protected]0f292de02012-02-01 22:28:20685 }
[email protected]cd565142012-06-12 16:21:45686 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_ATTEMPT_FINISHED,
687 net_log_callback);
[email protected]0f292de02012-02-01 22:28:20688
689 if (was_completed())
690 return;
691
692 // Copy the results from the first worker thread that resolves the host.
693 results_ = results;
694 completed_attempt_number_ = attempt_number;
695 completed_attempt_error_ = error;
696
[email protected]e87b8b512011-06-14 22:12:52697 if (was_retry_attempt) {
698 // If retry attempt finishes before 1st attempt, then get stats on how
699 // much time is saved by having spawned an extra attempt.
700 retry_attempt_finished_time_ = base::TimeTicks::Now();
701 }
702
[email protected]189163e2011-05-11 01:48:54703 if (error != OK) {
[email protected]cd565142012-06-12 16:21:45704 net_log_callback = base::Bind(&NetLogProcTaskFailedCallback,
705 0, error, os_error);
[email protected]ee094b82010-08-24 15:55:51706 } else {
[email protected]cd565142012-06-12 16:21:45707 net_log_callback = results_.CreateNetLogCallback();
[email protected]ee094b82010-08-24 15:55:51708 }
[email protected]cd565142012-06-12 16:21:45709 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK,
710 net_log_callback);
[email protected]ee094b82010-08-24 15:55:51711
[email protected]b3601bc22012-02-21 21:23:20712 callback_.Run(error, results_);
[email protected]b59ff372009-07-15 22:04:32713 }
714
[email protected]189163e2011-05-11 01:48:54715 void RecordPerformanceHistograms(const base::TimeTicks& start_time,
716 const int error,
717 const int os_error) const {
[email protected]3e9d9cc2011-05-03 21:08:15718 DCHECK(origin_loop_->BelongsToCurrentThread());
[email protected]1e9bbd22010-10-15 16:42:45719 enum Category { // Used in HISTOGRAM_ENUMERATION.
720 RESOLVE_SUCCESS,
721 RESOLVE_FAIL,
722 RESOLVE_SPECULATIVE_SUCCESS,
723 RESOLVE_SPECULATIVE_FAIL,
724 RESOLVE_MAX, // Bounding value.
725 };
726 int category = RESOLVE_MAX; // Illegal value for later DCHECK only.
727
[email protected]189163e2011-05-11 01:48:54728 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
729 if (error == OK) {
[email protected]1e9bbd22010-10-15 16:42:45730 if (had_non_speculative_request_) {
731 category = RESOLVE_SUCCESS;
732 DNS_HISTOGRAM("DNS.ResolveSuccess", duration);
733 } else {
734 category = RESOLVE_SPECULATIVE_SUCCESS;
735 DNS_HISTOGRAM("DNS.ResolveSpeculativeSuccess", duration);
736 }
[email protected]7e96d792011-06-10 17:08:23737
[email protected]78eac2a2012-03-14 19:09:27738 // Log DNS lookups based on |address_family|. This will help us determine
[email protected]7e96d792011-06-10 17:08:23739 // if IPv4 or IPv4/6 lookups are faster or slower.
740 switch(key_.address_family) {
741 case ADDRESS_FAMILY_IPV4:
742 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_IPV4", duration);
743 break;
744 case ADDRESS_FAMILY_IPV6:
745 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_IPV6", duration);
746 break;
747 case ADDRESS_FAMILY_UNSPECIFIED:
748 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_UNSPEC", duration);
749 break;
750 }
[email protected]1e9bbd22010-10-15 16:42:45751 } else {
752 if (had_non_speculative_request_) {
753 category = RESOLVE_FAIL;
754 DNS_HISTOGRAM("DNS.ResolveFail", duration);
755 } else {
756 category = RESOLVE_SPECULATIVE_FAIL;
757 DNS_HISTOGRAM("DNS.ResolveSpeculativeFail", duration);
758 }
[email protected]78eac2a2012-03-14 19:09:27759 // Log DNS lookups based on |address_family|. This will help us determine
[email protected]7e96d792011-06-10 17:08:23760 // if IPv4 or IPv4/6 lookups are faster or slower.
761 switch(key_.address_family) {
762 case ADDRESS_FAMILY_IPV4:
763 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_IPV4", duration);
764 break;
765 case ADDRESS_FAMILY_IPV6:
766 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_IPV6", duration);
767 break;
768 case ADDRESS_FAMILY_UNSPECIFIED:
769 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_UNSPEC", duration);
770 break;
771 }
[email protected]c833e322010-10-16 23:51:36772 UMA_HISTOGRAM_CUSTOM_ENUMERATION(kOSErrorsForGetAddrinfoHistogramName,
[email protected]189163e2011-05-11 01:48:54773 std::abs(os_error),
[email protected]1e9bbd22010-10-15 16:42:45774 GetAllGetAddrinfoOSErrors());
775 }
[email protected]051b6ab2010-10-18 16:50:46776 DCHECK_LT(category, static_cast<int>(RESOLVE_MAX)); // Be sure it was set.
[email protected]1e9bbd22010-10-15 16:42:45777
778 UMA_HISTOGRAM_ENUMERATION("DNS.ResolveCategory", category, RESOLVE_MAX);
779
[email protected]edafd4c2011-05-10 17:18:53780 static const bool show_parallelism_experiment_histograms =
781 base::FieldTrialList::TrialExists("DnsParallelism");
[email protected]ecd95ae2010-10-20 23:58:17782 if (show_parallelism_experiment_histograms) {
783 UMA_HISTOGRAM_ENUMERATION(
784 base::FieldTrial::MakeName("DNS.ResolveCategory", "DnsParallelism"),
785 category, RESOLVE_MAX);
786 if (RESOLVE_SUCCESS == category) {
787 DNS_HISTOGRAM(base::FieldTrial::MakeName("DNS.ResolveSuccess",
788 "DnsParallelism"), duration);
789 }
790 }
[email protected]1e9bbd22010-10-15 16:42:45791 }
792
[email protected]189163e2011-05-11 01:48:54793 void RecordAttemptHistograms(const base::TimeTicks& start_time,
794 const uint32 attempt_number,
795 const int error,
796 const int os_error) const {
[email protected]0f292de02012-02-01 22:28:20797 DCHECK(origin_loop_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54798 bool first_attempt_to_complete =
799 completed_attempt_number_ == attempt_number;
[email protected]e87b8b512011-06-14 22:12:52800 bool is_first_attempt = (attempt_number == 1);
[email protected]1e9bbd22010-10-15 16:42:45801
[email protected]189163e2011-05-11 01:48:54802 if (first_attempt_to_complete) {
803 // If this was first attempt to complete, then record the resolution
804 // status of the attempt.
805 if (completed_attempt_error_ == OK) {
806 UMA_HISTOGRAM_ENUMERATION(
807 "DNS.AttemptFirstSuccess", attempt_number, 100);
808 } else {
809 UMA_HISTOGRAM_ENUMERATION(
810 "DNS.AttemptFirstFailure", attempt_number, 100);
811 }
812 }
813
814 if (error == OK)
815 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptSuccess", attempt_number, 100);
816 else
817 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptFailure", attempt_number, 100);
818
[email protected]e87b8b512011-06-14 22:12:52819 // If first attempt didn't finish before retry attempt, then calculate stats
820 // on how much time is saved by having spawned an extra attempt.
[email protected]0f292de02012-02-01 22:28:20821 if (!first_attempt_to_complete && is_first_attempt && !was_canceled()) {
[email protected]e87b8b512011-06-14 22:12:52822 DNS_HISTOGRAM("DNS.AttemptTimeSavedByRetry",
823 base::TimeTicks::Now() - retry_attempt_finished_time_);
824 }
825
[email protected]0f292de02012-02-01 22:28:20826 if (was_canceled() || !first_attempt_to_complete) {
[email protected]189163e2011-05-11 01:48:54827 // Count those attempts which completed after the job was already canceled
828 // OR after the job was already completed by an earlier attempt (so in
829 // effect).
830 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptDiscarded", attempt_number, 100);
831
[email protected]0f292de02012-02-01 22:28:20832 // Record if job is canceled.
833 if (was_canceled())
[email protected]189163e2011-05-11 01:48:54834 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptCancelled", attempt_number, 100);
835 }
836
837 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
838 if (error == OK)
839 DNS_HISTOGRAM("DNS.AttemptSuccessDuration", duration);
840 else
841 DNS_HISTOGRAM("DNS.AttemptFailDuration", duration);
842 }
[email protected]1e9bbd22010-10-15 16:42:45843
[email protected]b59ff372009-07-15 22:04:32844 // Set on the origin thread, read on the worker thread.
[email protected]123ab1e32009-10-21 19:12:57845 Key key_;
[email protected]b59ff372009-07-15 22:04:32846
[email protected]0f292de02012-02-01 22:28:20847 // Holds an owning reference to the HostResolverProc that we are going to use.
[email protected]b59ff372009-07-15 22:04:32848 // This may not be the current resolver procedure by the time we call
849 // ResolveAddrInfo, but that's OK... we'll use it anyways, and the owning
850 // reference ensures that it remains valid until we are done.
[email protected]0f292de02012-02-01 22:28:20851 ProcTaskParams params_;
[email protected]b59ff372009-07-15 22:04:32852
[email protected]0f292de02012-02-01 22:28:20853 // The listener to the results of this ProcTask.
854 Callback callback_;
855
856 // Used to post ourselves onto the origin thread.
857 scoped_refptr<base::MessageLoopProxy> origin_loop_;
[email protected]189163e2011-05-11 01:48:54858
859 // Keeps track of the number of attempts we have made so far to resolve the
860 // host. Whenever we start an attempt to resolve the host, we increase this
861 // number.
862 uint32 attempt_number_;
863
864 // The index of the attempt which finished first (or 0 if the job is still in
865 // progress).
866 uint32 completed_attempt_number_;
867
868 // The result (a net error code) from the first attempt to complete.
869 int completed_attempt_error_;
[email protected]252b699b2010-02-05 21:38:06870
[email protected]e87b8b512011-06-14 22:12:52871 // The time when retry attempt was finished.
872 base::TimeTicks retry_attempt_finished_time_;
873
[email protected]252b699b2010-02-05 21:38:06874 // True if a non-speculative request was ever attached to this job
[email protected]0f292de02012-02-01 22:28:20875 // (regardless of whether or not it was later canceled.
[email protected]252b699b2010-02-05 21:38:06876 // This boolean is used for histogramming the duration of jobs used to
877 // service non-speculative requests.
878 bool had_non_speculative_request_;
879
[email protected]b59ff372009-07-15 22:04:32880 AddressList results_;
881
[email protected]ee094b82010-08-24 15:55:51882 BoundNetLog net_log_;
883
[email protected]0f292de02012-02-01 22:28:20884 DISALLOW_COPY_AND_ASSIGN(ProcTask);
[email protected]b59ff372009-07-15 22:04:32885};
886
887//-----------------------------------------------------------------------------
888
[email protected]12faa4c2012-11-06 04:44:18889// Wraps a call to TestIPv6Support to be executed on the WorkerPool as it takes
890// 40-100ms.
891class HostResolverImpl::IPv6ProbeJob {
[email protected]0f8f1b432010-03-16 19:06:03892 public:
[email protected]12faa4c2012-11-06 04:44:18893 IPv6ProbeJob(const base::WeakPtr<HostResolverImpl>& resolver, NetLog* net_log)
[email protected]0f8f1b432010-03-16 19:06:03894 : resolver_(resolver),
[email protected]12faa4c2012-11-06 04:44:18895 net_log_(BoundNetLog::Make(net_log, NetLog::SOURCE_IPV6_PROBE_JOB)),
896 result_(false, IPV6_SUPPORT_MAX, OK) {
[email protected]3e9d9cc2011-05-03 21:08:15897 DCHECK(resolver);
[email protected]ae8e80f2012-07-19 21:08:33898 net_log_.BeginEvent(NetLog::TYPE_IPV6_PROBE_RUNNING);
[email protected]f092e64b2010-03-17 00:39:18899 const bool kIsSlow = true;
[email protected]12faa4c2012-11-06 04:44:18900 base::WorkerPool::PostTaskAndReply(
901 FROM_HERE,
902 base::Bind(&IPv6ProbeJob::DoProbe, base::Unretained(this)),
903 base::Bind(&IPv6ProbeJob::OnProbeComplete, base::Owned(this)),
904 kIsSlow);
[email protected]0f8f1b432010-03-16 19:06:03905 }
906
[email protected]12faa4c2012-11-06 04:44:18907 virtual ~IPv6ProbeJob() {}
[email protected]0f8f1b432010-03-16 19:06:03908
[email protected]0f8f1b432010-03-16 19:06:03909 private:
[email protected]12faa4c2012-11-06 04:44:18910 // Runs on worker thread.
[email protected]0f8f1b432010-03-16 19:06:03911 void DoProbe() {
[email protected]12faa4c2012-11-06 04:44:18912 result_ = TestIPv6Support();
[email protected]0f8f1b432010-03-16 19:06:03913 }
914
[email protected]12faa4c2012-11-06 04:44:18915 void OnProbeComplete() {
916 net_log_.EndEvent(NetLog::TYPE_IPV6_PROBE_RUNNING,
917 base::Bind(&IPv6SupportResult::ToNetLogValue,
918 base::Unretained(&result_)));
919 if (!resolver_)
[email protected]a9af7112010-05-08 00:56:01920 return;
[email protected]12faa4c2012-11-06 04:44:18921 resolver_->IPv6ProbeSetDefaultAddressFamily(
922 result_.ipv6_supported ? ADDRESS_FAMILY_UNSPECIFIED
[email protected]ae8e80f2012-07-19 21:08:33923 : ADDRESS_FAMILY_IPV4);
[email protected]0f8f1b432010-03-16 19:06:03924 }
925
[email protected]0f8f1b432010-03-16 19:06:03926 // Used/set only on origin thread.
[email protected]12faa4c2012-11-06 04:44:18927 base::WeakPtr<HostResolverImpl> resolver_;
[email protected]0f8f1b432010-03-16 19:06:03928
[email protected]ae8e80f2012-07-19 21:08:33929 BoundNetLog net_log_;
930
[email protected]12faa4c2012-11-06 04:44:18931 IPv6SupportResult result_;
932
[email protected]0f8f1b432010-03-16 19:06:03933 DISALLOW_COPY_AND_ASSIGN(IPv6ProbeJob);
934};
935
[email protected]12faa4c2012-11-06 04:44:18936// Wraps a call to HaveOnlyLoopbackAddresses to be executed on the WorkerPool as
937// it takes 40-100ms and should not block initialization.
938class HostResolverImpl::LoopbackProbeJob {
939 public:
940 explicit LoopbackProbeJob(const base::WeakPtr<HostResolverImpl>& resolver)
941 : resolver_(resolver),
942 result_(false) {
943 DCHECK(resolver);
944 const bool kIsSlow = true;
945 base::WorkerPool::PostTaskAndReply(
946 FROM_HERE,
947 base::Bind(&LoopbackProbeJob::DoProbe, base::Unretained(this)),
948 base::Bind(&LoopbackProbeJob::OnProbeComplete, base::Owned(this)),
949 kIsSlow);
950 }
951
952 virtual ~LoopbackProbeJob() {}
953
954 private:
955 // Runs on worker thread.
956 void DoProbe() {
957 result_ = HaveOnlyLoopbackAddresses();
958 }
959
960 void OnProbeComplete() {
961 if (!resolver_)
962 return;
963 resolver_->SetHaveOnlyLoopbackAddresses(result_);
964 }
965
966 // Used/set only on origin thread.
967 base::WeakPtr<HostResolverImpl> resolver_;
968
969 bool result_;
970
971 DISALLOW_COPY_AND_ASSIGN(LoopbackProbeJob);
972};
973
[email protected]0f8f1b432010-03-16 19:06:03974//-----------------------------------------------------------------------------
975
[email protected]b3601bc22012-02-21 21:23:20976// Resolves the hostname using DnsTransaction.
977// TODO(szym): This could be moved to separate source file as well.
[email protected]0adcb2b2012-08-15 21:30:46978class HostResolverImpl::DnsTask : public base::SupportsWeakPtr<DnsTask> {
[email protected]b3601bc22012-02-21 21:23:20979 public:
980 typedef base::Callback<void(int net_error,
981 const AddressList& addr_list,
982 base::TimeDelta ttl)> Callback;
983
[email protected]0adcb2b2012-08-15 21:30:46984 DnsTask(DnsClient* client,
[email protected]b3601bc22012-02-21 21:23:20985 const Key& key,
986 const Callback& callback,
987 const BoundNetLog& job_net_log)
[email protected]0adcb2b2012-08-15 21:30:46988 : client_(client),
989 family_(key.address_family),
990 callback_(callback),
991 net_log_(job_net_log) {
992 DCHECK(client);
[email protected]b3601bc22012-02-21 21:23:20993 DCHECK(!callback.is_null());
994
[email protected]0adcb2b2012-08-15 21:30:46995 // If unspecified, do IPv4 first, because suffix search will be faster.
996 uint16 qtype = (family_ == ADDRESS_FAMILY_IPV6) ?
997 dns_protocol::kTypeAAAA :
998 dns_protocol::kTypeA;
999 transaction_ = client_->GetTransactionFactory()->CreateTransaction(
[email protected]b3601bc22012-02-21 21:23:201000 key.hostname,
1001 qtype,
[email protected]1def74c2012-03-22 20:07:001002 base::Bind(&DnsTask::OnTransactionComplete, base::Unretained(this),
[email protected]0adcb2b2012-08-15 21:30:461003 true /* first_query */, base::TimeTicks::Now()),
[email protected]b3601bc22012-02-21 21:23:201004 net_log_);
[email protected]b3601bc22012-02-21 21:23:201005 }
1006
1007 int Start() {
[email protected]4da911f2012-06-14 19:45:201008 net_log_.BeginEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK);
[email protected]b3601bc22012-02-21 21:23:201009 return transaction_->Start();
1010 }
1011
[email protected]0adcb2b2012-08-15 21:30:461012 private:
1013 void OnTransactionComplete(bool first_query,
1014 const base::TimeTicks& start_time,
[email protected]1def74c2012-03-22 20:07:001015 DnsTransaction* transaction,
[email protected]b3601bc22012-02-21 21:23:201016 int net_error,
1017 const DnsResponse* response) {
[email protected]add76532012-03-30 14:47:471018 DCHECK(transaction);
[email protected]b3601bc22012-02-21 21:23:201019 // Run |callback_| last since the owning Job will then delete this DnsTask.
[email protected]0adcb2b2012-08-15 21:30:461020 if (net_error != OK) {
[email protected]708d0cc2012-08-14 23:32:291021 DNS_HISTOGRAM("AsyncDNS.TransactionFailure",
[email protected]6c411902012-08-14 22:36:361022 base::TimeTicks::Now() - start_time);
[email protected]0adcb2b2012-08-15 21:30:461023 OnFailure(net_error, DnsResponse::DNS_PARSE_OK);
1024 return;
[email protected]6c411902012-08-14 22:36:361025 }
[email protected]0adcb2b2012-08-15 21:30:461026
1027 CHECK(response);
1028 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess",
1029 base::TimeTicks::Now() - start_time);
1030 AddressList addr_list;
1031 base::TimeDelta ttl;
1032 DnsResponse::Result result = response->ParseToAddressList(&addr_list, &ttl);
1033 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ParseToAddressList",
1034 result,
1035 DnsResponse::DNS_PARSE_RESULT_MAX);
1036 if (result != DnsResponse::DNS_PARSE_OK) {
1037 // Fail even if the other query succeeds.
1038 OnFailure(ERR_DNS_MALFORMED_RESPONSE, result);
1039 return;
1040 }
1041
1042 bool needs_sort = false;
1043 if (first_query) {
1044 DCHECK(client_->GetConfig()) <<
1045 "Transaction should have been aborted when config changed!";
1046 if (family_ == ADDRESS_FAMILY_IPV6) {
1047 needs_sort = (addr_list.size() > 1);
1048 } else if (family_ == ADDRESS_FAMILY_UNSPECIFIED) {
1049 first_addr_list_ = addr_list;
1050 first_ttl_ = ttl;
1051 // Use fully-qualified domain name to avoid search.
1052 transaction_ = client_->GetTransactionFactory()->CreateTransaction(
1053 response->GetDottedName() + ".",
1054 dns_protocol::kTypeAAAA,
1055 base::Bind(&DnsTask::OnTransactionComplete, base::Unretained(this),
1056 false /* first_query */, base::TimeTicks::Now()),
1057 net_log_);
1058 net_error = transaction_->Start();
1059 if (net_error != ERR_IO_PENDING)
1060 OnFailure(net_error, DnsResponse::DNS_PARSE_OK);
1061 return;
1062 }
1063 } else {
1064 DCHECK_EQ(ADDRESS_FAMILY_UNSPECIFIED, family_);
1065 bool has_ipv6_addresses = !addr_list.empty();
1066 if (!first_addr_list_.empty()) {
1067 ttl = std::min(ttl, first_ttl_);
1068 // Place IPv4 addresses after IPv6.
1069 addr_list.insert(addr_list.end(), first_addr_list_.begin(),
1070 first_addr_list_.end());
1071 }
1072 needs_sort = (has_ipv6_addresses && addr_list.size() > 1);
1073 }
1074
1075 if (addr_list.empty()) {
1076 // TODO(szym): Don't fallback to ProcTask in this case.
1077 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
1078 return;
1079 }
1080
1081 if (needs_sort) {
1082 // Sort could complete synchronously.
1083 client_->GetAddressSorter()->Sort(
1084 addr_list,
[email protected]4589a3a2012-09-20 20:57:071085 base::Bind(&DnsTask::OnSortComplete,
1086 AsWeakPtr(),
[email protected]0adcb2b2012-08-15 21:30:461087 base::TimeTicks::Now(),
1088 ttl));
1089 } else {
1090 OnSuccess(addr_list, ttl);
1091 }
1092 }
1093
1094 void OnSortComplete(base::TimeTicks start_time,
1095 base::TimeDelta ttl,
1096 bool success,
1097 const AddressList& addr_list) {
1098 if (!success) {
1099 DNS_HISTOGRAM("AsyncDNS.SortFailure",
1100 base::TimeTicks::Now() - start_time);
1101 OnFailure(ERR_DNS_SORT_ERROR, DnsResponse::DNS_PARSE_OK);
1102 return;
1103 }
1104
1105 DNS_HISTOGRAM("AsyncDNS.SortSuccess",
1106 base::TimeTicks::Now() - start_time);
1107
1108 // AddressSorter prunes unusable destinations.
1109 if (addr_list.empty()) {
1110 LOG(WARNING) << "Address list empty after RFC3484 sort";
1111 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
1112 return;
1113 }
1114
1115 OnSuccess(addr_list, ttl);
1116 }
1117
1118 void OnFailure(int net_error, DnsResponse::Result result) {
1119 DCHECK_NE(OK, net_error);
[email protected]cd565142012-06-12 16:21:451120 net_log_.EndEvent(
1121 NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK,
1122 base::Bind(&NetLogDnsTaskFailedCallback, net_error, result));
[email protected]b3601bc22012-02-21 21:23:201123 callback_.Run(net_error, AddressList(), base::TimeDelta());
1124 }
1125
[email protected]0adcb2b2012-08-15 21:30:461126 void OnSuccess(const AddressList& addr_list, base::TimeDelta ttl) {
1127 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK,
1128 addr_list.CreateNetLogCallback());
1129 callback_.Run(OK, addr_list, ttl);
1130 }
1131
1132 DnsClient* client_;
1133 AddressFamily family_;
[email protected]b3601bc22012-02-21 21:23:201134 // The listener to the results of this DnsTask.
1135 Callback callback_;
[email protected]b3601bc22012-02-21 21:23:201136 const BoundNetLog net_log_;
1137
1138 scoped_ptr<DnsTransaction> transaction_;
[email protected]0adcb2b2012-08-15 21:30:461139
1140 // Results from the first transaction. Used only if |family_| is unspecified.
1141 AddressList first_addr_list_;
1142 base::TimeDelta first_ttl_;
1143
1144 DISALLOW_COPY_AND_ASSIGN(DnsTask);
[email protected]b3601bc22012-02-21 21:23:201145};
1146
1147//-----------------------------------------------------------------------------
1148
[email protected]0f292de02012-02-01 22:28:201149// Aggregates all Requests for the same Key. Dispatched via PriorityDispatch.
[email protected]0f292de02012-02-01 22:28:201150class HostResolverImpl::Job : public PrioritizedDispatcher::Job {
[email protected]68ad3ee2010-01-30 03:45:391151 public:
[email protected]0f292de02012-02-01 22:28:201152 // Creates new job for |key| where |request_net_log| is bound to the
[email protected]16ee26d2012-03-08 03:34:351153 // request that spawned it.
[email protected]12faa4c2012-11-06 04:44:181154 Job(const base::WeakPtr<HostResolverImpl>& resolver,
[email protected]0f292de02012-02-01 22:28:201155 const Key& key,
[email protected]8c98d002012-07-18 19:02:271156 RequestPriority priority,
[email protected]16ee26d2012-03-08 03:34:351157 const BoundNetLog& request_net_log)
[email protected]12faa4c2012-11-06 04:44:181158 : resolver_(resolver),
[email protected]0f292de02012-02-01 22:28:201159 key_(key),
[email protected]8c98d002012-07-18 19:02:271160 priority_tracker_(priority),
[email protected]0f292de02012-02-01 22:28:201161 had_non_speculative_request_(false),
[email protected]51b9a6b2012-06-25 21:50:291162 had_dns_config_(false),
[email protected]1d932852012-06-19 19:40:331163 dns_task_error_(OK),
[email protected]51b9a6b2012-06-25 21:50:291164 creation_time_(base::TimeTicks::Now()),
1165 priority_change_time_(creation_time_),
[email protected]0f292de02012-02-01 22:28:201166 net_log_(BoundNetLog::Make(request_net_log.net_log(),
[email protected]b3601bc22012-02-21 21:23:201167 NetLog::SOURCE_HOST_RESOLVER_IMPL_JOB)) {
[email protected]4da911f2012-06-14 19:45:201168 request_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_CREATE_JOB);
[email protected]0f292de02012-02-01 22:28:201169
1170 net_log_.BeginEvent(
1171 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
[email protected]cd565142012-06-12 16:21:451172 base::Bind(&NetLogJobCreationCallback,
1173 request_net_log.source(),
1174 &key_.hostname));
[email protected]68ad3ee2010-01-30 03:45:391175 }
1176
[email protected]0f292de02012-02-01 22:28:201177 virtual ~Job() {
[email protected]b3601bc22012-02-21 21:23:201178 if (is_running()) {
1179 // |resolver_| was destroyed with this Job still in flight.
1180 // Clean-up, record in the log, but don't run any callbacks.
1181 if (is_proc_running()) {
[email protected]0f292de02012-02-01 22:28:201182 proc_task_->Cancel();
1183 proc_task_ = NULL;
[email protected]0f292de02012-02-01 22:28:201184 }
[email protected]16ee26d2012-03-08 03:34:351185 // Clean up now for nice NetLog.
1186 dns_task_.reset(NULL);
[email protected]b3601bc22012-02-21 21:23:201187 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
1188 ERR_ABORTED);
1189 } else if (is_queued()) {
[email protected]57a48d32012-03-03 00:04:551190 // |resolver_| was destroyed without running this Job.
[email protected]16ee26d2012-03-08 03:34:351191 // TODO(szym): is there any benefit in having this distinction?
[email protected]4da911f2012-06-14 19:45:201192 net_log_.AddEvent(NetLog::TYPE_CANCELLED);
1193 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB);
[email protected]68ad3ee2010-01-30 03:45:391194 }
[email protected]b3601bc22012-02-21 21:23:201195 // else CompleteRequests logged EndEvent.
[email protected]68ad3ee2010-01-30 03:45:391196
[email protected]b3601bc22012-02-21 21:23:201197 // Log any remaining Requests as cancelled.
1198 for (RequestsList::const_iterator it = requests_.begin();
1199 it != requests_.end(); ++it) {
1200 Request* req = *it;
1201 if (req->was_canceled())
1202 continue;
1203 DCHECK_EQ(this, req->job());
1204 LogCancelRequest(req->source_net_log(), req->request_net_log(),
1205 req->info());
1206 }
[email protected]68ad3ee2010-01-30 03:45:391207 }
1208
[email protected]16ee26d2012-03-08 03:34:351209 // Add this job to the dispatcher.
[email protected]8c98d002012-07-18 19:02:271210 void Schedule() {
1211 handle_ = resolver_->dispatcher_.Add(this, priority());
[email protected]16ee26d2012-03-08 03:34:351212 }
1213
[email protected]b3601bc22012-02-21 21:23:201214 void AddRequest(scoped_ptr<Request> req) {
[email protected]0f292de02012-02-01 22:28:201215 DCHECK_EQ(key_.hostname, req->info().hostname());
1216
1217 req->set_job(this);
[email protected]0f292de02012-02-01 22:28:201218 priority_tracker_.Add(req->info().priority());
1219
1220 req->request_net_log().AddEvent(
1221 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_ATTACH,
[email protected]cd565142012-06-12 16:21:451222 net_log_.source().ToEventParametersCallback());
[email protected]0f292de02012-02-01 22:28:201223
1224 net_log_.AddEvent(
1225 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_REQUEST_ATTACH,
[email protected]cd565142012-06-12 16:21:451226 base::Bind(&NetLogJobAttachCallback,
1227 req->request_net_log().source(),
1228 priority()));
[email protected]0f292de02012-02-01 22:28:201229
1230 // TODO(szym): Check if this is still needed.
1231 if (!req->info().is_speculative()) {
1232 had_non_speculative_request_ = true;
1233 if (proc_task_)
1234 proc_task_->set_had_non_speculative_request();
[email protected]68ad3ee2010-01-30 03:45:391235 }
[email protected]b3601bc22012-02-21 21:23:201236
1237 requests_.push_back(req.release());
1238
[email protected]51b9a6b2012-06-25 21:50:291239 UpdatePriority();
[email protected]68ad3ee2010-01-30 03:45:391240 }
1241
[email protected]16ee26d2012-03-08 03:34:351242 // Marks |req| as cancelled. If it was the last active Request, also finishes
[email protected]0adcb2b2012-08-15 21:30:461243 // this Job, marking it as cancelled, and deletes it.
[email protected]0f292de02012-02-01 22:28:201244 void CancelRequest(Request* req) {
1245 DCHECK_EQ(key_.hostname, req->info().hostname());
1246 DCHECK(!req->was_canceled());
[email protected]16ee26d2012-03-08 03:34:351247
[email protected]0f292de02012-02-01 22:28:201248 // Don't remove it from |requests_| just mark it canceled.
1249 req->MarkAsCanceled();
1250 LogCancelRequest(req->source_net_log(), req->request_net_log(),
1251 req->info());
[email protected]16ee26d2012-03-08 03:34:351252
[email protected]0f292de02012-02-01 22:28:201253 priority_tracker_.Remove(req->info().priority());
1254 net_log_.AddEvent(
1255 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_REQUEST_DETACH,
[email protected]cd565142012-06-12 16:21:451256 base::Bind(&NetLogJobAttachCallback,
1257 req->request_net_log().source(),
1258 priority()));
[email protected]b3601bc22012-02-21 21:23:201259
[email protected]16ee26d2012-03-08 03:34:351260 if (num_active_requests() > 0) {
[email protected]51b9a6b2012-06-25 21:50:291261 UpdatePriority();
[email protected]16ee26d2012-03-08 03:34:351262 } else {
1263 // If we were called from a Request's callback within CompleteRequests,
1264 // that Request could not have been cancelled, so num_active_requests()
1265 // could not be 0. Therefore, we are not in CompleteRequests().
[email protected]1339a2a22012-10-17 08:39:431266 CompleteRequestsWithError(OK /* cancelled */);
[email protected]b3601bc22012-02-21 21:23:201267 }
[email protected]68ad3ee2010-01-30 03:45:391268 }
1269
[email protected]7af985a2012-12-14 22:40:421270 // Called from AbortAllInProgressJobs. Completes all requests and destroys
1271 // the job. This currently assumes the abort is due to a network change.
[email protected]0f292de02012-02-01 22:28:201272 void Abort() {
[email protected]0f292de02012-02-01 22:28:201273 DCHECK(is_running());
[email protected]7af985a2012-12-14 22:40:421274 CompleteRequestsWithError(ERR_NETWORK_CHANGED);
[email protected]b3601bc22012-02-21 21:23:201275 }
1276
[email protected]f0f602bd2012-11-15 18:01:021277 // If DnsTask present, abort it and fall back to ProcTask.
1278 void AbortDnsTask() {
1279 if (dns_task_) {
1280 dns_task_.reset();
1281 dns_task_error_ = OK;
1282 StartProcTask();
1283 }
1284 }
1285
[email protected]16ee26d2012-03-08 03:34:351286 // Called by HostResolverImpl when this job is evicted due to queue overflow.
1287 // Completes all requests and destroys the job.
1288 void OnEvicted() {
1289 DCHECK(!is_running());
1290 DCHECK(is_queued());
1291 handle_.Reset();
1292
[email protected]4da911f2012-06-14 19:45:201293 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_EVICTED);
[email protected]16ee26d2012-03-08 03:34:351294
1295 // This signals to CompleteRequests that this job never ran.
[email protected]1339a2a22012-10-17 08:39:431296 CompleteRequestsWithError(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
[email protected]16ee26d2012-03-08 03:34:351297 }
1298
[email protected]78eac2a2012-03-14 19:09:271299 // Attempts to serve the job from HOSTS. Returns true if succeeded and
1300 // this Job was destroyed.
1301 bool ServeFromHosts() {
1302 DCHECK_GT(num_active_requests(), 0u);
1303 AddressList addr_list;
1304 if (resolver_->ServeFromHosts(key(),
[email protected]3cb676a12012-06-30 15:46:031305 requests_.front()->info(),
[email protected]78eac2a2012-03-14 19:09:271306 &addr_list)) {
1307 // This will destroy the Job.
[email protected]895123222012-10-25 15:21:171308 CompleteRequests(
1309 HostCache::Entry(OK, MakeAddressListForRequest(addr_list)),
1310 base::TimeDelta());
[email protected]78eac2a2012-03-14 19:09:271311 return true;
1312 }
1313 return false;
1314 }
1315
[email protected]b4481b222012-03-16 17:13:111316 const Key key() const {
1317 return key_;
1318 }
1319
1320 bool is_queued() const {
1321 return !handle_.is_null();
1322 }
1323
1324 bool is_running() const {
1325 return is_dns_running() || is_proc_running();
1326 }
1327
[email protected]16ee26d2012-03-08 03:34:351328 private:
[email protected]51b9a6b2012-06-25 21:50:291329 void UpdatePriority() {
1330 if (is_queued()) {
1331 if (priority() != static_cast<RequestPriority>(handle_.priority()))
1332 priority_change_time_ = base::TimeTicks::Now();
1333 handle_ = resolver_->dispatcher_.ChangePriority(handle_, priority());
1334 }
1335 }
1336
[email protected]895123222012-10-25 15:21:171337 AddressList MakeAddressListForRequest(const AddressList& list) const {
1338 if (requests_.empty())
1339 return list;
1340 return AddressList::CopyWithPort(list, requests_.front()->info().port());
1341 }
1342
[email protected]16ee26d2012-03-08 03:34:351343 // PriorityDispatch::Job:
[email protected]0f292de02012-02-01 22:28:201344 virtual void Start() OVERRIDE {
1345 DCHECK(!is_running());
[email protected]b3601bc22012-02-21 21:23:201346 handle_.Reset();
[email protected]0f292de02012-02-01 22:28:201347
[email protected]4da911f2012-06-14 19:45:201348 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_STARTED);
[email protected]0f292de02012-02-01 22:28:201349
[email protected]51b9a6b2012-06-25 21:50:291350 had_dns_config_ = resolver_->HaveDnsConfig();
1351
1352 base::TimeTicks now = base::TimeTicks::Now();
1353 base::TimeDelta queue_time = now - creation_time_;
1354 base::TimeDelta queue_time_after_change = now - priority_change_time_;
1355
1356 if (had_dns_config_) {
1357 DNS_HISTOGRAM_BY_PRIORITY("AsyncDNS.JobQueueTime", priority(),
1358 queue_time);
1359 DNS_HISTOGRAM_BY_PRIORITY("AsyncDNS.JobQueueTimeAfterChange", priority(),
1360 queue_time_after_change);
1361 } else {
1362 DNS_HISTOGRAM_BY_PRIORITY("DNS.JobQueueTime", priority(), queue_time);
1363 DNS_HISTOGRAM_BY_PRIORITY("DNS.JobQueueTimeAfterChange", priority(),
1364 queue_time_after_change);
1365 }
1366
[email protected]1d932852012-06-19 19:40:331367 // Caution: Job::Start must not complete synchronously.
[email protected]51b9a6b2012-06-25 21:50:291368 if (had_dns_config_ && !ResemblesMulticastDNSName(key_.hostname)) {
[email protected]b3601bc22012-02-21 21:23:201369 StartDnsTask();
1370 } else {
1371 StartProcTask();
1372 }
1373 }
1374
[email protected]b3601bc22012-02-21 21:23:201375 // TODO(szym): Since DnsTransaction does not consume threads, we can increase
1376 // the limits on |dispatcher_|. But in order to keep the number of WorkerPool
1377 // threads low, we will need to use an "inner" PrioritizedDispatcher with
1378 // tighter limits.
1379 void StartProcTask() {
[email protected]16ee26d2012-03-08 03:34:351380 DCHECK(!is_dns_running());
[email protected]0f292de02012-02-01 22:28:201381 proc_task_ = new ProcTask(
1382 key_,
1383 resolver_->proc_params_,
[email protected]e3bd4822012-10-23 18:01:371384 base::Bind(&Job::OnProcTaskComplete, base::Unretained(this),
1385 base::TimeTicks::Now()),
[email protected]0f292de02012-02-01 22:28:201386 net_log_);
1387
1388 if (had_non_speculative_request_)
1389 proc_task_->set_had_non_speculative_request();
1390 // Start() could be called from within Resolve(), hence it must NOT directly
1391 // call OnProcTaskComplete, for example, on synchronous failure.
1392 proc_task_->Start();
[email protected]68ad3ee2010-01-30 03:45:391393 }
1394
[email protected]0f292de02012-02-01 22:28:201395 // Called by ProcTask when it completes.
[email protected]e3bd4822012-10-23 18:01:371396 void OnProcTaskComplete(base::TimeTicks start_time,
1397 int net_error,
1398 const AddressList& addr_list) {
[email protected]b3601bc22012-02-21 21:23:201399 DCHECK(is_proc_running());
[email protected]68ad3ee2010-01-30 03:45:391400
[email protected]1d932852012-06-19 19:40:331401 if (dns_task_error_ != OK) {
[email protected]e3bd4822012-10-23 18:01:371402 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]1def74c2012-03-22 20:07:001403 if (net_error == OK) {
[email protected]e3bd4822012-10-23 18:01:371404 DNS_HISTOGRAM("AsyncDNS.FallbackSuccess", duration);
[email protected]1d932852012-06-19 19:40:331405 if ((dns_task_error_ == ERR_NAME_NOT_RESOLVED) &&
1406 ResemblesNetBIOSName(key_.hostname)) {
1407 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_SUSPECT_NETBIOS);
1408 } else {
1409 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_PROC_SUCCESS);
1410 }
1411 UMA_HISTOGRAM_CUSTOM_ENUMERATION("AsyncDNS.ResolveError",
1412 std::abs(dns_task_error_),
1413 GetAllErrorCodesForUma());
[email protected]1ffdda82012-12-12 23:04:221414 resolver_->OnDnsTaskResolve(dns_task_error_);
[email protected]1def74c2012-03-22 20:07:001415 } else {
[email protected]e3bd4822012-10-23 18:01:371416 DNS_HISTOGRAM("AsyncDNS.FallbackFail", duration);
[email protected]1def74c2012-03-22 20:07:001417 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
1418 }
1419 }
1420
[email protected]1339a2a22012-10-17 08:39:431421 base::TimeDelta ttl =
1422 base::TimeDelta::FromSeconds(kNegativeCacheEntryTTLSeconds);
[email protected]b3601bc22012-02-21 21:23:201423 if (net_error == OK)
1424 ttl = base::TimeDelta::FromSeconds(kCacheEntryTTLSeconds);
[email protected]68ad3ee2010-01-30 03:45:391425
[email protected]895123222012-10-25 15:21:171426 // Don't store the |ttl| in cache since it's not obtained from the server.
1427 CompleteRequests(
1428 HostCache::Entry(net_error, MakeAddressListForRequest(addr_list)),
1429 ttl);
[email protected]b3601bc22012-02-21 21:23:201430 }
1431
1432 void StartDnsTask() {
[email protected]78eac2a2012-03-14 19:09:271433 DCHECK(resolver_->HaveDnsConfig());
[email protected]b3601bc22012-02-21 21:23:201434 dns_task_.reset(new DnsTask(
[email protected]0adcb2b2012-08-15 21:30:461435 resolver_->dns_client_.get(),
[email protected]b3601bc22012-02-21 21:23:201436 key_,
[email protected]e3bd4822012-10-23 18:01:371437 base::Bind(&Job::OnDnsTaskComplete, base::Unretained(this),
1438 base::TimeTicks::Now()),
[email protected]b3601bc22012-02-21 21:23:201439 net_log_));
1440
1441 int rv = dns_task_->Start();
1442 if (rv != ERR_IO_PENDING) {
1443 DCHECK_NE(OK, rv);
[email protected]51b9a6b2012-06-25 21:50:291444 dns_task_error_ = rv;
[email protected]b3601bc22012-02-21 21:23:201445 dns_task_.reset();
1446 StartProcTask();
1447 }
1448 }
1449
1450 // Called by DnsTask when it completes.
[email protected]e3bd4822012-10-23 18:01:371451 void OnDnsTaskComplete(base::TimeTicks start_time,
1452 int net_error,
[email protected]b3601bc22012-02-21 21:23:201453 const AddressList& addr_list,
1454 base::TimeDelta ttl) {
1455 DCHECK(is_dns_running());
[email protected]b3601bc22012-02-21 21:23:201456
[email protected]e3bd4822012-10-23 18:01:371457 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]b3601bc22012-02-21 21:23:201458 if (net_error != OK) {
[email protected]e3bd4822012-10-23 18:01:371459 DNS_HISTOGRAM("AsyncDNS.ResolveFail", duration);
1460
[email protected]1d932852012-06-19 19:40:331461 dns_task_error_ = net_error;
[email protected]16ee26d2012-03-08 03:34:351462 dns_task_.reset();
[email protected]78eac2a2012-03-14 19:09:271463
1464 // TODO(szym): Run ServeFromHosts now if nsswitch.conf says so.
1465 // http://crbug.com/117655
1466
[email protected]b3601bc22012-02-21 21:23:201467 // TODO(szym): Some net errors indicate lack of connectivity. Starting
1468 // ProcTask in that case is a waste of time.
1469 StartProcTask();
1470 return;
1471 }
[email protected]e3bd4822012-10-23 18:01:371472 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess", duration);
[email protected]b3601bc22012-02-21 21:23:201473
[email protected]1def74c2012-03-22 20:07:001474 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_DNS_SUCCESS);
[email protected]1339a2a22012-10-17 08:39:431475 RecordTTL(ttl);
[email protected]0adcb2b2012-08-15 21:30:461476
[email protected]1ffdda82012-12-12 23:04:221477 resolver_->OnDnsTaskResolve(OK);
[email protected]f0f602bd2012-11-15 18:01:021478
[email protected]895123222012-10-25 15:21:171479 base::TimeDelta bounded_ttl =
1480 std::max(ttl, base::TimeDelta::FromSeconds(kMinimumTTLSeconds));
1481
1482 CompleteRequests(
1483 HostCache::Entry(net_error, MakeAddressListForRequest(addr_list), ttl),
1484 bounded_ttl);
[email protected]b3601bc22012-02-21 21:23:201485 }
1486
[email protected]16ee26d2012-03-08 03:34:351487 // Performs Job's last rites. Completes all Requests. Deletes this.
[email protected]895123222012-10-25 15:21:171488 void CompleteRequests(const HostCache::Entry& entry,
1489 base::TimeDelta ttl) {
[email protected]b3601bc22012-02-21 21:23:201490 CHECK(resolver_);
[email protected]b3601bc22012-02-21 21:23:201491
[email protected]16ee26d2012-03-08 03:34:351492 // This job must be removed from resolver's |jobs_| now to make room for a
1493 // new job with the same key in case one of the OnComplete callbacks decides
1494 // to spawn one. Consequently, the job deletes itself when CompleteRequests
1495 // is done.
1496 scoped_ptr<Job> self_deleter(this);
1497
1498 resolver_->RemoveJob(this);
1499
[email protected]16ee26d2012-03-08 03:34:351500 if (is_running()) {
1501 DCHECK(!is_queued());
1502 if (is_proc_running()) {
1503 proc_task_->Cancel();
1504 proc_task_ = NULL;
1505 }
1506 dns_task_.reset();
1507
1508 // Signal dispatcher that a slot has opened.
1509 resolver_->dispatcher_.OnJobFinished();
1510 } else if (is_queued()) {
1511 resolver_->dispatcher_.Cancel(handle_);
1512 handle_.Reset();
1513 }
1514
1515 if (num_active_requests() == 0) {
[email protected]4da911f2012-06-14 19:45:201516 net_log_.AddEvent(NetLog::TYPE_CANCELLED);
[email protected]16ee26d2012-03-08 03:34:351517 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
1518 OK);
1519 return;
1520 }
[email protected]b3601bc22012-02-21 21:23:201521
1522 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
[email protected]895123222012-10-25 15:21:171523 entry.error);
[email protected]68ad3ee2010-01-30 03:45:391524
[email protected]78eac2a2012-03-14 19:09:271525 DCHECK(!requests_.empty());
1526
[email protected]895123222012-10-25 15:21:171527 if (entry.error == OK) {
[email protected]d7b9a2b2012-05-31 22:31:191528 // Record this histogram here, when we know the system has a valid DNS
1529 // configuration.
[email protected]539df6c2012-06-19 21:21:291530 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.HaveDnsConfig",
1531 resolver_->received_dns_config_);
[email protected]d7b9a2b2012-05-31 22:31:191532 }
[email protected]16ee26d2012-03-08 03:34:351533
[email protected]7af985a2012-12-14 22:40:421534 bool did_complete = (entry.error != ERR_NETWORK_CHANGED) &&
[email protected]895123222012-10-25 15:21:171535 (entry.error != ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
1536 if (did_complete)
[email protected]1339a2a22012-10-17 08:39:431537 resolver_->CacheResult(key_, entry, ttl);
[email protected]16ee26d2012-03-08 03:34:351538
[email protected]0f292de02012-02-01 22:28:201539 // Complete all of the requests that were attached to the job.
1540 for (RequestsList::const_iterator it = requests_.begin();
1541 it != requests_.end(); ++it) {
1542 Request* req = *it;
1543
1544 if (req->was_canceled())
1545 continue;
1546
1547 DCHECK_EQ(this, req->job());
1548 // Update the net log and notify registered observers.
1549 LogFinishRequest(req->source_net_log(), req->request_net_log(),
[email protected]895123222012-10-25 15:21:171550 req->info(), entry.error);
[email protected]51b9a6b2012-06-25 21:50:291551 if (did_complete) {
1552 // Record effective total time from creation to completion.
1553 RecordTotalTime(had_dns_config_, req->info().is_speculative(),
1554 base::TimeTicks::Now() - req->request_time());
1555 }
[email protected]895123222012-10-25 15:21:171556 req->OnComplete(entry.error, entry.addrlist);
[email protected]0f292de02012-02-01 22:28:201557
1558 // Check if the resolver was destroyed as a result of running the
1559 // callback. If it was, we could continue, but we choose to bail.
1560 if (!resolver_)
1561 return;
1562 }
1563 }
1564
[email protected]1339a2a22012-10-17 08:39:431565 // Convenience wrapper for CompleteRequests in case of failure.
1566 void CompleteRequestsWithError(int net_error) {
[email protected]895123222012-10-25 15:21:171567 CompleteRequests(HostCache::Entry(net_error, AddressList()),
1568 base::TimeDelta());
[email protected]1339a2a22012-10-17 08:39:431569 }
1570
[email protected]b4481b222012-03-16 17:13:111571 RequestPriority priority() const {
1572 return priority_tracker_.highest_priority();
1573 }
1574
1575 // Number of non-canceled requests in |requests_|.
1576 size_t num_active_requests() const {
1577 return priority_tracker_.total_count();
1578 }
1579
1580 bool is_dns_running() const {
1581 return dns_task_.get() != NULL;
1582 }
1583
1584 bool is_proc_running() const {
1585 return proc_task_.get() != NULL;
1586 }
1587
[email protected]0f292de02012-02-01 22:28:201588 base::WeakPtr<HostResolverImpl> resolver_;
1589
1590 Key key_;
1591
1592 // Tracks the highest priority across |requests_|.
1593 PriorityTracker priority_tracker_;
1594
1595 bool had_non_speculative_request_;
1596
[email protected]51b9a6b2012-06-25 21:50:291597 // Distinguishes measurements taken while DnsClient was fully configured.
1598 bool had_dns_config_;
1599
[email protected]1d932852012-06-19 19:40:331600 // Result of DnsTask.
1601 int dns_task_error_;
[email protected]1def74c2012-03-22 20:07:001602
[email protected]51b9a6b2012-06-25 21:50:291603 const base::TimeTicks creation_time_;
1604 base::TimeTicks priority_change_time_;
1605
[email protected]0f292de02012-02-01 22:28:201606 BoundNetLog net_log_;
1607
[email protected]b3601bc22012-02-21 21:23:201608 // Resolves the host using a HostResolverProc.
[email protected]0f292de02012-02-01 22:28:201609 scoped_refptr<ProcTask> proc_task_;
1610
[email protected]b3601bc22012-02-21 21:23:201611 // Resolves the host using a DnsTransaction.
1612 scoped_ptr<DnsTask> dns_task_;
1613
[email protected]0f292de02012-02-01 22:28:201614 // All Requests waiting for the result of this Job. Some can be canceled.
1615 RequestsList requests_;
1616
[email protected]16ee26d2012-03-08 03:34:351617 // A handle used in |HostResolverImpl::dispatcher_|.
[email protected]0f292de02012-02-01 22:28:201618 PrioritizedDispatcher::Handle handle_;
[email protected]68ad3ee2010-01-30 03:45:391619};
1620
1621//-----------------------------------------------------------------------------
1622
[email protected]0f292de02012-02-01 22:28:201623HostResolverImpl::ProcTaskParams::ProcTaskParams(
[email protected]e95d3aca2010-01-11 22:47:431624 HostResolverProc* resolver_proc,
[email protected]0f292de02012-02-01 22:28:201625 size_t max_retry_attempts)
1626 : resolver_proc(resolver_proc),
1627 max_retry_attempts(max_retry_attempts),
1628 unresponsive_delay(base::TimeDelta::FromMilliseconds(6000)),
1629 retry_factor(2) {
1630}
1631
1632HostResolverImpl::ProcTaskParams::~ProcTaskParams() {}
1633
1634HostResolverImpl::HostResolverImpl(
[email protected]c54a8912012-10-22 22:09:431635 scoped_ptr<HostCache> cache,
[email protected]0f292de02012-02-01 22:28:201636 const PrioritizedDispatcher::Limits& job_limits,
1637 const ProcTaskParams& proc_params,
[email protected]ee094b82010-08-24 15:55:511638 NetLog* net_log)
[email protected]c54a8912012-10-22 22:09:431639 : cache_(cache.Pass()),
[email protected]0f292de02012-02-01 22:28:201640 dispatcher_(job_limits),
1641 max_queued_jobs_(job_limits.total_jobs * 100u),
1642 proc_params_(proc_params),
[email protected]0c7798452009-10-26 17:59:511643 default_address_family_(ADDRESS_FAMILY_UNSPECIFIED),
[email protected]4589a3a2012-09-20 20:57:071644 weak_ptr_factory_(this),
[email protected]12faa4c2012-11-06 04:44:181645 probe_weak_ptr_factory_(this),
[email protected]d7b9a2b2012-05-31 22:31:191646 received_dns_config_(false),
[email protected]f0f602bd2012-11-15 18:01:021647 num_dns_failures_(0),
[email protected]2f3bc65c2010-07-23 17:47:101648 ipv6_probe_monitoring_(false),
[email protected]ee094b82010-08-24 15:55:511649 additional_resolver_flags_(0),
1650 net_log_(net_log) {
[email protected]0f292de02012-02-01 22:28:201651
1652 DCHECK_GE(dispatcher_.num_priorities(), static_cast<size_t>(NUM_PRIORITIES));
[email protected]68ad3ee2010-01-30 03:45:391653
[email protected]06ef6d92011-05-19 04:24:581654 // Maximum of 4 retry attempts for host resolution.
1655 static const size_t kDefaultMaxRetryAttempts = 4u;
1656
[email protected]0f292de02012-02-01 22:28:201657 if (proc_params_.max_retry_attempts == HostResolver::kDefaultRetryAttempts)
1658 proc_params_.max_retry_attempts = kDefaultMaxRetryAttempts;
[email protected]68ad3ee2010-01-30 03:45:391659
[email protected]b59ff372009-07-15 22:04:321660#if defined(OS_WIN)
1661 EnsureWinsockInit();
1662#endif
[email protected]23f771162011-06-02 18:37:511663#if defined(OS_POSIX) && !defined(OS_MACOSX)
[email protected]12faa4c2012-11-06 04:44:181664 new LoopbackProbeJob(weak_ptr_factory_.GetWeakPtr());
[email protected]2f3bc65c2010-07-23 17:47:101665#endif
[email protected]232a5812011-03-04 22:42:081666 NetworkChangeNotifier::AddIPAddressObserver(this);
[email protected]bb0e34542012-08-31 19:52:401667 NetworkChangeNotifier::AddDNSObserver(this);
[email protected]d7b9a2b2012-05-31 22:31:191668#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD) && \
1669 !defined(OS_ANDROID)
[email protected]d7b9a2b2012-05-31 22:31:191670 EnsureDnsReloaderInit();
[email protected]46018c9d2011-09-06 03:42:341671#endif
[email protected]2ac22db2012-11-28 19:50:041672
1673 // TODO(szym): Remove when received_dns_config_ is removed, once
1674 // http://crbug.com/137914 is resolved.
1675 {
1676 DnsConfig dns_config;
1677 NetworkChangeNotifier::GetDnsConfig(&dns_config);
1678 received_dns_config_ = dns_config.IsValid();
1679 }
[email protected]b59ff372009-07-15 22:04:321680}
1681
1682HostResolverImpl::~HostResolverImpl() {
[email protected]0f292de02012-02-01 22:28:201683 // This will also cancel all outstanding requests.
1684 STLDeleteValues(&jobs_);
[email protected]e95d3aca2010-01-11 22:47:431685
[email protected]232a5812011-03-04 22:42:081686 NetworkChangeNotifier::RemoveIPAddressObserver(this);
[email protected]bb0e34542012-08-31 19:52:401687 NetworkChangeNotifier::RemoveDNSObserver(this);
[email protected]b59ff372009-07-15 22:04:321688}
1689
[email protected]0f292de02012-02-01 22:28:201690void HostResolverImpl::SetMaxQueuedJobs(size_t value) {
1691 DCHECK_EQ(0u, dispatcher_.num_queued_jobs());
1692 DCHECK_GT(value, 0u);
1693 max_queued_jobs_ = value;
[email protected]be1a48b2011-01-20 00:12:131694}
1695
[email protected]684970b2009-08-14 04:54:461696int HostResolverImpl::Resolve(const RequestInfo& info,
[email protected]b59ff372009-07-15 22:04:321697 AddressList* addresses,
[email protected]aa22b242011-11-16 18:58:291698 const CompletionCallback& callback,
[email protected]684970b2009-08-14 04:54:461699 RequestHandle* out_req,
[email protected]ee094b82010-08-24 15:55:511700 const BoundNetLog& source_net_log) {
[email protected]95a214c2011-08-04 21:50:401701 DCHECK(addresses);
[email protected]1ac6af92010-06-03 21:00:141702 DCHECK(CalledOnValidThread());
[email protected]aa22b242011-11-16 18:58:291703 DCHECK_EQ(false, callback.is_null());
[email protected]1ac6af92010-06-03 21:00:141704
[email protected]ee094b82010-08-24 15:55:511705 // Make a log item for the request.
1706 BoundNetLog request_net_log = BoundNetLog::Make(net_log_,
1707 NetLog::SOURCE_HOST_RESOLVER_IMPL_REQUEST);
1708
[email protected]0f292de02012-02-01 22:28:201709 LogStartRequest(source_net_log, request_net_log, info);
[email protected]b59ff372009-07-15 22:04:321710
[email protected]123ab1e32009-10-21 19:12:571711 // Build a key that identifies the request in the cache and in the
1712 // outstanding jobs map.
[email protected]137af622010-02-05 02:14:351713 Key key = GetEffectiveKeyForRequest(info);
[email protected]123ab1e32009-10-21 19:12:571714
[email protected]287d7c22011-11-15 17:34:251715 int rv = ResolveHelper(key, info, addresses, request_net_log);
[email protected]95a214c2011-08-04 21:50:401716 if (rv != ERR_DNS_CACHE_MISS) {
[email protected]b3601bc22012-02-21 21:23:201717 LogFinishRequest(source_net_log, request_net_log, info, rv);
[email protected]51b9a6b2012-06-25 21:50:291718 RecordTotalTime(HaveDnsConfig(), info.is_speculative(), base::TimeDelta());
[email protected]95a214c2011-08-04 21:50:401719 return rv;
[email protected]38368712011-03-02 08:09:401720 }
1721
[email protected]0f292de02012-02-01 22:28:201722 // Next we need to attach our request to a "job". This job is responsible for
1723 // calling "getaddrinfo(hostname)" on a worker thread.
1724
1725 JobMap::iterator jobit = jobs_.find(key);
1726 Job* job;
1727 if (jobit == jobs_.end()) {
[email protected]407a30ab2012-08-15 17:16:101728 // If we couldn't find the desired address family, check to see if the
1729 // other family is in the cache or another job, which indicates waste,
1730 // and we should fix crbug.com/139811.
1731 {
1732 bool ipv4 = key.address_family == ADDRESS_FAMILY_IPV4;
1733 Key other_family_key = key;
1734 other_family_key.address_family = ipv4 ?
1735 ADDRESS_FAMILY_UNSPECIFIED : ADDRESS_FAMILY_IPV4;
1736 bool found_other_family_cache = false;
1737 bool found_other_family_job = false;
1738 if (default_address_family_ == ADDRESS_FAMILY_UNSPECIFIED) {
1739 found_other_family_cache = cache_.get() &&
1740 cache_->Lookup(other_family_key, base::TimeTicks::Now()) != NULL;
1741 if (!found_other_family_cache)
1742 found_other_family_job = jobs_.count(other_family_key) > 0;
1743 }
1744 enum { // Used in UMA_HISTOGRAM_ENUMERATION.
1745 AF_WASTE_IPV4_ONLY,
1746 AF_WASTE_CACHE_IPV4,
1747 AF_WASTE_CACHE_UNSPEC,
1748 AF_WASTE_JOB_IPV4,
1749 AF_WASTE_JOB_UNSPEC,
1750 AF_WASTE_NONE_IPV4,
1751 AF_WASTE_NONE_UNSPEC,
1752 AF_WASTE_MAX, // Bounding value.
1753 } category = AF_WASTE_MAX;
1754 if (default_address_family_ != ADDRESS_FAMILY_UNSPECIFIED) {
1755 category = AF_WASTE_IPV4_ONLY;
1756 } else if (found_other_family_cache) {
1757 category = ipv4 ? AF_WASTE_CACHE_IPV4 : AF_WASTE_CACHE_UNSPEC;
1758 } else if (found_other_family_job) {
1759 category = ipv4 ? AF_WASTE_JOB_IPV4 : AF_WASTE_JOB_UNSPEC;
1760 } else {
1761 category = ipv4 ? AF_WASTE_NONE_IPV4 : AF_WASTE_NONE_UNSPEC;
1762 }
1763 UMA_HISTOGRAM_ENUMERATION("DNS.ResolveUnspecWaste", category,
1764 AF_WASTE_MAX);
1765 }
1766
[email protected]12faa4c2012-11-06 04:44:181767 job = new Job(weak_ptr_factory_.GetWeakPtr(), key, info.priority(),
1768 request_net_log);
[email protected]8c98d002012-07-18 19:02:271769 job->Schedule();
[email protected]0f292de02012-02-01 22:28:201770
1771 // Check for queue overflow.
1772 if (dispatcher_.num_queued_jobs() > max_queued_jobs_) {
1773 Job* evicted = static_cast<Job*>(dispatcher_.EvictOldestLowest());
1774 DCHECK(evicted);
[email protected]16ee26d2012-03-08 03:34:351775 evicted->OnEvicted(); // Deletes |evicted|.
[email protected]0f292de02012-02-01 22:28:201776 if (evicted == job) {
[email protected]0f292de02012-02-01 22:28:201777 rv = ERR_HOST_RESOLVER_QUEUE_TOO_LARGE;
[email protected]b3601bc22012-02-21 21:23:201778 LogFinishRequest(source_net_log, request_net_log, info, rv);
[email protected]0f292de02012-02-01 22:28:201779 return rv;
1780 }
[email protected]0f292de02012-02-01 22:28:201781 }
[email protected]0f292de02012-02-01 22:28:201782 jobs_.insert(jobit, std::make_pair(key, job));
1783 } else {
1784 job = jobit->second;
1785 }
1786
1787 // Can't complete synchronously. Create and attach request.
[email protected]b3601bc22012-02-21 21:23:201788 scoped_ptr<Request> req(new Request(source_net_log,
1789 request_net_log,
1790 info,
1791 callback,
1792 addresses));
[email protected]b59ff372009-07-15 22:04:321793 if (out_req)
[email protected]b3601bc22012-02-21 21:23:201794 *out_req = reinterpret_cast<RequestHandle>(req.get());
[email protected]b59ff372009-07-15 22:04:321795
[email protected]b3601bc22012-02-21 21:23:201796 job->AddRequest(req.Pass());
[email protected]0f292de02012-02-01 22:28:201797 // Completion happens during Job::CompleteRequests().
[email protected]b59ff372009-07-15 22:04:321798 return ERR_IO_PENDING;
1799}
1800
[email protected]287d7c22011-11-15 17:34:251801int HostResolverImpl::ResolveHelper(const Key& key,
[email protected]95a214c2011-08-04 21:50:401802 const RequestInfo& info,
1803 AddressList* addresses,
[email protected]20cd5332011-10-12 22:38:001804 const BoundNetLog& request_net_log) {
[email protected]95a214c2011-08-04 21:50:401805 // The result of |getaddrinfo| for empty hosts is inconsistent across systems.
1806 // On Windows it gives the default interface's address, whereas on Linux it
1807 // gives an error. We will make it fail on all platforms for consistency.
1808 if (info.hostname().empty() || info.hostname().size() > kMaxHostLength)
1809 return ERR_NAME_NOT_RESOLVED;
1810
1811 int net_error = ERR_UNEXPECTED;
1812 if (ResolveAsIP(key, info, &net_error, addresses))
1813 return net_error;
[email protected]78eac2a2012-03-14 19:09:271814 if (ServeFromCache(key, info, &net_error, addresses)) {
[email protected]4da911f2012-06-14 19:45:201815 request_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_CACHE_HIT);
[email protected]78eac2a2012-03-14 19:09:271816 return net_error;
1817 }
1818 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
1819 // http://crbug.com/117655
1820 if (ServeFromHosts(key, info, addresses)) {
[email protected]4da911f2012-06-14 19:45:201821 request_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_HOSTS_HIT);
[email protected]78eac2a2012-03-14 19:09:271822 return OK;
1823 }
1824 return ERR_DNS_CACHE_MISS;
[email protected]95a214c2011-08-04 21:50:401825}
1826
1827int HostResolverImpl::ResolveFromCache(const RequestInfo& info,
1828 AddressList* addresses,
1829 const BoundNetLog& source_net_log) {
1830 DCHECK(CalledOnValidThread());
1831 DCHECK(addresses);
1832
[email protected]95a214c2011-08-04 21:50:401833 // Make a log item for the request.
1834 BoundNetLog request_net_log = BoundNetLog::Make(net_log_,
1835 NetLog::SOURCE_HOST_RESOLVER_IMPL_REQUEST);
1836
1837 // Update the net log and notify registered observers.
[email protected]0f292de02012-02-01 22:28:201838 LogStartRequest(source_net_log, request_net_log, info);
[email protected]95a214c2011-08-04 21:50:401839
[email protected]95a214c2011-08-04 21:50:401840 Key key = GetEffectiveKeyForRequest(info);
1841
[email protected]287d7c22011-11-15 17:34:251842 int rv = ResolveHelper(key, info, addresses, request_net_log);
[email protected]b3601bc22012-02-21 21:23:201843 LogFinishRequest(source_net_log, request_net_log, info, rv);
[email protected]95a214c2011-08-04 21:50:401844 return rv;
1845}
1846
[email protected]b59ff372009-07-15 22:04:321847void HostResolverImpl::CancelRequest(RequestHandle req_handle) {
[email protected]1ac6af92010-06-03 21:00:141848 DCHECK(CalledOnValidThread());
[email protected]b59ff372009-07-15 22:04:321849 Request* req = reinterpret_cast<Request*>(req_handle);
1850 DCHECK(req);
[email protected]0f292de02012-02-01 22:28:201851 Job* job = req->job();
1852 DCHECK(job);
[email protected]0f292de02012-02-01 22:28:201853 job->CancelRequest(req);
[email protected]b59ff372009-07-15 22:04:321854}
1855
[email protected]0f8f1b432010-03-16 19:06:031856void HostResolverImpl::SetDefaultAddressFamily(AddressFamily address_family) {
[email protected]1ac6af92010-06-03 21:00:141857 DCHECK(CalledOnValidThread());
[email protected]0f8f1b432010-03-16 19:06:031858 default_address_family_ = address_family;
[email protected]12faa4c2012-11-06 04:44:181859 ipv6_probe_monitoring_ = false;
[email protected]0f8f1b432010-03-16 19:06:031860}
1861
[email protected]f7d310e2010-10-07 16:25:111862AddressFamily HostResolverImpl::GetDefaultAddressFamily() const {
1863 return default_address_family_;
1864}
1865
[email protected]a78f4272011-10-21 19:16:331866void HostResolverImpl::ProbeIPv6Support() {
1867 DCHECK(CalledOnValidThread());
1868 DCHECK(!ipv6_probe_monitoring_);
1869 ipv6_probe_monitoring_ = true;
[email protected]12faa4c2012-11-06 04:44:181870 OnIPAddressChanged();
[email protected]ddb1e5a2010-12-13 20:10:451871}
1872
[email protected]a8883e452012-11-17 05:58:061873void HostResolverImpl::SetDnsClientEnabled(bool enabled) {
1874 DCHECK(CalledOnValidThread());
1875#if defined(ENABLE_BUILT_IN_DNS)
1876 if (enabled && !dns_client_) {
1877 SetDnsClient(DnsClient::CreateClient(net_log_));
1878 } else if (!enabled && dns_client_) {
1879 SetDnsClient(scoped_ptr<DnsClient>());
1880 }
1881#endif
1882}
1883
[email protected]489d1a82011-10-12 03:09:111884HostCache* HostResolverImpl::GetHostCache() {
1885 return cache_.get();
1886}
[email protected]95a214c2011-08-04 21:50:401887
[email protected]17e92032012-03-29 00:56:241888base::Value* HostResolverImpl::GetDnsConfigAsValue() const {
1889 // Check if async DNS is disabled.
1890 if (!dns_client_.get())
1891 return NULL;
1892
1893 // Check if async DNS is enabled, but we currently have no configuration
1894 // for it.
1895 const DnsConfig* dns_config = dns_client_->GetConfig();
1896 if (dns_config == NULL)
1897 return new DictionaryValue();
1898
1899 return dns_config->ToValue();
1900}
1901
[email protected]95a214c2011-08-04 21:50:401902bool HostResolverImpl::ResolveAsIP(const Key& key,
1903 const RequestInfo& info,
1904 int* net_error,
1905 AddressList* addresses) {
1906 DCHECK(addresses);
1907 DCHECK(net_error);
1908 IPAddressNumber ip_number;
1909 if (!ParseIPLiteralToNumber(key.hostname, &ip_number))
1910 return false;
1911
1912 DCHECK_EQ(key.host_resolver_flags &
1913 ~(HOST_RESOLVER_CANONNAME | HOST_RESOLVER_LOOPBACK_ONLY |
1914 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6),
1915 0) << " Unhandled flag";
[email protected]0f292de02012-02-01 22:28:201916 bool ipv6_disabled = (default_address_family_ == ADDRESS_FAMILY_IPV4) &&
1917 !ipv6_probe_monitoring_;
[email protected]95a214c2011-08-04 21:50:401918 *net_error = OK;
[email protected]0f292de02012-02-01 22:28:201919 if ((ip_number.size() == kIPv6AddressSize) && ipv6_disabled) {
[email protected]95a214c2011-08-04 21:50:401920 *net_error = ERR_NAME_NOT_RESOLVED;
1921 } else {
[email protected]7054e78f2012-05-07 21:44:561922 *addresses = AddressList::CreateFromIPAddress(ip_number, info.port());
1923 if (key.host_resolver_flags & HOST_RESOLVER_CANONNAME)
1924 addresses->SetDefaultCanonicalName();
[email protected]95a214c2011-08-04 21:50:401925 }
1926 return true;
1927}
1928
1929bool HostResolverImpl::ServeFromCache(const Key& key,
1930 const RequestInfo& info,
[email protected]95a214c2011-08-04 21:50:401931 int* net_error,
1932 AddressList* addresses) {
1933 DCHECK(addresses);
1934 DCHECK(net_error);
1935 if (!info.allow_cached_response() || !cache_.get())
1936 return false;
1937
[email protected]407a30ab2012-08-15 17:16:101938 const HostCache::Entry* cache_entry = cache_->Lookup(
1939 key, base::TimeTicks::Now());
[email protected]95a214c2011-08-04 21:50:401940 if (!cache_entry)
1941 return false;
1942
[email protected]95a214c2011-08-04 21:50:401943 *net_error = cache_entry->error;
[email protected]7054e78f2012-05-07 21:44:561944 if (*net_error == OK) {
[email protected]1339a2a22012-10-17 08:39:431945 if (cache_entry->has_ttl())
1946 RecordTTL(cache_entry->ttl);
[email protected]895123222012-10-25 15:21:171947 *addresses = EnsurePortOnAddressList(cache_entry->addrlist, info.port());
[email protected]7054e78f2012-05-07 21:44:561948 }
[email protected]95a214c2011-08-04 21:50:401949 return true;
1950}
1951
[email protected]78eac2a2012-03-14 19:09:271952bool HostResolverImpl::ServeFromHosts(const Key& key,
1953 const RequestInfo& info,
1954 AddressList* addresses) {
1955 DCHECK(addresses);
1956 if (!HaveDnsConfig())
1957 return false;
1958
[email protected]cb507622012-03-23 16:17:061959 // HOSTS lookups are case-insensitive.
1960 std::string hostname = StringToLowerASCII(key.hostname);
1961
[email protected]78eac2a2012-03-14 19:09:271962 // If |address_family| is ADDRESS_FAMILY_UNSPECIFIED other implementations
1963 // (glibc and c-ares) return the first matching line. We have more
1964 // flexibility, but lose implicit ordering.
1965 // TODO(szym) http://crbug.com/117850
1966 const DnsHosts& hosts = dns_client_->GetConfig()->hosts;
1967 DnsHosts::const_iterator it = hosts.find(
[email protected]cb507622012-03-23 16:17:061968 DnsHostsKey(hostname,
[email protected]78eac2a2012-03-14 19:09:271969 key.address_family == ADDRESS_FAMILY_UNSPECIFIED ?
1970 ADDRESS_FAMILY_IPV4 : key.address_family));
1971
1972 if (it == hosts.end()) {
1973 if (key.address_family != ADDRESS_FAMILY_UNSPECIFIED)
1974 return false;
1975
[email protected]cb507622012-03-23 16:17:061976 it = hosts.find(DnsHostsKey(hostname, ADDRESS_FAMILY_IPV6));
[email protected]78eac2a2012-03-14 19:09:271977 if (it == hosts.end())
1978 return false;
1979 }
1980
1981 *addresses = AddressList::CreateFromIPAddress(it->second, info.port());
1982 return true;
1983}
1984
[email protected]16ee26d2012-03-08 03:34:351985void HostResolverImpl::CacheResult(const Key& key,
[email protected]1339a2a22012-10-17 08:39:431986 const HostCache::Entry& entry,
[email protected]16ee26d2012-03-08 03:34:351987 base::TimeDelta ttl) {
1988 if (cache_.get())
[email protected]1339a2a22012-10-17 08:39:431989 cache_->Set(key, entry, base::TimeTicks::Now(), ttl);
[email protected]ef4c40c2010-09-01 14:42:031990}
1991
[email protected]0f292de02012-02-01 22:28:201992void HostResolverImpl::RemoveJob(Job* job) {
1993 DCHECK(job);
[email protected]16ee26d2012-03-08 03:34:351994 JobMap::iterator it = jobs_.find(job->key());
1995 if (it != jobs_.end() && it->second == job)
1996 jobs_.erase(it);
[email protected]b59ff372009-07-15 22:04:321997}
1998
[email protected]0f8f1b432010-03-16 19:06:031999void HostResolverImpl::IPv6ProbeSetDefaultAddressFamily(
2000 AddressFamily address_family) {
2001 DCHECK(address_family == ADDRESS_FAMILY_UNSPECIFIED ||
2002 address_family == ADDRESS_FAMILY_IPV4);
[email protected]12faa4c2012-11-06 04:44:182003 if (!ipv6_probe_monitoring_)
2004 return;
[email protected]f092e64b2010-03-17 00:39:182005 if (default_address_family_ != address_family) {
[email protected]b30a3f52010-10-16 01:05:462006 VLOG(1) << "IPv6Probe forced AddressFamily setting to "
2007 << ((address_family == ADDRESS_FAMILY_UNSPECIFIED) ?
2008 "ADDRESS_FAMILY_UNSPECIFIED" : "ADDRESS_FAMILY_IPV4");
[email protected]f092e64b2010-03-17 00:39:182009 }
[email protected]0f8f1b432010-03-16 19:06:032010 default_address_family_ = address_family;
[email protected]e95d3aca2010-01-11 22:47:432011}
2012
[email protected]9936a7862012-10-26 04:44:022013void HostResolverImpl::SetHaveOnlyLoopbackAddresses(bool result) {
2014 if (result) {
2015 additional_resolver_flags_ |= HOST_RESOLVER_LOOPBACK_ONLY;
2016 } else {
2017 additional_resolver_flags_ &= ~HOST_RESOLVER_LOOPBACK_ONLY;
2018 }
2019}
2020
[email protected]137af622010-02-05 02:14:352021HostResolverImpl::Key HostResolverImpl::GetEffectiveKeyForRequest(
2022 const RequestInfo& info) const {
[email protected]eaf3a3b2010-09-03 20:34:272023 HostResolverFlags effective_flags =
2024 info.host_resolver_flags() | additional_resolver_flags_;
[email protected]137af622010-02-05 02:14:352025 AddressFamily effective_address_family = info.address_family();
[email protected]eaf3a3b2010-09-03 20:34:272026 if (effective_address_family == ADDRESS_FAMILY_UNSPECIFIED &&
2027 default_address_family_ != ADDRESS_FAMILY_UNSPECIFIED) {
[email protected]137af622010-02-05 02:14:352028 effective_address_family = default_address_family_;
[email protected]eaf3a3b2010-09-03 20:34:272029 if (ipv6_probe_monitoring_)
2030 effective_flags |= HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
2031 }
2032 return Key(info.hostname(), effective_address_family, effective_flags);
[email protected]137af622010-02-05 02:14:352033}
2034
[email protected]35ddc282010-09-21 23:42:062035void HostResolverImpl::AbortAllInProgressJobs() {
[email protected]b3601bc22012-02-21 21:23:202036 // In Abort, a Request callback could spawn new Jobs with matching keys, so
2037 // first collect and remove all running jobs from |jobs_|.
[email protected]c143d892012-04-06 07:56:542038 ScopedVector<Job> jobs_to_abort;
[email protected]0f292de02012-02-01 22:28:202039 for (JobMap::iterator it = jobs_.begin(); it != jobs_.end(); ) {
2040 Job* job = it->second;
[email protected]0f292de02012-02-01 22:28:202041 if (job->is_running()) {
[email protected]b3601bc22012-02-21 21:23:202042 jobs_to_abort.push_back(job);
2043 jobs_.erase(it++);
[email protected]0f292de02012-02-01 22:28:202044 } else {
[email protected]b3601bc22012-02-21 21:23:202045 DCHECK(job->is_queued());
2046 ++it;
[email protected]0f292de02012-02-01 22:28:202047 }
[email protected]ef4c40c2010-09-01 14:42:032048 }
[email protected]b3601bc22012-02-21 21:23:202049
[email protected]57a48d32012-03-03 00:04:552050 // Check if no dispatcher slots leaked out.
2051 DCHECK_EQ(dispatcher_.num_running_jobs(), jobs_to_abort.size());
2052
2053 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072054 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]57a48d32012-03-03 00:04:552055
[email protected]16ee26d2012-03-08 03:34:352056 // Then Abort them.
[email protected]57a48d32012-03-03 00:04:552057 for (size_t i = 0; self && i < jobs_to_abort.size(); ++i) {
[email protected]57a48d32012-03-03 00:04:552058 jobs_to_abort[i]->Abort();
[email protected]c143d892012-04-06 07:56:542059 jobs_to_abort[i] = NULL;
[email protected]b3601bc22012-02-21 21:23:202060 }
[email protected]ef4c40c2010-09-01 14:42:032061}
2062
[email protected]78eac2a2012-03-14 19:09:272063void HostResolverImpl::TryServingAllJobsFromHosts() {
2064 if (!HaveDnsConfig())
2065 return;
2066
2067 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2068 // http://crbug.com/117655
2069
2070 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072071 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]78eac2a2012-03-14 19:09:272072
2073 for (JobMap::iterator it = jobs_.begin(); self && it != jobs_.end(); ) {
2074 Job* job = it->second;
2075 ++it;
2076 // This could remove |job| from |jobs_|, but iterator will remain valid.
2077 job->ServeFromHosts();
2078 }
2079}
2080
[email protected]be1a48b2011-01-20 00:12:132081void HostResolverImpl::OnIPAddressChanged() {
[email protected]12faa4c2012-11-06 04:44:182082 // Abandon all ProbeJobs.
2083 probe_weak_ptr_factory_.InvalidateWeakPtrs();
[email protected]be1a48b2011-01-20 00:12:132084 if (cache_.get())
2085 cache_->clear();
[email protected]12faa4c2012-11-06 04:44:182086 if (ipv6_probe_monitoring_)
2087 new IPv6ProbeJob(probe_weak_ptr_factory_.GetWeakPtr(), net_log_);
[email protected]23f771162011-06-02 18:37:512088#if defined(OS_POSIX) && !defined(OS_MACOSX)
[email protected]12faa4c2012-11-06 04:44:182089 new LoopbackProbeJob(probe_weak_ptr_factory_.GetWeakPtr());
[email protected]be1a48b2011-01-20 00:12:132090#endif
2091 AbortAllInProgressJobs();
2092 // |this| may be deleted inside AbortAllInProgressJobs().
2093}
2094
[email protected]bb0e34542012-08-31 19:52:402095void HostResolverImpl::OnDNSChanged() {
2096 DnsConfig dns_config;
2097 NetworkChangeNotifier::GetDnsConfig(&dns_config);
[email protected]b4481b222012-03-16 17:13:112098 if (net_log_) {
2099 net_log_->AddGlobalEntry(
2100 NetLog::TYPE_DNS_CONFIG_CHANGED,
[email protected]cd565142012-06-12 16:21:452101 base::Bind(&NetLogDnsConfigCallback, &dns_config));
[email protected]b4481b222012-03-16 17:13:112102 }
2103
[email protected]01b3b9d2012-08-13 16:18:142104 // TODO(szym): Remove once http://crbug.com/137914 is resolved.
[email protected]d7b9a2b2012-05-31 22:31:192105 received_dns_config_ = dns_config.IsValid();
[email protected]78eac2a2012-03-14 19:09:272106
[email protected]a8883e452012-11-17 05:58:062107 num_dns_failures_ = 0;
2108
[email protected]01b3b9d2012-08-13 16:18:142109 // We want a new DnsSession in place, before we Abort running Jobs, so that
2110 // the newly started jobs use the new config.
[email protected]f0f602bd2012-11-15 18:01:022111 if (dns_client_.get()) {
[email protected]d7b9a2b2012-05-31 22:31:192112 dns_client_->SetConfig(dns_config);
[email protected]a8883e452012-11-17 05:58:062113 if (dns_config.IsValid())
[email protected]f0f602bd2012-11-15 18:01:022114 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
[email protected]f0f602bd2012-11-15 18:01:022115 }
[email protected]01b3b9d2012-08-13 16:18:142116
2117 // If the DNS server has changed, existing cached info could be wrong so we
2118 // have to drop our internal cache :( Note that OS level DNS caches, such
2119 // as NSCD's cache should be dropped automatically by the OS when
2120 // resolv.conf changes so we don't need to do anything to clear that cache.
2121 if (cache_.get())
2122 cache_->clear();
2123
[email protected]f0f602bd2012-11-15 18:01:022124 // Life check to bail once |this| is deleted.
2125 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
2126
[email protected]01b3b9d2012-08-13 16:18:142127 // Existing jobs will have been sent to the original server so they need to
2128 // be aborted.
2129 AbortAllInProgressJobs();
2130
2131 // |this| may be deleted inside AbortAllInProgressJobs().
2132 if (self)
2133 TryServingAllJobsFromHosts();
[email protected]78eac2a2012-03-14 19:09:272134}
2135
2136bool HostResolverImpl::HaveDnsConfig() const {
2137 return (dns_client_.get() != NULL) && (dns_client_->GetConfig() != NULL);
[email protected]b3601bc22012-02-21 21:23:202138}
2139
[email protected]1ffdda82012-12-12 23:04:222140void HostResolverImpl::OnDnsTaskResolve(int net_error) {
[email protected]f0f602bd2012-11-15 18:01:022141 DCHECK(dns_client_);
[email protected]1ffdda82012-12-12 23:04:222142 if (net_error == OK) {
[email protected]f0f602bd2012-11-15 18:01:022143 num_dns_failures_ = 0;
2144 return;
2145 }
2146 ++num_dns_failures_;
2147 if (num_dns_failures_ < kMaximumDnsFailures)
2148 return;
2149 // Disable DnsClient until the next DNS change.
2150 for (JobMap::iterator it = jobs_.begin(); it != jobs_.end(); ++it)
2151 it->second->AbortDnsTask();
2152 dns_client_->SetConfig(DnsConfig());
2153 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", false);
[email protected]1ffdda82012-12-12 23:04:222154 UMA_HISTOGRAM_CUSTOM_ENUMERATION("AsyncDNS.DnsClientDisabledReason",
2155 std::abs(net_error),
2156 GetAllErrorCodesForUma());
[email protected]f0f602bd2012-11-15 18:01:022157}
2158
[email protected]a8883e452012-11-17 05:58:062159void HostResolverImpl::SetDnsClient(scoped_ptr<DnsClient> dns_client) {
2160 if (HaveDnsConfig()) {
2161 for (JobMap::iterator it = jobs_.begin(); it != jobs_.end(); ++it)
2162 it->second->AbortDnsTask();
2163 }
2164 dns_client_ = dns_client.Pass();
2165 if (!dns_client_ || dns_client_->GetConfig() ||
2166 num_dns_failures_ >= kMaximumDnsFailures) {
2167 return;
2168 }
2169 DnsConfig dns_config;
2170 NetworkChangeNotifier::GetDnsConfig(&dns_config);
2171 dns_client_->SetConfig(dns_config);
2172 num_dns_failures_ = 0;
2173 if (dns_config.IsValid())
2174 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
2175}
2176
[email protected]b59ff372009-07-15 22:04:322177} // namespace net