blob: 0a3e8640fbeb12727e6816d35aaaa0f86b7162eb [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]02cd6982013-01-10 20:12:511019 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]b3601bc22012-02-21 21:23:201020 // Run |callback_| last since the owning Job will then delete this DnsTask.
[email protected]0adcb2b2012-08-15 21:30:461021 if (net_error != OK) {
[email protected]02cd6982013-01-10 20:12:511022 DNS_HISTOGRAM("AsyncDNS.TransactionFailure", duration);
[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);
[email protected]02cd6982013-01-10 20:12:511028 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess", duration);
1029 switch (transaction->GetType()) {
1030 case dns_protocol::kTypeA:
1031 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess_A", duration);
1032 break;
1033 case dns_protocol::kTypeAAAA:
1034 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess_AAAA", duration);
1035 break;
1036 }
[email protected]0adcb2b2012-08-15 21:30:461037 AddressList addr_list;
1038 base::TimeDelta ttl;
1039 DnsResponse::Result result = response->ParseToAddressList(&addr_list, &ttl);
1040 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ParseToAddressList",
1041 result,
1042 DnsResponse::DNS_PARSE_RESULT_MAX);
1043 if (result != DnsResponse::DNS_PARSE_OK) {
1044 // Fail even if the other query succeeds.
1045 OnFailure(ERR_DNS_MALFORMED_RESPONSE, result);
1046 return;
1047 }
1048
1049 bool needs_sort = false;
1050 if (first_query) {
1051 DCHECK(client_->GetConfig()) <<
1052 "Transaction should have been aborted when config changed!";
1053 if (family_ == ADDRESS_FAMILY_IPV6) {
1054 needs_sort = (addr_list.size() > 1);
1055 } else if (family_ == ADDRESS_FAMILY_UNSPECIFIED) {
1056 first_addr_list_ = addr_list;
1057 first_ttl_ = ttl;
1058 // Use fully-qualified domain name to avoid search.
1059 transaction_ = client_->GetTransactionFactory()->CreateTransaction(
1060 response->GetDottedName() + ".",
1061 dns_protocol::kTypeAAAA,
1062 base::Bind(&DnsTask::OnTransactionComplete, base::Unretained(this),
1063 false /* first_query */, base::TimeTicks::Now()),
1064 net_log_);
1065 net_error = transaction_->Start();
1066 if (net_error != ERR_IO_PENDING)
1067 OnFailure(net_error, DnsResponse::DNS_PARSE_OK);
1068 return;
1069 }
1070 } else {
1071 DCHECK_EQ(ADDRESS_FAMILY_UNSPECIFIED, family_);
1072 bool has_ipv6_addresses = !addr_list.empty();
1073 if (!first_addr_list_.empty()) {
1074 ttl = std::min(ttl, first_ttl_);
1075 // Place IPv4 addresses after IPv6.
1076 addr_list.insert(addr_list.end(), first_addr_list_.begin(),
1077 first_addr_list_.end());
1078 }
1079 needs_sort = (has_ipv6_addresses && addr_list.size() > 1);
1080 }
1081
1082 if (addr_list.empty()) {
1083 // TODO(szym): Don't fallback to ProcTask in this case.
1084 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
1085 return;
1086 }
1087
1088 if (needs_sort) {
1089 // Sort could complete synchronously.
1090 client_->GetAddressSorter()->Sort(
1091 addr_list,
[email protected]4589a3a2012-09-20 20:57:071092 base::Bind(&DnsTask::OnSortComplete,
1093 AsWeakPtr(),
[email protected]0adcb2b2012-08-15 21:30:461094 base::TimeTicks::Now(),
1095 ttl));
1096 } else {
1097 OnSuccess(addr_list, ttl);
1098 }
1099 }
1100
1101 void OnSortComplete(base::TimeTicks start_time,
1102 base::TimeDelta ttl,
1103 bool success,
1104 const AddressList& addr_list) {
1105 if (!success) {
1106 DNS_HISTOGRAM("AsyncDNS.SortFailure",
1107 base::TimeTicks::Now() - start_time);
1108 OnFailure(ERR_DNS_SORT_ERROR, DnsResponse::DNS_PARSE_OK);
1109 return;
1110 }
1111
1112 DNS_HISTOGRAM("AsyncDNS.SortSuccess",
1113 base::TimeTicks::Now() - start_time);
1114
1115 // AddressSorter prunes unusable destinations.
1116 if (addr_list.empty()) {
1117 LOG(WARNING) << "Address list empty after RFC3484 sort";
1118 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
1119 return;
1120 }
1121
1122 OnSuccess(addr_list, ttl);
1123 }
1124
1125 void OnFailure(int net_error, DnsResponse::Result result) {
1126 DCHECK_NE(OK, net_error);
[email protected]cd565142012-06-12 16:21:451127 net_log_.EndEvent(
1128 NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK,
1129 base::Bind(&NetLogDnsTaskFailedCallback, net_error, result));
[email protected]b3601bc22012-02-21 21:23:201130 callback_.Run(net_error, AddressList(), base::TimeDelta());
1131 }
1132
[email protected]0adcb2b2012-08-15 21:30:461133 void OnSuccess(const AddressList& addr_list, base::TimeDelta ttl) {
1134 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK,
1135 addr_list.CreateNetLogCallback());
1136 callback_.Run(OK, addr_list, ttl);
1137 }
1138
1139 DnsClient* client_;
1140 AddressFamily family_;
[email protected]b3601bc22012-02-21 21:23:201141 // The listener to the results of this DnsTask.
1142 Callback callback_;
[email protected]b3601bc22012-02-21 21:23:201143 const BoundNetLog net_log_;
1144
1145 scoped_ptr<DnsTransaction> transaction_;
[email protected]0adcb2b2012-08-15 21:30:461146
1147 // Results from the first transaction. Used only if |family_| is unspecified.
1148 AddressList first_addr_list_;
1149 base::TimeDelta first_ttl_;
1150
1151 DISALLOW_COPY_AND_ASSIGN(DnsTask);
[email protected]b3601bc22012-02-21 21:23:201152};
1153
1154//-----------------------------------------------------------------------------
1155
[email protected]0f292de02012-02-01 22:28:201156// Aggregates all Requests for the same Key. Dispatched via PriorityDispatch.
[email protected]0f292de02012-02-01 22:28:201157class HostResolverImpl::Job : public PrioritizedDispatcher::Job {
[email protected]68ad3ee2010-01-30 03:45:391158 public:
[email protected]0f292de02012-02-01 22:28:201159 // Creates new job for |key| where |request_net_log| is bound to the
[email protected]16ee26d2012-03-08 03:34:351160 // request that spawned it.
[email protected]12faa4c2012-11-06 04:44:181161 Job(const base::WeakPtr<HostResolverImpl>& resolver,
[email protected]0f292de02012-02-01 22:28:201162 const Key& key,
[email protected]8c98d002012-07-18 19:02:271163 RequestPriority priority,
[email protected]16ee26d2012-03-08 03:34:351164 const BoundNetLog& request_net_log)
[email protected]12faa4c2012-11-06 04:44:181165 : resolver_(resolver),
[email protected]0f292de02012-02-01 22:28:201166 key_(key),
[email protected]8c98d002012-07-18 19:02:271167 priority_tracker_(priority),
[email protected]0f292de02012-02-01 22:28:201168 had_non_speculative_request_(false),
[email protected]51b9a6b2012-06-25 21:50:291169 had_dns_config_(false),
[email protected]1d932852012-06-19 19:40:331170 dns_task_error_(OK),
[email protected]51b9a6b2012-06-25 21:50:291171 creation_time_(base::TimeTicks::Now()),
1172 priority_change_time_(creation_time_),
[email protected]0f292de02012-02-01 22:28:201173 net_log_(BoundNetLog::Make(request_net_log.net_log(),
[email protected]b3601bc22012-02-21 21:23:201174 NetLog::SOURCE_HOST_RESOLVER_IMPL_JOB)) {
[email protected]4da911f2012-06-14 19:45:201175 request_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_CREATE_JOB);
[email protected]0f292de02012-02-01 22:28:201176
1177 net_log_.BeginEvent(
1178 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
[email protected]cd565142012-06-12 16:21:451179 base::Bind(&NetLogJobCreationCallback,
1180 request_net_log.source(),
1181 &key_.hostname));
[email protected]68ad3ee2010-01-30 03:45:391182 }
1183
[email protected]0f292de02012-02-01 22:28:201184 virtual ~Job() {
[email protected]b3601bc22012-02-21 21:23:201185 if (is_running()) {
1186 // |resolver_| was destroyed with this Job still in flight.
1187 // Clean-up, record in the log, but don't run any callbacks.
1188 if (is_proc_running()) {
[email protected]0f292de02012-02-01 22:28:201189 proc_task_->Cancel();
1190 proc_task_ = NULL;
[email protected]0f292de02012-02-01 22:28:201191 }
[email protected]16ee26d2012-03-08 03:34:351192 // Clean up now for nice NetLog.
1193 dns_task_.reset(NULL);
[email protected]b3601bc22012-02-21 21:23:201194 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
1195 ERR_ABORTED);
1196 } else if (is_queued()) {
[email protected]57a48d32012-03-03 00:04:551197 // |resolver_| was destroyed without running this Job.
[email protected]16ee26d2012-03-08 03:34:351198 // TODO(szym): is there any benefit in having this distinction?
[email protected]4da911f2012-06-14 19:45:201199 net_log_.AddEvent(NetLog::TYPE_CANCELLED);
1200 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB);
[email protected]68ad3ee2010-01-30 03:45:391201 }
[email protected]b3601bc22012-02-21 21:23:201202 // else CompleteRequests logged EndEvent.
[email protected]68ad3ee2010-01-30 03:45:391203
[email protected]b3601bc22012-02-21 21:23:201204 // Log any remaining Requests as cancelled.
1205 for (RequestsList::const_iterator it = requests_.begin();
1206 it != requests_.end(); ++it) {
1207 Request* req = *it;
1208 if (req->was_canceled())
1209 continue;
1210 DCHECK_EQ(this, req->job());
1211 LogCancelRequest(req->source_net_log(), req->request_net_log(),
1212 req->info());
1213 }
[email protected]68ad3ee2010-01-30 03:45:391214 }
1215
[email protected]16ee26d2012-03-08 03:34:351216 // Add this job to the dispatcher.
[email protected]8c98d002012-07-18 19:02:271217 void Schedule() {
1218 handle_ = resolver_->dispatcher_.Add(this, priority());
[email protected]16ee26d2012-03-08 03:34:351219 }
1220
[email protected]b3601bc22012-02-21 21:23:201221 void AddRequest(scoped_ptr<Request> req) {
[email protected]0f292de02012-02-01 22:28:201222 DCHECK_EQ(key_.hostname, req->info().hostname());
1223
1224 req->set_job(this);
[email protected]0f292de02012-02-01 22:28:201225 priority_tracker_.Add(req->info().priority());
1226
1227 req->request_net_log().AddEvent(
1228 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_ATTACH,
[email protected]cd565142012-06-12 16:21:451229 net_log_.source().ToEventParametersCallback());
[email protected]0f292de02012-02-01 22:28:201230
1231 net_log_.AddEvent(
1232 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_REQUEST_ATTACH,
[email protected]cd565142012-06-12 16:21:451233 base::Bind(&NetLogJobAttachCallback,
1234 req->request_net_log().source(),
1235 priority()));
[email protected]0f292de02012-02-01 22:28:201236
1237 // TODO(szym): Check if this is still needed.
1238 if (!req->info().is_speculative()) {
1239 had_non_speculative_request_ = true;
1240 if (proc_task_)
1241 proc_task_->set_had_non_speculative_request();
[email protected]68ad3ee2010-01-30 03:45:391242 }
[email protected]b3601bc22012-02-21 21:23:201243
1244 requests_.push_back(req.release());
1245
[email protected]51b9a6b2012-06-25 21:50:291246 UpdatePriority();
[email protected]68ad3ee2010-01-30 03:45:391247 }
1248
[email protected]16ee26d2012-03-08 03:34:351249 // Marks |req| as cancelled. If it was the last active Request, also finishes
[email protected]0adcb2b2012-08-15 21:30:461250 // this Job, marking it as cancelled, and deletes it.
[email protected]0f292de02012-02-01 22:28:201251 void CancelRequest(Request* req) {
1252 DCHECK_EQ(key_.hostname, req->info().hostname());
1253 DCHECK(!req->was_canceled());
[email protected]16ee26d2012-03-08 03:34:351254
[email protected]0f292de02012-02-01 22:28:201255 // Don't remove it from |requests_| just mark it canceled.
1256 req->MarkAsCanceled();
1257 LogCancelRequest(req->source_net_log(), req->request_net_log(),
1258 req->info());
[email protected]16ee26d2012-03-08 03:34:351259
[email protected]0f292de02012-02-01 22:28:201260 priority_tracker_.Remove(req->info().priority());
1261 net_log_.AddEvent(
1262 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_REQUEST_DETACH,
[email protected]cd565142012-06-12 16:21:451263 base::Bind(&NetLogJobAttachCallback,
1264 req->request_net_log().source(),
1265 priority()));
[email protected]b3601bc22012-02-21 21:23:201266
[email protected]16ee26d2012-03-08 03:34:351267 if (num_active_requests() > 0) {
[email protected]51b9a6b2012-06-25 21:50:291268 UpdatePriority();
[email protected]16ee26d2012-03-08 03:34:351269 } else {
1270 // If we were called from a Request's callback within CompleteRequests,
1271 // that Request could not have been cancelled, so num_active_requests()
1272 // could not be 0. Therefore, we are not in CompleteRequests().
[email protected]1339a2a22012-10-17 08:39:431273 CompleteRequestsWithError(OK /* cancelled */);
[email protected]b3601bc22012-02-21 21:23:201274 }
[email protected]68ad3ee2010-01-30 03:45:391275 }
1276
[email protected]7af985a2012-12-14 22:40:421277 // Called from AbortAllInProgressJobs. Completes all requests and destroys
1278 // the job. This currently assumes the abort is due to a network change.
[email protected]0f292de02012-02-01 22:28:201279 void Abort() {
[email protected]0f292de02012-02-01 22:28:201280 DCHECK(is_running());
[email protected]7af985a2012-12-14 22:40:421281 CompleteRequestsWithError(ERR_NETWORK_CHANGED);
[email protected]b3601bc22012-02-21 21:23:201282 }
1283
[email protected]f0f602bd2012-11-15 18:01:021284 // If DnsTask present, abort it and fall back to ProcTask.
1285 void AbortDnsTask() {
1286 if (dns_task_) {
1287 dns_task_.reset();
1288 dns_task_error_ = OK;
1289 StartProcTask();
1290 }
1291 }
1292
[email protected]16ee26d2012-03-08 03:34:351293 // Called by HostResolverImpl when this job is evicted due to queue overflow.
1294 // Completes all requests and destroys the job.
1295 void OnEvicted() {
1296 DCHECK(!is_running());
1297 DCHECK(is_queued());
1298 handle_.Reset();
1299
[email protected]4da911f2012-06-14 19:45:201300 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_EVICTED);
[email protected]16ee26d2012-03-08 03:34:351301
1302 // This signals to CompleteRequests that this job never ran.
[email protected]1339a2a22012-10-17 08:39:431303 CompleteRequestsWithError(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
[email protected]16ee26d2012-03-08 03:34:351304 }
1305
[email protected]78eac2a2012-03-14 19:09:271306 // Attempts to serve the job from HOSTS. Returns true if succeeded and
1307 // this Job was destroyed.
1308 bool ServeFromHosts() {
1309 DCHECK_GT(num_active_requests(), 0u);
1310 AddressList addr_list;
1311 if (resolver_->ServeFromHosts(key(),
[email protected]3cb676a12012-06-30 15:46:031312 requests_.front()->info(),
[email protected]78eac2a2012-03-14 19:09:271313 &addr_list)) {
1314 // This will destroy the Job.
[email protected]895123222012-10-25 15:21:171315 CompleteRequests(
1316 HostCache::Entry(OK, MakeAddressListForRequest(addr_list)),
1317 base::TimeDelta());
[email protected]78eac2a2012-03-14 19:09:271318 return true;
1319 }
1320 return false;
1321 }
1322
[email protected]b4481b222012-03-16 17:13:111323 const Key key() const {
1324 return key_;
1325 }
1326
1327 bool is_queued() const {
1328 return !handle_.is_null();
1329 }
1330
1331 bool is_running() const {
1332 return is_dns_running() || is_proc_running();
1333 }
1334
[email protected]16ee26d2012-03-08 03:34:351335 private:
[email protected]51b9a6b2012-06-25 21:50:291336 void UpdatePriority() {
1337 if (is_queued()) {
1338 if (priority() != static_cast<RequestPriority>(handle_.priority()))
1339 priority_change_time_ = base::TimeTicks::Now();
1340 handle_ = resolver_->dispatcher_.ChangePriority(handle_, priority());
1341 }
1342 }
1343
[email protected]895123222012-10-25 15:21:171344 AddressList MakeAddressListForRequest(const AddressList& list) const {
1345 if (requests_.empty())
1346 return list;
1347 return AddressList::CopyWithPort(list, requests_.front()->info().port());
1348 }
1349
[email protected]16ee26d2012-03-08 03:34:351350 // PriorityDispatch::Job:
[email protected]0f292de02012-02-01 22:28:201351 virtual void Start() OVERRIDE {
1352 DCHECK(!is_running());
[email protected]b3601bc22012-02-21 21:23:201353 handle_.Reset();
[email protected]0f292de02012-02-01 22:28:201354
[email protected]4da911f2012-06-14 19:45:201355 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_STARTED);
[email protected]0f292de02012-02-01 22:28:201356
[email protected]51b9a6b2012-06-25 21:50:291357 had_dns_config_ = resolver_->HaveDnsConfig();
1358
1359 base::TimeTicks now = base::TimeTicks::Now();
1360 base::TimeDelta queue_time = now - creation_time_;
1361 base::TimeDelta queue_time_after_change = now - priority_change_time_;
1362
1363 if (had_dns_config_) {
1364 DNS_HISTOGRAM_BY_PRIORITY("AsyncDNS.JobQueueTime", priority(),
1365 queue_time);
1366 DNS_HISTOGRAM_BY_PRIORITY("AsyncDNS.JobQueueTimeAfterChange", priority(),
1367 queue_time_after_change);
1368 } else {
1369 DNS_HISTOGRAM_BY_PRIORITY("DNS.JobQueueTime", priority(), queue_time);
1370 DNS_HISTOGRAM_BY_PRIORITY("DNS.JobQueueTimeAfterChange", priority(),
1371 queue_time_after_change);
1372 }
1373
[email protected]1d932852012-06-19 19:40:331374 // Caution: Job::Start must not complete synchronously.
[email protected]51b9a6b2012-06-25 21:50:291375 if (had_dns_config_ && !ResemblesMulticastDNSName(key_.hostname)) {
[email protected]b3601bc22012-02-21 21:23:201376 StartDnsTask();
1377 } else {
1378 StartProcTask();
1379 }
1380 }
1381
[email protected]b3601bc22012-02-21 21:23:201382 // TODO(szym): Since DnsTransaction does not consume threads, we can increase
1383 // the limits on |dispatcher_|. But in order to keep the number of WorkerPool
1384 // threads low, we will need to use an "inner" PrioritizedDispatcher with
1385 // tighter limits.
1386 void StartProcTask() {
[email protected]16ee26d2012-03-08 03:34:351387 DCHECK(!is_dns_running());
[email protected]0f292de02012-02-01 22:28:201388 proc_task_ = new ProcTask(
1389 key_,
1390 resolver_->proc_params_,
[email protected]e3bd4822012-10-23 18:01:371391 base::Bind(&Job::OnProcTaskComplete, base::Unretained(this),
1392 base::TimeTicks::Now()),
[email protected]0f292de02012-02-01 22:28:201393 net_log_);
1394
1395 if (had_non_speculative_request_)
1396 proc_task_->set_had_non_speculative_request();
1397 // Start() could be called from within Resolve(), hence it must NOT directly
1398 // call OnProcTaskComplete, for example, on synchronous failure.
1399 proc_task_->Start();
[email protected]68ad3ee2010-01-30 03:45:391400 }
1401
[email protected]0f292de02012-02-01 22:28:201402 // Called by ProcTask when it completes.
[email protected]e3bd4822012-10-23 18:01:371403 void OnProcTaskComplete(base::TimeTicks start_time,
1404 int net_error,
1405 const AddressList& addr_list) {
[email protected]b3601bc22012-02-21 21:23:201406 DCHECK(is_proc_running());
[email protected]68ad3ee2010-01-30 03:45:391407
[email protected]1d932852012-06-19 19:40:331408 if (dns_task_error_ != OK) {
[email protected]e3bd4822012-10-23 18:01:371409 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]1def74c2012-03-22 20:07:001410 if (net_error == OK) {
[email protected]e3bd4822012-10-23 18:01:371411 DNS_HISTOGRAM("AsyncDNS.FallbackSuccess", duration);
[email protected]1d932852012-06-19 19:40:331412 if ((dns_task_error_ == ERR_NAME_NOT_RESOLVED) &&
1413 ResemblesNetBIOSName(key_.hostname)) {
1414 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_SUSPECT_NETBIOS);
1415 } else {
1416 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_PROC_SUCCESS);
1417 }
1418 UMA_HISTOGRAM_CUSTOM_ENUMERATION("AsyncDNS.ResolveError",
1419 std::abs(dns_task_error_),
1420 GetAllErrorCodesForUma());
[email protected]1ffdda82012-12-12 23:04:221421 resolver_->OnDnsTaskResolve(dns_task_error_);
[email protected]1def74c2012-03-22 20:07:001422 } else {
[email protected]e3bd4822012-10-23 18:01:371423 DNS_HISTOGRAM("AsyncDNS.FallbackFail", duration);
[email protected]1def74c2012-03-22 20:07:001424 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
1425 }
1426 }
1427
[email protected]1339a2a22012-10-17 08:39:431428 base::TimeDelta ttl =
1429 base::TimeDelta::FromSeconds(kNegativeCacheEntryTTLSeconds);
[email protected]b3601bc22012-02-21 21:23:201430 if (net_error == OK)
1431 ttl = base::TimeDelta::FromSeconds(kCacheEntryTTLSeconds);
[email protected]68ad3ee2010-01-30 03:45:391432
[email protected]895123222012-10-25 15:21:171433 // Don't store the |ttl| in cache since it's not obtained from the server.
1434 CompleteRequests(
1435 HostCache::Entry(net_error, MakeAddressListForRequest(addr_list)),
1436 ttl);
[email protected]b3601bc22012-02-21 21:23:201437 }
1438
1439 void StartDnsTask() {
[email protected]78eac2a2012-03-14 19:09:271440 DCHECK(resolver_->HaveDnsConfig());
[email protected]b3601bc22012-02-21 21:23:201441 dns_task_.reset(new DnsTask(
[email protected]0adcb2b2012-08-15 21:30:461442 resolver_->dns_client_.get(),
[email protected]b3601bc22012-02-21 21:23:201443 key_,
[email protected]e3bd4822012-10-23 18:01:371444 base::Bind(&Job::OnDnsTaskComplete, base::Unretained(this),
1445 base::TimeTicks::Now()),
[email protected]b3601bc22012-02-21 21:23:201446 net_log_));
1447
1448 int rv = dns_task_->Start();
1449 if (rv != ERR_IO_PENDING) {
1450 DCHECK_NE(OK, rv);
[email protected]51b9a6b2012-06-25 21:50:291451 dns_task_error_ = rv;
[email protected]b3601bc22012-02-21 21:23:201452 dns_task_.reset();
1453 StartProcTask();
1454 }
1455 }
1456
1457 // Called by DnsTask when it completes.
[email protected]e3bd4822012-10-23 18:01:371458 void OnDnsTaskComplete(base::TimeTicks start_time,
1459 int net_error,
[email protected]b3601bc22012-02-21 21:23:201460 const AddressList& addr_list,
1461 base::TimeDelta ttl) {
1462 DCHECK(is_dns_running());
[email protected]b3601bc22012-02-21 21:23:201463
[email protected]e3bd4822012-10-23 18:01:371464 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
[email protected]b3601bc22012-02-21 21:23:201465 if (net_error != OK) {
[email protected]e3bd4822012-10-23 18:01:371466 DNS_HISTOGRAM("AsyncDNS.ResolveFail", duration);
1467
[email protected]1d932852012-06-19 19:40:331468 dns_task_error_ = net_error;
[email protected]16ee26d2012-03-08 03:34:351469 dns_task_.reset();
[email protected]78eac2a2012-03-14 19:09:271470
1471 // TODO(szym): Run ServeFromHosts now if nsswitch.conf says so.
1472 // http://crbug.com/117655
1473
[email protected]b3601bc22012-02-21 21:23:201474 // TODO(szym): Some net errors indicate lack of connectivity. Starting
1475 // ProcTask in that case is a waste of time.
1476 StartProcTask();
1477 return;
1478 }
[email protected]e3bd4822012-10-23 18:01:371479 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess", duration);
[email protected]02cd6982013-01-10 20:12:511480 // Log DNS lookups based on |address_family|.
1481 switch(key_.address_family) {
1482 case ADDRESS_FAMILY_IPV4:
1483 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_IPV4", duration);
1484 break;
1485 case ADDRESS_FAMILY_IPV6:
1486 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_IPV6", duration);
1487 break;
1488 case ADDRESS_FAMILY_UNSPECIFIED:
1489 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_UNSPEC", duration);
1490 break;
1491 }
[email protected]b3601bc22012-02-21 21:23:201492
[email protected]1def74c2012-03-22 20:07:001493 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_DNS_SUCCESS);
[email protected]1339a2a22012-10-17 08:39:431494 RecordTTL(ttl);
[email protected]0adcb2b2012-08-15 21:30:461495
[email protected]1ffdda82012-12-12 23:04:221496 resolver_->OnDnsTaskResolve(OK);
[email protected]f0f602bd2012-11-15 18:01:021497
[email protected]895123222012-10-25 15:21:171498 base::TimeDelta bounded_ttl =
1499 std::max(ttl, base::TimeDelta::FromSeconds(kMinimumTTLSeconds));
1500
1501 CompleteRequests(
1502 HostCache::Entry(net_error, MakeAddressListForRequest(addr_list), ttl),
1503 bounded_ttl);
[email protected]b3601bc22012-02-21 21:23:201504 }
1505
[email protected]16ee26d2012-03-08 03:34:351506 // Performs Job's last rites. Completes all Requests. Deletes this.
[email protected]895123222012-10-25 15:21:171507 void CompleteRequests(const HostCache::Entry& entry,
1508 base::TimeDelta ttl) {
[email protected]b3601bc22012-02-21 21:23:201509 CHECK(resolver_);
[email protected]b3601bc22012-02-21 21:23:201510
[email protected]16ee26d2012-03-08 03:34:351511 // This job must be removed from resolver's |jobs_| now to make room for a
1512 // new job with the same key in case one of the OnComplete callbacks decides
1513 // to spawn one. Consequently, the job deletes itself when CompleteRequests
1514 // is done.
1515 scoped_ptr<Job> self_deleter(this);
1516
1517 resolver_->RemoveJob(this);
1518
[email protected]16ee26d2012-03-08 03:34:351519 if (is_running()) {
1520 DCHECK(!is_queued());
1521 if (is_proc_running()) {
1522 proc_task_->Cancel();
1523 proc_task_ = NULL;
1524 }
1525 dns_task_.reset();
1526
1527 // Signal dispatcher that a slot has opened.
1528 resolver_->dispatcher_.OnJobFinished();
1529 } else if (is_queued()) {
1530 resolver_->dispatcher_.Cancel(handle_);
1531 handle_.Reset();
1532 }
1533
1534 if (num_active_requests() == 0) {
[email protected]4da911f2012-06-14 19:45:201535 net_log_.AddEvent(NetLog::TYPE_CANCELLED);
[email protected]16ee26d2012-03-08 03:34:351536 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
1537 OK);
1538 return;
1539 }
[email protected]b3601bc22012-02-21 21:23:201540
1541 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
[email protected]895123222012-10-25 15:21:171542 entry.error);
[email protected]68ad3ee2010-01-30 03:45:391543
[email protected]78eac2a2012-03-14 19:09:271544 DCHECK(!requests_.empty());
1545
[email protected]895123222012-10-25 15:21:171546 if (entry.error == OK) {
[email protected]d7b9a2b2012-05-31 22:31:191547 // Record this histogram here, when we know the system has a valid DNS
1548 // configuration.
[email protected]539df6c2012-06-19 21:21:291549 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.HaveDnsConfig",
1550 resolver_->received_dns_config_);
[email protected]d7b9a2b2012-05-31 22:31:191551 }
[email protected]16ee26d2012-03-08 03:34:351552
[email protected]7af985a2012-12-14 22:40:421553 bool did_complete = (entry.error != ERR_NETWORK_CHANGED) &&
[email protected]895123222012-10-25 15:21:171554 (entry.error != ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
1555 if (did_complete)
[email protected]1339a2a22012-10-17 08:39:431556 resolver_->CacheResult(key_, entry, ttl);
[email protected]16ee26d2012-03-08 03:34:351557
[email protected]0f292de02012-02-01 22:28:201558 // Complete all of the requests that were attached to the job.
1559 for (RequestsList::const_iterator it = requests_.begin();
1560 it != requests_.end(); ++it) {
1561 Request* req = *it;
1562
1563 if (req->was_canceled())
1564 continue;
1565
1566 DCHECK_EQ(this, req->job());
1567 // Update the net log and notify registered observers.
1568 LogFinishRequest(req->source_net_log(), req->request_net_log(),
[email protected]895123222012-10-25 15:21:171569 req->info(), entry.error);
[email protected]51b9a6b2012-06-25 21:50:291570 if (did_complete) {
1571 // Record effective total time from creation to completion.
1572 RecordTotalTime(had_dns_config_, req->info().is_speculative(),
1573 base::TimeTicks::Now() - req->request_time());
1574 }
[email protected]895123222012-10-25 15:21:171575 req->OnComplete(entry.error, entry.addrlist);
[email protected]0f292de02012-02-01 22:28:201576
1577 // Check if the resolver was destroyed as a result of running the
1578 // callback. If it was, we could continue, but we choose to bail.
1579 if (!resolver_)
1580 return;
1581 }
1582 }
1583
[email protected]1339a2a22012-10-17 08:39:431584 // Convenience wrapper for CompleteRequests in case of failure.
1585 void CompleteRequestsWithError(int net_error) {
[email protected]895123222012-10-25 15:21:171586 CompleteRequests(HostCache::Entry(net_error, AddressList()),
1587 base::TimeDelta());
[email protected]1339a2a22012-10-17 08:39:431588 }
1589
[email protected]b4481b222012-03-16 17:13:111590 RequestPriority priority() const {
1591 return priority_tracker_.highest_priority();
1592 }
1593
1594 // Number of non-canceled requests in |requests_|.
1595 size_t num_active_requests() const {
1596 return priority_tracker_.total_count();
1597 }
1598
1599 bool is_dns_running() const {
1600 return dns_task_.get() != NULL;
1601 }
1602
1603 bool is_proc_running() const {
1604 return proc_task_.get() != NULL;
1605 }
1606
[email protected]0f292de02012-02-01 22:28:201607 base::WeakPtr<HostResolverImpl> resolver_;
1608
1609 Key key_;
1610
1611 // Tracks the highest priority across |requests_|.
1612 PriorityTracker priority_tracker_;
1613
1614 bool had_non_speculative_request_;
1615
[email protected]51b9a6b2012-06-25 21:50:291616 // Distinguishes measurements taken while DnsClient was fully configured.
1617 bool had_dns_config_;
1618
[email protected]1d932852012-06-19 19:40:331619 // Result of DnsTask.
1620 int dns_task_error_;
[email protected]1def74c2012-03-22 20:07:001621
[email protected]51b9a6b2012-06-25 21:50:291622 const base::TimeTicks creation_time_;
1623 base::TimeTicks priority_change_time_;
1624
[email protected]0f292de02012-02-01 22:28:201625 BoundNetLog net_log_;
1626
[email protected]b3601bc22012-02-21 21:23:201627 // Resolves the host using a HostResolverProc.
[email protected]0f292de02012-02-01 22:28:201628 scoped_refptr<ProcTask> proc_task_;
1629
[email protected]b3601bc22012-02-21 21:23:201630 // Resolves the host using a DnsTransaction.
1631 scoped_ptr<DnsTask> dns_task_;
1632
[email protected]0f292de02012-02-01 22:28:201633 // All Requests waiting for the result of this Job. Some can be canceled.
1634 RequestsList requests_;
1635
[email protected]16ee26d2012-03-08 03:34:351636 // A handle used in |HostResolverImpl::dispatcher_|.
[email protected]0f292de02012-02-01 22:28:201637 PrioritizedDispatcher::Handle handle_;
[email protected]68ad3ee2010-01-30 03:45:391638};
1639
1640//-----------------------------------------------------------------------------
1641
[email protected]0f292de02012-02-01 22:28:201642HostResolverImpl::ProcTaskParams::ProcTaskParams(
[email protected]e95d3aca2010-01-11 22:47:431643 HostResolverProc* resolver_proc,
[email protected]0f292de02012-02-01 22:28:201644 size_t max_retry_attempts)
1645 : resolver_proc(resolver_proc),
1646 max_retry_attempts(max_retry_attempts),
1647 unresponsive_delay(base::TimeDelta::FromMilliseconds(6000)),
1648 retry_factor(2) {
1649}
1650
1651HostResolverImpl::ProcTaskParams::~ProcTaskParams() {}
1652
1653HostResolverImpl::HostResolverImpl(
[email protected]c54a8912012-10-22 22:09:431654 scoped_ptr<HostCache> cache,
[email protected]0f292de02012-02-01 22:28:201655 const PrioritizedDispatcher::Limits& job_limits,
1656 const ProcTaskParams& proc_params,
[email protected]ee094b82010-08-24 15:55:511657 NetLog* net_log)
[email protected]c54a8912012-10-22 22:09:431658 : cache_(cache.Pass()),
[email protected]0f292de02012-02-01 22:28:201659 dispatcher_(job_limits),
1660 max_queued_jobs_(job_limits.total_jobs * 100u),
1661 proc_params_(proc_params),
[email protected]0c7798452009-10-26 17:59:511662 default_address_family_(ADDRESS_FAMILY_UNSPECIFIED),
[email protected]4589a3a2012-09-20 20:57:071663 weak_ptr_factory_(this),
[email protected]12faa4c2012-11-06 04:44:181664 probe_weak_ptr_factory_(this),
[email protected]d7b9a2b2012-05-31 22:31:191665 received_dns_config_(false),
[email protected]f0f602bd2012-11-15 18:01:021666 num_dns_failures_(0),
[email protected]2f3bc65c2010-07-23 17:47:101667 ipv6_probe_monitoring_(false),
[email protected]ee094b82010-08-24 15:55:511668 additional_resolver_flags_(0),
1669 net_log_(net_log) {
[email protected]0f292de02012-02-01 22:28:201670
1671 DCHECK_GE(dispatcher_.num_priorities(), static_cast<size_t>(NUM_PRIORITIES));
[email protected]68ad3ee2010-01-30 03:45:391672
[email protected]06ef6d92011-05-19 04:24:581673 // Maximum of 4 retry attempts for host resolution.
1674 static const size_t kDefaultMaxRetryAttempts = 4u;
1675
[email protected]0f292de02012-02-01 22:28:201676 if (proc_params_.max_retry_attempts == HostResolver::kDefaultRetryAttempts)
1677 proc_params_.max_retry_attempts = kDefaultMaxRetryAttempts;
[email protected]68ad3ee2010-01-30 03:45:391678
[email protected]b59ff372009-07-15 22:04:321679#if defined(OS_WIN)
1680 EnsureWinsockInit();
1681#endif
[email protected]23f771162011-06-02 18:37:511682#if defined(OS_POSIX) && !defined(OS_MACOSX)
[email protected]12faa4c2012-11-06 04:44:181683 new LoopbackProbeJob(weak_ptr_factory_.GetWeakPtr());
[email protected]2f3bc65c2010-07-23 17:47:101684#endif
[email protected]232a5812011-03-04 22:42:081685 NetworkChangeNotifier::AddIPAddressObserver(this);
[email protected]bb0e34542012-08-31 19:52:401686 NetworkChangeNotifier::AddDNSObserver(this);
[email protected]d7b9a2b2012-05-31 22:31:191687#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD) && \
1688 !defined(OS_ANDROID)
[email protected]d7b9a2b2012-05-31 22:31:191689 EnsureDnsReloaderInit();
[email protected]46018c9d2011-09-06 03:42:341690#endif
[email protected]2ac22db2012-11-28 19:50:041691
1692 // TODO(szym): Remove when received_dns_config_ is removed, once
1693 // http://crbug.com/137914 is resolved.
1694 {
1695 DnsConfig dns_config;
1696 NetworkChangeNotifier::GetDnsConfig(&dns_config);
1697 received_dns_config_ = dns_config.IsValid();
1698 }
[email protected]b59ff372009-07-15 22:04:321699}
1700
1701HostResolverImpl::~HostResolverImpl() {
[email protected]0f292de02012-02-01 22:28:201702 // This will also cancel all outstanding requests.
1703 STLDeleteValues(&jobs_);
[email protected]e95d3aca2010-01-11 22:47:431704
[email protected]232a5812011-03-04 22:42:081705 NetworkChangeNotifier::RemoveIPAddressObserver(this);
[email protected]bb0e34542012-08-31 19:52:401706 NetworkChangeNotifier::RemoveDNSObserver(this);
[email protected]b59ff372009-07-15 22:04:321707}
1708
[email protected]0f292de02012-02-01 22:28:201709void HostResolverImpl::SetMaxQueuedJobs(size_t value) {
1710 DCHECK_EQ(0u, dispatcher_.num_queued_jobs());
1711 DCHECK_GT(value, 0u);
1712 max_queued_jobs_ = value;
[email protected]be1a48b2011-01-20 00:12:131713}
1714
[email protected]684970b2009-08-14 04:54:461715int HostResolverImpl::Resolve(const RequestInfo& info,
[email protected]b59ff372009-07-15 22:04:321716 AddressList* addresses,
[email protected]aa22b242011-11-16 18:58:291717 const CompletionCallback& callback,
[email protected]684970b2009-08-14 04:54:461718 RequestHandle* out_req,
[email protected]ee094b82010-08-24 15:55:511719 const BoundNetLog& source_net_log) {
[email protected]95a214c2011-08-04 21:50:401720 DCHECK(addresses);
[email protected]1ac6af92010-06-03 21:00:141721 DCHECK(CalledOnValidThread());
[email protected]aa22b242011-11-16 18:58:291722 DCHECK_EQ(false, callback.is_null());
[email protected]1ac6af92010-06-03 21:00:141723
[email protected]ee094b82010-08-24 15:55:511724 // Make a log item for the request.
1725 BoundNetLog request_net_log = BoundNetLog::Make(net_log_,
1726 NetLog::SOURCE_HOST_RESOLVER_IMPL_REQUEST);
1727
[email protected]0f292de02012-02-01 22:28:201728 LogStartRequest(source_net_log, request_net_log, info);
[email protected]b59ff372009-07-15 22:04:321729
[email protected]123ab1e32009-10-21 19:12:571730 // Build a key that identifies the request in the cache and in the
1731 // outstanding jobs map.
[email protected]137af622010-02-05 02:14:351732 Key key = GetEffectiveKeyForRequest(info);
[email protected]123ab1e32009-10-21 19:12:571733
[email protected]287d7c22011-11-15 17:34:251734 int rv = ResolveHelper(key, info, addresses, request_net_log);
[email protected]95a214c2011-08-04 21:50:401735 if (rv != ERR_DNS_CACHE_MISS) {
[email protected]b3601bc22012-02-21 21:23:201736 LogFinishRequest(source_net_log, request_net_log, info, rv);
[email protected]51b9a6b2012-06-25 21:50:291737 RecordTotalTime(HaveDnsConfig(), info.is_speculative(), base::TimeDelta());
[email protected]95a214c2011-08-04 21:50:401738 return rv;
[email protected]38368712011-03-02 08:09:401739 }
1740
[email protected]0f292de02012-02-01 22:28:201741 // Next we need to attach our request to a "job". This job is responsible for
1742 // calling "getaddrinfo(hostname)" on a worker thread.
1743
1744 JobMap::iterator jobit = jobs_.find(key);
1745 Job* job;
1746 if (jobit == jobs_.end()) {
[email protected]12faa4c2012-11-06 04:44:181747 job = new Job(weak_ptr_factory_.GetWeakPtr(), key, info.priority(),
1748 request_net_log);
[email protected]8c98d002012-07-18 19:02:271749 job->Schedule();
[email protected]0f292de02012-02-01 22:28:201750
1751 // Check for queue overflow.
1752 if (dispatcher_.num_queued_jobs() > max_queued_jobs_) {
1753 Job* evicted = static_cast<Job*>(dispatcher_.EvictOldestLowest());
1754 DCHECK(evicted);
[email protected]16ee26d2012-03-08 03:34:351755 evicted->OnEvicted(); // Deletes |evicted|.
[email protected]0f292de02012-02-01 22:28:201756 if (evicted == job) {
[email protected]0f292de02012-02-01 22:28:201757 rv = ERR_HOST_RESOLVER_QUEUE_TOO_LARGE;
[email protected]b3601bc22012-02-21 21:23:201758 LogFinishRequest(source_net_log, request_net_log, info, rv);
[email protected]0f292de02012-02-01 22:28:201759 return rv;
1760 }
[email protected]0f292de02012-02-01 22:28:201761 }
[email protected]0f292de02012-02-01 22:28:201762 jobs_.insert(jobit, std::make_pair(key, job));
1763 } else {
1764 job = jobit->second;
1765 }
1766
1767 // Can't complete synchronously. Create and attach request.
[email protected]b3601bc22012-02-21 21:23:201768 scoped_ptr<Request> req(new Request(source_net_log,
1769 request_net_log,
1770 info,
1771 callback,
1772 addresses));
[email protected]b59ff372009-07-15 22:04:321773 if (out_req)
[email protected]b3601bc22012-02-21 21:23:201774 *out_req = reinterpret_cast<RequestHandle>(req.get());
[email protected]b59ff372009-07-15 22:04:321775
[email protected]b3601bc22012-02-21 21:23:201776 job->AddRequest(req.Pass());
[email protected]0f292de02012-02-01 22:28:201777 // Completion happens during Job::CompleteRequests().
[email protected]b59ff372009-07-15 22:04:321778 return ERR_IO_PENDING;
1779}
1780
[email protected]287d7c22011-11-15 17:34:251781int HostResolverImpl::ResolveHelper(const Key& key,
[email protected]95a214c2011-08-04 21:50:401782 const RequestInfo& info,
1783 AddressList* addresses,
[email protected]20cd5332011-10-12 22:38:001784 const BoundNetLog& request_net_log) {
[email protected]95a214c2011-08-04 21:50:401785 // The result of |getaddrinfo| for empty hosts is inconsistent across systems.
1786 // On Windows it gives the default interface's address, whereas on Linux it
1787 // gives an error. We will make it fail on all platforms for consistency.
1788 if (info.hostname().empty() || info.hostname().size() > kMaxHostLength)
1789 return ERR_NAME_NOT_RESOLVED;
1790
1791 int net_error = ERR_UNEXPECTED;
1792 if (ResolveAsIP(key, info, &net_error, addresses))
1793 return net_error;
[email protected]78eac2a2012-03-14 19:09:271794 if (ServeFromCache(key, info, &net_error, addresses)) {
[email protected]4da911f2012-06-14 19:45:201795 request_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_CACHE_HIT);
[email protected]78eac2a2012-03-14 19:09:271796 return net_error;
1797 }
1798 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
1799 // http://crbug.com/117655
1800 if (ServeFromHosts(key, info, addresses)) {
[email protected]4da911f2012-06-14 19:45:201801 request_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_HOSTS_HIT);
[email protected]78eac2a2012-03-14 19:09:271802 return OK;
1803 }
1804 return ERR_DNS_CACHE_MISS;
[email protected]95a214c2011-08-04 21:50:401805}
1806
1807int HostResolverImpl::ResolveFromCache(const RequestInfo& info,
1808 AddressList* addresses,
1809 const BoundNetLog& source_net_log) {
1810 DCHECK(CalledOnValidThread());
1811 DCHECK(addresses);
1812
[email protected]95a214c2011-08-04 21:50:401813 // Make a log item for the request.
1814 BoundNetLog request_net_log = BoundNetLog::Make(net_log_,
1815 NetLog::SOURCE_HOST_RESOLVER_IMPL_REQUEST);
1816
1817 // Update the net log and notify registered observers.
[email protected]0f292de02012-02-01 22:28:201818 LogStartRequest(source_net_log, request_net_log, info);
[email protected]95a214c2011-08-04 21:50:401819
[email protected]95a214c2011-08-04 21:50:401820 Key key = GetEffectiveKeyForRequest(info);
1821
[email protected]287d7c22011-11-15 17:34:251822 int rv = ResolveHelper(key, info, addresses, request_net_log);
[email protected]b3601bc22012-02-21 21:23:201823 LogFinishRequest(source_net_log, request_net_log, info, rv);
[email protected]95a214c2011-08-04 21:50:401824 return rv;
1825}
1826
[email protected]b59ff372009-07-15 22:04:321827void HostResolverImpl::CancelRequest(RequestHandle req_handle) {
[email protected]1ac6af92010-06-03 21:00:141828 DCHECK(CalledOnValidThread());
[email protected]b59ff372009-07-15 22:04:321829 Request* req = reinterpret_cast<Request*>(req_handle);
1830 DCHECK(req);
[email protected]0f292de02012-02-01 22:28:201831 Job* job = req->job();
1832 DCHECK(job);
[email protected]0f292de02012-02-01 22:28:201833 job->CancelRequest(req);
[email protected]b59ff372009-07-15 22:04:321834}
1835
[email protected]0f8f1b432010-03-16 19:06:031836void HostResolverImpl::SetDefaultAddressFamily(AddressFamily address_family) {
[email protected]1ac6af92010-06-03 21:00:141837 DCHECK(CalledOnValidThread());
[email protected]0f8f1b432010-03-16 19:06:031838 default_address_family_ = address_family;
[email protected]12faa4c2012-11-06 04:44:181839 ipv6_probe_monitoring_ = false;
[email protected]0f8f1b432010-03-16 19:06:031840}
1841
[email protected]f7d310e2010-10-07 16:25:111842AddressFamily HostResolverImpl::GetDefaultAddressFamily() const {
1843 return default_address_family_;
1844}
1845
[email protected]a78f4272011-10-21 19:16:331846void HostResolverImpl::ProbeIPv6Support() {
1847 DCHECK(CalledOnValidThread());
1848 DCHECK(!ipv6_probe_monitoring_);
1849 ipv6_probe_monitoring_ = true;
[email protected]12faa4c2012-11-06 04:44:181850 OnIPAddressChanged();
[email protected]ddb1e5a2010-12-13 20:10:451851}
1852
[email protected]a8883e452012-11-17 05:58:061853void HostResolverImpl::SetDnsClientEnabled(bool enabled) {
1854 DCHECK(CalledOnValidThread());
1855#if defined(ENABLE_BUILT_IN_DNS)
1856 if (enabled && !dns_client_) {
1857 SetDnsClient(DnsClient::CreateClient(net_log_));
1858 } else if (!enabled && dns_client_) {
1859 SetDnsClient(scoped_ptr<DnsClient>());
1860 }
1861#endif
1862}
1863
[email protected]489d1a82011-10-12 03:09:111864HostCache* HostResolverImpl::GetHostCache() {
1865 return cache_.get();
1866}
[email protected]95a214c2011-08-04 21:50:401867
[email protected]17e92032012-03-29 00:56:241868base::Value* HostResolverImpl::GetDnsConfigAsValue() const {
1869 // Check if async DNS is disabled.
1870 if (!dns_client_.get())
1871 return NULL;
1872
1873 // Check if async DNS is enabled, but we currently have no configuration
1874 // for it.
1875 const DnsConfig* dns_config = dns_client_->GetConfig();
1876 if (dns_config == NULL)
1877 return new DictionaryValue();
1878
1879 return dns_config->ToValue();
1880}
1881
[email protected]95a214c2011-08-04 21:50:401882bool HostResolverImpl::ResolveAsIP(const Key& key,
1883 const RequestInfo& info,
1884 int* net_error,
1885 AddressList* addresses) {
1886 DCHECK(addresses);
1887 DCHECK(net_error);
1888 IPAddressNumber ip_number;
1889 if (!ParseIPLiteralToNumber(key.hostname, &ip_number))
1890 return false;
1891
1892 DCHECK_EQ(key.host_resolver_flags &
1893 ~(HOST_RESOLVER_CANONNAME | HOST_RESOLVER_LOOPBACK_ONLY |
1894 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6),
1895 0) << " Unhandled flag";
[email protected]0f292de02012-02-01 22:28:201896 bool ipv6_disabled = (default_address_family_ == ADDRESS_FAMILY_IPV4) &&
1897 !ipv6_probe_monitoring_;
[email protected]95a214c2011-08-04 21:50:401898 *net_error = OK;
[email protected]0f292de02012-02-01 22:28:201899 if ((ip_number.size() == kIPv6AddressSize) && ipv6_disabled) {
[email protected]95a214c2011-08-04 21:50:401900 *net_error = ERR_NAME_NOT_RESOLVED;
1901 } else {
[email protected]7054e78f2012-05-07 21:44:561902 *addresses = AddressList::CreateFromIPAddress(ip_number, info.port());
1903 if (key.host_resolver_flags & HOST_RESOLVER_CANONNAME)
1904 addresses->SetDefaultCanonicalName();
[email protected]95a214c2011-08-04 21:50:401905 }
1906 return true;
1907}
1908
1909bool HostResolverImpl::ServeFromCache(const Key& key,
1910 const RequestInfo& info,
[email protected]95a214c2011-08-04 21:50:401911 int* net_error,
1912 AddressList* addresses) {
1913 DCHECK(addresses);
1914 DCHECK(net_error);
1915 if (!info.allow_cached_response() || !cache_.get())
1916 return false;
1917
[email protected]407a30ab2012-08-15 17:16:101918 const HostCache::Entry* cache_entry = cache_->Lookup(
1919 key, base::TimeTicks::Now());
[email protected]95a214c2011-08-04 21:50:401920 if (!cache_entry)
1921 return false;
1922
[email protected]95a214c2011-08-04 21:50:401923 *net_error = cache_entry->error;
[email protected]7054e78f2012-05-07 21:44:561924 if (*net_error == OK) {
[email protected]1339a2a22012-10-17 08:39:431925 if (cache_entry->has_ttl())
1926 RecordTTL(cache_entry->ttl);
[email protected]895123222012-10-25 15:21:171927 *addresses = EnsurePortOnAddressList(cache_entry->addrlist, info.port());
[email protected]7054e78f2012-05-07 21:44:561928 }
[email protected]95a214c2011-08-04 21:50:401929 return true;
1930}
1931
[email protected]78eac2a2012-03-14 19:09:271932bool HostResolverImpl::ServeFromHosts(const Key& key,
1933 const RequestInfo& info,
1934 AddressList* addresses) {
1935 DCHECK(addresses);
1936 if (!HaveDnsConfig())
1937 return false;
1938
[email protected]cb507622012-03-23 16:17:061939 // HOSTS lookups are case-insensitive.
1940 std::string hostname = StringToLowerASCII(key.hostname);
1941
[email protected]78eac2a2012-03-14 19:09:271942 // If |address_family| is ADDRESS_FAMILY_UNSPECIFIED other implementations
1943 // (glibc and c-ares) return the first matching line. We have more
1944 // flexibility, but lose implicit ordering.
1945 // TODO(szym) http://crbug.com/117850
1946 const DnsHosts& hosts = dns_client_->GetConfig()->hosts;
1947 DnsHosts::const_iterator it = hosts.find(
[email protected]cb507622012-03-23 16:17:061948 DnsHostsKey(hostname,
[email protected]78eac2a2012-03-14 19:09:271949 key.address_family == ADDRESS_FAMILY_UNSPECIFIED ?
1950 ADDRESS_FAMILY_IPV4 : key.address_family));
1951
1952 if (it == hosts.end()) {
1953 if (key.address_family != ADDRESS_FAMILY_UNSPECIFIED)
1954 return false;
1955
[email protected]cb507622012-03-23 16:17:061956 it = hosts.find(DnsHostsKey(hostname, ADDRESS_FAMILY_IPV6));
[email protected]78eac2a2012-03-14 19:09:271957 if (it == hosts.end())
1958 return false;
1959 }
1960
1961 *addresses = AddressList::CreateFromIPAddress(it->second, info.port());
1962 return true;
1963}
1964
[email protected]16ee26d2012-03-08 03:34:351965void HostResolverImpl::CacheResult(const Key& key,
[email protected]1339a2a22012-10-17 08:39:431966 const HostCache::Entry& entry,
[email protected]16ee26d2012-03-08 03:34:351967 base::TimeDelta ttl) {
1968 if (cache_.get())
[email protected]1339a2a22012-10-17 08:39:431969 cache_->Set(key, entry, base::TimeTicks::Now(), ttl);
[email protected]ef4c40c2010-09-01 14:42:031970}
1971
[email protected]0f292de02012-02-01 22:28:201972void HostResolverImpl::RemoveJob(Job* job) {
1973 DCHECK(job);
[email protected]16ee26d2012-03-08 03:34:351974 JobMap::iterator it = jobs_.find(job->key());
1975 if (it != jobs_.end() && it->second == job)
1976 jobs_.erase(it);
[email protected]b59ff372009-07-15 22:04:321977}
1978
[email protected]0f8f1b432010-03-16 19:06:031979void HostResolverImpl::IPv6ProbeSetDefaultAddressFamily(
1980 AddressFamily address_family) {
1981 DCHECK(address_family == ADDRESS_FAMILY_UNSPECIFIED ||
1982 address_family == ADDRESS_FAMILY_IPV4);
[email protected]12faa4c2012-11-06 04:44:181983 if (!ipv6_probe_monitoring_)
1984 return;
[email protected]f092e64b2010-03-17 00:39:181985 if (default_address_family_ != address_family) {
[email protected]b30a3f52010-10-16 01:05:461986 VLOG(1) << "IPv6Probe forced AddressFamily setting to "
1987 << ((address_family == ADDRESS_FAMILY_UNSPECIFIED) ?
1988 "ADDRESS_FAMILY_UNSPECIFIED" : "ADDRESS_FAMILY_IPV4");
[email protected]f092e64b2010-03-17 00:39:181989 }
[email protected]0f8f1b432010-03-16 19:06:031990 default_address_family_ = address_family;
[email protected]e95d3aca2010-01-11 22:47:431991}
1992
[email protected]9936a7862012-10-26 04:44:021993void HostResolverImpl::SetHaveOnlyLoopbackAddresses(bool result) {
1994 if (result) {
1995 additional_resolver_flags_ |= HOST_RESOLVER_LOOPBACK_ONLY;
1996 } else {
1997 additional_resolver_flags_ &= ~HOST_RESOLVER_LOOPBACK_ONLY;
1998 }
1999}
2000
[email protected]137af622010-02-05 02:14:352001HostResolverImpl::Key HostResolverImpl::GetEffectiveKeyForRequest(
2002 const RequestInfo& info) const {
[email protected]eaf3a3b2010-09-03 20:34:272003 HostResolverFlags effective_flags =
2004 info.host_resolver_flags() | additional_resolver_flags_;
[email protected]137af622010-02-05 02:14:352005 AddressFamily effective_address_family = info.address_family();
[email protected]eaf3a3b2010-09-03 20:34:272006 if (effective_address_family == ADDRESS_FAMILY_UNSPECIFIED &&
2007 default_address_family_ != ADDRESS_FAMILY_UNSPECIFIED) {
[email protected]137af622010-02-05 02:14:352008 effective_address_family = default_address_family_;
[email protected]eaf3a3b2010-09-03 20:34:272009 if (ipv6_probe_monitoring_)
2010 effective_flags |= HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
2011 }
2012 return Key(info.hostname(), effective_address_family, effective_flags);
[email protected]137af622010-02-05 02:14:352013}
2014
[email protected]35ddc282010-09-21 23:42:062015void HostResolverImpl::AbortAllInProgressJobs() {
[email protected]b3601bc22012-02-21 21:23:202016 // In Abort, a Request callback could spawn new Jobs with matching keys, so
2017 // first collect and remove all running jobs from |jobs_|.
[email protected]c143d892012-04-06 07:56:542018 ScopedVector<Job> jobs_to_abort;
[email protected]0f292de02012-02-01 22:28:202019 for (JobMap::iterator it = jobs_.begin(); it != jobs_.end(); ) {
2020 Job* job = it->second;
[email protected]0f292de02012-02-01 22:28:202021 if (job->is_running()) {
[email protected]b3601bc22012-02-21 21:23:202022 jobs_to_abort.push_back(job);
2023 jobs_.erase(it++);
[email protected]0f292de02012-02-01 22:28:202024 } else {
[email protected]b3601bc22012-02-21 21:23:202025 DCHECK(job->is_queued());
2026 ++it;
[email protected]0f292de02012-02-01 22:28:202027 }
[email protected]ef4c40c2010-09-01 14:42:032028 }
[email protected]b3601bc22012-02-21 21:23:202029
[email protected]57a48d32012-03-03 00:04:552030 // Check if no dispatcher slots leaked out.
2031 DCHECK_EQ(dispatcher_.num_running_jobs(), jobs_to_abort.size());
2032
2033 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072034 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]57a48d32012-03-03 00:04:552035
[email protected]16ee26d2012-03-08 03:34:352036 // Then Abort them.
[email protected]57a48d32012-03-03 00:04:552037 for (size_t i = 0; self && i < jobs_to_abort.size(); ++i) {
[email protected]57a48d32012-03-03 00:04:552038 jobs_to_abort[i]->Abort();
[email protected]c143d892012-04-06 07:56:542039 jobs_to_abort[i] = NULL;
[email protected]b3601bc22012-02-21 21:23:202040 }
[email protected]ef4c40c2010-09-01 14:42:032041}
2042
[email protected]78eac2a2012-03-14 19:09:272043void HostResolverImpl::TryServingAllJobsFromHosts() {
2044 if (!HaveDnsConfig())
2045 return;
2046
2047 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2048 // http://crbug.com/117655
2049
2050 // Life check to bail once |this| is deleted.
[email protected]4589a3a2012-09-20 20:57:072051 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
[email protected]78eac2a2012-03-14 19:09:272052
2053 for (JobMap::iterator it = jobs_.begin(); self && it != jobs_.end(); ) {
2054 Job* job = it->second;
2055 ++it;
2056 // This could remove |job| from |jobs_|, but iterator will remain valid.
2057 job->ServeFromHosts();
2058 }
2059}
2060
[email protected]be1a48b2011-01-20 00:12:132061void HostResolverImpl::OnIPAddressChanged() {
[email protected]12faa4c2012-11-06 04:44:182062 // Abandon all ProbeJobs.
2063 probe_weak_ptr_factory_.InvalidateWeakPtrs();
[email protected]be1a48b2011-01-20 00:12:132064 if (cache_.get())
2065 cache_->clear();
[email protected]12faa4c2012-11-06 04:44:182066 if (ipv6_probe_monitoring_)
2067 new IPv6ProbeJob(probe_weak_ptr_factory_.GetWeakPtr(), net_log_);
[email protected]23f771162011-06-02 18:37:512068#if defined(OS_POSIX) && !defined(OS_MACOSX)
[email protected]12faa4c2012-11-06 04:44:182069 new LoopbackProbeJob(probe_weak_ptr_factory_.GetWeakPtr());
[email protected]be1a48b2011-01-20 00:12:132070#endif
2071 AbortAllInProgressJobs();
2072 // |this| may be deleted inside AbortAllInProgressJobs().
2073}
2074
[email protected]bb0e34542012-08-31 19:52:402075void HostResolverImpl::OnDNSChanged() {
2076 DnsConfig dns_config;
2077 NetworkChangeNotifier::GetDnsConfig(&dns_config);
[email protected]b4481b222012-03-16 17:13:112078 if (net_log_) {
2079 net_log_->AddGlobalEntry(
2080 NetLog::TYPE_DNS_CONFIG_CHANGED,
[email protected]cd565142012-06-12 16:21:452081 base::Bind(&NetLogDnsConfigCallback, &dns_config));
[email protected]b4481b222012-03-16 17:13:112082 }
2083
[email protected]01b3b9d2012-08-13 16:18:142084 // TODO(szym): Remove once http://crbug.com/137914 is resolved.
[email protected]d7b9a2b2012-05-31 22:31:192085 received_dns_config_ = dns_config.IsValid();
[email protected]78eac2a2012-03-14 19:09:272086
[email protected]a8883e452012-11-17 05:58:062087 num_dns_failures_ = 0;
2088
[email protected]01b3b9d2012-08-13 16:18:142089 // We want a new DnsSession in place, before we Abort running Jobs, so that
2090 // the newly started jobs use the new config.
[email protected]f0f602bd2012-11-15 18:01:022091 if (dns_client_.get()) {
[email protected]d7b9a2b2012-05-31 22:31:192092 dns_client_->SetConfig(dns_config);
[email protected]a8883e452012-11-17 05:58:062093 if (dns_config.IsValid())
[email protected]f0f602bd2012-11-15 18:01:022094 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
[email protected]f0f602bd2012-11-15 18:01:022095 }
[email protected]01b3b9d2012-08-13 16:18:142096
2097 // If the DNS server has changed, existing cached info could be wrong so we
2098 // have to drop our internal cache :( Note that OS level DNS caches, such
2099 // as NSCD's cache should be dropped automatically by the OS when
2100 // resolv.conf changes so we don't need to do anything to clear that cache.
2101 if (cache_.get())
2102 cache_->clear();
2103
[email protected]f0f602bd2012-11-15 18:01:022104 // Life check to bail once |this| is deleted.
2105 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
2106
[email protected]01b3b9d2012-08-13 16:18:142107 // Existing jobs will have been sent to the original server so they need to
2108 // be aborted.
2109 AbortAllInProgressJobs();
2110
2111 // |this| may be deleted inside AbortAllInProgressJobs().
2112 if (self)
2113 TryServingAllJobsFromHosts();
[email protected]78eac2a2012-03-14 19:09:272114}
2115
2116bool HostResolverImpl::HaveDnsConfig() const {
2117 return (dns_client_.get() != NULL) && (dns_client_->GetConfig() != NULL);
[email protected]b3601bc22012-02-21 21:23:202118}
2119
[email protected]1ffdda82012-12-12 23:04:222120void HostResolverImpl::OnDnsTaskResolve(int net_error) {
[email protected]f0f602bd2012-11-15 18:01:022121 DCHECK(dns_client_);
[email protected]1ffdda82012-12-12 23:04:222122 if (net_error == OK) {
[email protected]f0f602bd2012-11-15 18:01:022123 num_dns_failures_ = 0;
2124 return;
2125 }
2126 ++num_dns_failures_;
2127 if (num_dns_failures_ < kMaximumDnsFailures)
2128 return;
2129 // Disable DnsClient until the next DNS change.
2130 for (JobMap::iterator it = jobs_.begin(); it != jobs_.end(); ++it)
2131 it->second->AbortDnsTask();
2132 dns_client_->SetConfig(DnsConfig());
2133 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", false);
[email protected]1ffdda82012-12-12 23:04:222134 UMA_HISTOGRAM_CUSTOM_ENUMERATION("AsyncDNS.DnsClientDisabledReason",
2135 std::abs(net_error),
2136 GetAllErrorCodesForUma());
[email protected]f0f602bd2012-11-15 18:01:022137}
2138
[email protected]a8883e452012-11-17 05:58:062139void HostResolverImpl::SetDnsClient(scoped_ptr<DnsClient> dns_client) {
2140 if (HaveDnsConfig()) {
2141 for (JobMap::iterator it = jobs_.begin(); it != jobs_.end(); ++it)
2142 it->second->AbortDnsTask();
2143 }
2144 dns_client_ = dns_client.Pass();
2145 if (!dns_client_ || dns_client_->GetConfig() ||
2146 num_dns_failures_ >= kMaximumDnsFailures) {
2147 return;
2148 }
2149 DnsConfig dns_config;
2150 NetworkChangeNotifier::GetDnsConfig(&dns_config);
2151 dns_client_->SetConfig(dns_config);
2152 num_dns_failures_ = 0;
2153 if (dns_config.IsValid())
2154 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
2155}
2156
[email protected]b59ff372009-07-15 22:04:322157} // namespace net