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"
10 #include "base/bind.h"
11 #include "base/bind_helpers.h"
12 #include "base/memory/ref_counted.h"
13 #include "base/memory/scoped_vector.h"
14 #include "base/message_loop/message_loop.h"
15 #include "base/run_loop.h"
16 #include "base/strings/string_util.h"
17 #include "base/strings/stringprintf.h"
18 #include "base/synchronization/condition_variable.h"
19 #include "base/synchronization/lock.h"
20 #include "base/test/test_timeouts.h"
21 #include "base/time/time.h"
22 #include "net/base/address_list.h"
23 #include "net/base/net_errors.h"
24 #include "net/base/net_util.h"
25 #include "net/dns/dns_client.h"
26 #include "net/dns/dns_test_util.h"
27 #include "net/dns/mock_host_resolver.h"
28 #include "testing/gtest/include/gtest/gtest.h"
34 const size_t kMaxJobs
= 10u;
35 const size_t kMaxRetryAttempts
= 4u;
37 HostResolver::Options
DefaultOptions() {
38 HostResolver::Options options
;
39 options
.max_concurrent_resolves
= kMaxJobs
;
40 options
.max_retry_attempts
= kMaxRetryAttempts
;
41 options
.enable_caching
= true;
45 HostResolverImpl::ProcTaskParams
DefaultParams(
46 HostResolverProc
* resolver_proc
) {
47 return HostResolverImpl::ProcTaskParams(resolver_proc
, kMaxRetryAttempts
);
50 // A HostResolverProc that pushes each host mapped into a list and allows
51 // waiting for a specific number of requests. Unlike RuleBasedHostResolverProc
52 // it never calls SystemHostResolverCall. By default resolves all hostnames to
53 // "127.0.0.1". After AddRule(), it resolves only names explicitly specified.
54 class MockHostResolverProc
: public HostResolverProc
{
57 ResolveKey(const std::string
& hostname
, AddressFamily address_family
)
58 : hostname(hostname
), address_family(address_family
) {}
59 bool operator<(const ResolveKey
& other
) const {
60 return address_family
< other
.address_family
||
61 (address_family
== other
.address_family
&& hostname
< other
.hostname
);
64 AddressFamily address_family
;
67 typedef std::vector
<ResolveKey
> CaptureList
;
69 MockHostResolverProc()
70 : HostResolverProc(NULL
),
71 num_requests_waiting_(0),
72 num_slots_available_(0),
73 requests_waiting_(&lock_
),
74 slots_available_(&lock_
) {
77 // Waits until |count| calls to |Resolve| are blocked. Returns false when
79 bool WaitFor(unsigned count
) {
80 base::AutoLock
lock(lock_
);
81 base::Time start_time
= base::Time::Now();
82 while (num_requests_waiting_
< count
) {
83 requests_waiting_
.TimedWait(TestTimeouts::action_timeout());
84 if (base::Time::Now() > start_time
+ TestTimeouts::action_timeout())
90 // Signals |count| waiting calls to |Resolve|. First come first served.
91 void SignalMultiple(unsigned count
) {
92 base::AutoLock
lock(lock_
);
93 num_slots_available_
+= count
;
94 slots_available_
.Broadcast();
97 // Signals all waiting calls to |Resolve|. Beware of races.
99 base::AutoLock
lock(lock_
);
100 num_slots_available_
= num_requests_waiting_
;
101 slots_available_
.Broadcast();
104 void AddRule(const std::string
& hostname
, AddressFamily family
,
105 const AddressList
& result
) {
106 base::AutoLock
lock(lock_
);
107 rules_
[ResolveKey(hostname
, family
)] = result
;
110 void AddRule(const std::string
& hostname
, AddressFamily family
,
111 const std::string
& ip_list
) {
113 int rv
= ParseAddressList(ip_list
, std::string(), &result
);
115 AddRule(hostname
, family
, result
);
118 void AddRuleForAllFamilies(const std::string
& hostname
,
119 const std::string
& ip_list
) {
121 int rv
= ParseAddressList(ip_list
, std::string(), &result
);
123 AddRule(hostname
, ADDRESS_FAMILY_UNSPECIFIED
, result
);
124 AddRule(hostname
, ADDRESS_FAMILY_IPV4
, result
);
125 AddRule(hostname
, ADDRESS_FAMILY_IPV6
, result
);
128 int Resolve(const std::string
& hostname
,
129 AddressFamily address_family
,
130 HostResolverFlags host_resolver_flags
,
131 AddressList
* addrlist
,
132 int* os_error
) override
{
133 base::AutoLock
lock(lock_
);
134 capture_list_
.push_back(ResolveKey(hostname
, address_family
));
135 ++num_requests_waiting_
;
136 requests_waiting_
.Broadcast();
137 while (!num_slots_available_
)
138 slots_available_
.Wait();
139 DCHECK_GT(num_requests_waiting_
, 0u);
140 --num_slots_available_
;
141 --num_requests_waiting_
;
142 if (rules_
.empty()) {
143 int rv
= ParseAddressList("127.0.0.1", std::string(), addrlist
);
147 ResolveKey
key(hostname
, address_family
);
148 if (rules_
.count(key
) == 0)
149 return ERR_NAME_NOT_RESOLVED
;
150 *addrlist
= rules_
[key
];
154 CaptureList
GetCaptureList() const {
157 base::AutoLock
lock(lock_
);
158 copy
= capture_list_
;
163 bool HasBlockedRequests() const {
164 base::AutoLock
lock(lock_
);
165 return num_requests_waiting_
> num_slots_available_
;
169 ~MockHostResolverProc() override
{}
172 mutable base::Lock lock_
;
173 std::map
<ResolveKey
, AddressList
> rules_
;
174 CaptureList capture_list_
;
175 unsigned num_requests_waiting_
;
176 unsigned num_slots_available_
;
177 base::ConditionVariable requests_waiting_
;
178 base::ConditionVariable slots_available_
;
180 DISALLOW_COPY_AND_ASSIGN(MockHostResolverProc
);
183 bool AddressListContains(const AddressList
& list
, const std::string
& address
,
186 bool rv
= ParseIPLiteralToNumber(address
, &ip
);
188 return std::find(list
.begin(),
190 IPEndPoint(ip
, port
)) != list
.end();
193 // A wrapper for requests to a HostResolver.
196 // Base class of handlers to be executed on completion of requests.
198 virtual ~Handler() {}
199 virtual void Handle(Request
* request
) = 0;
202 Request(const HostResolver::RequestInfo
& info
,
203 RequestPriority priority
,
205 HostResolver
* resolver
,
212 quit_on_complete_(false),
213 result_(ERR_UNEXPECTED
),
219 list_
= AddressList();
220 result_
= resolver_
->Resolve(
224 base::Bind(&Request::OnComplete
, base::Unretained(this)),
228 EXPECT_EQ(OK
, result_
);
232 int ResolveFromCache() {
235 return resolver_
->ResolveFromCache(info_
, &list_
, BoundNetLog());
241 resolver_
->CancelRequest(handle_
);
245 const HostResolver::RequestInfo
& info() const { return info_
; }
246 size_t index() const { return index_
; }
247 const AddressList
& list() const { return list_
; }
248 int result() const { return result_
; }
249 bool completed() const { return result_
!= ERR_IO_PENDING
; }
250 bool pending() const { return handle_
!= NULL
; }
252 bool HasAddress(const std::string
& address
, uint16 port
) const {
253 return AddressListContains(list_
, address
, port
);
256 // Returns the number of addresses in |list_|.
257 unsigned NumberOfAddresses() const {
261 bool HasOneAddress(const std::string
& address
, uint16 port
) const {
262 return HasAddress(address
, port
) && (NumberOfAddresses() == 1u);
265 // Returns ERR_UNEXPECTED if timed out.
266 int WaitForResult() {
269 base::CancelableClosure
closure(base::MessageLoop::QuitClosure());
270 base::MessageLoop::current()->PostDelayedTask(
271 FROM_HERE
, closure
.callback(), TestTimeouts::action_max_timeout());
272 quit_on_complete_
= true;
273 base::MessageLoop::current()->Run();
274 bool did_quit
= !quit_on_complete_
;
275 quit_on_complete_
= false;
280 return ERR_UNEXPECTED
;
284 void OnComplete(int rv
) {
285 EXPECT_TRUE(pending());
286 EXPECT_EQ(ERR_IO_PENDING
, result_
);
287 EXPECT_NE(ERR_IO_PENDING
, rv
);
290 if (!list_
.empty()) {
291 EXPECT_EQ(OK
, result_
);
292 EXPECT_EQ(info_
.port(), list_
.front().port());
295 handler_
->Handle(this);
296 if (quit_on_complete_
) {
297 base::MessageLoop::current()->Quit();
298 quit_on_complete_
= false;
302 HostResolver::RequestInfo info_
;
303 RequestPriority priority_
;
305 HostResolver
* resolver_
;
307 bool quit_on_complete_
;
311 HostResolver::RequestHandle handle_
;
313 DISALLOW_COPY_AND_ASSIGN(Request
);
316 // Using LookupAttemptHostResolverProc simulate very long lookups, and control
317 // which attempt resolves the host.
318 class LookupAttemptHostResolverProc
: public HostResolverProc
{
320 LookupAttemptHostResolverProc(HostResolverProc
* previous
,
321 int attempt_number_to_resolve
,
323 : HostResolverProc(previous
),
324 attempt_number_to_resolve_(attempt_number_to_resolve
),
325 current_attempt_number_(0),
326 total_attempts_(total_attempts
),
327 total_attempts_resolved_(0),
328 resolved_attempt_number_(0),
332 // Test harness will wait for all attempts to finish before checking the
334 void WaitForAllAttemptsToFinish(const base::TimeDelta
& wait_time
) {
335 base::TimeTicks end_time
= base::TimeTicks::Now() + wait_time
;
337 base::AutoLock
auto_lock(lock_
);
338 while (total_attempts_resolved_
!= total_attempts_
&&
339 base::TimeTicks::Now() < end_time
) {
340 all_done_
.TimedWait(end_time
- base::TimeTicks::Now());
345 // All attempts will wait for an attempt to resolve the host.
346 void WaitForAnAttemptToComplete() {
347 base::TimeDelta wait_time
= base::TimeDelta::FromSeconds(60);
348 base::TimeTicks end_time
= base::TimeTicks::Now() + wait_time
;
350 base::AutoLock
auto_lock(lock_
);
351 while (resolved_attempt_number_
== 0 && base::TimeTicks::Now() < end_time
)
352 all_done_
.TimedWait(end_time
- base::TimeTicks::Now());
354 all_done_
.Broadcast(); // Tell all waiting attempts to proceed.
357 // Returns the number of attempts that have finished the Resolve() method.
358 int total_attempts_resolved() { return total_attempts_resolved_
; }
360 // Returns the first attempt that that has resolved the host.
361 int resolved_attempt_number() { return resolved_attempt_number_
; }
363 // HostResolverProc methods.
364 int Resolve(const std::string
& host
,
365 AddressFamily address_family
,
366 HostResolverFlags host_resolver_flags
,
367 AddressList
* addrlist
,
368 int* os_error
) override
{
369 bool wait_for_right_attempt_to_complete
= true;
371 base::AutoLock
auto_lock(lock_
);
372 ++current_attempt_number_
;
373 if (current_attempt_number_
== attempt_number_to_resolve_
) {
374 resolved_attempt_number_
= current_attempt_number_
;
375 wait_for_right_attempt_to_complete
= false;
379 if (wait_for_right_attempt_to_complete
)
380 // Wait for the attempt_number_to_resolve_ attempt to resolve.
381 WaitForAnAttemptToComplete();
383 int result
= ResolveUsingPrevious(host
, address_family
, host_resolver_flags
,
387 base::AutoLock
auto_lock(lock_
);
388 ++total_attempts_resolved_
;
391 all_done_
.Broadcast(); // Tell all attempts to proceed.
393 // Since any negative number is considered a network error, with -1 having
394 // special meaning (ERR_IO_PENDING). We could return the attempt that has
395 // resolved the host as a negative number. For example, if attempt number 3
396 // resolves the host, then this method returns -4.
398 return -1 - resolved_attempt_number_
;
404 ~LookupAttemptHostResolverProc() override
{}
407 int attempt_number_to_resolve_
;
408 int current_attempt_number_
; // Incremented whenever Resolve is called.
410 int total_attempts_resolved_
;
411 int resolved_attempt_number_
;
413 // All attempts wait for right attempt to be resolve.
415 base::ConditionVariable all_done_
;
420 class HostResolverImplTest
: public testing::Test
{
422 static const int kDefaultPort
= 80;
424 HostResolverImplTest() : proc_(new MockHostResolverProc()) {}
426 void CreateResolver() {
427 CreateResolverWithLimitsAndParams(kMaxJobs
,
428 DefaultParams(proc_
.get()));
431 // This HostResolverImpl will only allow 1 outstanding resolve at a time and
432 // perform no retries.
433 void CreateSerialResolver() {
434 HostResolverImpl::ProcTaskParams params
= DefaultParams(proc_
.get());
435 params
.max_retry_attempts
= 0u;
436 CreateResolverWithLimitsAndParams(1u, params
);
440 // A Request::Handler which is a proxy to the HostResolverImplTest fixture.
441 struct Handler
: public Request::Handler
{
442 ~Handler() override
{}
444 // Proxy functions so that classes derived from Handler can access them.
445 Request
* CreateRequest(const HostResolver::RequestInfo
& info
,
446 RequestPriority priority
) {
447 return test
->CreateRequest(info
, priority
);
449 Request
* CreateRequest(const std::string
& hostname
, int port
) {
450 return test
->CreateRequest(hostname
, port
);
452 Request
* CreateRequest(const std::string
& hostname
) {
453 return test
->CreateRequest(hostname
);
455 ScopedVector
<Request
>& requests() { return test
->requests_
; }
457 void DeleteResolver() { test
->resolver_
.reset(); }
459 HostResolverImplTest
* test
;
462 // testing::Test implementation:
463 void SetUp() override
{ CreateResolver(); }
465 void TearDown() override
{
467 EXPECT_EQ(0u, resolver_
->num_running_dispatcher_jobs_for_tests());
468 EXPECT_FALSE(proc_
->HasBlockedRequests());
471 virtual void CreateResolverWithLimitsAndParams(
472 size_t max_concurrent_resolves
,
473 const HostResolverImpl::ProcTaskParams
& params
) {
474 HostResolverImpl::Options options
= DefaultOptions();
475 options
.max_concurrent_resolves
= max_concurrent_resolves
;
476 resolver_
.reset(new HostResolverImpl(options
, NULL
));
477 resolver_
->set_proc_params_for_test(params
);
480 // The Request will not be made until a call to |Resolve()|, and the Job will
481 // not start until released by |proc_->SignalXXX|.
482 Request
* CreateRequest(const HostResolver::RequestInfo
& info
,
483 RequestPriority priority
) {
484 Request
* req
= new Request(
485 info
, priority
, requests_
.size(), resolver_
.get(), handler_
.get());
486 requests_
.push_back(req
);
490 Request
* CreateRequest(const std::string
& hostname
,
492 RequestPriority priority
,
493 AddressFamily family
) {
494 HostResolver::RequestInfo
info(HostPortPair(hostname
, port
));
495 info
.set_address_family(family
);
496 return CreateRequest(info
, priority
);
499 Request
* CreateRequest(const std::string
& hostname
,
501 RequestPriority priority
) {
502 return CreateRequest(hostname
, port
, priority
, ADDRESS_FAMILY_UNSPECIFIED
);
505 Request
* CreateRequest(const std::string
& hostname
, int port
) {
506 return CreateRequest(hostname
, port
, MEDIUM
);
509 Request
* CreateRequest(const std::string
& hostname
) {
510 return CreateRequest(hostname
, kDefaultPort
);
513 void set_handler(Handler
* handler
) {
514 handler_
.reset(handler
);
515 handler_
->test
= this;
518 // Friendship is not inherited, so use proxies to access those.
519 size_t num_running_dispatcher_jobs() const {
520 DCHECK(resolver_
.get());
521 return resolver_
->num_running_dispatcher_jobs_for_tests();
524 void set_fallback_to_proctask(bool fallback_to_proctask
) {
525 DCHECK(resolver_
.get());
526 resolver_
->fallback_to_proctask_
= fallback_to_proctask
;
529 static unsigned maximum_dns_failures() {
530 return HostResolverImpl::kMaximumDnsFailures
;
533 scoped_refptr
<MockHostResolverProc
> proc_
;
534 scoped_ptr
<HostResolverImpl
> resolver_
;
535 ScopedVector
<Request
> requests_
;
537 scoped_ptr
<Handler
> handler_
;
540 TEST_F(HostResolverImplTest
, AsynchronousLookup
) {
541 proc_
->AddRuleForAllFamilies("just.testing", "192.168.1.42");
542 proc_
->SignalMultiple(1u);
544 Request
* req
= CreateRequest("just.testing", 80);
545 EXPECT_EQ(ERR_IO_PENDING
, req
->Resolve());
546 EXPECT_EQ(OK
, req
->WaitForResult());
548 EXPECT_TRUE(req
->HasOneAddress("192.168.1.42", 80));
550 EXPECT_EQ("just.testing", proc_
->GetCaptureList()[0].hostname
);
553 TEST_F(HostResolverImplTest
, LocalhostLookup
) {
554 proc_
->SignalMultiple(1u);
555 Request
* req
= CreateRequest("foo.localhost", 80);
556 EXPECT_EQ(ERR_IO_PENDING
, req
->Resolve());
557 EXPECT_EQ(OK
, req
->WaitForResult());
559 EXPECT_TRUE(req
->HasOneAddress("127.0.0.1", 80));
561 EXPECT_EQ("localhost.", proc_
->GetCaptureList()[0].hostname
);
564 TEST_F(HostResolverImplTest
, EmptyListMeansNameNotResolved
) {
565 proc_
->AddRuleForAllFamilies("just.testing", "");
566 proc_
->SignalMultiple(1u);
568 Request
* req
= CreateRequest("just.testing", 80);
569 EXPECT_EQ(ERR_IO_PENDING
, req
->Resolve());
570 EXPECT_EQ(ERR_NAME_NOT_RESOLVED
, req
->WaitForResult());
571 EXPECT_EQ(0u, req
->NumberOfAddresses());
572 EXPECT_EQ("just.testing", proc_
->GetCaptureList()[0].hostname
);
575 TEST_F(HostResolverImplTest
, FailedAsynchronousLookup
) {
576 proc_
->AddRuleForAllFamilies(std::string(),
577 "0.0.0.0"); // Default to failures.
578 proc_
->SignalMultiple(1u);
580 Request
* req
= CreateRequest("just.testing", 80);
581 EXPECT_EQ(ERR_IO_PENDING
, req
->Resolve());
582 EXPECT_EQ(ERR_NAME_NOT_RESOLVED
, req
->WaitForResult());
584 EXPECT_EQ("just.testing", proc_
->GetCaptureList()[0].hostname
);
586 // Also test that the error is not cached.
587 EXPECT_EQ(ERR_DNS_CACHE_MISS
, req
->ResolveFromCache());
590 TEST_F(HostResolverImplTest
, AbortedAsynchronousLookup
) {
591 Request
* req0
= CreateRequest("just.testing", 80);
592 EXPECT_EQ(ERR_IO_PENDING
, req0
->Resolve());
594 EXPECT_TRUE(proc_
->WaitFor(1u));
596 // Resolver is destroyed while job is running on WorkerPool.
601 // To ensure there was no spurious callback, complete with a new resolver.
603 Request
* req1
= CreateRequest("just.testing", 80);
604 EXPECT_EQ(ERR_IO_PENDING
, req1
->Resolve());
606 proc_
->SignalMultiple(2u);
608 EXPECT_EQ(OK
, req1
->WaitForResult());
610 // This request was canceled.
611 EXPECT_FALSE(req0
->completed());
614 #if defined(THREAD_SANITIZER)
615 // Use of WorkerPool in HostResolverImpl causes a data race. crbug.com/334140
616 #define MAYBE_NumericIPv4Address DISABLED_NumericIPv4Address
618 #define MAYBE_NumericIPv4Address NumericIPv4Address
620 TEST_F(HostResolverImplTest
, MAYBE_NumericIPv4Address
) {
621 // Stevens says dotted quads with AI_UNSPEC resolve to a single sockaddr_in.
622 Request
* req
= CreateRequest("127.1.2.3", 5555);
623 EXPECT_EQ(OK
, req
->Resolve());
625 EXPECT_TRUE(req
->HasOneAddress("127.1.2.3", 5555));
628 #if defined(THREAD_SANITIZER)
629 // Use of WorkerPool in HostResolverImpl causes a data race. crbug.com/334140
630 #define MAYBE_NumericIPv6Address DISABLED_NumericIPv6Address
632 #define MAYBE_NumericIPv6Address NumericIPv6Address
634 TEST_F(HostResolverImplTest
, MAYBE_NumericIPv6Address
) {
635 // Resolve a plain IPv6 address. Don't worry about [brackets], because
636 // the caller should have removed them.
637 Request
* req
= CreateRequest("2001:db8::1", 5555);
638 EXPECT_EQ(OK
, req
->Resolve());
640 EXPECT_TRUE(req
->HasOneAddress("2001:db8::1", 5555));
643 #if defined(THREAD_SANITIZER)
644 // Use of WorkerPool in HostResolverImpl causes a data race. crbug.com/334140
645 #define MAYBE_EmptyHost DISABLED_EmptyHost
647 #define MAYBE_EmptyHost EmptyHost
649 TEST_F(HostResolverImplTest
, MAYBE_EmptyHost
) {
650 Request
* req
= CreateRequest(std::string(), 5555);
651 EXPECT_EQ(ERR_NAME_NOT_RESOLVED
, req
->Resolve());
654 #if defined(THREAD_SANITIZER)
655 // There's a data race in this test that may lead to use-after-free.
656 // If the test starts to crash without ThreadSanitizer it needs to be disabled
657 // globally. See http://crbug.com/268946 (stacks for this test in
658 // crbug.com/333567).
659 #define MAYBE_EmptyDotsHost DISABLED_EmptyDotsHost
661 #define MAYBE_EmptyDotsHost EmptyDotsHost
663 TEST_F(HostResolverImplTest
, MAYBE_EmptyDotsHost
) {
664 for (int i
= 0; i
< 16; ++i
) {
665 Request
* req
= CreateRequest(std::string(i
, '.'), 5555);
666 EXPECT_EQ(ERR_NAME_NOT_RESOLVED
, req
->Resolve());
670 #if defined(THREAD_SANITIZER)
671 // There's a data race in this test that may lead to use-after-free.
672 // If the test starts to crash without ThreadSanitizer it needs to be disabled
673 // globally. See http://crbug.com/268946.
674 #define MAYBE_LongHost DISABLED_LongHost
676 #define MAYBE_LongHost LongHost
678 TEST_F(HostResolverImplTest
, MAYBE_LongHost
) {
679 Request
* req
= CreateRequest(std::string(4097, 'a'), 5555);
680 EXPECT_EQ(ERR_NAME_NOT_RESOLVED
, req
->Resolve());
683 TEST_F(HostResolverImplTest
, DeDupeRequests
) {
684 // Start 5 requests, duplicating hosts "a" and "b". Since the resolver_proc is
685 // blocked, these should all pile up until we signal it.
686 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("a", 80)->Resolve());
687 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("b", 80)->Resolve());
688 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("b", 81)->Resolve());
689 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("a", 82)->Resolve());
690 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("b", 83)->Resolve());
692 proc_
->SignalMultiple(2u); // One for "a", one for "b".
694 for (size_t i
= 0; i
< requests_
.size(); ++i
) {
695 EXPECT_EQ(OK
, requests_
[i
]->WaitForResult()) << i
;
699 TEST_F(HostResolverImplTest
, CancelMultipleRequests
) {
700 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("a", 80)->Resolve());
701 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("b", 80)->Resolve());
702 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("b", 81)->Resolve());
703 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("a", 82)->Resolve());
704 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("b", 83)->Resolve());
706 // Cancel everything except request for ("a", 82).
707 requests_
[0]->Cancel();
708 requests_
[1]->Cancel();
709 requests_
[2]->Cancel();
710 requests_
[4]->Cancel();
712 proc_
->SignalMultiple(2u); // One for "a", one for "b".
714 EXPECT_EQ(OK
, requests_
[3]->WaitForResult());
717 TEST_F(HostResolverImplTest
, CanceledRequestsReleaseJobSlots
) {
718 // Fill up the dispatcher and queue.
719 for (unsigned i
= 0; i
< kMaxJobs
+ 1; ++i
) {
720 std::string hostname
= "a_";
721 hostname
[1] = 'a' + i
;
722 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest(hostname
, 80)->Resolve());
723 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest(hostname
, 81)->Resolve());
726 EXPECT_TRUE(proc_
->WaitFor(kMaxJobs
));
728 // Cancel all but last two.
729 for (unsigned i
= 0; i
< requests_
.size() - 2; ++i
) {
730 requests_
[i
]->Cancel();
733 EXPECT_TRUE(proc_
->WaitFor(kMaxJobs
+ 1));
737 size_t num_requests
= requests_
.size();
738 EXPECT_EQ(OK
, requests_
[num_requests
- 1]->WaitForResult());
739 EXPECT_EQ(OK
, requests_
[num_requests
- 2]->result());
742 TEST_F(HostResolverImplTest
, CancelWithinCallback
) {
743 struct MyHandler
: public Handler
{
744 void Handle(Request
* req
) override
{
745 // Port 80 is the first request that the callback will be invoked for.
746 // While we are executing within that callback, cancel the other requests
747 // in the job and start another request.
748 if (req
->index() == 0) {
749 // Once "a:80" completes, it will cancel "a:81" and "a:82".
750 requests()[1]->Cancel();
751 requests()[2]->Cancel();
755 set_handler(new MyHandler());
757 for (size_t i
= 0; i
< 4; ++i
) {
758 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("a", 80 + i
)->Resolve()) << i
;
761 proc_
->SignalMultiple(2u); // One for "a". One for "finalrequest".
763 EXPECT_EQ(OK
, requests_
[0]->WaitForResult());
765 Request
* final_request
= CreateRequest("finalrequest", 70);
766 EXPECT_EQ(ERR_IO_PENDING
, final_request
->Resolve());
767 EXPECT_EQ(OK
, final_request
->WaitForResult());
768 EXPECT_TRUE(requests_
[3]->completed());
771 TEST_F(HostResolverImplTest
, DeleteWithinCallback
) {
772 struct MyHandler
: public Handler
{
773 void Handle(Request
* req
) override
{
774 EXPECT_EQ("a", req
->info().hostname());
775 EXPECT_EQ(80, req
->info().port());
779 // Quit after returning from OnCompleted (to give it a chance at
780 // incorrectly running the cancelled tasks).
781 base::MessageLoop::current()->PostTask(FROM_HERE
,
782 base::MessageLoop::QuitClosure());
785 set_handler(new MyHandler());
787 for (size_t i
= 0; i
< 4; ++i
) {
788 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("a", 80 + i
)->Resolve()) << i
;
791 proc_
->SignalMultiple(1u); // One for "a".
793 // |MyHandler| will send quit message once all the requests have finished.
794 base::MessageLoop::current()->Run();
797 TEST_F(HostResolverImplTest
, DeleteWithinAbortedCallback
) {
798 struct MyHandler
: public Handler
{
799 void Handle(Request
* req
) override
{
800 EXPECT_EQ("a", req
->info().hostname());
801 EXPECT_EQ(80, req
->info().port());
805 // Quit after returning from OnCompleted (to give it a chance at
806 // incorrectly running the cancelled tasks).
807 base::MessageLoop::current()->PostTask(FROM_HERE
,
808 base::MessageLoop::QuitClosure());
811 set_handler(new MyHandler());
813 // This test assumes that the Jobs will be Aborted in order ["a", "b"]
814 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("a", 80)->Resolve());
815 // HostResolverImpl will be deleted before later Requests can complete.
816 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("a", 81)->Resolve());
817 // Job for 'b' will be aborted before it can complete.
818 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("b", 82)->Resolve());
819 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("b", 83)->Resolve());
821 EXPECT_TRUE(proc_
->WaitFor(1u));
823 // Triggering an IP address change.
824 NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
826 // |MyHandler| will send quit message once all the requests have finished.
827 base::MessageLoop::current()->Run();
829 EXPECT_EQ(ERR_NETWORK_CHANGED
, requests_
[0]->result());
830 EXPECT_EQ(ERR_IO_PENDING
, requests_
[1]->result());
831 EXPECT_EQ(ERR_IO_PENDING
, requests_
[2]->result());
832 EXPECT_EQ(ERR_IO_PENDING
, requests_
[3]->result());
834 proc_
->SignalMultiple(requests_
.size());
837 TEST_F(HostResolverImplTest
, StartWithinCallback
) {
838 struct MyHandler
: public Handler
{
839 void Handle(Request
* req
) override
{
840 if (req
->index() == 0) {
841 // On completing the first request, start another request for "a".
842 // Since caching is disabled, this will result in another async request.
843 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("a", 70)->Resolve());
847 set_handler(new MyHandler());
849 // Turn off caching for this host resolver.
850 HostResolver::Options options
= DefaultOptions();
851 options
.enable_caching
= false;
852 resolver_
.reset(new HostResolverImpl(options
, NULL
));
853 resolver_
->set_proc_params_for_test(DefaultParams(proc_
.get()));
855 for (size_t i
= 0; i
< 4; ++i
) {
856 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("a", 80 + i
)->Resolve()) << i
;
859 proc_
->SignalMultiple(2u); // One for "a". One for the second "a".
861 EXPECT_EQ(OK
, requests_
[0]->WaitForResult());
862 ASSERT_EQ(5u, requests_
.size());
863 EXPECT_EQ(OK
, requests_
.back()->WaitForResult());
865 EXPECT_EQ(2u, proc_
->GetCaptureList().size());
868 TEST_F(HostResolverImplTest
, BypassCache
) {
869 struct MyHandler
: public Handler
{
870 void Handle(Request
* req
) override
{
871 if (req
->index() == 0) {
872 // On completing the first request, start another request for "a".
873 // Since caching is enabled, this should complete synchronously.
874 std::string hostname
= req
->info().hostname();
875 EXPECT_EQ(OK
, CreateRequest(hostname
, 70)->Resolve());
876 EXPECT_EQ(OK
, CreateRequest(hostname
, 75)->ResolveFromCache());
878 // Ok good. Now make sure that if we ask to bypass the cache, it can no
879 // longer service the request synchronously.
880 HostResolver::RequestInfo
info(HostPortPair(hostname
, 71));
881 info
.set_allow_cached_response(false);
882 EXPECT_EQ(ERR_IO_PENDING
,
883 CreateRequest(info
, DEFAULT_PRIORITY
)->Resolve());
884 } else if (71 == req
->info().port()) {
886 base::MessageLoop::current()->Quit();
888 FAIL() << "Unexpected request";
892 set_handler(new MyHandler());
894 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("a", 80)->Resolve());
895 proc_
->SignalMultiple(3u); // Only need two, but be generous.
897 // |verifier| will send quit message once all the requests have finished.
898 base::MessageLoop::current()->Run();
899 EXPECT_EQ(2u, proc_
->GetCaptureList().size());
902 // Test that IP address changes flush the cache but initial DNS config reads do
904 TEST_F(HostResolverImplTest
, FlushCacheOnIPAddressChange
) {
905 proc_
->SignalMultiple(2u); // One before the flush, one after.
907 Request
* req
= CreateRequest("host1", 70);
908 EXPECT_EQ(ERR_IO_PENDING
, req
->Resolve());
909 EXPECT_EQ(OK
, req
->WaitForResult());
911 req
= CreateRequest("host1", 75);
912 EXPECT_EQ(OK
, req
->Resolve()); // Should complete synchronously.
914 // Verify initial DNS config read does not flush cache.
915 NetworkChangeNotifier::NotifyObserversOfInitialDNSConfigReadForTests();
916 req
= CreateRequest("host1", 75);
917 EXPECT_EQ(OK
, req
->Resolve()); // Should complete synchronously.
919 // Flush cache by triggering an IP address change.
920 NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
921 base::MessageLoop::current()->RunUntilIdle(); // Notification happens async.
923 // Resolve "host1" again -- this time it won't be served from cache, so it
924 // will complete asynchronously.
925 req
= CreateRequest("host1", 80);
926 EXPECT_EQ(ERR_IO_PENDING
, req
->Resolve());
927 EXPECT_EQ(OK
, req
->WaitForResult());
930 // Test that IP address changes send ERR_NETWORK_CHANGED to pending requests.
931 TEST_F(HostResolverImplTest
, AbortOnIPAddressChanged
) {
932 Request
* req
= CreateRequest("host1", 70);
933 EXPECT_EQ(ERR_IO_PENDING
, req
->Resolve());
935 EXPECT_TRUE(proc_
->WaitFor(1u));
936 // Triggering an IP address change.
937 NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
938 base::MessageLoop::current()->RunUntilIdle(); // Notification happens async.
941 EXPECT_EQ(ERR_NETWORK_CHANGED
, req
->WaitForResult());
942 EXPECT_EQ(0u, resolver_
->GetHostCache()->size());
945 // Test that initial DNS config read signals do not abort pending requests.
946 TEST_F(HostResolverImplTest
, DontAbortOnInitialDNSConfigRead
) {
947 Request
* req
= CreateRequest("host1", 70);
948 EXPECT_EQ(ERR_IO_PENDING
, req
->Resolve());
950 EXPECT_TRUE(proc_
->WaitFor(1u));
951 // Triggering initial DNS config read signal.
952 NetworkChangeNotifier::NotifyObserversOfInitialDNSConfigReadForTests();
953 base::MessageLoop::current()->RunUntilIdle(); // Notification happens async.
956 EXPECT_EQ(OK
, req
->WaitForResult());
959 // Obey pool constraints after IP address has changed.
960 TEST_F(HostResolverImplTest
, ObeyPoolConstraintsAfterIPAddressChange
) {
961 // Runs at most one job at a time.
962 CreateSerialResolver();
963 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("a")->Resolve());
964 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("b")->Resolve());
965 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("c")->Resolve());
967 EXPECT_TRUE(proc_
->WaitFor(1u));
968 // Triggering an IP address change.
969 NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
970 base::MessageLoop::current()->RunUntilIdle(); // Notification happens async.
971 proc_
->SignalMultiple(3u); // Let the false-start go so that we can catch it.
973 EXPECT_EQ(ERR_NETWORK_CHANGED
, requests_
[0]->WaitForResult());
975 EXPECT_EQ(1u, num_running_dispatcher_jobs());
977 EXPECT_FALSE(requests_
[1]->completed());
978 EXPECT_FALSE(requests_
[2]->completed());
980 EXPECT_EQ(OK
, requests_
[2]->WaitForResult());
981 EXPECT_EQ(OK
, requests_
[1]->result());
984 // Tests that a new Request made from the callback of a previously aborted one
985 // will not be aborted.
986 TEST_F(HostResolverImplTest
, AbortOnlyExistingRequestsOnIPAddressChange
) {
987 struct MyHandler
: public Handler
{
988 void Handle(Request
* req
) override
{
989 // Start new request for a different hostname to ensure that the order
990 // of jobs in HostResolverImpl is not stable.
991 std::string hostname
;
992 if (req
->index() == 0)
994 else if (req
->index() == 1)
996 else if (req
->index() == 2)
999 return; // A request started from within MyHandler.
1000 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest(hostname
)->Resolve()) << hostname
;
1003 set_handler(new MyHandler());
1005 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("bbb")->Resolve());
1006 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("eee")->Resolve());
1007 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("ccc")->Resolve());
1009 // Wait until all are blocked;
1010 EXPECT_TRUE(proc_
->WaitFor(3u));
1011 // Trigger an IP address change.
1012 NetworkChangeNotifier::NotifyObserversOfIPAddressChangeForTests();
1013 // This should abort all running jobs.
1014 base::MessageLoop::current()->RunUntilIdle();
1015 EXPECT_EQ(ERR_NETWORK_CHANGED
, requests_
[0]->result());
1016 EXPECT_EQ(ERR_NETWORK_CHANGED
, requests_
[1]->result());
1017 EXPECT_EQ(ERR_NETWORK_CHANGED
, requests_
[2]->result());
1018 ASSERT_EQ(6u, requests_
.size());
1019 // Unblock all calls to proc.
1020 proc_
->SignalMultiple(requests_
.size());
1021 // Run until the re-started requests finish.
1022 EXPECT_EQ(OK
, requests_
[3]->WaitForResult());
1023 EXPECT_EQ(OK
, requests_
[4]->WaitForResult());
1024 EXPECT_EQ(OK
, requests_
[5]->WaitForResult());
1025 // Verify that results of aborted Jobs were not cached.
1026 EXPECT_EQ(6u, proc_
->GetCaptureList().size());
1027 EXPECT_EQ(3u, resolver_
->GetHostCache()->size());
1030 // Tests that when the maximum threads is set to 1, requests are dequeued
1031 // in order of priority.
1032 TEST_F(HostResolverImplTest
, HigherPriorityRequestsStartedFirst
) {
1033 CreateSerialResolver();
1035 // Note that at this point the MockHostResolverProc is blocked, so any
1036 // requests we make will not complete.
1037 CreateRequest("req0", 80, LOW
);
1038 CreateRequest("req1", 80, MEDIUM
);
1039 CreateRequest("req2", 80, MEDIUM
);
1040 CreateRequest("req3", 80, LOW
);
1041 CreateRequest("req4", 80, HIGHEST
);
1042 CreateRequest("req5", 80, LOW
);
1043 CreateRequest("req6", 80, LOW
);
1044 CreateRequest("req5", 80, HIGHEST
);
1046 for (size_t i
= 0; i
< requests_
.size(); ++i
) {
1047 EXPECT_EQ(ERR_IO_PENDING
, requests_
[i
]->Resolve()) << i
;
1050 // Unblock the resolver thread so the requests can run.
1051 proc_
->SignalMultiple(requests_
.size()); // More than needed.
1053 // Wait for all the requests to complete succesfully.
1054 for (size_t i
= 0; i
< requests_
.size(); ++i
) {
1055 EXPECT_EQ(OK
, requests_
[i
]->WaitForResult()) << i
;
1058 // Since we have restricted to a single concurrent thread in the jobpool,
1059 // the requests should complete in order of priority (with the exception
1060 // of the first request, which gets started right away, since there is
1061 // nothing outstanding).
1062 MockHostResolverProc::CaptureList capture_list
= proc_
->GetCaptureList();
1063 ASSERT_EQ(7u, capture_list
.size());
1065 EXPECT_EQ("req0", capture_list
[0].hostname
);
1066 EXPECT_EQ("req4", capture_list
[1].hostname
);
1067 EXPECT_EQ("req5", capture_list
[2].hostname
);
1068 EXPECT_EQ("req1", capture_list
[3].hostname
);
1069 EXPECT_EQ("req2", capture_list
[4].hostname
);
1070 EXPECT_EQ("req3", capture_list
[5].hostname
);
1071 EXPECT_EQ("req6", capture_list
[6].hostname
);
1074 // Try cancelling a job which has not started yet.
1075 TEST_F(HostResolverImplTest
, CancelPendingRequest
) {
1076 CreateSerialResolver();
1078 CreateRequest("req0", 80, LOWEST
);
1079 CreateRequest("req1", 80, HIGHEST
); // Will cancel.
1080 CreateRequest("req2", 80, MEDIUM
);
1081 CreateRequest("req3", 80, LOW
);
1082 CreateRequest("req4", 80, HIGHEST
); // Will cancel.
1083 CreateRequest("req5", 80, LOWEST
); // Will cancel.
1084 CreateRequest("req6", 80, MEDIUM
);
1086 // Start all of the requests.
1087 for (size_t i
= 0; i
< requests_
.size(); ++i
) {
1088 EXPECT_EQ(ERR_IO_PENDING
, requests_
[i
]->Resolve()) << i
;
1091 // Cancel some requests
1092 requests_
[1]->Cancel();
1093 requests_
[4]->Cancel();
1094 requests_
[5]->Cancel();
1096 // Unblock the resolver thread so the requests can run.
1097 proc_
->SignalMultiple(requests_
.size()); // More than needed.
1099 // Wait for all the requests to complete succesfully.
1100 for (size_t i
= 0; i
< requests_
.size(); ++i
) {
1101 if (!requests_
[i
]->pending())
1102 continue; // Don't wait for the requests we cancelled.
1103 EXPECT_EQ(OK
, requests_
[i
]->WaitForResult()) << i
;
1106 // Verify that they called out the the resolver proc (which runs on the
1107 // resolver thread) in the expected order.
1108 MockHostResolverProc::CaptureList capture_list
= proc_
->GetCaptureList();
1109 ASSERT_EQ(4u, capture_list
.size());
1111 EXPECT_EQ("req0", capture_list
[0].hostname
);
1112 EXPECT_EQ("req2", capture_list
[1].hostname
);
1113 EXPECT_EQ("req6", capture_list
[2].hostname
);
1114 EXPECT_EQ("req3", capture_list
[3].hostname
);
1117 // Test that when too many requests are enqueued, old ones start to be aborted.
1118 TEST_F(HostResolverImplTest
, QueueOverflow
) {
1119 CreateSerialResolver();
1121 // Allow only 3 queued jobs.
1122 const size_t kMaxPendingJobs
= 3u;
1123 resolver_
->SetMaxQueuedJobs(kMaxPendingJobs
);
1125 // Note that at this point the MockHostResolverProc is blocked, so any
1126 // requests we make will not complete.
1128 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("req0", 80, LOWEST
)->Resolve());
1129 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("req1", 80, HIGHEST
)->Resolve());
1130 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("req2", 80, MEDIUM
)->Resolve());
1131 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("req3", 80, MEDIUM
)->Resolve());
1133 // At this point, there are 3 enqueued jobs.
1134 // Insertion of subsequent requests will cause evictions
1135 // based on priority.
1137 EXPECT_EQ(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE
,
1138 CreateRequest("req4", 80, LOW
)->Resolve()); // Evicts itself!
1140 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("req5", 80, MEDIUM
)->Resolve());
1141 EXPECT_EQ(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE
, requests_
[2]->result());
1142 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("req6", 80, HIGHEST
)->Resolve());
1143 EXPECT_EQ(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE
, requests_
[3]->result());
1144 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("req7", 80, MEDIUM
)->Resolve());
1145 EXPECT_EQ(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE
, requests_
[5]->result());
1147 // Unblock the resolver thread so the requests can run.
1148 proc_
->SignalMultiple(4u);
1150 // The rest should succeed.
1151 EXPECT_EQ(OK
, requests_
[7]->WaitForResult());
1152 EXPECT_EQ(OK
, requests_
[0]->result());
1153 EXPECT_EQ(OK
, requests_
[1]->result());
1154 EXPECT_EQ(OK
, requests_
[6]->result());
1156 // Verify that they called out the the resolver proc (which runs on the
1157 // resolver thread) in the expected order.
1158 MockHostResolverProc::CaptureList capture_list
= proc_
->GetCaptureList();
1159 ASSERT_EQ(4u, capture_list
.size());
1161 EXPECT_EQ("req0", capture_list
[0].hostname
);
1162 EXPECT_EQ("req1", capture_list
[1].hostname
);
1163 EXPECT_EQ("req6", capture_list
[2].hostname
);
1164 EXPECT_EQ("req7", capture_list
[3].hostname
);
1166 // Verify that the evicted (incomplete) requests were not cached.
1167 EXPECT_EQ(4u, resolver_
->GetHostCache()->size());
1169 for (size_t i
= 0; i
< requests_
.size(); ++i
) {
1170 EXPECT_TRUE(requests_
[i
]->completed()) << i
;
1174 // Tests that after changing the default AddressFamily to IPV4, requests
1175 // with UNSPECIFIED address family map to IPV4.
1176 TEST_F(HostResolverImplTest
, SetDefaultAddressFamily_IPv4
) {
1177 CreateSerialResolver(); // To guarantee order of resolutions.
1179 proc_
->AddRule("h1", ADDRESS_FAMILY_IPV4
, "1.0.0.1");
1180 proc_
->AddRule("h1", ADDRESS_FAMILY_IPV6
, "::2");
1182 resolver_
->SetDefaultAddressFamily(ADDRESS_FAMILY_IPV4
);
1184 CreateRequest("h1", 80, MEDIUM
, ADDRESS_FAMILY_UNSPECIFIED
);
1185 CreateRequest("h1", 80, MEDIUM
, ADDRESS_FAMILY_IPV4
);
1186 CreateRequest("h1", 80, MEDIUM
, ADDRESS_FAMILY_IPV6
);
1188 // Start all of the requests.
1189 for (size_t i
= 0; i
< requests_
.size(); ++i
) {
1190 EXPECT_EQ(ERR_IO_PENDING
, requests_
[i
]->Resolve()) << i
;
1193 proc_
->SignalMultiple(requests_
.size());
1195 // Wait for all the requests to complete.
1196 for (size_t i
= 0u; i
< requests_
.size(); ++i
) {
1197 EXPECT_EQ(OK
, requests_
[i
]->WaitForResult()) << i
;
1200 // Since the requests all had the same priority and we limited the thread
1201 // count to 1, they should have completed in the same order as they were
1202 // requested. Moreover, request0 and request1 will have been serviced by
1205 MockHostResolverProc::CaptureList capture_list
= proc_
->GetCaptureList();
1206 ASSERT_EQ(2u, capture_list
.size());
1208 EXPECT_EQ("h1", capture_list
[0].hostname
);
1209 EXPECT_EQ(ADDRESS_FAMILY_IPV4
, capture_list
[0].address_family
);
1211 EXPECT_EQ("h1", capture_list
[1].hostname
);
1212 EXPECT_EQ(ADDRESS_FAMILY_IPV6
, capture_list
[1].address_family
);
1214 // Now check that the correct resolved IP addresses were returned.
1215 EXPECT_TRUE(requests_
[0]->HasOneAddress("1.0.0.1", 80));
1216 EXPECT_TRUE(requests_
[1]->HasOneAddress("1.0.0.1", 80));
1217 EXPECT_TRUE(requests_
[2]->HasOneAddress("::2", 80));
1220 // This is the exact same test as SetDefaultAddressFamily_IPv4, except the
1221 // default family is set to IPv6 and the family of requests is flipped where
1223 TEST_F(HostResolverImplTest
, SetDefaultAddressFamily_IPv6
) {
1224 CreateSerialResolver(); // To guarantee order of resolutions.
1226 // Don't use IPv6 replacements here since some systems don't support it.
1227 proc_
->AddRule("h1", ADDRESS_FAMILY_IPV4
, "1.0.0.1");
1228 proc_
->AddRule("h1", ADDRESS_FAMILY_IPV6
, "::2");
1230 resolver_
->SetDefaultAddressFamily(ADDRESS_FAMILY_IPV6
);
1232 CreateRequest("h1", 80, MEDIUM
, ADDRESS_FAMILY_UNSPECIFIED
);
1233 CreateRequest("h1", 80, MEDIUM
, ADDRESS_FAMILY_IPV6
);
1234 CreateRequest("h1", 80, MEDIUM
, ADDRESS_FAMILY_IPV4
);
1236 // Start all of the requests.
1237 for (size_t i
= 0; i
< requests_
.size(); ++i
) {
1238 EXPECT_EQ(ERR_IO_PENDING
, requests_
[i
]->Resolve()) << i
;
1241 proc_
->SignalMultiple(requests_
.size());
1243 // Wait for all the requests to complete.
1244 for (size_t i
= 0u; i
< requests_
.size(); ++i
) {
1245 EXPECT_EQ(OK
, requests_
[i
]->WaitForResult()) << i
;
1248 // Since the requests all had the same priority and we limited the thread
1249 // count to 1, they should have completed in the same order as they were
1250 // requested. Moreover, request0 and request1 will have been serviced by
1253 MockHostResolverProc::CaptureList capture_list
= proc_
->GetCaptureList();
1254 ASSERT_EQ(2u, capture_list
.size());
1256 EXPECT_EQ("h1", capture_list
[0].hostname
);
1257 EXPECT_EQ(ADDRESS_FAMILY_IPV6
, capture_list
[0].address_family
);
1259 EXPECT_EQ("h1", capture_list
[1].hostname
);
1260 EXPECT_EQ(ADDRESS_FAMILY_IPV4
, capture_list
[1].address_family
);
1262 // Now check that the correct resolved IP addresses were returned.
1263 EXPECT_TRUE(requests_
[0]->HasOneAddress("::2", 80));
1264 EXPECT_TRUE(requests_
[1]->HasOneAddress("::2", 80));
1265 EXPECT_TRUE(requests_
[2]->HasOneAddress("1.0.0.1", 80));
1268 // Make sure that the address family parameter is respected when raw IPs are
1270 TEST_F(HostResolverImplTest
, AddressFamilyWithRawIPs
) {
1272 CreateRequest("127.0.0.1", 80, MEDIUM
, ADDRESS_FAMILY_IPV4
);
1273 EXPECT_EQ(OK
, request
->Resolve());
1274 EXPECT_TRUE(request
->HasOneAddress("127.0.0.1", 80));
1276 request
= CreateRequest("127.0.0.1", 80, MEDIUM
, ADDRESS_FAMILY_IPV6
);
1277 EXPECT_EQ(ERR_NAME_NOT_RESOLVED
, request
->Resolve());
1279 request
= CreateRequest("127.0.0.1", 80, MEDIUM
, ADDRESS_FAMILY_UNSPECIFIED
);
1280 EXPECT_EQ(OK
, request
->Resolve());
1281 EXPECT_TRUE(request
->HasOneAddress("127.0.0.1", 80));
1283 request
= CreateRequest("::1", 80, MEDIUM
, ADDRESS_FAMILY_IPV4
);
1284 EXPECT_EQ(ERR_NAME_NOT_RESOLVED
, request
->Resolve());
1286 request
= CreateRequest("::1", 80, MEDIUM
, ADDRESS_FAMILY_IPV6
);
1287 EXPECT_EQ(OK
, request
->Resolve());
1288 EXPECT_TRUE(request
->HasOneAddress("::1", 80));
1290 request
= CreateRequest("::1", 80, MEDIUM
, ADDRESS_FAMILY_UNSPECIFIED
);
1291 EXPECT_EQ(OK
, request
->Resolve());
1292 EXPECT_TRUE(request
->HasOneAddress("::1", 80));
1295 TEST_F(HostResolverImplTest
, ResolveFromCache
) {
1296 proc_
->AddRuleForAllFamilies("just.testing", "192.168.1.42");
1297 proc_
->SignalMultiple(1u); // Need only one.
1299 HostResolver::RequestInfo
info(HostPortPair("just.testing", 80));
1301 // First hit will miss the cache.
1302 EXPECT_EQ(ERR_DNS_CACHE_MISS
,
1303 CreateRequest(info
, DEFAULT_PRIORITY
)->ResolveFromCache());
1305 // This time, we fetch normally.
1306 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest(info
, DEFAULT_PRIORITY
)->Resolve());
1307 EXPECT_EQ(OK
, requests_
[1]->WaitForResult());
1309 // Now we should be able to fetch from the cache.
1310 EXPECT_EQ(OK
, CreateRequest(info
, DEFAULT_PRIORITY
)->ResolveFromCache());
1311 EXPECT_TRUE(requests_
[2]->HasOneAddress("192.168.1.42", 80));
1314 // Test the retry attempts simulating host resolver proc that takes too long.
1315 TEST_F(HostResolverImplTest
, MultipleAttempts
) {
1316 // Total number of attempts would be 3 and we want the 3rd attempt to resolve
1317 // the host. First and second attempt will be forced to sleep until they get
1318 // word that a resolution has completed. The 3rd resolution attempt will try
1319 // to get done ASAP, and won't sleep..
1320 int kAttemptNumberToResolve
= 3;
1321 int kTotalAttempts
= 3;
1323 scoped_refptr
<LookupAttemptHostResolverProc
> resolver_proc(
1324 new LookupAttemptHostResolverProc(
1325 NULL
, kAttemptNumberToResolve
, kTotalAttempts
));
1327 HostResolverImpl::ProcTaskParams params
= DefaultParams(resolver_proc
.get());
1329 // Specify smaller interval for unresponsive_delay_ for HostResolverImpl so
1330 // that unit test runs faster. For example, this test finishes in 1.5 secs
1332 params
.unresponsive_delay
= base::TimeDelta::FromMilliseconds(500);
1334 resolver_
.reset(new HostResolverImpl(DefaultOptions(), NULL
));
1335 resolver_
->set_proc_params_for_test(params
);
1338 HostResolver::RequestInfo
info(HostPortPair("host1", 70));
1339 Request
* req
= CreateRequest(info
, DEFAULT_PRIORITY
);
1340 EXPECT_EQ(ERR_IO_PENDING
, req
->Resolve());
1342 // Resolve returns -4 to indicate that 3rd attempt has resolved the host.
1343 EXPECT_EQ(-4, req
->WaitForResult());
1345 resolver_proc
->WaitForAllAttemptsToFinish(
1346 base::TimeDelta::FromMilliseconds(60000));
1347 base::MessageLoop::current()->RunUntilIdle();
1349 EXPECT_EQ(resolver_proc
->total_attempts_resolved(), kTotalAttempts
);
1350 EXPECT_EQ(resolver_proc
->resolved_attempt_number(), kAttemptNumberToResolve
);
1353 // If a host resolves to a list that includes 127.0.53.53, this is treated as
1354 // an error. 127.0.53.53 is a localhost address, however it has been given a
1355 // special significance by ICANN to help surfance name collision resulting from
1357 TEST_F(HostResolverImplTest
, NameCollision127_0_53_53
) {
1358 proc_
->AddRuleForAllFamilies("single", "127.0.53.53");
1359 proc_
->AddRuleForAllFamilies("multiple", "127.0.0.1,127.0.53.53");
1360 proc_
->AddRuleForAllFamilies("ipv6", "::127.0.53.53");
1361 proc_
->AddRuleForAllFamilies("not_reserved1", "53.53.0.127");
1362 proc_
->AddRuleForAllFamilies("not_reserved2", "127.0.53.54");
1363 proc_
->AddRuleForAllFamilies("not_reserved3", "10.0.53.53");
1364 proc_
->SignalMultiple(6u);
1368 request
= CreateRequest("single");
1369 EXPECT_EQ(ERR_IO_PENDING
, request
->Resolve());
1370 EXPECT_EQ(ERR_ICANN_NAME_COLLISION
, request
->WaitForResult());
1372 request
= CreateRequest("multiple");
1373 EXPECT_EQ(ERR_IO_PENDING
, request
->Resolve());
1374 EXPECT_EQ(ERR_ICANN_NAME_COLLISION
, request
->WaitForResult());
1376 // Resolving an IP literal of 127.0.53.53 however is allowed.
1377 EXPECT_EQ(OK
, CreateRequest("127.0.53.53")->Resolve());
1379 // Moreover the address should not be recognized when embedded in an IPv6
1381 request
= CreateRequest("ipv6");
1382 EXPECT_EQ(ERR_IO_PENDING
, request
->Resolve());
1383 EXPECT_EQ(OK
, request
->WaitForResult());
1385 // Try some other IPs which are similar, but NOT an exact match on
1387 request
= CreateRequest("not_reserved1");
1388 EXPECT_EQ(ERR_IO_PENDING
, request
->Resolve());
1389 EXPECT_EQ(OK
, request
->WaitForResult());
1391 request
= CreateRequest("not_reserved2");
1392 EXPECT_EQ(ERR_IO_PENDING
, request
->Resolve());
1393 EXPECT_EQ(OK
, request
->WaitForResult());
1395 request
= CreateRequest("not_reserved3");
1396 EXPECT_EQ(ERR_IO_PENDING
, request
->Resolve());
1397 EXPECT_EQ(OK
, request
->WaitForResult());
1400 DnsConfig
CreateValidDnsConfig() {
1401 IPAddressNumber dns_ip
;
1402 bool rv
= ParseIPLiteralToNumber("192.168.1.0", &dns_ip
);
1406 config
.nameservers
.push_back(IPEndPoint(dns_ip
, dns_protocol::kDefaultPort
));
1407 EXPECT_TRUE(config
.IsValid());
1411 // Specialized fixture for tests of DnsTask.
1412 class HostResolverImplDnsTest
: public HostResolverImplTest
{
1414 HostResolverImplDnsTest() : dns_client_(NULL
) {}
1417 // testing::Test implementation:
1418 void SetUp() override
{
1419 AddDnsRule("nx", dns_protocol::kTypeA
, MockDnsClientRule::FAIL
, false);
1420 AddDnsRule("nx", dns_protocol::kTypeAAAA
, MockDnsClientRule::FAIL
, false);
1421 AddDnsRule("ok", dns_protocol::kTypeA
, MockDnsClientRule::OK
, false);
1422 AddDnsRule("ok", dns_protocol::kTypeAAAA
, MockDnsClientRule::OK
, false);
1423 AddDnsRule("4ok", dns_protocol::kTypeA
, MockDnsClientRule::OK
, false);
1424 AddDnsRule("4ok", dns_protocol::kTypeAAAA
, MockDnsClientRule::EMPTY
, false);
1425 AddDnsRule("6ok", dns_protocol::kTypeA
, MockDnsClientRule::EMPTY
, false);
1426 AddDnsRule("6ok", dns_protocol::kTypeAAAA
, MockDnsClientRule::OK
, false);
1427 AddDnsRule("4nx", dns_protocol::kTypeA
, MockDnsClientRule::OK
, false);
1428 AddDnsRule("4nx", dns_protocol::kTypeAAAA
, MockDnsClientRule::FAIL
, false);
1429 AddDnsRule("empty", dns_protocol::kTypeA
, MockDnsClientRule::EMPTY
, false);
1430 AddDnsRule("empty", dns_protocol::kTypeAAAA
, MockDnsClientRule::EMPTY
,
1433 AddDnsRule("slow_nx", dns_protocol::kTypeA
, MockDnsClientRule::FAIL
, true);
1434 AddDnsRule("slow_nx", dns_protocol::kTypeAAAA
, MockDnsClientRule::FAIL
,
1437 AddDnsRule("4slow_ok", dns_protocol::kTypeA
, MockDnsClientRule::OK
, true);
1438 AddDnsRule("4slow_ok", dns_protocol::kTypeAAAA
, MockDnsClientRule::OK
,
1440 AddDnsRule("6slow_ok", dns_protocol::kTypeA
, MockDnsClientRule::OK
, false);
1441 AddDnsRule("6slow_ok", dns_protocol::kTypeAAAA
, MockDnsClientRule::OK
,
1443 AddDnsRule("4slow_4ok", dns_protocol::kTypeA
, MockDnsClientRule::OK
, true);
1444 AddDnsRule("4slow_4ok", dns_protocol::kTypeAAAA
, MockDnsClientRule::EMPTY
,
1446 AddDnsRule("4slow_4timeout", dns_protocol::kTypeA
,
1447 MockDnsClientRule::TIMEOUT
, true);
1448 AddDnsRule("4slow_4timeout", dns_protocol::kTypeAAAA
, MockDnsClientRule::OK
,
1450 AddDnsRule("4slow_6timeout", dns_protocol::kTypeA
,
1451 MockDnsClientRule::OK
, true);
1452 AddDnsRule("4slow_6timeout", dns_protocol::kTypeAAAA
,
1453 MockDnsClientRule::TIMEOUT
, false);
1457 // HostResolverImplTest implementation:
1458 void CreateResolverWithLimitsAndParams(
1459 size_t max_concurrent_resolves
,
1460 const HostResolverImpl::ProcTaskParams
& params
) override
{
1461 HostResolverImpl::Options options
= DefaultOptions();
1462 options
.max_concurrent_resolves
= max_concurrent_resolves
;
1463 resolver_
.reset(new HostResolverImpl(options
, NULL
));
1464 resolver_
->set_proc_params_for_test(params
);
1465 // Disable IPv6 support probing.
1466 resolver_
->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED
);
1467 dns_client_
= new MockDnsClient(DnsConfig(), dns_rules_
);
1468 resolver_
->SetDnsClient(scoped_ptr
<DnsClient
>(dns_client_
));
1471 // Adds a rule to |dns_rules_|. Must be followed by |CreateResolver| to apply.
1472 void AddDnsRule(const std::string
& prefix
,
1474 MockDnsClientRule::Result result
,
1476 dns_rules_
.push_back(MockDnsClientRule(prefix
, qtype
, result
, delay
));
1479 void ChangeDnsConfig(const DnsConfig
& config
) {
1480 NetworkChangeNotifier::SetDnsConfig(config
);
1481 // Notification is delivered asynchronously.
1482 base::MessageLoop::current()->RunUntilIdle();
1485 MockDnsClientRuleList dns_rules_
;
1486 // Owned by |resolver_|.
1487 MockDnsClient
* dns_client_
;
1490 // TODO(szym): Test AbortAllInProgressJobs due to DnsConfig change.
1492 // TODO(cbentzel): Test a mix of requests with different HostResolverFlags.
1494 // Test successful and fallback resolutions in HostResolverImpl::DnsTask.
1495 TEST_F(HostResolverImplDnsTest
, DnsTask
) {
1496 resolver_
->SetDefaultAddressFamily(ADDRESS_FAMILY_IPV4
);
1498 proc_
->AddRuleForAllFamilies("nx_succeed", "192.168.1.102");
1499 // All other hostnames will fail in proc_.
1501 // Initially there is no config, so client should not be invoked.
1502 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("ok_fail", 80)->Resolve());
1503 proc_
->SignalMultiple(requests_
.size());
1505 EXPECT_EQ(ERR_NAME_NOT_RESOLVED
, requests_
[0]->WaitForResult());
1507 ChangeDnsConfig(CreateValidDnsConfig());
1509 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("ok_fail", 80)->Resolve());
1510 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("nx_fail", 80)->Resolve());
1511 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("nx_succeed", 80)->Resolve());
1513 proc_
->SignalMultiple(requests_
.size());
1515 for (size_t i
= 1; i
< requests_
.size(); ++i
)
1516 EXPECT_NE(ERR_UNEXPECTED
, requests_
[i
]->WaitForResult()) << i
;
1518 EXPECT_EQ(OK
, requests_
[1]->result());
1519 // Resolved by MockDnsClient.
1520 EXPECT_TRUE(requests_
[1]->HasOneAddress("127.0.0.1", 80));
1521 // Fallback to ProcTask.
1522 EXPECT_EQ(ERR_NAME_NOT_RESOLVED
, requests_
[2]->result());
1523 EXPECT_EQ(OK
, requests_
[3]->result());
1524 EXPECT_TRUE(requests_
[3]->HasOneAddress("192.168.1.102", 80));
1527 // Test successful and failing resolutions in HostResolverImpl::DnsTask when
1528 // fallback to ProcTask is disabled.
1529 TEST_F(HostResolverImplDnsTest
, NoFallbackToProcTask
) {
1530 resolver_
->SetDefaultAddressFamily(ADDRESS_FAMILY_IPV4
);
1531 set_fallback_to_proctask(false);
1533 proc_
->AddRuleForAllFamilies("nx_succeed", "192.168.1.102");
1534 // All other hostnames will fail in proc_.
1536 // Set empty DnsConfig.
1537 ChangeDnsConfig(DnsConfig());
1538 // Initially there is no config, so client should not be invoked.
1539 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("ok_fail", 80)->Resolve());
1540 // There is no config, so fallback to ProcTask must work.
1541 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("nx_succeed", 80)->Resolve());
1542 proc_
->SignalMultiple(requests_
.size());
1544 EXPECT_EQ(ERR_NAME_NOT_RESOLVED
, requests_
[0]->WaitForResult());
1545 EXPECT_EQ(OK
, requests_
[1]->WaitForResult());
1546 EXPECT_TRUE(requests_
[1]->HasOneAddress("192.168.1.102", 80));
1548 ChangeDnsConfig(CreateValidDnsConfig());
1550 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("ok_abort", 80)->Resolve());
1551 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("nx_abort", 80)->Resolve());
1553 // Simulate the case when the preference or policy has disabled the DNS client
1554 // causing AbortDnsTasks.
1555 resolver_
->SetDnsClient(
1556 scoped_ptr
<DnsClient
>(new MockDnsClient(DnsConfig(), dns_rules_
)));
1557 ChangeDnsConfig(CreateValidDnsConfig());
1559 // First request is resolved by MockDnsClient, others should fail due to
1560 // disabled fallback to ProcTask.
1561 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("ok_fail", 80)->Resolve());
1562 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("nx_fail", 80)->Resolve());
1563 proc_
->SignalMultiple(requests_
.size());
1565 // Aborted due to Network Change.
1566 EXPECT_EQ(ERR_NETWORK_CHANGED
, requests_
[2]->WaitForResult());
1567 EXPECT_EQ(ERR_NETWORK_CHANGED
, requests_
[3]->WaitForResult());
1568 // Resolved by MockDnsClient.
1569 EXPECT_EQ(OK
, requests_
[4]->WaitForResult());
1570 EXPECT_TRUE(requests_
[4]->HasOneAddress("127.0.0.1", 80));
1571 // Fallback to ProcTask is disabled.
1572 EXPECT_EQ(ERR_NAME_NOT_RESOLVED
, requests_
[5]->WaitForResult());
1575 // Test behavior of OnDnsTaskFailure when Job is aborted.
1576 TEST_F(HostResolverImplDnsTest
, OnDnsTaskFailureAbortedJob
) {
1577 resolver_
->SetDefaultAddressFamily(ADDRESS_FAMILY_IPV4
);
1578 ChangeDnsConfig(CreateValidDnsConfig());
1579 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("nx_abort", 80)->Resolve());
1580 // Abort all jobs here.
1582 proc_
->SignalMultiple(requests_
.size());
1583 // Run to completion.
1584 base::MessageLoop::current()->RunUntilIdle(); // Notification happens async.
1585 // It shouldn't crash during OnDnsTaskFailure callbacks.
1586 EXPECT_EQ(ERR_IO_PENDING
, requests_
[0]->result());
1588 // Repeat test with Fallback to ProcTask disabled
1589 resolver_
->SetDefaultAddressFamily(ADDRESS_FAMILY_IPV4
);
1590 set_fallback_to_proctask(false);
1591 ChangeDnsConfig(CreateValidDnsConfig());
1592 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("nx_abort", 80)->Resolve());
1593 // Abort all jobs here.
1595 // Run to completion.
1596 base::MessageLoop::current()->RunUntilIdle(); // Notification happens async.
1597 // It shouldn't crash during OnDnsTaskFailure callbacks.
1598 EXPECT_EQ(ERR_IO_PENDING
, requests_
[1]->result());
1601 TEST_F(HostResolverImplDnsTest
, DnsTaskUnspec
) {
1602 ChangeDnsConfig(CreateValidDnsConfig());
1604 proc_
->AddRuleForAllFamilies("4nx", "192.168.1.101");
1605 // All other hostnames will fail in proc_.
1607 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("ok", 80)->Resolve());
1608 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("4ok", 80)->Resolve());
1609 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("6ok", 80)->Resolve());
1610 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("4nx", 80)->Resolve());
1612 proc_
->SignalMultiple(requests_
.size());
1614 for (size_t i
= 0; i
< requests_
.size(); ++i
)
1615 EXPECT_EQ(OK
, requests_
[i
]->WaitForResult()) << i
;
1617 EXPECT_EQ(2u, requests_
[0]->NumberOfAddresses());
1618 EXPECT_TRUE(requests_
[0]->HasAddress("127.0.0.1", 80));
1619 EXPECT_TRUE(requests_
[0]->HasAddress("::1", 80));
1620 EXPECT_EQ(1u, requests_
[1]->NumberOfAddresses());
1621 EXPECT_TRUE(requests_
[1]->HasAddress("127.0.0.1", 80));
1622 EXPECT_EQ(1u, requests_
[2]->NumberOfAddresses());
1623 EXPECT_TRUE(requests_
[2]->HasAddress("::1", 80));
1624 EXPECT_EQ(1u, requests_
[3]->NumberOfAddresses());
1625 EXPECT_TRUE(requests_
[3]->HasAddress("192.168.1.101", 80));
1628 TEST_F(HostResolverImplDnsTest
, ServeFromHosts
) {
1629 // Initially, use empty HOSTS file.
1630 DnsConfig config
= CreateValidDnsConfig();
1631 ChangeDnsConfig(config
);
1633 proc_
->AddRuleForAllFamilies(std::string(),
1634 std::string()); // Default to failures.
1635 proc_
->SignalMultiple(1u); // For the first request which misses.
1637 Request
* req0
= CreateRequest("nx_ipv4", 80);
1638 EXPECT_EQ(ERR_IO_PENDING
, req0
->Resolve());
1639 EXPECT_EQ(ERR_NAME_NOT_RESOLVED
, req0
->WaitForResult());
1641 IPAddressNumber local_ipv4
, local_ipv6
;
1642 ASSERT_TRUE(ParseIPLiteralToNumber("127.0.0.1", &local_ipv4
));
1643 ASSERT_TRUE(ParseIPLiteralToNumber("::1", &local_ipv6
));
1646 hosts
[DnsHostsKey("nx_ipv4", ADDRESS_FAMILY_IPV4
)] = local_ipv4
;
1647 hosts
[DnsHostsKey("nx_ipv6", ADDRESS_FAMILY_IPV6
)] = local_ipv6
;
1648 hosts
[DnsHostsKey("nx_both", ADDRESS_FAMILY_IPV4
)] = local_ipv4
;
1649 hosts
[DnsHostsKey("nx_both", ADDRESS_FAMILY_IPV6
)] = local_ipv6
;
1651 // Update HOSTS file.
1652 config
.hosts
= hosts
;
1653 ChangeDnsConfig(config
);
1655 Request
* req1
= CreateRequest("nx_ipv4", 80);
1656 EXPECT_EQ(OK
, req1
->Resolve());
1657 EXPECT_TRUE(req1
->HasOneAddress("127.0.0.1", 80));
1659 Request
* req2
= CreateRequest("nx_ipv6", 80);
1660 EXPECT_EQ(OK
, req2
->Resolve());
1661 EXPECT_TRUE(req2
->HasOneAddress("::1", 80));
1663 Request
* req3
= CreateRequest("nx_both", 80);
1664 EXPECT_EQ(OK
, req3
->Resolve());
1665 EXPECT_TRUE(req3
->HasAddress("127.0.0.1", 80) &&
1666 req3
->HasAddress("::1", 80));
1668 // Requests with specified AddressFamily.
1669 Request
* req4
= CreateRequest("nx_ipv4", 80, MEDIUM
, ADDRESS_FAMILY_IPV4
);
1670 EXPECT_EQ(OK
, req4
->Resolve());
1671 EXPECT_TRUE(req4
->HasOneAddress("127.0.0.1", 80));
1673 Request
* req5
= CreateRequest("nx_ipv6", 80, MEDIUM
, ADDRESS_FAMILY_IPV6
);
1674 EXPECT_EQ(OK
, req5
->Resolve());
1675 EXPECT_TRUE(req5
->HasOneAddress("::1", 80));
1677 // Request with upper case.
1678 Request
* req6
= CreateRequest("nx_IPV4", 80);
1679 EXPECT_EQ(OK
, req6
->Resolve());
1680 EXPECT_TRUE(req6
->HasOneAddress("127.0.0.1", 80));
1683 TEST_F(HostResolverImplDnsTest
, BypassDnsTask
) {
1684 ChangeDnsConfig(CreateValidDnsConfig());
1686 proc_
->AddRuleForAllFamilies(std::string(),
1687 std::string()); // Default to failures.
1689 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("ok.local", 80)->Resolve());
1690 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("ok.local.", 80)->Resolve());
1691 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("oklocal", 80)->Resolve());
1692 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("oklocal.", 80)->Resolve());
1693 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("ok", 80)->Resolve());
1695 proc_
->SignalMultiple(requests_
.size());
1697 for (size_t i
= 0; i
< 2; ++i
)
1698 EXPECT_EQ(ERR_NAME_NOT_RESOLVED
, requests_
[i
]->WaitForResult()) << i
;
1700 for (size_t i
= 2; i
< requests_
.size(); ++i
)
1701 EXPECT_EQ(OK
, requests_
[i
]->WaitForResult()) << i
;
1704 TEST_F(HostResolverImplDnsTest
, SystemOnlyBypassesDnsTask
) {
1705 ChangeDnsConfig(CreateValidDnsConfig());
1707 proc_
->AddRuleForAllFamilies(std::string(), std::string());
1709 HostResolver::RequestInfo
info_bypass(HostPortPair("ok", 80));
1710 info_bypass
.set_host_resolver_flags(HOST_RESOLVER_SYSTEM_ONLY
);
1711 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest(info_bypass
, MEDIUM
)->Resolve());
1713 HostResolver::RequestInfo
info(HostPortPair("ok", 80));
1714 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest(info
, MEDIUM
)->Resolve());
1716 proc_
->SignalMultiple(requests_
.size());
1718 EXPECT_EQ(ERR_NAME_NOT_RESOLVED
, requests_
[0]->WaitForResult());
1719 EXPECT_EQ(OK
, requests_
[1]->WaitForResult());
1722 TEST_F(HostResolverImplDnsTest
, DisableDnsClientOnPersistentFailure
) {
1723 ChangeDnsConfig(CreateValidDnsConfig());
1725 proc_
->AddRuleForAllFamilies(std::string(),
1726 std::string()); // Default to failures.
1728 // Check that DnsTask works.
1729 Request
* req
= CreateRequest("ok_1", 80);
1730 EXPECT_EQ(ERR_IO_PENDING
, req
->Resolve());
1731 EXPECT_EQ(OK
, req
->WaitForResult());
1733 for (unsigned i
= 0; i
< maximum_dns_failures(); ++i
) {
1734 // Use custom names to require separate Jobs.
1735 std::string hostname
= base::StringPrintf("nx_%u", i
);
1736 // Ensure fallback to ProcTask succeeds.
1737 proc_
->AddRuleForAllFamilies(hostname
, "192.168.1.101");
1738 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest(hostname
, 80)->Resolve()) << i
;
1741 proc_
->SignalMultiple(requests_
.size());
1743 for (size_t i
= 0; i
< requests_
.size(); ++i
)
1744 EXPECT_EQ(OK
, requests_
[i
]->WaitForResult()) << i
;
1746 ASSERT_FALSE(proc_
->HasBlockedRequests());
1748 // DnsTask should be disabled by now.
1749 req
= CreateRequest("ok_2", 80);
1750 EXPECT_EQ(ERR_IO_PENDING
, req
->Resolve());
1751 proc_
->SignalMultiple(1u);
1752 EXPECT_EQ(ERR_NAME_NOT_RESOLVED
, req
->WaitForResult());
1754 // Check that it is re-enabled after DNS change.
1755 ChangeDnsConfig(CreateValidDnsConfig());
1756 req
= CreateRequest("ok_3", 80);
1757 EXPECT_EQ(ERR_IO_PENDING
, req
->Resolve());
1758 EXPECT_EQ(OK
, req
->WaitForResult());
1761 TEST_F(HostResolverImplDnsTest
, DontDisableDnsClientOnSporadicFailure
) {
1762 ChangeDnsConfig(CreateValidDnsConfig());
1764 // |proc_| defaults to successes.
1766 // 20 failures interleaved with 20 successes.
1767 for (unsigned i
= 0; i
< 40; ++i
) {
1768 // Use custom names to require separate Jobs.
1769 std::string hostname
= (i
% 2) == 0 ? base::StringPrintf("nx_%u", i
)
1770 : base::StringPrintf("ok_%u", i
);
1771 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest(hostname
, 80)->Resolve()) << i
;
1774 proc_
->SignalMultiple(requests_
.size());
1776 for (size_t i
= 0; i
< requests_
.size(); ++i
)
1777 EXPECT_EQ(OK
, requests_
[i
]->WaitForResult()) << i
;
1779 // Make |proc_| default to failures.
1780 proc_
->AddRuleForAllFamilies(std::string(), std::string());
1782 // DnsTask should still be enabled.
1783 Request
* req
= CreateRequest("ok_last", 80);
1784 EXPECT_EQ(ERR_IO_PENDING
, req
->Resolve());
1785 EXPECT_EQ(OK
, req
->WaitForResult());
1788 // Confirm that resolving "localhost" is unrestricted even if there are no
1789 // global IPv6 address. See SystemHostResolverCall for rationale.
1790 // Test both the DnsClient and system host resolver paths.
1791 TEST_F(HostResolverImplDnsTest
, DualFamilyLocalhost
) {
1792 // Use regular SystemHostResolverCall!
1793 scoped_refptr
<HostResolverProc
> proc(new SystemHostResolverProc());
1794 resolver_
.reset(new HostResolverImpl(DefaultOptions(), NULL
));
1795 resolver_
->set_proc_params_for_test(DefaultParams(proc
.get()));
1797 resolver_
->SetDnsClient(
1798 scoped_ptr
<DnsClient
>(new MockDnsClient(DnsConfig(), dns_rules_
)));
1799 resolver_
->SetDefaultAddressFamily(ADDRESS_FAMILY_IPV4
);
1801 // Get the expected output.
1802 AddressList addrlist
;
1803 int rv
= proc
->Resolve("localhost", ADDRESS_FAMILY_UNSPECIFIED
, 0, &addrlist
,
1808 for (unsigned i
= 0; i
< addrlist
.size(); ++i
)
1809 LOG(WARNING
) << addrlist
[i
].ToString();
1811 bool saw_ipv4
= AddressListContains(addrlist
, "127.0.0.1", 0);
1812 bool saw_ipv6
= AddressListContains(addrlist
, "::1", 0);
1813 if (!saw_ipv4
&& !saw_ipv6
)
1816 HostResolver::RequestInfo
info(HostPortPair("localhost", 80));
1817 info
.set_address_family(ADDRESS_FAMILY_UNSPECIFIED
);
1818 info
.set_host_resolver_flags(HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6
);
1820 // Try without DnsClient.
1821 ChangeDnsConfig(DnsConfig());
1822 Request
* req
= CreateRequest(info
, DEFAULT_PRIORITY
);
1823 // It is resolved via getaddrinfo, so expect asynchronous result.
1824 EXPECT_EQ(ERR_IO_PENDING
, req
->Resolve());
1825 EXPECT_EQ(OK
, req
->WaitForResult());
1827 EXPECT_EQ(saw_ipv4
, req
->HasAddress("127.0.0.1", 80));
1828 EXPECT_EQ(saw_ipv6
, req
->HasAddress("::1", 80));
1830 // Configure DnsClient with dual-host HOSTS file.
1831 DnsConfig config
= CreateValidDnsConfig();
1833 IPAddressNumber local_ipv4
, local_ipv6
;
1834 ASSERT_TRUE(ParseIPLiteralToNumber("127.0.0.1", &local_ipv4
));
1835 ASSERT_TRUE(ParseIPLiteralToNumber("::1", &local_ipv6
));
1837 hosts
[DnsHostsKey("localhost", ADDRESS_FAMILY_IPV4
)] = local_ipv4
;
1839 hosts
[DnsHostsKey("localhost", ADDRESS_FAMILY_IPV6
)] = local_ipv6
;
1840 config
.hosts
= hosts
;
1842 ChangeDnsConfig(config
);
1843 req
= CreateRequest(info
, DEFAULT_PRIORITY
);
1844 // Expect synchronous resolution from DnsHosts.
1845 EXPECT_EQ(OK
, req
->Resolve());
1847 EXPECT_EQ(saw_ipv4
, req
->HasAddress("127.0.0.1", 80));
1848 EXPECT_EQ(saw_ipv6
, req
->HasAddress("::1", 80));
1851 // Cancel a request with a single DNS transaction active.
1852 TEST_F(HostResolverImplDnsTest
, CancelWithOneTransactionActive
) {
1853 resolver_
->SetDefaultAddressFamily(ADDRESS_FAMILY_IPV4
);
1854 ChangeDnsConfig(CreateValidDnsConfig());
1856 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("ok", 80)->Resolve());
1857 EXPECT_EQ(1u, num_running_dispatcher_jobs());
1858 requests_
[0]->Cancel();
1860 // Dispatcher state checked in TearDown.
1863 // Cancel a request with a single DNS transaction active and another pending.
1864 TEST_F(HostResolverImplDnsTest
, CancelWithOneTransactionActiveOnePending
) {
1865 CreateSerialResolver();
1866 resolver_
->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED
);
1867 ChangeDnsConfig(CreateValidDnsConfig());
1869 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("ok", 80)->Resolve());
1870 EXPECT_EQ(1u, num_running_dispatcher_jobs());
1871 requests_
[0]->Cancel();
1873 // Dispatcher state checked in TearDown.
1876 // Cancel a request with two DNS transactions active.
1877 TEST_F(HostResolverImplDnsTest
, CancelWithTwoTransactionsActive
) {
1878 resolver_
->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED
);
1879 ChangeDnsConfig(CreateValidDnsConfig());
1881 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("ok", 80)->Resolve());
1882 EXPECT_EQ(2u, num_running_dispatcher_jobs());
1883 requests_
[0]->Cancel();
1885 // Dispatcher state checked in TearDown.
1888 // Delete a resolver with some active requests and some queued requests.
1889 TEST_F(HostResolverImplDnsTest
, DeleteWithActiveTransactions
) {
1890 // At most 10 Jobs active at once.
1891 CreateResolverWithLimitsAndParams(10u, DefaultParams(proc_
.get()));
1893 resolver_
->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED
);
1894 ChangeDnsConfig(CreateValidDnsConfig());
1896 // First active job is an IPv4 request.
1897 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("ok", 80, MEDIUM
,
1898 ADDRESS_FAMILY_IPV4
)->Resolve());
1900 // Add 10 more DNS lookups for different hostnames. First 4 should have two
1901 // active jobs, next one has a single active job, and one pending. Others
1902 // should all be queued.
1903 for (int i
= 0; i
< 10; ++i
) {
1904 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest(
1905 base::StringPrintf("ok%i", i
))->Resolve());
1907 EXPECT_EQ(10u, num_running_dispatcher_jobs());
1912 // Cancel a request with only the IPv6 transaction active.
1913 TEST_F(HostResolverImplDnsTest
, CancelWithIPv6TransactionActive
) {
1914 resolver_
->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED
);
1915 ChangeDnsConfig(CreateValidDnsConfig());
1917 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("6slow_ok", 80)->Resolve());
1918 EXPECT_EQ(2u, num_running_dispatcher_jobs());
1920 // The IPv4 request should complete, the IPv6 request is still pending.
1921 base::RunLoop().RunUntilIdle();
1922 EXPECT_EQ(1u, num_running_dispatcher_jobs());
1923 requests_
[0]->Cancel();
1925 // Dispatcher state checked in TearDown.
1928 // Cancel a request with only the IPv4 transaction pending.
1929 TEST_F(HostResolverImplDnsTest
, CancelWithIPv4TransactionPending
) {
1930 set_fallback_to_proctask(false);
1931 resolver_
->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED
);
1932 ChangeDnsConfig(CreateValidDnsConfig());
1934 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("4slow_ok", 80)->Resolve());
1935 EXPECT_EQ(2u, num_running_dispatcher_jobs());
1937 // The IPv6 request should complete, the IPv4 request is still pending.
1938 base::RunLoop().RunUntilIdle();
1939 EXPECT_EQ(1u, num_running_dispatcher_jobs());
1941 requests_
[0]->Cancel();
1944 // Test cases where AAAA completes first.
1945 TEST_F(HostResolverImplDnsTest
, AAAACompletesFirst
) {
1946 set_fallback_to_proctask(false);
1947 resolver_
->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED
);
1948 ChangeDnsConfig(CreateValidDnsConfig());
1950 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("4slow_ok", 80)->Resolve());
1951 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("4slow_4ok", 80)->Resolve());
1952 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("4slow_4timeout", 80)->Resolve());
1953 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("4slow_6timeout", 80)->Resolve());
1955 base::RunLoop().RunUntilIdle();
1956 EXPECT_FALSE(requests_
[0]->completed());
1957 EXPECT_FALSE(requests_
[1]->completed());
1958 EXPECT_FALSE(requests_
[2]->completed());
1959 // The IPv6 of the third request should have failed and resulted in cancelling
1960 // the IPv4 request.
1961 EXPECT_TRUE(requests_
[3]->completed());
1962 EXPECT_EQ(ERR_DNS_TIMED_OUT
, requests_
[3]->result());
1963 EXPECT_EQ(3u, num_running_dispatcher_jobs());
1965 dns_client_
->CompleteDelayedTransactions();
1966 EXPECT_TRUE(requests_
[0]->completed());
1967 EXPECT_EQ(OK
, requests_
[0]->result());
1968 EXPECT_EQ(2u, requests_
[0]->NumberOfAddresses());
1969 EXPECT_TRUE(requests_
[0]->HasAddress("127.0.0.1", 80));
1970 EXPECT_TRUE(requests_
[0]->HasAddress("::1", 80));
1972 EXPECT_TRUE(requests_
[1]->completed());
1973 EXPECT_EQ(OK
, requests_
[1]->result());
1974 EXPECT_EQ(1u, requests_
[1]->NumberOfAddresses());
1975 EXPECT_TRUE(requests_
[1]->HasAddress("127.0.0.1", 80));
1977 EXPECT_TRUE(requests_
[2]->completed());
1978 EXPECT_EQ(ERR_DNS_TIMED_OUT
, requests_
[2]->result());
1981 // Test the case where only a single transaction slot is available.
1982 TEST_F(HostResolverImplDnsTest
, SerialResolver
) {
1983 CreateSerialResolver();
1984 set_fallback_to_proctask(false);
1985 resolver_
->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED
);
1986 ChangeDnsConfig(CreateValidDnsConfig());
1988 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("ok", 80)->Resolve());
1989 EXPECT_EQ(1u, num_running_dispatcher_jobs());
1991 base::RunLoop().RunUntilIdle();
1992 EXPECT_TRUE(requests_
[0]->completed());
1993 EXPECT_EQ(OK
, requests_
[0]->result());
1994 EXPECT_EQ(2u, requests_
[0]->NumberOfAddresses());
1995 EXPECT_TRUE(requests_
[0]->HasAddress("127.0.0.1", 80));
1996 EXPECT_TRUE(requests_
[0]->HasAddress("::1", 80));
1999 // Test the case where the AAAA query is started when another transaction
2001 TEST_F(HostResolverImplDnsTest
, AAAAStartsAfterOtherJobFinishes
) {
2002 CreateResolverWithLimitsAndParams(2u, DefaultParams(proc_
.get()));
2003 set_fallback_to_proctask(false);
2004 resolver_
->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED
);
2005 ChangeDnsConfig(CreateValidDnsConfig());
2007 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("ok", 80, MEDIUM
,
2008 ADDRESS_FAMILY_IPV4
)->Resolve());
2009 EXPECT_EQ(ERR_IO_PENDING
,
2010 CreateRequest("4slow_ok", 80, MEDIUM
)->Resolve());
2011 // An IPv4 request should have been started pending for each job.
2012 EXPECT_EQ(2u, num_running_dispatcher_jobs());
2014 // Request 0's IPv4 request should complete, starting Request 1's IPv6
2015 // request, which should also complete.
2016 base::RunLoop().RunUntilIdle();
2017 EXPECT_EQ(1u, num_running_dispatcher_jobs());
2018 EXPECT_TRUE(requests_
[0]->completed());
2019 EXPECT_FALSE(requests_
[1]->completed());
2021 dns_client_
->CompleteDelayedTransactions();
2022 EXPECT_TRUE(requests_
[1]->completed());
2023 EXPECT_EQ(OK
, requests_
[1]->result());
2024 EXPECT_EQ(2u, requests_
[1]->NumberOfAddresses());
2025 EXPECT_TRUE(requests_
[1]->HasAddress("127.0.0.1", 80));
2026 EXPECT_TRUE(requests_
[1]->HasAddress("::1", 80));
2029 // Tests the case that a Job with a single transaction receives an empty address
2030 // list, triggering fallback to ProcTask.
2031 TEST_F(HostResolverImplDnsTest
, IPv4EmptyFallback
) {
2032 ChangeDnsConfig(CreateValidDnsConfig());
2033 proc_
->AddRuleForAllFamilies("empty_fallback", "192.168.0.1");
2034 proc_
->SignalMultiple(1u);
2035 EXPECT_EQ(ERR_IO_PENDING
,
2036 CreateRequest("empty_fallback", 80, MEDIUM
,
2037 ADDRESS_FAMILY_IPV4
)->Resolve());
2038 EXPECT_EQ(OK
, requests_
[0]->WaitForResult());
2039 EXPECT_TRUE(requests_
[0]->HasOneAddress("192.168.0.1", 80));
2042 // Tests the case that a Job with two transactions receives two empty address
2043 // lists, triggering fallback to ProcTask.
2044 TEST_F(HostResolverImplDnsTest
, UnspecEmptyFallback
) {
2045 ChangeDnsConfig(CreateValidDnsConfig());
2046 proc_
->AddRuleForAllFamilies("empty_fallback", "192.168.0.1");
2047 proc_
->SignalMultiple(1u);
2048 EXPECT_EQ(ERR_IO_PENDING
,
2049 CreateRequest("empty_fallback", 80, MEDIUM
,
2050 ADDRESS_FAMILY_UNSPECIFIED
)->Resolve());
2051 EXPECT_EQ(OK
, requests_
[0]->WaitForResult());
2052 EXPECT_TRUE(requests_
[0]->HasOneAddress("192.168.0.1", 80));
2055 // Tests getting a new invalid DnsConfig while there are active DnsTasks.
2056 TEST_F(HostResolverImplDnsTest
, InvalidDnsConfigWithPendingRequests
) {
2057 // At most 3 jobs active at once. This number is important, since we want to
2058 // make sure that aborting the first HostResolverImpl::Job does not trigger
2059 // another DnsTransaction on the second Job when it releases its second
2060 // prioritized dispatcher slot.
2061 CreateResolverWithLimitsAndParams(3u, DefaultParams(proc_
.get()));
2063 resolver_
->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED
);
2064 ChangeDnsConfig(CreateValidDnsConfig());
2066 proc_
->AddRuleForAllFamilies("slow_nx1", "192.168.0.1");
2067 proc_
->AddRuleForAllFamilies("slow_nx2", "192.168.0.2");
2068 proc_
->AddRuleForAllFamilies("ok", "192.168.0.3");
2070 // First active job gets two slots.
2071 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("slow_nx1")->Resolve());
2072 // Next job gets one slot, and waits on another.
2073 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("slow_nx2")->Resolve());
2074 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("ok")->Resolve());
2076 EXPECT_EQ(3u, num_running_dispatcher_jobs());
2078 // Clear DNS config. Two in-progress jobs should be aborted, and the next one
2079 // should use a ProcTask.
2080 ChangeDnsConfig(DnsConfig());
2081 EXPECT_EQ(ERR_NETWORK_CHANGED
, requests_
[0]->WaitForResult());
2082 EXPECT_EQ(ERR_NETWORK_CHANGED
, requests_
[1]->WaitForResult());
2084 // Finish up the third job. Should bypass the DnsClient, and get its results
2085 // from MockHostResolverProc.
2086 EXPECT_FALSE(requests_
[2]->completed());
2087 proc_
->SignalMultiple(1u);
2088 EXPECT_EQ(OK
, requests_
[2]->WaitForResult());
2089 EXPECT_TRUE(requests_
[2]->HasOneAddress("192.168.0.3", 80));
2092 // Tests the case that DnsClient is automatically disabled due to failures
2093 // while there are active DnsTasks.
2094 TEST_F(HostResolverImplDnsTest
,
2095 AutomaticallyDisableDnsClientWithPendingRequests
) {
2096 // Trying different limits is important for this test: Different limits
2097 // result in different behavior when aborting in-progress DnsTasks. Having
2098 // a DnsTask that has one job active and one in the queue when another job
2099 // occupying two slots has its DnsTask aborted is the case most likely to run
2101 for (size_t limit
= 1u; limit
< 6u; ++limit
) {
2102 CreateResolverWithLimitsAndParams(limit
, DefaultParams(proc_
.get()));
2104 resolver_
->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED
);
2105 ChangeDnsConfig(CreateValidDnsConfig());
2107 // Queue up enough failures to disable DnsTasks. These will all fall back
2108 // to ProcTasks, and succeed there.
2109 for (unsigned i
= 0u; i
< maximum_dns_failures(); ++i
) {
2110 std::string host
= base::StringPrintf("nx%u", i
);
2111 proc_
->AddRuleForAllFamilies(host
, "192.168.0.1");
2112 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest(host
)->Resolve());
2115 // These requests should all bypass DnsTasks, due to the above failures,
2116 // so should end up using ProcTasks.
2117 proc_
->AddRuleForAllFamilies("slow_ok1", "192.168.0.2");
2118 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("slow_ok1")->Resolve());
2119 proc_
->AddRuleForAllFamilies("slow_ok2", "192.168.0.3");
2120 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("slow_ok2")->Resolve());
2121 proc_
->AddRuleForAllFamilies("slow_ok3", "192.168.0.4");
2122 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("slow_ok3")->Resolve());
2123 proc_
->SignalMultiple(maximum_dns_failures() + 3);
2125 for (size_t i
= 0u; i
< maximum_dns_failures(); ++i
) {
2126 EXPECT_EQ(OK
, requests_
[i
]->WaitForResult());
2127 EXPECT_TRUE(requests_
[i
]->HasOneAddress("192.168.0.1", 80));
2130 EXPECT_EQ(OK
, requests_
[maximum_dns_failures()]->WaitForResult());
2131 EXPECT_TRUE(requests_
[maximum_dns_failures()]->HasOneAddress(
2132 "192.168.0.2", 80));
2133 EXPECT_EQ(OK
, requests_
[maximum_dns_failures() + 1]->WaitForResult());
2134 EXPECT_TRUE(requests_
[maximum_dns_failures() + 1]->HasOneAddress(
2135 "192.168.0.3", 80));
2136 EXPECT_EQ(OK
, requests_
[maximum_dns_failures() + 2]->WaitForResult());
2137 EXPECT_TRUE(requests_
[maximum_dns_failures() + 2]->HasOneAddress(
2138 "192.168.0.4", 80));
2143 // Tests a call to SetDnsClient while there are active DnsTasks.
2144 TEST_F(HostResolverImplDnsTest
, ManuallyDisableDnsClientWithPendingRequests
) {
2145 // At most 3 jobs active at once. This number is important, since we want to
2146 // make sure that aborting the first HostResolverImpl::Job does not trigger
2147 // another DnsTransaction on the second Job when it releases its second
2148 // prioritized dispatcher slot.
2149 CreateResolverWithLimitsAndParams(3u, DefaultParams(proc_
.get()));
2151 resolver_
->SetDefaultAddressFamily(ADDRESS_FAMILY_UNSPECIFIED
);
2152 ChangeDnsConfig(CreateValidDnsConfig());
2154 proc_
->AddRuleForAllFamilies("slow_ok1", "192.168.0.1");
2155 proc_
->AddRuleForAllFamilies("slow_ok2", "192.168.0.2");
2156 proc_
->AddRuleForAllFamilies("ok", "192.168.0.3");
2158 // First active job gets two slots.
2159 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("slow_ok1")->Resolve());
2160 // Next job gets one slot, and waits on another.
2161 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("slow_ok2")->Resolve());
2162 // Next one is queued.
2163 EXPECT_EQ(ERR_IO_PENDING
, CreateRequest("ok")->Resolve());
2165 EXPECT_EQ(3u, num_running_dispatcher_jobs());
2167 // Clear DnsClient. The two in-progress jobs should fall back to a ProcTask,
2168 // and the next one should be started with a ProcTask.
2169 resolver_
->SetDnsClient(scoped_ptr
<DnsClient
>());
2171 // All three in-progress requests should now be running a ProcTask.
2172 EXPECT_EQ(3u, num_running_dispatcher_jobs());
2173 proc_
->SignalMultiple(3u);
2175 EXPECT_EQ(OK
, requests_
[0]->WaitForResult());
2176 EXPECT_TRUE(requests_
[0]->HasOneAddress("192.168.0.1", 80));
2177 EXPECT_EQ(OK
, requests_
[1]->WaitForResult());
2178 EXPECT_TRUE(requests_
[1]->HasOneAddress("192.168.0.2", 80));
2179 EXPECT_EQ(OK
, requests_
[2]->WaitForResult());
2180 EXPECT_TRUE(requests_
[2]->HasOneAddress("192.168.0.3", 80));