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(
301 uint32 attempt_number
,
304 NetLogCaptureMode
/* capture_mode */) {
305 base::DictionaryValue
* dict
= new base::DictionaryValue();
307 dict
->SetInteger("attempt_number", attempt_number
);
309 dict
->SetInteger("net_error", net_error
);
312 dict
->SetInteger("os_error", os_error
);
313 #if defined(OS_POSIX)
314 dict
->SetString("os_error_string", gai_strerror(os_error
));
315 #elif defined(OS_WIN)
316 // Map the error code to a human-readable string.
317 LPWSTR error_string
= NULL
;
318 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
319 0, // Use the internal message table.
321 0, // Use default language.
322 (LPWSTR
)&error_string
,
324 0); // Arguments (unused).
325 dict
->SetString("os_error_string", base::WideToUTF8(error_string
));
326 LocalFree(error_string
);
333 // Creates NetLog parameters when the DnsTask failed.
334 base::Value
* NetLogDnsTaskFailedCallback(int net_error
,
336 NetLogCaptureMode
/* capture_mode */) {
337 base::DictionaryValue
* dict
= new base::DictionaryValue();
338 dict
->SetInteger("net_error", net_error
);
340 dict
->SetInteger("dns_error", dns_error
);
344 // Creates NetLog parameters containing the information in a RequestInfo object,
345 // along with the associated NetLog::Source.
346 base::Value
* NetLogRequestInfoCallback(const HostResolver::RequestInfo
* info
,
347 NetLogCaptureMode
/* capture_mode */) {
348 base::DictionaryValue
* dict
= new base::DictionaryValue();
350 dict
->SetString("host", info
->host_port_pair().ToString());
351 dict
->SetInteger("address_family",
352 static_cast<int>(info
->address_family()));
353 dict
->SetBoolean("allow_cached_response", info
->allow_cached_response());
354 dict
->SetBoolean("is_speculative", info
->is_speculative());
358 // Creates NetLog parameters for the creation of a HostResolverImpl::Job.
359 base::Value
* NetLogJobCreationCallback(const NetLog::Source
& source
,
360 const std::string
* host
,
361 NetLogCaptureMode
/* capture_mode */) {
362 base::DictionaryValue
* dict
= new base::DictionaryValue();
363 source
.AddToEventParameters(dict
);
364 dict
->SetString("host", *host
);
368 // Creates NetLog parameters for HOST_RESOLVER_IMPL_JOB_ATTACH/DETACH events.
369 base::Value
* NetLogJobAttachCallback(const NetLog::Source
& source
,
370 RequestPriority priority
,
371 NetLogCaptureMode
/* capture_mode */) {
372 base::DictionaryValue
* dict
= new base::DictionaryValue();
373 source
.AddToEventParameters(dict
);
374 dict
->SetString("priority", RequestPriorityToString(priority
));
378 // Creates NetLog parameters for the DNS_CONFIG_CHANGED event.
379 base::Value
* NetLogDnsConfigCallback(const DnsConfig
* config
,
380 NetLogCaptureMode
/* capture_mode */) {
381 return config
->ToValue();
384 // The logging routines are defined here because some requests are resolved
385 // without a Request object.
387 // Logs when a request has just been started.
388 void LogStartRequest(const BoundNetLog
& source_net_log
,
389 const HostResolver::RequestInfo
& info
) {
390 source_net_log
.BeginEvent(
391 NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST
,
392 base::Bind(&NetLogRequestInfoCallback
, &info
));
395 // Logs when a request has just completed (before its callback is run).
396 void LogFinishRequest(const BoundNetLog
& source_net_log
,
397 const HostResolver::RequestInfo
& info
,
399 source_net_log
.EndEventWithNetErrorCode(
400 NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST
, net_error
);
403 // Logs when a request has been cancelled.
404 void LogCancelRequest(const BoundNetLog
& source_net_log
,
405 const HostResolverImpl::RequestInfo
& info
) {
406 source_net_log
.AddEvent(NetLog::TYPE_CANCELLED
);
407 source_net_log
.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST
);
410 //-----------------------------------------------------------------------------
412 // Keeps track of the highest priority.
413 class PriorityTracker
{
415 explicit PriorityTracker(RequestPriority initial_priority
)
416 : highest_priority_(initial_priority
), total_count_(0) {
417 memset(counts_
, 0, sizeof(counts_
));
420 RequestPriority
highest_priority() const {
421 return highest_priority_
;
424 size_t total_count() const {
428 void Add(RequestPriority req_priority
) {
430 ++counts_
[req_priority
];
431 if (highest_priority_
< req_priority
)
432 highest_priority_
= req_priority
;
435 void Remove(RequestPriority req_priority
) {
436 DCHECK_GT(total_count_
, 0u);
437 DCHECK_GT(counts_
[req_priority
], 0u);
439 --counts_
[req_priority
];
441 for (i
= highest_priority_
; i
> MINIMUM_PRIORITY
&& !counts_
[i
]; --i
);
442 highest_priority_
= static_cast<RequestPriority
>(i
);
444 // In absence of requests, default to MINIMUM_PRIORITY.
445 if (total_count_
== 0)
446 DCHECK_EQ(MINIMUM_PRIORITY
, highest_priority_
);
450 RequestPriority highest_priority_
;
452 size_t counts_
[NUM_PRIORITIES
];
457 //-----------------------------------------------------------------------------
459 const unsigned HostResolverImpl::kMaximumDnsFailures
= 16;
461 // Holds the data for a request that could not be completed synchronously.
462 // It is owned by a Job. Canceled Requests are only marked as canceled rather
463 // than removed from the Job's |requests_| list.
464 class HostResolverImpl::Request
{
466 Request(const BoundNetLog
& source_net_log
,
467 const RequestInfo
& info
,
468 RequestPriority priority
,
469 const CompletionCallback
& callback
,
470 AddressList
* addresses
)
471 : source_net_log_(source_net_log
),
476 addresses_(addresses
),
477 request_time_(base::TimeTicks::Now()) {}
479 // Mark the request as canceled.
480 void MarkAsCanceled() {
486 bool was_canceled() const {
487 return callback_
.is_null();
490 void set_job(Job
* job
) {
492 // Identify which job the request is waiting on.
496 // Prepare final AddressList and call completion callback.
497 void OnComplete(int error
, const AddressList
& addr_list
) {
498 DCHECK(!was_canceled());
500 *addresses_
= EnsurePortOnAddressList(addr_list
, info_
.port());
501 CompletionCallback callback
= callback_
;
510 // NetLog for the source, passed in HostResolver::Resolve.
511 const BoundNetLog
& source_net_log() {
512 return source_net_log_
;
515 const RequestInfo
& info() const {
519 RequestPriority
priority() const { return priority_
; }
521 base::TimeTicks
request_time() const { return request_time_
; }
524 const BoundNetLog source_net_log_
;
526 // The request info that started the request.
527 const RequestInfo info_
;
529 // TODO(akalin): Support reprioritization.
530 const RequestPriority priority_
;
532 // The resolve job that this request is dependent on.
535 // The user's callback to invoke when the request completes.
536 CompletionCallback callback_
;
538 // The address list to save result into.
539 AddressList
* addresses_
;
541 const base::TimeTicks request_time_
;
543 DISALLOW_COPY_AND_ASSIGN(Request
);
546 //------------------------------------------------------------------------------
548 // Calls HostResolverProc on the WorkerPool. Performs retries if necessary.
550 // Whenever we try to resolve the host, we post a delayed task to check if host
551 // resolution (OnLookupComplete) is completed or not. If the original attempt
552 // hasn't completed, then we start another attempt for host resolution. We take
553 // the results from the first attempt that finishes and ignore the results from
554 // all other attempts.
556 // TODO(szym): Move to separate source file for testing and mocking.
558 class HostResolverImpl::ProcTask
559 : public base::RefCountedThreadSafe
<HostResolverImpl::ProcTask
> {
561 typedef base::Callback
<void(int net_error
,
562 const AddressList
& addr_list
)> Callback
;
564 ProcTask(const Key
& key
,
565 const ProcTaskParams
& params
,
566 const Callback
& callback
,
567 const BoundNetLog
& job_net_log
)
571 origin_loop_(base::MessageLoopProxy::current()),
573 completed_attempt_number_(0),
574 completed_attempt_error_(ERR_UNEXPECTED
),
575 had_non_speculative_request_(false),
576 net_log_(job_net_log
) {
577 if (!params_
.resolver_proc
.get())
578 params_
.resolver_proc
= HostResolverProc::GetDefault();
579 // If default is unset, use the system proc.
580 if (!params_
.resolver_proc
.get())
581 params_
.resolver_proc
= new SystemHostResolverProc();
585 DCHECK(origin_loop_
->BelongsToCurrentThread());
586 net_log_
.BeginEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK
);
587 StartLookupAttempt();
590 // Cancels this ProcTask. It will be orphaned. Any outstanding resolve
591 // attempts running on worker threads will continue running. Only once all the
592 // attempts complete will the final reference to this ProcTask be released.
594 DCHECK(origin_loop_
->BelongsToCurrentThread());
596 if (was_canceled() || was_completed())
600 net_log_
.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK
);
603 void set_had_non_speculative_request() {
604 DCHECK(origin_loop_
->BelongsToCurrentThread());
605 had_non_speculative_request_
= true;
608 bool was_canceled() const {
609 DCHECK(origin_loop_
->BelongsToCurrentThread());
610 return callback_
.is_null();
613 bool was_completed() const {
614 DCHECK(origin_loop_
->BelongsToCurrentThread());
615 return completed_attempt_number_
> 0;
619 friend class base::RefCountedThreadSafe
<ProcTask
>;
622 void StartLookupAttempt() {
623 DCHECK(origin_loop_
->BelongsToCurrentThread());
624 base::TimeTicks start_time
= base::TimeTicks::Now();
626 // Dispatch the lookup attempt to a worker thread.
627 if (!base::WorkerPool::PostTask(
629 base::Bind(&ProcTask::DoLookup
, this, start_time
, attempt_number_
),
633 // Since we could be running within Resolve() right now, we can't just
634 // call OnLookupComplete(). Instead we must wait until Resolve() has
635 // returned (IO_PENDING).
636 origin_loop_
->PostTask(
638 base::Bind(&ProcTask::OnLookupComplete
, this, AddressList(),
639 start_time
, attempt_number_
, ERR_UNEXPECTED
, 0));
644 NetLog::TYPE_HOST_RESOLVER_IMPL_ATTEMPT_STARTED
,
645 NetLog::IntegerCallback("attempt_number", attempt_number_
));
647 // If we don't get the results within a given time, RetryIfNotComplete
648 // will start a new attempt on a different worker thread if none of our
649 // outstanding attempts have completed yet.
650 if (attempt_number_
<= params_
.max_retry_attempts
) {
651 origin_loop_
->PostDelayedTask(
653 base::Bind(&ProcTask::RetryIfNotComplete
, this),
654 params_
.unresponsive_delay
);
658 // WARNING: This code runs inside a worker pool. The shutdown code cannot
659 // wait for it to finish, so we must be very careful here about using other
660 // objects (like MessageLoops, Singletons, etc). During shutdown these objects
661 // may no longer exist. Multiple DoLookups() could be running in parallel, so
662 // any state inside of |this| must not mutate .
663 void DoLookup(const base::TimeTicks
& start_time
,
664 const uint32 attempt_number
) {
667 // Running on the worker thread
668 int error
= params_
.resolver_proc
->Resolve(key_
.hostname
,
670 key_
.host_resolver_flags
,
674 // Fail the resolution if the result contains 127.0.53.53. See the comment
675 // block of kIcanNameCollisionIp for details on why.
676 for (const auto& it
: results
) {
677 const IPAddressNumber
& cur
= it
.address();
678 if (cur
.size() == arraysize(kIcanNameCollisionIp
) &&
679 0 == memcmp(&cur
.front(), kIcanNameCollisionIp
, cur
.size())) {
680 error
= ERR_ICANN_NAME_COLLISION
;
685 origin_loop_
->PostTask(
687 base::Bind(&ProcTask::OnLookupComplete
, this, results
, start_time
,
688 attempt_number
, error
, os_error
));
691 // Makes next attempt if DoLookup() has not finished (runs on origin thread).
692 void RetryIfNotComplete() {
693 DCHECK(origin_loop_
->BelongsToCurrentThread());
695 if (was_completed() || was_canceled())
698 params_
.unresponsive_delay
*= params_
.retry_factor
;
699 StartLookupAttempt();
702 // Callback for when DoLookup() completes (runs on origin thread).
703 void OnLookupComplete(const AddressList
& results
,
704 const base::TimeTicks
& start_time
,
705 const uint32 attempt_number
,
707 const int os_error
) {
708 DCHECK(origin_loop_
->BelongsToCurrentThread());
709 // If results are empty, we should return an error.
710 bool empty_list_on_ok
= (error
== OK
&& results
.empty());
711 UMA_HISTOGRAM_BOOLEAN("DNS.EmptyAddressListAndNoError", empty_list_on_ok
);
712 if (empty_list_on_ok
)
713 error
= ERR_NAME_NOT_RESOLVED
;
715 bool was_retry_attempt
= attempt_number
> 1;
717 // Ideally the following code would be part of host_resolver_proc.cc,
718 // however it isn't safe to call NetworkChangeNotifier from worker threads.
719 // So we do it here on the IO thread instead.
720 if (error
!= OK
&& NetworkChangeNotifier::IsOffline())
721 error
= ERR_INTERNET_DISCONNECTED
;
723 // If this is the first attempt that is finishing later, then record data
724 // for the first attempt. Won't contaminate with retry attempt's data.
725 if (!was_retry_attempt
)
726 RecordPerformanceHistograms(start_time
, error
, os_error
);
728 RecordAttemptHistograms(start_time
, attempt_number
, error
, os_error
);
733 NetLog::ParametersCallback net_log_callback
;
735 net_log_callback
= base::Bind(&NetLogProcTaskFailedCallback
,
740 net_log_callback
= NetLog::IntegerCallback("attempt_number",
743 net_log_
.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_ATTEMPT_FINISHED
,
749 // Copy the results from the first worker thread that resolves the host.
751 completed_attempt_number_
= attempt_number
;
752 completed_attempt_error_
= error
;
754 if (was_retry_attempt
) {
755 // If retry attempt finishes before 1st attempt, then get stats on how
756 // much time is saved by having spawned an extra attempt.
757 retry_attempt_finished_time_
= base::TimeTicks::Now();
761 net_log_callback
= base::Bind(&NetLogProcTaskFailedCallback
,
764 net_log_callback
= results_
.CreateNetLogCallback();
766 net_log_
.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK
,
769 callback_
.Run(error
, results_
);
772 void RecordPerformanceHistograms(const base::TimeTicks
& start_time
,
774 const int os_error
) const {
775 DCHECK(origin_loop_
->BelongsToCurrentThread());
776 enum Category
{ // Used in UMA_HISTOGRAM_ENUMERATION.
779 RESOLVE_SPECULATIVE_SUCCESS
,
780 RESOLVE_SPECULATIVE_FAIL
,
781 RESOLVE_MAX
, // Bounding value.
783 int category
= RESOLVE_MAX
; // Illegal value for later DCHECK only.
785 base::TimeDelta duration
= base::TimeTicks::Now() - start_time
;
787 if (had_non_speculative_request_
) {
788 category
= RESOLVE_SUCCESS
;
789 DNS_HISTOGRAM("DNS.ResolveSuccess", duration
);
791 category
= RESOLVE_SPECULATIVE_SUCCESS
;
792 DNS_HISTOGRAM("DNS.ResolveSpeculativeSuccess", duration
);
795 // Log DNS lookups based on |address_family|. This will help us determine
796 // if IPv4 or IPv4/6 lookups are faster or slower.
797 switch(key_
.address_family
) {
798 case ADDRESS_FAMILY_IPV4
:
799 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_IPV4", duration
);
801 case ADDRESS_FAMILY_IPV6
:
802 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_IPV6", duration
);
804 case ADDRESS_FAMILY_UNSPECIFIED
:
805 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_UNSPEC", duration
);
809 if (had_non_speculative_request_
) {
810 category
= RESOLVE_FAIL
;
811 DNS_HISTOGRAM("DNS.ResolveFail", duration
);
813 category
= RESOLVE_SPECULATIVE_FAIL
;
814 DNS_HISTOGRAM("DNS.ResolveSpeculativeFail", duration
);
816 // Log DNS lookups based on |address_family|. This will help us determine
817 // if IPv4 or IPv4/6 lookups are faster or slower.
818 switch(key_
.address_family
) {
819 case ADDRESS_FAMILY_IPV4
:
820 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_IPV4", duration
);
822 case ADDRESS_FAMILY_IPV6
:
823 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_IPV6", duration
);
825 case ADDRESS_FAMILY_UNSPECIFIED
:
826 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_UNSPEC", duration
);
829 UMA_HISTOGRAM_CUSTOM_ENUMERATION(kOSErrorsForGetAddrinfoHistogramName
,
831 GetAllGetAddrinfoOSErrors());
833 DCHECK_LT(category
, static_cast<int>(RESOLVE_MAX
)); // Be sure it was set.
835 UMA_HISTOGRAM_ENUMERATION("DNS.ResolveCategory", category
, RESOLVE_MAX
);
838 void RecordAttemptHistograms(const base::TimeTicks
& start_time
,
839 const uint32 attempt_number
,
841 const int os_error
) const {
842 DCHECK(origin_loop_
->BelongsToCurrentThread());
843 bool first_attempt_to_complete
=
844 completed_attempt_number_
== attempt_number
;
845 bool is_first_attempt
= (attempt_number
== 1);
847 if (first_attempt_to_complete
) {
848 // If this was first attempt to complete, then record the resolution
849 // status of the attempt.
850 if (completed_attempt_error_
== OK
) {
851 UMA_HISTOGRAM_ENUMERATION(
852 "DNS.AttemptFirstSuccess", attempt_number
, 100);
854 UMA_HISTOGRAM_ENUMERATION(
855 "DNS.AttemptFirstFailure", attempt_number
, 100);
860 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptSuccess", attempt_number
, 100);
862 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptFailure", attempt_number
, 100);
864 // If first attempt didn't finish before retry attempt, then calculate stats
865 // on how much time is saved by having spawned an extra attempt.
866 if (!first_attempt_to_complete
&& is_first_attempt
&& !was_canceled()) {
867 DNS_HISTOGRAM("DNS.AttemptTimeSavedByRetry",
868 base::TimeTicks::Now() - retry_attempt_finished_time_
);
871 if (was_canceled() || !first_attempt_to_complete
) {
872 // Count those attempts which completed after the job was already canceled
873 // OR after the job was already completed by an earlier attempt (so in
875 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptDiscarded", attempt_number
, 100);
877 // Record if job is canceled.
879 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptCancelled", attempt_number
, 100);
882 base::TimeDelta duration
= base::TimeTicks::Now() - start_time
;
884 DNS_HISTOGRAM("DNS.AttemptSuccessDuration", duration
);
886 DNS_HISTOGRAM("DNS.AttemptFailDuration", duration
);
889 // Set on the origin thread, read on the worker thread.
892 // Holds an owning reference to the HostResolverProc that we are going to use.
893 // This may not be the current resolver procedure by the time we call
894 // ResolveAddrInfo, but that's OK... we'll use it anyways, and the owning
895 // reference ensures that it remains valid until we are done.
896 ProcTaskParams params_
;
898 // The listener to the results of this ProcTask.
901 // Used to post ourselves onto the origin thread.
902 scoped_refptr
<base::MessageLoopProxy
> origin_loop_
;
904 // Keeps track of the number of attempts we have made so far to resolve the
905 // host. Whenever we start an attempt to resolve the host, we increase this
907 uint32 attempt_number_
;
909 // The index of the attempt which finished first (or 0 if the job is still in
911 uint32 completed_attempt_number_
;
913 // The result (a net error code) from the first attempt to complete.
914 int completed_attempt_error_
;
916 // The time when retry attempt was finished.
917 base::TimeTicks retry_attempt_finished_time_
;
919 // True if a non-speculative request was ever attached to this job
920 // (regardless of whether or not it was later canceled.
921 // This boolean is used for histogramming the duration of jobs used to
922 // service non-speculative requests.
923 bool had_non_speculative_request_
;
925 AddressList results_
;
927 BoundNetLog net_log_
;
929 DISALLOW_COPY_AND_ASSIGN(ProcTask
);
932 //-----------------------------------------------------------------------------
934 // Wraps a call to HaveOnlyLoopbackAddresses to be executed on the WorkerPool as
935 // it takes 40-100ms and should not block initialization.
936 class HostResolverImpl::LoopbackProbeJob
{
938 explicit LoopbackProbeJob(const base::WeakPtr
<HostResolverImpl
>& resolver
)
939 : resolver_(resolver
),
941 DCHECK(resolver
.get());
942 const bool kIsSlow
= true;
943 base::WorkerPool::PostTaskAndReply(
945 base::Bind(&LoopbackProbeJob::DoProbe
, base::Unretained(this)),
946 base::Bind(&LoopbackProbeJob::OnProbeComplete
, base::Owned(this)),
950 virtual ~LoopbackProbeJob() {}
953 // Runs on worker thread.
955 result_
= HaveOnlyLoopbackAddresses();
958 void OnProbeComplete() {
959 if (!resolver_
.get())
961 resolver_
->SetHaveOnlyLoopbackAddresses(result_
);
964 // Used/set only on origin thread.
965 base::WeakPtr
<HostResolverImpl
> resolver_
;
969 DISALLOW_COPY_AND_ASSIGN(LoopbackProbeJob
);
972 //-----------------------------------------------------------------------------
974 // Resolves the hostname using DnsTransaction.
975 // TODO(szym): This could be moved to separate source file as well.
976 class HostResolverImpl::DnsTask
: public base::SupportsWeakPtr
<DnsTask
> {
980 virtual void OnDnsTaskComplete(base::TimeTicks start_time
,
982 const AddressList
& addr_list
,
983 base::TimeDelta ttl
) = 0;
985 // Called when the first of two jobs succeeds. If the first completed
986 // transaction fails, this is not called. Also not called when the DnsTask
987 // only needs to run one transaction.
988 virtual void OnFirstDnsTransactionComplete() = 0;
992 virtual ~Delegate() {}
995 DnsTask(DnsClient
* client
,
998 const BoundNetLog
& job_net_log
)
1001 delegate_(delegate
),
1002 net_log_(job_net_log
),
1003 num_completed_transactions_(0),
1004 task_start_time_(base::TimeTicks::Now()) {
1009 bool needs_two_transactions() const {
1010 return key_
.address_family
== ADDRESS_FAMILY_UNSPECIFIED
;
1013 bool needs_another_transaction() const {
1014 return needs_two_transactions() && !transaction_aaaa_
;
1017 void StartFirstTransaction() {
1018 DCHECK_EQ(0u, num_completed_transactions_
);
1019 net_log_
.BeginEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK
);
1020 if (key_
.address_family
== ADDRESS_FAMILY_IPV6
) {
1027 void StartSecondTransaction() {
1028 DCHECK(needs_two_transactions());
1034 DCHECK(!transaction_a_
);
1035 DCHECK_NE(ADDRESS_FAMILY_IPV6
, key_
.address_family
);
1036 transaction_a_
= CreateTransaction(ADDRESS_FAMILY_IPV4
);
1037 transaction_a_
->Start();
1041 DCHECK(!transaction_aaaa_
);
1042 DCHECK_NE(ADDRESS_FAMILY_IPV4
, key_
.address_family
);
1043 transaction_aaaa_
= CreateTransaction(ADDRESS_FAMILY_IPV6
);
1044 transaction_aaaa_
->Start();
1047 scoped_ptr
<DnsTransaction
> CreateTransaction(AddressFamily family
) {
1048 DCHECK_NE(ADDRESS_FAMILY_UNSPECIFIED
, family
);
1049 return client_
->GetTransactionFactory()->CreateTransaction(
1051 family
== ADDRESS_FAMILY_IPV6
? dns_protocol::kTypeAAAA
:
1052 dns_protocol::kTypeA
,
1053 base::Bind(&DnsTask::OnTransactionComplete
, base::Unretained(this),
1054 base::TimeTicks::Now()),
1058 void OnTransactionComplete(const base::TimeTicks
& start_time
,
1059 DnsTransaction
* transaction
,
1061 const DnsResponse
* response
) {
1062 DCHECK(transaction
);
1063 base::TimeDelta duration
= base::TimeTicks::Now() - start_time
;
1064 if (net_error
!= OK
) {
1065 DNS_HISTOGRAM("AsyncDNS.TransactionFailure", duration
);
1066 OnFailure(net_error
, DnsResponse::DNS_PARSE_OK
);
1070 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess", duration
);
1071 switch (transaction
->GetType()) {
1072 case dns_protocol::kTypeA
:
1073 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess_A", duration
);
1075 case dns_protocol::kTypeAAAA
:
1076 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess_AAAA", duration
);
1080 AddressList addr_list
;
1081 base::TimeDelta ttl
;
1082 DnsResponse::Result result
= response
->ParseToAddressList(&addr_list
, &ttl
);
1083 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ParseToAddressList",
1085 DnsResponse::DNS_PARSE_RESULT_MAX
);
1086 if (result
!= DnsResponse::DNS_PARSE_OK
) {
1087 // Fail even if the other query succeeds.
1088 OnFailure(ERR_DNS_MALFORMED_RESPONSE
, result
);
1092 ++num_completed_transactions_
;
1093 if (num_completed_transactions_
== 1) {
1096 ttl_
= std::min(ttl_
, ttl
);
1099 if (transaction
->GetType() == dns_protocol::kTypeA
) {
1100 DCHECK_EQ(transaction_a_
.get(), transaction
);
1101 // Place IPv4 addresses after IPv6.
1102 addr_list_
.insert(addr_list_
.end(), addr_list
.begin(), addr_list
.end());
1104 DCHECK_EQ(transaction_aaaa_
.get(), transaction
);
1105 // Place IPv6 addresses before IPv4.
1106 addr_list_
.insert(addr_list_
.begin(), addr_list
.begin(), addr_list
.end());
1109 if (needs_two_transactions() && num_completed_transactions_
== 1) {
1110 // No need to repeat the suffix search.
1111 key_
.hostname
= transaction
->GetHostname();
1112 delegate_
->OnFirstDnsTransactionComplete();
1116 if (addr_list_
.empty()) {
1117 // TODO(szym): Don't fallback to ProcTask in this case.
1118 OnFailure(ERR_NAME_NOT_RESOLVED
, DnsResponse::DNS_PARSE_OK
);
1122 // If there are multiple addresses, and at least one is IPv6, need to sort
1123 // them. Note that IPv6 addresses are always put before IPv4 ones, so it's
1124 // sufficient to just check the family of the first address.
1125 if (addr_list_
.size() > 1 &&
1126 addr_list_
[0].GetFamily() == ADDRESS_FAMILY_IPV6
) {
1127 // Sort addresses if needed. Sort could complete synchronously.
1128 client_
->GetAddressSorter()->Sort(
1130 base::Bind(&DnsTask::OnSortComplete
,
1132 base::TimeTicks::Now()));
1134 OnSuccess(addr_list_
);
1138 void OnSortComplete(base::TimeTicks start_time
,
1140 const AddressList
& addr_list
) {
1142 DNS_HISTOGRAM("AsyncDNS.SortFailure",
1143 base::TimeTicks::Now() - start_time
);
1144 OnFailure(ERR_DNS_SORT_ERROR
, DnsResponse::DNS_PARSE_OK
);
1148 DNS_HISTOGRAM("AsyncDNS.SortSuccess",
1149 base::TimeTicks::Now() - start_time
);
1151 // AddressSorter prunes unusable destinations.
1152 if (addr_list
.empty()) {
1153 LOG(WARNING
) << "Address list empty after RFC3484 sort";
1154 OnFailure(ERR_NAME_NOT_RESOLVED
, DnsResponse::DNS_PARSE_OK
);
1158 OnSuccess(addr_list
);
1161 void OnFailure(int net_error
, DnsResponse::Result result
) {
1162 DCHECK_NE(OK
, net_error
);
1164 NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK
,
1165 base::Bind(&NetLogDnsTaskFailedCallback
, net_error
, result
));
1166 delegate_
->OnDnsTaskComplete(task_start_time_
, net_error
, AddressList(),
1170 void OnSuccess(const AddressList
& addr_list
) {
1171 net_log_
.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK
,
1172 addr_list
.CreateNetLogCallback());
1173 delegate_
->OnDnsTaskComplete(task_start_time_
, OK
, addr_list
, ttl_
);
1179 // The listener to the results of this DnsTask.
1180 Delegate
* delegate_
;
1181 const BoundNetLog net_log_
;
1183 scoped_ptr
<DnsTransaction
> transaction_a_
;
1184 scoped_ptr
<DnsTransaction
> transaction_aaaa_
;
1186 unsigned num_completed_transactions_
;
1188 // These are updated as each transaction completes.
1189 base::TimeDelta ttl_
;
1190 // IPv6 addresses must appear first in the list.
1191 AddressList addr_list_
;
1193 base::TimeTicks task_start_time_
;
1195 DISALLOW_COPY_AND_ASSIGN(DnsTask
);
1198 //-----------------------------------------------------------------------------
1200 // Aggregates all Requests for the same Key. Dispatched via PriorityDispatch.
1201 class HostResolverImpl::Job
: public PrioritizedDispatcher::Job
,
1202 public HostResolverImpl::DnsTask::Delegate
{
1204 // Creates new job for |key| where |request_net_log| is bound to the
1205 // request that spawned it.
1206 Job(const base::WeakPtr
<HostResolverImpl
>& resolver
,
1208 RequestPriority priority
,
1209 const BoundNetLog
& source_net_log
)
1210 : resolver_(resolver
),
1212 priority_tracker_(priority
),
1213 had_non_speculative_request_(false),
1214 had_dns_config_(false),
1215 num_occupied_job_slots_(0),
1216 dns_task_error_(OK
),
1217 creation_time_(base::TimeTicks::Now()),
1218 priority_change_time_(creation_time_
),
1219 net_log_(BoundNetLog::Make(source_net_log
.net_log(),
1220 NetLog::SOURCE_HOST_RESOLVER_IMPL_JOB
)) {
1221 source_net_log
.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_CREATE_JOB
);
1223 net_log_
.BeginEvent(
1224 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB
,
1225 base::Bind(&NetLogJobCreationCallback
,
1226 source_net_log
.source(),
1232 // |resolver_| was destroyed with this Job still in flight.
1233 // Clean-up, record in the log, but don't run any callbacks.
1234 if (is_proc_running()) {
1235 proc_task_
->Cancel();
1238 // Clean up now for nice NetLog.
1240 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB
,
1242 } else if (is_queued()) {
1243 // |resolver_| was destroyed without running this Job.
1244 // TODO(szym): is there any benefit in having this distinction?
1245 net_log_
.AddEvent(NetLog::TYPE_CANCELLED
);
1246 net_log_
.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB
);
1248 // else CompleteRequests logged EndEvent.
1250 // Log any remaining Requests as cancelled.
1251 for (RequestsList::const_iterator it
= requests_
.begin();
1252 it
!= requests_
.end(); ++it
) {
1254 if (req
->was_canceled())
1256 DCHECK_EQ(this, req
->job());
1257 LogCancelRequest(req
->source_net_log(), req
->info());
1261 // Add this job to the dispatcher. If "at_head" is true, adds at the front
1263 void Schedule(bool at_head
) {
1264 DCHECK(!is_queued());
1265 PrioritizedDispatcher::Handle handle
;
1267 handle
= resolver_
->dispatcher_
->Add(this, priority());
1269 handle
= resolver_
->dispatcher_
->AddAtHead(this, priority());
1271 // The dispatcher could have started |this| in the above call to Add, which
1272 // could have called Schedule again. In that case |handle| will be null,
1273 // but |handle_| may have been set by the other nested call to Schedule.
1274 if (!handle
.is_null()) {
1275 DCHECK(handle_
.is_null());
1280 void AddRequest(scoped_ptr
<Request
> req
) {
1281 // .localhost queries are redirected to "localhost." to make sure
1282 // that they are never sent out on the network, per RFC 6761.
1283 if (IsLocalhostTLD(req
->info().hostname())) {
1284 DCHECK_EQ(key_
.hostname
, kLocalhost
);
1286 DCHECK_EQ(key_
.hostname
, req
->info().hostname());
1290 priority_tracker_
.Add(req
->priority());
1292 req
->source_net_log().AddEvent(
1293 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_ATTACH
,
1294 net_log_
.source().ToEventParametersCallback());
1297 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_REQUEST_ATTACH
,
1298 base::Bind(&NetLogJobAttachCallback
,
1299 req
->source_net_log().source(),
1302 // TODO(szym): Check if this is still needed.
1303 if (!req
->info().is_speculative()) {
1304 had_non_speculative_request_
= true;
1305 if (proc_task_
.get())
1306 proc_task_
->set_had_non_speculative_request();
1309 requests_
.push_back(req
.release());
1314 // Marks |req| as cancelled. If it was the last active Request, also finishes
1315 // this Job, marking it as cancelled, and deletes it.
1316 void CancelRequest(Request
* req
) {
1317 DCHECK_EQ(key_
.hostname
, req
->info().hostname());
1318 DCHECK(!req
->was_canceled());
1320 // Don't remove it from |requests_| just mark it canceled.
1321 req
->MarkAsCanceled();
1322 LogCancelRequest(req
->source_net_log(), req
->info());
1324 priority_tracker_
.Remove(req
->priority());
1325 net_log_
.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_REQUEST_DETACH
,
1326 base::Bind(&NetLogJobAttachCallback
,
1327 req
->source_net_log().source(),
1330 if (num_active_requests() > 0) {
1333 // If we were called from a Request's callback within CompleteRequests,
1334 // that Request could not have been cancelled, so num_active_requests()
1335 // could not be 0. Therefore, we are not in CompleteRequests().
1336 CompleteRequestsWithError(OK
/* cancelled */);
1340 // Called from AbortAllInProgressJobs. Completes all requests and destroys
1341 // the job. This currently assumes the abort is due to a network change.
1343 DCHECK(is_running());
1344 CompleteRequestsWithError(ERR_NETWORK_CHANGED
);
1347 // If DnsTask present, abort it and fall back to ProcTask.
1348 void AbortDnsTask() {
1351 dns_task_error_
= OK
;
1356 // Called by HostResolverImpl when this job is evicted due to queue overflow.
1357 // Completes all requests and destroys the job.
1359 DCHECK(!is_running());
1360 DCHECK(is_queued());
1363 net_log_
.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_EVICTED
);
1365 // This signals to CompleteRequests that this job never ran.
1366 CompleteRequestsWithError(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE
);
1369 // Attempts to serve the job from HOSTS. Returns true if succeeded and
1370 // this Job was destroyed.
1371 bool ServeFromHosts() {
1372 DCHECK_GT(num_active_requests(), 0u);
1373 AddressList addr_list
;
1374 if (resolver_
->ServeFromHosts(key(),
1375 requests_
.front()->info(),
1377 // This will destroy the Job.
1379 HostCache::Entry(OK
, MakeAddressListForRequest(addr_list
)),
1386 const Key
key() const {
1390 bool is_queued() const {
1391 return !handle_
.is_null();
1394 bool is_running() const {
1395 return is_dns_running() || is_proc_running();
1399 void KillDnsTask() {
1401 ReduceToOneJobSlot();
1406 // Reduce the number of job slots occupied and queued in the dispatcher
1407 // to one. If the second Job slot is queued in the dispatcher, cancels the
1408 // queued job. Otherwise, the second Job has been started by the
1409 // PrioritizedDispatcher, so signals it is complete.
1410 void ReduceToOneJobSlot() {
1411 DCHECK_GE(num_occupied_job_slots_
, 1u);
1413 resolver_
->dispatcher_
->Cancel(handle_
);
1415 } else if (num_occupied_job_slots_
> 1) {
1416 resolver_
->dispatcher_
->OnJobFinished();
1417 --num_occupied_job_slots_
;
1419 DCHECK_EQ(1u, num_occupied_job_slots_
);
1422 void UpdatePriority() {
1424 if (priority() != static_cast<RequestPriority
>(handle_
.priority()))
1425 priority_change_time_
= base::TimeTicks::Now();
1426 handle_
= resolver_
->dispatcher_
->ChangePriority(handle_
, priority());
1430 AddressList
MakeAddressListForRequest(const AddressList
& list
) const {
1431 if (requests_
.empty())
1433 return AddressList::CopyWithPort(list
, requests_
.front()->info().port());
1436 // PriorityDispatch::Job:
1437 void Start() override
{
1438 DCHECK_LE(num_occupied_job_slots_
, 1u);
1441 ++num_occupied_job_slots_
;
1443 if (num_occupied_job_slots_
== 2) {
1444 StartSecondDnsTransaction();
1448 DCHECK(!is_running());
1450 net_log_
.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_STARTED
);
1452 had_dns_config_
= resolver_
->HaveDnsConfig();
1454 base::TimeTicks now
= base::TimeTicks::Now();
1455 base::TimeDelta queue_time
= now
- creation_time_
;
1456 base::TimeDelta queue_time_after_change
= now
- priority_change_time_
;
1458 if (had_dns_config_
) {
1459 DNS_HISTOGRAM_BY_PRIORITY("AsyncDNS.JobQueueTime", priority(),
1461 DNS_HISTOGRAM_BY_PRIORITY("AsyncDNS.JobQueueTimeAfterChange", priority(),
1462 queue_time_after_change
);
1464 DNS_HISTOGRAM_BY_PRIORITY("DNS.JobQueueTime", priority(), queue_time
);
1465 DNS_HISTOGRAM_BY_PRIORITY("DNS.JobQueueTimeAfterChange", priority(),
1466 queue_time_after_change
);
1470 (key_
.host_resolver_flags
& HOST_RESOLVER_SYSTEM_ONLY
) != 0;
1472 // Caution: Job::Start must not complete synchronously.
1473 if (!system_only
&& had_dns_config_
&&
1474 !ResemblesMulticastDNSName(key_
.hostname
)) {
1481 // TODO(szym): Since DnsTransaction does not consume threads, we can increase
1482 // the limits on |dispatcher_|. But in order to keep the number of WorkerPool
1483 // threads low, we will need to use an "inner" PrioritizedDispatcher with
1485 void StartProcTask() {
1486 DCHECK(!is_dns_running());
1487 proc_task_
= new ProcTask(
1489 resolver_
->proc_params_
,
1490 base::Bind(&Job::OnProcTaskComplete
, base::Unretained(this),
1491 base::TimeTicks::Now()),
1494 if (had_non_speculative_request_
)
1495 proc_task_
->set_had_non_speculative_request();
1496 // Start() could be called from within Resolve(), hence it must NOT directly
1497 // call OnProcTaskComplete, for example, on synchronous failure.
1498 proc_task_
->Start();
1501 // Called by ProcTask when it completes.
1502 void OnProcTaskComplete(base::TimeTicks start_time
,
1504 const AddressList
& addr_list
) {
1505 DCHECK(is_proc_running());
1507 if (!resolver_
->resolved_known_ipv6_hostname_
&&
1509 key_
.address_family
== ADDRESS_FAMILY_UNSPECIFIED
) {
1510 if (key_
.hostname
== "www.google.com") {
1511 resolver_
->resolved_known_ipv6_hostname_
= true;
1512 bool got_ipv6_address
= false;
1513 for (size_t i
= 0; i
< addr_list
.size(); ++i
) {
1514 if (addr_list
[i
].GetFamily() == ADDRESS_FAMILY_IPV6
) {
1515 got_ipv6_address
= true;
1519 UMA_HISTOGRAM_BOOLEAN("Net.UnspecResolvedIPv6", got_ipv6_address
);
1523 if (dns_task_error_
!= OK
) {
1524 base::TimeDelta duration
= base::TimeTicks::Now() - start_time
;
1525 if (net_error
== OK
) {
1526 DNS_HISTOGRAM("AsyncDNS.FallbackSuccess", duration
);
1527 if ((dns_task_error_
== ERR_NAME_NOT_RESOLVED
) &&
1528 ResemblesNetBIOSName(key_
.hostname
)) {
1529 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_SUSPECT_NETBIOS
);
1531 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_PROC_SUCCESS
);
1533 UMA_HISTOGRAM_CUSTOM_ENUMERATION("AsyncDNS.ResolveError",
1534 std::abs(dns_task_error_
),
1535 GetAllErrorCodesForUma());
1536 resolver_
->OnDnsTaskResolve(dns_task_error_
);
1538 DNS_HISTOGRAM("AsyncDNS.FallbackFail", duration
);
1539 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL
);
1543 base::TimeDelta ttl
=
1544 base::TimeDelta::FromSeconds(kNegativeCacheEntryTTLSeconds
);
1545 if (net_error
== OK
)
1546 ttl
= base::TimeDelta::FromSeconds(kCacheEntryTTLSeconds
);
1548 // Don't store the |ttl| in cache since it's not obtained from the server.
1550 HostCache::Entry(net_error
, MakeAddressListForRequest(addr_list
)),
1554 void StartDnsTask() {
1555 DCHECK(resolver_
->HaveDnsConfig());
1556 dns_task_
.reset(new DnsTask(resolver_
->dns_client_
.get(), key_
, this,
1559 dns_task_
->StartFirstTransaction();
1560 // Schedule a second transaction, if needed.
1561 if (dns_task_
->needs_two_transactions())
1565 void StartSecondDnsTransaction() {
1566 DCHECK(dns_task_
->needs_two_transactions());
1567 dns_task_
->StartSecondTransaction();
1570 // Called if DnsTask fails. It is posted from StartDnsTask, so Job may be
1571 // deleted before this callback. In this case dns_task is deleted as well,
1572 // so we use it as indicator whether Job is still valid.
1573 void OnDnsTaskFailure(const base::WeakPtr
<DnsTask
>& dns_task
,
1574 base::TimeDelta duration
,
1576 DNS_HISTOGRAM("AsyncDNS.ResolveFail", duration
);
1578 if (dns_task
== NULL
)
1581 dns_task_error_
= net_error
;
1583 // TODO(szym): Run ServeFromHosts now if nsswitch.conf says so.
1584 // http://crbug.com/117655
1586 // TODO(szym): Some net errors indicate lack of connectivity. Starting
1587 // ProcTask in that case is a waste of time.
1588 if (resolver_
->fallback_to_proctask_
) {
1592 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL
);
1593 CompleteRequestsWithError(net_error
);
1598 // HostResolverImpl::DnsTask::Delegate implementation:
1600 void OnDnsTaskComplete(base::TimeTicks start_time
,
1602 const AddressList
& addr_list
,
1603 base::TimeDelta ttl
) override
{
1604 DCHECK(is_dns_running());
1606 base::TimeDelta duration
= base::TimeTicks::Now() - start_time
;
1607 if (net_error
!= OK
) {
1608 OnDnsTaskFailure(dns_task_
->AsWeakPtr(), duration
, net_error
);
1611 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess", duration
);
1612 // Log DNS lookups based on |address_family|.
1613 switch(key_
.address_family
) {
1614 case ADDRESS_FAMILY_IPV4
:
1615 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_IPV4", duration
);
1617 case ADDRESS_FAMILY_IPV6
:
1618 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_IPV6", duration
);
1620 case ADDRESS_FAMILY_UNSPECIFIED
:
1621 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_UNSPEC", duration
);
1625 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_DNS_SUCCESS
);
1628 resolver_
->OnDnsTaskResolve(OK
);
1630 base::TimeDelta bounded_ttl
=
1631 std::max(ttl
, base::TimeDelta::FromSeconds(kMinimumTTLSeconds
));
1634 HostCache::Entry(net_error
, MakeAddressListForRequest(addr_list
), ttl
),
1638 void OnFirstDnsTransactionComplete() override
{
1639 DCHECK(dns_task_
->needs_two_transactions());
1640 DCHECK_EQ(dns_task_
->needs_another_transaction(), is_queued());
1641 // No longer need to occupy two dispatcher slots.
1642 ReduceToOneJobSlot();
1644 // We already have a job slot at the dispatcher, so if the second
1645 // transaction hasn't started, reuse it now instead of waiting in the queue
1646 // for the second slot.
1647 if (dns_task_
->needs_another_transaction())
1648 dns_task_
->StartSecondTransaction();
1651 // Performs Job's last rites. Completes all Requests. Deletes this.
1652 void CompleteRequests(const HostCache::Entry
& entry
,
1653 base::TimeDelta ttl
) {
1654 CHECK(resolver_
.get());
1656 // This job must be removed from resolver's |jobs_| now to make room for a
1657 // new job with the same key in case one of the OnComplete callbacks decides
1658 // to spawn one. Consequently, the job deletes itself when CompleteRequests
1660 scoped_ptr
<Job
> self_deleter(this);
1662 resolver_
->RemoveJob(this);
1665 if (is_proc_running()) {
1666 DCHECK(!is_queued());
1667 proc_task_
->Cancel();
1672 // Signal dispatcher that a slot has opened.
1673 resolver_
->dispatcher_
->OnJobFinished();
1674 } else if (is_queued()) {
1675 resolver_
->dispatcher_
->Cancel(handle_
);
1679 if (num_active_requests() == 0) {
1680 net_log_
.AddEvent(NetLog::TYPE_CANCELLED
);
1681 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB
,
1686 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB
,
1689 DCHECK(!requests_
.empty());
1691 if (entry
.error
== OK
) {
1692 // Record this histogram here, when we know the system has a valid DNS
1694 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.HaveDnsConfig",
1695 resolver_
->received_dns_config_
);
1698 bool did_complete
= (entry
.error
!= ERR_NETWORK_CHANGED
) &&
1699 (entry
.error
!= ERR_HOST_RESOLVER_QUEUE_TOO_LARGE
);
1701 resolver_
->CacheResult(key_
, entry
, ttl
);
1703 // Complete all of the requests that were attached to the job.
1704 for (RequestsList::const_iterator it
= requests_
.begin();
1705 it
!= requests_
.end(); ++it
) {
1708 if (req
->was_canceled())
1711 DCHECK_EQ(this, req
->job());
1712 // Update the net log and notify registered observers.
1713 LogFinishRequest(req
->source_net_log(), req
->info(), entry
.error
);
1715 // Record effective total time from creation to completion.
1716 RecordTotalTime(had_dns_config_
, req
->info().is_speculative(),
1717 base::TimeTicks::Now() - req
->request_time());
1719 req
->OnComplete(entry
.error
, entry
.addrlist
);
1721 // Check if the resolver was destroyed as a result of running the
1722 // callback. If it was, we could continue, but we choose to bail.
1723 if (!resolver_
.get())
1728 // Convenience wrapper for CompleteRequests in case of failure.
1729 void CompleteRequestsWithError(int net_error
) {
1730 CompleteRequests(HostCache::Entry(net_error
, AddressList()),
1734 RequestPriority
priority() const {
1735 return priority_tracker_
.highest_priority();
1738 // Number of non-canceled requests in |requests_|.
1739 size_t num_active_requests() const {
1740 return priority_tracker_
.total_count();
1743 bool is_dns_running() const {
1744 return dns_task_
.get() != NULL
;
1747 bool is_proc_running() const {
1748 return proc_task_
.get() != NULL
;
1751 base::WeakPtr
<HostResolverImpl
> resolver_
;
1755 // Tracks the highest priority across |requests_|.
1756 PriorityTracker priority_tracker_
;
1758 bool had_non_speculative_request_
;
1760 // Distinguishes measurements taken while DnsClient was fully configured.
1761 bool had_dns_config_
;
1763 // Number of slots occupied by this Job in resolver's PrioritizedDispatcher.
1764 unsigned num_occupied_job_slots_
;
1766 // Result of DnsTask.
1767 int dns_task_error_
;
1769 const base::TimeTicks creation_time_
;
1770 base::TimeTicks priority_change_time_
;
1772 BoundNetLog net_log_
;
1774 // Resolves the host using a HostResolverProc.
1775 scoped_refptr
<ProcTask
> proc_task_
;
1777 // Resolves the host using a DnsTransaction.
1778 scoped_ptr
<DnsTask
> dns_task_
;
1780 // All Requests waiting for the result of this Job. Some can be canceled.
1781 RequestsList requests_
;
1783 // A handle used in |HostResolverImpl::dispatcher_|.
1784 PrioritizedDispatcher::Handle handle_
;
1787 //-----------------------------------------------------------------------------
1789 HostResolverImpl::ProcTaskParams::ProcTaskParams(
1790 HostResolverProc
* resolver_proc
,
1791 size_t max_retry_attempts
)
1792 : resolver_proc(resolver_proc
),
1793 max_retry_attempts(max_retry_attempts
),
1794 unresponsive_delay(base::TimeDelta::FromMilliseconds(6000)),
1796 // Maximum of 4 retry attempts for host resolution.
1797 static const size_t kDefaultMaxRetryAttempts
= 4u;
1798 if (max_retry_attempts
== HostResolver::kDefaultRetryAttempts
)
1799 max_retry_attempts
= kDefaultMaxRetryAttempts
;
1802 HostResolverImpl::ProcTaskParams::~ProcTaskParams() {}
1804 HostResolverImpl::HostResolverImpl(const Options
& options
, NetLog
* net_log
)
1805 : max_queued_jobs_(0),
1806 proc_params_(NULL
, options
.max_retry_attempts
),
1808 default_address_family_(ADDRESS_FAMILY_UNSPECIFIED
),
1809 received_dns_config_(false),
1810 num_dns_failures_(0),
1811 probe_ipv6_support_(true),
1812 use_local_ipv6_(false),
1813 resolved_known_ipv6_hostname_(false),
1814 additional_resolver_flags_(0),
1815 fallback_to_proctask_(true),
1816 weak_ptr_factory_(this),
1817 probe_weak_ptr_factory_(this) {
1818 if (options
.enable_caching
)
1819 cache_
= HostCache::CreateDefaultCache();
1821 PrioritizedDispatcher::Limits job_limits
= options
.GetDispatcherLimits();
1822 dispatcher_
.reset(new PrioritizedDispatcher(job_limits
));
1823 max_queued_jobs_
= job_limits
.total_jobs
* 100u;
1825 DCHECK_GE(dispatcher_
->num_priorities(), static_cast<size_t>(NUM_PRIORITIES
));
1828 EnsureWinsockInit();
1830 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
1831 new LoopbackProbeJob(weak_ptr_factory_
.GetWeakPtr());
1833 NetworkChangeNotifier::AddIPAddressObserver(this);
1834 NetworkChangeNotifier::AddDNSObserver(this);
1835 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD) && \
1836 !defined(OS_ANDROID)
1837 EnsureDnsReloaderInit();
1841 DnsConfig dns_config
;
1842 NetworkChangeNotifier::GetDnsConfig(&dns_config
);
1843 received_dns_config_
= dns_config
.IsValid();
1844 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
1845 use_local_ipv6_
= !dns_config
.IsValid() || dns_config
.use_local_ipv6
;
1848 fallback_to_proctask_
= !ConfigureAsyncDnsNoFallbackFieldTrial();
1851 HostResolverImpl::~HostResolverImpl() {
1852 // Prevent the dispatcher from starting new jobs.
1853 dispatcher_
->SetLimitsToZero();
1854 // It's now safe for Jobs to call KillDsnTask on destruction, because
1855 // OnJobComplete will not start any new jobs.
1856 STLDeleteValues(&jobs_
);
1858 NetworkChangeNotifier::RemoveIPAddressObserver(this);
1859 NetworkChangeNotifier::RemoveDNSObserver(this);
1862 void HostResolverImpl::SetMaxQueuedJobs(size_t value
) {
1863 DCHECK_EQ(0u, dispatcher_
->num_queued_jobs());
1864 DCHECK_GT(value
, 0u);
1865 max_queued_jobs_
= value
;
1868 int HostResolverImpl::Resolve(const RequestInfo
& info
,
1869 RequestPriority priority
,
1870 AddressList
* addresses
,
1871 const CompletionCallback
& callback
,
1872 RequestHandle
* out_req
,
1873 const BoundNetLog
& source_net_log
) {
1875 DCHECK(CalledOnValidThread());
1876 DCHECK_EQ(false, callback
.is_null());
1878 // Check that the caller supplied a valid hostname to resolve.
1879 std::string labeled_hostname
;
1880 if (!DNSDomainFromDot(info
.hostname(), &labeled_hostname
))
1881 return ERR_NAME_NOT_RESOLVED
;
1883 LogStartRequest(source_net_log
, info
);
1885 IPAddressNumber ip_number
;
1886 IPAddressNumber
* ip_number_ptr
= nullptr;
1887 if (ParseIPLiteralToNumber(info
.hostname(), &ip_number
))
1888 ip_number_ptr
= &ip_number
;
1890 // Build a key that identifies the request in the cache and in the
1891 // outstanding jobs map.
1892 Key key
= GetEffectiveKeyForRequest(info
, ip_number_ptr
, source_net_log
);
1894 int rv
= ResolveHelper(key
, info
, ip_number_ptr
, addresses
, source_net_log
);
1895 if (rv
!= ERR_DNS_CACHE_MISS
) {
1896 LogFinishRequest(source_net_log
, info
, rv
);
1897 RecordTotalTime(HaveDnsConfig(), info
.is_speculative(), base::TimeDelta());
1901 // Next we need to attach our request to a "job". This job is responsible for
1902 // calling "getaddrinfo(hostname)" on a worker thread.
1904 JobMap::iterator jobit
= jobs_
.find(key
);
1906 if (jobit
== jobs_
.end()) {
1908 new Job(weak_ptr_factory_
.GetWeakPtr(), key
, priority
, source_net_log
);
1909 job
->Schedule(false);
1911 // Check for queue overflow.
1912 if (dispatcher_
->num_queued_jobs() > max_queued_jobs_
) {
1913 Job
* evicted
= static_cast<Job
*>(dispatcher_
->EvictOldestLowest());
1915 evicted
->OnEvicted(); // Deletes |evicted|.
1916 if (evicted
== job
) {
1917 rv
= ERR_HOST_RESOLVER_QUEUE_TOO_LARGE
;
1918 LogFinishRequest(source_net_log
, info
, rv
);
1922 jobs_
.insert(jobit
, std::make_pair(key
, job
));
1924 job
= jobit
->second
;
1927 // Can't complete synchronously. Create and attach request.
1928 scoped_ptr
<Request
> req(new Request(
1929 source_net_log
, info
, priority
, callback
, addresses
));
1931 *out_req
= reinterpret_cast<RequestHandle
>(req
.get());
1933 job
->AddRequest(req
.Pass());
1934 // Completion happens during Job::CompleteRequests().
1935 return ERR_IO_PENDING
;
1938 int HostResolverImpl::ResolveHelper(const Key
& key
,
1939 const RequestInfo
& info
,
1940 const IPAddressNumber
* ip_number
,
1941 AddressList
* addresses
,
1942 const BoundNetLog
& source_net_log
) {
1943 // The result of |getaddrinfo| for empty hosts is inconsistent across systems.
1944 // On Windows it gives the default interface's address, whereas on Linux it
1945 // gives an error. We will make it fail on all platforms for consistency.
1946 if (info
.hostname().empty() || info
.hostname().size() > kMaxHostLength
)
1947 return ERR_NAME_NOT_RESOLVED
;
1949 int net_error
= ERR_UNEXPECTED
;
1950 if (ResolveAsIP(key
, info
, ip_number
, &net_error
, addresses
))
1952 if (ServeFromCache(key
, info
, &net_error
, addresses
)) {
1953 source_net_log
.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_CACHE_HIT
);
1956 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
1957 // http://crbug.com/117655
1958 if (ServeFromHosts(key
, info
, addresses
)) {
1959 source_net_log
.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_HOSTS_HIT
);
1962 return ERR_DNS_CACHE_MISS
;
1965 int HostResolverImpl::ResolveFromCache(const RequestInfo
& info
,
1966 AddressList
* addresses
,
1967 const BoundNetLog
& source_net_log
) {
1968 DCHECK(CalledOnValidThread());
1971 // Update the net log and notify registered observers.
1972 LogStartRequest(source_net_log
, info
);
1974 IPAddressNumber ip_number
;
1975 IPAddressNumber
* ip_number_ptr
= nullptr;
1976 if (ParseIPLiteralToNumber(info
.hostname(), &ip_number
))
1977 ip_number_ptr
= &ip_number
;
1979 Key key
= GetEffectiveKeyForRequest(info
, ip_number_ptr
, source_net_log
);
1981 int rv
= ResolveHelper(key
, info
, ip_number_ptr
, addresses
, source_net_log
);
1982 LogFinishRequest(source_net_log
, info
, rv
);
1986 void HostResolverImpl::CancelRequest(RequestHandle req_handle
) {
1987 DCHECK(CalledOnValidThread());
1988 Request
* req
= reinterpret_cast<Request
*>(req_handle
);
1990 Job
* job
= req
->job();
1992 job
->CancelRequest(req
);
1995 void HostResolverImpl::SetDefaultAddressFamily(AddressFamily address_family
) {
1996 DCHECK(CalledOnValidThread());
1997 default_address_family_
= address_family
;
1998 probe_ipv6_support_
= false;
2001 AddressFamily
HostResolverImpl::GetDefaultAddressFamily() const {
2002 return default_address_family_
;
2005 void HostResolverImpl::SetDnsClientEnabled(bool enabled
) {
2006 DCHECK(CalledOnValidThread());
2007 #if defined(ENABLE_BUILT_IN_DNS)
2008 if (enabled
&& !dns_client_
) {
2009 SetDnsClient(DnsClient::CreateClient(net_log_
));
2010 } else if (!enabled
&& dns_client_
) {
2011 SetDnsClient(scoped_ptr
<DnsClient
>());
2016 HostCache
* HostResolverImpl::GetHostCache() {
2017 return cache_
.get();
2020 base::Value
* HostResolverImpl::GetDnsConfigAsValue() const {
2021 // Check if async DNS is disabled.
2022 if (!dns_client_
.get())
2025 // Check if async DNS is enabled, but we currently have no configuration
2027 const DnsConfig
* dns_config
= dns_client_
->GetConfig();
2028 if (dns_config
== NULL
)
2029 return new base::DictionaryValue();
2031 return dns_config
->ToValue();
2034 bool HostResolverImpl::ResolveAsIP(const Key
& key
,
2035 const RequestInfo
& info
,
2036 const IPAddressNumber
* ip_number
,
2038 AddressList
* addresses
) {
2041 if (ip_number
== nullptr)
2044 DCHECK_EQ(key
.host_resolver_flags
&
2045 ~(HOST_RESOLVER_CANONNAME
| HOST_RESOLVER_LOOPBACK_ONLY
|
2046 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6
),
2047 0) << " Unhandled flag";
2050 AddressFamily family
= GetAddressFamily(*ip_number
);
2051 if (family
== ADDRESS_FAMILY_IPV6
&&
2052 !probe_ipv6_support_
&&
2053 default_address_family_
== ADDRESS_FAMILY_IPV4
) {
2054 // Don't return IPv6 addresses if default address family is set to IPv4,
2055 // and probes are disabled.
2056 *net_error
= ERR_NAME_NOT_RESOLVED
;
2057 } else if (key
.address_family
!= ADDRESS_FAMILY_UNSPECIFIED
&&
2058 key
.address_family
!= family
) {
2059 // Don't return IPv6 addresses for IPv4 queries, and vice versa.
2060 *net_error
= ERR_NAME_NOT_RESOLVED
;
2062 *addresses
= AddressList::CreateFromIPAddress(*ip_number
, info
.port());
2063 if (key
.host_resolver_flags
& HOST_RESOLVER_CANONNAME
)
2064 addresses
->SetDefaultCanonicalName();
2069 bool HostResolverImpl::ServeFromCache(const Key
& key
,
2070 const RequestInfo
& info
,
2072 AddressList
* addresses
) {
2075 if (!info
.allow_cached_response() || !cache_
.get())
2078 const HostCache::Entry
* cache_entry
= cache_
->Lookup(
2079 key
, base::TimeTicks::Now());
2083 *net_error
= cache_entry
->error
;
2084 if (*net_error
== OK
) {
2085 if (cache_entry
->has_ttl())
2086 RecordTTL(cache_entry
->ttl
);
2087 *addresses
= EnsurePortOnAddressList(cache_entry
->addrlist
, info
.port());
2092 bool HostResolverImpl::ServeFromHosts(const Key
& key
,
2093 const RequestInfo
& info
,
2094 AddressList
* addresses
) {
2096 if (!HaveDnsConfig())
2100 // HOSTS lookups are case-insensitive.
2101 std::string hostname
= base::StringToLowerASCII(key
.hostname
);
2103 const DnsHosts
& hosts
= dns_client_
->GetConfig()->hosts
;
2105 // If |address_family| is ADDRESS_FAMILY_UNSPECIFIED other implementations
2106 // (glibc and c-ares) return the first matching line. We have more
2107 // flexibility, but lose implicit ordering.
2108 // We prefer IPv6 because "happy eyeballs" will fall back to IPv4 if
2110 if (key
.address_family
== ADDRESS_FAMILY_IPV6
||
2111 key
.address_family
== ADDRESS_FAMILY_UNSPECIFIED
) {
2112 DnsHosts::const_iterator it
= hosts
.find(
2113 DnsHostsKey(hostname
, ADDRESS_FAMILY_IPV6
));
2114 if (it
!= hosts
.end())
2115 addresses
->push_back(IPEndPoint(it
->second
, info
.port()));
2118 if (key
.address_family
== ADDRESS_FAMILY_IPV4
||
2119 key
.address_family
== ADDRESS_FAMILY_UNSPECIFIED
) {
2120 DnsHosts::const_iterator it
= hosts
.find(
2121 DnsHostsKey(hostname
, ADDRESS_FAMILY_IPV4
));
2122 if (it
!= hosts
.end())
2123 addresses
->push_back(IPEndPoint(it
->second
, info
.port()));
2126 // If got only loopback addresses and the family was restricted, resolve
2127 // again, without restrictions. See SystemHostResolverCall for rationale.
2128 if ((key
.host_resolver_flags
&
2129 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6
) &&
2130 IsAllIPv4Loopback(*addresses
)) {
2132 new_key
.address_family
= ADDRESS_FAMILY_UNSPECIFIED
;
2133 new_key
.host_resolver_flags
&=
2134 ~HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6
;
2135 return ServeFromHosts(new_key
, info
, addresses
);
2137 return !addresses
->empty();
2140 void HostResolverImpl::CacheResult(const Key
& key
,
2141 const HostCache::Entry
& entry
,
2142 base::TimeDelta ttl
) {
2144 cache_
->Set(key
, entry
, base::TimeTicks::Now(), ttl
);
2147 void HostResolverImpl::RemoveJob(Job
* job
) {
2149 JobMap::iterator it
= jobs_
.find(job
->key());
2150 if (it
!= jobs_
.end() && it
->second
== job
)
2154 void HostResolverImpl::SetHaveOnlyLoopbackAddresses(bool result
) {
2156 additional_resolver_flags_
|= HOST_RESOLVER_LOOPBACK_ONLY
;
2158 additional_resolver_flags_
&= ~HOST_RESOLVER_LOOPBACK_ONLY
;
2162 HostResolverImpl::Key
HostResolverImpl::GetEffectiveKeyForRequest(
2163 const RequestInfo
& info
,
2164 const IPAddressNumber
* ip_number
,
2165 const BoundNetLog
& net_log
) const {
2166 HostResolverFlags effective_flags
=
2167 info
.host_resolver_flags() | additional_resolver_flags_
;
2168 AddressFamily effective_address_family
= info
.address_family();
2170 if (info
.address_family() == ADDRESS_FAMILY_UNSPECIFIED
) {
2171 if (probe_ipv6_support_
&& !use_local_ipv6_
&&
2172 // When resolving IPv4 literals, there's no need to probe for IPv6.
2173 // When resolving IPv6 literals, there's no benefit to artificially
2174 // limiting our resolution based on a probe. Prior logic ensures
2175 // that this query is UNSPECIFIED (see info.address_family()
2176 // check above) and that |default_address_family_| is UNSPECIFIED
2177 // (|prove_ipv6_support_| is false if |default_address_family_| is
2178 // set) so the code requesting the resolution should be amenable to
2179 // receiving a IPv6 resolution.
2180 ip_number
== nullptr) {
2181 // Google DNS address.
2182 const uint8 kIPv6Address
[] =
2183 { 0x20, 0x01, 0x48, 0x60, 0x48, 0x60, 0x00, 0x00,
2184 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x88 };
2185 IPAddressNumber
address(kIPv6Address
,
2186 kIPv6Address
+ arraysize(kIPv6Address
));
2187 BoundNetLog probe_net_log
= BoundNetLog::Make(
2188 net_log
.net_log(), NetLog::SOURCE_IPV6_REACHABILITY_CHECK
);
2189 probe_net_log
.BeginEvent(NetLog::TYPE_IPV6_REACHABILITY_CHECK
,
2190 net_log
.source().ToEventParametersCallback());
2191 bool rv6
= IsGloballyReachable(address
, probe_net_log
);
2192 probe_net_log
.EndEvent(NetLog::TYPE_IPV6_REACHABILITY_CHECK
);
2194 net_log
.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_IPV6_SUPPORTED
);
2196 effective_address_family
= ADDRESS_FAMILY_IPV4
;
2197 effective_flags
|= HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6
;
2200 effective_address_family
= default_address_family_
;
2204 std::string hostname
= info
.hostname();
2205 // Redirect .localhost queries to "localhost." to make sure that they
2206 // are never sent out on the network, per RFC 6761.
2207 if (IsLocalhostTLD(info
.hostname()))
2208 hostname
= kLocalhost
;
2210 return Key(hostname
, effective_address_family
, effective_flags
);
2213 void HostResolverImpl::AbortAllInProgressJobs() {
2214 // In Abort, a Request callback could spawn new Jobs with matching keys, so
2215 // first collect and remove all running jobs from |jobs_|.
2216 ScopedVector
<Job
> jobs_to_abort
;
2217 for (JobMap::iterator it
= jobs_
.begin(); it
!= jobs_
.end(); ) {
2218 Job
* job
= it
->second
;
2219 if (job
->is_running()) {
2220 jobs_to_abort
.push_back(job
);
2223 DCHECK(job
->is_queued());
2228 // Pause the dispatcher so it won't start any new dispatcher jobs while
2229 // aborting the old ones. This is needed so that it won't start the second
2230 // DnsTransaction for a job in |jobs_to_abort| if the DnsConfig just became
2232 PrioritizedDispatcher::Limits limits
= dispatcher_
->GetLimits();
2233 dispatcher_
->SetLimits(
2234 PrioritizedDispatcher::Limits(limits
.reserved_slots
.size(), 0));
2236 // Life check to bail once |this| is deleted.
2237 base::WeakPtr
<HostResolverImpl
> self
= weak_ptr_factory_
.GetWeakPtr();
2240 for (size_t i
= 0; self
.get() && i
< jobs_to_abort
.size(); ++i
) {
2241 jobs_to_abort
[i
]->Abort();
2242 jobs_to_abort
[i
] = NULL
;
2246 dispatcher_
->SetLimits(limits
);
2249 void HostResolverImpl::AbortDnsTasks() {
2250 // Pause the dispatcher so it won't start any new dispatcher jobs while
2251 // aborting the old ones. This is needed so that it won't start the second
2252 // DnsTransaction for a job if the DnsConfig just changed.
2253 PrioritizedDispatcher::Limits limits
= dispatcher_
->GetLimits();
2254 dispatcher_
->SetLimits(
2255 PrioritizedDispatcher::Limits(limits
.reserved_slots
.size(), 0));
2257 for (JobMap::iterator it
= jobs_
.begin(); it
!= jobs_
.end(); ++it
)
2258 it
->second
->AbortDnsTask();
2259 dispatcher_
->SetLimits(limits
);
2262 void HostResolverImpl::TryServingAllJobsFromHosts() {
2263 if (!HaveDnsConfig())
2266 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2267 // http://crbug.com/117655
2269 // Life check to bail once |this| is deleted.
2270 base::WeakPtr
<HostResolverImpl
> self
= weak_ptr_factory_
.GetWeakPtr();
2272 for (JobMap::iterator it
= jobs_
.begin(); self
.get() && it
!= jobs_
.end();) {
2273 Job
* job
= it
->second
;
2275 // This could remove |job| from |jobs_|, but iterator will remain valid.
2276 job
->ServeFromHosts();
2280 void HostResolverImpl::OnIPAddressChanged() {
2281 resolved_known_ipv6_hostname_
= false;
2282 // Abandon all ProbeJobs.
2283 probe_weak_ptr_factory_
.InvalidateWeakPtrs();
2286 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
2287 new LoopbackProbeJob(probe_weak_ptr_factory_
.GetWeakPtr());
2289 AbortAllInProgressJobs();
2290 // |this| may be deleted inside AbortAllInProgressJobs().
2293 void HostResolverImpl::OnInitialDNSConfigRead() {
2294 UpdateDNSConfig(false);
2297 void HostResolverImpl::OnDNSChanged() {
2298 UpdateDNSConfig(true);
2301 void HostResolverImpl::UpdateDNSConfig(bool config_changed
) {
2302 DnsConfig dns_config
;
2303 NetworkChangeNotifier::GetDnsConfig(&dns_config
);
2306 net_log_
->AddGlobalEntry(
2307 NetLog::TYPE_DNS_CONFIG_CHANGED
,
2308 base::Bind(&NetLogDnsConfigCallback
, &dns_config
));
2311 // TODO(szym): Remove once http://crbug.com/137914 is resolved.
2312 received_dns_config_
= dns_config
.IsValid();
2313 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
2314 use_local_ipv6_
= !dns_config
.IsValid() || dns_config
.use_local_ipv6
;
2316 num_dns_failures_
= 0;
2318 // We want a new DnsSession in place, before we Abort running Jobs, so that
2319 // the newly started jobs use the new config.
2320 if (dns_client_
.get()) {
2321 dns_client_
->SetConfig(dns_config
);
2322 if (dns_client_
->GetConfig()) {
2323 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
2324 // If we just switched DnsClients, restart jobs using new resolver.
2325 // TODO(pauljensen): Is this necessary?
2326 config_changed
= true;
2330 if (config_changed
) {
2331 // If the DNS server has changed, existing cached info could be wrong so we
2332 // have to drop our internal cache :( Note that OS level DNS caches, such
2333 // as NSCD's cache should be dropped automatically by the OS when
2334 // resolv.conf changes so we don't need to do anything to clear that cache.
2338 // Life check to bail once |this| is deleted.
2339 base::WeakPtr
<HostResolverImpl
> self
= weak_ptr_factory_
.GetWeakPtr();
2341 // Existing jobs will have been sent to the original server so they need to
2343 AbortAllInProgressJobs();
2345 // |this| may be deleted inside AbortAllInProgressJobs().
2347 TryServingAllJobsFromHosts();
2351 bool HostResolverImpl::HaveDnsConfig() const {
2352 // Use DnsClient only if it's fully configured and there is no override by
2353 // ScopedDefaultHostResolverProc.
2354 // The alternative is to use NetworkChangeNotifier to override DnsConfig,
2355 // but that would introduce construction order requirements for NCN and SDHRP.
2356 return (dns_client_
.get() != NULL
) && (dns_client_
->GetConfig() != NULL
) &&
2357 !(proc_params_
.resolver_proc
.get() == NULL
&&
2358 HostResolverProc::GetDefault() != NULL
);
2361 void HostResolverImpl::OnDnsTaskResolve(int net_error
) {
2362 DCHECK(dns_client_
);
2363 if (net_error
== OK
) {
2364 num_dns_failures_
= 0;
2367 ++num_dns_failures_
;
2368 if (num_dns_failures_
< kMaximumDnsFailures
)
2371 // Disable DnsClient until the next DNS change. Must be done before aborting
2372 // DnsTasks, since doing so may start new jobs.
2373 dns_client_
->SetConfig(DnsConfig());
2375 // Switch jobs with active DnsTasks over to using ProcTasks.
2378 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", false);
2379 UMA_HISTOGRAM_CUSTOM_ENUMERATION("AsyncDNS.DnsClientDisabledReason",
2380 std::abs(net_error
),
2381 GetAllErrorCodesForUma());
2384 void HostResolverImpl::SetDnsClient(scoped_ptr
<DnsClient
> dns_client
) {
2385 // DnsClient and config must be updated before aborting DnsTasks, since doing
2386 // so may start new jobs.
2387 dns_client_
= dns_client
.Pass();
2388 if (dns_client_
&& !dns_client_
->GetConfig() &&
2389 num_dns_failures_
< kMaximumDnsFailures
) {
2390 DnsConfig dns_config
;
2391 NetworkChangeNotifier::GetDnsConfig(&dns_config
);
2392 dns_client_
->SetConfig(dns_config
);
2393 num_dns_failures_
= 0;
2394 if (dns_client_
->GetConfig())
2395 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);