Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / net / dns / host_resolver_impl.cc
blob97345a029e49e6e73511a94eb3f1414da7f699e7
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/dns/host_resolver_impl.h"
7 #if defined(OS_WIN)
8 #include <Winsock2.h>
9 #elif defined(OS_POSIX)
10 #include <netdb.h>
11 #endif
13 #include <cmath>
14 #include <utility>
15 #include <vector>
17 #include "base/basictypes.h"
18 #include "base/bind.h"
19 #include "base/bind_helpers.h"
20 #include "base/callback.h"
21 #include "base/compiler_specific.h"
22 #include "base/debug/debugger.h"
23 #include "base/debug/stack_trace.h"
24 #include "base/metrics/field_trial.h"
25 #include "base/metrics/histogram_macros.h"
26 #include "base/metrics/sparse_histogram.h"
27 #include "base/profiler/scoped_tracker.h"
28 #include "base/single_thread_task_runner.h"
29 #include "base/stl_util.h"
30 #include "base/strings/string_util.h"
31 #include "base/strings/utf_string_conversions.h"
32 #include "base/thread_task_runner_handle.h"
33 #include "base/threading/worker_pool.h"
34 #include "base/time/time.h"
35 #include "base/values.h"
36 #include "net/base/address_family.h"
37 #include "net/base/address_list.h"
38 #include "net/base/dns_reloader.h"
39 #include "net/base/dns_util.h"
40 #include "net/base/host_port_pair.h"
41 #include "net/base/ip_endpoint.h"
42 #include "net/base/net_errors.h"
43 #include "net/base/net_util.h"
44 #include "net/dns/address_sorter.h"
45 #include "net/dns/dns_client.h"
46 #include "net/dns/dns_config_service.h"
47 #include "net/dns/dns_protocol.h"
48 #include "net/dns/dns_response.h"
49 #include "net/dns/dns_transaction.h"
50 #include "net/dns/host_resolver_proc.h"
51 #include "net/log/net_log.h"
52 #include "net/socket/client_socket_factory.h"
53 #include "net/udp/datagram_client_socket.h"
54 #include "url/url_canon_ip.h"
56 #if defined(OS_WIN)
57 #include "net/base/winsock_init.h"
58 #endif
60 namespace net {
62 namespace {
64 // Limit the size of hostnames that will be resolved to combat issues in
65 // some platform's resolvers.
66 const size_t kMaxHostLength = 4096;
68 // Default TTL for successful resolutions with ProcTask.
69 const unsigned kCacheEntryTTLSeconds = 60;
71 // Default TTL for unsuccessful resolutions with ProcTask.
72 const unsigned kNegativeCacheEntryTTLSeconds = 0;
74 // Minimum TTL for successful resolutions with DnsTask.
75 const unsigned kMinimumTTLSeconds = kCacheEntryTTLSeconds;
77 // Time between IPv6 probes, i.e. for how long results of each IPv6 probe are
78 // cached.
79 const int kIPv6ProbePeriodMs = 1000;
81 // Google DNS address used for IPv6 probes.
82 const uint8_t kIPv6ProbeAddress[] =
83 { 0x20, 0x01, 0x48, 0x60, 0x48, 0x60, 0x00, 0x00,
84 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x88 };
86 // We use a separate histogram name for each platform to facilitate the
87 // display of error codes by their symbolic name (since each platform has
88 // different mappings).
89 const char kOSErrorsForGetAddrinfoHistogramName[] =
90 #if defined(OS_WIN)
91 "Net.OSErrorsForGetAddrinfo_Win";
92 #elif defined(OS_MACOSX)
93 "Net.OSErrorsForGetAddrinfo_Mac";
94 #elif defined(OS_LINUX)
95 "Net.OSErrorsForGetAddrinfo_Linux";
96 #else
97 "Net.OSErrorsForGetAddrinfo";
98 #endif
100 // Gets a list of the likely error codes that getaddrinfo() can return
101 // (non-exhaustive). These are the error codes that we will track via
102 // a histogram.
103 std::vector<int> GetAllGetAddrinfoOSErrors() {
104 int os_errors[] = {
105 #if defined(OS_POSIX)
106 #if !defined(OS_FREEBSD)
107 #if !defined(OS_ANDROID)
108 // EAI_ADDRFAMILY has been declared obsolete in Android's and
109 // FreeBSD's netdb.h.
110 EAI_ADDRFAMILY,
111 #endif
112 // EAI_NODATA has been declared obsolete in FreeBSD's netdb.h.
113 EAI_NODATA,
114 #endif
115 EAI_AGAIN,
116 EAI_BADFLAGS,
117 EAI_FAIL,
118 EAI_FAMILY,
119 EAI_MEMORY,
120 EAI_NONAME,
121 EAI_SERVICE,
122 EAI_SOCKTYPE,
123 EAI_SYSTEM,
124 #elif defined(OS_WIN)
125 // See: http://msdn.microsoft.com/en-us/library/ms738520(VS.85).aspx
126 WSA_NOT_ENOUGH_MEMORY,
127 WSAEAFNOSUPPORT,
128 WSAEINVAL,
129 WSAESOCKTNOSUPPORT,
130 WSAHOST_NOT_FOUND,
131 WSANO_DATA,
132 WSANO_RECOVERY,
133 WSANOTINITIALISED,
134 WSATRY_AGAIN,
135 WSATYPE_NOT_FOUND,
136 // The following are not in doc, but might be to appearing in results :-(.
137 WSA_INVALID_HANDLE,
138 #endif
141 // Ensure all errors are positive, as histogram only tracks positive values.
142 for (size_t i = 0; i < arraysize(os_errors); ++i) {
143 os_errors[i] = std::abs(os_errors[i]);
146 return base::CustomHistogram::ArrayToCustomRanges(os_errors,
147 arraysize(os_errors));
150 enum DnsResolveStatus {
151 RESOLVE_STATUS_DNS_SUCCESS = 0,
152 RESOLVE_STATUS_PROC_SUCCESS,
153 RESOLVE_STATUS_FAIL,
154 RESOLVE_STATUS_SUSPECT_NETBIOS,
155 RESOLVE_STATUS_MAX
158 // ICANN uses this localhost address to indicate a name collision.
160 // The policy in Chromium is to fail host resolving if it resolves to
161 // this special address.
163 // Not however that IP literals are exempt from this policy, so it is still
164 // possible to navigate to http://127.0.53.53/ directly.
166 // For more details: https://www.icann.org/news/announcement-2-2014-08-01-en
167 const unsigned char kIcanNameCollisionIp[] = {127, 0, 53, 53};
169 void UmaAsyncDnsResolveStatus(DnsResolveStatus result) {
170 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ResolveStatus",
171 result,
172 RESOLVE_STATUS_MAX);
175 bool ResemblesNetBIOSName(const std::string& hostname) {
176 return (hostname.size() < 16) && (hostname.find('.') == std::string::npos);
179 // True if |hostname| ends with either ".local" or ".local.".
180 bool ResemblesMulticastDNSName(const std::string& hostname) {
181 DCHECK(!hostname.empty());
182 const char kSuffix[] = ".local.";
183 const size_t kSuffixLen = sizeof(kSuffix) - 1;
184 const size_t kSuffixLenTrimmed = kSuffixLen - 1;
185 if (hostname[hostname.size() - 1] == '.') {
186 return hostname.size() > kSuffixLen &&
187 !hostname.compare(hostname.size() - kSuffixLen, kSuffixLen, kSuffix);
189 return hostname.size() > kSuffixLenTrimmed &&
190 !hostname.compare(hostname.size() - kSuffixLenTrimmed, kSuffixLenTrimmed,
191 kSuffix, kSuffixLenTrimmed);
194 // Attempts to connect a UDP socket to |dest|:53.
195 bool IsGloballyReachable(const IPAddressNumber& dest,
196 const BoundNetLog& net_log) {
197 // TODO(eroman): Remove ScopedTracker below once crbug.com/455942 is fixed.
198 tracked_objects::ScopedTracker tracking_profile_1(
199 FROM_HERE_WITH_EXPLICIT_FUNCTION("455942 IsGloballyReachable"));
201 scoped_ptr<DatagramClientSocket> socket(
202 ClientSocketFactory::GetDefaultFactory()->CreateDatagramClientSocket(
203 DatagramSocket::DEFAULT_BIND,
204 RandIntCallback(),
205 net_log.net_log(),
206 net_log.source()));
207 int rv = socket->Connect(IPEndPoint(dest, 53));
208 if (rv != OK)
209 return false;
210 IPEndPoint endpoint;
211 rv = socket->GetLocalAddress(&endpoint);
212 if (rv != OK)
213 return false;
214 DCHECK_EQ(ADDRESS_FAMILY_IPV6, endpoint.GetFamily());
215 const IPAddressNumber& address = endpoint.address();
216 bool is_link_local = (address[0] == 0xFE) && ((address[1] & 0xC0) == 0x80);
217 if (is_link_local)
218 return false;
219 const uint8 kTeredoPrefix[] = { 0x20, 0x01, 0, 0 };
220 bool is_teredo = std::equal(kTeredoPrefix,
221 kTeredoPrefix + arraysize(kTeredoPrefix),
222 address.begin());
223 if (is_teredo)
224 return false;
225 return true;
228 // Provide a common macro to simplify code and readability. We must use a
229 // macro as the underlying HISTOGRAM macro creates static variables.
230 #define DNS_HISTOGRAM(name, time) UMA_HISTOGRAM_CUSTOM_TIMES(name, time, \
231 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromHours(1), 100)
233 // A macro to simplify code and readability.
234 #define DNS_HISTOGRAM_BY_PRIORITY(basename, priority, time) \
235 do { \
236 switch (priority) { \
237 case HIGHEST: DNS_HISTOGRAM(basename "_HIGHEST", time); break; \
238 case MEDIUM: DNS_HISTOGRAM(basename "_MEDIUM", time); break; \
239 case LOW: DNS_HISTOGRAM(basename "_LOW", time); break; \
240 case LOWEST: DNS_HISTOGRAM(basename "_LOWEST", time); break; \
241 case IDLE: DNS_HISTOGRAM(basename "_IDLE", time); break; \
242 default: NOTREACHED(); break; \
244 DNS_HISTOGRAM(basename, time); \
245 } while (0)
247 // Record time from Request creation until a valid DNS response.
248 void RecordTotalTime(bool had_dns_config,
249 bool speculative,
250 base::TimeDelta duration) {
251 if (had_dns_config) {
252 if (speculative) {
253 DNS_HISTOGRAM("AsyncDNS.TotalTime_speculative", duration);
254 } else {
255 DNS_HISTOGRAM("AsyncDNS.TotalTime", duration);
257 } else {
258 if (speculative) {
259 DNS_HISTOGRAM("DNS.TotalTime_speculative", duration);
260 } else {
261 DNS_HISTOGRAM("DNS.TotalTime", duration);
266 void RecordTTL(base::TimeDelta ttl) {
267 UMA_HISTOGRAM_CUSTOM_TIMES("AsyncDNS.TTL", ttl,
268 base::TimeDelta::FromSeconds(1),
269 base::TimeDelta::FromDays(1), 100);
272 bool ConfigureAsyncDnsNoFallbackFieldTrial() {
273 const bool kDefault = false;
275 // Configure the AsyncDns field trial as follows:
276 // groups AsyncDnsNoFallbackA and AsyncDnsNoFallbackB: return true,
277 // groups AsyncDnsA and AsyncDnsB: return false,
278 // groups SystemDnsA and SystemDnsB: return false,
279 // otherwise (trial absent): return default.
280 std::string group_name = base::FieldTrialList::FindFullName("AsyncDns");
281 if (!group_name.empty()) {
282 return base::StartsWith(group_name, "AsyncDnsNoFallback",
283 base::CompareCase::INSENSITIVE_ASCII);
285 return kDefault;
288 //-----------------------------------------------------------------------------
290 AddressList EnsurePortOnAddressList(const AddressList& list, uint16 port) {
291 if (list.empty() || list.front().port() == port)
292 return list;
293 return AddressList::CopyWithPort(list, port);
296 // Returns true if |addresses| contains only IPv4 loopback addresses.
297 bool IsAllIPv4Loopback(const AddressList& addresses) {
298 for (unsigned i = 0; i < addresses.size(); ++i) {
299 const IPAddressNumber& address = addresses[i].address();
300 switch (addresses[i].GetFamily()) {
301 case ADDRESS_FAMILY_IPV4:
302 if (address[0] != 127)
303 return false;
304 break;
305 case ADDRESS_FAMILY_IPV6:
306 return false;
307 default:
308 NOTREACHED();
309 return false;
312 return true;
315 // Creates NetLog parameters when the resolve failed.
316 scoped_ptr<base::Value> NetLogProcTaskFailedCallback(
317 uint32 attempt_number,
318 int net_error,
319 int os_error,
320 NetLogCaptureMode /* capture_mode */) {
321 scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
322 if (attempt_number)
323 dict->SetInteger("attempt_number", attempt_number);
325 dict->SetInteger("net_error", net_error);
327 if (os_error) {
328 dict->SetInteger("os_error", os_error);
329 #if defined(OS_POSIX)
330 dict->SetString("os_error_string", gai_strerror(os_error));
331 #elif defined(OS_WIN)
332 // Map the error code to a human-readable string.
333 LPWSTR error_string = NULL;
334 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
335 0, // Use the internal message table.
336 os_error,
337 0, // Use default language.
338 (LPWSTR)&error_string,
339 0, // Buffer size.
340 0); // Arguments (unused).
341 dict->SetString("os_error_string", base::WideToUTF8(error_string));
342 LocalFree(error_string);
343 #endif
346 return dict.Pass();
349 // Creates NetLog parameters when the DnsTask failed.
350 scoped_ptr<base::Value> NetLogDnsTaskFailedCallback(
351 int net_error,
352 int dns_error,
353 NetLogCaptureMode /* capture_mode */) {
354 scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
355 dict->SetInteger("net_error", net_error);
356 if (dns_error)
357 dict->SetInteger("dns_error", dns_error);
358 return dict.Pass();
361 // Creates NetLog parameters containing the information in a RequestInfo object,
362 // along with the associated NetLog::Source.
363 scoped_ptr<base::Value> NetLogRequestInfoCallback(
364 const HostResolver::RequestInfo* info,
365 NetLogCaptureMode /* capture_mode */) {
366 scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
368 dict->SetString("host", info->host_port_pair().ToString());
369 dict->SetInteger("address_family",
370 static_cast<int>(info->address_family()));
371 dict->SetBoolean("allow_cached_response", info->allow_cached_response());
372 dict->SetBoolean("is_speculative", info->is_speculative());
373 return dict.Pass();
376 // Creates NetLog parameters for the creation of a HostResolverImpl::Job.
377 scoped_ptr<base::Value> NetLogJobCreationCallback(
378 const NetLog::Source& source,
379 const std::string* host,
380 NetLogCaptureMode /* capture_mode */) {
381 scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
382 source.AddToEventParameters(dict.get());
383 dict->SetString("host", *host);
384 return dict.Pass();
387 // Creates NetLog parameters for HOST_RESOLVER_IMPL_JOB_ATTACH/DETACH events.
388 scoped_ptr<base::Value> NetLogJobAttachCallback(
389 const NetLog::Source& source,
390 RequestPriority priority,
391 NetLogCaptureMode /* capture_mode */) {
392 scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
393 source.AddToEventParameters(dict.get());
394 dict->SetString("priority", RequestPriorityToString(priority));
395 return dict.Pass();
398 // Creates NetLog parameters for the DNS_CONFIG_CHANGED event.
399 scoped_ptr<base::Value> NetLogDnsConfigCallback(
400 const DnsConfig* config,
401 NetLogCaptureMode /* capture_mode */) {
402 return make_scoped_ptr(config->ToValue());
405 scoped_ptr<base::Value> NetLogIPv6AvailableCallback(
406 bool ipv6_available,
407 bool cached,
408 NetLogCaptureMode /* capture_mode */) {
409 scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
410 dict->SetBoolean("ipv6_available", ipv6_available);
411 dict->SetBoolean("cached", cached);
412 return dict.Pass();
415 // The logging routines are defined here because some requests are resolved
416 // without a Request object.
418 // Logs when a request has just been started.
419 void LogStartRequest(const BoundNetLog& source_net_log,
420 const HostResolver::RequestInfo& info) {
421 source_net_log.BeginEvent(
422 NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST,
423 base::Bind(&NetLogRequestInfoCallback, &info));
426 // Logs when a request has just completed (before its callback is run).
427 void LogFinishRequest(const BoundNetLog& source_net_log,
428 const HostResolver::RequestInfo& info,
429 int net_error) {
430 source_net_log.EndEventWithNetErrorCode(
431 NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST, net_error);
434 // Logs when a request has been cancelled.
435 void LogCancelRequest(const BoundNetLog& source_net_log,
436 const HostResolverImpl::RequestInfo& info) {
437 source_net_log.AddEvent(NetLog::TYPE_CANCELLED);
438 source_net_log.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST);
441 //-----------------------------------------------------------------------------
443 // Keeps track of the highest priority.
444 class PriorityTracker {
445 public:
446 explicit PriorityTracker(RequestPriority initial_priority)
447 : highest_priority_(initial_priority), total_count_(0) {
448 memset(counts_, 0, sizeof(counts_));
451 RequestPriority highest_priority() const {
452 return highest_priority_;
455 size_t total_count() const {
456 return total_count_;
459 void Add(RequestPriority req_priority) {
460 ++total_count_;
461 ++counts_[req_priority];
462 if (highest_priority_ < req_priority)
463 highest_priority_ = req_priority;
466 void Remove(RequestPriority req_priority) {
467 DCHECK_GT(total_count_, 0u);
468 DCHECK_GT(counts_[req_priority], 0u);
469 --total_count_;
470 --counts_[req_priority];
471 size_t i;
472 for (i = highest_priority_; i > MINIMUM_PRIORITY && !counts_[i]; --i);
473 highest_priority_ = static_cast<RequestPriority>(i);
475 // In absence of requests, default to MINIMUM_PRIORITY.
476 if (total_count_ == 0)
477 DCHECK_EQ(MINIMUM_PRIORITY, highest_priority_);
480 private:
481 RequestPriority highest_priority_;
482 size_t total_count_;
483 size_t counts_[NUM_PRIORITIES];
486 } // namespace
488 //-----------------------------------------------------------------------------
490 const unsigned HostResolverImpl::kMaximumDnsFailures = 16;
492 // Holds the data for a request that could not be completed synchronously.
493 // It is owned by a Job. Canceled Requests are only marked as canceled rather
494 // than removed from the Job's |requests_| list.
495 class HostResolverImpl::Request {
496 public:
497 Request(const BoundNetLog& source_net_log,
498 const RequestInfo& info,
499 RequestPriority priority,
500 const CompletionCallback& callback,
501 AddressList* addresses)
502 : source_net_log_(source_net_log),
503 info_(info),
504 priority_(priority),
505 job_(NULL),
506 callback_(callback),
507 addresses_(addresses),
508 request_time_(base::TimeTicks::Now()) {}
510 // Mark the request as canceled.
511 void MarkAsCanceled() {
512 job_ = NULL;
513 addresses_ = NULL;
514 callback_.Reset();
517 bool was_canceled() const {
518 return callback_.is_null();
521 void set_job(Job* job) {
522 DCHECK(job);
523 // Identify which job the request is waiting on.
524 job_ = job;
527 // Prepare final AddressList and call completion callback.
528 void OnComplete(int error, const AddressList& addr_list) {
529 DCHECK(!was_canceled());
530 if (error == OK)
531 *addresses_ = EnsurePortOnAddressList(addr_list, info_.port());
532 CompletionCallback callback = callback_;
533 MarkAsCanceled();
534 callback.Run(error);
537 Job* job() const {
538 return job_;
541 // NetLog for the source, passed in HostResolver::Resolve.
542 const BoundNetLog& source_net_log() {
543 return source_net_log_;
546 const RequestInfo& info() const {
547 return info_;
550 RequestPriority priority() const { return priority_; }
552 base::TimeTicks request_time() const { return request_time_; }
554 private:
555 const BoundNetLog source_net_log_;
557 // The request info that started the request.
558 const RequestInfo info_;
560 // TODO(akalin): Support reprioritization.
561 const RequestPriority priority_;
563 // The resolve job that this request is dependent on.
564 Job* job_;
566 // The user's callback to invoke when the request completes.
567 CompletionCallback callback_;
569 // The address list to save result into.
570 AddressList* addresses_;
572 const base::TimeTicks request_time_;
574 DISALLOW_COPY_AND_ASSIGN(Request);
577 //------------------------------------------------------------------------------
579 // Calls HostResolverProc on the WorkerPool. Performs retries if necessary.
581 // Whenever we try to resolve the host, we post a delayed task to check if host
582 // resolution (OnLookupComplete) is completed or not. If the original attempt
583 // hasn't completed, then we start another attempt for host resolution. We take
584 // the results from the first attempt that finishes and ignore the results from
585 // all other attempts.
587 // TODO(szym): Move to separate source file for testing and mocking.
589 class HostResolverImpl::ProcTask
590 : public base::RefCountedThreadSafe<HostResolverImpl::ProcTask> {
591 public:
592 typedef base::Callback<void(int net_error,
593 const AddressList& addr_list)> Callback;
595 ProcTask(const Key& key,
596 const ProcTaskParams& params,
597 const Callback& callback,
598 const BoundNetLog& job_net_log)
599 : key_(key),
600 params_(params),
601 callback_(callback),
602 task_runner_(base::ThreadTaskRunnerHandle::Get()),
603 attempt_number_(0),
604 completed_attempt_number_(0),
605 completed_attempt_error_(ERR_UNEXPECTED),
606 had_non_speculative_request_(false),
607 net_log_(job_net_log) {
608 if (!params_.resolver_proc.get())
609 params_.resolver_proc = HostResolverProc::GetDefault();
610 // If default is unset, use the system proc.
611 if (!params_.resolver_proc.get())
612 params_.resolver_proc = new SystemHostResolverProc();
615 void Start() {
616 DCHECK(task_runner_->BelongsToCurrentThread());
617 net_log_.BeginEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK);
618 StartLookupAttempt();
621 // Cancels this ProcTask. It will be orphaned. Any outstanding resolve
622 // attempts running on worker threads will continue running. Only once all the
623 // attempts complete will the final reference to this ProcTask be released.
624 void Cancel() {
625 DCHECK(task_runner_->BelongsToCurrentThread());
627 if (was_canceled() || was_completed())
628 return;
630 callback_.Reset();
631 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK);
634 void set_had_non_speculative_request() {
635 DCHECK(task_runner_->BelongsToCurrentThread());
636 had_non_speculative_request_ = true;
639 bool was_canceled() const {
640 DCHECK(task_runner_->BelongsToCurrentThread());
641 return callback_.is_null();
644 bool was_completed() const {
645 DCHECK(task_runner_->BelongsToCurrentThread());
646 return completed_attempt_number_ > 0;
649 private:
650 friend class base::RefCountedThreadSafe<ProcTask>;
651 ~ProcTask() {}
653 void StartLookupAttempt() {
654 DCHECK(task_runner_->BelongsToCurrentThread());
655 base::TimeTicks start_time = base::TimeTicks::Now();
656 ++attempt_number_;
657 // Dispatch the lookup attempt to a worker thread.
658 if (!base::WorkerPool::PostTask(
659 FROM_HERE,
660 base::Bind(&ProcTask::DoLookup, this, start_time, attempt_number_),
661 true)) {
662 NOTREACHED();
664 // Since we could be running within Resolve() right now, we can't just
665 // call OnLookupComplete(). Instead we must wait until Resolve() has
666 // returned (IO_PENDING).
667 task_runner_->PostTask(FROM_HERE,
668 base::Bind(&ProcTask::OnLookupComplete,
669 this,
670 AddressList(),
671 start_time,
672 attempt_number_,
673 ERR_UNEXPECTED,
674 0));
675 return;
678 net_log_.AddEvent(
679 NetLog::TYPE_HOST_RESOLVER_IMPL_ATTEMPT_STARTED,
680 NetLog::IntegerCallback("attempt_number", attempt_number_));
682 // If we don't get the results within a given time, RetryIfNotComplete
683 // will start a new attempt on a different worker thread if none of our
684 // outstanding attempts have completed yet.
685 if (attempt_number_ <= params_.max_retry_attempts) {
686 task_runner_->PostDelayedTask(
687 FROM_HERE,
688 base::Bind(&ProcTask::RetryIfNotComplete, this),
689 params_.unresponsive_delay);
693 // WARNING: This code runs inside a worker pool. The shutdown code cannot
694 // wait for it to finish, so we must be very careful here about using other
695 // objects (like MessageLoops, Singletons, etc). During shutdown these objects
696 // may no longer exist. Multiple DoLookups() could be running in parallel, so
697 // any state inside of |this| must not mutate .
698 void DoLookup(const base::TimeTicks& start_time,
699 const uint32 attempt_number) {
700 AddressList results;
701 int os_error = 0;
702 // Running on the worker thread
703 int error = params_.resolver_proc->Resolve(key_.hostname,
704 key_.address_family,
705 key_.host_resolver_flags,
706 &results,
707 &os_error);
709 // Fail the resolution if the result contains 127.0.53.53. See the comment
710 // block of kIcanNameCollisionIp for details on why.
711 for (const auto& it : results) {
712 const IPAddressNumber& cur = it.address();
713 if (cur.size() == arraysize(kIcanNameCollisionIp) &&
714 0 == memcmp(&cur.front(), kIcanNameCollisionIp, cur.size())) {
715 error = ERR_ICANN_NAME_COLLISION;
716 break;
720 task_runner_->PostTask(FROM_HERE,
721 base::Bind(&ProcTask::OnLookupComplete,
722 this,
723 results,
724 start_time,
725 attempt_number,
726 error,
727 os_error));
730 // Makes next attempt if DoLookup() has not finished (runs on task runner
731 // thread).
732 void RetryIfNotComplete() {
733 DCHECK(task_runner_->BelongsToCurrentThread());
735 if (was_completed() || was_canceled())
736 return;
738 params_.unresponsive_delay *= params_.retry_factor;
739 StartLookupAttempt();
742 // Callback for when DoLookup() completes (runs on task runner thread).
743 void OnLookupComplete(const AddressList& results,
744 const base::TimeTicks& start_time,
745 const uint32 attempt_number,
746 int error,
747 const int os_error) {
748 DCHECK(task_runner_->BelongsToCurrentThread());
749 // If results are empty, we should return an error.
750 bool empty_list_on_ok = (error == OK && results.empty());
751 UMA_HISTOGRAM_BOOLEAN("DNS.EmptyAddressListAndNoError", empty_list_on_ok);
752 if (empty_list_on_ok)
753 error = ERR_NAME_NOT_RESOLVED;
755 bool was_retry_attempt = attempt_number > 1;
757 // Ideally the following code would be part of host_resolver_proc.cc,
758 // however it isn't safe to call NetworkChangeNotifier from worker threads.
759 // So we do it here on the IO thread instead.
760 if (error != OK && NetworkChangeNotifier::IsOffline())
761 error = ERR_INTERNET_DISCONNECTED;
763 // If this is the first attempt that is finishing later, then record data
764 // for the first attempt. Won't contaminate with retry attempt's data.
765 if (!was_retry_attempt)
766 RecordPerformanceHistograms(start_time, error, os_error);
768 RecordAttemptHistograms(start_time, attempt_number, error, os_error);
770 if (was_canceled())
771 return;
773 NetLog::ParametersCallback net_log_callback;
774 if (error != OK) {
775 net_log_callback = base::Bind(&NetLogProcTaskFailedCallback,
776 attempt_number,
777 error,
778 os_error);
779 } else {
780 net_log_callback = NetLog::IntegerCallback("attempt_number",
781 attempt_number);
783 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_ATTEMPT_FINISHED,
784 net_log_callback);
786 if (was_completed())
787 return;
789 // Copy the results from the first worker thread that resolves the host.
790 results_ = results;
791 completed_attempt_number_ = attempt_number;
792 completed_attempt_error_ = error;
794 if (was_retry_attempt) {
795 // If retry attempt finishes before 1st attempt, then get stats on how
796 // much time is saved by having spawned an extra attempt.
797 retry_attempt_finished_time_ = base::TimeTicks::Now();
800 if (error != OK) {
801 net_log_callback = base::Bind(&NetLogProcTaskFailedCallback,
802 0, error, os_error);
803 } else {
804 net_log_callback = results_.CreateNetLogCallback();
806 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK,
807 net_log_callback);
809 callback_.Run(error, results_);
812 void RecordPerformanceHistograms(const base::TimeTicks& start_time,
813 const int error,
814 const int os_error) const {
815 DCHECK(task_runner_->BelongsToCurrentThread());
816 enum Category { // Used in UMA_HISTOGRAM_ENUMERATION.
817 RESOLVE_SUCCESS,
818 RESOLVE_FAIL,
819 RESOLVE_SPECULATIVE_SUCCESS,
820 RESOLVE_SPECULATIVE_FAIL,
821 RESOLVE_MAX, // Bounding value.
823 int category = RESOLVE_MAX; // Illegal value for later DCHECK only.
825 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
826 if (error == OK) {
827 if (had_non_speculative_request_) {
828 category = RESOLVE_SUCCESS;
829 DNS_HISTOGRAM("DNS.ResolveSuccess", duration);
830 } else {
831 category = RESOLVE_SPECULATIVE_SUCCESS;
832 DNS_HISTOGRAM("DNS.ResolveSpeculativeSuccess", duration);
835 // Log DNS lookups based on |address_family|. This will help us determine
836 // if IPv4 or IPv4/6 lookups are faster or slower.
837 switch(key_.address_family) {
838 case ADDRESS_FAMILY_IPV4:
839 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_IPV4", duration);
840 break;
841 case ADDRESS_FAMILY_IPV6:
842 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_IPV6", duration);
843 break;
844 case ADDRESS_FAMILY_UNSPECIFIED:
845 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_UNSPEC", duration);
846 break;
848 } else {
849 if (had_non_speculative_request_) {
850 category = RESOLVE_FAIL;
851 DNS_HISTOGRAM("DNS.ResolveFail", duration);
852 } else {
853 category = RESOLVE_SPECULATIVE_FAIL;
854 DNS_HISTOGRAM("DNS.ResolveSpeculativeFail", duration);
856 // Log DNS lookups based on |address_family|. This will help us determine
857 // if IPv4 or IPv4/6 lookups are faster or slower.
858 switch(key_.address_family) {
859 case ADDRESS_FAMILY_IPV4:
860 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_IPV4", duration);
861 break;
862 case ADDRESS_FAMILY_IPV6:
863 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_IPV6", duration);
864 break;
865 case ADDRESS_FAMILY_UNSPECIFIED:
866 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_UNSPEC", duration);
867 break;
869 UMA_HISTOGRAM_CUSTOM_ENUMERATION(kOSErrorsForGetAddrinfoHistogramName,
870 std::abs(os_error),
871 GetAllGetAddrinfoOSErrors());
873 DCHECK_LT(category, static_cast<int>(RESOLVE_MAX)); // Be sure it was set.
875 UMA_HISTOGRAM_ENUMERATION("DNS.ResolveCategory", category, RESOLVE_MAX);
878 void RecordAttemptHistograms(const base::TimeTicks& start_time,
879 const uint32 attempt_number,
880 const int error,
881 const int os_error) const {
882 DCHECK(task_runner_->BelongsToCurrentThread());
883 bool first_attempt_to_complete =
884 completed_attempt_number_ == attempt_number;
885 bool is_first_attempt = (attempt_number == 1);
887 if (first_attempt_to_complete) {
888 // If this was first attempt to complete, then record the resolution
889 // status of the attempt.
890 if (completed_attempt_error_ == OK) {
891 UMA_HISTOGRAM_ENUMERATION(
892 "DNS.AttemptFirstSuccess", attempt_number, 100);
893 } else {
894 UMA_HISTOGRAM_ENUMERATION(
895 "DNS.AttemptFirstFailure", attempt_number, 100);
899 if (error == OK)
900 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptSuccess", attempt_number, 100);
901 else
902 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptFailure", attempt_number, 100);
904 // If first attempt didn't finish before retry attempt, then calculate stats
905 // on how much time is saved by having spawned an extra attempt.
906 if (!first_attempt_to_complete && is_first_attempt && !was_canceled()) {
907 DNS_HISTOGRAM("DNS.AttemptTimeSavedByRetry",
908 base::TimeTicks::Now() - retry_attempt_finished_time_);
911 if (was_canceled() || !first_attempt_to_complete) {
912 // Count those attempts which completed after the job was already canceled
913 // OR after the job was already completed by an earlier attempt (so in
914 // effect).
915 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptDiscarded", attempt_number, 100);
917 // Record if job is canceled.
918 if (was_canceled())
919 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptCancelled", attempt_number, 100);
922 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
923 if (error == OK)
924 DNS_HISTOGRAM("DNS.AttemptSuccessDuration", duration);
925 else
926 DNS_HISTOGRAM("DNS.AttemptFailDuration", duration);
929 // Set on the task runner thread, read on the worker thread.
930 Key key_;
932 // Holds an owning reference to the HostResolverProc that we are going to use.
933 // This may not be the current resolver procedure by the time we call
934 // ResolveAddrInfo, but that's OK... we'll use it anyways, and the owning
935 // reference ensures that it remains valid until we are done.
936 ProcTaskParams params_;
938 // The listener to the results of this ProcTask.
939 Callback callback_;
941 // Used to post ourselves onto the task runner thread.
942 scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
944 // Keeps track of the number of attempts we have made so far to resolve the
945 // host. Whenever we start an attempt to resolve the host, we increase this
946 // number.
947 uint32 attempt_number_;
949 // The index of the attempt which finished first (or 0 if the job is still in
950 // progress).
951 uint32 completed_attempt_number_;
953 // The result (a net error code) from the first attempt to complete.
954 int completed_attempt_error_;
956 // The time when retry attempt was finished.
957 base::TimeTicks retry_attempt_finished_time_;
959 // True if a non-speculative request was ever attached to this job
960 // (regardless of whether or not it was later canceled.
961 // This boolean is used for histogramming the duration of jobs used to
962 // service non-speculative requests.
963 bool had_non_speculative_request_;
965 AddressList results_;
967 BoundNetLog net_log_;
969 DISALLOW_COPY_AND_ASSIGN(ProcTask);
972 //-----------------------------------------------------------------------------
974 // Wraps a call to HaveOnlyLoopbackAddresses to be executed on the WorkerPool as
975 // it takes 40-100ms and should not block initialization.
976 class HostResolverImpl::LoopbackProbeJob {
977 public:
978 explicit LoopbackProbeJob(const base::WeakPtr<HostResolverImpl>& resolver)
979 : resolver_(resolver),
980 result_(false) {
981 DCHECK(resolver.get());
982 const bool kIsSlow = true;
983 base::WorkerPool::PostTaskAndReply(
984 FROM_HERE,
985 base::Bind(&LoopbackProbeJob::DoProbe, base::Unretained(this)),
986 base::Bind(&LoopbackProbeJob::OnProbeComplete, base::Owned(this)),
987 kIsSlow);
990 virtual ~LoopbackProbeJob() {}
992 private:
993 // Runs on worker thread.
994 void DoProbe() {
995 result_ = HaveOnlyLoopbackAddresses();
998 void OnProbeComplete() {
999 if (!resolver_.get())
1000 return;
1001 resolver_->SetHaveOnlyLoopbackAddresses(result_);
1004 // Used/set only on task runner thread.
1005 base::WeakPtr<HostResolverImpl> resolver_;
1007 bool result_;
1009 DISALLOW_COPY_AND_ASSIGN(LoopbackProbeJob);
1012 //-----------------------------------------------------------------------------
1014 // Resolves the hostname using DnsTransaction.
1015 // TODO(szym): This could be moved to separate source file as well.
1016 class HostResolverImpl::DnsTask : public base::SupportsWeakPtr<DnsTask> {
1017 public:
1018 class Delegate {
1019 public:
1020 virtual void OnDnsTaskComplete(base::TimeTicks start_time,
1021 int net_error,
1022 const AddressList& addr_list,
1023 base::TimeDelta ttl) = 0;
1025 // Called when the first of two jobs succeeds. If the first completed
1026 // transaction fails, this is not called. Also not called when the DnsTask
1027 // only needs to run one transaction.
1028 virtual void OnFirstDnsTransactionComplete() = 0;
1030 protected:
1031 Delegate() {}
1032 virtual ~Delegate() {}
1035 DnsTask(DnsClient* client,
1036 const Key& key,
1037 Delegate* delegate,
1038 const BoundNetLog& job_net_log)
1039 : client_(client),
1040 key_(key),
1041 delegate_(delegate),
1042 net_log_(job_net_log),
1043 num_completed_transactions_(0),
1044 task_start_time_(base::TimeTicks::Now()) {
1045 DCHECK(client);
1046 DCHECK(delegate_);
1049 bool needs_two_transactions() const {
1050 return key_.address_family == ADDRESS_FAMILY_UNSPECIFIED;
1053 bool needs_another_transaction() const {
1054 return needs_two_transactions() && !transaction_aaaa_;
1057 void StartFirstTransaction() {
1058 DCHECK_EQ(0u, num_completed_transactions_);
1059 net_log_.BeginEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK);
1060 if (key_.address_family == ADDRESS_FAMILY_IPV6) {
1061 StartAAAA();
1062 } else {
1063 StartA();
1067 void StartSecondTransaction() {
1068 DCHECK(needs_two_transactions());
1069 StartAAAA();
1072 private:
1073 void StartA() {
1074 DCHECK(!transaction_a_);
1075 DCHECK_NE(ADDRESS_FAMILY_IPV6, key_.address_family);
1076 transaction_a_ = CreateTransaction(ADDRESS_FAMILY_IPV4);
1077 transaction_a_->Start();
1080 void StartAAAA() {
1081 DCHECK(!transaction_aaaa_);
1082 DCHECK_NE(ADDRESS_FAMILY_IPV4, key_.address_family);
1083 transaction_aaaa_ = CreateTransaction(ADDRESS_FAMILY_IPV6);
1084 transaction_aaaa_->Start();
1087 scoped_ptr<DnsTransaction> CreateTransaction(AddressFamily family) {
1088 DCHECK_NE(ADDRESS_FAMILY_UNSPECIFIED, family);
1089 return client_->GetTransactionFactory()->CreateTransaction(
1090 key_.hostname,
1091 family == ADDRESS_FAMILY_IPV6 ? dns_protocol::kTypeAAAA :
1092 dns_protocol::kTypeA,
1093 base::Bind(&DnsTask::OnTransactionComplete, base::Unretained(this),
1094 base::TimeTicks::Now()),
1095 net_log_);
1098 void OnTransactionComplete(const base::TimeTicks& start_time,
1099 DnsTransaction* transaction,
1100 int net_error,
1101 const DnsResponse* response) {
1102 DCHECK(transaction);
1103 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
1104 if (net_error != OK) {
1105 DNS_HISTOGRAM("AsyncDNS.TransactionFailure", duration);
1106 OnFailure(net_error, DnsResponse::DNS_PARSE_OK);
1107 return;
1110 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess", duration);
1111 switch (transaction->GetType()) {
1112 case dns_protocol::kTypeA:
1113 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess_A", duration);
1114 break;
1115 case dns_protocol::kTypeAAAA:
1116 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess_AAAA", duration);
1117 break;
1120 AddressList addr_list;
1121 base::TimeDelta ttl;
1122 DnsResponse::Result result = response->ParseToAddressList(&addr_list, &ttl);
1123 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ParseToAddressList",
1124 result,
1125 DnsResponse::DNS_PARSE_RESULT_MAX);
1126 if (result != DnsResponse::DNS_PARSE_OK) {
1127 // Fail even if the other query succeeds.
1128 OnFailure(ERR_DNS_MALFORMED_RESPONSE, result);
1129 return;
1132 ++num_completed_transactions_;
1133 if (num_completed_transactions_ == 1) {
1134 ttl_ = ttl;
1135 } else {
1136 ttl_ = std::min(ttl_, ttl);
1139 if (transaction->GetType() == dns_protocol::kTypeA) {
1140 DCHECK_EQ(transaction_a_.get(), transaction);
1141 // Place IPv4 addresses after IPv6.
1142 addr_list_.insert(addr_list_.end(), addr_list.begin(), addr_list.end());
1143 } else {
1144 DCHECK_EQ(transaction_aaaa_.get(), transaction);
1145 // Place IPv6 addresses before IPv4.
1146 addr_list_.insert(addr_list_.begin(), addr_list.begin(), addr_list.end());
1149 if (needs_two_transactions() && num_completed_transactions_ == 1) {
1150 // No need to repeat the suffix search.
1151 key_.hostname = transaction->GetHostname();
1152 delegate_->OnFirstDnsTransactionComplete();
1153 return;
1156 if (addr_list_.empty()) {
1157 // TODO(szym): Don't fallback to ProcTask in this case.
1158 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
1159 return;
1162 // If there are multiple addresses, and at least one is IPv6, need to sort
1163 // them. Note that IPv6 addresses are always put before IPv4 ones, so it's
1164 // sufficient to just check the family of the first address.
1165 if (addr_list_.size() > 1 &&
1166 addr_list_[0].GetFamily() == ADDRESS_FAMILY_IPV6) {
1167 // Sort addresses if needed. Sort could complete synchronously.
1168 client_->GetAddressSorter()->Sort(
1169 addr_list_,
1170 base::Bind(&DnsTask::OnSortComplete,
1171 AsWeakPtr(),
1172 base::TimeTicks::Now()));
1173 } else {
1174 OnSuccess(addr_list_);
1178 void OnSortComplete(base::TimeTicks start_time,
1179 bool success,
1180 const AddressList& addr_list) {
1181 if (!success) {
1182 DNS_HISTOGRAM("AsyncDNS.SortFailure",
1183 base::TimeTicks::Now() - start_time);
1184 OnFailure(ERR_DNS_SORT_ERROR, DnsResponse::DNS_PARSE_OK);
1185 return;
1188 DNS_HISTOGRAM("AsyncDNS.SortSuccess",
1189 base::TimeTicks::Now() - start_time);
1191 // AddressSorter prunes unusable destinations.
1192 if (addr_list.empty()) {
1193 LOG(WARNING) << "Address list empty after RFC3484 sort";
1194 OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
1195 return;
1198 OnSuccess(addr_list);
1201 void OnFailure(int net_error, DnsResponse::Result result) {
1202 DCHECK_NE(OK, net_error);
1203 net_log_.EndEvent(
1204 NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK,
1205 base::Bind(&NetLogDnsTaskFailedCallback, net_error, result));
1206 delegate_->OnDnsTaskComplete(task_start_time_, net_error, AddressList(),
1207 base::TimeDelta());
1210 void OnSuccess(const AddressList& addr_list) {
1211 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK,
1212 addr_list.CreateNetLogCallback());
1213 delegate_->OnDnsTaskComplete(task_start_time_, OK, addr_list, ttl_);
1216 DnsClient* client_;
1217 Key key_;
1219 // The listener to the results of this DnsTask.
1220 Delegate* delegate_;
1221 const BoundNetLog net_log_;
1223 scoped_ptr<DnsTransaction> transaction_a_;
1224 scoped_ptr<DnsTransaction> transaction_aaaa_;
1226 unsigned num_completed_transactions_;
1228 // These are updated as each transaction completes.
1229 base::TimeDelta ttl_;
1230 // IPv6 addresses must appear first in the list.
1231 AddressList addr_list_;
1233 base::TimeTicks task_start_time_;
1235 DISALLOW_COPY_AND_ASSIGN(DnsTask);
1238 //-----------------------------------------------------------------------------
1240 // Aggregates all Requests for the same Key. Dispatched via PriorityDispatch.
1241 class HostResolverImpl::Job : public PrioritizedDispatcher::Job,
1242 public HostResolverImpl::DnsTask::Delegate {
1243 public:
1244 // Creates new job for |key| where |request_net_log| is bound to the
1245 // request that spawned it.
1246 Job(const base::WeakPtr<HostResolverImpl>& resolver,
1247 const Key& key,
1248 RequestPriority priority,
1249 const BoundNetLog& source_net_log)
1250 : resolver_(resolver),
1251 key_(key),
1252 priority_tracker_(priority),
1253 had_non_speculative_request_(false),
1254 had_dns_config_(false),
1255 num_occupied_job_slots_(0),
1256 dns_task_error_(OK),
1257 creation_time_(base::TimeTicks::Now()),
1258 priority_change_time_(creation_time_),
1259 net_log_(BoundNetLog::Make(source_net_log.net_log(),
1260 NetLog::SOURCE_HOST_RESOLVER_IMPL_JOB)) {
1261 source_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_CREATE_JOB);
1263 net_log_.BeginEvent(
1264 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
1265 base::Bind(&NetLogJobCreationCallback,
1266 source_net_log.source(),
1267 &key_.hostname));
1270 ~Job() override {
1271 if (is_running()) {
1272 // |resolver_| was destroyed with this Job still in flight.
1273 // Clean-up, record in the log, but don't run any callbacks.
1274 if (is_proc_running()) {
1275 proc_task_->Cancel();
1276 proc_task_ = NULL;
1278 // Clean up now for nice NetLog.
1279 KillDnsTask();
1280 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
1281 ERR_ABORTED);
1282 } else if (is_queued()) {
1283 // |resolver_| was destroyed without running this Job.
1284 // TODO(szym): is there any benefit in having this distinction?
1285 net_log_.AddEvent(NetLog::TYPE_CANCELLED);
1286 net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB);
1288 // else CompleteRequests logged EndEvent.
1290 // Log any remaining Requests as cancelled.
1291 for (RequestsList::const_iterator it = requests_.begin();
1292 it != requests_.end(); ++it) {
1293 Request* req = *it;
1294 if (req->was_canceled())
1295 continue;
1296 DCHECK_EQ(this, req->job());
1297 LogCancelRequest(req->source_net_log(), req->info());
1301 // Add this job to the dispatcher. If "at_head" is true, adds at the front
1302 // of the queue.
1303 void Schedule(bool at_head) {
1304 DCHECK(!is_queued());
1305 PrioritizedDispatcher::Handle handle;
1306 if (!at_head) {
1307 handle = resolver_->dispatcher_->Add(this, priority());
1308 } else {
1309 handle = resolver_->dispatcher_->AddAtHead(this, priority());
1311 // The dispatcher could have started |this| in the above call to Add, which
1312 // could have called Schedule again. In that case |handle| will be null,
1313 // but |handle_| may have been set by the other nested call to Schedule.
1314 if (!handle.is_null()) {
1315 DCHECK(handle_.is_null());
1316 handle_ = handle;
1320 void AddRequest(scoped_ptr<Request> req) {
1321 DCHECK_EQ(key_.hostname, req->info().hostname());
1323 req->set_job(this);
1324 priority_tracker_.Add(req->priority());
1326 req->source_net_log().AddEvent(
1327 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_ATTACH,
1328 net_log_.source().ToEventParametersCallback());
1330 net_log_.AddEvent(
1331 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_REQUEST_ATTACH,
1332 base::Bind(&NetLogJobAttachCallback,
1333 req->source_net_log().source(),
1334 priority()));
1336 // TODO(szym): Check if this is still needed.
1337 if (!req->info().is_speculative()) {
1338 had_non_speculative_request_ = true;
1339 if (proc_task_.get())
1340 proc_task_->set_had_non_speculative_request();
1343 requests_.push_back(req.Pass());
1345 UpdatePriority();
1348 // Marks |req| as cancelled. If it was the last active Request, also finishes
1349 // this Job, marking it as cancelled, and deletes it.
1350 void CancelRequest(Request* req) {
1351 DCHECK_EQ(key_.hostname, req->info().hostname());
1352 DCHECK(!req->was_canceled());
1354 // Don't remove it from |requests_| just mark it canceled.
1355 req->MarkAsCanceled();
1356 LogCancelRequest(req->source_net_log(), req->info());
1358 priority_tracker_.Remove(req->priority());
1359 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_REQUEST_DETACH,
1360 base::Bind(&NetLogJobAttachCallback,
1361 req->source_net_log().source(),
1362 priority()));
1364 if (num_active_requests() > 0) {
1365 UpdatePriority();
1366 } else {
1367 // If we were called from a Request's callback within CompleteRequests,
1368 // that Request could not have been cancelled, so num_active_requests()
1369 // could not be 0. Therefore, we are not in CompleteRequests().
1370 CompleteRequestsWithError(OK /* cancelled */);
1374 // Called from AbortAllInProgressJobs. Completes all requests and destroys
1375 // the job. This currently assumes the abort is due to a network change.
1376 void Abort() {
1377 DCHECK(is_running());
1378 CompleteRequestsWithError(ERR_NETWORK_CHANGED);
1381 // If DnsTask present, abort it and fall back to ProcTask.
1382 void AbortDnsTask() {
1383 if (dns_task_) {
1384 KillDnsTask();
1385 dns_task_error_ = OK;
1386 StartProcTask();
1390 // Called by HostResolverImpl when this job is evicted due to queue overflow.
1391 // Completes all requests and destroys the job.
1392 void OnEvicted() {
1393 DCHECK(!is_running());
1394 DCHECK(is_queued());
1395 handle_.Reset();
1397 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_EVICTED);
1399 // This signals to CompleteRequests that this job never ran.
1400 CompleteRequestsWithError(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
1403 // Attempts to serve the job from HOSTS. Returns true if succeeded and
1404 // this Job was destroyed.
1405 bool ServeFromHosts() {
1406 DCHECK_GT(num_active_requests(), 0u);
1407 AddressList addr_list;
1408 if (resolver_->ServeFromHosts(key(),
1409 requests_.front()->info(),
1410 &addr_list)) {
1411 // This will destroy the Job.
1412 CompleteRequests(
1413 HostCache::Entry(OK, MakeAddressListForRequest(addr_list)),
1414 base::TimeDelta());
1415 return true;
1417 return false;
1420 const Key& key() const { return key_; }
1422 bool is_queued() const {
1423 return !handle_.is_null();
1426 bool is_running() const {
1427 return is_dns_running() || is_proc_running();
1430 private:
1431 void KillDnsTask() {
1432 if (dns_task_) {
1433 ReduceToOneJobSlot();
1434 dns_task_.reset();
1438 // Reduce the number of job slots occupied and queued in the dispatcher
1439 // to one. If the second Job slot is queued in the dispatcher, cancels the
1440 // queued job. Otherwise, the second Job has been started by the
1441 // PrioritizedDispatcher, so signals it is complete.
1442 void ReduceToOneJobSlot() {
1443 DCHECK_GE(num_occupied_job_slots_, 1u);
1444 if (is_queued()) {
1445 resolver_->dispatcher_->Cancel(handle_);
1446 handle_.Reset();
1447 } else if (num_occupied_job_slots_ > 1) {
1448 resolver_->dispatcher_->OnJobFinished();
1449 --num_occupied_job_slots_;
1451 DCHECK_EQ(1u, num_occupied_job_slots_);
1454 void UpdatePriority() {
1455 if (is_queued()) {
1456 if (priority() != static_cast<RequestPriority>(handle_.priority()))
1457 priority_change_time_ = base::TimeTicks::Now();
1458 handle_ = resolver_->dispatcher_->ChangePriority(handle_, priority());
1462 AddressList MakeAddressListForRequest(const AddressList& list) const {
1463 if (requests_.empty())
1464 return list;
1465 return AddressList::CopyWithPort(list, requests_.front()->info().port());
1468 // PriorityDispatch::Job:
1469 void Start() override {
1470 DCHECK_LE(num_occupied_job_slots_, 1u);
1472 handle_.Reset();
1473 ++num_occupied_job_slots_;
1475 if (num_occupied_job_slots_ == 2) {
1476 StartSecondDnsTransaction();
1477 return;
1480 DCHECK(!is_running());
1482 net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_STARTED);
1484 had_dns_config_ = resolver_->HaveDnsConfig();
1486 base::TimeTicks now = base::TimeTicks::Now();
1487 base::TimeDelta queue_time = now - creation_time_;
1488 base::TimeDelta queue_time_after_change = now - priority_change_time_;
1490 if (had_dns_config_) {
1491 DNS_HISTOGRAM_BY_PRIORITY("AsyncDNS.JobQueueTime", priority(),
1492 queue_time);
1493 DNS_HISTOGRAM_BY_PRIORITY("AsyncDNS.JobQueueTimeAfterChange", priority(),
1494 queue_time_after_change);
1495 } else {
1496 DNS_HISTOGRAM_BY_PRIORITY("DNS.JobQueueTime", priority(), queue_time);
1497 DNS_HISTOGRAM_BY_PRIORITY("DNS.JobQueueTimeAfterChange", priority(),
1498 queue_time_after_change);
1501 bool system_only =
1502 (key_.host_resolver_flags & HOST_RESOLVER_SYSTEM_ONLY) != 0;
1504 // Caution: Job::Start must not complete synchronously.
1505 if (!system_only && had_dns_config_ &&
1506 !ResemblesMulticastDNSName(key_.hostname)) {
1507 StartDnsTask();
1508 } else {
1509 StartProcTask();
1513 // TODO(szym): Since DnsTransaction does not consume threads, we can increase
1514 // the limits on |dispatcher_|. But in order to keep the number of WorkerPool
1515 // threads low, we will need to use an "inner" PrioritizedDispatcher with
1516 // tighter limits.
1517 void StartProcTask() {
1518 DCHECK(!is_dns_running());
1519 proc_task_ = new ProcTask(
1520 key_,
1521 resolver_->proc_params_,
1522 base::Bind(&Job::OnProcTaskComplete, base::Unretained(this),
1523 base::TimeTicks::Now()),
1524 net_log_);
1526 if (had_non_speculative_request_)
1527 proc_task_->set_had_non_speculative_request();
1528 // Start() could be called from within Resolve(), hence it must NOT directly
1529 // call OnProcTaskComplete, for example, on synchronous failure.
1530 proc_task_->Start();
1533 // Called by ProcTask when it completes.
1534 void OnProcTaskComplete(base::TimeTicks start_time,
1535 int net_error,
1536 const AddressList& addr_list) {
1537 DCHECK(is_proc_running());
1539 if (!resolver_->resolved_known_ipv6_hostname_ &&
1540 net_error == OK &&
1541 key_.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
1542 if (key_.hostname == "www.google.com") {
1543 resolver_->resolved_known_ipv6_hostname_ = true;
1544 bool got_ipv6_address = false;
1545 for (size_t i = 0; i < addr_list.size(); ++i) {
1546 if (addr_list[i].GetFamily() == ADDRESS_FAMILY_IPV6) {
1547 got_ipv6_address = true;
1548 break;
1551 UMA_HISTOGRAM_BOOLEAN("Net.UnspecResolvedIPv6", got_ipv6_address);
1555 if (dns_task_error_ != OK) {
1556 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
1557 if (net_error == OK) {
1558 DNS_HISTOGRAM("AsyncDNS.FallbackSuccess", duration);
1559 if ((dns_task_error_ == ERR_NAME_NOT_RESOLVED) &&
1560 ResemblesNetBIOSName(key_.hostname)) {
1561 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_SUSPECT_NETBIOS);
1562 } else {
1563 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_PROC_SUCCESS);
1565 UMA_HISTOGRAM_SPARSE_SLOWLY("AsyncDNS.ResolveError",
1566 std::abs(dns_task_error_));
1567 resolver_->OnDnsTaskResolve(dns_task_error_);
1568 } else {
1569 DNS_HISTOGRAM("AsyncDNS.FallbackFail", duration);
1570 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
1574 base::TimeDelta ttl =
1575 base::TimeDelta::FromSeconds(kNegativeCacheEntryTTLSeconds);
1576 if (net_error == OK)
1577 ttl = base::TimeDelta::FromSeconds(kCacheEntryTTLSeconds);
1579 // Don't store the |ttl| in cache since it's not obtained from the server.
1580 CompleteRequests(
1581 HostCache::Entry(net_error, MakeAddressListForRequest(addr_list)),
1582 ttl);
1585 void StartDnsTask() {
1586 DCHECK(resolver_->HaveDnsConfig());
1587 dns_task_.reset(new DnsTask(resolver_->dns_client_.get(), key_, this,
1588 net_log_));
1590 dns_task_->StartFirstTransaction();
1591 // Schedule a second transaction, if needed.
1592 if (dns_task_->needs_two_transactions())
1593 Schedule(true);
1596 void StartSecondDnsTransaction() {
1597 DCHECK(dns_task_->needs_two_transactions());
1598 dns_task_->StartSecondTransaction();
1601 // Called if DnsTask fails. It is posted from StartDnsTask, so Job may be
1602 // deleted before this callback. In this case dns_task is deleted as well,
1603 // so we use it as indicator whether Job is still valid.
1604 void OnDnsTaskFailure(const base::WeakPtr<DnsTask>& dns_task,
1605 base::TimeDelta duration,
1606 int net_error) {
1607 DNS_HISTOGRAM("AsyncDNS.ResolveFail", duration);
1609 if (dns_task == NULL)
1610 return;
1612 dns_task_error_ = net_error;
1614 // TODO(szym): Run ServeFromHosts now if nsswitch.conf says so.
1615 // http://crbug.com/117655
1617 // TODO(szym): Some net errors indicate lack of connectivity. Starting
1618 // ProcTask in that case is a waste of time.
1619 if (resolver_->fallback_to_proctask_) {
1620 KillDnsTask();
1621 StartProcTask();
1622 } else {
1623 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
1624 CompleteRequestsWithError(net_error);
1629 // HostResolverImpl::DnsTask::Delegate implementation:
1631 void OnDnsTaskComplete(base::TimeTicks start_time,
1632 int net_error,
1633 const AddressList& addr_list,
1634 base::TimeDelta ttl) override {
1635 DCHECK(is_dns_running());
1637 base::TimeDelta duration = base::TimeTicks::Now() - start_time;
1638 if (net_error != OK) {
1639 OnDnsTaskFailure(dns_task_->AsWeakPtr(), duration, net_error);
1640 return;
1642 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess", duration);
1643 // Log DNS lookups based on |address_family|.
1644 switch(key_.address_family) {
1645 case ADDRESS_FAMILY_IPV4:
1646 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_IPV4", duration);
1647 break;
1648 case ADDRESS_FAMILY_IPV6:
1649 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_IPV6", duration);
1650 break;
1651 case ADDRESS_FAMILY_UNSPECIFIED:
1652 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_UNSPEC", duration);
1653 break;
1656 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_DNS_SUCCESS);
1657 RecordTTL(ttl);
1659 resolver_->OnDnsTaskResolve(OK);
1661 base::TimeDelta bounded_ttl =
1662 std::max(ttl, base::TimeDelta::FromSeconds(kMinimumTTLSeconds));
1664 CompleteRequests(
1665 HostCache::Entry(net_error, MakeAddressListForRequest(addr_list), ttl),
1666 bounded_ttl);
1669 void OnFirstDnsTransactionComplete() override {
1670 DCHECK(dns_task_->needs_two_transactions());
1671 DCHECK_EQ(dns_task_->needs_another_transaction(), is_queued());
1672 // No longer need to occupy two dispatcher slots.
1673 ReduceToOneJobSlot();
1675 // We already have a job slot at the dispatcher, so if the second
1676 // transaction hasn't started, reuse it now instead of waiting in the queue
1677 // for the second slot.
1678 if (dns_task_->needs_another_transaction())
1679 dns_task_->StartSecondTransaction();
1682 // Performs Job's last rites. Completes all Requests. Deletes this.
1683 void CompleteRequests(const HostCache::Entry& entry,
1684 base::TimeDelta ttl) {
1685 CHECK(resolver_.get());
1687 // This job must be removed from resolver's |jobs_| now to make room for a
1688 // new job with the same key in case one of the OnComplete callbacks decides
1689 // to spawn one. Consequently, the job deletes itself when CompleteRequests
1690 // is done.
1691 scoped_ptr<Job> self_deleter(this);
1693 resolver_->RemoveJob(this);
1695 if (is_running()) {
1696 if (is_proc_running()) {
1697 DCHECK(!is_queued());
1698 proc_task_->Cancel();
1699 proc_task_ = NULL;
1701 KillDnsTask();
1703 // Signal dispatcher that a slot has opened.
1704 resolver_->dispatcher_->OnJobFinished();
1705 } else if (is_queued()) {
1706 resolver_->dispatcher_->Cancel(handle_);
1707 handle_.Reset();
1710 if (num_active_requests() == 0) {
1711 net_log_.AddEvent(NetLog::TYPE_CANCELLED);
1712 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
1713 OK);
1714 return;
1717 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
1718 entry.error);
1720 DCHECK(!requests_.empty());
1722 if (entry.error == OK) {
1723 // Record this histogram here, when we know the system has a valid DNS
1724 // configuration.
1725 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.HaveDnsConfig",
1726 resolver_->received_dns_config_);
1729 bool did_complete = (entry.error != ERR_NETWORK_CHANGED) &&
1730 (entry.error != ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
1731 if (did_complete)
1732 resolver_->CacheResult(key_, entry, ttl);
1734 // Complete all of the requests that were attached to the job.
1735 for (RequestsList::const_iterator it = requests_.begin();
1736 it != requests_.end(); ++it) {
1737 Request* req = *it;
1739 if (req->was_canceled())
1740 continue;
1742 DCHECK_EQ(this, req->job());
1743 // Update the net log and notify registered observers.
1744 LogFinishRequest(req->source_net_log(), req->info(), entry.error);
1745 if (did_complete) {
1746 // Record effective total time from creation to completion.
1747 RecordTotalTime(had_dns_config_, req->info().is_speculative(),
1748 base::TimeTicks::Now() - req->request_time());
1750 req->OnComplete(entry.error, entry.addrlist);
1752 // Check if the resolver was destroyed as a result of running the
1753 // callback. If it was, we could continue, but we choose to bail.
1754 if (!resolver_.get())
1755 return;
1759 // Convenience wrapper for CompleteRequests in case of failure.
1760 void CompleteRequestsWithError(int net_error) {
1761 CompleteRequests(HostCache::Entry(net_error, AddressList()),
1762 base::TimeDelta());
1765 RequestPriority priority() const {
1766 return priority_tracker_.highest_priority();
1769 // Number of non-canceled requests in |requests_|.
1770 size_t num_active_requests() const {
1771 return priority_tracker_.total_count();
1774 bool is_dns_running() const {
1775 return dns_task_.get() != NULL;
1778 bool is_proc_running() const {
1779 return proc_task_.get() != NULL;
1782 base::WeakPtr<HostResolverImpl> resolver_;
1784 Key key_;
1786 // Tracks the highest priority across |requests_|.
1787 PriorityTracker priority_tracker_;
1789 bool had_non_speculative_request_;
1791 // Distinguishes measurements taken while DnsClient was fully configured.
1792 bool had_dns_config_;
1794 // Number of slots occupied by this Job in resolver's PrioritizedDispatcher.
1795 unsigned num_occupied_job_slots_;
1797 // Result of DnsTask.
1798 int dns_task_error_;
1800 const base::TimeTicks creation_time_;
1801 base::TimeTicks priority_change_time_;
1803 BoundNetLog net_log_;
1805 // Resolves the host using a HostResolverProc.
1806 scoped_refptr<ProcTask> proc_task_;
1808 // Resolves the host using a DnsTransaction.
1809 scoped_ptr<DnsTask> dns_task_;
1811 // All Requests waiting for the result of this Job. Some can be canceled.
1812 RequestsList requests_;
1814 // A handle used in |HostResolverImpl::dispatcher_|.
1815 PrioritizedDispatcher::Handle handle_;
1818 //-----------------------------------------------------------------------------
1820 HostResolverImpl::ProcTaskParams::ProcTaskParams(
1821 HostResolverProc* resolver_proc,
1822 size_t max_retry_attempts)
1823 : resolver_proc(resolver_proc),
1824 max_retry_attempts(max_retry_attempts),
1825 unresponsive_delay(base::TimeDelta::FromMilliseconds(6000)),
1826 retry_factor(2) {
1827 // Maximum of 4 retry attempts for host resolution.
1828 static const size_t kDefaultMaxRetryAttempts = 4u;
1829 if (max_retry_attempts == HostResolver::kDefaultRetryAttempts)
1830 max_retry_attempts = kDefaultMaxRetryAttempts;
1833 HostResolverImpl::ProcTaskParams::~ProcTaskParams() {}
1835 HostResolverImpl::HostResolverImpl(const Options& options, NetLog* net_log)
1836 : max_queued_jobs_(0),
1837 proc_params_(NULL, options.max_retry_attempts),
1838 net_log_(net_log),
1839 received_dns_config_(false),
1840 num_dns_failures_(0),
1841 use_local_ipv6_(false),
1842 last_ipv6_probe_result_(true),
1843 resolved_known_ipv6_hostname_(false),
1844 additional_resolver_flags_(0),
1845 fallback_to_proctask_(true),
1846 weak_ptr_factory_(this),
1847 probe_weak_ptr_factory_(this) {
1848 if (options.enable_caching)
1849 cache_ = HostCache::CreateDefaultCache();
1851 PrioritizedDispatcher::Limits job_limits = options.GetDispatcherLimits();
1852 dispatcher_.reset(new PrioritizedDispatcher(job_limits));
1853 max_queued_jobs_ = job_limits.total_jobs * 100u;
1855 DCHECK_GE(dispatcher_->num_priorities(), static_cast<size_t>(NUM_PRIORITIES));
1857 #if defined(OS_WIN)
1858 EnsureWinsockInit();
1859 #endif
1860 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
1861 new LoopbackProbeJob(weak_ptr_factory_.GetWeakPtr());
1862 #endif
1863 NetworkChangeNotifier::AddIPAddressObserver(this);
1864 NetworkChangeNotifier::AddDNSObserver(this);
1865 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD) && \
1866 !defined(OS_ANDROID)
1867 EnsureDnsReloaderInit();
1868 #endif
1871 DnsConfig dns_config;
1872 NetworkChangeNotifier::GetDnsConfig(&dns_config);
1873 received_dns_config_ = dns_config.IsValid();
1874 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
1875 use_local_ipv6_ = !dns_config.IsValid() || dns_config.use_local_ipv6;
1878 fallback_to_proctask_ = !ConfigureAsyncDnsNoFallbackFieldTrial();
1881 HostResolverImpl::~HostResolverImpl() {
1882 // Prevent the dispatcher from starting new jobs.
1883 dispatcher_->SetLimitsToZero();
1884 // It's now safe for Jobs to call KillDsnTask on destruction, because
1885 // OnJobComplete will not start any new jobs.
1886 STLDeleteValues(&jobs_);
1888 NetworkChangeNotifier::RemoveIPAddressObserver(this);
1889 NetworkChangeNotifier::RemoveDNSObserver(this);
1892 void HostResolverImpl::SetMaxQueuedJobs(size_t value) {
1893 DCHECK_EQ(0u, dispatcher_->num_queued_jobs());
1894 DCHECK_GT(value, 0u);
1895 max_queued_jobs_ = value;
1898 int HostResolverImpl::Resolve(const RequestInfo& info,
1899 RequestPriority priority,
1900 AddressList* addresses,
1901 const CompletionCallback& callback,
1902 RequestHandle* out_req,
1903 const BoundNetLog& source_net_log) {
1904 DCHECK(addresses);
1905 DCHECK(CalledOnValidThread());
1906 DCHECK_EQ(false, callback.is_null());
1908 // Check that the caller supplied a valid hostname to resolve.
1909 std::string labeled_hostname;
1910 if (!DNSDomainFromDot(info.hostname(), &labeled_hostname))
1911 return ERR_NAME_NOT_RESOLVED;
1913 LogStartRequest(source_net_log, info);
1915 IPAddressNumber ip_number;
1916 IPAddressNumber* ip_number_ptr = nullptr;
1917 if (ParseIPLiteralToNumber(info.hostname(), &ip_number))
1918 ip_number_ptr = &ip_number;
1920 // Build a key that identifies the request in the cache and in the
1921 // outstanding jobs map.
1922 Key key = GetEffectiveKeyForRequest(info, ip_number_ptr, source_net_log);
1924 int rv = ResolveHelper(key, info, ip_number_ptr, addresses, source_net_log);
1925 if (rv != ERR_DNS_CACHE_MISS) {
1926 LogFinishRequest(source_net_log, info, rv);
1927 RecordTotalTime(HaveDnsConfig(), info.is_speculative(), base::TimeDelta());
1928 return rv;
1931 // Next we need to attach our request to a "job". This job is responsible for
1932 // calling "getaddrinfo(hostname)" on a worker thread.
1934 JobMap::iterator jobit = jobs_.find(key);
1935 Job* job;
1936 if (jobit == jobs_.end()) {
1937 job =
1938 new Job(weak_ptr_factory_.GetWeakPtr(), key, priority, source_net_log);
1939 job->Schedule(false);
1941 // Check for queue overflow.
1942 if (dispatcher_->num_queued_jobs() > max_queued_jobs_) {
1943 Job* evicted = static_cast<Job*>(dispatcher_->EvictOldestLowest());
1944 DCHECK(evicted);
1945 evicted->OnEvicted(); // Deletes |evicted|.
1946 if (evicted == job) {
1947 rv = ERR_HOST_RESOLVER_QUEUE_TOO_LARGE;
1948 LogFinishRequest(source_net_log, info, rv);
1949 return rv;
1952 jobs_.insert(jobit, std::make_pair(key, job));
1953 } else {
1954 job = jobit->second;
1957 // Can't complete synchronously. Create and attach request.
1958 scoped_ptr<Request> req(new Request(
1959 source_net_log, info, priority, callback, addresses));
1960 if (out_req)
1961 *out_req = reinterpret_cast<RequestHandle>(req.get());
1963 job->AddRequest(req.Pass());
1964 // Completion happens during Job::CompleteRequests().
1965 return ERR_IO_PENDING;
1968 int HostResolverImpl::ResolveHelper(const Key& key,
1969 const RequestInfo& info,
1970 const IPAddressNumber* ip_number,
1971 AddressList* addresses,
1972 const BoundNetLog& source_net_log) {
1973 // The result of |getaddrinfo| for empty hosts is inconsistent across systems.
1974 // On Windows it gives the default interface's address, whereas on Linux it
1975 // gives an error. We will make it fail on all platforms for consistency.
1976 if (info.hostname().empty() || info.hostname().size() > kMaxHostLength)
1977 return ERR_NAME_NOT_RESOLVED;
1979 int net_error = ERR_UNEXPECTED;
1980 if (ResolveAsIP(key, info, ip_number, &net_error, addresses))
1981 return net_error;
1982 if (ServeFromCache(key, info, &net_error, addresses)) {
1983 source_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_CACHE_HIT);
1984 return net_error;
1986 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
1987 // http://crbug.com/117655
1988 if (ServeFromHosts(key, info, addresses)) {
1989 source_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_HOSTS_HIT);
1990 return OK;
1993 if (ServeLocalhost(key, info, addresses))
1994 return OK;
1996 return ERR_DNS_CACHE_MISS;
1999 int HostResolverImpl::ResolveFromCache(const RequestInfo& info,
2000 AddressList* addresses,
2001 const BoundNetLog& source_net_log) {
2002 DCHECK(CalledOnValidThread());
2003 DCHECK(addresses);
2005 // Update the net log and notify registered observers.
2006 LogStartRequest(source_net_log, info);
2008 IPAddressNumber ip_number;
2009 IPAddressNumber* ip_number_ptr = nullptr;
2010 if (ParseIPLiteralToNumber(info.hostname(), &ip_number))
2011 ip_number_ptr = &ip_number;
2013 Key key = GetEffectiveKeyForRequest(info, ip_number_ptr, source_net_log);
2015 int rv = ResolveHelper(key, info, ip_number_ptr, addresses, source_net_log);
2016 LogFinishRequest(source_net_log, info, rv);
2017 return rv;
2020 void HostResolverImpl::CancelRequest(RequestHandle req_handle) {
2021 DCHECK(CalledOnValidThread());
2022 Request* req = reinterpret_cast<Request*>(req_handle);
2023 DCHECK(req);
2024 Job* job = req->job();
2025 DCHECK(job);
2026 job->CancelRequest(req);
2029 void HostResolverImpl::SetDnsClientEnabled(bool enabled) {
2030 DCHECK(CalledOnValidThread());
2031 #if defined(ENABLE_BUILT_IN_DNS)
2032 if (enabled && !dns_client_) {
2033 SetDnsClient(DnsClient::CreateClient(net_log_));
2034 } else if (!enabled && dns_client_) {
2035 SetDnsClient(scoped_ptr<DnsClient>());
2037 #endif
2040 HostCache* HostResolverImpl::GetHostCache() {
2041 return cache_.get();
2044 base::Value* HostResolverImpl::GetDnsConfigAsValue() const {
2045 // Check if async DNS is disabled.
2046 if (!dns_client_.get())
2047 return NULL;
2049 // Check if async DNS is enabled, but we currently have no configuration
2050 // for it.
2051 const DnsConfig* dns_config = dns_client_->GetConfig();
2052 if (dns_config == NULL)
2053 return new base::DictionaryValue();
2055 return dns_config->ToValue();
2058 bool HostResolverImpl::ResolveAsIP(const Key& key,
2059 const RequestInfo& info,
2060 const IPAddressNumber* ip_number,
2061 int* net_error,
2062 AddressList* addresses) {
2063 DCHECK(addresses);
2064 DCHECK(net_error);
2065 if (ip_number == nullptr)
2066 return false;
2068 DCHECK_EQ(key.host_resolver_flags &
2069 ~(HOST_RESOLVER_CANONNAME | HOST_RESOLVER_LOOPBACK_ONLY |
2070 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6),
2071 0) << " Unhandled flag";
2073 *net_error = OK;
2074 AddressFamily family = GetAddressFamily(*ip_number);
2075 if (key.address_family != ADDRESS_FAMILY_UNSPECIFIED &&
2076 key.address_family != family) {
2077 // Don't return IPv6 addresses for IPv4 queries, and vice versa.
2078 *net_error = ERR_NAME_NOT_RESOLVED;
2079 } else {
2080 *addresses = AddressList::CreateFromIPAddress(*ip_number, info.port());
2081 if (key.host_resolver_flags & HOST_RESOLVER_CANONNAME)
2082 addresses->SetDefaultCanonicalName();
2084 return true;
2087 bool HostResolverImpl::ServeFromCache(const Key& key,
2088 const RequestInfo& info,
2089 int* net_error,
2090 AddressList* addresses) {
2091 DCHECK(addresses);
2092 DCHECK(net_error);
2093 if (!info.allow_cached_response() || !cache_.get())
2094 return false;
2096 const HostCache::Entry* cache_entry = cache_->Lookup(
2097 key, base::TimeTicks::Now());
2098 if (!cache_entry)
2099 return false;
2101 *net_error = cache_entry->error;
2102 if (*net_error == OK) {
2103 if (cache_entry->has_ttl())
2104 RecordTTL(cache_entry->ttl);
2105 *addresses = EnsurePortOnAddressList(cache_entry->addrlist, info.port());
2107 return true;
2110 bool HostResolverImpl::ServeFromHosts(const Key& key,
2111 const RequestInfo& info,
2112 AddressList* addresses) {
2113 DCHECK(addresses);
2114 if (!HaveDnsConfig())
2115 return false;
2116 addresses->clear();
2118 // HOSTS lookups are case-insensitive.
2119 std::string hostname = base::ToLowerASCII(key.hostname);
2121 const DnsHosts& hosts = dns_client_->GetConfig()->hosts;
2123 // If |address_family| is ADDRESS_FAMILY_UNSPECIFIED other implementations
2124 // (glibc and c-ares) return the first matching line. We have more
2125 // flexibility, but lose implicit ordering.
2126 // We prefer IPv6 because "happy eyeballs" will fall back to IPv4 if
2127 // necessary.
2128 if (key.address_family == ADDRESS_FAMILY_IPV6 ||
2129 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
2130 DnsHosts::const_iterator it = hosts.find(
2131 DnsHostsKey(hostname, ADDRESS_FAMILY_IPV6));
2132 if (it != hosts.end())
2133 addresses->push_back(IPEndPoint(it->second, info.port()));
2136 if (key.address_family == ADDRESS_FAMILY_IPV4 ||
2137 key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
2138 DnsHosts::const_iterator it = hosts.find(
2139 DnsHostsKey(hostname, ADDRESS_FAMILY_IPV4));
2140 if (it != hosts.end())
2141 addresses->push_back(IPEndPoint(it->second, info.port()));
2144 // If got only loopback addresses and the family was restricted, resolve
2145 // again, without restrictions. See SystemHostResolverCall for rationale.
2146 if ((key.host_resolver_flags &
2147 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6) &&
2148 IsAllIPv4Loopback(*addresses)) {
2149 Key new_key(key);
2150 new_key.address_family = ADDRESS_FAMILY_UNSPECIFIED;
2151 new_key.host_resolver_flags &=
2152 ~HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
2153 return ServeFromHosts(new_key, info, addresses);
2155 return !addresses->empty();
2158 bool HostResolverImpl::ServeLocalhost(const Key& key,
2159 const RequestInfo& info,
2160 AddressList* addresses) {
2161 AddressList resolved_addresses;
2162 if (!ResolveLocalHostname(key.hostname, info.port(), &resolved_addresses))
2163 return false;
2165 addresses->clear();
2167 for (const auto& address : resolved_addresses) {
2168 // Include the address if:
2169 // - caller didn't specify an address family, or
2170 // - caller specifically asked for the address family of this address, or
2171 // - this is an IPv6 address and caller specifically asked for IPv4 due
2172 // to lack of detected IPv6 support. (See SystemHostResolverCall for
2173 // rationale).
2174 if (key.address_family == ADDRESS_FAMILY_UNSPECIFIED ||
2175 key.address_family == address.GetFamily() ||
2176 (address.GetFamily() == ADDRESS_FAMILY_IPV6 &&
2177 key.address_family == ADDRESS_FAMILY_IPV4 &&
2178 (key.host_resolver_flags &
2179 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6))) {
2180 addresses->push_back(address);
2184 return true;
2187 void HostResolverImpl::CacheResult(const Key& key,
2188 const HostCache::Entry& entry,
2189 base::TimeDelta ttl) {
2190 if (cache_.get())
2191 cache_->Set(key, entry, base::TimeTicks::Now(), ttl);
2194 void HostResolverImpl::RemoveJob(Job* job) {
2195 DCHECK(job);
2196 JobMap::iterator it = jobs_.find(job->key());
2197 if (it != jobs_.end() && it->second == job)
2198 jobs_.erase(it);
2201 void HostResolverImpl::SetHaveOnlyLoopbackAddresses(bool result) {
2202 if (result) {
2203 additional_resolver_flags_ |= HOST_RESOLVER_LOOPBACK_ONLY;
2204 } else {
2205 additional_resolver_flags_ &= ~HOST_RESOLVER_LOOPBACK_ONLY;
2209 HostResolverImpl::Key HostResolverImpl::GetEffectiveKeyForRequest(
2210 const RequestInfo& info,
2211 const IPAddressNumber* ip_number,
2212 const BoundNetLog& net_log) {
2213 HostResolverFlags effective_flags =
2214 info.host_resolver_flags() | additional_resolver_flags_;
2215 AddressFamily effective_address_family = info.address_family();
2217 if (info.address_family() == ADDRESS_FAMILY_UNSPECIFIED) {
2218 if (!use_local_ipv6_ &&
2219 // When resolving IPv4 literals, there's no need to probe for IPv6.
2220 // When resolving IPv6 literals, there's no benefit to artificially
2221 // limiting our resolution based on a probe. Prior logic ensures
2222 // that this query is UNSPECIFIED (see info.address_family()
2223 // check above) so the code requesting the resolution should be amenable
2224 // to receiving a IPv6 resolution.
2225 ip_number == nullptr) {
2226 if (!IsIPv6Reachable(net_log)) {
2227 effective_address_family = ADDRESS_FAMILY_IPV4;
2228 effective_flags |= HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
2233 return Key(info.hostname(), effective_address_family, effective_flags);
2236 bool HostResolverImpl::IsIPv6Reachable(const BoundNetLog& net_log) {
2237 base::TimeTicks now = base::TimeTicks::Now();
2238 bool cached = true;
2239 if ((now - last_ipv6_probe_time_).InMilliseconds() > kIPv6ProbePeriodMs) {
2240 IPAddressNumber address(kIPv6ProbeAddress,
2241 kIPv6ProbeAddress + arraysize(kIPv6ProbeAddress));
2242 last_ipv6_probe_result_ = IsGloballyReachable(address, net_log);
2243 last_ipv6_probe_time_ = now;
2244 cached = false;
2246 net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_IPV6_REACHABILITY_CHECK,
2247 base::Bind(&NetLogIPv6AvailableCallback,
2248 last_ipv6_probe_result_, cached));
2249 return last_ipv6_probe_result_;
2252 void HostResolverImpl::AbortAllInProgressJobs() {
2253 // In Abort, a Request callback could spawn new Jobs with matching keys, so
2254 // first collect and remove all running jobs from |jobs_|.
2255 ScopedVector<Job> jobs_to_abort;
2256 for (JobMap::iterator it = jobs_.begin(); it != jobs_.end(); ) {
2257 Job* job = it->second;
2258 if (job->is_running()) {
2259 jobs_to_abort.push_back(job);
2260 jobs_.erase(it++);
2261 } else {
2262 DCHECK(job->is_queued());
2263 ++it;
2267 // Pause the dispatcher so it won't start any new dispatcher jobs while
2268 // aborting the old ones. This is needed so that it won't start the second
2269 // DnsTransaction for a job in |jobs_to_abort| if the DnsConfig just became
2270 // invalid.
2271 PrioritizedDispatcher::Limits limits = dispatcher_->GetLimits();
2272 dispatcher_->SetLimits(
2273 PrioritizedDispatcher::Limits(limits.reserved_slots.size(), 0));
2275 // Life check to bail once |this| is deleted.
2276 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
2278 // Then Abort them.
2279 for (size_t i = 0; self.get() && i < jobs_to_abort.size(); ++i) {
2280 jobs_to_abort[i]->Abort();
2281 jobs_to_abort[i] = NULL;
2284 if (self)
2285 dispatcher_->SetLimits(limits);
2288 void HostResolverImpl::AbortDnsTasks() {
2289 // Pause the dispatcher so it won't start any new dispatcher jobs while
2290 // aborting the old ones. This is needed so that it won't start the second
2291 // DnsTransaction for a job if the DnsConfig just changed.
2292 PrioritizedDispatcher::Limits limits = dispatcher_->GetLimits();
2293 dispatcher_->SetLimits(
2294 PrioritizedDispatcher::Limits(limits.reserved_slots.size(), 0));
2296 for (JobMap::iterator it = jobs_.begin(); it != jobs_.end(); ++it)
2297 it->second->AbortDnsTask();
2298 dispatcher_->SetLimits(limits);
2301 void HostResolverImpl::TryServingAllJobsFromHosts() {
2302 if (!HaveDnsConfig())
2303 return;
2305 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2306 // http://crbug.com/117655
2308 // Life check to bail once |this| is deleted.
2309 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
2311 for (JobMap::iterator it = jobs_.begin(); self.get() && it != jobs_.end();) {
2312 Job* job = it->second;
2313 ++it;
2314 // This could remove |job| from |jobs_|, but iterator will remain valid.
2315 job->ServeFromHosts();
2319 void HostResolverImpl::OnIPAddressChanged() {
2320 resolved_known_ipv6_hostname_ = false;
2321 last_ipv6_probe_time_ = base::TimeTicks();
2322 // Abandon all ProbeJobs.
2323 probe_weak_ptr_factory_.InvalidateWeakPtrs();
2324 if (cache_.get())
2325 cache_->clear();
2326 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
2327 new LoopbackProbeJob(probe_weak_ptr_factory_.GetWeakPtr());
2328 #endif
2329 AbortAllInProgressJobs();
2330 // |this| may be deleted inside AbortAllInProgressJobs().
2333 void HostResolverImpl::OnInitialDNSConfigRead() {
2334 UpdateDNSConfig(false);
2337 void HostResolverImpl::OnDNSChanged() {
2338 UpdateDNSConfig(true);
2341 void HostResolverImpl::UpdateDNSConfig(bool config_changed) {
2342 DnsConfig dns_config;
2343 NetworkChangeNotifier::GetDnsConfig(&dns_config);
2345 if (net_log_) {
2346 net_log_->AddGlobalEntry(
2347 NetLog::TYPE_DNS_CONFIG_CHANGED,
2348 base::Bind(&NetLogDnsConfigCallback, &dns_config));
2351 // TODO(szym): Remove once http://crbug.com/137914 is resolved.
2352 received_dns_config_ = dns_config.IsValid();
2353 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
2354 use_local_ipv6_ = !dns_config.IsValid() || dns_config.use_local_ipv6;
2356 num_dns_failures_ = 0;
2358 // We want a new DnsSession in place, before we Abort running Jobs, so that
2359 // the newly started jobs use the new config.
2360 if (dns_client_.get()) {
2361 dns_client_->SetConfig(dns_config);
2362 if (dns_client_->GetConfig()) {
2363 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
2364 // If we just switched DnsClients, restart jobs using new resolver.
2365 // TODO(pauljensen): Is this necessary?
2366 config_changed = true;
2370 if (config_changed) {
2371 // If the DNS server has changed, existing cached info could be wrong so we
2372 // have to drop our internal cache :( Note that OS level DNS caches, such
2373 // as NSCD's cache should be dropped automatically by the OS when
2374 // resolv.conf changes so we don't need to do anything to clear that cache.
2375 if (cache_.get())
2376 cache_->clear();
2378 // Life check to bail once |this| is deleted.
2379 base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
2381 // Existing jobs will have been sent to the original server so they need to
2382 // be aborted.
2383 AbortAllInProgressJobs();
2385 // |this| may be deleted inside AbortAllInProgressJobs().
2386 if (self.get())
2387 TryServingAllJobsFromHosts();
2391 bool HostResolverImpl::HaveDnsConfig() const {
2392 // Use DnsClient only if it's fully configured and there is no override by
2393 // ScopedDefaultHostResolverProc.
2394 // The alternative is to use NetworkChangeNotifier to override DnsConfig,
2395 // but that would introduce construction order requirements for NCN and SDHRP.
2396 return (dns_client_.get() != NULL) && (dns_client_->GetConfig() != NULL) &&
2397 !(proc_params_.resolver_proc.get() == NULL &&
2398 HostResolverProc::GetDefault() != NULL);
2401 void HostResolverImpl::OnDnsTaskResolve(int net_error) {
2402 DCHECK(dns_client_);
2403 if (net_error == OK) {
2404 num_dns_failures_ = 0;
2405 return;
2407 ++num_dns_failures_;
2408 if (num_dns_failures_ < kMaximumDnsFailures)
2409 return;
2411 // Disable DnsClient until the next DNS change. Must be done before aborting
2412 // DnsTasks, since doing so may start new jobs.
2413 dns_client_->SetConfig(DnsConfig());
2415 // Switch jobs with active DnsTasks over to using ProcTasks.
2416 AbortDnsTasks();
2418 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", false);
2419 UMA_HISTOGRAM_SPARSE_SLOWLY("AsyncDNS.DnsClientDisabledReason",
2420 std::abs(net_error));
2423 void HostResolverImpl::SetDnsClient(scoped_ptr<DnsClient> dns_client) {
2424 // DnsClient and config must be updated before aborting DnsTasks, since doing
2425 // so may start new jobs.
2426 dns_client_ = dns_client.Pass();
2427 if (dns_client_ && !dns_client_->GetConfig() &&
2428 num_dns_failures_ < kMaximumDnsFailures) {
2429 DnsConfig dns_config;
2430 NetworkChangeNotifier::GetDnsConfig(&dns_config);
2431 dns_client_->SetConfig(dns_config);
2432 num_dns_failures_ = 0;
2433 if (dns_client_->GetConfig())
2434 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
2437 AbortDnsTasks();
2440 } // namespace net