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"
9 #elif defined(OS_POSIX)
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/message_loop/message_loop_proxy.h"
25 #include "base/metrics/field_trial.h"
26 #include "base/metrics/histogram.h"
27 #include "base/stl_util.h"
28 #include "base/strings/string_util.h"
29 #include "base/strings/utf_string_conversions.h"
30 #include "base/threading/worker_pool.h"
31 #include "base/time/time.h"
32 #include "base/values.h"
33 #include "net/base/address_family.h"
34 #include "net/base/address_list.h"
35 #include "net/base/dns_reloader.h"
36 #include "net/base/dns_util.h"
37 #include "net/base/host_port_pair.h"
38 #include "net/base/ip_endpoint.h"
39 #include "net/base/net_errors.h"
40 #include "net/base/net_util.h"
41 #include "net/dns/address_sorter.h"
42 #include "net/dns/dns_client.h"
43 #include "net/dns/dns_config_service.h"
44 #include "net/dns/dns_protocol.h"
45 #include "net/dns/dns_response.h"
46 #include "net/dns/dns_transaction.h"
47 #include "net/dns/host_resolver_proc.h"
48 #include "net/log/net_log.h"
49 #include "net/socket/client_socket_factory.h"
50 #include "net/udp/datagram_client_socket.h"
51 #include "url/url_canon_ip.h"
54 #include "net/base/winsock_init.h"
61 // Limit the size of hostnames that will be resolved to combat issues in
62 // some platform's resolvers.
63 const size_t kMaxHostLength
= 4096;
65 // Default TTL for successful resolutions with ProcTask.
66 const unsigned kCacheEntryTTLSeconds
= 60;
68 // Default TTL for unsuccessful resolutions with ProcTask.
69 const unsigned kNegativeCacheEntryTTLSeconds
= 0;
71 // Minimum TTL for successful resolutions with DnsTask.
72 const unsigned kMinimumTTLSeconds
= kCacheEntryTTLSeconds
;
74 const char kLocalhost
[] = "localhost.";
76 // We use a separate histogram name for each platform to facilitate the
77 // display of error codes by their symbolic name (since each platform has
78 // different mappings).
79 const char kOSErrorsForGetAddrinfoHistogramName
[] =
81 "Net.OSErrorsForGetAddrinfo_Win";
82 #elif defined(OS_MACOSX)
83 "Net.OSErrorsForGetAddrinfo_Mac";
84 #elif defined(OS_LINUX)
85 "Net.OSErrorsForGetAddrinfo_Linux";
87 "Net.OSErrorsForGetAddrinfo";
90 // Gets a list of the likely error codes that getaddrinfo() can return
91 // (non-exhaustive). These are the error codes that we will track via
93 std::vector
<int> GetAllGetAddrinfoOSErrors() {
96 #if !defined(OS_FREEBSD)
97 #if !defined(OS_ANDROID)
98 // EAI_ADDRFAMILY has been declared obsolete in Android's and
102 // EAI_NODATA has been declared obsolete in FreeBSD's netdb.h.
114 #elif defined(OS_WIN)
115 // See: http://msdn.microsoft.com/en-us/library/ms738520(VS.85).aspx
116 WSA_NOT_ENOUGH_MEMORY
,
126 // The following are not in doc, but might be to appearing in results :-(.
131 // Ensure all errors are positive, as histogram only tracks positive values.
132 for (size_t i
= 0; i
< arraysize(os_errors
); ++i
) {
133 os_errors
[i
] = std::abs(os_errors
[i
]);
136 return base::CustomHistogram::ArrayToCustomRanges(os_errors
,
137 arraysize(os_errors
));
140 enum DnsResolveStatus
{
141 RESOLVE_STATUS_DNS_SUCCESS
= 0,
142 RESOLVE_STATUS_PROC_SUCCESS
,
144 RESOLVE_STATUS_SUSPECT_NETBIOS
,
148 // ICANN uses this localhost address to indicate a name collision.
150 // The policy in Chromium is to fail host resolving if it resolves to
151 // this special address.
153 // Not however that IP literals are exempt from this policy, so it is still
154 // possible to navigate to http://127.0.53.53/ directly.
156 // For more details: https://www.icann.org/news/announcement-2-2014-08-01-en
157 const unsigned char kIcanNameCollisionIp
[] = {127, 0, 53, 53};
159 void UmaAsyncDnsResolveStatus(DnsResolveStatus result
) {
160 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ResolveStatus",
165 bool ResemblesNetBIOSName(const std::string
& hostname
) {
166 return (hostname
.size() < 16) && (hostname
.find('.') == std::string::npos
);
169 // True if |hostname| ends with either ".local" or ".local.".
170 bool ResemblesMulticastDNSName(const std::string
& hostname
) {
171 DCHECK(!hostname
.empty());
172 const char kSuffix
[] = ".local.";
173 const size_t kSuffixLen
= sizeof(kSuffix
) - 1;
174 const size_t kSuffixLenTrimmed
= kSuffixLen
- 1;
175 if (hostname
[hostname
.size() - 1] == '.') {
176 return hostname
.size() > kSuffixLen
&&
177 !hostname
.compare(hostname
.size() - kSuffixLen
, kSuffixLen
, kSuffix
);
179 return hostname
.size() > kSuffixLenTrimmed
&&
180 !hostname
.compare(hostname
.size() - kSuffixLenTrimmed
, kSuffixLenTrimmed
,
181 kSuffix
, kSuffixLenTrimmed
);
184 // Attempts to connect a UDP socket to |dest|:53.
185 bool IsGloballyReachable(const IPAddressNumber
& dest
,
186 const BoundNetLog
& net_log
) {
187 scoped_ptr
<DatagramClientSocket
> socket(
188 ClientSocketFactory::GetDefaultFactory()->CreateDatagramClientSocket(
189 DatagramSocket::DEFAULT_BIND
,
193 int rv
= socket
->Connect(IPEndPoint(dest
, 53));
197 rv
= socket
->GetLocalAddress(&endpoint
);
200 DCHECK_EQ(ADDRESS_FAMILY_IPV6
, endpoint
.GetFamily());
201 const IPAddressNumber
& address
= endpoint
.address();
202 bool is_link_local
= (address
[0] == 0xFE) && ((address
[1] & 0xC0) == 0x80);
205 const uint8 kTeredoPrefix
[] = { 0x20, 0x01, 0, 0 };
206 bool is_teredo
= std::equal(kTeredoPrefix
,
207 kTeredoPrefix
+ arraysize(kTeredoPrefix
),
214 // Provide a common macro to simplify code and readability. We must use a
215 // macro as the underlying HISTOGRAM macro creates static variables.
216 #define DNS_HISTOGRAM(name, time) UMA_HISTOGRAM_CUSTOM_TIMES(name, time, \
217 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromHours(1), 100)
219 // A macro to simplify code and readability.
220 #define DNS_HISTOGRAM_BY_PRIORITY(basename, priority, time) \
222 switch (priority) { \
223 case HIGHEST: DNS_HISTOGRAM(basename "_HIGHEST", time); break; \
224 case MEDIUM: DNS_HISTOGRAM(basename "_MEDIUM", time); break; \
225 case LOW: DNS_HISTOGRAM(basename "_LOW", time); break; \
226 case LOWEST: DNS_HISTOGRAM(basename "_LOWEST", time); break; \
227 case IDLE: DNS_HISTOGRAM(basename "_IDLE", time); break; \
228 default: NOTREACHED(); break; \
230 DNS_HISTOGRAM(basename, time); \
233 // Record time from Request creation until a valid DNS response.
234 void RecordTotalTime(bool had_dns_config
,
236 base::TimeDelta duration
) {
237 if (had_dns_config
) {
239 DNS_HISTOGRAM("AsyncDNS.TotalTime_speculative", duration
);
241 DNS_HISTOGRAM("AsyncDNS.TotalTime", duration
);
245 DNS_HISTOGRAM("DNS.TotalTime_speculative", duration
);
247 DNS_HISTOGRAM("DNS.TotalTime", duration
);
252 void RecordTTL(base::TimeDelta ttl
) {
253 UMA_HISTOGRAM_CUSTOM_TIMES("AsyncDNS.TTL", ttl
,
254 base::TimeDelta::FromSeconds(1),
255 base::TimeDelta::FromDays(1), 100);
258 bool ConfigureAsyncDnsNoFallbackFieldTrial() {
259 const bool kDefault
= false;
261 // Configure the AsyncDns field trial as follows:
262 // groups AsyncDnsNoFallbackA and AsyncDnsNoFallbackB: return true,
263 // groups AsyncDnsA and AsyncDnsB: return false,
264 // groups SystemDnsA and SystemDnsB: return false,
265 // otherwise (trial absent): return default.
266 std::string group_name
= base::FieldTrialList::FindFullName("AsyncDns");
267 if (!group_name
.empty())
268 return StartsWithASCII(group_name
, "AsyncDnsNoFallback", false);
272 //-----------------------------------------------------------------------------
274 AddressList
EnsurePortOnAddressList(const AddressList
& list
, uint16 port
) {
275 if (list
.empty() || list
.front().port() == port
)
277 return AddressList::CopyWithPort(list
, port
);
280 // Returns true if |addresses| contains only IPv4 loopback addresses.
281 bool IsAllIPv4Loopback(const AddressList
& addresses
) {
282 for (unsigned i
= 0; i
< addresses
.size(); ++i
) {
283 const IPAddressNumber
& address
= addresses
[i
].address();
284 switch (addresses
[i
].GetFamily()) {
285 case ADDRESS_FAMILY_IPV4
:
286 if (address
[0] != 127)
289 case ADDRESS_FAMILY_IPV6
:
299 // Creates NetLog parameters when the resolve failed.
300 base::Value
* NetLogProcTaskFailedCallback(uint32 attempt_number
,
303 NetLog::LogLevel
/* log_level */) {
304 base::DictionaryValue
* dict
= new base::DictionaryValue();
306 dict
->SetInteger("attempt_number", attempt_number
);
308 dict
->SetInteger("net_error", net_error
);
311 dict
->SetInteger("os_error", os_error
);
312 #if defined(OS_POSIX)
313 dict
->SetString("os_error_string", gai_strerror(os_error
));
314 #elif defined(OS_WIN)
315 // Map the error code to a human-readable string.
316 LPWSTR error_string
= NULL
;
317 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
318 0, // Use the internal message table.
320 0, // Use default language.
321 (LPWSTR
)&error_string
,
323 0); // Arguments (unused).
324 dict
->SetString("os_error_string", base::WideToUTF8(error_string
));
325 LocalFree(error_string
);
332 // Creates NetLog parameters when the DnsTask failed.
333 base::Value
* NetLogDnsTaskFailedCallback(int net_error
,
335 NetLog::LogLevel
/* log_level */) {
336 base::DictionaryValue
* dict
= new base::DictionaryValue();
337 dict
->SetInteger("net_error", net_error
);
339 dict
->SetInteger("dns_error", dns_error
);
343 // Creates NetLog parameters containing the information in a RequestInfo object,
344 // along with the associated NetLog::Source.
345 base::Value
* NetLogRequestInfoCallback(const HostResolver::RequestInfo
* info
,
346 NetLog::LogLevel
/* log_level */) {
347 base::DictionaryValue
* dict
= new base::DictionaryValue();
349 dict
->SetString("host", info
->host_port_pair().ToString());
350 dict
->SetInteger("address_family",
351 static_cast<int>(info
->address_family()));
352 dict
->SetBoolean("allow_cached_response", info
->allow_cached_response());
353 dict
->SetBoolean("is_speculative", info
->is_speculative());
357 // Creates NetLog parameters for the creation of a HostResolverImpl::Job.
358 base::Value
* NetLogJobCreationCallback(const NetLog::Source
& source
,
359 const std::string
* host
,
360 NetLog::LogLevel
/* log_level */) {
361 base::DictionaryValue
* dict
= new base::DictionaryValue();
362 source
.AddToEventParameters(dict
);
363 dict
->SetString("host", *host
);
367 // Creates NetLog parameters for HOST_RESOLVER_IMPL_JOB_ATTACH/DETACH events.
368 base::Value
* NetLogJobAttachCallback(const NetLog::Source
& source
,
369 RequestPriority priority
,
370 NetLog::LogLevel
/* log_level */) {
371 base::DictionaryValue
* dict
= new base::DictionaryValue();
372 source
.AddToEventParameters(dict
);
373 dict
->SetString("priority", RequestPriorityToString(priority
));
377 // Creates NetLog parameters for the DNS_CONFIG_CHANGED event.
378 base::Value
* NetLogDnsConfigCallback(const DnsConfig
* config
,
379 NetLog::LogLevel
/* log_level */) {
380 return config
->ToValue();
383 // The logging routines are defined here because some requests are resolved
384 // without a Request object.
386 // Logs when a request has just been started.
387 void LogStartRequest(const BoundNetLog
& source_net_log
,
388 const HostResolver::RequestInfo
& info
) {
389 source_net_log
.BeginEvent(
390 NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST
,
391 base::Bind(&NetLogRequestInfoCallback
, &info
));
394 // Logs when a request has just completed (before its callback is run).
395 void LogFinishRequest(const BoundNetLog
& source_net_log
,
396 const HostResolver::RequestInfo
& info
,
398 source_net_log
.EndEventWithNetErrorCode(
399 NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST
, net_error
);
402 // Logs when a request has been cancelled.
403 void LogCancelRequest(const BoundNetLog
& source_net_log
,
404 const HostResolverImpl::RequestInfo
& info
) {
405 source_net_log
.AddEvent(NetLog::TYPE_CANCELLED
);
406 source_net_log
.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST
);
409 //-----------------------------------------------------------------------------
411 // Keeps track of the highest priority.
412 class PriorityTracker
{
414 explicit PriorityTracker(RequestPriority initial_priority
)
415 : highest_priority_(initial_priority
), total_count_(0) {
416 memset(counts_
, 0, sizeof(counts_
));
419 RequestPriority
highest_priority() const {
420 return highest_priority_
;
423 size_t total_count() const {
427 void Add(RequestPriority req_priority
) {
429 ++counts_
[req_priority
];
430 if (highest_priority_
< req_priority
)
431 highest_priority_
= req_priority
;
434 void Remove(RequestPriority req_priority
) {
435 DCHECK_GT(total_count_
, 0u);
436 DCHECK_GT(counts_
[req_priority
], 0u);
438 --counts_
[req_priority
];
440 for (i
= highest_priority_
; i
> MINIMUM_PRIORITY
&& !counts_
[i
]; --i
);
441 highest_priority_
= static_cast<RequestPriority
>(i
);
443 // In absence of requests, default to MINIMUM_PRIORITY.
444 if (total_count_
== 0)
445 DCHECK_EQ(MINIMUM_PRIORITY
, highest_priority_
);
449 RequestPriority highest_priority_
;
451 size_t counts_
[NUM_PRIORITIES
];
456 //-----------------------------------------------------------------------------
458 const unsigned HostResolverImpl::kMaximumDnsFailures
= 16;
460 // Holds the data for a request that could not be completed synchronously.
461 // It is owned by a Job. Canceled Requests are only marked as canceled rather
462 // than removed from the Job's |requests_| list.
463 class HostResolverImpl::Request
{
465 Request(const BoundNetLog
& source_net_log
,
466 const RequestInfo
& info
,
467 RequestPriority priority
,
468 const CompletionCallback
& callback
,
469 AddressList
* addresses
)
470 : source_net_log_(source_net_log
),
475 addresses_(addresses
),
476 request_time_(base::TimeTicks::Now()) {}
478 // Mark the request as canceled.
479 void MarkAsCanceled() {
485 bool was_canceled() const {
486 return callback_
.is_null();
489 void set_job(Job
* job
) {
491 // Identify which job the request is waiting on.
495 // Prepare final AddressList and call completion callback.
496 void OnComplete(int error
, const AddressList
& addr_list
) {
497 DCHECK(!was_canceled());
499 *addresses_
= EnsurePortOnAddressList(addr_list
, info_
.port());
500 CompletionCallback callback
= callback_
;
509 // NetLog for the source, passed in HostResolver::Resolve.
510 const BoundNetLog
& source_net_log() {
511 return source_net_log_
;
514 const RequestInfo
& info() const {
518 RequestPriority
priority() const { return priority_
; }
520 base::TimeTicks
request_time() const { return request_time_
; }
523 const BoundNetLog source_net_log_
;
525 // The request info that started the request.
526 const RequestInfo info_
;
528 // TODO(akalin): Support reprioritization.
529 const RequestPriority priority_
;
531 // The resolve job that this request is dependent on.
534 // The user's callback to invoke when the request completes.
535 CompletionCallback callback_
;
537 // The address list to save result into.
538 AddressList
* addresses_
;
540 const base::TimeTicks request_time_
;
542 DISALLOW_COPY_AND_ASSIGN(Request
);
545 //------------------------------------------------------------------------------
547 // Calls HostResolverProc on the WorkerPool. Performs retries if necessary.
549 // Whenever we try to resolve the host, we post a delayed task to check if host
550 // resolution (OnLookupComplete) is completed or not. If the original attempt
551 // hasn't completed, then we start another attempt for host resolution. We take
552 // the results from the first attempt that finishes and ignore the results from
553 // all other attempts.
555 // TODO(szym): Move to separate source file for testing and mocking.
557 class HostResolverImpl::ProcTask
558 : public base::RefCountedThreadSafe
<HostResolverImpl::ProcTask
> {
560 typedef base::Callback
<void(int net_error
,
561 const AddressList
& addr_list
)> Callback
;
563 ProcTask(const Key
& key
,
564 const ProcTaskParams
& params
,
565 const Callback
& callback
,
566 const BoundNetLog
& job_net_log
)
570 origin_loop_(base::MessageLoopProxy::current()),
572 completed_attempt_number_(0),
573 completed_attempt_error_(ERR_UNEXPECTED
),
574 had_non_speculative_request_(false),
575 net_log_(job_net_log
) {
576 if (!params_
.resolver_proc
.get())
577 params_
.resolver_proc
= HostResolverProc::GetDefault();
578 // If default is unset, use the system proc.
579 if (!params_
.resolver_proc
.get())
580 params_
.resolver_proc
= new SystemHostResolverProc();
584 DCHECK(origin_loop_
->BelongsToCurrentThread());
585 net_log_
.BeginEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK
);
586 StartLookupAttempt();
589 // Cancels this ProcTask. It will be orphaned. Any outstanding resolve
590 // attempts running on worker threads will continue running. Only once all the
591 // attempts complete will the final reference to this ProcTask be released.
593 DCHECK(origin_loop_
->BelongsToCurrentThread());
595 if (was_canceled() || was_completed())
599 net_log_
.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK
);
602 void set_had_non_speculative_request() {
603 DCHECK(origin_loop_
->BelongsToCurrentThread());
604 had_non_speculative_request_
= true;
607 bool was_canceled() const {
608 DCHECK(origin_loop_
->BelongsToCurrentThread());
609 return callback_
.is_null();
612 bool was_completed() const {
613 DCHECK(origin_loop_
->BelongsToCurrentThread());
614 return completed_attempt_number_
> 0;
618 friend class base::RefCountedThreadSafe
<ProcTask
>;
621 void StartLookupAttempt() {
622 DCHECK(origin_loop_
->BelongsToCurrentThread());
623 base::TimeTicks start_time
= base::TimeTicks::Now();
625 // Dispatch the lookup attempt to a worker thread.
626 if (!base::WorkerPool::PostTask(
628 base::Bind(&ProcTask::DoLookup
, this, start_time
, attempt_number_
),
632 // Since we could be running within Resolve() right now, we can't just
633 // call OnLookupComplete(). Instead we must wait until Resolve() has
634 // returned (IO_PENDING).
635 origin_loop_
->PostTask(
637 base::Bind(&ProcTask::OnLookupComplete
, this, AddressList(),
638 start_time
, attempt_number_
, ERR_UNEXPECTED
, 0));
643 NetLog::TYPE_HOST_RESOLVER_IMPL_ATTEMPT_STARTED
,
644 NetLog::IntegerCallback("attempt_number", attempt_number_
));
646 // If we don't get the results within a given time, RetryIfNotComplete
647 // will start a new attempt on a different worker thread if none of our
648 // outstanding attempts have completed yet.
649 if (attempt_number_
<= params_
.max_retry_attempts
) {
650 origin_loop_
->PostDelayedTask(
652 base::Bind(&ProcTask::RetryIfNotComplete
, this),
653 params_
.unresponsive_delay
);
657 // WARNING: This code runs inside a worker pool. The shutdown code cannot
658 // wait for it to finish, so we must be very careful here about using other
659 // objects (like MessageLoops, Singletons, etc). During shutdown these objects
660 // may no longer exist. Multiple DoLookups() could be running in parallel, so
661 // any state inside of |this| must not mutate .
662 void DoLookup(const base::TimeTicks
& start_time
,
663 const uint32 attempt_number
) {
666 // Running on the worker thread
667 int error
= params_
.resolver_proc
->Resolve(key_
.hostname
,
669 key_
.host_resolver_flags
,
673 // Fail the resolution if the result contains 127.0.53.53. See the comment
674 // block of kIcanNameCollisionIp for details on why.
675 for (const auto& it
: results
) {
676 const IPAddressNumber
& cur
= it
.address();
677 if (cur
.size() == arraysize(kIcanNameCollisionIp
) &&
678 0 == memcmp(&cur
.front(), kIcanNameCollisionIp
, cur
.size())) {
679 error
= ERR_ICANN_NAME_COLLISION
;
684 origin_loop_
->PostTask(
686 base::Bind(&ProcTask::OnLookupComplete
, this, results
, start_time
,
687 attempt_number
, error
, os_error
));
690 // Makes next attempt if DoLookup() has not finished (runs on origin thread).
691 void RetryIfNotComplete() {
692 DCHECK(origin_loop_
->BelongsToCurrentThread());
694 if (was_completed() || was_canceled())
697 params_
.unresponsive_delay
*= params_
.retry_factor
;
698 StartLookupAttempt();
701 // Callback for when DoLookup() completes (runs on origin thread).
702 void OnLookupComplete(const AddressList
& results
,
703 const base::TimeTicks
& start_time
,
704 const uint32 attempt_number
,
706 const int os_error
) {
707 DCHECK(origin_loop_
->BelongsToCurrentThread());
708 // If results are empty, we should return an error.
709 bool empty_list_on_ok
= (error
== OK
&& results
.empty());
710 UMA_HISTOGRAM_BOOLEAN("DNS.EmptyAddressListAndNoError", empty_list_on_ok
);
711 if (empty_list_on_ok
)
712 error
= ERR_NAME_NOT_RESOLVED
;
714 bool was_retry_attempt
= attempt_number
> 1;
716 // Ideally the following code would be part of host_resolver_proc.cc,
717 // however it isn't safe to call NetworkChangeNotifier from worker threads.
718 // So we do it here on the IO thread instead.
719 if (error
!= OK
&& NetworkChangeNotifier::IsOffline())
720 error
= ERR_INTERNET_DISCONNECTED
;
722 // If this is the first attempt that is finishing later, then record data
723 // for the first attempt. Won't contaminate with retry attempt's data.
724 if (!was_retry_attempt
)
725 RecordPerformanceHistograms(start_time
, error
, os_error
);
727 RecordAttemptHistograms(start_time
, attempt_number
, error
, os_error
);
732 NetLog::ParametersCallback net_log_callback
;
734 net_log_callback
= base::Bind(&NetLogProcTaskFailedCallback
,
739 net_log_callback
= NetLog::IntegerCallback("attempt_number",
742 net_log_
.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_ATTEMPT_FINISHED
,
748 // Copy the results from the first worker thread that resolves the host.
750 completed_attempt_number_
= attempt_number
;
751 completed_attempt_error_
= error
;
753 if (was_retry_attempt
) {
754 // If retry attempt finishes before 1st attempt, then get stats on how
755 // much time is saved by having spawned an extra attempt.
756 retry_attempt_finished_time_
= base::TimeTicks::Now();
760 net_log_callback
= base::Bind(&NetLogProcTaskFailedCallback
,
763 net_log_callback
= results_
.CreateNetLogCallback();
765 net_log_
.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK
,
768 callback_
.Run(error
, results_
);
771 void RecordPerformanceHistograms(const base::TimeTicks
& start_time
,
773 const int os_error
) const {
774 DCHECK(origin_loop_
->BelongsToCurrentThread());
775 enum Category
{ // Used in UMA_HISTOGRAM_ENUMERATION.
778 RESOLVE_SPECULATIVE_SUCCESS
,
779 RESOLVE_SPECULATIVE_FAIL
,
780 RESOLVE_MAX
, // Bounding value.
782 int category
= RESOLVE_MAX
; // Illegal value for later DCHECK only.
784 base::TimeDelta duration
= base::TimeTicks::Now() - start_time
;
786 if (had_non_speculative_request_
) {
787 category
= RESOLVE_SUCCESS
;
788 DNS_HISTOGRAM("DNS.ResolveSuccess", duration
);
790 category
= RESOLVE_SPECULATIVE_SUCCESS
;
791 DNS_HISTOGRAM("DNS.ResolveSpeculativeSuccess", duration
);
794 // Log DNS lookups based on |address_family|. This will help us determine
795 // if IPv4 or IPv4/6 lookups are faster or slower.
796 switch(key_
.address_family
) {
797 case ADDRESS_FAMILY_IPV4
:
798 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_IPV4", duration
);
800 case ADDRESS_FAMILY_IPV6
:
801 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_IPV6", duration
);
803 case ADDRESS_FAMILY_UNSPECIFIED
:
804 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_UNSPEC", duration
);
808 if (had_non_speculative_request_
) {
809 category
= RESOLVE_FAIL
;
810 DNS_HISTOGRAM("DNS.ResolveFail", duration
);
812 category
= RESOLVE_SPECULATIVE_FAIL
;
813 DNS_HISTOGRAM("DNS.ResolveSpeculativeFail", duration
);
815 // Log DNS lookups based on |address_family|. This will help us determine
816 // if IPv4 or IPv4/6 lookups are faster or slower.
817 switch(key_
.address_family
) {
818 case ADDRESS_FAMILY_IPV4
:
819 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_IPV4", duration
);
821 case ADDRESS_FAMILY_IPV6
:
822 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_IPV6", duration
);
824 case ADDRESS_FAMILY_UNSPECIFIED
:
825 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_UNSPEC", duration
);
828 UMA_HISTOGRAM_CUSTOM_ENUMERATION(kOSErrorsForGetAddrinfoHistogramName
,
830 GetAllGetAddrinfoOSErrors());
832 DCHECK_LT(category
, static_cast<int>(RESOLVE_MAX
)); // Be sure it was set.
834 UMA_HISTOGRAM_ENUMERATION("DNS.ResolveCategory", category
, RESOLVE_MAX
);
837 void RecordAttemptHistograms(const base::TimeTicks
& start_time
,
838 const uint32 attempt_number
,
840 const int os_error
) const {
841 DCHECK(origin_loop_
->BelongsToCurrentThread());
842 bool first_attempt_to_complete
=
843 completed_attempt_number_
== attempt_number
;
844 bool is_first_attempt
= (attempt_number
== 1);
846 if (first_attempt_to_complete
) {
847 // If this was first attempt to complete, then record the resolution
848 // status of the attempt.
849 if (completed_attempt_error_
== OK
) {
850 UMA_HISTOGRAM_ENUMERATION(
851 "DNS.AttemptFirstSuccess", attempt_number
, 100);
853 UMA_HISTOGRAM_ENUMERATION(
854 "DNS.AttemptFirstFailure", attempt_number
, 100);
859 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptSuccess", attempt_number
, 100);
861 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptFailure", attempt_number
, 100);
863 // If first attempt didn't finish before retry attempt, then calculate stats
864 // on how much time is saved by having spawned an extra attempt.
865 if (!first_attempt_to_complete
&& is_first_attempt
&& !was_canceled()) {
866 DNS_HISTOGRAM("DNS.AttemptTimeSavedByRetry",
867 base::TimeTicks::Now() - retry_attempt_finished_time_
);
870 if (was_canceled() || !first_attempt_to_complete
) {
871 // Count those attempts which completed after the job was already canceled
872 // OR after the job was already completed by an earlier attempt (so in
874 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptDiscarded", attempt_number
, 100);
876 // Record if job is canceled.
878 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptCancelled", attempt_number
, 100);
881 base::TimeDelta duration
= base::TimeTicks::Now() - start_time
;
883 DNS_HISTOGRAM("DNS.AttemptSuccessDuration", duration
);
885 DNS_HISTOGRAM("DNS.AttemptFailDuration", duration
);
888 // Set on the origin thread, read on the worker thread.
891 // Holds an owning reference to the HostResolverProc that we are going to use.
892 // This may not be the current resolver procedure by the time we call
893 // ResolveAddrInfo, but that's OK... we'll use it anyways, and the owning
894 // reference ensures that it remains valid until we are done.
895 ProcTaskParams params_
;
897 // The listener to the results of this ProcTask.
900 // Used to post ourselves onto the origin thread.
901 scoped_refptr
<base::MessageLoopProxy
> origin_loop_
;
903 // Keeps track of the number of attempts we have made so far to resolve the
904 // host. Whenever we start an attempt to resolve the host, we increase this
906 uint32 attempt_number_
;
908 // The index of the attempt which finished first (or 0 if the job is still in
910 uint32 completed_attempt_number_
;
912 // The result (a net error code) from the first attempt to complete.
913 int completed_attempt_error_
;
915 // The time when retry attempt was finished.
916 base::TimeTicks retry_attempt_finished_time_
;
918 // True if a non-speculative request was ever attached to this job
919 // (regardless of whether or not it was later canceled.
920 // This boolean is used for histogramming the duration of jobs used to
921 // service non-speculative requests.
922 bool had_non_speculative_request_
;
924 AddressList results_
;
926 BoundNetLog net_log_
;
928 DISALLOW_COPY_AND_ASSIGN(ProcTask
);
931 //-----------------------------------------------------------------------------
933 // Wraps a call to HaveOnlyLoopbackAddresses to be executed on the WorkerPool as
934 // it takes 40-100ms and should not block initialization.
935 class HostResolverImpl::LoopbackProbeJob
{
937 explicit LoopbackProbeJob(const base::WeakPtr
<HostResolverImpl
>& resolver
)
938 : resolver_(resolver
),
940 DCHECK(resolver
.get());
941 const bool kIsSlow
= true;
942 base::WorkerPool::PostTaskAndReply(
944 base::Bind(&LoopbackProbeJob::DoProbe
, base::Unretained(this)),
945 base::Bind(&LoopbackProbeJob::OnProbeComplete
, base::Owned(this)),
949 virtual ~LoopbackProbeJob() {}
952 // Runs on worker thread.
954 result_
= HaveOnlyLoopbackAddresses();
957 void OnProbeComplete() {
958 if (!resolver_
.get())
960 resolver_
->SetHaveOnlyLoopbackAddresses(result_
);
963 // Used/set only on origin thread.
964 base::WeakPtr
<HostResolverImpl
> resolver_
;
968 DISALLOW_COPY_AND_ASSIGN(LoopbackProbeJob
);
971 //-----------------------------------------------------------------------------
973 // Resolves the hostname using DnsTransaction.
974 // TODO(szym): This could be moved to separate source file as well.
975 class HostResolverImpl::DnsTask
: public base::SupportsWeakPtr
<DnsTask
> {
979 virtual void OnDnsTaskComplete(base::TimeTicks start_time
,
981 const AddressList
& addr_list
,
982 base::TimeDelta ttl
) = 0;
984 // Called when the first of two jobs succeeds. If the first completed
985 // transaction fails, this is not called. Also not called when the DnsTask
986 // only needs to run one transaction.
987 virtual void OnFirstDnsTransactionComplete() = 0;
991 virtual ~Delegate() {}
994 DnsTask(DnsClient
* client
,
997 const BoundNetLog
& job_net_log
)
1000 delegate_(delegate
),
1001 net_log_(job_net_log
),
1002 num_completed_transactions_(0),
1003 task_start_time_(base::TimeTicks::Now()) {
1008 bool needs_two_transactions() const {
1009 return key_
.address_family
== ADDRESS_FAMILY_UNSPECIFIED
;
1012 bool needs_another_transaction() const {
1013 return needs_two_transactions() && !transaction_aaaa_
;
1016 void StartFirstTransaction() {
1017 DCHECK_EQ(0u, num_completed_transactions_
);
1018 net_log_
.BeginEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK
);
1019 if (key_
.address_family
== ADDRESS_FAMILY_IPV6
) {
1026 void StartSecondTransaction() {
1027 DCHECK(needs_two_transactions());
1033 DCHECK(!transaction_a_
);
1034 DCHECK_NE(ADDRESS_FAMILY_IPV6
, key_
.address_family
);
1035 transaction_a_
= CreateTransaction(ADDRESS_FAMILY_IPV4
);
1036 transaction_a_
->Start();
1040 DCHECK(!transaction_aaaa_
);
1041 DCHECK_NE(ADDRESS_FAMILY_IPV4
, key_
.address_family
);
1042 transaction_aaaa_
= CreateTransaction(ADDRESS_FAMILY_IPV6
);
1043 transaction_aaaa_
->Start();
1046 scoped_ptr
<DnsTransaction
> CreateTransaction(AddressFamily family
) {
1047 DCHECK_NE(ADDRESS_FAMILY_UNSPECIFIED
, family
);
1048 return client_
->GetTransactionFactory()->CreateTransaction(
1050 family
== ADDRESS_FAMILY_IPV6
? dns_protocol::kTypeAAAA
:
1051 dns_protocol::kTypeA
,
1052 base::Bind(&DnsTask::OnTransactionComplete
, base::Unretained(this),
1053 base::TimeTicks::Now()),
1057 void OnTransactionComplete(const base::TimeTicks
& start_time
,
1058 DnsTransaction
* transaction
,
1060 const DnsResponse
* response
) {
1061 DCHECK(transaction
);
1062 base::TimeDelta duration
= base::TimeTicks::Now() - start_time
;
1063 if (net_error
!= OK
) {
1064 DNS_HISTOGRAM("AsyncDNS.TransactionFailure", duration
);
1065 OnFailure(net_error
, DnsResponse::DNS_PARSE_OK
);
1069 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess", duration
);
1070 switch (transaction
->GetType()) {
1071 case dns_protocol::kTypeA
:
1072 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess_A", duration
);
1074 case dns_protocol::kTypeAAAA
:
1075 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess_AAAA", duration
);
1079 AddressList addr_list
;
1080 base::TimeDelta ttl
;
1081 DnsResponse::Result result
= response
->ParseToAddressList(&addr_list
, &ttl
);
1082 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ParseToAddressList",
1084 DnsResponse::DNS_PARSE_RESULT_MAX
);
1085 if (result
!= DnsResponse::DNS_PARSE_OK
) {
1086 // Fail even if the other query succeeds.
1087 OnFailure(ERR_DNS_MALFORMED_RESPONSE
, result
);
1091 ++num_completed_transactions_
;
1092 if (num_completed_transactions_
== 1) {
1095 ttl_
= std::min(ttl_
, ttl
);
1098 if (transaction
->GetType() == dns_protocol::kTypeA
) {
1099 DCHECK_EQ(transaction_a_
.get(), transaction
);
1100 // Place IPv4 addresses after IPv6.
1101 addr_list_
.insert(addr_list_
.end(), addr_list
.begin(), addr_list
.end());
1103 DCHECK_EQ(transaction_aaaa_
.get(), transaction
);
1104 // Place IPv6 addresses before IPv4.
1105 addr_list_
.insert(addr_list_
.begin(), addr_list
.begin(), addr_list
.end());
1108 if (needs_two_transactions() && num_completed_transactions_
== 1) {
1109 // No need to repeat the suffix search.
1110 key_
.hostname
= transaction
->GetHostname();
1111 delegate_
->OnFirstDnsTransactionComplete();
1115 if (addr_list_
.empty()) {
1116 // TODO(szym): Don't fallback to ProcTask in this case.
1117 OnFailure(ERR_NAME_NOT_RESOLVED
, DnsResponse::DNS_PARSE_OK
);
1121 // If there are multiple addresses, and at least one is IPv6, need to sort
1122 // them. Note that IPv6 addresses are always put before IPv4 ones, so it's
1123 // sufficient to just check the family of the first address.
1124 if (addr_list_
.size() > 1 &&
1125 addr_list_
[0].GetFamily() == ADDRESS_FAMILY_IPV6
) {
1126 // Sort addresses if needed. Sort could complete synchronously.
1127 client_
->GetAddressSorter()->Sort(
1129 base::Bind(&DnsTask::OnSortComplete
,
1131 base::TimeTicks::Now()));
1133 OnSuccess(addr_list_
);
1137 void OnSortComplete(base::TimeTicks start_time
,
1139 const AddressList
& addr_list
) {
1141 DNS_HISTOGRAM("AsyncDNS.SortFailure",
1142 base::TimeTicks::Now() - start_time
);
1143 OnFailure(ERR_DNS_SORT_ERROR
, DnsResponse::DNS_PARSE_OK
);
1147 DNS_HISTOGRAM("AsyncDNS.SortSuccess",
1148 base::TimeTicks::Now() - start_time
);
1150 // AddressSorter prunes unusable destinations.
1151 if (addr_list
.empty()) {
1152 LOG(WARNING
) << "Address list empty after RFC3484 sort";
1153 OnFailure(ERR_NAME_NOT_RESOLVED
, DnsResponse::DNS_PARSE_OK
);
1157 OnSuccess(addr_list
);
1160 void OnFailure(int net_error
, DnsResponse::Result result
) {
1161 DCHECK_NE(OK
, net_error
);
1163 NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK
,
1164 base::Bind(&NetLogDnsTaskFailedCallback
, net_error
, result
));
1165 delegate_
->OnDnsTaskComplete(task_start_time_
, net_error
, AddressList(),
1169 void OnSuccess(const AddressList
& addr_list
) {
1170 net_log_
.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK
,
1171 addr_list
.CreateNetLogCallback());
1172 delegate_
->OnDnsTaskComplete(task_start_time_
, OK
, addr_list
, ttl_
);
1178 // The listener to the results of this DnsTask.
1179 Delegate
* delegate_
;
1180 const BoundNetLog net_log_
;
1182 scoped_ptr
<DnsTransaction
> transaction_a_
;
1183 scoped_ptr
<DnsTransaction
> transaction_aaaa_
;
1185 unsigned num_completed_transactions_
;
1187 // These are updated as each transaction completes.
1188 base::TimeDelta ttl_
;
1189 // IPv6 addresses must appear first in the list.
1190 AddressList addr_list_
;
1192 base::TimeTicks task_start_time_
;
1194 DISALLOW_COPY_AND_ASSIGN(DnsTask
);
1197 //-----------------------------------------------------------------------------
1199 // Aggregates all Requests for the same Key. Dispatched via PriorityDispatch.
1200 class HostResolverImpl::Job
: public PrioritizedDispatcher::Job
,
1201 public HostResolverImpl::DnsTask::Delegate
{
1203 // Creates new job for |key| where |request_net_log| is bound to the
1204 // request that spawned it.
1205 Job(const base::WeakPtr
<HostResolverImpl
>& resolver
,
1207 RequestPriority priority
,
1208 const BoundNetLog
& source_net_log
)
1209 : resolver_(resolver
),
1211 priority_tracker_(priority
),
1212 had_non_speculative_request_(false),
1213 had_dns_config_(false),
1214 num_occupied_job_slots_(0),
1215 dns_task_error_(OK
),
1216 creation_time_(base::TimeTicks::Now()),
1217 priority_change_time_(creation_time_
),
1218 net_log_(BoundNetLog::Make(source_net_log
.net_log(),
1219 NetLog::SOURCE_HOST_RESOLVER_IMPL_JOB
)) {
1220 source_net_log
.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_CREATE_JOB
);
1222 net_log_
.BeginEvent(
1223 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB
,
1224 base::Bind(&NetLogJobCreationCallback
,
1225 source_net_log
.source(),
1231 // |resolver_| was destroyed with this Job still in flight.
1232 // Clean-up, record in the log, but don't run any callbacks.
1233 if (is_proc_running()) {
1234 proc_task_
->Cancel();
1237 // Clean up now for nice NetLog.
1239 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB
,
1241 } else if (is_queued()) {
1242 // |resolver_| was destroyed without running this Job.
1243 // TODO(szym): is there any benefit in having this distinction?
1244 net_log_
.AddEvent(NetLog::TYPE_CANCELLED
);
1245 net_log_
.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB
);
1247 // else CompleteRequests logged EndEvent.
1249 // Log any remaining Requests as cancelled.
1250 for (RequestsList::const_iterator it
= requests_
.begin();
1251 it
!= requests_
.end(); ++it
) {
1253 if (req
->was_canceled())
1255 DCHECK_EQ(this, req
->job());
1256 LogCancelRequest(req
->source_net_log(), req
->info());
1260 // Add this job to the dispatcher. If "at_head" is true, adds at the front
1262 void Schedule(bool at_head
) {
1263 DCHECK(!is_queued());
1264 PrioritizedDispatcher::Handle handle
;
1266 handle
= resolver_
->dispatcher_
->Add(this, priority());
1268 handle
= resolver_
->dispatcher_
->AddAtHead(this, priority());
1270 // The dispatcher could have started |this| in the above call to Add, which
1271 // could have called Schedule again. In that case |handle| will be null,
1272 // but |handle_| may have been set by the other nested call to Schedule.
1273 if (!handle
.is_null()) {
1274 DCHECK(handle_
.is_null());
1279 void AddRequest(scoped_ptr
<Request
> req
) {
1280 // .localhost queries are redirected to "localhost." to make sure
1281 // that they are never sent out on the network, per RFC 6761.
1282 if (IsLocalhostTLD(req
->info().hostname())) {
1283 DCHECK_EQ(key_
.hostname
, kLocalhost
);
1285 DCHECK_EQ(key_
.hostname
, req
->info().hostname());
1289 priority_tracker_
.Add(req
->priority());
1291 req
->source_net_log().AddEvent(
1292 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_ATTACH
,
1293 net_log_
.source().ToEventParametersCallback());
1296 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_REQUEST_ATTACH
,
1297 base::Bind(&NetLogJobAttachCallback
,
1298 req
->source_net_log().source(),
1301 // TODO(szym): Check if this is still needed.
1302 if (!req
->info().is_speculative()) {
1303 had_non_speculative_request_
= true;
1304 if (proc_task_
.get())
1305 proc_task_
->set_had_non_speculative_request();
1308 requests_
.push_back(req
.release());
1313 // Marks |req| as cancelled. If it was the last active Request, also finishes
1314 // this Job, marking it as cancelled, and deletes it.
1315 void CancelRequest(Request
* req
) {
1316 DCHECK_EQ(key_
.hostname
, req
->info().hostname());
1317 DCHECK(!req
->was_canceled());
1319 // Don't remove it from |requests_| just mark it canceled.
1320 req
->MarkAsCanceled();
1321 LogCancelRequest(req
->source_net_log(), req
->info());
1323 priority_tracker_
.Remove(req
->priority());
1324 net_log_
.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_REQUEST_DETACH
,
1325 base::Bind(&NetLogJobAttachCallback
,
1326 req
->source_net_log().source(),
1329 if (num_active_requests() > 0) {
1332 // If we were called from a Request's callback within CompleteRequests,
1333 // that Request could not have been cancelled, so num_active_requests()
1334 // could not be 0. Therefore, we are not in CompleteRequests().
1335 CompleteRequestsWithError(OK
/* cancelled */);
1339 // Called from AbortAllInProgressJobs. Completes all requests and destroys
1340 // the job. This currently assumes the abort is due to a network change.
1342 DCHECK(is_running());
1343 CompleteRequestsWithError(ERR_NETWORK_CHANGED
);
1346 // If DnsTask present, abort it and fall back to ProcTask.
1347 void AbortDnsTask() {
1350 dns_task_error_
= OK
;
1355 // Called by HostResolverImpl when this job is evicted due to queue overflow.
1356 // Completes all requests and destroys the job.
1358 DCHECK(!is_running());
1359 DCHECK(is_queued());
1362 net_log_
.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_EVICTED
);
1364 // This signals to CompleteRequests that this job never ran.
1365 CompleteRequestsWithError(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE
);
1368 // Attempts to serve the job from HOSTS. Returns true if succeeded and
1369 // this Job was destroyed.
1370 bool ServeFromHosts() {
1371 DCHECK_GT(num_active_requests(), 0u);
1372 AddressList addr_list
;
1373 if (resolver_
->ServeFromHosts(key(),
1374 requests_
.front()->info(),
1376 // This will destroy the Job.
1378 HostCache::Entry(OK
, MakeAddressListForRequest(addr_list
)),
1385 const Key
key() const {
1389 bool is_queued() const {
1390 return !handle_
.is_null();
1393 bool is_running() const {
1394 return is_dns_running() || is_proc_running();
1398 void KillDnsTask() {
1400 ReduceToOneJobSlot();
1405 // Reduce the number of job slots occupied and queued in the dispatcher
1406 // to one. If the second Job slot is queued in the dispatcher, cancels the
1407 // queued job. Otherwise, the second Job has been started by the
1408 // PrioritizedDispatcher, so signals it is complete.
1409 void ReduceToOneJobSlot() {
1410 DCHECK_GE(num_occupied_job_slots_
, 1u);
1412 resolver_
->dispatcher_
->Cancel(handle_
);
1414 } else if (num_occupied_job_slots_
> 1) {
1415 resolver_
->dispatcher_
->OnJobFinished();
1416 --num_occupied_job_slots_
;
1418 DCHECK_EQ(1u, num_occupied_job_slots_
);
1421 void UpdatePriority() {
1423 if (priority() != static_cast<RequestPriority
>(handle_
.priority()))
1424 priority_change_time_
= base::TimeTicks::Now();
1425 handle_
= resolver_
->dispatcher_
->ChangePriority(handle_
, priority());
1429 AddressList
MakeAddressListForRequest(const AddressList
& list
) const {
1430 if (requests_
.empty())
1432 return AddressList::CopyWithPort(list
, requests_
.front()->info().port());
1435 // PriorityDispatch::Job:
1436 void Start() override
{
1437 DCHECK_LE(num_occupied_job_slots_
, 1u);
1440 ++num_occupied_job_slots_
;
1442 if (num_occupied_job_slots_
== 2) {
1443 StartSecondDnsTransaction();
1447 DCHECK(!is_running());
1449 net_log_
.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_STARTED
);
1451 had_dns_config_
= resolver_
->HaveDnsConfig();
1453 base::TimeTicks now
= base::TimeTicks::Now();
1454 base::TimeDelta queue_time
= now
- creation_time_
;
1455 base::TimeDelta queue_time_after_change
= now
- priority_change_time_
;
1457 if (had_dns_config_
) {
1458 DNS_HISTOGRAM_BY_PRIORITY("AsyncDNS.JobQueueTime", priority(),
1460 DNS_HISTOGRAM_BY_PRIORITY("AsyncDNS.JobQueueTimeAfterChange", priority(),
1461 queue_time_after_change
);
1463 DNS_HISTOGRAM_BY_PRIORITY("DNS.JobQueueTime", priority(), queue_time
);
1464 DNS_HISTOGRAM_BY_PRIORITY("DNS.JobQueueTimeAfterChange", priority(),
1465 queue_time_after_change
);
1469 (key_
.host_resolver_flags
& HOST_RESOLVER_SYSTEM_ONLY
) != 0;
1471 // Caution: Job::Start must not complete synchronously.
1472 if (!system_only
&& had_dns_config_
&&
1473 !ResemblesMulticastDNSName(key_
.hostname
)) {
1480 // TODO(szym): Since DnsTransaction does not consume threads, we can increase
1481 // the limits on |dispatcher_|. But in order to keep the number of WorkerPool
1482 // threads low, we will need to use an "inner" PrioritizedDispatcher with
1484 void StartProcTask() {
1485 DCHECK(!is_dns_running());
1486 proc_task_
= new ProcTask(
1488 resolver_
->proc_params_
,
1489 base::Bind(&Job::OnProcTaskComplete
, base::Unretained(this),
1490 base::TimeTicks::Now()),
1493 if (had_non_speculative_request_
)
1494 proc_task_
->set_had_non_speculative_request();
1495 // Start() could be called from within Resolve(), hence it must NOT directly
1496 // call OnProcTaskComplete, for example, on synchronous failure.
1497 proc_task_
->Start();
1500 // Called by ProcTask when it completes.
1501 void OnProcTaskComplete(base::TimeTicks start_time
,
1503 const AddressList
& addr_list
) {
1504 DCHECK(is_proc_running());
1506 if (!resolver_
->resolved_known_ipv6_hostname_
&&
1508 key_
.address_family
== ADDRESS_FAMILY_UNSPECIFIED
) {
1509 if (key_
.hostname
== "www.google.com") {
1510 resolver_
->resolved_known_ipv6_hostname_
= true;
1511 bool got_ipv6_address
= false;
1512 for (size_t i
= 0; i
< addr_list
.size(); ++i
) {
1513 if (addr_list
[i
].GetFamily() == ADDRESS_FAMILY_IPV6
) {
1514 got_ipv6_address
= true;
1518 UMA_HISTOGRAM_BOOLEAN("Net.UnspecResolvedIPv6", got_ipv6_address
);
1522 if (dns_task_error_
!= OK
) {
1523 base::TimeDelta duration
= base::TimeTicks::Now() - start_time
;
1524 if (net_error
== OK
) {
1525 DNS_HISTOGRAM("AsyncDNS.FallbackSuccess", duration
);
1526 if ((dns_task_error_
== ERR_NAME_NOT_RESOLVED
) &&
1527 ResemblesNetBIOSName(key_
.hostname
)) {
1528 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_SUSPECT_NETBIOS
);
1530 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_PROC_SUCCESS
);
1532 UMA_HISTOGRAM_CUSTOM_ENUMERATION("AsyncDNS.ResolveError",
1533 std::abs(dns_task_error_
),
1534 GetAllErrorCodesForUma());
1535 resolver_
->OnDnsTaskResolve(dns_task_error_
);
1537 DNS_HISTOGRAM("AsyncDNS.FallbackFail", duration
);
1538 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL
);
1542 base::TimeDelta ttl
=
1543 base::TimeDelta::FromSeconds(kNegativeCacheEntryTTLSeconds
);
1544 if (net_error
== OK
)
1545 ttl
= base::TimeDelta::FromSeconds(kCacheEntryTTLSeconds
);
1547 // Don't store the |ttl| in cache since it's not obtained from the server.
1549 HostCache::Entry(net_error
, MakeAddressListForRequest(addr_list
)),
1553 void StartDnsTask() {
1554 DCHECK(resolver_
->HaveDnsConfig());
1555 dns_task_
.reset(new DnsTask(resolver_
->dns_client_
.get(), key_
, this,
1558 dns_task_
->StartFirstTransaction();
1559 // Schedule a second transaction, if needed.
1560 if (dns_task_
->needs_two_transactions())
1564 void StartSecondDnsTransaction() {
1565 DCHECK(dns_task_
->needs_two_transactions());
1566 dns_task_
->StartSecondTransaction();
1569 // Called if DnsTask fails. It is posted from StartDnsTask, so Job may be
1570 // deleted before this callback. In this case dns_task is deleted as well,
1571 // so we use it as indicator whether Job is still valid.
1572 void OnDnsTaskFailure(const base::WeakPtr
<DnsTask
>& dns_task
,
1573 base::TimeDelta duration
,
1575 DNS_HISTOGRAM("AsyncDNS.ResolveFail", duration
);
1577 if (dns_task
== NULL
)
1580 dns_task_error_
= net_error
;
1582 // TODO(szym): Run ServeFromHosts now if nsswitch.conf says so.
1583 // http://crbug.com/117655
1585 // TODO(szym): Some net errors indicate lack of connectivity. Starting
1586 // ProcTask in that case is a waste of time.
1587 if (resolver_
->fallback_to_proctask_
) {
1591 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL
);
1592 CompleteRequestsWithError(net_error
);
1597 // HostResolverImpl::DnsTask::Delegate implementation:
1599 void OnDnsTaskComplete(base::TimeTicks start_time
,
1601 const AddressList
& addr_list
,
1602 base::TimeDelta ttl
) override
{
1603 DCHECK(is_dns_running());
1605 base::TimeDelta duration
= base::TimeTicks::Now() - start_time
;
1606 if (net_error
!= OK
) {
1607 OnDnsTaskFailure(dns_task_
->AsWeakPtr(), duration
, net_error
);
1610 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess", duration
);
1611 // Log DNS lookups based on |address_family|.
1612 switch(key_
.address_family
) {
1613 case ADDRESS_FAMILY_IPV4
:
1614 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_IPV4", duration
);
1616 case ADDRESS_FAMILY_IPV6
:
1617 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_IPV6", duration
);
1619 case ADDRESS_FAMILY_UNSPECIFIED
:
1620 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_UNSPEC", duration
);
1624 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_DNS_SUCCESS
);
1627 resolver_
->OnDnsTaskResolve(OK
);
1629 base::TimeDelta bounded_ttl
=
1630 std::max(ttl
, base::TimeDelta::FromSeconds(kMinimumTTLSeconds
));
1633 HostCache::Entry(net_error
, MakeAddressListForRequest(addr_list
), ttl
),
1637 void OnFirstDnsTransactionComplete() override
{
1638 DCHECK(dns_task_
->needs_two_transactions());
1639 DCHECK_EQ(dns_task_
->needs_another_transaction(), is_queued());
1640 // No longer need to occupy two dispatcher slots.
1641 ReduceToOneJobSlot();
1643 // We already have a job slot at the dispatcher, so if the second
1644 // transaction hasn't started, reuse it now instead of waiting in the queue
1645 // for the second slot.
1646 if (dns_task_
->needs_another_transaction())
1647 dns_task_
->StartSecondTransaction();
1650 // Performs Job's last rites. Completes all Requests. Deletes this.
1651 void CompleteRequests(const HostCache::Entry
& entry
,
1652 base::TimeDelta ttl
) {
1653 CHECK(resolver_
.get());
1655 // This job must be removed from resolver's |jobs_| now to make room for a
1656 // new job with the same key in case one of the OnComplete callbacks decides
1657 // to spawn one. Consequently, the job deletes itself when CompleteRequests
1659 scoped_ptr
<Job
> self_deleter(this);
1661 resolver_
->RemoveJob(this);
1664 if (is_proc_running()) {
1665 DCHECK(!is_queued());
1666 proc_task_
->Cancel();
1671 // Signal dispatcher that a slot has opened.
1672 resolver_
->dispatcher_
->OnJobFinished();
1673 } else if (is_queued()) {
1674 resolver_
->dispatcher_
->Cancel(handle_
);
1678 if (num_active_requests() == 0) {
1679 net_log_
.AddEvent(NetLog::TYPE_CANCELLED
);
1680 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB
,
1685 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB
,
1688 DCHECK(!requests_
.empty());
1690 if (entry
.error
== OK
) {
1691 // Record this histogram here, when we know the system has a valid DNS
1693 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.HaveDnsConfig",
1694 resolver_
->received_dns_config_
);
1697 bool did_complete
= (entry
.error
!= ERR_NETWORK_CHANGED
) &&
1698 (entry
.error
!= ERR_HOST_RESOLVER_QUEUE_TOO_LARGE
);
1700 resolver_
->CacheResult(key_
, entry
, ttl
);
1702 // Complete all of the requests that were attached to the job.
1703 for (RequestsList::const_iterator it
= requests_
.begin();
1704 it
!= requests_
.end(); ++it
) {
1707 if (req
->was_canceled())
1710 DCHECK_EQ(this, req
->job());
1711 // Update the net log and notify registered observers.
1712 LogFinishRequest(req
->source_net_log(), req
->info(), entry
.error
);
1714 // Record effective total time from creation to completion.
1715 RecordTotalTime(had_dns_config_
, req
->info().is_speculative(),
1716 base::TimeTicks::Now() - req
->request_time());
1718 req
->OnComplete(entry
.error
, entry
.addrlist
);
1720 // Check if the resolver was destroyed as a result of running the
1721 // callback. If it was, we could continue, but we choose to bail.
1722 if (!resolver_
.get())
1727 // Convenience wrapper for CompleteRequests in case of failure.
1728 void CompleteRequestsWithError(int net_error
) {
1729 CompleteRequests(HostCache::Entry(net_error
, AddressList()),
1733 RequestPriority
priority() const {
1734 return priority_tracker_
.highest_priority();
1737 // Number of non-canceled requests in |requests_|.
1738 size_t num_active_requests() const {
1739 return priority_tracker_
.total_count();
1742 bool is_dns_running() const {
1743 return dns_task_
.get() != NULL
;
1746 bool is_proc_running() const {
1747 return proc_task_
.get() != NULL
;
1750 base::WeakPtr
<HostResolverImpl
> resolver_
;
1754 // Tracks the highest priority across |requests_|.
1755 PriorityTracker priority_tracker_
;
1757 bool had_non_speculative_request_
;
1759 // Distinguishes measurements taken while DnsClient was fully configured.
1760 bool had_dns_config_
;
1762 // Number of slots occupied by this Job in resolver's PrioritizedDispatcher.
1763 unsigned num_occupied_job_slots_
;
1765 // Result of DnsTask.
1766 int dns_task_error_
;
1768 const base::TimeTicks creation_time_
;
1769 base::TimeTicks priority_change_time_
;
1771 BoundNetLog net_log_
;
1773 // Resolves the host using a HostResolverProc.
1774 scoped_refptr
<ProcTask
> proc_task_
;
1776 // Resolves the host using a DnsTransaction.
1777 scoped_ptr
<DnsTask
> dns_task_
;
1779 // All Requests waiting for the result of this Job. Some can be canceled.
1780 RequestsList requests_
;
1782 // A handle used in |HostResolverImpl::dispatcher_|.
1783 PrioritizedDispatcher::Handle handle_
;
1786 //-----------------------------------------------------------------------------
1788 HostResolverImpl::ProcTaskParams::ProcTaskParams(
1789 HostResolverProc
* resolver_proc
,
1790 size_t max_retry_attempts
)
1791 : resolver_proc(resolver_proc
),
1792 max_retry_attempts(max_retry_attempts
),
1793 unresponsive_delay(base::TimeDelta::FromMilliseconds(6000)),
1795 // Maximum of 4 retry attempts for host resolution.
1796 static const size_t kDefaultMaxRetryAttempts
= 4u;
1797 if (max_retry_attempts
== HostResolver::kDefaultRetryAttempts
)
1798 max_retry_attempts
= kDefaultMaxRetryAttempts
;
1801 HostResolverImpl::ProcTaskParams::~ProcTaskParams() {}
1803 HostResolverImpl::HostResolverImpl(const Options
& options
, NetLog
* net_log
)
1804 : max_queued_jobs_(0),
1805 proc_params_(NULL
, options
.max_retry_attempts
),
1807 default_address_family_(ADDRESS_FAMILY_UNSPECIFIED
),
1808 received_dns_config_(false),
1809 num_dns_failures_(0),
1810 probe_ipv6_support_(true),
1811 use_local_ipv6_(false),
1812 resolved_known_ipv6_hostname_(false),
1813 additional_resolver_flags_(0),
1814 fallback_to_proctask_(true),
1815 weak_ptr_factory_(this),
1816 probe_weak_ptr_factory_(this) {
1817 if (options
.enable_caching
)
1818 cache_
= HostCache::CreateDefaultCache();
1820 PrioritizedDispatcher::Limits job_limits
= options
.GetDispatcherLimits();
1821 dispatcher_
.reset(new PrioritizedDispatcher(job_limits
));
1822 max_queued_jobs_
= job_limits
.total_jobs
* 100u;
1824 DCHECK_GE(dispatcher_
->num_priorities(), static_cast<size_t>(NUM_PRIORITIES
));
1827 EnsureWinsockInit();
1829 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
1830 new LoopbackProbeJob(weak_ptr_factory_
.GetWeakPtr());
1832 NetworkChangeNotifier::AddIPAddressObserver(this);
1833 NetworkChangeNotifier::AddDNSObserver(this);
1834 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD) && \
1835 !defined(OS_ANDROID)
1836 EnsureDnsReloaderInit();
1840 DnsConfig dns_config
;
1841 NetworkChangeNotifier::GetDnsConfig(&dns_config
);
1842 received_dns_config_
= dns_config
.IsValid();
1843 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
1844 use_local_ipv6_
= !dns_config
.IsValid() || dns_config
.use_local_ipv6
;
1847 fallback_to_proctask_
= !ConfigureAsyncDnsNoFallbackFieldTrial();
1850 HostResolverImpl::~HostResolverImpl() {
1851 // Prevent the dispatcher from starting new jobs.
1852 dispatcher_
->SetLimitsToZero();
1853 // It's now safe for Jobs to call KillDsnTask on destruction, because
1854 // OnJobComplete will not start any new jobs.
1855 STLDeleteValues(&jobs_
);
1857 NetworkChangeNotifier::RemoveIPAddressObserver(this);
1858 NetworkChangeNotifier::RemoveDNSObserver(this);
1861 void HostResolverImpl::SetMaxQueuedJobs(size_t value
) {
1862 DCHECK_EQ(0u, dispatcher_
->num_queued_jobs());
1863 DCHECK_GT(value
, 0u);
1864 max_queued_jobs_
= value
;
1867 int HostResolverImpl::Resolve(const RequestInfo
& info
,
1868 RequestPriority priority
,
1869 AddressList
* addresses
,
1870 const CompletionCallback
& callback
,
1871 RequestHandle
* out_req
,
1872 const BoundNetLog
& source_net_log
) {
1874 DCHECK(CalledOnValidThread());
1875 DCHECK_EQ(false, callback
.is_null());
1877 // Check that the caller supplied a valid hostname to resolve.
1878 std::string labeled_hostname
;
1879 if (!DNSDomainFromDot(info
.hostname(), &labeled_hostname
))
1880 return ERR_NAME_NOT_RESOLVED
;
1882 LogStartRequest(source_net_log
, info
);
1884 // Build a key that identifies the request in the cache and in the
1885 // outstanding jobs map.
1886 Key key
= GetEffectiveKeyForRequest(info
, source_net_log
);
1888 int rv
= ResolveHelper(key
, info
, addresses
, source_net_log
);
1889 if (rv
!= ERR_DNS_CACHE_MISS
) {
1890 LogFinishRequest(source_net_log
, info
, rv
);
1891 RecordTotalTime(HaveDnsConfig(), info
.is_speculative(), base::TimeDelta());
1895 // Next we need to attach our request to a "job". This job is responsible for
1896 // calling "getaddrinfo(hostname)" on a worker thread.
1898 JobMap::iterator jobit
= jobs_
.find(key
);
1900 if (jobit
== jobs_
.end()) {
1902 new Job(weak_ptr_factory_
.GetWeakPtr(), key
, priority
, source_net_log
);
1903 job
->Schedule(false);
1905 // Check for queue overflow.
1906 if (dispatcher_
->num_queued_jobs() > max_queued_jobs_
) {
1907 Job
* evicted
= static_cast<Job
*>(dispatcher_
->EvictOldestLowest());
1909 evicted
->OnEvicted(); // Deletes |evicted|.
1910 if (evicted
== job
) {
1911 rv
= ERR_HOST_RESOLVER_QUEUE_TOO_LARGE
;
1912 LogFinishRequest(source_net_log
, info
, rv
);
1916 jobs_
.insert(jobit
, std::make_pair(key
, job
));
1918 job
= jobit
->second
;
1921 // Can't complete synchronously. Create and attach request.
1922 scoped_ptr
<Request
> req(new Request(
1923 source_net_log
, info
, priority
, callback
, addresses
));
1925 *out_req
= reinterpret_cast<RequestHandle
>(req
.get());
1927 job
->AddRequest(req
.Pass());
1928 // Completion happens during Job::CompleteRequests().
1929 return ERR_IO_PENDING
;
1932 int HostResolverImpl::ResolveHelper(const Key
& key
,
1933 const RequestInfo
& info
,
1934 AddressList
* addresses
,
1935 const BoundNetLog
& source_net_log
) {
1936 // The result of |getaddrinfo| for empty hosts is inconsistent across systems.
1937 // On Windows it gives the default interface's address, whereas on Linux it
1938 // gives an error. We will make it fail on all platforms for consistency.
1939 if (info
.hostname().empty() || info
.hostname().size() > kMaxHostLength
)
1940 return ERR_NAME_NOT_RESOLVED
;
1942 int net_error
= ERR_UNEXPECTED
;
1943 if (ResolveAsIP(key
, info
, &net_error
, addresses
))
1945 if (ServeFromCache(key
, info
, &net_error
, addresses
)) {
1946 source_net_log
.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_CACHE_HIT
);
1949 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
1950 // http://crbug.com/117655
1951 if (ServeFromHosts(key
, info
, addresses
)) {
1952 source_net_log
.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_HOSTS_HIT
);
1955 return ERR_DNS_CACHE_MISS
;
1958 int HostResolverImpl::ResolveFromCache(const RequestInfo
& info
,
1959 AddressList
* addresses
,
1960 const BoundNetLog
& source_net_log
) {
1961 DCHECK(CalledOnValidThread());
1964 // Update the net log and notify registered observers.
1965 LogStartRequest(source_net_log
, info
);
1967 Key key
= GetEffectiveKeyForRequest(info
, source_net_log
);
1969 int rv
= ResolveHelper(key
, info
, addresses
, source_net_log
);
1970 LogFinishRequest(source_net_log
, info
, rv
);
1974 void HostResolverImpl::CancelRequest(RequestHandle req_handle
) {
1975 DCHECK(CalledOnValidThread());
1976 Request
* req
= reinterpret_cast<Request
*>(req_handle
);
1978 Job
* job
= req
->job();
1980 job
->CancelRequest(req
);
1983 void HostResolverImpl::SetDefaultAddressFamily(AddressFamily address_family
) {
1984 DCHECK(CalledOnValidThread());
1985 default_address_family_
= address_family
;
1986 probe_ipv6_support_
= false;
1989 AddressFamily
HostResolverImpl::GetDefaultAddressFamily() const {
1990 return default_address_family_
;
1993 void HostResolverImpl::SetDnsClientEnabled(bool enabled
) {
1994 DCHECK(CalledOnValidThread());
1995 #if defined(ENABLE_BUILT_IN_DNS)
1996 if (enabled
&& !dns_client_
) {
1997 SetDnsClient(DnsClient::CreateClient(net_log_
));
1998 } else if (!enabled
&& dns_client_
) {
1999 SetDnsClient(scoped_ptr
<DnsClient
>());
2004 HostCache
* HostResolverImpl::GetHostCache() {
2005 return cache_
.get();
2008 base::Value
* HostResolverImpl::GetDnsConfigAsValue() const {
2009 // Check if async DNS is disabled.
2010 if (!dns_client_
.get())
2013 // Check if async DNS is enabled, but we currently have no configuration
2015 const DnsConfig
* dns_config
= dns_client_
->GetConfig();
2016 if (dns_config
== NULL
)
2017 return new base::DictionaryValue();
2019 return dns_config
->ToValue();
2022 bool HostResolverImpl::ResolveAsIP(const Key
& key
,
2023 const RequestInfo
& info
,
2025 AddressList
* addresses
) {
2028 IPAddressNumber ip_number
;
2029 if (!ParseIPLiteralToNumber(key
.hostname
, &ip_number
))
2032 DCHECK_EQ(key
.host_resolver_flags
&
2033 ~(HOST_RESOLVER_CANONNAME
| HOST_RESOLVER_LOOPBACK_ONLY
|
2034 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6
),
2035 0) << " Unhandled flag";
2038 AddressFamily family
= GetAddressFamily(ip_number
);
2039 if (family
== ADDRESS_FAMILY_IPV6
&&
2040 !probe_ipv6_support_
&&
2041 default_address_family_
== ADDRESS_FAMILY_IPV4
) {
2042 // Don't return IPv6 addresses if default address family is set to IPv4,
2043 // and probes are disabled.
2044 *net_error
= ERR_NAME_NOT_RESOLVED
;
2045 } else if (key
.address_family
!= ADDRESS_FAMILY_UNSPECIFIED
&&
2046 key
.address_family
!= family
) {
2047 // Don't return IPv6 addresses for IPv4 queries, and vice versa.
2048 *net_error
= ERR_NAME_NOT_RESOLVED
;
2050 *addresses
= AddressList::CreateFromIPAddress(ip_number
, info
.port());
2051 if (key
.host_resolver_flags
& HOST_RESOLVER_CANONNAME
)
2052 addresses
->SetDefaultCanonicalName();
2057 bool HostResolverImpl::ServeFromCache(const Key
& key
,
2058 const RequestInfo
& info
,
2060 AddressList
* addresses
) {
2063 if (!info
.allow_cached_response() || !cache_
.get())
2066 const HostCache::Entry
* cache_entry
= cache_
->Lookup(
2067 key
, base::TimeTicks::Now());
2071 *net_error
= cache_entry
->error
;
2072 if (*net_error
== OK
) {
2073 if (cache_entry
->has_ttl())
2074 RecordTTL(cache_entry
->ttl
);
2075 *addresses
= EnsurePortOnAddressList(cache_entry
->addrlist
, info
.port());
2080 bool HostResolverImpl::ServeFromHosts(const Key
& key
,
2081 const RequestInfo
& info
,
2082 AddressList
* addresses
) {
2084 if (!HaveDnsConfig())
2088 // HOSTS lookups are case-insensitive.
2089 std::string hostname
= base::StringToLowerASCII(key
.hostname
);
2091 const DnsHosts
& hosts
= dns_client_
->GetConfig()->hosts
;
2093 // If |address_family| is ADDRESS_FAMILY_UNSPECIFIED other implementations
2094 // (glibc and c-ares) return the first matching line. We have more
2095 // flexibility, but lose implicit ordering.
2096 // We prefer IPv6 because "happy eyeballs" will fall back to IPv4 if
2098 if (key
.address_family
== ADDRESS_FAMILY_IPV6
||
2099 key
.address_family
== ADDRESS_FAMILY_UNSPECIFIED
) {
2100 DnsHosts::const_iterator it
= hosts
.find(
2101 DnsHostsKey(hostname
, ADDRESS_FAMILY_IPV6
));
2102 if (it
!= hosts
.end())
2103 addresses
->push_back(IPEndPoint(it
->second
, info
.port()));
2106 if (key
.address_family
== ADDRESS_FAMILY_IPV4
||
2107 key
.address_family
== ADDRESS_FAMILY_UNSPECIFIED
) {
2108 DnsHosts::const_iterator it
= hosts
.find(
2109 DnsHostsKey(hostname
, ADDRESS_FAMILY_IPV4
));
2110 if (it
!= hosts
.end())
2111 addresses
->push_back(IPEndPoint(it
->second
, info
.port()));
2114 // If got only loopback addresses and the family was restricted, resolve
2115 // again, without restrictions. See SystemHostResolverCall for rationale.
2116 if ((key
.host_resolver_flags
&
2117 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6
) &&
2118 IsAllIPv4Loopback(*addresses
)) {
2120 new_key
.address_family
= ADDRESS_FAMILY_UNSPECIFIED
;
2121 new_key
.host_resolver_flags
&=
2122 ~HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6
;
2123 return ServeFromHosts(new_key
, info
, addresses
);
2125 return !addresses
->empty();
2128 void HostResolverImpl::CacheResult(const Key
& key
,
2129 const HostCache::Entry
& entry
,
2130 base::TimeDelta ttl
) {
2132 cache_
->Set(key
, entry
, base::TimeTicks::Now(), ttl
);
2135 void HostResolverImpl::RemoveJob(Job
* job
) {
2137 JobMap::iterator it
= jobs_
.find(job
->key());
2138 if (it
!= jobs_
.end() && it
->second
== job
)
2142 void HostResolverImpl::SetHaveOnlyLoopbackAddresses(bool result
) {
2144 additional_resolver_flags_
|= HOST_RESOLVER_LOOPBACK_ONLY
;
2146 additional_resolver_flags_
&= ~HOST_RESOLVER_LOOPBACK_ONLY
;
2150 HostResolverImpl::Key
HostResolverImpl::GetEffectiveKeyForRequest(
2151 const RequestInfo
& info
, const BoundNetLog
& net_log
) const {
2152 HostResolverFlags effective_flags
=
2153 info
.host_resolver_flags() | additional_resolver_flags_
;
2154 AddressFamily effective_address_family
= info
.address_family();
2156 if (info
.address_family() == ADDRESS_FAMILY_UNSPECIFIED
) {
2157 unsigned char ip_number
[4];
2158 url::Component
host_comp(0, info
.hostname().size());
2160 if (probe_ipv6_support_
&& !use_local_ipv6_
&&
2161 // Don't bother IPv6 probing when resolving IPv4 literals.
2162 url::IPv4AddressToNumber(info
.hostname().c_str(), host_comp
, ip_number
,
2163 &num_components
) != url::CanonHostInfo::IPV4
) {
2164 // Google DNS address.
2165 const uint8 kIPv6Address
[] =
2166 { 0x20, 0x01, 0x48, 0x60, 0x48, 0x60, 0x00, 0x00,
2167 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x88 };
2168 IPAddressNumber
address(kIPv6Address
,
2169 kIPv6Address
+ arraysize(kIPv6Address
));
2170 BoundNetLog probe_net_log
= BoundNetLog::Make(
2171 net_log
.net_log(), NetLog::SOURCE_IPV6_REACHABILITY_CHECK
);
2172 probe_net_log
.BeginEvent(NetLog::TYPE_IPV6_REACHABILITY_CHECK
,
2173 net_log
.source().ToEventParametersCallback());
2174 bool rv6
= IsGloballyReachable(address
, probe_net_log
);
2175 probe_net_log
.EndEvent(NetLog::TYPE_IPV6_REACHABILITY_CHECK
);
2177 net_log
.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_IPV6_SUPPORTED
);
2179 effective_address_family
= ADDRESS_FAMILY_IPV4
;
2180 effective_flags
|= HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6
;
2183 effective_address_family
= default_address_family_
;
2187 std::string hostname
= info
.hostname();
2188 // Redirect .localhost queries to "localhost." to make sure that they
2189 // are never sent out on the network, per RFC 6761.
2190 if (IsLocalhostTLD(info
.hostname()))
2191 hostname
= kLocalhost
;
2193 return Key(hostname
, effective_address_family
, effective_flags
);
2196 void HostResolverImpl::AbortAllInProgressJobs() {
2197 // In Abort, a Request callback could spawn new Jobs with matching keys, so
2198 // first collect and remove all running jobs from |jobs_|.
2199 ScopedVector
<Job
> jobs_to_abort
;
2200 for (JobMap::iterator it
= jobs_
.begin(); it
!= jobs_
.end(); ) {
2201 Job
* job
= it
->second
;
2202 if (job
->is_running()) {
2203 jobs_to_abort
.push_back(job
);
2206 DCHECK(job
->is_queued());
2211 // Pause the dispatcher so it won't start any new dispatcher jobs while
2212 // aborting the old ones. This is needed so that it won't start the second
2213 // DnsTransaction for a job in |jobs_to_abort| if the DnsConfig just became
2215 PrioritizedDispatcher::Limits limits
= dispatcher_
->GetLimits();
2216 dispatcher_
->SetLimits(
2217 PrioritizedDispatcher::Limits(limits
.reserved_slots
.size(), 0));
2219 // Life check to bail once |this| is deleted.
2220 base::WeakPtr
<HostResolverImpl
> self
= weak_ptr_factory_
.GetWeakPtr();
2223 for (size_t i
= 0; self
.get() && i
< jobs_to_abort
.size(); ++i
) {
2224 jobs_to_abort
[i
]->Abort();
2225 jobs_to_abort
[i
] = NULL
;
2229 dispatcher_
->SetLimits(limits
);
2232 void HostResolverImpl::AbortDnsTasks() {
2233 // Pause the dispatcher so it won't start any new dispatcher jobs while
2234 // aborting the old ones. This is needed so that it won't start the second
2235 // DnsTransaction for a job if the DnsConfig just changed.
2236 PrioritizedDispatcher::Limits limits
= dispatcher_
->GetLimits();
2237 dispatcher_
->SetLimits(
2238 PrioritizedDispatcher::Limits(limits
.reserved_slots
.size(), 0));
2240 for (JobMap::iterator it
= jobs_
.begin(); it
!= jobs_
.end(); ++it
)
2241 it
->second
->AbortDnsTask();
2242 dispatcher_
->SetLimits(limits
);
2245 void HostResolverImpl::TryServingAllJobsFromHosts() {
2246 if (!HaveDnsConfig())
2249 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2250 // http://crbug.com/117655
2252 // Life check to bail once |this| is deleted.
2253 base::WeakPtr
<HostResolverImpl
> self
= weak_ptr_factory_
.GetWeakPtr();
2255 for (JobMap::iterator it
= jobs_
.begin(); self
.get() && it
!= jobs_
.end();) {
2256 Job
* job
= it
->second
;
2258 // This could remove |job| from |jobs_|, but iterator will remain valid.
2259 job
->ServeFromHosts();
2263 void HostResolverImpl::OnIPAddressChanged() {
2264 resolved_known_ipv6_hostname_
= false;
2265 // Abandon all ProbeJobs.
2266 probe_weak_ptr_factory_
.InvalidateWeakPtrs();
2269 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
2270 new LoopbackProbeJob(probe_weak_ptr_factory_
.GetWeakPtr());
2272 AbortAllInProgressJobs();
2273 // |this| may be deleted inside AbortAllInProgressJobs().
2276 void HostResolverImpl::OnDNSChanged() {
2277 DnsConfig dns_config
;
2278 NetworkChangeNotifier::GetDnsConfig(&dns_config
);
2281 net_log_
->AddGlobalEntry(
2282 NetLog::TYPE_DNS_CONFIG_CHANGED
,
2283 base::Bind(&NetLogDnsConfigCallback
, &dns_config
));
2286 // TODO(szym): Remove once http://crbug.com/137914 is resolved.
2287 received_dns_config_
= dns_config
.IsValid();
2288 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
2289 use_local_ipv6_
= !dns_config
.IsValid() || dns_config
.use_local_ipv6
;
2291 num_dns_failures_
= 0;
2293 // We want a new DnsSession in place, before we Abort running Jobs, so that
2294 // the newly started jobs use the new config.
2295 if (dns_client_
.get()) {
2296 dns_client_
->SetConfig(dns_config
);
2297 if (dns_client_
->GetConfig())
2298 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
2301 // If the DNS server has changed, existing cached info could be wrong so we
2302 // have to drop our internal cache :( Note that OS level DNS caches, such
2303 // as NSCD's cache should be dropped automatically by the OS when
2304 // resolv.conf changes so we don't need to do anything to clear that cache.
2308 // Life check to bail once |this| is deleted.
2309 base::WeakPtr
<HostResolverImpl
> self
= weak_ptr_factory_
.GetWeakPtr();
2311 // Existing jobs will have been sent to the original server so they need to
2313 AbortAllInProgressJobs();
2315 // |this| may be deleted inside AbortAllInProgressJobs().
2317 TryServingAllJobsFromHosts();
2320 bool HostResolverImpl::HaveDnsConfig() const {
2321 // Use DnsClient only if it's fully configured and there is no override by
2322 // ScopedDefaultHostResolverProc.
2323 // The alternative is to use NetworkChangeNotifier to override DnsConfig,
2324 // but that would introduce construction order requirements for NCN and SDHRP.
2325 return (dns_client_
.get() != NULL
) && (dns_client_
->GetConfig() != NULL
) &&
2326 !(proc_params_
.resolver_proc
.get() == NULL
&&
2327 HostResolverProc::GetDefault() != NULL
);
2330 void HostResolverImpl::OnDnsTaskResolve(int net_error
) {
2331 DCHECK(dns_client_
);
2332 if (net_error
== OK
) {
2333 num_dns_failures_
= 0;
2336 ++num_dns_failures_
;
2337 if (num_dns_failures_
< kMaximumDnsFailures
)
2340 // Disable DnsClient until the next DNS change. Must be done before aborting
2341 // DnsTasks, since doing so may start new jobs.
2342 dns_client_
->SetConfig(DnsConfig());
2344 // Switch jobs with active DnsTasks over to using ProcTasks.
2347 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", false);
2348 UMA_HISTOGRAM_CUSTOM_ENUMERATION("AsyncDNS.DnsClientDisabledReason",
2349 std::abs(net_error
),
2350 GetAllErrorCodesForUma());
2353 void HostResolverImpl::SetDnsClient(scoped_ptr
<DnsClient
> dns_client
) {
2354 // DnsClient and config must be updated before aborting DnsTasks, since doing
2355 // so may start new jobs.
2356 dns_client_
= dns_client
.Pass();
2357 if (dns_client_
&& !dns_client_
->GetConfig() &&
2358 num_dns_failures_
< kMaximumDnsFailures
) {
2359 DnsConfig dns_config
;
2360 NetworkChangeNotifier::GetDnsConfig(&dns_config
);
2361 dns_client_
->SetConfig(dns_config
);
2362 num_dns_failures_
= 0;
2363 if (dns_client_
->GetConfig())
2364 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);