blob: a66f950e5fa8d9d6c477ebc49e1aaac329df6f6d [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]ee094b82010-08-24 15:55:5135#include "net/base/address_list_net_log_param.h"
[email protected]46018c9d2011-09-06 03:42:3436#include "net/base/dns_reloader.h"
[email protected]ee094b82010-08-24 15:55:5137#include "net/base/host_port_pair.h"
[email protected]b59ff372009-07-15 22:04:3238#include "net/base/host_resolver_proc.h"
[email protected]2bb04442010-08-18 18:01:1539#include "net/base/net_errors.h"
[email protected]ee094b82010-08-24 15:55:5140#include "net/base/net_log.h"
[email protected]0f8f1b432010-03-16 19:06:0341#include "net/base/net_util.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]4f8a16a2012-04-07 23:59:2066// Maximum of 6 concurrent resolver threads (excluding retries).
[email protected]0f292de02012-02-01 22:28:2067// Some routers (or resolvers) appear to start to provide host-not-found if
68// too many simultaneous resolutions are pending. This number needs to be
[email protected]4f8a16a2012-04-07 23:59:2069// further optimized, but 8 is what FF currently does. We found some routers
70// that limit this to 6, so we're temporarily holding it at that level.
71static const size_t kDefaultMaxProcTasks = 6u;
[email protected]0f292de02012-02-01 22:28:2072
[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,
141 RESOLVE_STATUS_MAX
142};
143
144void UmaAsyncDnsResolveStatus(DnsResolveStatus result) {
145 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ResolveStatus",
146 result,
147 RESOLVE_STATUS_MAX);
148}
149
[email protected]d7b9a2b2012-05-31 22:31:19150//-----------------------------------------------------------------------------
151
[email protected]0f292de02012-02-01 22:28:20152// Wraps call to SystemHostResolverProc as an instance of HostResolverProc.
153// TODO(szym): This should probably be declared in host_resolver_proc.h.
154class CallSystemHostResolverProc : public HostResolverProc {
155 public:
156 CallSystemHostResolverProc() : HostResolverProc(NULL) {}
157 virtual int Resolve(const std::string& hostname,
158 AddressFamily address_family,
159 HostResolverFlags host_resolver_flags,
[email protected]b3601bc22012-02-21 21:23:20160 AddressList* addr_list,
[email protected]0f292de02012-02-01 22:28:20161 int* os_error) OVERRIDE {
162 return SystemHostResolverProc(hostname,
163 address_family,
164 host_resolver_flags,
[email protected]b3601bc22012-02-21 21:23:20165 addr_list,
[email protected]0f292de02012-02-01 22:28:20166 os_error);
[email protected]b59ff372009-07-15 22:04:32167 }
[email protected]a9813302012-04-28 09:29:28168
169 protected:
170 virtual ~CallSystemHostResolverProc() {}
[email protected]0f292de02012-02-01 22:28:20171};
[email protected]b59ff372009-07-15 22:04:32172
[email protected]7054e78f2012-05-07 21:44:56173void EnsurePortOnAddressList(uint16 port, AddressList* list) {
174 DCHECK(list);
175 if (list->empty() || list->front().port() == port)
176 return;
177 SetPortOnAddressList(port, list);
178}
179
[email protected]21526002010-05-16 19:42:46180// Extra parameters to attach to the NetLog when the resolve failed.
[email protected]b3601bc22012-02-21 21:23:20181class ProcTaskFailedParams : public NetLog::EventParameters {
[email protected]21526002010-05-16 19:42:46182 public:
[email protected]b3601bc22012-02-21 21:23:20183 ProcTaskFailedParams(uint32 attempt_number, int net_error, int os_error)
[email protected]13024882011-05-18 23:19:16184 : attempt_number_(attempt_number),
185 net_error_(net_error),
[email protected]ee094b82010-08-24 15:55:51186 os_error_(os_error) {
[email protected]21526002010-05-16 19:42:46187 }
188
[email protected]0f292de02012-02-01 22:28:20189 virtual Value* ToValue() const OVERRIDE {
[email protected]21526002010-05-16 19:42:46190 DictionaryValue* dict = new DictionaryValue();
[email protected]13024882011-05-18 23:19:16191 if (attempt_number_)
192 dict->SetInteger("attempt_number", attempt_number_);
193
[email protected]ccaff652010-07-31 06:28:20194 dict->SetInteger("net_error", net_error_);
[email protected]21526002010-05-16 19:42:46195
196 if (os_error_) {
[email protected]ccaff652010-07-31 06:28:20197 dict->SetInteger("os_error", os_error_);
[email protected]21526002010-05-16 19:42:46198#if defined(OS_POSIX)
[email protected]ccaff652010-07-31 06:28:20199 dict->SetString("os_error_string", gai_strerror(os_error_));
[email protected]21526002010-05-16 19:42:46200#elif defined(OS_WIN)
201 // Map the error code to a human-readable string.
202 LPWSTR error_string = NULL;
203 int size = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
204 FORMAT_MESSAGE_FROM_SYSTEM,
205 0, // Use the internal message table.
206 os_error_,
207 0, // Use default language.
208 (LPWSTR)&error_string,
209 0, // Buffer size.
210 0); // Arguments (unused).
[email protected]ccaff652010-07-31 06:28:20211 dict->SetString("os_error_string", WideToUTF8(error_string));
[email protected]21526002010-05-16 19:42:46212 LocalFree(error_string);
213#endif
214 }
215
216 return dict;
217 }
218
[email protected]a9813302012-04-28 09:29:28219 protected:
220 virtual ~ProcTaskFailedParams() {}
221
[email protected]21526002010-05-16 19:42:46222 private:
[email protected]13024882011-05-18 23:19:16223 const uint32 attempt_number_;
[email protected]21526002010-05-16 19:42:46224 const int net_error_;
225 const int os_error_;
[email protected]ee094b82010-08-24 15:55:51226};
227
[email protected]b3601bc22012-02-21 21:23:20228// Extra parameters to attach to the NetLog when the DnsTask failed.
229class DnsTaskFailedParams : public NetLog::EventParameters {
230 public:
231 DnsTaskFailedParams(int net_error, int dns_error)
232 : net_error_(net_error), dns_error_(dns_error) {
233 }
234
235 virtual Value* ToValue() const OVERRIDE {
236 DictionaryValue* dict = new DictionaryValue();
237 dict->SetInteger("net_error", net_error_);
238 if (dns_error_)
239 dict->SetInteger("dns_error", dns_error_);
240 return dict;
241 }
242
[email protected]a9813302012-04-28 09:29:28243 protected:
244 virtual ~DnsTaskFailedParams() {}
245
[email protected]b3601bc22012-02-21 21:23:20246 private:
247 const int net_error_;
248 const int dns_error_;
249};
250
[email protected]ee094b82010-08-24 15:55:51251// Parameters representing the information in a RequestInfo object, along with
252// the associated NetLog::Source.
253class RequestInfoParameters : public NetLog::EventParameters {
254 public:
255 RequestInfoParameters(const HostResolver::RequestInfo& info,
256 const NetLog::Source& source)
257 : info_(info), source_(source) {}
258
[email protected]0f292de02012-02-01 22:28:20259 virtual Value* ToValue() const OVERRIDE {
[email protected]ee094b82010-08-24 15:55:51260 DictionaryValue* dict = new DictionaryValue();
[email protected]930cc742010-09-15 22:54:10261 dict->SetString("host", info_.host_port_pair().ToString());
[email protected]ee094b82010-08-24 15:55:51262 dict->SetInteger("address_family",
263 static_cast<int>(info_.address_family()));
264 dict->SetBoolean("allow_cached_response", info_.allow_cached_response());
265 dict->SetBoolean("is_speculative", info_.is_speculative());
266 dict->SetInteger("priority", info_.priority());
267
268 if (source_.is_valid())
269 dict->Set("source_dependency", source_.ToValue());
270
271 return dict;
272 }
273
[email protected]a9813302012-04-28 09:29:28274 protected:
275 virtual ~RequestInfoParameters() {}
276
[email protected]ee094b82010-08-24 15:55:51277 private:
278 const HostResolver::RequestInfo info_;
279 const NetLog::Source source_;
280};
281
[email protected]b3601bc22012-02-21 21:23:20282// Parameters associated with the creation of a HostResolverImpl::Job.
[email protected]ee094b82010-08-24 15:55:51283class JobCreationParameters : public NetLog::EventParameters {
284 public:
[email protected]0f292de02012-02-01 22:28:20285 JobCreationParameters(const std::string& host,
286 const NetLog::Source& source)
[email protected]ee094b82010-08-24 15:55:51287 : host_(host), source_(source) {}
288
[email protected]0f292de02012-02-01 22:28:20289 virtual Value* ToValue() const OVERRIDE {
[email protected]ee094b82010-08-24 15:55:51290 DictionaryValue* dict = new DictionaryValue();
291 dict->SetString("host", host_);
292 dict->Set("source_dependency", source_.ToValue());
293 return dict;
294 }
295
[email protected]a9813302012-04-28 09:29:28296 protected:
297 virtual ~JobCreationParameters() {}
298
[email protected]ee094b82010-08-24 15:55:51299 private:
300 const std::string host_;
301 const NetLog::Source source_;
[email protected]21526002010-05-16 19:42:46302};
303
[email protected]0f292de02012-02-01 22:28:20304// Parameters of the HOST_RESOLVER_IMPL_JOB_ATTACH/DETACH event.
305class JobAttachParameters : public NetLog::EventParameters {
306 public:
307 JobAttachParameters(const NetLog::Source& source,
308 RequestPriority priority)
309 : source_(source), priority_(priority) {}
310
311 virtual Value* ToValue() const OVERRIDE {
312 DictionaryValue* dict = new DictionaryValue();
313 dict->Set("source_dependency", source_.ToValue());
314 dict->SetInteger("priority", priority_);
315 return dict;
316 }
317
[email protected]a9813302012-04-28 09:29:28318 protected:
319 virtual ~JobAttachParameters() {}
320
[email protected]0f292de02012-02-01 22:28:20321 private:
322 const NetLog::Source source_;
323 const RequestPriority priority_;
324};
325
[email protected]b4481b222012-03-16 17:13:11326// Parameters of the DNS_CONFIG_CHANGED event.
327class DnsConfigParameters : public NetLog::EventParameters {
328 public:
329 explicit DnsConfigParameters(const DnsConfig& config)
330 : num_hosts_(config.hosts.size()) {
331 config_.CopyIgnoreHosts(config);
332 }
333
334 virtual Value* ToValue() const OVERRIDE {
[email protected]17e92032012-03-29 00:56:24335 Value* value = config_.ToValue();
336 if (!value)
337 return NULL;
338 DictionaryValue* dict;
339 if (value->GetAsDictionary(&dict))
340 dict->SetInteger("num_hosts", num_hosts_);
341 return value;
[email protected]b4481b222012-03-16 17:13:11342 }
343
[email protected]a9813302012-04-28 09:29:28344 protected:
345 virtual ~DnsConfigParameters() {}
346
[email protected]b4481b222012-03-16 17:13:11347 private:
348 DnsConfig config_; // Does not include DnsHosts to save memory and work.
349 const size_t num_hosts_;
350};
351
[email protected]0f292de02012-02-01 22:28:20352// The logging routines are defined here because some requests are resolved
353// without a Request object.
354
355// Logs when a request has just been started.
356void LogStartRequest(const BoundNetLog& source_net_log,
357 const BoundNetLog& request_net_log,
358 const HostResolver::RequestInfo& info) {
359 source_net_log.BeginEvent(
360 NetLog::TYPE_HOST_RESOLVER_IMPL,
361 make_scoped_refptr(new NetLogSourceParameter(
362 "source_dependency", request_net_log.source())));
363
364 request_net_log.BeginEvent(
365 NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST,
366 make_scoped_refptr(new RequestInfoParameters(
367 info, source_net_log.source())));
368}
369
370// Logs when a request has just completed (before its callback is run).
371void LogFinishRequest(const BoundNetLog& source_net_log,
372 const BoundNetLog& request_net_log,
373 const HostResolver::RequestInfo& info,
[email protected]b3601bc22012-02-21 21:23:20374 int net_error) {
375 request_net_log.EndEventWithNetErrorCode(
376 NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST, net_error);
[email protected]0f292de02012-02-01 22:28:20377 source_net_log.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL, NULL);
378}
379
380// Logs when a request has been cancelled.
381void LogCancelRequest(const BoundNetLog& source_net_log,
382 const BoundNetLog& request_net_log,
383 const HostResolverImpl::RequestInfo& info) {
384 request_net_log.AddEvent(NetLog::TYPE_CANCELLED, NULL);
385 request_net_log.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST, NULL);
386 source_net_log.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL, NULL);
387}
388
[email protected]b59ff372009-07-15 22:04:32389//-----------------------------------------------------------------------------
390
[email protected]0f292de02012-02-01 22:28:20391// Keeps track of the highest priority.
392class PriorityTracker {
393 public:
[email protected]16ee26d2012-03-08 03:34:35394 PriorityTracker()
395 : highest_priority_(IDLE), total_count_(0) {
[email protected]0f292de02012-02-01 22:28:20396 memset(counts_, 0, sizeof(counts_));
397 }
398
399 RequestPriority highest_priority() const {
400 return highest_priority_;
401 }
402
403 size_t total_count() const {
404 return total_count_;
405 }
406
407 void Add(RequestPriority req_priority) {
408 ++total_count_;
409 ++counts_[req_priority];
[email protected]31ae7ab2012-04-24 21:09:05410 if (highest_priority_ < req_priority)
[email protected]0f292de02012-02-01 22:28:20411 highest_priority_ = req_priority;
412 }
413
414 void Remove(RequestPriority req_priority) {
415 DCHECK_GT(total_count_, 0u);
416 DCHECK_GT(counts_[req_priority], 0u);
417 --total_count_;
418 --counts_[req_priority];
419 size_t i;
[email protected]31ae7ab2012-04-24 21:09:05420 for (i = highest_priority_; i > MINIMUM_PRIORITY && !counts_[i]; --i);
[email protected]0f292de02012-02-01 22:28:20421 highest_priority_ = static_cast<RequestPriority>(i);
422
[email protected]31ae7ab2012-04-24 21:09:05423 // In absence of requests, default to MINIMUM_PRIORITY.
424 if (total_count_ == 0)
425 DCHECK_EQ(MINIMUM_PRIORITY, highest_priority_);
[email protected]0f292de02012-02-01 22:28:20426 }
427
428 private:
429 RequestPriority highest_priority_;
430 size_t total_count_;
431 size_t counts_[NUM_PRIORITIES];
432};
433
434//-----------------------------------------------------------------------------
435
436HostResolver* CreateHostResolver(size_t max_concurrent_resolves,
437 size_t max_retry_attempts,
[email protected]b3601bc22012-02-21 21:23:20438 HostCache* cache,
439 scoped_ptr<DnsConfigService> config_service,
[email protected]d7b9a2b2012-05-31 22:31:19440 scoped_ptr<DnsClient> dns_client,
[email protected]0f292de02012-02-01 22:28:20441 NetLog* net_log) {
442 if (max_concurrent_resolves == HostResolver::kDefaultParallelism)
443 max_concurrent_resolves = kDefaultMaxProcTasks;
444
445 // TODO(szym): Add experiments with reserved slots for higher priority
446 // requests.
447
448 PrioritizedDispatcher::Limits limits(NUM_PRIORITIES, max_concurrent_resolves);
449
450 HostResolverImpl* resolver = new HostResolverImpl(
[email protected]b3601bc22012-02-21 21:23:20451 cache,
[email protected]0f292de02012-02-01 22:28:20452 limits,
453 HostResolverImpl::ProcTaskParams(NULL, max_retry_attempts),
[email protected]b3601bc22012-02-21 21:23:20454 config_service.Pass(),
[email protected]d7b9a2b2012-05-31 22:31:19455 dns_client.Pass(),
[email protected]0f292de02012-02-01 22:28:20456 net_log);
457
458 return resolver;
459}
460
461} // anonymous namespace
462
463//-----------------------------------------------------------------------------
464
465HostResolver* CreateSystemHostResolver(size_t max_concurrent_resolves,
466 size_t max_retry_attempts,
467 NetLog* net_log) {
468 return CreateHostResolver(max_concurrent_resolves,
469 max_retry_attempts,
[email protected]b3601bc22012-02-21 21:23:20470 HostCache::CreateDefaultCache(),
[email protected]d7b9a2b2012-05-31 22:31:19471 DnsConfigService::CreateSystemService(),
472 scoped_ptr<DnsClient>(NULL),
[email protected]0f292de02012-02-01 22:28:20473 net_log);
474}
475
476HostResolver* CreateNonCachingSystemHostResolver(size_t max_concurrent_resolves,
477 size_t max_retry_attempts,
478 NetLog* net_log) {
479 return CreateHostResolver(max_concurrent_resolves,
480 max_retry_attempts,
[email protected]b3601bc22012-02-21 21:23:20481 NULL,
482 scoped_ptr<DnsConfigService>(NULL),
[email protected]d7b9a2b2012-05-31 22:31:19483 scoped_ptr<DnsClient>(NULL),
[email protected]b3601bc22012-02-21 21:23:20484 net_log);
485}
486
487HostResolver* CreateAsyncHostResolver(size_t max_concurrent_resolves,
488 size_t max_retry_attempts,
489 NetLog* net_log) {
[email protected]b3601bc22012-02-21 21:23:20490 return CreateHostResolver(max_concurrent_resolves,
491 max_retry_attempts,
492 HostCache::CreateDefaultCache(),
[email protected]d7b9a2b2012-05-31 22:31:19493 DnsConfigService::CreateSystemService(),
494 DnsClient::CreateClient(net_log),
[email protected]0f292de02012-02-01 22:28:20495 net_log);
496}
497
498//-----------------------------------------------------------------------------
499
500// Holds the data for a request that could not be completed synchronously.
501// It is owned by a Job. Canceled Requests are only marked as canceled rather
502// than removed from the Job's |requests_| list.
[email protected]b59ff372009-07-15 22:04:32503class HostResolverImpl::Request {
504 public:
[email protected]ee094b82010-08-24 15:55:51505 Request(const BoundNetLog& source_net_log,
506 const BoundNetLog& request_net_log,
[email protected]54e13772009-08-14 03:01:09507 const RequestInfo& info,
[email protected]aa22b242011-11-16 18:58:29508 const CompletionCallback& callback,
[email protected]b59ff372009-07-15 22:04:32509 AddressList* addresses)
[email protected]ee094b82010-08-24 15:55:51510 : source_net_log_(source_net_log),
511 request_net_log_(request_net_log),
[email protected]54e13772009-08-14 03:01:09512 info_(info),
513 job_(NULL),
514 callback_(callback),
515 addresses_(addresses) {
516 }
[email protected]b59ff372009-07-15 22:04:32517
[email protected]0f292de02012-02-01 22:28:20518 // Mark the request as canceled.
519 void MarkAsCanceled() {
[email protected]b59ff372009-07-15 22:04:32520 job_ = NULL;
[email protected]b59ff372009-07-15 22:04:32521 addresses_ = NULL;
[email protected]aa22b242011-11-16 18:58:29522 callback_.Reset();
[email protected]b59ff372009-07-15 22:04:32523 }
524
[email protected]0f292de02012-02-01 22:28:20525 bool was_canceled() const {
[email protected]aa22b242011-11-16 18:58:29526 return callback_.is_null();
[email protected]b59ff372009-07-15 22:04:32527 }
528
529 void set_job(Job* job) {
[email protected]0f292de02012-02-01 22:28:20530 DCHECK(job);
[email protected]b59ff372009-07-15 22:04:32531 // Identify which job the request is waiting on.
532 job_ = job;
533 }
534
[email protected]0f292de02012-02-01 22:28:20535 // Prepare final AddressList and call completion callback.
[email protected]b3601bc22012-02-21 21:23:20536 void OnComplete(int error, const AddressList& addr_list) {
[email protected]7054e78f2012-05-07 21:44:56537 if (error == OK) {
538 *addresses_ = addr_list;
539 EnsurePortOnAddressList(info_.port(), addresses_);
540 }
[email protected]aa22b242011-11-16 18:58:29541 CompletionCallback callback = callback_;
[email protected]0f292de02012-02-01 22:28:20542 MarkAsCanceled();
[email protected]aa22b242011-11-16 18:58:29543 callback.Run(error);
[email protected]b59ff372009-07-15 22:04:32544 }
545
[email protected]b59ff372009-07-15 22:04:32546 Job* job() const {
547 return job_;
548 }
549
[email protected]0f292de02012-02-01 22:28:20550 // NetLog for the source, passed in HostResolver::Resolve.
[email protected]ee094b82010-08-24 15:55:51551 const BoundNetLog& source_net_log() {
552 return source_net_log_;
553 }
554
[email protected]0f292de02012-02-01 22:28:20555 // NetLog for this request.
[email protected]ee094b82010-08-24 15:55:51556 const BoundNetLog& request_net_log() {
557 return request_net_log_;
[email protected]54e13772009-08-14 03:01:09558 }
559
[email protected]b59ff372009-07-15 22:04:32560 const RequestInfo& info() const {
561 return info_;
562 }
563
564 private:
[email protected]ee094b82010-08-24 15:55:51565 BoundNetLog source_net_log_;
566 BoundNetLog request_net_log_;
[email protected]54e13772009-08-14 03:01:09567
[email protected]b59ff372009-07-15 22:04:32568 // The request info that started the request.
569 RequestInfo info_;
570
[email protected]0f292de02012-02-01 22:28:20571 // The resolve job that this request is dependent on.
[email protected]b59ff372009-07-15 22:04:32572 Job* job_;
573
574 // The user's callback to invoke when the request completes.
[email protected]aa22b242011-11-16 18:58:29575 CompletionCallback callback_;
[email protected]b59ff372009-07-15 22:04:32576
577 // The address list to save result into.
578 AddressList* addresses_;
579
580 DISALLOW_COPY_AND_ASSIGN(Request);
581};
582
[email protected]1e9bbd22010-10-15 16:42:45583//------------------------------------------------------------------------------
584
585// Provide a common macro to simplify code and readability. We must use a
586// macros as the underlying HISTOGRAM macro creates static varibles.
587#define DNS_HISTOGRAM(name, time) UMA_HISTOGRAM_CUSTOM_TIMES(name, time, \
588 base::TimeDelta::FromMicroseconds(1), base::TimeDelta::FromHours(1), 100)
[email protected]b59ff372009-07-15 22:04:32589
[email protected]0f292de02012-02-01 22:28:20590// Calls HostResolverProc on the WorkerPool. Performs retries if necessary.
591//
592// Whenever we try to resolve the host, we post a delayed task to check if host
593// resolution (OnLookupComplete) is completed or not. If the original attempt
594// hasn't completed, then we start another attempt for host resolution. We take
595// the results from the first attempt that finishes and ignore the results from
596// all other attempts.
597//
598// TODO(szym): Move to separate source file for testing and mocking.
599//
600class HostResolverImpl::ProcTask
601 : public base::RefCountedThreadSafe<HostResolverImpl::ProcTask> {
[email protected]b59ff372009-07-15 22:04:32602 public:
[email protected]b3601bc22012-02-21 21:23:20603 typedef base::Callback<void(int net_error,
604 const AddressList& addr_list)> Callback;
[email protected]b59ff372009-07-15 22:04:32605
[email protected]0f292de02012-02-01 22:28:20606 ProcTask(const Key& key,
607 const ProcTaskParams& params,
608 const Callback& callback,
609 const BoundNetLog& job_net_log)
610 : key_(key),
611 params_(params),
612 callback_(callback),
613 origin_loop_(base::MessageLoopProxy::current()),
614 attempt_number_(0),
615 completed_attempt_number_(0),
616 completed_attempt_error_(ERR_UNEXPECTED),
617 had_non_speculative_request_(false),
[email protected]b3601bc22012-02-21 21:23:20618 net_log_(job_net_log) {
[email protected]0f292de02012-02-01 22:28:20619 if (!params_.resolver_proc)
620 params_.resolver_proc = HostResolverProc::GetDefault();
621 // If default is unset, use the system proc.
622 if (!params_.resolver_proc)
623 params_.resolver_proc = new CallSystemHostResolverProc();
[email protected]b59ff372009-07-15 22:04:32624 }
625
[email protected]b59ff372009-07-15 22:04:32626 void Start() {
[email protected]3e9d9cc2011-05-03 21:08:15627 DCHECK(origin_loop_->BelongsToCurrentThread());
[email protected]9c571762012-02-27 19:12:40628 net_log_.BeginEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK, NULL);
[email protected]189163e2011-05-11 01:48:54629 StartLookupAttempt();
630 }
[email protected]252b699b2010-02-05 21:38:06631
[email protected]0f292de02012-02-01 22:28:20632 // Cancels this ProcTask. It will be orphaned. Any outstanding resolve
633 // attempts running on worker threads will continue running. Only once all the
634 // attempts complete will the final reference to this ProcTask be released.
635 void Cancel() {
636 DCHECK(origin_loop_->BelongsToCurrentThread());
637
638 if (was_canceled())
639 return;
640
[email protected]0f292de02012-02-01 22:28:20641 callback_.Reset();
[email protected]0f292de02012-02-01 22:28:20642 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK, NULL);
643 }
644
645 void set_had_non_speculative_request() {
646 DCHECK(origin_loop_->BelongsToCurrentThread());
647 had_non_speculative_request_ = true;
648 }
649
650 bool was_canceled() const {
651 DCHECK(origin_loop_->BelongsToCurrentThread());
652 return callback_.is_null();
653 }
654
655 bool was_completed() const {
656 DCHECK(origin_loop_->BelongsToCurrentThread());
657 return completed_attempt_number_ > 0;
658 }
659
660 private:
[email protected]a9813302012-04-28 09:29:28661 friend class base::RefCountedThreadSafe<ProcTask>;
662 ~ProcTask() {}
663
[email protected]189163e2011-05-11 01:48:54664 void StartLookupAttempt() {
665 DCHECK(origin_loop_->BelongsToCurrentThread());
666 base::TimeTicks start_time = base::TimeTicks::Now();
667 ++attempt_number_;
668 // Dispatch the lookup attempt to a worker thread.
669 if (!base::WorkerPool::PostTask(
670 FROM_HERE,
[email protected]0f292de02012-02-01 22:28:20671 base::Bind(&ProcTask::DoLookup, this, start_time, attempt_number_),
[email protected]189163e2011-05-11 01:48:54672 true)) {
[email protected]b59ff372009-07-15 22:04:32673 NOTREACHED();
674
675 // Since we could be running within Resolve() right now, we can't just
676 // call OnLookupComplete(). Instead we must wait until Resolve() has
677 // returned (IO_PENDING).
[email protected]3e9d9cc2011-05-03 21:08:15678 origin_loop_->PostTask(
[email protected]189163e2011-05-11 01:48:54679 FROM_HERE,
[email protected]0f292de02012-02-01 22:28:20680 base::Bind(&ProcTask::OnLookupComplete, this, AddressList(),
[email protected]33152acc2011-10-20 23:37:12681 start_time, attempt_number_, ERR_UNEXPECTED, 0));
[email protected]189163e2011-05-11 01:48:54682 return;
[email protected]b59ff372009-07-15 22:04:32683 }
[email protected]13024882011-05-18 23:19:16684
685 net_log_.AddEvent(
686 NetLog::TYPE_HOST_RESOLVER_IMPL_ATTEMPT_STARTED,
687 make_scoped_refptr(new NetLogIntegerParameter(
688 "attempt_number", attempt_number_)));
689
[email protected]0f292de02012-02-01 22:28:20690 // If we don't get the results within a given time, RetryIfNotComplete
691 // will start a new attempt on a different worker thread if none of our
692 // outstanding attempts have completed yet.
693 if (attempt_number_ <= params_.max_retry_attempts) {
[email protected]06ef6d92011-05-19 04:24:58694 origin_loop_->PostDelayedTask(
695 FROM_HERE,
[email protected]0f292de02012-02-01 22:28:20696 base::Bind(&ProcTask::RetryIfNotComplete, this),
[email protected]7e560102012-03-08 20:58:42697 params_.unresponsive_delay);
[email protected]06ef6d92011-05-19 04:24:58698 }
[email protected]b59ff372009-07-15 22:04:32699 }
700
[email protected]6c710ee2010-05-07 07:51:16701 // WARNING: This code runs inside a worker pool. The shutdown code cannot
702 // wait for it to finish, so we must be very careful here about using other
703 // objects (like MessageLoops, Singletons, etc). During shutdown these objects
[email protected]189163e2011-05-11 01:48:54704 // may no longer exist. Multiple DoLookups() could be running in parallel, so
705 // any state inside of |this| must not mutate .
706 void DoLookup(const base::TimeTicks& start_time,
707 const uint32 attempt_number) {
708 AddressList results;
709 int os_error = 0;
[email protected]b59ff372009-07-15 22:04:32710 // Running on the worker thread
[email protected]0f292de02012-02-01 22:28:20711 int error = params_.resolver_proc->Resolve(key_.hostname,
712 key_.address_family,
713 key_.host_resolver_flags,
714 &results,
715 &os_error);
[email protected]b59ff372009-07-15 22:04:32716
[email protected]189163e2011-05-11 01:48:54717 origin_loop_->PostTask(
718 FROM_HERE,
[email protected]0f292de02012-02-01 22:28:20719 base::Bind(&ProcTask::OnLookupComplete, this, results, start_time,
[email protected]33152acc2011-10-20 23:37:12720 attempt_number, error, os_error));
[email protected]189163e2011-05-11 01:48:54721 }
722
[email protected]0f292de02012-02-01 22:28:20723 // Makes next attempt if DoLookup() has not finished (runs on origin thread).
724 void RetryIfNotComplete() {
[email protected]189163e2011-05-11 01:48:54725 DCHECK(origin_loop_->BelongsToCurrentThread());
726
[email protected]0f292de02012-02-01 22:28:20727 if (was_completed() || was_canceled())
[email protected]189163e2011-05-11 01:48:54728 return;
729
[email protected]0f292de02012-02-01 22:28:20730 params_.unresponsive_delay *= params_.retry_factor;
[email protected]189163e2011-05-11 01:48:54731 StartLookupAttempt();
[email protected]b59ff372009-07-15 22:04:32732 }
733
734 // Callback for when DoLookup() completes (runs on origin thread).
[email protected]189163e2011-05-11 01:48:54735 void OnLookupComplete(const AddressList& results,
736 const base::TimeTicks& start_time,
737 const uint32 attempt_number,
738 int error,
739 const int os_error) {
[email protected]3e9d9cc2011-05-03 21:08:15740 DCHECK(origin_loop_->BelongsToCurrentThread());
[email protected]7054e78f2012-05-07 21:44:56741 DCHECK(error || !results.empty());
[email protected]189163e2011-05-11 01:48:54742
743 bool was_retry_attempt = attempt_number > 1;
744
[email protected]2d3b7762010-10-09 00:35:47745 // Ideally the following code would be part of host_resolver_proc.cc,
[email protected]b3601bc22012-02-21 21:23:20746 // however it isn't safe to call NetworkChangeNotifier from worker threads.
747 // So we do it here on the IO thread instead.
[email protected]189163e2011-05-11 01:48:54748 if (error != OK && NetworkChangeNotifier::IsOffline())
749 error = ERR_INTERNET_DISCONNECTED;
[email protected]2d3b7762010-10-09 00:35:47750
[email protected]b3601bc22012-02-21 21:23:20751 // If this is the first attempt that is finishing later, then record data
752 // for the first attempt. Won't contaminate with retry attempt's data.
[email protected]189163e2011-05-11 01:48:54753 if (!was_retry_attempt)
754 RecordPerformanceHistograms(start_time, error, os_error);
755
756 RecordAttemptHistograms(start_time, attempt_number, error, os_error);
[email protected]f2d8c4212010-02-02 00:56:35757
[email protected]0f292de02012-02-01 22:28:20758 if (was_canceled())
[email protected]b59ff372009-07-15 22:04:32759 return;
760
[email protected]0f292de02012-02-01 22:28:20761 scoped_refptr<NetLog::EventParameters> params;
762 if (error != OK) {
[email protected]b3601bc22012-02-21 21:23:20763 params = new ProcTaskFailedParams(attempt_number, error, os_error);
[email protected]0f292de02012-02-01 22:28:20764 } else {
[email protected]53b583b2012-02-09 00:10:47765 params = new NetLogIntegerParameter("attempt_number", attempt_number);
[email protected]0f292de02012-02-01 22:28:20766 }
767 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_ATTEMPT_FINISHED, params);
768
769 if (was_completed())
770 return;
771
772 // Copy the results from the first worker thread that resolves the host.
773 results_ = results;
774 completed_attempt_number_ = attempt_number;
775 completed_attempt_error_ = error;
776
[email protected]e87b8b512011-06-14 22:12:52777 if (was_retry_attempt) {
778 // If retry attempt finishes before 1st attempt, then get stats on how
779 // much time is saved by having spawned an extra attempt.
780 retry_attempt_finished_time_ = base::TimeTicks::Now();
781 }
782
[email protected]189163e2011-05-11 01:48:54783 if (error != OK) {
[email protected]b3601bc22012-02-21 21:23:20784 params = new ProcTaskFailedParams(0, error, os_error);
[email protected]ee094b82010-08-24 15:55:51785 } else {
786 params = new AddressListNetLogParam(results_);
787 }
[email protected]0f292de02012-02-01 22:28:20788 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK, params);
[email protected]ee094b82010-08-24 15:55:51789
[email protected]b3601bc22012-02-21 21:23:20790 callback_.Run(error, results_);
[email protected]b59ff372009-07-15 22:04:32791 }
792
[email protected]189163e2011-05-11 01:48:54793 void RecordPerformanceHistograms(const base::TimeTicks& start_time,
794 const int error,
795 const int os_error) const {
[email protected]3e9d9cc2011-05-03 21:08:15796 DCHECK(origin_loop_->BelongsToCurrentThread());
[email protected]1e9bbd22010-10-15 16:42:45797 enum Category { // Used in HISTOGRAM_ENUMERATION.
798 RESOLVE_SUCCESS,
799 RESOLVE_FAIL,
800 RESOLVE_SPECULATIVE_SUCCESS,
801 RESOLVE_SPECULATIVE_FAIL,
802 RESOLVE_MAX, // Bounding value.
803 };
804 int category = RESOLVE_MAX; // Illegal value for later DCHECK only.
805
[email protected]189163e2011-05-11 01:48:54806 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
807 if (error == OK) {
[email protected]1e9bbd22010-10-15 16:42:45808 if (had_non_speculative_request_) {
809 category = RESOLVE_SUCCESS;
810 DNS_HISTOGRAM("DNS.ResolveSuccess", duration);
811 } else {
812 category = RESOLVE_SPECULATIVE_SUCCESS;
813 DNS_HISTOGRAM("DNS.ResolveSpeculativeSuccess", duration);
814 }
[email protected]7e96d792011-06-10 17:08:23815
[email protected]78eac2a2012-03-14 19:09:27816 // Log DNS lookups based on |address_family|. This will help us determine
[email protected]7e96d792011-06-10 17:08:23817 // if IPv4 or IPv4/6 lookups are faster or slower.
818 switch(key_.address_family) {
819 case ADDRESS_FAMILY_IPV4:
820 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_IPV4", duration);
821 break;
822 case ADDRESS_FAMILY_IPV6:
823 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_IPV6", duration);
824 break;
825 case ADDRESS_FAMILY_UNSPECIFIED:
826 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_UNSPEC", duration);
827 break;
828 }
[email protected]1e9bbd22010-10-15 16:42:45829 } else {
830 if (had_non_speculative_request_) {
831 category = RESOLVE_FAIL;
832 DNS_HISTOGRAM("DNS.ResolveFail", duration);
833 } else {
834 category = RESOLVE_SPECULATIVE_FAIL;
835 DNS_HISTOGRAM("DNS.ResolveSpeculativeFail", duration);
836 }
[email protected]78eac2a2012-03-14 19:09:27837 // Log DNS lookups based on |address_family|. This will help us determine
[email protected]7e96d792011-06-10 17:08:23838 // if IPv4 or IPv4/6 lookups are faster or slower.
839 switch(key_.address_family) {
840 case ADDRESS_FAMILY_IPV4:
841 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_IPV4", duration);
842 break;
843 case ADDRESS_FAMILY_IPV6:
844 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_IPV6", duration);
845 break;
846 case ADDRESS_FAMILY_UNSPECIFIED:
847 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_UNSPEC", duration);
848 break;
849 }
[email protected]c833e322010-10-16 23:51:36850 UMA_HISTOGRAM_CUSTOM_ENUMERATION(kOSErrorsForGetAddrinfoHistogramName,
[email protected]189163e2011-05-11 01:48:54851 std::abs(os_error),
[email protected]1e9bbd22010-10-15 16:42:45852 GetAllGetAddrinfoOSErrors());
853 }
[email protected]051b6ab2010-10-18 16:50:46854 DCHECK_LT(category, static_cast<int>(RESOLVE_MAX)); // Be sure it was set.
[email protected]1e9bbd22010-10-15 16:42:45855
856 UMA_HISTOGRAM_ENUMERATION("DNS.ResolveCategory", category, RESOLVE_MAX);
857
[email protected]edafd4c2011-05-10 17:18:53858 static const bool show_speculative_experiment_histograms =
859 base::FieldTrialList::TrialExists("DnsImpact");
[email protected]ecd95ae2010-10-20 23:58:17860 if (show_speculative_experiment_histograms) {
[email protected]1e9bbd22010-10-15 16:42:45861 UMA_HISTOGRAM_ENUMERATION(
862 base::FieldTrial::MakeName("DNS.ResolveCategory", "DnsImpact"),
863 category, RESOLVE_MAX);
864 if (RESOLVE_SUCCESS == category) {
865 DNS_HISTOGRAM(base::FieldTrial::MakeName("DNS.ResolveSuccess",
866 "DnsImpact"), duration);
867 }
868 }
[email protected]edafd4c2011-05-10 17:18:53869 static const bool show_parallelism_experiment_histograms =
870 base::FieldTrialList::TrialExists("DnsParallelism");
[email protected]ecd95ae2010-10-20 23:58:17871 if (show_parallelism_experiment_histograms) {
872 UMA_HISTOGRAM_ENUMERATION(
873 base::FieldTrial::MakeName("DNS.ResolveCategory", "DnsParallelism"),
874 category, RESOLVE_MAX);
875 if (RESOLVE_SUCCESS == category) {
876 DNS_HISTOGRAM(base::FieldTrial::MakeName("DNS.ResolveSuccess",
877 "DnsParallelism"), duration);
878 }
879 }
[email protected]1e9bbd22010-10-15 16:42:45880 }
881
[email protected]189163e2011-05-11 01:48:54882 void RecordAttemptHistograms(const base::TimeTicks& start_time,
883 const uint32 attempt_number,
884 const int error,
885 const int os_error) const {
[email protected]0f292de02012-02-01 22:28:20886 DCHECK(origin_loop_->BelongsToCurrentThread());
[email protected]189163e2011-05-11 01:48:54887 bool first_attempt_to_complete =
888 completed_attempt_number_ == attempt_number;
[email protected]e87b8b512011-06-14 22:12:52889 bool is_first_attempt = (attempt_number == 1);
[email protected]1e9bbd22010-10-15 16:42:45890
[email protected]189163e2011-05-11 01:48:54891 if (first_attempt_to_complete) {
892 // If this was first attempt to complete, then record the resolution
893 // status of the attempt.
894 if (completed_attempt_error_ == OK) {
895 UMA_HISTOGRAM_ENUMERATION(
896 "DNS.AttemptFirstSuccess", attempt_number, 100);
897 } else {
898 UMA_HISTOGRAM_ENUMERATION(
899 "DNS.AttemptFirstFailure", attempt_number, 100);
900 }
901 }
902
903 if (error == OK)
904 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptSuccess", attempt_number, 100);
905 else
906 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptFailure", attempt_number, 100);
907
[email protected]e87b8b512011-06-14 22:12:52908 // If first attempt didn't finish before retry attempt, then calculate stats
909 // on how much time is saved by having spawned an extra attempt.
[email protected]0f292de02012-02-01 22:28:20910 if (!first_attempt_to_complete && is_first_attempt && !was_canceled()) {
[email protected]e87b8b512011-06-14 22:12:52911 DNS_HISTOGRAM("DNS.AttemptTimeSavedByRetry",
912 base::TimeTicks::Now() - retry_attempt_finished_time_);
913 }
914
[email protected]0f292de02012-02-01 22:28:20915 if (was_canceled() || !first_attempt_to_complete) {
[email protected]189163e2011-05-11 01:48:54916 // Count those attempts which completed after the job was already canceled
917 // OR after the job was already completed by an earlier attempt (so in
918 // effect).
919 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptDiscarded", attempt_number, 100);
920
[email protected]0f292de02012-02-01 22:28:20921 // Record if job is canceled.
922 if (was_canceled())
[email protected]189163e2011-05-11 01:48:54923 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptCancelled", attempt_number, 100);
924 }
925
926 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
927 if (error == OK)
928 DNS_HISTOGRAM("DNS.AttemptSuccessDuration", duration);
929 else
930 DNS_HISTOGRAM("DNS.AttemptFailDuration", duration);
931 }
[email protected]1e9bbd22010-10-15 16:42:45932
[email protected]b59ff372009-07-15 22:04:32933 // Set on the origin thread, read on the worker thread.
[email protected]123ab1e32009-10-21 19:12:57934 Key key_;
[email protected]b59ff372009-07-15 22:04:32935
[email protected]0f292de02012-02-01 22:28:20936 // Holds an owning reference to the HostResolverProc that we are going to use.
[email protected]b59ff372009-07-15 22:04:32937 // This may not be the current resolver procedure by the time we call
938 // ResolveAddrInfo, but that's OK... we'll use it anyways, and the owning
939 // reference ensures that it remains valid until we are done.
[email protected]0f292de02012-02-01 22:28:20940 ProcTaskParams params_;
[email protected]b59ff372009-07-15 22:04:32941
[email protected]0f292de02012-02-01 22:28:20942 // The listener to the results of this ProcTask.
943 Callback callback_;
944
945 // Used to post ourselves onto the origin thread.
946 scoped_refptr<base::MessageLoopProxy> origin_loop_;
[email protected]189163e2011-05-11 01:48:54947
948 // Keeps track of the number of attempts we have made so far to resolve the
949 // host. Whenever we start an attempt to resolve the host, we increase this
950 // number.
951 uint32 attempt_number_;
952
953 // The index of the attempt which finished first (or 0 if the job is still in
954 // progress).
955 uint32 completed_attempt_number_;
956
957 // The result (a net error code) from the first attempt to complete.
958 int completed_attempt_error_;
[email protected]252b699b2010-02-05 21:38:06959
[email protected]e87b8b512011-06-14 22:12:52960 // The time when retry attempt was finished.
961 base::TimeTicks retry_attempt_finished_time_;
962
[email protected]252b699b2010-02-05 21:38:06963 // True if a non-speculative request was ever attached to this job
[email protected]0f292de02012-02-01 22:28:20964 // (regardless of whether or not it was later canceled.
[email protected]252b699b2010-02-05 21:38:06965 // This boolean is used for histogramming the duration of jobs used to
966 // service non-speculative requests.
967 bool had_non_speculative_request_;
968
[email protected]b59ff372009-07-15 22:04:32969 AddressList results_;
970
[email protected]ee094b82010-08-24 15:55:51971 BoundNetLog net_log_;
972
[email protected]0f292de02012-02-01 22:28:20973 DISALLOW_COPY_AND_ASSIGN(ProcTask);
[email protected]b59ff372009-07-15 22:04:32974};
975
976//-----------------------------------------------------------------------------
977
[email protected]0f292de02012-02-01 22:28:20978// Represents a request to the worker pool for a "probe for IPv6 support" call.
[email protected]b3601bc22012-02-21 21:23:20979//
980// TODO(szym): This could also be replaced with PostTaskAndReply and Callbacks.
[email protected]0f8f1b432010-03-16 19:06:03981class HostResolverImpl::IPv6ProbeJob
982 : public base::RefCountedThreadSafe<HostResolverImpl::IPv6ProbeJob> {
983 public:
984 explicit IPv6ProbeJob(HostResolverImpl* resolver)
985 : resolver_(resolver),
[email protected]edd685f2011-08-15 20:33:46986 origin_loop_(base::MessageLoopProxy::current()) {
[email protected]3e9d9cc2011-05-03 21:08:15987 DCHECK(resolver);
[email protected]0f8f1b432010-03-16 19:06:03988 }
989
990 void Start() {
[email protected]3e9d9cc2011-05-03 21:08:15991 DCHECK(origin_loop_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:20992 if (was_canceled())
[email protected]a9af7112010-05-08 00:56:01993 return;
[email protected]f092e64b2010-03-17 00:39:18994 const bool kIsSlow = true;
[email protected]ac9ba8fe2010-12-30 18:08:36995 base::WorkerPool::PostTask(
[email protected]33152acc2011-10-20 23:37:12996 FROM_HERE, base::Bind(&IPv6ProbeJob::DoProbe, this), kIsSlow);
[email protected]0f8f1b432010-03-16 19:06:03997 }
998
999 // Cancels the current job.
1000 void Cancel() {
[email protected]3e9d9cc2011-05-03 21:08:151001 DCHECK(origin_loop_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:201002 if (was_canceled())
[email protected]a9af7112010-05-08 00:56:011003 return;
[email protected]0f8f1b432010-03-16 19:06:031004 resolver_ = NULL; // Read/write ONLY on origin thread.
[email protected]0f8f1b432010-03-16 19:06:031005 }
1006
[email protected]0f8f1b432010-03-16 19:06:031007 private:
1008 friend class base::RefCountedThreadSafe<HostResolverImpl::IPv6ProbeJob>;
1009
1010 ~IPv6ProbeJob() {
1011 }
1012
[email protected]0f292de02012-02-01 22:28:201013 bool was_canceled() const {
[email protected]3e9d9cc2011-05-03 21:08:151014 DCHECK(origin_loop_->BelongsToCurrentThread());
1015 return !resolver_;
[email protected]a9af7112010-05-08 00:56:011016 }
1017
[email protected]0f8f1b432010-03-16 19:06:031018 // Run on worker thread.
1019 void DoProbe() {
1020 // Do actual testing on this thread, as it takes 40-100ms.
1021 AddressFamily family = IPv6Supported() ? ADDRESS_FAMILY_UNSPECIFIED
1022 : ADDRESS_FAMILY_IPV4;
1023
[email protected]3e9d9cc2011-05-03 21:08:151024 origin_loop_->PostTask(
1025 FROM_HERE,
[email protected]33152acc2011-10-20 23:37:121026 base::Bind(&IPv6ProbeJob::OnProbeComplete, this, family));
[email protected]0f8f1b432010-03-16 19:06:031027 }
1028
[email protected]3e9d9cc2011-05-03 21:08:151029 // Callback for when DoProbe() completes.
[email protected]0f8f1b432010-03-16 19:06:031030 void OnProbeComplete(AddressFamily address_family) {
[email protected]3e9d9cc2011-05-03 21:08:151031 DCHECK(origin_loop_->BelongsToCurrentThread());
[email protected]0f292de02012-02-01 22:28:201032 if (was_canceled())
[email protected]a9af7112010-05-08 00:56:011033 return;
[email protected]a9af7112010-05-08 00:56:011034 resolver_->IPv6ProbeSetDefaultAddressFamily(address_family);
[email protected]0f8f1b432010-03-16 19:06:031035 }
1036
[email protected]0f8f1b432010-03-16 19:06:031037 // Used/set only on origin thread.
1038 HostResolverImpl* resolver_;
1039
1040 // Used to post ourselves onto the origin thread.
[email protected]3e9d9cc2011-05-03 21:08:151041 scoped_refptr<base::MessageLoopProxy> origin_loop_;
[email protected]0f8f1b432010-03-16 19:06:031042
1043 DISALLOW_COPY_AND_ASSIGN(IPv6ProbeJob);
1044};
1045
1046//-----------------------------------------------------------------------------
1047
[email protected]b3601bc22012-02-21 21:23:201048// Resolves the hostname using DnsTransaction.
1049// TODO(szym): This could be moved to separate source file as well.
1050class HostResolverImpl::DnsTask {
1051 public:
1052 typedef base::Callback<void(int net_error,
1053 const AddressList& addr_list,
1054 base::TimeDelta ttl)> Callback;
1055
1056 DnsTask(DnsTransactionFactory* factory,
1057 const Key& key,
1058 const Callback& callback,
1059 const BoundNetLog& job_net_log)
1060 : callback_(callback), net_log_(job_net_log) {
1061 DCHECK(factory);
1062 DCHECK(!callback.is_null());
1063
1064 // For now we treat ADDRESS_FAMILY_UNSPEC as if it was IPV4.
1065 uint16 qtype = (key.address_family == ADDRESS_FAMILY_IPV6)
1066 ? dns_protocol::kTypeAAAA
1067 : dns_protocol::kTypeA;
1068 // TODO(szym): Implement "happy eyeballs".
1069 transaction_ = factory->CreateTransaction(
1070 key.hostname,
1071 qtype,
[email protected]1def74c2012-03-22 20:07:001072 base::Bind(&DnsTask::OnTransactionComplete, base::Unretained(this),
1073 base::TimeTicks::Now()),
[email protected]b3601bc22012-02-21 21:23:201074 net_log_);
1075 DCHECK(transaction_.get());
1076 }
1077
1078 int Start() {
1079 net_log_.BeginEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK, NULL);
1080 return transaction_->Start();
1081 }
1082
[email protected]1def74c2012-03-22 20:07:001083 void OnTransactionComplete(const base::TimeTicks& start_time,
1084 DnsTransaction* transaction,
[email protected]b3601bc22012-02-21 21:23:201085 int net_error,
1086 const DnsResponse* response) {
[email protected]add76532012-03-30 14:47:471087 DCHECK(transaction);
[email protected]b3601bc22012-02-21 21:23:201088 // Run |callback_| last since the owning Job will then delete this DnsTask.
1089 DnsResponse::Result result = DnsResponse::DNS_SUCCESS;
1090 if (net_error == OK) {
[email protected]add76532012-03-30 14:47:471091 CHECK(response);
[email protected]1def74c2012-03-22 20:07:001092 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess",
1093 base::TimeTicks::Now() - start_time);
[email protected]b3601bc22012-02-21 21:23:201094 AddressList addr_list;
1095 base::TimeDelta ttl;
1096 result = response->ParseToAddressList(&addr_list, &ttl);
[email protected]1def74c2012-03-22 20:07:001097 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ParseToAddressList",
1098 result,
1099 DnsResponse::DNS_PARSE_RESULT_MAX);
[email protected]b3601bc22012-02-21 21:23:201100 if (result == DnsResponse::DNS_SUCCESS) {
1101 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK,
1102 new AddressListNetLogParam(addr_list));
1103 callback_.Run(net_error, addr_list, ttl);
1104 return;
1105 }
1106 net_error = ERR_DNS_MALFORMED_RESPONSE;
[email protected]1def74c2012-03-22 20:07:001107 } else {
1108 DNS_HISTOGRAM("AsyncDNS.TransactionFailure",
1109 base::TimeTicks::Now() - start_time);
[email protected]b3601bc22012-02-21 21:23:201110 }
1111 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK,
1112 new DnsTaskFailedParams(net_error, result));
1113 callback_.Run(net_error, AddressList(), base::TimeDelta());
1114 }
1115
1116 private:
1117 // The listener to the results of this DnsTask.
1118 Callback callback_;
1119
1120 const BoundNetLog net_log_;
1121
1122 scoped_ptr<DnsTransaction> transaction_;
1123};
1124
1125//-----------------------------------------------------------------------------
1126
[email protected]0f292de02012-02-01 22:28:201127// Aggregates all Requests for the same Key. Dispatched via PriorityDispatch.
[email protected]0f292de02012-02-01 22:28:201128class HostResolverImpl::Job : public PrioritizedDispatcher::Job {
[email protected]68ad3ee2010-01-30 03:45:391129 public:
[email protected]0f292de02012-02-01 22:28:201130 // Creates new job for |key| where |request_net_log| is bound to the
[email protected]16ee26d2012-03-08 03:34:351131 // request that spawned it.
[email protected]0f292de02012-02-01 22:28:201132 Job(HostResolverImpl* resolver,
1133 const Key& key,
[email protected]16ee26d2012-03-08 03:34:351134 const BoundNetLog& request_net_log)
[email protected]0f292de02012-02-01 22:28:201135 : resolver_(resolver->AsWeakPtr()),
1136 key_(key),
1137 had_non_speculative_request_(false),
[email protected]1def74c2012-03-22 20:07:001138 had_dns_config_(false),
[email protected]0f292de02012-02-01 22:28:201139 net_log_(BoundNetLog::Make(request_net_log.net_log(),
[email protected]b3601bc22012-02-21 21:23:201140 NetLog::SOURCE_HOST_RESOLVER_IMPL_JOB)) {
[email protected]0f292de02012-02-01 22:28:201141 request_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_CREATE_JOB, NULL);
1142
1143 net_log_.BeginEvent(
1144 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
1145 make_scoped_refptr(new JobCreationParameters(
1146 key_.hostname, request_net_log.source())));
[email protected]68ad3ee2010-01-30 03:45:391147 }
1148
[email protected]0f292de02012-02-01 22:28:201149 virtual ~Job() {
[email protected]b3601bc22012-02-21 21:23:201150 if (is_running()) {
1151 // |resolver_| was destroyed with this Job still in flight.
1152 // Clean-up, record in the log, but don't run any callbacks.
1153 if (is_proc_running()) {
[email protected]0f292de02012-02-01 22:28:201154 proc_task_->Cancel();
1155 proc_task_ = NULL;
[email protected]0f292de02012-02-01 22:28:201156 }
[email protected]16ee26d2012-03-08 03:34:351157 // Clean up now for nice NetLog.
1158 dns_task_.reset(NULL);
[email protected]b3601bc22012-02-21 21:23:201159 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
1160 ERR_ABORTED);
1161 } else if (is_queued()) {
[email protected]57a48d32012-03-03 00:04:551162 // |resolver_| was destroyed without running this Job.
[email protected]16ee26d2012-03-08 03:34:351163 // TODO(szym): is there any benefit in having this distinction?
[email protected]b3601bc22012-02-21 21:23:201164 net_log_.AddEvent(NetLog::TYPE_CANCELLED, NULL);
1165 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB, NULL);
[email protected]68ad3ee2010-01-30 03:45:391166 }
[email protected]b3601bc22012-02-21 21:23:201167 // else CompleteRequests logged EndEvent.
[email protected]68ad3ee2010-01-30 03:45:391168
[email protected]b3601bc22012-02-21 21:23:201169 // Log any remaining Requests as cancelled.
1170 for (RequestsList::const_iterator it = requests_.begin();
1171 it != requests_.end(); ++it) {
1172 Request* req = *it;
1173 if (req->was_canceled())
1174 continue;
1175 DCHECK_EQ(this, req->job());
1176 LogCancelRequest(req->source_net_log(), req->request_net_log(),
1177 req->info());
1178 }
[email protected]68ad3ee2010-01-30 03:45:391179 }
1180
[email protected]16ee26d2012-03-08 03:34:351181 // Add this job to the dispatcher.
1182 void Schedule(RequestPriority priority) {
1183 handle_ = resolver_->dispatcher_.Add(this, priority);
1184 }
1185
[email protected]b3601bc22012-02-21 21:23:201186 void AddRequest(scoped_ptr<Request> req) {
[email protected]0f292de02012-02-01 22:28:201187 DCHECK_EQ(key_.hostname, req->info().hostname());
1188
1189 req->set_job(this);
[email protected]0f292de02012-02-01 22:28:201190 priority_tracker_.Add(req->info().priority());
1191
1192 req->request_net_log().AddEvent(
1193 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_ATTACH,
1194 make_scoped_refptr(new NetLogSourceParameter(
1195 "source_dependency", net_log_.source())));
1196
1197 net_log_.AddEvent(
1198 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_REQUEST_ATTACH,
1199 make_scoped_refptr(new JobAttachParameters(
1200 req->request_net_log().source(), priority())));
1201
1202 // TODO(szym): Check if this is still needed.
1203 if (!req->info().is_speculative()) {
1204 had_non_speculative_request_ = true;
1205 if (proc_task_)
1206 proc_task_->set_had_non_speculative_request();
[email protected]68ad3ee2010-01-30 03:45:391207 }
[email protected]b3601bc22012-02-21 21:23:201208
1209 requests_.push_back(req.release());
1210
[email protected]16ee26d2012-03-08 03:34:351211 if (is_queued())
[email protected]b3601bc22012-02-21 21:23:201212 handle_ = resolver_->dispatcher_.ChangePriority(handle_, priority());
[email protected]68ad3ee2010-01-30 03:45:391213 }
1214
[email protected]16ee26d2012-03-08 03:34:351215 // Marks |req| as cancelled. If it was the last active Request, also finishes
1216 // this Job marking it either as aborted or cancelled, and deletes it.
[email protected]0f292de02012-02-01 22:28:201217 void CancelRequest(Request* req) {
1218 DCHECK_EQ(key_.hostname, req->info().hostname());
1219 DCHECK(!req->was_canceled());
[email protected]16ee26d2012-03-08 03:34:351220
[email protected]0f292de02012-02-01 22:28:201221 // Don't remove it from |requests_| just mark it canceled.
1222 req->MarkAsCanceled();
1223 LogCancelRequest(req->source_net_log(), req->request_net_log(),
1224 req->info());
[email protected]16ee26d2012-03-08 03:34:351225
[email protected]0f292de02012-02-01 22:28:201226 priority_tracker_.Remove(req->info().priority());
1227 net_log_.AddEvent(
1228 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_REQUEST_DETACH,
1229 make_scoped_refptr(new JobAttachParameters(
1230 req->request_net_log().source(), priority())));
[email protected]b3601bc22012-02-21 21:23:201231
[email protected]16ee26d2012-03-08 03:34:351232 if (num_active_requests() > 0) {
1233 if (is_queued())
[email protected]b3601bc22012-02-21 21:23:201234 handle_ = resolver_->dispatcher_.ChangePriority(handle_, priority());
[email protected]16ee26d2012-03-08 03:34:351235 } else {
1236 // If we were called from a Request's callback within CompleteRequests,
1237 // that Request could not have been cancelled, so num_active_requests()
1238 // could not be 0. Therefore, we are not in CompleteRequests().
1239 CompleteRequests(OK, AddressList(), base::TimeDelta());
[email protected]b3601bc22012-02-21 21:23:201240 }
[email protected]68ad3ee2010-01-30 03:45:391241 }
1242
[email protected]16ee26d2012-03-08 03:34:351243 // Called from AbortAllInProgressJobs. Completes all requests as aborted
1244 // and destroys the job.
[email protected]0f292de02012-02-01 22:28:201245 void Abort() {
[email protected]0f292de02012-02-01 22:28:201246 DCHECK(is_running());
[email protected]b3601bc22012-02-21 21:23:201247 CompleteRequests(ERR_ABORTED, AddressList(), base::TimeDelta());
1248 }
1249
[email protected]16ee26d2012-03-08 03:34:351250 // Called by HostResolverImpl when this job is evicted due to queue overflow.
1251 // Completes all requests and destroys the job.
1252 void OnEvicted() {
1253 DCHECK(!is_running());
1254 DCHECK(is_queued());
1255 handle_.Reset();
1256
1257 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_EVICTED, NULL);
1258
1259 // This signals to CompleteRequests that this job never ran.
1260 CompleteRequests(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE,
1261 AddressList(),
1262 base::TimeDelta());
1263 }
1264
[email protected]78eac2a2012-03-14 19:09:271265 // Attempts to serve the job from HOSTS. Returns true if succeeded and
1266 // this Job was destroyed.
1267 bool ServeFromHosts() {
1268 DCHECK_GT(num_active_requests(), 0u);
1269 AddressList addr_list;
1270 if (resolver_->ServeFromHosts(key(),
[email protected]c143d892012-04-06 07:56:541271 requests_->front()->info(),
[email protected]78eac2a2012-03-14 19:09:271272 &addr_list)) {
1273 // This will destroy the Job.
1274 CompleteRequests(OK, addr_list, base::TimeDelta());
1275 return true;
1276 }
1277 return false;
1278 }
1279
[email protected]b4481b222012-03-16 17:13:111280 const Key key() const {
1281 return key_;
1282 }
1283
1284 bool is_queued() const {
1285 return !handle_.is_null();
1286 }
1287
1288 bool is_running() const {
1289 return is_dns_running() || is_proc_running();
1290 }
1291
[email protected]16ee26d2012-03-08 03:34:351292 private:
[email protected]16ee26d2012-03-08 03:34:351293 // PriorityDispatch::Job:
[email protected]0f292de02012-02-01 22:28:201294 virtual void Start() OVERRIDE {
1295 DCHECK(!is_running());
[email protected]b3601bc22012-02-21 21:23:201296 handle_.Reset();
[email protected]0f292de02012-02-01 22:28:201297
1298 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_STARTED, NULL);
1299
[email protected]1def74c2012-03-22 20:07:001300 had_dns_config_ = resolver_->HaveDnsConfig();
[email protected]16ee26d2012-03-08 03:34:351301 // Job::Start must not complete synchronously.
[email protected]1def74c2012-03-22 20:07:001302 if (had_dns_config_) {
[email protected]b3601bc22012-02-21 21:23:201303 StartDnsTask();
1304 } else {
1305 StartProcTask();
1306 }
1307 }
1308
[email protected]b3601bc22012-02-21 21:23:201309 // TODO(szym): Since DnsTransaction does not consume threads, we can increase
1310 // the limits on |dispatcher_|. But in order to keep the number of WorkerPool
1311 // threads low, we will need to use an "inner" PrioritizedDispatcher with
1312 // tighter limits.
1313 void StartProcTask() {
[email protected]16ee26d2012-03-08 03:34:351314 DCHECK(!is_dns_running());
[email protected]0f292de02012-02-01 22:28:201315 proc_task_ = new ProcTask(
1316 key_,
1317 resolver_->proc_params_,
1318 base::Bind(&Job::OnProcTaskComplete, base::Unretained(this)),
1319 net_log_);
1320
1321 if (had_non_speculative_request_)
1322 proc_task_->set_had_non_speculative_request();
1323 // Start() could be called from within Resolve(), hence it must NOT directly
1324 // call OnProcTaskComplete, for example, on synchronous failure.
1325 proc_task_->Start();
[email protected]68ad3ee2010-01-30 03:45:391326 }
1327
[email protected]0f292de02012-02-01 22:28:201328 // Called by ProcTask when it completes.
[email protected]b3601bc22012-02-21 21:23:201329 void OnProcTaskComplete(int net_error, const AddressList& addr_list) {
1330 DCHECK(is_proc_running());
[email protected]68ad3ee2010-01-30 03:45:391331
[email protected]1def74c2012-03-22 20:07:001332 if (had_dns_config_) {
1333 // TODO(szym): guess if the hostname is a NetBIOS name and discount it.
1334 if (net_error == OK) {
1335 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_PROC_SUCCESS);
1336 } else {
1337 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
1338 }
1339 }
1340
[email protected]b3601bc22012-02-21 21:23:201341 base::TimeDelta ttl = base::TimeDelta::FromSeconds(
1342 kNegativeCacheEntryTTLSeconds);
1343 if (net_error == OK)
1344 ttl = base::TimeDelta::FromSeconds(kCacheEntryTTLSeconds);
[email protected]68ad3ee2010-01-30 03:45:391345
[email protected]16ee26d2012-03-08 03:34:351346 CompleteRequests(net_error, addr_list, ttl);
[email protected]b3601bc22012-02-21 21:23:201347 }
1348
1349 void StartDnsTask() {
[email protected]78eac2a2012-03-14 19:09:271350 DCHECK(resolver_->HaveDnsConfig());
[email protected]b3601bc22012-02-21 21:23:201351 dns_task_.reset(new DnsTask(
[email protected]78eac2a2012-03-14 19:09:271352 resolver_->dns_client_->GetTransactionFactory(),
[email protected]b3601bc22012-02-21 21:23:201353 key_,
1354 base::Bind(&Job::OnDnsTaskComplete, base::Unretained(this)),
1355 net_log_));
1356
1357 int rv = dns_task_->Start();
1358 if (rv != ERR_IO_PENDING) {
1359 DCHECK_NE(OK, rv);
1360 dns_task_.reset();
1361 StartProcTask();
1362 }
1363 }
1364
1365 // Called by DnsTask when it completes.
1366 void OnDnsTaskComplete(int net_error,
1367 const AddressList& addr_list,
1368 base::TimeDelta ttl) {
1369 DCHECK(is_dns_running());
[email protected]b3601bc22012-02-21 21:23:201370
1371 if (net_error != OK) {
[email protected]16ee26d2012-03-08 03:34:351372 dns_task_.reset();
[email protected]78eac2a2012-03-14 19:09:271373
1374 // TODO(szym): Run ServeFromHosts now if nsswitch.conf says so.
1375 // http://crbug.com/117655
1376
[email protected]b3601bc22012-02-21 21:23:201377 // TODO(szym): Some net errors indicate lack of connectivity. Starting
1378 // ProcTask in that case is a waste of time.
1379 StartProcTask();
1380 return;
1381 }
1382
[email protected]1def74c2012-03-22 20:07:001383 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_DNS_SUCCESS);
[email protected]16ee26d2012-03-08 03:34:351384 CompleteRequests(net_error, addr_list, ttl);
[email protected]b3601bc22012-02-21 21:23:201385 }
1386
[email protected]16ee26d2012-03-08 03:34:351387 // Performs Job's last rites. Completes all Requests. Deletes this.
[email protected]b3601bc22012-02-21 21:23:201388 void CompleteRequests(int net_error,
1389 const AddressList& addr_list,
1390 base::TimeDelta ttl) {
1391 CHECK(resolver_);
[email protected]b3601bc22012-02-21 21:23:201392
[email protected]16ee26d2012-03-08 03:34:351393 // This job must be removed from resolver's |jobs_| now to make room for a
1394 // new job with the same key in case one of the OnComplete callbacks decides
1395 // to spawn one. Consequently, the job deletes itself when CompleteRequests
1396 // is done.
1397 scoped_ptr<Job> self_deleter(this);
1398
1399 resolver_->RemoveJob(this);
1400
1401 // |addr_list| will be destroyed once we destroy |proc_task_| and
1402 // |dns_task_|.
[email protected]b3601bc22012-02-21 21:23:201403 AddressList list = addr_list;
[email protected]16ee26d2012-03-08 03:34:351404
1405 if (is_running()) {
1406 DCHECK(!is_queued());
1407 if (is_proc_running()) {
1408 proc_task_->Cancel();
1409 proc_task_ = NULL;
1410 }
1411 dns_task_.reset();
1412
1413 // Signal dispatcher that a slot has opened.
1414 resolver_->dispatcher_.OnJobFinished();
1415 } else if (is_queued()) {
1416 resolver_->dispatcher_.Cancel(handle_);
1417 handle_.Reset();
1418 }
1419
1420 if (num_active_requests() == 0) {
1421 net_log_.AddEvent(NetLog::TYPE_CANCELLED, NULL);
1422 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
1423 OK);
1424 return;
1425 }
[email protected]b3601bc22012-02-21 21:23:201426
1427 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
1428 net_error);
[email protected]68ad3ee2010-01-30 03:45:391429
[email protected]78eac2a2012-03-14 19:09:271430 DCHECK(!requests_.empty());
1431
[email protected]d7b9a2b2012-05-31 22:31:191432 if (net_error == OK) {
[email protected]7054e78f2012-05-07 21:44:561433 SetPortOnAddressList(requests_->front()->info().port(), &list);
[email protected]d7b9a2b2012-05-31 22:31:191434 // Record this histogram here, when we know the system has a valid DNS
1435 // configuration.
1436 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.HaveDnsConfig",
1437 resolver_->received_dns_config_ ? 1 : 0,
1438 2);
1439 }
[email protected]16ee26d2012-03-08 03:34:351440
1441 if ((net_error != ERR_ABORTED) &&
1442 (net_error != ERR_HOST_RESOLVER_QUEUE_TOO_LARGE)) {
1443 resolver_->CacheResult(key_, net_error, list, ttl);
1444 }
1445
[email protected]0f292de02012-02-01 22:28:201446 // Complete all of the requests that were attached to the job.
1447 for (RequestsList::const_iterator it = requests_.begin();
1448 it != requests_.end(); ++it) {
1449 Request* req = *it;
1450
1451 if (req->was_canceled())
1452 continue;
1453
1454 DCHECK_EQ(this, req->job());
1455 // Update the net log and notify registered observers.
1456 LogFinishRequest(req->source_net_log(), req->request_net_log(),
[email protected]b3601bc22012-02-21 21:23:201457 req->info(), net_error);
[email protected]0f292de02012-02-01 22:28:201458
[email protected]b3601bc22012-02-21 21:23:201459 req->OnComplete(net_error, list);
[email protected]0f292de02012-02-01 22:28:201460
1461 // Check if the resolver was destroyed as a result of running the
1462 // callback. If it was, we could continue, but we choose to bail.
1463 if (!resolver_)
1464 return;
1465 }
1466 }
1467
[email protected]b4481b222012-03-16 17:13:111468 RequestPriority priority() const {
1469 return priority_tracker_.highest_priority();
1470 }
1471
1472 // Number of non-canceled requests in |requests_|.
1473 size_t num_active_requests() const {
1474 return priority_tracker_.total_count();
1475 }
1476
1477 bool is_dns_running() const {
1478 return dns_task_.get() != NULL;
1479 }
1480
1481 bool is_proc_running() const {
1482 return proc_task_.get() != NULL;
1483 }
1484
[email protected]0f292de02012-02-01 22:28:201485 base::WeakPtr<HostResolverImpl> resolver_;
1486
1487 Key key_;
1488
1489 // Tracks the highest priority across |requests_|.
1490 PriorityTracker priority_tracker_;
1491
1492 bool had_non_speculative_request_;
1493
[email protected]1def74c2012-03-22 20:07:001494 // True if resolver had DnsConfig when the Job was started.
1495 bool had_dns_config_;
1496
[email protected]0f292de02012-02-01 22:28:201497 BoundNetLog net_log_;
1498
[email protected]b3601bc22012-02-21 21:23:201499 // Resolves the host using a HostResolverProc.
[email protected]0f292de02012-02-01 22:28:201500 scoped_refptr<ProcTask> proc_task_;
1501
[email protected]b3601bc22012-02-21 21:23:201502 // Resolves the host using a DnsTransaction.
1503 scoped_ptr<DnsTask> dns_task_;
1504
[email protected]0f292de02012-02-01 22:28:201505 // All Requests waiting for the result of this Job. Some can be canceled.
1506 RequestsList requests_;
1507
[email protected]16ee26d2012-03-08 03:34:351508 // A handle used in |HostResolverImpl::dispatcher_|.
[email protected]0f292de02012-02-01 22:28:201509 PrioritizedDispatcher::Handle handle_;
[email protected]68ad3ee2010-01-30 03:45:391510};
1511
1512//-----------------------------------------------------------------------------
1513
[email protected]0f292de02012-02-01 22:28:201514HostResolverImpl::ProcTaskParams::ProcTaskParams(
[email protected]e95d3aca2010-01-11 22:47:431515 HostResolverProc* resolver_proc,
[email protected]0f292de02012-02-01 22:28:201516 size_t max_retry_attempts)
1517 : resolver_proc(resolver_proc),
1518 max_retry_attempts(max_retry_attempts),
1519 unresponsive_delay(base::TimeDelta::FromMilliseconds(6000)),
1520 retry_factor(2) {
1521}
1522
1523HostResolverImpl::ProcTaskParams::~ProcTaskParams() {}
1524
1525HostResolverImpl::HostResolverImpl(
[email protected]e95d3aca2010-01-11 22:47:431526 HostCache* cache,
[email protected]0f292de02012-02-01 22:28:201527 const PrioritizedDispatcher::Limits& job_limits,
1528 const ProcTaskParams& proc_params,
[email protected]b3601bc22012-02-21 21:23:201529 scoped_ptr<DnsConfigService> dns_config_service,
[email protected]d7b9a2b2012-05-31 22:31:191530 scoped_ptr<DnsClient> dns_client,
[email protected]ee094b82010-08-24 15:55:511531 NetLog* net_log)
[email protected]112bd462009-12-10 07:23:401532 : cache_(cache),
[email protected]0f292de02012-02-01 22:28:201533 dispatcher_(job_limits),
1534 max_queued_jobs_(job_limits.total_jobs * 100u),
1535 proc_params_(proc_params),
[email protected]0c7798452009-10-26 17:59:511536 default_address_family_(ADDRESS_FAMILY_UNSPECIFIED),
[email protected]b3601bc22012-02-21 21:23:201537 dns_config_service_(dns_config_service.Pass()),
[email protected]d7b9a2b2012-05-31 22:31:191538 dns_client_(dns_client.Pass()),
1539 received_dns_config_(false),
[email protected]2f3bc65c2010-07-23 17:47:101540 ipv6_probe_monitoring_(false),
[email protected]ee094b82010-08-24 15:55:511541 additional_resolver_flags_(0),
1542 net_log_(net_log) {
[email protected]0f292de02012-02-01 22:28:201543
1544 DCHECK_GE(dispatcher_.num_priorities(), static_cast<size_t>(NUM_PRIORITIES));
[email protected]68ad3ee2010-01-30 03:45:391545
[email protected]06ef6d92011-05-19 04:24:581546 // Maximum of 4 retry attempts for host resolution.
1547 static const size_t kDefaultMaxRetryAttempts = 4u;
1548
[email protected]0f292de02012-02-01 22:28:201549 if (proc_params_.max_retry_attempts == HostResolver::kDefaultRetryAttempts)
1550 proc_params_.max_retry_attempts = kDefaultMaxRetryAttempts;
[email protected]68ad3ee2010-01-30 03:45:391551
[email protected]b59ff372009-07-15 22:04:321552#if defined(OS_WIN)
1553 EnsureWinsockInit();
1554#endif
[email protected]23f771162011-06-02 18:37:511555#if defined(OS_POSIX) && !defined(OS_MACOSX)
[email protected]2f3bc65c2010-07-23 17:47:101556 if (HaveOnlyLoopbackAddresses())
1557 additional_resolver_flags_ |= HOST_RESOLVER_LOOPBACK_ONLY;
1558#endif
[email protected]232a5812011-03-04 22:42:081559 NetworkChangeNotifier::AddIPAddressObserver(this);
[email protected]d7b9a2b2012-05-31 22:31:191560#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD) && \
1561 !defined(OS_ANDROID)
[email protected]46018c9d2011-09-06 03:42:341562 NetworkChangeNotifier::AddDNSObserver(this);
[email protected]d7b9a2b2012-05-31 22:31:191563 EnsureDnsReloaderInit();
[email protected]46018c9d2011-09-06 03:42:341564#endif
[email protected]b3601bc22012-02-21 21:23:201565
[email protected]78eac2a2012-03-14 19:09:271566 if (dns_config_service_.get()) {
[email protected]b4481b222012-03-16 17:13:111567 dns_config_service_->Watch(
1568 base::Bind(&HostResolverImpl::OnDnsConfigChanged,
1569 base::Unretained(this)));
[email protected]78eac2a2012-03-14 19:09:271570 }
[email protected]b59ff372009-07-15 22:04:321571}
1572
1573HostResolverImpl::~HostResolverImpl() {
[email protected]0f8f1b432010-03-16 19:06:031574 DiscardIPv6ProbeJob();
1575
[email protected]0f292de02012-02-01 22:28:201576 // This will also cancel all outstanding requests.
1577 STLDeleteValues(&jobs_);
[email protected]e95d3aca2010-01-11 22:47:431578
[email protected]232a5812011-03-04 22:42:081579 NetworkChangeNotifier::RemoveIPAddressObserver(this);
[email protected]46018c9d2011-09-06 03:42:341580 NetworkChangeNotifier::RemoveDNSObserver(this);
[email protected]b59ff372009-07-15 22:04:321581}
1582
[email protected]0f292de02012-02-01 22:28:201583void HostResolverImpl::SetMaxQueuedJobs(size_t value) {
1584 DCHECK_EQ(0u, dispatcher_.num_queued_jobs());
1585 DCHECK_GT(value, 0u);
1586 max_queued_jobs_ = value;
[email protected]be1a48b2011-01-20 00:12:131587}
1588
[email protected]684970b2009-08-14 04:54:461589int HostResolverImpl::Resolve(const RequestInfo& info,
[email protected]b59ff372009-07-15 22:04:321590 AddressList* addresses,
[email protected]aa22b242011-11-16 18:58:291591 const CompletionCallback& callback,
[email protected]684970b2009-08-14 04:54:461592 RequestHandle* out_req,
[email protected]ee094b82010-08-24 15:55:511593 const BoundNetLog& source_net_log) {
[email protected]95a214c2011-08-04 21:50:401594 DCHECK(addresses);
[email protected]1ac6af92010-06-03 21:00:141595 DCHECK(CalledOnValidThread());
[email protected]aa22b242011-11-16 18:58:291596 DCHECK_EQ(false, callback.is_null());
[email protected]1ac6af92010-06-03 21:00:141597
[email protected]ee094b82010-08-24 15:55:511598 // Make a log item for the request.
1599 BoundNetLog request_net_log = BoundNetLog::Make(net_log_,
1600 NetLog::SOURCE_HOST_RESOLVER_IMPL_REQUEST);
1601
[email protected]0f292de02012-02-01 22:28:201602 LogStartRequest(source_net_log, request_net_log, info);
[email protected]b59ff372009-07-15 22:04:321603
[email protected]123ab1e32009-10-21 19:12:571604 // Build a key that identifies the request in the cache and in the
1605 // outstanding jobs map.
[email protected]137af622010-02-05 02:14:351606 Key key = GetEffectiveKeyForRequest(info);
[email protected]123ab1e32009-10-21 19:12:571607
[email protected]287d7c22011-11-15 17:34:251608 int rv = ResolveHelper(key, info, addresses, request_net_log);
[email protected]95a214c2011-08-04 21:50:401609 if (rv != ERR_DNS_CACHE_MISS) {
[email protected]b3601bc22012-02-21 21:23:201610 LogFinishRequest(source_net_log, request_net_log, info, rv);
[email protected]95a214c2011-08-04 21:50:401611 return rv;
[email protected]38368712011-03-02 08:09:401612 }
1613
[email protected]0f292de02012-02-01 22:28:201614 // Next we need to attach our request to a "job". This job is responsible for
1615 // calling "getaddrinfo(hostname)" on a worker thread.
1616
1617 JobMap::iterator jobit = jobs_.find(key);
1618 Job* job;
1619 if (jobit == jobs_.end()) {
1620 // Create new Job.
[email protected]16ee26d2012-03-08 03:34:351621 job = new Job(this, key, request_net_log);
1622 job->Schedule(info.priority());
[email protected]0f292de02012-02-01 22:28:201623
1624 // Check for queue overflow.
1625 if (dispatcher_.num_queued_jobs() > max_queued_jobs_) {
1626 Job* evicted = static_cast<Job*>(dispatcher_.EvictOldestLowest());
1627 DCHECK(evicted);
[email protected]16ee26d2012-03-08 03:34:351628 evicted->OnEvicted(); // Deletes |evicted|.
[email protected]0f292de02012-02-01 22:28:201629 if (evicted == job) {
[email protected]0f292de02012-02-01 22:28:201630 rv = ERR_HOST_RESOLVER_QUEUE_TOO_LARGE;
[email protected]b3601bc22012-02-21 21:23:201631 LogFinishRequest(source_net_log, request_net_log, info, rv);
[email protected]0f292de02012-02-01 22:28:201632 return rv;
1633 }
[email protected]0f292de02012-02-01 22:28:201634 }
[email protected]0f292de02012-02-01 22:28:201635 jobs_.insert(jobit, std::make_pair(key, job));
1636 } else {
1637 job = jobit->second;
1638 }
1639
1640 // Can't complete synchronously. Create and attach request.
[email protected]b3601bc22012-02-21 21:23:201641 scoped_ptr<Request> req(new Request(source_net_log,
1642 request_net_log,
1643 info,
1644 callback,
1645 addresses));
[email protected]b59ff372009-07-15 22:04:321646 if (out_req)
[email protected]b3601bc22012-02-21 21:23:201647 *out_req = reinterpret_cast<RequestHandle>(req.get());
[email protected]b59ff372009-07-15 22:04:321648
[email protected]b3601bc22012-02-21 21:23:201649 job->AddRequest(req.Pass());
[email protected]0f292de02012-02-01 22:28:201650 // Completion happens during Job::CompleteRequests().
[email protected]b59ff372009-07-15 22:04:321651 return ERR_IO_PENDING;
1652}
1653
[email protected]287d7c22011-11-15 17:34:251654int HostResolverImpl::ResolveHelper(const Key& key,
[email protected]95a214c2011-08-04 21:50:401655 const RequestInfo& info,
1656 AddressList* addresses,
[email protected]20cd5332011-10-12 22:38:001657 const BoundNetLog& request_net_log) {
[email protected]95a214c2011-08-04 21:50:401658 // The result of |getaddrinfo| for empty hosts is inconsistent across systems.
1659 // On Windows it gives the default interface's address, whereas on Linux it
1660 // gives an error. We will make it fail on all platforms for consistency.
1661 if (info.hostname().empty() || info.hostname().size() > kMaxHostLength)
1662 return ERR_NAME_NOT_RESOLVED;
1663
1664 int net_error = ERR_UNEXPECTED;
1665 if (ResolveAsIP(key, info, &net_error, addresses))
1666 return net_error;
[email protected]78eac2a2012-03-14 19:09:271667 if (ServeFromCache(key, info, &net_error, addresses)) {
1668 request_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_CACHE_HIT, NULL);
1669 return net_error;
1670 }
1671 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
1672 // http://crbug.com/117655
1673 if (ServeFromHosts(key, info, addresses)) {
1674 request_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_HOSTS_HIT, NULL);
1675 return OK;
1676 }
1677 return ERR_DNS_CACHE_MISS;
[email protected]95a214c2011-08-04 21:50:401678}
1679
1680int HostResolverImpl::ResolveFromCache(const RequestInfo& info,
1681 AddressList* addresses,
1682 const BoundNetLog& source_net_log) {
1683 DCHECK(CalledOnValidThread());
1684 DCHECK(addresses);
1685
[email protected]95a214c2011-08-04 21:50:401686 // Make a log item for the request.
1687 BoundNetLog request_net_log = BoundNetLog::Make(net_log_,
1688 NetLog::SOURCE_HOST_RESOLVER_IMPL_REQUEST);
1689
1690 // Update the net log and notify registered observers.
[email protected]0f292de02012-02-01 22:28:201691 LogStartRequest(source_net_log, request_net_log, info);
[email protected]95a214c2011-08-04 21:50:401692
[email protected]95a214c2011-08-04 21:50:401693 Key key = GetEffectiveKeyForRequest(info);
1694
[email protected]287d7c22011-11-15 17:34:251695 int rv = ResolveHelper(key, info, addresses, request_net_log);
[email protected]b3601bc22012-02-21 21:23:201696 LogFinishRequest(source_net_log, request_net_log, info, rv);
[email protected]95a214c2011-08-04 21:50:401697 return rv;
1698}
1699
[email protected]b59ff372009-07-15 22:04:321700void HostResolverImpl::CancelRequest(RequestHandle req_handle) {
[email protected]1ac6af92010-06-03 21:00:141701 DCHECK(CalledOnValidThread());
[email protected]b59ff372009-07-15 22:04:321702 Request* req = reinterpret_cast<Request*>(req_handle);
1703 DCHECK(req);
[email protected]0f292de02012-02-01 22:28:201704 Job* job = req->job();
1705 DCHECK(job);
[email protected]0f292de02012-02-01 22:28:201706 job->CancelRequest(req);
[email protected]b59ff372009-07-15 22:04:321707}
1708
[email protected]0f8f1b432010-03-16 19:06:031709void HostResolverImpl::SetDefaultAddressFamily(AddressFamily address_family) {
[email protected]1ac6af92010-06-03 21:00:141710 DCHECK(CalledOnValidThread());
[email protected]0f8f1b432010-03-16 19:06:031711 ipv6_probe_monitoring_ = false;
1712 DiscardIPv6ProbeJob();
1713 default_address_family_ = address_family;
1714}
1715
[email protected]f7d310e2010-10-07 16:25:111716AddressFamily HostResolverImpl::GetDefaultAddressFamily() const {
1717 return default_address_family_;
1718}
1719
[email protected]a78f4272011-10-21 19:16:331720void HostResolverImpl::ProbeIPv6Support() {
1721 DCHECK(CalledOnValidThread());
1722 DCHECK(!ipv6_probe_monitoring_);
1723 ipv6_probe_monitoring_ = true;
1724 OnIPAddressChanged(); // Give initial setup call.
[email protected]ddb1e5a2010-12-13 20:10:451725}
1726
[email protected]489d1a82011-10-12 03:09:111727HostCache* HostResolverImpl::GetHostCache() {
1728 return cache_.get();
1729}
[email protected]95a214c2011-08-04 21:50:401730
[email protected]17e92032012-03-29 00:56:241731base::Value* HostResolverImpl::GetDnsConfigAsValue() const {
1732 // Check if async DNS is disabled.
1733 if (!dns_client_.get())
1734 return NULL;
1735
1736 // Check if async DNS is enabled, but we currently have no configuration
1737 // for it.
1738 const DnsConfig* dns_config = dns_client_->GetConfig();
1739 if (dns_config == NULL)
1740 return new DictionaryValue();
1741
1742 return dns_config->ToValue();
1743}
1744
[email protected]95a214c2011-08-04 21:50:401745bool HostResolverImpl::ResolveAsIP(const Key& key,
1746 const RequestInfo& info,
1747 int* net_error,
1748 AddressList* addresses) {
1749 DCHECK(addresses);
1750 DCHECK(net_error);
1751 IPAddressNumber ip_number;
1752 if (!ParseIPLiteralToNumber(key.hostname, &ip_number))
1753 return false;
1754
1755 DCHECK_EQ(key.host_resolver_flags &
1756 ~(HOST_RESOLVER_CANONNAME | HOST_RESOLVER_LOOPBACK_ONLY |
1757 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6),
1758 0) << " Unhandled flag";
[email protected]0f292de02012-02-01 22:28:201759 bool ipv6_disabled = (default_address_family_ == ADDRESS_FAMILY_IPV4) &&
1760 !ipv6_probe_monitoring_;
[email protected]95a214c2011-08-04 21:50:401761 *net_error = OK;
[email protected]0f292de02012-02-01 22:28:201762 if ((ip_number.size() == kIPv6AddressSize) && ipv6_disabled) {
[email protected]95a214c2011-08-04 21:50:401763 *net_error = ERR_NAME_NOT_RESOLVED;
1764 } else {
[email protected]7054e78f2012-05-07 21:44:561765 *addresses = AddressList::CreateFromIPAddress(ip_number, info.port());
1766 if (key.host_resolver_flags & HOST_RESOLVER_CANONNAME)
1767 addresses->SetDefaultCanonicalName();
[email protected]95a214c2011-08-04 21:50:401768 }
1769 return true;
1770}
1771
1772bool HostResolverImpl::ServeFromCache(const Key& key,
1773 const RequestInfo& info,
[email protected]95a214c2011-08-04 21:50:401774 int* net_error,
1775 AddressList* addresses) {
1776 DCHECK(addresses);
1777 DCHECK(net_error);
1778 if (!info.allow_cached_response() || !cache_.get())
1779 return false;
1780
1781 const HostCache::Entry* cache_entry = cache_->Lookup(
1782 key, base::TimeTicks::Now());
1783 if (!cache_entry)
1784 return false;
1785
[email protected]95a214c2011-08-04 21:50:401786 *net_error = cache_entry->error;
[email protected]7054e78f2012-05-07 21:44:561787 if (*net_error == OK) {
1788 *addresses = cache_entry->addrlist;
1789 EnsurePortOnAddressList(info.port(), addresses);
1790 }
[email protected]95a214c2011-08-04 21:50:401791 return true;
1792}
1793
[email protected]78eac2a2012-03-14 19:09:271794bool HostResolverImpl::ServeFromHosts(const Key& key,
1795 const RequestInfo& info,
1796 AddressList* addresses) {
1797 DCHECK(addresses);
1798 if (!HaveDnsConfig())
1799 return false;
1800
[email protected]cb507622012-03-23 16:17:061801 // HOSTS lookups are case-insensitive.
1802 std::string hostname = StringToLowerASCII(key.hostname);
1803
[email protected]78eac2a2012-03-14 19:09:271804 // If |address_family| is ADDRESS_FAMILY_UNSPECIFIED other implementations
1805 // (glibc and c-ares) return the first matching line. We have more
1806 // flexibility, but lose implicit ordering.
1807 // TODO(szym) http://crbug.com/117850
1808 const DnsHosts& hosts = dns_client_->GetConfig()->hosts;
1809 DnsHosts::const_iterator it = hosts.find(
[email protected]cb507622012-03-23 16:17:061810 DnsHostsKey(hostname,
[email protected]78eac2a2012-03-14 19:09:271811 key.address_family == ADDRESS_FAMILY_UNSPECIFIED ?
1812 ADDRESS_FAMILY_IPV4 : key.address_family));
1813
1814 if (it == hosts.end()) {
1815 if (key.address_family != ADDRESS_FAMILY_UNSPECIFIED)
1816 return false;
1817
[email protected]cb507622012-03-23 16:17:061818 it = hosts.find(DnsHostsKey(hostname, ADDRESS_FAMILY_IPV6));
[email protected]78eac2a2012-03-14 19:09:271819 if (it == hosts.end())
1820 return false;
1821 }
1822
1823 *addresses = AddressList::CreateFromIPAddress(it->second, info.port());
1824 return true;
1825}
1826
[email protected]16ee26d2012-03-08 03:34:351827void HostResolverImpl::CacheResult(const Key& key,
1828 int net_error,
1829 const AddressList& addr_list,
1830 base::TimeDelta ttl) {
1831 if (cache_.get())
1832 cache_->Set(key, net_error, addr_list, base::TimeTicks::Now(), ttl);
[email protected]ef4c40c2010-09-01 14:42:031833}
1834
[email protected]0f292de02012-02-01 22:28:201835void HostResolverImpl::RemoveJob(Job* job) {
1836 DCHECK(job);
[email protected]16ee26d2012-03-08 03:34:351837 JobMap::iterator it = jobs_.find(job->key());
1838 if (it != jobs_.end() && it->second == job)
1839 jobs_.erase(it);
[email protected]b59ff372009-07-15 22:04:321840}
1841
[email protected]0f8f1b432010-03-16 19:06:031842void HostResolverImpl::DiscardIPv6ProbeJob() {
1843 if (ipv6_probe_job_.get()) {
1844 ipv6_probe_job_->Cancel();
1845 ipv6_probe_job_ = NULL;
1846 }
1847}
1848
1849void HostResolverImpl::IPv6ProbeSetDefaultAddressFamily(
1850 AddressFamily address_family) {
1851 DCHECK(address_family == ADDRESS_FAMILY_UNSPECIFIED ||
1852 address_family == ADDRESS_FAMILY_IPV4);
[email protected]f092e64b2010-03-17 00:39:181853 if (default_address_family_ != address_family) {
[email protected]b30a3f52010-10-16 01:05:461854 VLOG(1) << "IPv6Probe forced AddressFamily setting to "
1855 << ((address_family == ADDRESS_FAMILY_UNSPECIFIED) ?
1856 "ADDRESS_FAMILY_UNSPECIFIED" : "ADDRESS_FAMILY_IPV4");
[email protected]f092e64b2010-03-17 00:39:181857 }
[email protected]0f8f1b432010-03-16 19:06:031858 default_address_family_ = address_family;
1859 // Drop reference since the job has called us back.
1860 DiscardIPv6ProbeJob();
[email protected]e95d3aca2010-01-11 22:47:431861}
1862
[email protected]137af622010-02-05 02:14:351863HostResolverImpl::Key HostResolverImpl::GetEffectiveKeyForRequest(
1864 const RequestInfo& info) const {
[email protected]eaf3a3b2010-09-03 20:34:271865 HostResolverFlags effective_flags =
1866 info.host_resolver_flags() | additional_resolver_flags_;
[email protected]137af622010-02-05 02:14:351867 AddressFamily effective_address_family = info.address_family();
[email protected]eaf3a3b2010-09-03 20:34:271868 if (effective_address_family == ADDRESS_FAMILY_UNSPECIFIED &&
1869 default_address_family_ != ADDRESS_FAMILY_UNSPECIFIED) {
[email protected]137af622010-02-05 02:14:351870 effective_address_family = default_address_family_;
[email protected]eaf3a3b2010-09-03 20:34:271871 if (ipv6_probe_monitoring_)
1872 effective_flags |= HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
1873 }
1874 return Key(info.hostname(), effective_address_family, effective_flags);
[email protected]137af622010-02-05 02:14:351875}
1876
[email protected]35ddc282010-09-21 23:42:061877void HostResolverImpl::AbortAllInProgressJobs() {
[email protected]b3601bc22012-02-21 21:23:201878 // In Abort, a Request callback could spawn new Jobs with matching keys, so
1879 // first collect and remove all running jobs from |jobs_|.
[email protected]c143d892012-04-06 07:56:541880 ScopedVector<Job> jobs_to_abort;
[email protected]0f292de02012-02-01 22:28:201881 for (JobMap::iterator it = jobs_.begin(); it != jobs_.end(); ) {
1882 Job* job = it->second;
[email protected]0f292de02012-02-01 22:28:201883 if (job->is_running()) {
[email protected]b3601bc22012-02-21 21:23:201884 jobs_to_abort.push_back(job);
1885 jobs_.erase(it++);
[email protected]0f292de02012-02-01 22:28:201886 } else {
[email protected]b3601bc22012-02-21 21:23:201887 DCHECK(job->is_queued());
1888 ++it;
[email protected]0f292de02012-02-01 22:28:201889 }
[email protected]ef4c40c2010-09-01 14:42:031890 }
[email protected]b3601bc22012-02-21 21:23:201891
[email protected]57a48d32012-03-03 00:04:551892 // Check if no dispatcher slots leaked out.
1893 DCHECK_EQ(dispatcher_.num_running_jobs(), jobs_to_abort.size());
1894
1895 // Life check to bail once |this| is deleted.
1896 base::WeakPtr<HostResolverImpl> self = AsWeakPtr();
1897
[email protected]16ee26d2012-03-08 03:34:351898 // Then Abort them.
[email protected]57a48d32012-03-03 00:04:551899 for (size_t i = 0; self && i < jobs_to_abort.size(); ++i) {
[email protected]57a48d32012-03-03 00:04:551900 jobs_to_abort[i]->Abort();
[email protected]c143d892012-04-06 07:56:541901 jobs_to_abort[i] = NULL;
[email protected]b3601bc22012-02-21 21:23:201902 }
[email protected]ef4c40c2010-09-01 14:42:031903}
1904
[email protected]78eac2a2012-03-14 19:09:271905void HostResolverImpl::TryServingAllJobsFromHosts() {
1906 if (!HaveDnsConfig())
1907 return;
1908
1909 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
1910 // http://crbug.com/117655
1911
1912 // Life check to bail once |this| is deleted.
1913 base::WeakPtr<HostResolverImpl> self = AsWeakPtr();
1914
1915 for (JobMap::iterator it = jobs_.begin(); self && it != jobs_.end(); ) {
1916 Job* job = it->second;
1917 ++it;
1918 // This could remove |job| from |jobs_|, but iterator will remain valid.
1919 job->ServeFromHosts();
1920 }
1921}
1922
[email protected]be1a48b2011-01-20 00:12:131923void HostResolverImpl::OnIPAddressChanged() {
1924 if (cache_.get())
1925 cache_->clear();
1926 if (ipv6_probe_monitoring_) {
[email protected]be1a48b2011-01-20 00:12:131927 DiscardIPv6ProbeJob();
1928 ipv6_probe_job_ = new IPv6ProbeJob(this);
1929 ipv6_probe_job_->Start();
1930 }
[email protected]23f771162011-06-02 18:37:511931#if defined(OS_POSIX) && !defined(OS_MACOSX)
[email protected]be1a48b2011-01-20 00:12:131932 if (HaveOnlyLoopbackAddresses()) {
1933 additional_resolver_flags_ |= HOST_RESOLVER_LOOPBACK_ONLY;
1934 } else {
1935 additional_resolver_flags_ &= ~HOST_RESOLVER_LOOPBACK_ONLY;
1936 }
1937#endif
1938 AbortAllInProgressJobs();
1939 // |this| may be deleted inside AbortAllInProgressJobs().
1940}
1941
[email protected]446df2952012-02-28 07:22:511942void HostResolverImpl::OnDNSChanged(unsigned detail) {
[email protected]d7b9a2b2012-05-31 22:31:191943 // Ignore signals about watches.
1944 const unsigned kIgnoredDetail =
1945 NetworkChangeNotifier::CHANGE_DNS_WATCH_STARTED |
1946 NetworkChangeNotifier::CHANGE_DNS_WATCH_FAILED;
1947 if ((detail & ~kIgnoredDetail) == 0)
1948 return;
[email protected]46018c9d2011-09-06 03:42:341949 // If the DNS server has changed, existing cached info could be wrong so we
1950 // have to drop our internal cache :( Note that OS level DNS caches, such
1951 // as NSCD's cache should be dropped automatically by the OS when
1952 // resolv.conf changes so we don't need to do anything to clear that cache.
1953 if (cache_.get())
1954 cache_->clear();
1955 // Existing jobs will have been sent to the original server so they need to
[email protected]d7b9a2b2012-05-31 22:31:191956 // be aborted.
[email protected]46018c9d2011-09-06 03:42:341957 AbortAllInProgressJobs();
1958 // |this| may be deleted inside AbortAllInProgressJobs().
1959}
1960
[email protected]b4481b222012-03-16 17:13:111961void HostResolverImpl::OnDnsConfigChanged(const DnsConfig& dns_config) {
1962 if (net_log_) {
1963 net_log_->AddGlobalEntry(
1964 NetLog::TYPE_DNS_CONFIG_CHANGED,
1965 make_scoped_refptr(new DnsConfigParameters(dns_config)));
1966 }
1967
[email protected]d7b9a2b2012-05-31 22:31:191968 // TODO(szym): Remove once http://crbug.com/125599 is resolved.
1969 received_dns_config_ = dns_config.IsValid();
[email protected]78eac2a2012-03-14 19:09:271970
1971 // Life check to bail once |this| is deleted.
1972 base::WeakPtr<HostResolverImpl> self = AsWeakPtr();
1973
[email protected]d7b9a2b2012-05-31 22:31:191974 if (dns_client_.get()) {
1975 // We want a new factory in place, before we Abort running Jobs, so that the
1976 // newly started jobs use the new factory.
1977 dns_client_->SetConfig(dns_config);
[email protected]446df2952012-02-28 07:22:511978 OnDNSChanged(NetworkChangeNotifier::CHANGE_DNS_SETTINGS);
[email protected]d7b9a2b2012-05-31 22:31:191979 // |this| may be deleted inside OnDNSChanged().
1980 if (self)
1981 TryServingAllJobsFromHosts();
[email protected]7b5db762012-03-24 09:02:011982 }
[email protected]78eac2a2012-03-14 19:09:271983}
1984
1985bool HostResolverImpl::HaveDnsConfig() const {
1986 return (dns_client_.get() != NULL) && (dns_client_->GetConfig() != NULL);
[email protected]b3601bc22012-02-21 21:23:201987}
1988
[email protected]b59ff372009-07-15 22:04:321989} // namespace net