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/metrics/field_trial.h"
25 #include "base/metrics/histogram_macros.h"
26 #include "base/metrics/sparse_histogram.h"
27 #include "base/profiler/scoped_tracker.h"
28 #include "base/single_thread_task_runner.h"
29 #include "base/stl_util.h"
30 #include "base/strings/string_util.h"
31 #include "base/strings/utf_string_conversions.h"
32 #include "base/thread_task_runner_handle.h"
33 #include "base/threading/worker_pool.h"
34 #include "base/time/time.h"
35 #include "base/values.h"
36 #include "net/base/address_family.h"
37 #include "net/base/address_list.h"
38 #include "net/base/dns_reloader.h"
39 #include "net/base/dns_util.h"
40 #include "net/base/host_port_pair.h"
41 #include "net/base/ip_endpoint.h"
42 #include "net/base/net_errors.h"
43 #include "net/base/net_util.h"
44 #include "net/dns/address_sorter.h"
45 #include "net/dns/dns_client.h"
46 #include "net/dns/dns_config_service.h"
47 #include "net/dns/dns_protocol.h"
48 #include "net/dns/dns_response.h"
49 #include "net/dns/dns_transaction.h"
50 #include "net/dns/host_resolver_proc.h"
51 #include "net/log/net_log.h"
52 #include "net/socket/client_socket_factory.h"
53 #include "net/udp/datagram_client_socket.h"
54 #include "url/url_canon_ip.h"
57 #include "net/base/winsock_init.h"
64 // Limit the size of hostnames that will be resolved to combat issues in
65 // some platform's resolvers.
66 const size_t kMaxHostLength
= 4096;
68 // Default TTL for successful resolutions with ProcTask.
69 const unsigned kCacheEntryTTLSeconds
= 60;
71 // Default TTL for unsuccessful resolutions with ProcTask.
72 const unsigned kNegativeCacheEntryTTLSeconds
= 0;
74 // Minimum TTL for successful resolutions with DnsTask.
75 const unsigned kMinimumTTLSeconds
= kCacheEntryTTLSeconds
;
77 const char kLocalhost
[] = "localhost.";
79 // Time between IPv6 probes, i.e. for how long results of each IPv6 probe are
81 const int kIPv6ProbePeriodMs
= 1000;
83 // Google DNS address used for IPv6 probes.
84 const uint8_t kIPv6ProbeAddress
[] =
85 { 0x20, 0x01, 0x48, 0x60, 0x48, 0x60, 0x00, 0x00,
86 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x88 };
88 // We use a separate histogram name for each platform to facilitate the
89 // display of error codes by their symbolic name (since each platform has
90 // different mappings).
91 const char kOSErrorsForGetAddrinfoHistogramName
[] =
93 "Net.OSErrorsForGetAddrinfo_Win";
94 #elif defined(OS_MACOSX)
95 "Net.OSErrorsForGetAddrinfo_Mac";
96 #elif defined(OS_LINUX)
97 "Net.OSErrorsForGetAddrinfo_Linux";
99 "Net.OSErrorsForGetAddrinfo";
102 // Gets a list of the likely error codes that getaddrinfo() can return
103 // (non-exhaustive). These are the error codes that we will track via
105 std::vector
<int> GetAllGetAddrinfoOSErrors() {
107 #if defined(OS_POSIX)
108 #if !defined(OS_FREEBSD)
109 #if !defined(OS_ANDROID)
110 // EAI_ADDRFAMILY has been declared obsolete in Android's and
111 // FreeBSD's netdb.h.
114 // EAI_NODATA has been declared obsolete in FreeBSD's netdb.h.
126 #elif defined(OS_WIN)
127 // See: http://msdn.microsoft.com/en-us/library/ms738520(VS.85).aspx
128 WSA_NOT_ENOUGH_MEMORY
,
138 // The following are not in doc, but might be to appearing in results :-(.
143 // Ensure all errors are positive, as histogram only tracks positive values.
144 for (size_t i
= 0; i
< arraysize(os_errors
); ++i
) {
145 os_errors
[i
] = std::abs(os_errors
[i
]);
148 return base::CustomHistogram::ArrayToCustomRanges(os_errors
,
149 arraysize(os_errors
));
152 enum DnsResolveStatus
{
153 RESOLVE_STATUS_DNS_SUCCESS
= 0,
154 RESOLVE_STATUS_PROC_SUCCESS
,
156 RESOLVE_STATUS_SUSPECT_NETBIOS
,
160 // ICANN uses this localhost address to indicate a name collision.
162 // The policy in Chromium is to fail host resolving if it resolves to
163 // this special address.
165 // Not however that IP literals are exempt from this policy, so it is still
166 // possible to navigate to http://127.0.53.53/ directly.
168 // For more details: https://www.icann.org/news/announcement-2-2014-08-01-en
169 const unsigned char kIcanNameCollisionIp
[] = {127, 0, 53, 53};
171 void UmaAsyncDnsResolveStatus(DnsResolveStatus result
) {
172 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ResolveStatus",
177 bool ResemblesNetBIOSName(const std::string
& hostname
) {
178 return (hostname
.size() < 16) && (hostname
.find('.') == std::string::npos
);
181 // True if |hostname| ends with either ".local" or ".local.".
182 bool ResemblesMulticastDNSName(const std::string
& hostname
) {
183 DCHECK(!hostname
.empty());
184 const char kSuffix
[] = ".local.";
185 const size_t kSuffixLen
= sizeof(kSuffix
) - 1;
186 const size_t kSuffixLenTrimmed
= kSuffixLen
- 1;
187 if (hostname
[hostname
.size() - 1] == '.') {
188 return hostname
.size() > kSuffixLen
&&
189 !hostname
.compare(hostname
.size() - kSuffixLen
, kSuffixLen
, kSuffix
);
191 return hostname
.size() > kSuffixLenTrimmed
&&
192 !hostname
.compare(hostname
.size() - kSuffixLenTrimmed
, kSuffixLenTrimmed
,
193 kSuffix
, kSuffixLenTrimmed
);
196 // Attempts to connect a UDP socket to |dest|:53.
197 bool IsGloballyReachable(const IPAddressNumber
& dest
,
198 const BoundNetLog
& net_log
) {
199 // TODO(eroman): Remove ScopedTracker below once crbug.com/455942 is fixed.
200 tracked_objects::ScopedTracker
tracking_profile_1(
201 FROM_HERE_WITH_EXPLICIT_FUNCTION("455942 IsGloballyReachable"));
203 scoped_ptr
<DatagramClientSocket
> socket(
204 ClientSocketFactory::GetDefaultFactory()->CreateDatagramClientSocket(
205 DatagramSocket::DEFAULT_BIND
,
209 int rv
= socket
->Connect(IPEndPoint(dest
, 53));
213 rv
= socket
->GetLocalAddress(&endpoint
);
216 DCHECK_EQ(ADDRESS_FAMILY_IPV6
, endpoint
.GetFamily());
217 const IPAddressNumber
& address
= endpoint
.address();
218 bool is_link_local
= (address
[0] == 0xFE) && ((address
[1] & 0xC0) == 0x80);
221 const uint8 kTeredoPrefix
[] = { 0x20, 0x01, 0, 0 };
222 bool is_teredo
= std::equal(kTeredoPrefix
,
223 kTeredoPrefix
+ arraysize(kTeredoPrefix
),
230 // Provide a common macro to simplify code and readability. We must use a
231 // macro as the underlying HISTOGRAM macro creates static variables.
232 #define DNS_HISTOGRAM(name, time) UMA_HISTOGRAM_CUSTOM_TIMES(name, time, \
233 base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromHours(1), 100)
235 // A macro to simplify code and readability.
236 #define DNS_HISTOGRAM_BY_PRIORITY(basename, priority, time) \
238 switch (priority) { \
239 case HIGHEST: DNS_HISTOGRAM(basename "_HIGHEST", time); break; \
240 case MEDIUM: DNS_HISTOGRAM(basename "_MEDIUM", time); break; \
241 case LOW: DNS_HISTOGRAM(basename "_LOW", time); break; \
242 case LOWEST: DNS_HISTOGRAM(basename "_LOWEST", time); break; \
243 case IDLE: DNS_HISTOGRAM(basename "_IDLE", time); break; \
244 default: NOTREACHED(); break; \
246 DNS_HISTOGRAM(basename, time); \
249 // Record time from Request creation until a valid DNS response.
250 void RecordTotalTime(bool had_dns_config
,
252 base::TimeDelta duration
) {
253 if (had_dns_config
) {
255 DNS_HISTOGRAM("AsyncDNS.TotalTime_speculative", duration
);
257 DNS_HISTOGRAM("AsyncDNS.TotalTime", duration
);
261 DNS_HISTOGRAM("DNS.TotalTime_speculative", duration
);
263 DNS_HISTOGRAM("DNS.TotalTime", duration
);
268 void RecordTTL(base::TimeDelta ttl
) {
269 UMA_HISTOGRAM_CUSTOM_TIMES("AsyncDNS.TTL", ttl
,
270 base::TimeDelta::FromSeconds(1),
271 base::TimeDelta::FromDays(1), 100);
274 bool ConfigureAsyncDnsNoFallbackFieldTrial() {
275 const bool kDefault
= false;
277 // Configure the AsyncDns field trial as follows:
278 // groups AsyncDnsNoFallbackA and AsyncDnsNoFallbackB: return true,
279 // groups AsyncDnsA and AsyncDnsB: return false,
280 // groups SystemDnsA and SystemDnsB: return false,
281 // otherwise (trial absent): return default.
282 std::string group_name
= base::FieldTrialList::FindFullName("AsyncDns");
283 if (!group_name
.empty())
284 return base::StartsWithASCII(group_name
, "AsyncDnsNoFallback", false);
288 //-----------------------------------------------------------------------------
290 AddressList
EnsurePortOnAddressList(const AddressList
& list
, uint16 port
) {
291 if (list
.empty() || list
.front().port() == port
)
293 return AddressList::CopyWithPort(list
, port
);
296 // Returns true if |addresses| contains only IPv4 loopback addresses.
297 bool IsAllIPv4Loopback(const AddressList
& addresses
) {
298 for (unsigned i
= 0; i
< addresses
.size(); ++i
) {
299 const IPAddressNumber
& address
= addresses
[i
].address();
300 switch (addresses
[i
].GetFamily()) {
301 case ADDRESS_FAMILY_IPV4
:
302 if (address
[0] != 127)
305 case ADDRESS_FAMILY_IPV6
:
315 // Creates NetLog parameters when the resolve failed.
316 scoped_ptr
<base::Value
> NetLogProcTaskFailedCallback(
317 uint32 attempt_number
,
320 NetLogCaptureMode
/* capture_mode */) {
321 scoped_ptr
<base::DictionaryValue
> dict(new base::DictionaryValue());
323 dict
->SetInteger("attempt_number", attempt_number
);
325 dict
->SetInteger("net_error", net_error
);
328 dict
->SetInteger("os_error", os_error
);
329 #if defined(OS_POSIX)
330 dict
->SetString("os_error_string", gai_strerror(os_error
));
331 #elif defined(OS_WIN)
332 // Map the error code to a human-readable string.
333 LPWSTR error_string
= NULL
;
334 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
335 0, // Use the internal message table.
337 0, // Use default language.
338 (LPWSTR
)&error_string
,
340 0); // Arguments (unused).
341 dict
->SetString("os_error_string", base::WideToUTF8(error_string
));
342 LocalFree(error_string
);
349 // Creates NetLog parameters when the DnsTask failed.
350 scoped_ptr
<base::Value
> NetLogDnsTaskFailedCallback(
353 NetLogCaptureMode
/* capture_mode */) {
354 scoped_ptr
<base::DictionaryValue
> dict(new base::DictionaryValue());
355 dict
->SetInteger("net_error", net_error
);
357 dict
->SetInteger("dns_error", dns_error
);
361 // Creates NetLog parameters containing the information in a RequestInfo object,
362 // along with the associated NetLog::Source.
363 scoped_ptr
<base::Value
> NetLogRequestInfoCallback(
364 const HostResolver::RequestInfo
* info
,
365 NetLogCaptureMode
/* capture_mode */) {
366 scoped_ptr
<base::DictionaryValue
> dict(new base::DictionaryValue());
368 dict
->SetString("host", info
->host_port_pair().ToString());
369 dict
->SetInteger("address_family",
370 static_cast<int>(info
->address_family()));
371 dict
->SetBoolean("allow_cached_response", info
->allow_cached_response());
372 dict
->SetBoolean("is_speculative", info
->is_speculative());
376 // Creates NetLog parameters for the creation of a HostResolverImpl::Job.
377 scoped_ptr
<base::Value
> NetLogJobCreationCallback(
378 const NetLog::Source
& source
,
379 const std::string
* host
,
380 NetLogCaptureMode
/* capture_mode */) {
381 scoped_ptr
<base::DictionaryValue
> dict(new base::DictionaryValue());
382 source
.AddToEventParameters(dict
.get());
383 dict
->SetString("host", *host
);
387 // Creates NetLog parameters for HOST_RESOLVER_IMPL_JOB_ATTACH/DETACH events.
388 scoped_ptr
<base::Value
> NetLogJobAttachCallback(
389 const NetLog::Source
& source
,
390 RequestPriority priority
,
391 NetLogCaptureMode
/* capture_mode */) {
392 scoped_ptr
<base::DictionaryValue
> dict(new base::DictionaryValue());
393 source
.AddToEventParameters(dict
.get());
394 dict
->SetString("priority", RequestPriorityToString(priority
));
398 // Creates NetLog parameters for the DNS_CONFIG_CHANGED event.
399 scoped_ptr
<base::Value
> NetLogDnsConfigCallback(
400 const DnsConfig
* config
,
401 NetLogCaptureMode
/* capture_mode */) {
402 return make_scoped_ptr(config
->ToValue());
405 scoped_ptr
<base::Value
> NetLogIPv6AvailableCallback(
408 NetLogCaptureMode
/* capture_mode */) {
409 scoped_ptr
<base::DictionaryValue
> dict(new base::DictionaryValue());
410 dict
->SetBoolean("ipv6_available", ipv6_available
);
411 dict
->SetBoolean("cached", cached
);
415 // The logging routines are defined here because some requests are resolved
416 // without a Request object.
418 // Logs when a request has just been started.
419 void LogStartRequest(const BoundNetLog
& source_net_log
,
420 const HostResolver::RequestInfo
& info
) {
421 source_net_log
.BeginEvent(
422 NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST
,
423 base::Bind(&NetLogRequestInfoCallback
, &info
));
426 // Logs when a request has just completed (before its callback is run).
427 void LogFinishRequest(const BoundNetLog
& source_net_log
,
428 const HostResolver::RequestInfo
& info
,
430 source_net_log
.EndEventWithNetErrorCode(
431 NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST
, net_error
);
434 // Logs when a request has been cancelled.
435 void LogCancelRequest(const BoundNetLog
& source_net_log
,
436 const HostResolverImpl::RequestInfo
& info
) {
437 source_net_log
.AddEvent(NetLog::TYPE_CANCELLED
);
438 source_net_log
.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST
);
441 //-----------------------------------------------------------------------------
443 // Keeps track of the highest priority.
444 class PriorityTracker
{
446 explicit PriorityTracker(RequestPriority initial_priority
)
447 : highest_priority_(initial_priority
), total_count_(0) {
448 memset(counts_
, 0, sizeof(counts_
));
451 RequestPriority
highest_priority() const {
452 return highest_priority_
;
455 size_t total_count() const {
459 void Add(RequestPriority req_priority
) {
461 ++counts_
[req_priority
];
462 if (highest_priority_
< req_priority
)
463 highest_priority_
= req_priority
;
466 void Remove(RequestPriority req_priority
) {
467 DCHECK_GT(total_count_
, 0u);
468 DCHECK_GT(counts_
[req_priority
], 0u);
470 --counts_
[req_priority
];
472 for (i
= highest_priority_
; i
> MINIMUM_PRIORITY
&& !counts_
[i
]; --i
);
473 highest_priority_
= static_cast<RequestPriority
>(i
);
475 // In absence of requests, default to MINIMUM_PRIORITY.
476 if (total_count_
== 0)
477 DCHECK_EQ(MINIMUM_PRIORITY
, highest_priority_
);
481 RequestPriority highest_priority_
;
483 size_t counts_
[NUM_PRIORITIES
];
488 //-----------------------------------------------------------------------------
490 const unsigned HostResolverImpl::kMaximumDnsFailures
= 16;
492 // Holds the data for a request that could not be completed synchronously.
493 // It is owned by a Job. Canceled Requests are only marked as canceled rather
494 // than removed from the Job's |requests_| list.
495 class HostResolverImpl::Request
{
497 Request(const BoundNetLog
& source_net_log
,
498 const RequestInfo
& info
,
499 RequestPriority priority
,
500 const CompletionCallback
& callback
,
501 AddressList
* addresses
)
502 : source_net_log_(source_net_log
),
507 addresses_(addresses
),
508 request_time_(base::TimeTicks::Now()) {}
510 // Mark the request as canceled.
511 void MarkAsCanceled() {
517 bool was_canceled() const {
518 return callback_
.is_null();
521 void set_job(Job
* job
) {
523 // Identify which job the request is waiting on.
527 // Prepare final AddressList and call completion callback.
528 void OnComplete(int error
, const AddressList
& addr_list
) {
529 DCHECK(!was_canceled());
531 *addresses_
= EnsurePortOnAddressList(addr_list
, info_
.port());
532 CompletionCallback callback
= callback_
;
541 // NetLog for the source, passed in HostResolver::Resolve.
542 const BoundNetLog
& source_net_log() {
543 return source_net_log_
;
546 const RequestInfo
& info() const {
550 RequestPriority
priority() const { return priority_
; }
552 base::TimeTicks
request_time() const { return request_time_
; }
555 const BoundNetLog source_net_log_
;
557 // The request info that started the request.
558 const RequestInfo info_
;
560 // TODO(akalin): Support reprioritization.
561 const RequestPriority priority_
;
563 // The resolve job that this request is dependent on.
566 // The user's callback to invoke when the request completes.
567 CompletionCallback callback_
;
569 // The address list to save result into.
570 AddressList
* addresses_
;
572 const base::TimeTicks request_time_
;
574 DISALLOW_COPY_AND_ASSIGN(Request
);
577 //------------------------------------------------------------------------------
579 // Calls HostResolverProc on the WorkerPool. Performs retries if necessary.
581 // Whenever we try to resolve the host, we post a delayed task to check if host
582 // resolution (OnLookupComplete) is completed or not. If the original attempt
583 // hasn't completed, then we start another attempt for host resolution. We take
584 // the results from the first attempt that finishes and ignore the results from
585 // all other attempts.
587 // TODO(szym): Move to separate source file for testing and mocking.
589 class HostResolverImpl::ProcTask
590 : public base::RefCountedThreadSafe
<HostResolverImpl::ProcTask
> {
592 typedef base::Callback
<void(int net_error
,
593 const AddressList
& addr_list
)> Callback
;
595 ProcTask(const Key
& key
,
596 const ProcTaskParams
& params
,
597 const Callback
& callback
,
598 const BoundNetLog
& job_net_log
)
602 task_runner_(base::ThreadTaskRunnerHandle::Get()),
604 completed_attempt_number_(0),
605 completed_attempt_error_(ERR_UNEXPECTED
),
606 had_non_speculative_request_(false),
607 net_log_(job_net_log
) {
608 if (!params_
.resolver_proc
.get())
609 params_
.resolver_proc
= HostResolverProc::GetDefault();
610 // If default is unset, use the system proc.
611 if (!params_
.resolver_proc
.get())
612 params_
.resolver_proc
= new SystemHostResolverProc();
616 DCHECK(task_runner_
->BelongsToCurrentThread());
617 net_log_
.BeginEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK
);
618 StartLookupAttempt();
621 // Cancels this ProcTask. It will be orphaned. Any outstanding resolve
622 // attempts running on worker threads will continue running. Only once all the
623 // attempts complete will the final reference to this ProcTask be released.
625 DCHECK(task_runner_
->BelongsToCurrentThread());
627 if (was_canceled() || was_completed())
631 net_log_
.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK
);
634 void set_had_non_speculative_request() {
635 DCHECK(task_runner_
->BelongsToCurrentThread());
636 had_non_speculative_request_
= true;
639 bool was_canceled() const {
640 DCHECK(task_runner_
->BelongsToCurrentThread());
641 return callback_
.is_null();
644 bool was_completed() const {
645 DCHECK(task_runner_
->BelongsToCurrentThread());
646 return completed_attempt_number_
> 0;
650 friend class base::RefCountedThreadSafe
<ProcTask
>;
653 void StartLookupAttempt() {
654 DCHECK(task_runner_
->BelongsToCurrentThread());
655 base::TimeTicks start_time
= base::TimeTicks::Now();
657 // Dispatch the lookup attempt to a worker thread.
658 if (!base::WorkerPool::PostTask(
660 base::Bind(&ProcTask::DoLookup
, this, start_time
, attempt_number_
),
664 // Since we could be running within Resolve() right now, we can't just
665 // call OnLookupComplete(). Instead we must wait until Resolve() has
666 // returned (IO_PENDING).
667 task_runner_
->PostTask(FROM_HERE
,
668 base::Bind(&ProcTask::OnLookupComplete
,
679 NetLog::TYPE_HOST_RESOLVER_IMPL_ATTEMPT_STARTED
,
680 NetLog::IntegerCallback("attempt_number", attempt_number_
));
682 // If we don't get the results within a given time, RetryIfNotComplete
683 // will start a new attempt on a different worker thread if none of our
684 // outstanding attempts have completed yet.
685 if (attempt_number_
<= params_
.max_retry_attempts
) {
686 task_runner_
->PostDelayedTask(
688 base::Bind(&ProcTask::RetryIfNotComplete
, this),
689 params_
.unresponsive_delay
);
693 // WARNING: This code runs inside a worker pool. The shutdown code cannot
694 // wait for it to finish, so we must be very careful here about using other
695 // objects (like MessageLoops, Singletons, etc). During shutdown these objects
696 // may no longer exist. Multiple DoLookups() could be running in parallel, so
697 // any state inside of |this| must not mutate .
698 void DoLookup(const base::TimeTicks
& start_time
,
699 const uint32 attempt_number
) {
702 // Running on the worker thread
703 int error
= params_
.resolver_proc
->Resolve(key_
.hostname
,
705 key_
.host_resolver_flags
,
709 // Fail the resolution if the result contains 127.0.53.53. See the comment
710 // block of kIcanNameCollisionIp for details on why.
711 for (const auto& it
: results
) {
712 const IPAddressNumber
& cur
= it
.address();
713 if (cur
.size() == arraysize(kIcanNameCollisionIp
) &&
714 0 == memcmp(&cur
.front(), kIcanNameCollisionIp
, cur
.size())) {
715 error
= ERR_ICANN_NAME_COLLISION
;
720 task_runner_
->PostTask(FROM_HERE
,
721 base::Bind(&ProcTask::OnLookupComplete
,
730 // Makes next attempt if DoLookup() has not finished (runs on task runner
732 void RetryIfNotComplete() {
733 DCHECK(task_runner_
->BelongsToCurrentThread());
735 if (was_completed() || was_canceled())
738 params_
.unresponsive_delay
*= params_
.retry_factor
;
739 StartLookupAttempt();
742 // Callback for when DoLookup() completes (runs on task runner thread).
743 void OnLookupComplete(const AddressList
& results
,
744 const base::TimeTicks
& start_time
,
745 const uint32 attempt_number
,
747 const int os_error
) {
748 DCHECK(task_runner_
->BelongsToCurrentThread());
749 // If results are empty, we should return an error.
750 bool empty_list_on_ok
= (error
== OK
&& results
.empty());
751 UMA_HISTOGRAM_BOOLEAN("DNS.EmptyAddressListAndNoError", empty_list_on_ok
);
752 if (empty_list_on_ok
)
753 error
= ERR_NAME_NOT_RESOLVED
;
755 bool was_retry_attempt
= attempt_number
> 1;
757 // Ideally the following code would be part of host_resolver_proc.cc,
758 // however it isn't safe to call NetworkChangeNotifier from worker threads.
759 // So we do it here on the IO thread instead.
760 if (error
!= OK
&& NetworkChangeNotifier::IsOffline())
761 error
= ERR_INTERNET_DISCONNECTED
;
763 // If this is the first attempt that is finishing later, then record data
764 // for the first attempt. Won't contaminate with retry attempt's data.
765 if (!was_retry_attempt
)
766 RecordPerformanceHistograms(start_time
, error
, os_error
);
768 RecordAttemptHistograms(start_time
, attempt_number
, error
, os_error
);
773 NetLog::ParametersCallback net_log_callback
;
775 net_log_callback
= base::Bind(&NetLogProcTaskFailedCallback
,
780 net_log_callback
= NetLog::IntegerCallback("attempt_number",
783 net_log_
.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_ATTEMPT_FINISHED
,
789 // Copy the results from the first worker thread that resolves the host.
791 completed_attempt_number_
= attempt_number
;
792 completed_attempt_error_
= error
;
794 if (was_retry_attempt
) {
795 // If retry attempt finishes before 1st attempt, then get stats on how
796 // much time is saved by having spawned an extra attempt.
797 retry_attempt_finished_time_
= base::TimeTicks::Now();
801 net_log_callback
= base::Bind(&NetLogProcTaskFailedCallback
,
804 net_log_callback
= results_
.CreateNetLogCallback();
806 net_log_
.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK
,
809 callback_
.Run(error
, results_
);
812 void RecordPerformanceHistograms(const base::TimeTicks
& start_time
,
814 const int os_error
) const {
815 DCHECK(task_runner_
->BelongsToCurrentThread());
816 enum Category
{ // Used in UMA_HISTOGRAM_ENUMERATION.
819 RESOLVE_SPECULATIVE_SUCCESS
,
820 RESOLVE_SPECULATIVE_FAIL
,
821 RESOLVE_MAX
, // Bounding value.
823 int category
= RESOLVE_MAX
; // Illegal value for later DCHECK only.
825 base::TimeDelta duration
= base::TimeTicks::Now() - start_time
;
827 if (had_non_speculative_request_
) {
828 category
= RESOLVE_SUCCESS
;
829 DNS_HISTOGRAM("DNS.ResolveSuccess", duration
);
831 category
= RESOLVE_SPECULATIVE_SUCCESS
;
832 DNS_HISTOGRAM("DNS.ResolveSpeculativeSuccess", duration
);
835 // Log DNS lookups based on |address_family|. This will help us determine
836 // if IPv4 or IPv4/6 lookups are faster or slower.
837 switch(key_
.address_family
) {
838 case ADDRESS_FAMILY_IPV4
:
839 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_IPV4", duration
);
841 case ADDRESS_FAMILY_IPV6
:
842 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_IPV6", duration
);
844 case ADDRESS_FAMILY_UNSPECIFIED
:
845 DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_UNSPEC", duration
);
849 if (had_non_speculative_request_
) {
850 category
= RESOLVE_FAIL
;
851 DNS_HISTOGRAM("DNS.ResolveFail", duration
);
853 category
= RESOLVE_SPECULATIVE_FAIL
;
854 DNS_HISTOGRAM("DNS.ResolveSpeculativeFail", duration
);
856 // Log DNS lookups based on |address_family|. This will help us determine
857 // if IPv4 or IPv4/6 lookups are faster or slower.
858 switch(key_
.address_family
) {
859 case ADDRESS_FAMILY_IPV4
:
860 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_IPV4", duration
);
862 case ADDRESS_FAMILY_IPV6
:
863 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_IPV6", duration
);
865 case ADDRESS_FAMILY_UNSPECIFIED
:
866 DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_UNSPEC", duration
);
869 UMA_HISTOGRAM_CUSTOM_ENUMERATION(kOSErrorsForGetAddrinfoHistogramName
,
871 GetAllGetAddrinfoOSErrors());
873 DCHECK_LT(category
, static_cast<int>(RESOLVE_MAX
)); // Be sure it was set.
875 UMA_HISTOGRAM_ENUMERATION("DNS.ResolveCategory", category
, RESOLVE_MAX
);
878 void RecordAttemptHistograms(const base::TimeTicks
& start_time
,
879 const uint32 attempt_number
,
881 const int os_error
) const {
882 DCHECK(task_runner_
->BelongsToCurrentThread());
883 bool first_attempt_to_complete
=
884 completed_attempt_number_
== attempt_number
;
885 bool is_first_attempt
= (attempt_number
== 1);
887 if (first_attempt_to_complete
) {
888 // If this was first attempt to complete, then record the resolution
889 // status of the attempt.
890 if (completed_attempt_error_
== OK
) {
891 UMA_HISTOGRAM_ENUMERATION(
892 "DNS.AttemptFirstSuccess", attempt_number
, 100);
894 UMA_HISTOGRAM_ENUMERATION(
895 "DNS.AttemptFirstFailure", attempt_number
, 100);
900 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptSuccess", attempt_number
, 100);
902 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptFailure", attempt_number
, 100);
904 // If first attempt didn't finish before retry attempt, then calculate stats
905 // on how much time is saved by having spawned an extra attempt.
906 if (!first_attempt_to_complete
&& is_first_attempt
&& !was_canceled()) {
907 DNS_HISTOGRAM("DNS.AttemptTimeSavedByRetry",
908 base::TimeTicks::Now() - retry_attempt_finished_time_
);
911 if (was_canceled() || !first_attempt_to_complete
) {
912 // Count those attempts which completed after the job was already canceled
913 // OR after the job was already completed by an earlier attempt (so in
915 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptDiscarded", attempt_number
, 100);
917 // Record if job is canceled.
919 UMA_HISTOGRAM_ENUMERATION("DNS.AttemptCancelled", attempt_number
, 100);
922 base::TimeDelta duration
= base::TimeTicks::Now() - start_time
;
924 DNS_HISTOGRAM("DNS.AttemptSuccessDuration", duration
);
926 DNS_HISTOGRAM("DNS.AttemptFailDuration", duration
);
929 // Set on the task runner thread, read on the worker thread.
932 // Holds an owning reference to the HostResolverProc that we are going to use.
933 // This may not be the current resolver procedure by the time we call
934 // ResolveAddrInfo, but that's OK... we'll use it anyways, and the owning
935 // reference ensures that it remains valid until we are done.
936 ProcTaskParams params_
;
938 // The listener to the results of this ProcTask.
941 // Used to post ourselves onto the task runner thread.
942 scoped_refptr
<base::SingleThreadTaskRunner
> task_runner_
;
944 // Keeps track of the number of attempts we have made so far to resolve the
945 // host. Whenever we start an attempt to resolve the host, we increase this
947 uint32 attempt_number_
;
949 // The index of the attempt which finished first (or 0 if the job is still in
951 uint32 completed_attempt_number_
;
953 // The result (a net error code) from the first attempt to complete.
954 int completed_attempt_error_
;
956 // The time when retry attempt was finished.
957 base::TimeTicks retry_attempt_finished_time_
;
959 // True if a non-speculative request was ever attached to this job
960 // (regardless of whether or not it was later canceled.
961 // This boolean is used for histogramming the duration of jobs used to
962 // service non-speculative requests.
963 bool had_non_speculative_request_
;
965 AddressList results_
;
967 BoundNetLog net_log_
;
969 DISALLOW_COPY_AND_ASSIGN(ProcTask
);
972 //-----------------------------------------------------------------------------
974 // Wraps a call to HaveOnlyLoopbackAddresses to be executed on the WorkerPool as
975 // it takes 40-100ms and should not block initialization.
976 class HostResolverImpl::LoopbackProbeJob
{
978 explicit LoopbackProbeJob(const base::WeakPtr
<HostResolverImpl
>& resolver
)
979 : resolver_(resolver
),
981 DCHECK(resolver
.get());
982 const bool kIsSlow
= true;
983 base::WorkerPool::PostTaskAndReply(
985 base::Bind(&LoopbackProbeJob::DoProbe
, base::Unretained(this)),
986 base::Bind(&LoopbackProbeJob::OnProbeComplete
, base::Owned(this)),
990 virtual ~LoopbackProbeJob() {}
993 // Runs on worker thread.
995 result_
= HaveOnlyLoopbackAddresses();
998 void OnProbeComplete() {
999 if (!resolver_
.get())
1001 resolver_
->SetHaveOnlyLoopbackAddresses(result_
);
1004 // Used/set only on task runner thread.
1005 base::WeakPtr
<HostResolverImpl
> resolver_
;
1009 DISALLOW_COPY_AND_ASSIGN(LoopbackProbeJob
);
1012 //-----------------------------------------------------------------------------
1014 // Resolves the hostname using DnsTransaction.
1015 // TODO(szym): This could be moved to separate source file as well.
1016 class HostResolverImpl::DnsTask
: public base::SupportsWeakPtr
<DnsTask
> {
1020 virtual void OnDnsTaskComplete(base::TimeTicks start_time
,
1022 const AddressList
& addr_list
,
1023 base::TimeDelta ttl
) = 0;
1025 // Called when the first of two jobs succeeds. If the first completed
1026 // transaction fails, this is not called. Also not called when the DnsTask
1027 // only needs to run one transaction.
1028 virtual void OnFirstDnsTransactionComplete() = 0;
1032 virtual ~Delegate() {}
1035 DnsTask(DnsClient
* client
,
1038 const BoundNetLog
& job_net_log
)
1041 delegate_(delegate
),
1042 net_log_(job_net_log
),
1043 num_completed_transactions_(0),
1044 task_start_time_(base::TimeTicks::Now()) {
1049 bool needs_two_transactions() const {
1050 return key_
.address_family
== ADDRESS_FAMILY_UNSPECIFIED
;
1053 bool needs_another_transaction() const {
1054 return needs_two_transactions() && !transaction_aaaa_
;
1057 void StartFirstTransaction() {
1058 DCHECK_EQ(0u, num_completed_transactions_
);
1059 net_log_
.BeginEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK
);
1060 if (key_
.address_family
== ADDRESS_FAMILY_IPV6
) {
1067 void StartSecondTransaction() {
1068 DCHECK(needs_two_transactions());
1074 DCHECK(!transaction_a_
);
1075 DCHECK_NE(ADDRESS_FAMILY_IPV6
, key_
.address_family
);
1076 transaction_a_
= CreateTransaction(ADDRESS_FAMILY_IPV4
);
1077 transaction_a_
->Start();
1081 DCHECK(!transaction_aaaa_
);
1082 DCHECK_NE(ADDRESS_FAMILY_IPV4
, key_
.address_family
);
1083 transaction_aaaa_
= CreateTransaction(ADDRESS_FAMILY_IPV6
);
1084 transaction_aaaa_
->Start();
1087 scoped_ptr
<DnsTransaction
> CreateTransaction(AddressFamily family
) {
1088 DCHECK_NE(ADDRESS_FAMILY_UNSPECIFIED
, family
);
1089 return client_
->GetTransactionFactory()->CreateTransaction(
1091 family
== ADDRESS_FAMILY_IPV6
? dns_protocol::kTypeAAAA
:
1092 dns_protocol::kTypeA
,
1093 base::Bind(&DnsTask::OnTransactionComplete
, base::Unretained(this),
1094 base::TimeTicks::Now()),
1098 void OnTransactionComplete(const base::TimeTicks
& start_time
,
1099 DnsTransaction
* transaction
,
1101 const DnsResponse
* response
) {
1102 DCHECK(transaction
);
1103 base::TimeDelta duration
= base::TimeTicks::Now() - start_time
;
1104 if (net_error
!= OK
) {
1105 DNS_HISTOGRAM("AsyncDNS.TransactionFailure", duration
);
1106 OnFailure(net_error
, DnsResponse::DNS_PARSE_OK
);
1110 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess", duration
);
1111 switch (transaction
->GetType()) {
1112 case dns_protocol::kTypeA
:
1113 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess_A", duration
);
1115 case dns_protocol::kTypeAAAA
:
1116 DNS_HISTOGRAM("AsyncDNS.TransactionSuccess_AAAA", duration
);
1120 AddressList addr_list
;
1121 base::TimeDelta ttl
;
1122 DnsResponse::Result result
= response
->ParseToAddressList(&addr_list
, &ttl
);
1123 UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ParseToAddressList",
1125 DnsResponse::DNS_PARSE_RESULT_MAX
);
1126 if (result
!= DnsResponse::DNS_PARSE_OK
) {
1127 // Fail even if the other query succeeds.
1128 OnFailure(ERR_DNS_MALFORMED_RESPONSE
, result
);
1132 ++num_completed_transactions_
;
1133 if (num_completed_transactions_
== 1) {
1136 ttl_
= std::min(ttl_
, ttl
);
1139 if (transaction
->GetType() == dns_protocol::kTypeA
) {
1140 DCHECK_EQ(transaction_a_
.get(), transaction
);
1141 // Place IPv4 addresses after IPv6.
1142 addr_list_
.insert(addr_list_
.end(), addr_list
.begin(), addr_list
.end());
1144 DCHECK_EQ(transaction_aaaa_
.get(), transaction
);
1145 // Place IPv6 addresses before IPv4.
1146 addr_list_
.insert(addr_list_
.begin(), addr_list
.begin(), addr_list
.end());
1149 if (needs_two_transactions() && num_completed_transactions_
== 1) {
1150 // No need to repeat the suffix search.
1151 key_
.hostname
= transaction
->GetHostname();
1152 delegate_
->OnFirstDnsTransactionComplete();
1156 if (addr_list_
.empty()) {
1157 // TODO(szym): Don't fallback to ProcTask in this case.
1158 OnFailure(ERR_NAME_NOT_RESOLVED
, DnsResponse::DNS_PARSE_OK
);
1162 // If there are multiple addresses, and at least one is IPv6, need to sort
1163 // them. Note that IPv6 addresses are always put before IPv4 ones, so it's
1164 // sufficient to just check the family of the first address.
1165 if (addr_list_
.size() > 1 &&
1166 addr_list_
[0].GetFamily() == ADDRESS_FAMILY_IPV6
) {
1167 // Sort addresses if needed. Sort could complete synchronously.
1168 client_
->GetAddressSorter()->Sort(
1170 base::Bind(&DnsTask::OnSortComplete
,
1172 base::TimeTicks::Now()));
1174 OnSuccess(addr_list_
);
1178 void OnSortComplete(base::TimeTicks start_time
,
1180 const AddressList
& addr_list
) {
1182 DNS_HISTOGRAM("AsyncDNS.SortFailure",
1183 base::TimeTicks::Now() - start_time
);
1184 OnFailure(ERR_DNS_SORT_ERROR
, DnsResponse::DNS_PARSE_OK
);
1188 DNS_HISTOGRAM("AsyncDNS.SortSuccess",
1189 base::TimeTicks::Now() - start_time
);
1191 // AddressSorter prunes unusable destinations.
1192 if (addr_list
.empty()) {
1193 LOG(WARNING
) << "Address list empty after RFC3484 sort";
1194 OnFailure(ERR_NAME_NOT_RESOLVED
, DnsResponse::DNS_PARSE_OK
);
1198 OnSuccess(addr_list
);
1201 void OnFailure(int net_error
, DnsResponse::Result result
) {
1202 DCHECK_NE(OK
, net_error
);
1204 NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK
,
1205 base::Bind(&NetLogDnsTaskFailedCallback
, net_error
, result
));
1206 delegate_
->OnDnsTaskComplete(task_start_time_
, net_error
, AddressList(),
1210 void OnSuccess(const AddressList
& addr_list
) {
1211 net_log_
.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK
,
1212 addr_list
.CreateNetLogCallback());
1213 delegate_
->OnDnsTaskComplete(task_start_time_
, OK
, addr_list
, ttl_
);
1219 // The listener to the results of this DnsTask.
1220 Delegate
* delegate_
;
1221 const BoundNetLog net_log_
;
1223 scoped_ptr
<DnsTransaction
> transaction_a_
;
1224 scoped_ptr
<DnsTransaction
> transaction_aaaa_
;
1226 unsigned num_completed_transactions_
;
1228 // These are updated as each transaction completes.
1229 base::TimeDelta ttl_
;
1230 // IPv6 addresses must appear first in the list.
1231 AddressList addr_list_
;
1233 base::TimeTicks task_start_time_
;
1235 DISALLOW_COPY_AND_ASSIGN(DnsTask
);
1238 //-----------------------------------------------------------------------------
1240 // Aggregates all Requests for the same Key. Dispatched via PriorityDispatch.
1241 class HostResolverImpl::Job
: public PrioritizedDispatcher::Job
,
1242 public HostResolverImpl::DnsTask::Delegate
{
1244 // Creates new job for |key| where |request_net_log| is bound to the
1245 // request that spawned it.
1246 Job(const base::WeakPtr
<HostResolverImpl
>& resolver
,
1248 RequestPriority priority
,
1249 const BoundNetLog
& source_net_log
)
1250 : resolver_(resolver
),
1252 priority_tracker_(priority
),
1253 had_non_speculative_request_(false),
1254 had_dns_config_(false),
1255 num_occupied_job_slots_(0),
1256 dns_task_error_(OK
),
1257 creation_time_(base::TimeTicks::Now()),
1258 priority_change_time_(creation_time_
),
1259 net_log_(BoundNetLog::Make(source_net_log
.net_log(),
1260 NetLog::SOURCE_HOST_RESOLVER_IMPL_JOB
)) {
1261 source_net_log
.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_CREATE_JOB
);
1263 net_log_
.BeginEvent(
1264 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB
,
1265 base::Bind(&NetLogJobCreationCallback
,
1266 source_net_log
.source(),
1272 // |resolver_| was destroyed with this Job still in flight.
1273 // Clean-up, record in the log, but don't run any callbacks.
1274 if (is_proc_running()) {
1275 proc_task_
->Cancel();
1278 // Clean up now for nice NetLog.
1280 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB
,
1282 } else if (is_queued()) {
1283 // |resolver_| was destroyed without running this Job.
1284 // TODO(szym): is there any benefit in having this distinction?
1285 net_log_
.AddEvent(NetLog::TYPE_CANCELLED
);
1286 net_log_
.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB
);
1288 // else CompleteRequests logged EndEvent.
1290 // Log any remaining Requests as cancelled.
1291 for (RequestsList::const_iterator it
= requests_
.begin();
1292 it
!= requests_
.end(); ++it
) {
1294 if (req
->was_canceled())
1296 DCHECK_EQ(this, req
->job());
1297 LogCancelRequest(req
->source_net_log(), req
->info());
1301 // Add this job to the dispatcher. If "at_head" is true, adds at the front
1303 void Schedule(bool at_head
) {
1304 DCHECK(!is_queued());
1305 PrioritizedDispatcher::Handle handle
;
1307 handle
= resolver_
->dispatcher_
->Add(this, priority());
1309 handle
= resolver_
->dispatcher_
->AddAtHead(this, priority());
1311 // The dispatcher could have started |this| in the above call to Add, which
1312 // could have called Schedule again. In that case |handle| will be null,
1313 // but |handle_| may have been set by the other nested call to Schedule.
1314 if (!handle
.is_null()) {
1315 DCHECK(handle_
.is_null());
1320 void AddRequest(scoped_ptr
<Request
> req
) {
1321 // .localhost queries are redirected to "localhost." to make sure
1322 // that they are never sent out on the network, per RFC 6761.
1323 if (IsLocalhostTLD(req
->info().hostname())) {
1324 DCHECK_EQ(key_
.hostname
, kLocalhost
);
1326 DCHECK_EQ(key_
.hostname
, req
->info().hostname());
1330 priority_tracker_
.Add(req
->priority());
1332 req
->source_net_log().AddEvent(
1333 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_ATTACH
,
1334 net_log_
.source().ToEventParametersCallback());
1337 NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_REQUEST_ATTACH
,
1338 base::Bind(&NetLogJobAttachCallback
,
1339 req
->source_net_log().source(),
1342 // TODO(szym): Check if this is still needed.
1343 if (!req
->info().is_speculative()) {
1344 had_non_speculative_request_
= true;
1345 if (proc_task_
.get())
1346 proc_task_
->set_had_non_speculative_request();
1349 requests_
.push_back(req
.Pass());
1354 // Marks |req| as cancelled. If it was the last active Request, also finishes
1355 // this Job, marking it as cancelled, and deletes it.
1356 void CancelRequest(Request
* req
) {
1357 DCHECK_EQ(key_
.hostname
, req
->info().hostname());
1358 DCHECK(!req
->was_canceled());
1360 // Don't remove it from |requests_| just mark it canceled.
1361 req
->MarkAsCanceled();
1362 LogCancelRequest(req
->source_net_log(), req
->info());
1364 priority_tracker_
.Remove(req
->priority());
1365 net_log_
.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_REQUEST_DETACH
,
1366 base::Bind(&NetLogJobAttachCallback
,
1367 req
->source_net_log().source(),
1370 if (num_active_requests() > 0) {
1373 // If we were called from a Request's callback within CompleteRequests,
1374 // that Request could not have been cancelled, so num_active_requests()
1375 // could not be 0. Therefore, we are not in CompleteRequests().
1376 CompleteRequestsWithError(OK
/* cancelled */);
1380 // Called from AbortAllInProgressJobs. Completes all requests and destroys
1381 // the job. This currently assumes the abort is due to a network change.
1383 DCHECK(is_running());
1384 CompleteRequestsWithError(ERR_NETWORK_CHANGED
);
1387 // If DnsTask present, abort it and fall back to ProcTask.
1388 void AbortDnsTask() {
1391 dns_task_error_
= OK
;
1396 // Called by HostResolverImpl when this job is evicted due to queue overflow.
1397 // Completes all requests and destroys the job.
1399 DCHECK(!is_running());
1400 DCHECK(is_queued());
1403 net_log_
.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_EVICTED
);
1405 // This signals to CompleteRequests that this job never ran.
1406 CompleteRequestsWithError(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE
);
1409 // Attempts to serve the job from HOSTS. Returns true if succeeded and
1410 // this Job was destroyed.
1411 bool ServeFromHosts() {
1412 DCHECK_GT(num_active_requests(), 0u);
1413 AddressList addr_list
;
1414 if (resolver_
->ServeFromHosts(key(),
1415 requests_
.front()->info(),
1417 // This will destroy the Job.
1419 HostCache::Entry(OK
, MakeAddressListForRequest(addr_list
)),
1426 const Key
key() const {
1430 bool is_queued() const {
1431 return !handle_
.is_null();
1434 bool is_running() const {
1435 return is_dns_running() || is_proc_running();
1439 void KillDnsTask() {
1441 ReduceToOneJobSlot();
1446 // Reduce the number of job slots occupied and queued in the dispatcher
1447 // to one. If the second Job slot is queued in the dispatcher, cancels the
1448 // queued job. Otherwise, the second Job has been started by the
1449 // PrioritizedDispatcher, so signals it is complete.
1450 void ReduceToOneJobSlot() {
1451 DCHECK_GE(num_occupied_job_slots_
, 1u);
1453 resolver_
->dispatcher_
->Cancel(handle_
);
1455 } else if (num_occupied_job_slots_
> 1) {
1456 resolver_
->dispatcher_
->OnJobFinished();
1457 --num_occupied_job_slots_
;
1459 DCHECK_EQ(1u, num_occupied_job_slots_
);
1462 void UpdatePriority() {
1464 if (priority() != static_cast<RequestPriority
>(handle_
.priority()))
1465 priority_change_time_
= base::TimeTicks::Now();
1466 handle_
= resolver_
->dispatcher_
->ChangePriority(handle_
, priority());
1470 AddressList
MakeAddressListForRequest(const AddressList
& list
) const {
1471 if (requests_
.empty())
1473 return AddressList::CopyWithPort(list
, requests_
.front()->info().port());
1476 // PriorityDispatch::Job:
1477 void Start() override
{
1478 DCHECK_LE(num_occupied_job_slots_
, 1u);
1481 ++num_occupied_job_slots_
;
1483 if (num_occupied_job_slots_
== 2) {
1484 StartSecondDnsTransaction();
1488 DCHECK(!is_running());
1490 net_log_
.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_STARTED
);
1492 had_dns_config_
= resolver_
->HaveDnsConfig();
1494 base::TimeTicks now
= base::TimeTicks::Now();
1495 base::TimeDelta queue_time
= now
- creation_time_
;
1496 base::TimeDelta queue_time_after_change
= now
- priority_change_time_
;
1498 if (had_dns_config_
) {
1499 DNS_HISTOGRAM_BY_PRIORITY("AsyncDNS.JobQueueTime", priority(),
1501 DNS_HISTOGRAM_BY_PRIORITY("AsyncDNS.JobQueueTimeAfterChange", priority(),
1502 queue_time_after_change
);
1504 DNS_HISTOGRAM_BY_PRIORITY("DNS.JobQueueTime", priority(), queue_time
);
1505 DNS_HISTOGRAM_BY_PRIORITY("DNS.JobQueueTimeAfterChange", priority(),
1506 queue_time_after_change
);
1510 (key_
.host_resolver_flags
& HOST_RESOLVER_SYSTEM_ONLY
) != 0;
1512 // Caution: Job::Start must not complete synchronously.
1513 if (!system_only
&& had_dns_config_
&&
1514 !ResemblesMulticastDNSName(key_
.hostname
)) {
1521 // TODO(szym): Since DnsTransaction does not consume threads, we can increase
1522 // the limits on |dispatcher_|. But in order to keep the number of WorkerPool
1523 // threads low, we will need to use an "inner" PrioritizedDispatcher with
1525 void StartProcTask() {
1526 DCHECK(!is_dns_running());
1527 proc_task_
= new ProcTask(
1529 resolver_
->proc_params_
,
1530 base::Bind(&Job::OnProcTaskComplete
, base::Unretained(this),
1531 base::TimeTicks::Now()),
1534 if (had_non_speculative_request_
)
1535 proc_task_
->set_had_non_speculative_request();
1536 // Start() could be called from within Resolve(), hence it must NOT directly
1537 // call OnProcTaskComplete, for example, on synchronous failure.
1538 proc_task_
->Start();
1541 // Called by ProcTask when it completes.
1542 void OnProcTaskComplete(base::TimeTicks start_time
,
1544 const AddressList
& addr_list
) {
1545 DCHECK(is_proc_running());
1547 if (!resolver_
->resolved_known_ipv6_hostname_
&&
1549 key_
.address_family
== ADDRESS_FAMILY_UNSPECIFIED
) {
1550 if (key_
.hostname
== "www.google.com") {
1551 resolver_
->resolved_known_ipv6_hostname_
= true;
1552 bool got_ipv6_address
= false;
1553 for (size_t i
= 0; i
< addr_list
.size(); ++i
) {
1554 if (addr_list
[i
].GetFamily() == ADDRESS_FAMILY_IPV6
) {
1555 got_ipv6_address
= true;
1559 UMA_HISTOGRAM_BOOLEAN("Net.UnspecResolvedIPv6", got_ipv6_address
);
1563 if (dns_task_error_
!= OK
) {
1564 base::TimeDelta duration
= base::TimeTicks::Now() - start_time
;
1565 if (net_error
== OK
) {
1566 DNS_HISTOGRAM("AsyncDNS.FallbackSuccess", duration
);
1567 if ((dns_task_error_
== ERR_NAME_NOT_RESOLVED
) &&
1568 ResemblesNetBIOSName(key_
.hostname
)) {
1569 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_SUSPECT_NETBIOS
);
1571 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_PROC_SUCCESS
);
1573 UMA_HISTOGRAM_SPARSE_SLOWLY("AsyncDNS.ResolveError",
1574 std::abs(dns_task_error_
));
1575 resolver_
->OnDnsTaskResolve(dns_task_error_
);
1577 DNS_HISTOGRAM("AsyncDNS.FallbackFail", duration
);
1578 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL
);
1582 base::TimeDelta ttl
=
1583 base::TimeDelta::FromSeconds(kNegativeCacheEntryTTLSeconds
);
1584 if (net_error
== OK
)
1585 ttl
= base::TimeDelta::FromSeconds(kCacheEntryTTLSeconds
);
1587 // Don't store the |ttl| in cache since it's not obtained from the server.
1589 HostCache::Entry(net_error
, MakeAddressListForRequest(addr_list
)),
1593 void StartDnsTask() {
1594 DCHECK(resolver_
->HaveDnsConfig());
1595 dns_task_
.reset(new DnsTask(resolver_
->dns_client_
.get(), key_
, this,
1598 dns_task_
->StartFirstTransaction();
1599 // Schedule a second transaction, if needed.
1600 if (dns_task_
->needs_two_transactions())
1604 void StartSecondDnsTransaction() {
1605 DCHECK(dns_task_
->needs_two_transactions());
1606 dns_task_
->StartSecondTransaction();
1609 // Called if DnsTask fails. It is posted from StartDnsTask, so Job may be
1610 // deleted before this callback. In this case dns_task is deleted as well,
1611 // so we use it as indicator whether Job is still valid.
1612 void OnDnsTaskFailure(const base::WeakPtr
<DnsTask
>& dns_task
,
1613 base::TimeDelta duration
,
1615 DNS_HISTOGRAM("AsyncDNS.ResolveFail", duration
);
1617 if (dns_task
== NULL
)
1620 dns_task_error_
= net_error
;
1622 // TODO(szym): Run ServeFromHosts now if nsswitch.conf says so.
1623 // http://crbug.com/117655
1625 // TODO(szym): Some net errors indicate lack of connectivity. Starting
1626 // ProcTask in that case is a waste of time.
1627 if (resolver_
->fallback_to_proctask_
) {
1631 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL
);
1632 CompleteRequestsWithError(net_error
);
1637 // HostResolverImpl::DnsTask::Delegate implementation:
1639 void OnDnsTaskComplete(base::TimeTicks start_time
,
1641 const AddressList
& addr_list
,
1642 base::TimeDelta ttl
) override
{
1643 DCHECK(is_dns_running());
1645 base::TimeDelta duration
= base::TimeTicks::Now() - start_time
;
1646 if (net_error
!= OK
) {
1647 OnDnsTaskFailure(dns_task_
->AsWeakPtr(), duration
, net_error
);
1650 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess", duration
);
1651 // Log DNS lookups based on |address_family|.
1652 switch(key_
.address_family
) {
1653 case ADDRESS_FAMILY_IPV4
:
1654 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_IPV4", duration
);
1656 case ADDRESS_FAMILY_IPV6
:
1657 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_IPV6", duration
);
1659 case ADDRESS_FAMILY_UNSPECIFIED
:
1660 DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_UNSPEC", duration
);
1664 UmaAsyncDnsResolveStatus(RESOLVE_STATUS_DNS_SUCCESS
);
1667 resolver_
->OnDnsTaskResolve(OK
);
1669 base::TimeDelta bounded_ttl
=
1670 std::max(ttl
, base::TimeDelta::FromSeconds(kMinimumTTLSeconds
));
1673 HostCache::Entry(net_error
, MakeAddressListForRequest(addr_list
), ttl
),
1677 void OnFirstDnsTransactionComplete() override
{
1678 DCHECK(dns_task_
->needs_two_transactions());
1679 DCHECK_EQ(dns_task_
->needs_another_transaction(), is_queued());
1680 // No longer need to occupy two dispatcher slots.
1681 ReduceToOneJobSlot();
1683 // We already have a job slot at the dispatcher, so if the second
1684 // transaction hasn't started, reuse it now instead of waiting in the queue
1685 // for the second slot.
1686 if (dns_task_
->needs_another_transaction())
1687 dns_task_
->StartSecondTransaction();
1690 // Performs Job's last rites. Completes all Requests. Deletes this.
1691 void CompleteRequests(const HostCache::Entry
& entry
,
1692 base::TimeDelta ttl
) {
1693 CHECK(resolver_
.get());
1695 // This job must be removed from resolver's |jobs_| now to make room for a
1696 // new job with the same key in case one of the OnComplete callbacks decides
1697 // to spawn one. Consequently, the job deletes itself when CompleteRequests
1699 scoped_ptr
<Job
> self_deleter(this);
1701 resolver_
->RemoveJob(this);
1704 if (is_proc_running()) {
1705 DCHECK(!is_queued());
1706 proc_task_
->Cancel();
1711 // Signal dispatcher that a slot has opened.
1712 resolver_
->dispatcher_
->OnJobFinished();
1713 } else if (is_queued()) {
1714 resolver_
->dispatcher_
->Cancel(handle_
);
1718 if (num_active_requests() == 0) {
1719 net_log_
.AddEvent(NetLog::TYPE_CANCELLED
);
1720 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB
,
1725 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB
,
1728 DCHECK(!requests_
.empty());
1730 if (entry
.error
== OK
) {
1731 // Record this histogram here, when we know the system has a valid DNS
1733 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.HaveDnsConfig",
1734 resolver_
->received_dns_config_
);
1737 bool did_complete
= (entry
.error
!= ERR_NETWORK_CHANGED
) &&
1738 (entry
.error
!= ERR_HOST_RESOLVER_QUEUE_TOO_LARGE
);
1740 resolver_
->CacheResult(key_
, entry
, ttl
);
1742 // Complete all of the requests that were attached to the job.
1743 for (RequestsList::const_iterator it
= requests_
.begin();
1744 it
!= requests_
.end(); ++it
) {
1747 if (req
->was_canceled())
1750 DCHECK_EQ(this, req
->job());
1751 // Update the net log and notify registered observers.
1752 LogFinishRequest(req
->source_net_log(), req
->info(), entry
.error
);
1754 // Record effective total time from creation to completion.
1755 RecordTotalTime(had_dns_config_
, req
->info().is_speculative(),
1756 base::TimeTicks::Now() - req
->request_time());
1758 req
->OnComplete(entry
.error
, entry
.addrlist
);
1760 // Check if the resolver was destroyed as a result of running the
1761 // callback. If it was, we could continue, but we choose to bail.
1762 if (!resolver_
.get())
1767 // Convenience wrapper for CompleteRequests in case of failure.
1768 void CompleteRequestsWithError(int net_error
) {
1769 CompleteRequests(HostCache::Entry(net_error
, AddressList()),
1773 RequestPriority
priority() const {
1774 return priority_tracker_
.highest_priority();
1777 // Number of non-canceled requests in |requests_|.
1778 size_t num_active_requests() const {
1779 return priority_tracker_
.total_count();
1782 bool is_dns_running() const {
1783 return dns_task_
.get() != NULL
;
1786 bool is_proc_running() const {
1787 return proc_task_
.get() != NULL
;
1790 base::WeakPtr
<HostResolverImpl
> resolver_
;
1794 // Tracks the highest priority across |requests_|.
1795 PriorityTracker priority_tracker_
;
1797 bool had_non_speculative_request_
;
1799 // Distinguishes measurements taken while DnsClient was fully configured.
1800 bool had_dns_config_
;
1802 // Number of slots occupied by this Job in resolver's PrioritizedDispatcher.
1803 unsigned num_occupied_job_slots_
;
1805 // Result of DnsTask.
1806 int dns_task_error_
;
1808 const base::TimeTicks creation_time_
;
1809 base::TimeTicks priority_change_time_
;
1811 BoundNetLog net_log_
;
1813 // Resolves the host using a HostResolverProc.
1814 scoped_refptr
<ProcTask
> proc_task_
;
1816 // Resolves the host using a DnsTransaction.
1817 scoped_ptr
<DnsTask
> dns_task_
;
1819 // All Requests waiting for the result of this Job. Some can be canceled.
1820 RequestsList requests_
;
1822 // A handle used in |HostResolverImpl::dispatcher_|.
1823 PrioritizedDispatcher::Handle handle_
;
1826 //-----------------------------------------------------------------------------
1828 HostResolverImpl::ProcTaskParams::ProcTaskParams(
1829 HostResolverProc
* resolver_proc
,
1830 size_t max_retry_attempts
)
1831 : resolver_proc(resolver_proc
),
1832 max_retry_attempts(max_retry_attempts
),
1833 unresponsive_delay(base::TimeDelta::FromMilliseconds(6000)),
1835 // Maximum of 4 retry attempts for host resolution.
1836 static const size_t kDefaultMaxRetryAttempts
= 4u;
1837 if (max_retry_attempts
== HostResolver::kDefaultRetryAttempts
)
1838 max_retry_attempts
= kDefaultMaxRetryAttempts
;
1841 HostResolverImpl::ProcTaskParams::~ProcTaskParams() {}
1843 HostResolverImpl::HostResolverImpl(const Options
& options
, NetLog
* net_log
)
1844 : max_queued_jobs_(0),
1845 proc_params_(NULL
, options
.max_retry_attempts
),
1847 received_dns_config_(false),
1848 num_dns_failures_(0),
1849 use_local_ipv6_(false),
1850 last_ipv6_probe_result_(true),
1851 resolved_known_ipv6_hostname_(false),
1852 additional_resolver_flags_(0),
1853 fallback_to_proctask_(true),
1854 weak_ptr_factory_(this),
1855 probe_weak_ptr_factory_(this) {
1856 if (options
.enable_caching
)
1857 cache_
= HostCache::CreateDefaultCache();
1859 PrioritizedDispatcher::Limits job_limits
= options
.GetDispatcherLimits();
1860 dispatcher_
.reset(new PrioritizedDispatcher(job_limits
));
1861 max_queued_jobs_
= job_limits
.total_jobs
* 100u;
1863 DCHECK_GE(dispatcher_
->num_priorities(), static_cast<size_t>(NUM_PRIORITIES
));
1866 EnsureWinsockInit();
1868 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
1869 new LoopbackProbeJob(weak_ptr_factory_
.GetWeakPtr());
1871 NetworkChangeNotifier::AddIPAddressObserver(this);
1872 NetworkChangeNotifier::AddDNSObserver(this);
1873 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD) && \
1874 !defined(OS_ANDROID)
1875 EnsureDnsReloaderInit();
1879 DnsConfig dns_config
;
1880 NetworkChangeNotifier::GetDnsConfig(&dns_config
);
1881 received_dns_config_
= dns_config
.IsValid();
1882 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
1883 use_local_ipv6_
= !dns_config
.IsValid() || dns_config
.use_local_ipv6
;
1886 fallback_to_proctask_
= !ConfigureAsyncDnsNoFallbackFieldTrial();
1889 HostResolverImpl::~HostResolverImpl() {
1890 // Prevent the dispatcher from starting new jobs.
1891 dispatcher_
->SetLimitsToZero();
1892 // It's now safe for Jobs to call KillDsnTask on destruction, because
1893 // OnJobComplete will not start any new jobs.
1894 STLDeleteValues(&jobs_
);
1896 NetworkChangeNotifier::RemoveIPAddressObserver(this);
1897 NetworkChangeNotifier::RemoveDNSObserver(this);
1900 void HostResolverImpl::SetMaxQueuedJobs(size_t value
) {
1901 DCHECK_EQ(0u, dispatcher_
->num_queued_jobs());
1902 DCHECK_GT(value
, 0u);
1903 max_queued_jobs_
= value
;
1906 int HostResolverImpl::Resolve(const RequestInfo
& info
,
1907 RequestPriority priority
,
1908 AddressList
* addresses
,
1909 const CompletionCallback
& callback
,
1910 RequestHandle
* out_req
,
1911 const BoundNetLog
& source_net_log
) {
1913 DCHECK(CalledOnValidThread());
1914 DCHECK_EQ(false, callback
.is_null());
1916 // Check that the caller supplied a valid hostname to resolve.
1917 std::string labeled_hostname
;
1918 if (!DNSDomainFromDot(info
.hostname(), &labeled_hostname
))
1919 return ERR_NAME_NOT_RESOLVED
;
1921 LogStartRequest(source_net_log
, info
);
1923 IPAddressNumber ip_number
;
1924 IPAddressNumber
* ip_number_ptr
= nullptr;
1925 if (ParseIPLiteralToNumber(info
.hostname(), &ip_number
))
1926 ip_number_ptr
= &ip_number
;
1928 // Build a key that identifies the request in the cache and in the
1929 // outstanding jobs map.
1930 Key key
= GetEffectiveKeyForRequest(info
, ip_number_ptr
, source_net_log
);
1932 int rv
= ResolveHelper(key
, info
, ip_number_ptr
, addresses
, source_net_log
);
1933 if (rv
!= ERR_DNS_CACHE_MISS
) {
1934 LogFinishRequest(source_net_log
, info
, rv
);
1935 RecordTotalTime(HaveDnsConfig(), info
.is_speculative(), base::TimeDelta());
1939 // Next we need to attach our request to a "job". This job is responsible for
1940 // calling "getaddrinfo(hostname)" on a worker thread.
1942 JobMap::iterator jobit
= jobs_
.find(key
);
1944 if (jobit
== jobs_
.end()) {
1946 new Job(weak_ptr_factory_
.GetWeakPtr(), key
, priority
, source_net_log
);
1947 job
->Schedule(false);
1949 // Check for queue overflow.
1950 if (dispatcher_
->num_queued_jobs() > max_queued_jobs_
) {
1951 Job
* evicted
= static_cast<Job
*>(dispatcher_
->EvictOldestLowest());
1953 evicted
->OnEvicted(); // Deletes |evicted|.
1954 if (evicted
== job
) {
1955 rv
= ERR_HOST_RESOLVER_QUEUE_TOO_LARGE
;
1956 LogFinishRequest(source_net_log
, info
, rv
);
1960 jobs_
.insert(jobit
, std::make_pair(key
, job
));
1962 job
= jobit
->second
;
1965 // Can't complete synchronously. Create and attach request.
1966 scoped_ptr
<Request
> req(new Request(
1967 source_net_log
, info
, priority
, callback
, addresses
));
1969 *out_req
= reinterpret_cast<RequestHandle
>(req
.get());
1971 job
->AddRequest(req
.Pass());
1972 // Completion happens during Job::CompleteRequests().
1973 return ERR_IO_PENDING
;
1976 int HostResolverImpl::ResolveHelper(const Key
& key
,
1977 const RequestInfo
& info
,
1978 const IPAddressNumber
* ip_number
,
1979 AddressList
* addresses
,
1980 const BoundNetLog
& source_net_log
) {
1981 // The result of |getaddrinfo| for empty hosts is inconsistent across systems.
1982 // On Windows it gives the default interface's address, whereas on Linux it
1983 // gives an error. We will make it fail on all platforms for consistency.
1984 if (info
.hostname().empty() || info
.hostname().size() > kMaxHostLength
)
1985 return ERR_NAME_NOT_RESOLVED
;
1987 int net_error
= ERR_UNEXPECTED
;
1988 if (ResolveAsIP(key
, info
, ip_number
, &net_error
, addresses
))
1990 if (ServeFromCache(key
, info
, &net_error
, addresses
)) {
1991 source_net_log
.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_CACHE_HIT
);
1994 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
1995 // http://crbug.com/117655
1996 if (ServeFromHosts(key
, info
, addresses
)) {
1997 source_net_log
.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_HOSTS_HIT
);
2000 return ERR_DNS_CACHE_MISS
;
2003 int HostResolverImpl::ResolveFromCache(const RequestInfo
& info
,
2004 AddressList
* addresses
,
2005 const BoundNetLog
& source_net_log
) {
2006 DCHECK(CalledOnValidThread());
2009 // Update the net log and notify registered observers.
2010 LogStartRequest(source_net_log
, info
);
2012 IPAddressNumber ip_number
;
2013 IPAddressNumber
* ip_number_ptr
= nullptr;
2014 if (ParseIPLiteralToNumber(info
.hostname(), &ip_number
))
2015 ip_number_ptr
= &ip_number
;
2017 Key key
= GetEffectiveKeyForRequest(info
, ip_number_ptr
, source_net_log
);
2019 int rv
= ResolveHelper(key
, info
, ip_number_ptr
, addresses
, source_net_log
);
2020 LogFinishRequest(source_net_log
, info
, rv
);
2024 void HostResolverImpl::CancelRequest(RequestHandle req_handle
) {
2025 DCHECK(CalledOnValidThread());
2026 Request
* req
= reinterpret_cast<Request
*>(req_handle
);
2028 Job
* job
= req
->job();
2030 job
->CancelRequest(req
);
2033 void HostResolverImpl::SetDnsClientEnabled(bool enabled
) {
2034 DCHECK(CalledOnValidThread());
2035 #if defined(ENABLE_BUILT_IN_DNS)
2036 if (enabled
&& !dns_client_
) {
2037 SetDnsClient(DnsClient::CreateClient(net_log_
));
2038 } else if (!enabled
&& dns_client_
) {
2039 SetDnsClient(scoped_ptr
<DnsClient
>());
2044 HostCache
* HostResolverImpl::GetHostCache() {
2045 return cache_
.get();
2048 base::Value
* HostResolverImpl::GetDnsConfigAsValue() const {
2049 // Check if async DNS is disabled.
2050 if (!dns_client_
.get())
2053 // Check if async DNS is enabled, but we currently have no configuration
2055 const DnsConfig
* dns_config
= dns_client_
->GetConfig();
2056 if (dns_config
== NULL
)
2057 return new base::DictionaryValue();
2059 return dns_config
->ToValue();
2062 bool HostResolverImpl::ResolveAsIP(const Key
& key
,
2063 const RequestInfo
& info
,
2064 const IPAddressNumber
* ip_number
,
2066 AddressList
* addresses
) {
2069 if (ip_number
== nullptr)
2072 DCHECK_EQ(key
.host_resolver_flags
&
2073 ~(HOST_RESOLVER_CANONNAME
| HOST_RESOLVER_LOOPBACK_ONLY
|
2074 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6
),
2075 0) << " Unhandled flag";
2078 AddressFamily family
= GetAddressFamily(*ip_number
);
2079 if (key
.address_family
!= ADDRESS_FAMILY_UNSPECIFIED
&&
2080 key
.address_family
!= family
) {
2081 // Don't return IPv6 addresses for IPv4 queries, and vice versa.
2082 *net_error
= ERR_NAME_NOT_RESOLVED
;
2084 *addresses
= AddressList::CreateFromIPAddress(*ip_number
, info
.port());
2085 if (key
.host_resolver_flags
& HOST_RESOLVER_CANONNAME
)
2086 addresses
->SetDefaultCanonicalName();
2091 bool HostResolverImpl::ServeFromCache(const Key
& key
,
2092 const RequestInfo
& info
,
2094 AddressList
* addresses
) {
2097 if (!info
.allow_cached_response() || !cache_
.get())
2100 const HostCache::Entry
* cache_entry
= cache_
->Lookup(
2101 key
, base::TimeTicks::Now());
2105 *net_error
= cache_entry
->error
;
2106 if (*net_error
== OK
) {
2107 if (cache_entry
->has_ttl())
2108 RecordTTL(cache_entry
->ttl
);
2109 *addresses
= EnsurePortOnAddressList(cache_entry
->addrlist
, info
.port());
2114 bool HostResolverImpl::ServeFromHosts(const Key
& key
,
2115 const RequestInfo
& info
,
2116 AddressList
* addresses
) {
2118 if (!HaveDnsConfig())
2122 // HOSTS lookups are case-insensitive.
2123 std::string hostname
= base::StringToLowerASCII(key
.hostname
);
2125 const DnsHosts
& hosts
= dns_client_
->GetConfig()->hosts
;
2127 // If |address_family| is ADDRESS_FAMILY_UNSPECIFIED other implementations
2128 // (glibc and c-ares) return the first matching line. We have more
2129 // flexibility, but lose implicit ordering.
2130 // We prefer IPv6 because "happy eyeballs" will fall back to IPv4 if
2132 if (key
.address_family
== ADDRESS_FAMILY_IPV6
||
2133 key
.address_family
== ADDRESS_FAMILY_UNSPECIFIED
) {
2134 DnsHosts::const_iterator it
= hosts
.find(
2135 DnsHostsKey(hostname
, ADDRESS_FAMILY_IPV6
));
2136 if (it
!= hosts
.end())
2137 addresses
->push_back(IPEndPoint(it
->second
, info
.port()));
2140 if (key
.address_family
== ADDRESS_FAMILY_IPV4
||
2141 key
.address_family
== ADDRESS_FAMILY_UNSPECIFIED
) {
2142 DnsHosts::const_iterator it
= hosts
.find(
2143 DnsHostsKey(hostname
, ADDRESS_FAMILY_IPV4
));
2144 if (it
!= hosts
.end())
2145 addresses
->push_back(IPEndPoint(it
->second
, info
.port()));
2148 // If got only loopback addresses and the family was restricted, resolve
2149 // again, without restrictions. See SystemHostResolverCall for rationale.
2150 if ((key
.host_resolver_flags
&
2151 HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6
) &&
2152 IsAllIPv4Loopback(*addresses
)) {
2154 new_key
.address_family
= ADDRESS_FAMILY_UNSPECIFIED
;
2155 new_key
.host_resolver_flags
&=
2156 ~HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6
;
2157 return ServeFromHosts(new_key
, info
, addresses
);
2159 return !addresses
->empty();
2162 void HostResolverImpl::CacheResult(const Key
& key
,
2163 const HostCache::Entry
& entry
,
2164 base::TimeDelta ttl
) {
2166 cache_
->Set(key
, entry
, base::TimeTicks::Now(), ttl
);
2169 void HostResolverImpl::RemoveJob(Job
* job
) {
2171 JobMap::iterator it
= jobs_
.find(job
->key());
2172 if (it
!= jobs_
.end() && it
->second
== job
)
2176 void HostResolverImpl::SetHaveOnlyLoopbackAddresses(bool result
) {
2178 additional_resolver_flags_
|= HOST_RESOLVER_LOOPBACK_ONLY
;
2180 additional_resolver_flags_
&= ~HOST_RESOLVER_LOOPBACK_ONLY
;
2184 HostResolverImpl::Key
HostResolverImpl::GetEffectiveKeyForRequest(
2185 const RequestInfo
& info
,
2186 const IPAddressNumber
* ip_number
,
2187 const BoundNetLog
& net_log
) {
2188 HostResolverFlags effective_flags
=
2189 info
.host_resolver_flags() | additional_resolver_flags_
;
2190 AddressFamily effective_address_family
= info
.address_family();
2192 if (info
.address_family() == ADDRESS_FAMILY_UNSPECIFIED
) {
2193 if (!use_local_ipv6_
&&
2194 // When resolving IPv4 literals, there's no need to probe for IPv6.
2195 // When resolving IPv6 literals, there's no benefit to artificially
2196 // limiting our resolution based on a probe. Prior logic ensures
2197 // that this query is UNSPECIFIED (see info.address_family()
2198 // check above) so the code requesting the resolution should be amenable
2199 // to receiving a IPv6 resolution.
2200 ip_number
== nullptr) {
2201 if (!IsIPv6Reachable(net_log
)) {
2202 effective_address_family
= ADDRESS_FAMILY_IPV4
;
2203 effective_flags
|= HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6
;
2208 std::string hostname
= info
.hostname();
2209 // Redirect .localhost queries to "localhost." to make sure that they
2210 // are never sent out on the network, per RFC 6761.
2211 if (IsLocalhostTLD(info
.hostname()))
2212 hostname
= kLocalhost
;
2214 return Key(hostname
, effective_address_family
, effective_flags
);
2217 bool HostResolverImpl::IsIPv6Reachable(const BoundNetLog
& net_log
) {
2218 base::TimeTicks now
= base::TimeTicks::Now();
2220 if ((now
- last_ipv6_probe_time_
).InMilliseconds() > kIPv6ProbePeriodMs
) {
2221 IPAddressNumber
address(kIPv6ProbeAddress
,
2222 kIPv6ProbeAddress
+ arraysize(kIPv6ProbeAddress
));
2223 last_ipv6_probe_result_
= IsGloballyReachable(address
, net_log
);
2224 last_ipv6_probe_time_
= now
;
2227 net_log
.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_IPV6_REACHABILITY_CHECK
,
2228 base::Bind(&NetLogIPv6AvailableCallback
,
2229 last_ipv6_probe_result_
, cached
));
2230 return last_ipv6_probe_result_
;
2233 void HostResolverImpl::AbortAllInProgressJobs() {
2234 // In Abort, a Request callback could spawn new Jobs with matching keys, so
2235 // first collect and remove all running jobs from |jobs_|.
2236 ScopedVector
<Job
> jobs_to_abort
;
2237 for (JobMap::iterator it
= jobs_
.begin(); it
!= jobs_
.end(); ) {
2238 Job
* job
= it
->second
;
2239 if (job
->is_running()) {
2240 jobs_to_abort
.push_back(job
);
2243 DCHECK(job
->is_queued());
2248 // Pause the dispatcher so it won't start any new dispatcher jobs while
2249 // aborting the old ones. This is needed so that it won't start the second
2250 // DnsTransaction for a job in |jobs_to_abort| if the DnsConfig just became
2252 PrioritizedDispatcher::Limits limits
= dispatcher_
->GetLimits();
2253 dispatcher_
->SetLimits(
2254 PrioritizedDispatcher::Limits(limits
.reserved_slots
.size(), 0));
2256 // Life check to bail once |this| is deleted.
2257 base::WeakPtr
<HostResolverImpl
> self
= weak_ptr_factory_
.GetWeakPtr();
2260 for (size_t i
= 0; self
.get() && i
< jobs_to_abort
.size(); ++i
) {
2261 jobs_to_abort
[i
]->Abort();
2262 jobs_to_abort
[i
] = NULL
;
2266 dispatcher_
->SetLimits(limits
);
2269 void HostResolverImpl::AbortDnsTasks() {
2270 // Pause the dispatcher so it won't start any new dispatcher jobs while
2271 // aborting the old ones. This is needed so that it won't start the second
2272 // DnsTransaction for a job if the DnsConfig just changed.
2273 PrioritizedDispatcher::Limits limits
= dispatcher_
->GetLimits();
2274 dispatcher_
->SetLimits(
2275 PrioritizedDispatcher::Limits(limits
.reserved_slots
.size(), 0));
2277 for (JobMap::iterator it
= jobs_
.begin(); it
!= jobs_
.end(); ++it
)
2278 it
->second
->AbortDnsTask();
2279 dispatcher_
->SetLimits(limits
);
2282 void HostResolverImpl::TryServingAllJobsFromHosts() {
2283 if (!HaveDnsConfig())
2286 // TODO(szym): Do not do this if nsswitch.conf instructs not to.
2287 // http://crbug.com/117655
2289 // Life check to bail once |this| is deleted.
2290 base::WeakPtr
<HostResolverImpl
> self
= weak_ptr_factory_
.GetWeakPtr();
2292 for (JobMap::iterator it
= jobs_
.begin(); self
.get() && it
!= jobs_
.end();) {
2293 Job
* job
= it
->second
;
2295 // This could remove |job| from |jobs_|, but iterator will remain valid.
2296 job
->ServeFromHosts();
2300 void HostResolverImpl::OnIPAddressChanged() {
2301 resolved_known_ipv6_hostname_
= false;
2302 last_ipv6_probe_time_
= base::TimeTicks();
2303 // Abandon all ProbeJobs.
2304 probe_weak_ptr_factory_
.InvalidateWeakPtrs();
2307 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
2308 new LoopbackProbeJob(probe_weak_ptr_factory_
.GetWeakPtr());
2310 AbortAllInProgressJobs();
2311 // |this| may be deleted inside AbortAllInProgressJobs().
2314 void HostResolverImpl::OnInitialDNSConfigRead() {
2315 UpdateDNSConfig(false);
2318 void HostResolverImpl::OnDNSChanged() {
2319 UpdateDNSConfig(true);
2322 void HostResolverImpl::UpdateDNSConfig(bool config_changed
) {
2323 DnsConfig dns_config
;
2324 NetworkChangeNotifier::GetDnsConfig(&dns_config
);
2327 net_log_
->AddGlobalEntry(
2328 NetLog::TYPE_DNS_CONFIG_CHANGED
,
2329 base::Bind(&NetLogDnsConfigCallback
, &dns_config
));
2332 // TODO(szym): Remove once http://crbug.com/137914 is resolved.
2333 received_dns_config_
= dns_config
.IsValid();
2334 // Conservatively assume local IPv6 is needed when DnsConfig is not valid.
2335 use_local_ipv6_
= !dns_config
.IsValid() || dns_config
.use_local_ipv6
;
2337 num_dns_failures_
= 0;
2339 // We want a new DnsSession in place, before we Abort running Jobs, so that
2340 // the newly started jobs use the new config.
2341 if (dns_client_
.get()) {
2342 dns_client_
->SetConfig(dns_config
);
2343 if (dns_client_
->GetConfig()) {
2344 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
2345 // If we just switched DnsClients, restart jobs using new resolver.
2346 // TODO(pauljensen): Is this necessary?
2347 config_changed
= true;
2351 if (config_changed
) {
2352 // If the DNS server has changed, existing cached info could be wrong so we
2353 // have to drop our internal cache :( Note that OS level DNS caches, such
2354 // as NSCD's cache should be dropped automatically by the OS when
2355 // resolv.conf changes so we don't need to do anything to clear that cache.
2359 // Life check to bail once |this| is deleted.
2360 base::WeakPtr
<HostResolverImpl
> self
= weak_ptr_factory_
.GetWeakPtr();
2362 // Existing jobs will have been sent to the original server so they need to
2364 AbortAllInProgressJobs();
2366 // |this| may be deleted inside AbortAllInProgressJobs().
2368 TryServingAllJobsFromHosts();
2372 bool HostResolverImpl::HaveDnsConfig() const {
2373 // Use DnsClient only if it's fully configured and there is no override by
2374 // ScopedDefaultHostResolverProc.
2375 // The alternative is to use NetworkChangeNotifier to override DnsConfig,
2376 // but that would introduce construction order requirements for NCN and SDHRP.
2377 return (dns_client_
.get() != NULL
) && (dns_client_
->GetConfig() != NULL
) &&
2378 !(proc_params_
.resolver_proc
.get() == NULL
&&
2379 HostResolverProc::GetDefault() != NULL
);
2382 void HostResolverImpl::OnDnsTaskResolve(int net_error
) {
2383 DCHECK(dns_client_
);
2384 if (net_error
== OK
) {
2385 num_dns_failures_
= 0;
2388 ++num_dns_failures_
;
2389 if (num_dns_failures_
< kMaximumDnsFailures
)
2392 // Disable DnsClient until the next DNS change. Must be done before aborting
2393 // DnsTasks, since doing so may start new jobs.
2394 dns_client_
->SetConfig(DnsConfig());
2396 // Switch jobs with active DnsTasks over to using ProcTasks.
2399 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", false);
2400 UMA_HISTOGRAM_SPARSE_SLOWLY("AsyncDNS.DnsClientDisabledReason",
2401 std::abs(net_error
));
2404 void HostResolverImpl::SetDnsClient(scoped_ptr
<DnsClient
> dns_client
) {
2405 // DnsClient and config must be updated before aborting DnsTasks, since doing
2406 // so may start new jobs.
2407 dns_client_
= dns_client
.Pass();
2408 if (dns_client_
&& !dns_client_
->GetConfig() &&
2409 num_dns_failures_
< kMaximumDnsFailures
) {
2410 DnsConfig dns_config
;
2411 NetworkChangeNotifier::GetDnsConfig(&dns_config
);
2412 dns_client_
->SetConfig(dns_config
);
2413 num_dns_failures_
= 0;
2414 if (dns_client_
->GetConfig())
2415 UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);